SET client_encoding = 'UTF8';
-- TYPES
-- none

-- GLOBAL TEMPORARY TABLES (require pgtt extension) 

CREATE GLOBAL TEMPORARY TABLE  global_temp_alloc4 (
    "AllocatH" numeric(10,0) NOT NULL,
    "PayType" numeric(5,0),
    "TrxType" numeric(5,0),
    "TrxId" numeric(10,0),
    "TrxTreatment" numeric(5,0),
    "Amount" numeric,
    "AllocateLink" numeric(10,0) NOT NULL,
    "TxHistoryId" numeric(10,0) NOT NULL,
    "PmtHistoryId" numeric(10,0) NOT NULL,
    "OrigRecNo" numeric(10,0),
    "History" numeric(10,0),
    "HistoryType" numeric(5,0),
    "Patient" numeric(10,0),
    "TxModifiedDate" timestamp without time zone,
    "Payed" numeric,
    "InsPayed" numeric,
    "PtAdj" numeric,
    "InsAdj" numeric,
    "InsTransfer" numeric,
    "Discipline" character(15),
    "Procedure" character(7),
    "Practice" numeric(5,0),
    "ClaimDoctor" character(10),
    "Location" character(6),
    "EntryUser" numeric(10,0),
    "AppUser" numeric(10,0),
    "Custom1" character(6),
    "Custom2" character(6),
    "Producer" character(10),
    "TypeCode" character(1),
    "PGroup" character(6),
    "Year" numeric(10,0),
    "CustomCode1" character(6),
    "CustomCode2" character(6),
    "CustomCode3" character(6),
    "CustomCode4" character(6),
    "CustomCode5" character(6),
    "CustomCode6" character(6),
    "CustomCode7" character(6),
    "CustomCode8" character(6),
    "CustomCode9" character(6),
    "CustomCode10" character(6),
    "Department" character(6),
    "HistoryTypeDescription" character(30),
    "GroupBy1" numeric,
    "GroupBy2" numeric,
    "PreviousHistory" numeric(10,0),
    "PreviousDiscipline" character(15),
    "PreviousProcedure" character(7),
    "PreviousPractice" numeric(5,0),
    "PreviousClaimDoctor" character(10),
    "PreviousLocation" character(6),
    "PreviousEntryUser" numeric(10,0),
    "PreviousAppUser" numeric(10,0),
    "PreviousCustom1" character(6),
    "PreviousCustom2" character(6),
    "PreviousProducer" character(10),
    "PreviousTypeCode" character(1),
    "PreviousPGroup" character(6),
    "PreviousYear" numeric(10,0),
    "PreviousCustomCode1" character(6),
    "PreviousCustomCode2" character(6),
    "PreviousCustomCode3" character(6),
    "PreviousCustomCode4" character(6),
    "PreviousCustomCode5" character(6),
    "PreviousCustomCode6" character(6),
    "PreviousCustomCode7" character(6),
    "PreviousCustomCode8" character(6),
    "PreviousCustomCode9" character(6),
    "PreviousCustomCode10" character(6),
    "PreviousDepartment" character(6),
    "GroupBy1Value" character(30),
    "GroupBy2Value" character(30),
    "PreviousGroupBy1Value" character(30),
    "PreviousGroupBy2Value" character(30)
);


--
-- Name: history_ar_global_temp3; Type: TABLE; Schema: pgtt_schema; Owner: -
--

CREATE GLOBAL TEMPORARY TABLE  history_ar_global_temp3 (
    "History" numeric(10,0),
    "HistoryType" numeric(5,0),
    "OrigRecNo" numeric(10,0),
    "Type" numeric(5,0),
    "Id" numeric(10,0),
    "Treatment" numeric(5,0),
    "ModifiedDate" timestamp without time zone,
    "TreatmentDate" timestamp without time zone,
    "Producer" character(10),
    "Procedure" character(7),
    "Patient" numeric(10,0),
    "Family" numeric(10,0),
    "Code" character(6),
    "Description" character varying(60),
    "Company1" character(6),
    "ReportDepartment" character(6),
    "ReportDiscipline" character(15),
    "ReportProcedure" character(7),
    "ReportPractice" numeric(5,0),
    "ReportClaimDoctor" character(10),
    "ReportLocation" character(6),
    "ReportEntryUser" numeric(10,0),
    "ReportAppUser" numeric(10,0),
    "ReportCustom1" character(6),
    "ReportCustom2" character(6),
    "ReportProducer" character(10),
    "ReportTypeCode" character(1),
    "ReportPGroup" character(6),
    "ReportYear" numeric(10,0),
    "ReportCustomCode1" character(6),
    "ReportCustomCode2" character(6),
    "ReportCustomCode3" character(6),
    "ReportCustomCode4" character(6),
    "ReportCustomCode5" character(6),
    "ReportCustomCode6" character(6),
    "ReportCustomCode7" character(6),
    "ReportCustomCode8" character(6),
    "ReportCustomCode9" character(6),
    "ReportCustomCode10" character(6),
    "ReportGroupBy1" numeric,
    "ReportGroupBy1Description" character(23),
    "ReportGroupBy2" numeric,
    "ReportGroupBy2Description" character(23),
    "ReportFromDate" timestamp without time zone,
    "ReportToDate" timestamp without time zone,
    "ReportIsDetailed" numeric,
    "ReportIncludeUnallocated" numeric,
    "ReportHistoryTypeDescription" character(30),
    "ReportOldTotal" numeric,
    "ReportTotal" numeric,
    "ReportTotalChange" numeric,
    "ReportOldInsTotal" numeric,
    "ReportInsTotal" numeric,
    "ReportInsTotalChange" numeric,
    "ReportOldPayed" numeric,
    "ReportPayed" numeric,
    "ReportPayedChange" numeric,
    "ReportOldInsPayed" numeric,
    "ReportInsPayed" numeric,
    "ReportInsPayedChange" numeric,
    "ReportOldPtAdj" numeric,
    "ReportPtAdj" numeric,
    "ReportPtAdjChange" numeric,
    "ReportOldInsAdj" numeric,
    "ReportInsAdj" numeric,
    "ReportInsAdjChange" numeric,
    "ReportOldInsTransfer" numeric,
    "ReportInsTransfer" numeric,
    "ReportInsTransferChange" numeric,
    "PreviousHistory" numeric(10,0)
);


--
-- Name: global_temp_alloc1; Type: TABLE; Schema: pgtt_schema; Owner: -
--

CREATE GLOBAL TEMPORARY TABLE  global_temp_alloc1 (
    "AllocatH" numeric(10,0) NOT NULL,
    "PayType" numeric(5,0),
    "TrxType" numeric(5,0),
    "TrxId" numeric(10,0),
    "TrxTreatment" numeric(5,0),
    "Amount" numeric,
    "AllocateLink" numeric(10,0) NOT NULL,
    "TxHistoryId" numeric(10,0) NOT NULL,
    "PmtHistoryId" numeric(10,0) NOT NULL,
    "OrigRecNo" numeric(10,0),
    "History" numeric(10,0),
    "HistoryType" numeric(5,0),
    "Patient" numeric(10,0),
    "TxModifiedDate" timestamp without time zone,
    "Payed" numeric,
    "InsPayed" numeric,
    "PtAdj" numeric,
    "InsAdj" numeric,
    "InsTransfer" numeric,
    "Discipline" character(15),
    "Procedure" character(7),
    "Practice" numeric(5,0),
    "ClaimDoctor" character(10),
    "Location" character(6),
    "EntryUser" numeric(10,0),
    "AppUser" numeric(10,0),
    "Custom1" character(6),
    "Custom2" character(6),
    "Producer" character(10),
    "TypeCode" character(1),
    "PGroup" character(6),
    "Year" numeric(10,0),
    "CustomCode1" character(6),
    "CustomCode2" character(6),
    "CustomCode3" character(6),
    "CustomCode4" character(6),
    "CustomCode5" character(6),
    "CustomCode6" character(6),
    "CustomCode7" character(6),
    "CustomCode8" character(6),
    "CustomCode9" character(6),
    "CustomCode10" character(6),
    "Department" character(6),
    "HistoryTypeDescription" character(30),
    "GroupBy1" numeric,
    "GroupBy2" numeric
);


--
-- Name: global_temp_alloc2; Type: TABLE; Schema: pgtt_schema; Owner: -
--

CREATE GLOBAL TEMPORARY TABLE  global_temp_alloc2 (
    "AllocatH" numeric(10,0) NOT NULL,
    "PayType" numeric(5,0),
    "TrxType" numeric(5,0),
    "TrxId" numeric(10,0),
    "TrxTreatment" numeric(5,0),
    "Amount" numeric,
    "AllocateLink" numeric(10,0) NOT NULL,
    "TxHistoryId" numeric(10,0) NOT NULL,
    "PmtHistoryId" numeric(10,0) NOT NULL,
    "OrigRecNo" numeric(10,0),
    "History" numeric(10,0),
    "HistoryType" numeric(5,0),
    "Patient" numeric(10,0),
    "TxModifiedDate" timestamp without time zone,
    "Payed" numeric,
    "InsPayed" numeric,
    "PtAdj" numeric,
    "InsAdj" numeric,
    "InsTransfer" numeric,
    "Discipline" character(15),
    "Procedure" character(7),
    "Practice" numeric(5,0),
    "ClaimDoctor" character(10),
    "Location" character(6),
    "EntryUser" numeric(10,0),
    "AppUser" numeric(10,0),
    "Custom1" character(6),
    "Custom2" character(6),
    "Producer" character(10),
    "TypeCode" character(1),
    "PGroup" character(6),
    "Year" numeric(10,0),
    "CustomCode1" character(6),
    "CustomCode2" character(6),
    "CustomCode3" character(6),
    "CustomCode4" character(6),
    "CustomCode5" character(6),
    "CustomCode6" character(6),
    "CustomCode7" character(6),
    "CustomCode8" character(6),
    "CustomCode9" character(6),
    "CustomCode10" character(6),
    "Department" character(6),
    "HistoryTypeDescription" character(30),
    "GroupBy1" numeric,
    "GroupBy2" numeric
);


--
-- Name: global_temp_alloc3; Type: TABLE; Schema: pgtt_schema; Owner: -
--

CREATE GLOBAL TEMPORARY TABLE  global_temp_alloc3 (
    "AllocatH" numeric(10,0) NOT NULL,
    "PayType" numeric(5,0),
    "TrxType" numeric(5,0),
    "TrxId" numeric(10,0),
    "TrxTreatment" numeric(5,0),
    "Amount" numeric,
    "AllocateLink" numeric(10,0) NOT NULL,
    "TxHistoryId" numeric(10,0) NOT NULL,
    "PmtHistoryId" numeric(10,0) NOT NULL,
    "OrigRecNo" numeric(10,0),
    "History" numeric(10,0),
    "HistoryType" numeric(5,0),
    "Patient" numeric(10,0),
    "TxModifiedDate" timestamp without time zone,
    "Payed" numeric,
    "InsPayed" numeric,
    "PtAdj" numeric,
    "InsAdj" numeric,
    "InsTransfer" numeric,
    "Discipline" character(15),
    "Procedure" character(7),
    "Practice" numeric(5,0),
    "ClaimDoctor" character(10),
    "Location" character(6),
    "EntryUser" numeric(10,0),
    "AppUser" numeric(10,0),
    "Custom1" character(6),
    "Custom2" character(6),
    "Producer" character(10),
    "TypeCode" character(1),
    "PGroup" character(6),
    "Year" numeric(10,0),
    "CustomCode1" character(6),
    "CustomCode2" character(6),
    "CustomCode3" character(6),
    "CustomCode4" character(6),
    "CustomCode5" character(6),
    "CustomCode6" character(6),
    "CustomCode7" character(6),
    "CustomCode8" character(6),
    "CustomCode9" character(6),
    "CustomCode10" character(6),
    "Department" character(6),
    "HistoryTypeDescription" character(30),
    "GroupBy1" numeric,
    "GroupBy2" numeric,
    "PreviousHistory" numeric(10,0),
    "PreviousDiscipline" character(15),
    "PreviousProcedure" character(7),
    "PreviousPractice" numeric(5,0),
    "PreviousClaimDoctor" character(10),
    "PreviousLocation" character(6),
    "PreviousEntryUser" numeric(10,0),
    "PreviousAppUser" numeric(10,0),
    "PreviousCustom1" character(6),
    "PreviousCustom2" character(6),
    "PreviousProducer" character(10),
    "PreviousTypeCode" character(1),
    "PreviousPGroup" character(6),
    "PreviousYear" numeric(10,0),
    "PreviousCustomCode1" character(6),
    "PreviousCustomCode2" character(6),
    "PreviousCustomCode3" character(6),
    "PreviousCustomCode4" character(6),
    "PreviousCustomCode5" character(6),
    "PreviousCustomCode6" character(6),
    "PreviousCustomCode7" character(6),
    "PreviousCustomCode8" character(6),
    "PreviousCustomCode9" character(6),
    "PreviousCustomCode10" character(6),
    "PreviousDepartment" character(6),
    "GroupBy1Value" character(30),
    "GroupBy2Value" character(30),
    "PreviousGroupBy1Value" character(30),
    "PreviousGroupBy2Value" character(30)
);


--
-- Name: history_ar_global_temp; Type: TABLE; Schema: pgtt_schema; Owner: -
--

CREATE GLOBAL TEMPORARY TABLE  history_ar_global_temp (
    "History" numeric(10,0),
    "HistoryType" numeric(5,0),
    "Type" numeric(5,0),
    "Id" numeric(10,0),
    "Treatment" numeric(5,0),
    "Patient" numeric(10,0),
    "Family" numeric(10,0),
    "Status" character(6),
    edi character(15),
    "EDIStatus" numeric(5,0),
    "Date" timestamp without time zone,
    "SubmitDate" timestamp without time zone,
    "ClaimDoctor" character(10),
    "Submitted" numeric(5,0),
    "TreatmentDate" timestamp without time zone,
    "CreationDate" timestamp without time zone,
    "Procedure" character(7),
    "Code" character(6),
    "Site" character(3),
    "Surface" character(6),
    "Unit" numeric,
    "Producer" character(10),
    "Total" numeric,
    "InsTotal" numeric,
    "Company1" character(6),
    "Policy1" character varying(20),
    "Category1" character(6),
    "Item1" numeric(10,0),
    "Deduct1" numeric,
    "Assign1" numeric(5,0),
    "Eligible1" numeric,
    "Pct1" numeric,
    "Amount1" numeric,
    "InsPayed1" numeric,
    "InsAdj1" numeric,
    "Company2" character(6),
    "Policy2" character varying(20),
    "Category2" character(6),
    "Item2" numeric(10,0),
    "Assign2" numeric(5,0),
    "Deduct2" numeric,
    "Eligible2" numeric,
    "Pct2" numeric,
    "Amount2" numeric,
    "InsPayed2" numeric,
    "InsAdj2" numeric,
    "Company3" character(6),
    "Policy3" character varying(20),
    "Category3" character(6),
    "Item3" numeric(10,0),
    "Assign3" numeric(5,0),
    "Deduct3" numeric,
    "Eligible3" numeric,
    "Pct3" numeric,
    "Amount3" numeric,
    "InsPayed3" numeric,
    "InsAdj3" numeric,
    "Description" character varying(60),
    "Deleted" numeric(5,0),
    "Bank" character(6),
    "Payed" numeric,
    "InsPayed" numeric,
    "PtAdj" numeric,
    "InsAdj" numeric,
    "EstimateF" numeric(10,0),
    "Additional" character(7),
    "TxStatus" character(6),
    "User" numeric(10,0),
    "PtWriteOff" numeric,
    "PolicyId1" numeric(10,0),
    "PolicyId2" numeric(10,0),
    "PolicyId3" numeric(10,0),
    "InsStatus1" numeric(5,0),
    "InsStatus2" numeric(5,0),
    "InsStatus3" numeric(5,0),
    "IsBankDeposit" numeric(5,0),
    "ChartTrx" numeric(10,0),
    "PlanTotal" numeric,
    "Phase" character(2),
    "Seq" numeric(5,0),
    "AppUser" numeric(10,0),
    "AppDate" timestamp without time zone,
    "Grading" numeric(10,0),
    "Site2" character(3),
    "Custom1" character(6),
    "Custom2" character(6),
    "PayPlanId" numeric(10,0),
    "Discipline" character(15),
    "DiscountedPmtId" numeric(10,0),
    "Location" character(6),
    "OrigAssign1" numeric(5,0),
    "OrigAssign2" numeric(5,0),
    "OrigAssign3" numeric(5,0),
    "InDispute" numeric(5,0),
    "DisputeDate" timestamp without time zone,
    "DeletionDate" timestamp without time zone,
    "EDIPat" character(15),
    "EDIPatStatus" numeric(5,0),
    "InsTransfer1" numeric,
    "InsTransfer2" numeric,
    "InsTransfer3" numeric,
    "InsTransfer" numeric,
    "InsPmtId" numeric(10,0),
    "StationId" numeric(10,0),
    "Practice" numeric(5,0),
    "Suspended" numeric(5,0),
    "DelAppUser" numeric(10,0),
    "DelAppDate" timestamp without time zone,
    "OrthoStatus" numeric(5,0),
    "CvgType" numeric(5,0),
    "ModifiedDate" timestamp without time zone,
    "OrigClaimDate" timestamp without time zone,
    "SubmitMode" numeric(5,0),
    "Custom3" character(6),
    "Custom4" character(6),
    "CorrespondCode" character(7),
    "InsCvgType1" numeric(5,0),
    "InsCvgType2" numeric(5,0),
    "InsCvgType3" numeric(5,0),
    "OrigRecNo" numeric(10,0),
    "EntryUser" numeric(10,0),
    "PlanInProcTotal" numeric,
    "TrxDep" numeric(10,0),
    "CustomaryTotal" numeric,
    "TaxRate" numeric,
    "TaxAmount" numeric,
    "ReportPeriod" character(11),
    "Department" character(6),
    "Producer_TypeCode" character(1),
    "Producer_PGroup" character(6),
    "Producer_Year" numeric(10,0),
    "Patient_CustomCode1" character(6),
    "Patient_CustomCode2" character(6),
    "Patient_CustomCode3" character(6),
    "Patient_CustomCode4" character(6),
    "Patient_CustomCode5" character(6),
    "Patient_CustomCode6" character(6),
    "Patient_CustomCode7" character(6),
    "Patient_CustomCode8" character(6),
    "Patient_CustomCode9" character(6),
    "Patient_CustomCode10" character(6),
    "ReportGroupBy1" numeric,
    "ReportGroupBy1Description" character(23),
    "ReportGroupBy2" numeric,
    "ReportGroupBy2Description" character(23),
    "ReportFromDate" timestamp without time zone,
    "ReportToDate" timestamp without time zone,
    "ReportIsDetailed" numeric,
    "ReportIncludeUnallocated" numeric
);


--
-- Name: history_ar_global_temp2; Type: TABLE; Schema: pgtt_schema; Owner: -
--

CREATE GLOBAL TEMPORARY TABLE  history_ar_global_temp2 (
    "History" numeric(10,0),
    "HistoryType" numeric(5,0),
    "Type" numeric(5,0),
    "Id" numeric(10,0),
    "Treatment" numeric(5,0),
    "Patient" numeric(10,0),
    "Family" numeric(10,0),
    "Status" character(6),
    edi character(15),
    "EDIStatus" numeric(5,0),
    "Date" timestamp without time zone,
    "SubmitDate" timestamp without time zone,
    "ClaimDoctor" character(10),
    "Submitted" numeric(5,0),
    "TreatmentDate" timestamp without time zone,
    "CreationDate" timestamp without time zone,
    "Procedure" character(7),
    "Code" character(6),
    "Site" character(3),
    "Surface" character(6),
    "Unit" numeric,
    "Producer" character(10),
    "Total" numeric,
    "InsTotal" numeric,
    "Company1" character(6),
    "Policy1" character varying(20),
    "Category1" character(6),
    "Item1" numeric(10,0),
    "Deduct1" numeric,
    "Assign1" numeric(5,0),
    "Eligible1" numeric,
    "Pct1" numeric,
    "Amount1" numeric,
    "InsPayed1" numeric,
    "InsAdj1" numeric,
    "Company2" character(6),
    "Policy2" character varying(20),
    "Category2" character(6),
    "Item2" numeric(10,0),
    "Assign2" numeric(5,0),
    "Deduct2" numeric,
    "Eligible2" numeric,
    "Pct2" numeric,
    "Amount2" numeric,
    "InsPayed2" numeric,
    "InsAdj2" numeric,
    "Company3" character(6),
    "Policy3" character varying(20),
    "Category3" character(6),
    "Item3" numeric(10,0),
    "Assign3" numeric(5,0),
    "Deduct3" numeric,
    "Eligible3" numeric,
    "Pct3" numeric,
    "Amount3" numeric,
    "InsPayed3" numeric,
    "InsAdj3" numeric,
    "Description" character varying(60),
    "Deleted" numeric(5,0),
    "Bank" character(6),
    "Payed" numeric,
    "InsPayed" numeric,
    "PtAdj" numeric,
    "InsAdj" numeric,
    "EstimateF" numeric(10,0),
    "Additional" character(7),
    "TxStatus" character(6),
    "User" numeric(10,0),
    "PtWriteOff" numeric,
    "PolicyId1" numeric(10,0),
    "PolicyId2" numeric(10,0),
    "PolicyId3" numeric(10,0),
    "InsStatus1" numeric(5,0),
    "InsStatus2" numeric(5,0),
    "InsStatus3" numeric(5,0),
    "IsBankDeposit" numeric(5,0),
    "ChartTrx" numeric(10,0),
    "PlanTotal" numeric,
    "Phase" character(2),
    "Seq" numeric(5,0),
    "AppUser" numeric(10,0),
    "AppDate" timestamp without time zone,
    "Grading" numeric(10,0),
    "Site2" character(3),
    "Custom1" character(6),
    "Custom2" character(6),
    "PayPlanId" numeric(10,0),
    "Discipline" character(15),
    "DiscountedPmtId" numeric(10,0),
    "Location" character(6),
    "OrigAssign1" numeric(5,0),
    "OrigAssign2" numeric(5,0),
    "OrigAssign3" numeric(5,0),
    "InDispute" numeric(5,0),
    "DisputeDate" timestamp without time zone,
    "DeletionDate" timestamp without time zone,
    "EDIPat" character(15),
    "EDIPatStatus" numeric(5,0),
    "InsTransfer1" numeric,
    "InsTransfer2" numeric,
    "InsTransfer3" numeric,
    "InsTransfer" numeric,
    "InsPmtId" numeric(10,0),
    "StationId" numeric(10,0),
    "Practice" numeric(5,0),
    "Suspended" numeric(5,0),
    "DelAppUser" numeric(10,0),
    "DelAppDate" timestamp without time zone,
    "OrthoStatus" numeric(5,0),
    "CvgType" numeric(5,0),
    "ModifiedDate" timestamp without time zone,
    "OrigClaimDate" timestamp without time zone,
    "SubmitMode" numeric(5,0),
    "Custom3" character(6),
    "Custom4" character(6),
    "CorrespondCode" character(7),
    "InsCvgType1" numeric(5,0),
    "InsCvgType2" numeric(5,0),
    "InsCvgType3" numeric(5,0),
    "OrigRecNo" numeric(10,0),
    "EntryUser" numeric(10,0),
    "PlanInProcTotal" numeric,
    "TrxDep" numeric(10,0),
    "CustomaryTotal" numeric,
    "TaxRate" numeric,
    "TaxAmount" numeric,
    "ReportPeriod" character(11),
    "Department" character(6),
    "Producer_TypeCode" character(1),
    "Producer_PGroup" character(6),
    "Producer_Year" numeric(10,0),
    "Patient_CustomCode1" character(6),
    "Patient_CustomCode2" character(6),
    "Patient_CustomCode3" character(6),
    "Patient_CustomCode4" character(6),
    "Patient_CustomCode5" character(6),
    "Patient_CustomCode6" character(6),
    "Patient_CustomCode7" character(6),
    "Patient_CustomCode8" character(6),
    "Patient_CustomCode9" character(6),
    "Patient_CustomCode10" character(6),
    "ReportGroupBy1" numeric,
    "ReportGroupBy1Description" character(23),
    "ReportGroupBy2" numeric,
    "ReportGroupBy2Description" character(23),
    "ReportFromDate" timestamp without time zone,
    "ReportToDate" timestamp without time zone,
    "ReportIsDetailed" numeric,
    "ReportIncludeUnallocated" numeric,
    "ReportHistoryTypeDescription" character(30),
    "ReportTotal" numeric,
    "ReportInsTotal" numeric,
    "ReportPayed" numeric,
    "ReportInsPayed" numeric,
    "ReportPtAdj" numeric,
    "ReportInsAdj" numeric,
    "ReportInsTransfer" numeric,
    "ReportDepartment" character(6),
    "ReportDiscipline" character(15),
    "ReportProcedure" character(7),
    "ReportPractice" numeric(5,0),
    "ReportClaimDoctor" character(10),
    "ReportLocation" character(6),
    "ReportEntryUser" numeric(10,0),
    "ReportAppUser" numeric(10,0),
    "ReportCustom1" character(6),
    "ReportCustom2" character(6),
    "ReportProducer" character(10),
    "ReportTypeCode" character(1),
    "ReportPGroup" character(6),
    "ReportYear" numeric(10,0),
    "ReportCustomCode1" character(6),
    "ReportCustomCode2" character(6),
    "ReportCustomCode3" character(6),
    "ReportCustomCode4" character(6),
    "ReportCustomCode5" character(6),
    "ReportCustomCode6" character(6),
    "ReportCustomCode7" character(6),
    "ReportCustomCode8" character(6),
    "ReportCustomCode9" character(6),
    "ReportCustomCode10" character(6)
);


--
-- Name: history_ar_global_temp4; Type: TABLE; Schema: pgtt_schema; Owner: -
--

CREATE GLOBAL TEMPORARY TABLE  history_ar_global_temp4 (
    "History" numeric(10,0)
);


--
-- Name: global_temp_alloc4_idx1; Type: INDEX; Schema: pgtt_schema; Owner: -
--

CREATE INDEX global_temp_alloc4_idx1 ON global_temp_alloc4 USING btree ("OrigRecNo");


--
-- Name: history_ar_global_temp2_idx1; Type: INDEX; Schema: pgtt_schema; Owner: -
--

CREATE INDEX history_ar_global_temp2_idx1 ON history_ar_global_temp2 USING btree ("History");


--
-- Name: history_ar_global_temp2_idx2; Type: INDEX; Schema: pgtt_schema; Owner: -
--

CREATE INDEX history_ar_global_temp2_idx2 ON history_ar_global_temp2 USING btree ("OrigRecNo", "Family", "History");


--
-- Name: history_ar_global_temp3_idx1; Type: INDEX; Schema: pgtt_schema; Owner: -
--

CREATE INDEX history_ar_global_temp3_idx1 ON history_ar_global_temp3 USING btree ("History");


--
-- Name: history_ar_global_temp3_idx2; Type: INDEX; Schema: pgtt_schema; Owner: -
--

CREATE INDEX history_ar_global_temp3_idx2 ON history_ar_global_temp3 USING btree ("OrigRecNo", "HistoryType", "Type");


--
-- Name: history_ar_global_temp_idx1; Type: INDEX; Schema: pgtt_schema; Owner: -
--

CREATE UNIQUE INDEX history_ar_global_temp_idx1 ON history_ar_global_temp USING btree ("History");


--
-- Name: history_ar_global_temp_idx2; Type: INDEX; Schema: pgtt_schema; Owner: -
--

CREATE UNIQUE INDEX history_ar_global_temp_idx2 ON history_ar_global_temp USING btree ("OrigRecNo", "Family", "History");


 
-- Skipping unhandled type: TYPE 
 
-- SEQUENCES (standalone) 
--
-- EnterpriseDB database dump
--




--
-- Name: afl_secret_versions_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE afl_secret_versions_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: afl_secrets_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE afl_secrets_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: alertd2_auto_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE alertd2_auto_seq
    START WITH 2147483646
    INCREMENT BY -1
    MINVALUE 1
    MAXVALUE 2147483646
    CACHE 1;


--
-- Name: alertp2_auto_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE alertp2_auto_seq
    START WITH 2147483646
    INCREMENT BY -1
    MINVALUE 1
    MAXVALUE 2147483646
    CACHE 1;


--
-- Name: alertp2h_alertp2h_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE alertp2h_alertp2h_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: allocatelink_link_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE allocatelink_link_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: allocath_allocath_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE allocath_allocath_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: altphone_altphone_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE altphone_altphone_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: analytics_error_log_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE analytics_error_log_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: analytics_log_analyticslog_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE analytics_log_analyticslog_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: anesdelv_anesdelv_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE anesdelv_anesdelv_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: anesdmax_anesdmax_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE anesdmax_anesdmax_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: anesdrug_anesdrug_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE anesdrug_anesdrug_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: anesgaug_anesgaug_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE anesgaug_anesgaug_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: anesmix_anesmix_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE anesmix_anesmix_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: anesunit_anesunit_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE anesunit_anesunit_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: answer2_auto_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE answer2_auto_seq
    START WITH 2147483646
    INCREMENT BY -1
    MINVALUE 1
    MAXVALUE 2147483646
    CACHE 1;


--
-- Name: ap_note_ap_note_autodec_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ap_note_ap_note_autodec_seq
    START WITH 2147483646
    INCREMENT BY -1
    MINVALUE 1
    MAXVALUE 2147483646
    CACHE 1;


--
-- Name: apcdmax_apcdmax_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE apcdmax_apcdmax_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: apexpert_expertid_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE apexpert_expertid_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: appoint_appointment_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE appoint_appointment_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: apptcard_apptcard_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE apptcard_apptcard_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: appthis_appthis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE appthis_appthis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: apptrx_apptrx_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE apptrx_apptrx_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: apseries_apseries_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE apseries_apseries_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ar_recon_saved_data_hdr_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ar_recon_saved_data_hdr_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: atdispl_atdisplay_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE atdispl_atdisplay_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: atsect_atsect_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE atsect_atsect_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: attab_attab_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE attab_attab_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: audithis_audit_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE audithis_audit_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: auditlog_auditlog_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE auditlog_auditlog_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: authlog_authlog_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE authlog_authlog_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ax_log_logid_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ax_log_logid_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ax_setting_axsetting_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ax_setting_axsetting_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;


--
-- Name: axium_api_err_log_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE axium_api_err_log_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: axium_api_log_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE axium_api_log_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: axium_api_log_sessionid_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE axium_api_log_sessionid_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: axvektis_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE axvektis_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: book_book_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE book_book_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: bookdet_bookdetail_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE bookdet_bookdetail_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: breakt_breakt_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE breakt_breakt_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: capfwarn_capfwarn_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE capfwarn_capfwarn_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: capreq_capreq_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE capreq_capreq_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: capreqbi_capreqbi_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE capreqbi_capreqbi_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: capreqit_capreqit_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE capreqit_capreqit_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: carequality_documents_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE carequality_documents_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: carequality_error_log_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE carequality_error_log_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: carequality_eventhis_eventhis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE carequality_eventhis_eventhis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: carequality_log_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE carequality_log_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: carequality_log_sessionid_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE carequality_log_sessionid_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: carequality_patient_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE carequality_patient_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ccdasch_ccdasch_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ccdasch_ccdasch_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: cformcd_cformcdid_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE cformcd_cformcdid_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: chair_chair_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE chair_chair_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: chairsth_chairsth_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE chairsth_chairsth_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: charthis_charthis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE charthis_charthis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: chartlnk_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE chartlnk_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: checkin_checkin_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE checkin_checkin_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: checkin_orderid_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE checkin_orderid_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: claim_attach_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE claim_attach_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: claim_claim_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE claim_claim_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: claimcah_claimcah_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE claimcah_claimcah_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: claimcas_claimcas_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE claimcas_claimcas_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: claimeit_claimeit_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE claimeit_claimeit_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: claimeob_claimeob_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE claimeob_claimeob_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: claimfile_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE claimfile_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: claimh_claimh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE claimh_claimh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: claimhis_claimhis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE claimhis_claimhis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: claiminq_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE claiminq_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: claimith_claimith_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE claimith_claimith_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: claimrit_claimrit_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE claimrit_claimrit_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: claimtset_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE claimtset_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: clingrp_clingrp_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE clingrp_clingrp_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: clinic_clinic_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE clinic_clinic_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: clinict_clinictime_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE clinict_clinictime_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: clinmax_clinmax_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE clinmax_clinmax_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: clinsch_clinsch_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE clinsch_clinsch_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: comment2_auto_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE comment2_auto_seq
    START WITH 2147483646
    INCREMENT BY -1
    MINVALUE 1
    MAXVALUE 2147483646
    CACHE 1;


--
-- Name: commenth_commenth_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE commenth_commenth_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: complain_auto_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE complain_auto_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: consinit_consinit_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE consinit_consinit_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: consreq_consreq_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE consreq_consreq_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: conssig_consentsig_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE conssig_consentsig_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: contract_contract_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE contract_contract_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: copytxplan_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE copytxplan_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;


--
-- Name: coverfrq_coverfrq_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE coverfrq_coverfrq_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: coverhis_coverhis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE coverhis_coverhis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: coverit_coverit_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE coverit_coverit_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: covithis_covithis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE covithis_covithis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: covsiteh_covsiteh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE covsiteh_covsiteh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ctblfile_ctblfile_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ctblfile_ctblfile_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ctblfld_ctblfld_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ctblfld_ctblfld_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: cust_qry_cust_qry_autodec_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE cust_qry_cust_qry_autodec_seq
    START WITH 2147483646
    INCREMENT BY -1
    MINVALUE 1
    MAXVALUE 2147483646
    CACHE 1;


--
-- Name: custevnt_custevnt_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE custevnt_custevnt_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: custmsg_msgid_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE custmsg_msgid_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;


--
-- Name: custrcat_custrcat_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE custrcat_custrcat_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: custrpt_custrpt_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE custrpt_custrpt_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: custtext_custtext_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE custtext_custtext_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: dentx_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE dentx_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: depttx_batch_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE depttx_batch_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: detail2_auto_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE detail2_auto_seq
    START WITH 2147483646
    INCREMENT BY -1
    MINVALUE 1
    MAXVALUE 2147483646
    CACHE 1;


--
-- Name: diagnose_auto_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE diagnose_auto_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: disphis_disphis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE disphis_disphis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: displost_displost_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE displost_displost_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: dispreq_dispreq_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE dispreq_dispreq_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: dispreq_order_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE dispreq_order_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: disptrx_disptrx_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE disptrx_disptrx_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: dmsgsent_dmsgid_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE dmsgsent_dmsgid_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: doctempl_doctempl_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE doctempl_doctempl_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: drugfrq_drugfrq_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE drugfrq_drugfrq_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: drugreac_drugreac_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE drugreac_drugreac_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: dtmplhis_dtmplhis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE dtmplhis_dtmplhis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: edielig_edielig_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE edielig_edielig_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ediform_ediform_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ediform_ediform_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ehrcat_ehrcat_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ehrcat_ehrcat_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ehrcitem_ehrcitem_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ehrcitem_ehrcitem_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ehrdcat_ehrdcat_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ehrdcat_ehrdcat_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ehrditem_ehrditem_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ehrditem_ehrditem_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ehropts_ehropts_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ehropts_ehropts_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: elmah$error_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE "elmah$error_seq"
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: emphis_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE emphis_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: employer_employer_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE employer_employer_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: eobadj_eobadj_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE eobadj_eobadj_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: eobamt_eobamt_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE eobamt_eobamt_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: eobcas_eobcas_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE eobcas_eobcas_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: eobclaim_eobclaim_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE eobclaim_eobclaim_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: eobclmit_eobclmit_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE eobclmit_eobclmit_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: eobfile_eobfile_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE eobfile_eobfile_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: eobqty_eobqty_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE eobqty_eobqty_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: eobrem_eobrem_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE eobrem_eobrem_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: eobtset_eobtset_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE eobtset_eobtset_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: epbatch_epbatch_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE epbatch_epbatch_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: epbitem_epbitem_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE epbitem_epbitem_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: epreview_epreview_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE epreview_epreview_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: erxlog_erxlog_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE erxlog_erxlog_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: external_link_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE external_link_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: external_link_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE external_link_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: faptwatch_faptwatch_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE faptwatch_faptwatch_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: feedates_feedates_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE feedates_feedates_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: fitem_fitem_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE fitem_fitem_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: fitemadd_fitemadd_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE fitemadd_fitemadd_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: fitemcol_fitemcol_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE fitemcol_fitemcol_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: fitemreq_fitemreq_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE fitemreq_fitemreq_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: form_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE form_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: formrpt_formrpt_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE formrpt_formrpt_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: formsig_formsig_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE formsig_formsig_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ftaclexception_exceptionid_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ftaclexception_exceptionid_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;


--
-- Name: ftksetting_profile_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ftksetting_profile_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: fuserticket_fuserticket_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE fuserticket_fuserticket_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: gentx_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE gentx_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: grading_grading_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE grading_grading_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: graphhis_graphhis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE graphhis_graphhis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: graphp2_auto_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE graphp2_auto_seq
    START WITH 2147483646
    INCREMENT BY -1
    MINVALUE 1
    MAXVALUE 2147483646
    CACHE 1;


--
-- Name: groupl_grouplayout_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE groupl_grouplayout_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: gtxopt_option_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE gtxopt_option_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: gtxplan_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE gtxplan_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: gtxpro_gtxpro_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE gtxpro_gtxpro_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: history_history_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE history_history_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: hit_epr_o_labo_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE hit_epr_o_labo_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;


--
-- Name: hit_epr_o_radi_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE hit_epr_o_radi_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;


--
-- Name: hit_pqri_log_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE hit_pqri_log_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: holdtime_holdtime_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE holdtime_holdtime_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: holiday_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE holiday_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: iaccessh_iaccessh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE iaccessh_iaccessh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: iagree_iagreedid_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE iagree_iagreedid_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: idealsch_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE idealsch_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: idlschh_idlschh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE idlschh_idlschh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ilog_ilog_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ilog_ilog_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: indicat_indicat_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE indicat_indicat_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: indicath_indicath_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE indicath_indicath_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: indlog_indlog_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE indlog_indlog_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: infoproc_infoproc_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE infoproc_infoproc_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: inidef_inidef_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE inidef_inidef_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: iniset_iniset_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE iniset_iniset_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: invitdet_batchid_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE invitdet_batchid_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: invitdet_invitdet_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE invitdet_invitdet_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: invitem_invitem_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE invitem_invitem_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: invorder_invorder_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE invorder_invorder_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: invordit_invordit_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE invordit_invordit_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: invordit_picklist_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE invordit_picklist_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: invrec_invrec_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE invrec_invrec_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: iptform_iptform_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE iptform_iptform_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: isecureq_isecureq_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE isecureq_isecureq_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: isetting_isetting_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE isetting_isetting_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: isetting_pa2_isetting_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE isetting_pa2_isetting_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: isettinggrp_isettinggrp_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE isettinggrp_isettinggrp_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: isettinggrp_pa2_isettinggrp_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE isettinggrp_pa2_isettinggrp_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: isettingovr_isettingovr_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE isettingovr_isettingovr_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: istickynote_istickynote_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE istickynote_istickynote_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: iuserh_iuserh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE iuserh_iuserh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: iuserpwh_iuserpwh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE iuserpwh_iuserpwh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: kit_kit_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE kit_kit_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: kitinv_kitinv_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE kitinv_kitinv_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: labcosts_labcosts_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE labcosts_labcosts_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: labels_labels_autodec_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE labels_labels_autodec_seq
    START WITH 2147483646
    INCREMENT BY -1
    MINVALUE 1
    MAXVALUE 2147483646
    CACHE 1;


--
-- Name: labeltmp_batch_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE labeltmp_batch_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;


--
-- Name: labhis_labhis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE labhis_labhis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: labitemh_labitemh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE labitemh_labitemh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: laborder_caseno_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE laborder_caseno_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: laborder_laborder_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE laborder_laborder_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: labordh_labordh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE labordh_labordh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: labotrxh_labotrxh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE labotrxh_labotrxh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: labptout_labprintout_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE labptout_labprintout_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: labsitem_labsitem_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE labsitem_labsitem_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: labsith_labsith_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE labsith_labsith_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: lblsetup_lblsetup_autodec_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE lblsetup_lblsetup_autodec_seq
    START WITH 2147483646
    INCREMENT BY -1
    MINVALUE 1
    MAXVALUE 2147483646
    CACHE 1;


--
-- Name: letters_letters_autodec_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE letters_letters_autodec_seq
    START WITH 2147483646
    INCREMENT BY -1
    MINVALUE 1
    MAXVALUE 2147483646
    CACHE 1;


--
-- Name: linkdef_linkdef_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE linkdef_linkdef_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: log_loginhistory_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE log_loginhistory_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: logon_logon_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE logon_logon_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: medalert_medalert_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE medalert_medalert_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: mergelog_mergelog_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE mergelog_mergelog_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: message_message_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE message_message_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: msgevent_msgevent_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE msgevent_msgevent_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: mtestlab_mtestlab_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE mtestlab_mtestlab_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: mtestord_mtestord_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE mtestord_mtestord_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: mtestreq_mtestreq_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE mtestreq_mtestreq_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: mtestres_mtestres_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE mtestres_mtestres_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: mtestspm_mtestspm_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE mtestspm_mtestspm_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: needlink_needlink_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE needlink_needlink_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: needreq_needreq_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE needreq_needreq_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: needreqh_needreqh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE needreqh_needreqh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: noteovr_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE noteovr_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: notes2_auto_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE notes2_auto_seq
    START WITH 2147483646
    INCREMENT BY -1
    MINVALUE 1
    MAXVALUE 2147483646
    CACHE 1;


--
-- Name: notes2_clinicalnote_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE notes2_clinicalnote_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: npattach_npattach_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE npattach_npattach_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: objlist_objlist_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE objlist_objlist_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: objlisth_objlisth_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE objlisth_objlisth_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: odmsgrcp_odmsgrcp_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE odmsgrcp_odmsgrcp_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: odmsgsnt_odmsgsnt_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE odmsgsnt_odmsgsnt_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: online_comment_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE online_comment_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: online_commenthis_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE online_commenthis_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: online_customizedquestion_answer_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE online_customizedquestion_answer_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: online_customizedquestion_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE online_customizedquestion_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: online_patcontroldefn_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE online_patcontroldefn_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: online_patient_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE online_patient_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: online_reqevent_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE online_reqevent_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: online_reqreason_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE online_reqreason_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: online_request_answer_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE online_request_answer_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: online_request_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE online_request_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: online_request_question_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE online_request_question_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: osstage_osset_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE osstage_osset_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ostempl_ostempl_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ostempl_ostempl_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: osvbound_osvbound_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE osvbound_osvbound_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: outerkit_outerkit_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE outerkit_outerkit_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;


--
-- Name: paccda_paccdaid_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE paccda_paccdaid_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: pacontent_pacontentid_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE pacontent_pacontentid_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: pacontent_panavcontentid_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE pacontent_panavcontentid_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: pafiles_pafilesid_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE pafiles_pafilesid_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: panav_panavid_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE panav_panavid_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: panewpage_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE panewpage_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: papasres_pasresid_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE papasres_pasresid_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: pat2his_pat2his_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE pat2his_pat2his_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: patemplate_patemplateid_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE patemplate_patemplateid_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: pathis_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE pathis_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: patient2_auto_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE patient2_auto_seq
    START WITH 2147483646
    INCREMENT BY -1
    MINVALUE 1
    MAXVALUE 2147483646
    CACHE 1;


--
-- Name: patient_patient_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE patient_patient_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: patient_request_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE patient_request_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: payplan_planid_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE payplan_planid_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: pcview_pcview_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE pcview_pcview_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: percdhis_percdhis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE percdhis_percdhis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: percodis_perconddis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE percodis_perconddis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: percohis_percohis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE percohis_percohis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: periop2_auto_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE periop2_auto_seq
    START WITH 2147483646
    INCREMENT BY -1
    MINVALUE 1
    MAXVALUE 2147483646
    CACHE 1;


--
-- Name: permeth_permeth_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE permeth_permeth_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: peropts_peropts_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE peropts_peropts_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: persdhis_persdhis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE persdhis_persdhis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: persudis_persummdis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE persudis_persummdis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: pform_pform_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE pform_pform_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: pformevt_pformevt_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE pformevt_pformevt_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: physhis_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE physhis_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: physicia_physician_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE physicia_physician_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: pinvitem_pinvitem_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE pinvitem_pinvitem_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: pinvoice_pinvoice_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE pinvoice_pinvoice_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: pinvoich_pinvoich_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE pinvoich_pinvoich_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: pitem_pitem_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE pitem_pitem_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: pitemcol_pitemcol_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE pitemcol_pitemcol_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: pitemimg_pitemimg_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE pitemimg_pitemimg_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: pitemtmp_jobid_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE pitemtmp_jobid_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: planfhis_planfhis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE planfhis_planfhis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: planhis_planhis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE planhis_planhis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: polhist_polhist_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE polhist_polhist_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: policy_sharedentryid_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE policy_sharedentryid_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: polins_polins_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE polins_polins_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: polinsh_polinsh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE polinsh_polinsh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: polrider_polrider_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE polrider_polrider_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ppage_ppage_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ppage_ppage_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: prdtype_prdtype_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE prdtype_prdtype_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: prdunit_prdunit_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE prdunit_prdunit_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: prescrih_prescriph_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE prescrih_prescriph_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: prescrip_prescription_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE prescrip_prescription_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: problem_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE problem_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: procedur_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE procedur_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: procform_procform_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE procform_procform_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: prockit_prockit_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE prockit_prockit_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: procmcit_procmcit_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE procmcit_procmcit_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: proctbl_proctbl_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE proctbl_proctbl_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: prodhis_prodhis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE prodhis_prodhis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: prodsch_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE prodsch_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: product_product_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE product_product_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: prolist_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE prolist_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: prolisth_prolisth_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE prolisth_prolisth_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: provnote_provnote_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE provnote_provnote_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: provnoth_provnoth_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE provnoth_provnoth_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: provsigh_provsigh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE provsigh_provsigh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptalert_ptalert_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptalert_ptalert_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptalerth_ptalerth_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptalerth_ptalerth_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptavail_ptavail_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptavail_ptavail_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptbal_batch_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptbal_batch_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptcase_ptcase_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptcase_ptcase_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptcaseh_ptcaseh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptcaseh_ptcaseh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptconhis_contacthis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptconhis_contacthis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptcont_contact_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptcont_contact_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptdepext_ptdepext_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptdepext_ptdepext_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptdephis_ptdephis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptdephis_ptdephis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptekg_ptekg_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptekg_ptekg_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptekgit_ptekgit_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptekgit_ptekgit_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptemphis_ptemphis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptemphis_ptemphis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptfacul_ptfacul_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptfacul_ptfacul_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptfaculh_ptfaculh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptfaculh_ptfaculh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptfund_ptfund_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptfund_ptfund_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptgendrh_ptgendrh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptgendrh_ptgendrh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptguahis_ptguahis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptguahis_ptguahis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: pthist_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE pthist_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptimplnh_ptimplnh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptimplnh_ptimplnh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptimplnt_ptimplnt_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptimplnt_ptimplnt_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptimptx_ptimptx_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptimptx_ptimptx_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptletter_ptletter_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptletter_ptletter_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptlinfo_ptlinfo_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptlinfo_ptlinfo_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptmanagh_ptmanagehist_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptmanagh_ptmanagehist_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptneed_ptneed_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptneed_ptneed_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptneehis_ptneehis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptneehis_ptneehis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptnote_ptnote_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptnote_ptnote_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptnoteh_ptnotehistory_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptnoteh_ptnotehistory_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptobj_ptobj_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptobj_ptobj_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptobjh_ptobjh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptobjh_ptobjh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptovrext_ptovrext_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptovrext_ptovrext_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptperco_ptperco_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptperco_ptperco_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptperhis_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptperhis_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptperio_ptperio_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptperio_ptperio_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptperst_ptperst_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptperst_ptperst_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptphys_ptphys_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptphys_ptphys_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptphyshis_ptphyshis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptphyshis_ptphyshis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptpol_policyid_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptpol_policyid_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptpolh_ptpolh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptpolh_ptpolh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptprb_ptprb_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptprb_ptprb_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptprbdxh_ptprbdxh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptprbdxh_ptprbdxh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptprbh_ptprbh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptprbh_ptprbh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptprev_ptprev_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptprev_ptprev_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptprevh_ptprevh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptprevh_ptprevh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptprod_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptprod_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptprodh_ptprodhistory_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptprodh_ptprodhistory_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptpsthis_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptpsthis_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptraceh_ptraceh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptraceh_ptraceh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptrcgrih_ptrcgrih_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptrcgrih_ptrcgrih_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptrcgrp_ptrcgrp_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptrcgrp_ptrcgrp_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptrcgrph_ptrcgrph_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptrcgrph_ptrcgrph_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptrecall_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptrecall_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptrechis_ptrechis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptrechis_ptrechis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptrefer_ptrefer_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptrefer_ptrefer_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptrefhis_ptrefhis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptrefhis_ptrefhis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptsdose_ptsdose_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptsdose_ptsdose_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptsdoseh_ptsdoseh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptsdoseh_ptsdoseh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptsdrug_ptsdrug_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptsdrug_ptsdrug_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptsdrugh_ptsdrugh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptsdrugh_ptsdrugh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptsig_ptsig_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptsig_ptsig_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptstage_ptstage_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptstage_ptstage_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptstageh_ptstageh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptstageh_ptstageh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptsummh_ptsummh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptsummh_ptsummh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptsurg_ptsurg_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptsurg_ptsurg_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: pttyphis_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE pttyphis_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptvital_ptvital_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptvital_ptvital_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptvitalh_ptvitalh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptvitalh_ptvitalh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptvtlarh_ptvtlarh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptvtlarh_ptvtlarh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptvtlart_ptvtlart_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptvtlart_ptvtlart_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptvtlerr_ptvtlerr_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptvtlerr_ptvtlerr_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptxrahis_ptxrayhis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptxrahis_ptxrayhis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: ptxray_ptxray_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE ptxray_ptxray_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: rcgroup_rcgroup_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE rcgroup_rcgroup_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: receipt_receipt_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE receipt_receipt_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: referral_referral_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE referral_referral_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: referral_request_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE referral_request_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: referrer_request_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE referrer_request_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: refhis_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE refhis_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: reqfld_reqfld_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE reqfld_reqfld_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: reqnote_reqnote_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE reqnote_reqnote_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: request_request_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE request_request_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: reserve_reserve_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE reserve_reserve_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: resphis_resphis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE resphis_resphis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: resplist_resplist_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE resplist_resplist_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: rpthis_rpthis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE rpthis_rpthis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: rtfcolor_rtfcolor_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE rtfcolor_rtfcolor_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: schrule_schrule_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE schrule_schrule_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: slevel_slevel_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE slevel_slevel_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: slevrolh_slevrolh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE slevrolh_slevrolh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: slraudit_slraudit_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE slraudit_slraudit_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: sreport_sreport_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE sreport_sreport_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: srole_srole_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE srole_srole_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: startchk_startchk_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE startchk_startchk_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: starttrx_starttrx_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE starttrx_starttrx_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: statement_history_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE statement_history_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: statemnt_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE statemnt_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: station_stationid_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE station_stationid_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: sterbat_sterbat_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE sterbat_sterbat_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: stmtjob_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE stmtjob_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: sundry_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE sundry_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: surcode2_auto_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE surcode2_auto_seq
    START WITH 2147483646
    INCREMENT BY -1
    MINVALUE 1
    MAXVALUE 2147483646
    CACHE 1;


--
-- Name: survey2_auto_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE survey2_auto_seq
    START WITH 2147483646
    INCREMENT BY -1
    MINVALUE 1
    MAXVALUE 2147483646
    CACHE 1;


--
-- Name: swipe_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE swipe_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: sysblob_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE sysblob_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: tcunlock_tcunlock_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE tcunlock_tcunlock_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: textmsgaudit_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE textmsgaudit_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: titem_item_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE titem_item_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: titempr_titempr_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE titempr_titempr_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: tlocrule_ruleno_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE tlocrule_ruleno_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: tlocrule_tlocrule_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE tlocrule_tlocrule_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: tpartydef_tpartydef_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE tpartydef_tpartydef_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: tplanopt_tplanopt_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE tplanopt_tplanopt_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: treatme2_auto_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE treatme2_auto_seq
    START WITH 2147483646
    INCREMENT BY -1
    MINVALUE 1
    MAXVALUE 2147483646
    CACHE 1;


--
-- Name: trojaud_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE trojaud_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: trx_id_adjustment_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE trx_id_adjustment_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: trx_id_insadjustment_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE trx_id_insadjustment_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: trx_id_officecharges_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE trx_id_officecharges_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: trx_id_payment_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE trx_id_payment_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: trx_id_plannedtreatment_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE trx_id_plannedtreatment_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: trx_id_treatment_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE trx_id_treatment_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: trx_origrecno_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE trx_origrecno_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: trxcont_trxcont_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE trxcont_trxcont_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: trxdep_trxdep_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE trxdep_trxdep_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: trxpol_trxpol_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE trxpol_trxpol_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: trxpolh_trxpolh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE trxpolh_trxpolh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: txhview_txhview_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE txhview_txhview_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: txpdx_txpdx_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE txpdx_txpdx_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: txpdxh_txpdxh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE txpdxh_txpdxh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: txpdxtxh_txpdxtxh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE txpdxtxh_txpdxtxh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: txplan_txplan_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE txplan_txplan_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: txplanh_txplanh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE txplanh_txplanh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: txpnohis_txpnotehistory_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE txpnohis_txpnotehistory_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: txpnote_txpnote_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE txpnote_txpnote_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: txpopt_txpopt_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE txpopt_txpopt_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: txpopth_txpopth_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE txpopth_txpopth_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: txpprbh_txpprbh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE txpprbh_txpprbh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: txptx_macroseq_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE txptx_macroseq_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: txptx_txptx_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE txptx_txptx_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: txptxh_txptxh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE txptxh_txptxh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: txquest_txquest_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE txquest_txquest_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: uapprove_uapprove_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE uapprove_uapprove_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: uhealhis_uhealhis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE uhealhis_uhealhis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: uhealth_uhealth_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE uhealth_uhealth_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: umsgfld_umsgfld_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE umsgfld_umsgfld_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: users_user_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE users_user_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: usershis_usershis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE usershis_usershis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: vacaset_vacaset_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE vacaset_vacaset_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: vacaseth_vacaseth_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE vacaseth_vacaseth_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: vacation_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE vacation_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: vacatnh_vacatnh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE vacatnh_vacatnh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: vendor_vendor_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE vendor_vendor_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: vkbatch_vkbatch_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE vkbatch_vkbatch_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: vkclaim_vkclaim_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE vkclaim_vkclaim_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: vkclmit_vkclmit_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE vkclmit_vkclmit_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: vkcomm_vkcomm_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE vkcomm_vkcomm_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: waitlhis_waitlhis_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE waitlhis_waitlhis_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: waitlist_waitlist_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE waitlist_waitlist_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: workschd_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE workschd_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: wrkschh_wrkschh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE wrkschh_wrkschh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: wschitch_wschitchair_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE wschitch_wschitchair_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: wschitem_id_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE wschitem_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: wschitmh_wschitmh_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE wschitmh_wschitmh_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- Name: xrayinfo_xrayinfo_seq; Type: SEQUENCE; Schema:  Owner: -
--

CREATE SEQUENCE xrayinfo_xrayinfo_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 20;


--
-- EnterpriseDB database dump complete
--


 
-- PRIORITY TABLES (includes constraints, indexes, owned sequences) 
CREATE  TABLE history (
  "History" numeric(10,0) NOT NULL,
  "HistoryType" numeric(5,0),
  "Type" numeric(5,0),
  "Id" numeric(10,0),
  "Treatment" numeric(5,0),
  "Patient" numeric(10,0),
  "Family" numeric(10,0),
  "Status" character(6),
  "EDI" character(15),
  "EDIStatus" numeric(5,0),
  "Date" timestamp without time zone,
  "SubmitDate" timestamp without time zone,
  "ClaimDoctor" character(10),
  "Submitted" numeric(5,0),
  "TreatmentDate" timestamp without time zone,
  "CreationDate" timestamp without time zone,
  "Procedure" character(7),
  "Code" character(6),
  "Site" character(3),
  "Surface" character(6),
  "Unit" numeric,
  "Producer" character(10),
  "Total" numeric,
  "InsTotal" numeric,
  "Company1" character(6),
  "Policy1" character varying(20),
  "Category1" character(6),
  "Item1" numeric(10,0),
  "Deduct1" numeric,
  "Assign1" numeric(5,0),
  "Eligible1" numeric,
  "Pct1" numeric,
  "Amount1" numeric,
  "InsPayed1" numeric,
  "InsAdj1" numeric,
  "Company2" character(6),
  "Policy2" character varying(20),
  "Category2" character(6),
  "Item2" numeric(10,0),
  "Assign2" numeric(5,0),
  "Deduct2" numeric,
  "Eligible2" numeric,
  "Pct2" numeric,
  "Amount2" numeric,
  "InsPayed2" numeric,
  "InsAdj2" numeric,
  "Company3" character(6),
  "Policy3" character varying(20),
  "Category3" character(6),
  "Item3" numeric(10,0),
  "Assign3" numeric(5,0),
  "Deduct3" numeric,
  "Eligible3" numeric,
  "Pct3" numeric,
  "Amount3" numeric,
  "InsPayed3" numeric,
  "InsAdj3" numeric,
  "Description" character varying(60),
  "Deleted" numeric(5,0),
  "Bank" character(6),
  "Payed" numeric,
  "InsPayed" numeric,
  "PtAdj" numeric,
  "InsAdj" numeric,
  "EstimateF" numeric(10,0),
  "Additional" character(7),
  "TxStatus" character(6),
  "User" numeric(10,0),
  "PtWriteOff" numeric,
  "PolicyId1" numeric(10,0),
  "PolicyId2" numeric(10,0),
  "PolicyId3" numeric(10,0),
  "InsStatus1" numeric(5,0),
  "InsStatus2" numeric(5,0),
  "InsStatus3" numeric(5,0),
  "IsBankDeposit" numeric(5,0),
  "ChartTrx" numeric(10,0),
  "PlanTotal" numeric,
  "Phase" character(2),
  "Seq" numeric(5,0),
  "AppUser" numeric(10,0),
  "AppDate" timestamp without time zone,
  "Grading" numeric(10,0),
  "Site2" character(3),
  "Custom1" character(6),
  "Custom2" character(6),
  "PayPlanId" numeric(10,0),
  "Discipline" character(15),
  "DiscountedPmtId" numeric(10,0),
  "Location" character(6),
  "OrigAssign1" numeric(5,0),
  "OrigAssign2" numeric(5,0),
  "OrigAssign3" numeric(5,0),
  "InDispute" numeric(5,0),
  "DisputeDate" timestamp without time zone,
  "DeletionDate" timestamp without time zone,
  "EDIPat" character(15),
  "EDIPatStatus" numeric(5,0),
  "InsTransfer1" numeric,
  "InsTransfer2" numeric,
  "InsTransfer3" numeric,
  "InsTransfer" numeric,
  "InsPmtId" numeric(10,0),
  "StationId" numeric(10,0),
  "Practice" numeric(5,0),
  "Suspended" numeric(5,0),
  "DelAppUser" numeric(10,0),
  "DelAppDate" timestamp without time zone,
  "OrthoStatus" numeric(5,0),
  "CvgType" numeric(5,0),
  "ModifiedDate" timestamp without time zone,
  "OrigClaimDate" timestamp without time zone,
  "SubmitMode" numeric(5,0),
  "Custom3" character(6),
  "Custom4" character(6),
  "CorrespondCode" character(7),
  "InsCvgType1" numeric(5,0),
  "InsCvgType2" numeric(5,0),
  "InsCvgType3" numeric(5,0),
  "OrigRecNo" numeric(10,0),
  "EntryUser" numeric(10,0),
  "PlanInProcTotal" numeric,
  "TrxDep" numeric(10,0),
  "CustomaryTotal" numeric,
  "TaxRate" numeric,
  "TaxAmount" numeric,
  CONSTRAINT history_primary PRIMARY KEY ("History")
) ;
CREATE INDEX IF NOT EXISTS history_ar ON history USING btree ("OrigRecNo", "Type", trunc("ModifiedDate"), "History") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS history_charttrx ON history USING btree ("ChartTrx") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS history_claimdoctor ON history USING btree ("ClaimDoctor") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS history_family ON history USING btree ("Family") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS history_key ON history USING btree ("Type", "Id", "Treatment") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS history_modifieddate ON history USING btree ("ModifiedDate") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS history_origrecno ON history USING btree ("OrigRecNo") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS history_patientkey ON history USING btree ("Patient") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS history_txdatekey ON history USING btree ("TreatmentDate") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS history_typedatekey ON history USING btree ("Type", "ModifiedDate") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS history_type_historytype ON history USING btree ("Type", "HistoryType") TABLESPACE pg_default;
COMMENT ON TABLE history IS 'Transaction History';
COMMENT ON COLUMN history."User" IS 'User ID of entry user. Ptr to USERS.User';
COMMENT ON COLUMN history."Unit" IS 'For Type=1/5, number of units for the treatment. For Type=2, quantity for the office charge.';
COMMENT ON COLUMN history."Type" IS 'Transaction record type (1=Treatment, 2=Office Charge, 3=Patient Payment, 4=Insurance Payment, 5=Planned Treatment, 6=Adjustment, 7=Insurance Adjustment, 73=Allocated portion of a Patient Payment, 74= Insurance Payment allocated to patient treatment)';
COMMENT ON COLUMN history."TxStatus" IS 'User-definable Treatment status, ptr to STATUS.Status';
COMMENT ON COLUMN history."TrxDep" IS 'Associated deductables / charges / estimates. Ptr to TRXDEP.TrxDep';
COMMENT ON COLUMN history."TreatmentDate" IS 'For Type=1/5, the date that the treatment was performed/planned for (this is the date visible in the Date column of the EHR - Tx History tab)';
COMMENT ON COLUMN history."Treatment" IS 'Transaction line number within claim (for treatments).';
COMMENT ON COLUMN history."Total" IS 'Total amount of the transaction, in dollars. For treatments, this is the total for the treatment (not the claim) and includes the patient and insurance amounts.';
COMMENT ON COLUMN history."TaxRate" IS 'Sales tax percentage.';
COMMENT ON COLUMN history."TaxAmount" IS 'Calculated sales tax amount, in dollars. ';
COMMENT ON COLUMN history."Suspended" IS 'Is suspended? (0=No, 1=Yes)';
COMMENT ON COLUMN history."Surface" IS 'Surface on crown for treatment.';
COMMENT ON COLUMN history."Submitted" IS 'Has Treatment been submitted? (0 = Unsubmitted, 1 = Submitted, 2 = Mark as Void, 3 = Voided)';
COMMENT ON COLUMN history."SubmitMode" IS 'Submit mode (0=Bill current policy, 1=Bill Original policy, 2=Bill policy effective on date of treatment)';
COMMENT ON COLUMN history."SubmitDate" IS 'Date treatment was submitted to insurance. ';
COMMENT ON COLUMN history."Status" IS 'Treatment Status (P = Planned, I = In Progress, C = Complete)';
COMMENT ON COLUMN history."StationId" IS 'Station ID, ptr to STATION.StationId';
COMMENT ON COLUMN history."Site2" IS 'Ending site/tooth for multi-site treatments (e.g. bridges)';
COMMENT ON COLUMN history."Site" IS 'Site/tooth for treatment.';
COMMENT ON COLUMN history."Seq" IS 'Treatment sequence number.';
COMMENT ON COLUMN history."PtWriteOff" IS 'Internal amount field used with special billing method Auto Discount';
COMMENT ON COLUMN history."PtAdj" IS 'Total of all patient adjustments allocated to this transaction, in dollars.';
COMMENT ON COLUMN history."Producer" IS 'Producer ID, ptr to PRODUCER.Producer';
COMMENT ON COLUMN history."Procedure" IS 'Procedure code, ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN history."Practice" IS 'Practice for this transaction, ptr to PRACTICE.Id';
COMMENT ON COLUMN history."PolicyId3" IS 'Tertiary insurance policy ID, ptr to PTPOL.PolicyId';
COMMENT ON COLUMN history."PolicyId2" IS 'Secondary insurance policy ID, ptr to PTPOL.PolicyId';
COMMENT ON COLUMN history."PolicyId1" IS 'Primary insurance policy ID, ptr to PTPOL.PolicyId';
COMMENT ON COLUMN history."Policy3" IS 'Policy ID for the tertiary insurance policy. Ptr to PTPOL.Policy.';
COMMENT ON COLUMN history."Policy2" IS 'Policy ID for the secondary insurance policy. Ptr to PTPOL.Policy.';
COMMENT ON COLUMN history."Policy1" IS 'Policy ID for the primary insurance policy. Ptr to PTPOL.Policy.';
COMMENT ON COLUMN history."PlanTotal" IS 'Planned treatment amount used for binding quote, in dollars.';
COMMENT ON COLUMN history."PlanInProcTotal" IS 'Amount of the planned in-process treatment, in dollars.';
COMMENT ON COLUMN history."Phase" IS 'Treatment phase order.';
COMMENT ON COLUMN history."Pct3" IS 'Percentage of coverage for item under tertiary insurance policy, in dollars.';
COMMENT ON COLUMN history."Pct2" IS 'Percentage of coverage for item under secondary insurance policy, in dollars.';
COMMENT ON COLUMN history."Pct1" IS 'Percentage of coverage for item under primary insurance policy, in dollars.';
COMMENT ON COLUMN history."Payed" IS 'Total of all patient payments allocated to this transaction, in dollars.';
COMMENT ON COLUMN history."PayPlanId" IS 'Payment Plan ID, ptr to PAYPLAN.PlanId';
COMMENT ON COLUMN history."Patient" IS 'If Type=3/6/73, the ID of the payor. For other types, the ID patient that the transaction is for. Ptr to PATIENT.Patient';
COMMENT ON COLUMN history."OrthoStatus" IS 'Ortho treatment status (0=Non-Ortho treatment or Ortho treatment not tied to an Ortho payment plan, 1=Treatment tied to an Ortho payment plan, 2=Treatment created by the Ortho Billing process)';
COMMENT ON COLUMN history."OrigRecNo" IS 'Original record number, unique ID from sequence. ';
COMMENT ON COLUMN history."OrigClaimDate" IS 'Original date of claim';
COMMENT ON COLUMN history."OrigAssign3" IS 'DEPRECATED';
COMMENT ON COLUMN history."OrigAssign2" IS 'DEPRECATED';
COMMENT ON COLUMN history."OrigAssign1" IS 'DEPRECATED';
COMMENT ON COLUMN history."ModifiedDate" IS 'The date/time that the transaction was last modified';
COMMENT ON COLUMN history."Location" IS 'Location at which procedure was performed, ptr to FACILITY.Code';
COMMENT ON COLUMN history."Item3" IS 'Item line in policy coverage for this treatment under the tertiary insurance policy. Ptr to COVERIT.Item.';
COMMENT ON COLUMN history."Item2" IS 'Item line in policy coverage for this treatment under the secondary insurance policy. Ptr to COVERIT.Item.';
COMMENT ON COLUMN history."Item1" IS 'Item line in policy coverage for this treatment under the primary insurance policy. Ptr to COVERIT.Item.';
COMMENT ON COLUMN history."IsBankDeposit" IS 'Print transaction on Bank Deposit report? (0=No, 1=Yes)';
COMMENT ON COLUMN history."InsTransfer3" IS 'Amount transferred from tertiary insurance to patient, in dollars.';
COMMENT ON COLUMN history."InsTransfer2" IS 'Amount transferred from secondary insurance to patient or tertiary insurance, in dollars.';
COMMENT ON COLUMN history."InsTransfer1" IS 'Amount transferred from primary insurance to patient or secondary insurance, in dollars.';
COMMENT ON COLUMN history."InsTransfer" IS 'Total amount transferred from insurance, in dollars.';
COMMENT ON COLUMN history."InsTotal" IS 'Insurance portion of the Total amount, in dollars.';
COMMENT ON COLUMN history."InsStatus3" IS 'For treatments paid by tertiary insurance, indicates what was done with the insurance outstanding amount (0=Left Outstanding, 1=Transferred to Patient, 2=Written Off, 3=Transferred and Written Off)';
COMMENT ON COLUMN history."InsStatus2" IS 'For treatments paid by secondary insurance, indicates what was done with the insurance outstanding amount (0=Left Outstanding, 1=Transferred to Patient, 2=Written Off, 3=Transferred and Written Off)';
COMMENT ON COLUMN history."InsStatus1" IS 'For treatments paid by primary insurance, indicates what was done with the insurance outstanding amount (0=Left Outstanding, 1=Transferred to Patient, 2=Written Off, 3=Transferred and Written Off)';
COMMENT ON COLUMN history."InsPmtId" IS 'If Type=7, the insurance payment being adjusted. Ptr to a TRX.Id with TRX.Type=4.';
COMMENT ON COLUMN history."InsPayed3" IS 'Amount paid by tertiary insurance, in dollars.';
COMMENT ON COLUMN history."InsPayed2" IS 'Amount paid by secondary insurance, in dollars.';
COMMENT ON COLUMN history."InsPayed1" IS 'Amount paid by primary insurance, in dollars.';
COMMENT ON COLUMN history."InsPayed" IS 'Total of all insurance payments allocated to this transaction, in dollars.';
COMMENT ON COLUMN history."InsCvgType3" IS 'Insurance coverage type for tertiary insurance (0=Dental, 1= Medical, 2= NowIsDental, 3= NowIsMedical)';
COMMENT ON COLUMN history."InsCvgType2" IS 'Insurance coverage type for secondary insurance (0=Dental, 1= Medical, 2= NowIsDental, 3= NowIsMedical)';
COMMENT ON COLUMN history."InsCvgType1" IS 'Insurance coverage type for primary insurance (0=Dental, 1= Medical, 2= NowIsDental, 3= NowIsMedical).';
COMMENT ON COLUMN history."InsAdj3" IS 'Amount adjusted (written-off) by tertiary insurance, in dollars.';
COMMENT ON COLUMN history."InsAdj2" IS 'Amount adjusted (written-off) by secondary insurance, in dollars.';
COMMENT ON COLUMN history."InsAdj1" IS 'Amount adjusted (written-off) by primary insurance, in dollars.';
COMMENT ON COLUMN history."InsAdj" IS 'Total of all insurance adjustments allocated to this transaction, in dollars.';
COMMENT ON COLUMN history."InDispute" IS 'Treatment in dispute? (0 = No, 1 = Yes)';
COMMENT ON COLUMN history."Id" IS 'Unique ID of the transaction record. Sequence used depends on Type. For treatments, this is the claim number. ';
COMMENT ON COLUMN history."HistoryType" IS 'Type of history record (0 = Unknown, 1 = Add, 2 = Edit, 3 = Allocation, 4 = Delete, 5 = Rebill)';
COMMENT ON COLUMN history."History" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN history."Grading" IS 'Link to evaluation for this treatment, ptr to GRADING.Grading';
COMMENT ON COLUMN history."Family" IS 'If Type=3/6/73, the ID of patient who is being paid for (ptr to PATIENT.Patient). For other types, the family ID of the patient that the transaction is for (ptr to PATIENT.Family)';
COMMENT ON COLUMN history."EstimateF" IS 'Indicator if Policy Limit reached on transaction - values can be 1,2,4, or 8 or any combination of them. Taken from the SPLIT screen';
COMMENT ON COLUMN history."EntryUser" IS 'ID code of the entry user, ptr to USERS.User';
COMMENT ON COLUMN history."Eligible3" IS 'Eligible amount of coverage for item under tertiary insurance policy, in dollars.';
COMMENT ON COLUMN history."Eligible2" IS 'Eligible amount of coverage for item under secondary insurance policy, in dollars.';
COMMENT ON COLUMN history."Eligible1" IS 'Eligible amount of coverage for item under primary insurance policy, in dollars.';
COMMENT ON COLUMN history."EDIStatus" IS 'EDI submission status (0=Not Applicable, 1=Not Sent, 2=Sent, 3=Rejected, 4=Held, 5=N/A, 6=Applied, 7=Paid, 8=Error)';
COMMENT ON COLUMN history."EDIPatStatus" IS 'EDI submission status (0=Not Applicable, 1=Not Sent, 2=Sent, 3=Rejected, 4=Held, 5=N/A, 6=Applied, 7=Paid, 8=Error (Patient Side - used in axiUm Dutch Version))';
COMMENT ON COLUMN history."EDIPat" IS 'Patient "EDI" submission number (Patient Side - used in axiUm Dutch Version)';
COMMENT ON COLUMN history."EDI" IS 'EDI submission number';
COMMENT ON COLUMN history."DisputeDate" IS 'If InDispute=1, the date that the treatment became in dispute. ';
COMMENT ON COLUMN history."DiscountedPmtId" IS 'If this record is discount adjustment (Type=6), the patient payment that is being adjusted. Ptr to a TRX.Id with TRX.Type=3.';
COMMENT ON COLUMN history."Discipline" IS 'Discipline, ptr to CLASS.Class';
COMMENT ON COLUMN history."Description" IS 'Description of transaction';
COMMENT ON COLUMN history."DeletionDate" IS 'If Deleted=1, the date that the treatment was deleted. ';
COMMENT ON COLUMN history."Deleted" IS 'Deleted? (0 = No, 1 = Yes, 2= Strikeout / Rebilled)';
COMMENT ON COLUMN history."DelAppUser" IS 'Deletion approval user, ptr to USERS.User';
COMMENT ON COLUMN history."DelAppDate" IS 'Date of the deletion approval';
COMMENT ON COLUMN history."Deduct3" IS 'Tertiary insurance policy accepts assignment? (0 = No, 1 = Yes)';
COMMENT ON COLUMN history."Deduct2" IS 'Secondary insurance policy accepts assignment? (0 = No, 1 = Yes)';
COMMENT ON COLUMN history."Deduct1" IS 'Deductible amount for item under primary insurance policy, in dollars.';
COMMENT ON COLUMN history."Date" IS 'Transaction date, date of the claim';
COMMENT ON COLUMN history."CvgType" IS 'Number to indicate type of coverage (0 = Dental, 1 = Medical), ptr to INSURANC.CvgType';
COMMENT ON COLUMN history."CustomaryTotal" IS 'Customary total (fee to bill if not a government plan or discount), in dollars.';
COMMENT ON COLUMN history."Custom4" IS 'Treatment/Clinical2 code for this transaction, ptr to CUSTCODE.Code';
COMMENT ON COLUMN history."Custom3" IS 'Treatment/Clinical1 code for this transaction, ptr to CUSTCODE.Code';
COMMENT ON COLUMN history."Custom2" IS 'Treatment/Note2 code for this transaction, ptr to CUSTCODE.Code';
COMMENT ON COLUMN history."Custom1" IS 'Treatment/Note1 code for this transaction, ptr to CUSTCODE.Code';
COMMENT ON COLUMN history."CreationDate" IS 'Date that the first history record was created for this transaction.';
COMMENT ON COLUMN history."CorrespondCode" IS 'If InsCvgType=2 or 3, the corresponding medical treatment code or procedure code. Ptr to PROCEDUR.Procedure.';
COMMENT ON COLUMN history."Company3" IS 'Tertiary insurance company, ptr to INSURANC.Company';
COMMENT ON COLUMN history."Company2" IS 'Secondary insurance company, ptr to INSURANC.Company';
COMMENT ON COLUMN history."Company1" IS 'Primary insurance company, ptr to INSURANC.Company';
COMMENT ON COLUMN history."Code" IS 'Office charge, Payment, or Adjustment code, depending on Type. (Type=2, ptr to OFCHARGE.OfficeCharge; Type=3/4/73/74, ptr to PAYMENT.Payment; Type=6/7, ptr to ADJUST.Adjust)';
COMMENT ON COLUMN history."ClaimDoctor" IS 'Billing entity/Fee Guide, ptr to PRODUCER.Producer';
COMMENT ON COLUMN history."ChartTrx" IS 'Link to treatment on chart, ptr to TREATME2.Auto';
COMMENT ON COLUMN history."Category3" IS 'Category of coverage for this treatment under the tertiary insurance policy. Ptr to COVERIT.Category.';
COMMENT ON COLUMN history."Category2" IS 'Category of coverage for this treatment under the secondary insurance policy. Ptr to COVERIT.Category.';
COMMENT ON COLUMN history."Category1" IS 'Category of coverage for this treatment under the primary insurance policy. Ptr to COVERIT.Category.';
COMMENT ON COLUMN history."Bank" IS 'Cash drawer / point of sale teminal ID, ptr to BANK.Bank';
COMMENT ON COLUMN history."Assign3" IS 'Deductible amount for item under tertiary insurance policy, in dollars.';
COMMENT ON COLUMN history."Assign2" IS 'Deductible amount for item under secondary insurance policy, in dollars.';
COMMENT ON COLUMN history."Assign1" IS 'Primary insurance policy accepts assignment? (0 = No, 1 = Yes)';
COMMENT ON COLUMN history."AppUser" IS 'User ID of Instructor that approved the procedure, ptr to USERS.User';
COMMENT ON COLUMN history."AppDate" IS 'Date treatment was approved';
COMMENT ON COLUMN history."Amount3" IS 'Amount of coverage for item under tertiary insurance policy, in dollars.';
COMMENT ON COLUMN history."Amount2" IS 'Amount of coverage for item under secondary insurance policy, in dollars.';
COMMENT ON COLUMN history."Amount1" IS 'Amount of coverage for item under primary insurance policy, in dollars.';
COMMENT ON COLUMN history."Additional" IS 'Additional field used optionally for treatments.';


CREATE  TABLE isettinggrp_pa2 (
  "iSettingGrp" numeric(5,0) NOT NULL DEFAULT 0,
  "ParentId" numeric(5,0) NOT NULL DEFAULT 0,
  "Priority" numeric(5,0) NOT NULL DEFAULT 0,
  "Name" character varying(255) NOT NULL,
  "SettingGroupType" numeric(5,0) NOT NULL DEFAULT 0,
  "PageId" numeric(10,0) NOT NULL DEFAULT 0,
  "ShowPageSettings" numeric(5,0) NOT NULL DEFAULT 1,
  CONSTRAINT isettinggrp_pa2_primary PRIMARY KEY ("iSettingGrp")
) ;
COMMENT ON TABLE isettinggrp_pa2 IS 'Setting groups for PA 2.0';
COMMENT ON COLUMN isettinggrp_pa2."iSettingGrp" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN isettinggrp_pa2."ShowPageSettings" IS 'Show the page settings panel (0=No, 1=Yes). The page should have the SettingGroupType equal to PageManagement.';
COMMENT ON COLUMN isettinggrp_pa2."SettingGroupType" IS 'Type of the setting group, 1 = PageManagement, 2 = SiteSettings, 3 = GroupParent';
COMMENT ON COLUMN isettinggrp_pa2."Priority" IS 'Priority of the setting group.';
COMMENT ON COLUMN isettinggrp_pa2."ParentId" IS 'If a subgroup, ptr to ISETTINGGRP_PA2.iSettingGrp of parent group.';
COMMENT ON COLUMN isettinggrp_pa2."PageId" IS 'Reference to PANEWPAGE.Id, in case that SettingGroupType = 1, this points to the page';
COMMENT ON COLUMN isettinggrp_pa2."Name" IS 'Name of the setting group.';


CREATE  TABLE langcd (
  "LangCd" character(6) NOT NULL,
  "Description" character varying(30),
  "ISOCode" character(3),
  "IsDeclined" numeric(5,0),
  "Default" numeric(5,0),
  "Inactive" numeric(5,0),
  CONSTRAINT langcd_primary PRIMARY KEY ("LangCd")
) ;
COMMENT ON TABLE langcd IS 'Language Codes';
COMMENT ON COLUMN langcd."LangCd" IS 'Primary Key, User defined code';
COMMENT ON COLUMN langcd."IsDeclined" IS 'Means declined to determine preferred language (0=No, 1=Yes)';
COMMENT ON COLUMN langcd."Inactive" IS '0 = No, 1 = Yes';
COMMENT ON COLUMN langcd."ISOCode" IS 'Optional ISO 639-2/B code';
COMMENT ON COLUMN langcd."Description" IS 'Code description ';
COMMENT ON COLUMN langcd."Default" IS 'Default code to use for new patients';


 
-- TABLES (includes constraints, indexes, owned sequences) 
CREATE  TABLE address (
  "Postal" character(15) NOT NULL,
  "Street" character(30),
  "HouseStart" character(6) NOT NULL,
  "HouseEnd" character(6),
  "Flag" numeric(5,0) NOT NULL,
  CONSTRAINT address_pk PRIMARY KEY ("Postal", "HouseStart", "Flag")
) ;
COMMENT ON TABLE address IS 'Stores information used for setting the Street Address from a Zip code and House Number.  Only in ACTA version.';


CREATE  TABLE adjacc (
  "Adjust" character(6) NOT NULL,
  "SLevel" numeric(10,0) NOT NULL,
  "Access" numeric(5,0),
  "MaxAmount" numeric,
  "LimitedTo" numeric(5,0),
  CONSTRAINT adjacc_primary PRIMARY KEY ("Adjust", "SLevel")
) ;
COMMENT ON TABLE adjacc IS 'Adjustment Code Access';
COMMENT ON COLUMN adjacc."SLevel" IS 'Primary key component, the security level that access is being defined for. Ptr to SLEVEL.Slevel';
COMMENT ON COLUMN adjacc."MaxAmount" IS 'If Access=1, optional max amount restricted to, in dollars.';
COMMENT ON COLUMN adjacc."LimitedTo" IS 'If Access=1, optional type of transaction the user is limited to (0=N/A, 1=Treatments, 2=Office Charges, 3=Patient Pmts, 4=Insurance Pmts)';
COMMENT ON COLUMN adjacc."Adjust" IS 'Primary key component, the adjustment code that access is being defined for. Ptr to ADJUST.Adjust';
COMMENT ON COLUMN adjacc."Access" IS 'Level has access to this adjustment code? (0=No, 1=Yes)';


CREATE  TABLE adjust (
  "Adjust" character(6) NOT NULL,
  "Description" character(30),
  "PrintDescription" character(30),
  "Type" numeric(5,0),
  "TotalPayment" numeric(5,0),
  "BankDeposit" numeric(5,0),
  "Reversal" numeric(5,0),
  "Transfer" numeric(5,0),
  "ClaimTotal" numeric(5,0),
  "Inactive" numeric(5,0),
  CONSTRAINT adjust_primary PRIMARY KEY ("Adjust")
) ;
COMMENT ON TABLE adjust IS 'Adjustment Codes';
COMMENT ON COLUMN adjust."Type" IS 'Effect on the patient balance (0=Debit, 1=Credit).';
COMMENT ON COLUMN adjust."Transfer" IS 'Use code to transfer funds between patient and insurance? (0=No, 1=Yes). Corresponds to the “Transfer Balance” checkbox on the adjustment code window. ';
COMMENT ON COLUMN adjust."TotalPayment" IS 'Type of transaction that the adjustment applies to (0=Charges, 1=Payments). Corresponds to the “Apply To” dropdown on the adjustment codes window';
COMMENT ON COLUMN adjust."Reversal" IS 'Adjust full payment? (0=No, 1=Yes)';
COMMENT ON COLUMN adjust."PrintDescription" IS 'Description of the adjustment code to print on receipts / statements.';
COMMENT ON COLUMN adjust."Inactive" IS 'Adjustment code is inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN adjust."Description" IS 'Description of the adjustment code, shown in the transaction ledger.';
COMMENT ON COLUMN adjust."ClaimTotal" IS 'Affects the claim total  dollar amount? (0=Claim will be sent with pre-adjustment total, 1=Claim will be sent with post-adjustment total).  ';
COMMENT ON COLUMN adjust."BankDeposit" IS 'Print on bank deposit report? (0=No, 1=Yes)';
COMMENT ON COLUMN adjust."Adjust" IS 'Primary key, code that identifies the adjustment.';


CREATE  TABLE afl_secret_versions (
  "Id" numeric(10,0) NOT NULL DEFAULT 0,
  "SecretId" numeric(10,0) NOT NULL DEFAULT 0,
  "Version" numeric(10,0) NOT NULL DEFAULT 0,
  secret clob,
  "Salt" character varying(255),
  "CreatedByApp" character varying(255),
  "CreatedDate" timestamp without time zone,
  CONSTRAINT afl_secret_versions_pk PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE afl_secret_versions IS 'Table for storing the AFL secret versions';
COMMENT ON COLUMN afl_secret_versions.secret IS 'Encrypted secret value';
COMMENT ON COLUMN afl_secret_versions."Version" IS 'Version of the secret';
COMMENT ON COLUMN afl_secret_versions."SecretId" IS 'FK to AFL_SECRETS.Id';
COMMENT ON COLUMN afl_secret_versions."Salt" IS 'Salt used to encrypt the secret';
COMMENT ON COLUMN afl_secret_versions."Id" IS 'PK component, ptr to primary key of the table from a sequence.';
COMMENT ON COLUMN afl_secret_versions."CreatedDate" IS 'Date the secret was created';
COMMENT ON COLUMN afl_secret_versions."CreatedByApp" IS 'Name of the application that created the secret';


CREATE  TABLE afl_secrets (
  "Id" numeric(10,0) NOT NULL DEFAULT 0,
  "Name" character varying(255),
  "CreatedByApp" character varying(255),
  "CreatedDate" timestamp without time zone,
  "Status" numeric(10,0) NOT NULL DEFAULT 0,
  CONSTRAINT afl_secrets_pk PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE afl_secrets IS 'Table for storing the AFL secrets';
COMMENT ON COLUMN afl_secrets."Status" IS 'Status of the secret. 1 = Active, 0 = Inactive';
COMMENT ON COLUMN afl_secrets."Name" IS 'Name of the secret';
COMMENT ON COLUMN afl_secrets."Id" IS 'PK component, ptr to primary key of the table from a sequence.';
COMMENT ON COLUMN afl_secrets."CreatedDate" IS 'Date the secret was created';
COMMENT ON COLUMN afl_secrets."CreatedByApp" IS 'Name of the application that created the secret';


CREATE  TABLE alert (
  "Alert" character(6) NOT NULL,
  "Description" character(30),
  "Inactive" numeric(5,0),
  "Color" numeric(10,0),
  CONSTRAINT alert_primary PRIMARY KEY ("Alert")
) ;
COMMENT ON TABLE alert IS 'Patient Financial / General Alerts';
COMMENT ON COLUMN alert."Inactive" IS 'Code is inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN alert."Description" IS 'Description of the alert code.';
COMMENT ON COLUMN alert."Color" IS 'Color to display alert in, as decimal representation of binary RGB values';
COMMENT ON COLUMN alert."Alert" IS 'Primary key, code to identify the alert.';


CREATE  TABLE alertd2 (
  "Auto" numeric(10,0) NOT NULL,
  "Type" numeric(10,0),
  "Code" character(7),
  "Description" character(127),
  "Inactive" numeric(5,0),
  "Note" character varying(4000),
  "Color" numeric(10,0),
  "IsAllergy" numeric(5,0),
  "MedAlert" numeric(10,0),
  CONSTRAINT alertd2_primary PRIMARY KEY ("Auto")
) ;
CREATE INDEX IF NOT EXISTS "ALERTD2_Code" ON alertd2 USING btree ("Code") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS "ALERTD2_Type" ON alertd2 USING btree ("Type", "Code") TABLESPACE pg_default;
COMMENT ON TABLE alertd2 IS 'Medical Alert/Allergy Definitions';
COMMENT ON COLUMN alertd2."Type" IS 'Is code deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN alertd2."Note" IS 'Note text attached to this alert';
COMMENT ON COLUMN alertd2."MedAlert" IS 'For conversion. Mapping to new MEDALERT table, ptr to MEDALERT.MedAlert.';
COMMENT ON COLUMN alertd2."IsAllergy" IS 'Does this alert represent an allergy? (0=No, 1=Yes)';
COMMENT ON COLUMN alertd2."Inactive" IS 'Code is inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN alertd2."Description" IS 'Description of the alert code';
COMMENT ON COLUMN alertd2."Color" IS 'Color to display alert in, as decimal representation of binary RGB values';
COMMENT ON COLUMN alertd2."Code" IS 'Code to identify the alert';
COMMENT ON COLUMN alertd2."Auto" IS 'Primary key, internal ID from sequence.';


CREATE  TABLE alertp2 (
  "Auto" numeric(10,0) NOT NULL,
  "PId" numeric(10,0),
  "AddDateTime" timestamp without time zone,
  "AId" numeric(10,0),
  "User" numeric(10,0),
  "Flag" numeric(10,0),
  "Note" character varying(4000),
  "Audit" numeric(10,0),
  "PtAlert" numeric(10,0),
  "Patient" numeric(10,0),
  "AlertType" numeric(5,0),
  "Description" character varying(127),
  "Status" numeric(5,0),
  CONSTRAINT alertp2_primary PRIMARY KEY ("Auto")
) ;
CREATE INDEX IF NOT EXISTS "ALERTP2_AId" ON alertp2 USING btree ("PId", "Flag", "AId") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS "ALERTP2_PId" ON alertp2 USING btree ("PId", "AddDateTime", "Flag") TABLESPACE pg_default;
COMMENT ON TABLE alertp2 IS 'Patient Medical Alerts/Allergies';
COMMENT ON COLUMN alertp2."User" IS 'User ID of entry user. Ptr to USERS.User';
COMMENT ON COLUMN alertp2."Status" IS 'For conversion. Status of the alert (0 = Active, 1 = Inactive, 2 = Resolved).';
COMMENT ON COLUMN alertp2."PtAlert" IS 'For conversion. Mapping to new PTALERT table, ptr to PTALERT.PtAlert.';
COMMENT ON COLUMN alertp2."Patient" IS 'For conversion. Ptr to PATIENT.Patient.';
COMMENT ON COLUMN alertp2."PId" IS 'Patient chart, ptr to PATIENT2.Auto';
COMMENT ON COLUMN alertp2."Note" IS 'Note text attached to this alert';
COMMENT ON COLUMN alertp2."Flag" IS 'Deleted? (0 = No, 1 = Yes).';
COMMENT ON COLUMN alertp2."Description" IS 'For conversion. Description of the alert.';
COMMENT ON COLUMN alertp2."Auto" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN alertp2."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN alertp2."AlertType" IS 'For conversion. Type of the alert (0 = Clinical Alert, 1 = Allergy, 2 = Medical Problem)';
COMMENT ON COLUMN alertp2."AddDateTime" IS 'Date/time of entry.';
COMMENT ON COLUMN alertp2."AId" IS 'Alert ID, ptr to ALERTD2.Auto';


CREATE  TABLE alertp2h (
  "AlertP2H" numeric(10,0) NOT NULL,
  "Auto" numeric(10,0),
  "PId" numeric(10,0),
  "AddDateTime" timestamp without time zone,
  "AId" numeric(10,0),
  "User" numeric(10,0),
  "Flag" numeric(10,0),
  "Note" character varying(4000),
  "Audit" numeric(10,0),
  "PtAlertH" numeric(10,0),
  "PtAlert" numeric(10,0),
  "Patient" numeric(10,0),
  "AlertType" numeric(5,0),
  "Description" character varying(127),
  "Status" numeric(5,0),
  CONSTRAINT alertp2h_primary PRIMARY KEY ("AlertP2H")
) ;
CREATE INDEX IF NOT EXISTS alertp2h_auto ON alertp2h USING btree ("Auto") TABLESPACE pg_default;
COMMENT ON TABLE alertp2h IS 'Patient Medical Alert/Allergy History';
COMMENT ON COLUMN alertp2h."User" IS 'User ID of entry user. Ptr to USERS.User';
COMMENT ON COLUMN alertp2h."Status" IS 'For conversion. Status of the alert (0 = Active, 1 = Inactive, 2 = Resolved).';
COMMENT ON COLUMN alertp2h."PtAlertH" IS 'For conversion. Mapping to new PTALERTH table, ptr to PTALERTH.PtAlertH.';
COMMENT ON COLUMN alertp2h."PtAlert" IS 'For conversion. Mapping to new PTALERT table, ptr to PTALERT.PtAlert.';
COMMENT ON COLUMN alertp2h."Patient" IS 'For conversion. Ptr to PATIENT.Patient.';
COMMENT ON COLUMN alertp2h."PId" IS 'Patient chart, ptr to PATIENT2.Auto';
COMMENT ON COLUMN alertp2h."Note" IS 'Note text attached to this alert';
COMMENT ON COLUMN alertp2h."Flag" IS 'Deleted? (0 = No, 1 = Yes).';
COMMENT ON COLUMN alertp2h."Description" IS 'For conversion. Description of the alert.';
COMMENT ON COLUMN alertp2h."Auto" IS 'Patient alert that this history item is for, Ptr to ALERTP2.Auto';
COMMENT ON COLUMN alertp2h."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN alertp2h."AlertType" IS 'For conversion. Type of the alert (0 = Clinical Alert, 1 = Allergy, 2 = Medical Problem)';
COMMENT ON COLUMN alertp2h."AlertP2H" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN alertp2h."AddDateTime" IS 'Date/time of entry.';
COMMENT ON COLUMN alertp2h."AId" IS 'Alert ID, ptr to ALERTD2.Auto';


CREATE  TABLE allocate (
  "PayType" numeric(5,0) NOT NULL,
  "PayId" numeric(10,0) NOT NULL,
  "PayTreatment" numeric(5,0) NOT NULL,
  "TrxType" numeric(5,0) NOT NULL,
  "TrxId" numeric(10,0) NOT NULL,
  "TrxTreatment" numeric(5,0) NOT NULL,
  "PolicyId" numeric(10,0) NOT NULL,
  "Amount" numeric,
  "User" numeric(10,0),
  "AllocateLink" numeric(10,0) NOT NULL DEFAULT 0,
  CONSTRAINT allocate_primary PRIMARY KEY ("PayType", "PayId", "PayTreatment", "TrxType", "TrxId", "TrxTreatment", "PolicyId")
) ;
CREATE INDEX IF NOT EXISTS allocate_allocatelink ON allocate USING btree ("AllocateLink") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS allocate_paykey ON allocate USING btree ("PayType", "PayId", "PayTreatment") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS allocate_trxkey ON allocate USING btree ("TrxType", "TrxId", "TrxTreatment") TABLESPACE pg_default;
COMMENT ON TABLE allocate IS 'Payment / Adjustment Allocations';
COMMENT ON COLUMN allocate."User" IS 'ID of the user who performed the allocation. Ptr to USERS.User';
COMMENT ON COLUMN allocate."TrxType" IS 'Primary key component, type of the charge being applied to. Ptr to TRX.Type';
COMMENT ON COLUMN allocate."TrxTreatment" IS 'Primary key component, line number of the of the charge being applied to. Ptr to TRX.Treatment';
COMMENT ON COLUMN allocate."TrxId" IS 'Primary key component, ID of the charge being applied to. Ptr to TRX.Id';
COMMENT ON COLUMN allocate."PolicyId" IS 'Primary key component, insurance policy ID. Ptr to PTPOL.PolicyId';
COMMENT ON COLUMN allocate."PayType" IS 'Primary key component, type of the payment or adjustment being applied from (3=Patient Payment,4=Insurance Payment, 6=Adjustment, 7=Insurance Adjustment). Ptr to TRX.Type';
COMMENT ON COLUMN allocate."PayTreatment" IS 'Primary key component, line number of the payment or adjustment being applied from. Ptr to TRX.Treatment';
COMMENT ON COLUMN allocate."PayId" IS 'Primary key component, ID of the payment or adjustment being applied from. Ptr to TRX.Id';
COMMENT ON COLUMN allocate."Amount" IS 'Amount being allocated, in dollars.';
COMMENT ON COLUMN allocate."AllocateLink" IS 'Key to ALLOCATELINK.AllocateLink, pointer to record holding the related history Ids.';


CREATE  TABLE allocatelink (
  "AllocateLink" numeric(10,0) NOT NULL DEFAULT 0,
  "TxHistoryId" numeric(10,0) NOT NULL DEFAULT 0,
  "PmtHistoryId" numeric(10,0) NOT NULL DEFAULT 0,
  "EntryDate" timestamp without time zone,
  CONSTRAINT allocatelink_primary PRIMARY KEY ("AllocateLink"),
  CONSTRAINT allocatelink_pmthis_fk FOREIGN KEY ("PmtHistoryId") REFERENCES history("History"),
  CONSTRAINT allocatelink_txhis_fk FOREIGN KEY ("TxHistoryId") REFERENCES history("History")
) ;
CREATE INDEX IF NOT EXISTS allocatelink_pmthiskey ON allocatelink USING btree ("PmtHistoryId") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS allocatelink_txhiskey ON allocatelink USING btree ("TxHistoryId") TABLESPACE pg_default;
COMMENT ON TABLE allocatelink IS 'AllocateLink records';
COMMENT ON COLUMN allocatelink."TxHistoryId" IS 'Foreign key to HISTORY.HistoryId, pointer to the latest Tx History record.';
COMMENT ON COLUMN allocatelink."PmtHistoryId" IS 'Foreign key to HISTORY.HistoryId, pointer to the latest Pmt History record.';
COMMENT ON COLUMN allocatelink."EntryDate" IS 'Date record is created.';
COMMENT ON COLUMN allocatelink."AllocateLink" IS 'Unique Primary key (to be maintained manually).';


CREATE  TABLE allocath (
  "AllocatH" numeric(10,0) NOT NULL,
  "PayType" numeric(5,0),
  "PayId" numeric(10,0),
  "PayTreatment" numeric(5,0),
  "TrxType" numeric(5,0),
  "TrxId" numeric(10,0),
  "TrxTreatment" numeric(5,0),
  "PolicyId" numeric(10,0),
  "Amount" numeric,
  "ModifiedDate" timestamp without time zone,
  "User" numeric(10,0),
  "AllocateLink" numeric(10,0) NOT NULL DEFAULT 0,
  CONSTRAINT allocath_primary PRIMARY KEY ("AllocatH")
) ;
CREATE INDEX IF NOT EXISTS allocath_allocatelink ON allocath USING btree ("AllocateLink") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS allocath_paykey ON allocath USING btree ("PayType", "PayId", "PayTreatment") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS allocath_trxkey ON allocath USING btree ("TrxType", "TrxId", "TrxTreatment") TABLESPACE pg_default;
COMMENT ON TABLE allocath IS 'Payment / Adjustment Allocations History';
COMMENT ON COLUMN allocath."User" IS 'ID of the user who performed the allocation. Ptr to USERS.User';
COMMENT ON COLUMN allocath."TrxType" IS 'Type of the charge being applied to. Ptr to TRX.Type';
COMMENT ON COLUMN allocath."TrxTreatment" IS 'Line number of the of the charge being applied to. Ptr to TRX.Treatment';
COMMENT ON COLUMN allocath."TrxId" IS 'ID of the charge being applied to. Ptr to TRX.Id';
COMMENT ON COLUMN allocath."PolicyId" IS 'Insurance policy ID. Ptr to PTPOL.PolicyId';
COMMENT ON COLUMN allocath."PayType" IS 'Type of the payment or adjustment being applied from (3=Patient Payment,4=Insurance Payment, 6=Adjustment, 7=Insurance Adjustment). Ptr to TRX.Type';
COMMENT ON COLUMN allocath."PayTreatment" IS 'Line number of the payment or adjustment being applied from. Ptr to TRX.Treatment';
COMMENT ON COLUMN allocath."PayId" IS 'ID of the payment or adjustment being applied from. Ptr to TRX.Id';
COMMENT ON COLUMN allocath."ModifiedDate" IS 'Last modified date/time of this allocation.';
COMMENT ON COLUMN allocath."Amount" IS 'Amount being allocated, in dollars.';
COMMENT ON COLUMN allocath."AllocateLink" IS 'Key to ALLOCATELINK.AllocateLink, pointer to record holding the related history Ids.';
COMMENT ON COLUMN allocath."AllocatH" IS 'Primary key, internal ID from sequence.';


CREATE  TABLE altphone (
  "AltPhone" numeric(10,0) NOT NULL,
  "Id" numeric(10,0),
  "Description" character varying(30),
  "Reference" character(6),
  "Area" character varying(4),
  "Telephone" character varying(8),
  "Ext" character varying(6),
  CONSTRAINT altphone_primary PRIMARY KEY ("AltPhone")
) ;
COMMENT ON TABLE altphone IS 'Alternate phone numbers for practices';
COMMENT ON COLUMN altphone."Telephone" IS 'Telephone number';
COMMENT ON COLUMN altphone."Reference" IS 'Optional Reference code';
COMMENT ON COLUMN altphone."Id" IS 'Pracitce Id';
COMMENT ON COLUMN altphone."Ext" IS 'Extension';
COMMENT ON COLUMN altphone."Description" IS 'Description of the alternate phone number.';
COMMENT ON COLUMN altphone."Area" IS 'Area Code';
COMMENT ON COLUMN altphone."AltPhone" IS 'Unqiue sequence';


CREATE  TABLE analytics_error_log (
  "Id" numeric(10,0) NOT NULL DEFAULT 0,
  "Date" timestamp without time zone,
  "User" numeric(10,0) NOT NULL DEFAULT 0,
  "Station" numeric(10,0) NOT NULL DEFAULT 0,
  "Source" character varying(255),
  error clob,
  parameters clob,
  CONSTRAINT analytics_error_log_pk PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE analytics_error_log IS 'Table for storing Analytics errors';
COMMENT ON COLUMN analytics_error_log.parameters IS 'The report parameters';
COMMENT ON COLUMN analytics_error_log.error IS 'The error description';
COMMENT ON COLUMN analytics_error_log."User" IS 'The user Id';
COMMENT ON COLUMN analytics_error_log."Station" IS 'The station Id';
COMMENT ON COLUMN analytics_error_log."Source" IS 'The source of the error';
COMMENT ON COLUMN analytics_error_log."Id" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN analytics_error_log."Date" IS 'Date record was created';


CREATE  TABLE analytics_log (
  "AnalyticsLog" numeric(10,0) NOT NULL DEFAULT 0,
  "Date" timestamp without time zone,
  "User" numeric(10,0) NOT NULL DEFAULT 0,
  "Station" numeric(10,0) NOT NULL DEFAULT 0,
  "Value1" numeric(5,0) NOT NULL DEFAULT 0,
  "Value2" numeric(5,0) NOT NULL DEFAULT 0,
  "Action" character varying(45),
  "HashValue" character varying(45),
  CONSTRAINT analytics_log_pk PRIMARY KEY ("AnalyticsLog")
) ;
COMMENT ON TABLE analytics_log IS 'Table for storing Analytics opt in and opt out logs';
COMMENT ON COLUMN analytics_log."Value2" IS 'Random number used for hash';
COMMENT ON COLUMN analytics_log."Value1" IS 'Random number used for hash';
COMMENT ON COLUMN analytics_log."User" IS 'The user Id';
COMMENT ON COLUMN analytics_log."Station" IS 'The station Id';
COMMENT ON COLUMN analytics_log."HashValue" IS 'Audit hash for tamper-resistance';
COMMENT ON COLUMN analytics_log."Date" IS 'Date record was created';
COMMENT ON COLUMN analytics_log."AnalyticsLog" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN analytics_log."Action" IS 'Encrypted value representing opt in actions';


CREATE  TABLE anesdelv (
  "AnesDelv" numeric(10,0) NOT NULL,
  "Name" character varying(30),
  "Order" numeric(5,0),
  "Inactive" numeric(5,0),
  CONSTRAINT anesdelv_primary PRIMARY KEY ("AnesDelv")
) ;
COMMENT ON TABLE anesdelv IS 'Table for Pre-defined Delivery of Anesthetics Drugs';
COMMENT ON COLUMN anesdelv."Order" IS 'Order of the Delivery of Anesthetics Drugs';
COMMENT ON COLUMN anesdelv."Name" IS 'Name/description of the Delivery of Anesthetics Drugs';
COMMENT ON COLUMN anesdelv."Inactive" IS 'Defines if the Delivery of Anesthetics Drugs is active or inactive (0=active; 1=inactive)';
COMMENT ON COLUMN anesdelv."AnesDelv" IS 'Primary key , unique code to identify the Delivery of Anesthetics Drugs';


CREATE  TABLE anesdmax (
  "AnesDMax" numeric(10,0) NOT NULL,
  "AnesDrug" numeric(10,0),
  "AgeFrom" numeric(10,0),
  "AgeTo" numeric(10,0),
  "MaxTotal" numeric,
  "WarnPerc" numeric(10,0),
  "ErrPerc" numeric(10,0),
  "ErrIndiv" numeric,
  "AnesUnit" numeric(10,0),
  CONSTRAINT anesdmax_primary PRIMARY KEY ("AnesDMax")
) ;
CREATE INDEX IF NOT EXISTS anesdmax_drugagefromtokey ON anesdmax USING btree ("AnesDrug", "AgeFrom", "AgeTo") TABLESPACE pg_default;
COMMENT ON TABLE anesdmax IS 'Anesthetics Drug Maximums table for Surgery.';
COMMENT ON COLUMN anesdmax."WarnPerc" IS 'Warn if maximum dosage exceeds percentage of Total';
COMMENT ON COLUMN anesdmax."MaxTotal" IS 'Total maximum dosage (per kg of patient)';
COMMENT ON COLUMN anesdmax."ErrPerc" IS 'Show error if maximum dosage exceeds percentage of Total';
COMMENT ON COLUMN anesdmax."ErrIndiv" IS '(Optional) Show error if individual value exceeds this maximum';
COMMENT ON COLUMN anesdmax."AnesUnit" IS 'Pointer to ANESUNIT.AnesUnit';
COMMENT ON COLUMN anesdmax."AnesDrug" IS 'Anesthetic Drug, ptr to ANESDRUG.AnesDrug.';
COMMENT ON COLUMN anesdmax."AnesDMax" IS 'Primary key, unique code to identify entry.';
COMMENT ON COLUMN anesdmax."AgeTo" IS 'Age of Patient, maximum value.';
COMMENT ON COLUMN anesdmax."AgeFrom" IS 'Age of Patient, minimum value.';


CREATE  TABLE anesdrug (
  "AnesDrug" numeric(10,0) NOT NULL,
  "Drug" character(10),
  "AnesUnit" numeric(10,0),
  "AnesDelv" numeric(10,0),
  "AnesGaug" numeric(10,0),
  "Order" numeric(5,0),
  "Default" numeric(5,0),
  "IsPercentage" numeric(5,0),
  "Waste" numeric(5,0),
  "ShortName" character varying(15),
  CONSTRAINT anesdrug_primary PRIMARY KEY ("AnesDrug")
) ;
COMMENT ON TABLE anesdrug IS 'Anesthetic Drugs For Surgery Appointments';
COMMENT ON COLUMN anesdrug."Waste" IS 'Is entry allowed and approval required for this Drug (0=No, 1=Yes, 2=Yes with approval)';
COMMENT ON COLUMN anesdrug."ShortName" IS 'Short name of the drug';
COMMENT ON COLUMN anesdrug."Order" IS 'Order of the Anesthetic Drug';
COMMENT ON COLUMN anesdrug."IsPercentage" IS 'Is a percentage mixture of another drug? (0=No, 1=Yes).';
COMMENT ON COLUMN anesdrug."Drug" IS 'Pointer to DRUG.Drug';
COMMENT ON COLUMN anesdrug."Default" IS '0/1 - Is a default drug to use for surgery appointments';
COMMENT ON COLUMN anesdrug."AnesUnit" IS 'Default Unit used, Pointer to ANESUNIT.AnesUnit.';
COMMENT ON COLUMN anesdrug."AnesGaug" IS 'Pointer to ANESGAUG.AnesGaug';
COMMENT ON COLUMN anesdrug."AnesDrug" IS 'Primary key , unique code to identify the Anesthetic Drug';
COMMENT ON COLUMN anesdrug."AnesDelv" IS 'Pointer to ANESDELV.AnesDelv';


CREATE  TABLE anesgaug (
  "AnesGaug" numeric(10,0) NOT NULL,
  "Name" character varying(30),
  "Order" numeric(5,0),
  "Inactive" numeric(5,0),
  CONSTRAINT anesgaug_primary PRIMARY KEY ("AnesGaug")
) ;
COMMENT ON TABLE anesgaug IS 'Table for Pre-defined Gauges for delivery Drugs';
COMMENT ON COLUMN anesgaug."Order" IS 'Order of the Gauges for delivery Drugs';
COMMENT ON COLUMN anesgaug."Name" IS 'Name/description of the Gauges for delivery Drugs';
COMMENT ON COLUMN anesgaug."Inactive" IS 'Defines if the Gauges for delivery Drugs is active or inactive (0=active; 1=inactive)';
COMMENT ON COLUMN anesgaug."AnesGaug" IS 'Primary key , unique code to identify the Gauges for delivery Drugs';


CREATE  TABLE anesmix (
  "AnesMix" numeric(10,0) NOT NULL,
  "MainDrug" numeric(10,0),
  "OtherDrug" numeric(10,0),
  CONSTRAINT anesmix_primary PRIMARY KEY ("AnesMix")
) ;
CREATE INDEX IF NOT EXISTS anesmix_maindrugkey ON anesmix USING btree ("MainDrug") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS anesmix_otherdrugkey ON anesmix USING btree ("OtherDrug") TABLESPACE pg_default;
COMMENT ON TABLE anesmix IS 'Anesthetic Mixture for Surgery module.';
COMMENT ON COLUMN anesmix."OtherDrug" IS 'Other Drug, ptr to ANESDRUG.AnesDrug.';
COMMENT ON COLUMN anesmix."MainDrug" IS 'Main Drug, ptr to ANESDRUG.AnesDrug.';
COMMENT ON COLUMN anesmix."AnesMix" IS 'Primary key, unique code to identify single entry of Anesthetic Mixture.';


CREATE  TABLE anesunit (
  "AnesUnit" numeric(10,0) NOT NULL,
  "Name" character varying(30),
  "Order" numeric(5,0),
  "Inactive" numeric(5,0),
  "IsPercentage" numeric(5,0),
  "IsPerKg" numeric(5,0),
  "IsContinued" numeric(5,0),
  CONSTRAINT anesunit_primary PRIMARY KEY ("AnesUnit")
) ;
COMMENT ON TABLE anesunit IS 'Table for Pre-defined Units (Forms) of Anesthetic Drugs';
COMMENT ON COLUMN anesunit."Order" IS 'Order of the anestethics Units(Forms)';
COMMENT ON COLUMN anesunit."Name" IS 'Name/description of the anestethics Units(Forms)';
COMMENT ON COLUMN anesunit."IsPercentage" IS 'Is this percentage-based unit? (0=No, 1=Yes).';
COMMENT ON COLUMN anesunit."IsPerKg" IS 'Is this unit per kg? (0=No, 1=Yes).';
COMMENT ON COLUMN anesunit."IsContinued" IS '0/1 - Is a continued flow (graphed as a line)';
COMMENT ON COLUMN anesunit."Inactive" IS 'Defines if the anestethics Units(Forms) is active or inactive (0=active; 1=inactive)';
COMMENT ON COLUMN anesunit."AnesUnit" IS 'Primary key , unique code to identify the anestethics Units(Forms)';


CREATE  TABLE answer2 (
  "Auto" numeric(10,0) NOT NULL,
  "PId" numeric(10,0),
  "SId" numeric(10,0),
  "Status" numeric(10,0),
  "Text" character(63),
  "ModifiedDateTime" timestamp without time zone,
  "User" numeric(10,0),
  CONSTRAINT answer2_primary PRIMARY KEY ("Auto")
) ;
CREATE INDEX IF NOT EXISTS "ANSWER2_PId" ON answer2 USING btree ("PId", "SId") TABLESPACE pg_default;
COMMENT ON TABLE answer2 IS 'Survey Answers';
COMMENT ON COLUMN answer2."User" IS 'User ID of entry user, ptr to USERS.User';
COMMENT ON COLUMN answer2."Text" IS 'Text of the answer.';
COMMENT ON COLUMN answer2."Status" IS 'Not used.';
COMMENT ON COLUMN answer2."SId" IS 'Survey question that this answer is for, ptr to SURVEY2.Auto';
COMMENT ON COLUMN answer2."PId" IS 'Patient chart, ptr to PATIENT2.Auto';
COMMENT ON COLUMN answer2."ModifiedDateTime" IS 'Date/time of entry. ';
COMMENT ON COLUMN answer2."Auto" IS 'Primary key, internal ID from sequence.';


CREATE  TABLE ap_note (
  "AP_NOTE_AutoDec" numeric(10,0) NOT NULL,
  "AP_NOTE_AppId" numeric(10,0),
  "AP_NOTE_Type" numeric(10,0),
  "AP_NOTE_PatientId" numeric(10,0),
  "AddDateTime" timestamp without time zone,
  "ModifiedDateTime" timestamp without time zone,
  "AP_NOTE_Flag" numeric(10,0),
  "AP_NOTE_Date1" numeric(10,0),
  "AP_NOTE_Date2" numeric(10,0),
  "AP_NOTE_PAmount" numeric,
  "AP_NOTE_IAmount" numeric,
  "AP_NOTE_Text" character(255),
  "AP_NOTE_Treatment" numeric(10,0),
  "CreationUser" numeric(10,0),
  "ModifiedUser" numeric(10,0),
  "StationId" numeric(10,0),
  CONSTRAINT ap_note_primaryindex PRIMARY KEY ("AP_NOTE_AutoDec")
) ;
CREATE INDEX IF NOT EXISTS "AP_NOTE_AppId_Type" ON ap_note USING btree ("AP_NOTE_AppId", "AP_NOTE_Type", "AP_NOTE_Treatment") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ap_note_patientkey ON ap_note USING btree ("AP_NOTE_PatientId") TABLESPACE pg_default;
COMMENT ON TABLE ap_note IS 'Sticky notes, user definable notes that can be attached to patients, appts, txs, etc';
COMMENT ON COLUMN ap_note."StationId" IS 'Id code of the workstation.';
COMMENT ON COLUMN ap_note."ModifiedUser" IS 'User Id of the user that last modified the record. ptr to USERS.User';
COMMENT ON COLUMN ap_note."ModifiedDateTime" IS 'Date/time of most recent modification. ';
COMMENT ON COLUMN ap_note."CreationUser" IS 'User Id of the entry user, ptr to USERS.User';
COMMENT ON COLUMN ap_note."AddDateTime" IS 'Date/time of entry. ';
COMMENT ON COLUMN ap_note."AP_NOTE_Type" IS 'Indicates what the note is attached to (0=Appointment, 1 = Scheduler, 2 = Patients, 3 = Patient, 4 = Patient Trx, 5 = Trx General, 6 = Treatment, 7 = Planned Treatment, 8 = Office Charge, 9 = Payment, 10 = Adjustment, 11 = Insurance Payment, 12 = Clinic, 13 = Book, 16 = Availability)';
COMMENT ON COLUMN ap_note."AP_NOTE_Treatment" IS 'If Transaction specific note, then this is the TRX.Treatment number';
COMMENT ON COLUMN ap_note."AP_NOTE_Text" IS 'Free text area to write the note.';
COMMENT ON COLUMN ap_note."AP_NOTE_PatientId" IS 'This is set to 0 for AP_NOTE_Types (1, 2, 3, 13, 16) ELSE this is set to the patient Id';
COMMENT ON COLUMN ap_note."AP_NOTE_PAmount" IS 'DEPRECATED';
COMMENT ON COLUMN ap_note."AP_NOTE_IAmount" IS 'DEPRECATED';
COMMENT ON COLUMN ap_note."AP_NOTE_Flag" IS 'Numeric field to store the note options, this is the total combined value of the options (On Date=1, When making appointments=2, When view treatment plan=4, At check in=8, At Check out=16, When select patient=32, Patient claims=525288, After Date=32768).';
COMMENT ON COLUMN ap_note."AP_NOTE_Date2" IS 'Date to de-activate the note (in days since Jan 1, 1901).';
COMMENT ON COLUMN ap_note."AP_NOTE_Date1" IS 'Date to display the note on screen (in days since Jan 1, 1901)';
COMMENT ON COLUMN ap_note."AP_NOTE_AutoDec" IS 'Primary key, internal ID from sequence, code to identify the AP_Note';
COMMENT ON COLUMN ap_note."AP_NOTE_AppId" IS 'Record Id that note is tied to, may be APPOINT.Appointment, TRX.Id, PATIENT.Patient, or Dialog Resource Id (if AP_NOTE_Type=2)';


CREATE  TABLE apcdmax (
  "ApCdMax" numeric(10,0) NOT NULL,
  "Provider" character(10),
  "ApptCode" character(15),
  "StartTime" numeric(10,0),
  "EndTime" numeric(10,0),
  "Limit" numeric(5,0),
  "AllowBacktoBack" numeric(5,0),
  CONSTRAINT apcdmax_primary PRIMARY KEY ("ApCdMax")
) ;
CREATE INDEX IF NOT EXISTS apcdmax_provapptcode ON apcdmax USING btree ("Provider", "ApptCode") TABLESPACE pg_default;
COMMENT ON TABLE apcdmax IS 'Appointment Code Limits';
COMMENT ON COLUMN apcdmax."StartTime" IS 'Start time for the limit, in minutes from midnight. ';
COMMENT ON COLUMN apcdmax."Provider" IS 'Provider that the limit is for, ptr to PRODUCER.Producer';
COMMENT ON COLUMN apcdmax."Limit" IS 'Maximum number of the appointment codes allowed for the provider. ';
COMMENT ON COLUMN apcdmax."EndTime" IS 'End time for the limit, in minutes from midnight. ';
COMMENT ON COLUMN apcdmax."ApptCode" IS 'Appointment code that the limit is on, ptr to APPTCODE.ApptCode';
COMMENT ON COLUMN apcdmax."ApCdMax" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN apcdmax."AllowBacktoBack" IS 'Allow back-to-back? (0=No, 1=Yes)';


CREATE  TABLE apexpert (
  "ExpertId" numeric(10,0) NOT NULL,
  "ApptNum" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "Provider" character(10),
  "ApptCode" character(15),
  "Length" numeric(10,0),
  "Discipline" character(6),
  "Clinic" numeric(10,0),
  "Chair" numeric(10,0),
  "Book" numeric(10,0),
  "Instructor" numeric(10,0),
  "Specialist" numeric(5,0),
  "PGroup" character(6),
  "Time0" numeric(10,0),
  "Time1" numeric(10,0),
  "Time2" numeric(10,0),
  "Time3" numeric(10,0),
  "Time4" numeric(10,0),
  "Time5" numeric(10,0),
  "ClinGrp" numeric(10,0),
  "Appointment" numeric(10,0),
  "Assistant" character(10),
  "SecondaryMCBFlag" numeric(5,0),
  "PrimaryExclusive" numeric(5,0),
  CONSTRAINT apexpert_primary PRIMARY KEY ("ExpertId", "ApptNum")
) ;
COMMENT ON TABLE apexpert IS 'Holds information neccessary to perform searches based on user selections. Used for Appointment Expert searches.';
COMMENT ON COLUMN apexpert."Time5" IS 'Appt Assistant Time 5 in minutes (for production details)';
COMMENT ON COLUMN apexpert."Time4" IS 'Appt Assistant Time 4 in minutes (for production details)';
COMMENT ON COLUMN apexpert."Time3" IS 'Appt Assistant Time 3 in minutes (for production details)';
COMMENT ON COLUMN apexpert."Time2" IS 'Appt Assistant Time 2 in minutes (for production details)';
COMMENT ON COLUMN apexpert."Time1" IS 'Appt Assistant Time1 in minutes (for production details)';
COMMENT ON COLUMN apexpert."Time0" IS 'Appt Assistant Time 0 in minutes (for production details)';
COMMENT ON COLUMN apexpert."Specialist" IS 'Search for a specialist? (0 = No, 1 = Yes)';
COMMENT ON COLUMN apexpert."SecondaryMCBFlag" IS '0=N/A(if no 2nd provider), 1=Assistant Time, 2=Primary Provider Time, 3=Total Time';
COMMENT ON COLUMN apexpert."Provider" IS 'Provider ID, ptr to PRODUCER.Producer';
COMMENT ON COLUMN apexpert."PrimaryExclusive" IS 'Primary exclusive time? (0=No, 1=Yes [Appt Time], 2=Yes [Prov Time])';
COMMENT ON COLUMN apexpert."Patient" IS 'Patient ID, ptr to PATIENT.Patient';
COMMENT ON COLUMN apexpert."PGroup" IS 'Provider Group, ptr to PGROUP.PGroup';
COMMENT ON COLUMN apexpert."Length" IS 'Optional field, ID code of the appointment length to find.';
COMMENT ON COLUMN apexpert."Instructor" IS 'Optional field, ID code of the instructor to search. ';
COMMENT ON COLUMN apexpert."ExpertId" IS 'ID code of the expert search';
COMMENT ON COLUMN apexpert."Discipline" IS 'Optional field, ID code of the discipline to search, defaults to all disciplines.';
COMMENT ON COLUMN apexpert."Clinic" IS 'Optional field, ID code of the Clinic to search, defaults to the currently selected clinic in the scheduler.';
COMMENT ON COLUMN apexpert."ClinGrp" IS 'Ptr to CLINGRP.ClinGrp';
COMMENT ON COLUMN apexpert."Chair" IS 'Optional field, ID code of the chair to search, defaults to all available chairs.';
COMMENT ON COLUMN apexpert."Book" IS 'Optional field, ID code of the book or scheduler to search.';
COMMENT ON COLUMN apexpert."Assistant" IS 'Appointment assistant, second provider';
COMMENT ON COLUMN apexpert."ApptNum" IS 'Appointment ID, ptr to APPOINT.Appointment';
COMMENT ON COLUMN apexpert."ApptCode" IS 'Type or length of appointment to find, ptr to APPTCODE.Apptcode';
COMMENT ON COLUMN apexpert."Appointment" IS 'Ptr to APPT.Appointment';


CREATE  TABLE appoint (
  "Appointment" numeric(10,0) NOT NULL,
  "Date" timestamp without time zone,
  "Chair" numeric(10,0),
  "Patient" numeric(10,0),
  "Type" numeric(5,0),
  "Producer" character(10),
  "From" numeric(10,0),
  "CreateDate" timestamp without time zone,
  "Code" character(15),
  "Unit0" numeric(10,0),
  "Unit1" numeric(10,0),
  "Unit2" numeric(10,0),
  "Unit3" numeric(10,0),
  "Unit4" numeric(10,0),
  "Unit5" numeric(10,0),
  "Time0" numeric(10,0),
  "Time1" numeric(10,0),
  "Time2" numeric(10,0),
  "Time3" numeric(10,0),
  "Time4" numeric(10,0),
  "Time5" numeric(10,0),
  "Estimate" numeric,
  "Class" character(15),
  "ModifiedDateTime" timestamp without time zone,
  "User" numeric(10,0),
  "IsRecall" numeric(5,0),
  "IsAsap" numeric(5,0),
  "IsConfirm" numeric(5,0),
  "IsShortNotice" numeric(5,0),
  "Status" numeric(5,0),
  "Request" numeric(10,0),
  "Rank" numeric(10,0),
  "UStatus" character(6),
  "Reserve" numeric(10,0),
  "OrthoStage" character(6),
  "IsOrtho" numeric(5,0),
  "Cancel" character(6),
  "Reason" character varying(200),
  "Assistant" character(10),
  "Clinic" numeric(10,0),
  "IsRequest" numeric(5,0),
  "Instructor" numeric(10,0),
  "IsNew" numeric(5,0),
  "CheckInTime" numeric(10,0),
  "TimeSeated" numeric(10,0),
  "Held" numeric(5,0),
  "SignInTime" numeric(10,0),
  "SecondaryMCBFlag" numeric(5,0),
  "NotBeforeDate" timestamp without time zone,
  "PtEstimateStatus" numeric(5,0),
  "PtEstimate" numeric,
  "BookingOrder" numeric(10,0),
  "ExpertAdd" numeric(5,0),
  "CheckOutDate" timestamp without time zone,
  "CheckOutTime" numeric(10,0),
  "PrimaryExclusive" numeric(5,0),
  CONSTRAINT appoint_primary PRIMARY KEY ("Appointment")
) ;
CREATE INDEX IF NOT EXISTS appoint_dateclinic ON appoint USING btree ("Date", "Clinic") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS appoint_datekey ON appoint USING btree ("Date", "Chair", "Type", "Producer") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS appoint_patientkey ON appoint USING btree ("Patient", "Type", "Date") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS appoint_reservekey ON appoint USING btree ("Reserve") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS appoint_typekey ON appoint USING btree ("Type", "Producer", "Date") TABLESPACE pg_default;
COMMENT ON TABLE appoint IS 'Apppointments';
COMMENT ON COLUMN appoint."User" IS 'User ID of entry user, ptr to USERS.User';
COMMENT ON COLUMN appoint."Unit5" IS 'Appt Doctor Unit3 (for production details)';
COMMENT ON COLUMN appoint."Unit4" IS 'Appt Assistant Unit3 (for production details)';
COMMENT ON COLUMN appoint."Unit3" IS 'Appt Doctor Unit2 (for production details)';
COMMENT ON COLUMN appoint."Unit2" IS 'Appt Assistant Unit2 (for production details)';
COMMENT ON COLUMN appoint."Unit1" IS 'Appt Doctor Unit1 (for production details)';
COMMENT ON COLUMN appoint."Unit0" IS 'Appt Assistant Unit1 (for production details)';
COMMENT ON COLUMN appoint."UStatus" IS 'User-definable appt status, ptr to STATUS.Status';
COMMENT ON COLUMN appoint."Type" IS 'Status of Appt (0=Active, 1=Checked-in, 2=Checked-out, 3=Pending, 4=Reschedule status, 5=Failed, 6=Cancelled, 7=Deleted, 8=Requested, 9=Ortho Request, 10=Planned)';
COMMENT ON COLUMN appoint."TimeSeated" IS 'Actual time that the patient sits in chair';
COMMENT ON COLUMN appoint."Time5" IS 'Appt Doctor Time3 in minutes (for production details)';
COMMENT ON COLUMN appoint."Time4" IS 'Appt Assistant Time3 in minutes (for production details)';
COMMENT ON COLUMN appoint."Time3" IS 'Appt Doctor Time2 in minutes (for production details)';
COMMENT ON COLUMN appoint."Time2" IS 'Appt Assistant Time2 in minutes (for production details)';
COMMENT ON COLUMN appoint."Time1" IS 'Appt Doctor Time1 in minutes (for production details)';
COMMENT ON COLUMN appoint."Time0" IS 'Appt Assistant Time1 in minutes (for production details)';
COMMENT ON COLUMN appoint."Status" IS 'Appt is Deleted? (0 = No, 2=Yes)';
COMMENT ON COLUMN appoint."SignInTime" IS 'Time (minutes since midnight) that the patient signed in for the appointment';
COMMENT ON COLUMN appoint."SecondaryMCBFlag" IS '0=N/A(if no 2nd provider), 1=Assistant Time, 2=Primary Provider Time, 3=Total Time';
COMMENT ON COLUMN appoint."Reserve" IS 'ID of the Chair reservation that the appt is made in, ptr to RESERVE.Reserve';
COMMENT ON COLUMN appoint."Request" IS 'ID of the Chart Request that is related to the appt, ptr to REQUEST.Request';
COMMENT ON COLUMN appoint."Reason" IS 'Reason/note for the appointment - pts to CANCEL.Description';
COMMENT ON COLUMN appoint."Rank" IS 'Rating of the importance / urgency of the appointment, ptr to CLASS.Rank';
COMMENT ON COLUMN appoint."PtEstimateStatus" IS 'Patient estimate status (0=no estimate, 1=estimated)';
COMMENT ON COLUMN appoint."PtEstimate" IS 'Patient portion of the estimate amount for this appt';
COMMENT ON COLUMN appoint."Producer" IS 'Primary appointment provider, ptr to PRODUCER.Producer';
COMMENT ON COLUMN appoint."PrimaryExclusive" IS 'Primary exclusive time? (0=No, 1=Yes [Appt Time], 2=Yes [Prov Time])';
COMMENT ON COLUMN appoint."Patient" IS 'Patient that the appointment is for, ptr to PATIENT.Patient';
COMMENT ON COLUMN appoint."OrthoStage" IS 'If IsOrtho=1, the ortho stage for this appointment. Ptr to STAGE.Code.';
COMMENT ON COLUMN appoint."NotBeforeDate" IS 'For Type 8 and 10, appointment must be booked to occur on or after this date';
COMMENT ON COLUMN appoint."ModifiedDateTime" IS 'Date/time of most recent modification. ';
COMMENT ON COLUMN appoint."IsShortNotice" IS 'Appointment was made on short notice? (0 = No, 1 = Yes).';
COMMENT ON COLUMN appoint."IsRequest" IS 'Is this an appointment request? (0 = No, 1 = Yes)';
COMMENT ON COLUMN appoint."IsRecall" IS 'Appointment is for a recall? (0 = No, 1 = Yes).';
COMMENT ON COLUMN appoint."IsOrtho" IS 'Ortho appointment? (0 = No, 1 = Yes).';
COMMENT ON COLUMN appoint."IsNew" IS 'Is this a new appointment request? (0 = No alert, 1=Need to alert group mgr (staff), 2=Need to alert student (provider), 3=Need to alert both parties, 4=Edit mode - not new, 5=Need to acknowledge group manager -staff - in edit mode, 6= Need to acknowledge student provider in edit mode, 7=Need to acknowledge both parties in edit mode)';
COMMENT ON COLUMN appoint."IsConfirm" IS 'Appointment has been confirmed? (0 = No, 1 = Yes).';
COMMENT ON COLUMN appoint."IsAsap" IS 'Appointment needs to be done ASAP (Emergency)? (0 = No, 1 = Yes).';
COMMENT ON COLUMN appoint."Instructor" IS 'If IsRequest=1, ID code of the instructor for the appointment request. Ptr to USERS.User.';
COMMENT ON COLUMN appoint."Held" IS 'Flag to indicate whether an appointment has been successfully added. 0 = Added successfully, 1 = Not yet added';
COMMENT ON COLUMN appoint."From" IS 'For APPOINT.Type=0,1,2, represents the time that the appointment starts in minutes from midnight. For APPOINT.Type=4, encodes the screen position of the yellow floating appointment. Not used for other APPOINT.Type values. ';
COMMENT ON COLUMN appoint."ExpertAdd" IS 'Was appointment booked with the Expert? (0=No, 1=Yes)';
COMMENT ON COLUMN appoint."Estimate" IS 'Estimated charge for/cost of appt';
COMMENT ON COLUMN appoint."Date" IS 'Date of the appointment';
COMMENT ON COLUMN appoint."CreateDate" IS 'Date that the appointment record was created. ';
COMMENT ON COLUMN appoint."Code" IS 'Appointment code for this appointment, ptr to APPTCODE.Apptcode';
COMMENT ON COLUMN appoint."Clinic" IS 'If IsRequest=1 - requested clinic for the appointment, ptr to CLINIC.Clinic';
COMMENT ON COLUMN appoint."Class" IS 'Discipline of the appt, ptr to CLASS.Class';
COMMENT ON COLUMN appoint."CheckOutTime" IS 'Time that the appointment was checked out (in minutes from midnight).';
COMMENT ON COLUMN appoint."CheckOutDate" IS 'Date that the appointment was checked out.';
COMMENT ON COLUMN appoint."CheckInTime" IS 'Check in time in minutes from midnight';
COMMENT ON COLUMN appoint."Chair" IS 'Chair that the appointment is scheduled in, ptr to CHAIR.Chair';
COMMENT ON COLUMN appoint."Cancel" IS 'Appt Cancellation code, ptr to CANCEL.Cancel';
COMMENT ON COLUMN appoint."BookingOrder" IS 'Internal number to determine appointment booking order';
COMMENT ON COLUMN appoint."Assistant" IS 'Secondary appointment provider/assistant. Ptr to PRODUCER.Producer.';
COMMENT ON COLUMN appoint."Appointment" IS 'Primary key, internal ID from sequence.';


CREATE  TABLE apptacc (
  "ApptCode" character(15) NOT NULL,
  "ProdType" character(1) NOT NULL,
  "Access" numeric(5,0),
  "Type" numeric(5,0) NOT NULL,
  "Provider" character(10) NOT NULL,
  CONSTRAINT apptacc_primary PRIMARY KEY ("ApptCode", "ProdType", "Type", "Provider")
) ;
CREATE INDEX IF NOT EXISTS apptacc_provider ON apptacc USING btree ("ProdType", "Type", "Provider") TABLESPACE pg_default;
COMMENT ON TABLE apptacc IS 'Appointment code access by provider type';
COMMENT ON COLUMN apptacc."Type" IS '0 = ProdType, 1 = Provider';
COMMENT ON COLUMN apptacc."Provider" IS 'if Type = 1, PRODUCER.Producer';
COMMENT ON COLUMN apptacc."ProdType" IS 'PRODTYPE.Code';
COMMENT ON COLUMN apptacc."ApptCode" IS 'APPTCODE.ApptCode';
COMMENT ON COLUMN apptacc."Access" IS '0 = No, 1 = Yes, 2 = Limited (some providers)';


CREATE  TABLE apptcode (
  "ApptCode" character(15) NOT NULL,
  "Name" character(63),
  "Unit0" numeric(10,0),
  "Unit1" numeric(10,0),
  "Unit2" numeric(10,0),
  "Unit3" numeric(10,0),
  "Unit4" numeric(10,0),
  "Unit5" numeric(10,0),
  "Time0" numeric(10,0),
  "Time1" numeric(10,0),
  "Time2" numeric(10,0),
  "Time3" numeric(10,0),
  "Time4" numeric(10,0),
  "Time5" numeric(10,0),
  "Estimate" numeric,
  "IsRecall" numeric(5,0),
  "IsAsap" numeric(5,0),
  "IsConfirm" numeric(5,0),
  "IsShortNotice" numeric(5,0),
  "Discipline" character(6),
  "DefaultReason" character(30),
  "Inactive" numeric(5,0),
  "PrimaryProvider" numeric(5,0),
  "SecondProvider" numeric(5,0),
  "AssignProvider" numeric(5,0),
  "AssignSecondProvider" numeric(5,0),
  "IsNewPatientExam" numeric(5,0),
  "IsHygiene" numeric(5,0),
  "SecondProvRequired" numeric(5,0),
  "AssignEvent" numeric(5,0),
  "CodeType" numeric(5,0),
  "EnforceBookingOrder" numeric(5,0),
  "PrimaryExclusive" numeric(5,0),
  "SecondaryExclusive" numeric(5,0),
  CONSTRAINT apptcode_primary PRIMARY KEY ("ApptCode")
) ;
COMMENT ON TABLE apptcode IS 'Appointment codes.';
COMMENT ON COLUMN apptcode."Unit5" IS 'Appt Doctor Unit3 (for production details)';
COMMENT ON COLUMN apptcode."Unit4" IS 'Appt Assistant Unit3 (for production details)';
COMMENT ON COLUMN apptcode."Unit3" IS 'Appt Doctor Unit2 (for production details)';
COMMENT ON COLUMN apptcode."Unit2" IS 'Appt Assistant Unit2 (for production details)';
COMMENT ON COLUMN apptcode."Unit1" IS 'Appt Doctor Unit1 (for production details)';
COMMENT ON COLUMN apptcode."Unit0" IS 'Appt Assistant Unit1 (for production details)';
COMMENT ON COLUMN apptcode."Time5" IS 'Appt Doctor Time3 in minutes (for production details)';
COMMENT ON COLUMN apptcode."Time4" IS 'Appt Assistant Time3 in minutes (for production details)';
COMMENT ON COLUMN apptcode."Time3" IS 'Appt Doctor Time2 in minutes (for production details)';
COMMENT ON COLUMN apptcode."Time2" IS 'Appt Assistant Time2 in minutes (for production details)';
COMMENT ON COLUMN apptcode."Time1" IS 'Appt Doctor Time1 in minutes (for production details)';
COMMENT ON COLUMN apptcode."Time0" IS 'Appt Assistant Time1 in minutes (for production details)';
COMMENT ON COLUMN apptcode."SecondaryExclusive" IS 'Secondary provider is exclusive? (0=No, 1=Yes)';
COMMENT ON COLUMN apptcode."SecondProvider" IS '0 = none specified, 1 = Dentist / Student, 2 = Hygienist / "CDA", 3 = Other';
COMMENT ON COLUMN apptcode."SecondProvRequired" IS '0 = No, 1 = Yes';
COMMENT ON COLUMN apptcode."PrimaryProvider" IS '0 = none specified, 1 = Dentist / Student, 2 = Hygienist / "CDA", 3 = Other';
COMMENT ON COLUMN apptcode."PrimaryExclusive" IS 'Primary exclusive time? (0=No, 1=Yes [Appt Time], 2=Yes [Prov Time])';
COMMENT ON COLUMN apptcode."Name" IS 'Description of the appointment type.';
COMMENT ON COLUMN apptcode."IsShortNotice" IS 'DEPRECATED';
COMMENT ON COLUMN apptcode."IsRecall" IS 'appointment type is for a recall? (0 = No, 1 = Yes)';
COMMENT ON COLUMN apptcode."IsNewPatientExam" IS '0=No, 1=Yes';
COMMENT ON COLUMN apptcode."IsHygiene" IS 'is the appt code for hygiene appts (0=n, 1=y)';
COMMENT ON COLUMN apptcode."IsConfirm" IS 'DEPRECATED';
COMMENT ON COLUMN apptcode."IsAsap" IS 'DEPRECATED';
COMMENT ON COLUMN apptcode."Inactive" IS 'Code is inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN apptcode."Estimate" IS 'Estimated charge for/cost of appt type';
COMMENT ON COLUMN apptcode."EnforceBookingOrder" IS 'Enforce booking order for appointment code? (0=No, 1=Yes)';
COMMENT ON COLUMN apptcode."Discipline" IS 'Discipline of the appt type, ptr to DISCIPL.Discipline';
COMMENT ON COLUMN apptcode."DefaultReason" IS 'Default reason for the appointment';
COMMENT ON COLUMN apptcode."CodeType" IS '0 – regular, 1 – Recall, 2 – Hygiene Recall, 3 – New Patient Exam, 4 – New Patient Exam using Hygiene Time';
COMMENT ON COLUMN apptcode."AssignSecondProvider" IS '0=No, 1=Prompt (as now), 2=Auto-assign (if primary), 3=Auto-assign';
COMMENT ON COLUMN apptcode."AssignProvider" IS '0=No, 1=Prompt (as now), 2=Auto-assign';
COMMENT ON COLUMN apptcode."AssignEvent" IS '0 = N/A, 1 = Patient Check-In, 2 = Scheduling Appt';
COMMENT ON COLUMN apptcode."ApptCode" IS 'Primary key, code that indicates the appointment type or length.';


CREATE  TABLE appthis (
  "ApptHis" numeric(10,0) NOT NULL,
  "Appointment" numeric(10,0),
  "Date" timestamp without time zone,
  "Chair" numeric(10,0),
  "Patient" numeric(10,0),
  "Type" numeric(5,0),
  "Producer" character(10),
  "From" numeric(10,0),
  "CreateDate" timestamp without time zone,
  "Code" character(15),
  "Unit0" numeric(10,0),
  "Unit1" numeric(10,0),
  "Unit2" numeric(10,0),
  "Unit3" numeric(10,0),
  "Unit4" numeric(10,0),
  "Unit5" numeric(10,0),
  "Time0" numeric(10,0),
  "Time1" numeric(10,0),
  "Time2" numeric(10,0),
  "Time3" numeric(10,0),
  "Time4" numeric(10,0),
  "Time5" numeric(10,0),
  "Estimate" numeric,
  "Class" character(15),
  "ModifiedDateTime" timestamp without time zone,
  "User" numeric(10,0),
  "IsRecall" numeric(5,0),
  "IsAsap" numeric(5,0),
  "IsConfirm" numeric(5,0),
  "IsShortNotice" numeric(5,0),
  "Status" numeric(5,0),
  "Request" numeric(10,0),
  "Rank" numeric(10,0),
  "UStatus" character(6),
  "Reserve" numeric(10,0),
  "OrthoStage" character(6),
  "IsOrtho" numeric(5,0),
  "Cancel" character(6),
  "Reason" character varying(200),
  "Assistant" character(10),
  "Clinic" numeric(10,0),
  "IsRequest" numeric(5,0),
  "Instructor" numeric(10,0),
  "IsNew" numeric(5,0),
  "CheckInTime" numeric(10,0),
  "TimeSeated" numeric(10,0),
  "Held" numeric(5,0),
  "SignInTime" numeric(10,0),
  "SecondaryMCBFlag" numeric(5,0),
  "NotBeforeDate" timestamp without time zone,
  "PtEstimateStatus" numeric(5,0),
  "PtEstimate" numeric,
  "BookingOrder" numeric(10,0),
  "ExpertAdd" numeric(5,0),
  "CheckOutDate" timestamp without time zone,
  "CheckOutTime" numeric(10,0),
  "PrimaryExclusive" numeric(5,0),
  CONSTRAINT appthis_primary PRIMARY KEY ("ApptHis")
) ;
CREATE INDEX IF NOT EXISTS appthis_appointment ON appthis USING btree ("Appointment") TABLESPACE pg_default;
COMMENT ON TABLE appthis IS 'Appointment History';
COMMENT ON COLUMN appthis."User" IS 'User ID of entry user, ptr to USERS.User';
COMMENT ON COLUMN appthis."Unit5" IS 'Appt Doctor Unit3 (for production details)';
COMMENT ON COLUMN appthis."Unit4" IS 'Appt Assistant Unit3 (for production details)';
COMMENT ON COLUMN appthis."Unit3" IS 'Appt Doctor Unit2 (for production details)';
COMMENT ON COLUMN appthis."Unit2" IS 'Appt Assistant Unit2 (for production details)';
COMMENT ON COLUMN appthis."Unit1" IS 'Appt Doctor Unit1 (for production details)';
COMMENT ON COLUMN appthis."Unit0" IS 'Appt Assistant Unit1 (for production details)';
COMMENT ON COLUMN appthis."UStatus" IS 'User-definable appt status, ptr to STATUS.Status';
COMMENT ON COLUMN appthis."Type" IS 'Status of Appt (0=Active, 1=Checked-in, 2=Checked-out, 3=Pending, 4=Reschedule status, 5=Failed, 6=Cancelled, 7=Deleted, 8=Requested, 9=Ortho Request, 10=Planned)';
COMMENT ON COLUMN appthis."TimeSeated" IS 'Actual time that the patient sits in chair';
COMMENT ON COLUMN appthis."Time5" IS 'Appt Doctor Time3 in minutes (for production details)';
COMMENT ON COLUMN appthis."Time4" IS 'Appt Assistant Time3 in minutes (for production details)';
COMMENT ON COLUMN appthis."Time3" IS 'Appt Doctor Time2 in minutes (for production details)';
COMMENT ON COLUMN appthis."Time2" IS 'Appt Assistant Time2 in minutes (for production details)';
COMMENT ON COLUMN appthis."Time1" IS 'Appt Doctor Time1 in minutes (for production details)';
COMMENT ON COLUMN appthis."Time0" IS 'Appt Assistant Time1 in minutes (for production details)';
COMMENT ON COLUMN appthis."Status" IS 'Appt is Deleted? (0 = No, 2=Yes)';
COMMENT ON COLUMN appthis."SignInTime" IS 'Time (minutes since midnight) that the patient signed in for the appointment';
COMMENT ON COLUMN appthis."SecondaryMCBFlag" IS '0=N/A(if no 2nd provider), 1=Assistant Time, 2=Primary Provider Time, 3=Total Time';
COMMENT ON COLUMN appthis."Reserve" IS 'ID of the Chair reservation that the appt is made in, ptr to RESERVE.Reserve';
COMMENT ON COLUMN appthis."Request" IS 'ID of the Chart Request that is related to the appt, ptr to REQUEST.Request';
COMMENT ON COLUMN appthis."Reason" IS 'Reason/note for the appointment - pts to CANCEL.Description';
COMMENT ON COLUMN appthis."Rank" IS 'Rating of the importance / urgency of the appointment, ptr to CLASS.Rank';
COMMENT ON COLUMN appthis."PtEstimateStatus" IS 'Patient estimate status (0=no estimate, 1=estimated)';
COMMENT ON COLUMN appthis."PtEstimate" IS 'Patient portion of the estimate amount for this appt';
COMMENT ON COLUMN appthis."Producer" IS 'Primary appointment provider, ptr to PRODUCER.Producer';
COMMENT ON COLUMN appthis."PrimaryExclusive" IS 'Primary exclusive time? (0=No, 1=Yes [Appt Time], 2=Yes [Prov Time])';
COMMENT ON COLUMN appthis."Patient" IS 'Patient that the appointment is for, ptr to PATIENT.Patient';
COMMENT ON COLUMN appthis."OrthoStage" IS 'If IsOrtho=1, the ortho stage for this appointment. Ptr to STAGE.Code.';
COMMENT ON COLUMN appthis."NotBeforeDate" IS 'For Type 8 and 10, appointment must be booked to occur on or after this date';
COMMENT ON COLUMN appthis."ModifiedDateTime" IS 'Date/time of most recent modification. ';
COMMENT ON COLUMN appthis."IsShortNotice" IS 'Appointment was made on short notice? (0 = No, 1 = Yes).';
COMMENT ON COLUMN appthis."IsRequest" IS 'Is this an appointment request? (0 = No, 1 = Yes)';
COMMENT ON COLUMN appthis."IsRecall" IS 'Appointment is for a recall? (0 = No, 1 = Yes).';
COMMENT ON COLUMN appthis."IsOrtho" IS 'Ortho appointment? (0 = No, 1 = Yes).';
COMMENT ON COLUMN appthis."IsNew" IS 'Is this a new appointment request? (0 = No alert, 1=Need to alert group mgr (staff), 2=Need to alert student (provider), 3=Need to alert both parties, 4=Edit mode - not new, 5=Need to acknowledge group manager -staff - in edit mode, 6= Need to acknowledge student provider in edit mode, 7=Need to acknowledge both parties in edit mode)';
COMMENT ON COLUMN appthis."IsConfirm" IS 'Appointment has been confirmed? (0 = No, 1 = Yes).';
COMMENT ON COLUMN appthis."IsAsap" IS 'Appointment needs to be done ASAP (Emergency)? (0 = No, 1 = Yes).';
COMMENT ON COLUMN appthis."Instructor" IS 'If IsRequest=1, ID code of the instructor for the appointment request. Ptr to USERS.User.';
COMMENT ON COLUMN appthis."Held" IS 'Flag to indicate whether an appointment has been successfully added. 0 = Added successfully, 1 = Not yet added';
COMMENT ON COLUMN appthis."From" IS 'Time that appointment starts, in minutes from midnight. ';
COMMENT ON COLUMN appthis."ExpertAdd" IS 'Was appointment booked with the Expert? (0=No, 1=Yes)';
COMMENT ON COLUMN appthis."Estimate" IS 'Estimated charge for/cost of appt';
COMMENT ON COLUMN appthis."Date" IS 'Date of the appointment';
COMMENT ON COLUMN appthis."CreateDate" IS 'Date that the appointment record was created. ';
COMMENT ON COLUMN appthis."Code" IS 'Appointment code for this appointment, ptr to APPTCODE.Apptcode';
COMMENT ON COLUMN appthis."Clinic" IS 'If IsRequest=1 - requested clinic for the appointment, ptr to CLINIC.Clinic';
COMMENT ON COLUMN appthis."Class" IS 'Discipline of the appt, ptr to CLASS.Class';
COMMENT ON COLUMN appthis."CheckOutTime" IS 'Time that the appointment was checked out (in minutes from midnight).';
COMMENT ON COLUMN appthis."CheckOutDate" IS 'Date that the appointment was checked out.';
COMMENT ON COLUMN appthis."CheckInTime" IS 'Check in time in minutes from midnight';
COMMENT ON COLUMN appthis."Chair" IS 'Chair that the appointment is scheduled in, ptr to CHAIR.Chair';
COMMENT ON COLUMN appthis."Cancel" IS 'Appt Cancellation code, ptr to CANCEL.Cancel';
COMMENT ON COLUMN appthis."BookingOrder" IS 'Internal number to determine appointment booking order';
COMMENT ON COLUMN appthis."Assistant" IS 'Secondary appointment provider/assistant. Ptr to PRODUCER.Producer.';
COMMENT ON COLUMN appthis."ApptHis" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN appthis."Appointment" IS 'Appointment that this history is for, ptr to APPOINT.Appointment.';


CREATE  TABLE apptind (
  "ApptInd" character(6) NOT NULL,
  "Description" character varying(30),
  "FunctionName" character varying(50),
  "Color" numeric(10,0),
  "ForTodayOnly" numeric(5,0),
  "Active" numeric(5,0),
  CONSTRAINT apptind_primary PRIMARY KEY ("ApptInd")
) ;
COMMENT ON TABLE apptind IS 'Appointment indicator records';
COMMENT ON COLUMN apptind."FunctionName" IS 'Functions associated with appointment indicator';
COMMENT ON COLUMN apptind."ForTodayOnly" IS 'Calculate for today only: 0=No, 1=Yes, X=2..100 (Today and the next X-1 days)';
COMMENT ON COLUMN apptind."Description" IS 'Description for appointment indicator (example: “X-rays Required today”)';
COMMENT ON COLUMN apptind."Color" IS 'RGB Color values';
COMMENT ON COLUMN apptind."ApptInd" IS 'Code (example: XRAY)';
COMMENT ON COLUMN apptind."Active" IS '0=No, 1=Yes';


CREATE  TABLE apptinit (
  "ApptInd" character(6) NOT NULL,
  "Value" numeric(5,0) NOT NULL,
  "Description" character varying(50),
  "Symbol" character(1),
  "Inverted" numeric(5,0),
  CONSTRAINT apptinit_primary PRIMARY KEY ("ApptInd", "Value")
) ;
COMMENT ON TABLE apptinit IS 'Appointment inidicator values';
COMMENT ON COLUMN apptinit."Value" IS 'Numeric return value';
COMMENT ON COLUMN apptinit."Symbol" IS 'Symbol to represent appointment indicator item (example: X)';
COMMENT ON COLUMN apptinit."Inverted" IS 'Color inverted: 0=No, 1=Yes ';
COMMENT ON COLUMN apptinit."Description" IS 'Description of initial appointment description';
COMMENT ON COLUMN apptinit."ApptInd" IS 'Appointment Indicator Code, ptr to APPTIND.ApptInd';


CREATE  TABLE apptprov (
  "Appointment" numeric(10,0) NOT NULL,
  "Provider" character(10) NOT NULL,
  CONSTRAINT apptprov_primary PRIMARY KEY ("Appointment", "Provider")
) ;
CREATE INDEX IF NOT EXISTS apptprov_provider ON apptprov USING btree ("Provider") TABLESPACE pg_default;
COMMENT ON TABLE apptprov IS 'Additonal providers/attendees for a given appointment.';
COMMENT ON COLUMN apptprov."Provider" IS 'Provider ID, ptr to PRODUCER.Producer';
COMMENT ON COLUMN apptprov."Appointment" IS 'Appointment ID, ptr to APPOINT.Appointment';


CREATE  TABLE apptrecl (
  "Appointment" numeric(10,0) NOT NULL,
  "PtRecall" numeric(10,0) NOT NULL,
  CONSTRAINT apptrecl_primary PRIMARY KEY ("Appointment", "PtRecall")
) ;
CREATE INDEX IF NOT EXISTS apptrecl_ptrecall ON apptrecl USING btree ("PtRecall") TABLESPACE pg_default;
COMMENT ON TABLE apptrecl IS 'Link table between appointments and recalls';
COMMENT ON COLUMN apptrecl."PtRecall" IS 'PTRECALL.Id';
COMMENT ON COLUMN apptrecl."Appointment" IS 'Points to APPOINT.Appointment';


CREATE  TABLE apptrx (
  "AppTrx" numeric(10,0) NOT NULL,
  "Appointment" numeric(10,0),
  "Type" numeric(5,0),
  "Id" numeric(10,0),
  "Treatment" numeric(5,0),
  "Procedure" character(7),
  "Date" timestamp without time zone,
  CONSTRAINT apptrx_primary PRIMARY KEY ("AppTrx")
) ;
CREATE INDEX IF NOT EXISTS apptrx_appointment ON apptrx USING btree ("Appointment") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS apptrx_apptrxkey ON apptrx USING btree ("Appointment", "Type", "Id", "Treatment") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS apptrx_trxkey ON apptrx USING btree ("Type", "Id", "Treatment") TABLESPACE pg_default;
COMMENT ON TABLE apptrx IS 'Appointment Transaction (Treatment tied to an appt)';
COMMENT ON COLUMN apptrx."Type" IS 'Ptr to TRX.Type of treatment';
COMMENT ON COLUMN apptrx."Treatment" IS 'Points to TRX.Treatment';
COMMENT ON COLUMN apptrx."Procedure" IS 'Procedure code of the treatment, ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN apptrx."Id" IS 'Ptr to TRX.Id';
COMMENT ON COLUMN apptrx."Date" IS 'Date (Julian format) of this entry.';
COMMENT ON COLUMN apptrx."Appointment" IS 'Ptr to APPOINT.Appointment';
COMMENT ON COLUMN apptrx."AppTrx" IS 'Primary key, Internal ID (from sequence).';


CREATE  TABLE apseries (
  "ApSeries" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "SeriesNumber" numeric(5,0),
  "Description" character varying(30),
  "BookingOrder" numeric(10,0),
  CONSTRAINT apseries_primary PRIMARY KEY ("ApSeries")
) ;
CREATE INDEX IF NOT EXISTS apseries_patientseriesnumber ON apseries USING btree ("Patient", "SeriesNumber") TABLESPACE pg_default;
COMMENT ON TABLE apseries IS 'Appointment Series';
COMMENT ON COLUMN apseries."SeriesNumber" IS 'Identifier of appointment series for this patient';
COMMENT ON COLUMN apseries."Patient" IS 'Patient ID, ptr to PATIENT.Patient';
COMMENT ON COLUMN apseries."Description" IS 'Description of appointment series';
COMMENT ON COLUMN apseries."BookingOrder" IS 'Internal number used to determine booking order';
COMMENT ON COLUMN apseries."ApSeries" IS 'Primary key, internal ID from sequence';


CREATE  TABLE apserit (
  "ApSeries" numeric(10,0) NOT NULL,
  "Appointment" numeric(10,0) NOT NULL,
  "Order" numeric(5,0),
  "Interval" numeric(5,0),
  "IntervalType" numeric(5,0),
  "Note" character varying(4000),
  CONSTRAINT apserit_primary PRIMARY KEY ("ApSeries", "Appointment")
) ;
COMMENT ON TABLE apserit IS 'Appointments that are part of an Appointment Series';
COMMENT ON COLUMN apserit."Order" IS 'Order of the appointment within the series (starts at 1)';
COMMENT ON COLUMN apserit."Note" IS 'Description of this appointment within the series';
COMMENT ON COLUMN apserit."IntervalType" IS 'Type of interval (0=days, 1=weeks, 2=months)';
COMMENT ON COLUMN apserit."Interval" IS 'Numeric value of interval';
COMMENT ON COLUMN apserit."Appointment" IS 'Primary key, Appointment ID, ptr to APPOINT.Appointment';
COMMENT ON COLUMN apserit."ApSeries" IS 'Primary key, Appointment Series ID, ptr to APSERIES.ApSeries';


CREATE  TABLE ar_recon_saved_data_dtl (
  "Batch" numeric(10,0) NOT NULL,
  "History" numeric(10,0),
  "HistoryType" numeric(5,0),
  "OrigRecNo" numeric(10,0),
  "Type" numeric(5,0),
  "Id" numeric(10,0),
  "Treatment" numeric(5,0),
  "ModifiedDate" timestamp without time zone,
  "TreatmentDate" timestamp without time zone,
  "Producer" character(10),
  "Procedure" character(7),
  "Patient" numeric(10,0),
  "Family" numeric(10,0),
  "Code" character(6),
  "Description" character varying(60),
  "Company1" character(6),
  "ReportDepartment" character(6),
  "ReportDiscipline" character(15),
  "ReportProcedure" character(7),
  "ReportPractice" numeric(5,0),
  "ReportClaimDoctor" character(10),
  "ReportLocation" character(6),
  "ReportEntryUser" numeric(10,0),
  "ReportAppUser" numeric(10,0),
  "ReportCustom1" character(6),
  "ReportCustom2" character(6),
  "ReportProducer" character(10),
  "ReportTypeCode" character(1),
  "ReportPGroup" character(6),
  "ReportYear" numeric(10,0),
  "ReportCustomCode1" character(6),
  "ReportCustomCode2" character(6),
  "ReportCustomCode3" character(6),
  "ReportCustomCode4" character(6),
  "ReportCustomCode5" character(6),
  "ReportCustomCode6" character(6),
  "ReportCustomCode7" character(6),
  "ReportCustomCode8" character(6),
  "ReportCustomCode9" character(6),
  "ReportCustomCode10" character(6),
  "ReportGroupBy1" numeric,
  "ReportGroupBy1Description" character(23),
  "ReportGroupBy2" numeric,
  "ReportGroupBy2Description" character(23),
  "ReportFromDate" timestamp without time zone,
  "ReportToDate" timestamp without time zone,
  "ReportIsDetailed" numeric,
  "ReportIncludeUnallocated" numeric,
  "ReportHistoryTypeDescription" character(30),
  "ReportOldTotal" numeric,
  "ReportTotal" numeric,
  "ReportTotalChange" numeric,
  "ReportOldInsTotal" numeric,
  "ReportInsTotal" numeric,
  "ReportInsTotalChange" numeric,
  "ReportOldPayed" numeric,
  "ReportPayed" numeric,
  "ReportPayedChange" numeric,
  "ReportOldInsPayed" numeric,
  "ReportInsPayed" numeric,
  "ReportInsPayedChange" numeric,
  "ReportOldPtAdj" numeric,
  "ReportPtAdj" numeric,
  "ReportPtAdjChange" numeric,
  "ReportOldInsAdj" numeric,
  "ReportInsAdj" numeric,
  "ReportInsAdjChange" numeric,
  "ReportOldInsTransfer" numeric,
  "ReportInsTransfer" numeric,
  "ReportInsTransferChange" numeric,
  "PreviousHistory" numeric(10,0)
) ;
CREATE INDEX IF NOT EXISTS ar_recon_saved_data_dtl_idx1 ON ar_recon_saved_data_dtl USING btree ("Batch") TABLESPACE pg_default;
COMMENT ON TABLE ar_recon_saved_data_dtl IS 'A/R reconciliation report data details.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."Type" IS 'Transaction record type.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."TreatmentDate" IS 'The date that the treatment was performed/planned for.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."Treatment" IS 'Transaction line number within claim.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportYear" IS 'Provider Year. Used for grouping by.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportTypeCode" IS 'Provider Type. Used for grouping by.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportTotalChange" IS 'Change in the total amount during the reporting period.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportTotal" IS 'Total amount of the transaction during the reporting period.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportToDate" IS 'Ending date that the report is being run for.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportPtAdjChange" IS 'Change in the total amount of all patient adjustments allocated to this transaction during the reporting period.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportPtAdj" IS 'Total amount of all patient adjustments allocated to this transaction during the reporting period.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportProducer" IS 'Provider Code. Used for grouping by.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportProcedure" IS 'Tx Procedure. Used for grouping by.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportPractice" IS 'Tx Practice. Used for grouping by.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportPayedChange" IS 'Change in the total amount of all patient payments allocated to this transaction during the reporting period.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportPayed" IS 'Total amount of all patient payments allocated to this transaction during the reporting period.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportPGroup" IS 'Provider Group. Used for grouping by.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportOldTotal" IS 'Total amount of the transaction prior to the reporting period start date.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportOldPtAdj" IS 'Total amount of all patient adjustments allocated to this transaction prior to the reporting period start date.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportOldPayed" IS 'Total amount of all patient payments allocated to this transaction prior to the reporting period start date.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportOldInsTransfer" IS 'Total amount transferred from insurance to patient prior to the reporting period start date.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportOldInsTotal" IS 'Insurance portion of the total amount prior to the reporting period start date.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportOldInsPayed" IS 'Total amount of all insurance payments allocated to this transaction prior to the reporting period start date.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportOldInsAdj" IS 'Total amount of all insurance adjustments allocated to this transaction prior to the reporting period start date.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportLocation" IS 'Tx Facility. Used for grouping by.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportIsDetailed" IS 'Flag to indicate if the report ran without details (0) or with details (1).';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportInsTransferChange" IS 'Change in the total amount transferred from insurance to patient during the reporting period.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportInsTransfer" IS 'Total amount transferred from insurance to patient during the reporting period.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportInsTotalChange" IS 'Change in the insurance portion of the total amount during the reporting period.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportInsTotal" IS 'Insurance portion of the total amount during the reporting period.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportInsPayedChange" IS 'Change in the total amount of all insurance payments allocated to this transaction during the reporting period.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportInsPayed" IS 'Total amount of all insurance payments allocated to this transaction during the reporting period.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportInsAdjChange" IS 'Change in the total amount of all insurance adjustments allocated to this transaction during the reporting period.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportInsAdj" IS 'Total amount of all insurance adjustments allocated to this transaction during the reporting period.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportIncludeUnallocated" IS 'Flag to indicate if the report ran without the unallocated amounts (0) or with the unallocated amounts (1).';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportHistoryTypeDescription" IS 'Description of the type of history.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportGroupBy2Description" IS 'Secondary group by description.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportGroupBy2" IS 'Secondary numeric group by code that the report is being run for.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportGroupBy1Description" IS 'Primary group by description.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportGroupBy1" IS 'Primary numeric group by code that the report is being run for.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportFromDate" IS 'Starting date that the report is being run for.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportEntryUser" IS 'Tx Entry User. Used for grouping by.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportDiscipline" IS 'Tx Discipline. Used for grouping by.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportDepartment" IS 'Department code that the record belongs to.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportCustomCode9" IS 'Patient Custom Code 9. Used for grouping by.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportCustomCode8" IS 'Patient Custom Code 8. Used for grouping by.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportCustomCode7" IS 'Patient Custom Code 7. Used for grouping by.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportCustomCode6" IS 'Patient Custom Code 6. Used for grouping by.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportCustomCode5" IS 'Patient Custom Code 5. Used for grouping by.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportCustomCode4" IS 'Patient Custom Code 4. Used for grouping by.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportCustomCode3" IS 'Patient Custom Code 3. Used for grouping by.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportCustomCode2" IS 'Patient Custom Code 2. Used for grouping by.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportCustomCode10" IS 'Patient Custom Code 10. Used for grouping by.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportCustomCode1" IS 'Patient Custom Code 1. Used for grouping by.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportCustom2" IS 'Tx Notes 2. Used for grouping by.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportCustom1" IS 'Tx Notes 1. Used for grouping by.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportClaimDoctor" IS 'Tx Fee Guide/Billing Doctor. Used for grouping by.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ReportAppUser" IS 'Tx Approving Instructor. Used for grouping by.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."Producer" IS 'Producer Id. Pointer to PRODUCER."Producer".';
COMMENT ON COLUMN ar_recon_saved_data_dtl."Procedure" IS 'Procedure code. Pointer to PROCEDURE."Procedure".';
COMMENT ON COLUMN ar_recon_saved_data_dtl."PreviousHistory" IS 'Previous History Id of the record with the same OrigRecNo. Pointer to HISTORY."History".';
COMMENT ON COLUMN ar_recon_saved_data_dtl."Patient" IS 'Patient Id. Pointer to PATIENT."Patient".';
COMMENT ON COLUMN ar_recon_saved_data_dtl."OrigRecNo" IS 'Original record number. Pointer to HISTORY."OrigRecNo".';
COMMENT ON COLUMN ar_recon_saved_data_dtl."ModifiedDate" IS 'The date and time that the transaction was last modified.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."Id" IS 'Unique Id of the transaction record.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."HistoryType" IS 'Type of history.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."History" IS 'History Id. Pointer to HISTORY."History".';
COMMENT ON COLUMN ar_recon_saved_data_dtl."Family" IS 'Family Id. Pointer to PATIENT."Family".';
COMMENT ON COLUMN ar_recon_saved_data_dtl."Description" IS 'Description of the transaction.';
COMMENT ON COLUMN ar_recon_saved_data_dtl."Company1" IS 'Primary insurance company. Pointer to INSURANC."Company".';
COMMENT ON COLUMN ar_recon_saved_data_dtl."Code" IS 'Office charge, payment or adjustment code, depending on "Type".';
COMMENT ON COLUMN ar_recon_saved_data_dtl."Batch" IS 'Id code to identify the batch. Points to AR_RECON_SAVED_DATA_HDR.Batch';


CREATE  TABLE ar_recon_saved_data_hdr (
  "Batch" numeric(10,0) NOT NULL DEFAULT 0,
  "ExpiryDate" timestamp without time zone NOT NULL,
  "FirstRunDate" timestamp without time zone NOT NULL,
  "LastRunDate" timestamp without time zone NOT NULL,
  "Department" character(6) NOT NULL,
  "FromDate" timestamp without time zone NOT NULL,
  "ToDate" timestamp without time zone NOT NULL,
  "GroupBy1" numeric(10,0) NOT NULL DEFAULT 0,
  "GroupBy1Description" character(23) NOT NULL,
  "GroupBy2" numeric(10,0) NOT NULL DEFAULT 0,
  "GroupBy2Description" character(23) NOT NULL,
  "IsDetailed" numeric(10,0) NOT NULL DEFAULT 0,
  "IncludeUnallocated" numeric(10,0) NOT NULL DEFAULT 0,
  "Patient" numeric(10,0) NOT NULL DEFAULT 0,
  "OrigRecNo" numeric(10,0) NOT NULL DEFAULT 0,
  "BeginningBalance" numeric NOT NULL DEFAULT 0,
  "PeriodBalance" numeric NOT NULL DEFAULT 0,
  "EndingBalance" numeric NOT NULL DEFAULT 0,
  "ReportType" numeric(10,0) NOT NULL DEFAULT 0,
  "StartDateTime" timestamp without time zone,
  "EndDateTime" timestamp without time zone
) ;
CREATE UNIQUE INDEX IF NOT EXISTS ar_recon_saved_data_hdr_idx1 ON ar_recon_saved_data_hdr USING btree ("Batch") TABLESPACE pg_default;
CREATE UNIQUE INDEX IF NOT EXISTS ar_recon_saved_data_hdr_idx2 ON ar_recon_saved_data_hdr USING btree ("Department", "FromDate", "ToDate", "GroupBy1", "GroupBy2", "IncludeUnallocated", "ReportType", "Batch") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ar_recon_saved_data_hdr_idx3 ON ar_recon_saved_data_hdr USING btree ("Department", "ToDate") TABLESPACE pg_default;
COMMENT ON TABLE ar_recon_saved_data_hdr IS 'A/R reconciliation report data header';
COMMENT ON COLUMN ar_recon_saved_data_hdr."ToDate" IS 'Ending date that the report is being run for.';
COMMENT ON COLUMN ar_recon_saved_data_hdr."StartDateTime" IS 'Date and Time when the procedure that created this record and all associated detail records was being called.';
COMMENT ON COLUMN ar_recon_saved_data_hdr."ReportType" IS 'Report Type (0 - A/R, 1 - Allocations).';
COMMENT ON COLUMN ar_recon_saved_data_hdr."PeriodBalance" IS 'Balance amount change during the reporting period.';
COMMENT ON COLUMN ar_recon_saved_data_hdr."Patient" IS 'Particular patient Id that the report is being run for (0 = all patients). Needed for troubleshooting.';
COMMENT ON COLUMN ar_recon_saved_data_hdr."OrigRecNo" IS 'Particular OrigRecNo that the report is being run for (0 = all OrigRecNo). Needed for troubleshooting.';
COMMENT ON COLUMN ar_recon_saved_data_hdr."LastRunDate" IS 'Date that the report was last ran using exactly the same parameter.';
COMMENT ON COLUMN ar_recon_saved_data_hdr."IsDetailed" IS 'Flag to indicate if the report ran without details (0) or with details (1).';
COMMENT ON COLUMN ar_recon_saved_data_hdr."IncludeUnallocated" IS 'Flag to indicate if the report ran without the unallocated amounts (0) or with the unallocated amounts (1).';
COMMENT ON COLUMN ar_recon_saved_data_hdr."GroupBy2Description" IS 'Secondary group by description.';
COMMENT ON COLUMN ar_recon_saved_data_hdr."GroupBy2" IS 'Secondary numeric group by code that the report is being run for.';
COMMENT ON COLUMN ar_recon_saved_data_hdr."GroupBy1Description" IS 'Primary group by description.';
COMMENT ON COLUMN ar_recon_saved_data_hdr."GroupBy1" IS 'Primary numeric group by code that the report is being run for.';
COMMENT ON COLUMN ar_recon_saved_data_hdr."FromDate" IS 'Starting date that the report is being run for.';
COMMENT ON COLUMN ar_recon_saved_data_hdr."FirstRunDate" IS 'Date that the report was first ran using exactly the same parameters.';
COMMENT ON COLUMN ar_recon_saved_data_hdr."ExpiryDate" IS 'Expiry Date of the record. Any expiry date less than current/system date will be deleted.';
COMMENT ON COLUMN ar_recon_saved_data_hdr."EndingBalance" IS 'Resulting ending balance after the report ran.';
COMMENT ON COLUMN ar_recon_saved_data_hdr."EndDateTime" IS 'Date and Time when the procedure that created this record and all associated detail records was completed and about to return.';
COMMENT ON COLUMN ar_recon_saved_data_hdr."Department" IS 'Department code that the report is being run for.';
COMMENT ON COLUMN ar_recon_saved_data_hdr."BeginningBalance" IS 'Resulting beginning balance after the report ran.';
COMMENT ON COLUMN ar_recon_saved_data_hdr."Batch" IS 'Id code to identify the batch.';


CREATE  TABLE ataccess (
  "AtTab" numeric(10,0) NOT NULL,
  "SLevel" numeric(10,0) NOT NULL,
  "Access" numeric(5,0),
  CONSTRAINT ataccess_primary PRIMARY KEY ("AtTab", "SLevel")
) ;
COMMENT ON TABLE ataccess IS 'Attachment Tab Access';
COMMENT ON COLUMN ataccess."SLevel" IS 'Primary key component, the security level that access is being defined for. Ptr to SLEVEL.SLevel';
COMMENT ON COLUMN ataccess."AtTab" IS 'Primary key component, the attachment tab that access is being defined for. Ptr to ATTAB.AtTab';
COMMENT ON COLUMN ataccess."Access" IS 'Level has access? (0=No, 1=Read Only, 2=Full Access)';


CREATE  TABLE atdispl (
  "AtDisplay" numeric(10,0) NOT NULL,
  "ModuleID" numeric(5,0),
  "AtTab" numeric(10,0),
  CONSTRAINT atdispl_primary PRIMARY KEY ("AtDisplay")
) ;
COMMENT ON TABLE atdispl IS 'Attachment Display settings';
COMMENT ON COLUMN atdispl."ModuleID" IS 'Id to represent the attachments module (0=Pt Card, 1=Transactions, 2= TxPlan, 3= Chart, 4= Perio, 5= Ortho)';
COMMENT ON COLUMN atdispl."AtTab" IS 'Ptr to ATTAB.AtTab';
COMMENT ON COLUMN atdispl."AtDisplay" IS 'Internal Id from sequence';


CREATE  TABLE atsect (
  "AtSect" numeric(10,0) NOT NULL,
  "Order" numeric(5,0),
  "Description" character varying(20),
  "Inactive" numeric(5,0),
  CONSTRAINT atsect_primary PRIMARY KEY ("AtSect")
) ;
COMMENT ON TABLE atsect IS 'Patient attachment sections';
COMMENT ON COLUMN atsect."Order" IS 'Order to display ( 0...99) ';
COMMENT ON COLUMN atsect."Inactive" IS 'Inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN atsect."Description" IS 'Description of the attachment section.';
COMMENT ON COLUMN atsect."AtSect" IS 'Primary key, internal ID from sequence. ';


CREATE  TABLE attab (
  "AtTab" numeric(10,0) NOT NULL,
  "AtSect" numeric(10,0),
  "Order" numeric(5,0),
  "Description" character varying(20),
  "Type" numeric(5,0),
  "Inactive" numeric(5,0),
  "AvailablePa" numeric(5,0),
  CONSTRAINT attab_primary PRIMARY KEY ("AtTab")
) ;
CREATE INDEX IF NOT EXISTS attab_atsect ON attab USING btree ("AtSect") TABLESPACE pg_default;
COMMENT ON TABLE attab IS 'Patient attachemnt sub-tabs';
COMMENT ON COLUMN attab."Type" IS 'Type (0=Attachment, 1=Letter, 2=Consent, 3=EPR Form, 4=Summary of Care)';
COMMENT ON COLUMN attab."Order" IS 'Order (1...9)';
COMMENT ON COLUMN attab."Inactive" IS 'Inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN attab."Description" IS 'Description of the attachment tab.';
COMMENT ON COLUMN attab."AvailablePa" IS 'Available in PatientAccess? (0=No, 1=Yes)';
COMMENT ON COLUMN attab."AtTab" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN attab."AtSect" IS 'Attachment section that this tab is in, ptr to ATSECT.AtSect.';


CREATE  TABLE attype (
  "Type" numeric(5,0) NOT NULL,
  "Stored" numeric(5,0),
  "AtSect" numeric(10,0),
  "AtTab" numeric(10,0),
  CONSTRAINT attype_primary PRIMARY KEY ("Type")
) ;
COMMENT ON TABLE attype IS 'Attachment types';
COMMENT ON COLUMN attype."Type" IS 'Type (0=Receipt, 1=Statement, 2=Estimate, 3=Payment Plan, 4=Treatment Plan, 5=Treatment Plan Letter, 6=Summary of Care, 7=Invoice(Dutch only), 8=Invoice Letter(Dutch only))';
COMMENT ON COLUMN attype."Stored" IS 'Stored? (0 = No, 1 = Yes)';
COMMENT ON COLUMN attype."AtTab" IS 'Ptr to ATTAB.AtTab';
COMMENT ON COLUMN attype."AtSect" IS 'Ptr to ATSECT.AtSect';


CREATE  TABLE audithis (
  "Audit" numeric(10,0) NOT NULL,
  "Date" timestamp without time zone,
  "Time" numeric(10,0),
  "User" numeric(10,0),
  "StationId" numeric(10,0),
  "TableName" character varying(128),
  "HistoryType" numeric(5,0),
  CONSTRAINT audithis_primary PRIMARY KEY ("Audit")
) ;
CREATE INDEX IF NOT EXISTS audithis_date ON audithis USING btree ("User", "Date") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS audithis_user ON audithis USING btree ("User", "TableName") TABLESPACE pg_default;
COMMENT ON TABLE audithis IS 'Audit history table';
COMMENT ON COLUMN audithis."User" IS 'User Id of the entry user, ptr to USERS.User';
COMMENT ON COLUMN audithis."Time" IS 'Time this audit record was created';
COMMENT ON COLUMN audithis."TableName" IS 'Name of the table this audit record refers to';
COMMENT ON COLUMN audithis."StationId" IS 'Id code of the station from which this entry was made, ptr to STATION.StationId.';
COMMENT ON COLUMN audithis."HistoryType" IS 'Type of audit record (0=Unknown, 1=Add, 2=Edit, 4=Delete, 5=Rebill, 6=Merge, 7=Converted, 8=As At, 9=Edit Time)';
COMMENT ON COLUMN audithis."Date" IS 'Date this audit record was created';
COMMENT ON COLUMN audithis."Audit" IS 'Audit code to identify this audit history record, internal Id from sequence';


CREATE  TABLE auditlog (
  "Patient" numeric(10,0),
  "Date" timestamp without time zone,
  "User" numeric(10,0),
  "Station" numeric(10,0),
  "ActionType" numeric(5,0),
  "TableName" character varying(8),
  "PrimaryInfo" character varying(255),
  "AdditionalInfo" character varying(255),
  "HashValue" character varying(45),
  "SecondarySortKey" numeric(5,0),
  "Auditlog" character(28) NOT NULL,
  CONSTRAINT auditlog_primary PRIMARY KEY ("Auditlog")
) ;
CREATE INDEX IF NOT EXISTS auditlog_datekey ON auditlog USING btree ("Date") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS auditlog_patientkey ON auditlog USING btree ("Patient", "Date") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS auditlog_userkey ON auditlog USING btree ("User", "Date") TABLESPACE pg_default;
COMMENT ON TABLE auditlog IS 'Patient Clinical Auditing';
COMMENT ON COLUMN auditlog."User" IS 'User Id of the entry user, ptr to USERS.User';
COMMENT ON COLUMN auditlog."TableName" IS 'The table name that this log applies to';
COMMENT ON COLUMN auditlog."Station" IS 'Id code of the station from which this entry was made, ptr to STATION.StationId.';
COMMENT ON COLUMN auditlog."SecondarySortKey" IS 'Sort Value';
COMMENT ON COLUMN auditlog."PrimaryInfo" IS 'Specific type of information involved';
COMMENT ON COLUMN auditlog."Patient" IS 'Patient that this log is for, ptr to PATIENT.Patient';
COMMENT ON COLUMN auditlog."HashValue" IS 'SHA hash used to detect tampering of message contents.';
COMMENT ON COLUMN auditlog."Date" IS 'Date this audit record was created';
COMMENT ON COLUMN auditlog."Auditlog" IS 'Primary key, unique code to identify single entry of Auditlog.';
COMMENT ON COLUMN auditlog."AdditionalInfo" IS 'Additional Information related to what is being logged';
COMMENT ON COLUMN auditlog."ActionType" IS '0=Add, 1=Edit, 2=Del, 3=View, 4=Print, 5=Copy, 6=Preview';


CREATE  TABLE authlog (
  "AuthLog" numeric(10,0) NOT NULL,
  "AuthLogon" character(16),
  "AuthUser" numeric(10,0),
  "AuthType" character varying(32),
  "IsPINAttempt" numeric(5,0),
  "Action" numeric(5,0),
  "Date" timestamp without time zone,
  "Time" numeric(10,0),
  "LogonUser" numeric(10,0),
  "StationId" numeric(10,0),
  CONSTRAINT authlog_primary PRIMARY KEY ("AuthLog")
) ;
CREATE INDEX IF NOT EXISTS authlog_authlogon ON authlog USING btree ("AuthLogon", "Date", "Time") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS authlog_authuser ON authlog USING btree ("AuthUser", "Date", "Time") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS authlog_stationid ON authlog USING btree ("StationId", "Date", "Time") TABLESPACE pg_default;
COMMENT ON TABLE authlog IS 'Authentication Logon Records';
COMMENT ON COLUMN authlog."Time" IS 'Time of the attempt (in minutes from midnight)';
COMMENT ON COLUMN authlog."StationId" IS 'axiUm Station Id';
COMMENT ON COLUMN authlog."LogonUser" IS 'USERS.User of person logged into axiUm';
COMMENT ON COLUMN authlog."IsPINAttempt" IS '0=No (approval attempt), 1=Yes ("PIN" attempt)';
COMMENT ON COLUMN authlog."Date" IS 'Date of the attempt';
COMMENT ON COLUMN authlog."AuthUser" IS 'approval user ID, ptr to USERS.User';
COMMENT ON COLUMN authlog."AuthType" IS 'authorization type';
COMMENT ON COLUMN authlog."AuthLogon" IS 'approval user logon, ptr to USERS.Logon';
COMMENT ON COLUMN authlog."AuthLog" IS 'Primary Key: internal ID (from sequence)';
COMMENT ON COLUMN authlog."Action" IS '0=Failed, 1=Success';


CREATE  TABLE auto_recon_rules (
  "Type" numeric(5,0) NOT NULL DEFAULT 0,
  "Months" numeric(5,0) NOT NULL DEFAULT 0,
  "AllowDuplicates" numeric(5,0) NOT NULL DEFAULT 0,
  "CurrentOnly" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT auto_recon_rules_pk PRIMARY KEY ("Type")
) ;
COMMENT ON TABLE auto_recon_rules IS 'Table for storing the Clinical Auto-reconciliation rules.';
COMMENT ON COLUMN auto_recon_rules."Type" IS 'Primary key component. Clinical record type. 1 - Medical Problems, 2 - Medical Test Results, 3 - Medications, 4 - Medical Allergies';
COMMENT ON COLUMN auto_recon_rules."Months" IS 'Auto-reconcile the last x months of data';
COMMENT ON COLUMN auto_recon_rules."CurrentOnly" IS 'Auto-reconcile only current records. 0 - No, 1 - Yes';
COMMENT ON COLUMN auto_recon_rules."AllowDuplicates" IS 'Allow duplicate entries. 0 - No, 1 - Yes';


CREATE  TABLE autolmap (
  "Id" numeric(10,0) NOT NULL,
  "Value" numeric(5,0) NOT NULL,
  "DisplayText" character varying(255),
  CONSTRAINT autolmap_primary PRIMARY KEY ("Id", "Value")
) ;
COMMENT ON TABLE autolmap IS 'Stores mapping information for autolock functions when AUTOLOCK.Type = 1 and AUTOLOCK.FunctionType = 0';
COMMENT ON COLUMN autolmap."Value" IS 'Primary key, value returned by AUTOLOCK.FunctionName function';
COMMENT ON COLUMN autolmap."Id" IS 'Primary key, Ptr. To AUTOLOCK.Id';
COMMENT ON COLUMN autolmap."DisplayText" IS 'Text to display';


CREATE  TABLE autolock (
  "Id" numeric(10,0) NOT NULL,
  "OfficeCode1" character(6),
  "OfficeCode2" character(6),
  "OfficeCode3" character(6),
  "OfficeCode4" character(6),
  "OfficeCode5" character(6),
  "PatientStatus" character(6),
  "PatientBalance" numeric,
  "Patient00" numeric,
  "Patient30" numeric,
  "Patient60" numeric,
  "Patient90" numeric,
  "AlertCode1" character(6),
  "AlertCode2" character(6),
  "AlertCode3" character(6),
  "AlertCode4" character(6),
  "AlertCode5" character(6),
  "Monday" numeric(5,0),
  "Tuesday" numeric(5,0),
  "Wednesday" numeric(5,0),
  "Thursday" numeric(5,0),
  "Friday" numeric(5,0),
  "Saturday" numeric(5,0),
  "Sunday" numeric(5,0),
  "ProviderBalance" numeric,
  "PatientStatus2" character(6),
  "PatientStatus3" character(6),
  "PatientStatus4" character(6),
  "PatientStatus5" character(6),
  "Description" character varying(30),
  "Consent1" character(6),
  "Consent2" character(6),
  "Consent3" character(6),
  "Patient120" numeric,
  "PtStatusFlag" numeric(5,0),
  "IncludeTodaysChgs" numeric(5,0),
  "Type" numeric(5,0),
  "FunctionType" numeric(5,0),
  "FunctionName" character varying(50),
  CONSTRAINT autolock_primary PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE autolock IS 'Chart Tracking Locks';
COMMENT ON COLUMN autolock."Wednesday" IS 'Is school open on Wednesday? (0 = No, 1 = Yes) defaults to 1';
COMMENT ON COLUMN autolock."Type" IS 'Type of autolock (0=Basic, 1=Function)';
COMMENT ON COLUMN autolock."Tuesday" IS 'Is school open on Tuesday? (0 = No, 1 = Yes) defaults to 1';
COMMENT ON COLUMN autolock."Thursday" IS 'Is school open on Thursday? (0 = No, 1 = Yes) defaults to 1';
COMMENT ON COLUMN autolock."Sunday" IS 'Is school open on Sunday? (0 = No, 1 = Yes), defaults to 0';
COMMENT ON COLUMN autolock."Saturday" IS 'Is school open on Saturday? (0 = No, 1 = Yes), defaults to 0';
COMMENT ON COLUMN autolock."PtStatusFlag" IS '0 = not equal to, 1 = equal to - Set in Chart Tracking Lock Defn. If 0 a chart is locked if the Patient Status value is not equal to any of the values specified. If 1, a chart is locked if the Patient Status value is equal to any of the values specified.';
COMMENT ON COLUMN autolock."ProviderBalance" IS 'Provider balance restriction (for Dispensary use)';
COMMENT ON COLUMN autolock."PatientStatus5" IS 'The status of a patient that will cause the auto lock to be ON. Ptr to STATUS.Status.';
COMMENT ON COLUMN autolock."PatientStatus4" IS 'The status of a patient that will cause the auto lock to be ON. Ptr to STATUS.Status.';
COMMENT ON COLUMN autolock."PatientStatus3" IS 'The status of a patient that will cause the auto lock to be ON. Ptr to STATUS.Status.';
COMMENT ON COLUMN autolock."PatientStatus2" IS 'The status of a patient that will cause the auto lock to be ON. Ptr to STATUS.Status.';
COMMENT ON COLUMN autolock."PatientStatus" IS 'The status of a patient that will cause the auto lock to be ON. Ptr to STATUS.Status.';
COMMENT ON COLUMN autolock."PatientBalance" IS 'The amount of an overall balance that will cause the auto lock to be ON regardless of whether it is a new or a late balance. ie: $100.00.';
COMMENT ON COLUMN autolock."Patient90" IS 'The amount of a balance owing (90-120 days old) that will cause the auto lock to be ON. ie: $1.00.';
COMMENT ON COLUMN autolock."Patient60" IS 'The amount of a balance owing (60-90 days old) that will cause the auto lock to be ON. Ie: $10.00.';
COMMENT ON COLUMN autolock."Patient30" IS 'The amount of a balance owing (30-60 days old) that will cause the auto lock to be ON. ie: $40.00.';
COMMENT ON COLUMN autolock."Patient120" IS 'The amount of a balance owing (over 120 days old) that will cause the auto lock to be ON. ie: $1.00.';
COMMENT ON COLUMN autolock."Patient00" IS 'The amount of a balance owing (less than 30 days old) that will cause the auto lock to be ON. ie: $100.00.';
COMMENT ON COLUMN autolock."OfficeCode5" IS 'Office code that will cause the auto lock to be ON for that particular chart ie: NSF cheque, ptr to OFFICE.Office';
COMMENT ON COLUMN autolock."OfficeCode4" IS 'Office code that will cause the auto lock to be ON for that particular chart ie: NSF cheque, ptr to OFFICE.Office';
COMMENT ON COLUMN autolock."OfficeCode3" IS 'Office code that will cause the auto lock to be ON for that particular chart ie: NSF cheque, ptr to OFFICE.Office';
COMMENT ON COLUMN autolock."OfficeCode2" IS 'Office code that will cause the auto lock to be ON for that particular chart ie: NSF cheque, ptr to OFFICE.Office';
COMMENT ON COLUMN autolock."OfficeCode1" IS 'Office code that will cause the auto lock to be ON for that particular chart ie: NSF cheque, ptr to OFFICE.Office';
COMMENT ON COLUMN autolock."Monday" IS 'Is school open on Monday? (0 = No, 1 = Yes) defaults to 1';
COMMENT ON COLUMN autolock."IncludeTodaysChgs" IS 'Include today''s charges (0 = No, 1 = Yes)';
COMMENT ON COLUMN autolock."Id" IS 'Primary key';
COMMENT ON COLUMN autolock."FunctionType" IS 'If Type = 1, (0 = text (mapped), 1 = text (returned))';
COMMENT ON COLUMN autolock."FunctionName" IS 'If Type = 1, function name';
COMMENT ON COLUMN autolock."Friday" IS 'Is school open on Friday? (0 = No, 1 = Yes) defaults to 1';
COMMENT ON COLUMN autolock."Description" IS 'Description of the auto lock';
COMMENT ON COLUMN autolock."Consent3" IS 'The ID code of a consent that will cause the auto lock to be ON if the consent is not on file for the patient. Ptr to CONSENT.Consent';
COMMENT ON COLUMN autolock."Consent2" IS 'The ID code of a consent that will cause the auto lock to be ON if the consent is not on file for the patient. Ptr to CONSENT.Consent';
COMMENT ON COLUMN autolock."Consent1" IS 'The ID code of a consent that will cause the auto lock to be ON if the consent is not on file for the patient. Ptr to CONSENT.Consent';
COMMENT ON COLUMN autolock."AlertCode5" IS 'Alert code that will cause the auto lock to be ON for that particular chart ie: NSF cheque, ptr to ALERT.Alert';
COMMENT ON COLUMN autolock."AlertCode4" IS 'Alert code that will cause the auto lock to be ON for that particular chart ie: NSF cheque, ptr to ALERT.Alert';
COMMENT ON COLUMN autolock."AlertCode3" IS 'Alert code that will cause the auto lock to be ON for that particular chart ie: NSF cheque, ptr to ALERT.Alert';
COMMENT ON COLUMN autolock."AlertCode2" IS 'Alert code that will cause the auto lock to be ON for that particular chart ie: NSF cheque, ptr to ALERT.Alert';
COMMENT ON COLUMN autolock."AlertCode1" IS 'Alert code that will cause the auto lock to be ON for that particular chart ie: NSF cheque, ptr to ALERT.Alert';


CREATE  TABLE ax_help (
  "PackageName" character varying(30),
  "ObjectName" character varying(30),
  "Description" character varying(4000),
  CONSTRAINT ax_help_key UNIQUE ("PackageName", "ObjectName")
) ;
COMMENT ON TABLE ax_help IS 'This table is used by ax_pkg.help, AXSO built in help system.';
COMMENT ON COLUMN ax_help."PackageName" IS 'The name of the AXSO package the help file is describing.';
COMMENT ON COLUMN ax_help."ObjectName" IS 'The name of the procedure, function, or constant within the AXSO package.';
COMMENT ON COLUMN ax_help."Description" IS 'Describes the function of the object.';


CREATE  TABLE ax_log (
  "LogId" numeric NOT NULL,
  "LogSetId" numeric,
  "DateTime" timestamp(6) without time zone,
  "Source" character varying(255),
  "Request" character varying(50),
  "User" numeric,
  "StationId" numeric,
  "Log" character varying(4000),
  CONSTRAINT ax_log_pk PRIMARY KEY ("LogId")
) ;
COMMENT ON TABLE ax_log IS 'Table for logging AXSO events';
COMMENT ON COLUMN ax_log."User" IS 'User Id that triggered the log';
COMMENT ON COLUMN ax_log."StationId" IS 'Station Id, ptr to STATION.StationId';
COMMENT ON COLUMN ax_log."Source" IS 'Name of the program/oracle object that generated this record';
COMMENT ON COLUMN ax_log."Request" IS 'Associated ticket or case number';
COMMENT ON COLUMN ax_log."LogSetId" IS 'Group identifier for the log';
COMMENT ON COLUMN ax_log."LogId" IS 'Unique identifier for the log';
COMMENT ON COLUMN ax_log."Log" IS 'Content of the log';
COMMENT ON COLUMN ax_log."DateTime" IS 'Date/Time of the log';


CREATE  TABLE ax_map (
  "Audit" numeric(10,0),
  "TableName" character varying(30),
  "SourceId" numeric(10,0),
  "TargetId" numeric(10,0),
  "SourceCode" character varying(50),
  "TargetCode" character varying(50)
) ;
CREATE INDEX IF NOT EXISTS ax_map_sourceidtableaudit ON ax_map USING btree ("SourceId", "TableName", "Audit") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ax_map_audittablesourceid ON ax_map USING btree ("Audit", "TableName", "SourceId") TABLESPACE pg_default;
COMMENT ON TABLE ax_map IS 'Table of temporary data used by ax_copy_pkg and ax_users_pkg';
COMMENT ON COLUMN ax_map."TargetId" IS 'Id for the target record';
COMMENT ON COLUMN ax_map."TargetCode" IS 'Code for the target record';
COMMENT ON COLUMN ax_map."TableName" IS 'axiUm table name';
COMMENT ON COLUMN ax_map."SourceId" IS 'Id from the source record';
COMMENT ON COLUMN ax_map."SourceCode" IS 'Code from the source record';
COMMENT ON COLUMN ax_map."Audit" IS 'Audit number';


CREATE  TABLE ax_setting (
  "axSetting" numeric(5,0) NOT NULL,
  "Key" character varying(255) NOT NULL,
  "SettingType" numeric(5,0) NOT NULL,
  "axSettingGrp" numeric(5,0),
  "Priority" numeric(5,0),
  "Value" character varying(4000),
  "Description" character varying(4000),
  CONSTRAINT ax_setting_key_con UNIQUE ("Key")
) ;
CREATE UNIQUE INDEX IF NOT EXISTS ax_setting_key ON ax_setting USING btree ("Key") TABLESPACE pg_default;
COMMENT ON TABLE ax_setting IS 'Table for AXSO settings';
COMMENT ON COLUMN ax_setting."axSettingGrp" IS 'Number field used to group settings together, should equal an axSetting value.';
COMMENT ON COLUMN ax_setting."axSetting" IS 'Unique Identifier for setting';
COMMENT ON COLUMN ax_setting."Value" IS 'Value of the setting';
COMMENT ON COLUMN ax_setting."SettingType" IS 'Type of the setting (0 = system setting, 1 = boolean, 2 = number, 3 = string, 4 = text, 5 = list)';
COMMENT ON COLUMN ax_setting."Priority" IS 'Priority of the setting';
COMMENT ON COLUMN ax_setting."Key" IS 'Unique identifier of the setting';
COMMENT ON COLUMN ax_setting."Description" IS 'Instructions/notes about this setting';


CREATE  TABLE ax_upgrade (
  "Module" character varying(20),
  "Major" numeric(5,0),
  "Minor" numeric(2,0),
  "Patch" numeric(2,0),
  "Build" numeric(5,0),
  "Timestamp" timestamp without time zone
) ;
COMMENT ON TABLE ax_upgrade IS 'DbUpgrade records.';
COMMENT ON COLUMN ax_upgrade."Timestamp" IS 'Timestamp that the upgrade occurred on.';
COMMENT ON COLUMN ax_upgrade."Patch" IS 'Patch version upgraded to.';
COMMENT ON COLUMN ax_upgrade."Module" IS 'Module that was last upgraded using DbUpgrade.';
COMMENT ON COLUMN ax_upgrade."Minor" IS 'Minor version upgraded to.';
COMMENT ON COLUMN ax_upgrade."Major" IS 'Major version upgraded to.';
COMMENT ON COLUMN ax_upgrade."Build" IS 'Build number upgraded to.';


CREATE  TABLE ax_upgrade_runonce (
  "ScriptId" numeric(5,0)
) ;
COMMENT ON TABLE ax_upgrade_runonce IS 'Records of DbUpgrade run-once scripts that have already been run.';
COMMENT ON COLUMN ax_upgrade_runonce."ScriptId" IS 'Internal ID of the DbUpgrade script that should only be run once.';


CREATE  TABLE ax_upgrade_xltable (
  "TableName" character varying(255),
  "State" numeric(5,0),
  "DateTime" timestamp without time zone,
  "InsertClause" character varying(255)
) ;


CREATE  TABLE axium_api_err_log (
  "Id" numeric(10,0) NOT NULL,
  "AxiumApiLogId" numeric(10,0),
  "DateTime" timestamp without time zone,
  "Application" character varying(255),
  error clob,
  CONSTRAINT axium_api_err_log_primary PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE axium_api_err_log IS 'Table for storing Error log messages';
COMMENT ON COLUMN axium_api_err_log.error IS 'Error Message';
COMMENT ON COLUMN axium_api_err_log."Id" IS 'Primary key sequence field';
COMMENT ON COLUMN axium_api_err_log."DateTime" IS 'Date and time of the error';
COMMENT ON COLUMN axium_api_err_log."AxiumApiLogId" IS 'Id of the AXIUM_API_LOG entry during this error';
COMMENT ON COLUMN axium_api_err_log."Application" IS 'Indicates if it came from queue-processor, public-api, or job-utils';


CREATE  TABLE axium_api_log (
  "Id" numeric(10,0) NOT NULL,
  "SessionId" numeric(10,0),
  "ParentId" numeric(10,0),
  "DateTime" timestamp without time zone,
  "Source" character varying(255),
  "Url" character varying(4000),
  body clob,
  response clob,
  CONSTRAINT axium_api_log_primary PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE axium_api_log IS 'Axium API Log';
COMMENT ON COLUMN axium_api_log.response IS 'The raw json body of the api response';
COMMENT ON COLUMN axium_api_log.body IS 'the raw json body of the api call';
COMMENT ON COLUMN axium_api_log."Url" IS 'complete url of the request, including query parameters';
COMMENT ON COLUMN axium_api_log."Source" IS 'The source of the call (vendor id)';
COMMENT ON COLUMN axium_api_log."SessionId" IS 'Sequenced ID linking all internal API calls to the original external request';
COMMENT ON COLUMN axium_api_log."ParentId" IS 'Id of the API log that resulted in this internal API call';
COMMENT ON COLUMN axium_api_log."Id" IS 'Primary key, sequence field';
COMMENT ON COLUMN axium_api_log."DateTime" IS 'date and time of api call';


CREATE  TABLE axiumopt (
  "RegVal1" character(10) NOT NULL,
  "RegVal2" character(10) NOT NULL,
  "TerminalType" numeric(5,0),
  "EnvVarName" character(24),
  "AntBuccal" character(1),
  "AntDistal" character(1),
  "AntOcclusal" character(1),
  "AntMesial" character(1),
  "AntLingual" character(1),
  "BicBuccal" character(1),
  "BicDistal" character(1),
  "BicOcclusal" character(1),
  "BicMesial" character(1),
  "BicLingual" character(1),
  "MolBuccal" character(1),
  "MolDistal" character(1),
  "MolOcclusal" character(1),
  "MolMesial" character(1),
  "MolLingual" character(1),
  "EDIInfo1" character(60),
  "EDIInfo2" character(60),
  "EDIInfo3" character(60),
  "EDIInfo4" character(10),
  "EDIInfo5" character(30),
  "EDIInfo6" character(30),
  "OrthoClaims" numeric(5,0),
  "PlanInitProcedure" character(7),
  "PlanMonthProcedure" character(7),
  "PlanQuarterProcedure" character(7),
  "PlanManualProcedure" character(7),
  "PlanFinalProcedure" character(7),
  "OrthoEDI" numeric(5,0),
  "PlanBiAnnualProcedur" character(7),
  "DocType" numeric(5,0),
  "MissingSymbol" character(6),
  "EDIContact" character varying(33),
  "EDIPhone" character varying(10),
  "StmtInclInsTrx" numeric(5,0),
  "MaxRemote" numeric(5,0),
  "SterilizeOuterCd" numeric(5,0),
  "SterilizeInternalCd" numeric(5,0),
  "SterilizeBatchLabels" numeric(5,0),
  "LifeCycleBySterilize" numeric(5,0),
  "UseSterilizeDefaults" numeric(5,0),
  "MinLevelOption" numeric(5,0),
  "RequireConsent" numeric(5,0),
  "AuditLogging" numeric(5,0),
  "DirtyDispWarning" numeric(5,0),
  "BillStepInsurance" numeric(5,0),
  "OvernightUser" numeric(10,0),
  "CheckClinMax" numeric(5,0),
  "BillInProcTotal" numeric(5,0),
  "UsePwdFunction" numeric(5,0),
  "PwdFunctionName" character(50),
  "DispWarnLocation" numeric(5,0),
  "IndicatePtUnappr" numeric(5,0),
  "ShowUserLogon" numeric(5,0),
  "UseMulticast" numeric(5,0),
  "MulticastPort" numeric(5,0),
  "MulticastAddress" character(15),
  "KeepQuote" numeric(5,0),
  "LoadAllMaterials" numeric(5,0),
  "UseCitrix" numeric(5,0),
  "UseDiagCode" numeric(5,0),
  "InvLeadTime" numeric(5,0),
  "InvLeadUnit" numeric(5,0),
  "InvProdSize" numeric(5,0),
  "NoGuarWarn" numeric(5,0),
  "NoGuarAge" numeric(5,0),
  "InProcICharge" numeric(5,0),
  "ApplyLimitOnPlanTxs" numeric(5,0),
  "NewStnKey" character varying(51),
  "RptAccessLogs" numeric(5,0),
  "UsePreventiveCare" numeric(5,0),
  "UseSharedChairs" numeric(5,0),
  "HygAgeCutoff" numeric(5,0),
  "BlockSchRules" character varying(20),
  "NoteStartTag" character(1),
  "NoteTextTag" character(1),
  "NoteEndTag" character(1),
  "ApprovalLogs" numeric(5,0),
  "ICDType" numeric(5,0),
  "RegVal3" character(10),
  "RegVal4" character(10),
  "EnforceBookingOrder" numeric(5,0),
  "EncryptionMethod" numeric(5,0),
  "EDIUnderPayMode" numeric(5,0),
  "EDIPmtCode" character(6),
  "EDIEFTCode" character(6),
  "SoftModuleCnt" character varying(45),
  "SoftModuleDel" character(10),
  "EDIOverPayMode" numeric(5,0),
  "DefaultDBAdjust" character(6),
  "DefaultCRAdjust" character(6),
  "AttnRequired" character varying(255),
  "LastSeqNo" numeric(10,0),
  "FormRefCodesUnique" numeric(5,0),
  "NEAVendorId" character varying(8),
  "MsgEncryption" numeric(5,0),
  "HiTechOverride" numeric(5,0),
  "EMailNtfy" numeric(5,0),
  "EMailCd" character(6),
  "MaskCharacter" character(1),
  "MaskClearTextLast" numeric(5,0) DEFAULT 0,
  "RestrictLoginAdmin" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT axiumopt_primary PRIMARY KEY ("RegVal1")
) ;
COMMENT ON TABLE axiumopt IS 'System options record, one record per database';
COMMENT ON COLUMN axiumopt."UseSterilizeDefaults" IS 'Use sterilize defaults? (0 = No, 1= Yes use the number in KITTYPE.DefaultSterilization for the number of days a kit is sterile)';
COMMENT ON COLUMN axiumopt."UseSharedChairs" IS '1 = Yes, 0 = No';
COMMENT ON COLUMN axiumopt."UsePwdFunction" IS 'Use an Oracle function for password validation? (0 = No, 1 = Yes)';
COMMENT ON COLUMN axiumopt."UsePreventiveCare" IS 'Use preventative care features? (0 = No, 1 = Yes)';
COMMENT ON COLUMN axiumopt."UseMulticast" IS 'Not accessible through axiUm. Use Multi-Cast? (0 = No, 1 = Yes), defaults to 0';
COMMENT ON COLUMN axiumopt."UseDiagCode" IS 'Use diagnostic codes? (0 = No, 1 = Yes, 2=Mandatory)';
COMMENT ON COLUMN axiumopt."UseCitrix" IS 'Use Citrix to run axiUm? (0 = No, 1 = Yes)';
COMMENT ON COLUMN axiumopt."TerminalType" IS 'Terminal type (0=operating system, 1= environment variable)';
COMMENT ON COLUMN axiumopt."StmtInclInsTrx" IS 'Statements for this University include insurance transactions? (0 = No, 1 = Yes)';
COMMENT ON COLUMN axiumopt."SterilizeOuterCd" IS 'Sterilize outer codes (0 = No, 1 = Yes), defaults to 0';
COMMENT ON COLUMN axiumopt."SterilizeInternalCd" IS 'Sterilize internal codes (0 = No, 1 = Yes (axiUm generated)), defaults to 1';
COMMENT ON COLUMN axiumopt."SterilizeBatchLabels" IS 'If AXIUMOPT.SterilizeInternalCodes = 1, created in a batch (0 = No, 1 = Yes (suppress during sterilize process))';
COMMENT ON COLUMN axiumopt."SoftModuleDel" IS 'Obsolete';
COMMENT ON COLUMN axiumopt."SoftModuleCnt" IS 'Obsolete';
COMMENT ON COLUMN axiumopt."ShowUserLogon" IS 'Display user logon when listing users? (0 = No, 1 = Yes)';
COMMENT ON COLUMN axiumopt."RptAccessLogs" IS 'Logging Info Manager reports - 0 = Off, 1 = On';
COMMENT ON COLUMN axiumopt."RestrictLoginAdmin" IS 'Restrict access to axiUm to admin users only (0 = No, 1 = Yes).';
COMMENT ON COLUMN axiumopt."RequireConsent" IS 'Require release of information consent to be on file? (0 = No, 1 = Yes)';
COMMENT ON COLUMN axiumopt."RegVal4" IS 'Obsolete';
COMMENT ON COLUMN axiumopt."RegVal3" IS 'Optional hardware modules (encrypted)';
COMMENT ON COLUMN axiumopt."RegVal2" IS 'Primary key, license expiry date (encrypted)';
COMMENT ON COLUMN axiumopt."RegVal1" IS 'Primary key, # of workstations (encrypted)';
COMMENT ON COLUMN axiumopt."PwdFunctionName" IS 'Name of the Oracle function that controls the password';
COMMENT ON COLUMN axiumopt."PlanQuarterProcedure" IS 'Quarterly ortho payment plan fee procedure';
COMMENT ON COLUMN axiumopt."PlanMonthProcedure" IS 'Monthly ortho payment plan fee procedure';
COMMENT ON COLUMN axiumopt."PlanManualProcedure" IS 'Manual ortho payment plan fee procedure';
COMMENT ON COLUMN axiumopt."PlanInitProcedure" IS 'Initial ortho payment plan fee procedure';
COMMENT ON COLUMN axiumopt."PlanFinalProcedure" IS 'Final ortho payment plan fee procedure';
COMMENT ON COLUMN axiumopt."PlanBiAnnualProcedur" IS 'Biannual ortho payment plan fee procedure';
COMMENT ON COLUMN axiumopt."OvernightUser" IS 'Id code of the user for the overnight process';
COMMENT ON COLUMN axiumopt."OrthoEDI" IS 'Accept "EDI"? (0 = No, 1 = Yes)';
COMMENT ON COLUMN axiumopt."OrthoClaims" IS 'Ortho claim submission method flag (0 = No, 1 = Current plan fee, 2 = Trx Total, 3 = Trx Total on 1st claim; plan fee thereafter, 4 = Trx Total on 1st claim only)';
COMMENT ON COLUMN axiumopt."NoteTextTag" IS 'character that displays to the user when entering a note (e.g. ''*'')';
COMMENT ON COLUMN axiumopt."NoteStartTag" IS 'starting character of a tag (e.g. ''{'')';
COMMENT ON COLUMN axiumopt."NoteEndTag" IS 'end character of a tag (e.g. ''}'')';
COMMENT ON COLUMN axiumopt."NoGuarWarn" IS 'Warn if no appropriate guarantor on record (0 = No, 1 = Yes) ';
COMMENT ON COLUMN axiumopt."NoGuarAge" IS 'Age at which a guarantor other than self is not required. ';
COMMENT ON COLUMN axiumopt."NewStnKey" IS 'US Schools = 1, OtherSchools = 0';
COMMENT ON COLUMN axiumopt."NEAVendorId" IS 'NEA Vendor Facility ID';
COMMENT ON COLUMN axiumopt."MulticastPort" IS 'Not accessible through axiUm. If UseMulticast = 1, the port to use (16464)';
COMMENT ON COLUMN axiumopt."MulticastAddress" IS 'Not accessible through axiUm. If UseMulticast = 1, the address to use (230.255.255.255)';
COMMENT ON COLUMN axiumopt."MsgEncryption" IS 'Encrypt all messages in Messenger? (0=No - only messages involving patients are encrypted, 1=Yes - all messages are encrypted)';
COMMENT ON COLUMN axiumopt."MolOcclusal" IS 'Letter to display for the Occlusal surface of the Molar';
COMMENT ON COLUMN axiumopt."MolMesial" IS 'Letter to display for the Mesial surface of the Molar';
COMMENT ON COLUMN axiumopt."MolLingual" IS 'Letter to display for the Lingual surface of the Molar';
COMMENT ON COLUMN axiumopt."MolDistal" IS 'Letter to display for the Distal surface of the Molar';
COMMENT ON COLUMN axiumopt."MolBuccal" IS 'Letter to display for the Buccal surface of the Molar';
COMMENT ON COLUMN axiumopt."MissingSymbol" IS 'Code to identify the symbol as missing';
COMMENT ON COLUMN axiumopt."MinLevelOption" IS 'Minimum level option? (0=Min extra, 1=target levels)';
COMMENT ON COLUMN axiumopt."MaxRemote" IS 'Maximum Number of remote databases ';
COMMENT ON COLUMN axiumopt."MaskClearTextLast" IS 'Clear the last entry when modifying a masked entry field? (0 = No, 1 = Yes).';
COMMENT ON COLUMN axiumopt."MaskCharacter" IS 'Character to display for masked text in masked entry fields.';
COMMENT ON COLUMN axiumopt."LoadAllMaterials" IS 'Load all lab material codes when searching? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN axiumopt."LifeCycleBySterilize" IS 'Life cycle calculated by sterilization cycles? (0 = No, 1 = Yes)';
COMMENT ON COLUMN axiumopt."LastSeqNo" IS 'Internal field used for CDANet "EDI". Last sequence number for field A02.';
COMMENT ON COLUMN axiumopt."KeepQuote" IS 'Keep binding quote when procedure changes? (0 = No, 1 = Yes)';
COMMENT ON COLUMN axiumopt."InvProdSize" IS 'Inventory product code length (Set to 6 by default). ';
COMMENT ON COLUMN axiumopt."InvLeadUnit" IS 'Obsolete';
COMMENT ON COLUMN axiumopt."InvLeadTime" IS 'Obsolete';
COMMENT ON COLUMN axiumopt."IndicatePtUnappr" IS 'Indicate unapproved patients in the status bar? (0 = No, 1 = Yes)';
COMMENT ON COLUMN axiumopt."InProcICharge" IS 'In process individual charge billing - 0 = No, 1 = When first moved to I status, 2 = while in I status';
COMMENT ON COLUMN axiumopt."ICDType" IS 'Default type of ICD diagnosis code to use (0=ICD-9, 1=ICD-10) ';
COMMENT ON COLUMN axiumopt."HygAgeCutoff" IS 'age cutoff for CDA/hygienist';
COMMENT ON COLUMN axiumopt."HiTechOverride" IS 'HiTech Override (0 = No Override, 1 = Yes)';
COMMENT ON COLUMN axiumopt."FormRefCodesUnique" IS 'Are reference codes in EPR forms required to be unique across all forms? (0=No, only need to be unique within a form, 1=Yes)';
COMMENT ON COLUMN axiumopt."EnvVarName" IS 'Computer name';
COMMENT ON COLUMN axiumopt."EnforceBookingOrder" IS 'Enforce booking order for appointments? (0=No, 1=Yes)';
COMMENT ON COLUMN axiumopt."EncryptionMethod" IS 'Use advanced encryption? (0=No, 1=Yes)';
COMMENT ON COLUMN axiumopt."EMailNtfy" IS 'Send email notifcations to patients? (0=No, 1=Yes)';
COMMENT ON COLUMN axiumopt."EMailCd" IS 'Email template to send to patients. Ptr. To EMAILCD.EmailCd';
COMMENT ON COLUMN axiumopt."EDIUnderPayMode" IS 'EDI Underpayment mode (1 = Change tx to match, 2 = Adjust (based on Ins))';
COMMENT ON COLUMN axiumopt."EDIPmtCode" IS 'Default code for "EDI" autopayments (ptr to PAYMENT.Payment)';
COMMENT ON COLUMN axiumopt."EDIPhone" IS 'Phone number of the "EDI" contact';
COMMENT ON COLUMN axiumopt."EDIOverPayMode" IS 'EDI Overpayment mode (1 = Change tx to match, 2 = Adjust (based on Ins))';
COMMENT ON COLUMN axiumopt."EDIInfo6" IS 'Encrypted data for "EDI" use';
COMMENT ON COLUMN axiumopt."EDIInfo5" IS 'Encrypted data for "EDI" use';
COMMENT ON COLUMN axiumopt."EDIInfo4" IS 'Encrypted data for "EDI" use';
COMMENT ON COLUMN axiumopt."EDIInfo3" IS 'Encrypted data for "EDI" use';
COMMENT ON COLUMN axiumopt."EDIInfo2" IS 'Encrypted data for "EDI" use';
COMMENT ON COLUMN axiumopt."EDIInfo1" IS 'Encrypted data for "EDI" use';
COMMENT ON COLUMN axiumopt."EDIEFTCode" IS 'Default code for "EDI" direct-deposit electronic funds transfers (ptr to PAYMENT.Payment)';
COMMENT ON COLUMN axiumopt."EDIContact" IS 'Contact person for "EDI" ';
COMMENT ON COLUMN axiumopt."DocType" IS 'The type of document (1= MS Word, 2= PDF)';
COMMENT ON COLUMN axiumopt."DispWarnLocation" IS 'Warn if checking out kits that are currently not at that location? (0 = No, 1 = Yes)';
COMMENT ON COLUMN axiumopt."DirtyDispWarning" IS 'Warn if dispensary item being transferred is dirty (0 = No, 1 = Yes)';
COMMENT ON COLUMN axiumopt."DefaultDBAdjust" IS 'Default adjustment code to use for "EDI" debit adjustments (ptr to ADJUST.Adjust)';
COMMENT ON COLUMN axiumopt."DefaultCRAdjust" IS 'Default adjustment code to use for "EDI" credit adjustments (ptr to ADJUST.Adjust)';
COMMENT ON COLUMN axiumopt."CheckClinMax" IS 'Check clinical limits when appointments added? (0 = No, 1 = Yes)';
COMMENT ON COLUMN axiumopt."BlockSchRules" IS 'Schedule rules for the block (i.e. 00000000000000000000)';
COMMENT ON COLUMN axiumopt."BillStepInsurance" IS 'Bill the patient portion of the step treatments as they are completed (0 = No, 1 = Yes)';
COMMENT ON COLUMN axiumopt."BillInProcTotal" IS 'Bill in-process treatments to patients? (0 = No, 1 = Yes)';
COMMENT ON COLUMN axiumopt."BicOcclusal" IS 'Letter to display for the Occlusal surface of the Bicuspid';
COMMENT ON COLUMN axiumopt."BicMesial" IS 'Letter to display for the Mesial surface of the Bicuspid';
COMMENT ON COLUMN axiumopt."BicLingual" IS 'Letter to display for the Lingual surface of the Bicuspid';
COMMENT ON COLUMN axiumopt."BicDistal" IS 'Letter to display for the Distal surface of the Bicuspid';
COMMENT ON COLUMN axiumopt."BicBuccal" IS 'Letter to display for the Buccal surface of the Bicuspid';
COMMENT ON COLUMN axiumopt."AuditLogging" IS 'Record to PTLOG table? (0 = No, 1 = Basic, 2 = Advanced)';
COMMENT ON COLUMN axiumopt."AttnRequired" IS 'Binary string to determine which process types require attention';
COMMENT ON COLUMN axiumopt."ApprovalLogs" IS '0=No, 1=Yes (log approval attempts)';
COMMENT ON COLUMN axiumopt."ApplyLimitOnPlanTxs" IS 'Flag to indicate whether to apply limit when posting plan treatments.';
COMMENT ON COLUMN axiumopt."AntOcclusal" IS 'Letter to display for the Occlusal surface of the Anterior tooth';
COMMENT ON COLUMN axiumopt."AntMesial" IS 'Letter to display for the Mesial surface of the Anterior tooth';
COMMENT ON COLUMN axiumopt."AntLingual" IS 'Letter to display for the Lingual surface of the Anterior tooth';
COMMENT ON COLUMN axiumopt."AntDistal" IS 'Letter to display for the Distal surface of the Anterior tooth';
COMMENT ON COLUMN axiumopt."AntBuccal" IS 'Letter to display for the Buccal surface of the Anterior tooth';


CREATE  TABLE axvektis (
  "Id" numeric(10,0) NOT NULL,
  "MessageFormat" numeric(5,0),
  "MessageFormatVer" numeric(5,0),
  "MessageFormatSubVer" numeric(5,0),
  "InfoSystemId" numeric(10,0),
  "InfoSystemVer" character varying(10),
  "ServiceCode" numeric(10,0),
  "PaymentSendTo" numeric(5,0),
  "VATId" character varying(14),
  "CurrencyCode" character varying(5),
  "AutoUpdateBank" numeric(5,0),
  CONSTRAINT axvektis_primary PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE axvektis IS 'Stores additional information for Vektis II';
COMMENT ON COLUMN axvektis."VATId" IS 'Sales tax ID';
COMMENT ON COLUMN axvektis."ServiceCode" IS 'Identification service code';
COMMENT ON COLUMN axvektis."PaymentSendTo" IS 'Identification code for payment';
COMMENT ON COLUMN axvektis."MessageFormatVer" IS 'Message format version';
COMMENT ON COLUMN axvektis."MessageFormatSubVer" IS 'Message format sub-version';
COMMENT ON COLUMN axvektis."MessageFormat" IS 'Message format';
COMMENT ON COLUMN axvektis."InfoSystemVer" IS 'Information system version';
COMMENT ON COLUMN axvektis."InfoSystemId" IS 'Information system Id';
COMMENT ON COLUMN axvektis."Id" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN axvektis."CurrencyCode" IS 'Currency code';
COMMENT ON COLUMN axvektis."AutoUpdateBank" IS 'Auto-update patient bank information? (0 = No, 1 = Yes [Default])';


CREATE  TABLE axvespec (
  "Code" character(10) NOT NULL,
  "Description" character varying(150),
  CONSTRAINT axvespec_primary PRIMARY KEY ("Code")
) ;
COMMENT ON TABLE axvespec IS 'Stores additional referral information for Vektis II';
COMMENT ON COLUMN axvespec."Description" IS 'Specialty description';
COMMENT ON COLUMN axvespec."Code" IS 'Specialty code';


CREATE  TABLE bank (
  "Bank" character(6) NOT NULL,
  "Name" character(30),
  "Address1" character(30),
  "Address2" character(30),
  "City" character(24),
  "Province" character(6),
  "Postal" character(15),
  "AddressOther" character(15),
  "Inactive" numeric(5,0),
  "IsEFT" numeric(5,0) DEFAULT 0,
  "EFTAccNumber" character varying(21),
  CONSTRAINT bank_primary PRIMARY KEY ("Bank")
) ;
COMMENT ON TABLE bank IS 'Banks for Transactions module.';
COMMENT ON COLUMN bank."Province" IS 'Province/state that the bank is located in, ptr to PROVINCE.Province';
COMMENT ON COLUMN bank."Postal" IS 'Postal/ZIP code for the bank, ptr to CITY.Postal';
COMMENT ON COLUMN bank."Name" IS 'Name of the bank.';
COMMENT ON COLUMN bank."IsEFT" IS 'Flag to mark if this record is used for EFT (0 = No, 1 = Yes).';
COMMENT ON COLUMN bank."Inactive" IS 'Bank code is inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN bank."EFTAccNumber" IS 'Bank account number for EFT.';
COMMENT ON COLUMN bank."City" IS 'City that the bank is located in, ptr to CITY.City';
COMMENT ON COLUMN bank."Bank" IS 'Primary key, ID code that identifies the bank (cash drawer or point of sale terminal).';
COMMENT ON COLUMN bank."AddressOther" IS 'For USA, represents County. For Dutch, represents Room Number.';
COMMENT ON COLUMN bank."Address2" IS 'Bank address, line 2.';
COMMENT ON COLUMN bank."Address1" IS 'Bank address, line 1.';


CREATE  TABLE billdef (
  "Company" character(6) NOT NULL,
  "ProdType" character(1) NOT NULL,
  "BillDoctor" character(10),
  "PrintOnClaim" numeric(5,0),
  CONSTRAINT billdef_primary PRIMARY KEY ("Company", "ProdType")
) ;
COMMENT ON TABLE billdef IS 'Billing Definitions';
COMMENT ON COLUMN billdef."ProdType" IS 'Primary key component, provider type for this billing definition. Ptr to PRODTYPE.Code';
COMMENT ON COLUMN billdef."PrintOnClaim" IS 'What to print on claim (0=Provider, 1=Practice)';
COMMENT ON COLUMN billdef."Company" IS 'Primary key component, insurance company for this billing definition. Ptr to INSURANC.Company';
COMMENT ON COLUMN billdef."BillDoctor" IS 'ID code of the billing doctor, ptr to PRODUCER.Producer';


CREATE  TABLE billexc (
  "Company" character(6) NOT NULL,
  "Practice" numeric(5,0) NOT NULL,
  "ProdType" character(1) NOT NULL,
  "Discipline" character(15) NOT NULL,
  "BillDoctor" character(10),
  "Producer" character(10) NOT NULL,
  "PrintOnClaim" numeric(5,0),
  "ApplyAny" numeric(5,0),
  "Rank" numeric(5,0),
  CONSTRAINT billexc_primary PRIMARY KEY ("Company", "Practice", "Producer", "ProdType", "Discipline")
) ;
COMMENT ON TABLE billexc IS 'Billing Exceptions';
COMMENT ON COLUMN billexc."Rank" IS 'If ApplyAny=1, the order/precedence of the exception relative to others.';
COMMENT ON COLUMN billexc."Producer" IS 'Primary key component, ID code of the producer for this billin exception. Ptr to PRODUCER.Producer';
COMMENT ON COLUMN billexc."ProdType" IS 'Primary key component, provider type for this billing exception. Ptr to PRODTYPE.Code';
COMMENT ON COLUMN billexc."PrintOnClaim" IS 'What to print on claim (0=Provider, 1=Practice)';
COMMENT ON COLUMN billexc."Practice" IS 'Primary key component, ID code of the practice for this billing exception. Ptr to PRACTICE.Id';
COMMENT ON COLUMN billexc."Discipline" IS 'Primary key component, discipline for this billing exception. Ptr to CLASS.Class';
COMMENT ON COLUMN billexc."Company" IS 'Primary key component, insurance company for this billing exception. Ptr to INSURANC.Company';
COMMENT ON COLUMN billexc."BillDoctor" IS 'ID code of the billing doctor, ptr to PRODUCER.Producer';
COMMENT ON COLUMN billexc."ApplyAny" IS 'Does the exception apply to any treatments on the claim? (0 – No, only for the first Tx on the claim, 1=Yes)';


CREATE  TABLE billfee (
  "Company" character(6) NOT NULL,
  "ProdType" character(1) NOT NULL,
  "ClaimDoctor" character(10),
  "BillOverride" numeric(5,0),
  CONSTRAINT billfee_primary PRIMARY KEY ("Company", "ProdType")
) ;
COMMENT ON TABLE billfee IS 'Bill Fee Overrides';
COMMENT ON COLUMN billfee."ProdType" IS 'Primary key component, provider type for this override. Ptr to PRODTYPE.Code';
COMMENT ON COLUMN billfee."Company" IS 'Primary key component, insurance company for this override. Ptr to INSURANC.Company';
COMMENT ON COLUMN billfee."ClaimDoctor" IS 'ID code of the claim doctor, ptr to PRODUCER.Producer';
COMMENT ON COLUMN billfee."BillOverride" IS 'Use override fee? (0 = Not applicable, 1=Always, 2=Unless practice override)';


CREATE  TABLE billing (
  "Company" character(6) NOT NULL,
  "Producer" character(10) NOT NULL,
  "Number" character(15),
  "Group" character(15),
  "AssignOverride" numeric(5,0),
  "NetworkId" character varying(15),
  "IsApproved" numeric(5,0),
  "Qualifier" character varying(2),
  "GroupIdQual" character varying(2),
  "NetworkIdQual" character varying(2),
  "BillingName" numeric(5,0),
  "NameQual" numeric(5,0),
  "ClaimLast" character varying(40),
  "ClaimFirst" character varying(30),
  "EDIOfficeId" character(7),
  CONSTRAINT billing_primary PRIMARY KEY ("Company", "Producer")
) ;
COMMENT ON TABLE billing IS 'Billing Numbers';
COMMENT ON COLUMN billing."Qualifier" IS 'ID prefix for claim form submisson';
COMMENT ON COLUMN billing."Producer" IS 'Primary key component, provider that this applies to. Ptr to PRODUCER.Producer';
COMMENT ON COLUMN billing."Number" IS 'Billing number for this company / doctor combination.';
COMMENT ON COLUMN billing."NetworkIdQual" IS 'Network ID prefix for claim form submisson';
COMMENT ON COLUMN billing."NetworkId" IS 'Network ID code assigned to the provider by the insurance company.';
COMMENT ON COLUMN billing."NameQual" IS 'Billing Entity (0=Provider, 1=Organization)';
COMMENT ON COLUMN billing."IsApproved" IS 'Approved? (0 = No, 1 = Yes)';
COMMENT ON COLUMN billing."GroupIdQual" IS 'Group ID prefix for claim form submisson';
COMMENT ON COLUMN billing."Group" IS 'Billing group number for this company / doctor combination. ';
COMMENT ON COLUMN billing."EDIOfficeId" IS 'Billing doctor office ID for "EDI" claims';
COMMENT ON COLUMN billing."Company" IS 'Primary key component, insurance company this applies to. Ptr to INSURANC.Company';
COMMENT ON COLUMN billing."ClaimLast" IS 'Organization name or provider last name to print on claims. ';
COMMENT ON COLUMN billing."ClaimFirst" IS 'Provider first name to print on claims.';
COMMENT ON COLUMN billing."BillingName" IS 'Has a different billing provider name? (0 = No, 1 = Yes)';
COMMENT ON COLUMN billing."AssignOverride" IS 'Assignment override setting (0=Insurance company, 1 = Yes, 2=No)';


CREATE  TABLE billref (
  "Referral" numeric(10,0) NOT NULL,
  "Company" character(6) NOT NULL,
  "IDNumber" character(10),
  "Qualifier" character varying(2),
  CONSTRAINT billref_primary PRIMARY KEY ("Referral", "Company")
) ;
COMMENT ON TABLE billref IS 'Referral Doctors by Insurance Company';
COMMENT ON COLUMN billref."Referral" IS 'Primary key component, ID code of the referral. Ptr to REFERRAL.Referral';
COMMENT ON COLUMN billref."Qualifier" IS 'ID prefix for claim form submisson';
COMMENT ON COLUMN billref."IDNumber" IS 'Billing number of the referring doctor.';
COMMENT ON COLUMN billref."Company" IS 'Primary key component, ID Code of the referring insurance company. Ptr to INSURANC.Company';


CREATE  TABLE book (
  "Book" numeric(10,0) NOT NULL,
  "Name" character(63),
  "Tab1Name" character(15),
  "Tab1Days" numeric(10,0),
  "Tab2Name" character(15),
  "Tab2Days" numeric(10,0),
  "Tab3Name" character(15),
  "Tab3Days" numeric(10,0),
  "Tab4Name" character(15),
  "Tab4Days" numeric(10,0),
  "Flag" numeric(10,0),
  "HasReserves" numeric(5,0),
  "DisplayReserves" numeric(5,0),
  "ColsPerPage" numeric(5,0),
  "SortChair" numeric(5,0),
  "ReservesByProvider" numeric(5,0),
  "ShowAllProviders" numeric(5,0),
  "DynamicCol" numeric(5,0),
  "ReserveClinic" numeric(10,0),
  "ShowSecondaryAppts" numeric(5,0),
  "Inactive" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT book_primary PRIMARY KEY ("Book")
) ;
CREATE INDEX IF NOT EXISTS book_name ON book USING btree ("Name") TABLESPACE pg_default;
COMMENT ON TABLE book IS 'Appointment Books';
COMMENT ON COLUMN book."Tab4Name" IS 'Text to display on the fourth tab. (6 Months)';
COMMENT ON COLUMN book."Tab4Days" IS 'Number of days to advance when tab is clicked (178 / 182)';
COMMENT ON COLUMN book."Tab3Name" IS 'Text to display on the third tab. (1 Month)';
COMMENT ON COLUMN book."Tab3Days" IS 'Number of days to advance when tab is clicked (30 / 31)';
COMMENT ON COLUMN book."Tab2Name" IS 'Text to display on the second tab. (1 Week)';
COMMENT ON COLUMN book."Tab2Days" IS 'Number of days to advance when tab is clicked (7)';
COMMENT ON COLUMN book."Tab1Name" IS 'Text to display on the first tab. (1 Day)';
COMMENT ON COLUMN book."Tab1Days" IS 'Number of days to advance when tab is clicked (1)';
COMMENT ON COLUMN book."SortChair" IS 'Order chairs by: 0 = Chair, 1 = Provider';
COMMENT ON COLUMN book."ShowSecondaryAppts" IS 'Show columns for second providers? (0=No, 1=Yes)';
COMMENT ON COLUMN book."ShowAllProviders" IS 'Load providers with no reservations: 0 = Only ones with reserves, 1 = all Providers';
COMMENT ON COLUMN book."ReservesByProvider" IS 'Book by: 0 = By Chair, 1 = By Provider';
COMMENT ON COLUMN book."ReserveClinic" IS 'If ReservesByProvider=1, clinic to use for the reserves (0=not used, else Ptr to CLINIC.Clinic)';
COMMENT ON COLUMN book."Name" IS 'Name of the scheduler book';
COMMENT ON COLUMN book."Inactive" IS 'Code inactive? 0 - no, 1 = yes';
COMMENT ON COLUMN book."HasReserves" IS 'Chairs in book have been reserved by a provider? (0 = No, 1 = Yes)';
COMMENT ON COLUMN book."Flag" IS 'DEPRECATED';
COMMENT ON COLUMN book."DynamicCol" IS 'if a book has dynamic columns or not. 0 = no, 1 = yes';
COMMENT ON COLUMN book."DisplayReserves" IS 'Display the reserves only for the book open times? (0 = No, 1 = Yes)';
COMMENT ON COLUMN book."ColsPerPage" IS 'Default number of columns per page per appointment book';
COMMENT ON COLUMN book."Book" IS 'Primary key, Internal ID (from sequence), ID code to identify the book';


CREATE  TABLE bookchr (
  "BookDetail" numeric(10,0) NOT NULL,
  "Chair" numeric(10,0) NOT NULL,
  "Order" numeric(5,0),
  CONSTRAINT bookchr_primary PRIMARY KEY ("BookDetail", "Chair")
) ;
COMMENT ON TABLE bookchr IS 'Chairs within appointment books';
COMMENT ON COLUMN bookchr."Order" IS 'A number to represent the order in which the chair is to appear within the book';
COMMENT ON COLUMN bookchr."Chair" IS 'Chair Id of a chair in the Appt Book';
COMMENT ON COLUMN bookchr."BookDetail" IS 'Ptr to BOOKDET.BookDetail, the book detail record to which this applies';


CREATE  TABLE bookdet (
  "BookDetail" numeric(10,0) NOT NULL,
  "Book" numeric(10,0),
  "StartDate" timestamp without time zone,
  "EndDate" timestamp without time zone,
  "Opened0" numeric(5,0),
  "From0" numeric(10,0),
  "To0" numeric(10,0),
  "From0Second" numeric(10,0),
  "To0Second" numeric(10,0),
  "From0Third" numeric(10,0),
  "To0Third" numeric(10,0),
  "Opened1" numeric(5,0),
  "From1" numeric(10,0),
  "To1" numeric(10,0),
  "From1Second" numeric(10,0),
  "To1Second" numeric(10,0),
  "From1Third" numeric(10,0),
  "To1Third" numeric(10,0),
  "Opened2" numeric(5,0),
  "From2" numeric(10,0),
  "To2" numeric(10,0),
  "From2Second" numeric(10,0),
  "To2Second" numeric(10,0),
  "From2Third" numeric(10,0),
  "To2Third" numeric(10,0),
  "Opened3" numeric(5,0),
  "From3" numeric(10,0),
  "To3" numeric(10,0),
  "From3Second" numeric(10,0),
  "To3Second" numeric(10,0),
  "From3Third" numeric(10,0),
  "To3Third" numeric(10,0),
  "Opened4" numeric(5,0),
  "From4" numeric(10,0),
  "To4" numeric(10,0),
  "From4Second" numeric(10,0),
  "To4Second" numeric(10,0),
  "From4Third" numeric(10,0),
  "To4Third" numeric(10,0),
  "Opened5" numeric(5,0),
  "From5" numeric(10,0),
  "To5" numeric(10,0),
  "From5Second" numeric(10,0),
  "To5Second" numeric(10,0),
  "From5Third" numeric(10,0),
  "To5Third" numeric(10,0),
  "Opened6" numeric(5,0),
  "From6" numeric(10,0),
  "To6" numeric(10,0),
  "From6Second" numeric(10,0),
  "To6Second" numeric(10,0),
  "From6Third" numeric(10,0),
  "To6Third" numeric(10,0),
  "NumChair" numeric(5,0),
  CONSTRAINT bookdet_primary PRIMARY KEY ("BookDetail")
) ;
CREATE INDEX IF NOT EXISTS bookdet_book ON bookdet USING btree ("Book") TABLESPACE pg_default;
COMMENT ON TABLE bookdet IS 'Book details table';
COMMENT ON COLUMN bookdet."To6Third" IS 'Time range for book scheduling (in minutes from midnight)';
COMMENT ON COLUMN bookdet."To6Second" IS 'Time range for book scheduling (in minutes from midnight)';
COMMENT ON COLUMN bookdet."To6" IS 'Sunday Close Time (in minutes from midnight format)';
COMMENT ON COLUMN bookdet."To5Third" IS 'Time range for book scheduling (in minutes from midnight)';
COMMENT ON COLUMN bookdet."To5Second" IS 'Time range for book scheduling (in minutes from midnight)';
COMMENT ON COLUMN bookdet."To5" IS 'Saturday Close Time (in minutes from midnight format)';
COMMENT ON COLUMN bookdet."To4Third" IS 'Time range for book scheduling (in minutes from midnight)';
COMMENT ON COLUMN bookdet."To4Second" IS 'Time range for book scheduling (in minutes from midnight)';
COMMENT ON COLUMN bookdet."To4" IS 'Friday Close Time (in minutes from midnight format)';
COMMENT ON COLUMN bookdet."To3Third" IS 'Time range for book scheduling (in minutes from midnight)';
COMMENT ON COLUMN bookdet."To3Second" IS 'Time range for book scheduling (in minutes from midnight)';
COMMENT ON COLUMN bookdet."To3" IS 'Thursday Close Time (in minutes from midnight format)';
COMMENT ON COLUMN bookdet."To2Third" IS 'Time range for book scheduling (in minutes from midnight)';
COMMENT ON COLUMN bookdet."To2Second" IS 'Time range for book scheduling (in minutes from midnight)';
COMMENT ON COLUMN bookdet."To2" IS 'Wednesday Close Time (in minutes from midnight format)';
COMMENT ON COLUMN bookdet."To1Third" IS 'Time range for book scheduling (in minutes from midnight)';
COMMENT ON COLUMN bookdet."To1Second" IS 'Time range for book scheduling (in minutes from midnight)';
COMMENT ON COLUMN bookdet."To1" IS 'Tuesday Close Time (in minutes from midnight format)';
COMMENT ON COLUMN bookdet."To0Third" IS 'Time range for book scheduling (in minutes from midnight)';
COMMENT ON COLUMN bookdet."To0Second" IS 'Time range for book scheduling (in minutes from midnight)';
COMMENT ON COLUMN bookdet."To0" IS 'Monday Close Time (in minutes from midnight format)';
COMMENT ON COLUMN bookdet."StartDate" IS 'Date this book detail begins';
COMMENT ON COLUMN bookdet."Opened6" IS 'Appt Book open on Sunday (0 = No, 1 = Yes)';
COMMENT ON COLUMN bookdet."Opened5" IS 'Appt Book open on Saturday (0 = No, 1 = Yes)';
COMMENT ON COLUMN bookdet."Opened4" IS 'Appt Book open on Friday (0 = No, 1 = Yes)';
COMMENT ON COLUMN bookdet."Opened3" IS 'Appt Book open on Thursday (0 = No, 1 = Yes)';
COMMENT ON COLUMN bookdet."Opened2" IS 'Appt Book open on Wednesday (0 = No, 1 = Yes)';
COMMENT ON COLUMN bookdet."Opened1" IS 'Appt Book open on Tuesday (0 = No, 1 = Yes)';
COMMENT ON COLUMN bookdet."Opened0" IS 'Appt Book open on Monday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN bookdet."NumChair" IS 'Number of Chairs in the Appt Book (max 50)';
COMMENT ON COLUMN bookdet."From6Third" IS 'Time range for book scheduling (in minutes from midnight)';
COMMENT ON COLUMN bookdet."From6Second" IS 'Time range for book scheduling (in minutes from midnight)';
COMMENT ON COLUMN bookdet."From6" IS 'Sunday Start Time (in minutes from midnight format)';
COMMENT ON COLUMN bookdet."From5Third" IS 'Time range for book scheduling (in minutes from midnight)';
COMMENT ON COLUMN bookdet."From5Second" IS 'Time range for book scheduling (in minutes from midnight)';
COMMENT ON COLUMN bookdet."From5" IS 'Saturday Start Time (in minutes from midnight format)';
COMMENT ON COLUMN bookdet."From4Third" IS 'Time range for book scheduling (in minutes from midnight)';
COMMENT ON COLUMN bookdet."From4Second" IS 'Time range for book scheduling (in minutes from midnight)';
COMMENT ON COLUMN bookdet."From4" IS 'Friday Start Time (in minutes from midnight format)';
COMMENT ON COLUMN bookdet."From3Third" IS 'Time range for book scheduling (in minutes from midnight)';
COMMENT ON COLUMN bookdet."From3Second" IS 'Time range for book scheduling (in minutes from midnight)';
COMMENT ON COLUMN bookdet."From3" IS 'Thursday Start Time (in minutes from midnight format)';
COMMENT ON COLUMN bookdet."From2Third" IS 'Time range for book scheduling (in minutes from midnight)';
COMMENT ON COLUMN bookdet."From2Second" IS 'Time range for book scheduling (in minutes from midnight)';
COMMENT ON COLUMN bookdet."From2" IS 'Wednesday Start Time (in minutes from midnight format)';
COMMENT ON COLUMN bookdet."From1Third" IS 'Time range for book scheduling (in minutes from midnight)';
COMMENT ON COLUMN bookdet."From1Second" IS 'Time range for book scheduling (in minutes from midnight)';
COMMENT ON COLUMN bookdet."From1" IS 'Tuesday Start Time (in minutes from midnight format)';
COMMENT ON COLUMN bookdet."From0Third" IS 'Time range for book scheduling (in minutes from midnight)';
COMMENT ON COLUMN bookdet."From0Second" IS 'Time range for book scheduling (in minutes from midnight)';
COMMENT ON COLUMN bookdet."From0" IS 'Monday Start Time (in minutes from midnight format)';
COMMENT ON COLUMN bookdet."EndDate" IS 'Date this book detail ends';
COMMENT ON COLUMN bookdet."BookDetail" IS 'Primary key, Internal ID (from sequence), ID code to identify the book detail record';
COMMENT ON COLUMN bookdet."Book" IS 'Book that the detail record is for. Ptr to BOOK.Book';


CREATE  TABLE bookprov (
  "BookDetail" numeric(10,0) NOT NULL,
  "Provider" character(10) NOT NULL,
  "Order" numeric(5,0),
  CONSTRAINT bookprov_primary PRIMARY KEY ("BookDetail", "Provider")
) ;
COMMENT ON TABLE bookprov IS 'List of providers belonging to a book';
COMMENT ON COLUMN bookprov."Provider" IS 'Provider code';
COMMENT ON COLUMN bookprov."Order" IS 'Display Order';
COMMENT ON COLUMN bookprov."BookDetail" IS 'Record ID of the BOOKDET record it ties to';


CREATE  TABLE breakt (
  "BreakT" numeric(10,0) NOT NULL,
  "Description" character varying(30),
  "ProdType" character(1),
  "Minutes" numeric(5,0),
  "BeginMinutes" numeric(10,0),
  "EndMinutes" numeric(10,0),
  CONSTRAINT breakt_primary PRIMARY KEY ("BreakT")
) ;
COMMENT ON TABLE breakt IS 'Break Times';
COMMENT ON COLUMN breakt."ProdType" IS 'Provider type that the break time applies to, ptr to PRODTYPE.Code';
COMMENT ON COLUMN breakt."Minutes" IS 'Break length, in minutes.';
COMMENT ON COLUMN breakt."EndMinutes" IS 'End time of the break, in minutes into the shift. ';
COMMENT ON COLUMN breakt."Description" IS 'Description of the break time.';
COMMENT ON COLUMN breakt."BreakT" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN breakt."BeginMinutes" IS 'Start of the break, in minutes into the shift.';


CREATE  TABLE cancel (
  "Cancel" character(6) NOT NULL,
  "Description" character(30),
  "Excused" numeric(5,0),
  "Type" numeric(5,0),
  "Default" numeric(5,0),
  "ChargeCode" character(6),
  "Inactive" numeric(5,0),
  CONSTRAINT cancel_primary PRIMARY KEY ("Cancel")
) ;
COMMENT ON TABLE cancel IS 'Cancellation Codes';
COMMENT ON COLUMN cancel."Type" IS '0 (Cancellation), 1 (Failed)';
COMMENT ON COLUMN cancel."Inactive" IS 'Make Cancel Code Inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN cancel."Excused" IS 'Academic cancellation? (0 = No, 1 = Yes)';
COMMENT ON COLUMN cancel."Description" IS 'Description of the cancellation code';
COMMENT ON COLUMN cancel."Default" IS '0 (No), 1 (Yes)';
COMMENT ON COLUMN cancel."ChargeCode" IS 'Office Charge Code to charge for this cancel/fail reason';
COMMENT ON COLUMN cancel."Cancel" IS 'Code to identify the cancellation reason';


CREATE  TABLE capfwarn (
  "CApFWarn" numeric(10,0) NOT NULL,
  "CApReq" numeric(10,0),
  "Type" numeric(5,0),
  "Id" numeric(10,0),
  "Treatment" numeric(5,0),
  "WarnId" numeric(5,0),
  "WarnMessage" character varying(255),
  "CreateAudit" numeric(10,0),
  "State" numeric(5,0),
  CONSTRAINT capfwarn_primary PRIMARY KEY ("CApFWarn")
) ;
CREATE INDEX IF NOT EXISTS capfwarn_capreq ON capfwarn USING btree ("CApReq") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS capfwarn_typeid ON capfwarn USING btree ("Type", "Id", "Treatment") TABLESPACE pg_default;
COMMENT ON TABLE capfwarn IS 'Clinical financial warning for patient approval';
COMMENT ON COLUMN capfwarn."WarnMessage" IS 'Warning message';
COMMENT ON COLUMN capfwarn."WarnId" IS 'Warning message Id';
COMMENT ON COLUMN capfwarn."Type" IS 'TRX Type; 1 - I/C tx, 5 - plan tx';
COMMENT ON COLUMN capfwarn."Treatment" IS 'TRX Treatment';
COMMENT ON COLUMN capfwarn."State" IS 'State of the warning; 0 - open, 1 - acknowledged';
COMMENT ON COLUMN capfwarn."Id" IS 'TRX Id';
COMMENT ON COLUMN capfwarn."CreateAudit" IS 'Ptr to AUDITHIS.Audit; audit information when record is added';
COMMENT ON COLUMN capfwarn."CApReq" IS 'Ptr to CAPREQ.CApReq, Parent request record';
COMMENT ON COLUMN capfwarn."CApFWarn" IS 'Primary key, sequence field';


CREATE  TABLE capreq (
  "CApReq" numeric(10,0) NOT NULL,
  "ReqType" numeric(5,0),
  "User" numeric(10,0),
  "Producer" character(10),
  "EntryAudit" numeric(10,0),
  "Patient" numeric(10,0),
  "Clinic" numeric(10,0),
  "Chair" numeric(10,0),
  "State" numeric(5,0),
  "UpdateAudit" numeric(10,0),
  CONSTRAINT capreq_primary PRIMARY KEY ("CApReq")
) ;
COMMENT ON TABLE capreq IS 'Clinical request for patient approval';
COMMENT ON COLUMN capreq."User" IS 'Ptr to USERS.User; user making the request';
COMMENT ON COLUMN capreq."UpdateAudit" IS 'Ptr to AUDITHIS.Audit; audit information when State is altered';
COMMENT ON COLUMN capreq."State" IS 'State of the request; 0 - open, 1 - acknowledged, 2 - approved/closed';
COMMENT ON COLUMN capreq."ReqType" IS 'Type of Request; 0 - request for approval, 1 - request for help';
COMMENT ON COLUMN capreq."Producer" IS 'Ptr to PRODUCER.Producer; producer the request is for';
COMMENT ON COLUMN capreq."Patient" IS 'Ptr to PATIENT.Patient; patient this request is for';
COMMENT ON COLUMN capreq."EntryAudit" IS 'Ptr to AUDITHIS.Audit; audit record with date/time/user/station';
COMMENT ON COLUMN capreq."Clinic" IS 'Ptr to CLINIC.Clinic';
COMMENT ON COLUMN capreq."Chair" IS 'Ptr to CHAIR.Chair';
COMMENT ON COLUMN capreq."CApReq" IS 'Primary key, sequence field';


CREATE  TABLE capreqbi (
  "CApReqBi" numeric(10,0) NOT NULL,
  "CApReq" numeric(10,0),
  "Clinic" numeric(10,0),
  "Practice" numeric(5,0),
  "Location" character(6),
  "BillingId" character(10),
  "IsMedical" numeric(5,0),
  "PolicyId1" numeric(10,0),
  "PolicyId2" numeric(10,0),
  "PolicyId3" numeric(10,0),
  "Discipline" character(15),
  CONSTRAINT capreqbi_primary PRIMARY KEY ("CApReqBi")
) ;
CREATE INDEX IF NOT EXISTS capreqbi_capreq ON capreqbi USING btree ("CApReq") TABLESPACE pg_default;
COMMENT ON TABLE capreqbi IS 'Clinical request billing information for patient approval';
COMMENT ON COLUMN capreqbi."Practice" IS 'Ptr to PRACTICE.Id';
COMMENT ON COLUMN capreqbi."PolicyId3" IS 'Ptr to POLICY.PolicyId; tertiary patient policy to bill';
COMMENT ON COLUMN capreqbi."PolicyId2" IS 'Ptr to POLICY.PolicyId; secondary patient policy to bill';
COMMENT ON COLUMN capreqbi."PolicyId1" IS 'Ptr to POLICY.PolicyId; primary patient policy to bill';
COMMENT ON COLUMN capreqbi."Location" IS 'Ptr to LOCATION.Location';
COMMENT ON COLUMN capreqbi."IsMedical" IS 'Is medical claim?  0 - no, 1 - yes';
COMMENT ON COLUMN capreqbi."Discipline" IS 'Ptr to CLASS.Class if applicable';
COMMENT ON COLUMN capreqbi."Clinic" IS 'Ptr to CLINIC.Clinic';
COMMENT ON COLUMN capreqbi."CApReqBi" IS 'Primary key, sequence field';
COMMENT ON COLUMN capreqbi."CApReq" IS 'Ptr to CAPREQ.CApReq, Parent request record';
COMMENT ON COLUMN capreqbi."BillingId" IS 'Ptr to PRODUCER.Producer of Type 0 or 2';


CREATE  TABLE capreqit (
  "CApReqIt" numeric(10,0) NOT NULL,
  "CApReq" numeric(10,0),
  "Type" numeric(5,0),
  "Id" numeric(10,0),
  "Status" numeric(5,0),
  "UpdateAudit" numeric(10,0),
  CONSTRAINT capreqit_primary PRIMARY KEY ("CApReqIt")
) ;
CREATE INDEX IF NOT EXISTS capreqit_capreq ON capreqit USING btree ("CApReq") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS capreqit_typeid ON capreqit USING btree ("Type", "Id") TABLESPACE pg_default;
COMMENT ON TABLE capreqit IS 'Clinical request items for patient approval';
COMMENT ON COLUMN capreqit."UpdateAudit" IS 'Ptr to AUDITHIS.Audit; audit information when the Status is altered';
COMMENT ON COLUMN capreqit."Type" IS 'Type of records; 1 - notes, 2 - txs, 3 - problems, 4 - soap notes, 5 - ortho visits, 6 - other notes, 7 - forms, 8 - web forms, 9 - perio, 10 - letters, 11 - lab orders, 12 - elab orders, 13 - surgery, 14 - surgery waste, 15 - tx plan';
COMMENT ON COLUMN capreqit."Status" IS 'Status of the individual request item; 0 - N/A, 1 - approved, 2 - rejected, 3 - revoked, 4 - obsolete';
COMMENT ON COLUMN capreqit."Id" IS 'Unique Id of the given record type; examples: ChartLnk.Id if txs, Notes2.Auto if notes, etc. ';
COMMENT ON COLUMN capreqit."CApReqIt" IS 'Primary key, sequence field';
COMMENT ON COLUMN capreqit."CApReq" IS 'Ptr to CAPREQ.CApReq, Parent request record';


CREATE  TABLE caradj (
  "CAReason" character(6) NOT NULL,
  "Company" character(6) NOT NULL,
  "PayeeIdCode" character(15) NOT NULL,
  "AdjType" numeric(5,0),
  "AdjCode" character(6),
  CONSTRAINT caradj_primary PRIMARY KEY ("CAReason", "Company", "PayeeIdCode")
) ;
COMMENT ON TABLE caradj IS 'New Claim Adjustment Reason Adjustments Table';
COMMENT ON COLUMN caradj."PayeeIdCode" IS 'Payee Id Code (optional)';
COMMENT ON COLUMN caradj."Company" IS 'Insurance Company Code (optional)';
COMMENT ON COLUMN caradj."CAReason" IS 'Claim Adjustment Reason Code';
COMMENT ON COLUMN caradj."AdjType" IS 'Adjustment Processing? (0 = No, 1 = transfer to patient, 2 = write-off)';
COMMENT ON COLUMN caradj."AdjCode" IS 'Adjustment Code';


CREATE  TABLE careason (
  "CAReason" character(6) NOT NULL,
  "Description" character varying(200),
  "Type" numeric(5,0),
  "GroupCode" character(6),
  "Inactive" numeric(5,0),
  CONSTRAINT careason_primary PRIMARY KEY ("CAReason")
) ;
COMMENT ON TABLE careason IS 'Claim Adjustment Reasons';
COMMENT ON COLUMN careason."Type" IS '0=Other, 1=Deductible, 2=Co-Ins, 3=Co-Pay';
COMMENT ON COLUMN careason."Inactive" IS 'Make Reason Inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN careason."GroupCode" IS 'CO, CR, OA, PI, PR (in "EDI" Specs)';
COMMENT ON COLUMN careason."Description" IS 'Long description of adjustment';
COMMENT ON COLUMN careason."CAReason" IS 'Claim adjustment reason, primary key';


CREATE  TABLE carequality_docpull (
  "RedoxPatientId" character varying(255) NOT NULL,
  "OrganizationId" character varying(255) NOT NULL,
  "LastPullDateTime" timestamp without time zone,
  CONSTRAINT carequality_docpull_pk PRIMARY KEY ("RedoxPatientId", "OrganizationId")
) ;
COMMENT ON TABLE carequality_docpull IS 'Table for storing the LastPullDateTime of documents for Carequality patients.';
COMMENT ON COLUMN carequality_docpull."RedoxPatientId" IS 'Primary key component. Ptr to CQ_PATIENT.RedoxPatientId ';
COMMENT ON COLUMN carequality_docpull."OrganizationId" IS 'Primary key component. Id of the org rec’d in a LocationQuery response';
COMMENT ON COLUMN carequality_docpull."LastPullDateTime" IS 'Date and time of the last pull/sync from the Carequality network';


CREATE  TABLE carequality_documents (
  "Id" numeric(10,0) NOT NULL DEFAULT 0,
  "Patient" numeric(10,0) NOT NULL DEFAULT 0,
  "ExpectedTotal" numeric(10,0) NOT NULL DEFAULT 0,
  "AddCount" numeric(10,0) NOT NULL DEFAULT 0,
  "TopicName" character varying(255),
  CONSTRAINT carequality_documents_primary PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE carequality_documents IS 'Table for storing temporary Carequality document records.';
COMMENT ON COLUMN carequality_documents."TopicName" IS 'The push notification Topic Name';
COMMENT ON COLUMN carequality_documents."Patient" IS 'Patient Id field';
COMMENT ON COLUMN carequality_documents."Id" IS 'Primary Sequence key ';
COMMENT ON COLUMN carequality_documents."ExpectedTotal" IS 'The total number of documents expected to be added to the patient clinical chart';
COMMENT ON COLUMN carequality_documents."AddCount" IS 'The total number of documents added to the patient clinical chart';


CREATE  TABLE carequality_error_log (
  "Id" numeric(10,0) NOT NULL DEFAULT 0,
  "LogId" numeric(10,0) NOT NULL DEFAULT 0,
  "DateTime" timestamp without time zone,
  "Application" character varying(255),
  error clob,
  CONSTRAINT carequality_error_log_primary PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE carequality_error_log IS 'Table for storing Carequality error logs.';
COMMENT ON COLUMN carequality_error_log.error IS 'the error description';
COMMENT ON COLUMN carequality_error_log."LogId" IS 'Ptr to CAREQUALITY_LOG';
COMMENT ON COLUMN carequality_error_log."Id" IS 'Primary key sequence field';
COMMENT ON COLUMN carequality_error_log."DateTime" IS 'Date and time of the error log';
COMMENT ON COLUMN carequality_error_log."Application" IS 'Indicates if it came from queue-processor, public-api, or job-utils';


CREATE  TABLE carequality_event (
  "Patient" numeric(10,0) NOT NULL DEFAULT 0,
  "EventType" numeric(5,0) NOT NULL DEFAULT 0,
  "EventDate" timestamp without time zone,
  "Status" numeric(5,0) NOT NULL DEFAULT 0,
  "OtherId" numeric(10,0) NOT NULL DEFAULT 0,
  CONSTRAINT carequality_event_primary PRIMARY KEY ("Patient", "EventType", "OtherId")
) ;
COMMENT ON TABLE carequality_event IS 'Table for storing Carequality events.';
COMMENT ON COLUMN carequality_event."Status" IS 'Status of the event: 0 - pending, 1 - processing, 2 - sent, 3 - not sent (carequality off), 4 - not sent (patient missing consent), 5 - not sent (other)';
COMMENT ON COLUMN carequality_event."Patient" IS 'Primary key Patient field';
COMMENT ON COLUMN carequality_event."OtherId" IS 'Primary key Additional record id (eg. bad patient in chart merge).';
COMMENT ON COLUMN carequality_event."EventType" IS 'Primary key Event Type field: 0 - Patient New, 1 - Patient Update, 2 - Patient Merge, 3 - Visit Push';
COMMENT ON COLUMN carequality_event."EventDate" IS 'Date and time of the event';


CREATE  TABLE carequality_eventhis (
  "EventHis" numeric(10,0) NOT NULL DEFAULT 0,
  "Patient" numeric(10,0) NOT NULL DEFAULT 0,
  "EventType" numeric(5,0) NOT NULL DEFAULT 0,
  "EventDate" timestamp without time zone,
  "Status" numeric(5,0) NOT NULL DEFAULT 0,
  "AddDateTime" timestamp without time zone,
  "OtherId" numeric(10,0) NOT NULL DEFAULT 0,
  CONSTRAINT carequality_eventhis_primary PRIMARY KEY ("EventHis")
) ;
COMMENT ON TABLE carequality_eventhis IS 'Table for storing Carequality event history records.';
COMMENT ON COLUMN carequality_eventhis."Status" IS 'Status of the event: 0 - pending, 1 - processing, 2 - sent, 3 - not sent (carequality off), 4 - not sent (patient missing consent), 5 - not sent (other)';
COMMENT ON COLUMN carequality_eventhis."Patient" IS 'Patient Id field';
COMMENT ON COLUMN carequality_eventhis."OtherId" IS 'Additional record id (eg. bad patient in chart merge).';
COMMENT ON COLUMN carequality_eventhis."EventType" IS 'Event Type field: 0 - Patient New, 1 - Patient Update, 2 - Patient Merge, 3 - Visit Push';
COMMENT ON COLUMN carequality_eventhis."EventHis" IS 'Primary Sequence key ';
COMMENT ON COLUMN carequality_eventhis."EventDate" IS 'Date and time of the event';
COMMENT ON COLUMN carequality_eventhis."AddDateTime" IS 'Date and time when this entry is created';


CREATE  TABLE carequality_log (
  "Id" numeric(10,0) NOT NULL DEFAULT 0,
  "SessionId" numeric(10,0) NOT NULL DEFAULT 0,
  "ParentId" numeric(10,0) NOT NULL DEFAULT 0,
  "DateTime" timestamp without time zone,
  url clob,
  body clob,
  response clob,
  "OrganizationOID" character varying(255),
  CONSTRAINT carequality_log_primary PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE carequality_log IS 'Table for storing Carequality logs.';
COMMENT ON COLUMN carequality_log.url IS 'complete url of the request, including query parameters';
COMMENT ON COLUMN carequality_log.response IS 'the raw json body of the api response';
COMMENT ON COLUMN carequality_log.body IS 'the raw json body of the api call';
COMMENT ON COLUMN carequality_log."SessionId" IS 'Session Id';
COMMENT ON COLUMN carequality_log."ParentId" IS 'Id of the CAREQUALITY_LOG that resulted in this internal API call';
COMMENT ON COLUMN carequality_log."OrganizationOID" IS 'Organization Object Identifier';
COMMENT ON COLUMN carequality_log."Id" IS 'Primary key sequence field';
COMMENT ON COLUMN carequality_log."DateTime" IS 'Date and time of the log';


CREATE  TABLE carequality_patient (
  "Id" numeric(10,0) NOT NULL DEFAULT 0,
  "Patient" numeric(10,0) NOT NULL DEFAULT 0,
  "RedoxPatientId" character varying(255),
  "RedoxPatientIdType" character varying(255),
  "LogId" numeric(10,0) NOT NULL DEFAULT 0,
  "CreatedDateTime" timestamp without time zone,
  "Deleted" numeric(5,0) NOT NULL DEFAULT 0,
  "DeletedDateTime" timestamp without time zone,
  "Inactive" numeric(5,0) NOT NULL DEFAULT 0,
  "LastPullDateTime" timestamp without time zone,
  "PullChangeDateTime" timestamp without time zone,
  "LastVisitPushDateTime" timestamp without time zone,
  "LastPatientPushDateTime" timestamp without time zone,
  "AxiumChangeDateTime" timestamp without time zone,
  CONSTRAINT carequality_patient_primary PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE carequality_patient IS 'Table for storing Carequality patients.';
COMMENT ON COLUMN carequality_patient."RedoxPatientIdType" IS 'The type of ID in the Carequality network';
COMMENT ON COLUMN carequality_patient."RedoxPatientId" IS 'Id of the patient in the Carequality network';
COMMENT ON COLUMN carequality_patient."PullChangeDateTime" IS 'Date and time of the last update made to the patient record in axiUm';
COMMENT ON COLUMN carequality_patient."Patient" IS 'ptr to PATIENT.Patient';
COMMENT ON COLUMN carequality_patient."LogId" IS 'Id of the CAREQUALITY_LOG entry that resulted in this patient request';
COMMENT ON COLUMN carequality_patient."LastVisitPushDateTime" IS 'Date and time of the last Visit push/send to the Carequality network';
COMMENT ON COLUMN carequality_patient."LastPullDateTime" IS 'Date and time of the last pull/sync from the Carequality network';
COMMENT ON COLUMN carequality_patient."LastPatientPushDateTime" IS 'Date and time of the last Patient push/send to the Carequality network';
COMMENT ON COLUMN carequality_patient."Inactive" IS 'if 1, Disables synchronization for this link';
COMMENT ON COLUMN carequality_patient."Id" IS 'Primary key sequence field,';
COMMENT ON COLUMN carequality_patient."DeletedDateTime" IS 'Date and time the link was deleted';
COMMENT ON COLUMN carequality_patient."Deleted" IS '0: no, 1: yes';
COMMENT ON COLUMN carequality_patient."CreatedDateTime" IS 'Date and time the link was created';
COMMENT ON COLUMN carequality_patient."AxiumChangeDateTime" IS 'Date and time of the last update made to the patient record in axiUm';


CREATE  TABLE caseform (
  "CaseType" character(6) NOT NULL,
  "TimeOutForm" character varying(255),
  "TimeOutQuestion" character varying(255),
  "DOSForm" character varying(255),
  "DOSQuestion" character varying(255),
  CONSTRAINT caseform_primary PRIMARY KEY ("CaseType")
) ;
COMMENT ON TABLE caseform IS 'Case type forms for Surgery module.';
COMMENT ON COLUMN caseform."TimeOutQuestion" IS 'Reference Code for the Question that will be used to associate the Time Out Form to the Surgery Date. Points to EF_QUESTION.RefCode.';
COMMENT ON COLUMN caseform."TimeOutForm" IS 'Time Out Form Reference code. Points to EF_FORM.RefCode.';
COMMENT ON COLUMN caseform."DOSQuestion" IS 'Reference Code for the Question that will be used to associate the Day of Surgery Form to the Surgery Date. Points to EF_QUESTION.RefCode.';
COMMENT ON COLUMN caseform."DOSForm" IS 'Day of Surgery Form Reference code. Points to EF_FORM.RefCode.';
COMMENT ON COLUMN caseform."CaseType" IS 'Primary key, unique code to identify the Case Type.';


CREATE  TABLE casereqform (
  "CaseType" character(6) NOT NULL,
  "FormCode" character(6) NOT NULL,
  CONSTRAINT casereqform_primary PRIMARY KEY ("CaseType", "FormCode")
) ;
COMMENT ON TABLE casereqform IS 'specifies forms to add when a new case is created';
COMMENT ON COLUMN casereqform."FormCode" IS 'Primary key, the form to add';
COMMENT ON COLUMN casereqform."CaseType" IS 'Primary key, the case type';


CREATE  TABLE casetype (
  "CaseType" character(6) NOT NULL,
  "Description" character varying(30),
  "Inactive" numeric(5,0),
  CONSTRAINT casetype_primary PRIMARY KEY ("CaseType")
) ;
COMMENT ON TABLE casetype IS 'Case types for Surgery module.';
COMMENT ON COLUMN casetype."Inactive" IS 'Case Type is inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN casetype."Description" IS 'Description of the Case Type.';
COMMENT ON COLUMN casetype."CaseType" IS 'Primary key, unique code to identify the Case Type.';


CREATE  TABLE ccdapat (
  "CCDASch" numeric(10,0) NOT NULL,
  "PatientId" numeric(10,0) NOT NULL,
  CONSTRAINT ccdapat_primary PRIMARY KEY ("CCDASch", "PatientId")
) ;
COMMENT ON TABLE ccdapat IS 'Table for storing patient ids tied to the CCDA schedule';
COMMENT ON COLUMN ccdapat."PatientId" IS 'Id of patient to be exported';
COMMENT ON COLUMN ccdapat."CCDASch" IS 'Primary key, CCDASCH record the patient is tied to';


CREATE  TABLE ccdasch (
  "CCDASch" numeric(10,0) NOT NULL,
  "CCDAType" numeric(5,0),
  "SaveToAttach" numeric(5,0),
  "AtSect" numeric(10,0),
  "AtTab" numeric(10,0),
  "SaveAsFile" numeric(5,0),
  "HasDateTimeRange" numeric(5,0),
  "FromDate" timestamp without time zone,
  "FromTime" numeric(10,0),
  "ToDate" timestamp without time zone,
  "ToTime" numeric(10,0),
  "SchStartDate" timestamp without time zone,
  "SchStartTime" numeric(10,0),
  "CanRepeat" numeric(5,0),
  "CycleType" numeric(5,0),
  "CycleWeekday" numeric(5,0),
  "SchEndDate" timestamp without time zone,
  selectptquery clob,
  "Audit" numeric(10,0),
  "OracleDir" character varying(255),
  "FilePrefix" character varying(255),
  CONSTRAINT ccdasch_primary PRIMARY KEY ("CCDASch")
) ;
COMMENT ON TABLE ccdasch IS 'Table for storing information regarding the schedule setup for CCDA export';
COMMENT ON COLUMN ccdasch.selectptquery IS 'Query for selecting patient';
COMMENT ON COLUMN ccdasch."ToTime" IS 'To time';
COMMENT ON COLUMN ccdasch."ToDate" IS 'To date';
COMMENT ON COLUMN ccdasch."SchStartTime" IS 'Schedule start time';
COMMENT ON COLUMN ccdasch."SchStartDate" IS 'Schedule start date';
COMMENT ON COLUMN ccdasch."SchEndDate" IS 'Schedule end date';
COMMENT ON COLUMN ccdasch."SaveToAttach" IS 'Save to attachment?: 0 = no, 1 = yes';
COMMENT ON COLUMN ccdasch."SaveAsFile" IS 'Save as file?: 0 = no, 1 = yes';
COMMENT ON COLUMN ccdasch."OracleDir" IS 'Oracle Directory to use for placing the export files';
COMMENT ON COLUMN ccdasch."HasDateTimeRange" IS 'Has date/time fields?: 0 = no, 1 = yes';
COMMENT ON COLUMN ccdasch."FromTime" IS 'From time';
COMMENT ON COLUMN ccdasch."FromDate" IS 'From date';
COMMENT ON COLUMN ccdasch."FilePrefix" IS 'Filename prefix to use for the export files';
COMMENT ON COLUMN ccdasch."CycleWeekday" IS 'cycle weekday: 1 = Sunday, 2 = Monday...';
COMMENT ON COLUMN ccdasch."CycleType" IS 'Cycle type: 0 = daily, 1 = weekly, 2 = monthly, 3 = annually';
COMMENT ON COLUMN ccdasch."CanRepeat" IS 'Can Repeat?: 0 = no, 1 = yes';
COMMENT ON COLUMN ccdasch."CCDAType" IS 'Type of CCDA: 0=Transition of Care, 1=Ambulatory, 2=Export';
COMMENT ON COLUMN ccdasch."CCDASch" IS 'Primary key, sequence field';
COMMENT ON COLUMN ccdasch."Audit" IS 'Audit Id, audit record of the user/station that last updated this information';
COMMENT ON COLUMN ccdasch."AtTab" IS 'Attachment tab (if applicable) ';
COMMENT ON COLUMN ccdasch."AtSect" IS 'Attachment section (if applicable) ';


CREATE  TABLE cformcd (
  "FormCode" character(6) NOT NULL,
  "Description" character(30),
  "FormType" numeric(5,0),
  "LaserDrawn" numeric(5,0),
  "MultiPage" numeric(5,0),
  "CFormCdId" numeric(10,0),
  "UseDigitalSig" numeric(5,0),
  "PrintPtSigDate" numeric(5,0),
  "BlockPtSig" numeric(5,0),
  "UseApprovalFaculty" numeric(5,0),
  "MarkMissingTeeth" numeric(5,0),
  "PaidAssign" numeric(5,0),
  "PaidNonAssign" numeric(5,0),
  "UseNPI" numeric(5,0),
  "UseTreatDrToBill" numeric(5,0),
  "Punctuation" numeric(5,0),
  "PrintClaimNo" numeric(5,0),
  "DefaultOrtho" numeric(5,0),
  CONSTRAINT cformcd_primary PRIMARY KEY ("FormCode")
) ;
COMMENT ON TABLE cformcd IS 'Claim form codes';
COMMENT ON COLUMN cformcd."UseTreatDrToBill" IS 'Use treating dentist as billing entity? (0 = No, 1 = Yes)';
COMMENT ON COLUMN cformcd."UseNPI" IS 'US only - National Provider Identification 0 = Not to use "NPI", 1 = Use "NPI", 2 = Use "NPI" only - no other IDs allowed';
COMMENT ON COLUMN cformcd."UseDigitalSig" IS 'Use the digital signature? (0 = No, 1 = Yes)';
COMMENT ON COLUMN cformcd."UseApprovalFaculty" IS 'Use approval faculty billing ID on claim? (0 = No, 1 = Yes)';
COMMENT ON COLUMN cformcd."Punctuation" IS 'Suppress punctuation? (0 = No, 1 = Suppress decimals only, 2 = Suppress decimals, commas, and others)';
COMMENT ON COLUMN cformcd."PrintPtSigDate" IS 'Print patient signature date (0 = No, 1 = Yes)';
COMMENT ON COLUMN cformcd."PrintClaimNo" IS 'Print claim number? (0 = No, 1 = Yes)';
COMMENT ON COLUMN cformcd."PaidNonAssign" IS 'What does the calculation for box 31 include? (0=both insurance and patient payments, 1= insurance payments only, 2= patient payments only). ';
COMMENT ON COLUMN cformcd."PaidAssign" IS 'What does the calculation for box 31 include? (0=both insurance and patient payments, 1= insurance payments only, 2= patient payments only). ';
COMMENT ON COLUMN cformcd."MultiPage" IS 'Multi page? (0 = No, 1 = Yes)';
COMMENT ON COLUMN cformcd."MarkMissingTeeth" IS 'Mark missing teeth on claim form? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN cformcd."LaserDrawn" IS 'Laser drawn? (0 = No, 1 = Yes)';
COMMENT ON COLUMN cformcd."FormType" IS 'Type of Form: 0: ADA 1994, 1: ADA 2000, 2: HCFA, 3: Penn. Medicaid, 4: BCBS Medical HCFA, 5: BCBS Dental ADA, 6: Mich Medicaid (HCFA), 7: Mich. Medicaid (ADA), 8: Denti-Cal, 9: Delta Dental (CA Govt Pgm), 10: MUSC Medicaid (ADA), 11: Delta GP05 "CIF", 12: ADA 2002, 13: Denti-Cal DC 003 "CIF", 14: Priv. Med. 60-1C "CIF", 15: Delta 495 "CIF", 16: Maryland Medicaid, 17: Mass. Health, 18: ADA 2002 Original, 19: Florida Medicaid, 20: ADA 2006 "NPI", 21: HCFA 2006 ("NPI"), 22: Ohio Medicaid Pre-Auth, 23: Delta Dental "NPI" (CA Govt Pgm), 24: Denti-Cal "NPI", 25: Mich. Medicaid Pre-Auth, 26: Illinois HFS 2360 Claim, 27: ADA 2012 ("NPI"), 100: Standard [Canada Only]';
COMMENT ON COLUMN cformcd."FormCode" IS 'Primary key, ID code to identify the claim form. ';
COMMENT ON COLUMN cformcd."Description" IS 'Description of the form';
COMMENT ON COLUMN cformcd."DefaultOrtho" IS 'Flag to indicate whether to default the Ortho related info from the linked tx when doing Ortho Billing (0=No, 1=Yes)';
COMMENT ON COLUMN cformcd."CFormCdId" IS 'Internal ID from sequence';
COMMENT ON COLUMN cformcd."BlockPtSig" IS 'Block out assignment of payment for non assignment claims (0 = No, 1 = Yes)';


CREATE  TABLE chair (
  "Chair" numeric(10,0) NOT NULL,
  "Name" character(15),
  "Description" character(63),
  "Clinic" numeric(10,0),
  "Row" numeric(5,0),
  "Col" numeric(5,0),
  "Unavailable" numeric(5,0),
  "Import" character(10),
  "Location" character(6),
  "BlockSize" numeric(5,0),
  "IsOverflow" numeric(5,0),
  "OverflowOrder" numeric(5,0),
  CONSTRAINT chair_primary PRIMARY KEY ("Chair")
) ;
CREATE INDEX IF NOT EXISTS chair_clinic ON chair USING btree ("Clinic", "Unavailable", "Chair", "Name") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS chair_import ON chair USING btree ("Import") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS chair_name ON chair USING btree ("Name") TABLESPACE pg_default;
COMMENT ON TABLE chair IS 'Chairs';
COMMENT ON COLUMN chair."Unavailable" IS 'Chair unavailable / out of service? (0 = No, 1 = Yes)';
COMMENT ON COLUMN chair."Row" IS 'Row ID of the chair within the scheduler.';
COMMENT ON COLUMN chair."OverflowOrder" IS 'if IsOverflow=1, the overflow order for the chair (0=First, 1=Second, etc..)';
COMMENT ON COLUMN chair."Name" IS 'Name assigned to the chair.';
COMMENT ON COLUMN chair."Location" IS 'Location that charts should be delivered for appointment in the chair, ptr to LOCATION.Location';
COMMENT ON COLUMN chair."IsOverflow" IS 'Overflow chair? (0 = No, 1 = Yes)';
COMMENT ON COLUMN chair."Import" IS 'Import code for importing chair data from a delimited file.';
COMMENT ON COLUMN chair."Description" IS 'A description of the chair.';
COMMENT ON COLUMN chair."Col" IS 'Column ID of the chair within the scheduler.';
COMMENT ON COLUMN chair."Clinic" IS 'Clinic that this chair is in, ptr to CLINIC.Clinic';
COMMENT ON COLUMN chair."Chair" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN chair."BlockSize" IS 'Number that indicates the block size for the scheduler display for this chair (0=10minutes, 1=15 minutes, 2=20 minutes, 3=30 minutes) ';


CREATE  TABLE chairl (
  "GroupLayout" numeric(10,0) NOT NULL,
  "Chair" numeric(10,0) NOT NULL,
  "Discipline" character(6),
  "Group" character(6),
  "Producer" character(10),
  "User" numeric(10,0),
  "WSchItemId" numeric(10,0),
  CONSTRAINT chairl_primary PRIMARY KEY ("GroupLayout", "Chair")
) ;
COMMENT ON TABLE chairl IS 'Chair Layouts';
COMMENT ON COLUMN chairl."WSchItemId" IS 'Stores the work schedule item ID for future references so that changes in work schedule can be reflected in the corresponding records';
COMMENT ON COLUMN chairl."User" IS 'Assigned provider for chair session';
COMMENT ON COLUMN chairl."Producer" IS 'DEPRECATED';
COMMENT ON COLUMN chairl."GroupLayout" IS 'Primary key, ptr to GROUPL.GroupLayout';
COMMENT ON COLUMN chairl."Group" IS 'Student group label for chair / session, free text or ptr to PGROUP.PGroup';
COMMENT ON COLUMN chairl."Discipline" IS 'Optional, assigned discipline for chair/session, free text or ptr to DISCIPL.Discipline';
COMMENT ON COLUMN chairl."Chair" IS 'Primary key, ptr to CHAIR.Chair';


CREATE  TABLE chairst (
  "Chair" numeric(10,0) NOT NULL,
  "ClinicTime" numeric(10,0) NOT NULL,
  "CNState" character(6),
  "Audit" numeric(10,0),
  CONSTRAINT chairst_primary PRIMARY KEY ("Chair", "ClinicTime")
) ;
COMMENT ON TABLE chairst IS 'Chair Notification States';
COMMENT ON COLUMN chairst."ClinicTime" IS 'If session-based, then ptr to CLINICT.ClinicTime, else 0. ';
COMMENT ON COLUMN chairst."Chair" IS 'Primary Key, ptr to CHAIR.Chair';
COMMENT ON COLUMN chairst."CNState" IS 'Chair state, ptr to CNSTATE.CNState or blank';
COMMENT ON COLUMN chairst."Audit" IS 'Ptr to AUDITHIS.Audit';


CREATE  TABLE chairsth (
  "ChairStH" numeric(10,0) NOT NULL,
  "Chair" numeric(10,0),
  "ClinicTime" numeric(10,0),
  "CNState" character(6),
  "Audit" numeric(10,0),
  CONSTRAINT chairsth_primary PRIMARY KEY ("ChairStH")
) ;
COMMENT ON TABLE chairsth IS 'Chair Notification State History';
COMMENT ON COLUMN chairsth."ClinicTime" IS 'If session-based, then ptr to CLINICT.ClinicTime, else 0. ';
COMMENT ON COLUMN chairsth."ChairStH" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN chairsth."Chair" IS 'Ptr to CHAIR.Chair';
COMMENT ON COLUMN chairsth."CNState" IS 'Chair state, ptr to CNSTATE.CNState or blank';
COMMENT ON COLUMN chairsth."Audit" IS 'Ptr to AUDITHIS.Audit';


CREATE  TABLE charthis (
  "ChartHis" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "Chart" character(10),
  "User" numeric(10,0),
  "IsIn" numeric(5,0),
  "Date" timestamp without time zone,
  "Time" numeric(10,0),
  "Location" character(6),
  "Reason" character(40),
  "Audit" numeric(10,0),
  CONSTRAINT charthis_primary PRIMARY KEY ("ChartHis")
) ;
CREATE INDEX IF NOT EXISTS charthis_date ON charthis USING btree ("Date") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS charthis_patient ON charthis USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE charthis IS 'Chart Tracking History';
COMMENT ON COLUMN charthis."User" IS 'User ID of user who had the chart, ptr to USERS.User';
COMMENT ON COLUMN charthis."Time" IS 'Time of chart scanning, in minutes from midnight.';
COMMENT ON COLUMN charthis."Reason" IS 'Free text area to enter the reason for the chart going out';
COMMENT ON COLUMN charthis."Patient" IS 'Patient that the chart belongs to, ptr to PATIENT.Patient';
COMMENT ON COLUMN charthis."Location" IS 'Location that the chart is going out to, ptr to LOCATION.Location.';
COMMENT ON COLUMN charthis."IsIn" IS 'Chart history type? (0=Chart scanned out, 1=Chart scanned in)';
COMMENT ON COLUMN charthis."Date" IS 'Date of chart scanning';
COMMENT ON COLUMN charthis."ChartHis" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN charthis."Chart" IS 'Patient chart number, ptr to PATIENT.Chart';
COMMENT ON COLUMN charthis."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE chartlnk (
  "Id" numeric(10,0) NOT NULL,
  "Auto" numeric(10,0),
  "User" numeric(10,0),
  "TxDate" timestamp without time zone,
  "ChartId" character(10),
  "Producer" character(10),
  "Procedure" character(7),
  "Site" character(3),
  "Surface" character(6),
  "Status" character(6),
  "Previous" numeric(10,0),
  "Action" numeric(5,0),
  "PlanPhase" character(2),
  "PlanSeq" numeric(5,0),
  "Site2" character(3),
  "Custom1" character(6),
  "Custom2" character(6),
  "Total" numeric,
  "InsTotal" numeric,
  "Discipline" character(15),
  "Additional" character(7),
  "StationId" numeric(10,0),
  "Patient" numeric(10,0),
  "Custom3" character(6),
  "Custom4" character(6),
  "BillTotal" numeric(5,0),
  "XCount" numeric(5,0),
  "Unit" numeric,
  CONSTRAINT chartlnk_primary PRIMARY KEY ("Id")
) ;
CREATE INDEX IF NOT EXISTS chartlnk_auto ON chartlnk USING btree ("Auto") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS chartlnk_patientkey ON chartlnk USING btree ("Patient") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS chartlnk_producer ON chartlnk USING btree ("Producer") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS chartlnk_user ON chartlnk USING btree ("User") TABLESPACE pg_default;
COMMENT ON TABLE chartlnk IS 'Temporary Unapproved Treatments';
COMMENT ON COLUMN chartlnk."XCount" IS 'For x-ray procedures, the number of exposures.';
COMMENT ON COLUMN chartlnk."User" IS 'User ID of entry user. Ptr to USERS.User';
COMMENT ON COLUMN chartlnk."Unit" IS 'Number of units for the unapproved treatment, ptr to PROCEDUR.Units';
COMMENT ON COLUMN chartlnk."TxDate" IS 'Treatment date.';
COMMENT ON COLUMN chartlnk."Total" IS 'Estimated total treatment cost (including patient and insurance amounts), in dollars.';
COMMENT ON COLUMN chartlnk."Surface" IS 'Surface on crown for treatment.';
COMMENT ON COLUMN chartlnk."Status" IS 'Treatment status (P=Treatment Plan, I = Incomplete, C = Completed, D = Deleted, E = Materials/Pre-Existing, A = Condition, O = Ortho Visit)';
COMMENT ON COLUMN chartlnk."StationId" IS 'Station ID of entry station, ptr to STATION.StationId';
COMMENT ON COLUMN chartlnk."Site2" IS 'Ending site/tooth for multi-site treatments (e.g. bridges)';
COMMENT ON COLUMN chartlnk."Site" IS 'Site/tooth for treatment.';
COMMENT ON COLUMN chartlnk."Producer" IS 'Provider for the treatment, ptr to PRODUCER.Producer';
COMMENT ON COLUMN chartlnk."Procedure" IS 'Procedure code of the treatment, ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN chartlnk."Previous" IS 'ID of previous treatment record modified, ptr to TREATME2.Auto';
COMMENT ON COLUMN chartlnk."PlanSeq" IS 'Treatment sequence number.';
COMMENT ON COLUMN chartlnk."PlanPhase" IS 'Treatment phase order.';
COMMENT ON COLUMN chartlnk."Patient" IS 'Patient that this treatment is for, ptr to PATIENT.Patient';
COMMENT ON COLUMN chartlnk."InsTotal" IS 'Estimated insurance amount, in dollars.';
COMMENT ON COLUMN chartlnk."Id" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN chartlnk."Discipline" IS 'Discipline, ptr to CLASS.Class';
COMMENT ON COLUMN chartlnk."Custom4" IS 'Treatment/Clinical2 code for this transaction, ptr to CUSTCODE.Code';
COMMENT ON COLUMN chartlnk."Custom3" IS 'Treatment/Clinical1 code for this transaction, ptr to CUSTCODE.Code';
COMMENT ON COLUMN chartlnk."Custom2" IS 'Treatment/Note2 code for this transaction, ptr to CUSTCODE.Code';
COMMENT ON COLUMN chartlnk."Custom1" IS 'Treatment/Note1 code for this transaction, ptr to CUSTCODE.Code';
COMMENT ON COLUMN chartlnk."ChartId" IS 'DEPRECATED';
COMMENT ON COLUMN chartlnk."BillTotal" IS 'Bill total of lab order? (0=Charge the procedure code amount; 1=If an auto-completed lab, charge the total from the lab order)';
COMMENT ON COLUMN chartlnk."Auto" IS 'Treatment record for the chart, ptr to TREATME2.Auto';
COMMENT ON COLUMN chartlnk."Additional" IS 'Additional field used optionally for treatments.';
COMMENT ON COLUMN chartlnk."Action" IS 'Last action taken on this unapproved temporary treatment (0=Added or Modified, 1=Deleted)';


CREATE  TABLE checkin (
  "CheckIn" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "IsIn" numeric(5,0),
  "DateIn" timestamp without time zone,
  "TimeIn" numeric(10,0),
  "DateOut" timestamp without time zone,
  "TimeOut" numeric(10,0),
  "User" numeric(10,0),
  "Appointment" numeric(10,0),
  "OrderId" numeric(10,0),
  "UserIn" numeric(10,0),
  "SignInDate" timestamp without time zone,
  "SignInTime" numeric(10,0),
  "SignInUser" numeric(10,0),
  CONSTRAINT checkin_primary PRIMARY KEY ("CheckIn")
) ;
CREATE INDEX IF NOT EXISTS checkin_datekey ON checkin USING btree ("DateIn") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS checkin_patient ON checkin USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE checkin IS 'Patient Checkins / Checkouts / Sign-ins';
COMMENT ON COLUMN checkin."UserIn" IS 'User ID of user that did the checkin. Ptr to USERS.User';
COMMENT ON COLUMN checkin."User" IS 'User ID of user that did the checkout. Ptr to USERS.User';
COMMENT ON COLUMN checkin."TimeOut" IS 'Time patient checked out, in minutes from midnight.';
COMMENT ON COLUMN checkin."TimeIn" IS 'Time patient checked in, in minutes from midnight.';
COMMENT ON COLUMN checkin."SignInUser" IS 'axiUm user ID used by the Kiosk for sign-ins. Ptr to Users.User.';
COMMENT ON COLUMN checkin."SignInTime" IS 'Time the patient signed in via the Kiosk, in minutes from midnight.';
COMMENT ON COLUMN checkin."SignInDate" IS 'Date the patient signed in via the Kiosk.';
COMMENT ON COLUMN checkin."Patient" IS 'Patient ID, ptr to PATIENT.Patient';
COMMENT ON COLUMN checkin."OrderId" IS 'Checkin/checkout ticket that this record is for. Internal ID from sequence.';
COMMENT ON COLUMN checkin."IsIn" IS 'Patient is checked/signed in? (0=Checked Out, 1=Checked In, 2=Signed In)';
COMMENT ON COLUMN checkin."DateOut" IS 'Date patient checked out';
COMMENT ON COLUMN checkin."DateIn" IS 'Date patient checked in.';
COMMENT ON COLUMN checkin."CheckIn" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN checkin."Appointment" IS 'Appointment that the patient signed in for, ptr to APPOINT.Appointment';


CREATE  TABLE city (
  "City" character(24) NOT NULL,
  "Province" character(6),
  "Postal" character(15) NOT NULL,
  "Area" character(4),
  "AddressOther" character(15),
  CONSTRAINT city_primary PRIMARY KEY ("City", "Postal")
) ;
CREATE INDEX IF NOT EXISTS city_postal ON city USING btree ("Postal") TABLESPACE pg_default;
COMMENT ON TABLE city IS 'The City codes associated with a city / state / postal code combination.';
COMMENT ON COLUMN city."Province" IS 'Province / state, ptr to PROVINCE.Province';
COMMENT ON COLUMN city."Postal" IS 'Primary key component, postal / ZIP code';
COMMENT ON COLUMN city."City" IS 'Primary key component, city name';
COMMENT ON COLUMN city."Area" IS 'Default telephone area code for this city ';
COMMENT ON COLUMN city."AddressOther" IS 'Secondary address information';


CREATE  TABLE claim (
  "Type" numeric(5,0) NOT NULL,
  "Id" numeric(10,0) NOT NULL,
  "InsNumber" numeric(5,0) NOT NULL,
  "Patient" numeric(10,0),
  "Status" numeric(5,0),
  "Date" timestamp without time zone,
  "FormType" numeric(10,0),
  "Insurance" character(6),
  "Doctor" character(10),
  "HeldType" numeric(5,0),
  buffer clob,
  "Practice" numeric(5,0),
  "ControlNumber" character varying(50),
  "IsVoid" numeric(5,0),
  "SubmitterClmId" character varying(38),
  "EDI" character varying(15),
  "Claim" numeric(10,0),
  "EDIStatus" numeric(5,0),
  "Facility" character(6),
  "ClaimTSetId" character varying(30),
  "EDIStatusUpdateDate" timestamp without time zone,
  CONSTRAINT claim_primary PRIMARY KEY ("Type", "Id", "InsNumber")
) ;
CREATE INDEX IF NOT EXISTS claim_datekey ON claim USING btree ("Date") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS claim_formins ON claim USING btree ("FormType", "Insurance") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS claim_formprac ON claim USING btree ("FormType", "Practice") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS claim_patientkey ON claim USING btree ("Patient") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS claim_submitterclmid ON claim USING btree ("SubmitterClmId") TABLESPACE pg_default;
COMMENT ON TABLE claim IS 'Held Claims';
COMMENT ON COLUMN claim.buffer IS 'Raw data containing information about the claim';
COMMENT ON COLUMN claim."Type" IS 'Primary key component, treatment type for this claim. Ptr to TRX.Type';
COMMENT ON COLUMN claim."SubmitterClmId" IS 'Submitter-Claim ID for "EDI" remittance processing';
COMMENT ON COLUMN claim."Status" IS 'Status of the claim (0=Not Printed, 1=Printed, 2=Processed X12N Claim)';
COMMENT ON COLUMN claim."Practice" IS 'ID code of the practice for this claim record, ptr to PRACTICE.Id';
COMMENT ON COLUMN claim."Patient" IS 'Patient that the claim is for, ptr to PATIENT.Patient';
COMMENT ON COLUMN claim."IsVoid" IS 'Is voided? (0=No, 1=Yes)';
COMMENT ON COLUMN claim."Insurance" IS 'Insurance Company code, ptr to INSURANC.Company';
COMMENT ON COLUMN claim."InsNumber" IS 'Primary key component, the insurance policy being billed (1=Primary, 2=Secondary, 3=Tertiary)';
COMMENT ON COLUMN claim."Id" IS 'Primary key component, claim number for this claim. Ptr to TRX.Id';
COMMENT ON COLUMN claim."HeldType" IS 'Held Type (0 = Non-"EDI"/Dropped to Paper, 1 = NEIC 2.1, 2 = NSF 2.0, 3 = X12N4010 Dental, 4 = X124010 NYMed 1.0, 5 = DCDS 3.00, 6 = NSF 2.01, 7 = X12N4010 NYMed2.1, 8 = X12N4010 Medical, 9=X12N5010 Dental, 10=X12N5010 Medical, 11=X12N5010 NYMed 2.1, 12=X12N4010 NYMed(D), 13=X12N5010 NYMed(D))';
COMMENT ON COLUMN claim."FormType" IS 'Claim form code, ptr to CFORMCD.CFormCdId';
COMMENT ON COLUMN claim."Facility" IS 'Facility code for the claim, ptr to TRX.Location';
COMMENT ON COLUMN claim."EDIStatusUpdateDate" IS 'Date of the most recent update made to the EDIStatus';
COMMENT ON COLUMN claim."EDIStatus" IS 'EDI status (1=(B)atched, 2=(W)aiting to send, 3=(A)CK, 4=(X)Error, 5=Accepted, 6=(R)ejected, 7=(P)ending, 8=(E)OB)';
COMMENT ON COLUMN claim."EDI" IS 'Claim batch number for this claim';
COMMENT ON COLUMN claim."Doctor" IS 'Billing Doctor or Fee Guide, ptr to PRODUCER.Producer';
COMMENT ON COLUMN claim."Date" IS 'Date of claim';
COMMENT ON COLUMN claim."ControlNumber" IS 'TCN (claim identification number) for voiding claim';
COMMENT ON COLUMN claim."ClaimTSetId" IS 'Control number of the transaction set, ptr to CLAIMTSET.Id';
COMMENT ON COLUMN claim."Claim" IS 'Internal ID, from sequence';


CREATE  TABLE claimatt (
  "Type" numeric(5,0) NOT NULL,
  "Id" numeric(10,0) NOT NULL,
  "InsNumber" numeric(5,0) NOT NULL,
  "InstanceId" numeric(5,0) NOT NULL,
  "AttachStatus" numeric(5,0),
  "NEAFacId" character varying(8),
  "NEANumber" character varying(20),
  CONSTRAINT claimatt_primary PRIMARY KEY ("Type", "Id", "InsNumber", "InstanceId")
) ;
CREATE INDEX IF NOT EXISTS claimatt_attachstatus ON claimatt USING btree ("AttachStatus", "NEAFacId") TABLESPACE pg_default;
COMMENT ON TABLE claimatt IS 'Claim Attachments';
COMMENT ON COLUMN claimatt."Type" IS 'Primary key component, treatment type for the claim. Ptr to TRX.Type';
COMMENT ON COLUMN claimatt."NEANumber" IS 'NEA #, used when AttachStatus=3';
COMMENT ON COLUMN claimatt."NEAFacId" IS 'NEA Provider Facility ID ';
COMMENT ON COLUMN claimatt."InstanceId" IS 'Primary key component, Instance ID (incremented each time a distinct Type/Id/InsNumber is sent to NEA)';
COMMENT ON COLUMN claimatt."InsNumber" IS 'Primary key component, the insurance policy being billed (1=Primary, 2=Secondary, 3=Tertiary)';
COMMENT ON COLUMN claimatt."Id" IS 'Primary key component, claim number for the claim. Ptr to TRX.Id';
COMMENT ON COLUMN claimatt."AttachStatus" IS 'Attachment status (0=Not Required, 1=Required, 2=Pending, 3=Attached)';


CREATE  TABLE claimcah (
  "ClaimCAH" numeric(10,0) NOT NULL,
  "ClaimCAS" numeric(10,0),
  "ClaimEOB" numeric(10,0),
  "Type" numeric(5,0),
  "Treatment" numeric(5,0),
  "CAReason" character(6),
  "Amount" numeric,
  "Audit" numeric(10,0),
  "GroupCode" character(6),
  CONSTRAINT claimcah_primary PRIMARY KEY ("ClaimCAH")
) ;
COMMENT ON TABLE claimcah IS 'Claim Adjustment Segment History';
COMMENT ON COLUMN claimcah."Type" IS 'Type of adjustment (0=Claim, 1=Treatment)';
COMMENT ON COLUMN claimcah."Treatment" IS 'If Type=1, the treatment on the claim that the adjustment is for. Ptr to CLAIMIT.Treatment';
COMMENT ON COLUMN claimcah."GroupCode" IS 'Claim adjustment reason group, ptr to CAREASON.GroupCode';
COMMENT ON COLUMN claimcah."ClaimEOB" IS 'EOB that this claim adjustment is for, ptr to CLAIMEOB.ClaimEOB';
COMMENT ON COLUMN claimcah."ClaimCAS" IS 'Claim adjustment segment that this history is for, ptr to CLAIMCAS.ClaimCAS';
COMMENT ON COLUMN claimcah."ClaimCAH" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN claimcah."CAReason" IS 'Claim adjustment reason, ptr to CAREASON.CAReason';
COMMENT ON COLUMN claimcah."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN claimcah."Amount" IS 'Optional amount tied to the reason, in dollars.';


CREATE  TABLE claimcas (
  "ClaimCAS" numeric(10,0) NOT NULL,
  "ClaimEOB" numeric(10,0),
  "Type" numeric(5,0),
  "Treatment" numeric(5,0),
  "CAReason" character(6),
  "Amount" numeric,
  "Audit" numeric(10,0),
  "GroupCode" character(6),
  CONSTRAINT claimcas_primary PRIMARY KEY ("ClaimCAS")
) ;
CREATE INDEX IF NOT EXISTS claimcas_claimeob ON claimcas USING btree ("ClaimEOB") TABLESPACE pg_default;
COMMENT ON TABLE claimcas IS 'Claim Adjustment Segments';
COMMENT ON COLUMN claimcas."Type" IS 'Type of adjustment (0=Claim, 1=Treatment)';
COMMENT ON COLUMN claimcas."Treatment" IS 'If Type=1, the treatment on the claim that the adjustment is for. Ptr to CLAIMIT.Treatment';
COMMENT ON COLUMN claimcas."GroupCode" IS 'Claim adjustment reason group, ptr to CAREASON.GroupCode';
COMMENT ON COLUMN claimcas."ClaimEOB" IS 'EOB that this claim adjustment is for, ptr to CLAIMEOB.ClaimEOB';
COMMENT ON COLUMN claimcas."ClaimCAS" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN claimcas."CAReason" IS 'Claim adjustment reason, ptr to CAREASON.CAReason';
COMMENT ON COLUMN claimcas."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN claimcas."Amount" IS 'Optional amount tied to the reason, in dollars.';


CREATE  TABLE claimeit (
  "ClaimEIt" numeric(10,0) NOT NULL,
  "ClaimEOB" numeric(10,0),
  "Treatment" numeric(5,0),
  "Deductible" numeric,
  "CoPay" numeric,
  "CoIns" numeric,
  "AdjudicationDate" timestamp without time zone,
  CONSTRAINT claimeit_primary PRIMARY KEY ("ClaimEIt")
) ;
CREATE INDEX IF NOT EXISTS claimeit_claimeob ON claimeit USING btree ("ClaimEOB") TABLESPACE pg_default;
COMMENT ON TABLE claimeit IS 'Claim EOB Items';
COMMENT ON COLUMN claimeit."Treatment" IS 'Treatment that this item is for, ptr to TRX.Treatment';
COMMENT ON COLUMN claimeit."Deductible" IS 'Amount of deductible, in dollars.';
COMMENT ON COLUMN claimeit."CoPay" IS 'Amount of copayment, in dollars.';
COMMENT ON COLUMN claimeit."CoIns" IS 'Other Insurer amount, in dollars.';
COMMENT ON COLUMN claimeit."ClaimEOB" IS 'EOB that this item is part of, ptr to CLAIMEOB.ClaimEOB';
COMMENT ON COLUMN claimeit."ClaimEIt" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN claimeit."AdjudicationDate" IS 'Date of adjudication';


CREATE  TABLE claimeob (
  "ClaimEOB" numeric(10,0) NOT NULL,
  "Id" numeric(10,0),
  "InsNumber" numeric(5,0),
  "EOBNumber" character varying(20),
  "CreateAudit" numeric(10,0),
  "Type" numeric(5,0),
  CONSTRAINT claimeob_primary PRIMARY KEY ("ClaimEOB")
) ;
CREATE INDEX IF NOT EXISTS claimeob_id ON claimeob USING btree ("Id") TABLESPACE pg_default;
COMMENT ON TABLE claimeob IS 'Claim EOBs (Explanation of Benefits)';
COMMENT ON COLUMN claimeob."Type" IS 'Treatment type (ptr to TRX.Type)';
COMMENT ON COLUMN claimeob."InsNumber" IS 'Insurance policy being billed for this claim (1=Primary, 2=Secondary, 3=Tertiary)';
COMMENT ON COLUMN claimeob."Id" IS 'Claim number for this claim. Ptr to TRX.Id';
COMMENT ON COLUMN claimeob."EOBNumber" IS 'EOB# (like an internal Claim Id#)';
COMMENT ON COLUMN claimeob."CreateAudit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN claimeob."ClaimEOB" IS 'Primary key, internal ID from sequence.';


CREATE  TABLE claimfile (
  "Id" numeric(10,0) NOT NULL DEFAULT 0,
  filecontent clob,
  "BatchNumber" character varying(15),
  "FileName" character varying(255),
  CONSTRAINT claimfile_pk PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE claimfile IS 'Table for storing claim file content.';
COMMENT ON COLUMN claimfile.filecontent IS 'The claim file content.';
COMMENT ON COLUMN claimfile."Id" IS 'PK component, ptr to primary key of the table from a sequence.';
COMMENT ON COLUMN claimfile."FileName" IS 'The file name where the claim file was originally exported.';
COMMENT ON COLUMN claimfile."BatchNumber" IS 'Claim batch number for this claim.';


CREATE  TABLE claimh (
  "ClaimH" numeric(10,0) NOT NULL,
  "Type" numeric(5,0),
  "Id" numeric(10,0),
  "InsNumber" numeric(5,0),
  "Patient" numeric(10,0),
  "Status" numeric(5,0),
  "Date" timestamp without time zone,
  "FormType" numeric(10,0),
  "Insurance" character(6),
  "Doctor" character(10),
  "HeldType" numeric(5,0),
  buffer clob,
  "Practice" numeric(5,0),
  "ControlNumber" character varying(50),
  "IsVoid" numeric(5,0),
  "SubmitterClmId" character varying(38),
  "EDI" character varying(15),
  "Claim" numeric(10,0),
  "EDIStatus" numeric(5,0),
  "Facility" character(6),
  "ClaimTSetId" character varying(30),
  "EDIStatusUpdateDate" timestamp without time zone,
  CONSTRAINT claimh_primary PRIMARY KEY ("ClaimH")
) ;
CREATE INDEX IF NOT EXISTS claimh_patientkey ON claimh USING btree ("Patient") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS claimh_typeidinsnumber ON claimh USING btree ("Type", "Id", "InsNumber") TABLESPACE pg_default;
COMMENT ON TABLE claimh IS 'Held Claim History';
COMMENT ON COLUMN claimh.buffer IS 'Raw data containing information about the claim';
COMMENT ON COLUMN claimh."Type" IS 'Treatment type for this claim. Ptr to TRX.Type';
COMMENT ON COLUMN claimh."SubmitterClmId" IS 'Submitter-Claim ID for "EDI" remittance processing';
COMMENT ON COLUMN claimh."Status" IS 'Status of the claim (0=Not Printed, 1=Printed, 2=Processed X12N Claim)';
COMMENT ON COLUMN claimh."Practice" IS 'ID code of the practice for this claim record, ptr to PRACTICE.Id';
COMMENT ON COLUMN claimh."Patient" IS 'Patient that the claim is for, ptr to PATIENT.Patient';
COMMENT ON COLUMN claimh."IsVoid" IS 'Is voided? (0=No, 1=Yes)';
COMMENT ON COLUMN claimh."Insurance" IS 'Insurance Company code, ptr to INSURANC.Company';
COMMENT ON COLUMN claimh."InsNumber" IS 'Insurance policy being billed (1=Primary, 2=Secondary, 3=Tertiary)';
COMMENT ON COLUMN claimh."Id" IS 'Claim number for this claim. Ptr to TRX.Id';
COMMENT ON COLUMN claimh."HeldType" IS 'Held Type (0 = Non-"EDI"/Dropped to Paper, 1 = NEIC 2.1, 2 = NSF 2.0, 3 = X12N4010 Dental, 4 = X124010 NYMed 1.0, 5 = DCDS 3.00, 6 = NSF 2.01, 7 = X12N4010 NYMed2.1, 8 = X12N4010 Medical, 9=X12N5010 Dental, 10=X12N5010 Medical, 11=X12N5010 NYMed 2.1, 12=X12N4010 NYMed(D), 13=X12N5010 NYMed(D))';
COMMENT ON COLUMN claimh."FormType" IS 'Claim form code, ptr to CFORMCD.CFormCdId';
COMMENT ON COLUMN claimh."Facility" IS 'Facility code for the claim, ptr to TRX.Location';
COMMENT ON COLUMN claimh."EDIStatusUpdateDate" IS 'Date of the most recent update made to the EDIStatus';
COMMENT ON COLUMN claimh."EDIStatus" IS 'CDANET "EDI" status (0=N/A, 1=Batched, 2=Waiting to send, 3=Rejected, 4=Error, 5=ACK, 6=EOB, 7=Pending, 8=Manual, 9=Emp Cert, 10=Voided) (Canada Only)';
COMMENT ON COLUMN claimh."EDI" IS 'Claim batch number for this claim';
COMMENT ON COLUMN claimh."Doctor" IS 'Billing Doctor or Fee Guide, ptr to PRODUCER.Producer';
COMMENT ON COLUMN claimh."Date" IS 'Date of claim';
COMMENT ON COLUMN claimh."ControlNumber" IS 'TCN (claim identification number) for voiding claim';
COMMENT ON COLUMN claimh."ClaimTSetId" IS 'Control number of the transaction set, ptr to CLAIMTSET.Id';
COMMENT ON COLUMN claimh."ClaimH" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN claimh."Claim" IS 'Internal ID, from sequence';


CREATE  TABLE claimhis (
  "ClaimHis" numeric(10,0) NOT NULL,
  "Type" numeric(5,0),
  "Id" numeric(10,0),
  "Date" timestamp without time zone,
  "Company" character(6),
  "User" numeric(10,0),
  "SendType" numeric(5,0),
  "IsVoid" numeric(5,0),
  "EDI" character varying(15),
  "ClaimH" numeric(10,0),
  CONSTRAINT claimhis_primary PRIMARY KEY ("ClaimHis")
) ;
CREATE INDEX IF NOT EXISTS claimhis_trx ON claimhis USING btree ("Type", "Id") TABLESPACE pg_default;
COMMENT ON TABLE claimhis IS 'Claim Submission History';
COMMENT ON COLUMN claimhis."User" IS 'User who submitted the claim, ptr to USERS.User';
COMMENT ON COLUMN claimhis."Type" IS 'Treatment type for this claim. Ptr to TRX.Type';
COMMENT ON COLUMN claimhis."SendType" IS 'Type of sent claim (0=Unknown, 1=Paper, 2="EDI")';
COMMENT ON COLUMN claimhis."IsVoid" IS 'Is voided? (0=No, 1=Yes)';
COMMENT ON COLUMN claimhis."Id" IS 'Claim number for this claim. Ptr to TRX.Id';
COMMENT ON COLUMN claimhis."EDI" IS 'Claim batch number for this claim';
COMMENT ON COLUMN claimhis."Date" IS 'Date of claim submission.';
COMMENT ON COLUMN claimhis."Company" IS 'Insurance company for the claim, ptr to INSURANC.Company';
COMMENT ON COLUMN claimhis."ClaimHis" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN claimhis."ClaimH" IS 'Held claim history for this submission, ptr to CLAIMH.ClaimH';


CREATE  TABLE claiminq (
  "Id" numeric(10,0) NOT NULL,
  "ClaimHisId" numeric(10,0),
  "DocControlNumber" character varying(15),
  "Remarks" character varying(4000),
  "Status" numeric(5,0),
  CONSTRAINT claiminq_primary PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE claiminq IS 'Claim Inquiries';
COMMENT ON COLUMN claiminq."Status" IS 'Is Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN claiminq."Remarks" IS 'Free text entry field for remarks about the claim inquiry.';
COMMENT ON COLUMN claiminq."Id" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN claiminq."DocControlNumber" IS 'Free text entry for the document control number.';
COMMENT ON COLUMN claiminq."ClaimHisId" IS 'Submitted claim number that the inquiry is for, ptr to CLAIMHIS.ClaimHis';


CREATE  TABLE claimit (
  "Type" numeric(5,0) NOT NULL,
  "Id" numeric(10,0) NOT NULL,
  "InsNumber" numeric(5,0) NOT NULL,
  "Treatment" numeric(5,0) NOT NULL,
  "Patient" numeric(10,0),
  "Status" numeric(5,0),
  "Buffer" character(255),
  "Buffer2" character varying(255),
  CONSTRAINT claimit_primary PRIMARY KEY ("Type", "Id", "InsNumber", "Treatment")
) ;
CREATE INDEX IF NOT EXISTS claimit_patientkey ON claimit USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE claimit IS 'Held Claim Items';
COMMENT ON COLUMN claimit."Type" IS 'Primary key component, treatment type for this claim. Ptr to TRX.Type';
COMMENT ON COLUMN claimit."Treatment" IS 'Primary key component, treatment line within the held claim. Ptr to TRX.Treatment';
COMMENT ON COLUMN claimit."Status" IS 'Status of the claim (0=Not Printed, 1=Printed, 2=Processed X12N Claim)';
COMMENT ON COLUMN claimit."Patient" IS 'Patient that the claim is for, ptr to PATIENT.Patient';
COMMENT ON COLUMN claimit."InsNumber" IS 'Primary key component, the insurance policy being billed (1=Primary, 2=Secondary, 3=Tertiary)';
COMMENT ON COLUMN claimit."Id" IS 'Primary key component, claim number for this claim. Ptr to TRX.Id';
COMMENT ON COLUMN claimit."Buffer2" IS 'Additional buffer for storing information about the claim ';
COMMENT ON COLUMN claimit."Buffer" IS 'Raw data containing information about the claim';


CREATE  TABLE claimith (
  "ClaimItH" numeric(10,0) NOT NULL,
  "ClaimH" numeric(10,0),
  "Type" numeric(5,0),
  "Id" numeric(10,0),
  "InsNumber" numeric(5,0),
  "Treatment" numeric(5,0),
  "Patient" numeric(10,0),
  "Status" numeric(5,0),
  "Buffer" character(255),
  "Buffer2" character varying(255),
  CONSTRAINT claimith_primary PRIMARY KEY ("ClaimItH")
) ;
CREATE INDEX IF NOT EXISTS claimith_patientkey ON claimith USING btree ("Patient") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS claimith_typeidinsnumber ON claimith USING btree ("Type", "Id", "InsNumber", "Treatment") TABLESPACE pg_default;
COMMENT ON TABLE claimith IS 'Held Claim Item History';
COMMENT ON COLUMN claimith."Type" IS 'Treatment type for this claim. Ptr to TRX.Type';
COMMENT ON COLUMN claimith."Treatment" IS 'Treatment line within the held claim. Ptr to TRX.Treatment';
COMMENT ON COLUMN claimith."Status" IS 'Status of the claim (0=Not Printed, 1=Printed, 2=Processed X12N Claim)';
COMMENT ON COLUMN claimith."Patient" IS 'Patient that the claim is for, ptr to PATIENT.Patient';
COMMENT ON COLUMN claimith."InsNumber" IS 'Insurance policy being billed (1=Primary, 2=Secondary, 3=Tertiary)';
COMMENT ON COLUMN claimith."Id" IS 'Claim number for this claim. Ptr to TRX.Id';
COMMENT ON COLUMN claimith."ClaimItH" IS 'Primary key, internal ID from sequence';
COMMENT ON COLUMN claimith."ClaimH" IS 'Claim history, ptr to CLAIMH.ClaimH';
COMMENT ON COLUMN claimith."Buffer2" IS 'Additional buffer for storing information about the claim ';
COMMENT ON COLUMN claimith."Buffer" IS 'Raw data containing information about the claim';


CREATE  TABLE claimrejreason (
  "Type" numeric(5,0) NOT NULL DEFAULT 0,
  "Id" numeric(10,0) NOT NULL DEFAULT 0,
  "InsNumber" numeric(5,0) NOT NULL DEFAULT 0,
  "Reason" character varying(1000),
  "FromFile" character varying(10)
) ;
COMMENT ON TABLE claimrejreason IS 'Table for storing claim rejection reasons.';
COMMENT ON COLUMN claimrejreason."Type" IS 'Claim type';
COMMENT ON COLUMN claimrejreason."Reason" IS 'Rejection reason';
COMMENT ON COLUMN claimrejreason."InsNumber" IS 'Claim InsNumber';
COMMENT ON COLUMN claimrejreason."Id" IS 'Claim id';
COMMENT ON COLUMN claimrejreason."FromFile" IS 'Origin of reason. Values: 277, 999';


CREATE  TABLE claimrit (
  "ClaimRit" numeric(10,0) NOT NULL,
  "ClaimEOB" numeric(10,0),
  "Treatment" numeric(5,0),
  "RARemark" character(6),
  "Audit" numeric(10,0),
  CONSTRAINT claimrit_primary PRIMARY KEY ("ClaimRit")
) ;
COMMENT ON TABLE claimrit IS 'Remittance Remarks for processed "EDI" 835 claims';
COMMENT ON COLUMN claimrit."Treatment" IS 'Ptr to TRX.Treatment which matches CLAIMIT';
COMMENT ON COLUMN claimrit."RARemark" IS 'Remark code of remark, ptr to RAREMARK.RARemark';
COMMENT ON COLUMN claimrit."ClaimRit" IS 'Primary key, internal ID from sequence';
COMMENT ON COLUMN claimrit."ClaimEOB" IS 'Claim EOB that this remark is for, ptr to CLAIMEOB.ClaimEOB';
COMMENT ON COLUMN claimrit."Audit" IS 'Last audit, ptr to AUDITHIS.Audit';


CREATE  TABLE claimtset (
  "Id" character varying(30) NOT NULL,
  "TransactionType" character varying(10),
  "ClaimFileId" numeric(10,0) NOT NULL DEFAULT 0,
  CONSTRAINT claimtset_pk PRIMARY KEY ("Id")
) ;
CREATE INDEX IF NOT EXISTS claimtset_claimfileid ON claimtset USING btree ("ClaimFileId") TABLESPACE pg_default;
COMMENT ON TABLE claimtset IS 'Table for storing information about the claims transaction set.';
COMMENT ON COLUMN claimtset."TransactionType" IS 'Stores the code that represents the type of "EDI" transaction.';
COMMENT ON COLUMN claimtset."Id" IS 'PK component, ptr to primary key of the table from a sequence.';
COMMENT ON COLUMN claimtset."ClaimFileId" IS 'Claim file content, ptr to CLAIMFILE.Id';


CREATE  TABLE class (
  "Class" character(15) NOT NULL,
  "Name" character(63),
  "Rank" numeric(10,0),
  "Module" numeric(5,0),
  "BkgColor" numeric(10,0),
  "Inactive" numeric(5,0),
  CONSTRAINT class_primary PRIMARY KEY ("Class")
) ;
COMMENT ON TABLE class IS 'Treatment Disciplines';
COMMENT ON COLUMN class."Rank" IS 'Number 0..5 to rank the importance / urgency of this class of procedure';
COMMENT ON COLUMN class."Name" IS 'Description of the tx discipline class. ie: Orthodontics';
COMMENT ON COLUMN class."Module" IS 'Number to indicate the module type for this discipline (0=General, 1=Ortho, 2=Perio)';
COMMENT ON COLUMN class."Inactive" IS 'Code inactive? 0 - no, 1 = yes';
COMMENT ON COLUMN class."Class" IS 'Primary key, code to identify the tx discipline class';
COMMENT ON COLUMN class."BkgColor" IS 'Background colours for appointments in Scheduler';


CREATE  TABLE clevel (
  "CompLevel" character(6) NOT NULL,
  "Description" character(30),
  "MinYear" numeric(10,0),
  CONSTRAINT clevel_primary PRIMARY KEY ("CompLevel")
) ;
COMMENT ON TABLE clevel IS 'Competency Level Codes';
COMMENT ON COLUMN clevel."MinYear" IS 'Minimum year for student to be in for this level. ';
COMMENT ON COLUMN clevel."Description" IS 'Name/description of the competency level.';
COMMENT ON COLUMN clevel."CompLevel" IS 'Primary key, code to identify the competency level.';


CREATE  TABLE clingit (
  "ClinGrp" numeric(10,0) NOT NULL,
  "Clinic" numeric(10,0) NOT NULL,
  CONSTRAINT clingit_primary PRIMARY KEY ("ClinGrp", "Clinic")
) ;
COMMENT ON TABLE clingit IS 'Clinic Group Items';
COMMENT ON COLUMN clingit."Clinic" IS 'Primary key component, the clinic that is in the clinic group. Ptr to CLINIC.Clinic';
COMMENT ON COLUMN clingit."ClinGrp" IS 'Primary key component, the clinic group that the clinic is in. Ptr to CLINGRP.ClinGrp';


CREATE  TABLE clingrp (
  "ClinGrp" numeric(10,0) NOT NULL,
  "Description" character varying(30),
  CONSTRAINT clingrp_primary PRIMARY KEY ("ClinGrp")
) ;
COMMENT ON TABLE clingrp IS 'Clinic Groups';
COMMENT ON COLUMN clingrp."Description" IS 'Name of the clinic group.';
COMMENT ON COLUMN clingrp."ClinGrp" IS 'Primary key, internal ID from sequence. ';


CREATE  TABLE clinic (
  "Clinic" numeric(10,0) NOT NULL,
  "Description" character(30),
  "UseInstSch" numeric(5,0),
  "Selectable" numeric(5,0),
  "AutoCheckIn" numeric(5,0),
  "CancelCharge" numeric(5,0),
  "FailCharge" numeric(5,0),
  "Practice" numeric(5,0),
  "UseApptProvider" numeric(5,0),
  "Provider" character(10),
  "Discipline" character(6),
  "Custom1" character(6),
  "Custom2" character(6),
  "StartChkMethod" numeric(5,0),
  "Import" character(10),
  "StartChkTxConsent" numeric(5,0),
  "CustomLocation" character(6),
  "RulesOffset" numeric(10,0),
  "Inactive" numeric(5,0),
  CONSTRAINT clinic_primary PRIMARY KEY ("Clinic")
) ;
CREATE INDEX IF NOT EXISTS clinic_import ON clinic USING btree ("Import") TABLESPACE pg_default;
COMMENT ON TABLE clinic IS 'Clinics';
COMMENT ON COLUMN clinic."UseInstSch" IS 'Does this clinic use instructor work schedules? (0 = No, 1 = Yes)';
COMMENT ON COLUMN clinic."UseApptProvider" IS 'Use the appointment provider for charges? (0=No, 1=Yes)';
COMMENT ON COLUMN clinic."StartChkTxConsent" IS 'Start check missing consent checks based on? (0=Primary Appt Provider, 1=Assigned Tx Provider, 2=Both)';
COMMENT ON COLUMN clinic."StartChkMethod" IS 'Start checks for provider setting (0 = Not Required, 1 = Primary Only, 2 = Both)';
COMMENT ON COLUMN clinic."Selectable" IS 'This clinic is selectable for appointment requests? (0 = No, 1 = Yes)';
COMMENT ON COLUMN clinic."RulesOffset" IS 'Time offset in munutes for to apply treatments rules after appointment ends';
COMMENT ON COLUMN clinic."Provider" IS 'If UseApptProvider = 0, the provider to use for charge. Ptr to PRODUCER.Producer';
COMMENT ON COLUMN clinic."Practice" IS 'Default practice to use for charges. Ptr to PRACTICE.Id';
COMMENT ON COLUMN clinic."Inactive" IS 'Code inactive? 0 - no, 1 = yes';
COMMENT ON COLUMN clinic."Import" IS 'Import code for importing data from delimited files.';
COMMENT ON COLUMN clinic."FailCharge" IS 'Charge for failed appointments? (0 = No Charge, 1 = Auto-add, 2 = Prompt)';
COMMENT ON COLUMN clinic."Discipline" IS 'Default discipline to use for charges. Ptr to DISCIPL.Discipline';
COMMENT ON COLUMN clinic."Description" IS 'Name of the clinic. ';
COMMENT ON COLUMN clinic."CustomLocation" IS 'Default Tx Location';
COMMENT ON COLUMN clinic."Custom2" IS 'Default Treatment/Note2 value to use for charges. Ptr to CUSTCODE.Code';
COMMENT ON COLUMN clinic."Custom1" IS 'Default Treatment/Note1 value to use for charges. Ptr to CUSTCODE.Code';
COMMENT ON COLUMN clinic."Clinic" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN clinic."CancelCharge" IS 'Charge for cancelled appointments? (0 = No Charge, 1 = Auto-add, 2 = Prompt)';
COMMENT ON COLUMN clinic."AutoCheckIn" IS 'Automatically check in patients when they sign in? (0=No, 1=Yes)';


CREATE  TABLE clinical (
  "Clinical" character(6) NOT NULL,
  "Description" character(30),
  CONSTRAINT clinical_primary PRIMARY KEY ("Clinical")
) ;
COMMENT ON TABLE clinical IS 'Clinical codes used to classify referral sources';
COMMENT ON COLUMN clinical."Description" IS 'Description of the referral source classification';
COMMENT ON COLUMN clinical."Clinical" IS 'Primary key, ID code to classify the referral source';


CREATE  TABLE clinict (
  "ClinicTime" numeric(10,0) NOT NULL,
  "Clinic" numeric(10,0),
  "Description" character(30),
  "Start" numeric(10,0),
  "End" numeric(10,0),
  "Monday" numeric(5,0),
  "Tuesday" numeric(5,0),
  "Wednesday" numeric(5,0),
  "Thursday" numeric(5,0),
  "Friday" numeric(5,0),
  "Saturday" numeric(5,0),
  "Sunday" numeric(5,0),
  "Import" character(10),
  "Period" numeric(5,0),
  "StartDate" timestamp without time zone,
  "EndDate" timestamp without time zone,
  CONSTRAINT clinict_primary PRIMARY KEY ("ClinicTime")
) ;
CREATE INDEX IF NOT EXISTS clinict_clinic ON clinict USING btree ("Clinic") TABLESPACE pg_default;
COMMENT ON TABLE clinict IS 'Clinic Sessions';
COMMENT ON COLUMN clinict."Wednesday" IS 'Active on Wednesday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN clinict."Tuesday" IS 'Active on Tuesday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN clinict."Thursday" IS 'Active on Thursday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN clinict."Sunday" IS 'Active on Sunday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN clinict."StartDate" IS 'Start date for this clinic session (date this session definition becomes effective). ';
COMMENT ON COLUMN clinict."Start" IS 'Time that the session starts, in minutes from midnight.';
COMMENT ON COLUMN clinict."Saturday" IS 'Active on Saturday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN clinict."Period" IS 'Period for the clinic. Represented as a number 0..2 (Usually 0 = AM, 1 = PM, 2 = Evening)';
COMMENT ON COLUMN clinict."Monday" IS 'Active on Monday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN clinict."Import" IS 'Import code for importing data from delimited files.';
COMMENT ON COLUMN clinict."Friday" IS 'Active on Friday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN clinict."EndDate" IS 'End date for this clinic session (date this session definition is no longer effective).';
COMMENT ON COLUMN clinict."End" IS 'Time that the session ends, in minutes from midnight.';
COMMENT ON COLUMN clinict."Description" IS 'Name/description of the session.';
COMMENT ON COLUMN clinict."ClinicTime" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN clinict."Clinic" IS 'Clinic that this session is in, ptr to CLINIC.clinic';


CREATE  TABLE clinmax (
  "ClinMax" numeric(10,0) NOT NULL,
  "Clinic" numeric(10,0) NOT NULL,
  "ClinicTime" numeric(10,0) NOT NULL,
  "ProcTbl" numeric(10,0) NOT NULL,
  "DateFrom" timestamp without time zone,
  "DateTo" timestamp without time zone,
  "Limit" numeric(5,0),
  "LimitType" numeric(5,0),
  "Monday" numeric(5,0),
  "Tuesday" numeric(5,0),
  "Wednesday" numeric(5,0),
  "Thursday" numeric(5,0),
  "Friday" numeric(5,0),
  "Saturday" numeric(5,0),
  "Sunday" numeric(5,0),
  CONSTRAINT clinmax_primary PRIMARY KEY ("ClinMax")
) ;
CREATE INDEX IF NOT EXISTS clinmax_clinic ON clinmax USING btree ("Clinic", "ClinicTime", "DateFrom", "DateTo") TABLESPACE pg_default;
COMMENT ON TABLE clinmax IS 'Clinical procedure limits';
COMMENT ON COLUMN clinmax."Wednesday" IS 'This clinical limit applies to Wednesdays (0 = No, 1 = Yes) ';
COMMENT ON COLUMN clinmax."Tuesday" IS 'This clinical limit applies to Tuesdays (0 = No, 1 = Yes) ';
COMMENT ON COLUMN clinmax."Thursday" IS 'This clinical limit applies to Thursdays (0 = No, 1 = Yes) ';
COMMENT ON COLUMN clinmax."Sunday" IS 'This clinical limit applies to Sundays (0 = No, 1 = Yes) ';
COMMENT ON COLUMN clinmax."Saturday" IS 'This clinical limit applies to Saturdays (0 = No, 1 = Yes) ';
COMMENT ON COLUMN clinmax."ProcTbl" IS 'ProcTbl that defines the limits for the clinic, ptr to PROCTBL.ProcTbl';
COMMENT ON COLUMN clinmax."Monday" IS 'This clinical limit applies to Mondays (0 = No, 1 = Yes) ';
COMMENT ON COLUMN clinmax."LimitType" IS 'Type of clinical limit ( 0=, 1= ) ';
COMMENT ON COLUMN clinmax."Limit" IS 'Number to identify the limit.';
COMMENT ON COLUMN clinmax."Friday" IS 'This clinical limit applies to Fridays (0 = No, 1 = Yes) ';
COMMENT ON COLUMN clinmax."DateTo" IS 'Date the limit ends';
COMMENT ON COLUMN clinmax."DateFrom" IS 'Date the limit begins';
COMMENT ON COLUMN clinmax."ClinicTime" IS 'Clinic time to which this limit applies';
COMMENT ON COLUMN clinmax."Clinic" IS 'Id code of the clinic to which this applies, ptr to CLINIC.Clinic';
COMMENT ON COLUMN clinmax."ClinMax" IS 'Id code to identify this record, internal ID';


CREATE  TABLE clinsch (
  "ClinSch" numeric(10,0) NOT NULL,
  "Type" numeric(5,0),
  "Overdue" character(6),
  "Description" character(30),
  "StartDate" timestamp without time zone,
  "EndDate" timestamp without time zone,
  "Monday" numeric(5,0),
  "Tuesday" numeric(5,0),
  "Wednesday" numeric(5,0),
  "Thursday" numeric(5,0),
  "Friday" numeric(5,0),
  "Saturday" numeric(5,0),
  "Sunday" numeric(5,0),
  CONSTRAINT clinsch_primary PRIMARY KEY ("ClinSch")
) ;
CREATE INDEX IF NOT EXISTS clinsch_type ON clinsch USING btree ("Type", "Overdue") TABLESPACE pg_default;
COMMENT ON TABLE clinsch IS 'Clinic schedules. For use with Overdue functions';
COMMENT ON COLUMN clinsch."Wednesday" IS 'Applies to Wednesday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN clinsch."Type" IS 'Type of clinic schedule (0= General, 1= Specific)';
COMMENT ON COLUMN clinsch."Tuesday" IS 'Applies to Tuesday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN clinsch."Thursday" IS 'Applies to Thursday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN clinsch."Sunday" IS 'Applies to Sunday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN clinsch."StartDate" IS 'Start date of the schedule';
COMMENT ON COLUMN clinsch."Saturday" IS 'Applies to Saturday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN clinsch."Overdue" IS 'Overdue condition to which this applies, ptr to OVERDUE.Overdue';
COMMENT ON COLUMN clinsch."Monday" IS 'Applies to Monday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN clinsch."Friday" IS 'Applies to Friday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN clinsch."EndDate" IS 'End date of the schedule';
COMMENT ON COLUMN clinsch."Description" IS 'Description of the clinic schedule (ie: summer session)';
COMMENT ON COLUMN clinsch."ClinSch" IS 'Id code to identify this clinic schedule record';


CREATE  TABLE clmnote (
  "ClmNote" character(6) NOT NULL,
  "Text" character(100),
  CONSTRAINT clmnote_primary PRIMARY KEY ("ClmNote")
) ;
COMMENT ON TABLE clmnote IS 'Claim note records';
COMMENT ON COLUMN clmnote."Text" IS 'Text of the claim note';
COMMENT ON COLUMN clmnote."ClmNote" IS 'Id code to identify this claim note.';


CREATE  TABLE clmstcat (
  "Code" character(6) NOT NULL,
  "Description" character varying(500),
  "IsRejection" numeric(5,0),
  "ShowResponse" numeric(5,0),
  CONSTRAINT clmstcat_primary PRIMARY KEY ("Code")
) ;
COMMENT ON TABLE clmstcat IS 'Claim Status Category';
COMMENT ON COLUMN clmstcat."ShowResponse" IS '0 = Suppress response, 1 = Show response';
COMMENT ON COLUMN clmstcat."IsRejection" IS '1 = Its been rejected, 0 = has not been rejected';
COMMENT ON COLUMN clmstcat."Description" IS 'Claim Status Category Description';
COMMENT ON COLUMN clmstcat."Code" IS 'Claim Status Code, ptr to CLMSTCOD.Code';


CREATE  TABLE clmstcod (
  "Code" character(6) NOT NULL,
  "Description" character varying(500),
  CONSTRAINT clmstcod_primary PRIMARY KEY ("Code")
) ;
COMMENT ON TABLE clmstcod IS 'Claim Status Codes';
COMMENT ON COLUMN clmstcod."Description" IS 'Claim Status Code Description ';
COMMENT ON COLUMN clmstcod."Code" IS 'Claim Status Code';


CREATE  TABLE closure (
  "Reason" character varying(30) NOT NULL,
  "AllChairs" numeric(5,0),
  "IsDefault" numeric(5,0),
  "Inactive" numeric(5,0),
  CONSTRAINT closure_primary PRIMARY KEY ("Reason")
) ;
COMMENT ON TABLE closure IS 'Chair closure reason codes';
COMMENT ON COLUMN closure."Reason" IS 'Reason for the closure.';
COMMENT ON COLUMN closure."IsDefault" IS 'Default closure code? (0 = No, 1 = Yes)';
COMMENT ON COLUMN closure."Inactive" IS 'Code is inactive? (0 = No,1 = Yes)';
COMMENT ON COLUMN closure."AllChairs" IS 'Close all chairs when this reason is selected? (0 = No, 1 = Yes)';


CREATE  TABLE cnsacc (
  "CNState" character(6) NOT NULL,
  "SLevel" numeric(10,0) NOT NULL,
  "Access" numeric(5,0),
  CONSTRAINT cnsacc_primary PRIMARY KEY ("CNState", "SLevel")
) ;
COMMENT ON TABLE cnsacc IS 'Clinical Notification State Code Access';
COMMENT ON COLUMN cnsacc."SLevel" IS 'Primary key component; security level that the access rights are for, ptr to SLEVEL.SLevel';
COMMENT ON COLUMN cnsacc."CNState" IS 'Primary key component; chair state code, ptr to CNSTATE.CNState';
COMMENT ON COLUMN cnsacc."Access" IS 'Access rights for this chair state (0=No, 1=Yes, can set)';


CREATE  TABLE cnstate (
  "CNState" character(6) NOT NULL,
  "ShortDesc" character(12),
  "Description" character varying(30),
  "Order" numeric(5,0),
  "BkgColor" numeric(10,0),
  "PtColorPersists" numeric(5,0),
  "SessionBased" numeric(5,0),
  "Inactive" numeric(5,0),
  "Priority" numeric(5,0),
  "IsApprRequest" numeric(5,0),
  CONSTRAINT cnstate_primary PRIMARY KEY ("CNState")
) ;
COMMENT ON TABLE cnstate IS 'Clinical Notification State Codes';
COMMENT ON COLUMN cnstate."ShortDesc" IS 'Short description of the notification state.';
COMMENT ON COLUMN cnstate."SessionBased" IS 'Is this notification state session-based? (0=No, 1=Yes)';
COMMENT ON COLUMN cnstate."PtColorPersists" IS 'Pt appointment text displays with state color? (0=No (black text), 1=Yes (Pt APPT color))';
COMMENT ON COLUMN cnstate."Priority" IS 'Priority for this notification state (0=Low, 1=Medium, 2=High)';
COMMENT ON COLUMN cnstate."Order" IS 'Order to display in the list when sending notification.';
COMMENT ON COLUMN cnstate."IsApprRequest" IS 'Indicates an Approval request to Faculty';
COMMENT ON COLUMN cnstate."Inactive" IS 'Is this notification state inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN cnstate."Description" IS 'Full description / menu text of the notification state.';
COMMENT ON COLUMN cnstate."CNState" IS 'Primary key, chair notification state code. ';
COMMENT ON COLUMN cnstate."BkgColor" IS 'Background color of notification, as decimal representation of RGB value. ';


CREATE  TABLE code_mapping (
  "RecordType" numeric(5,0) NOT NULL,
  "DataType" numeric(5,0),
  "ExternalCode" character varying(255) NOT NULL,
  "MapNumber" numeric(5,0),
  "MapCode" character(6),
  "MapOther" character varying(255),
  CONSTRAINT code_mapping_pk PRIMARY KEY ("RecordType", "ExternalCode")
) ;
COMMENT ON TABLE code_mapping IS 'Mapping table for miscellaneous codes';
COMMENT ON COLUMN code_mapping."RecordType" IS 'Primary key, type of records (1- Gender, 2 - Marital, 3 - Language, 4 - Race, 5 - Ethnicity)';
COMMENT ON COLUMN code_mapping."MapOther" IS 'Mapping other code (for future)';
COMMENT ON COLUMN code_mapping."MapNumber" IS 'Mapping code (in number)';
COMMENT ON COLUMN code_mapping."MapCode" IS 'Mapping standard code';
COMMENT ON COLUMN code_mapping."ExternalCode" IS 'External code received from inbound record';
COMMENT ON COLUMN code_mapping."DataType" IS 'Data type of the record to map to (0 - numeric, 1 - alpha, 2 - other)';


CREATE  TABLE comacc (
  "Auto" numeric(10,0) NOT NULL,
  "SLevel" numeric(10,0) NOT NULL,
  "Access" numeric(5,0),
  CONSTRAINT comacc_pk PRIMARY KEY ("Auto", "SLevel")
) ;
COMMENT ON TABLE comacc IS 'Table for storing the user access to clinical note codes';
COMMENT ON COLUMN comacc."SLevel" IS 'Primary key component, ptr to SLEVEL.SLEVEL';
COMMENT ON COLUMN comacc."Auto" IS 'Primary key component, the internal ID from sequence that was added to this note. Ptr to COMMENT2.Auto';
COMMENT ON COLUMN comacc."Access" IS 'Access to the clinical code note for this security level (0=None, 1= Full Access)';


CREATE  TABLE comment2 (
  "Auto" numeric(10,0) NOT NULL,
  "Type" numeric(5,0),
  "Code" character(7),
  "Description" character varying(4000),
  "SectionNo" numeric(5,0),
  "Level" numeric(5,0),
  "IsNode" numeric(5,0),
  "Deleted" numeric(5,0),
  "Heading" character varying(20),
  "FormCode" character(6),
  "Audit" numeric(10,0),
  rtfdescription clob,
  CONSTRAINT comment2_primary PRIMARY KEY ("Auto")
) ;
CREATE INDEX IF NOT EXISTS "COMMENT2_Code" ON comment2 USING btree ("Code") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS "COMMENT2_Type" ON comment2 USING btree ("Type", "SectionNo", "Code") TABLESPACE pg_default;
COMMENT ON TABLE comment2 IS 'Clinical Patient Note Codes';
COMMENT ON COLUMN comment2.rtfdescription IS 'Free RTF text area to enter the text of the note code.';
COMMENT ON COLUMN comment2."Type" IS 'Type of note code (0=General, 1=SOAP, 2=Template)';
COMMENT ON COLUMN comment2."SectionNo" IS 'If Type = 1, the section that this note code corresponds to (0=Subjective, 1=Objective, 2=Assessment, 3=Planned) ';
COMMENT ON COLUMN comment2."Level" IS 'Node level in tree.';
COMMENT ON COLUMN comment2."IsNode" IS 'Item is a node? (0= item is a heading, 1=item is a node)';
COMMENT ON COLUMN comment2."Heading" IS 'Optional heading for the note code.';
COMMENT ON COLUMN comment2."FormCode" IS 'If Type=2, ptr to FORM.Code.';
COMMENT ON COLUMN comment2."Description" IS 'Free text area to enter the text of the note code.';
COMMENT ON COLUMN comment2."Deleted" IS 'Item is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN comment2."Code" IS 'Code used to reference this predefined note.';
COMMENT ON COLUMN comment2."Auto" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN comment2."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE commenth (
  "CommentH" numeric(10,0) NOT NULL,
  "Auto" numeric(10,0),
  "Type" numeric(5,0),
  "Code" character(7),
  "Description" character varying(4000),
  "SectionNo" numeric(5,0),
  "Level" numeric(5,0),
  "IsNode" numeric(5,0),
  "Deleted" numeric(5,0),
  "Heading" character varying(20),
  "FormCode" character(6),
  "Audit" numeric(10,0),
  rtfdescription clob,
  CONSTRAINT commenth_primary PRIMARY KEY ("CommentH")
) ;
CREATE INDEX IF NOT EXISTS commenth_code ON commenth USING btree ("Code", "Audit") TABLESPACE pg_default;
COMMENT ON TABLE commenth IS 'Clinical Patient Note Code History';
COMMENT ON COLUMN commenth.rtfdescription IS 'Free RTF text area to enter the text of the note code.';
COMMENT ON COLUMN commenth."Type" IS 'Type of note code (0=General, 1=SOAP, 2=Template)';
COMMENT ON COLUMN commenth."SectionNo" IS 'If Type = 1, the section that this note code corresponds to (0=Subjective, 1=Objective, 2=Assessment, 3=Planned) ';
COMMENT ON COLUMN commenth."Level" IS 'Node level in tree.';
COMMENT ON COLUMN commenth."IsNode" IS 'Item is a node? (0= item is a heading, 1=item is a node)';
COMMENT ON COLUMN commenth."Heading" IS 'Optional heading for the note code.';
COMMENT ON COLUMN commenth."FormCode" IS 'If Type=2, ptr to FORM.Code.';
COMMENT ON COLUMN commenth."Description" IS 'Free text area to enter the text of the note code.';
COMMENT ON COLUMN commenth."Deleted" IS 'Item is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN commenth."CommentH" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN commenth."Code" IS 'Code used to reference this predefined note.';
COMMENT ON COLUMN commenth."Auto" IS 'Note code that this history is for, ptr to COMMENT2.Auto';
COMMENT ON COLUMN commenth."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE complain (
  "Auto" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "User" numeric(10,0),
  "Prob_Desc" character(255),
  "Clinical_Sign" character(255),
  "Time" timestamp without time zone,
  "DisableGtx" numeric(5,0),
  "Description" character varying(30),
  CONSTRAINT complain_primary PRIMARY KEY ("Auto")
) ;
COMMENT ON TABLE complain IS 'Treatment Plan Complaints';
COMMENT ON COLUMN complain."User" IS 'User ID of entry user, ptr to USERS.User';
COMMENT ON COLUMN complain."Time" IS 'Date/time of entry. ';
COMMENT ON COLUMN complain."Prob_Desc" IS 'Patients Chief Concern(s), user-entered text. ';
COMMENT ON COLUMN complain."Patient" IS 'Patient ID that the treatment plan is for, ptr to PATIENT.Patient';
COMMENT ON COLUMN complain."DisableGtx" IS 'Disable general treatment plan? (0 = No, 1 = Yes)';
COMMENT ON COLUMN complain."Description" IS 'Description or name for the treatment plan';
COMMENT ON COLUMN complain."Clinical_Sign" IS 'Additional Problems, user-entered text. ';
COMMENT ON COLUMN complain."Auto" IS 'Primary key, internal ID from sequence.';


CREATE  TABLE consacc (
  "Consent" character(6) NOT NULL,
  "SLevel" numeric(10,0) NOT NULL,
  "Access" numeric(5,0),
  CONSTRAINT consacc_primary PRIMARY KEY ("Consent", "SLevel")
) ;
COMMENT ON TABLE consacc IS 'Access rights for consents.';
COMMENT ON COLUMN consacc."SLevel" IS 'Primary key component, ptr to SLEVEL.SLevel';
COMMENT ON COLUMN consacc."Consent" IS 'Primary key component, ptr to CONSENT.Consent';
COMMENT ON COLUMN consacc."Access" IS 'Access to the consent for this security level (0=Read Only, 1=Full Access)';


CREATE  TABLE consent (
  "Consent" character(6) NOT NULL,
  "Description" character varying(30),
  "Inactive" numeric(5,0),
  "OnLineForm" numeric(5,0),
  "FilePath" character varying(255),
  content bytea,
  "DenialText" character varying(100),
  "PtSigRequired" numeric(5,0),
  "CanDeny" numeric(5,0),
  "TxBased" numeric(5,0),
  "AtTab" numeric(10,0),
  "DefaultExpiryPeriod" numeric(5,0),
  "DefaultExpiryFreq" numeric(5,0),
  "ExpiryRequired" numeric(5,0),
  "PassUser" numeric(5,0),
  CONSTRAINT consent_primary PRIMARY KEY ("Consent")
) ;
COMMENT ON TABLE consent IS 'Consent Types';
COMMENT ON COLUMN consent.content IS 'Oracle field that holds the consent data. Note: In Oracle 9i this field is Type: BLOB';
COMMENT ON COLUMN consent."TxBased" IS 'Yes/No field to determine whether cosents is linked to treatments';
COMMENT ON COLUMN consent."PtSigRequired" IS 'Signature required? (0 = No, 1 = Yes )';
COMMENT ON COLUMN consent."PassUser" IS 'Pass the current user for this consent? (0=No, 1=Yes)';
COMMENT ON COLUMN consent."OnLineForm" IS 'Online form with signature? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN consent."Inactive" IS 'Inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN consent."FilePath" IS 'The UNC file path that indicates where this consent template is found';
COMMENT ON COLUMN consent."ExpiryRequired" IS 'Is an expiry date required? (0=No, 1=Yes)';
COMMENT ON COLUMN consent."Description" IS 'Description of the consent.';
COMMENT ON COLUMN consent."DenialText" IS 'Custom text for the consent signature dialog to explain consequences of denying the consent (we have a default if this is not set) ';
COMMENT ON COLUMN consent."DefaultExpiryPeriod" IS 'Number of days/weeks/months/years for default expiry.';
COMMENT ON COLUMN consent."DefaultExpiryFreq" IS 'Unit of default expiry (0=days, 1=weeks, 2=months, 3=years)';
COMMENT ON COLUMN consent."Consent" IS 'ID code to identify the consent record. ';
COMMENT ON COLUMN consent."CanDeny" IS '0 = Cannot Deny (deny option will not show on signature window), 1 = Consent can be denied';
COMMENT ON COLUMN consent."AtTab" IS 'Id of attachment manager tab to use as the default tab to store this consent. Ptr to ATTAB.AtTab.';


CREATE  TABLE consinit (
  "ConsInit" numeric(10,0) NOT NULL,
  "Consent" character(6),
  "Page" numeric(5,0),
  "Order" numeric(5,0),
  "Required" numeric(5,0),
  "Description" character varying(255),
  CONSTRAINT consinit_primary PRIMARY KEY ("ConsInit")
) ;
COMMENT ON TABLE consinit IS 'New Consent Patient Initials Table';
COMMENT ON COLUMN consinit."Required" IS 'Initial required? (0 = No, 1 = Yes)';
COMMENT ON COLUMN consinit."Page" IS 'Page that this initial belongs to';
COMMENT ON COLUMN consinit."Order" IS 'Order to prompt initial for (1..x)';
COMMENT ON COLUMN consinit."Description" IS 'Description to show for initials prompt';
COMMENT ON COLUMN consinit."Consent" IS 'Consent code initial required for, ptr to CONSENT.Consent.';
COMMENT ON COLUMN consinit."ConsInit" IS 'Primary key, internal ID from sequence.';


CREATE  TABLE consreq (
  "ConsReq" numeric(10,0) NOT NULL,
  "Description" character varying(30),
  "RuleType" numeric(5,0),
  "Consent" character(6),
  "Function" character varying(50),
  CONSTRAINT consreq_primary PRIMARY KEY ("ConsReq")
) ;
COMMENT ON TABLE consreq IS 'Consent Requirement Rules';
COMMENT ON COLUMN consreq."RuleType" IS 'Type of the rule (0=Any Tx Consent, 1=Specific Consent, 2=Custom Function)';
COMMENT ON COLUMN consreq."Function" IS '(Optional) Name of Oracle function to override the consent required. ';
COMMENT ON COLUMN consreq."Description" IS 'Description of the rule.';
COMMENT ON COLUMN consreq."Consent" IS 'Consent code that is required, ptr to CONSENT.Consent';
COMMENT ON COLUMN consreq."ConsReq" IS 'Primary key, internal ID from sequence.';


CREATE  TABLE conssig (
  "ConsentSig" numeric(10,0) NOT NULL,
  "Consent" character(6),
  "Order" numeric(5,0),
  "Signee" character varying(30),
  "Required" numeric(5,0),
  "NameRequired" numeric(5,0),
  CONSTRAINT conssig_primary PRIMARY KEY ("ConsentSig")
) ;
COMMENT ON TABLE conssig IS 'Consent Signature Requirements';
COMMENT ON COLUMN conssig."Signee" IS 'Type or role of the signee.';
COMMENT ON COLUMN conssig."Required" IS 'Signature required? (0 = No, 1 = Yes )';
COMMENT ON COLUMN conssig."Order" IS 'Order to prompt signature for (1..x)';
COMMENT ON COLUMN conssig."NameRequired" IS 'Name required? (0 = No, 1 = Yes )';
COMMENT ON COLUMN conssig."ConsentSig" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN conssig."Consent" IS 'Consent code signature required for, ptr to CONSENT.Consent.';


CREATE  TABLE consults (
  "Id" numeric(5,0) NOT NULL,
  "Desc" character(20),
  "ReqApprove" numeric(5,0),
  "ShortDesc" character(3),
  CONSTRAINT consults_primary PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE consults IS 'Consultant Type Codes';
COMMENT ON COLUMN consults."ShortDesc" IS '3 digit abbreviation for the consultant type. Used as a column heading in the detailed tab of the Treatment Planning module.';
COMMENT ON COLUMN consults."ReqApprove" IS 'Consult type requires approval? (0 = No, 1 = Yes)';
COMMENT ON COLUMN consults."Id" IS 'Primary key, internal ID autogenerated from axiUm (not sequenced).';
COMMENT ON COLUMN consults."Desc" IS 'Description of the consultant type. ';


CREATE  TABLE continit (
  "Contract" numeric(10,0) NOT NULL,
  "Page" numeric(5,0),
  "Order" numeric(5,0),
  "PtSig" numeric(10,0) NOT NULL,
  CONSTRAINT continit_primary PRIMARY KEY ("Contract", "PtSig")
) ;
COMMENT ON TABLE continit IS 'New Contract Patient Initials Table';
COMMENT ON COLUMN continit."PtSig" IS 'Primary key component, initials for this contract. Ptr to PTSIG.PtSig.';
COMMENT ON COLUMN continit."Page" IS 'Page that this initial belongs to';
COMMENT ON COLUMN continit."Order" IS 'Order on the page this initial goes';
COMMENT ON COLUMN continit."Contract" IS 'Primary key component, contract that this initial is for. Ptr to CONTRACT.Contract.';


CREATE  TABLE contract (
  "Contract" numeric(10,0) NOT NULL,
  "Type" numeric(5,0),
  "Date" timestamp without time zone,
  "Patient" numeric(10,0),
  "PtSig" numeric(10,0),
  content bytea,
  "Audit" numeric(10,0),
  "AtTab" numeric(10,0),
  "Consent" character(6),
  "ExpiryDate" timestamp without time zone,
  "Deleted" numeric(5,0),
  "DelAudit" numeric(10,0),
  "Denied" numeric(5,0),
  "SigStatus" numeric(5,0),
  "FileExt" character varying(32),
  "Description" character varying(80),
  "AddDateTime" timestamp without time zone,
  CONSTRAINT contract_primary PRIMARY KEY ("Contract")
) ;
CREATE INDEX IF NOT EXISTS contract_pattypedatekey ON contract USING btree ("Patient", "Type", "Date" DESC) TABLESPACE pg_default;
COMMENT ON TABLE contract IS 'Contracts for payment plans and treatment estimates';
COMMENT ON COLUMN contract.content IS 'Internal data field to store a pdf format copy of the contract. Note: In Oracle 9i this field is Type: BLOB';
COMMENT ON COLUMN contract."Type" IS 'Type of contract (0 = Tx estimate, 1 = payment plan, 2 = Treatment Plan, 3 = Online Consent )';
COMMENT ON COLUMN contract."SigStatus" IS 'In the case of a treatment plan - 0 = Printed for patient but no captured, 1 = Signed electronically, 2 = Scanned';
COMMENT ON COLUMN contract."PtSig" IS 'Id code to identify the patient signature record, ptr to PTSIG.PtSig';
COMMENT ON COLUMN contract."Patient" IS 'Id code to identify the patient, ptr to PATIENT.Patient';
COMMENT ON COLUMN contract."FileExt" IS 'To store the file extension of the contract BLOB. Previously always PDF.';
COMMENT ON COLUMN contract."ExpiryDate" IS 'Expiry date of the consent';
COMMENT ON COLUMN contract."Description" IS 'Description of contract';
COMMENT ON COLUMN contract."Denied" IS 'Contract has been denied 0= No, 1 = Yes';
COMMENT ON COLUMN contract."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN contract."DelAudit" IS 'Audit history, ptr to AUDITHIS.Audit of the deletion ';
COMMENT ON COLUMN contract."Date" IS 'Date contract signed ';
COMMENT ON COLUMN contract."Contract" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN contract."Consent" IS 'Consent code to which this relates, ptr to CONSENT.Consent';
COMMENT ON COLUMN contract."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN contract."AtTab" IS 'Ptr to ATTAB.AtTab to show attachment in';
COMMENT ON COLUMN contract."AddDateTime" IS 'Date/time of entry.';


CREATE  TABLE contsig (
  "Contract" numeric(10,0) NOT NULL,
  "Signee" character varying(30),
  "Name" character varying(60),
  "PtSig" numeric(10,0) NOT NULL,
  CONSTRAINT contsig_primary PRIMARY KEY ("Contract", "PtSig")
) ;
COMMENT ON TABLE contsig IS 'Contract Signatures';
COMMENT ON COLUMN contsig."Signee" IS 'Type or role of the signee.';
COMMENT ON COLUMN contsig."PtSig" IS 'Primary key component, signature for this contract. Ptr to PTSIG.PtSig.';
COMMENT ON COLUMN contsig."Name" IS 'Name of the signee';
COMMENT ON COLUMN contsig."Contract" IS 'Primary key component, contract that this signature is for. Ptr to CONTRACT.Contract.';


CREATE  TABLE country (
  "Country" character(30) NOT NULL,
  "UseAddressCheck" numeric(5,0),
  CONSTRAINT country_primary PRIMARY KEY ("Country")
) ;
COMMENT ON TABLE country IS 'Look up table for Countries';
COMMENT ON COLUMN country."UseAddressCheck" IS 'Use address check? (0 = No, 1 = Yes)';
COMMENT ON COLUMN country."Country" IS 'Primary key, ID code to identify the country. ';


CREATE  TABLE coverage (
  "Coverage" numeric(10,0) NOT NULL,
  "Description" character(30),
  "Audit" numeric(10,0),
  "Order" numeric(10,0),
  "Inactive" numeric(5,0),
  "IsRider" numeric(5,0),
  CONSTRAINT coverage_primary PRIMARY KEY ("Coverage")
) ;
COMMENT ON TABLE coverage IS 'Insurance Policy Coverage Templates';
COMMENT ON COLUMN coverage."Order" IS 'Number to represent the order in which this coverage will appear in the Coverage Template List.';
COMMENT ON COLUMN coverage."IsRider" IS 'Is this coverage template a rider template? (0=No, 1=Yes)';
COMMENT ON COLUMN coverage."Inactive" IS 'Is this coverage template inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN coverage."Description" IS 'Description of the coverage template';
COMMENT ON COLUMN coverage."Coverage" IS 'Primary key, numeric ID code to identify the coverage template. ';
COMMENT ON COLUMN coverage."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE coverfit (
  "CoverFrq" numeric(10,0) NOT NULL,
  "Procedure" character(7) NOT NULL,
  CONSTRAINT coverfit_primary PRIMARY KEY ("CoverFrq", "Procedure")
) ;
COMMENT ON TABLE coverfit IS 'New Coverage Limits Frequency Item Table';
COMMENT ON COLUMN coverfit."Procedure" IS 'Procedure code';
COMMENT ON COLUMN coverfit."CoverFrq" IS 'Parent record';


CREATE  TABLE coverfrq (
  "CoverFrq" numeric(10,0) NOT NULL,
  "ParentType" numeric(5,0),
  "ParentId" numeric(10,0),
  "Item" numeric(5,0),
  "Description" character varying(30),
  "Frequency" numeric(10,0),
  "FrequencyFlag" numeric(5,0),
  "Times" numeric(10,0),
  CONSTRAINT coverfrq_primary PRIMARY KEY ("CoverFrq")
) ;
CREATE INDEX IF NOT EXISTS coverfrq_parentkey ON coverfrq USING btree ("ParentType", "ParentId", "Item") TABLESPACE pg_default;
COMMENT ON TABLE coverfrq IS 'New Coverage Limits Frequency Table';
COMMENT ON COLUMN coverfrq."Times" IS '# of times list of procedures will be covered in frequency range';
COMMENT ON COLUMN coverfrq."ParentType" IS 'Parent type (0 – COVERAGE, 1 – POLINS)';
COMMENT ON COLUMN coverfrq."ParentId" IS 'Parent record id (Coverage or PolIns Id, based on ParentType)';
COMMENT ON COLUMN coverfrq."Item" IS 'User definable item #';
COMMENT ON COLUMN coverfrq."FrequencyFlag" IS 'Frequency period (0=N/A, 1=Months, 2=Years, 3=Policy Years, 4=Life Time)';
COMMENT ON COLUMN coverfrq."Frequency" IS 'Frequency limit period (used with the frequency flag)';
COMMENT ON COLUMN coverfrq."Description" IS 'Name / description';
COMMENT ON COLUMN coverfrq."CoverFrq" IS 'Primary key, internal ID from sequence.';


CREATE  TABLE coverhis (
  "CoverHis" numeric(10,0) NOT NULL,
  "Coverage" numeric(10,0),
  "Description" character(30),
  "Audit" numeric(10,0),
  "Order" numeric(10,0),
  "Inactive" numeric(5,0),
  "IsRider" numeric(5,0),
  CONSTRAINT coverhis_primary PRIMARY KEY ("CoverHis")
) ;
CREATE INDEX IF NOT EXISTS coverhis_coverage ON coverhis USING btree ("Coverage") TABLESPACE pg_default;
COMMENT ON TABLE coverhis IS 'Insurance Policy Coverage Template History';
COMMENT ON COLUMN coverhis."Order" IS 'Number to represent the order in which this coverage will appear in the Coverage Template List.';
COMMENT ON COLUMN coverhis."IsRider" IS 'Is this coverage template a rider template? (0=No, 1=Yes)';
COMMENT ON COLUMN coverhis."Inactive" IS 'Is this coverage template inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN coverhis."Description" IS 'Description of the coverage template';
COMMENT ON COLUMN coverhis."Coverage" IS 'Coverage template that this history is for, ptr to COVERAGE.Coverage';
COMMENT ON COLUMN coverhis."CoverHis" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN coverhis."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE coverit (
  "Coverage" numeric(10,0),
  "Item" numeric(10,0),
  "Description" character(30),
  "Category" character(6),
  "FromProcedure" character(7),
  "ToProcedure" character(7),
  "Percent" numeric,
  "Frequency" numeric(10,0),
  "FrequencyFlag" numeric(5,0),
  "Times" numeric(10,0),
  "CoverIt" numeric(10,0) NOT NULL,
  "HasCatLimit" numeric(5,0),
  "CatLimit" numeric,
  "CatPeriod" numeric(10,0),
  "CatFrequency" numeric(5,0),
  "HasItemLimit" numeric(5,0),
  "ItemLimit" numeric,
  "ItemPeriod" numeric(10,0),
  "ItemFrequency" numeric(5,0),
  "CatDeduct" numeric,
  "CatAffectFamily" numeric(5,0),
  "HasCategory" numeric(5,0),
  "Audit" numeric(10,0),
  "ItemDeduct" numeric,
  "ItemAffectFamily" numeric(5,0),
  "ItemPtChg" numeric,
  "LimitOnPatient" numeric(5,0),
  "AgeRules" numeric(5,0),
  "AgeFrom" numeric(5,0),
  "AgeTo" numeric(5,0),
  "SiteRules" numeric(5,0),
  "CatLimitChildOnly" numeric(5,0) NOT NULL DEFAULT 0,
  "HasCatFamilyLimit" numeric(5,0) NOT NULL DEFAULT 0,
  "CatFamilyLimit" numeric NOT NULL DEFAULT 0,
  CONSTRAINT coverit_primary PRIMARY KEY ("CoverIt")
) ;
CREATE INDEX IF NOT EXISTS coverit_coverageitem ON coverit USING btree ("Coverage", "Item") TABLESPACE pg_default;
COMMENT ON TABLE coverit IS 'Insurance Policy Coverage Template Items';
COMMENT ON COLUMN coverit."ToProcedure" IS 'End of procedure code range, ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN coverit."Times" IS '# of times procedure will be covered in frequency range, to be used in conjunction with the Frequency and FrequencyFlag fields';
COMMENT ON COLUMN coverit."SiteRules" IS 'Does this line item have tooth-specific coverage rules? (0=No, 1=Yes)';
COMMENT ON COLUMN coverit."Percent" IS 'Percentage of coverage for procedure range, ie: 100 for 100%';
COMMENT ON COLUMN coverit."LimitOnPatient" IS 'Is this a patient limit? (0=No (limit on insurance), 1=Yes (limit on patient maximum), 2=Yes (limit on patient maximum + deductable))';
COMMENT ON COLUMN coverit."ItemPtChg" IS 'Dollar value ($) to be charged to the patient for this item ';
COMMENT ON COLUMN coverit."ItemPeriod" IS 'Item period';
COMMENT ON COLUMN coverit."ItemLimit" IS 'Dollar ($) amount of the item limit';
COMMENT ON COLUMN coverit."ItemFrequency" IS 'Item Frequency';
COMMENT ON COLUMN coverit."ItemDeduct" IS 'Dollar ($) value of the optional deductible per item';
COMMENT ON COLUMN coverit."ItemAffectFamily" IS 'Item affects family deductibles (0 = No, 1 = Yes)';
COMMENT ON COLUMN coverit."Item" IS 'Primary key component, coverage template line item.';
COMMENT ON COLUMN coverit."HasItemLimit" IS 'Has item limit? (0 = No, 1 = Yes)';
COMMENT ON COLUMN coverit."HasCategory" IS 'Has category? (0 = No, 1 = Yes)';
COMMENT ON COLUMN coverit."HasCatLimit" IS 'Has category limit? (0 = No, 1 = Yes)';
COMMENT ON COLUMN coverit."HasCatFamilyLimit" IS 'Has category family limit? (0 = No, 1 = Yes)';
COMMENT ON COLUMN coverit."FromProcedure" IS 'Start of Procedure code range, ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN coverit."FrequencyFlag" IS 'Frequency period (0=N/A, 1=Months, 2=Years, 3=Policy Years, 4=Life Time)';
COMMENT ON COLUMN coverit."Frequency" IS 'Frequency limit period (used with the frequency flag)';
COMMENT ON COLUMN coverit."Description" IS 'Description of the line item';
COMMENT ON COLUMN coverit."Coverage" IS 'Primary key component, coverage template that this item is part of. Ptr to COVERAGE.Coverage. ';
COMMENT ON COLUMN coverit."CoverIt" IS 'Internal ID from sequence.';
COMMENT ON COLUMN coverit."Category" IS 'Category of coverage line (Basic, Major, Ortho, etc.)';
COMMENT ON COLUMN coverit."CatPeriod" IS 'Category Period, like 4';
COMMENT ON COLUMN coverit."CatLimitChildOnly" IS 'Flag to determine whether or not the Patient Maximum applies to children only which is based on the policy child age';
COMMENT ON COLUMN coverit."CatLimit" IS 'Dollar ($) value of the category limit';
COMMENT ON COLUMN coverit."CatFrequency" IS 'Category Limit frequency, (0=N/A, 1=Mo, …)';
COMMENT ON COLUMN coverit."CatFamilyLimit" IS 'Dollar ($) value of the category family limit';
COMMENT ON COLUMN coverit."CatDeduct" IS 'Dollar ($) value of the category deductible';
COMMENT ON COLUMN coverit."CatAffectFamily" IS 'Affects family limits/deductibles? (0 = No, 1 = Yes)';
COMMENT ON COLUMN coverit."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN coverit."AgeTo" IS 'End of patient age range to which line item applies';
COMMENT ON COLUMN coverit."AgeRules" IS 'Age-specific coverage? (0 = No, 1 = Yes)';
COMMENT ON COLUMN coverit."AgeFrom" IS 'Start of patient age range to which line item applies';


CREATE  TABLE covithis (
  "CovItHis" numeric(10,0) NOT NULL,
  "Coverage" numeric(10,0),
  "Item" numeric(10,0),
  "Description" character(30),
  "Category" character(6),
  "FromProcedure" character(7),
  "ToProcedure" character(7),
  "Percent" numeric,
  "Frequency" numeric(10,0),
  "FrequencyFlag" numeric(5,0),
  "Times" numeric(10,0),
  "CoverIt" numeric(10,0),
  "HasCatLimit" numeric(5,0),
  "CatLimit" numeric,
  "CatPeriod" numeric(10,0),
  "CatFrequency" numeric(5,0),
  "HasItemLimit" numeric(5,0),
  "ItemLimit" numeric,
  "ItemPeriod" numeric(10,0),
  "ItemFrequency" numeric(5,0),
  "CatDeduct" numeric,
  "CatAffectFamily" numeric(5,0),
  "HasCategory" numeric(5,0),
  "Audit" numeric(10,0),
  "ItemDeduct" numeric,
  "ItemAffectFamily" numeric(5,0),
  "ItemPtChg" numeric,
  "LimitOnPatient" numeric(5,0),
  "AgeRules" numeric(5,0),
  "AgeFrom" numeric(5,0),
  "AgeTo" numeric(5,0),
  "SiteRules" numeric(5,0),
  "CatLimitChildOnly" numeric(5,0) NOT NULL DEFAULT 0,
  "HasCatFamilyLimit" numeric(5,0) NOT NULL DEFAULT 0,
  "CatFamilyLimit" numeric NOT NULL DEFAULT 0,
  CONSTRAINT covithis_primary PRIMARY KEY ("CovItHis")
) ;
CREATE INDEX IF NOT EXISTS covithis_coveragekey ON covithis USING btree ("Coverage", "Item") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS covithis_coverit ON covithis USING btree ("CoverIt") TABLESPACE pg_default;
COMMENT ON TABLE covithis IS 'Insurance Policy Coverage Template Item History';
COMMENT ON COLUMN covithis."ToProcedure" IS 'End of procedure code range, ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN covithis."Times" IS '# of times procedure will be covered in frequency range, to be used in conjunction with the Frequency and FrequencyFlag fields';
COMMENT ON COLUMN covithis."SiteRules" IS 'Does this line item have tooth-specific coverage rules? (0=No, 1=Yes)';
COMMENT ON COLUMN covithis."Percent" IS 'Percentage of coverage for procedure range, ie: 100 for 100%';
COMMENT ON COLUMN covithis."LimitOnPatient" IS 'Is this a patient limit? (0=No (limit on insurance), 1=Yes (limit on patient maximum), 2=Yes (limit on patient maximum + deductable))';
COMMENT ON COLUMN covithis."ItemPtChg" IS 'Dollar value ($) to be charged to the patient for this item ';
COMMENT ON COLUMN covithis."ItemPeriod" IS 'Item period';
COMMENT ON COLUMN covithis."ItemLimit" IS 'Dollar ($) amount of the item limit';
COMMENT ON COLUMN covithis."ItemFrequency" IS 'Item Frequency';
COMMENT ON COLUMN covithis."ItemDeduct" IS 'Dollar ($) value of the optional deductible per item';
COMMENT ON COLUMN covithis."ItemAffectFamily" IS 'Item affects family deductibles (0 = No, 1 = Yes)';
COMMENT ON COLUMN covithis."Item" IS 'Coverage template line item.';
COMMENT ON COLUMN covithis."HasItemLimit" IS 'Has item limit? (0 = No, 1 = Yes)';
COMMENT ON COLUMN covithis."HasCategory" IS 'Has category? (0 = No, 1 = Yes)';
COMMENT ON COLUMN covithis."HasCatLimit" IS 'Has category limit? (0 = No, 1 = Yes)';
COMMENT ON COLUMN covithis."HasCatFamilyLimit" IS 'Has category family limit? (0 = No, 1 = Yes)';
COMMENT ON COLUMN covithis."FromProcedure" IS 'Start of Procedure code range, ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN covithis."FrequencyFlag" IS 'Frequency period (0=N/A, 1=Months, 2=Years, 3=Policy Years, 4=Life Time)';
COMMENT ON COLUMN covithis."Frequency" IS 'Frequency limit period (used with the frequency flag)';
COMMENT ON COLUMN covithis."Description" IS 'Description of the line item';
COMMENT ON COLUMN covithis."Coverage" IS 'Coverage template that this item is part of. Ptr to COVERAGE.Coverage. ';
COMMENT ON COLUMN covithis."CoverIt" IS 'Internal ID from sequence.';
COMMENT ON COLUMN covithis."CovItHis" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN covithis."Category" IS 'Category of coverage line (Basic, Major, Ortho, etc.)';
COMMENT ON COLUMN covithis."CatPeriod" IS 'Category Period, like 4';
COMMENT ON COLUMN covithis."CatLimitChildOnly" IS 'Flag to determine whether or not the Patient Maximum applies to children only which is based on the policy child age';
COMMENT ON COLUMN covithis."CatLimit" IS 'Dollar ($) value of the category limit';
COMMENT ON COLUMN covithis."CatFrequency" IS 'Category Limit frequency, (0=N/A, 1=Mo, …)';
COMMENT ON COLUMN covithis."CatFamilyLimit" IS 'Dollar ($) value of the category family limit';
COMMENT ON COLUMN covithis."CatDeduct" IS 'Dollar ($) value of the category deductible';
COMMENT ON COLUMN covithis."CatAffectFamily" IS 'Affects family limits/deductibles? (0 = No, 1 = Yes)';
COMMENT ON COLUMN covithis."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN covithis."AgeTo" IS 'End of patient age range to which line item applies';
COMMENT ON COLUMN covithis."AgeRules" IS 'Age-specific coverage? (0 = No, 1 = Yes)';
COMMENT ON COLUMN covithis."AgeFrom" IS 'Start of patient age range to which line item applies';


CREATE  TABLE covsite (
  "CoverIt" numeric(10,0) NOT NULL,
  "Site" character varying(3) NOT NULL,
  "Audit" numeric(10,0),
  CONSTRAINT convsite_primary PRIMARY KEY ("CoverIt", "Site")
) ;
COMMENT ON TABLE covsite IS 'Sites for tooth-specific coverage items.';
COMMENT ON COLUMN covsite."Site" IS 'Primary key component, Site that is covered.';
COMMENT ON COLUMN covsite."CoverIt" IS 'Primary key component, coverage item this site is covered for. Ptr to COVERIT.CoverIt';
COMMENT ON COLUMN covsite."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE covsiteh (
  "CovSiteH" numeric(10,0) NOT NULL,
  "CoverIt" numeric(10,0),
  "Site" character varying(3),
  "Audit" numeric(10,0),
  CONSTRAINT covsiteh_primary PRIMARY KEY ("CovSiteH")
) ;
COMMENT ON TABLE covsiteh IS 'History of sites for tooth-specific coverage items. ';
COMMENT ON COLUMN covsiteh."Site" IS 'Site that is covered.';
COMMENT ON COLUMN covsiteh."CoverIt" IS 'Coverage item this site is covered for. Ptr to COVERIT.CoverIt';
COMMENT ON COLUMN covsiteh."CovSiteH" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN covsiteh."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE cqaccess (
  "CustQry" numeric(10,0) NOT NULL,
  "SLevel" numeric(10,0) NOT NULL,
  "UserId" numeric(10,0) NOT NULL,
  "Access" numeric(5,0),
  CONSTRAINT cqaccess_primary PRIMARY KEY ("CustQry", "SLevel", "UserId")
) ;
COMMENT ON TABLE cqaccess IS 'Security restrictions for custom queries.';
COMMENT ON COLUMN cqaccess."UserId" IS 'Primary key component, ptr to USERS.User';
COMMENT ON COLUMN cqaccess."SLevel" IS 'Primary key component, ptr to SLEVEL.SLevel';
COMMENT ON COLUMN cqaccess."CustQry" IS 'Primary key component, ptr to CUST_QRY.CUST_QRY_AutoDec';
COMMENT ON COLUMN cqaccess."Access" IS 'Access rights (0=No Access, 1=Read Only, 2=Full Access)';


CREATE  TABLE cqmdataelement (
  "CQMId" character varying(10),
  "UID" character varying(100),
  "UIDDescription" character varying(4000)
) ;
CREATE INDEX IF NOT EXISTS cqmdataelement_pk ON cqmdataelement USING btree ("CQMId", "UID") TABLESPACE pg_default;
COMMENT ON TABLE cqmdataelement IS 'CQM (Clinical Quality Measure) data elements.';
COMMENT ON COLUMN cqmdataelement."UIDDescription" IS 'Unique ID value set description.';
COMMENT ON COLUMN cqmdataelement."UID" IS 'Unique ID value set.';
COMMENT ON COLUMN cqmdataelement."CQMId" IS 'CQM (Clinical Quality Measure) that this applies to.';


CREATE  TABLE cqmvalset (
  "CQM" character(3) NOT NULL,
  "NQF" character varying(32),
  "Title" character varying(255),
  "NeutralId" character(36),
  "SpecificId" character(36),
  "Version" numeric(5,0),
  CONSTRAINT cqmvalset_pk PRIMARY KEY ("CQM")
) ;
COMMENT ON TABLE cqmvalset IS 'Clinical Quality Measure value sets for Meaningful Use Dashboard.';
COMMENT ON COLUMN cqmvalset."Version" IS 'CQM Version.';
COMMENT ON COLUMN cqmvalset."Title" IS 'Title of the CQM.';
COMMENT ON COLUMN cqmvalset."SpecificId" IS 'Specific ID of the CQM.';
COMMENT ON COLUMN cqmvalset."NeutralId" IS 'Neutral ID of the CQM.';
COMMENT ON COLUMN cqmvalset."NQF" IS '"NQF" ID.';
COMMENT ON COLUMN cqmvalset."CQM" IS 'Primary key, CQM ID.';


CREATE  TABLE craccess (
  "CustRpt" numeric(10,0) NOT NULL,
  "SLevel" numeric(10,0) NOT NULL,
  "Access" numeric(5,0),
  "DisablePrint" numeric(5,0),
  "DisableExport" numeric(5,0),
  "IsDefault" numeric(5,0),
  "DisableAttach" numeric(5,0),
  "UserId" numeric(10,0) NOT NULL,
  CONSTRAINT craccess_primary PRIMARY KEY ("CustRpt", "SLevel", "UserId")
) ;
COMMENT ON TABLE craccess IS 'Custom Info Manager Report Access';
COMMENT ON COLUMN craccess."UserId" IS 'Primary key component, the user that access is being defined for. Ptr to USERS.User';
COMMENT ON COLUMN craccess."SLevel" IS 'Primary key component, the security level that access is being defined for. Ptr to SLEVEL.SLevel';
COMMENT ON COLUMN craccess."IsDefault" IS 'Is this the default report for this security level and report type? (0=No, 1=Yes)';
COMMENT ON COLUMN craccess."DisablePrint" IS 'Disable printing of this report for this security level? (0=No, 1=Yes)';
COMMENT ON COLUMN craccess."DisableExport" IS 'Disable exporting of this report for this security level? (0=No, 1=Yes)';
COMMENT ON COLUMN craccess."DisableAttach" IS 'Disable attachments? (0=No, 1=Yes)';
COMMENT ON COLUMN craccess."CustRpt" IS 'Primary key component, the custom report that access is being defined for. Ptr to CUSTRPT.CustRpt';
COMMENT ON COLUMN craccess."Access" IS 'Level has access to the report? (0=No, 1=Yes)';


CREATE  TABLE crproc (
  "ConsReq" numeric(10,0) NOT NULL,
  "Procedure" character(7) NOT NULL,
  CONSTRAINT crproc_primary PRIMARY KEY ("ConsReq", "Procedure")
) ;
COMMENT ON TABLE crproc IS 'Procedures that apply to Consent Requirement Rules';
COMMENT ON COLUMN crproc."Procedure" IS 'Procedure code that the rule applies to, ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN crproc."ConsReq" IS 'Consent Requirement Rule, ptr to CONSREQ.ConsReq';


CREATE  TABLE crptype (
  "ConsReq" numeric(10,0) NOT NULL,
  "ProvType" character(1) NOT NULL,
  CONSTRAINT crptype_primary PRIMARY KEY ("ConsReq", "ProvType")
) ;
COMMENT ON TABLE crptype IS 'Provider types that apply to Consent Requirement Rules';
COMMENT ON COLUMN crptype."ProvType" IS 'Provider type that the rule applies to, ptr to PRODTYPE.Code';
COMMENT ON COLUMN crptype."ConsReq" IS 'Consent Requirement Rule, ptr to CONSREQ.ConsReq';


CREATE  TABLE ctblacc (
  "CTblFile" numeric(10,0) NOT NULL,
  "SLevel" numeric(10,0) NOT NULL,
  "Access" numeric(5,0),
  CONSTRAINT ctblacc_primary PRIMARY KEY ("CTblFile", "SLevel")
) ;
COMMENT ON TABLE ctblacc IS 'Access to custom Info Manager tables and views.';
COMMENT ON COLUMN ctblacc."SLevel" IS 'Primary key, ptr. to SLEVEL.SLevel';
COMMENT ON COLUMN ctblacc."CTblFile" IS 'Primary key, ptr. to CTBLFILE.CTblFile';
COMMENT ON COLUMN ctblacc."Access" IS 'Type of Access (0=Read only, 1=Full Access)';


CREATE  TABLE ctblfile (
  "CTblFile" numeric(10,0) NOT NULL,
  "SchemaName" character varying(30),
  "FileType" numeric(5,0),
  "DisplayName" character varying(30),
  "DisplayPrefix" character varying(10),
  "Inactive" numeric(5,0),
  CONSTRAINT ctblfile_primary PRIMARY KEY ("CTblFile")
) ;
COMMENT ON TABLE ctblfile IS 'Stores custom tables and views added to Info Manager';
COMMENT ON COLUMN ctblfile."SchemaName" IS 'Name of the Table/View, e.g. PATPLUS';
COMMENT ON COLUMN ctblfile."Inactive" IS 'Is table inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN ctblfile."FileType" IS 'Type of file (0=Table, 1=View)';
COMMENT ON COLUMN ctblfile."DisplayPrefix" IS 'Name used as prefix for fields, e.g. Pt. Plus';
COMMENT ON COLUMN ctblfile."DisplayName" IS 'Name used in Info Manager, e.g. Patient Plus';
COMMENT ON COLUMN ctblfile."CTblFile" IS 'Primary key';


CREATE  TABLE ctblfld (
  "CTblFld" numeric(10,0) NOT NULL,
  "CTblFile" numeric(10,0),
  "FieldId" numeric(5,0),
  "FieldName" character varying(30),
  "FieldType" numeric(5,0),
  "DisplayName" character varying(50),
  "Inactive" numeric(5,0),
  "MapToField" numeric(5,0),
  CONSTRAINT ctblfld_primary PRIMARY KEY ("CTblFld")
) ;
CREATE INDEX IF NOT EXISTS ctblfld_ctblfilekey ON ctblfld USING btree ("CTblFile", "FieldId") TABLESPACE pg_default;
COMMENT ON TABLE ctblfld IS 'Stores field information for Info Manager custom tables and views';
COMMENT ON COLUMN ctblfld."MapToField" IS 'Does field map to Patient or User Id? (0=No, 1=Patient Id, 2= User Id, 3=User Id [Current User Only])';
COMMENT ON COLUMN ctblfld."Inactive" IS 'Is field inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN ctblfld."FieldType" IS 'Field Type (0=Other, 1=Text, 2=Number, 3=Date)';
COMMENT ON COLUMN ctblfld."FieldName" IS 'Field Name';
COMMENT ON COLUMN ctblfld."FieldId" IS 'Primary key, Unique field ID, starting as 1 and autoincrement by 1';
COMMENT ON COLUMN ctblfld."DisplayName" IS 'Name use in Info Manager, e.g. Plus Name';
COMMENT ON COLUMN ctblfld."CTblFld" IS 'Primary key';
COMMENT ON COLUMN ctblfld."CTblFile" IS 'Ptr. to CTBLFILE.CTblFile';


CREATE  TABLE cust_qry (
  "CUST_QRY_AutoDec" numeric(10,0) NOT NULL,
  "CUST_QRY_Type" numeric(10,0),
  "CUST_QRY_Description" character(50),
  cust_qry_data bytea,
  "CUST_QRY_Comment" character varying(200),
  "CreateUser" numeric(10,0),
  "CreateDate" timestamp without time zone,
  CONSTRAINT cust_qry_primaryindex PRIMARY KEY ("CUST_QRY_AutoDec")
) ;
CREATE INDEX IF NOT EXISTS "CUST_QRY_Type" ON cust_qry USING btree ("CUST_QRY_Type") TABLESPACE pg_default;
COMMENT ON TABLE cust_qry IS 'CUST_QRY';
COMMENT ON COLUMN cust_qry.cust_qry_data IS 'Binary object containing report information (the placement of fields and text, including fonts, colors, etc...non-readable by SQL). Note: In Oracle 9i this field is Type: BLOB';
COMMENT ON COLUMN cust_qry."CreateUser" IS 'User Id of person who created the predefined report';
COMMENT ON COLUMN cust_qry."CreateDate" IS 'Date report created';
COMMENT ON COLUMN cust_qry."CUST_QRY_Type" IS 'Info Manager Report Category';
COMMENT ON COLUMN cust_qry."CUST_QRY_Description" IS 'Report name';
COMMENT ON COLUMN cust_qry."CUST_QRY_Comment" IS 'Report comment';
COMMENT ON COLUMN cust_qry."CUST_QRY_AutoDec" IS 'Primary key, record Id';


CREATE  TABLE custcode (
  "Type" numeric(5,0) NOT NULL,
  "Code" character(6) NOT NULL,
  "Description" character(30),
  "Default" numeric(5,0),
  "Inactive" numeric(5,0),
  CONSTRAINT custcode_primary PRIMARY KEY ("Type", "Code")
) ;
COMMENT ON TABLE custcode IS 'Custom codes for custom fields (for comboboxes)';
COMMENT ON COLUMN custcode."Type" IS 'Primary key, ptr to the CUSTTYPE.Type';
COMMENT ON COLUMN custcode."Inactive" IS 'Code inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN custcode."Description" IS 'Description of the custom code';
COMMENT ON COLUMN custcode."Default" IS 'Default custom code to display for this custom type';
COMMENT ON COLUMN custcode."Code" IS 'Primary key, ID code to identify this custom code';


CREATE  TABLE custevnt (
  "EventType" numeric(5,0),
  "Description" character varying(50),
  "PrimaryTable" character varying(20),
  "PrimaryKey" character varying(50),
  "Key1" numeric(10,0),
  "Key2" numeric(5,0),
  "CustEvnt" numeric(10,0) NOT NULL,
  CONSTRAINT custevnt_pk PRIMARY KEY ("CustEvnt")
) ;
CREATE INDEX IF NOT EXISTS custevnt_eventkey ON custevnt USING btree ("EventType", "Key1", "Key2") TABLESPACE pg_default;
COMMENT ON TABLE custevnt IS 'custom events for auto-message triggers';
COMMENT ON COLUMN custevnt."PrimaryTable" IS 'Main table that this event is related to.';
COMMENT ON COLUMN custevnt."PrimaryKey" IS 'Description of primary key of main table. How the custom trigger should look up the record';
COMMENT ON COLUMN custevnt."Key2" IS 'Primary key value for this instance of the event';
COMMENT ON COLUMN custevnt."Key1" IS 'Primary key value for this instance of the event';
COMMENT ON COLUMN custevnt."EventType" IS 'Type of event that is being triggered. 1 = Patient Assignment, 2 = Lab in, 3 = Lab out, 4= Emergency Mode';
COMMENT ON COLUMN custevnt."Description" IS 'Description of the event';
COMMENT ON COLUMN custevnt."CustEvnt" IS 'sequenced primary key';


CREATE  TABLE custmsg (
  "MessageId" numeric(10,0) NOT NULL,
  "ProfileId" numeric(10,0),
  "Message" character varying(4000),
  "LANGCD" character(6),
  "MessageType" numeric(5,0),
  CONSTRAINT custmsg_pk PRIMARY KEY ("MessageId")
) ;
COMMENT ON TABLE custmsg IS 'FirstAccess custom messages.';
COMMENT ON COLUMN custmsg."ProfileId" IS 'ID of the FirstAccess profile that this custom message is for.';
COMMENT ON COLUMN custmsg."MessageType" IS 'Type of the custom message (0 = Successful Sign-in, 1 = Chart Lock).';
COMMENT ON COLUMN custmsg."MessageId" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN custmsg."Message" IS 'Custom message to display.';
COMMENT ON COLUMN custmsg."LANGCD" IS 'Language code that this custom message is for. Ptr to LANGCD.LangCd.';


CREATE  TABLE custrcat (
  "CustRCat" numeric(10,0) NOT NULL,
  "Description" character varying(30),
  "Order" numeric(5,0),
  "Inactive" numeric(5,0),
  CONSTRAINT custrcat_primary PRIMARY KEY ("CustRCat")
) ;
COMMENT ON TABLE custrcat IS 'Custom report categories for organizing Info Manager custom reports ';
COMMENT ON COLUMN custrcat."Order" IS 'Number indicating position of the category in the list ';
COMMENT ON COLUMN custrcat."Inactive" IS '0 = No, 1 = Yes: Is the category inactive? ';
COMMENT ON COLUMN custrcat."Description" IS 'Category name ';
COMMENT ON COLUMN custrcat."CustRCat" IS 'Sequenced primary key  ';


CREATE  TABLE custrpt (
  "CustRpt" numeric(10,0) NOT NULL,
  "Description" character varying(30),
  "FilePath" character varying(255),
  "Inactive" numeric(5,0),
  "IsCrystal" numeric(5,0),
  "PassUser" numeric(5,0),
  content bytea,
  "Type" numeric(5,0),
  "Order" numeric(5,0),
  "Note" character varying(4000),
  "CustRCat" numeric(10,0),
  "PtAttachType" numeric(5,0),
  "Consent" character(6),
  "AtTab" numeric(10,0),
  "SReport" numeric(10,0),
  CONSTRAINT custrpt_primary PRIMARY KEY ("CustRpt")
) ;
COMMENT ON TABLE custrpt IS 'Custom Reports';
COMMENT ON COLUMN custrpt.content IS 'Raw data that stores a copy of the report for future use. Note: In Oracle 9i this field is Type: BLOB';
COMMENT ON COLUMN custrpt."Type" IS 'Type of custom report? (0=Info manager, 1=Patient Care, 2=Personal Planner, 3=Standard Report)';
COMMENT ON COLUMN custrpt."SReport" IS 'Pointer to SReport.SReport';
COMMENT ON COLUMN custrpt."PtAttachType" IS 'If Type=1, attachment type for the report (0 = No, 1 = Yes (Attach), 2 = Yes (Consent))';
COMMENT ON COLUMN custrpt."PassUser" IS 'If IsCrystal = 1, Pass current user to report? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN custrpt."Order" IS 'Number to indicate the order in which this should appear in the custom report list';
COMMENT ON COLUMN custrpt."Note" IS 'Note that can be added to a custom report';
COMMENT ON COLUMN custrpt."IsCrystal" IS 'Report is a Crystal report? (0 = No, 1 = Yes)';
COMMENT ON COLUMN custrpt."Inactive" IS 'Report is inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN custrpt."FilePath" IS 'The network path to the original copy of the report. ';
COMMENT ON COLUMN custrpt."Description" IS 'Description of the report';
COMMENT ON COLUMN custrpt."CustRpt" IS 'Id code of the custom report being defined, internal ID from sequence';
COMMENT ON COLUMN custrpt."CustRCat" IS 'Category that the report belongs too, ptr to CUSTRCAT.CustRCat';
COMMENT ON COLUMN custrpt."Consent" IS 'If Type=1 and PtAttachType=2, ptr to CONSENT.Consent';
COMMENT ON COLUMN custrpt."AtTab" IS 'If Type=1 and PtAttachType =1 or 2, ptr to ATTAB.AtTab';


CREATE  TABLE custtext (
  "CustText" numeric(10,0) NOT NULL,
  "Type" numeric(5,0),
  "Text" character varying(500),
  CONSTRAINT custtext_primary PRIMARY KEY ("CustText")
) ;
COMMENT ON TABLE custtext IS 'Custom text for use in the start check window.';
COMMENT ON COLUMN custtext."Type" IS 'The type of custom text (0=Start check, 1=Password error)';
COMMENT ON COLUMN custtext."Text" IS 'Customized text.';
COMMENT ON COLUMN custtext."CustText" IS 'Id code, unique code to identify this custom text record';


CREATE  TABLE custtype (
  "Type" numeric(5,0) NOT NULL,
  "Description" character(20),
  "Validatefield" numeric(5,0),
  "RequiredField" numeric(5,0),
  "IsLocation" numeric(5,0),
  CONSTRAINT custtype_primary PRIMARY KEY ("Type")
) ;
COMMENT ON TABLE custtype IS 'Custom field types (labels for fields)';
COMMENT ON COLUMN custtype."Validatefield" IS 'Validate against the custom codes table? (0 = No, 1 = Yes)';
COMMENT ON COLUMN custtype."Type" IS 'Custom Field Number (Patient [0-9],Treatment (Note) [10 - 11], User [12-21], Treatment (Clinical) [22-23], Prescription [24-25], Patient text [26-30], InfoMgr Patient [31-40], Patient Pmt [41-42], Adjustment [43-44], Ins Pmt [45-46])';
COMMENT ON COLUMN custtype."RequiredField" IS 'Field is required? (0 = No, 1 = Yes)';
COMMENT ON COLUMN custtype."IsLocation" IS 'Indicates one and only Tx Location custom field';
COMMENT ON COLUMN custtype."Description" IS 'Description of this custom type';


CREATE  TABLE cvgproc (
  "Procedure" character(7) NOT NULL,
  "Coverage" numeric(10,0) NOT NULL,
  "PolIns" numeric(10,0) NOT NULL,
  CONSTRAINT cvgproc_primary PRIMARY KEY ("Procedure", "Coverage", "PolIns")
) ;
COMMENT ON TABLE cvgproc IS 'Deductible exemption in the policy/coverage level';
COMMENT ON COLUMN cvgproc."Procedure" IS 'Procedure Code, ptr. to PROCEDUR.Procedure ';
COMMENT ON COLUMN cvgproc."PolIns" IS 'Policy Id, ptr. to POLRANGE.PolIns';
COMMENT ON COLUMN cvgproc."Coverage" IS 'Id code of the coverage template, ptr to COVERAGE.Coverage';


CREATE  TABLE dentx (
  "Id" numeric(10,0) NOT NULL,
  "StartDtxCode" character(7),
  "EndDtxCode" character(7),
  "Freq" numeric(5,0),
  "ConsultantType" numeric(5,0),
  CONSTRAINT dentx_primary PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE dentx IS 'Consultant Approval Requirements (from Maintenance)';
COMMENT ON COLUMN dentx."StartDtxCode" IS 'Starting procedure code in range';
COMMENT ON COLUMN dentx."Id" IS 'Record Id, based on sequence';
COMMENT ON COLUMN dentx."Freq" IS 'Number of procedures required to approve';
COMMENT ON COLUMN dentx."EndDtxCode" IS 'Ending procedure code in range';
COMMENT ON COLUMN dentx."ConsultantType" IS 'Consultant Type required to approve, ptr to CONSULTS.Id';


CREATE  TABLE deplimit (
  "PolicyId" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0) NOT NULL,
  "Id" numeric(10,0) NOT NULL,
  "Category" character(6) NOT NULL,
  "Limit" numeric,
  "Description" character(30),
  "LimitBalance" numeric,
  "Deduct" numeric,
  "DeductBalance" numeric,
  "ResetDate" timestamp without time zone,
  "CoverageId" numeric(10,0) NOT NULL,
  "LimitOnPatient" numeric(5,0),
  CONSTRAINT deplimit_primary PRIMARY KEY ("PolicyId", "Patient", "Id", "Category", "CoverageId")
) ;
COMMENT ON TABLE deplimit IS 'Insurance Policy Limits';
COMMENT ON COLUMN deplimit."ResetDate" IS 'Date on which to reset the deductible limits';
COMMENT ON COLUMN deplimit."PolicyId" IS 'Primary key, ID code of the policy this limit applies to';
COMMENT ON COLUMN deplimit."Patient" IS 'Primary key, patient ID, ptr to PATIENT.Patient';
COMMENT ON COLUMN deplimit."LimitOnPatient" IS 'Is this a patient limit? (0=No (limit on insurance), 1=Yes (limit on patient maximum), 2=Yes (limit on patient maximum + deductable))';
COMMENT ON COLUMN deplimit."LimitBalance" IS 'Dollar ($) amount of the limit balance';
COMMENT ON COLUMN deplimit."Limit" IS 'Dollar ($) amount of the limit';
COMMENT ON COLUMN deplimit."Id" IS 'Primary key, policy limits ID';
COMMENT ON COLUMN deplimit."Description" IS 'Description of the treatment';
COMMENT ON COLUMN deplimit."DeductBalance" IS 'Balance remaining on the deductible (the unpaid portion of the full deductible)';
COMMENT ON COLUMN deplimit."Deduct" IS 'Amount of the deductible';
COMMENT ON COLUMN deplimit."CoverageId" IS 'ID code of the coverage template';
COMMENT ON COLUMN deplimit."Category" IS 'Primary key, policy category, ptr to COVERIT.Category';


CREATE  TABLE dept (
  "Department" character(6) NOT NULL,
  "Description" character varying(50),
  "Inactive" numeric(5,0),
  CONSTRAINT dept_primary PRIMARY KEY ("Department")
) ;
COMMENT ON TABLE dept IS 'Record of departments';
COMMENT ON COLUMN dept."Inactive" IS 'Code is inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN dept."Description" IS 'Description of the department';
COMMENT ON COLUMN dept."Department" IS 'Id code to identify the department ';


CREATE  TABLE deptdef (
  "Department" character(6) NOT NULL,
  "Type" numeric(5,0) NOT NULL,
  "Condition" numeric(5,0) NOT NULL,
  "Criteria1" character varying(15) NOT NULL,
  "Criteria2" character varying(15),
  CONSTRAINT deptdef_primary PRIMARY KEY ("Department", "Type", "Condition", "Criteria1")
) ;
COMMENT ON TABLE deptdef IS 'Record of departmental definitions';
COMMENT ON COLUMN deptdef."Type" IS 'Department criteria type ( 0=TxDiscipline, 1=TxProcedure, 2=TxPractice, 3=TxFee Guide / Billing Doctor, 4=TxFacility, 5=TxEntry User, 6=TxApproval Instructor, 7=TxCustomField1, 8=TxCustomField2, 9=Provider Code, 10= Provider Type, 11=Provider Group, 12=Provider Year, 13=PtCustField1, 14=PtCustField2, 15=PtCustField3, 16=PtCustField4, 17=PtCustField5, 18=PtCustField6, 19=PtCustField7, 20=PtCustField8, 21=PtCustField9, 22=PtCustField10)';
COMMENT ON COLUMN deptdef."Department" IS 'Id code of the department, ptr to DEPT.Department';
COMMENT ON COLUMN deptdef."Criteria2" IS 'Criteria';
COMMENT ON COLUMN deptdef."Criteria1" IS 'Criteria ';
COMMENT ON COLUMN deptdef."Condition" IS 'Filter criteria (0=Equal, 1=Between, 2=Not equal)';


CREATE  TABLE depttx (
  "Batch" numeric(10,0) NOT NULL,
  "Department" character(6) NOT NULL,
  "HistoryLast" numeric(10,0) NOT NULL,
  "InDeptLast" numeric(5,0),
  "HistoryPrior" numeric(10,0),
  "InDeptPrior" numeric(5,0),
  CONSTRAINT depttx_primary PRIMARY KEY ("Batch", "Department", "HistoryLast")
) ;
COMMENT ON TABLE depttx IS 'Temporary table used by the AR Reconcialiation by Department report.';
COMMENT ON COLUMN depttx."InDeptPrior" IS 'HistoryPrior belonged to the Department? (0 = No, 1 = Yes)';
COMMENT ON COLUMN depttx."InDeptLast" IS 'HistoryLast belonged to the Department? (0 = No, 1 = Yes)';
COMMENT ON COLUMN depttx."HistoryPrior" IS 'The last history ID that is prior to the date range the report is being run for. Ptr to HISTORY.History';
COMMENT ON COLUMN depttx."HistoryLast" IS 'The Last history ID that is in the date range the report is being run for. Ptr to HISTORY.History';
COMMENT ON COLUMN depttx."Department" IS 'The department for which this report is being run. Ptr to DEPT.Department';
COMMENT ON COLUMN depttx."Batch" IS 'Unique batch number of the report. ';


CREATE  TABLE detail2 (
  "Auto" numeric(10,0) NOT NULL,
  "PId" numeric(10,0),
  "Site" numeric(10,0),
  "ModifiedDateTime" timestamp without time zone,
  color bytea,
  "User" numeric(10,0),
  CONSTRAINT detail2_primary PRIMARY KEY ("Auto")
) ;
CREATE INDEX IF NOT EXISTS "DETAIL2_PId" ON detail2 USING btree ("PId", "Site", "ModifiedDateTime") TABLESPACE pg_default;
COMMENT ON TABLE detail2 IS 'Drawings on Chart';
COMMENT ON COLUMN detail2.color IS 'Binary BLOB containing paint details. ';
COMMENT ON COLUMN detail2."User" IS 'User ID of the user that made the drawing, ptr to USERS.User';
COMMENT ON COLUMN detail2."Site" IS 'Tooth that that the drawing is on.';
COMMENT ON COLUMN detail2."PId" IS 'Patient charting information, ptr to PATIENT2.Auto';
COMMENT ON COLUMN detail2."ModifiedDateTime" IS 'Date / time that detail was drawn.';
COMMENT ON COLUMN detail2."Auto" IS 'Primary key, internal ID from sequence. ';


CREATE  TABLE diagcat (
  "DiagCat" character(6) NOT NULL,
  "Parent" character(6),
  "Order" numeric(5,0),
  "Description" character varying(30),
  "Inactive" numeric(5,0),
  CONSTRAINT diagcat_primary PRIMARY KEY ("DiagCat")
) ;
CREATE INDEX IF NOT EXISTS diagcat_parent ON diagcat USING btree ("Parent") TABLESPACE pg_default;
COMMENT ON TABLE diagcat IS 'Diagnosis Categories';
COMMENT ON COLUMN diagcat."Parent" IS 'If this is a subcategory, ID code of the parent category. Ptr to DIAGCAT.DiagCat';
COMMENT ON COLUMN diagcat."Order" IS 'Number to represent the order in which this code should appear in the list';
COMMENT ON COLUMN diagcat."Inactive" IS 'Code is inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN diagcat."DiagCat" IS 'Primary key, ID code to represent this diagnostic category.';
COMMENT ON COLUMN diagcat."Description" IS 'Description of the diagnostic category.';


CREATE  TABLE diagcode (
  "DiagCode" character(8) NOT NULL,
  "DiagCat" character(6),
  "Description" character varying(60),
  "Inactive" numeric(5,0),
  "DiagNo" character(10),
  "ICDType" numeric(5,0),
  "ShortDesc" character varying(20),
  "Rank" numeric(5,0),
  "Note" character varying(4000),
  CONSTRAINT diagcode_primary PRIMARY KEY ("DiagCode")
) ;
CREATE INDEX IF NOT EXISTS diagcode_diagcat ON diagcode USING btree ("DiagCat") TABLESPACE pg_default;
COMMENT ON TABLE diagcode IS 'Clinical Diagnosis Codes ';
COMMENT ON COLUMN diagcode."ShortDesc" IS 'Short description of the diagnosis code. ';
COMMENT ON COLUMN diagcode."Rank" IS 'Internal number from 1-9999, for sorting intellisense results in ascending order.';
COMMENT ON COLUMN diagcode."Note" IS 'Diagnosis Code Note';
COMMENT ON COLUMN diagcode."Inactive" IS 'Code is inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN diagcode."ICDType" IS 'ICD type of optional medical diagnosis code (0=ICD-9, 1=ICD-10)';
COMMENT ON COLUMN diagcode."DiagNo" IS 'Optional linked medical diagnosis, ptr to DIAGNO.Code';
COMMENT ON COLUMN diagcode."DiagCode" IS 'Primary key, ID to represent this clinical diagnosis code. ';
COMMENT ON COLUMN diagcode."DiagCat" IS 'ID code of the diagnostic category under which this code falls, ptr to DIAGCAT.DiagCat';
COMMENT ON COLUMN diagcode."Description" IS 'Description of the diagnosis code ';


CREATE  TABLE diagno (
  "Code" character(10) NOT NULL,
  "Description" character varying(80),
  "ICDType" numeric(5,0) NOT NULL,
  "MapCode" character(10),
  "Inactive" numeric(5,0),
  CONSTRAINT diagno_primary PRIMARY KEY ("Code", "ICDType")
) ;
COMMENT ON TABLE diagno IS 'Medical Diagnosis Codes';
COMMENT ON COLUMN diagno."MapCode" IS 'If ICDType=1, ICD-9 code that this code will map down to (optional). Ptr to DIAGNO.Code';
COMMENT ON COLUMN diagno."Inactive" IS 'Code is inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN diagno."ICDType" IS 'Primary key component, ICD type of code (0=ICD-9, 1=ICD-10)';
COMMENT ON COLUMN diagno."Description" IS 'Description of the diagnosis code ';
COMMENT ON COLUMN diagno."Code" IS 'Primary key component, ID to represent this medical diagnosis code. ';


CREATE  TABLE diagnose (
  "Auto" numeric(10,0) NOT NULL,
  "Complaint" numeric(10,0),
  "LineNum" numeric(5,0),
  "Diag_Desc" character(255),
  "DiagCode" character(8),
  CONSTRAINT diagnose_primary PRIMARY KEY ("Auto")
) ;
CREATE INDEX IF NOT EXISTS diagnose_complaint ON diagnose USING btree ("Complaint") TABLESPACE pg_default;
COMMENT ON TABLE diagnose IS 'Treatment Plan Diagnoses';
COMMENT ON COLUMN diagnose."LineNum" IS 'Diagnosis line number (line that text appears on).';
COMMENT ON COLUMN diagnose."Diag_Desc" IS 'Diagnosis line text description.';
COMMENT ON COLUMN diagnose."DiagCode" IS 'Diagnosis code, ptr to DIAGCODE.DiagCode';
COMMENT ON COLUMN diagnose."Complaint" IS 'Complaint (Tx Plan) record ID, ptr to COMPLAIN.Auto';
COMMENT ON COLUMN diagnose."Auto" IS 'Primary key, internal ID from sequence. ';


CREATE  TABLE diagproc (
  "DiagCode" character(8) NOT NULL,
  "Procedure" character(7) NOT NULL,
  CONSTRAINT diagproc_primary PRIMARY KEY ("DiagCode", "Procedure")
) ;
COMMENT ON TABLE diagproc IS 'Diagnosis Procedure Association';
COMMENT ON COLUMN diagproc."Procedure" IS 'Primary key component, procedure code for this association. Ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN diagproc."DiagCode" IS 'Primary key component, diagnosis code for this association. Ptr to DIAGCODE.DiagCode';


CREATE  TABLE diagsyn (
  "DiagCode" character(8) NOT NULL,
  "Synonym" character varying(100) NOT NULL,
  CONSTRAINT diagsyn_primary PRIMARY KEY ("DiagCode", "Synonym")
) ;
COMMENT ON TABLE diagsyn IS 'Diagnosis Code Synonyms';
COMMENT ON COLUMN diagsyn."Synonym" IS 'Synonyn for this diagnosis code.';
COMMENT ON COLUMN diagsyn."DiagCode" IS 'Primary key component, diagnosis code with the synonym. Ptr to DIAGCODE.DiagCode';


CREATE  TABLE dicharge (
  "DICharge" character(6) NOT NULL,
  "Type" numeric(5,0),
  "Description" character(30),
  "AffectReceipts" numeric(5,0),
  CONSTRAINT dicharge_primary PRIMARY KEY ("DICharge")
) ;
COMMENT ON TABLE dicharge IS 'Dispensary charges';
COMMENT ON COLUMN dicharge."Type" IS 'Type of charge (0=debit, 1=credit)';
COMMENT ON COLUMN dicharge."Description" IS 'Description of the charge type';
COMMENT ON COLUMN dicharge."DICharge" IS 'Primary key, code to identify the charge type';
COMMENT ON COLUMN dicharge."AffectReceipts" IS 'Charge affects receipts? (0 = No, 1 = Yes)';


CREATE  TABLE discgrit (
  "DiscGrp" character(6) NOT NULL,
  "Item" numeric(10,0) NOT NULL,
  "Description" character varying(30),
  "FromProcedure" character(7),
  "ToProcedure" character(7),
  "Percent" numeric(5,0),
  CONSTRAINT discgrit_primary PRIMARY KEY ("DiscGrp", "Item")
) ;
COMMENT ON TABLE discgrit IS 'Discount Group Items';
COMMENT ON COLUMN discgrit."ToProcedure" IS 'Ending code part of the procedure code range for this item. Ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN discgrit."Percent" IS 'Discount percentage for this item.';
COMMENT ON COLUMN discgrit."Item" IS 'Primary key component, the item within the discount group.';
COMMENT ON COLUMN discgrit."FromProcedure" IS 'Starting code of the procedure code range for this item. Ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN discgrit."DiscGrp" IS 'Primary key component, the discount group. Ptr to DISCGRP.DiscGrp.';
COMMENT ON COLUMN discgrit."Description" IS 'Discount group item description.';


CREATE  TABLE discgrp (
  "DiscGrp" character(6) NOT NULL,
  "Description" character varying(50),
  "RoundOff" numeric(5,0),
  "Inactive" numeric(5,0),
  "Suspend" numeric(5,0),
  CONSTRAINT discgrp_primary PRIMARY KEY ("DiscGrp")
) ;
COMMENT ON TABLE discgrp IS 'Discount Groups';
COMMENT ON COLUMN discgrp."Suspend" IS 'Is charging with this discount suspended? (0=No, 1=Yes)';
COMMENT ON COLUMN discgrp."RoundOff" IS 'Round to nearest dollar? (0=No, 1=Yes)';
COMMENT ON COLUMN discgrp."Inactive" IS 'Is this discount group inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN discgrp."DiscGrp" IS 'Primary key, code to identify the discount group.';
COMMENT ON COLUMN discgrp."Description" IS 'Discount group description.';


CREATE  TABLE discipl (
  "Discipline" character(6) NOT NULL,
  "Description" character(30),
  "Import" character(10),
  "Class" character(15),
  "Color" numeric(10,0),
  "SwipeCode" character(6),
  "GradingType" numeric(5,0),
  CONSTRAINT discipl_primary PRIMARY KEY ("Discipline")
) ;
CREATE INDEX IF NOT EXISTS discipl_classgrading ON discipl USING btree ("Class", "GradingType") TABLESPACE pg_default;
COMMENT ON TABLE discipl IS 'Discipline Codes';
COMMENT ON COLUMN discipl."SwipeCode" IS 'Code used (to represent this discipline) on magnetic swipe cards';
COMMENT ON COLUMN discipl."Import" IS 'Import code to import data from a delimited file';
COMMENT ON COLUMN discipl."GradingType" IS 'Number to represent type of grading (0 = n/a, 1 = Sessional, 2 = Periodic)';
COMMENT ON COLUMN discipl."Discipline" IS 'Primary key, ID code to identify the discipline';
COMMENT ON COLUMN discipl."Description" IS 'Description of the discipline code';
COMMENT ON COLUMN discipl."Color" IS 'Color to represent the discipline within the scheduler (for ideal day)';
COMMENT ON COLUMN discipl."Class" IS 'Link to CLASS table, ptr to CLASS.Class';


CREATE  TABLE dispcode (
  "DispCode" character(6) NOT NULL,
  "Description" character(30),
  "Type" numeric(5,0),
  "HasBarCode" numeric(5,0),
  "BarCode" character varying(30),
  "Inactive" numeric(5,0),
  CONSTRAINT dispcode_primary PRIMARY KEY ("DispCode")
) ;
COMMENT ON TABLE dispcode IS 'Dispensary codes';
COMMENT ON COLUMN dispcode."Type" IS 'Type of dispensary item. (0=Dispensary, 1=Sterilization, 2=Cart, 3=Other)';
COMMENT ON COLUMN dispcode."Inactive" IS 'Inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN dispcode."HasBarCode" IS 'If DISPCODE.Type is 1, 2 or 3, then Has Bar Code? (0=No, 1=Yes)';
COMMENT ON COLUMN dispcode."DispCode" IS 'Primary key, code to identify the dispensary';
COMMENT ON COLUMN dispcode."Description" IS 'Description of the dispensary';
COMMENT ON COLUMN dispcode."BarCode" IS 'If DISPCODE.HasBarCode=1, the bar code';


CREATE  TABLE dispdisc (
  "Module" numeric(5,0) NOT NULL,
  "Discipline" character(15) NOT NULL,
  CONSTRAINT dispdisc_primary PRIMARY KEY ("Module", "Discipline")
) ;
COMMENT ON TABLE dispdisc IS 'Chart Add Disciplines';
COMMENT ON COLUMN dispdisc."Module" IS 'Module? (0=Dental, 1=Ortho, 2=Perio)';
COMMENT ON COLUMN dispdisc."Discipline" IS 'Discipline, ptr to CLASS.Class';


CREATE  TABLE disphis (
  "DispHis" numeric(10,0) NOT NULL,
  "Provider" character(10),
  "DispCode" character(6),
  "Type" numeric(5,0),
  "Kit" character(30),
  "Sundry" character(6),
  "IsIn" numeric(5,0),
  "DateOut" timestamp without time zone,
  "TimeOut" numeric(10,0),
  "DateIn" timestamp without time zone,
  "TimeIn" numeric(10,0),
  "ChargeStatus" numeric(5,0),
  "Appointment" numeric(10,0),
  "AuditOut" numeric(10,0),
  "AuditIn" numeric(10,0),
  "DispCodeIn" character(6),
  "OuterBarCode" character(30),
  "Override" numeric(5,0),
  CONSTRAINT disphis_primary PRIMARY KEY ("DispHis")
) ;
CREATE INDEX IF NOT EXISTS disphis_appointment ON disphis USING btree ("Appointment") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS disphis_kit ON disphis USING btree ("Kit") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS disphis_outerbarcode ON disphis USING btree ("OuterBarCode") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS disphis_provider ON disphis USING btree ("Provider", "Sundry") TABLESPACE pg_default;
COMMENT ON TABLE disphis IS 'Dispensary history record';
COMMENT ON COLUMN disphis."Type" IS 'Type of dispensary item (0=Kit, 1=Sundry)';
COMMENT ON COLUMN disphis."TimeOut" IS 'Time dispensary item checked out (in minutes from midnight)';
COMMENT ON COLUMN disphis."TimeIn" IS 'Time dispensary item checked in (in minutes from midnight).';
COMMENT ON COLUMN disphis."Sundry" IS 'ID code of the sundry (if type = 1), ptr to SUNDRY.Sundry';
COMMENT ON COLUMN disphis."Provider" IS 'ID code of the provider to which this record belongs, ptr to PRODUCER.Producer';
COMMENT ON COLUMN disphis."Override" IS 'Was a warning overridden for this dispensary history? (0=No, 1=Yes)';
COMMENT ON COLUMN disphis."OuterBarCode" IS 'Outer bar code assigned to the kit, only used for schools that capture an outer bar code. ';
COMMENT ON COLUMN disphis."Kit" IS 'ID code of the kit (if type = 0), ptr to KIT.Kit';
COMMENT ON COLUMN disphis."IsIn" IS 'Item is checked in? (0 = No, 1 = Yes)';
COMMENT ON COLUMN disphis."DispHis" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN disphis."DispCodeIn" IS 'ID code of the dispensary related to this record when checked item checked in (IsIn=1), ptr to DISPCODE.DispCode';
COMMENT ON COLUMN disphis."DispCode" IS 'ID code of the dispensary related to this record, ptr to DISPCODE.DispCode';
COMMENT ON COLUMN disphis."DateOut" IS 'Date dispensary item checked out';
COMMENT ON COLUMN disphis."DateIn" IS 'Date dispensary item checked in ';
COMMENT ON COLUMN disphis."ChargeStatus" IS 'Charge status (0 = Not Applicable, 1=Charged, 2=Not Charged)';
COMMENT ON COLUMN disphis."AuditOut" IS 'Ptr to AUDITHIS.Audit, audit information with User who scanned item out';
COMMENT ON COLUMN disphis."AuditIn" IS 'Ptr to AUDITHIS.Audit, audit information with User who scanned item in';
COMMENT ON COLUMN disphis."Appointment" IS 'ID code of the appointment, ptr to APPOINT.Appointment';


CREATE  TABLE displevl (
  "DispCode" character(6) NOT NULL,
  "KitType" character(6) NOT NULL,
  "MinLevel" numeric(5,0),
  CONSTRAINT displevl_primary PRIMARY KEY ("DispCode", "KitType")
) ;
COMMENT ON TABLE displevl IS 'Minimum inventory levels per dispensary ';
COMMENT ON COLUMN displevl."MinLevel" IS 'Minimum level for this kit type';
COMMENT ON COLUMN displevl."KitType" IS 'Primary key component, the kit type that this minimum level is for. Ptr to KITTYPE.KitType';
COMMENT ON COLUMN displevl."DispCode" IS 'Primary key component, the dispensary that this minimum level is for. Ptr to DISPCODE.DispCode';


CREATE  TABLE displost (
  "DispLost" numeric(10,0) NOT NULL,
  "Provider" character(10),
  "DispCode" character(6),
  "Returned" numeric(5,0),
  "Type" numeric(5,0),
  "Kit" character(30),
  "Item" numeric(10,0),
  "Sundry" character(6),
  "Date" timestamp without time zone,
  "DReason" character(6),
  "Deleted" numeric(5,0),
  CONSTRAINT displost_primary PRIMARY KEY ("DispLost")
) ;
COMMENT ON TABLE displost IS 'Record of lost dispensary items';
COMMENT ON COLUMN displost."Type" IS 'Type of dispensary item lost (0=Kit, 1=Sundry, 2=Kit item)';
COMMENT ON COLUMN displost."Sundry" IS 'If Type=1, ID code of the sundry item. Ptr to SUNDRY.Sundry';
COMMENT ON COLUMN displost."Returned" IS 'Item returned? (0 = No, 1 = Yes)';
COMMENT ON COLUMN displost."Provider" IS 'ID code of the provider this item was last checked out to, ptr to PRODUCER.Producer ';
COMMENT ON COLUMN displost."Kit" IS 'If Type=0, ID code of the kit. Ptr to KIT.Kit';
COMMENT ON COLUMN displost."Item" IS 'If Type=0, number of the item in the kit. ';
COMMENT ON COLUMN displost."DispLost" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN displost."DispCode" IS 'ID code of the dispensary, ptr to DISPCODE.DispCode';
COMMENT ON COLUMN displost."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN displost."Date" IS 'Date the item was reported as lost';
COMMENT ON COLUMN displost."DReason" IS 'ID code to identify the reason, ptr to DREASON.DReason';


CREATE  TABLE dispreq (
  "DispReq" numeric(10,0) NOT NULL,
  "Provider" character(10),
  "Order" numeric(10,0),
  "DispCode" character(6),
  "Type" numeric(5,0),
  "KitType" character(6),
  "Sundry" character(6),
  "Date" timestamp without time zone,
  "Time" numeric(10,0),
  "DateOut" timestamp without time zone,
  "TimeOut" numeric(10,0),
  CONSTRAINT dispreq_primary PRIMARY KEY ("DispReq")
) ;
CREATE INDEX IF NOT EXISTS dispreq_dateout ON dispreq USING btree ("DateOut") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS dispreq_provider ON dispreq USING btree ("Provider") TABLESPACE pg_default;
COMMENT ON TABLE dispreq IS 'Dispensary request records';
COMMENT ON COLUMN dispreq."Type" IS 'Type of dispensary item requested (0=Kit, 1=Sundry)';
COMMENT ON COLUMN dispreq."TimeOut" IS 'Time item requested for';
COMMENT ON COLUMN dispreq."Time" IS 'Time of the request';
COMMENT ON COLUMN dispreq."Sundry" IS 'ID code of the sundry being requested (if type=1), ptr to SUNDRY.Sundry';
COMMENT ON COLUMN dispreq."Provider" IS 'Id code of the provider making the request, ptr to PRODUCER.Producer';
COMMENT ON COLUMN dispreq."Order" IS 'Request Order# (like an invoice#)';
COMMENT ON COLUMN dispreq."KitType" IS 'ID code of the KitType requested (if type = 0), ptr to KITTYPE.KitType';
COMMENT ON COLUMN dispreq."DispReq" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN dispreq."DispCode" IS 'ID code of the Dispensary thay this request is for, ptr to DISPCODE.DispCode';
COMMENT ON COLUMN dispreq."DateOut" IS 'Date item requested for';
COMMENT ON COLUMN dispreq."Date" IS 'Date of the request';


CREATE  TABLE disptrx (
  "DispTrx" numeric(10,0) NOT NULL,
  "Provider" character(10),
  "Date" timestamp without time zone,
  "DICharge" character(6),
  "Description" character(30),
  "Total" numeric,
  "CreateDate" timestamp without time zone,
  "Deleted" numeric(5,0),
  "User" numeric(10,0),
  "DispLost" numeric(10,0),
  CONSTRAINT disptrx_primary PRIMARY KEY ("DispTrx")
) ;
CREATE INDEX IF NOT EXISTS disptrx_provider ON disptrx USING btree ("Provider") TABLESPACE pg_default;
COMMENT ON TABLE disptrx IS 'Dispensary transactions';
COMMENT ON COLUMN disptrx."User" IS 'User Id of the entry user, ptr to USERS.User';
COMMENT ON COLUMN disptrx."Total" IS 'Dollar ($) amount of this transaction';
COMMENT ON COLUMN disptrx."Provider" IS 'Id code of the provider, ptr to PRODUCER.Producer';
COMMENT ON COLUMN disptrx."DispTrx" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN disptrx."DispLost" IS 'Ptr to DISPLOST.DispLost';
COMMENT ON COLUMN disptrx."Description" IS 'Description of the dispensary charge';
COMMENT ON COLUMN disptrx."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN disptrx."Date" IS 'Date of the transaction';
COMMENT ON COLUMN disptrx."DICharge" IS 'ID code of the dispensary charge type, ptr to DICHARGE.DICharge';
COMMENT ON COLUMN disptrx."CreateDate" IS 'Date of the transaction';


CREATE  TABLE distempl (
  "Provider" character(10) NOT NULL,
  "Template" character(6) NOT NULL,
  "Description" character(30),
  CONSTRAINT distempl_primary PRIMARY KEY ("Provider", "Template")
) ;
COMMENT ON TABLE distempl IS 'Dispensary template';
COMMENT ON COLUMN distempl."Template" IS 'Primary key component, ID code to identify the template.';
COMMENT ON COLUMN distempl."Provider" IS 'Primary key component, ID of the provider that this template is for. Ptr to PRODUCER.Producer.';
COMMENT ON COLUMN distempl."Description" IS 'Description of the template';


CREATE  TABLE distitem (
  "Provider" character(10) NOT NULL,
  "Template" character(6) NOT NULL,
  "Item" numeric(10,0) NOT NULL,
  "Type" numeric(5,0),
  "KitType" character(6),
  "Sundry" character(6),
  CONSTRAINT distitem_primary PRIMARY KEY ("Provider", "Template", "Item")
) ;
COMMENT ON TABLE distitem IS 'Dispensary template items';
COMMENT ON COLUMN distitem."Type" IS 'Type of dispensary item (0=Kit, 1=Sundry)';
COMMENT ON COLUMN distitem."Template" IS 'Primary key component, ID code the template. Ptr to DISTEMPL.Template.';
COMMENT ON COLUMN distitem."Sundry" IS 'ID Code to identify the sundry item, ptr to SUNDRY.Sundry';
COMMENT ON COLUMN distitem."Provider" IS 'Primary key component, ID of the provider that this template item is for. Ptr to PRODUCER.Producer.';
COMMENT ON COLUMN distitem."KitType" IS 'ID code to indicate the kit type, ptr to KITTYPE.KitType';
COMMENT ON COLUMN distitem."Item" IS 'Primary key component, item # of the dispensary item in this template. ';


CREATE  TABLE dmsgsent (
  "DMsgId" numeric(10,0) NOT NULL,
  "Date" timestamp without time zone,
  "FromAddr" character varying(100),
  "ToAddr" character varying(4000),
  "Subject" character varying(4000),
  "Text" character varying(4000),
  attach clob,
  "Patient" numeric(10,0),
  "Audit" numeric(10,0),
  "ExternalId" character varying(255),
  "MsgStatus" character varying(4000),
  CONSTRAINT dmsgsent_primary PRIMARY KEY ("DMsgId")
) ;
COMMENT ON TABLE dmsgsent IS 'Table for storing direct messages sent';
COMMENT ON COLUMN dmsgsent.attach IS 'Message attachment';
COMMENT ON COLUMN dmsgsent."ToAddr" IS 'Email address(es) of recipient(s)';
COMMENT ON COLUMN dmsgsent."Text" IS 'Message text';
COMMENT ON COLUMN dmsgsent."Subject" IS 'Message subject';
COMMENT ON COLUMN dmsgsent."Patient" IS 'Patient Id the attachment is for';
COMMENT ON COLUMN dmsgsent."MsgStatus" IS 'Status(es) of the message sent for each recipient email';
COMMENT ON COLUMN dmsgsent."FromAddr" IS 'Email address of sender';
COMMENT ON COLUMN dmsgsent."ExternalId" IS 'External GUID returned by SES';
COMMENT ON COLUMN dmsgsent."Date" IS 'Date / Time for message sent';
COMMENT ON COLUMN dmsgsent."DMsgId" IS 'Primary key, sequence field';
COMMENT ON COLUMN dmsgsent."Audit" IS 'Audit Id for the given sent message';


CREATE  TABLE doctempl (
  "DocTempl" numeric(10,0) NOT NULL,
  "Name" character(50),
  "ReportId" numeric(10,0),
  "CustomId" numeric(10,0),
  "User" numeric(10,0),
  "Date" timestamp without time zone,
  "StationId" numeric(10,0),
  "Type" numeric(5,0),
  "ReqAudit" numeric(5,0),
  "Deleted" numeric(5,0),
  template bytea,
  "AddToContact" numeric(5,0),
  "AtTab" numeric(10,0),
  CONSTRAINT doctempl_primary PRIMARY KEY ("DocTempl")
) ;
CREATE INDEX IF NOT EXISTS doctempl_type ON doctempl USING btree ("Type", "ReportId", "CustomId") TABLESPACE pg_default;
COMMENT ON TABLE doctempl IS 'Document templates';
COMMENT ON COLUMN doctempl.template IS 'Raw data that holds the template formatting information. Note: In Oracle 9i this field is Type: BLOB';
COMMENT ON COLUMN doctempl."User" IS 'User Id of entry user, ptr to USERS.User';
COMMENT ON COLUMN doctempl."Type" IS 'Type of template (0=Letter, 1=Label)';
COMMENT ON COLUMN doctempl."StationId" IS 'Station Id of the entry station, ptr to STATION.StationId';
COMMENT ON COLUMN doctempl."ReqAudit" IS 'Audit changes to this template? (0 = No, 1 = Yes)';
COMMENT ON COLUMN doctempl."ReportId" IS 'Info manager category Id';
COMMENT ON COLUMN doctempl."Name" IS 'The name / title assigned to the document';
COMMENT ON COLUMN doctempl."DocTempl" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN doctempl."Deleted" IS 'Template deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN doctempl."Date" IS 'Date the document was entered. ';
COMMENT ON COLUMN doctempl."CustomId" IS 'ptr to CUSTQRY_AutoDec, 0 if not a custom report.';
COMMENT ON COLUMN doctempl."AtTab" IS 'Ptr to ATTAB.AtTab to show attachment in';
COMMENT ON COLUMN doctempl."AddToContact" IS 'Add to contact? (0 = No, 1= Program is required to make an entry to PTCONT table when letter is printed) Only applicable to patient type letters.';


CREATE  TABLE drapptcd (
  "ApptCode" character(15) NOT NULL,
  "Provider" character(10) NOT NULL,
  "Unit0" numeric(10,0),
  "Unit1" numeric(10,0),
  "Unit2" numeric(10,0),
  "Unit3" numeric(10,0),
  "Unit4" numeric(10,0),
  "Unit5" numeric(10,0),
  "Time0" numeric(10,0),
  "Time1" numeric(10,0),
  "Time2" numeric(10,0),
  "Time3" numeric(10,0),
  "Time4" numeric(10,0),
  "Time5" numeric(10,0),
  "PrimaryExclusive" numeric(5,0),
  CONSTRAINT drapptcd_primary PRIMARY KEY ("ApptCode", "Provider")
) ;
COMMENT ON TABLE drapptcd IS 'Appt Codes for an individual provider - used to specify different appt times for each doctor';
COMMENT ON COLUMN drapptcd."Unit5" IS 'Appt Doctor Unit3 (for production details)';
COMMENT ON COLUMN drapptcd."Unit4" IS 'Appt Assistant Unit3 (for production details)';
COMMENT ON COLUMN drapptcd."Unit3" IS 'Appt Doctor Unit2 (for production details)';
COMMENT ON COLUMN drapptcd."Unit2" IS 'Appt Assistant Unit2 (for production details)';
COMMENT ON COLUMN drapptcd."Unit1" IS 'Appt Doctor Unit1 (for production details)';
COMMENT ON COLUMN drapptcd."Unit0" IS 'Appt Assistant Unit1 (for production details)';
COMMENT ON COLUMN drapptcd."Time5" IS 'Appt Doctor Time3 in minutes (for production details)';
COMMENT ON COLUMN drapptcd."Time4" IS 'Appt Assistant Time3 in minutes (for production details)';
COMMENT ON COLUMN drapptcd."Time3" IS 'Appt Doctor Time2 in minutes (for production details)';
COMMENT ON COLUMN drapptcd."Time2" IS 'Appt Assistant Time2 in minutes (for production details)';
COMMENT ON COLUMN drapptcd."Time1" IS 'Appt Doctor Time1 in minutes (for production details)';
COMMENT ON COLUMN drapptcd."Time0" IS 'Appt Assistant Time1 in minutes (for production details)';
COMMENT ON COLUMN drapptcd."Provider" IS 'Provider that code is for, ptr to PRODUCER.Producer';
COMMENT ON COLUMN drapptcd."PrimaryExclusive" IS 'Primary exclusive time? (0=No, 1=Yes [Appt Time], 2=Yes [Prov Time])';
COMMENT ON COLUMN drapptcd."ApptCode" IS 'Appt Code that code is for, ptr to APPTCODE.ApptCode';


CREATE  TABLE dreason (
  "DReason" character(6) NOT NULL,
  "Description" character(30),
  "IsChargeable" numeric(5,0),
  "DICharge" character(6),
  "RefundCode" character(6),
  CONSTRAINT dreason_primary PRIMARY KEY ("DReason")
) ;
COMMENT ON TABLE dreason IS 'Dispensary Reason Codes';
COMMENT ON COLUMN dreason."RefundCode" IS 'Billing code to use for refunding dispensary charge, ptr to DICHARGE.DICharge';
COMMENT ON COLUMN dreason."IsChargeable" IS 'Chargeable? (0 = No, 1 = Yes)';
COMMENT ON COLUMN dreason."Description" IS 'Description of the reason';
COMMENT ON COLUMN dreason."DReason" IS 'ID code to identify this reason';
COMMENT ON COLUMN dreason."DICharge" IS 'Billing code of the charge type, ptr to DICHARGE.DICharge';


CREATE  TABLE drug (
  "Drug" character(10) NOT NULL,
  "Description" character varying(100),
  "Inactive" numeric(5,0),
  "DoseRequired" numeric(5,0),
  "BlockPrint" numeric(5,0),
  "FilePath" character varying(255),
  printcontent bytea,
  "NumericQty" numeric(5,0),
  "MinQty" numeric(5,0),
  "MaxQty" numeric(5,0),
  "MinRefill" numeric(5,0),
  "MaxRefill" numeric(5,0),
  "ControlledSubstance" numeric(5,0),
  "CSSchedule" numeric(5,0),
  "Narcotic" numeric(5,0),
  "SideEffects" character varying(4000),
  "Formulary" numeric(5,0),
  "AllowRefills" numeric(5,0),
  CONSTRAINT drug_primary PRIMARY KEY ("Drug")
) ;
CREATE INDEX IF NOT EXISTS drug_description ON drug USING btree ("Description") TABLESPACE pg_default;
COMMENT ON TABLE drug IS 'Table of drug names';
COMMENT ON COLUMN drug.printcontent IS 'Copy of the rpt referenced in FilePath above. ';
COMMENT ON COLUMN drug."SideEffects" IS 'Text describing side effects and reactions.';
COMMENT ON COLUMN drug."NumericQty" IS '0 = No, 1 = Yes';
COMMENT ON COLUMN drug."Narcotic" IS 'Is drug a narcotic? (0=No, 1=Yes)';
COMMENT ON COLUMN drug."MinRefill" IS 'Minimum value allowed in the Refills field when prescribing this drug. ';
COMMENT ON COLUMN drug."MinQty" IS 'Minimum value allowed in the Total field when prescribing this drug. ';
COMMENT ON COLUMN drug."MaxRefill" IS 'Maximum value allowed in the Refills field when prescribing this drug. ';
COMMENT ON COLUMN drug."MaxQty" IS 'Maximum value allowed in the Total field when prescribing this drug. ';
COMMENT ON COLUMN drug."Inactive" IS 'Inactive? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN drug."Formulary" IS 'Is the drug available for prescriptions? (0=No, 1=Yes)';
COMMENT ON COLUMN drug."FilePath" IS 'Pathname to location of rpt to use when printing a prescription for this drug.';
COMMENT ON COLUMN drug."Drug" IS 'ID code to identify the drug record';
COMMENT ON COLUMN drug."DoseRequired" IS 'Dosage is required for this drug (0 = No, 1 = Yes)';
COMMENT ON COLUMN drug."Description" IS 'Full name of the drug';
COMMENT ON COLUMN drug."ControlledSubstance" IS 'Is drug a controlled substance? (0=No, 1=Yes)';
COMMENT ON COLUMN drug."CSSchedule" IS 'Schedule that drug is on, if a controlled substance.';
COMMENT ON COLUMN drug."BlockPrint" IS 'Block Printing? (0 = No, 1 = Yes)';
COMMENT ON COLUMN drug."AllowRefills" IS 'Are prescriptions for this drug allowed to have refills? (0=No, 1=Yes)';


CREATE  TABLE drugacc (
  "Drug" character(10) NOT NULL,
  "SLevel" numeric(10,0) NOT NULL,
  "Access" numeric(5,0),
  "CanApprove" numeric(5,0),
  CONSTRAINT drugacc_primary PRIMARY KEY ("Drug", "SLevel")
) ;
COMMENT ON TABLE drugacc IS 'Drug Access';
COMMENT ON COLUMN drugacc."SLevel" IS 'Primary key component, the security level access is being defined for. Ptr to SLEVEL.SLevel';
COMMENT ON COLUMN drugacc."Drug" IS 'Primary key component, the drug access is being defined for. Ptr to DRUG.Drug';
COMMENT ON COLUMN drugacc."CanApprove" IS 'Can approve? (0=No, 1=Yes)';
COMMENT ON COLUMN drugacc."Access" IS 'Can prescribe? (0=No, 1=Yes, 2=Yes with Approval)';


CREATE  TABLE drugdfrq (
  "Drug" character(10) NOT NULL,
  "Dose" character varying(25) NOT NULL,
  "DrugFrq" numeric(10,0) NOT NULL,
  "Default" numeric(5,0),
  CONSTRAINT drugdfrq_primary PRIMARY KEY ("Drug", "Dose", "DrugFrq")
) ;
COMMENT ON TABLE drugdfrq IS 'Frequencies for use with specific drug dosages';
COMMENT ON COLUMN drugdfrq."DrugFrq" IS 'Drug frequency, ptr to DRUGFRQ.DrugFrq';
COMMENT ON COLUMN drugdfrq."Drug" IS 'ID code of the drug, ptr to DRUGDOSE.Drug';
COMMENT ON COLUMN drugdfrq."Dose" IS 'Acceptable dosage for this drug, ptr to DRUGDOSE.Dose';
COMMENT ON COLUMN drugdfrq."Default" IS 'Default frequency for this drug? (0 = No, 1 = Yes)';


CREATE  TABLE drugdose (
  "Drug" character(10) NOT NULL,
  "Dose" character varying(25) NOT NULL,
  "Note" character varying(100),
  "RxNorm" character varying(8),
  "Order" numeric(5,0),
  "Default" numeric(5,0),
  CONSTRAINT drugdose_primary PRIMARY KEY ("Drug", "Dose")
) ;
CREATE INDEX IF NOT EXISTS drugdose_rxnormkey ON drugdose USING btree ("RxNorm") TABLESPACE pg_default;
COMMENT ON TABLE drugdose IS 'Table of drug dosages';
COMMENT ON COLUMN drugdose."RxNorm" IS 'National Drug Code (US) for medication/dosage combination.';
COMMENT ON COLUMN drugdose."Order" IS 'Integer 1..x to represent the order of this dosage in the list of dosages for this drug';
COMMENT ON COLUMN drugdose."Note" IS 'Default dosage note for this drug/ dose combination.';
COMMENT ON COLUMN drugdose."Drug" IS 'ID code of the drug, ptr to DRUG.Drug';
COMMENT ON COLUMN drugdose."Dose" IS 'Acceptable dosage for the drug (i.e. 250mg.)';
COMMENT ON COLUMN drugdose."Default" IS 'Is this the default dosage for this drug? (0=No, 1=Yes)';


CREATE  TABLE drugfrq (
  "DrugFrq" numeric(10,0) NOT NULL,
  "Description" character varying(250),
  "Inactive" numeric(5,0),
  CONSTRAINT drugfrq_primary PRIMARY KEY ("DrugFrq")
) ;
COMMENT ON TABLE drugfrq IS 'List of drug frequencies for prescription writing ';
COMMENT ON COLUMN drugfrq."Inactive" IS 'Record is inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN drugfrq."DrugFrq" IS 'Id code to identify the drug frequency, internal ID from sequence';
COMMENT ON COLUMN drugfrq."Description" IS 'Description of the frequency (i.e. 2 x TID)';


CREATE  TABLE drugfrqreferential (
  "DrugFrqDescLike" character varying(250) NOT NULL,
  "Value" character varying(250),
  "UnitCode" character varying(250),
  "SystemCode" character varying(250),
  "Description" character varying(250),
  CONSTRAINT drugfrqreferential_pk_ct PRIMARY KEY ("DrugFrqDescLike")
) ;
COMMENT ON TABLE drugfrqreferential IS 'Table for Drug Frequency Code Lookup (used by CCDA_CFG_PKG).';


CREATE  TABLE drugreac (
  "DrugReac" numeric(10,0) NOT NULL,
  "Drug" character(10),
  "ReactType" numeric(5,0),
  "ReactDrug" character(10),
  "ReactAlert" character(7),
  "Severity" numeric(5,0),
  "Description" character varying(4000),
  "AlertType" numeric(5,0),
  "MedAlert" numeric(10,0),
  CONSTRAINT drugreac_primary PRIMARY KEY ("DrugReac")
) ;
CREATE INDEX IF NOT EXISTS drugreac_drug ON drugreac USING btree ("Drug") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS drugreac_reactalert ON drugreac USING btree ("ReactAlert") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS drugreac_reactdrug ON drugreac USING btree ("ReactDrug") TABLESPACE pg_default;
COMMENT ON TABLE drugreac IS 'Drug Interactions / Reactions';
COMMENT ON COLUMN drugreac."Severity" IS 'Severity of the interaction (0=Low, 1=Medium, 2=High, 3=Very High)';
COMMENT ON COLUMN drugreac."ReactType" IS 'Type of reaction with this drug (0=Drug/Drug interaction, 1=Drug/Alert interaction)';
COMMENT ON COLUMN drugreac."ReactDrug" IS 'If ReactType=0, drug that this drug interacts with, ptr to DRUG.Drug';
COMMENT ON COLUMN drugreac."ReactAlert" IS 'If ReactType=1, alert that this drug interacts with, ptr to ALERTD2.Code';
COMMENT ON COLUMN drugreac."MedAlert" IS 'If ReactAlert = 1, ptr to MEDALERT.Auto';
COMMENT ON COLUMN drugreac."DrugReac" IS 'Primary key, internal ID from sequence';
COMMENT ON COLUMN drugreac."Drug" IS 'Drug that has the inter ptr to DRUG.Drug';
COMMENT ON COLUMN drugreac."Description" IS 'Description of the interaction.';
COMMENT ON COLUMN drugreac."AlertType" IS 'Alert type (0 = Clinical Alert, 1 = Allergy, 2 = Medical Problem)';


CREATE  TABLE drugroutecode (
  "RxNorm" character varying(250) NOT NULL,
  "Code" character varying(250),
  "DisplayName" character varying(250),
  "SystemCode" character varying(250),
  "CodeSystemName" character varying(250),
  CONSTRAINT drugroutecode_pk_ct PRIMARY KEY ("RxNorm")
) ;
COMMENT ON TABLE drugroutecode IS 'Table for RxNorm Drug Code Lookup (used by CCDA_CFG_PKG).';


CREATE  TABLE dsetting (
  "User" numeric(10,0) NOT NULL,
  "Key" character varying(255) NOT NULL,
  "Value" character varying(4000),
  CONSTRAINT dsetting_pk PRIMARY KEY ("User", "Key")
) ;
COMMENT ON TABLE dsetting IS 'Stores both global and user-specific settings for DA';
COMMENT ON COLUMN dsetting."Value" IS 'Value of setting';
COMMENT ON COLUMN dsetting."User" IS 'User this setting applies for (0 = Global)';
COMMENT ON COLUMN dsetting."Key" IS 'Lookup key for setting';


CREATE  TABLE dtaccess (
  "DTType" numeric(5,0) NOT NULL,
  "DocTempl" numeric(10,0) NOT NULL,
  "SLevel" numeric(10,0) NOT NULL,
  "UserId" numeric(10,0) NOT NULL,
  "Access" numeric(5,0),
  CONSTRAINT dtaccess_primary PRIMARY KEY ("DTType", "DocTempl", "SLevel", "UserId")
) ;
COMMENT ON TABLE dtaccess IS 'Security restrictions for DOCTEMPL Word Letter and Word Label Templates';
COMMENT ON COLUMN dtaccess."UserId" IS 'Primary key component, ptr to USERS.User';
COMMENT ON COLUMN dtaccess."SLevel" IS 'Primary key component, ptr to SLEVEL.SLevel';
COMMENT ON COLUMN dtaccess."DocTempl" IS 'Primary key component, ptr to DOCTEMPL.DocTempl';
COMMENT ON COLUMN dtaccess."DTType" IS 'Primary key component. Type of template (0=Word Letter, 1=Word Label)';
COMMENT ON COLUMN dtaccess."Access" IS 'Access rights (0=No Access, 1=Read Only, 2=Full Access)';


CREATE  TABLE dtemplat (
  "Discipline" character(6) NOT NULL,
  "Year" numeric(10,0) NOT NULL,
  "Template" character(6),
  CONSTRAINT dtemplat_primary PRIMARY KEY ("Discipline", "Year")
) ;
COMMENT ON TABLE dtemplat IS 'Link between disciplines and evaluation forms.. ie: ENDO, 3rd year uses the ENDO grading form';
COMMENT ON COLUMN dtemplat."Year" IS 'Primary key component, student year of studies (usually 1...4)';
COMMENT ON COLUMN dtemplat."Template" IS 'Template code to use as the default template for this particular year / discipline combination, ptr to TEMPLATE.Template.';
COMMENT ON COLUMN dtemplat."Discipline" IS 'Primary key component, discipline that this link is for. Ptr to DISCIPL.Discipline.';


CREATE  TABLE dtmplhis (
  "DTmplHis" numeric(10,0) NOT NULL,
  "HistoryType" numeric(5,0),
  "DocTempl" numeric(10,0),
  "Name" character(50),
  "ReportId" numeric(10,0),
  "CustomId" numeric(10,0),
  "User" numeric(10,0),
  "Date" timestamp without time zone,
  "StationId" numeric(10,0),
  "Type" numeric(5,0),
  "ReqAudit" numeric(5,0),
  "Deleted" numeric(5,0),
  template bytea,
  "AddToContact" numeric(5,0),
  "AtTab" numeric(10,0),
  CONSTRAINT dtmplhis_primary PRIMARY KEY ("DTmplHis")
) ;
CREATE INDEX IF NOT EXISTS dtmplhis_doctempl ON dtmplhis USING btree ("DocTempl") TABLESPACE pg_default;
COMMENT ON TABLE dtmplhis IS 'History records of the document templates';
COMMENT ON COLUMN dtmplhis.template IS 'Raw data that holds the template formatting information. Note: In Oracle 9i this field is Type: BLOB';
COMMENT ON COLUMN dtmplhis."User" IS 'User Id of entry user, ptr to USERS.User';
COMMENT ON COLUMN dtmplhis."Type" IS 'Type of template (0=Letter, 1=Label)';
COMMENT ON COLUMN dtmplhis."StationId" IS 'Station Id of the entry station, ptr to STATION.StationId';
COMMENT ON COLUMN dtmplhis."ReqAudit" IS 'Audit changes to this template? (0 = No, 1 = Yes)';
COMMENT ON COLUMN dtmplhis."ReportId" IS 'Info manager category Id';
COMMENT ON COLUMN dtmplhis."Name" IS 'The name / title assigned to the document';
COMMENT ON COLUMN dtmplhis."HistoryType" IS 'Type of history record';
COMMENT ON COLUMN dtmplhis."DocTempl" IS 'Document template that this history is for, ptr to DOCTEMPL.DocTempl';
COMMENT ON COLUMN dtmplhis."Deleted" IS 'Template deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN dtmplhis."Date" IS 'Date the document was entered. ';
COMMENT ON COLUMN dtmplhis."DTmplHis" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN dtmplhis."CustomId" IS 'ptr to CUSTQRY_AutoDec, 0 if not a custom report.';
COMMENT ON COLUMN dtmplhis."AtTab" IS 'Ptr to ATTAB.AtTab to show attachment in';
COMMENT ON COLUMN dtmplhis."AddToContact" IS 'Add to contact? (0 = No, 1= Program is required to make an entry to PTCONT table when letter is printed) Only applicable to patient type letters.';


CREATE  TABLE dtxapp (
  "Id" numeric(10,0) NOT NULL,
  "AppointNumber" character(7),
  "EstTime" character(30),
  "PatientApprove" numeric(5,0),
  "ApproveDate" timestamp without time zone,
  CONSTRAINT dtxapp_primary PRIMARY KEY ("Id")
) ;


CREATE  TABLE dtxappid (
  "Option" numeric(10,0) NOT NULL,
  "ConsultantId" numeric(10,0),
  "ConsultantType" numeric(5,0) NOT NULL,
  "ApproveDate" timestamp without time zone,
  "Approved" numeric(5,0),
  CONSTRAINT dtxappid_primary PRIMARY KEY ("Option", "ConsultantType")
) ;
COMMENT ON TABLE dtxappid IS 'Detailed Tx Plan Approval by Consultant';
COMMENT ON COLUMN dtxappid."Option" IS 'Primary key component, the detailed tx plan option being approved. Ptr to DTXOPT.Option';
COMMENT ON COLUMN dtxappid."ConsultantType" IS 'Primary key component, the consultant type that approved. Ptr to CONSULTS.Id';
COMMENT ON COLUMN dtxappid."ConsultantId" IS 'User ID of consultant that approved, ptr to USERS.User';
COMMENT ON COLUMN dtxappid."Approved" IS 'Is Approved? (0 = No, 1 = Yes)';
COMMENT ON COLUMN dtxappid."ApproveDate" IS 'Date of approval';


CREATE  TABLE dtxopt (
  "Option" numeric(10,0) NOT NULL,
  "Complaint" numeric(10,0),
  "Consultant" numeric(5,0),
  "Instructor" numeric(5,0),
  "Cost" numeric,
  "Date" timestamp without time zone,
  "InsCost" numeric,
  "InstructorId" numeric(10,0),
  "InstructorApproveDate" timestamp without time zone,
  "Description" character varying(60),
  "AppNA" numeric(5,0),
  CONSTRAINT dtxopt_primary PRIMARY KEY ("Option")
) ;
CREATE INDEX IF NOT EXISTS dtxopt_complaint ON dtxopt USING btree ("Complaint") TABLESPACE pg_default;
COMMENT ON TABLE dtxopt IS 'Detailed Tx Plan Option (consisting of Detailed Tx)';
COMMENT ON COLUMN dtxopt."Option" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN dtxopt."InstructorId" IS 'User ID of instructor that approved treatment plan option, ptr to USERS.User';
COMMENT ON COLUMN dtxopt."InstructorApproveDate" IS 'Date instructor approved this treatment plan option.';
COMMENT ON COLUMN dtxopt."Instructor" IS 'Has Instructor Approval? (0 = No, 1 = Yes)';
COMMENT ON COLUMN dtxopt."InsCost" IS 'Estimated insurance portion of cost, in dollars.';
COMMENT ON COLUMN dtxopt."Description" IS 'Optional description of option.';
COMMENT ON COLUMN dtxopt."Date" IS 'Date of Entry';
COMMENT ON COLUMN dtxopt."Cost" IS 'Estimated cost of option, in dollars. ';
COMMENT ON COLUMN dtxopt."Consultant" IS 'Has Consultant Approval? (0 = No, 1 = Yes)';
COMMENT ON COLUMN dtxopt."Complaint" IS 'Complaint (Tx Plan) Id, ptr to COMPLAIN.Auto';
COMMENT ON COLUMN dtxopt."AppNA" IS 'Is approval not required/not applicable for this option? ( 0 = No, 1 = Yes)';


CREATE  TABLE dtxplan (
  "Id" numeric(10,0) NOT NULL,
  "Option" numeric(10,0),
  "Complaint" numeric(10,0),
  "Code" character(7),
  "Tooth" character(3),
  "Surface" character(6),
  "Phase" character(2),
  "Sequence" character(2),
  "Deleted" numeric(5,0),
  "Desc" character varying(60),
  "Cost" numeric,
  "Site2" character(3),
  "InsCost" numeric,
  "ConsultantType" numeric(5,0),
  "Site1Index" numeric(5,0),
  "Surface1" numeric(5,0),
  "Site2Index" numeric(5,0),
  "Surface2" numeric(5,0),
  "Status" character(1),
  "Treatmen2Id" numeric(10,0),
  "GtxPlanId" numeric(10,0),
  "Custom1" character(6),
  "Custom2" character(6),
  "Provider" character(10),
  "Diagnose" numeric(10,0),
  "Discipline" character(15),
  "DtxType" numeric(5,0),
  "Text" character varying(4000),
  "Order" numeric(5,0),
  "ClaimDoctor" character(10),
  "HeldTotal" numeric(5,0),
  "MacroSeq" numeric(10,0),
  "Unit" numeric,
  CONSTRAINT dtxplan_primary PRIMARY KEY ("Id")
) ;
CREATE INDEX IF NOT EXISTS dtxplan_complaint ON dtxplan USING btree ("Complaint") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS dtxplan_gtxplanid ON dtxplan USING btree ("GtxPlanId") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS dtxplan_option ON dtxplan USING btree ("Option") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS dtxplan_treatme2id ON dtxplan USING btree ("Treatmen2Id") TABLESPACE pg_default;
COMMENT ON TABLE dtxplan IS 'Detailed Tx Plan Treatment';
COMMENT ON COLUMN dtxplan."Unit" IS 'Number of units for the unapproved treatment.';
COMMENT ON COLUMN dtxplan."Treatmen2Id" IS 'ID code of the treatment in the EHR, ptr to TREATME2.Auto';
COMMENT ON COLUMN dtxplan."Tooth" IS 'Site (tooth #) treatment will be performed on. ';
COMMENT ON COLUMN dtxplan."Text" IS 'If DtxType=1, then the quote text. ';
COMMENT ON COLUMN dtxplan."Surface2" IS 'Internal index # of end site surfaces, if procedure spans multiple sites (i.e. bridges)';
COMMENT ON COLUMN dtxplan."Surface1" IS 'Internal index # of surfaces treatment will be performed on. ';
COMMENT ON COLUMN dtxplan."Surface" IS 'Surface treatment will be performed on.';
COMMENT ON COLUMN dtxplan."Status" IS 'Status of the treatment (P=Planned, I=InProcess, C=Complete) ';
COMMENT ON COLUMN dtxplan."Site2Index" IS 'Internal index # of end site, if procedure spans multiple sites (i.e. bridges)';
COMMENT ON COLUMN dtxplan."Site2" IS 'If procedure spans multiple sites (i.e. bridges), the ending site of the span.';
COMMENT ON COLUMN dtxplan."Site1Index" IS 'Internal index # of site (tooth) treatment will be performed on. ';
COMMENT ON COLUMN dtxplan."Sequence" IS 'Treatment sequence order.';
COMMENT ON COLUMN dtxplan."Provider" IS 'ID code of the treating provider, ptr to PRODUCER.Producer';
COMMENT ON COLUMN dtxplan."Phase" IS 'Treatment phase.';
COMMENT ON COLUMN dtxplan."Order" IS 'Line order in the summarized estimate.';
COMMENT ON COLUMN dtxplan."Option" IS 'Detailed treament plan option that this treatment is on, ptr to DTXOPT.Option';
COMMENT ON COLUMN dtxplan."MacroSeq" IS 'Unique ID given to all procedures added from the same macro, internal ID from sequence. ';
COMMENT ON COLUMN dtxplan."InsCost" IS 'Estimated insurance portion of cost, in dollars.';
COMMENT ON COLUMN dtxplan."Id" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN dtxplan."HeldTotal" IS 'Held estimate? (0=No, 1=Yes)';
COMMENT ON COLUMN dtxplan."GtxPlanId" IS 'General treatment plan ID, ptr to GTXPLAN.Id';
COMMENT ON COLUMN dtxplan."DtxType" IS 'Type: (0 = Procedure, 1 = Quote Text)';
COMMENT ON COLUMN dtxplan."Discipline" IS 'Discipline for this treatment, ptr to CLASS.Class';
COMMENT ON COLUMN dtxplan."Diagnose" IS 'Associated diagnosis for this treatment, prt to DIAGNOSE.Auto';
COMMENT ON COLUMN dtxplan."Desc" IS 'Description of procedure.';
COMMENT ON COLUMN dtxplan."Deleted" IS 'Has treatment been deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN dtxplan."Custom2" IS 'Custom field #2, ptr to CUSTCODE.Code';
COMMENT ON COLUMN dtxplan."Custom1" IS 'Custom field #1, ptr to CUSTCODE.Code';
COMMENT ON COLUMN dtxplan."Cost" IS 'Estimated cost of procedure, in dollars.';
COMMENT ON COLUMN dtxplan."ConsultantType" IS 'Consultant type required to approve, ptr to CONSULTS.I';
COMMENT ON COLUMN dtxplan."Complaint" IS 'Complaint (Tx Plan) ID, ptr to COMPLAIN.Auto';
COMMENT ON COLUMN dtxplan."Code" IS 'Procedure code, ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN dtxplan."ClaimDoctor" IS 'Claim doctor to use for calculating the plan fees, ptr to PRODUCER.Producer';


CREATE  TABLE ediattach (
  "Claim" numeric(10,0) NOT NULL DEFAULT 0,
  "Number" numeric(10,0) NOT NULL DEFAULT 0,
  "Date" timestamp without time zone,
  "PtLetter" numeric(10,0) NOT NULL DEFAULT 0,
  "Path" character varying(255),
  "Audit" numeric(10,0) NOT NULL DEFAULT 0,
  "Status" numeric(5,0) NOT NULL DEFAULT 0,
  "EDIForm" numeric(10,0) NOT NULL DEFAULT 0,
  CONSTRAINT ediattach_pk PRIMARY KEY ("Claim", "Number")
) ;
COMMENT ON TABLE ediattach IS 'Table for storing claim attachments sent to CDAnet';
COMMENT ON COLUMN ediattach."Status" IS 'The status of the attachment. 0 - Not sent, 1 - Accepted, 2 - Rejected';
COMMENT ON COLUMN ediattach."PtLetter" IS 'If the attachment is stored in the Attachment Manager, this is the PTLETTER.PtLetter of that attachment';
COMMENT ON COLUMN ediattach."Path" IS 'Path to the attachment storage location if loaded from a hard drive';
COMMENT ON COLUMN ediattach."Number" IS 'Primary key component. The attachment number';
COMMENT ON COLUMN ediattach."EDIForm" IS 'Ptr to EDIFORM.EDIForm';
COMMENT ON COLUMN ediattach."Date" IS 'Date the attachment was sent to CDAnet';
COMMENT ON COLUMN ediattach."Claim" IS 'Primary key component. Ptr to CLAIM.Claim';
COMMENT ON COLUMN ediattach."Audit" IS 'Ptr to AUDITHIS.Audit';


CREATE  TABLE edielig (
  "EDIElig" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "PolIns" numeric(10,0),
  "ContentType" numeric(5,0),
  content clob,
  "FileExtension" character varying(32),
  "Audit" numeric(10,0),
  "Result" numeric(5,0),
  CONSTRAINT edielig_primary PRIMARY KEY ("EDIElig")
) ;
CREATE INDEX IF NOT EXISTS edielig_patient ON edielig USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE edielig IS 'Patient eligibility check results';
COMMENT ON COLUMN edielig.content IS 'If ContentType=0, contains HTML sent by Emdeon, if ContentType=1, contains 271 blob data';
COMMENT ON COLUMN edielig."Result" IS 'Result of eligibility check (0=Unknown, 1=Yes, 2=Rejected, 3=Eligibility Error, 4=Other error(see details))';
COMMENT ON COLUMN edielig."PolIns" IS 'Benefit plan that the check was done for, ptr to POLINS.PolIns';
COMMENT ON COLUMN edielig."Patient" IS 'Patient that the eligibility check was done for, ptr to PATIENT.Patient';
COMMENT ON COLUMN edielig."FileExtension" IS 'If ContentType=1, extension of the file contained in the blob data';
COMMENT ON COLUMN edielig."EDIElig" IS 'Primary key, internal ID from sequence';
COMMENT ON COLUMN edielig."ContentType" IS 'Type of data in the CONTENT field (0=HTML or human-readable file, 1=271 blob data)';
COMMENT ON COLUMN edielig."Audit" IS 'Ptr to AUDITHIS.Audit';


CREATE  TABLE edierr (
  "Type" numeric(5,0) NOT NULL,
  "Code" character(6) NOT NULL,
  "Description" character varying(100),
  "FrenchDesc" character varying(100),
  CONSTRAINT edierr_primary PRIMARY KEY ("Type", "Code")
) ;
COMMENT ON TABLE edierr IS 'EDI error codes for CDANet (Canada only)';
COMMENT ON COLUMN edierr."Type" IS 'EDI error type (0=CDANet, 1=Exan, 2=iTrans)';
COMMENT ON COLUMN edierr."FrenchDesc" IS 'French description of the error code.';
COMMENT ON COLUMN edierr."Description" IS 'Description of the error code. ';
COMMENT ON COLUMN edierr."Code" IS 'Error code';


CREATE  TABLE ediform (
  "EDIForm" numeric(10,0) NOT NULL,
  "FormType" numeric(5,0),
  "FormTrxCode" character(2),
  "FormStatus" character(1),
  "InsCoTrxId" numeric(10,0),
  "Claim" numeric(10,0),
  "SendAudit" numeric(10,0),
  content clob,
  "ErrorType" numeric(5,0),
  "ErrorCode" character(6),
  "Network" character(6),
  "OrigClaim" character varying(15),
  CONSTRAINT ediform_primary PRIMARY KEY ("EDIForm")
) ;
CREATE INDEX IF NOT EXISTS ediform_claimkey ON ediform USING btree ("Claim") TABLESPACE pg_default;
COMMENT ON TABLE ediform IS 'EDI Forms for CDANet (Canada only)';
COMMENT ON COLUMN ediform.content IS 'Content of "EDI" form.';
COMMENT ON COLUMN ediform."SendAudit" IS 'Audit with timestamp of when axiUm started submission for this "EDI" form. Ptr to AUDITHIS.Audit';
COMMENT ON COLUMN ediform."OrigClaim" IS 'Six digit office sequence number, used as A02';
COMMENT ON COLUMN ediform."Network" IS 'Network code, ptr to NETWORK.Network';
COMMENT ON COLUMN ediform."InsCoTrxId" IS 'Insurance company TRX# (unique for each insurance company)';
COMMENT ON COLUMN ediform."FormType" IS 'Type of "EDI" form (0=X-file [send], 1=Y-file [receive])';
COMMENT ON COLUMN ediform."FormTrxCode" IS 'Transaction code of the "EDI" form (00=V2 Eligibility request, 01=Claim, 02=Reversal, 03=Pre-determination, 04=Request pending, 05=Request summary reconcilliation, 06=Request payment reconcilliation, 08=Eligibility request, 09=Attachment, 10=V2 Eligibility response, 11=Claim response, 12=Reversal response, 13=Pre-determination response, 15=Summary reconcilliation, 16=Payment reconcilliation, 18=Eligibility response, 19=Attachment response, 21=EOB, 23=Pre-determined EOB, 31=Coordination of benefits.';
COMMENT ON COLUMN ediform."FormStatus" IS 'Status of the form (B=Batched, W=Submitted, I=In Process, R=Received, P=Printed, E=Error)';
COMMENT ON COLUMN ediform."ErrorType" IS 'EDI error type (0=CDANet, 1=Exan, 2=CDA CCD, 3=iTrans), ptr to EDIERR.Type';
COMMENT ON COLUMN ediform."ErrorCode" IS 'Error code, ptr to EDIERR.Code';
COMMENT ON COLUMN ediform."EDIForm" IS 'Primary key, internal ID from sequence';
COMMENT ON COLUMN ediform."Claim" IS 'Ptr to CLAIM.Claim';


CREATE  TABLE editaxcd (
  "NPI" character varying(10) NOT NULL,
  "Company" character(6) NOT NULL,
  "TaxonomyCode" character varying(10),
  CONSTRAINT editaxcd_pk PRIMARY KEY ("NPI", "Company")
) ;
COMMENT ON TABLE editaxcd IS 'EDI Taxonomy Code mapping table';
COMMENT ON COLUMN editaxcd."TaxonomyCode" IS 'Corresponding taxonomy code';
COMMENT ON COLUMN editaxcd."NPI" IS 'Primary key component, "NPI" number';
COMMENT ON COLUMN editaxcd."Company" IS 'Primary key component, insurance company code (blank implies for all)';


CREATE  TABLE ehracc (
  "EHRTab" numeric(5,0) NOT NULL,
  "SLevel" numeric(10,0) NOT NULL,
  "Access" numeric(5,0),
  CONSTRAINT ehracc_primary PRIMARY KEY ("EHRTab", "SLevel")
) ;
COMMENT ON TABLE ehracc IS 'EHR Tab Access';
COMMENT ON COLUMN ehracc."SLevel" IS 'Primary key component, the security level that access is being defined for. Ptr to SLEVEL.SLevel';
COMMENT ON COLUMN ehracc."EHRTab" IS 'Primary key component, the EHR tab that access is being defined for (0=Chart, 1=In Progress, 2=Tx History, 3=Forms, 4=Attachments, 5=Perio, 6=Imaging, 7=Tx Plan, 8=Labs, 9=Prescriptions, 10=Medical Tests, 11=Implants, 12=Case Management, 13=Chart Add)';
COMMENT ON COLUMN ehracc."Access" IS 'Level has access? (0=No, 1=Yes)';


CREATE  TABLE ehrcat (
  "EHRCat" numeric(10,0) NOT NULL,
  "EHROpts" numeric(10,0),
  "Type" numeric(5,0),
  "Index" numeric(5,0),
  "Category" character varying(30),
  "OpenMode" numeric(5,0),
  CONSTRAINT ehrcat_primary PRIMARY KEY ("EHRCat")
) ;
CREATE INDEX IF NOT EXISTS ehrcat_ehroptskey ON ehrcat USING btree ("EHROpts") TABLESPACE pg_default;
COMMENT ON TABLE ehrcat IS 'EHR quick list categories';
COMMENT ON COLUMN ehrcat."Type" IS 'Type? (0= Finding, 1=ADA/"CDA", 2=CPT)';
COMMENT ON COLUMN ehrcat."OpenMode" IS '0=fully expanded, 1=collapsed';
COMMENT ON COLUMN ehrcat."Index" IS 'Order in list (0=First, 1=Second ...)';
COMMENT ON COLUMN ehrcat."EHROpts" IS 'Id code of the EHR option to which this applies, copy of EHROPTS.EHROpts';
COMMENT ON COLUMN ehrcat."EHRCat" IS 'ID code to identify this record, Internal ID from sequence';
COMMENT ON COLUMN ehrcat."Category" IS 'Description of the category';


CREATE  TABLE ehrcitem (
  "EHRCItem" numeric(10,0) NOT NULL,
  "EHRCat" numeric(10,0),
  "IsHeading" numeric(5,0),
  "Parent" numeric(10,0),
  "Index" numeric(5,0),
  "Description" character varying(60),
  "Code" character(7),
  "Type" numeric(5,0),
  CONSTRAINT ehrcitem_primary PRIMARY KEY ("EHRCItem")
) ;
CREATE INDEX IF NOT EXISTS ehrcitem_ehrcatkey ON ehrcitem USING btree ("EHRCat") TABLESPACE pg_default;
COMMENT ON TABLE ehrcitem IS 'EHR quick list category items';
COMMENT ON COLUMN ehrcitem."Type" IS '0 = Procedure (PROCEDUR) , 1 = Procedure Macros (PROCMC)';
COMMENT ON COLUMN ehrcitem."Parent" IS 'Parent EHRCItem, ptr. to EHRCITEM.EHRCItem';
COMMENT ON COLUMN ehrcitem."IsHeading" IS 'Is a heading line? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ehrcitem."Index" IS 'Order in list (0=First, 1=Second ...)';
COMMENT ON COLUMN ehrcitem."EHRCat" IS 'ID code to identify this record, Internal ID from sequence';
COMMENT ON COLUMN ehrcitem."EHRCItem" IS 'ID code to identify this category item, internal ID from sequence';
COMMENT ON COLUMN ehrcitem."Description" IS 'Description of item ';
COMMENT ON COLUMN ehrcitem."Code" IS 'Procdeure code';


CREATE  TABLE ehrcolor (
  "EHROpts" numeric(10,0) NOT NULL,
  "Index" numeric(5,0) NOT NULL,
  "Color" numeric(10,0),
  CONSTRAINT ehrcolor_primary PRIMARY KEY ("EHROpts", "Index")
) ;
COMMENT ON TABLE ehrcolor IS 'table is used to determine colors for tx history rows';
COMMENT ON COLUMN ehrcolor."Index" IS 'index of tx history row type. Values: 0=planned, 1=inprocess, 2=complete, 3=condition, 4=material, 5=orthovisit, 6=appointment, 7=recall, 8=txform ';
COMMENT ON COLUMN ehrcolor."EHROpts" IS 'Points to EHROPTS row this color defn applies to';
COMMENT ON COLUMN ehrcolor."Color" IS 'Color to make the given row in the tx history (RGB value) ';


CREATE  TABLE ehrdcat (
  "EHRDCat" numeric(10,0) NOT NULL,
  "EHROpts" numeric(10,0),
  "Index" numeric(5,0),
  "Category" character varying(30),
  "OpenMode" numeric(5,0),
  CONSTRAINT ehrdcat_primary PRIMARY KEY ("EHRDCat")
) ;
COMMENT ON TABLE ehrdcat IS 'EHR Diagnosis Quick List Categories';
COMMENT ON COLUMN ehrdcat."OpenMode" IS '0=fully expanded, 1=collapsed';
COMMENT ON COLUMN ehrdcat."Index" IS 'Order in list (0=First, 1=Second ...)';
COMMENT ON COLUMN ehrdcat."EHROpts" IS 'points to EHROPTS.EHROpts';
COMMENT ON COLUMN ehrdcat."EHRDCat" IS 'Internal ID from sequence';
COMMENT ON COLUMN ehrdcat."Category" IS 'Description of the category';


CREATE  TABLE ehrditem (
  "EHRDItem" numeric(10,0) NOT NULL,
  "EHRDCat" numeric(10,0),
  "IsHeading" numeric(5,0),
  "Parent" numeric(10,0),
  "Index" numeric(5,0),
  "Description" character varying(60),
  "DiagCode" character(8),
  CONSTRAINT ehrditem_primary PRIMARY KEY ("EHRDItem")
) ;
COMMENT ON TABLE ehrditem IS 'EHR Diagnosis Quick List Items';
COMMENT ON COLUMN ehrditem."Parent" IS 'Parent EHRDItem, ptr. to EHRDITEM.EHRDItem';
COMMENT ON COLUMN ehrditem."IsHeading" IS 'Is a heading line? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ehrditem."Index" IS 'Order in list (0=First, 1=Second ...)';
COMMENT ON COLUMN ehrditem."EHRDItem" IS 'Internal ID from sequence';
COMMENT ON COLUMN ehrditem."EHRDCat" IS 'points to EHRDCAT.EHRDCat';
COMMENT ON COLUMN ehrditem."DiagCode" IS 'points to DIAGCODE.DiagCode';
COMMENT ON COLUMN ehrditem."Description" IS 'Description of the item';


CREATE  TABLE ehropts (
  "EHROpts" numeric(10,0) NOT NULL,
  "SLevel" numeric(10,0),
  "User" numeric(10,0),
  "Status" numeric(5,0),
  "Background" numeric(10,0),
  "PerioCond1" character(6),
  "PerioSection1" numeric(5,0),
  "PerioCond2" character(6),
  "PerioSection2" numeric(5,0),
  "PerioCond3" character(6),
  "PerioSection3" numeric(5,0),
  "PerioCond4" character(6),
  "PerioSection4" numeric(5,0),
  "DefaultTab" numeric(5,0),
  "DefaultMaximized" numeric(5,0),
  "ShowAlert" numeric(5,0),
  "ShowPtAlert" numeric(5,0),
  "ShowPtNeed" numeric(5,0),
  "ShowPtOffice" numeric(5,0),
  "DefaultAddTxTab" numeric(5,0),
  "DefaultTxHView" numeric(10,0),
  "DefaultForm" character(6),
  "TabOrder" character varying(128),
  "InProgressView" numeric(10,0),
  "OpenToolbars" numeric(5,0),
  "DefaultOrthoView" numeric(10,0),
  "DefaultPerioView" numeric(10,0),
  "InProgressSteps" numeric(5,0),
  "DefaultSubTab" numeric(5,0),
  "ShowMedications" numeric(5,0),
  "ShowPtSummaries" numeric(5,0),
  "UseDiagProc" numeric(5,0),
  "ShowDiagFull" numeric(5,0),
  "ShowAllergies" numeric(5,0),
  "ShowMedProb" numeric(5,0),
  "EHRisOS" numeric(5,0),
  CONSTRAINT ehropts_primary PRIMARY KEY ("EHROpts")
) ;
CREATE INDEX IF NOT EXISTS ehropts_userkey ON ehropts USING btree ("User") TABLESPACE pg_default;
COMMENT ON TABLE ehropts IS 'EHR options ';
COMMENT ON COLUMN ehropts."User" IS 'ID code of the User for this set of options, copy of USERS.User';
COMMENT ON COLUMN ehropts."UseDiagProc" IS 'Filter procedure codes by Diagnoses? (0=No, 1=Yes)';
COMMENT ON COLUMN ehropts."TabOrder" IS 'Tab order';
COMMENT ON COLUMN ehropts."Status" IS 'Number to represent the treatment statuses to display in the EHR. (1 = Completed tx, 2 = In-Process, 4= Planned, 8 = Conditions, 16 = Pre-Existing). When more than one status is checked the number will be the sum of the statuses checked.';
COMMENT ON COLUMN ehropts."ShowPtSummaries" IS '0=Hide PT Summaries, 1=Show PT Summaries';
COMMENT ON COLUMN ehropts."ShowPtOffice" IS 'Show Office Codes? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ehropts."ShowPtNeed" IS 'Show Patient Needs? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ehropts."ShowPtAlert" IS 'Show Patient Alerts? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ehropts."ShowMedications" IS 'Option to display medication in EHR | Alerts subtab or not; (0=No, 1=Yes)';
COMMENT ON COLUMN ehropts."ShowMedProb" IS 'Show Medical Problems in EHR Alerts tab (0=No, 1=Yes)';
COMMENT ON COLUMN ehropts."ShowDiagFull" IS 'Show Diagnosis Full List in EHR? (0=No, 1=Yes)';
COMMENT ON COLUMN ehropts."ShowAllergies" IS 'Show Allergies in EHR Alerts tab (0=No, 1=Yes)';
COMMENT ON COLUMN ehropts."ShowAlert" IS 'Show Medical Alerts? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ehropts."SLevel" IS 'Security level for this set of options, copy of SLEVEL.Level';
COMMENT ON COLUMN ehropts."PerioSection4" IS 'Option to display this section';
COMMENT ON COLUMN ehropts."PerioSection3" IS 'Option to display this section';
COMMENT ON COLUMN ehropts."PerioSection2" IS 'Option to display this section';
COMMENT ON COLUMN ehropts."PerioSection1" IS 'Option to display this section';
COMMENT ON COLUMN ehropts."PerioCond4" IS 'ID code of the perio condition to display ';
COMMENT ON COLUMN ehropts."PerioCond3" IS 'ID code of the perio condition to display ';
COMMENT ON COLUMN ehropts."PerioCond2" IS 'ID code of the perio condition to display ';
COMMENT ON COLUMN ehropts."PerioCond1" IS 'ID code of the perio condition to display ';
COMMENT ON COLUMN ehropts."OpenToolbars" IS 'Auto open toolbars? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ehropts."InProgressView" IS 'Id code of the patient care view to use for the In-Progress tab of the EHR ';
COMMENT ON COLUMN ehropts."InProgressSteps" IS 'determines whether to show steps or not upon startup';
COMMENT ON COLUMN ehropts."EHRisOS" IS 'Obsolete';
COMMENT ON COLUMN ehropts."EHROpts" IS 'Internal Id, from sequence ';
COMMENT ON COLUMN ehropts."DefaultTxHView" IS 'Default treatment history view, copy of TXHVIEW.TxHView';
COMMENT ON COLUMN ehropts."DefaultTab" IS 'Default Tab to display when the EHR opens (0=Chart, 1=In Progress, 2=Tx History, 3=Forms, 4=Attachments, 5=Perio, 6=Imaging, 7=Tx Plan, 8=Labs, 9=Prescriptions, 10=Medical Tests, 11=Implants, 12=Case Management, 13=Chart Add)';
COMMENT ON COLUMN ehropts."DefaultSubTab" IS '0 = System Default, 1 = Alerts, 2 = Problems, 3 = Objectives';
COMMENT ON COLUMN ehropts."DefaultPerioView" IS 'Default view to use when opening the tx history from the perio module (TXHVIEW.TxHView)';
COMMENT ON COLUMN ehropts."DefaultOrthoView" IS 'Default view to use when opening the tx history from the ortho module (TXHVIEW.TxHView)';
COMMENT ON COLUMN ehropts."DefaultMaximized" IS 'Open window maximized? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ehropts."DefaultForm" IS 'Default Form to display ';
COMMENT ON COLUMN ehropts."DefaultAddTxTab" IS 'Default sub-tab on ChartAdd (0=Codes, 1=Details)';
COMMENT ON COLUMN ehropts."Background" IS 'Background color for the Imaging Tab';


CREATE  TABLE elmah$error (
  "ERRORID" character varying(32) NOT NULL,
  "APPLICATION" character varying(60) NOT NULL,
  "HOST" character varying(30) NOT NULL,
  "TYPE" character varying(100) NOT NULL,
  "SOURCE" character varying(60),
  "MESSAGE" character varying(500) NOT NULL,
  "USERNAME" character varying(50),
  "STATUSCODE" numeric NOT NULL,
  "TIMEUTC" timestamp without time zone NOT NULL,
  "SEQUENCENUMBER" numeric NOT NULL,
  allxml clob NOT NULL,
  CONSTRAINT elmah$error_pk PRIMARY KEY ("ERRORID")
) ;
CREATE INDEX IF NOT EXISTS "idx_elmah$error_app_time_seq" ON "elmah$error" USING btree ("APPLICATION", "TIMEUTC" DESC, "SEQUENCENUMBER" DESC) TABLESPACE pg_default;
COMMENT ON TABLE "elmah$error" IS 'Doctor access error logging';
COMMENT ON COLUMN "elmah$error".allxml IS 'Additional information related to the error such as server variable values, stored in a XML format';
COMMENT ON COLUMN "elmah$error"."USERNAME" IS 'The user name returned by the error handler, if applicable';
COMMENT ON COLUMN "elmah$error"."TYPE" IS 'The application exception type';
COMMENT ON COLUMN "elmah$error"."TIMEUTC" IS 'UTC time of the error';
COMMENT ON COLUMN "elmah$error"."STATUSCODE" IS 'The HTTP status code that was returned on the response';
COMMENT ON COLUMN "elmah$error"."SOURCE" IS 'The application DLL or EXE which threw the error';
COMMENT ON COLUMN "elmah$error"."SEQUENCENUMBER" IS 'Internal ID from sequence';
COMMENT ON COLUMN "elmah$error"."MESSAGE" IS 'Description of the error';
COMMENT ON COLUMN "elmah$error"."HOST" IS 'The machine ID that the error occurred on';
COMMENT ON COLUMN "elmah$error"."ERRORID" IS 'Primary key, auto generated GUID for every entry into the table';
COMMENT ON COLUMN "elmah$error"."APPLICATION" IS 'The application that threw the error';


CREATE  TABLE emailcd (
  "EMailCd" character(6) NOT NULL,
  "Description" character varying(50),
  "Type" numeric(5,0),
  "Priority" numeric(5,0),
  "Subject" character varying(100),
  "FileName" character varying(255),
  body bytea,
  "AddNoteCode" character(6),
  "TemplateType" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT emailcd_primary PRIMARY KEY ("EMailCd")
) ;
COMMENT ON TABLE emailcd IS 'Email Template';
COMMENT ON COLUMN emailcd.body IS 'The body of the email template (Text or HTML)';
COMMENT ON COLUMN emailcd."Type" IS 'Type of email template (0=Text, 1=HTML)';
COMMENT ON COLUMN emailcd."TemplateType" IS 'Type of Template: 0 - patient general email, 1 - user general email, 2 - PA invitation email, 3 - online request email';
COMMENT ON COLUMN emailcd."Subject" IS 'Email template subject';
COMMENT ON COLUMN emailcd."Priority" IS 'Priority of the email template (0=Normal, 1=Low, 2=High)';
COMMENT ON COLUMN emailcd."FileName" IS 'Filename for HTML email templates';
COMMENT ON COLUMN emailcd."EMailCd" IS 'Primary key, code that identifies the email template';
COMMENT ON COLUMN emailcd."Description" IS 'Description of the email template';
COMMENT ON COLUMN emailcd."AddNoteCode" IS 'The note code to be added. Ptr. To NOTECODE.NoteCode';


CREATE  TABLE emailset (
  "FromAddress" character varying(255) NOT NULL,
  "FromName" character varying(255),
  "SmtpServerURL" character varying(255),
  "SmtpPort" numeric(10,0),
  "UseSSL" numeric(5,0),
  "SmtpUser" character varying(255),
  "SmtpPass" character varying(100),
  "ClientID" character varying(255),
  "ClientSecret" character varying(255),
  "TenantID" character varying(255),
  "Scope" character varying(255),
  "WebServiceURL" character varying(255),
  CONSTRAINT emailset_primary PRIMARY KEY ("FromAddress")
) ;
COMMENT ON TABLE emailset IS 'Email settings.';
COMMENT ON COLUMN emailset."WebServiceURL" IS 'OAuth Exchange web service URL.';
COMMENT ON COLUMN emailset."UseSSL" IS 'Does the server require SSL? (0=No, 1=Yes)';
COMMENT ON COLUMN emailset."TenantID" IS 'OAuth tenant ID.';
COMMENT ON COLUMN emailset."SmtpUser" IS 'The SMTP username';
COMMENT ON COLUMN emailset."SmtpServerURL" IS 'The SMTP server URL';
COMMENT ON COLUMN emailset."SmtpPort" IS 'The SMTP server port';
COMMENT ON COLUMN emailset."SmtpPass" IS 'The SMTP password (encrypted)';
COMMENT ON COLUMN emailset."Scope" IS 'OAuth Permission scope.';
COMMENT ON COLUMN emailset."FromName" IS 'The sender display name';
COMMENT ON COLUMN emailset."FromAddress" IS 'The sender email address';
COMMENT ON COLUMN emailset."ClientSecret" IS 'OAuth client secret.';
COMMENT ON COLUMN emailset."ClientID" IS 'OAuth client ID.';


CREATE  TABLE emphis (
  "Id" numeric(10,0) NOT NULL,
  "Employer" numeric(10,0),
  "Name" character(50),
  "Address1" character(30),
  "Address2" character(30),
  "City" character(24),
  "Province" character(6),
  "Postal" character(15),
  "Area" character(4),
  "Telephone" character(8),
  "Ext" character varying(6),
  "Note" character varying(4000),
  "AddressOther" character(15),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT emphis_primary PRIMARY KEY ("Id")
) ;
CREATE INDEX IF NOT EXISTS emphis_employer ON emphis USING btree ("Employer") TABLESPACE pg_default;
COMMENT ON TABLE emphis IS 'History for Employer Codes';
COMMENT ON COLUMN emphis."Telephone" IS 'Telephone number';
COMMENT ON COLUMN emphis."Province" IS 'Province / state, ptr to PROVINCE.Province';
COMMENT ON COLUMN emphis."Postal" IS 'Postal / zip code, ptr to CITY.Postal';
COMMENT ON COLUMN emphis."Note" IS 'Telephone extension';
COMMENT ON COLUMN emphis."Name" IS 'Company name';
COMMENT ON COLUMN emphis."Id" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN emphis."Ext" IS 'Telephone extension';
COMMENT ON COLUMN emphis."Employer" IS 'Employer that this history record is for, ptr to EMPLOYER.Employer.';
COMMENT ON COLUMN emphis."Deleted" IS 'Item is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN emphis."City" IS 'City, ptr to CITY.City';
COMMENT ON COLUMN emphis."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN emphis."Area" IS 'Telephone area code';
COMMENT ON COLUMN emphis."AddressOther" IS 'For USA, represents County. For Dutch, represents Room Number.';
COMMENT ON COLUMN emphis."Address2" IS 'Company address line 2';
COMMENT ON COLUMN emphis."Address1" IS 'Company address line 1';


CREATE  TABLE employer (
  "Employer" numeric(10,0) NOT NULL,
  "Name" character(50),
  "Address1" character(30),
  "Address2" character(30),
  "City" character(24),
  "Province" character(6),
  "Postal" character(15),
  "Area" character(4),
  "Telephone" character(8),
  "Ext" character varying(6),
  "Note" character varying(4000),
  "AddressOther" character(15),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT employer_primary PRIMARY KEY ("Employer")
) ;
CREATE INDEX IF NOT EXISTS employer_namekey ON employer USING btree ("Name") TABLESPACE pg_default;
COMMENT ON TABLE employer IS 'Employer Codes';
COMMENT ON COLUMN employer."Telephone" IS 'Telephone number';
COMMENT ON COLUMN employer."Province" IS 'Province / state, ptr to PROVINCE.Province';
COMMENT ON COLUMN employer."Postal" IS 'Postal / zip code, ptr to CITY.Postal';
COMMENT ON COLUMN employer."Note" IS 'Free text area to enter notes about this employer';
COMMENT ON COLUMN employer."Name" IS 'Company name';
COMMENT ON COLUMN employer."Ext" IS 'Telephone extension';
COMMENT ON COLUMN employer."Employer" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN employer."Deleted" IS 'Item is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN employer."City" IS 'City, ptr to CITY.City';
COMMENT ON COLUMN employer."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN employer."Area" IS 'Telephone area code';
COMMENT ON COLUMN employer."AddressOther" IS 'For USA, represents County. For Dutch, represents Room Number.';
COMMENT ON COLUMN employer."Address2" IS 'Company address line 2';
COMMENT ON COLUMN employer."Address1" IS 'Company address line 1';


CREATE  TABLE eobadj (
  "EOBAdj" numeric(10,0) NOT NULL,
  "EOBTSet" numeric(10,0),
  "Date" timestamp without time zone,
  "AdjReason" character(2),
  "Amount" numeric,
  "AdjStatus" numeric(5,0),
  "ReferenceId" character varying(100),
  CONSTRAINT eobadj_primary PRIMARY KEY ("EOBAdj")
) ;
CREATE INDEX IF NOT EXISTS eobadj_eobtset ON eobadj USING btree ("EOBTSet") TABLESPACE pg_default;
COMMENT ON TABLE eobadj IS 'EOB Adjustments - per payment adjustment in a PLB segment';
COMMENT ON COLUMN eobadj."ReferenceId" IS 'Optional reference ID for a payment adjustment';
COMMENT ON COLUMN eobadj."EOBTSet" IS 'Ptr to EOBTSET.EOBTSet';
COMMENT ON COLUMN eobadj."EOBAdj" IS 'Primary key, internal ID from sequence';
COMMENT ON COLUMN eobadj."Date" IS 'Date of the adjustment';
COMMENT ON COLUMN eobadj."Amount" IS 'Amount of the adjustment';
COMMENT ON COLUMN eobadj."AdjStatus" IS 'Status of the adjustment (0=Not processed, 1=Handled, 2=Unknown/Not handled)';
COMMENT ON COLUMN eobadj."AdjReason" IS 'Reason for the adjustment';


CREATE  TABLE eobamt (
  "EOBAmt" numeric(10,0) NOT NULL,
  "EOBClaim" numeric(10,0),
  "EOBClmIt" numeric(10,0),
  "Qualifier" character(2),
  "Amount" numeric,
  CONSTRAINT eobamt_primary PRIMARY KEY ("EOBAmt")
) ;
COMMENT ON TABLE eobamt IS 'EOB Amounts - per AMT in CLP/SVC segment';
COMMENT ON COLUMN eobamt."Qualifier" IS 'Amount qualifier code';
COMMENT ON COLUMN eobamt."EOBClmIt" IS 'Ptr to EOBCLAIM.EOBClmIt';
COMMENT ON COLUMN eobamt."EOBClaim" IS 'Ptr to EOBCLAIM.EOBClaim';
COMMENT ON COLUMN eobamt."EOBAmt" IS 'Primary key, internal ID from sequence';
COMMENT ON COLUMN eobamt."Amount" IS 'Amount, in dollars';


CREATE  TABLE eobcas (
  "EOBCas" numeric(10,0) NOT NULL,
  "EOBClaim" numeric(10,0),
  "EOBClmIt" numeric(10,0),
  "CASGroup" character(2),
  "CASReason" character(6),
  "Amount" numeric,
  "CasStatus" numeric(5,0),
  CONSTRAINT eobcas_primary PRIMARY KEY ("EOBCas")
) ;
CREATE INDEX IF NOT EXISTS eobcas_eobclaim ON eobcas USING btree ("EOBClaim") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS eobcas_eobclmit ON eobcas USING btree ("EOBClmIt") TABLESPACE pg_default;
COMMENT ON TABLE eobcas IS 'EOB CAS (claim adjustment) - per CAS record in a CLP/SVC segment';
COMMENT ON COLUMN eobcas."EOBClmIt" IS 'Ptr to EOBCLMIT.EOBClmIt';
COMMENT ON COLUMN eobcas."EOBClaim" IS 'Ptr to EOBCLAIM.EOBClaim';
COMMENT ON COLUMN eobcas."EOBCas" IS 'Primary key, internal ID from sequence';
COMMENT ON COLUMN eobcas."CasStatus" IS 'Internal field set after processing (0=Not Processed, 1=Handled, 2=Unknown/Not handled)';
COMMENT ON COLUMN eobcas."CASReason" IS 'CAS02 - 1034, claim adjustment reason code';
COMMENT ON COLUMN eobcas."CASGroup" IS 'CAS01 - 1033, claim adjustment group code';
COMMENT ON COLUMN eobcas."Amount" IS 'CAS03 - 782, Monetary amount of adjustment';


CREATE  TABLE eobcastx (
  "EOBCas" numeric(10,0) NOT NULL,
  "OrigRecNo" numeric(10,0),
  "ClaimCAS" numeric(10,0),
  CONSTRAINT eobcastx_primary PRIMARY KEY ("EOBCas")
) ;
CREATE INDEX IF NOT EXISTS eobcastx_claimcas ON eobcastx USING btree ("ClaimCAS") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS eobcastx_origrecno ON eobcastx USING btree ("OrigRecNo") TABLESPACE pg_default;
COMMENT ON TABLE eobcastx IS 'New Claim Adjustment Reason to TRX Adjustment Joint Table';
COMMENT ON COLUMN eobcastx."OrigRecNo" IS 'OrigRecNo of the TRX adjsutment added as part of the intelli-adjust';
COMMENT ON COLUMN eobcastx."EOBCas" IS 'EOBCas (EOB claim adjustment) Id';
COMMENT ON COLUMN eobcastx."ClaimCAS" IS 'ClaimCAS (claim adjustment) Id';


CREATE  TABLE eobclaim (
  "EOBClaim" numeric(10,0) NOT NULL,
  "EOBTSet" numeric(10,0),
  "ClaimId" character varying(38),
  "TrxType" numeric(5,0),
  "TrxId" numeric(10,0),
  "ClmStatus" numeric(5,0),
  "ErrCode" numeric(5,0),
  "ErrDesc" character varying(255),
  "ProviderId" character varying(50),
  "FacCode" character varying(2),
  "FiscYearDate" timestamp without time zone,
  "ClmCount" numeric(5,0),
  "ClmAmt" numeric,
  "MSPPayerAmt" numeric,
  "NonLabAmt" numeric,
  "HCPCSChgAmt" numeric,
  "HCPCSPayAmt" numeric,
  "TPCAmt" numeric,
  "MSPAmt" numeric,
  "PtReimbAmt" numeric,
  "PIPClmAmt" numeric,
  "PIPAdjAmt" numeric,
  "DRGAmt" numeric,
  "FedAmt" numeric,
  "HospAmt" numeric,
  "DispShareAmt" numeric,
  "CapitalAmt" numeric,
  "IndirectMedEdAmt" numeric,
  "OutlierDayCount" numeric(5,0),
  "DayOutlierAmt" numeric,
  "CostOutlierAmt" numeric,
  "AvgDRGStay" numeric(5,0),
  "DischargeCnt" numeric(5,0),
  "CostRptDayCnt" numeric(5,0),
  "CoveredDayCnt" numeric(5,0),
  "NonCoveredDayCnt" numeric(5,0),
  "MSPPassAmt" numeric,
  "AvgDRGWeight" numeric(5,0),
  "PPSCapFSPDRGAmt" numeric,
  "PPSCapHSPDRGAmt" numeric,
  "PPSDSHDRGAmt" numeric,
  "ClaimStatusCode" character varying(2),
  "ChargeAmt" numeric,
  "PmtAmt" numeric,
  "PtRespAmt" numeric,
  "ClmIndCode" character varying(2),
  "CtrlNumber" character varying(50),
  "FacilityType" character varying(2),
  "ClmFreqType" character varying(1),
  "DRGCode" character varying(4),
  "DRGWeight" character varying(15),
  "DischargeFract" character varying(10),
  "PtLastName" character varying(60),
  "PtFirstName" character varying(35),
  "PtMiddleName" character varying(25),
  "PtNameSuffix" character varying(10),
  "PtIdQual" character varying(2),
  "PtIdCode" character varying(80),
  "SubLastName" character varying(60),
  "SubFirstName" character varying(35),
  "SubMiddleName" character varying(25),
  "SubNameSuffix" character varying(10),
  "SubIdQual" character varying(2),
  "SubIdCode" character varying(80),
  "CorrLastName" character varying(60),
  "CorrFirstName" character varying(35),
  "CorrMiddleName" character varying(25),
  "CorrNameSuffix" character varying(10),
  "CorrIdCode" character varying(80),
  "ProvTypeQual" character varying(1),
  "ProvLastName" character varying(60),
  "ProvFirstName" character varying(35),
  "ProvMiddleName" character varying(25),
  "ProvNameSuffix" character varying(10),
  "ProvIdQual" character varying(2),
  "ProvIdCode" character varying(80),
  "COBName" character varying(60),
  "COBIdQual" character varying(2),
  "COBIdCode" character varying(80),
  "CorrPPName" character varying(60),
  "CorrPPIdQual" character varying(2),
  "CorrPPIdCode" character varying(80),
  "OtherSubLastName" character varying(60),
  "OtherSubFirstName" character varying(35),
  "OtherSubMiddleName" character varying(25),
  "OtherSubNameSuffix" character varying(10),
  "OtherSubQual" character varying(2),
  "OtherSubIdCode" character varying(80),
  "CoveredDaysOrVisitsCnt" numeric(5,0),
  "PPSOpOutlierAmt" numeric,
  "PsychDaysCnt" numeric(5,0),
  "ClmDRGAmt" numeric,
  "ClmPmtRemarkCode" character varying(50),
  "ClmDispShareAmt" numeric,
  "ClmMSPPassAmt" numeric,
  "ClmPPSCapAmt" numeric,
  "ClmPPSCapFSPDRGAmt" numeric,
  "ClmPPSCapHSPDRGAmt" numeric,
  "ClmPPSCapDSHDRGAmt" numeric,
  "ClmOldCapAmt" numeric,
  "ClmPPSCapIMEAmt" numeric,
  "ClmPPSHospDRGAmt" numeric,
  "ClmCostRptDayCnt" numeric(5,0),
  "ClmPPSOpFedDRGAmt" numeric,
  "ClmPPSCapOutlierAmt" numeric,
  "ClmIndTeachAmt" numeric,
  "NonpayProfAmt" numeric,
  "ClmPmtRemarkCode2" character varying(50),
  "ClmPmtRemarkCode3" character varying(50),
  "ClmPmtRemarkCode4" character varying(50),
  "ClmPmtRemarkCode5" character varying(50),
  "PPSCapExceptAmt" numeric,
  "ReimbRate" numeric,
  "ClmHCPCSPayAmt" numeric,
  "ClmPmtRemarkCode6" character varying(50),
  "ClmPmtRemarkCode7" character varying(50),
  "ClmPmtRemarkCode8" character varying(50),
  "ClmPmtRemarkCode9" character varying(50),
  "ClmPmtRemarkCode10" character varying(50),
  "ClmESRDPmtAmt" numeric,
  "NonpayProAmt" numeric,
  "ClmGroupNum" character varying(50),
  "PreAuthNum" character varying(50),
  "ClmStmtPeriodStart" timestamp without time zone,
  "ClmStmtPeriodEnd" timestamp without time zone,
  "CvgExp" timestamp without time zone,
  "ReceivedDate" timestamp without time zone,
  "ClmContactName" character varying(60),
  "CommNumQual" character varying(2),
  "CommNumber" character varying(256),
  "CommNumQual2" character varying(2),
  "CommNumber2" character varying(256),
  "CommNumQual3" character varying(2),
  "CommNumber3" character varying(256),
  CONSTRAINT eobclaim_primary PRIMARY KEY ("EOBClaim")
) ;
CREATE INDEX IF NOT EXISTS eobclaim_eobtset ON eobclaim USING btree ("EOBTSet", "ErrCode") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS eobclaim_trxtypetrxid ON eobclaim USING btree ("TrxType", "TrxId", "CtrlNumber") TABLESPACE pg_default;
COMMENT ON TABLE eobclaim IS 'EOB Claims - per CLP segment from a transaction set';
COMMENT ON COLUMN eobclaim."TrxType" IS 'Ptr to TRX.Type (5=PreAuth, 1=Claim)';
COMMENT ON COLUMN eobclaim."TrxId" IS 'Ptr to TRX.Id (if found)';
COMMENT ON COLUMN eobclaim."TPCAmt" IS '2000 TS320 - Total professional component amount';
COMMENT ON COLUMN eobclaim."SubNameSuffix" IS '2100 NM107 where NM101 is IL - Subscriber name suffix';
COMMENT ON COLUMN eobclaim."SubMiddleName" IS '2100 NM105 where NM101 is IL - Subscriber middle name';
COMMENT ON COLUMN eobclaim."SubLastName" IS '2100 NM103 where NM101 is IL - Subscriber last name';
COMMENT ON COLUMN eobclaim."SubIdQual" IS '2100 NM108 where NM101 is IL - Subscriber ID qualifier';
COMMENT ON COLUMN eobclaim."SubIdCode" IS '2100 NM109 where NM101 is IL - Subscriber ID code';
COMMENT ON COLUMN eobclaim."SubFirstName" IS '2100 NM104 where NM101 is IL - Subscriber first name';
COMMENT ON COLUMN eobclaim."ReimbRate" IS '2100 MOA01 - Reimbursement rate';
COMMENT ON COLUMN eobclaim."ReceivedDate" IS '2100 DTM02 WHERE DTM01 is 050 - Claim received date';
COMMENT ON COLUMN eobclaim."PtRespAmt" IS '2100 CLP05 - Patient responsibility amount';
COMMENT ON COLUMN eobclaim."PtReimbAmt" IS '2000 TS322 - Patient reimbursement amount';
COMMENT ON COLUMN eobclaim."PtNameSuffix" IS '2100 NM107 where NM101 is QC- Patient name suffix';
COMMENT ON COLUMN eobclaim."PtMiddleName" IS '2100 NM105 where NM101 is QC - Patient middle name';
COMMENT ON COLUMN eobclaim."PtLastName" IS '2100 NM103 where NM101 is QC - Patient last name';
COMMENT ON COLUMN eobclaim."PtIdQual" IS '2100 NM108 where NM101 is QC - Patient ID qualifier';
COMMENT ON COLUMN eobclaim."PtIdCode" IS '2100 NM109 where NM101 is QC - Patient ID code';
COMMENT ON COLUMN eobclaim."PtFirstName" IS '2100 NM104 where NM101 is QC - Patient first name';
COMMENT ON COLUMN eobclaim."PsychDaysCnt" IS '2100 MIA03 - Psychiatric days count';
COMMENT ON COLUMN eobclaim."ProviderId" IS '2000 TS301 - Provider code';
COMMENT ON COLUMN eobclaim."ProvTypeQual" IS '2100 NM102 where NM101 is 82 - Provider type qualifier';
COMMENT ON COLUMN eobclaim."ProvNameSuffix" IS '2100 NM107 where NM101 is 82 - Provider name suffix';
COMMENT ON COLUMN eobclaim."ProvMiddleName" IS '2100 NM105 where NM101 is 82 - Provider middle name';
COMMENT ON COLUMN eobclaim."ProvLastName" IS '2100 NM103 where NM101 is 82 - Provider last name';
COMMENT ON COLUMN eobclaim."ProvIdQual" IS '2100 NM108 where NM101 is 82 - Provider ID qualifier';
COMMENT ON COLUMN eobclaim."ProvIdCode" IS '2100 NM109 where NM101 is 82 - Provider ID code';
COMMENT ON COLUMN eobclaim."ProvFirstName" IS '2100 NM104 where NM101 is 82 - Provider first name';
COMMENT ON COLUMN eobclaim."PreAuthNum" IS '2100 REF02 where REF01 is G1 or G3 - Preauthorization number';
COMMENT ON COLUMN eobclaim."PmtAmt" IS '2100 CLP04 - Payment amount';
COMMENT ON COLUMN eobclaim."PPSOpOutlierAmt" IS '2100 MIA02 - Prospective Payment System operating outlier amount';
COMMENT ON COLUMN eobclaim."PPSDSHDRGAmt" IS '2000 TS219 - Prospective Payment System disproportionate share diagnosis related group amount';
COMMENT ON COLUMN eobclaim."PPSCapHSPDRGAmt" IS '2000 TS218 - Prospective Payment System Hospital Specific Portion diagnosis related group amount';
COMMENT ON COLUMN eobclaim."PPSCapFSPDRGAmt" IS '2000 TS217 - Prospective Payment System capital federal diagnosis related group amount';
COMMENT ON COLUMN eobclaim."PPSCapExceptAmt" IS '2100 MIA24 - PPS-capital exception amount';
COMMENT ON COLUMN eobclaim."PIPClmAmt" IS '2000 TS323 - Periodic Interim Payment claim amount';
COMMENT ON COLUMN eobclaim."PIPAdjAmt" IS '2000 TS324 - Periodic Interim Payment adjustment amount';
COMMENT ON COLUMN eobclaim."OutlierDayCount" IS '2000 TS207 - Outlier day count';
COMMENT ON COLUMN eobclaim."OtherSubQual" IS '2100 NM108 where NM101 is GB - Other subscriber ID qualifier';
COMMENT ON COLUMN eobclaim."OtherSubNameSuffix" IS '2100 NM107 where NM101 is GB - Other subscriber name suffix';
COMMENT ON COLUMN eobclaim."OtherSubMiddleName" IS '2100 NM105 where NM101 is GB - Other subscriber middle name';
COMMENT ON COLUMN eobclaim."OtherSubLastName" IS '2100 NM103 where NM101 is GB - Other subscriber last name';
COMMENT ON COLUMN eobclaim."OtherSubIdCode" IS '2100 NM109 where NM101 is GB - Other subscriber ID code';
COMMENT ON COLUMN eobclaim."OtherSubFirstName" IS '2100 NM104 where NM101 is GB - Other subscriber first name';
COMMENT ON COLUMN eobclaim."NonpayProfAmt" IS '2100 MIA19 - Nonpayable professional component amount';
COMMENT ON COLUMN eobclaim."NonpayProAmt" IS '2100 MOA09 - Nonpayable professional amount';
COMMENT ON COLUMN eobclaim."NonLabAmt" IS '2000 TS315 - Total non-lab charge amount';
COMMENT ON COLUMN eobclaim."NonCoveredDayCnt" IS '2000 TS214 - Non-covered days count';
COMMENT ON COLUMN eobclaim."MSPPayerAmt" IS '2000 TS313 - Medical secondary payer amount';
COMMENT ON COLUMN eobclaim."MSPPassAmt" IS '2000 TS215 - Medicare Secondary Payer pass-through amount';
COMMENT ON COLUMN eobclaim."MSPAmt" IS '2000 TS321 - Medical secondary payer amount';
COMMENT ON COLUMN eobclaim."IndirectMedEdAmt" IS '2000 TS206 - Indirect medical education amount';
COMMENT ON COLUMN eobclaim."HospAmt" IS '2000 TS203 - Hospital amount';
COMMENT ON COLUMN eobclaim."HCPCSPayAmt" IS '2000 TS318 - HCPCs payable amount';
COMMENT ON COLUMN eobclaim."HCPCSChgAmt" IS '2000 TS317 - HCPCs charge amount';
COMMENT ON COLUMN eobclaim."FiscYearDate" IS '2000 TS303 - Last day of providers fiscal year through the date of the bill.';
COMMENT ON COLUMN eobclaim."FedAmt" IS '2000 TS202 - Federal amount';
COMMENT ON COLUMN eobclaim."FacilityType" IS '2100 CLP08 - Facility type';
COMMENT ON COLUMN eobclaim."FacCode" IS '2000 TS302 - Facility code';
COMMENT ON COLUMN eobclaim."ErrDesc" IS 'Text description of the error';
COMMENT ON COLUMN eobclaim."ErrCode" IS 'Error code (0=No error, 201=Claim not found, 202=Patient not found, 203=Claim not expecting payment, 204=Patient mismatch, 205=Claim mismatch)';
COMMENT ON COLUMN eobclaim."EOBTSet" IS 'Transaction set tied to this claim, ptr to EOBTSET.EOBTSet';
COMMENT ON COLUMN eobclaim."EOBClaim" IS 'Primary key, internal ID from sequence';
COMMENT ON COLUMN eobclaim."DispShareAmt" IS '2000 TS204 - Disproportionate share amount';
COMMENT ON COLUMN eobclaim."DischargeFract" IS '2100 CLP13 - Discharge fraction';
COMMENT ON COLUMN eobclaim."DischargeCnt" IS '2000 TS211 - Discharge count';
COMMENT ON COLUMN eobclaim."DayOutlierAmt" IS '2000 TS208 - Day outlier amount';
COMMENT ON COLUMN eobclaim."DRGWeight" IS '2100 CLP12 - Diagnosis related group weight';
COMMENT ON COLUMN eobclaim."DRGCode" IS '2100 CLP11 - Diagnosis related group code';
COMMENT ON COLUMN eobclaim."DRGAmt" IS '2000 TS201 - Diagnosis related group amount';
COMMENT ON COLUMN eobclaim."CvgExp" IS '2100 DTM02 WHERE DTM01 is 036 - Coverage expiration date';
COMMENT ON COLUMN eobclaim."CtrlNumber" IS '2100 CLP07 - Control number';
COMMENT ON COLUMN eobclaim."CoveredDaysOrVisitsCnt" IS '2100 MIA01 - Covered days or visits count';
COMMENT ON COLUMN eobclaim."CoveredDayCnt" IS '2000 TS213 - Covered days count';
COMMENT ON COLUMN eobclaim."CostRptDayCnt" IS '2000 TS212 - Cost report day count';
COMMENT ON COLUMN eobclaim."CostOutlierAmt" IS '2000 TS209 - Cost outlier amount';
COMMENT ON COLUMN eobclaim."CorrPPName" IS '2100 NM103 where NM101 is PR - Corrected priority payer name';
COMMENT ON COLUMN eobclaim."CorrPPIdQual" IS '2100 NM108 where NM101 is PR - Corrected priority payer ID qualifier';
COMMENT ON COLUMN eobclaim."CorrPPIdCode" IS '2100 NM109 where NM101 is PR - Corrected priority payer ID code';
COMMENT ON COLUMN eobclaim."CorrNameSuffix" IS '2100 NM107 where NM101 is 74 -Corrected name suffix';
COMMENT ON COLUMN eobclaim."CorrMiddleName" IS '2100 NM105 where NM101 is 74 - Corrected middle name';
COMMENT ON COLUMN eobclaim."CorrLastName" IS '2100 NM103 where NM101 is 74 - Corrected last name';
COMMENT ON COLUMN eobclaim."CorrIdCode" IS '2100 NM109 where NM101 is 74 - Corrected ID code';
COMMENT ON COLUMN eobclaim."CorrFirstName" IS '2100 NM104 where NM101 is 74 - Corrected first name';
COMMENT ON COLUMN eobclaim."CommNumber3" IS '2100 PER08 - Communication number 3';
COMMENT ON COLUMN eobclaim."CommNumber2" IS '2100 PER06 - Communication number 2';
COMMENT ON COLUMN eobclaim."CommNumber" IS '2100 PER04 - Communication number';
COMMENT ON COLUMN eobclaim."CommNumQual3" IS '2100 PER07 - Communication number qualifier 3';
COMMENT ON COLUMN eobclaim."CommNumQual2" IS '2100 PER05 - Communication number qualifier 2';
COMMENT ON COLUMN eobclaim."CommNumQual" IS '2100 PER03 - Communication number qualifier';
COMMENT ON COLUMN eobclaim."ClmStmtPeriodStart" IS '2100 DTM02 WHERE DTM01 is 232 - Claim statement period start date';
COMMENT ON COLUMN eobclaim."ClmStmtPeriodEnd" IS '2100 DTM02 WHERE DTM01 is 233 - Claim statement period end date';
COMMENT ON COLUMN eobclaim."ClmStatus" IS 'Claim status (0=Not processed, 1=Paid in full, 2=Underpayment, 3=Overpayment, 4=Rejected, 5=Reversed, 6=PreAuth, 7=Forwarded)';
COMMENT ON COLUMN eobclaim."ClmPmtRemarkCode9" IS '2100 MOA06 - Claim payment remark code 9';
COMMENT ON COLUMN eobclaim."ClmPmtRemarkCode8" IS '2100 MOA05 - Claim payment remark code 8';
COMMENT ON COLUMN eobclaim."ClmPmtRemarkCode7" IS '2100 MOA04 - Claim payment remark code 7';
COMMENT ON COLUMN eobclaim."ClmPmtRemarkCode6" IS '2100 MOA03 - Claim payment remark code 6';
COMMENT ON COLUMN eobclaim."ClmPmtRemarkCode5" IS '2100 MIA23 - Claim payment remark code 5';
COMMENT ON COLUMN eobclaim."ClmPmtRemarkCode4" IS '2100 MIA22 - Claim payment remark code 4';
COMMENT ON COLUMN eobclaim."ClmPmtRemarkCode3" IS '2100 MIA21 - Claim payment remark code 3';
COMMENT ON COLUMN eobclaim."ClmPmtRemarkCode2" IS '2100 MIA20 - Claim payment remark code 2';
COMMENT ON COLUMN eobclaim."ClmPmtRemarkCode10" IS '2100 MOA07 - Claim payment remark code 10';
COMMENT ON COLUMN eobclaim."ClmPmtRemarkCode" IS '2100 MIA05 - Claim payment remark code';
COMMENT ON COLUMN eobclaim."ClmPPSOpFedDRGAmt" IS '2100 MIA16 - Claim Prospective Payer System operating federal diagnosis related group amount';
COMMENT ON COLUMN eobclaim."ClmPPSHospDRGAmt" IS '2100 MIA14 - Claim Prospective Payment System Hospital diagnosis related group amount';
COMMENT ON COLUMN eobclaim."ClmPPSCapOutlierAmt" IS '2100 MIA17 - Claim Prospective Payment System capital outlier amount ';
COMMENT ON COLUMN eobclaim."ClmPPSCapIMEAmt" IS '2100 MIA13 - Claim Prospective Payment System capital amount';
COMMENT ON COLUMN eobclaim."ClmPPSCapHSPDRGAmt" IS '2100 MIA10 - Claim Prospective Payment System capital Hospital-Specific Portion diagnosis related group amount';
COMMENT ON COLUMN eobclaim."ClmPPSCapFSPDRGAmt" IS '2100 MIA09 - Claim Prospective Payment System capital federal diagnosis related group amount';
COMMENT ON COLUMN eobclaim."ClmPPSCapDSHDRGAmt" IS '2100 MIA11 - Claim Prospective Payment System capital disproportionate share diagnosis related group amount';
COMMENT ON COLUMN eobclaim."ClmPPSCapAmt" IS '2100 MIA08 - Claim Prospective Payment System capital amount';
COMMENT ON COLUMN eobclaim."ClmOldCapAmt" IS '2100 MIA12 - Claim old capital amount';
COMMENT ON COLUMN eobclaim."ClmMSPPassAmt" IS '2100 MIA07 - Claim Medicare Secondary Payer pass-through amount';
COMMENT ON COLUMN eobclaim."ClmIndTeachAmt" IS '2100 MIA18 - Claim indirect teaching amount';
COMMENT ON COLUMN eobclaim."ClmIndCode" IS '2100 CLP06 - Claim filing indicator code';
COMMENT ON COLUMN eobclaim."ClmHCPCSPayAmt" IS '2100 MOA02 - Claim HCPCS payable amount';
COMMENT ON COLUMN eobclaim."ClmGroupNum" IS '2100 REF02 where REF01 is 1L - Claim group number';
COMMENT ON COLUMN eobclaim."ClmFreqType" IS '2100 CLP09 - Claim frequency type code';
COMMENT ON COLUMN eobclaim."ClmESRDPmtAmt" IS '2100 MOA08 - Claim End Stage Renal Disease payment amount';
COMMENT ON COLUMN eobclaim."ClmDispShareAmt" IS '2100 MIA06 - Claim disproportionate share amount';
COMMENT ON COLUMN eobclaim."ClmDRGAmt" IS '2100 MIA04 - Claim diagnosis related group amount';
COMMENT ON COLUMN eobclaim."ClmCount" IS '2000 TS304 - Total number of claims in this transaction';
COMMENT ON COLUMN eobclaim."ClmCostRptDayCnt" IS '2100 MIA15 - Claim Cost report day count';
COMMENT ON COLUMN eobclaim."ClmContactName" IS '2100 PER02 - Claim contact name';
COMMENT ON COLUMN eobclaim."ClmAmt" IS '2000 TS305 - Sum of all charges included in this claim';
COMMENT ON COLUMN eobclaim."ClaimStatusCode" IS '2100 CLP02 - Claim status code';
COMMENT ON COLUMN eobclaim."ClaimId" IS 'Claim ID';
COMMENT ON COLUMN eobclaim."ChargeAmt" IS '2100 CLP03 - Charge amount';
COMMENT ON COLUMN eobclaim."CapitalAmt" IS '2000 TS205 - Capital amount';
COMMENT ON COLUMN eobclaim."COBName" IS '2100 NM103 where NM101 is TT - Coordination of benefits carrier name';
COMMENT ON COLUMN eobclaim."COBIdQual" IS '2100 NM108 where NM101 is TT - Coordination of benefits ID qualifier';
COMMENT ON COLUMN eobclaim."COBIdCode" IS '2100 NM109 where NM101 is TT - Coordination of benefits ID code';
COMMENT ON COLUMN eobclaim."AvgDRGWeight" IS '2000 TS216 - Average diagnosis related group weight';
COMMENT ON COLUMN eobclaim."AvgDRGStay" IS '2000 TS210 - Average diagnosis related group length of stay';


CREATE  TABLE eobclmit (
  "EOBClmIt" numeric(10,0) NOT NULL,
  "EOBClaim" numeric(10,0),
  "TrxType" numeric(5,0),
  "OrigRecNo" numeric(10,0),
  "EOBType" numeric(5,0),
  "ProcessType" numeric(5,0),
  "ErrCode" numeric(5,0),
  "ErrDesc" character varying(255),
  "ServiceIdQual" character varying(2),
  "ServiceId" character varying(48),
  "ProcMod" character varying(2),
  "ProcMod2" character varying(2),
  "ProcMod3" character varying(2),
  "ProcMod4" character varying(2),
  "LineItmChrgAmt" numeric,
  "LineItmPmtAmt" numeric,
  "NUBCRevCode" character varying(48),
  "UnitsSvcPaidCnt" numeric(5,0),
  "ServiceIdQual2" character varying(2),
  "ServiceId2" character varying(48),
  "Proc2Mod" character varying(2),
  "Proc2Mod2" character varying(2),
  "Proc2Mod3" character varying(2),
  "Proc2Mod4" character varying(2),
  "ProcDesc" character varying(80),
  "OrigUnitsSvcCnt" numeric(5,0),
  "DateStart" timestamp without time zone,
  "DateEnd" timestamp without time zone,
  "LocationNum" character varying(50),
  "LineItemCtrl" character varying(50),
  "PolicyFormId" character varying(50),
  CONSTRAINT eobclmit_primary PRIMARY KEY ("EOBClmIt")
) ;
CREATE INDEX IF NOT EXISTS eobclmit_eobclaim ON eobclmit USING btree ("EOBClaim", "ErrCode") TABLESPACE pg_default;
COMMENT ON TABLE eobclmit IS 'EOB Claim Items - per SVC segment in a CLP segment';
COMMENT ON COLUMN eobclmit."UnitsSvcPaidCnt" IS '2110 SVC05 - Paid units of service count';
COMMENT ON COLUMN eobclmit."TrxType" IS 'Ptr to TRX.Type (5=PreAuth, 1=Claim)';
COMMENT ON COLUMN eobclmit."ServiceIdQual2" IS '2110 SVC06 - 1 - Service ID qualifier 2';
COMMENT ON COLUMN eobclmit."ServiceIdQual" IS '2110 SVC01 - 1 - Service ID qualifier';
COMMENT ON COLUMN eobclmit."ServiceId2" IS '2110 SVC06 - 2 - Service ID 2';
COMMENT ON COLUMN eobclmit."ServiceId" IS '2110 SVC01 - 2 - Service ID';
COMMENT ON COLUMN eobclmit."ProcessType" IS 'Processing result type (0=N/A, 1=Paid as expected, 2=Underpayment w/ balance, 3=Underpayment w/ writeoff, 4=Underpayment w/ TSF, 5=Underpayment rebilled, 6=Overpayment w/ balance, 7=Overpayment w/ writeoff, 8=Overpayment w/ TSF, 9=Overpayment rebilled, 10=Paid w/ $0 Balance (Intelli-Adj), 11=Paid w/ DB Balance (Intelli-Adj), 12=Paid w/ CR Balance (Intelli-Adj), 13=Rejected w/ $0 Balance (Intelli-Adj), 14=Rejected w/ Pt Balance (Intelli-Adj), 15=Bundled/Unbundled Tx, 16=Rejected, 17=Reversed, 18=PreAuth Tx, 19=Forwarded Tx)';
COMMENT ON COLUMN eobclmit."ProcMod4" IS '2110 SVC01 - 6 - Procedure Modifier 4-1';
COMMENT ON COLUMN eobclmit."ProcMod3" IS '2110 SVC01 - 5 - Procedure Modifier 1-3';
COMMENT ON COLUMN eobclmit."ProcMod2" IS '2110 SVC01 - 4 - Procedure Modifier 1-2';
COMMENT ON COLUMN eobclmit."ProcMod" IS '2110 SVC01 - 3 - Procedure Modifier 1-1';
COMMENT ON COLUMN eobclmit."ProcDesc" IS '2110 SVC06 - 7 - Procedure description';
COMMENT ON COLUMN eobclmit."Proc2Mod4" IS '2110 SVC06 - 6 - Procedure Modifier 2-4';
COMMENT ON COLUMN eobclmit."Proc2Mod3" IS '2110 SVC06 - 5 - Procedure Modifier 2-3';
COMMENT ON COLUMN eobclmit."Proc2Mod2" IS '2110 SVC06 - 4 - Procedure Modifier 2-2';
COMMENT ON COLUMN eobclmit."Proc2Mod" IS '2110 SVC06 - 3 - Procedure Modifier 2-1';
COMMENT ON COLUMN eobclmit."PolicyFormId" IS '2110 REF02 where REF01 is 0K - Policy form ID';
COMMENT ON COLUMN eobclmit."OrigUnitsSvcCnt" IS '2110 SVC07 - Original paid units of service count';
COMMENT ON COLUMN eobclmit."OrigRecNo" IS 'Ptr to TRX.OrigRecNo (if found)';
COMMENT ON COLUMN eobclmit."NUBCRevCode" IS '2110 SVC04 - National Uniform Billing Committee Revenue Code';
COMMENT ON COLUMN eobclmit."LocationNum" IS '2110 REF02 where REF01 is LU - Location number';
COMMENT ON COLUMN eobclmit."LineItmPmtAmt" IS '2110 SVC03 - Line item payment amount';
COMMENT ON COLUMN eobclmit."LineItmChrgAmt" IS '2110 SVC02 - Line item charge amount';
COMMENT ON COLUMN eobclmit."LineItemCtrl" IS '2110 REF02 where REF01 is 6R - Line item control';
COMMENT ON COLUMN eobclmit."ErrDesc" IS 'Text description of error';
COMMENT ON COLUMN eobclmit."ErrCode" IS 'Error code (0=No error, 301=Tx not found, 302=Tx not expecting payment, 303=Tx ID mismatch, 304=Tx code mismatch, 305=Record type not handled, 306=Run of funds to allocate, 307=Cannot rebill)';
COMMENT ON COLUMN eobclmit."EOBType" IS 'EOB type (0=N/A, 1=Paid in full, 2=Underpayment, 3=Overpayment, 4=Rejection, 5=Reversal, 6=PreAuth, 7=Forwarded)';
COMMENT ON COLUMN eobclmit."EOBClmIt" IS 'Primary key, internal ID from sequence';
COMMENT ON COLUMN eobclmit."EOBClaim" IS 'Ptr to EOBCLAIM.EOBClaim';
COMMENT ON COLUMN eobclmit."DateStart" IS '2110 DTM02 where DTM01 is 150 or 472 - Start date';
COMMENT ON COLUMN eobclmit."DateEnd" IS '2110 DTM02 where DTM01 is 151 or 472 - End date';


CREATE  TABLE eobfile (
  "EOBFile" numeric(10,0) NOT NULL,
  "EOBDate" timestamp without time zone,
  "FileName" character varying(255),
  content bytea,
  "Audit" numeric(10,0),
  "FileType" character varying(10),
  CONSTRAINT eobfile_primary PRIMARY KEY ("EOBFile")
) ;
COMMENT ON TABLE eobfile IS 'EOB Remittance Files - per EOB remittance from clearing house';
COMMENT ON COLUMN eobfile.content IS 'Data contained in the remittance file';
COMMENT ON COLUMN eobfile."FileType" IS 'File type';
COMMENT ON COLUMN eobfile."FileName" IS 'Name of the remittance file';
COMMENT ON COLUMN eobfile."EOBFile" IS 'Primary key, internal ID from sequence';
COMMENT ON COLUMN eobfile."EOBDate" IS 'Date of the remittance';
COMMENT ON COLUMN eobfile."Audit" IS 'Last audit, ptr to AUDITHIS.Audit';


CREATE  TABLE eobopt (
  "PayeeIdCode" character(15) NOT NULL,
  "EDIPmtCode" character(6),
  "EDIEFTCode" character(6),
  "EDIUnderPayMode" numeric(5,0),
  "EDIOverPayMode" numeric(5,0),
  "DefaultDBAdjust" character(6),
  "DefaultCRAdjust" character(6),
  CONSTRAINT eobopt_primary PRIMARY KEY ("PayeeIdCode")
) ;
COMMENT ON TABLE eobopt IS 'EOB "EDI" remittance parameters override by Payee Code';
COMMENT ON COLUMN eobopt."PayeeIdCode" IS 'Primary key, internal ID from sequence';
COMMENT ON COLUMN eobopt."EDIUnderPayMode" IS 'Payment process for underpayment (0 = Leave it, 1 = Change Tx to match, 2 = Adjust (based on Ins))';
COMMENT ON COLUMN eobopt."EDIPmtCode" IS 'Payment code for regular payment';
COMMENT ON COLUMN eobopt."EDIOverPayMode" IS 'Payment process for overpayment (0 = Leave it, 1 = Change Tx to match, 2 = Adjust (based on Ins))';
COMMENT ON COLUMN eobopt."EDIEFTCode" IS 'Payment code for electronic fund transfer';
COMMENT ON COLUMN eobopt."DefaultDBAdjust" IS 'Adjustment code for debit type ins payment adjustment';
COMMENT ON COLUMN eobopt."DefaultCRAdjust" IS 'Adjustment code for credit type ins payment adjustment';


CREATE  TABLE eobqty (
  "EOBQty" numeric(10,0) NOT NULL,
  "EOBClaim" numeric(10,0),
  "EOBClmIt" numeric(10,0),
  "Qualifier" character(2),
  "Quantity" numeric,
  CONSTRAINT eobqty_primary PRIMARY KEY ("EOBQty")
) ;
COMMENT ON TABLE eobqty IS 'EOB Quantities - per QTY from CLP/SVC segment';
COMMENT ON COLUMN eobqty."Quantity" IS 'Quantity';
COMMENT ON COLUMN eobqty."Qualifier" IS 'Qualifier code';
COMMENT ON COLUMN eobqty."EOBQty" IS 'Primary key, internal ID from sequence';
COMMENT ON COLUMN eobqty."EOBClmIt" IS 'Ptr to EOBClmIt.EOBClmIt';
COMMENT ON COLUMN eobqty."EOBClaim" IS 'Ptr to EOBClmIt.EOBClaim';


CREATE  TABLE eobrem (
  "EOBRem" numeric(10,0) NOT NULL,
  "EOBClmIt" numeric(10,0),
  "RARemark" character(6),
  CONSTRAINT eobrem_primary PRIMARY KEY ("EOBRem")
) ;
CREATE INDEX IF NOT EXISTS eobrem_eobclmit ON eobrem USING btree ("EOBClmIt") TABLESPACE pg_default;
COMMENT ON TABLE eobrem IS 'EOB Claim Item Remarks - per remark in a SVC segment';
COMMENT ON COLUMN eobrem."RARemark" IS 'Ptr to RAREMARK.RARemark';
COMMENT ON COLUMN eobrem."EOBRem" IS 'Primary key, internal ID from sequence';
COMMENT ON COLUMN eobrem."EOBClmIt" IS 'Ptr to EOBClmIt.EOBClmIt';


CREATE  TABLE eobtset (
  "EOBTSet" numeric(10,0) NOT NULL,
  "EOBFile" numeric(10,0),
  "TraceNumber" character varying(50),
  "Insurance" character(6),
  "Doctor" character(10),
  "PmtDate" timestamp without time zone,
  "ProductionDate" timestamp without time zone,
  "NumPreAuth" numeric(10,0),
  "NumClaim" numeric(10,0),
  "NumAdjust" numeric(10,0),
  "PmtTotal" numeric,
  "TSetStatus" numeric(5,0),
  "ErrCode" numeric(5,0),
  "ErrDesc" character varying(255),
  "EOBDate" timestamp without time zone,
  "TrxPmtId" numeric(10,0),
  "Audit" numeric(10,0),
  "TSetHCode" character varying(2),
  "TSetCrDbFlag" character(1),
  "PmtMethod" character varying(3),
  "PmtFormatCode" character varying(10),
  "SenderDFIQual" character varying(2),
  "SenderDFINum" character varying(12),
  "SenderAccQual" character varying(2),
  "SenderAccNum" character varying(35),
  "SenderPayerId" character varying(10),
  "SenderSuppCode" character varying(9),
  "ReceiverDFIQual" character varying(2),
  "ReceiverDFINum" character varying(12),
  "ReceiverAccQual" character varying(2),
  "ReceiverAccNum" character varying(35),
  "TRNPayerId" character varying(10),
  "TRNReceiverId" character varying(50),
  "TRNVersionId" character varying(50),
  "PayerIdName" character varying(60),
  "PayerIdCode" character varying(80),
  "PayerAddress1" character varying(55),
  "PayerAddress2" character varying(55),
  "PayerCity" character varying(30),
  "PayerState" character varying(2),
  "PayerZip" character varying(15),
  "PayerCountry" character varying(3),
  "PayerIdNum" character varying(50),
  "PayerSubmitIdNum" character varying(50),
  "PayerHIN" character varying(50),
  "PayerNAIC" character varying(50),
  "PayerOfficeName" character varying(60),
  "PayerOfficeType" character varying(2),
  "PayerOfficeNumber" character varying(256),
  "PayerOfficeType2" character varying(2),
  "PayerOfficeNumber2" character varying(256),
  "PayerOfficeType3" character varying(2),
  "PayerOfficeNumber3" character varying(256),
  "PayerTechName" character varying(60),
  "PayerTechType" character varying(2),
  "PayerTechNumber" character varying(256),
  "PayerTechType2" character varying(2),
  "PayerTechNumber2" character varying(256),
  "PayerTechType3" character varying(2),
  "PayerTechNumber3" character varying(256),
  "PayerWebsite" character varying(256),
  "PayeeIdName" character varying(60),
  "PayeeIdQual" character varying(2),
  "PayeeIdCode" character varying(80),
  "PayeeAddress1" character varying(55),
  "PayeeAddress2" character varying(55),
  "PayeeCity" character varying(30),
  "PayeeState" character varying(2),
  "PayeePostal" character varying(15),
  "PayeeCountry" character varying(3),
  "PayeeStateLN" character varying(50),
  "PayeeNCPDPPN" character varying(50),
  "PayeeId" character varying(50),
  "PayeeTaxId" character varying(50),
  "TransmCode" character varying(2),
  "RDMName" character varying(60),
  "RDMNumber" character varying(256),
  CONSTRAINT eobtset_primary PRIMARY KEY ("EOBTSet")
) ;
CREATE INDEX IF NOT EXISTS eobtset_eobdate ON eobtset USING btree ("EOBDate") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS eobtset_eobfile ON eobtset USING btree ("EOBFile") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS eobtset_pmtdate ON eobtset USING btree ("PmtDate") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS eobtset_trxpmtid ON eobtset USING btree ("TrxPmtId") TABLESPACE pg_default;
COMMENT ON TABLE eobtset IS 'EOB Transaction Set - per ST/SE segment from a payor within EOB';
COMMENT ON COLUMN eobtset."TrxPmtId" IS 'Transaction payment ID, ptr to TRX.Id';
COMMENT ON COLUMN eobtset."TransmCode" IS '1000B RDM01 - Transmission code';
COMMENT ON COLUMN eobtset."TraceNumber" IS 'TRN02 - Unique trace number';
COMMENT ON COLUMN eobtset."TSetStatus" IS 'Transaction set status (0=Not processed, 1=Processed, 2=Processing, 3=Manually processed, 4=Deleted)';
COMMENT ON COLUMN eobtset."TSetHCode" IS 'BPR01 - Transaction handling code';
COMMENT ON COLUMN eobtset."TSetCrDbFlag" IS 'BPR03 - Transaction set credit/debit flag';
COMMENT ON COLUMN eobtset."TRNVersionId" IS 'REF02 with REF01=F2 - Trace version ID';
COMMENT ON COLUMN eobtset."TRNReceiverId" IS 'REF02 with REF01=EV - Trace receiver ID';
COMMENT ON COLUMN eobtset."TRNPayerId" IS 'TRN03 - Trace payer ID';
COMMENT ON COLUMN eobtset."SenderSuppCode" IS 'BPR11 - Sender supplemental code';
COMMENT ON COLUMN eobtset."SenderPayerId" IS 'BPR10 - Sender Payer ID';
COMMENT ON COLUMN eobtset."SenderDFIQual" IS 'BPR06 - Sender Depository Financial Institution qualifier';
COMMENT ON COLUMN eobtset."SenderDFINum" IS 'BPR07 - Sender Depository Financial Institution number';
COMMENT ON COLUMN eobtset."SenderAccQual" IS 'BPR08 - Sender account number qualifier';
COMMENT ON COLUMN eobtset."SenderAccNum" IS 'BPR09 - Sender account number';
COMMENT ON COLUMN eobtset."ReceiverDFIQual" IS 'BPR12 - Receiver Depository Financial Institution qualifier';
COMMENT ON COLUMN eobtset."ReceiverDFINum" IS 'BPR13 - Receiver Depository Financial Institution number';
COMMENT ON COLUMN eobtset."ReceiverAccQual" IS 'BPR14 - Receiver account number qualifier';
COMMENT ON COLUMN eobtset."ReceiverAccNum" IS 'BPR15 - Receiver account number';
COMMENT ON COLUMN eobtset."RDMNumber" IS '1000B RDM03 - Remittance delivery method number';
COMMENT ON COLUMN eobtset."RDMName" IS '1000B RDM02 - Remittance delivery method name';
COMMENT ON COLUMN eobtset."ProductionDate" IS 'OTM production date';
COMMENT ON COLUMN eobtset."PmtTotal" IS 'BPR02 - Payment total amount';
COMMENT ON COLUMN eobtset."PmtMethod" IS 'BPR04 - Payment method';
COMMENT ON COLUMN eobtset."PmtFormatCode" IS 'BPR05 - Payment format code';
COMMENT ON COLUMN eobtset."PmtDate" IS 'BRP16 - Date of the payment';
COMMENT ON COLUMN eobtset."PayerZip" IS '1000A N4, N403 - Payer ZIP code';
COMMENT ON COLUMN eobtset."PayerWebsite" IS '1000A PER04 where PER01 is IC - Payer website URL';
COMMENT ON COLUMN eobtset."PayerTechType3" IS '1000A PER07 where PER01 is BL - Payer technical contact type 3';
COMMENT ON COLUMN eobtset."PayerTechType2" IS '1000A PER05 where PER01 is BL - Payer technical contact type 2';
COMMENT ON COLUMN eobtset."PayerTechType" IS '1000A PER03 where PER01 is BL - Payer technical contact type';
COMMENT ON COLUMN eobtset."PayerTechNumber3" IS '1000A PER08 where PER01 is BL - Payer technical contact number 3';
COMMENT ON COLUMN eobtset."PayerTechNumber2" IS '1000A PER06 where PER01 is BL - Payer technical contact number 2';
COMMENT ON COLUMN eobtset."PayerTechNumber" IS '1000A PER04 where PER01 is BL - Payer technical contact number';
COMMENT ON COLUMN eobtset."PayerTechName" IS '1000A PER02 where PER01 is BL - Payer technical contact name';
COMMENT ON COLUMN eobtset."PayerSubmitIdNum" IS '1000A REF02 where REF01 is EO - Payer submission ID number';
COMMENT ON COLUMN eobtset."PayerState" IS '1000A N4, N402 - Payer state';
COMMENT ON COLUMN eobtset."PayerOfficeType3" IS '1000A PER07 where PER01 is CX - Payer office type 3';
COMMENT ON COLUMN eobtset."PayerOfficeType2" IS '1000A PER05 where PER01 is CX - Payer office type 2';
COMMENT ON COLUMN eobtset."PayerOfficeType" IS '1000A PER03 where PER01 is CX - Payer office type';
COMMENT ON COLUMN eobtset."PayerOfficeNumber3" IS '1000A PER08 where PER01 is CX - Payer office number 3';
COMMENT ON COLUMN eobtset."PayerOfficeNumber2" IS '1000A PER06 where PER01 is CX - Payer office number 2';
COMMENT ON COLUMN eobtset."PayerOfficeNumber" IS '1000A PER04 where PER01 is CX - Payer office number';
COMMENT ON COLUMN eobtset."PayerOfficeName" IS '1000A PER02 where PER01 is CX - - Payer office name';
COMMENT ON COLUMN eobtset."PayerNAIC" IS '1000A REF02 where REF01 is NF - Payer National Association of Insurance Commissioners code (NAIC)';
COMMENT ON COLUMN eobtset."PayerIdNum" IS '1000A REF02 where REF01 is 2U - Payer ID number';
COMMENT ON COLUMN eobtset."PayerIdName" IS '1000A N1, N102 - Payer ID name';
COMMENT ON COLUMN eobtset."PayerIdCode" IS '1000A N1, N104 - Payer ID code';
COMMENT ON COLUMN eobtset."PayerHIN" IS '1000A REF02 where REF01 is HI - Payer Health Industry Number (HIN)';
COMMENT ON COLUMN eobtset."PayerCountry" IS '1000A N4, N404 - Payer country';
COMMENT ON COLUMN eobtset."PayerCity" IS '1000A N4, N401 - Payer city';
COMMENT ON COLUMN eobtset."PayerAddress2" IS '1000A N3, N302 - Payer address line 2';
COMMENT ON COLUMN eobtset."PayerAddress1" IS '1000A N3, N301 - Payer address line 1';
COMMENT ON COLUMN eobtset."PayeeTaxId" IS '1000B REF02 where REF01 is TJ - Payee tax ID';
COMMENT ON COLUMN eobtset."PayeeStateLN" IS '1000B REF02 where REF01 is 0B - Payee state license number';
COMMENT ON COLUMN eobtset."PayeeState" IS '1000B N402 - Payee state';
COMMENT ON COLUMN eobtset."PayeePostal" IS '1000B N403 - Payee ZIP code';
COMMENT ON COLUMN eobtset."PayeeNCPDPPN" IS '1000B REF02 where REF01 is D3 - Payee National Council for Prescription Drug Programs Pharmacy Number (NCPDPPN)';
COMMENT ON COLUMN eobtset."PayeeIdQual" IS '1000B N1, N103 - Payee ID qualifier';
COMMENT ON COLUMN eobtset."PayeeIdName" IS '1000B N1, N102 - Payee ID name';
COMMENT ON COLUMN eobtset."PayeeIdCode" IS '1000B N1, N104 - Payee ID code';
COMMENT ON COLUMN eobtset."PayeeId" IS '1000B REF02 where REF01 is PQ - Payee ID';
COMMENT ON COLUMN eobtset."PayeeCountry" IS '1000B N404 - Payee country';
COMMENT ON COLUMN eobtset."PayeeCity" IS '1000B N401 - Payee city';
COMMENT ON COLUMN eobtset."PayeeAddress2" IS '1000B N3, N302 - Payee address line 2';
COMMENT ON COLUMN eobtset."PayeeAddress1" IS '1000B N3, N301 - Payee address line 1';
COMMENT ON COLUMN eobtset."NumPreAuth" IS 'Number of pre-auths';
COMMENT ON COLUMN eobtset."NumClaim" IS 'Number of claims';
COMMENT ON COLUMN eobtset."NumAdjust" IS 'Number of adjustments';
COMMENT ON COLUMN eobtset."Insurance" IS 'The insurance company payor, ptr to INSURANC.Insurance';
COMMENT ON COLUMN eobtset."ErrDesc" IS 'Text description of the error';
COMMENT ON COLUMN eobtset."ErrCode" IS 'Error code (0=No error, 101=Payment code not setup, 102=Payment bank code not setup, 103=Adjustment code not setup, 104=Adjustment code has wrong CR/DB type, 105=Insurance not found, 106=Insurance adjustment code not setup, 107=Invalid transaction type, 108=Remittance payment not found, 109=Remittance payment already exists)';
COMMENT ON COLUMN eobtset."EOBTSet" IS 'Primary key, internal ID from sequence';
COMMENT ON COLUMN eobtset."EOBFile" IS 'EOB remittance file, Ptr to EOBFILE.EOBFile';
COMMENT ON COLUMN eobtset."EOBDate" IS 'Processing date of the EOB';
COMMENT ON COLUMN eobtset."Doctor" IS 'The doctor payee, ptr to PRODUCER.Producer';
COMMENT ON COLUMN eobtset."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE epbatch (
  "EPBatch" numeric(10,0) NOT NULL,
  "TransRefNo" character varying(255),
  "Bank" character(6),
  "AcctId" character varying(255),
  "OpenDate" timestamp without time zone,
  "OpenBalance" numeric,
  "CloseAvailBalance" numeric,
  "PatientPaidTotal" numeric,
  "Status" numeric(5,0),
  mt940content clob,
  "PmtFileName" character varying(255),
  "LoadAudit" numeric(10,0),
  "ProcessAudit" numeric(10,0),
  "LBPayer" character(6),
  CONSTRAINT epbatch_primary PRIMARY KEY ("EPBatch")
) ;
COMMENT ON TABLE epbatch IS 'Stores 940/Lockbox payment file information';
COMMENT ON COLUMN epbatch.mt940content IS 'Full content of the 940 payment file';
COMMENT ON COLUMN epbatch."TransRefNo" IS 'Transaction reference number provided by the bank';
COMMENT ON COLUMN epbatch."Status" IS 'Load status (0=Loaded, 1=Processed)';
COMMENT ON COLUMN epbatch."ProcessAudit" IS 'Audit history when processed, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN epbatch."PmtFileName" IS 'Filename of the 940 payment file';
COMMENT ON COLUMN epbatch."PatientPaidTotal" IS 'Total patient paid amount';
COMMENT ON COLUMN epbatch."OpenDate" IS 'Open balance date';
COMMENT ON COLUMN epbatch."OpenBalance" IS 'Open balance as of open date';
COMMENT ON COLUMN epbatch."LoadAudit" IS 'Audit history when loading, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN epbatch."LBPayer" IS 'ptr to LBPAYER.LBPayer';
COMMENT ON COLUMN epbatch."EPBatch" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN epbatch."CloseAvailBalance" IS 'Balance on closing';
COMMENT ON COLUMN epbatch."Bank" IS 'Bank code, ptr. to BANK.Code';
COMMENT ON COLUMN epbatch."AcctId" IS 'Bank account number';


CREATE  TABLE epbitem (
  "EPBItem" numeric(10,0) NOT NULL,
  "EPBatch" numeric(10,0),
  "PInvoice" numeric(10,0),
  "ValueDate" timestamp without time zone,
  "EntryDate" character(5),
  "DCMark" character(2),
  "FundsCode" character(1),
  "Amount" numeric,
  "TransTypeId" character(1),
  "TransTypeCode" character varying(255),
  "CustomerRef" character varying(255),
  "BankRef" character varying(255),
  "Details" character varying(255),
  "ProcessType" numeric(5,0),
  "ErrCode" numeric(5,0),
  "CustomerBankAccount" character varying(10),
  CONSTRAINT epbitem_primary PRIMARY KEY ("EPBItem")
) ;
CREATE INDEX IF NOT EXISTS epbitem_epbatch ON epbitem USING btree ("EPBatch") TABLESPACE pg_default;
COMMENT ON TABLE epbitem IS 'Stores 940/Lockbox payment item information';
COMMENT ON COLUMN epbitem."ValueDate" IS 'Date of transaction';
COMMENT ON COLUMN epbitem."TransTypeId" IS 'Transaction type Id';
COMMENT ON COLUMN epbitem."TransTypeCode" IS 'Transaction type Code';
COMMENT ON COLUMN epbitem."ProcessType" IS 'Process Type (0=Not applicable, 1=Paid as expected, 2=Under payment with balance, 6=Over payment with balance)';
COMMENT ON COLUMN epbitem."PInvoice" IS 'Invoice Id, ptr. to PINVOICE.PInvoice';
COMMENT ON COLUMN epbitem."FundsCode" IS '3rd Character of the currency code (May not be required)';
COMMENT ON COLUMN epbitem."ErrCode" IS 'Error code (10=Record not found, 11=Not applicable, 201=Claim not found, 202=Patient not found, 305=Record type not handled)';
COMMENT ON COLUMN epbitem."EntryDate" IS 'Date of payment entry by patient';
COMMENT ON COLUMN epbitem."EPBatch" IS 'Payment file Id this item belongs to, ptr. to EPBATCH.EPBatch';
COMMENT ON COLUMN epbitem."EPBItem" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN epbitem."Details" IS 'Supplementary details';
COMMENT ON COLUMN epbitem."DCMark" IS 'Debit/Credit (D=Debit, C=Credit, RD=Reversal of Debit, RC=Reversal of Credit)';
COMMENT ON COLUMN epbitem."CustomerRef" IS 'Invoice number found in PINVOICE';
COMMENT ON COLUMN epbitem."CustomerBankAccount" IS 'Patient bank account number';
COMMENT ON COLUMN epbitem."BankRef" IS 'Bank reference number for this line payment';
COMMENT ON COLUMN epbitem."Amount" IS 'Payment amount';


CREATE  TABLE epbitinf (
  "EPBItem" numeric(10,0),
  "Information" character varying(65),
  "Order" numeric(5,0)
) ;
COMMENT ON TABLE epbitinf IS 'Stores parsed segment lines';
COMMENT ON COLUMN epbitinf."Order" IS 'The Order the given record are in te bank payment file (Primarily for InfoMgr to sort them) ';
COMMENT ON COLUMN epbitinf."Information" IS 'Additional Information pertaining to the bank payment (including the Customer Bank Acct#)';
COMMENT ON COLUMN epbitinf."EPBItem" IS 'Ptr. To EPBITEM.EPBItem';


CREATE  TABLE epreview (
  "EPReview" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "Type" numeric(5,0),
  "ReviewDate" timestamp without time zone,
  "ReviewUser" numeric(10,0),
  "HasRecords" numeric(5,0),
  "Content" character varying(4000),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "DeleteAudit" numeric(10,0),
  CONSTRAINT epreview_primary PRIMARY KEY ("EPReview")
) ;
CREATE INDEX IF NOT EXISTS epreview_patient ON epreview USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE epreview IS 'Patient EPR Information Reviews';
COMMENT ON COLUMN epreview."Type" IS 'Type of EPR information reviewed (0=Medications, 1=Allergies, 2=Problems)';
COMMENT ON COLUMN epreview."ReviewUser" IS 'User who performed the review. Ptr to USERS.User';
COMMENT ON COLUMN epreview."ReviewDate" IS 'Date/time of review.';
COMMENT ON COLUMN epreview."Patient" IS 'Patient being reviewed, ptr to PATIENT.Patient';
COMMENT ON COLUMN epreview."HasRecords" IS 'Has records? (0=No, 1=Yes)';
COMMENT ON COLUMN epreview."EPReview" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN epreview."Deleted" IS 'Deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN epreview."DeleteAudit" IS 'If Deleted=1, audit history of deletion. Ptr to AUDITHIS.Audit';
COMMENT ON COLUMN epreview."Content" IS 'Summarized view of content being reviewed. ';
COMMENT ON COLUMN epreview."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE eprimg (
  "EPRImg" character(6) NOT NULL,
  "Description" character varying(30),
  image bytea,
  "Inactive" numeric(5,0),
  CONSTRAINT eprimg_primary PRIMARY KEY ("EPRImg")
) ;
COMMENT ON TABLE eprimg IS 'EPR Image Templates';
COMMENT ON COLUMN eprimg.image IS 'BLOB data, image file. ';
COMMENT ON COLUMN eprimg."Inactive" IS 'Record is inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN eprimg."EPRImg" IS 'Primary key, ID code to identify the image. ';
COMMENT ON COLUMN eprimg."Description" IS 'Description of the image';


CREATE  TABLE erreason (
  "ERReason" character(6) NOT NULL,
  "Description" character varying(200),
  "Inactive" numeric(5,0),
  CONSTRAINT erreason_primary PRIMARY KEY ("ERReason")
) ;
COMMENT ON TABLE erreason IS 'Patient Eligibility Rejection Reasons';
COMMENT ON COLUMN erreason."Inactive" IS 'Inactive reason? (0=No, 1=Yes)';
COMMENT ON COLUMN erreason."ERReason" IS 'Primary key, patient eligibility rejection reason code per AAA03';
COMMENT ON COLUMN erreason."Description" IS 'Description of the patient eligibility rejection reason';


CREATE  TABLE erxlog (
  "eRxLog" numeric(10,0) NOT NULL,
  "Action" character varying(255),
  "Code" character varying(255),
  "Description" character varying(255),
  "DateTime" timestamp without time zone,
  "User" numeric(10,0),
  "StationId" numeric(10,0),
  "XMLRequest" character varying(4000),
  "XMLResponse" character varying(4000),
  "eRxSyncAudit" numeric(10,0),
  CONSTRAINT erxlog_primary PRIMARY KEY ("eRxLog")
) ;
CREATE INDEX IF NOT EXISTS erxlog_erxsyncauditkey ON erxlog USING btree ("eRxSyncAudit") TABLESPACE pg_default;
COMMENT ON TABLE erxlog IS 'Logs errors that occur when accessing Rcopia e-Rx integration';
COMMENT ON COLUMN erxlog."eRxSyncAudit" IS 'Used to match log entries to a specific session; ptr to PRESCRIP.eRxSyncAudit';
COMMENT ON COLUMN erxlog."eRxLog" IS 'Primary key, internal ID from sequence';
COMMENT ON COLUMN erxlog."XMLResponse" IS 'XML response string received from Rcopia ';
COMMENT ON COLUMN erxlog."XMLRequest" IS 'XML request string sent from axiUm ';
COMMENT ON COLUMN erxlog."User" IS 'Ptr to USERS.User';
COMMENT ON COLUMN erxlog."StationId" IS 'Ptr to STATION.StationId';
COMMENT ON COLUMN erxlog."Description" IS 'Description of error code, if any';
COMMENT ON COLUMN erxlog."DateTime" IS 'Date/time of log entry';
COMMENT ON COLUMN erxlog."Code" IS 'Error code, if any';
COMMENT ON COLUMN erxlog."Action" IS 'Action that was attempted';


CREATE  TABLE erxnotif (
  "User" numeric(10,0) NOT NULL,
  "DateTime" timestamp without time zone,
  "All" numeric(5,0),
  "Refill" numeric(5,0),
  "Note" numeric(5,0),
  "Error" numeric(5,0),
  "Share" numeric(5,0),
  "RequestShare" numeric(5,0),
  "RxPending" numeric(5,0),
  "RxNeedSigning" numeric(5,0),
  "RxNeedDualSign" numeric(5,0),
  "RxNeedDualVerify" numeric(5,0),
  "RxOrdersPending" numeric(5,0),
  "RxChange" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT erxnotif_primary PRIMARY KEY ("User")
) ;
COMMENT ON TABLE erxnotif IS 'eRx Notification Records';
COMMENT ON COLUMN erxnotif."User" IS 'Primary key, user that the notification counts are for. Ptr to USERS.User';
COMMENT ON COLUMN erxnotif."Share" IS 'Count of patient sharing notifications';
COMMENT ON COLUMN erxnotif."RxPending" IS 'Count of incomplete prescription assigned notifications';
COMMENT ON COLUMN erxnotif."RxOrdersPending" IS 'Count of notifications which require review';
COMMENT ON COLUMN erxnotif."RxNeedSigning" IS 'Count of completed prescriptions that require a signature by this provider';
COMMENT ON COLUMN erxnotif."RxNeedDualVerify" IS 'Count of completed prescriptions that require dual signatures that have been signed but not verified';
COMMENT ON COLUMN erxnotif."RxNeedDualSign" IS 'Count of completed prescriptions that require dual signatures that have been verified but not signed';
COMMENT ON COLUMN erxnotif."RxChange" IS 'Count of completed prescriptions that changed';
COMMENT ON COLUMN erxnotif."RequestShare" IS 'Count of patient sharing request notifications';
COMMENT ON COLUMN erxnotif."Refill" IS 'Count of refill/renewal notifications';
COMMENT ON COLUMN erxnotif."Note" IS 'Count of text message notifications';
COMMENT ON COLUMN erxnotif."Error" IS 'Count of error message notifications';
COMMENT ON COLUMN erxnotif."DateTime" IS 'Date/time that the notification counts were last received';
COMMENT ON COLUMN erxnotif."All" IS 'Count of all notifications';


CREATE  TABLE erxopt (
  "PracticeName" character varying(255) NOT NULL,
  "RcopiaUsername" character varying(255),
  "VendorName" character varying(255),
  "VendorPassword" character varying(255),
  "ANSPrimaryURL" character varying(255),
  "ANSSecondaryURL" character varying(255),
  "LastANSDateTime" timestamp without time zone,
  "LastANSResult" numeric(5,0),
  "WebBrowserURL" character varying(255),
  "EngineUploadURL" character varying(255),
  "EngineDownloadURL" character varying(255),
  "URLCacheDateTime" timestamp without time zone,
  "WebBrowserCache" character varying(255),
  "EngineUploadCache" character varying(255),
  "EngineDownloadCache" character varying(255),
  "ExternalUser" numeric(10,0),
  "LastUpdateAllergyGrp" character varying(24),
  "UseiPrescribe" numeric(5,0) NOT NULL DEFAULT 0,
  "LastiPrescribeEventsDate" timestamp without time zone,
  "LastUpdateiPrescribeEvents" character varying(24),
  CONSTRAINT erxopt_primary PRIMARY KEY ("PracticeName")
) ;
COMMENT ON TABLE erxopt IS 'Stores credentials, URLs, and options for Rcopia e-Rx integration';
COMMENT ON COLUMN erxopt."WebBrowserURL" IS 'Web browser URL for Rcopia';
COMMENT ON COLUMN erxopt."WebBrowserCache" IS 'Field to temporarily store the Web Browser URL during ANS attempts.';
COMMENT ON COLUMN erxopt."VendorPassword" IS '[Encrypted] - Vendor password for connecting to Rcopia';
COMMENT ON COLUMN erxopt."VendorName" IS '[Encrypted] - Vendor name for connecting to Rcopia';
COMMENT ON COLUMN erxopt."UseiPrescribe" IS 'Flag to indicate if client is using iPrescribe or not.';
COMMENT ON COLUMN erxopt."URLCacheDateTime" IS 'Date and time that the cached values were last updated.';
COMMENT ON COLUMN erxopt."RcopiaUsername" IS '[Encrypted] - User name for connecting to Rcopia';
COMMENT ON COLUMN erxopt."PracticeName" IS '[Encrypted] - Practice name for connecting to Rcopia';
COMMENT ON COLUMN erxopt."LastiPrescribeEventsDate" IS 'Date and time when Get iPrescribe Events was called from axiUm.';
COMMENT ON COLUMN erxopt."LastUpdateiPrescribeEvents" IS 'Date and time of last iPrescribe Events update from Rcopia.';
COMMENT ON COLUMN erxopt."LastUpdateAllergyGrp" IS 'Date and Time of last sync with Rcopia';
COMMENT ON COLUMN erxopt."LastANSResult" IS 'Deprecated';
COMMENT ON COLUMN erxopt."LastANSDateTime" IS 'Deprecated';
COMMENT ON COLUMN erxopt."ExternalUser" IS 'External prescribing user (Ptr to USERS.User)';
COMMENT ON COLUMN erxopt."EngineUploadURL" IS 'Engine upload URL for Rcopia';
COMMENT ON COLUMN erxopt."EngineUploadCache" IS 'Field to temporarily store the Engine Upload URL during ANS attempts.';
COMMENT ON COLUMN erxopt."EngineDownloadURL" IS 'Engine download URL for Rcopia';
COMMENT ON COLUMN erxopt."EngineDownloadCache" IS 'Field to temporarily store the Engine Download URL during ANS attempts.';
COMMENT ON COLUMN erxopt."ANSSecondaryURL" IS 'Deprecated';
COMMENT ON COLUMN erxopt."ANSPrimaryURL" IS 'Deprecated';


CREATE  TABLE ethnic (
  "Ethnic" character(6) NOT NULL,
  "Description" character varying(30),
  "USType" numeric(5,0),
  "Inactive" numeric(5,0),
  CONSTRAINT ethnic_primary PRIMARY KEY ("Ethnic")
) ;
COMMENT ON TABLE ethnic IS 'Patient Ethnicity Codes';
COMMENT ON COLUMN ethnic."USType" IS 'US only (0=Hispanic or Latino, 1=Other)';
COMMENT ON COLUMN ethnic."Inactive" IS 'Is Inactive? 0 = No, 1 = Yes';
COMMENT ON COLUMN ethnic."Ethnic" IS 'Id Code to identify this ethnic type';
COMMENT ON COLUMN ethnic."Description" IS 'Description of this ethnic type';


CREATE  TABLE eventlog (
  "Date" timestamp without time zone NOT NULL,
  "User" numeric(10,0),
  "StationId" numeric(10,0) NOT NULL,
  "EventType" character varying(20),
  "InfoText" character varying(4000),
  CONSTRAINT eventlog_primary PRIMARY KEY ("Date", "StationId")
) ;
COMMENT ON TABLE eventlog IS 'Table to track program crashes, database errors and empty content for contracts (estimate, payment plan, tx plan and consents)';
COMMENT ON COLUMN eventlog."User" IS 'Ptr to USERS.User';
COMMENT ON COLUMN eventlog."StationId" IS 'Ptr to STATION.StationId';
COMMENT ON COLUMN eventlog."InfoText" IS 'Text description of the event';
COMMENT ON COLUMN eventlog."EventType" IS 'Type of event: "CRASH OR HANG", "DATABASE ERROR", or "EMPTY CONTRACT"';
COMMENT ON COLUMN eventlog."Date" IS 'Primary key, Date/time of the event';


CREATE  TABLE external_link (
  "Id" numeric(10,0) NOT NULL,
  "axiUmApiLogId" numeric(10,0),
  "CreatedDateTime" timestamp without time zone,
  "PatientId" numeric(10,0),
  "EHR" character varying(255),
  "EHRPatientId" character varying(255),
  "Deleted" numeric(5,0),
  "DeletedDateTime" timestamp without time zone,
  "EHRPatientIdType" character varying(255),
  "Inactive" numeric(5,0),
  "PullDateTime" timestamp without time zone,
  "PullChangeDateTime" timestamp without time zone,
  "PushDateTime" timestamp without time zone,
  "AxiumChangeDateTime" timestamp without time zone,
  "VerifyDateTime" timestamp without time zone,
  CONSTRAINT external_link_primary PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE external_link IS 'Table for storing CoC external links.';
COMMENT ON COLUMN external_link."axiUmApiLogId" IS 'Id of the API_LOG entry that resulted in this patient request';
COMMENT ON COLUMN external_link."VerifyDateTime" IS 'Date and time of the last time a user verified changes pulled from the external EHR';
COMMENT ON COLUMN external_link."PushDateTime" IS 'Date and time of the last push/send to the external EHR';
COMMENT ON COLUMN external_link."PullDateTime" IS 'Date and time of the last pull/sync from the external EHR';
COMMENT ON COLUMN external_link."PullChangeDateTime" IS 'Date and time of the last update made to the patient record in axiUm';
COMMENT ON COLUMN external_link."PatientId" IS 'ptr to PATIENT.Patient';
COMMENT ON COLUMN external_link."Inactive" IS 'if 1, Disables synchronization for this link';
COMMENT ON COLUMN external_link."Id" IS 'Primary key sequence field,';
COMMENT ON COLUMN external_link."EHRPatientIdType" IS 'The type of ID in the external EHR (e.g. MRN or "UID")';
COMMENT ON COLUMN external_link."EHRPatientId" IS 'Id of the patient in the external EHR';
COMMENT ON COLUMN external_link."EHR" IS 'Name of the EHR that the patient is linked to';
COMMENT ON COLUMN external_link."DeletedDateTime" IS 'Date and time the link was deleted';
COMMENT ON COLUMN external_link."Deleted" IS '0: no, 1: yes';
COMMENT ON COLUMN external_link."CreatedDateTime" IS 'Date and time the link was created';
COMMENT ON COLUMN external_link."AxiumChangeDateTime" IS 'Date and time of the last update made to the patient record in axiUm';


CREATE  TABLE facilids (
  "Code" character(6) NOT NULL,
  "Service" character(6) NOT NULL,
  "Number" character(15),
  "Qualifier" character varying(2),
  CONSTRAINT facilids_primary PRIMARY KEY ("Code", "Service")
) ;
COMMENT ON TABLE facilids IS 'Facility Service IDs.';
COMMENT ON COLUMN facilids."Service" IS 'Ptr to SERVICE.Code';
COMMENT ON COLUMN facilids."Qualifier" IS 'ID prefix for claim form submisson';
COMMENT ON COLUMN facilids."Number" IS 'Facility service ID number';
COMMENT ON COLUMN facilids."Code" IS 'Ptr to FACILITY.Code';


CREATE  TABLE facility (
  "Code" character(6) NOT NULL,
  "Description" character(30),
  "Address1" character(30),
  "Address2" character(30),
  "City" character(24),
  "Province" character(6),
  "Postal" character(15),
  "Area" character(4),
  "Phone" character(8),
  "Note" character varying(4000),
  "IsOther" numeric(5,0),
  "AddressOther" character(15),
  "NPI" character varying(10),
  "IDNumber" character varying(15),
  "IsTIN" numeric(5,0),
  "Inactive" numeric(5,0),
  CONSTRAINT facility_primary PRIMARY KEY ("Code")
) ;
COMMENT ON TABLE facility IS 'Facility Codes';
COMMENT ON COLUMN facility."Province" IS 'Province/state that the facility is located in, ptr to PROVINCE.Province';
COMMENT ON COLUMN facility."Postal" IS 'Postal/ZIP code for the facility, ptr to CITY.Postal';
COMMENT ON COLUMN facility."Phone" IS 'Telephone number.';
COMMENT ON COLUMN facility."Note" IS 'Free text area to enter notes about this facility.';
COMMENT ON COLUMN facility."NPI" IS 'US only - National Provider Identification ("NPI") for this facility.';
COMMENT ON COLUMN facility."IsTIN" IS 'ID number to use (0=SSN, 1="TIN")';
COMMENT ON COLUMN facility."IsOther" IS 'Other location? (0=No, 1=Yes)';
COMMENT ON COLUMN facility."Inactive" IS 'Facility is inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN facility."IDNumber" IS 'If IsTIN=0, then the SSN associated with the facility. If IsTin=1, then the "TIN" associated with the facility.';
COMMENT ON COLUMN facility."Description" IS 'Description of the facility.';
COMMENT ON COLUMN facility."Code" IS 'Primary key, code to identify the facility.';
COMMENT ON COLUMN facility."City" IS 'City that the facility is located in, ptr to CITY.City';
COMMENT ON COLUMN facility."Area" IS 'Telephone area code.';
COMMENT ON COLUMN facility."AddressOther" IS 'For USA, represents County. For Dutch, represents Room Number.';
COMMENT ON COLUMN facility."Address2" IS 'Facility address, line 2.';
COMMENT ON COLUMN facility."Address1" IS 'Facility address, line 1.';


CREATE  TABLE famlimit (
  "PolicyId" numeric(10,0) NOT NULL,
  "CoverageId" numeric(10,0) NOT NULL,
  "Category" character(6) NOT NULL,
  "Description" character(30),
  "Limit" numeric,
  "LimitOnPatient" numeric(5,0),
  "LimitBalance" numeric,
  "ResetDate" timestamp without time zone,
  CONSTRAINT famlimit_primary PRIMARY KEY ("PolicyId", "CoverageId", "Category")
) ;
COMMENT ON TABLE famlimit IS 'Family Insurance Limits';
COMMENT ON COLUMN famlimit."ResetDate" IS 'Date on which to reset the family limits';
COMMENT ON COLUMN famlimit."PolicyId" IS 'Primary key component, insurance policy ID. Ptr to PTPOL.PolicyId';
COMMENT ON COLUMN famlimit."LimitOnPatient" IS 'Is this a patient limit? (0=No (limit on insurance), 1=Yes (limit on patient maximum), 2=Yes (limit on patient maximum + deductable))';
COMMENT ON COLUMN famlimit."LimitBalance" IS 'Dollar ($) amount of the limit balance';
COMMENT ON COLUMN famlimit."Limit" IS 'Dollar ($) amount of the limit';
COMMENT ON COLUMN famlimit."Description" IS 'Description of coverage template item';
COMMENT ON COLUMN famlimit."CoverageId" IS 'Primary key component, Id code of the coverage template, ptr to COVERAGE.Coverage';
COMMENT ON COLUMN famlimit."Category" IS 'Primary key component, policy category, ptr to COVERIT.Category';


CREATE  TABLE faptwatch (
  "Id" numeric(10,0) NOT NULL,
  "Appointment" numeric(10,0) NOT NULL,
  "Instructor" numeric(10,0) NOT NULL,
  "Date" timestamp without time zone,
  CONSTRAINT faptwatch_pk PRIMARY KEY ("Id")
) ;
CREATE INDEX IF NOT EXISTS faptwatch_user ON faptwatch USING btree ("Instructor", "Date") TABLESPACE pg_default;
COMMENT ON TABLE faptwatch IS 'FacultyAccess Watched Appointments';
COMMENT ON COLUMN faptwatch."Instructor" IS 'Instructor that is watching, ptr to USERS.User.';
COMMENT ON COLUMN faptwatch."Id" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN faptwatch."Date" IS 'Date that the appointment is being watched for. ';
COMMENT ON COLUMN faptwatch."Appointment" IS 'Appointment that is being watched, ptr to APPOINT.Appointment.';


CREATE  TABLE faq_pa2 (
  "iSetting" numeric(5,0) NOT NULL DEFAULT 0,
  "Key" character varying(255) NOT NULL,
  "SettingType" numeric(5,0) NOT NULL DEFAULT 1,
  "iSettingGrp" numeric(5,0) NOT NULL DEFAULT 0,
  "Priority" numeric(5,0) NOT NULL DEFAULT 0,
  "Value" clob,
  "Description" character varying(4000),
  "Status" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT faq_pa2_primary PRIMARY KEY ("iSetting")
) ;
COMMENT ON COLUMN faq_pa2."iSettingGrp" IS 'Group that the iSetting is in. Ptr to ISETTINGGRP.iSettingGrp.';
COMMENT ON COLUMN faq_pa2."iSetting" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN faq_pa2."Value" IS 'Message or setting value.';
COMMENT ON COLUMN faq_pa2."Status" IS 'The status of the setting (0=Active, 1=Hidden, 2=Deleted)';
COMMENT ON COLUMN faq_pa2."SettingType" IS 'Type of setting: (1 = Logical setting, 2=Message/HTMLEncode, 3=Message/HTMLNoEncode, 4=Special, 5=File, 6=Color picker)';
COMMENT ON COLUMN faq_pa2."Priority" IS 'Priority of the ISETTING_PA2.';
COMMENT ON COLUMN faq_pa2."Key" IS 'Lookup key for setting/message.';
COMMENT ON COLUMN faq_pa2."Description" IS 'Description of the ISETTING_PA2.';


CREATE  TABLE feedates (
  "FeeDates" numeric(10,0) NOT NULL,
  "Fee" character(6),
  "StartDate" timestamp without time zone,
  "EndDate" timestamp without time zone,
  CONSTRAINT feedates_primary PRIMARY KEY ("FeeDates")
) ;
COMMENT ON TABLE feedates IS 'Fee Schedule Dates';
COMMENT ON COLUMN feedates."StartDate" IS 'Date that the fee schedule starts';
COMMENT ON COLUMN feedates."FeeDates" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN feedates."Fee" IS 'Fee schedule that these dates are for, ptr to FEESCHED.Fee';
COMMENT ON COLUMN feedates."EndDate" IS 'Date that the fee schedule ends';


CREATE  TABLE feesched (
  "Fee" character(6) NOT NULL,
  "Description" character(30),
  "Inactive" numeric(5,0),
  CONSTRAINT feesched_primary PRIMARY KEY ("Fee")
) ;
COMMENT ON TABLE feesched IS 'Fee Schedule Codes';
COMMENT ON COLUMN feesched."Inactive" IS 'Code is inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN feesched."Fee" IS 'Primary key, ID code to identify the fee schedule';
COMMENT ON COLUMN feesched."Description" IS 'Name of the fee schedule';


CREATE  TABLE fiaccess (
  "FormCode" character(6) NOT NULL,
  "FItem" numeric(10,0) NOT NULL,
  "SLevel" numeric(10,0) NOT NULL,
  "Access" numeric(5,0),
  "CanApprove" numeric(5,0),
  CONSTRAINT fiaccess_primary PRIMARY KEY ("FormCode", "FItem", "SLevel")
) ;
CREATE INDEX IF NOT EXISTS fiaccess_fitem ON fiaccess USING btree ("FItem", "SLevel") TABLESPACE pg_default;
COMMENT ON TABLE fiaccess IS 'Form Item Access';
COMMENT ON COLUMN fiaccess."SLevel" IS 'Primary key component, security level that this access is for. Ptr to SLEVEL.SLevel.';
COMMENT ON COLUMN fiaccess."FormCode" IS 'Primary key component, form code that this access is for. Ptr to FITEM.FormCode';
COMMENT ON COLUMN fiaccess."FItem" IS 'Primary key component, form item that this access is for. Ptr to FITEM.FItem';
COMMENT ON COLUMN fiaccess."CanApprove" IS 'Can users of this level approve this form item? (0=No, 1=Yes)';
COMMENT ON COLUMN fiaccess."Access" IS 'Can access? (0 = No, 1 = Read only, 2 = Require Approval, 3 = Full)';


CREATE  TABLE fischeme (
  "FIScheme" character(6) NOT NULL,
  "Min" numeric,
  "Max" numeric,
  "Increment" numeric,
  CONSTRAINT fischeme_primary PRIMARY KEY ("FIScheme")
) ;
COMMENT ON TABLE fischeme IS 'Holds number schemes(similar to grading SCHEME table), so EPR number answers can be restricted to a certain range and increment.';
COMMENT ON COLUMN fischeme."Min" IS 'Minimum value allowed';
COMMENT ON COLUMN fischeme."Max" IS 'Maximum value allowed';
COMMENT ON COLUMN fischeme."Increment" IS 'Answer must be an increment of this number';
COMMENT ON COLUMN fischeme."FIScheme" IS 'Primary key, ID code to identify the number scheme.';


CREATE  TABLE fitem (
  "FormCode" character(6),
  "Page" numeric(10,0),
  "Row" numeric(10,0),
  "FormId" numeric(10,0),
  "FItem" numeric(10,0) NOT NULL,
  "Type" numeric(5,0),
  "Text" character varying(255),
  "AnsType" numeric(5,0),
  "AnsList" character(6),
  "PageComment" numeric(5,0),
  "Date" timestamp without time zone,
  "Deleted" numeric(5,0),
  "DeletionDate" timestamp without time zone,
  "CanChange" numeric(5,0),
  "ASAPage" numeric(5,0),
  "ASAScore" numeric(5,0),
  "NeedPtSig" numeric(5,0),
  "Time" numeric(10,0),
  "DeletionTime" numeric(10,0),
  "OrgFItem" numeric(10,0),
  "EPRImg" character(6),
  "Code" character varying(10),
  "FunctionName" character varying(50),
  "IsHealth" numeric(5,0),
  "HasChildQuestions" numeric(5,0),
  "ParentFItem" numeric(10,0),
  "NeedOtherSigs" numeric(5,0),
  "ColSize" numeric(5,0),
  "FIScheme" character(6),
  "iForm" numeric(5,0),
  "Instructions" character varying(4000),
  "SubLevel" numeric(5,0),
  "EntryDateTime" timestamp without time zone,
  "DeletionDateTime" timestamp without time zone,
  "LimitChildAnswers" numeric(5,0),
  "AllowDontKnow" numeric(5,0),
  "SubQAnswer" numeric(5,0),
  CONSTRAINT fitem_primary PRIMARY KEY ("FItem")
) ;
CREATE INDEX IF NOT EXISTS fitem_code ON fitem USING btree ("Code", "Deleted") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS fitem_codetypekey ON fitem USING btree ("FormCode", "Type", "Deleted", "FItem", "Page") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS fitem_history ON fitem USING btree ("FItem", "OrgFItem", "DeletionDate", "DeletionTime", "Date") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS fitem_parentfitem ON fitem USING btree ("ParentFItem") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS fitem_rowkey ON fitem USING btree ("FormCode", "Page", "Row", "Type") TABLESPACE pg_default;
COMMENT ON TABLE fitem IS 'Form Item (question line on form)';
COMMENT ON COLUMN fitem."iForm" IS 'Is this question available in iForms? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN fitem."Type" IS 'Item Type (0 = Page Label, 1 = Header, 2 = Question/Item, 3 = Checklist Item, 4 = Additional Info, 5 = Spreadsheet Heading, 6 = Spreadsheet Row )';
COMMENT ON COLUMN fitem."Time" IS 'Time the entry was made';
COMMENT ON COLUMN fitem."Text" IS 'Item Description';
COMMENT ON COLUMN fitem."SubQAnswer" IS 'If this question has subquestions, which answer triggers them? (0=No answers, 1=Yes answers, 2=Don''t Know answers)';
COMMENT ON COLUMN fitem."SubLevel" IS 'Nesting level of the question, values: 1..n';
COMMENT ON COLUMN fitem."Row" IS 'Row number of the page that this item is displayed on. ';
COMMENT ON COLUMN fitem."ParentFItem" IS 'If this is a subquestion, ID code of the parent record. Ptr to FITEM.FItem';
COMMENT ON COLUMN fitem."PageComment" IS 'If Type=0, page requires a comment? (0 = No, 1 = Yes)';
COMMENT ON COLUMN fitem."Page" IS 'Page number of the form that this item is in. ';
COMMENT ON COLUMN fitem."OrgFItem" IS 'Original FItem, ptr to FITEM.FItem.';
COMMENT ON COLUMN fitem."NeedPtSig" IS 'Capture patient signature for EPR page? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN fitem."NeedOtherSigs" IS 'Needs other signatures? (0 = No, 1 = Yes)';
COMMENT ON COLUMN fitem."LimitChildAnswers" IS 'If Type != 5, limit checklist answers to a single checked answer? (0=No, 1=Yes); If Type = 5, maximimum number of columns allowed in the spreadsheet. ';
COMMENT ON COLUMN fitem."IsHealth" IS 'Is health history related? (0=No, 1=Yes - show in In Progress health summary)';
COMMENT ON COLUMN fitem."Instructions" IS 'Instructions for this question.';
COMMENT ON COLUMN fitem."HasChildQuestions" IS 'Item has sub-questions? (0 = No, 1 = Checklist, 2 = Additional Info, 3 = Spreadsheet)';
COMMENT ON COLUMN fitem."FunctionName" IS 'If AnsType = 7, name of the Oracle function used to perform the calculation.';
COMMENT ON COLUMN fitem."FormId" IS 'Form record ID, ptr to FORM.Id';
COMMENT ON COLUMN fitem."FormCode" IS 'Form code that this item is for, ptr to FORM.Code';
COMMENT ON COLUMN fitem."FItem" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN fitem."FIScheme" IS 'If AnsType=2, optional answer scheme. Ptr to FISCHEME.FIScheme';
COMMENT ON COLUMN fitem."EntryDateTime" IS 'Date/time of when the FITEM was entered.';
COMMENT ON COLUMN fitem."EPRImg" IS 'If AnsType=6, ID code of the EPR image. Ptr to EPRIMG.EPRImg.';
COMMENT ON COLUMN fitem."DeletionTime" IS 'Time the entry was deleted';
COMMENT ON COLUMN fitem."DeletionDateTime" IS 'Date/time of when the FITEM was deleted.';
COMMENT ON COLUMN fitem."DeletionDate" IS 'Date of deletion';
COMMENT ON COLUMN fitem."Deleted" IS 'Is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN fitem."Date" IS 'Date of entry';
COMMENT ON COLUMN fitem."ColSize" IS 'If Type=0, this stores the size (width) of the List windows (via moving column width in EPR form creation in axiUm)';
COMMENT ON COLUMN fitem."Code" IS 'Optional reference code.';
COMMENT ON COLUMN fitem."CanChange" IS 'Can change? (0 = No, 1 = Yes)';
COMMENT ON COLUMN fitem."AnsType" IS 'Answer Type ( 0 = Yes/No, 1 = Text, 2 = Number, 3 = List, 4 = Date, 5 = Long Text, 6 = Image, 7 = Calculated, 8 = Attachment, 9 = Spreadsheet)';
COMMENT ON COLUMN fitem."AnsList" IS 'If AnsType=3, answer list to use. Ptr to FORMLIST.ListCode';
COMMENT ON COLUMN fitem."AllowDontKnow" IS 'Is Don''t Know an available answer for this question? (0=No, 1=Yes)';
COMMENT ON COLUMN fitem."ASAScore" IS 'The ASA score to assign for this response';
COMMENT ON COLUMN fitem."ASAPage" IS 'Is an ASA page? (0 = No, 1 = Yes)';


CREATE  TABLE fitemadd (
  "FItemAdd" numeric(10,0) NOT NULL,
  "FItem" numeric(10,0),
  "Answer" character varying(50),
  "Color" numeric(10,0),
  "AddAlert" numeric(5,0),
  "Alert" character(7),
  "AddPtNeed" numeric(5,0),
  "NeedCode" character(6),
  "NumFlag" numeric(5,0),
  "NumValue1" numeric,
  "NumValue2" numeric,
  "AlertType" numeric(5,0),
  "MedAlert" numeric(10,0),
  CONSTRAINT fitemadd_primary PRIMARY KEY ("FItemAdd")
) ;
CREATE INDEX IF NOT EXISTS fitemadd_fitem ON fitemadd USING btree ("FItem") TABLESPACE pg_default;
COMMENT ON TABLE fitemadd IS 'Form Item Additional Definitions - alert/need codes assigned based on form answers.';
COMMENT ON COLUMN fitemadd."NumValue2" IS 'The high end of the between clause.';
COMMENT ON COLUMN fitemadd."NumValue1" IS 'The value the answer must be less than or more than, or the low end of the Between clause';
COMMENT ON COLUMN fitemadd."NumFlag" IS 'For numeric-type questions, value comparison method (0 = N/A, 1 = Less than, 2 = More than, 3 = Between)';
COMMENT ON COLUMN fitemadd."NeedCode" IS 'If AddPtNeed=1, the need code to be added. Ptr to NEEDCODE.NeedCode';
COMMENT ON COLUMN fitemadd."MedAlert" IS 'If AddAlert = 1 or 2, ptr to MEDALERT.MedAlert';
COMMENT ON COLUMN fitemadd."FItemAdd" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN fitemadd."FItem" IS 'Question that this additional definition is for, ptr to FITEM.FItem. ';
COMMENT ON COLUMN fitemadd."Color" IS 'Color to use for matching answers. Decimal representation of RGB value. ';
COMMENT ON COLUMN fitemadd."Answer" IS 'Specific answer that this additional definition applies to. ';
COMMENT ON COLUMN fitemadd."AlertType" IS 'Alert type (0 = Clinical Alert, 1 = Allergy, 2 = Medical Problem)';
COMMENT ON COLUMN fitemadd."Alert" IS 'If AddAlert=1, the alert code to be added. Ptr to ALERTD2.Code';
COMMENT ON COLUMN fitemadd."AddPtNeed" IS 'Add a patient need? (0 = No, 1 = Yes, 2 = Prompt)';
COMMENT ON COLUMN fitemadd."AddAlert" IS 'Add an alert? (0 = No, 1 = Yes, 2 = Prompt)';


CREATE  TABLE fitemcol (
  "FItemCol" numeric(10,0) NOT NULL,
  "FItem" numeric(10,0),
  "Column" numeric(5,0),
  "AnsType" numeric(5,0),
  "AnsText" character varying(50),
  "AnsList" character(6),
  "AnsListDesc" character varying(50),
  "AnsDate" timestamp without time zone,
  "CanChangeText" numeric(5,0),
  "CanDelete" numeric(5,0),
  "ColSize" numeric(5,0),
  "EntryDateTime" timestamp without time zone,
  "Deleted" numeric(5,0),
  "DeletionDateTime" timestamp without time zone,
  "OrgFItemCol" numeric(10,0),
  CONSTRAINT fitemcol_primary PRIMARY KEY ("FItemCol")
) ;
CREATE INDEX IF NOT EXISTS fitemcol_fitem ON fitemcol USING btree ("FItem") TABLESPACE pg_default;
COMMENT ON TABLE fitemcol IS 'Details for spreadsheet columns';
COMMENT ON COLUMN fitemcol."OrgFItemCol" IS 'Original FItem column, Ptr to FITEMCOL.FItemCol';
COMMENT ON COLUMN fitemcol."FItemCol" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN fitemcol."FItem" IS 'Spreadsheet heading for this record. Ptr to an FITEM.FItem with FITEM.Type=5.';
COMMENT ON COLUMN fitemcol."EntryDateTime" IS 'Date/time of entry.';
COMMENT ON COLUMN fitemcol."DeletionDateTime" IS 'Date/time of deletion. ';
COMMENT ON COLUMN fitemcol."Deleted" IS 'Is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN fitemcol."Column" IS 'Column number';
COMMENT ON COLUMN fitemcol."ColSize" IS 'Default size of the column';
COMMENT ON COLUMN fitemcol."CanDelete" IS 'Can the column be deleted by the user answering the form? (0 = No, 1 = Yes)';
COMMENT ON COLUMN fitemcol."CanChangeText" IS 'Can the default column heading text be changed? (0 = No, 1 = Yes)';
COMMENT ON COLUMN fitemcol."AnsType" IS 'The type of answer used by a pre-defined column (1=Text, 2=Number, 3=List, 4=Date)';
COMMENT ON COLUMN fitemcol."AnsText" IS 'If the type of the column heading is Text or Number, default text for the column header.';
COMMENT ON COLUMN fitemcol."AnsListDesc" IS 'If the type of the column heading is List, then pre-defined column''s list answer.';
COMMENT ON COLUMN fitemcol."AnsList" IS 'If the type of the column heading is List, then pre-defined column''s list. Ptr to FORMLIST.ListCode';
COMMENT ON COLUMN fitemcol."AnsDate" IS 'If the type of the column heading is Date, then pre-defined column''s date.';


CREATE  TABLE fitemreq (
  "FItemReq" numeric(10,0) NOT NULL,
  "FItem" numeric(10,0),
  "FStatus" character(6),
  CONSTRAINT fitemreq_primary PRIMARY KEY ("FItemReq")
) ;
CREATE INDEX IF NOT EXISTS fitemreq_fitemfstatus ON fitemreq USING btree ("FItem", "FStatus") TABLESPACE pg_default;
COMMENT ON TABLE fitemreq IS 'Required form answers';
COMMENT ON COLUMN fitemreq."FStatus" IS 'Form status that makes this question required, ptr to FSTATUS.FStatus';
COMMENT ON COLUMN fitemreq."FItemReq" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN fitemreq."FItem" IS 'Question that is required, ptr to FITEM.FItem';


CREATE  TABLE form (
  "Code" character(6) NOT NULL,
  "Description" character(30),
  "Id" numeric(10,0),
  "Type" numeric(5,0),
  "Multiple" numeric(5,0),
  "AtTab" numeric(10,0),
  "Inactive" numeric(5,0),
  "OwnerType" numeric(5,0),
  "iForm" numeric(5,0),
  "Instructions" character varying(4000),
  "CanBeAssigned" numeric(5,0),
  CONSTRAINT form_primary PRIMARY KEY ("Code")
) ;
CREATE INDEX IF NOT EXISTS form_id ON form USING btree ("Id") TABLESPACE pg_default;
COMMENT ON TABLE form IS 'Enhanced Survey Form Code';
COMMENT ON COLUMN form."iForm" IS 'Enable as iForm (0 = no, 1 =yes)';
COMMENT ON COLUMN form."Type" IS 'Form Type (0=Ortho, 1=Dental, 2=Perio, 4=User, 5=Template Note, 98 = Shared EPR)';
COMMENT ON COLUMN form."OwnerType" IS 'Form owner type (0=EPR window, 1=Lab Orders, 2=Referrals, 3=Provider Assignment, 4=Treatment, 5=User, 6=Template Note)';
COMMENT ON COLUMN form."Multiple" IS 'Form is a multiple form type? (0 = No, 1 = Yes). i.e. this form is reused for the same patient but holds different information (multiple instances of the same form)';
COMMENT ON COLUMN form."Instructions" IS 'Instructions/descriptions for using this form';
COMMENT ON COLUMN form."Inactive" IS 'Record is inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN form."Id" IS 'Internal ID from sequence';
COMMENT ON COLUMN form."Description" IS 'Form Description';
COMMENT ON COLUMN form."Code" IS 'Primary key, ID code to identify the form.';
COMMENT ON COLUMN form."CanBeAssigned" IS 'Can this form be assigned to a user? (0=No, 1=Yes)';
COMMENT ON COLUMN form."AtTab" IS 'ID code of the attachment tab in which to store this form, ptr to ATTAB.AtTab';


CREATE  TABLE formlist (
  "ListCode" character(6) NOT NULL,
  "Description" character(30),
  "Type" numeric(5,0) NOT NULL,
  "IsASA" numeric(5,0),
  CONSTRAINT formlist_primary PRIMARY KEY ("ListCode", "Type")
) ;
COMMENT ON TABLE formlist IS 'Form Answer List Type';
COMMENT ON COLUMN formlist."Type" IS 'Primary key component, form type (0 = Ortho , 1 = EPR, 2 = Perio, 4 = User, 5 = Clinical Note Answer List, 99 = All EPR)';
COMMENT ON COLUMN formlist."ListCode" IS 'Primary key component, ID code to identify the answer list.';
COMMENT ON COLUMN formlist."IsASA" IS 'Is an ASA form? (0 = No, 1 = Yes)';
COMMENT ON COLUMN formlist."Description" IS 'Description of the answer list.';


CREATE  TABLE formrpt (
  "FormRpt" numeric(10,0) NOT NULL,
  "FItem" numeric(10,0),
  "ReportName" character varying(50),
  "FilePath" character varying(255),
  content bytea,
  "BeforeProcedure" character varying(50),
  "AfterProcedure" character varying(50),
  CONSTRAINT formrpt_primary PRIMARY KEY ("FormRpt")
) ;
COMMENT ON TABLE formrpt IS 'EPR form report records';
COMMENT ON COLUMN formrpt.content IS 'BLOB data, copy of the report file.';
COMMENT ON COLUMN formrpt."ReportName" IS 'Name of the report ';
COMMENT ON COLUMN formrpt."FormRpt" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN formrpt."FilePath" IS 'Path that the report was originally added from. ';
COMMENT ON COLUMN formrpt."FItem" IS 'Page that this report is for, ptr to FITEM.FItem.';
COMMENT ON COLUMN formrpt."BeforeProcedure" IS 'Name of Oracle stored procedure to run before the report';
COMMENT ON COLUMN formrpt."AfterProcedure" IS 'Name of Oracle stored procedure to run after the report';


CREATE  TABLE formsig (
  "FormSig" numeric(10,0) NOT NULL,
  "FormCode" character(6),
  "FItem" numeric(10,0),
  "Order" numeric(5,0),
  "Signee" character varying(30),
  "Required" numeric(5,0),
  "NameRequired" numeric(5,0),
  CONSTRAINT formsig_primary PRIMARY KEY ("FormSig")
) ;
COMMENT ON TABLE formsig IS 'Form Page Signature Requirements';
COMMENT ON COLUMN formsig."Signee" IS 'Name of the signee';
COMMENT ON COLUMN formsig."Required" IS 'Signature is required? (0 = No, 1 = Yes)';
COMMENT ON COLUMN formsig."Order" IS 'Order to prompt signature for (1..x)';
COMMENT ON COLUMN formsig."NameRequired" IS 'Printed name is required? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN formsig."FormSig" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN formsig."FormCode" IS 'Form code signature is required for, ptr to FORM.Code';
COMMENT ON COLUMN formsig."FItem" IS 'Form page item signature required for, ptr to FITEM.FItem';


CREATE  TABLE fsetting (
  "User" numeric(10,0) NOT NULL,
  "Key" character varying(255) NOT NULL,
  "Scope" numeric(10,0) NOT NULL,
  "SettingType" numeric(5,0) NOT NULL DEFAULT 1,
  "Value" character varying(4000) NOT NULL,
  "ShortDescription" character varying(255),
  "LongDescription" character varying(4000),
  "DefaultValue" character varying(4000),
  "Rules" character varying(255),
  CONSTRAINT fsetting_pk PRIMARY KEY ("User", "Key")
) ;
COMMENT ON TABLE fsetting IS 'Stores both global and user-specific settings for FacultyAccess';
COMMENT ON COLUMN fsetting."Value" IS 'Value of the setting.';
COMMENT ON COLUMN fsetting."User" IS 'User that this setting applies to (0 = all, else points to USERS.User)';
COMMENT ON COLUMN fsetting."ShortDescription" IS 'Short description of the setting, displayed in main FAAdmin area.';
COMMENT ON COLUMN fsetting."SettingType" IS 'Type of the setting value (0 = Text, 1 = Numeric, 2 = Date (DD-MON-YYYY format))';
COMMENT ON COLUMN fsetting."Scope" IS 'Scope of the setting (0 = global setting, 1 = user-specific setting)';
COMMENT ON COLUMN fsetting."Rules" IS 'Description of what values are valid for this setting.';
COMMENT ON COLUMN fsetting."LongDescription" IS 'Long description of the setting, displayed in details area.';
COMMENT ON COLUMN fsetting."Key" IS 'Name of the setting';
COMMENT ON COLUMN fsetting."DefaultValue" IS 'The value to reset to when restoring to default.';


CREATE  TABLE fsiteref (
  "Id" numeric(10,0) NOT NULL,
  "Value" character varying(30),
  "Country" character varying(30) NOT NULL,
  CONSTRAINT fsiteref_pk PRIMARY KEY ("Id", "Country")
) ;
COMMENT ON TABLE fsiteref IS 'Lookup table for Sites based on country, used for displaying Notes in FacultyAccess';
COMMENT ON COLUMN fsiteref."Value" IS 'Country-specific value assocated with the ID.';
COMMENT ON COLUMN fsiteref."Id" IS 'Internal ID of the site, ptr to NOTES2.Site';
COMMENT ON COLUMN fsiteref."Country" IS 'Country (either USA or Canada)';


CREATE  TABLE fstatus (
  "FormCode" character(6) NOT NULL,
  "FStatus" character(6) NOT NULL,
  "Description" character varying(50),
  "Open" numeric(5,0),
  "Optional" numeric(5,0),
  "Order" numeric(5,0),
  "Inactive" numeric(5,0),
  "IsDefault" numeric(5,0),
  "DefaultAssignToUGroup" character(6),
  "DefaultAssignToUser" numeric(10,0),
  CONSTRAINT fstatus_primary PRIMARY KEY ("FormCode", "FStatus")
) ;
COMMENT ON TABLE fstatus IS 'Form Status Codes';
COMMENT ON COLUMN fstatus."Order" IS 'Internal number that defines the order of this status in the overall progression of the form. ';
COMMENT ON COLUMN fstatus."Optional" IS 'Can this status can be skipped when filling out the form? (0=No , 1=Yes)';
COMMENT ON COLUMN fstatus."Open" IS 'Are forms of this status are considered open tasks? (0=No , 1=Yes)';
COMMENT ON COLUMN fstatus."IsDefault" IS 'Is this the default form status code? (0=No, 1=Yes)';
COMMENT ON COLUMN fstatus."Inactive" IS 'Is this form status code inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN fstatus."FormCode" IS 'Primary key component, form that this status is for. Ptr to FORM.Code';
COMMENT ON COLUMN fstatus."FStatus" IS 'Primary key component, status code. ';
COMMENT ON COLUMN fstatus."Description" IS 'Description of Form Status Code';
COMMENT ON COLUMN fstatus."DefaultAssignToUser" IS 'The default User to assign the form to at this status, ptr to USERS.User.';
COMMENT ON COLUMN fstatus."DefaultAssignToUGroup" IS 'The default Messenger group to assign the form to at this status, ptr to UGROUP.UGroup.';


CREATE  TABLE ftaclexception (
  "ExceptionId" numeric(10,0) NOT NULL,
  "ProfileId" numeric(10,0),
  "ClinicId" numeric(10,0),
  "Message" character varying(4000),
  "CreatedBy" numeric(10,0),
  "CreatedOn" timestamp without time zone DEFAULT systimestamp,
  "LANGCD" character(6),
  CONSTRAINT ftaclexception_pk PRIMARY KEY ("ExceptionId"),
  CONSTRAINT ftaclexception_fk1 FOREIGN KEY ("LANGCD") REFERENCES langcd("LangCd")
) ;
COMMENT ON TABLE ftaclexception IS 'Clinic exception messages for FirstAccess.';
COMMENT ON COLUMN ftaclexception."ProfileId" IS 'Kiosk profile ID that the message is for.';
COMMENT ON COLUMN ftaclexception."Message" IS 'Text of the clinic exception message.';
COMMENT ON COLUMN ftaclexception."LANGCD" IS 'Language that the message is for. Ptr to LANGCD.LangCd.';
COMMENT ON COLUMN ftaclexception."ExceptionId" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN ftaclexception."CreatedOn" IS 'Date that the clinic exception message was created.';
COMMENT ON COLUMN ftaclexception."CreatedBy" IS 'FirstAccess Admin user who created the clinic exception message. Ptr to USERS.User.';
COMMENT ON COLUMN ftaclexception."ClinicId" IS 'Clinic that the message is for. Ptr to CLINIC.Clinic.';


CREATE  TABLE ftksetting (
  "Profile" numeric(10,0) NOT NULL,
  "Key" character varying(255) NOT NULL,
  "Value" character varying(4000),
  filecontent bytea DEFAULT empty_blob(),
  CONSTRAINT ftksetting_pk PRIMARY KEY ("Profile", "Key")
) ;
COMMENT ON TABLE ftksetting IS 'FirstAccess settings table';
COMMENT ON COLUMN ftksetting.filecontent IS 'Holds content for certain settings such as custom logos';
COMMENT ON COLUMN ftksetting."Value" IS 'Value of setting';
COMMENT ON COLUMN ftksetting."Profile" IS 'Primary key, Kiosk profile ID this setting applies to';
COMMENT ON COLUMN ftksetting."Key" IS 'Primary key, name of setting';


CREATE  TABLE fuserticket (
  "Id" numeric(10,0) NOT NULL,
  "User" numeric(10,0) NOT NULL,
  "Date" timestamp without time zone,
  CONSTRAINT fuserticket_pk PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE fuserticket IS 'FacultyAccess user tickets for tracking logged-in users.';
COMMENT ON COLUMN fuserticket."User" IS 'The user logged in to FacultyAccess, ptr to USERS.User';
COMMENT ON COLUMN fuserticket."Id" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN fuserticket."Date" IS 'Datetime that the ticket is created for. ';


CREATE  TABLE gender (
  "Gender" character(1) NOT NULL,
  "Description" character varying(30),
  "Type" numeric(5,0),
  "Inactive" numeric(5,0),
  CONSTRAINT gender_primary PRIMARY KEY ("Gender")
) ;
COMMENT ON TABLE gender IS 'Table for storing gender codes';
COMMENT ON COLUMN gender."Type" IS 'Gender type:  0 = Unknown, 1 = Male, 2 = Female, 3 = Transgender, 4 = Gender X, 5 = Other';
COMMENT ON COLUMN gender."Inactive" IS 'Code inactive? 0 - no, 1 = yes';
COMMENT ON COLUMN gender."Gender" IS 'Primary key, Gender code: U - unknown, M - male, F - female, T - transgender, X -gender X, O - other';
COMMENT ON COLUMN gender."Description" IS 'Description: Unknown, Male, Female, Transgender, Gender X, Other';


CREATE  TABLE gentx (
  "GenTx" character(7) NOT NULL,
  "Description" character(30),
  "LevelDesc" character(30),
  "Level" numeric(5,0),
  "IsNode" numeric(5,0),
  "Deleted" numeric(5,0),
  "Id" numeric(10,0) NOT NULL,
  "Consultant" numeric(5,0),
  "Cost" numeric,
  "GtxConsultantType" numeric(5,0),
  "CompLevel" character(6),
  "MaxRequests" numeric(5,0),
  CONSTRAINT gentx_primary PRIMARY KEY ("GenTx")
) ;
CREATE INDEX IF NOT EXISTS gentx_id ON gentx USING btree ("Id") TABLESPACE pg_default;


CREATE  TABLE grading (
  "Grading" numeric(10,0) NOT NULL,
  "Producer" character(10),
  "Year" numeric(10,0),
  "Date" timestamp without time zone,
  "CreateDate" timestamp without time zone,
  "Instructor" numeric(10,0),
  "Patient" numeric(10,0),
  "Discipline" character(6),
  "Template" character(6),
  "Deleted" numeric(5,0),
  "TimeSpent" numeric,
  "Period" numeric(5,0),
  "Instructor2" numeric(10,0),
  "Instructor3" numeric(10,0),
  "Passed" numeric(5,0),
  "Comment" character varying(4000),
  "IsCompetency" numeric(5,0),
  "Incomplete" numeric(5,0),
  "HeldForUser" numeric(10,0),
  "SelfEval" numeric(5,0),
  CONSTRAINT grading_primary PRIMARY KEY ("Grading")
) ;
CREATE INDEX IF NOT EXISTS grading_date ON grading USING btree ("Date", "Instructor") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS grading_patientkey ON grading USING btree ("Patient") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS grading_provider ON grading USING btree ("Producer") TABLESPACE pg_default;
COMMENT ON TABLE grading IS 'Student Evaluation records';
COMMENT ON COLUMN grading."Year" IS 'Year of studies (usually 1...4)';
COMMENT ON COLUMN grading."TimeSpent" IS 'Amount of time spent on this procedure';
COMMENT ON COLUMN grading."Template" IS 'Template ID used for grading, ptr to TEMPLATE.Template';
COMMENT ON COLUMN grading."SelfEval" IS 'Is this a self evaluation? (0 = No, 1 = Yes)';
COMMENT ON COLUMN grading."Producer" IS 'Student Provider that was graded, ptr to PRODUCER.Producer';
COMMENT ON COLUMN grading."Period" IS 'Period number 0...2 (usually 0 = AM, 1 = PM, 2 = Evening)';
COMMENT ON COLUMN grading."Patient" IS 'Patient being evaluated for, if not a general evaluatuion. Ptr to PATIENT.Patient';
COMMENT ON COLUMN grading."Passed" IS 'Was session passed? (0 = No, 1 = Yes)';
COMMENT ON COLUMN grading."IsCompetency" IS 'Is this a competency evaluation? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN grading."Instructor3" IS 'Optional field, third instructor ID code, ptr to USERS.User';
COMMENT ON COLUMN grading."Instructor2" IS 'Optional field, second instructor ID code, ptr to USERS.User';
COMMENT ON COLUMN grading."Instructor" IS 'ID code of the primary instructor who entered the grades, ptr to USERS.User';
COMMENT ON COLUMN grading."Incomplete" IS 'Is this evaluation incomplete? (0 = No, 1 = Yes)';
COMMENT ON COLUMN grading."HeldForUser" IS 'If incomplete, optional user that the evaluation is being held for. Ptr to USERS.User.';
COMMENT ON COLUMN grading."Grading" IS 'Primary key, internal ID from sequence';
COMMENT ON COLUMN grading."Discipline" IS 'Discipline for this evaluation, ptr to DISCIPL.Discipline';
COMMENT ON COLUMN grading."Deleted" IS 'Is this evaluation deleted? (0 = No, 1 = Yes, 2 = Strike-out)';
COMMENT ON COLUMN grading."Date" IS 'Date that the evaluation is for.';
COMMENT ON COLUMN grading."CreateDate" IS 'Date/time that the evaluation was created.';
COMMENT ON COLUMN grading."Comment" IS 'Text field to enter comments about the student performance, or other grading remarks';


CREATE  TABLE graditem (
  "Grading" numeric(10,0) NOT NULL,
  "TrxSpecific" numeric(5,0) NOT NULL,
  "Row" numeric(10,0) NOT NULL,
  "IsHeading" numeric(5,0),
  "QuestionText" character(40),
  "Text" character(6),
  "Type" numeric(5,0),
  "Id" numeric(10,0),
  "Treatment" numeric(5,0),
  "RelValue" numeric,
  "Scheme" character(6),
  "User" numeric(10,0),
  "Date" timestamp without time zone,
  "Note" character varying(4000),
  "Item" numeric(10,0),
  CONSTRAINT graditem_primary PRIMARY KEY ("Grading", "TrxSpecific", "Row")
) ;
CREATE INDEX IF NOT EXISTS graditem_id ON graditem USING btree ("Id") TABLESPACE pg_default;
COMMENT ON TABLE graditem IS 'Student evaluation items (x items per grading record)';
COMMENT ON COLUMN graditem."User" IS 'User ID of entry user, ptr to USERS.User';
COMMENT ON COLUMN graditem."Type" IS 'If TrxSpecific=1, ptr to the TRX.Type of the specific treatment being graded. ';
COMMENT ON COLUMN graditem."TrxSpecific" IS 'Primary key component, is this item treatment specific? (0 = No, 1 = Yes)';
COMMENT ON COLUMN graditem."Treatment" IS 'If TrxSpecific=1, ptr to the TRX.Treatment of the specific treatment being graded. ';
COMMENT ON COLUMN graditem."Text" IS 'Text of the grading answer.';
COMMENT ON COLUMN graditem."Scheme" IS 'Grading scheme ID to use for this question, ptr to SCHEME.Scheme';
COMMENT ON COLUMN graditem."Row" IS 'Primary key component, the row ID of the grading item within the grading card.';
COMMENT ON COLUMN graditem."RelValue" IS 'If TrxSpecific=1, credit points assigned for the treatment.';
COMMENT ON COLUMN graditem."QuestionText" IS 'Text of the grading question.';
COMMENT ON COLUMN graditem."Note" IS 'Note that can be added to a grading answer ';
COMMENT ON COLUMN graditem."Item" IS 'Template item for this grade item, ptr to TITEM.Item';
COMMENT ON COLUMN graditem."IsHeading" IS 'Is this item a heading? (0 = No, 1 = Yes, 2 = Question, 3 = Comment)';
COMMENT ON COLUMN graditem."Id" IS 'If TrxSpecific=1, ptr to the TRX.Id of the specific treatment being graded. ';
COMMENT ON COLUMN graditem."Grading" IS 'Primary key component, ptr to parent grading record (GRADING.Grading)';
COMMENT ON COLUMN graditem."Date" IS 'Date that the item was graded.';


CREATE  TABLE graphhis (
  "GraphHis" numeric(10,0) NOT NULL,
  "HistoryType" numeric(5,0),
  "Deleted" numeric(5,0),
  "Auto" numeric(10,0),
  "PId" numeric(10,0),
  "Site" numeric(10,0),
  "ModifiedDateTime" timestamp without time zone,
  "Start" numeric(10,0),
  "End" numeric(10,0),
  "Color" numeric(10,0),
  "Type" numeric(10,0),
  "Status" numeric(10,0),
  "Surface" numeric(10,0),
  "TxId" numeric(10,0),
  "FillStyle" numeric(5,0),
  "Audit" numeric(10,0),
  "TxPTx" numeric(10,0),
  CONSTRAINT graphhis_primary PRIMARY KEY ("GraphHis")
) ;
CREATE INDEX IF NOT EXISTS graphhis_auto ON graphhis USING btree ("Auto") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS graphhis_pid ON graphhis USING btree ("PId") TABLESPACE pg_default;
COMMENT ON TABLE graphhis IS 'Graphics History on Chart';
COMMENT ON COLUMN graphhis."Type" IS 'Type of graphic (1=Filling, 2=Crown, 3=Bridge, 4=Implant, 5=Retainer Bar, 6=Pontic)';
COMMENT ON COLUMN graphhis."TxPTx" IS 'If this graphic is from a procedure on a treatment plan, ptr to TXPTX.TxPTx. 0 otherwise. ';
COMMENT ON COLUMN graphhis."TxId" IS 'Treatment ID that graphic is related to, ptr to TREATME2.Auto';
COMMENT ON COLUMN graphhis."Surface" IS 'Surfaces of crown that are covered by graphic';
COMMENT ON COLUMN graphhis."Status" IS 'Status of procedure (0 = Complete, 1 = InProcess, 2 = Planned, 3 = PreExisting, 4 = Condition,5 = OrthoVisit, 6 = Treatment Plan)';
COMMENT ON COLUMN graphhis."Start" IS 'For Bridge type procedures, a value of 1 indicates the starting tooth of the bridge';
COMMENT ON COLUMN graphhis."Site" IS 'Tooth that that the drawing is on.';
COMMENT ON COLUMN graphhis."PId" IS 'Patient charting information, ptr to PATIENT2.Auto';
COMMENT ON COLUMN graphhis."ModifiedDateTime" IS 'Date / time that detail was drawn.';
COMMENT ON COLUMN graphhis."HistoryType" IS 'Type of history (1=Add, 2=Edit, 4=Delete)';
COMMENT ON COLUMN graphhis."GraphHis" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN graphhis."FillStyle" IS 'Number to represent the fill style (0=Solid Color, 1=Transparent Diagonal Hatched, 2=Transparent Crosshatched, 3=Transparent Downward Diagonal Lines, 4=Transparent Upward Diagonal Lines, 5=Diagonal Hatched, 6=Crosshatched, 7=Downward Diagonal Lines, 8=Upward Diagonal Lines)';
COMMENT ON COLUMN graphhis."End" IS 'For Bridge type procedures, a value of 1 indicates the ending tooth of the bridge';
COMMENT ON COLUMN graphhis."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN graphhis."Color" IS 'Color of graphic (0=None, 1=Purple/Blue, 2=Royal Blue, 3=Teal, 4=Forest Green, 5=Light Green, 6=Yellow/Gold, 7=Red, 8=Orange, 9=Grey, 10=Black)';
COMMENT ON COLUMN graphhis."Auto" IS 'Graphic that this history is for, ptr to GRAPHP2.Auto';
COMMENT ON COLUMN graphhis."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE graphp2 (
  "Auto" numeric(10,0) NOT NULL,
  "PId" numeric(10,0),
  "Site" numeric(10,0),
  "ModifiedDateTime" timestamp without time zone,
  "Start" numeric(10,0),
  "End" numeric(10,0),
  "Color" numeric(10,0),
  "Type" numeric(10,0),
  "Status" numeric(10,0),
  "Surface" numeric(10,0),
  "TxId" numeric(10,0),
  "FillStyle" numeric(5,0),
  "Audit" numeric(10,0),
  "TxPTx" numeric(10,0),
  CONSTRAINT graphp2_primary PRIMARY KEY ("Auto")
) ;
CREATE INDEX IF NOT EXISTS "GRAPHP2_PId" ON graphp2 USING btree ("PId", "Site", "ModifiedDateTime") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS "GRAPHP2_TxId" ON graphp2 USING btree ("TxId") TABLESPACE pg_default;
COMMENT ON TABLE graphp2 IS 'Graphics on Chart';
COMMENT ON COLUMN graphp2."Type" IS 'Type of graphic (1=Filling, 2=Crown, 3=Bridge, 4=Implant, 5=Retainer Bar, 6=Pontic)';
COMMENT ON COLUMN graphp2."TxPTx" IS 'If this graphic is from a procedure on a treatment plan, ptr to TXPTX.TxPTx. 0 otherwise. ';
COMMENT ON COLUMN graphp2."TxId" IS 'Treatment ID that graphic is related to, ptr to TREATME2.Auto';
COMMENT ON COLUMN graphp2."Surface" IS 'Surfaces of crown that are covered by graphic';
COMMENT ON COLUMN graphp2."Status" IS 'Status of procedure (0 = Complete, 1 = InProcess, 2 = Planned, 3 = PreExisting, 4 = Condition,5 = OrthoVisit, 6 = Treatment Plan)';
COMMENT ON COLUMN graphp2."Start" IS 'For Bridge type procedures, a value of 1 indicates the starting tooth of the bridge';
COMMENT ON COLUMN graphp2."Site" IS 'Tooth that that the drawing is on.';
COMMENT ON COLUMN graphp2."PId" IS 'Patient charting information, ptr to PATIENT2.Auto';
COMMENT ON COLUMN graphp2."ModifiedDateTime" IS 'Date / time that detail was drawn.';
COMMENT ON COLUMN graphp2."FillStyle" IS 'Number to represent the fill style (0=Solid Color, 1=Transparent Diagonal Hatched, 2=Transparent Crosshatched, 3=Transparent Downward Diagonal Lines, 4=Transparent Upward Diagonal Lines, 5=Diagonal Hatched, 6=Crosshatched, 7=Downward Diagonal Lines, 8=Upward Diagonal Lines)';
COMMENT ON COLUMN graphp2."End" IS 'For Bridge type procedures, a value of 1 indicates the ending tooth of the bridge';
COMMENT ON COLUMN graphp2."Color" IS 'Color of graphic (0=None, 1=Purple/Blue, 2=Royal Blue, 3=Teal, 4=Forest Green, 5=Light Green, 6=Yellow/Gold, 7=Red, 8=Orange, 9=Grey, 10=Black)';
COMMENT ON COLUMN graphp2."Auto" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN graphp2."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE groupl (
  "GroupLayout" numeric(10,0) NOT NULL,
  "Clinic" numeric(10,0),
  "ClinicTime" numeric(10,0),
  "Description" character(30),
  "From" timestamp without time zone,
  "To" timestamp without time zone,
  "Days0" numeric(5,0),
  "Days1" numeric(5,0),
  "Days2" numeric(5,0),
  "Days3" numeric(5,0),
  "Days4" numeric(5,0),
  "Days5" numeric(5,0),
  "Days6" numeric(5,0),
  "Daily" numeric(5,0),
  "WorkSchType" numeric(5,0),
  CONSTRAINT groupl_primary PRIMARY KEY ("GroupLayout")
) ;
CREATE INDEX IF NOT EXISTS groupl_clinic ON groupl USING btree ("Clinic") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS groupl_timefrom ON groupl USING btree ("ClinicTime", "From") TABLESPACE pg_default;
COMMENT ON TABLE groupl IS 'Scheduler clinic definition ';
COMMENT ON COLUMN groupl."WorkSchType" IS 'Work schedule type (0= no, 1= generated from instructor work schedule setup) and will be cleared once user goes into daily layout via scheduler';
COMMENT ON COLUMN groupl."To" IS 'Date (julian format) this layout will end';
COMMENT ON COLUMN groupl."GroupLayout" IS 'Primary key, Internal ID (from sequence), ID code of the layout';
COMMENT ON COLUMN groupl."From" IS 'Date (julian format) this layout will begin';
COMMENT ON COLUMN groupl."Description" IS 'Description of the layout';
COMMENT ON COLUMN groupl."Days6" IS 'Optional field, applies to Sunday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN groupl."Days5" IS 'Optional field, applies to Saturday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN groupl."Days4" IS 'Optional field, applies to Friday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN groupl."Days3" IS 'Optional field, applies to Thursday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN groupl."Days2" IS 'Optional field, applies to Wednesday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN groupl."Days1" IS 'Optional field, applies to Tuesday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN groupl."Days0" IS 'Optional field, applies to Monday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN groupl."Daily" IS 'Layout only applies to a single day, not a date range? (0 = No, 1 = Yes)';
COMMENT ON COLUMN groupl."ClinicTime" IS 'Clinic session that layout applies to, ptr to CLINICT.ClinicTime';
COMMENT ON COLUMN groupl."Clinic" IS 'Clinic ID to which this layout applies';


CREATE  TABLE gtxappid (
  "Option" numeric(10,0) NOT NULL,
  "ConsultantId" numeric(10,0),
  "ConsultantType" numeric(5,0) NOT NULL,
  "ApproveDate" timestamp without time zone,
  "Approved" numeric(5,0),
  CONSTRAINT gtxappid_primary PRIMARY KEY ("Option", "ConsultantType")
) ;


CREATE  TABLE gtxopt (
  "Option" numeric(10,0) NOT NULL,
  "Complaint" numeric(10,0),
  "Consultant" numeric(5,0),
  "Instructor" numeric(5,0),
  "Cost" numeric,
  "Date" timestamp without time zone,
  "Flag" numeric(5,0),
  "InstructorId" numeric(10,0),
  "InstructorApproveDate" timestamp without time zone,
  CONSTRAINT gtxopt_primary PRIMARY KEY ("Option")
) ;
CREATE INDEX IF NOT EXISTS gtxopt_complaint ON gtxopt USING btree ("Complaint") TABLESPACE pg_default;


CREATE  TABLE gtxplan (
  "Id" numeric(10,0) NOT NULL,
  "Option" numeric(10,0),
  "Complaint" numeric(10,0),
  "Code" character(7),
  "Tooth" numeric(5,0),
  "Deleted" numeric(5,0),
  "Desc" character(30),
  "Cost" numeric,
  "ConsultantType" numeric(5,0),
  "Provider" character(10),
  "Phase" character(2),
  "Status" character(1),
  "CloseDate" timestamp without time zone,
  "Diagnose" numeric(10,0),
  CONSTRAINT gtxplan_primary PRIMARY KEY ("Id")
) ;
CREATE INDEX IF NOT EXISTS gtxplan_complaint ON gtxplan USING btree ("Complaint") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS gtxplan_option ON gtxplan USING btree ("Option") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS gtxplan_provider ON gtxplan USING btree ("Provider") TABLESPACE pg_default;


CREATE  TABLE gtxpro (
  "GtxPro" numeric(10,0) NOT NULL,
  "GtxPlan" numeric(10,0),
  "Type" numeric(5,0),
  "ProList" numeric(10,0),
  "Complain" numeric(10,0),
  CONSTRAINT gtxpro_primary PRIMARY KEY ("GtxPro")
) ;
CREATE INDEX IF NOT EXISTS gtxpro_gtxplankey ON gtxpro USING btree ("GtxPlan") TABLESPACE pg_default;


CREATE  TABLE health (
  "Health" character(6) NOT NULL,
  "Description" character(30),
  CONSTRAINT health_primary PRIMARY KEY ("Health")
) ;
COMMENT ON TABLE health IS 'Health Information / Certification Codes';
COMMENT ON COLUMN health."Health" IS 'Primary key, ID code to identify the certification or health condition. ';
COMMENT ON COLUMN health."Description" IS 'Description of the certification or health condition. ';


CREATE  TABLE holdtime (
  "HoldTime" numeric(10,0) NOT NULL,
  "Description" character varying(30),
  "DisplayDesc" character varying(30),
  "Color" numeric(10,0),
  "ReleaseDays" numeric(5,0),
  "ReleaseTime" numeric(10,0),
  CONSTRAINT holdtime_primary PRIMARY KEY ("HoldTime")
) ;
COMMENT ON TABLE holdtime IS 'Hold Time records';
COMMENT ON COLUMN holdtime."ReleaseTime" IS 'Time opens up in mins since midnight';
COMMENT ON COLUMN holdtime."ReleaseDays" IS '# days expires (not effective in last 2 days)';
COMMENT ON COLUMN holdtime."HoldTime" IS 'Sequence primary key';
COMMENT ON COLUMN holdtime."DisplayDesc" IS 'Display description';
COMMENT ON COLUMN holdtime."Description" IS 'Description of hold time';
COMMENT ON COLUMN holdtime."Color" IS 'Display color';


CREATE  TABLE holiday (
  "Id" numeric(10,0) NOT NULL,
  "Clinic" numeric(10,0),
  "Description" character(30),
  "StartDate" timestamp without time zone,
  "EndDate" timestamp without time zone,
  "PartialDay" numeric(5,0),
  "StartTime" numeric(10,0),
  "EndTime" numeric(10,0),
  "DisplayDesc" character varying(30),
  CONSTRAINT holiday_primary PRIMARY KEY ("Id")
) ;
CREATE INDEX IF NOT EXISTS holiday_clinic ON holiday USING btree ("Clinic", "StartDate") TABLESPACE pg_default;
COMMENT ON TABLE holiday IS 'Clinic Holidays';
COMMENT ON COLUMN holiday."StartTime" IS 'Time holiday begins, in minutes from midnight.';
COMMENT ON COLUMN holiday."StartDate" IS 'Date that the holiday begins.';
COMMENT ON COLUMN holiday."PartialDay" IS 'Is a partial day holiday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN holiday."Id" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN holiday."EndTime" IS 'Time holiday ends, in minutes from midnight. ';
COMMENT ON COLUMN holiday."EndDate" IS 'Date that the holiday ends.';
COMMENT ON COLUMN holiday."DisplayDesc" IS 'The description that will display within the scheduler for this holiday.';
COMMENT ON COLUMN holiday."Description" IS 'Description of the holiday.';
COMMENT ON COLUMN holiday."Clinic" IS 'Clinic that this clinic holiday is for (0=All Clinics, else ptr to CLINIC.Clinic)';


CREATE  TABLE iaccess (
  "iUser" numeric(10,0) NOT NULL,
  "RespiUser" numeric(10,0) NOT NULL,
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT iaccess_primary PRIMARY KEY ("iUser", "RespiUser")
) ;
COMMENT ON TABLE iaccess IS 'Guarantor Access table for PatientAccess Patients';
COMMENT ON COLUMN iaccess."iUser" IS 'iUser that access is for, ptr to IUSER.iUser';
COMMENT ON COLUMN iaccess."RespiUser" IS 'Guarantor that is getting access, ptr to IUSER.iUser';
COMMENT ON COLUMN iaccess."Deleted" IS 'Is Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN iaccess."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE iaccessh (
  "iAccessH" numeric(10,0) NOT NULL,
  "iUser" numeric(10,0),
  "RespiUser" numeric(10,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT iaccessh_primary PRIMARY KEY ("iAccessH")
) ;
COMMENT ON TABLE iaccessh IS 'History of Guarantor Access table for PatientAccess Patients';
COMMENT ON COLUMN iaccessh."iUser" IS 'iUser that access is for, ptr to IUSER.iUser';
COMMENT ON COLUMN iaccessh."iAccessH" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN iaccessh."RespiUser" IS 'Guarantor that is getting access, ptr to IUSER.iUser';
COMMENT ON COLUMN iaccessh."Deleted" IS 'Is Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN iaccessh."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE iagree (
  "IAGREEDID" numeric(10,0) NOT NULL,
  "IUSER" numeric(10,0),
  "DATEAGREED" timestamp without time zone,
  "TIMEAGREED" numeric(10,0),
  CONSTRAINT iagree_pk PRIMARY KEY ("IAGREEDID")
) ;
COMMENT ON TABLE iagree IS 'Records of patient agreement to PatientAccess Terms of Use';
COMMENT ON COLUMN iagree."TIMEAGREED" IS 'The time that the patient agreed to the Terms of Use, in minutes from midnight. ';
COMMENT ON COLUMN iagree."IUSER" IS 'The PatientAccess user that agreed to the Terms of Use. Ptr to IUSER.Iuser.';
COMMENT ON COLUMN iagree."IAGREEDID" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN iagree."DATEAGREED" IS 'The date that the patient agreed to the Terms of Use.';


CREATE  TABLE idealdet (
  "IdealSchId" numeric(10,0) NOT NULL,
  "ApptCode" character(15) NOT NULL,
  CONSTRAINT idealdet_primary PRIMARY KEY ("IdealSchId", "ApptCode")
) ;
COMMENT ON TABLE idealdet IS 'Ideal Day Schedule detail record';
COMMENT ON COLUMN idealdet."IdealSchId" IS 'Ideal Schedule Record id, ptr to IDEALSCH.Id';
COMMENT ON COLUMN idealdet."ApptCode" IS 'Available appt description code for the schedule, ptr to APPTCODE.ApptCode';


CREATE  TABLE idealit (
  "IdealTmp" character(6) NOT NULL,
  "ApptCode" character(15) NOT NULL,
  CONSTRAINT idealit_primary PRIMARY KEY ("IdealTmp", "ApptCode")
) ;
COMMENT ON TABLE idealit IS 'Ideal Day Template Item record';
COMMENT ON COLUMN idealit."IdealTmp" IS 'Ideal Schedule Template Id, ptr to IDEALTMP.IdealTmp';
COMMENT ON COLUMN idealit."ApptCode" IS 'Appt Description code for the Template, ptr to APPTCODE.ApptCode';


CREATE  TABLE idealsch (
  "Id" numeric(10,0) NOT NULL,
  "WschitemId" numeric(10,0),
  "StartTime" numeric(10,0),
  "EndTime" numeric(10,0),
  "Preferred" character(6),
  "Restricted1" character(6),
  "Restricted2" character(6),
  "Restricted3" character(6),
  "Restricted4" character(6),
  "Deleted" numeric(5,0),
  "AuditId" numeric(10,0),
  "Enforced" numeric(5,0),
  "MaxWaitDays" numeric(5,0),
  "HoldTime" numeric(10,0),
  "ReleaseDays" numeric(5,0),
  "ReleaseTime" numeric(10,0),
  CONSTRAINT idealsch_primary PRIMARY KEY ("Id")
) ;
CREATE INDEX IF NOT EXISTS idealsch_wschitemid ON idealsch USING btree ("WschitemId") TABLESPACE pg_default;
COMMENT ON TABLE idealsch IS 'Ideal Day Schedule record';
COMMENT ON COLUMN idealsch."WschitemId" IS 'Record Id of WorkSchedule Item, ptr to WSCHITEM.Id';
COMMENT ON COLUMN idealsch."StartTime" IS 'Starting time (in minutes from midnight) for this item';
COMMENT ON COLUMN idealsch."Restricted4" IS 'Restricted Discipline (do not want to schedule), ptr to DISCIPL.Discipline';
COMMENT ON COLUMN idealsch."Restricted3" IS 'Restricted Discipline (do not want to schedule), ptr to DISCIPL.Discipline';
COMMENT ON COLUMN idealsch."Restricted2" IS 'Restricted Discipline (do not want to schedule), ptr to DISCIPL.Discipline';
COMMENT ON COLUMN idealsch."Restricted1" IS 'Restricted Discipline (do not want to schedule), ptr to DISCIPL.Discipline';
COMMENT ON COLUMN idealsch."ReleaseTime" IS 'Time it opens up in mins past midnight';
COMMENT ON COLUMN idealsch."ReleaseDays" IS '# days before expiry (not effective in last 2 days)';
COMMENT ON COLUMN idealsch."Preferred" IS 'Preferred Discipline to schedule, ptr to DISCIPL.Discipline';
COMMENT ON COLUMN idealsch."MaxWaitDays" IS 'If Enforced=1, 0=No Limit or N/A, or [1..999]';
COMMENT ON COLUMN idealsch."Id" IS 'Record Id of Ideal Schedule';
COMMENT ON COLUMN idealsch."HoldTime" IS 'Ptr to HOLDTIME.HoldTime';
COMMENT ON COLUMN idealsch."Enforced" IS '0=No, a Preference, 1=Yes, a Rule';
COMMENT ON COLUMN idealsch."EndTime" IS 'Ending time (in minutes from midnight) for this item';
COMMENT ON COLUMN idealsch."Deleted" IS 'Is Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN idealsch."AuditId" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE idealtmp (
  "IdealTmp" character(6) NOT NULL,
  "Description" character(30),
  CONSTRAINT idealtmp_primary PRIMARY KEY ("IdealTmp")
) ;
COMMENT ON TABLE idealtmp IS 'Ideal Day Template record';
COMMENT ON COLUMN idealtmp."IdealTmp" IS 'Ideal Schedule Template code (primary key)';
COMMENT ON COLUMN idealtmp."Description" IS 'Description for template';


CREATE  TABLE idefform (
  "PatType" character(6) NOT NULL,
  "FormCode" character(6) NOT NULL,
  "Access" numeric(5,0),
  "Order" numeric(10,0),
  CONSTRAINT idefform_primary PRIMARY KEY ("PatType", "FormCode")
) ;
COMMENT ON TABLE idefform IS 'Default iForms to be filled out per Patient Type';
COMMENT ON COLUMN idefform."PatType" IS 'Patient Type, ptr to PATTYPE.Pattype';
COMMENT ON COLUMN idefform."Order" IS 'Order number within iForm list (1, 2, 3, … , n)';
COMMENT ON COLUMN idefform."FormCode" IS 'Form Code, Ptr to FORM.Code';
COMMENT ON COLUMN idefform."Access" IS '0=Read Only, 1=Full';


CREATE  TABLE idlschh (
  "IdlSchH" numeric(10,0) NOT NULL,
  "Id" numeric(10,0),
  "WschitemId" numeric(10,0),
  "StartTime" numeric(10,0),
  "EndTime" numeric(10,0),
  "Preferred" character(6),
  "Restricted1" character(6),
  "Restricted2" character(6),
  "Restricted3" character(6),
  "Restricted4" character(6),
  "Deleted" numeric(5,0),
  "AuditId" numeric(10,0),
  "Enforced" numeric(5,0),
  "MaxWaitDays" numeric(5,0),
  "HoldTime" numeric(10,0),
  "ReleaseDays" numeric(5,0),
  "ReleaseTime" numeric(10,0),
  CONSTRAINT idlschh_primary PRIMARY KEY ("IdlSchH")
) ;
CREATE INDEX IF NOT EXISTS idlschh_idealsch ON idlschh USING btree ("Id") TABLESPACE pg_default;
COMMENT ON TABLE idlschh IS 'Audit history for the IDEALSCH table';
COMMENT ON COLUMN idlschh."WschitemId" IS 'Record Id of WorkSchedule Item, ptr to WSCHITEM.Id';
COMMENT ON COLUMN idlschh."StartTime" IS 'Starting time (in minutes from midnight) for this item';
COMMENT ON COLUMN idlschh."Restricted4" IS 'Restricted Discipline (do not want to schedule), ptr to DISCIPL.Discipline';
COMMENT ON COLUMN idlschh."Restricted3" IS 'Restricted Discipline (do not want to schedule), ptr to DISCIPL.Discipline';
COMMENT ON COLUMN idlschh."Restricted2" IS 'Restricted Discipline (do not want to schedule), ptr to DISCIPL.Discipline';
COMMENT ON COLUMN idlschh."Restricted1" IS 'Restricted Discipline (do not want to schedule), ptr to DISCIPL.Discipline';
COMMENT ON COLUMN idlschh."ReleaseTime" IS 'Time it opens up in mins past midnight';
COMMENT ON COLUMN idlschh."ReleaseDays" IS '# days before expiry (not effective in last 2 days)';
COMMENT ON COLUMN idlschh."Preferred" IS 'Preferred Discipline to schedule, ptr to DISCIPL.Discipline';
COMMENT ON COLUMN idlschh."MaxWaitDays" IS 'If Enforced=1, 0=No Limit or N/A, or [1..999]';
COMMENT ON COLUMN idlschh."IdlSchH" IS 'Unique Id to represent this history record, internal Id from sequence';
COMMENT ON COLUMN idlschh."Id" IS 'Record Id of Ideal Schedule';
COMMENT ON COLUMN idlschh."HoldTime" IS 'Ptr to HOLDTIME.HoldTime';
COMMENT ON COLUMN idlschh."Enforced" IS '0=No, a Preference, 1=Yes, a Rule';
COMMENT ON COLUMN idlschh."EndTime" IS 'Ending time (in minutes from midnight) for this item';
COMMENT ON COLUMN idlschh."Deleted" IS 'Is Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN idlschh."AuditId" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE ilog (
  "iLog" numeric(10,0) NOT NULL,
  "UserName" character varying(100),
  "Action" numeric(5,0),
  "Date" timestamp without time zone,
  "Time" numeric(10,0),
  "Terminal" character varying(128),
  "iUser" numeric(10,0),
  CONSTRAINT ilog_primary PRIMARY KEY ("iLog")
) ;
COMMENT ON TABLE ilog IS 'Internet Access Audit';
COMMENT ON COLUMN ilog."iUser" IS 'PatientAccess: Ptr to IUSER.IUser; PatientAccess Admin: Ptr to USER.User; FacultyAccess: Ptr to USER.User';
COMMENT ON COLUMN ilog."iLog" IS 'Primary key, unique ID (from sequence)';
COMMENT ON COLUMN ilog."UserName" IS 'PatientAccess: Ptr to IUSER.UserName; PatientAccess Admin: Ptr to USER.Logon; FacultyAccess: Ptr to USER.Logon';
COMMENT ON COLUMN ilog."Time" IS 'Audit time (in minutes from midnight)';
COMMENT ON COLUMN ilog."Terminal" IS 'Product name';
COMMENT ON COLUMN ilog."Date" IS 'Audit date/time.';
COMMENT ON COLUMN ilog."Action" IS 'Action (0=Login, 1=Logout, 2=Failed, 3=Not Used, 4=Locked, 5=No PA Access, 6=Dependent Patient Deleted, 7=MFA (Success), 8=MFA (Failed))';


CREATE  TABLE implnadd (
  "DeviceId" character varying(255) NOT NULL,
  "Description" character varying(255),
  "BrandName" character varying(255),
  "VersionNumber" character varying(255),
  "CompanyName" character varying(255),
  "MRISafetySts" character varying(255),
  "LabelContainsNRL" character varying(255),
  "LabelNoNRL" character varying(255),
  "DeviceDescription" character varying(255),
  "SizeType" character varying(128),
  "SizeUnit" character varying(128),
  "SizeValue" character varying(128),
  "SizeString" character varying(255),
  "ManualEntry" numeric(5,0),
  CONSTRAINT implnadd_primary PRIMARY KEY ("DeviceId")
) ;
COMMENT ON TABLE implnadd IS 'Table for storing additional implant information';
COMMENT ON COLUMN implnadd."VersionNumber" IS 'Version/Model number';
COMMENT ON COLUMN implnadd."SizeValue" IS 'Device Size Value';
COMMENT ON COLUMN implnadd."SizeUnit" IS 'Device Size Unit';
COMMENT ON COLUMN implnadd."SizeType" IS 'Device Size Type';
COMMENT ON COLUMN implnadd."SizeString" IS 'Device Size String';
COMMENT ON COLUMN implnadd."ManualEntry" IS '0 - Dental Device data is Available in GUIDID; 1 - Manual Entry';
COMMENT ON COLUMN implnadd."MRISafetySts" IS 'MRI Safety Information';
COMMENT ON COLUMN implnadd."LabelNoNRL" IS 'Label for dry natural rubber';
COMMENT ON COLUMN implnadd."LabelContainsNRL" IS 'Label for natural rubber latex';
COMMENT ON COLUMN implnadd."DeviceId" IS 'Device Id (Product Code)';
COMMENT ON COLUMN implnadd."DeviceDescription" IS 'Device Description of the device/product';
COMMENT ON COLUMN implnadd."Description" IS 'Description/Name of the device/product';
COMMENT ON COLUMN implnadd."CompanyName" IS 'Company name';
COMMENT ON COLUMN implnadd."BrandName" IS 'Brand name';


CREATE  TABLE indacc (
  "Indicat" numeric(10,0) NOT NULL,
  "SLevel" numeric(10,0) NOT NULL,
  "Show" numeric(5,0),
  "Order" numeric(5,0),
  CONSTRAINT indacc_primary PRIMARY KEY ("Indicat", "SLevel")
) ;
COMMENT ON TABLE indacc IS 'Status bar indicator access rights by level';
COMMENT ON COLUMN indacc."Show" IS 'If INDICAT.IsIntervention=0 (0=No, 1=On Status Bar, 2=In Indicator Popup), If INDICAT.IsIntervention=1 (0=No, 1=Yes In Intervention Area)';
COMMENT ON COLUMN indacc."SLevel" IS 'Primary key component, ptr to SLEVEL.SLevel';
COMMENT ON COLUMN indacc."Order" IS 'Ordered position of this indicator.';
COMMENT ON COLUMN indacc."Indicat" IS 'Primary key component, ptr to INDICAT.Indicat';


CREATE  TABLE indevent (
  "Indicat" numeric(10,0) NOT NULL,
  "EventId" numeric(5,0) NOT NULL,
  CONSTRAINT indevent_primary PRIMARY KEY ("Indicat", "EventId")
) ;
COMMENT ON TABLE indevent IS 'Intervention Events';
COMMENT ON COLUMN indevent."Indicat" IS 'Primary key component, ptr to INDICAT.Indicat';
COMMENT ON COLUMN indevent."EventId" IS 'Primary key component, Event ID (1=OnSelect, 2=OnCheckIn, 3=OnCheckOut, etc…)';


CREATE  TABLE indicat (
  "Indicat" numeric(10,0) NOT NULL,
  "Description" character varying(50),
  "IndicatorType" numeric(5,0),
  "FunctionName" character varying(50),
  "RefreshTime" numeric(10,0),
  "PatientBased" numeric(5,0),
  "TextColor" numeric(10,0),
  "BackgroundColor" numeric(10,0),
  "Inactive" numeric(5,0),
  "IsIntervention" numeric(5,0),
  "DetailFunction" character varying(50),
  "EventInputData" numeric(5,0) DEFAULT 0,
  "RefreshType" numeric(5,0) DEFAULT 0,
  "NeedAdditionalParams" numeric(5,0),
  CONSTRAINT indicat_primary PRIMARY KEY ("Indicat")
) ;
COMMENT ON TABLE indicat IS 'Status bar indicators';
COMMENT ON COLUMN indicat."TextColor" IS 'If IndicatorType=1 or 2, color to use for the text, as decimal representation of RGB value. ';
COMMENT ON COLUMN indicat."RefreshType" IS 'Clinical intervention refresh type (0 = Do not refresh, 1 = Refresh, 2 = Refresh after events have occurred)';
COMMENT ON COLUMN indicat."RefreshTime" IS 'Time between indicator refreshes, in seconds.';
COMMENT ON COLUMN indicat."PatientBased" IS 'Pass PATIENT.Patient to Oracle function? (0=User Based, 1=Patient Based, 2=Controllable, 3=Notification)';
COMMENT ON COLUMN indicat."NeedAdditionalParams" IS 'For indicating additional input data parameters needed for the controllable events (0 = No, 1 = Yes).';
COMMENT ON COLUMN indicat."IsIntervention" IS 'Clinical intervention type (0=No, 1=Yes)';
COMMENT ON COLUMN indicat."IndicatorType" IS 'If IsIntervention=0 (0=Image, 1=Text (Mapped), 2=Text (Returned)), If IsIntervention=1 (1=Text (Mapped))';
COMMENT ON COLUMN indicat."Indicat" IS 'Primary key, unique ID from sequence';
COMMENT ON COLUMN indicat."Inactive" IS 'Indicator is inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN indicat."FunctionName" IS 'Name of the Oracle function used to calculate the indicator.';
COMMENT ON COLUMN indicat."EventInputData" IS 'For patient-based and controllable/notification events, the input data required for the indicator function(0 = Patient ID, 1 = Treatment, 2 = Appointment, 3 = Approval Request, 4 = Care Quality Notification).';
COMMENT ON COLUMN indicat."DetailFunction" IS 'Function for showing additional indicator information';
COMMENT ON COLUMN indicat."Description" IS 'Description of the indicator';
COMMENT ON COLUMN indicat."BackgroundColor" IS 'If IndicatorType=1 or 2, color to use for the background, as decimal representation of RGB value. ';


CREATE  TABLE indicath (
  "IndicatH" numeric(10,0) NOT NULL,
  "Indicat" numeric(10,0),
  "Description" character varying(50),
  "IndicatorType" numeric(5,0),
  "FunctionName" character varying(50),
  "RefreshTime" numeric(10,0),
  "PatientBased" numeric(5,0),
  "TextColor" numeric(10,0),
  "BackgroundColor" numeric(10,0),
  "Inactive" numeric(5,0),
  "Deleted" numeric(5,0),
  "IsIntervention" numeric(5,0),
  "ModifiedDate" timestamp without time zone,
  "DetailFunction" character varying(50),
  "EventInputData" numeric(5,0) DEFAULT 0,
  "RefreshType" numeric(5,0) DEFAULT 0,
  CONSTRAINT indicath_primary PRIMARY KEY ("IndicatH")
) ;
COMMENT ON TABLE indicath IS 'Status bar indicator history';
COMMENT ON COLUMN indicath."TextColor" IS 'If IndicatorType=1 or 2, color to use for the text, as decimal representation of RGB value. ';
COMMENT ON COLUMN indicath."RefreshType" IS 'Clinical intervention refresh type (0 = Do not refresh, 1 = Refresh, 2 = Refresh after events have occurred)';
COMMENT ON COLUMN indicath."RefreshTime" IS 'Time between indicator refreshes, in seconds.';
COMMENT ON COLUMN indicath."PatientBased" IS 'Pass PATIENT.Patient to Oracle function? (0=User Based, 1=Patient Based, 2=Controllable, 3=Notification)';
COMMENT ON COLUMN indicath."ModifiedDate" IS 'Date the indicator was modified';
COMMENT ON COLUMN indicath."IsIntervention" IS 'Clinical intervention type (0=No, 1=Yes)';
COMMENT ON COLUMN indicath."IndicatorType" IS 'If IsIntervention=0 (0=Image, 1=Text (Mapped), 2=Text (Returned)), If IsIntervention=1 (1=Text (Mapped))';
COMMENT ON COLUMN indicath."IndicatH" IS 'Primary key, unique ID from sequence';
COMMENT ON COLUMN indicath."Indicat" IS 'Indicat ID, ptr to INDICAT.Indicat';
COMMENT ON COLUMN indicath."Inactive" IS 'Indicator is inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN indicath."FunctionName" IS 'Name of the Oracle function used to calculate the indicator.';
COMMENT ON COLUMN indicath."EventInputData" IS 'For patient-based and controllable/notification events, the input data required for the indicator function(0 = Patient ID, 1 = Treatment, 2 = Appointment, 3 = Approval Request, 4 = Care Quality Notification).';
COMMENT ON COLUMN indicath."DetailFunction" IS 'Function for showing additional indicator information';
COMMENT ON COLUMN indicath."Description" IS 'Description of the indicator';
COMMENT ON COLUMN indicath."Deleted" IS 'Indicator was deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN indicath."BackgroundColor" IS 'If IndicatorType=1 or 2, color to use for the background, as decimal representation of RGB value. ';


CREATE  TABLE inditem (
  "Indicat" numeric(10,0) NOT NULL,
  "Value" numeric(5,0) NOT NULL,
  "Tooltip" character varying(30),
  image bytea,
  "DisplayText" character(3),
  "TextColor" numeric(10,0),
  "BackgroundColor" numeric(10,0),
  "InterventionText" character varying(4000),
  "IntSeverity" numeric(5,0),
  "IntDegree" numeric(5,0),
  CONSTRAINT inditem_primary PRIMARY KEY ("Indicat", "Value")
) ;
COMMENT ON TABLE inditem IS 'Status bar indicator values';
COMMENT ON COLUMN inditem.image IS 'If INDICAT.IndicatorType=0, the image to display for this value.';
COMMENT ON COLUMN inditem."Value" IS 'Primary key component, discrete value returned by INDICAT.FunctionName function.';
COMMENT ON COLUMN inditem."Tooltip" IS 'Description of the value.';
COMMENT ON COLUMN inditem."TextColor" IS 'If INDICAT.IndicatorType=1, color to use for the text for this value, as decimal representation of RGB value. ';
COMMENT ON COLUMN inditem."InterventionText" IS 'Text to display to the provider';
COMMENT ON COLUMN inditem."IntSeverity" IS 'Indicator severity (0=Mild/informative, 1=Mod, 2=Severe)';
COMMENT ON COLUMN inditem."IntDegree" IS 'For controllable events, specifies the degree of a response (0=N/A, 1=Warning, user can continue, 2= Error, user cannot continue)';
COMMENT ON COLUMN inditem."Indicat" IS 'Primary key component, ptr to INDICAT.Indicat';
COMMENT ON COLUMN inditem."DisplayText" IS 'If INDICAT.IndicatorType=1, the text to displaly for this value.';
COMMENT ON COLUMN inditem."BackgroundColor" IS 'If INDICAT.IndicatorType=1, color to use for the background for this value, as decimal representation of RGB value. ';


CREATE  TABLE indlog (
  "IndLog" numeric(10,0) NOT NULL,
  "Indicat" numeric(10,0) NOT NULL,
  "Value" numeric(5,0),
  "Patient" numeric(10,0),
  "State" numeric(5,0),
  "Severity" numeric(5,0),
  "Text" character varying(4000),
  "Audit" numeric(10,0),
  "Details" character varying(4000),
  "Degree" numeric(5,0),
  CONSTRAINT indlog_primary PRIMARY KEY ("IndLog", "Indicat")
) ;
CREATE INDEX IF NOT EXISTS indlog_audit ON indlog USING btree ("Audit") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS indlog_patient ON indlog USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE indlog IS 'Intervention log table';
COMMENT ON COLUMN indlog."Value" IS 'INDITEM.Value (directly related to intervention)';
COMMENT ON COLUMN indlog."Text" IS 'Text to display to the provider';
COMMENT ON COLUMN indlog."State" IS 'Intervention state, 0=None, 1=Detected, 2=Displayed, 3=Dismissed';
COMMENT ON COLUMN indlog."Severity" IS 'Intervention severity, 0=Mild/informative, 1=Mod, 2=Severe';
COMMENT ON COLUMN indlog."Patient" IS 'If INDICAT.PatientBased=1, ptr to PATIENT.Patient';
COMMENT ON COLUMN indlog."Indicat" IS 'Primary key component, ptr to INDICAT.Indicat';
COMMENT ON COLUMN indlog."IndLog" IS 'Primary key component, unique ID from sequence';
COMMENT ON COLUMN indlog."Details" IS 'Optional Details that were displayed to the provider';
COMMENT ON COLUMN indlog."Degree" IS 'For controllable events, specifies the degree of a response. (0=N/A, 1=Warning, user can continue, 2=Error, user cannot continue)';
COMMENT ON COLUMN indlog."Audit" IS 'Audit record, ptr to AUDITHIS.Audit.';


CREATE  TABLE infopacc (
  "InfoProc" numeric(10,0) NOT NULL,
  "SLevel" numeric(10,0) NOT NULL,
  "Access" numeric(5,0),
  CONSTRAINT infopacc_primary PRIMARY KEY ("InfoProc", "SLevel")
) ;
COMMENT ON TABLE infopacc IS 'Info Manager Process Access';
COMMENT ON COLUMN infopacc."SLevel" IS 'Primary key component, the security level that access is being defined for. Ptr to SLEVEL.SLevel';
COMMENT ON COLUMN infopacc."InfoProc" IS 'Primary key component, the Info Manager Process that access is being defined for. Ptr to INFOPROC.InfoProc';
COMMENT ON COLUMN infopacc."Access" IS 'Level has access? (0=No, 1=Yes)';


CREATE  TABLE infoproc (
  "InfoProc" numeric(10,0) NOT NULL,
  "Description" character varying(30),
  "Procedure" character varying(50),
  "Warning" character varying(500),
  "CreateUser" numeric(10,0),
  "CreateDate" timestamp without time zone,
  "SendFirstColAsParam" numeric(5,0),
  CONSTRAINT infoproc_primary PRIMARY KEY ("InfoProc")
) ;
COMMENT ON TABLE infoproc IS 'Info Manager Processes';
COMMENT ON COLUMN infoproc."Warning" IS 'Warning text to display prior to execution.';
COMMENT ON COLUMN infoproc."SendFirstColAsParam" IS 'Send the first column of the Info Manager column as a parameter to the procedure? (0=No, 1=Yes)';
COMMENT ON COLUMN infoproc."Procedure" IS 'Name of the PL/SQL procedure to execute. ';
COMMENT ON COLUMN infoproc."InfoProc" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN infoproc."Description" IS 'Description of the procedure.';
COMMENT ON COLUMN infoproc."CreateUser" IS 'User that created the process record, ptr to USERS.User';
COMMENT ON COLUMN infoproc."CreateDate" IS 'Date that the process record was created.';


CREATE  TABLE inidef (
  "Inidef" numeric(10,0) NOT NULL,
  "Module" character varying(25),
  "Section" character varying(20),
  "Key" character varying(30),
  "Type" numeric(5,0),
  "Description" character varying(4000),
  "Values" character varying(4000),
  "Default" character varying(4000),
  "SetBy" character varying(100),
  "FieldName" character varying(100),
  "Comment" character varying(4000),
  "DefaultDesc" character varying(100),
  CONSTRAINT inidef_primary PRIMARY KEY ("Inidef")
) ;
COMMENT ON TABLE inidef IS 'Table for defining ALL of the various INI entries';
COMMENT ON COLUMN inidef."Values" IS 'List of values (with descritpion of the value) that can be used for settign this station option';
COMMENT ON COLUMN inidef."Type" IS 'Type of entry (0 = Numeric, 1 = String)';
COMMENT ON COLUMN inidef."SetBy" IS 'Event / Name of dialog field set from (optional)';
COMMENT ON COLUMN inidef."Section" IS '[Section] of the former ini file, like Chart Settings, Card, etc…';
COMMENT ON COLUMN inidef."Module" IS 'Module this setting is found in. Like Chart Tracking, Scheduler, etc…';
COMMENT ON COLUMN inidef."Key" IS 'Key from the former ini file, Like ActiveStatus, Bill, etc..';
COMMENT ON COLUMN inidef."Inidef" IS 'Unique Id code to represent this ini file definition. Internal Id from sequence';
COMMENT ON COLUMN inidef."FieldName" IS 'If SetBy is a window name, the field name';
COMMENT ON COLUMN inidef."Description" IS 'Description of the station options purpose';
COMMENT ON COLUMN inidef."DefaultDesc" IS 'Description of default value for station options ';
COMMENT ON COLUMN inidef."Default" IS 'Default value.';
COMMENT ON COLUMN inidef."Comment" IS 'User comment about the field';


CREATE  TABLE iniitem (
  "Iniset" numeric(10,0) NOT NULL,
  "Inidef" numeric(10,0) NOT NULL,
  "ValueNum" numeric(10,0),
  "ValueStr" character varying(4000),
  CONSTRAINT iniitem_primary PRIMARY KEY ("Iniset", "Inidef")
) ;
COMMENT ON TABLE iniitem IS 'Table for defining subset details of the various INI entries';
COMMENT ON COLUMN iniitem."ValueStr" IS 'If INIDEF.Type = 1, the value';
COMMENT ON COLUMN iniitem."ValueNum" IS 'If INIDEF.Type = 0, the value';
COMMENT ON COLUMN iniitem."Iniset" IS 'Id code of the parent the item belongs to, copy of INISET.Iniset';
COMMENT ON COLUMN iniitem."Inidef" IS 'Id code of the inidef record this item belongs to, copy of INIDEF.Inidef ';


CREATE  TABLE iniset (
  "Iniset" numeric(10,0) NOT NULL,
  "IsTemplate" numeric(5,0),
  "Description" character varying(50),
  "Station" numeric(10,0),
  CONSTRAINT iniset_primary PRIMARY KEY ("Iniset")
) ;
COMMENT ON TABLE iniset IS 'Table for defining (sub)sets of the various INI entries';
COMMENT ON COLUMN iniset."Station" IS 'if IsTemplate = 0, STATION.StationId';
COMMENT ON COLUMN iniset."IsTemplate" IS 'Is template? (0 = No, 1 = Yes)';
COMMENT ON COLUMN iniset."Iniset" IS 'Unique Id code to represent this set. Internal Id from sequence';
COMMENT ON COLUMN iniset."Description" IS 'if IsTemplate = 0, Station name else Template name';


CREATE  TABLE insadjop (
  "Company" character(6) NOT NULL,
  "PayeeIdCode" character(15) NOT NULL,
  "PmtAutoProcess" numeric(5,0),
  "PmtAutoAdjust" character(6),
  "MinAutoTransferAmt" numeric,
  "WOffAutoAdjust" character(6),
  "OverpayAutoProcess" numeric(5,0),
  "OverpayAutoAdjust" character(6),
  CONSTRAINT insadjop_pk PRIMARY KEY ("Company", "PayeeIdCode")
) ;
COMMENT ON TABLE insadjop IS 'Insurance adjustment options.';
COMMENT ON COLUMN insadjop."WOffAutoAdjust" IS 'If PmtAutoProcess  = 1, Adjustment code to for writeoffs. Ptr to ADJUST.Adjust.';
COMMENT ON COLUMN insadjop."PmtAutoProcess" IS 'Automatic payment processing? (0 = No, 1 = Auto transfer, 2 = Auto write-off, US only: 3 = Intelli-Adjustments)';
COMMENT ON COLUMN insadjop."PmtAutoAdjust" IS 'If PmtAutoProcess > 0, the adjustment code to use for auto-processing.';
COMMENT ON COLUMN insadjop."PayeeIdCode" IS 'Primary key component, payee code.';
COMMENT ON COLUMN insadjop."OverpayAutoProcess" IS 'Method of automatically handling overpayments (0 = Leave credit, 1 = Transfer to patient, 2 = Write-up credit, US only: 3 = Intelli-Adjustments)';
COMMENT ON COLUMN insadjop."OverpayAutoAdjust" IS 'If OverPayAutoProcess = 1 or 2, Adjustment code to use for overpayments.';
COMMENT ON COLUMN insadjop."MinAutoTransferAmt" IS 'If PmtAutoProcess  = 1, Mimimum amount.';
COMMENT ON COLUMN insadjop."Company" IS 'Primary key, insurance company this applies to. Ptr to INSURANC.Company.';


CREATE  TABLE insedi (
  "Company" character(6) NOT NULL,
  "TxFlags" character varying(16),
  "TxCounter" numeric(10,0),
  "Encryption" numeric(5,0),
  CONSTRAINT insedi_primary PRIMARY KEY ("Company")
) ;
COMMENT ON TABLE insedi IS 'Insurance company "EDI" setup for CDANet (Canada only)';
COMMENT ON COLUMN insedi."TxFlags" IS 'EDI flags per record type (0=No, 1=Yes)';
COMMENT ON COLUMN insedi."TxCounter" IS 'Counter, field A09';
COMMENT ON COLUMN insedi."Encryption" IS 'Encryption method for "EDI" (0=None, 1=Method 1, 2=Method 2), field A10';
COMMENT ON COLUMN insedi."Company" IS 'Primary key, insurance company this applies to. Ptr to INSURANC.Company';


CREATE  TABLE insgroup (
  "ParentCompany" character(6) NOT NULL,
  "Company" character(6) NOT NULL,
  CONSTRAINT insgroup_primary PRIMARY KEY ("ParentCompany", "Company")
) ;
COMMENT ON TABLE insgroup IS 'Insurance Company Groups';
COMMENT ON COLUMN insgroup."ParentCompany" IS 'Primary key component, ID of the parent insurance company for the group. Ptr to INSURANC.Company';
COMMENT ON COLUMN insgroup."Company" IS 'Primary key component, ID of the child insurance company. Ptr to INSURANC.Company';


CREATE  TABLE insproc (
  "Procedure" character(7) NOT NULL,
  "Company" character(6) NOT NULL,
  "NeedAuth" numeric(5,0),
  "EDIExempt" numeric(5,0),
  "NoDeductible" numeric(5,0),
  "NoCopay" numeric(5,0),
  "OralCavity" numeric(5,0),
  "ICDRequired" numeric(5,0),
  "NeedAttach" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT insproc_primary PRIMARY KEY ("Procedure", "Company")
) ;
COMMENT ON TABLE insproc IS 'Insurance Company Procedures';
COMMENT ON COLUMN insproc."Procedure" IS 'Primary key component, procedure code. Ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN insproc."OralCavity" IS 'Mapped oral cavity (0 = None, 1 = ISO Quadrant, 2 = ISO Arch, 3 = Additional Details)';
COMMENT ON COLUMN insproc."NoDeductible" IS 'Procedure has deductable exemption? (0 = No, 1 = Yes)';
COMMENT ON COLUMN insproc."NoCopay" IS 'Procedure has co-pay exemption? (0 = No, 1 = Yes)';
COMMENT ON COLUMN insproc."NeedAuth" IS 'Procedure requires pre-authorization? (0 = No, 1 = Yes)';
COMMENT ON COLUMN insproc."NeedAttach" IS 'Procedure needs NEA attachment? (0 = No, 1 = Yes. 2=No and persists)';
COMMENT ON COLUMN insproc."ICDRequired" IS 'Is an ICD code required for this procedure? (0=No, 1=Yes - if INSURANC.ICDRequired=1 for the insurance company)';
COMMENT ON COLUMN insproc."EDIExempt" IS 'Procedure is "EDI" Exempt? (0 = No, 1 = Yes)';
COMMENT ON COLUMN insproc."Company" IS 'Primary key component, insurance company. Ptr to INSURANC.Company';


CREATE  TABLE inssite (
  "Company" character(6) NOT NULL,
  "Type" numeric(5,0) NOT NULL,
  "MapFrom" character(3) NOT NULL,
  "MapTo" character(3),
  CONSTRAINT inssite_primary PRIMARY KEY ("Company", "Type", "MapFrom")
) ;
COMMENT ON TABLE inssite IS 'Claim Form Exceptions';
COMMENT ON COLUMN inssite."Type" IS 'Primary key component, type this applies to (0 = Site, 1 = Surface, 2 = all Surfaces)';
COMMENT ON COLUMN inssite."MapTo" IS 'Letter or number that should print on the claim form for this site or surface (how you want it to appear on the form)';
COMMENT ON COLUMN inssite."MapFrom" IS 'Current letter or number for the site or surface (how it appears within Axium)';
COMMENT ON COLUMN inssite."Company" IS 'Primary key component, insurance company that the exception applies to. Ptr to INSURANC.Company';


CREATE  TABLE instrumt (
  "Instrument" character(6) NOT NULL,
  "Description" character varying(60),
  "LifeCycle" numeric(10,0),
  "Amount" numeric,
  "Inactive" numeric(5,0),
  CONSTRAINT instrumt_primary PRIMARY KEY ("Instrument")
) ;
COMMENT ON TABLE instrumt IS 'Dispensary instrument information record';
COMMENT ON COLUMN instrumt."LifeCycle" IS 'Number indicating the expected life cycle of the instrument (number of uses before it is considered to be out of service)';
COMMENT ON COLUMN instrumt."Instrument" IS 'Id code to identify this instrument';
COMMENT ON COLUMN instrumt."Inactive" IS '0 = No, 1 = Yes';
COMMENT ON COLUMN instrumt."Description" IS 'Description of the instrument';
COMMENT ON COLUMN instrumt."Amount" IS 'Replacement cost for this item.';


CREATE  TABLE insuranc (
  "Company" character(6) NOT NULL,
  "EDI" character(6),
  "Name" character(50),
  "Address1" character(30),
  "Address2" character(30),
  "City" character(24),
  "Province" character(6),
  "Postal" character(15),
  "Area" character(4),
  "Telephone" character(8),
  "Ext" character varying(6),
  "Contact" character(30),
  "Note" character varying(4000),
  "Signature" numeric(5,0),
  "Consolidate" numeric(5,0),
  "Assign" numeric(5,0),
  "Form" numeric(10,0),
  "Claim" character(6),
  "EDIFlag" numeric(5,0),
  "OverCharge" numeric(5,0),
  "WriteOff" numeric(5,0),
  "GovPolicy" character(6),
  "DefaultFee" character(6),
  "BillGovtFee" numeric(5,0),
  "Service" character(6),
  "AddressOther" character(15),
  "SubmitPatient" numeric(5,0),
  "PlanType" numeric(5,0),
  "MedicalType" character(2),
  "OrthoCycle" numeric(5,0),
  "PlanInitProcedure" character(7),
  "PlanRegProcedure" character(7),
  "RoundUpEstimate" numeric(5,0),
  "CvgType" numeric(5,0),
  "AllPayor" numeric(5,0),
  "UseAltCode" numeric(5,0),
  "PreAuthComment" character varying(200),
  "AssignComment" character varying(200),
  "NonAssignComment" character varying(200),
  "ReqCompPreAuth" numeric(5,0),
  "TJInsCarrier" character(6),
  "EDIOffId" character varying(4),
  "CIF" numeric(10,0),
  "CoverageAge" numeric(5,0),
  "CoverageAgeStud" numeric(5,0),
  "LimitedVisits" numeric(5,0),
  "VisitsPerYear" numeric(5,0),
  "EDIFormat" numeric(5,0),
  "EDIClaims" numeric(5,0),
  "PmtAutoProcess" numeric(5,0),
  "PmtAutoAdjust" character(6),
  "Inactive" numeric(5,0),
  "IsParent" numeric(5,0),
  "PrintTreatingDrId" numeric(5,0),
  "ChildCoverage" numeric(10,0),
  "AdultCoverage" numeric(10,0),
  "Copay" numeric,
  "NoPayMedicaid" numeric(5,0),
  "ClaimGrpFlag" numeric(5,0),
  "GovtBillZero" numeric(5,0),
  "ApprovalRequired" numeric(5,0),
  "Qualifier" character varying(2),
  "PreAuth" numeric(10,0),
  "NotCoveredWarning" numeric(5,0),
  "NotCoveredText" character varying(200),
  "ReqdPreAuthOnly" numeric(5,0),
  "PrintCustomaryTotal" numeric(5,0),
  "PrintGrpNPI" numeric(5,0),
  "PrintSubscriberId" numeric(5,0),
  "OrthoClaims" numeric(5,0),
  "MedicaidProgram" numeric(5,0),
  "HasVisitFees" numeric(5,0),
  "WaiveDualDeduct" numeric(5,0),
  "LimitedDeducts" numeric(5,0),
  "DeductFactor" numeric(5,0),
  "EDISecondaryClaims" numeric(5,0),
  "EDIPayerToPayer" numeric(5,0),
  "ReserveFunds" numeric(5,0),
  "ICDType" numeric(5,0),
  "HasRiderPlans" numeric(5,0),
  "NPI" character varying(10),
  "ICDRequired" numeric(5,0),
  "MinAutoTransferAmt" numeric,
  "WOffAutoAdjust" character(6),
  "OverpayAutoProcess" numeric(5,0),
  "OverpayAutoAdjust" character(6),
  "Network" character(6),
  "EligFormat" numeric(5,0),
  "EDICode2" character varying(10),
  "EDICode3" character varying(10),
  "EligUserID" character varying(100),
  "EligPassword" character varying(100),
  "NeedsEligUserID" numeric(5,0),
  "NeedsEligPassword" numeric(5,0),
  "EDIOverPayMode" numeric(5,0),
  "EDIUnderPayMode" numeric(5,0),
  "PartCoveredWarning" numeric(5,0),
  "PartCoveredText" character varying(200),
  "SubmitZeroDollar" numeric(5,0),
  "CoverageAgeYoungAdult" numeric(5,0),
  "YoungAdultCoverage" numeric(10,0),
  "CvgOnBirthdate" numeric(5,0),
  "UsePracticeEDI" numeric(5,0) NOT NULL DEFAULT 0,
  "NEAImportAudit" numeric(10,0) NOT NULL DEFAULT 0,
  "ChargeDedAndPtChg" numeric(5,0) NOT NULL DEFAULT 0,
  "OnlyCoveredOnClaim" numeric(5,0),
  CONSTRAINT insuranc_primary PRIMARY KEY ("Company")
) ;
CREATE INDEX IF NOT EXISTS insuranc_assign ON insuranc USING btree ("Assign") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS insuranc_tjinscarrierkey ON insuranc USING btree ("TJInsCarrier" DESC) TABLESPACE pg_default;
COMMENT ON TABLE insuranc IS 'Insurance Company Codes';
COMMENT ON COLUMN insuranc."YoungAdultCoverage" IS 'Id code of the coverage template for young adult, ptr to COVERAGE.Coverage';
COMMENT ON COLUMN insuranc."WriteOff" IS 'Allow write-off? (0 = No, 1 = Yes)';
COMMENT ON COLUMN insuranc."WaiveDualDeduct" IS '0=No, 1=Yes(smaller deduct. waived)';
COMMENT ON COLUMN insuranc."WOffAutoAdjust" IS 'If PmtAutoProcess = 1, adjustment code to for writeoffs. Ptr to ADJUST.Adjust';
COMMENT ON COLUMN insuranc."VisitsPerYear" IS 'If INSURANC.LimitedVisits = 1, number of visits allowed per year (1..99)';
COMMENT ON COLUMN insuranc."UsePracticeEDI" IS 'Option to determine whether to use Producer "EDI" or practice ED for submission (0=Producer, 1=Practice)';
COMMENT ON COLUMN insuranc."UseAltCode" IS 'Use alternate code? (0 = No, 1 = Yes) For Dentical Insurance companies.';
COMMENT ON COLUMN insuranc."Telephone" IS 'Telephone number';
COMMENT ON COLUMN insuranc."TJInsCarrier" IS 'Trojan carrier code';
COMMENT ON COLUMN insuranc."SubmitZeroDollar" IS 'Allow submission of $0 claims? (0=No [default], 1=Yes [for procedures defined to print if total=$0])';
COMMENT ON COLUMN insuranc."SubmitPatient" IS 'Submit to Vektis? (0 = No, 1 = Yes) For ACTA only';
COMMENT ON COLUMN insuranc."Signature" IS 'Claim forms require a patients signature? (0 = No, 1 = Yes)';
COMMENT ON COLUMN insuranc."Service" IS 'Service Type, ptr to SERVICE.Code';
COMMENT ON COLUMN insuranc."RoundUpEstimate" IS 'Round up amounts? (0 = No, 1 = Yes)';
COMMENT ON COLUMN insuranc."ReserveFunds" IS 'Track patient reserve funds? (0 = No, 1 = Yes)';
COMMENT ON COLUMN insuranc."ReqdPreAuthOnly" IS 'Only submit those txs that require pre-auth? (0 =No, 1=Yes)';
COMMENT ON COLUMN insuranc."ReqCompPreAuth" IS '(0 = No, 1 = Yes), Defaults to 0';
COMMENT ON COLUMN insuranc."Qualifier" IS 'ID prefix for claim form submisson';
COMMENT ON COLUMN insuranc."Province" IS 'Province / state, ptr to PROVINCE.Province';
COMMENT ON COLUMN insuranc."PrintTreatingDrId" IS 'Print the treating doctor Id on the HCFA claim form? (0 = No, 1 = Yes). Set to 1 for Michigan, West Virginia, California and Massachusetts claims';
COMMENT ON COLUMN insuranc."PrintSubscriberId" IS 'Flag for special claim form printing related to box 23 of ADA forms. 0 = No, 1 = Yes - to print Subscriber Id or not.';
COMMENT ON COLUMN insuranc."PrintGrpNPI" IS 'Print Group "NPI" (0 = No, 1 = Yes)';
COMMENT ON COLUMN insuranc."PrintCustomaryTotal" IS 'Print Customary Total (0 = No, 1 = Yes)';
COMMENT ON COLUMN insuranc."PreAuthComment" IS 'Comment to print on pre-authorized claims. Defaults to "This is for Pre-Authorization Only"';
COMMENT ON COLUMN insuranc."PreAuth" IS 'New form field to use when submitting planned treatments';
COMMENT ON COLUMN insuranc."Postal" IS 'Postal / zip code, ptr to CITY.Postal';
COMMENT ON COLUMN insuranc."PmtAutoProcess" IS 'Automatic payment processing? (0 = No, 1 = Auto transfer, 2 = Auto write-off, US only: 3 = Intelli-Adjustments, 4 = Transfer + "EDI" Intelli-Adj, 5 = Write-off + "EDI" Intelli-Adj)';
COMMENT ON COLUMN insuranc."PmtAutoAdjust" IS 'If PmtAutoProcess is greater than 0, the adjustment code to use for auto-processing. ';
COMMENT ON COLUMN insuranc."PlanType" IS 'Insurance plan type (for claim forms). (0 = Not applicable, 1=SelfPay, 2=Workers Compensation, 3=Medicare, 4=Medicaid, 5=Other Federal Program, 6=Commercial, 7=BlueCross, 8=CHAMPUS, 9=Other, 10=PPO, 11=POS,12=EPO, 13=Indemnity Ins, 14=HMO Medicare Risk, 15=Dental Maint. Org., 16=Disability, 17=Fed Employees Prog., 18=HMO, 19=Liability, 20=Managed Care, 21=Self Admin. Gp., 22=Veteran, 23=Mutually Defined)';
COMMENT ON COLUMN insuranc."PlanRegProcedure" IS 'Ortho Billing Monthly Fee code, ptr to PROCEDUR.Procedure ';
COMMENT ON COLUMN insuranc."PlanInitProcedure" IS 'Ortho Billing Initial Fee code, ptr to PROCEDUR.Procedure ';
COMMENT ON COLUMN insuranc."PartCoveredWarning" IS 'Warning for partially non-covered services? (0 = No (default), 1 = On Add, 2 = On Approval, 3 = Both)';
COMMENT ON COLUMN insuranc."PartCoveredText" IS 'Warning text for partially non-covered services';
COMMENT ON COLUMN insuranc."OverpayAutoProcess" IS 'Method of automatically handling overpayments (0 = leave credit, 1 = transfer to patient, 2 = write-up credit, US only: 3 = Intelli-Adjustments, 4 = Transfer + "EDI" Intelli-Adj, 5 = Write-up + "EDI" Intelli-Adj)';
COMMENT ON COLUMN insuranc."OverpayAutoAdjust" IS 'If OverPayAutoProcess = 1 or 2, adjustment code to use for overpayments. Ptr to ADJUST.Adjust';
COMMENT ON COLUMN insuranc."OverCharge" IS 'Allow overcharge? (0 = No, 1 = Yes)';
COMMENT ON COLUMN insuranc."OrthoCycle" IS 'Ortho cycle (0 = Plan period, 1 = Monthly, 2 = Quarterly, 3 = Semi-annually)';
COMMENT ON COLUMN insuranc."OrthoClaims" IS '0 - No,1 - With current plan fee,2 - With treatment total, 3 - With treatment total on 1st, claim; plan fee thereafter';
COMMENT ON COLUMN insuranc."OnlyCoveredOnClaim" IS 'Only submit covered services on claims. (0=No, 1=Yes)';
COMMENT ON COLUMN insuranc."Note" IS 'Text field to enter comments / notes';
COMMENT ON COLUMN insuranc."NotCoveredWarning" IS 'Warn if services are not covered? (0 = No, 1 = On add, 2 = On approval, 3 = Both)';
COMMENT ON COLUMN insuranc."NotCoveredText" IS 'If NotCoveredWarning is is greater than 0, the warning to display if the procedure is not covered by the Insurance company';
COMMENT ON COLUMN insuranc."NonAssignComment" IS 'Comment to print on non-assignment claims. Defaults to "Please PayPatient"';
COMMENT ON COLUMN insuranc."NoPayMedicaid" IS 'Insurance company does not cover Medicaid claims/services? (0=No [covers], 1=Yes [does not cover])';
COMMENT ON COLUMN insuranc."Network" IS 'Network centre for "EDI" (Canada only)';
COMMENT ON COLUMN insuranc."NeedsEligUserID" IS 'Is EligUserID required? (0=No, 1=Yes)';
COMMENT ON COLUMN insuranc."NeedsEligPassword" IS 'Is EligPassword required? (0=No, 1=Yes)';
COMMENT ON COLUMN insuranc."Name" IS 'Full name of the insurance company';
COMMENT ON COLUMN insuranc."NPI" IS 'Insurance company "NPI"';
COMMENT ON COLUMN insuranc."NEAImportAudit" IS 'Audit for when import was done for this insurance company, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN insuranc."MinAutoTransferAmt" IS 'If PmtAutoProcess = 1, mimimum amount';
COMMENT ON COLUMN insuranc."MedicalType" IS 'Medical type (for claim form printing)';
COMMENT ON COLUMN insuranc."MedicaidProgram" IS 'Limited Visit Billing Method for Medicaid (0=Rate-based, 1= APG Method)';
COMMENT ON COLUMN insuranc."LimitedVisits" IS 'Limited visits? (0 = No, 1 = Yes)';
COMMENT ON COLUMN insuranc."LimitedDeducts" IS 'Limit the number of times that the patient deductable is charged per family? (0=No, 1=Yes)';
COMMENT ON COLUMN insuranc."IsParent" IS 'This company is a parent company (0 = No, 1 = Yes) ';
COMMENT ON COLUMN insuranc."Inactive" IS 'Insurance company record is inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN insuranc."ICDType" IS 'Diagnosis code ICD type? (0=ICD-9, 1=ICD-10)';
COMMENT ON COLUMN insuranc."ICDRequired" IS 'Are ICD codes required for medical claims? (0=No, 1=Yes)';
COMMENT ON COLUMN insuranc."HasVisitFees" IS 'Charge patient visit fees? (0=No, 1=Yes)';
COMMENT ON COLUMN insuranc."HasRiderPlans" IS 'Benefit plans have optional rider coverage? (0=No, 1=Yes)';
COMMENT ON COLUMN insuranc."GovtBillZero" IS 'Bill $0.00 amounts? (0 = No, Bill Office fees to the Patient, 1 = Yes, bill $0.00 if fee guide is $0) ';
COMMENT ON COLUMN insuranc."GovPolicy" IS 'Optional, ID code of the government policy. Ptr to POLICYCO.GovPolicy.';
COMMENT ON COLUMN insuranc."Form" IS 'Type of form, ptr to CFORMCD.CFormCdId';
COMMENT ON COLUMN insuranc."Ext" IS 'Telephone extension';
COMMENT ON COLUMN insuranc."EligUserID" IS 'Encrypted user ID for patient eligibility';
COMMENT ON COLUMN insuranc."EligPassword" IS 'Encrypted password for patient eligibility';
COMMENT ON COLUMN insuranc."EligFormat" IS 'Eligibility format (0=N/A, 1=X12N 5010) (US only)';
COMMENT ON COLUMN insuranc."EDIUnderPayMode" IS 'EDI Underpayment mode (0 = Use system default, 1 = Add payment / no adjustments,  2 = Change tx to match, 3 = Change tx total to match, 4 = Adjust (based on Ins))';
COMMENT ON COLUMN insuranc."EDISecondaryClaims" IS 'Allow secondary "EDI" claims? (0=No, 1=Yes)';
COMMENT ON COLUMN insuranc."EDIPayerToPayer" IS 'Support Payer-to-Payer COB? (0=No, 1=Yes)';
COMMENT ON COLUMN insuranc."EDIOverPayMode" IS 'EDI Overpayment mode (0 = Use system default, 1 = Add payment / no adjustments,  2 = Change tx to match, 3 = Change tx total to match, 4 = Adjust (based on Ins))';
COMMENT ON COLUMN insuranc."EDIOffId" IS 'Office Id for "EDI" submissions, defaults to NOCD, set to CA00 where "EDI" = 77777';
COMMENT ON COLUMN insuranc."EDIFormat" IS 'EDI Format (0 = N/A, 1 = NEIC 2.1, 2 = NSF 2.0, 3 = X12N4010 Dental, 4 = X124010 NYMed 1.0, 5 = DCDS 3.00, 6 = NSF 2.01, 7 = X12N4010 NYMed2.1, 8 = X12N4010 Medical, 9=X12N5010 Dental, 10=X12N5010 Medical, 11=X12N5010 NYMed 2.1, 12=X12N4010 NYMed(D), 13=X12N5010 NYMed(D))';
COMMENT ON COLUMN insuranc."EDIFlag" IS 'Flag that indicates whether or not this insurance company participates in "EDI" (0=No, 1=Yes)';
COMMENT ON COLUMN insuranc."EDICode3" IS 'NEA Provider Facility ID / Payor Master ID';
COMMENT ON COLUMN insuranc."EDICode2" IS 'Emdeon real-time ID#';
COMMENT ON COLUMN insuranc."EDIClaims" IS 'EDI Claims (0 = No, 1 = Claims only, 2 = Claims/Preauths)';
COMMENT ON COLUMN insuranc."EDI" IS 'Electronic Data Interchange code';
COMMENT ON COLUMN insuranc."DefaultFee" IS 'Default fee guide ID, ptr to FEESCHED.Fee';
COMMENT ON COLUMN insuranc."DeductFactor" IS 'If LimitedDeducts=1, maximum number of times to charge patient deductable per family.';
COMMENT ON COLUMN insuranc."CvgType" IS 'Number to identify type of coverage (0 = Dental, 1 = Medical)';
COMMENT ON COLUMN insuranc."CvgOnBirthdate" IS 'The point at which coverage ends. Default: 0=Day,1=End of Month, 2=End of Year';
COMMENT ON COLUMN insuranc."CoverageAgeYoungAdult" IS 'Coverage age of young adult';
COMMENT ON COLUMN insuranc."CoverageAgeStud" IS 'Age at which coverage ends for a dependent who is a full-time student';
COMMENT ON COLUMN insuranc."CoverageAge" IS 'Age at which coverage ends for a dependent';
COMMENT ON COLUMN insuranc."Copay" IS 'Dollar ($) amount of the copay';
COMMENT ON COLUMN insuranc."Contact" IS 'Name or title of the assigned contact person';
COMMENT ON COLUMN insuranc."Consolidate" IS 'Consolidate labs? (0 = No, 1 = Yes)';
COMMENT ON COLUMN insuranc."Company" IS 'Primary key, code to identify the insurance company';
COMMENT ON COLUMN insuranc."ClaimGrpFlag" IS 'Print billing group in box 33 (Grp#) field on HCFA claim forms? (0 = No, 1 = Yes)';
COMMENT ON COLUMN insuranc."Claim" IS 'DEPRECATED';
COMMENT ON COLUMN insuranc."City" IS 'City, ptr to CITY.City';
COMMENT ON COLUMN insuranc."ChildCoverage" IS 'Id code of the coverage template for children, ptr to COVERAGE.Coverage';
COMMENT ON COLUMN insuranc."ChargeDedAndPtChg" IS 'KP Only: Flag to determine whether or not to charge both deductible and patient charge (0=No, 1=Yes)';
COMMENT ON COLUMN insuranc."CIF" IS 'Claim inquiry form, ptr to CFORMCD.CFormCdId';
COMMENT ON COLUMN insuranc."BillGovtFee" IS 'Bill government fees? (0=Up to government fees, 1=Always government fees)';
COMMENT ON COLUMN insuranc."AssignComment" IS 'Comment to print on assignment claims. Defaults to "Please Pay Dentist"';
COMMENT ON COLUMN insuranc."Assign" IS 'Assignment amounts (0 = Full, 1 = Primary, 2 = No)';
COMMENT ON COLUMN insuranc."Area" IS 'Telephone area code';
COMMENT ON COLUMN insuranc."ApprovalRequired" IS 'Approval Faculty must be authorized? (0 = No, 1 = Yes)';
COMMENT ON COLUMN insuranc."AllPayor" IS 'All Payor? (0 = No, 1= Can submit to "EDI" without an "EDI" Id #)';
COMMENT ON COLUMN insuranc."AdultCoverage" IS 'Id code of the coverage template for adults, ptr to COVERAGE.Coverage';
COMMENT ON COLUMN insuranc."AddressOther" IS 'For USA, represents County. For Dutch, represents Room Number.';
COMMENT ON COLUMN insuranc."Address2" IS 'Address line 2';
COMMENT ON COLUMN insuranc."Address1" IS 'Address line 1';


CREATE  TABLE invadj (
  "InvAdj" character(6) NOT NULL,
  "Description" character varying(30),
  "Type" numeric(5,0),
  "Inactive" numeric(5,0),
  CONSTRAINT invadj_primary PRIMARY KEY ("InvAdj")
) ;
COMMENT ON TABLE invadj IS 'Inventory Adjustment codes';
COMMENT ON COLUMN invadj."Type" IS 'Adjustment type (0 = Credit, 1 = Debit, 2 = Inventory Adjustment)';
COMMENT ON COLUMN invadj."InvAdj" IS 'Inventory adjustment code, like “LOST”, “RETURN”';
COMMENT ON COLUMN invadj."Inactive" IS 'Inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN invadj."Description" IS 'Description of adjustment code, like “Item Lost”, “Credit memo”, …';


CREATE  TABLE invhold (
  "InvHold" character(6) NOT NULL,
  "Description" character varying(30),
  "Inactive" numeric(5,0),
  "IsInDispute" numeric(5,0),
  CONSTRAINT invhold_primary PRIMARY KEY ("InvHold")
) ;
COMMENT ON TABLE invhold IS 'Invoice On Hold reason codes';
COMMENT ON COLUMN invhold."IsInDispute" IS 'Flag to determine if this On Hold reason code should set invoice treatments to be In Dispute (0=No, 1=Yes)';
COMMENT ON COLUMN invhold."InvHold" IS 'Primary key, code to identify the invoice On Hold reason';
COMMENT ON COLUMN invhold."Inactive" IS 'Code is inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN invhold."Description" IS 'Description of the On Hold reason code';


CREATE  TABLE invitdet (
  "InvItDet" numeric(10,0) NOT NULL,
  "InvItem" numeric(10,0),
  "Type" numeric(5,0),
  "InvLoc" character(6),
  "Product" numeric(10,0),
  "Quantity" numeric,
  "Unit" character varying(10),
  "ItemsPerUnit" numeric(5,0),
  "CostPerUnit" numeric,
  "InvAdj" character(6),
  "Count" numeric,
  "Audit" numeric(10,0),
  "BatchId" numeric(10,0),
  "InvLocTo" character(6),
  CONSTRAINT invitdet_primary PRIMARY KEY ("InvItDet")
) ;
CREATE INDEX IF NOT EXISTS invitdet_invitemkey ON invitdet USING btree ("InvItem") TABLESPACE pg_default;
COMMENT ON TABLE invitdet IS 'Inventory Item Details (Usage out/in, adjustments to inventory details, received, transferred goods)';
COMMENT ON COLUMN invitdet."Unit" IS 'The unit type. Like “Boxes”';
COMMENT ON COLUMN invitdet."Type" IS 'The detail type (0=Receipt, 1=Transfer, 2=Adjustment, 3=Out to person/place, 4=In, 5=Repkg, 6=Count, 7=Check-out, 8=Check-in)';
COMMENT ON COLUMN invitdet."Quantity" IS 'The quantity of the inventory item. Like 15.25';
COMMENT ON COLUMN invitdet."Product" IS 'ID code of the product, ptr to PRODUCT.Product';
COMMENT ON COLUMN invitdet."ItemsPerUnit" IS 'The number of items per unit. Like 100 (gloves per box)';
COMMENT ON COLUMN invitdet."InvLocTo" IS 'The ID code of the location inventory is to go to, ptr to INVLOC.InvLoc';
COMMENT ON COLUMN invitdet."InvLoc" IS 'ID code of the inventory location, ptr to INVLOC.InvLoc';
COMMENT ON COLUMN invitdet."InvItem" IS 'Item that the details are for, ptr to INVITEM.InvItem';
COMMENT ON COLUMN invitdet."InvItDet" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN invitdet."InvAdj" IS 'If INVITDET.Type=2, the inventory adjustment code used. Ptr to INVADJ.InvAdj.';
COMMENT ON COLUMN invitdet."Count" IS 'If INVITDET.Type=2 for inventory count, the count ';
COMMENT ON COLUMN invitdet."CostPerUnit" IS 'The ($) dollar value per unit';
COMMENT ON COLUMN invitdet."BatchId" IS 'Batch ID number, internal ID from sequence';
COMMENT ON COLUMN invitdet."Audit" IS 'Audit record, ptr to AUDITHIS.Audit.';


CREATE  TABLE invitem (
  "InvItem" numeric(10,0) NOT NULL,
  "Type" numeric(5,0),
  "InvRec" numeric(10,0),
  "InvLoc" character(6),
  "Product" numeric(10,0),
  "Quantity" numeric(5,0),
  "Unit" character varying(10),
  "ItemsPerUnit" numeric(5,0),
  "ItemsPerDesc" character varying(10),
  "CostPerUnit" numeric,
  "Balance" numeric,
  "ExpiryDate" timestamp without time zone,
  "InvLocFrom" character(6),
  "InvOrdIt" numeric(10,0),
  "IsException" numeric(5,0),
  "Audit" numeric(10,0),
  "RefNumber" character varying(50),
  CONSTRAINT invitem_primary PRIMARY KEY ("InvItem")
) ;
CREATE INDEX IF NOT EXISTS invitem_invlockey ON invitem USING btree ("InvLoc", "Product") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS invitem_productkey ON invitem USING btree ("Product") TABLESPACE pg_default;
COMMENT ON TABLE invitem IS 'Inventory Item Balances';
COMMENT ON COLUMN invitem."Unit" IS 'The unit type. Like “Boxes”';
COMMENT ON COLUMN invitem."Type" IS 'Inventory item type (0 = Receipt, 1 = Transfer, 2 = Adjust, 5 = Repkg)';
COMMENT ON COLUMN invitem."RefNumber" IS 'User defined reference (ie. could be Vendor’s Invoice Number for Received Goods)';
COMMENT ON COLUMN invitem."Quantity" IS 'The quantity of the inventory item. Like 15.25';
COMMENT ON COLUMN invitem."Product" IS 'The ID code of the product, ptr to PRODUCT.Product.';
COMMENT ON COLUMN invitem."ItemsPerUnit" IS 'The number of items per unit. Like 100 (gloves per box)';
COMMENT ON COLUMN invitem."ItemsPerDesc" IS 'Optional text (Eg. Box, 20 “Books”)';
COMMENT ON COLUMN invitem."IsException" IS 'Is an exception? ( 0 = No, 1 = Yes, added by axiUm (Type=2))';
COMMENT ON COLUMN invitem."InvRec" IS 'If INVITEM.Type = 0, the INVREC.InvRec item ';
COMMENT ON COLUMN invitem."InvOrdIt" IS 'Order item receipt/transfer fills, ptr to INVORDIT.InvOrdIt';
COMMENT ON COLUMN invitem."InvLocFrom" IS ' If Type=1, location being transferred from, ptr to INVLOC.InvLoc.';
COMMENT ON COLUMN invitem."InvLoc" IS 'ID code of the store/warehouse location the product is at, ptr to INVLOC.InvLoc';
COMMENT ON COLUMN invitem."InvItem" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN invitem."ExpiryDate" IS ' If TrackExpiryDate, date expires';
COMMENT ON COLUMN invitem."CostPerUnit" IS 'Dollar ($) value per unit when received';
COMMENT ON COLUMN invitem."Balance" IS 'Quantity left (for LIFO, FIFO)';
COMMENT ON COLUMN invitem."Audit" IS 'Audit record for receipt of items, ptr to AUDITHIS.Audit';


CREATE  TABLE invloc (
  "InvLoc" character(6) NOT NULL,
  "Type" numeric(5,0),
  "Name" character varying(30),
  "BarCode" character varying(20),
  "Inactive" numeric(5,0),
  CONSTRAINT invloc_primary PRIMARY KEY ("InvLoc")
) ;
COMMENT ON TABLE invloc IS 'Locations with inventory';
COMMENT ON COLUMN invloc."Type" IS 'The location type ( 0 = Warehouse, 1 = Store, 2 = Cart, 3 = Other)';
COMMENT ON COLUMN invloc."Name" IS 'If IsDispLoc 0, the name of location';
COMMENT ON COLUMN invloc."InvLoc" IS 'Id code to identify the location. ';
COMMENT ON COLUMN invloc."Inactive" IS 'Inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN invloc."BarCode" IS 'If Type=2, bar code of Cart';


CREATE  TABLE invlocmap (
  "InvLoc" character(6) NOT NULL,
  "DispCode" character(6) NOT NULL,
  CONSTRAINT invlocmap_primary PRIMARY KEY ("InvLoc", "DispCode")
) ;
COMMENT ON TABLE invlocmap IS 'INVLOCMAP records';
COMMENT ON COLUMN invlocmap."InvLoc" IS 'Primary Key. The inventory location code. Ptr to INVLOC.InvLoc.';
COMMENT ON COLUMN invlocmap."DispCode" IS 'Primary Key. The dispensary location code. Ptr to DISPCODE.DispCode.';


CREATE  TABLE invorder (
  "InvOrder" numeric(10,0) NOT NULL,
  "IsExternal" numeric(5,0),
  "InvLoc" character(6),
  "Vendor" numeric(10,0),
  "PONumber" character varying(20),
  "InvLocFrom" character(6),
  "InvOType" character(6),
  "SpecialOrder" numeric(5,0),
  "Recurs" numeric(5,0),
  "Cycle" numeric(5,0),
  "CycleCnt" numeric(5,0),
  "Date" timestamp without time zone,
  "EndDate" timestamp without time zone,
  "Inactive" numeric(5,0),
  "ApprovalUser" numeric(10,0),
  "ParentOrder" numeric(10,0),
  "Audit" numeric(10,0),
  CONSTRAINT invorder_primary PRIMARY KEY ("InvOrder")
) ;
COMMENT ON TABLE invorder IS 'Orders (internal to warehouse / store, external to vendor)';
COMMENT ON COLUMN invorder."Vendor" IS 'If an external order, the vendor that was ordered from. Ptr to VENDOR.Vendor.';
COMMENT ON COLUMN invorder."SpecialOrder" IS 'Is this a special order? (0=No, 1=Yes (if IsExternal=1))';
COMMENT ON COLUMN invorder."Recurs" IS 'Order recurs? (0=No, 1=Yes, 2=Child of recurring order)';
COMMENT ON COLUMN invorder."ParentOrder" IS 'If Recurs=2, ID of the parent order. Ptr to INVORDER.InvOrder';
COMMENT ON COLUMN invorder."PONumber" IS 'PO Number, typed in if is IsExternal=1';
COMMENT ON COLUMN invorder."IsExternal" IS 'Is an external order? (0 = No, 1 = Yes, from outside Vendor)';
COMMENT ON COLUMN invorder."InvOrder" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN invorder."InvOType" IS 'Type of the inventory order, ptr to INVOTYPE.InvOType.';
COMMENT ON COLUMN invorder."InvLocFrom" IS 'Inventory location that products are ordered from. Ptr to INVLOC.InvLoc.';
COMMENT ON COLUMN invorder."InvLoc" IS 'If an internal order, the inventory location placing the order. Ptr to INVLOC.InvLoc.';
COMMENT ON COLUMN invorder."Inactive" IS 'Order is inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN invorder."EndDate" IS 'If a recurring order, the date of the last order.';
COMMENT ON COLUMN invorder."Date" IS 'Date of the inventory order. If a recurring order, the date of the first order.';
COMMENT ON COLUMN invorder."CycleCnt" IS 'If Recurs = 1 or 2, the cycle count. For example, “6” for every 6 weeks';
COMMENT ON COLUMN invorder."Cycle" IS 'Order recurrance cycle (0 = No, 1 = Daily, 2 = Weekly)';
COMMENT ON COLUMN invorder."Audit" IS 'Audit record, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN invorder."ApprovalUser" IS '0=Unapproved, otherwise the ID of the approving user (ptr to USERS.User)';


CREATE  TABLE invordit (
  "InvOrdIt" numeric(10,0) NOT NULL,
  "InvOrder" numeric(10,0),
  "Item" numeric(5,0),
  "Product" numeric(10,0),
  "Quantity" numeric(5,0),
  "Unit" character varying(10),
  "CostPerUnit" numeric,
  "NeedBy" timestamp without time zone,
  "Comment" character varying(4000),
  "Status" numeric(5,0),
  "PickList" numeric(10,0),
  "PickUser" numeric(10,0),
  "PickDate" timestamp without time zone,
  "QtyFilled" numeric(5,0),
  "WasBackOrdered" numeric(5,0),
  "Stocked" numeric(5,0),
  "StockedFrom" numeric(5,0),
  "Description" character varying(50),
  CONSTRAINT invordit_primary PRIMARY KEY ("InvOrdIt")
) ;
CREATE INDEX IF NOT EXISTS invordit_invorderkey ON invordit USING btree ("InvOrder") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS invordit_statuskey ON invordit USING btree ("Status", "PickList") TABLESPACE pg_default;
COMMENT ON TABLE invordit IS 'Products ordered';
COMMENT ON COLUMN invordit."WasBackOrdered" IS 'Was back ordered? (0=No, 1=Yes)';
COMMENT ON COLUMN invordit."Unit" IS 'Unit type ordered. Like “Boxes” (copied from Product)';
COMMENT ON COLUMN invordit."StockedFrom" IS 'Product is stocked at the location ordering from at the time of ordering? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN invordit."Stocked" IS 'Product is stocked at the ordering location at the time of ordering? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN invordit."Status" IS 'Status of order ( 0 = Ordered, 1 = Purchased, 2 = Picked, 3 = Partial, 4 = Cancelled, 5 = Back-ordered, 6 = Closed, 7 = Filled, 8 = Reviewed, 9=Requested)';
COMMENT ON COLUMN invordit."Quantity" IS 'Quantity ordered';
COMMENT ON COLUMN invordit."QtyFilled" IS 'Quantity of order filled';
COMMENT ON COLUMN invordit."Product" IS 'ID code of the product being ordered, ptr to PRODUCT.Product.';
COMMENT ON COLUMN invordit."PickUser" IS 'User who last filled/processed item, ptr to USERS.User.';
COMMENT ON COLUMN invordit."PickList" IS 'ID code of pick list, internal ID from sequence.';
COMMENT ON COLUMN invordit."PickDate" IS 'Date last filled/processed item';
COMMENT ON COLUMN invordit."NeedBy" IS 'Date that the item is needed by (optional).';
COMMENT ON COLUMN invordit."Item" IS 'Line# on order (starts at 1 per order)';
COMMENT ON COLUMN invordit."InvOrder" IS 'Inventory order that this item is for, ptr to INVORDER.InvOrder.';
COMMENT ON COLUMN invordit."InvOrdIt" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN invordit."Description" IS 'Description of the product to order (defaults to PRODUCT.Description for normal orders, what the user types in for Special orders)';
COMMENT ON COLUMN invordit."CostPerUnit" IS 'If an external order, the cost per unit.';
COMMENT ON COLUMN invordit."Comment" IS 'Special comments, instructions';


CREATE  TABLE invotype (
  "InvOType" character(6) NOT NULL,
  "Description" character varying(30),
  "IsExternal" numeric(5,0),
  "FilePath" character varying(255),
  content bytea,
  "Inactive" numeric(5,0),
  CONSTRAINT invotype_primary PRIMARY KEY ("InvOType")
) ;
COMMENT ON TABLE invotype IS 'Types of Order (internal transfers)';
COMMENT ON COLUMN invotype.content IS 'Crystal Report to print';
COMMENT ON COLUMN invotype."IsExternal" IS 'Is an external order type? (0 = No, 1 = Yes, Default from outside Vendor)';
COMMENT ON COLUMN invotype."InvOType" IS 'ID code of the inventory order type. Examples: “EORDER”, “PHONE”';
COMMENT ON COLUMN invotype."Inactive" IS 'Inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN invotype."FilePath" IS 'Original path of report to print (info only)';
COMMENT ON COLUMN invotype."Description" IS 'Full description of the inventory order type. Examples: “Electronic request”, “Telephone order”';


CREATE  TABLE invprodmap (
  "Product" numeric(10,0) NOT NULL DEFAULT 0,
  "Sundry" character(6) NOT NULL,
  "Inactive" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT invprodmap_primary PRIMARY KEY ("Product", "Sundry")
) ;
COMMENT ON TABLE invprodmap IS 'INVPRODMAP records';
COMMENT ON COLUMN invprodmap."Sundry" IS 'Primary Key. The Sundry code. Ptr to SUNDRY.Sundry.';
COMMENT ON COLUMN invprodmap."Product" IS 'Primary Key. The Product code. Ptr to PRODUCT.Product.';
COMMENT ON COLUMN invprodmap."Inactive" IS 'Obsolete.';


CREATE  TABLE invrec (
  "InvRec" numeric(10,0) NOT NULL,
  "InvLoc" character(6),
  "Date" timestamp without time zone,
  "PONumber" character varying(20),
  "PODate" timestamp without time zone,
  "Vendor" numeric(10,0),
  "Audit" numeric(10,0),
  CONSTRAINT invrec_primary PRIMARY KEY ("InvRec")
) ;
COMMENT ON TABLE invrec IS 'Inventory Received';
COMMENT ON COLUMN invrec."Vendor" IS 'Vendor ordered from (if External Order), ptr to VENDOR.Vendor.';
COMMENT ON COLUMN invrec."PONumber" IS 'PO Number goods received on';
COMMENT ON COLUMN invrec."PODate" IS 'Original purchase order date';
COMMENT ON COLUMN invrec."InvRec" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN invrec."InvLoc" IS 'INVLOC.InvLoc order is received at';
COMMENT ON COLUMN invrec."Date" IS 'Date products received';
COMMENT ON COLUMN invrec."Audit" IS 'Audit record, ptr to AUDITHIS.Audit ';


CREATE  TABLE iprocmap (
  "Company" character(6) NOT NULL,
  "ProcMapFrom" character(7) NOT NULL,
  "ProcMapTo" character(7) NOT NULL,
  CONSTRAINT iprocmap_pk PRIMARY KEY ("Company", "ProcMapFrom")
) ;
CREATE INDEX IF NOT EXISTS iprocmap_maptokey ON iprocmap USING btree ("Company", "ProcMapTo") TABLESPACE pg_default;
COMMENT ON TABLE iprocmap IS 'Insurance Procedure Mapping Table.';
COMMENT ON COLUMN iprocmap."ProcMapTo" IS 'procedure code to map to.';
COMMENT ON COLUMN iprocmap."ProcMapFrom" IS 'Primary key component, procedure code to map from.';
COMMENT ON COLUMN iprocmap."Company" IS 'Primary key component, insurance company code.';


CREATE  TABLE iptform (
  "iPtForm" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "FormCode" character(6),
  "PForm" numeric(10,0),
  "iUser" numeric(10,0),
  "Access" numeric(5,0),
  "Order" numeric(10,0),
  "RequiresAttention" numeric(5,0),
  "FormStatus" numeric(5,0) NOT NULL DEFAULT 0,
  "LastSavedPageNumber" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT iptform_primary PRIMARY KEY ("iPtForm")
) ;
CREATE INDEX IF NOT EXISTS iptform_formcode ON iptform USING btree ("FormCode") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS iptform_iuser ON iptform USING btree ("iUser") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS iptform_patient ON iptform USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE iptform IS 'iForms defined that each patient can access';
COMMENT ON COLUMN iptform."iUser" IS 'IUSER.iUser that can access the form';
COMMENT ON COLUMN iptform."iPtForm" IS 'Primary key, sequenced';
COMMENT ON COLUMN iptform."RequiresAttention" IS '0=No, 1=Yes, in To do list';
COMMENT ON COLUMN iptform."Patient" IS 'Ptr to PATIENT.Patient';
COMMENT ON COLUMN iptform."PForm" IS 'Ptr to PFORM.PForm or 0 (if form not created yet)';
COMMENT ON COLUMN iptform."Order" IS 'Order patient sees this in the list';
COMMENT ON COLUMN iptform."LastSavedPageNumber" IS 'Number of the form page that was last saved by the user';
COMMENT ON COLUMN iptform."FormStatus" IS 'Status for the Internet Form (0-not defined, 1-Incomplete, 2-Complete)';
COMMENT ON COLUMN iptform."FormCode" IS 'Ptr to FORM.Code';
COMMENT ON COLUMN iptform."Access" IS '0=Read only, 1=Full access';


CREATE  TABLE iptform_deleted (
  "iPtForm" numeric(10,0),
  "Patient" numeric(10,0),
  "FormCode" character(6),
  "PForm" numeric(10,0),
  "iUser" numeric(10,0),
  "Access" numeric(5,0),
  "Order" numeric(10,0),
  "RequiresAttention" numeric(5,0),
  "FormStatus" numeric(5,0) NOT NULL,
  "LastSavedPageNumber" numeric(5,0) NOT NULL DEFAULT 0
) ;
COMMENT ON TABLE iptform_deleted IS 'Deleted iForms';
COMMENT ON COLUMN iptform_deleted."iUser" IS 'IUSER.iUser that can access the form';
COMMENT ON COLUMN iptform_deleted."iPtForm" IS 'Primary key, sequenced';
COMMENT ON COLUMN iptform_deleted."RequiresAttention" IS '0=No, 1=Yes, in To do list';
COMMENT ON COLUMN iptform_deleted."Patient" IS 'Ptr to PATIENT.Patient';
COMMENT ON COLUMN iptform_deleted."PForm" IS 'Ptr to PFORM.PForm or 0 (if form not created yet)';
COMMENT ON COLUMN iptform_deleted."Order" IS 'Order patient sees this in the list';
COMMENT ON COLUMN iptform_deleted."LastSavedPageNumber" IS 'Number of the form page that was last saved by the user';
COMMENT ON COLUMN iptform_deleted."FormStatus" IS 'Status for the Internet Form (0-not defined, 1-Incomplete, 2-Complete)';
COMMENT ON COLUMN iptform_deleted."FormCode" IS 'Ptr to FORM.Code';
COMMENT ON COLUMN iptform_deleted."Access" IS '0=Read only, 1=Full access';


CREATE  TABLE isecureq (
  "iSecureQ" numeric(10,0) NOT NULL,
  "Description" character varying(80),
  CONSTRAINT isecureq_primary PRIMARY KEY ("iSecureQ")
) ;
CREATE UNIQUE INDEX IF NOT EXISTS isecureq_uk1 ON isecureq USING btree ("iSecureQ", "Description") TABLESPACE pg_default;
COMMENT ON TABLE isecureq IS 'Internet Security Questions';
COMMENT ON COLUMN isecureq."iSecureQ" IS 'Primary key, sequenced';
COMMENT ON COLUMN isecureq."Description" IS 'Security Question';


CREATE  TABLE isetting (
  "iSetting" numeric(5,0) NOT NULL,
  "Key" character varying(255) NOT NULL,
  "SettingType" numeric(5,0) NOT NULL DEFAULT 1,
  "iSettingGrp" numeric(5,0),
  "Priority" numeric(5,0),
  "Value" character varying(4000) NOT NULL,
  "Description" character varying(4000),
  CONSTRAINT isetting_pk PRIMARY KEY ("iSetting")
) ;
CREATE INDEX IF NOT EXISTS isetting_key_idx ON isetting USING btree (lower(("Key")::text)) TABLESPACE pg_default;
COMMENT ON TABLE isetting IS 'Settings for axiUm PatientAccess Web application (i.e. timeouts, etc)';
COMMENT ON COLUMN isetting."iSettingGrp" IS 'Group that the iSetting is in. Ptr to ISETTINGGRP.iSettingGrp.';
COMMENT ON COLUMN isetting."iSetting" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN isetting."Value" IS 'Message or setting value.';
COMMENT ON COLUMN isetting."SettingType" IS 'Type of setting: (1 = Logical setting, 2=Message/HTMLEncode, 3=Message/HTMLNoEncode, 4=Special)';
COMMENT ON COLUMN isetting."Priority" IS 'Priority of the ISETTING.';
COMMENT ON COLUMN isetting."Key" IS 'Lookup key for setting/message.';
COMMENT ON COLUMN isetting."Description" IS 'Description of the ISETTING';


CREATE  TABLE isetting_pa2 (
  "iSetting" numeric(5,0) NOT NULL DEFAULT 0,
  "Key" character varying(255) NOT NULL,
  "SettingType" numeric(5,0) NOT NULL DEFAULT 1,
  "iSettingGrp" numeric(5,0) NOT NULL DEFAULT 0,
  "Priority" numeric(5,0) NOT NULL DEFAULT 0,
  "Value" character varying(4000),
  "Description" character varying(4000),
  "Status" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT isetting_pa2_pk PRIMARY KEY ("iSetting"),
  CONSTRAINT isetting_pa2_isettinggrp_fk FOREIGN KEY ("iSettingGrp") REFERENCES isettinggrp_pa2("iSettingGrp")
) ;
CREATE INDEX IF NOT EXISTS isetting_pa2_isettinggrpkey ON isetting_pa2 USING btree ("iSettingGrp") TABLESPACE pg_default;
COMMENT ON TABLE isetting_pa2 IS 'Table for storing settings for Patient Access 2.0';
COMMENT ON COLUMN isetting_pa2."iSettingGrp" IS 'Group that the iSetting is in. Ptr to ISETTINGGRP.iSettingGrp.';
COMMENT ON COLUMN isetting_pa2."iSetting" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN isetting_pa2."Value" IS 'Message or setting value.';
COMMENT ON COLUMN isetting_pa2."Status" IS 'The status of the setting (0=Active, 1=Hidden, 2=Deleted)';
COMMENT ON COLUMN isetting_pa2."SettingType" IS 'Type of setting: (1 = Logical setting, 2=Message/HTMLEncode, 3=Message/HTMLNoEncode, 4=Special, 5=File, 6=Color picker)';
COMMENT ON COLUMN isetting_pa2."Priority" IS 'Priority of the ISETTING_PA2.';
COMMENT ON COLUMN isetting_pa2."Key" IS 'Lookup key for setting/message.';
COMMENT ON COLUMN isetting_pa2."Description" IS 'Description of the ISETTING_PA2.';


CREATE  TABLE isettinggrp (
  "iSettingGrp" numeric(5,0) NOT NULL,
  "ParentId" numeric(5,0),
  "Priority" numeric(5,0),
  "Name" character varying(255),
  CONSTRAINT isettinggrp_pk PRIMARY KEY ("iSettingGrp")
) ;
COMMENT ON TABLE isettinggrp IS 'Setting Groups for PatientAccess';
COMMENT ON COLUMN isettinggrp."iSettingGrp" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN isettinggrp."Priority" IS 'Priority of the setting group. ';
COMMENT ON COLUMN isettinggrp."ParentId" IS 'If a subgroup, ptr to ISETTINGGRP.iSettingGrp of parent group. ';
COMMENT ON COLUMN isettinggrp."Name" IS 'Name of the setting group.';


CREATE  TABLE isettingovr (
  "iSettingOvr" numeric(5,0) NOT NULL,
  "Key" character varying(255) NOT NULL,
  "Order" numeric(5,0),
  "Value" character varying(4000) NOT NULL,
  CONSTRAINT isettingovr_pk PRIMARY KEY ("iSettingOvr")
) ;
COMMENT ON TABLE isettingovr IS 'Overflow records for long ISETTINGs';
COMMENT ON COLUMN isettingovr."iSettingOvr" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN isettingovr."Value" IS 'Message or setting value.';
COMMENT ON COLUMN isettingovr."Order" IS 'Number to identify the order of this overflow record.';
COMMENT ON COLUMN isettingovr."Key" IS 'Setting that this overflow record is for, ptr to ISETTING.Key';


CREATE  TABLE isomap (
  "ISO639_2B" character(3) NOT NULL,
  "ISO639_1" character(2),
  CONSTRAINT isomap_primary PRIMARY KEY ("ISO639_2B")
) ;
COMMENT ON TABLE isomap IS 'Mapping table for Patient Language codes';
COMMENT ON COLUMN isomap."ISO639_2B" IS 'ISO639-2/B Code. Primary key.';
COMMENT ON COLUMN isomap."ISO639_1" IS 'ISO639-1 Code.';


CREATE  TABLE istickynote (
  "Auto" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "AP_NOTE_AutoDec" numeric(10,0),
  "Type" numeric(5,0),
  "SecondaryId" numeric(10,0),
  CONSTRAINT istickynote_pk PRIMARY KEY ("Auto")
) ;
COMMENT ON TABLE istickynote IS 'Records of sticky notes managed by PatientAccess';
COMMENT ON COLUMN istickynote."Type" IS 'Area in PatientAccess that generated this sticky note (1=Insurance Policy, 2=Patient Profile, 3=Medical Information)';
COMMENT ON COLUMN istickynote."SecondaryId" IS 'If Type = 1 (Insurance), then ptr to PTPOL.PolicyId. If Type = 2 (Patient Profile), then one of the following values: 1: Patient Updated (Patient has permission to update demographic information), 2: Patient Flagged (patient has ability to mark demographic as correct/incorrect). If Type = 3 (Medical Information), then one of the following values: 1: Problems, 2: Medications, 3: Medical Alerts, 4: Medical Problems, 5: Allergies';
COMMENT ON COLUMN istickynote."Patient" IS 'Patient that this sticky note is for, ptr to PATIENT.Patient';
COMMENT ON COLUMN istickynote."Auto" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN istickynote."AP_NOTE_AutoDec" IS 'Sticky note, ptr to AP_NOTE.AP_NOTE_AutoDec';


CREATE  TABLE iuser (
  "iUser" numeric(10,0) NOT NULL,
  "Type" numeric(5,0),
  "Id" numeric(10,0),
  "UserName" character varying(100),
  "Password" character varying(255),
  "IsTemp" numeric(5,0),
  "IsAgreed" numeric(5,0),
  "IsLocked" numeric(5,0),
  "Audit" numeric(10,0),
  "Deleted" numeric(5,0),
  "PasswordQuestion1" numeric(10,0),
  "PasswordAnswer1" character varying(161),
  "PasswordQuestion2" numeric(10,0),
  "PasswordAnswer2" character varying(161),
  "PasswordQuestion3" numeric(10,0),
  "PasswordAnswer3" character varying(161),
  "FailedPWAttemptCount" numeric(5,0),
  "FailedPWAttemptDate" timestamp without time zone,
  "FailedPWAttemptTime" numeric(10,0),
  "PwdLastChanged" timestamp without time zone,
  "MsgAccess" numeric(5,0),
  "LastAccessDateTime" timestamp without time zone,
  "IsNoAccess" numeric(5,0),
  "LastEmailDateTime" timestamp without time zone,
  "PersonalInfoCorrect" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT iuser_primary PRIMARY KEY ("iUser")
) ;
CREATE UNIQUE INDEX IF NOT EXISTS iusers_username ON iuser USING btree (upper(("UserName")::text)) TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS iuser_audit ON iuser USING btree ("Audit") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS iuser_typeid ON iuser USING btree ("Type", "Id") TABLESPACE pg_default;
COMMENT ON TABLE iuser IS 'Internet (PatientAccess) Web User';
COMMENT ON COLUMN iuser."iUser" IS 'Primary key, internal ID from sequence (uses USERS_USER_SEQ).';
COMMENT ON COLUMN iuser."UserName" IS 'Internet account user name';
COMMENT ON COLUMN iuser."Type" IS 'Type of the internet user. (0=Patient)';
COMMENT ON COLUMN iuser."PwdLastChanged" IS 'Date that the password for this web user was last changed. ';
COMMENT ON COLUMN iuser."PersonalInfoCorrect" IS 'Status for the personal information (0-not defined, 1-correct, 2-incorrect)';
COMMENT ON COLUMN iuser."PasswordQuestion3" IS 'Internet Security Question 3, Ptr to ISECUREQ.iSecureQ';
COMMENT ON COLUMN iuser."PasswordQuestion2" IS 'Internet Security Question 2, Ptr to ISECUREQ.iSecureQ';
COMMENT ON COLUMN iuser."PasswordQuestion1" IS 'Internet Security Question 1, Ptr to ISECUREQ.iSecureQ';
COMMENT ON COLUMN iuser."PasswordAnswer3" IS 'Password Answer 3 [encrypted]';
COMMENT ON COLUMN iuser."PasswordAnswer2" IS 'Password Answer 2 [encrypted]';
COMMENT ON COLUMN iuser."PasswordAnswer1" IS 'Password Answer 1 [encrypted]';
COMMENT ON COLUMN iuser."Password" IS 'Internet account password';
COMMENT ON COLUMN iuser."MsgAccess" IS 'Can this internet user send and receive messages in PatientAccess? (0=No, 1=Yes)';
COMMENT ON COLUMN iuser."LastEmailDateTime" IS 'DateTime of last Email Invitation.';
COMMENT ON COLUMN iuser."LastAccessDateTime" IS 'Date/Time of last patient access';
COMMENT ON COLUMN iuser."IsTemp" IS 'Is the password on this account a temporary password? (0=No, 1=Yes)';
COMMENT ON COLUMN iuser."IsNoAccess" IS 'Defines no access to patient access, Default: 0=No (Patient or representative can login), 1=Yes (Only representatives can login)';
COMMENT ON COLUMN iuser."IsLocked" IS 'Is this account locked? (0=No, 1=Yes)';
COMMENT ON COLUMN iuser."IsAgreed" IS 'Has this user agreed to the Terms of Use Agreement? (0=No, 1=Yes)';
COMMENT ON COLUMN iuser."Id" IS 'ID of the internet user (if Type=0, ptr to PATIENT.Patient)';
COMMENT ON COLUMN iuser."FailedPWAttemptTime" IS 'Time of most recent failed login attempt. ';
COMMENT ON COLUMN iuser."FailedPWAttemptDate" IS 'Date/time of most recent failed login attempt. ';
COMMENT ON COLUMN iuser."FailedPWAttemptCount" IS 'Number of failed login attempts since last successful login. ';
COMMENT ON COLUMN iuser."Deleted" IS 'Is this internet user deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN iuser."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE iuserh (
  "iUserH" numeric(10,0) NOT NULL,
  "iUser" numeric(10,0),
  "Type" numeric(5,0),
  "Id" numeric(10,0),
  "UserName" character varying(100),
  "Password" character varying(255),
  "IsTemp" numeric(5,0),
  "IsAgreed" numeric(5,0),
  "IsLocked" numeric(5,0),
  "Audit" numeric(10,0),
  "Deleted" numeric(5,0),
  "PasswordQuestion1" numeric(10,0),
  "PasswordAnswer1" character varying(161),
  "PasswordQuestion2" numeric(10,0),
  "PasswordAnswer2" character varying(161),
  "PasswordQuestion3" numeric(10,0),
  "PasswordAnswer3" character varying(161),
  "FailedPWAttemptCount" numeric(5,0),
  "FailedPWAttemptDate" timestamp without time zone,
  "FailedPWAttemptTime" numeric(10,0),
  "PwdLastChanged" timestamp without time zone,
  "MsgAccess" numeric(5,0),
  "LastAccessDateTime" timestamp without time zone,
  "IsNoAccess" numeric(5,0),
  "LastEmailDateTime" timestamp without time zone,
  "PersonalInfoCorrect" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT iuserh_primary PRIMARY KEY ("iUserH")
) ;
CREATE INDEX IF NOT EXISTS iuserh_iuser ON iuserh USING btree ("iUser") TABLESPACE pg_default;
COMMENT ON TABLE iuserh IS 'Internet (PatientAccess) Web User History';
COMMENT ON COLUMN iuserh."iUserH" IS 'Primary key, internal ID from sequence';
COMMENT ON COLUMN iuserh."iUser" IS 'iUser ID, Ptr to IUSER.iUser';
COMMENT ON COLUMN iuserh."UserName" IS 'Internet account user name';
COMMENT ON COLUMN iuserh."Type" IS 'Type of the internet user. (0=Patient)';
COMMENT ON COLUMN iuserh."PwdLastChanged" IS 'Date that the password for this web user was last changed. ';
COMMENT ON COLUMN iuserh."PersonalInfoCorrect" IS 'Status for the personal information (0-not defined, 1-correct, 2-incorrect)';
COMMENT ON COLUMN iuserh."PasswordQuestion3" IS 'Internet Security Question 3, Ptr to ISECUREQ.iSecureQ';
COMMENT ON COLUMN iuserh."PasswordQuestion2" IS 'Internet Security Question 2, Ptr to ISECUREQ.iSecureQ';
COMMENT ON COLUMN iuserh."PasswordQuestion1" IS 'Internet Security Question 1, Ptr to ISECUREQ.iSecureQ';
COMMENT ON COLUMN iuserh."PasswordAnswer3" IS 'Password Answer 3 [encrypted]';
COMMENT ON COLUMN iuserh."PasswordAnswer2" IS 'Password Answer 2 [encrypted]';
COMMENT ON COLUMN iuserh."PasswordAnswer1" IS 'Password Answer 1 [encrypted]';
COMMENT ON COLUMN iuserh."Password" IS 'Internet account password';
COMMENT ON COLUMN iuserh."MsgAccess" IS 'Can this internet user send and receive messages in PatientAccess? (0=No, 1=Yes)';
COMMENT ON COLUMN iuserh."LastEmailDateTime" IS 'Date/Time of last Email Invitation.';
COMMENT ON COLUMN iuserh."LastAccessDateTime" IS 'Date/Time of last patient access';
COMMENT ON COLUMN iuserh."IsTemp" IS 'Is the password on this account a temporary password? (0=No, 1=Yes)';
COMMENT ON COLUMN iuserh."IsNoAccess" IS 'Defines no access to patient access, Default: 0=No (Patient or representative can login), 1=Yes (Only representatives can login)';
COMMENT ON COLUMN iuserh."IsLocked" IS 'Is this account locked? (0=No, 1=Yes)';
COMMENT ON COLUMN iuserh."IsAgreed" IS 'Has this user agreed to the Terms of Use Agreement? (0=No, 1=Yes)';
COMMENT ON COLUMN iuserh."Id" IS 'ID of the internet user (if Type=0, ptr to PATIENT.Patient)';
COMMENT ON COLUMN iuserh."FailedPWAttemptTime" IS 'Time of most recent failed login attempt. ';
COMMENT ON COLUMN iuserh."FailedPWAttemptDate" IS 'Date/time of most recent failed login attempt. ';
COMMENT ON COLUMN iuserh."FailedPWAttemptCount" IS 'Number of failed login attempts since last successful login. ';
COMMENT ON COLUMN iuserh."Deleted" IS 'Is this internet user deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN iuserh."Audit" IS 'Audit record of IUSER creation. Ptr to AUDITHIS.Audit.';


CREATE  TABLE iuserpwh (
  "iUserPwhId" numeric(10,0) NOT NULL,
  "iUser" numeric(10,0) NOT NULL,
  "Password" character varying(255),
  "PasswordSetDate" timestamp without time zone,
  "Type" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT iuserpwh_pk PRIMARY KEY ("iUserPwhId")
) ;
COMMENT ON TABLE iuserpwh IS 'Internet  (PatientAccess) Web User Password History';
COMMENT ON COLUMN iuserpwh."iUserPwhId" IS 'Primary key, internal ID from sequence';
COMMENT ON COLUMN iuserpwh."iUser" IS 'PatientAccess user that this history is for, ptr to IUSER.iUser';
COMMENT ON COLUMN iuserpwh."Type" IS 'Type of encryption';
COMMENT ON COLUMN iuserpwh."PasswordSetDate" IS 'Date/time that this password was set.';
COMMENT ON COLUMN iuserpwh."Password" IS 'Password (encrypted hash)';


CREATE  TABLE kit (
  "Kit" character(30) NOT NULL,
  "KitType" character(6),
  "TimesUsed" numeric(10,0),
  "KitOut" numeric(5,0),
  "Location" character(6),
  "ProviderOut" character(10),
  "DateOut" timestamp without time zone,
  "TimeOut" numeric(10,0),
  "OutOfService" numeric(5,0),
  "Cost" numeric,
  "DispCode" character(6),
  "OuterBarCode" character varying(30),
  "SterilizationExpiry" timestamp without time zone,
  "Destination" character(6),
  "Note" character varying(4000),
  "OwnerUser" numeric(10,0),
  "RawBarCode" character varying(1000),
  CONSTRAINT kit_primary PRIMARY KEY ("Kit")
) ;
CREATE INDEX IF NOT EXISTS kit_kittypelocation ON kit USING btree ("KitType", "Location") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS kit_kittypeprovider ON kit USING btree ("KitType", "ProviderOut") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS kit_location ON kit USING btree ("Location") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS kit_outerbarcode ON kit USING btree ("OuterBarCode") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS kit_rawbarcode ON kit USING btree ("RawBarCode") TABLESPACE pg_default;
COMMENT ON TABLE kit IS 'Dispensary kit information record';
COMMENT ON COLUMN kit."TimesUsed" IS 'Number of times this kit has been checked out for use.';
COMMENT ON COLUMN kit."TimeOut" IS 'Time this kit was checked out';
COMMENT ON COLUMN kit."SterilizationExpiry" IS 'Date last sterilization is expired';
COMMENT ON COLUMN kit."RawBarCode" IS 'Raw bar code, used for GS1 bar codes';
COMMENT ON COLUMN kit."ProviderOut" IS 'Id code of the provider this kit is checked out to (if KitOut = YES), ptr to PRODUCER.Producer';
COMMENT ON COLUMN kit."OwnerUser" IS 'User who owns the kit, ptr to USERS.User';
COMMENT ON COLUMN kit."OuterBarCode" IS 'Optional, current outer bar code';
COMMENT ON COLUMN kit."OutOfService" IS 'Kit is out of service? (0 = No, 1 = Yes)';
COMMENT ON COLUMN kit."Note" IS 'Contains a User added note';
COMMENT ON COLUMN kit."Location" IS 'Current dispensary location of this kit, updated on scan in / scan out / transfer. Can be any type of dispensary code (dispensary, cart, sterilization, other), or blank in the case of manual requests. If the kit is out, refers to the dispensary that the kit was requested from. Ptr to DISPCODE.DispCode. ';
COMMENT ON COLUMN kit."KitType" IS 'Type of the kit, ptr to KITTYPE.KitType';
COMMENT ON COLUMN kit."KitOut" IS 'Is the kit checked out? (0 = No, 1 = Yes)';
COMMENT ON COLUMN kit."Kit" IS 'Primary key, ID code of the kit';
COMMENT ON COLUMN kit."DispCode" IS 'Current dispensary for this kit, updated on scan in / scan out / transfer. Must be a dispensary-type dispensary code (DISPCODE.Type=0). If the kit is out, last dispensary that the kit was in. Ptr to DISPCODE.DispCode. ';
COMMENT ON COLUMN kit."Destination" IS 'If on a cart, the DISPCODE.DispCode of the destination dispensary.';
COMMENT ON COLUMN kit."DateOut" IS 'Date this kit was checked out';
COMMENT ON COLUMN kit."Cost" IS 'Original cassette cost (the cost of the casette, when the kit was new). ';


CREATE  TABLE kitinv (
  "KitInv" numeric(10,0) NOT NULL,
  "StartDate" timestamp without time zone,
  "EndDate" timestamp without time zone,
  CONSTRAINT kitinv_primary PRIMARY KEY ("KitInv")
) ;
COMMENT ON TABLE kitinv IS 'Inventory session records ';
COMMENT ON COLUMN kitinv."StartDate" IS 'Start date of inventory count';
COMMENT ON COLUMN kitinv."KitInv" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN kitinv."EndDate" IS 'End date of inventory count';


CREATE  TABLE kitinvit (
  "KitInv" numeric(10,0) NOT NULL,
  "Kit" character(30) NOT NULL,
  "Type" numeric(5,0),
  "KitOut" numeric(5,0),
  "DispCode" character(6),
  "Audit" numeric(10,0),
  CONSTRAINT kitinvit_primary PRIMARY KEY ("KitInv", "Kit")
) ;
COMMENT ON TABLE kitinvit IS 'Inventory session items';
COMMENT ON COLUMN kitinvit."Type" IS 'Record type (0=Scanned; 1=Not Scanned - participating dispensary; 2=Not Scanned - non-participating dispensary; 3=Appended)';
COMMENT ON COLUMN kitinvit."KitOut" IS 'Kit is out to a location/provider? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN kitinvit."KitInv" IS 'Primary key component, ID code to identify the kit inventory record. Ptr to KITINV.KitInv';
COMMENT ON COLUMN kitinvit."Kit" IS 'Primary key component, ID code of the counted kit. Ptr to KIT.Kit';
COMMENT ON COLUMN kitinvit."DispCode" IS 'Dispensary code, ptr to DISPCODE.DispCode';
COMMENT ON COLUMN kitinvit."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE kititem (
  "Kit" character(30) NOT NULL,
  "Item" numeric(10,0) NOT NULL,
  "Instrument" character(6),
  "TimesUsed" numeric(10,0),
  "Cost" numeric,
  "ID" character(12),
  "PurchaseDate" timestamp without time zone,
  CONSTRAINT kititem_primary PRIMARY KEY ("Kit", "Item")
) ;
CREATE INDEX IF NOT EXISTS kititem_instrument ON kititem USING btree ("Instrument") TABLESPACE pg_default;
COMMENT ON TABLE kititem IS 'Kit item information record';
COMMENT ON COLUMN kititem."TimesUsed" IS 'Number of times the kit has been checked out for use';
COMMENT ON COLUMN kititem."PurchaseDate" IS 'Date the item was purchased';
COMMENT ON COLUMN kititem."Kit" IS 'Primary key component, ID code of the kit. Ptr to KIT.Kit';
COMMENT ON COLUMN kititem."Item" IS 'Primary key component, item number within the kit';
COMMENT ON COLUMN kititem."Instrument" IS 'ID code of the instrument, ptr to INSTRUMT.Instrument';
COMMENT ON COLUMN kititem."ID" IS '(Optional) the serial number or ID number of the instrument.';
COMMENT ON COLUMN kititem."Cost" IS 'Original item cost (the cost of this individual item when the kit was first added to the system)';


CREATE  TABLE kittempl (
  "KitType" character(6) NOT NULL,
  "Instrument" character(6) NOT NULL,
  "Quantity" numeric(5,0),
  CONSTRAINT kittempl_primary PRIMARY KEY ("KitType", "Instrument")
) ;
COMMENT ON TABLE kittempl IS 'Template of the kits';
COMMENT ON COLUMN kittempl."Quantity" IS 'Number of these instruments contained within the kit';
COMMENT ON COLUMN kittempl."KitType" IS 'Primary key component, ID code of the kit type. Ptr to KITTYPE.KitType.';
COMMENT ON COLUMN kittempl."Instrument" IS 'Primary key component, ID code of the instrument. Ptr to INSTRUMT.Instrument';


CREATE  TABLE kittype (
  "KitType" character(6) NOT NULL,
  "Description" character(30),
  "Amount" numeric,
  "DefaultSterilization" numeric(5,0),
  "KitsBarCoded" numeric(5,0),
  "BarCode" character(30),
  "Inactive" numeric(5,0),
  CONSTRAINT kittype_primary PRIMARY KEY ("KitType")
) ;
COMMENT ON TABLE kittype IS 'Record of the kit type';
COMMENT ON COLUMN kittype."KitsBarCoded" IS 'Kits barcoded? (0 = No, 1 = Yes)';
COMMENT ON COLUMN kittype."KitType" IS 'Id code of the kit type';
COMMENT ON COLUMN kittype."Inactive" IS 'Make Kit Type inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN kittype."Description" IS 'Description of the kit type';
COMMENT ON COLUMN kittype."DefaultSterilization" IS 'Default numbers of days this kit will be sterile for on sterilization';
COMMENT ON COLUMN kittype."BarCode" IS 'Bar code for the kittype';
COMMENT ON COLUMN kittype."Amount" IS 'Replacement cost for this cassette.';


CREATE  TABLE labcode (
  "LabCode" character(6) NOT NULL,
  "Name" character(50),
  "Address1" character(30),
  "Address2" character(30),
  "City" character(24),
  "Province" character(6),
  "Postal" character(15),
  "AddressOther" character(15),
  "Area" character(4),
  "Phone" character(8),
  "IsInternal" numeric(5,0),
  "Note" character varying(4000),
  "Monday" numeric(5,0),
  "Tuesday" numeric(5,0),
  "Wednesday" numeric(5,0),
  "Thursday" numeric(5,0),
  "Friday" numeric(5,0),
  "Saturday" numeric(5,0),
  "Sunday" numeric(5,0),
  "Inactive" numeric(5,0),
  CONSTRAINT labcode_primary PRIMARY KEY ("LabCode")
) ;
COMMENT ON TABLE labcode IS 'Codes to identify the Laboratories';
COMMENT ON COLUMN labcode."Wednesday" IS 'Lab is open on Wednesdays? (0 = No, 1 = Yes)';
COMMENT ON COLUMN labcode."Tuesday" IS 'Lab is open on Tuesdays? (0 = No, 1 = Yes)';
COMMENT ON COLUMN labcode."Thursday" IS 'Lab is open on Thursdays? (0 = No, 1 = Yes)';
COMMENT ON COLUMN labcode."Sunday" IS 'Lab is open on Sundays? (0 = No, 1 = Yes)';
COMMENT ON COLUMN labcode."Saturday" IS 'Lab is open on Saturdays? (0 = No, 1 = Yes)';
COMMENT ON COLUMN labcode."Province" IS 'Province / state, ptr to CITY.Province';
COMMENT ON COLUMN labcode."Postal" IS 'Postal / zip code, ptr to CITY.Postal';
COMMENT ON COLUMN labcode."Phone" IS 'Telephone number';
COMMENT ON COLUMN labcode."Note" IS 'Text area to enter notes about the laboratory';
COMMENT ON COLUMN labcode."Name" IS 'Full name of the lab';
COMMENT ON COLUMN labcode."Monday" IS 'Lab is open on Mondays? (0 = No, 1 = Yes)';
COMMENT ON COLUMN labcode."LabCode" IS 'Primary key, code that identifies the lab';
COMMENT ON COLUMN labcode."IsInternal" IS 'Is internal? (0 = No, 1 = Yes)';
COMMENT ON COLUMN labcode."Inactive" IS 'Make Labcode inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN labcode."Friday" IS 'Lab is open on Fridays? (0 = No, 1 = Yes)';
COMMENT ON COLUMN labcode."City" IS 'City, ptr to CITY.City';
COMMENT ON COLUMN labcode."Area" IS 'Telephone area code';
COMMENT ON COLUMN labcode."AddressOther" IS 'For USA, represents County. For Dutch, represents Room Number.';
COMMENT ON COLUMN labcode."Address2" IS 'Laboratory address line 2';
COMMENT ON COLUMN labcode."Address1" IS 'Laboratory address line 1';


CREATE  TABLE labcosts (
  "LabCosts" numeric(10,0) NOT NULL,
  "LabOrder" numeric(10,0) NOT NULL,
  "Item" numeric(5,0) NOT NULL,
  "Date" timestamp without time zone,
  "User" numeric(10,0),
  "Material" character(20),
  "Unit" numeric,
  "Cost" numeric,
  "Technician" numeric(10,0),
  "WeightDispensed" numeric,
  "WeightReturned" numeric,
  "WeightType" numeric(5,0),
  "UnitDesc" character(10),
  "MatCostPerUnit" numeric,
  "Invoice" character varying(12),
  "LCStatus" character(6),
  CONSTRAINT labcosts_primary PRIMARY KEY ("LabCosts")
) ;
CREATE INDEX IF NOT EXISTS labcosts_laborder ON labcosts USING btree ("LabOrder", "Item") TABLESPACE pg_default;
COMMENT ON TABLE labcosts IS 'Record of the costs related to a lab procedure';
COMMENT ON COLUMN labcosts."WeightType" IS 'Type (0 = an amount used with a possible cost, 1 = amount dispensed or returned with a cost of 0)';
COMMENT ON COLUMN labcosts."WeightReturned" IS 'Number of units returned';
COMMENT ON COLUMN labcosts."WeightDispensed" IS 'Number of units dispensed';
COMMENT ON COLUMN labcosts."User" IS 'User Id of entry user, ptr to USERS.User';
COMMENT ON COLUMN labcosts."UnitDesc" IS 'Description of material unit for a lab material used (eg. grams)';
COMMENT ON COLUMN labcosts."Unit" IS 'Number of units used (ie: ounces)';
COMMENT ON COLUMN labcosts."Technician" IS 'User ID of the technician that worked on the lab, ptr to USERS.User';
COMMENT ON COLUMN labcosts."Material" IS 'Type of material used, ptr to MATERIAL.Material';
COMMENT ON COLUMN labcosts."MatCostPerUnit" IS 'Cost per unit for the lab material used (eg. 2.50) ';
COMMENT ON COLUMN labcosts."LabOrder" IS 'Id code of the parent lab order, ptr to LABORDER.LabOrder';
COMMENT ON COLUMN labcosts."LabCosts" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN labcosts."LCStatus" IS 'Lab invoice status code, ptr to LCSTATUS.Code';
COMMENT ON COLUMN labcosts."Item" IS 'Id code of the parent item, ptr to LABITEM.Item';
COMMENT ON COLUMN labcosts."Invoice" IS 'Lab invoice #';
COMMENT ON COLUMN labcosts."Date" IS 'Date the cost was added';
COMMENT ON COLUMN labcosts."Cost" IS 'Cost in dollars ($) for this lab';


CREATE  TABLE labels (
  "LABELS_AutoDec" numeric(10,0) NOT NULL,
  "LABELS_Type" numeric(10,0),
  "LABELS_Description" character(50),
  "LABELS_Flags" numeric(10,0),
  labels_data bytea,
  "LABELS_LabelSelect" numeric(5,0),
  "LABELS_LblSetupId" numeric(10,0),
  "LABELS_DefaultCopies" numeric(5,0),
  CONSTRAINT labels_primaryindex PRIMARY KEY ("LABELS_AutoDec")
) ;
CREATE INDEX IF NOT EXISTS "LABELS_Type" ON labels USING btree ("LABELS_Type") TABLESPACE pg_default;
COMMENT ON TABLE labels IS 'Custom label reports, created with form designer';
COMMENT ON COLUMN labels.labels_data IS 'Info for the placement of fields and text, including fonts, colors etc...non-readable by SQL. Note: In Oracle 9i this field is Type: BLOB';
COMMENT ON COLUMN labels."LABELS_Type" IS 'Label Type';
COMMENT ON COLUMN labels."LABELS_LblSetupId" IS 'Id code of the label setup';
COMMENT ON COLUMN labels."LABELS_LabelSelect" IS 'Selected? (0 = No, 1 = Yes)';
COMMENT ON COLUMN labels."LABELS_Flags" IS 'DEPRECATED';
COMMENT ON COLUMN labels."LABELS_Description" IS 'Description / name of the label';
COMMENT ON COLUMN labels."LABELS_DefaultCopies" IS 'Default number of copies';
COMMENT ON COLUMN labels."LABELS_AutoDec" IS 'Primary key';


CREATE  TABLE labeltmp (
  "Batch" numeric(10,0) NOT NULL,
  "BarCode" character varying(30)
) ;
COMMENT ON TABLE labeltmp IS 'Holds temporary data used to print Kit labels';
COMMENT ON COLUMN labeltmp."Batch" IS 'Internal batch number, from sequence';
COMMENT ON COLUMN labeltmp."BarCode" IS 'Barcode for this kit label';


CREATE  TABLE labhis (
  "LabHis" numeric(10,0) NOT NULL,
  "Provider" character(10),
  "LabOrder" numeric(10,0) NOT NULL,
  "Item" numeric(5,0) NOT NULL,
  "IsIn" numeric(5,0),
  "DateOut" timestamp without time zone,
  "TimeOut" numeric(10,0),
  "DateIn" timestamp without time zone,
  "TimeIn" numeric(10,0),
  CONSTRAINT labhis_primary PRIMARY KEY ("LabHis")
) ;
CREATE INDEX IF NOT EXISTS labhis_laborder ON labhis USING btree ("LabOrder", "Item") TABLESPACE pg_default;
COMMENT ON TABLE labhis IS 'History record of lab requests';
COMMENT ON COLUMN labhis."TimeOut" IS 'Time lab went out, ptr to LABORDER.TimeOut';
COMMENT ON COLUMN labhis."TimeIn" IS 'Time lab returned, ptr to LABORDER.TimeIn';
COMMENT ON COLUMN labhis."Provider" IS 'ID code of the Provider making lab order, ptr to PRODUCER.Producer.';
COMMENT ON COLUMN labhis."LabOrder" IS 'LabOrder code, ptr to LABORDER.LabOrder';
COMMENT ON COLUMN labhis."LabHis" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN labhis."Item" IS 'Item number within this LabOrder, ptr to LABITEM.Item';
COMMENT ON COLUMN labhis."IsIn" IS 'Is lab in? (0 = No, 1 = Yes)';
COMMENT ON COLUMN labhis."DateOut" IS 'Date lab went out, ptr to LABORDER.DateOut';
COMMENT ON COLUMN labhis."DateIn" IS 'Date lab returned, ptr to LABORDER.DateIn';


CREATE  TABLE labitem (
  "LabOrder" numeric(10,0) NOT NULL,
  "Item" numeric(5,0) NOT NULL,
  "Provider" character(10),
  "Date" timestamp without time zone,
  "Text" character varying(4000),
  "Comment" character varying(4000),
  "Redo" numeric(5,0),
  "RedoItem" numeric(5,0),
  "ApprovalUser" numeric(10,0),
  "ApprovalDate" timestamp without time zone,
  "ExpectedDate" timestamp without time zone,
  "DateChanged" numeric(5,0),
  "LabOut" numeric(5,0),
  "DateOut" timestamp without time zone,
  "TimeOut" numeric(10,0),
  "OutUser" numeric(10,0),
  "DateIn" timestamp without time zone,
  "TimeIn" numeric(10,0),
  "User" numeric(10,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "LabCode" character(6),
  CONSTRAINT labitem_primary PRIMARY KEY ("LabOrder", "Item")
) ;
COMMENT ON TABLE labitem IS 'Lab item details';
COMMENT ON COLUMN labitem."User" IS 'ID code of entry user, ptr to USERS.User';
COMMENT ON COLUMN labitem."TimeOut" IS 'If LabOut - Time lab went out';
COMMENT ON COLUMN labitem."TimeIn" IS 'If LabOut = 0, time lab returned';
COMMENT ON COLUMN labitem."Text" IS 'Text area to enter item description of needs';
COMMENT ON COLUMN labitem."RedoItem" IS 'If Redo, previous item number';
COMMENT ON COLUMN labitem."Redo" IS 'Redo? (0 = No, 1 = Yes)';
COMMENT ON COLUMN labitem."Provider" IS 'ID code of the Provider this lab item is for, ptr to PRODUCER.Producer';
COMMENT ON COLUMN labitem."OutUser" IS 'ID code of user who signed lab out, ptr to USERS.User';
COMMENT ON COLUMN labitem."LabOut" IS 'Lab out? (0 = No, 1 = Yes, 2=In but requested to go out)';
COMMENT ON COLUMN labitem."LabOrder" IS 'Primary key component, ID of the parent LabOrder. Ptr to LABORDER.LabOrder';
COMMENT ON COLUMN labitem."LabCode" IS 'If LabOut - Id code of the lab, ptr to LABCODE.Labcode';
COMMENT ON COLUMN labitem."Item" IS 'Primary key component, item number within this LabOrder, starting with 1';
COMMENT ON COLUMN labitem."ExpectedDate" IS 'Expected date of return';
COMMENT ON COLUMN labitem."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN labitem."DateOut" IS 'If LabOut - Date lab went out';
COMMENT ON COLUMN labitem."DateIn" IS 'If LabOut = 0, date lab returned';
COMMENT ON COLUMN labitem."DateChanged" IS 'ExpectedDate changed? (0 = No, 1 = Yes)';
COMMENT ON COLUMN labitem."Date" IS 'Date of entry / date item was created';
COMMENT ON COLUMN labitem."Comment" IS 'An internal comment field';
COMMENT ON COLUMN labitem."Audit" IS 'Audit record of most recent change, ptr to AUDITHIS.Audit.';
COMMENT ON COLUMN labitem."ApprovalUser" IS 'ID code of approval user, ptr to USERS.User';
COMMENT ON COLUMN labitem."ApprovalDate" IS 'Date of approval';


CREATE  TABLE labitemh (
  "LabItemH" numeric(10,0) NOT NULL,
  "LabOrder" numeric(10,0),
  "Item" numeric(5,0),
  "Provider" character(10),
  "Date" timestamp without time zone,
  "Text" character varying(4000),
  "Comment" character varying(4000),
  "Redo" numeric(5,0),
  "RedoItem" numeric(5,0),
  "ApprovalUser" numeric(10,0),
  "ApprovalDate" timestamp without time zone,
  "ExpectedDate" timestamp without time zone,
  "DateChanged" numeric(5,0),
  "LabOut" numeric(5,0),
  "DateOut" timestamp without time zone,
  "TimeOut" numeric(10,0),
  "OutUser" numeric(10,0),
  "DateIn" timestamp without time zone,
  "TimeIn" numeric(10,0),
  "User" numeric(10,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "LabCode" character(6),
  CONSTRAINT labitemh_primary PRIMARY KEY ("LabItemH")
) ;
CREATE INDEX IF NOT EXISTS labitemh_audit ON labitemh USING btree ("Audit") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS labitemh_laborder ON labitemh USING btree ("LabOrder") TABLESPACE pg_default;
COMMENT ON TABLE labitemh IS 'Lab Item History';
COMMENT ON COLUMN labitemh."User" IS 'Id code of entry user, ptr to USERS.User';
COMMENT ON COLUMN labitemh."TimeOut" IS 'If LabOut - Time lab went out';
COMMENT ON COLUMN labitemh."TimeIn" IS 'If LabOut = 0, time lab returned';
COMMENT ON COLUMN labitemh."Text" IS 'Text area to enter item description of needs';
COMMENT ON COLUMN labitemh."RedoItem" IS 'If Redo, previous item number';
COMMENT ON COLUMN labitemh."Redo" IS 'Redo? (0 = No, 1 = Yes)';
COMMENT ON COLUMN labitemh."Provider" IS 'Id code of the Provider this lab item is for, ptr to PRODUCER.Producer';
COMMENT ON COLUMN labitemh."OutUser" IS 'Id code of user who signed lab out, ptr to USERS.User';
COMMENT ON COLUMN labitemh."LabOut" IS 'Lab out? (0 = No, 1 = Yes, 2=In but requested to go out)';
COMMENT ON COLUMN labitemh."LabOrder" IS 'Id code of the parent LabOrder, ptr to LABORDER.LabOrder';
COMMENT ON COLUMN labitemh."LabItemH" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN labitemh."LabCode" IS 'If LabOut - Id code of the lab, ptr to LABCODE.Labcode';
COMMENT ON COLUMN labitemh."Item" IS 'Item number within this LabOrder, starting with 1';
COMMENT ON COLUMN labitemh."ExpectedDate" IS 'Expected date of return';
COMMENT ON COLUMN labitemh."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN labitemh."DateOut" IS 'If LabOut - Date lab went out';
COMMENT ON COLUMN labitemh."DateIn" IS 'If LabOut = 0, date lab returned';
COMMENT ON COLUMN labitemh."DateChanged" IS 'ExpectedDate changed? (0 = No, 1 = Yes)';
COMMENT ON COLUMN labitemh."Date" IS 'Date of entry / date item was created';
COMMENT ON COLUMN labitemh."Comment" IS 'An internal comment field';
COMMENT ON COLUMN labitemh."Audit" IS 'Audit record of most recent change, ptr to AUDITHIS.Audit.';
COMMENT ON COLUMN labitemh."ApprovalUser" IS 'Id code of approval user, ptr to USERS.User';
COMMENT ON COLUMN labitemh."ApprovalDate" IS 'Date of approval';


CREATE  TABLE laboext (
  "LabOrder" numeric(10,0) NOT NULL,
  "ExternalApplication" character varying(50),
  "ExternalId" character varying(50),
  "ProcedureDescription" character varying(50),
  "CompanyName" character varying(50),
  CONSTRAINT laboext_pk PRIMARY KEY ("LabOrder")
) ;
COMMENT ON TABLE laboext IS 'Additional information for lab orders added by an external application';
COMMENT ON COLUMN laboext."ProcedureDescription" IS 'description of the lab in the external application';
COMMENT ON COLUMN laboext."LabOrder" IS 'Primary key, lab order that this external information is for. Ptr to LABORDER.LabOrder.';
COMMENT ON COLUMN laboext."ExternalId" IS 'identifier for the lab in the external application';
COMMENT ON COLUMN laboext."ExternalApplication" IS 'Application that created the external lab order';
COMMENT ON COLUMN laboext."CompanyName" IS 'name of the lab company in the external appliation';


CREATE  TABLE laborder (
  "LabOrder" numeric(10,0) NOT NULL,
  "CaseNo" character varying(10),
  "Patient" numeric(10,0) NOT NULL,
  "LabProcedure" character(7),
  "Discipline" character(6),
  "Date" timestamp without time zone,
  "RemakeStudent" numeric(5,0),
  "RemakeStaff" numeric(5,0),
  "RemakeLabOrder" numeric(10,0),
  "WaiveCharges" numeric(5,0),
  "LabOut" numeric(5,0),
  "LabCode" character(6),
  "DateOut" timestamp without time zone,
  "TimeOut" numeric(10,0),
  "User" numeric(10,0),
  "Deleted" numeric(5,0),
  "CurrentItem" numeric(5,0),
  "Status" numeric(5,0),
  "CompletionDate" timestamp without time zone,
  "TotalCost" numeric,
  "TotalCharge" numeric,
  "IsOrtho" numeric(5,0),
  "OrigRecNo" numeric(10,0),
  "Audit" numeric(10,0),
  "IseLab" numeric(5,0),
  CONSTRAINT laborder_primary PRIMARY KEY ("LabOrder")
) ;
CREATE INDEX IF NOT EXISTS laborder_patient ON laborder USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE laborder IS 'Lab Order details.';
COMMENT ON COLUMN laborder."WaiveCharges" IS 'If lab is a remake, waive charges? (0 = No, 1 = Yes)';
COMMENT ON COLUMN laborder."User" IS 'User ID of entry user, ptr to USERS.User';
COMMENT ON COLUMN laborder."TotalCost" IS 'Sum of lab costs';
COMMENT ON COLUMN laborder."TotalCharge" IS 'Total dollar ($) amount of the customary charge';
COMMENT ON COLUMN laborder."TimeOut" IS 'If LabOut=1, the time lab went out';
COMMENT ON COLUMN laborder."Status" IS 'Status of the order (0=Unapproved, 1=In-Progress, 2=Completed, 3=Closed)';
COMMENT ON COLUMN laborder."RemakeStudent" IS 'Is this a student remake? (0 = No, 1 = Yes)';
COMMENT ON COLUMN laborder."RemakeStaff" IS 'Is this a staff remake? (0 = No, 1 = Yes)';
COMMENT ON COLUMN laborder."RemakeLabOrder" IS 'If lab is a remake, previous LabOrder number (ptr to LABORDER.LabOrder)';
COMMENT ON COLUMN laborder."Patient" IS 'Patient that the lab order is for, ptr to PATIENT.Patient';
COMMENT ON COLUMN laborder."OrigRecNo" IS 'The TRX.OrigRecNo of the LabOrder.LabProcedure';
COMMENT ON COLUMN laborder."LabProcedure" IS 'Code of the lab procedure, ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN laborder."LabOut" IS 'Lab out? (0 = No, 1 = Yes, 2= In but requested to go out)';
COMMENT ON COLUMN laborder."LabOrder" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN laborder."LabCode" IS 'If LabOut - ID code of the lab, ptr to LABCODE.Labcode';
COMMENT ON COLUMN laborder."IseLab" IS 'Is eLab? (0 = No, 1 = Yes)';
COMMENT ON COLUMN laborder."IsOrtho" IS 'Is Ortho? (0 = No, 1 = Yes)';
COMMENT ON COLUMN laborder."Discipline" IS 'Discipline for this lab, ptr to DISCIPL.Discipline';
COMMENT ON COLUMN laborder."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN laborder."DateOut" IS 'If LabOut=1, the date lab went out';
COMMENT ON COLUMN laborder."Date" IS 'Date the lab order was opened / created';
COMMENT ON COLUMN laborder."CurrentItem" IS 'Current lab item, ptr to LABITEM.Item';
COMMENT ON COLUMN laborder."CompletionDate" IS 'If completed - date of completion';
COMMENT ON COLUMN laborder."CaseNo" IS 'The case number of the lab order';
COMMENT ON COLUMN laborder."Audit" IS 'Audit record of most recent change, ptr to AUDITHIS.Audit.';


CREATE  TABLE labordh (
  "LabOrdH" numeric(10,0) NOT NULL,
  "LabItemH" numeric(10,0),
  "HisView" numeric(5,0),
  "LabOrder" numeric(10,0),
  "CaseNo" character varying(10),
  "Patient" numeric(10,0),
  "LabProcedure" character(7),
  "Discipline" character(6),
  "Date" timestamp without time zone,
  "RemakeStudent" numeric(5,0),
  "RemakeStaff" numeric(5,0),
  "RemakeLabOrder" numeric(10,0),
  "WaiveCharges" numeric(5,0),
  "LabOut" numeric(5,0),
  "LabCode" character(6),
  "DateOut" timestamp without time zone,
  "TimeOut" numeric(10,0),
  "User" numeric(10,0),
  "Deleted" numeric(5,0),
  "CurrentItem" numeric(5,0),
  "Status" numeric(5,0),
  "CompletionDate" timestamp without time zone,
  "TotalCost" numeric,
  "TotalCharge" numeric,
  "IsOrtho" numeric(5,0),
  "OrigRecNo" numeric(10,0),
  "Audit" numeric(10,0),
  "IseLab" numeric(5,0),
  CONSTRAINT labordh_primary PRIMARY KEY ("LabOrdH")
) ;
CREATE INDEX IF NOT EXISTS labordh_audit ON labordh USING btree ("Audit") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS labordh_laborder ON labordh USING btree ("LabOrder") TABLESPACE pg_default;
COMMENT ON TABLE labordh IS 'Lab Order History';
COMMENT ON COLUMN labordh."WaiveCharges" IS 'If lab is a remake, waive charges? (0 = No, 1 = Yes)';
COMMENT ON COLUMN labordh."User" IS 'User Id of entry user, ptr to USERS.User';
COMMENT ON COLUMN labordh."TotalCost" IS 'Sum of lab costs';
COMMENT ON COLUMN labordh."TotalCharge" IS 'Total dollar ($) amount of the customary charge';
COMMENT ON COLUMN labordh."TimeOut" IS 'If LabOut - Time lab went out';
COMMENT ON COLUMN labordh."Status" IS 'Status of the order (0=Unapproved, 1=In-Progress, 2=Completed, 3=Closed)';
COMMENT ON COLUMN labordh."RemakeStudent" IS 'Is this a student remake? (0 = No, 1 = Yes)';
COMMENT ON COLUMN labordh."RemakeStaff" IS 'Is this a staff remake? (0 = No, 1 = Yes)';
COMMENT ON COLUMN labordh."RemakeLabOrder" IS 'If lab is a remake, previous LabOrder number';
COMMENT ON COLUMN labordh."Patient" IS 'Id code of the patient the order is for, ptr to PATIENT.Patient';
COMMENT ON COLUMN labordh."OrigRecNo" IS 'The TRX.OrigRecNo of the LabOrder.LabProcedure';
COMMENT ON COLUMN labordh."LabProcedure" IS 'Code of the lab procedure, ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN labordh."LabOut" IS 'Lab out? (0 = No, 1 = Yes, 2= In but requested to go out)';
COMMENT ON COLUMN labordh."LabOrder" IS 'Ptr to LABORDER.LabOrder.';
COMMENT ON COLUMN labordh."LabOrdH" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN labordh."LabItemH" IS 'Ptr to LABITEMH.LabItemH, or 0.';
COMMENT ON COLUMN labordh."LabCode" IS 'If LabOut - Id code of the lab, ptr to LABCODE.Labcode';
COMMENT ON COLUMN labordh."IseLab" IS 'Is eLab? (0 = No, 1 = Yes)';
COMMENT ON COLUMN labordh."IsOrtho" IS 'Is Ortho? (0 = No, 1 = Yes)';
COMMENT ON COLUMN labordh."HisView" IS 'Always show in history? (0 = only show with full history, 1 = always show in history)';
COMMENT ON COLUMN labordh."Discipline" IS ' Id code to identify the discipline for this lab, ptr to DISCIPL.Discipline';
COMMENT ON COLUMN labordh."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN labordh."DateOut" IS 'If LabOut - date lab went out';
COMMENT ON COLUMN labordh."Date" IS 'Date the lab order was opened / created';
COMMENT ON COLUMN labordh."CurrentItem" IS 'Current lab item, ptr to LABITEM.LabItem';
COMMENT ON COLUMN labordh."CompletionDate" IS 'If completed - date of completion';
COMMENT ON COLUMN labordh."CaseNo" IS 'The case number';
COMMENT ON COLUMN labordh."Audit" IS 'Audit record of most recent change, ptr to AUDITHIS.Audit.';


CREATE  TABLE labotrx (
  "LabOrder" numeric(10,0) NOT NULL,
  "OrigRecNo" numeric(10,0) NOT NULL,
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT labotrx_primary PRIMARY KEY ("LabOrder", "OrigRecNo")
) ;
CREATE INDEX IF NOT EXISTS labotrx_origrecno ON labotrx USING btree ("OrigRecNo") TABLESPACE pg_default;
COMMENT ON TABLE labotrx IS 'Lab Treatments';
COMMENT ON COLUMN labotrx."OrigRecNo" IS 'Primary key component, the TRX.OrigRecNo of the treatment lab is for.';
COMMENT ON COLUMN labotrx."LabOrder" IS 'Primary key component, the lab order that the treatment is for. Ptr to LABORDER.LabOrder';
COMMENT ON COLUMN labotrx."Deleted" IS 'Is this link deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN labotrx."Audit" IS 'Audit record of most recent change, ptr to AUDITHIS.Audit.';


CREATE  TABLE labotrxh (
  "LabOTrxH" numeric(10,0) NOT NULL,
  "LabOrder" numeric(10,0),
  "OrigRecNo" numeric(10,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT labotrxh_primary PRIMARY KEY ("LabOTrxH")
) ;
CREATE INDEX IF NOT EXISTS labotrxh_audit ON labotrxh USING btree ("Audit") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS labotrxh_laborder ON labotrxh USING btree ("LabOrder") TABLESPACE pg_default;
COMMENT ON TABLE labotrxh IS 'Lab Treatment History';
COMMENT ON COLUMN labotrxh."OrigRecNo" IS 'The TRX.OrigRecNo of the treatment lab is for';
COMMENT ON COLUMN labotrxh."LabOrder" IS 'Id code of the lab order';
COMMENT ON COLUMN labotrxh."LabOTrxH" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN labotrxh."Deleted" IS 'Is this link deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN labotrxh."Audit" IS 'Audit record of most recent change, ptr to AUDITHIS.Audit.';


CREATE  TABLE labptout (
  "LabPrintOut" numeric(10,0) NOT NULL,
  "LabOrder" numeric(10,0),
  content bytea,
  "Audit" numeric(10,0),
  CONSTRAINT labptout_primary PRIMARY KEY ("LabPrintOut")
) ;
COMMENT ON TABLE labptout IS 'Lab Print Out Details';
COMMENT ON COLUMN labptout.content IS 'Content of the print out. Note: In Oracle 9i this field is Type: BLOB';
COMMENT ON COLUMN labptout."LabPrintOut" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN labptout."LabOrder" IS 'ID code of the lab order, ptr to LABORDER.LabOrder';
COMMENT ON COLUMN labptout."Audit" IS 'Audit record, ptr to AUDITHIS.Audit.';


CREATE  TABLE labsitem (
  "LabSItem" numeric(10,0) NOT NULL,
  "LabOrder" numeric(10,0) NOT NULL,
  "Item" numeric(5,0) NOT NULL,
  "Description" character(30),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT labsitem_primary PRIMARY KEY ("LabSItem")
) ;
CREATE INDEX IF NOT EXISTS labsitem_laborder ON labsitem USING btree ("LabOrder", "Item") TABLESPACE pg_default;
COMMENT ON TABLE labsitem IS 'Lab Supplement Item Details';
COMMENT ON COLUMN labsitem."LabSItem" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN labsitem."LabOrder" IS 'ID code of the parent LabOrder, ptr to LABORDER.LabOrder';
COMMENT ON COLUMN labsitem."Item" IS 'Item number in the parent lab order, ptr to LABITEM.Item';
COMMENT ON COLUMN labsitem."Description" IS 'Description of the supplement item.';
COMMENT ON COLUMN labsitem."Deleted" IS 'Is this item deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN labsitem."Audit" IS 'Audit record of most recent change, ptr to AUDITHIS.Audit.';


CREATE  TABLE labsith (
  "LabSItH" numeric(10,0) NOT NULL,
  "LabSItem" numeric(10,0),
  "LabOrder" numeric(10,0),
  "Item" numeric(5,0),
  "Description" character(30),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT labsith_primary PRIMARY KEY ("LabSItH")
) ;
CREATE INDEX IF NOT EXISTS labsith_audit ON labsith USING btree ("Audit") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS labsith_laborder ON labsith USING btree ("LabOrder") TABLESPACE pg_default;
COMMENT ON TABLE labsith IS 'Lab Supplemental Item History';
COMMENT ON COLUMN labsith."LabSItem" IS 'Ptr to LABSItem.LABSItem';
COMMENT ON COLUMN labsith."LabSItH" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN labsith."LabOrder" IS 'Id code of the parent LabOrder, ptr to LABORDER.LabOrder';
COMMENT ON COLUMN labsith."Item" IS 'Parent item number';
COMMENT ON COLUMN labsith."Description" IS 'Description of the labsitem';
COMMENT ON COLUMN labsith."Deleted" IS 'Is this item deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN labsith."Audit" IS 'Audit record of most recent change, ptr to AUDITHIS.Audit.';


CREATE  TABLE labttrx (
  "Patient" numeric(10,0) NOT NULL,
  "OrigRecNo" numeric(10,0) NOT NULL,
  "Audit" numeric(10,0),
  "PtCaseId" numeric(10,0),
  CONSTRAINT labttrx_primary PRIMARY KEY ("Patient", "OrigRecNo")
) ;
COMMENT ON TABLE labttrx IS 'Temporary Lab Treatments Table';
COMMENT ON COLUMN labttrx."PtCaseId" IS 'Optional PtCase Id for tying lab order/txs to Oral Surgery case';
COMMENT ON COLUMN labttrx."Patient" IS 'Primary key component, Patient Id';
COMMENT ON COLUMN labttrx."OrigRecNo" IS 'Primary key component, OrigRecNo of TRX treatment';
COMMENT ON COLUMN labttrx."Audit" IS 'Audit record for this lab tx entry, ptr to AUDITHIS.Audit';


CREATE  TABLE lblsetup (
  "LBLSETUP_AutoDec" numeric(10,0) NOT NULL,
  "LBLSETUP_Description" character(50),
  "LBLSETUP_Flags" numeric(10,0),
  "LBLSETUP_TopMgn" numeric(5,0),
  "LBLSETUP_BtmMgn" numeric(5,0),
  "LBLSETUP_LftMgn" numeric(5,0),
  "LBLSETUP_RghtMgn" numeric(5,0),
  "LBLSETUP_HrzMgn" numeric(5,0),
  "LBLSETUP_VerMgn" numeric(5,0),
  "LBLSETUP_Width" numeric(5,0),
  "LBLSETUP_Height" numeric(5,0),
  "LBLSETUP_Row" numeric(5,0),
  "LBLSETUP_Col" numeric(5,0),
  "LBLSETUP_TopInnerMgn" numeric(5,0),
  "LBLSETUP_BtmInnerMgn" numeric(5,0),
  "LBLSETUP_LftInnerMgn" numeric(5,0),
  "LBLSETUP_RghtInnerMgn" numeric(5,0),
  "LBLSETUP_Landscape" numeric(5,0),
  CONSTRAINT lblsetup_primaryindex PRIMARY KEY ("LBLSETUP_AutoDec")
) ;
COMMENT ON TABLE lblsetup IS 'Codes neccessary to define labels created by the user';
COMMENT ON COLUMN lblsetup."LBLSETUP_Width" IS 'Label width, expressed in 1/96 inches';
COMMENT ON COLUMN lblsetup."LBLSETUP_VerMgn" IS 'Vertical margin, expressed in 1/96 inches';
COMMENT ON COLUMN lblsetup."LBLSETUP_TopMgn" IS 'Top margin, expressed in 1/96 inches';
COMMENT ON COLUMN lblsetup."LBLSETUP_TopInnerMgn" IS 'Top inner margin, expressed in 1/96 inches, defaults to 0';
COMMENT ON COLUMN lblsetup."LBLSETUP_Row" IS 'Row # of the item within the label';
COMMENT ON COLUMN lblsetup."LBLSETUP_RghtMgn" IS 'Right margin, expressed in 1/96 inches';
COMMENT ON COLUMN lblsetup."LBLSETUP_RghtInnerMgn" IS 'Right inner margin, expressed in 1/96 inches, defaults to 0';
COMMENT ON COLUMN lblsetup."LBLSETUP_LftMgn" IS 'Left margin, expressed in 1/96 inches';
COMMENT ON COLUMN lblsetup."LBLSETUP_LftInnerMgn" IS 'Left inner margin, expressed in 1/96 inches, defaults to 0';
COMMENT ON COLUMN lblsetup."LBLSETUP_Landscape" IS 'Is landscape? (0 = No, 1 = Yes)';
COMMENT ON COLUMN lblsetup."LBLSETUP_HrzMgn" IS 'Horizontal margin, expressed in 1/96 inches';
COMMENT ON COLUMN lblsetup."LBLSETUP_Height" IS 'Label height, expressed in 1/96 inches';
COMMENT ON COLUMN lblsetup."LBLSETUP_Flags" IS 'DEPRECATED';
COMMENT ON COLUMN lblsetup."LBLSETUP_Description" IS 'Name / description of the label';
COMMENT ON COLUMN lblsetup."LBLSETUP_Col" IS 'Column # of the item within the label';
COMMENT ON COLUMN lblsetup."LBLSETUP_BtmMgn" IS 'Bottom margin, expressed in 1/96 inches';
COMMENT ON COLUMN lblsetup."LBLSETUP_BtmInnerMgn" IS 'Bottom inner margin, expressed in 1/96 inches, defaults to 0';
COMMENT ON COLUMN lblsetup."LBLSETUP_AutoDec" IS 'Primary key';


CREATE  TABLE lbpayer (
  "LBPayer" character(6) NOT NULL,
  "Description" character varying(50),
  "Bank" character(6),
  "Payment" character(6),
  "Inactive" numeric(5,0),
  "DefaultFolder" character varying(255),
  "FieldDelimeter" numeric(5,0),
  "DelimeterChar" character(1),
  "HasHeader" numeric(5,0),
  "HeaderRows" numeric(5,0),
  "HeadDateRow" numeric(5,0),
  "HeadDateCol" numeric(5,0),
  "HeadTotalRow" numeric(5,0),
  "HeadTotalCol" numeric(5,0),
  "HeadTraceRow" numeric(5,0),
  "HeadTraceCol" numeric(5,0),
  "HeadAcctNoRow" numeric(5,0),
  "HeadAcctNoCol" numeric(5,0),
  "PatientCol" numeric(5,0),
  "DateCol" numeric(5,0),
  "AmountCol" numeric(5,0),
  "PmtCodeCol" numeric(5,0),
  "DescriptionCol" numeric(5,0),
  "ReferenceCol" numeric(5,0),
  "DateFormat" numeric(5,0),
  "DateDelimeter" numeric(5,0),
  "DateDelimeterChar" character(1),
  "AmountFormat" numeric(5,0),
  CONSTRAINT lbpayer_primary PRIMARY KEY ("LBPayer")
) ;
COMMENT ON TABLE lbpayer IS 'Lockbox Payer table';
COMMENT ON COLUMN lbpayer."ReferenceCol" IS 'Column reference#/trace# for specific patient payment is in (Optional), may be store in EPBITEM.BankRef';
COMMENT ON COLUMN lbpayer."PmtCodeCol" IS 'Column payment method code is in (Optional)';
COMMENT ON COLUMN lbpayer."Payment" IS 'Payment code that will be used to add payments for (axiUm PAYMENT.Payment)';
COMMENT ON COLUMN lbpayer."PatientCol" IS 'Column that patient Id/Chart# is in (Required column)';
COMMENT ON COLUMN lbpayer."LBPayer" IS 'Primary key, Lockbox payer code';
COMMENT ON COLUMN lbpayer."Inactive" IS 'Inactive 0=No, 1=Yes';
COMMENT ON COLUMN lbpayer."HeaderRows" IS 'number of header rows 0..9';
COMMENT ON COLUMN lbpayer."HeadTraceRow" IS 'Row for reference#/trace# for bulk payment (Optional), may be store in EPBATACH.TransRefNo';
COMMENT ON COLUMN lbpayer."HeadTraceCol" IS 'Col for reference#/trace#';
COMMENT ON COLUMN lbpayer."HeadTotalRow" IS 'Row for total for bulk payment (Optional), may be store in EPBATACH.OpenBalance';
COMMENT ON COLUMN lbpayer."HeadTotalCol" IS 'Col for total';
COMMENT ON COLUMN lbpayer."HeadDateRow" IS 'Row for date for bulk payment (Optional), may be store in EPBATACH.OpenDate';
COMMENT ON COLUMN lbpayer."HeadDateCol" IS 'Col for date';
COMMENT ON COLUMN lbpayer."HeadAcctNoRow" IS 'Row for Bank Account# for bulk payment (Optional), may be store in EPBATACH.AcctId';
COMMENT ON COLUMN lbpayer."HeadAcctNoCol" IS 'Col for Bank Account#';
COMMENT ON COLUMN lbpayer."HasHeader" IS '0=No, 1=Yes';
COMMENT ON COLUMN lbpayer."FieldDelimeter" IS '0=Comma, 1=Tab, 2=Other';
COMMENT ON COLUMN lbpayer."DescriptionCol" IS 'Column description is in (Optional)';
COMMENT ON COLUMN lbpayer."Description" IS 'Lockbox payer description';
COMMENT ON COLUMN lbpayer."DelimeterChar" IS 'If Field Delimeter=2, the character (validated like Provider Imports)';
COMMENT ON COLUMN lbpayer."DefaultFolder" IS 'Default that Load will use to open files form for this payer';
COMMENT ON COLUMN lbpayer."DateFormat" IS '0 = MMDDYYYY, 1 = DDMMYYYY';
COMMENT ON COLUMN lbpayer."DateDelimeterChar" IS 'If Date Delimeter=1, the character';
COMMENT ON COLUMN lbpayer."DateDelimeter" IS '0=No, 1=Yes';
COMMENT ON COLUMN lbpayer."DateCol" IS 'Column that payment date is in (Required column)';
COMMENT ON COLUMN lbpayer."Bank" IS 'Bank that will be used to add payments for (axiUm BANK.Bank)';
COMMENT ON COLUMN lbpayer."AmountFormat" IS '0 = NNNN.NN, 1 = NNNNNN';
COMMENT ON COLUMN lbpayer."AmountCol" IS 'Column that payment amount is in (Required column)';


CREATE  TABLE lcstatus (
  "Code" character(6) NOT NULL,
  "Description" character varying(30),
  "Inactive" numeric(5,0),
  CONSTRAINT lcstatus_primary PRIMARY KEY ("Code")
) ;
COMMENT ON TABLE lcstatus IS 'Lab invoice status codes';
COMMENT ON COLUMN lcstatus."Inactive" IS 'Is the code inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN lcstatus."Description" IS 'Lab invoice status description';
COMMENT ON COLUMN lcstatus."Code" IS 'Lab invoice status code';


CREATE  TABLE letters (
  "LETTERS_AutoDec" numeric(10,0) NOT NULL,
  "LETTERS_Type" numeric(10,0),
  "LETTERS_Description" character(50),
  "LETTERS_Flags" numeric(10,0),
  letters_data bytea,
  CONSTRAINT letters_primaryindex PRIMARY KEY ("LETTERS_AutoDec")
) ;
CREATE INDEX IF NOT EXISTS "LETTERS_Type" ON letters USING btree ("LETTERS_Type") TABLESPACE pg_default;
COMMENT ON TABLE letters IS 'Custom letter reports, created with form designer';
COMMENT ON COLUMN letters.letters_data IS 'Info for the placement of fields and text, including fonts, colors etc...non-readable by SQL. Note: In Oracle 9i this field is Type: BLOB';
COMMENT ON COLUMN letters."LETTERS_Type" IS 'Report type that uses the letter';
COMMENT ON COLUMN letters."LETTERS_Flags" IS 'DEPRECATED';
COMMENT ON COLUMN letters."LETTERS_Description" IS 'Name / description of the letter';
COMMENT ON COLUMN letters."LETTERS_AutoDec" IS 'Primary key';


CREATE  TABLE linkacc (
  "LinkDef" numeric(10,0) NOT NULL,
  "SLevel" numeric(10,0) NOT NULL,
  "Access" numeric(5,0),
  CONSTRAINT linkacc_primary PRIMARY KEY ("LinkDef", "SLevel")
) ;
COMMENT ON TABLE linkacc IS 'Custom Link Access';
COMMENT ON COLUMN linkacc."SLevel" IS 'Primary key component, the security level that access is being defined for. Ptr to SLEVEL.SLevel';
COMMENT ON COLUMN linkacc."LinkDef" IS 'Primary key component, the custom link that access is being defined for. Ptr to LINKDEF.LinkDef';
COMMENT ON COLUMN linkacc."Access" IS 'Level has access? (0=No, 1=Yes)';


CREATE  TABLE linkdef (
  "LinkDef" numeric(10,0) NOT NULL,
  "Name" character varying(50),
  "Execute" character varying(4000),
  "Order" numeric(10,0),
  CONSTRAINT linkdef_primary PRIMARY KEY ("LinkDef")
) ;
COMMENT ON TABLE linkdef IS 'Custom Link Definitions';
COMMENT ON COLUMN linkdef."Order" IS 'Order in the list of custom links.';
COMMENT ON COLUMN linkdef."Name" IS 'Description of the custom link.';
COMMENT ON COLUMN linkdef."LinkDef" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN linkdef."Execute" IS 'URL or UNC path for the custom link.';


CREATE  TABLE listitem (
  "ListCode" character(6) NOT NULL,
  "Description" character varying(50) NOT NULL,
  "Order" numeric(10,0),
  "Type" numeric(5,0) NOT NULL,
  "ASAScore" numeric(5,0),
  "RefCode" character varying(10),
  CONSTRAINT listitem_primary PRIMARY KEY ("ListCode", "Type", "Description")
) ;
COMMENT ON TABLE listitem IS 'Form Answer List Item (List of answers for an answer type)';
COMMENT ON COLUMN listitem."Type" IS 'Primary key component, form type (0 = Dental EPR, 1 = Perio EPR, 2 = Shared EPR, 5=Clinical Note Answer List, 99 = All EPR)';
COMMENT ON COLUMN listitem."RefCode" IS 'Reference code';
COMMENT ON COLUMN listitem."Order" IS 'Order of answer in answer list';
COMMENT ON COLUMN listitem."ListCode" IS 'Primary key component, answer list that this item is in. Ptr to FORMLIST.ListCode';
COMMENT ON COLUMN listitem."Description" IS 'Primary key component, description of answer';
COMMENT ON COLUMN listitem."ASAScore" IS 'Number to represent the ASA score';


CREATE  TABLE llaccess (
  "LLType" numeric(5,0) NOT NULL,
  "Id" numeric(10,0) NOT NULL,
  "SLevel" numeric(10,0) NOT NULL,
  "UserId" numeric(10,0) NOT NULL,
  "Access" numeric(5,0),
  CONSTRAINT llaccess_primary PRIMARY KEY ("LLType", "Id", "SLevel", "UserId")
) ;
COMMENT ON TABLE llaccess IS 'Security restrictions for Regular Letter and Regular Label templates.';
COMMENT ON COLUMN llaccess."UserId" IS 'Primary key component, ptr to USERS.User';
COMMENT ON COLUMN llaccess."SLevel" IS 'Primary key component, ptr to SLEVEL.SLevel';
COMMENT ON COLUMN llaccess."LLType" IS 'Primary key component. Type of template (0=Regular Letter, 1=Regular Label)';
COMMENT ON COLUMN llaccess."Id" IS 'Primary key component, ID of template (LLType=0, ptr to LETTERS.LETTERS_AutoDec; LLType=1, ptr to LABELS_LABELS_AutoDec)';
COMMENT ON COLUMN llaccess."Access" IS 'Access rights (0=No Access, 1=Read Only, 2=Full Access)';


CREATE  TABLE location (
  "Location" character(6) NOT NULL,
  "Description" character(30),
  "ChartsTo" numeric(5,0),
  "DispCode" character(6),
  "AutoLock" numeric(10,0),
  "Inactive" numeric(5,0),
  "Monday" numeric(5,0),
  "Tuesday" numeric(5,0),
  "Wednesday" numeric(5,0),
  "Thursday" numeric(5,0),
  "Friday" numeric(5,0),
  "Saturday" numeric(5,0),
  "Sunday" numeric(5,0),
  CONSTRAINT location_primary PRIMARY KEY ("Location")
) ;
COMMENT ON TABLE location IS 'Chart Locations';
COMMENT ON COLUMN location."Wednesday" IS 'Used for checking restricted time for manual chart request, for Wednesdays';
COMMENT ON COLUMN location."Tuesday" IS 'Used for checking restricted time for manual chart request, for Tuesdays';
COMMENT ON COLUMN location."Thursday" IS 'Used for checking restricted time for manual chart request, for Thursdays';
COMMENT ON COLUMN location."Sunday" IS 'Used for checking restricted time for manual chart request, for Sundays';
COMMENT ON COLUMN location."Saturday" IS 'Used for checking restricted time for manual chart request, for Saturdays';
COMMENT ON COLUMN location."Monday" IS 'Used for checking restricted time for manual chart request, for Mondays';
COMMENT ON COLUMN location."Location" IS 'Primary key, ID code to identify the chart location.';
COMMENT ON COLUMN location."Inactive" IS 'Inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN location."Friday" IS 'Used for checking restricted time for manual chart request, for Fridays';
COMMENT ON COLUMN location."DispCode" IS 'Code to indicate the dispensary used by this location, ptr to DISPCODE.DispCode';
COMMENT ON COLUMN location."Description" IS 'Description of the chart location.';
COMMENT ON COLUMN location."ChartsTo" IS 'Out to? (0=Location, 1=Person)';
COMMENT ON COLUMN location."AutoLock" IS 'ID code to identify the type of automatic chart lock in use for this location, ptr to AUTOLOCK.Id ';


CREATE  TABLE log (
  "LoginHistory" numeric(10,0) NOT NULL,
  "Logon" character(16),
  "Action" numeric(5,0),
  "Date" timestamp without time zone,
  "Time" numeric(10,0),
  "Terminal" character varying(128),
  "AudSID" numeric,
  "User" numeric(10,0),
  "StationId" numeric(10,0),
  "Application" numeric(5,0),
  "IsPINAttempt" numeric(5,0),
  "AuditUser" numeric(10,0),
  "AuditStationId" numeric(10,0),
  "ServerHost" character varying(255),
  "InstanceID" numeric(5,0),
  CONSTRAINT log_primary PRIMARY KEY ("LoginHistory")
) ;
CREATE INDEX IF NOT EXISTS log_terminalaction ON log USING btree ("Terminal", "Action", "LoginHistory") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS log_useraction ON log USING btree ("AuditUser", "Action") TABLESPACE pg_default;
COMMENT ON TABLE log IS 'Login Audit File';
COMMENT ON COLUMN log."User" IS 'Axium User Id';
COMMENT ON COLUMN log."Time" IS 'Time of the login (in minutes from midnight)';
COMMENT ON COLUMN log."Terminal" IS 'Name of the terminal used to login';
COMMENT ON COLUMN log."StationId" IS 'Axium Station Id';
COMMENT ON COLUMN log."ServerHost" IS 'Oracle Server Host Name';
COMMENT ON COLUMN log."Logon" IS 'The user ID used to log in';
COMMENT ON COLUMN log."LoginHistory" IS 'Primary key, internal ID (from sequence) ';
COMMENT ON COLUMN log."IsPINAttempt" IS '0=No (approval attempt), 1=Yes ("PIN" attempt)';
COMMENT ON COLUMN log."InstanceID" IS 'Oracle Instance ID';
COMMENT ON COLUMN log."Date" IS 'Date of the login';
COMMENT ON COLUMN log."AuditUser" IS 'Original user ID (when using Log In As feature)';
COMMENT ON COLUMN log."AuditStationId" IS 'Original station ID (when using Log In As feature)';
COMMENT ON COLUMN log."AudSID" IS 'Oracle audit ID - unique per session';
COMMENT ON COLUMN log."Application" IS 'Used to determine which program did the login( values: 0=axiUm, 1=PowerAdm)';
COMMENT ON COLUMN log."Action" IS 'Log type (0=Failed login, 1=Login, 2=Logout, 3=Cleared Logon Restrictions, 4=Emergency Mode Logon, 5=Emergency Mode Logout, 6=Windows Logoff, 7=Windows Restart)';


CREATE  TABLE loinc (
  "LOINC" character(7) NOT NULL,
  "Class" character varying(20),
  "LastChangedDate" timestamp without time zone,
  "Status" character varying(11),
  "ShortName" character varying(40),
  "LongCommonName" character varying(255),
  CONSTRAINT loinc_primary PRIMARY KEY ("LOINC")
) ;
COMMENT ON COLUMN loinc."Status" IS 'Status of code (eg ACTIVE, DEPRICATED)';
COMMENT ON COLUMN loinc."ShortName" IS 'Short display name';
COMMENT ON COLUMN loinc."LongCommonName" IS 'Long display name';
COMMENT ON COLUMN loinc."LastChangedDate" IS 'Date the code was last changed';
COMMENT ON COLUMN loinc."LOINC" IS 'LOINC Code';
COMMENT ON COLUMN loinc."Class" IS 'LOINC Class (Like a category)';


CREATE  TABLE maintrecent (
  "User" numeric(10,0) NOT NULL,
  "RecentActivityIds" character varying(255),
  CONSTRAINT maintrecent_pk PRIMARY KEY ("User")
) ;
COMMENT ON TABLE maintrecent IS 'Maintenance recent activity dialogs for given user';
COMMENT ON COLUMN maintrecent."User" IS 'User Id of entry user, ptr to USERS.User';
COMMENT ON COLUMN maintrecent."RecentActivityIds" IS 'Recent used Maintenance Dialogs IDs separated by commas';


CREATE  TABLE maptxplan (
  "TableName" character varying(16) NOT NULL,
  "Session" numeric NOT NULL,
  "Old" numeric(10,0) NOT NULL,
  "New" numeric(10,0) NOT NULL,
  CONSTRAINT maptxplan_primary PRIMARY KEY ("TableName", "Session", "Old")
) ;
COMMENT ON TABLE maptxplan IS 'Temporary table used while copying a TXPLAN';
COMMENT ON COLUMN maptxplan."TableName" IS 'Obsolete';
COMMENT ON COLUMN maptxplan."Session" IS 'Obsolete';
COMMENT ON COLUMN maptxplan."Old" IS 'Obsolete';
COMMENT ON COLUMN maptxplan."New" IS 'Obsolete';


CREATE  TABLE matcat (
  "Category" character varying(15) NOT NULL,
  CONSTRAINT matcat_primary PRIMARY KEY ("Category")
) ;
COMMENT ON TABLE matcat IS 'Categories for Material Codes';
COMMENT ON COLUMN matcat."Category" IS 'Primary key, description / name of the category';


CREATE  TABLE material (
  "Material" character(20) NOT NULL,
  "Category" character varying(15),
  "UnitDesc" character(10),
  "MatCostPerUnit" numeric,
  CONSTRAINT material_primary PRIMARY KEY ("Material")
) ;
COMMENT ON TABLE material IS 'Record of the type of material used in treatment';
COMMENT ON COLUMN material."UnitDesc" IS 'Default description of material unit (eg. grams), ptr to MATUNIT.UnitDesc';
COMMENT ON COLUMN material."Material" IS 'Primary key, material used for this treatment (ie: amalgamate, silver, gold plate, porcelain)';
COMMENT ON COLUMN material."MatCostPerUnit" IS 'Default cost per unit for the material (eg. 2.50) ';
COMMENT ON COLUMN material."Category" IS 'ID code of the category the material belongs in, ptr to MATCAT.Category';


CREATE  TABLE matunit (
  "UnitDesc" character(10) NOT NULL,
  CONSTRAINT matunit_primary PRIMARY KEY ("UnitDesc")
) ;
COMMENT ON TABLE matunit IS 'Table of standard units for materials ';
COMMENT ON COLUMN matunit."UnitDesc" IS 'Primary key, standard unit (eg. Grams)';


CREATE  TABLE medalert (
  "MedAlert" numeric(10,0) NOT NULL,
  "AlertType" numeric(5,0),
  "Type" numeric(10,0),
  "Code" character(7),
  "Description" character varying(255),
  "Inactive" numeric(5,0),
  "Note" character varying(4000),
  "Color" numeric(10,0),
  "eRxSyncAudit" numeric(10,0),
  "RcopiaID" character varying(32),
  "SNOCode" character(18),
  CONSTRAINT medalert_primary PRIMARY KEY ("MedAlert")
) ;
CREATE INDEX IF NOT EXISTS medalert_codekey ON medalert USING btree ("AlertType", "Code") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS medalert_rcopiakey ON medalert USING btree ("AlertType", "RcopiaID") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS medalert_snocode ON medalert USING btree ("SNOCode") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS medalert_typekey ON medalert USING btree ("AlertType", "Type", "Code") TABLESPACE pg_default;
COMMENT ON TABLE medalert IS 'Medical Alert Codes : contains axiUm and non-axiUm codes (e.g. Rcopia codes)';
COMMENT ON COLUMN medalert."eRxSyncAudit" IS 'Audit number used to match log entries to a specific Rcopia sync session';
COMMENT ON COLUMN medalert."Type" IS 'Is code deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN medalert."SNOCode" IS 'SNOCode ID, ptr to SNOCODE.SNOCode';
COMMENT ON COLUMN medalert."RcopiaID" IS 'RcopiaID for HiTech code (e.g. Allergy Group or Medical Problem)';
COMMENT ON COLUMN medalert."Note" IS 'Note text attached to this alert';
COMMENT ON COLUMN medalert."MedAlert" IS 'Primary key, internal ID (from sequence), the Id number that identifies this medical alert';
COMMENT ON COLUMN medalert."Inactive" IS 'Code is inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN medalert."Description" IS 'Description of the alert code';
COMMENT ON COLUMN medalert."Color" IS 'Color to display alert in, as decimal representation of binary RGB values';
COMMENT ON COLUMN medalert."Code" IS 'Code to identify the alert';
COMMENT ON COLUMN medalert."AlertType" IS 'Alert type (0 = Clinical Alert, 1 = Allergy, 2 = Medical Problem)';


CREATE  TABLE mergelog (
  "MergeLog" numeric(10,0) NOT NULL,
  "BadPatient" numeric(10,0),
  "GoodPatient" numeric(10,0),
  "DateTime" timestamp without time zone,
  "TableName" character(8),
  recordid clob,
  recordcontent clob,
  "Action" numeric(5,0),
  CONSTRAINT mergelog_primary PRIMARY KEY ("MergeLog")
) ;
COMMENT ON TABLE mergelog IS 'Table for logging chart merges.';
COMMENT ON COLUMN mergelog.recordid IS 'JSON object of “Bad” record key (Eg. Type, Id, Treatment OR Id OR Prescription)';
COMMENT ON COLUMN mergelog.recordcontent IS 'JSON object of Pre-merge record (before updated/deleted)';
COMMENT ON COLUMN mergelog."TableName" IS 'Name of table record merged from (Eg. PTALERT)';
COMMENT ON COLUMN mergelog."MergeLog" IS 'Primary key, Sequenced Id of log record';
COMMENT ON COLUMN mergelog."GoodPatient" IS 'PATIENT.Patient record was merged to';
COMMENT ON COLUMN mergelog."DateTime" IS 'Audit date and time merge happened';
COMMENT ON COLUMN mergelog."BadPatient" IS 'PATIENT.Patient record was merged from';
COMMENT ON COLUMN mergelog."Action" IS '0=Record Updated, 1=Record Deleted, 2= Updated then Deleted';


CREATE  TABLE message (
  "Message" numeric(10,0) NOT NULL,
  "Date" timestamp without time zone,
  "Time" numeric(10,0),
  "Sender" numeric(10,0),
  "Subject" character varying(4000),
  text clob,
  "Deleted" numeric(5,0),
  "Recipients" character varying(4000),
  "IsPriority" numeric(5,0),
  "UMsgFld" numeric(10,0),
  "IsAutoReply" numeric(5,0),
  "CCRecipients" character varying(4000),
  "HashValue" character varying(45),
  "SenderRespiUser" numeric(10,0),
  "SendEMail" numeric(5,0),
  "EMailType" numeric(5,0),
  "EMailStatus" numeric(5,0),
  CONSTRAINT message_primary PRIMARY KEY ("Message")
) ;
CREATE INDEX IF NOT EXISTS message_emailstatuskey ON message USING btree ("EMailStatus") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS message_sender ON message USING btree ("Sender") TABLESPACE pg_default;
COMMENT ON TABLE message IS 'Stores the message contents. There is one record per message.';
COMMENT ON COLUMN message.text IS 'CLOB containing the body of the message. Contents will be encrypted if the recipient list includes a patient or if AXIUMOPT.MsgEncryption=1.';
COMMENT ON COLUMN message."UMsgFld" IS 'Sent Items - type folder where message is stored by the sender. Points to UMSGFLD.UMsgFld (0=default, else points to custom folder)';
COMMENT ON COLUMN message."Time" IS 'Time the message was (or is to be) sent, in minutes from midnight.';
COMMENT ON COLUMN message."Subject" IS 'Text field to enter the subject of the message.';
COMMENT ON COLUMN message."SenderRespiUser" IS 'If sent by Representative, IUSER.iUser of that representative';
COMMENT ON COLUMN message."Sender" IS 'ID of the axiUm user (USERS.User) or PatientAccess patient (IUSER.IUser) that sent the message.';
COMMENT ON COLUMN message."SendEMail" IS 'Should an email be sent? (0=No [Default], 1=Yes (All possible), 2=Yes [If user subscribes]), 3=Yes[Subscribers with Forwarding]';
COMMENT ON COLUMN message."Recipients" IS 'Copy of the recipient list';
COMMENT ON COLUMN message."Message" IS 'Primary key, internal ID (from sequence), the Id number that identifies this message.';
COMMENT ON COLUMN message."IsPriority" IS 'Is a priority message? (0 = No, 1 = Yes)';
COMMENT ON COLUMN message."IsAutoReply" IS '0=No, 1=Yes';
COMMENT ON COLUMN message."HashValue" IS 'SHA hash of MESSAGE.Text, used to detect tampering of message contents.';
COMMENT ON COLUMN message."EMailType" IS 'Type of email to send (0=N/A, 1=Notification, 2=Subject, 3=Full text [and Subject], 4=Full text [No Subject])';
COMMENT ON COLUMN message."EMailStatus" IS 'Email status (0 = N/A, 1 = Waiting, 2 = Processing, 3 = Sent, 4 = Failed, 5 = Not Subscribed [MSGSENT Only], 6 = Invalid email [MSGSENT only], 7 = No recipients [MESSAGE only])';
COMMENT ON COLUMN message."Deleted" IS 'Deleted by sender? (0 = No, 1 = Yes)';
COMMENT ON COLUMN message."Date" IS 'Date the message was ( or is to be ) sent.';
COMMENT ON COLUMN message."CCRecipients" IS 'Copy of the CC recipient list.';


CREATE  TABLE modifier (
  "Code" character(2) NOT NULL,
  "Description" character(30),
  CONSTRAINT modifier_primary PRIMARY KEY ("Code")
) ;
COMMENT ON TABLE modifier IS 'Modifier Codes';
COMMENT ON COLUMN modifier."Description" IS 'Description of the modifier code';
COMMENT ON COLUMN modifier."Code" IS 'ID code to identify the modifier';


CREATE  TABLE mryear (
  "User" numeric(10,0) NOT NULL,
  "Year" numeric(5,0) NOT NULL,
  "DateFrom" timestamp without time zone,
  "DateTo" timestamp without time zone,
  "Status" numeric(5,0),
  "MedicaidVolumeType" numeric(5,0),
  "Submitted" numeric(5,0),
  "PDFName" character varying(100),
  "PDFSummary" bytea,
  "Stage" numeric(5,0),
  CONSTRAINT mryear_primary PRIMARY KEY ("User", "Year")
) ;
COMMENT ON TABLE mryear IS 'Stores provider reporting years';
COMMENT ON COLUMN mryear."Year" IS 'Primary key component, the Meaningful Use reporting year (e.g. 2, 3, 4..)';
COMMENT ON COLUMN mryear."User" IS 'Primary key component, the eligible provider that this reporting year is for. Ptr to USERS.User';
COMMENT ON COLUMN mryear."Submitted" IS 'Has this reporting year been marked as submitted? (0=No, 1=Yes)';
COMMENT ON COLUMN mryear."Status" IS 'The status of the reporting year (0=None, 1=Pass, 2=Fail)';
COMMENT ON COLUMN mryear."Stage" IS 'Stage for the year to distinguish between Modified Stage 2 and Stage 3 (2=Modified Stage 2, 3=Stage 3)';
COMMENT ON COLUMN mryear."PDFSummary" IS 'If the reporting year has been marked as submitted, BLOB contains the PDF data for the stored printable summary. ';
COMMENT ON COLUMN mryear."PDFName" IS 'if the reporting year has been marked as submitted, the filename of the PDF version of the printable summary.';
COMMENT ON COLUMN mryear."MedicaidVolumeType" IS 'The method used to calculate Medicaid patient volume for this reporting year (0=EP, 1=Faculty, 2=Proxy)';
COMMENT ON COLUMN mryear."DateTo" IS 'The end date of the reporting period for this reporting year.';
COMMENT ON COLUMN mryear."DateFrom" IS 'The start date of the reporting period for this reporting year.';


CREATE  TABLE msetting (
  "User" numeric(10,0) NOT NULL,
  "Key" character varying(255) NOT NULL,
  "Value" character varying(4000),
  "Description" character varying(4000),
  "SettingType" numeric(5,0) NOT NULL DEFAULT 1,
  "ShortDescription" character varying(255),
  "DefaultValue" character varying(4000),
  "Rules" character varying(255),
  CONSTRAINT msetting_pk PRIMARY KEY ("User", "Key")
) ;
COMMENT ON TABLE msetting IS 'Stores both global and user-specific settings for Meaningful Use Dashboard.';
COMMENT ON COLUMN msetting."Value" IS 'The value of this setting.';
COMMENT ON COLUMN msetting."User" IS 'Primary key component, the user that this setting is for (0=Global, otherwise ptr to USERS.User).';
COMMENT ON COLUMN msetting."ShortDescription" IS 'The short description of this setting.';
COMMENT ON COLUMN msetting."SettingType" IS 'The type of setting (0 = Text, 1 = Numeric)';
COMMENT ON COLUMN msetting."Rules" IS 'Text description of the rules that should be followed for values for this setting.';
COMMENT ON COLUMN msetting."Key" IS 'Primary key component, the name of the setting.';
COMMENT ON COLUMN msetting."Description" IS 'The long description of this setting.';
COMMENT ON COLUMN msetting."DefaultValue" IS 'The default value of this setting.';


CREATE  TABLE msgevent (
  "MsgEvent" numeric(10,0) NOT NULL,
  "Order" numeric(5,0),
  "Description" character varying(30),
  "TriggerName" character varying(30),
  "Inactive" numeric(5,0),
  "IsPriority" numeric(5,0),
  "SendEMail" numeric(5,0),
  "EMailType" numeric(5,0),
  "UseSLevel" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT msgevent_primary PRIMARY KEY ("MsgEvent")
) ;
COMMENT ON TABLE msgevent IS 'Used to manage / configure auto-message triggers';
COMMENT ON COLUMN msgevent."UseSLevel" IS 'Apply the event to levels found in MSGEVENT_SLEVEL. (0 = No (all levels), 1 = Yes)';
COMMENT ON COLUMN msgevent."TriggerName" IS 'Trigger name';
COMMENT ON COLUMN msgevent."SendEMail" IS 'Should an email be sent? (0=No [Default], 1=Yes (All possible), 2=Yes [If user subscribes]), 3=Yes[Subscribers with Forwarding]';
COMMENT ON COLUMN msgevent."Order" IS 'Order to display in the list';
COMMENT ON COLUMN msgevent."MsgEvent" IS 'Sequenced primary key';
COMMENT ON COLUMN msgevent."IsPriority" IS 'Are messages generated by this trigger a high priority? 0 = No, 1 = Yes.';
COMMENT ON COLUMN msgevent."Inactive" IS 'Inactive flag - Should the trigger still fire? 0 = No, 1 = Yes';
COMMENT ON COLUMN msgevent."EMailType" IS 'Type of email to send (0=N/A, 1=Notification, 2=Subject, 3=Full text [and Subject], 4=Full text [No Subject])';
COMMENT ON COLUMN msgevent."Description" IS 'Description';


CREATE  TABLE msgevent_slevel (
  "MsgEvent" numeric(10,0) NOT NULL DEFAULT 0,
  "SLevel" numeric(10,0) NOT NULL DEFAULT 0,
  CONSTRAINT msgevent_slevel_primary PRIMARY KEY ("MsgEvent", "SLevel")
) ;
COMMENT ON TABLE msgevent_slevel IS 'MSGEVENT_SLEVEL records';
COMMENT ON COLUMN msgevent_slevel."SLevel" IS 'Primary Key. Ptr to SLEVEL.SLevel.';
COMMENT ON COLUMN msgevent_slevel."MsgEvent" IS 'Primary Key. Ptr to MSGEVENT.MsgEvent.';


CREATE  TABLE msgsent (
  "Message" numeric(10,0) NOT NULL,
  "User" numeric(10,0) NOT NULL,
  "UGroup" character(6) NOT NULL,
  "Status" numeric(5,0),
  "UMsgFld" numeric(10,0),
  "RecType" numeric(5,0),
  "EMailStatus" numeric(5,0),
  CONSTRAINT msgsent_primary PRIMARY KEY ("Message", "User", "UGroup")
) ;
CREATE INDEX IF NOT EXISTS msgsent_user ON msgsent USING btree ("User") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS msgsent_userstatusmsgkey ON msgsent USING btree ("User", "Status", "Message") TABLESPACE pg_default;
COMMENT ON TABLE msgsent IS 'Stores the message sent record. There is one record for each recipient of a message.';
COMMENT ON COLUMN msgsent."User" IS 'ID of the axiUm user (USERS.User) or PatientAccess patient (IUSER.IUser) who is a recipient of this message.';
COMMENT ON COLUMN msgsent."UMsgFld" IS 'Inbox-type folder where message is stored by the recipient. Points to UMSGFLD.UMsgFld (0=default, else points to custom folder)';
COMMENT ON COLUMN msgsent."UGroup" IS 'ID of the Group this message was sent to, ptr to UGROUP.UGroup, defaults to none if message was sent to an individual or list of individuals rather than a group';
COMMENT ON COLUMN msgsent."Status" IS 'Status of the message (0=New, 1=Read, 2=Deleted)';
COMMENT ON COLUMN msgsent."RecType" IS 'Type of recipient for this sent message (0 = To, 1 = CC, 2 = BCC)';
COMMENT ON COLUMN msgsent."Message" IS 'MessageId, ptr to MESSAGE.Message, the Id of the message';
COMMENT ON COLUMN msgsent."EMailStatus" IS 'Email status (0 = N/A, 1 = Waiting, 2 = Processing, 3 = Sent, 4 = Failed, 5 = Not Subscribed [MSGSENT Only], 6 = Invalid email [MSGSENT only], 7 = No recipients [MESSAGE only]), 8 = Waiting (Patient)';


CREATE  TABLE mtestlab (
  "MTestLab" numeric(10,0) NOT NULL,
  "Name" character varying(255),
  "Address1" character varying(30),
  "Address2" character varying(30),
  "City" character varying(24),
  "Province" character varying(6),
  "Postal" character varying(15),
  "Country" character varying(30),
  "AddressOther" character varying(30),
  CONSTRAINT mtestlab_primary PRIMARY KEY ("MTestLab")
) ;
COMMENT ON TABLE mtestlab IS 'Medical Test Laboratory (Maps to HL7 OBX.23 and OBX.24 fields)';
COMMENT ON COLUMN mtestlab."Province" IS 'State/Province';
COMMENT ON COLUMN mtestlab."Postal" IS 'Zip/Postal Code';
COMMENT ON COLUMN mtestlab."Name" IS 'Name of medical lab';
COMMENT ON COLUMN mtestlab."MTestLab" IS 'Primary key, internal ID (from sequence), the Id number that identifies this laboratory';
COMMENT ON COLUMN mtestlab."Country" IS 'Country';
COMMENT ON COLUMN mtestlab."City" IS 'City';
COMMENT ON COLUMN mtestlab."AddressOther" IS 'County';
COMMENT ON COLUMN mtestlab."Address2" IS 'Address line 2';
COMMENT ON COLUMN mtestlab."Address1" IS 'Address line 1 ';


CREATE  TABLE mtestord (
  "MTestOrd" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "OrderNumber" character varying(255),
  "OrderProviderNPI" character varying(10),
  "OrderProviderLast" character varying(30),
  "OrderProviderFirst" character varying(30),
  "Audit" numeric(10,0),
  "Deleted" numeric(5,0),
  "DeletedAudit" numeric(10,0) NOT NULL DEFAULT 0,
  CONSTRAINT mtestord_primary PRIMARY KEY ("MTestOrd")
) ;
CREATE INDEX IF NOT EXISTS mtestord_ordernumberkey ON mtestord USING btree ("OrderNumber") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS mtestord_patientkey ON mtestord USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE mtestord IS 'Medical Test Order (Maps to HL7 ORC segment)';
COMMENT ON COLUMN mtestord."Patient" IS 'Patient that the order is for, ptr to PATIENT.Patient';
COMMENT ON COLUMN mtestord."OrderProviderNPI" IS 'Ordering provider’s Id (from external system)';
COMMENT ON COLUMN mtestord."OrderProviderLast" IS 'Ordering provider’s last name (from external system)';
COMMENT ON COLUMN mtestord."OrderProviderFirst" IS 'Ordering provider’s first name (from external system)';
COMMENT ON COLUMN mtestord."OrderNumber" IS 'Internal ID (from sequence), the Id number that identifies this order';
COMMENT ON COLUMN mtestord."MTestOrd" IS 'Primary key, internal ID (from sequence), the Id number that identifies this test order';
COMMENT ON COLUMN mtestord."DeletedAudit" IS 'Deleted audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN mtestord."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN mtestord."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE mtestreq (
  "MTestReq" numeric(10,0) NOT NULL,
  "MTestOrd" numeric(10,0),
  "RequestNumber" numeric(5,0),
  "LOINC" character(7),
  "RequestDateTime" timestamp without time zone,
  "Status" character varying(15),
  "RelevantClinicalInfo" character varying(255),
  "Note" character varying(4000),
  "Audit" numeric(10,0),
  "Deleted" numeric(5,0),
  "DeletedAudit" numeric(10,0) NOT NULL DEFAULT 0,
  CONSTRAINT mtestreq_primary PRIMARY KEY ("MTestReq")
) ;
CREATE INDEX IF NOT EXISTS mtestreq_mtestordkey ON mtestreq USING btree ("MTestOrd") TABLESPACE pg_default;
COMMENT ON TABLE mtestreq IS 'Medical Test Requested Procedure (Maps to HL7 OBR segment)';
COMMENT ON COLUMN mtestreq."Status" IS 'Result status for this request';
COMMENT ON COLUMN mtestreq."RequestNumber" IS 'Request number for the order (1, 2, …)';
COMMENT ON COLUMN mtestreq."RequestDateTime" IS 'Date/time of request';
COMMENT ON COLUMN mtestreq."RelevantClinicalInfo" IS 'Additional info included in request ';
COMMENT ON COLUMN mtestreq."Note" IS 'Any notes about the request (from HL7 NTE segment)';
COMMENT ON COLUMN mtestreq."MTestReq" IS 'Primary key, internal ID (from sequence), the Id number that identifies this request procedure';
COMMENT ON COLUMN mtestreq."MTestOrd" IS 'Order this request is on, ptr to MTESTORD.MTestOrd';
COMMENT ON COLUMN mtestreq."LOINC" IS 'LOINC code for medical test requested ';
COMMENT ON COLUMN mtestreq."DeletedAudit" IS 'Deleted audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN mtestreq."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN mtestreq."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE mtestres (
  "MTestRes" numeric(10,0) NOT NULL,
  "MTestReq" numeric(10,0),
  "ResultNumber" numeric(5,0),
  "LOINC" character(7),
  "MTestLab" numeric(10,0),
  "ObservationDateTime" timestamp without time zone,
  "AnalysisDateTime" timestamp without time zone,
  "ResultValue" character varying(255),
  "ResultUnits" character varying(255),
  "ReferenceRange" character varying(60),
  "Abnormal" character varying(15),
  "Status" character varying(15),
  "Note" character varying(4000),
  "Audit" numeric(10,0),
  "Deleted" numeric(5,0),
  "DeletedAudit" numeric(10,0) NOT NULL DEFAULT 0,
  CONSTRAINT mtestres_primary PRIMARY KEY ("MTestRes")
) ;
CREATE INDEX IF NOT EXISTS mtestres_mtestreqkey ON mtestres USING btree ("MTestReq") TABLESPACE pg_default;
COMMENT ON TABLE mtestres IS 'Medical Test Results (Maps to HL7 OBX segment)';
COMMENT ON COLUMN mtestres."Status" IS 'Status for this result';
COMMENT ON COLUMN mtestres."ResultValue" IS 'Value of test result';
COMMENT ON COLUMN mtestres."ResultUnits" IS 'Units of test result';
COMMENT ON COLUMN mtestres."ResultNumber" IS 'Result number for the request (1, 2, …)';
COMMENT ON COLUMN mtestres."ReferenceRange" IS 'Information about the expected normal range of result';
COMMENT ON COLUMN mtestres."ObservationDateTime" IS 'Date/time of observation (result)';
COMMENT ON COLUMN mtestres."Note" IS 'Any notes about the result (from HL7 NTE segment)';
COMMENT ON COLUMN mtestres."MTestRes" IS 'Primary key, internal ID (from sequence), the Id number that identifies this test result';
COMMENT ON COLUMN mtestres."MTestReq" IS 'Rrequested procedure this result is for, ptr to MTESTREQ.MTestReq';
COMMENT ON COLUMN mtestres."MTestLab" IS 'Laboratory that performed the test, ptr to MTESTLAB.MTestLab';
COMMENT ON COLUMN mtestres."LOINC" IS 'LOINC code for medical test performed ';
COMMENT ON COLUMN mtestres."DeletedAudit" IS 'Deleted audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN mtestres."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN mtestres."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN mtestres."AnalysisDateTime" IS 'Date/time of analysis';
COMMENT ON COLUMN mtestres."Abnormal" IS 'Code to indicate if the result is considered abnormal';


CREATE  TABLE mtestspm (
  "MTestSpm" numeric(10,0) NOT NULL,
  "MTestReq" numeric(10,0),
  "SpecimenNumber" numeric(5,0),
  "CollectionDateTime" timestamp without time zone,
  "SpecimenType" character varying(15),
  "Condition" character varying(255),
  "RejectReason" character varying(255),
  "Audit" numeric(10,0),
  "Deleted" numeric(5,0),
  CONSTRAINT mtestspm_primary PRIMARY KEY ("MTestSpm")
) ;
CREATE INDEX IF NOT EXISTS mtestspm_mtestordkey ON mtestspm USING btree ("MTestReq") TABLESPACE pg_default;
COMMENT ON TABLE mtestspm IS 'Medical Test Specimen Info (Maps to HL7 SPM segment)';
COMMENT ON COLUMN mtestspm."SpecimenType" IS 'Specimen type';
COMMENT ON COLUMN mtestspm."SpecimenNumber" IS 'Specimen number for the request (1, 2, …)';
COMMENT ON COLUMN mtestspm."RejectReason" IS 'Reason specimen was rejected (if applicable)';
COMMENT ON COLUMN mtestspm."MTestSpm" IS 'Primary key, internal ID (from sequence), the Id number that identifies this test specimen info';
COMMENT ON COLUMN mtestspm."MTestReq" IS 'Requested procedure this specimen is for, ptr to MTESTREQ.MTestReq';
COMMENT ON COLUMN mtestspm."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN mtestspm."Condition" IS 'Specimen condition when it was received';
COMMENT ON COLUMN mtestspm."CollectionDateTime" IS 'Date/time the specimen was collected';
COMMENT ON COLUMN mtestspm."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE needcode (
  "NeedCode" character(6) NOT NULL,
  "Description" character(30),
  "Inactive" numeric(5,0),
  CONSTRAINT needcode_primary PRIMARY KEY ("NeedCode")
) ;
COMMENT ON TABLE needcode IS 'Need Codes';
COMMENT ON COLUMN needcode."NeedCode" IS 'Primary key, ID code to identify the need code.';
COMMENT ON COLUMN needcode."Inactive" IS 'Is this need code inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN needcode."Description" IS 'Description of the need code.';


CREATE  TABLE needlink (
  "NeedLink" numeric(10,0) NOT NULL,
  "NeedCode" character(6),
  "From" character(7),
  "To" character(7),
  "MinCount" numeric(5,0),
  CONSTRAINT needlink_primary PRIMARY KEY ("NeedLink")
) ;
COMMENT ON TABLE needlink IS 'Links between patient needs and procedure codes';
COMMENT ON COLUMN needlink."To" IS 'Last procedure code covered by this need link. If Type=1, ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN needlink."NeedLink" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN needlink."NeedCode" IS 'ID code to identify the need, ptr to NEEDCODE.NeedCode';
COMMENT ON COLUMN needlink."MinCount" IS 'Minimum count (if applicable), defaults to 0';
COMMENT ON COLUMN needlink."From" IS 'First procedure code covered by this need link. If Type=1, ptr to PROCEDUR.Procedure';


CREATE  TABLE needreq (
  "NeedReq" numeric(10,0) NOT NULL,
  "Provider" character(10),
  "Date" timestamp without time zone,
  "Time" numeric(10,0),
  "Type" numeric(5,0),
  "NeedCode" character(6),
  "Procedure" character(7),
  "PatType" character(6),
  "Note" character(100),
  "Assigned" numeric(5,0),
  "AssignedDate" timestamp without time zone,
  "PtProdId" numeric(10,0),
  "Deleted" numeric(5,0),
  "AuditId" numeric(10,0),
  CONSTRAINT needreq_primary PRIMARY KEY ("NeedReq")
) ;
CREATE INDEX IF NOT EXISTS needreq_provider ON needreq USING btree ("Provider") TABLESPACE pg_default;
COMMENT ON TABLE needreq IS 'Need Requests';
COMMENT ON COLUMN needreq."Type" IS 'Type of request (0=Needcode, 1=DEPRECATED, 2=TxDiscipline, 3=TxProcedure)';
COMMENT ON COLUMN needreq."Time" IS 'Time of the request';
COMMENT ON COLUMN needreq."PtProdId" IS 'ID code to identify the PTPROD record when a provider is assigned to cover this need, ptr to PTPROD.Id';
COMMENT ON COLUMN needreq."Provider" IS 'Provider ID, ptr to PRODUCER.Producer';
COMMENT ON COLUMN needreq."Procedure" IS 'If Type=3, the procedure code. Ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN needreq."PatType" IS 'Patient type requested [optional]. Ptr to PATTYPE.PatType ';
COMMENT ON COLUMN needreq."Note" IS 'Free text area to enter a note for the request';
COMMENT ON COLUMN needreq."NeedReq" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN needreq."NeedCode" IS 'If Type=0, the need code. Ptr to NEEDCODE.NeedCode.';
COMMENT ON COLUMN needreq."Deleted" IS 'Item is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN needreq."Date" IS 'Date of the request';
COMMENT ON COLUMN needreq."AuditId" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN needreq."AssignedDate" IS 'Date of the assignment (if assigned)';
COMMENT ON COLUMN needreq."Assigned" IS 'Patient has been assigned to student for this request? (0 = Not assigned, 1=Assigned)';


CREATE  TABLE needreqh (
  "NeedReqH" numeric(10,0) NOT NULL,
  "NeedReq" numeric(10,0),
  "Provider" character(10),
  "Date" timestamp without time zone,
  "Time" numeric(10,0),
  "Type" numeric(5,0),
  "NeedCode" character(6),
  "Procedure" character(7),
  "PatType" character(6),
  "Note" character varying(100),
  "Assigned" numeric(5,0),
  "AssignedDate" timestamp without time zone,
  "PtProdId" numeric(10,0),
  "Deleted" numeric(5,0),
  "AuditId" numeric(10,0),
  CONSTRAINT needreqh_primary PRIMARY KEY ("NeedReqH")
) ;
CREATE INDEX IF NOT EXISTS needreqh_needreq ON needreqh USING btree ("NeedReq") TABLESPACE pg_default;
COMMENT ON TABLE needreqh IS 'Need Request History';
COMMENT ON COLUMN needreqh."Type" IS 'Type of request (0=Needcode, 1=DEPRECATED, 2=TxDiscipline, 3=TxProcedure)';
COMMENT ON COLUMN needreqh."Time" IS 'Time of the request';
COMMENT ON COLUMN needreqh."PtProdId" IS 'ID code to identify the PTPROD record when a provider is assigned to cover this need, ptr to PTPROD.Id';
COMMENT ON COLUMN needreqh."Provider" IS 'Provider ID, ptr to PRODUCER.Producer';
COMMENT ON COLUMN needreqh."Procedure" IS 'If Type=3, the procedure code. Ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN needreqh."PatType" IS 'Patient type requested [optional]. Ptr to PATTYPE.PatType ';
COMMENT ON COLUMN needreqh."Note" IS 'Free text area to enter a note for the request';
COMMENT ON COLUMN needreqh."NeedReqH" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN needreqh."NeedReq" IS 'Need request that this history is for, ptr to NEEDREQ.NeedReq';
COMMENT ON COLUMN needreqh."NeedCode" IS 'If Type=0, the need code. Ptr to NEEDCODE.NeedCode.';
COMMENT ON COLUMN needreqh."Deleted" IS 'Item is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN needreqh."Date" IS 'Date of the request';
COMMENT ON COLUMN needreqh."AuditId" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN needreqh."AssignedDate" IS 'Date of the assignment (if assigned)';
COMMENT ON COLUMN needreqh."Assigned" IS 'Patient has been assigned to student for this request? (0 = Not assigned, 1=Assigned)';


CREATE  TABLE needsts (
  "Code" character(6) NOT NULL,
  "Description" character varying(30),
  "IsDefault" numeric(5,0),
  "Show" numeric(5,0),
  "Resolved" numeric(5,0),
  "Inactive" numeric(5,0),
  CONSTRAINT needsts_primary PRIMARY KEY ("Code")
) ;
COMMENT ON TABLE needsts IS 'Need Status Codes';
COMMENT ON COLUMN needsts."Show" IS 'Show in EHR? (0 = No, 1 = Yes)';
COMMENT ON COLUMN needsts."Resolved" IS 'This need code indicates that the need is resolved? (0 = No, 1 = Yes)';
COMMENT ON COLUMN needsts."IsDefault" IS 'Is this the default need status code? (0 = No, 1 = Yes)';
COMMENT ON COLUMN needsts."Inactive" IS 'Inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN needsts."Description" IS 'Description of the need status.';
COMMENT ON COLUMN needsts."Code" IS 'Primary key, ID code to identify the need status. ';


CREATE  TABLE network (
  "Network" character(6) NOT NULL,
  "Description" character varying(30),
  "TransmitSW" numeric(5,0),
  "Prefix" character varying(12),
  "SoftwareId" character(3),
  "OfficeId" character(4),
  "Area" character(4),
  "Telephone" character(8),
  CONSTRAINT network_primary PRIMARY KEY ("Network")
) ;
COMMENT ON TABLE network IS 'Network codes for CDANet (Canada only)';
COMMENT ON COLUMN network."TransmitSW" IS 'Transmit software (0= iTrans, 1 = CDA CCD)';
COMMENT ON COLUMN network."Telephone" IS 'Default phone number';
COMMENT ON COLUMN network."SoftwareId" IS 'Vendor software ID#, field A06';
COMMENT ON COLUMN network."Prefix" IS 'Network record prefix, field A01';
COMMENT ON COLUMN network."OfficeId" IS 'Office ID#, field B02';
COMMENT ON COLUMN network."Network" IS 'Network code';
COMMENT ON COLUMN network."Description" IS 'Network code description';
COMMENT ON COLUMN network."Area" IS 'Default phone number area code';


CREATE  TABLE notecode (
  "NoteCode" character(6) NOT NULL,
  "Text" character varying(4000),
  "Type" numeric(5,0) NOT NULL,
  CONSTRAINT notecode_primary PRIMARY KEY ("NoteCode", "Type")
) ;
COMMENT ON TABLE notecode IS 'Codes to identify the type of note';
COMMENT ON COLUMN notecode."Type" IS 'Type of note code (0= Patient, 1 = Statement, 2= Receipt, 3 = Contact, 4=Provider Scheduling Note)';
COMMENT ON COLUMN notecode."Text" IS 'Text of the note code';
COMMENT ON COLUMN notecode."NoteCode" IS 'Primary key, ID code to identify the note code';


CREATE  TABLE noteovr (
  "Id" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "Type" numeric(5,0),
  "ParentId" numeric(10,0),
  "Order" numeric(5,0),
  "Text" character varying(4000),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT noteovr_primary PRIMARY KEY ("Id")
) ;
CREATE INDEX IF NOT EXISTS noteovr_typeparentkey ON noteovr USING btree ("Type", "ParentId", "Order", "Deleted") TABLESPACE pg_default;
COMMENT ON TABLE noteovr IS 'Clinical Patient Note Overflow Records (for long notes)';
COMMENT ON COLUMN noteovr."Type" IS 'Type of note that this overflow record is for (0=General/SOAP note, 1= EPR Form/Template Note Long Text, 2= Lab Note)';
COMMENT ON COLUMN noteovr."Text" IS 'Text contained in this note chunk.';
COMMENT ON COLUMN noteovr."Patient" IS 'ID code of the patient, ptr to PATIENT.Patient';
COMMENT ON COLUMN noteovr."ParentId" IS 'ID code of the parent note. For General/SOAP/Tx Notes/Lab Notes, ptr to NOTES2.Auto. For EPR Long Text questions, ptr to PITEM.Pitem';
COMMENT ON COLUMN noteovr."Order" IS 'Number to identify the order of this note chunk in the overall note.';
COMMENT ON COLUMN noteovr."Id" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN noteovr."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN noteovr."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE notes2 (
  "Auto" numeric(10,0) NOT NULL,
  "PId" numeric(10,0),
  "ModifiedDateTime" timestamp without time zone,
  "TxId" numeric(10,0),
  "Site" numeric(5,0),
  "Text" character varying(4000),
  "User" numeric(10,0),
  "Status" numeric(5,0),
  "Phase" character(2),
  "Seq" numeric(5,0),
  "Custom1" character(6),
  "Custom2" character(6),
  "AppUser" numeric(10,0),
  "AppDate" timestamp without time zone,
  "Code" character(7),
  "Type" numeric(5,0),
  "OtherId" numeric(10,0),
  "Module" numeric(5,0),
  "SectionNo" numeric(10,0),
  "Date" timestamp without time zone,
  "DeletionDate" timestamp without time zone,
  "OrigId" numeric(10,0),
  "AddDateTime" timestamp without time zone,
  "IsTemplate" numeric(5,0),
  rtftext clob,
  "DeletionUser" numeric(10,0) NOT NULL DEFAULT 0,
  CONSTRAINT notes2_primary PRIMARY KEY ("Auto")
) ;
CREATE INDEX IF NOT EXISTS notes2_appuserkey ON notes2 USING btree ("AppUser", "User") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS notes2_origid ON notes2 USING btree ("OrigId") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS notes2_otherid ON notes2 USING btree ("Type", "OtherId", "SectionNo") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS "NOTES2_PId" ON notes2 USING btree ("PId", "Date") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS "NOTES2_Site" ON notes2 USING btree ("PId", "Site", "ModifiedDateTime") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS "NOTES2_TxId" ON notes2 USING btree ("TxId") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS notes2_user ON notes2 USING btree ("User", "AppDate") TABLESPACE pg_default;
COMMENT ON TABLE notes2 IS 'Clinical Patient Notes';
COMMENT ON COLUMN notes2.rtftext IS 'Free RTF text area for the body of the note.';
COMMENT ON COLUMN notes2."User" IS 'User ID of entry user. Ptr to USERS.User';
COMMENT ON COLUMN notes2."Type" IS 'Type of note (0 = General note, 1 = Tx note, 2 = Lab note, 3 = Ortho, 4 = SOAP, 5 = Rx Note, 6 = Surgery Note)';
COMMENT ON COLUMN notes2."TxId" IS 'If note is tied to a treatment, then the treatment that it is attached to. Ptr to TREATME2.Auto';
COMMENT ON COLUMN notes2."Text" IS 'Free text area for the body of the note.';
COMMENT ON COLUMN notes2."Status" IS 'Deactivated? (0 = No, 1 = Yes, 2 = Strikeout)';
COMMENT ON COLUMN notes2."Site" IS 'If non-tx note, then site (tooth) that note refers to.';
COMMENT ON COLUMN notes2."Seq" IS 'Sequence number for this note. ';
COMMENT ON COLUMN notes2."SectionNo" IS 'If Type=4, section of the note that this record is for (0=Subjective, 1=Objective, 2=Assessment, 3=Planned)';
COMMENT ON COLUMN notes2."Phase" IS 'Phase order for this note.';
COMMENT ON COLUMN notes2."PId" IS 'Patient chart, ptr to PATIENT2.Auto';
COMMENT ON COLUMN notes2."OtherId" IS 'If Type = 1 or 3, not used (see TxId field for record ID). If Type = 2, then ptr to LABORDER.LabOrder. If Type = 4, then an internal ID from the NOTES2_CLINICALNOTE_SEQ sequence. If Type = 5 then ptr to PRESCRIP.Prescription. If Type = 6 then ptr to PTLETTER.PtLetter.';
COMMENT ON COLUMN notes2."OrigId" IS 'Original copy of the note, ptr to NOTES2.Auto';
COMMENT ON COLUMN notes2."Module" IS 'Module this note applies to (0=Dental, 1=Ortho, 2=Perio)';
COMMENT ON COLUMN notes2."ModifiedDateTime" IS 'Date/time of most recent modification. ';
COMMENT ON COLUMN notes2."IsTemplate" IS 'Is this template note? (0=No, 1=Yes)';
COMMENT ON COLUMN notes2."DeletionUser" IS 'User ID of deletion user. Ptr to USERS.User.';
COMMENT ON COLUMN notes2."DeletionDate" IS 'Date the note was deleted.';
COMMENT ON COLUMN notes2."Date" IS 'Date the note was entered for.';
COMMENT ON COLUMN notes2."Custom2" IS 'Treatment/Note2 custom field, ptr to CUSTCODE.Code';
COMMENT ON COLUMN notes2."Custom1" IS 'Treatment/Note1 custom field, ptr to CUSTCODE.Code';
COMMENT ON COLUMN notes2."Code" IS 'Comment code, ptr to COMMENT2.Code';
COMMENT ON COLUMN notes2."Auto" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN notes2."AppUser" IS 'Approving user, ptr to USERS.User';
COMMENT ON COLUMN notes2."AppDate" IS 'Date of the approval';
COMMENT ON COLUMN notes2."AddDateTime" IS 'Date/time when the record was added. Must be initialized if converting, otherwise current date/time will be set the next time treatment or note is changed.';


CREATE  TABLE notes2cd (
  "Auto" numeric(10,0) NOT NULL,
  "Code" character(7) NOT NULL,
  "Item" numeric(5,0) NOT NULL,
  CONSTRAINT notes2cd_primary PRIMARY KEY ("Auto", "Item")
) ;
COMMENT ON TABLE notes2cd IS 'Note Codes added to Clinical Patient Notes';
COMMENT ON COLUMN notes2cd."Item" IS 'Item # for this note code in the list of codes added to this clinical patient note. ';
COMMENT ON COLUMN notes2cd."Code" IS 'Primary key component, the note code that was added to this note. Ptr to COMMENT2.Code';
COMMENT ON COLUMN notes2cd."Auto" IS 'Primary key component, the note that the note code was added to. Ptr to NOTES2.Auto';


CREATE  TABLE npattach (
  "NPAttach" numeric(10,0) NOT NULL,
  "Type" numeric(5,0),
  "Id" numeric(10,0),
  "Description" character varying(80),
  content bytea,
  "FileExt" character(3),
  "Deleted" numeric(5,0),
  "CreateAudit" numeric(10,0),
  "DeleteAudit" numeric(10,0),
  CONSTRAINT npattach_primary PRIMARY KEY ("NPAttach")
) ;
CREATE INDEX IF NOT EXISTS "NPATTACH_Type_Id" ON npattach USING btree ("Type", "Id") TABLESPACE pg_default;
COMMENT ON TABLE npattach IS 'Non-Patient Attachments';
COMMENT ON COLUMN npattach.content IS 'The scanned attachment';
COMMENT ON COLUMN npattach."Type" IS '0=Future, 1=Ins Pmt, 2=Lab Cost';
COMMENT ON COLUMN npattach."NPAttach" IS 'Sequenced primary key';
COMMENT ON COLUMN npattach."Id" IS 'If Type=1, TRX.Id (of ins cheque)';
COMMENT ON COLUMN npattach."FileExt" IS 'If Type=1, the file extension';
COMMENT ON COLUMN npattach."Description" IS 'Description (optional)';
COMMENT ON COLUMN npattach."Deleted" IS '0=No, 1=Yes';
COMMENT ON COLUMN npattach."DeleteAudit" IS 'Audit info. when attachment was deleted (ptr to AUDITHIS.Audit)';
COMMENT ON COLUMN npattach."CreateAudit" IS 'Audit info. when attachment was created (ptr to AUDITHIS.Audit)';


CREATE  TABLE objlist (
  "ObjList" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0) NOT NULL,
  "Complaint" numeric(10,0),
  "Description" character varying(4000),
  "Status" character(6),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT objlist_primary PRIMARY KEY ("ObjList")
) ;
CREATE INDEX IF NOT EXISTS objlist_patientkey ON objlist USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE objlist IS 'Patient Objectives';
COMMENT ON COLUMN objlist."Status" IS 'Status of the objective, ptr to OBJSTS.Code  ';
COMMENT ON COLUMN objlist."Patient" IS 'Patient ID, ptr to PATIENT.Patient';
COMMENT ON COLUMN objlist."ObjList" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN objlist."Description" IS 'Description of the objective ';
COMMENT ON COLUMN objlist."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN objlist."Complaint" IS 'If attached to a treatment plan, then ptr to COMPLAIN.Auto. (0 otherwise)';
COMMENT ON COLUMN objlist."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE objlisth (
  "ObjListH" numeric(10,0) NOT NULL,
  "ObjList" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0) NOT NULL,
  "Complaint" numeric(10,0),
  "Description" character varying(4000),
  "Status" character(6),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT objlisth_primary PRIMARY KEY ("ObjListH")
) ;
CREATE INDEX IF NOT EXISTS objlisth_objlistkey ON objlisth USING btree ("ObjList") TABLESPACE pg_default;
COMMENT ON TABLE objlisth IS 'Patient Objective History';
COMMENT ON COLUMN objlisth."Status" IS 'Status of the objective, ptr to OBJSTS.Code  ';
COMMENT ON COLUMN objlisth."Patient" IS 'Patient ID, ptr to PATIENT.Patient';
COMMENT ON COLUMN objlisth."ObjListH" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN objlisth."ObjList" IS 'Objective that this history is for, ptr to OBJLIST.ObjList';
COMMENT ON COLUMN objlisth."Description" IS 'Description of the objective ';
COMMENT ON COLUMN objlisth."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN objlisth."Complaint" IS 'If attached to a treatment plan, then ptr to COMPLAIN.Auto. (0 otherwise)';
COMMENT ON COLUMN objlisth."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE objsts (
  "Code" character(6) NOT NULL,
  "Description" character varying(30),
  "Show" numeric(5,0),
  "Resolved" numeric(5,0),
  "Inactive" numeric(5,0),
  "Default" numeric(5,0),
  CONSTRAINT objsts_primary PRIMARY KEY ("Code")
) ;
COMMENT ON TABLE objsts IS 'Objective Status Codes';
COMMENT ON COLUMN objsts."Show" IS 'Show objectve in the EHR Objectives tab? (0 = No, 1 = Yes)';
COMMENT ON COLUMN objsts."Resolved" IS 'Status indicates the objective has been resolved? (0 = No, 1 = Yes)';
COMMENT ON COLUMN objsts."Inactive" IS 'Record is inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN objsts."Description" IS 'Description of the objective status.';
COMMENT ON COLUMN objsts."Default" IS 'Is this the default status for new objectives? (0 = No, 1 = Yes)';
COMMENT ON COLUMN objsts."Code" IS 'Primary key, ID code to identify this objective status. ';


CREATE  TABLE obligate (
  "CompLevel" character(6) NOT NULL,
  "Template" character(6) NOT NULL,
  "MinNumber" numeric(5,0),
  "Option" numeric(5,0) NOT NULL,
  CONSTRAINT obligate_primary PRIMARY KEY ("CompLevel", "Option", "Template")
) ;
COMMENT ON TABLE obligate IS 'Competency Level Exam Obligations';
COMMENT ON COLUMN obligate."Template" IS 'Primary Key, Grading Template/Card code, ptr to TEMPLATE.Template';
COMMENT ON COLUMN obligate."Option" IS 'Is an option? (0 = No, 1 = Yes)';
COMMENT ON COLUMN obligate."MinNumber" IS 'Minimum number of exams that student must pass to achieve level';
COMMENT ON COLUMN obligate."CompLevel" IS 'Primary Key, Competency Level Code';


CREATE  TABLE oblitem (
  "CompLevel" character(6) NOT NULL,
  "PriorLevel" character(6) NOT NULL,
  "Option" numeric(5,0) NOT NULL,
  CONSTRAINT oblitem_primary PRIMARY KEY ("CompLevel", "Option", "PriorLevel")
) ;
COMMENT ON TABLE oblitem IS 'Competency Level Obligations of Previous levels';
COMMENT ON COLUMN oblitem."PriorLevel" IS 'Prior competency level that must have been achieved';
COMMENT ON COLUMN oblitem."Option" IS 'Competency Level Option number';
COMMENT ON COLUMN oblitem."CompLevel" IS 'Primary Key, Competency Level Code';


CREATE  TABLE oblopt (
  "CompLevel" character(6) NOT NULL,
  "Option" numeric(5,0) NOT NULL,
  "Description" character(50),
  CONSTRAINT oblopt_primary PRIMARY KEY ("CompLevel", "Option")
) ;
COMMENT ON TABLE oblopt IS 'Competency Level Obligation Options (options for passing level)';
COMMENT ON COLUMN oblopt."Option" IS 'Option number, 1, 2, 3, ...';
COMMENT ON COLUMN oblopt."Description" IS 'Description of the option';
COMMENT ON COLUMN oblopt."CompLevel" IS 'Competency Level, ptr to CLEVEL.Clevel';


CREATE  TABLE occupate (
  "Occupation" character(30) NOT NULL,
  CONSTRAINT occupate_primary PRIMARY KEY ("Occupation")
) ;
COMMENT ON TABLE occupate IS 'A list of possible occupations to choose from when entering patient demographic information, used in the patient card module';
COMMENT ON COLUMN occupate."Occupation" IS 'Occupation of the patient';


CREATE  TABLE odextrsn (
  "Reason" character varying(30) NOT NULL,
  CONSTRAINT odextrsn_primary PRIMARY KEY ("Reason")
) ;
COMMENT ON TABLE odextrsn IS 'Overdue Extension reasons';
COMMENT ON COLUMN odextrsn."Reason" IS 'overdue extension reason                      ';


CREATE  TABLE odlimits (
  "Overdue" character(6) NOT NULL,
  "Limit" numeric(10,0),
  "Frequency" numeric(10,0),
  "Date" timestamp without time zone,
  CONSTRAINT odlimits_primary PRIMARY KEY ("Overdue")
) ;
COMMENT ON TABLE odlimits IS 'Stores calculated limits during the overnight process to speed processing';
COMMENT ON COLUMN odlimits."Overdue" IS 'Id code to identify the overdue reason, ptr to OVERDUE.Overdue';
COMMENT ON COLUMN odlimits."Limit" IS 'Limit, in days';
COMMENT ON COLUMN odlimits."Frequency" IS 'How often to resend the message';
COMMENT ON COLUMN odlimits."Date" IS 'Date generated';


CREATE  TABLE odmsgrcp (
  "OdMsgRcp" numeric(10,0) NOT NULL,
  "OdueMsg" character(6),
  "User" numeric(10,0),
  "UGroup" character(6),
  CONSTRAINT odmsgrcp_primary PRIMARY KEY ("OdMsgRcp")
) ;
COMMENT ON TABLE odmsgrcp IS 'List of other recipients to send a message to, used when ODUEMSG.OtherRecipients =1';
COMMENT ON COLUMN odmsgrcp."User" IS 'Id code of the user to which the message was sent, ptr to USERS.User';
COMMENT ON COLUMN odmsgrcp."UGroup" IS 'Id code to identify the UGroup to which the message was sent, ptr to UGROUP.UGroup';
COMMENT ON COLUMN odmsgrcp."OdueMsg" IS 'Id code of the overdue message, ptr to ODUEMSG.OdueMsg';
COMMENT ON COLUMN odmsgrcp."OdMsgRcp" IS 'Id code to identify this overdue message recipient record';


CREATE  TABLE odmsgsnt (
  "OdMsgSnt" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "Producer" character(10),
  "Overdue" character(6),
  "User" numeric(10,0),
  "Type" numeric(5,0),
  "Date" timestamp without time zone,
  CONSTRAINT odmsgsnt_primary PRIMARY KEY ("OdMsgSnt")
) ;
COMMENT ON TABLE odmsgsnt IS 'Record of overdue messages that have been sent';
COMMENT ON COLUMN odmsgsnt."User" IS 'Id code of the user that generated the overdue message, ptr to USERS.User';
COMMENT ON COLUMN odmsgsnt."Type" IS 'The relationship that resulted in the message being sent (provider, providers group leader, patients care manager, other), and is determined by the 4 yes/no questions in the ODUEMSG table';
COMMENT ON COLUMN odmsgsnt."Producer" IS 'Id code of the provider that is overdue, ptr to PRODUCER.Producer';
COMMENT ON COLUMN odmsgsnt."Patient" IS 'Id code of the patient that is overdue, ptr to PATIENT.Patient';
COMMENT ON COLUMN odmsgsnt."Overdue" IS 'ID code of the overdue condition';
COMMENT ON COLUMN odmsgsnt."OdMsgSnt" IS 'Id code of the message sent record';
COMMENT ON COLUMN odmsgsnt."Date" IS 'Date the overdue message was sent';


CREATE  TABLE oduemsg (
  "OdueMsg" character(6) NOT NULL,
  "Producer" numeric(5,0),
  "GroupLeader" numeric(5,0),
  "PatientManager" numeric(5,0),
  "OtherRecipients" numeric(5,0),
  CONSTRAINT oduemsg_primary PRIMARY KEY ("OdueMsg")
) ;
COMMENT ON TABLE oduemsg IS 'Table to define what message to send and who to send it to  when an overdue condition occurs ';
COMMENT ON COLUMN oduemsg."Producer" IS 'Message goes to provider? (0 = No, 1 = Yes)';
COMMENT ON COLUMN oduemsg."PatientManager" IS 'Message goes to patient manager? (0 = No, 1 = Yes)';
COMMENT ON COLUMN oduemsg."OtherRecipients" IS 'Message goes to other recipients? (0 = No, 1 = Yes)';
COMMENT ON COLUMN oduemsg."OdueMsg" IS 'Id Code to identify this overdue message record';
COMMENT ON COLUMN oduemsg."GroupLeader" IS 'Message goes to group leader? (0 = No, 1 = Yes)';


CREATE  TABLE ofcharge (
  "OfficeCharge" character(6) NOT NULL,
  "Description" character(30),
  "PrintDescription" character(30),
  "Amount" numeric,
  "Inactive" numeric(5,0),
  "IsPrepay" numeric(5,0),
  "Taxable" numeric(5,0),
  CONSTRAINT ofcharge_primary PRIMARY KEY ("OfficeCharge")
) ;
COMMENT ON TABLE ofcharge IS 'Office Charge Codes';
COMMENT ON COLUMN ofcharge."Taxable" IS 'Is charge taxable? (0=No, 1=Yes)';
COMMENT ON COLUMN ofcharge."PrintDescription" IS 'Description of the office charge to print on receipt.';
COMMENT ON COLUMN ofcharge."OfficeCharge" IS 'Primary key, code that identifies the office charge.';
COMMENT ON COLUMN ofcharge."IsPrepay" IS 'This is for a pre-payment (held funds)? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ofcharge."Inactive" IS 'Code is inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN ofcharge."Description" IS 'Description of the office charge.';
COMMENT ON COLUMN ofcharge."Amount" IS 'Amount to charge for this item/service, in dollars.';


CREATE  TABLE office (
  "Office" character(6) NOT NULL,
  "Description" character(30),
  "Inactive" numeric(5,0),
  "Color" numeric(10,0),
  CONSTRAINT office_primary PRIMARY KEY ("Office")
) ;
COMMENT ON TABLE office IS 'Patient Office Codes';
COMMENT ON COLUMN office."Office" IS 'Primary key, code to identify the office code';
COMMENT ON COLUMN office."Inactive" IS 'Code is inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN office."Description" IS 'Description of the office code';
COMMENT ON COLUMN office."Color" IS 'Color to display office code in, as decimal representation of binary RGB values';


CREATE  TABLE online_comment (
  "Id" numeric(10,0) NOT NULL DEFAULT 0,
  "RequestId" numeric(10,0) NOT NULL DEFAULT 0,
  "Date" timestamp without time zone,
  "Comment" character varying(4000),
  "Deleted" numeric(5,0) NOT NULL DEFAULT 0,
  "Audit" numeric(10,0) NOT NULL DEFAULT 0,
  "IsContactNote" numeric(5,0) NOT NULL DEFAULT 0,
  "Time" numeric(10,0) NOT NULL DEFAULT 0,
  "EntryUser" numeric(10,0) NOT NULL DEFAULT 0,
  CONSTRAINT online_comment_primary PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE online_comment IS 'Comment table for the Online Request';
COMMENT ON COLUMN online_comment."Time" IS 'Time the comment was entered';
COMMENT ON COLUMN online_comment."RequestId" IS 'Pointer to ONLINE_REQUEST.Id';
COMMENT ON COLUMN online_comment."IsContactNote" IS 'Yes/No flag to indicate if it is a contact note or not';
COMMENT ON COLUMN online_comment."Id" IS 'Primary key, sequence field';
COMMENT ON COLUMN online_comment."EntryUser" IS 'User that entered the comment';
COMMENT ON COLUMN online_comment."Deleted" IS 'Deleted: 0 - no, 1 - yes';
COMMENT ON COLUMN online_comment."Date" IS 'Date of the comment';
COMMENT ON COLUMN online_comment."Comment" IS 'Comment';
COMMENT ON COLUMN online_comment."Audit" IS 'Pointer to AUDITHIS.Audit; track who/when/where the record is touched';


CREATE  TABLE online_commenthis (
  "Id" numeric(10,0) NOT NULL DEFAULT 0,
  "CommentId" numeric(10,0) NOT NULL DEFAULT 0,
  "RequestId" numeric(10,0) NOT NULL DEFAULT 0,
  "Date" timestamp without time zone,
  "Comment" character varying(4000),
  "Deleted" numeric(5,0) NOT NULL DEFAULT 0,
  "Audit" numeric(10,0) NOT NULL DEFAULT 0,
  "IsContactNote" numeric(5,0) NOT NULL DEFAULT 0,
  "Time" numeric(10,0) NOT NULL DEFAULT 0,
  "EntryUser" numeric(10,0) NOT NULL DEFAULT 0,
  CONSTRAINT online_commenthis_primary PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE online_commenthis IS 'History table on Comment for the Online Request';
COMMENT ON COLUMN online_commenthis."Time" IS 'Time the comment was entered';
COMMENT ON COLUMN online_commenthis."RequestId" IS 'Pointer to ONLINE_REQUEST.Id';
COMMENT ON COLUMN online_commenthis."IsContactNote" IS 'Yes/No flag to indicate if it is a contact note or not';
COMMENT ON COLUMN online_commenthis."Id" IS 'Primary key, sequence field';
COMMENT ON COLUMN online_commenthis."EntryUser" IS 'User that entered the comment';
COMMENT ON COLUMN online_commenthis."Deleted" IS 'Deleted: 0 - no, 1 - yes';
COMMENT ON COLUMN online_commenthis."Date" IS 'Date of the comment';
COMMENT ON COLUMN online_commenthis."CommentId" IS 'Pointer to ONLINE_COMMENT.Id';
COMMENT ON COLUMN online_commenthis."Comment" IS 'Comment';
COMMENT ON COLUMN online_commenthis."Audit" IS 'Pointer to AUDITHIS.Audit; track who/when/where the record is touched';


CREATE  TABLE online_customizedquestion (
  "Id" numeric(10,0) NOT NULL DEFAULT 0,
  "Question" character varying(255) NOT NULL,
  "Type" numeric(5,0) NOT NULL DEFAULT 0,
  "Required" numeric(5,0) NOT NULL DEFAULT 0,
  "Section" numeric(5,0) NOT NULL DEFAULT 0,
  "Order" numeric(5,0) NOT NULL DEFAULT 0,
  "QuestionType" numeric(5,0) NOT NULL DEFAULT 0,
  "ControlId" numeric(10,0) NOT NULL DEFAULT 0,
  "GroupName" character varying(20),
  "CanSpecifyOther" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT online_customizedquestion_primary PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE online_customizedquestion IS 'Online request customized question.';
COMMENT ON COLUMN online_customizedquestion."Type" IS '-1-N/A, 0-multi select, 1-single select, 2-text, 3-date picker, 4-email, 5-phone, 6-checkbox, 7-long text, 8-yes/no buttons';
COMMENT ON COLUMN online_customizedquestion."Section" IS '0-patient, 1-request (For future use.)';
COMMENT ON COLUMN online_customizedquestion."Required" IS '0-not required(optional), 1-required(mandatory), 2-hidden';
COMMENT ON COLUMN online_customizedquestion."QuestionType" IS 'Question type: 0 - Custom, 1 - Patient Profile';
COMMENT ON COLUMN online_customizedquestion."Question" IS 'Customized question';
COMMENT ON COLUMN online_customizedquestion."Order" IS 'Order of question';
COMMENT ON COLUMN online_customizedquestion."Id" IS 'Primary key, sequence field';
COMMENT ON COLUMN online_customizedquestion."GroupName" IS 'Group name (if applicable)';
COMMENT ON COLUMN online_customizedquestion."ControlId" IS 'Id to ONLINE_PATCONTROLDEFN table';
COMMENT ON COLUMN online_customizedquestion."CanSpecifyOther" IS 'Flag to specify if Other values can be input by end user: 0 - No, 1 - Yes';


CREATE  TABLE online_customizedquestion_answer (
  "Id" numeric(10,0) NOT NULL DEFAULT 0,
  "OnlineCustomizedQuestionId" numeric(10,0) NOT NULL DEFAULT 0,
  "Answer" character varying(255) NOT NULL,
  "Order" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT online_customizedquestion_answer_primary PRIMARY KEY ("Id"),
  CONSTRAINT online_customizedquestion_answer_questionid_fk FOREIGN KEY ("OnlineCustomizedQuestionId") REFERENCES online_customizedquestion("Id")
) ;
CREATE INDEX IF NOT EXISTS online_customizedquestion_answer_questionidkey ON online_customizedquestion_answer USING btree ("OnlineCustomizedQuestionId") TABLESPACE pg_default;
COMMENT ON TABLE online_customizedquestion_answer IS 'Online request customized question answer.';
COMMENT ON COLUMN online_customizedquestion_answer."Order" IS 'Order of answer in answer list';
COMMENT ON COLUMN online_customizedquestion_answer."OnlineCustomizedQuestionId" IS 'Primary key component, id from ONLINE_CUSTOMIZEDQUESTION.';
COMMENT ON COLUMN online_customizedquestion_answer."Id" IS 'Primary key, sequence field';
COMMENT ON COLUMN online_customizedquestion_answer."Answer" IS 'Description of answer.';


CREATE  TABLE online_patcontroldefn (
  "Id" numeric(10,0) NOT NULL DEFAULT 0,
  "Description" character varying(255),
  "GroupName" character varying(20),
  "Status" numeric(5,0) NOT NULL DEFAULT 0,
  "ParentGroup" character varying(20),
  "Prompt" character varying(255),
  "Type" numeric(5,0) NOT NULL DEFAULT 0,
  "TableId" numeric(5,0) NOT NULL DEFAULT 0,
  "FieldId" numeric(5,0) NOT NULL DEFAULT 0,
  "Order" numeric(5,0) NOT NULL DEFAULT 0,
  "FieldLen" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT online_patcontroldefn_primary PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE online_patcontroldefn IS 'New Patient Control definition table';
COMMENT ON COLUMN online_patcontroldefn."Type" IS 'Field type: -1-N/A, 0-multi select, 1-single select, 2-text, 3-date picker, 4-email, 5-phone, 6-checkbox, 7-long text, 8-yes/no buttons';
COMMENT ON COLUMN online_patcontroldefn."TableId" IS 'Predefned table id';
COMMENT ON COLUMN online_patcontroldefn."Status" IS 'Usage flag: 0 - optional, 1 - mandatory';
COMMENT ON COLUMN online_patcontroldefn."Prompt" IS 'Field prompt if GroupName is blank; else optional group caption';
COMMENT ON COLUMN online_patcontroldefn."ParentGroup" IS 'Group name of the parent grouping';
COMMENT ON COLUMN online_patcontroldefn."Order" IS 'Default Ordering for the record';
COMMENT ON COLUMN online_patcontroldefn."Id" IS 'Primary key, sequence field';
COMMENT ON COLUMN online_patcontroldefn."GroupName" IS 'Group name';
COMMENT ON COLUMN online_patcontroldefn."FieldLen" IS 'Field length of the given field (only applicable to text/long text fields)';
COMMENT ON COLUMN online_patcontroldefn."FieldId" IS 'Predefned field id';
COMMENT ON COLUMN online_patcontroldefn."Description" IS 'Description';


CREATE  TABLE online_patient (
  "Id" numeric(10,0) NOT NULL DEFAULT 0,
  "LastName" character varying(25),
  "FirstName" character varying(30),
  "Birth" timestamp without time zone,
  "Sex" numeric(5,0) NOT NULL DEFAULT 0,
  "ContactPhone" character varying(20),
  "ContactType" numeric(5,0) NOT NULL DEFAULT 0,
  "Email" character varying(100),
  "InsPlanType" character varying(100),
  "InsCompany" character varying(100),
  "InsGroupNo" character varying(100),
  "InsSubscriberNo" character varying(100),
  "Patient" numeric(10,0) NOT NULL DEFAULT 0,
  CONSTRAINT online_patient_primary PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE online_patient IS 'Obsolete - DO NOT USE';
COMMENT ON COLUMN online_patient."Sex" IS 'Obsolete - DO NOT USE';
COMMENT ON COLUMN online_patient."Patient" IS 'Obsolete - DO NOT USE';
COMMENT ON COLUMN online_patient."LastName" IS 'Obsolete - DO NOT USE';
COMMENT ON COLUMN online_patient."InsSubscriberNo" IS 'Obsolete - DO NOT USE';
COMMENT ON COLUMN online_patient."InsPlanType" IS 'Obsolete - DO NOT USE';
COMMENT ON COLUMN online_patient."InsGroupNo" IS 'Obsolete - DO NOT USE';
COMMENT ON COLUMN online_patient."InsCompany" IS 'Obsolete - DO NOT USE';
COMMENT ON COLUMN online_patient."Id" IS 'Obsolete - DO NOT USE';
COMMENT ON COLUMN online_patient."FirstName" IS 'Obsolete - DO NOT USE';
COMMENT ON COLUMN online_patient."Email" IS 'Obsolete - DO NOT USE';
COMMENT ON COLUMN online_patient."ContactType" IS 'Obsolete - DO NOT USE';
COMMENT ON COLUMN online_patient."ContactPhone" IS 'Obsolete - DO NOT USE';
COMMENT ON COLUMN online_patient."Birth" IS 'Obsolete - DO NOT USE';


CREATE  TABLE online_reqapptjt (
  "RequestId" numeric(10,0) NOT NULL DEFAULT 0,
  "Appointment" numeric(10,0) NOT NULL DEFAULT 0,
  CONSTRAINT online_reqapptjt_primary PRIMARY KEY ("RequestId", "Appointment")
) ;
COMMENT ON TABLE online_reqapptjt IS 'Joint table that links an appointment and the request';
COMMENT ON COLUMN online_reqapptjt."RequestId" IS 'Primary key, pointer to ONLINE_REQUEST.Id';
COMMENT ON COLUMN online_reqapptjt."Appointment" IS 'Primary key, pointer to APPOINT.Appointment';


CREATE  TABLE online_reqevent (
  "Id" numeric(10,0) NOT NULL DEFAULT 0,
  "RequestId" numeric(10,0) NOT NULL DEFAULT 0,
  "Event" numeric(10,0) NOT NULL DEFAULT 0,
  "Details" character varying(255),
  "Audit" numeric(10,0) NOT NULL DEFAULT 0,
  CONSTRAINT online_reqevent_primary PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE online_reqevent IS 'Event table for the Online Request';
COMMENT ON COLUMN online_reqevent."RequestId" IS 'Pointer to ONLINE_REQUEST.Id';
COMMENT ON COLUMN online_reqevent."Id" IS 'Primary key, sequence field';
COMMENT ON COLUMN online_reqevent."Event" IS 'Event Type: 0 - N/A, 1 - add, 2 - status updated, 3 - assignment updated, 4 - added as new patient, 5 - linked to existing patient, 6 - add appointment, 7 - send email acknowledgement';
COMMENT ON COLUMN online_reqevent."Details" IS 'Event Info captured pertaining to the event type';
COMMENT ON COLUMN online_reqevent."Audit" IS 'Pointer to AUDITHIS.Audit; track who/when/where the record is created';


CREATE  TABLE online_reqreason (
  "Id" numeric(10,0) NOT NULL DEFAULT 0,
  "Reason" character varying(255),
  "AssignedUser" numeric(10,0) NOT NULL DEFAULT 0,
  "AssignedUGroup" character(6),
  CONSTRAINT online_reqreason_primary PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE online_reqreason IS 'Reason table for the Online Request';
COMMENT ON COLUMN online_reqreason."Reason" IS 'Reason for treatment';
COMMENT ON COLUMN online_reqreason."Id" IS 'Primary key, sequence field';
COMMENT ON COLUMN online_reqreason."AssignedUser" IS 'If assigned to a user, points to a USER record';
COMMENT ON COLUMN online_reqreason."AssignedUGroup" IS 'If assigned to a user group, points to a UGROUP record';


CREATE  TABLE online_request (
  "Id" numeric(10,0) NOT NULL DEFAULT 0,
  "CreateDateTime" timestamp without time zone,
  "Type" numeric(5,0) NOT NULL DEFAULT 0,
  "Status" character(6),
  "PatientReqId" numeric(10,0) NOT NULL DEFAULT 0,
  "RequestDateTime" timestamp without time zone,
  "Reason" character varying(255),
  "Note" character varying(4000),
  "PreferMonday" numeric(5,0) NOT NULL DEFAULT 0,
  "PreferTuesday" numeric(5,0) NOT NULL DEFAULT 0,
  "PreferWednesday" numeric(5,0) NOT NULL DEFAULT 0,
  "PreferThursday" numeric(5,0) NOT NULL DEFAULT 0,
  "PreferFriday" numeric(5,0) NOT NULL DEFAULT 0,
  "PreferSaturday" numeric(5,0) NOT NULL DEFAULT 0,
  "PreferSunday" numeric(5,0) NOT NULL DEFAULT 0,
  "AssignedUser" numeric(10,0) NOT NULL DEFAULT 0,
  "AssignedUGroup" character(6),
  "Patient" numeric(10,0) NOT NULL DEFAULT 0,
  CONSTRAINT online_request_primary PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE online_request IS 'Details of the online request';
COMMENT ON COLUMN online_request."Type" IS 'The type of the request (0 - appt request)';
COMMENT ON COLUMN online_request."Status" IS 'The Status of the Online Request; map to STATUS table';
COMMENT ON COLUMN online_request."RequestDateTime" IS 'Date and time the request was made from external source ';
COMMENT ON COLUMN online_request."Reason" IS 'Short reason for the request (e.g. checkup, cleaning, toothache, etc.)';
COMMENT ON COLUMN online_request."PreferWednesday" IS 'Preferred wednesday: 0 - no, 1 - morning only, 2 - afternoon only, 3 - all day';
COMMENT ON COLUMN online_request."PreferTuesday" IS 'Preferred tuesday: 0 - no, 1 - morning only, 2 - afternoon only, 3 - all day';
COMMENT ON COLUMN online_request."PreferThursday" IS 'Preferred thursday: 0 - no, 1 - morning only, 2 - afternoon only, 3 - all day';
COMMENT ON COLUMN online_request."PreferSunday" IS 'Preferred sunday: 0 - no, 1 - morning only, 2 - afternoon only, 3 - all day';
COMMENT ON COLUMN online_request."PreferSaturday" IS 'Preferred saturday: 0 - no, 1 - morning only, 2 - afternoon only, 3 - all day';
COMMENT ON COLUMN online_request."PreferMonday" IS 'Preferred monday: 0 - no, 1 - morning only, 2 - afternoon only, 3 - all day';
COMMENT ON COLUMN online_request."PreferFriday" IS 'Preferred friday: 0 - no, 1 - morning only, 2 - afternoon only, 3 - all day';
COMMENT ON COLUMN online_request."PatientReqId" IS 'Obsolete - DO NOT USE';
COMMENT ON COLUMN online_request."Patient" IS 'Points to the corresponding PATIENT record created or referenced';
COMMENT ON COLUMN online_request."Note" IS 'Additional notes about the request';
COMMENT ON COLUMN online_request."Id" IS 'Primary key, sequence field';
COMMENT ON COLUMN online_request."CreateDateTime" IS 'date and time the request was received and created';
COMMENT ON COLUMN online_request."AssignedUser" IS 'If assigned to a user, points to a USER record';
COMMENT ON COLUMN online_request."AssignedUGroup" IS 'If assigned to a user group, points to a UGROUP record';


CREATE  TABLE online_request_answer (
  "Id" numeric(10,0) NOT NULL DEFAULT 0,
  "OnlineRequestQuestionId" numeric(10,0) NOT NULL DEFAULT 0,
  "Answer" character varying(255),
  "Order" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT online_request_answer_primary PRIMARY KEY ("Id")
) ;
CREATE INDEX IF NOT EXISTS online_request_answer_questionidkey ON online_request_answer USING btree ("OnlineRequestQuestionId") TABLESPACE pg_default;
COMMENT ON TABLE online_request_answer IS 'Answer to a Online Request Customized Question';
COMMENT ON COLUMN online_request_answer."Order" IS 'Order of answer';
COMMENT ON COLUMN online_request_answer."OnlineRequestQuestionId" IS 'Primary key component, id from ONLINE_REQUEST_QUESTION.';
COMMENT ON COLUMN online_request_answer."Id" IS 'Primary key, sequence field';
COMMENT ON COLUMN online_request_answer."Answer" IS 'Answer to a customized question.';


CREATE  TABLE online_request_question (
  "Id" numeric(10,0) NOT NULL DEFAULT 0,
  "RequestId" numeric(10,0) NOT NULL DEFAULT 0,
  "Question" character varying(255),
  "Order" numeric(5,0) NOT NULL DEFAULT 0,
  "ControlId" numeric(10,0) NOT NULL DEFAULT 0,
  CONSTRAINT online_request_question_primary PRIMARY KEY ("Id")
) ;
CREATE INDEX IF NOT EXISTS online_request_question_requestidkey ON online_request_question USING btree ("RequestId") TABLESPACE pg_default;
COMMENT ON TABLE online_request_question IS 'Online Request Question';
COMMENT ON COLUMN online_request_question."RequestId" IS 'Primary key component, id from ONLINE_REQUEST.';
COMMENT ON COLUMN online_request_question."Question" IS 'Question';
COMMENT ON COLUMN online_request_question."Order" IS 'Order of question';
COMMENT ON COLUMN online_request_question."Id" IS 'Primary key, sequence field';
COMMENT ON COLUMN online_request_question."ControlId" IS 'Id to ONLINE_PATCONTROLDEFN table';


CREATE  TABLE orthoset (
  "Code" character(6) NOT NULL,
  "Description" character(30),
  CONSTRAINT orthoset_primary PRIMARY KEY ("Code")
) ;
COMMENT ON TABLE orthoset IS 'Ortho Set Codes';
COMMENT ON COLUMN orthoset."Description" IS 'Description of the ortho set ';
COMMENT ON COLUMN orthoset."Code" IS 'Primary key, ID code to identify the ortho set. ';


CREATE  TABLE osstage (
  "Set" numeric(10,0) NOT NULL,
  "Code" character(1) NOT NULL,
  "ShortDesc" character varying(8),
  "Description" character varying(30),
  "BkgColor" numeric(10,0),
  "Inactive" numeric(5,0),
  CONSTRAINT osstage_primary PRIMARY KEY ("Set", "Code")
) ;
COMMENT ON TABLE osstage IS 'Surgery stage codes.';
COMMENT ON COLUMN osstage."ShortDesc" IS 'Short description of the Surgery stage.';
COMMENT ON COLUMN osstage."Set" IS 'Primary key component, internal ID from sequence.';
COMMENT ON COLUMN osstage."Inactive" IS 'Is this stage inactive? (0 = No, 1 = Yes).';
COMMENT ON COLUMN osstage."Description" IS 'Longer description of the Surgery stage.';
COMMENT ON COLUMN osstage."Code" IS 'Primary key component, single character code for the stage.';
COMMENT ON COLUMN osstage."BkgColor" IS 'Background color to display for this stage, numeric representation of RGB value.';


CREATE  TABLE ostemacc (
  "OSTempl" numeric(10,0) NOT NULL,
  "SLevel" numeric(10,0) NOT NULL,
  "Access" numeric(5,0),
  CONSTRAINT ostemacc_pk PRIMARY KEY ("OSTempl", "SLevel")
) ;
COMMENT ON TABLE ostemacc IS 'Surgery Document Template Access';
COMMENT ON COLUMN ostemacc."SLevel" IS 'Primary key component, ptr to SLEVEL.SLevel';
COMMENT ON COLUMN ostemacc."OSTempl" IS 'Primary key component, ptr to OSTEMPL.OSTempl';
COMMENT ON COLUMN ostemacc."Access" IS 'Access to the template for this security level (0=Read Only, 1=Full Access)';


CREATE  TABLE ostempl (
  "OSTempl" numeric(10,0) NOT NULL,
  "Description" character varying(60),
  "FilePath" character varying(255),
  "IsHeading" numeric(5,0),
  "Inactive" numeric(5,0),
  "Order" numeric(5,0),
  template bytea,
  "Note" numeric(5,0),
  "AtTab" numeric(10,0),
  "CreateFlag" numeric(5,0),
  CONSTRAINT ostempl_primary PRIMARY KEY ("OSTempl")
) ;
COMMENT ON TABLE ostempl IS 'Surgery Document Templates';
COMMENT ON COLUMN ostempl.template IS 'Word Document content';
COMMENT ON COLUMN ostempl."Order" IS 'Display Order in the dialog';
COMMENT ON COLUMN ostempl."OSTempl" IS 'Primary key, unique code to identify Surgery Doc Templates.';
COMMENT ON COLUMN ostempl."Note" IS 'Note should be created after generating document (0=No, 1=Yes).';
COMMENT ON COLUMN ostempl."IsHeading" IS 'Is a heading line? (0 = No, 1 = Yes).';
COMMENT ON COLUMN ostempl."Inactive" IS 'Doc Template is inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ostempl."FilePath" IS 'Original path of the template file (including name and extension).';
COMMENT ON COLUMN ostempl."Description" IS 'Description of the template.';
COMMENT ON COLUMN ostempl."CreateFlag" IS '0=Furture use';
COMMENT ON COLUMN ostempl."AtTab" IS 'Id of attachment manager tab to store this document. Ptr to ATTAB.AtTab.';


CREATE  TABLE osvbound (
  "VitalBounds" numeric(10,0) NOT NULL,
  "VitalType" numeric(5,0),
  "MinValue" numeric(5,0),
  "MaxValue" numeric(5,0),
  "VarianceValue" numeric(5,0),
  "PedMinValue" numeric(5,0),
  "PedMaxValue" numeric(5,0),
  "PedVarianceValue" numeric(5,0),
  CONSTRAINT osvbound_primary PRIMARY KEY ("VitalBounds")
) ;
COMMENT ON TABLE osvbound IS 'Vital Bounds For Surgery Appointments';
COMMENT ON COLUMN osvbound."VitalType" IS 'Vital Type (1=HeartRate;2=Temperature;3=RespRate;6=SpO2;7=ECO2)';
COMMENT ON COLUMN osvbound."VitalBounds" IS 'Primary key , unique code to identify the Vital Bounds';
COMMENT ON COLUMN osvbound."VarianceValue" IS 'Adult variance value';
COMMENT ON COLUMN osvbound."PedVarianceValue" IS 'Pediatric variance value';
COMMENT ON COLUMN osvbound."PedMinValue" IS 'Pediatric min value';
COMMENT ON COLUMN osvbound."PedMaxValue" IS 'Pediatric max value';
COMMENT ON COLUMN osvbound."MinValue" IS 'Adult min value';
COMMENT ON COLUMN osvbound."MaxValue" IS 'Adult max value';


CREATE  TABLE osvitmon (
  "VitMon" character(6) NOT NULL,
  "Description" character varying(30),
  "IsMobile" numeric(5,0),
  "Interface" numeric(5,0),
  "SupportHeartRate" numeric(5,0),
  "SupportTemperature" numeric(5,0),
  "SupportRespRate" numeric(5,0),
  "SupportBloodPressure" numeric(5,0),
  "SupportSpO2" numeric(5,0),
  "SupportECO2" numeric(5,0),
  "SupportEKG" numeric(5,0),
  "SupportPanic" numeric(5,0),
  "Inactive" numeric(5,0),
  CONSTRAINT osvitmon_primary PRIMARY KEY ("VitMon")
) ;
COMMENT ON TABLE osvitmon IS 'Vital Monitors for Surgery.';
COMMENT ON COLUMN osvitmon."VitMon" IS 'Primary key, unique code to identify the Vital Monitor';
COMMENT ON COLUMN osvitmon."SupportTemperature" IS 'flag 0/1 if supported';
COMMENT ON COLUMN osvitmon."SupportSpO2" IS 'flag 0/1 if supported';
COMMENT ON COLUMN osvitmon."SupportRespRate" IS 'flag 0/1 if supported';
COMMENT ON COLUMN osvitmon."SupportPanic" IS 'flag 0/1 if supported';
COMMENT ON COLUMN osvitmon."SupportHeartRate" IS 'flag 0/1 if supported';
COMMENT ON COLUMN osvitmon."SupportEKG" IS 'flag 0/1 if supported';
COMMENT ON COLUMN osvitmon."SupportECO2" IS 'flag 0/1 if supported';
COMMENT ON COLUMN osvitmon."SupportBloodPressure" IS 'flag 0/1 if supported';
COMMENT ON COLUMN osvitmon."IsMobile" IS '0=No (stationary), 1=Yes';
COMMENT ON COLUMN osvitmon."Interface" IS 'interface to use e.g. 0 = Mortara, 1 = Mindray, etc.';
COMMENT ON COLUMN osvitmon."Inactive" IS 'flag 0/1 if active (in service or out of service)';
COMMENT ON COLUMN osvitmon."Description" IS 'name/description of the monitor e.g. OS Mortara Mon#1';


CREATE  TABLE overdue (
  "Overdue" character(6) NOT NULL,
  "Description" character(50),
  "FunctionName" character(50),
  "Limit" numeric(10,0),
  "Period" numeric(5,0),
  "Active" numeric(5,0),
  "PerProducer" numeric(5,0),
  "AffectPatAssign" numeric(5,0),
  "MsgOnLimit" character(6),
  "MsgOnExtension" character(6),
  "MsgFrequency" numeric(10,0),
  "MsgPeriod" numeric(5,0),
  CONSTRAINT overdue_primary PRIMARY KEY ("Overdue")
) ;
COMMENT ON TABLE overdue IS 'Overdue functions';
COMMENT ON COLUMN overdue."Period" IS 'Period? (0=Calendar days, 1=Clinical days, 2=Calendar Months)';
COMMENT ON COLUMN overdue."PerProducer" IS 'Condition is checked per assigned provider? (0 = No, 1 = Yes)';
COMMENT ON COLUMN overdue."Overdue" IS 'Id code to identify this overdue record';
COMMENT ON COLUMN overdue."MsgPeriod" IS 'Message period (0=Calendar days, 1=Clinical days, 2=Calendar months)';
COMMENT ON COLUMN overdue."MsgOnLimit" IS 'Id code of the message to send when limit is reached ';
COMMENT ON COLUMN overdue."MsgOnExtension" IS 'Id code of the message to send when an extension is granted ';
COMMENT ON COLUMN overdue."MsgFrequency" IS 'How often to send the message';
COMMENT ON COLUMN overdue."Limit" IS 'Number (1-9999) to indicate the # of periods before flag is set';
COMMENT ON COLUMN overdue."FunctionName" IS 'Name of the Oracle function';
COMMENT ON COLUMN overdue."Description" IS 'Description of the overdue function / the reason for this overdue flag';
COMMENT ON COLUMN overdue."AffectPatAssign" IS 'Affects future patient assignment to the provider? (0 = No, 1 = Yes)';
COMMENT ON COLUMN overdue."Active" IS 'Overdue condition is active (on)? (0 = No, 1 = Yes)';


CREATE  TABLE paccda (
  "PaccdaId" numeric(5,0) NOT NULL,
  "Patient" numeric(10,0),
  "Date" timestamp without time zone,
  "User" numeric(10,0),
  "ActionType" numeric(5,0),
  CONSTRAINT paccda_pk PRIMARY KEY ("PaccdaId")
) ;
COMMENT ON TABLE paccda IS 'CCDA auditing table for Patient Access';
COMMENT ON COLUMN paccda."User" IS 'User that this audit is for, ptr to USERS.User';
COMMENT ON COLUMN paccda."Patient" IS 'Patient that this audit is for, ptr to PATIENT.Patient';
COMMENT ON COLUMN paccda."PaccdaId" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN paccda."Date" IS 'Audit date';
COMMENT ON COLUMN paccda."ActionType" IS 'Type of action (0=Viewed, 1=Downloaded, 2=Transmitted)';


CREATE  TABLE pafiles (
  "PAFILESID" numeric NOT NULL,
  fileblob bytea,
  "FILEMIME" character varying(50),
  "CREATEDATE" timestamp(6) without time zone,
  "FILENAME" character varying(200),
  "DIMENSION" character varying(50),
  CONSTRAINT pafiles_primary PRIMARY KEY ("PAFILESID")
) ;
COMMENT ON TABLE pafiles IS 'CMS PatientAccess Image Files';
COMMENT ON COLUMN pafiles.fileblob IS 'BLOB containing the raw file data.';
COMMENT ON COLUMN pafiles."PAFILESID" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN pafiles."FILENAME" IS 'Name of the file.';
COMMENT ON COLUMN pafiles."FILEMIME" IS 'MIME type of the file.';
COMMENT ON COLUMN pafiles."DIMENSION" IS 'Dimensions of the image file, in pixels.';
COMMENT ON COLUMN pafiles."CREATEDATE" IS 'Timestamp of when the file was imported to the CMS.';


CREATE  TABLE pagination (
  "User" numeric(10,0) NOT NULL,
  "Tab" numeric(5,0) NOT NULL,
  "Show" numeric(5,0),
  CONSTRAINT pagination_pk PRIMARY KEY ("User", "Tab")
) ;
COMMENT ON TABLE pagination IS 'User Pagination Settings';
COMMENT ON COLUMN pagination."User" IS 'Primary key component, Ptr to USERS.User';
COMMENT ON COLUMN pagination."Tab" IS 'Primary key component, 0 - EHR/Tx History, 1 - Transactions/General';
COMMENT ON COLUMN pagination."Show" IS '0-show all records for Tab, 1-show 20, 2-show 30, 3-show 40';


CREATE  TABLE panav (
  "PANAVID" numeric NOT NULL,
  "PANAVNAME" character varying(256),
  "PANAVACTIVE" numeric(38,0),
  "PANAVAUTH" numeric(38,0),
  "PANAVPRIORITY" numeric,
  patemplateid_fk numeric,
  "PAPARENTID" numeric,
  "Type" numeric NOT NULL DEFAULT 0,
  "PANAVHIDERES" numeric(38,0),
  "PANAVFIRSTACCESS" numeric(38,0),
  CONSTRAINT panav_pk PRIMARY KEY ("PANAVID")
) ;
COMMENT ON TABLE panav IS 'CMS PatientAccess Pages';
COMMENT ON COLUMN panav.patemplateid_fk IS 'Template used to render this page, ptr to PATEMPLATE."PATEMPLATEID"';
COMMENT ON COLUMN panav."Type" IS 'Page type (0 = Custom Pages, 1 = Home: Landing Page, 2 = Home: Logged In Page, 3 = Home: Logged Out Page, 4 = Online Appointment Request, 5 = Online Appointment Confirmation)';
COMMENT ON COLUMN panav."PAPARENTID" IS 'Parent page of this page (0=No parent, Else ptr to PANAV."PANAVID" of parent page)';
COMMENT ON COLUMN panav."PANAVPRIORITY" IS 'Priority of the page.';
COMMENT ON COLUMN panav."PANAVNAME" IS 'Page title.';
COMMENT ON COLUMN panav."PANAVID" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN panav."PANAVHIDERES" IS 'Hide Page from logged in authorized representatives? (0=No, 1=Yes)';
COMMENT ON COLUMN panav."PANAVFIRSTACCESS" IS 'Available in First Access? (0=No, 1=Yes)';
COMMENT ON COLUMN panav."PANAVAUTH" IS 'Does the patient need to be logged in to see this page? (0=No, 1=Yes)';
COMMENT ON COLUMN panav."PANAVACTIVE" IS 'Is this page active? (0=No, 1=Yes)';


CREATE  TABLE panavcontent (
  "PANAVCONTENTID" numeric NOT NULL,
  panavid_fk numeric,
  "PANAVCONTENTNAME" character varying(50),
  "PANAVCONTENTTYPE" numeric,
  panavcontent clob,
  CONSTRAINT panavcontent_primary PRIMARY KEY ("PANAVCONTENTID")
) ;
COMMENT ON TABLE panavcontent IS 'CMS Content Elements for PatientAccess Pages';
COMMENT ON COLUMN panavcontent.panavid_fk IS 'The page that this content element is for, ptr to PANAV."PANAVID"';
COMMENT ON COLUMN panavcontent.panavcontent IS 'Content of the content element.';
COMMENT ON COLUMN panavcontent."PANAVCONTENTTYPE" IS 'Type of content in this content element (1=Content [user defined], 2=Forms, 3=Patient Profile, 4=Login, 5=Change Password, 6=Change Security Questions, 7=Upcoming Appt, 8=Appt List, 9=Medical Info)';
COMMENT ON COLUMN panavcontent."PANAVCONTENTNAME" IS 'Name of the content element.';
COMMENT ON COLUMN panavcontent."PANAVCONTENTID" IS 'Primary key, internal ID from sequence.';


CREATE  TABLE panewpage (
  "Id" numeric(10,0) NOT NULL DEFAULT 0,
  "Name" character varying(255) NOT NULL,
  "IsActive" numeric(10,0) NOT NULL DEFAULT 0,
  "PageUrl" character varying(2048) NOT NULL,
  "ShowOnSidebar" numeric(1,0) NOT NULL DEFAULT 0,
  "Icon" character varying(100),
  "ParentId" numeric(10,0) NOT NULL DEFAULT 0,
  "Order" numeric(10,0) NOT NULL DEFAULT 0,
  "HideFromAuthRep" numeric(10,0) NOT NULL DEFAULT 0,
  "ShowOnFirstAccess" numeric(10,0) NOT NULL DEFAULT 0,
  CONSTRAINT panewpage_primary PRIMARY KEY ("Id")
) ;
CREATE INDEX IF NOT EXISTS panewpage_parentidkey ON panewpage USING btree ("ParentId") TABLESPACE pg_default;
COMMENT ON TABLE panewpage IS 'Table for storing Patient Access 2.0 pages';
COMMENT ON COLUMN panewpage."ShowOnSidebar" IS 'Is this column shown in the sidebar (0 = No, 1 = Yes)';
COMMENT ON COLUMN panewpage."ShowOnFirstAccess" IS 'Available in First Access? (0=No, 1=Yes)';
COMMENT ON COLUMN panewpage."ParentId" IS 'Id of the parent page, for sub-pages.';
COMMENT ON COLUMN panewpage."PageUrl" IS 'iframe source for the page';
COMMENT ON COLUMN panewpage."Order" IS 'Order of the page in the menu.';
COMMENT ON COLUMN panewpage."Name" IS 'Page name';
COMMENT ON COLUMN panewpage."IsActive" IS 'Is this page active? (0=No, 1=Yes)';
COMMENT ON COLUMN panewpage."Id" IS 'Primary key, sequence field';
COMMENT ON COLUMN panewpage."Icon" IS 'FontAwesome icon for the page in the menu';
COMMENT ON COLUMN panewpage."HideFromAuthRep" IS 'Hide Page from logged in authorized representatives? (0=No, 1=Yes)';


CREATE  TABLE papasres (
  "PasResId" numeric(10,0) NOT NULL,
  "PatientId" numeric(10,0),
  "UserName" character varying(100),
  "First" character(30),
  "Birth" timestamp without time zone,
  "Email" character varying(100),
  "RequestDateTime" timestamp without time zone,
  "ExpiryDateTime" timestamp without time zone,
  "Error" numeric(5,0),
  "ProcessType" numeric(5,0),
  CONSTRAINT papasres_pk PRIMARY KEY ("PasResId")
) ;
COMMENT ON TABLE papasres IS 'Password reset / Self Registration Tickets';
COMMENT ON COLUMN papasres."UserName" IS 'PatientAccess username for the patient, ptr to IUSER.UserName.';
COMMENT ON COLUMN papasres."RequestDateTime" IS 'Date/time that the ticket was created.';
COMMENT ON COLUMN papasres."ProcessType" IS 'Process that the ticket is for (1=Password Reset, 2=Self Registration)';
COMMENT ON COLUMN papasres."PatientId" IS 'Patient that the ticket is for, ptr to PATIENT.Patient.';
COMMENT ON COLUMN papasres."PasResId" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN papasres."First" IS 'First or preferred name of the patient. ';
COMMENT ON COLUMN papasres."ExpiryDateTime" IS 'Date/time that the ticket expires.';
COMMENT ON COLUMN papasres."Error" IS 'Is this ticket valid (0=No, 1=Yes)';
COMMENT ON COLUMN papasres."Email" IS 'Email address of the patient.';
COMMENT ON COLUMN papasres."Birth" IS 'Birthdate of the patient.';


CREATE  TABLE pat2his (
  "Pat2His" numeric(10,0) NOT NULL,
  "HistoryType" numeric(5,0),
  "Auto" numeric(10,0),
  "ChartId" character(15),
  "LastName" character(31),
  "FirstName" character(31),
  "MidName" character(31),
  "Status" numeric(10,0),
  "User" numeric(10,0),
  "PtxPId" numeric(10,0),
  "ToothState" character(32),
  "PermanentState" character(32),
  "PrimaryState" character(32),
  "Date" timestamp without time zone,
  "StationId" numeric(10,0),
  CONSTRAINT pat2his_primary PRIMARY KEY ("Pat2His")
) ;
CREATE INDEX IF NOT EXISTS pat2his_auto ON pat2his USING btree ("Auto") TABLESPACE pg_default;
COMMENT ON TABLE pat2his IS 'Patient Charting Information History';
COMMENT ON COLUMN pat2his."User" IS 'ID code of the entry user, ptr to USERS.User';
COMMENT ON COLUMN pat2his."ToothState" IS 'Array of current tooth states (0 = Permanent, 1 = Primary, 2 = Permanent Missing, 3 = Primary Missing)';
COMMENT ON COLUMN pat2his."Status" IS 'DEPRECATED';
COMMENT ON COLUMN pat2his."StationId" IS 'Station ID of the entry user, ptr to STATION.StationId';
COMMENT ON COLUMN pat2his."PtxPId" IS 'Link to patient record, ptr to PATIENT.Patient';
COMMENT ON COLUMN pat2his."PrimaryState" IS 'Array of additional information regarding primary teeth (0 = Exists, 1 = Extracted, 2 = Impacted, 4 = Planned Extraction)';
COMMENT ON COLUMN pat2his."PermanentState" IS 'Array of additional information regarding permanent teeth (0 = Exists, 1 = Extracted, 2 = Impacted, 4 = Planned Extraction)';
COMMENT ON COLUMN pat2his."Pat2His" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN pat2his."MidName" IS 'Patient middle name, ptr to PATIENT.Middle';
COMMENT ON COLUMN pat2his."LastName" IS 'Patient last name, ptr to PATIENT.Last';
COMMENT ON COLUMN pat2his."HistoryType" IS 'Type of history (1=Add, 2=Edit, 4=Delete)';
COMMENT ON COLUMN pat2his."FirstName" IS 'Patient first name, ptr to PATIENT.First';
COMMENT ON COLUMN pat2his."Date" IS 'Date the entry was made';
COMMENT ON COLUMN pat2his."ChartId" IS 'Chart number of the patient, ptr to PATIENT.Chart';
COMMENT ON COLUMN pat2his."Auto" IS 'Patient charting record that this history is for, ptr to PATIENT2.Auto.';


CREATE  TABLE patacces (
  "PatType" character(6) NOT NULL,
  "SLevel" numeric(10,0) NOT NULL,
  "Patients" numeric(5,0),
  "AddTxs" numeric(5,0),
  "MultiProcedure" numeric(5,0),
  "AddFees" numeric(5,0),
  "Reporting" numeric(5,0),
  CONSTRAINT patacces_primary PRIMARY KEY ("PatType", "SLevel")
) ;
COMMENT ON TABLE patacces IS 'Patient Access for specific patient types';
COMMENT ON COLUMN patacces."SLevel" IS 'Primary Key, Security Level, ptr to SLEVEL.Level';
COMMENT ON COLUMN patacces."Reporting" IS 'Report on in Info Manager (0 = No, 1 = Yes)';
COMMENT ON COLUMN patacces."Patients" IS 'Can search in Patients module? (0 = No, 1 = Yes)';
COMMENT ON COLUMN patacces."PatType" IS 'Primary Key, Patient Type, ptr to PATTYPE.PatType';
COMMENT ON COLUMN patacces."MultiProcedure" IS 'Metal-Head, Dummy pt. (0 = No, 1 = Yes)';
COMMENT ON COLUMN patacces."AddTxs" IS 'Can Add Treatments? (0 = No, 1 = Yes)';
COMMENT ON COLUMN patacces."AddFees" IS 'Add Fees for Treatments? (0 = No, 1 = Yes)';


CREATE  TABLE patemplate (
  "PATEMPLATEID" numeric NOT NULL,
  patemplatehtml clob,
  patemplatecss clob,
  patemplatejs clob,
  "PATEMPLATENAME" character varying(256),
  patemplatelogiccss clob,
  CONSTRAINT patemplate_primary PRIMARY KEY ("PATEMPLATEID")
) ;
COMMENT ON TABLE patemplate IS 'CMS Templates for PatientAccess';
COMMENT ON COLUMN patemplate.patemplatelogiccss IS 'Logic CSS for the template.';
COMMENT ON COLUMN patemplate.patemplatejs IS 'Javascript for the template.';
COMMENT ON COLUMN patemplate.patemplatehtml IS 'HTML for the template.';
COMMENT ON COLUMN patemplate.patemplatecss IS 'CSS for the template.';
COMMENT ON COLUMN patemplate."PATEMPLATENAME" IS 'Name of the template as shown in CMS.';
COMMENT ON COLUMN patemplate."PATEMPLATEID" IS 'Primary key, internal ID from sequence.';


CREATE  TABLE pathis (
  "Id" numeric(10,0) NOT NULL,
  "UserAddedFlag" numeric(5,0),
  "PtStatusFlag" numeric(5,0),
  "PtNameFlag" numeric(5,0),
  "PtAddressFlag" numeric(5,0),
  "PtOfficeFlag" numeric(5,0),
  "PtAlertFlag" numeric(5,0),
  "PtCustom1Flag" numeric(5,0),
  "PtCustom2Flag" numeric(5,0),
  "PtCustom3Flag" numeric(5,0),
  "PtCustom4Flag" numeric(5,0),
  "PtCustom5Flag" numeric(5,0),
  "PtCustom6Flag" numeric(5,0),
  "PtCustom7Flag" numeric(5,0),
  "PtCustom8Flag" numeric(5,0),
  "PtCustom9Flag" numeric(5,0),
  "PtCustom10Flag" numeric(5,0),
  "PtChartFlag" numeric(5,0),
  "PtAddFlag" numeric(5,0),
  "PtDeleteFlag" numeric(5,0),
  "Patient" numeric(10,0),
  "Family" numeric(10,0),
  "Last" character(25),
  "First" character(30),
  "Preferred" character(30),
  "Middle" character(15),
  "Title" character(15),
  "Birth" timestamp without time zone,
  "Address1" character(30),
  "Address2" character(30),
  "City" character(24),
  "Province" character(6),
  "Postal" character(15),
  "HomeArea" character(4),
  "HomePhone" character(8),
  "WorkArea" character(4),
  "WorkPhone" character(8),
  "WorkExt" character varying(6),
  "OtherArea" character(4),
  "OtherPhone" character(8),
  "OtherExt" character varying(6),
  "ContactAt" numeric(5,0),
  "ContactTime" character(15),
  "Status" character(6),
  "Sex" numeric(5,0),
  "Marital" numeric(5,0),
  "IsPatient" numeric(5,0),
  "IsStudent" numeric(5,0),
  "IsHandicaped" numeric(5,0),
  "Chart" character(10),
  "Sin" character(15),
  "Office1" character(6),
  "Office2" character(6),
  "Office3" character(6),
  "Office4" character(6),
  "Office5" character(6),
  "Alert1" character(6),
  "Alert2" character(6),
  "Alert3" character(6),
  "Alert4" character(6),
  "Alert5" character(6),
  "Open" timestamp without time zone,
  "Close" timestamp without time zone,
  "Path" numeric(5,0),
  "School" character varying(25),
  "Health" character(20),
  "AccountStatus" character(6),
  "Assignment" numeric(5,0),
  "Statements" numeric(5,0),
  "IsFreeAccess" numeric(5,0),
  "Fee" character(6),
  "OtherLocation" character(15),
  "NoLocks" numeric(5,0),
  "CustomCode1" character(6),
  "CustomCode2" character(6),
  "CustomCode3" character(6),
  "CustomCode4" character(6),
  "CustomCode5" character(6),
  "CustomCode6" character(6),
  "CustomCode7" character(6),
  "CustomCode8" character(6),
  "CustomCode9" character(6),
  "CustomCode10" character(6),
  "Physician" numeric(10,0),
  "EmergLast" character(30),
  "EmergFirst" character(30),
  "EmergMiddle" character(15),
  "EmergAddress" character(30),
  "EmergAddress2" character(30),
  "EmergAddressOther" character(15),
  "EmergCity" character(24),
  "EmergProvince" character(6),
  "EmergPostal" character(15),
  "EmergArea" character(4),
  "EmergPhone" character(8),
  "EmergAltArea" character(4),
  "EmergAltPhone" character(8),
  "EmergRelation" character(15),
  "IsChartFixed" numeric(5,0),
  "IsOrtho" numeric(5,0),
  "OrthoSet" character(6),
  "AltChart" character(15),
  "AddressOther" character(15),
  "BankAccount" character(10),
  "EDIFlag" numeric(5,0),
  "StatusEndDate" timestamp without time zone,
  "IsEmergency" numeric(5,0),
  "ActiveDate" timestamp without time zone,
  "PartnerName" character(25),
  "BoxNumber" character(15),
  "Email" character varying(100),
  "ChartSort" character(10),
  "PartnerPrefix" character(15),
  "PrefApptTime" character(15),
  "XRayReceived" numeric(5,0),
  "DateXRayExpected" timestamp without time zone,
  "DateXRayReceived" timestamp without time zone,
  "Country" character(30),
  "XRayExposures" numeric(5,0),
  "MergedChart" character(10),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "ChartSuffix" character(1),
  "ReleaseOnFile" numeric(5,0),
  "EmergExt" character varying(6),
  "EmergAltExt" character varying(6),
  "FeeOverride" numeric(5,0),
  "DiscGrp" character(6),
  "RequireTxConsent" numeric(5,0),
  "PaperChart" numeric(5,0),
  "InfoNotify" numeric(5,0),
  "TaxExempt" numeric(5,0),
  "RecallDoctorToUse" numeric(5,0),
  "RecallHygToUse" numeric(5,0),
  "CustomText1" character varying(30),
  "CustomText2" character varying(30),
  "CustomText3" character varying(30),
  "CustomText4" character varying(30),
  "CustomText5" character varying(30),
  "PtCustomText1Flag" numeric(5,0),
  "PtCustomText2Flag" numeric(5,0),
  "PtCustomText3Flag" numeric(5,0),
  "PtCustomText4Flag" numeric(5,0),
  "PtCustomText5Flag" numeric(5,0),
  "MobileArea" character(4),
  "MobilePhone" character(8),
  "ApptFeesExempt" numeric(5,0),
  "PrefLanguage" character(6),
  "RaceEthDeclined" numeric(5,0),
  "Ethnic" character(6),
  "IsTrustedAudit" numeric(10,0),
  "SecondIDType" numeric(5,0),
  "SecondIDNumber" character varying(15),
  "Is2ndIdTrustedAudit" numeric(10,0),
  "HasExternalLink" numeric(5,0),
  "HasCarequality" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT pathis_primary PRIMARY KEY ("Id")
) ;
CREATE INDEX IF NOT EXISTS pathis_familykey ON pathis USING btree ("Family") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS pathis_patient ON pathis USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE pathis IS 'Patient History';
COMMENT ON COLUMN pathis."XRayReceived" IS 'X-Ray received? (0=No, 1=Yes)';
COMMENT ON COLUMN pathis."XRayExposures" IS 'Total number of X-Ray exposures for this patient.';
COMMENT ON COLUMN pathis."WorkPhone" IS 'Telephone number (work), Format: ###-####';
COMMENT ON COLUMN pathis."WorkExt" IS 'Telephone extension (work)';
COMMENT ON COLUMN pathis."WorkArea" IS 'Telephone area code (work)';
COMMENT ON COLUMN pathis."UserAddedFlag" IS 'For internal use. ';
COMMENT ON COLUMN pathis."Title" IS 'Patient title, either freetext or from TITLE.Title';
COMMENT ON COLUMN pathis."TaxExempt" IS 'Patient is tax exempt? (0=No, 1=Yes)';
COMMENT ON COLUMN pathis."StatusEndDate" IS 'Date that the current status ends.';
COMMENT ON COLUMN pathis."Status" IS 'Patient status, ptr to STATUS.Status';
COMMENT ON COLUMN pathis."Statements" IS 'Are statements sent to the patient? (0=No, 1=Yes)';
COMMENT ON COLUMN pathis."Sin" IS 'ID number for the patient, used generally to store SIN (Canada), SSN (US)';
COMMENT ON COLUMN pathis."Sex" IS 'Patient gender (0=Unknown, 1=Male, 2=Female, 3=Transgender, 4=Gender X, 5=Other)';
COMMENT ON COLUMN pathis."SecondIDType" IS 'Secondary ID document Type (0=N/A, 1=Passport, 2=Drivers License, 3=Government ID Card)';
COMMENT ON COLUMN pathis."SecondIDNumber" IS 'Secondary ID doucment number';
COMMENT ON COLUMN pathis."School" IS 'School name, either freetext or from SCHOOL.School';
COMMENT ON COLUMN pathis."RequireTxConsent" IS 'Patient requires treatment consent? (0=No, 1=Yes)';
COMMENT ON COLUMN pathis."ReleaseOnFile" IS 'Release of information on file? (0=No, 1=Yes)';
COMMENT ON COLUMN pathis."RecallHygToUse" IS 'Recall hygienist to use (0=Any, 1=Assigned Hygienist, 2=Assigned Hygienst or same provider type, 3=Any Hygienist or enhanced CDA)';
COMMENT ON COLUMN pathis."RecallDoctorToUse" IS 'Recall doctor to use? (0=Any, 1=Assigned Doctor)';
COMMENT ON COLUMN pathis."RaceEthDeclined" IS 'Declined to answer Race? (0=No, 1=Yes)';
COMMENT ON COLUMN pathis."PtStatusFlag" IS 'Flag to indicate changes to the patient status.';
COMMENT ON COLUMN pathis."PtOfficeFlag" IS 'Flag to indicate changes to the office code fields.';
COMMENT ON COLUMN pathis."PtNameFlag" IS 'Flag to indicate changes to the patient name.';
COMMENT ON COLUMN pathis."PtDeleteFlag" IS 'For internal use. ';
COMMENT ON COLUMN pathis."PtCustomText5Flag" IS 'Flag to indicate changes to the CustomText5 field';
COMMENT ON COLUMN pathis."PtCustomText4Flag" IS 'Flag to indicate changes to the CustomText4 field';
COMMENT ON COLUMN pathis."PtCustomText3Flag" IS 'Flag to indicate changes to the CustomText3 field';
COMMENT ON COLUMN pathis."PtCustomText2Flag" IS 'Flag to indicate changes to the CustomText2 field';
COMMENT ON COLUMN pathis."PtCustomText1Flag" IS 'Flag to indicate changes to the CustomText1 field';
COMMENT ON COLUMN pathis."PtCustom9Flag" IS 'Flag to indicate changes to the CustomCode9 field';
COMMENT ON COLUMN pathis."PtCustom8Flag" IS 'Flag to indicate changes to the CustomCode8 field';
COMMENT ON COLUMN pathis."PtCustom7Flag" IS 'Flag to indicate changes to the CustomCode7 field';
COMMENT ON COLUMN pathis."PtCustom6Flag" IS 'Flag to indicate changes to the CustomCode6 field';
COMMENT ON COLUMN pathis."PtCustom5Flag" IS 'Flag to indicate changes to the CustomCode5 field';
COMMENT ON COLUMN pathis."PtCustom4Flag" IS 'Flag to indicate changes to the CustomCode4 field';
COMMENT ON COLUMN pathis."PtCustom3Flag" IS 'Flag to indicate changes to the CustomCode3 field';
COMMENT ON COLUMN pathis."PtCustom2Flag" IS 'Flag to indicate changes to the CustomCode2 field';
COMMENT ON COLUMN pathis."PtCustom1Flag" IS 'Flag to indicate changes to the CustomCode1 field';
COMMENT ON COLUMN pathis."PtCustom10Flag" IS 'Flag to indicate changes to the CustomCode10 field';
COMMENT ON COLUMN pathis."PtChartFlag" IS 'Flag to indicate changes to the Chart field';
COMMENT ON COLUMN pathis."PtAlertFlag" IS 'Flag to indicate changes to the alert code fields.';
COMMENT ON COLUMN pathis."PtAddressFlag" IS 'Flag to indicate changes to the patient address.';
COMMENT ON COLUMN pathis."PtAddFlag" IS 'For internal use. ';
COMMENT ON COLUMN pathis."Province" IS 'Province / state, ptr to PROVINCE.Province';
COMMENT ON COLUMN pathis."Preferred" IS 'Patient preferred name.';
COMMENT ON COLUMN pathis."PrefLanguage" IS 'Preferred Language. Ptr to LANGCD.LangCd';
COMMENT ON COLUMN pathis."PrefApptTime" IS 'Preferred appointment time, freetext.';
COMMENT ON COLUMN pathis."Postal" IS 'Postal / ZIP code, ptr to CITY.Postal';
COMMENT ON COLUMN pathis."Physician" IS 'Treating physician, ptr to PHYSICIA.Physician';
COMMENT ON COLUMN pathis."Patient" IS 'Patient that this history is for, ptr to PATIENT.Patient';
COMMENT ON COLUMN pathis."Path" IS 'Patient has a picture? (0=No, 1=Yes)';
COMMENT ON COLUMN pathis."PartnerPrefix" IS 'Dutch version only, partner name prefix. Freetext.';
COMMENT ON COLUMN pathis."PartnerName" IS 'Dutch version only, partner name.';
COMMENT ON COLUMN pathis."PaperChart" IS 'Paper chart? (0=Electronic chart, 1=Paper chart)';
COMMENT ON COLUMN pathis."OtherPhone" IS 'Telephone number (other), Format: ###-####';
COMMENT ON COLUMN pathis."OtherLocation" IS 'Freetext location of the Other telephone number. ';
COMMENT ON COLUMN pathis."OtherExt" IS 'Telephone extension (other)';
COMMENT ON COLUMN pathis."OtherArea" IS 'Telephone area code (other)';
COMMENT ON COLUMN pathis."OrthoSet" IS 'Current Ortho Set, ptr to ORTHOSET.Code';
COMMENT ON COLUMN pathis."Open" IS 'Account open date';
COMMENT ON COLUMN pathis."Office5" IS 'Office code 5, ptr to OFFICE.Office';
COMMENT ON COLUMN pathis."Office4" IS 'Office code 4, ptr to OFFICE.Office';
COMMENT ON COLUMN pathis."Office3" IS 'Office code 3, ptr to OFFICE.Office';
COMMENT ON COLUMN pathis."Office2" IS 'Office code 2, ptr to OFFICE.Office';
COMMENT ON COLUMN pathis."Office1" IS 'Office code 1, ptr to OFFICE.Office';
COMMENT ON COLUMN pathis."NoLocks" IS 'No chart locks? (0=No, 1=Yes)';
COMMENT ON COLUMN pathis."MobilePhone" IS 'Telephone number (mobile), Format: ###-####';
COMMENT ON COLUMN pathis."MobileArea" IS 'Telephone area code (mobile)';
COMMENT ON COLUMN pathis."Middle" IS 'Patient middle name.';
COMMENT ON COLUMN pathis."MergedChart" IS 'If this patient was chart merged in the past, the (bad) chart that was merged into this one. Ptr to PATIENT.Chart';
COMMENT ON COLUMN pathis."Marital" IS 'Patient marital status (0=Unknown, 1=Single, 2=Married, 3=Divorced, 4=Common-Law, 5=Separated, 6=Widowed, 7=Domestic Partner)';
COMMENT ON COLUMN pathis."Last" IS 'Patient last name.';
COMMENT ON COLUMN pathis."IsTrustedAudit" IS 'The audit number that is recorded when the Patient SIN is stamped as trusted';
COMMENT ON COLUMN pathis."IsStudent" IS 'Is the patient a student? (0=No, 1=Full time, 2=Part time)';
COMMENT ON COLUMN pathis."IsPatient" IS 'Is this a patient or a non-patient guarantor? (0=Non-patient guarantor, 1=Patient)';
COMMENT ON COLUMN pathis."IsOrtho" IS 'Is this an Ortho patient? (0=No, 1=Yes)';
COMMENT ON COLUMN pathis."IsHandicaped" IS 'Patient has special needs / is handicapped? (0=No, 1=Yes)';
COMMENT ON COLUMN pathis."IsFreeAccess" IS 'Free access? (0=No, 1=Yes)';
COMMENT ON COLUMN pathis."IsEmergency" IS 'Emergency? (0=No, 1=Yes)';
COMMENT ON COLUMN pathis."IsChartFixed" IS 'Chart number is fixed? (0=No, 1=Yes)';
COMMENT ON COLUMN pathis."Is2ndIdTrustedAudit" IS 'The audit number that is recorded when the Patient SecondIDNumber is stamped as trusted';
COMMENT ON COLUMN pathis."InfoNotify" IS 'Address is incorrect? (0=No, 1=Yes)';
COMMENT ON COLUMN pathis."Id" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN pathis."HomePhone" IS 'Telephone number (home), Format: ###-####';
COMMENT ON COLUMN pathis."HomeArea" IS 'Telephone area code (home)';
COMMENT ON COLUMN pathis."Health" IS 'Health unit of the school, either freetext or from SCHOOL.Health';
COMMENT ON COLUMN pathis."HasExternalLink" IS 'true if patient has at least 1 non-deleted EXTERNAL_LINK record';
COMMENT ON COLUMN pathis."HasCarequality" IS 'true if patient has at least 1 non-deleted CAREQUALITY_PATIENT record';
COMMENT ON COLUMN pathis."First" IS 'Patient first name.';
COMMENT ON COLUMN pathis."FeeOverride" IS 'Bill patient fee (0=N/A, 1=Always, 2=Unless practice override)';
COMMENT ON COLUMN pathis."Fee" IS 'Default fee schedule for this patient, ptr to FEESCHED.Fee';
COMMENT ON COLUMN pathis."Family" IS 'Family ID. This will be the same as PATIENT.Patient unless this patient is or was formerly a non-patient guarantor (PATIENT.IsPatient=0)';
COMMENT ON COLUMN pathis."Ethnic" IS 'Ethnic code, Ptr to ETHNIC.Ethnic';
COMMENT ON COLUMN pathis."EmergRelation" IS 'Emergency contact relationship to the patient.';
COMMENT ON COLUMN pathis."EmergProvince" IS 'Emergency contact province / state, ptr to PROVINCE.Province';
COMMENT ON COLUMN pathis."EmergPostal" IS 'Emergency contact postal / ZIP code, ptr to CITY.Postal';
COMMENT ON COLUMN pathis."EmergPhone" IS 'Emergency contact telephone number. Format: ###-####';
COMMENT ON COLUMN pathis."EmergMiddle" IS 'Emergency contact middle name.';
COMMENT ON COLUMN pathis."EmergLast" IS 'Emergency contact last name.';
COMMENT ON COLUMN pathis."EmergFirst" IS 'Emergency contact first name.';
COMMENT ON COLUMN pathis."EmergExt" IS 'Emergency contact phone extension';
COMMENT ON COLUMN pathis."EmergCity" IS 'Emergency contact city, ptr to CITY.City';
COMMENT ON COLUMN pathis."EmergArea" IS 'Emergency contact telephone area code';
COMMENT ON COLUMN pathis."EmergAltPhone" IS 'Emergency contact alternate telephone number. Format: ###-####';
COMMENT ON COLUMN pathis."EmergAltExt" IS 'Emergency contact alternate phone extension';
COMMENT ON COLUMN pathis."EmergAltArea" IS 'Emergency contact alternate telephone area code';
COMMENT ON COLUMN pathis."EmergAddressOther" IS 'For USA, represents County. For Dutch, represents Room Number.';
COMMENT ON COLUMN pathis."EmergAddress2" IS 'Emergency contact address, line 2';
COMMENT ON COLUMN pathis."EmergAddress" IS 'Emergency contact address, line 1';
COMMENT ON COLUMN pathis."Email" IS 'Email address of the patient';
COMMENT ON COLUMN pathis."EDIFlag" IS 'Factoring Co. - Dutch version only. Held Billings? (Both "EDI" and Vektis Invoices) (0=No, 1=Yes)';
COMMENT ON COLUMN pathis."DiscGrp" IS 'Patient discount group, ptr to DISCGRP.DiscGrp';
COMMENT ON COLUMN pathis."Deleted" IS 'Patient is deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN pathis."DateXRayReceived" IS 'Date the X-Ray was received.';
COMMENT ON COLUMN pathis."DateXRayExpected" IS 'Date the X-Ray is expected to be received.';
COMMENT ON COLUMN pathis."CustomText5" IS 'Custom text field 5 value.';
COMMENT ON COLUMN pathis."CustomText4" IS 'Custom text field 4 value.';
COMMENT ON COLUMN pathis."CustomText3" IS 'Custom text field 3 value.';
COMMENT ON COLUMN pathis."CustomText2" IS 'Custom text field 2 value.';
COMMENT ON COLUMN pathis."CustomText1" IS 'Custom text field 1 value.';
COMMENT ON COLUMN pathis."CustomCode9" IS 'Custom field 9, ptr to CUSTCODE.Code';
COMMENT ON COLUMN pathis."CustomCode8" IS 'Custom field 8, ptr to CUSTCODE.Code';
COMMENT ON COLUMN pathis."CustomCode7" IS 'Custom field 7, ptr to CUSTCODE.Code';
COMMENT ON COLUMN pathis."CustomCode6" IS 'Custom field 6, ptr to CUSTCODE.Code';
COMMENT ON COLUMN pathis."CustomCode5" IS 'Custom field 5, ptr to CUSTCODE.Code';
COMMENT ON COLUMN pathis."CustomCode4" IS 'Custom field 4, ptr to CUSTCODE.Code';
COMMENT ON COLUMN pathis."CustomCode3" IS 'Custom field 3, ptr to CUSTCODE.Code';
COMMENT ON COLUMN pathis."CustomCode2" IS 'Custom field 2, ptr to CUSTCODE.Code';
COMMENT ON COLUMN pathis."CustomCode10" IS 'Custom field 10, ptr to CUSTCODE.Code';
COMMENT ON COLUMN pathis."CustomCode1" IS 'Custom field 1, ptr to CUSTCODE.Code';
COMMENT ON COLUMN pathis."Country" IS 'Country, either freetext or from COUNTRY.Country.';
COMMENT ON COLUMN pathis."ContactTime" IS 'Time of day that the patient prefers to be contacted at, freetext.';
COMMENT ON COLUMN pathis."ContactAt" IS 'Location that the patient prefers to be contacted at? (1=Home, 2=Work, 3=Other, 4=Mobile)';
COMMENT ON COLUMN pathis."Close" IS 'Account closed date';
COMMENT ON COLUMN pathis."City" IS 'City, ptr to CITY.City';
COMMENT ON COLUMN pathis."ChartSuffix" IS 'Internal field used for sorting charts, only used for the Custom Chart Sort method. Used to generate the ChartArea';
COMMENT ON COLUMN pathis."ChartSort" IS 'Internal field used for sorting charts, contents depend on chart sort order configuration in Practice options. ';
COMMENT ON COLUMN pathis."Chart" IS 'Patient chart number.';
COMMENT ON COLUMN pathis."BoxNumber" IS 'Patient assigned box number.';
COMMENT ON COLUMN pathis."Birth" IS 'Patient date of birth.';
COMMENT ON COLUMN pathis."BankAccount" IS 'Patient bank account number.';
COMMENT ON COLUMN pathis."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN pathis."Assignment" IS 'Patients claims are billed to insurance directly? (0=No, 1=Yes)';
COMMENT ON COLUMN pathis."ApptFeesExempt" IS 'Is the patient exempt from being charged appointment cancellation fees? (0=No, 1=Yes)';
COMMENT ON COLUMN pathis."AltChart" IS 'Alternate chart ID';
COMMENT ON COLUMN pathis."Alert5" IS 'Alert code 5, ptr to ALERT.Alert';
COMMENT ON COLUMN pathis."Alert4" IS 'Alert code 4, ptr to ALERT.Alert';
COMMENT ON COLUMN pathis."Alert3" IS 'Alert code 3, ptr to ALERT.Alert';
COMMENT ON COLUMN pathis."Alert2" IS 'Alert code 2, ptr to ALERT.Alert';
COMMENT ON COLUMN pathis."Alert1" IS 'Alert code 1, ptr to ALERT.Alert';
COMMENT ON COLUMN pathis."AddressOther" IS 'For USA, represents County. For Dutch, represents Room Number.';
COMMENT ON COLUMN pathis."Address2" IS 'Patient address line 2';
COMMENT ON COLUMN pathis."Address1" IS 'Patient address line 1';
COMMENT ON COLUMN pathis."ActiveDate" IS 'Date this patient record becomes active.';
COMMENT ON COLUMN pathis."AccountStatus" IS 'Status of the account, ptr to STATUS.Status';


CREATE  TABLE patient (
  "Patient" numeric(10,0) NOT NULL,
  "Family" numeric(10,0),
  "Last" character(25),
  "First" character(30),
  "Prefered" character(30),
  "Middle" character(15),
  "Title" character(15),
  "Birth" timestamp without time zone,
  "Address1" character(30),
  "Address2" character(30),
  "City" character(24),
  "Province" character(6),
  "Postal" character(15),
  "HomeArea" character(4),
  "HomePhone" character(8),
  "WorkArea" character(4),
  "WorkPhone" character(8),
  "WorkExt" character varying(6),
  "OtherArea" character(4),
  "OtherPhone" character(8),
  "OtherExt" character varying(6),
  "OtherLoc" character(8),
  "ContactAt" numeric(5,0),
  "ContactTime" character(15),
  "Status" character(6),
  "Sex" numeric(5,0),
  "Marital" numeric(5,0),
  "IsPatient" numeric(5,0),
  "IsStudent" numeric(5,0),
  "IsHandicaped" numeric(5,0),
  "Doctor" character(10),
  "Hygienist" character(10),
  "Aux" character(10),
  "Chart" character(10),
  "Sin" character(15),
  "Office1" character(6),
  "Office2" character(6),
  "Office3" character(6),
  "Office4" character(6),
  "Office5" character(6),
  "Alert1" character(6),
  "Alert2" character(6),
  "Alert3" character(6),
  "Alert4" character(6),
  "Alert5" character(6),
  "Permenant" numeric(10,0),
  "Primary" numeric(10,0),
  "Flags" numeric(10,0),
  "Open" timestamp without time zone,
  "Close" timestamp without time zone,
  "FirstTreatment" timestamp without time zone,
  "LastClaimDate" timestamp without time zone,
  "LastClaimAmount" numeric,
  "Extra" numeric(10,0),
  "Path" numeric(5,0),
  "LastVisit" timestamp without time zone,
  "Deleted" numeric(5,0),
  "School" character varying(25),
  "Health" character(20),
  "InsPt" numeric(5,0),
  "OpenBalance" numeric,
  "AccountStatus" character(6),
  "Assignment" numeric(5,0),
  "Statements" numeric(5,0),
  "Interest" numeric(5,0),
  "ChartIn" numeric(5,0),
  "Location" character(6),
  "UserOut" numeric(10,0),
  "DateOut" timestamp without time zone,
  "TimeOut" numeric(10,0),
  "IsFreeAccess" numeric(5,0),
  "Fee" character(6),
  "OtherLocation" character(15),
  "NoLocks" numeric(5,0),
  "CustomCode1" character(6),
  "CustomCode2" character(6),
  "CustomCode3" character(6),
  "CustomCode4" character(6),
  "CustomCode5" character(6),
  "CustomCode6" character(6),
  "CustomCode7" character(6),
  "CustomCode8" character(6),
  "CustomCode9" character(6),
  "CustomCode10" character(6),
  "Physician" numeric(10,0),
  "EmergLast" character(30),
  "EmergFirst" character(30),
  "EmergMiddle" character(15),
  "EmergAddress" character(30),
  "EmergCity" character(24),
  "EmergProvince" character(6),
  "EmergPostal" character(15),
  "EmergArea" character(4),
  "EmergPhone" character(8),
  "EmergRelation" character(15),
  "IsChartFixed" numeric(5,0),
  "EmergAltArea" character(4),
  "EmergAltPhone" character(8),
  "IsOrtho" numeric(5,0),
  "OrthoSet" character(6),
  "IsIn" numeric(5,0),
  "EmergAddress2" character(30),
  "AltChart" character(15),
  "LastUpper" character(25),
  "PrefUpper" character(30),
  "AddressOther" character(15),
  "BankAccount" character(10),
  "RespNumber" character(15),
  "EmergAddressOther" character(15),
  "LastStatementDate" timestamp without time zone,
  "LastStatementAmount" numeric,
  "EDIFlag" numeric(5,0),
  "StatusEndDate" timestamp without time zone,
  "PatType" character(1),
  "IsEmergency" numeric(5,0),
  "ActiveDate" timestamp without time zone,
  "PartnerName" character(25),
  "BoxNumber" character(15),
  "Email" character varying(100),
  "ChartSort" character(10),
  "PartnerPrefix" character(15),
  "PrefApptTime" character(15),
  "User" numeric(10,0),
  "StationId" numeric(10,0),
  "XRayReceived" numeric(5,0),
  "DateXRayExpected" timestamp without time zone,
  "DateXRayReceived" timestamp without time zone,
  "StatusStartDate" timestamp without time zone,
  "Country" character(30),
  "XRayExposures" numeric(5,0),
  "LastPmtDate" timestamp without time zone,
  "LastPaymentAmount" numeric,
  "Audit" numeric(10,0),
  "MergedChart" character(10),
  "ChartSuffix" character(1),
  "ReleaseOnFile" numeric(5,0),
  "EmergExt" character varying(6),
  "EmergAltExt" character varying(6),
  "HomeExt" character varying(6),
  "FeeOverride" numeric(5,0),
  "DiscGrp" character(6),
  "EmancedMinor" numeric(5,0),
  "RequireTxConsent" numeric(5,0),
  "PaperChart" numeric(5,0),
  "InfoNotify" numeric(5,0),
  "TaxExempt" numeric(5,0),
  "RecallDoctorToUse" numeric(5,0),
  "RecallHygToUse" numeric(5,0),
  "CustomText1" character varying(30),
  "CustomText2" character varying(30),
  "CustomText3" character varying(30),
  "CustomText4" character varying(30),
  "CustomText5" character varying(30),
  "MobileArea" character(4),
  "MobilePhone" character(8),
  "ApptFeesExempt" numeric(5,0),
  "PrefLanguage" character(6),
  "RaceEthDeclined" numeric(5,0),
  "Ethnic" character(6),
  "IsTrustedAudit" numeric(10,0),
  "SecondIDType" numeric(5,0),
  "SecondIDNumber" character varying(15),
  "Is2ndIdTrustedAudit" numeric(10,0),
  "HasExternalLink" numeric(5,0),
  "HasCarequality" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT patient_primary PRIMARY KEY ("Patient")
) ;
CREATE INDEX IF NOT EXISTS patient_altchart ON patient USING btree ("AltChart") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS patient_audit ON patient USING btree ("Audit") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS patient_chart ON patient USING btree ("Chart") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS patient_chartkey ON patient USING btree ("Chart", "Patient", "Family") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS patient_familykey ON patient USING btree ("Family", "Patient") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS patient_firstnamekey ON patient USING btree ("LastUpper", upper(("First")::text)) TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS patient_homephone ON patient USING btree ("HomePhone") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS patient_isfreeaccess ON patient USING btree ("IsFreeAccess") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS patient_lastupperkey ON patient USING btree ("LastUpper", "PrefUpper") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS patient_mobilephone ON patient USING btree ("MobilePhone") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS patient_otherphone ON patient USING btree ("OtherPhone") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS patient_sin ON patient USING btree ("Sin") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS patient_userout ON patient USING btree ("UserOut", "ChartIn") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS patient_workphone ON patient USING btree ("WorkPhone") TABLESPACE pg_default;
COMMENT ON TABLE patient IS 'Patients';
COMMENT ON COLUMN patient."XRayReceived" IS 'X-Ray received? (0=No, 1=Yes)';
COMMENT ON COLUMN patient."XRayExposures" IS 'Total number of X-Ray exposures for this patient.';
COMMENT ON COLUMN patient."WorkPhone" IS 'Telephone number (work), Format: ###-####';
COMMENT ON COLUMN patient."WorkExt" IS 'Telephone extension (work)';
COMMENT ON COLUMN patient."WorkArea" IS 'Telephone area code (work)';
COMMENT ON COLUMN patient."UserOut" IS 'User who currently has this chart out. Ptr to USERS.User';
COMMENT ON COLUMN patient."User" IS 'ID code of entry user, ptr to USERS.User';
COMMENT ON COLUMN patient."Title" IS 'Patient title, either freetext or from TITLE.Title';
COMMENT ON COLUMN patient."TimeOut" IS 'Time the chart was taken out, in minutes from midnight.';
COMMENT ON COLUMN patient."TaxExempt" IS 'Patient is tax exempt? (0=No, 1=Yes)';
COMMENT ON COLUMN patient."StatusStartDate" IS 'Date that the current status started.';
COMMENT ON COLUMN patient."StatusEndDate" IS 'Date that the current status ends.';
COMMENT ON COLUMN patient."Status" IS 'Patient status, ptr to STATUS.Status';
COMMENT ON COLUMN patient."StationId" IS 'ID code of the station, ptr to STATION.StationId';
COMMENT ON COLUMN patient."Statements" IS 'Are statements sent to the patient? (0=No, 1=Yes)';
COMMENT ON COLUMN patient."Sin" IS 'ID number for the patient, used generally to store SIN (Canada), SSN (US)';
COMMENT ON COLUMN patient."Sex" IS 'Patient gender (0=Unknown, 1=Male, 2=Female, 3=Transgender, 4=Gender X, 5=Other)';
COMMENT ON COLUMN patient."SecondIDType" IS 'Secondary ID document Type (0=N/A, 1=Passport, 2=Drivers License, 3=Government ID Card)';
COMMENT ON COLUMN patient."SecondIDNumber" IS 'Secondary ID doucment number';
COMMENT ON COLUMN patient."School" IS 'School name, either freetext or from SCHOOL.School';
COMMENT ON COLUMN patient."RespNumber" IS 'Guarantor ID number. If the patient is their own primary guarantor, this is a copy of PATIENT.Sin';
COMMENT ON COLUMN patient."RequireTxConsent" IS 'Patient requires treatment consent? (0=No, 1=Yes)';
COMMENT ON COLUMN patient."ReleaseOnFile" IS 'Release of information on file? (0=No, 1=Yes)';
COMMENT ON COLUMN patient."RecallHygToUse" IS 'Recall hygienist to use (0=Any, 1=Assigned Hygienist, 2=Assigned Hygienst or same provider type, 3=Any Hygienist or enhanced CDA)';
COMMENT ON COLUMN patient."RecallDoctorToUse" IS 'Recall doctor to use? (0=Any, 1=Assigned Doctor)';
COMMENT ON COLUMN patient."RaceEthDeclined" IS 'Declined to answer Race? (0=No, 1=Yes)';
COMMENT ON COLUMN patient."Province" IS 'Province / state, ptr to PROVINCE.Province';
COMMENT ON COLUMN patient."Primary" IS 'DEPRECATED';
COMMENT ON COLUMN patient."Prefered" IS 'Patient preferred name.';
COMMENT ON COLUMN patient."PrefUpper" IS 'Uppercase copy of patient preferred Name, used for searches.';
COMMENT ON COLUMN patient."PrefLanguage" IS 'Preferred Language. Ptr to LANGCD.LangCd';
COMMENT ON COLUMN patient."PrefApptTime" IS 'Preferred appointment time, freetext.';
COMMENT ON COLUMN patient."Postal" IS 'Postal / ZIP code, ptr to CITY.Postal';
COMMENT ON COLUMN patient."Physician" IS 'Treating physician, ptr to PHYSICIA.Physician';
COMMENT ON COLUMN patient."Permenant" IS 'DEPRECATED';
COMMENT ON COLUMN patient."Patient" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN patient."Path" IS 'Patient has a picture? (0=No, 1=Yes)';
COMMENT ON COLUMN patient."PatType" IS 'DEPRECATED';
COMMENT ON COLUMN patient."PartnerPrefix" IS 'Dutch version only, partner name prefix. Freetext.';
COMMENT ON COLUMN patient."PartnerName" IS 'Dutch version only, Partner name.';
COMMENT ON COLUMN patient."PaperChart" IS 'Paper chart? (0=Electronic chart, 1=Paper chart)';
COMMENT ON COLUMN patient."OtherPhone" IS 'Telephone number (other), Format: ###-####';
COMMENT ON COLUMN patient."OtherLocation" IS 'Freetext location of the Other telephone number. ';
COMMENT ON COLUMN patient."OtherLoc" IS 'Obsolete - DO NOT USE';
COMMENT ON COLUMN patient."OtherExt" IS 'Telephone extension (other)';
COMMENT ON COLUMN patient."OtherArea" IS 'Telephone area code (other)';
COMMENT ON COLUMN patient."OrthoSet" IS 'Current Ortho Set, ptr to ORTHOSET.Code';
COMMENT ON COLUMN patient."OpenBalance" IS 'Opening balance for this patient, in dollars. Generally used only for data import.';
COMMENT ON COLUMN patient."Open" IS 'Account open date';
COMMENT ON COLUMN patient."Office5" IS 'Office code 5, ptr to OFFICE.Office';
COMMENT ON COLUMN patient."Office4" IS 'Office code 4, ptr to OFFICE.Office';
COMMENT ON COLUMN patient."Office3" IS 'Office code 3, ptr to OFFICE.Office';
COMMENT ON COLUMN patient."Office2" IS 'Office code 2, ptr to OFFICE.Office';
COMMENT ON COLUMN patient."Office1" IS 'Office code 1, ptr to OFFICE.Office';
COMMENT ON COLUMN patient."NoLocks" IS 'No chart locks? (0=No, 1=Yes)';
COMMENT ON COLUMN patient."MobilePhone" IS 'Telephone number (mobile), Format: ###-####';
COMMENT ON COLUMN patient."MobileArea" IS 'Telephone area code (mobile)';
COMMENT ON COLUMN patient."Middle" IS 'Patient middle name.';
COMMENT ON COLUMN patient."MergedChart" IS 'If this patient was chart merged in the past, the (bad) chart that was merged into this one. Ptr to PATIENT.Chart';
COMMENT ON COLUMN patient."Marital" IS 'Patient marital status (0=Unknown, 1=Single, 2=Married, 3=Divorced, 4=Common-Law, 5=Separated, 6=Widowed, 7=Domestic Partner)';
COMMENT ON COLUMN patient."Location" IS 'Current location of this patient chart. Ptr to LOCATION.Location';
COMMENT ON COLUMN patient."LastVisit" IS 'Date of last appointment.';
COMMENT ON COLUMN patient."LastUpper" IS 'Uppercase copy of patient last name, used for searches.';
COMMENT ON COLUMN patient."LastStatementDate" IS 'Date the last statement was sent.';
COMMENT ON COLUMN patient."LastStatementAmount" IS 'Amount of the last statement, in dollars.';
COMMENT ON COLUMN patient."LastPmtDate" IS 'Date of the last payment.';
COMMENT ON COLUMN patient."LastPaymentAmount" IS 'Amount of the last payment, in dollars.';
COMMENT ON COLUMN patient."LastClaimDate" IS 'Date of last invoice';
COMMENT ON COLUMN patient."LastClaimAmount" IS 'Amount of last invoice, in dollars.';
COMMENT ON COLUMN patient."Last" IS 'Patient last name.';
COMMENT ON COLUMN patient."IsTrustedAudit" IS 'The audit number that is recorded when the Patient SIN is stamped as trusted';
COMMENT ON COLUMN patient."IsStudent" IS 'Is the patient a student? (0=No, 1=Full time, 2=Part time)';
COMMENT ON COLUMN patient."IsPatient" IS 'Is this a patient or a non-patient guarantor? (0=Non-patient guarantor, 1=Patient)';
COMMENT ON COLUMN patient."IsOrtho" IS 'Is this an Ortho patient? (0=No, 1=Yes)';
COMMENT ON COLUMN patient."IsIn" IS 'Patient is checked in? (0=No,1=Yes)';
COMMENT ON COLUMN patient."IsHandicaped" IS 'Patient has special needs / is handicapped? (0=No, 1=Yes)';
COMMENT ON COLUMN patient."IsFreeAccess" IS 'Free access? (0=No, 1=Yes)';
COMMENT ON COLUMN patient."IsEmergency" IS 'Emergency? (0=No, 1=Yes)';
COMMENT ON COLUMN patient."IsChartFixed" IS 'Chart number is fixed? (0=No, 1=Yes)';
COMMENT ON COLUMN patient."Is2ndIdTrustedAudit" IS 'The audit number that is recorded when the Patient SecondIDNumber is stamped as trusted';
COMMENT ON COLUMN patient."Interest" IS 'Charge interest on outstanding balance? (0=No, 1=Yes)';
COMMENT ON COLUMN patient."InsPt" IS 'Obsolete';
COMMENT ON COLUMN patient."InfoNotify" IS 'Address is incorrect? (0=No, 1=Yes)';
COMMENT ON COLUMN patient."Hygienist" IS 'DEPRECATED';
COMMENT ON COLUMN patient."HomePhone" IS 'Telephone number (home), Format: ###-####';
COMMENT ON COLUMN patient."HomeExt" IS 'Patient home phone extension';
COMMENT ON COLUMN patient."HomeArea" IS 'Telephone area code (home)';
COMMENT ON COLUMN patient."Health" IS 'Health unit of the school, either freetext or from SCHOOL.Health';
COMMENT ON COLUMN patient."HasExternalLink" IS 'true if patient has at least 1 non-deleted EXTERNAL_LINK record';
COMMENT ON COLUMN patient."HasCarequality" IS 'true if patient has at least 1 non-deleted CAREQUALITY_PATIENT record';
COMMENT ON COLUMN patient."Flags" IS 'DEPRECATED';
COMMENT ON COLUMN patient."FirstTreatment" IS 'Date of first treatment';
COMMENT ON COLUMN patient."First" IS 'Patient first name.';
COMMENT ON COLUMN patient."FeeOverride" IS 'Bill patient fee (0=N/A, 1=Always, 2=Unless practice override)';
COMMENT ON COLUMN patient."Fee" IS 'Default fee schedule for this patient, ptr to FEESCHED.Fee';
COMMENT ON COLUMN patient."Family" IS 'Family ID. This will be the same as PATIENT.Patient unless this patient is or was formerly a non-patient guarantor (PATIENT.IsPatient=0)';
COMMENT ON COLUMN patient."Extra" IS 'DEPRECATED';
COMMENT ON COLUMN patient."Ethnic" IS 'Ethnic code, Ptr to ETHNIC.Ethnic';
COMMENT ON COLUMN patient."EmergRelation" IS 'Emergency contact relationship to the patient.';
COMMENT ON COLUMN patient."EmergProvince" IS 'Emergency contact province / state, ptr to PROVINCE.Province';
COMMENT ON COLUMN patient."EmergPostal" IS 'Emergency contact postal / ZIP code, ptr to CITY.Postal';
COMMENT ON COLUMN patient."EmergPhone" IS 'Emergency contact telephone number. Format: ###-####';
COMMENT ON COLUMN patient."EmergMiddle" IS 'Emergency contact middle name.';
COMMENT ON COLUMN patient."EmergLast" IS 'Emergency contact last name.';
COMMENT ON COLUMN patient."EmergFirst" IS 'Emergency contact first name.';
COMMENT ON COLUMN patient."EmergExt" IS 'Emergency contact phone extension';
COMMENT ON COLUMN patient."EmergCity" IS 'Emergency contact city, ptr to CITY.City';
COMMENT ON COLUMN patient."EmergArea" IS 'Emergency contact telephone area code';
COMMENT ON COLUMN patient."EmergAltPhone" IS 'Emergency contact alternate telephone number. Format: ###-####';
COMMENT ON COLUMN patient."EmergAltExt" IS 'Emergency contact alternate phone extension';
COMMENT ON COLUMN patient."EmergAltArea" IS 'Emergency contact alternate telephone area code.';
COMMENT ON COLUMN patient."EmergAddressOther" IS 'For USA, represents County. For Dutch, represents Room Number.';
COMMENT ON COLUMN patient."EmergAddress2" IS 'Emergency contact address, line 2';
COMMENT ON COLUMN patient."EmergAddress" IS 'Emergency contact address, line 1';
COMMENT ON COLUMN patient."EmancedMinor" IS 'Patient is an emancipated minor? (0=No, 1=Yes).';
COMMENT ON COLUMN patient."Email" IS 'Email address of the patient';
COMMENT ON COLUMN patient."EDIFlag" IS 'Factoring Co. - Dutch version only. Held Billings? (Both "EDI" and Vektis Invoices) (0=No, 1=Yes)';
COMMENT ON COLUMN patient."Doctor" IS 'DEPRECATED';
COMMENT ON COLUMN patient."DiscGrp" IS 'Patient discount group, ptr to DISCGRP.DiscGrp';
COMMENT ON COLUMN patient."Deleted" IS 'Patient is deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN patient."DateXRayReceived" IS 'Date the X-Ray was received.';
COMMENT ON COLUMN patient."DateXRayExpected" IS 'Date the X-Ray is expected to be received.';
COMMENT ON COLUMN patient."DateOut" IS 'Date the chart was taken out';
COMMENT ON COLUMN patient."CustomText5" IS 'Custom text field 5 value.';
COMMENT ON COLUMN patient."CustomText4" IS 'Custom text field 4 value.';
COMMENT ON COLUMN patient."CustomText3" IS 'Custom text field 3 value.';
COMMENT ON COLUMN patient."CustomText2" IS 'Custom text field 2 value.';
COMMENT ON COLUMN patient."CustomText1" IS 'Custom text field 1 value.';
COMMENT ON COLUMN patient."CustomCode9" IS 'Custom field 9, ptr to CUSTCODE.Code';
COMMENT ON COLUMN patient."CustomCode8" IS 'Custom field 8, ptr to CUSTCODE.Code';
COMMENT ON COLUMN patient."CustomCode7" IS 'Custom field 7, ptr to CUSTCODE.Code';
COMMENT ON COLUMN patient."CustomCode6" IS 'Custom field 6, ptr to CUSTCODE.Code';
COMMENT ON COLUMN patient."CustomCode5" IS 'Custom field 5, ptr to CUSTCODE.Code';
COMMENT ON COLUMN patient."CustomCode4" IS 'Custom field 4, ptr to CUSTCODE.Code';
COMMENT ON COLUMN patient."CustomCode3" IS 'Custom field 3, ptr to CUSTCODE.Code';
COMMENT ON COLUMN patient."CustomCode2" IS 'Custom field 2, ptr to CUSTCODE.Code';
COMMENT ON COLUMN patient."CustomCode10" IS 'Custom field 10, ptr to CUSTCODE.Code';
COMMENT ON COLUMN patient."CustomCode1" IS 'Custom field 1, ptr to CUSTCODE.Code';
COMMENT ON COLUMN patient."Country" IS 'Country, either freetext or from COUNTRY.Country.';
COMMENT ON COLUMN patient."ContactTime" IS 'Time of day that the patient prefers to be contacted at, freetext.';
COMMENT ON COLUMN patient."ContactAt" IS 'Location that the patient prefers to be contacted at? (1=Home, 2=Work, 3=Other, 4=Mobile)';
COMMENT ON COLUMN patient."Close" IS 'Account closed date';
COMMENT ON COLUMN patient."City" IS 'City, ptr to CITY.City';
COMMENT ON COLUMN patient."ChartSuffix" IS 'Internal field used for sorting charts, only used for the Custom Chart Sort method. Used to generate the ChartArea';
COMMENT ON COLUMN patient."ChartSort" IS 'Internal field used for sorting charts, contents depend on chart sort order configuration in Practice options. ';
COMMENT ON COLUMN patient."ChartIn" IS 'Chart in the chart room? (0=No, 1=Yes)';
COMMENT ON COLUMN patient."Chart" IS 'Patient chart number.';
COMMENT ON COLUMN patient."BoxNumber" IS 'Patient assigned box number.';
COMMENT ON COLUMN patient."Birth" IS 'Patient date of birth.';
COMMENT ON COLUMN patient."BankAccount" IS 'Patient bank account number.';
COMMENT ON COLUMN patient."Aux" IS 'DEPRECATED';
COMMENT ON COLUMN patient."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN patient."Assignment" IS 'Patients claims are billed to insurance directly? (0=No, 1=Yes)';
COMMENT ON COLUMN patient."ApptFeesExempt" IS 'Is the patient exempt from being charged appointment cancellation fees? (0=No, 1=Yes)';
COMMENT ON COLUMN patient."AltChart" IS 'Alternate chart ID';
COMMENT ON COLUMN patient."Alert5" IS 'Alert code 5, ptr to ALERT.Alert';
COMMENT ON COLUMN patient."Alert4" IS 'Alert code 4, ptr to ALERT.Alert';
COMMENT ON COLUMN patient."Alert3" IS 'Alert code 3, ptr to ALERT.Alert';
COMMENT ON COLUMN patient."Alert2" IS 'Alert code 2, ptr to ALERT.Alert';
COMMENT ON COLUMN patient."Alert1" IS 'Alert code 1, ptr to ALERT.Alert';
COMMENT ON COLUMN patient."AddressOther" IS 'For USA, represents County. For Dutch, represents Room Number.';
COMMENT ON COLUMN patient."Address2" IS 'Patient address line 2';
COMMENT ON COLUMN patient."Address1" IS 'Patient address line 1';
COMMENT ON COLUMN patient."ActiveDate" IS 'Date this patient record becomes active.';
COMMENT ON COLUMN patient."AccountStatus" IS 'Status of the account, ptr to STATUS.Status';


CREATE  TABLE patient2 (
  "Auto" numeric(10,0) NOT NULL,
  "ChartId" character(15),
  "LastName" character(31),
  "FirstName" character(31),
  "MidName" character(31),
  "Status" numeric(10,0),
  "User" numeric(10,0),
  "PtxPId" numeric(10,0),
  "ToothState" character(32),
  "PermanentState" character(32),
  "PrimaryState" character(32),
  "Date" timestamp without time zone,
  "StationId" numeric(10,0),
  CONSTRAINT patient2_primary PRIMARY KEY ("Auto")
) ;
CREATE INDEX IF NOT EXISTS "PATIENT2_ChartId" ON patient2 USING btree ("ChartId", "LastName", "FirstName") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS "PATIENT2_PtxPId" ON patient2 USING btree ("PtxPId") TABLESPACE pg_default;
COMMENT ON TABLE patient2 IS 'Patient Charting Information';
COMMENT ON COLUMN patient2."User" IS 'ID code of the entry user, ptr to USERS.User';
COMMENT ON COLUMN patient2."ToothState" IS 'Array of current tooth states (0 = Permanent, 1 = Primary, 2 = Permanent Missing, 3 = Primary Missing)';
COMMENT ON COLUMN patient2."Status" IS 'DEPRECATED';
COMMENT ON COLUMN patient2."StationId" IS 'Station ID of the entry user, ptr to STATION.StationId';
COMMENT ON COLUMN patient2."PtxPId" IS 'Link to patient record, ptr to PATIENT.Patient';
COMMENT ON COLUMN patient2."PrimaryState" IS 'Array of additional information regarding primary teeth (0 = Exists, 1 = Extracted, 2 = Impacted, 4 = Planned Extraction)';
COMMENT ON COLUMN patient2."PermanentState" IS 'Array of additional information regarding permanent teeth (0 = Exists, 1 = Extracted, 2 = Impacted, 4 = Planned Extraction)';
COMMENT ON COLUMN patient2."MidName" IS 'Patient middle name, ptr to PATIENT.Middle';
COMMENT ON COLUMN patient2."LastName" IS 'Patient last name, ptr to PATIENT.Last';
COMMENT ON COLUMN patient2."FirstName" IS 'Patient first name, ptr to PATIENT.First';
COMMENT ON COLUMN patient2."Date" IS 'Date the entry was made';
COMMENT ON COLUMN patient2."ChartId" IS 'Chart number of the patient, ptr to PATIENT.Chart';
COMMENT ON COLUMN patient2."Auto" IS 'Primary key, internal ID from sequence. ';


CREATE  TABLE patient_request (
  "Id" numeric(10,0) NOT NULL,
  "axiUmApiLogId" numeric(10,0),
  "ExternalId" character varying(255),
  "CreateDateTime" timestamp without time zone,
  "Patient" numeric(10,0),
  "LastName" character varying(255),
  "FirstName" character varying(255),
  "MiddleName" character varying(255),
  "Birth" timestamp without time zone,
  "Sin" character varying(255),
  "Sex" character varying(255),
  "Race" character varying(255),
  "Ethnicity" character varying(255),
  "Marital" character varying(255),
  "HomePhone" character varying(255),
  "OfficePhone" character varying(255),
  "MobilePhone" character varying(255),
  "Email" character varying(255),
  "Language" character varying(255),
  "StreetAddress" character varying(255),
  "City" character varying(255),
  "Province" character varying(255),
  "Postal" character varying(255),
  "Country" character varying(255),
  "Title" character varying(255),
  "ExternalIdType" character varying(255),
  "Source" character varying(255),
  "AddressOther" character varying(255),
  "FaxPhone" character varying(255),
  CONSTRAINT patient_request_primary PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE patient_request IS '[OBSOLETE] details for a patient that has been requested to be added';
COMMENT ON COLUMN patient_request."axiUmApiLogId" IS 'Id of the AXIUM_API_LOG record that resulted in this entry (if applicable)';
COMMENT ON COLUMN patient_request."Title" IS 'title';
COMMENT ON COLUMN patient_request."StreetAddress" IS 'street address';
COMMENT ON COLUMN patient_request."Source" IS 'The source of the call (vendor id)';
COMMENT ON COLUMN patient_request."Sin" IS 'SSN or SIN';
COMMENT ON COLUMN patient_request."Sex" IS 'sex';
COMMENT ON COLUMN patient_request."Race" IS 'race code';
COMMENT ON COLUMN patient_request."Province" IS 'state or province';
COMMENT ON COLUMN patient_request."Postal" IS 'zip or postal code';
COMMENT ON COLUMN patient_request."Patient" IS 'points to the corresponding PATIENT record created or referenced';
COMMENT ON COLUMN patient_request."OfficePhone" IS 'office phone number';
COMMENT ON COLUMN patient_request."MobilePhone" IS 'mobile phone number';
COMMENT ON COLUMN patient_request."MiddleName" IS 'middle name';
COMMENT ON COLUMN patient_request."Marital" IS 'marital status';
COMMENT ON COLUMN patient_request."LastName" IS 'last name';
COMMENT ON COLUMN patient_request."Language" IS 'preferred languange code';
COMMENT ON COLUMN patient_request."Id" IS 'Primary key, sequence field';
COMMENT ON COLUMN patient_request."HomePhone" IS 'home phone number';
COMMENT ON COLUMN patient_request."FirstName" IS 'first name';
COMMENT ON COLUMN patient_request."FaxPhone" IS 'fax phone number';
COMMENT ON COLUMN patient_request."ExternalIdType" IS 'the type of id in ExternalId (e.g. MRN)';
COMMENT ON COLUMN patient_request."ExternalId" IS 'patient Id in the referring system';
COMMENT ON COLUMN patient_request."Ethnicity" IS 'ethnicity code';
COMMENT ON COLUMN patient_request."Email" IS 'email address';
COMMENT ON COLUMN patient_request."CreateDateTime" IS 'date and time of the request';
COMMENT ON COLUMN patient_request."Country" IS 'country';
COMMENT ON COLUMN patient_request."City" IS 'city';
COMMENT ON COLUMN patient_request."Birth" IS 'date of birth';
COMMENT ON COLUMN patient_request."AddressOther" IS 'county, or other address information';


CREATE  TABLE pattype (
  "PatType" character(6) NOT NULL,
  "Description" character(30),
  "Inactive" numeric(5,0),
  "StartChkRequired" numeric(5,0),
  "RecallTypeLimit" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT pattype_primary PRIMARY KEY ("PatType")
) ;
COMMENT ON TABLE pattype IS 'Patient Type Codes';
COMMENT ON COLUMN pattype."StartChkRequired" IS 'Start check required? (0=No, 1=Yes)';
COMMENT ON COLUMN pattype."RecallTypeLimit" IS 'Enable Recall Type limit to one active recall? (0=No, 1=Yes)';
COMMENT ON COLUMN pattype."PatType" IS 'Primary key, code to identify the patient type.';
COMMENT ON COLUMN pattype."Inactive" IS 'Inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN pattype."Description" IS 'Patient type description';


CREATE  TABLE payment (
  "Payment" character(6) NOT NULL,
  "Description" character(30),
  "PrintDescription" character(30),
  "Bank" character(6),
  "From" numeric(5,0),
  "Deposit" numeric(5,0),
  "DiscountCode" character(6),
  "DiscountPct" numeric,
  "DiscountFull" numeric(5,0),
  "IsEDI" numeric(5,0),
  "Inactive" numeric(5,0),
  CONSTRAINT payment_primary PRIMARY KEY ("Payment")
) ;
COMMENT ON TABLE payment IS 'Payment Codes';
COMMENT ON COLUMN payment."PrintDescription" IS 'Description to print on receipts. ';
COMMENT ON COLUMN payment."Payment" IS 'Primary key, code to identify the payment type.';
COMMENT ON COLUMN payment."IsEDI" IS 'For Dutch version only - is Vektis payment? (0=No, 1=Yes)';
COMMENT ON COLUMN payment."Inactive" IS 'Payment code is inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN payment."From" IS 'Payor that the payment is from? (0=Patient, 1=Insurance Company)';
COMMENT ON COLUMN payment."DiscountPct" IS 'Discount percentage.';
COMMENT ON COLUMN payment."DiscountFull" IS 'Discount full payments? (0=No, 1=Yes)';
COMMENT ON COLUMN payment."DiscountCode" IS 'Adjustment code to use for payment auto-discounts, ptr to ADJUST.Adjust';
COMMENT ON COLUMN payment."Description" IS 'Description of the payment type.';
COMMENT ON COLUMN payment."Deposit" IS 'Affects the daily bank deposit? (0=No, 1=Yes)';
COMMENT ON COLUMN payment."Bank" IS 'Default cash drawer or POS to use for this payment, ptr to BANK.Bank.';


CREATE  TABLE payplan (
  "PlanId" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "Family" numeric(10,0),
  "Type" numeric(5,0),
  "Total" numeric,
  "InitialFee" numeric,
  "InitialDate" timestamp without time zone,
  "Period" numeric(5,0),
  "RegularStart" timestamp without time zone,
  "RegularFee" numeric,
  "RegularCount" numeric(5,0),
  "FinalFee" numeric,
  "FinalDate" timestamp without time zone,
  "Comment" character(100),
  "Status" numeric(5,0),
  "ClosingBalance" numeric,
  "RespId" numeric(10,0),
  "CreationDate" timestamp without time zone,
  "Contract" numeric(10,0),
  "Audit" numeric(10,0),
  "VisitLimit" numeric(5,0),
  "RegularSch" numeric(5,0),
  CONSTRAINT payplan_primary PRIMARY KEY ("PlanId")
) ;
CREATE INDEX IF NOT EXISTS payplan_family ON payplan USING btree ("Family") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS payplan_respid ON payplan USING btree ("RespId") TABLESPACE pg_default;
COMMENT ON TABLE payplan IS 'Payment Plans';
COMMENT ON COLUMN payplan."VisitLimit" IS 'Bill only if patient visit occurred during the billing period? (0=No, 1=Yes)';
COMMENT ON COLUMN payplan."Type" IS 'Plan is for (0=Specific Charges, 1=Outstanding Balance, 2=Orthodontics)';
COMMENT ON COLUMN payplan."Total" IS 'Plan total amount, in dollars.';
COMMENT ON COLUMN payplan."Status" IS 'Payment plan status (0 = Active, 1 = Closed, 2 = Deleted)';
COMMENT ON COLUMN payplan."RespId" IS 'The guarantor of the payment plan. Ptr to PATIENT.Patient';
COMMENT ON COLUMN payplan."RegularStart" IS 'Starting date of the regular payments on the payment plan.';
COMMENT ON COLUMN payplan."RegularSch" IS 'Plan uses a regular payment schedule? (0=No, 1=Yes)';
COMMENT ON COLUMN payplan."RegularFee" IS 'Regular payment amount, in dollars.';
COMMENT ON COLUMN payplan."RegularCount" IS 'Expected number of regular payments. ';
COMMENT ON COLUMN payplan."PlanId" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN payplan."Period" IS 'Payment period (0=Monthly, 1=Quarterly, 2=Semi-Annual).';
COMMENT ON COLUMN payplan."Patient" IS 'Patient that this payment plan is for, ptr to PATIENT.Patient';
COMMENT ON COLUMN payplan."InitialFee" IS 'Down payment amount, in dollars.';
COMMENT ON COLUMN payplan."InitialDate" IS 'Down payment date.';
COMMENT ON COLUMN payplan."FinalFee" IS 'Final payment amount, in dollars. ';
COMMENT ON COLUMN payplan."FinalDate" IS 'Expected date of the final payment.';
COMMENT ON COLUMN payplan."Family" IS 'Family ID, ptr to PATIENT.Family';
COMMENT ON COLUMN payplan."CreationDate" IS 'Date that the payment plan was created.';
COMMENT ON COLUMN payplan."Contract" IS 'Contract for this payment plan, ptr to CONTRACT.Contract';
COMMENT ON COLUMN payplan."Comment" IS 'Free text area to type notes on the payment plan.';
COMMENT ON COLUMN payplan."ClosingBalance" IS 'Closing balance amount, in dollars.';
COMMENT ON COLUMN payplan."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE pcaccess (
  "PCView" numeric(10,0) NOT NULL,
  "RecType" numeric(5,0) NOT NULL,
  "SLevel" numeric(10,0) NOT NULL,
  "Access" numeric(5,0),
  CONSTRAINT pcaccess_primary PRIMARY KEY ("PCView", "RecType", "SLevel")
) ;
CREATE INDEX IF NOT EXISTS pcaccess_slevelkey ON pcaccess USING btree ("PCView", "SLevel") TABLESPACE pg_default;
COMMENT ON TABLE pcaccess IS 'Patient Care View Item Access';
COMMENT ON COLUMN pcaccess."SLevel" IS 'Primary key component, security level that these rights are for, ptr to SLEVEL.SLevel.';
COMMENT ON COLUMN pcaccess."RecType" IS 'Primary key component, record Type [1..~35]';
COMMENT ON COLUMN pcaccess."PCView" IS 'Primary key component, patient care view that the item is in, ptr to PCVIEW.PCView.';
COMMENT ON COLUMN pcaccess."Access" IS 'Allow access for this security level? (0 = No, 1 = Yes) ';


CREATE  TABLE pcvacc (
  "PCView" numeric(10,0) NOT NULL,
  "SLevel" numeric(10,0) NOT NULL,
  "Access" numeric(5,0),
  CONSTRAINT pcvacc_primary PRIMARY KEY ("PCView", "SLevel")
) ;
COMMENT ON TABLE pcvacc IS 'Patient Care View Access';
COMMENT ON COLUMN pcvacc."SLevel" IS 'Primary key component, security level that these rights are for, ptr to SLEVEL.SLevel.';
COMMENT ON COLUMN pcvacc."PCView" IS 'Primary key component, ID of the patient care view, ptr to PCVIEW.PCView.';
COMMENT ON COLUMN pcvacc."Access" IS 'Allow access for this security level? (0 = No, 1 = Yes) ';


CREATE  TABLE pcview (
  "PCView" numeric(10,0) NOT NULL,
  "Type" numeric(5,0),
  "Description" character varying(30),
  CONSTRAINT pcview_primary PRIMARY KEY ("PCView")
) ;
COMMENT ON TABLE pcview IS 'Patient Care Views';
COMMENT ON COLUMN pcview."Type" IS 'Type? (0=All, 1=User defined)';
COMMENT ON COLUMN pcview."PCView" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN pcview."Description" IS 'User-defined name for the view if Type=1, otherwise “All” if Type=0.';


CREATE  TABLE pcvitem (
  "PCView" numeric(10,0) NOT NULL,
  "RecType" numeric(5,0) NOT NULL,
  CONSTRAINT pcvitem_primary PRIMARY KEY ("PCView", "RecType")
) ;
COMMENT ON TABLE pcvitem IS 'Patient Care View Items';
COMMENT ON COLUMN pcvitem."RecType" IS 'Primary key component, record Type [1..~35]';
COMMENT ON COLUMN pcvitem."PCView" IS 'Primary key component, patient care view that this item is in, ptr to PCVIEW.PCView.';


CREATE  TABLE percdhis (
  "PerCdHis" numeric(10,0) NOT NULL,
  "PerCondDis" numeric(10,0),
  "ProdType" character(1),
  "Provider" character(10),
  "PerCond" character(6),
  "Section" numeric(5,0) NOT NULL,
  "Order" numeric(5,0),
  "Color" numeric(10,0),
  "Chart" numeric(5,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "SiteRestricted" numeric(5,0),
  CONSTRAINT percdhis_primary PRIMARY KEY ("PerCdHis")
) ;
CREATE INDEX IF NOT EXISTS percdhis_perconddis ON percdhis USING btree ("PerCondDis") TABLESPACE pg_default;
COMMENT ON TABLE percdhis IS 'Audit history for PERCODIS table';
COMMENT ON COLUMN percdhis."SiteRestricted" IS 'User can only chart on defined sites? (0 = No, 1 = Yes)';
COMMENT ON COLUMN percdhis."Section" IS 'Section (0=Buccal, 1=Lingual, 2=Graphics on teeth)';
COMMENT ON COLUMN percdhis."Provider" IS 'ID code of the provider, used if this perio condition display is for a specific provider. Ptr to PRODUCER.Producer ';
COMMENT ON COLUMN percdhis."ProdType" IS 'Provider type, used if restricted to a sepcific provider type. Ptr to PRODTYPE.Code';
COMMENT ON COLUMN percdhis."PerCondDis" IS 'Perio condition for provider type that this history is for, ptr to PERCODIS.PerCondDis.';
COMMENT ON COLUMN percdhis."PerCond" IS 'Default display condition, ptr to PERCOND.PerCond';
COMMENT ON COLUMN percdhis."PerCdHis" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN percdhis."Order" IS 'Order# displayed on within section [0..15]';
COMMENT ON COLUMN percdhis."Deleted" IS 'Record is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN percdhis."Color" IS 'Numeric value of the color in which to display this item, decimal representation of RGB value. ';
COMMENT ON COLUMN percdhis."Chart" IS 'Chart? (0 = No, 1 = Yes, 2=Yes with auto-advance)';
COMMENT ON COLUMN percdhis."Audit" IS 'Audit record, ptr to AUDITHIS.Audit';


CREATE  TABLE percodis (
  "PerCondDis" numeric(10,0) NOT NULL,
  "ProdType" character(1),
  "Provider" character(10),
  "PerCond" character(6),
  "Section" numeric(5,0) NOT NULL,
  "Order" numeric(5,0),
  "Color" numeric(10,0),
  "Chart" numeric(5,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "SiteRestricted" numeric(5,0),
  CONSTRAINT percodis_primary PRIMARY KEY ("PerCondDis")
) ;
CREATE INDEX IF NOT EXISTS percodis_provider ON percodis USING btree ("ProdType", "Provider", "PerCond", "Section") TABLESPACE pg_default;
COMMENT ON TABLE percodis IS 'Charting Conditions displayed per provider type';
COMMENT ON COLUMN percodis."SiteRestricted" IS 'User can only chart on defined sites? (0 = No, 1 = Yes)';
COMMENT ON COLUMN percodis."Section" IS 'Section (0=Buccal, 1=Lingual, 2=Graphics on teeth)';
COMMENT ON COLUMN percodis."Provider" IS 'ID code of the provider, used if this perio condition display is for a specific provider. Ptr to PRODUCER.Producer ';
COMMENT ON COLUMN percodis."ProdType" IS 'Provider type, used if restricted to a sepcific provider type. Ptr to PRODTYPE.Code';
COMMENT ON COLUMN percodis."PerCondDis" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN percodis."PerCond" IS 'Default display condition, ptr to PERCOND.PerCond';
COMMENT ON COLUMN percodis."Order" IS 'Order# displayed on within section [0..15]';
COMMENT ON COLUMN percodis."Deleted" IS 'Record is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN percodis."Color" IS 'Numeric value of the color in which to display this item, decimal representation of RGB value. ';
COMMENT ON COLUMN percodis."Chart" IS 'Chart? (0 = No, 1 = Yes, 2=Yes with auto-advance)';
COMMENT ON COLUMN percodis."Audit" IS 'Audit record, ptr to AUDITHIS.Audit';


CREATE  TABLE percohis (
  "PerCoHis" numeric(10,0) NOT NULL,
  "PerCond" character(6) NOT NULL,
  "Description" character varying(30),
  "ShortDesc" character(10),
  "AnsType" numeric(5,0),
  "Color" numeric(10,0),
  "DisplayType" numeric(5,0),
  "ChartType" numeric(5,0),
  "ChartMissing" numeric(5,0),
  "CondType" numeric(5,0),
  "Status" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT percohis_primary PRIMARY KEY ("PerCoHis")
) ;
CREATE INDEX IF NOT EXISTS percohis_percond ON percohis USING btree ("PerCond") TABLESPACE pg_default;
COMMENT ON TABLE percohis IS 'Audit history for PERCOND table';
COMMENT ON COLUMN percohis."Status" IS 'Status (0=Active, 1=Deleted, 2=Inactive)';
COMMENT ON COLUMN percohis."ShortDesc" IS 'Abbreviated description of the perio condition for Perio Main window';
COMMENT ON COLUMN percohis."PerCond" IS 'Perio conditions';
COMMENT ON COLUMN percohis."PerCoHis" IS 'Id code to identify this percohis record';
COMMENT ON COLUMN percohis."DisplayType" IS 'Display type (0=Line graph, 1=Bar graph) only for AnsType [0, 2]';
COMMENT ON COLUMN percohis."Description" IS 'Description of the perio condition';
COMMENT ON COLUMN percohis."CondType" IS 'Condition type (0=Other, 1=FGM, 2=Pocket, 3=Attachment, 4=Bleeding, 5=Supperation, 6=Calculus, 7=Overhangs)';
COMMENT ON COLUMN percohis."Color" IS 'Default color to display as';
COMMENT ON COLUMN percohis."ChartType" IS 'Chart Type (0=Buccal/Lingual, 1=One per tooth)';
COMMENT ON COLUMN percohis."ChartMissing" IS 'Chart missing? (0 = No, 1 = Yes)';
COMMENT ON COLUMN percohis."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN percohis."AnsType" IS 'Answer type (0=Number, 1=Alpha, 2=Yes/No)';


CREATE  TABLE percond (
  "PerCond" character(6) NOT NULL,
  "Description" character varying(30),
  "ShortDesc" character(10),
  "AnsType" numeric(5,0),
  "Color" numeric(10,0),
  "DisplayType" numeric(5,0),
  "ChartType" numeric(5,0),
  "ChartMissing" numeric(5,0),
  "CondType" numeric(5,0),
  "Status" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT percond_primary PRIMARY KEY ("PerCond")
) ;
COMMENT ON TABLE percond IS 'Table of Perio Conditions';
COMMENT ON COLUMN percond."Status" IS 'Status (0=Active, 1=Deleted, 2=Inactive)';
COMMENT ON COLUMN percond."ShortDesc" IS 'Abbreviated description of the perio condition for Perio Main window';
COMMENT ON COLUMN percond."PerCond" IS 'Perio conditions';
COMMENT ON COLUMN percond."DisplayType" IS 'Display type (0=Line graph, 1=Bar graph) only for AnsType [0, 2]';
COMMENT ON COLUMN percond."Description" IS 'Description of the perio condition';
COMMENT ON COLUMN percond."CondType" IS 'Condition type (0=Other, 1=FGM, 2=Pocket, 3=Attachment, 4=Bleeding, 5=Supperation, 6=Calculus, 7=Overhangs)';
COMMENT ON COLUMN percond."Color" IS 'Default color to display as';
COMMENT ON COLUMN percond."ChartType" IS 'Chart Type (0=Buccal/Lingual, 1=One per tooth)';
COMMENT ON COLUMN percond."ChartMissing" IS 'Chart missing? (0 = No, 1 = Yes)';
COMMENT ON COLUMN percond."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN percond."AnsType" IS 'Answer type (0=Number, 1=Alpha, 2=Yes/No)';


CREATE  TABLE perexam (
  "PerExam" character(6) NOT NULL,
  "Description" character varying(30),
  "Inactive" numeric(5,0),
  CONSTRAINT perexam_primary PRIMARY KEY ("PerExam")
) ;
COMMENT ON TABLE perexam IS 'Record of Perio Examination Types';
COMMENT ON COLUMN perexam."PerExam" IS 'Unique ID code to identify the perio examination type';
COMMENT ON COLUMN perexam."Inactive" IS 'Record is inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN perexam."Description" IS 'Description (name) of the perio examination type ';


CREATE  TABLE permeit (
  "PerMeth" numeric(10,0) NOT NULL,
  "Order" numeric(5,0) NOT NULL,
  "Cell" numeric(5,0),
  "LeftRight" numeric(5,0),
  CONSTRAINT permeit_primary PRIMARY KEY ("PerMeth", "Order")
) ;
COMMENT ON TABLE permeit IS 'Method of auto-advancing for perio charting for a specific cell';
COMMENT ON COLUMN permeit."PerMeth" IS 'Primary key component, charting method sub-item / definition, ptr to PERMETH.PerMeth';
COMMENT ON COLUMN permeit."Order" IS 'Primary key component, tooth/site position [1..64]';
COMMENT ON COLUMN permeit."LeftRight" IS 'Direction within cell (0=Right to left, 1=Left to right)';
COMMENT ON COLUMN permeit."Cell" IS 'Numeric value to represent the cell';


CREATE  TABLE permeth (
  "PerMeth" numeric(10,0) NOT NULL,
  "Description" character varying(30),
  CONSTRAINT permeth_primary PRIMARY KEY ("PerMeth")
) ;
COMMENT ON TABLE permeth IS 'Perio methods';
COMMENT ON COLUMN permeth."PerMeth" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN permeth."Description" IS 'Description of the perio method.';


CREATE  TABLE peropts (
  "PerOpts" numeric(10,0) NOT NULL,
  "ProdType" character(1),
  "Provider" character(10),
  "ShowGraphics" numeric(5,0),
  "ShowBorders" numeric(5,0),
  "CalculateScores" numeric(5,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "RequireExam" numeric(5,0),
  "ApprovalMethod" numeric(5,0),
  "CalculateAttach" numeric(5,0),
  "NewExamCopy" numeric(5,0),
  CONSTRAINT peropts_primary PRIMARY KEY ("PerOpts")
) ;
CREATE INDEX IF NOT EXISTS peropts_provider ON peropts USING btree ("ProdType", "Provider") TABLESPACE pg_default;
COMMENT ON TABLE peropts IS 'Perio options';
COMMENT ON COLUMN peropts."ShowGraphics" IS 'Show graphics? (0 = No, 1 = Yes)';
COMMENT ON COLUMN peropts."ShowBorders" IS 'Show borders? (0 = No, 1 = Yes)';
COMMENT ON COLUMN peropts."RequireExam" IS 'Require user to identify exam type? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN peropts."Provider" IS 'If this chart option is for a specific provider, ptr to PRODUCER.Producer.';
COMMENT ON COLUMN peropts."ProdType" IS 'Provider type to which this charting option applies, ptr to PRODUCER.ProdType';
COMMENT ON COLUMN peropts."PerOpts" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN peropts."NewExamCopy" IS '0 = No (default), 1 = Yes/Prompt';
COMMENT ON COLUMN peropts."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN peropts."CalculateScores" IS 'Auto-calculate PSR/DPSI? ( 0 = No, 1 = Yes)';
COMMENT ON COLUMN peropts."CalculateAttach" IS '0 = Always on entry, 1 = Only if both POCKETS and FGM have values, 2 = Never ';
COMMENT ON COLUMN peropts."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN peropts."ApprovalMethod" IS '0 = No : no approvals during entry, 1 = Yes : get approval during entry (4.3 behaviour), 2 = Optional (prompt user during entry)';


CREATE  TABLE perprog (
  "PerProg" character(6) NOT NULL,
  "Description" character varying(30),
  "Status" numeric(5,0),
  CONSTRAINT perprog_primary PRIMARY KEY ("PerProg")
) ;
COMMENT ON TABLE perprog IS 'Perio prognosis codes';
COMMENT ON COLUMN perprog."Status" IS 'Status? (0=Active, 1=Deleted, 2=Inactive)';
COMMENT ON COLUMN perprog."PerProg" IS 'ID code to identify the perio prognosis. ';
COMMENT ON COLUMN perprog."Description" IS 'Description of the perio prognosis. ';


CREATE  TABLE persdhis (
  "PerSdHis" numeric(10,0) NOT NULL,
  "PerSummDis" numeric(10,0),
  "ProdType" character(1),
  "Provider" character(10),
  "PerSumm" character(6) NOT NULL,
  "Order" numeric(5,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT persdhis_primary PRIMARY KEY ("PerSdHis")
) ;
CREATE INDEX IF NOT EXISTS persdhis_persummdis ON persdhis USING btree ("PerSummDis") TABLESPACE pg_default;
COMMENT ON TABLE persdhis IS 'Audit history for PERSUDIS table';
COMMENT ON COLUMN persdhis."Provider" IS 'ID code of the provider if for a specific provider, ptr to PRODUCER.Producer';
COMMENT ON COLUMN persdhis."ProdType" IS 'Provider type, ptr to PRODTYPE.Code';
COMMENT ON COLUMN persdhis."PerSummDis" IS 'Perio summary display that this history is for, ptr to PERSUDIS.PerSummDis.';
COMMENT ON COLUMN persdhis."PerSumm" IS 'ID code of the perio summary/statistic, ptr to PERSUMM.PerSumm';
COMMENT ON COLUMN persdhis."PerSdHis" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN persdhis."Order" IS 'Order displayed in summary list';
COMMENT ON COLUMN persdhis."Deleted" IS 'Record is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN persdhis."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE persite (
  "PerCond" character(6) NOT NULL,
  "Site" numeric(5,0) NOT NULL,
  "Facial1" numeric(5,0),
  "Facial2" numeric(5,0),
  "Facial3" numeric(5,0),
  "Lingual1" numeric(5,0),
  "Lingual2" numeric(5,0),
  "Lingual3" numeric(5,0),
  "Arch" numeric(5,0) NOT NULL,
  CONSTRAINT persite_primary PRIMARY KEY ("PerCond", "Site", "Arch")
) ;
COMMENT ON TABLE persite IS 'Sites conditions are charted in the mouth';
COMMENT ON COLUMN persite."Site" IS 'Primary key component, site 1-8 (site 1 = tooth 1, 16, 17, 32)';
COMMENT ON COLUMN persite."PerCond" IS 'Primary key component, perio condition charted for this site. Ptr to PERCOND.PerCond.';
COMMENT ON COLUMN persite."Lingual3" IS '0 if ChartType = 1';
COMMENT ON COLUMN persite."Lingual2" IS '0 if ChartType = 1';
COMMENT ON COLUMN persite."Lingual1" IS 'Second checkbox for the site (1 thru 8) the point on the site is charted? (1 = yes, 0 = No)';
COMMENT ON COLUMN persite."Facial3" IS '0 if ChartType = 1';
COMMENT ON COLUMN persite."Facial2" IS '0 if ChartType = 1';
COMMENT ON COLUMN persite."Facial1" IS 'First checkbox for the site (1 thru 8) the point on the site is charted? (1 = yes, 0 = No)';
COMMENT ON COLUMN persite."Arch" IS 'Primary key component, arch (0 = Maxillary, 1 = Mandibular)';


CREATE  TABLE persudis (
  "PerSummDis" numeric(10,0) NOT NULL,
  "ProdType" character(1),
  "Provider" character(10),
  "PerSumm" character(6) NOT NULL,
  "Order" numeric(5,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT persudis_primary PRIMARY KEY ("PerSummDis")
) ;
CREATE INDEX IF NOT EXISTS persudis_provider ON persudis USING btree ("ProdType", "Provider", "PerSumm") TABLESPACE pg_default;
COMMENT ON TABLE persudis IS 'Summary/Stats displayed per provider type';
COMMENT ON COLUMN persudis."Provider" IS 'ID code of the provider if for a specific provider, ptr to PRODUCER.Producer';
COMMENT ON COLUMN persudis."ProdType" IS 'Provider type, ptr to PRODTYPE.Code';
COMMENT ON COLUMN persudis."PerSummDis" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN persudis."PerSumm" IS 'ID code of the perio summary/statistic, ptr to PERSUMM.PerSumm';
COMMENT ON COLUMN persudis."Order" IS 'Order displayed in summary list';
COMMENT ON COLUMN persudis."Deleted" IS 'Record is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN persudis."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE persumm (
  "PerSumm" character(6) NOT NULL,
  "Description" character varying(30),
  "FunctionName" character varying(50),
  CONSTRAINT persumm_primary PRIMARY KEY ("PerSumm")
) ;
COMMENT ON TABLE persumm IS 'Perio Summaries/Statistics';
COMMENT ON COLUMN persumm."PerSumm" IS 'ID code to identify this perio summary';
COMMENT ON COLUMN persumm."FunctionName" IS 'Oracle function to calculate value';
COMMENT ON COLUMN persumm."Description" IS 'Description of the perio summary';


CREATE  TABLE pertype (
  "PerType" character(6) NOT NULL,
  "Description" character varying(30),
  "Status" numeric(5,0),
  CONSTRAINT pertype_primary PRIMARY KEY ("PerType")
) ;
COMMENT ON TABLE pertype IS 'Perio Type Codes';
COMMENT ON COLUMN pertype."Status" IS 'Status (0=Active, 1=Deleted, 2=Inactive)';
COMMENT ON COLUMN pertype."PerType" IS 'ID code to identify the perio type. ';
COMMENT ON COLUMN pertype."Description" IS 'Description of the perio type.';


CREATE  TABLE perval (
  "PerCond" character(6) NOT NULL,
  "TextValue" character(2) NOT NULL,
  "Value" numeric,
  "Description" character varying(30),
  "Alert" numeric(5,0),
  "KeyValue" character(1),
  "ShiftKey" numeric(5,0),
  "JumpKey" numeric(5,0),
  CONSTRAINT perval_primary PRIMARY KEY ("PerCond", "TextValue")
) ;
COMMENT ON TABLE perval IS 'Perio Condition Values';
COMMENT ON COLUMN perval."Value" IS 'Numeric value';
COMMENT ON COLUMN perval."TextValue" IS 'Primary key component, text to represent the value (Like B for Yes/No, or 4 for Number)';
COMMENT ON COLUMN perval."ShiftKey" IS 'Shift key? (0 = None, 1=Ctrl, 2=Alt)';
COMMENT ON COLUMN perval."PerCond" IS 'Primary key component, perio condition that the value is for. Ptr to PERCOND.PerCond.';
COMMENT ON COLUMN perval."KeyValue" IS 'Value of the keyboard entry';
COMMENT ON COLUMN perval."JumpKey" IS 'Jump key? (0 = No, 1 = Yes)';
COMMENT ON COLUMN perval."Description" IS 'Optional description of the perio value.';
COMMENT ON COLUMN perval."Alert" IS 'Will alert be entered on tooth if value entered? (0 = No, 1 = Yes) ';


CREATE  TABLE pform (
  "Patient" numeric(10,0) NOT NULL,
  "FormCode" character(6) NOT NULL,
  "Date" timestamp without time zone,
  "User" numeric(10,0),
  "PForm" numeric(10,0) NOT NULL,
  "Description" character varying(30),
  "OwnerType" numeric(5,0),
  "OwnerId" numeric(10,0),
  "CreatedDate" timestamp without time zone,
  "Approved" numeric(5,0),
  "LastAppUser" numeric(10,0),
  "LastAppDate" timestamp without time zone,
  "Inactive" numeric(5,0),
  "InactiveAppUser" numeric(10,0),
  "InactiveAppDate" timestamp without time zone,
  "InactiveReason" character varying(50),
  "FStatus" character(6),
  "AssignedUser" numeric(10,0),
  "AssignedUGroup" character(6),
  "LastStartDateTime" timestamp without time zone,
  CONSTRAINT pform_primary PRIMARY KEY ("FormCode", "Patient", "PForm")
) ;
CREATE INDEX IF NOT EXISTS pform_assigneduser ON pform USING btree ("AssignedUser", "AssignedUGroup") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS pform_owner ON pform USING btree ("OwnerType", "OwnerId") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS pform_patient ON pform USING btree ("Patient") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS pform_pformkey ON pform USING btree ("PForm") TABLESPACE pg_default;
COMMENT ON TABLE pform IS 'Patient EPR / ORTHO Form Record';
COMMENT ON COLUMN pform."User" IS 'Entry User ID, ptr to USERS.User or IUSER.iUser';
COMMENT ON COLUMN pform."Patient" IS 'Primary key component, patient that this form is for. Ptr to PATIENT.Patient';
COMMENT ON COLUMN pform."PForm" IS 'Primary key component, internal ID from sequence.';
COMMENT ON COLUMN pform."OwnerType" IS 'Form owner type (0 = EPR window, 1 = Lab Orders, 2 = Referrals, 3 = Patient Producer, 4 = TREATME2.Auto, 5= User, 6=Clinical Note)';
COMMENT ON COLUMN pform."OwnerId" IS 'ID code of the owner (if OwnerType=0 then OwnerId=PATIENT.Patient, if OwnerType=4 then OwnerId=TREATME2.Auto, if OwnerType=6 then OwnerId=NOTES2.Auto)';
COMMENT ON COLUMN pform."LastStartDateTime" IS 'Date/Time of last access date/time for the session';
COMMENT ON COLUMN pform."LastAppUser" IS 'The last user to approve answers on this form, ptr to USERS.User';
COMMENT ON COLUMN pform."LastAppDate" IS 'The last date answers on this form were approved  ';
COMMENT ON COLUMN pform."InactiveReason" IS 'If Inactive = 1, a brief reason why';
COMMENT ON COLUMN pform."InactiveAppUser" IS 'If Inactive = 1, then the USERS.User who approved suspension';
COMMENT ON COLUMN pform."InactiveAppDate" IS 'If Inactive = 1, then the date approved making it suspended';
COMMENT ON COLUMN pform."Inactive" IS 'Inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN pform."FormCode" IS 'Primary key component, form code of this form. Ptr to FORM.Code';
COMMENT ON COLUMN pform."FStatus" IS 'The current status of the form, ptr to FSTATUS.FStatus';
COMMENT ON COLUMN pform."Description" IS 'Optional description if Multiple forms supported';
COMMENT ON COLUMN pform."Date" IS 'Date of entry';
COMMENT ON COLUMN pform."CreatedDate" IS 'Date form created';
COMMENT ON COLUMN pform."AssignedUser" IS 'The user the form was assigned to, ptr to USERS.User';
COMMENT ON COLUMN pform."AssignedUGroup" IS 'The user group the form was assigned to, ptr to UGROUP.UGroup';
COMMENT ON COLUMN pform."Approved" IS 'Is the current form fully approved (1 = yes, 0 = no) ';


CREATE  TABLE pform_deleted (
  "Patient" numeric(10,0),
  "FormCode" character(6),
  "Date" timestamp without time zone,
  "User" numeric(10,0),
  "PForm" numeric(10,0) NOT NULL,
  "Description" character varying(30),
  "OwnerType" numeric(5,0),
  "OwnerId" numeric(10,0),
  "CreatedDate" timestamp without time zone,
  "Approved" numeric(5,0),
  "LastAppUser" numeric(10,0),
  "LastAppDate" timestamp without time zone,
  "Inactive" numeric(5,0),
  "InactiveAppUser" numeric(10,0),
  "InactiveAppDate" timestamp without time zone,
  "InactiveReason" character varying(50),
  "FStatus" character(6),
  "AssignedUser" numeric(10,0),
  "AssignedUGroup" character(6),
  "LastStartDateTime" timestamp without time zone
) ;
COMMENT ON TABLE pform_deleted IS 'Deleted Patient EPR/ORTHO Form Records';
COMMENT ON COLUMN pform_deleted."User" IS 'Entry User ID, ptr to USERS.User or IUSER.iUser';
COMMENT ON COLUMN pform_deleted."Patient" IS 'Primary key component, patient that this form is for. Ptr to PATIENT.Patient';
COMMENT ON COLUMN pform_deleted."PForm" IS 'Primary key component, internal ID from sequence.';
COMMENT ON COLUMN pform_deleted."OwnerType" IS 'Form owner type (0 = EPR window, 1 = Lab Orders, 2 = Referrals, 3 = Patient Producer, 4 = TREATME2.Auto, 5= User, 6=Clinical Note)';
COMMENT ON COLUMN pform_deleted."OwnerId" IS 'ID code of the owner (if OwnerType=0 then OwnerId=PATIENT.Patient, if OwnerType=4 then OwnerId=TREATME2.Auto, if OwnerType=6 then OwnerId=NOTES2.Auto)';
COMMENT ON COLUMN pform_deleted."LastStartDateTime" IS 'Date/Time of last access date/time for the session';
COMMENT ON COLUMN pform_deleted."LastAppUser" IS 'The last user to approve answers on this form, ptr to USERS.User';
COMMENT ON COLUMN pform_deleted."LastAppDate" IS 'The last date answers on this form were approved ';
COMMENT ON COLUMN pform_deleted."InactiveReason" IS 'If Inactive = 1, a brief reason why';
COMMENT ON COLUMN pform_deleted."InactiveAppUser" IS 'If Inactive = 1, then the USERS.User who approved suspension';
COMMENT ON COLUMN pform_deleted."InactiveAppDate" IS 'If Inactive = 1, then the date approved making it suspended';
COMMENT ON COLUMN pform_deleted."Inactive" IS 'Inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN pform_deleted."FormCode" IS 'Primary key component, form code of this form. Ptr to FORM.Code';
COMMENT ON COLUMN pform_deleted."FStatus" IS 'The current status of the form, ptr to FSTATUS.FStatus';
COMMENT ON COLUMN pform_deleted."Description" IS 'Optional description if Multiple forms supported';
COMMENT ON COLUMN pform_deleted."Date" IS 'Date of entry';
COMMENT ON COLUMN pform_deleted."CreatedDate" IS 'Date form created';
COMMENT ON COLUMN pform_deleted."AssignedUser" IS 'The user the form was assigned to, ptr to USERS.User';
COMMENT ON COLUMN pform_deleted."AssignedUGroup" IS 'The user group the form was assigned to, ptr to UGROUP.UGroup';
COMMENT ON COLUMN pform_deleted."Approved" IS 'Is the current form fully approved (1 = yes, 0 = no)';


CREATE  TABLE pformevt (
  "PFormEvt" numeric(10,0) NOT NULL,
  "PForm" numeric(10,0),
  "Audit" numeric(10,0),
  "FStatus" character(6),
  "AssignedUser" numeric(10,0),
  "AssignedUGroup" character(6),
  "Comment" character varying(4000),
  CONSTRAINT pformevt_primary PRIMARY KEY ("PFormEvt")
) ;
CREATE INDEX IF NOT EXISTS pformevt_assigneduser ON pformevt USING btree ("AssignedUser") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS pformevt_pform ON pformevt USING btree ("PForm") TABLESPACE pg_default;
COMMENT ON TABLE pformevt IS 'Form Action Records';
COMMENT ON COLUMN pformevt."PFormEvt" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN pformevt."PForm" IS 'Form that this action occurred on, ptr to PFORM.PForm';
COMMENT ON COLUMN pformevt."FStatus" IS 'Status that the form was set to for this action, ptr to FSTATUS.Fstatus';
COMMENT ON COLUMN pformevt."Comment" IS 'Comment entered for the action';
COMMENT ON COLUMN pformevt."Audit" IS 'Audit record of assignment for this action, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN pformevt."AssignedUser" IS 'The user the form was assigned to, ptr to USERS.User';
COMMENT ON COLUMN pformevt."AssignedUGroup" IS 'The Messenger group the form was assigned to, ptr to UGROUP.Ugroup';


CREATE  TABLE pformevt_deleted (
  "PFormEvt" numeric(10,0),
  "PForm" numeric(10,0),
  "Audit" numeric(10,0),
  "FStatus" character(6),
  "AssignedUser" numeric(10,0),
  "AssignedUGroup" character(6),
  "Comment" character varying(4000)
) ;
COMMENT ON TABLE pformevt_deleted IS 'Deleted Form Action Records';
COMMENT ON COLUMN pformevt_deleted."PFormEvt" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN pformevt_deleted."PForm" IS 'Form that this action occurred on, ptr to PFORM.PForm';
COMMENT ON COLUMN pformevt_deleted."FStatus" IS 'Status that the form was set to for this action, ptr to FSTATUS.Fstatus';
COMMENT ON COLUMN pformevt_deleted."Comment" IS 'Comment entered for the action';
COMMENT ON COLUMN pformevt_deleted."Audit" IS 'Audit record of assignment for this action, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN pformevt_deleted."AssignedUser" IS 'The user the form was assigned to, ptr to USERS.User';
COMMENT ON COLUMN pformevt_deleted."AssignedUGroup" IS 'The Messenger group the form was assigned to, ptr to UGROUP.Ugroup';


CREATE  TABLE pgroup (
  "PGroup" character(6) NOT NULL,
  "Description" character(30),
  "Inactive" numeric(5,0),
  CONSTRAINT pgroup_primary PRIMARY KEY ("PGroup")
) ;
COMMENT ON TABLE pgroup IS 'Provider Groups';
COMMENT ON COLUMN pgroup."PGroup" IS 'Primary key, code to identify the provider/student group';
COMMENT ON COLUMN pgroup."Inactive" IS 'Is the code inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN pgroup."Description" IS 'Description of the group.';


CREATE  TABLE pharmacy (
  "Pharmacy" character varying(50) NOT NULL,
  "Address1" character varying(30),
  "Address2" character varying(30),
  "City" character(24),
  "Province" character(6),
  "Postal" character(15),
  "Area" character varying(4),
  "Phone" character varying(8),
  "Note" character varying(4000),
  "Inactive" numeric(5,0),
  "AddressOther" character(15),
  "FaxArea" character(4),
  "FaxPhone" character(8),
  "DisplayDesc" character varying(50),
  CONSTRAINT pharmacy_primary PRIMARY KEY ("Pharmacy")
) ;
COMMENT ON TABLE pharmacy IS 'Pharmacies that a prescription can be phoned in to';
COMMENT ON COLUMN pharmacy."Province" IS 'State or Province';
COMMENT ON COLUMN pharmacy."Postal" IS 'Postal / Zip code';
COMMENT ON COLUMN pharmacy."Phone" IS 'Pharmacy phone number';
COMMENT ON COLUMN pharmacy."Pharmacy" IS 'Name of the pharmacy';
COMMENT ON COLUMN pharmacy."Note" IS 'Note about the pharmacy';
COMMENT ON COLUMN pharmacy."Inactive" IS 'Code is inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN pharmacy."FaxPhone" IS 'Fax number of the pharmacy ';
COMMENT ON COLUMN pharmacy."FaxArea" IS 'Area code for fax number of the pharmacy ';
COMMENT ON COLUMN pharmacy."DisplayDesc" IS 'Display field to show on printouts';
COMMENT ON COLUMN pharmacy."City" IS 'City';
COMMENT ON COLUMN pharmacy."Area" IS 'Pharmacy area code';
COMMENT ON COLUMN pharmacy."AddressOther" IS 'Address Line 2';
COMMENT ON COLUMN pharmacy."Address2" IS 'Address line 2 of the pharmacy';
COMMENT ON COLUMN pharmacy."Address1" IS 'Address line 1 of the pharmacy';


CREATE  TABLE physhis (
  "Id" numeric(10,0) NOT NULL,
  "Physician" numeric(10,0),
  "Last" character(30),
  "First" character(30),
  "Address1" character(30),
  "Address2" character(30),
  "City" character(24),
  "Province" character(6),
  "Postal" character(15),
  "Area" character(4),
  "Phone" character(8),
  "Comment" character varying(4000),
  "Middle" character(15),
  "AddressOther" character(15),
  "FaxArea" character(4),
  "FaxPhone" character(8),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "Extension" character varying(6),
  "PhysType" character(6),
  "Email" character varying(100),
  CONSTRAINT physhis_primary PRIMARY KEY ("Id")
) ;
CREATE INDEX IF NOT EXISTS physhis_physician ON physhis USING btree ("Physician") TABLESPACE pg_default;
COMMENT ON TABLE physhis IS 'Physician History';
COMMENT ON COLUMN physhis."Province" IS 'Physician province / state, ptr to PROVINCE.Province';
COMMENT ON COLUMN physhis."Postal" IS 'Physician city, ptr to CITY.City';
COMMENT ON COLUMN physhis."Physician" IS 'Physician that this history is for, ptr to PHYSICIA.Physician';
COMMENT ON COLUMN physhis."PhysType" IS 'Type code for this physician, ptr to PHYSTYPE.PhysType';
COMMENT ON COLUMN physhis."Phone" IS 'Physician postal / zip code, ptr to CITY.Postal';
COMMENT ON COLUMN physhis."Middle" IS 'Physician telephone number';
COMMENT ON COLUMN physhis."Last" IS 'Physician last name.';
COMMENT ON COLUMN physhis."Id" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN physhis."First" IS 'Physician middle name.';
COMMENT ON COLUMN physhis."FaxPhone" IS 'Physician fax number';
COMMENT ON COLUMN physhis."FaxArea" IS 'Physician fax area code';
COMMENT ON COLUMN physhis."Extension" IS 'Physician phone extension number';
COMMENT ON COLUMN physhis."Email" IS 'Physician email address.';
COMMENT ON COLUMN physhis."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN physhis."Comment" IS 'Physician telephone area code';
COMMENT ON COLUMN physhis."City" IS 'Physician address, line 2';
COMMENT ON COLUMN physhis."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN physhis."Area" IS 'Physician province / state, ptr to PROVINCE.Province';
COMMENT ON COLUMN physhis."AddressOther" IS 'Text area to enter comments/notes about the physician';
COMMENT ON COLUMN physhis."Address2" IS 'Physician address, line 1';
COMMENT ON COLUMN physhis."Address1" IS 'Physician first name.';


CREATE  TABLE physicia (
  "Physician" numeric(10,0) NOT NULL,
  "Last" character(30),
  "First" character(30),
  "Address1" character(30),
  "Address2" character(30),
  "City" character(24),
  "Province" character(6),
  "Postal" character(15),
  "Area" character(4),
  "Phone" character(8),
  "Comment" character varying(4000),
  "Middle" character(15),
  "AddressOther" character(15),
  "FaxArea" character(4),
  "FaxPhone" character(8),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "Extension" character varying(6),
  "PhysType" character(6),
  "Email" character varying(100),
  CONSTRAINT physicia_primary PRIMARY KEY ("Physician")
) ;
COMMENT ON TABLE physicia IS 'Physicians';
COMMENT ON COLUMN physicia."Province" IS 'Physician province / state, ptr to PROVINCE.Province';
COMMENT ON COLUMN physicia."Postal" IS 'Physician postal / zip code, ptr to CITY.Postal';
COMMENT ON COLUMN physicia."Physician" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN physicia."PhysType" IS 'Type code for this physician, ptr to PHYSTYPE.PhysType';
COMMENT ON COLUMN physicia."Phone" IS 'Physician telephone number';
COMMENT ON COLUMN physicia."Middle" IS 'Physician middle name.';
COMMENT ON COLUMN physicia."Last" IS 'Physician last name.';
COMMENT ON COLUMN physicia."First" IS 'Physician first name.';
COMMENT ON COLUMN physicia."FaxPhone" IS 'Physician fax number';
COMMENT ON COLUMN physicia."FaxArea" IS 'Physician fax area code';
COMMENT ON COLUMN physicia."Extension" IS 'Physician phone extension number';
COMMENT ON COLUMN physicia."Email" IS 'Physician email address.';
COMMENT ON COLUMN physicia."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN physicia."Comment" IS 'Text area to enter comments/notes about the physician';
COMMENT ON COLUMN physicia."City" IS 'Physician city, ptr to CITY.City';
COMMENT ON COLUMN physicia."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN physicia."Area" IS 'Physician telephone area code';
COMMENT ON COLUMN physicia."AddressOther" IS 'For USA, represents County. For Dutch, represents Room Number.';
COMMENT ON COLUMN physicia."Address2" IS 'Physician address, line 2';
COMMENT ON COLUMN physicia."Address1" IS 'Physician address, line 1';


CREATE  TABLE phystype (
  "PhysType" character(6) NOT NULL,
  "Description" character(30),
  "Inactive" numeric(5,0),
  CONSTRAINT phystype_primary PRIMARY KEY ("PhysType")
) ;
COMMENT ON TABLE phystype IS 'Physician Types';
COMMENT ON COLUMN phystype."PhysType" IS 'Code identifying the type of physician';
COMMENT ON COLUMN phystype."Inactive" IS 'Is this type inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN phystype."Description" IS 'Description of the this type';


CREATE  TABLE picture (
  "Patient" numeric(10,0) NOT NULL,
  "Path" character(254),
  "FileExt" character varying(32),
  picture bytea,
  CONSTRAINT picture_primary PRIMARY KEY ("Patient")
) ;
COMMENT ON TABLE picture IS 'Stored patient pictures';
COMMENT ON COLUMN picture.picture IS 'Internal data field to store the picture';
COMMENT ON COLUMN picture."Patient" IS 'Primary key, ID code of the patient, ptr to PATIENT.Patient';
COMMENT ON COLUMN picture."Path" IS 'Pathname to the picture storage location';
COMMENT ON COLUMN picture."FileExt" IS 'File extension';


CREATE  TABLE pinviadj (
  "TrtId" numeric(10,0) NOT NULL,
  "TrtTreatment" numeric(5,0) NOT NULL,
  "AdjId" numeric(10,0) NOT NULL,
  "AdjTreatment" numeric(5,0),
  "Amount" numeric,
  "IsInvoiced" numeric(5,0),
  CONSTRAINT pinviadj_primary PRIMARY KEY ("TrtId", "TrtTreatment", "AdjId")
) ;
COMMENT ON TABLE pinviadj IS 'Information about auto-refunded payments after deleting treatment';
COMMENT ON COLUMN pinviadj."TrtTreatment" IS 'Primary key, line number of the treatment being applied to, ptr to TRX.Treatment';
COMMENT ON COLUMN pinviadj."TrtId" IS 'Primary key, ID of the treatment being applied to, ptr to TRX.Id';
COMMENT ON COLUMN pinviadj."IsInvoiced" IS 'Is invoiced printed? (0=No, 1= Yes)';
COMMENT ON COLUMN pinviadj."Amount" IS 'Refunded amount from this Payment';
COMMENT ON COLUMN pinviadj."AdjTreatment" IS 'Line number of the adjustment being applied from, ptr to TRX.Treatment';
COMMENT ON COLUMN pinviadj."AdjId" IS 'Primary key, ID of the adjustment being applied from, ptr to TRX.Id';


CREATE  TABLE pinvitem (
  "PInvItem" numeric(10,0) NOT NULL,
  "PInvoice" numeric(10,0),
  "Type" numeric(5,0),
  "Id" numeric(10,0),
  "Treatment" numeric(5,0),
  "OrigRecNo" numeric(10,0),
  "PreviousPInvoice" numeric(10,0),
  "TxDate" timestamp without time zone,
  "Procedure" character(7),
  "Site" character(3),
  "Surface" character(6),
  "Total" numeric,
  "InsTotal" numeric,
  "InsTransfer" numeric,
  "PtAdj" numeric,
  "Payed" numeric,
  "ProcessType" numeric(5,0),
  "ErrCode" numeric(5,0),
  CONSTRAINT pinvitem_primary PRIMARY KEY ("PInvItem")
) ;
CREATE INDEX IF NOT EXISTS pinvitem_tx ON pinvitem USING btree ("Type", "Id", "Treatment") TABLESPACE pg_default;
COMMENT ON TABLE pinvitem IS 'Stored treatment information for each treatment on an invoice';
COMMENT ON COLUMN pinvitem."Type" IS 'Transaction type, ptr. to TRX.Type';
COMMENT ON COLUMN pinvitem."TxDate" IS 'Treatment date, ptr. to TRX.Date';
COMMENT ON COLUMN pinvitem."Treatment" IS 'Transaction treatment, ptr. to TRX.Treatment';
COMMENT ON COLUMN pinvitem."Total" IS 'Treatment total, ptr. to TRX.Total';
COMMENT ON COLUMN pinvitem."Surface" IS 'Treatment surface, ptr. to TRX.Surface';
COMMENT ON COLUMN pinvitem."Site" IS 'Treatment site, ptr. to TRX.Site';
COMMENT ON COLUMN pinvitem."PtAdj" IS 'Treatment patient adjustments, ptr. to TRX.PtAdj';
COMMENT ON COLUMN pinvitem."ProcessType" IS 'Result of processing (0=Not paid, 1=Paid, 2=Underpaid)';
COMMENT ON COLUMN pinvitem."Procedure" IS 'Treatment procedure, ptr. to TRX.Procedure';
COMMENT ON COLUMN pinvitem."PreviousPInvoice" IS 'Previous invoice that this treatment appeared on if applicable (For corrections), ptr. to PINVOICE.PInvoice';
COMMENT ON COLUMN pinvitem."Payed" IS 'Treatment patient paid, ptr. to TRX.PtPayed';
COMMENT ON COLUMN pinvitem."PInvoice" IS 'Invoice number, ptr. to PINVOICE.PInvoice';
COMMENT ON COLUMN pinvitem."PInvItem" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN pinvitem."OrigRecNo" IS 'Transaction original record number, ptr. to TRX.OrigRecNo';
COMMENT ON COLUMN pinvitem."InsTransfer" IS 'Treatment insurance transfer, ptr. to TRX.InsTransfer';
COMMENT ON COLUMN pinvitem."InsTotal" IS 'Treatment insurance total, ptr. to TRX.InsTotal';
COMMENT ON COLUMN pinvitem."Id" IS 'Transaction ID, ptr. to TRX.Id';
COMMENT ON COLUMN pinvitem."ErrCode" IS 'If error during processing (301=Tx not found, 302=Tx not expecting payment, 306=Not enough funds)';


CREATE  TABLE pinvoice (
  "PInvoice" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "InvoiceNumber" character(15),
  "Total" numeric,
  "InsTotal" numeric,
  "InsTransfer" numeric,
  "PtAdj" numeric,
  "Payed" numeric,
  "Audit" numeric(10,0),
  "PrintStatus" numeric(5,0) DEFAULT 0,
  "Bank" character(6),
  "InvoiceDate" timestamp without time zone,
  "InvHold" character(6),
  "InvHoldAudit" numeric(10,0) NOT NULL DEFAULT 0,
  "PmtDueDate" timestamp without time zone,
  "InvLetter1Audit" numeric(10,0) NOT NULL DEFAULT 0,
  "InvLetter2Audit" numeric(10,0) NOT NULL DEFAULT 0,
  "InvLetter3Audit" numeric(10,0) NOT NULL DEFAULT 0,
  "Refund" numeric,
  CONSTRAINT pinvoice_primary PRIMARY KEY ("PInvoice")
) ;
COMMENT ON TABLE pinvoice IS 'Invoice header information';
COMMENT ON COLUMN pinvoice."Total" IS 'Sum of total of invoice items';
COMMENT ON COLUMN pinvoice."Refund" IS 'The amount that refunded on this credit invoice';
COMMENT ON COLUMN pinvoice."PtAdj" IS 'Sum of PtAdj of invoice items';
COMMENT ON COLUMN pinvoice."PrintStatus" IS 'Print status (0=Queued, 1=Printed, 2=Re-printed)';
COMMENT ON COLUMN pinvoice."PmtDueDate" IS 'Payment due date for this invoice, defaulted to Invoice Date + 30 Days (Station Option)';
COMMENT ON COLUMN pinvoice."Payed" IS 'Sum of Payed of invoice items';
COMMENT ON COLUMN pinvoice."Patient" IS 'Id code to identify the patient, ptr to PATIENT.Patient';
COMMENT ON COLUMN pinvoice."PInvoice" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN pinvoice."InvoiceNumber" IS 'Generated invoice number';
COMMENT ON COLUMN pinvoice."InvoiceDate" IS 'Invoice date';
COMMENT ON COLUMN pinvoice."InvLetter3Audit" IS 'Audit recording the date that reminder letter 3 was sent, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN pinvoice."InvLetter2Audit" IS 'Audit recording the date that reminder letter 2 was sent, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN pinvoice."InvLetter1Audit" IS 'Audit recording the date that reminder letter 1 was sent, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN pinvoice."InvHoldAudit" IS 'Audit of last user who put the invoice on hold, updated the onl hold reason, or took the invoice off hold, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN pinvoice."InvHold" IS 'On hold reason code if on hold, blank if not on hold';
COMMENT ON COLUMN pinvoice."InsTransfer" IS 'Sum of InsTransfer of invoice items';
COMMENT ON COLUMN pinvoice."InsTotal" IS 'Sum of InsTotal of invoice items';
COMMENT ON COLUMN pinvoice."Bank" IS 'Bank Code, ptr. to BANK.Bank';
COMMENT ON COLUMN pinvoice."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE pinvoich (
  "PInvoicH" numeric(10,0) NOT NULL,
  "PInvoice" numeric(10,0),
  "Patient" numeric(10,0),
  "InvoiceNumber" character(15),
  "Total" numeric,
  "InsTotal" numeric,
  "InsTransfer" numeric,
  "PtAdj" numeric,
  "Payed" numeric,
  "Audit" numeric(10,0),
  "PrintStatus" numeric(5,0),
  "Bank" character(6),
  "InvoiceDate" timestamp without time zone,
  "InvHold" character(6),
  "InvHoldAudit" numeric(10,0),
  "PmtDueDate" timestamp without time zone,
  "InvLetter1Audit" numeric(10,0),
  "InvLetter2Audit" numeric(10,0),
  "InvLetter3Audit" numeric(10,0),
  "Refund" numeric,
  CONSTRAINT pinvoich_primary PRIMARY KEY ("PInvoicH")
) ;
COMMENT ON TABLE pinvoich IS 'Invoice header information history';
COMMENT ON COLUMN pinvoich."Total" IS 'Sum of total of invoice items';
COMMENT ON COLUMN pinvoich."Refund" IS 'The amount that refunded on this credit invoice';
COMMENT ON COLUMN pinvoich."PtAdj" IS 'Sum of PtAdj of invoice items';
COMMENT ON COLUMN pinvoich."PrintStatus" IS 'Print status (0=Queued, 1=Printed, 2=Re-printed)';
COMMENT ON COLUMN pinvoich."PmtDueDate" IS 'Payment due date for this invoice, defaulted to Invoice Date + 30 Days (Station Option)';
COMMENT ON COLUMN pinvoich."Payed" IS 'Sum of Payed of invoice items';
COMMENT ON COLUMN pinvoich."Patient" IS 'Id code to identify the patient, ptr to PATIENT.Patient';
COMMENT ON COLUMN pinvoich."PInvoice" IS 'Invoice header this history is for, ptr to PINVOICE.Pinvoice';
COMMENT ON COLUMN pinvoich."PInvoicH" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN pinvoich."InvoiceNumber" IS 'Generated invoice number';
COMMENT ON COLUMN pinvoich."InvoiceDate" IS 'Invoice date';
COMMENT ON COLUMN pinvoich."InvLetter3Audit" IS 'Audit recording the date that reminder letter 3 was sent, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN pinvoich."InvLetter2Audit" IS 'Audit recording the date that reminder letter 2 was sent, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN pinvoich."InvLetter1Audit" IS 'Audit recording the date that reminder letter 1 was sent, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN pinvoich."InvHoldAudit" IS 'Audit of last user who put the invoice on hold, updated the onl hold reason, or took the invoice off hold, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN pinvoich."InvHold" IS 'On hold reason code if on hold, blank if not on hold';
COMMENT ON COLUMN pinvoich."InsTransfer" IS 'Sum of InsTransfer of invoice items';
COMMENT ON COLUMN pinvoich."InsTotal" IS 'Sum of InsTotal of invoice items';
COMMENT ON COLUMN pinvoich."Bank" IS 'Bank Code, ptr. to BANK.Bank';
COMMENT ON COLUMN pinvoich."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE pitem (
  "Patient" numeric(10,0) NOT NULL,
  "FormCode" character(6) NOT NULL,
  "FItem" numeric(10,0) NOT NULL,
  "AnsType" numeric(5,0),
  "AnsYes" numeric(5,0),
  "AnsText" character varying(4000),
  "AnsList" character(6),
  "AnsListDesc" character varying(50),
  "Date" timestamp without time zone,
  "User" numeric(10,0),
  "Status" numeric(5,0),
  "AuditNumber" numeric(5,0) NOT NULL,
  "AppUser" numeric(10,0),
  "AppDate" timestamp without time zone,
  "AnsDate" timestamp without time zone,
  "ASAType" numeric(5,0),
  "ASAScore" numeric(5,0),
  "PItem" numeric(10,0),
  "Time" numeric(10,0),
  "PForm" numeric(10,0) NOT NULL,
  "PItemImg" numeric(10,0),
  "AnsListRefCode" character varying(10),
  "EntryDateTime" timestamp without time zone,
  "AppDateTime" timestamp without time zone,
  "PItemCol" numeric(10,0) NOT NULL,
  CONSTRAINT pitem_primary PRIMARY KEY ("FormCode", "Patient", "PForm", "FItem", "AuditNumber", "PItemCol")
) ;
CREATE INDEX IF NOT EXISTS pitem_anslistkey ON pitem USING btree ("AnsType", "AnsList") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS pitem_appuserkey ON pitem USING btree ("AppUser", "User") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS pitem_asatypekey ON pitem USING btree ("FormCode", "Patient", "PForm", "ASAType", "Status") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS pitem_codekey ON pitem USING btree ("FormCode", "FItem", "Patient") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS pitem_formapprovalkey ON pitem USING btree ("PForm", "Patient", "FormCode", "User", "AppUser", "FItem") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS pitem_patient ON pitem USING btree ("Patient") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS pitem_pformkey ON pitem USING btree ("PForm") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS pitem_pitem ON pitem USING btree ("PItem") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS pitem_statuskey ON pitem USING btree ("FormCode", "Patient", "PForm", "FItem", "Status", "PItemCol") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS pitem_userappdate ON pitem USING btree ("User", "AppDate") TABLESPACE pg_default;
COMMENT ON TABLE pitem IS 'Patient EPR / ORTHO Form Answers';
COMMENT ON COLUMN pitem."User" IS 'Entry User ID, ptr to USERS.User or IUSER.iUser';
COMMENT ON COLUMN pitem."Time" IS 'Time of the entry';
COMMENT ON COLUMN pitem."Status" IS 'Status (0=Active, 1=Old answer/archived)';
COMMENT ON COLUMN pitem."Patient" IS 'Primary key component, patient that this answer is for. Ptr to PATIENT.Patient';
COMMENT ON COLUMN pitem."PItemImg" IS 'If AnsType=6, ptr to PITEMIMG.PItemImg';
COMMENT ON COLUMN pitem."PItemCol" IS 'Primary key component; for spreadsheets, record with information about this column of answers. Ptr to PITEMCOL.PItemCol.';
COMMENT ON COLUMN pitem."PItem" IS 'Internal ID from sequence.';
COMMENT ON COLUMN pitem."PForm" IS 'Primary key component, form that this answer is for, ptr to PFORM.PForm.';
COMMENT ON COLUMN pitem."FormCode" IS 'Primary key component, form code of this form. Ptr to FORM.Code';
COMMENT ON COLUMN pitem."FItem" IS 'Primary key component, question that this answer is for. Ptr to FITEM.FItem';
COMMENT ON COLUMN pitem."EntryDateTime" IS 'Date/time of when the PItem was entered.';
COMMENT ON COLUMN pitem."Date" IS 'Date the question was answered';
COMMENT ON COLUMN pitem."AuditNumber" IS 'Primary key component, number used to order the change history for the answer (1=First, 2=Second … Higher number indicates the most recent)';
COMMENT ON COLUMN pitem."AppUser" IS 'Approval user, ptr to USERS.User';
COMMENT ON COLUMN pitem."AppDateTime" IS 'Date/time of when the PItem was approved. Only used if AppUser differs from User.';
COMMENT ON COLUMN pitem."AppDate" IS 'Approval date.';
COMMENT ON COLUMN pitem."AnsYes" IS 'Answer to Yes/No question (0 = No, 1 = Yes, -1 = Unanswered)';
COMMENT ON COLUMN pitem."AnsType" IS 'Answer Type ( 0 = Yes/No, 1 = Text, 2 = Number, 3 = List, 4 = Date, 5 = Long Text, 6 = Image, 7 = Calculated, 8 = Attachment, 9 = Spreadsheet)';
COMMENT ON COLUMN pitem."AnsText" IS 'Answer to Text question. If AnsType=5 and the note is longer than 4k characters, the remaining text will be written to NOTEOVR segments. ';
COMMENT ON COLUMN pitem."AnsListRefCode" IS 'Reference code for List Types';
COMMENT ON COLUMN pitem."AnsListDesc" IS 'Description of the list question answer.';
COMMENT ON COLUMN pitem."AnsList" IS 'Answer to List question, ptr to LISTITEM.ListCode';
COMMENT ON COLUMN pitem."AnsDate" IS 'Answer to Date question.';
COMMENT ON COLUMN pitem."ASAType" IS 'Is an ASA type question? (0 = No, 1 = Yes)';
COMMENT ON COLUMN pitem."ASAScore" IS 'If this is an ASA question, the ASA score to assign when this answer is selected (0=N/A, 1=1, 2=2, 3=3, 4=4, 5=5)';


CREATE  TABLE pitem_deleted (
  "Patient" numeric(10,0),
  "FormCode" character(6),
  "FItem" numeric(10,0),
  "AnsType" numeric(5,0),
  "AnsYes" numeric(5,0),
  "AnsText" character varying(4000),
  "AnsList" character(6),
  "AnsListDesc" character varying(50),
  "Date" timestamp without time zone,
  "User" numeric(10,0),
  "Status" numeric(5,0),
  "AuditNumber" numeric(5,0),
  "AppUser" numeric(10,0),
  "AppDate" timestamp without time zone,
  "AnsDate" timestamp without time zone,
  "ASAType" numeric(5,0),
  "ASAScore" numeric(5,0),
  "PItem" numeric(10,0),
  "Time" numeric(10,0),
  "PForm" numeric(10,0) NOT NULL,
  "PItemImg" numeric(10,0),
  "AnsListRefCode" character varying(10),
  "EntryDateTime" timestamp without time zone,
  "AppDateTime" timestamp without time zone,
  "PItemCol" numeric(10,0)
) ;
COMMENT ON TABLE pitem_deleted IS 'Deleted Patient EPR/ORTHO From Answers';
COMMENT ON COLUMN pitem_deleted."User" IS 'Entry User ID, ptr to USERS.User or IUSER.iUser';
COMMENT ON COLUMN pitem_deleted."Time" IS 'Time of the entry';
COMMENT ON COLUMN pitem_deleted."Status" IS 'Status (0=Active, 1=Old answer/archived)';
COMMENT ON COLUMN pitem_deleted."Patient" IS 'Primary key component, patient that this answer is for. Ptr to PATIENT.Patient';
COMMENT ON COLUMN pitem_deleted."PItemImg" IS 'If AnsType=6, ptr to PITEMIMG.PItemImg';
COMMENT ON COLUMN pitem_deleted."PItemCol" IS 'Primary key component; for spreadsheets, record with information about this column of answers. Ptr to PITEMCOL.PItemCol.';
COMMENT ON COLUMN pitem_deleted."PItem" IS 'Internal ID from sequence.';
COMMENT ON COLUMN pitem_deleted."PForm" IS 'Primary key component, form that this answer is for, ptr to PFORM.PForm.';
COMMENT ON COLUMN pitem_deleted."FormCode" IS 'Primary key component, form code of this form. Ptr to FORM.Code';
COMMENT ON COLUMN pitem_deleted."FItem" IS 'Primary key component, question that this answer is for. Ptr to FITEM.FItem';
COMMENT ON COLUMN pitem_deleted."EntryDateTime" IS 'Date/time of when the PItem was entered.';
COMMENT ON COLUMN pitem_deleted."Date" IS 'Date the question was answered';
COMMENT ON COLUMN pitem_deleted."AuditNumber" IS 'Primary key component, number used to order the change history for the answer (1=First, 2=Second … Higher number indicates the most recent)';
COMMENT ON COLUMN pitem_deleted."AppUser" IS 'Approval user, ptr to USERS.User';
COMMENT ON COLUMN pitem_deleted."AppDateTime" IS 'Date/time of when the PItem was approved. Only used if AppUser differs from User.';
COMMENT ON COLUMN pitem_deleted."AppDate" IS 'Approval date.';
COMMENT ON COLUMN pitem_deleted."AnsYes" IS 'Answer to Yes/No question (0 = No, 1 = Yes, -1 = Unanswered)';
COMMENT ON COLUMN pitem_deleted."AnsType" IS 'Answer Type ( 0 = Yes/No, 1 = Text, 2 = Number, 3 = List, 4 = Date, 5 = Long Text, 6 = Image, 7 = Calculated, 8 = Attachment, 9 = Spreadsheet)';
COMMENT ON COLUMN pitem_deleted."AnsText" IS 'Answer to Text question. If AnsType=5 and the note is longer than 4k characters, the remaining text will be written to NOTEOVR segments. ';
COMMENT ON COLUMN pitem_deleted."AnsListRefCode" IS 'Reference code for List Types';
COMMENT ON COLUMN pitem_deleted."AnsListDesc" IS 'Description of the list question answer.';
COMMENT ON COLUMN pitem_deleted."AnsList" IS 'Answer to List question, ptr to LISTITEM.ListCode';
COMMENT ON COLUMN pitem_deleted."AnsDate" IS 'Answer to Date question.';
COMMENT ON COLUMN pitem_deleted."ASAType" IS 'Is an ASA type question? (0 = No, 1 = Yes)';
COMMENT ON COLUMN pitem_deleted."ASAScore" IS 'If this is an ASA question, the ASA score to assign when this answer is selected (0=N/A, 1=1, 2=2, 3=3, 4=4, 5=5)';


CREATE  TABLE pitemcol (
  "PItemCol" numeric(10,0) NOT NULL,
  "FItemCol" numeric(10,0),
  "FormCode" character(6),
  "Patient" numeric(10,0),
  "PForm" numeric(10,0),
  "VariableColumn" numeric(5,0),
  "EntryDateTime" timestamp without time zone,
  "Deleted" numeric(5,0),
  "DeletionDateTime" timestamp without time zone,
  "OrgPItemCol" numeric(10,0),
  CONSTRAINT pitemcol_primary PRIMARY KEY ("PItemCol")
) ;
CREATE INDEX IF NOT EXISTS pitemcol_patient ON pitemcol USING btree ("Patient") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS pitemcol_rowkey ON pitemcol USING btree ("FItemCol", "FormCode", "Patient", "PForm", "Deleted") TABLESPACE pg_default;
COMMENT ON TABLE pitemcol IS 'Stores answered column information.';
COMMENT ON COLUMN pitemcol."VariableColumn" IS 'Variable column number if not pre-defined, 0 if pre-defined.';
COMMENT ON COLUMN pitemcol."Patient" IS 'Patient that this column is for, ptr to PATIENT.Patient';
COMMENT ON COLUMN pitemcol."PItemCol" IS 'Primary key, internal ID from sequence';
COMMENT ON COLUMN pitemcol."PForm" IS 'Instance of this form, ptr to PFORM.PForm';
COMMENT ON COLUMN pitemcol."OrgPItemCol" IS 'If deleted, ptr to original PITEMCOL.PItemCol';
COMMENT ON COLUMN pitemcol."FormCode" IS 'Form that this column is for, ptr to FITEM.FormCode.';
COMMENT ON COLUMN pitemcol."FItemCol" IS 'If the column was pre-defined, ptr to FITEMCOL.FItemCol record for the column.';
COMMENT ON COLUMN pitemcol."EntryDateTime" IS 'Date/time of entry.';
COMMENT ON COLUMN pitemcol."DeletionDateTime" IS 'Date/time of deletion';
COMMENT ON COLUMN pitemcol."Deleted" IS 'Is this column deleted? (0=No, 1=Yes)';


CREATE  TABLE pitemcol_deleted (
  "PItemCol" numeric(10,0),
  "FItemCol" numeric(10,0),
  "FormCode" character(6),
  "Patient" numeric(10,0),
  "PForm" numeric(10,0),
  "VariableColumn" numeric(5,0),
  "EntryDateTime" timestamp without time zone,
  "Deleted" numeric(5,0),
  "DeletionDateTime" timestamp without time zone,
  "OrgPItemCol" numeric(10,0)
) ;
COMMENT ON TABLE pitemcol_deleted IS 'Deleted answered column information';
COMMENT ON COLUMN pitemcol_deleted."VariableColumn" IS 'Variable column number if not pre-defined, 0 if pre-defined.';
COMMENT ON COLUMN pitemcol_deleted."Patient" IS 'Patient that this column is for, ptr to PATIENT.Patient';
COMMENT ON COLUMN pitemcol_deleted."PItemCol" IS 'Primary key, internal ID from sequence';
COMMENT ON COLUMN pitemcol_deleted."PForm" IS 'Instance of this form, ptr to PFORM.PForm';
COMMENT ON COLUMN pitemcol_deleted."OrgPItemCol" IS 'If deleted, ptr to original PITEMCOL.PItemCol';
COMMENT ON COLUMN pitemcol_deleted."FormCode" IS 'Form that this column is for, ptr to FITEM.FormCode.';
COMMENT ON COLUMN pitemcol_deleted."FItemCol" IS 'If the column was pre-defined, ptr to FITEMCOL.FItemCol record for the column.';
COMMENT ON COLUMN pitemcol_deleted."EntryDateTime" IS 'Date/time of entry.';
COMMENT ON COLUMN pitemcol_deleted."DeletionDateTime" IS 'Date/time of deletion';
COMMENT ON COLUMN pitemcol_deleted."Deleted" IS 'Is this column deleted? (0=No, 1=Yes)';


CREATE  TABLE pitemimg (
  "PItemImg" numeric(10,0) NOT NULL,
  image bytea,
  "Type" numeric(5,0),
  "FileExt" character varying(32),
  CONSTRAINT pitemimg_primary PRIMARY KEY ("PItemImg")
) ;
COMMENT ON TABLE pitemimg IS 'EPR Image Answers';
COMMENT ON COLUMN pitemimg.image IS 'BLOB data, the image template with the overlaid drawing. ';
COMMENT ON COLUMN pitemimg."Type" IS 'Type of image (0=Image, 1=Attachment';
COMMENT ON COLUMN pitemimg."PItemImg" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN pitemimg."FileExt" IS 'If Type=1, then the extension of the attached file';


CREATE  TABLE pitemimg_deleted (
  "PItemImg" numeric(10,0) NOT NULL,
  image bytea,
  "Type" numeric(5,0),
  "FileExt" character varying(32)
) ;
COMMENT ON TABLE pitemimg_deleted IS 'Deleted EPR Image Answers';
COMMENT ON COLUMN pitemimg_deleted.image IS 'BLOB data, the image template with the overlaid drawing. ';
COMMENT ON COLUMN pitemimg_deleted."Type" IS 'Type of image (0=Image, 1=Attachment';
COMMENT ON COLUMN pitemimg_deleted."PItemImg" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN pitemimg_deleted."FileExt" IS 'If Type=1, then the extension of the attached file';


CREATE  TABLE pitemtmp (
  "JobId" numeric(10,0) NOT NULL,
  "LineId" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "Type" numeric(5,0),
  "Text" character varying(255),
  "AnsType" numeric(5,0),
  "AnsYes" numeric(5,0),
  anstext clob,
  "AnsList" character(6),
  "AnsListDesc" character varying(50),
  "FormType" numeric(5,0),
  "PtSigDate" timestamp without time zone,
  "PtSigId" numeric(10,0),
  "PItem" numeric(10,0),
  "PForm" numeric(10,0),
  "PItemImg" numeric(10,0),
  "SubLevel" numeric(5,0),
  CONSTRAINT pitemtmp_primary PRIMARY KEY ("JobId", "LineId")
) ;
COMMENT ON TABLE pitemtmp IS 'Temporary Table used when printing EPR and ORTHO forms';
COMMENT ON COLUMN pitemtmp.anstext IS 'Answer Text';
COMMENT ON COLUMN pitemtmp."Type" IS 'Question line type, ptr to FITEM.Type (0=Page Label, 1= Heading, 2 =Question, 3= Checklist, 4 =Additional Info)';
COMMENT ON COLUMN pitemtmp."Text" IS 'Question Text';
COMMENT ON COLUMN pitemtmp."SubLevel" IS '1..n (the level of nesting for the question)';
COMMENT ON COLUMN pitemtmp."PtSigId" IS 'Id code of the patient signature record';
COMMENT ON COLUMN pitemtmp."PtSigDate" IS 'Date of the patient signature';
COMMENT ON COLUMN pitemtmp."Patient" IS 'Patient Id, ptr to PATIENT.Patient';
COMMENT ON COLUMN pitemtmp."PItemImg" IS 'PItem Image ';
COMMENT ON COLUMN pitemtmp."PItem" IS 'The PItem record ';
COMMENT ON COLUMN pitemtmp."PForm" IS 'Internal Id - points to PFORM.PForm';
COMMENT ON COLUMN pitemtmp."LineId" IS 'Line number';
COMMENT ON COLUMN pitemtmp."JobId" IS 'Job Number';
COMMENT ON COLUMN pitemtmp."FormType" IS 'Type of form (0=Ortho, 1=EPR)';
COMMENT ON COLUMN pitemtmp."AnsYes" IS 'Answer to Yes/No (0 = No, 1 = Yes)';
COMMENT ON COLUMN pitemtmp."AnsType" IS 'Answer Type (0=Yes/No, 1=Text, 2=Number, 3=List, 4=Date, 5=Long Text, 6=Image, 7=Calculated)';
COMMENT ON COLUMN pitemtmp."AnsListDesc" IS 'Answer Description if from List';
COMMENT ON COLUMN pitemtmp."AnsList" IS 'Answer to List Type, ptr to LISTITEM.ListCode';


CREATE  TABLE pitemtmp_deleted (
  "JobId" numeric(10,0),
  "LineId" numeric(10,0),
  "Patient" numeric(10,0),
  "Type" numeric(5,0),
  "Text" character varying(255),
  "AnsType" numeric(5,0),
  "AnsYes" numeric(5,0),
  anstext clob,
  "AnsList" character(6),
  "AnsListDesc" character varying(50),
  "FormType" numeric(5,0),
  "PtSigDate" timestamp without time zone,
  "PtSigId" numeric(10,0),
  "PItem" numeric(10,0),
  "PForm" numeric(10,0),
  "PItemImg" numeric(10,0),
  "SubLevel" numeric(5,0)
) ;
COMMENT ON TABLE pitemtmp_deleted IS 'Deleted records for printing EPR and ORTHO forms temporary table';
COMMENT ON COLUMN pitemtmp_deleted.anstext IS 'Answer Text';
COMMENT ON COLUMN pitemtmp_deleted."Type" IS 'Question line type, ptr to FITEM.Type (0=Page Label, 1= Heading, 2 =Question, 3= Checklist, 4 =Additional Info)';
COMMENT ON COLUMN pitemtmp_deleted."Text" IS 'Question Text';
COMMENT ON COLUMN pitemtmp_deleted."SubLevel" IS '1..n (the level of nesting for the question)';
COMMENT ON COLUMN pitemtmp_deleted."PtSigId" IS 'Id code of the patient signature record';
COMMENT ON COLUMN pitemtmp_deleted."PtSigDate" IS 'Date of the patient signature';
COMMENT ON COLUMN pitemtmp_deleted."Patient" IS 'Patient Id, ptr to PATIENT.Patient';
COMMENT ON COLUMN pitemtmp_deleted."PItemImg" IS 'PItem Image ';
COMMENT ON COLUMN pitemtmp_deleted."PItem" IS 'The PItem record ';
COMMENT ON COLUMN pitemtmp_deleted."PForm" IS 'Internal Id - points to PFORM.PForm';
COMMENT ON COLUMN pitemtmp_deleted."LineId" IS 'Line number';
COMMENT ON COLUMN pitemtmp_deleted."JobId" IS 'Job Number';
COMMENT ON COLUMN pitemtmp_deleted."FormType" IS 'Type of form (0=Ortho, 1=EPR)';
COMMENT ON COLUMN pitemtmp_deleted."AnsYes" IS 'Answer to Yes/No (0 = No, 1 = Yes)';
COMMENT ON COLUMN pitemtmp_deleted."AnsType" IS 'Answer Type (0=Yes/No, 1=Text, 2=Number, 3=List, 4=Date, 5=Long Text, 6=Image, 7=Calculated)';
COMMENT ON COLUMN pitemtmp_deleted."AnsListDesc" IS 'Answer Description if from List';
COMMENT ON COLUMN pitemtmp_deleted."AnsList" IS 'Answer to List Type, ptr to LISTITEM.ListCode';


CREATE  TABLE placecd (
  "Code" character(6) NOT NULL,
  "Service" character(6) NOT NULL,
  "ServicePlace" character(2),
  CONSTRAINT placecd_primary PRIMARY KEY ("Code", "Service")
) ;
COMMENT ON TABLE placecd IS 'Place/Service codes';
COMMENT ON COLUMN placecd."ServicePlace" IS 'Service Place identifier';
COMMENT ON COLUMN placecd."Service" IS 'Ptr to SERVICE.Code';
COMMENT ON COLUMN placecd."Code" IS 'Ptr to PLACEOS.Code';


CREATE  TABLE placeos (
  "Code" character(6) NOT NULL,
  "Description" character(30),
  "HIPAACode" character(2),
  "InstitutionCode" character(2),
  CONSTRAINT placeos_primary PRIMARY KEY ("Code")
) ;
COMMENT ON TABLE placeos IS 'Place of Service codes';
COMMENT ON COLUMN placeos."InstitutionCode" IS 'Institution code to use on paper/"EDI" claims (73=Office, 33=Home, 15=IP Hospital, 13=OP Hospital, 23=SNF, 65=ICF)';
COMMENT ON COLUMN placeos."HIPAACode" IS 'HIPAA code to use on paper/"EDI" claims (11=Office, 12=Home, 21=IP Hospital, 22=OP Hospital, 31=SNF, 54=ICF)';
COMMENT ON COLUMN placeos."Description" IS 'Description of the code';
COMMENT ON COLUMN placeos."Code" IS 'Primary Key, ID code to define the place of service';


CREATE  TABLE planfee (
  "PlanId" numeric(10,0) NOT NULL,
  "PlanItem" numeric(10,0) NOT NULL,
  "Type" numeric(5,0),
  "Date" timestamp without time zone,
  "Amount" numeric,
  "TrxId" numeric(10,0),
  "TrxTreatment" numeric(5,0),
  "Procedure" character(7),
  "InsAmount" numeric,
  "ClaimDate" timestamp without time zone,
  "ClaimCreated" numeric(5,0),
  "Audit" numeric(10,0),
  "ClaimFlag" numeric(5,0),
  "CustomaryAmount" numeric,
  CONSTRAINT planfee_primary PRIMARY KEY ("PlanId", "PlanItem")
) ;
CREATE INDEX IF NOT EXISTS planfee_claimdate ON planfee USING btree ("ClaimDate") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS planfee_date ON planfee USING btree ("Date") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS planfee_trxid ON planfee USING btree ("TrxId", "TrxTreatment") TABLESPACE pg_default;
COMMENT ON TABLE planfee IS 'Payment Plan Fees';
COMMENT ON COLUMN planfee."Type" IS 'Fee item type ( 0=Initial, 1=Regular, 2=Final, 3=Manually entered)';
COMMENT ON COLUMN planfee."TrxTreatment" IS 'Treatment line number that this plan fee is for, ptr to TRX.Treatment';
COMMENT ON COLUMN planfee."TrxId" IS 'ID of the treatment that this plan fee is for, ptr to TRX.Id';
COMMENT ON COLUMN planfee."Procedure" IS 'Procedure code of the treatment that this plan fee is for, ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN planfee."PlanItem" IS 'Primary key component, the item # for this fee within the payment plan. ';
COMMENT ON COLUMN planfee."PlanId" IS 'Primary key component, the payment plan that this fee is for. Ptr to PAYPLAN.PlanId';
COMMENT ON COLUMN planfee."InsAmount" IS 'Insurance portion of the fee, in dollars.';
COMMENT ON COLUMN planfee."Date" IS 'Fee item date (date the fee is charged)';
COMMENT ON COLUMN planfee."CustomaryAmount" IS 'Customary Total amount, in dollars.';
COMMENT ON COLUMN planfee."ClaimFlag" IS 'For Orthodontic payment plans, create claim? (0 = N/A, 1 = No (don’t submit), 2 = With plan fee amount, 3 = With treatment total)';
COMMENT ON COLUMN planfee."ClaimDate" IS 'Date the claim was submitted';
COMMENT ON COLUMN planfee."ClaimCreated" IS 'Was a claim created? (0=No, 1=Yes)';
COMMENT ON COLUMN planfee."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN planfee."Amount" IS 'Amount of the fee, in dollars.';


CREATE  TABLE planfhis (
  "PlanFHis" numeric(10,0) NOT NULL,
  "PlanId" numeric(10,0) NOT NULL,
  "PlanItem" numeric(10,0) NOT NULL,
  "Type" numeric(5,0),
  "Date" timestamp without time zone,
  "Amount" numeric,
  "TrxId" numeric(10,0),
  "TrxTreatment" numeric(5,0),
  "Procedure" character(7),
  "InsAmount" numeric,
  "ClaimDate" timestamp without time zone,
  "ClaimCreated" numeric(5,0),
  "Audit" numeric(10,0),
  "ClaimFlag" numeric(5,0),
  "CustomaryAmount" numeric,
  CONSTRAINT planfhis_primary PRIMARY KEY ("PlanFHis")
) ;
CREATE INDEX IF NOT EXISTS planfhis_planfee ON planfhis USING btree ("PlanId", "PlanItem") TABLESPACE pg_default;
COMMENT ON TABLE planfhis IS 'Payment Plan Fee History';
COMMENT ON COLUMN planfhis."Type" IS 'Fee item type ( 0=Initial, 1=Regular, 2=Final, 3=Manually entered)';
COMMENT ON COLUMN planfhis."TrxTreatment" IS 'Treatment line number that this plan fee is for, ptr to TRX.Treatment';
COMMENT ON COLUMN planfhis."TrxId" IS 'ID of the treatment that this plan fee is for, ptr to TRX.Id';
COMMENT ON COLUMN planfhis."Procedure" IS 'Procedure code of the treatment that this plan fee is for, ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN planfhis."PlanItem" IS 'The item # for this fee within the payment plan that this history is for. ';
COMMENT ON COLUMN planfhis."PlanId" IS 'The payment plan that this history is for. Ptr to PAYPLAN.PlanId';
COMMENT ON COLUMN planfhis."PlanFHis" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN planfhis."InsAmount" IS 'Insurance portion of the fee, in dollars.';
COMMENT ON COLUMN planfhis."Date" IS 'Fee item date (date the fee is charged)';
COMMENT ON COLUMN planfhis."CustomaryAmount" IS 'Customary Total amount, in dollars.';
COMMENT ON COLUMN planfhis."ClaimFlag" IS 'For Orthodontic payment plans, create claim? (0 = N/A, 1 = No (don’t submit), 2 = With plan fee amount, 3 = With treatment total)';
COMMENT ON COLUMN planfhis."ClaimDate" IS 'Date the claim was submitted';
COMMENT ON COLUMN planfhis."ClaimCreated" IS 'Was a claim created? (0=No, 1=Yes)';
COMMENT ON COLUMN planfhis."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN planfhis."Amount" IS 'Amount of the fee, in dollars.';


CREATE  TABLE planhis (
  "PlanHis" numeric(10,0) NOT NULL,
  "PlanId" numeric(10,0),
  "Patient" numeric(10,0),
  "Family" numeric(10,0),
  "Type" numeric(5,0),
  "Total" numeric,
  "InitialFee" numeric,
  "InitialDate" timestamp without time zone,
  "Period" numeric(5,0),
  "RegularStart" timestamp without time zone,
  "RegularFee" numeric,
  "RegularCount" numeric(5,0),
  "FinalFee" numeric,
  "FinalDate" timestamp without time zone,
  "Comment" character(100),
  "Status" numeric(5,0),
  "ClosingBalance" numeric,
  "RespId" numeric(10,0),
  "CreationDate" timestamp without time zone,
  "Contract" numeric(10,0),
  "Audit" numeric(10,0),
  "VisitLimit" numeric(5,0),
  "RegularSch" numeric(5,0),
  CONSTRAINT planhis_primary PRIMARY KEY ("PlanHis")
) ;
CREATE INDEX IF NOT EXISTS planhis_planid ON planhis USING btree ("PlanId") TABLESPACE pg_default;
COMMENT ON TABLE planhis IS 'Payment Plan History';
COMMENT ON COLUMN planhis."VisitLimit" IS 'Bill only if patient visit occurred during the billing period? (0=No, 1=Yes)';
COMMENT ON COLUMN planhis."Type" IS 'Plan is for (0=Specific Charges, 1=Outstanding Balance, 2=Orthodontics)';
COMMENT ON COLUMN planhis."Total" IS 'Plan total amount, in dollars.';
COMMENT ON COLUMN planhis."Status" IS 'Payment plan status (0 = Active, 1 = Closed, 2 = Deleted)';
COMMENT ON COLUMN planhis."RespId" IS 'The guarantor of the payment plan. Ptr to PATIENT.Patient';
COMMENT ON COLUMN planhis."RegularStart" IS 'Starting date of the regular payments on the payment plan.';
COMMENT ON COLUMN planhis."RegularSch" IS 'Plan uses a regular payment schedule? (0=No, 1=Yes)';
COMMENT ON COLUMN planhis."RegularFee" IS 'Regular payment amount, in dollars.';
COMMENT ON COLUMN planhis."RegularCount" IS 'Expected number of regular payments. ';
COMMENT ON COLUMN planhis."PlanId" IS 'Payment plan that this history is for, ptr to PAYPLAN.PlanId';
COMMENT ON COLUMN planhis."PlanHis" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN planhis."Period" IS 'Payment period (0=Monthly, 1=Quarterly, 2=Semi-Annual).';
COMMENT ON COLUMN planhis."Patient" IS 'Patient that this payment plan is for, ptr to PATIENT.Patient';
COMMENT ON COLUMN planhis."InitialFee" IS 'Down payment amount, in dollars.';
COMMENT ON COLUMN planhis."InitialDate" IS 'Down payment date.';
COMMENT ON COLUMN planhis."FinalFee" IS 'Final payment amount, in dollars. ';
COMMENT ON COLUMN planhis."FinalDate" IS 'Expected date of the final payment.';
COMMENT ON COLUMN planhis."Family" IS 'Family ID, ptr to PATIENT.Family';
COMMENT ON COLUMN planhis."CreationDate" IS 'Date that the payment plan was created.';
COMMENT ON COLUMN planhis."Contract" IS 'Contract for this payment plan, ptr to CONTRACT.Contract';
COMMENT ON COLUMN planhis."Comment" IS 'Free text area to type notes on the payment plan.';
COMMENT ON COLUMN planhis."ClosingBalance" IS 'Closing balance amount, in dollars.';
COMMENT ON COLUMN planhis."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE plbcode (
  "Code" character(6) NOT NULL,
  "Description" character varying(30),
  CONSTRAINT plbcode_primary PRIMARY KEY ("Code")
) ;
COMMENT ON TABLE plbcode IS 'HIPAA Provider Level Adjustment Codes';
COMMENT ON COLUMN plbcode."Description" IS 'Description of HIPAA code';
COMMENT ON COLUMN plbcode."Code" IS 'HIPAA code for PLB segments';


CREATE  TABLE plreason (
  "Code" character(6) NOT NULL,
  "Description" character varying(30),
  "AdjustType" numeric(5,0),
  "AdjustDB" character(6),
  "AdjustCR" character(6),
  "Inactive" numeric(5,0),
  CONSTRAINT plreason_primary PRIMARY KEY ("Code")
) ;
COMMENT ON TABLE plreason IS 'Insurance Payment Adjustment Reason Codes';
COMMENT ON COLUMN plreason."Inactive" IS 'Is this code inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN plreason."Description" IS 'Description of insurance payment adjustment reason code';
COMMENT ON COLUMN plreason."Code" IS 'Primary Key, insurance payment adjustment reason code';
COMMENT ON COLUMN plreason."AdjustType" IS 'Type of insurance payment adjustment reason code (0=Debit, 1=Credit, 2=Debit or Credit)';
COMMENT ON COLUMN plreason."AdjustDB" IS 'Adjustment code to use if AdjustType is 0 or 2, ptr to ADJUST.Adjust';
COMMENT ON COLUMN plreason."AdjustCR" IS 'Adjustment code to use if AdjustType is 1 or 2, ptr to ADJUST.Adjust';


CREATE  TABLE polfees (
  "PolIns" numeric(10,0) NOT NULL,
  "BillDoctor" character(10) NOT NULL,
  "Fee" character(6),
  CONSTRAINT polfees_primary PRIMARY KEY ("PolIns", "BillDoctor")
) ;
COMMENT ON TABLE polfees IS 'New Policy Fee Schedule Table';
COMMENT ON COLUMN polfees."PolIns" IS 'Primary key, Policy Id.';
COMMENT ON COLUMN polfees."Fee" IS 'fee schedule to use';
COMMENT ON COLUMN polfees."BillDoctor" IS 'Primary key, Billing doctor/ fee guide';


CREATE  TABLE policyco (
  "GovPolicy" character(6) NOT NULL,
  "Type" numeric(5,0),
  "Description" character(30),
  CONSTRAINT policyco_primary PRIMARY KEY ("GovPolicy")
) ;
COMMENT ON TABLE policyco IS 'Government Policy Codes';
COMMENT ON COLUMN policyco."Type" IS 'Coverage Type (0=Family, 1=Patient)';
COMMENT ON COLUMN policyco."GovPolicy" IS 'Primary key, code to identify the government policy';
COMMENT ON COLUMN policyco."Description" IS 'Description of the government policy';


CREATE  TABLE polins (
  "PolIns" numeric(10,0) NOT NULL,
  "Group" character(15),
  "Division" character(10),
  "FormsTo" numeric(5,0),
  "Company" character(6),
  "GovPolicy" character(6),
  "Fee" character(6),
  "Employer" numeric(10,0),
  "HasFamilyLimit" numeric(5,0),
  "FamilyDeduct" numeric,
  "FamilyLimit" numeric,
  "HasPatientLimit" numeric(5,0),
  "PatientDeduct" numeric,
  "PatientLimit" numeric,
  "YearEnd" numeric(10,0),
  "Assignment" numeric(5,0),
  "Signature" numeric(5,0),
  "ChangeDate" timestamp without time zone,
  "CvgPct" character(30),
  "WriteOff" numeric(5,0),
  "Deleted" numeric(5,0),
  "PlanType" numeric(5,0),
  "MonthlyDeduct" numeric(5,0),
  "Date" timestamp without time zone,
  "Time" numeric(10,0),
  "User" numeric(10,0),
  "StationId" numeric(10,0),
  "TrojanId" character(7),
  "YearEndDay" numeric(5,0),
  "ChildCoverage" numeric(10,0),
  "AdultCoverage" numeric(10,0),
  "Copay" numeric,
  "SharedEntryId" numeric(10,0),
  "Description" character varying(30),
  "SharablePlan" numeric(5,0),
  "StartDate" timestamp without time zone,
  "EndDate" timestamp without time zone,
  "VisitFee" numeric,
  "CoverageAge" numeric(5,0),
  "CoverageAgeStud" numeric(5,0),
  "OrigRecNo" numeric(10,0),
  "EDIFlag" numeric(5,0),
  "CoverageAgeYoungAdult" numeric(5,0),
  "YoungAdultCoverage" numeric(10,0),
  "CvgOnBirthChild" numeric(5,0),
  "CvgOnBirthStudent" numeric(5,0),
  "CvgOnBirthYoungAdult" numeric(5,0),
  "ChargeDedAndPtChg" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT polins_primary PRIMARY KEY ("PolIns")
) ;
CREATE INDEX IF NOT EXISTS polins_adultcoverage ON polins USING btree ("AdultCoverage") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS polins_childcoverage ON polins USING btree ("ChildCoverage") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS polins_company ON polins USING btree ("Company") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS polins_employer ON polins USING btree ("Employer") TABLESPACE pg_default;
COMMENT ON TABLE polins IS 'Insurance benefit plans  ';
COMMENT ON COLUMN polins."YoungAdultCoverage" IS 'Id code of the coverage template for young adult, ptr to COVERAGE.Coverage';
COMMENT ON COLUMN polins."YearEndDay" IS 'Number to indicate the day of the month on which the benefit plan year end occurs. ';
COMMENT ON COLUMN polins."YearEnd" IS 'Number of the month that is considered the year-end for the benefit plan (1=January...12=December)';
COMMENT ON COLUMN polins."WriteOff" IS 'Does this benefit plan allow write offs? (0 = No, 1 = Yes)';
COMMENT ON COLUMN polins."VisitFee" IS 'Visit Fee amount (i.e. $10.00)';
COMMENT ON COLUMN polins."User" IS 'ID code of the entry user, ptr to USERS.User';
COMMENT ON COLUMN polins."TrojanId" IS 'For linking to Trojan policy';
COMMENT ON COLUMN polins."Time" IS 'Time the record was added/altered';
COMMENT ON COLUMN polins."StationId" IS 'ID code of the station from which this record was added, ptr to STATION.StationId';
COMMENT ON COLUMN polins."StartDate" IS 'Date that coverage for this benefit plan begins.';
COMMENT ON COLUMN polins."Signature" IS 'Does this benefit plan requires signatures? (0 = No, 1 = Yes)';
COMMENT ON COLUMN polins."SharedEntryId" IS 'POLICY_SharedEntryId_SEQ (Internal field used to link PTPOL and POLINS auditing )';
COMMENT ON COLUMN polins."SharablePlan" IS 'Is this benefit plan a group plan that multiple subscribers can belong to? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN polins."PolIns" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN polins."PlanType" IS 'Insurance plan type (for claim forms). (0=N/A, 1=Self Pay, 2=Workers Comp., 3=Medicare Part B, 4=Medicaid, 5=Other Federal, 6=Commercial, 7=BC/BS, 8=CHAMPUS, 9=Other Non-Fed. Prog., 10=PPO, 11=POS, 12=EPO, 13=Indemnity Ins, 14=HMO Medicare Risk, 15=Dental Maint. Org., 16=Disability, 17=Fed Employees Prog., 18=HMO, 19=Liability, 20=Managed Care, 21=Self Admin. Gp., 22=Veteran, 23=Mutually Defined, 24=Automobile Medical, 25=Medicare Part A, 26=Title V)';
COMMENT ON COLUMN polins."PatientLimit" IS 'Dollar ($) amount of patient limit';
COMMENT ON COLUMN polins."PatientDeduct" IS 'Dollar ($) amount of patient deductible';
COMMENT ON COLUMN polins."OrigRecNo" IS 'Original record number, ptr to POLINS.PolIns';
COMMENT ON COLUMN polins."MonthlyDeduct" IS 'Is deductible monthly? (0 = No, 1 = Yes)';
COMMENT ON COLUMN polins."HasPatientLimit" IS 'Does this benefit plan have a patient limit? (0 = No, 1 = Yes, 2 = Yes, for adults only)';
COMMENT ON COLUMN polins."HasFamilyLimit" IS 'Does this benefit plan have a family limit? (0 = No, 1 = Yes, 2 = Yes, for adults only)';
COMMENT ON COLUMN polins."Group" IS 'Benefit plan group number/identifier.';
COMMENT ON COLUMN polins."GovPolicy" IS 'Optional field, if policy is government, then ptr to POLICYCO.GovPolicy';
COMMENT ON COLUMN polins."FormsTo" IS 'Where are forms sent to? (0 = Insurance [default], 1 = Patient, 2 = Employer, 3 = Office)';
COMMENT ON COLUMN polins."Fee" IS 'Benefit plan fee schedule (schedule that the policy charges/pays), ptr to FEESCHED.Fee';
COMMENT ON COLUMN polins."FamilyLimit" IS 'Dollar ($) amount of family limit';
COMMENT ON COLUMN polins."FamilyDeduct" IS 'Dollar ($) amount of family deductible';
COMMENT ON COLUMN polins."EndDate" IS 'Date that coverage for this benefit plan expires.';
COMMENT ON COLUMN polins."Employer" IS 'Employer for this benefit plan, ptr to EMPLOYER.Employer';
COMMENT ON COLUMN polins."EDIFlag" IS 'Policy accepts "EDI" Claims? (0=No, 1=Yes) (Canada only)';
COMMENT ON COLUMN polins."Division" IS 'Benefit plan division number/identifier. ';
COMMENT ON COLUMN polins."Description" IS 'Description of Benefit Plan';
COMMENT ON COLUMN polins."Deleted" IS 'Is this benefit plan deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN polins."Date" IS 'Date the record was added/altered';
COMMENT ON COLUMN polins."CvgPct" IS 'Description of coverage for the benefit plan';
COMMENT ON COLUMN polins."CvgOnBirthYoungAdult" IS 'The point at which young adult coverage ends. Default: 0=Day,1=End of Month, 2=End of Year';
COMMENT ON COLUMN polins."CvgOnBirthStudent" IS 'The point at which student coverage ends. Default: 0=Day,1=End of Month, 2=End of Year';
COMMENT ON COLUMN polins."CvgOnBirthChild" IS 'The point at which child coverage ends. Default: 0=Day,1=End of Month, 2=End of Year';
COMMENT ON COLUMN polins."CoverageAgeYoungAdult" IS 'Coverage age of young adult';
COMMENT ON COLUMN polins."CoverageAgeStud" IS 'Age in years that students covered up to.';
COMMENT ON COLUMN polins."CoverageAge" IS 'Age in years that children covered up to.';
COMMENT ON COLUMN polins."Copay" IS 'Dollar ($) amount of the copay';
COMMENT ON COLUMN polins."Company" IS 'Insurance company ID, ptr to INSURANC.Company';
COMMENT ON COLUMN polins."ChildCoverage" IS 'ID code of the child coverage template, ptr to COVERAGE.Coverage.';
COMMENT ON COLUMN polins."ChargeDedAndPtChg" IS 'KP Only: Flag to determine whether or not to charge both deductible and patient charge (0=No, 1=Yes)';
COMMENT ON COLUMN polins."ChangeDate" IS 'Date that the benefit plan was last modified. ';
COMMENT ON COLUMN polins."Assignment" IS 'Does this benefit plan accept assignment? (0 = No, 1 = Yes [default])';
COMMENT ON COLUMN polins."AdultCoverage" IS 'Id code of the adult coveage template, ptr to COVERAGE.Coverage.';


CREATE  TABLE polinsh (
  "PolInsH" numeric(10,0) NOT NULL,
  "HistoryType" numeric(5,0),
  "PolIns" numeric(10,0),
  "Group" character(15),
  "Division" character(10),
  "FormsTo" numeric(5,0),
  "Company" character(6),
  "GovPolicy" character(6),
  "Fee" character(6),
  "Employer" numeric(10,0),
  "HasFamilyLimit" numeric(5,0),
  "FamilyDeduct" numeric,
  "FamilyLimit" numeric,
  "HasPatientLimit" numeric(5,0),
  "PatientDeduct" numeric,
  "PatientLimit" numeric,
  "YearEnd" numeric(10,0),
  "Assignment" numeric(5,0),
  "Signature" numeric(5,0),
  "ChangeDate" timestamp without time zone,
  "CvgPct" character(30),
  "WriteOff" numeric(5,0),
  "Deleted" numeric(5,0),
  "PlanType" numeric(5,0),
  "MonthlyDeduct" numeric(5,0),
  "Date" timestamp without time zone,
  "Time" numeric(10,0),
  "User" numeric(10,0),
  "StationId" numeric(10,0),
  "TrojanId" character(7),
  "YearEndDay" numeric(5,0),
  "ChildCoverage" numeric(10,0),
  "AdultCoverage" numeric(10,0),
  "Copay" numeric,
  "SharedEntryId" numeric(10,0),
  "Description" character varying(30),
  "SharablePlan" numeric(5,0),
  "StartDate" timestamp without time zone,
  "EndDate" timestamp without time zone,
  "VisitFee" numeric,
  "CoverageAge" numeric(5,0),
  "CoverageAgeStud" numeric(5,0),
  "OrigRecNo" numeric(10,0),
  "EDIFlag" numeric(5,0),
  "CoverageAgeYoungAdult" numeric(5,0),
  "YoungAdultCoverage" numeric(10,0),
  "CvgOnBirthChild" numeric(5,0),
  "CvgOnBirthStudent" numeric(5,0),
  "CvgOnBirthYoungAdult" numeric(5,0),
  "ChargeDedAndPtChg" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT polinsh_primary PRIMARY KEY ("PolInsH")
) ;
CREATE INDEX IF NOT EXISTS polinsh_adultcoverage ON polinsh USING btree ("AdultCoverage") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS polinsh_childcoverage ON polinsh USING btree ("ChildCoverage") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS polinsh_polins ON polinsh USING btree ("PolIns") TABLESPACE pg_default;
COMMENT ON TABLE polinsh IS 'History table for POLINS ';
COMMENT ON COLUMN polinsh."YoungAdultCoverage" IS 'Id code of the coverage template for young adult, ptr to COVERAGE.Coverage';
COMMENT ON COLUMN polinsh."YearEndDay" IS 'Number to indicate the day of the month on which the benefit plan year end occurs. ';
COMMENT ON COLUMN polinsh."YearEnd" IS 'Number of the month that is considered the year-end for the benefit plan (1=January...12=December)';
COMMENT ON COLUMN polinsh."WriteOff" IS 'Does this benefit plan allow write offs? (0 = No, 1 = Yes)';
COMMENT ON COLUMN polinsh."VisitFee" IS 'Visit Fee amount (i.e. $10.00)';
COMMENT ON COLUMN polinsh."User" IS 'ID code of the entry user, ptr to USERS.User';
COMMENT ON COLUMN polinsh."TrojanId" IS 'For linking to Trojan policy';
COMMENT ON COLUMN polinsh."Time" IS 'Time the record was added/altered';
COMMENT ON COLUMN polinsh."StationId" IS 'ID code of the station from which this record was added, ptr to STATION.StationId';
COMMENT ON COLUMN polinsh."StartDate" IS 'Date that coverage for this benefit plan begins.';
COMMENT ON COLUMN polinsh."Signature" IS 'Does this benefit plan requires signatures? (0 = No, 1 = Yes)';
COMMENT ON COLUMN polinsh."SharedEntryId" IS 'POLICY_SharedEntryId_SEQ (Internal field used to link PTPOL and POLINS auditing )';
COMMENT ON COLUMN polinsh."SharablePlan" IS 'Is this benefit plan a group plan that multiple subscribers can belong to? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN polinsh."PolInsH" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN polinsh."PolIns" IS 'Benefit plan that this history is for, ptr to POLINS.PolIns';
COMMENT ON COLUMN polinsh."PlanType" IS 'Insurance plan type (for claim forms). (0=N/A, 1=Self Pay, 2=Workers Comp., 3=Medicare Part B, 4=Medicaid, 5=Other Federal, 6=Commercial, 7=BC/BS, 8=CHAMPUS, 9=Other Non-Fed. Prog., 10=PPO, 11=POS, 12=EPO, 13=Indemnity Ins, 14=HMO Medicare Risk, 15=Dental Maint. Org., 16=Disability, 17=Fed Employees Prog., 18=HMO, 19=Liability, 20=Managed Care, 21=Self Admin. Gp., 22=Veteran, 23=Mutually Defined, 24=Automobile Medical, 25=Medicare Part A, 26=Title V)';
COMMENT ON COLUMN polinsh."PatientLimit" IS 'Dollar ($) amount of patient limit';
COMMENT ON COLUMN polinsh."PatientDeduct" IS 'Dollar ($) amount of patient deductible';
COMMENT ON COLUMN polinsh."OrigRecNo" IS 'Original record number, ptr to POLINS.PolIns';
COMMENT ON COLUMN polinsh."MonthlyDeduct" IS 'Is deductible monthly? (0 = No, 1 = Yes)';
COMMENT ON COLUMN polinsh."HistoryType" IS 'Type of audit record (1=Add, 2=Edit, 4=Delete)';
COMMENT ON COLUMN polinsh."HasPatientLimit" IS 'Does this benefit plan have a patient limit? (0 = No, 1 = Yes, 2 = Yes, for adults only)';
COMMENT ON COLUMN polinsh."HasFamilyLimit" IS 'Does this benefit plan have a family limit? (0 = No, 1 = Yes, 2 = Yes, for adults only)';
COMMENT ON COLUMN polinsh."Group" IS 'Benefit plan group number/identifier.';
COMMENT ON COLUMN polinsh."GovPolicy" IS 'Optional field, if policy is government, then ptr to POLICYCO.GovPolicy';
COMMENT ON COLUMN polinsh."FormsTo" IS 'Where are forms sent to? (0 = Insurance [default], 1 = Patient, 2 = Employer, 3 = Office)';
COMMENT ON COLUMN polinsh."Fee" IS 'Benefit plan fee schedule (schedule that the policy charges/pays), ptr to FEESCHED.Fee';
COMMENT ON COLUMN polinsh."FamilyLimit" IS 'Dollar ($) amount of family limit';
COMMENT ON COLUMN polinsh."FamilyDeduct" IS 'Dollar ($) amount of family deductible';
COMMENT ON COLUMN polinsh."EndDate" IS 'Date that coverage for this benefit plan expires.';
COMMENT ON COLUMN polinsh."Employer" IS 'Employer for this benefit plan, ptr to EMPLOYER.Employer';
COMMENT ON COLUMN polinsh."EDIFlag" IS 'Policy accepts "EDI" Claims? (0=No, 1=Yes) (Canada only)';
COMMENT ON COLUMN polinsh."Division" IS 'Benefit plan division number/identifier. ';
COMMENT ON COLUMN polinsh."Description" IS 'Description of Benefit Plan';
COMMENT ON COLUMN polinsh."Deleted" IS 'Is this benefit plan deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN polinsh."Date" IS 'Date the record was added/altered';
COMMENT ON COLUMN polinsh."CvgPct" IS 'Description of coverage for the benefit plan';
COMMENT ON COLUMN polinsh."CvgOnBirthYoungAdult" IS 'The point at which young adult coverage ends. Default: 0=Day,1=End of Month, 2=End of Year';
COMMENT ON COLUMN polinsh."CvgOnBirthStudent" IS 'The point at which student coverage ends. Default: 0=Day,1=End of Month, 2=End of Year';
COMMENT ON COLUMN polinsh."CvgOnBirthChild" IS 'The point at which child coverage ends. Default: 0=Day,1=End of Month, 2=End of Year';
COMMENT ON COLUMN polinsh."CoverageAgeYoungAdult" IS 'Coverage age of young adult';
COMMENT ON COLUMN polinsh."CoverageAgeStud" IS 'Age in years that students covered up to.';
COMMENT ON COLUMN polinsh."CoverageAge" IS 'Age in years that children covered up to.';
COMMENT ON COLUMN polinsh."Copay" IS 'Dollar ($) amount of the copay';
COMMENT ON COLUMN polinsh."Company" IS 'Insurance company ID, ptr to INSURANC.Company';
COMMENT ON COLUMN polinsh."ChildCoverage" IS 'ID code of the child coverage template, ptr to COVERAGE.Coverage.';
COMMENT ON COLUMN polinsh."ChargeDedAndPtChg" IS 'KP Only: Flag to determine whether or not to charge both deductible and patient charge (0=No, 1=Yes)';
COMMENT ON COLUMN polinsh."ChangeDate" IS 'Date that the benefit plan was last modified. ';
COMMENT ON COLUMN polinsh."Assignment" IS 'Does this benefit plan accept assignment? (0 = No, 1 = Yes [default])';
COMMENT ON COLUMN polinsh."AdultCoverage" IS 'Id code of the adult coveage template, ptr to COVERAGE.Coverage.';


CREATE  TABLE polrange (
  "PolIns" numeric(10,0) NOT NULL,
  "Id" numeric(10,0) NOT NULL,
  "Description" character(30),
  "Category" character(6),
  "From" character(7),
  "To" character(7),
  "Percent" numeric,
  "Times" numeric(10,0),
  "Frequency" numeric(10,0),
  "FrequencyCode" numeric(5,0),
  "HasCatLimit" numeric(5,0),
  "CatLimit" numeric,
  "CatPeriod" numeric(10,0),
  "CatFrequency" numeric(5,0),
  "HasItemLimit" numeric(5,0),
  "ItemLimit" numeric,
  "ItemPeriod" numeric(10,0),
  "ItemFrequency" numeric(5,0),
  "CatDeduct" numeric,
  "CatAffectFamily" numeric(5,0),
  "HasCategory" numeric(5,0),
  "ItemDeduct" numeric,
  "ItemAffectFamily" numeric(5,0),
  "ItemPtChg" numeric,
  "LimitOnPatient" numeric(5,0),
  CONSTRAINT polrange_primary PRIMARY KEY ("PolIns", "Id")
) ;
CREATE INDEX IF NOT EXISTS polrange_categorykey ON polrange USING btree ("PolIns", "Category") TABLESPACE pg_default;
COMMENT ON TABLE polrange IS 'Policy coverage ranges, used for specifying % coverage for a range of procedure codes';
COMMENT ON COLUMN polrange."To" IS 'Ending procedure code for coverage range, ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN polrange."Times" IS '# of times procedure will be covered in Frequency range';
COMMENT ON COLUMN polrange."PolIns" IS 'Primary key component, benefit plan that this coverage range applies to. Ptr to POLINS.PolIns.';
COMMENT ON COLUMN polrange."Percent" IS 'Percentage of coverage.';
COMMENT ON COLUMN polrange."LimitOnPatient" IS 'Is this a patient limit? (0=No (limit on insurance), 1=Yes (limit on patient maximum), 2=Yes (limit on patient maximum + deductable))';
COMMENT ON COLUMN polrange."ItemPtChg" IS 'Dollar value ($) to be charged to the patient for this item ';
COMMENT ON COLUMN polrange."ItemPeriod" IS 'Item limit period (used with ItemFrequency)';
COMMENT ON COLUMN polrange."ItemLimit" IS 'Item Limit amount';
COMMENT ON COLUMN polrange."ItemFrequency" IS 'Frequency period (0=N/A, 1=Months, 2=Years, 3=Lifetime)';
COMMENT ON COLUMN polrange."ItemDeduct" IS 'Dollar ($) value of the optional deductible per item';
COMMENT ON COLUMN polrange."ItemAffectFamily" IS 'Item affects family deductibles? (0 = No, 1 = Yes)';
COMMENT ON COLUMN polrange."Id" IS 'Primary key component, line number of coverage range.';
COMMENT ON COLUMN polrange."HasItemLimit" IS 'Has Item limit? (0 = No, 1 = Yes)';
COMMENT ON COLUMN polrange."HasCategory" IS 'Has a category? (0 = No, 1 = Yes)';
COMMENT ON COLUMN polrange."HasCatLimit" IS 'Has Category limit? (0 = No, 1 = Yes)';
COMMENT ON COLUMN polrange."From" IS 'Starting procedure code for coverage range, ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN polrange."FrequencyCode" IS 'Frequency period (0=N/A, 1=Months, 2=Years, 3=Policy Years, 4=Life Time)';
COMMENT ON COLUMN polrange."Frequency" IS 'Frequency limit period (used with FrequencyFlag)';
COMMENT ON COLUMN polrange."Description" IS 'Description of coverage range.';
COMMENT ON COLUMN polrange."Category" IS 'Category of coverage range.';
COMMENT ON COLUMN polrange."CatPeriod" IS 'Category Limit period (used with CatFrequency)';
COMMENT ON COLUMN polrange."CatLimit" IS 'Category Limit amount';
COMMENT ON COLUMN polrange."CatFrequency" IS 'Frequency period (0=N/A, 1=Months, 2=Years, 3=Lifetime)';
COMMENT ON COLUMN polrange."CatDeduct" IS 'Category deductable amount, in dollars. ';
COMMENT ON COLUMN polrange."CatAffectFamily" IS 'Affect the family deductible? (0 = No, 1 = Yes) ';


CREATE  TABLE polrider (
  "PolRider" numeric(10,0) NOT NULL,
  "PolIns" numeric(10,0),
  "Description" character varying(30),
  "RiderChildCoverage" numeric(10,0),
  "RiderAdultCoverage" numeric(10,0),
  "RiderAge" numeric(5,0),
  "RiderAgeStud" numeric(5,0),
  "RiderYoungAdultCoverage" numeric(10,0),
  "RiderAgeYoungAdult" numeric(5,0),
  CONSTRAINT polrider_primary PRIMARY KEY ("PolRider")
) ;
CREATE INDEX IF NOT EXISTS polrider_polins ON polrider USING btree ("PolIns") TABLESPACE pg_default;
COMMENT ON TABLE polrider IS 'Policy Coverage Riiders';
COMMENT ON COLUMN polrider."RiderYoungAdultCoverage" IS 'Id code of the coverage template for young adult, ptr to COVERAGE.Coverage';
COMMENT ON COLUMN polrider."RiderChildCoverage" IS 'Coverage template to use for child rider coverage, ptr to COVERAGE.Coverage';
COMMENT ON COLUMN polrider."RiderAgeYoungAdult" IS 'Coverage age of young adult';
COMMENT ON COLUMN polrider."RiderAgeStud" IS 'Age in years that students covered up to.';
COMMENT ON COLUMN polrider."RiderAge" IS 'Age in years that children covered up to.';
COMMENT ON COLUMN polrider."RiderAdultCoverage" IS 'Coverage template to use for adult rider coverage, ptr to COVERAGE.Coverage';
COMMENT ON COLUMN polrider."PolRider" IS 'Primary key, internal ID from sequence';
COMMENT ON COLUMN polrider."PolIns" IS 'Benefit plan that this rider is for, ptr to POLINS.PolIns';
COMMENT ON COLUMN polrider."Description" IS 'Description of the rider';


CREATE  TABLE ppage (
  "Patient" numeric(10,0) NOT NULL,
  "FormCode" character(6) NOT NULL,
  "FItem" numeric(10,0) NOT NULL,
  "Comment" character varying(100),
  "Date" timestamp without time zone,
  "User" numeric(10,0),
  "Status" numeric(5,0),
  "AuditNumber" numeric(5,0) NOT NULL,
  "OrgFItem" numeric(10,0),
  "PtSig" numeric(10,0),
  "PtSigDate" timestamp without time zone,
  "PForm" numeric(10,0) NOT NULL,
  "PPage" numeric(10,0),
  "EntryDateTime" timestamp without time zone,
  "PtSigDateTime" timestamp without time zone,
  CONSTRAINT ppage_primary PRIMARY KEY ("FormCode", "Patient", "PForm", "FItem", "AuditNumber")
) ;
CREATE INDEX IF NOT EXISTS ppage_auditkey ON ppage USING btree ("OrgFItem", "FormCode", "Patient", "PForm") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ppage_codekey ON ppage USING btree ("FormCode", "FItem", "Patient") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ppage_patient ON ppage USING btree ("Patient") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ppage_ppagekey ON ppage USING btree ("PPage") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ppage_statuskey ON ppage USING btree ("FormCode", "Patient", "PForm", "FItem", "Status") TABLESPACE pg_default;
COMMENT ON TABLE ppage IS 'Page of Electronic Patient Record for a patient';
COMMENT ON COLUMN ppage."User" IS 'Entry User ID, ptr to USERS.User or IUSER.iUser';
COMMENT ON COLUMN ppage."Status" IS 'Status (0=Active, 1=Archived/deleted)';
COMMENT ON COLUMN ppage."PtSigDateTime" IS 'Date/time of when the page signature was last changed.';
COMMENT ON COLUMN ppage."PtSigDate" IS 'Date the patient signature was captured';
COMMENT ON COLUMN ppage."PtSig" IS 'Patient signature, ptr to PTSIG.PtSig';
COMMENT ON COLUMN ppage."Patient" IS 'Primary key component, patient that this page is for. Ptr to PATIENT.Patient';
COMMENT ON COLUMN ppage."PPage" IS 'Internal ID from sequence.';
COMMENT ON COLUMN ppage."PForm" IS 'Primary key component, patient form that contains this page. Ptr to PFORM.PForm';
COMMENT ON COLUMN ppage."OrgFItem" IS 'ID code of the FItem when record first entered, ptr to FITEM.FItem ';
COMMENT ON COLUMN ppage."FormCode" IS 'Primary key component, form code that this page is on. Ptr to PFORM.FormCode';
COMMENT ON COLUMN ppage."FItem" IS 'Primary key component, page definition. Ptr to FITEM.FItem';
COMMENT ON COLUMN ppage."EntryDateTime" IS 'Date/time of when the page comment was last changed.';
COMMENT ON COLUMN ppage."Date" IS 'Creation date of page';
COMMENT ON COLUMN ppage."Comment" IS 'Page Comment (shown at bottom of page)';
COMMENT ON COLUMN ppage."AuditNumber" IS 'Primary key component, change number for this record (1=First, 2=Second...)';


CREATE  TABLE ppage_deleted (
  "Patient" numeric(10,0),
  "FormCode" character(6),
  "FItem" numeric(10,0),
  "Comment" character varying(100),
  "Date" timestamp without time zone,
  "User" numeric(10,0),
  "Status" numeric(5,0),
  "AuditNumber" numeric(5,0),
  "OrgFItem" numeric(10,0),
  "PtSig" numeric(10,0),
  "PtSigDate" timestamp without time zone,
  "PForm" numeric(10,0) NOT NULL,
  "PPage" numeric(10,0),
  "EntryDateTime" timestamp without time zone,
  "PtSigDateTime" timestamp without time zone
) ;


CREATE  TABLE ppagesig (
  "PPage" numeric(10,0) NOT NULL,
  "Signee" character varying(30),
  "Name" character varying(60),
  "PtSig" numeric(10,0) NOT NULL,
  CONSTRAINT ppagesig_primary PRIMARY KEY ("PPage", "PtSig")
) ;
COMMENT ON TABLE ppagesig IS 'Signatures other than the patient for an EPR form ';
COMMENT ON COLUMN ppagesig."Signee" IS 'Prompt for who is to sign (eg. Additional Witness)';
COMMENT ON COLUMN ppagesig."PtSig" IS 'Primary key component, signature data for this signature. Ptr to PTSIG.PtSig';
COMMENT ON COLUMN ppagesig."PPage" IS 'Primary key component, EPR form page that requires the signature. Ptr to PPAGE.Ppage';
COMMENT ON COLUMN ppagesig."Name" IS 'Name of the person who signed (eg. John Smith)  ';


CREATE  TABLE ppagesig_deleted (
  "PPage" numeric(10,0),
  "Signee" character varying(30),
  "Name" character varying(60),
  "PtSig" numeric(10,0)
) ;


CREATE  TABLE pracbill (
  "Practice" numeric(10,0) NOT NULL,
  "ProdType" character(1) NOT NULL,
  "ClaimDoctor" character(10),
  CONSTRAINT pracbill_primary PRIMARY KEY ("Practice", "ProdType")
) ;
COMMENT ON TABLE pracbill IS 'Practice billiig overrides';
COMMENT ON COLUMN pracbill."ProdType" IS 'Provider Type';
COMMENT ON COLUMN pracbill."Practice" IS 'Id code of the practice to which this applies';
COMMENT ON COLUMN pracbill."ClaimDoctor" IS 'Billing doctor Id to use when a provider of this type performs work at this practice';


CREATE  TABLE practice (
  "Id" numeric(5,0) NOT NULL,
  "Name" character(40),
  "Address1" character varying(40),
  "Address2" character varying(40),
  "City" character varying(24),
  "Province" character varying(6),
  "Postal" character varying(15),
  "Area" character(4),
  "Phone" character(10),
  "Country" numeric(5,0),
  "DateType" numeric(5,0),
  "AutoLogout" numeric(5,0),
  "Version" numeric(10,0),
  "VersionSrc" character(254),
  "DefaultDoctor" character(10),
  "EDIOfficeId" character(7),
  "EDIPrefix" character(20),
  "EDIPassword" character(12),
  "ChartSortOn" numeric(5,0),
  "SingleDiscipl" numeric(5,0),
  "TimeType" numeric(5,0),
  "RclStatusBooked" character(6),
  "RclStatusUnSch" character(6),
  "PatType" character(6),
  "UpdateTxStatus" numeric(5,0),
  "TxStatusCode" character(6),
  "TxStatusDays" numeric(10,0),
  "AutoPatAssignMsg" numeric(5,0),
  "AutoLabInMsg" numeric(5,0),
  "PmtDiscount" numeric(5,0),
  "OrthoApptCode" character(15),
  "UsingTrojan" numeric(5,0),
  "ChartSortMethod" numeric(5,0),
  "ChartSize" numeric(5,0),
  "ChartSortPattern" character varying(10),
  "NeedTxEstSig" numeric(5,0),
  "NeedPmtPlanSig" numeric(5,0),
  "AutoBatchClaim" numeric(5,0),
  "NeedTxPlanSig" numeric(5,0),
  "AcceptAsg" numeric(5,0),
  "SublistOpt" numeric(5,0),
  "LabChargeTotal" numeric(5,0),
  "AssignOverride" numeric(5,0),
  "OrthoVisitProc" character(7),
  "RequirePrepayment" numeric(5,0),
  "ChartSortFunc" character varying(50),
  "Code" character(6),
  "Inactive" numeric(5,0),
  "DisciplineWarning" numeric(5,0),
  "MultiNoteTypes" numeric(5,0),
  "PtBalInclPlanTxs" numeric(5,0),
  "ShowCommentHeading" numeric(5,0),
  "DefaultFacility" character(6),
  "MedicaidCode" character(7),
  "MedicaidAmount" numeric,
  "MedicaidPtAmount" numeric,
  "BillAtStart" numeric(5,0),
  "NPI" character varying(10),
  "Ext" character varying(6),
  "MedicaidAPGCode" character(7),
  "MedicaidAPGAmount" numeric,
  "SalesTaxRate" numeric,
  "TemplateNotes" numeric(5,0),
  "RclStatusCheckIn" character(6),
  "ReactivateTxStatus" character(6),
  "MedicaidEpisodeCode" character(7),
  "MedicaidEpisodeAmt" numeric,
  "EDINotify" numeric(5,0),
  "EDISticky" numeric(5,0),
  "PlanFeeChgWarning" numeric(5,0),
  "BuildNumber" numeric(10,0),
  "NEAFacId" character varying(8),
  "ReactivatePrompt" numeric(5,0),
  "AutoLabNoteInProg" numeric(5,0),
  "AutoLabNoteComplete" numeric(5,0),
  "AutoLabNoteRedo" numeric(5,0),
  "AutoLabNoteReopen" numeric(5,0),
  CONSTRAINT practice_primary PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE practice IS 'Practice Information';
COMMENT ON COLUMN practice."VersionSrc" IS 'Axium Update file directory (used for auto-update facility)';
COMMENT ON COLUMN practice."Version" IS 'Current Axium database version (used for auto-update facility)';
COMMENT ON COLUMN practice."UsingTrojan" IS 'Using Trojan? (0 = No, 1 = Yes)';
COMMENT ON COLUMN practice."UpdateTxStatus" IS 'Update Tx status? (0 = No, 1 = Yes)';
COMMENT ON COLUMN practice."TxStatusDays" IS 'If UpdateTxStatus - number of days prior to update of status.';
COMMENT ON COLUMN practice."TxStatusCode" IS 'If UpdateTxStatus - default code to update the status to based on number of days selected in TxStatusDays';
COMMENT ON COLUMN practice."TimeType" IS 'Time Format ( 0 = 24 hour clock, 1 = 12 hour AM/PM clock)';
COMMENT ON COLUMN practice."TemplateNotes" IS '0=No, 1=Yes, 2=Yes + is default';
COMMENT ON COLUMN practice."SublistOpt" IS 'When to pop up lab sublist (0=When tx planned, 1=When tx completed, 2=Manually)';
COMMENT ON COLUMN practice."SingleDiscipl" IS 'Practice option, single discipline per claim (0 = No, 1 = Yes)';
COMMENT ON COLUMN practice."ShowCommentHeading" IS 'Show headings when selecting notes? (0 = No, 1 = Yes)';
COMMENT ON COLUMN practice."SalesTaxRate" IS 'sales tax rate as % (eg. 5.5 or 7.0)';
COMMENT ON COLUMN practice."RequirePrepayment" IS 'Require prepayment? (0 = No, 1 = Yes)';
COMMENT ON COLUMN practice."ReactivateTxStatus" IS 'TxStatus to use on inactive treatments that have been reactivated from Tx History. Ptr to STATUS.Status';
COMMENT ON COLUMN practice."ReactivatePrompt" IS 'Prompt for Tx Status when reactivating treatment? (0 = No, 1 = Yes)';
COMMENT ON COLUMN practice."RclStatusUnSch" IS 'Default recall status for unscheduled recall, ptr to RECALL.Recall';
COMMENT ON COLUMN practice."RclStatusCheckIn" IS 'Recall status to set on appt check-in';
COMMENT ON COLUMN practice."RclStatusBooked" IS 'Default recall status for a booked recall, ptr to RECALL.Recall';
COMMENT ON COLUMN practice."PtBalInclPlanTxs" IS 'Patient balance includes payment plan transactions';
COMMENT ON COLUMN practice."Province" IS 'Province / state, ptr to CITY.Province';
COMMENT ON COLUMN practice."Postal" IS 'Postal / zip code, ptr to CITY.Postal';
COMMENT ON COLUMN practice."PmtDiscount" IS 'Apply a payment discount? (0 = No, 1 = Yes) Defaults to Yes.';
COMMENT ON COLUMN practice."PlanFeeChgWarning" IS 'Display a warning if changes are made to a payment plan schedule that has a signature on file? (0=No, 1=Yes)';
COMMENT ON COLUMN practice."Phone" IS 'Telephone Number';
COMMENT ON COLUMN practice."PatType" IS 'Default PatType, ptr to PATTYPE.PatType';
COMMENT ON COLUMN practice."OrthoVisitProc" IS 'Default procedure code to use for indicatng an Ortho visit occured, ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN practice."OrthoApptCode" IS 'Default appointment code for Ortho appointments';
COMMENT ON COLUMN practice."NeedTxPlanSig" IS 'Require signature on treatment plan contracts? (0 = No, 1 = Yes), defaults to 0';
COMMENT ON COLUMN practice."NeedTxEstSig" IS 'Need patient signature for estimates? (0 = No, 1 = Yes)';
COMMENT ON COLUMN practice."NeedPmtPlanSig" IS 'Need patient signature for payment plans? (0 = No, 1 = Yes)';
COMMENT ON COLUMN practice."Name" IS 'Name of the school / dental practice ';
COMMENT ON COLUMN practice."NPI" IS '"NPI" number for the practice';
COMMENT ON COLUMN practice."NEAFacId" IS 'NEA Provider Facility ID#';
COMMENT ON COLUMN practice."MultiNoteTypes" IS 'Type of clinical notes used by the University (0 = General notes only, 1 = Default General notes but SOAP notes allowed, 2 = Default SOAP notes but General Notes allowed';
COMMENT ON COLUMN practice."MedicaidPtAmount" IS 'Amount to bill patient for medicaid visits';
COMMENT ON COLUMN practice."MedicaidEpisodeCode" IS 'NY Medicaid episode billing code. Ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN practice."MedicaidEpisodeAmt" IS 'NY Medicaid Episode billing fee amount';
COMMENT ON COLUMN practice."MedicaidCode" IS 'Default code to use for Medicaid billing, ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN practice."MedicaidAmount" IS 'Amount to bill for medicaid visits';
COMMENT ON COLUMN practice."MedicaidAPGCode" IS 'Procedure code to use as the APG Rate Code. Ptr to PROCEDUR.Procedure.';
COMMENT ON COLUMN practice."MedicaidAPGAmount" IS 'Blended rate amount in dollars.';
COMMENT ON COLUMN practice."LabChargeTotal" IS 'Bill patient the lab charge total from the lab order? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN practice."Inactive" IS 'Inactive practice? (0 = No, 1 = Yes)';
COMMENT ON COLUMN practice."Id" IS 'Primary key';
COMMENT ON COLUMN practice."Ext" IS 'NY Medicaid blended billing amount';
COMMENT ON COLUMN practice."EDISticky" IS 'Add patient sticky note in case of claim error? (0=No, 1=Yes)';
COMMENT ON COLUMN practice."EDIPrefix" IS 'NEIC / "EDI" Prefix for claim submissions';
COMMENT ON COLUMN practice."EDIPassword" IS 'NEIC / "EDI" password for claim submissions';
COMMENT ON COLUMN practice."EDIOfficeId" IS 'NEIC /"EDI" office ID for claim submissions';
COMMENT ON COLUMN practice."EDINotify" IS 'Notify provider in case of claim error? (0=No, 1=Yes)';
COMMENT ON COLUMN practice."DisciplineWarning" IS 'Warn if discipline not specified (0 = No, 1 = For all I/C treatments, 2= For all P/I/C treatments.)';
COMMENT ON COLUMN practice."DefaultFacility" IS 'Default Facility for use when entering medical treatments. ';
COMMENT ON COLUMN practice."DefaultDoctor" IS 'Id code to identify the default billing doctor / fee schedule, ptr to PRODUCER.Producer';
COMMENT ON COLUMN practice."DateType" IS 'Date format to use within Axium (0=dd/mm/yyyy, 1=mm/dd/yyyy)';
COMMENT ON COLUMN practice."Country" IS 'Country (0=Canada, 1=USA, 2=Netherlands)';
COMMENT ON COLUMN practice."Code" IS 'Unique code used to identify this practice, for reporting purposes';
COMMENT ON COLUMN practice."City" IS 'City, ptr to CITY.City';
COMMENT ON COLUMN practice."ChartSortPattern" IS 'If ChartSortOn = 1, letter combination that represents the chart sort pattern';
COMMENT ON COLUMN practice."ChartSortOn" IS 'Practice option, works with the chart tracking option ChartSort, a number to represent the amount of characters from the chart to display. For Michigan - Chart Sort On = 3';
COMMENT ON COLUMN practice."ChartSortMethod" IS ',Defaults to 0';
COMMENT ON COLUMN practice."ChartSortFunc" IS 'Chart sort function name';
COMMENT ON COLUMN practice."ChartSize" IS ',Defaults to 0';
COMMENT ON COLUMN practice."BuildNumber" IS 'Current axiUm database build # (used for auto-update)';
COMMENT ON COLUMN practice."BillAtStart" IS 'Bill total when in process? (0 = No, 1 = Yes, 2 = Yes but cannot submit)';
COMMENT ON COLUMN practice."AutoPatAssignMsg" IS 'Enable auto email when assigning patients? (0 = No, 1 = Yes), defaults to 1. ';
COMMENT ON COLUMN practice."AutoLogout" IS 'Auto Logout inactive users after X minutes of inactivity';
COMMENT ON COLUMN practice."AutoLabNoteReopen" IS 'Automatically create clinical lab note when lab is reopened? (0=No, 1=Yes)';
COMMENT ON COLUMN practice."AutoLabNoteRedo" IS 'Automatically create clinical lab note when lab is set to Redo? (0=No, 1=Yes)';
COMMENT ON COLUMN practice."AutoLabNoteInProg" IS 'Automatically create clinical lab note when lab is set to In Progress? (0=No, 1=Yes)';
COMMENT ON COLUMN practice."AutoLabNoteComplete" IS 'Automatically create clinical lab note when lab is set to Complete? (0=No, 1=Yes)';
COMMENT ON COLUMN practice."AutoLabInMsg" IS 'Enable auto email when lab order in OR out. (0 = No, 1 = Yes), defaults to 1. ';
COMMENT ON COLUMN practice."AutoBatchClaim" IS 'Auto batch claims on check out? (0 = No, 1 = Yes), defaults to 0';
COMMENT ON COLUMN practice."AssignOverride" IS 'Accept assignment? (0 = No, 1 = Yes)';
COMMENT ON COLUMN practice."Area" IS 'Telephone Area Code';
COMMENT ON COLUMN practice."Address2" IS 'Address line 2';
COMMENT ON COLUMN practice."Address1" IS 'Address line 1';
COMMENT ON COLUMN practice."AcceptAsg" IS 'Accept assignment? (0 = No, 1 = Yes), defaults to 1';


CREATE  TABLE prdcat (
  "PrdType" numeric(10,0) NOT NULL,
  "PrdCat" character(6) NOT NULL,
  "Description" character varying(30),
  "Inactive" numeric(5,0),
  CONSTRAINT prdcat_primary PRIMARY KEY ("PrdType", "PrdCat")
) ;
COMMENT ON TABLE prdcat IS 'Product Categories';
COMMENT ON COLUMN prdcat."PrdType" IS 'Id code to identify the product type, ptr to PRDTYPE.PrdType';
COMMENT ON COLUMN prdcat."PrdCat" IS 'Code to identify the prodcut category';
COMMENT ON COLUMN prdcat."Inactive" IS 'Inactive? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN prdcat."Description" IS 'Full description of the product category.';


CREATE  TABLE prdloc (
  "Product" numeric(10,0) NOT NULL,
  "InvLoc" character(6) NOT NULL,
  "Stocked" numeric(5,0),
  "Inactive" numeric(5,0),
  "Bin" character varying(12),
  "TrackUsage" numeric(5,0),
  "CanOrderFrom" numeric(5,0),
  "ReorderCount" numeric(5,0),
  "MinToOrder" numeric(5,0),
  "StdToOrder" numeric(5,0),
  "MinCount" numeric(5,0),
  "MaxCount" numeric(5,0),
  "Balance" numeric,
  "LastCount" numeric,
  "LastCountDate" timestamp without time zone,
  CONSTRAINT prdloc_primary PRIMARY KEY ("Product", "InvLoc")
) ;
COMMENT ON TABLE prdloc IS 'Warehouse and Store product information';
COMMENT ON COLUMN prdloc."TrackUsage" IS 'Track usage? (0=Caounted, 1=decrease as used)';
COMMENT ON COLUMN prdloc."Stocked" IS 'Item stocked at this location? (0 = No, 1= Yes)';
COMMENT ON COLUMN prdloc."StdToOrder" IS 'Standard quantity to order';
COMMENT ON COLUMN prdloc."ReorderCount" IS 'The point at which to re-order stock of this product';
COMMENT ON COLUMN prdloc."Product" IS 'Id code to identify the product at this location. Ptr to PRODUCT.Product';
COMMENT ON COLUMN prdloc."MinToOrder" IS 'Minimum quantity to order';
COMMENT ON COLUMN prdloc."MinCount" IS 'Minimum needed on hand';
COMMENT ON COLUMN prdloc."MaxCount" IS 'Maximum needed on hand';
COMMENT ON COLUMN prdloc."LastCountDate" IS 'Date of last count of product at location';
COMMENT ON COLUMN prdloc."LastCount" IS 'Quantity at last count';
COMMENT ON COLUMN prdloc."InvLoc" IS 'Id code to identify the location. Ptr to INVLOC.InvLoc';
COMMENT ON COLUMN prdloc."Inactive" IS 'Inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN prdloc."CanOrderFrom" IS 'Can be ordered from this location? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN prdloc."Bin" IS 'Area kept, like “B427-02”';
COMMENT ON COLUMN prdloc."Balance" IS 'Quantity currently at Store';


CREATE  TABLE prdtype (
  "PrdType" numeric(10,0) NOT NULL,
  "Description" character varying(30),
  CONSTRAINT prdtype_primary PRIMARY KEY ("PrdType")
) ;
COMMENT ON TABLE prdtype IS 'Product Types (Catalogues)';
COMMENT ON COLUMN prdtype."PrdType" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN prdtype."Description" IS 'Full description of product type. Like “Office Supplies”, “Dental Sundries”, …';


CREATE  TABLE prdunit (
  "PrdUnit" numeric(10,0) NOT NULL,
  "Description" character varying(10),
  "IsDividable" numeric(5,0),
  "Inactive" numeric(5,0),
  CONSTRAINT prdunit_primary PRIMARY KEY ("PrdUnit")
) ;
COMMENT ON TABLE prdunit IS 'Unit sizes of inventory';
COMMENT ON COLUMN prdunit."PrdUnit" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN prdunit."IsDividable" IS 'Is this unit divided into another unit size before distribution? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN prdunit."Inactive" IS 'Inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN prdunit."Description" IS 'Description of the product unit. Like “Items”, “Boxes”, “mls”';


CREATE  TABLE prescrih (
  "PrescripH" numeric(10,0) NOT NULL,
  "Prescription" numeric(10,0),
  "Patient" numeric(10,0),
  "Date" timestamp without time zone,
  "Practice" numeric(5,0),
  "Provider" character(10),
  "DrugDescription" character varying(100),
  "Dose" character varying(25),
  "DrugFrqDesc" character varying(250),
  "Total" character varying(7),
  "Refills" numeric(5,0),
  "Note" character varying(100),
  "IsPhoned" numeric(5,0),
  "Area" character(4),
  "Telephone" character(8),
  "Pharmacy" character varying(50),
  "Audit" numeric(10,0),
  "ApprovalUser" numeric(10,0),
  "ApprovalDate" timestamp without time zone,
  "IsVoided" numeric(5,0),
  "VoidReason" character varying(50),
  "VoidAudit" numeric(10,0),
  "VoidAppUser" numeric(10,0),
  "Reference" character varying(30),
  "Custom1" character(6),
  "Custom2" character(6),
  "IsFaxed" numeric(5,0),
  "FaxArea" character(4),
  "FaxPhone" character(8),
  "Drug" character(10),
  "PrescripType" numeric(5,0),
  "StartDate" timestamp without time zone,
  "EndDate" timestamp without time zone,
  "Deleted" numeric(5,0),
  "eRxSyncAudit" numeric(10,0),
  "RxNorm" character varying(8),
  "RcopiaID" character varying(32),
  "DrugSchedule" character varying(30),
  "IsSentEDI" numeric(5,0),
  "IsPrinted" numeric(5,0),
  CONSTRAINT prescrih_primary PRIMARY KEY ("PrescripH")
) ;
CREATE INDEX IF NOT EXISTS prescrih_patient ON prescrih USING btree ("Patient") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS prescrih_prescription ON prescrih USING btree ("Prescription") TABLESPACE pg_default;
COMMENT ON TABLE prescrih IS 'History table for Prescriptions / Medication records';
COMMENT ON COLUMN prescrih."eRxSyncAudit" IS 'Timestamp of when record was last synchronized with Rcopia, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN prescrih."VoidReason" IS 'Reason the record was voided';
COMMENT ON COLUMN prescrih."VoidAudit" IS 'Audit history, ptr to AUDITHIS.Audit - Audit of user who voided the prescription record';
COMMENT ON COLUMN prescrih."VoidAppUser" IS 'User ID of the person that approved the void';
COMMENT ON COLUMN prescrih."Total" IS 'Total number of pills, or total amount of liquid prescribed';
COMMENT ON COLUMN prescrih."Telephone" IS 'If PRESCRIP.IsPhoned = 1, number called';
COMMENT ON COLUMN prescrih."StartDate" IS 'Date that the patient started or will start taking the medication.';
COMMENT ON COLUMN prescrih."RxNorm" IS 'National Drug Code (US) for medication/dosage combination.';
COMMENT ON COLUMN prescrih."Refills" IS 'Number of refills (-1=PRN, 0+ number of allow refills)';
COMMENT ON COLUMN prescrih."Reference" IS 'Field to store a reference Id or number for this prescription (optional).';
COMMENT ON COLUMN prescrih."RcopiaID" IS 'Rcopia ID for this prescription / medication';
COMMENT ON COLUMN prescrih."Provider" IS 'Id code of provider writing prescription, ptr to PRODUCER.Producer ';
COMMENT ON COLUMN prescrih."Prescription" IS 'ID code of the prescription record, internal ID from sequence';
COMMENT ON COLUMN prescrih."PrescripType" IS 'Type of record (0 = Medication, 1 = axiUm paper prescription, 2 = Rcopia e-Rx)';
COMMENT ON COLUMN prescrih."PrescripH" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN prescrih."Practice" IS 'ID code to identify the practice prescription written at, ptr to PRACTICE.Id';
COMMENT ON COLUMN prescrih."Pharmacy" IS 'If PRESCRIP.IsPhoned = 1, name of the pharmacy ';
COMMENT ON COLUMN prescrih."Patient" IS 'ID code of the patient prescription is written for, ptr to PATIENT.Patient';
COMMENT ON COLUMN prescrih."Note" IS 'Free form text field for comments and special instructions added to the prescription. ';
COMMENT ON COLUMN prescrih."IsVoided" IS 'Is voided? (0 = No, 1 = Yes)';
COMMENT ON COLUMN prescrih."IsSentEDI" IS 'Is sent via "EDI" (electronically)?  0-no; 1-yes; 2-unknown';
COMMENT ON COLUMN prescrih."IsPrinted" IS 'Is printed?  0-no; 1-yes; 2-unknown';
COMMENT ON COLUMN prescrih."IsPhoned" IS 'Phoned in to pharmacy? (0 = No, 1 = Yes)';
COMMENT ON COLUMN prescrih."IsFaxed" IS 'Prescription faxed to pharmacy? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN prescrih."FaxPhone" IS 'Pharmacy fax number';
COMMENT ON COLUMN prescrih."FaxArea" IS 'Area code of the pharmacy fax number ';
COMMENT ON COLUMN prescrih."EndDate" IS 'Date that the patient stopped or will stop taking the medication. ';
COMMENT ON COLUMN prescrih."DrugSchedule" IS 'Used to describe the schedule for controlled substances, US: 1-5, CA: 1-8, DU: 1-2';
COMMENT ON COLUMN prescrih."DrugFrqDesc" IS 'Frequency instructions';
COMMENT ON COLUMN prescrih."DrugDescription" IS 'Description of the drug. May be pulled from the drug table (DRUG.Description) but could also be free text entry by user';
COMMENT ON COLUMN prescrih."Drug" IS 'ID code of the drug, ptr to DRUG.DRUG';
COMMENT ON COLUMN prescrih."Dose" IS 'Dosage prescribed';
COMMENT ON COLUMN prescrih."Deleted" IS 'If an existing medication, is it deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN prescrih."Date" IS 'Date prescription written for';
COMMENT ON COLUMN prescrih."Custom2" IS 'Id code of the second custom field to display on the prescription window, ptr to CUSTCODE.Code';
COMMENT ON COLUMN prescrih."Custom1" IS 'Id code of the first custom field to display on the prescription window, ptr to CUSTCODE.Code';
COMMENT ON COLUMN prescrih."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN prescrih."Area" IS 'If PRESCRIP.IsPhoned = 1, area code of number called';
COMMENT ON COLUMN prescrih."ApprovalUser" IS 'ID code of the approval user, ptr to USERS.User';
COMMENT ON COLUMN prescrih."ApprovalDate" IS 'Date of the approval ';


CREATE  TABLE prescrip (
  "Prescription" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "Date" timestamp without time zone,
  "Practice" numeric(5,0),
  "Provider" character(10),
  "DrugDescription" character varying(100),
  "Dose" character varying(25),
  "DrugFrqDesc" character varying(250),
  "Total" character varying(7),
  "Refills" numeric(5,0),
  "Note" character varying(100),
  "IsPhoned" numeric(5,0),
  "Area" character(4),
  "Telephone" character(8),
  "Pharmacy" character varying(50),
  "Audit" numeric(10,0),
  "ApprovalUser" numeric(10,0),
  "ApprovalDate" timestamp without time zone,
  "IsVoided" numeric(5,0),
  "VoidReason" character varying(50),
  "VoidAudit" numeric(10,0),
  "VoidAppUser" numeric(10,0),
  "Reference" character varying(30),
  "Custom1" character(6),
  "Custom2" character(6),
  "IsFaxed" numeric(5,0),
  "FaxArea" character(4),
  "FaxPhone" character(8),
  "Drug" character(10),
  "PrescripType" numeric(5,0),
  "StartDate" timestamp without time zone,
  "EndDate" timestamp without time zone,
  "Deleted" numeric(5,0),
  "eRxSyncAudit" numeric(10,0),
  "RxNorm" character varying(8),
  "RcopiaID" character varying(32),
  "DrugSchedule" character varying(30),
  "IsSentEDI" numeric(5,0),
  "IsPrinted" numeric(5,0),
  CONSTRAINT prescrip_primary PRIMARY KEY ("Prescription")
) ;
CREATE INDEX IF NOT EXISTS prescrip_patient ON prescrip USING btree ("Patient") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS prescrip_rcopiaidkey ON prescrip USING btree ("RcopiaID") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS prescrip_syncauditkey ON prescrip USING btree ("eRxSyncAudit") TABLESPACE pg_default;
COMMENT ON TABLE prescrip IS 'Prescription / Medication records';
COMMENT ON COLUMN prescrip."eRxSyncAudit" IS 'Timestamp of when record was last synchronized with Rcopia, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN prescrip."VoidReason" IS 'Reason the record was voided';
COMMENT ON COLUMN prescrip."VoidAudit" IS 'Audit history, ptr to AUDITHIS.Audit - Audit of user who voided the prescription record';
COMMENT ON COLUMN prescrip."VoidAppUser" IS 'User ID of the person that approved the void';
COMMENT ON COLUMN prescrip."Total" IS 'Total number of pills, or total amount of liquid prescribed';
COMMENT ON COLUMN prescrip."Telephone" IS 'If PRESCRIP.IsPhoned = 1, number called';
COMMENT ON COLUMN prescrip."StartDate" IS 'Date that the patient started or will start taking the medication.';
COMMENT ON COLUMN prescrip."RxNorm" IS 'National Drug Code (US) for medication/dosage combination.';
COMMENT ON COLUMN prescrip."Refills" IS 'Number of refills (-1=PRN, 0+ number of allow refills)';
COMMENT ON COLUMN prescrip."Reference" IS 'Field to store a reference Id or number for this prescription (optional).';
COMMENT ON COLUMN prescrip."RcopiaID" IS 'Rcopia ID for this prescription / medication';
COMMENT ON COLUMN prescrip."Provider" IS 'Id code of provider writing prescription, ptr to PRODUCER.Producer ';
COMMENT ON COLUMN prescrip."Prescription" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN prescrip."PrescripType" IS 'Type of record (0 = Medication, 1 = axiUm paper prescription, 2 = Rcopia e-Rx)';
COMMENT ON COLUMN prescrip."Practice" IS 'ID code to identify the practice prescription written at, ptr to PRACTICE.Id';
COMMENT ON COLUMN prescrip."Pharmacy" IS 'If PRESCRIP.IsPhoned = 1, name of the pharmacy ';
COMMENT ON COLUMN prescrip."Patient" IS 'ID code of the patient prescription is written for, ptr to PATIENT.Patient';
COMMENT ON COLUMN prescrip."Note" IS 'Free form text field for comments and special instructions added to the prescription. ';
COMMENT ON COLUMN prescrip."IsVoided" IS 'Is voided? (0 = No, 1 = Yes)';
COMMENT ON COLUMN prescrip."IsSentEDI" IS 'Is sent via "EDI" (electronically)?  0-no; 1-yes; 2-unknown';
COMMENT ON COLUMN prescrip."IsPrinted" IS 'Is printed?  0-no; 1-yes; 2-unknown';
COMMENT ON COLUMN prescrip."IsPhoned" IS 'Phoned in to pharmacy? (0 = No, 1 = Yes)';
COMMENT ON COLUMN prescrip."IsFaxed" IS 'Prescription faxed to pharmacy? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN prescrip."FaxPhone" IS 'Pharmacy fax number';
COMMENT ON COLUMN prescrip."FaxArea" IS 'Area code of the pharmacy fax number ';
COMMENT ON COLUMN prescrip."EndDate" IS 'Date that the patient stopped or will stop taking the medication. ';
COMMENT ON COLUMN prescrip."DrugSchedule" IS 'Used to describe the schedule for controlled substances, US: 1-5, CA: 1-8, DU: 1-2';
COMMENT ON COLUMN prescrip."DrugFrqDesc" IS 'Frequency instructions';
COMMENT ON COLUMN prescrip."DrugDescription" IS 'Description of the drug. May be pulled from the drug table (DRUG.Description) but could also be free text entry by user';
COMMENT ON COLUMN prescrip."Drug" IS 'ID code of the drug, ptr to DRUG.DRUG';
COMMENT ON COLUMN prescrip."Dose" IS 'Dosage prescribed';
COMMENT ON COLUMN prescrip."Deleted" IS 'If an existing medication, is it deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN prescrip."Date" IS 'Date prescription written for';
COMMENT ON COLUMN prescrip."Custom2" IS 'Id code of the second custom field to display on the prescription window, ptr to CUSTCODE.Code';
COMMENT ON COLUMN prescrip."Custom1" IS 'Id code of the first custom field to display on the prescription window, ptr to CUSTCODE.Code';
COMMENT ON COLUMN prescrip."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN prescrip."Area" IS 'If PRESCRIP.IsPhoned = 1, area code of number called';
COMMENT ON COLUMN prescrip."ApprovalUser" IS 'ID code of the approval user, ptr to USERS.User';
COMMENT ON COLUMN prescrip."ApprovalDate" IS 'Date of the approval ';


CREATE  TABLE prescrip_dates (
  oneday timestamp without time zone
) ;
COMMENT ON TABLE prescrip_dates IS 'Table used by PRESCRIP_ASAT view that contains all dates that can be used by the PRESCRIH table';
COMMENT ON COLUMN prescrip_dates.oneday IS 'A date that can be used in PRESCRIH.';


CREATE  TABLE prevcare (
  "PrevCare" character(6) NOT NULL,
  "Type" numeric(5,0),
  "Description" character varying(30),
  "CycleMonths" numeric(5,0),
  "WithinDays" numeric(5,0),
  "Inactive" numeric(5,0),
  CONSTRAINT prevcare_primary PRIMARY KEY ("PrevCare")
) ;
COMMENT ON TABLE prevcare IS 'Preventive Care Codes';
COMMENT ON COLUMN prevcare."WithinDays" IS 'Care should be completed if it is within this number of days of the hygiene appointment. ';
COMMENT ON COLUMN prevcare."Type" IS 'Type of preventive care (1=Exam, 2=X-Ray)';
COMMENT ON COLUMN prevcare."PrevCare" IS 'Primary key, code to identify the preventive care type.';
COMMENT ON COLUMN prevcare."Inactive" IS 'Inactive code? (0=No, 1=Yes)';
COMMENT ON COLUMN prevcare."Description" IS 'Description of the preventive care.';
COMMENT ON COLUMN prevcare."CycleMonths" IS 'Default number of months between care.';


CREATE  TABLE prlevel (
  "Provider" character(10) NOT NULL,
  "CompLevel" character(6) NOT NULL,
  "Date" timestamp without time zone,
  "CreationUser" numeric(10,0),
  CONSTRAINT prlevel_primary PRIMARY KEY ("Provider", "CompLevel")
) ;
COMMENT ON TABLE prlevel IS 'Provider Competency Levels';
COMMENT ON COLUMN prlevel."Provider" IS 'Primary key component, the provider who achieved this competency level. Ptr to PRODUCER.Producer';
COMMENT ON COLUMN prlevel."Date" IS 'Date level achieved';
COMMENT ON COLUMN prlevel."CreationUser" IS 'ID code of the entry user, ptr to USERS.User';
COMMENT ON COLUMN prlevel."CompLevel" IS 'Primary key component, the competency level achieved. Ptr to CLEVEL.CompLevel';


CREATE  TABLE problem (
  "Problem" character(7) NOT NULL,
  "Description" character(50),
  "LevelDesc" character(50),
  "Level" numeric(5,0),
  "IsNode" numeric(5,0),
  "Deleted" numeric(5,0),
  "Id" numeric(10,0) NOT NULL,
  "ShortDesc" character varying(20),
  "Rank" numeric(5,0),
  "SiteBased" numeric(5,0),
  "SurfaceBased" numeric(5,0),
  CONSTRAINT problem_primary PRIMARY KEY ("Problem")
) ;
CREATE INDEX IF NOT EXISTS problem_id ON problem USING btree ("Id") TABLESPACE pg_default;
COMMENT ON TABLE problem IS 'Problem Codes';
COMMENT ON COLUMN problem."SurfaceBased" IS 'Is the problem surface-based? (0=No, 1=Yes, 2=Optional)';
COMMENT ON COLUMN problem."SiteBased" IS 'Is the problem site-based? (0=No, 1=Yes, 2=Optional)';
COMMENT ON COLUMN problem."ShortDesc" IS 'Short description of the problem.';
COMMENT ON COLUMN problem."Rank" IS 'Internal number from 1-9999, for sorting intellisense results in ascending order.';
COMMENT ON COLUMN problem."Problem" IS 'Primary key, ID code to identify the problem. ';
COMMENT ON COLUMN problem."LevelDesc" IS 'Description of the problem, used in hierarchy list.';
COMMENT ON COLUMN problem."Level" IS 'Level of item in hierarchy list (0=Top Level, 1=SubLevel, 2=Item)';
COMMENT ON COLUMN problem."IsNode" IS 'Is item a node? (0 = No it is a topic, 1 = Yes)';
COMMENT ON COLUMN problem."Id" IS 'Internal ID from sequence. ';
COMMENT ON COLUMN problem."Description" IS 'Description of the problem';
COMMENT ON COLUMN problem."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';


CREATE  TABLE probslev (
  "SLevel" numeric(10,0) NOT NULL,
  "Problem" character(7) NOT NULL,
  CONSTRAINT probslev_primary PRIMARY KEY ("SLevel", "Problem")
) ;
COMMENT ON TABLE probslev IS 'Problem Code Access ';
COMMENT ON COLUMN probslev."SLevel" IS 'Primary key component, security level access is being defined for. Ptr to SLEVEL.SLevel';
COMMENT ON COLUMN probslev."Problem" IS 'Primary key component, problem code to allow this level access to. Ptr to PROBLEM.Problem.';


CREATE  TABLE procedur (
  "Procedure" character(7) NOT NULL,
  "Insurance" character(7),
  "Description" character varying(60),
  "Print" numeric(5,0),
  "LabReq" numeric(5,0),
  "IsLab" numeric(5,0),
  "Factor" numeric(5,0),
  "Hygienist" numeric(5,0),
  "Units" numeric,
  "RelValue" numeric,
  "Global" numeric(5,0),
  "Local" numeric(5,0),
  "Type" numeric(5,0),
  "Zone" numeric(5,0),
  "MaxSurface" numeric(10,0),
  "Age" numeric(5,0),
  "Prompt" numeric(5,0),
  "ColorStart" numeric(10,0),
  "ColorEnd" numeric(10,0),
  "CanAttach" numeric(5,0),
  "IsOrthoFee" numeric(5,0),
  "Discipline" character(15),
  "Category" numeric(5,0),
  "Level" numeric(5,0),
  "LevelDesc" character varying(60),
  "IsProcedure" numeric(5,0),
  "Deleted" numeric(5,0),
  "Id" numeric(10,0),
  "RequireGrading" numeric(5,0),
  "IsStepParent" numeric(5,0),
  "IsStepChild" numeric(5,0),
  "ParentProcedure" character(7),
  "StepNumber" numeric(5,0),
  "OptionalStep" numeric(5,0),
  "CodeType" numeric(5,0),
  "PrintOnClaim" numeric(5,0),
  "BudgetCode" character(10),
  "ParentGroup" character(7),
  "CompLevel" character(6),
  "MaxRequests" numeric(5,0),
  "RequiresRecall" numeric(5,0),
  "IsRecall" numeric(5,0),
  "AlternateCode" character(7),
  "IsXRayExposure" numeric(5,0),
  "CorrespondCode" character(7),
  "FillStyle" numeric(5,0),
  "HasSymbol" numeric(5,0),
  "Symbol" character(6),
  "OldCode" character(7),
  "ExposureCount" numeric(5,0),
  "CondType" numeric(5,0),
  "AddLab" numeric(5,0),
  "DaysAtLab" numeric(5,0),
  "OrMoreSurfaces" numeric(5,0),
  "EDIExempt" numeric(5,0),
  "Inactive" numeric(5,0),
  "AdditionalInfo" numeric(5,0),
  "PreventInProc" numeric(5,0),
  "DefaultPhase" character(2),
  "RequireTxConsent" numeric(5,0),
  "PrintDesc" character varying(30),
  "IsRemoval" numeric(5,0),
  "DiagnosisNotReqd" numeric(5,0),
  "ReqImplnt" numeric(5,0),
  "ImplntIsRemoval" numeric(5,0),
  CONSTRAINT procedur_primary PRIMARY KEY ("Procedure")
) ;
CREATE INDEX IF NOT EXISTS procedur_category ON procedur USING btree ("Category", "Procedure") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS procedur_groupkey ON procedur USING btree ("Category", "ParentGroup") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS procedur_id ON procedur USING btree ("Id") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS procedur_insurance ON procedur USING btree ("Insurance") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS procedur_parentkey ON procedur USING btree ("Category", "ParentProcedure") TABLESPACE pg_default;
COMMENT ON TABLE procedur IS 'Procedure Codes (ADA, CPT, Conditions, and Materials)';
COMMENT ON COLUMN procedur."Zone" IS 'Represents where the graphics should be drawn on the odontogram. The following are acceptable values of (Type, Zone) combinations: {0,0 : Text, N/A}, {1,0 : Illustrated, Nowhere}, {1,1 : Illustrated, Surfaces on Crown/Boxes}, {1,2 : Illustrated, Root/Root Triangle}, {1,3 : Illustrated, Crown}, {2,0 : Object, N/A}, {2,1 : Object, Bridge}, {2,2 : Object, Implant}, {2,3 : Object, Retainer Bar},{2,4 : Object, Pontic}, {3,0 : Extraction, N/A}';
COMMENT ON COLUMN procedur."Units" IS 'For factoring units, the amount of a single unit.';
COMMENT ON COLUMN procedur."Type" IS 'Graphic Detail -> Type value for the procedure. Represents how the procedure should affect the odontogram (0=Text, 1=Illustrated, 2=Object, 3=Extraction, 5=Impacted)';
COMMENT ON COLUMN procedur."Symbol" IS 'If HasSymbol=1, the symbol to use. Ptr to SYMBOL.Symbol';
COMMENT ON COLUMN procedur."StepNumber" IS 'If IsStepChild=1, then the step number (1, 2,...)';
COMMENT ON COLUMN procedur."RequiresRecall" IS 'Does procedure require recall(s)? (0=No, 1=Yes)';
COMMENT ON COLUMN procedur."RequireTxConsent" IS 'Does procedure require patient consent? (0=No, 1=Yes)';
COMMENT ON COLUMN procedur."RequireGrading" IS 'Does procedure require grading? (0=No, 1=Yes)';
COMMENT ON COLUMN procedur."ReqImplnt" IS 'Does procedure require Dental Device? (0=No, 1=Yes)';
COMMENT ON COLUMN procedur."RelValue" IS 'RVU / CPV for procedure. ';
COMMENT ON COLUMN procedur."Prompt" IS 'Prompt for additional code? (0=No, 1=Yes)';
COMMENT ON COLUMN procedur."Procedure" IS 'Primary key, the procedure code.';
COMMENT ON COLUMN procedur."PrintOnClaim" IS 'Submit on insurance claim forms? (0=No, 1=Yes [unless Total = $0], 2=Yes [even if Total = $0])';
COMMENT ON COLUMN procedur."PrintDesc" IS 'Short description of the procedure, to be printed on reports given to the patient.';
COMMENT ON COLUMN procedur."Print" IS 'DEPRECATED';
COMMENT ON COLUMN procedur."PreventInProc" IS 'Prevent entry of this procedure as In-Process? (0=No, 1=Yes)';
COMMENT ON COLUMN procedur."ParentProcedure" IS 'If IsStepChild=1, the procedure code of the parent procedure. Ptr to PROCEDUR.Procedure.';
COMMENT ON COLUMN procedur."ParentGroup" IS 'Procedure group group that this procedure belongs to. Used for auto-switching procedure codes.';
COMMENT ON COLUMN procedur."OrMoreSurfaces" IS 'Can this procedure be performed on more surfaces than indicated? (0=No, 1=Yes)';
COMMENT ON COLUMN procedur."OptionalStep" IS 'If IsStepChild=1, is this an optional step? (0=Required Step, 1=Optional)';
COMMENT ON COLUMN procedur."OldCode" IS 'For Trojan lookup, the old ADA code that corresponds to the current code. ';
COMMENT ON COLUMN procedur."MaxSurface" IS 'Number of surfaces that this procedure requires (1-5)';
COMMENT ON COLUMN procedur."MaxRequests" IS 'Maximum number of requests for this procedure. ';
COMMENT ON COLUMN procedur."Local" IS 'Represents the sub-area that the procedure applies to. The following are acceptable values of (Global, Local) combinations: {0,0 : N/A,N/A}, {1,0 : Arch, OK for both arches}, {1,1 : Arch, Upper}, {1,2 : Arch, Lower}, {2,0 : Quadrant, N/A}, {3,0 : Sextant, N/A}, {4,0 : Tooth, OK for all teeth}, {4,1 : Tooth, Anterior}, {4,2 : Tooth, Posterior}, {4,3 : Tooth, Premolar}, {4,4 : Tooth, Molar}, {4,5 : Tooth, Anterior or Bicuspid}, {5,0 : Full Mouth, N/A}';
COMMENT ON COLUMN procedur."LevelDesc" IS 'Node description, short description for procedure that is displayed in the tree-list.';
COMMENT ON COLUMN procedur."Level" IS 'Level of procedure in tree-list (0 = Topic, 1 = Sub-Topic, 2 = Item, 3 = Sub-Item)';
COMMENT ON COLUMN procedur."LabReq" IS 'Does procedure require a lab? (0=No, 1=Yes)';
COMMENT ON COLUMN procedur."IsXRayExposure" IS 'Is an X-Ray exposure? (0=No, 1=Yes)';
COMMENT ON COLUMN procedur."IsStepParent" IS 'Procedure has steps? (0=No, 1=Yes)';
COMMENT ON COLUMN procedur."IsStepChild" IS 'Is a procedure step? (0=No, 1=Yes)';
COMMENT ON COLUMN procedur."IsRemoval" IS 'For Object type procedures, is this a removal? (0=No, 1=Yes)';
COMMENT ON COLUMN procedur."IsRecall" IS 'Is this a recall procedure? (0=No, 1=Yes)';
COMMENT ON COLUMN procedur."IsProcedure" IS 'Is this a procedure? (0 = No, 1 = Yes [Dental or Medical], 2 = Condition, 3 = Material)';
COMMENT ON COLUMN procedur."IsOrthoFee" IS 'Is this an ortho fee? (0=No, 1=Yes)';
COMMENT ON COLUMN procedur."IsLab" IS 'Is this a lab procedure? (0=No, 1=Yes)';
COMMENT ON COLUMN procedur."Insurance" IS 'Procedure code to use for insurance claims. ';
COMMENT ON COLUMN procedur."Inactive" IS 'Inactive procedure? (0=No, 1=Yes) ';
COMMENT ON COLUMN procedur."ImplntIsRemoval" IS 'Does the Dental Device is for Removal? (0=No, 1=Yes)';
COMMENT ON COLUMN procedur."Id" IS 'Internal ID, from sequence.';
COMMENT ON COLUMN procedur."Hygienist" IS 'DEPRECATED';
COMMENT ON COLUMN procedur."HasSymbol" IS 'Does procedure has a symbol? (0=No, 1=Yes)';
COMMENT ON COLUMN procedur."Global" IS 'Represents the area that the procedure applies to (0=N/A, 1=Arch, 2=Quadrant, 3=Sextant, 4=Tooth, 5=Full Mouth)';
COMMENT ON COLUMN procedur."FillStyle" IS 'Number to represent the fill style (0=Solid Color, 1=Transparent Diagonal Hatched, 2=Transparent Crosshatched, 3=Transparent Downward Diagonal Lines, 4=Transparent Upward Diagonal Lines, 5=Diagonal Hatched, 6=Crosshatched, 7=Downward Diagonal Lines, 8=Upward Diagonal Lines)';
COMMENT ON COLUMN procedur."Factor" IS 'Factor units performed for calculating amount of charge (0=No, 1=Yes)';
COMMENT ON COLUMN procedur."ExposureCount" IS 'If IsXRayExposure=1, the number of exposures that this procedure is counted as. ';
COMMENT ON COLUMN procedur."EDIExempt" IS 'EDI exempt? (0=No, 1=Yes)';
COMMENT ON COLUMN procedur."Discipline" IS 'Default discipline for this procedure, ptr to CLASS.Class';
COMMENT ON COLUMN procedur."DiagnosisNotReqd" IS 'Diagnosis required for procedures? (0=No: required based on System option (default), 1=Yes)';
COMMENT ON COLUMN procedur."Description" IS 'Description of this procedure.';
COMMENT ON COLUMN procedur."Deleted" IS 'Deleted? (0 = No,1 = Yes)';
COMMENT ON COLUMN procedur."DefaultPhase" IS 'Default phase order for this procedure.';
COMMENT ON COLUMN procedur."DaysAtLab" IS 'Expected number of days out at the lab this procedure will require.';
COMMENT ON COLUMN procedur."CorrespondCode" IS 'For mixed medical / dental billing, the corresponding medical procedure to use for a dental procedure that can be billed to medical. Ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN procedur."CondType" IS 'For conditions, the type of condition (0=Other, 4=Bleeding, 5=Supperation, 6=Calculus, 7=Overhangs)';
COMMENT ON COLUMN procedur."CompLevel" IS 'Competency level required, ptr to CLEVEL.CompLevel';
COMMENT ON COLUMN procedur."ColorStart" IS 'For graphic drawing on odontogram. The color to draw (0=Purple/Blue, 1=Royal Blue, 2=Teal, 3=Forest Green, 4=Light Green, 5=Yellow/Gold, 6=Red, 7=Orange, 8=Grey, 9=Black). ';
COMMENT ON COLUMN procedur."ColorEnd" IS 'DEPRECATED';
COMMENT ON COLUMN procedur."CodeType" IS 'Type of procedure (0=Dental, 1=Medical, 2=Condition, 3=Material)';
COMMENT ON COLUMN procedur."Category" IS 'Category sub-list that procedure is in. (0 = Diagnostics, 1 = Preventative, 2 = Restorative, 3 = Endodontics, 4 = Periodontics, 5 = Removable Pros, 6 = Fixed Pros, 7 = Surgery, 8 = Orthodontics, 9 = Miscellaneous, 10=CPT 10000, 11=CPT 20000, 12=CPT 30000, 13=CPT 40000, 14=CPT 50000, 15=CPT 60000, 16=CPT 70000, 17=CPT 80000, 18=CPT 90000, 20 = Conditions, 30=Materials) ';
COMMENT ON COLUMN procedur."CanAttach" IS 'Providers requiring approval can add I/C treatments with this code without prior Planning? (0=No, 1=Yes)';
COMMENT ON COLUMN procedur."BudgetCode" IS 'Budget code (used for reporting, to classify charges to a defined budget)';
COMMENT ON COLUMN procedur."AlternateCode" IS 'Alternate code for the procedure. Generally populated with DentiCal equivalent code for ADA procedures.';
COMMENT ON COLUMN procedur."Age" IS 'Represents the type of dentition that the procedure applies to (0 = Mixed, 1 = Primary, 2 = Permanent)';
COMMENT ON COLUMN procedur."AdditionalInfo" IS 'Additional info (0=None, 1=Prosthetics, 2=Orthodontics)';
COMMENT ON COLUMN procedur."AddLab" IS 'If LabReq=1, pop up lab sublist automatically? (0=No, 1=Yes)';


CREATE  TABLE procfee (
  "Procedure" character(7) NOT NULL,
  "Fee" character(6),
  "Amount" numeric,
  "ICharge" numeric(5,0),
  "InProcAmount" numeric,
  "FeeDates" numeric(10,0) NOT NULL,
  CONSTRAINT procfee_primary PRIMARY KEY ("FeeDates", "Procedure")
) ;
CREATE INDEX IF NOT EXISTS procfee_fee ON procfee USING btree ("Fee") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS procfee_procedurefee ON procfee USING btree ("Procedure", "Fee") TABLESPACE pg_default;
COMMENT ON TABLE procfee IS 'Procedure Fee Amount';
COMMENT ON COLUMN procfee."Procedure" IS 'Primary key component, procedure code that the fee is for. Ptr to PROCEDUR.Procedure.';
COMMENT ON COLUMN procfee."InProcAmount" IS 'Bill the amount at In Process? (0=No, 1=Yes)';
COMMENT ON COLUMN procfee."ICharge" IS 'Individual charge? (0=No, 1=Yes)';
COMMENT ON COLUMN procfee."FeeDates" IS 'Dates that this fee amount is valid for. Ptr to FEEDATES.FeeDates.';
COMMENT ON COLUMN procfee."Fee" IS 'Primary key component, fee schedule for the procedure. Ptr to FEESCHED.Fee.';
COMMENT ON COLUMN procfee."Amount" IS 'Amount to charge, in dollars.';


CREATE  TABLE procform (
  "ProcForm" numeric(10,0) NOT NULL,
  "Procedure" character(7),
  "FormCode" character(6),
  "Default" numeric(5,0),
  "IsRequired" numeric(5,0),
  CONSTRAINT procform_primary PRIMARY KEY ("ProcForm")
) ;
CREATE INDEX IF NOT EXISTS procform_procedure ON procform USING btree ("Procedure") TABLESPACE pg_default;
COMMENT ON TABLE procform IS 'Table to define which forms are available for which procedures';
COMMENT ON COLUMN procform."Procedure" IS 'Procedure code pts to PROCEDUR.Procedure';
COMMENT ON COLUMN procform."ProcForm" IS 'Sequenced primary key';
COMMENT ON COLUMN procform."IsRequired" IS 'Is this Form required to be answered in order to complete the procedure - Y / N';
COMMENT ON COLUMN procform."FormCode" IS 'EPR form code pts to FORM.Code';
COMMENT ON COLUMN procform."Default" IS 'The default form for this procedure - Y / N';


CREATE  TABLE procinc (
  "Procedure" character(7) NOT NULL,
  "IncompProcedure" character(7) NOT NULL,
  CONSTRAINT procinc_primary PRIMARY KEY ("Procedure", "IncompProcedure")
) ;
COMMENT ON TABLE procinc IS 'Incompatible Procedures';
COMMENT ON COLUMN procinc."Procedure" IS 'Primary key component, procedure triggering this rule. Ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN procinc."IncompProcedure" IS 'Primary key component, procedure that is incompatible. Ptr to PROCEDUR.Procedure';


CREATE  TABLE prockit (
  "ProcFrom" character(7),
  "ProcTo" character(7),
  "KitType" character(6),
  "ProvType" character(1),
  "ProcKit" numeric(10,0) NOT NULL,
  "Type" numeric(5,0),
  "Sundry" character(6),
  "SundryFrq" numeric(5,0),
  CONSTRAINT prockit_primary PRIMARY KEY ("ProcKit")
) ;
CREATE INDEX IF NOT EXISTS prockit_prockey ON prockit USING btree ("ProcFrom", "ProcTo") TABLESPACE pg_default;
COMMENT ON TABLE prockit IS 'Procedure Kit Requirements';
COMMENT ON COLUMN prockit."Type" IS 'Type of item required (0=Kit, 1=Sundry)';
COMMENT ON COLUMN prockit."SundryFrq" IS 'If PROCKIT.Type = 1, sundry frequency (0=Per appointment, 1=Per procedure)';
COMMENT ON COLUMN prockit."Sundry" IS 'If PROCKIT.Type = 1, ID code of the sundry. Ptr to SUNDRY.Sundry';
COMMENT ON COLUMN prockit."ProvType" IS 'Provider type that requires this kit, ptr to PRODTYPE.Code';
COMMENT ON COLUMN prockit."ProcTo" IS 'Last procedure code in the range that requires this type of kit. Ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN prockit."ProcKit" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN prockit."ProcFrom" IS 'First procedure code in the range that requires this type of kit. Ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN prockit."KitType" IS 'Kit type that is required, ptr to KITTYPE.KitType';


CREATE  TABLE procmc (
  "ProcMc" character(7) NOT NULL,
  "Description" character varying(30),
  "MultiSite" numeric(5,0),
  "Reviewable" numeric(5,0),
  "AlwaysEdit" numeric(5,0),
  CONSTRAINT procmc_primary PRIMARY KEY ("ProcMc")
) ;
COMMENT ON TABLE procmc IS 'Procedure Macro support';
COMMENT ON COLUMN procmc."Reviewable" IS '0 = No, 1 = Yes';
COMMENT ON COLUMN procmc."ProcMc" IS 'Procedure macro code';
COMMENT ON COLUMN procmc."MultiSite" IS '0 = No, 1 = Yes';
COMMENT ON COLUMN procmc."Description" IS 'Procedure macro code description';
COMMENT ON COLUMN procmc."AlwaysEdit" IS 'Always edit the macro procedures before adding them? (0=No, 1=Yes)';


CREATE  TABLE procmcit (
  "ProcMc" character(7),
  "Procedure" character(7),
  "Order" numeric(5,0),
  "ProcMcIt" numeric(10,0) NOT NULL,
  "ItemType" numeric(5,0),
  "Number" numeric(5,0),
  "Factored" numeric(5,0),
  "SiteGroup" character(6),
  "Text" character varying(4000),
  CONSTRAINT procmcit_primary PRIMARY KEY ("ProcMcIt")
) ;
CREATE INDEX IF NOT EXISTS procmcit_procmc ON procmcit USING btree ("ProcMc", "Procedure") TABLESPACE pg_default;
COMMENT ON TABLE procmcit IS 'Procedure macros';
COMMENT ON COLUMN procmcit."Text" IS 'Text which will display on the Estimate (ItemType = 1)';
COMMENT ON COLUMN procmcit."SiteGroup" IS 'Name to group procedures (ItemType = 0) with the same site';
COMMENT ON COLUMN procmcit."Procedure" IS 'Procedure code';
COMMENT ON COLUMN procmcit."ProcMcIt" IS 'Sequence - new primary key';
COMMENT ON COLUMN procmcit."ProcMc" IS 'Procedure macro code';
COMMENT ON COLUMN procmcit."Order" IS 'Order index of this procedure code within the macro';
COMMENT ON COLUMN procmcit."Number" IS 'If ItemType = 0, the default number of occurrences in macro';
COMMENT ON COLUMN procmcit."ItemType" IS '0 = Procedure, 1 = Quote Text';
COMMENT ON COLUMN procmcit."Factored" IS '0 = No, 1 = Yes (Only applies if ItemType = 0)';


CREATE  TABLE procmed (
  "Procedure" character(7) NOT NULL,
  "ICDCode1" character(10),
  "ICDCode2" character(10),
  "ICDCode3" character(10),
  "ICDCode4" character(10),
  "PlaceCode" character(6),
  "Modifier" character(2),
  "Modifier2" character(2),
  "ICDType" numeric(5,0),
  "Modifier3" character(2),
  "Modifier4" character(2),
  CONSTRAINT procmed_primary PRIMARY KEY ("Procedure")
) ;
COMMENT ON TABLE procmed IS 'Medical procedure information';
COMMENT ON COLUMN procmed."Procedure" IS 'Procedure code, ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN procmed."PlaceCode" IS 'Id code of the place where this medical procedure was performed, ptr to PLACEOS.Code';
COMMENT ON COLUMN procmed."Modifier4" IS 'Fourth modifier code that applies to this medical procedure claim, ptr to MODIFIER.Code';
COMMENT ON COLUMN procmed."Modifier3" IS 'Third modifier code that applies to this medical procedure claim, ptr to MODIFIER.Code';
COMMENT ON COLUMN procmed."Modifier2" IS 'Second modifier code that applies to this medical procedure claim, ptr to MODIFIER.Code';
COMMENT ON COLUMN procmed."Modifier" IS 'First modifier code that applies to this medical procedure claim, ptr to MODIFIER.Code';
COMMENT ON COLUMN procmed."ICDType" IS 'Default type of ICD diagnosis code to use (0=ICD-9, 1=ICD-10) ';
COMMENT ON COLUMN procmed."ICDCode4" IS 'Fourth ICD Code that applies to this medical procedure claim';
COMMENT ON COLUMN procmed."ICDCode3" IS 'Third ICD Code that applies to this medical procedure claim';
COMMENT ON COLUMN procmed."ICDCode2" IS 'Second ICD Code that applies to this medical procedure claim';
COMMENT ON COLUMN procmed."ICDCode1" IS 'First ICD Code that applies to this medical procedure claim';


CREATE  TABLE procnote (
  "ProcCode" character(7) NOT NULL,
  "Note" character varying(100),
  CONSTRAINT procnote_primary PRIMARY KEY ("ProcCode")
) ;
COMMENT ON TABLE procnote IS 'Comments for alternate procedure codes';
COMMENT ON COLUMN procnote."ProcCode" IS 'Procedure code to which this relates';
COMMENT ON COLUMN procnote."Note" IS 'Comment associated with this alternate procedure code. ';


CREATE  TABLE procptyp (
  "Code" character(7) NOT NULL,
  "ProdType" character(1) NOT NULL,
  "Type" numeric(5,0),
  CONSTRAINT procptyp_primary PRIMARY KEY ("Code", "ProdType")
) ;
COMMENT ON TABLE procptyp IS 'Accessible procedures by provider type';
COMMENT ON COLUMN procptyp."Type" IS '0 = PROCEDUR.Procedure, 1 = PROCMC.Procedure Macros';
COMMENT ON COLUMN procptyp."ProdType" IS 'Id code of the producer type (ProdType.Code)';
COMMENT ON COLUMN procptyp."Code" IS 'The procedure to allow (Procedur.Procedure)';


CREATE  TABLE procrecl (
  "Procedure" character(7) NOT NULL,
  "ProdType" character(1) NOT NULL,
  "Recall" character(6),
  "RecallType" character(6),
  "RecallStatus" character(6),
  "RecallComment" character varying(50),
  "Required" numeric(5,0),
  "Clinic" numeric(10,0),
  CONSTRAINT procrecl_primary PRIMARY KEY ("Procedure", "ProdType")
) ;
COMMENT ON TABLE procrecl IS 'Procedure recall defaults';
COMMENT ON COLUMN procrecl."Required" IS 'Recall is required? ( 0 = Not Required, 1=Optional, 2=Required, 3=Automated)';
COMMENT ON COLUMN procrecl."RecallType" IS 'The recall type to trigger';
COMMENT ON COLUMN procrecl."RecallStatus" IS 'The recall status to trigger';
COMMENT ON COLUMN procrecl."RecallComment" IS 'Comment about the recall';
COMMENT ON COLUMN procrecl."Recall" IS 'The recall to trigger';
COMMENT ON COLUMN procrecl."ProdType" IS 'The producer type that requires this type of recall';
COMMENT ON COLUMN procrecl."Procedure" IS 'Procedure code that triggers a recall';
COMMENT ON COLUMN procrecl."Clinic" IS 'Default clinic for recall. Ptr to CLINIC.Clinic';


CREATE  TABLE procrule (
  "Procedure" character(7) NOT NULL,
  "MaxPerVisit" numeric(5,0),
  "MaxPerTooth" numeric(5,0),
  "PreReqProcedure" character(7),
  CONSTRAINT procrule_primary PRIMARY KEY ("Procedure")
) ;
COMMENT ON TABLE procrule IS 'Procedure-based Rules';
COMMENT ON COLUMN procrule."Procedure" IS 'Primary key, the procedure code that this rule is for. Ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN procrule."PreReqProcedure" IS 'Procedure that is a pre-requisite for this procedure, ptr to PROCEDUR.Procedure (optional)';
COMMENT ON COLUMN procrule."MaxPerVisit" IS 'Max number of times this procedure can be added per visit (0= no limit, else 1..9)';
COMMENT ON COLUMN procrule."MaxPerTooth" IS 'Max number of times this procedure can be added per tooth (0=no limit, else 1..9)';


CREATE  TABLE procstyp (
  "Service" character(6) NOT NULL,
  "ProcFrom" character(7) NOT NULL,
  "ProcTo" character(7),
  "ServiceType" character(2),
  CONSTRAINT procstyp_primary PRIMARY KEY ("Service", "ProcFrom")
) ;
COMMENT ON TABLE procstyp IS 'Procedure Service Type Ranges';
COMMENT ON COLUMN procstyp."ServiceType" IS 'Service Type, ptr to PROCTYPE.ServiceType';
COMMENT ON COLUMN procstyp."Service" IS 'ProcType Service this range is defined for, ptr to PROCTYPE.Service';
COMMENT ON COLUMN procstyp."ProcTo" IS 'Procedure code the service type range ends at';
COMMENT ON COLUMN procstyp."ProcFrom" IS 'Procedure code the service type range begins at';


CREATE  TABLE proctbit (
  "ProcTbl" numeric(10,0) NOT NULL,
  "Item" numeric(10,0) NOT NULL,
  "ProcFrom" character(7),
  "ProcTo" character(7),
  CONSTRAINT proctbit_primary PRIMARY KEY ("ProcTbl", "Item")
) ;
COMMENT ON TABLE proctbit IS 'Items within the limited procedures table. Used to refine the clinical limits for the availability scheduler.';
COMMENT ON COLUMN proctbit."ProcTo" IS 'Procedure code that this range ends with, ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN proctbit."ProcTbl" IS 'ProcTbl Id, ptr to PROCTBL.ProcTbl';
COMMENT ON COLUMN proctbit."ProcFrom" IS 'Procedure code that this range begins with, ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN proctbit."Item" IS 'Number in the range 1-999 to indicate the item within the procedure table range.';


CREATE  TABLE proctbl (
  "ProcTbl" numeric(10,0) NOT NULL,
  "Description" character(30),
  "Order" numeric(5,0),
  CONSTRAINT proctbl_primary PRIMARY KEY ("ProcTbl")
) ;
COMMENT ON TABLE proctbl IS 'Limited procedures table.  Definitions of the clinical limits for availability scheduling.';
COMMENT ON COLUMN proctbl."ProcTbl" IS 'Internal ID code for this procedure code range, Not null';
COMMENT ON COLUMN proctbl."Order" IS 'Number in the range 1 - 999 to represent the order';
COMMENT ON COLUMN proctbl."Description" IS 'Description of the procedure table';


CREATE  TABLE proctype (
  "Procedure" character(7) NOT NULL,
  "Service" character(6) NOT NULL,
  "ServiceType" character(2),
  CONSTRAINT proctype_primary PRIMARY KEY ("Procedure", "Service")
) ;
COMMENT ON TABLE proctype IS 'Type of Service that ties to this Procedure';
COMMENT ON COLUMN proctype."ServiceType" IS 'Service Type';
COMMENT ON COLUMN proctype."Service" IS 'Ptr to SERVICE.Code';
COMMENT ON COLUMN proctype."Procedure" IS 'Ptr to PROCEDUR.Procedure';


CREATE  TABLE prodhis (
  "ProdHis" numeric(10,0) NOT NULL,
  "Producer" character(10) NOT NULL,
  "LastName" character(30),
  "FirstName" character(30),
  "MiddleName" character(30),
  "Title" character(15),
  "Address1" character(30),
  "Address2" character(30),
  "City" character(24),
  "Province" character(6),
  "Postal" character(15),
  "BArea" character(4),
  "BTel" character(8),
  "BExt" character varying(6),
  "HArea" character(4),
  "HTel" character(8),
  "Fee" character(6),
  "Specialist" character(15),
  "CDA" character(15),
  "EDI" character(10),
  "Color" numeric(10,0),
  "Goal0" numeric,
  "Goal1" numeric,
  "Goal2" numeric,
  "Goal3" numeric,
  "Goal4" numeric,
  "Goal5" numeric,
  "Goal6" numeric,
  "Type" numeric(5,0),
  "PrintOnClaim" numeric(5,0),
  "RequireGrading" numeric(5,0),
  "Year" numeric(10,0),
  "UnavailableBooking" numeric(5,0),
  "Chair" numeric(10,0),
  "Import" character(10),
  "CanComplete" numeric(5,0),
  "MultiChairs" numeric(5,0),
  "TypeCode" character(1),
  "EndDate" timestamp without time zone,
  "PGroup" character(6),
  "CPRDate" timestamp without time zone,
  "Standing" character(10),
  "Inactive" numeric(5,0),
  "RequireSteps" numeric(5,0),
  "Specialty" character(6),
  "PhaseCheck" numeric(5,0),
  "AddressOther" character(15),
  "Preferred" character(30),
  "FirstYear" numeric(10,0),
  "Box" character(4),
  "Manager" numeric(10,0),
  "DispLocked" numeric(5,0),
  "DispMaxHours" numeric(10,0),
  "DispBalance" numeric,
  "NeedLocked" numeric(5,0),
  "SpecialtyCode" character(3),
  "DefaultPractice" numeric(5,0),
  "LabLocked" numeric(5,0),
  "ClaimLast" character varying(40),
  "ClaimFirst" character varying(30),
  "PatAssignOverdue" numeric(5,0),
  "OtherOverdue" numeric(5,0),
  "OverdueDate" timestamp without time zone,
  "NameQual" numeric(5,0),
  "ClaimSpecCode" character varying(10),
  "RequireStartCheck" numeric(5,0),
  "IsTIN" numeric(5,0),
  "DispLockedUnappr" numeric(5,0),
  "Audit" numeric(10,0),
  "DoubleBooking" numeric(5,0),
  "MedNEICSpec" character(3),
  "MedSpecCode" character varying(10),
  "NPI" character varying(10),
  "NPI2" character varying(10),
  "ReviewExposures" numeric(5,0),
  "RequireTxConsent" numeric(5,0),
  "MaxApptMinutes" numeric(5,0),
  "TxLocked" numeric(5,0),
  "SchLocked" numeric(5,0),
  "SecondaryMCBFlag" numeric(5,0),
  "LimitedExams" numeric(5,0),
  "ExamCnt" numeric(5,0),
  "UnavailableGrace" numeric(5,0),
  "RequireCaseNote" numeric(5,0),
  "MaxSchDays" numeric(5,0),
  "SchToDate" timestamp without time zone,
  "MUEligible" numeric(5,0),
  "DiagnosisNotReqd" numeric(5,0),
  "StartCheckMinutes" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT prodhis_primary PRIMARY KEY ("ProdHis")
) ;
CREATE INDEX IF NOT EXISTS prodhis_producer ON prodhis USING btree ("Producer") TABLESPACE pg_default;
COMMENT ON TABLE prodhis IS 'History records for the PRODUCER table';
COMMENT ON COLUMN prodhis."Year" IS 'Year of study';
COMMENT ON COLUMN prodhis."UnavailableGrace" IS 'Number of minutes that appointments for this provider can extend beyond available time.';
COMMENT ON COLUMN prodhis."UnavailableBooking" IS 'Book appointment without a chair? (0 = Yes, 1 = No)';
COMMENT ON COLUMN prodhis."TypeCode" IS 'Provider type (points to a PRODTYPE.Code)';
COMMENT ON COLUMN prodhis."Type" IS 'Producer type(0: Doctor (bills under self), 1: Student/Doctor (bills under clinic), 2: Fee Guide)';
COMMENT ON COLUMN prodhis."TxLocked" IS 'For dummy providers - Allow adding completed transactions - 0 = No, 1 = Yes';
COMMENT ON COLUMN prodhis."Title" IS 'Prefix to the producer name ie: Dr. or Rev.';
COMMENT ON COLUMN prodhis."StartCheckMinutes" IS 'Number of minutes before appt when you can do start checks';
COMMENT ON COLUMN prodhis."Standing" IS 'Academic standing (could be anything)';
COMMENT ON COLUMN prodhis."SpecialtyCode" IS 'A code to identify the specialty, used for NEIC claims';
COMMENT ON COLUMN prodhis."Specialty" IS 'Discipline specialty (points to a DISCIPL.Discipline)';
COMMENT ON COLUMN prodhis."Specialist" IS 'Specialist # in Canada, SSN/"TIN" in USA (alternate Id number)';
COMMENT ON COLUMN prodhis."SecondaryMCBFlag" IS '0=N/A(if no 2nd provider), 1=Assistant Time, 2=Primary Provider Time, 3=Total Time';
COMMENT ON COLUMN prodhis."SchToDate" IS 'Date past which provider cannot be scheduled for appointments.';
COMMENT ON COLUMN prodhis."SchLocked" IS 'For dummy providers - Allow adding appointments or reschedules for other providers - 0 = No, 1 = Yes';
COMMENT ON COLUMN prodhis."ReviewExposures" IS 'Upon checkout this provider is required to review the exposures entered entered for exposure type procedures';
COMMENT ON COLUMN prodhis."RequireTxConsent" IS 'Yes / No field to determine whether a Producer requires patient consent for treatment';
COMMENT ON COLUMN prodhis."RequireSteps" IS 'Uses tx steps when adding tx (0 = No, 1 = Yes)';
COMMENT ON COLUMN prodhis."RequireStartCheck" IS 'Producer requires a start check? (0 = No, 1 = Yes)';
COMMENT ON COLUMN prodhis."RequireGrading" IS 'Is provider graded? (0 = No, 1 = Yes (sessional), 2 = Yes (periodic))';
COMMENT ON COLUMN prodhis."RequireCaseNote" IS 'Provider must enter a general/template note on date of treatments? (0=No, 1=Yes)';
COMMENT ON COLUMN prodhis."Province" IS 'Province / state, ptr to CITY.Province';
COMMENT ON COLUMN prodhis."Producer" IS 'Primary key, producer code (student code)';
COMMENT ON COLUMN prodhis."ProdHis" IS 'Unique Id code to identify this history record, Internal Id, from sequence';
COMMENT ON COLUMN prodhis."PrintOnClaim" IS 'Address to print on claim form (0 = Provider, 1 = Clinic)';
COMMENT ON COLUMN prodhis."Preferred" IS 'Prefered name';
COMMENT ON COLUMN prodhis."Postal" IS 'Postal / zip code, ptr to CITY.Postal';
COMMENT ON COLUMN prodhis."PhaseCheck" IS 'Requires phase order check (0 = No, 1 = Yes)';
COMMENT ON COLUMN prodhis."PatAssignOverdue" IS 'Producer has overdue patient assignment? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN prodhis."PGroup" IS 'Student group (points to a PGROUP.PGroup)';
COMMENT ON COLUMN prodhis."OverdueDate" IS 'Date the overdue condition occured';
COMMENT ON COLUMN prodhis."OtherOverdue" IS 'Producer has overdue condition other than patient assignment (0 = No, 1 = Yes)';
COMMENT ON COLUMN prodhis."NeedLocked" IS 'Producer locked from making need requests? (0 = No, 1 = Yes)';
COMMENT ON COLUMN prodhis."NameQual" IS 'For medical billing, a special ID for printing claim forms';
COMMENT ON COLUMN prodhis."NPI2" IS '"NPI" (Type 2) # for dental entity (to be used by claim form and "EDI" submission)';
COMMENT ON COLUMN prodhis."NPI" IS 'US only - National Provider Identification';
COMMENT ON COLUMN prodhis."MultiChairs" IS 'Can provider be double-booked in more than 1 chair? (0 = one Chair only, 1 = Multiple chairs allowed)';
COMMENT ON COLUMN prodhis."MiddleName" IS 'Middle name';
COMMENT ON COLUMN prodhis."MedSpecCode" IS 'Medical Specialty Code of the billing doctor for HIPAA';
COMMENT ON COLUMN prodhis."MedNEICSpec" IS 'Number to indicate the NEIC specialty of this producer';
COMMENT ON COLUMN prodhis."MaxSchDays" IS 'Number of days in advance that the provider can be scheduled for appointments. ';
COMMENT ON COLUMN prodhis."MaxApptMinutes" IS 'Maximum # of appt minutes allowed for the provider ';
COMMENT ON COLUMN prodhis."Manager" IS 'Faculty manager, ptr to USERS.User';
COMMENT ON COLUMN prodhis."MUEligible" IS 'US ONLY - Is the provider eligible for Meaningful Use funding under the HITECH act? (0=No, 1=Yes)';
COMMENT ON COLUMN prodhis."LimitedExams" IS '0=No, 1=Yes';
COMMENT ON COLUMN prodhis."LastName" IS 'Last name';
COMMENT ON COLUMN prodhis."LabLocked" IS 'Lab locked? (0 = No, 1 = Yes)';
COMMENT ON COLUMN prodhis."IsTIN" IS 'Type of license number (0=Social Security Number, 1= Tax Information Number) ';
COMMENT ON COLUMN prodhis."Inactive" IS 'Inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN prodhis."Import" IS 'Import code for scheduler import';
COMMENT ON COLUMN prodhis."HTel" IS 'Telephone Number (Home)';
COMMENT ON COLUMN prodhis."HArea" IS 'Telephone Area Code (Home)';
COMMENT ON COLUMN prodhis."Goal6" IS 'DEPRECATED';
COMMENT ON COLUMN prodhis."Goal5" IS 'DEPRECATED';
COMMENT ON COLUMN prodhis."Goal4" IS 'DEPRECATED';
COMMENT ON COLUMN prodhis."Goal3" IS 'DEPRECATED';
COMMENT ON COLUMN prodhis."Goal2" IS 'DEPRECATED';
COMMENT ON COLUMN prodhis."Goal1" IS 'DEPRECATED';
COMMENT ON COLUMN prodhis."Goal0" IS 'DEPRECATED';
COMMENT ON COLUMN prodhis."FirstYear" IS 'First year in school';
COMMENT ON COLUMN prodhis."FirstName" IS 'First name';
COMMENT ON COLUMN prodhis."Fee" IS 'Fee guide used when billing claims (only applies to fee guides, billing doctors)';
COMMENT ON COLUMN prodhis."ExamCnt" IS 'Maximum number of exams at a time [0..9] (only if LimitedExams=1)';
COMMENT ON COLUMN prodhis."EndDate" IS 'Default end date for all patient assignments to this provider';
COMMENT ON COLUMN prodhis."EDI" IS 'EDI billing number';
COMMENT ON COLUMN prodhis."DoubleBooking" IS 'Double booking warning (0=Warn on appointment overlap, 1=Warn if Dr. Time overlaps, 2= No warning)';
COMMENT ON COLUMN prodhis."DispMaxHours" IS 'Maximum number of hours out for dispensary item';
COMMENT ON COLUMN prodhis."DispLockedUnappr" IS 'Locked out of Dispensary due to unapproved items? (0 = No, 1 = Yes)';
COMMENT ON COLUMN prodhis."DispLocked" IS 'Locked out of dispensary? (0 = No, 1 = Yes)';
COMMENT ON COLUMN prodhis."DispBalance" IS 'Current balance ($) for dispensary';
COMMENT ON COLUMN prodhis."DiagnosisNotReqd" IS 'Diagnosis required for procedures? (0=No: required based on System option (default), 1=Yes)';
COMMENT ON COLUMN prodhis."DefaultPractice" IS 'ID Code of the default practice for this producer, ptr to PRACTICE.Id';
COMMENT ON COLUMN prodhis."Color" IS 'Scheduler color';
COMMENT ON COLUMN prodhis."ClaimSpecCode" IS 'Claim specialty code';
COMMENT ON COLUMN prodhis."ClaimLast" IS 'Last name to appear on the claim';
COMMENT ON COLUMN prodhis."ClaimFirst" IS 'First name to appear on the form';
COMMENT ON COLUMN prodhis."City" IS 'City, ptr to CITY.City';
COMMENT ON COLUMN prodhis."Chair" IS 'Provider chair number (points to a CHAIR.Chair), used in daily layout.';
COMMENT ON COLUMN prodhis."CanComplete" IS 'Complete unapproved tx? (0 = No, 1 = Yes)';
COMMENT ON COLUMN prodhis."CPRDate" IS 'CPR certification date';
COMMENT ON COLUMN prodhis."CDA" IS 'License number to bill under. ';
COMMENT ON COLUMN prodhis."Box" IS 'Mail box number';
COMMENT ON COLUMN prodhis."BTel" IS 'Telephone Number (Work)';
COMMENT ON COLUMN prodhis."BExt" IS 'Telephone Extension (Work)';
COMMENT ON COLUMN prodhis."BArea" IS 'Telephone area code (work)';
COMMENT ON COLUMN prodhis."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN prodhis."AddressOther" IS 'For USA, represents County. For Dutch, represents Room Number.';
COMMENT ON COLUMN prodhis."Address2" IS 'Address line 2';
COMMENT ON COLUMN prodhis."Address1" IS 'Address line 1';


CREATE  TABLE prodtype (
  "Code" character(1) NOT NULL,
  "Description" character(20),
  "Type" numeric(5,0),
  "RequestsLimited" numeric(5,0),
  "SubType" numeric(5,0),
  "HygOnChildren" numeric(5,0),
  "HygOnLowPerioRiskPt" numeric(5,0),
  CONSTRAINT prodtype_primary PRIMARY KEY ("Code")
) ;
COMMENT ON TABLE prodtype IS 'Producer Type Codes';
COMMENT ON COLUMN prodtype."Type" IS 'Producer type(0: Doctor (bills under self), 1: Student/Doctor (bills under clinic), 2: Fee Guide)';
COMMENT ON COLUMN prodtype."SubType" IS '0=N/A, 1=Student, 2=Dentist, 3=Hygienist, 4=CDA (what Kaiser calls a PDTA), 5=Other';
COMMENT ON COLUMN prodtype."RequestsLimited" IS 'Are the requests limited for this producer type? (0 = No, 1 = Yes)';
COMMENT ON COLUMN prodtype."HygOnLowPerioRiskPt" IS '0 = No; 1 = Yes';
COMMENT ON COLUMN prodtype."HygOnChildren" IS '0 = No; 1 = Yes';
COMMENT ON COLUMN prodtype."Description" IS 'Description of the producer type';
COMMENT ON COLUMN prodtype."Code" IS 'Primary key, single character code to define the producer type';


CREATE  TABLE producer (
  "Producer" character(10) NOT NULL,
  "LastName" character(30),
  "FirstName" character(30),
  "MiddleName" character(30),
  "Title" character(15),
  "Address1" character(30),
  "Address2" character(30),
  "City" character(24),
  "Province" character(6),
  "Postal" character(15),
  "BArea" character(4),
  "BTel" character(8),
  "BExt" character varying(6),
  "HArea" character(4),
  "HTel" character(8),
  "Fee" character(6),
  "Specialist" character(15),
  "CDA" character(15),
  "EDI" character(10),
  "Color" numeric(10,0),
  "Goal0" numeric,
  "Goal1" numeric,
  "Goal2" numeric,
  "Goal3" numeric,
  "Goal4" numeric,
  "Goal5" numeric,
  "Goal6" numeric,
  "Type" numeric(5,0),
  "PrintOnClaim" numeric(5,0),
  "RequireGrading" numeric(5,0),
  "Year" numeric(10,0),
  "UnavailableBooking" numeric(5,0),
  "Chair" numeric(10,0),
  "Import" character(10),
  "CanComplete" numeric(5,0),
  "MultiChairs" numeric(5,0),
  "TypeCode" character(1),
  "EndDate" timestamp without time zone,
  "PGroup" character(6),
  "CPRDate" timestamp without time zone,
  "Standing" character(10),
  "Inactive" numeric(5,0),
  "RequireSteps" numeric(5,0),
  "Specialty" character(6),
  "PhaseCheck" numeric(5,0),
  "AddressOther" character(15),
  "Preferred" character(30),
  "FirstYear" numeric(10,0),
  "Box" character(4),
  "Manager" numeric(10,0),
  "DispLocked" numeric(5,0),
  "DispMaxHours" numeric(10,0),
  "DispBalance" numeric,
  "NeedLocked" numeric(5,0),
  "SpecialtyCode" character(3),
  "DefaultPractice" numeric(5,0),
  "LabLocked" numeric(5,0),
  "ClaimLast" character varying(40),
  "ClaimFirst" character varying(30),
  "PatAssignOverdue" numeric(5,0),
  "OtherOverdue" numeric(5,0),
  "OverdueDate" timestamp without time zone,
  "NameQual" numeric(5,0),
  "ClaimSpecCode" character varying(10),
  "RequireStartCheck" numeric(5,0),
  "IsTIN" numeric(5,0),
  "DispLockedUnappr" numeric(5,0),
  "Audit" numeric(10,0),
  "DoubleBooking" numeric(5,0),
  "MedNEICSpec" character(3),
  "MedSpecCode" character varying(10),
  "NPI" character varying(10),
  "NPI2" character varying(10),
  "ReviewExposures" numeric(5,0),
  "RequireTxConsent" numeric(5,0),
  "MaxApptMinutes" numeric(5,0),
  "TxLocked" numeric(5,0),
  "SchLocked" numeric(5,0),
  "SecondaryMCBFlag" numeric(5,0),
  "LimitedExams" numeric(5,0),
  "ExamCnt" numeric(5,0),
  "UnavailableGrace" numeric(5,0),
  "RequireCaseNote" numeric(5,0),
  "MaxSchDays" numeric(5,0),
  "SchToDate" timestamp without time zone,
  "MUEligible" numeric(5,0),
  "DiagnosisNotReqd" numeric(5,0),
  "StartCheckMinutes" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT producer_primary PRIMARY KEY ("Producer")
) ;
CREATE INDEX IF NOT EXISTS producer_fee ON producer USING btree ("Fee") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS producer_import ON producer USING btree ("Import") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS producer_type ON producer USING btree ("Type") TABLESPACE pg_default;
COMMENT ON TABLE producer IS 'Producers: i.e. any student, assistant, faculty member, hygienist performing dental procedures';
COMMENT ON COLUMN producer."Year" IS 'Year of study';
COMMENT ON COLUMN producer."UnavailableGrace" IS 'Number of minutes that appointments for this provider can extend beyond available time.';
COMMENT ON COLUMN producer."UnavailableBooking" IS 'Book appointment without a chair? (0 = Yes, 1 = No)';
COMMENT ON COLUMN producer."TypeCode" IS 'Provider type (points to a PRODTYPE.Code)';
COMMENT ON COLUMN producer."Type" IS 'Producer type(0: Doctor (bills under self), 1: Student/Doctor (bills under clinic), 2: Fee Guide)';
COMMENT ON COLUMN producer."TxLocked" IS 'For dummy providers - Allow adding completed transactions - 0 = No, 1 = Yes';
COMMENT ON COLUMN producer."Title" IS 'Prefix to the producer name ie: Dr. or Rev.';
COMMENT ON COLUMN producer."StartCheckMinutes" IS 'Number of minutes before appt when you can do start checks';
COMMENT ON COLUMN producer."Standing" IS 'Academic standing (could be anything)';
COMMENT ON COLUMN producer."SpecialtyCode" IS 'A code to identify the specialty, used for NEIC claims';
COMMENT ON COLUMN producer."Specialty" IS 'Discipline specialty (points to a DISCIPL.Discipline)';
COMMENT ON COLUMN producer."Specialist" IS 'Specialist # in Canada, SSN/"TIN" in USA (alternate Id number)';
COMMENT ON COLUMN producer."SecondaryMCBFlag" IS '0=N/A(if no 2nd provider), 1=Assistant Time, 2=Primary Provider Time, 3=Total Time';
COMMENT ON COLUMN producer."SchToDate" IS 'Date past which provider cannot be scheduled for appointments.';
COMMENT ON COLUMN producer."SchLocked" IS 'For dummy providers - Allow adding appointments or reschedules for other providers - 0 = No, 1 = Yes';
COMMENT ON COLUMN producer."ReviewExposures" IS 'Upon checkout this provider is required to review the exposures entered entered for exposure type procedures';
COMMENT ON COLUMN producer."RequireTxConsent" IS 'Yes / No field to determine whether a Producer requires patient consent for treatment';
COMMENT ON COLUMN producer."RequireSteps" IS 'Uses tx steps when adding tx (0=Manual only, 1=Yes, 2=Auto Only)';
COMMENT ON COLUMN producer."RequireStartCheck" IS 'Producer requires a start check? (0 = No, 1 = Yes)';
COMMENT ON COLUMN producer."RequireGrading" IS 'Is provider graded? (0 = No, 1 = Yes (sessional), 2 = Yes (periodic))';
COMMENT ON COLUMN producer."RequireCaseNote" IS 'Provider must enter a general/template note on date of treatments? (0=No, 1=Yes)';
COMMENT ON COLUMN producer."Province" IS 'Province / state, ptr to CITY.Province';
COMMENT ON COLUMN producer."Producer" IS 'Primary key, producer code (student code)';
COMMENT ON COLUMN producer."PrintOnClaim" IS 'Address to print on claim form (0 = Provider, 1 = Clinic)';
COMMENT ON COLUMN producer."Preferred" IS 'Prefered name';
COMMENT ON COLUMN producer."Postal" IS 'Postal / zip code, ptr to CITY.Postal';
COMMENT ON COLUMN producer."PhaseCheck" IS 'Requires phase order check (0 = No, 1 = Yes)';
COMMENT ON COLUMN producer."PatAssignOverdue" IS 'Producer has overdue patient assignment? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN producer."PGroup" IS 'Student group (points to a PGROUP.PGroup)';
COMMENT ON COLUMN producer."OverdueDate" IS 'Date the overdue condition occured';
COMMENT ON COLUMN producer."OtherOverdue" IS 'Producer has overdue condition other than patient assignment (0 = No, 1 = Yes)';
COMMENT ON COLUMN producer."NeedLocked" IS 'Producer locked from making need requests? (0 = No, 1 = Yes)';
COMMENT ON COLUMN producer."NameQual" IS 'Billing entity to use (0=Provider, 1=Organization)';
COMMENT ON COLUMN producer."NPI2" IS '"NPI" (Type 2) # for dental entity (to be used by claim form and "EDI" submission)';
COMMENT ON COLUMN producer."NPI" IS 'US only - National Provider Identification';
COMMENT ON COLUMN producer."MultiChairs" IS 'Can provider be double-booked in more than 1 chair? (0 = one Chair only, 1 = Multiple chairs allowed)';
COMMENT ON COLUMN producer."MiddleName" IS 'Middle name';
COMMENT ON COLUMN producer."MedSpecCode" IS '10 digit number to represent the field of specialty for medical claims';
COMMENT ON COLUMN producer."MedNEICSpec" IS 'Number to indicate the NEIC specialty of this producer';
COMMENT ON COLUMN producer."MaxSchDays" IS 'Number of days in advance that the provider can be scheduled for appointments. ';
COMMENT ON COLUMN producer."MaxApptMinutes" IS 'Maximum # of appt minutes allow for the provider ';
COMMENT ON COLUMN producer."Manager" IS 'Faculty manager, ptr to USERS.User';
COMMENT ON COLUMN producer."MUEligible" IS 'US ONLY - Is the provider eligible for Meaningful Use funding under the HITECH act? (0=No, 1=Yes)';
COMMENT ON COLUMN producer."LimitedExams" IS '0=No, 1=Yes';
COMMENT ON COLUMN producer."LastName" IS 'Last name';
COMMENT ON COLUMN producer."LabLocked" IS 'Lab locked? (0 = No, 1 = Yes)';
COMMENT ON COLUMN producer."IsTIN" IS 'Type of license number (0=Social Security Number, 1= Tax Information Number) ';
COMMENT ON COLUMN producer."Inactive" IS 'Inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN producer."Import" IS 'Import code for scheduler import';
COMMENT ON COLUMN producer."HTel" IS 'Telephone Number (Home)';
COMMENT ON COLUMN producer."HArea" IS 'Telephone Area Code (Home)';
COMMENT ON COLUMN producer."Goal6" IS 'DEPRECATED';
COMMENT ON COLUMN producer."Goal5" IS 'DEPRECATED';
COMMENT ON COLUMN producer."Goal4" IS 'DEPRECATED';
COMMENT ON COLUMN producer."Goal3" IS 'DEPRECATED';
COMMENT ON COLUMN producer."Goal2" IS 'DEPRECATED';
COMMENT ON COLUMN producer."Goal1" IS 'DEPRECATED';
COMMENT ON COLUMN producer."Goal0" IS 'DEPRECATED';
COMMENT ON COLUMN producer."FirstYear" IS 'First year in school';
COMMENT ON COLUMN producer."FirstName" IS 'First name';
COMMENT ON COLUMN producer."Fee" IS 'Fee guide used when billing claims (only applies to fee guides, billing doctors)';
COMMENT ON COLUMN producer."ExamCnt" IS 'Maximum number of exams at a time [0..9] (only if LimitedExams=1)';
COMMENT ON COLUMN producer."EndDate" IS 'Default end date for all patient assignments to this provider';
COMMENT ON COLUMN producer."EDI" IS 'EDI billing number';
COMMENT ON COLUMN producer."DoubleBooking" IS 'Double booking warning (0=Warn on appointment overlap, 1=Warn if Dr. Time overlaps, 2= No warning)';
COMMENT ON COLUMN producer."DispMaxHours" IS 'Maximum number of hours out for dispensary item';
COMMENT ON COLUMN producer."DispLockedUnappr" IS 'Locked out of Dispensary due to unapproved items? (0 = No, 1 = Yes)';
COMMENT ON COLUMN producer."DispLocked" IS 'Locked out of dispensary? (0 = No, 1 = Yes)';
COMMENT ON COLUMN producer."DispBalance" IS 'Current balance ($) for dispensary';
COMMENT ON COLUMN producer."DiagnosisNotReqd" IS 'Diagnosis required for procedures? (0=No: required based on System option (default), 1=Yes)';
COMMENT ON COLUMN producer."DefaultPractice" IS 'ID Code of the default practice for this producer, ptr to PRACTICE.Id';
COMMENT ON COLUMN producer."Color" IS 'Scheduler color';
COMMENT ON COLUMN producer."ClaimSpecCode" IS 'Claim specialty code';
COMMENT ON COLUMN producer."ClaimLast" IS 'Last name to appear on the claim';
COMMENT ON COLUMN producer."ClaimFirst" IS 'First name to appear on the form';
COMMENT ON COLUMN producer."City" IS 'City, ptr to CITY.City';
COMMENT ON COLUMN producer."Chair" IS 'Provider chair number (points to a CHAIR.Chair), used in daily layout.';
COMMENT ON COLUMN producer."CanComplete" IS 'Complete unapproved tx? (0 = No, 1 = Yes)';
COMMENT ON COLUMN producer."CPRDate" IS 'CPR certification date';
COMMENT ON COLUMN producer."CDA" IS 'License number to bill under. ';
COMMENT ON COLUMN producer."Box" IS 'Mail box number';
COMMENT ON COLUMN producer."BTel" IS 'Telephone Number (Work)';
COMMENT ON COLUMN producer."BExt" IS 'Telephone Extension (Work)';
COMMENT ON COLUMN producer."BArea" IS 'Telephone area code (work)';
COMMENT ON COLUMN producer."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN producer."AddressOther" IS 'For USA, represents County, For Dutch, represents Room Number';
COMMENT ON COLUMN producer."Address2" IS 'Address line 2';
COMMENT ON COLUMN producer."Address1" IS 'Address line 1';


CREATE  TABLE product (
  "Product" numeric(10,0) NOT NULL,
  "PrdType" numeric(10,0),
  "PrdCat" character(6),
  "Description" character varying(50),
  "ProductCode" character varying(20),
  "CanOrder" numeric(5,0),
  "Inactive" numeric(5,0),
  "Manufacturer" character varying(50),
  "UPCCode" character varying(30),
  "Unit" character varying(10),
  "ItemsPerUnit" numeric(5,0),
  "ItemsPerDesc" character varying(10),
  "WeightPerUnit" numeric,
  "WeightUnit" character varying(10),
  "CostPerUnit" numeric,
  "CostMethod" numeric(5,0),
  "AverageCost" numeric,
  "IsDividable" numeric(5,0),
  "LeadTime" numeric(5,0),
  "LeadUnit" numeric(5,0),
  "InvOType" character(6),
  "TrackExpiryDate" numeric(5,0),
  "Vendor" numeric(10,0),
  "Comment" character varying(200),
  "PrintCode" character varying(20),
  CONSTRAINT product_primary PRIMARY KEY ("Product")
) ;
COMMENT ON TABLE product IS 'Products for Inventory.';
COMMENT ON COLUMN product."WeightUnit" IS 'Unit of weight measurement (Eg: lb, kg) ';
COMMENT ON COLUMN product."WeightPerUnit" IS 'Number to represent the weight per unit. ';
COMMENT ON COLUMN product."Vendor" IS 'ID code of the vendor of this product, ptr to VENDOR.Vendor';
COMMENT ON COLUMN product."Unit" IS 'The unit type, for example: Box, Case, Bottle.';
COMMENT ON COLUMN product."UPCCode" IS 'UPC Product Code.';
COMMENT ON COLUMN product."TrackExpiryDate" IS 'Track expiry dates for this product? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN product."ProductCode" IS 'Unique product # to identify this product ';
COMMENT ON COLUMN product."Product" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN product."PrintCode" IS 'Product print code';
COMMENT ON COLUMN product."PrdType" IS 'Id code of the product type, PRDTYPE.PrdType';
COMMENT ON COLUMN product."PrdCat" IS 'Id code of the product category, ptr to PRDCAT.PrdCat';
COMMENT ON COLUMN product."Manufacturer" IS ' Manufacturer’s name';
COMMENT ON COLUMN product."LeadUnit" IS 'Used with PRODUCT.LeadTime, the unit of time. ( -1=N/A, 0=Days, 1=Weeks)';
COMMENT ON COLUMN product."LeadTime" IS 'The normal lead time for delivery';
COMMENT ON COLUMN product."ItemsPerUnit" IS 'The number of items per PRODUCT.Unit';
COMMENT ON COLUMN product."ItemsPerDesc" IS 'Optional text (Eg: 20 per unit, 15 ml per)';
COMMENT ON COLUMN product."IsDividable" IS 'Product can be repackaged into smaller units? (0 = No, 1 = Yes)';
COMMENT ON COLUMN product."InvOType" IS 'The default order type. For information only, not a restriction.';
COMMENT ON COLUMN product."Inactive" IS 'Product is inactive? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN product."Description" IS 'Description of the product category. If above =0, like “Medium Fine Blue Pens”';
COMMENT ON COLUMN product."CostPerUnit" IS 'Current cost per unit';
COMMENT ON COLUMN product."CostMethod" IS 'The cost method in use ( 0=FIFO, 1=LIFO, 2=Average Cost)';
COMMENT ON COLUMN product."Comment" IS 'Short comment';
COMMENT ON COLUMN product."CanOrder" IS 'Product can be ordered internally (from a location at the school)? (0 = No, 1 = Yes)';
COMMENT ON COLUMN product."AverageCost" IS 'If PRODUCT.CostMethod=2, the average cost per unit';


CREATE  TABLE prolist (
  "Id" numeric(10,0) NOT NULL,
  "Complaint" numeric(10,0),
  "Problem" character(7),
  "Desc" character(50),
  "Deleted" numeric(5,0),
  "Area" numeric(5,0),
  "Site" character(3),
  "Note" character varying(4000),
  "AppUser" numeric(10,0),
  "AppDate" timestamp without time zone,
  "Status" character(6),
  "Audit" numeric(10,0),
  "Patient" numeric(10,0),
  CONSTRAINT prolist_primary PRIMARY KEY ("Id")
) ;
CREATE INDEX IF NOT EXISTS prolist_audit ON prolist USING btree ("Audit") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS prolist_complaint ON prolist USING btree ("Complaint") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS prolist_patientkey ON prolist USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE prolist IS 'Patient Problems';
COMMENT ON COLUMN prolist."Status" IS 'Status of the problem, ptr to PROSTS.Code';
COMMENT ON COLUMN prolist."Site" IS 'Site/tooth number, if site specific';
COMMENT ON COLUMN prolist."Problem" IS 'Problem code, ptr to PROBLEM.Problem';
COMMENT ON COLUMN prolist."Patient" IS 'ID code of the patient, ptr to PATIENT.Patient';
COMMENT ON COLUMN prolist."Note" IS 'Text of the problem note.';
COMMENT ON COLUMN prolist."Id" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN prolist."Desc" IS 'Description of problem';
COMMENT ON COLUMN prolist."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN prolist."Complaint" IS 'If attached to a treatment plan, then ptr to COMPLAIN.Auto. (0 otherwise)';
COMMENT ON COLUMN prolist."Audit" IS 'Audit history, ptr to AUDITHIS.Audit.';
COMMENT ON COLUMN prolist."Area" IS 'Area problem found in (-1=None, 0=Chart, 1=In-Progress, 2=TxHistory, 3=Forms, 4=Attachments, 5=Perio, 6=IMaging, 7=TxPlan, 8=Labs, 9=Prescriptions, 10=ChartAdd)';
COMMENT ON COLUMN prolist."AppUser" IS 'Approval user, if approval required. Ptr to USERS.User';
COMMENT ON COLUMN prolist."AppDate" IS 'Date approval obtained, if approval required';


CREATE  TABLE prolisth (
  "ProListH" numeric(10,0) NOT NULL,
  "Id" numeric(10,0),
  "Complaint" numeric(10,0),
  "Problem" character(7),
  "Desc" character(50),
  "Deleted" numeric(5,0),
  "Area" numeric(5,0),
  "Site" character(3),
  "Note" character varying(4000),
  "AppUser" numeric(10,0),
  "AppDate" timestamp without time zone,
  "Status" character(6),
  "Audit" numeric(10,0),
  "Patient" numeric(10,0),
  CONSTRAINT prolisth_primary PRIMARY KEY ("ProListH")
) ;
CREATE INDEX IF NOT EXISTS prolisth_id ON prolisth USING btree ("Id") TABLESPACE pg_default;
COMMENT ON TABLE prolisth IS 'Patient Problem History';
COMMENT ON COLUMN prolisth."Status" IS 'Status of the problem, ptr to PROSTS.Code';
COMMENT ON COLUMN prolisth."Site" IS 'Site/tooth number, if site specific';
COMMENT ON COLUMN prolisth."Problem" IS 'Problem code, ptr to PROBLEM.Problem';
COMMENT ON COLUMN prolisth."ProListH" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN prolisth."Patient" IS 'ID code of the patient, ptr to PATIENT.Patient';
COMMENT ON COLUMN prolisth."Note" IS 'Text of the problem note.';
COMMENT ON COLUMN prolisth."Id" IS 'Problem list that this history is for, ptr to PROLIST.Id';
COMMENT ON COLUMN prolisth."Desc" IS 'Description of problem';
COMMENT ON COLUMN prolisth."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN prolisth."Complaint" IS 'If attached to a treatment plan, then ptr to COMPLAIN.Auto. (0 otherwise)';
COMMENT ON COLUMN prolisth."Audit" IS 'Audit history, ptr to AUDITHIS.Audit.';
COMMENT ON COLUMN prolisth."Area" IS 'Area problem found in (-1=None, 0=Chart, 1=In-Progress, 2=TxHistory, 3=Forms, 4=Attachments, 5=Perio, 6=IMaging, 7=TxPlan, 8=Labs, 9=Prescriptions, 10=ChartAdd)';
COMMENT ON COLUMN prolisth."AppUser" IS 'Approval user, if approval required. Ptr to USERS.User';
COMMENT ON COLUMN prolisth."AppDate" IS 'Date approval obtained, if approval required';


CREATE  TABLE propcid2 (
  "ChartId" character(10) NOT NULL,
  CONSTRAINT propcid2_primary PRIMARY KEY ("ChartId")
) ;
COMMENT ON TABLE propcid2 IS 'Stores next patient chart ID based on previously entered values.';
COMMENT ON COLUMN propcid2."ChartId" IS 'Primary key, ID code to identify the chart';


CREATE  TABLE prosts (
  "Code" character(6) NOT NULL,
  "Description" character varying(30),
  "Show" numeric(5,0),
  "Resolved" numeric(5,0),
  "Inactive" numeric(5,0),
  "Default" numeric(5,0),
  CONSTRAINT prosts_primary PRIMARY KEY ("Code")
) ;
COMMENT ON TABLE prosts IS 'Problem Status Codes';
COMMENT ON COLUMN prosts."Show" IS 'Show problem in the EHR problems tab? (0 = No, 1 = Yes)';
COMMENT ON COLUMN prosts."Resolved" IS 'Status indicates the problem has been resolved? (0 = No, 1 = Yes)';
COMMENT ON COLUMN prosts."Inactive" IS 'Record is inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN prosts."Description" IS 'Description of the status.';
COMMENT ON COLUMN prosts."Default" IS 'Is this the default status for new problems? (0 = No, 1 = Yes)';
COMMENT ON COLUMN prosts."Code" IS 'Primary key, ID code to identify the problem status. ';


CREATE  TABLE province (
  "Province" character(6) NOT NULL,
  "Description" character(30),
  "Country" character(30),
  CONSTRAINT province_primary PRIMARY KEY ("Province")
) ;
COMMENT ON TABLE province IS 'Province / State Codes';
COMMENT ON COLUMN province."Province" IS 'Primary key, ID code to identify the province / state.';
COMMENT ON COLUMN province."Description" IS 'Full name of the province / state.';
COMMENT ON COLUMN province."Country" IS 'Country that this province / state is in. Ptr to COUNTRY.Country';


CREATE  TABLE provnote (
  "ProvNote" numeric(10,0) NOT NULL,
  "Provider" character(10),
  "Note" character varying(255),
  "StartDate" timestamp without time zone,
  "EndDate" timestamp without time zone,
  "Order" numeric(5,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT provnote_primary PRIMARY KEY ("ProvNote")
) ;
COMMENT ON TABLE provnote IS 'Provider Scheduling Notes';
COMMENT ON COLUMN provnote."StartDate" IS 'Date that the note takes effect (optional)';
COMMENT ON COLUMN provnote."Provider" IS 'Provider that the note is for, ptr to PRODUCER.Producer';
COMMENT ON COLUMN provnote."ProvNote" IS 'Primary key, unique ID from sequence.';
COMMENT ON COLUMN provnote."Order" IS 'Display order of the note.';
COMMENT ON COLUMN provnote."Note" IS 'Text of the provider scheduling note.';
COMMENT ON COLUMN provnote."EndDate" IS 'Date that the note expires (optional)';
COMMENT ON COLUMN provnote."Deleted" IS 'Is this note deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN provnote."Audit" IS 'Audit history, Ptr to AUDITHIS.Audit';


CREATE  TABLE provnoth (
  "ProvNotH" numeric(10,0) NOT NULL,
  "ProvNote" numeric(10,0),
  "Provider" character(10),
  "Note" character varying(255),
  "StartDate" timestamp without time zone,
  "EndDate" timestamp without time zone,
  "Order" numeric(5,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT provnoth_primary PRIMARY KEY ("ProvNotH")
) ;
COMMENT ON TABLE provnoth IS 'Provider Scheduling Note History';
COMMENT ON COLUMN provnoth."StartDate" IS 'Date that the note takes effect (optional)';
COMMENT ON COLUMN provnoth."Provider" IS 'Provider that the note is for, Ptr to PRODUCER.Producer';
COMMENT ON COLUMN provnoth."ProvNote" IS 'Provider scheduling note that this history row is for, ptr to PROVNOTE.ProvNote';
COMMENT ON COLUMN provnoth."ProvNotH" IS 'Primary key, unique ID from sequence.';
COMMENT ON COLUMN provnoth."Order" IS 'Display order of the note.';
COMMENT ON COLUMN provnoth."Note" IS 'Text of the provider scheduling note.';
COMMENT ON COLUMN provnoth."EndDate" IS 'Date that the note expires (optional)';
COMMENT ON COLUMN provnoth."Deleted" IS 'Is this note deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN provnoth."Audit" IS 'Audit history, Ptr to AUDITHIS.Audit';


CREATE  TABLE provsig (
  "Provider" character(10) NOT NULL,
  signature bytea,
  "Date" timestamp without time zone,
  "User" numeric(10,0),
  "StationId" numeric(10,0),
  CONSTRAINT provsig_primary PRIMARY KEY ("Provider")
) ;
COMMENT ON TABLE provsig IS 'Provider signature table';
COMMENT ON COLUMN provsig.signature IS 'BLOB data that contains the signature. Note: In Oracle 9i this field is Type: BLOB';
COMMENT ON COLUMN provsig."User" IS 'Id code of the entry user, ptr to USERS.User';
COMMENT ON COLUMN provsig."StationId" IS 'Id code of the station from which this entry was made, ptr to STATION.StationId.';
COMMENT ON COLUMN provsig."Provider" IS 'Id code of the provider, ptr to PRODUCER.Producer';
COMMENT ON COLUMN provsig."Date" IS 'Date the signature was recorded';


CREATE  TABLE provsigh (
  "ProvSigH" numeric(10,0) NOT NULL,
  "HistoryType" numeric(5,0),
  "Provider" character(10),
  signature bytea,
  "Date" timestamp without time zone,
  "User" numeric(10,0),
  "StationId" numeric(10,0),
  CONSTRAINT provsigh_primary PRIMARY KEY ("ProvSigH")
) ;
CREATE INDEX IF NOT EXISTS provsigh_providerkey ON provsigh USING btree ("Provider") TABLESPACE pg_default;
COMMENT ON TABLE provsigh IS 'Audit trail of the provider signature table. ';
COMMENT ON COLUMN provsigh.signature IS 'BLOB data that holds the provider signature, ptr to PROVSIG.Signature Note: In Oracle 9i this field is Type: BLOB';
COMMENT ON COLUMN provsigh."User" IS 'User Id of the entry user, ptr to USERS.User';
COMMENT ON COLUMN provsigh."StationId" IS 'Station Id of the entry user, ptr to STATION.StationId.';
COMMENT ON COLUMN provsigh."Provider" IS 'Id code of the provider, ptr to PROVSIG.Provider';
COMMENT ON COLUMN provsigh."ProvSigH" IS 'Id code to identify the history record';
COMMENT ON COLUMN provsigh."HistoryType" IS 'Type of audit record (0=Unknown, 1=Add, 2=Edit, 3=Allocation, 4=Delete)';
COMMENT ON COLUMN provsigh."Date" IS 'Date the entry was made / modified.';


CREATE  TABLE ptalert (
  "PtAlert" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "AlertType" numeric(5,0),
  "MedAlert" numeric(10,0),
  "Description" character varying(255),
  "Status" numeric(5,0),
  "OnsetDate" timestamp without time zone,
  "Note" character varying(4000),
  "Reaction" character varying(1000),
  "Deleted" numeric(5,0),
  "User" numeric(10,0),
  "AddDateTime" timestamp without time zone,
  "Audit" numeric(10,0),
  "eRxSyncAudit" numeric(10,0),
  "RcopiaID" character varying(32),
  "NDCID" character varying(11),
  "SNOCode" character varying(18),
  CONSTRAINT ptalert_primary PRIMARY KEY ("PtAlert")
) ;
CREATE INDEX IF NOT EXISTS ptalert_datekey ON ptalert USING btree ("Patient", "AddDateTime", "Deleted") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptalert_medalertkey ON ptalert USING btree ("Patient", "Deleted", "AlertType", "MedAlert") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptalert_rcopiakey ON ptalert USING btree ("Patient", "AlertType", "RcopiaID") TABLESPACE pg_default;
COMMENT ON TABLE ptalert IS 'Patient Medical Alerts : contains axiUm and non-axiUm alerts (e.g. Rcopia Allergies and Problems)';
COMMENT ON COLUMN ptalert."eRxSyncAudit" IS 'Audit number used to match log entries to a specific Rcopia sync session';
COMMENT ON COLUMN ptalert."User" IS 'User Id of the entry user, ptr to USERS.User';
COMMENT ON COLUMN ptalert."Status" IS 'Alert status (0 = Active, 1 = Inactive, 2 = Resolved[Problems])';
COMMENT ON COLUMN ptalert."SNOCode" IS 'SNOMED code (used to store problem code sent by Rcopia)';
COMMENT ON COLUMN ptalert."Reaction" IS 'Optional description of allergic reaction';
COMMENT ON COLUMN ptalert."RcopiaID" IS 'RcopiaID for HiTech code (e.g. Allergy Group or Medical Problem)';
COMMENT ON COLUMN ptalert."PtAlert" IS 'Primary key, unique ID from sequence.';
COMMENT ON COLUMN ptalert."Patient" IS 'Patient ID, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptalert."OnsetDate" IS 'Date alert became active';
COMMENT ON COLUMN ptalert."Note" IS 'Note text attached to this alert';
COMMENT ON COLUMN ptalert."NDCID" IS '"NDCID" of drug allergy sent by Rcopia';
COMMENT ON COLUMN ptalert."MedAlert" IS 'Medical Alert ID, ptr to MEDALERT.MedAlert';
COMMENT ON COLUMN ptalert."Description" IS 'Alert description';
COMMENT ON COLUMN ptalert."Deleted" IS 'Is this alert deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN ptalert."Audit" IS 'Audit history, Ptr to AUDITHIS.Audit';
COMMENT ON COLUMN ptalert."AlertType" IS 'Alert type (0 = Clinical Alert, 1 = Allergy, 2 = Medical Problem)';
COMMENT ON COLUMN ptalert."AddDateTime" IS 'Date and Time of entry';


CREATE  TABLE ptalerth (
  "PtAlertH" numeric(10,0) NOT NULL,
  "PtAlert" numeric(10,0),
  "Patient" numeric(10,0),
  "AlertType" numeric(5,0),
  "MedAlert" numeric(10,0),
  "Description" character varying(255),
  "Status" numeric(5,0),
  "OnsetDate" timestamp without time zone,
  "Note" character varying(4000),
  "Reaction" character varying(1000),
  "Deleted" numeric(5,0),
  "User" numeric(10,0),
  "AddDateTime" timestamp without time zone,
  "Audit" numeric(10,0),
  "eRxSyncAudit" numeric(10,0),
  "RcopiaID" character varying(32),
  "NDCID" character varying(11),
  "SNOCode" character varying(18),
  CONSTRAINT ptalerth_primary PRIMARY KEY ("PtAlertH")
) ;
CREATE INDEX IF NOT EXISTS ptalerth_ptalertkey ON ptalerth USING btree ("PtAlert", "Audit") TABLESPACE pg_default;
COMMENT ON TABLE ptalerth IS 'Patient Medical Alerts History';
COMMENT ON COLUMN ptalerth."eRxSyncAudit" IS 'Audit number used to match log entries to a specific Rcopia sync session';
COMMENT ON COLUMN ptalerth."User" IS 'User Id of the entry user, ptr to USERS.User';
COMMENT ON COLUMN ptalerth."Status" IS 'Alert status (0 = Active, 1 = Inactive, 2 = Resolved[Problems])';
COMMENT ON COLUMN ptalerth."SNOCode" IS 'SNOMED code (used to store problem code sent by Rcopia)';
COMMENT ON COLUMN ptalerth."Reaction" IS 'Optional description of allergic reaction';
COMMENT ON COLUMN ptalerth."RcopiaID" IS 'RcopiaID for HiTech code (e.g. Allergy Group or Medical Problem)';
COMMENT ON COLUMN ptalerth."PtAlertH" IS 'Primary key, unique ID from sequence.';
COMMENT ON COLUMN ptalerth."PtAlert" IS 'Patient Alert ID, ptr to PTALERT.PtAlert';
COMMENT ON COLUMN ptalerth."Patient" IS 'Patient ID, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptalerth."OnsetDate" IS 'Date alert became active';
COMMENT ON COLUMN ptalerth."Note" IS 'Note text attached to this alert';
COMMENT ON COLUMN ptalerth."NDCID" IS '"NDCID" of drug allergy sent by Rcopia';
COMMENT ON COLUMN ptalerth."MedAlert" IS 'Medical Alert ID, ptr to MEDALERT.MedAlert';
COMMENT ON COLUMN ptalerth."Description" IS 'Alert description';
COMMENT ON COLUMN ptalerth."Deleted" IS 'Is this alert deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN ptalerth."Audit" IS 'Audit history, Ptr to AUDITHIS.Audit';
COMMENT ON COLUMN ptalerth."AlertType" IS 'Alert type (0 = Clinical Alert, 1 = Allergy, 2 = Medical Problem)';
COMMENT ON COLUMN ptalerth."AddDateTime" IS 'Date and Time of entry';


CREATE  TABLE ptavail (
  "PtAvail" numeric(10,0) NOT NULL,
  "Appointment" numeric(10,0),
  "Sunday" character(24),
  "Monday" character(24),
  "Tuesday" character(24),
  "Wednesday" character(24),
  "Thursday" character(24),
  "Friday" character(24),
  "Saturday" character(24),
  "MinNoticeMode" numeric(5,0),
  "MinNotice" numeric(5,0),
  CONSTRAINT ptavail_primary PRIMARY KEY ("PtAvail")
) ;
CREATE INDEX IF NOT EXISTS ptavail_appointment ON ptavail USING btree ("Appointment") TABLESPACE pg_default;
COMMENT ON TABLE ptavail IS 'Patient Availability Records';
COMMENT ON COLUMN ptavail."Wednesday" IS 'Access times for Wednesday';
COMMENT ON COLUMN ptavail."Tuesday" IS 'Access times for Tuesday';
COMMENT ON COLUMN ptavail."Thursday" IS 'Access times for Thursday';
COMMENT ON COLUMN ptavail."Sunday" IS 'Access times for Sunday (24 hours, ex. 000000000000000000000000)';
COMMENT ON COLUMN ptavail."Saturday" IS 'Access times for Saturday';
COMMENT ON COLUMN ptavail."PtAvail" IS 'sequenced primary key';
COMMENT ON COLUMN ptavail."Monday" IS 'Access times for Monday';
COMMENT ON COLUMN ptavail."MinNoticeMode" IS '0=Days, 1= Hours';
COMMENT ON COLUMN ptavail."MinNotice" IS '#hours/days, minimum notice req’d before appt time';
COMMENT ON COLUMN ptavail."Friday" IS 'Access times for Friday';
COMMENT ON COLUMN ptavail."Appointment" IS 'Ptr to APPOINT.Appointment';


CREATE  TABLE ptbal (
  "Batch" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "RespPatient" numeric(10,0),
  "PtTotal" numeric,
  "PtCurrent" numeric,
  "Pt30" numeric,
  "Pt60" numeric,
  "Pt90" numeric,
  "Pt120" numeric,
  "InsTotal" numeric,
  "InsCurrent" numeric,
  "Ins30" numeric,
  "Ins60" numeric,
  "Ins90" numeric,
  "Ins120" numeric,
  "DisputedTotal" numeric,
  "NonPayPlanTotal" numeric,
  "PaymentPlan" numeric(5,0),
  "AmountDue" numeric,
  "PPlanTotal" numeric,
  "PPlanCurrent" numeric,
  "PPlan30" numeric,
  "PPlan60" numeric,
  "PPlan90" numeric,
  "PPlan120" numeric,
  "NonPPCurrent" numeric,
  "NonPP30" numeric,
  "NonPP60" numeric,
  "NonPP90" numeric,
  "NonPP120" numeric,
  "PPDispTotal" numeric
) ;
CREATE INDEX IF NOT EXISTS ptbal_byguarantor ON ptbal USING btree ("Batch", "RespPatient") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptbal_bypatient ON ptbal USING btree ("Batch", "Patient") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptbal_patient ON ptbal USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE ptbal IS 'Stores patient balance information as of the time/date the report is run in info manager';
COMMENT ON COLUMN ptbal."RespPatient" IS 'Id code to represent the responisble party, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptbal."PtTotal" IS 'Patient total balance';
COMMENT ON COLUMN ptbal."PtCurrent" IS 'Patient current balance (under 30 days)';
COMMENT ON COLUMN ptbal."Pt90" IS 'Patient balance over 90 and 120 days';
COMMENT ON COLUMN ptbal."Pt60" IS 'patient balance between 60 and 90 days';
COMMENT ON COLUMN ptbal."Pt30" IS 'patient balance between 30 and 60 days';
COMMENT ON COLUMN ptbal."Pt120" IS 'Patients balance over 120';
COMMENT ON COLUMN ptbal."PaymentPlan" IS 'Total of payment plan items';
COMMENT ON COLUMN ptbal."Patient" IS 'Id code to represent the patient, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptbal."PPlanTotal" IS 'Payment plan total balance';
COMMENT ON COLUMN ptbal."PPlanCurrent" IS 'Payment plan current balance';
COMMENT ON COLUMN ptbal."PPlan90" IS 'Payment plan balance between 90 and 120';
COMMENT ON COLUMN ptbal."PPlan60" IS 'Payment plan balance between 60 and 90';
COMMENT ON COLUMN ptbal."PPlan30" IS 'Payment plan balance between 30 and 60';
COMMENT ON COLUMN ptbal."PPlan120" IS 'Payment plan balance over 120';
COMMENT ON COLUMN ptbal."PPDispTotal" IS 'Payment plan dispute total amount';
COMMENT ON COLUMN ptbal."NonPayPlanTotal" IS 'Total of non payment plan items';
COMMENT ON COLUMN ptbal."NonPPCurrent" IS 'Non payment plan current balance';
COMMENT ON COLUMN ptbal."NonPP90" IS 'Non payment plan balance between 90 and 120';
COMMENT ON COLUMN ptbal."NonPP60" IS 'Non payment plan balance between 60 and 90';
COMMENT ON COLUMN ptbal."NonPP30" IS 'Non payment plan balance between 30 and 60';
COMMENT ON COLUMN ptbal."NonPP120" IS 'Non payment plan balance over 120';
COMMENT ON COLUMN ptbal."InsTotal" IS 'Insurance total balance';
COMMENT ON COLUMN ptbal."InsCurrent" IS 'Insurance current balance (under 30)';
COMMENT ON COLUMN ptbal."Ins90" IS 'Insurance balance between 90 and 120';
COMMENT ON COLUMN ptbal."Ins60" IS 'Insurance balance between 60 and 90';
COMMENT ON COLUMN ptbal."Ins30" IS 'Insurance balance between 30 and 60';
COMMENT ON COLUMN ptbal."Ins120" IS 'Insurance balance over 120';
COMMENT ON COLUMN ptbal."DisputedTotal" IS 'Total balance of in dispute items';
COMMENT ON COLUMN ptbal."Batch" IS 'Id code to identify the batch';
COMMENT ON COLUMN ptbal."AmountDue" IS 'Total amount now due';


CREATE  TABLE ptbalbat (
  "Batch" numeric(10,0) NOT NULL,
  "CreateDate" timestamp without time zone,
  "Method" character varying(10),
  "AsAtDate" timestamp without time zone,
  "Mode" numeric(5,0),
  CONSTRAINT ptbalbat_primary PRIMARY KEY ("Batch")
) ;
CREATE INDEX IF NOT EXISTS ptbalbat_asatdate ON ptbalbat USING btree (trunc("AsAtDate")) TABLESPACE pg_default;
COMMENT ON TABLE ptbalbat IS 'Records a record for each time the A/R package has been run in Info Manager';
COMMENT ON COLUMN ptbalbat."Mode" IS '0 implies By Patient, 1 implies by Guarantor';
COMMENT ON COLUMN ptbalbat."Method" IS 'A/R methodology (0=Open item, 1=Balance Forward)';
COMMENT ON COLUMN ptbalbat."CreateDate" IS 'Date/time that the A/R package was run';
COMMENT ON COLUMN ptbalbat."Batch" IS 'Id code to identify the batch - points to PTBAL.Batch';
COMMENT ON COLUMN ptbalbat."AsAtDate" IS 'The as of date/time for backdated A/R';


CREATE  TABLE ptcase (
  "PtCase" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "CaseType" character(6),
  "CreationDate" timestamp without time zone,
  "SiteName" character varying(30),
  "ProdType" character(1),
  "ExamDate" timestamp without time zone,
  "StartDate" timestamp without time zone,
  "CompleteDate" timestamp without time zone,
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT ptcase_primary PRIMARY KEY ("PtCase")
) ;
CREATE INDEX IF NOT EXISTS ptcase_patientkey ON ptcase USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE ptcase IS 'Patient cases for Surgery module.';
COMMENT ON COLUMN ptcase."StartDate" IS 'Date that this case was started.';
COMMENT ON COLUMN ptcase."SiteName" IS 'Site name for this case.';
COMMENT ON COLUMN ptcase."PtCase" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN ptcase."ProdType" IS 'Provider type for this case.';
COMMENT ON COLUMN ptcase."Patient" IS 'ID code of the patient, ptr to PATIENT.Patient.';
COMMENT ON COLUMN ptcase."ExamDate" IS 'Date of the exam for this case.';
COMMENT ON COLUMN ptcase."Deleted" IS 'Is this case deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptcase."CreationDate" IS 'Date that the case was created.';
COMMENT ON COLUMN ptcase."CompleteDate" IS 'Date that this case was completed.';
COMMENT ON COLUMN ptcase."CaseType" IS 'ID code of the case type, ptr to CASETYPE.CaseType.';
COMMENT ON COLUMN ptcase."Audit" IS 'Audit record for this case, ptr to AUDITHIS.Audit.';


CREATE  TABLE ptcaseh (
  "PtCaseH" numeric(10,0) NOT NULL,
  "PtCase" numeric(10,0),
  "Patient" numeric(10,0),
  "CaseType" character(6),
  "CreationDate" timestamp without time zone,
  "SiteName" character varying(30),
  "ProdType" character(1),
  "ExamDate" timestamp without time zone,
  "StartDate" timestamp without time zone,
  "CompleteDate" timestamp without time zone,
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT ptcaseh_primary PRIMARY KEY ("PtCaseH")
) ;
CREATE INDEX IF NOT EXISTS ptcaseh_ptcasekey ON ptcaseh USING btree ("PtCase") TABLESPACE pg_default;
COMMENT ON TABLE ptcaseh IS 'History of patient cases.';
COMMENT ON COLUMN ptcaseh."StartDate" IS 'Date that this case was started.';
COMMENT ON COLUMN ptcaseh."SiteName" IS 'Site name for this case.';
COMMENT ON COLUMN ptcaseh."PtCaseH" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN ptcaseh."PtCase" IS 'Case that this history record is for, ptr to PTCASE.PtCase.';
COMMENT ON COLUMN ptcaseh."ProdType" IS 'Provider type for this case.';
COMMENT ON COLUMN ptcaseh."Patient" IS 'ID code of the patient, ptr to PATIENT.Patient.';
COMMENT ON COLUMN ptcaseh."ExamDate" IS 'Date of the exam for this case.';
COMMENT ON COLUMN ptcaseh."Deleted" IS 'Is this case deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptcaseh."CreationDate" IS 'Date that the case was created.';
COMMENT ON COLUMN ptcaseh."CompleteDate" IS 'Date that this case was completed.';
COMMENT ON COLUMN ptcaseh."CaseType" IS 'ID code of the case type, ptr to CASETYPE.CaseType.';
COMMENT ON COLUMN ptcaseh."Audit" IS 'Audit record for this case, ptr to AUDITHIS.Audit.';


CREATE  TABLE ptcasejt (
  "PtCase" numeric(10,0) NOT NULL,
  "Type" numeric(5,0) NOT NULL,
  "Id" numeric(10,0) NOT NULL,
  "NeedAnesVitals" numeric(5,0),
  CONSTRAINT ptcasejt_primary PRIMARY KEY ("PtCase", "Type", "Id")
) ;
CREATE INDEX IF NOT EXISTS ptcasejt_typekey ON ptcasejt USING btree ("Type", "Id") TABLESPACE pg_default;
COMMENT ON TABLE ptcasejt IS 'Join table for attaching various different records to a patient case.';
COMMENT ON COLUMN ptcasejt."Type" IS 'Primary key component, type of record referenced by the Id column (0 = APPOINT, 1 = PTRECALL, 2 = TREATME2/TRX, 3 = NOTES2, 4 = TXPLAN, 5 = PTLETTER, 6 = PTCONT, 7 = LABORDER, 8 = PFORM, 9 = PTREFER, 10 = PTIMPLNT)';
COMMENT ON COLUMN ptcasejt."PtCase" IS 'Primary key component, ptr to PTCASE.PtCase.';
COMMENT ON COLUMN ptcasejt."NeedAnesVitals" IS 'To inidicate if Anes/Vitals are needed (for Appointment joint only)';
COMMENT ON COLUMN ptcasejt."Id" IS 'Primary key component, ptr to primary key of table referenced by the Type column.';


CREATE  TABLE ptconhis (
  "ContactHis" numeric(10,0) NOT NULL,
  "HistoryType" numeric(5,0),
  "Contact" numeric(10,0),
  "Patient" numeric(10,0),
  "Date" timestamp without time zone,
  "Time" numeric(10,0),
  "User" numeric(10,0),
  "StationId" numeric(10,0),
  "Note" character varying(4000),
  "Deleted" numeric(5,0),
  "NoteCode" character(6),
  "ContactDate" timestamp without time zone,
  "ContactTime" numeric(10,0),
  "ContactUser" numeric(10,0),
  CONSTRAINT ptconhis_primary PRIMARY KEY ("ContactHis")
) ;
CREATE INDEX IF NOT EXISTS ptconhis_contactkey ON ptconhis USING btree ("Contact") TABLESPACE pg_default;
COMMENT ON TABLE ptconhis IS 'History record of changes to the patient contact records. ';
COMMENT ON COLUMN ptconhis."User" IS 'Id code of the entry user, ptr to PTCONT.User';
COMMENT ON COLUMN ptconhis."Time" IS 'Time the note was added or last modified, ptr to PTCONT.Time';
COMMENT ON COLUMN ptconhis."StationId" IS 'Id code of the workstation from which this entry was made, ptr to PTCONT.StationId';
COMMENT ON COLUMN ptconhis."Patient" IS 'Id code of the patient, ptr to PTCONT.Patient';
COMMENT ON COLUMN ptconhis."NoteCode" IS 'Id code to identify the patient contact note';
COMMENT ON COLUMN ptconhis."Note" IS 'Text area to hold the contents of the note, ptr to PTCONT.Note';
COMMENT ON COLUMN ptconhis."HistoryType" IS 'The type of history being recorded (1= Note Added, 2= Note Modified, 4= Note Deleted). ';
COMMENT ON COLUMN ptconhis."Deleted" IS 'Is deleted? (0 = No, 1 = Yes), ptr to PTCONT.Deleted';
COMMENT ON COLUMN ptconhis."Date" IS 'Date the note was added or last modified, ptr to PTCONT.Date';
COMMENT ON COLUMN ptconhis."ContactUser" IS 'User that contacted the patient, ptr to USERS.User';
COMMENT ON COLUMN ptconhis."ContactTime" IS 'Time that the patient was contacted, in minutes from midnight. ';
COMMENT ON COLUMN ptconhis."ContactHis" IS 'Id code of the patient contact history record';
COMMENT ON COLUMN ptconhis."ContactDate" IS 'Date that the patient was contacted.';
COMMENT ON COLUMN ptconhis."Contact" IS 'Id code to identify the type of contact, ptr to PTCONT.Contact';


CREATE  TABLE ptcont (
  "Contact" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "Date" timestamp without time zone,
  "Time" numeric(10,0),
  "User" numeric(10,0),
  "StationId" numeric(10,0),
  "Note" character varying(4000),
  "Deleted" numeric(5,0),
  "NoteCode" character(6),
  "ContactDate" timestamp without time zone,
  "ContactTime" numeric(10,0),
  "ContactUser" numeric(10,0),
  CONSTRAINT ptcont_primary PRIMARY KEY ("Contact")
) ;
CREATE INDEX IF NOT EXISTS ptcont_patientkey ON ptcont USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE ptcont IS 'Record of Patient Contacts ';
COMMENT ON COLUMN ptcont."User" IS 'Id code of the entry user, ptr to USERS.User';
COMMENT ON COLUMN ptcont."Time" IS 'Time the note was added or last modified';
COMMENT ON COLUMN ptcont."StationId" IS 'Id code of the workstation from which this entry was made';
COMMENT ON COLUMN ptcont."Patient" IS 'Id code of the patient, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptcont."NoteCode" IS 'Id code to identify the patient contact note';
COMMENT ON COLUMN ptcont."Note" IS 'Text area that holds the contents of the note.';
COMMENT ON COLUMN ptcont."Deleted" IS 'Is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptcont."Date" IS 'Date the note was added or last modified';
COMMENT ON COLUMN ptcont."ContactUser" IS 'User that contacted the patient, ptr to USERS.User';
COMMENT ON COLUMN ptcont."ContactTime" IS 'Time that the patient was contacted, in minutes from midnight. ';
COMMENT ON COLUMN ptcont."ContactDate" IS 'Date that the patient was contacted.';
COMMENT ON COLUMN ptcont."Contact" IS 'Id code to identify the patient contact record';


CREATE  TABLE ptdepend (
  "PolicyId" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0) NOT NULL,
  "Number" character(15),
  "IsCovered" numeric(5,0),
  "Relation" numeric(5,0),
  "HasPatientLimit" numeric(5,0),
  "PatientLimit" numeric,
  "PatientDeduct" numeric,
  "LimitBalance" numeric,
  "DeductBalance" numeric,
  "Date" timestamp without time zone,
  "Time" numeric(10,0),
  "User" numeric(10,0),
  "StationId" numeric(10,0),
  "Deleted" numeric(5,0),
  "BillOrder" numeric(5,0),
  "VisitBalance" numeric(5,0),
  "MedicaidCoPay" numeric(5,0),
  "StartDate" timestamp without time zone,
  "EndDate" timestamp without time zone,
  "CardVerNo" character varying(2),
  "CorrectStatus" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT ptdepend_primary PRIMARY KEY ("PolicyId", "Patient")
) ;
CREATE INDEX IF NOT EXISTS ptdepend_patient ON ptdepend USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE ptdepend IS 'Insurance Policy Dependants (patients covered by insurance)';
COMMENT ON COLUMN ptdepend."VisitBalance" IS 'Number of visits left (if INSURANC.LimitedVisits=1)';
COMMENT ON COLUMN ptdepend."User" IS 'ID code of the entry user, ptr to USERS.User';
COMMENT ON COLUMN ptdepend."Time" IS 'Time the entry was made';
COMMENT ON COLUMN ptdepend."StationId" IS 'ID code of the station from which this record was added, ptr to STATION.StationId';
COMMENT ON COLUMN ptdepend."StartDate" IS 'Start date of dependant coverage under this policy';
COMMENT ON COLUMN ptdepend."Relation" IS 'Dependent relationship to the policy holder (0=Self, 1=Spouse, 2=CommonLaw, 3=Child, 4=Other, 5=Handicapped Dependant, 6=Significant Other, 7=Employee)';
COMMENT ON COLUMN ptdepend."PolicyId" IS 'Primary key component, insurance policy that this is for. Ptr to PTPOL.PolicyId';
COMMENT ON COLUMN ptdepend."PatientLimit" IS 'Dollar ($) amount of the patient limit, ptr to POLICY.PatientLimit';
COMMENT ON COLUMN ptdepend."PatientDeduct" IS 'Dollar ($) amount of the patient deductable, ptr to POLICY.PatientDeduct';
COMMENT ON COLUMN ptdepend."Patient" IS 'Primary key component, dependant patient ID. Ptr to PATIENT.Patient';
COMMENT ON COLUMN ptdepend."Number" IS 'Dependent number/ freetext ID field.';
COMMENT ON COLUMN ptdepend."MedicaidCoPay" IS 'Apply Medicaid Co-pay? (0=No, 1=Yes)';
COMMENT ON COLUMN ptdepend."LimitBalance" IS 'Dollar ($) amount of the limit balance, ptr to POLICY.LimitBalance';
COMMENT ON COLUMN ptdepend."IsCovered" IS 'Dependent is covered by this policy? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptdepend."HasPatientLimit" IS 'Does this benefit plan have a patient limit? (0 = No, 1 = Yes, 2 = Yes, for adults only)';
COMMENT ON COLUMN ptdepend."EndDate" IS 'End date of dependant coverage under this policy';
COMMENT ON COLUMN ptdepend."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptdepend."DeductBalance" IS 'Dollar ($) amount of the deductable balance, ptr to POLICY.DeductBalance';
COMMENT ON COLUMN ptdepend."Date" IS 'Date the record was added/altered';
COMMENT ON COLUMN ptdepend."CorrectStatus" IS 'Status for the insurance policy (0-not defined, 1-correct, 2-incorrect)';
COMMENT ON COLUMN ptdepend."CardVerNo" IS 'For CDANet, Dentaid policy card version number. Either blank, or a number [1..99]. (Canada only)';
COMMENT ON COLUMN ptdepend."BillOrder" IS 'Number to indicate the policy billing order, If no order is specified will be based on the current insurance birth date rule in conjunction with the primary employer flag.';


CREATE  TABLE ptdepext (
  "PtDepExt" numeric(10,0) NOT NULL,
  "PolicyId" numeric(10,0),
  "Patient" numeric(10,0),
  "Type" numeric(5,0),
  "Visits" numeric(5,0),
  "Comment" character varying(80),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT ptdepext_primary PRIMARY KEY ("PtDepExt")
) ;
CREATE INDEX IF NOT EXISTS ptdepext_policyidkey ON ptdepext USING btree ("PolicyId", "Patient") TABLESPACE pg_default;
COMMENT ON TABLE ptdepext IS 'Patient Visit Extensions';
COMMENT ON COLUMN ptdepext."Visits" IS 'Number of extended/revoked visits';
COMMENT ON COLUMN ptdepext."Type" IS 'Type (0 = Extend, 1 = Revoke)';
COMMENT ON COLUMN ptdepext."PtDepExt" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN ptdepext."PolicyId" IS 'Policy that the visit extension is for, ptr to PTPOL.PolicyId';
COMMENT ON COLUMN ptdepext."Patient" IS 'Dependent that the visit extension is for, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptdepext."Deleted" IS 'Extension is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptdepext."Comment" IS 'Free text entry field to provide a comment about the extension';
COMMENT ON COLUMN ptdepext."Audit" IS 'Audit record, ptr to AUDITHIS.Audit';


CREATE  TABLE ptdephis (
  "PtDepHis" numeric(10,0) NOT NULL,
  "HistoryType" numeric(5,0),
  "PolicyId" numeric(10,0),
  "Patient" numeric(10,0),
  "Number" character(15),
  "IsCovered" numeric(5,0),
  "Relation" numeric(5,0),
  "HasPatientLimit" numeric(5,0),
  "PatientLimit" numeric,
  "PatientDeduct" numeric,
  "LimitBalance" numeric,
  "DeductBalance" numeric,
  "Date" timestamp without time zone,
  "Time" numeric(10,0),
  "User" numeric(10,0),
  "StationId" numeric(10,0),
  "Deleted" numeric(5,0),
  "BillOrder" numeric(5,0),
  "VisitBalance" numeric(5,0),
  "MedicaidCoPay" numeric(5,0),
  "StartDate" timestamp without time zone,
  "EndDate" timestamp without time zone,
  "CardVerNo" character varying(2),
  "CorrectStatus" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT ptdephis_primary PRIMARY KEY ("PtDepHis")
) ;
CREATE INDEX IF NOT EXISTS ptdephis_ptdependkey ON ptdephis USING btree ("PolicyId", "Patient") TABLESPACE pg_default;
COMMENT ON TABLE ptdephis IS 'Record of changes to PTDEPEND records';
COMMENT ON COLUMN ptdephis."VisitBalance" IS 'Number of visits left (if INSURANC.LimitedVisits=1)';
COMMENT ON COLUMN ptdephis."User" IS 'ID code of the entry user, ptr to USERS.User';
COMMENT ON COLUMN ptdephis."Time" IS 'Time the entry was made';
COMMENT ON COLUMN ptdephis."StationId" IS 'ID code of the station from which this record was added, ptr to STATION.StationId';
COMMENT ON COLUMN ptdephis."StartDate" IS 'Start date of dependant coverage under this policy';
COMMENT ON COLUMN ptdephis."Relation" IS 'Dependent relationship to the policy holder (0=Self, 1=Spouse, 2=CommonLaw, 3=Child, 4=Other, 5=Handicapped Dependant, 6=Significant Other, 7=Employee)';
COMMENT ON COLUMN ptdephis."PtDepHis" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN ptdephis."PolicyId" IS 'Insurance policy that this is for. Ptr to PTPOL.PolicyId';
COMMENT ON COLUMN ptdephis."PatientLimit" IS 'Dollar ($) amount of the patient limit, ptr to POLICY.PatientLimit';
COMMENT ON COLUMN ptdephis."PatientDeduct" IS 'Dollar ($) amount of the patient deductable, ptr to POLICY.PatientDeduct';
COMMENT ON COLUMN ptdephis."Patient" IS 'Dependant patient ID. Ptr to PATIENT.Patient';
COMMENT ON COLUMN ptdephis."Number" IS 'Dependent number/ freetext ID field.';
COMMENT ON COLUMN ptdephis."MedicaidCoPay" IS 'Apply Medicaid Co-pay? (0=No, 1=Yes)';
COMMENT ON COLUMN ptdephis."LimitBalance" IS 'Dollar ($) amount of the limit balance, ptr to POLICY.LimitBalance';
COMMENT ON COLUMN ptdephis."IsCovered" IS 'Dependent is covered by this policy? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptdephis."HistoryType" IS 'Type of history record. (1=Add, 2=Modify, 4=Delete)';
COMMENT ON COLUMN ptdephis."HasPatientLimit" IS 'Does this benefit plan have a patient limit? (0 = No, 1 = Yes, 2 = Yes, for adults only)';
COMMENT ON COLUMN ptdephis."EndDate" IS 'End date of dependant coverage under this policy';
COMMENT ON COLUMN ptdephis."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptdephis."DeductBalance" IS 'Dollar ($) amount of the deductable balance, ptr to POLICY.DeductBalance';
COMMENT ON COLUMN ptdephis."Date" IS 'Date the record was added/altered';
COMMENT ON COLUMN ptdephis."CorrectStatus" IS 'Status for the insurance policy (0-not defined, 1-correct, 2-incorrect)';
COMMENT ON COLUMN ptdephis."CardVerNo" IS 'For CDANet, Dentaid policy card version number. Either blank, or a number [1..99]. (Canada only)';
COMMENT ON COLUMN ptdephis."BillOrder" IS 'Number to indicate the policy billing order, If no order is specified will be based on the current insurance birth date rule in conjunction with the primary employer flag.';


CREATE  TABLE ptekg (
  "PtEKG" numeric(10,0) NOT NULL,
  "Appointment" numeric(10,0),
  "StartTime" timestamp without time zone,
  "Length" numeric(5,0),
  "Type" numeric(5,0),
  "Audit" numeric(10,0),
  "VitMon" character(6),
  CONSTRAINT ptekg_primary PRIMARY KEY ("PtEKG")
) ;
CREATE INDEX IF NOT EXISTS ptekg_apptstarttimekey ON ptekg USING btree ("Appointment", "StartTime") TABLESPACE pg_default;
COMMENT ON TABLE ptekg IS 'Patient EKGs for Surgery module.';
COMMENT ON COLUMN ptekg."VitMon" IS 'Vital Monitor used to capture these EKG info.';
COMMENT ON COLUMN ptekg."Type" IS 'Type of data being captured.';
COMMENT ON COLUMN ptekg."StartTime" IS 'Start date and time for the given collection of EKG data sets.';
COMMENT ON COLUMN ptekg."PtEKG" IS 'Primary key, unique code to identify single capture of EKGs.';
COMMENT ON COLUMN ptekg."Length" IS 'Length in seconds for the given collection of data.';
COMMENT ON COLUMN ptekg."Audit" IS 'Audit record for this EKGs captured, ptr to AUDITHIS.Audit.';
COMMENT ON COLUMN ptekg."Appointment" IS 'Appointment, ptr to APPOINT.Appointment.';


CREATE  TABLE ptekgit (
  "PtEKGIt" numeric(10,0) NOT NULL,
  "PtEKG" numeric(10,0),
  "EntryTime" timestamp without time zone,
  ekgdata bytea,
  CONSTRAINT ptekgit_primary PRIMARY KEY ("PtEKGIt")
) ;
CREATE INDEX IF NOT EXISTS ptekgit_ptekgkey ON ptekgit USING btree ("PtEKG") TABLESPACE pg_default;
COMMENT ON TABLE ptekgit IS 'Patient EKGs detail records.';
COMMENT ON COLUMN ptekgit.ekgdata IS 'The data set captured for the given date/time.';
COMMENT ON COLUMN ptekgit."PtEKGIt" IS 'Primary key, unique code to identify the one set of EKG data';
COMMENT ON COLUMN ptekgit."PtEKG" IS 'Ptr to PTEKG table to identify the parent record for this collection';
COMMENT ON COLUMN ptekgit."EntryTime" IS 'The date and time for the given data set.';


CREATE  TABLE ptemphis (
  "PtEmpHis" numeric(10,0) NOT NULL,
  "HistoryType" numeric(5,0),
  "Patient" numeric(10,0),
  "Employer" numeric(10,0),
  "Primary" numeric(5,0),
  "Area" character(4),
  "Tel" character(8),
  "Ext" character varying(6),
  "Occupation" character(30),
  "Date" timestamp without time zone,
  "Time" numeric(10,0),
  "User" numeric(10,0),
  "StationId" numeric(10,0),
  "Deleted" numeric(5,0),
  "EndDate" timestamp without time zone,
  CONSTRAINT ptemphis_primary PRIMARY KEY ("PtEmpHis")
) ;
CREATE INDEX IF NOT EXISTS ptemphis_ptemploykey ON ptemphis USING btree ("Patient", "Employer") TABLESPACE pg_default;
COMMENT ON TABLE ptemphis IS 'Record of changes to PTEMPLOY records';
COMMENT ON COLUMN ptemphis."User" IS 'ID code of the entry user, ptr to USERS.User';
COMMENT ON COLUMN ptemphis."Time" IS 'Time the record was added/altered';
COMMENT ON COLUMN ptemphis."Tel" IS 'Telephone number of the employer. ';
COMMENT ON COLUMN ptemphis."StationId" IS 'ID code of the station from which this record was added, ptr to STATION.StationId';
COMMENT ON COLUMN ptemphis."PtEmpHis" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN ptemphis."Primary" IS 'Is this the primary employer? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptemphis."Patient" IS 'Patient who is employed. Ptr to PATIENT.Patient';
COMMENT ON COLUMN ptemphis."Occupation" IS 'Occupation of the patient';
COMMENT ON COLUMN ptemphis."HistoryType" IS 'Type of history record. (1=Add, 2=Modify, 4=Delete)';
COMMENT ON COLUMN ptemphis."Ext" IS 'Telephone extension of the employer. ';
COMMENT ON COLUMN ptemphis."EndDate" IS 'Date that the employment with this employer ends. ';
COMMENT ON COLUMN ptemphis."Employer" IS 'Employer that employs the patient. Ptr to EMPLOYER.Employer';
COMMENT ON COLUMN ptemphis."Deleted" IS 'Is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptemphis."Date" IS 'Date the record was added/altered';
COMMENT ON COLUMN ptemphis."Area" IS 'Telephone area code of the employer. ';


CREATE  TABLE ptemploy (
  "Patient" numeric(10,0) NOT NULL,
  "Employer" numeric(10,0) NOT NULL,
  "Primary" numeric(5,0),
  "Area" character(4),
  "Tel" character(8),
  "Ext" character varying(6),
  "Occupation" character(30),
  "Date" timestamp without time zone,
  "Time" numeric(10,0),
  "User" numeric(10,0),
  "StationId" numeric(10,0),
  "Deleted" numeric(5,0),
  "EndDate" timestamp without time zone,
  CONSTRAINT ptemploy_primary PRIMARY KEY ("Patient", "Employer")
) ;
CREATE INDEX IF NOT EXISTS ptemploy_employer ON ptemploy USING btree ("Employer") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptemploy_patient ON ptemploy USING btree ("Patient") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptemploy_primaryflagkey ON ptemploy USING btree ("Patient", "Primary") TABLESPACE pg_default;
COMMENT ON TABLE ptemploy IS 'Patient Employer records (links a patient to an employer)';
COMMENT ON COLUMN ptemploy."User" IS 'ID code of the entry user, ptr to USERS.User';
COMMENT ON COLUMN ptemploy."Time" IS 'Time the record was added/altered';
COMMENT ON COLUMN ptemploy."Tel" IS 'Telephone number of the employer. ';
COMMENT ON COLUMN ptemploy."StationId" IS 'ID code of the station from which this record was added, ptr to STATION.StationId';
COMMENT ON COLUMN ptemploy."Primary" IS 'Is this the primary employer? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptemploy."Patient" IS 'Primary key component, patient who is employed. Ptr to PATIENT.Patient';
COMMENT ON COLUMN ptemploy."Occupation" IS 'Occupation of the patient';
COMMENT ON COLUMN ptemploy."Ext" IS 'Telephone extension of the employer. ';
COMMENT ON COLUMN ptemploy."EndDate" IS 'Date that the employment with this employer ends. ';
COMMENT ON COLUMN ptemploy."Employer" IS 'Primary key component, employer that employs the patient. Ptr to EMPLOYER.Employer';
COMMENT ON COLUMN ptemploy."Deleted" IS 'Is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptemploy."Date" IS 'Date the record was added/altered';
COMMENT ON COLUMN ptemploy."Area" IS 'Telephone area code of the employer. ';


CREATE  TABLE pterx (
  "Patient" numeric(10,0) NOT NULL,
  "LastUpdateRx" character varying(24),
  "LastUpdateMeds" character varying(24),
  "LastUpdateReviews" character varying(24),
  "LastUpdateAllergies" character varying(24),
  "LastUpdateProblems" character varying(24),
  "RequiresSync" numeric(5,0),
  CONSTRAINT pterx_primary PRIMARY KEY ("Patient")
) ;
COMMENT ON TABLE pterx IS 'Patient e-Rx update timestamps';
COMMENT ON COLUMN pterx."RequiresSync" IS 'Does this patient require a sync w Rcopia? (0=No, 1=Yes)';
COMMENT ON COLUMN pterx."Patient" IS 'Primary key, ptr to PATIENT.Patient';
COMMENT ON COLUMN pterx."LastUpdateRx" IS 'Date and time of last prescription update with Rcopia for this patient';
COMMENT ON COLUMN pterx."LastUpdateReviews" IS 'Date and time of last medication review with Rcopia for this patient. ';
COMMENT ON COLUMN pterx."LastUpdateProblems" IS 'Date and time of last problem sync with Rcopia for this patient. ';
COMMENT ON COLUMN pterx."LastUpdateMeds" IS 'Date and time of last medication update with Rcopia for this patient';
COMMENT ON COLUMN pterx."LastUpdateAllergies" IS 'Date and time of last allergie sync with Rcopia for this patient. ';


CREATE  TABLE ptfacul (
  "PtFacul" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "Faculty" numeric(10,0),
  "Discipline" character(15),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "IsPrimary" numeric(5,0),
  CONSTRAINT ptfacul_primary PRIMARY KEY ("PtFacul")
) ;
CREATE INDEX IF NOT EXISTS ptfacul_patientkey ON ptfacul USING btree ("Patient", "Faculty", "Discipline") TABLESPACE pg_default;
COMMENT ON TABLE ptfacul IS 'Patient Faculty Assignments';
COMMENT ON COLUMN ptfacul."PtFacul" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN ptfacul."Patient" IS 'Patient that the faculty is assigned to, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptfacul."IsPrimary" IS 'Is this the primary assigned faculty for this patient? (0=No, 1=Yes)';
COMMENT ON COLUMN ptfacul."Faculty" IS 'Faculty member who is assigned, ptr to USERS.User';
COMMENT ON COLUMN ptfacul."Discipline" IS 'If the faculty member is overseeing treatments for a particular discipline, the discipline code. Ptr to CLASS.Class.';
COMMENT ON COLUMN ptfacul."Deleted" IS 'Deleted assignment? (0=No, 1=Yes) ';
COMMENT ON COLUMN ptfacul."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE ptfaculh (
  "PtFaculH" numeric(10,0) NOT NULL,
  "PtFacul" numeric(10,0),
  "Patient" numeric(10,0),
  "Faculty" numeric(10,0),
  "Discipline" character(15),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "IsPrimary" numeric(5,0),
  CONSTRAINT ptfaculh_primary PRIMARY KEY ("PtFaculH")
) ;
CREATE INDEX IF NOT EXISTS ptfaculh_ptfaculkey ON ptfaculh USING btree ("PtFacul") TABLESPACE pg_default;
COMMENT ON TABLE ptfaculh IS 'Patient Faculty Assignment History';
COMMENT ON COLUMN ptfaculh."PtFaculH" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN ptfaculh."PtFacul" IS 'Faculty assignment that this history is for, ptr to PTFACUL.PtFacul';
COMMENT ON COLUMN ptfaculh."Patient" IS 'Patient that the faculty is assigned to, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptfaculh."IsPrimary" IS 'Is this the primary assigned faculty for this patient? (0=No, 1=Yes)';
COMMENT ON COLUMN ptfaculh."Faculty" IS 'Faculty member who is assigned, ptr to USERS.User';
COMMENT ON COLUMN ptfaculh."Discipline" IS 'If the faculty member is overseeing treatments for a particular discipline, the discipline code. Ptr to CLASS.Class.';
COMMENT ON COLUMN ptfaculh."Deleted" IS 'Deleted assignment? (0=No, 1=Yes) ';
COMMENT ON COLUMN ptfaculh."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE ptfund (
  "PtFund" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "Insurance" character(6),
  "Type" numeric(5,0),
  "Amount" numeric,
  "TrxType" numeric(5,0),
  "TrxOrigRecNo" numeric(10,0),
  "Comment" character varying(200),
  "Method" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT ptfund_primary PRIMARY KEY ("PtFund")
) ;
CREATE INDEX IF NOT EXISTS ptfund_patient ON ptfund USING btree ("Patient") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptfund_trxorigrecno ON ptfund USING btree ("TrxOrigRecNo") TABLESPACE pg_default;
COMMENT ON TABLE ptfund IS 'Deposit and withdrawal records for each patient  reserve funds';
COMMENT ON COLUMN ptfund."Type" IS '0 = Deposit(+), 1 = Withdrawal(-)';
COMMENT ON COLUMN ptfund."TrxType" IS 'Associated TRX.Type';
COMMENT ON COLUMN ptfund."TrxOrigRecNo" IS 'Associated TRX.OrigRecNo';
COMMENT ON COLUMN ptfund."PtFund" IS 'Primary Key: internal ID (from sequence)';
COMMENT ON COLUMN ptfund."Patient" IS 'Ptr to PATIENT.Patient';
COMMENT ON COLUMN ptfund."Method" IS '0 = automated, 1 = manual';
COMMENT ON COLUMN ptfund."Insurance" IS 'Ptr to INSURANC.Company';
COMMENT ON COLUMN ptfund."Comment" IS 'Comment';
COMMENT ON COLUMN ptfund."Audit" IS 'Ptr to AUDITHIS.Audit';
COMMENT ON COLUMN ptfund."Amount" IS 'fund amount';


CREATE  TABLE ptgender (
  "Patient" numeric(10,0) NOT NULL,
  "PtSexOrient" numeric(5,0),
  "PtSOther" character varying(255),
  "PtSDeclined" numeric(5,0),
  "PtGenderId" numeric(5,0),
  "PtGOther" character varying(255),
  "PtGDeclined" numeric(5,0),
  "Audit" numeric(10,0),
  "PtPreferPronouns" numeric(5,0) NOT NULL DEFAULT 0,
  "PtPronounsOther" character varying(255),
  "PtPronounsDeclined" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT ptgender_primary PRIMARY KEY ("Patient")
) ;
COMMENT ON TABLE ptgender IS 'Table for storing patient sexual orientation / gender identity information';
COMMENT ON COLUMN ptgender."PtSexOrient" IS 'Sexual Orientation: 0-N/A; 1-straight/heterosexual;2-lesbian/gay; 3-bisexual; 4-do not know';
COMMENT ON COLUMN ptgender."PtSOther" IS 'Free format text to specify other sexual orientation; PtSOrient has to be zero if this is entered';
COMMENT ON COLUMN ptgender."PtSDeclined" IS 'Declined to answer sexual orientation: 0-no; 1-yes';
COMMENT ON COLUMN ptgender."PtPronounsOther" IS 'Free format text to specify other preferred pronouns';
COMMENT ON COLUMN ptgender."PtPronounsDeclined" IS 'Declined to answer preferred pronouns: 0-no; 1-yes';
COMMENT ON COLUMN ptgender."PtPreferPronouns" IS 'Preferred Pronouns: 0-N/A; 1-He/Him; 2-She/Her; 3-They/Them; 4-Don''t Know';
COMMENT ON COLUMN ptgender."PtGenderId" IS 'Gender Identity: 0-N/A; 1-male; 2-female; 4-transgender male; 8-transgender female; 16-genderqueer; can be a combination of one or more';
COMMENT ON COLUMN ptgender."PtGOther" IS 'Free format text to specify other gender identity';
COMMENT ON COLUMN ptgender."PtGDeclined" IS 'Declined to answer gender identity: 0-no; 1-yes';
COMMENT ON COLUMN ptgender."Patient" IS 'Primary key, Patient Id';
COMMENT ON COLUMN ptgender."Audit" IS 'Audit Id, audit record of the user/station that last updated this information';


CREATE  TABLE ptgendrh (
  "PtGendrH" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "PtSexOrient" numeric(5,0),
  "PtSOther" character varying(255),
  "PtSDeclined" numeric(5,0),
  "PtGenderId" numeric(5,0),
  "PtGOther" character varying(255),
  "PtGDeclined" numeric(5,0),
  "Audit" numeric(10,0),
  "PtPreferPronouns" numeric(5,0) NOT NULL DEFAULT 0,
  "PtPronounsOther" character varying(255),
  "PtPronounsDeclined" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT ptgendrh_primary PRIMARY KEY ("PtGendrH")
) ;
CREATE INDEX IF NOT EXISTS ptgendrh_patient ON ptgendrh USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE ptgendrh IS 'Table for storing history of patient sexual orientation / gender identity information';
COMMENT ON COLUMN ptgendrh."PtSexOrient" IS 'Sexual Orientation: 0-N/A; 1-straight/heterosexual;2-lesbian/gay; 3-bisexual; 4-do not know';
COMMENT ON COLUMN ptgendrh."PtSOther" IS 'Free format text to specify other sexual orientation; PtSOrient has to be zero if this is entered';
COMMENT ON COLUMN ptgendrh."PtSDeclined" IS 'Declined to answer sexual orientation: 0-no; 1-yes';
COMMENT ON COLUMN ptgendrh."PtPronounsOther" IS 'Free format text to specify other preferred pronouns';
COMMENT ON COLUMN ptgendrh."PtPronounsDeclined" IS 'Declined to answer preferred pronouns: 0-no; 1-yes';
COMMENT ON COLUMN ptgendrh."PtPreferPronouns" IS 'Preferred Pronouns: 0-N/A; 1-He/Him; 2-She/Her; 3-They/Them; 4-Don''t Know';
COMMENT ON COLUMN ptgendrh."PtGendrH" IS 'Primary key, sequence field';
COMMENT ON COLUMN ptgendrh."PtGenderId" IS 'Gender Identity: 0-N/A; 1-male; 2-female; 4-transgender male; 8-transgender female; 16-genderqueer; can be a combination of one or more';
COMMENT ON COLUMN ptgendrh."PtGOther" IS 'Free format text to specify other gender identity';
COMMENT ON COLUMN ptgendrh."PtGDeclined" IS 'Declined to answer gender identity: 0-no; 1-yes';
COMMENT ON COLUMN ptgendrh."Patient" IS 'Primary key, Patient Id';
COMMENT ON COLUMN ptgendrh."Audit" IS 'Audit Id, audit record of the user/station that last updated this information';


CREATE  TABLE ptguahis (
  "PtGuaHis" numeric(10,0) NOT NULL,
  "RespPatient" numeric(10,0),
  "Patient" numeric(10,0),
  "IsPrimaryGuarantor" numeric(5,0),
  "IsSecondaryGuarantor" numeric(5,0),
  "IsPolicyGuarantor" numeric(5,0),
  "RespRelation" character(15),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "Inactive" numeric(5,0),
  CONSTRAINT ptguahis_primary PRIMARY KEY ("PtGuaHis")
) ;
CREATE INDEX IF NOT EXISTS ptguahis_patientkey ON ptguahis USING btree ("Patient", "RespPatient") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptguahis_respkey ON ptguahis USING btree ("RespPatient", "Patient") TABLESPACE pg_default;
COMMENT ON TABLE ptguahis IS 'Audit history for PTGUAR table';
COMMENT ON COLUMN ptguahis."RespRelation" IS 'Responsible parties relationship to the patient ';
COMMENT ON COLUMN ptguahis."RespPatient" IS 'ID code of the guarantor who is responsible for the patient, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptguahis."PtGuaHis" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN ptguahis."Patient" IS 'ID code of the patient who is under the guarantor, ptr to PATIENT.Patient ';
COMMENT ON COLUMN ptguahis."IsSecondaryGuarantor" IS 'Secondary guarantor? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptguahis."IsPrimaryGuarantor" IS 'Primary guarantor? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptguahis."IsPolicyGuarantor" IS 'Policy holder? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptguahis."Inactive" IS 'Inactive record? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptguahis."Deleted" IS 'Deleted record? (0 = No 1 = Yes)';
COMMENT ON COLUMN ptguahis."Audit" IS 'Audit record, ptr to AUDITHIS.Audit';


CREATE  TABLE ptguar (
  "RespPatient" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0) NOT NULL,
  "IsPrimaryGuarantor" numeric(5,0),
  "IsSecondaryGuarantor" numeric(5,0),
  "IsPolicyGuarantor" numeric(5,0),
  "RespRelation" character(15),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "Inactive" numeric(5,0),
  CONSTRAINT ptguar_primary PRIMARY KEY ("RespPatient", "Patient")
) ;
CREATE INDEX IF NOT EXISTS ptguar_patientkey ON ptguar USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE ptguar IS 'Patient guarantor records';
COMMENT ON COLUMN ptguar."RespRelation" IS 'Responsible parties relationship to the patient ';
COMMENT ON COLUMN ptguar."RespPatient" IS 'Primary key component, ID code of the guarantor who is responsible for the patient. Ptr to PATIENT.Patient';
COMMENT ON COLUMN ptguar."Patient" IS 'Primary key component, ID code of the patient who is under the guarantor. Ptr to PATIENT.Patient ';
COMMENT ON COLUMN ptguar."IsSecondaryGuarantor" IS 'Secondary guarantor? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptguar."IsPrimaryGuarantor" IS 'Primary guarantor? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptguar."IsPolicyGuarantor" IS 'Policy holder? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptguar."Inactive" IS 'Inactive record? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptguar."Deleted" IS 'Deleted record? (0 = No 1 = Yes)';
COMMENT ON COLUMN ptguar."Audit" IS 'Audit record, ptr to AUDITHIS.Audit';


CREATE  TABLE pthist (
  "Id" numeric(10,0) NOT NULL,
  "ItemId" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "Date" timestamp without time zone,
  "Type" numeric(5,0),
  "RecId" numeric(10,0),
  "Deleted" numeric(5,0),
  "SiteString" character(15),
  CONSTRAINT pthist_primary PRIMARY KEY ("Id", "ItemId")
) ;
COMMENT ON TABLE pthist IS 'Temporary table used for printing Patient History contents (consisting of Treatments and Clinical Notes)';
COMMENT ON COLUMN pthist."Type" IS 'Type of Record (0=Treatment, 1=Note)';
COMMENT ON COLUMN pthist."SiteString" IS 'Text containing the Site and Surface information';
COMMENT ON COLUMN pthist."RecId" IS 'Record Id of Note/Treatment';
COMMENT ON COLUMN pthist."Patient" IS 'Patient Id, ptr to PATIENT.Patient';
COMMENT ON COLUMN pthist."ItemId" IS 'Row Number on printout list';
COMMENT ON COLUMN pthist."Id" IS 'Primary Key, Internal ID (from sequence)';
COMMENT ON COLUMN pthist."Deleted" IS 'Record is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN pthist."Date" IS 'Date of Note/Treatment';


CREATE  TABLE ptimpadd (
  "PtImplnt" numeric(10,0) NOT NULL,
  "ReadableBarCode" character varying(1000),
  CONSTRAINT ptimpadd_primary PRIMARY KEY ("PtImplnt")
) ;
COMMENT ON TABLE ptimpadd IS 'Table for storing implant readable bar code';
COMMENT ON COLUMN ptimpadd."ReadableBarCode" IS 'Bar code in readable format';
COMMENT ON COLUMN ptimpadd."PtImplnt" IS 'Primary key, Id to PTIMPLNT record';


CREATE  TABLE ptimplnh (
  "PtImplnH" numeric(10,0) NOT NULL,
  "PtImplnt" numeric(10,0),
  "Patient" numeric(10,0),
  "Date" timestamp without time zone,
  "Comment" character varying(1000),
  "RawBarCode" character varying(1000),
  "DeviceId" character varying(255),
  "SerialNumber" character varying(255),
  "LotNumber" character varying(255),
  "DistinctIdCode" character varying(255),
  "ManufacturedDate" timestamp without time zone,
  "ExpiryDate" timestamp without time zone,
  "IsRemoved" numeric(5,0),
  "Deleted" numeric(5,0),
  "CreateAudit" numeric(10,0),
  "Audit" numeric(10,0),
  "Sites" character varying(255),
  "RemovedDate" timestamp without time zone,
  CONSTRAINT ptimplnh_primary PRIMARY KEY ("PtImplnH")
) ;
CREATE INDEX IF NOT EXISTS ptimplnh_ptimplntkey ON ptimplnh USING btree ("PtImplnt") TABLESPACE pg_default;
COMMENT ON TABLE ptimplnh IS 'Table for storing history of patient dental device information';
COMMENT ON COLUMN ptimplnh."Sites" IS 'Sites/Teeth # separated by coma';
COMMENT ON COLUMN ptimplnh."SerialNumber" IS 'Serial number';
COMMENT ON COLUMN ptimplnh."RemovedDate" IS 'Date when Dental Device is removed';
COMMENT ON COLUMN ptimplnh."RawBarCode" IS 'Raw bar code';
COMMENT ON COLUMN ptimplnh."PtImplnt" IS 'PtImplnt sequence Id';
COMMENT ON COLUMN ptimplnh."PtImplnH" IS 'Primary key, Unique sequence Id';
COMMENT ON COLUMN ptimplnh."Patient" IS 'Patient Id';
COMMENT ON COLUMN ptimplnh."ManufacturedDate" IS 'Manufactured date';
COMMENT ON COLUMN ptimplnh."LotNumber" IS 'Lot / Batch number';
COMMENT ON COLUMN ptimplnh."IsRemoved" IS 'Is implant removed: 0-no; 1-yes';
COMMENT ON COLUMN ptimplnh."ExpiryDate" IS 'Expiry date';
COMMENT ON COLUMN ptimplnh."DistinctIdCode" IS 'Distinct Id code (optional)';
COMMENT ON COLUMN ptimplnh."DeviceId" IS 'Device Id (Product Code)';
COMMENT ON COLUMN ptimplnh."Deleted" IS 'Deleted entry: 0-no; 1-yes';
COMMENT ON COLUMN ptimplnh."Date" IS 'Entry date of this record (default) or placement date of implant';
COMMENT ON COLUMN ptimplnh."CreateAudit" IS 'Audit Id, audit record of the user/station that first created this record';
COMMENT ON COLUMN ptimplnh."Comment" IS 'User comment / note';
COMMENT ON COLUMN ptimplnh."Audit" IS 'Audit Id, audit record of the user/station that last updated this information';


CREATE  TABLE ptimplnt (
  "PtImplnt" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "Date" timestamp without time zone,
  "Comment" character varying(1000),
  "RawBarCode" character varying(1000),
  "DeviceId" character varying(255),
  "SerialNumber" character varying(255),
  "LotNumber" character varying(255),
  "DistinctIdCode" character varying(255),
  "ManufacturedDate" timestamp without time zone,
  "ExpiryDate" timestamp without time zone,
  "IsRemoved" numeric(5,0),
  "Deleted" numeric(5,0),
  "CreateAudit" numeric(10,0),
  "Audit" numeric(10,0),
  "Sites" character varying(255),
  "RemovedDate" timestamp without time zone,
  CONSTRAINT ptimplnt_primary PRIMARY KEY ("PtImplnt")
) ;
CREATE INDEX IF NOT EXISTS ptimplnt_patientkey ON ptimplnt USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE ptimplnt IS 'Table for storing patient dental device information';
COMMENT ON COLUMN ptimplnt."Sites" IS 'Sites/Teeth # separated by coma';
COMMENT ON COLUMN ptimplnt."SerialNumber" IS 'Serial number';
COMMENT ON COLUMN ptimplnt."RemovedDate" IS 'Date when Dental Device is removed';
COMMENT ON COLUMN ptimplnt."RawBarCode" IS 'Raw bar code';
COMMENT ON COLUMN ptimplnt."PtImplnt" IS 'Primary key, Unique sequence Id';
COMMENT ON COLUMN ptimplnt."Patient" IS 'Patient Id';
COMMENT ON COLUMN ptimplnt."ManufacturedDate" IS 'Manufactured date';
COMMENT ON COLUMN ptimplnt."LotNumber" IS 'Lot / Batch number';
COMMENT ON COLUMN ptimplnt."IsRemoved" IS 'Is implant removed: 0-no; 1-yes';
COMMENT ON COLUMN ptimplnt."ExpiryDate" IS 'Expiry date';
COMMENT ON COLUMN ptimplnt."DistinctIdCode" IS 'Distinct Id code (optional)';
COMMENT ON COLUMN ptimplnt."DeviceId" IS 'Device Id (Product Code)';
COMMENT ON COLUMN ptimplnt."Deleted" IS 'Deleted entry: 0-no; 1-yes';
COMMENT ON COLUMN ptimplnt."Date" IS 'Entry date of this record (default) or placement date of implant';
COMMENT ON COLUMN ptimplnt."CreateAudit" IS 'Audit Id, audit record of the user/station that first created this record';
COMMENT ON COLUMN ptimplnt."Comment" IS 'User comment / note';
COMMENT ON COLUMN ptimplnt."Audit" IS 'Audit Id, audit record of the user/station that last updated this information';


CREATE  TABLE ptimptx (
  "PtImpTx" numeric(10,0) NOT NULL,
  "PtImplnt" numeric(10,0),
  "OrigRecNo" numeric(10,0),
  "ActionType" numeric(5,0),
  "Audit" numeric(10,0),
  "Deleted" numeric(5,0),
  "DeleteAudit" numeric(10,0),
  CONSTRAINT ptimptx_primary PRIMARY KEY ("PtImpTx")
) ;
CREATE INDEX IF NOT EXISTS ptimptx_origrecno ON ptimptx USING btree ("OrigRecNo") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptimptx_ptimplntkey ON ptimptx USING btree ("PtImplnt") TABLESPACE pg_default;
COMMENT ON TABLE ptimptx IS 'Table for storing dental device treatments';
COMMENT ON COLUMN ptimptx."PtImplnt" IS 'PtImplnt Id';
COMMENT ON COLUMN ptimptx."PtImpTx" IS 'Primary key sequence field, Id to PTIMPTX record';
COMMENT ON COLUMN ptimptx."OrigRecNo" IS 'OrigRecNo Id';
COMMENT ON COLUMN ptimptx."Deleted" IS 'Is this record deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptimptx."DeleteAudit" IS 'Foreign key to AUDIT.Id. Audit information of the user that deleted this record.';
COMMENT ON COLUMN ptimptx."Audit" IS 'Audit record of most recent change, ptr to AUDITHIS.Audit.';
COMMENT ON COLUMN ptimptx."ActionType" IS 'Type of action (0 = Add Device, 1 = Remove Device)';


CREATE  TABLE ptlcontent (
  "PtLetter" numeric(10,0) NOT NULL,
  content bytea,
  CONSTRAINT ptletter_primary PRIMARY KEY ("PtLetter")
) ;
COMMENT ON TABLE ptlcontent IS 'Holds attachments to the patient file';
COMMENT ON COLUMN ptlcontent.content IS 'Raw data that holds the formatting and data for the patient letters. Note: In Oracle 9i this field is Type: BLOB';
COMMENT ON COLUMN ptlcontent."PtLetter" IS 'Primary key, internal ID from sequence.';


CREATE  TABLE ptldetails (
  "PtLetter" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "Description" character varying(80),
  "Date" timestamp without time zone,
  "User" numeric(10,0),
  "Path" character varying(254),
  "Type" numeric(5,0),
  "Deleted" numeric(5,0),
  "StationId" numeric(10,0),
  "FileExt" character varying(32),
  "DelAudit" numeric(10,0),
  "AtTab" numeric(10,0),
  "Consent" character(6),
  "ExpiryDate" timestamp without time zone,
  "Status" numeric(5,0),
  "OrigId" numeric(10,0),
  "AuditNumber" numeric(5,0),
  "DocTempl" numeric(10,0),
  "AppUser" numeric(10,0),
  "AppDate" timestamp without time zone,
  "ModifiedDate" timestamp without time zone,
  "OwnerType" numeric(5,0),
  "OwnerId" numeric(10,0),
  "AddDateTime" timestamp without time zone,
  CONSTRAINT ptldetails_primary PRIMARY KEY ("PtLetter")
) ;
CREATE INDEX IF NOT EXISTS ptldetails_origid ON ptldetails USING btree ("OrigId", "AuditNumber") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptldetails_owner ON ptldetails USING btree ("OwnerType", "OwnerId") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptldetails_patient ON ptldetails USING btree ("Patient") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptldetails_user ON ptldetails USING btree ("User") TABLESPACE pg_default;
COMMENT ON TABLE ptldetails IS 'Holds information about attachments to the patient file';
COMMENT ON COLUMN ptldetails."User" IS 'User Id of entry user, ptr to USERS.User';
COMMENT ON COLUMN ptldetails."Type" IS 'Type of attachment (0 = Attachment stored locally - obsolete, 1 = Attachment which includes letters created before Ver 4.6, 2 = PDF obsolete as well??, 3 = Letter created in Ver 4.6 or later)';
COMMENT ON COLUMN ptldetails."Status" IS '0 - Draft; 1 - Final; 2 - Attachment';
COMMENT ON COLUMN ptldetails."StationId" IS 'Id code to identify the entry user workstation, ptr to STATION.StationId';
COMMENT ON COLUMN ptldetails."PtLetter" IS 'Primary key field';
COMMENT ON COLUMN ptldetails."Patient" IS 'Patient Id of the patient this attachment belongs to, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptldetails."Path" IS 'Pathname to the attachment storage location';
COMMENT ON COLUMN ptldetails."OwnerType" IS 'Flag to indicate if record is tied to an invoice (0=Stand alone, 1=Invoice, 2=Invoice letter [Dutch only])';
COMMENT ON COLUMN ptldetails."OwnerId" IS 'Points to PINVOICE.Pinvoice when OwnerType = 1 or OwnerType = 2 [Dutch only]';
COMMENT ON COLUMN ptldetails."OrigId" IS 'ID of the original letter, ptr to PTLETTER.PtLetter.';
COMMENT ON COLUMN ptldetails."ModifiedDate" IS 'Modified Date';
COMMENT ON COLUMN ptldetails."FileExt" IS 'File extension';
COMMENT ON COLUMN ptldetails."ExpiryDate" IS 'If a consent type, an optional consent expiry date';
COMMENT ON COLUMN ptldetails."DocTempl" IS 'The original letter template used to create this (DOCTEMPL.DocTempl)';
COMMENT ON COLUMN ptldetails."Description" IS 'Description of the attachment';
COMMENT ON COLUMN ptldetails."Deleted" IS 'Is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptldetails."DelAudit" IS 'Audit history, ptr to AUDITHIS.Audit of the deletion';
COMMENT ON COLUMN ptldetails."Date" IS 'Date the file was attached';
COMMENT ON COLUMN ptldetails."Consent" IS 'ID code of the consent record, ptr to CONSENT.Consent';
COMMENT ON COLUMN ptldetails."AuditNumber" IS 'Revision number of the letter (1,2,3..)';
COMMENT ON COLUMN ptldetails."AtTab" IS 'Ptr to ATTAB.AtTab to show attachment in';
COMMENT ON COLUMN ptldetails."AppUser" IS 'User Id of Instructor that approved the procedure, ptr to USERS.User';
COMMENT ON COLUMN ptldetails."AppDate" IS 'Date treatment was approved';
COMMENT ON COLUMN ptldetails."AddDateTime" IS 'Date/time of entry.';


CREATE  TABLE ptlinfo (
  "PtLInfo" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "PtLetter" numeric(10,0),
  "PtLType" numeric(5,0),
  "ContentDate" timestamp without time zone,
  "ContentSource" character varying(255),
  reconcilcontent clob,
  "Audit" numeric(10,0),
  CONSTRAINT ptlinfo_primary PRIMARY KEY ("PtLInfo")
) ;
CREATE INDEX IF NOT EXISTS ptlinfo_ptletterkey ON ptlinfo USING btree ("PtLetter") TABLESPACE pg_default;
COMMENT ON TABLE ptlinfo IS 'Holds patient reconciliation records';
COMMENT ON COLUMN ptlinfo.reconcilcontent IS 'Reconciled content summary (Only for PtLType = 2 [Reconciled])';
COMMENT ON COLUMN ptlinfo."PtLetter" IS 'PtLetter Id, Ptr to PTLETTER.PtLetter';
COMMENT ON COLUMN ptlinfo."PtLType" IS 'Reconciliation Type (0 = Imported, 1 = Exported, 2 = Reconciled, 3 = API Import, 4 = Auto-Reconciled, 5 = Partially Reconciled)';
COMMENT ON COLUMN ptlinfo."PtLInfo" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN ptlinfo."Patient" IS 'Patient Id of the patient this reconciliation belongs to, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptlinfo."ContentSource" IS 'Source of Content';
COMMENT ON COLUMN ptlinfo."ContentDate" IS 'Date of Content';
COMMENT ON COLUMN ptlinfo."Audit" IS 'Audit history Id, ptr to AUDITHIS.Audit.';


CREATE  TABLE ptlog (
  "Patient" numeric(10,0) NOT NULL,
  "Date" timestamp without time zone NOT NULL,
  "User" numeric(10,0) NOT NULL,
  "StationId" numeric(10,0) NOT NULL,
  "ModuleID" numeric(5,0) NOT NULL,
  CONSTRAINT ptlog_primary PRIMARY KEY ("Patient", "Date", "User", "StationId", "ModuleID")
) ;
CREATE INDEX IF NOT EXISTS ptlog_userkey ON ptlog USING btree ("User", "Date") TABLESPACE pg_default;
COMMENT ON TABLE ptlog IS 'Patient Access Log';
COMMENT ON COLUMN ptlog."User" IS 'ID code of the user that accessed the record, ptr to USERS.User';
COMMENT ON COLUMN ptlog."StationId" IS 'ID Code of the station from whcih the record was accessed, ptr to STATION.Station. ';
COMMENT ON COLUMN ptlog."Patient" IS 'ID code of the patient, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptlog."ModuleID" IS 'Module acessed (0=Pt Card, 1=Transactions, 2= TxPlan, 3=Chart, 4=Perio, 5=Ortho, 6=Patients, 7=Scheduler, 8 = EPR, 9 = Perio EPR, 10 = X-Ray, 11 = Attach Mgr, 12 = Imaging, 13 = Pt Care Mgr, 14 = EHR, 15 = Ortho Tx History, 16 = Perio Tx History, 17 = Imaging2)';
COMMENT ON COLUMN ptlog."Date" IS 'Date the record was accessed ';


CREATE  TABLE ptmanage (
  "Patient" numeric(10,0) NOT NULL,
  "User" numeric(10,0) NOT NULL,
  "IsPrimary" numeric(5,0),
  "CreateDate" timestamp without time zone,
  "AuditUser" numeric(10,0),
  "StationId" numeric(10,0),
  "Deleted" numeric(5,0),
  CONSTRAINT ptmanage_primary PRIMARY KEY ("Patient", "User")
) ;
COMMENT ON TABLE ptmanage IS 'Patient Manager Assignments';
COMMENT ON COLUMN ptmanage."User" IS 'Primary key component, manager who is assigned. Ptr to USERS.User';
COMMENT ON COLUMN ptmanage."StationId" IS 'ID code of the station, ptr to STATION.StationId.';
COMMENT ON COLUMN ptmanage."Patient" IS 'Primary key component, patient that the manager is assigned to. Ptr to PATIENT.Patient';
COMMENT ON COLUMN ptmanage."IsPrimary" IS 'Is this the primary manager for the patient? (0=No, 1=Yes)';
COMMENT ON COLUMN ptmanage."Deleted" IS 'Deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN ptmanage."CreateDate" IS 'Date the record was created';
COMMENT ON COLUMN ptmanage."AuditUser" IS 'ID of user who last edited the assignement, ptr to USERS.User';


CREATE  TABLE ptmanagh (
  "PtManageHist" numeric(10,0) NOT NULL,
  "Type" numeric(5,0),
  "Time" numeric(10,0),
  "Date" timestamp without time zone,
  "Patient" numeric(10,0),
  "User" numeric(10,0),
  "IsPrimary" numeric(5,0),
  "CreateDate" timestamp without time zone,
  "AuditUser" numeric(10,0),
  "StationId" numeric(10,0),
  "Deleted" numeric(5,0),
  CONSTRAINT ptmanagh_primary PRIMARY KEY ("PtManageHist")
) ;
CREATE INDEX IF NOT EXISTS ptmanagh_patient ON ptmanagh USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE ptmanagh IS 'Patient Manager Assignment History';
COMMENT ON COLUMN ptmanagh."User" IS 'Manager who is assigned. Ptr to USERS.User';
COMMENT ON COLUMN ptmanagh."Type" IS 'History Type (0=Add, 1=Delete, 2=Edit)';
COMMENT ON COLUMN ptmanagh."Time" IS 'Time of history record entry, in minutes from midnight.';
COMMENT ON COLUMN ptmanagh."StationId" IS 'ID code of the station, ptr to STATION.StationId.';
COMMENT ON COLUMN ptmanagh."PtManageHist" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN ptmanagh."Patient" IS 'Patient that the manager is assigned to. Ptr to PATIENT.Patient';
COMMENT ON COLUMN ptmanagh."IsPrimary" IS 'Is this the primary manager for the patient? (0=No, 1=Yes)';
COMMENT ON COLUMN ptmanagh."Deleted" IS 'Deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN ptmanagh."Date" IS 'Date of history record entry';
COMMENT ON COLUMN ptmanagh."CreateDate" IS 'Date the record was created';
COMMENT ON COLUMN ptmanagh."AuditUser" IS 'ID of user who last edited the assignement, ptr to USERS.User';


CREATE  TABLE ptneed (
  "PtNeed" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "NeedCode" character(6),
  "NeedDate" timestamp without time zone,
  "Assigned" numeric(5,0),
  "AuditId" numeric(10,0),
  "Deleted" numeric(5,0),
  "Note" character varying(100),
  "NeedSts" character(6),
  CONSTRAINT ptneed_primary PRIMARY KEY ("PtNeed")
) ;
CREATE INDEX IF NOT EXISTS ptneed_patientkey ON ptneed USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE ptneed IS 'Patient Needs';
COMMENT ON COLUMN ptneed."PtNeed" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN ptneed."Patient" IS 'ID code of the patient, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptneed."Note" IS 'Note related to the patient need';
COMMENT ON COLUMN ptneed."NeedSts" IS 'Need status, ptr to NEEDSTS.Code';
COMMENT ON COLUMN ptneed."NeedDate" IS 'Date of entry';
COMMENT ON COLUMN ptneed."NeedCode" IS 'ID code of the need, ptr to NEEDCODE.NeedCode';
COMMENT ON COLUMN ptneed."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptneed."AuditId" IS 'Audit history, ptr to AUDITHIS.Audit.';
COMMENT ON COLUMN ptneed."Assigned" IS 'Assigned? (0 = No, 1 = Yes)';


CREATE  TABLE ptneehis (
  "PtNeeHis" numeric(10,0) NOT NULL,
  "PtNeed" numeric(10,0),
  "Patient" numeric(10,0),
  "NeedCode" character(6),
  "NeedDate" timestamp without time zone,
  "Assigned" numeric(5,0),
  "AuditId" numeric(10,0),
  "Deleted" numeric(5,0),
  "Note" character varying(100),
  "NeedSts" character(6),
  CONSTRAINT ptneehis_primary PRIMARY KEY ("PtNeeHis")
) ;
CREATE INDEX IF NOT EXISTS ptneehis_patientkey ON ptneehis USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE ptneehis IS 'Patient Need History';
COMMENT ON COLUMN ptneehis."PtNeed" IS 'Patient need that this history is for, ptr to PTNEED.PtNeed';
COMMENT ON COLUMN ptneehis."PtNeeHis" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN ptneehis."Patient" IS 'ID code of the patient, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptneehis."Note" IS 'Note related to the patient need';
COMMENT ON COLUMN ptneehis."NeedSts" IS 'Need status, ptr to NEEDSTS.Code';
COMMENT ON COLUMN ptneehis."NeedDate" IS 'Date of entry';
COMMENT ON COLUMN ptneehis."NeedCode" IS 'ID code of the need, ptr to NEEDCODE.NeedCode';
COMMENT ON COLUMN ptneehis."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptneehis."AuditId" IS 'Audit history, ptr to AUDITHIS.Audit.';
COMMENT ON COLUMN ptneehis."Assigned" IS 'Assigned? (0 = No, 1 = Yes)';


CREATE  TABLE ptnote (
  "PtNote" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "Date" timestamp without time zone,
  "User" numeric(10,0),
  "EntryDate" timestamp without time zone,
  "NoteCode" character(6),
  "Text" character varying(4000),
  "Deleted" numeric(5,0),
  "IsClaimNote" numeric(5,0),
  CONSTRAINT ptnote_primary PRIMARY KEY ("PtNote")
) ;
CREATE INDEX IF NOT EXISTS ptnote_patient ON ptnote USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE ptnote IS 'Record of the notes pertaining to a patient';
COMMENT ON COLUMN ptnote."User" IS 'Id Code of the entry user, ptr to USERS.User';
COMMENT ON COLUMN ptnote."Text" IS 'Text of the note';
COMMENT ON COLUMN ptnote."PtNote" IS 'Primary key, Id of the patient note';
COMMENT ON COLUMN ptnote."Patient" IS 'ID code of the patient, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptnote."NoteCode" IS 'User definable note code, ptr to NOTECODE.NoteCode';
COMMENT ON COLUMN ptnote."IsClaimNote" IS 'Is a claim note? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptnote."EntryDate" IS 'Date the note was entered';
COMMENT ON COLUMN ptnote."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptnote."Date" IS 'Date note is for';


CREATE  TABLE ptnoteh (
  "PtNoteHistory" numeric(10,0) NOT NULL,
  "PtNote" numeric(10,0),
  "Patient" numeric(10,0),
  "Date" timestamp without time zone,
  "User" numeric(10,0),
  "EntryDate" timestamp without time zone,
  "NoteCode" character(6),
  "Text" character varying(4000),
  "Deleted" numeric(5,0),
  "IsClaimNote" numeric(5,0),
  CONSTRAINT ptnoteh_primary PRIMARY KEY ("PtNoteHistory")
) ;
CREATE INDEX IF NOT EXISTS ptnoteh_ptnote ON ptnoteh USING btree ("PtNote") TABLESPACE pg_default;
COMMENT ON TABLE ptnoteh IS 'History table for ptnote';
COMMENT ON COLUMN ptnoteh."User" IS 'ID code of the entry user, ptr to USERS.User';
COMMENT ON COLUMN ptnoteh."Text" IS 'Text of the note';
COMMENT ON COLUMN ptnoteh."PtNoteHistory" IS 'ID code to identify this history record';
COMMENT ON COLUMN ptnoteh."PtNote" IS 'Id of the patient note';
COMMENT ON COLUMN ptnoteh."Patient" IS 'ID code of the patient, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptnoteh."NoteCode" IS 'User definable note code, ptr to NOTECODE.NoteCode';
COMMENT ON COLUMN ptnoteh."IsClaimNote" IS 'History record of PTNOTE.IsClaimNote';
COMMENT ON COLUMN ptnoteh."EntryDate" IS 'Date the note was entered';
COMMENT ON COLUMN ptnoteh."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptnoteh."Date" IS 'Date the history record was created';


CREATE  TABLE ptobj (
  "PtObj" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "Description" character varying(4000),
  "Status" character(6),
  "TxPlan" numeric(10,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT ptobj_primary PRIMARY KEY ("PtObj")
) ;
CREATE INDEX IF NOT EXISTS ptobj_patient ON ptobj USING btree ("Patient") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptobj_txplan ON ptobj USING btree ("TxPlan") TABLESPACE pg_default;
COMMENT ON TABLE ptobj IS 'Patient Objectives';
COMMENT ON COLUMN ptobj."TxPlan" IS 'Treatment plan containing this objective, ptr to TXPLAN.TxPlan';
COMMENT ON COLUMN ptobj."Status" IS 'Status code of the objective, ptr to OBJSTS.Code';
COMMENT ON COLUMN ptobj."PtObj" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN ptobj."Patient" IS 'Patient that this objective is for, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptobj."Description" IS 'Description of the objective.';
COMMENT ON COLUMN ptobj."Deleted" IS 'Is this objective deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN ptobj."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE ptobjh (
  "PtObjH" numeric(10,0) NOT NULL,
  "PtObj" numeric(10,0),
  "Patient" numeric(10,0),
  "Description" character varying(4000),
  "Status" character(6),
  "TxPlan" numeric(10,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT ptobjh_primary PRIMARY KEY ("PtObjH")
) ;
CREATE INDEX IF NOT EXISTS ptobjh_ptobj ON ptobjh USING btree ("PtObj") TABLESPACE pg_default;
COMMENT ON TABLE ptobjh IS 'Patient Objective History';
COMMENT ON COLUMN ptobjh."TxPlan" IS 'Treatment plan containing this objective, ptr to TXPLAN.TxPlan';
COMMENT ON COLUMN ptobjh."Status" IS 'Status code of the objective, ptr to OBJSTS.Code';
COMMENT ON COLUMN ptobjh."PtObjH" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN ptobjh."PtObj" IS 'Patient objective that this history is for, ptr to PTOBJ.PtObj';
COMMENT ON COLUMN ptobjh."Patient" IS 'Patient that this objective is for, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptobjh."Description" IS 'Description of the objective.';
COMMENT ON COLUMN ptobjh."Deleted" IS 'Is this objective deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN ptobjh."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE ptorient (
  "Id" character(32) NOT NULL,
  "ProfileId" numeric(10,0),
  "LanguageCode" character varying(32),
  "Order" numeric(5,0),
  "Type" numeric(5,0),
  "QuestionText" character varying(1000),
  "MessageText" character varying(1000),
  "CrystalReport" character varying(4000),
  filecontent bytea,
  CONSTRAINT ptorient_pk PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE ptorient IS 'Patient orientation question w/ associated message and crystal report';
COMMENT ON COLUMN ptorient.filecontent IS 'Binary content';
COMMENT ON COLUMN ptorient."Type" IS 'Question type (0 = Unanswered,1 = Yes/No)';
COMMENT ON COLUMN ptorient."QuestionText" IS 'Question text.';
COMMENT ON COLUMN ptorient."ProfileId" IS 'Foreign key to FTKSETTING.Profile, points to the profile that the question belongs to.';
COMMENT ON COLUMN ptorient."Order" IS 'Question ordering.';
COMMENT ON COLUMN ptorient."MessageText" IS 'Message text.';
COMMENT ON COLUMN ptorient."LanguageCode" IS 'ISO-639 language code.';
COMMENT ON COLUMN ptorient."Id" IS 'Primary key, GUID-based.';
COMMENT ON COLUMN ptorient."CrystalReport" IS 'Path to Crystal Report.';


CREATE  TABLE ptovrdue (
  "Patient" numeric(10,0) NOT NULL,
  "Producer" character(10),
  "Overdue" character(6) NOT NULL,
  "DaysOverdue" numeric(10,0),
  "Date" timestamp without time zone,
  "Limit" numeric(10,0)
) ;
CREATE INDEX IF NOT EXISTS ptovrdue_patient ON ptovrdue USING btree ("Patient") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptovrdue_producer ON ptovrdue USING btree ("Producer") TABLESPACE pg_default;
COMMENT ON TABLE ptovrdue IS 'Stores the results calculated by the overnight process.';
COMMENT ON COLUMN ptovrdue."Producer" IS 'Id code of the provider assigned to the patient, ptr to PRODUCER.Producer';
COMMENT ON COLUMN ptovrdue."Patient" IS 'Id code of the patient that is overdue, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptovrdue."Overdue" IS 'Overdue reason, ptr to OVERDUE.Overdue';
COMMENT ON COLUMN ptovrdue."Limit" IS 'Exact number of days before the patient is to be considered overdue';
COMMENT ON COLUMN ptovrdue."DaysOverdue" IS 'Days overdue, value returned by the overdue function';
COMMENT ON COLUMN ptovrdue."Date" IS 'Date the record was calculated';


CREATE  TABLE ptovrext (
  "PtOvrExt" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0) NOT NULL,
  "Overdue" character(6) NOT NULL,
  "Provider" character(10),
  "Date" timestamp without time zone,
  "Extend" numeric(10,0),
  "Period" numeric(5,0),
  "ExpiryDate" timestamp without time zone,
  "ForAll" numeric(5,0),
  "Reason" character varying(30),
  CONSTRAINT ptovrext_primary PRIMARY KEY ("PtOvrExt")
) ;
CREATE INDEX IF NOT EXISTS ptovrext_patientkey ON ptovrext USING btree ("Patient", "Overdue") TABLESPACE pg_default;
COMMENT ON TABLE ptovrext IS 'Extensions for overdue patients';
COMMENT ON COLUMN ptovrext."Reason" IS 'Reason patient was granted an overdue extension (eg. on holidays) ';
COMMENT ON COLUMN ptovrext."PtOvrExt" IS 'Id code of this extension record';
COMMENT ON COLUMN ptovrext."Provider" IS 'Id code of the provider this extension is granted to, ptr to PRODUCER.Producer';
COMMENT ON COLUMN ptovrext."Period" IS 'Period (0=Calendar days, 1=Clinical days, 2=Calendar months)';
COMMENT ON COLUMN ptovrext."Patient" IS 'Id code of the patient this extesnion is granted for, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptovrext."Overdue" IS 'Id of the overdue code, ptr to OVERDUE.Overdue';
COMMENT ON COLUMN ptovrext."ForAll" IS 'Grant this extension for all overdue conditions for this patient? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN ptovrext."Extend" IS 'Number (1-9999) to indicate the # of periods to grant this extension for';
COMMENT ON COLUMN ptovrext."ExpiryDate" IS 'Expiry date of the extension';
COMMENT ON COLUMN ptovrext."Date" IS 'Date this extension was granted';


CREATE  TABLE ptperco (
  "PtPerCo" numeric(10,0) NOT NULL,
  "PtPerio" numeric(10,0) NOT NULL,
  "PerCond" character(6) NOT NULL,
  "Patient" numeric(10,0) NOT NULL,
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT ptperco_primary PRIMARY KEY ("PtPerCo")
) ;
CREATE INDEX IF NOT EXISTS ptperco_patientkey ON ptperco USING btree ("Patient", "PerCond") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptperco_ptperio ON ptperco USING btree ("PtPerio") TABLESPACE pg_default;
COMMENT ON TABLE ptperco IS 'Perio Condition Table';
COMMENT ON COLUMN ptperco."PtPerio" IS 'Perio record that the condition is for, ptr to PTPERIO.PtPerio.';
COMMENT ON COLUMN ptperco."PtPerCo" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN ptperco."PerCond" IS 'ID code of the perio condition, ptr to PERCOND.PerCond.';
COMMENT ON COLUMN ptperco."Patient" IS 'ID Code of the patient, ptr to PATIENT.Patient ';
COMMENT ON COLUMN ptperco."Deleted" IS 'Record is deleted? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN ptperco."Audit" IS 'Audit record, ptr to AUDITHIS.Audit';


CREATE  TABLE ptperhis (
  "Id" numeric(10,0) NOT NULL,
  "PtPerio" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0) NOT NULL,
  "ChartDate" timestamp without time zone,
  "AppUser" numeric(10,0),
  "AppDate" timestamp without time zone,
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "ChartByType" numeric(5,0),
  "ProdType" character(1),
  "Provider" character(10),
  "Completed" numeric(5,0),
  "PerExam" character(6),
  "OrigPtPerio" numeric(10,0),
  "DelDate" timestamp without time zone,
  "DelUser" numeric(10,0),
  CONSTRAINT ptperhis_primary PRIMARY KEY ("Id")
) ;
CREATE INDEX IF NOT EXISTS ptperhis_patient ON ptperhis USING btree ("Patient") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptperhis_ptperio ON ptperhis USING btree ("PtPerio") TABLESPACE pg_default;
COMMENT ON TABLE ptperhis IS 'Patient Perio Chart History';
COMMENT ON COLUMN ptperhis."PtPerio" IS 'Internal Id, from sequence';
COMMENT ON COLUMN ptperhis."Provider" IS 'If ChartByType = 1, Id code to identify the provider, ptr to PRODUCER.Producer';
COMMENT ON COLUMN ptperhis."ProdType" IS 'If ChartByType = 0, Producer type of the entry user, ptr to PRODTYPE.Code';
COMMENT ON COLUMN ptperhis."PerExam" IS 'Perio examination type,copy of PTPERIO.PerExam';
COMMENT ON COLUMN ptperhis."Patient" IS 'Id code of the patient to which this applies';
COMMENT ON COLUMN ptperhis."OrigPtPerio" IS 'For resumed charts, the original PTPERIO.PtPerio Id ';
COMMENT ON COLUMN ptperhis."Id" IS 'Id code to identify this history record';
COMMENT ON COLUMN ptperhis."Deleted" IS 'Deleted? (0 = No, 1 = Yes, 2=Strikeout)';
COMMENT ON COLUMN ptperhis."DelUser" IS 'User that deleted the perio';
COMMENT ON COLUMN ptperhis."DelDate" IS 'Date when the Perio was deleted';
COMMENT ON COLUMN ptperhis."Completed" IS 'Chart complete? (0 = Incomplete, 1 = Completed, 2 = Closed) ';
COMMENT ON COLUMN ptperhis."ChartDate" IS 'Date the chart was entered';
COMMENT ON COLUMN ptperhis."ChartByType" IS 'Charted by what perio method? (0 = Method for a producer type, 1 = Method for a specific provider)';
COMMENT ON COLUMN ptperhis."Audit" IS 'Audit record, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN ptperhis."AppUser" IS 'Id code of the approval user, ptr to USERS.User';
COMMENT ON COLUMN ptperhis."AppDate" IS 'Approval date of the record';


CREATE  TABLE ptperio (
  "PtPerio" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0) NOT NULL,
  "ChartDate" timestamp without time zone,
  "AppUser" numeric(10,0),
  "AppDate" timestamp without time zone,
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "ChartByType" numeric(5,0),
  "ProdType" character(1),
  "Provider" character(10),
  "Completed" numeric(5,0),
  "PerExam" character(6),
  "OrigPtPerio" numeric(10,0),
  "DelDate" timestamp without time zone,
  "DelUser" numeric(10,0),
  CONSTRAINT ptperio_primary PRIMARY KEY ("PtPerio")
) ;
CREATE INDEX IF NOT EXISTS ptperio_appuserdelkey ON ptperio USING btree ("AppUser", "Deleted") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptperio_appuserkey ON ptperio USING btree ("AppUser") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptperio_audit ON ptperio USING btree ("Audit") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptperio_patient ON ptperio USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE ptperio IS 'Patient Perio Charts';
COMMENT ON COLUMN ptperio."PtPerio" IS 'Internal Id, from sequence';
COMMENT ON COLUMN ptperio."Provider" IS 'If ChartByType = 1, Id code to identify the provider, ptr to PRODUCER.Producer';
COMMENT ON COLUMN ptperio."ProdType" IS 'If ChartByType = 0, Producer type of the entry user, ptr to PRODTYPE.Code';
COMMENT ON COLUMN ptperio."PerExam" IS 'Perio examination type, ptr to PEREXAM.PerExam';
COMMENT ON COLUMN ptperio."Patient" IS 'Id code of the patient to which this applies';
COMMENT ON COLUMN ptperio."OrigPtPerio" IS 'For resumed charts, the original PTPERIO.PtPerio Id ';
COMMENT ON COLUMN ptperio."Deleted" IS 'Deleted? (0 = No, 1 = Yes, 2=Strikeout)';
COMMENT ON COLUMN ptperio."DelUser" IS 'User that deleted the perio';
COMMENT ON COLUMN ptperio."DelDate" IS 'Date when the Perio was deleted';
COMMENT ON COLUMN ptperio."Completed" IS 'Chart complete? (0 = Incomplete, 1 = Completed, 2 = Closed) ';
COMMENT ON COLUMN ptperio."ChartDate" IS 'Date the chart was entered';
COMMENT ON COLUMN ptperio."ChartByType" IS 'Charted by what perio method? (0 = Method for a producer type, 1 = Method for a specific provider)';
COMMENT ON COLUMN ptperio."Audit" IS 'Audit record, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN ptperio."AppUser" IS 'Id code of the approval user, ptr to USERS.User';
COMMENT ON COLUMN ptperio."AppDate" IS 'Approval date of the record';


CREATE  TABLE ptperit (
  "PtPerio" numeric(10,0) NOT NULL,
  "PerCond" character(6) NOT NULL,
  "Site" numeric(5,0) NOT NULL,
  "Section" numeric(5,0) NOT NULL,
  "Value1" character(2),
  "Value2" character(2),
  "Value3" character(2),
  "DValue1" numeric,
  "DValue2" numeric,
  "DValue3" numeric,
  "Deleted" numeric(5,0),
  "SiteName" character(2),
  CONSTRAINT ptperit_primary PRIMARY KEY ("PtPerio", "PerCond", "Site", "Section")
) ;
COMMENT ON TABLE ptperit IS 'Perio values for a Patient/condition/site';
COMMENT ON COLUMN ptperit."Value3" IS 'Perio value for a patient/condition/site stored as a string';
COMMENT ON COLUMN ptperit."Value2" IS 'Perio value for a patient/condition/site stored as a string';
COMMENT ON COLUMN ptperit."Value1" IS 'Perio value for a patient/condition/site stored as a string';
COMMENT ON COLUMN ptperit."SiteName" IS 'String representation of Site (for InfoMgr reporting)';
COMMENT ON COLUMN ptperit."Site" IS 'Primary key component, site [1= tooth 1, ...32= tooth 32]';
COMMENT ON COLUMN ptperit."Section" IS 'Primary key component, section (0=Buccal or N/A if 1 value per tooth, 1=Lingual)';
COMMENT ON COLUMN ptperit."PtPerio" IS 'Primary key component, perio chart that this value is for. Ptr to PTPERIO.PtPerio.';
COMMENT ON COLUMN ptperit."PerCond" IS 'Primary key component, condition being charted. Ptr to PERCOND.PerCond.';
COMMENT ON COLUMN ptperit."Deleted" IS 'Status (0=Active, 1=Deleted, 2=Inactive) ';
COMMENT ON COLUMN ptperit."DValue3" IS 'Perio value for a patient/condition/site stored as a number with decimal place';
COMMENT ON COLUMN ptperit."DValue2" IS 'Perio value for a patient/condition/site stored as a number with decimal place';
COMMENT ON COLUMN ptperit."DValue1" IS 'Perio value for a patient/condition/site stored as a number with decimal place';


CREATE  TABLE ptperst (
  "PtPerSt" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0) NOT NULL,
  "PerProg" character(6),
  "PerType" character(6),
  "PS1Score" numeric(5,0),
  "PS1Abnormal" numeric(5,0),
  "PS2Score" numeric(5,0),
  "PS2Abnormal" numeric(5,0),
  "PS3Score" numeric(5,0),
  "PS3Abnormal" numeric(5,0),
  "PS4Score" numeric(5,0),
  "PS4Abnormal" numeric(5,0),
  "PS5Score" numeric(5,0),
  "PS5Abnormal" numeric(5,0),
  "PS6Score" numeric(5,0),
  "PS6Abnormal" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT ptperst_primary PRIMARY KEY ("PtPerSt")
) ;
CREATE INDEX IF NOT EXISTS ptperst_patient ON ptperst USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE ptperst IS 'Patient Perio Statistics ';
COMMENT ON COLUMN ptperst."PtPerSt" IS 'Primary key, internal ID from sequence';
COMMENT ON COLUMN ptperst."PerType" IS 'Perio type code, ptr to PERTYPE.PerType';
COMMENT ON COLUMN ptperst."PerProg" IS 'Perio prognosis code, ptr to PERPROG.PerProg.';
COMMENT ON COLUMN ptperst."Patient" IS 'Patient that the perio statistics are for, ptr to PATIENT.Patient. ';
COMMENT ON COLUMN ptperst."PS6Score" IS 'Sextant 6 score ';
COMMENT ON COLUMN ptperst."PS6Abnormal" IS 'Flag to indicate an abnormal score';
COMMENT ON COLUMN ptperst."PS5Score" IS 'Sextant 5 score ';
COMMENT ON COLUMN ptperst."PS5Abnormal" IS 'Flag to indicate an abnormal score';
COMMENT ON COLUMN ptperst."PS4Score" IS 'Sextant 4 score ';
COMMENT ON COLUMN ptperst."PS4Abnormal" IS 'Flag to indicate an abnormal score';
COMMENT ON COLUMN ptperst."PS3Score" IS 'Sextant 3 score ';
COMMENT ON COLUMN ptperst."PS3Abnormal" IS 'Flag to indicate an abnormal score';
COMMENT ON COLUMN ptperst."PS2Score" IS 'Sextant 2 score ';
COMMENT ON COLUMN ptperst."PS2Abnormal" IS 'Flag to indicate an abnormal score';
COMMENT ON COLUMN ptperst."PS1Score" IS 'Sextant 1 score ';
COMMENT ON COLUMN ptperst."PS1Abnormal" IS 'Flag to indicate an abnormal score';
COMMENT ON COLUMN ptperst."Audit" IS 'Audit record, ptr to AUDITHIS.Audit';


CREATE  TABLE ptphys (
  "PtPhys" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "Physician" numeric(10,0),
  "IsPrimary" numeric(5,0),
  "Comment" character varying(4000),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT ptphys_primary PRIMARY KEY ("PtPhys")
) ;
CREATE INDEX IF NOT EXISTS ptphys_patient ON ptphys USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE ptphys IS 'Patient Physicians';
COMMENT ON COLUMN ptphys."PtPhys" IS 'Primary key, internal ID from sequence';
COMMENT ON COLUMN ptphys."Physician" IS 'Physician ID, ptr to PHYSICA.Physician';
COMMENT ON COLUMN ptphys."Patient" IS 'Patient ID, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptphys."IsPrimary" IS 'Is this the primary physician? (0=No, 1=Yes)';
COMMENT ON COLUMN ptphys."Deleted" IS 'Is this record deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN ptphys."Comment" IS 'Comment about this patient-physician relationship';
COMMENT ON COLUMN ptphys."Audit" IS 'Ptr to AUDITHIS.Audit';


CREATE  TABLE ptphysh (
  "PtPhysH" numeric(10,0) NOT NULL,
  "PtPhys" numeric(10,0),
  "Patient" numeric(10,0),
  "Physician" numeric(10,0),
  "IsPrimary" numeric(5,0),
  "Comment" character varying(4000),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT ptphysh_primary PRIMARY KEY ("PtPhysH")
) ;
CREATE INDEX IF NOT EXISTS ptphysh_ptphyspatient ON ptphysh USING btree ("PtPhys", "Patient") TABLESPACE pg_default;
COMMENT ON TABLE ptphysh IS 'Patient Physician History';
COMMENT ON COLUMN ptphysh."PtPhysH" IS 'Primary key, internal ID from sequence';
COMMENT ON COLUMN ptphysh."PtPhys" IS 'Patient-physician relationship, ptr to PTPHYS.PtPhys';
COMMENT ON COLUMN ptphysh."Physician" IS 'Physician ID, ptr to PHYSICA.Physician';
COMMENT ON COLUMN ptphysh."Patient" IS 'Patient ID, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptphysh."IsPrimary" IS 'Is this the  primary physician? (0=No, 1=Yes)';
COMMENT ON COLUMN ptphysh."Deleted" IS 'Is this record deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN ptphysh."Comment" IS 'Comment about this patient-physician relationship';
COMMENT ON COLUMN ptphysh."Audit" IS 'Ptr to AUDITHIS.Audit';


CREATE  TABLE ptpol (
  "PolicyId" numeric(10,0) NOT NULL,
  "PolIns" numeric(10,0),
  "Family" numeric(10,0),
  "Patient" numeric(10,0),
  "Policy" character varying(20),
  "LimitBalance" numeric,
  "DeductBalance" numeric,
  "ResetDate" timestamp without time zone,
  "StartDate" timestamp without time zone,
  "YEResetDate" timestamp without time zone,
  "MEResetDate" timestamp without time zone,
  "Deleted" numeric(5,0),
  "Date" timestamp without time zone,
  "Time" numeric(10,0),
  "User" numeric(10,0),
  "StationId" numeric(10,0),
  "SharedEntryId" numeric(10,0),
  CONSTRAINT ptpol_primary PRIMARY KEY ("PolicyId")
) ;
CREATE INDEX IF NOT EXISTS ptpol_patient ON ptpol USING btree ("Patient") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptpol_policy ON ptpol USING btree ("Family", "Policy") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptpol_polins ON ptpol USING btree ("PolIns") TABLESPACE pg_default;
COMMENT ON TABLE ptpol IS 'Patient insurance policy ';
COMMENT ON COLUMN ptpol."YEResetDate" IS 'Year end reset date';
COMMENT ON COLUMN ptpol."User" IS 'Last user to modify record, ptr to USERS.User';
COMMENT ON COLUMN ptpol."Time" IS 'Last modified time';
COMMENT ON COLUMN ptpol."StationId" IS 'Station ID where record was last modified, ptr to STATION.StationId';
COMMENT ON COLUMN ptpol."StartDate" IS 'Date this policy begins';
COMMENT ON COLUMN ptpol."SharedEntryId" IS 'POLICY_SharedEntryId_SEQ (Internal field used to link PTPOL and POLINS auditing )';
COMMENT ON COLUMN ptpol."ResetDate" IS 'Date this policy terminates';
COMMENT ON COLUMN ptpol."PolicyId" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN ptpol."Policy" IS 'Subscriber # for this policy';
COMMENT ON COLUMN ptpol."PolIns" IS 'Benefit plan that this policy is under, ptr to POLINS.PolIns';
COMMENT ON COLUMN ptpol."Patient" IS 'Patient that holds this policy, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptpol."MEResetDate" IS 'Month end reset date';
COMMENT ON COLUMN ptpol."LimitBalance" IS 'Dollar ($) amount of limit balance';
COMMENT ON COLUMN ptpol."Family" IS 'The family that holds this policy, ptr to PATIENT.Family';
COMMENT ON COLUMN ptpol."Deleted" IS 'Is this policy deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptpol."DeductBalance" IS 'Dollar ($) amount of deductible balance';
COMMENT ON COLUMN ptpol."Date" IS 'Last modified date';


CREATE  TABLE ptpolh (
  "PtPolH" numeric(10,0) NOT NULL,
  "HistoryType" numeric(5,0),
  "PolicyId" numeric(10,0),
  "PolIns" numeric(10,0),
  "Family" numeric(10,0),
  "Patient" numeric(10,0),
  "Policy" character varying(20),
  "LimitBalance" numeric,
  "DeductBalance" numeric,
  "ResetDate" timestamp without time zone,
  "StartDate" timestamp without time zone,
  "YEResetDate" timestamp without time zone,
  "MEResetDate" timestamp without time zone,
  "Deleted" numeric(5,0),
  "Date" timestamp without time zone,
  "Time" numeric(10,0),
  "User" numeric(10,0),
  "StationId" numeric(10,0),
  "SharedEntryId" numeric(10,0),
  CONSTRAINT ptpolh_primary PRIMARY KEY ("PtPolH")
) ;
CREATE INDEX IF NOT EXISTS ptpolh_policyid ON ptpolh USING btree ("PolicyId") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptpolh_polins ON ptpolh USING btree ("PolIns") TABLESPACE pg_default;
COMMENT ON TABLE ptpolh IS 'History of changes made to PTPOL ';
COMMENT ON COLUMN ptpolh."YEResetDate" IS 'Year end reset date';
COMMENT ON COLUMN ptpolh."User" IS 'Last user to modify record, ptr to USERS.User';
COMMENT ON COLUMN ptpolh."Time" IS 'Last modified time';
COMMENT ON COLUMN ptpolh."StationId" IS 'Station ID where record was last modified, ptr to STATION.StationId';
COMMENT ON COLUMN ptpolh."StartDate" IS 'Date this policy begins';
COMMENT ON COLUMN ptpolh."SharedEntryId" IS 'POLICY_SharedEntryId_SEQ (Internal field used to link PTPOL and POLINS auditing )';
COMMENT ON COLUMN ptpolh."ResetDate" IS 'Date this policy terminates';
COMMENT ON COLUMN ptpolh."PtPolH" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN ptpolh."PolicyId" IS 'Patient policy that this history is for, ptr to PTPOL.PtPol';
COMMENT ON COLUMN ptpolh."Policy" IS 'Subscriber # for this policy';
COMMENT ON COLUMN ptpolh."PolIns" IS 'Benefit plan that this policy is under, ptr to POLINS.PolIns';
COMMENT ON COLUMN ptpolh."Patient" IS 'Patient that holds this policy, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptpolh."MEResetDate" IS 'Month end reset date';
COMMENT ON COLUMN ptpolh."LimitBalance" IS 'Dollar ($) amount of limit balance';
COMMENT ON COLUMN ptpolh."HistoryType" IS 'Type of history (1=Add, 2=Modify, 4=Delete)';
COMMENT ON COLUMN ptpolh."Family" IS 'The family that holds this policy, ptr to PATIENT.Family';
COMMENT ON COLUMN ptpolh."Deleted" IS 'Is this policy deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptpolh."DeductBalance" IS 'Dollar ($) amount of deductible balance';
COMMENT ON COLUMN ptpolh."Date" IS 'Last modified date';


CREATE  TABLE ptprb (
  "PtPrb" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "Problem" character(7),
  "Description" character varying(50),
  "ShortDesc" character varying(20),
  "Site" character(3),
  "Surface" character(6),
  "Note" character varying(4000),
  "Status" character(6),
  "AreaFound" numeric(5,0),
  "AppUser" numeric(10,0),
  "AppDateTime" timestamp without time zone,
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "Date" timestamp without time zone,
  CONSTRAINT ptprb_primary PRIMARY KEY ("PtPrb")
) ;
CREATE INDEX IF NOT EXISTS ptprb_patient ON ptprb USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE ptprb IS 'Patient Problems';
COMMENT ON COLUMN ptprb."Surface" IS 'Problem surface (optional)';
COMMENT ON COLUMN ptprb."Status" IS 'Problem status code, ptr to PROSTS.Code';
COMMENT ON COLUMN ptprb."Site" IS 'Problem site (optional)';
COMMENT ON COLUMN ptprb."ShortDesc" IS 'Short description of the problem - displayed in lists. ';
COMMENT ON COLUMN ptprb."PtPrb" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN ptprb."Problem" IS 'Problem code, ptr to PROBLEM.Problem';
COMMENT ON COLUMN ptprb."Patient" IS 'Patient that this problem is for, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptprb."Note" IS 'Problem note';
COMMENT ON COLUMN ptprb."Description" IS 'Description of the problem';
COMMENT ON COLUMN ptprb."Deleted" IS 'Is this problem deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN ptprb."Date" IS 'Problem date (set by user)';
COMMENT ON COLUMN ptprb."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN ptprb."AreaFound" IS 'Area for the problem (-1=Unknown, 0=Chart, 1=In Progress, 2=Tx History, 3=Forms, 4=Attachments, 5=Perio, 6=Imaging, 7=TxPlan, 8=Labs, 9=Rx, 10=Chart Add)';
COMMENT ON COLUMN ptprb."AppUser" IS 'User that approved this problem, ptr to USERS.User';
COMMENT ON COLUMN ptprb."AppDateTime" IS 'Date/time that this problem was approved.';


CREATE  TABLE ptprbdx (
  "PtPrb" numeric(10,0) NOT NULL,
  "TxPDx" numeric(10,0) NOT NULL,
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT ptprbdx_primary PRIMARY KEY ("TxPDx", "PtPrb")
) ;
CREATE INDEX IF NOT EXISTS ptprbdx_ptprb ON ptprbdx USING btree ("PtPrb") TABLESPACE pg_default;
COMMENT ON TABLE ptprbdx IS 'Patient Problems linked to a Treamtent Plan Diagnosis';
COMMENT ON COLUMN ptprbdx."TxPDx" IS 'Primary key component, the treatment plan diagnosis linked. Ptr to TXPDX.TxPDx';
COMMENT ON COLUMN ptprbdx."PtPrb" IS 'Primary key component, the patient problem linked. Ptr to PTPRB.PtPrb';
COMMENT ON COLUMN ptprbdx."Deleted" IS 'Is this link deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN ptprbdx."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE ptprbdxh (
  "PtPrbDxH" numeric(10,0) NOT NULL,
  "PtPrb" numeric(10,0),
  "TxPDx" numeric(10,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT ptprbdxh_primary PRIMARY KEY ("PtPrbDxH")
) ;
CREATE INDEX IF NOT EXISTS ptprbdxh_ptprbdx ON ptprbdxh USING btree ("TxPDx", "PtPrb") TABLESPACE pg_default;
COMMENT ON TABLE ptprbdxh IS 'History of Patient Problems linked to a Treamtent Plan Diagnosis';
COMMENT ON COLUMN ptprbdxh."TxPDx" IS 'The treatment plan diagnosis linked, Ptr to TXPDX.TxPDx';
COMMENT ON COLUMN ptprbdxh."PtPrbDxH" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN ptprbdxh."PtPrb" IS 'The patient problem linked, Ptr to PTPRB.PtPrb';
COMMENT ON COLUMN ptprbdxh."Deleted" IS 'Is this link deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN ptprbdxh."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE ptprbh (
  "PtPrbH" numeric(10,0) NOT NULL,
  "PtPrb" numeric(10,0),
  "Patient" numeric(10,0),
  "Problem" character(7),
  "Description" character varying(50),
  "ShortDesc" character varying(20),
  "Site" character(3),
  "Surface" character(6),
  "Note" character varying(4000),
  "Status" character(6),
  "AreaFound" numeric(5,0),
  "AppUser" numeric(10,0),
  "AppDateTime" timestamp without time zone,
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "Date" timestamp without time zone,
  CONSTRAINT ptprbh_primary PRIMARY KEY ("PtPrbH")
) ;
CREATE INDEX IF NOT EXISTS ptprbh_ptprb ON ptprbh USING btree ("PtPrb") TABLESPACE pg_default;
COMMENT ON TABLE ptprbh IS 'Patient Problem History';
COMMENT ON COLUMN ptprbh."Surface" IS 'Problem surface (optional)';
COMMENT ON COLUMN ptprbh."Status" IS 'Problem status code, ptr to PROSTS.Code';
COMMENT ON COLUMN ptprbh."Site" IS 'Problem site (optional)';
COMMENT ON COLUMN ptprbh."ShortDesc" IS 'Short description of the problem - displayed in lists. ';
COMMENT ON COLUMN ptprbh."PtPrbH" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN ptprbh."PtPrb" IS 'Patient problem that this history is for, ptr to PTPRB.PtPrb';
COMMENT ON COLUMN ptprbh."Problem" IS 'Problem code, ptr to PROBLEM.Problem';
COMMENT ON COLUMN ptprbh."Patient" IS 'Patient that this problem is for, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptprbh."Note" IS 'Problem note';
COMMENT ON COLUMN ptprbh."Description" IS 'Description of the problem';
COMMENT ON COLUMN ptprbh."Deleted" IS 'Is this problem deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN ptprbh."Date" IS 'Problem date (set by user)';
COMMENT ON COLUMN ptprbh."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN ptprbh."AreaFound" IS 'Area for the problem (-1=Unknown, 0=Chart, 1=In Progress, 2=Tx History, 3=Forms, 4=Attachments, 5=Perio, 6=Imaging, 7=TxPlan, 8=Labs, 9=Rx, 10=Chart Add)';
COMMENT ON COLUMN ptprbh."AppUser" IS 'User that approved this problem, ptr to USERS.User';
COMMENT ON COLUMN ptprbh."AppDateTime" IS 'Date/time that this problem was approved.';


CREATE  TABLE ptprev (
  "PtPrev" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "PrevCare" character(6),
  "DueDate" timestamp without time zone,
  "Completed" numeric(5,0),
  "CompletedDate" timestamp without time zone,
  "CompletedAppt" numeric(10,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "ExamState" numeric(5,0),
  CONSTRAINT ptprev_primary PRIMARY KEY ("PtPrev")
) ;
COMMENT ON TABLE ptprev IS 'Patient Preventive Care';
COMMENT ON COLUMN ptprev."PtPrev" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN ptprev."PrevCare" IS 'Preventive care type, ptr to PREVCARE.PrevCare';
COMMENT ON COLUMN ptprev."Patient" IS 'The patient receiving preventive care, ptr to PATIENT.Patient.';
COMMENT ON COLUMN ptprev."ExamState" IS 'Exam state (0 = N/A or Not Ready, 1 = Ready (for Doctor), 2 = Exam Done)';
COMMENT ON COLUMN ptprev."DueDate" IS 'Date that the preventive care is due/should be performed on.';
COMMENT ON COLUMN ptprev."Deleted" IS 'Deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN ptprev."CompletedDate" IS 'If Completed=1, then the date that it was completed.';
COMMENT ON COLUMN ptprev."CompletedAppt" IS 'If Completed=1, the appointment that it was completed on. Ptr to APPOINT.Appointment';
COMMENT ON COLUMN ptprev."Completed" IS 'Has the preventive care been completed? (0=No, 1=Yes)';
COMMENT ON COLUMN ptprev."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE ptprevh (
  "PtPrevH" numeric(10,0) NOT NULL,
  "PtPrev" numeric(10,0),
  "Patient" numeric(10,0),
  "PrevCare" character(6),
  "DueDate" timestamp without time zone,
  "Completed" numeric(5,0),
  "CompletedDate" timestamp without time zone,
  "CompletedAppt" numeric(10,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "ExamState" numeric(5,0),
  CONSTRAINT ptprevh_primary PRIMARY KEY ("PtPrevH")
) ;
COMMENT ON TABLE ptprevh IS 'Patient Preventive Care History';
COMMENT ON COLUMN ptprevh."PtPrevH" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN ptprevh."PtPrev" IS 'Preventive care record this history is for, ptr to PTPREV.PtPrev';
COMMENT ON COLUMN ptprevh."PrevCare" IS 'Preventive care type, ptr to PREVCARE.PrevCare';
COMMENT ON COLUMN ptprevh."Patient" IS 'The patient receiving preventive care, ptr to PATIENT.Patient.';
COMMENT ON COLUMN ptprevh."ExamState" IS 'Exam state (0 = N/A or Not Ready, 1 = Ready (for Doctor), 2 = Exam Done)';
COMMENT ON COLUMN ptprevh."DueDate" IS 'Date that the preventive care is due/should be performed on.';
COMMENT ON COLUMN ptprevh."Deleted" IS 'Deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN ptprevh."CompletedDate" IS 'If Completed=1, then the date that it was completed.';
COMMENT ON COLUMN ptprevh."CompletedAppt" IS 'If Completed=1, the appointment that it was completed on. Ptr to APPOINT.Appointment';
COMMENT ON COLUMN ptprevh."Completed" IS 'Has the preventive care been completed? (0=No, 1=Yes)';
COMMENT ON COLUMN ptprevh."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE ptprod (
  "Patient" numeric(10,0),
  "Producer" character(10),
  "StartDate" timestamp without time zone,
  "EndDate" timestamp without time zone,
  "IsRestricted" numeric(5,0),
  "IsPrimary" numeric(5,0),
  "Discipline" character(15),
  "NeedReq" numeric(10,0),
  "Id" numeric(10,0) NOT NULL,
  "CreateDate" timestamp without time zone,
  "User" numeric(10,0),
  "StationId" numeric(10,0),
  "Deleted" numeric(5,0),
  "Note" character varying(4000),
  CONSTRAINT ptprod_primary PRIMARY KEY ("Id")
) ;
CREATE INDEX IF NOT EXISTS ptprod_patkey ON ptprod USING btree ("Patient", "Producer") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptprod_producer ON ptprod USING btree ("Producer") TABLESPACE pg_default;
COMMENT ON TABLE ptprod IS 'Student assignments (links a patient to an assigned student provider)';
COMMENT ON COLUMN ptprod."User" IS 'User ID of entry user, ptr to USERS.User';
COMMENT ON COLUMN ptprod."StationId" IS 'ID code of the station, ptr to STATION.StationId';
COMMENT ON COLUMN ptprod."StartDate" IS 'Date the assignment becomes effective';
COMMENT ON COLUMN ptprod."Producer" IS 'Provider assigned, ptr to PRODUCER.Producer';
COMMENT ON COLUMN ptprod."Patient" IS 'Patient ID, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptprod."Note" IS 'Free text area to enter a note for this patient assignment';
COMMENT ON COLUMN ptprod."NeedReq" IS 'If assignment is based on Need Request, ptr to NEEDREQ.NeedReq';
COMMENT ON COLUMN ptprod."IsRestricted" IS 'Is a restricted assignment? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptprod."IsPrimary" IS 'Primary assigned provider? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptprod."Id" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN ptprod."EndDate" IS 'Date the assignment ends';
COMMENT ON COLUMN ptprod."Discipline" IS 'If IsRestricted=1, the discipline of the Restricted Tx. Ptr to CLASS.Class';
COMMENT ON COLUMN ptprod."Deleted" IS 'Item is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptprod."CreateDate" IS 'Creation date';


CREATE  TABLE ptprodh (
  "PtProdHistory" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "Producer" character(10),
  "Date" timestamp without time zone,
  "Action" numeric(5,0),
  "StartDate" timestamp without time zone,
  "EndDate" timestamp without time zone,
  "IsRestricted" numeric(5,0),
  "IsPrimary" numeric(5,0),
  "Discipline" character(15),
  "Time" numeric(10,0),
  "CreateDate" timestamp without time zone,
  "User" numeric(10,0),
  "StationId" numeric(10,0),
  "Id" numeric(10,0),
  "Note" character varying(4000),
  "Deleted" numeric(5,0),
  CONSTRAINT ptprodh_primary PRIMARY KEY ("PtProdHistory")
) ;
CREATE INDEX IF NOT EXISTS ptprodh_id ON ptprodh USING btree ("Id") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptprodh_ptprodkey ON ptprodh USING btree ("Patient", "Producer") TABLESPACE pg_default;
COMMENT ON TABLE ptprodh IS 'History of student assignments (past and present)';
COMMENT ON COLUMN ptprodh."User" IS 'User ID of entry user, ptr to USERS.User';
COMMENT ON COLUMN ptprodh."Time" IS 'Modified time of PTPROD record, in minutes from midnight';
COMMENT ON COLUMN ptprodh."StationId" IS 'ID code of the station, ptr to STATION.StationId';
COMMENT ON COLUMN ptprodh."StartDate" IS 'Date the assignment becomes effective';
COMMENT ON COLUMN ptprodh."PtProdHistory" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN ptprodh."Producer" IS 'Provider assigned, ptr to PRODUCER.Producer';
COMMENT ON COLUMN ptprodh."Patient" IS 'Patient ID, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptprodh."Note" IS 'Text of the note for this patient assignment, ptr to PTPROD.Note ';
COMMENT ON COLUMN ptprodh."IsRestricted" IS 'Is a restricted assignment? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptprodh."IsPrimary" IS 'Primary assigned provider? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptprodh."Id" IS 'Record ID that this history is for, ptr to PTPROD.Id';
COMMENT ON COLUMN ptprodh."EndDate" IS 'Date the assignment ends';
COMMENT ON COLUMN ptprodh."Discipline" IS 'If IsRestricted=1, the discipline of the Restricted Tx. Ptr to CLASS.Class';
COMMENT ON COLUMN ptprodh."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptprodh."Date" IS 'Modified date of PTPROD record';
COMMENT ON COLUMN ptprodh."CreateDate" IS 'Creation date';
COMMENT ON COLUMN ptprodh."Action" IS 'Action (0=Added, 1=Deleted, 2=Edited)';


CREATE  TABLE ptpsthis (
  "Id" numeric(10,0) NOT NULL,
  "PtPerSt" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0) NOT NULL,
  "PerProg" character(6),
  "PerType" character(6),
  "PS1Score" numeric(5,0),
  "PS1Abnormal" numeric(5,0),
  "PS2Score" numeric(5,0),
  "PS2Abnormal" numeric(5,0),
  "PS3Score" numeric(5,0),
  "PS3Abnormal" numeric(5,0),
  "PS4Score" numeric(5,0),
  "PS4Abnormal" numeric(5,0),
  "PS5Score" numeric(5,0),
  "PS5Abnormal" numeric(5,0),
  "PS6Score" numeric(5,0),
  "PS6Abnormal" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT ptpsthis_primary PRIMARY KEY ("Id")
) ;
CREATE INDEX IF NOT EXISTS ptpsthis_patient ON ptpsthis USING btree ("Patient") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptpsthis_ptperst ON ptpsthis USING btree ("PtPerSt") TABLESPACE pg_default;
COMMENT ON TABLE ptpsthis IS 'History table for PTPERST';
COMMENT ON COLUMN ptpsthis."PtPerSt" IS 'Points to PTPERST.PtPerSt';
COMMENT ON COLUMN ptpsthis."PerType" IS 'Points to PERTYPE (Perio Type code) ';
COMMENT ON COLUMN ptpsthis."PerProg" IS 'Points to PERPROG (Perio Prognosis code) ';
COMMENT ON COLUMN ptpsthis."Patient" IS 'Points to PATIENT.Patient';
COMMENT ON COLUMN ptpsthis."PS6Score" IS 'Sextant score ';
COMMENT ON COLUMN ptpsthis."PS6Abnormal" IS 'Flag to indicate an abnormal score';
COMMENT ON COLUMN ptpsthis."PS5Score" IS 'Sextant score ';
COMMENT ON COLUMN ptpsthis."PS5Abnormal" IS 'Flag to indicate an abnormal score';
COMMENT ON COLUMN ptpsthis."PS4Score" IS 'Sextant score ';
COMMENT ON COLUMN ptpsthis."PS4Abnormal" IS 'Flag to indicate an abnormal score';
COMMENT ON COLUMN ptpsthis."PS3Score" IS 'Sextant score ';
COMMENT ON COLUMN ptpsthis."PS3Abnormal" IS 'Flag to indicate an abnormal score';
COMMENT ON COLUMN ptpsthis."PS2Score" IS 'Sextant score ';
COMMENT ON COLUMN ptpsthis."PS2Abnormal" IS 'Flag to indicate an abnormal score';
COMMENT ON COLUMN ptpsthis."PS1Score" IS 'Sextant score ';
COMMENT ON COLUMN ptpsthis."PS1Abnormal" IS 'Flag to indicate an abnormal score';
COMMENT ON COLUMN ptpsthis."Id" IS 'Primary key, internal ID (from sequence)';
COMMENT ON COLUMN ptpsthis."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE ptrace (
  "Patient" numeric(10,0) NOT NULL,
  "Race" character(6) NOT NULL,
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT ptrace_primary PRIMARY KEY ("Patient", "Race")
) ;
COMMENT ON TABLE ptrace IS 'Patient Race';
COMMENT ON COLUMN ptrace."Race" IS 'Race code, ptr to RACE.Race';
COMMENT ON COLUMN ptrace."Patient" IS 'Race patient ID, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptrace."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptrace."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE ptraceh (
  "PtRaceH" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "Race" character(6),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT ptraceh_primary PRIMARY KEY ("PtRaceH")
) ;
COMMENT ON TABLE ptraceh IS 'Patient Race History';
COMMENT ON COLUMN ptraceh."Race" IS 'Race code, copy of PTRACE.Race';
COMMENT ON COLUMN ptraceh."PtRaceH" IS 'Primary key, Internal Id (from sequence)';
COMMENT ON COLUMN ptraceh."Patient" IS 'Race patient ID, Copy of PTRACE.Patient';
COMMENT ON COLUMN ptraceh."Deleted" IS 'Deleted? (0 = No, 1 = Yes), copy of PTRACE.Deleted';
COMMENT ON COLUMN ptraceh."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE ptrcgrih (
  "PtRcGrIH" numeric(10,0) NOT NULL,
  "PtRcGrp" numeric(10,0),
  "PtRecall" numeric(10,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT ptrcgrih_primary PRIMARY KEY ("PtRcGrIH")
) ;
CREATE INDEX IF NOT EXISTS ptrcgrih_ptrcgrpkey ON ptrcgrih USING btree ("PtRcGrp", "PtRecall") TABLESPACE pg_default;
COMMENT ON TABLE ptrcgrih IS 'Patient recall group item history';
COMMENT ON COLUMN ptrcgrih."PtRecall" IS 'Patient recall this item is tied to, ptr to PTRECALL.Id';
COMMENT ON COLUMN ptrcgrih."PtRcGrp" IS 'Patient recall group that this history is for, ptr to PTRCGRP.PtRcGrp';
COMMENT ON COLUMN ptrcgrih."PtRcGrIH" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN ptrcgrih."Deleted" IS 'Is this record deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN ptrcgrih."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE ptrcgrp (
  "PtRcGrp" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "RcGroup" numeric(10,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT ptrcgrp_primary PRIMARY KEY ("PtRcGrp")
) ;
COMMENT ON TABLE ptrcgrp IS 'Patient recall group';
COMMENT ON COLUMN ptrcgrp."RcGroup" IS 'Recall group this patient belongs to, ptr to RCGROUP.RcGroup';
COMMENT ON COLUMN ptrcgrp."PtRcGrp" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN ptrcgrp."Patient" IS 'Patient that this recall group is for, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptrcgrp."Deleted" IS 'Is this record deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN ptrcgrp."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE ptrcgrph (
  "PtRcGrpH" numeric(10,0) NOT NULL,
  "PtRcGrp" numeric(10,0),
  "Patient" numeric(10,0),
  "RcGroup" numeric(10,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT ptrcgrph_primary PRIMARY KEY ("PtRcGrpH")
) ;
CREATE INDEX IF NOT EXISTS ptrcgrph_ptrcgrpkey ON ptrcgrph USING btree ("PtRcGrp", "Patient") TABLESPACE pg_default;
COMMENT ON TABLE ptrcgrph IS 'Patient recall group history';
COMMENT ON COLUMN ptrcgrph."RcGroup" IS 'Recall group this patient belongs to, ptr to RCGROUP.RcGroup';
COMMENT ON COLUMN ptrcgrph."PtRcGrpH" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN ptrcgrph."PtRcGrp" IS 'Patient recall group that this history is for, ptr to PTRCGRP.PtRcGrp';
COMMENT ON COLUMN ptrcgrph."Patient" IS 'Patient that this recall group is for, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptrcgrph."Deleted" IS 'Is this record deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN ptrcgrph."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE ptrcgrpi (
  "PtRcGrp" numeric(10,0) NOT NULL,
  "PtRecall" numeric(10,0) NOT NULL,
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT ptrcgrpi_primary PRIMARY KEY ("PtRcGrp", "PtRecall")
) ;
COMMENT ON TABLE ptrcgrpi IS 'Patient recall group item';
COMMENT ON COLUMN ptrcgrpi."PtRecall" IS 'Primary Key, patient recall this item is tied to, ptr to PTRECALL.Id';
COMMENT ON COLUMN ptrcgrpi."PtRcGrp" IS 'Primary Key, patient recall group that this history is for, ptr to PTRCGRP.PtRcGrp';
COMMENT ON COLUMN ptrcgrpi."Deleted" IS 'Is this record deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN ptrcgrpi."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE ptrecall (
  "Id" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0) NOT NULL,
  "Recall" character(6),
  "RecallDate" timestamp without time zone,
  "Provider" character(10),
  "Status" character(6),
  "Comment" character(50),
  "Units" numeric(10,0),
  "ApptDate" timestamp without time zone,
  "Booked" numeric(5,0),
  "User" numeric(10,0),
  "CreationDate" timestamp without time zone,
  "RecallType" character(6),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "Treatme2Id" numeric(10,0),
  "Clinic" numeric(10,0),
  "ApptCode" character(15),
  "IsDefault" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT ptrecall_primary PRIMARY KEY ("Id")
) ;
CREATE INDEX IF NOT EXISTS ptrecall_patient ON ptrecall USING btree ("Patient") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptrecall_recalldate ON ptrecall USING btree ("RecallDate") TABLESPACE pg_default;
COMMENT ON TABLE ptrecall IS 'Patient recalls';
COMMENT ON COLUMN ptrecall."User" IS 'User ID of entry user. Ptr to USERS.User';
COMMENT ON COLUMN ptrecall."Units" IS 'Number of units required for recall appointment';
COMMENT ON COLUMN ptrecall."Treatme2Id" IS 'Id code of the Treatme2 record that triggered a recall';
COMMENT ON COLUMN ptrecall."Status" IS 'Quality / value of the patient, ptr to STATUS.Status';
COMMENT ON COLUMN ptrecall."RecallType" IS 'Type of recall. ptr to RCTYPE.RecallType';
COMMENT ON COLUMN ptrecall."RecallDate" IS 'Date for recall to occur';
COMMENT ON COLUMN ptrecall."Recall" IS 'Recall code, ptr to RECALL.Recall';
COMMENT ON COLUMN ptrecall."Provider" IS 'Provider ID, ptr to PRODUCER.Producer';
COMMENT ON COLUMN ptrecall."Patient" IS 'Recall patient ID, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptrecall."IsDefault" IS 'Is this recall a default recall added during re-activation? (0 = No,1 = Yes)';
COMMENT ON COLUMN ptrecall."Id" IS 'Primary key, Internal Id (from sequence)';
COMMENT ON COLUMN ptrecall."Deleted" IS 'Recall is deleted? (0 = No,1 = Yes)';
COMMENT ON COLUMN ptrecall."CreationDate" IS 'Date of creation';
COMMENT ON COLUMN ptrecall."Comment" IS 'Free text area to enter comments about the recall';
COMMENT ON COLUMN ptrecall."Clinic" IS 'Id code of the clinic requested for the recall appointment';
COMMENT ON COLUMN ptrecall."Booked" IS 'Booked for recall? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptrecall."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN ptrecall."ApptDate" IS 'Appt date for recall, if appt booked';
COMMENT ON COLUMN ptrecall."ApptCode" IS 'Appt Code planned for this recall';


CREATE  TABLE ptrechis (
  "PtRecHis" numeric(10,0) NOT NULL,
  "Id" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0) NOT NULL,
  "Recall" character(6),
  "RecallDate" timestamp without time zone,
  "Provider" character(10),
  "Status" character(6),
  "Comment" character(50),
  "Units" numeric(10,0),
  "ApptDate" timestamp without time zone,
  "Booked" numeric(5,0),
  "User" numeric(10,0),
  "CreationDate" timestamp without time zone,
  "RecallType" character(6),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "Treatme2Id" numeric(10,0),
  "Clinic" numeric(10,0),
  "ApptCode" character(15),
  "IsDefault" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT ptrechis_primary PRIMARY KEY ("PtRecHis")
) ;
CREATE INDEX IF NOT EXISTS ptrechis_id ON ptrechis USING btree ("Id") TABLESPACE pg_default;
COMMENT ON TABLE ptrechis IS 'History record for the PTRECALL table';
COMMENT ON COLUMN ptrechis."User" IS 'User ID of entry user. Ptr to USERS.User';
COMMENT ON COLUMN ptrechis."Units" IS 'Number of units required for recall appointment, copy of PTRECALL.Units';
COMMENT ON COLUMN ptrechis."Treatme2Id" IS 'Id code of the Treatme2 record that triggered a recall';
COMMENT ON COLUMN ptrechis."Status" IS 'Quality / value of the patient, copy of PTRECALL.Status';
COMMENT ON COLUMN ptrechis."RecallType" IS 'Type of recall. copy of PTRECALL.RecallType';
COMMENT ON COLUMN ptrechis."RecallDate" IS 'Date for recall to occur, copy of PTRECALL.RecallDate';
COMMENT ON COLUMN ptrechis."Recall" IS 'Recall code, copy of PTRECALL..Recall';
COMMENT ON COLUMN ptrechis."PtRecHis" IS 'ID code to identify this hsitory record, Internal ID from sequence.';
COMMENT ON COLUMN ptrechis."Provider" IS 'Provider ID, copy of PTRECALL.Producer';
COMMENT ON COLUMN ptrechis."Patient" IS 'Recall patient ID, copy of PTRECALL.Patient';
COMMENT ON COLUMN ptrechis."IsDefault" IS 'Is this recall a default recall added during re-activation? (0 = No,1 = Yes)';
COMMENT ON COLUMN ptrechis."Id" IS 'Id code of the ptrecall, copy of PTRECALL.Id';
COMMENT ON COLUMN ptrechis."Deleted" IS 'Recall is deleted? copy of PTRECALL.Deleted';
COMMENT ON COLUMN ptrechis."CreationDate" IS 'Date of creation, copy of PTRECALL.CreationDate';
COMMENT ON COLUMN ptrechis."Comment" IS 'Comments about the recall,copy of PTRECALL.Comment';
COMMENT ON COLUMN ptrechis."Clinic" IS 'Id code of the clinic the recall is requested for';
COMMENT ON COLUMN ptrechis."Booked" IS 'Booked for recall? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptrechis."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN ptrechis."ApptDate" IS 'Appt date for recall, if appt booked';
COMMENT ON COLUMN ptrechis."ApptCode" IS 'Appt Code planned for this recall';


CREATE  TABLE ptrefer (
  "PtRefer" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "Date" timestamp without time zone,
  "Referral" numeric(10,0),
  "IsPrimary" numeric(5,0),
  "FromToFlag" numeric(5,0),
  "Note" character varying(255),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "EndDate" timestamp without time zone,
  CONSTRAINT ptrefer_primary PRIMARY KEY ("PtRefer")
) ;
CREATE INDEX IF NOT EXISTS ptrefer_patient ON ptrefer USING btree ("Patient", "FromToFlag") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptrefer_referral ON ptrefer USING btree ("Referral") TABLESPACE pg_default;
COMMENT ON TABLE ptrefer IS 'Patient Referrals';
COMMENT ON COLUMN ptrefer."Referral" IS 'Doctor/source of the referral, ptr to REFERRAL.Referral';
COMMENT ON COLUMN ptrefer."PtRefer" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN ptrefer."Patient" IS 'Patient who was referred, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptrefer."Note" IS 'Free text area to enter referral notes';
COMMENT ON COLUMN ptrefer."IsPrimary" IS 'Is primary? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptrefer."FromToFlag" IS 'Was referred from or to? (0=From, 1=To, 2=Both)';
COMMENT ON COLUMN ptrefer."EndDate" IS 'End date for the referral';
COMMENT ON COLUMN ptrefer."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptrefer."Date" IS 'Date of the referral';
COMMENT ON COLUMN ptrefer."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE ptrefhis (
  "PtRefHis" numeric(10,0) NOT NULL,
  "PtRefer" numeric(10,0),
  "Patient" numeric(10,0),
  "Date" timestamp without time zone,
  "Referral" numeric(10,0),
  "IsPrimary" numeric(5,0),
  "FromToFlag" numeric(5,0),
  "Note" character varying(255),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "EndDate" timestamp without time zone,
  CONSTRAINT ptrefhis_primary PRIMARY KEY ("PtRefHis")
) ;
CREATE INDEX IF NOT EXISTS ptrefhis_ptrefer ON ptrefhis USING btree ("PtRefer") TABLESPACE pg_default;
COMMENT ON TABLE ptrefhis IS 'Patient Referral History';
COMMENT ON COLUMN ptrefhis."Referral" IS 'Doctor/source of the referral, ptr to REFERRAL.Referral';
COMMENT ON COLUMN ptrefhis."PtRefer" IS 'Patient referral that this history is for, ptr to PTREFER.PtRefer';
COMMENT ON COLUMN ptrefhis."PtRefHis" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN ptrefhis."Patient" IS 'Patient who was referred, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptrefhis."Note" IS 'Free text area to enter referral notes';
COMMENT ON COLUMN ptrefhis."IsPrimary" IS 'Is primary? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptrefhis."FromToFlag" IS 'Was referred from or to? (0=From, 1=To, 2=Both)';
COMMENT ON COLUMN ptrefhis."EndDate" IS 'End date for the referral';
COMMENT ON COLUMN ptrefhis."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptrefhis."Date" IS 'Date of the referral';
COMMENT ON COLUMN ptrefhis."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE ptsdose (
  "PtSDose" numeric(10,0) NOT NULL,
  "PtSDrug" numeric(10,0),
  "EntryTime" timestamp without time zone,
  "Amount" numeric(10,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT ptsdose_primary PRIMARY KEY ("PtSDose")
) ;
COMMENT ON TABLE ptsdose IS 'Patient drug amounts dispensed during surgery.';
COMMENT ON COLUMN ptsdose."PtSDrug" IS 'Ptr to PTSDRUG table to identify the appointment, drug, unit, delivery, etc for this dispensed amount';
COMMENT ON COLUMN ptsdose."PtSDose" IS 'Primary key, unique code to identify the drug amounts dispensed during surgery';
COMMENT ON COLUMN ptsdose."EntryTime" IS 'The date and time that the drug was administered (accurate to the nearest minute)';
COMMENT ON COLUMN ptsdose."Deleted" IS 'Is this record deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptsdose."Audit" IS 'Audit record for this dose, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN ptsdose."Amount" IS 'The amount of anesthetics dispensed (in the unit identified in PtSDrug)';


CREATE  TABLE ptsdoseh (
  "PtSDoseH" numeric(10,0) NOT NULL,
  "PtSDose" numeric(10,0),
  "PtSDrug" numeric(10,0),
  "EntryTime" timestamp without time zone,
  "Amount" numeric(10,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT ptsdoseh_primary PRIMARY KEY ("PtSDoseH")
) ;
COMMENT ON TABLE ptsdoseh IS 'History of Patient Surgery doses.';
COMMENT ON COLUMN ptsdoseh."PtSDrug" IS 'Ptr to PTSDRUG table to identify the appointment, drug, unit, delivery, etc for this dispensed amount';
COMMENT ON COLUMN ptsdoseh."PtSDoseH" IS 'Primary key, unique code to identify history of surgery doses.';
COMMENT ON COLUMN ptsdoseh."PtSDose" IS 'Ptr to PTSDOSE to identify the drug amounts dispensed during surgery';
COMMENT ON COLUMN ptsdoseh."EntryTime" IS 'The date and time that the drug was administered (accurate to the nearest minute)';
COMMENT ON COLUMN ptsdoseh."Deleted" IS 'Is this record deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptsdoseh."Audit" IS 'Audit record for this dose, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN ptsdoseh."Amount" IS 'The amount of anesthetics dispensed (in the unit identified in PtSDrug)';


CREATE  TABLE ptsdrug (
  "PtSDrug" numeric(10,0) NOT NULL,
  "Appointment" numeric(10,0),
  "Drug" character(10),
  "AnesUnit" numeric(10,0),
  "AnesDelv" numeric(10,0),
  "AnesGaug" numeric(10,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "Order" numeric(5,0),
  "OtherDrug" numeric(10,0),
  "Waste" numeric(5,0),
  "WasteAmount" numeric(10,0),
  "WasteDeleted" numeric(5,0),
  "WasteAudit" numeric(10,0),
  "SDrugHType" numeric(5,0),
  "IsContinued" numeric(5,0),
  "ShortName" character varying(15),
  CONSTRAINT ptsdrug_primary PRIMARY KEY ("PtSDrug")
) ;
CREATE INDEX IF NOT EXISTS ptsdrug_apptkey ON ptsdrug USING btree ("Appointment") TABLESPACE pg_default;
COMMENT ON TABLE ptsdrug IS 'Patient Surgery drugs.';
COMMENT ON COLUMN ptsdrug."WasteDeleted" IS 'Is this waste amount deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptsdrug."WasteAudit" IS 'Audit record for waste, ptr to AUDITHIS.Audit.';
COMMENT ON COLUMN ptsdrug."WasteAmount" IS 'Amount of waste for this Drug';
COMMENT ON COLUMN ptsdrug."Waste" IS 'Is entry allowed and approval required for this Drug (0=No, 1=Yes, 2=Yes with approval)';
COMMENT ON COLUMN ptsdrug."ShortName" IS 'Short name of the drug';
COMMENT ON COLUMN ptsdrug."SDrugHType" IS 'For an audit, the type of change (0 = Drug change, 1 = Waste change)';
COMMENT ON COLUMN ptsdrug."PtSDrug" IS 'Primary key, unique code to identify the surgery drug';
COMMENT ON COLUMN ptsdrug."OtherDrug" IS 'Other drug points to main drug. Pointer to PTSDRUG.PtSDrug';
COMMENT ON COLUMN ptsdrug."Order" IS 'Order of the Surgery Drug to appear on O/S Anesthetics Display';
COMMENT ON COLUMN ptsdrug."IsContinued" IS '0/1 - Is a continued flow (graphed as a line)';
COMMENT ON COLUMN ptsdrug."Drug" IS 'Pointer to DRUG.Drug';
COMMENT ON COLUMN ptsdrug."Deleted" IS 'Is this drug deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptsdrug."Audit" IS 'Audit record for this Surgery Drug, ptr to AUDITHIS.Audit.';
COMMENT ON COLUMN ptsdrug."Appointment" IS 'Pointer to APPOINT.Appointment.';
COMMENT ON COLUMN ptsdrug."AnesUnit" IS 'Pointer to ANESUNIT.AnesUnit';
COMMENT ON COLUMN ptsdrug."AnesGaug" IS 'Pointer to ANESGAUG.AnesGaug';
COMMENT ON COLUMN ptsdrug."AnesDelv" IS 'Pointer to ANESDELV.AnesDelv';


CREATE  TABLE ptsdrugh (
  "PtSDrugH" numeric(10,0) NOT NULL,
  "PtSDrug" numeric(10,0),
  "Appointment" numeric(10,0),
  "Drug" character(10),
  "AnesUnit" numeric(10,0),
  "AnesDelv" numeric(10,0),
  "AnesGaug" numeric(10,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "Order" numeric(5,0),
  "OtherDrug" numeric(10,0),
  "Waste" numeric(5,0),
  "WasteAmount" numeric(10,0),
  "WasteDeleted" numeric(5,0),
  "WasteAudit" numeric(10,0),
  "SDrugHType" numeric(5,0),
  "IsContinued" numeric(5,0),
  "ShortName" character varying(15),
  CONSTRAINT ptsdrugh_primary PRIMARY KEY ("PtSDrugH")
) ;
CREATE INDEX IF NOT EXISTS ptsdrugh_apptkey ON ptsdrugh USING btree ("Appointment") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptsdrugh_ptsdrugkey ON ptsdrugh USING btree ("PtSDrug") TABLESPACE pg_default;
COMMENT ON TABLE ptsdrugh IS 'History of Patient Surgery drugs.';
COMMENT ON COLUMN ptsdrugh."WasteDeleted" IS 'Is this waste amount deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptsdrugh."WasteAudit" IS 'Audit record for waste, ptr to AUDITHIS.Audit.';
COMMENT ON COLUMN ptsdrugh."WasteAmount" IS 'Amount of waste for this Drug';
COMMENT ON COLUMN ptsdrugh."Waste" IS 'Is entry allowed and approval required for this Drug (0=No, 1=Yes, 2=Yes with approval)';
COMMENT ON COLUMN ptsdrugh."ShortName" IS 'Short name of the drug';
COMMENT ON COLUMN ptsdrugh."SDrugHType" IS 'For an audit, the type of change (0 = Drug change, 1 = Waste change)';
COMMENT ON COLUMN ptsdrugh."PtSDrugH" IS 'Primary key, unique code to identify history of surgery drug.';
COMMENT ON COLUMN ptsdrugh."PtSDrug" IS 'History record for specific drug, ptr to PTSDRUG.PtSDrug';
COMMENT ON COLUMN ptsdrugh."OtherDrug" IS 'Main drug in a mixture has this pointer to other drug PTSDRUGH.PtSDrug';
COMMENT ON COLUMN ptsdrugh."Order" IS 'Order of the Surgery Drug to appear on O/S Anesthetics Display';
COMMENT ON COLUMN ptsdrugh."IsContinued" IS '0/1 - Is a continued flow (graphed as a line)';
COMMENT ON COLUMN ptsdrugh."Drug" IS 'Pointer to DRUG.Drug';
COMMENT ON COLUMN ptsdrugh."Deleted" IS 'Is this drug deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptsdrugh."Audit" IS 'Audit record for this Surgery Drug, ptr to AUDITHIS.Audit.';
COMMENT ON COLUMN ptsdrugh."Appointment" IS 'Pointer to APPOINT.Appointment.';
COMMENT ON COLUMN ptsdrugh."AnesUnit" IS 'Pointer to ANESUNIT.AnesUnit';
COMMENT ON COLUMN ptsdrugh."AnesGaug" IS 'Pointer to ANESGAUG.AnesGaug';
COMMENT ON COLUMN ptsdrugh."AnesDelv" IS 'Pointer to ANESDELV.AnesDelv';


CREATE  TABLE ptsig (
  "PtSig" numeric(10,0) NOT NULL,
  signature bytea,
  "Denied" numeric(5,0),
  CONSTRAINT ptsig_primary PRIMARY KEY ("PtSig")
) ;
COMMENT ON TABLE ptsig IS 'Patient signature records';
COMMENT ON COLUMN ptsig.signature IS 'BLOB data, patient signature.';
COMMENT ON COLUMN ptsig."PtSig" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN ptsig."Denied" IS 'Is this signature denied? (0 = Consent is accepted and signed, 1 = Consent is denied and signed)';


CREATE  TABLE ptsig_deleted (
  "PtSig" numeric(10,0),
  signature bytea,
  "Denied" numeric(5,0)
) ;
COMMENT ON TABLE ptsig_deleted IS 'Deleted Patient signature records';
COMMENT ON COLUMN ptsig_deleted.signature IS 'BLOB data, patient signature.';
COMMENT ON COLUMN ptsig_deleted."PtSig" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN ptsig_deleted."Denied" IS 'Is this signature denied? (0 = Consent is accepted and signed, 1 = Consent is denied and signed)';


CREATE  TABLE ptstage (
  "PtStage" numeric(10,0) NOT NULL,
  "Appointment" numeric(10,0),
  "StageSet" numeric(10,0),
  "StageCode" character(1),
  "StageStart" timestamp without time zone,
  "Audit" numeric(10,0),
  CONSTRAINT ptstage_primary PRIMARY KEY ("PtStage")
) ;
CREATE INDEX IF NOT EXISTS ptstage_apptkey ON ptstage USING btree ("Appointment") TABLESPACE pg_default;
COMMENT ON TABLE ptstage IS 'Patient Surgery stages.';
COMMENT ON COLUMN ptstage."StageStart" IS 'Start date and time for the stage.';
COMMENT ON COLUMN ptstage."StageSet" IS 'Stage Set, ptr to OSSTAGE.Set';
COMMENT ON COLUMN ptstage."StageCode" IS 'Stage code, ptr to OSSTAGE.Code. If empty - End of Surgery';
COMMENT ON COLUMN ptstage."PtStage" IS 'Primary key, unique code of stage for specific surgery.';
COMMENT ON COLUMN ptstage."Audit" IS 'Audit record for this Stage entry, ptr to AUDITHIS.Audit.';
COMMENT ON COLUMN ptstage."Appointment" IS 'Appointment, ptr to APPOINT.Appointment.';


CREATE  TABLE ptstageh (
  "PtStageH" numeric(10,0) NOT NULL,
  "PtStage" numeric(10,0),
  "Appointment" numeric(10,0),
  "StageSet" numeric(10,0),
  "StageCode" character(1),
  "StageStart" timestamp without time zone,
  "Audit" numeric(10,0),
  CONSTRAINT ptstageh_primary PRIMARY KEY ("PtStageH")
) ;
CREATE INDEX IF NOT EXISTS ptstageh_apptkey ON ptstageh USING btree ("Appointment") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptstageh_ptstagekey ON ptstageh USING btree ("PtStage") TABLESPACE pg_default;
COMMENT ON TABLE ptstageh IS 'History of Patient Surgery stages.';
COMMENT ON COLUMN ptstageh."StageStart" IS 'Start date and time for the stage.';
COMMENT ON COLUMN ptstageh."StageSet" IS 'Stage Set, ptr to OSSTAGE.Set';
COMMENT ON COLUMN ptstageh."StageCode" IS 'Stage code, ptr to OSSTAGE.Code. If empty - End of Surgery';
COMMENT ON COLUMN ptstageh."PtStageH" IS 'Primary key, unique code to identify history of surgery stage.';
COMMENT ON COLUMN ptstageh."PtStage" IS 'History record for specific Stage, ptr to PTSTAGE.PtStage';
COMMENT ON COLUMN ptstageh."Audit" IS 'Audit record for this Stage entry, ptr to AUDITHIS.Audit.';
COMMENT ON COLUMN ptstageh."Appointment" IS 'Appointment, ptr to APPOINT.Appointment.';


CREATE  TABLE ptsumm (
  "Patient" numeric(10,0) NOT NULL,
  "SummCode" character(6) NOT NULL,
  "Value1" character varying(30),
  "Value2" character varying(30),
  "Audit" numeric(10,0),
  "Value1Override" character varying(30),
  "Value2Override" character varying(30),
  "OverrideNote" character varying(4000),
  "OverrideAudit" numeric(10,0),
  CONSTRAINT ptsumm_primary PRIMARY KEY ("Patient", "SummCode")
) ;
CREATE INDEX IF NOT EXISTS ptsumm_patientkey ON ptsumm USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE ptsumm IS 'Patient Summary Values ';
COMMENT ON COLUMN ptsumm."Value2Override" IS 'user override of Value2';
COMMENT ON COLUMN ptsumm."Value2" IS 'e.g. Low, Moderate, High ';
COMMENT ON COLUMN ptsumm."Value1Override" IS 'user override of Value1';
COMMENT ON COLUMN ptsumm."Value1" IS 'e.g. C0..C3 for Caries, P1..P4 for Perio';
COMMENT ON COLUMN ptsumm."SummCode" IS 'Ptr to SUMMCODE.SummCode';
COMMENT ON COLUMN ptsumm."Patient" IS 'Ptr to PATIENT.Patient';
COMMENT ON COLUMN ptsumm."OverrideNote" IS 'user note explaining override';
COMMENT ON COLUMN ptsumm."OverrideAudit" IS 'points to AUDITHIS.Audit';
COMMENT ON COLUMN ptsumm."Audit" IS 'points to AUDITHIS.Audit';


CREATE  TABLE ptsummh (
  "PtSummH" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "SummCode" character(6),
  "Value1" character varying(30),
  "Value2" character varying(30),
  "Audit" numeric(10,0),
  "Value1Override" character varying(30),
  "Value2Override" character varying(30),
  "OverrideNote" character varying(4000),
  "OverrideAudit" numeric(10,0),
  CONSTRAINT ptsummh_primary PRIMARY KEY ("PtSummH")
) ;
CREATE INDEX IF NOT EXISTS ptsummh_patientkey ON ptsummh USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE ptsummh IS 'Patient Summary History ';
COMMENT ON COLUMN ptsummh."Value2Override" IS 'user override of Value2';
COMMENT ON COLUMN ptsummh."Value2" IS 'e.g. Low, Moderate, High ';
COMMENT ON COLUMN ptsummh."Value1Override" IS 'user override of Value1';
COMMENT ON COLUMN ptsummh."Value1" IS 'e.g. C0..C3 for Caries, P1..P4 for Perio';
COMMENT ON COLUMN ptsummh."SummCode" IS 'Ptr to SUMMCODE.SummCode';
COMMENT ON COLUMN ptsummh."PtSummH" IS 'Primary key (from sequence)';
COMMENT ON COLUMN ptsummh."Patient" IS 'Ptr to PATIENT.Patient';
COMMENT ON COLUMN ptsummh."OverrideNote" IS 'user note explaining override';
COMMENT ON COLUMN ptsummh."OverrideAudit" IS 'points to AUDITHIS.Audit';
COMMENT ON COLUMN ptsummh."Audit" IS 'points to AUDITHIS.Audit';


CREATE  TABLE ptsurg (
  "PtSurg" numeric(10,0) NOT NULL,
  "Appointment" numeric(10,0),
  "HeightType" numeric(5,0),
  "Height" numeric(10,0),
  "HeightADate" timestamp without time zone,
  "HeightAUser" numeric(10,0),
  "Height2" numeric(10,0),
  "Height2ADate" timestamp without time zone,
  "Height2AUser" numeric(10,0),
  "WeightType" numeric(5,0),
  "Weight" numeric(10,0),
  "WeightADate" timestamp without time zone,
  "WeightAUser" numeric(10,0),
  "BMI" numeric,
  "Audit" numeric(10,0),
  "ApprovalUser" numeric(10,0),
  "ApprovalDate" timestamp without time zone,
  "WasteApprovalUser" numeric(10,0),
  "WasteApprovalDate" timestamp without time zone,
  "IsPediatric" numeric(5,0),
  CONSTRAINT ptsurg_primary PRIMARY KEY ("PtSurg")
) ;
CREATE INDEX IF NOT EXISTS ptsurg_apptkey ON ptsurg USING btree ("Appointment") TABLESPACE pg_default;
COMMENT ON TABLE ptsurg IS 'Patient Surgery table for Surgery.';
COMMENT ON COLUMN ptsurg."WeightType" IS 'Weight Type (0=kg;1=lb). For now we use kg only';
COMMENT ON COLUMN ptsurg."WeightAUser" IS 'Weight audit user (from Form audit record)';
COMMENT ON COLUMN ptsurg."WeightADate" IS 'Weight audit date and time (from Form audit record).';
COMMENT ON COLUMN ptsurg."Weight" IS 'Weight in kg or lb, depending on WeightType';
COMMENT ON COLUMN ptsurg."WasteApprovalUser" IS 'Id code of waste approval user, ptr to USERS.User; -1 if approval is not required';
COMMENT ON COLUMN ptsurg."WasteApprovalDate" IS 'Date/Time of waste approval';
COMMENT ON COLUMN ptsurg."PtSurg" IS 'Primary key, unique code to identify Surgery.';
COMMENT ON COLUMN ptsurg."IsPediatric" IS 'Is this surgery for pediatric patient? 0=No (Adult), 1=Yes (Pediatric).';
COMMENT ON COLUMN ptsurg."HeightType" IS 'Height Type (0=cm;1=inch;2=ft and inch)';
COMMENT ON COLUMN ptsurg."HeightAUser" IS 'Height audit user (from Form audit record)';
COMMENT ON COLUMN ptsurg."HeightADate" IS 'Height audit date and time (from Form audit record).';
COMMENT ON COLUMN ptsurg."Height2AUser" IS 'Height2 audit user (from Form audit record)';
COMMENT ON COLUMN ptsurg."Height2ADate" IS 'Height2 audit date and time (from Form audit record).';
COMMENT ON COLUMN ptsurg."Height2" IS 'Feet (used only with HeightType=2)';
COMMENT ON COLUMN ptsurg."Height" IS 'Height in cm or inches (full or partual), depeding on HeightType';
COMMENT ON COLUMN ptsurg."BMI" IS 'Calculated Body Mass Index (added to benefit info manager)';
COMMENT ON COLUMN ptsurg."Audit" IS 'Audit record for this Surgery, ptr to AUDITHIS.Audit.';
COMMENT ON COLUMN ptsurg."ApprovalUser" IS 'Id code of approval user, ptr to USERS.User; -1 if approval is not required';
COMMENT ON COLUMN ptsurg."ApprovalDate" IS 'Date/Time of approval';
COMMENT ON COLUMN ptsurg."Appointment" IS 'Appointment, ptr to APPOINT.Appointment.';


CREATE  TABLE pttypes (
  "Patient" numeric(10,0) NOT NULL,
  "PatType" character(6) NOT NULL,
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT pttypes_primary PRIMARY KEY ("Patient", "PatType")
) ;
COMMENT ON TABLE pttypes IS 'Patient Types';
COMMENT ON COLUMN pttypes."Patient" IS 'Primary key component, the patient. Ptr to PATIENT.Patient';
COMMENT ON COLUMN pttypes."PatType" IS 'Primary key component, patient type for this patient. Ptr to PATTYPE.PatType';
COMMENT ON COLUMN pttypes."Deleted" IS 'Deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN pttypes."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE pttyphis (
  "Id" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "PatType" character(6),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT pttyphis_primary PRIMARY KEY ("Id")
) ;
CREATE INDEX IF NOT EXISTS pttyphis_pttype ON pttyphis USING btree ("Patient", "PatType") TABLESPACE pg_default;
COMMENT ON TABLE pttyphis IS 'Patient Type History';
COMMENT ON COLUMN pttyphis."Patient" IS 'The patient. Ptr to PATIENT.Patient';
COMMENT ON COLUMN pttyphis."PatType" IS 'Patient type for this patient. Ptr to PATTYPE.PatType';
COMMENT ON COLUMN pttyphis."Id" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN pttyphis."Deleted" IS 'Deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN pttyphis."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE ptvital (
  "PtVital" numeric(10,0) NOT NULL,
  "Appointment" numeric(10,0),
  "EntryMode" numeric(5,0),
  "EntryTime" timestamp without time zone,
  "Error" character(7),
  "Artifact" character(7),
  "HeartRate" numeric(5,0),
  "Temperature" numeric(5,0),
  "RespRate" numeric(5,0),
  "SystolicBP" numeric(5,0),
  "DiastolicBP" numeric(5,0),
  "SpO2" numeric(5,0),
  "ECO2" numeric(5,0),
  "Audit" numeric(10,0),
  "VitMon" character(6),
  "Deleted" numeric(5,0),
  CONSTRAINT ptvital_primary PRIMARY KEY ("PtVital")
) ;
CREATE INDEX IF NOT EXISTS ptvital_apptentrytimekey ON ptvital USING btree ("Appointment", "EntryTime") TABLESPACE pg_default;
COMMENT ON TABLE ptvital IS 'Patient Vitals for Surgery module.';
COMMENT ON COLUMN ptvital."VitMon" IS 'Vital Monitor used to capture these vital info.';
COMMENT ON COLUMN ptvital."Temperature" IS 'Vital Type 2. Range 0-500 (in 10th degree Celsius). -1 if invalid.';
COMMENT ON COLUMN ptvital."SystolicBP" IS 'Vital Type 4. Range 0-300 mmHg. -1 if invalid.';
COMMENT ON COLUMN ptvital."SpO2" IS 'Vital Type 6. Range 0-100 %. -1 if invalid.';
COMMENT ON COLUMN ptvital."RespRate" IS 'Vital Type 3. Range 0-120 bpm. -1 if invalid.';
COMMENT ON COLUMN ptvital."PtVital" IS 'Primary key, unique code to identify single entry of Vitals.';
COMMENT ON COLUMN ptvital."HeartRate" IS 'Vital Type 1. Range 0-300 bpm. -1 if invalid.';
COMMENT ON COLUMN ptvital."Error" IS 'Bitwise string to show if specific vital type has an error.';
COMMENT ON COLUMN ptvital."EntryTime" IS 'Entry date and time.';
COMMENT ON COLUMN ptvital."EntryMode" IS '(0 = manual entry; 1 = regular/timer; 2 = capture now)';
COMMENT ON COLUMN ptvital."ECO2" IS 'Vital Type 7. Range 0-150 mmHg. -1 if invalid';
COMMENT ON COLUMN ptvital."DiastolicBP" IS 'Vital Type 5. Range 0-300 mmHg. -1 if invalid.';
COMMENT ON COLUMN ptvital."Deleted" IS 'Is vital record deleted? (0 = No, 1 = Yes).';
COMMENT ON COLUMN ptvital."Audit" IS 'Audit record for this Vital entry, ptr to AUDITHIS.Audit.';
COMMENT ON COLUMN ptvital."Artifact" IS 'Bitwise string to show if specific vital type has an artifact.';
COMMENT ON COLUMN ptvital."Appointment" IS 'Appointment, ptr to APPOINT.Appointment.';


CREATE  TABLE ptvitalh (
  "PtVitalH" numeric(10,0) NOT NULL,
  "PtVital" numeric(10,0),
  "Appointment" numeric(10,0),
  "EntryMode" numeric(5,0),
  "EntryTime" timestamp without time zone,
  "Error" character(7),
  "Artifact" character(7),
  "HeartRate" numeric(5,0),
  "Temperature" numeric(5,0),
  "RespRate" numeric(5,0),
  "SystolicBP" numeric(5,0),
  "DiastolicBP" numeric(5,0),
  "SpO2" numeric(5,0),
  "ECO2" numeric(5,0),
  "Audit" numeric(10,0),
  "VitMon" character(6),
  "Deleted" numeric(5,0),
  CONSTRAINT ptvitalh_primary PRIMARY KEY ("PtVitalH")
) ;
CREATE INDEX IF NOT EXISTS ptvitalh_apptentrytimekey ON ptvitalh USING btree ("Appointment", "EntryTime") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptvitalh_ptvitalkey ON ptvitalh USING btree ("PtVital") TABLESPACE pg_default;
COMMENT ON TABLE ptvitalh IS 'History of Patient Vitals for Surgery module.';
COMMENT ON COLUMN ptvitalh."VitMon" IS 'Vital Monitor used to capture these vital info.';
COMMENT ON COLUMN ptvitalh."Temperature" IS 'Vital Type 2. Range 0-500 (in 10th degree Celsius). -1 if invalid.';
COMMENT ON COLUMN ptvitalh."SystolicBP" IS 'Vital Type 4. Range 0-300 mmHg. -1 if invalid.';
COMMENT ON COLUMN ptvitalh."SpO2" IS 'Vital Type 6. Range 0-100 %. -1 if invalid.';
COMMENT ON COLUMN ptvitalh."RespRate" IS 'Vital Type 3. Range 0-120 bpm. -1 if invalid.';
COMMENT ON COLUMN ptvitalh."PtVitalH" IS 'Primary key, unique code to identify history entry of Vitals';
COMMENT ON COLUMN ptvitalh."PtVital" IS 'History record for specific Vitals, ptr to PTVITAL.PtVital.';
COMMENT ON COLUMN ptvitalh."HeartRate" IS 'Vital Type 1. Range 0-300 bpm. -1 if invalid.';
COMMENT ON COLUMN ptvitalh."Error" IS 'Bitwise string to show if specific vital type has an error.';
COMMENT ON COLUMN ptvitalh."EntryTime" IS 'Entry date and time.';
COMMENT ON COLUMN ptvitalh."EntryMode" IS '(0 = manual entry; 1 = regular/timer; 2 = capture now)';
COMMENT ON COLUMN ptvitalh."ECO2" IS 'Vital Type 7. Range 0-150 mmHg. -1 if invalid';
COMMENT ON COLUMN ptvitalh."DiastolicBP" IS 'Vital Type 5. Range 0-300 mmHg. -1 if invalid.';
COMMENT ON COLUMN ptvitalh."Deleted" IS 'Is vital record deleted? (0 = No, 1 = Yes).';
COMMENT ON COLUMN ptvitalh."Audit" IS 'Audit record for this Vital entry, ptr to AUDITHIS.Audit.';
COMMENT ON COLUMN ptvitalh."Artifact" IS 'Bitwise string to show if specific vital type has an artifact.';
COMMENT ON COLUMN ptvitalh."Appointment" IS 'Appointment, ptr to APPOINT.Appointment.';


CREATE  TABLE ptvtlarh (
  "PtVtlArH" numeric(10,0) NOT NULL,
  "PtVtlArt" numeric(10,0),
  "PtVital" numeric(10,0),
  "VitalType" numeric(5,0),
  "ArtifactText" character varying(1000),
  "Audit" numeric(10,0),
  CONSTRAINT ptvtlarh_primary PRIMARY KEY ("PtVtlArH")
) ;
CREATE INDEX IF NOT EXISTS ptvtlarh_ptvitalkey ON ptvtlarh USING btree ("PtVital") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptvtlarh_ptvtlartkey ON ptvtlarh USING btree ("PtVtlArt") TABLESPACE pg_default;
COMMENT ON TABLE ptvtlarh IS 'History of Vitals entry Artifact for Surgery.';
COMMENT ON COLUMN ptvtlarh."VitalType" IS 'Vital Type (1=HeartRate;2=Temperature;3=RespRate;4=SystolicBP;5=DiastolicBP;6=SpO2;7="ECO2")';
COMMENT ON COLUMN ptvtlarh."PtVtlArt" IS 'History record for specific Artifact, ptr to PTVTLART.PtVtlArt.';
COMMENT ON COLUMN ptvtlarh."PtVtlArH" IS 'Primary key, unique code to identify history of Vitals Artifact.';
COMMENT ON COLUMN ptvtlarh."PtVital" IS 'Patient Vitals. Ptr to PTVITAL.PtVital.';
COMMENT ON COLUMN ptvtlarh."Audit" IS 'Audit record for this Artifact, ptr to AUDITHIS.Audit.';
COMMENT ON COLUMN ptvtlarh."ArtifactText" IS 'Artifact text, entered by user';


CREATE  TABLE ptvtlart (
  "PtVtlArt" numeric(10,0) NOT NULL,
  "PtVital" numeric(10,0),
  "VitalType" numeric(5,0),
  "ArtifactText" character varying(1000),
  "Audit" numeric(10,0),
  CONSTRAINT ptvtlart_primary PRIMARY KEY ("PtVtlArt")
) ;
CREATE INDEX IF NOT EXISTS ptvtlart_ptvitalkey ON ptvtlart USING btree ("PtVital") TABLESPACE pg_default;
COMMENT ON TABLE ptvtlart IS 'Vitals entry Artifact for Surgery.';
COMMENT ON COLUMN ptvtlart."VitalType" IS 'Vital Type (1=HeartRate;2=Temperature;3=RespRate;4=SystolicBP;5=DiastolicBP;6=SpO2;7="ECO2")';
COMMENT ON COLUMN ptvtlart."PtVtlArt" IS 'Primary key, unique code to identify Artifact.';
COMMENT ON COLUMN ptvtlart."PtVital" IS 'Patient Vitals. Ptr to PTVITAL.PtVital.';
COMMENT ON COLUMN ptvtlart."Audit" IS 'Audit record for this Artifact, ptr to AUDITHIS.Audit.';
COMMENT ON COLUMN ptvtlart."ArtifactText" IS 'Artifact text, entered by user';


CREATE  TABLE ptvtlerr (
  "PtVtlErr" numeric(10,0) NOT NULL,
  "PtVital" numeric(10,0),
  "VitalType" numeric(5,0),
  "ErrorCode" character varying(20),
  "ErrorText" character varying(1000),
  "Audit" numeric(10,0),
  CONSTRAINT ptvtlerr_primary PRIMARY KEY ("PtVtlErr")
) ;
CREATE INDEX IF NOT EXISTS ptvtlerr_ptvitalkey ON ptvtlerr USING btree ("PtVital") TABLESPACE pg_default;
COMMENT ON TABLE ptvtlerr IS 'Vitals entry Errors for Surgery.';
COMMENT ON COLUMN ptvtlerr."VitalType" IS 'Vital Type (1=HeartRate;2=Temperature;3=RespRate;4=SystolicBP;5=DiastolicBP;6=SpO2;7="ECO2")';
COMMENT ON COLUMN ptvtlerr."PtVtlErr" IS 'Primary key, unique code to identify Vitals Error.';
COMMENT ON COLUMN ptvtlerr."PtVital" IS 'Patient Vitals. Ptr to PTVITAL.PtVital.';
COMMENT ON COLUMN ptvtlerr."ErrorText" IS 'Error Text (translated/transcribed by axiUm)';
COMMENT ON COLUMN ptvtlerr."ErrorCode" IS 'Error Code (returned from Vitals monitor API)';
COMMENT ON COLUMN ptvtlerr."Audit" IS 'Audit record for this Error, ptr to AUDITHIS.Audit.';


CREATE  TABLE ptxrahis (
  "PtXRayHis" numeric(10,0) NOT NULL,
  "HistoryType" numeric(5,0),
  "PtXRay" numeric(10,0),
  "Patient" numeric(10,0),
  "DateTaken" timestamp without time zone,
  "Procedure" character(7),
  "ExposureCount" numeric(5,0),
  "AddedByUser" numeric(5,0),
  "Date" timestamp without time zone,
  "Time" numeric(10,0),
  "User" numeric(10,0),
  "StationId" numeric(10,0),
  "Deleted" numeric(5,0),
  "OrigRecNo" numeric(10,0),
  "Description" character varying(60),
  "IsDigital" numeric(5,0),
  CONSTRAINT ptxrahis_primary PRIMARY KEY ("PtXRayHis")
) ;
CREATE INDEX IF NOT EXISTS ptxrahis_patientkey ON ptxrahis USING btree ("Patient") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptxrahis_ptxraykey ON ptxrahis USING btree ("PtXRay") TABLESPACE pg_default;
COMMENT ON TABLE ptxrahis IS 'Record of changes to the patient xray table (PTXRAY).';
COMMENT ON COLUMN ptxrahis."User" IS 'User Id of the entry user, ptr to USERS.User';
COMMENT ON COLUMN ptxrahis."Time" IS 'Time the record was entered.';
COMMENT ON COLUMN ptxrahis."StationId" IS 'Station Id of the entry station';
COMMENT ON COLUMN ptxrahis."PtXRayHis" IS 'Id code to identify the history record.';
COMMENT ON COLUMN ptxrahis."PtXRay" IS 'Internal Id (from sequence), Id code of the patient xray record';
COMMENT ON COLUMN ptxrahis."Procedure" IS 'Id code of the procedure performed that required an xray, ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN ptxrahis."Patient" IS 'Id code of the patient, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptxrahis."OrigRecNo" IS 'Original record number. Ptr to TRX.OrigRecNo';
COMMENT ON COLUMN ptxrahis."IsDigital" IS 'Digital image available to view in the EHR? (0 = Unknown, 1 = Yes, digital and available to view in the EHR, 2 = No [Film or not available])';
COMMENT ON COLUMN ptxrahis."HistoryType" IS 'Type of change';
COMMENT ON COLUMN ptxrahis."ExposureCount" IS 'Number of exposures';
COMMENT ON COLUMN ptxrahis."Description" IS 'Description of the xray procedure';
COMMENT ON COLUMN ptxrahis."Deleted" IS 'Is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptxrahis."DateTaken" IS 'Date the xray was taken';
COMMENT ON COLUMN ptxrahis."Date" IS 'Date the record was entered';
COMMENT ON COLUMN ptxrahis."AddedByUser" IS 'Id code of the entry user';


CREATE  TABLE ptxray (
  "PtXRay" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "DateTaken" timestamp without time zone,
  "Procedure" character(7),
  "ExposureCount" numeric(5,0),
  "AddedByUser" numeric(5,0),
  "Date" timestamp without time zone,
  "Time" numeric(10,0),
  "User" numeric(10,0),
  "StationId" numeric(10,0),
  "Deleted" numeric(5,0),
  "OrigRecNo" numeric(10,0),
  "Description" character varying(60),
  "IsDigital" numeric(5,0),
  CONSTRAINT ptxray_primary PRIMARY KEY ("PtXRay")
) ;
CREATE INDEX IF NOT EXISTS ptxray_origrecno ON ptxray USING btree ("OrigRecNo") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS ptxray_patientkey ON ptxray USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE ptxray IS 'Patient Xray records';
COMMENT ON COLUMN ptxray."User" IS 'User Id of the entry user, ptr to USERS.User';
COMMENT ON COLUMN ptxray."Time" IS 'Time the record was entered.';
COMMENT ON COLUMN ptxray."StationId" IS 'Station Id of the entry station';
COMMENT ON COLUMN ptxray."PtXRay" IS 'Internal Id (from sequence), Id code of the patient xray record';
COMMENT ON COLUMN ptxray."Procedure" IS 'Id code of the procedure performed that is an xray procedure, ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN ptxray."Patient" IS 'Id code of the patient, ptr to PATIENT.Patient';
COMMENT ON COLUMN ptxray."OrigRecNo" IS 'Original record number. Ptr to TRX.OrigRecNo';
COMMENT ON COLUMN ptxray."IsDigital" IS 'Digital image available to view in the EHR? (0 = Unknown, 1 = Yes, digital and available to view in the EHR, 2 = No [Film or not available])';
COMMENT ON COLUMN ptxray."ExposureCount" IS 'NUmber of exposures this patient has had';
COMMENT ON COLUMN ptxray."Description" IS 'Description of the xray procedure';
COMMENT ON COLUMN ptxray."Deleted" IS 'Is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN ptxray."DateTaken" IS 'Date the xray was taken';
COMMENT ON COLUMN ptxray."Date" IS 'Date the record was entered';
COMMENT ON COLUMN ptxray."AddedByUser" IS 'Id code of the user who added this record, ptr to USERS.User';


CREATE  TABLE qrdavalset (
  "CQMId" character varying(10),
  "DataElement" numeric(5,0),
  "UID" character varying(100),
  "Code" character(18)
) ;


CREATE  TABLE question (
  "Question" character(6) NOT NULL,
  "Description" character(40),
  CONSTRAINT question_primary PRIMARY KEY ("Question")
) ;
COMMENT ON TABLE question IS 'Question codes used for creating grading/evaluation forms';
COMMENT ON COLUMN question."Question" IS 'Primary key, ID code of the question';
COMMENT ON COLUMN question."Description" IS 'Text to appear on the evaluation grading form for this question';


CREATE  TABLE race (
  "Race" character(6) NOT NULL,
  "Description" character varying(50),
  "USType" numeric(5,0),
  "Inactive" numeric(5,0),
  CONSTRAINT race_primary PRIMARY KEY ("Race")
) ;
COMMENT ON TABLE race IS 'Patient Race Codes';
COMMENT ON COLUMN race."USType" IS 'US only (0=Am. Indian/Alaskan, 1=Asian, 2=Black/Af. American, 3=Native Hawaiian/Pac. Islander, 4=White, 5=Other)';
COMMENT ON COLUMN race."Race" IS 'Id Code to identify this race type';
COMMENT ON COLUMN race."Inactive" IS 'Is Inactive? 0 = No, 1 = Yes';
COMMENT ON COLUMN race."Description" IS 'Description of this race type';


CREATE  TABLE raremark (
  "RARemark" character(6) NOT NULL,
  "Description" character varying(4000),
  "Inactive" numeric(5,0),
  CONSTRAINT raremark_primary PRIMARY KEY ("RARemark")
) ;
COMMENT ON TABLE raremark IS 'EOB Claim Item Remark Codes';
COMMENT ON COLUMN raremark."RARemark" IS 'Primary key, claim item remark code';
COMMENT ON COLUMN raremark."Inactive" IS 'Is this remark code inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN raremark."Description" IS 'Description of this remark code';


CREATE  TABLE rcgroup (
  "RcGroup" numeric(10,0) NOT NULL,
  "Name" character varying(50),
  "Days" numeric(5,0),
  CONSTRAINT rcgroup_primary PRIMARY KEY ("RcGroup")
) ;
COMMENT ON TABLE rcgroup IS 'Recall groups';
COMMENT ON COLUMN rcgroup."RcGroup" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN rcgroup."Name" IS 'Recall group name';
COMMENT ON COLUMN rcgroup."Days" IS 'Group recalls within X number of days';


CREATE  TABLE rcgrpit (
  "RcGroup" numeric(10,0),
  "RecallType" character(6) NOT NULL,
  CONSTRAINT rcgrpit_primary PRIMARY KEY ("RecallType")
) ;
COMMENT ON TABLE rcgrpit IS 'Recall group items';
COMMENT ON COLUMN rcgrpit."RecallType" IS 'Primary key, ptr to RCTYPE.RecallType';
COMMENT ON COLUMN rcgrpit."RcGroup" IS 'Primary key, ptr to RCGROUP.RcGroup';


CREATE  TABLE rctype (
  "RecallType" character(6) NOT NULL,
  "Description" character(30),
  "PreventiveCare" numeric(5,0),
  "Inactive" numeric(5,0),
  "TypeLimit" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT rctype_primary PRIMARY KEY ("RecallType")
) ;
COMMENT ON TABLE rctype IS 'Recall type codes';
COMMENT ON COLUMN rctype."TypeLimit" IS 'Limit to one active recall (0=No, 1=Yes)';
COMMENT ON COLUMN rctype."RecallType" IS 'Id Code to identify this recall type';
COMMENT ON COLUMN rctype."PreventiveCare" IS 'Type of preventive care (0=No, 1=Hygiene, 2=Exam, 3=X-Ray)';
COMMENT ON COLUMN rctype."Inactive" IS 'Make Recall type code inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN rctype."Description" IS 'Description of the recall type';


CREATE  TABLE recall (
  "Recall" character(6) NOT NULL,
  "Description" character(30),
  "Months" numeric(5,0),
  "Days" numeric(5,0),
  "Inactive" numeric(5,0),
  CONSTRAINT recall_primary PRIMARY KEY ("Recall")
) ;
COMMENT ON TABLE recall IS 'Recall Codes';
COMMENT ON COLUMN recall."Recall" IS 'Primary key, ID code of the recall';
COMMENT ON COLUMN recall."Months" IS 'Number of months for the recall period';
COMMENT ON COLUMN recall."Inactive" IS 'Make recal code inactive? 0=No,1=Yes';
COMMENT ON COLUMN recall."Description" IS 'Description of the recall code';
COMMENT ON COLUMN recall."Days" IS 'Number of days for the recall period';


CREATE  TABLE recon_tracking (
  "Id" numeric(10,0) NOT NULL DEFAULT 0,
  "Type" numeric(5,0) NOT NULL DEFAULT 0,
  "PtLetter" numeric(10,0) NOT NULL DEFAULT 0,
  "ReconDate" timestamp without time zone,
  "ReconType" numeric(5,0) NOT NULL DEFAULT 0,
  "Audit" numeric(10,0) NOT NULL DEFAULT 0,
  CONSTRAINT recon_tracking_pk PRIMARY KEY ("Id", "Type", "PtLetter")
) ;
COMMENT ON TABLE recon_tracking IS 'Join table for tracking clinical reconciliation data and their associated records.';
COMMENT ON COLUMN recon_tracking."Type" IS 'PK component.  1 - Medical Problems, 2 - Medical Test Results, 3 - Medications, 4 - Allergies';
COMMENT ON COLUMN recon_tracking."ReconType" IS 'Was the reconciliation performed manually or automatically?  0 - Automatically, 1 - Manuals';
COMMENT ON COLUMN recon_tracking."ReconDate" IS 'The reconciliation date and time';
COMMENT ON COLUMN recon_tracking."PtLetter" IS 'PK component - ptr to the attachment record';
COMMENT ON COLUMN recon_tracking."Id" IS 'PK component, ptr to primary key of table referenced by the Type column';
COMMENT ON COLUMN recon_tracking."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE refassign_override (
  "ReferralType" character varying(255) NOT NULL,
  "AssignedUser" numeric(10,0),
  "AssignedUGroup" character(6),
  CONSTRAINT refassign_override_pk PRIMARY KEY ("ReferralType")
) ;
COMMENT ON TABLE refassign_override IS 'Override table for referral''s user/user group assignment';
COMMENT ON COLUMN refassign_override."ReferralType" IS 'Primary key, referral type (in free format text)';
COMMENT ON COLUMN refassign_override."AssignedUser" IS 'if assigned to a user, points to a USER record';
COMMENT ON COLUMN refassign_override."AssignedUGroup" IS 'if assigned to a user group, points to a UGROUP record';


CREATE  TABLE referral (
  "Referral" numeric(10,0) NOT NULL,
  "Type" numeric(5,0),
  "Name" character(30),
  "Address1" character(30),
  "Address2" character(30),
  "City" character(24),
  "Province" character(6),
  "Postal" character(15),
  "Area" character(4),
  "Phone" character(8),
  "Ext" character varying(6),
  "Comment" character varying(4000),
  "Clinical1" character(6),
  "Clinical2" character(6),
  "Clinical3" character(6),
  "Clinical4" character(6),
  "Clinical5" character(6),
  "Office1" character(6),
  "Office2" character(6),
  "Office3" character(6),
  "Office4" character(6),
  "Office5" character(6),
  "First" character(15),
  "Title" character(15),
  "Middle" character(15),
  "AddressOther" character(15),
  "IDNumber" character(10),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "FromTo" numeric(5,0),
  "ClaimSpecCode" character(10),
  "FaxArea" character(4),
  "FaxPhone" character(8),
  "Email" character varying(100),
  "NPI" character varying(10),
  "IsTIN" numeric(5,0),
  CONSTRAINT referral_primary PRIMARY KEY ("Referral")
) ;
COMMENT ON TABLE referral IS 'Referrals';
COMMENT ON COLUMN referral."Type" IS 'Referral Type (0=Doctor, 1=Source)';
COMMENT ON COLUMN referral."Title" IS 'Title (prefix to the name) of the referral if the referral is not a business';
COMMENT ON COLUMN referral."Referral" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN referral."Province" IS 'Province, ptr to CITY.Province';
COMMENT ON COLUMN referral."Postal" IS 'Postal / zip code, ptr to CITY.Postal';
COMMENT ON COLUMN referral."Phone" IS 'Telephone number';
COMMENT ON COLUMN referral."Office5" IS 'Office code to classify the referral, ptr to OFFICE.Office';
COMMENT ON COLUMN referral."Office4" IS 'Office code to classify the referral, ptr to OFFICE.Office';
COMMENT ON COLUMN referral."Office3" IS 'Office code to classify the referral, ptr to OFFICE.Office';
COMMENT ON COLUMN referral."Office2" IS 'Office code to classify the referral, ptr to OFFICE.Office';
COMMENT ON COLUMN referral."Office1" IS 'Office code to classify the referral, ptr to OFFICE.Office';
COMMENT ON COLUMN referral."Name" IS 'Last name of the referral, or company name if the referral is another business.';
COMMENT ON COLUMN referral."NPI" IS 'US only - National Provider Identity';
COMMENT ON COLUMN referral."Middle" IS 'Middle name of the referral.';
COMMENT ON COLUMN referral."IsTIN" IS 'IDNumber is a "TIN"? (0=No, it represents the SSN instead, 1=Yes)';
COMMENT ON COLUMN referral."IDNumber" IS 'Billing number of the referring doctor, ptr to BILLREF.IDNumber';
COMMENT ON COLUMN referral."FromTo" IS 'Referral from or referral to? (0=From, 1=To, 2=Both)';
COMMENT ON COLUMN referral."First" IS 'First name of the referral';
COMMENT ON COLUMN referral."FaxPhone" IS 'Fax phone number';
COMMENT ON COLUMN referral."FaxArea" IS 'Fax area code';
COMMENT ON COLUMN referral."Ext" IS 'Telephone extension';
COMMENT ON COLUMN referral."Email" IS 'Email address of referral';
COMMENT ON COLUMN referral."Deleted" IS 'Item is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN referral."Comment" IS 'Free text area to enter comments about this referral';
COMMENT ON COLUMN referral."Clinical5" IS 'ID code to classify the referral, ptr to CLINICAL.Clinical';
COMMENT ON COLUMN referral."Clinical4" IS 'ID code to classify the referral, ptr to CLINICAL.Clinical';
COMMENT ON COLUMN referral."Clinical3" IS 'ID code to classify the referral, ptr to CLINICAL.Clinical';
COMMENT ON COLUMN referral."Clinical2" IS 'ID code to classify the referral, ptr to CLINICAL.Clinical';
COMMENT ON COLUMN referral."Clinical1" IS 'ID code to classify the referral, ptr to CLINICAL.Clinical';
COMMENT ON COLUMN referral."ClaimSpecCode" IS 'Taxonomy code ';
COMMENT ON COLUMN referral."City" IS 'City, ptr to CITY.City';
COMMENT ON COLUMN referral."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN referral."Area" IS 'Telephone area code';
COMMENT ON COLUMN referral."AddressOther" IS 'For USA, represents County. For Dutch, represents Room Number.';
COMMENT ON COLUMN referral."Address2" IS 'Referral address line 2';
COMMENT ON COLUMN referral."Address1" IS 'Referral address line 1';


CREATE  TABLE referral_request (
  "Id" numeric(10,0) NOT NULL,
  "axiUmApiLogId" numeric(10,0),
  "ExternalId" character varying(255),
  "CreateDateTime" timestamp without time zone,
  "Status" character varying(255),
  "ReferrerRequestId" numeric(10,0),
  "PatientRequestId" numeric(10,0),
  "AssignedUser" numeric(10,0),
  "AssignedUGroup" character(6),
  "PtRefer" numeric(10,0),
  "Type" character varying(255),
  "Category" character varying(255),
  "Priority" character varying(255),
  "RequestDateTime" timestamp without time zone,
  "ExpirationDateTime" timestamp without time zone,
  "Reason" character varying(255),
  note clob,
  "ExternalIdType" character varying(255),
  "Source" character varying(255),
  CONSTRAINT referral_request_primary PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE referral_request IS '[OBSOLETE] details for an inbound referral request';
COMMENT ON COLUMN referral_request.note IS 'notes about the referral';
COMMENT ON COLUMN referral_request."axiUmApiLogId" IS 'Id of the AXIUM_API_LOG record that resulted in this entry (if applicable)';
COMMENT ON COLUMN referral_request."Type" IS 'type of referral request (e.g. Laboratory, Radiology, etc.)';
COMMENT ON COLUMN referral_request."Status" IS 'The status of the request (Pending, Accepted, REjected, Expired, Closed)';
COMMENT ON COLUMN referral_request."Source" IS 'The source of the call (vendor id)';
COMMENT ON COLUMN referral_request."RequestDateTime" IS 'date and tikme the request was made in the referring system';
COMMENT ON COLUMN referral_request."ReferrerRequestId" IS 'id of the REFERRER_REQUEST record associated with this referral request';
COMMENT ON COLUMN referral_request."Reason" IS 'short reason for the referral request (e.g. Second Opinion, Patient Preference, etc.)';
COMMENT ON COLUMN referral_request."PtRefer" IS 'points to the corresponding PTREFER record created';
COMMENT ON COLUMN referral_request."Priority" IS 'priority of the referral request (e.g. STAT, ASAP, Routine)';
COMMENT ON COLUMN referral_request."PatientRequestId" IS 'id of the PATIENT_REQUEST record associated with this referral request';
COMMENT ON COLUMN referral_request."Id" IS 'Primary key, sequence field';
COMMENT ON COLUMN referral_request."ExternalIdType" IS 'the type of id in ExternalId';
COMMENT ON COLUMN referral_request."ExternalId" IS 'referral Id in the referring system';
COMMENT ON COLUMN referral_request."ExpirationDateTime" IS 'date and time the referral request expires';
COMMENT ON COLUMN referral_request."CreateDateTime" IS 'date and time the request was received and created';
COMMENT ON COLUMN referral_request."Category" IS 'category of referral request (e.g. Inpatient, Emergency, etc.)';
COMMENT ON COLUMN referral_request."AssignedUser" IS 'if assigned to a user, points to a USER record';
COMMENT ON COLUMN referral_request."AssignedUGroup" IS 'if assigned to a user group, points to a UGROUP record';


CREATE  TABLE referrer_request (
  "Id" numeric(10,0) NOT NULL,
  "axiUmApiLogId" numeric(10,0),
  "ExternalId" character varying(255),
  "CreateDateTime" timestamp without time zone,
  "Referral" numeric(10,0),
  "LastName" character varying(255),
  "FirstName" character varying(255),
  "StreetAddress" character varying(255),
  "City" character varying(255),
  "Province" character varying(255),
  "Postal" character varying(255),
  "OfficePhone" character varying(255),
  "ExternalIdType" character varying(255),
  "Title" character varying(255),
  "Email" character varying(255),
  note clob,
  "MiddleName" character varying(255),
  "Source" character varying(255),
  "FaxPhone" character varying(255),
  "AddressOther" character varying(255),
  CONSTRAINT referrer_request_primary PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE referrer_request IS '[OBSOLETE] details for a referring doctor or entity that has been requested to be added';
COMMENT ON COLUMN referrer_request.note IS 'notes about the referral';
COMMENT ON COLUMN referrer_request."axiUmApiLogId" IS 'Id of the AXIUM_API_LOG record that resulted in this entry (if applicable)';
COMMENT ON COLUMN referrer_request."Title" IS 'title';
COMMENT ON COLUMN referrer_request."StreetAddress" IS 'street address';
COMMENT ON COLUMN referrer_request."Source" IS 'The source of the call (vendor id)';
COMMENT ON COLUMN referrer_request."Referral" IS 'points to the corresponding REFERRAL record created or referenced';
COMMENT ON COLUMN referrer_request."Province" IS 'state or province';
COMMENT ON COLUMN referrer_request."Postal" IS 'zip or postal code';
COMMENT ON COLUMN referrer_request."OfficePhone" IS 'office phone number';
COMMENT ON COLUMN referrer_request."MiddleName" IS 'middle name';
COMMENT ON COLUMN referrer_request."LastName" IS 'last name';
COMMENT ON COLUMN referrer_request."Id" IS 'Primary key, sequence field';
COMMENT ON COLUMN referrer_request."FirstName" IS 'first name';
COMMENT ON COLUMN referrer_request."FaxPhone" IS 'fax phone number';
COMMENT ON COLUMN referrer_request."ExternalIdType" IS 'the type of id in ExternalId (e.g. "NPI")';
COMMENT ON COLUMN referrer_request."ExternalId" IS 'referrer Id in the referring system';
COMMENT ON COLUMN referrer_request."Email" IS 'email address';
COMMENT ON COLUMN referrer_request."CreateDateTime" IS 'date and time of the request';
COMMENT ON COLUMN referrer_request."City" IS 'city';
COMMENT ON COLUMN referrer_request."AddressOther" IS 'county, or other address information';


CREATE  TABLE refhis (
  "Id" numeric(10,0) NOT NULL,
  "Referral" numeric(10,0),
  "Type" numeric(5,0),
  "Name" character(30),
  "Address1" character(30),
  "Address2" character(30),
  "City" character(24),
  "Province" character(6),
  "Postal" character(15),
  "Area" character(4),
  "Phone" character(8),
  "Ext" character varying(6),
  "Comment" character varying(4000),
  "Clinical1" character(6),
  "Clinical2" character(6),
  "Clinical3" character(6),
  "Clinical4" character(6),
  "Clinical5" character(6),
  "Office1" character(6),
  "Office2" character(6),
  "Office3" character(6),
  "Office4" character(6),
  "Office5" character(6),
  "First" character(15),
  "Title" character(15),
  "Middle" character(15),
  "AddressOther" character(15),
  "IDNumber" character(10),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "FromTo" numeric(5,0),
  "ClaimSpecCode" character(10),
  "FaxArea" character(4),
  "FaxPhone" character(8),
  "Email" character varying(100),
  "NPI" character varying(10),
  "IsTIN" numeric(5,0),
  CONSTRAINT refhis_primary PRIMARY KEY ("Id")
) ;
CREATE INDEX IF NOT EXISTS refhis_referral ON refhis USING btree ("Referral") TABLESPACE pg_default;
COMMENT ON TABLE refhis IS 'Referral History';
COMMENT ON COLUMN refhis."Type" IS 'Referral Type (0=Doctor, 1=Source)';
COMMENT ON COLUMN refhis."Title" IS 'Office code to classify the referral, ptr to OFFICE.Office';
COMMENT ON COLUMN refhis."Referral" IS 'Referral that this history is for, ptr to REFERRAL.Referral';
COMMENT ON COLUMN refhis."Province" IS 'For USA, represents County. For Dutch, represents Room Number.';
COMMENT ON COLUMN refhis."Postal" IS 'City, ptr to CITY.City';
COMMENT ON COLUMN refhis."Phone" IS 'Postal / zip code, ptr to CITY.Postal';
COMMENT ON COLUMN refhis."Office5" IS 'Office code to classify the referral, ptr to OFFICE.Office';
COMMENT ON COLUMN refhis."Office4" IS 'Office code to classify the referral, ptr to OFFICE.Office';
COMMENT ON COLUMN refhis."Office3" IS 'Office code to classify the referral, ptr to OFFICE.Office';
COMMENT ON COLUMN refhis."Office2" IS 'ID code to classify the referral, ptr to CLINICAL.Clinical';
COMMENT ON COLUMN refhis."Office1" IS 'ID code to classify the referral, ptr to CLINICAL.Clinical';
COMMENT ON COLUMN refhis."Name" IS 'Last name of the referral, or company name if the referral is another business.';
COMMENT ON COLUMN refhis."NPI" IS 'US only - National Provider Identity';
COMMENT ON COLUMN refhis."Middle" IS 'First name of the referral';
COMMENT ON COLUMN refhis."IsTIN" IS 'IDNumber is a "TIN"? (0=No, it represents the SSN instead, 1=Yes)';
COMMENT ON COLUMN refhis."Id" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN refhis."IDNumber" IS 'Billing number of the referring doctor, ptr to BILLREF.IDNumber';
COMMENT ON COLUMN refhis."FromTo" IS 'Referral from or referral to? (0=From, 1=To, 2=Both)';
COMMENT ON COLUMN refhis."First" IS 'Office code to classify the referral, ptr to OFFICE.Office';
COMMENT ON COLUMN refhis."FaxPhone" IS 'Fax phone number';
COMMENT ON COLUMN refhis."FaxArea" IS 'Fax area code';
COMMENT ON COLUMN refhis."Ext" IS 'Telephone area code';
COMMENT ON COLUMN refhis."Email" IS 'Email address of referral';
COMMENT ON COLUMN refhis."Deleted" IS 'Item is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN refhis."Comment" IS 'Telephone number';
COMMENT ON COLUMN refhis."Clinical5" IS 'ID code to classify the referral, ptr to CLINICAL.Clinical';
COMMENT ON COLUMN refhis."Clinical4" IS 'ID code to classify the referral, ptr to CLINICAL.Clinical';
COMMENT ON COLUMN refhis."Clinical3" IS 'ID code to classify the referral, ptr to CLINICAL.Clinical';
COMMENT ON COLUMN refhis."Clinical2" IS 'Free text area to enter comments about this referral';
COMMENT ON COLUMN refhis."Clinical1" IS 'Telephone extension';
COMMENT ON COLUMN refhis."ClaimSpecCode" IS 'Taxonomy code ';
COMMENT ON COLUMN refhis."City" IS 'Referral address line 2';
COMMENT ON COLUMN refhis."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN refhis."Area" IS 'Province, ptr to CITY.Province';
COMMENT ON COLUMN refhis."AddressOther" IS 'Title (prefix to the name) of the referral if the referral is not a business';
COMMENT ON COLUMN refhis."Address2" IS 'Referral address line 1';
COMMENT ON COLUMN refhis."Address1" IS 'Middle name of the referral.';


CREATE  TABLE regional (
  "Key" numeric(5,0) NOT NULL,
  "Value" numeric(5,0),
  "Description" character varying(255),
  CONSTRAINT regional_primary PRIMARY KEY ("Key")
) ;
COMMENT ON TABLE regional IS 'Regional Settings';
COMMENT ON COLUMN regional."Value" IS 'Numeric value of the regional setting.';
COMMENT ON COLUMN regional."Key" IS 'Primary key, internal ID.';
COMMENT ON COLUMN regional."Description" IS 'Description of the regional setting.';


CREATE  TABLE relation (
  "Relation" character(15) NOT NULL,
  CONSTRAINT relation_primary PRIMARY KEY ("Relation")
) ;
COMMENT ON TABLE relation IS 'Code table for relation';
COMMENT ON COLUMN relation."Relation" IS 'Values - Aunt, Brother, Cousin, Father, Grandfather, Grandmother, Mother, Sister, Uncle';


CREATE  TABLE reqfld (
  "ReqFld" numeric(10,0) NOT NULL,
  "Description" character varying(50),
  "Type" numeric(5,0),
  CONSTRAINT reqfld_primary PRIMARY KEY ("ReqFld")
) ;
COMMENT ON TABLE reqfld IS 'User definable required fields';
COMMENT ON COLUMN reqfld."Type" IS 'Required field control type (0=Patient, 1=Recall, 2=Guarantor, 3=Prescription)';
COMMENT ON COLUMN reqfld."ReqFld" IS 'Id code to identify the required field control, internal Id from sequence';
COMMENT ON COLUMN reqfld."Description" IS 'Description of the required field control';


CREATE  TABLE reqfldcr (
  "ReqFld" numeric(10,0) NOT NULL,
  "Practice" numeric(10,0) NOT NULL,
  "Code" character(6) NOT NULL,
  "Type" numeric(5,0) NOT NULL,
  CONSTRAINT reqfldcr_primary PRIMARY KEY ("Type", "Practice", "Code", "ReqFld")
) ;
CREATE INDEX IF NOT EXISTS reqfldcr_type ON reqfldcr USING btree ("Type") TABLESPACE pg_default;
COMMENT ON TABLE reqfldcr IS 'Required fields assignments';
COMMENT ON COLUMN reqfldcr."Type" IS 'Required field control type (0=Patient, 1=Recall, 2=Guarantor, 3=Prescription)';
COMMENT ON COLUMN reqfldcr."ReqFld" IS 'Id code of the required field control, copy of REQFLD.ReqFld';
COMMENT ON COLUMN reqfldcr."Practice" IS 'Id code of the practice the required field control is being set up for';
COMMENT ON COLUMN reqfldcr."Code" IS 'If Type =0, PATIENT.Status. If Type =1, RECALL.Recall';


CREATE  TABLE reqfldit (
  "ParentId" numeric(10,0) NOT NULL,
  "DialogId" numeric(5,0) NOT NULL,
  "FieldId" numeric(5,0) NOT NULL,
  "Description" character varying(60),
  CONSTRAINT reqfldit_primary PRIMARY KEY ("ParentId", "DialogId", "FieldId")
) ;
COMMENT ON TABLE reqfldit IS 'User definable required fields';
COMMENT ON COLUMN reqfldit."ParentId" IS 'Parent record (REQFLD.ReqFld) ';
COMMENT ON COLUMN reqfldit."FieldId" IS 'Field # in the resource code';
COMMENT ON COLUMN reqfldit."DialogId" IS 'Dialog ID in the resource code';
COMMENT ON COLUMN reqfldit."Description" IS 'Description of the field (for reporting purposes)';


CREATE  TABLE reqnote (
  "ReqNote" numeric(10,0) NOT NULL,
  "Appointment" numeric(10,0) NOT NULL,
  "Date" timestamp without time zone,
  "Time" numeric(10,0),
  "User" numeric(10,0),
  "StationId" numeric(10,0),
  "Deleted" numeric(5,0),
  "DeleteDate" timestamp without time zone,
  "Note" character varying(4000),
  CONSTRAINT reqnote_primary PRIMARY KEY ("ReqNote")
) ;
CREATE INDEX IF NOT EXISTS reqnote_appointment ON reqnote USING btree ("Appointment") TABLESPACE pg_default;
COMMENT ON TABLE reqnote IS 'Holds the contents of the note fields for the appointment requests.';
COMMENT ON COLUMN reqnote."User" IS 'User Id of the entry user, ptr to USERS.User';
COMMENT ON COLUMN reqnote."Time" IS 'Time the note was entered (in minutes from midnight) ';
COMMENT ON COLUMN reqnote."StationId" IS 'StationId of the entry user';
COMMENT ON COLUMN reqnote."ReqNote" IS 'Id code, internal Id (from sequence) representing the appointment request note';
COMMENT ON COLUMN reqnote."Note" IS 'Free text area to enter the body of the note';
COMMENT ON COLUMN reqnote."Deleted" IS 'Note is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN reqnote."DeleteDate" IS 'Date this note was deleted';
COMMENT ON COLUMN reqnote."Date" IS 'Date the note was entered';
COMMENT ON COLUMN reqnote."Appointment" IS 'Appointment this note is attached to, ptr to APPOINT.Appointment';


CREATE  TABLE request (
  "Request" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "Chart" character(10),
  "User" numeric(10,0),
  "DateOut" timestamp without time zone,
  "TimeOut" numeric(10,0),
  "WhenDateIn" timestamp without time zone,
  "WhenTimeIn" numeric(10,0),
  "Location" character(6),
  "Reason" character(40),
  "Override" numeric(5,0),
  CONSTRAINT request_primary PRIMARY KEY ("Request")
) ;
CREATE INDEX IF NOT EXISTS request_datetimeout ON request USING btree ("DateOut", "TimeOut") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS request_patientdatekey ON request USING btree ("Patient", "DateOut") TABLESPACE pg_default;
COMMENT ON TABLE request IS 'Chart requests, used for Chart Tracking';
COMMENT ON COLUMN request."WhenTimeIn" IS 'Time the chart is due back (in minutes from midnight)';
COMMENT ON COLUMN request."WhenDateIn" IS 'Date the chart is due back';
COMMENT ON COLUMN request."User" IS 'User requesting the patient chart, ptr to USERS.User';
COMMENT ON COLUMN request."TimeOut" IS 'Time the chart is requested for (in minutes from midnight)';
COMMENT ON COLUMN request."Request" IS 'Primary key, Internal ID (from sequence)';
COMMENT ON COLUMN request."Reason" IS 'Reason for the request';
COMMENT ON COLUMN request."Patient" IS 'Patient ID, ptr to PATIENT.Patient';
COMMENT ON COLUMN request."Override" IS 'Override locks? (0 = No, 1 = Yes)';
COMMENT ON COLUMN request."Location" IS 'Location ID to send chart to, ptr to LOCATION.Location';
COMMENT ON COLUMN request."DateOut" IS 'Date the chart is requested for';
COMMENT ON COLUMN request."Chart" IS 'Patient chart ID, ptr to PATIENT.Chart';


CREATE  TABLE reservcd (
  "DisplayDesc" character varying(30) NOT NULL,
  "Color" numeric(10,0),
  "Inactive" numeric(5,0),
  CONSTRAINT reservcd_primary PRIMARY KEY ("DisplayDesc")
) ;
COMMENT ON TABLE reservcd IS 'Clinic Time Reasons';
COMMENT ON COLUMN reservcd."Inactive" IS 'Is this clinic time reason inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN reservcd."DisplayDesc" IS 'Primary key, description of the clinic time reason.';
COMMENT ON COLUMN reservcd."Color" IS 'Color to display this clinic time reason with, numeric representation of RGB value. ';


CREATE  TABLE reserve (
  "Reserve" numeric(10,0) NOT NULL,
  "Chair" numeric(10,0) NOT NULL,
  "Date" timestamp without time zone,
  "ClinicTime" numeric(10,0),
  "Producer" character(10),
  "Start" numeric(10,0),
  "End" numeric(10,0),
  "Appointment" numeric(10,0),
  "Cancelled" numeric(5,0),
  "Holiday" numeric(10,0),
  "Vacation" numeric(10,0),
  "WschitemId" numeric(10,0),
  "GroupLayout" numeric(10,0),
  "Assistant" character(10),
  "Unavailable" numeric(5,0),
  "Closed" numeric(5,0),
  "DisplayDesc" character varying(30),
  "Restricted" numeric(5,0),
  "Shared" numeric(5,0),
  CONSTRAINT reserve_primary PRIMARY KEY ("Reserve")
) ;
CREATE INDEX IF NOT EXISTS reserve_appointmentkey ON reserve USING btree ("Chair", "Date", "Appointment") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS reserve_dateavailkey ON reserve USING btree ("Date", "Cancelled", "Unavailable", "Closed") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS reserve_datechairkey ON reserve USING btree ("Date", "Chair") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS reserve_producerdate ON reserve USING btree ("Producer", "Date") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS reserve_producervacationkey ON reserve USING btree ("Producer", "Vacation") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS reserve_provider ON reserve USING btree ("Date", "Producer") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS reserve_wschitemidkey ON reserve USING btree ("WschitemId") TABLESPACE pg_default;
COMMENT ON TABLE reserve IS 'Chair Reservations';
COMMENT ON COLUMN reserve."WschitemId" IS 'If this reserve is from a workschedule, ptr to the WSCHITEM.Id';
COMMENT ON COLUMN reserve."Vacation" IS 'If this reserve is from a vacation, ptr to the VACATION.Id';
COMMENT ON COLUMN reserve."Unavailable" IS 'Is the chair unavailable during this reservation? (0 = No, 1 = Yes)';
COMMENT ON COLUMN reserve."Start" IS 'Start time of the reservation, in minutes from midnight.';
COMMENT ON COLUMN reserve."Shared" IS 'Is shared? (0=No, 1=Yes)';
COMMENT ON COLUMN reserve."Restricted" IS 'Is restricted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN reserve."Reserve" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN reserve."Producer" IS 'Provider to book for this reservation, ptr to PRODUCER.Producer';
COMMENT ON COLUMN reserve."Holiday" IS 'If this reserve is from a holiday, ptr to the HOLIDAY.Id';
COMMENT ON COLUMN reserve."GroupLayout" IS 'If this reserve is from a group layout, ptr to the GROUPL.GroupLayout';
COMMENT ON COLUMN reserve."End" IS 'End time of the reservation, in minutes from midnight.';
COMMENT ON COLUMN reserve."DisplayDesc" IS 'The description that will display within the scheduler on this reserve.';
COMMENT ON COLUMN reserve."Date" IS 'Date that the reservation is for. ';
COMMENT ON COLUMN reserve."Closed" IS 'Is closed? (0 = No, 1 = Yes)';
COMMENT ON COLUMN reserve."ClinicTime" IS 'The session to book for this reservation, ptr to CLINICT.ClinicTime';
COMMENT ON COLUMN reserve."Chair" IS 'Chair that is being reserved, ptr to CHAIR.Chair';
COMMENT ON COLUMN reserve."Cancelled" IS 'Reservation is cancelled? (0 = No, 1 = Yes)';
COMMENT ON COLUMN reserve."Assistant" IS 'Secondary provider or assistant for this reservation. Ptr to PRODUCER.Producer';
COMMENT ON COLUMN reserve."Appointment" IS 'Appointment that this reservation is for, ptr to APPOINT.Appointment';


CREATE  TABLE resphis (
  "RespHis" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "Last" character(25),
  "First" character(30),
  "Middle" character(15),
  "Title" character(15),
  "Birth" timestamp without time zone,
  "Address1" character(30),
  "Address2" character(30),
  "City" character(24),
  "Province" character(6),
  "Postal" character(15),
  "HomeArea" character(4),
  "HomePhone" character(8),
  "AltArea" character(4),
  "AltPhone" character(8),
  "Status" character(6),
  "Sex" numeric(5,0),
  "Marital" numeric(5,0),
  "AddressOther" character(15),
  "RespNumber" character(15),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "Country" character(30),
  "Preferred" character(30),
  "HomeExt" character varying(6),
  "AltExt" character varying(6),
  "EmancedMinor" numeric(5,0),
  "PrefLanguage" character(6),
  "Statements" numeric(5,0),
  "Email" character varying(100),
  "IsTrustedAudit" numeric(10,0),
  "Sin" character varying(15),
  CONSTRAINT resphis_primary PRIMARY KEY ("RespHis")
) ;
CREATE INDEX IF NOT EXISTS resphis_patient ON resphis USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE resphis IS 'Record of changes to responsible party in patient record ';
COMMENT ON COLUMN resphis."Title" IS 'Prefix to the name ie: Sir, Mr.';
COMMENT ON COLUMN resphis."Status" IS 'Patient status, defaults to active, ptr to STATUS.Status';
COMMENT ON COLUMN resphis."Statements" IS 'Are statements sent to the responsible party? (0=No, 1=Yes)';
COMMENT ON COLUMN resphis."Sin" IS 'ID number for the patient, used generally to store SIN (Canada), SSN (US)';
COMMENT ON COLUMN resphis."Sex" IS 'Responsible person gender (0=Unknown, 1=Male, 2=Female, 3=Transgender, 4=Gender X, 5=Other)';
COMMENT ON COLUMN resphis."RespNumber" IS 'Responsible person ID #';
COMMENT ON COLUMN resphis."RespHis" IS 'Primary key, Id code to represent the history record';
COMMENT ON COLUMN resphis."Province" IS 'Province / state, ptr to CITY.Province';
COMMENT ON COLUMN resphis."Preferred" IS 'Responsible party preferred name';
COMMENT ON COLUMN resphis."PrefLanguage" IS 'Preferred Language, ptr to LANGCD.LangCd';
COMMENT ON COLUMN resphis."Postal" IS 'Postal / zip code, ptr to CITY.Postal';
COMMENT ON COLUMN resphis."Patient" IS 'Primary key, Internal ID (from sequence), ID code of the patient';
COMMENT ON COLUMN resphis."Middle" IS 'Middle name';
COMMENT ON COLUMN resphis."Marital" IS 'Marital status (0=Unknown, 1=Single, 2=Married, 3=Divorced, 4=Common-Law, 5=Separated, 6=Widowed), defaults to unknown';
COMMENT ON COLUMN resphis."Last" IS 'Last name';
COMMENT ON COLUMN resphis."IsTrustedAudit" IS 'The audit number that is recorded when the Patient SIN is stamped as trusted';
COMMENT ON COLUMN resphis."HomePhone" IS 'Telephone number (home), Format: ###-####';
COMMENT ON COLUMN resphis."HomeExt" IS 'Patient home phone extension number';
COMMENT ON COLUMN resphis."HomeArea" IS 'Telephone area code (home)';
COMMENT ON COLUMN resphis."First" IS 'First name';
COMMENT ON COLUMN resphis."EmancedMinor" IS 'Patient is an emancipated minor and can be a primary guarantor. 0 = No, 1 = Yes.';
COMMENT ON COLUMN resphis."Email" IS 'Email address of the responsible party';
COMMENT ON COLUMN resphis."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN resphis."Country" IS 'Country ';
COMMENT ON COLUMN resphis."City" IS 'City, ptr to CITY.City';
COMMENT ON COLUMN resphis."Birth" IS 'Date of birth, (MM/DD/YYYY) defaults to 00/00/0000 if no entry is made';
COMMENT ON COLUMN resphis."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN resphis."AltPhone" IS 'Alternate phone number';
COMMENT ON COLUMN resphis."AltExt" IS 'Patient alternate phone extension number';
COMMENT ON COLUMN resphis."AltArea" IS 'Alternate area code';
COMMENT ON COLUMN resphis."AddressOther" IS 'For USA, represents County. For Dutch, represents Room Number';
COMMENT ON COLUMN resphis."Address2" IS 'Patient address line 2';
COMMENT ON COLUMN resphis."Address1" IS 'Patient address line 1';


CREATE  TABLE resplist (
  "RespList" numeric(10,0) NOT NULL,
  "Description" character varying(30),
  "Inactive" numeric(5,0),
  CONSTRAINT resplist_primary PRIMARY KEY ("RespList")
) ;
COMMENT ON TABLE resplist IS 'Ortho custom lists';
COMMENT ON COLUMN resplist."RespList" IS 'Id code to identify the ortho custom list, Internal ID from sequence';
COMMENT ON COLUMN resplist."Inactive" IS 'Record is inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN resplist."Description" IS 'Description of the Ortho custom list';


CREATE  TABLE response (
  "RespList" numeric(10,0) NOT NULL,
  "Response" character varying(30) NOT NULL,
  "Inactive" numeric(5,0),
  CONSTRAINT response_primary PRIMARY KEY ("RespList", "Response")
) ;
COMMENT ON TABLE response IS 'Ortho custom list items for use with the RESPLIST table';
COMMENT ON COLUMN response."Response" IS 'Description of the response';
COMMENT ON COLUMN response."RespList" IS 'Id code of the ortho custom list to which this belongs';
COMMENT ON COLUMN response."Inactive" IS 'Record is inactive? (=No, 1 = Yes)';


CREATE  TABLE rpthis (
  "RptHis" numeric(10,0) NOT NULL,
  "Type" numeric(5,0),
  "Category" numeric(5,0),
  "CustRpt" numeric(10,0),
  "Description" character varying(50),
  "CustColumns" character varying(4000),
  data bytea,
  "Audit" numeric(10,0),
  "Cust_Qry_AutoDec" numeric(10,0),
  CONSTRAINT rpthis_primary PRIMARY KEY ("RptHis")
) ;
COMMENT ON TABLE rpthis IS 'Log of who ran Info Manager Reports';
COMMENT ON COLUMN rpthis.data IS 'If Type in (0,1) the columns / criteria of query';
COMMENT ON COLUMN rpthis."Type" IS '0 = Info Manager - ad hoc query, 1 = Info Manager Custom report, 2 = Info Manager Practice report, 3 = Crystal Custom Tab report';
COMMENT ON COLUMN rpthis."RptHis" IS 'Sequenced primary key';
COMMENT ON COLUMN rpthis."Description" IS 'The report description';
COMMENT ON COLUMN rpthis."Cust_Qry_AutoDec" IS 'If Type = 1 then the ID of CUST_QRY record for the pre-defined report - points to CUST_QRY.CUST_QRY_AutoDec';
COMMENT ON COLUMN rpthis."CustRpt" IS 'If Type = 3 the link to the Custom Report in Maintenance - points to CUSTRPT.Custrpt';
COMMENT ON COLUMN rpthis."CustColumns" IS 'If Type in (0,1) the column labels';
COMMENT ON COLUMN rpthis."Category" IS 'If Type in (0,1,2) the Index category. Like the CUST_QRY.Type field - 0 = Patient List…';
COMMENT ON COLUMN rpthis."Audit" IS 'AUDITHIS.Audit (User / Date / Time audit info)';


CREATE  TABLE rtfcolor (
  "RtfColor" numeric(10,0) NOT NULL,
  "TxtColor" numeric(10,0),
  "Order" numeric(5,0),
  CONSTRAINT rtfcolor_primary PRIMARY KEY ("RtfColor")
) ;
COMMENT ON TABLE rtfcolor IS 'Available colors for RTF notes';
COMMENT ON COLUMN rtfcolor."TxtColor" IS 'Background color to display for this stage, numeric representation of RGB value.';
COMMENT ON COLUMN rtfcolor."RtfColor" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN rtfcolor."Order" IS 'Display Order in the dialog';


CREATE  TABLE rxnconso (
  "RXCUI" character varying(8) NOT NULL,
  "LAT" character varying(3) NOT NULL DEFAULT 'ENG'::character varying,
  "TS" character varying(1),
  "LUI" character varying(8),
  "STT" character varying(3),
  "SUI" character varying(8),
  "ISPREF" character varying(1),
  "RXAUI" character varying(8) NOT NULL,
  "SAUI" character varying(50),
  "SCUI" character varying(50),
  "SDUI" character varying(50),
  "SAB" character varying(20) NOT NULL,
  "TTY" character varying(20) NOT NULL,
  "CODE" character varying(50) NOT NULL,
  "STR" character varying(3000) NOT NULL,
  "SRL" character varying(10),
  "SUPPRESS" character varying(1),
  "CVF" character varying(50)
) ;
CREATE INDEX IF NOT EXISTS x_rxnconso_rxcui ON rxnconso USING btree ("RXCUI") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS x_rxnconso_tty ON rxnconso USING btree ("TTY") TABLESPACE pg_default;


CREATE  TABLE rxnndc (
  "RxNorm" character varying(8) NOT NULL,
  "NDC" character varying(4000) NOT NULL
) ;
CREATE INDEX IF NOT EXISTS rxnndc_rxnorm ON rxnndc USING btree ("RxNorm") TABLESPACE pg_default;
COMMENT ON TABLE rxnndc IS 'Mapping table to map between RxNorm and "NDC" codes';
COMMENT ON COLUMN rxnndc."RxNorm" IS 'RxNorm code';
COMMENT ON COLUMN rxnndc."NDC" IS 'National Drug Code';


CREATE  TABLE rxnorm (
  "RxNormAtom" character varying(50) NOT NULL,
  "RxNorm" character varying(8) NOT NULL,
  "Description" character varying(3000) NOT NULL
) ;
CREATE INDEX IF NOT EXISTS rxnorm_rxnorm ON rxnorm USING btree ("RxNorm") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS rxnorm_rxnormatom ON rxnorm USING btree ("RxNormAtom") TABLESPACE pg_default;
COMMENT ON TABLE rxnorm IS 'RxNorm codes';
COMMENT ON COLUMN rxnorm."RxNormAtom" IS 'RxNorm Atom code ("RXCUI")';
COMMENT ON COLUMN rxnorm."RxNorm" IS 'RxNorm code';
COMMENT ON COLUMN rxnorm."Description" IS 'Description of the code';


CREATE  TABLE rxnrel (
  rxcui1 character varying(8),
  rxaui1 character varying(8),
  stype1 character varying(50),
  "REL" character varying(4),
  rxcui2 character varying(8),
  rxaui2 character varying(8),
  stype2 character varying(50),
  "RELA" character varying(100),
  "RUI" character varying(10),
  "SRUI" character varying(50),
  "SAB" character varying(20) NOT NULL,
  "SL" character varying(1000),
  "DIR" character varying(1),
  "RG" character varying(10),
  "SUPPRESS" character varying(1),
  "CVF" character varying(50)
) ;
CREATE INDEX IF NOT EXISTS x_rxnrel_rela ON rxnrel USING btree ("RELA") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS x_rxnrel_rxcui1 ON rxnrel USING btree (rxcui1) TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS x_rxnrel_rxcui2 ON rxnrel USING btree (rxcui2) TABLESPACE pg_default;


CREATE  TABLE rxnsat (
  "RXCUI" character varying(8),
  "LUI" character varying(8),
  "SUI" character varying(8),
  "RXAUI" character varying(8),
  "STYPE" character varying(50),
  "CODE" character varying(50),
  "ATUI" character varying(11),
  "SATUI" character varying(50),
  "ATN" character varying(50) NOT NULL,
  "SAB" character varying(20) NOT NULL,
  "ATV" character varying(4000),
  "SUPPRESS" character varying(1),
  "CVF" character varying(50)
) ;
CREATE INDEX IF NOT EXISTS x_rxnsat_atn ON rxnsat USING btree ("ATN") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS x_rxnsat_rxcui ON rxnsat USING btree ("RXCUI") TABLESPACE pg_default;


CREATE  TABLE scheme (
  "Scheme" character(6) NOT NULL,
  "MarkScheme" numeric(5,0),
  "Min" numeric,
  "Max" numeric,
  "Increment" numeric,
  "Validate" numeric(5,0),
  CONSTRAINT scheme_primary PRIMARY KEY ("Scheme")
) ;
COMMENT ON TABLE scheme IS 'Grading schemes, used to store all different methods of evaluation used';
COMMENT ON COLUMN scheme."Validate" IS 'Limit acceptable grades to the scheme item records defined? (0 = No, 1 = Yes)';
COMMENT ON COLUMN scheme."Scheme" IS 'Primary key, ID code to identify the scheme';
COMMENT ON COLUMN scheme."Min" IS 'If numeric, then minimum acceptable grade';
COMMENT ON COLUMN scheme."Max" IS 'If numeric, then maximum acceptable grade';
COMMENT ON COLUMN scheme."MarkScheme" IS 'Scheme Type (0=Numeric, 1=Letter)';
COMMENT ON COLUMN scheme."Increment" IS 'If numeric, then acceptable increment values (I.e., 0.5)';


CREATE  TABLE school (
  "School" character varying(25) NOT NULL,
  "Health" character(20),
  CONSTRAINT school_primary PRIMARY KEY ("School")
) ;
COMMENT ON TABLE school IS 'School information for patients who are students';
COMMENT ON COLUMN school."School" IS 'Primary key, name of the school';
COMMENT ON COLUMN school."Health" IS 'Health unit name';


CREATE  TABLE schrule (
  "SchRule" numeric(10,0) NOT NULL,
  "ProdType" character(1),
  "Provider" character(10),
  "MaxProvSCFreeTime" numeric(5,0),
  "MinSCGapTime" numeric(5,0),
  "SchRuleExpiry" numeric(5,0),
  "MaxProvMCFreeTime" numeric(5,0),
  "MaxApptMCTime" numeric(5,0),
  "DORSameGHyg" numeric(5,0),
  "DORDiffGHyg" numeric(5,0),
  "SameGDocHOR" numeric(5,0),
  "DiffGDocHOR" numeric(5,0),
  "SameGDocSameGHyg" numeric(5,0),
  "SameGDocDiffGHyg" numeric(5,0),
  "SameGHyg" numeric(5,0),
  "DiffGHyg" numeric(5,0),
  "UseEnhancedCDA" numeric(5,0),
  "DiffGDocSameGHyg" numeric(5,0),
  "DiffGDocDiffGHyg" numeric(5,0),
  "DOREnhCDA" numeric(5,0),
  "SameGDocEnhCDA" numeric(5,0),
  "DiffGDocEnhCDA" numeric(5,0),
  CONSTRAINT schrule_primary PRIMARY KEY ("SchRule")
) ;
CREATE INDEX IF NOT EXISTS schrule_provider ON schrule USING btree ("ProdType", "Provider") TABLESPACE pg_default;
COMMENT ON TABLE schrule IS 'Scheduler rules';
COMMENT ON COLUMN schrule."UseEnhancedCDA" IS 'cutoff (in days) if special dental assistant is available';
COMMENT ON COLUMN schrule."SchRuleExpiry" IS 'max. wait time (in days) before rules expiry';
COMMENT ON COLUMN schrule."SchRule" IS 'sequence primary key';
COMMENT ON COLUMN schrule."SameGHyg" IS 'cutoff (in days) for same team hyg.';
COMMENT ON COLUMN schrule."SameGDocSameGHyg" IS 'cutoff (in days) for same team doc + hyg.';
COMMENT ON COLUMN schrule."SameGDocHOR" IS 'cutoff (in days) for same team doc + DHR.';
COMMENT ON COLUMN schrule."SameGDocEnhCDA" IS 'cutoff (in days) for same team doctor and Enh.CDA';
COMMENT ON COLUMN schrule."SameGDocDiffGHyg" IS 'cutoff (in days) for diff team doc + hyg.';
COMMENT ON COLUMN schrule."Provider" IS 'provider code';
COMMENT ON COLUMN schrule."ProdType" IS 'provider type';
COMMENT ON COLUMN schrule."MinSCGapTime" IS 'min. gap time (in minutes) for single chair day';
COMMENT ON COLUMN schrule."MaxProvSCFreeTime" IS 'max. contiguous free time for Prov. (in minutes)';
COMMENT ON COLUMN schrule."MaxProvMCFreeTime" IS 'max. contiguous free time for Prov. (in minutes)';
COMMENT ON COLUMN schrule."MaxApptMCTime" IS 'max. appt time (in minutes) for multi-chair day';
COMMENT ON COLUMN schrule."DiffGHyg" IS 'cutoff (in days) for diff team hyg.';
COMMENT ON COLUMN schrule."DiffGDocSameGHyg" IS 'cutoff (in days) for diff team doc and same team Hyg';
COMMENT ON COLUMN schrule."DiffGDocHOR" IS 'cutoff (in days) for diff team doc + DHR.';
COMMENT ON COLUMN schrule."DiffGDocEnhCDA" IS 'cutoff (in days) for diff team doctor and Enh.CDA';
COMMENT ON COLUMN schrule."DiffGDocDiffGHyg" IS 'cutoff (in days) for diff team doc and Hyg';
COMMENT ON COLUMN schrule."DORSameGHyg" IS 'cutoff (in days) for DOR + same team hyg.';
COMMENT ON COLUMN schrule."DOREnhCDA" IS 'cutoff (in days) for DOR and Enh.CDA';
COMMENT ON COLUMN schrule."DORDiffGHyg" IS 'cutoff (in days) for DOR + diff team hyg.';


CREATE  TABLE scratchp (
  "User" numeric(10,0) NOT NULL,
  text bytea,
  CONSTRAINT scratchp_primary PRIMARY KEY ("User")
) ;
COMMENT ON TABLE scratchp IS 'Scratchpad contents';
COMMENT ON COLUMN scratchp.text IS 'Contents of the scratchpad.';
COMMENT ON COLUMN scratchp."User" IS 'User that the scratchpad content belongs to, ptr to USERS.User';


CREATE  TABLE selected (
  "User" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0) NOT NULL,
  "Held" numeric(5,0),
  CONSTRAINT selected_primary PRIMARY KEY ("User", "Patient")
) ;
CREATE INDEX IF NOT EXISTS selected_patient ON selected USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE selected IS 'Selected patients, used by the Patients module';
COMMENT ON COLUMN selected."User" IS 'Primary key, ID of the user that selected the patient, ptr to USERS.User';
COMMENT ON COLUMN selected."Patient" IS 'Primary key, patient ID, ptr to PATIENT.Patient';
COMMENT ON COLUMN selected."Held" IS 'Record is to be held in the Patients module and not cleared by the overnight process. (0 = No, 1 = Yes)';


CREATE  TABLE service (
  "Code" character(6) NOT NULL,
  "Description" character(30),
  "IsNEIC" numeric(5,0),
  CONSTRAINT service_primary PRIMARY KEY ("Code")
) ;
COMMENT ON TABLE service IS 'Service Type Codes';
COMMENT ON COLUMN service."IsNEIC" IS 'IS NEIC? (0 = No, 1 = Yes)';
COMMENT ON COLUMN service."Description" IS 'Description of the service type';
COMMENT ON COLUMN service."Code" IS 'Primary key, ID code to identify the service type';


CREATE  TABLE setitem (
  "SetCode" character(6) NOT NULL,
  "StageCode" character(6) NOT NULL,
  "Order" numeric(10,0),
  CONSTRAINT setitem_primary PRIMARY KEY ("SetCode", "StageCode")
) ;
CREATE INDEX IF NOT EXISTS setitem_setitemorderkey ON setitem USING btree ("SetCode", "Order") TABLESPACE pg_default;
COMMENT ON TABLE setitem IS 'Ortho Set Item';
COMMENT ON COLUMN setitem."StageCode" IS 'Primary key component, stage that this item is part of. Ptr to STAGE.Code';
COMMENT ON COLUMN setitem."SetCode" IS 'Primary key component, ortho set that this item is part of. Ptr to ORTHOSET.Code';
COMMENT ON COLUMN setitem."Order" IS 'Order number for item';


CREATE  TABLE sitem (
  "Scheme" character(6) NOT NULL,
  "Grade" character(5) NOT NULL,
  "Description" character(30),
  "RequireComment" numeric(5,0),
  "OrderIdx" numeric(5,0),
  "RequiredLineComment" numeric(5,0),
  CONSTRAINT sitem_primary PRIMARY KEY ("Scheme", "Grade")
) ;
COMMENT ON TABLE sitem IS 'Grading scheme items, used to define grades, i.e: 1 = Poor, 2 = Good, 3 = Excellent';
COMMENT ON COLUMN sitem."Scheme" IS 'Primary key component, ID code of the scheme, ptr to SCHEME.Scheme';
COMMENT ON COLUMN sitem."RequiredLineComment" IS 'Does this grade require a comment or explanation? 0 = No, 1 = Yes ';
COMMENT ON COLUMN sitem."RequireComment" IS 'Requires a comment? (0 = No, 1 = Yes)';
COMMENT ON COLUMN sitem."OrderIdx" IS 'Number to indicate the postion of this item in the scheme. ';
COMMENT ON COLUMN sitem."Grade" IS 'Primary key component, acceptable grading value for the scheme';
COMMENT ON COLUMN sitem."Description" IS 'Description of the grading entry';


CREATE  TABLE slevel (
  "SLevel" numeric(10,0) NOT NULL,
  "Description" character varying(30),
  "Deleted" numeric(5,0),
  "GroupAccess" numeric(5,0),
  "PwdChangeDays" numeric(5,0),
  "SingleLogin" numeric(5,0),
  "IsPtRestrict" numeric(5,0),
  "Comment" character varying(4000),
  "MaskPatient" numeric(5,0) DEFAULT 0,
  "MaskGuarantor" numeric(5,0) DEFAULT 0,
  "MaskSubscriber" numeric(5,0) DEFAULT 0,
  "MaskOther" numeric(5,0) DEFAULT 0,
  CONSTRAINT slevel_primary PRIMARY KEY ("SLevel")
) ;
COMMENT ON TABLE slevel IS 'Security Levels';
COMMENT ON COLUMN slevel."SingleLogin" IS 'User is restricted to a single logged in session? (0=No, 1=Yes)';
COMMENT ON COLUMN slevel."SLevel" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN slevel."PwdChangeDays" IS 'Number of days between forced password changes. ';
COMMENT ON COLUMN slevel."MaskSubscriber" IS 'Mask Subscriber IDs? (0 = No, 1 = Yes).';
COMMENT ON COLUMN slevel."MaskPatient" IS 'Mask Patient IDs? (0 = No, 1 = Yes).';
COMMENT ON COLUMN slevel."MaskOther" IS 'Mask other IDs? (0 = No, 1 = Yes).';
COMMENT ON COLUMN slevel."MaskGuarantor" IS 'Mask Guarantor IDs? (0 = No, 1 = Yes).';
COMMENT ON COLUMN slevel."IsPtRestrict" IS 'Level is restricted to assigned patients? (0=No, 1=Yes)';
COMMENT ON COLUMN slevel."GroupAccess" IS 'If IsPtRestrict=1, only allow access to providers in group? (0=No, 1=Yes).';
COMMENT ON COLUMN slevel."Description" IS 'Description of the security level';
COMMENT ON COLUMN slevel."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN slevel."Comment" IS 'Comment for the security level.';


CREATE  TABLE slevrole (
  "SLevel" numeric(10,0) NOT NULL,
  "SRole" numeric(10,0) NOT NULL,
  "Audit" numeric(10,0),
  CONSTRAINT slevrole_primary PRIMARY KEY ("SLevel", "SRole")
) ;
CREATE INDEX IF NOT EXISTS slevrole_srolekey ON slevrole USING btree ("SRole") TABLESPACE pg_default;
COMMENT ON TABLE slevrole IS 'Table that joins an SLEVEL to one or more SROLEs';
COMMENT ON COLUMN slevrole."SRole" IS 'Primary key component, the security role contained in the level. Ptr to SROLE.SRole';
COMMENT ON COLUMN slevrole."SLevel" IS 'Primary key component, the security level that contains the role. Ptr to SLEVEL.SLevel';
COMMENT ON COLUMN slevrole."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE slevrolh (
  "SLevRolH" numeric(10,0) NOT NULL,
  "SLevel" numeric(10,0),
  "SRole" numeric(10,0),
  "Audit" numeric(10,0),
  CONSTRAINT slevrolh_primary PRIMARY KEY ("SLevRolH")
) ;
CREATE INDEX IF NOT EXISTS slevrolh_slevelkey ON slevrolh USING btree ("SLevel") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS slevrolh_srolekey ON slevrolh USING btree ("SRole") TABLESPACE pg_default;
COMMENT ON TABLE slevrolh IS 'History table for SLEVROLE';
COMMENT ON COLUMN slevrolh."SRole" IS 'The security role contained in the level. Ptr to SROLE.SRole';
COMMENT ON COLUMN slevrolh."SLevel" IS 'The security level that contains the role. Ptr to SLEVEL.SLevel';
COMMENT ON COLUMN slevrolh."SLevRolH" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN slevrolh."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE slraudit (
  "SLRAudit" numeric(10,0) NOT NULL,
  "SRole" numeric(10,0),
  "Audit" numeric(10,0),
  "Type" numeric(5,0),
  "IDNo" numeric(10,0),
  "IDDesc" character varying(200),
  "SubIDNo" numeric(10,0),
  "SubIDDesc" character varying(200),
  "OldVal" numeric(5,0),
  "NewVal" numeric(5,0),
  CONSTRAINT slraudit_primary PRIMARY KEY ("SLRAudit")
) ;
CREATE INDEX IF NOT EXISTS slraudit_iddesc ON slraudit USING btree ("IDDesc") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS slraudit_srole ON slraudit USING btree ("SRole") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS slraudit_type ON slraudit USING btree ("Type", "IDNo", "SubIDNo") TABLESPACE pg_default;
COMMENT ON TABLE slraudit IS 'Security Role Audit Information';
COMMENT ON COLUMN slraudit."Type" IS 'Type of control (0=Dialog, 1=Info Manager Table, 2=Info Manager Report, 3=Menu, 6=Main Program, 7=Other Access)';
COMMENT ON COLUMN slraudit."SubIDNo" IS 'ID of the subcontrol (Field ID, Menu Item ID, etc)';
COMMENT ON COLUMN slraudit."SubIDDesc" IS 'Name/description of the subcontrol. ';
COMMENT ON COLUMN slraudit."SRole" IS 'Security role, ptr to SROLE.Srole';
COMMENT ON COLUMN slraudit."SLRAudit" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN slraudit."OldVal" IS 'Previous rights to this control/subcontrol: (0=Hidden/Red, 1=Enabled/Green, 2=Disabled/Yellow)';
COMMENT ON COLUMN slraudit."NewVal" IS 'New rights to this control/subcontrol: (0=Hidden/Red, 1=Enabled/Green, 2=Disabled/Yellow)';
COMMENT ON COLUMN slraudit."IDNo" IS 'ID number of the control (Dialog ID, Menu ID, etc)';
COMMENT ON COLUMN slraudit."IDDesc" IS 'Name/description of the control. ';
COMMENT ON COLUMN slraudit."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE snocode (
  "SNOCode" character(18) NOT NULL,
  "Description" character varying(255),
  "EffectiveDate" timestamp without time zone,
  "Inactive" numeric(5,0),
  CONSTRAINT snocode_primary PRIMARY KEY ("SNOCode")
) ;
COMMENT ON TABLE snocode IS 'SNOMED Clinical Terms';
COMMENT ON COLUMN snocode."SNOCode" IS 'Primary key, code that identifies the SNOCode';
COMMENT ON COLUMN snocode."Inactive" IS 'SNOCode is inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN snocode."EffectiveDate" IS 'Date the SNOCode is in effect';
COMMENT ON COLUMN snocode."Description" IS 'Description of the SNOCode';


CREATE  TABLE snoicd9 (
  "SNOCode" character(18) NOT NULL,
  "ICD9Code" character(10) NOT NULL,
  "Inactive" numeric(5,0),
  CONSTRAINT snoicd9_primary PRIMARY KEY ("SNOCode", "ICD9Code")
) ;
COMMENT ON TABLE snoicd9 IS 'SNOMED Clinical Terms';
COMMENT ON COLUMN snoicd9."SNOCode" IS 'SNOCode code, ptr to SNOCODE.SNOCode';
COMMENT ON COLUMN snoicd9."Inactive" IS 'Is inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN snoicd9."ICD9Code" IS 'Code that identifies the ICD9 code';


CREATE  TABLE snosyn (
  "SNOCode" character(18) NOT NULL,
  "Synonym" character varying(255) NOT NULL,
  CONSTRAINT snosyn_primary PRIMARY KEY ("SNOCode", "Synonym")
) ;
COMMENT ON TABLE snosyn IS 'SNOMED Synonyms';
COMMENT ON COLUMN snosyn."Synonym" IS 'Primary key component, synonym term';
COMMENT ON COLUMN snosyn."SNOCode" IS 'Primary key component, ptr to SNOCODE.SNOCode';


CREATE  TABLE sreport (
  "SReport" numeric(10,0) NOT NULL,
  "ReportFile" character varying(30),
  "ReportName" character varying(255),
  "ReportLoc" character varying(255),
  "Country" numeric(5,0),
  content bytea,
  "Inactive" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT sreport_primary PRIMARY KEY ("SReport")
) ;
CREATE INDEX IF NOT EXISTS sreport_reportfile ON sreport USING btree ("ReportFile") TABLESPACE pg_default;
COMMENT ON TABLE sreport IS 'SReport Records';
COMMENT ON COLUMN sreport.content IS 'Report content (in Crystal Format)';
COMMENT ON COLUMN sreport."SReport" IS 'Primary key sequence field';
COMMENT ON COLUMN sreport."ReportName" IS 'Name of the report';
COMMENT ON COLUMN sreport."ReportLoc" IS 'Where to find the report';
COMMENT ON COLUMN sreport."ReportFile" IS 'Report file name';
COMMENT ON COLUMN sreport."Inactive" IS 'Flag to inactivate Standard Report: 0 - active, 1 - inactive';
COMMENT ON COLUMN sreport."Country" IS 'Country this report is applicable to (0-All, 1-Intl, 2-US, 3-Intl/US, 4-Dutch)';


CREATE  TABLE srole (
  "SRole" numeric(10,0) NOT NULL,
  "Description" character varying(30),
  "IsAdmin" numeric(5,0),
  "DefaultRights" numeric(5,0),
  "CanLogonAsUser" numeric(5,0),
  "IsRider" numeric(5,0),
  rights bytea,
  "Comment" character varying(4000),
  "Deleted" numeric(5,0),
  "PAdminAccess" numeric(5,0),
  CONSTRAINT srole_primary PRIMARY KEY ("SRole")
) ;
COMMENT ON TABLE srole IS 'Security Roles';
COMMENT ON COLUMN srole.rights IS 'Blob containing the security rights for the security role.';
COMMENT ON COLUMN srole."SRole" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN srole."PAdminAccess" IS 'Does this role have access to Power Admin? (0=No (default), 1=Yes)';
COMMENT ON COLUMN srole."IsRider" IS 'Obsolete';
COMMENT ON COLUMN srole."IsAdmin" IS 'Is this an Administrator role? (0=No, 1=Yes)';
COMMENT ON COLUMN srole."Description" IS 'Description of the security role.';
COMMENT ON COLUMN srole."Deleted" IS 'Is this role deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN srole."DefaultRights" IS 'Default access rights (0=full access - all green, 1= no access - all red)';
COMMENT ON COLUMN srole."Comment" IS 'Comment for the security role.';
COMMENT ON COLUMN srole."CanLogonAsUser" IS 'Can this user logon as another user? (0=No, 1=Yes)';


CREATE  TABLE stage (
  "Code" character(6) NOT NULL,
  "Description" character(30),
  "DefaultUnits" numeric(10,0),
  "HasAppoint" numeric(5,0),
  "DefaultMinutes" numeric(10,0),
  "BkgColor" numeric(10,0),
  CONSTRAINT stage_primary PRIMARY KEY ("Code")
) ;
COMMENT ON TABLE stage IS 'Ortho Stage Codes';
COMMENT ON COLUMN stage."HasAppoint" IS 'Is there appt for this stage? (0 = No, 1 = Yes)';
COMMENT ON COLUMN stage."Description" IS 'Description of the ortho stage.';
COMMENT ON COLUMN stage."DefaultUnits" IS 'Default number of units for stage appointments.';
COMMENT ON COLUMN stage."DefaultMinutes" IS 'Default length in minutes for stage appointments.';
COMMENT ON COLUMN stage."Code" IS 'Primary key, ID code to identify the ortho stage. ';
COMMENT ON COLUMN stage."BkgColor" IS 'Background colour for stage appointments, numeric representation of RGB value. ';


CREATE  TABLE stagetim (
  "Stage" character(6) NOT NULL,
  "ProvType" character(1) NOT NULL,
  "Minutes" numeric(10,0),
  CONSTRAINT stagetim_primary PRIMARY KEY ("Stage", "ProvType")
) ;
COMMENT ON TABLE stagetim IS 'Default Appointment Lengths for Stage Appointments';
COMMENT ON COLUMN stagetim."Stage" IS 'Primary key component, ortho stage for this record. Ptr to STAGE.Stage';
COMMENT ON COLUMN stagetim."ProvType" IS 'Primary key component, provider type that the default minutes applies to. Ptr to PRODTYPE.Code';
COMMENT ON COLUMN stagetim."Minutes" IS 'Default length in minutes for appointments with this stage and provider type. ';


CREATE  TABLE startchk (
  "StartChk" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "Appointment" numeric(10,0),
  "Provider" character(10),
  "AppUser" numeric(10,0),
  "Audit" numeric(10,0),
  CONSTRAINT startchk_primary PRIMARY KEY ("StartChk")
) ;
CREATE INDEX IF NOT EXISTS startchk_appointment ON startchk USING btree ("Appointment") TABLESPACE pg_default;
COMMENT ON TABLE startchk IS 'Record of start checks processed';
COMMENT ON COLUMN startchk."StartChk" IS 'Id code to identify the start check reecord, unique Id from sequence. ';
COMMENT ON COLUMN startchk."Provider" IS 'Provider who got a start check, can be the primary provider or assistant (APPOINT.Producer or APPOINT.Assistant)';
COMMENT ON COLUMN startchk."Patient" IS 'Id code of the patient this startcheck is for, (PATIENT.Patient)';
COMMENT ON COLUMN startchk."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN startchk."Appointment" IS 'Id code of the appointment for the start check (APPOINT.Appointment)';
COMMENT ON COLUMN startchk."AppUser" IS 'Id code of the approval user, (USERS.USER)';


CREATE  TABLE starttrx (
  "StartTrx" numeric(10,0) NOT NULL,
  "StartChk" numeric(10,0),
  "Type" numeric(5,0),
  "Id" numeric(10,0),
  "Treatment" numeric(5,0),
  "OrigRecNo" numeric(10,0),
  "Procedure" character(7),
  CONSTRAINT starttrx_primary PRIMARY KEY ("StartTrx")
) ;
CREATE INDEX IF NOT EXISTS starttrx_startchk ON starttrx USING btree ("StartChk") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS starttrx_trxkey ON starttrx USING btree ("Type", "Id", "Treatment") TABLESPACE pg_default;
COMMENT ON TABLE starttrx IS 'Support for multiple startchecks per appointment';
COMMENT ON COLUMN starttrx."Type" IS 'The TRX Type of the TRX';
COMMENT ON COLUMN starttrx."Treatment" IS 'The TRX treatment number of the TRX';
COMMENT ON COLUMN starttrx."StartTrx" IS 'Unique ID of Start TRX record';
COMMENT ON COLUMN starttrx."StartChk" IS 'StartChk ID that the StartTrx is associated with';
COMMENT ON COLUMN starttrx."Procedure" IS 'Procedure code of the TRX';
COMMENT ON COLUMN starttrx."OrigRecNo" IS 'The original record # of the TRX';
COMMENT ON COLUMN starttrx."Id" IS 'The TRX ID of the TRX';


CREATE  TABLE statement_history (
  "Id" numeric(10,0) NOT NULL DEFAULT 0,
  "Patient" numeric(10,0) NOT NULL DEFAULT 0,
  "StatementDateTime" timestamp without time zone,
  CONSTRAINT statement_history_pk PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE statement_history IS 'Table for storing the StatementDateTime for the creation of patient statements.';
COMMENT ON COLUMN statement_history."StatementDateTime" IS 'Date and time the patient statement was created';
COMMENT ON COLUMN statement_history."Patient" IS 'Patient Id, ptr to PATIENT.Patient.';
COMMENT ON COLUMN statement_history."Id" IS 'PK component, ptr to primary key of the table from a sequence.';


CREATE  TABLE statemnt (
  "Id" numeric(10,0) NOT NULL,
  "ItemId" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "Date" timestamp without time zone,
  "TrxType" numeric(5,0),
  "TrxId" numeric(10,0),
  "TrxTreatment" numeric(5,0),
  "PlanId" numeric(10,0),
  "PlanItem" numeric(10,0),
  "Amount" numeric,
  "Amount1" numeric,
  "Amount2" numeric,
  CONSTRAINT statemnt_primary PRIMARY KEY ("Id", "ItemId")
) ;
COMMENT ON TABLE statemnt IS 'Temporary table used for printing Statements and Receipts';
COMMENT ON COLUMN statemnt."TrxType" IS 'Transaction type, ptr to TRX.Type';
COMMENT ON COLUMN statemnt."TrxTreatment" IS 'Transaction line number, ptr to TRX.Treatment';
COMMENT ON COLUMN statemnt."TrxId" IS 'Transaction Id, ptr to TRX.Id';
COMMENT ON COLUMN statemnt."PlanItem" IS 'Payment plan item Id';
COMMENT ON COLUMN statemnt."PlanId" IS 'Payment plan Id';
COMMENT ON COLUMN statemnt."Patient" IS 'Patient ID, ptr to PATIENT.Patient';
COMMENT ON COLUMN statemnt."ItemId" IS 'Primary key, item number of line within Id';
COMMENT ON COLUMN statemnt."Id" IS 'Primary key, internal ID (from sequence)';
COMMENT ON COLUMN statemnt."Date" IS 'Item transaction date';
COMMENT ON COLUMN statemnt."Amount2" IS 'Internal field to be used by the program differently based on the situation ';
COMMENT ON COLUMN statemnt."Amount1" IS 'Internal field to be used by the program differently based on the situation ';
COMMENT ON COLUMN statemnt."Amount" IS 'Dollar ($) amount of the item';


CREATE  TABLE station (
  "StationId" numeric(10,0) NOT NULL,
  "RegDate" timestamp without time zone,
  "Terminal" character varying(128),
  "EnvVariable" character varying(128),
  "LastLogDate" timestamp without time zone,
  "Deleted" numeric(5,0),
  "Version" numeric(10,0),
  "Inactive" numeric(5,0),
  "BuildNumber" numeric(10,0),
  CONSTRAINT station_primary PRIMARY KEY ("StationId")
) ;
COMMENT ON TABLE station IS 'Workstation registration information';
COMMENT ON COLUMN station."Version" IS 'axiUm version installed on the station';
COMMENT ON COLUMN station."Terminal" IS 'Terminal identification';
COMMENT ON COLUMN station."StationId" IS 'Primary key, station Id, the code that identifies this station.';
COMMENT ON COLUMN station."RegDate" IS 'Date of registration';
COMMENT ON COLUMN station."LastLogDate" IS 'Date of last logged activity';
COMMENT ON COLUMN station."Inactive" IS ' 0 = No, 1 = Yes';
COMMENT ON COLUMN station."EnvVariable" IS 'Computer name';
COMMENT ON COLUMN station."Deleted" IS 'Is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN station."BuildNumber" IS 'axiUm build number installed on the station';


CREATE  TABLE status (
  "Type" numeric(5,0) NOT NULL,
  "Status" character(6) NOT NULL,
  "Description" character(30),
  "Default" numeric(5,0),
  "DefaultOther" numeric(5,0),
  "Submit" numeric(5,0),
  "Color" numeric(10,0),
  "MakeInactive" numeric(5,0),
  "BkgColor" numeric(10,0),
  "Inactive" numeric(5,0),
  "ReactivateRecall" numeric(5,0) NOT NULL DEFAULT 0,
  "Recall" character(6),
  "RecallStatus" character(6),
  "RecallType" character(6),
  "ArchiveRestore" numeric(5,0),
  CONSTRAINT status_primary PRIMARY KEY ("Type", "Status")
) ;
COMMENT ON TABLE status IS 'Status Codes';
COMMENT ON COLUMN status."Type" IS 'Primary key component, status code type (0=Account, 1=Appt, 2=Patient, 3=Treatment, 4=Recall, 5=Online Request)';
COMMENT ON COLUMN status."Submit" IS 'Dutch version only. If Type=3, then submit? (0=No, 1=Yes, 2=Held)';
COMMENT ON COLUMN status."Status" IS 'Primary key component, ID code to identify the status ';
COMMENT ON COLUMN status."RecallType" IS 'Recall type to use if patient is re-activated, ptr to RCTYPE.RecallType';
COMMENT ON COLUMN status."RecallStatus" IS 'Recall status to use if patient is re-activated, ptr to STATUS.Status';
COMMENT ON COLUMN status."Recall" IS 'Recall code to use if patient is re-activated, ptr to RECALL.Recall';
COMMENT ON COLUMN status."ReactivateRecall" IS 'Re-activate recall(s) automatically when patient is assigned this status. If patient does not have any recalls, create a new recall. (0=No, 1=Yes)';
COMMENT ON COLUMN status."MakeInactive" IS 'Are items with this status inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN status."Inactive" IS 'Is this status code inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN status."Description" IS 'Description of the status';
COMMENT ON COLUMN status."DefaultOther" IS 'Is default patient status for family member? (0=No, 1=Yes)';
COMMENT ON COLUMN status."Default" IS 'Default status for this Type? (0=No, 1=Yes)';
COMMENT ON COLUMN status."Color" IS 'Color, numeric representation of binary RGB values. ';
COMMENT ON COLUMN status."BkgColor" IS 'Appointment background color, numeric representation of binary RGB values. ';
COMMENT ON COLUMN status."ArchiveRestore" IS 'Mark status to be reserved for patients that are archived or restored (0=NA, 1=Archive, 2=Restore)';


CREATE  TABLE sterbat (
  "SterBat" numeric(10,0) NOT NULL,
  "Type" numeric(5,0),
  "DispCode" character(6),
  "BatchNumber" character varying(12),
  "ExpiryDate" timestamp without time zone,
  "Audit" numeric(10,0),
  CONSTRAINT sterbat_primary PRIMARY KEY ("SterBat")
) ;
COMMENT ON TABLE sterbat IS 'Sterilization batch records';
COMMENT ON COLUMN sterbat."Type" IS 'Type (0=Sterilized, 1=Verified)';
COMMENT ON COLUMN sterbat."SterBat" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN sterbat."ExpiryDate" IS ' If STERBAT.Type = 0, date that sterilization expires for batch';
COMMENT ON COLUMN sterbat."DispCode" IS 'Dispensary where sterilized from if STERBAT.Type = 1, or location scanned to if STERBAT.Type = 0, ptr to DISPCODE.Code ';
COMMENT ON COLUMN sterbat."BatchNumber" IS ' If STERBAT.Type = 1, the sterilization batch #';
COMMENT ON COLUMN sterbat."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE sterkit (
  "SterBat" numeric(10,0) NOT NULL,
  "Kit" character(30) NOT NULL,
  "OuterBarCode" character varying(30),
  "PostSterBat" numeric(10,0),
  CONSTRAINT sterkit_primary PRIMARY KEY ("SterBat", "Kit")
) ;
CREATE INDEX IF NOT EXISTS sterkit_kitkey ON sterkit USING btree ("Kit") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS sterkit_outerbarcodekey ON sterkit USING btree ("OuterBarCode") TABLESPACE pg_default;
COMMENT ON TABLE sterkit IS 'Kits that were sterilized in a given batch';
COMMENT ON COLUMN sterkit."SterBat" IS 'Primary key component, sterilization batch. Ptr to STERBAT.SterBat.';
COMMENT ON COLUMN sterkit."PostSterBat" IS 'Verification number for the sterilization';
COMMENT ON COLUMN sterkit."OuterBarCode" IS 'Outer barcode assigned to the kit';
COMMENT ON COLUMN sterkit."Kit" IS 'Primary key component, ID code of the kit that was sterilized. Ptr to KIT.Kit.';


CREATE  TABLE stmtjob (
  "Id" numeric(10,0) NOT NULL,
  "StatemntId" numeric(10,0) NOT NULL,
  "AcctName" character varying(128),
  "AcctAddress1" character varying(128),
  "AcctAddress2" character varying(128),
  "AcctAddress3" character varying(128),
  "AcctAddress4" character varying(128),
  "AcctChart" character varying(16),
  "FirstPatientName" character varying(128),
  "TrxPatientName" character varying(128),
  "PtTotal" numeric,
  "PtCurrent" numeric,
  "Pt30" numeric,
  "Pt60" numeric,
  "Pt90" numeric,
  "InsCurrent" numeric,
  "Ins30" numeric,
  "Ins60" numeric,
  "Ins90" numeric,
  "OpenBal" numeric,
  "AmountDue" numeric,
  "PlanOpenBal" numeric,
  "PlanDue" numeric,
  "NextFee" numeric,
  "NextFeeDate" character varying(100),
  "Dunning" character varying(128),
  "Policy1" numeric(10,0),
  "Policy2" numeric(10,0),
  "Policy3" numeric(10,0),
  "PrintInsAR" numeric(5,0),
  "Pt120" numeric,
  "Ins120" numeric,
  "AcctPatId" numeric(10,0),
  CONSTRAINT stmtjob_primary PRIMARY KEY ("Id", "StatemntId")
) ;
COMMENT ON TABLE stmtjob IS 'Temporary record of the Statement Job sent to print,  there are 1 or more STATEMNT records created for each STMTJOB record';
COMMENT ON COLUMN stmtjob."TrxPatientName" IS 'Name of the first patient with treatment on statement';
COMMENT ON COLUMN stmtjob."StatemntId" IS 'Id code of the statement, Ptr to STATEMNT.Id';
COMMENT ON COLUMN stmtjob."PtTotal" IS 'The amount of an overall balance due from the patient';
COMMENT ON COLUMN stmtjob."PtCurrent" IS 'The amount of a balance owing (90-120 days old) due from the patient';
COMMENT ON COLUMN stmtjob."Pt90" IS 'The amount of a balance owing (90-120 days old) due from the patient';
COMMENT ON COLUMN stmtjob."Pt60" IS 'The amount of a balance owing (60-90 days old) due from the patient';
COMMENT ON COLUMN stmtjob."Pt30" IS 'The amount of a balance owing (30-60 days old) due from the patient';
COMMENT ON COLUMN stmtjob."Pt120" IS 'The amount of a balance owing (greater than 120 days old) due from patient';
COMMENT ON COLUMN stmtjob."PrintInsAR" IS 'Print insurance AR? (0 = No, 1 = Yes)';
COMMENT ON COLUMN stmtjob."Policy3" IS 'Id code of the third policy';
COMMENT ON COLUMN stmtjob."Policy2" IS 'Id code of thesecondary policy';
COMMENT ON COLUMN stmtjob."Policy1" IS 'Id code of the primary policy';
COMMENT ON COLUMN stmtjob."PlanOpenBal" IS 'Opening Balance for the payment plan (previous plan balance)';
COMMENT ON COLUMN stmtjob."PlanDue" IS 'The total (remaining) amount due on payment plan';
COMMENT ON COLUMN stmtjob."OpenBal" IS 'Opening Balance for Statement (Previous Balance)';
COMMENT ON COLUMN stmtjob."NextFeeDate" IS 'Date the next fee is due on payment plan';
COMMENT ON COLUMN stmtjob."NextFee" IS 'The amount of the next fee due on payment plan';
COMMENT ON COLUMN stmtjob."InsCurrent" IS 'The amount of a balance owing (less than 30 days old) due from insurance';
COMMENT ON COLUMN stmtjob."Ins90" IS 'The amount of a balance owing (90-120 days old) due from insurance';
COMMENT ON COLUMN stmtjob."Ins60" IS 'The amount of a balance owing (60-90 days old) due from insurance';
COMMENT ON COLUMN stmtjob."Ins30" IS 'The amount of a balance owing (30-60 days old) due from insurance';
COMMENT ON COLUMN stmtjob."Ins120" IS 'The amount of a balance owing (greater than 120 days old) due from insurance';
COMMENT ON COLUMN stmtjob."Id" IS 'Id code of the statement job';
COMMENT ON COLUMN stmtjob."FirstPatientName" IS 'Name of the first patient for this statement';
COMMENT ON COLUMN stmtjob."Dunning" IS 'Dunning message to print on the statement';
COMMENT ON COLUMN stmtjob."AmountDue" IS 'The total amount due from patient and insurance combined';
COMMENT ON COLUMN stmtjob."AcctPatId" IS 'Used to place either the patient or guarantor. ptr to PATIENT.Patient';
COMMENT ON COLUMN stmtjob."AcctName" IS 'Full name of the Patient this statement is issued for';
COMMENT ON COLUMN stmtjob."AcctChart" IS 'Chart number of the patient ';
COMMENT ON COLUMN stmtjob."AcctAddress4" IS 'Address Line 4 of the patient this statement is issued for';
COMMENT ON COLUMN stmtjob."AcctAddress3" IS 'Address Line 3 of the patient this statement is issued for';
COMMENT ON COLUMN stmtjob."AcctAddress2" IS 'Address Line 2 of the patient this statement is issued for';
COMMENT ON COLUMN stmtjob."AcctAddress1" IS 'Address Line 1 of the patient this statement is issued for';


CREATE  TABLE stnclexc (
  "StationId" numeric(10,0) NOT NULL,
  "Clinic" numeric(10,0) NOT NULL,
  "SignInMsg" character varying(255),
  CONSTRAINT stnclexc_primary PRIMARY KEY ("StationId", "Clinic")
) ;
COMMENT ON TABLE stnclexc IS 'Kiosk Restricted sign-in by Clinic';
COMMENT ON COLUMN stnclexc."StationId" IS 'Primary key, ptr to STATION.StationId, station ID of the kiosk';
COMMENT ON COLUMN stnclexc."SignInMsg" IS 'Message or instructions to display when a patient attempts to sign to this Clinic from this kiosk Station.';
COMMENT ON COLUMN stnclexc."Clinic" IS 'Primary key, ptr to CLINIC.Clinic ';


CREATE  TABLE stngrp (
  "StnGrp" character(6) NOT NULL,
  "Description" character varying(30),
  "Inactive" numeric(5,0),
  CONSTRAINT stngrp_primary PRIMARY KEY ("StnGrp")
) ;
COMMENT ON TABLE stngrp IS 'New table for defining (sub)sets of stations for aiding in setting the various INI entries';
COMMENT ON COLUMN stngrp."StnGrp" IS 'Id code to identify the group of stations ';
COMMENT ON COLUMN stngrp."Inactive" IS 'Code is inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN stngrp."Description" IS 'Description or the name of the station group';


CREATE  TABLE stngrpit (
  "StnGrp" character(6) NOT NULL,
  "Station" numeric(10,0) NOT NULL,
  CONSTRAINT stngrpit_primary PRIMARY KEY ("StnGrp", "Station")
) ;
COMMENT ON TABLE stngrpit IS 'New table for defining station group(s) a station belongs to (usually 1)';
COMMENT ON COLUMN stngrpit."StnGrp" IS 'STNGRP.StnGrp station belongs to';
COMMENT ON COLUMN stngrpit."Station" IS 'Id code of the station, copy of STATION.StationId';


CREATE  TABLE sublist (
  "Procedure" character(7) NOT NULL,
  "SubProcedure" character(7) NOT NULL,
  CONSTRAINT sublist_primary PRIMARY KEY ("Procedure", "SubProcedure")
) ;
COMMENT ON TABLE sublist IS 'Relation of lab codes to treatment codes';
COMMENT ON COLUMN sublist."SubProcedure" IS 'Lab procedure code';
COMMENT ON COLUMN sublist."Procedure" IS 'Treatment procedure code';


CREATE  TABLE summcode (
  "SummCode" character(6) NOT NULL,
  "Type" numeric(5,0),
  "Description" character varying(30),
  "Value1Desc" character varying(30),
  "Value2Desc" character varying(30),
  "AllowOverride" numeric(5,0),
  "ShowInAlerts" numeric(5,0),
  "Inactive" numeric(5,0),
  CONSTRAINT summcode_primary PRIMARY KEY ("SummCode")
) ;
COMMENT ON TABLE summcode IS 'Patient Summary Codes ';
COMMENT ON COLUMN summcode."Value2Desc" IS 'Description of Value2 (shown in override dialog)';
COMMENT ON COLUMN summcode."Value1Desc" IS 'Description of Value1 (shown in override dialog)';
COMMENT ON COLUMN summcode."Type" IS '0=Other, 1=Caries, 2=Periodontitis';
COMMENT ON COLUMN summcode."SummCode" IS 'Primary Key';
COMMENT ON COLUMN summcode."ShowInAlerts" IS '0=Don’t show in Alerts, 1=Show in Alerts';
COMMENT ON COLUMN summcode."Inactive" IS 'Make Inactive? (0=active, 1=inactive)';
COMMENT ON COLUMN summcode."Description" IS 'Description of code';
COMMENT ON COLUMN summcode."AllowOverride" IS '0=No override, 1=Allows user override';


CREATE  TABLE sundry (
  "Sundry" character(6) NOT NULL,
  "Description" character(30),
  "BarCode" character(30),
  "HasLimit" numeric(5,0),
  "MaxOut" numeric(10,0),
  "Level" numeric(5,0),
  "IsLeaf" numeric(5,0),
  "Deleted" numeric(5,0),
  "Id" numeric(10,0) NOT NULL,
  "Disposable" numeric(5,0),
  "Inactive" numeric(5,0),
  "Amount" numeric,
  CONSTRAINT sundry_primary PRIMARY KEY ("Sundry")
) ;
CREATE INDEX IF NOT EXISTS sundry_id ON sundry USING btree ("Id") TABLESPACE pg_default;
COMMENT ON TABLE sundry IS 'Record of all Sundry items';
COMMENT ON COLUMN sundry."Sundry" IS 'ID Code to identify the sundry item';
COMMENT ON COLUMN sundry."MaxOut" IS 'Maximum number of this item that a provider can have out at one time.';
COMMENT ON COLUMN sundry."Level" IS 'Node Level ( 0 = Level1, 1 = Level 2, 2 = Level 3)';
COMMENT ON COLUMN sundry."IsLeaf" IS 'Is this a Sundry/(not a header)? (0 = No, 1 = Yes)';
COMMENT ON COLUMN sundry."Inactive" IS 'Make Inactive? (0=active, 1=inactive)';
COMMENT ON COLUMN sundry."Id" IS 'Id Code of the sundry item (internal ID from sequence)';
COMMENT ON COLUMN sundry."HasLimit" IS 'Item has a limit? (0 = No, 1 = Yes)';
COMMENT ON COLUMN sundry."Disposable" IS 'Disposable item? (0 = No, 1 = Yes)';
COMMENT ON COLUMN sundry."Description" IS 'Description of the sundry item';
COMMENT ON COLUMN sundry."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN sundry."BarCode" IS 'BarCode to identify the sundry item';
COMMENT ON COLUMN sundry."Amount" IS 'Replacement cost of the sundry item, in dollars.';


CREATE  TABLE supplmnt (
  "Supplement" character(6) NOT NULL,
  "Description" character(30),
  CONSTRAINT supplmnt_primary PRIMARY KEY ("Supplement")
) ;
COMMENT ON TABLE supplmnt IS 'Lab supplement details';
COMMENT ON COLUMN supplmnt."Supplement" IS 'Primary key, Id code to identify the supplement';
COMMENT ON COLUMN supplmnt."Description" IS 'Description of the supplement';


CREATE  TABLE surcode2 (
  "Auto" numeric(10,0) NOT NULL,
  "Code" character(5),
  "Description" character(25),
  "Signature" numeric(5,0),
  CONSTRAINT surcode2_primary PRIMARY KEY ("Auto")
) ;
CREATE INDEX IF NOT EXISTS "SURCODE2_Code" ON surcode2 USING btree ("Code") TABLESPACE pg_default;
COMMENT ON TABLE surcode2 IS 'Survey Codes';
COMMENT ON COLUMN surcode2."Signature" IS 'Signatures (Patient, Student, Instructor) required for this survey. Numeric representation of binary string.';
COMMENT ON COLUMN surcode2."Description" IS 'Name / description of the survey code';
COMMENT ON COLUMN surcode2."Code" IS 'ID code to identify the survey code';
COMMENT ON COLUMN surcode2."Auto" IS 'Primary key, internal ID from sequence. ';


CREATE  TABLE survey2 (
  "Auto" numeric(10,0) NOT NULL,
  "Category" numeric(10,0),
  "TopicId" numeric(10,0),
  "QuestIndex" numeric(10,0),
  "Type" numeric(10,0),
  "Status" numeric(10,0),
  "Text" character(127),
  CONSTRAINT survey2_primary PRIMARY KEY ("Auto")
) ;
CREATE INDEX IF NOT EXISTS "SURVEY2_Category" ON survey2 USING btree ("Category", "TopicId", "QuestIndex") TABLESPACE pg_default;
COMMENT ON TABLE survey2 IS 'Survey Questions';
COMMENT ON COLUMN survey2."Type" IS 'Answer type (0=Yes/No, 1=Text)';
COMMENT ON COLUMN survey2."TopicId" IS 'Section of survey, split by topic lines (starting with 0)';
COMMENT ON COLUMN survey2."Text" IS 'Question/topic text';
COMMENT ON COLUMN survey2."Status" IS 'Is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN survey2."QuestIndex" IS 'Within a section, the line number (topic is 0, questions start with 1)';
COMMENT ON COLUMN survey2."Category" IS 'Survey that question belongs to, ptr to SURCODE2.Auto';
COMMENT ON COLUMN survey2."Auto" IS 'Primary key, internal ID from sequence. ';


CREATE  TABLE swipe (
  "Id" numeric(10,0) NOT NULL,
  "NoOfTracks" numeric(5,0),
  "UserIDTrack" numeric(5,0),
  "UserIDStart" numeric(5,0),
  "UserIDEnd" numeric(5,0),
  "PasswordTrack" numeric(5,0),
  "PasswordStart" numeric(5,0),
  "PasswordEnd" numeric(5,0),
  "EffectiveDateTrack" numeric(5,0),
  "EffectiveDateStart" numeric(5,0),
  "EffectiveDateEnd" numeric(5,0),
  "ExpiryDateTrack" numeric(5,0),
  "ExpiryDateStart" numeric(5,0),
  "ExpiryDateEnd" numeric(5,0),
  "DisciplineTrack" numeric(5,0),
  "DisciplineStart" numeric(5,0),
  "DisciplineEnd" numeric(5,0),
  CONSTRAINT swipe_primary PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE swipe IS 'Magnetic Swipe Card Settings, used for reading information from swipe card input.';
COMMENT ON COLUMN swipe."UserIDTrack" IS 'Track with User Login Id';
COMMENT ON COLUMN swipe."UserIDStart" IS 'Starting position of User Login Id';
COMMENT ON COLUMN swipe."UserIDEnd" IS 'Ending position of User Login Id';
COMMENT ON COLUMN swipe."PasswordTrack" IS 'Track with User Password';
COMMENT ON COLUMN swipe."PasswordStart" IS 'Starting position of User Password';
COMMENT ON COLUMN swipe."PasswordEnd" IS 'Ending position of User Password';
COMMENT ON COLUMN swipe."NoOfTracks" IS 'Number of tracks to read';
COMMENT ON COLUMN swipe."Id" IS 'Primary key, Internal ID (from sequence)';
COMMENT ON COLUMN swipe."ExpiryDateTrack" IS 'Track with Access Expiry Date';
COMMENT ON COLUMN swipe."ExpiryDateStart" IS 'Starting position of Access Expiry Date';
COMMENT ON COLUMN swipe."ExpiryDateEnd" IS 'Ending position of Access Expiry Date';
COMMENT ON COLUMN swipe."EffectiveDateTrack" IS 'Track with Effective Date';
COMMENT ON COLUMN swipe."EffectiveDateStart" IS 'Starting position of Effective Date';
COMMENT ON COLUMN swipe."EffectiveDateEnd" IS 'Ending position of Effective Date';
COMMENT ON COLUMN swipe."DisciplineTrack" IS 'Track with Discipline';
COMMENT ON COLUMN swipe."DisciplineStart" IS 'Starting position of Discipline';
COMMENT ON COLUMN swipe."DisciplineEnd" IS 'Ending position of Discipline';


CREATE  TABLE symbol (
  "Symbol" character(6) NOT NULL,
  "Description" character(30),
  "Filename" character varying(255),
  "MirrorToSide" numeric(5,0),
  "MirrorToLower" numeric(5,0),
  "ShowDental" numeric(5,0),
  "ShowPerio" numeric(5,0),
  content bytea,
  CONSTRAINT symbol_primary PRIMARY KEY ("Symbol")
) ;
COMMENT ON TABLE symbol IS 'Clinical Symbol Codes';
COMMENT ON COLUMN symbol.content IS 'BLOB that contains the image data, created from the image file specified in the Filename field.';
COMMENT ON COLUMN symbol."Symbol" IS 'Primary key, ID code to identify the symbol.';
COMMENT ON COLUMN symbol."ShowPerio" IS 'Display in Perio chart? (0=No, 1=Yes) ';
COMMENT ON COLUMN symbol."ShowDental" IS 'Display in Dental chart? (0=No, 1=Yes) ';
COMMENT ON COLUMN symbol."MirrorToSide" IS 'Mirror on opposite quadrant? (0=No, 1=Yes)';
COMMENT ON COLUMN symbol."MirrorToLower" IS 'Mirror on lower arch? (0=No, 1=Yes)';
COMMENT ON COLUMN symbol."Filename" IS 'UNC path to the image file. This is the original path that was used to populate the Content field blob - it is not used every time the symbol is displayed. ';
COMMENT ON COLUMN symbol."Description" IS 'Description of the symbol.';


CREATE  TABLE sysblob (
  "Id" numeric(10,0) NOT NULL,
  "Type" numeric(5,0),
  "Name" character varying(255),
  content bytea,
  CONSTRAINT sysblob_primary PRIMARY KEY ("Id")
) ;
CREATE INDEX IF NOT EXISTS sysblob_typenamekey ON sysblob USING btree ("Type", "Name") TABLESPACE pg_default;
COMMENT ON TABLE sysblob IS 'System-level BLOBs';
COMMENT ON COLUMN sysblob.content IS 'Any data';
COMMENT ON COLUMN sysblob."Type" IS 'Record type (1 - image as base64)';
COMMENT ON COLUMN sysblob."Name" IS 'Unique Name for the Type';
COMMENT ON COLUMN sysblob."Id" IS 'Primary key, internal ID from sequence.';


CREATE  TABLE sysopts (
  "Name" character varying(255) NOT NULL,
  "Value" character varying(1000),
  "Type" numeric(5,0) NOT NULL,
  "Description" character varying(1000),
  CONSTRAINT sysopts_primary PRIMARY KEY ("Name")
) ;
COMMENT ON TABLE sysopts IS 'System options.';
COMMENT ON COLUMN sysopts."Value" IS 'Value of the system option.';
COMMENT ON COLUMN sysopts."Type" IS 'Type of the system option (0 = String, 1 = Int, 2 = Double, 3 = Date, 4 = Long).';
COMMENT ON COLUMN sysopts."Name" IS 'Name of the system option.';
COMMENT ON COLUMN sysopts."Description" IS 'Description of the system option.';


CREATE  TABLE table_of_dates (
  oneday timestamp without time zone
) ;
CREATE UNIQUE INDEX IF NOT EXISTS table_of_dates_pk ON table_of_dates USING btree (oneday) TABLESPACE pg_default;
COMMENT ON TABLE table_of_dates IS 'Table used by TRX_ASAT view that contains all dates that can be used by the TRX/HISTORY table';
COMMENT ON COLUMN table_of_dates.oneday IS 'A date that can be used in TRX/HISTORY.';


CREATE  TABLE tcunlock (
  "TCUnlock" numeric(10,0) NOT NULL,
  "User" numeric(10,0),
  "Patient" numeric(10,0),
  "Expires" timestamp without time zone,
  "AppUser" numeric(10,0),
  "Audit" numeric(10,0),
  CONSTRAINT tcunlock_primary PRIMARY KEY ("TCUnlock")
) ;
CREATE INDEX IF NOT EXISTS tcunlock_userpatientkey ON tcunlock USING btree ("User", "Patient", "Expires") TABLESPACE pg_default;
COMMENT ON TABLE tcunlock IS 'Table Used for temporary chart unlocks';
COMMENT ON COLUMN tcunlock."User" IS 'User Id that the unlock belongs to, ptr to USERS.User';
COMMENT ON COLUMN tcunlock."TCUnlock" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN tcunlock."Patient" IS 'Patient Id that the unlock is for, ptr to PATIENT.Patient';
COMMENT ON COLUMN tcunlock."Expires" IS 'DateTime that the unlock expires';
COMMENT ON COLUMN tcunlock."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN tcunlock."AppUser" IS 'Approval user of the unlock, ptr to USERS.User';


CREATE  TABLE tempappt (
  "ExpertId" numeric(10,0) NOT NULL,
  "RowId" numeric(10,0) NOT NULL,
  "ApptNum" numeric(10,0) NOT NULL,
  "Reserve" numeric(10,0) NOT NULL,
  "StartTime" numeric(10,0) NOT NULL,
  "EndTime" numeric(10,0),
  "Provider" character(10),
  "Assistant" character(10),
  "SearchType" numeric(5,0),
  CONSTRAINT tempappt_primary PRIMARY KEY ("ExpertId", "RowId", "ApptNum", "Reserve", "StartTime")
) ;
COMMENT ON TABLE tempappt IS 'Temporary table used by Appointment Expert to create appointment records';
COMMENT ON COLUMN tempappt."StartTime" IS 'Start time for temp appt (in minutes from midnight)';
COMMENT ON COLUMN tempappt."SearchType" IS '0=new patient exam, 1=hygiene recall, 2=other';
COMMENT ON COLUMN tempappt."RowId" IS 'Row number in list';
COMMENT ON COLUMN tempappt."Reserve" IS 'Reserve record found, ptr to RESERVE.Reserve';
COMMENT ON COLUMN tempappt."Provider" IS 'Provider Code';
COMMENT ON COLUMN tempappt."ExpertId" IS 'Appt expert session id, auto-assigned sequence';
COMMENT ON COLUMN tempappt."EndTime" IS 'End time for temp appt (in minutes from midnight)';
COMMENT ON COLUMN tempappt."Assistant" IS '2nd Provider Code';
COMMENT ON COLUMN tempappt."ApptNum" IS 'Appt number within session';


CREATE  TABLE templacc (
  "Template" character(6) NOT NULL,
  "SLevel" numeric(10,0) NOT NULL,
  "Access" numeric(5,0),
  CONSTRAINT templacc_primary PRIMARY KEY ("Template", "SLevel")
) ;
COMMENT ON TABLE templacc IS 'Template Access';
COMMENT ON COLUMN templacc."Template" IS 'Primary key, ptr. to TEMPLATE.Template';
COMMENT ON COLUMN templacc."SLevel" IS 'Primary key, ptr. to SLEVEL.Slevel';
COMMENT ON COLUMN templacc."Access" IS 'Access (0=Read only, 1=Full access)';


CREATE  TABLE template (
  "Template" character(6) NOT NULL,
  "Description" character(30),
  "IsDefaultPeriodic" numeric(5,0),
  "NoOfSwipes" numeric(5,0),
  "Import" character(10),
  "Qualifier" numeric(5,0),
  "IsExam" numeric(5,0),
  "InActive" numeric(5,0),
  "NoOfInstructors" numeric(5,0),
  "Type" numeric(5,0),
  "IsDefaultSessional" numeric(5,0),
  "Incomplete" numeric(5,0),
  "SelfEval" numeric(5,0),
  "CanContinue" numeric(5,0),
  "OnlyEvalDisplayedTx" numeric(5,0),
  CONSTRAINT template_primary PRIMARY KEY ("Template")
) ;
COMMENT ON TABLE template IS 'Grading / Evaluation Form Templates';
COMMENT ON COLUMN template."Type" IS 'Value to indicate type. If sessional grading is used Type = 1 where IsExam and IsDefaultPeriodic = 0. If periodic grading is used, Type = 2 where IsExam =0';
COMMENT ON COLUMN template."Template" IS 'Primary key, ID code of the template';
COMMENT ON COLUMN template."SelfEval" IS 'Is this a self evaluation? (0 = No, 1 = Yes, 2 = Yes - one copy of form is for self evaluation)';
COMMENT ON COLUMN template."Qualifier" IS 'Is a qualifying exam for competency? (0 = No, 1 = Yes)';
COMMENT ON COLUMN template."OnlyEvalDisplayedTx" IS 'Are treatments not displayed on the grade form (i.e. no tx-specific questions for them) considered unevaluated? (0=No, TRXGRADE rows will be created, 1=Yes, TRXGRADE rows will not be created). ';
COMMENT ON COLUMN template."NoOfSwipes" IS 'Number of swipes to accept grades given [1..3]';
COMMENT ON COLUMN template."NoOfInstructors" IS 'Number of instructors required to perform grading on this template';
COMMENT ON COLUMN template."IsExam" IS 'Is a written exam? (0 = No, 1 = Yes)';
COMMENT ON COLUMN template."IsDefaultSessional" IS 'Is this template the default for Sessional evaluations? (0 = No, 1 = Yes)';
COMMENT ON COLUMN template."IsDefaultPeriodic" IS 'Is this template the default for Periodic evaluations? (0 = No, 1 = Yes)';
COMMENT ON COLUMN template."Incomplete" IS 'If Type=1 (Sessional grading), can evaluations using this template be held? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN template."InActive" IS 'Template is inactive (will not appear in Student Evaluation Manager)? (0 = No, 1 = Yes)';
COMMENT ON COLUMN template."Import" IS 'Import code for Exan import';
COMMENT ON COLUMN template."Description" IS 'Description of the template';
COMMENT ON COLUMN template."CanContinue" IS 'If Type=1 (Sessional grading), are treatments on evaluations using this template cumulative? (0 = No, 1 = Yes) ';


CREATE  TABLE textmsgaudit (
  "Id" numeric(10,0) NOT NULL DEFAULT 0,
  "CreateDateTime" timestamp without time zone,
  "PhoneNumber" character varying(20),
  "Patient" numeric(10,0) NOT NULL DEFAULT 0,
  "Type" numeric(5,0) NOT NULL DEFAULT 0,
  "Content" character varying(4000),
  "SendDateTime" timestamp without time zone,
  "Status" character varying(255),
  "ErrorInfo" character varying(255),
  CONSTRAINT textmsgaudit_pk PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE textmsgaudit IS 'Audit table for logging text messaging usages.';
COMMENT ON COLUMN textmsgaudit."Type" IS 'Reason for the text message: 1 - Registration; 2 - Password Reset; 3 - Login; 4 - MFA; 5 - Recover Username.';
COMMENT ON COLUMN textmsgaudit."Status" IS 'Status of the text message.';
COMMENT ON COLUMN textmsgaudit."SendDateTime" IS 'The date/time the text message was sent.';
COMMENT ON COLUMN textmsgaudit."PhoneNumber" IS 'Phone Number to send text message to.';
COMMENT ON COLUMN textmsgaudit."Patient" IS 'Patient Id, ptr to Patient.Patient.';
COMMENT ON COLUMN textmsgaudit."Id" IS 'PK component, ptr to primary key of the table from a sequence.';
COMMENT ON COLUMN textmsgaudit."ErrorInfo" IS 'Error code / message (if applicable).';
COMMENT ON COLUMN textmsgaudit."CreateDateTime" IS 'The date/time the text message was created.';
COMMENT ON COLUMN textmsgaudit."Content" IS 'Text message content.';


CREATE  TABLE titem (
  "Item" numeric(10,0) NOT NULL,
  "Template" character(6),
  "Question" character(6),
  "QuestionText" character(40),
  "Row" numeric(10,0),
  "TrxSpecific" numeric(5,0),
  "Marking" numeric(5,0),
  "Scheme" character(6),
  "IsHeading" numeric(5,0),
  "IsRequired" numeric(5,0),
  "IsLimited" numeric(5,0),
  instruction clob,
  CONSTRAINT titem_primary PRIMARY KEY ("Item")
) ;
CREATE INDEX IF NOT EXISTS titem_templateitemkey ON titem USING btree ("Template", "Item") TABLESPACE pg_default;
COMMENT ON TABLE titem IS 'Grading / Evaluation Form Template Items';
COMMENT ON COLUMN titem.instruction IS 'Instructions to display on the grading window as a prompt to the instructor';
COMMENT ON COLUMN titem."TrxSpecific" IS 'Is this item treatment specific? (0 = No, 1 = Yes)';
COMMENT ON COLUMN titem."Template" IS 'ID code of the template that includes this item, ptr to TEMPLATE.Template';
COMMENT ON COLUMN titem."Scheme" IS 'Grading scheme, ptr to SCHEME.Scheme';
COMMENT ON COLUMN titem."Row" IS 'Row ID of the grading item within the template';
COMMENT ON COLUMN titem."QuestionText" IS 'Text of the question';
COMMENT ON COLUMN titem."Question" IS 'Question code, ptr to QUESTION.Question';
COMMENT ON COLUMN titem."Marking" IS 'Grade type (0=Numeric, 1=Letter, 2=Percentage)';
COMMENT ON COLUMN titem."Item" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN titem."IsRequired" IS 'Is this item required? (0 = No, 1= Yes)';
COMMENT ON COLUMN titem."IsLimited" IS 'Question is limited to specific procedures? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN titem."IsHeading" IS 'Is this item a heading? (1=Heading, 2=Question)';


CREATE  TABLE titempr (
  "TItemPr" numeric(10,0) NOT NULL,
  "Item" numeric(10,0),
  "ProcFrom" character(7),
  "ProcTo" character(7),
  CONSTRAINT titempr_primary PRIMARY KEY ("TItemPr")
) ;
COMMENT ON TABLE titempr IS 'Procedure codes that trigger trx specific questions in grading';
COMMENT ON COLUMN titempr."TItemPr" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN titempr."ProcTo" IS 'The ending procedure in the range, ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN titempr."ProcFrom" IS 'The beginning procedure in the range, ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN titempr."Item" IS 'Template item that this procedure code range is for, ptr to TITEM.Item';


CREATE  TABLE title (
  "Title" character(15) NOT NULL,
  "DefaultSex" numeric(5,0),
  CONSTRAINT title_primary PRIMARY KEY ("Title")
) ;
COMMENT ON TABLE title IS 'Title codes used for names. ie: Sir, Mr., Mrs.';
COMMENT ON COLUMN title."Title" IS 'Primary key, title ie: Sir, Mr., Mrs.';
COMMENT ON COLUMN title."DefaultSex" IS 'Default gender (0=Unknown, 1=Male, 2=Female, 3=Transgender, 4=Gender X, 5=Other)';


CREATE  TABLE tjfeesch (
  "TrojanId" character(7) NOT NULL,
  "FeeCode" character varying(5) NOT NULL,
  "Amount" numeric(10,0),
  "CovFlag" numeric(5,0),
  "Category" character(1),
  "Deleted" numeric(5,0),
  CONSTRAINT tjfeesch_primary PRIMARY KEY ("TrojanId", "FeeCode")
) ;
COMMENT ON TABLE tjfeesch IS 'FOR INTERNAL USE ONLY - DO NOT ALTER. Trojan fee schedule (fee schedule look-up)';
COMMENT ON COLUMN tjfeesch."TrojanId" IS 'Trojan ID / Employer #';
COMMENT ON COLUMN tjfeesch."FeeCode" IS 'Fee code';
COMMENT ON COLUMN tjfeesch."Deleted" IS 'Is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN tjfeesch."CovFlag" IS 'Coverage flag (0 = Ok, 1=N/A, 2=By Report, 3=Not covered, 4=UCR)';
COMMENT ON COLUMN tjfeesch."Category" IS 'Category (P= Preventive, B= Basic, M=Major)';
COMMENT ON COLUMN tjfeesch."Amount" IS 'Fee Amount';


CREATE  TABLE tjflag (
  "Type" numeric(5,0) NOT NULL,
  "Code" character(1) NOT NULL,
  "Description" character varying(60),
  "Handled" numeric(5,0),
  CONSTRAINT tjflag_primary PRIMARY KEY ("Type", "Code")
) ;
COMMENT ON TABLE tjflag IS 'FOR INTERNAL USE ONLY - DO NOT ALTER Trojan code fields lookup ';
COMMENT ON COLUMN tjflag."Type" IS 'Trojan flag type';
COMMENT ON COLUMN tjflag."Handled" IS 'Flag not handled internally? (0=default, 1=not handled), if not handled the text of the flag in the policy record will be red';
COMMENT ON COLUMN tjflag."Description" IS 'Trojan flag description';
COMMENT ON COLUMN tjflag."Code" IS 'Trojan flag code';


CREATE  TABLE tjfschh (
  "TrojanId" character(7) NOT NULL,
  "FeeCode" character varying(5) NOT NULL,
  "Amount" numeric(10,0),
  "CovFlag" numeric(5,0),
  "Category" character(1),
  "Deleted" numeric(5,0),
  "ExpiredDate" timestamp without time zone NOT NULL,
  CONSTRAINT tjfschh_primary PRIMARY KEY ("TrojanId", "FeeCode", "ExpiredDate")
) ;
COMMENT ON TABLE tjfschh IS 'FOR INTERNAL USE ONLY - DO NOT ALTER - Audit history for the TJFEESCH table';
COMMENT ON COLUMN tjfschh."TrojanId" IS 'Trojan ID / Employer #, ptr to TJFEESCH.TrojanId';
COMMENT ON COLUMN tjfschh."FeeCode" IS 'Fee code, ptr to TJFEESCH.FeeCode';
COMMENT ON COLUMN tjfschh."ExpiredDate" IS 'Date of expiry, ptr to TJFEESCH.ExpiredDate';
COMMENT ON COLUMN tjfschh."Deleted" IS 'Is deleted? (0 = No, 1 = Yes), ptr to TJFEESCH.Deleted';
COMMENT ON COLUMN tjfschh."CovFlag" IS 'Coverage flag (0 = Ok, 1=N/A, 2=By Report, 3=Not covered, 4=UCR), ptr to TJFEESCH.CovFlag';
COMMENT ON COLUMN tjfschh."Category" IS 'Category (P= Preventive, B= Basic, M=Major), ptr to TJFEESCH.Category';
COMMENT ON COLUMN tjfschh."Amount" IS 'Fee amount, ptr to TJFEESCH.Amount';


CREATE  TABLE tjftype (
  "Type" numeric(5,0) NOT NULL,
  "Description" character varying(255),
  "ShortDesp" character varying(60),
  CONSTRAINT tjftype_primary PRIMARY KEY ("Type")
) ;
COMMENT ON TABLE tjftype IS 'Trojan code type description table';
COMMENT ON COLUMN tjftype."Type" IS 'Trojan code type';
COMMENT ON COLUMN tjftype."ShortDesp" IS 'Trojan flag description';
COMMENT ON COLUMN tjftype."Description" IS 'Trojan code type description';


CREATE  TABLE tjinsur (
  "InsCarrier" character(6) NOT NULL,
  "InsName" character varying(30),
  "InsAddr1" character varying(30),
  "InsAddr2" character varying(30),
  "InsCity" character varying(15),
  "InsState" character varying(2),
  "InsZip" character varying(5),
  "InsAreaCd" character varying(3),
  "InsPhone" character varying(8),
  "PayerID" character varying(7),
  "Deleted" numeric(5,0),
  CONSTRAINT tjinsur_primary PRIMARY KEY ("InsCarrier")
) ;
COMMENT ON TABLE tjinsur IS 'Trojan Insurance Carriers';
COMMENT ON COLUMN tjinsur."PayerID" IS 'Payer ID or E-Claim ID';
COMMENT ON COLUMN tjinsur."InsZip" IS 'Trojan insurance postal / zip code';
COMMENT ON COLUMN tjinsur."InsState" IS 'Trojan insurance state';
COMMENT ON COLUMN tjinsur."InsPhone" IS 'Trojan insurance phone number';
COMMENT ON COLUMN tjinsur."InsName" IS 'Trojan insurance name';
COMMENT ON COLUMN tjinsur."InsCity" IS 'Trojan insurance city';
COMMENT ON COLUMN tjinsur."InsCarrier" IS 'Trojan insurance carrier code';
COMMENT ON COLUMN tjinsur."InsAreaCd" IS 'Trojan insurance area code';
COMMENT ON COLUMN tjinsur."InsAddr2" IS 'Trojan insurance address line 2';
COMMENT ON COLUMN tjinsur."InsAddr1" IS 'Trojan insurance Address line 1';
COMMENT ON COLUMN tjinsur."Deleted" IS 'Is deleted? (0 = No, 1 = Yes)';


CREATE  TABLE tjnotes (
  "TrojanId" character(7) NOT NULL,
  "Type" numeric(5,0) NOT NULL,
  "Sequence" numeric(5,0) NOT NULL,
  "Notes" character varying(48),
  CONSTRAINT tjnotes_primary PRIMARY KEY ("TrojanId", "Type", "Sequence")
) ;
COMMENT ON TABLE tjnotes IS 'Trojan employer notes';
COMMENT ON COLUMN tjnotes."Type" IS 'Trojan note type (1= notes from trojan notes1 table, 2= notes from trojan notes2 table)';
COMMENT ON COLUMN tjnotes."TrojanId" IS 'Trojan ID / Employer #';
COMMENT ON COLUMN tjnotes."Sequence" IS 'Note sequence';
COMMENT ON COLUMN tjnotes."Notes" IS 'Text of the note';


CREATE  TABLE tjpolicy (
  "TrojanId" character(7) NOT NULL,
  "EmpName" character varying(30),
  "EmpAddr1" character varying(30),
  "EmpAddr2" character varying(30),
  "EmpCity" character varying(15),
  "EmpState" character varying(2),
  "EmpZip" character varying(5),
  "EmpAreaCd" character varying(3),
  "EmpPhone" character varying(8),
  "InsCarrier" character(6),
  "MailToName" character varying(30),
  "MailToAddr" character varying(30),
  "MailToCity" character varying(15),
  "MailToState" character varying(2),
  "MailToZip" character varying(5),
  "PolicyNum" character varying(10),
  "Flags" character(43),
  "EligAreaCd" character varying(3),
  "EligPhone" character varying(8),
  "PendingDel" numeric(5,0),
  "Deleted" numeric(5,0),
  "DeletionDate" timestamp without time zone,
  "Contact" character(1),
  "Reason" character varying(175),
  CONSTRAINT tjpolicy_primary PRIMARY KEY ("TrojanId")
) ;
CREATE INDEX IF NOT EXISTS tjpolicy_policynumkey ON tjpolicy USING btree ("PolicyNum") TABLESPACE pg_default;
COMMENT ON TABLE tjpolicy IS 'Trojan Insurance Policies';
COMMENT ON COLUMN tjpolicy."TrojanId" IS 'Trojan ID / Employer #';
COMMENT ON COLUMN tjpolicy."Reason" IS 'Reason for deletion';
COMMENT ON COLUMN tjpolicy."PolicyNum" IS 'Policy Number';
COMMENT ON COLUMN tjpolicy."PendingDel" IS 'Pending to be Deleted';
COMMENT ON COLUMN tjpolicy."MailToZip" IS 'Mail to postal / zip code';
COMMENT ON COLUMN tjpolicy."MailToState" IS 'Mail to state';
COMMENT ON COLUMN tjpolicy."MailToName" IS 'Mail to name';
COMMENT ON COLUMN tjpolicy."MailToCity" IS 'Mail to city';
COMMENT ON COLUMN tjpolicy."MailToAddr" IS 'Mail to address';
COMMENT ON COLUMN tjpolicy."InsCarrier" IS 'Insurance carrier code';
COMMENT ON COLUMN tjpolicy."Flags" IS 'Miscellaneous flags';
COMMENT ON COLUMN tjpolicy."EmpZip" IS 'Employer zip code';
COMMENT ON COLUMN tjpolicy."EmpState" IS 'Employer state';
COMMENT ON COLUMN tjpolicy."EmpPhone" IS 'Employer phone';
COMMENT ON COLUMN tjpolicy."EmpName" IS 'Employer name';
COMMENT ON COLUMN tjpolicy."EmpCity" IS 'Employer city';
COMMENT ON COLUMN tjpolicy."EmpAreaCd" IS 'Employer area code';
COMMENT ON COLUMN tjpolicy."EmpAddr2" IS 'Employer address 2';
COMMENT ON COLUMN tjpolicy."EmpAddr1" IS 'Employer address 1';
COMMENT ON COLUMN tjpolicy."EligPhone" IS 'Eligibility phone';
COMMENT ON COLUMN tjpolicy."EligAreaCd" IS 'Eligibility area code';
COMMENT ON COLUMN tjpolicy."DeletionDate" IS 'Deletion date';
COMMENT ON COLUMN tjpolicy."Deleted" IS 'Is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN tjpolicy."Contact" IS 'Who to contact';


CREATE  TABLE tlocrule (
  "TLocRule" numeric(10,0) NOT NULL,
  "Clinic" numeric(10,0),
  "ProdType" character(1),
  "Year" numeric(10,0),
  "Practice" numeric(5,0),
  "CustomLocation" character(6),
  "RuleNo" numeric(10,0),
  CONSTRAINT tlocrule_primary PRIMARY KEY ("TLocRule")
) ;
CREATE INDEX IF NOT EXISTS tlocrule_clinicprodkey ON tlocrule USING btree ("Clinic", "ProdType") TABLESPACE pg_default;
COMMENT ON TABLE tlocrule IS 'Rules to set Practice and Location based on Clinic and Provider Type';
COMMENT ON COLUMN tlocrule."Year" IS 'Ptr to PRODUCER.Year or -1 for all years';
COMMENT ON COLUMN tlocrule."TLocRule" IS 'Primary key, sequence field';
COMMENT ON COLUMN tlocrule."RuleNo" IS 'Rule Number to group rules to display';
COMMENT ON COLUMN tlocrule."ProdType" IS 'Ptr to PRODTYPE.Code';
COMMENT ON COLUMN tlocrule."Practice" IS 'Ptr to PRACTICE.Id';
COMMENT ON COLUMN tlocrule."CustomLocation" IS 'CUSTCODE.Code value (based on IsLocation from CUSTTYPE)';
COMMENT ON COLUMN tlocrule."Clinic" IS 'Ptr to CLINIC.Clinic';


CREATE  TABLE tmp_fadd (
  "FItemAdd" numeric(10,0) NOT NULL,
  "FItem" numeric(10,0),
  "Answer" character varying(50),
  "Color" numeric(10,0),
  "AddAlert" numeric(5,0),
  "Alert" character(7),
  "AddPtNeed" numeric(5,0),
  "NeedCode" character(6),
  "NumFlag" numeric(5,0),
  "NumValue1" numeric,
  "NumValue2" numeric,
  "AlertType" numeric(5,0),
  "MedAlert" numeric(10,0)
) ;


CREATE  TABLE tpartyacc (
  "TPartyDef" numeric(10,0) NOT NULL DEFAULT 0,
  "SLevel" numeric(10,0) NOT NULL DEFAULT 0,
  "Access" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT tpartyacc_primary PRIMARY KEY ("TPartyDef", "SLevel")
) ;
COMMENT ON TABLE tpartyacc IS 'Table for controlling Third Party Integration access by SLevel.';
COMMENT ON COLUMN tpartyacc."TPartyDef" IS 'Part of primary key: TPARTYDEF parent Id';
COMMENT ON COLUMN tpartyacc."SLevel" IS 'Part of primary key: User SLEVEL Id';
COMMENT ON COLUMN tpartyacc."Access" IS 'Level Access - 0 - No, 1 - Yes';


CREATE  TABLE tpartydef (
  "TPartyDef" numeric(10,0) NOT NULL DEFAULT 0,
  "Name" character varying(255),
  "ShortName" character varying(20),
  "CmdType" numeric(5,0) NOT NULL DEFAULT 0,
  "ExecuteCmd" character varying(255),
  "CustomProc" character varying(255),
  "Inactive" numeric(5,0) NOT NULL DEFAULT 0,
  "PatientBased" numeric(5,0) NOT NULL DEFAULT 0,
  "Order" numeric(10,0) NOT NULL DEFAULT 0,
  "StationBased" numeric(5,0) NOT NULL DEFAULT 0,
  CONSTRAINT tpartydef_primary PRIMARY KEY ("TPartyDef")
) ;
COMMENT ON TABLE tpartydef IS 'Table for storing Third Party Integration definition.';
COMMENT ON COLUMN tpartydef."TPartyDef" IS 'Primary key sequence field';
COMMENT ON COLUMN tpartydef."StationBased" IS 'Interface requires station access setup: 0 - no, 1 - yes';
COMMENT ON COLUMN tpartydef."ShortName" IS 'Short name of the software';
COMMENT ON COLUMN tpartydef."PatientBased" IS 'Interface is patient base: 0 - no, 1 - yes';
COMMENT ON COLUMN tpartydef."Order" IS 'Display order (in maintenance and navpanel)';
COMMENT ON COLUMN tpartydef."Name" IS 'Name of the software';
COMMENT ON COLUMN tpartydef."Inactive" IS 'Allow admin to inactivate/turn off interface: 0 - active, 1 - inactive';
COMMENT ON COLUMN tpartydef."ExecuteCmd" IS 'Command to be executed';
COMMENT ON COLUMN tpartydef."CustomProc" IS 'Custom procedure to return parameter list';
COMMENT ON COLUMN tpartydef."CmdType" IS 'Command type: 0 - command line, 1 - URL';


CREATE  TABLE tpartystn (
  "TPartyDef" numeric(10,0) NOT NULL DEFAULT 0,
  "Station" numeric(10,0) NOT NULL DEFAULT 0,
  CONSTRAINT tpartystn_primary PRIMARY KEY ("TPartyDef", "Station")
) ;
COMMENT ON TABLE tpartystn IS 'Table for controlling Third Party Integration access by Station.';
COMMENT ON COLUMN tpartystn."TPartyDef" IS 'Part of primary key: TPARTYDEF parent Id';
COMMENT ON COLUMN tpartystn."Station" IS 'Part of primary key: Station Id';


CREATE  TABLE tplanopt (
  "TPlanOpt" numeric(10,0) NOT NULL,
  "NeedsConsultant" numeric(5,0),
  "ProdType" character(1),
  "PGroup" character(6),
  "PrintNeedsApp" numeric(5,0),
  "PtAcceptNeedsApp" numeric(5,0),
  "DiagPathDisplay" numeric(5,0),
  "SelectExistingPrb" numeric(5,0),
  CONSTRAINT tplanopt_primary PRIMARY KEY ("TPlanOpt")
) ;
COMMENT ON TABLE tplanopt IS 'Treatment Planning Module Option Sets';
COMMENT ON COLUMN tplanopt."TPlanOpt" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN tplanopt."SelectExistingPrb" IS 'Select from existing problems when adding problems to Tx Plans? (0=No, 1=Yes)';
COMMENT ON COLUMN tplanopt."PtAcceptNeedsApp" IS 'Require approval on patient acceptance? (0 = No,1 = Yes)';
COMMENT ON COLUMN tplanopt."ProdType" IS 'Provider type for the treatment plan option set, ptr to PRODTYPE.Code';
COMMENT ON COLUMN tplanopt."PrintNeedsApp" IS 'Require approval to print tx plan? (0 = No, 1 = Yes)';
COMMENT ON COLUMN tplanopt."PGroup" IS 'Provider group for the treatment plan option set, ptr to PGROUP.Pgroup';
COMMENT ON COLUMN tplanopt."NeedsConsultant" IS 'Requires approval on Tx Plan? (0 = No, 1 = Yes)';
COMMENT ON COLUMN tplanopt."DiagPathDisplay" IS 'Diagnosis path (0=Show Nothing, 1=Show Full Path, 2=Show Quick List Categories)';


CREATE  TABLE treatme2 (
  "Auto" numeric(10,0) NOT NULL,
  "PId" numeric(10,0),
  "CodeId" numeric(10,0),
  "Days" numeric(10,0),
  "ModifiedDateTime" timestamp without time zone,
  "PreId" numeric(10,0),
  "User" numeric(10,0),
  "Site" numeric(5,0),
  "Status" numeric(5,0),
  "Surface" numeric(5,0),
  "Deleted" numeric(5,0),
  "Site2" numeric(5,0),
  "Number" character(7),
  "Phase" character(2),
  "Seq" numeric(5,0),
  "Provider" character(10),
  "Custom1" character(6),
  "Custom2" character(6),
  "ParentId" numeric(10,0),
  "Discipline" character(15),
  "TxPTx" numeric(10,0),
  "StationId" numeric(10,0),
  "Custom3" character(6),
  "Custom4" character(6),
  "DeletionDate" timestamp without time zone,
  "AddDateTime" timestamp without time zone,
  "AppUser" numeric(10,0),
  "AppDate" timestamp without time zone,
  "DelAppUser" numeric(10,0),
  "DelAppDate" timestamp without time zone,
  "Unit" numeric,
  CONSTRAINT treatme2_primary PRIMARY KEY ("Auto")
) ;
CREATE INDEX IF NOT EXISTS treatme2_dtxplanid ON treatme2 USING btree ("TxPTx") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS treatme2_parentid ON treatme2 USING btree ("ParentId") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS "TREATME2_PId" ON treatme2 USING btree ("PId") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS treatme2_preid ON treatme2 USING btree ("PreId") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS treatme2_providerappdatekey ON treatme2 USING btree ("Provider", "AppDate") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS "TREATME2_Time" ON treatme2 USING btree ("ModifiedDateTime") TABLESPACE pg_default;
COMMENT ON TABLE treatme2 IS 'Treatments on Chart';
COMMENT ON COLUMN treatme2."User" IS 'User ID of entry user. Ptr to USERS.User';
COMMENT ON COLUMN treatme2."Unit" IS 'Number of units for this treatment (if unapproved, from PROCEDUR.Units; if approved, from TRX.Unit)';
COMMENT ON COLUMN treatme2."TxPTx" IS 'If this treatment is on a treatment plan, ptr to TXPTX.TxPTx';
COMMENT ON COLUMN treatme2."Surface" IS 'Surface treatment performed on';
COMMENT ON COLUMN treatme2."Status" IS 'Status of procedure (0=Complete, 1=In Process, 2=Planned, 3=Pre-Existing, 4= Condition, 5=Ortho Visit)';
COMMENT ON COLUMN treatme2."StationId" IS 'Station ID of entry user. Ptr to STATION.StationId';
COMMENT ON COLUMN treatme2."Site2" IS 'Ending site (tooth) for bridge/bar type procedure';
COMMENT ON COLUMN treatme2."Site" IS 'Site (tooth) treatment performed on';
COMMENT ON COLUMN treatme2."Seq" IS 'Treatment sequence number';
COMMENT ON COLUMN treatme2."Provider" IS 'Provider ID, ptr to PRODUCER.Producer';
COMMENT ON COLUMN treatme2."PreId" IS 'Previous treatment record for this treatment, if any. Ptr to TREATME2.Auto';
COMMENT ON COLUMN treatme2."Phase" IS 'Treatment phase';
COMMENT ON COLUMN treatme2."ParentId" IS 'If this treatment is a step, the parent treatment. Ptr to TREATME2.Auto';
COMMENT ON COLUMN treatme2."PId" IS 'Patient chart, ptr to PATIENT2.Auto';
COMMENT ON COLUMN treatme2."Number" IS 'Additional number for special procedures, from TRX';
COMMENT ON COLUMN treatme2."ModifiedDateTime" IS 'Date/time of most recent modification. ';
COMMENT ON COLUMN treatme2."Discipline" IS 'Treatment discipline, ptr to CLASS.Class';
COMMENT ON COLUMN treatme2."DeletionDate" IS 'If deleted, the date of deletion.';
COMMENT ON COLUMN treatme2."Deleted" IS 'Deleted? (0 = No, 1 = Yes, 2 = Strikeout)';
COMMENT ON COLUMN treatme2."DelAppUser" IS 'If deleted and approved, the user who approved the deletion. Ptr to USERS.User';
COMMENT ON COLUMN treatme2."DelAppDate" IS 'If deleted and approved, the date that the deletion was approved.';
COMMENT ON COLUMN treatme2."Days" IS 'Date of treatment (in days since 01-JAN-1901)';
COMMENT ON COLUMN treatme2."Custom4" IS 'Treatment/Clinical2 custom field. ptr to CUSTCODE.Code';
COMMENT ON COLUMN treatme2."Custom3" IS 'Treatment/Clinical1 custom field. ptr to CUSTCODE.Code';
COMMENT ON COLUMN treatme2."Custom2" IS 'Treatment/Note2 custom field. ptr to CUSTCODE.Code';
COMMENT ON COLUMN treatme2."Custom1" IS 'Treatment/Note1 custom field. ptr to CUSTCODE.Code';
COMMENT ON COLUMN treatme2."CodeId" IS 'Procedure Code ID, ptr to PROCEDUR.Id';
COMMENT ON COLUMN treatme2."Auto" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN treatme2."AppUser" IS 'If approved, the user ID of the approving user. Ptr to USERS.User';
COMMENT ON COLUMN treatme2."AppDate" IS 'If approved, the date of the approval';
COMMENT ON COLUMN treatme2."AddDateTime" IS 'Date/time of when the record was added';


CREATE  TABLE trojaud (
  "Id" numeric(10,0) NOT NULL,
  "UpdateDate" timestamp without time zone,
  "Station" numeric(10,0),
  "User" numeric(10,0),
  "FileDate" timestamp without time zone,
  "FileTime" numeric(10,0),
  "LastPurge" timestamp without time zone,
  "PurgeCutoff" timestamp without time zone,
  "PurgeStation" numeric(10,0),
  "PurgeUser" numeric(10,0),
  "Action" numeric(5,0),
  CONSTRAINT trojaud_primary PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE trojaud IS 'Audit trail for Trojan';
COMMENT ON COLUMN trojaud."User" IS 'Id code of the user who performed the Trojan update';
COMMENT ON COLUMN trojaud."UpdateDate" IS 'Date of the Trojan update';
COMMENT ON COLUMN trojaud."Station" IS 'Id code of the station on which the Trojan update was performed';
COMMENT ON COLUMN trojaud."PurgeUser" IS 'Id code of the user who performed the last purge';
COMMENT ON COLUMN trojaud."PurgeStation" IS 'Id code of the station on which the last purge was performed';
COMMENT ON COLUMN trojaud."PurgeCutoff" IS 'Date last used as a cutoff for the Trojan purge';
COMMENT ON COLUMN trojaud."LastPurge" IS 'Date of last Purge ';
COMMENT ON COLUMN trojaud."Id" IS 'ID code of the audit record';
COMMENT ON COLUMN trojaud."FileTime" IS 'Time stamp on the Trojan file last imported';
COMMENT ON COLUMN trojaud."FileDate" IS 'Date stamp on the Trojan file last imported';
COMMENT ON COLUMN trojaud."Action" IS 'Action (0=Import, 1=Purge)';


CREATE  TABLE trx (
  "Type" numeric(5,0) NOT NULL,
  "Id" numeric(10,0) NOT NULL,
  "Treatment" numeric(5,0) NOT NULL,
  "Patient" numeric(10,0),
  "Family" numeric(10,0),
  "Status" character(6),
  "EDI" character(15),
  "EDIStatus" numeric(5,0),
  "Date" timestamp without time zone,
  "SubmitDate" timestamp without time zone,
  "ClaimDoctor" character(10),
  "Submitted" numeric(5,0),
  "TreatmentDate" timestamp without time zone,
  "CreationDate" timestamp without time zone DEFAULT current_date,
  "Procedure" character(7),
  "Code" character(6),
  "Site" character(3),
  "Surface" character(6),
  "Unit" numeric,
  "Producer" character(10),
  "Total" numeric,
  "InsTotal" numeric,
  "Company1" character(6),
  "Policy1" character varying(20),
  "Category1" character(6),
  "Item1" numeric(10,0),
  "Deduct1" numeric,
  "Assign1" numeric(5,0),
  "Eligible1" numeric,
  "Pct1" numeric,
  "Amount1" numeric,
  "InsPayed1" numeric,
  "InsAdj1" numeric,
  "Company2" character(6),
  "Policy2" character varying(20),
  "Category2" character(6),
  "Item2" numeric(10,0),
  "Assign2" numeric(5,0),
  "Deduct2" numeric,
  "Eligible2" numeric,
  "Pct2" numeric,
  "Amount2" numeric,
  "InsPayed2" numeric,
  "InsAdj2" numeric,
  "Company3" character(6),
  "Policy3" character varying(20),
  "Category3" character(6),
  "Item3" numeric(10,0),
  "Assign3" numeric(5,0),
  "Deduct3" numeric,
  "Eligible3" numeric,
  "Pct3" numeric,
  "Amount3" numeric,
  "InsPayed3" numeric,
  "InsAdj3" numeric,
  "Description" character varying(60),
  "Deleted" numeric(5,0),
  "Bank" character(6),
  "Payed" numeric,
  "InsPayed" numeric,
  "PtAdj" numeric,
  "InsAdj" numeric,
  "EstimateF" numeric(10,0),
  "Additional" character(7),
  "TxStatus" character(6),
  "User" numeric(10,0),
  "PtWriteOff" numeric,
  "PolicyId1" numeric(10,0),
  "PolicyId2" numeric(10,0),
  "PolicyId3" numeric(10,0),
  "InsStatus1" numeric(5,0),
  "InsStatus2" numeric(5,0),
  "InsStatus3" numeric(5,0),
  "IsBankDeposit" numeric(5,0),
  "ChartTrx" numeric(10,0),
  "PlanTotal" numeric,
  "Phase" character(2),
  "Seq" numeric(5,0),
  "AppUser" numeric(10,0),
  "AppDate" timestamp without time zone,
  "Grading" numeric(10,0),
  "Site2" character(3),
  "Custom1" character(6),
  "Custom2" character(6),
  "PayPlanId" numeric(10,0),
  "Discipline" character(15),
  "DiscountedPmtId" numeric(10,0),
  "Location" character(6),
  "OrigAssign1" numeric(5,0),
  "OrigAssign2" numeric(5,0),
  "OrigAssign3" numeric(5,0),
  "InDispute" numeric(5,0),
  "DisputeDate" timestamp without time zone,
  "DeletionDate" timestamp without time zone,
  "EDIPat" character(15),
  "EDIPatStatus" numeric(5,0),
  "InsTransfer1" numeric,
  "InsTransfer2" numeric,
  "InsTransfer3" numeric,
  "InsTransfer" numeric,
  "InsPmtId" numeric(10,0),
  "StationId" numeric(10,0),
  "Practice" numeric(5,0),
  "Suspended" numeric(5,0),
  "DelAppUser" numeric(10,0),
  "DelAppDate" timestamp without time zone,
  "OrthoStatus" numeric(5,0),
  "CvgType" numeric(5,0),
  "ModifiedDate" timestamp without time zone,
  "OrigClaimDate" timestamp without time zone,
  "SubmitMode" numeric(5,0),
  "Custom3" character(6),
  "Custom4" character(6),
  "CorrespondCode" character(7),
  "InsCvgType1" numeric(5,0),
  "InsCvgType2" numeric(5,0),
  "InsCvgType3" numeric(5,0),
  "OrigRecNo" numeric(10,0),
  "EntryUser" numeric(10,0),
  "PlanInProcTotal" numeric,
  "TrxDep" numeric(10,0),
  "CustomaryTotal" numeric,
  "TaxRate" numeric,
  "TaxAmount" numeric,
  CONSTRAINT trx_primary PRIMARY KEY ("Type", "Id", "Treatment")
) ;
CREATE INDEX IF NOT EXISTS trx_appuser_appdate_mu_idx ON trx USING btree ("AppUser", "AppDate") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS trx_charttrx ON trx USING btree ("ChartTrx") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS trx_claimdoctor ON trx USING btree ("ClaimDoctor") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS trx_claimdoctor_trxdate ON trx USING btree ("ClaimDoctor", "TreatmentDate") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS trx_company1assign1 ON trx USING btree ("Company1", "Assign1") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS trx_company1key ON trx USING btree ("Type", "Company1", "Date") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS trx_company2assign2 ON trx USING btree ("Company2", "Assign2") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS trx_company2key ON trx USING btree ("Type", "Company2") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS trx_company3assign3 ON trx USING btree ("Company3", "Assign3") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS trx_company3key ON trx USING btree ("Type", "Company3") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS trx_datekey ON trx USING btree ("Date", "Type", "AppUser") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS trx_edi ON trx USING btree ("EDI") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS trx_edipat ON trx USING btree ("EDIPat") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS trx_edists ON trx USING btree ("EDIStatus") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS trx_familykey ON trx USING btree ("Family", "Type") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS trx_grading ON trx USING btree ("Grading") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS trx_gradingappuser ON trx USING btree ("Type", "Grading", "Deleted", "AppUser") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS trx_inspmtid ON trx USING btree ("InsPmtId") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS trx_origrecno ON trx USING btree ("OrigRecNo") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS trx_patientdatekey ON trx USING btree ("Patient", "Date", "Type") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS trx_patientkey ON trx USING btree ("Patient", "Type") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS trx_payplan ON trx USING btree ("PayPlanId") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS trx_producer ON trx USING btree ("Producer") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS trx_treatmentdatekey ON trx USING btree ("TreatmentDate") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS trx_typegradingdeleted ON trx USING btree ("Type", "Grading", "Deleted") TABLESPACE pg_default;
COMMENT ON TABLE trx IS 'Transactions';
COMMENT ON COLUMN trx."User" IS 'User ID of entry user. Ptr to USERS.User';
COMMENT ON COLUMN trx."Unit" IS 'For Type=1/5, number of units for the treatment. For Type=2, quantity for the office charge.';
COMMENT ON COLUMN trx."Type" IS 'Primary key component, transaction record type (1=Treatment, 2=Office Charge, 3=Patient Payment, 4=Insurance Payment, 5=Planned Treatment, 6=Adjustment, 7=Insurance Adjustment, 73=Allocated portion of a Patient Payment, 74= Insurance Payment allocated to patient treatment)';
COMMENT ON COLUMN trx."TxStatus" IS 'User-definable Treatment status, ptr to STATUS.Status';
COMMENT ON COLUMN trx."TrxDep" IS 'Associated deductables / charges / estimates. Ptr to TRXDEP.TrxDep';
COMMENT ON COLUMN trx."TreatmentDate" IS 'For Type=1/5, the date that the treatment was performed/planned for (this is the date visible in the Date column of the EHR - Tx History tab)';
COMMENT ON COLUMN trx."Treatment" IS 'Primary key component, transaction line number within claim (for treatments).';
COMMENT ON COLUMN trx."Total" IS 'Total amount of the transaction, in dollars. For treatments, this is the total for the treatment (not the claim) and includes the patient and insurance amounts.';
COMMENT ON COLUMN trx."TaxRate" IS 'Sales tax percentage.';
COMMENT ON COLUMN trx."TaxAmount" IS 'Calculated sales tax amount, in dollars. ';
COMMENT ON COLUMN trx."Suspended" IS 'Is suspended? (0=No, 1=Yes)';
COMMENT ON COLUMN trx."Surface" IS 'Surface on crown for treatment.';
COMMENT ON COLUMN trx."Submitted" IS 'Has Treatment been submitted? (0 = Unsubmitted, 1 = Submitted, 2 = Mark as Void, 3 = Voided)';
COMMENT ON COLUMN trx."SubmitMode" IS 'Submit mode (0=Bill current policy, 1=Bill Original policy, 2=Bill policy effective on date of treatment)';
COMMENT ON COLUMN trx."SubmitDate" IS 'Date treatment was submitted to insurance. ';
COMMENT ON COLUMN trx."Status" IS 'Treatment Status (P = Planned, I = In Progress, C = Complete)';
COMMENT ON COLUMN trx."StationId" IS 'Station ID, ptr to STATION.StationId';
COMMENT ON COLUMN trx."Site2" IS 'Ending site/tooth for multi-site treatments (e.g. bridges)';
COMMENT ON COLUMN trx."Site" IS 'Site/tooth for treatment.';
COMMENT ON COLUMN trx."Seq" IS 'Treatment sequence number.';
COMMENT ON COLUMN trx."PtWriteOff" IS 'Internal amount field used with special billing method Auto Discount';
COMMENT ON COLUMN trx."PtAdj" IS 'Total of all patient adjustments allocated to this transaction, in dollars.';
COMMENT ON COLUMN trx."Producer" IS 'Producer ID, ptr to PRODUCER.Producer';
COMMENT ON COLUMN trx."Procedure" IS 'Procedure code, ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN trx."Practice" IS 'Practice for this transaction, ptr to PRACTICE.Id';
COMMENT ON COLUMN trx."PolicyId3" IS 'Tertiary insurance policy ID, ptr to PTPOL.PolicyId';
COMMENT ON COLUMN trx."PolicyId2" IS 'Secondary insurance policy ID, ptr to PTPOL.PolicyId';
COMMENT ON COLUMN trx."PolicyId1" IS 'Primary insurance policy ID, ptr to PTPOL.PolicyId';
COMMENT ON COLUMN trx."Policy3" IS 'Policy ID for the tertiary insurance policy. Ptr to PTPOL.Policy.';
COMMENT ON COLUMN trx."Policy2" IS 'Policy ID for the secondary insurance policy. Ptr to PTPOL.Policy.';
COMMENT ON COLUMN trx."Policy1" IS 'Policy ID for the primary insurance policy. Ptr to PTPOL.Policy.';
COMMENT ON COLUMN trx."PlanTotal" IS 'Planned treatment amount used for binding quote, in dollars.';
COMMENT ON COLUMN trx."PlanInProcTotal" IS 'Amount of the planned in-process treatment, in dollars.';
COMMENT ON COLUMN trx."Phase" IS 'Treatment phase order.';
COMMENT ON COLUMN trx."Pct3" IS 'Percentage of coverage for item under tertiary insurance policy, in dollars.';
COMMENT ON COLUMN trx."Pct2" IS 'Percentage of coverage for item under secondary insurance policy, in dollars.';
COMMENT ON COLUMN trx."Pct1" IS 'Percentage of coverage for item under primary insurance policy, in dollars.';
COMMENT ON COLUMN trx."Payed" IS 'Total of all patient payments allocated to this transaction, in dollars.';
COMMENT ON COLUMN trx."PayPlanId" IS 'Payment Plan ID, ptr to PAYPLAN.PlanId';
COMMENT ON COLUMN trx."Patient" IS 'If Type=3/6/73, the ID of the payor. For other types, the ID patient that the transaction is for. Ptr to PATIENT.Patient';
COMMENT ON COLUMN trx."OrthoStatus" IS 'Ortho treatment status (0=Regular Ortho treatment, 1=Treatment tied to an Ortho payment plan, 2=Treatment created by th eOrtho Billings Process )';
COMMENT ON COLUMN trx."OrigRecNo" IS 'Original record number, unique ID from sequence. ';
COMMENT ON COLUMN trx."OrigClaimDate" IS 'Original date of claim';
COMMENT ON COLUMN trx."OrigAssign3" IS 'DEPRECATED';
COMMENT ON COLUMN trx."OrigAssign2" IS 'DEPRECATED';
COMMENT ON COLUMN trx."OrigAssign1" IS 'DEPRECATED';
COMMENT ON COLUMN trx."ModifiedDate" IS 'The date/time that the transaction was last modified';
COMMENT ON COLUMN trx."Location" IS 'Location at which procedure was performed, ptr to FACILITY.Code';
COMMENT ON COLUMN trx."Item3" IS 'Item line in policy coverage for this treatment under the tertiary insurance policy. Ptr to COVERIT.Item.';
COMMENT ON COLUMN trx."Item2" IS 'Item line in policy coverage for this treatment under the secondary insurance policy. Ptr to COVERIT.Item.';
COMMENT ON COLUMN trx."Item1" IS 'Item line in policy coverage for this treatment under the primary insurance policy. Ptr to COVERIT.Item.';
COMMENT ON COLUMN trx."IsBankDeposit" IS 'Print transaction on Bank Deposit report? (0=No, 1=Yes)';
COMMENT ON COLUMN trx."InsTransfer3" IS 'Amount transferred from tertiary insurance to patient, in dollars.';
COMMENT ON COLUMN trx."InsTransfer2" IS 'Amount transferred from secondary insurance to patient or tertiary insurance, in dollars.';
COMMENT ON COLUMN trx."InsTransfer1" IS 'Amount transferred from primary insurance to patient or secondary insurance, in dollars.';
COMMENT ON COLUMN trx."InsTransfer" IS 'Total amount transferred from insurance, in dollars.';
COMMENT ON COLUMN trx."InsTotal" IS 'Insurance portion of the Total amount, in dollars.';
COMMENT ON COLUMN trx."InsStatus3" IS 'For treatments paid by tertiary insurance, indicates what was done with the insurance outstanding amount (0=Left Outstanding, 1=Transferred to Patient, 2=Written Off, 3=Transferred and Written Off)';
COMMENT ON COLUMN trx."InsStatus2" IS 'For treatments paid by secondary insurance, indicates what was done with the insurance outstanding amount (0=Left Outstanding, 1=Transferred to Patient, 2=Written Off, 3=Transferred and Written Off)';
COMMENT ON COLUMN trx."InsStatus1" IS 'For treatments paid by primary insurance, indicates what was done with the insurance outstanding amount (0=Left Outstanding, 1=Transferred to Patient, 2=Written Off, 3=Transferred and Written Off)';
COMMENT ON COLUMN trx."InsPmtId" IS 'If Type=7, the insurance payment being adjusted. Ptr to a TRX.Id with TRX.Type=4.';
COMMENT ON COLUMN trx."InsPayed3" IS 'Amount paid by tertiary insurance, in dollars.';
COMMENT ON COLUMN trx."InsPayed2" IS 'Amount paid by secondary insurance, in dollars.';
COMMENT ON COLUMN trx."InsPayed1" IS 'Amount paid by primary insurance, in dollars.';
COMMENT ON COLUMN trx."InsPayed" IS 'Total of all insurance payments allocated to this transaction, in dollars.';
COMMENT ON COLUMN trx."InsCvgType3" IS 'Insurance coverage type for tertiary insurance (0=Dental, 1= Medical, 2= NowIsDental, 3= NowIsMedical)';
COMMENT ON COLUMN trx."InsCvgType2" IS 'Insurance coverage type for secondary insurance (0=Dental, 1= Medical, 2= NowIsDental, 3= NowIsMedical)';
COMMENT ON COLUMN trx."InsCvgType1" IS 'Insurance coverage type for primary insurance (0=Dental, 1= Medical, 2= NowIsDental, 3= NowIsMedical).';
COMMENT ON COLUMN trx."InsAdj3" IS 'Amount adjusted (written-off) by tertiary insurance, in dollars.';
COMMENT ON COLUMN trx."InsAdj2" IS 'Amount adjusted (written-off) by secondary insurance, in dollars.';
COMMENT ON COLUMN trx."InsAdj1" IS 'Amount adjusted (written-off) by primary insurance, in dollars.';
COMMENT ON COLUMN trx."InsAdj" IS 'Total of all insurance adjustments allocated to this transaction, in dollars.';
COMMENT ON COLUMN trx."InDispute" IS 'Treatment in dispute? (0 = No, 1 = Yes)';
COMMENT ON COLUMN trx."Id" IS 'Primary key component, unique ID of the transaction record. Sequence used depends on Type. For treatments, this is the claim number. ';
COMMENT ON COLUMN trx."Grading" IS 'Link to evaluation for this treatment, ptr to GRADING.Grading';
COMMENT ON COLUMN trx."Family" IS 'If Type=3/6/73, the ID of patient who is being paid for (ptr to PATIENT.Patient). For other types, the family ID of the patient that the transaction is for (ptr to PATIENT.Family)';
COMMENT ON COLUMN trx."EstimateF" IS 'Indicator if Policy Limit reached on transaction - values can be 1,2,4, or 8 or any combination of them. Taken from the SPLIT screen';
COMMENT ON COLUMN trx."EntryUser" IS 'ID code of the entry user, ptr to USERS.User';
COMMENT ON COLUMN trx."Eligible3" IS 'Eligible amount of coverage for item under tertiary insurance policy, in dollars.';
COMMENT ON COLUMN trx."Eligible2" IS 'Eligible amount of coverage for item under secondary insurance policy, in dollars.';
COMMENT ON COLUMN trx."Eligible1" IS 'Eligible amount of coverage for item under primary insurance policy, in dollars.';
COMMENT ON COLUMN trx."EDIStatus" IS 'EDI submission status (0=Not Applicable, 1=Not Sent, 2=Sent, 3=Rejected, 4=Held, 5=N/A, 6=Applied, 7=Paid, 8=Error)';
COMMENT ON COLUMN trx."EDIPatStatus" IS 'EDI submission status (0=N/A, 1=Not Sent, 2=Sent, 3=Rejected, 4=Held, 5=N/A, 6=Applied, 7=Paid, 8=Error (Patient Side - used in axiUm Dutch Version))';
COMMENT ON COLUMN trx."EDIPat" IS 'Dutch: Patient "EDI" submission number. US/CA: ptr to EPBItem for Lockbox payment';
COMMENT ON COLUMN trx."EDI" IS 'EDI submission number';
COMMENT ON COLUMN trx."DisputeDate" IS 'If InDispute=1, the date that the treatment became in dispute. ';
COMMENT ON COLUMN trx."DiscountedPmtId" IS 'If this record is discount adjustment (Type=6), the patient payment that is being adjusted. Ptr to a TRX.Id with TRX.Type=3.';
COMMENT ON COLUMN trx."Discipline" IS 'Discipline, ptr to CLASS.Class';
COMMENT ON COLUMN trx."Description" IS 'Description of transaction';
COMMENT ON COLUMN trx."DeletionDate" IS 'If Deleted=1, the date that the treatment was deleted. ';
COMMENT ON COLUMN trx."Deleted" IS 'Deleted? (0 = No, 1 = Yes, 2= Strikeout / Rebilled)';
COMMENT ON COLUMN trx."DelAppUser" IS 'Deletion approval user, ptr to USERS.User';
COMMENT ON COLUMN trx."DelAppDate" IS 'Date of the deletion approval';
COMMENT ON COLUMN trx."Deduct3" IS 'Tertiary insurance policy accepts assignment? (0 = No, 1 = Yes)';
COMMENT ON COLUMN trx."Deduct2" IS 'Secondary insurance policy accepts assignment? (0 = No, 1 = Yes)';
COMMENT ON COLUMN trx."Deduct1" IS 'Deductible amount for item under primary insurance policy, in dollars.';
COMMENT ON COLUMN trx."Date" IS 'Transaction date, date of the claim';
COMMENT ON COLUMN trx."CvgType" IS 'Number to indicate type of coverage (0 = Dental, 1 = Medical), ptr to INSURANC.CvgType';
COMMENT ON COLUMN trx."CustomaryTotal" IS 'Customary total (fee to bill if not a government plan or discount), in dollars.';
COMMENT ON COLUMN trx."Custom4" IS 'Treatment/Clinical2 code for this transaction, ptr to CUSTCODE.Code';
COMMENT ON COLUMN trx."Custom3" IS 'Treatment/Clinical1 code for this transaction, ptr to CUSTCODE.Code';
COMMENT ON COLUMN trx."Custom2" IS 'Treatment/Note2 code for this transaction, ptr to CUSTCODE.Code';
COMMENT ON COLUMN trx."Custom1" IS 'Treatment/Note1 code for this transaction, ptr to CUSTCODE.Code';
COMMENT ON COLUMN trx."CreationDate" IS 'Date that the first history record was created for this transaction.';
COMMENT ON COLUMN trx."CorrespondCode" IS 'If InsCvgType=2 or 3, the corresponding medical treatment code or procedure code. Ptr to PROCEDUR.Procedure.';
COMMENT ON COLUMN trx."Company3" IS 'Tertiary insurance company, ptr to INSURANC.Company';
COMMENT ON COLUMN trx."Company2" IS 'Secondary insurance company, ptr to INSURANC.Company';
COMMENT ON COLUMN trx."Company1" IS 'Primary insurance company, ptr to INSURANC.Company';
COMMENT ON COLUMN trx."Code" IS 'Office charge, Payment, or Adjustment code, depending on Type. (Type=2, ptr to OFCHARGE.OfficeCharge; Type=3/4/73/74, ptr to PAYMENT.Payment; Type=6/7, ptr to ADJUST.Adjust)';
COMMENT ON COLUMN trx."ClaimDoctor" IS 'Billing entity/Fee Guide, ptr to PRODUCER.Producer';
COMMENT ON COLUMN trx."ChartTrx" IS 'Link to treatment on chart, ptr to TREATME2.Auto';
COMMENT ON COLUMN trx."Category3" IS 'Category of coverage for this treatment under the tertiary insurance policy. Ptr to COVERIT.Category.';
COMMENT ON COLUMN trx."Category2" IS 'Category of coverage for this treatment under the secondary insurance policy. Ptr to COVERIT.Category.';
COMMENT ON COLUMN trx."Category1" IS 'Category of coverage for this treatment under the primary insurance policy. Ptr to COVERIT.Category.';
COMMENT ON COLUMN trx."Bank" IS 'Cash drawer / point of sale teminal ID, ptr to BANK.Bank';
COMMENT ON COLUMN trx."Assign3" IS 'Deductible amount for item under tertiary insurance policy, in dollars.';
COMMENT ON COLUMN trx."Assign2" IS 'Deductible amount for item under secondary insurance policy, in dollars.';
COMMENT ON COLUMN trx."Assign1" IS 'Primary insurance policy accepts assignment? (0 = No, 1 = Yes)';
COMMENT ON COLUMN trx."AppUser" IS 'User ID of Instructor that approved the procedure, ptr to USERS.User';
COMMENT ON COLUMN trx."AppDate" IS 'Date treatment was approved';
COMMENT ON COLUMN trx."Amount3" IS 'Amount of coverage for item under tertiary insurance policy, in dollars.';
COMMENT ON COLUMN trx."Amount2" IS 'Amount of coverage for item under secondary insurance policy, in dollars.';
COMMENT ON COLUMN trx."Amount1" IS 'Amount of coverage for item under primary insurance policy, in dollars.';
COMMENT ON COLUMN trx."Additional" IS 'Additional field used optionally for treatments.';


CREATE  TABLE trxaddl (
  "Type" numeric(5,0) NOT NULL,
  "Id" numeric(10,0) NOT NULL,
  "Treatment" numeric(5,0) NOT NULL,
  "IsProsthetics" numeric(5,0),
  "IsInitialPlacement" numeric(5,0),
  "InitialPlacementDate" timestamp without time zone,
  "IsOrthodontics" numeric(5,0),
  "IsOrthoReplacement" numeric(5,0),
  "OrthoReplacementDate" timestamp without time zone,
  "OrthoTotalMonths" numeric(5,0),
  "OrthoMonthsLeft" numeric(5,0),
  "ProstheticArch" numeric(5,0),
  "PriorProsthMaterial" numeric(5,0),
  "ProcType" character varying(5),
  "MtlFwdEmail" numeric(5,0),
  "MtlFwdCorrespond" numeric(5,0),
  "MtlFwdModels" numeric(5,0),
  "MtlFwdXrays" numeric(5,0),
  "MtlFwdImages" numeric(5,0),
  "DiagnosticCode" character(6),
  "InstitutionCode" character(6),
  "Referral" numeric(10,0),
  "ReferralCDANo" character varying(10),
  "ReferralReason" character(2),
  "OrthoStartDate" timestamp without time zone,
  "OrthoFirstFee" numeric,
  "OrthoDiagFee" numeric,
  "OrthoInitPmt" numeric,
  "OrthoPmtMode" numeric(5,0),
  "OrthoDuration" numeric(5,0),
  "OrthoNumPmts" numeric(5,0),
  "OrthoPmtAmt" numeric,
  "ChartLnk" numeric(10,0),
  "NeedAddlSiteInfo" numeric(5,0) NOT NULL DEFAULT 0,
  "AdditionalSiteInfo" character varying(15),
  CONSTRAINT trxaddl_primary PRIMARY KEY ("Type", "Id", "Treatment")
) ;
COMMENT ON TABLE trxaddl IS 'TRX Additional Info table';
COMMENT ON COLUMN trxaddl."Type" IS 'Primary key, Transaction record type (1=Treatment, 2=Office Charge, 3=Patient Payment, 4=Insurance Payment, 5=Planned Treatment, 6=Adjustment, 7=Insurance Adjustment, 73=Allocated portion of a Patient Payment, 74= Insurance Payment allocated to patient treatment)';
COMMENT ON COLUMN trxaddl."Treatment" IS 'Primary key, Transaction line number within claim (for treatments)';
COMMENT ON COLUMN trxaddl."ReferralReason" IS 'Referral reason (B06)';
COMMENT ON COLUMN trxaddl."ReferralCDANo" IS 'Referral CDA number';
COMMENT ON COLUMN trxaddl."Referral" IS 'Referral record ID.';
COMMENT ON COLUMN trxaddl."ProstheticArch" IS 'If IsProsthetics=1, arch that the prosthetic is on (0=Maxillary, 1=Mandibular)';
COMMENT ON COLUMN trxaddl."ProcType" IS 'Type of procedure (A=Repair, B=Temporary, C=TMJ, D=Cosmetic, E=Implant, L=Lost Appliance, S=Stolen Appliance, X=None of the above)';
COMMENT ON COLUMN trxaddl."PriorProsthMaterial" IS 'If IsProsthetics=1, material of the prosthetic (0=N/A, 1=Fixed bridge, 2= Maryland bridge, 3=Denture (acrylic), 4=Denture (chrome cobalt), 5=Implant (fixed), 6=Implant (removable))';
COMMENT ON COLUMN trxaddl."OrthoTotalMonths" IS 'For formatting of ortho treatments on "EDI" claims. Total months for ortho.';
COMMENT ON COLUMN trxaddl."OrthoStartDate" IS 'Start date of orthodontics.';
COMMENT ON COLUMN trxaddl."OrthoReplacementDate" IS 'For formatting of ortho treatments on "EDI" claims. If TRX.IsOrthoReplacement=0, the initial placement date. IfTRX.IsOrthoReplacement=1, the replacement date.';
COMMENT ON COLUMN trxaddl."OrthoPmtMode" IS 'Ortho payment mode (1=Monthly, 2=Bimonthly, 3=Quarterly, 4=Every 4 months) (F29)';
COMMENT ON COLUMN trxaddl."OrthoPmtAmt" IS 'Amount of each payment for ortho';
COMMENT ON COLUMN trxaddl."OrthoNumPmts" IS 'Number of payments for ortho';
COMMENT ON COLUMN trxaddl."OrthoMonthsLeft" IS 'For formatting of ortho treatments on "EDI" claims. Months left for ortho.';
COMMENT ON COLUMN trxaddl."OrthoInitPmt" IS 'Amount of initial ortho payment';
COMMENT ON COLUMN trxaddl."OrthoFirstFee" IS 'First examination fee';
COMMENT ON COLUMN trxaddl."OrthoDuration" IS 'Duration of orthodontic treatment';
COMMENT ON COLUMN trxaddl."OrthoDiagFee" IS 'Diagnostic phase fee';
COMMENT ON COLUMN trxaddl."NeedAddlSiteInfo" IS 'Need additional site information (0 = No, 1 = Yes).';
COMMENT ON COLUMN trxaddl."MtlFwdXrays" IS 'Material forward x-rays? (0=No, 1=Yes)';
COMMENT ON COLUMN trxaddl."MtlFwdModels" IS 'Material forward models? (0=No, 1=Yes)';
COMMENT ON COLUMN trxaddl."MtlFwdImages" IS 'Material forward images? (0=No, 1=Yes)';
COMMENT ON COLUMN trxaddl."MtlFwdEmail" IS 'Material forward e-mail? (0=No, 1=Yes)';
COMMENT ON COLUMN trxaddl."MtlFwdCorrespond" IS 'Material forward correspondence? (0=No, 1=Yes)';
COMMENT ON COLUMN trxaddl."IsProsthetics" IS 'For formatting of ortho treatments on "EDI" claims. Is prosthetics? (0 = No, 1 = Yes)';
COMMENT ON COLUMN trxaddl."IsOrthodontics" IS 'For formatting of ortho treatments on "EDI" claims. Is orthodontics? (0 = No, 1 = Yes)';
COMMENT ON COLUMN trxaddl."IsOrthoReplacement" IS 'For formatting of ortho treatments on "EDI" claims. Is ortho replacement? (0 = No, 1 = Yes if Ortho and replacement)';
COMMENT ON COLUMN trxaddl."IsInitialPlacement" IS 'For formatting of ortho treatments on "EDI" claims. Is initial placement? (0 = No, 1 = Yes if Crown and first one)';
COMMENT ON COLUMN trxaddl."InstitutionCode" IS 'Institutional code';
COMMENT ON COLUMN trxaddl."InitialPlacementDate" IS 'For formatting of ortho treatments on "EDI" claims. Date of initial placement';
COMMENT ON COLUMN trxaddl."Id" IS 'Primary key, unique ID of the transaction record (with Type and Treatment)';
COMMENT ON COLUMN trxaddl."DiagnosticCode" IS 'Diagnostic code';
COMMENT ON COLUMN trxaddl."ChartLnk" IS 'Id code of the dental chart record';
COMMENT ON COLUMN trxaddl."AdditionalSiteInfo" IS 'Additional site information.';


CREATE  TABLE trxarchamt (
  "Type" numeric(5,0) NOT NULL,
  "Id" numeric(10,0) NOT NULL,
  "Treatment" numeric(5,0) NOT NULL,
  "ArchivedAmt" numeric,
  CONSTRAINT trxarchamt_pk PRIMARY KEY ("Type", "Id", "Treatment")
) ;
COMMENT ON TABLE trxarchamt IS 'Archived Amount for a given patient / insurance payment';
COMMENT ON COLUMN trxarchamt."Type" IS 'Primary key component, transaction record type (3=Patient Payment, 4=Insurance Payment).';
COMMENT ON COLUMN trxarchamt."Treatment" IS 'Primary key component, transaction line number.';
COMMENT ON COLUMN trxarchamt."Id" IS 'Primary key component, unique ID of the transaction record. Sequence used depends on Type.';
COMMENT ON COLUMN trxarchamt."ArchivedAmt" IS 'Total archived amount, in dollars';


CREATE  TABLE trxcont (
  "OrigRecNo" numeric(10,0) NOT NULL,
  "Contract" numeric(10,0) NOT NULL,
  "Procedure" character(7),
  "Site" character(3),
  "TrxCont" numeric(10,0) NOT NULL,
  "ConsentType" numeric(5,0),
  "PtLetter" numeric(10,0),
  CONSTRAINT trxcont_primary PRIMARY KEY ("TrxCont")
) ;
CREATE INDEX IF NOT EXISTS trxcont_contract ON trxcont USING btree ("Contract") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS trxcont_origrecno ON trxcont USING btree ("OrigRecNo") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS trxcont_ptletter ON trxcont USING btree ("PtLetter") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS trxcont_trxprocedure ON trxcont USING btree ("OrigRecNo", "Procedure") TABLESPACE pg_default;
COMMENT ON TABLE trxcont IS 'Treatment Contracts / Consents';
COMMENT ON COLUMN trxcont."TrxCont" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN trxcont."Site" IS 'Site/tooth number of the treatment at the time the contract was signed.';
COMMENT ON COLUMN trxcont."PtLetter" IS 'If ConsentType=1, ptr to PTLETTER.PtLetter';
COMMENT ON COLUMN trxcont."Procedure" IS 'Procedure of the treatment at the time the contract was signed, ptr to PROCEDUR.Procedure.';
COMMENT ON COLUMN trxcont."OrigRecNo" IS 'Treatment that the contract is for, ptr to TRX.OrigRecNo.';
COMMENT ON COLUMN trxcont."Contract" IS 'Contract for the treatment, ptr to CONTRACT.Contract';
COMMENT ON COLUMN trxcont."ConsentType" IS 'Type of the consent (0=Online Consent, 1=Scanned-in Consent)';


CREATE  TABLE trxdep (
  "TrxDep" numeric(10,0) NOT NULL,
  "CatDed1" numeric,
  "CatDed2" numeric,
  "CatDed3" numeric,
  "ItemDed1" numeric,
  "ItemDed2" numeric,
  "ItemDed3" numeric,
  "Copay1" numeric,
  "Copay2" numeric,
  "Copay3" numeric,
  "ItemPtChg1" numeric,
  "ItemPtChg2" numeric,
  "ItemPtChg3" numeric,
  "DualDeductFlag1" numeric(5,0),
  "DualDeductFlag2" numeric(5,0),
  "DualDeductFlag3" numeric(5,0),
  "ExpectedDeduct" numeric,
  "FamDeduct1" numeric,
  "FamDeduct2" numeric,
  "FamDeduct3" numeric,
  "PatDeduct1" numeric,
  "PatDeduct2" numeric,
  "PatDeduct3" numeric,
  "EstimateF1" numeric(10,0),
  "EstimateF2" numeric(10,0),
  "EstimateF3" numeric(10,0),
  CONSTRAINT trxdep_primary PRIMARY KEY ("TrxDep")
) ;
COMMENT ON TABLE trxdep IS 'Treatment Deductables, Copays, Patient Charges, Estimates';
COMMENT ON COLUMN trxdep."TrxDep" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN trxdep."PatDeduct3" IS 'Patient deductable used for tertiary insurance policy, in dollars. ';
COMMENT ON COLUMN trxdep."PatDeduct2" IS 'Patient deductable used for secondary insurance policy, in dollars. ';
COMMENT ON COLUMN trxdep."PatDeduct1" IS 'Patient deductable used for primary insurance policy, in dollars. ';
COMMENT ON COLUMN trxdep."ItemPtChg3" IS 'Patient charge amount for tertiary insurance policy, in dollars.';
COMMENT ON COLUMN trxdep."ItemPtChg2" IS 'Patient charge amount for secondary insurance policy, in dollars.';
COMMENT ON COLUMN trxdep."ItemPtChg1" IS 'Patient charge amount for primary insurance policy, in dollars.';
COMMENT ON COLUMN trxdep."ItemDed3" IS 'Item deductible used for tertiary insurance policy, in dollars.';
COMMENT ON COLUMN trxdep."ItemDed2" IS 'Item deductible used for secondary insurance policy, in dollars.';
COMMENT ON COLUMN trxdep."ItemDed1" IS 'Item deductible used for primary insurance policy, in dollars.';
COMMENT ON COLUMN trxdep."FamDeduct3" IS 'Family deductable used for tertiary insurance policy, in dollars. ';
COMMENT ON COLUMN trxdep."FamDeduct2" IS 'Family deductable used for secondary insurance policy, in dollars. ';
COMMENT ON COLUMN trxdep."FamDeduct1" IS 'Family deductable used for primary insurance policy, in dollars. ';
COMMENT ON COLUMN trxdep."ExpectedDeduct" IS 'If smaller deductable was waived, the expected deductable amount, in dollars.';
COMMENT ON COLUMN trxdep."EstimateF3" IS 'Decimal value of binary string containing estimate flags for tertiary insurance.';
COMMENT ON COLUMN trxdep."EstimateF2" IS 'Decimal value of binary string containing estimate flags for secondary insurance.';
COMMENT ON COLUMN trxdep."EstimateF1" IS 'Decimal value of binary string containing estimate flags for primary insurance.';
COMMENT ON COLUMN trxdep."DualDeductFlag3" IS 'If patient has dual coverage with the tertiary insurance company, was the smaller deductable waived? (0=N/A, 1=No, 2=Yes)';
COMMENT ON COLUMN trxdep."DualDeductFlag2" IS 'If patient has dual coverage with the secondary insurance company, was the smaller deductable waived? (0=N/A, 1=No, 2=Yes)';
COMMENT ON COLUMN trxdep."DualDeductFlag1" IS 'If patient has dual coverage with the primary insurance company, was the smaller deductable waived? (0=N/A, 1=No, 2=Yes)';
COMMENT ON COLUMN trxdep."Copay3" IS 'Copay amount billed to patient for tertiary insurance policy, in dollars.';
COMMENT ON COLUMN trxdep."Copay2" IS 'Copay amount billed to patient for secondary insurance policy, in dollars.';
COMMENT ON COLUMN trxdep."Copay1" IS 'Copay amount billed to patient for primary insurance policy, in dollars.';
COMMENT ON COLUMN trxdep."CatDed3" IS 'Category deductable used for tertiary insurance policy, in dollars.';
COMMENT ON COLUMN trxdep."CatDed2" IS 'Category deductable used for secondary insurance policy, in dollars.';
COMMENT ON COLUMN trxdep."CatDed1" IS 'Category deductable used for primary insurance policy, in dollars.';


CREATE  TABLE trxedimax (
  "Id" numeric(10,0) NOT NULL DEFAULT 0,
  "MaxEDI" character varying(15),
  CONSTRAINT trxedimax_pk PRIMARY KEY ("Id")
) ;
COMMENT ON TABLE trxedimax IS 'Table for storing the maximum "EDI" number for generating the next batch number.';
COMMENT ON COLUMN trxedimax."MaxEDI" IS 'The max "EDI" number from the TRX table';
COMMENT ON COLUMN trxedimax."Id" IS 'Primary Key component';


CREATE  TABLE trxgrade (
  "Type" numeric(5,0) NOT NULL,
  "Id" numeric(10,0) NOT NULL,
  "Treatment" numeric(5,0) NOT NULL,
  "Grading" numeric(10,0) NOT NULL,
  "Status" numeric(5,0),
  CONSTRAINT trxgrade_primary PRIMARY KEY ("Type", "Id", "Treatment", "Grading")
) ;
CREATE INDEX IF NOT EXISTS trxgrade_grading ON trxgrade USING btree ("Grading") TABLESPACE pg_default;
COMMENT ON TABLE trxgrade IS 'Contains many to many relationships between TRX and GRADING ';
COMMENT ON COLUMN trxgrade."Type" IS 'Primary key component, ptr to the TRX.Type of a treatment being graded. ';
COMMENT ON COLUMN trxgrade."Treatment" IS 'Primary key component, ptr to the TRX.Treatment of a treatment being graded. ';
COMMENT ON COLUMN trxgrade."Status" IS 'Does the grading form contain a Tx-specific question for this treatment? (0=No, 1=Yes)';
COMMENT ON COLUMN trxgrade."Id" IS 'Primary key component, ptr to the TRX.Id of a treatment being graded. ';
COMMENT ON COLUMN trxgrade."Grading" IS 'Primary key component, evaluation that this record is for. Ptr to GRADING.Grading.';


CREATE  TABLE trxmed (
  "Patient" numeric(10,0),
  "Type" numeric(5,0) NOT NULL,
  "Id" numeric(10,0) NOT NULL,
  "Treatment" numeric(5,0) NOT NULL,
  "ICDCode1" character(10),
  "ICDCode2" character(10),
  "ICDCode3" character(10),
  "ICDCode4" character(10),
  "ICDIsTx1" numeric(5,0),
  "ICDIsTx2" numeric(5,0),
  "ICDIsTx3" numeric(5,0),
  "ICDIsTx4" numeric(5,0),
  "PlaceCode" character(6),
  "Modifier" character(2),
  "DateTo" timestamp without time zone,
  "Modifier2" character(2),
  "AnesMin" numeric(5,0),
  "Referral" numeric(10,0),
  "ChartLnk" numeric(10,0) NOT NULL,
  "ICDType" numeric(5,0),
  "IsAccident" numeric(5,0) NOT NULL DEFAULT 0,
  "ICDCode5" character(10),
  "ICDCode6" character(10),
  "ICDCode7" character(10),
  "ICDCode8" character(10),
  "ICDCode9" character(10),
  "ICDCode10" character(10),
  "ICDCode11" character(10),
  "ICDCode12" character(10),
  "ICDIsTx5" numeric(5,0) NOT NULL DEFAULT 0,
  "ICDIsTx6" numeric(5,0) NOT NULL DEFAULT 0,
  "ICDIsTx7" numeric(5,0) NOT NULL DEFAULT 0,
  "ICDIsTx8" numeric(5,0) NOT NULL DEFAULT 0,
  "ICDIsTx9" numeric(5,0) NOT NULL DEFAULT 0,
  "ICDIsTx10" numeric(5,0) NOT NULL DEFAULT 0,
  "ICDIsTx11" numeric(5,0) NOT NULL DEFAULT 0,
  "ICDIsTx12" numeric(5,0) NOT NULL DEFAULT 0,
  "Modifier3" character(2),
  "Modifier4" character(2),
  CONSTRAINT trxmed_primary PRIMARY KEY ("Type", "Id", "Treatment", "ChartLnk")
) ;
CREATE INDEX IF NOT EXISTS trxmed_patientkey ON trxmed USING btree ("Patient", "Type", "Id", "Treatment") TABLESPACE pg_default;
COMMENT ON TABLE trxmed IS 'Transaction medical information record';
COMMENT ON COLUMN trxmed."Type" IS 'Type of TRX record';
COMMENT ON COLUMN trxmed."Treatment" IS 'Treatment (#) of Trx record';
COMMENT ON COLUMN trxmed."Referral" IS 'Id code of the referral source';
COMMENT ON COLUMN trxmed."PlaceCode" IS 'Place of service code, ptr to PLACEOS.Code';
COMMENT ON COLUMN trxmed."Patient" IS 'Patient Id';
COMMENT ON COLUMN trxmed."Modifier4" IS 'Modifier code #4 for the procedure, ptr to MODIFIER.Code';
COMMENT ON COLUMN trxmed."Modifier3" IS 'Modifier code #3 for the procedure, ptr to MODIFIER.Code';
COMMENT ON COLUMN trxmed."Modifier2" IS 'Modifier code #2 for the procedure, ptr to MODIFIER.Code';
COMMENT ON COLUMN trxmed."Modifier" IS 'Modifier code #1 for the procedure, ptr to MODIFIER.Code';
COMMENT ON COLUMN trxmed."IsAccident" IS 'Dutch Only (0 = No, 1 = Yes, 2 = Don''t know)';
COMMENT ON COLUMN trxmed."Id" IS 'Id of TRX record';
COMMENT ON COLUMN trxmed."ICDType" IS 'Default type of ICD diagnosis code to use (0=ICD-9, 1=ICD-10) ';
COMMENT ON COLUMN trxmed."ICDIsTx9" IS 'Diagnostic code #9 applies to this treatment (0 = No, 1 = Yes)';
COMMENT ON COLUMN trxmed."ICDIsTx8" IS 'Diagnostic code #8 applies to this treatment (0 = No, 1 = Yes)';
COMMENT ON COLUMN trxmed."ICDIsTx7" IS 'Diagnostic code #7 applies to this treatment (0 = No, 1 = Yes)';
COMMENT ON COLUMN trxmed."ICDIsTx6" IS 'Diagnostic code #6 applies to this treatment (0 = No, 1 = Yes)';
COMMENT ON COLUMN trxmed."ICDIsTx5" IS 'Diagnostic code #5 applies to this treatment (0 = No, 1 = Yes)';
COMMENT ON COLUMN trxmed."ICDIsTx4" IS 'Diagnostic code #4 applies to this treatment (0 = No, 1 = Yes)';
COMMENT ON COLUMN trxmed."ICDIsTx3" IS 'Diagnostic code #3 applies to this treatment (0 = No, 1 = Yes)';
COMMENT ON COLUMN trxmed."ICDIsTx2" IS 'Diagnostic code #2 applies to this treatment (0 = No, 1 = Yes)';
COMMENT ON COLUMN trxmed."ICDIsTx12" IS 'Diagnostic code #12 applies to this treatment (0 = No, 1 = Yes)';
COMMENT ON COLUMN trxmed."ICDIsTx11" IS 'Diagnostic code #11 applies to this treatment (0 = No, 1 = Yes)';
COMMENT ON COLUMN trxmed."ICDIsTx10" IS 'Diagnostic code #10 applies to this treatment (0 = No, 1 = Yes)';
COMMENT ON COLUMN trxmed."ICDIsTx1" IS 'Diagnostic code #1 applies to this treatment (0 = No, 1 = Yes)';
COMMENT ON COLUMN trxmed."ICDCode9" IS 'Diagnostic code #9';
COMMENT ON COLUMN trxmed."ICDCode8" IS 'Diagnostic code #8';
COMMENT ON COLUMN trxmed."ICDCode7" IS 'Diagnostic code #7';
COMMENT ON COLUMN trxmed."ICDCode6" IS 'Diagnostic code #6';
COMMENT ON COLUMN trxmed."ICDCode5" IS 'Diagnostic code #5';
COMMENT ON COLUMN trxmed."ICDCode4" IS 'Diagnostic code #4';
COMMENT ON COLUMN trxmed."ICDCode3" IS 'Diagnostic code #3';
COMMENT ON COLUMN trxmed."ICDCode2" IS 'Diagnostic code #2';
COMMENT ON COLUMN trxmed."ICDCode12" IS 'Diagnostic code #12';
COMMENT ON COLUMN trxmed."ICDCode11" IS 'Diagnostic code #11';
COMMENT ON COLUMN trxmed."ICDCode10" IS 'Diagnostic code #10';
COMMENT ON COLUMN trxmed."ICDCode1" IS 'Diagnostic code #1';
COMMENT ON COLUMN trxmed."DateTo" IS 'Tx EndDate of the current procedure (defaulted to TxDate of the Trx record)';
COMMENT ON COLUMN trxmed."ChartLnk" IS 'Id code of the dental chart record';
COMMENT ON COLUMN trxmed."AnesMin" IS 'Number of anaesthetic minutes administered per treatment. Related to NEIC and "EDI" only.';


CREATE  TABLE trxpol (
  "TrxPol" numeric(10,0) NOT NULL,
  "PolicyId" numeric(10,0),
  "Type" numeric(5,0),
  "Id" numeric(10,0),
  "Treatment" numeric(5,0),
  "PreAuth" character varying(20),
  "PreAuthStartDate" timestamp without time zone,
  "PreAuthEndDate" timestamp without time zone,
  "SubmitDate" timestamp without time zone,
  "Submitted" numeric(5,0),
  "Received" numeric(5,0),
  "ReceiveDate" timestamp without time zone,
  "Denied" numeric(5,0),
  "ServAuthException" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT trxpol_primary PRIMARY KEY ("TrxPol")
) ;
CREATE INDEX IF NOT EXISTS trxpol_preauth ON trxpol USING btree ("PreAuth") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS trxpol_trxkey ON trxpol USING btree ("Type", "Id", "Treatment") TABLESPACE pg_default;
COMMENT ON TABLE trxpol IS 'Policy submission information ';
COMMENT ON COLUMN trxpol."Type" IS 'Transaction type, ptr to TRX.Type';
COMMENT ON COLUMN trxpol."TrxPol" IS 'Id code to identify this TrxPol record';
COMMENT ON COLUMN trxpol."Treatment" IS 'Treatment, ptr to TRX.Treatment';
COMMENT ON COLUMN trxpol."Submitted" IS 'Claim submitted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN trxpol."SubmitDate" IS 'Date the claim was submitted';
COMMENT ON COLUMN trxpol."ServAuthException" IS 'Authorization exception (0 = No, 1 = Yes)';
COMMENT ON COLUMN trxpol."Received" IS 'Preauthorization received? (0 = No, 1 = Yes)';
COMMENT ON COLUMN trxpol."ReceiveDate" IS 'Date the preauthorization was entered into the system';
COMMENT ON COLUMN trxpol."PreAuthStartDate" IS 'Effective date of the preauthorization';
COMMENT ON COLUMN trxpol."PreAuthEndDate" IS 'Expiry date of the preauthorization';
COMMENT ON COLUMN trxpol."PreAuth" IS 'Preauthorization number';
COMMENT ON COLUMN trxpol."PolicyId" IS 'Id code of the policy to which this record applies, ptr to POLICY.PolicyId';
COMMENT ON COLUMN trxpol."Id" IS 'Transaction Id, ptr to TRX.Id';
COMMENT ON COLUMN trxpol."Denied" IS 'Preauthorization denied? (0=No (accepted), 1=Yes (denied entirely, rebill to patient), 2=Accepted as university claim - DentiCal only)';
COMMENT ON COLUMN trxpol."Audit" IS 'Audit record for this history, ptr to AUDITHIS.Audit';


CREATE  TABLE trxpolh (
  "TrxPolH" numeric(10,0) NOT NULL,
  "TrxPol" numeric(10,0) NOT NULL,
  "PolicyId" numeric(10,0),
  "Type" numeric(5,0),
  "Id" numeric(10,0),
  "Treatment" numeric(5,0),
  "PreAuth" character varying(20),
  "PreAuthStartDate" timestamp without time zone,
  "PreAuthEndDate" timestamp without time zone,
  "SubmitDate" timestamp without time zone,
  "Submitted" numeric(5,0),
  "Received" numeric(5,0),
  "ReceiveDate" timestamp without time zone,
  "Denied" numeric(5,0),
  "ServAuthException" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT trxpolh_primary PRIMARY KEY ("TrxPolH")
) ;
CREATE INDEX IF NOT EXISTS trxpolh_trxpol ON trxpolh USING btree ("TrxPol") TABLESPACE pg_default;
COMMENT ON TABLE trxpolh IS 'History of Policy Submissions';
COMMENT ON COLUMN trxpolh."Type" IS 'Transaction type, ptr to TRX.Type';
COMMENT ON COLUMN trxpolh."TrxPolH" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN trxpolh."TrxPol" IS 'Policy submission that the history is for, ptr to TRXPOL.TrxPol';
COMMENT ON COLUMN trxpolh."Treatment" IS 'Treatment, ptr to TRX.Treatment';
COMMENT ON COLUMN trxpolh."Submitted" IS 'Claim submitted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN trxpolh."SubmitDate" IS 'Date the claim was submitted';
COMMENT ON COLUMN trxpolh."ServAuthException" IS 'Authorization exception (0 = No, 1 = Yes)';
COMMENT ON COLUMN trxpolh."Received" IS 'Preauthorization received? (0 = No, 1 = Yes)';
COMMENT ON COLUMN trxpolh."ReceiveDate" IS 'Date the preauthorization was entered into the system';
COMMENT ON COLUMN trxpolh."PreAuthStartDate" IS 'Effective date of the preauthorization';
COMMENT ON COLUMN trxpolh."PreAuthEndDate" IS 'Expiry date of the preauthorization';
COMMENT ON COLUMN trxpolh."PreAuth" IS 'Preauthorization number';
COMMENT ON COLUMN trxpolh."PolicyId" IS 'Id code of the policy to which this record applies, ptr to POLICY.PolicyId';
COMMENT ON COLUMN trxpolh."Id" IS 'Transaction Id, ptr to TRX.Id';
COMMENT ON COLUMN trxpolh."Denied" IS 'Preauthorization denied? (0 = No, 1 = Yes)';
COMMENT ON COLUMN trxpolh."Audit" IS 'Audit record for this history, ptr to AUDITHIS.Audit';


CREATE  TABLE tx_audit (
  "AuditDate" timestamp without time zone NOT NULL,
  CONSTRAINT tx_audit_primary PRIMARY KEY ("AuditDate")
) ;
COMMENT ON TABLE tx_audit IS 'Stores earliest modified date';
COMMENT ON COLUMN tx_audit."AuditDate" IS 'For clients prior to 1.73.30, the date they first upgrade to 1.73.30. For all other clients, the earliest modified date in the HISTORY table';


CREATE  TABLE txcust (
  "Treatme2" numeric(10,0) NOT NULL,
  "TxQuest" numeric(10,0) NOT NULL,
  "Item" numeric(5,0),
  "Heading" character(12),
  "Question" character varying(20),
  "ResponseType" numeric(5,0),
  "RespCode" numeric(5,0),
  "Response" character varying(30),
  "Deleted" numeric(5,0),
  CONSTRAINT txcust_primary PRIMARY KEY ("Treatme2", "TxQuest")
) ;
COMMENT ON TABLE txcust IS 'Custom questions for Ortho treatments';
COMMENT ON COLUMN txcust."TxQuest" IS 'Ortho custom field responded to';
COMMENT ON COLUMN txcust."Treatme2" IS 'Identifies a TREATME2 record that the TXCUST is linked to';
COMMENT ON COLUMN txcust."ResponseType" IS 'Resposne type (0=Yes/No, 1=Date,2=Free Text, 3=Ortho Custom Lists, 4= axiUm codes)';
COMMENT ON COLUMN txcust."Response" IS 'Response entered (could be Yes/No, Date, Free Text or response code)';
COMMENT ON COLUMN txcust."RespCode" IS 'Response code ';
COMMENT ON COLUMN txcust."Question" IS 'Field Prompt or Question';
COMMENT ON COLUMN txcust."Item" IS 'Number to indicate the order in which this item should appear in the window ';
COMMENT ON COLUMN txcust."Heading" IS 'Text to display in the tretament hsitory window as a title for this column';
COMMENT ON COLUMN txcust."Deleted" IS 'Record is deleted? (0 = No, 1 = Yes) ';


CREATE  TABLE txdiag (
  "ChartTrx" numeric(10,0) NOT NULL,
  "DiagCode" character(8) NOT NULL,
  CONSTRAINT txdiag_primary PRIMARY KEY ("ChartTrx", "DiagCode")
) ;
COMMENT ON TABLE txdiag IS 'Treatment Diagnoses';
COMMENT ON COLUMN txdiag."DiagCode" IS 'Primary key component, diagnosis code for this treatment. Ptr to DIAGCODE.DiagCode';
COMMENT ON COLUMN txdiag."ChartTrx" IS 'Primary key component, link to treatment on chart. Ptr to TREATME2.Auto';


CREATE  TABLE txhvacc (
  "TxHView" numeric(10,0) NOT NULL,
  "SLevel" numeric(10,0) NOT NULL,
  "Access" numeric(5,0),
  CONSTRAINT txhvacc_primary PRIMARY KEY ("TxHView", "SLevel")
) ;
COMMENT ON TABLE txhvacc IS 'Tx History View Access';
COMMENT ON COLUMN txhvacc."TxHView" IS 'Primary key component, the Tx History View that access is being defined for. Ptr to TXHVIEW.TxHView';
COMMENT ON COLUMN txhvacc."SLevel" IS 'Primary key component, the security level that access is being defined for. Ptr to SLEVEL.SLevel';
COMMENT ON COLUMN txhvacc."Access" IS 'Can the security level access this view? (0=No, 1=Yes)';


CREATE  TABLE txhvdisc (
  "TxHView" numeric(10,0) NOT NULL,
  "Discipline" character(15) NOT NULL,
  CONSTRAINT txhvdisc_primary PRIMARY KEY ("TxHView", "Discipline")
) ;
COMMENT ON TABLE txhvdisc IS 'Tx History View Disciplines';
COMMENT ON COLUMN txhvdisc."TxHView" IS 'Primary key component, the Tx History View that displays the discipline. Ptr to TXHVIEW.TxHView';
COMMENT ON COLUMN txhvdisc."Discipline" IS 'Primary key component, the discipline to display. Ptr to CLASS.Class';


CREATE  TABLE txhvhide (
  "TxHView" numeric(10,0) NOT NULL,
  "ColIndex" numeric(10,0) NOT NULL,
  CONSTRAINT txhvhide_primary PRIMARY KEY ("TxHView", "ColIndex")
) ;
COMMENT ON TABLE txhvhide IS 'Tx History View Hidden Columns';
COMMENT ON COLUMN txhvhide."TxHView" IS 'Primary key component, the Tx History View that contains the column. Ptr to TXHVIEW.TxHView';
COMMENT ON COLUMN txhvhide."ColIndex" IS 'Primary key component, the index number fo the column to be hidden.';


CREATE  TABLE txhview (
  "TxHView" numeric(10,0) NOT NULL,
  "Description" character varying(30),
  "ShowStsE" numeric(5,0),
  "ShowStsP" numeric(5,0),
  "ShowStsI" numeric(5,0),
  "ShowStsC" numeric(5,0),
  "ShowStsA" numeric(5,0),
  "ShowStsV" numeric(5,0),
  "ShowStrikeouts" numeric(5,0),
  "ShowDeleted" numeric(5,0),
  "ShowNotesByMod" numeric(5,0),
  "ShowFullNotes" numeric(5,0),
  "ShowSteps" numeric(5,0),
  "ShowAppts" numeric(5,0),
  "ShowRecalls" numeric(5,0),
  "PhaseFrom" character(2),
  "PhaseTo" character(2),
  "DateFrom" numeric(5,0),
  "DateFromType" numeric(5,0),
  "DateTo" numeric(5,0),
  "DateToType" numeric(5,0),
  "Sort1" numeric(5,0),
  "Sort2" numeric(5,0),
  "SortPToEnd" numeric(5,0),
  "ShowNotes" numeric(5,0),
  "Sort3" numeric(5,0),
  "ShowForms" numeric(5,0),
  "AppUserFormat" numeric(5,0),
  "ListTxByAppoint" numeric(5,0),
  "SortTxNotesByTx" numeric(5,0),
  "HideInactive" numeric(5,0) DEFAULT 0,
  CONSTRAINT txhview_primary PRIMARY KEY ("TxHView")
) ;
COMMENT ON TABLE txhview IS 'Tx History Views';
COMMENT ON COLUMN txhview."TxHView" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN txhview."SortTxNotesByTx" IS 'Sort treatment notes under each treatment? (0=No, 1=Yes)';
COMMENT ON COLUMN txhview."SortPToEnd" IS 'Sort planned activity to the end of the list? (0=No, 1=Yes)';
COMMENT ON COLUMN txhview."Sort3" IS 'Tertiary sort (0=Date, 1=Phase, 2=Procedure, 3=Site, 4=Entry Time, 5=Treatment/Note1 custom field, 6=Treatment/Note2 custom field)';
COMMENT ON COLUMN txhview."Sort2" IS 'Secondary sort (0=Date, 1=Phase, 2=Procedure, 3=Site, 4=Entry Time, 5=Treatment/Note1 custom field, 6=Treatment/Note2 custom field)';
COMMENT ON COLUMN txhview."Sort1" IS 'Primary sort (0=Date, 1=Phase, 2=Site, 3=Treatment/Note1 custom field, 4=Treatment/Note2 custom field)';
COMMENT ON COLUMN txhview."ShowStsV" IS 'Show Ortho Visits? (0=No, 1=Yes)';
COMMENT ON COLUMN txhview."ShowStsP" IS 'Show Planned treatments? (0=No, 1=Yes)';
COMMENT ON COLUMN txhview."ShowStsI" IS 'Show In-Progress treatments? (0=No, 1=Yes)';
COMMENT ON COLUMN txhview."ShowStsE" IS 'Show Pre-Exisiting treatments? (0=No, 1=Yes)';
COMMENT ON COLUMN txhview."ShowStsC" IS 'Show Completed treatments? (0=No, 1=Yes)';
COMMENT ON COLUMN txhview."ShowStsA" IS 'Show Conditions? (0=No, 1=Yes)';
COMMENT ON COLUMN txhview."ShowStrikeouts" IS 'Show Strike-out lines? (0=No, 1=Yes)';
COMMENT ON COLUMN txhview."ShowSteps" IS 'Show steps? (0=No, 1=Yes)';
COMMENT ON COLUMN txhview."ShowRecalls" IS 'Show Recalls? (0=No, 1=Yes)';
COMMENT ON COLUMN txhview."ShowNotesByMod" IS 'Show notes by module? (0=No, 1=Yes)';
COMMENT ON COLUMN txhview."ShowNotes" IS 'Show notes? (0=No, 1=Yes)';
COMMENT ON COLUMN txhview."ShowFullNotes" IS 'Show full notes? (0=No, 1=Yes)';
COMMENT ON COLUMN txhview."ShowForms" IS 'Show Treatment Forms? (0=No, 1=Yes)';
COMMENT ON COLUMN txhview."ShowDeleted" IS 'Show deleted items? (0=No, 1=Yes)';
COMMENT ON COLUMN txhview."ShowAppts" IS 'Show Appointments? (0=No, 1=Yes)';
COMMENT ON COLUMN txhview."PhaseTo" IS 'The phase to show records to ';
COMMENT ON COLUMN txhview."PhaseFrom" IS 'The phase to show records from';
COMMENT ON COLUMN txhview."ListTxByAppoint" IS 'Show appointment treatments? (0=No, 1=Yes)';
COMMENT ON COLUMN txhview."HideInactive" IS 'Hide Inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN txhview."Description" IS 'Name for the view. This MUST be a unique name.';
COMMENT ON COLUMN txhview."DateToType" IS 'Used with DateTo, indicates the time period (0=Days, 1= Months, 2=Years)';
COMMENT ON COLUMN txhview."DateTo" IS 'Used with DateToType, indicates the amount of time to which to show records';
COMMENT ON COLUMN txhview."DateFromType" IS 'Used with DateFrom, indicates the time period (0=Days, 1= Months, 2=Years)';
COMMENT ON COLUMN txhview."DateFrom" IS 'Used with DateFromType, indicates the amount of time from which to show records';
COMMENT ON COLUMN txhview."AppUserFormat" IS 'Show approval user credentials? (0=No, 1=Yes)';


CREATE  TABLE txhvmod (
  "TxHView" numeric(10,0) NOT NULL,
  "Module" numeric(5,0) NOT NULL,
  "Order" numeric(5,0),
  CONSTRAINT txhvmod_primary PRIMARY KEY ("TxHView", "Module")
) ;
COMMENT ON TABLE txhvmod IS 'Tx History View Order by Module ';
COMMENT ON COLUMN txhvmod."TxHView" IS 'Primary key component, the Tx History View that this ordering is for. Ptr to TXHVIEW.TxHView';
COMMENT ON COLUMN txhvmod."Order" IS 'Order in which to display the view (0=First, 1=Second...)';
COMMENT ON COLUMN txhvmod."Module" IS 'Primary key component, the module this view belongs to (0=EHR, 1=Ortho, 2=Perio)';


CREATE  TABLE txpdx (
  "TxPDx" numeric(10,0) NOT NULL,
  "TxPlan" numeric(10,0),
  "DiagCode" character(8),
  "Description" character varying(255),
  "ShortDesc" character varying(20),
  "Note" character varying(4000),
  "Order" numeric(5,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT txpdx_primary PRIMARY KEY ("TxPDx")
) ;
CREATE INDEX IF NOT EXISTS txpdx_txplan ON txpdx USING btree ("TxPlan", "Order") TABLESPACE pg_default;
COMMENT ON TABLE txpdx IS 'Treatment Plan Diagnoses';
COMMENT ON COLUMN txpdx."TxPlan" IS 'Treatment plan containing this diagnosis, ptr to TXPLAN.TxPlan';
COMMENT ON COLUMN txpdx."TxPDx" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN txpdx."ShortDesc" IS 'Short description of the diagnosis code to show in the list';
COMMENT ON COLUMN txpdx."Order" IS 'Order that the diagnosis appears in the list';
COMMENT ON COLUMN txpdx."Note" IS 'Diagnosis note';
COMMENT ON COLUMN txpdx."DiagCode" IS 'Diagnosis code, ptr to DIAGCODE.DiagCode';
COMMENT ON COLUMN txpdx."Description" IS 'Description of the diagnosis code';
COMMENT ON COLUMN txpdx."Deleted" IS 'Is this treatment plan diagnosis deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN txpdx."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE txpdxh (
  "TxPDxH" numeric(10,0) NOT NULL,
  "TxPDx" numeric(10,0),
  "TxPlan" numeric(10,0),
  "DiagCode" character(8),
  "Description" character varying(255),
  "ShortDesc" character varying(20),
  "Note" character varying(4000),
  "Order" numeric(5,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT txpdxh_primary PRIMARY KEY ("TxPDxH")
) ;
CREATE INDEX IF NOT EXISTS txpdxh_txpdx ON txpdxh USING btree ("TxPDx") TABLESPACE pg_default;
COMMENT ON TABLE txpdxh IS 'Treatment Plan Diagnosis History';
COMMENT ON COLUMN txpdxh."TxPlan" IS 'Treatment plan containing this diagnosis, ptr to TXPLAN.TxPlan';
COMMENT ON COLUMN txpdxh."TxPDxH" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN txpdxh."TxPDx" IS 'Treatment plan diagnosis that this history is for, ptr to TXPDX.TxPDx';
COMMENT ON COLUMN txpdxh."ShortDesc" IS 'Short description of the diagnosis code to show in the list';
COMMENT ON COLUMN txpdxh."Order" IS 'Order that the diagnosis appears in the list';
COMMENT ON COLUMN txpdxh."Note" IS 'Diagnosis note';
COMMENT ON COLUMN txpdxh."DiagCode" IS 'Diagnosis code, ptr to DIAGCODE.DiagCode';
COMMENT ON COLUMN txpdxh."Description" IS 'Description of the diagnosis code';
COMMENT ON COLUMN txpdxh."Deleted" IS 'Is this treatment plan diagnosis deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN txpdxh."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE txpdxtx (
  "TxPDx" numeric(10,0) NOT NULL,
  "TxPTx" numeric(10,0) NOT NULL,
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT txpdxtx_primary PRIMARY KEY ("TxPDx", "TxPTx")
) ;
CREATE INDEX IF NOT EXISTS txpdxtx_txptx ON txpdxtx USING btree ("TxPTx") TABLESPACE pg_default;
COMMENT ON TABLE txpdxtx IS 'Treatment Plan Diagnoses linked to Treatment Plan Treatments';
COMMENT ON COLUMN txpdxtx."TxPTx" IS 'Primary key component, linked treatment plan treatment. Ptr to TXPTX.TxPTx';
COMMENT ON COLUMN txpdxtx."TxPDx" IS 'Primary key component, linked treatment plan diagnosis. Ptr to TXPDX.TxPDx';
COMMENT ON COLUMN txpdxtx."Deleted" IS 'Is this link deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN txpdxtx."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE txpdxtxh (
  "TxPDxTxH" numeric(10,0) NOT NULL,
  "TxPDx" numeric(10,0),
  "TxPTx" numeric(10,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT txpdxtxh_primary PRIMARY KEY ("TxPDxTxH")
) ;
CREATE INDEX IF NOT EXISTS txpdxtxh_txpdxtx ON txpdxtxh USING btree ("TxPDx", "TxPTx") TABLESPACE pg_default;
COMMENT ON TABLE txpdxtxh IS 'History of Treatment Plan Diagnoses linked to Treatment Plan Treatments';
COMMENT ON COLUMN txpdxtxh."TxPTx" IS 'Linked treatment plan treatment. Ptr to TXPTX.TxPTx';
COMMENT ON COLUMN txpdxtxh."TxPDxTxH" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN txpdxtxh."TxPDx" IS 'Linked treatment plan diagnosis. Ptr to TXPDX.TxPDx';
COMMENT ON COLUMN txpdxtxh."Deleted" IS 'Is this link deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN txpdxtxh."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE txplan (
  "TxPlan" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "Description" character varying(30),
  "ChiefConcern" character varying(255),
  "Inactive" numeric(5,0),
  "InactiveReason" character varying(4000),
  "InactiveAppUser" numeric(10,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT txplan_primary PRIMARY KEY ("TxPlan")
) ;
CREATE INDEX IF NOT EXISTS txplan_patient ON txplan USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE txplan IS 'Treatment Plans';
COMMENT ON COLUMN txplan."TxPlan" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN txplan."Patient" IS 'Patient that the treatment plan is for, ptr to PATIENT.Patient';
COMMENT ON COLUMN txplan."InactiveReason" IS 'If Inactive=1, the reason that this treatment plan is inactive. ';
COMMENT ON COLUMN txplan."InactiveAppUser" IS 'If Inactive=1, the user that approved making it inactive. Ptr to USERS.User';
COMMENT ON COLUMN txplan."Inactive" IS 'Is this treatment plan inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN txplan."Description" IS 'Short description or name of the treament plan.';
COMMENT ON COLUMN txplan."Deleted" IS 'Is this treatment plan deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN txplan."ChiefConcern" IS 'Patient''s chief concerns';
COMMENT ON COLUMN txplan."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE txplanh (
  "TxPlanH" numeric(10,0) NOT NULL,
  "TxPlan" numeric(10,0),
  "Patient" numeric(10,0),
  "Description" character varying(30),
  "ChiefConcern" character varying(255),
  "Inactive" numeric(5,0),
  "InactiveReason" character varying(4000),
  "InactiveAppUser" numeric(10,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT txplanh_primary PRIMARY KEY ("TxPlanH")
) ;
CREATE INDEX IF NOT EXISTS txplanh_txplan ON txplanh USING btree ("TxPlan") TABLESPACE pg_default;
COMMENT ON TABLE txplanh IS 'Treatment Plan History';
COMMENT ON COLUMN txplanh."TxPlanH" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN txplanh."TxPlan" IS 'Treatment plan that this history is for, ptr to TXPLAN.TxPlan';
COMMENT ON COLUMN txplanh."Patient" IS 'Patient that the treatment plan is for, ptr to PATIENT.Patient';
COMMENT ON COLUMN txplanh."InactiveReason" IS 'If Inactive=1, the reason that this treatment plan is inactive. ';
COMMENT ON COLUMN txplanh."InactiveAppUser" IS 'If Inactive=1, the user that approved making it inactive. Ptr to USERS.User';
COMMENT ON COLUMN txplanh."Inactive" IS 'Is this treatment plan inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN txplanh."Description" IS 'Short description or name of the treament plan.';
COMMENT ON COLUMN txplanh."Deleted" IS 'Is this treatment plan deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN txplanh."ChiefConcern" IS 'Patient''s chief concerns';
COMMENT ON COLUMN txplanh."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE txplncon (
  "TxPlan" numeric(10,0) NOT NULL,
  "Contract" numeric(10,0) NOT NULL,
  CONSTRAINT txplncon_primary PRIMARY KEY ("TxPlan", "Contract")
) ;
COMMENT ON TABLE txplncon IS 'Treatment Plan Contracts';
COMMENT ON COLUMN txplncon."TxPlan" IS 'Primary key component, ID code of the treatment plan. Ptr to TXPLAN.TxPlan';
COMMENT ON COLUMN txplncon."Contract" IS 'Primary key component, ID code of the contract. Ptr to CONTRACT.Contract';


CREATE  TABLE txpnohis (
  "TxPNoteHistory" numeric(10,0) NOT NULL,
  "TxPNote" numeric(10,0),
  "Patient" numeric(10,0),
  "TxPlan" numeric(10,0),
  "Date" timestamp without time zone,
  "Code" character(6),
  "Text" character varying(4000),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT txpnohis_primary PRIMARY KEY ("TxPNoteHistory")
) ;
CREATE INDEX IF NOT EXISTS txpnohis_txpnote ON txpnohis USING btree ("TxPNote") TABLESPACE pg_default;
COMMENT ON TABLE txpnohis IS 'Treatment Plan Note History';
COMMENT ON COLUMN txpnohis."TxPlan" IS 'ID code of the treatment plan. Ptr to TXPLAN.TxPlan';
COMMENT ON COLUMN txpnohis."TxPNoteHistory" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN txpnohis."TxPNote" IS 'Treatment plan note that this history is for, ptr to TXPNOTE.TxPNote';
COMMENT ON COLUMN txpnohis."Text" IS 'Text of the note.';
COMMENT ON COLUMN txpnohis."Patient" IS 'ID code of the patient, ptr to PATIENT.Patient';
COMMENT ON COLUMN txpnohis."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN txpnohis."Date" IS 'Date of entry';
COMMENT ON COLUMN txpnohis."Code" IS 'ID code of the predefined note, ptr to TXPNOCD.Code';
COMMENT ON COLUMN txpnohis."Audit" IS 'Audit record, ptr to AUDITHIS.Audit';


CREATE  TABLE txpnote (
  "TxPNote" numeric(10,0) NOT NULL,
  "Patient" numeric(10,0),
  "TxPlan" numeric(10,0),
  "Date" timestamp without time zone,
  "Code" character(6),
  "Text" character varying(4000),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT txpnote_primary PRIMARY KEY ("TxPNote")
) ;
CREATE INDEX IF NOT EXISTS txpnote_patient ON txpnote USING btree ("Patient") TABLESPACE pg_default;
COMMENT ON TABLE txpnote IS 'Treatment Plan Notes';
COMMENT ON COLUMN txpnote."TxPlan" IS 'ID code of the treatment plan. Ptr to TXPLAN.TxPlan';
COMMENT ON COLUMN txpnote."TxPNote" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN txpnote."Text" IS 'Text of the note.';
COMMENT ON COLUMN txpnote."Patient" IS 'ID code of the patient, ptr to PATIENT.Patient';
COMMENT ON COLUMN txpnote."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN txpnote."Date" IS 'Date of entry';
COMMENT ON COLUMN txpnote."Code" IS 'ID code of the predefined note, ptr to TXPNOCD.Code';
COMMENT ON COLUMN txpnote."Audit" IS 'Audit record, ptr to AUDITHIS.Audit';


CREATE  TABLE txpopap (
  "TxPOpt" numeric(10,0) NOT NULL,
  "ConsultantType" numeric(5,0) NOT NULL,
  "AppUser" numeric(10,0),
  "AppDateTime" timestamp without time zone,
  "Approved" numeric(5,0),
  CONSTRAINT txpopap_primary PRIMARY KEY ("TxPOpt", "ConsultantType")
) ;
COMMENT ON TABLE txpopap IS 'Treatment Plan Option Consultant Approvals';
COMMENT ON COLUMN txpopap."TxPOpt" IS 'Primary key component, the treatmetn plan option. Ptr to TXPOPT.TxPOpt';
COMMENT ON COLUMN txpopap."ConsultantType" IS 'Primary key component, consultant type for this approval. Ptr to CONSULTS.Id';
COMMENT ON COLUMN txpopap."Approved" IS 'Is approved? (0=No, 1=Yes)';
COMMENT ON COLUMN txpopap."AppUser" IS 'Approval user, ptr to USERS.User';
COMMENT ON COLUMN txpopap."AppDateTime" IS 'Approval date/time';


CREATE  TABLE txpopt (
  "TxPOpt" numeric(10,0) NOT NULL,
  "TxPlan" numeric(10,0),
  "Description" character varying(60),
  "NeedsConsultantAppr" numeric(5,0),
  "InstructorApproved" numeric(5,0),
  "Total" numeric,
  "InsTotal" numeric,
  "AppUser" numeric(10,0),
  "AppDateTime" timestamp without time zone,
  "AppNA" numeric(5,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT txpopt_primary PRIMARY KEY ("TxPOpt")
) ;
CREATE INDEX IF NOT EXISTS txpopt_txplan ON txpopt USING btree ("TxPlan") TABLESPACE pg_default;
COMMENT ON TABLE txpopt IS 'Treatment Plan Options';
COMMENT ON COLUMN txpopt."TxPlan" IS 'Treatment plan that this option is for, ptr to TXPLAN.TxPlan';
COMMENT ON COLUMN txpopt."TxPOpt" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN txpopt."Total" IS 'Estimated total cost of the treatment plan option, in dollars.';
COMMENT ON COLUMN txpopt."NeedsConsultantAppr" IS 'Is consultant approval required for this treatment plan option? (0=No, 1=Yes)';
COMMENT ON COLUMN txpopt."InstructorApproved" IS 'Has the instructor approved this treatment plan option? (0=No, 1=Yes)';
COMMENT ON COLUMN txpopt."InsTotal" IS 'Estimated insurance portion of the total cost, in dollars.';
COMMENT ON COLUMN txpopt."Description" IS 'Description of the treatment plan option.';
COMMENT ON COLUMN txpopt."Deleted" IS 'Is this treatment plan option deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN txpopt."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN txpopt."AppUser" IS 'User that approved this treatment plan option, ptr to USERS.User';
COMMENT ON COLUMN txpopt."AppNA" IS 'Is instructor approval not required? (0=No, 1=Yes)';
COMMENT ON COLUMN txpopt."AppDateTime" IS 'Date/time that the treatment plan option was approved.';


CREATE  TABLE txpopth (
  "TxPOptH" numeric(10,0) NOT NULL,
  "TxPOpt" numeric(10,0),
  "TxPlan" numeric(10,0),
  "Description" character varying(60),
  "NeedsConsultantAppr" numeric(5,0),
  "InstructorApproved" numeric(5,0),
  "Total" numeric,
  "InsTotal" numeric,
  "AppUser" numeric(10,0),
  "AppDateTime" timestamp without time zone,
  "AppNA" numeric(5,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT txpopth_primary PRIMARY KEY ("TxPOptH")
) ;
CREATE INDEX IF NOT EXISTS txpopth_txpopt ON txpopth USING btree ("TxPOpt") TABLESPACE pg_default;
COMMENT ON TABLE txpopth IS 'Treatment Plan Option History';
COMMENT ON COLUMN txpopth."TxPlan" IS 'Treatment plan that this option is for, ptr to TXPLAN.TxPlan';
COMMENT ON COLUMN txpopth."TxPOptH" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN txpopth."TxPOpt" IS 'Treatment plan option that this history is for, ptr to TXPOPT.TxPOpt';
COMMENT ON COLUMN txpopth."Total" IS 'Estimated total cost of the treatment plan option, in dollars.';
COMMENT ON COLUMN txpopth."NeedsConsultantAppr" IS 'Is consultant approval required for this treatment plan option? (0=No, 1=Yes)';
COMMENT ON COLUMN txpopth."InstructorApproved" IS 'Has the instructor approved this treatment plan option? (0=No, 1=Yes)';
COMMENT ON COLUMN txpopth."InsTotal" IS 'Estimated insurance portion of the total cost, in dollars.';
COMMENT ON COLUMN txpopth."Description" IS 'Description of the treatment plan option.';
COMMENT ON COLUMN txpopth."Deleted" IS 'Is this treatment plan option deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN txpopth."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN txpopth."AppUser" IS 'User that approved this treatment plan option, ptr to USERS.User';
COMMENT ON COLUMN txpopth."AppNA" IS 'Is instructor approval not required? (0=No, 1=Yes)';
COMMENT ON COLUMN txpopth."AppDateTime" IS 'Date/time that the treatment plan option was approved.';


CREATE  TABLE txpprb (
  "TxPlan" numeric(10,0) NOT NULL,
  "PtPrb" numeric(10,0) NOT NULL,
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT txpprb_primary PRIMARY KEY ("TxPlan", "PtPrb")
) ;
CREATE INDEX IF NOT EXISTS txpprb_ptprb ON txpprb USING btree ("PtPrb") TABLESPACE pg_default;
COMMENT ON TABLE txpprb IS 'Treatment Plan Problems';
COMMENT ON COLUMN txpprb."TxPlan" IS 'Primary key component, the treatment plan containing this problem. Ptr to TXPLAN.TxPlan';
COMMENT ON COLUMN txpprb."PtPrb" IS 'Primary key component, the problem contained in the treatment plan. Ptr to PTPRB.PtPrb';
COMMENT ON COLUMN txpprb."Deleted" IS 'Is this link deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN txpprb."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE txpprbh (
  "TxPPrbH" numeric(10,0) NOT NULL,
  "TxPlan" numeric(10,0),
  "PtPrb" numeric(10,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT txpprbh_primary PRIMARY KEY ("TxPPrbH")
) ;
CREATE INDEX IF NOT EXISTS txpprbh_txplanptprb ON txpprbh USING btree ("TxPlan", "PtPrb") TABLESPACE pg_default;
COMMENT ON TABLE txpprbh IS 'Treatment Plan Problem History';
COMMENT ON COLUMN txpprbh."TxPlan" IS 'The treatment plan containing this problem. Ptr to TXPLAN.TxPlan';
COMMENT ON COLUMN txpprbh."TxPPrbH" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN txpprbh."PtPrb" IS 'The problem contained in the treatment plan. Ptr to PTPRB.PtPrb';
COMMENT ON COLUMN txpprbh."Deleted" IS 'Is this link deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN txpprbh."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE txptx (
  "TxPTx" numeric(10,0) NOT NULL,
  "TxPOpt" numeric(10,0),
  "TxPlan" numeric(10,0),
  "TxPTxType" numeric(5,0),
  "Text" character varying(4000),
  "TxPTxDateTime" timestamp without time zone,
  "Order" numeric(5,0),
  "Provider" character(10),
  "Code" character(7),
  "Description" character varying(60),
  "MacroSeq" numeric(10,0),
  "Site" character(3),
  "Site2" character(3),
  "Surface" character(6),
  "Phase" character(2),
  "Sequence" numeric(5,0),
  "Status" character(1),
  "Total" numeric,
  "InsTotal" numeric,
  "HeldTotal" numeric(5,0),
  "ClaimDoctor" character(10),
  "Discipline" character(15),
  "Unit" numeric,
  "Custom1" character(6),
  "Custom2" character(6),
  "PtAccepted" numeric(5,0),
  "PtAcceptDateTime" timestamp without time zone,
  "Treatme2Id" numeric(10,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT txptx_primary PRIMARY KEY ("TxPTx")
) ;
CREATE INDEX IF NOT EXISTS txptx_treatme2id ON txptx USING btree ("Treatme2Id") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS txptx_txplan ON txptx USING btree ("TxPlan") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS txptx_txpopt ON txptx USING btree ("TxPOpt") TABLESPACE pg_default;
COMMENT ON TABLE txptx IS 'Treatment Plan Treatments';
COMMENT ON COLUMN txptx."Unit" IS 'Number of units for the procedure.';
COMMENT ON COLUMN txptx."TxPlan" IS 'Treatment plan that this treatment is on, ptr to TXPLAN.TxPlan';
COMMENT ON COLUMN txptx."TxPTxType" IS 'Type of record (0=Procedure, 1=Quote Text)';
COMMENT ON COLUMN txptx."TxPTxDateTime" IS 'DEPRECATED';
COMMENT ON COLUMN txptx."TxPTx" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN txptx."TxPOpt" IS 'Treatment plan option that this treatment is on, ptr to TXPOPT.TxPOpt';
COMMENT ON COLUMN txptx."Treatme2Id" IS 'ID code of the treatment in the EHR, ptr to TREATME2.Auto';
COMMENT ON COLUMN txptx."Total" IS 'Estimated total cost of the treatment.';
COMMENT ON COLUMN txptx."Text" IS 'If TxPTxType=1, the quote text.';
COMMENT ON COLUMN txptx."Surface" IS 'Surface(s) treatment is to be performed on';
COMMENT ON COLUMN txptx."Status" IS 'Treatment status (P=Planned, I=In Process, C=Completed)';
COMMENT ON COLUMN txptx."Site2" IS 'End site treatment is to be performed on, for multisite procedures (e.g. bridges)';
COMMENT ON COLUMN txptx."Site" IS 'Site treatment is to be performed on.';
COMMENT ON COLUMN txptx."Sequence" IS 'Treatment sequence';
COMMENT ON COLUMN txptx."PtAccepted" IS 'Has the patient accepted this treatment? (0=No, 1=Yes, 2=Yes and Printed)';
COMMENT ON COLUMN txptx."PtAcceptDateTime" IS 'If PtAccepted=1, the date/time that the patient accepted it. ';
COMMENT ON COLUMN txptx."Provider" IS 'Provider who is expected to perform this treatment, ptr to PRODUCER.Producer';
COMMENT ON COLUMN txptx."Phase" IS 'Treatment phase';
COMMENT ON COLUMN txptx."Order" IS 'Order that this line appears in the summarized estimate.';
COMMENT ON COLUMN txptx."MacroSeq" IS 'Unique internal ID given to all procedures added from the same macro.';
COMMENT ON COLUMN txptx."InsTotal" IS 'Estimated insurance portion of the total cost of the treatment.';
COMMENT ON COLUMN txptx."HeldTotal" IS 'Held estimate? (0=No, 1=Yes)';
COMMENT ON COLUMN txptx."Discipline" IS 'Treatment discipline, ptr to CLASS.Class';
COMMENT ON COLUMN txptx."Description" IS 'Description of the procedure.';
COMMENT ON COLUMN txptx."Deleted" IS 'Is this treatment plan treatment deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN txptx."Custom2" IS 'Treatment/Clinical2 code for this transaction, ptr to CUSTCODE.Code';
COMMENT ON COLUMN txptx."Custom1" IS 'Treatment/Clinical1 code for this treatment, ptr to CUSTCODE.Code';
COMMENT ON COLUMN txptx."Code" IS 'The procedure code for the treatment, ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN txptx."ClaimDoctor" IS 'Billing doctor used to calculated fees, ptr to PRODUCER.Producer';
COMMENT ON COLUMN txptx."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE txptxh (
  "TxPTxH" numeric(10,0) NOT NULL,
  "TxPTx" numeric(10,0),
  "TxPOpt" numeric(10,0),
  "TxPlan" numeric(10,0),
  "TxPTxType" numeric(5,0),
  "Text" character varying(4000),
  "TxPTxDateTime" timestamp without time zone,
  "Order" numeric(5,0),
  "Provider" character(10),
  "Code" character(7),
  "Description" character varying(60),
  "MacroSeq" numeric(10,0),
  "Site" character(3),
  "Site2" character(3),
  "Surface" character(6),
  "Phase" character(2),
  "Sequence" numeric(5,0),
  "Status" character(1),
  "Total" numeric,
  "InsTotal" numeric,
  "HeldTotal" numeric(5,0),
  "ClaimDoctor" character(10),
  "Discipline" character(15),
  "Unit" numeric,
  "Custom1" character(6),
  "Custom2" character(6),
  "PtAccepted" numeric(5,0),
  "PtAcceptDateTime" timestamp without time zone,
  "Treatme2Id" numeric(10,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  CONSTRAINT txptxh_con PRIMARY KEY ("TxPTxH")
) ;
CREATE INDEX IF NOT EXISTS txptxh_txptx ON txptxh USING btree ("TxPTx") TABLESPACE pg_default;
COMMENT ON TABLE txptxh IS 'Treatment Plan Treatment History';
COMMENT ON COLUMN txptxh."Unit" IS 'Number of units for the procedure.';
COMMENT ON COLUMN txptxh."TxPlan" IS 'Treatment plan that this treatment is on, ptr to TXPLAN.TxPlan';
COMMENT ON COLUMN txptxh."TxPTxType" IS 'Type of record (0=Procedure, 1=Quote Text)';
COMMENT ON COLUMN txptxh."TxPTxH" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN txptxh."TxPTxDateTime" IS 'DEPRECATED';
COMMENT ON COLUMN txptxh."TxPTx" IS 'Treatment plan treatment that this history is for, ptr to TXPTX.TxPTx';
COMMENT ON COLUMN txptxh."TxPOpt" IS 'Treatment plan option that this treatment is on, ptr to TXPOPT.TxPOpt';
COMMENT ON COLUMN txptxh."Treatme2Id" IS 'ID code of the treatment in the EHR, ptr to TREATME2.Auto';
COMMENT ON COLUMN txptxh."Total" IS 'Estimated total cost of the treatment.';
COMMENT ON COLUMN txptxh."Text" IS 'If TxPTxType=1, the quote text.';
COMMENT ON COLUMN txptxh."Surface" IS 'Surface(s) treatment is to be performed on';
COMMENT ON COLUMN txptxh."Status" IS 'Treatment status (P=Planned, I=In Process, C=Completed)';
COMMENT ON COLUMN txptxh."Site2" IS 'End site treatment is to be performed on, for multisite procedures (e.g. bridges)';
COMMENT ON COLUMN txptxh."Site" IS 'Site treatment is to be performed on.';
COMMENT ON COLUMN txptxh."Sequence" IS 'Treatment sequence';
COMMENT ON COLUMN txptxh."PtAccepted" IS 'Has the patient accepted this treatment? (0=No, 1=Yes)';
COMMENT ON COLUMN txptxh."PtAcceptDateTime" IS 'If PtAccepted=1, the date/time that the patient accepted it. ';
COMMENT ON COLUMN txptxh."Provider" IS 'Provider who is expected to perform this treatment, ptr to PRODUCER.Producer';
COMMENT ON COLUMN txptxh."Phase" IS 'Treatment phase';
COMMENT ON COLUMN txptxh."Order" IS 'Order that this line appears in the summarized estimate.';
COMMENT ON COLUMN txptxh."MacroSeq" IS 'Unique internal ID given to all procedures added from the same macro.';
COMMENT ON COLUMN txptxh."InsTotal" IS 'Estimated insurance portion of the total cost of the treatment.';
COMMENT ON COLUMN txptxh."HeldTotal" IS 'Held estimate? (0=No, 1=Yes)';
COMMENT ON COLUMN txptxh."Discipline" IS 'Treatment discipline, ptr to CLASS.Class';
COMMENT ON COLUMN txptxh."Description" IS 'Description of the procedure.';
COMMENT ON COLUMN txptxh."Deleted" IS 'Has the patient accepted this treatment? (0=No, 1=Yes, 2=Yes and Printed)';
COMMENT ON COLUMN txptxh."Custom2" IS 'Treatment/Clinical2 code for this transaction, ptr to CUSTCODE.Code';
COMMENT ON COLUMN txptxh."Custom1" IS 'Treatment/Clinical1 code for this treatment, ptr to CUSTCODE.Code';
COMMENT ON COLUMN txptxh."Code" IS 'The procedure code for the treatment, ptr to PROCEDUR.Procedure';
COMMENT ON COLUMN txptxh."ClaimDoctor" IS 'Billing doctor used to calculated fees, ptr to PRODUCER.Producer';
COMMENT ON COLUMN txptxh."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE txquest (
  "TxQuest" numeric(10,0) NOT NULL,
  "Module" numeric(5,0),
  "Item" numeric(5,0),
  "Heading" character(12),
  "Question" character varying(20),
  "ResponseType" numeric(5,0),
  "RespList" numeric(10,0),
  "RespCode" numeric(5,0),
  "Inactive" numeric(5,0),
  "Width" numeric(5,0),
  CONSTRAINT txquest_primary PRIMARY KEY ("TxQuest")
) ;
COMMENT ON TABLE txquest IS 'Ortho custom fields';
COMMENT ON COLUMN txquest."Width" IS 'Width of the column for this question in the treatment history window';
COMMENT ON COLUMN txquest."TxQuest" IS 'Id code to identify this tx quest record';
COMMENT ON COLUMN txquest."ResponseType" IS 'Resposne type (0=Yes/No, 1=Date,2=Free Text, 3=Ortho Custom Lists, 4= axiUm codes)';
COMMENT ON COLUMN txquest."RespList" IS 'If TXQUEST.ResponseType = 4, the Ortho response list to use.';
COMMENT ON COLUMN txquest."RespCode" IS 'Response Detail, used if response type is ‘Application Codes’. 0 = Provider List, 1 = Users List ';
COMMENT ON COLUMN txquest."Question" IS 'Text to display as the prompt for this question';
COMMENT ON COLUMN txquest."Module" IS 'Module to which this relates (0=Ortho)';
COMMENT ON COLUMN txquest."Item" IS 'Item number, internal ID ';
COMMENT ON COLUMN txquest."Inactive" IS 'Record is inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN txquest."Heading" IS 'Text to display in the tretament hsitory window as a title for this column';


CREATE  TABLE uaccess (
  "User" numeric(10,0) NOT NULL,
  "Sunday" character(24),
  "Monday" character(24),
  "Tuesday" character(24),
  "Wednesday" character(24),
  "Thursday" character(24),
  "Friday" character(24),
  "Saturday" character(24),
  CONSTRAINT uaccess_primary PRIMARY KEY ("User")
) ;
COMMENT ON TABLE uaccess IS 'Accessible Hours for Users';
COMMENT ON COLUMN uaccess."Wednesday" IS 'Access times for Wednesday';
COMMENT ON COLUMN uaccess."User" IS 'Primary key, the user who these access hours are for. Ptr to USERS.User.';
COMMENT ON COLUMN uaccess."Tuesday" IS 'Access times for Tuesday';
COMMENT ON COLUMN uaccess."Thursday" IS 'Access times for Thursday';
COMMENT ON COLUMN uaccess."Sunday" IS 'Access times for Sunday (First character in string is for 12 AM, 2nd for 1 AM, ...)';
COMMENT ON COLUMN uaccess."Saturday" IS 'Access times for Saturday';
COMMENT ON COLUMN uaccess."Monday" IS 'Access times for Monday';
COMMENT ON COLUMN uaccess."Friday" IS 'Access times for Friday';


CREATE  TABLE uapprove (
  "UApprove" numeric(10,0) NOT NULL,
  "Type" numeric(5,0),
  "User" numeric(10,0),
  "Discipline" character(6),
  "ProdType" character(1),
  "PGroup" character(6),
  CONSTRAINT uapprove_primary PRIMARY KEY ("UApprove")
) ;
CREATE INDEX IF NOT EXISTS uapprove_user ON uapprove USING btree ("User", "Type") TABLESPACE pg_default;
COMMENT ON TABLE uapprove IS 'Restricted Approval Definitions';
COMMENT ON COLUMN uapprove."User" IS 'The user that this restricted approval definition is for, ptr to USERS.User';
COMMENT ON COLUMN uapprove."UApprove" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN uapprove."Type" IS 'Type of restricted approval (0=Discipline, 1=Provider Type)';
COMMENT ON COLUMN uapprove."ProdType" IS 'For Type=2, the provider type that the user is allowed to approve for. Ptr to PRODTYPE.Code';
COMMENT ON COLUMN uapprove."PGroup" IS 'For Type=2, the provider group that the user is allowed to approve for. Ptr to PGROUP.Pgroup';
COMMENT ON COLUMN uapprove."Discipline" IS 'For Type=1, the discipline that the user is allowed to approve. Ptr to DISCIPL.Discipline';


CREATE  TABLE ubook (
  "User" numeric(10,0) NOT NULL,
  "Book" numeric(10,0) NOT NULL,
  "AutoSelect" numeric(5,0),
  "Access" numeric(5,0),
  CONSTRAINT ubook_primary PRIMARY KEY ("User", "Book")
) ;
COMMENT ON TABLE ubook IS 'List of scheduling books in use by each user of axiUm. ';
COMMENT ON COLUMN ubook."User" IS 'Id code of the user, ptr to USERS.User';
COMMENT ON COLUMN ubook."Book" IS 'Id code of the book for which this user will require patients to be selected, ptr to BOOK.Book';
COMMENT ON COLUMN ubook."AutoSelect" IS 'Pre-select patients from this book in the overnight process? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN ubook."Access" IS '0 = Read Only, 1 = Full Access, 2 = Full Access (For own only)';


CREATE  TABLE uclinic (
  "User" numeric(10,0) NOT NULL,
  "Clinic" numeric(10,0) NOT NULL,
  "IsDefault" numeric(5,0),
  CONSTRAINT uclinic_primary PRIMARY KEY ("User", "Clinic")
) ;
COMMENT ON TABLE uclinic IS 'List of clinics the user has access to ';
COMMENT ON COLUMN uclinic."User" IS 'Id code of the user that has access to this clinic, ptr to USERS.User';
COMMENT ON COLUMN uclinic."IsDefault" IS 'Is this the default clinic for this user? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN uclinic."Clinic" IS 'Id code of the clinic this user has access to, ptr to CLINIC.Clinic';


CREATE  TABLE ugroup (
  "UGroup" character(6) NOT NULL,
  "Description" character(30),
  CONSTRAINT ugroup_primary PRIMARY KEY ("UGroup")
) ;
COMMENT ON TABLE ugroup IS 'Messenger Groups';
COMMENT ON COLUMN ugroup."UGroup" IS 'Primary key, ID code to identify the messenger group.';
COMMENT ON COLUMN ugroup."Description" IS 'Name/description of the messenger group.';


CREATE  TABLE uhealhis (
  "UHealHis" numeric(10,0) NOT NULL,
  "UHealth" numeric(10,0) NOT NULL,
  "User" numeric(10,0) NOT NULL,
  "Health" character(6) NOT NULL,
  "Category" character varying(30),
  "Date" timestamp without time zone,
  "ExpiryDate" timestamp without time zone,
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "Note" character varying(1000),
  CONSTRAINT uhealhis_primary PRIMARY KEY ("UHealHis")
) ;
CREATE INDEX IF NOT EXISTS uhealhis_uhealth ON uhealhis USING btree ("UHealth") TABLESPACE pg_default;
COMMENT ON TABLE uhealhis IS 'User Health Information History';
COMMENT ON COLUMN uhealhis."User" IS 'The user that this health information record is for. Ptr to USERS.User';
COMMENT ON COLUMN uhealhis."UHealth" IS 'User health information record that this history is for. Ptr to UHEALTH.Uhealth';
COMMENT ON COLUMN uhealhis."UHealHis" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN uhealhis."Note" IS 'Note about the health information. ';
COMMENT ON COLUMN uhealhis."Health" IS 'Health code, ptr to HEALTH.Health';
COMMENT ON COLUMN uhealhis."ExpiryDate" IS 'Expiry date of the training certificate, or the date the immunization becomes ineffective.';
COMMENT ON COLUMN uhealhis."Deleted" IS 'Deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN uhealhis."Date" IS 'Date the immunization or training was received, or in the case of a disease the date of diagnosis.';
COMMENT ON COLUMN uhealhis."Category" IS 'Text field to enter category of this health code. ie: immunization, disease. ';
COMMENT ON COLUMN uhealhis."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE uhealth (
  "UHealth" numeric(10,0) NOT NULL,
  "User" numeric(10,0) NOT NULL,
  "Health" character(6) NOT NULL,
  "Category" character varying(30),
  "Date" timestamp without time zone,
  "ExpiryDate" timestamp without time zone,
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "Note" character varying(1000),
  CONSTRAINT uhealth_primary PRIMARY KEY ("UHealth")
) ;
CREATE INDEX IF NOT EXISTS uhealth_user ON uhealth USING btree ("User") TABLESPACE pg_default;
COMMENT ON TABLE uhealth IS 'User Health Information';
COMMENT ON COLUMN uhealth."User" IS 'The user that this health information record is for. Ptr to USERS.User';
COMMENT ON COLUMN uhealth."UHealth" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN uhealth."Note" IS 'Note about the health information. ';
COMMENT ON COLUMN uhealth."Health" IS 'Health code, ptr to HEALTH.Health';
COMMENT ON COLUMN uhealth."ExpiryDate" IS 'Expiry date of the training certificate, or the date the immunization becomes ineffective.';
COMMENT ON COLUMN uhealth."Deleted" IS 'Deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN uhealth."Date" IS 'Date the immunization or training was received, or in the case of a disease the date of diagnosis.';
COMMENT ON COLUMN uhealth."Category" IS 'Text field to enter category of this health code. ie: immunization, disease. ';
COMMENT ON COLUMN uhealth."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE umember (
  "UGroup" character(6) NOT NULL,
  "User" numeric(10,0) NOT NULL,
  CONSTRAINT umember_primary PRIMARY KEY ("UGroup", "User")
) ;
COMMENT ON TABLE umember IS 'Messenger Group Membership';
COMMENT ON COLUMN umember."User" IS 'Primary key component, the user who is a member of the messenger group. Ptr to USERS.User';
COMMENT ON COLUMN umember."UGroup" IS 'Primary key component, the messenger group. Ptr to UGROUP.UGroup';


CREATE  TABLE umsgfld (
  "UMsgFld" numeric(10,0) NOT NULL,
  "User" numeric(10,0),
  "Folder" character varying(30),
  "FolderType" numeric(5,0),
  CONSTRAINT umsgfld_primary PRIMARY KEY ("UMsgFld")
) ;
CREATE INDEX IF NOT EXISTS umsgfld_user ON umsgfld USING btree ("User") TABLESPACE pg_default;
COMMENT ON TABLE umsgfld IS 'User defined messenger folders';
COMMENT ON COLUMN umsgfld."User" IS 'User ID';
COMMENT ON COLUMN umsgfld."UMsgFld" IS 'Sequenced primary key';
COMMENT ON COLUMN umsgfld."FolderType" IS '0 = Inbox, 1 = Sent';
COMMENT ON COLUMN umsgfld."Folder" IS 'Name of the folder';


CREATE  TABLE upgroup (
  "User" numeric(10,0) NOT NULL,
  "PGroup" character(6) NOT NULL,
  CONSTRAINT upgroup_primary PRIMARY KEY ("User", "PGroup")
) ;
COMMENT ON TABLE upgroup IS 'Group Manager Records';
COMMENT ON COLUMN upgroup."User" IS 'Primary key component, ID code of group manager. Ptr to USERS.User';
COMMENT ON COLUMN upgroup."PGroup" IS 'Primary key component, provider group that the user manages. Ptr to PGROUP.PGroup';


CREATE  TABLE upicture (
  "User" numeric(10,0) NOT NULL,
  "FileExt" character varying(32),
  picture bytea,
  CONSTRAINT upicture_primary PRIMARY KEY ("User")
) ;
COMMENT ON TABLE upicture IS 'Record of user pictures.';
COMMENT ON COLUMN upicture.picture IS 'Binary object storing user image data. Note: In Oracle 9i this field is Type: BLOB';
COMMENT ON COLUMN upicture."User" IS 'Id code of the user this picture is attached to (Users.User).';
COMMENT ON COLUMN upicture."FileExt" IS '3 digit file extension indicating type of image stored for the user (ie: bmp, jpeg, gif).';


CREATE  TABLE usedistatuscode (
  "Code" numeric(10,0) NOT NULL DEFAULT 0,
  "Name" character varying(255),
  CONSTRAINT usedistatuscode_pk PRIMARY KEY ("Code")
) ;
COMMENT ON TABLE usedistatuscode IS 'Table for storing the code and description for "EDI" status.';
COMMENT ON COLUMN usedistatuscode."Name" IS 'Status description';
COMMENT ON COLUMN usedistatuscode."Code" IS 'PK component, status code.';


CREATE  TABLE usernotifylog (
  "ExternalApplication" character varying(50) NOT NULL,
  "ExternalId" character varying(50) NOT NULL,
  "MessageId" numeric(10,0),
  CONSTRAINT usernotifylog_pk PRIMARY KEY ("ExternalApplication", "ExternalId")
) ;
COMMENT ON TABLE usernotifylog IS 'record for each notificaiton received through the User Notification API';
COMMENT ON COLUMN usernotifylog."MessageId" IS 'axiUm messenger message ID that was created from the notification';
COMMENT ON COLUMN usernotifylog."ExternalId" IS 'External application''s notification id, part of primary key';
COMMENT ON COLUMN usernotifylog."ExternalApplication" IS 'External application name, part of primary key';


CREATE  TABLE users (
  "User" numeric(10,0) NOT NULL,
  "Logon" character(16),
  "Name" character(30),
  "Password" character varying(61),
  "Level" numeric(10,0),
  "Producer" character(10),
  "Deleted" numeric(5,0),
  "ClaimDoctor" character(10),
  "Locked" numeric(5,0),
  "Scheduler" numeric(5,0),
  "RestrictDays" numeric(5,0),
  "First" character(30),
  "DisableAutoChart" numeric(5,0),
  "MaxChartOut" numeric(10,0),
  "MaxHoursOut" numeric(10,0),
  "EffDate" timestamp without time zone,
  "ExpDate" timestamp without time zone,
  "SwipeLogon" character(12),
  "SwipePassword" character(45),
  "PwdLastChanged" timestamp without time zone,
  "Audit" numeric(10,0),
  "IsInstructor" numeric(5,0),
  "MaxSchDays" numeric(5,0),
  "MaxApptReqDays" numeric(5,0),
  "Credentials" character varying(18),
  "MinSchHours" numeric(10,0),
  "Import" character(10),
  "MinContacts" numeric(5,0),
  "AddSteps" numeric(5,0),
  "ConsultantType" numeric(5,0),
  "IsManager" numeric(5,0),
  "RestrictedApproval" numeric(5,0),
  "Preferred" character(30),
  "Middle" character(15),
  "Sex" numeric(5,0),
  "Birth" timestamp without time zone,
  "Address1" character(30),
  "Address2" character(30),
  "City" character(24),
  "Province" character(6),
  "Postal" character(15),
  "AddressOther" character(15),
  "HomeArea" character(4),
  "HomePhone" character(8),
  "AltArea" character(4),
  "AltPhone" character(8),
  "Email" character(40),
  "Note" character(40),
  "DeptCode" character(6),
  "DeptRoom" character(6),
  "DeptArea" character(4),
  "DeptPhone" character(8),
  "AddNotes" numeric(5,0),
  "EditNotes" numeric(5,0),
  "EditTxs" numeric(5,0),
  "RequireLabApp" numeric(5,0),
  "CanApproveLabs" numeric(5,0),
  "ApprovePlanTx" numeric(5,0),
  "ApproveCompTx" numeric(5,0),
  "ApproveExistingTx" numeric(5,0),
  "ExistingNeedsApp" numeric(5,0),
  "IsGroupManager" numeric(5,0),
  "Custom1" character(6),
  "Custom2" character(6),
  "Custom3" character(6),
  "Custom4" character(6),
  "Custom5" character(6),
  "Custom6" character(6),
  "Custom7" character(6),
  "Custom8" character(6),
  "Custom9" character(6),
  "Custom10" character(6),
  "ConditionNeedsApp" numeric(5,0),
  "ApproveConditionTx" numeric(5,0),
  "MobileId" character(8),
  "MobilePassword" character(6),
  "PerioNeedsApp" numeric(5,0),
  "ApprovePerio" numeric(5,0),
  "PerMeth" numeric(10,0),
  "ApproveOrthoV" numeric(5,0),
  "OrthoVNeedsApp" numeric(5,0),
  "DeleteTxs" numeric(5,0),
  "DrugsOnDemand" numeric(5,0),
  "RequireASAApproval" numeric(5,0),
  "SchClinic" numeric(10,0),
  "ApprovePrescript" numeric(5,0),
  "AutoLock" numeric(10,0),
  "DefaultBank" character(6),
  "UseActiveDir" numeric(5,0),
  "ProblemsNeedApp" numeric(5,0),
  "ApproveProblems" numeric(5,0),
  "StartupMDI" numeric(5,0),
  "ApproveInvOrder" numeric(5,0),
  "ApproveNotes" numeric(5,0),
  "ApproveEHRForms" numeric(5,0),
  "ApproveStartChks" numeric(5,0),
  "AssignTxs" numeric(5,0),
  "ApproveNoTxConsent" numeric(5,0),
  "EditAppts" numeric(5,0),
  "CanAbortEvals" numeric(5,0),
  "CanEvaluate" numeric(5,0),
  "ApproveTxPlan" numeric(5,0),
  "ApproveDispLock" numeric(5,0),
  "ApproveUndefDrugs" numeric(5,0),
  "AutoLockErr" numeric(10,0),
  "PlanNeedsApp" numeric(5,0),
  "CompNeedsApp" numeric(5,0),
  "MsgRefreshRate" numeric(5,0),
  "NeedsTxPlanApp" numeric(5,0),
  "EditLabs" numeric(5,0),
  "LettersNeedApp" numeric(5,0),
  "ApproveLetters" numeric(5,0),
  "MsgAuthenticate" numeric(5,0),
  "MsgOutOfOffice" numeric(5,0),
  "MsgOutOfOfficeText" character varying(4000),
  "DefaultInfoMgrTab" numeric(5,0),
  "EnforcePIN" numeric(5,0),
  "PIN" character varying(45),
  "PINLocked" numeric(5,0),
  "ProxyAppMode" numeric(5,0),
  "OpenSchClinicMode" numeric(5,0),
  "CanUseEmergMode" numeric(5,0),
  "PrescribeCS" numeric(5,0),
  "PrescribeCSSchedule" numeric(5,0),
  "PrescribeNarcotic" numeric(5,0),
  "ApproveCS" numeric(5,0),
  "ApproveCSSchedule" numeric(5,0),
  "ApproveNarcotic" numeric(5,0),
  "CanUseERx" numeric(5,0),
  "PrescribeProxyMode" numeric(5,0),
  "AutoSpellChk" numeric(5,0),
  "MsgAccess" numeric(5,0),
  "EnterAlerts" numeric(5,0),
  "EnterAllergies" numeric(5,0),
  "EnterMedProb" numeric(5,0),
  "ChartLockDelay" numeric(5,0) NOT NULL DEFAULT 0,
  "TempChartUnlock" numeric(5,0) NOT NULL DEFAULT 0,
  "TempChartUnlockDays" numeric(5,0) NOT NULL DEFAULT 0,
  "TempChartUnlockHours" numeric(5,0) NOT NULL DEFAULT 0,
  "CanTempChartUnlock" numeric(5,0) NOT NULL DEFAULT 0,
  "EMailSubscribe" numeric(5,0),
  "EMailNotify" character varying(40),
  "SurgeryNeedsApp" numeric(5,0),
  "ApproveSurgery" numeric(5,0),
  "ApproveDrugWaste" numeric(5,0),
  "CallCenterId" character varying(40),
  "CallCenterPrompt" numeric(5,0),
  "EMailForward" numeric(5,0),
  "RequestApproval" numeric(5,0),
  "MsgDismissHighPrior" numeric(5,0),
  "DeletePerioExam" numeric(5,0),
  "MsgOutOfOfficeStart" timestamp without time zone,
  "MsgOutOfOfficeEnd" timestamp without time zone,
  CONSTRAINT users_primary PRIMARY KEY ("User")
) ;
CREATE INDEX IF NOT EXISTS users_audit ON users USING btree ("Audit") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS users_level ON users USING btree ("Level") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS users_levelkey ON users USING btree ("Level", "Name", "First") TABLESPACE pg_default;
CREATE UNIQUE INDEX IF NOT EXISTS users_logon ON users USING btree ("Logon") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS users_producer ON users USING btree ("Producer") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS users_swipelogon ON users USING btree ("SwipeLogon") TABLESPACE pg_default;
COMMENT ON TABLE users IS 'Users';
COMMENT ON COLUMN users."User" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN users."UseActiveDir" IS 'Use Windows authentication? (0=No, 1=Yes) ';
COMMENT ON COLUMN users."TempChartUnlockHours" IS 'Amount of hours the temporary unlock is for';
COMMENT ON COLUMN users."TempChartUnlockDays" IS 'Amount of days the temporary unlock is for';
COMMENT ON COLUMN users."TempChartUnlock" IS 'Can request temporary chart unlock? (0=Not allowed, 1=For specific patient, 2=For all assigned patient records)';
COMMENT ON COLUMN users."SwipePassword" IS 'Swipe card password [encrypted].';
COMMENT ON COLUMN users."SwipeLogon" IS 'Swipe card logon.';
COMMENT ON COLUMN users."SurgeryNeedsApp" IS 'Require approval for Surgery? (0=No, 1=Yes).';
COMMENT ON COLUMN users."StartupMDI" IS 'Module that opens at startup when this user logs into axiUm (0=None, 1=Patients, 2=Scheduler, 3=Personal Planner, 4=Patient Assignment, 5=Overdue Patients, 6=Chart Tracker, 7=Evaluations, 8=Dispensary, 9=Inventory, 10=Lab Tracker, 11=Info Manager, 12=Maintenance)';
COMMENT ON COLUMN users."Sex" IS 'User gender (0=Unknown, 1=Male, 2=Female, 3=Transgender, 4=Gender X, 5=Other)';
COMMENT ON COLUMN users."Scheduler" IS 'Default scheduler mode (0=Chair, 1=Book, 2=Availability)';
COMMENT ON COLUMN users."SchClinic" IS 'The clinic that the user was last using in the Scheduler. Ptr to CLINIC.Clinic';
COMMENT ON COLUMN users."RestrictedApproval" IS 'Restricted approval? (0=No, 1=Yes)';
COMMENT ON COLUMN users."RestrictDays" IS 'Number of days in the future that the user can view in the schedule (0=No Restriction)';
COMMENT ON COLUMN users."RequireLabApp" IS 'Require approval for Lab Orders? (0=No, 1=Yes)';
COMMENT ON COLUMN users."RequireASAApproval" IS 'Require approval for Patient ASA? (0=No, 1=Yes) ';
COMMENT ON COLUMN users."RequestApproval" IS 'Can Request Approval form Faculty? 0 = no, 1 = yes (required), 2 = yes (optional)';
COMMENT ON COLUMN users."PwdLastChanged" IS 'Date/time on which the password was last changed.';
COMMENT ON COLUMN users."ProxyAppMode" IS 'Do entries on behalf of another provider require approval? (0=Always, 1=Based on own settings)';
COMMENT ON COLUMN users."Province" IS 'Province, ptr to PROVINCE.Province';
COMMENT ON COLUMN users."Producer" IS 'If the user is a provider, the provider code. Ptr to PRODUCER.Producer';
COMMENT ON COLUMN users."ProblemsNeedApp" IS 'Require approval for Problems? (0=No, 1=Yes)';
COMMENT ON COLUMN users."PrescribeProxyMode" IS 'Rights to use when prescribing on behalf of another provider (0=Use own rights, 1=Inherit proxy-user rights)';
COMMENT ON COLUMN users."PrescribeNarcotic" IS 'Can the user prescribe narcotics? (0=No, 1=Yes)';
COMMENT ON COLUMN users."PrescribeCSSchedule" IS 'If the user can prescribe controlled substances, can prescribe them for this Schedule or higher.';
COMMENT ON COLUMN users."PrescribeCS" IS 'Can the user prescribe controlled substances? (0=No, 1=Yes)';
COMMENT ON COLUMN users."Preferred" IS 'User preferred first name.';
COMMENT ON COLUMN users."Postal" IS 'Postal code, ptr to CITY.Postal';
COMMENT ON COLUMN users."PlanNeedsApp" IS 'Require approval for Planned Treatments? (0=No, 1=Yes)';
COMMENT ON COLUMN users."PerioNeedsApp" IS 'Require approval for Perio Charts? (0=No, 1=Yes)';
COMMENT ON COLUMN users."PerMeth" IS 'Perio method for this user, ptr to PERMETH.PerMeth';
COMMENT ON COLUMN users."Password" IS 'Password for logging in to axiUm [encrypted].';
COMMENT ON COLUMN users."PINLocked" IS '"PIN" is locked? (0=No, 1=Yes)';
COMMENT ON COLUMN users."PIN" IS 'Swipe card "PIN" [encrypted].';
COMMENT ON COLUMN users."OrthoVNeedsApp" IS 'Require approval for Ortho Visits? (0=No, 1=Yes)';
COMMENT ON COLUMN users."OpenSchClinicMode" IS 'Clinic to open the Scheduler with (0=Last Clinic Viewed, 1=Default Clinic)';
COMMENT ON COLUMN users."Note" IS 'Freetext note about this user.';
COMMENT ON COLUMN users."NeedsTxPlanApp" IS 'Require approval for Tx Plans? (0=No, 1=Yes)';
COMMENT ON COLUMN users."Name" IS 'User last name.';
COMMENT ON COLUMN users."MsgRefreshRate" IS 'Messenger refreshes automatically? (0=No, otherwise the number of minutes between automatic refreshes)';
COMMENT ON COLUMN users."MsgOutOfOfficeText" IS 'Out of Office message for Messenger.';
COMMENT ON COLUMN users."MsgOutOfOfficeStart" IS 'Start date, if applicable, for the Out Of Office message';
COMMENT ON COLUMN users."MsgOutOfOfficeEnd" IS 'End date, if applicable, for the Out Of Office message';
COMMENT ON COLUMN users."MsgOutOfOffice" IS 'Messenger out of office? (0=In Office, 1=Out of Office)';
COMMENT ON COLUMN users."MsgDismissHighPrior" IS 'Messenger dismiss high priority messages? (0=No, 1=Yes)';
COMMENT ON COLUMN users."MsgAuthenticate" IS 'Messenger requires authentication? (0=No, 1=Yes)';
COMMENT ON COLUMN users."MsgAccess" IS 'Can this user send and receive messages to/from PatientAccess patients? (0=No, 1=Yes)';
COMMENT ON COLUMN users."MobilePassword" IS 'Password for Palm / Pocket PC to connect to axiUm.';
COMMENT ON COLUMN users."MobileId" IS 'Username for Palm / Pocket PC to connect to axiUm.';
COMMENT ON COLUMN users."MinSchHours" IS 'Minimum number of hours ahead that the user can schedule appointments. ';
COMMENT ON COLUMN users."MinContacts" IS 'Minimum number of contacts, for instructors using Periodic grading.';
COMMENT ON COLUMN users."Middle" IS 'User middle name';
COMMENT ON COLUMN users."MaxSchDays" IS 'Number of days in the future that the user can schedule appointments.';
COMMENT ON COLUMN users."MaxHoursOut" IS 'Maximum number of hours that a user may have a chart out (0=Unlimited)';
COMMENT ON COLUMN users."MaxChartOut" IS 'Maximum number of charts that the user can have out at one time (0=Unlimited)';
COMMENT ON COLUMN users."MaxApptReqDays" IS 'Number of days in the future that the user can request appointments.';
COMMENT ON COLUMN users."Logon" IS 'Username for logging in to axiUm.';
COMMENT ON COLUMN users."Locked" IS 'Charts locked from user? (0=No, 1=Yes)';
COMMENT ON COLUMN users."Level" IS 'User security level, ptr to SLEVEL.SLevel';
COMMENT ON COLUMN users."LettersNeedApp" IS 'Require approval for Letters? (0=No, 1=Yes)';
COMMENT ON COLUMN users."IsManager" IS 'User is a patient manager? (0=No, 1=Yes)';
COMMENT ON COLUMN users."IsInstructor" IS 'User is an instructor? (0=No, 1=Yes)';
COMMENT ON COLUMN users."IsGroupManager" IS 'User manages one or more Provider Groups? (0=No, 1=Yes)';
COMMENT ON COLUMN users."Import" IS 'Import code used, for scheduler imports.';
COMMENT ON COLUMN users."HomePhone" IS 'Home phone number. Format: ###-####';
COMMENT ON COLUMN users."HomeArea" IS 'Home phone area code';
COMMENT ON COLUMN users."First" IS 'User first name';
COMMENT ON COLUMN users."ExpDate" IS 'Expiry date for user (can only log in prior to this date)';
COMMENT ON COLUMN users."ExistingNeedsApp" IS 'Require approval for Pre-Existing Treatment? (0=No, 1=Yes)';
COMMENT ON COLUMN users."EnterMedProb" IS 'Can enter Medical Problems (0=No, 1=Yes)';
COMMENT ON COLUMN users."EnterAllergies" IS 'Can enter Allergies (0=No, 1=Yes)';
COMMENT ON COLUMN users."EnterAlerts" IS 'Can enter Clinical Alerts (0=No, 1=Yes)';
COMMENT ON COLUMN users."EnforcePIN" IS 'Enforce entry of "PIN" when swiping card? (0=No, 1=Yes)';
COMMENT ON COLUMN users."Email" IS 'User email address.';
COMMENT ON COLUMN users."EffDate" IS 'Effective date for user (can only log in after this date)';
COMMENT ON COLUMN users."EditTxs" IS 'Edit/Delete I or C Treatments? (0=No, 1=Entered for Self, 2=All Accessible)';
COMMENT ON COLUMN users."EditNotes" IS 'Edit/Delete Approved Notes? (0=No, 1=Entered by Self, 2=Entered by Anyone)';
COMMENT ON COLUMN users."EditLabs" IS 'Edit/Delete Approved Labs (0=No, 1=Yes [All], 2=Yes [Limited], 3=Yes with Approval [All])';
COMMENT ON COLUMN users."EditAppts" IS 'Edit appointments? (0=Entered by Self, 1=Entered by Anyone) ';
COMMENT ON COLUMN users."EMailSubscribe" IS 'Is the user an email subscriber? (0=No ([Default], 1=Yes)';
COMMENT ON COLUMN users."EMailNotify" IS 'Email address to route notifications to';
COMMENT ON COLUMN users."EMailForward" IS '0=No, only those sent by users, 1=All High Priority messages, 2=All messages';
COMMENT ON COLUMN users."DrugsOnDemand" IS 'Can prescribe undefined drugs? (0=No, 1=Yes, 2=Yes with Approval)';
COMMENT ON COLUMN users."DisableAutoChart" IS 'Disable auto chart request? (0=No, 1=Yes)';
COMMENT ON COLUMN users."DeptRoom" IS 'Department room.';
COMMENT ON COLUMN users."DeptPhone" IS 'Department phone number. Format: ###-####';
COMMENT ON COLUMN users."DeptCode" IS 'Department code.';
COMMENT ON COLUMN users."DeptArea" IS 'Department phone area code.';
COMMENT ON COLUMN users."Deleted" IS 'User is deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN users."DeleteTxs" IS 'Delete treatments? (0=No, 1=Planned or Unapproved I/C, 2 = Planned Only, 3=Unapproved Planned, 4=All Accessible)';
COMMENT ON COLUMN users."DeletePerioExam" IS 'Delete perio exams? (0=No, 1=Unapproved, 2 = Closed, 3=All (Accessible))';
COMMENT ON COLUMN users."DefaultInfoMgrTab" IS 'Default Info Manager tab (0=Patients, 1=Insurance, 2=Referral, 3=Billing, 4=Appointment, 5=Clinical, 6=Clinic Mgt, 7=Practice, 8=Management, 9=Custom)';
COMMENT ON COLUMN users."DefaultBank" IS 'Default bank for this user. Ptr to BANK.Bank ';
COMMENT ON COLUMN users."Custom9" IS 'User9 custom code value. Ptr to CUSTCODE.Code';
COMMENT ON COLUMN users."Custom8" IS 'User8 custom code value. Ptr to CUSTCODE.Code';
COMMENT ON COLUMN users."Custom7" IS 'User7 custom code value. Ptr to CUSTCODE.Code';
COMMENT ON COLUMN users."Custom6" IS 'User6 custom code value. Ptr to CUSTCODE.Code';
COMMENT ON COLUMN users."Custom5" IS 'User5 custom code value. Ptr to CUSTCODE.Code';
COMMENT ON COLUMN users."Custom4" IS 'User4 custom code value. Ptr to CUSTCODE.Code';
COMMENT ON COLUMN users."Custom3" IS 'User3 custom code value. Ptr to CUSTCODE.Code';
COMMENT ON COLUMN users."Custom2" IS 'User2 custom code value. Ptr to CUSTCODE.Code';
COMMENT ON COLUMN users."Custom10" IS 'User10 custom code value. Ptr to CUSTCODE.Code';
COMMENT ON COLUMN users."Custom1" IS 'User1 custom code value. Ptr to CUSTCODE.Code';
COMMENT ON COLUMN users."Credentials" IS 'Freetext field to store user credentials. ';
COMMENT ON COLUMN users."ConsultantType" IS 'Consultant type, ptr to CONSULTS.Id';
COMMENT ON COLUMN users."ConditionNeedsApp" IS 'Require approval for Conditions? (0=No, 1=Yes)';
COMMENT ON COLUMN users."CompNeedsApp" IS 'Require approval for Completed Treatments? (0=No, 1=Yes)';
COMMENT ON COLUMN users."ClaimDoctor" IS 'Default billing ID for this user. Ptr to PRODUCER.Producer';
COMMENT ON COLUMN users."City" IS 'City, ptr to CITY.City';
COMMENT ON COLUMN users."ChartLockDelay" IS 'Number of seconds before user is able to close the chart lock error/warning window';
COMMENT ON COLUMN users."CanUseEmergMode" IS 'Can the user enter Emergency Mode? (0=No, 1=Yes)';
COMMENT ON COLUMN users."CanUseERx" IS 'Can the user use e-Rx? (0=No, 1=Yes)';
COMMENT ON COLUMN users."CanTempChartUnlock" IS 'Can permit temporary chart unlock? (0=No, 1=Yes)';
COMMENT ON COLUMN users."CanEvaluate" IS 'Can approve evaluations? (0=No, 1=Yes)';
COMMENT ON COLUMN users."CanApproveLabs" IS 'Can approve Lab Orders? (0=No, 1=Yes)';
COMMENT ON COLUMN users."CanAbortEvals" IS 'Can abort evaluations? (0=No, 1=Yes)';
COMMENT ON COLUMN users."CallCenterPrompt" IS 'Prompt when receiving a phone call from the Call Center (0=No, 1=Yes';
COMMENT ON COLUMN users."CallCenterId" IS 'The Call Center Id.';
COMMENT ON COLUMN users."Birth" IS 'User date of birth';
COMMENT ON COLUMN users."AutoSpellChk" IS 'Automatically spellcheck clinical notes entered by this user? (0=No, 1=Yes)';
COMMENT ON COLUMN users."AutoLockErr" IS 'Automatic lock for Errors (cannot proceed after lock message). Ptr to AUTOLOCK.Id';
COMMENT ON COLUMN users."AutoLock" IS 'Automatic lock for Warnings (can proceed after lock message). Ptr to AUTOLOCK.Id';
COMMENT ON COLUMN users."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN users."AssignTxs" IS 'Assign treatments to appointments? (0=Optional, 1=Prompt User, 2=Required)';
COMMENT ON COLUMN users."ApproveUndefDrugs" IS 'Can approve Undefined Drugs? (0=No, 1=Yes)';
COMMENT ON COLUMN users."ApproveTxPlan" IS 'Can approve Tx Plans? (0=No, 1=Yes)';
COMMENT ON COLUMN users."ApproveSurgery" IS 'Can approve Surgery? (0=No, 1=Yes).';
COMMENT ON COLUMN users."ApproveStartChks" IS 'Can approve Start Checks (0=No, 1=Yes)';
COMMENT ON COLUMN users."ApproveProblems" IS 'Can approve Problems? (0=No, 1=Yes)';
COMMENT ON COLUMN users."ApprovePrescript" IS 'Can approve Prescriptions? (0=No, 1=Yes)';
COMMENT ON COLUMN users."ApprovePlanTx" IS 'Can approve Planned Treatment? (0=No, 1=Yes)';
COMMENT ON COLUMN users."ApprovePerio" IS 'Can approve Perio Charts? (0=No, 1=Yes)';
COMMENT ON COLUMN users."ApproveOrthoV" IS 'Can approve Ortho Visits? (0=No, 1=Yes)';
COMMENT ON COLUMN users."ApproveNotes" IS 'Can approve Notes (0=No, 1=Yes)';
COMMENT ON COLUMN users."ApproveNoTxConsent" IS 'Can approve Start Checks without patient consent (0=No, 1=Yes)';
COMMENT ON COLUMN users."ApproveNarcotic" IS 'Can the user approve prescriptions for narcotics? (0=No, 1=Yes)';
COMMENT ON COLUMN users."ApproveLetters" IS 'Can approve Letters? (0=No, 1=Yes)';
COMMENT ON COLUMN users."ApproveInvOrder" IS 'Can approve Inventory Orders (0=No, 1=Yes)';
COMMENT ON COLUMN users."ApproveExistingTx" IS 'Can approve Pre-Existing Treatment? (0=No, 1=Yes)';
COMMENT ON COLUMN users."ApproveEHRForms" IS 'Can approve EPR Forms / ASA (0=No, 1=Yes)';
COMMENT ON COLUMN users."ApproveDrugWaste" IS 'Can approve drug waste recorded during surgery? (0=No, 1=Yes).';
COMMENT ON COLUMN users."ApproveDispLock" IS 'Can clear dispensary locks on unapproved items? (0=No, 1=Yes)';
COMMENT ON COLUMN users."ApproveConditionTx" IS 'Can approve Conditions? (0=No, 1=Yes)';
COMMENT ON COLUMN users."ApproveCompTx" IS 'Can approve Completed Treatment? (0=No, 1=Yes)';
COMMENT ON COLUMN users."ApproveCSSchedule" IS 'If the user can approve controlled substances, can approve them for this Schedule or higher.';
COMMENT ON COLUMN users."ApproveCS" IS 'Can the user approve prescriptions for controlled substances? (0=No, 1=Yes)';
COMMENT ON COLUMN users."AltPhone" IS 'Alternate phone number. Format: ###-####';
COMMENT ON COLUMN users."AltArea" IS 'Alternate phone area code';
COMMENT ON COLUMN users."AddressOther" IS 'For USA, represents County. For Dutch, represents Room Number';
COMMENT ON COLUMN users."Address2" IS 'User address, line 2';
COMMENT ON COLUMN users."Address1" IS 'User address, line 1';
COMMENT ON COLUMN users."AddSteps" IS 'Add step treatments when non-provider? (0=Manual only, 1=Yes, 2=Auto Only)';
COMMENT ON COLUMN users."AddNotes" IS 'Add/Edit Notes? (0=No, 1=Yes with Approval, 2=Yes)';


CREATE  TABLE usersad (
  "User" numeric(10,0) NOT NULL,
  "ADPre2KLogon" character varying(128) NOT NULL,
  "ADPre2KDomain" character varying(128) NOT NULL,
  "ADLogon" character varying(128),
  "ADDomain" character varying(128),
  CONSTRAINT usersad_primary PRIMARY KEY ("User", "ADPre2KLogon", "ADPre2KDomain")
) ;
CREATE INDEX IF NOT EXISTS usersad_adlogon ON usersad USING btree ("ADLogon") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS usersad_adpre2klogon ON usersad USING btree ("ADPre2KLogon") TABLESPACE pg_default;
COMMENT ON TABLE usersad IS 'User Active Directory Accounts';
COMMENT ON COLUMN usersad."User" IS 'Primary key component, the user who this Active Directory info is for. Ptr to USERS.User';
COMMENT ON COLUMN usersad."ADPre2KLogon" IS 'Primary key component, the Active Directory username (for legacy pre-Windows 2000 systems)';
COMMENT ON COLUMN usersad."ADPre2KDomain" IS 'Primary key component, the Active Directory domain name (for legacy pre-Windows 2000 systems)';
COMMENT ON COLUMN usersad."ADLogon" IS 'Active Directory username.';
COMMENT ON COLUMN usersad."ADDomain" IS 'Active Directory domain name.';


CREATE  TABLE usershis (
  "UsersHis" numeric(10,0) NOT NULL,
  "User" numeric(10,0) NOT NULL,
  "Logon" character(16),
  "Name" character(30),
  "Password" character varying(61),
  "Level" numeric(10,0),
  "Producer" character(10),
  "Deleted" numeric(5,0),
  "ClaimDoctor" character(10),
  "Locked" numeric(5,0),
  "Scheduler" numeric(5,0),
  "RestrictDays" numeric(5,0),
  "First" character(30),
  "DisableAutoChart" numeric(5,0),
  "MaxChartOut" numeric(10,0),
  "MaxHoursOut" numeric(10,0),
  "EffDate" timestamp without time zone,
  "ExpDate" timestamp without time zone,
  "SwipeLogon" character(12),
  "SwipePassword" character(45),
  "PwdLastChanged" timestamp without time zone,
  "MinSchHours" numeric(10,0),
  "Import" character(10),
  "MinContacts" numeric(5,0),
  "AddSteps" numeric(5,0),
  "ConsultantType" numeric(5,0),
  "IsManager" numeric(5,0),
  "RestrictedApproval" numeric(5,0),
  "Preferred" character(30),
  "Middle" character(15),
  "Sex" numeric(5,0),
  "Birth" timestamp without time zone,
  "Address1" character(30),
  "Address2" character(30),
  "City" character(24),
  "Province" character(6),
  "Postal" character(15),
  "AddressOther" character(15),
  "HomeArea" character(4),
  "HomePhone" character(8),
  "AltArea" character(4),
  "AltPhone" character(8),
  "Email" character(40),
  "Note" character(40),
  "DeptCode" character(6),
  "DeptRoom" character(6),
  "DeptArea" character(4),
  "DeptPhone" character(8),
  "AddNotes" numeric(5,0),
  "EditNotes" numeric(5,0),
  "EditTxs" numeric(5,0),
  "RequireLabApp" numeric(5,0),
  "CanApproveLabs" numeric(5,0),
  "ApprovePlanTx" numeric(5,0),
  "ApproveCompTx" numeric(5,0),
  "ApproveExistingTx" numeric(5,0),
  "ExistingNeedsApp" numeric(5,0),
  "IsGroupManager" numeric(5,0),
  "Custom1" character(6),
  "Custom2" character(6),
  "Custom3" character(6),
  "Custom4" character(6),
  "Custom5" character(6),
  "Custom6" character(6),
  "Custom7" character(6),
  "Custom8" character(6),
  "Custom9" character(6),
  "Custom10" character(6),
  "ConditionNeedsApp" numeric(5,0),
  "ApproveConditionTx" numeric(5,0),
  "MobileId" character(8),
  "MobilePassword" character(6),
  "PerioNeedsApp" numeric(5,0),
  "ApprovePerio" numeric(5,0),
  "PerMeth" numeric(10,0),
  "ApproveOrthoV" numeric(5,0),
  "OrthoVNeedsApp" numeric(5,0),
  "DeleteTxs" numeric(5,0),
  "DrugsOnDemand" numeric(5,0),
  "RequireASAApproval" numeric(5,0),
  "SchClinic" numeric(10,0),
  "ApprovePrescript" numeric(5,0),
  "AutoLock" numeric(10,0),
  "DefaultBank" character(6),
  "Audit" numeric(10,0),
  "UseActiveDir" numeric(5,0),
  "ProblemsNeedApp" numeric(5,0),
  "ApproveProblems" numeric(5,0),
  "StartupMDI" numeric(5,0),
  "ApproveInvOrder" numeric(5,0),
  "ApproveNotes" numeric(5,0),
  "ApproveEHRForms" numeric(5,0),
  "ApproveStartChks" numeric(5,0),
  "AssignTxs" numeric(5,0),
  "ApproveNoTxConsent" numeric(5,0),
  "EditAppts" numeric(5,0),
  "CanAbortEvals" numeric(5,0),
  "IsInstructor" numeric(5,0),
  "CanEvaluate" numeric(5,0),
  "ApproveTxPlan" numeric(5,0),
  "ApproveDispLock" numeric(5,0),
  "ApproveUndefDrugs" numeric(5,0),
  "AutoLockErr" numeric(10,0),
  "PlanNeedsApp" numeric(5,0),
  "CompNeedsApp" numeric(5,0),
  "MsgRefreshRate" numeric(5,0),
  "NeedsTxPlanApp" numeric(5,0),
  "MaxSchDays" numeric(5,0),
  "MaxApptReqDays" numeric(5,0),
  "Credentials" character varying(18),
  "EditLabs" numeric(5,0),
  "LettersNeedApp" numeric(5,0),
  "ApproveLetters" numeric(5,0),
  "MsgAuthenticate" numeric(5,0),
  "MsgOutOfOffice" numeric(5,0),
  "MsgOutOfOfficeText" character varying(4000),
  "DefaultInfoMgrTab" numeric(5,0),
  "EnforcePIN" numeric(5,0),
  "PIN" character varying(45),
  "PINLocked" numeric(5,0),
  "ProxyAppMode" numeric(5,0),
  "OpenSchClinicMode" numeric(5,0),
  "CanUseEmergMode" numeric(5,0),
  "PrescribeCS" numeric(5,0),
  "PrescribeCSSchedule" numeric(5,0),
  "PrescribeNarcotic" numeric(5,0),
  "ApproveCS" numeric(5,0),
  "ApproveCSSchedule" numeric(5,0),
  "ApproveNarcotic" numeric(5,0),
  "CanUseERx" numeric(5,0),
  "PrescribeProxyMode" numeric(5,0),
  "AutoSpellChk" numeric(5,0),
  "MsgAccess" numeric(5,0),
  "EnterAlerts" numeric(5,0),
  "EnterAllergies" numeric(5,0),
  "EnterMedProb" numeric(5,0),
  "ChartLockDelay" numeric(5,0) NOT NULL DEFAULT 0,
  "TempChartUnlock" numeric(5,0) NOT NULL DEFAULT 0,
  "TempChartUnlockDays" numeric(5,0) NOT NULL DEFAULT 0,
  "TempChartUnlockHours" numeric(5,0) NOT NULL DEFAULT 0,
  "CanTempChartUnlock" numeric(5,0) NOT NULL DEFAULT 0,
  "EMailSubscribe" numeric(5,0),
  "EMailNotify" character varying(40),
  "SurgeryNeedsApp" numeric(5,0),
  "ApproveSurgery" numeric(5,0),
  "ApproveDrugWaste" numeric(5,0),
  "CallCenterId" character varying(40),
  "CallCenterPrompt" numeric(5,0),
  "EMailForward" numeric(5,0),
  "RequestApproval" numeric(5,0),
  "MsgDismissHighPrior" numeric(5,0),
  "DeletePerioExam" numeric(5,0),
  "MsgOutOfOfficeStart" timestamp without time zone,
  "MsgOutOfOfficeEnd" timestamp without time zone,
  CONSTRAINT usershis_primary PRIMARY KEY ("UsersHis")
) ;
CREATE INDEX IF NOT EXISTS usershis_user ON usershis USING btree ("User") TABLESPACE pg_default;
COMMENT ON TABLE usershis IS 'User History';
COMMENT ON COLUMN usershis."UsersHis" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN usershis."User" IS 'The user that this history is for. Ptr to USERS.User';
COMMENT ON COLUMN usershis."UseActiveDir" IS 'Use Windows authentication? (0=No, 1=Yes) ';
COMMENT ON COLUMN usershis."TempChartUnlockHours" IS 'Amount of hours the temporary unlock is for';
COMMENT ON COLUMN usershis."TempChartUnlockDays" IS 'Amount of days the temporary unlock is for';
COMMENT ON COLUMN usershis."TempChartUnlock" IS 'Can request temporary chart unlock? (0=Not allowed, 1=For specific patient, 2=For all assigned patient records)';
COMMENT ON COLUMN usershis."SwipePassword" IS 'Swipe card password [encrypted].';
COMMENT ON COLUMN usershis."SwipeLogon" IS 'Swipe card logon.';
COMMENT ON COLUMN usershis."SurgeryNeedsApp" IS 'Require approval for Surgery? (0=No, 1=Yes).';
COMMENT ON COLUMN usershis."StartupMDI" IS 'Module that opens at startup when this user logs into axiUm (0=None, 1=Patients, 2=Scheduler, 3=Personal Planner, 4=Patient Assignment, 5=Overdue Patients, 6=Chart Tracker, 7=Evaluations, 8=Dispensary, 9=Inventory, 10=Lab Tracker, 11=Info Manager, 12=Maintenance)';
COMMENT ON COLUMN usershis."Sex" IS 'User gender (0=Unknown, 1=Male, 2=Female, 3=Transgender, 4=Gender X, 5=Other)';
COMMENT ON COLUMN usershis."Scheduler" IS 'Default scheduler mode (0=Chair, 1=Book, 2=Availability)';
COMMENT ON COLUMN usershis."SchClinic" IS 'The clinic that the user was last using in the Scheduler. Ptr to CLINIC.Clinic';
COMMENT ON COLUMN usershis."RestrictedApproval" IS 'Restricted approval? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."RestrictDays" IS 'Number of days in the future that the user can view in the schedule (0=No Restriction)';
COMMENT ON COLUMN usershis."RequireLabApp" IS 'Require approval for Lab Orders? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."RequireASAApproval" IS 'Require approval for Patient ASA? (0=No, 1=Yes) ';
COMMENT ON COLUMN usershis."RequestApproval" IS 'Can Request Approval form Faculty? 0 = no, 1 = yes (required), 2 = yes (optional)';
COMMENT ON COLUMN usershis."PwdLastChanged" IS 'Date/time on which the password was last changed.';
COMMENT ON COLUMN usershis."ProxyAppMode" IS 'Do entries on behalf of another provider require approval? (0=Always, 1=Based on own settings)';
COMMENT ON COLUMN usershis."Province" IS 'Province, ptr to PROVINCE.Province';
COMMENT ON COLUMN usershis."Producer" IS 'If the user is a provider, the provider code. Ptr to PRODUCER.Producer';
COMMENT ON COLUMN usershis."ProblemsNeedApp" IS 'Require approval for Problems? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."PrescribeProxyMode" IS 'Rights to use when prescribing on behalf of another provider (0=Use own rights, 1=Inherit proxy-user rights)';
COMMENT ON COLUMN usershis."PrescribeNarcotic" IS 'Can the user prescribe narcotics? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."PrescribeCSSchedule" IS 'If the user can prescribe controlled substances, can prescribe them for this Schedule or higher.';
COMMENT ON COLUMN usershis."PrescribeCS" IS 'Can the user prescribe controlled substances? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."Preferred" IS 'User preferred first name.';
COMMENT ON COLUMN usershis."Postal" IS 'Postal code, ptr to CITY.Postal';
COMMENT ON COLUMN usershis."PlanNeedsApp" IS 'Require approval for Planned Treatments? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."PerioNeedsApp" IS 'Require approval for Perio Charts? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."PerMeth" IS 'Perio method for this user, ptr to PERMETH.PerMeth';
COMMENT ON COLUMN usershis."Password" IS 'Password for logging in to axiUm [encrypted].';
COMMENT ON COLUMN usershis."PINLocked" IS '"PIN" is locked? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."PIN" IS 'Swipe card "PIN" [encrypted].';
COMMENT ON COLUMN usershis."OrthoVNeedsApp" IS 'Require approval for Ortho Visits? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."OpenSchClinicMode" IS 'Clinic to open the Scheduler with (0=Last Clinic Viewed, 1=Default Clinic)';
COMMENT ON COLUMN usershis."Note" IS 'Freetext note about this user.';
COMMENT ON COLUMN usershis."NeedsTxPlanApp" IS 'Require approval for Tx Plans? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."Name" IS 'User last name.';
COMMENT ON COLUMN usershis."MsgRefreshRate" IS 'Messenger refreshes automatically? (0=No, otherwise the number of minutes between automatic refreshes)';
COMMENT ON COLUMN usershis."MsgOutOfOfficeText" IS 'Out of Office message for Messenger.';
COMMENT ON COLUMN usershis."MsgOutOfOfficeStart" IS 'Start date, if applicable, for the Out Of Office message';
COMMENT ON COLUMN usershis."MsgOutOfOfficeEnd" IS 'End date, if applicable, for the Out Of Office message';
COMMENT ON COLUMN usershis."MsgOutOfOffice" IS 'Messenger out of office? (0=In Office, 1=Out of Office)';
COMMENT ON COLUMN usershis."MsgDismissHighPrior" IS 'Messenger dismiss high priority messages? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."MsgAuthenticate" IS 'Messenger requires authentication? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."MsgAccess" IS 'Can this user send and receive messages to/from PatientAccess patients? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."MobilePassword" IS 'Password for Palm / Pocket PC to connect to axiUm.';
COMMENT ON COLUMN usershis."MobileId" IS 'Username for Palm / Pocket PC to connect to axiUm.';
COMMENT ON COLUMN usershis."MinSchHours" IS 'Minimum number of hours ahead that the user can schedule appointments. ';
COMMENT ON COLUMN usershis."MinContacts" IS 'Minimum number of contacts, for instructors using Periodic grading.';
COMMENT ON COLUMN usershis."Middle" IS 'User middle name';
COMMENT ON COLUMN usershis."MaxSchDays" IS 'Number of days in the future that the user can schedule appointments.';
COMMENT ON COLUMN usershis."MaxHoursOut" IS 'Maximum number of hours that a user may have a chart out (0=Unlimited)';
COMMENT ON COLUMN usershis."MaxChartOut" IS 'Maximum number of charts that the user can have out at one time (0=Unlimited)';
COMMENT ON COLUMN usershis."MaxApptReqDays" IS 'Number of days in the future that the user can request appointments.';
COMMENT ON COLUMN usershis."Logon" IS 'Username for logging in to axiUm.';
COMMENT ON COLUMN usershis."Locked" IS 'Charts locked from user? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."Level" IS 'User security level, ptr to SLEVEL.Level';
COMMENT ON COLUMN usershis."LettersNeedApp" IS 'Require approval for Letters? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."IsManager" IS 'User is a patient manager? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."IsInstructor" IS 'User is an instructor? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."IsGroupManager" IS 'User manages one or more Provider Groups? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."Import" IS 'Import code used, for scheduler imports.';
COMMENT ON COLUMN usershis."HomePhone" IS 'Home phone number. Format: ###-####';
COMMENT ON COLUMN usershis."HomeArea" IS 'Home phone area code';
COMMENT ON COLUMN usershis."First" IS 'User first name';
COMMENT ON COLUMN usershis."ExpDate" IS 'Expiry date for user (can only log in prior to this date)';
COMMENT ON COLUMN usershis."ExistingNeedsApp" IS 'Require approval for Pre-Existing Treatment? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."EnterMedProb" IS 'Can enter Medical Problems (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."EnterAllergies" IS 'Can enter Allergies (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."EnterAlerts" IS 'Can enter Clinical Alerts (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."EnforcePIN" IS 'Enforce entry of "PIN" when swiping card? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."Email" IS 'User email address.';
COMMENT ON COLUMN usershis."EffDate" IS 'Effective date for user (can only log in after this date)';
COMMENT ON COLUMN usershis."EditTxs" IS 'Edit/Delete I or C Treatments? (0=No, 1=Entered for Self, 2=All Accessible)';
COMMENT ON COLUMN usershis."EditNotes" IS 'Edit/Delete Approved Notes? (0=No, 1=Entered by Self, 2=Entered by Anyone)';
COMMENT ON COLUMN usershis."EditLabs" IS 'Edit/Delete Approved Labs (0=No, 1=Yes [All], 2=Yes [Limited], 3=Yes with Approval [All])';
COMMENT ON COLUMN usershis."EditAppts" IS 'Edit appointments? (0=Entered by Self, 1=Entered by Anyone) ';
COMMENT ON COLUMN usershis."EMailSubscribe" IS 'Is the user an email subscriber? (0=No ([Default], 1=Yes)';
COMMENT ON COLUMN usershis."EMailNotify" IS 'Email address to route notifications to';
COMMENT ON COLUMN usershis."EMailForward" IS '0=No, only those sent by users, 1=All High Priority messages, 2=All messages';
COMMENT ON COLUMN usershis."DrugsOnDemand" IS 'Can prescribe undefined drugs? (0=No, 1=Yes, 2=Yes with Approval)';
COMMENT ON COLUMN usershis."DisableAutoChart" IS 'Disable auto chart request? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."DeptRoom" IS 'Department room.';
COMMENT ON COLUMN usershis."DeptPhone" IS 'Department phone number. Format: ###-####';
COMMENT ON COLUMN usershis."DeptCode" IS 'Department code.';
COMMENT ON COLUMN usershis."DeptArea" IS 'Department phone area code.';
COMMENT ON COLUMN usershis."Deleted" IS 'User is deleted? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."DeleteTxs" IS 'Delete treatments? (0=No, 1=Planned or Unapproved I/C, 2 = Planned Only, 3=Unapproved Planned, 4=All Accessible)';
COMMENT ON COLUMN usershis."DeletePerioExam" IS 'Delete perio exams? (0=No, 1=Unapproved, 2 = Closed, 3=All (Accessible))';
COMMENT ON COLUMN usershis."DefaultInfoMgrTab" IS 'Default Info Manager tab (0=Patients, 1=Insurance, 2=Referral, 3=Billing, 4=Appointment, 5=Clinical, 6=Clinic Mgt, 7=Practice, 8=Management, 9=Custom)';
COMMENT ON COLUMN usershis."DefaultBank" IS 'Default bank for this user. Ptr to BANK.Bank ';
COMMENT ON COLUMN usershis."Custom9" IS 'User9 custom code value. Ptr to CUSTCODE.Code';
COMMENT ON COLUMN usershis."Custom8" IS 'User8 custom code value. Ptr to CUSTCODE.Code';
COMMENT ON COLUMN usershis."Custom7" IS 'User7 custom code value. Ptr to CUSTCODE.Code';
COMMENT ON COLUMN usershis."Custom6" IS 'User6 custom code value. Ptr to CUSTCODE.Code';
COMMENT ON COLUMN usershis."Custom5" IS 'User5 custom code value. Ptr to CUSTCODE.Code';
COMMENT ON COLUMN usershis."Custom4" IS 'User4 custom code value. Ptr to CUSTCODE.Code';
COMMENT ON COLUMN usershis."Custom3" IS 'User3 custom code value. Ptr to CUSTCODE.Code';
COMMENT ON COLUMN usershis."Custom2" IS 'User2 custom code value. Ptr to CUSTCODE.Code';
COMMENT ON COLUMN usershis."Custom10" IS 'User10 custom code value. Ptr to CUSTCODE.Code';
COMMENT ON COLUMN usershis."Custom1" IS 'User1 custom code value. Ptr to CUSTCODE.Code';
COMMENT ON COLUMN usershis."Credentials" IS 'Freetext field to store user credentials. ';
COMMENT ON COLUMN usershis."ConsultantType" IS 'Consultant type, ptr to CONSULTS.Id';
COMMENT ON COLUMN usershis."ConditionNeedsApp" IS 'Require approval for Conditions? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."CompNeedsApp" IS 'Require approval for Completed Treatments? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."ClaimDoctor" IS 'Default billing ID for this user. Ptr to PRODUCER.Producer';
COMMENT ON COLUMN usershis."City" IS 'City, ptr to CITY.City';
COMMENT ON COLUMN usershis."ChartLockDelay" IS 'Number of seconds before user is able to close the chart lock error/warning window';
COMMENT ON COLUMN usershis."CanUseEmergMode" IS 'Can the user enter Emergency Mode? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."CanUseERx" IS 'Can the user use e-Rx? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."CanTempChartUnlock" IS 'Can permit temporary chart unlock? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."CanEvaluate" IS 'Can approve evaluations? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."CanApproveLabs" IS 'Can approve Lab Orders? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."CanAbortEvals" IS 'Can abort evaluations? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."CallCenterPrompt" IS 'Prompt when receiving a phone call from the Call Center (0=No, 1=Yes';
COMMENT ON COLUMN usershis."CallCenterId" IS 'The Call Center Id.';
COMMENT ON COLUMN usershis."Birth" IS 'User date of birth';
COMMENT ON COLUMN usershis."AutoSpellChk" IS 'Automatically spellcheck clinical notes entered by this user? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."AutoLockErr" IS 'Automatic lock for Errors (cannot proceed after lock message). Ptr to AUTOLOCK.Id';
COMMENT ON COLUMN usershis."AutoLock" IS 'Automatic lock for Warnings (can proceed after lock message). Ptr to AUTOLOCK.Id';
COMMENT ON COLUMN usershis."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';
COMMENT ON COLUMN usershis."AssignTxs" IS 'Assign treatments to appointments? (0=Optional, 1=Prompt User, 2=Required)';
COMMENT ON COLUMN usershis."ApproveUndefDrugs" IS 'Can approve Undefined Drugs? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."ApproveTxPlan" IS 'Can approve Tx Plans? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."ApproveSurgery" IS 'Can approve Surgery? (0=No, 1=Yes).';
COMMENT ON COLUMN usershis."ApproveStartChks" IS 'Can approve Start Checks (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."ApproveProblems" IS 'Can approve Problems? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."ApprovePrescript" IS 'Can approve Prescriptions? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."ApprovePlanTx" IS 'Can approve Planned Treatment? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."ApprovePerio" IS 'Can approve Perio Charts? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."ApproveOrthoV" IS 'Can approve Ortho Visits? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."ApproveNotes" IS 'Can approve Notes (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."ApproveNoTxConsent" IS 'Can approve Start Checks without patient consent (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."ApproveNarcotic" IS 'Can the user approve prescriptions for narcotics? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."ApproveLetters" IS 'Can approve Letters? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."ApproveInvOrder" IS 'Can approve Inventory Orders (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."ApproveExistingTx" IS 'Can approve Pre-Existing Treatment? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."ApproveEHRForms" IS 'Can approve EPR Forms / ASA (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."ApproveDrugWaste" IS 'Can approve drug waste recorded during surgery? (0=No, 1=Yes).';
COMMENT ON COLUMN usershis."ApproveDispLock" IS 'Can clear dispensary locks on unapproved items? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."ApproveConditionTx" IS 'Can approve Conditions? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."ApproveCompTx" IS 'Can approve Completed Treatment? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."ApproveCSSchedule" IS 'If the user can approve controlled substances, can approve them for this Schedule or higher.';
COMMENT ON COLUMN usershis."ApproveCS" IS 'Can the user approve prescriptions for controlled substances? (0=No, 1=Yes)';
COMMENT ON COLUMN usershis."AltPhone" IS 'Alternate phone number. Format: ###-####';
COMMENT ON COLUMN usershis."AltArea" IS 'Alternate phone area code';
COMMENT ON COLUMN usershis."AddressOther" IS 'For USA, represents County. For Dutch, represents Room Number';
COMMENT ON COLUMN usershis."Address2" IS 'User address, line 2';
COMMENT ON COLUMN usershis."Address1" IS 'User address, line 1';
COMMENT ON COLUMN usershis."AddSteps" IS 'Add step treatments when non-provider? (0=Manual only, 1=Yes, 2=Auto Only)';
COMMENT ON COLUMN usershis."AddNotes" IS 'Add/Edit Notes? (0=No, 1=Yes with Approval, 2=Yes)';


CREATE  TABLE usersmsg (
  "User" numeric(10,0) NOT NULL,
  "Time" timestamp without time zone,
  CONSTRAINT usersmsg_primary PRIMARY KEY ("User")
) ;
COMMENT ON TABLE usersmsg IS 'Quick lookup table storing the last time something changed in the messenger for that User, indicating a refresh is required. Much faster than polling the message and msgsent tables.';
COMMENT ON COLUMN usersmsg."User" IS 'User ID';
COMMENT ON COLUMN usersmsg."Time" IS 'Time of the most recent messenger change for this User';


CREATE  TABLE vacaset (
  "VacaSet" numeric(10,0) NOT NULL,
  "Type" numeric(5,0),
  "Provider" character(10),
  "User" numeric(10,0),
  "Description" character varying(30),
  "DisplayDesc" character varying(30),
  "StartDate" timestamp without time zone,
  "EndDate" timestamp without time zone,
  "StartTime" numeric(10,0),
  "EndTime" numeric(10,0),
  "Cycle" numeric(5,0),
  "CycleStart" timestamp without time zone,
  "Monday" numeric(5,0),
  "Tuesday" numeric(5,0),
  "Wednesday" numeric(5,0),
  "Thursday" numeric(5,0),
  "Friday" numeric(5,0),
  "Saturday" numeric(5,0),
  "Sunday" numeric(5,0),
  "Imported" numeric(5,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "Color" numeric(10,0),
  "CycleType" numeric(5,0),
  "CycleFrq" numeric(5,0),
  "IsBreak" numeric(5,0),
  "AvailableClinic" numeric(10,0),
  CONSTRAINT vacaset_primary PRIMARY KEY ("VacaSet")
) ;
CREATE INDEX IF NOT EXISTS vacaset_provider ON vacaset USING btree ("Provider") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS vacaset_type ON vacaset USING btree ("Type", "User", "StartDate") TABLESPACE pg_default;
COMMENT ON TABLE vacaset IS 'Recurring Non-Clinic Times';
COMMENT ON COLUMN vacaset."Wednesday" IS 'If Cycle is greater than  0, applies to Wednesday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN vacaset."VacaSet" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN vacaset."User" IS 'Entry user, ptr to USERS.User';
COMMENT ON COLUMN vacaset."Type" IS 'Schedule type (0 = Provider, 1=Instructor)';
COMMENT ON COLUMN vacaset."Tuesday" IS 'If Cycle is greater than  0, applies to Tuesday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN vacaset."Thursday" IS 'If Cycle is greater than  0, applies to Thursday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN vacaset."Sunday" IS 'If Cycle is greater than  0, applies to Sunday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN vacaset."StartTime" IS 'Start time for partial day records, in minutes from midnight.';
COMMENT ON COLUMN vacaset."StartDate" IS 'Start date of the non-clinic time.';
COMMENT ON COLUMN vacaset."Saturday" IS 'If Cycle is greater than  0, applies to Saturday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN vacaset."Provider" IS 'Provider that the non-clinic times are for, ptr to PRODUCER.Producer.';
COMMENT ON COLUMN vacaset."Monday" IS 'If Cycle is greater than  0, applies to Monday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN vacaset."IsBreak" IS 'Does this non-clinic time qualify as a break time for providers? (0=No, 1=Yes)';
COMMENT ON COLUMN vacaset."Imported" IS 'Vacaset record was imported? (0 = No, 1 = Yes)';
COMMENT ON COLUMN vacaset."Friday" IS 'If Cycle is greater than 0, applies to Friday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN vacaset."EndTime" IS 'End time for partial day records, in minutes from midnight.';
COMMENT ON COLUMN vacaset."EndDate" IS 'End date of the non-clinic time.';
COMMENT ON COLUMN vacaset."DisplayDesc" IS 'Description of the non-clinic time for display in the scheduler.';
COMMENT ON COLUMN vacaset."Description" IS 'Description of the non-clinic time.';
COMMENT ON COLUMN vacaset."Deleted" IS 'Is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN vacaset."CycleType" IS 'Recurrence cycle type (0=Weekly, 1=Monthly)';
COMMENT ON COLUMN vacaset."CycleStart" IS 'Recurrence start date.';
COMMENT ON COLUMN vacaset."CycleFrq" IS 'If CycleType=1, cycle recurs on the (0=First, 1=Second, 2=Third, 3=Fourth, 4=Last)';
COMMENT ON COLUMN vacaset."Cycle" IS 'Weekly recurrence cycle (1=recurs every week, 2= recurs every second week, 3= recurs every third week…)';
COMMENT ON COLUMN vacaset."Color" IS 'Color in which to display the non-clinic time in the scheduler. Numeric representation of RGB values. ';
COMMENT ON COLUMN vacaset."AvailableClinic" IS 'Clinic that the provider is only available in, for Clinic Time Exceptions (0=None, else ptr to CLINIC.Clinic)';
COMMENT ON COLUMN vacaset."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE vacaseth (
  "VacaSetH" numeric(10,0) NOT NULL,
  "VacaSet" numeric(10,0),
  "Type" numeric(5,0),
  "Provider" character(10),
  "User" numeric(10,0),
  "Description" character varying(30),
  "DisplayDesc" character varying(30),
  "StartDate" timestamp without time zone,
  "EndDate" timestamp without time zone,
  "StartTime" numeric(10,0),
  "EndTime" numeric(10,0),
  "Cycle" numeric(5,0),
  "CycleStart" timestamp without time zone,
  "Monday" numeric(5,0),
  "Tuesday" numeric(5,0),
  "Wednesday" numeric(5,0),
  "Thursday" numeric(5,0),
  "Friday" numeric(5,0),
  "Saturday" numeric(5,0),
  "Sunday" numeric(5,0),
  "Imported" numeric(5,0),
  "Deleted" numeric(5,0),
  "Audit" numeric(10,0),
  "Color" numeric(10,0),
  "CycleType" numeric(5,0),
  "CycleFrq" numeric(5,0),
  "IsBreak" numeric(5,0),
  "AvailableClinic" numeric(10,0),
  CONSTRAINT vacaseth_primary PRIMARY KEY ("VacaSetH")
) ;
CREATE INDEX IF NOT EXISTS vacaseth_id ON vacaseth USING btree ("VacaSet") TABLESPACE pg_default;
COMMENT ON TABLE vacaseth IS 'Recurring Non-Clinic Time History';
COMMENT ON COLUMN vacaseth."Wednesday" IS 'If Cycle is greater than  0, applies to Wednesday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN vacaseth."VacaSetH" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN vacaseth."VacaSet" IS 'Recurring non-clinic time this history is for, ptr to VACASET.VacaSet';
COMMENT ON COLUMN vacaseth."User" IS 'Entry user, ptr to USERS.User';
COMMENT ON COLUMN vacaseth."Type" IS 'Schedule type (0 = Provider, 1=Instructor)';
COMMENT ON COLUMN vacaseth."Tuesday" IS 'If Cycle is greater than  0, applies to Tuesday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN vacaseth."Thursday" IS 'If Cycle is greater than  0, applies to Thursday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN vacaseth."Sunday" IS 'If Cycle is greater than  0, applies to Sunday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN vacaseth."StartTime" IS 'Start time for partial day records, in minutes from midnight.';
COMMENT ON COLUMN vacaseth."StartDate" IS 'Start date of the non-clinic time.';
COMMENT ON COLUMN vacaseth."Saturday" IS 'If Cycle is greater than  0, applies to Saturday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN vacaseth."Provider" IS 'Provider that the non-clinic times are for, ptr to PRODUCER.Producer.';
COMMENT ON COLUMN vacaseth."Monday" IS 'If Cycle is greater than  0, applies to Monday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN vacaseth."IsBreak" IS 'Does this non-clinic time qualify as a break time for providers? (0=No, 1=Yes)';
COMMENT ON COLUMN vacaseth."Imported" IS 'Vacaset record was imported? (0 = No, 1 = Yes)';
COMMENT ON COLUMN vacaseth."Friday" IS 'If Cycle is greater than  0, applies to Friday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN vacaseth."EndTime" IS 'End time for partial day records, in minutes from midnight.';
COMMENT ON COLUMN vacaseth."EndDate" IS 'End date of the non-clinic time.';
COMMENT ON COLUMN vacaseth."DisplayDesc" IS 'Description of the non-clinic time for display in the scheduler.';
COMMENT ON COLUMN vacaseth."Description" IS 'Description of the non-clinic time.';
COMMENT ON COLUMN vacaseth."Deleted" IS 'Is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN vacaseth."CycleType" IS 'Recurrence cycle type (0=Weekly, 1=Monthly)';
COMMENT ON COLUMN vacaseth."CycleStart" IS 'Recurrence start date.';
COMMENT ON COLUMN vacaseth."CycleFrq" IS 'If CycleType=1, cycle recurs on the (0=First, 1=Second, 2=Third, 3=Fourth, 4=Last)';
COMMENT ON COLUMN vacaseth."Cycle" IS 'Weekly recurrence cycle (1=recurs every week, 2= recurs every second week, 3= recurs every third week…)';
COMMENT ON COLUMN vacaseth."Color" IS 'Color in which to display the non-clinic time in the scheduler. Numeric representation of RGB values. ';
COMMENT ON COLUMN vacaseth."AvailableClinic" IS 'Clinic that the provider is only available in, for Clinic Time Exceptions (0=None, else ptr to CLINIC.Clinic)';
COMMENT ON COLUMN vacaseth."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE vacatecd (
  "Description" character varying(30) NOT NULL,
  "DisplayDesc" character varying(30),
  "Color" numeric(10,0),
  "Inactive" numeric(5,0),
  "IsBreak" numeric(5,0),
  "AvailableClinic" numeric(10,0),
  CONSTRAINT vacatecd_primary PRIMARY KEY ("Description")
) ;
COMMENT ON TABLE vacatecd IS 'Non-clinic time reason codes';
COMMENT ON COLUMN vacatecd."IsBreak" IS '0=No, 1=Yes, qualifies as a break time for providers';
COMMENT ON COLUMN vacatecd."Inactive" IS 'Code is inactive? (0 = No, 1 = Yes)';
COMMENT ON COLUMN vacatecd."DisplayDesc" IS 'Description of the non-clinic time for display in the scheduler';
COMMENT ON COLUMN vacatecd."Description" IS 'Description of the non-clinic time';
COMMENT ON COLUMN vacatecd."Color" IS 'Color in which to display the non-clinic time record';
COMMENT ON COLUMN vacatecd."AvailableClinic" IS 'Clinic that the provider is only available in, for Clinic Time Exceptions (0=None, else ptr to CLINIC.Clinic)';


CREATE  TABLE vacation (
  "Id" numeric(10,0) NOT NULL,
  "Provider" character(10),
  "Description" character(30),
  "StartDate" timestamp without time zone,
  "StartTime" numeric(10,0),
  "EndTime" numeric(10,0),
  "User" numeric(10,0),
  "Type" numeric(5,0),
  "DisplayDesc" character varying(30),
  "Deleted" numeric(5,0),
  "AuditId" numeric(10,0),
  "Color" numeric(10,0),
  "VacaSet" numeric(10,0),
  "SetException" numeric(5,0),
  "IsBreak" numeric(5,0),
  "AvailableClinic" numeric(10,0),
  CONSTRAINT vacation_primary PRIMARY KEY ("Id")
) ;
CREATE INDEX IF NOT EXISTS vacation_provider ON vacation USING btree ("Provider") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS vacation_type ON vacation USING btree ("Type", "User", "StartDate") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS vacation_vacaset ON vacation USING btree ("VacaSet") TABLESPACE pg_default;
COMMENT ON TABLE vacation IS 'Provider Vacations';
COMMENT ON COLUMN vacation."VacaSet" IS 'Non-clinic time associated with this vacation. Ptr to VACASET.VacaSet';
COMMENT ON COLUMN vacation."User" IS 'If Type=1, the user ID of the instructor that the vacation record is for. Ptr to USERS.User';
COMMENT ON COLUMN vacation."Type" IS 'Type of user this vacation is for (0=Provider, 1=Instructor)';
COMMENT ON COLUMN vacation."StartTime" IS 'Time that the vacation starts, in minutes from midnight.';
COMMENT ON COLUMN vacation."StartDate" IS 'Date that the vacation starts.';
COMMENT ON COLUMN vacation."SetException" IS 'Exception to the set? (0=No, 1=Yes)';
COMMENT ON COLUMN vacation."Provider" IS 'Provider that this vaction is for, ptr to PRODUCER.Producer';
COMMENT ON COLUMN vacation."IsBreak" IS 'Does this vacation qualify as a break time for providers? (0=No, 1=Yes)';
COMMENT ON COLUMN vacation."Id" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN vacation."EndTime" IS 'Time that the vacation ends, in minutes from midnight.';
COMMENT ON COLUMN vacation."DisplayDesc" IS 'The description that will display within the scheduler for this vacation time block.';
COMMENT ON COLUMN vacation."Description" IS 'Description/reason of the vacation.';
COMMENT ON COLUMN vacation."Deleted" IS 'Is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN vacation."Color" IS 'Color that the vacation displays with in the scheduler, numeric representation of RGB values.';
COMMENT ON COLUMN vacation."AvailableClinic" IS 'Clinic that the provider is only available in, for Clinic Time Exceptions (0=None, else ptr to CLINIC.Clinic)';
COMMENT ON COLUMN vacation."AuditId" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE vacatnh (
  "VacatnH" numeric(10,0) NOT NULL,
  "Id" numeric(10,0),
  "Provider" character(10),
  "Description" character(30),
  "StartDate" timestamp without time zone,
  "StartTime" numeric(10,0),
  "EndTime" numeric(10,0),
  "User" numeric(10,0),
  "Type" numeric(5,0),
  "DisplayDesc" character varying(30),
  "Deleted" numeric(5,0),
  "AuditId" numeric(10,0),
  "Color" numeric(10,0),
  "VacaSet" numeric(10,0),
  "SetException" numeric(5,0),
  "IsBreak" numeric(5,0),
  "AvailableClinic" numeric(10,0),
  CONSTRAINT vacatnh_primary PRIMARY KEY ("VacatnH")
) ;
CREATE INDEX IF NOT EXISTS vacatnh_id ON vacatnh USING btree ("Id") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS vacatnh_vacaset ON vacatnh USING btree ("VacaSet") TABLESPACE pg_default;
COMMENT ON TABLE vacatnh IS 'Provider Vacation History';
COMMENT ON COLUMN vacatnh."VacatnH" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN vacatnh."VacaSet" IS 'Non-clinic time associated with this vacation. Ptr to VACASET.VacaSet';
COMMENT ON COLUMN vacatnh."User" IS 'If Type=1, the user ID of the instructor that the vacation record is for. Ptr to USERS.User';
COMMENT ON COLUMN vacatnh."Type" IS 'Type of user this vacation is for (0=Provider, 1=Instructor)';
COMMENT ON COLUMN vacatnh."StartTime" IS 'Time that the vacation starts, in minutes from midnight.';
COMMENT ON COLUMN vacatnh."StartDate" IS 'Date that the vacation starts.';
COMMENT ON COLUMN vacatnh."SetException" IS 'Exception to the set? (0=No, 1=Yes)';
COMMENT ON COLUMN vacatnh."Provider" IS 'Provider that this vaction is for, ptr to PRODUCER.Producer';
COMMENT ON COLUMN vacatnh."IsBreak" IS 'Does this vacation qualify as a break time for providers? (0=No, 1=Yes)';
COMMENT ON COLUMN vacatnh."Id" IS 'Vacation record that this history is for. Ptr to VACATION.Id';
COMMENT ON COLUMN vacatnh."EndTime" IS 'Time that the vacation ends, in minutes from midnight.';
COMMENT ON COLUMN vacatnh."DisplayDesc" IS 'The description that will display within the scheduler for this vacation time block.';
COMMENT ON COLUMN vacatnh."Description" IS 'Description/reason of the vacation.';
COMMENT ON COLUMN vacatnh."Deleted" IS 'Is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN vacatnh."Color" IS 'Color that the vacation displays with in the scheduler, numeric representation of RGB values.';
COMMENT ON COLUMN vacatnh."AvailableClinic" IS 'Clinic that the provider is only available in, for Clinic Time Exceptions (0=None, else ptr to CLINIC.Clinic)';
COMMENT ON COLUMN vacatnh."AuditId" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE vendor (
  "Vendor" numeric(10,0) NOT NULL,
  "Name" character varying(50),
  "Address1" character varying(30),
  "Address2" character varying(30),
  "City" character varying(24),
  "Province" character varying(6),
  "Postal" character varying(15),
  "AddressOther" character varying(15),
  "Area" character(4),
  "Phone" character(8),
  "Salesman" character varying(50),
  "SalesArea" character(4),
  "SalesPhone" character(8),
  "SalesExt" character varying(6),
  "SalesEMail" character varying(100),
  "Comment" character varying(4000),
  "Inactive" numeric(5,0),
  "SalesOthArea" character(4),
  "SalesOthPhone" character(8),
  "SalesOthLoc" character(8),
  CONSTRAINT vendor_primary PRIMARY KEY ("Vendor")
) ;
COMMENT ON TABLE vendor IS 'Suppliers of Products';
COMMENT ON COLUMN vendor."Vendor" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN vendor."Salesman" IS 'Name of contact person ';
COMMENT ON COLUMN vendor."SalesPhone" IS 'Telephone number of vendor contact ';
COMMENT ON COLUMN vendor."SalesOthPhone" IS 'Other telephone number of vendor contact ';
COMMENT ON COLUMN vendor."SalesOthLoc" IS 'Other telephone location. i.e: Pager';
COMMENT ON COLUMN vendor."SalesOthArea" IS 'Other telephone area code of vendor contact ';
COMMENT ON COLUMN vendor."SalesExt" IS 'Telephone extension number of contact';
COMMENT ON COLUMN vendor."SalesEMail" IS 'Email address for vendor or vendor contact ';
COMMENT ON COLUMN vendor."SalesArea" IS 'Telephone area code of vendor contact ';
COMMENT ON COLUMN vendor."Province" IS 'Province / State, CITY.Province';
COMMENT ON COLUMN vendor."Postal" IS 'Postal / Zip code, ptr to CITY.Postal';
COMMENT ON COLUMN vendor."Phone" IS 'Telephone number of vendor ';
COMMENT ON COLUMN vendor."Name" IS 'Vendor name ';
COMMENT ON COLUMN vendor."Inactive" IS 'Vendor is inactive? (0 = No, 1 = Yes) ';
COMMENT ON COLUMN vendor."Comment" IS 'Short comment about vendor ';
COMMENT ON COLUMN vendor."City" IS 'City name, ptr to CITY.City';
COMMENT ON COLUMN vendor."Area" IS 'Telephone area code of vendor ';
COMMENT ON COLUMN vendor."AddressOther" IS 'County (if other than the institutions country)';
COMMENT ON COLUMN vendor."Address2" IS 'Vendor address line 2';
COMMENT ON COLUMN vendor."Address1" IS 'Vendor address line 1';


CREATE  TABLE visitfee (
  "PolIns" numeric(10,0) NOT NULL,
  "ProdType" character(1) NOT NULL,
  "VisitFee" numeric,
  CONSTRAINT visitfee_primary PRIMARY KEY ("PolIns", "ProdType")
) ;
COMMENT ON TABLE visitfee IS 'Visit Fee Overrides';
COMMENT ON COLUMN visitfee."VisitFee" IS 'Visit fee amount for the override, in dollars.';
COMMENT ON COLUMN visitfee."ProdType" IS 'Primary key component, the provider type that the override affects. Ptr to PRODTYPE.Code';
COMMENT ON COLUMN visitfee."PolIns" IS 'Primary key component, the policy that the override affects. Ptr to POLINS.PolIns';


CREATE  TABLE vkbatch (
  "VKBatch" numeric(10,0) NOT NULL,
  "Batch" character(15),
  "DateFrom" timestamp without time zone,
  "DateTo" timestamp without time zone,
  "Practice" numeric(5,0),
  "Insurance" character(6),
  "Audit" numeric(10,0),
  "BatchDate" timestamp without time zone,
  "ClaimsTotal" numeric,
  "PmtGrantedAmt" numeric,
  "InsPaymentRef" character varying(24),
  "PaymentDate" timestamp without time zone,
  "BatchErrCd1" character(4),
  "BatchErrCd2" character(4),
  "BatchErrCd3" character(4),
  "Status" numeric(5,0),
  "PmtFileName" character varying(255),
  mz302content clob,
  "LoadAudit" numeric(10,0),
  "ProcessAudit" numeric(10,0),
  CONSTRAINT vkbatch_primary PRIMARY KEY ("VKBatch")
) ;
CREATE INDEX IF NOT EXISTS vkbatch_batch ON vkbatch USING btree ("Batch") TABLESPACE pg_default;
COMMENT ON TABLE vkbatch IS 'Stores batch information for Vektis II';
COMMENT ON COLUMN vkbatch.mz302content IS 'The 302 file contents';
COMMENT ON COLUMN vkbatch."VKBatch" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN vkbatch."Status" IS 'Status (0=submitted, 1=rejected, 2=loaded, 3=processed)';
COMMENT ON COLUMN vkbatch."ProcessAudit" IS 'Audit date/time/user/station when Process was done';
COMMENT ON COLUMN vkbatch."Practice" IS 'Practice Id, ptr. to PRACTICE.Practice';
COMMENT ON COLUMN vkbatch."PmtGrantedAmt" IS 'Total amt paid by insurance. Can be +/-';
COMMENT ON COLUMN vkbatch."PmtFileName" IS 'The name of the 302 file';
COMMENT ON COLUMN vkbatch."PaymentDate" IS 'Payment date';
COMMENT ON COLUMN vkbatch."LoadAudit" IS 'Audit date/time/user/station when Load was done';
COMMENT ON COLUMN vkbatch."Insurance" IS 'Insurance company code that the batch is for, ptr. to INSURANC.Company';
COMMENT ON COLUMN vkbatch."InsPaymentRef" IS 'Insurance payment reference number';
COMMENT ON COLUMN vkbatch."DateTo" IS 'To Date';
COMMENT ON COLUMN vkbatch."DateFrom" IS 'From date';
COMMENT ON COLUMN vkbatch."ClaimsTotal" IS 'Total claims amount';
COMMENT ON COLUMN vkbatch."BatchErrCd3" IS 'Batch rejection error';
COMMENT ON COLUMN vkbatch."BatchErrCd2" IS 'Batch rejection error';
COMMENT ON COLUMN vkbatch."BatchErrCd1" IS 'Batch rejection error';
COMMENT ON COLUMN vkbatch."BatchDate" IS 'Date batch created';
COMMENT ON COLUMN vkbatch."Batch" IS 'Batch number';
COMMENT ON COLUMN vkbatch."Audit" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE vkclaim (
  "VKClaim" numeric(10,0) NOT NULL,
  "VKBatch" numeric(10,0),
  "Type" numeric(5,0),
  "Id" numeric(10,0),
  "InsNumber" numeric(5,0),
  "Patient" numeric(10,0),
  "Date" timestamp without time zone,
  "PatErrCd1" character(4),
  "PatErrCd2" character(4),
  "PatErrCd3" character(4),
  CONSTRAINT vkclaim_primary PRIMARY KEY ("VKClaim")
) ;
CREATE INDEX IF NOT EXISTS vkclaim_batch ON vkclaim USING btree ("VKBatch") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS vkclaim_trx ON vkclaim USING btree ("Type", "Id", "InsNumber") TABLESPACE pg_default;
COMMENT ON TABLE vkclaim IS 'Stores claim information for Vektis II';
COMMENT ON COLUMN vkclaim."VKClaim" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN vkclaim."VKBatch" IS 'Batch Id this claim belongs to, ptr. to VKBATCH.VKBatch';
COMMENT ON COLUMN vkclaim."Type" IS 'Transaction type, ptr. to TRX.Type';
COMMENT ON COLUMN vkclaim."Patient" IS 'Id code to identify the patient, ptr to PATIENT.Patient';
COMMENT ON COLUMN vkclaim."PatErrCd3" IS 'Patient rejection error';
COMMENT ON COLUMN vkclaim."PatErrCd2" IS 'Patient rejection error';
COMMENT ON COLUMN vkclaim."PatErrCd1" IS 'Patient rejection error';
COMMENT ON COLUMN vkclaim."InsNumber" IS 'Treatment Insurance number';
COMMENT ON COLUMN vkclaim."Id" IS 'Transaction ID, ptr. to TRX.Id';
COMMENT ON COLUMN vkclaim."Date" IS 'Treatment date';


CREATE  TABLE vkclmit (
  "VKClmIt" numeric(10,0) NOT NULL,
  "VKClaim" numeric(10,0),
  "Type" numeric(5,0),
  "Id" numeric(10,0),
  "Treatment" numeric(5,0),
  "OrigRecNo" numeric(10,0),
  "Procedure" character(7),
  "Site" character(3),
  "Surface" character(6),
  "Total" numeric,
  "InsTotal" numeric,
  "LabOrigRecNo" numeric(10,0),
  "PmtGrantedAmt" numeric,
  "PmtType" numeric(5,0),
  "ProcessType" numeric(5,0),
  "TrxErrCd1" character(4),
  "TrxErrCd2" character(4),
  "TrxErrCd3" character(4),
  "LabTotal" numeric,
  "LabInsTotal" numeric,
  "ErrCode" numeric(5,0),
  "SeqNo" numeric(10,0),
  "PrevInsPmtId" numeric(10,0) NOT NULL DEFAULT 0,
  CONSTRAINT vkclmit_primary PRIMARY KEY ("VKClmIt")
) ;
CREATE INDEX IF NOT EXISTS vkclmit_origrecno ON vkclmit USING btree ("OrigRecNo") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS vkclmit_trx ON vkclmit USING btree ("Type", "Id", "Treatment") TABLESPACE pg_default;
COMMENT ON TABLE vkclmit IS 'Stores claim item information for Vektis II';
COMMENT ON COLUMN vkclmit."VKClmIt" IS 'Primary key, internal ID from sequence.';
COMMENT ON COLUMN vkclmit."VKClaim" IS 'Claim number this item belongs to, ptr. to VKCLAIM.VKClaim';
COMMENT ON COLUMN vkclmit."Type" IS 'Transaction type, ptr. to TRX.Type';
COMMENT ON COLUMN vkclmit."TrxErrCd3" IS 'Trx rejection error';
COMMENT ON COLUMN vkclmit."TrxErrCd2" IS 'Trx rejection error';
COMMENT ON COLUMN vkclmit."TrxErrCd1" IS 'Trx rejection error';
COMMENT ON COLUMN vkclmit."Treatment" IS 'Transaction treatment, ptr. to TRX.Treatment';
COMMENT ON COLUMN vkclmit."Total" IS 'Treatment total, ptr. to TRX.Total';
COMMENT ON COLUMN vkclmit."Surface" IS 'Treatment surface, ptr. to TRX.Surface';
COMMENT ON COLUMN vkclmit."Site" IS 'Treatment site, ptr. to TRX.Site';
COMMENT ON COLUMN vkclmit."SeqNo" IS 'Sequence number returned in the 302 file';
COMMENT ON COLUMN vkclmit."ProcessType" IS 'Processing result type (0=N/A, 1=Paid as expected, 2=Underpayment w/balance,3=Underpayment w/ writeoff, 4=Underpayment w/ TSF, 5=Underpayment rebilled, 6=Overpayment w/ balance, 7=Overpayment w/ writeoff, 8=Overpayment w/ TSF, 9=Overpayment rebilled)';
COMMENT ON COLUMN vkclmit."Procedure" IS 'Treatment procedure, ptr. to TRX.Procedure';
COMMENT ON COLUMN vkclmit."PrevInsPmtId" IS 'Previous insurance payment ID this record belongs to, if applicable, ptr to TRX.Id';
COMMENT ON COLUMN vkclmit."PmtType" IS 'Payment type (0=N/A, 1=Paid in full, 2=Underpayment, 3=Overpayment, 4=Rejection, 5=Reversal, 6=PreAuth, 7=Forwarded)';
COMMENT ON COLUMN vkclmit."PmtGrantedAmt" IS 'Total amt paid by insurance. Can be +/-';
COMMENT ON COLUMN vkclmit."OrigRecNo" IS 'Treatment original record number, ptr. to TRX.OrigRecNo';
COMMENT ON COLUMN vkclmit."LabTotal" IS 'Treatment lab total';
COMMENT ON COLUMN vkclmit."LabOrigRecNo" IS 'Treatment original record number of the lab procedure, ptr. to TRX.OrigRecNo';
COMMENT ON COLUMN vkclmit."LabInsTotal" IS 'Treatment lab insurance total';
COMMENT ON COLUMN vkclmit."InsTotal" IS 'Treatment insurance total, ptr. to TRX.InsTotal';
COMMENT ON COLUMN vkclmit."Id" IS 'Transaction ID, ptr. to TRX.Id';
COMMENT ON COLUMN vkclmit."ErrCode" IS 'If error during processing (301=Tx not found, 302=Tx not expecting payment, 306=Not enough funds)';


CREATE  TABLE vkcomm (
  "VKComm" numeric(10,0) NOT NULL,
  "VKBatch" numeric(10,0),
  "VKClaim" numeric(10,0),
  "VKClmIt" numeric(10,0),
  "Type" numeric(5,0),
  "LineNo" numeric(5,0),
  "Text" character varying(140),
  "RetCd1" character(4),
  "RetCd2" character(4),
  "RetCd3" character(4),
  CONSTRAINT vkcomm_primary PRIMARY KEY ("VKComm")
) ;
COMMENT ON TABLE vkcomm IS 'Stores 302 remittance response comment information for Vektis II';
COMMENT ON COLUMN vkcomm."VKComm" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN vkcomm."VKClmIt" IS 'Ptr. to VKBATCH.VKClaimIt';
COMMENT ON COLUMN vkcomm."VKClaim" IS 'Ptr. to VKBATCH.VKClaim';
COMMENT ON COLUMN vkcomm."VKBatch" IS 'Ptr. to VKBATCH.VKBatch';
COMMENT ON COLUMN vkcomm."Type" IS 'Type (0=Batch, 1=Claim, 2=Claim Item)';
COMMENT ON COLUMN vkcomm."Text" IS 'Comment';
COMMENT ON COLUMN vkcomm."RetCd3" IS 'Response Code 3';
COMMENT ON COLUMN vkcomm."RetCd2" IS 'Response Code 2';
COMMENT ON COLUMN vkcomm."RetCd1" IS 'Response Code 1';
COMMENT ON COLUMN vkcomm."LineNo" IS 'Line number';


CREATE  TABLE vkremerr (
  "Code" character(4) NOT NULL,
  "Description" character varying(200),
  "Inactive" numeric(5,0),
  CONSTRAINT vkremerr_primary PRIMARY KEY ("Code")
) ;
COMMENT ON TABLE vkremerr IS 'Stores remittance error codes';
COMMENT ON COLUMN vkremerr."Inactive" IS 'Inactive? (0=No, 1=Yes)';
COMMENT ON COLUMN vkremerr."Description" IS 'Remittance response description';
COMMENT ON COLUMN vkremerr."Code" IS 'Remittance response code';


CREATE  TABLE waitlhis (
  "WaitLHis" numeric(10,0) NOT NULL,
  "WaitList" numeric(10,0),
  "Appointment" numeric(10,0),
  "WaitRsn" character(6),
  "Priority" numeric(5,0),
  "Note" character varying(4000),
  "Status" numeric(5,0),
  "CreateAudit" numeric(10,0),
  "Audit" numeric(10,0),
  CONSTRAINT waitlhis_primary PRIMARY KEY ("WaitLHis")
) ;
COMMENT ON TABLE waitlhis IS 'Wait List History';
COMMENT ON COLUMN waitlhis."WaitRsn" IS 'Wait list reason';
COMMENT ON COLUMN waitlhis."WaitList" IS 'Ptr to WAITLIST.WaitList';
COMMENT ON COLUMN waitlhis."WaitLHis" IS 'WaitLHis ID, Sequenced, primary key';
COMMENT ON COLUMN waitlhis."Status" IS '0=Active, 1=Resolved, 2=Expired, 3=Removed';
COMMENT ON COLUMN waitlhis."Priority" IS '[1.. 99]';
COMMENT ON COLUMN waitlhis."Note" IS 'Description/note';
COMMENT ON COLUMN waitlhis."CreateAudit" IS 'When it was added to the list (ptr to AUDITHIS.Audit)';
COMMENT ON COLUMN waitlhis."Audit" IS 'When it was it was last modified (ptr to AUDITHIS.Audit)';
COMMENT ON COLUMN waitlhis."Appointment" IS 'Ptr to APPOINT.Appointment.';


CREATE  TABLE waitlist (
  "WaitList" numeric(10,0) NOT NULL,
  "Appointment" numeric(10,0),
  "WaitRsn" character(6),
  "Priority" numeric(5,0),
  "Note" character varying(4000),
  "Status" numeric(5,0),
  "CreateAudit" numeric(10,0),
  "Audit" numeric(10,0),
  CONSTRAINT waitlist_primary PRIMARY KEY ("WaitList")
) ;
CREATE INDEX IF NOT EXISTS waitlist_appointment ON waitlist USING btree ("Appointment") TABLESPACE pg_default;
COMMENT ON TABLE waitlist IS 'Wait List Records';
COMMENT ON COLUMN waitlist."WaitRsn" IS 'Wait list reason';
COMMENT ON COLUMN waitlist."WaitList" IS 'WaitList ID, Sequenced, primary key';
COMMENT ON COLUMN waitlist."Status" IS '0=Active, 1=Resolved, 2=Expired, 3=Removed';
COMMENT ON COLUMN waitlist."Priority" IS '[1.. 99]';
COMMENT ON COLUMN waitlist."Note" IS 'Description/note';
COMMENT ON COLUMN waitlist."CreateAudit" IS 'When it was added to the list (ptr to AUDITHIS.Audit)';
COMMENT ON COLUMN waitlist."Audit" IS 'When it was it was last modified (ptr to AUDITHIS.Audit)';
COMMENT ON COLUMN waitlist."Appointment" IS 'Ptr to APPOINT.Appointment.';


CREATE  TABLE waitrsn (
  "WaitRsn" character(6) NOT NULL,
  "Description" character varying(30),
  "DefaultPri" numeric(5,0),
  "ExpiryDays" numeric(5,0),
  CONSTRAINT waitrsn_primary PRIMARY KEY ("WaitRsn")
) ;
COMMENT ON TABLE waitrsn IS 'Wait Reason';
COMMENT ON COLUMN waitrsn."WaitRsn" IS 'Wait Reason Code, Primary key';
COMMENT ON COLUMN waitrsn."ExpiryDays" IS 'If APPOINT.Type=0, Will expire #Days before the booked appointment';
COMMENT ON COLUMN waitrsn."Description" IS 'Wait Reason Description';
COMMENT ON COLUMN waitrsn."DefaultPri" IS '1=High, 2=fairly high, .. 99=dead last';


CREATE  TABLE workschd (
  "Id" numeric(10,0) NOT NULL,
  "Provider" character(10),
  "Description" character(30),
  "StartDate" timestamp without time zone,
  "EndDate" timestamp without time zone,
  "Monday" numeric(5,0),
  "Tuesday" numeric(5,0),
  "Wednesday" numeric(5,0),
  "Thursday" numeric(5,0),
  "Friday" numeric(5,0),
  "Saturday" numeric(5,0),
  "Sunday" numeric(5,0),
  "Cycle" numeric(5,0),
  "CycleStart" timestamp without time zone,
  "WorkSchType" numeric(5,0),
  "ExcWorkSchId" numeric(10,0),
  "User" numeric(10,0),
  "Type" numeric(5,0),
  "Deleted" numeric(5,0),
  "AuditId" numeric(10,0),
  "CycleType" numeric(5,0),
  "CycleFrq" numeric(5,0),
  CONSTRAINT workschd_primary PRIMARY KEY ("Id")
) ;
CREATE INDEX IF NOT EXISTS workschd_provider ON workschd USING btree ("Provider") TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS workschd_type ON workschd USING btree ("Type", "User", "StartDate") TABLESPACE pg_default;
COMMENT ON TABLE workschd IS 'Work Schedules';
COMMENT ON COLUMN workschd."WorkSchType" IS 'Work schedule type (1=Normal, 2=Exception)';
COMMENT ON COLUMN workschd."Wednesday" IS 'Applies to Wednesday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN workschd."User" IS 'ID code of the user, ptr to USERS.User';
COMMENT ON COLUMN workschd."Type" IS 'Type of user the work schedule is for (0=Provider schedule, 1=Instructor schedule)';
COMMENT ON COLUMN workschd."Tuesday" IS 'Applies to Tuesday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN workschd."Thursday" IS 'Applies to Thursday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN workschd."Sunday" IS 'Applies to Sunday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN workschd."StartDate" IS 'Date that the work schedule starts.';
COMMENT ON COLUMN workschd."Saturday" IS 'Applies to Saturday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN workschd."Provider" IS 'Provider ID, ptr to PRODUCER.Producer';
COMMENT ON COLUMN workschd."Monday" IS 'Applies to Monday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN workschd."Id" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN workschd."Friday" IS 'Applies to Friday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN workschd."ExcWorkSchId" IS 'If WorkSchType=2, then the work schedule that the exception applies to. Ptr to WORKSCHD.Id';
COMMENT ON COLUMN workschd."EndDate" IS 'Date that the work schedule ends. ';
COMMENT ON COLUMN workschd."Description" IS 'Description of the work schedule. ';
COMMENT ON COLUMN workschd."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN workschd."CycleType" IS 'Cycle type for work schedules/non-clinic times (0=Weekly, 1=Monthly)';
COMMENT ON COLUMN workschd."CycleStart" IS 'Date the cycle starts.';
COMMENT ON COLUMN workschd."CycleFrq" IS 'If CycleType=1, cycle recurs on the (0=First, 1=Second, 2=Third, 3=Fourth, 4=Last)';
COMMENT ON COLUMN workschd."Cycle" IS 'Number of weeks for cycle (1=Weekly, 2=Bi-Weekly, 3=every third week, etc)';
COMMENT ON COLUMN workschd."AuditId" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE wrkschh (
  "WrkSchH" numeric(10,0) NOT NULL,
  "Id" numeric(10,0),
  "Provider" character(10),
  "Description" character(30),
  "StartDate" timestamp without time zone,
  "EndDate" timestamp without time zone,
  "Monday" numeric(5,0),
  "Tuesday" numeric(5,0),
  "Wednesday" numeric(5,0),
  "Thursday" numeric(5,0),
  "Friday" numeric(5,0),
  "Saturday" numeric(5,0),
  "Sunday" numeric(5,0),
  "Cycle" numeric(5,0),
  "CycleStart" timestamp without time zone,
  "WorkSchType" numeric(5,0),
  "ExcWorkSchId" numeric(10,0),
  "User" numeric(10,0),
  "Type" numeric(5,0),
  "Deleted" numeric(5,0),
  "AuditId" numeric(10,0),
  "CycleType" numeric(5,0),
  "CycleFrq" numeric(5,0),
  CONSTRAINT wrkschh_primary PRIMARY KEY ("WrkSchH")
) ;
CREATE INDEX IF NOT EXISTS wrkschh_id ON wrkschh USING btree ("Id") TABLESPACE pg_default;
COMMENT ON TABLE wrkschh IS 'Work Schedule History';
COMMENT ON COLUMN wrkschh."WrkSchH" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN wrkschh."WorkSchType" IS 'Work schedule type (1=Normal, 2=Exception)';
COMMENT ON COLUMN wrkschh."Wednesday" IS 'Applies to Wednesday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN wrkschh."User" IS 'ID code of the user, ptr to USERS.User';
COMMENT ON COLUMN wrkschh."Type" IS 'Type of user the work schedule is for (0=Provider schedule, 1=Instructor schedule)';
COMMENT ON COLUMN wrkschh."Tuesday" IS 'Applies to Tuesday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN wrkschh."Thursday" IS 'Applies to Thursday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN wrkschh."Sunday" IS 'Applies to Sunday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN wrkschh."StartDate" IS 'Date that the work schedule starts.';
COMMENT ON COLUMN wrkschh."Saturday" IS 'Applies to Saturday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN wrkschh."Provider" IS 'Provider ID, ptr to PRODUCER.Producer';
COMMENT ON COLUMN wrkschh."Monday" IS 'Applies to Monday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN wrkschh."Id" IS 'Work schedule that this history is for, ptr to WORKSCHD.Id';
COMMENT ON COLUMN wrkschh."Friday" IS 'Applies to Friday? (0 = No, 1 = Yes)';
COMMENT ON COLUMN wrkschh."ExcWorkSchId" IS 'If WorkSchType=2, then the work schedule that the exception applies to. Ptr to WORKSCHD.Id';
COMMENT ON COLUMN wrkschh."EndDate" IS 'Date that the work schedule ends. ';
COMMENT ON COLUMN wrkschh."Description" IS 'Description of the work schedule. ';
COMMENT ON COLUMN wrkschh."Deleted" IS 'Deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN wrkschh."CycleType" IS 'Cycle type for work schedules/non-clinic times (0=Weekly, 1=Monthly)';
COMMENT ON COLUMN wrkschh."CycleStart" IS 'Date the cycle starts.';
COMMENT ON COLUMN wrkschh."CycleFrq" IS 'If CycleType=1, cycle recurs on the (0=First, 1=Second, 2=Third, 3=Fourth, 4=Last)';
COMMENT ON COLUMN wrkschh."Cycle" IS 'Number of weeks for cycle (1=Weekly, 2=Bi-Weekly, 3=every third week, etc)';
COMMENT ON COLUMN wrkschh."AuditId" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE wschitch (
  "WSchItChair" numeric(10,0) NOT NULL,
  "WSchItem" numeric(10,0),
  "Chair" numeric(10,0),
  CONSTRAINT wschitch_primary PRIMARY KEY ("WSchItChair")
) ;
CREATE INDEX IF NOT EXISTS wschitch_wschitem ON wschitch USING btree ("WSchItem") TABLESPACE pg_default;
COMMENT ON TABLE wschitch IS 'Work Schedule Item Chairs';
COMMENT ON COLUMN wschitch."WSchItem" IS 'Work schedule item that this record is for, ptr to WSCHITEM.Id';
COMMENT ON COLUMN wschitch."WSchItChair" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN wschitch."Chair" IS 'The chair to reserve, ptr to CHAIR.Chair';


CREATE  TABLE wschitem (
  "Id" numeric(10,0) NOT NULL,
  "WorkschdId" numeric(10,0) NOT NULL,
  "Weekday" numeric(5,0),
  "StartTime" numeric(10,0),
  "EndTime" numeric(10,0),
  "Clinic" numeric(10,0),
  "NumChairs" numeric(5,0),
  "ClinicTime" numeric(10,0),
  "PGroup" character(6),
  "Deleted" numeric(5,0),
  "AuditId" numeric(10,0),
  "ReserveChangeDate" timestamp without time zone,
  "BreakT" numeric(10,0),
  "UseSharedChairs" numeric(5,0),
  CONSTRAINT wschitem_primary PRIMARY KEY ("Id")
) ;
CREATE INDEX IF NOT EXISTS wschitem_workschd ON wschitem USING btree ("WorkschdId", "Weekday") TABLESPACE pg_default;
COMMENT ON TABLE wschitem IS 'Work Schedule Items';
COMMENT ON COLUMN wschitem."WorkschdId" IS 'Work schedule that contains this item, ptr to WORKSCHD.Id';
COMMENT ON COLUMN wschitem."Weekday" IS 'Day of the week (1=Sunday, 2=Monday, 3=Tuesday, 4=Wednesday, 5=Thursday, 6=Friday, 7=Saturday)';
COMMENT ON COLUMN wschitem."UseSharedChairs" IS 'Use shared chairs? (0=No, 1=Yes)';
COMMENT ON COLUMN wschitem."StartTime" IS 'Start time (in minutes from midnight)';
COMMENT ON COLUMN wschitem."ReserveChangeDate" IS 'Date on which the reserve changed.';
COMMENT ON COLUMN wschitem."PGroup" IS 'Provider group for this item, ptr to PGROUP.Pgroup';
COMMENT ON COLUMN wschitem."NumChairs" IS 'Number of chairs the provider will be working in/require';
COMMENT ON COLUMN wschitem."Id" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN wschitem."EndTime" IS 'End time (in minutes from midnight)';
COMMENT ON COLUMN wschitem."Deleted" IS 'Is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN wschitem."ClinicTime" IS 'The clinic time record to which this item refers, ptr to CLINICT.ClinicTime';
COMMENT ON COLUMN wschitem."Clinic" IS 'Clinic that this item is for, ptr to CLINIC.Clinic';
COMMENT ON COLUMN wschitem."BreakT" IS 'Break rule for this item, ptr to BREAKT.BreakT';
COMMENT ON COLUMN wschitem."AuditId" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE wschitmh (
  "WSchItmH" numeric(10,0) NOT NULL,
  "Id" numeric(10,0),
  "WorkschdId" numeric(10,0),
  "Weekday" numeric(5,0),
  "StartTime" numeric(10,0),
  "EndTime" numeric(10,0),
  "Clinic" numeric(10,0),
  "NumChairs" numeric(5,0),
  "ClinicTime" numeric(10,0),
  "PGroup" character(6),
  "Deleted" numeric(5,0),
  "AuditId" numeric(10,0),
  "ReserveChangeDate" timestamp without time zone,
  "BreakT" numeric(10,0),
  "UseSharedChairs" numeric(5,0),
  CONSTRAINT wschitmh_primary PRIMARY KEY ("WSchItmH")
) ;
CREATE INDEX IF NOT EXISTS wschitmh_id ON wschitmh USING btree ("Id") TABLESPACE pg_default;
COMMENT ON TABLE wschitmh IS 'Work Schedule Item History';
COMMENT ON COLUMN wschitmh."WorkschdId" IS 'Work schedule that contains this item, ptr to WORKSCHD.Id';
COMMENT ON COLUMN wschitmh."Weekday" IS 'Day of the week (1=Sunday, 2=Monday, 3=Tuesday, 4=Wednesday, 5=Thursday, 6=Friday, 7=Saturday)';
COMMENT ON COLUMN wschitmh."WSchItmH" IS 'Primary key, internal ID from sequence. ';
COMMENT ON COLUMN wschitmh."UseSharedChairs" IS 'Use shared chairs? (0=No, 1=Yes)';
COMMENT ON COLUMN wschitmh."StartTime" IS 'Start time (in minutes from midnight)';
COMMENT ON COLUMN wschitmh."ReserveChangeDate" IS 'Date on which the reserve changed.';
COMMENT ON COLUMN wschitmh."PGroup" IS 'Provider group for this item, ptr to PGROUP.Pgroup';
COMMENT ON COLUMN wschitmh."NumChairs" IS 'Number of chairs the provider will be working in/require';
COMMENT ON COLUMN wschitmh."Id" IS 'Work schedule item that this history is for, ptr to WSCHITEM.Id';
COMMENT ON COLUMN wschitmh."EndTime" IS 'End time (in minutes from midnight)';
COMMENT ON COLUMN wschitmh."Deleted" IS 'Is deleted? (0 = No, 1 = Yes)';
COMMENT ON COLUMN wschitmh."ClinicTime" IS 'The clinic time record to which this item refers, ptr to CLINICT.ClinicTime';
COMMENT ON COLUMN wschitmh."Clinic" IS 'Clinic that this item is for, ptr to CLINIC.Clinic';
COMMENT ON COLUMN wschitmh."BreakT" IS 'Break rule for this item, ptr to BREAKT.BreakT';
COMMENT ON COLUMN wschitmh."AuditId" IS 'Audit history, ptr to AUDITHIS.Audit';


CREATE  TABLE xrayinfo (
  "XRayInfo" numeric(10,0) NOT NULL,
  "PtPrev" numeric(10,0),
  "Patient" numeric(10,0),
  "BWRMolar" numeric(5,0),
  "BWRPremolar" numeric(5,0),
  "BWLMolar" numeric(5,0),
  "BWLPremolar" numeric(5,0),
  "PA" character varying(20),
  "Panoramic" numeric(5,0),
  "Cephalometric" numeric(5,0),
  "FMX" numeric(5,0),
  "Other" character varying(20),
  "Note" character varying(4000),
  "Taken" numeric(5,0),
  CONSTRAINT xrayinfo_primary PRIMARY KEY ("XRayInfo")
) ;
COMMENT ON TABLE xrayinfo IS 'Stored information about which x-rays are planned for the recall';
COMMENT ON COLUMN xrayinfo."XRayInfo" IS 'Sequenced primary key';
COMMENT ON COLUMN xrayinfo."Taken" IS '0=No, 1=Yes';
COMMENT ON COLUMN xrayinfo."PtPrev" IS 'PtPrev the xray info is for (PTPREV.PtPrev)';
COMMENT ON COLUMN xrayinfo."Patient" IS 'Patient the xray info is for (PATIENT.Patient)';
COMMENT ON COLUMN xrayinfo."Panoramic" IS 'y/n panoramic';
COMMENT ON COLUMN xrayinfo."PA" IS 'free text (PA # tooth sites)';
COMMENT ON COLUMN xrayinfo."Other" IS 'other x-rays needed (eg. Hand)';
COMMENT ON COLUMN xrayinfo."Note" IS 'note about the xrays needed';
COMMENT ON COLUMN xrayinfo."FMX" IS 'y/n "FMX"';
COMMENT ON COLUMN xrayinfo."Cephalometric" IS 'y/n cephalometric';
COMMENT ON COLUMN xrayinfo."BWRPremolar" IS 'y/n bitewing on right premolar';
COMMENT ON COLUMN xrayinfo."BWRMolar" IS 'y/n bitewing on right molar';
COMMENT ON COLUMN xrayinfo."BWLPremolar" IS 'y/n bitewing on left premolar';
COMMENT ON COLUMN xrayinfo."BWLMolar" IS 'y/n bitewing on left molar';


 
-- PRIORITY VIEWS 
CREATE OR REPLACE VIEW ptletter AS
 SELECT d."PtLetter",
    d."Patient",
    d."Description",
    d."Date",
    d."User",
    d."Path",
    d."Type",
    d."Deleted",
    d."StationId",
    c.content,
    d."FileExt",
    d."DelAudit",
    d."AtTab",
    d."Consent",
    d."ExpiryDate",
    d."Status",
    d."OrigId",
    d."AuditNumber",
    d."DocTempl",
    d."AppUser",
    d."AppDate",
    d."ModifiedDate",
    d."OwnerType",
    d."OwnerId",
    d."AddDateTime"
   FROM ptldetails d,
    ptlcontent c
  WHERE d."PtLetter" = c."PtLetter"
;
CREATE OR REPLACE VIEW user_procedures AS
 SELECT
        CASE
            WHEN n.nspname <> (( SELECT "current_schema"() AS "current_schema")) THEN 'PACKAGE'::text
            WHEN p.prokind = 'p'::"char" THEN 'PROCEDURE'::text
            WHEN p.prokind = 'f'::"char" THEN 'FUNCTION'::text
            ELSE NULL::text
        END AS object_type,
        CASE
            WHEN n.nspname <> (( SELECT "current_schema"() AS "current_schema")) THEN upper(n.nspname::text)
            ELSE upper(p.proname::text)
        END AS object_name,
        CASE
            WHEN n.nspname <> (( SELECT "current_schema"() AS "current_schema")) THEN upper(p.proname::text)
            ELSE NULL::text
        END AS procedure_name,
    p.oid AS object_id
   FROM pg_proc p,
    pg_namespace n
  WHERE p.pronamespace = n.oid
;
CREATE OR REPLACE VIEW user_view AS
 SELECT 0 AS "Type",
    u."User",
    u."Name"::character varying(30) AS "Last",
    u."First"::character varying(30) AS "First",
    u."Preferred"::character varying(30) AS "Preferred",
    u."Middle"::character varying(15) AS "Middle",
    u."Producer" AS "Provider",
    0 AS "Deleted",
    0 AS "Expired",
    u."Logon"::character varying(100) AS "Logon",
    u."Password",
    u."SwipeLogon"::character varying(100) AS "SwipeLogon",
    u."SwipePassword",
    0 AS "Audit"
   FROM users u
  WHERE 0 = 1
UNION ALL
 SELECT 0 AS "Type",
    u."User",
    TRIM(BOTH FROM u."Name")::character varying(30) AS "Last",
    TRIM(BOTH FROM u."First")::character varying(30) AS "First",
    TRIM(BOTH FROM u."Preferred")::character varying(30) AS "Preferred",
    TRIM(BOTH FROM u."Middle")::character varying(15) AS "Middle",
    u."Producer" AS "Provider",
    u."Deleted",
        CASE
            WHEN nvl(u."ExpDate", sysdate) < trunc(sysdate) THEN 1
            ELSE 0
        END AS "Expired",
    u."Logon"::character varying(100) AS "Logon",
    u."Password",
    u."SwipeLogon"::character varying(100) AS "SwipeLogon",
    u."SwipePassword"::character varying(45) AS "SwipePassword",
    u."Audit"
   FROM users u
UNION ALL
 SELECT 1 AS "Type",
    i."iUser" AS "User",
    TRIM(BOTH FROM p."Last")::character varying(30) AS "Last",
    TRIM(BOTH FROM p."First")::character varying(30) AS "First",
    TRIM(BOTH FROM p."Prefered")::character varying(30) AS "Preferred",
    TRIM(BOTH FROM p."Middle")::character varying(15) AS "Middle",
    NULL::bpchar AS "Provider",
    p."Deleted",
    0 AS "Expired",
    i."UserName" AS "Logon",
    i."Password"::character varying(61) AS "Password",
    ' '::character varying(100) AS "SwipeLogon",
    ' '::character varying(45) AS "SwipePassword",
        CASE
            WHEN p."Audit" > i."Audit" THEN p."Audit"
            ELSE i."Audit"
        END AS "Audit"
   FROM iuser i,
    patient p
  WHERE i."Type" = 0::numeric AND i."Id" = p."Patient"
;
 
-- PACKAGE SPECS 
-- Dependant packages first 
CREATE OR REPLACE PACKAGE cursor_pkg IS

  TYPE weakcursor IS REF CURSOR;

END;
CREATE OR REPLACE PACKAGE ax_pkg IS 

/******************************************************************************

* AXSO - ax_pkg

* 

* Common Functionality for other AXium Scripting Objects

*

* Revisions:

*   SF-00209922 Mar 06, 2019 blc Fixed a problem with GetStationUser_P returning incorrect user/station information when run from a process outside of axiUm

*   SF-00248344 Jul 13, 2020 blc Added procedure GetOvernightUser_F for backward compatibility.

*   AX-27010 	Jun 23, 22   j.s removed all references to hardcoded table spaces, causing Oracle errors

*   AX-36778    Jun 02, 25   j.s removed obsolete dbmsoutput_linesarray variable

* 	AX-39259     May 28, 25  w.s Changed all $$PLSQL_UNIT to DDL name for both Oracle and EDB compatiblity

*	AX-37536     May 28, 25	 j.s removed unused DBMSOUTPUT_LINE declarations				

*

******************************************************************************/



  -- Package Version

  --   Increment whenever you make changes.

  --   For New Items increment the number to the left of the decimal, and set the number on the right to 00

  --   For Changes increment the number to the right of the decimal

  version CONSTANT numeric DEFAULT 9.00;

  -- Version of axiUm this package is made to be compatible with.

  --   Only include Major Releases, as Patch Releases should not impact compatibility

  axium_version CONSTANT numeric DEFAULT 0.00; --DEV



/*

 

  -- Requires:

   

--------------------------------------------------------

--  DDL for Table AX_LOG

--------------------------------------------------------

   

  CREATE TABLE "AX_LOG"

   (    

    "LogId" NUMBER,

    "LogSetId" NUMBER,

    "DateTime" TIMESTAMP (6),

    "Source" VARCHAR2(255 BYTE),

    "Request" VARCHAR2(50 BYTE),

    "User" NUMBER,

    "StationId" NUMBER,

    "Log" VARCHAR2(4000 BYTE)

   );

--------------------------------------------------------

--  DDL for Index AX_LOG_PK

--------------------------------------------------------

   

  CREATE UNIQUE INDEX "AX_LOG_PK" ON "AX_LOG" ("LogId");

--------------------------------------------------------

--  Constraints for Table AX_LOG

--------------------------------------------------------

   

  ALTER TABLE "AX_LOG" ADD CONSTRAINT "AX_LOG_PK" PRIMARY KEY ("LogId")

  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS

  ENABLE;

    

  ALTER TABLE "AX_LOG" MODIFY ("LogId" NOT NULL ENABLE);

   

--------------------------------------------------------

--  DDL for Sequence AXLOG_SEQ

--------------------------------------------------------

   

   CREATE SEQUENCE  "AX_LOG_LOGID_SEQ"  MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 1 NOCACHE 

ORDER NOCYCLE;



--------------------------------------------------------

--  DDL for Table AX_SETTING

--------------------------------------------------------

 

  CREATE TABLE "AX_SETTING"

   (    

    "axSetting" NUMBER(5,0),

    "Key" VARCHAR2(255 BYTE),

    "SettingType" NUMBER(5,0),

    "axSettingGrp" NUMBER(5,0),

    "Priority" NUMBER(5,0),

    "Value" VARCHAR2(4000 BYTE),

    "Description" VARCHAR2(4000 BYTE)

   );

--------------------------------------------------------

--  Constraints for Table AX_SETTING

--------------------------------------------------------

 

  ALTER TABLE "AX_SETTING" MODIFY ("axSetting" NOT NULL ENABLE);

  

  ALTER TABLE "AX_SETTING" MODIFY ("Key" NOT NULL ENABLE);

  

  ALTER TABLE "AX_SETTING" MODIFY ("SettingType" NOT NULL ENABLE);

 

  ALTER TABLE AX_SETTING ADD CONSTRAINT AX_SETTING_KEY UNIQUE("Key") ENABLE;

 

--------------------------------------------------------

--  Sequence for Table AX_SETTING

--------------------------------------------------------

 

  CREATE SEQUENCE  AX_SETTING_AXSETTING_SEQ  MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 1 

NOCACHE;

 

--------------------------------------------------------

--  DDL for Table AX_HELP

-------------------------------------------------------- 

 

  CREATE TABLE "AX_HELP"

   (    

    "PackageName" varchar2(30),

    "ObjectName" varchar2(30),

    "Description" varchar2(4000)

   );

  

--------------------------------------------------------

--  Constraints for Table AX_HELP

--------------------------------------------------------  

  

  ALTER TABLE AX_HELP ADD CONSTRAINT AX_HELP_KEY UNIQUE("PackageName","ObjectName") ENABLE;

 

 

*/



  -- Constants

  

    -- Message Types

      -- These Constants should be used in your PL/SQL Objects to describe the type of message being shared.

  msg_error CONSTANT numeric DEFAULT 1;  -- Error

  msg_warning CONSTANT numeric DEFAULT 2;  -- Warning, which may not directly cause an error

  msg_info CONSTANT numeric DEFAULT 3;  -- Informational

  msg_dml CONSTANT numeric DEFAULT 4;  -- Insert/Update/Delete/Truncate information

  msg_ddl CONSTANT numeric DEFAULT 5;  -- Create/Alter/Drop/Truncate information

  msg_debug CONSTANT numeric DEFAULT 10; -- Debug information, such as what Debug Point has been reached at various times.

  msg_code CONSTANT numeric DEFAULT 90; -- This message is meant for code generation

  msg_none CONSTANT numeric DEFAULT 101; -- Do not show this message in DBMS_OUTPUT

  

    -- Verbose Types

      -- These Constants should be sent to your PL/SQL Objects to describe the level of messages which should be displayed.

  show_none CONSTANT numeric DEFAULT 0;   -- Use this when your script will not be run by a human looking at the results, 

                                        --  such as procedures called from the overnight.

  show_errors CONSTANT numeric DEFAULT 1;   -- Only display errors

  show_warnings CONSTANT numeric DEFAULT 2;   -- Show Errors and Warnings

  show_info CONSTANT numeric DEFAULT 3;   -- Show Errors, Warnings and Informational messages

  show_dml CONSTANT numeric DEFAULT 4;   -- Show '' and Insert/Update/Delete information (May also show Truncate, 

                                        -- which is DDL but may cause confusion if not shown with DML info)

  show_ddl CONSTANT numeric DEFAULT 5;   -- Show '' and Create/Alter/Drop/Truncate information

  show_debug CONSTANT numeric DEFAULT 10;  -- Show '' and Debug information

  show_code_gen CONSTANT numeric DEFAULT 90;  -- Show ONLY Code Generation messages

  show_all CONSTANT numeric DEFAULT 100; -- Show every message regardless of type.

  

    -- Audit History Types

      -- These Constants relate to audithis."HistoryType"

  audit_unknown CONSTANT numeric DEFAULT 0;

  audit_add CONSTANT numeric DEFAULT 1;

  audit_insert CONSTANT numeric DEFAULT 1;

  audit_edit CONSTANT numeric DEFAULT 2;

  audit_update CONSTANT numeric DEFAULT 2;

  audit_delete CONSTANT numeric DEFAULT 4;

  audit_rebill CONSTANT numeric DEFAULT 5;

  audit_merge CONSTANT numeric DEFAULT 6;

  audit_converted CONSTANT numeric DEFAULT 7;

  audit_asat CONSTANT numeric DEFAULT 8;

  

    -- Verification Levels

      -- These Constants should be sent to your PL/SQL Objects to describe the level of data integrity checks 

      --  which should be made.

      -- More Verification equals safer code, but also slower code. 

      -- Sometimes it makes sense to move the data verification to the driver script and avoid it in the PL/SQL Object.

      -- You do not have to support all levels in your PL/SQL objects, use these values only as they make sense to do so.

  verify_none CONSTANT numeric DEFAULT 0;  -- Do not do any data verification checks, 

                                         -- and assume this was done by the calling code.

  verify_errors CONSTANT numeric DEFAULT 5;  -- Only do data verification checks where invalid data would be serious, 

                                         -- such as causing an error or making the AR appear incorrect

  verify_all CONSTANT numeric DEFAULT 10; -- Do as many data verification checks as possible

    

    -- dbmsoutput_P Settings

  dbms_hide_source CONSTANT numeric DEFAULT 0; -- Only display the exact message sent

  dbms_show_source CONSTANT numeric DEFAULT 1; -- Include the script name before the message

  dbms_show_line CONSTANT numeric DEFAULT 2; -- Include the script name . the line number before the message

  dbms_show_step CONSTANT numeric DEFAULT 3; -- Include the script name ^ pParams."Step" before the message

  

    -- ax_setting Setting Types

  setting_system CONSTANT numeric DEFAULT 0;  -- ax_setting."Value" is a property that should not be edited (Read Only)

  setting_boolean CONSTANT numeric DEFAULT 1;  -- ax_setting."Value" is a 1 or 0 value (Yes / No)

  setting_number CONSTANT numeric DEFAULT 2;  -- ax_setting."Value" is a number 

  setting_string CONSTANT numeric DEFAULT 3;  -- ax_setting."Value" is a small Char -or- Varchar2 (0-255 characters)

  setting_text CONSTANT numeric DEFAULT 4;  -- ax_setting."Value" is a Long Text Value (256-4000 characters)

  setting_list CONSTANT numeric DEFAULT 5;  -- ax_setting."Value" should come from a pre-defined list (dropdown)

    

  -- Answer Types  

    -- These Constants relate to fitem."AnsType"

  answer_yes_no CONSTANT numeric DEFAULT 0;

  answer_text CONSTANT numeric DEFAULT 1;

  answer_number CONSTANT numeric DEFAULT 2;

  answer_list CONSTANT numeric DEFAULT 3;

  answer_date CONSTANT numeric DEFAULT 4;

  answer_long_text CONSTANT numeric DEFAULT 5;

  answer_image CONSTANT numeric DEFAULT 6;

  answer_calculated CONSTANT numeric DEFAULT 7;

  answer_attachment CONSTANT numeric DEFAULT 8;

  answer_spreadsheet CONSTANT numeric DEFAULT 9;    

  

  -- Date/Time Formats  

  date_format CONSTANT character varying(50) DEFAULT 'mm/dd/yyyy'; -- Normal Date Format with no Time Element

  descriptive_date_format CONSTANT character varying(50) DEFAULT 'FMMonth ddth, YYYY'; -- Descritive Date Format, with Month spelled out

  ordered_date_format CONSTANT character varying(50) DEFAULT 'yyyy/mm/dd'; -- Date Format for situations where the string will be ordered by

  date_time_format CONSTANT character varying(50) DEFAULT 'dd/mm/yyyy HH:MI AM'; -- Date Format with a Time Element

  time_format CONSTANT character varying(50) DEFAULT 'HH:MI AM'; -- Time Format

  date_time_24h_format CONSTANT character varying(50) DEFAULT 'dd/mm/yyyy HH24:MI'; -- Date Format with a 24 hour Time Element

  time_24h_format CONSTANT character varying(50) DEFAULT 'HH24:MI';  -- 24 hour Time Elemant

  ordered_date_time_format CONSTANT character varying(50) DEFAULT 'yyyy/mm/dd HH24:MI'; -- Date and Time format where the string will be ordered by

  

  -- History Types

  history_unknown CONSTANT numeric DEFAULT 0;

  history_add CONSTANT numeric DEFAULT 1;

  history_edit CONSTANT numeric DEFAULT 2;

  history_allocation CONSTANT numeric DEFAULT 3;

  history_delete CONSTANT numeric DEFAULT 4;

  history_rebill CONSTANT numeric DEFAULT 5;

    

  -- Standard collection of Common Parameters for most AXSO procedures/functions

  TYPE tparams IS RECORD ("User" numeric, "StationId" numeric, "Step" numeric DEFAULT 0, "VerboseType" numeric DEFAULT ax_pkg.show_warnings, "VerifyLevel" numeric DEFAULT ax_pkg.verify_all, "ShowSource" numeric DEFAULT ax_pkg.dbms_hide_source, "IsInit" boolean DEFAULT false);

  

  -- Global Variables

    -- Parameter List, with defaults, for most AXSO procedures/functions

  ax_params ax_pkg.tparams; -- Do not alter, treat as a constant

     

  -- Master Help function   

  FUNCTION help_f(ppackagename character varying, pobjectname character varying DEFAULT NULL::character varying, pparams tparams DEFAULT ax_pkg.ax_params) RETURN clob;    

  

  -- public help for this package   

  PROCEDURE help(IN pobjectname character varying DEFAULT NULL::character varying);    

         

  -- Add a new setting to the ax_setting table

  PROCEDURE addsetting_p(INOUT pvsettingrec ax_setting, IN poverridevalues boolean DEFAULT false, IN pparams tparams DEFAULT ax_pkg.ax_params);     

  

  -- Append String, adding leading spaces if needed 

  PROCEDURE appendstring_p(INOUT pvbasestring character varying, IN pnewstring character varying, IN pdelimiter character varying DEFAULT ' '::character varying, IN pmessagetype numeric DEFAULT ax_pkg.msg_info, IN pparams tparams DEFAULT ax_pkg.ax_params);  



  -- Append String, adding leading spaces if needed 

   -- depreciated version

  PROCEDURE appendstring_p(INOUT pvbasestring character varying, IN pnewstring character varying, IN pleadingdelimiter boolean, IN pdelimiter character varying, IN pmessagetype numeric, IN pparams tparams);  

  

  -- Returns a null if pString cannot be converted

  FUNCTION converttodate_f(pstring character varying, pdefault timestamp without time zone DEFAULT NULL::timestamp without time zone, pformat character varying DEFAULT NULL::character varying) RETURN timestamp without time zone;

  

  -- Returns a 0 if pString cannot be converted

  FUNCTION converttonumber_f(pstring character varying, pdefault numeric DEFAULT 0) RETURN numeric;

  

  -- Create a AuditHis record

   -- always gets the next sequence

  PROCEDURE createaudithis_p(INOUT pvaudithisrow audithis, IN pparams tparams DEFAULT ax_pkg.ax_params);    

  

  -- This function accepts a string value, then returns the same value cropped down to the length of the provided string field.  

  FUNCTION croptofieldsize_f(pstring character varying, ptable character varying, pfield character varying, pparams tparams DEFAULT ax_pkg.ax_params) RETURN character varying;  

  

  -- This function returns a true or false based on if pInstance is the current database instance

  FUNCTION databaseinstancematch_f(pinstance character varying, piscasesensative boolean DEFAULT true) RETURN boolean;

  

  -- This procedure writes to the dbms output

    --  but only if the Verbose Type is greater than or equal to the Message Type

  PROCEDURE dbmsoutput_p(IN pmessagetype integer, IN pmessage character varying, IN pparams tparams DEFAULT ax_pkg.ax_params);  

  

  -- Overloaded procedure for numeric message type

  PROCEDURE dbmsoutput_p(IN pmessagetype numeric, IN pmessage character varying, IN pparams tparams DEFAULT ax_pkg.ax_params);  

  

  -- Translate fitem."AnsType" into a string

  FUNCTION getanswertype_f(panstype numeric) RETURN character varying;        

  

  -- Translate audithis."HistoryType" into a string

  FUNCTION getaudithistype_f(phistorytype numeric) RETURN character varying;    

   

  -- This function returns a partial list of columns for a table, formatted for use in a dynamic SQL statement.

  FUNCTION getcols_f(ptable character varying, pstartcol numeric DEFAULT 1, pendcol numeric DEFAULT 0, pexcludelist character varying DEFAULT NULL::character varying, palias character varying DEFAULT NULL::character varying) RETURN character varying;  

  

  -- Creates an audithis record and returns the Audit value, if pMapAudit is null.

  FUNCTION getmapaudit_f(pmapaudit numeric DEFAULT NULL::numeric, pparams tparams DEFAULT ax_pkg.ax_params) RETURN numeric;  

  

  -- Get a setting value from the ax_setting table

  FUNCTION getsetting_f(pkey character varying, pparams tparams DEFAULT ax_pkg.ax_params) RETURN character varying;

  

  -- Get a setting value from the ax_setting table

  -- Overload 

  FUNCTION getsetting_f(INOUT pvsettingrow ax_setting, poverridevalue character varying DEFAULT NULL::character varying, pparams tparams DEFAULT ax_pkg.ax_params) RETURN character varying;   

  

  -- Get the value of a Station Option, based on the Station and the Station Option ID

    -- Note that the function always returns a varchar2, even if the value type is Number, so convert to number accordingly

  FUNCTION getstationoption_f(pstationid numeric, pinidef numeric) RETURN character varying;

  

  -- Overload

    -- Allows you to check a station option by name instead of ID

  FUNCTION getstationoption_f(pstationid numeric, pmodule character varying, psection character varying, pkey character varying) RETURN character varying;  



-- This procedure gets the overnight user. 

  FUNCTION getovernightuser_f() RETURN numeric;

  

  -- This procedure populates the User and StationId for pvParams

    -- As long as those values are set to null

  PROCEDURE getstationuser_p(INOUT pvparams tparams);  



  -- Initialize a AuditHis record

  PROCEDURE initializeaudithis_p(INOUT pvaudithisrow audithis, IN pparams tparams DEFAULT ax_pkg.ax_params); 



  -- This procedure initializes an ax_log record

    -- GetStationUser_P is called for User and StationId values

  PROCEDURE initializelog_p(INOUT pvlogrow ax_log, IN pparams tparams DEFAULT ax_pkg.ax_params);



  -- This procedure sets any null tParams to current or default values

    -- GetStationUser_P is used for User and StationId values

  PROCEDURE initializeparams_p(INOUT pvparams tparams, IN pinitparams tparams DEFAULT NULL::tparams);

  

  -- Set default values for an ax_setting record

  PROCEDURE initializesetting_p(INOUT pvsettingrow ax_setting, IN pparams tparams DEFAULT ax_pkg.ax_params);   

  

  -- Insert a AuditHis record

  PROCEDURE insertaudithis_p(INOUT pvaudithisrow audithis, IN pparams tparams DEFAULT ax_pkg.ax_params);     

  

  -- Log a Custom Script Message into the ax_log table

  PROCEDURE log_p(INOUT pvlogrow ax_log, IN pmessagetype integer DEFAULT ax_pkg.msg_debug, IN pparams tparams DEFAULT ax_pkg.ax_params);  



  -- Overloaded procedure for numeric message type

  PROCEDURE log_p(INOUT pvlogrow ax_log, IN pmessagetype numeric, IN pparams tparams DEFAULT ax_pkg.ax_params);  

  

  -- Log a Custom Script Error 

    -- currently goes to ax_log table

    -- may eventually end up in eventlog if current limitations are accounted for

  PROCEDURE logevent_p(IN pobjectname character varying, IN pinfotext character varying, IN pparams tparams DEFAULT ax_pkg.ax_params, IN peventtype character varying DEFAULT 'CUSTOM SCRIPT FAILED'::character varying, IN pmessagetype integer DEFAULT ax_pkg.msg_debug);  

  

  -- Remove Label

    -- This function removes sub strings from a string, based on open/close delimiters

  FUNCTION removelabels_f(pstring character varying, popendelimiter character varying DEFAULT '('::character varying, pclosedelimiter character varying DEFAULT ')'::character varying) RETURN character varying;  

  

  -- Make a string safe for other formats

  PROCEDURE safestring_p(INOUT pvstring character varying, IN poutputtype character varying DEFAULT 'sql'::character varying);  

  

  -- This function returns the max length of a field type based on Table and Field names.

  FUNCTION typelength_f(ptable character varying, pfield character varying) RETURN numeric;  



  -- Compare two strings, taking Null values into account

  FUNCTION valuesequal_f(pstring1 character varying, pstring2 character varying) RETURN boolean;  

     

  -- This function returns if the provided version matches the axiUm version

  FUNCTION versionmatch_f(pversion numeric) RETURN boolean;     

       

  -- Report on the versions of products installed in the database

  FUNCTION versionreport_f(pdetailed numeric DEFAULT 0, pparams tparams DEFAULT ax_pkg.ax_params) RETURN character varying;

  

END;
-- The rest of the packages 
CREATE OR REPLACE PACKAGE alloc_pkg IS



  PROCEDURE createalloctxs_p(INOUT prefcursor cursor_pkg.weakcursor, IN pdepartment character, IN pfromdate timestamp without time zone, IN ptodate timestamp without time zone, IN pgroupby1 integer DEFAULT 0, IN pgroupby2 integer DEFAULT 0, IN pisdetailed integer DEFAULT 1, IN ppatient numeric DEFAULT 0, IN porigrecno numeric DEFAULT 0);

                              

  PROCEDURE returnbatchid_p(INOUT prefcursor cursor_pkg.weakcursor, IN pbatch numeric);

  

END;
CREATE OR REPLACE PACKAGE ar_dept_pkg IS



/* Original (before AX-30762)

  function ar_get_dept_f (pDepartment char,

                          pHistory number,

                          pProducer char,

                          pPatient number) return char;

*/



  -- AX-30762

  FUNCTION ar_get_dept_f(pdepartment character, phistory numeric, pproducer character, ppatient numeric) RETURN character;

                          

  FUNCTION ar_get_group_by_desc_f(pgroupby numeric) RETURN character;

                                  

  PROCEDURE ar_create_dept_txs_changes_p(IN porigrecno numeric, IN pfamily numeric, IN phistory numeric, IN pperiod character, IN pchangecolumn1 character varying, IN pgroupcolumn1 character varying, IN pchangecolumn2 character varying, IN pgroupcolumn2 character varying);



  FUNCTION ar_create_dept_txs_f(pdepartment character, pfromdate timestamp without time zone, ptodate timestamp without time zone, pgroupby1 numeric, pgroupby2 numeric, pisdetailed numeric, pincludeunallocated numeric, ppatient numeric DEFAULT 0, porigrecno numeric DEFAULT 0, precalculate integer DEFAULT 0, pexpirydate timestamp without time zone DEFAULT trunc(sysdate), pupdateexpirydateifnotnewdata integer DEFAULT 0) RETURN numeric;   



  PROCEDURE ar_create_dept_txs_p(OUT pbatchid numeric, OUT pisnewbatchid numeric, IN pdepartment character, IN pfromdate timestamp without time zone, IN ptodate timestamp without time zone, IN pgroupby1 numeric, IN pgroupby2 numeric, IN pisdetailed numeric, IN pincludeunallocated numeric, IN ppatient numeric DEFAULT 0, IN porigrecno numeric DEFAULT 0, IN precalculate integer DEFAULT 0, IN pexpirydate timestamp without time zone DEFAULT trunc(sysdate), IN pupdateexpirydateifnotnewdata integer DEFAULT 0);

                                 

  FUNCTION ar_get_group_by_column_name_f(pgroupby numeric, pisorigcolumnname numeric) RETURN character varying;

                                          

  FUNCTION ar_get_dept_asat_f(pdepartment character, pasatdate timestamp without time zone, ppatient numeric DEFAULT 0, porigrecno numeric DEFAULT 0, precalculate integer DEFAULT 0) RETURN numeric;

                               

  PROCEDURE ar_create_unallocated_txs_p(IN pfromdate timestamp without time zone, IN ptodate timestamp without time zone, IN pgroupby1 numeric, IN preportgroupby1description character, IN pgroupby2 numeric, IN preportgroupby2description character, IN pisdetailed numeric, IN pincludeunallocated numeric, IN ppatient numeric, IN porigrecno numeric);



END;
CREATE OR REPLACE PACKAGE arasat_pkg IS
  TYPE arasat_record IS RECORD (openar numeric, endar numeric);
  TYPE arasat_type IS REF CURSOR RETURN arasat_record;
  FUNCTION arasat(asatdate timestamp without time zone) RETURN numeric;
  FUNCTION arasat_i(asatdate timestamp without time zone) RETURN numeric;
END;
CREATE OR REPLACE PACKAGE archive_pkg IS
	-- AX-24111
	v_ndisabletriggersflag numeric DEFAULT 0;

	-- AX-24111
	PROCEDURE setdisabletriggers(IN ndisableflag numeric);

	-- AX-24111
	FUNCTION getdisabletriggersflag() RETURN numeric;
	
	-- this function is used to clone the last pathis entry and add a new one with the given parameters
	-- usage is limited to the archive and restore process as the appropriate trigger has been disabled
	PROCEDURE makepathisentry(IN npatientid numeric, IN nauditid numeric, IN cstatus character varying);

END;
CREATE OR REPLACE PACKAGE auditlog_pkg IS

	c_nactionadd CONSTANT numeric DEFAULT 0;

	c_nactionedit CONSTANT numeric DEFAULT 1;

	c_nactiondelete CONSTANT numeric DEFAULT 2;

	c_nactionview CONSTANT numeric DEFAULT 3;

	c_nactionprint CONSTANT numeric DEFAULT 4;

	c_nactioncopy CONSTANT numeric DEFAULT 5;

	c_nactionpreview CONSTANT numeric DEFAULT 6;

	c_nactionstrikeout CONSTANT numeric DEFAULT 7;



	v_nsecurelog numeric DEFAULT 0;

	v_nuserid numeric DEFAULT 0;

	v_nstationid numeric DEFAULT 0;

	v_csecretkey character varying(256) DEFAULT ' ';

	v_capplication character varying(256) DEFAULT ' '; --E143149.js5

	v_nsessioninit numeric DEFAULT 0;			-- B142694 (E141297.drb20)

	

	PROCEDURE setlogparameters(IN nsecurelog numeric, IN nuserid numeric, IN nstationid numeric, IN csecretkey character varying, IN capplication character varying, OUT nsessioninit numeric);



	--E143149.jsx (to be taken out eventually!!!)

	PROCEDURE setlogparameters(IN nsecurelog numeric, IN nuserid numeric, IN nstationid numeric, IN csecretkey character varying, OUT nsessioninit numeric);

	

	FUNCTION getsecurelog() RETURN numeric;

	

	FUNCTION getuserid() RETURN numeric;

	

	FUNCTION getstationid() RETURN numeric;

	

	FUNCTION getsecretkey() RETURN character varying;

	

	--E143149.js5

	FUNCTION getapplicationstring() RETURN character varying;

	

	FUNCTION gethashvalue(npatientid numeric, ddate timestamp without time zone, nuser numeric, nstation numeric, nactiontype numeric, ctablename character varying, cprimaryinfo character varying, cadditionalinfo character varying, csecretkey character varying) RETURN character varying;

	

	PROCEDURE insertauditlog(IN npatientid numeric, IN nactiontype numeric, IN ctablename character varying, IN cprimaryinfo character varying, IN cadditionalinfo character varying);



	--E135970.16 added

	FUNCTION getappointdescription(nappttype numeric) RETURN character varying;



	--E135970.16 added

	FUNCTION getappointadditionalinfo(szcode character varying, szreason character varying, nappttype numeric, ddate timestamp without time zone, nfrom numeric) RETURN character varying;

	

	--E135970.17 added

	FUNCTION gettrxdescription(ntrxtype numeric, ntrxid numeric, sztrxstatus character varying, nplantotal numeric) RETURN character varying;



	--E135970.19 added

	FUNCTION gettreatme2description(nstatus numeric) RETURN character varying;



	--E135970.19 added

	FUNCTION gettreatme2additionalinfo(nstatus numeric, ncodeid numeric, ndays numeric, nsite numeric, nsite2 numeric, nsurfaces numeric) RETURN character varying;



	--E135970.19 added

	FUNCTION getnotes2description(ntype numeric, nsection numeric) RETURN character varying;



	--E135970.20 added

	FUNCTION getpformdescription(nownertype numeric) RETURN character varying;

	

	-- E135970.22

	FUNCTION getapnotedescription(napnotetype numeric) RETURN character varying;

	

	-- E135970.22

	FUNCTION getapnotepatid(napnotetype numeric, napnotetreatment numeric, napnotepatid numeric, napnoteappid numeric) RETURN numeric;

	

	-- E135970.22

	FUNCTION getpthistdescription(ntype numeric, nrecid numeric) RETURN character varying;

	

	-- E135970.22

	FUNCTION getpthistinfo(ntype numeric, nrecid numeric) RETURN character varying;

	

	-- E136724

	FUNCTION getiuserpatid(niuserid numeric) RETURN numeric;

	

	-- E136724

	FUNCTION getiuserinfo(niuserid numeric) RETURN character varying;

	

	-- B142339

	FUNCTION getindicatordescription(nindicatid numeric) RETURN character varying;

	

		-- B142339

	FUNCTION getindlogstate(nstate numeric) RETURN character varying;

	

		-- B142339

	FUNCTION getindlogseverity(nseverity numeric) RETURN character varying;

	

	-- E142678

	FUNCTION getptlinfotype(ntype numeric) RETURN character varying;

	

	-- AX-14733.16052

	FUNCTION getosvitmonaudituser(nptvital numeric, naudit numeric) RETURN character varying;

	

	-- AX-18069.19112 

	FUNCTION ishashvalid(npatientid numeric, crowid character varying, csecretkey character varying) RETURN numeric;

END;
CREATE OR REPLACE PACKAGE ax_appoint_pkg IS 

/******************************************************************************

* AXSO - ax_appoint_pkg

* 

* Functions and Procedures for dealing with Appointment Records 

*******************************************************************************/

/*

  -- Requirements

    ax_pkg

*/

 -- Package Version

  --   Increment whenever you make changes.

  --   For New Items increment the number to the left of the decimal, and set the number on the right to 00

  --   For Changes increment the number to the right of the decimal

  version CONSTANT numeric DEFAULT 1.00; 

  -- Version of axiUm this package is made to be compatible with.

  --   Only include Major Releases, as Patch Releases should not impact compatibility

  axium_version CONSTANT numeric DEFAULT 0.00; -- dev! 



  -- Jul 05, 2018 nlm created package

  -- AX-26266  Jan 19, 22  j.s   added new functions responsible for cancelling and confimring appointments

  -- AX-26400  Feb 01, 22  j.s   changed to allow non string padded code



  -- public help for this package   

  PROCEDURE help(IN pobjectname character varying DEFAULT NULL::character varying);  

  

  -- initializes a blank appoint row with default values

  PROCEDURE initializeappoint_p(INOUT pvappointrow appoint, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);



  -- AX-26266 added

  FUNCTION isvalidappoint_p(papptid numeric) RETURN boolean;

  FUNCTION isvaliduser_p(puserid numeric) RETURN boolean;

  FUNCTION isvalidcancelcode_p(pcancelcode character varying) RETURN boolean;

  FUNCTION isvalidstatuscode_p(pstatuscode character varying) RETURN boolean;



  FUNCTION cancelappoint_p(papptid numeric, puserid numeric, pcancelcode character varying, prclstatusunsch character varying DEFAULT NULL::character varying) RETURN boolean;

  FUNCTION confirmappoint_p(papptid numeric, puserid numeric) RETURN boolean;



END;
CREATE OR REPLACE PACKAGE ax_assign_pkg IS

/******************************************************************************

* AXSO - ax_assign_pkg

* 

* Functions dealing with Patient Assignments and Need Requests

*

*******************************************************************************/

  -- Increment whenever you make changes. 

  --   For New Items increment the number to the left of the decimal, and set the number on the right to 00

  --   For changes increment the number to the right of the decimal

  version CONSTANT numeric DEFAULT 6.01;

  

  -- This should match the version of axiUm this package was created for.

  axium_version CONSTANT numeric DEFAULT 0.00; 



  -- public help for this package   

  PROCEDURE help(IN pobjectname character varying DEFAULT NULL::character varying); 



  -- Initialize a PtProd record 

  PROCEDURE initializeptprod_p(INOUT pvptprodrow ptprod, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params); 

  

  -- Initialize a PtManage record 

  PROCEDURE initializeptmanage_p(INOUT pvptmanagerow ptmanage, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params); 

  

   -- Initialize a PtFacul record 

  PROCEDURE initializeptfacul_p(INOUT pvptfaculrow ptfacul, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params); 

 

  -- Insert a PtProd record

  PROCEDURE insertptprod_p(INOUT pvptprodrow ptprod, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN poverride boolean DEFAULT true);

  

  -- Insert a PtManage record

  PROCEDURE insertptmanage_p(INOUT pvptmanagerow ptmanage, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN poverride boolean DEFAULT true);

  

   -- Insert a PtFacul record

  PROCEDURE insertptfacul_p(INOUT pvptfaculrow ptfacul, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN poverride boolean DEFAULT true);

  

  -- Assign a patient to one or more providers

  PROCEDURE ptprodassign_p(IN ppatient numeric, IN pproducers character varying, IN pareprimary character varying DEFAULT '0'::character varying, IN pstartdate timestamp without time zone DEFAULT sysdate, IN penddate timestamp without time zone DEFAULT NULL::timestamp without time zone, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN poverride boolean DEFAULT true);

  

   -- Assign a patient to one or more managers

  PROCEDURE ptmanageassign_p(IN ppatient numeric, IN pusers character varying, IN pareprimary character varying DEFAULT '0'::character varying, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN poverride boolean DEFAULT true);

  

   -- Assign a patient to one or more faculty members

  PROCEDURE ptfaculassign_p(IN ppatient numeric, IN pusers character varying, IN pareprimary character varying DEFAULT '0'::character varying, IN pdiscipline character DEFAULT ' '::bpchar, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN poverride boolean DEFAULT true);

     

  -- Set default values for a NeedReq record  

  PROCEDURE initializeneedreq_p(INOUT pvneedreqrow needreq, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

   

  -- Insert a new NeedReq

  --  It is recommended to Initialize your NeedReq record first

  PROCEDURE insertneedreq_p(INOUT pvneedreqrow needreq, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

  

  -- Copy provider need req from one provider to another

  PROCEDURE copyproviderneedreq_p(IN psourceprovider character, IN pdestprovider character, IN pdate timestamp without time zone DEFAULT sysdate, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

   

  -- Insert a new NeedReq based on a PItem Record

  --  Procedure assumes that PItem is tied to a User form

  PROCEDURE addneedfrompitem_p(IN ppitemrow pitem, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

  

  -- Transfer a group of patients from one Faculty to another

  PROCEDURE transferptfacul_p(IN pfromuser numeric, IN ptousers character varying, IN pmove boolean DEFAULT true, IN pareprimary character varying DEFAULT '0'::character varying, IN pdiscipline character DEFAULT ' '::bpchar, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN poverride boolean DEFAULT true);  

  

  -- Transfer a group of patients from one Manager to another

  PROCEDURE transferptmanage_p(IN pfromuser numeric, IN ptousers character varying, IN pmove boolean DEFAULT true, IN pareprimary character varying DEFAULT '0'::character varying, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN poverride boolean DEFAULT true);

  

  -- Transfer a group of patients from one Provider to another

  PROCEDURE transferptprod_p(IN pfromprovider character, IN ptoproviders character varying, IN pmove boolean DEFAULT true, IN pareprimary character varying DEFAULT '0'::character varying, IN pstartdate timestamp without time zone DEFAULT sysdate, IN penddate timestamp without time zone DEFAULT NULL::timestamp without time zone, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN poverride boolean DEFAULT true);  

  

END;
CREATE OR REPLACE PACKAGE ax_copy_pkg IS 

/******************************************************************************

* AXSO - ax_copy_pkg

* 

* Functions dealing with copying axiUm patient records

*

*******************************************************************************/



  -- Increment whenever you make changes. 

  --   For New Items increment the number to the left of the decimal, and set the number on the right to 00

  --   For changes increment the number to the right of the decimal

  version CONSTANT numeric DEFAULT 4.12;

  -- Version of axiUm this package is made to be compatible with.

  --   Only include Major Releases, as Patch Releases should not impact compatibility

  axium_version CONSTANT numeric DEFAULT 0.00;

  

/*

-- Requirements

  ax_pkg

  ax_assign_pkg

  ax_patient_pkg

    

  -- Required Table   

  create table AX_MAP (

    "Audit" number(10),

    "TableName" varchar(30),

    "SourceId" number(10),

    "TargetId" number(10),

    "SourceCode" VARCHAR2(50),

    "TargetCode" VARCHAR2(50)



  );

  create unique index "AX_MAP_SOURCEID" on ax_map ("Audit","SourceId", "SourceCode","TableName");



*/

   

  -- P189-155143 Jun 24, 2015 blc Updated for version 6.01, 6.02, and 6.03 database changes. Added copying of FAMLIMIT, PTRCGRP, and PTRCGRPI tables

  -- P189-156750 Sep 21, 2015 blc Removed copying of obsolete Tx Plan tables dropped on version 5.20

  -- SF-00134678 Sep 20, 2016 blc Changed CopyPatientRecords_P to clear second id field and trusted audit fields if scrambling patient data

  -- SF-00148848 Mar 16, 2017 blc Changed CopyTreatmentRecords_P to zero out amount related fields on In process and Completed treatment

  -- SF-00152633 May 03, 2017 blc Fixed problem with diagnoses not showing up for the treatment in Tx Plan module and added copying of diagnoses for planned treatment

  -- SF-00186337 Jul 06, 2018 nlm Fixed problem with fetching multiple records for tx notes when copying txs and notes

  -- SF-00257739 Nov 05, 2020 blc Fixed problem with spreadsheet answers not being copied

  -- SF-00241331 Jun 15, 2021 blc Changed CopyPatientRecords_P to set new (7.06) HasExternalLink field to 0 since EXTERNAL_LINK records are not being copied

  -- AX-35969    Sep 23, 2024 grt Changed CopyPatientRecords_P to handle the new HasCarequality field.

  

  -- Standard collection of Copy Parameters for ax_copy_pkg procedures/functions

  TYPE tcopyparams IS RECORD ("LoopAudit" numeric DEFAULT 0, "TargetChart" character(10) DEFAULT '%'::bpchar, "First" character(30) DEFAULT '%'::bpchar, "Middle" character(15) DEFAULT '%'::bpchar, "Last" character(25) DEFAULT '%'::bpchar, "Providers" character varying(4000) DEFAULT NULL::character varying, "ArePrimary" character varying(4000) DEFAULT '1'::character varying, "ProdStartDate" timestamp without time zone, "ProdEndDate" timestamp without time zone, "CopyFirstProviderDemographics" boolean DEFAULT false, "Email" character varying(100) DEFAULT NULL::character varying, "Address1" character(30) DEFAULT NULL::bpchar, "Address2" character(30) DEFAULT NULL::bpchar, "City" character(24) DEFAULT NULL::bpchar, "Province" character(6) DEFAULT NULL::bpchar, "Postal" character(15) DEFAULT NULL::bpchar, "HomeArea" character(4) DEFAULT NULL::bpchar, "HomePhone" character(8) DEFAULT NULL::bpchar, "HomeExt" character varying(6) DEFAULT NULL::character varying, "Birth" timestamp without time zone, "Sex" numeric(5,0) DEFAULT NULL::numeric, "AltChart" character(15) DEFAULT NULL::bpchar, "CustomCode1" character(6) DEFAULT NULL::bpchar, "CustomCode2" character(6) DEFAULT NULL::bpchar, "CustomCode3" character(6) DEFAULT NULL::bpchar, "CustomCode4" character(6) DEFAULT NULL::bpchar, "CustomCode5" character(6) DEFAULT NULL::bpchar, "CustomCode6" character(6) DEFAULT NULL::bpchar, "CustomCode7" character(6) DEFAULT NULL::bpchar, "CustomCode8" character(6) DEFAULT NULL::bpchar, "CustomCode9" character(6) DEFAULT NULL::bpchar, "CustomCode10" character(6) DEFAULT NULL::bpchar, "StatusCode" character varying(4000) DEFAULT NULL::character varying, "Scramble" character varying(4000) DEFAULT NULL::character varying, "CopyGeneralNotes" character varying(4000) DEFAULT NULL::character varying, "CopyTreatmentPlanning" character varying(4000) DEFAULT NULL::character varying, "CopyStickyNotes" character varying(4000) DEFAULT NULL::character varying, "CopyAttachments" character varying(4000) DEFAULT NULL::character varying, "CopyEPRForms" character varying(4000) DEFAULT NULL::character varying, "CopyInsurance" character varying(4000) DEFAULT NULL::character varying, "CopyContactNotes" character varying(4000) DEFAULT NULL::character varying, "CopyEmergencyContact" character varying(4000) DEFAULT NULL::character varying, "CopyPerio" character varying(4000) DEFAULT NULL::character varying, "CopyTreatments" character varying(4000) DEFAULT NULL::character varying);

  

  -- Global Variables

    -- Parameter List, with defaults, for most AXSO procedures/functions

  ax_copy_params ax_copy_pkg.tcopyparams; -- Do not alter, treat as a constant

   

  -- public help for this package   

  PROCEDURE help(IN pobjectname character varying DEFAULT NULL::character varying);

   

  -- Copy over basic Patient information

  PROCEDURE copypatientrecords_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN psourcepatient numeric, INOUT pvtargetpatient numeric, INOUT pvmapaudit numeric, IN pcopyparams tcopyparams DEFAULT ax_copy_pkg.ax_copy_params, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);



  -- Copy Treatments

  PROCEDURE copytreatmentrecords_p(IN psourcepatient numeric, IN ptargetpatient numeric, INOUT pvmapaudit numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN pcopyinsurance character varying DEFAULT '0'::character varying);

  

  -- Copy Perio

  PROCEDURE copyperiorecords_p(IN psourcepatient numeric, IN ptargetpatient numeric, INOUT pvmapaudit numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN pcopyinsurance character varying DEFAULT '0'::character varying);

  

  -- Copy General Notes

    -- If you wish to copy notes tied to other records, make sure to copy those records FIRST

  PROCEDURE copynotes2records_p(IN psourcepatient numeric, IN ptargetpatient numeric, INOUT pvmapaudit numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

  

  -- Copy Contact Notes

  PROCEDURE copycontactnoterecords_p(IN psourcepatient numeric, IN ptargetpatient numeric, INOUT pvmapaudit numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);



  -- Copy Treatment Planning

  PROCEDURE copytreatmentplanningrecords_p(IN psourcepatient numeric, IN ptargetpatient numeric, INOUT pvmapaudit numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

  

  -- Copy Sticky Notes

  PROCEDURE copystickynoterecords_p(IN psourcepatient numeric, IN ptargetpatient numeric, INOUT pvmapaudit numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

  

  -- Copy Attachments

    -- Note that this procedure must be called BEFORE any other procedure which may copy section specific attachments

    -- If called out of order, you may be missing attachments or links to attachments

  PROCEDURE copyattachmentrecords_p(IN psourcepatient numeric, IN ptargetpatient numeric, INOUT pvmapaudit numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);



  -- Copy EPR Forms

  PROCEDURE copyeprformrecords_p(IN psourcepatient numeric, IN ptargetpatient numeric, INOUT pvmapaudit numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

  

  -- Populate the Copy Params from the ax_setting table

  PROCEDURE getcopysettings_p(INOUT pvcopyparams tcopyparams, INOUT pvisproduction character varying, IN poverridevalues boolean DEFAULT false, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

  

  -- Copy a Patient Record

    -- to be depreciated  

  PROCEDURE copypatient_p(INOUT pvsuccess numeric, IN psourcepatient numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN ppatientloopaudit numeric DEFAULT 0, IN ptargetchart character DEFAULT '%'::bpchar, IN plast character DEFAULT '%'::bpchar, IN pfirst character DEFAULT '%'::bpchar, IN pmiddle character DEFAULT '%'::bpchar, IN pproducers character varying DEFAULT NULL::character varying, IN pareprimary character varying DEFAULT '1'::character varying, IN pprodassignstartdate timestamp without time zone DEFAULT NULL::timestamp without time zone, IN pprodassignenddate timestamp without time zone DEFAULT NULL::timestamp without time zone, IN pstatuscode character varying DEFAULT NULL::character varying, IN pscramble character varying DEFAULT NULL::character varying, IN pcopygeneralnotes character varying DEFAULT NULL::character varying, IN pcopytreatmentplanning character varying DEFAULT NULL::character varying, IN pcopystickynotes character varying DEFAULT NULL::character varying, IN pcopyattachments character varying DEFAULT NULL::character varying, IN pcopyeprforms character varying DEFAULT NULL::character varying, IN pcopyinsurance character varying DEFAULT NULL::character varying, IN pcopycontactnotes character varying DEFAULT NULL::character varying, IN pcopyemergencycontact character varying DEFAULT NULL::character varying);

  

  -- Copy a Patient Record

    -- standard call

  PROCEDURE copypatient_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN psourcepatient numeric, IN pcopyparams tcopyparams DEFAULT ax_copy_pkg.ax_copy_params, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

  

  -- Copy a Patient Record

    -- short override

  PROCEDURE copypatient_p(IN psourcepatient numeric, IN pcopyparams tcopyparams DEFAULT ax_copy_pkg.ax_copy_params, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

  

  PROCEDURE ax_clearax_map_p(IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

  

  -- Copy answers based on a set of mapping in the ax_map table

  PROCEDURE copymappedanswers_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN pmapaudit numeric, IN poverwriteexisting boolean DEFAULT false, IN pclearmapping boolean DEFAULT false, IN pfstatus character DEFAULT NULL::bpchar, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

  

-- overload

  PROCEDURE copymappedanswers_p(IN pmapaudit numeric, IN poverwriteexisting boolean DEFAULT false, IN pclearmapping boolean DEFAULT false, IN pfstatus character DEFAULT NULL::bpchar, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

  

  -- This procedure copies answers from one form to another

  -- This procedure differs from CopyEPRFormRecords_P in that it is copying from one Type of Form to Another

  -- Matching the FItem."Code" values

  PROCEDURE copyanswers_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN psourceform character, IN ptargetform character, IN poverwriteexisting boolean DEFAULT false, IN pfstatus character DEFAULT NULL::bpchar, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

  

  -- Overload

  PROCEDURE copyanswers_p(IN psourceform character, IN ptargetform character, IN poverwriteexisting boolean DEFAULT false, IN pfstatus character DEFAULT NULL::bpchar, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);  

 

END;
CREATE OR REPLACE PACKAGE ax_email_pkg IS 

/******************************************************************************

* AXSO - ax_email_pkg

* 

* Functions used for sending emails from axiUm, if the clients DBA has enabled UTL_SMTP.

*

*******************************************************************************/ 



  -- Increment whenever you make changes.

  --   For New Items increment the number to the left of the decimal, and set the number on the right to 00

  --   For changes increment the number to the right of the decimal

  version CONSTANT numeric DEFAULT 3.01;

  -- Version of axiUm this package is made to be compatible with.

  --   Only include Major Releases, as Patch Releases should not impact compatibility

  axium_version CONSTANT numeric DEFAULT 0.00; --DEV  

  

/*



  Requirements

  ----------------   

  ax_pkg

  ax_note_pkg

  

  ax_settings

  ----------------     


declare    

  vSettingRow ax_setting%rowtype;

begin

  vSettingRow."Key" := 'Email.Server';

  vSettingRow."Value" := '';

  vSettingRow."Description" := 'This is the local address of the email server.';

  ax_pkg.AddSetting_P(vSettingRow);

  vSettingRow."Key" := 'Email.DefaultSender';

  vSettingRow."Value" := '';

  vSettingRow."Description" := 'This is the sender email that should be used if no sender email is provided.';

  ax_pkg.AddSetting_P(vSettingRow);

  vSettingRow."Key" := 'Email.PatientNewMessageSubject';

  vSettingRow."Value" := 'New PatientAccess Message Recieved';

  vSettingRow."Description" := 'This is the subject of the email message that should be sent when a patient recieves an axiUm message.';

  ax_pkg.AddSetting_P(vSettingRow);

  vSettingRow."Key" := 'Email.PatientNewMessageText';

  vSettingRow."Value" := 'You have recieved a new message in PatientAccess. Login to PatientAccess to view the message.';

  vSettingRow."Description" := 'This is the Text email message that should be sent when a patient recieves an axiUm message.';

  ax_pkg.AddSetting_P(vSettingRow);

  vSettingRow."Key" := 'Email.PatientNewMessageHTML';

  vSettingRow."Value" := '';

  vSettingRow."Description" := 'This is the HTML email message that should be sent when a patient recieves an axiUm message.';

  ax_pkg.AddSetting_P(vSettingRow);

  vSettingRow."Key" := 'Email.PatientNewMessageContactNote';

  vSettingRow."Value" := '';

  vSettingRow."Description" := 'This is the NoteCode (notecode."NoteCode" where "Type" = 3) of the Contact Note copy, if you wish to record that the New Message email has been sent.';

  ax_pkg.AddSetting_P(vSettingRow);

end;

 

*/

  

  -- Standard collection of Email Parameters

  TYPE temailparams IS RECORD ("Sender" character(40) DEFAULT NULL::bpchar, "Recipient" character varying(4000) DEFAULT NULL::character varying, "Delimiter" character varying(5) DEFAULT ','::character varying, "Subject" character varying(4000) DEFAULT NULL::character varying, "TextMessage" character varying(32767) DEFAULT NULL::character varying, "HTMLMessage" character varying(32767) DEFAULT NULL::character varying, "CCRecipient" character varying(4000) DEFAULT NULL::character varying, "BCCRecipient" character varying(4000) DEFAULT NULL::character varying, "AttachBlob" bytea, "AttachClob" clob DEFAULT NULL::text, "AttachName" character varying(4000) DEFAULT NULL::character varying, "AttachMime" character varying(4000) DEFAULT NULL::character varying, "MailHost" character varying(255) DEFAULT NULL::character varying);

  

  -- Global Variables

    -- Parameter List, with defaults, for most AXSO procedures/functions

  ax_email_params ax_email_pkg.temailparams; -- Do not alter, treat as a constant  

  

  -- public help for this package   

  PROCEDURE help(IN pobjectname character varying DEFAULT NULL::character varying);    

  

  -- Master Email function

  PROCEDURE sendemail_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, INOUT pvemailparams temailparams, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

  

  -- Overload

  PROCEDURE sendemail_p(INOUT pvemailparams temailparams, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);  

 

  -- Send Email from User to User

  PROCEDURE senduseremail_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN psenderuser numeric, IN precipientuser numeric, INOUT pvemailparams temailparams, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

    

  -- Overload

  PROCEDURE senduseremail_p(IN psenderuser numeric, IN precipientuser numeric, INOUT pvemailparams temailparams, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);  

 

  -- Send Email from User to Patient

  PROCEDURE sendpatientemail_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN psenderuser numeric, IN precipientpatient numeric, INOUT pvemailparams temailparams, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);



  -- Send Email from User to Patient

    -- overload

  PROCEDURE sendpatientemail_p(IN psenderuser numeric, IN precipientpatient numeric, INOUT pvemailparams temailparams, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);  



  -- Sends an email from a user to a User Group

  PROCEDURE sendugroupemail_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN psenderuser numeric, IN precipientugroup character, INOUT pvemailparams temailparams, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

 

  -- Overload

  PROCEDURE sendugroupemail_p(IN psenderuser numeric, IN precipientugroup character, INOUT pvemailparams temailparams, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params); 

  

  -- Send Notification Email to Patient that they have a new axiUm message

  PROCEDURE sendpatientnewmessageemail_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN precipientpatient numeric, IN pemailparams temailparams DEFAULT ax_email_pkg.ax_email_params, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

  

  -- Send Notification Email to Patient that they have a new axiUm message

    -- overload

  PROCEDURE sendpatientnewmessageemail_p(IN precipientpatient numeric, IN pemailparams temailparams DEFAULT ax_email_pkg.ax_email_params, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

 

END;
CREATE OR REPLACE PACKAGE ax_forms_pkg IS 

/******************************************************************************

* AXSO - ax_forms_pkg

* 

* Procedures and Functions related to EPR and User Forms

*

* Revisions:

* SF-00199706 Jan 31, 2019 blc Added optional parameter pOnlyApproved to GetFormAnswer_F to control whether the answers have to be approved to be returned

*******************************************************************************/ 



  -- Increment whenever you make changes. 

  --   For New Items increment the number to the left of the decimal, and set the number on the right to 00

  --   For changes increment the number to the right of the decimal

	version CONSTANT numeric DEFAULT 2.03;

  -- Version of axiUm this package is made to be compatible with.

  --   Only include Major Releases, as Patch Releases should not impact compatibility

  axium_version CONSTANT numeric DEFAULT 0.00; --DEV    

  

  -- Constants

  

    -- Answer Types  

      -- These Constants relate to fitem."AnsType"

      -- moved to ax_pkg

  answer_yes_no CONSTANT numeric DEFAULT ax_pkg.ANSWER_YES_NO;

  answer_text CONSTANT numeric DEFAULT ax_pkg.ANSWER_TEXT;

  answer_number CONSTANT numeric DEFAULT ax_pkg.ANSWER_NUMBER;

  answer_list CONSTANT numeric DEFAULT ax_pkg.ANSWER_LIST;

  answer_date CONSTANT numeric DEFAULT ax_pkg.ANSWER_DATE;

  answer_long_text CONSTANT numeric DEFAULT ax_pkg.ANSWER_LONG_TEXT;

  answer_image CONSTANT numeric DEFAULT ax_pkg.ANSWER_IMAGE;

  answer_calculated CONSTANT numeric DEFAULT ax_pkg.ANSWER_CALCULATED;

  answer_attachment CONSTANT numeric DEFAULT ax_pkg.ANSWER_ATTACHMENT;

  answer_spreadsheet CONSTANT numeric DEFAULT ax_pkg.ANSWER_SPREADSHEET;

  

  -- public help for this package   

  PROCEDURE help(IN pobjectname character varying DEFAULT NULL::character varying);     

  

  -- Delete a comment 2 record by ID or Code

  PROCEDURE deletecomment2_p(IN pcomment2row comment2, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

  

  -- Return the Text for an Anwer Type

  FUNCTION getanswertypedesc_f(panstype numeric) RETURN character varying;

  

  -- Return a Form Answer by RefCode

  FUNCTION getformanswer_f(INOUT pvsuccess boolean, INOUT pvmessage character varying, ppatient numeric, pform character, prefcode character varying, panstype numeric DEFAULT NULL::numeric, ppform numeric DEFAULT NULL::numeric, ppage numeric DEFAULT NULL::numeric, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, ponlyapproved numeric DEFAULT 1) RETURN character varying;  

  

  -- Return a Form Answer by RefCode

   -- Overload

  FUNCTION getformanswer_f(ppatient numeric, pform character, prefcode character varying, panstype numeric DEFAULT NULL::numeric, ppform numeric DEFAULT NULL::numeric, ppage numeric DEFAULT NULL::numeric, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, ponlyapproved numeric DEFAULT 1) RETURN character varying;

  

  -- Returns a comma delimited list of Reference Codes which have been answered, 

    -- out of a comma delimited list of total Reference Codes provided

    -- For YesNo answer types, only the Yes answers will be included

  FUNCTION getquestionsanswered_f(INOUT pvsuccess boolean, INOUT pvmessage character varying, ppatient numeric, pform character, prefcodes character varying, panstype numeric DEFAULT NULL::numeric, ppform numeric DEFAULT NULL::numeric, ppage numeric DEFAULT NULL::numeric, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN character varying;

  

  -- Overload

  FUNCTION getquestionsanswered_f(ppatient numeric, pform character, prefcodes character varying, panstype numeric DEFAULT NULL::numeric, ppform numeric DEFAULT NULL::numeric, ppage numeric DEFAULT NULL::numeric, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN character varying;  

  

END;
CREATE OR REPLACE PACKAGE ax_lang_pkg IS 

  -- This package contains common text Constants which may need to be translated into other languages.

  --   To change languages, replace this package with the package of the desired language

  --   Note that some error and debugging messages will remain in english regardless of which ax_lang_pkg is installed



  -- Package Version

  --   Increment whenever you make changes.

  --   For New Items increment the number to the left of the decimal, and set the number on the right to 00

  --   For Changes increment the number to the right of the decimal

  version CONSTANT numeric DEFAULT 2.01;

  -- Version of axiUm this package is made to be compatible with.

  --   Only include Major Releases, as Patch Releases should not impact compatibility

  axium_version CONSTANT numeric DEFAULT 0.00; --DEV

  -- Language of this package

  base_lang CONSTANT character varying(25) DEFAULT 'English';

  

  -- Constants

    -- Date/Time Formats

    -- moved to ax_pkg

  date_format CONSTANT character varying(50) DEFAULT ax_pkg.DATE_FORMAT; -- Normal Date Format with no Time Element

  descriptive_date_format CONSTANT character varying(50) DEFAULT ax_pkg.DESCRIPTIVE_DATE_FORMAT; -- Descritive Date Format, with Month spelled out

  ordered_date_format CONSTANT character varying(50) DEFAULT ax_pkg.ORDERED_DATE_FORMAT; -- Date Format for situations where the string will be ordered by

  date_time_format CONSTANT character varying(50) DEFAULT ax_pkg.DATE_TIME_FORMAT; -- Date Format with a Time Element

  time_format CONSTANT character varying(50) DEFAULT ax_pkg.TIME_FORMAT; -- Time Format

  date_time_24h_format CONSTANT character varying(50) DEFAULT ax_pkg.DATE_TIME_24H_FORMAT; -- Date Format with a 24 hour Time Element

  time_24h_format CONSTANT character varying(50) DEFAULT ax_pkg.TIME_24H_FORMAT;  -- 24 hour Time Elemant

  ordered_date_time_format CONSTANT character varying(50) DEFAULT ax_pkg.ORDERED_DATE_TIME_FORMAT; -- Date and Time format where the string will be ordered by

   

    -- copied from axiUm

  ids_cannotdeleteaccountholder CONSTANT character varying(75) DEFAULT 'Cannot delete the account holder of a family';

  ids_patienthasappointment CONSTANT character varying(75) DEFAULT 'Cannot delete a patient with future or pending appointments';

  ids_patienthastrx CONSTANT character varying(75) DEFAULT 'Cannot delete a patient that has a transaction for today';

  ids_patienthasbalance CONSTANT character varying(75) DEFAULT 'Cannot delete a patient with a balance';

  ids_personhasbalance CONSTANT character varying(75) DEFAULT 'Cannot delete. This person has a transaction on file';

  ids_patienthaschartlnk CONSTANT character varying(75) DEFAULT 'Cannot delete a patient which has unapproved treatment or notes';

  ids_patienthasptguar CONSTANT character varying(75) DEFAULT 'Cannot delete a patient who is another patient''s guarantor';

  

    -- introduced here

  ids_patientnotfound CONSTANT character varying(75) DEFAULT 'Patient not found';

  ids_toomanychartsfound CONSTANT character varying(75) DEFAULT 'Chart not unique';

  ids_toomanypatientsfound CONSTANT character varying(75) DEFAULT 'Multiple patients found';



  -- public help for this package   

  PROCEDURE help(IN pobjectname character varying DEFAULT NULL::character varying);    



END;
CREATE OR REPLACE PACKAGE ax_note_pkg IS 



/******************************************************************************

* AXSO - ax_note_pkg

* 

* Functions for dealing with various types of Notes in axiUm. 

*

*******************************************************************************/ 



  -- Package Version

  --   Increment whenever you make changes.

  --   For New Items increment the number to the left of the decimal, and set the number on the right to 00

  --   For Changes increment the number to the right of the decimal

  version CONSTANT numeric DEFAULT 1.04;

  -- Version of axiUm this package is made to be compatible with.

  --   Only include Major Releases, as Patch Releases should not impact compatibility

  axium_version CONSTANT numeric DEFAULT 0.00; --DEV!



/*

This package provides functions for dealing with various note type records in axiUm.



Requirements:



  - ax_pkg

  

Changelog:





*/

  -- Note Actions  

  note_add_if_new CONSTANT integer DEFAULT 1;

  note_add_replace CONSTANT integer DEFAULT 2;

  note_append_start CONSTANT integer DEFAULT 3;

  note_append_end CONSTANT integer DEFAULT 4;

  note_delete_same_user CONSTANT integer DEFAULT 5;

  note_delete CONSTANT integer DEFAULT 6;

  note_add_always CONSTANT integer DEFAULT 7;

  

  -- Sticky Note Types

  sticky_note_appointment CONSTANT integer DEFAULT 0;

  sticky_note_scheduler CONSTANT integer DEFAULT 1;

  sticky_note_rolodex CONSTANT integer DEFAULT 2;

  sticky_note_patient CONSTANT integer DEFAULT 3;

  sticky_note_patient_trx CONSTANT integer DEFAULT 4;

  sticky_note_trx_general CONSTANT integer DEFAULT 5;

  sticky_note_treatment CONSTANT integer DEFAULT 6;

  sticky_note_planned_treatment CONSTANT integer DEFAULT 7;

  sticky_note_office_charge CONSTANT integer DEFAULT 8;

  sticky_note_payment CONSTANT integer DEFAULT 9;

  sticky_note_adjustment CONSTANT integer DEFAULT 10;

  sticky_note_insurance_payment CONSTANT integer DEFAULT 11;

  sticky_note_clinic CONSTANT integer DEFAULT 12;

  sticky_note_book CONSTANT integer DEFAULT 13;  

  sticky_note_availability CONSTANT integer DEFAULT 16; 

  

  -- Sticky Note Events (AP_NOTE_Flag)

   -- Bitwise type

   -- To trigger on multiple events, then simply add them together

  sticky_event_on_date CONSTANT numeric DEFAULT 1;

  sticky_event_make_appoint CONSTANT numeric DEFAULT 2;

  sticky_event_view_trx_plan CONSTANT numeric DEFAULT 4;

  sticky_event_check_in CONSTANT numeric DEFAULT 8;

  sticky_event_check_out CONSTANT numeric DEFAULT 16;

  sticky_event_select_patient CONSTANT numeric DEFAULT 32;

  sticky_event_after_date CONSTANT numeric DEFAULT 32768;

  sticky_event_patient_claims CONSTANT numeric DEFAULT 525288;

  

  -- Standard collection of Note Parameters

  TYPE tnoteparams IS RECORD ("Action" numeric DEFAULT ax_note_pkg.note_add_if_new, "MatchText" boolean DEFAULT true, "MatchUser" boolean DEFAULT false, "MatchStationId" boolean DEFAULT false, "MatchDate" boolean DEFAULT false, "SecondaryId" numeric, "DisplayDate" timestamp without time zone, "ExpireDate" timestamp without time zone);



  -- Global Variables

    -- Parameter List, with defaults, for most AXSO procedures/functions

  ax_note_params ax_note_pkg.tnoteparams; -- Do not alter, treat as a constant  



  -- public help for this package   

  PROCEDURE help(IN pobjectname character varying DEFAULT NULL::character varying);    



  -- Create/Update/Delete Sticky Note

  PROCEDURE stickynote_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, INOUT pvappnoterow ap_note, IN pnoteparams tnoteparams DEFAULT ax_note_pkg.ax_note_params, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);



  -- Create/Update/Delete Sticky Note

  PROCEDURE stickynote_p(IN ppatient numeric, INOUT pvappnoterow ap_note, IN pnoteparams tnoteparams DEFAULT ax_note_pkg.ax_note_params, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

  

  -- Create/Update/Delete Contact Note

  PROCEDURE contactnote_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, INOUT pvptcontrow ptcont, IN pnoteparams tnoteparams DEFAULT ax_note_pkg.ax_note_params, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

 

  -- Create/Update/Delete Contact Note

  PROCEDURE contactnote_p(IN ppatient numeric, INOUT pvptcontrow ptcont, IN pnoteparams tnoteparams DEFAULT ax_note_pkg.ax_note_params, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

 

  -- Create/Update/Delete Transaction Note

  PROCEDURE transactionnote_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, INOUT pvptnoterow ptnote, IN pnoteparams tnoteparams DEFAULT ax_note_pkg.ax_note_params, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);



  -- Create/Update/Delete Transaction Note

  PROCEDURE transactionnote_p(IN ppatient numeric, INOUT pvptnoterow ptnote, IN pnoteparams tnoteparams DEFAULT ax_note_pkg.ax_note_params, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);



END;
CREATE OR REPLACE PACKAGE ax_patient_pkg IS

/******************************************************************************

* AXSO - ax_patient_pkg

* 

* Functions and Procedures for dealing with Patient Records 

*******************************************************************************/

/*

  -- Requirements

    ax_pkg

    ax_lang_pkg



*/

  -- Package Version

  --   Increment whenever you make changes.

  --   For New Items increment the number to the left of the decimal, and set the number on the right to 00

  --   For Changes increment the number to the right of the decimal

  version CONSTANT numeric DEFAULT 6.11;

  -- Version of axiUm this package is made to be compatible with.

  --   Only include Major Releases, as Patch Releases should not impact compatibility

  axium_version CONSTANT numeric DEFAULT 0.00; --DEV!



  -- P189-157650 Oct 15, 2015 blc Changed DeletePatient_P to also delete records from the new iaccess table and audit the deletion of the iuser record

  -- P189-151697 Oct 27, 2015 pq  Update ax_patient_pkg to ensure new cities added have both a City and Postal Code

  --             Nov 11, 2015 pq  Minor changes to the AddEmployer_P to handle NULLs better when matching on employer. Also changed 

  --                              Employer Address match to not default to look for employer by name if no address match is found.

  --                              Also fixed some PATIENT table default values

  -- SF-00134678 Sep 20, 2016 blc Updated to handle new fields in PATIENT and RESPHIS tables added on 6.10

  --             Mar 20, 2018 nlm Add call to addcity_p to updatepatient_p

  --             Feb 22, 2021 blc Fixed numeric error in GetNextChart_F when using a prefix and there are non-numeric charts with this prefix

  -- SF-00241331 Jun 15, 2021 blc Updated to handle new field in PATIENT table added on version 7.06

  -- AX-27219	 Oct 12, 2022 j.s resolved minor typo 		

  -- AX-27767	 Jan 03, 2023 j.s added new field to PATIENT table		



  -- public help for this package   

  PROCEDURE help(IN pobjectname character varying DEFAULT NULL::character varying);    



  PROCEDURE initializepatient_p(INOUT pvpatientrow patient, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params); 



  PROCEDURE initializeptguar_p(INOUT pvptguarrow ptguar, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params); 

   

  PROCEDURE addpatient2_p(IN ppatient numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

   

  -- Insert a Patient Record

  PROCEDURE insertpatient_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, INOUT pvpatientrow patient, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN pprefix character varying DEFAULT NULL::character varying);

   

  -- Insert a Patient Record

    -- Overload

  PROCEDURE insertpatient_p(INOUT pvpatientrow patient, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

   

  -- Insert a Responsible Party History Record

    -- Called by InsertPatient

  PROCEDURE insertresphis_p(INOUT pvpatientrow patient, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

  

  -- Compare two Patient Records to see if they match

  FUNCTION patientsequal_f(pvpatientrow1 patient, pvpatientrow2 patient, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN boolean;

   

  -- Update an Existing Patient Record

  PROCEDURE updatepatient_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, INOUT pvpatientrow patient, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN pprefix character varying DEFAULT NULL::character varying); 

   

  -- Update an Existing Patient Record

  -- Overload

  PROCEDURE updatepatient_p(INOUT pvpatientrow patient, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

   

  -- Insert a Guarantor Record

  PROCEDURE insertguarantor_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, INOUT pvpatientrow patient, IN pfamily numeric, IN pptguarrow ptguar, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

   

  -- Insert a Guarantor Record

    -- Overload

  PROCEDURE insertguarantor_p(INOUT pvpatientrow patient, IN pfamily numeric, IN pptguarrow ptguar, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);   

   

  PROCEDURE updateptguar_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN pguarantor numeric, IN pptguarrow ptguar, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

  

  -- Overload

  PROCEDURE updateptguar_p(IN ppatient numeric, IN pguarantor numeric, IN pptguarrow ptguar, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);  

  

  PROCEDURE clearispolicyguarantor_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);



  -- Overload  

  PROCEDURE clearispolicyguarantor_p(IN ppatient numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

  

  FUNCTION getnextchart_f(pprefix character varying DEFAULT NULL::character varying, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN character;



   -- Returns True if pPatient exists.

  FUNCTION patientexists_f(INOUT pvmessage character varying, ppatient numeric, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN boolean;

 

  -- returns True if pPatient has no open appointments

  FUNCTION noappointments_f(INOUT pvmessage character varying, ppatient numeric, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN boolean; 

  

  -- returns True if pPatient has no Transactions from today

  FUNCTION notransactionstoday_f(INOUT pvmessage character varying, ppatient numeric, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN boolean; 

 

  -- returns True if pPatient has items that still need approval

  FUNCTION hasunapproveditems_f(INOUT pvmessage character varying, ppatient numeric, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN boolean;  

  

  -- returns True if pPatient is a Guarantor

  FUNCTION isguarantor_f(INOUT pvmessage character varying, ppatient numeric, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN boolean;

  

  -- returns the patient and insurance overall Balance

  FUNCTION getoverallbalance_f(ppatient numeric, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN numeric;

  

  -- returns the patient Balance

  FUNCTION getpatientbalance_f(ppatient numeric, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN numeric;



  FUNCTION candeletepatient_f(ppatient numeric, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN boolean;



  FUNCTION candeletepatient_f(INOUT pvmessage character varying, ppatient numeric, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN boolean;



  FUNCTION candeletepatient_f(INOUT pvmessage character varying, pchart character, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN boolean;



  PROCEDURE deletepatient_p(IN ppatient numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

   

  PROCEDURE deletepatient_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);



  PROCEDURE deletepatient_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN pchart character, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);



  PROCEDURE undeletepatient_p(IN ppatient numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);



  PROCEDURE undeletepatient_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);



  PROCEDURE undeletepatient_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN pchart character, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);



  PROCEDURE changepatientstatus_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN pnewstatus character, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

  

  PROCEDURE changepatientstatus_p(IN ppatient numeric, IN pnewstatus character, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);  

 

  PROCEDURE changechart_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN poldchart character, IN pnewchart character, IN pincludehistory boolean DEFAULT false, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

     

  PROCEDURE changechart_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN poldchart character, IN pnewchart character, IN pincludehistory boolean DEFAULT false, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

   

  PROCEDURE changechart_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN pnewchart character, IN pincludehistory boolean DEFAULT false, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

  

  PROCEDURE updaterace_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN pracelist character varying, IN pappendonly boolean DEFAULT false, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);   

  

  PROCEDURE updaterace_p(IN ppatient numeric, IN pracelist character varying, IN pappendonly boolean DEFAULT false, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);    

   

  -- This function checks to see if pPatient has pAlert in any of the 5 patient.Alert fields

    -- -2 is returned if pPatient is invalid

    -- -1 is returned if pAlert is invalid

    -- 0 is returned if the patient does not have pAlert

    -- 1-5 is returned if the patient has the alert, the number signifying which field number

    -- Additionally, the optional pvNextFree value is set to the first Null alert position, or -1 if none are available

  FUNCTION haspatientalert_f(ppatient numeric, palert character, INOUT pvnextfree numeric, plocation numeric DEFAULT 0, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN numeric;



  -- Overload (this allows for pvNextFree to be an optional parameter)

  FUNCTION haspatientalert_f(ppatient numeric, palert character, plocation numeric DEFAULT 0, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN numeric;



  PROCEDURE insertpatientalert_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN palert character, IN plocation numeric DEFAULT 0, IN paudit numeric DEFAULT NULL::numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);



  PROCEDURE insertpatientalert_p(IN ppatient numeric, IN palert character, IN plocation numeric DEFAULT 0, IN paudit numeric DEFAULT NULL::numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);  

   

  PROCEDURE removepatientalert_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN palert character, IN plocation numeric DEFAULT 0, IN paudit numeric DEFAULT NULL::numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

 

  PROCEDURE updatepatientalert_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN palert character, IN pcurrentvalue character varying, IN paddvalue character varying, IN plocation numeric DEFAULT 0, IN paudit numeric DEFAULT NULL::numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

   

  -- This function checks to see if pPatient has pOfficeCode in any of the 5 patient.OfficeCode fields

    -- Set pOnlyValue to false if you do not care if the office code is active or inactive, otherwise leave pOnlyValid as true

    --

    -- -2 is returned if pPatient is invalid

    -- -1 is returned if pOfficeCode is invalid

    -- 0 is returned if the patient does not have pOfficeCode

    -- 1-5 is returned if the patient has the alert, the number signifying which field number

    -- Additionally, the optional pvNextFree value is set to the first Null office code position

  FUNCTION hasofficecode_f(ppatient numeric, poffice character, INOUT pvnextfree numeric, plocation numeric DEFAULT 0, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN numeric;



  -- Overload (this allows for pvNextFree to be an optional parameter)

  FUNCTION hasofficecode_f(ppatient numeric, poffice character, plocation numeric DEFAULT 0, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN numeric;

   

  PROCEDURE insertofficecode_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN poffice character, IN plocation numeric DEFAULT 0, IN paudit numeric DEFAULT NULL::numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

   

  PROCEDURE removeofficecode_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN poffice character, IN plocation numeric DEFAULT 0, IN paudit numeric DEFAULT NULL::numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

   

  PROCEDURE updateofficecode_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN poffice character, IN pcurrentvalue character varying, IN paddvalue character varying, IN plocation numeric DEFAULT 0, IN paudit numeric DEFAULT NULL::numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

   

  PROCEDURE addpatienttype_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN ppattype character, IN paudit numeric DEFAULT NULL::numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

   

  PROCEDURE removepatienttype_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN ppattype character, IN paudit numeric DEFAULT NULL::numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);



  -- Add City, but Only if it does not exist already

  --  Returns any errors encountered, or null if no errors encountered

  PROCEDURE addcity_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, INOUT pvcityrow city, INOUT pvcountry character, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

   

  -- overload for simple add

  PROCEDURE addcity_p(INOUT pvcityrow city, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);  

   

  -- Inititalize an Employer Record

  PROCEDURE initializeemployer_p(INOUT pvemployerrow employer);   

   

  -- Add Employer, but Only if it does not exist already

  --  Sets pvEmployerId to a new Employer Id Value (if null or 0 and a new record added)

  --  Returns any errors encountered, or null if no errors encountered

  PROCEDURE addemployer_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, INOUT pvemployerrow employer, IN ppatient numeric, IN pprimary numeric DEFAULT 1, IN pmatchonaddress boolean DEFAULT true, IN pupdate numeric DEFAULT 1, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);



END;
CREATE OR REPLACE PACKAGE ax_trx_pkg IS 



  -- Package Version

  --   Increment whenever you make changes.

  --   For New Items increment the number to the left of the decimal, and set the number on the right to 00

  --   For Changes increment the number to the right of the decimal

  version CONSTANT numeric DEFAULT 5.00;

  -- Version of axiUm this package is made to be compatible with.

  --   Only include Major Releases, as Patch Releases should not impact compatibility

  axium_version CONSTANT numeric DEFAULT 0.00; --DEV

/*

-- Requirements

   ax_pkg

   

*/



  -- P189-146342 May 29, 2014 blc Changed CopyBenefitPlan_P to also copy POLRANGE, VISITFEE, and POLRIDER records

  --                              Also changed CopyBenefitPlan_P so that if a new PolIns value is assigned it also copies this to POLINS.OrigRecNo

  -- P189-146546 Jul 09, 2014 blc Added WriteOffPatientBalances_P to write off patient balances on Type 1 and Type 2 transactions (Treatments and office charges)

  -- P189-155143 Jun 24, 2015 blc Updated for version 6.03 database changes

  -- P189-155706 Jul 20, 2015 blc Fixed a few bugs in WriteOffInsuranceBalances_P

  --                                1. If run with pInsuranceBucket = 0 and pNewPaymentMode = 0 it will use the payment from company1 when writing off company2 and company3's treatments. 

  --                                   Removed ability to run with pInsuranceBucket = 0 as it doesn't make sense to write off the same amount for all three insurances and pvInsPaymentId

  --                                   can only return one value

  --                                2. If run for pInsuranceBucket = 2 or 3 with pNewPaymentMode > 0 and it doesn't find an insurance payment it creates the Type 74 with company 1's insurance code.

  --                                3. When writing off company 3's balance the insert/update of the ALLOCATE table uses PolicyId2 instead of PolicyId3 in the exception handling

  --                                4. The type 7 is created with Policy1 set to the treatment's PolicyIdx instead of Policyx. It also doesn't set PolicyId1.

  --                                5. When writing off company 3's balance the Type 7's Company1 is set to the treatment's company 2 instead of company 3.

  --                                6. For company 2 and 3 write offs it creates the Type 74 with a blank insurance company

  --                                7. When the procedure was looking for an insurance payment it was including records for insurance companies under the same parent company, changed to only

  --                                   use payments for the treatment's insurance company or a parent of that company.

  --                                8. InsStatus2/InsStatus3 were not being set when secondary/tertiary insurance were written off

  --                                9. Changed to update the Type 74 record if one already exists for the patient. Previously the write off could be linked to a deleted Type 74

  --                               10. Was considering the treatment as awaiting approval when ChartTrx = 0

  -- P189-158456 Dec 01, 2015 blc Changed WriteOffPatientPayments_P, WriteOffPatientBalances_P so that the TRX/HISTORY records always have a ModifiedDate that is less than 

  --                              or equal to their corresponding ALLOCATH.ModifiedDate's as required by AX-1849/3279

  -- SF-00247556 Jun 30, 2020 blc Fixed problems with WriteOffPatientPayments_P. The ALLOCATE records were being created with negative instaed of positive values in Amount

  --                              and the PtAdj fields were being set incorrectly on the TRX payment records.

  -- SF-00245964 Jul 01, 2020 blc Added AddUnApprovedTrx_P, a procedure to create unapproved treatment

  -- SF-00249989 Aug 14, 2020 blc Added InitializeTrxMed_P to initialize a TRXMED record

  -- AX-25978.2  Oct 14, 21   j.s added new field to ALLOCATE  (add dummy field for now to avoid compile error)

  -- AX-26086	 Nov 16, 2021 tsin	Added AllocateLinks

  -- AX-26086.26282 Dec 13, 21	j.s	resolved issue with ModifiedDate being NULL in ALLOCATELINK 

  -- AX-26015	 Jan 18, 2021 t.s Added optional parameter for practice to WriteOffInsuranceBalances_P, WriteOffPatientBalances_P and WriteOffPatientPayments_P

  -- AX-39259     May 28, 25  w.s Changed all $$PLSQL_UNIT to DDL name for both Oracle and EDB compatiblity



  -- public help for this package   

  PROCEDURE help(IN pobjectname character varying DEFAULT NULL::character varying);    



  -- trx."Id" is based on different sequences, based on the trx."Type".

  -- This function returns the proper ID from the correct sequence, based on that Type.

  FUNCTION gettrxid_f(ptrxrowtype numeric) RETURN numeric;



  -- This procedure writes off an Insurance Balance

  -- pvTrxRec should contain the treatment record being written off with a couple of changes. 

  --   Bank should contain the bank code used if an insurance payment needs to be created. 

  --   User should contain the user that will be used on the TRX and ALLOCATE records that are updated/created

  --   StationId should contain the station that will be used on the TRX records that are updated/created

  --

  -- DO NOT USE FOR TREATMENTS ON PAYMENT PLANS (OrthoStatus = 1) or Unapproved Treatments (have existing chartlnk record)

  -- DO NOT USE FOR INSURANCE COMPANIES THAT USE RESERVE FUNCS

  --

  PROCEDURE writeoffinsurancebalances_p(INOUT pvtrxrec trx, IN pnewpaymentmode numeric DEFAULT 0, IN pinsurancebucket numeric, IN ppaymentcode character, IN ppaymentdescription character varying, IN padjustmentcode character, IN padjustmentdescription character varying, IN padjustmentbalance numeric, INOUT pvinspaymentid numeric, INOUT pvinspaymenttotal numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN ppractice numeric DEFAULT 0);

  

  -- Write off patient balances on the passed in Type 1 or Type 2 transaction

  -- pvTrxRec : the treatment or office charge that is being written off

  -- pvAdjustment : TRX.Id of the adjustment. If null or 0 a new adjustment will be created, otherwise the passed in adjustment will be edited

  -- pAdjustmentAmount : Amount of the adjustment. For a write off this should be a negative value

  -- pAdjustmentCode : Adjustment code to use

  -- pAdjustmentDescription : Description to be used if creating a new adjustment

  -- pParams : parameters that define the detail of verifying to be done and amount of logging to be done

  PROCEDURE writeoffpatientbalances_p(INOUT pvtrxrec trx, INOUT pvadjustment numeric, IN padjustmentamount numeric, IN padjustmentcode character, IN padjustmentdescription character varying, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN ppractice numeric DEFAULT 0);

  

  -- This procedure resets an Insurance Payment (trx type 4) total to the amount sent

  PROCEDURE updateinsurancepaymenttotal_p(IN pinspaymentid numeric, IN pinspaymenttotal numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);



  -- This procedure writes off a Patient Payment

  --  if pvAdjustment is null or 0 then a new adjustment will be created

  --  if pvAdjustment is not null, then that existing adjustment will be edited

  PROCEDURE writeoffpatientpayments_p(INOUT pvtrxrec trx, INOUT pvadjustment numeric, IN padjustmentbalance numeric, IN padjustmentcode character, IN padjustmentdescription character varying, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN ppractice numeric DEFAULT 0);



  -- Initialize a new PolIns Record

  PROCEDURE initializepolins_p(INOUT pvpolinsrow polins, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);



  -- This procedure copies a Benefit Plan based on pvSourcePolIns."PolIns"

  -- The new Benefit Plan must have one of these differences set in pvTargetPolInsRow

    -- pvTargetPolInsRow."Company"

  PROCEDURE copybenefitplan_p(INOUT pvsuccess boolean, IN psourcepolins numeric, INOUT pvtargetpolinsrow polins, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

  

  -- This procedure re-orders the billing policy that shows on the Patient Info Window -> Insurance Tab at the bottom, 

  --  so that the provided Insurance company's policies show last in the list.

  PROCEDURE movepolbillorder_p(IN pinsurance character, IN pdebug boolean DEFAULT false, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);



  -- Set trx row defaults

  PROCEDURE initializetrx_p(INOUT pvtrxrow trx, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

  

  -- Insert TRX record, and matching History record

  PROCEDURE inserttrx_p(INOUT pvtrxrow trx, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

  

  -- Insert History record, based on existing TRX record

  PROCEDURE inserthistory_p(INOUT pvtrxrow trx, IN phistorytype numeric DEFAULT ax_pkg.history_add, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);



  -- add an unapproved procedure

  PROCEDURE addunapprovedtrx_p(OUT psuccess numeric, IN ppatient numeric, IN pprocedure character, IN pstatus character, IN ptxdate timestamp without time zone DEFAULT trunc(sysdate), IN pproducer character DEFAULT ' '::bpchar, IN pdiscipline character DEFAULT ' '::bpchar, IN pcustom1 character DEFAULT ' '::bpchar, IN pcustom2 character DEFAULT ' '::bpchar, IN pcustom3 character DEFAULT ' '::bpchar, IN pcustom4 character DEFAULT ' '::bpchar, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

  

  -- initialize TRXMED record

  PROCEDURE initializetrxmed_p(INOUT pvtrxmedrow trxmed);

  

  -- AX-26086 Insert history and returns history id

  PROCEDURE inserthistory(IN row_trx trx, OUT historyid numeric); 



END;
CREATE OR REPLACE PACKAGE ax_users_pkg IS 

/******************************************************************************

* AXSO - ax_users_pkg

* 

* Functions dealing with axiUm User and Provider Records

*

*******************************************************************************/

  -- Package Version

  --   Increment whenever you make changes.

  --   For New Items increment the number to the left of the decimal, and set the number on the right to 00

  --   For Changes increment the number to the right of the decimal

  version CONSTANT numeric DEFAULT 1.04;

  -- Version of axiUm this package is made to be compatible with.

  --   Only include Major Releases, as Patch Releases should not impact compatibility

  axium_version CONSTANT numeric DEFAULT 0.00; --DEV



/*

This package provides functions for dealing with various note type records in axiUm.



Requirements:



  - ax_pkg

  - ax_assign_pkg

  

  ax_settings

  ----------------     

  set serveroutput on ;

  declare    

    vSettingRow ax_setting%rowtype;

  begin

    vSettingRow."Key" := 'Lockout.MaxAttempts';

    vSettingRow."Value" := '5';

    vSettingRow."Description" := 'The number of failed login attempts that triggers a lockout.';

    ax_pkg.AddSetting_P(vSettingRow);

    vSettingRow."Key" := 'Lockout.LockedOutTime';

    vSettingRow."Value" := '15';

    vSettingRow."Description" := 'The number of minutes before the account is unlocked.';

    ax_pkg.AddSetting_P(vSettingRow);

  end;

  

Changelog:





*/



  -- public help for this package   

  PROCEDURE help(IN pobjectname character varying DEFAULT NULL::character varying);  



  FUNCTION lockoutcheck_f(plogon character varying, plogonhistory numeric, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN boolean;



  PROCEDURE lockoutlock_p(IN plogon character varying, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

  

  PROCEDURE lockoutunlock_p(IN plogon character, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);



  PROCEDURE inactivateprovidergroup_p(IN ppgroup character, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params);

    

  PROCEDURE changeprovider_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN poldprovider character, IN pnewprovider character, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN pasofdate timestamp without time zone DEFAULT NULL::timestamp without time zone, IN pchangehistory boolean DEFAULT false, IN pskiptables character varying DEFAULT NULL::character varying);

  

  FUNCTION checkaccesshour_f(puser numeric, pday numeric, ptime numeric) RETURN numeric;

  

  FUNCTION checkaccesshour_f(puser numeric, pdatetime timestamp without time zone) RETURN numeric;



END;
CREATE OR REPLACE PACKAGE carequality_pkg IS
	FUNCTION get_carequality_status() RETURN numeric;
	FUNCTION get_carequality_consentcode() RETURN character varying;							--AX-27002
	FUNCTION get_carequality_patient_has_consent(vpatient numeric) RETURN numeric; 	-- AX-27011
END;
CREATE OR REPLACE PACKAGE ccda_cfg_pkg IS

  -- used to determine which practice address/phone to use for batch export process

  FUNCTION getpracticeid(vpid numeric, vuserid numeric, vstationid numeric) RETURN numeric; 

  FUNCTION getexportdir() RETURN character varying;



  --E143263.3 added optional 2nd parameter

  FUNCTION getpatientidentifier(vpid numeric, vbshowinfo boolean DEFAULT true) RETURN character varying;

  FUNCTION getpatientidentifiertype() RETURN character varying;

  

  --E143263.3 added optional 2nd parameter

  FUNCTION getuseridentifier(vuserid numeric, vbshowinfo boolean DEFAULT true) RETURN character varying;

  FUNCTION getuseridentifiertype() RETURN character varying;

  

            

  FUNCTION getracecode(vustype numeric) RETURN character varying;

  FUNCTION getethniccode(vustype numeric) RETURN character varying;

  

  -- sections; E143263.4

  -- AX-18945.19095 - adding new date range params...

  FUNCTION getsocialhistorysection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob;

  FUNCTION getproblemsection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob;

  FUNCTION getimmunizationsection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob;

  FUNCTION getallergiessection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob;

  FUNCTION getmedicationsection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob;

  FUNCTION getreasonforreferralsection(vpid numeric, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob;

  FUNCTION getplanofcaresection(vpid numeric, vbshowobjinfo boolean DEFAULT true, vbshowapptinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob;

  FUNCTION getproceduresection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob;

  FUNCTION getvitalsignssection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob;

  FUNCTION getresultssection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob;

  FUNCTION getfunctionalstatussection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob;

  FUNCTION getencounterssection(vpid numeric, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob;

  FUNCTION getmedicalequipmentsection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob; -- AX-21118

  FUNCTION getgoalssection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob; -- AX-21739

  FUNCTION gethealthconcernssection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob; -- AX-21739

  FUNCTION getcognitivestatussection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob; -- AX-21879f

  FUNCTION getclinicalnotessection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob; -- AX-26344

  PROCEDURE getsoapnotes(IN vpid numeric, IN vnotedate timestamp without time zone, INOUT vtext clob, INOUT ventries clob, INOUT vcount numeric); 	-- AX-26430

  PROCEDURE gettxsoapnotes(IN vpid numeric, IN vnotedate timestamp without time zone, IN vcharttrx numeric, INOUT vtext clob, INOUT ventries clob, INOUT vcount numeric); -- AX-26430

  FUNCTION gettreatmentplansection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob; -- AX-26388



  FUNCTION getinstructionssection(vapptid numeric, vbshowptdecinfo boolean DEFAULT true, vbshowinfo boolean DEFAULT true) RETURN clob;

  FUNCTION getreasonforvisitsection(vapptid numeric, vbshowinfo boolean DEFAULT true) RETURN clob;

  FUNCTION getmedadministeredsection(vapptid numeric, vbshowinfo boolean DEFAULT true) RETURN clob; 

  FUNCTION getnucctype(vprov character varying) RETURN character varying;

  FUNCTION getproceduresectionvisit(vpid numeric, vapptdate timestamp without time zone, vbshowinfo boolean DEFAULT true) RETURN clob;

  

  

  	FUNCTION getreferralinfovisit(vpid numeric, vpform numeric) RETURN character varying;

  	FUNCTION getschedimginfovisit(vpid numeric, vpform numeric) RETURN character varying;

  	FUNCTION getschedlabinfovisit(vpid numeric, vpform numeric) RETURN character varying;

  	

	FUNCTION getplanofcaresectionvisit(vpid numeric, vapptdate timestamp without time zone, vbshowobjinfo boolean DEFAULT true, vbshowapptinfo boolean DEFAULT true, vbshowdiagtestspending boolean DEFAULT true, vbshowfutureschedtests boolean DEFAULT true, vbshowfuturereferrals boolean DEFAULT true) RETURN clob;

  

END;
CREATE OR REPLACE PACKAGE ccda_pkg IS



-- AX-18945.19094 - added new optional date/time range params...

FUNCTION ccdatocsummary(patientid numeric, practiceid numeric, userid numeric, sections character varying DEFAULT 'ALL'::character varying, isdatefrom numeric DEFAULT 0, date1 timestamp without time zone DEFAULT NULL::timestamp without time zone, date2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob;

FUNCTION ccdatocsecsummary(patientid numeric, practiceid numeric, userid numeric, isdatefrom numeric DEFAULT 0, date1 timestamp without time zone DEFAULT NULL::timestamp without time zone, date2 timestamp without time zone DEFAULT NULL::timestamp without time zone, sections character varying DEFAULT NULL::character varying) RETURN clob;

FUNCTION ccdaexportsummary(patientid numeric, practiceid numeric, userid numeric, sections character varying DEFAULT 'ALL'::character varying, isdatefrom numeric DEFAULT 0, date1 timestamp without time zone DEFAULT NULL::timestamp without time zone, date2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob;

FUNCTION ccdaambulatorysummary(patientid numeric, practiceid numeric, userid numeric, sections character varying DEFAULT 'ALL'::character varying, isdatefrom numeric DEFAULT 0, date1 timestamp without time zone DEFAULT NULL::timestamp without time zone, date2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob;





--E143263 added last optional parameter

FUNCTION ccdavisitsummary(patientid numeric, practiceid numeric, userid numeric, apptid numeric, selsections character varying DEFAULT NULL::character varying) RETURN clob;



PROCEDURE infomanagerexport(IN patientid numeric, IN userid numeric, IN stationid numeric);

PROCEDURE ccdatocsummaryproc(IN patientid numeric, IN practiceid numeric, IN userid numeric, IN isdatefrom numeric DEFAULT 0, IN date1 timestamp without time zone DEFAULT NULL::timestamp without time zone, IN date2 timestamp without time zone DEFAULT NULL::timestamp without time zone, IN sections character varying DEFAULT NULL::character varying, OUT tocsummary clob);



-- AX-21643.21710d

PROCEDURE executeccdaschedjob(IN ccdaschid numeric, IN practiceid numeric, IN audituser numeric);





END;
CREATE OR REPLACE PACKAGE chart_pkg IS

  -- call VerifyChart to verify all teeth

  PROCEDURE verifychart(IN chartid character);

  

  -- helper routines

  PROCEDURE toothfromsite(IN site numeric, OUT tooth numeric, OUT isprimary boolean, OUT error boolean);

  PROCEDURE verifysite(IN pid numeric, IN site numeric, IN currentstate numeric, INOUT state numeric);

  FUNCTION hasremoved(pid numeric, site numeric) RETURN boolean;

  FUNCTION hasimpacted(pid numeric, site numeric) RETURN boolean;

  FUNCTION hasplanremoved(pid numeric, site numeric) RETURN boolean;

END;
CREATE OR REPLACE PACKAGE consent_pkg IS



	-- shared table of missing consents, kept in memory until database call ends

	TYPE consent_table IS TABLE OF character varying(255);

	v_consenttable consent_pkg.consent_table DEFAULT CONSENT_TABLE();

	



	FUNCTION trx_significant_change(proc1 character, proc2 character, site1 character, site2 character) RETURN numeric;





	FUNCTION trx_has_consent(origrecno numeric, procedur character, site character, patientid numeric, providertype character, returnall numeric DEFAULT 0, initializedata numeric DEFAULT 1, site2 character DEFAULT NULL::bpchar) RETURN character varying;





	FUNCTION pt_needs_tx_consent(patientid numeric, returnall numeric DEFAULT 0) RETURN character varying;





	FUNCTION trx_needs_tx_consent(trxtype numeric, trxid numeric, trxtreatment numeric, includestatusc numeric) RETURN numeric;

	

	

	FUNCTION find_element(value character) RETURN numeric;

	FUNCTION add_element(value character) RETURN numeric;

	FUNCTION get_results() RETURN character varying;

	

	

END;
CREATE OR REPLACE PACKAGE custom_pa2template_pkg IS
FUNCTION custom_pa2template_html() RETURN clob;
FUNCTION custom_pa2template_css() RETURN clob;
FUNCTION custom_pa2template_js() RETURN clob;
END;
CREATE OR REPLACE PACKAGE dbms_lob_s IS

  PROCEDURE createtemporary(INOUT lob_loc clob, IN cache boolean, IN dur integer DEFAULT 0); 

  PROCEDURE append(INOUT dest_lob clob, IN src_lob clob); 

  

END;
CREATE OR REPLACE PACKAGE dept_pkg IS

  TYPE dept_ar_record IS RECORD (open_ar numeric, close_ar numeric);

  TYPE dept_ar_type IS REF CURSOR RETURN dept_ar_record;

  FUNCTION deptwhere(department character, t_alias character, p_alias character, pt_alias character) RETURN clob;

  FUNCTION deptwherecrystal(department character, t_alias character, p_alias character, pt_alias character) RETURN clob;

  FUNCTION arasat_dept(asatdate timestamp without time zone, department character) RETURN numeric;

  FUNCTION txindept(historyid numeric, wherestr character) RETURN numeric;

  FUNCTION historyprev(origrecno numeric, cutoffdate timestamp without time zone) RETURN numeric;

  PROCEDURE create_dept_txs(IN batch numeric, IN fromdate timestamp without time zone, IN todate timestamp without time zone, IN department character varying);

  PROCEDURE delete_dept_txs(IN batch numeric);

END;
CREATE OR REPLACE PACKAGE dpsi_pkg IS
  FUNCTION getptpsr(patientid numeric, sextant numeric) RETURN numeric;
  FUNCTION getptpsrbydate(chartdate timestamp without time zone, patientid numeric, sextant numeric) RETURN numeric; -- AX-24528.2
  FUNCTION iscode4(ptperioid numeric, sextant numeric) RETURN boolean;
  FUNCTION iscode3(ptperioid numeric, sextant numeric) RETURN boolean;
  FUNCTION iscode2(patientid numeric, ptperioid numeric, sextant numeric) RETURN boolean;
  FUNCTION iscode1(patientid numeric, ptperioid numeric, sextant numeric) RETURN boolean;
END;
CREATE OR REPLACE PACKAGE ehr_pkg IS

   -- delete an EPR form and all related records

   -- A99841 Phil Q. - Created procedure and tables.

   -- P189-157451 Amc. - Updated for 6.02

   -- SF-00241583 Mar 20, 2020 blc - updated with changes made to the standard version of this package on 7.06

   -- Requires the following tables:

   --DROP TABLE PFORM_DELETED;

   --DROP TABLE PITEMIMG_DELETED;

   --DROP TABLE PTSIG_DELETED;

   --DROP TABLE PPAGESIG_DELETED;

   --DROP TABLE PPAGE_DELETED;

   --DROP TABLE PITEM_DELETED;

   --DROP TABLE PITEMTMP_DELETED;

   --DROP TABLE PITEMCOL_DELETED;

   --DROP TABLE IPTFORM_DELETED;

   --DROP TABLE PFORMEVT_DELETED;

   --SELECT * FROM PFORMS_DELETED;

   --SELECT * FROM PITEMIMG_DELETED;

   --SELECT * FROM PTSIG_DELETED;

   --SELECT * FROM PPAGESIG_DELETED;

   --SELECT * FROM PPAGE_DELETED;

   --SELECT * FROM PITEM_DELETED;

   --SELECT * FROM PITEMTMP_DELETED;

   --SELECT * FROM IPTFORM_DELETED;

   --CREATE TABLE PFORM_DELETED as (select * from pform where 1=0);

   --CREATE TABLE PITEMIMG_DELETED as (select * from pitemimg where 1=0);

   --CREATE TABLE PTSIG_DELETED as (select * from ptsig where 1=0);

   --CREATE TABLE PPAGESIG_DELETED as (select * from ppagesig where 1=0);

   --CREATE TABLE PPAGE_DELETED as (select * from ppage where 1=0);

   --CREATE TABLE PITEM_DELETED as (select * from pitem where 1=0);

   --CREATE TABLE PITEMTMP_DELETED as (select * from pitemtmp where 1=0);

   --CREATE TABLE PITEMCOL_DELETED as (select * from pitemcol where 1=0);

   --CREATE TABLE IPTFORM_DELETED as (select * from iptform where 1=0);

   --CREATE TABLE PFORMEVT_DELETED as (select * from pformevt where 1=0);



   PROCEDURE delete_eprform(IN pformid numeric);

   -- determine if one FITEM is a decsendant of another



   FUNCTION isfitemdescendant(fitemparent numeric, fitemchild numeric) RETURN numeric;



END;
CREATE OR REPLACE PACKAGE fportal_pkg IS

  -- version: 6.02.xx

    -----------------------------------------------------------------------

    -- Types

    -----------------------------------------------------------------------

    

    /** Record type containing details for a particular appointment. */

    TYPE rec_apptdetail IS RECORD (apptpk integer DEFAULT 0, apptcode character varying(15), appttype integer, apptconfirmed integer, apptdiscipline character varying(15), apptclinic character varying(63), apptclinicstartchkmethod integer, apptchairid integer, apptchair character varying(63), apptconfirm integer, apptdate character varying(15), appttime character varying(15), apptbookdate character varying(15), apptpatient integer, apptreason character varying(200), apptprovider character varying(10), apptassistant character varying(10), apptprovideruser integer, apptstartchecked integer, apptstartcheck integer, apptstartcheckuser integer, apptstartchecktime integer, apptrequiresstartchk numeric, apptptrequiresstartchk integer, apptisortho numeric(5,0), apptorthostage character(6), apptorthostagedesc character(30)); 

        

    /** Record type containing details for a particular patient. */

    TYPE rec_patientdetail IS RECORD (ptpk integer DEFAULT 0, ptchart character varying(10), ptfirstinitial character varying(1), ptfirst character varying(30), ptlast character varying(60), ptagemonths integer, ptsex integer, ptname character varying(100), ptagesex character varying(10));

        

    /** Record type containing details for a particular user. */

    TYPE rec_userdetail IS RECORD (upk integer DEFAULT 0, ufirstinitial character varying(1), ufirst character varying(30), ulast character varying(60), uisinstructor integer, uisprovider integer, uproviderid character varying(10), uprovidergroup character varying(6), uprovideryear integer, uprovidertypedesc character varying(20), uname character varying(100), urequiregrading integer, uinactive integer);

    

    /** Record type containing details for a particular treatment. */

    TYPE rec_txdetail IS RECORD (txcharttrx integer DEFAULT '-1'::integer, txtype integer DEFAULT '-1'::integer, txchartid integer, txid integer, txdiscipline character varying(15), txdiagnosis character varying(8), txphase character varying(2), txsequence integer, txcustomval1 character varying(6), txcustomval2 character varying(6), txcustomval3 character varying(6), txcustomval4 character varying(6), txpatientid integer, txentryuser integer, txentrydate character varying(15), txappuser integer, txappdate character varying(15), txproducer character varying(100), txdate character varying(15), txproccode character varying(7), txprocdesc character varying(100), txstatus character varying(6), txsite character varying(10), txsurface character varying(6), txtreatme2 integer, txorthonote character varying(32767), txgrading integer, txevaldate character varying(15), txevaluser integer, txevalform character varying(30), txisorthotreatment integer);



    /** Record type containing details for a particular (general or template) note. */

    TYPE rec_notedetail IS RECORD (ntauto integer DEFAULT '-1'::integer, ntphase character varying(2), ntsequence integer, ntcustomval1 character varying(6), ntcustomval2 character varying(6), ntnotecode character varying(7), ntnotetext character varying(32767), ntpatientid integer, ntentryuser integer, ntentrydate character varying(15), ntappuser integer, ntappdate character varying(15), nttxid integer, ntdesc character varying(30), ntsite character varying(30), ntstatus character varying(6));

    

    /** Record type containing details for a particular (SOAP)note. */

    TYPE rec_soapnotedetail IS RECORD (ntotherid integer DEFAULT '-1'::integer, ntphase character varying(2), ntsequence integer, ntcustomval1 character varying(6), ntcustomval2 character varying(6), ntnotecode character varying(7), ntnotetexts character varying(32767), ntnotetexto character varying(32767), ntnotetexta character varying(32767), ntnotetextp character varying(32767), ntpatientid integer, ntentryuser integer, ntentrydate character varying(15), ntappuser integer, ntappdate character varying(15), nttxid integer, ntdesc character varying(30), ntsite character varying(30), ntstatus character varying(6), ntdate character varying(15));

    

    /** Record type containing details for a particular finding (material or condition). */

    TYPE rec_findingdetail IS RECORD (fauto integer DEFAULT '-1'::integer, ftype integer DEFAULT '-1'::integer, fchartid integer, fpatientid integer, fentryuser integer, fentrydate character varying(15), fappuser integer, fappdate character varying(15), ftxdate character varying(15), fproccode character varying(7), fprocdesc character varying(60), fstatus character varying(6), fsite character varying(10), fsurface character varying(6), fprevstatus character varying(6));

    

    /** Record type containing details for a particular Form. */

    TYPE rec_formdetail IS RECORD (fpform integer DEFAULT '-1'::integer, fcode character varying(6), fdesc character varying(60), ftxdate character varying(15), fstatus character varying(6), fassigneduser integer, fassignedugroup character(6), fpatientid integer, fentryuser integer, fentrydate character varying(15), fappuser integer, fappdate character varying(15));

    

    /** Record type containing details for a particular Perio. */

    TYPE rec_periodetail IS RECORD (pptperio integer DEFAULT '-1'::integer, pdesc character varying(60), pdate character varying(15), ppatientid integer, pentryuser integer, pentrydate character varying(15), pappuser integer, pappdate character varying(15), pstatus integer);

    

    /** Record type containing details for a particular Letter. */

    TYPE rec_letterdetail IS RECORD (pptletter integer DEFAULT '-1'::integer, pdate character varying(15), pdesc character varying(90), pfiletype character varying(15), pstatus character varying(15), ppatientid integer, pentryuser integer, pentrydate character varying(15), pappuser integer, pappdate character varying(15));



    /** Record type containing details for a particular Ortho Visit. */

    TYPE rec_orthovisitdetail IS RECORD (ovauto integer DEFAULT '-1'::integer, ovpatientid integer, ovpatientauto integer, ovstatus character varying(6), ovdeleted integer, ovcustomval1 character varying(6), ovcustomval2 character varying(6), ovcustomval3 character varying(6), ovcustomval4 character varying(6), ovdiscipline character varying(15), oventryuser integer, oventrydate character varying(15), ovprovider character varying(10), ovtxdate character varying(15), ovappuser integer, ovappdate character varying(15), ovdeluser integer, ovdeldate character varying(15), ovunit numeric, ovprocid integer, ovproccode character varying(7), ovprocdesc character varying(100), ovorthonote character varying(32767));

    

    -----------------------------------------------------------------------

    -- Procedures

    -----------------------------------------------------------------------    

    

    /**

    * Procedure used to create log entries in the ILOG table during a session.<p/>

    *

    * param: vUserName INPUT: Username entered by the user at login.<p/>

    * param: vAction INPUT: Action type for the log entry.<br/>

    *    <li>0= Failure.<br/>

    *    <li>1= Login.<br/>

    *    <li>2= Logout.<p/>

    * param: viUser INPUT: User ID of the user for this ILOG entry (USERS.User)<p/>

    */

    PROCEDURE loglogin(IN vusername character varying, IN vaction integer, IN viuser integer);

    

  /**

  * Procedure to open user ticket for Faculty Portal

  * param: vUserId INPUT: User ID

  * param: vTicketId OUTPUT: Ticket ID of ticket being created

  */

  PROCEDURE openticket(IN vuserid numeric, OUT vticketid numeric);

  

  /**

  * Procedure to close user ticket for Faculty Portal

  * param: vTicketId INPUT: Ticket ID

  */

  PROCEDURE closeticket(IN vticketid numeric);



  /**

  * Procedure to get user associated with the ticket for Faculty Portal

  * param: vTicketId INPUT: Ticket ID

  * param: results_cur OUTPUT: User Row containing:

  *  - User, Pin, Password, PINLocked, Logon, Name, Deleted, EffDate, ExpDate, IsInstructor, ApprovePlanTx, ApproveCompTx

  *    ApproveExistingTx, ApproveNotes, ApproveEHRForms, ApproveStartChks, ApproveLetters, ApprovePerio, ApproveConditionTx

  */

  PROCEDURE getuserfromticket(IN vticketid numeric, OUT results_cur cursor_pkg.weakcursor);

  

  /**

  * Procedure to check user ticket for Faculty Portal

  * param: vTicketId INPUT: Ticket ID

  * param: vResult OUTPUT: result of check (0=Ticket Closed, 1= Ticket Open)

  */

  PROCEDURE checkticket(IN vticketid numeric, OUT vresult integer);

  

    /**

  * Procedure used to get all appointments start checked today by selected instructor

    * param: vUserId INPUT: USERS.User

    * param: vClinicId INPUT: Clinic ID to filter the appointments - If set to 0, the list will be filtered by all clinics the instructor has an access to.

    * param: vClinicTimeId INPUT: Clinic Time ID to filter the appointments - If set to 0, the list will contain all clinic times the clinic has.

    * param: vStationId INPUT: Station ID used to get Server Time zone offset.

    * param: vIncludeNoNotification INPUT: Include/exclude appointments without chair notification state.

    * param: vSearchKeyword INPUT: Keyword for filtering the appointments.

    * param: vSearchType INPUT: Field to search using the keyword (Provider First/Last Name, Code, Patient First/Last Name)

    * param: vFilterNotification INPUT: list of chair state notification IDs to include in the appointment list (separated by comma)

    * param: vOrderBy INPUT: keyword to order the list by.

    * param: vNumRows INPUT: total number of rows for the list

    * param: vPage INPUT: page number for the paginated list (requested)

    * param: vCurrentPage OUTPUT: actual page number for the paginated list (retrieved)

    * param: vTotalPage OUTPUT: total number of pages available for given criteria

    * param: vResults OUTPUT: Weak cursor containing list of appointments matching given criteria

  */

  PROCEDURE getapptmylist(IN vuserid integer, IN vclinicid integer, IN vclinictimeid integer, IN vincludenonotification integer, IN vsearchkeyword character varying, IN vsearchtype character varying, IN vfilternotification character varying, IN vorderby character varying, OUT vresults cursor_pkg.weakcursor);

    

    /**

  * Procedure used to get all appointments watched today by selected instructor

    * param: vUserId INPUT: USERS.User

    * param: vClinicId INPUT: Clinic ID to filter the appointments - If set to 0, the list will be filtered by all clinics the instructor has an access to.

    * param: vClinicTimeId INPUT: Clinic Time ID to filter the appointments - If set to 0, the list will contain all clinic times the clinic has.

    * param: vStationId INPUT: Station ID used to get Server Time zone offset.

    * param: vIncludeNoNotification INPUT: Include/exclude appointments without chair notification state.

    * param: vSearchKeyword INPUT: Keyword for filtering the appointments.

    * param: vSearchType INPUT: Field to search using the keyword (Provider First/Last Name, Code, Patient First/Last Name)

    * param: vFilterNotification INPUT: list of chair state notification IDs to include in the appointment list (separated by comma)

    * param: vOrderBy INPUT: keyword to order the list by.

    * param: vNumRows INPUT: total number of rows for the list

    * param: vPage INPUT: page number for the paginated list (requested)

    * param: vCurrentPage OUTPUT: actual page number for the paginated list (retrieved)

    * param: vTotalPage OUTPUT: total number of pages available for given criteria

    * param: vResults OUTPUT: Weak cursor containing list of appointments matching given criteria

  */

    PROCEDURE getapptwatchedlist(IN vuserid integer, IN vclinicid integer, IN vclinictimeid integer, IN vincludenonotification integer, IN vsearchkeyword character varying, IN vsearchtype character varying, IN vfilternotification character varying, IN vorderby character varying, OUT vresults cursor_pkg.weakcursor);

    

    PROCEDURE getapptalllistwithstartcheck(IN vuserid integer, IN vclinicid integer, IN vclinictimeid integer, IN vhidepast integer, IN vincludenonotification integer, IN vsearchkeyword character varying, IN vsearchtype character varying, IN vfilternotification character varying, IN vorderby character varying, OUT vresults cursor_pkg.weakcursor);

        

    /**

  * Procedure used to get all appointments available

    * param: vUserId INPUT: USERS.User

    * param: vClinicId INPUT: Clinic ID to filter the appointments - If set to 0, the list will be filtered by all clinics the instructor has an access to.

    * param: vClinicTimeId INPUT: Clinic Time ID to filter the appointments - If set to 0, the list will contain all clinic times the clinic has.

    * param: vHidePast INPUT: Include/exclude past appointments (time passed).

    * param: vShowOnlyReqStartChk INPUT: Include/exclude appointment that does not require Start Check

    * param: vIncludeNoNotification INPUT: Include/exclude appointments without chair notification state.

    * param: vSearchKeyword INPUT: Keyword for filtering the appointments.

    * param: vSearchType INPUT: Field to search using the keyword (Provider First/Last Name, Code, Patient First/Last Name)

    * param: vFilterNotification INPUT: list of chair state notification IDs to include in the appointment list (separated by comma)

    * param: vOrderBy INPUT: keyword to order the list by.

  */

    PROCEDURE getapptalllist(IN vuserid integer, IN vclinicid integer, IN vclinictimeid integer, IN vhidepast integer, IN vincludenonotification integer, IN vsearchkeyword character varying, IN vsearchtype character varying, IN vfilternotification character varying, IN vorderby character varying, OUT vresults cursor_pkg.weakcursor);

    

  /**

  * Procedure to count all unapproved items for the appointment<p/>

  * param: vAppointment IN: Appointment ID<p/> 

  * param: results_cur OUT: Results cursor containing row of counts:<p/>

  * <li>NumTrx - Count of Treatments <br />

  * <li>NumNotes - Count of Notes <br />

  * <li>TxMissingStartChk - check if there are treatments missing start check <br />

  * <li>LastStartChkUser - Last Start Checked USER ID<br />

  */

  PROCEDURE getapptapprovecount(IN vappointment integer, OUT results_cur cursor_pkg.weakcursor);

  

  /**

  * Procedure used to get all provider StartChecked by current instructor

  * param: vUserId INPUT: Instructor ID<p/>

  * param: vClinicId INPUT: ID of Clinic to view list of appointments from (0 = all clinics)<p/>

  * param: vClinicTimeId INPUT: ID of Clinic Time to view list of appointment from (0 = all clinic times)<p/>

  * param: vSearchKeyword INPUT: Keyword to search list<p/>

  * param: vSearchType INPUT: Field used to search keyword<p/>

  * param: vProviderType INPUT: Provider Type to search list<p/>

  * param: vProviderGroup INPUT: Provider Group to search list<p/>

  * param: vOrderBy INPUT: DESC OR ASC<p/>

  * param: vNumRows INPUT: Number of rows to return<p/>

  * param: vPage INPUT: Number of page to return (page is a group of rows)<p/>

  * param: vCurrentPage OUTPUT: Actual page of the list<p/>

  * param: vTotalPage OUTPUT: Total number of pages available<p/>

  * param: vResults OUTPUT: Weak cursor to contain the data retrieved<p/>

  */

  PROCEDURE getprovmylist(IN vuserid integer, IN vclinicid integer, IN vclinictimeid integer, IN vsearchkeyword character varying, IN vsearchtype character varying, IN vprovidertype character varying, IN vprovidergroup character varying, IN vorderby character varying, IN vnumrows integer, IN vpage integer, OUT vcurrentpage integer, OUT vtotalpage integer, OUT vresults cursor_pkg.weakcursor);

  

  /**

  * Procedure to count all unapproved items for the provider<p/>

  * param: vUser IN: User ID of the provider<p/> 

  * param: vProducer IN: Provider Code in USERS."Provider"<p/> 

  * param: vMedicaidCode IN: list of procedure codes defined as Medicaid code<p/> 

  * param: results_cur OUT: Results cursor containing row of counts:<p/>

  * - TxCount: unapproved treatment count<p/>

  * - NoteCount: unapproved note count<p/>

  * - FormCount: unapproved forms count<p/>

  * - FindingCount: unapproved findings/conditions count<p/>

  * - PerioCount: unapproved perio count<p/>

  * - LetterCount: unapproved letter attachments count<p/>

  */

  PROCEDURE getprovapprovecount(IN vuser integer, IN vproducer character varying, IN vmedicaidcode character varying, OUT results_cur cursor_pkg.weakcursor);

  

  /**

  * Procedure used to get all provider reserved in clinic the instructor has access to

  * param: vUserId INPUT: Instructor ID<p/>

  * param: vClinicId INPUT: ID of Clinic to view list of appointments from (0 = all clinics)<p/>

  * param: vClinicTimeId INPUT: ID of Clinic Time to view list of appointment from (0 = all clinic times)<p/>

  * param: vSearchKeyword INPUT: Keyword to search list<p/>

  * param: vSearchType INPUT: Field used to search keyword<p/>

  * param: vProviderType INPUT: Provider Type to search list<p/>

  * param: vProviderGroup INPUT: Provider Group to search list<p/>

  * param: vOrderBy INPUT: DESC OR ASC<p/>

  * param: vNumRows INPUT: Number of rows to return<p/>

  * param: vPage INPUT: Number of page to return (page is a group of rows)<p/>

  * param: vCurrentPage OUTPUT: Actual page of the list<p/>

  * param: vTotalPage OUTPUT: Total number of pages available<p/>

  * param: vResults OUTPUT: Weak cursor to contain the data retrieved<p/>

  */

    PROCEDURE getprovalllist(IN vuserid integer, IN vclinicid integer, IN vclinictimeid integer, IN vsearchkeyword character varying, IN vsearchtype character varying, IN vprovidertype character varying, IN vprovidergroup character varying, IN vorderby character varying, IN vnumrows integer, IN vpage integer, OUT vcurrentpage integer, OUT vtotalpage integer, OUT vresults cursor_pkg.weakcursor);

  

  /**

  * Helpter function to count number of unapproved treatments a provider has

  * param: vProducer INPUT: Provider Code in USERS."Producer"

    * param: vMedicaidCode INPUT: List of procedure codes that are defined as a Medicaid code

  * return: number of unapproved treatments

  */

  FUNCTION counttx(vproducer character varying, vmedicaidcode character varying) RETURN integer;

  

  /**

  * Helpter function to count number of unapproved notes a provider has

  * param: vUser INPUT: User ID

  * return: number of unapproved ntoes

  */

  FUNCTION countnote(vuser integer) RETURN integer;

  

  /**

  * Helpter function to count number of unapproved forms a provider has

  * param: vUser INPUT: User ID

  * return: number of unapproved forms

  */

  FUNCTION countform(vuser integer) RETURN integer;

  

  /**

  * Helpter function to count number of unapproved findings/conditions a provider has

  * param: vProducer INPUT: Provider Code in USERS."Producer"

    * param: vMedicaidCode INPUT: List of procedure codes that are defined as a Medicaid code

  * return: number of unapproved findings/conditions

  */

  FUNCTION countfind(vproducer character varying, vmedicaidcode character varying) RETURN integer;

  

  /**

  * Helpter function to count number of unapproved perio charts a provider has

  * param: vUser INPUT: User ID

  * return: number of unapproved perio charts

  */

  FUNCTION countperio(vuser integer) RETURN integer;

  

  /**

  * Helpter function to count number of unapproved letter attachments a provider has

  * param: vUser INPUT: User ID

  * return: number of unapproved letter attachments

  */

  FUNCTION countletter(vuser integer) RETURN integer;

  

    /**

  * Helpter function to count number of ortho visits unapproved treatments a provider has

  * param: vProducer INPUT: Provider Code in USERS."Producer"

  * return: number of unapproved ortho visits

  */

  FUNCTION countorthovisits(vproducer character varying) RETURN integer;

  

    -----------------------------------------------------------------------

    -- Appointments Tab 

    -----------------------------------------------------------------------

    /**

    * Procedure to generate and return the list of line items (treatments on the appointment, and notes tied to those

    *  treatments) to be shown when an appointment is viewed in any of the Appointment subtabs (My Appts, Watch, All Appts).<p/>

    *

    * param: vAppointment INPUT: Appointment ID of the appointment (APPOINT.Appointment)<p/>

  * param: vPracticeId INPUT: Practice ID<p/>

  * param: vHideConsent INPUT: 1 = skip consent check<p/>

    * param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

    *    <li>Description - Description of the line item. For treatments, this is the procedure code and part of the procedure description. For notes, the type of note. <br/>

    *    <li>TxStatus - For treatments, the status of the treatment line (P,I,C,P*,I*,etc). Not used for notes.<br/>

    *    <li>Site - The site (tooth#) that the treatment or note applies to. <br/>

    *    <li>Surface - The surface(s) that the treatment applies to. Not used for notes.<br/>

    *    <li>TxDate - Treatment date of treatments or entry date for notes, as a string formatted MON DD YYYY.<br/>

    *    <li>LineType - Type of the line item (0=unapproved tx, 1=approved tx, 2=general tx note, 3=template tx note, 4=SOAP tx note).<br/>

    *    <li>TrxTreatme2 - For treatments, ptr to corresponding TREATME2.Auto. For treatment notes, same value as the treatment that it is attached to. <br/>

    *    <li>Approved - Flag indicating if this line is approved (0=no, 1=yes).<br/>

    *    <li>ItemKey - Unique key to use to get the details for this line item (treatments: TRX.ChartTrx, general/template notes: NOTES2.Auto, SOAP notes: NOTES2.OtherId).<br/>

    *    <li>StartChkUser - For treatments, User ID (USERS.User) of last user to start check this treatment. For notes, same as trx it's tied to. <br/>

    *    <li>TxHasReqConsent - Flag indicating if this treatment needs/has consent (0=needs it but doesn't have it, 1=either has it or doesn't need it) <p/>    

    */

    PROCEDURE getapptlines(IN vappointment integer, IN vpracticeid integer, IN vhideconsent integer, OUT results_cur cursor_pkg.weakcursor); 

    

    FUNCTION getapptrequirestartcheck(vappoint integer) RETURN integer;

    

    /**

    * Function to count the number of treatments on an appointment.<p/>

    * 

    * param: vAppoint INPUT: Appointment ID of the appointment (APPOINT.Appointment)<br/>

    * return: Count of the number of treatments on the appointment.<br/>

    */

    FUNCTION getappttrxcount(vappoint integer) RETURN integer; 

    

  /**

  * Function to count the number of ortho visit on an appointment.<p/>

  * 

  * param: vAppoint INPUT: Appointment ID of the appointment (APPOINT.Appointment)<br/>

  * return: Count of the number of ortho visits on the appointment.<br/>

  */

  FUNCTION getapptorthovisitcount(vappoint integer) RETURN integer;

  

  /**

  * Function to count the number of ortho visit notes that are attached to ortho visits on an appointment.<p/>

  * 

  * param: vAppoint INPUT: Appointment ID of the appointment (APPOINT.Appointment)<br/>

  * return: Count of the number of ortho visit notes attached to ortho visits on the appointment.<br/>

  */

  FUNCTION getapptorthovisitnotecount(vappoint integer) RETURN integer;

    

    /**

    * Function to count the number of treatment notes that are attached to treatments on an appointment.<p/>

    * 

    * param: vAppoint INPUT: Appointment ID of the appointment (APPOINT.Appointment)<br/>

    * return: Count of the number of treatment notes attached to treatments on the appointment.<br/>

    */

    FUNCTION getappttrxnotecount(vappoint integer) RETURN integer; 

    

    /**

    * Procedure to generate and return the data to show in the appointment details pane of the Appointments tab.<p/>

    * 

    * param: vApptId INPUT: Appointment ID of the appointment (APPOINT.Appointment)<p/>

    * param: vApptReason OUTPUT: Appointment reason text, returned separately to preserve formatting.<p/>

    * param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

    *    <li>PTNAMEAGESEX - String containing the patient's name, age, and gender, formatted like F.LastName(M50).<br/>

    *    <li>PTCHART - Patient's chart # (PATIENT.Chart).<br/>

    *    <li>APPTCODE - Appointment code of the appointment (APPOINT.Code).<br/>

    *    <li>APPTDISCIPLINE - Discipline of the appointment. (APPOINT.Discipline).<br/>

    *    <li>APPTCLINIC - Name of the clinic that this appointment is in (CLINIC.Description).<br/>

    *    <li>APPTCHAIR - Name of the chair that this appointment is in (CHAIR.Name).<br/>

    *    <li>APPTDATE - Date of the appointment, as a string formatted MON DD YYYY (APPOINT.Date).<br/>

    *    <li>APPTTIME - Time of the appointment, as a string formatted HH:MI - HH:MI.<br/>

    *    <li>APPTBOOKDATE - Date the appointment was created, as a string formatted MON DD YYYY (APPOINT.CreateDate).<br/>

    *    <li>APPTSTARTCHKD - Flag indicating if the appointment has been start checked or not today (0=No, 1=Yes).<br/>

    *    <li>APPTSTARTCHECKUSER - User ID of the last user to start check this appointment. (USERS.User).<br/>

    *    <li>APPTSTARTCHECKTIME - Time of the last start check for this appointment, in minutes from midnight.<p/>    

    */

    PROCEDURE getappttabdetail(IN vapptid integer, OUT vapptreason character varying, OUT results_cur cursor_pkg.weakcursor);

    

    /**

    * Procedure that gets the appointment IDs of all of the appointments for a provider for the current day.<p/>

    *

    * param: vUserId INPUT: User ID of the provider. (USERS.User)<p/>

    * param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

    *    <li>AP."Appointment" - Appointment ID of an appointment (APPOINT.Appointment).<p/>

    */

    PROCEDURE getproviderappointments(IN vuserid integer, OUT results_cur cursor_pkg.weakcursor);



    -----------------------------------------------------------------------

    -- Providers Tab

    -----------------------------------------------------------------------



  /**

  * Procedure that returns the line items (all unapproved items, and items approved today) to be shown 

  *  when an provider is opened from Providers tab -> My Prov or All Prov. <p/>

  *

  * param: vUserId INPUT: User ID of the provider (USERS.User)<p/>

  *    param: vCountryName INPUT: Name of country.<p/>

  * param: vSortDir INPUT: sorting direction 0 - ptFirstName -> ptLastName; 1 = ptLastName -> ptFirstName<p/>

  *    param: vHideConsent INPUT: 1 = skip consent check<p/>

    * param: vMedicaidCode INPUT: List of procedure codes that are defined as a Medicaid code

  * param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

  *    <li>Description - Description of the line item. For treatments/findings, this is the procedure code and part of the procedure description. For notes, the type of note. <br/>

  *    <li>Status - For treatments/findings, the status of the treatment line (P,I,C,P*,I*,A,E, etc). Not used for notes.

  *    <li>Site - The site (tooth#) that the treatment/finding or note applies to. <br/>

  * <li>Site2 - The ending site (tooth#) for bridge-type procedure.<br />

  *    <li>Surface - The surface(s) that the treatment/finding applies to. Not used for notes.<br/>

  *    <li>TxDate - Treatment date of treatments/findings or entry date for notes, as a string formatted MON DD YYYY.<br/>

  *    <li>LineType - Type of the line item (0=unapproved I/C tx, 1=tx approved today, 2=unapproved planned tx,  3=general note, 4=template note, 5=SOAP note, 6=unapproved finding, 7=finding approved today).<br/>

  *    <li>TrxTreatme2 - For treatments/findings, ptr to corresponding TREATME2.Auto. For treatment notes, same value as the treatment that it is attached to. <br/>

  *    <li>Approved - Flag indicating if this line is approved (0=no, 1=yes).<br/>

  *    <li>ItemKey - Unique key to use to get the details for this line item (treatments/findings: TRX.ChartTrx, general/template notes: NOTES2.Auto, SOAP notes: NOTES2.OtherId).<p/>

  *    <li>ChartLnk - ChartLnk ID (treatments/findings: CHARTLNK.Id, general/template notes: 0, SOAP notes: 0).<p/>

  */

    PROCEDURE getprovlines(IN vuserid integer, IN vcountryname character varying, IN vsortdir integer, IN vhideconsent integer, IN vmedicaidcode character varying, OUT results_cur cursor_pkg.weakcursor); 

    

    /**

    * Procedure that returns the data to show in the provider details pane of the Providers subtabs, and Messages tab.<p/>

    *

    * param: vUserId INPUT: User ID of the provider/user (USERS.User)<p/>

    * param: vApptReason OUTPUT: Appointment reason code for the providers next/current/prev appointment, if any (APPOINT.Reason).<p/>

    * param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

    *    <li>ISPROVIDER - Flag indicating if this user is also a provider (0=no, 1=yes).<br/>

    * <li>STATION - Name of the station that this user is currently logged in on, if any (LOG.Terminal).<br/>

    * <li>PROVIDERID - Provider ID of the provider (PRODUCER.Producer).<br/>

    * <li>PROVIDERTYPE - Text description of the provider's type (PRODTYPE.Description).<br/>

    * <li>PROVIDERGROUP - Provider group of the provider (PRODUCER.PGroup).<br/>    

    * <li>PROVIDERYEAR - Year of the provider (PRODUCER.Year).<br/>

    * <li>APPTTYPE - Flag indicating if the appointment info being shown is that of the next, current, or previous appt (-1 = no appointment found, 0 = current, 1 = next, 2 = previous).<br/>

    * <li>PTNAMEAGESEX - String containing the patient's name, age, and gender, formatted like F.LastName(M50).<br/>

    * <li>PTCHART - Patient's chart # (PATIENT.Chart).<br/>

    * <li>APPTCODE - Appointment code of the appointment (APPOINT.Code).<br/>

    *    <li>APPTDISCIPLINE - Discipline of the appointment. (APPOINT.Discipline).<br/>

    *    <li>APPTCLINIC - Name of the clinic that this appointment is in (CLINIC.Description).<br/>

    *    <li>APPTCHAIR - Name of the chair that this appointment is in (CHAIR.Name).<br/>

    *    <li>APPTDATE - Date of the appointment, as a string formatted MON DD YYYY (APPOINT.Date).<br/>

    *    <li>APPTTIME - Time of the appointment, as a string formatted HH:MI - HH:MI.<br/>

    * <li>APPTBOOKDATE - Date the appointment was created, as a string formatted MON DD YYYY (APPOINT.CreateDate).<p/>

    */

    PROCEDURE getprovtabdetail(IN vuserid integer, OUT vapptreason character varying, OUT results_cur cursor_pkg.weakcursor);

    

    /**

    * Procedure that returns the data to show in the provider details pane of the Providers subtabs.<p/>

    *

    * param: vProdId INPUT: ID of the producer/user (Producer.Producer)<p/>

    * param: results_cur OUTPUT: Weak cursor to contain the data retrieved<br/>

    */

    PROCEDURE getprodtabdetail(IN vprodid character varying, OUT results_cur cursor_pkg.weakcursor);

    

    -----------------------------------------------------------------------

    -- Messaging Tab

    -----------------------------------------------------------------------

 

    -----------------------------------------------------------------------

    -- Start Checks

    -----------------------------------------------------------------------

    

    /**

    * Procedure to retrieve the text that should be displayed to all users when performing start checks. Note: this

    *  text is defined in axiUm in Maint -> Basic tab -> Custom Text.<p/>

    *

    * param: vStartCheckText OUTPUT: String containing the text to be displayed.<p/>

    */    

    PROCEDURE getstartchecktext(OUT vstartchecktext character varying); 

    

    /**

    * Procedure to retrieve all warning and error conditions present that may prevent the logged-in user from performing a start check

    *  on a particular appointment. Returns these as a set of flags which are checked by the application to determine if a start check 

    *  should proceed.<p/>

    *

    * param: vInstructor INPUT: User ID of the logged-in user (USERS.User).<p/>

    * param: vAppointment INPUT: Appointment ID of the appointment to check (APPOINT.Appointment).<p/>

  * param: vStartCheckMinutes INPUT: Value for Start Check time before the scheduled appointment begins (original was 30 min). <p/>

    * param: vTiming OUTPUT: Flag indicating if its' too early or too late to do the start check (-1= too early, 0=within window, 1=too late).<p/>

    * param: vCanApprove OUTPUT: Flag indicating if the user has the ability to approve start checks (0= cannot approve, 1= can approve).<p/>

    * param: vCanApproveStartWithOutConsent OUTPUT: Flag indicating if the user has the ability to approve start checks w/out consent (0= cannot approve, 1= can approve).<p/>

    * param: vHasAccess OUTPUT: Flag indicating if the user has system access at this time, as setup in Power Admin -> Users -> Access Times (0=no access, 1=has access).<p/>

    * param: vAlreadyStartChecked OUTPUT: Flag indicating if this appointment has already been start checked (0=not start checked, 1+= User ID of last user to start check the appt).<p/>

    * param: vHasConsent OUTPUT: Flag indicating if the appointment contains treatments that the provider needs consent for and whether or not consent has been given (0=needs consent, and consent is missing, 1=needs consent, and has all consents, 2=doesn't require consent).<p/>

    * param: vPhaseOrder OUTPUT: Flag indicating if the appointment treatments are in or out of phase order, and whether or not the provider requires a phase order check (0=check req'd and out of phase, 1=check req'd and in phase, 2=check not req'd).<p/>

    * param: vIsRestrictedProv OUTPUT: Flag indicating if the appointment's provider is a restricted provider for the logged in user, as setup in Restricted Approvals (0=not restricted, 1=restricted).<p/>

    * param: vRestProvType OUTPUT: If the user is restricted for the provider, returns the provider's 1-character provider type.<p/>

    * param: vRestProvGroup OUTPUT: If the user is restricted for the provider, returns the provider's provider group code.<p/>

    * param: vIsRestrictedDisc OUTPUT: Flag indicating if the appointment treatments have disciplines that the logged in user is restricted from approving, as setup in Restricted Approvals (0=not restricted, 1=restricted).<p/>

    * param: vLastBlockedDisc OUTPUT: If the user is restricted on a discipline, returns the first discipline code found that was restricted.<p/>

    * param: vEarlyTimeToStartCheck OUTPUT: Early time the user can Start Check.<p/>

    * param: vMakeInactive OUTPUT: Inactive Status.<p/>

    */        

    PROCEDURE prestartchk(IN vinstructor integer, IN vappointment integer, IN vstartcheckminutes integer, OUT vtiming integer, OUT vcanapprove integer, OUT vcanapprovestartwithoutconsent integer, OUT vhasaccess integer, OUT valreadystartchecked integer, OUT vhasconsent integer, OUT vphaseorder integer, OUT visrestrictedprov integer, OUT vrestprovtype character varying, OUT vrestprovgroup character varying, OUT visrestricteddisc integer, OUT vlastblockeddisc character varying, OUT vearlytimetostartcheck integer, OUT vmakeinactive integer); -- 101044 -- AX-2489 -- AX-18744

            

    /**

    * Procedure to perform a start check. This procedure assumes that the user's ability to perform a start check has already been validated (via PreStartChk) and

    *  that it should be start checked by the logged-in user.<p/> 

    *

    * param: vInstructor INPUT: User ID of the logged-in user (USERS.User).<p/>

    * param: vAppointment INPUT: Appointment ID of the appointment to start check (APPOINT.Appointment).<p/>

    * param: vProviderUser INPUT: User ID of the appointment provider (USERS.User).<p/>

    * param: vPatient INPUT: Patient ID of the appointment patient (PATIENT.Patient).<p/>

    * param: vResult OUTPUT: Flag to indicate if the appointment was successfully start checked (0=yes,-1=error encountered).<p/>

    */            

    PROCEDURE dostartchk(IN vinstructor integer, IN vappointment integer, IN vprovideruser integer, IN vpatient integer, OUT vresult integer);

    

    /**

    * Function that checks whether or not an appointment has previously been start checked today.<p/>

    *

    * param: vAppointment INPUT: Appointment ID of the appointment to check (APPOINT.Appointment).<p/>

    * return: Value indicating whether or not the appointment has been start checked today (0=no start check, 1+=User ID of the last person to start check it).<p/>

    */    

    FUNCTION hasprevstartcheck(vappointment integer) RETURN integer; 

    

    /**

    * Function that checks whether or not a patient requires consent for treatment.<p/>

    *

    * param: vPatient INPUT: Patient ID of the appointment patient (PATIENT.Patient).<p/>

    * return: Flag indicating whether or not the patient requires consent (0=no, 1=yes).<p/>

    */    

    FUNCTION ptrequiresconsent(vpatientid integer) RETURN integer; 

    

    /**

    * Function that checks whether or not a provider requires consent to perform treatment.<p/>

    *

    * param: vProducer INPUT: Provider ID of the the provider (USERS.Producer).<p/>

    * return: Flag indicating whether or not the provider requires consent (0=no, 1=yes).<p/>

    */

    FUNCTION prodrequiresconsent(vproducer character) RETURN integer; 

    

    /**

    * Function that checks whether or not a procedure code requires patient consent.<p/>

    *

    * param: vProcCode INPUT: Procedure code of the procedure (PROCEDUR.Procedure). <p/>

    * return: Flag indicating whether or not the procedure requires consent (0=no, 1=yes).<p/>

    */    

    FUNCTION procrequiresconsent(vproccode character) RETURN integer; 

    

    /**

    * Function that checks whether or not the treatments on an appointment require consent, and if so, whether or not they have all been

    *  consented to by the patient.<p/>

    *

    * param: vAppointment INPUT: Appointment ID of the appointment to check (APPOINT.Appointment).<p/>

    * return: Flag indicating whether or not the appointment has been fully consented to (0=needs consent and one or more consents missing, 1=need consent, and has all consents, 2=no consent is needed).<p/>

    */    

    FUNCTION appthasptconsent(vappointment integer) RETURN integer; 

    

    /**

    * Function that checks whether or not the treatments on an appointment are in phase order or out of phase order. 

    *

    * param: vAppointment INPUT: Appointment ID of the appointment to check (APPOINT.Appointment).<p/>

    * return: Flag indicating what the phase order of the appointment treatments is (0=needs phase order, out of phase order, 1=needs phase order, in phase order, 2=phase check not req'd).<p/>

    */

    FUNCTION hascorrectphaseorder(vappointment integer) RETURN integer; 

    

    /**

    * Function that checks whether or not the appointment is within the correct window for start checks (window starts 30 mins before appointment, ends when appointment ends).<p/>

    *

    * param: vAppointment INPUT: Appointment ID of the appointment to check (APPOINT.Appointment).<p/>

  * param: vStartCheckMinutes For window starts, instead of fixed 30 minutes.<p/>

  * param: vEarlyTimeToStartCheck OUTPUT: Early time the user can Start Check.<p/>

    * return: Flag indicating if the appointment lies within the start check window (-1=too early, 0=within window, 1=too late).<p/>

    */

    FUNCTION withinstartchkwindow(vappointment integer, vstartcheckminutes integer, OUT vearlytimetostartcheck integer) RETURN integer;

    

    /**

    * Function that checks whether or not the logged-in user has system access at the current date/time as defined via PowerAdmin -> Users -> Access Times.<p/>

    *

    * param: vUser INPUT: User ID of the logged-in user (USERS.User).<p/>

    * return: Flag indicating if the user has system access at this time (0=no access, 1=has access).<p/>

    */    

    FUNCTION userhasaccess(vuser integer) RETURN integer;

    

    /**

    * Function that checks whether or not the logged-in user has the right to approve start checks.<p/>

    *

    * param: vInstructor INPUT: User ID of the logged-in user (USERS.User).<p/>

    * return: Flag indicating if the user is able to approve start checks (0=can't approve, 1=can approve).<p/>

    */    

    FUNCTION instructorcanappstartchks(vinstructor integer) RETURN integer;

    

    /**

    * Function that checks whether or not the logged-in user has the right to approve start checks without consent.<p/>

    *

    * param: vInstructor INPUT: User ID of the logged-in user (USERS.User).<p/>

    * return: Flag indicating if the user is able to approve start checks without consent(0=can't approve, 1=can approve).<p/>

    */    

    FUNCTION startchkswithoutconsent(vinstructor integer) RETURN integer;



    /**

    * Function that checks whether or not the logged-in user has restricted access to perform approvals for a particular provider or provider group.<p/>

    *

    * param: vInstructor INPUT: User ID of the logged-in user (USERS.User).<p/>

    * param: vProducer INPUT: Provider ID of the provider to check for (PRODUCER.Producer).<p/>

    * param: vPGroup INPUT: Provider group code to check for (PGROUP.PGroup).<p/>

    * return: Flag indicating if the user has restricted access for the provider or group (0=no restriction,1=restricted access).<p/>

    */        

    FUNCTION isinstrestrictprov(vinstructor integer, vproducer character, vpgroup character) RETURN integer; 

    

    /**

    * Procedure that checks whether or not the logged-in user has restricted access to perform approvals for the provider on a particular appointment.<p/>

    *

    * param: vInstructor INPUT: User ID of the logged-in user (USERS.User).<p/> 

    * param: vAppointment INPUT: Appointment ID of the appointment to check (APPOINT.Appointment).<p/>

    * param: vIsRestricted OUTPUT: Flag indicating if the user has restricted access for the appointment provider or their group (0=no restriction,1=restricted access).<p/>

    * param: vApptProvType OUTPUT: 1-character provider type code of the appointment provider.<p/>

    * param: vApptProvGroup OUTPUT: Provider group of the appointment provider.<p/> 

    */    

    PROCEDURE apptinstrestrictprov(IN vinstructor integer, IN vappointment integer, OUT visrestricted integer, OUT vapptprovtype character varying, OUT vapptprovgroup character varying); 

            

    /**

    * Function that checks whether or not the logged-in user has the right to approve start checks.<p/>

    *

    * param: vInstructor INPUT: User ID of the logged-in user (USERS.User).<p/>

    * param: vDiscipline INPUT: Discipline code to check. (DISCIPL.Discipline).<p/>

    * return: Flag indicating if the logged-in user has restricted approvals for that discipline (0=no restriction, 1=restricted access).<p/>

    */            

    FUNCTION isinstrestrictdisc(vinstructor integer, vdiscipline character) RETURN integer; 

    

    /**

    * Procedure that checked whether or not the logged-in user has restricted access to perform approvals for the treatment disciplines of the treatments on a particular appointment.<p/>

    *

    * param: vInstructor INPUT: User ID of the logged-in user (USERS.User).<p/> 

    * param: vAppointment INPUT: Appointment ID of the appointment to check (APPOINT.Appointment).<p/>

    * param: vIsRestricted OUTPUT: Flag indicating if the user has restricted access one or more of the disciplines of an appointment treatment (0=no restriction,1=restricted access).<p/>

    * param: vLastBlockedDisp OUTPUT: Discipline code of the first restricted discipline that this procedure encountered, if any.<p/>

    */    

    PROCEDURE apptinstrestrictdisc(IN vinstructor integer, IN vappointment integer, OUT visrestricted integer, OUT vlastblockeddisp character varying); 

  

  /**

  * Function to check if given criteria requires grading

  */

  FUNCTION requiregrading(vprovrequiregrading integer, vprocrequiregrading integer, vdiscipline character varying) RETURN integer;

  

    /**

    * Function that checks whether or not a particular treatment has been start checked today.<p/>

    *

    * param: vType INPUT: Type of the treatment being checked (APPTRX.Type).<p/>

    * param: vId INPUT: ID of the treatment being checked (APPTRX.Id).<p/>

    * param: vTreatment INPUT: Treatment # of the treatment being checked (APPTRX.Treatment).<p/>

    * return: Value indicating whether or not the appointment has been start checked today (0=no start check, 1+=User ID of the last person to start check it).<p/>

    */    

    FUNCTION hasprevstartchecktx(vappointment integer, vtype integer, vid integer, vtreatment integer, vprocedure character varying) RETURN integer; 

    

    /**

    * Function that checks whether or not an appointment contains any treatments that have not yet been start checked today.<p/>

    *

    * param: vAppointment INPUT: Appointment ID of the appointment to check (APPOINT.Appointment).<p/>

    * return: Count of the number of appointment treatments on the appointment that have not been start checked today.<p/>

    */    

    FUNCTION hasappttxmissingstartchk(vappointment integer) RETURN integer; 

  

  /**

  * Function that gets the latest start checked user for an appointment.<p/>

  *

  * param: vAppointment INPUT: Appointment ID of the appointment to check (APPOINT.Appointment).<p/>

  * return: User ID of the latest StartChecked user.<p/>

  */

    FUNCTION getapptstartchkuser(vappointment integer) RETURN integer;

	

    /**

    * Function that checks whether or not a trx has MakeInactive status.<p/>

    *

    * param: vAppointment INPUT: Appointment ID of the appointment to check (APPOINT.Appointment). <p/>

    * return: Flag indicating whether or not the trx has MakeInactive status (0=no, 1=yes).<p/>

    */        

	FUNCTION makeinactivetrx(vappointment integer) RETURN integer;

	

    /**

    * Function that returns the valur for MakeInactive field in Status table.<p/>

    *

    * param: vTxStatus INPUT: TxStatus  to check (APPOINT.Appointment). <p/>

    * return: Flag indicating value for MakeInactive in Status (0=no, 1=yes).<p/>

    */        	

	FUNCTION makeinactivestatus(vtxstatus character) RETURN integer;

	

    -----------------------------------------------------------------------

    -- Utility

    -----------------------------------------------------------------------

    

  /**

  * Procedure to get list of items the instuctor can approve FROM USERS<p/>

  * param: vInstructor INPUT: User ID of the instructor<p/>

  * param: results_cur OUTPUT: row containing following rows:<p/>

  * - ApprovePlanTx<p/>

  * - ApproveCompTx<p/>

  * - ApproveExistingTx<p/>

  * - ApproveNotes<p/>

  * - ApproveEHRForms<p/>

  * - ApproveProblems<p/>

  * - ApproveStartChks<p/>

  * - ApproveLetters<p/>

  * - ApprovePerio<p/>

  * - ApproveConditionTx<p/>

  */

  PROCEDURE getcanapprove(IN vinstructor integer, IN vstudent integer, OUT results_cur cursor_pkg.weakcursor);

  

  /**

  * Check if user can evaluate or not

  * param: vInstructor INPUT: user id of the instructor<p/>

  * param: vResult OUTPUT: result of the validation (0 = cannot evaluate, 1 = can evaluate)

  */

  PROCEDURE getcanevaluate(IN vinstructor integer, OUT vresult integer);

    

  /**

    * Procedure that retrieves the type and value of an FSETTING. The value of the FSETTING is converted by this procedure to the correct data type when returned. <p/>

    *

    * param: vUser INPUT: User ID that this FSETTING applies to (0=everyone, 1+= unique user ID (USERS.User)).<p/>

    * param: vKey INPUT: Unique key of the FSETTING to retrieve (FSETTING.Key).<p/>

    * param: vScope OUTPUT: Scope of the FSETTING (0=general, 1=user).<p/>

    * param: vType OUTPUT: Type of the FSETTING (-1=key not found, 0=text,1=number,2=date).<p/>

    * param: vTextVal OUTPUT: Value of the key, if it referenced a text type FSETTING. <p/>

    * param: vIntVal OUTPUT: Value of the key, if it referenced an integer type FSETTING. <p/>

    * param: vDateVal OUTPUT: Value of the key, if it referenced a date type FSETTING. <p/>

    * param: vShortDescription OUTPUT: Value of the short description. <p/>

    * param: vLongDescription OUTPUT: Value of the long description. <p/>

    * param: vDefaultValue OUTPUT: Value of the default value. <p/>

    * param: vRules OUTPUT: Value of the rules value. <p/>

    */

    PROCEDURE getfsetting(IN vuser integer, IN vkey character varying, OUT vscope integer, OUT vtype integer, OUT vtextval character varying, OUT vintval numeric, OUT vdateval timestamp without time zone, OUT vshortdescription character varying, OUT vlongdescription character varying, OUT vdefaultvalue character varying, OUT vrules character varying);

    

  /**

  * Procedure to change FSetting <p/>

  *

  * param: vUserId INPUT: User ID of the setting to change the value (0 = general, 1+ = FSETTING.User).<p/>

  * param: vKey INPUT: Key of the setting to change the value (FSETTING.Key).<p/>

  * param: vValue INPUT: Value of the setting (FSETTING.Value).<p/>

  */    

  PROCEDURE setfsetting(IN vuserid integer, IN vkey character varying, IN vvalue character varying);



  /**

  * Procedure to add FSetting <p/>

  *

  * param: vUserId INPUT: User ID (0 = general, 1+ = FSETTING.User).<p/>

  * param: vKey INPUT: Key of the setting (FSETTING.Key).<p/>

  * param: vSettingType INPUT: Setting type of the setting (0=Text, 1=Number, 2=Date).<p/>

  * param: vValue INPUT: Value of the setting (FSETTING.Value).<p/>

  * param: vScope INPUT: Scope of the setting (0=General, 1=User).<p/>

  */    

  PROCEDURE addfsetting(IN vuserid integer, IN vkey character varying, IN vsettingtype integer, IN vvalue character varying, IN vscope integer);

  

  /**

  * Add General FSetting

  */

  PROCEDURE addgeneralfsetting(IN vkey character varying, IN vscope integer, IN vtype integer, IN vshortdesc character varying, IN vlongdesc character varying, IN vdefaultvalue character varying, IN vrules character varying);



  /**

  * Procedure to delete FSetting <p/>

  * param: vUserId INPUT: User ID of setting to delete. <p/>

  * param: vKey INPUT: Key of setting to delete. <p/>

  */

  PROCEDURE deletefsetting(IN vuserid integer, IN vkey character varying);

  

  /**

  * Procedure to get a name of Practice

  * param: vPracticeId INPUT: ID of the practice PRACTICE.Id<p/>

  * param: vName OUTPUT: name of the practice PRACTICE.Name

  */

  PROCEDURE getpracticename(IN vpracticeid integer, OUT vname character varying);



  /**

  * Procedure to get list of practices

  * param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

  *    <li>Id - Numeric ID of the Practice. <br/>

  *    <li>Name - Name of the practice.<br/>

  */

  PROCEDURE getpractices(OUT results_cur cursor_pkg.weakcursor);

  

  /**

  * Procedure to check if the practice is a valid active practice. </p>

  * param: vPracticeId INPUT: Practice ID (PRACTICE."Id"). </p>

  * param: vInactive OUTPUT: State of practice ID (0=active, 1=inactive/none-valid). </p>

  */

  PROCEDURE checkpractice(IN vpracticeid integer, OUT vinactive integer);



  /**

  * Procedure to get default practice set in axiUm </p>

  * param: vStationID INPUT: station id to get default value from. </p>

  * param: vPracticeID OUTPUT: practice ID set in axiUm.</p>

  */

  PROCEDURE getdefaultpractice(IN vstationid integer, OUT vpracticeid integer);



    /**

  * Procedure to get the Country id for the practice

  * param: vPracticeId INPUT: Practice ID (PRACTICE."Id")

  * param: vCountryId OUTPUT: Country id

  */

  PROCEDURE getpracticecountry(IN vpracticeid integer, OUT vcountryid integer);



  /**

  * Procedure to get the axiUm Minimum Version for the practice

  * param: vVersion OUTPUT: version

  */

  PROCEDURE getpracticeminversion(OUT vversion character varying);

  

  /**

  * Procedure to get the axiUm Maximum Version for the practice

  * param: vVersion OUTPUT: version

  */

  PROCEDURE getpracticemaxversion(OUT vversion character varying);

  

    /**

    * Procedure that gets the station that a user is currently logged into. <p/>

    *

    * param: vUserId INPUT: User ID of the user to check (USERS.User).<p/>

    * param: vStation OUPUT: Station name of the station that the user is currently logged into, or null if not currently logged into axiUm.<p/>

    */    

    PROCEDURE getcurrentstnloc(IN vuserid integer, OUT vstation character varying); 

    

    /**

    * Procedure gets the current, next, or previous appointment for a provider for today. If the provider has an appointment at the current time, returns the current 

    *  appointment. Otherwise, returns the next appointment if the provider has an appointment scheduled later in the day, or the last appointment if there are no

    *  appointments scheduled later in the day and there was a previous appointment.<p/>

    *

    * param: vUserId INPUT: User ID of the provider to check (USERS.User).<p/>

    * param: vApptType OUTPUT: Type of the appointment being returned (-1=no appts found, 0=current appt, 1=next appt, 2=previous appt).<p/>

    * param: vAppoint OUTPUT: Appointment ID of the next/current/previous appointment, or null if no appointments today for the provider.<p/>

    */        

    PROCEDURE getcurrentapptloc(IN vuserid integer, OUT vappttype integer, OUT vappoint integer); 

    

    /**

    * Procedure to retrieve the picture data and format of a patient picture.<p/>

    *

    * param: vPatientId INPUT: Patient ID of the patient to get the picture for (PATIENT.Patient).<p/>

    * param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

    *    <li>FileExt - Format of the image, eg. 'jpg' (PICTURE.FileExt).<br/>

    *     <li>PICTURE - BLOB containing the picture data (PICTURE.PICTURE).<p/>

    */    

    PROCEDURE getpatientpicture(IN vpatientid integer, OUT results_cur cursor_pkg.weakcursor); 

    

    /**

    * Function to retrieve data about a particular patient and return it as a rec_PatientDetail RECORD type.<p/>

    *

    * param: vPatientId INPUT: Patient ID of the patient to fetch the data for (PATIENT.Patient).<p/>

    * return: rec_PatientDetail record containing the patient data.<p/>

    */    

    FUNCTION getpatientdetail(vpatientid integer) RETURN rec_patientdetail; -- 101765

    

    /**

    * Procedure to retrieve the picture data and format of a user picture.<p/>

    *

    * param: vUserId INPUT: User ID of the user to get the picture for (USERS.User).<p/>

    * param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

    *    <li>FileExt - Format of the image, eg. 'jpg' (UPICTURE.FileExt).<br/>

    *     <li>PICTURE - BLOB containing the picture data (UPICTURE.PICTURE).<p/>

    */

    PROCEDURE getuserpicture(IN vuserid integer, OUT results_cur cursor_pkg.weakcursor); 

    

    /**

    * Function to retrieve data about a particular user and return it as a rec_UserDetail RECORD type.<p/>

    *

    * param: vUserId INPUT: User ID of the user to fetch the data for (USERS.User).<p/>

    * return: rec_UserDetail record containing the user data.<p/>

    */    

    FUNCTION getuserdetail(vuserid integer) RETURN rec_userdetail;

  

    /**

    * Function to retrieve data about a particular provider and return it as a rec_UserDetail RECORD type.<p/>

    *

    * param: vProducer INPUT: Provider code of the user to fetch the data for (USERS.Producer).<p/>

    * return: rec_UserDetail record containing the user data.<p/>

    */

  FUNCTION getproviderdetail(vproducer character varying) RETURN rec_userdetail;

  

  /**

  * Procedure to retrieve Provider Type and Group.<p/>

  * param: vUser INPUT: USER ID.<br/>

  * return: results_cur OUTPUT: weak cursor containing:

  * <li>TypeCode - Provider Type Code <br/>

  * <li>PGroup - Provider Group <br/>

  */

  PROCEDURE getprovtypegroup(IN vuser integer, OUT results_cur cursor_pkg.weakcursor);

  /**

    * Function to retrieve name of user group by their key UGroup.<p/>

    *

    * param: vUGroup INPUT: UGroup."UGroup".<p/>

    * return: rec_UserDetail record containing the user data.<p/>

  */

    FUNCTION getugroupname(vugroup character) RETURN character varying;



    /**

    * Function to retrieve data about a particular appointment and return it as a rec_ApptDetail RECORD type.<p/>

    *

    * param: vApptId INPUT: Appointment ID of the appointment to fetch the data for (APPOINT.Appointment).<p/>

    * return: rec_ApptDetail record containing the appointment data.<p/>

    */        

    FUNCTION getapptdetail(vapptid integer) RETURN rec_apptdetail; 

    

    /**

    * Function to count the number of treatment notes that are attached to a particular treatment.<p/>

    *

    * param: vType INPUT: The type of the treatment (TRX.Type).<p/>

    * param: vId INPUT: The ID of the treatment (TRX.Id).<p/>

    * param: vTreatment INPUT: The treatment # of the treatment (TRX.Treatment).<p/>

    * return: Count of the number of treatment notes attached to the treatment.<p/>

    */    

    FUNCTION gettrxnotecount(vtype integer, vid integer, vtreatment integer) RETURN integer; 

    

    /**

    * Procedure to retrieve the names of the custom fields defined for treatments and notes via Maint -> Basic -> Custom Fields.<p/>

    *

    * param: vName1 OUTPUT: Name of the the Treatment(Clinical1) field.<p/>

    * param: vName2 OUTPUT: Name of the the Treatment(Clinical2) field.<p/>

    * param: vName3 OUTPUT: Name of the the Treatment/Note1 field.<p/>

    * param: vName4 OUTPUT: Name of the the Treatment/Note2 field.<p/>

    */    

    PROCEDURE getcustomfieldnames(OUT vname1 character, OUT vname2 character, OUT vname3 character, OUT vname4 character); 

    

    /**

    * Procedure to retrieve the ValidateField and RequiredField of the custom fields defined for treatments and notes via Maint -> Basic -> Custom Fields.<p/>

    *

    * param: vType INPUT: Type Id field.<p/>

    */    

    PROCEDURE getcustomvalidaterequired(IN vtype integer, OUT results_cur cursor_pkg.weakcursor);



    /**

    * Procedure to retrieve the custom codes for a specific vType.<p/>

    *

    * param: vType INPUT: Type Id field.<p/>

    * param: results_cur OUTPUT: Weak cursor to contain the data retrieved.</p>

    */    

    PROCEDURE getcustomcodes(IN vtype integer, OUT results_cur cursor_pkg.weakcursor);



    /**

    * Function to retrieve data about a particular treatment and return it as a rec_TxDetail RECORD type.<p/>

    *

    * param: vChartTrx INPUT: ID for the CHARTLNK row associated with this treatment (unapproved = CHARTLNK.Previous, approved = TRX.ChartTrx)<p/>

    * param: vType INPUT: Flag indicating if this treatment is approved or not approved (0=not approved, 1=approved)<p/>

    * return: rec_TxDetail record containing the treatment data.<p/>

    */    

    FUNCTION gettreatmentdetail(vcharttrx integer, vchartlnk integer, vtype integer) RETURN rec_txdetail; 

    

    /**

    * Function to retrieve data about a particular note (general or template) and return it as a rec_NoteDetail RECORD type.<p/>

    *

    * param: vAuto INPUT: ID for the note (NOTES2.Auto).<p/>

    * param: vCountryName INPUT: Name of country.<p/>

    * return: rec_NoteDetail record containing the note data.<p/>

    */    

    FUNCTION getnotedetail(vauto integer, vcountryname character varying) RETURN rec_notedetail; 

    

    /**

    * Function to retrieve data about a particular note (SOAP) and return it as a rec_SOAPNoteDetail RECORD type.<p/>

    *

    * param: vOtherId INPUT: ID for the SOAP note (NOTES2.OtherId).<p/>

    * param: vCountryName INPUT: Name of country.<p/>

    * return: rec_SOAPNoteDetail record containing the note data.<p/>

    */

    FUNCTION getsoapnotedetail(votherid integer, vcountryname character varying) RETURN rec_soapnotedetail;

    

    /**

    * Function that checks if a treatment needs consent, and if it has been consented to.<p/>

    *

    * param: vType INPUT: Type of the treatment (TRX.Type).<p/>

    * param: vId INPUT: ID of the treatment (TRX.Id).<p/>

    * param: vTreatment INPUT: Treatment # of the treatment (TRX.Treatment).<p/>

  * param: vPatient INPUT: Patient ID.<p/>

  * param: vProducer INPUT: Producer Code.<p/>

  * param: vProcedure INPUT: Procedure Code.<p/>

    * return: Flag indicating if the treament has/needs consent (0=need consent and don't have it, 1=either don't need consent or have consent).<p/>

    */    

    FUNCTION txhasreqconsent(vtype integer, vid integer, vtreatment integer, vpatient integer, vproducer character, vprocedure character, vsite character) RETURN integer; 

    

    /**

    * Function that checks if planned procedure (dummy appt tx) needs consent, and if it has been consented to.<p/>

    *

    * return: Flag indicating if the planned procedure has/needs consent (0=need consent and don't have it, 1=either don't need consent or have consent).<p/>

    */    

    FUNCTION plannedprochasreqconsent(vpatient integer, vproducer character, vprocedure character) RETURN integer;

    

    /**

    * Function to retrieve data about a particular finding (condition or material) and return it as a rec_FindingDetail RECORD type.<p/>

    *

    * param: vAuto INPUT: ID of the finding to get the details for (TREATME2.Auto).<p/>

    * param: vType INPUT: Flag indicating if the finding is approved or unapproved (0=unapproved, 1=approved).<p/>

    * return: rec_FindingDetail record containing the finding data.<p/>

    */

    FUNCTION getfindingdetail(vauto integer, vchartlnk integer, vtype integer) RETURN rec_findingdetail;

    

  

  /**

  * Function to retrieve data about a particular form and return it as a rec_FormDetail RECORD type.<p/>

  *

  * param: vPForm INPUT: ID of the finding to get the details for.<p/>

  * return: rec_FormDetail record containing the form data.<p/>

  */

  FUNCTION getformdetail(vpform integer) RETURN rec_formdetail;

  

  /**

  * Function to retrieve data about a particular Perio and return it as a rec_PerioDetail RECORD type.<p/>

  *

  * param: vPtPerio INPUT: ID of the perio to get the details for.<p/>

  * return: rec_PerioDetail record containing the perio data.<p/>

  */

  FUNCTION getperiodetail(vptperio integer) RETURN rec_periodetail;

  

  /**

  * Function to retrieve data about a particular Letter and return it as a rec_LetterDetail RECORD type.<p/>

  *

  * param: vPtLetter INPUT: ID of the letter to get the details for.<p/>

  * return: rec_LetterDetail record containing the letter data.<p/>

  */

  FUNCTION getletterdetail(vptletter integer) RETURN rec_letterdetail;

  

  /**

  * Procedure to retrieve list of diagnoses associated with a treatement<p/>

  * param: vChartTrx INPUT: ID for approved treatments TRX.ChartTrx<p/>

  * param: vChartLnk INPUT: ID for unapproved treatments CHARTLNK.Auto<p/>

  * param: vType INPUT: Flag indicating if this treatment is approved or not approved (0 = unapproved with trx record, 1 = approved, 2 = unapproved with no trx record)<p/>

  * param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

  *    <li>Description - Diagnosis description (DIAGCODE.Description).<br/>

  */

  PROCEDURE getdiagnosesfortreatment(IN vcharttrx integer, IN vchartlnk integer, IN vtype integer, OUT results_cur cursor_pkg.weakcursor);

  

  /**

  * 35485977 Procedure to retrieve Missing Consents Codes with a treatement<p/>

  * param: vChartTrx INPUT: ID for approved treatments TRX.ChartTrx<p/>

  * param: vChartLnk INPUT: ID for unapproved treatments CHARTLNK.Auto<p/>

  * param: vType INPUT: Flag indicating if this treatment is approved or not approved (0 = unapproved with trx record, 1 = approved, 2 = unapproved with no trx record)<p/>

  * param: results OUTPUT: VARCHAR2 with Missing Consent Codes Separated by commas<br/>

  */

  PROCEDURE getconsentcodesfortrx(IN vcharttrx integer, IN vchartlnk integer, IN vtype integer, OUT results character varying);    



  /**

  * 35485977 Procedure to retrieve Missing Consents Codes with a treatement<p/>

  * param: vMissingCodes INPUT: VARCHAR2 with Missing Consent Codes Separated by commas<p/>

  * param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

  *    <li>Consent - Consent Code (CONSENT.Consent).<br/>

  *    <li>Description - Consent description (CONSENT.Description).<br/>

  */

  PROCEDURE getconsentlistfortrx(IN vmissingcodes character varying, OUT results_cur cursor_pkg.weakcursor);    



    /**

    * Procedure that retrieves the details for a treatment line (in Appt tab or Provider tab).<p/>

    *

    * param: vChartTrx INPUT: ID for the CHARTLNK row associated with this treatment (unapproved = CHARTLNK.Previous, approved = TRX.ChartTrx)<p/>

    * param: vChartLnk INPUT: ID for the CHARTLNK row (unapproved = CHARTLNK.Id, approved = TRX.ChartTrx)<p/>

    * param: vType INPUT: Flag indicating if this treatment is approved or not approved (0=not approved, 1=approved)<p/>

    * param: vDescription OUTPUT: String containing the line description, returned outside cursor for safety.<p/>

    * param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

    *    <li>Discipline - Treatment discipline code (TRX.Discipline).<br/>

    *    <li>Diagnosis - Treatment diagnosis code (TRX.DiagCode).<br/>

    *    <li>Phase - Treatment phase (TRX.Phase).<br/>

    *    <li>Sequence - Treatment sequence (TRX.Seq).<br/>

    *    <li>Custom1Name - Name of the first custom field.<br/>

    *    <li>Custom1Val - Value of the first custom field.<br/>

    *    <li>Custom2Name - Name of the second custom field.<br/>

    *    <li>Custom2Val - Value of the second custom field.<br/>

    *    <li>Custom3Name - Name of the third custom field.<br/>

    *    <li>Custom3Val - Value of the third custom field.<br/>

    *    <li>Custom4Name - Name of the fourth custom field.<br/>

    *    <li>Custom4Val - Value of the fourth custom field.<br/>

    *    <li>PatientName - Name of the patient for this treatment, as a string formatted like 'F. LastName'.<br/>

    *    <li>EntryUserName - Name of the entry user for this treatment, as a string formatted like 'F. LastName'.<br/>

    *    <li>EntryDate - Entry/modified date for this treatment, as a string formatted like 'MON DD, YYYY'.<br/>

    *    <li>AppUserName - Name of the approval user for this treatment, as a string formatted like 'F. LastName'.<br/>

    *    <li>AppDate - Approval date for this treatment, as a string formatted like 'MON DD, YYYY'.<br/>

    *    <li>Status - Status of the treatment, eg P, I C, P*, I*.<br/>

    *    <li>Site - Tooth number for the treatment (TRX.Site).<br/>

    *    <li>Surface - Surfaces for the treatment (TRX.Surface).<p/> 

    */

    PROCEDURE getlinedetailtreatment(IN vcharttrx integer, IN vchartlnk integer, IN vtype integer, OUT vdescription character varying, OUT vorthonote character varying, OUT results_cur cursor_pkg.weakcursor);

    

    /**

    * Procedure that retrieves the details for a note (general or template) line (in Appt tab or Provider tab).<p/>

    *

    * param: vAuto INPUT: ID of the note (NOTES2.Auto).<p/>

    * param: vCountryName INPUT: Name of country.<p/>

    * param: vNoteText OUTPUT: The text of the note, returned outside cursor for safety (NOTES2.Text).<p/>

    * param: vDescription OUTPUT: String containing the line description, returned outside cursor for safety.<p/>

    * param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

    *    <li>Phase - Note phase (TRX.Phase).<br/>

    *    <li>Sequence - Note sequence (TRX.Seq).<br/>

    *    <li>Custom1Name - Name of the first custom field.<br/>

    *    <li>Custom1Val - Value of the first custom field.<br/>

    *    <li>Custom2Name - Name of the second custom field.<br/>

    *    <li>Custom2Val - Value of the second custom field.<br/>

    *    <li>NoteCode - Note code for the note (NOTES2.Code).<br/>

    *    <li>PatientName - Name of the patient for this note, as a string formatted like 'F. LastName'.<br/>

    *    <li>EntryUserName - Name of the entry user for this note, as a string formatted like 'F. LastName'.<br/>

    *    <li>EntryDate - Entry/modified date for this note, as a string formatted like 'MON DD, YYYY'.<br/>

    *    <li>AppUserName - Name of the approval user for this note, as a string formatted like 'F. LastName'.<br/>

    *    <li>AppDate - Approval date for this note, as a string formatted like 'MON DD, YYYY'.<br/>

    *    <li>Site - Tooth number for the note (TRX.Site).<p/>

    */    

    PROCEDURE getlinedetailnote(IN vauto integer, IN vcountryname character varying, OUT vnotetext character varying, OUT vdescription character varying, OUT results_cur cursor_pkg.weakcursor);

    

    /**

    * Procedure that retrieves the details for a note (SOAP) line (in Appt tab or Provider tab).<p/>

    *

    * param: vOtherId INPUT: ID of the SOAP note (NOTES2.OtherId).<p/>

    * param: vCountryName INPUT: Name of country.<p/>

    * param: vNoteTextS OUTPUT: The 'Subjective' text of the note, returned outside cursor for safety (NOTES2.Text).<p/>

    * param: vNoteTextO OUTPUT: The 'Objective' text of the note, returned outside cursor for safety (NOTES2.Text).<p/>

    * param: vNoteTextA OUTPUT: The 'Assessment' text of the note, returned outside cursor for safety (NOTES2.Text).<p/>

    * param: vNoteTextP OUTPUT: The 'Planned' text of the note, returned outside cursor for safety (NOTES2.Text).<p/>

    * param: vDescription OUTPUT: String containing the line description, returned outside cursor for safety.<p/>

    * param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

    *    <li>Phase - Note phase (TRX.Phase).<br/>

    *    <li>Sequence - Note sequence (TRX.Seq).<br/>

    *    <li>Custom1Name - Name of the first custom field.<br/>

    *    <li>Custom1Val - Value of the first custom field.<br/>

    *    <li>Custom2Name - Name of the second custom field.<br/>

    *    <li>Custom2Val - Value of the second custom field.<br/>

    *    <li>NoteCode - Note code for the note (NOTES2.Code).<br/>

    *    <li>PatientName - Name of the patient for this note, as a string formatted like 'F. LastName'.<br/>

    *    <li>EntryUserName - Name of the entry user for this note, as a string formatted like 'F. LastName'.<br/>

    *    <li>EntryDate - Entry/modified date for this note, as a string formatted like 'MON DD, YYYY'.<br/>

    *    <li>AppUserName - Name of the approval user for this note, as a string formatted like 'F. LastName'.<br/>

    *    <li>AppDate - Approval date for this note, as a string formatted like 'MON DD, YYYY'.<br/>

    *    <li>Site - Tooth number for the note (TRX.Site).<p/>

    */        

    PROCEDURE getlinedetailsoapnote(IN votherid integer, IN vcountryname character varying, OUT vnotetexts character varying, OUT vnotetexto character varying, OUT vnotetexta character varying, OUT vnotetextp character varying, OUT vdescription character varying, OUT results_cur cursor_pkg.weakcursor);

    

    /**

    * Procedure that retrieves the details for a finding line (in Appt tab or Provider tab).<p/>

    *

    * param: vAuto INPUT: ID for the TREATME2 row associated with this finding (TREATME2.Auto).<p/>

    * param: vType INPUT: Flag indicating if this treatment is approved or not approved (0=not approved, 1=approved)<p/>

    * param: vDescription OUTPUT: String containing the line description, returned outside cursor for safety.<p/>

    * param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

    *    <li>PatientName - Name of the patient for this treatment, as a string formatted like 'F. LastName'.<br/>

    *    <li>EntryUserName - Name of the entry user for this treatment, as a string formatted like 'F. LastName'.<br/>

    *    <li>EntryDate - Entry/modified date for this treatment, as a string formatted like 'MON DD, YYYY'.<br/>

    *    <li>AppUserName - Name of the approval user for this treatment, as a string formatted like 'F. LastName'.<br/>

    *    <li>AppDate - Approval date for this treatment, as a string formatted like 'MON DD, YYYY'.<br/>

    *    <li>Status - Status of the treatment, eg P, I C, P*, I*.<br/>

    *    <li>Site - Tooth number for the treatment (TRX.Site).<br/>

    *    <li>Surface - Surfaces for the treatment (TRX.Surface).<p/> 

    */

    PROCEDURE getlinedetailfinding(IN vauto integer, IN vchartlnk integer, IN vtype integer, OUT vdescription character varying, OUT results_cur cursor_pkg.weakcursor);

    

  /**

  * Procedure that retrieves the details for a finding line (in Appt tab or Provider tab).<p/>

  *

  * param: vAuto INPUT: ID for the TREATME2 row associated with this finding (TREATME2.Auto).<p/>

  * param: vType INPUT: Flag indicating if this treatment is approved or not approved (0=not approved, 1=approved)<p/>

  * param: vDescription OUTPUT: String containing the line description, returned outside cursor for safety.<p/>

  * param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

  *    <li>PatientName - Name of the patient for this treatment, as a string formatted like 'F. LastName'.<br/>

  *    <li>EntryUserName - Name of the entry user for this treatment, as a string formatted like 'F. LastName'.<br/>

  *    <li>EntryDate - Entry/modified date for this treatment, as a string formatted like 'MON DD, YYYY'.<br/>

  *    <li>AppUserName - Name of the approval user for this treatment, as a string formatted like 'F. LastName'.<br/>

  *    <li>AppDate - Approval date for this treatment, as a string formatted like 'MON DD, YYYY'.<br/>

  *    <li>Status - Status of the treatment, eg P, I C, P*, I*.<br/>

  *    <li>Site - Tooth number for the treatment (TRX.Site).<br/>

  *    <li>Surface - Surfaces for the treatment (TRX.Surface).<p/> 

  */

    PROCEDURE getlinedetailform(IN vpform integer, OUT vdescription character varying, OUT vugroup character varying, OUT results_cur cursor_pkg.weakcursor);

  

  /**

  * Procedure that retrieves the details for a perio line (in Appt tab or Provider tab).<p/>

  *

  * param: vPtPerio INPUT: ID for the PTPERIO row associated with this Perio.<p/>

  * param: vDescription OUTPUT: String containing the line description, returned outside cursor for safety.<p/>

  * param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

  *    <li>Date - Date of the perio<br/>

  *    <li>Status - Status of the perio<br/>

  *    <li>ProviderType - Provider Type.<br/>

  *    <li>PatientName - Patient Name.<br/>

  *    <li>PatientAgeSex - Patient's Age and Sex in code.<br/>

  *    <li>EntryUserName - Entry User's name.<br/>

  *    <li>EntryDate - Date of Entry.<br/>

  *    <li>AppUserName - Approved user's name.<p/> 

  *    <li>AppDate - Approved date.<p/> 

  */

  PROCEDURE getlinedetailperio(IN vptperio integer, OUT vdescription character varying, OUT results_cur cursor_pkg.weakcursor);

  

  /**

  * Procedure that retrieves the details for a letter line (in Appt tab or Provider tab).<p/>

  *

  * param: vPtLetter INPUT: ID for the PTLETTER row associated with this Perio.<p/>

  * param: vDescription OUTPUT: String containing the line description, returned outside cursor for safety.<p/>

  * param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

  *    <li>Date - Date of the letter<br/>

  *    <li>Status - Status of the letter<br/>

  *    <li>FileType - Type of Letter<br/>

  *    <li>PatientName - Patient Name.<br/>

  *    <li>PatientAgeSex - Patient's Age and Sex in code.<br/>

  *    <li>PatientChart - Patient Chart.<br/>

  *    <li>EntryUserName - Entry User's name.<br/>

  *    <li>EntryDate - Date of Entry.<br/>

  *    <li>AppUserName - Approved user's name.<p/> 

  *    <li>AppDate - Approved date.<p/> 

  */

  PROCEDURE getlinedetailletter(IN vptletter integer, OUT vdescription character varying, OUT results_cur cursor_pkg.weakcursor);

  /**

    * Function that creates an audit history and returns the ID of the created AUDITHIS record.<p/>

    *

    * param: vAuditUser INPUT: User ID of the user that the audit history is for (USERS.User).<p/>

    * param: vAuditTable INPUT: Name of the table that this audit history is for.<p/>

    * param: vHistoryType INPUT: Type of the audit history (0=undefined, 1=add, 2=edit, 4=delete).<p/>

    * return: Audit ID of the AUDITHIS row that was inserted (AUDITHIS.Audit).<p/>

    */    

    FUNCTION addaudithis(vaudituser integer, vaudittable character varying, vhistorytype integer) RETURN integer; 

    

  /*

    * Procedure to perform a Note Approval.<p/> 

    *

  * param: vAuto INPUT: ID of NOTES2 to approve (NOTES2.Auto).<p/>

    * param: vInstructor INPUT: User ID of the logged-in user (USERS.User).<p/>

  * param: vResult OUTPUT: Flag to indicate if the note was successfully approved (0=yes,-1=error encountered).<p/>

  */

  PROCEDURE doapprovenotes(IN vauto integer, IN vinstructor integer, OUT vresult integer);

  

  /**

  * Procedure to perform a SOAP Note approval.<p/>

  *

  * param: vOtherId INPUT: ID shared by a set of SOAP notes to approve (NOTES2.OtherId).<p/>

  * param: vInstructor INPUT: User ID of the logged-in user.<p/>

  * param: vResult OUTPUT: Flag to indicate if the SOAP note was successfully approved (0=yes, -1=error encountered).<p/>

  */

  PROCEDURE doapprovesoapnotes(IN votherid integer, IN vinstructor integer, OUT vresult integer);

  

  /**

  * Procedure to perform a Condition approval (Status A).<p/>

  *

  * param: vChartLnk INPUT: ChartLnk ID of the condition (CHARTLNK.Id).<p/>

  * param: vAuto INPUT: ID of TREATME2.Auto.<p/>

  * param: vInstructor INPUT: User ID of the logged-in user.<p/>

  * param: vResult OUTPUT: Flag to indicate if the condition was successfully approved (0=yes, -1=error encountered).<p/>

  */

  PROCEDURE doapproveconditions(IN vchartlnk integer, IN vauto integer, IN vinstructor integer, OUT vresult integer);

  

  /**

  * Procedure to perform a Findings approval (Status A).<p/>

  *

  * param: vChartLnk INPUT: ChartLnk ID of the finding (CHARTLNK.Id).<p/>

  * param: vAuto INPUT: ID of TREATME2.Auto.<p/>

  * param: vInstructor INPUT: User ID of the logged-in user.<p/>

  * param: vResult OUTPUT: Flag to indicate if the finding was successfully approved (0=yes, -1=error encountered).<p/>

  */

  PROCEDURE doapprovefindings(IN vchartlnk integer, IN vauto integer, IN vinstructor integer, OUT vresult integer);

  

  /**

  * Procedure to perform validation for a Form

  *

  * param: vFormCode INPUT: PITEM.FormCode.<p/>

  * param: vPatient INPUT: PITEM.Patient.<p/>

  * param: vInstructor INPUT: User ID approving the form (PITEM.AppUser).<p/>

  * param: vCanApprove OUTPUT: Flag to indicate if the form can be approved (1=yes, 0=no).<p/>

  * param: vRequiredBlank OUTPUT: Number of required answers not yet answered.<p/>

  */

  PROCEDURE preapproveforms(IN vformcode character varying, IN vpform integer, IN vpatient integer, IN vinstructor integer, OUT vcanapprove integer, OUT vrequiredblank integer);

  

  /**

  * Procedure to add all Alerts (alert, allergies, and medical problems) and Needs

    * for a patient item, if they are missing on approving an answer.

    * If validation checks out, calls AddPtAlert procedure.

  *

  * param: vPatientItemId INPUT: PITEM.PItem.<p/>

  * param: vInstructorId INPUT: USERS.User.<p/>

  */

  PROCEDURE addalertsandneeds(IN vpatientitemid numeric, IN vinstructorid numeric);

  

  /**

  * Procedure to add an alert.

    * Checks smoke status, adds audit history and patient item records

  *

  * param: vMedAlert INPUT: PTALERT.MedAlert.<p/>

  * param: vAlertType INPUT: PTALERT.AlertType. 0 = clinical alert, 1 = allergy, 2 = medical problem<p/>

  * param: vPatient INPUT: PTALERT.Patient.<p/>

  * param: vUser INPUT: User entering the data (approving user). PTALERT.User.<p/>

  */

  PROCEDURE addptalert(IN vmedalert integer, IN valerttype integer, IN vpatient integer, IN vuser integer);

  

  /**

  * Procedure to delete an alert.

  *

  * param: vPtAlert INPUT: PTALERT.PtAlert.<p/>

  * param: vUser INPUT: User entering the data (approving user). PTALERT.User.<p/>

  */

    PROCEDURE deleteptalert(IN vptalert integer, IN vuser integer);

  

  /**

  * Procedure to get user associated with the ticket for Faculty Portal

  * param: vFormCode INPUT: PITEM.FormCode.<p/>

  * param: vPatient INPUT: PITEM.Patient.<p/>

  * param: results_cur OUTPUT: Medical problem (PTALERT) row.

  *  

  */

  PROCEDURE getmedproblemstodeletefromform(IN vformcode character varying, IN vpform integer, IN vpatient integer, OUT results_cur cursor_pkg.weakcursor);

  

  /**

  * Procedure to get user associated with the ticket for Faculty Portal

  * param: vFormCode INPUT: PITEM.FormCode.<p/>

  * param: vPatient INPUT: PITEM.Patient.<p/>

  * param: results_cur OUTPUT: Allergy (PTALERT) row.

  *  

  */

  PROCEDURE getallergiestodeletefromform(IN vformcode character varying, IN vpform integer, IN vpatient integer, OUT results_cur cursor_pkg.weakcursor);

  

  /**

  * Procedure to get user associated with the ticket for Faculty Portal

  * param: vFormCode INPUT: PITEM.FormCode.<p/>

  * param: vPatient INPUT: PITEM.Patient.<p/>

  * param: results_cur OUTPUT: Alert (PTALERT) row.

  *  

  */

  PROCEDURE getalertstodeletefromform(IN vformcode character varying, IN vpform integer, IN vpatient integer, OUT results_cur cursor_pkg.weakcursor);

  

    /**

    * Procedure to add a need.

    * Adds audit history and patient item records

    *

    * param: vNeedCode INPUT: PTNEED.NeedCode.<p/>

    * param: vPatient INPUT: PTNEED.Patient.<p/>

    * param: vUser INPUT: User entering the data (approving user). PTNEED.User.<p/>

    */

    PROCEDURE addptneed(IN vneedcode character, IN vpatient integer, IN vuser integer);

    

  /**

  * Procedure to delete a need.

  *

  * param: vPtNeed INPUT: PTNEED.PtNeed.<p/>

  * param: vUser INPUT: User entering the data (approving user). PTNEED.User.<p/>

  */

    PROCEDURE deleteptneed(IN vptneed integer, IN vuser integer);

    

  /**

  * Procedure to get user associated with the ticket for Faculty Portal

  * param: vFormCode INPUT: PITEM.FormCode.<p/>

  * param: vPatient INPUT: PITEM.Patient.<p/>

  * param: results_cur OUTPUT: Need (PTNEED) row.

  *  

  */

  PROCEDURE getneedstodeletefromform(IN vformcode character varying, IN vpform integer, IN vpatient integer, OUT results_cur cursor_pkg.weakcursor);

  

  

  

  /**

  * Procedure to perform a Form approval

  *

  * param: vFormCode INPUT: PITEM.FormCode.<p/>

  * param: vPForm INPUT: PITEM.PForm.<p/>

  * param: vPatient INPUT: PITEM.Patient.<p/>

  * param: vInstructor INPUT: User ID approving the form (PITEM.AppUser).<p/>

  * param: vResult OUTPUT: Flag to indicate if the finding was successfully approved (0=yes, -1=error encountered).<p/>

  */

  PROCEDURE doapproveforms(IN vformcode character varying, IN vpform integer, IN vpatient integer, IN vinstructor integer, OUT vresult integer);

  

  /**

  * Procedure to perform a Perio Approval.<p/>

  *

  * param: vPtPerio INPUT: Perio ID (PTPERIO.PtPerio).<p/>

  * param: vInstructor INPUT: User ID of the logged-in user.<p/>

  * param: vResult OUTPUT: Flag to indicate if the finding was successfully approved (0=yes, -1=error encountered).<p/>

  */

  PROCEDURE doapproveperio(IN vptperio integer, IN vinstructor integer, OUT vresult integer);



  /**

  * Procedure to perform a Letter Approval.<p/>

  *

  * param: vPtLetter INPUT: Letter ID (PTLETTER.PtLetter).<p/>

  * param: vInstructor INPUT: User ID of the logged-in user.<p/>

  * param: vResult OUTPUT: Flag to indicate if the finding was successfully approved (0=yes, -1=error encountered).<p/>

  */

  PROCEDURE doapproveletter(IN vptletter integer, IN vinstructor integer, OUT vresult integer);



  

  /**

  * Helper function to validate and get full procedure name

  * param: vCode INPUT: Procedure name<p/>

  * return: procedure name if the procedure is valid, if not return 'Procedure Code - Not on File'

  */

  FUNCTION getprocedurename(vcode character varying) RETURN character varying;

  

  /**

  * Helper function to get session time of the appointment

  * param: vAppoint INPUT: ID of appointment

  * return: ID of clinic time CLINICT."ClinicTime"

  */

  FUNCTION getclinictime(vappoint integer) RETURN integer;



  /**

  * Gets all the clinic the user has access to

  * param: vUserId INPUT: User ID<p/>

  * return: results_cur OUTPUT: list of clinics with Clinic ID and description<p/>

  */

  PROCEDURE getcliniclist(IN vuserid integer, OUT results_cur cursor_pkg.weakcursor);



  /**

  * Gets name of the clinic

  * param: vClinic INPUT: Clinic ID<p/>

  * return: vDescription OUTPUT: Clinic description<p/>

  */

  PROCEDURE getclinicname(IN vclinic integer, OUT vdescription character varying);

  

  /**

  * Gets name of the clinic

  * param: vClinic INPUT: Clinic ID<p/>

  * return: vDescription OUTPUT: Clinic description<p/>

  */

  PROCEDURE getclinictimename(IN vclinictime integer, OUT vdescription character varying);



  /**

  * Gets sessions for a clinic

  * param: vClinic INPUT: Clinic ID<p/>

  * return: results_cur OUTPUT: List of sessions for the clinic<p/>

  */

  PROCEDURE getclinictimelist(IN vclinic integer, OUT results_cur cursor_pkg.weakcursor);



  /**

  * AX-25304 Gets Inactive of the clinic

  * param: vClinic INPUT: Clinic ID<p/>

  * return: vInactive OUTPUT: Clinic Inactive flag<p/>

  */

  PROCEDURE getclinicinactive(IN vclinic integer, OUT vinactive integer);





  /**

  * Helper function that returns all clinics a provider belongs to

  * param: vProviderId INPUT: Provider ID

  */

  FUNCTION getproviderclinics(vproducer character varying) RETURN character varying;

  

  /**

  * Helper function that returns all clinic Times a provider belongs to

  * param: vProviderId INPUT: Provider ID

  */

  FUNCTION getproviderclinictimes(vproducer character varying) RETURN character varying;

  

  /**

  * Gets active provider group list

  * return: results_cur OUTPUT: list of provider groups<p/>

  */

  PROCEDURE getprovidergrouplist(OUT results_cur cursor_pkg.weakcursor);



  /**

  * Gets provider type list

  * return: results_cur OUTPUT: list of provider types<p/>

  */

  PROCEDURE getprovidertypelist(OUT results_cur cursor_pkg.weakcursor);

  

  /**

  * Get rows of Treatments that are linked together with supplied vChartLnk

  * param: vChartLnk INPUT: CHARTLNK."Id"<p/>

  * return: results_cur OUTPUT: List of treatements that are bridged<p/>

  */

  PROCEDURE getbridgetreatments(IN vchartlnk integer, OUT results_cur cursor_pkg.weakcursor);





  /**

  * Get all ChartLnk that are linked with supplied vChartLnk sorted by Status Desc, TxDate Asc and Id Asc

  * param: vChartLnk INPUT: List of Ids <p/>

  * return: results_cur OUTPUT: List of treatements that are bridged<p/>

  */

  PROCEDURE getchartlnks(IN vchartlnk character varying, OUT results_cur cursor_pkg.weakcursor);

  

  /**

  * Helper function that gets Surface for NOTES

  * param: vSite: Site ID<p/>

  * param: vSurface: Surface Code<p/>

  * return: VARCHAR2 of proper matching Surface code<p/>

  */

  FUNCTION getsurface(vsite character varying, vsurface integer) RETURN character varying;

  

  /**

  * Procedure to get Instructor Detail

  * return: weakcursor<p/>

  */

  PROCEDURE getinstructordetail(IN vuser integer, OUT results_cur cursor_pkg.weakcursor);



  /**

  * Procedure to get providerDetails

  * return: weakcursor<p/>

  */

  PROCEDURE getprovdetail(IN vuser integer, OUT results_cur cursor_pkg.weakcursor);

  

  /**

  * Procedure to get provider detail from Producer code

  * return: provider row

  */

  PROCEDURE getprovdetailwithcode(IN vproducer character varying, OUT results_cur cursor_pkg.weakcursor);



  /**

  * Procedure to get patient detail

  * return: patient row

  */

  PROCEDURE getpatient(IN vpatient integer, OUT results_cur cursor_pkg.weakcursor);



  /**

  * Procedure to get discipline List for Sessional evaluations

  * return: Discipline PK and Description<p/>

  */

  PROCEDURE getevaldiscipllist(IN vyear integer, OUT results_cur cursor_pkg.weakcursor);



  /**

  * Procedure to get Template List for Sessional evaluations

  * return: Template PK and Description<p/>

  */

  PROCEDURE getevaltemplatelist(IN vlevel integer, OUT results_cur cursor_pkg.weakcursor);

  

  /**

  * Procedure to get template information

  */

  PROCEDURE getevaltemplatedetail(IN vtemplate character varying, IN vlevel integer, OUT results_cur cursor_pkg.weakcursor);

  

  /**

  * Helper function to get default template used for a discipline

  */

  FUNCTION getdefaulttemplate(vdiscipline character varying, vyear integer) RETURN character varying;

  

  /**

  * Procedure to get list of general questions for evaluation

  */

  PROCEDURE getevalgeneralquestions(IN vtemplate character varying, OUT results_cur cursor_pkg.weakcursor);

  

  /**

  * Procedure to get list of treatment specific questions for evaluation

  */

  PROCEDURE getevaltxquestions(IN vtemplate character varying, IN vproccode character varying, OUT results_cur cursor_pkg.weakcursor);

  

  /**

  * Procedure to check if a treatment can be added to a new evaluation

  * param: vGrading INPUT: Grading ID of an existing evaluation

  * param: vType INPUT: trx Type of the treatment being validted (TRX.Type)

  * param: vId INPUT: trx ID of the treatment being validated (TRX.Id)

  * param: vTreatment INPUT: trx Treatment of the treatment being validated (TRX.Treatment)

  * param: vResult OUTPUT: (0 = invalid; 1 = valid;)

  */

  PROCEDURE validatetemplatetreatment(IN vtemplate character varying, IN vtype integer, IN vid integer, IN vtreatment integer, OUT vresult integer);

  

  /**

  * Procedure to check if a treatment can be added to an existing evaluation

  * param: vGrading INPUT: Grading ID of an existing evaluation

  * param: vType INPUT: trx Type of the treatment being validted (TRX.Type)

  * param: vId INPUT: trx ID of the treatment being validated (TRX.Id)

  * param: vTreatment INPUT: trx Treatment of the treatment being validated (TRX.Treatment)

  * param: vResult OUTPUT: (0 = invalid; 1 = valid;)

  */

  PROCEDURE validateevaltreatment(IN vgrading integer, IN vtype integer, IN vid integer, IN vtreatment integer, OUT vresult integer);



  FUNCTION countevaltxquestions(vitem integer, vproccode character varying) RETURN integer;

  /**

  * Procedure to get list of scheme items used in particular Template Item

  */

  PROCEDURE getevalschemeitem(IN vscheme character varying, OUT results_cur cursor_pkg.weakcursor);



  /**

  * Procedure to get trx with ChartTrx

  */

  PROCEDURE gettrx(IN vcharttrx integer, OUT results_cur cursor_pkg.weakcursor);

  

  /*

  * Procedure to get trx with Type, ID, and Treatment

  */

  PROCEDURE gettrx2(IN vtype integer, IN vid integer, IN vtreatment integer, OUT results_cur cursor_pkg.weakcursor);

  

  /**

  * Procedure to update Grading table in editing mode

  */

  PROCEDURE doeditgrading(IN vgrading integer, IN vdate character varying, IN vprovider character varying, IN vinstructor integer, IN vcompetency integer, IN vtimespent double precision, IN vdiscipline character varying, IN vcomment character varying, IN vpassed integer, OUT vresult integer);

  

  /**

  * Procedure to insert into GRADITEM table

  */

  PROCEDURE doeditgraditem(IN vgrading integer, IN vtrxspecific integer, IN vrow integer, IN vanswer character varying, IN vcomment character varying, IN vuser integer, OUT vresult integer);

  

  /**

  * Procedure to update Grading table in resume mode

  */

  PROCEDURE doresumegrading(IN vgrading integer, IN vinstructor integer, IN vincomplete integer, IN vheldforuser integer, IN vtimespent double precision, IN vcomment character varying, IN vpassed integer, OUT vresult integer);

  

  /**

  * Procedure to insert into GRADITEM table

  */

  PROCEDURE doresumegraditem(IN vgrading integer, IN vnewgrading integer, IN vtrxspecific integer, IN vrow integer, IN vanswer character varying, IN vcomment character varying, IN vuser integer, OUT vresult integer);



  /**

  * Procedure to delete existing evaluation

  */

  PROCEDURE deletegrading(IN vgrading integer, OUT vresult integer);



  /**

  * Procedure to insert into GRADING table

  */

  PROCEDURE dograding(IN vproducer character varying, IN vdate timestamp without time zone, IN vinstructor integer, IN vpatient integer, IN vdiscipline character varying, IN vtemplate character varying, IN vtimespent double precision, IN vpassed integer, IN vcomment character varying, IN vcompetency integer, IN vincomplete integer, IN vheldforuser integer, OUT vresult integer);



  /**

  * Procedure to insert into GRADITEM table

  */

  PROCEDURE dograditem(IN vgrading integer, IN vtrxspecific integer, IN vrow integer, IN vitem integer, IN vtype integer, IN vid integer, IN vtreatment integer, IN vanswer character varying, IN vuser integer, IN vdate timestamp without time zone, IN vcomment character varying, OUT vresult integer);



  /**

  * PROCEDURE to copy TRXGRADE FROM one grading to another

  */

  PROCEDURE copytrxgrade(IN vprevgrading integer, IN vnewgrading integer);



  /**

  * PROCEDURE to mark TRXGRADE to processed for trx items not listed in TITEM

  */

  PROCEDURE updatetrxgrade(IN vtype integer, IN vid integer, IN vtreatment integer, IN vgrading integer, IN vstatus integer, OUT vresult integer);



  /**

  * Procedure to return a list of axium providers that meet the search criteria. <p/>

  * param: vSearchString INPUT: string to conduct the search on.<p/>

  * param: vSearchOn INPUT: Field in the producer table to search on (0 = Provider #, 1 = LastName, 2 = FirstName, 3 = Year, 4 = Group).</p>

  * param: vSearchInactive INPUT: to include inactive providers in the search result (0 = no, 1 = yes)<p/>

  * param: vSearchRequireGrading INPUT: to get list of provider based on RequireGrading setting (0 = all, 1 = sessional, 2 = periodic, 3 = sessional and periodic)<p/>

  * param: vSortBy INPUT: Sort on (0 = Provider #, 1 = LastName, 2 = FirstName, 3 = Year, 4 = Group)<p/>

  * param: vSortDir INPUT: Sort Direction (0 = ASC, 1 = DESC)<p/>

  * param: vNumRows INPUT: number of records to return<p/>

  * param: vPage INPUT: set of rows (eg. page-3 and numRows-20 = 40 ~ 59 rows)<p/>

  * param: vCurrentPage OUTPUT: page number of current records<p/>

  * param: vTotalPage OUTPUT: total page numbers of current search criteria<p/>

  * param: results_cur OUTPUT: Weak cursor to contain the data retrieved<br/>

  */

  PROCEDURE doevalprovidersearch(IN vsearchstring character varying, IN vsearchon integer, IN vsearchinactive integer, IN vsearchrequiregrading integer, IN vsortby integer, IN vsortdir integer, IN vnumrows integer, IN vpage integer, OUT vcurrentpage integer, OUT vtotalpage integer, OUT results_cur cursor_pkg.weakcursor);



  /**

  * Procedure to return a list of axiUm instructors that meet a search criteria.<p/>

  *

  * param: vSearchString INPUT: String to conduct the search on.<p/>

  * param: vSearchOn INPUT: Field in the user table to search on (0=first name, 1= last name, 2= provider ID, 3= provider group, 4= security level)<p/>

  * param: vSearchDeleted INPUT: to include deleted instructors in the search result (0 = no, 1 = yes)<p/>

  * param: vSearchExpired INPUT: to include expired instructors in the search result (0 = no, 1 = yes)<p/>

  * param: vSortBy INPUT: Sort on (0 = user, 1 = logon, 2 = lastName, 3 = firstName, 4 = userLevel, 5 = producer)<p/>

  * param: vSortDir INPUT: Sort Direction (0 = ASC, 1 = DESC)<p/>

  * param: vNumRows INPUT: number of records to return<p/>

  * param: vPage INPUT: set of rows (eg. page-3 and numRows-20 = 40 ~ 59 rows)<p/>

  * param: vCurrentPage OUTPUT: page number of current records<p/>

  * param: vTotalPage OUTPUT: total page numbers of current search criteria<p/>

  * param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

  */

  PROCEDURE doevalinstructorsearch(IN vsearchstring character varying, IN vsearchon integer, IN vsearchdeleted integer, IN vsearchexpired integer, IN vsortby integer, IN vsortdir integer, IN vnumrows integer, IN vpage integer, OUT vcurrentpage integer, OUT vtotalpage integer, OUT results_cur cursor_pkg.weakcursor);

  

  /**

  * Procedure to return a list of axiUm instructors that meet a search criteria.<p/>

  *

  * param: vSearchString INPUT: String to conduct the search on.<p/>

  * param: vSearchOn INPUT: Field in the user table to search on (0 = lastName, 1 = firstName, 2 = chart)<p/>

  * param: vSortBy INPUT: Sort on (0 = lastName, 1 = firstName, 2 = chart, 3 = gender)<p/>

  * param: vSortDir INPUT: Sort Direction (0 = ASC, 1 = DESC)<p/>

  * param: vNumRows INPUT: number of records to return<p/>

  * param: vPage INPUT: set of rows (eg. page-3 and numRows-20 = 40 ~ 59 rows)<p/>

  * param: vCurrentPage OUTPUT: page number of current records<p/>

  * param: vTotalPage OUTPUT: total page numbers of current search criteria<p/>

  * param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

  */

  PROCEDURE dopatientsearch(IN vsearchstring character varying, IN vsearchon integer, IN vsortby integer, IN vsortdir integer, IN vnumrows integer, IN vpage integer, OUT vcurrentpage integer, OUT vtotalpage integer, OUT results_cur cursor_pkg.weakcursor);

                              

  /**

  * Procedure to GET a list of unevaluted treatments for the indicated date<p/>

  *

  * param: vSearchProviderString INPUT: Provider keyword to conduct search on. Checks TRX.Producer<p/>

  * param: vSearchProviderOn INPUT: Provider field to conduct search on. (0 = lastName, 1 = firstName, 2 = provider #)<p/>

  * param: vSearchInstructorString INPUT: Instructor keyword to conduct search on. Checks TRX.AppUser<p/>

  * param: vSearchInstructorOn INPUT: Instructor field to conduct search on. (0 = lastName, 1 = firstName, 3 = provider #)<p/>

  * param: vDateFrom INPUT: Begining approved date to filter the list in DD-MMM-YY format (eg. 03-MAR-2010)<p/>

  * param: vDateTo INPUT: Ending approved date to filter the list in DD-MMM-YY format (eg. 03-MAR-2010)<p/>

  * param: vGroupBy INPUT: criteria in the table to group by (0 = no group, 1 = patient, 2 = provider)<p/>

  * param: vGroupDir INPUT: Group Direction (0 = ASC, 1 = DESC)<p/>

  * param: vSortBy INPUT: Sort on (0 = ProviderCode, 2 = ProviderName, 3 = TxDate, 4 = Instructor, 5 = Procedure, 6 = TxDescription, 7 = TxStatus, 8 = TxSite, 9 = Patient, 10 = PatientChart, 11 = TxClaim#, 12 = ApprovalDate)<p/>

  * param: vSortDir INPUT: Sort Direction (0 = ASC, 1 = DESC)<p/>

  * param: vMedicaidCode IN: list of procedure codes defined as Medicaid code<p/> 

  * param: results_cur OUTPUT: Weak cursor to contain the data retrieved<br/>

  */

  PROCEDURE getunevaluatedtxlist(IN vproducer character varying, IN vinstructor integer, IN vpatient integer, IN vdatefrom character varying, IN vdateto character varying, IN vgroupby integer, IN vgroupdir integer, IN vsortby integer, IN vsortdir integer, IN vmedicaidcode character varying, OUT results_cur cursor_pkg.weakcursor);

                                 

  /**

  * Procedure to GET a list of evaluated forms from Grading table.<p/>

  *

  * param: vProvider INPUT: User ID of the provider graded. (0 = search all, 1+ = USERS.User)<p/>

  * param: vInstructor INPUT: User ID of the instructor grading the form. (0 = search all, 1+ = GRADING.Instructor)<p/>

  * param: vPatient INPUT: Patient ID of the form. (0 = search all, 1+ = GRADING.Patient)<p/>

  * param: vDiscipline INPUT: Discipline the student was working on. (Blank = search all, else = find exact match)<p/>

  * param: vTemplate INPUT: Template ID used for grading prt to TEMPLATE.Template.<p/>

  * param: vShowGeneral INPUT: Show General/Patient evaluation (0 = show all, 1 = show general only, 2 = show patient only).<p/>

  * param: vIsExam INPUT: Search criteria if the template is exam<p/>

  * param: vIsCompetency INPUT: Search criteria if the grading is competency evaluation<p/>

  * param: vIsEvaluation INPUT: Search criteria if the grading is regular evaluation<p/>

  * param: vIncomplete INPUT: Search criteria if the grading is held (0 = all, 1 = completed, 2 = incomplete)<p/>

  * param: vHeldForUser INPUT: Search criteria for held instructor if the form is incomplete<p/>

  * param: vDateFrom INPUT: Begining grading date to filter the list in DD-MMM-YY format (eg. 03-MAR-2010)<p/>

  * param: vDateTo INPUT: Ending grading date to filter the list in DD-MMM-YY format (eg. 03-MAR-2010)<p/>

  * param: vDeleted INPUT: filter option to show deleted evaluations as well (0 = do not show deleted, 1 = show deleted)<p/>

  * param: vLevel INPUT: SLevel to check if has access to the Evaluation<p/>

  * param: vNumRows INPUT: number of records to return<p/>

  * param: vPage INPUT: page numer - set of rows (eg. page-3 and numRows-20 = 40 ~ 59 rows)<p/>

  * param: vCurrentPage OUTPUT: actual page number of current records<p/>

  * param: vTotalPage OUTPUT: total page number<p/>

  * param: results_cur OUTPUT: Weak cursor to contain the data retrieved<br/>

  */

  PROCEDURE getevaluationlist(IN vproducer character varying, IN vinstructor integer, IN vpatient integer, IN vdiscipline character varying, IN vtemplate character varying, IN vshowgeneral integer, IN visexam integer, IN viscompetency integer, IN visevaluation integer, IN vincomplete integer, IN vheldforuser integer, IN vdatefrom character varying, IN vdateto character varying, IN vdeleted integer, IN vlevel integer, IN vnumrows integer, IN vpage integer, OUT vcurrentpage integer, OUT vtotalpage integer, OUT results_cur cursor_pkg.weakcursor);





  /**

  * Procedure to GET a list of treatments evaluted for a specified Evaluation.<p/>

  *

  * param: vGrading INPUT: GRADING."Grading"<p/>

  * param: results_cur OUTPUT: Weak cursor to contain the data retrieved<br/>

  */

  PROCEDURE getevaluatedtxlist(IN vgrading integer, OUT results_cur cursor_pkg.weakcursor);

  /**

  * Procedure to GET a detail of an evaluation from GRADING table.<p/>

  *

  * param: vGrading INPUT: GRADING."Grading"<p/>

  * param: vLevel INPUT: SLevel to check if has access to the Evaluation<p/>

  * param: results_cur OUTPUT: Weak cursor to contain the data retrieved<br/>

  */

  PROCEDURE getgradingdetail(IN vgrading integer, IN vlevel integer, OUT results_cur cursor_pkg.weakcursor);

  

  /**

  * Procedure to GET a list of grade items for a indicated evaluation from GRADITEM table.<p/>

  *

  * param: vGrading INPUT: GRADING."Grading"<p/>

  * param: results_cur OUTPUT: Weak cursor to contain the data retrieved<br/>

  */

  PROCEDURE getgradingitemlist(IN vgrading integer, OUT results_cur cursor_pkg.weakcursor);



  /**

  * Procedure to GET a list of grade item list that has indicated treatment as a cumulative evaluation, and template as a form.<p/>

  *

  * param: vType INPUT: Treatment type<p/>

  * param: vId INPUT: Treatment type<p/>

  * param: vTreatment INPUT: Treatment GRADITEM."Treatment"<p/>

  * param: vTemplate INPUT: GRADITEM."Template"<p/>

  * param: results_cur OUTPUT: Weak cursor to contain the data retrieved<br/>

  */

  PROCEDURE getcumulativegraditemlist(IN vtype integer, IN vid integer, IN vtreatment integer, IN vtemplate character varying, OUT results_cur cursor_pkg.weakcursor);



  /**

  * Procedure to get a detail of a grade item for cumulative (trx based on OrigRecNo):

  * param: vGrading INPUT: Grading ID<p/>

  * param: vType INPUT: Type of treatment if the grade item is treatment specific<p/>

  * param: vId INPUT: Id of treatment if the grade item is treatment specific<p/>

  * param: vTreatment INPUT: Treatment type of trx if the grade item is treatment specific<p/>

  * param: vItem INPUT: Item id of the grade item it is based on GRADITEM."Item"<p/>

  * param: results_cur OUTPUT: weak-cursor outputing a GRADITEM row<p/>

  */

  PROCEDURE getdefaultcumulativegraditem(IN vgrading integer, IN vtype integer, IN vid integer, IN vtreatment integer, IN vitem integer, OUT results_cur cursor_pkg.weakcursor);



  /**

  * Procedure to GET a list of grading details that has indicated treatment as a cumulative evaluation.<p/>

  *

  * param: vType INPUT: Treatment type<p/>

  * param: vLevel INPUT: AX-1945 Level<p/>

  * param: results_cur OUTPUT: Weak cursor to contain the data retrieved<br/>

  */

  PROCEDURE getcumulativegradinglist(IN vtype integer, IN vid integer, IN vtreatment integer, IN vlevel integer, OUT results_cur cursor_pkg.weakcursor);



  /**

  * Procedure to Check if the instructor evaluated the treatment today.<p/>

  *

  * param: vInstructor INPUT: instructor ID<p/>

  * param: vChartTrx INPUT: Chart Trx ID<p/>

  * param: vResult OUTPUT: indicator who evaluated the treatment (0 = no one; 1 = self; 2 = other instructor)<br/>

  */

  PROCEDURE validatetxevaluatedtoday(IN vinstructor integer, IN vcharttrx integer, OUT vresult integer);

  

  /**

  * Procedure Get Server Date Time.<p/>

  *

  * param: vResult OUTPUT: Server DateTime in format 'DD-MON-YYYY HH24:MI:SS'<br/>

  */

  PROCEDURE getservertime(IN stationid integer, INOUT vresult character);



  /**

  * Procedure that set FA version in FSetting table.<p/>

  *

  * param: vVersion INPUT: version to set<p/>

  */

  PROCEDURE setfaversion(IN vversion character varying);



  

  /**

  * Procedure to Edit Notes (Update NOTES2 and delete NOTEOVR and then INSERT NOTEOVER if is necessary.<p/>

  *

  * param: vAuto INPUT: Auto ID<p/>

  * param: vCustom1Val INPUT: Custom1Val - Product Clinic<p/>

  * param: vCustom2Val INPUT: Custom2Val - Prognosis<p/>

  * param: vDate INPUT: Date<p/>

  * param: vNoteText INPUT: Note Text<p/>

  */

  PROCEDURE doeditnotes(IN vauto integer, IN vcustom1val character varying, IN vcustom2val character varying, IN vnotetext character varying);

  

  /**

  * Procedure to Edit SOAP Notes (Update NOTES2 and delete NOTEOVR and then INSERT NOTEOVER if is necessary.<p/>

  *

  * param: vAuto INPUT: Auto ID<p/>

  * param: vCustom1Val INPUT: Custom1Val - Product Clinic<p/>

  * param: vCustom2Val INPUT: Custom2Val - Prognosis<p/>

  * param: vDate INPUT: Date<p/>

  * param: vSubjectiveNote INPUT: Subjetive Note Text<p/>

  * param: vObjectiveNote INPUT: Objective Note Text<p/>

  * param: vAssessmentNote INPUT: Assessment Note Text<p/>

  * param: vPlannedNote INPUT: Planned Note Text<p/>

  */

  PROCEDURE doeditsoapnotes(IN vauto integer, IN vcustom1val character varying, IN vcustom2val character varying, IN vdate character varying, IN vsubjectivenote character varying, IN vobjectivenote character varying, IN vassessmentnote character varying, IN vplannednote character varying);



  /**

  * Procedure to Edit General and SOAP Notes (Update NOTES2 and delete NOTEOVR and then INSERT NOTEOVER if is necessary.<p/>

  *

  * param: vId INPUT: ID<p/>

  * param: vTypeNote INPUT: Type<p/>

  * param: vSectionNum INPUT: SectionNum<p/>

  * param: vCustom1Val INPUT: Custom1Val - Product Clinic<p/>

  * param: vCustom2Val INPUT: Custom2Val - Prognosis<p/>

  * param: vNoteText INPUT: Note Text<p/>

  */

  PROCEDURE editnotes(IN vid integer, INOUT vtypenote integer, IN vsectionnum integer, IN vcustom1val character varying, IN vcustom2val character varying, IN vdate character varying, IN vnotetext character varying);



  /**

  * Procedure to Get Chair State.<p/>

  *

  * param: vChair INPUT: Chair<p/>

  * param: vTimer1 INPUT: Timer 1<p/>

  * param: vTimer2 INPUT: Timer 2<p/>

  * param: results_cur OUT: Chair Status<p/>

  */

  PROCEDURE getchairstate(IN vchair integer, IN vtimer1 integer, IN vtimer2 integer, OUT results_cur cursor_pkg.weakcursor);

  

  /**

  * 29205783 Function to get the State notification name of the chair<p/>

  * param: vChair INPUT: Chair<p/>

  * param: vTimer1 INPUT: Timer 1<p/>

  * param: vTimer2 INPUT: Timer 2<p/>

  * return: ID of CNState CHAIRST."CNState" <p/>

  */

  FUNCTION getchaircnstate(vchair integer, vtimer1 integer, vtimer2 integer) RETURN character varying;



  /**

  * 29205783 Function to get the State order of the chair<p/>

  * 61660872 Sort chair notifications by priority<p/>

  * param: vChair INPUT: Chair<p/>

  * param: vTimer1 INPUT: Timer 1<p/>

  * param: vTimer2 INPUT: Timer 2<p/>

  * return: Order from CNSTATE <p/>

  */

  FUNCTION getcnstateorder(vchair integer, vtimer1 integer, vtimer2 integer) RETURN integer;



  /**

  * 61660872 Function to Date Chair CNSate<p/>

  * param: vChair INPUT: Chair<p/>

  * param: vTimer1 INPUT: Timer 1<p/>

  * param: vTimer2 INPUT: Timer 2<p/>

  * return: vOrderDateChair from AUDITHIS <p/>

  */

  FUNCTION getdateforchairstate(vchair integer, vtimer1 integer, vtimer2 integer, stationid integer) RETURN character varying;

  

  /** 

  * Procedure to get the State Notification Details of the chair<p/>

  * param: vCnState INPUT: CNState<p/>

  * param: vBkgColor OUT: BkgColor<p/>

  * param: vDescription OUT: Description<p/>

  * param: vSessionBased OUT: SessionBased<p/>

  * param: vOrder OUT: Order<p/>

  */

  PROCEDURE getchairstatedetails(IN vcnstate character varying, OUT vbkgcolor integer, OUT vdescription character varying, OUT vsessionbased character varying, OUT vorder integer);

  

  /**

  * Procedure to get GetClinicTime() function result <p/>

  * param: vApptId INPUT: Appointment Id<p/>

  * param: vClinicTime OUT: ClinicTime<p/>

  */

  PROCEDURE getclinictimeprocedure(IN vapptid integer, OUT vclinictime integer);



  /**

  * Procedure to Update Chair State table <p/>

  * param: vChair INPUT: Chair<p/>

  * param: vTimer1 INPUT: Timer 1<p/>

  * param: vTimer2 INPUT: Timer 2<p/>

  * param: vResult OUTPUT: result<p/>

  */

  PROCEDURE updatechairstate(IN vchair integer, IN vtimer1 integer, IN vtimer2 integer, IN vuser integer, OUT vresult integer);



  /**

  * Procedure to Get CNState info.<p/>

  * param: results_cur OUT: Chair Status<p/>

  */

  PROCEDURE getcnstate(OUT results_cur cursor_pkg.weakcursor);





  /**

  * Procedure used to get provider for "Find Provider" list

  * param: vFilterKeyword INPUT: Filter keyword to search list<p/>

  * param: vFilterField INPUT: Filter field used to filter keyword<p/>

  * param: vSearchInactive INPUT: to include inactive providers in the search result (0 = no, 1 = yes)<p/>

  * param: vOrderDirection INPUT: DESC OR ASC<p/>

  * param: vNumRows INPUT: number of records to return<p/>

  * param: vPage INPUT: set of rows (eg. page-3 and numRows-20 = 40 ~ 59 rows)<p/>

  * param: vCurrentPage OUTPUT: page number of current records<p/>

  * param: vTotalPage OUTPUT: total page numbers of current search criteria<p/>

  * param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br />

  * <li>Producer - Provider Code <br />

  * <li>FirstName - Provider First Name <br />

  * <li>LastName - Provider Last Name <br />

  * <li>FullName - Provider Full Name in F.LastName format <br />

  * <li>User - Provider User ID <br />

  * <li>TypeCode - Provider Type Code <br />

  * <li>PGroup - Provider Group <br />

  * <li>Year - Provider Year <br />

  */

  PROCEDURE getprovfindlist(IN vfilterkeyword character varying, IN vfilterfield character varying, IN vsearchinactive integer, IN vorderdirection character varying, IN vnumrows integer, IN vpage integer, OUT vcurrentpage integer, OUT vtotalpage integer, OUT results_cur cursor_pkg.weakcursor);

  

  /**

  * Check if an appointment is watched by current instructor

  * param: vAppointment INPUT: Appointment ID

  * param: vInstructor INPUT: User ID for current instructor

  * param: vCount OUTPUT: Number of items that matches appointment ID and instructor ID for today

  */

  PROCEDURE checkapptwatcheditem(IN vappointment integer, IN vinstructor integer, OUT vcount integer);

  

  /**

  * Add a record to FAPTWATCH table

  * param: vAppointment INPUT: Appointment ID

  * param: vInstructor INPUT: User ID for current instructor

  */

  PROCEDURE addapptwatcheditem(IN vappointment integer, IN vinstructor integer);

  

  /**

  * Delete a record from FAPTWATCH table

  * param: vAppointment INPUT: Appointment ID

  * param: vInstructor INPUT: User ID for current instructor

  */

  PROCEDURE deleteapptwatcheditem(IN vappointment integer, IN vinstructor integer);

  

  /**

  * Delete all record from FAPTWATCH table for a user

  * param: vInstructor INPUT: User ID for current instructor

  */

  PROCEDURE deleteallapptwatcheditems(IN vinstructor integer);

  

  /**

  * Clear all watched appointments with date after x number of days

  * param: vDay INPUT: Number of days

  * param: vInstructor INPUT: 0 = all, 1+ = instructor ID

  */

  PROCEDURE clearapptwatchedlist(IN vday integer, IN vinstructor integer);

  

  /**

  * Get Patient Id from IUSER table

  * param: vUserId INPUT: UserId to look for

  * param: vPstientId OUTPUT: PatientId if exist in IUSER table

  */

  PROCEDURE getiuserpatientid(IN vuserid integer, OUT vpatientid integer);

  

  /**

  * Get cursor containing all SLEVEL reocrds

  * param: results_cur OUTPUT: Weak cursor containing slevel data

  */

  PROCEDURE getslevels(OUT results_cur cursor_pkg.weakcursor);

  

  /** 

  * 50621785 Get Roles for Admin

  * param: results_cur OUTPUT: Weak cursor containing sRole data

  */  

  PROCEDURE getsroles(OUT results_cur cursor_pkg.weakcursor);

  

  /**

  * Get Patient Detail information for Tab panel

  * param: vPatient INPUT: PatientId

  * param: results_cur OUTPUT: Weak cursor containing watched patient data

  */  

  PROCEDURE getpatienttabdetail(IN vpatient integer, OUT results_cur cursor_pkg.weakcursor);



  /** 

  * Get Notes Information 

  * param: vTxId INPUT: TxId

  * param: vType INPUT Type

  * param: result_cur OUPUT: Weak cursor containing Note data

  */

  PROCEDURE getnotesinfobytxandtype(IN vtxid integer, IN vtype integer, OUT results_cur cursor_pkg.weakcursor);

  

  /**

  * Function to retrieve data about a particular Ortho Visit and return it as a rec_OrthoVisitDetail RECORD type.<p/>

  *

  * param: vAutoTrx INPUT: ID for the Treatment2 row associated with this ortho visit<p/>

  * param: vType INPUT: Flag indicating if this treatment is approved or not approved (0=not approved, 1=approved, 2=not-approved planned)<p/> 

  * return: rec_OrthoVisitDetail record containing the treatment data.<p/>

  */

  FUNCTION getorthovisitdetail(vautoov integer, vtype integer) RETURN rec_orthovisitdetail;

  

  /**

  * Function to retrieve data about a ortho visit treatment from Treatme2 and return it as a rec_OrthoVisitDetail RECORD type. Similar to GetLineDetailTreatment() <p/>

  *

  * param: vAutoTrx INPUT: ID for the Treatment2 row associated with this ortho visit<p/>

  * param: vType INPUT: Flag indicating if this treatment is approved or not approved (0=not approved, 1=approved, 2=not-approved planned)<p/> 

  * return: rec_OrthoVisitDetail record containing the treatment data.<p/>

  */

  PROCEDURE getlinedetailorthovisit(IN vautoov integer, IN vtype integer, OUT vdescription character varying, OUT vorthonote character varying, OUT results_cur cursor_pkg.weakcursor); 



  /**

  * Procedure to get information containing details for a particular Ortho Visit Custom Questions and Answers

  * 

  * param: vOrthoId INPUT: ID for the Treatment2 row associated with this ortho visit<p/>

  */

  PROCEDURE getorthovisitcustomfields(IN vorthoid integer, OUT results_cur cursor_pkg.weakcursor);



  /**

  * Procedure to perform a Ortho Visits approval (Status E).<p/>

  *

  * param: vChartLnk INPUT: ChartLnk ID of the ortho visit (CHARTLNK.Id).<p/>

  * param: vAuto INPUT: ID of TREATME2.Auto.<p/>

  * param: vInstructor INPUT: User ID of the logged-in user.<p/>

  * param: vResult OUTPUT: Flag to indicate if the finding was successfully approved (0=yes, -1=error encountered).<p/>

  */

  PROCEDURE doapproveorthovisits(IN vchartlnk integer, IN vauto integer, IN vinstructor integer, OUT vresult integer);

  

    PROCEDURE getmedicaidcodes(OUT vresult cursor_pkg.weakcursor);

    

  /**

  * Helper function to validate and get procedure code. If Treatment is associated to Ortho Visit code is '***Ortho Visit***'

  * param: vTxId INPUT: Treatment ID<p/>

  * return: procedure code if the procedure is valid or '***Ortho Visit***' if procedure is associated with OrthoVisitProc, if not return 'Procedure Code - Not on File'<p/>

  */

  FUNCTION getprocedurecodebytxid(vtxid integer) RETURN character varying;

  

  /**

  * Get Language fields by LangCd

  * param: vLangCd INPUT: Language Id<p/>

  * vResult: OUTPUT: Langualge fields <p/>

  */

  PROCEDURE getlanguagebylangcd(IN vlangcd character varying, OUT vresult cursor_pkg.weakcursor);

  

  FUNCTION safetonumber(vinput character varying) RETURN numeric;

  

END;
CREATE OR REPLACE PACKAGE lastappointtrx_pkg IS
  TYPE lastappointtrx_record IS RECORD (lasttrans timestamp without time zone, ar numeric, lastcode character(8));
  TYPE lastappointtrx_type IS REF CURSOR RETURN lastappointtrx_record;
  TYPE ptbal_record IS RECORD (ptbal numeric);
  TYPE ptbal_type IS REF CURSOR RETURN ptbal_record;
  FUNCTION ptbalance(familyid numeric) RETURN numeric;
  FUNCTION ptover30balance(familyid numeric) RETURN numeric;
END;
CREATE OR REPLACE PACKAGE medicaid_pkg IS
	FUNCTION getnymedconsolidateprocs() RETURN character varying;										-- E97315
	FUNCTION isancillaryproc(vproc character) RETURN numeric;									-- E87121
END;
CREATE OR REPLACE PACKAGE onlinereq_pkg IS

	FUNCTION getptlastname(vonlinereqid numeric) RETURN character varying;								

	FUNCTION getptfirstname(vonlinereqid numeric) RETURN character varying;								

	FUNCTION getptpreferredname(vonlinereqid numeric) RETURN character varying;								



	FUNCTION getptprofileanswer(vonlinereqid numeric, vtableid numeric, vfieldid numeric) RETURN character varying;								

END;
CREATE OR REPLACE PACKAGE overnight_std_pkg IS

  PROCEDURE all_clients_cleanup();

  

  PROCEDURE apply_all_payments(IN pstation numeric, IN nfamilymode numeric DEFAULT 0);		-- E137246 added optional parameter

  PROCEDURE apply_all_prepayments(IN pstation numeric, IN poptionaluser numeric, IN patientid numeric, OUT ppcount numeric);		-- E21522.4

  

  PROCEDURE checkout_patients(IN doaudit numeric);

  FUNCTION create_audit(tablename character, historytype numeric, auditstation numeric) RETURN numeric;

                       

  PROCEDURE delete_expired_assignments();

  PROCEDURE delete_selected_pts(IN clearheldpts numeric, IN clearallusers numeric);

  PROCEDURE generate_ptbal(IN imethod numeric DEFAULT 0);	-- E54754

  

  PROCEDURE preload_patient_list();

  PROCEDURE reset_policy_yearend();

  PROCEDURE reset_policy_monthend();

  PROCEDURE reset_policy_deplimitcat();

  PROCEDURE reset_policy_deplimititem();

  

  PROCEDURE reverse_freeaccess_pts();

  

  PROCEDURE update_failed_appts(IN num_stationid numeric);

  PROCEDURE checkout_appts();									-- E46841

  PROCEDURE update_plantx_status(IN pstation numeric);       -- E39675

  PROCEDURE update_plantx_steps(IN pstation numeric, IN puser numeric, IN pcharttrx numeric, IN pstatus character varying); -- AX-17355.18326

  

  PROCEDURE clear_custom_events();							-- E33069

  PROCEDURE clear_emancedminor();							-- E52612

  

  PROCEDURE cleanup_fitem_history();						-- B75126

  

  PROCEDURE delete_expired_waitlist_appts();			-- E73078.7.6

  

  PROCEDURE clear_chairst();                      -- E127712

  PROCEDURE delete_chairst();                     -- E127712

  PROCEDURE delete_dept_txs_all();                -- AX-2854

  PROCEDURE clear_processing_messages();		-- AX-11528.11629

  PROCEDURE delete_labtmptrx();					-- AX-19615.5c



  PROCEDURE set_elab_status();			-- AX-19762.20350			



  PROCEDURE cleanup_caprequests();		-- AX-22704

  

END;
CREATE OR REPLACE PACKAGE pa2_pkg IS

    PROCEDURE gettemplatedata(OUT out_html clob, OUT out_css clob, OUT out_js clob);


END;
CREATE OR REPLACE PACKAGE pa2template_pkg IS
FUNCTION pa2template_html(panavid numeric DEFAULT 0) RETURN clob;
FUNCTION pa2template_css(panavid numeric DEFAULT 0) RETURN clob;
FUNCTION pa2template_js(panavid numeric DEFAULT 0) RETURN clob;
END;
CREATE OR REPLACE PACKAGE patient_pkg IS



  /****************************************************************************

   *  vSuccess = 0 then ChartMerge succeeded

   *  vSuccess = 1 then "Patient records not found"

   *  vSuccess = 2 then "Patient2 toothstate records are corrupted"

   *  vSuccess = 3 then "Error merging EPR"

   *  vSuccess = 4 then "Any other Error"

   *

   *  Note: In any case if an error occurs, all modifications will be rolled

   *        back. Changes are commited when vSuccess = 0

   ****************************************************************************/

  PROCEDURE chartmerge(IN vpatientbad numeric, IN vpatientgood numeric, IN vuser numeric, IN vstationid numeric, OUT vsuccess numeric);



  PROCEDURE chartmergea(IN vchartbad character, IN vchartgood character, IN vuser numeric, IN vstationid numeric, OUT vsuccess numeric);



  PROCEDURE merge_epr(IN oldpatientid numeric, IN newpatientid numeric, IN oldiuserid numeric, IN newiuserid numeric, OUT success numeric);



  --E37209.3.4  

  PROCEDURE merge_iinfo(IN oldpatientid numeric, IN newpatientid numeric, OUT oldiuserid numeric, OUT newiuserid numeric);



  -- B132297 added

  PROCEDURE handle_trxtype74records(IN patientid numeric);

  PROCEDURE handle_trxtype73records(IN patientid numeric);

  PROCEDURE merge_trxtyperecords(IN patientid numeric, IN paymenttype numeric, IN paymentid numeric, IN payplanid numeric);

                   

  -- B65979

  -- convert an existing guarantor to a patient

  -- Success = 1 if successful, 0 if failed

  -- any changes will be rolled back on failure

  PROCEDURE convertguarantortopatient(IN patientid numeric, IN newstatus character, IN newchart character, IN newchartsort character, IN userid numeric, IN stationid numeric);

  													

	--E136707, B142771.1 													

	PROCEDURE getsmokingstatus(IN patientid numeric, OUT medalertid numeric, OUT userid numeric, OUT code character varying, OUT description character varying, OUT ptalertid numeric);

	FUNCTION issmokingproblem(medalertid numeric) RETURN numeric;

	FUNCTION issmokingsnomedcode(snomed character varying) RETURN numeric;

	

	FUNCTION getsmokingstatusdescription(patientid numeric) RETURN character varying;								



	--AX-11773.11800

	PROCEDURE getnonsmokingstatuscode(OUT code character varying);								



	--AX-18695.21037

	FUNCTION getsexorientation(ptsexorient numeric) RETURN character varying;								

	FUNCTION getgenderidentity(ptgenderid numeric) RETURN character varying;								

	

	FUNCTION getgenderpronouns(ptpreferpronouns numeric) RETURN character varying;								

	

	FUNCTION getpatientpronouns(patientid numeric) RETURN character varying;								



END;
CREATE OR REPLACE PACKAGE payplan_bal_pkg IS
  TYPE pp_open_bal_record IS RECORD (pp_open_bal numeric);
  TYPE pp_open_bal_type IS REF CURSOR RETURN pp_open_bal_record;
  FUNCTION pp_open_bal(patient numeric) RETURN numeric;
END;
CREATE OR REPLACE PACKAGE pe_custom_pkg IS
	FUNCTION get_golive_date() RETURN timestamp without time zone;
	FUNCTION get_books_touse() RETURN character varying;
END;
CREATE OR REPLACE PACKAGE "pkg_elmah$get_error" IS

    TYPE t_cursor IS REF CURSOR;

    PROCEDURE geterrorxml(IN v_application character varying, IN v_errorid character varying, OUT v_allxml clob);

    PROCEDURE geterrorsxml(IN v_application character varying, IN v_pageindex numeric DEFAULT 0, IN v_pagesize numeric DEFAULT 15, OUT v_totalcount numeric, OUT v_results t_cursor);

END;
CREATE OR REPLACE PACKAGE "pkg_elmah$log_error" IS
    PROCEDURE logerror(IN v_errorid character varying, IN v_application character varying, IN v_host character varying, IN v_type character varying, IN v_source character varying, IN v_message character varying, IN v_user character varying, IN v_allxml clob, IN v_statuscode numeric, IN v_timeutc timestamp without time zone);

END;
CREATE OR REPLACE PACKAGE polins_pkg IS

	-- defines to be used throughout; ideally should match axiUm's define

	cloneallrecords numeric DEFAULT 4;

	cloneallexceptdeplimit numeric DEFAULT 3;

	copyallkeeplimitded numeric DEFAULT 2;

	copyallusenewlimitdedandreset numeric DEFAULT 1;

	copyallusenewlimitdedandrecal numeric DEFAULT 0;



	-- B101882 defines to be used for value of IsCovered parameter for AddGuarantorDependant and AddPolicyDependant procedures

	ptdependiscoveredno numeric DEFAULT 0;

	ptdependiscoveredyes numeric DEFAULT 1;

	ptdependiscoverednoifnotset numeric DEFAULT -1;



	-- internal structure to hold most of POLINS fields for reference; B69331

	TYPE polinsrectyp IS RECORD ("Group" character(15), "Division" character(10), "FormsTo" numeric(5,0), "Company" character(6), "GovPolicy" character(6), "Fee" character(6), "Employer" numeric(10,0), "HasFamilyLimit" numeric(5,0), "FamilyDeduct" numeric, "FamilyLimit" numeric, "HasPatientLimit" numeric(5,0), "PatientDeduct" numeric, "PatientLimit" numeric, "YearEnd" numeric(10,0), "Assignment" numeric(5,0), "Signature" numeric(5,0), "WriteOff" numeric(5,0), "PlanType" numeric(5,0), "MonthlyDeduct" numeric(5,0), "TrojanId" character(7), "YearEndDay" numeric(5,0), "ChildCoverage" numeric(10,0), "AdultCoverage" numeric(10,0), "YoungAdultCoverage" numeric(10,0), "Copay" numeric, "StartDate" timestamp without time zone, "EndDate" timestamp without time zone, count numeric);

	

	-- B69753 internal structure to hold most of EMPLOYER fields for reference

	TYPE employerrectyp IS RECORD ("Name" character(50), "Address1" character(30), "Address2" character(30), "City" character(24), "Province" character(6), "Postal" character(15), "Area" character(4), "Telephone" character(8), "Ext" character varying(6), "AddressOther" character(15), count numeric);

	

	-- cursors definition

	TYPE polinscurtyp IS REF CURSOR;

	TYPE ptpolcurtyp IS REF CURSOR;

	TYPE employercurtyp IS REF CURSOR;															--B69753

	

	-- main merge routine for initial conversion (for POLINS) 

	PROCEDURE polinsmergeprocess(IN pstation numeric, IN puser numeric, IN bstrict boolean);

	-- merge routine for all POLINS's having similar info as PolInsRec passed in

	PROCEDURE mergedistinctpolins(IN p polinsrectyp, IN pstation numeric, IN puser numeric, IN bstrict boolean);

	-- routine to check it the POLRANGE records are identical for the given PolIns's

	FUNCTION arepolrangethesame(masterpolinsid numeric, polinsid numeric) RETURN boolean;



	-- routine for merging the two given POLINS records

	PROCEDURE mergepolins(IN masterpolinsid numeric, IN polinsid numeric, IN pstation numeric, IN puser numeric, IN imode numeric);

				

	-- routine for merging a given PTPOL to a POLINS 							

	PROCEDURE mergepolicy(IN masterpolinsid numeric, IN mp polinsrectyp, IN op polinsrectyp, IN oldpolicyid numeric, IN pstation numeric, IN puser numeric, IN imode numeric);

	-- alternate routine for merging a given PTPOL to a POLINS to be used by axiUm

	--	(does not require passing of the internal structure...)

	PROCEDURE mergepolicyalt(IN masterpolinsid numeric, IN policyid numeric, IN pstation numeric, IN puser numeric, IN imode numeric);





	-- routines for cloning the appropriate records 							

	PROCEDURE mergeptpol(IN polinsid numeric, IN mp polinsrectyp, IN op polinsrectyp, IN oldpolicyid numeric, IN newpolicyid numeric, IN pstation numeric, IN puser numeric, IN imode numeric);

	PROCEDURE mergeptdepend(IN polinsid numeric, IN mp polinsrectyp, IN op polinsrectyp, IN oldpolicyid numeric, IN newpolicyid numeric, IN pstation numeric, IN puser numeric, IN imode numeric);

	PROCEDURE mergedeplimit(IN polinsid numeric, IN mp polinsrectyp, IN op polinsrectyp, IN oldpolicyid numeric, IN newpolicyid numeric, IN pstation numeric, IN puser numeric, IN imode numeric);

	--B67952

	PROCEDURE updatetrx(IN oldpolicyid numeric, IN newpolicyid numeric, IN pstation numeric, IN puser numeric);

				

	-- routines for adjusting the balances based on the different modes / the pass in info

	FUNCTION adjustlimitbalance(orighaslimit numeric, origlimitamt numeric, origlimitbal numeric, newhaslimit numeric, newlimitamt numeric, imode numeric) RETURN numeric;

	FUNCTION adjustdeductbalance(origdeductamt numeric, origdeductbal numeric, newdeductamt numeric, imode numeric) RETURN numeric;

				

	-- routines for creating DEPLIMIT records from the given info (POLRANGE or Coverage Ids); E142886.8

	PROCEDURE createdeplimitfromcoverage(IN polinsid numeric, IN newpolicyid numeric, IN oldpolicyid numeric, IN childcoverage numeric, IN adultcoverage numeric, IN youngadultcoverage numeric, IN imode numeric);

	PROCEDURE createdeplimitfrompolrange(IN polinsid numeric, IN newpolicyid numeric, IN oldpolicyid numeric, IN imode numeric);

			

			

	-- B65979 routines for category and item limits

	-- B80125 - changed to be by policy

	PROCEDURE insertcatlimits(IN patientid numeric, IN policyholder numeric, IN policyid numeric); 

	PROCEDURE insertitemlimits(IN patientid numeric, IN policyholder numeric, IN policyid numeric); 

	PROCEDURE insertcatlimitsusingtempl(IN patientid numeric, IN policyholder numeric, IN policyid numeric); 

	PROCEDURE insertitemlimitsusingtempl(IN patientid numeric, IN policyholder numeric, IN policyid numeric); 

	

	-- B69753 merge routine for EMPLOYER 

	PROCEDURE employermergeprocess(IN pstation numeric, IN puser numeric);

	-- B69753 merge routine for all EMPLOYER's having similar info as EmployerRec passed in

	PROCEDURE mergedistinctemployer(IN e employerrectyp, IN pstation numeric, IN puser numeric, IN auditid numeric, IN sharedentryid numeric);

	-- B69753 routine for merging the two given EMPLOYER records

	PROCEDURE mergeemployer(IN masteremployerid numeric, IN employerid numeric, IN pstation numeric, IN puser numeric, IN auditid numeric, IN sharedentryid numeric);

	

	

	-- E72587 - routines to add a policy	

	-- S87161 - option to add dependents

	-- B116767 - option to ensure depenants match original policy (for renew or transfer)

	PROCEDURE addpolicy(IN holderid numeric, IN familyid numeric, IN polinsid numeric, IN subscribernum character varying, IN startdate timestamp without time zone, IN enddate timestamp without time zone, IN userid numeric, IN stationid numeric, IN adddepends numeric, IN origpolicyid numeric, OUT policyid numeric);	

   -- E72587 - routine to hook a patient up to his guarantor's policies				

	-- B101882 option to control how PTDEPEND.IsCovered is set

	PROCEDURE addguarantordependant(IN guarantorid numeric, IN patientid numeric, IN relationship numeric, IN userid numeric, IN stationid numeric, IN iscovered numeric DEFAULT polins_pkg.ptdependiscoveredyes);

	-- E72587 - routine to hook a patient up as a dependant for a policy

	-- B101882 option to control how PTDEPEND.IsCovered is set

	PROCEDURE addpolicydependant(IN policyid numeric, IN guarantorid numeric, IN patientid numeric, IN haspatientlimit numeric, IN patientlimit numeric, IN patientdeduct numeric, IN relationship numeric, IN userid numeric, IN stationid numeric, IN iscovered numeric DEFAULT polins_pkg.ptdependiscoveredyes);

	-- E72587 - routine to add a patient employer

	PROCEDURE addpatientemployer(IN patientid numeric, IN employerid numeric, IN isprimary numeric, IN userid numeric, IN stationid numeric);

	

	-- E72587 - routines to calculate the deductible balance for a new policy

	FUNCTION getfamilydeductbalance(deduct numeric, patientid numeric, company character, yeresetdate timestamp without time zone) RETURN numeric;

	FUNCTION getpatientdeductbalance(deduct numeric, patientid numeric, policyid numeric) RETURN numeric;

	FUNCTION getwaivedualdeductbalance(deductmode numeric, deduct numeric, patientid numeric, yeresetdate timestamp without time zone, parentcompany character) RETURN numeric;



	-- B80493 added				

	FUNCTION getdeductchargedtopatientsofar(patientid numeric, policyid numeric) RETURN numeric;

	

	-- E79752.5 added				

	FUNCTION getdeductchargedtofamilysofar(policyid numeric) RETURN numeric;

				

				

	-- E72598 - procedure to add policies to a renewed benefit plan

	PROCEDURE renewpolicies(IN oldpolins numeric, IN newpolins numeric, IN newpolinsstartdate timestamp without time zone, IN userid numeric, IN stationid numeric);

		

	--B143420.3 -- added procedure to clone riders

	PROCEDURE clonepolicyriders(IN oldpolins numeric, IN newpolins numeric);

	

	-- E72598 - function to calculate a policy's year end reset date for the current year

	FUNCTION getyeresetdate(polinsrec polins) RETURN timestamp without time zone;

	

	-- E68448 - procedure to transfer all policies from one benefit plan to another

	-- E99167 - added KeepSubscriberNum

	PROCEDURE transferpolicies(IN oldpolins numeric, IN newpolins numeric, IN effectivedate timestamp without time zone, IN keepsubscribernum numeric, IN userid numeric, IN stationid numeric);

    

  -- B123401

  FUNCTION isinsurancenetworkeligibility(edicode2 character) RETURN numeric;

	

END;
CREATE OR REPLACE PACKAGE pportal_pkg IS

  PROCEDURE loginuser(IN vusername character varying, IN vpassword character varying, IN vwindowinminutes integer, IN vmaxattempts integer, IN vterminal character varying, OUT visvalid integer, OUT visagreed integer, OUT vistemp integer, OUT viuser integer);
  PROCEDURE loginiuser(IN viuser numeric, IN vwindowinminutes numeric, IN vmaxattempts numeric, IN vterminal character varying, OUT visvalid numeric, OUT visagreed numeric, OUT vistemp numeric, OUT vusername character varying);
  PROCEDURE logoutuser(IN vusername character varying, IN vterminal character varying);
  PROCEDURE updateusercredentials(IN vusername character varying, IN voldusername character varying, IN vcurrentpassword character varying, IN vnewpassword character varying, IN vquestion1 integer, IN vquestion2 integer, IN vquestion3 integer, IN vanswer1 character varying, IN vanswer2 character varying, IN vanswer3 character varying, OUT vstatus integer);
  PROCEDURE usercrednoques(IN vusername character varying, IN voldusername character varying, IN vcurrentpassword character varying, IN vnewpassword character varying, OUT vstatus integer);
  PROCEDURE updatesecquesbyiuser(IN viuser integer, IN vquestion1 integer, IN vquestion2 integer, IN vquestion3 integer, IN vanswer1 character varying, IN vanswer2 character varying, IN vanswer3 character varying, OUT vstatus integer);

  PROCEDURE ilogentry(IN vusername character varying, IN vaction numeric, IN vdate timestamp without time zone, IN vtime numeric, IN vterminal character varying, IN viuser numeric);
  PROCEDURE incrementfailedpassword(IN viuser numeric, IN vattemptcount numeric, IN vattemptdate timestamp without time zone, IN vattempttime numeric, IN vwindowinminutes numeric, IN vmaxattempts numeric);
  PROCEDURE getnextattempt(IN viuser numeric, IN vattemptdate timestamp without time zone, IN vattempttime numeric, IN vwindowinminutes numeric, IN vmaxattempts numeric, INOUT vlockaccount numeric, INOUT vnewcount numeric, INOUT vnewdate timestamp without time zone, INOUT vnewtime numeric);

  PROCEDURE getencryptionmethod(OUT vencryptionmethod integer);
  PROCEDURE getauditlogging(OUT vauditlogging integer);

  PROCEDURE setpaversion(IN vversion character varying);
  PROCEDURE getpsetting(IN vkey character varying, OUT visetting integer, OUT vvalue character varying);
  PROCEDURE setpsetting(IN vkey character varying, IN vvalue character varying);
  PROCEDURE addpsetting(IN vkey character varying, IN vtype integer, IN vgroup integer, IN vpriority integer, IN vvalue character varying, IN vdescription character varying);

  --41549221
  PROCEDURE checkifonlyactiveinspolicy(IN vpatientid integer, OUT vpolicyid integer);

  --33514707
  PROCEDURE getinspolicylist(IN vpatientid integer, OUT vresult cursor_pkg.weakcursor);
  PROCEDURE getinspolicydetail(IN vpolicyid integer, OUT vresult cursor_pkg.weakcursor);
  PROCEDURE getinspolicyuserlist(IN vpolicyid integer, OUT vresult cursor_pkg.weakcursor);

  --AX-30143
  PROCEDURE updatecorrectstatus(IN vpolicyid integer, IN vpatient numeric, IN vstatus numeric);
  PROCEDURE getcorrectstatus(IN vpoliciesid character varying, OUT vresult cursor_pkg.weakcursor);

  --33514727
  PROCEDURE checkstickynote(IN vtype integer, IN vpatientid integer, IN vsecondaryid integer, OUT vexist integer);
  PROCEDURE checkstickynotebysecondarylist(IN vtype integer, IN vpatientid integer, IN vsecondaryidlist character varying, OUT vresult cursor_pkg.weakcursor);
  PROCEDURE createstickynote(IN vtype integer, IN vpatientid integer, IN vsecondaryid integer, IN vmessage character varying, IN vupdateifexist integer, IN vcreationuser integer);
  PROCEDURE deletestickynote(IN vtype integer, IN vpatientid integer, IN vsecondaryid integer);

  --29203967
  PROCEDURE setilogentry(IN vusername character varying);
  PROCEDURE userresetpassword(IN vusername character varying, IN vpassword character varying, OUT vstatus integer);

  --36889047
  PROCEDURE createaudithis(IN vuser numeric, IN vtablename character, IN vhistorytype numeric, OUT vaudithis numeric);

  -- 59160046
  PROCEDURE updateuserinaudithis(IN vuser numeric, IN vaudithis numeric, OUT vresult integer);

  --36198601
  PROCEDURE getinspolicylimitanddeductlist(IN vpolicyid integer, IN vpatient integer, OUT vresult cursor_pkg.weakcursor);

  --36732337
  PROCEDURE updateiuserpwh(IN viuser numeric, IN vpassword character varying, OUT vuserpwhid numeric);

  --38103735
  PROCEDURE getsecurityquestionsanswers(IN vpatientid integer, OUT vresult cursor_pkg.weakcursor);

  --38051723
  FUNCTION getaffectfamily(vcoverageid integer, vpolins integer, vid integer, vcategory character varying) RETURN integer;
  FUNCTION gethaslimit(vcoverageid integer, vpolins integer, vid integer, vcategory character varying) RETURN integer;

  --36732337
  PROCEDURE validateusercredentials(IN vusername character varying, IN voldusername character varying, IN vcurrentpassword character varying, OUT vstatus integer);

  -- 41655511
  PROCEDURE getpatientiuserbyusername(IN vusername character varying, OUT vresult cursor_pkg.weakcursor);

  -- 59797918 Get Patient and IUser infro by iUser Id
  PROCEDURE getpatientiuserbyiuser(IN viuser integer, OUT vresult cursor_pkg.weakcursor);
	
  -- 41655511
  PROCEDURE updatepatientinfo(IN vpatientid integer, IN vlast character varying, IN vfirst character varying, IN vprefered character varying, IN vmiddle character varying, IN vtitle character varying, IN vbirth timestamp without time zone, IN vaddress1 character varying, IN vaddress2 character varying, IN vcity character varying, IN vprovince character varying, IN vpostal character varying, IN vcountry character varying, IN vaddressother character varying, IN vhomearea character varying, IN vhomephone character varying, IN vworkarea character varying, IN vworkphone character varying, IN vworkext character varying, IN votherarea character varying, IN votherphone character varying, IN votherext character varying, IN vmobilearea character varying, IN vmobilephone character varying, IN vcontactat character varying, IN vcontacttime character varying, IN vemail character varying, IN vinfonotify integer, IN vaudit integer, IN vpreflang character varying, IN vraceethdeclined integer, IN vethnic character varying, IN vcustom1 character varying, IN vcustom2 character varying, IN vcustom3 character varying, IN vcustom4 character varying, IN vcustom5 character varying, IN vcustom6 character varying, IN vcustom7 character varying, IN vcustom8 character varying, IN vcustom9 character varying, IN vcustom10 character varying, IN vcustomtext1 character varying, IN vcustomtext2 character varying, IN vcustomtext3 character varying, IN vcustomtext4 character varying, IN vcustomtext5 character varying, IN vemerglast character varying, IN vemergfirst character varying, IN vemergmiddle character varying, IN vemergaddress character varying, IN vemergaddress2 character varying, IN vemergcity character varying, IN vemergprovince character varying, IN vemergpostal character varying, IN vemergaddressother character varying, IN vemergarea character varying, IN vemergphone character varying, IN vemergext character varying, IN vemergrelation character varying, IN vemergaltarea character varying, IN vemergaltphone character varying, IN vemergaltext character varying, OUT vresult integer);

  -- 38115205
  PROCEDURE createiuserwithnamepassword(IN vtype numeric, IN vid numeric, IN vusername character varying, IN vpassword character varying, IN vaudit numeric, IN vquestion1 integer, IN vquestion2 integer, IN vquestion3 integer, IN vanswer1 character varying, IN vanswer2 character varying, IN vanswer3 character varying, OUT viuser numeric);

  -- 38115205
  PROCEDURE addiformtopatient(IN vpatient numeric, IN vformcode character varying, IN vpfrom numeric, IN viuser numeric, IN vaccess integer, IN vorder integer, IN vreqattention integer, OUT viptform numeric);

  -- 49217375
  PROCEDURE getusernamebyid(IN vuser integer, OUT vresult cursor_pkg.weakcursor);

  -- 52499031 Get Language fields from LANGCD table by Language Code
  PROCEDURE getlanguagebylangcd(IN vlangcd character varying, OUT vresult cursor_pkg.weakcursor);

  -- 52499031 Get Languages fields from LANGCD table by Language Code List
  PROCEDURE getlanguagesbylangscd(IN vlangcdlist character varying, OUT vresult cursor_pkg.weakcursor);

  -- 52499051 Get Active Languages from LANGCD table
  PROCEDURE getactivelanguages(OUT vresult cursor_pkg.weakcursor);

  -- 52498863 Get Ethnicity fields from ETHNIC table
  PROCEDURE getethnicitybyethnic(IN vethnic character varying, OUT vresult cursor_pkg.weakcursor);

  -- 52499005 Get Active Ethnicity from ETHNIC table
  PROCEDURE getactiveethnicity(OUT vresult cursor_pkg.weakcursor);

  -- 52498815 GetRaces from RACE table for a Patient
  PROCEDURE getracesbypatient(IN vpatient character varying, OUT vresult cursor_pkg.weakcursor);

  -- 52498835 GetRaces active from RACE table
  PROCEDURE getraces(OUT vresult cursor_pkg.weakcursor);

  -- 52498835 Get Race by Race field from RACE table
  PROCEDURE getracebyrace(IN vrace character, OUT vresult cursor_pkg.weakcursor);

  -- 52498815 GetPatient Races from PTRACE table by PatientId
  PROCEDURE getpatientracesbypatient(IN vpatient character varying, OUT vresult cursor_pkg.weakcursor);

  -- 52498815 GetPatient Active Races from PTRACE table by PatientId
  PROCEDURE getpatientactiveracesbypatient(IN vpatient character varying, OUT vresult cursor_pkg.weakcursor);
  -- 52498815 Update Patient Race Informationin PTRACE table
  PROCEDURE updatepatientrace(IN vpatient numeric, IN vrace character, IN vdeleted numeric, IN vaudit numeric);

 -- 52498815 Insert Patient Race Informationin PTRACE table
  PROCEDURE addpatientrace(IN vpatient numeric, IN vrace character, IN vdeleted numeric, IN vaudit numeric);

  -- 59797918 Get all patients for a Guarantor by iUser
  PROCEDURE getguarantorpatientbyiuser(IN viuser integer, OUT vresult cursor_pkg.weakcursor);

  -- 60293906 Get all Guarantors for a Patient by iUser
  PROCEDURE getpatientguarantorsbyiuser(IN vpatient integer, IN viuser integer, OUT vresult cursor_pkg.weakcursor);

  -- 63762608 Get Audit Hash Value
  PROCEDURE getaudithashvalue(IN npatientid numeric, IN ddate timestamp without time zone, IN nuserid numeric, IN nstationid numeric, IN nactiontype numeric, IN ctablename character varying, IN cprimaryinfo character varying, IN cadditionalinfo character varying, IN csecretkey character varying, OUT vhashvalue character varying);

  -- 60293906 Get AuditLog Activity
  PROCEDURE getauditlogactivity(IN vpatient integer, IN viuser integer, IN vbegindate timestamp without time zone, IN venddate timestamp without time zone, IN vactionadd integer, IN vactionedit integer, IN vactiondelete integer, IN vactionview integer, IN vactionprint integer, IN vactioncopy integer, IN vactionpreview integer, IN vorderby character varying, IN vitemsperpage integer, INOUT vpage integer, OUT vtotalpages integer, OUT vresult cursor_pkg.weakcursor);

  -- 60293906 Get Total AuditLog Activity for the guarantors of a patient
  PROCEDURE gettotalactivityforguarantor(IN vpatient integer, IN viuserpatient integer, OUT vtotalactivityforguarantor integer);

  -- 52498721 Get custom code field name
  PROCEDURE getcusttype(IN vtype integer, OUT vresult cursor_pkg.weakcursor);
  PROCEDURE getcusttypebytypes(IN vtypes character varying, OUT vresult cursor_pkg.weakcursor);

  -- 52498721 Map custom code to description
  PROCEDURE getcustcode(IN vtype integer, IN vcode character varying, OUT vresult cursor_pkg.weakcursor);

  -- 52498757 Get all cust codes for this custtype
  PROCEDURE getcustcodes(IN vtype integer, OUT vresult cursor_pkg.weakcursor);
  PROCEDURE getcustcodesbytypes(IN vtypes character varying, OUT vresult cursor_pkg.weakcursor);

  -- 58348032 Create Landing pages
  PROCEDURE gettemplatelist(OUT vresult cursor_pkg.weakcursor);
  PROCEDURE gettemplatebyid(IN vtemplateid integer, OUT vresult cursor_pkg.weakcursor);
  PROCEDURE getpagelist(OUT vresult cursor_pkg.weakcursor);
  PROCEDURE addpage(IN vtypeid integer, OUT vresult cursor_pkg.weakcursor);
  PROCEDURE getfirstpage(OUT vresult cursor_pkg.weakcursor);
  PROCEDURE getfirstpagefirstaccess(OUT vresult cursor_pkg.weakcursor);
  PROCEDURE getpagebyid(IN vpageid integer, OUT vresult cursor_pkg.weakcursor);
  PROCEDURE getpagebytype(IN vtypeid integer, OUT vresult cursor_pkg.weakcursor);
  PROCEDURE updatepage(IN vpageid integer, IN vname character varying, IN vactive integer, IN vrestricted integer, IN vparentid integer, IN vpriority numeric, IN vtemplateid integer, IN vhiderepresent integer, IN vfirstaccess integer, OUT vresult integer);


  PROCEDURE addpagecontent(IN vpageid integer, IN vname character varying, OUT vresult cursor_pkg.weakcursor);
  PROCEDURE getpagecontentlist(IN vpageid integer, OUT vresult cursor_pkg.weakcursor);
  PROCEDURE getpagecontentbyid(IN vcontentid integer, OUT vresult cursor_pkg.weakcursor);
  PROCEDURE updatepagecontenttype(IN vcontentid integer, IN vtype integer, OUT vresult integer);
	
  -- 69495402 Add log record for Ambulatory summary CCDA. Insert in PACCDA table
	PROCEDURE insertpaccda(IN npatientid numeric, IN nuserid numeric, IN nactiontype numeric);

  -- AX-18952
  PROCEDURE getdocumentsattached(IN vpatient integer, IN vorderby character varying, IN vitemsperpage integer, INOUT vpage integer, OUT vtotalpages integer, OUT vresult cursor_pkg.weakcursor);
  PROCEDURE getdocinptletterbyid(IN vid integer, OUT vresult cursor_pkg.weakcursor);
  PROCEDURE getdocincontractbyid(IN vid integer, OUT vresult cursor_pkg.weakcursor);

  --AX-28119 added ability to add Online request and request patient info; AX-29370 kept ONLINE_PATIENT parameter for backward compatibility
  PROCEDURE createonlinerequest(IN pvonlinereq online_request, IN pvonlinepatobsolete online_patient, OUT presult integer);

  PROCEDURE updategenderinfo(IN vpatientid integer, IN vaudit integer, IN vptsexorient integer, IN vptsother character varying, IN vptsdeclined integer, IN vptgenderid integer, IN vptgother character varying, IN vptgdeclined integer, IN vptpreferpronouns integer, IN vptpronounsother character varying, IN vptpronounsdeclined integer, IN vupdatesexorient integer, IN vupdategender integer, IN vupdatepronouns integer, IN vsex integer, OUT vresult integer);

END;
CREATE OR REPLACE PACKAGE pps_pkg IS

  FUNCTION getptpps(patientid numeric, quadrant numeric) RETURN numeric;  -- AX-24597

  FUNCTION getptppsbydate(chartdate timestamp without time zone, patientid numeric, quadrant numeric) RETURN numeric;-- AX-24597

  FUNCTION isppscode1(ptperioid numeric, quadrant numeric) RETURN boolean; -- AX-24597

  FUNCTION isppscode2(ptperioid numeric, quadrant numeric) RETURN boolean; -- AX-24597

  FUNCTION isppscode3(ptperioid numeric, quadrant numeric) RETURN boolean; -- AX-24597

END;
CREATE OR REPLACE PACKAGE psr_pkg IS

  FUNCTION getptpsr(patientid numeric, sextant numeric) RETURN numeric;

  FUNCTION getptpsrbydate(chartdate timestamp without time zone, patientid numeric, sextant numeric) RETURN numeric; -- AX-24528.2

  FUNCTION iscode4(ptperioid numeric, sextant numeric) RETURN boolean;

  FUNCTION iscode3(ptperioid numeric, sextant numeric) RETURN boolean;

  FUNCTION iscode2(patientid numeric, ptperioid numeric, sextant numeric) RETURN boolean;

  FUNCTION iscode1(patientid numeric, ptperioid numeric, sextant numeric) RETURN boolean;

END;
CREATE OR REPLACE PACKAGE ptsumm_pkg IS
	PROCEDURE updateptsummaries();
	
	-- B82709
	PROCEDURE calculateptsummaries(IN patientid numeric, IN userid numeric);
	PROCEDURE calculatecariesrisk(IN patientid numeric, IN userid numeric);
	PROCEDURE calculateperiorisk(IN patientid numeric, IN userid numeric);
	PROCEDURE updatesummaryrec(IN patientid numeric, IN userid numeric, IN vsummcode character varying, IN vnewval1 character varying, IN vnewval2 character varying);
	-- add new routines here...

	-- E73070.3	added
	PROCEDURE updaterecalldrflag(IN patientid numeric, IN flag numeric);
	PROCEDURE updaterecallhygflag(IN patientid numeric, IN flag numeric);
	
	FUNCTION createauditrec(type numeric, userid numeric) RETURN numeric;
	
	-- If Value1 and/or Value2 are limited to pre-defined values,
	-- modify these fns accordingly...
	FUNCTION getvalue1strings(summcode character varying) RETURN character varying;
	FUNCTION getvalue2strings(summcode character varying) RETURN character varying;	
END;
CREATE OR REPLACE PACKAGE qrda_cfg_pkg IS

/**
* Returns the name of the sending application for CDC Immunization HL7 messages.<p/>
* @return The name of the sending application for CDC Immunization HL7 messages.<p/>
*/
FUNCTION getsendingapp() RETURN character varying;

/**
* Returns the name of the sending facility for CDC Immunization HL7 messages.<p/>
* @return The name of the sending facility for CDC Immunization HL7 messages.<p/>
*/
FUNCTION getsendingfac() RETURN character varying;

/**
* Returns the name of the Sending Application to use of Public Health Surveillance HL7 messages.
* @return The name of the Sending Application to use of Public Health Surveillance HL7 messages.
*/
FUNCTION getphssendingapp() RETURN character varying;

/**
* Returns the OID (Object Identifier) associated with the Sending Application.
* @return The OID (Object Identifier) associated with the Sending Application.
*/
FUNCTION getphssendingappoid() RETURN character varying;

/**
* Returns the name of the Sending Facility to use of Public Health Surveillance HL7 messages.
* @return The name of the Sending Facility to use of Public Health Surveillance HL7 messages.
*/
FUNCTION getphssendingfac() RETURN character varying;

/**
* Returns the OID (Object Identifier) associated with the Sending Facility.
* @return The OID (Object Identifier) associated with the Sending Facility.
*/
FUNCTION getphssendingfacoid() RETURN character varying;

/**
* Returns the name of the sending system for use in ASTM CCR clinical summaries (this is the ActorID for the From tag). <p/>
* @return The name of the sending system for use in ASTM CCR clinical summaries. <p/>
*/
FUNCTION getfromactorid() RETURN character varying;

/**
* Returns the Oracle DIRECTORY object that PQRI XML messages are saved to.<p/>
* @return The name of the DIRECTORY object where PQRI XML messages are saved to.<p/>
*/
FUNCTION getqrdaxmlexportdir() RETURN character varying;


/**
* Creates an QRDA Type I .XML file for any given patient and returns it as a CLOB to MUD
* @return The error code indicated success or failurI. 0 = Success, anything else = Failure
*/
PROCEDURE qrda_type1_xml(IN vproducer character, IN vpatient numeric, IN vreportingyear numeric, IN vmeasure character varying, OUT verror integer, OUT voutputfile clob);


/**
* Creates an QRDA Type III .XML file for the selected CQMs and returns it as a CLOB to MUD
* @return The error code indicated success or failurI. 0 = Success, anything else = Failure
*/
PROCEDURE qrda_type3_xml(IN vproducer character, IN vreportingyear numeric, IN vcqm22 numeric, IN vcqm50 numeric, IN vcqm68 numeric, IN vcqm69 numeric, IN vcqm74 numeric, IN vcqm75 numeric, IN vcqm124 numeric, IN vcqm125 numeric, IN vcqm127 numeric, IN vcqm130 numeric, IN vcqm138 numeric, IN vcqm147 numeric, IN vcqm155 numeric, IN vcqm156 numeric, IN vcqm165 numeric, OUT verror integer, OUT voutputfile clob);

PROCEDURE qrda_type1_stage3_xml_p(IN pproducer character, IN ppatient numeric, IN pyear numeric, INOUT perror integer, INOUT poutputfile clob);

PROCEDURE qrda_type3_stage3_xml_p(IN pproducer character, IN pyear numeric, IN piscqm22 integer, IN piscqm68 integer, IN piscqm74 integer, IN piscqm75 integer, IN piscqm127 integer, IN piscqm138 integer, IN piscqm147 integer, IN piscqm156 integer, INOUT perror integer, INOUT poutputfile clob);

END;
CREATE OR REPLACE PACKAGE sched_pkg IS



	FUNCTION dateiswithincycle(cycletype numeric, cyclecnt numeric, cyclestart timestamp without time zone, cyclefrq numeric, targetdate timestamp without time zone) RETURN numeric;

			

	FUNCTION iswithinweeklycycle(cyclecnt numeric, cyclestart timestamp without time zone, targetdate timestamp without time zone) RETURN numeric;

		

	FUNCTION iswithinmonthlycycle(cyclecnt numeric, cyclestart timestamp without time zone, cyclefrq numeric, targetdate timestamp without time zone) RETURN numeric;

			

	FUNCTION islastweekofmonth(targetdate timestamp without time zone) RETURN numeric;

			

	FUNCTION getweekofmonth(targetdate timestamp without time zone) RETURN numeric;

	

	-- E54655

	FUNCTION getmaxschdate(txtype numeric, txid numeric, txtreatment numeric, excludeapptid numeric) RETURN timestamp without time zone;

      

	-- E98324

	FUNCTION isreserveavailable(rreserve numeric, rdate timestamp without time zone, rchair numeric, rstart numeric, rend numeric, rprovider character, duration numeric, apptcode character) RETURN numeric;

			

	-- E37995.22   

	FUNCTION getapptrx(appointment numeric) RETURN character;

			

	PROCEDURE removefromwaitlist(IN nappointmentid numeric, IN nuser numeric, IN nstationid numeric, IN naudit numeric);



	-- E100080

	FUNCTION requiresstartchk(nappointmentid numeric) RETURN numeric;

			

	FUNCTION requirestrxstartchk(nappointmentid numeric, cprocedure character) RETURN numeric;

	

	-- E131368

	FUNCTION getwaitdays(nappointmentid numeric) RETURN numeric;		

			

	-- AX-17107.17477d			

	FUNCTION appointhasunapprovedwaste(nappointmentid numeric, nuser numeric) RETURN numeric;



	-- AX-17559.18658c		

	FUNCTION appointproviderhasunapproved(nappointmentid numeric, nuser numeric) RETURN numeric;

			

END;
CREATE OR REPLACE PACKAGE slevel_pkg IS

  PROCEDURE add_extra(IN slevel numeric);
  PROCEDURE copy_extra(IN newslevel numeric, IN oldslevel numeric);
  PROCEDURE delete_extra(IN slevel numeric);


END;
CREATE OR REPLACE PACKAGE split_pkg IS



  TYPE estimate_record IS RECORD (estimate numeric);

  TYPE estimate_type IS REF CURSOR RETURN estimate_record;



  FUNCTION trx_estimate(trxtype numeric, trxid numeric, trxtreatment numeric, bindingquote numeric, billmethod numeric, calculateowing numeric, provider character, frompayment numeric) RETURN numeric;



  FUNCTION appoint_estimate(appointment numeric, bindingquote numeric, billmethod numeric, calculateowing numeric, frompayment numeric) RETURN numeric;

  

  -- E80113

  FUNCTION get_feedates(fee character, asofdate timestamp without time zone) RETURN numeric;



END;
CREATE OR REPLACE PACKAGE swipepin_pkg IS
	FUNCTION isvalidpin("PIN" character varying) RETURN numeric;
	FUNCTION geterrorstr(errnum numeric) RETURN character varying;
END;
CREATE OR REPLACE PACKAGE treatme2_pkg IS
	-- E135970.19
  FUNCTION display_code(pcodeid numeric) RETURN character;
  FUNCTION display_date(pdate numeric) RETURN timestamp without time zone;
  FUNCTION display_site(psite numeric) RETURN character;
  FUNCTION surface_b_or_f(psite numeric) RETURN character;
  FUNCTION surface_o_or_i(psite numeric) RETURN character;
  FUNCTION display_surface(psite numeric, psurface numeric) RETURN character;
END;
CREATE OR REPLACE PACKAGE trx_pkg IS



	v_ndenticaltxgroupallowed numeric DEFAULT 0;						--AX-20838.20911b

	v_hascustomisnonclinicaltx numeric DEFAULT -1;						--AX-32573



-- AX-20838.20911b

PROCEDURE setdenticaltxgroupallowed(IN nfunctionallowed numeric);



FUNCTION hasstickynote(notetype numeric, id numeric, treatment numeric) RETURN numeric;

  

FUNCTION hastrxstickynote(id numeric, treatment numeric) RETURN numeric;



PROCEDURE initializetrx(INOUT row_trx trx); 



PROCEDURE adddefaultmissedapptcharge(INOUT row_trx trx, IN num_clinic numeric, IN char_producer character, IN num_cancelfailtype numeric); 



PROCEDURE inserttrx(IN row_trx trx); 

  

  -- AX-12108.19496

  PROCEDURE addlockboxpayment(IN chartno character, IN pmtcode character, IN bank character, IN description character varying, IN edipat character, IN audituser numeric, IN auditstation numeric, IN paymentdate timestamp without time zone, IN amountincents numeric, IN practice numeric, OUT trxid numeric);



PROCEDURE inserthistory(IN row_trx trx); 



PROCEDURE addnontaxableofficecharge(INOUT row_trx trx, IN num_clinic numeric, IN char_producer character, IN num_cancelfailtype numeric);



FUNCTION checkaddvisitfeetotrxandhist(INOUT row_trxvisitfee trx, nvisitfee numeric, noperation numeric, OUT ntotal numeric, OUT nerror numeric) RETURN numeric;

                                                                                

PROCEDURE addvisitfee(IN nid numeric, IN ntreatment numeric, IN noperation numeric, IN nintotalcents numeric, OUT nresult numeric, OUT nouttotal numeric, OUT nerror numeric); 

                                                                                

PROCEDURE processvisitfee(IN nid numeric, IN ntreatment numeric, IN noperation numeric, OUT nresult numeric); 



FUNCTION checkparentinsurance(nid numeric, company1 character, company2 character, company3 character) RETURN numeric; 



FUNCTION get_visit_fee(nvisitfee numeric, npolins numeric, szproducer character) RETURN numeric;                                                                  



PROCEDURE checktodeletevisitfee(IN nid numeric, IN ntreatment numeric, IN noperation numeric, OUT nresult numeric);



FUNCTION isnonclinicaltx(code character) RETURN numeric;

  

FUNCTION getnonclinicaltx() RETURN character varying;

  

FUNCTION shouldaddproctoclaim(insco character, code character) RETURN numeric;

  

FUNCTION getdefaultclaimdoctor(num_clinic numeric) RETURN character varying;

  

PROCEDURE adddefaultpolicies(INOUT row_trx trx);

  

FUNCTION iscvgonbirth(age numeric, birthdate timestamp without time zone, coverageage numeric, cvgonbirth numeric) RETURN boolean;



FUNCTION getnonclinicaltotal(patient numeric, code character) RETURN numeric;

  

FUNCTION getdiagdesc(charttrx numeric) RETURN character varying;

  

PROCEDURE addcharge(IN patient numeric, IN practice numeric, IN claimdoctor character, IN dtmonth numeric, IN dtday numeric, IN dtyear numeric, IN producer character, IN code character, IN description character varying, IN totalcents numeric, IN discipline character, IN custom1 character, IN custom2 character, IN userid numeric, IN entryuser numeric, IN stationid numeric, OUT nerror numeric);



  

PROCEDURE addmissedapptcharge(INOUT row_trx trx, IN num_clinic numeric, IN char_producer character, IN num_cancelfailtype numeric, IN char_chargecode character);

    

--E135338 added to determine if include $0 in claim submission for the given ins co.

FUNCTION shouldsubmitzeroproc(insco character) RETURN numeric;

  

--E136353 added to determine the patient charge method to use for the given insurance co.

FUNCTION getpatientchargemethod(insco character) RETURN numeric;



-- AX-2180.2923	added to determine the patient charge method for the given insurance co  	 	

--						and procedure code (in case of dual coverage under same company  

FUNCTION getptchargemethodforproc(insco character, usercode character) RETURN numeric;





  

--E136761 added to determine if using ins adjusted amount as ins paid amount for the given insurance co.

FUNCTION useadjustamountaspaidamount(insco character) RETURN numeric;

  

-- E136559	added to determine if the given ins co. cares if there're other PPO policies

FUNCTION needtouseppofeeifapplcable(policyid numeric) RETURN numeric;



-- E136559	added to determine if the given ins co. is PPO

FUNCTION isppoinsurancepolicy(policyid numeric) RETURN numeric;



--	B136211	added to handle undefined procedure for EDI 5010 claim

FUNCTION isundefinedprocedurecode(insco character, usercode character, inscode character) RETURN character varying;



  -- AX-2999.3727 - determine invoice payment due date, AX-2999.3743b

  FUNCTION getinvoicepmtduedate(patientid numeric, invoicedate timestamp without time zone, defaultduedays numeric) RETURN timestamp without time zone;





-- AX-19219; AX-19450

FUNCTION getpreauthstatusforinsnumber(ntype numeric, nid numeric, ntreatment numeric, ninsnumber numeric, datefor timestamp without time zone) RETURN numeric;





-- AX-19450

FUNCTION getpreauthstatusforprimary(ntype numeric, nid numeric, ntreatment numeric, datefor timestamp without time zone) RETURN numeric;



-- AX-19450

FUNCTION getpreauthstatus(ntype numeric, nid numeric, ntreatment numeric, ninsnumber numeric, datefor timestamp without time zone, OUT nmultiins numeric) RETURN numeric;



  -- AX-28836.29971

  FUNCTION getsrpdateforclaim(npatientid numeric, ntype numeric, nid numeric, ninsco character) RETURN timestamp without time zone;







END;
CREATE OR REPLACE PACKAGE web_common_pkg IS

  PROCEDURE getaxiumpracticeminversion(OUT vversion character varying);


  PROCEDURE getaxiumpracticemaxversion(OUT vversion character varying);

END;
CREATE OR REPLACE PACKAGE web_epr_pkg IS

  PROCEDURE getrepresentativelist(IN vwebuserid integer, OUT vresult cursor_pkg.weakcursor);

  PROCEDURE getinternetformlist(IN vwebuserid integer, OUT vresult cursor_pkg.weakcursor);

  PROCEDURE getinternetformdetail(IN vwebuserid integer, IN vinternetformid integer, OUT vresult cursor_pkg.weakcursor);

  PROCEDURE getformdetail(IN vformid integer, OUT vresult cursor_pkg.weakcursor);

  PROCEDURE getformitemlist(IN vformid integer, OUT vresult cursor_pkg.weakcursor);

  PROCEDURE getformitemcolumnlist(IN vformitemid integer, IN vpatientformid integer, OUT vresult cursor_pkg.weakcursor);

  PROCEDURE getpatientformdetail(IN vptformid integer, OUT vresult cursor_pkg.weakcursor);

  PROCEDURE getpatientformitemlist(IN vptformid integer, OUT vresult cursor_pkg.weakcursor);

  PROCEDURE getpatientformitemcolumnlist(IN vformitemid integer, IN vpatientformid integer, OUT vresult cursor_pkg.weakcursor);

  PROCEDURE getanswerschemelist(IN vlistid character varying, OUT vresult cursor_pkg.weakcursor);

  PROCEDURE createpatientform(IN vinternetformid integer, IN vwebuserid integer, IN vfstatus character varying, OUT vpatientformid integer);

  PROCEDURE updatepatientform(IN vinternetformid integer);

  PROCEDURE updatepatientformcompletion(IN vinternetformid integer, IN vformstatus integer, IN vlastsavedpagenumber integer);

  PROCEDURE clearpformrequireattnflag(IN vinternetformid integer);								--AX-30362

  PROCEDURE savepatientformitem(IN vinternetformid integer, IN vformitemid integer, IN vcolumnid integer, IN vanswer character varying, IN vwebuserid integer, OUT vpatientitem integer);

  PROCEDURE archivepatientformitem(IN vinternetformid integer, IN vformitemid integer);

  PROCEDURE addpatientcolumn(IN vinternetformid integer, OUT vpatientcolumnid integer);

  PROCEDURE savepatientcolumn(IN vinternetformid integer, IN vformcolumnid integer, OUT vpatientcolumnid integer);

  PROCEDURE deletepatientcolumn(IN vinternetformid integer, IN vformcolumnid integer, IN vpatientcolumnid integer);

  PROCEDURE resetcolumnheader(IN vinternetformid integer, IN vformitemid integer, IN vwebuserid integer);

  PROCEDURE resetcolumnrow(IN vinternetformid integer, IN vformitemid integer, IN vwebuserid integer);

  PROCEDURE resetspreadsheet(IN vinternetformid integer, IN vformitemid integer, IN vwebuserid integer);

  

  FUNCTION getauditnumber(vformcode character, vpatient numeric, vpatientform numeric, vformitemid integer) RETURN numeric;

  FUNCTION getanswertext(vpatientformitemid integer) RETURN clob;

  FUNCTION getanswertext(vpatientformitemid numeric) RETURN clob;

  FUNCTION getdefaultcolumnarchived(vformcolumnid integer, vpatientformid integer) RETURN integer;

  FUNCTION getdefaultcolumnarchived(vformcolumnid numeric, vpatientformid integer) RETURN integer;

	

  PROCEDURE getdefaultfstatus(IN vinternetformid character varying, OUT vresult cursor_pkg.weakcursor);

	PROCEDURE createaudithis(IN vuser numeric, IN vtablename character, IN vhistorytype numeric, OUT vaudithis numeric);

	PROCEDURE createformaction(IN vpformid integer, IN vwebuserid integer, IN vfstatus character varying, OUT vformevt integer);

END;
CREATE OR REPLACE PACKAGE web_message_pkg IS

  /**

  Count number of unread messages in a folder for a given user. If folder id is not defined (-1), it counts messages in in-box and all folders.

  param: vUserId - User ID of the MSGSENT to check (MSGSENT.User)

  param: vFolderId - Folder ID of the MSGSENT to check (MSGSENT.UMsgFld). [-1: all; 0: in-box; 1+: folder]

  param: vCount - Number of messages counted

  */

  PROCEDURE countnewmsgs(IN vuserid integer, IN vfolderid integer, OUT vcount integer);

  

  /**

  Count number of unread messages in a folder for a given patient. If folder id is not defined (-1), it counts messages in in-box and all folders.

  Check Sender is not another patient 

  param: vUserId - User ID of the MSGSENT to check (MSGSENT.User)

  param: vFolderId - Folder ID of the MSGSENT to check (MSGSENT.UMsgFld). [-1: all; 0: in-box; 1+: folder]

  param: vCount - Number of messages counted

  */

  PROCEDURE countnewmsgspatient(IN vuserid integer, IN vfolderid integer, OUT vcount integer);



  /**

  Count number of unread urgent messages in a folder for a given user. If folder id is not defined (-1), it counts messages in in-box and all folders.

  param: vUserId - User ID of the MSGSENT to check (MSGSENT.User)

  param: vFolderId - Folder ID of the MSGSENT to check (MSGSENT.UMsgFld). [-1: all; 0: in-box; 1+: folder]

  param: vCount - Number of messages counted

  */

  PROCEDURE countnewurgmsgs(IN vuserid integer, IN vfolderid integer, OUT vcount integer);

  

  /** 

  Count number of messages in a folder for a given user. If folder id is not defined (-1), it counts messages in in-box and all folders. (49213409)

  param: vUserId - User ID of the MSGSENT to check (MSGSENT.User)

  param: vFolderId - Folder ID of the MSGSENT to check (MSGSENT.UMsgFld). [-1: all; 0: in-box; 1+: folder]

  param: vCount - Number of messages counted

  */

  PROCEDURE countmsgs(IN vuserid integer, IN vfolderid integer, OUT vcount integer);

  

  /** Count number of messages for Patients in a folder for a given user. If folder id is not defined (-1), it counts messages in in-box and all folders.

      Check Sender is not a patient

  param: vUserId - User ID of the MSGSENT to check (MSGSENT.User)

  param: vFolderId - Folder ID of the MSGSENT to check (MSGSENT.UMsgFld). [-1: all; 0: in-box; 1+: folder]

  param: vCount - Number of messages counted

  */

  PROCEDURE countmsgspatients(IN vuserid integer, IN vfolderid integer, OUT vcount integer);

  /**

  Retrieve a list of folders for a user.

  param: vUserId - User ID of the UMSGFLD to check (UMSGFLD.User)

  param: vResult - A weak cursor containing a list of folder data

  <li>UMsgFld: Folder ID

  <li>User: User ID

  <li>Folder: Folder Name

  <li>FolderType: Folder Type [0: In-box; 1: Out-box]

  */

  PROCEDURE getfolderlist(IN vuserid integer, OUT vresult cursor_pkg.weakcursor);

  

  /**

  Retrieve details of a folder.

  param: vFolderId - Folder ID of the UMSGFLD to check (UMSGFLD.UMsgFld)

  param: vResult - A weak cursor containing details of a folder

  <li>UMsgFld: Folder ID

  <li>User: User ID

  <li>Folder: Folder Name

  <li>FolderType: Folder Type [0: In-box; 1: Out-box]

  */

  PROCEDURE getfolderdetail(IN vfolderid integer, OUT vresult cursor_pkg.weakcursor);

  

  /**

  Retrieve a list of urgent messages for a user.

  param: vUserId - User ID of MSGSENT to check (MSGSENT.User)

  param: vStationId - Station ID needed to calculate correct date and time for messages (GetTimeZoneOffset.vStationId)

  param: vOrderBy - Order by keyword to sort the list by

  <li>Date: [DATE_ASC; DATE_DESC]

  <li>Name: [LASTNAME_ASC; LASTNAME_DESC; FIRSTNAME_ASC; FIRSTNAME_DESC]

  <li>Subject: [SUBJECT_ASC; SUBJECT_DESC]

  <li>Priority: [PRIORITY_ASC; PRIORITY_DESC]

  param: vItemsPerPage - Maximum number of items to get for a paginated list

  param: vPage - Current page number of a paginated list. Returns an updated page number does not match available page number

  param: vTotalPages - Maximum page number of a paginated list

  param: vResult - A weak cursor containing a list of message data

  <li>Message: Message ID

  <li>Date: Created date

  <li>Sender: Sender's User ID

  <li>SenderLastName: Sender's Last Name

  <li>SenderFirstName: Sender's First Name

  <li>SenderPreferredName: Sender's Preferred Name

  <li>SenderProdCode: Sender's Producer Code

  <li>SenderDeleted: Check if sender is deleted

  <li>Subject: Subject of the message

  <li>Recipients: String representation of all TO recipients

  <li>CCRecipients: string representation of all CC recipients

  <li>IsPriority: Check if message is urgent

  <li>Status: Status of the message [0: new; 1: read; 2: deleted]

  */

  PROCEDURE geturgmsglist(IN vuserid integer, IN vstationid integer, IN vorderby character varying, IN vitemsperpage integer, INOUT vpage integer, OUT vtotalpages integer, OUT vresult cursor_pkg.weakcursor);

  

  /**

  Retrieve a list of in-box messages for a user.

  param: vUserId - User ID of MSGSENT to check (MSGSENT.User)

  param: vFolderId - Folder ID of MSGSENT to check (MSGSENT.UMsgFld) [0: Inbox; 1+: folder]

  param: vStationId - Station ID needed to calculate correct date and time for messages (GetTimeZoneOffset.vStationId)

  param: vOrderBy - Order by keyword to sort the list by

  <li>Date: [DATE_ASC; DATE_DESC]

  <li>Name: [LASTNAME_ASC; LASTNAME_DESC; FIRSTNAME_ASC; FIRSTNAME_DESC]

  <li>Subject: [SUBJECT_ASC; SUBJECT_DESC]

  <li>Priority: [PRIORITY_ASC; PRIORITY_DESC]

  param: vItemsPerPage - Maximum number of items to get for a paginated list

  param: vPage - Current page number of a paginated list. Returns an updated page number does not match available page number

  param: vTotalPages - Maximum page number of a paginated list

  param: vResult - A weak cursor containing a list of message data

  <li>Message: Message ID

  <li>Date: Created date

  <li>Sender: Sender's User ID

  <li>SenderLastName: Sender's Last Name

  <li>SenderFirstName: Sender's First Name

  <li>SenderPreferredName: Sender's Preferred Name

  <li>SenderProdCode: Sender's Producer Code

  <li>SenderDeleted: Check if sender is deleted

  <li>Subject: Subject of the message

  <li>Recipients: String representation of all TO recipients

  <li>CCRecipients: string representation of all CC recipients

  <li>IsPriority: Check if message is urgent

  <li>Status: Status of the message [0: new; 1: read; 2: deleted]

  */

  PROCEDURE getinboxmsglist(IN vuserid integer, IN vfolderid integer, IN vstationid integer, IN vorderby character varying, IN vitemsperpage integer, INOUT vpage integer, OUT vtotalpages integer, OUT vresult cursor_pkg.weakcursor);

  

  /**

  Retrieve a list of out-box messages for a user.

  param: vUserId - User ID of MESSAGE to check (MESSAGE.Sender)

  param: vFolderId - Folder ID of MESSAGE to check (MESSAGE.UMsgFld) [0: Outbox; 1+: folder]

  param: vStationId - Station ID needed to calculate correct date and time for messages (GetTimeZoneOffset.vStationId)

  param: vOrderBy - Order by keyword to sort the list by

  <li>Date: [DATE_ASC; DATE_DESC]

  <li>Name: [TO_ASC; TO_DESC; CC_ASC; CC_DESC]

  <li>Subject: [SUBJECT_ASC; SUBJECT_DESC]

  <li>Priority: [PRIORITY_ASC; PRIORITY_DESC]

  param: vItemsPerPage - Maximum number of items to get for a paginated list

  param: vPage - Current page number of a paginated list. Returns an updated page number does not match available page number

  param: vTotalPages - Maximum page number of a paginated list

  param: vResult - A weak cursor containing a list of message data

  <li>Message: Message ID

  <li>Date: Created date

  <li>Sender: Sender's User ID

  <li>SenderLastName: Sender's Last Name

  <li>SenderFirstName: Sender's First Name

  <li>SenderPreferredName: Sender's Preferred Name

  <li>SenderProdCode: Sender's Producer Code

  <li>SenderDeleted: Check if sender is deleted

  <li>Subject: Subject of the message

  <li>Recipients: String representation of all TO recipients

  <li>CCRecipients: string representation of all CC recipients

  <li>IsPriority: Check if message is urgent

  <li>Status: Status of the message [0: new; 1: read; 2: deleted]

  */

  PROCEDURE getoutboxmsglist(IN vuserid integer, IN vfolderid integer, IN vstationid integer, IN vorderby character varying, IN vitemsperpage integer, INOUT vpage integer, OUT vtotalpages integer, OUT vresult cursor_pkg.weakcursor);

  

  /**

  Retrieve total messages and total unread messages

  param: vUserId - User ID of MSGSENT to check (MSGSENT.User)

  param: vFolderId - Folder ID of MSGSENT to check (MSGSENT.UMsgFld) [0: In-box; 1+: folder]

  param: vStationId - Station ID needed to calculate correct date and time for messages (GetTimeZoneOffset.vStationId)

  param: vTotalMsg - Total messages

  param: vTotalUnread - Total Unread messages

  */    

  PROCEDURE gettotalinboxpatientmsg(IN vuserid integer, IN vfolderid integer, IN vstationid integer, INOUT vtotalmsg integer, OUT vtotalunread integer);

  

  /**

  Retrieve a list of in-box messages for a patient. (No pagination)

  param: vUserId - User ID of MSGSENT to check (MSGSENT.User)

  param: vFolderId - Folder ID of MSGSENT to check (MSGSENT.UMsgFld) [0: In-box; 1+: folder]

  param: vStationId - Station ID needed to calculate correct date and time for messages (GetTimeZoneOffset.vStationId)

  param: vOrderBy - Order by keyword to sort the list by

  <li>Date: [DATE_ASC; DATE_DESC]

  <li>Name: [LASTNAME_ASC; LASTNAME_DESC; FIRSTNAME_ASC; FIRSTNAME_DESC]

  <li>Subject: [SUBJECT_ASC; SUBJECT_DESC]

  <li>Priority: [PRIORITY_ASC; PRIORITY_DESC]

  param: vResult - A weak cursor containing a list of message data

  <li>Message: Message ID

  <li>Date: Created date

  <li>Sender: Sender's User ID

  <li>SenderLastName: Sender's Last Name

  <li>SenderFirstName: Sender's First Name

  <li>SenderPreferredName: Sender's Preferred Name

  <li>SenderProdCode: Sender's Producer Code

  <li>SenderDeleted: Check if sender is deleted

  <li>Subject: Subject of the message

  <li>Recipients: String representation of all TO recipients

  <li>CCRecipients: string representation of all CC recipients

  <li>IsPriority: Check if message is urgent

  <li>Status: Status of the message [0: new; 1: read; 2: deleted]

  */  

  PROCEDURE getinboxpatientmsglist(IN vuserid integer, IN vfolderid integer, IN vstationid integer, IN vorderby character varying, IN vitemsperpage integer, INOUT vpage integer, OUT vtotalpages integer, OUT vresult cursor_pkg.weakcursor);

  

  /**

  Retrieve a list of out-box messages for a Patient. (No pagination)

  param: vUserId - User ID of MESSAGE to check (MESSAGE.Sender) - Patient

  param: vFolderId - Folder ID of MESSAGE to check (MESSAGE.UMsgFld) [0: Outbox; 1+: folder]

  param: vStationId - Station ID needed to calculate correct date and time for messages (GetTimeZoneOffset.vStationId)

  param: vOrderBy - Order by keyword to sort the list by

  <li>Date: [DATE_ASC; DATE_DESC]

  <li>Name: [TO_ASC; TO_DESC; CC_ASC; CC_DESC]

  <li>Subject: [SUBJECT_ASC; SUBJECT_DESC]

  <li>Priority: [PRIORITY_ASC; PRIORITY_DESC]

  param: vItemsPerPage - Max number of items to get for a paginated list

  param: vPage - Current page number of a paginated list. Returns an updated page number does not match available page number

  param: vTotalPages - Maximum page number of a paginated list

  param: vResult - A weak cursor containing a list of message data

  <li>Message: Message ID

  <li>Date: Created date

  <li>Sender: Sender's User ID

  <li>SenderLastName: Patient Sender's Last Name

  <li>SenderFirstName: Patient Sender's First Name

  <li>SenderPreferredName: Patient Sender's Preferred Name

  <li>SenderProdCode: Sender's Producer Code

  <li>SenderDeleted: Check if sender is deleted

  <li>Subject: Subject of the message

  <li>Recipients: String representation of all TO recipients

  <li>CCRecipients: string representation of all CC recipients

  <li>IsPriority: Check if message is urgent

  <li>Status: Status of the message [0: new; 1: read; 2: deleted]

  */

  PROCEDURE getoutboxpatientmsglist(IN vuserid integer, IN vfolderid integer, IN vstationid integer, IN vorderby character varying, IN vitemsperpage integer, INOUT vpage integer, OUT vtotalpages integer, OUT vresult cursor_pkg.weakcursor);

  

  /**

  Retrieve details of a message.

  param: vMessageId - Message ID of MESSAGE to check (MESSAGE.Message)

  param: vStationId - Station ID needed to calculate correct date and time for the message (GetTimeZoneOffset.vStationId)

  param: vResult - A weak cursor containing details of a message

  <li>Message: Message ID

  <li>Date: Created date

  <li>Sender: Sender's User ID

  <li>SenderLastName: Sender's Last Name

  <li>SenderFirstName: Sender's First Name

  <li>SenderPreferredName: Sender's Preferred Name

  <li>SenderProdCode: Sender's Producer Code

  <li>SenderDeleted: Check if sender is deleted

  <li>Subject: Subject of the message

  <li>Recipients: String representation of all TO recipients

  <li>CCRecipients: string representation of all CC recipients

  <li>IsPriority: Check if message is urgent

  */

  PROCEDURE getmsgdetail(IN vmessageid integer, IN vstationid integer, OUT vresult cursor_pkg.weakcursor);

  

  /**

  Retrieve a list of all recipients (TO, CC, BCC) for a given message.

  param: vMessageId - Message ID of MSGSENT to check (MSGSENT.Message)

  param: vResult - A weak cursor containing a list of recipient data

  <li>User: User ID if the recipient is a User Type

  <li>Deleted: Check if user is deleted

  <li>LastName: User's Last Name

  <li>FirstName: User's First Name

  <li>PreferredName: User's Preferred Name

  <li>Producer: User's Producer Code

  <li>UGroup: Group ID if the recipient is a User Group Type

  <li>Description: Group Name

  <li>DeliveryType: Type of delivery method used to send the message [0: To; 1: CC; 2: Bcc]

  <li>RecipientType: Type of recipient the data is [0: User; 1: Group]

  */

  PROCEDURE getrecipientlist(IN vmessageid integer, OUT vresult cursor_pkg.weakcursor);

  

  /** 51503413

  Retrieve a list of all recipients (to, cc, bcc) for a given message including Users, Patients and Groups.

  param: vMessageId - Message ID of MSGSENT to check (MSGSENT.Message)

  param: vResult - A weak cursor containing a list of recipient data

  <li>User: User ID if the recipient is a User Type

  <li>Deleted: Check if user is deleted

  <li>LastName: User's Last Name

  <li>FirstName: User's First Name

  <li>PreferredName: User's Preferred Name

  <li>Producer: User's Producer Code

  <li>UGroup: Group ID if the recipient is a User Group Type

  <li>Description: Group Name

  <li>DeliveryType: Type of delivery method used to send the message [0: To; 1: CC; 2: Bcc]

  <li>RecipientType: Type of recipient the data is [0: User; 1: Group]

  <li>PatientId: PatientId

  */

  PROCEDURE getallrecipientlist(IN vmessageid integer, OUT vresult cursor_pkg.weakcursor);

  

  /**

  Retrieve a list of all Group type recipients available in axiUm system

  param: vOrderBy - Order by keyword to the list by

  <li>ID: [ID_ASC; ID_DESC]

  <li>Description: [DESC_ASC; DESC_DESC]

  param: vResult - A weak cursor containing a list of Group type recipients

  <li>UGroup: Group ID

  <li>Description: Group Name

  */

  PROCEDURE getgrouplist(IN vorderby character varying, OUT vresult cursor_pkg.weakcursor);

  

  /**

  Retrieve details for a User type recipient

  param: vUserId - User ID of USERS to check (USERS.User)

  param: vResult - A weak cursor containing details of a user

  <li>User: User ID

  <li>Deleted: Check if user is deleted

  <li>LastName: User's Last Name

  <li>FirstName: User's First Name

  <li>PreferredName: User's Preferred Name

  <li>Producer: User's Producer Code

  */

  PROCEDURE getuserdetail(IN vuserid integer, OUT vresult cursor_pkg.weakcursor);

  

  /**

  Retrieve details for a Group type recipient

  param: vGroupId - Group ID of UGROUP to check (UGROUP.UGroup)

  param: vResult - A weak cursor containing details of a user group

  <li>UGroup: Group ID

  <li>Description: Group Name

  */

  PROCEDURE getgroupdetail(IN vgroupid character, OUT vresult cursor_pkg.weakcursor);

  

  /**

  Retrieve a list of recipients with recipient's full name (first name + last name) or group name starting with the given keyword. 

  param: vKeyword - Case insensitive keyword to match the recipients' full name (first name + last name)

  param: vResult - A weak cursor containing a list of recipients with matching criteria

  <li>User: User ID if the recipient is a User Type

  <li>Deleted: Check if user is deleted

  <li>LastName: User's Last Name

  <li>FirstName: User's First Name

  <li>PreferredName: User's Preferred Name

  <li>ProdCode: User's Producer Code

  <li>UGroup: Group ID if the recipient is a User Group Type

  <li>Description: Group Name

  <li>RecipientType: Type of recipient the data is [0: User; 1: Group]

  */

  PROCEDURE getmatchingrecipientlist(IN vkeyword character varying, OUT vresult cursor_pkg.weakcursor);

  

  /**

  Update in-box message's status to "Read" if the message is not marked "Deleted"

  param: vMessageId - Message ID of MSGSENT to check (MSGSENT.Message)

  param: vUserId - User ID of MSGSENT to check (MSGSENT.User)

  */

  PROCEDURE markmsgread(IN vmessageid integer, IN vuserid integer);

  

  /**

  Move in-box message from current folder to targeted folder

  param: vMessageId - Message ID of MSGSENT to check (MSGSENT.Message)

  param: vUserId - User ID of MSGSENT to check (MSGSENT.User)

  param: vTargetFolderId - Folder ID to move the message to (MSGSENT.UMsgFld)

  */

  PROCEDURE moveinboxmsg(IN vmessageid integer, IN vuserid integer, IN vtargetfolderid integer);

  

  /**

  Move sent (out-box) message from current folder to targeted folder

  param: vMessageId - Message ID of MESSAGE to check (MESSAGE.Message)

  param: vTargetFolderId - Folder ID to move the message to (MESSAGE.UMsgFld)

  param: vHash - Hash value of Message

  */

  PROCEDURE moveoutboxmsg(IN vmessageid integer, IN vtargetfolderid integer, IN vhash character varying);

  

  /**

  Update in-box message's status to "Deleted"

  param: vMessageId - Message ID of MSGSENT to check (MSGSENT.Message)

  param: vUserId - User ID of MSGSENT to check (MSGSENT.User)

  */

  PROCEDURE deleteinboxmsg(IN vmessageid integer, IN vuserid integer);

  

  /**

  Update sent (out-box) message's status to "Deleted"

  param: vMessageId - Message ID of MESSAGE to check (MESSAGE.Message)

  param: vHash - Hash value of Message

  */

  PROCEDURE deleteoutboxmsg(IN vmessageid integer, IN vhash character varying);

  

  /**

  Create a new message using MESSAGE_PKG.ADD_MESSAGE, and SYSDATE

  param: vUserId - User ID

  param: vPriority - Check if the message is a priority

  param: vSubject - Subject of the message

  param: vText - Content of the message

  param: vDate - Date

  param: vHash - Hash value

  param: vSenderRespiUser - UserId of the representative

  param: vMessageId - Message ID created by the MESSAGE_PKG.ADD_MESSAGE

  */

  PROCEDURE createnewmsg(IN vuserid integer, IN vpriority integer, IN vsubject character varying, IN vtext clob, IN vdate timestamp without time zone, IN vhash character varying, IN vsenderrespiuser integer, OUT vmessageid integer);

  

  /**

  Add a User type recipient to a given message using MESSAGE_PKG.ADD_RECIPIENT_USER or MESSAGE_PKG.ADD_RECIPIENT_STRING.

  If the recipient being added already exists in the message, only string version of recipient name gets added to the

  message (MESSAGE_PKG.ADD_RECIPIENT_STRING), else, recipient information gets added to MSGSENT (MESSAGE_PKG.ADD_RECIPIENT_USER).

  param: vMessageId - Message ID

  param: vUserId - User ID getting added to message

  param: vDeliveryType - Type of delivery [0: To; 1: CC; 2: BCC]

  */

  PROCEDURE adduser(IN vmessageid integer, IN vuserid integer, IN vdeliverytype integer);

  

  /**

  Add a Group type recipient to a given message using MESSAGE_PKG.ADD_RECIPIENT_UGROUP

  param: vMessageId - Message ID

  param: vGroupId - GROUP ID

  param: vDeliveryType - Type of delivery [0: To; 1: CC; 2: BCC]

  */

  PROCEDURE addgroup(IN vmessageid integer, IN vgroupid character, IN vdeliverytype integer);



  /**

  * Procedure to return a list of axiUm users that meet a search criteria. The search is based on a LIKE comparison.<p/>

  *

  * param: vPatientId INPUT: Integer with PatientId.<p/>

  * param: vSearchTypeLevel INPUT: String with type of level ('ANY', 'PROVIDERS', 'FACULTY', 'ADMINISTRATORS')

  * param: vSearchString INPUT: String to conduct the search on.<p/>

  * param: vAllowAppointProv INPUT: Allow to Search by Appointment Providers.</p>

  * param: vAllowProv INPUT: Allow to Search by Assigned Providers.</p>

  * param: vAllowFaculty INPUT: Allow to Search by Assigned Faculty.</p>

  * param: vAllowAdmin INPUT: Allow to Search by Assigned Managers.</p>

  * param: vContactArray INPUT: List of Users to only get information. </p>

  * param: vSearchOn INPUT: Field in the user table to search on (0=first name, 1= last name, 2= provider ID, 3= provider group, 4= security level)<p/>

    param: vOrderBy - Order by keyword to sort the list by

    <li>First Name: [FIRST_ASC; FIRST_DESC]

    <li>Last Name: [LAST_ASC; LAST_DESC]

    <li>Level: [LEVEL_ASC; LEVEL_DESC]

    param: vItemsPerPage - Maximum number of items to get for a paginated list

    param: vPage - Current page number of a paginated list. Returns an updated page number does not match available page number

    param: vTotalPages - Maximum page number of a paginated list

  * param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

  *	<li>US."User" - User ID of the user that met the criteria (USERS.User).<br/>

  *	<li>US."Producer" - Provider ID of the user that met the criteria, if the user is a provider (USERS.Producer).<br/>

  *	<li>US."Name" - Last name of the user that met the criteria(USERS.Name).<br/>

  *	<li>US."First" - First name of the user that met the criteria (USERS.First).<br/>

  *	<li>PR."PGroup" - Provider group of the user that met the criteria, if the user is a provider and in a provider group (PRODUCER.PGroup).<br/>

  *	<li>SL."Description" - Security level of the user that met the criteria (SLEVEL.Description).<p/>

  */

  PROCEDURE docontactsearch(IN vpatientid integer, IN vsearchtypelevel character varying, IN vsearchstring character varying, IN vallowappointprov integer, IN vallowprov integer, IN vallowfaculty integer, IN vallowadmin integer, IN vcontactarray character varying, IN vsearchon integer, IN vorderby character varying, IN vitemsperpage integer, INOUT vpage integer, OUT vtotalpages integer, OUT results_cur cursor_pkg.weakcursor);

  

  /**

  * Procedure to get the time-zone offset in minutes.<p/>

  *

  * param: vStationId INPUT: Integer with Station Id.<p/>

  * param: vSearchTypeLevel OUTPUT: Integer with time-zone offset in minutes

  */

  PROCEDURE gettimezoneoffset(IN vstationid integer, OUT voffset integer);

  

  /**

  * Procedure to get all the user levels for specific user.<p/>

  *

  * param: vUserId INPUT: Integer with User Id.<p/>

  * param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

  *	<li>US."User" - User ID of the user that met the criteria (USERS.User).<br/>

  *	<li>US."Producer" - Provider ID of the user that met the criteria, if the user is a provider (USERS.Producer).<br/>

  *	<li>US."Name" - Last name of the user that met the criteria(USERS.Name).<br/>

  *	<li>US."First" - First name of the user that met the criteria (USERS.First).<br/>

  *	<li>SL."Description" - Security level of the user that met the criteria (SLEVEL.Description).<p/>

  */

  PROCEDURE douserlevels(IN vuserid integer, OUT results_cur cursor_pkg.weakcursor);

  

  /**

  * Procedure return Status for MessageId and UserId.<p/>

  *

  * param: vMessageId INPUT: Integer with Message Id.

  * param: vUserId INPUT: Integer with User Id.

  * param: vStatus OUTPUT: Integer with Message Status for specific User<br/>

  */

  PROCEDURE getmsgstatusbyuser(IN vmessageid integer, IN vuserid integer, OUT vstatus integer);

  

  -- 51503855 Procedure return MsgEncryption parameter from AxiumOpt table

  /**

  * Procedure return MsgEncryption parameter from AxiumOpt table<p/>

  *

  * param: vMsgEncryptParam OUTPUT: Integer with MessageEncrypt parameter<br/>

  */

  PROCEDURE getmsgencryptaxiumparam(OUT vmsgencryptparam integer);

  

  -- 51503855 FA

  /**

  Add a User type recipient to a given message using MESSAGE_PKG.ADD_RECIPIENT_USER or MESSAGE_PKG.ADD_RECIPIENT_STRING.

  If the recipient being added already exists in the message, only string version of recipient name gets added to the

  message (MESSAGE_PKG.ADD_RECIPIENT_STRING), else, recipient information gets added to MSGSENT (MESSAGE_PKG.ADD_RECIPIENT_USER).

  param: vMessageId - Message ID

  param: vUserId - User ID getting added to message

  param: vDeliveryType - Type of delivery [0: To; 1: CC; 2: BCC]

  param: vPatientId - Patient ID added to message

  */

  PROCEDURE addrecipientpatient(IN vmessageid integer, IN vuserid integer, IN vdeliverytype integer, IN vpatientid integer);

  

  /**

  * Get a list of most recent users for that a user has sent a message to.<p/>

  * param: vUserId - User ID getting added to message

  * param: vNumberOfRows - Maximum number of rows to return

  * param: vOrderBy - order by 

  * param: vResult OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

  *	<li>"User" - User ID USERS.User<br/>

  *	<li>"First" - First Name USERS.First<br/>

  *	<li>"Name" - Last Name USERS.Name<br/>

  *	<li>"PGroup" - Provider Group PRODUCER.PGroup<br/>

  *	<li>"Description" - Provider Group Description PGROUP.Description<p/>

  *	<li>"Producer" - Producer Code USERS.Producer<p/>

  */

  PROCEDURE getrecentusers(IN vuserid integer, IN vnumberofrows integer, IN vorderby character varying, OUT vresult cursor_pkg.weakcursor);



  /**

  * Get a list of users matching the criteria.<p/>

  */

  PROCEDURE searchusers(IN vsearchtype integer, IN vsearchkeyword character varying, IN vorderby character varying, IN vnumberofrows integer, INOUT vpagenumber integer, OUT vtotalpagenumber integer, OUT vresult cursor_pkg.weakcursor);

  

  /**

  * Get a list of messenger groups matching the criteria.<p/>

  */

  PROCEDURE searchgroups(IN vsearchtype integer, IN vsearchkeyword character varying, IN vorderby character varying, IN vnumberofrows integer, INOUT vpagenumber integer, OUT vtotalpagenumber integer, OUT vresult cursor_pkg.weakcursor);

  

  /**

  * Get a list of patients matching the criteria for the specific user.<p/>

  */

  PROCEDURE searchpatients(IN vsearchtype integer, IN vsearchkeyword character varying, IN vorderby character varying, IN vnumberofrows integer, IN vuserid integer, INOUT vpagenumber integer, OUT vtotalpagenumber integer, OUT vresult cursor_pkg.weakcursor);

  

  /**

  * Get true/false if a user has a permission to send a message to a patient.<p/>

  */

  PROCEDURE cansendmessagetopatient(IN vuserid integer, OUT vresult integer);

  

  /**

  * Get true/false if a user has a permission to send a message to a specific user (for patient).<p/>

  */

  PROCEDURE cansendmessagetouser(IN vsenderuserid integer, IN vrecipientuserid integer, OUT vresult integer);

  

  

  /**

  * Get total of unread recipients for a message

  */

  PROCEDURE gettotalrecipients(IN vmessageid integer, OUT vcount integer);

  

  /**

  * Delete Message

  */

  PROCEDURE deletemsg(IN vmessageid integer);

  

  /**

  * Delete all the recipients who didn't read the message

  */

  PROCEDURE deletemsgunreadrecipients(IN vmessageid integer);

  

END;
 
-- TABLE TRIGGERS (excluding view triggers) 
CREATE TRIGGER apnote_trg AFTER DELETE ON ap_note FOR EACH ROW  $trigger$DECLARE
	v_patient NUMBER(10,0);
	v_policy NUMBER(10,0);

BEGIN

	-- AX-24111.24145 arr added ability to disable triggers for the given sessions
    IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
		RETURN :new;
    END IF;

    v_patient := 0;
	v_policy := 0;
	
	-- Personal Info
	BEGIN
		SELECT COALESCE(ISTICKYNOTE."Patient",0)
		INTO v_patient
		FROM ISTICKYNOTE
		WHERE ISTICKYNOTE."AP_NOTE_AutoDec" = :OLD."AP_NOTE_AutoDec"
			AND ISTICKYNOTE."Type" = 2
			AND ISTICKYNOTE."SecondaryId" = 2;
		
		EXCEPTION
			WHEN NO_DATA_FOUND THEN
				v_patient := 0;
	END;
	
	IF (v_patient IS NOT NULL AND v_patient > 0) THEN
		UPDATE IUSER SET "PersonalInfoCorrect" = 0 WHERE "Id" = v_patient;
	END IF;
	
	-- Insurance Policy Info
	BEGIN
		SELECT COALESCE(ISTICKYNOTE."Patient",0), COALESCE(ISTICKYNOTE."SecondaryId",0)
		INTO v_patient, v_policy
		FROM ISTICKYNOTE
		WHERE ISTICKYNOTE."AP_NOTE_AutoDec" = :OLD."AP_NOTE_AutoDec"
			AND ISTICKYNOTE."Type" = 1;
		
		EXCEPTION
			WHEN NO_DATA_FOUND THEN
				v_patient := 0;
	END;
	
	IF (v_patient IS NOT NULL AND v_patient > 0) THEN
		UPDATE PTDEPEND SET "CorrectStatus" = 0 WHERE "PolicyId" = v_policy AND "Patient" = v_patient;
	END IF;
END$trigger$
 ;
CREATE TRIGGER appoint_bookingorder BEFORE INSERT ON appoint FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


	:NEW."BookingOrder" := :NEW."Appointment";

END$trigger$
 ;
CREATE TRIGGER auditlog_ap_note AFTER INSERT OR DELETE OR UPDATE OF "AP_NOTE_AppId", "AP_NOTE_Type", "ModifiedDateTime", "AP_NOTE_Flag", "AP_NOTE_Date1", "AP_NOTE_Date2", "AP_NOTE_Text", "AP_NOTE_Treatment", "CreationUser", "ModifiedUser", "StationId" ON ap_note FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'AP_NOTE';
   v_nPatientId := 0;

   IF ( DELETING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
      v_nPatientId := AUDITLOG_PKG.GetApNotePatId(:OLD."AP_NOTE_Type", :OLD."AP_NOTE_Treatment", :OLD."AP_NOTE_PatientId", :OLD."AP_NOTE_AppId");

		IF (v_nPatientId = 0) THEN
			RETURN :new;
		END IF;
		
		v_szTableDesc := AUDITLOG_PKG.GetApNoteDescription(:OLD."AP_NOTE_Type");
		
		IF (LENGTH(TRIM(:OLD."AP_NOTE_Text")) < 50) THEN
		   v_szInfo := TRIM(:OLD."AP_NOTE_Text");
		ELSE
			v_szInfo := RPAD(:OLD."AP_NOTE_Text", 50) || '...';
		END IF;

   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		END IF;

		v_nPatientId := AUDITLOG_PKG.GetApNotePatId(:NEW."AP_NOTE_Type", :NEW."AP_NOTE_Treatment", :NEW."AP_NOTE_PatientId", :NEW."AP_NOTE_AppId");
		
		IF (v_nPatientId = 0) THEN
			RETURN :new;
		END IF;
		
		IF (LENGTH(TRIM(:NEW."AP_NOTE_Text")) < 50) THEN
		   v_szInfo := TRIM(:NEW."AP_NOTE_Text");
		ELSE
			v_szInfo := RPAD(:NEW."AP_NOTE_Text", 50) || '...';
		END IF;

		v_szTableDesc := AUDITLOG_PKG.GetApNoteDescription(:NEW."AP_NOTE_Type");
	END IF;
	

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_appoint AFTER INSERT OR DELETE OR UPDATE OF "Date", "Chair", "Type", "Producer", "From", "Code", "Unit0", "Unit1", "Unit2", "Unit3", "Unit4", "Unit5", "Time0", "Time1", "Time2", "Time3", "Time4", "Time5", "Estimate", "Class", "User", "IsRecall", "IsAsap", "IsConfirm", "IsShortNotice", "Status", "Rank", "UStatus", "OrthoStage", "IsOrtho", "Cancel", "Reason", "Assistant", "Clinic", "IsRequest", "Instructor", "CheckInTime", "TimeSeated", "SignInTime", "SecondaryMCBFlag", "NotBeforeDate", "PtEstimateStatus", "PtEstimate", "ExpertAdd", "CheckOutDate", "CheckOutTime", "PrimaryExclusive" ON appoint FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

	IF ( INSERTING AND (:NEW."Chair"=0 AND :NEW."Type"=4) ) THEN
		-- new reschedule appoint, no need to audit
		RETURN :new;
	END IF;
	
	IF ( UPDATING AND (:NEW."Type"=4 AND :OLD."Type"=4 AND :NEW."From"!=:OLD."From") ) THEN
		-- move reschedule appt around, no need to audit
		RETURN :new;
	END IF;

   v_szTableName := 'APPOINT';

	IF (  deleting OR  (:OLD."Status" = 0 AND :NEW."Status" = 2) ) THEN
		v_nPatientId := :OLD."Patient";
		v_nActionType := AUDITLOG_PKG.c_nActionDelete;
		v_szTableDesc := AUDITLOG_PKG.GetAppointDescription(:OLD."Type");
		v_szInfo := AUDITLOG_PKG.GetAppointAdditionalInfo(:OLD."Code", :OLD."Reason", :OLD."Type", :OLD."Date", :OLD."From");
	ELSE
		v_nPatientId := :NEW."Patient";
		IF ( Inserting ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		END IF;
		v_szTableDesc := AUDITLOG_PKG.GetAppointDescription(:NEW."Type");
		v_szInfo := AUDITLOG_PKG.GetAppointAdditionalInfo(:NEW."Code", :NEW."Reason", :NEW."Type", :NEW."Date", :NEW."From");
	END IF;
	
   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_apptrx AFTER INSERT OR DELETE OR UPDATE OF "AppTrx", "Appointment", "Type", "Id", "Treatment", "Procedure", "Date" ON apptrx FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

   v_nApptType		NUMBER;

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'APPTRX';
   v_szTableDesc := 'Appointment Treatment';

   IF ( DELETING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
      BEGIN
			SELECT "Patient", "Type" INTO v_nPatientId, v_nApptType FROM APPOINT WHERE "Appointment" = :OLD."Appointment";
			v_szInfo := AUDITLOG_PKG.GetAppointDescription(v_nApptType) || ' - ' || TRIM(:OLD."Procedure");
	   EXCEPTION WHEN NO_DATA_FOUND THEN				--B142092
		  	return :new;
	   END;

   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		END IF;
      BEGIN
			SELECT "Patient", "Type" INTO v_nPatientId, v_nApptType FROM APPOINT WHERE "Appointment" = :NEW."Appointment";
		   v_szInfo := AUDITLOG_PKG.GetAppointDescription(v_nApptType) || ' - ' || TRIM(:NEW."Procedure");
	   EXCEPTION WHEN NO_DATA_FOUND THEN				--B142092
		  	return :new;
	   END;

	END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_contract AFTER INSERT OR DELETE OR UPDATE OF "Date", "PtSig", "AtTab", "Consent", "ExpiryDate", "Deleted", "SigStatus", "Description" ON contract FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

   v_szConsent	  VARCHAR2(255 );
   v_szDesc       VARCHAR2(255 );

   v_bContract	  BOOLEAN := FALSE;
   v_bSig	  BOOLEAN := FALSE;

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'CONTRACT';


   -- Audit the contract change
   IF ( DELETING  OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1)  ) THEN

      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
      v_nPatientId := :OLD."Patient";
      v_szConsent := :OLD."Consent";
      v_szDesc := :OLD."Description";
      v_bContract := TRUE;

   ELSIF ( INSERTING ) THEN

      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
      v_nPatientId := :NEW."Patient";
      v_szConsent := :NEW."Consent";
      v_szDesc := :NEW."Description";
      v_bContract := TRUE;

   ELSE

      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
      v_nPatientId := :NEW."Patient";
      v_szConsent := :NEW."Consent";
      v_szDesc := :NEW."Description";

      -- only audit the edit if something other than PtSig has changed
      IF (:OLD."Date" <> :NEW."Date"
         OR :OLD."AtTab" <> :NEW."AtTab"
         OR :OLD."Consent" <> :NEW."Consent"
         OR :OLD."ExpiryDate" <> :NEW."ExpiryDate"
         OR :OLD."SigStatus" <> :NEW."SigStatus"
         OR :OLD."Description" <> :NEW."Description")
      THEN
         v_bContract := TRUE;
      END IF;

   END IF;


   IF (TRIM(v_szConsent) IS NULL OR LENGTH(TRIM(v_szConsent)) = 0) THEN
	v_szInfo := TRIM(v_szDesc);
   ELSE
	v_szInfo := TRIM(v_szConsent) || ' - ' || TRIM(v_szDesc);
   END IF;


   -- add contract auditlog
   IF (v_bContract) THEN
      IF (TRIM(v_szConsent) IS NULL OR LENGTH(TRIM(v_szConsent)) = 0) THEN
         v_szTableDesc := 'Patient Contract';
      ELSE
         v_szTableDesc := 'Patient Consent';
      END IF;

      AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);
   END IF;



   -- add signature auditlog
   IF (INSERTING OR UPDATING) AND NVL(:OLD."PtSig", 0) = 0 AND :NEW."PtSig" > 0 THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
      v_szTableDesc := 'Patient Signature';
      AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);
   END IF;


END$trigger$
 ;
CREATE TRIGGER auditlog_contsig AFTER INSERT OR DELETE OR UPDATE OF "Contract", "Signee", "Name", "PtSig" ON contsig FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

   v_CONTRACT	  CONTRACT%ROWTYPE;

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'CONTSIG';


   IF ( DELETING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
   ELSIF ( INSERTING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
   END IF;

   -- lookup contract record
   BEGIN
      SELECT * INTO v_CONTRACT FROM CONTRACT WHERE "Contract" = NVL(:NEW."Contract", :OLD."Contract");
   EXCEPTION WHEN NO_DATA_FOUND THEN
      RETURN :new;
   END;

   v_szTableDesc := 'Additional Signature';
   v_nPatientId := v_CONTRACT."Patient";

   IF (TRIM(v_CONTRACT."Consent") IS NULL OR LENGTH(TRIM(v_CONTRACT."Consent")) = 0) THEN
      v_szInfo := v_CONTRACT."Description" || ', ' || NVL(:NEW."Signee", :OLD."Signee");
   ELSE
      v_szInfo := v_CONTRACT."Consent" || ' - ' || v_CONTRACT."Description" || ', ' || NVL(:NEW."Signee", :OLD."Signee");
   END IF;


   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_deplimit AFTER INSERT OR DELETE OR UPDATE OF "Category", "Limit", "Description", "LimitBalance", "Deduct", "DeductBalance", "ResetDate", "LimitOnPatient" ON deplimit FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'DEPLIMIT';


   IF ( DELETING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
   ELSIF ( INSERTING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
   END IF;

   v_szTableDesc := 'Policy Dependent Limits';
   v_nPatientId := NVL(:NEW."Patient", :OLD."Patient");

   SELECT TRIM("Company") || '(' || TRIM("Group" )|| ') - ' || TRIM("Policy")
   INTO v_szInfo FROM POLICY WHERE "PolicyId" = NVL(:NEW."PolicyId", :OLD."PolicyId");


   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_edielig AFTER INSERT ON edielig FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'EDIELIG';

   v_nActionType := AUDITLOG_PKG.c_nActionAdd;

   v_szTableDesc := 'Patient Eligibility Check';
   v_nPatientId := NVL(:NEW."Patient", :OLD."Patient");

   BEGIN
      SELECT TRIM("Company") || '(' || TRIM("Group" )|| ')'
      INTO v_szInfo FROM POLINS WHERE "PolIns" = NVL(:NEW."PolIns", :OLD."PolIns");
   EXCEPTION WHEN NO_DATA_FOUND THEN
      v_szInfo := '';
   END;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_epreview AFTER INSERT OR DELETE OR UPDATE OF "Type", "ReviewDate", "ReviewUser", "HasRecords", "Deleted" ON epreview FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

  	v_nReviewType	NUMBER;
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'EPREVIEW';

   IF ( DELETING   OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
   ELSIF ( INSERTING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
   END IF;

   v_nPatientId := NVL(:NEW."Patient", :OLD."Patient");
   v_nReviewType := NVL(:NEW."Type", :OLD."Type");

	IF ( v_nReviewType = 0 ) THEN
		v_szTableDesc := 'Medication Review';
	ELSIF ( v_nReviewType = 1 ) THEN
		v_szTableDesc := 'Allergy Review';
	ELSE -- v_nReviewType = 2
		v_szTableDesc := 'Medical Problem Review';
	END IF;

	v_szInfo := 'Review Date:' || ' - ' || TO_CHAR(NVL(:NEW."ReviewDate", :OLD."ReviewDate"), 'MON DD,YYYY');

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_famlimit AFTER INSERT OR DELETE OR UPDATE OF "Description", "Limit", "LimitOnPatient", "LimitBalance", "ResetDate" ON famlimit FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'FAMLIMIT';


   IF ( DELETING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
   ELSIF ( INSERTING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
   END IF;

   v_szTableDesc := 'Policy Category Family Limits';

   SELECT "Patient", TRIM("Company") || '(' || TRIM("Group" )|| ') - ' || TRIM("Policy") || ' - ' || NVL(:NEW."Category", :OLD."Category")
   INTO v_nPatientId, v_szInfo FROM POLICY WHERE "PolicyId" = NVL(:NEW."PolicyId", :OLD."PolicyId");


   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_iaccess AFTER INSERT OR DELETE OR UPDATE OF "RespiUser", "Deleted", "Audit" ON iaccess FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'IACCESS';
   v_szTableDesc := 'PatientAccess Representative Information';

   IF ( DELETING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
	   v_nPatientId := AUDITLOG_PKG.GetiUserPatId(:OLD."iUser");
	   v_szInfo := 'iUser Name: ' || AUDITLOG_PKG.GetiUserInfo(:OLD."iUser");
   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		END IF;

	   v_nPatientId := AUDITLOG_PKG.GetiUserPatId(:NEW."iUser");
	   v_szInfo := 'iUser Name: ' || AUDITLOG_PKG.GetiUserInfo(:NEW."iUser");
   END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_indlog AFTER INSERT OR DELETE OR UPDATE OF "Indicat", "Value", "Patient", "Audit" ON indlog FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'INDLOG';
   v_nActionType := AUDITLOG_PKG.c_nActionAdd;
   v_szTableDesc := 'Intervention Indicator Log';
   v_nPatientId := :NEW."Patient";	
	
	-- B142339
	v_szInfo := AUDITLOG_PKG.GetIndlogState(:NEW."State") ||
					AUDITLOG_PKG.GetIndicatorDescription(:NEW."Indicat") ||
					' (' || AUDITLOG_PKG.GetIndlogSeverity(:NEW."Severity") || ')';

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_iptform AFTER INSERT OR DELETE OR UPDATE OF "FormCode", "PForm", "iUser", "Access", "Order", "RequiresAttention" ON iptform FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'IPTFORM';
   v_szTableDesc := 'Available Patient iForms';

   IF (DELETING) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
      v_nPatientId := :OLD."Patient";
      v_szInfo := 'Form: ' || TRIM(:OLD."FormCode");
	
   ELSE
		IF (INSERTING) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		END IF;
		
		v_nPatientId := :NEW."Patient";
		v_szInfo := 'Form: ' || TRIM(:NEW."FormCode");
		
	END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_iuser AFTER INSERT OR DELETE OR UPDATE OF "UserName", "Password", "IsTemp", "IsAgreed", "IsLocked", "Deleted", "PasswordQuestion1", "PasswordAnswer1", "PasswordQuestion2", "PasswordAnswer2", "PasswordQuestion3", "PasswordAnswer3", "PwdLastChanged", "MsgAccess", "LastAccessDateTime", "LastEmailDateTime", "PersonalInfoCorrect" ON iuser FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'IUSER';
   v_szTableDesc := 'Internet User Information';

   IF ( DELETING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
	   v_nPatientId := :OLD."Id";
	   v_szInfo := 'User Name ' || :OLD."UserName";
   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		END IF;
	   v_nPatientId := :NEW."Id";
	   v_szInfo := 'User Name ' || :NEW."UserName";
   END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_labitem AFTER INSERT OR DELETE OR UPDATE OF "Provider", "Date", "Redo", "RedoItem", "ApprovalUser", "ApprovalDate", "ExpectedDate", "DateChanged", "LabOut", "DateOut", "TimeOut", "OutUser", "DateIn", "TimeIn", "User", "Deleted", "LabCode" ON labitem FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );
   v_szLabOrder	NUMBER;
   v_szCase 		VARCHAR2(10 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'LABITEM';
   v_szTableDesc := 'Lab Item';

   IF ( DELETING OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
      SELECT "Patient", "LabOrder", "CaseNo" INTO v_nPatientId, v_szLabOrder, v_szCase FROM LABORDER WHERE "LabOrder" = :OLD."LabOrder";
      v_szInfo := 'Order # ' || v_szLabOrder || '   Case # ' || v_szCase || '   Item: ' || :OLD."Item";

   ELSIF ( INSERTING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
      SELECT "Patient", "LabOrder", "CaseNo" INTO v_nPatientId, v_szLabOrder, v_szCase FROM LABORDER WHERE "LabOrder" = :NEW."LabOrder";
      v_szInfo := 'Order # ' || v_szLabOrder || '   Case # ' || v_szCase || '   Item: ' || :NEW."Item";

   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
      SELECT "Patient", "LabOrder", "CaseNo" INTO v_nPatientId, v_szLabOrder, v_szCase FROM LABORDER WHERE "LabOrder" = :NEW."LabOrder";
      v_szInfo := 'Order # ' || v_szLabOrder || '   Case # ' || v_szCase || '   Item: ' || :NEW."Item";

   END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_laborder AFTER INSERT OR DELETE OR UPDATE OF "CaseNo", "LabProcedure", "Discipline", "Date", "RemakeStudent", "RemakeStaff", "RemakeLabOrder", "WaiveCharges", "LabOut", "LabCode", "DateOut", "TimeOut", "User", "Deleted", "CurrentItem", "Status", "CompletionDate", "TotalCost", "TotalCharge", "IsOrtho" ON laborder FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'LABORDER';
   v_szTableDesc := 'Lab Order';

   IF ( DELETING OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
      v_nPatientId := :OLD."Patient";
      v_szInfo := 'Order # ' || :OLD."LabOrder" || '   Case # ' || :OLD."CaseNo";

   ELSIF ( INSERTING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
      v_nPatientId := :NEW."Patient";
      v_szInfo := 'Order # ' || :NEW."LabOrder" || '   Case # ' || :NEW."CaseNo";

   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
      v_nPatientId := :NEW."Patient";
      v_szInfo := 'Order # ' || :NEW."LabOrder" || '   Case # ' || :NEW."CaseNo";

   END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_labotrx AFTER INSERT OR DELETE OR UPDATE OF "Deleted" ON labotrx FOR EACH ROW  $trigger$DECLARE v_nPatientId NUMBER;
  v_nActionType NUMBER;
  v_szTableName VARCHAR2(255 );
  v_szTableDesc VARCHAR2(255 );
  v_szInfo      VARCHAR2(255 );
  v_szLabOrder  NUMBER;
  v_szCase      VARCHAR2(10 );
  v_szProcedure VARCHAR2(7 );
  vLabOrder laborder."LabOrder" %type := 0; -- AX-1368.1386
  vOrigRecNo trx."OrigRecNo" %type := 0; -- AX-1368.1386
  BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

    IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
    END IF;
    v_szTableName                   := 'LABOTRX';
    v_szTableDesc                   := 'Lab Treatment';
    IF ( DELETING OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType                 := AUDITLOG_PKG.c_nActionDelete;
      -- AX-1368.1386
      vLabOrder                         := :OLD."LabOrder";
      vOrigRecNo                        := :OLD."OrigRecNo";
    ELSIF ( INSERTING OR (:OLD."Deleted" = 1 AND :NEW."Deleted" = 0) ) THEN
      v_nActionType                     := AUDITLOG_PKG.c_nActionAdd;
      -- AX-1368.1386
      vLabOrder  := :NEW."LabOrder";
      vOrigRecNo := :NEW."OrigRecNo";
    ELSE -- should never get in here
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
      -- AX-1368.1386
      vLabOrder  := :NEW."LabOrder";
      vOrigRecNo := :NEW."OrigRecNo";
    END IF;

    -- AX-1368.1386 - start
    -- get lab order information
    BEGIN
      SELECT "Patient",
        "LabOrder",
        "CaseNo"
      INTO v_nPatientId,
        v_szLabOrder,
        v_szCase
      FROM LABORDER
      WHERE 1        =1
      AND "LabOrder" = vLabOrder;
    EXCEPTION
    WHEN OTHERS THEN
      v_nPatientId := 0;
      v_szLabOrder := 0;
      v_szCase     := '';
    END;
    -- get treatment information
    BEGIN
      SELECT "Procedure"
      INTO v_szProcedure
      FROM TRX
      WHERE 1         =1
      AND "OrigRecNo" = vOrigRecNo
      AND "Deleted"   = 0;
    EXCEPTION
    WHEN no_data_found THEN
      BEGIN
        SELECT "Procedure"
        INTO v_szProcedure
        FROM TRX
        WHERE 1         =1
        AND "OrigRecNo" = vOrigRecNo
        AND "Deleted"   = 1;
      EXCEPTION
      WHEN no_data_found THEN
        BEGIN
          SELECT "Procedure"
          INTO v_szProcedure
          FROM TRX
          WHERE 1         =1
          AND "OrigRecNo" = vOrigRecNo;
        EXCEPTION
        WHEN too_many_rows THEN
          SELECT "Procedure"
          INTO v_szProcedure
          FROM TRX
          WHERE 1         =1
          AND "OrigRecNo" = vOrigRecNo
          AND rownum      = 1;
        WHEN OTHERS THEN
          v_szProcedure := '';
        END;
      WHEN too_many_rows THEN
        SELECT "Procedure"
        INTO v_szProcedure
        FROM TRX
        WHERE 1         =1
        AND "OrigRecNo" = vOrigRecNo
        AND "Deleted"   = 1
        AND rownum      = 1;
      WHEN OTHERS THEN
        v_szProcedure := '';
      END;
    WHEN too_many_rows THEN
      SELECT "Procedure"
      INTO v_szProcedure
      FROM TRX
      WHERE 1         =1
      AND "OrigRecNo" = vOrigRecNo
      AND "Deleted"   = 0
      AND rownum      = 1;
    WHEN OTHERS THEN
      v_szProcedure := '';
    END;
    -- AX-1368.1386 - end

    v_szInfo := 'Order # ' || v_szLabOrder || '   Case # ' || v_szCase || '   Tx: ' || v_szProcedure;
    AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);
  END$trigger$
 ;
CREATE TRIGGER auditlog_labptout AFTER INSERT OR DELETE OR UPDATE OF "LabOrder", "Audit" ON labptout FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );
   v_szLabOrder	NUMBER;
   v_szCase 		VARCHAR2(10 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'LABPTOUT';
   v_szTableDesc := 'Print Lab Order';

   IF ( DELETING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
      SELECT "Patient", "LabOrder", "CaseNo" INTO v_nPatientId, v_szLabOrder, v_szCase FROM LABORDER WHERE "LabOrder" = :OLD."LabOrder";

   ELSIF ( INSERTING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
      SELECT "Patient", "LabOrder", "CaseNo" INTO v_nPatientId, v_szLabOrder, v_szCase FROM LABORDER WHERE "LabOrder" = :NEW."LabOrder";

   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
      SELECT "Patient", "LabOrder", "CaseNo" INTO v_nPatientId, v_szLabOrder, v_szCase FROM LABORDER WHERE "LabOrder" = :NEW."LabOrder";

   END IF;

   v_szInfo := 'Order # ' || v_szLabOrder || '   Case # ' || v_szCase;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_labsitem AFTER INSERT OR DELETE OR UPDATE OF "LabOrder", "Item", "Description", "Deleted" ON labsitem FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );
   v_szLabOrder	NUMBER;
   v_szCase 		VARCHAR2(10 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'LABSITEM';
   v_szTableDesc := 'Lab Item Supplement';

   IF ( DELETING OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
      SELECT "Patient", "LabOrder", "CaseNo" INTO v_nPatientId, v_szLabOrder, v_szCase FROM LABORDER WHERE "LabOrder" = :OLD."LabOrder";
      v_szInfo := 'Order # ' || v_szLabOrder || '   Case # ' || v_szCase || '   Item: ' || :OLD."Item" || '   Supplement: ' || :OLD."Description";

   ELSIF ( INSERTING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
      SELECT "Patient", "LabOrder", "CaseNo" INTO v_nPatientId, v_szLabOrder, v_szCase FROM LABORDER WHERE "LabOrder" = :NEW."LabOrder";
      v_szInfo := 'Order # ' || v_szLabOrder || '   Case # ' || v_szCase || '   Item: ' || :NEW."Item" || '   Supplement: ' || :NEW."Description";

   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
      SELECT "Patient", "LabOrder", "CaseNo" INTO v_nPatientId, v_szLabOrder, v_szCase FROM LABORDER WHERE "LabOrder" = :NEW."LabOrder";
      v_szInfo := 'Order # ' || v_szLabOrder || '   Case # ' || v_szCase || '   Item: ' || :NEW."Item" || '   Supplement: ' || :NEW."Description";

   END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_mtestord AFTER INSERT OR DELETE OR UPDATE OF "OrderNumber", "OrderProviderNPI", "OrderProviderLast", "OrderProviderFirst" ON mtestord FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'MTESTORD';


   IF ( DELETING OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
   ELSIF ( INSERTING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
   END IF;

   v_szTableDesc := 'Medical Test Order';
   v_nPatientId := NVL(:NEW."Patient", :OLD."Patient");
   v_szInfo := 'Order Number: ' || NVL(:NEW."OrderNumber", :OLD."OrderNumber");


   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_mtestreq AFTER INSERT OR DELETE OR UPDATE OF "RequestNumber", "LOINC", "RequestDateTime", "Status", "RelevantClinicalInfo" ON mtestreq FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'MTESTREQ';


   IF ( DELETING OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
   ELSIF ( INSERTING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
   END IF;

   SELECT MAX("Patient") INTO v_nPatientId
   FROM MTESTORD
   WHERE "MTestOrd" = NVL(:NEW."MTestOrd", :OLD."MTestOrd");

   v_szTableDesc := 'Medical Test Requested Procedure';
   v_szInfo := 'LOINC: ' || NVL(:NEW."LOINC", :OLD."LOINC");


   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_mtestres AFTER INSERT OR DELETE OR UPDATE OF "ResultNumber", "LOINC", "MTestLab", "ObservationDateTime", "AnalysisDateTime", "ResultValue", "ResultUnits", "ReferenceRange", "Abnormal", "Status" ON mtestres FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'MTESTRES';


   IF ( DELETING OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
   ELSIF ( INSERTING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
   END IF;

   SELECT MAX(O."Patient") INTO v_nPatientId
   FROM MTESTORD O, MTESTREQ R
   WHERE O."MTestOrd" = R."MTestOrd"
   AND R."MTestReq" = NVL(:NEW."MTestReq", :OLD."MTestReq");

   v_szTableDesc := 'Medical Test Result';
   v_szInfo := 'LOINC: ' || NVL(:NEW."LOINC", :OLD."LOINC");


   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_mtestspm AFTER INSERT OR DELETE OR UPDATE OF "SpecimenNumber", "CollectionDateTime", "Condition", "RejectReason" ON mtestspm FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'MTESTSPM';


   IF ( DELETING OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
   ELSIF ( INSERTING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
   END IF;

   SELECT MAX(O."Patient") INTO v_nPatientId
   FROM MTESTORD O, MTESTREQ R
   WHERE O."MTestOrd" = R."MTestOrd"
   AND R."MTestReq" = NVL(:NEW."MTestReq", :OLD."MTestReq");

   v_szTableDesc := 'Medical Test Result';
   v_szInfo := 'Specimen Number: ' || NVL(:NEW."SpecimenNumber", :OLD."SpecimenNumber");


   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_notes2 AFTER INSERT OR DELETE OR UPDATE OF "Auto", "PId", "Site", "User", "Status", "Phase", "Seq", "Custom1", "Custom2", "Code", "Type", "Module", "SectionNo", "Date", "DeletionDate", "AddDateTime", "IsTemplate" ON notes2 FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'NOTES2';
   v_szTableDesc := 'Clinical Notes';

   IF ( DELETING OR (:OLD."Status" = 0 AND :NEW."Status" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
		SELECT "PtxPId" INTO v_nPatientId FROM PATIENT2 WHERE "Auto" = :OLD."PId";
	   v_szTableDesc := v_szTableDesc || ' - ' || AUDITLOG_PKG.GetNotes2Description(:OLD."Type", :OLD."SectionNo");
		if ( LENGTH(TRIM(:OLD."Text")) < 50 ) THEN
		   v_szInfo := TRIM(:OLD."Text");
		ELSE
			v_szInfo := RPAD(:OLD."Text", 50) || '...';
		END IF;
   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSIF ( :NEW."Status" = 2 ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionStrikeOut;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		END IF;
		SELECT "PtxPId" INTO v_nPatientId FROM PATIENT2 WHERE "Auto" = :NEW."PId";
	   v_szTableDesc := v_szTableDesc || ' - ' || AUDITLOG_PKG.GetNotes2Description(:NEW."Type", :NEW."SectionNo");
		if ( LENGTH(TRIM(:NEW."Text")) < 50 ) THEN
		   v_szInfo := TRIM(:NEW."Text");
		ELSE
			v_szInfo := RPAD(:NEW."Text", 50) || '...';
		END IF;
   END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_patient AFTER INSERT OR DELETE OR UPDATE OF "Family", "Last", "First", "Prefered", "Middle", "Title", "Birth", "Address1", "Address2", "City", "Province", "Postal", "HomeArea", "HomePhone", "WorkArea", "WorkPhone", "WorkExt", "OtherArea", "OtherPhone", "OtherExt", "OtherLoc", "ContactAt", "ContactTime", "Status", "Sex", "Marital", "IsPatient", "IsStudent", "IsHandicaped", "Chart", "Sin", "Office1", "Office2", "Office3", "Office4", "Office5", "Alert1", "Alert2", "Alert3", "Alert4", "Alert5", "Open", "Close", "Path", "Deleted", "School", "Health", "InsPt", "OpenBalance", "AccountStatus", "Assignment", "Statements", "Interest", "ChartIn", "Location", "UserOut", "DateOut", "TimeOut", "IsFreeAccess", "Fee", "OtherLocation", "NoLocks", "CustomCode1", "CustomCode2", "CustomCode3", "CustomCode4", "CustomCode5", "CustomCode6", "CustomCode7", "CustomCode8", "CustomCode9", "CustomCode10", "Physician", "EmergLast", "EmergFirst", "EmergMiddle", "EmergAddress", "EmergCity", "EmergProvince", "EmergPostal", "EmergArea", "EmergPhone", "EmergRelation", "IsChartFixed", "EmergAltArea", "EmergAltPhone", "IsOrtho", "OrthoSet", "EmergAddress2", "AltChart", "LastUpper", "PrefUpper", "AddressOther", "BankAccount", "RespNumber", "EmergAddressOther", "EDIFlag", "PatType", "IsEmergency", "ActiveDate", "PartnerName", "BoxNumber", "Email", "ChartSort", "PartnerPrefix", "PrefApptTime", "XRayReceived", "DateXRayExpected", "DateXRayReceived", "Country", "XRayExposures", "MergedChart", "ChartSuffix", "ReleaseOnFile", "EmergExt", "EmergAltExt", "HomeExt", "FeeOverride", "DiscGrp", "EmancedMinor", "RequireTxConsent", "PaperChart", "InfoNotify", "TaxExempt", "RecallDoctorToUse", "RecallHygToUse", "CustomText1", "CustomText2", "CustomText3", "CustomText4", "CustomText5", "MobileArea", "MobilePhone", "ApptFeesExempt", "PrefLanguage", "RaceEthDeclined", "Ethnic", "IsTrustedAudit", "SecondIDType", "SecondIDNumber", "Is2ndIdTrustedAudit" ON patient FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PATIENT';
   v_szTableDesc := 'Patient Demographic Information';

   IF ( DELETING  OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
	   v_nPatientId := :OLD."Patient";
	   v_szInfo := 'Chart# ' || :OLD."Chart";
   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		END IF;
	   v_nPatientId := :NEW."Patient";
	   v_szInfo := 'Chart# ' || :NEW."Chart";
   END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_patient2 AFTER INSERT OR DELETE OR UPDATE OF "ChartId", "LastName", "FirstName", "MidName", "User", "ToothState", "PermanentState", "PrimaryState", "Date", "StationId" ON patient2 FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PATIENT2';
   v_szTableDesc := 'Extra Chart Data';

   IF (DELETING) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
      v_nPatientId := :OLD."PtxPId";
      v_szInfo := RTRIM(:OLD."LastName") || ', ' || RTRIM(:OLD."FirstName") || ' (' || RTRIM(:OLD."ChartId") || ')' ;
	
   ELSE
		IF (INSERTING) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		END IF;
		
		v_nPatientId := :NEW."PtxPId";
		v_szInfo := RTRIM(:NEW."LastName") || ', ' || RTRIM(:NEW."FirstName") || ' (' || RTRIM(:NEW."ChartId") || ')' ;
		
	END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_pform AFTER INSERT OR DELETE OR UPDATE OF "FormCode", "Date", "User", "PForm", "Description", "OwnerType", "OwnerId", "CreatedDate", "Inactive", "InactiveReason", "FStatus", "AssignedUser", "AssignedUGroup", "LastStartDateTime" ON pform FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PFORM';

   IF ( DELETING ) THEN
		IF :OLD."OwnerType" = 5 OR :OLD."Patient" = 0 THEN
			-- skip user form, no need to audit
			RETURN :new;
		END IF;
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
	   v_nPatientId := :OLD."Patient";
	   v_szTableDesc := AUDITLOG_PKG.GetPFormDescription(:OLD."OwnerType");
		v_szInfo := 'Form: ' || TRIM(:OLD."FormCode") || ' - ' || TRIM(:OLD."Description");
   ELSE
		IF :NEW."OwnerType" = 5 OR :NEW."Patient" = 0 THEN
			-- skip user form, no need to audit
			RETURN :new;
		END IF;
		
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
	   END IF;
	   v_nPatientId := :NEW."Patient";
	   v_szTableDesc := AUDITLOG_PKG.GetPFormDescription(:NEW."OwnerType");
		v_szInfo := 'Form: ' || TRIM(:NEW."FormCode") || ' - ' || TRIM(:NEW."Description");
   END IF;


   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_picture AFTER INSERT OR DELETE OR UPDATE ON picture FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PICTURE';
   v_szTableDesc := 'Patient Picture';
   v_szInfo := ' ';

   IF ( DELETING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
	   v_nPatientId := :OLD."Patient";
   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
	   END IF;
	   v_nPatientId := :NEW."Patient";
   END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_pinvoice AFTER INSERT OR DELETE OR UPDATE OF "PInvoice", "Patient", "InvoiceNumber", "Total", "InsTotal", "InsTransfer", "PtAdj", "Payed", "Audit", "PrintStatus", "Bank", "InvoiceDate", "InvHold", "InvHoldAudit", "PmtDueDate", "InvLetter1Audit", "InvLetter2Audit", "InvLetter3Audit", "Refund" ON pinvoice FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PINVOICE';

   IF ( DELETING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
   ELSIF ( INSERTING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
   END IF;

   v_szTableDesc := 'Patient Invoice';
   v_nPatientId := :NEW."Patient";
   v_szInfo := ' ';


   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ppage BEFORE INSERT ON ppage FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

   v_nOldPtSig	  NUMBER := 0;

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PPAGE';


   -- get previous PPAGE record
   BEGIN
     SELECT "PtSig" INTO v_nOldPtSig
     FROM PPAGE
     WHERE "FormCode" = :NEW."FormCode"
     AND "Patient" = :NEW."Patient"
     AND "PForm" = :NEW."PForm"
     AND "FItem" = :NEW."FItem"
     AND "AuditNumber" = :NEW."AuditNumber"-1;
   EXCEPTION WHEN NO_DATA_FOUND THEN
     v_nOldPtSig := 0;
   END;

   -- just auditing patient signing
   IF v_nOldPtSig = 0 AND :NEW."PtSig" <> 0 THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
      v_szTableDesc := 'Patient Form Signature';
      v_nPatientId := :NEW."Patient";
      v_szInfo := 'Form: ' || TRIM(:NEW."FormCode");

      AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);
   END IF;

END$trigger$
 ;
CREATE TRIGGER auditlog_ppagesig AFTER INSERT OR DELETE OR UPDATE OF "PPage", "Signee", "Name", "PtSig" ON ppagesig FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

   v_szFormCode	  VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PPAGESIG';

   -- Note: the followings will need to be customized
   --    to satisfy the requirements   needs!

   IF ( DELETING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
   ELSIF ( INSERTING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
   END IF;

   v_szTableDesc := 'Additional Form Signature';

   SELECT "Patient", "FormCode" INTO v_nPatientId, v_szFormCode FROM PPAGE WHERE "PPage" = NVL(:NEW."PPage", :OLD."PPage");
      v_szInfo := 'Form: ' || TRIM(v_szFormCode);


   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_prescrip AFTER INSERT OR DELETE OR UPDATE OF "Date", "Practice", "Provider", "DrugDescription", "Dose", "DrugFrqDesc", "Total", "Refills", "Note", "IsPhoned", "Area", "Telephone", "Pharmacy", "IsVoided", "VoidReason", "Reference", "Custom1", "Custom2", "IsFaxed", "FaxArea", "FaxPhone", "Drug", "PrescripType", "StartDate", "EndDate", "Deleted" ON prescrip FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

   v_nPrescipType  NUMBER;

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PRESCRIP';

   IF ( DELETING  OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
      v_nPrescipType := :OLD."PrescripType";
	   v_nPatientId := :OLD."Patient";
	   v_szInfo := TRIM(:OLD."Drug") || ' - ' || TRIM(:OLD."DrugDescription");
   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		END IF;
      v_nPrescipType := :NEW."PrescripType";
	   v_nPatientId := :NEW."Patient";
	   v_szInfo := TRIM(:NEW."Drug") || ' - ' || TRIM(:NEW."DrugDescription");
	END IF;

	IF ( v_nPrescipType = 0 ) THEN
		v_szTableDesc := 'Patient Medication';
	ELSIF ( v_nPrescipType = 1 ) THEN
		v_szTableDesc := 'Patient Prescription';
	ELSE
		v_szTableDesc := 'Patient RCopia e-Rx';
	END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptalert AFTER INSERT OR DELETE OR UPDATE OF "AlertType", "MedAlert", "Description", "Status", "OnsetDate", "Deleted", "User", "AddDateTime", "eRxSyncAudit", "RcopiaID", "NDCID", "SNOCode" ON ptalert FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

  	v_nAlertType	NUMBER;
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTALERT';

	IF (  deleting OR  (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
		v_szInfo := TRIM(:OLD."Description");
		v_nPatientId := :OLD."Patient";
		v_nActionType := AUDITLOG_PKG.c_nActionDelete;
		v_nAlertType := :OLD."AlertType";
	ELSE
		v_szInfo := TRIM(:NEW."Description");
		v_nPatientId := :NEW."Patient";
		IF ( Inserting ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		END IF;
		v_nAlertType := :NEW."AlertType";
	END IF;
	
	IF ( v_nAlertType = 0 ) THEN
		v_szTableDesc := 'Patient Clinical Alert';
	ELSIF ( v_nAlertType = 1 ) THEN
		v_szTableDesc := 'Patient Allergy';
	ELSE -- :OLD."AlertType" = 2
		v_szTableDesc := 'Patient Medical Problem';
	END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptcase AFTER INSERT OR DELETE OR UPDATE OF "CaseType", "CreationDate", "SiteName", "ProdType", "ExamDate", "StartDate", "CompleteDate", "Deleted" ON ptcase FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255);
   v_szTableDesc  VARCHAR2(255);
   v_szInfo       VARCHAR2(255);

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTCASE';

   v_szTableDesc := 'Surgery Cases';

   IF ( DELETING OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1)) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
      v_nPatientId := :OLD."Patient";
      v_szInfo := :OLD."CaseType" || ': Created on ' || TRIM(TO_CHAR(:OLD."CreationDate", 'MON DD,YYYY'));
   ELSE
      IF ( INSERTING ) THEN
      	v_nActionType := AUDITLOG_PKG.c_nActionAdd;
      ELSE
      	v_nActionType := AUDITLOG_PKG.c_nActionEdit;
      END IF;
      v_nPatientId := :NEW."Patient";
      v_szInfo := :NEW."CaseType" || ': Created on ' || TRIM(TO_CHAR(:NEW."CreationDate", 'MON DD,YYYY'));
   END IF;


   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptcont AFTER INSERT OR DELETE OR UPDATE OF "Deleted", "NoteCode", "ContactDate", "ContactTime", "ContactUser" ON ptcont FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTCONT';

   IF ( DELETING OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1)) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
   ELSIF ( INSERTING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
   END IF;

   v_szTableDesc := 'Patient Contact Notes';
   v_nPatientId := NVL(:NEW."Patient", :OLD."Patient");

   IF ( LENGTH(TRIM(NVL(:NEW."Note", :OLD."Note"))) < 50 ) THEN
      v_szInfo := TRIM(NVL(:NEW."Note", :OLD."Note"));
   ELSE
   	v_szInfo := RPAD(NVL(:NEW."Note", :OLD."Note"), 50) || '...';
   END IF;


   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptdepend AFTER INSERT OR DELETE OR UPDATE OF "Number", "IsCovered", "Relation", "HasPatientLimit", "PatientLimit", "PatientDeduct", "LimitBalance", "DeductBalance", "Deleted", "MedicaidCoPay", "StartDate", "EndDate", "CardVerNo", "CorrectStatus" ON ptdepend FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTDEPEND';
   v_szTableDesc := 'Policy Dependent';

   IF ( DELETING OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
	   v_nActionType := AUDITLOG_PKG.c_nActionDelete;
		v_nPatientId := :OLD."Patient";
	   SELECT TRIM(I."Company") || '(' || TRIM(I."Group") || ') - Holder: ' || TRIM(H."Last") || ', ' || TRIM(H."First")
				INTO v_szInfo FROM PATIENT H, PTPOL P, POLINS I
				WHERE H."Patient" = P."Patient" AND P."PolicyId" = :OLD."PolicyId" AND P."PolIns" = I."PolIns";
   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		END IF;
		v_nPatientId := :NEW."Patient";
	   SELECT TRIM(I."Company") || '(' || TRIM(I."Group") || ') - Holder: ' || TRIM(H."Last") || ', ' || TRIM(H."First")
				INTO v_szInfo FROM PATIENT H, PTPOL P, POLINS I
				WHERE H."Patient" = P."Patient" AND P."PolicyId" = :NEW."PolicyId" AND P."PolIns" = I."PolIns";
	END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptekg AFTER INSERT OR DELETE OR UPDATE OF "Appointment", "StartTime", "Length", "Type", "Audit", "VitMon" ON ptekg FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255);
   v_szTableDesc  VARCHAR2(255);
   v_szInfo       VARCHAR2(255);
   v_ApptDate     DATE;
   v_StartDateTime  DATE;

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTEKG';

   v_szTableDesc := 'Surgery EKGs';

   IF ( DELETING ) THEN
	v_nActionType := AUDITLOG_PKG.c_nActionDelete;
	SELECT "Patient", "Date" INTO v_nPatientId, v_ApptDate  FROM APPOINT WHERE "Appointment" = :OLD."Appointment";
	v_StartDateTime := :OLD."StartTime";

   ELSE
   	IF ( INSERTING ) THEN
		v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		SELECT "Patient", "Date" INTO v_nPatientId, v_ApptDate  FROM APPOINT WHERE "Appointment" = :NEW."Appointment";

   	ELSE
      		v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		SELECT "Patient", "Date" INTO v_nPatientId, v_ApptDate  FROM APPOINT WHERE "Appointment" = :NEW."Appointment";

   	END IF;
	v_StartDateTime := :NEW."StartTime";
   	
   END IF;

   v_szInfo := 'Appt Date: ' || TO_CHAR(v_ApptDate, 'MON DD,YYYY') || '; Entry Time: ' || TO_CHAR(v_StartDateTime, 'HH24:MI');

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptemploy AFTER INSERT OR DELETE OR UPDATE OF "Primary", "Area", "Tel", "Ext", "Occupation", "Deleted", "EndDate" ON ptemploy FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTEMPLOY';
   v_szTableDesc := 'Patient Employer';

   IF ( DELETING OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
	   v_nPatientId := :OLD."Patient";
		SELECT TRIM("Name") INTO v_szInfo FROM EMPLOYER WHERE "Employer" = :OLD."Employer";
   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		END IF;
	   v_nPatientId := :NEW."Patient";
		SELECT TRIM("Name") INTO v_szInfo FROM EMPLOYER WHERE "Employer" = :NEW."Employer";
	END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptfacul AFTER INSERT OR DELETE OR UPDATE OF "Faculty", "Discipline", "Deleted", "IsPrimary" ON ptfacul FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTFACUL';

   IF ( DELETING  OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
      v_nPatientId := :OLD."Patient";

      SELECT TRIM("First") || ' ' || TRIM("Name") || ' (' || TRIM("Logon") || ')'
		INTO v_szInfo FROM USERS WHERE "User" = :OLD."Faculty";
		
   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		END IF;
		
		v_nPatientId := :NEW."Patient";
		
      SELECT TRIM("First") || ' ' || TRIM("Name") || ' (' || TRIM("Logon" )|| ')'
		INTO v_szInfo FROM USERS WHERE "User" = :NEW."Faculty";
		
	END IF;

   v_szTableDesc := 'Faculty assigned';

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptgender AFTER INSERT OR DELETE OR UPDATE OF "PtSexOrient", "PtSOther", "PtSDeclined", "PtGenderId", "PtGOther", "PtGDeclined", "PtPreferPronouns", "PtPronounsOther", "PtPronounsDeclined" ON ptgender FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255);
   v_szTableDesc  VARCHAR2(255);
   v_szInfo       VARCHAR2(255);

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTGENDER';

   -- Note: the following will need to be customized
   --    to satisfy the requirements   needs!

   IF ( INSERTING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
   END IF;

   v_szTableDesc := 'Patient Sexual Orientation and Gender Identity';
   v_nPatientId := :NEW."Patient";
   v_szInfo := 'Inserted / updated';

   -- Note: end of customization!

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptguar AFTER INSERT OR DELETE OR UPDATE OF "IsPrimaryGuarantor", "IsSecondaryGuarantor", "IsPolicyGuarantor", "RespRelation", "Deleted", "Inactive" ON ptguar FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTGUAR';
   v_szTableDesc := 'Patient Guarantor';

   IF ( DELETING OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
	   v_nPatientId := :OLD."Patient";
	   SELECT RTRIM("Last") || ', ' || RTRIM("First") INTO v_szInfo FROM PATIENT WHERE "Patient" = :OLD."RespPatient";
   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		END IF;
	   v_nPatientId := :NEW."Patient";
	   SELECT RTRIM("Last") || ', ' || RTRIM("First") INTO v_szInfo FROM PATIENT WHERE "Patient" = :NEW."RespPatient";
   END IF;


   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_pthist AFTER INSERT ON pthist FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF (AUDITLOG_PKG.GetSecureLog() = 0) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTHIST';
   v_nActionType := AUDITLOG_PKG.c_nActionPrint;
   v_nPatientId := :NEW."Patient";
   v_szTableDesc := 'Patient History Printed: ' ||  SUBSTR(AUDITLOG_PKG.GetPtHistDescription(:NEW."Type", :NEW."RecId"), 1, 220);
   v_szInfo := SUBSTR(AUDITLOG_PKG.GetPtHistInfo(:NEW."Type", :NEW."RecId"), 1, 255);

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptimplnt AFTER INSERT OR DELETE OR UPDATE OF "Date", "Comment", "RawBarCode", "DeviceId", "SerialNumber", "LotNumber", "DistinctIdCode", "ManufacturedDate", "ExpiryDate", "IsRemoved", "Deleted", "Sites", "RemovedDate" ON ptimplnt FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255);
   v_szTableDesc  VARCHAR2(255);
   v_szInfo       VARCHAR2(255);

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTIMPLNT';

   -- Note: the following will need to be customized
   --    to satisfy the requirements   needs!

	IF ( DELETING  OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
	   v_nActionType := AUDITLOG_PKG.c_nActionDelete;
	   v_szInfo := 'Implant Info: ' || 'Sites ' || TRIM(:OLD."Sites") || '; ' || TRIM(:OLD."DeviceId") || '(' || TRIM(:OLD."SerialNumber") || ')';
    ELSIF ( INSERTING ) THEN
  	   v_nActionType := AUDITLOG_PKG.c_nActionAdd;
	   v_szInfo := 'Implant Info: ' || 'Sites ' || TRIM(:NEW."Sites") || '; ' || TRIM(:NEW."DeviceId") || '(' || TRIM(:NEW."SerialNumber") || ')';
    ELSE
       v_nActionType := AUDITLOG_PKG.c_nActionEdit;
	   v_szInfo := 'Implant Info: ' || 'Sites ' || TRIM(:NEW."Sites") || '; ' || TRIM(:NEW."DeviceId") || '(' || TRIM(:NEW."SerialNumber") || ')';
    END IF;

   v_szTableDesc := 'Patient Implant Information';
   v_nPatientId := :NEW."Patient";

   -- Note: end of customization!

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptldetails AFTER INSERT OR DELETE OR UPDATE OF "Description", "Date", "Path", "Type", "Deleted", "FileExt", "AtTab", "Consent", "ExpiryDate", "Status", "DocTempl", "OwnerType", "OwnerId", "AddDateTime" ON ptldetails FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTLETTER';


   IF ( DELETING   OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
   ELSIF ( INSERTING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
   END IF;


   v_nPatientId := NVL(:NEW."Patient", :OLD."Patient");

   IF (NVL(:NEW."Type", :OLD."Type") = 3) THEN
      v_szTableDesc := 'Patient Letter';
      v_szInfo := NVL(:NEW."Description", :OLD."Description");
   ELSIF (NVL(TRIM(:NEW."Consent"), TRIM(:OLD."Consent")) IS NOT NULL) THEN
      v_szTableDesc := 'Patient Consent';
      v_szInfo := NVL(TRIM(:NEW."Consent"), TRIM(:OLD."Consent")) || ' - ' || NVL(:NEW."Description", :OLD."Description");
   ELSE
      v_szTableDesc := 'Patient Attachment';
      v_szInfo := NVL(:NEW."Description", :OLD."Description");
   END IF;


   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptlinfo AFTER INSERT ON ptlinfo FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTLINFO';
   v_szTableDesc := 'Patient Clinical Reconciliation Info';
	v_nActionType := AUDITLOG_PKG.c_nActionAdd;
   v_nPatientId := :NEW."Patient";
   v_szInfo := :NEW."ContentSource" || ' - ' || TRIM(TO_CHAR(:NEW."ContentDate", 'MON DD,YYYY')) ||
		': ' || AUDITLOG_PKG.GetPtLInfoType(:NEW."PtLType");

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptmanage AFTER INSERT OR DELETE OR UPDATE OF "User", "IsPrimary", "AuditUser", "StationId", "Deleted" ON ptmanage FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTMANAGE';

   IF ( DELETING  OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
      v_nPatientId := :OLD."Patient";

      SELECT TRIM("First") || ' ' || TRIM("Name") || ' (' || TRIM("Logon") || ')'
		INTO v_szInfo FROM USERS WHERE "User" = :OLD."User";
		
   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		END IF;
		
		v_nPatientId := :NEW."Patient";
		
      SELECT TRIM("First") || ' ' || TRIM("Name") || ' (' || TRIM("Logon" )|| ')'
		INTO v_szInfo FROM USERS WHERE "User" = :NEW."User";
		
	END IF;

   v_szTableDesc := 'Assigned Managers';

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptneed AFTER INSERT OR DELETE OR UPDATE OF "NeedCode", "NeedDate", "Assigned", "Deleted", "Note", "NeedSts" ON ptneed FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTNEED';
   v_szTableDesc := 'Patient Needs';

   IF ( DELETING  OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
	   v_nPatientId := :OLD."Patient";
	   v_szInfo := :OLD."NeedCode";
   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
	   END IF;
	   v_nPatientId := :NEW."Patient";
	   v_szInfo := :NEW."NeedCode";
   END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptnote AFTER INSERT OR DELETE OR UPDATE OF "Date", "User", "EntryDate", "NoteCode", "Deleted" ON ptnote FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTNOTE';
   v_szTableDesc := 'Patient Notes';

   IF ( DELETING  OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
	   v_nPatientId := :OLD."Patient";
		if ( LENGTH(TRIM(:OLD."Text")) < 50 ) THEN
			v_szInfo := TRIM(:OLD."Text");
		ELSE
			v_szInfo := RPAD(:OLD."Text", 50) || '...';
		END IF;
   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
	   END IF;
	   v_nPatientId := :NEW."Patient";
		if ( LENGTH(TRIM(:NEW."Text")) < 50 ) THEN
			v_szInfo := TRIM(:NEW."Text");
		ELSE
			v_szInfo := RPAD(:NEW."Text", 50) || '...';
		END IF;
   END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptobj AFTER INSERT OR DELETE OR UPDATE OF "Status", "TxPlan", "Deleted" ON ptobj FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTOBJ';

   IF ( DELETING OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
   ELSIF ( INSERTING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
   END IF;

   v_szTableDesc := 'Patient Objective';
   v_nPatientId := NVL(:NEW."Patient", :OLD."Patient");

   IF ( LENGTH(TRIM(NVL(:NEW."Description", :OLD."Description"))) < 50 ) THEN
      v_szInfo := NVL(:NEW."Status", :OLD."Status") || ' - ' || TRIM(NVL(:NEW."Description", :OLD."Description"));
   ELSE
   	v_szInfo := NVL(:NEW."Status", :OLD."Status") || ' - ' || RPAD(NVL(:NEW."Description", :OLD."Description"), 50) || '...';
   END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptperio AFTER INSERT OR DELETE OR UPDATE OF "ChartDate", "Deleted", "ChartByType", "ProdType", "Provider", "Completed", "PerExam" ON ptperio FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTPERIO';
   v_szTableDesc := 'Patient Perio Chart';

   IF ( DELETING  OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
	   v_nPatientId := :OLD."Patient";
	   IF ( NOT (RTRIM(:OLD."PerExam") IS NULL OR LENGTH(RTRIM(:OLD."PerExam")) = 0) ) THEN
			v_szInfo := RTRIM(:OLD."PerExam") || ': Chart on ' || TRIM(TO_CHAR(:OLD."ChartDate", 'MON DD,YYYY'));	--B142155
		ELSE
			v_szInfo := 'Chart on ' || TRIM(TO_CHAR(:OLD."ChartDate", 'MON DD,YYYY'));	--B142155
		END IF;
   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSIF ( :NEW."Deleted" = 2 ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionStrikeOut;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
	   END IF;
	   v_nPatientId := :NEW."Patient";
	   IF ( NOT (RTRIM(:NEW."PerExam") IS NULL OR LENGTH(RTRIM(:NEW."PerExam")) = 0) ) THEN
			v_szInfo := RTRIM(:NEW."PerExam") || ': Chart on ' || TRIM(TO_CHAR(:NEW."ChartDate", 'MON DD,YYYY')) ;	--B142155
		ELSE
			v_szInfo := 'Chart on ' || TRIM(TO_CHAR(:NEW."ChartDate", 'MON DD,YYYY'));	--B142155
		END IF;
   END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptperst AFTER INSERT OR DELETE OR UPDATE OF "PerProg", "PerType", "PS1Score", "PS1Abnormal", "PS2Score", "PS2Abnormal", "PS3Score", "PS3Abnormal", "PS4Score", "PS4Abnormal", "PS5Score", "PS5Abnormal", "PS6Score", "PS6Abnormal" ON ptperst FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTPERST';
   v_szTableDesc := 'Patient Perio Statistics';

   IF ( DELETING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
	   v_nPatientId := :OLD."Patient";
	   v_szInfo := TRIM(:OLD."PerProg") || ' ' || TRIM(:OLD."PerType");
   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		END IF;
	   v_nPatientId := :NEW."Patient";
	   v_szInfo := TRIM(:NEW."PerProg") || ' ' || TRIM(:NEW."PerType");
	END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptphys AFTER INSERT OR DELETE OR UPDATE OF "Physician", "IsPrimary", "Deleted" ON ptphys FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTPHYS';
   v_szTableDesc := 'Patient Physician';

   IF ( DELETING OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
	   v_nPatientId := :OLD."Patient";
		SELECT RTRIM("Last") || ', ' || RTRIM("First") INTO v_szInfo FROM PHYSICIA WHERE "Physician" = :OLD."Physician";
   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		END IF;
	   v_nPatientId := :NEW."Patient";
		SELECT RTRIM("Last") || ', ' || RTRIM("First") INTO v_szInfo FROM PHYSICIA WHERE "Physician" = :NEW."Physician";
   END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptpol AFTER INSERT OR DELETE OR UPDATE OF "Policy", "LimitBalance", "DeductBalance", "ResetDate", "StartDate", "Deleted", "SharedEntryId" ON ptpol FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTPOL';
   v_szTableDesc := 'Patient Insurance Policy';

   -- Note: the followings will need to be customized
   --    to satisfy the requirements   needs!

   IF ( DELETING  OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
	   v_nPatientId := :OLD."Patient";
	   SELECT TRIM(I."Company") || '(' || TRIM(I."Group" )|| ') - ' || TRIM(:OLD."Policy")
					INTO v_szInfo FROM POLINS I WHERE I."PolIns" = :OLD."PolIns";
   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		END IF;
	   v_nPatientId := :NEW."Patient";
	   SELECT TRIM(I."Company") || '(' || TRIM(I."Group" )|| ') - ' || TRIM(:NEW."Policy")
					INTO v_szInfo FROM POLINS I WHERE I."PolIns" = :NEW."PolIns";
	END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptprb AFTER INSERT OR DELETE OR UPDATE OF "Problem", "Description", "ShortDesc", "Site", "Surface", "Status", "AreaFound", "AppUser", "AppDateTime", "Deleted", "Date" ON ptprb FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTPRB';
   v_szTableDesc := 'Patient Problem';

   IF ( DELETING OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
      v_nPatientId := :OLD."Patient";
      v_szInfo := :OLD."Description" || ' ' || :OLD."Site" || ' ' || :OLD."Surface" || ' ' || :OLD."Status";

   ELSIF ( INSERTING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
      v_nPatientId := :NEW."Patient";
		v_szInfo := :NEW."Description" || ' ' || :NEW."Site" || ' ' || :NEW."Surface" || ' ' || :NEW."Status";

   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
      v_nPatientId := :NEW."Patient";
      v_szInfo := :NEW."Description" || ' ' || :NEW."Site" || ' ' || :NEW."Surface" || ' ' || :NEW."Status";

   END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptprev AFTER INSERT OR DELETE OR UPDATE OF "PtPrev", "Patient", "PrevCare", "DueDate", "Deleted", "ExamState" ON ptprev FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTPREV';
   v_szTableDesc := 'Patient Preventive Care';

   IF ( DELETING  OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
	   v_nPatientId := :OLD."Patient";
	   v_szInfo := TRIM(:OLD."PrevCare") || ': Due on ' || TRIM(TO_CHAR(:OLD."DueDate", 'MON DD,YYYY'));	--B142155
   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		END IF;
	   v_nPatientId := :NEW."Patient";
	   v_szInfo := TRIM(:New."PrevCare") || ': Due on ' || TRIM(TO_CHAR(:NEW."DueDate", 'MON DD,YYYY'));	--B142155	
	END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptprod AFTER INSERT OR DELETE OR UPDATE OF "StartDate", "EndDate", "IsRestricted", "IsPrimary", "Discipline", "NeedReq", "Id", "CreateDate", "User", "StationId", "Deleted" ON ptprod FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTPROD';

   IF ( DELETING  OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
      v_nPatientId := :OLD."Patient";
		v_szInfo := 'Producer: ' || :OLD."Producer";
   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		END IF;
		
		v_nPatientId := :NEW."Patient";
		v_szInfo := 'Producer: ' || :NEW."Producer";
	END IF;

   v_szTableDesc := 'Assigned Providers';
   v_nPatientId := :NEW."Patient";

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptrace AFTER INSERT OR DELETE OR UPDATE OF "Race", "Deleted" ON ptrace FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTRACE';

   IF ( DELETING  OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
      v_nPatientId := :OLD."Patient";
		v_szInfo := 'Race: ' || :OLD."Race";
   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		END IF;
		
		v_nPatientId := :NEW."Patient";
		v_szInfo := 'Race: ' || :NEW."Race";
	END IF;

   v_szTableDesc := 'Race Information';

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptrecall AFTER INSERT OR DELETE OR UPDATE OF "Recall", "RecallDate", "Provider", "Status", "Comment", "Units", "ApptDate", "Booked", "User", "CreationDate", "RecallType", "Deleted", "Treatme2Id", "Clinic", "ApptCode" ON ptrecall FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTRECALL';

	v_szTableDesc := 'Patient Recall';
	IF (  DELETING OR  (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
		v_szInfo := TRIM(:OLD."RecallType") || ' - ' || TRIM(:OLD."Recall") || ' - ' || TRIM(TO_CHAR(:OLD."RecallDate", 'MON DD,YYYY'));	--B142155
		v_nPatientId := :OLD."Patient";
		v_nActionType := AUDITLOG_PKG.c_nActionDelete;
	ELSE
		v_szInfo := TRIM(:NEW."RecallType") ||  ' - ' || TRIM(:NEW."Recall") || ' - ' || TRIM(TO_CHAR(:NEW."RecallDate", 'MON DD,YYYY'));	--B142155
		v_nPatientId := :NEW."Patient";
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		END IF;
	END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptrefer AFTER INSERT OR DELETE OR UPDATE OF "Date", "Referral", "IsPrimary", "FromToFlag", "Note", "Deleted", "EndDate" ON ptrefer FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTREFER';
   v_szTableDesc := 'Patient Referral';

   IF ( DELETING OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
	   v_nPatientId := :OLD."Patient";
	   IF ( :OLD."FromToFlag" = 0 ) THEN
			v_szTableDesc := v_szTableDesc || ' (from)';
		ELSIF ( :OLD."FromToFlag" = 0 ) THEN
			v_szTableDesc := v_szTableDesc || ' (to)';
		ELSE
			v_szTableDesc := v_szTableDesc || ' (from/to)';
		END IF;
		SELECT RTRIM("Name") || (CASE WHEN NOT (TRIM("First") IS NULL OR LENGTH(TRIM("First")) = 0) THEN ', ' ELSE ' ' END) || RTRIM("First")
					INTO v_szInfo FROM REFERRAL WHERE "Referral" = :OLD."Referral";
   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
	   END IF;
	   v_nPatientId := :NEW."Patient";
	   IF ( :NEW."FromToFlag" = 0 ) THEN
			v_szTableDesc := v_szTableDesc || ' (from)';
		ELSIF ( :NEW."FromToFlag" = 0 ) THEN
			v_szTableDesc := v_szTableDesc || ' (to)';
		ELSE
			v_szTableDesc := v_szTableDesc || ' (from/to)';
		END IF;
		SELECT RTRIM("Name") || (CASE WHEN NOT (TRIM("First") IS NULL OR LENGTH(TRIM("First")) = 0) THEN ', ' ELSE ' ' END) || RTRIM("First")
							INTO v_szInfo FROM REFERRAL WHERE "Referral" = :NEW."Referral";
   END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptsdose AFTER INSERT OR DELETE OR UPDATE OF "PtSDrug", "EntryTime", "Amount", "Deleted" ON ptsdose FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255);
   v_szTableDesc  VARCHAR2(255);
   v_szInfo       VARCHAR2(255);
   v_szTime       VARCHAR2(255);
   v_szDrugDesc   VARCHAR2(255);
   v_ApptDate     DATE;

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTSDOSE';
   v_szTableDesc := 'Surgery Drug Doses';

   IF ( DELETING ) THEN
		v_nActionType := AUDITLOG_PKG.c_nActionDelete;
		v_szTime := '; Entry Time: ' || TO_CHAR(:OLD."EntryTime", 'HH24:MI');
		
		SELECT A."Patient", A."Date" INTO v_nPatientId, v_ApptDate FROM PTSDRUG P, APPOINT A WHERE A."Appointment" = P."Appointment" AND P."PtSDrug" = :OLD."PtSDrug";

		BEGIN
			SELECT D."ShortName" INTO v_szDrugDesc FROM PTSDRUG P, ANESDRUG D WHERE P."Drug" = D."Drug" AND P."PtSDrug" = :OLD."PtSDrug"; -- AX-16533.18277
   		EXCEPTION WHEN NO_DATA_FOUND THEN
			v_szDrugDesc := '';
		END;
   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
			v_szTime := '; Entry Time: ' || TO_CHAR(:NEW."EntryTime", 'HH24:MI');
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
			IF (:OLD."EntryTime"  = :NEW."EntryTime") THEN
				v_szTime := '; Entry Time: ' || TO_CHAR(:OLD."EntryTime", 'HH24:MI');
			ELSE
				v_szTime := '; Entry Time changed from ' || TO_CHAR(:OLD."EntryTime", 'HH24:MI') || ' to ' || TO_CHAR(:OLD."EntryTime", 'HH24:MI');
			END IF;
		END IF;
		
		BEGIN
			SELECT A."Patient", A."Date" INTO v_nPatientId, v_ApptDate FROM PTSDRUG P, APPOINT A WHERE A."Appointment" = P."Appointment" AND P."PtSDrug" = :NEW."PtSDrug";
			SELECT D."ShortName" INTO v_szDrugDesc FROM PTSDRUG P, ANESDRUG D WHERE P."Drug" = D."Drug" AND P."PtSDrug" = :NEW."PtSDrug"; -- AX-16533.18277
   		EXCEPTION WHEN NO_DATA_FOUND THEN
			v_szDrugDesc := '';
		END;
   END IF;

   v_szInfo := v_szDrugDesc  || v_szTime || '; Appt Date: ' || TO_CHAR(v_ApptDate, 'MON DD,YYYY');

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptsdrug AFTER INSERT OR DELETE OR UPDATE OF "Appointment", "Drug", "AnesUnit", "AnesDelv", "AnesGaug", "Deleted", "OtherDrug" ON ptsdrug FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255);
   v_szTableDesc  VARCHAR2(255);
   v_szInfo       VARCHAR2(255);
   v_szDrugDesc   VARCHAR2(255);
   v_ApptDate     DATE;

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTSDRUG';

   v_szTableDesc := 'Surgery Drugs';

   IF ( DELETING ) THEN
	v_nActionType := AUDITLOG_PKG.c_nActionDelete;
	SELECT "Patient", "Date" INTO v_nPatientId, v_ApptDate  FROM APPOINT WHERE "Appointment" = :OLD."Appointment";

	BEGIN
		SELECT "Description" INTO v_szDrugDesc FROM DRUG WHERE "Drug" = :OLD."Drug";
   	EXCEPTION WHEN NO_DATA_FOUND THEN
		v_szDrugDesc := '';
	END;
   ELSE
   	IF ( INSERTING ) THEN
		v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		SELECT "Patient", "Date" INTO v_nPatientId, v_ApptDate  FROM APPOINT WHERE "Appointment" = :NEW."Appointment";

   	ELSE
      		v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		SELECT "Patient", "Date" INTO v_nPatientId, v_ApptDate  FROM APPOINT WHERE "Appointment" = :NEW."Appointment";

   	END IF;
   	
	BEGIN
		SELECT "ShortName" INTO v_szDrugDesc FROM ANESDRUG WHERE "Drug" = :NEW."Drug";
   	EXCEPTION WHEN NO_DATA_FOUND THEN
		v_szDrugDesc := '';
	END;
   END IF;

   v_szInfo := v_szDrugDesc || '; Appt Date: ' || TO_CHAR(v_ApptDate, 'MON DD,YYYY');

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptstage AFTER INSERT OR DELETE OR UPDATE OF "Appointment", "StageSet", "StageCode", "StageStart" ON ptstage FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255);
   v_szTableDesc  VARCHAR2(255);
   v_szInfo       VARCHAR2(255);
   v_szStageDesc  VARCHAR2(255);

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTSTAGE';

   v_szTableDesc := 'Surgery Stages';

   IF ( DELETING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
      SELECT "Patient" INTO v_nPatientId  FROM APPOINT WHERE "Appointment" = :OLD."Appointment";

   ELSIF ( INSERTING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
      SELECT "Patient" INTO v_nPatientId  FROM APPOINT WHERE "Appointment" = :NEW."Appointment";

   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
      SELECT "Patient" INTO v_nPatientId  FROM APPOINT WHERE "Appointment" = :NEW."Appointment";

   END IF;

	BEGIN
		IF ( DELETING ) THEN
			IF ((TRIM(:OLD."StageCode") IS NULL OR LENGTH(TRIM(:OLD."StageCode")) = 0)) THEN
				v_szStageDesc := 'End Surgery';
			ELSE
				SELECT "Description" INTO v_szStageDesc FROM OSSTAGE WHERE "Code" = :OLD."StageCode" AND "Set" = :OLD."StageSet";
			END IF;
		ELSE
			IF ((TRIM(:NEW."StageCode") IS NULL OR LENGTH(TRIM(:NEW."StageCode")) = 0)) THEN
				v_szStageDesc := 'End Surgery';
			ELSE
				SELECT "Description" INTO v_szStageDesc FROM OSSTAGE WHERE "Code" = :NEW."StageCode" AND "Set" = :NEW."StageSet";
			END IF;
		END IF;
   EXCEPTION WHEN NO_DATA_FOUND THEN
		v_szStageDesc := '';
   END;


   v_szInfo := v_szStageDesc || ' ' || TO_CHAR(SYSDATE, 'MON DD,YYYY HH24:MI');

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptsumm AFTER INSERT OR DELETE OR UPDATE OF "SummCode", "Value1", "Value2", "Value1Override", "Value2Override" ON ptsumm FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTSUMM';

   IF ( DELETING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
   ELSIF ( INSERTING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
   END IF;

   v_szTableDesc := 'Patient Summaries';
   v_nPatientId := :NEW."Patient";
   v_szInfo := 'Summary Code: ' || :NEW."SummCode";

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_pttypes AFTER INSERT OR DELETE OR UPDATE OF "PatType", "Deleted" ON pttypes FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTTYPES';
   v_szTableDesc := 'Patient Types';

   IF ( DELETING  OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
      v_nPatientId := :OLD."Patient";
		v_szInfo := 'Type: ' || :OLD."PatType";
   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		END IF;
		
		v_nPatientId := :NEW."Patient";
		v_szInfo := 'Type: ' || :NEW."PatType";
	END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptvital AFTER INSERT OR DELETE OR UPDATE OF "Appointment", "EntryMode", "EntryTime", "Error", "Artifact", "HeartRate", "Temperature", "RespRate", "SystolicBP", "DiastolicBP", "SpO2", "ECO2", "Deleted" ON ptvital FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255);
   v_szTableDesc  VARCHAR2(255);
   v_szInfo       VARCHAR2(255);

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTVITAL';

   v_szTableDesc := 'Patient Vitals';

   IF ( DELETING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
      SELECT "Patient" INTO v_nPatientId  FROM APPOINT WHERE "Appointment" = :OLD."Appointment";

   ELSIF ( INSERTING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
      SELECT "Patient" INTO v_nPatientId  FROM APPOINT WHERE "Appointment" = :NEW."Appointment";

   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
      SELECT "Patient" INTO v_nPatientId  FROM APPOINT WHERE "Appointment" = :NEW."Appointment";

   END IF;

   v_szInfo := 'Entry Time: ' || TO_CHAR(:NEW."EntryTime", 'HH24:MI');

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptvtlart AFTER INSERT OR DELETE OR UPDATE OF "PtVital", "VitalType", "ArtifactText" ON ptvtlart FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255);
   v_szTableDesc  VARCHAR2(255);
   v_szInfo       VARCHAR2(255);

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTVTLART';

   v_szTableDesc := 'Patient Surgery Vitals Artifact';

   IF ( DELETING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
      SELECT "Patient" INTO v_nPatientId  FROM APPOINT A, PTVITAL V WHERE V."PtVital" = :OLD."PtVital" AND A."Appointment" = V."Appointment";

   ELSIF ( INSERTING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
      SELECT "Patient" INTO v_nPatientId  FROM APPOINT A, PTVITAL V WHERE V."PtVital" = :NEW."PtVital" AND A."Appointment" = V."Appointment";

   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
      SELECT "Patient" INTO v_nPatientId  FROM APPOINT A, PTVITAL V WHERE V."PtVital" = :NEW."PtVital" AND A."Appointment" = V."Appointment";

   END IF;

   v_szInfo := ' ';

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_ptxray AFTER INSERT OR DELETE OR UPDATE OF "DateTaken", "Procedure", "ExposureCount", "Deleted", "OrigRecNo", "Description", "IsDigital" ON ptxray FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'PTXRAY';
   v_szTableDesc := 'Patient X-ray Record';


   IF ( DELETING OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
		v_nPatientId := :OLD."Patient";
		v_szInfo := TRIM(:OLD."Procedure") || ' - Count# ' || TRIM(TO_CHAR(:OLD."ExposureCount"));

   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		END IF;
		v_nPatientId := :NEW."Patient";
		v_szInfo := TRIM(:NEW."Procedure") || ' - Count# ' || TRIM(TO_CHAR(:NEW."ExposureCount"));
   END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_reqnote AFTER INSERT OR DELETE OR UPDATE OF "ReqNote", "Appointment", "Date", "Time", "User", "StationId", "Deleted", "DeleteDate" ON reqnote FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

   v_nApptType		NUMBER;

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'REQNOTE';
   v_szTableDesc := 'Appointment Notes';

   IF ( DELETING  OR  (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
		SELECT "Patient", "Type" INTO v_nPatientId, v_nApptType FROM APPOINT WHERE "Appointment" = :OLD."Appointment";
		if ( LENGTH(TRIM(:OLD."Note")) < 50 ) THEN
			v_szInfo := AUDITLOG_PKG.GetAppointDescription(v_nApptType) || ' - ' || TRIM(:OLD."Note");
		ELSE
			v_szInfo := AUDITLOG_PKG.GetAppointDescription(v_nApptType) || ' - ' || RPAD(:OLD."Note", 50) || '...';
		END IF;
   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		END IF;
		SELECT "Patient", "Type" INTO v_nPatientId, v_nApptType FROM APPOINT WHERE "Appointment" = :NEW."Appointment";
		if ( LENGTH(TRIM(:NEW."Note")) < 50 ) THEN
		   v_szInfo := AUDITLOG_PKG.GetAppointDescription(v_nApptType) || ' - ' || TRIM(:NEW."Note");
		ELSE
			v_szInfo := AUDITLOG_PKG.GetAppointDescription(v_nApptType) || ' - ' || RPAD(:NEW."Note", 50) || '...';
		END IF;
   END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_treatme2 AFTER INSERT OR DELETE OR UPDATE OF "CodeId", "Days", "PreId", "Site", "Status", "Surface", "Deleted", "Site2", "Number", "Phase", "Seq", "Provider", "Custom1", "Custom2", "ParentId", "Discipline", "TxPTx", "StationId", "Custom3", "Custom4", "DeletionDate", "AddDateTime", "Unit" ON treatme2 FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'TREATME2';

   IF ( DELETING  OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
		SELECT "PtxPId" INTO v_nPatientId FROM PATIENT2 WHERE "Auto" = :OLD."PId";
	   v_szTableDesc := AUDITLOG_PKG.GetTreatme2Description(:OLD."Status");
	   v_szInfo := AUDITLOG_PKG.GetTreatme2AdditionalInfo(:OLD."Status", :OLD."CodeId", :OLD."Days", :OLD."Site", :OLD."Site2", :OLD."Surface");
   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSIF ( :NEW."Deleted" = 2 ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionStrikeOut;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		END IF;
		SELECT "PtxPId" INTO v_nPatientId FROM PATIENT2 WHERE "Auto" = :NEW."PId";
	   v_szTableDesc := AUDITLOG_PKG.GetTreatme2Description(:NEW."Status");
	   v_szInfo := AUDITLOG_PKG.GetTreatme2AdditionalInfo(:NEW."Status", :NEW."CodeId", :NEW."Days", :NEW."Site", :NEW."Site2", :NEW."Surface");
   END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_trx AFTER INSERT OR DELETE OR UPDATE OF "Type", "Id", "Treatment", "Patient", "Family", "Status", "Date", "SubmitDate", "ClaimDoctor", "Submitted", "TreatmentDate", "CreationDate", "Procedure", "Code", "Site", "Surface", "Unit", "Producer", "Total", "InsTotal", "Company1", "Policy1", "Category1", "Item1", "Deduct1", "Assign1", "Eligible1", "Pct1", "Amount1", "InsPayed1", "InsAdj1", "Company2", "Policy2", "Category2", "Item2", "Assign2", "Deduct2", "Eligible2", "Pct2", "Amount2", "InsPayed2", "InsAdj2", "Company3", "Policy3", "Category3", "Item3", "Assign3", "Deduct3", "Eligible3", "Pct3", "Amount3", "InsPayed3", "InsAdj3", "Description", "Deleted", "Bank", "Payed", "InsPayed", "PtAdj", "InsAdj", "EstimateF", "Additional", "TxStatus", "User", "PtWriteOff", "PolicyId1", "PolicyId2", "PolicyId3", "InsStatus1", "InsStatus2", "InsStatus3", "IsBankDeposit", "PlanTotal", "Phase", "Seq", "AppUser", "AppDate", "Site2", "Custom1", "Custom2", "PayPlanId", "Discipline", "DiscountedPmtId", "Location", "OrigAssign1", "OrigAssign2", "OrigAssign3", "InDispute", "DisputeDate", "DeletionDate", "InsTransfer1", "InsTransfer2", "InsTransfer3", "InsTransfer", "InsPmtId", "StationId", "Practice", "Suspended", "DelAppUser", "DelAppDate", "OrthoStatus", "CvgType", "ModifiedDate", "OrigClaimDate", "SubmitMode", "Custom3", "Custom4", "CorrespondCode", "InsCvgType1", "InsCvgType2", "InsCvgType3", "EntryUser", "PlanInProcTotal", "TrxDep", "CustomaryTotal", "TaxRate", "TaxAmount" ON trx FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'TRX';

   IF ( DELETING OR  (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
	   v_nPatientId := :OLD."Patient";
		v_szTableDesc := AUDITLOG_PKG.GetTrxDescription(:OLD."Type", :OLD."Id", :OLD."Status", :OLD."PlanTotal");
		if ( (TRIM(v_szTableDesc) IS NULL OR LENGTH(TRIM(v_szTableDesc)) = 0) ) THEN
			-- no audit required in this case
			RETURN :new;		
		END IF;
		
		IF ( :OLD."Type" = 5 ) THEN
		   v_szInfo := TRIM(:OLD."Procedure") || ' ' || :OLD."Site" || ' ' ||  :OLD."Surface";
		ELSIF ( :OLD."Type" = 1 ) THEN
		   v_szInfo := TO_CHAR(:OLD."TreatmentDate", 'MON DD,YYYY') || ' - ' || TRIM(:OLD."Procedure") || ' ' || :OLD."Site" || ' ' ||  :OLD."Surface";	--B142155
		ELSE
			v_szInfo := TO_CHAR(:OLD."TreatmentDate", 'MON DD,YYYY') || ' - ' || TRIM(:OLD."Code") || ' ' || :OLD."Description";	--B142155
		END IF;
		
   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
	      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
	   END IF;
	   v_nPatientId := :NEW."Patient";
		v_szTableDesc := AUDITLOG_PKG.GetTrxDescription(:NEW."Type", :NEW."Id", :NEW."Status", :NEW."PlanTotal");
		if ( (TRIM(v_szTableDesc) IS NULL OR LENGTH(TRIM(v_szTableDesc)) = 0) ) THEN
			-- no audit required in this case
			RETURN :new;		
		END IF;
		if ( :NEW."Deleted" = 2 ) THEN
			v_szTableDesc :=  v_szTableDesc || ' (strike-out)';	
		END IF;
		IF ( :NEW."Type" = 1 OR :NEW."Type" = 5 ) THEN
		   v_szInfo := TRIM(:NEW."Procedure") || ' ' || :NEW."Site" || ' ' ||  :NEW."Surface";
		ELSIF ( :OLD."Type" = 1 ) THEN
		   v_szInfo := TO_CHAR(:NEW."TreatmentDate", 'MON DD,YYYY') || ' - ' || TRIM(:NEW."Procedure") || ' ' || :NEW."Site" || ' ' ||  :NEW."Surface";	--B142155
		ELSE
			v_szInfo := TO_CHAR(:NEW."TreatmentDate", 'MON DD,YYYY') || ' - ' || TRIM(:NEW."Code") || ' ' || :NEW."Description";	--B142155
		END IF;
	
   END IF;


   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_trxaddl AFTER INSERT OR DELETE OR UPDATE OF "IsProsthetics", "IsInitialPlacement", "InitialPlacementDate", "IsOrthodontics", "IsOrthoReplacement", "OrthoReplacementDate", "OrthoTotalMonths", "OrthoMonthsLeft", "ProstheticArch", "PriorProsthMaterial", "ProcType", "MtlFwdEmail", "MtlFwdCorrespond", "MtlFwdModels", "MtlFwdXrays", "MtlFwdImages", "DiagnosticCode", "InstitutionCode", "Referral", "ReferralCDANo", "ReferralReason", "OrthoStartDate", "OrthoFirstFee", "OrthoDiagFee", "OrthoInitPmt", "OrthoPmtMode", "OrthoDuration", "OrthoNumPmts", "OrthoPmtAmt", "ChartLnk" ON trxaddl FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

   v_szDesc		   VARCHAR2(51 );
   v_szStatus		VARCHAR2(11 );
   v_nPlanTotal	NUMBER := 0; -- AX-21987

   v_szProcedure  VARCHAR2(11 );
   v_szSite			VARCHAR2(11 );
   v_szSurface		VARCHAR2(11 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'TRXADDL';
   v_szTableDesc := 'Additional Tx Information';

   IF ( DELETING ) THEN

      v_nActionType := AUDITLOG_PKG.c_nActionDelete;

		IF (:OLD."Id" > 0) THEN
			SELECT "Patient", "Status", "PlanTotal", "Procedure", "Site", "Surface"
				 INTO v_nPatientId, v_szStatus, v_nPlanTotal, v_szProcedure,v_szSite, v_szSurface
				 FROM TRX WHERE "Type" = :OLD."Type" AND "Id" = :OLD."Id" AND "Treatment" = :OLD."Treatment";
			v_szDesc := AUDITLOG_PKG.GetTrxDescription(:OLD."Type", :OLD."Id", v_szStatus, v_nPlanTotal);
		ELSE -- AX-21987

			-- AX-21988g
			BEGIN
				SELECT "Patient", "Status", "Procedure", "Site", "Surface"
				INTO v_nPatientId, v_szStatus, v_szProcedure, v_szSite, v_szSurface
				FROM CHARTLNK WHERE "Id" = :OLD."ChartLnk";
			EXCEPTION WHEN NO_DATA_FOUND THEN
				v_nPatientId := 0;
			END;

			v_szDesc := AUDITLOG_PKG.GetTrxDescription(0, 1, v_szStatus, 0);

		END IF;


   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
	      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
	   END IF;

	   IF (:NEW."Id" > 0) THEN
			SELECT "Patient", "Status", "PlanTotal", "Procedure", "Site", "Surface"
				 INTO v_nPatientId, v_szStatus, v_nPlanTotal, v_szProcedure,v_szSite, v_szSurface
				 FROM TRX WHERE "Type" = :NEW."Type" AND "Id" = :NEW."Id" AND "Treatment" = :NEW."Treatment";
			v_szDesc := AUDITLOG_PKG.GetTrxDescription(:NEW."Type", :NEW."Id", v_szStatus, v_nPlanTotal);
		ELSE -- AX-21987

			-- AX-22597 added exception handling; proper fix should be looking at treatme2
			BEGIN
				SELECT "Patient", "Status", "Procedure", "Site", "Surface"
				 INTO v_nPatientId, v_szStatus, v_szProcedure, v_szSite, v_szSurface
				 FROM CHARTLNK WHERE "Id" = :NEW."ChartLnk";
			EXCEPTION WHEN NO_DATA_FOUND THEN
				v_nPatientId := 0;
			END;
			v_szDesc := AUDITLOG_PKG.GetTrxDescription(0, 1, v_szStatus, 0);

		END IF;

   END IF;

   v_szInfo := TRIM(v_szDesc) || ' - ' || TRIM(v_szProcedure) || ' ' || TRIM(v_szSite) || ' ' ||  TRIM(v_szSurface);

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_trxcont AFTER INSERT OR DELETE OR UPDATE OF "Procedure", "Site", "ConsentType" ON trxcont FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'TRXCONT';


   IF ( DELETING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
   ELSIF ( INSERTING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
   END IF;

   v_szTableDesc := 'Contract/Consent Treatment';
   v_szInfo := NVL(:NEW."Procedure", :OLD."Procedure");

   -- B142182 - take max(Patient) in case multiple records exist
   IF NVL(:NEW."Contract", :OLD."Contract") > 0 THEN
      SELECT MAX("Patient") INTO v_nPatientId FROM CONTRACT WHERE "Contract" = NVL(:NEW."Contract", :OLD."Contract");
   ELSE
      SELECT MAX("Patient") INTO v_nPatientId FROM PTLETTER WHERE "PtLetter" = NVL(:NEW."PtLetter", :OLD."PtLetter");
   END IF;


   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_trxmed AFTER INSERT OR DELETE OR UPDATE OF "ICDCode1", "ICDCode2", "ICDCode3", "ICDCode4", "ICDIsTx1", "ICDIsTx2", "ICDIsTx3", "ICDIsTx4", "PlaceCode", "Modifier", "DateTo", "Modifier2", "AnesMin", "Referral", "ChartLnk", "ICDType", "IsAccident" ON trxmed FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

   v_szDesc		   VARCHAR2(51 );
   v_szStatus		VARCHAR2(11 );
   v_nPlanTotal	NUMBER;

   v_szProcedure  VARCHAR2(11 );
   v_szSite			VARCHAR2(11 );
   v_szSurface		VARCHAR2(11 );

   v_nStatus		NUMBER;							--B142673

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'TRXMED';
   v_szTableDesc := 'Tx Service Information';

   IF ( DELETING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
      --B142673
	    BEGIN
		  if ( :OLD."Id" <> 0 ) THEN
				SELECT "Patient", "Status", "PlanTotal", "Procedure", "Site", "Surface"
					 INTO v_nPatientId, v_szStatus, v_nPlanTotal, v_szProcedure,v_szSite, v_szSurface
					 FROM TRX WHERE "Type" = :OLD."Type" AND "Id" = :OLD."Id" AND "Treatment" = :OLD."Treatment";
				v_szDesc := AUDITLOG_PKG.GetTrxDescription(:OLD."Type", :OLD."Id", v_szStatus, v_nPlanTotal);
			ELSE
				SELECT C."Patient", T2."Status", C."Procedure", C."Site", C."Surface"
					 INTO v_nPatientId, v_nStatus, v_szProcedure,v_szSite, v_szSurface
					 FROM CHARTLNK C, TREATME2 T2 WHERE C."Id" = :OLD."ChartLnk" AND C."Auto" = T2."Auto";
				v_szDesc := AUDITLOG_PKG.GetTreatme2Description(v_nStatus);
			END IF;
			EXCEPTION WHEN OTHERS THEN
				v_szDesc := 'Treatment record not found!';
		END;
   ELSE
	BEGIN
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
	      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
	   END IF;
      --B142673
      if ( :NEW."Id" <> 0 ) THEN
			SELECT "Patient", "Status", "PlanTotal", "Procedure", "Site", "Surface"
				 INTO v_nPatientId, v_szStatus, v_nPlanTotal, v_szProcedure,v_szSite, v_szSurface
				 FROM TRX WHERE "Type" = :NEW."Type" AND "Id" = :NEW."Id" AND "Treatment" = :NEW."Treatment";
			v_szDesc := AUDITLOG_PKG.GetTrxDescription(:NEW."Type", :NEW."Id", v_szStatus, v_nPlanTotal);
		ELSE
			SELECT C."Patient", T2."Status", C."Procedure", C."Site", C."Surface"
				 INTO v_nPatientId, v_nStatus, v_szProcedure,v_szSite, v_szSurface
				 FROM CHARTLNK C, TREATME2 T2 WHERE C."Id" = :NEW."ChartLnk" AND C."Auto" = T2."Auto";
			v_szDesc := AUDITLOG_PKG.GetTreatme2Description(v_nStatus);
		END IF;
	EXCEPTION WHEN OTHERS THEN
		v_szDesc := 'Treatment record not found!';
	END;
   END IF;

   v_szInfo := TRIM(v_szDesc) || ' - ' || TRIM(v_szProcedure) || ' ' || TRIM(v_szSite) || ' ' ||  TRIM(v_szSurface);

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);
  	
END$trigger$
 ;
CREATE TRIGGER auditlog_trxpol AFTER INSERT OR DELETE OR UPDATE OF "PreAuth", "PreAuthStartDate", "PreAuthEndDate", "SubmitDate", "Submitted", "Received", "ReceiveDate", "Denied", "ServAuthException", "Audit" ON trxpol FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

   v_szDesc		   VARCHAR2(51 );
   v_szStatus		VARCHAR2(11 );
   v_nPlanTotal	NUMBER;

   v_szInsCo		VARCHAR2(11 );
   v_szPolicy		VARCHAR2(21 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'TRXPOL';
   v_szTableDesc := 'Tx Preauthorization';

   IF ( DELETING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
		SELECT "Patient", "Status", "PlanTotal",
				 (CASE WHEN "PolicyId1"=:OLD."PolicyId" THEN "Company1" WHEN "PolicyId2"=:OLD."PolicyId" THEN "Company2" WHEN "PolicyId3"=:OLD."PolicyId" THEN "Company3" ELSE '' END),
				 (CASE WHEN "PolicyId1"=:OLD."PolicyId" THEN "Policy1" WHEN "PolicyId2"=:OLD."PolicyId" THEN "Policy2" WHEN "PolicyId3"=:OLD."PolicyId" THEN "Policy3" ELSE '' END)
				 INTO v_nPatientId, v_szStatus, v_nPlanTotal, v_szInsCo, v_szPolicy
				 FROM TRX WHERE "Type" = :OLD."Type" AND "Id" = :OLD."Id" AND "Treatment" = :OLD."Treatment";
		v_szDesc := AUDITLOG_PKG.GetTrxDescription(:OLD."Type", :OLD."Id", v_szStatus, v_nPlanTotal);
   ELSE
		IF ( INSERTING ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
	      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
	   END IF;
		SELECT "Patient", "Status", "PlanTotal",
				 (CASE WHEN "PolicyId1"=:NEW."PolicyId" THEN "Company1" WHEN "PolicyId2"=:NEW."PolicyId" THEN "Company2" WHEN "PolicyId3"=:NEW."PolicyId" THEN "Company3" ELSE '' END),
				 (CASE WHEN "PolicyId1"=:NEW."PolicyId" THEN "Policy1" WHEN "PolicyId2"=:NEW."PolicyId" THEN "Policy2" WHEN "PolicyId3"=:NEW."PolicyId" THEN "Policy3" ELSE '' END)
				 INTO v_nPatientId, v_szStatus, v_nPlanTotal, v_szInsCo, v_szPolicy
				 FROM TRX WHERE "Type" = :NEW."Type" AND "Id" = :NEW."Id" AND "Treatment" = :NEW."Treatment";
		v_szDesc := AUDITLOG_PKG.GetTrxDescription(:NEW."Type", :NEW."Id", v_szStatus, v_nPlanTotal);
   END IF;

   v_szInfo := TRIM(v_szDesc) || ' - ' || TRIM(v_szInsCo) || ' ' || TRIM(v_szPolicy);

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_txcust AFTER INSERT OR DELETE OR UPDATE OF "Treatme2", "TxQuest", "Item", "Heading", "Question", "ResponseType", "RespCode", "Response", "Deleted" ON txcust FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

   v_nStatus		NUMBER;
   v_nPreId			NUMBER;

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'TXCUST';
   v_szTableDesc := 'Custom Question/Answer for Ortho Tx';

   IF ( DELETING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
		SELECT P."PtxPId", T."Status" INTO v_nPatientId, v_nStatus FROM PATIENT2 P, TREATME2 T WHERE T."Auto" = :OLD."Treatme2" AND T."PId" = P."Auto";
		if ( NOT (TRIM(:OLD."Response") IS NULL OR LENGTH(TRIM(:OLD."Response")) = 0) ) THEN
			v_szInfo := AUDITLOG_PKG.GetTreatme2Description(v_nStatus) || ': ' || TRIM(:OLD."Question") || ' - ' || TRIM(:OLD."Response");
		ELSE
			-- blank answer... no need to audit
			RETURN :new;
		END IF;
   ELSE
		SELECT P."PtxPId", T."Status", T."PreId" INTO v_nPatientId, v_nStatus, v_nPreId
							FROM PATIENT2 P, TREATME2 T WHERE T."Auto" = :NEW."Treatme2" AND T."PId" = P."Auto";
		IF ( INSERTING AND v_nPreId = 0 ) THEN
			v_nActionType := AUDITLOG_PKG.c_nActionAdd;
		ELSE
			v_nActionType := AUDITLOG_PKG.c_nActionEdit;
		END IF;
		if ( NOT (TRIM(:NEW."Response") IS NULL OR LENGTH(TRIM(:NEW."Response")) = 0) ) THEN
		   v_szInfo := AUDITLOG_PKG.GetTreatme2Description(v_nStatus) || ': ' || TRIM(:NEW."Question") || ' - ' || TRIM(:NEW."Response");
		ELSE
			-- blank answer... no need to audit
			RETURN :new;
		END IF;
		
   END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_txpdx AFTER INSERT OR DELETE OR UPDATE OF "TxPlan", "DiagCode", "Description", "ShortDesc", "Order", "Deleted", "Audit" ON txpdx FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );
   v_szTxPlan		VARCHAR2(30 );


BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'TXPDX';
   v_szTableDesc := 'Treatment Plan Diagnosis';

   IF ( DELETING OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
      SELECT "Patient" INTO v_nPatientId FROM TXPLAN WHERE "TxPlan" = :OLD."TxPlan";
  		SELECT "Description" INTO v_szTxPlan FROM TXPLAN WHERE "TxPlan" = :OLD."TxPlan";
  		v_szInfo := 'Plan: ' || v_szTxPlan || '   Diagnosis: ' || :OLD."Description";

   ELSIF ( INSERTING OR (:OLD."Deleted" = 1 AND :NEW."Deleted" = 0) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
      SELECT "Patient" INTO v_nPatientId FROM TXPLAN WHERE "TxPlan" = :NEW."TxPlan";
  		SELECT "Description" INTO v_szTxPlan FROM TXPLAN WHERE "TxPlan" = :NEW."TxPlan";
  		v_szInfo := 'Plan: ' || v_szTxPlan || '   Diagnosis: ' || :NEW."Description";

   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
      SELECT "Patient" INTO v_nPatientId FROM TXPLAN WHERE "TxPlan" = :NEW."TxPlan";
  		SELECT "Description" INTO v_szTxPlan FROM TXPLAN WHERE "TxPlan" = :NEW."TxPlan";
  		v_szInfo := 'Plan: ' || v_szTxPlan || '   Diagnosis: ' || :NEW."Description";

   END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_txplan AFTER INSERT OR DELETE OR UPDATE OF "Description", "ChiefConcern", "Inactive", "InactiveAppUser", "Deleted" ON txplan FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'TXPLAN';
   v_szTableDesc := 'Treatment Plan';

   IF ( DELETING OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
      v_nPatientId := :OLD."Patient";
      v_szInfo := :OLD."Description";

   ELSIF ( INSERTING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
      v_nPatientId := :NEW."Patient";
      v_szInfo := :NEW."Description";

   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
      v_nPatientId := :NEW."Patient";
      v_szInfo := :NEW."Description";

   END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_txpnote AFTER INSERT OR DELETE OR UPDATE OF "Date", "Code", "Deleted" ON txpnote FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'TXPNOTE';


   IF ( DELETING OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1)) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
   ELSIF ( INSERTING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
   END IF;

   v_szTableDesc := 'Treatment Plan Note';
   v_nPatientId := NVL(:NEW."Patient", :OLD."Patient");

   IF ( LENGTH(TRIM(NVL(:NEW."Text", :OLD."Text"))) < 50 ) THEN
      v_szInfo := TRIM(NVL(:NEW."Text", :OLD."Text"));
   ELSE
   	v_szInfo := RPAD(NVL(:NEW."Text", :OLD."Text"), 50) || '...';
   END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_txpopt AFTER INSERT OR DELETE OR UPDATE OF "Description", "NeedsConsultantAppr", "InstructorApproved", "AppUser", "AppDateTime", "Deleted" ON txpopt FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );
   v_szTxPlan		VARCHAR2(30 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'TXPOPT';
   v_szTableDesc := 'Treatment Plan Option';

   IF ( DELETING OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
      SELECT "Patient" INTO v_nPatientId FROM TXPLAN WHERE "TxPlan" = :OLD."TxPlan";
      SELECT "Description" INTO v_szTxPlan FROM TXPLAN WHERE "TxPlan" = :OLD."TxPlan";
      v_szInfo := 'Plan: ' || v_szTxPlan || '   Option: ' || :OLD."Description";

   ELSIF ( INSERTING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
      SELECT "Patient" INTO v_nPatientId FROM TXPLAN WHERE "TxPlan" = :NEW."TxPlan";
      SELECT "Description" INTO v_szTxPlan FROM TXPLAN WHERE "TxPlan" = :NEW."TxPlan";
      v_szInfo := 'Plan: ' || v_szTxPlan || '   Option: ' || :NEW."Description";

   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
      SELECT "Patient" INTO v_nPatientId FROM TXPLAN WHERE "TxPlan" = :NEW."TxPlan";
      SELECT "Description" INTO v_szTxPlan FROM TXPLAN WHERE "TxPlan" = :NEW."TxPlan";
      v_szInfo := 'Plan: ' || v_szTxPlan || '   Option: ' || :NEW."Description";

   END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_txpprb AFTER INSERT OR DELETE OR UPDATE OF "TxPlan", "PtPrb", "Deleted", "Audit" ON txpprb FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );
   v_szProblem		VARCHAR2(50 );
   v_szTxPlan		VARCHAR2(30 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'TXPPRB';
   v_szTableDesc := 'Treatment Plan Problem';

   IF ( DELETING OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
  		SELECT "Patient" INTO v_nPatientId FROM PTPRB WHERE "PtPrb" = :OLD."PtPrb";
  		SELECT "Description" INTO v_szTxPlan FROM TXPLAN WHERE "TxPlan" = :OLD."TxPlan";
  		SELECT "Description" INTO v_szProblem FROM PTPRB WHERE "PtPrb" = :OLD."PtPrb";
  		v_szInfo := 'Plan: ' || v_szTxPlan || '   Problem: ' || v_szProblem;

   ELSIF ( INSERTING OR (:OLD."Deleted" = 1 AND :NEW."Deleted" = 0) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
      SELECT "Patient" INTO v_nPatientId FROM PTPRB WHERE "PtPrb" = :NEW."PtPrb";
  		SELECT "Description" INTO v_szTxPlan FROM TXPLAN WHERE "TxPlan" = :NEW."TxPlan";
  		SELECT "Description" INTO v_szProblem FROM PTPRB WHERE "PtPrb" = :NEW."PtPrb";
  		v_szInfo := 'Plan: ' || v_szTxPlan || '   Problem: ' || v_szProblem;

   ELSE	
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
  		SELECT "Patient" INTO v_nPatientId FROM PTPRB WHERE "PtPrb" = :NEW."PtPrb";
  		SELECT "Description" INTO v_szTxPlan FROM TXPLAN WHERE "TxPlan" = :NEW."TxPlan";
  		SELECT "Description" INTO v_szProblem FROM PTPRB WHERE "PtPrb" = :NEW."PtPrb";
  		v_szInfo := 'Plan: ' || v_szTxPlan || '   Problem: ' || v_szProblem;

   END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_txptx AFTER INSERT OR DELETE OR UPDATE OF "TxPTxType", "TxPTxDateTime", "Order", "Provider", "Code", "Description", "Site", "Site2", "Surface", "Phase", "Sequence", "Status", "Total", "InsTotal", "HeldTotal", "ClaimDoctor", "Discipline", "Unit", "Custom1", "Custom2", "PtAccepted", "PtAcceptDateTime", "Treatme2Id", "Deleted", "Audit" ON txptx FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );
   v_szTxPlan		VARCHAR2(30 );
   v_szOption		VARCHAR2(60 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'TXPTX';
   v_szTableDesc := 'Treatment Plan Tx';

   IF ( DELETING OR (:OLD."Deleted" = 0 AND :NEW."Deleted" = 1) ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
      SELECT "Patient" INTO v_nPatientId FROM TXPLAN WHERE "TxPlan" = :OLD."TxPlan";
      SELECT "Description" INTO v_szTxPlan FROM TXPLAN WHERE "TxPlan" = :OLD."TxPlan";
      SELECT "Description" INTO v_szOption FROM TXPOPT WHERE "TxPOpt" = :OLD."TxPOpt";
      v_szInfo := 'Plan: ' || v_szTxPlan || '   Option: ' || v_szOption  || '   Tx: ' || :OLD."Code" || ' ' || :OLD."Site" || ' ' || :OLD."Surface";

   ELSIF ( INSERTING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
      SELECT "Patient" INTO v_nPatientId FROM TXPLAN WHERE "TxPlan" = :NEW."TxPlan";
      SELECT "Description" INTO v_szTxPlan FROM TXPLAN WHERE "TxPlan" = :NEW."TxPlan";
      SELECT "Description" INTO v_szOption FROM TXPOPT WHERE "TxPOpt" = :NEW."TxPOpt";
      v_szInfo := 'Plan: ' || v_szTxPlan || '   Option: ' || v_szOption  || '   Tx: ' || :NEW."Code" || ' ' || :NEW."Site" || ' ' || :NEW."Surface";

   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
      SELECT "Patient" INTO v_nPatientId FROM TXPLAN WHERE "TxPlan" = :NEW."TxPlan";
      SELECT "Description" INTO v_szTxPlan FROM TXPLAN WHERE "TxPlan" = :NEW."TxPlan";
      SELECT "Description" INTO v_szOption FROM TXPOPT WHERE "TxPOpt" = :NEW."TxPOpt";
      v_szInfo := 'Plan: ' || v_szTxPlan || '   Option: ' || v_szOption  || '   Tx: ' || :NEW."Code" || ' ' || :NEW."Site" || ' ' || :NEW."Surface";

   END IF;

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER auditlog_vkclaim AFTER INSERT OR DELETE OR UPDATE OF "VKClaim", "VKBatch", "Type", "Id", "InsNumber", "Patient", "Date", "PatErrCd1", "PatErrCd2", "PatErrCd3" ON vkclaim FOR EACH ROW  $trigger$DECLARE
   v_nPatientId   NUMBER;
   v_nActionType  NUMBER;
   v_szTableName  VARCHAR2(255 );
   v_szTableDesc  VARCHAR2(255 );
   v_szInfo       VARCHAR2(255 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   IF ( AUDITLOG_PKG.GetSecureLog() = 0 ) THEN
      RETURN :new;
   END IF;

   v_szTableName := 'VKCLAIM';

   IF ( DELETING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionDelete;
   ELSIF ( INSERTING ) THEN
      v_nActionType := AUDITLOG_PKG.c_nActionAdd;
   ELSE
      v_nActionType := AUDITLOG_PKG.c_nActionEdit;
   END IF;

   v_szTableDesc := 'Vektis II Claim';
   v_nPatientId := :NEW."Patient";
   v_szInfo := ' ';

   AUDITLOG_PKG.InsertAuditLog(v_nPatientId, v_nActionType, v_szTableName, v_szTableDesc, v_szInfo);

END$trigger$
 ;
CREATE TRIGGER automsg_cq_ptlinfo AFTER INSERT ON ptlinfo FOR EACH ROW WHEN (new."PtLType" = 4::numeric)  $trigger$DECLARE

	-- message variables
	v_MessageId MESSAGE."Message"%TYPE;
	v_Sender	NUMBER;
	v_Priority	MESSAGE."IsPriority"%TYPE;
	v_Subject	MESSAGE."Subject"%TYPE;
	v_Text		MESSAGE.TEXT%TYPE;

	-- other variables
	v_AuditUser NUMBER;
	v_PtName	VARCHAR2(128 );
	v_HasAppts  NUMBER;

	CURSOR curFutureAppts (PPATIENT PATIENT."Patient"%TYPE) IS
		SELECT
			a.*
		FROM
			appoint   a,
			patient   p
		WHERE
			p."Patient" = pPatient
			AND p."Patient" = a."Patient"
			AND a."Type" IN (
				0,
				1
			)
			AND a."Date" BETWEEN TRUNC(SYSDATE) AND TRUNC(SYSDATE) + 7;
		
	-- AX-25911
	CURSOR curPrimaryProviders (pPatient PATIENT."Patient"%TYPE) IS
		SELECT
			p."Producer"
		FROM
			ptprod   p
		WHERE
			p."Patient"        = pPatient
			AND p."StartDate" <= TRUNC(SYSDATE)
			AND p."EndDate"   >= TRUNC(SYSDATE)
			AND p."IsPrimary"  > 0
			AND p."Deleted"    = 0
		;


BEGIN

   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

	-- check if automated message should fire
	IF MESSAGE_PKG.MSG_TRIGGER_CAN_FIRE('AUTOMSG_CQ_PTLINFO', v_Priority) = 0 THEN
		RETURN :new;
	END IF;
	
	-- get the AUDIT record
	SELECT "User"
	  INTO v_AuditUser
	  FROM AUDITHIS
	 WHERE "Audit" = :NEW."Audit";
 	
	-- Sender
	v_Sender := v_AuditUser;

	-- Subject
	v_Subject := 'A C-CDA document has been received from ';
	v_Subject := v_Subject || :NEW."ContentSource";

	-- Text
	-- basic message
	v_PtName := MESSAGE_PKG.GET_PATIENT_NAME(2, :NEW."Patient");
	v_Text := 'A C-CDA document has been received from ' || :NEW."ContentSource" || '.' || chr(13) || chr(10) || 'It has been attached to ' || v_PtName || '.' || chr(13) || chr(10);


	-- Add the message
	MESSAGE_PKG.ADD_AUTOMESSAGE('AUTOMSG_CQ_PTLINFO', v_Sender, SYSDATE, v_Priority, v_Subject, v_Text, v_MessageId);

	-- get the Primary Provider record...
	v_HasAppts := 0;
	-- any appts in the nxt week?
	FOR cAppt in curFutureAppts(:NEW."Patient") LOOP
		v_HasAppts := 1;
		-- Add the recipient
		MESSAGE_PKG.ADD_RECIPIENT_PROVIDER(v_MessageId, cAppt."Producer");
	END LOOP;	

	IF v_HasAppts = 0 THEN
	
		-- AX-25911
		FOR pPrimaryProvider IN curPrimaryProviders(:NEW."Patient") LOOP

			-- Add the recipient
			MESSAGE_PKG.ADD_RECIPIENT_PROVIDER(v_MessageId, pPrimaryProvider."Producer");
		
		END LOOP;
		
	END IF;

EXCEPTION WHEN OTHERS THEN
	RETURN :new;
END$trigger$
 ;
CREATE TRIGGER automsg_dispunlock AFTER UPDATE OF "DispLocked" ON producer FOR EACH ROW WHEN (old."DispLocked" = 1::numeric AND new."DispLocked" = 0::numeric)  $trigger$DECLARE

	-- message variables
	v_MessageId MESSAGE."Message"%TYPE;
	v_Sender	USERS."User"%TYPE;
	v_Priority	MESSAGE."IsPriority"%TYPE;
	v_Subject	MESSAGE."Subject"%TYPE;
	v_Text		MESSAGE.TEXT%TYPE;


	-- other variables
	v_Date 		VARCHAR2(64 );
	v_ProdName	VARCHAR2(128 );
	
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


	-- check if automated message should fire
	IF MESSAGE_PKG.MSG_TRIGGER_CAN_FIRE('AUTOMSG_DISPUNLOCK', v_Priority) = 0 THEN
		RETURN :new;
	END IF;



	-- Sender
	BEGIN
		SELECT MIN("User")
		  INTO v_Sender
		  FROM AUDITHIS
		 WHERE "Audit" = :NEW."Audit";
	  EXCEPTION WHEN NO_DATA_FOUND THEN
		RETURN :new;	
	END;
	

	-- Subject
	v_Subject := 'Dispensary Unlocked';

	-- Text
	v_ProdName := MESSAGE_PKG.FORMAT_NAME(2, :NEW."FirstName", :NEW."MiddleName", :NEW."LastName");

	v_Date := MESSAGE_PKG.FORMAT_DATE(1, SYSDATE);


	v_Text := 'Access to the Dispensary has been unlocked for ' || v_ProdName || ' as of ' || v_Date;


	-- Add the message
	MESSAGE_PKG.ADD_AUTOMESSAGE('AUTOMSG_DISPUNLOCK', v_Sender, SYSDATE, v_Priority, v_Subject, v_Text, v_MessageId);


	-- Add the recipient
	MESSAGE_PKG.ADD_RECIPIENT_PROVIDER(v_MessageId, :NEW."Producer");


EXCEPTION WHEN OTHERS THEN
	RETURN :new;		
END$trigger$
 ;
CREATE TRIGGER automsg_emergency AFTER INSERT ON custevnt FOR EACH ROW WHEN (new."EventType" = 4::numeric)  $trigger$DECLARE


	-- message variables
	v_MessageId MESSAGE."Message"%TYPE;
	v_Sender		USERS."User"%TYPE;
	v_Priority	MESSAGE."IsPriority"%TYPE;
	v_Subject	MESSAGE."Subject"%TYPE;
	v_Text		MESSAGE.TEXT%TYPE;

	-- cursors
	CURSOR CUR_ADMINS IS
		SELECT DISTINCT U."User"
		  FROM USERS U, SLEVEL L, SLEVROLE LR, SROLE S
		 WHERE U."Deleted" = 0
			AND U."Level" = L."SLevel"
			AND L."Deleted" = 0
			AND L."SLevel" = LR."SLevel"
			AND LR."SRole" = S."SRole"
			AND S."Deleted" = 0
			AND S."IsAdmin" = 1
            AND (U."ExpDate" is  null
                  OR U."ExpDate" >= TRUNC(SYSDATE));
	
	
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


	-- check if automated message should fire
	IF MESSAGE_PKG.MSG_TRIGGER_CAN_FIRE('AUTOMSG_EMERGENCY', v_Priority) = 0 THEN
		RETURN :new;
	END IF;


	-- Sender
	-- get users record for the person using emergency mode
	begin
		select "User"
		  into v_Sender
		  from USERS
		 where "User" = :NEW."Key1"
		   and rownum < 2;
	exception when NO_DATA_FOUND then
		return :new;
	end;


	-- Subject
	v_Subject := 'Emergency Mode being used';

	-- Text
	v_Text := 'The following user has turned on emergency mode and now has access to all patients in the system:';
	v_Text := v_Text || chr(13) || chr(10);
	v_Text := v_Text || MESSAGE_PKG.GET_USER_NAME(2, v_Sender) || ' (Id: ' || TO_CHAR(v_Sender) || ').';
	


	-- Add the message
	MESSAGE_PKG.ADD_AUTOMESSAGE('AUTOMSG_EMERGENCY', v_Sender, SYSDATE, v_Priority, v_Subject, v_Text, v_MessageId);


	-- Add the recipients (all administrators)
	FOR rec IN CUR_ADMINS LOOP
		MESSAGE_PKG.ADD_RECIPIENT_USER(v_MessageId, rec."User");
	END LOOP;


EXCEPTION WHEN OTHERS THEN
	RETURN :new;		
END$trigger$
 ;
CREATE TRIGGER automsg_formassigned BEFORE INSERT ON pformevt FOR EACH ROW WHEN (nvl(new."AssignedUGroup", ' ') <> ' '::bpchar OR new."AssignedUser" > 0::numeric)  $trigger$DECLARE


	-- message variables
	v_MessageId MESSAGE."Message"%TYPE;
	v_Sender		USERS."User"%TYPE;
	v_Priority	MESSAGE."IsPriority"%TYPE;
	v_Subject	MESSAGE."Subject"%TYPE;
	v_Text		MESSAGE.TEXT%TYPE;


	-- other variables
	v_PFORM			PFORM%ROWTYPE;
	v_PrevPFORMEVT	PFORMEVT%ROWTYPE;
	v_PFormUser		AUDITHIS."User"%TYPE;
	v_Chart			PATIENT."Chart"%TYPE;

	
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


	-- check if automated message should fire
	IF MESSAGE_PKG.MSG_TRIGGER_CAN_FIRE('AUTOMSG_FORMASSIGNED', v_Priority) = 0 THEN
		RETURN :new;
	END IF;


	-- get form
	begin
		select *
		  into v_PFORM
		  from PFORM
		 where "PForm" = :NEW."PForm"
			and rownum < 2;
	exception when NO_DATA_FOUND then
		return :new;
	end;
	
	-- get previous form event (B81150 - if there is one)
	-- B81252 ROWNUM < 2 clause ignores order by clause - changed to do a subselect to get the max result
	begin
		select P.*
		  into v_PrevPFORMEVT
		  from PFORMEVT P
		 where P."PFormEvt" in (select max(p2."PFormEvt") from pformevt p2
				 where p2."PForm" = :NEW."PForm" and p2."PFormEvt" <> :NEW."PFormEvt");
	exception when NO_DATA_FOUND then
		v_PrevPFORMEVT."AssignedUser" := 0;
		v_PrevPFORMEVT."AssignedUGroup" := '';
	end;
	
	-- B81150 - get the user that did this assignment
	begin
		select "User"
		  into v_PFormUser
		  from AUDITHIS
		 where "Audit" = :NEW."Audit"
			and rownum < 2;
	exception when NO_DATA_FOUND then
		return :new;
	end;

	-- only do a message if the assignment has changed
	IF (v_PrevPFORMEVT."AssignedUser" = :NEW."AssignedUser"
		AND NVL(v_PrevPFORMEVT."AssignedUGroup", ' ') = NVL(:NEW."AssignedUGroup", ' '))
	THEN
		return :new;
	END IF;
	
	-- only do a message if the user did not assign the form to himself
	IF :NEW."AssignedUser" = v_PFormUser THEN
		return :new;
	END IF;
	

	-- determine if it's been assigned to a group or a user
	IF :NEW."AssignedUser" > 0 THEN

		-- Sender
		-- AX-4271.4875 - determine the sender from the PFORMEVT audit
		v_Sender := v_PFormUser;

		-- Subject
		v_Subject := 'Classic Form Assignment';

		-- Text
		v_Text := 'The following classic form has been assigned to you:'
			|| chr(13) || chr(10)
			|| 'Form #' || :NEW."PForm" || ' - ' || v_PFORM."FormCode"
			|| chr(13) || chr(10)
			|| v_PFORM."Description"
			|| chr(13) || chr(10)
			|| 'Status: ' || :NEW."FStatus"
			|| chr(13) || chr(10);

		-- B81150 - tag on patient chart if this is a patient form
		IF v_PFORM."Patient" > 0 THEN
		
			begin
				select TRIM("Chart") into v_Chart from patient where "Patient" = v_PFORM."Patient";
			exception when no_data_found then
				v_Chart := '';
			end;
			
			v_Text := v_Text
				|| 'Chart: ' || v_Chart
				|| chr(13) || chr(10);
		END IF;
		
		v_Text := v_Text
			|| :NEW."Comment";

	ELSE

		-- Sender
		-- AX-4271.4875 - determine the sender from the PFORMEVT audit
		v_Sender := v_PFormUser;

		-- Subject
		v_Subject := 'Classic Form Group Assignment';

		-- Text
		v_Text := 'The following classic form has been assigned to Group ' || :NEW."AssignedUGroup" || ':'
			|| chr(13) || chr(10)
			|| 'Form #' || :NEW."PForm" || ' - ' || v_PFORM."FormCode"
			|| chr(13) || chr(10)
			|| v_PFORM."Description"
			|| chr(13) || chr(10)
			|| 'Status: ' || :NEW."FStatus"
			|| chr(13) || chr(10);

		-- B81150 - tag on patient chart if this is a patient form
		IF v_PFORM."Patient" > 0 THEN
		
			begin
				select TRIM("Chart") into v_Chart from patient where "Patient" = v_PFORM."Patient";
			exception when no_data_found then
				v_Chart := '';
			end;
			
			v_Text := v_Text
				|| 'Chart: ' || v_Chart
				|| chr(13) || chr(10);
		END IF;
		
		v_Text := v_Text
			|| :NEW."Comment"
			|| chr(13) || chr(10)
			|| chr(13) || chr(10)
			|| 'Please re-assign the classic form to yourself before working on it.';

	END IF;


	-- Add the message
	MESSAGE_PKG.ADD_AUTOMESSAGE('AUTOMSG_FORMASSIGNED', v_Sender, SYSDATE, v_Priority, v_Subject, v_Text, v_MessageId);


	-- Add the recipient
	IF :NEW."AssignedUser" > 0 THEN
		MESSAGE_PKG.ADD_RECIPIENT_USER(v_MessageId, :NEW."AssignedUser");
	ELSE
		MESSAGE_PKG.ADD_RECIPIENT_UGROUP(v_MessageId, :NEW."AssignedUGroup");
	END IF;
		

EXCEPTION WHEN OTHERS THEN
	RETURN :new;		
END$trigger$
 ;
CREATE TRIGGER automsg_labout AFTER INSERT ON custevnt FOR EACH ROW WHEN (new."EventType" = 3::numeric)  $trigger$DECLARE

	-- Lab Site cursor
	CURSOR CUR_LABSITE(LabOrder NUMBER) IS
		SELECT T."Site"
		  FROM TRX T, LABOTRX LT
		 WHERE LT."LabOrder" = LabOrder
		   AND LT."OrigRecNo" = T."OrigRecNo"
		   AND T."Deleted" = 0
		 ORDER BY T."Site";
		

	-- message variables
	v_MessageId MESSAGE."Message"%TYPE;
	v_Sender	USERS."User"%TYPE;
	v_Priority	MESSAGE."IsPriority"%TYPE;
	v_Subject	MESSAGE."Subject"%TYPE;
	v_Text		MESSAGE.TEXT%TYPE;

	-- other variables
	v_LabItem   LABITEM%ROWTYPE;
	v_LabOrder	LABORDER%ROWTYPE;
	v_PtName	VARCHAR2(128 );
	v_OrderSite VARCHAR2(256 );

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


	-- check if automated message should fire
	IF MESSAGE_PKG.MSG_TRIGGER_CAN_FIRE('AUTOMSG_LABOUT', v_Priority) = 0 THEN
		RETURN :new;
	END IF;


	
	-- get the LABITEM record
	SELECT *
	  INTO v_LabItem
	  FROM LABITEM
	 WHERE "LabOrder" = :NEW."Key1"
	   AND "Item" = :NEW."Key2";
	
	-- get the LABORDER record
	SELECT *
	  INTO v_LabOrder
	  FROM LABORDER
	 WHERE "LabOrder" = :NEW."Key1";	
	


	-- Sender
	-- B70158 Changed from "User" to "OutUser"
	v_Sender := v_LabItem."OutUser";


	-- Subject
	v_Subject := 'Lab Order #' || TO_CHAR(v_LabItem."LabOrder") || ' is out';


	-- Text
	-- Site String
	v_OrderSite := TO_CHAR(v_LabItem."LabOrder");

	FOR rec IN CUR_LABSITE(v_LabItem."LabOrder") LOOP
	  BEGIN
	  	IF v_OrderSite = TO_CHAR(v_LabItem."LabOrder") THEN
	  		v_OrderSite := v_OrderSite || ' on site(s) ';
	  	ELSE
	  		v_OrderSite := v_OrderSite || ', ';
	  	END IF;
	  	
		v_OrderSite := v_OrderSite || TRIM(rec."Site");
	  END;
	END LOOP;


	-- Patient Name
	v_PtName := MESSAGE_PKG.GET_PATIENT_NAME(2, v_LabOrder."Patient");


	-- basic message text
	v_Text := 'Lab Order #' || v_OrderSite || ', Item #' || TO_CHAR(v_LabItem."Item") || ' for ' || v_PtName || ' is now OUT: ' || chr(13) || chr(10);


	-- add the lab item text
	IF LENGTH(v_LabItem."Text") > 0 THEN
		v_Text := v_Text || chr(13) || chr(10) || v_LabItem."Text";
	END IF;



	-- Add the message
	MESSAGE_PKG.ADD_AUTOMESSAGE('AUTOMSG_LABOUT', v_Sender, SYSDATE, v_Priority, v_Subject, v_Text, v_MessageId);


	-- Add the recipient
	MESSAGE_PKG.ADD_RECIPIENT_PROVIDER(v_MessageId, v_LabItem."Provider");

	

EXCEPTION WHEN OTHERS THEN
	RETURN :new;
END$trigger$
 ;
CREATE TRIGGER automsg_ptcheckin AFTER UPDATE OF "Type" ON appoint FOR EACH ROW WHEN (new."Type" = 1::numeric AND old."Type" <> 1::numeric)  $trigger$DECLARE

	-- message variables
	v_MessageId MESSAGE."Message"%TYPE;
	v_Sender	USERS."User"%TYPE;
	v_Priority	MESSAGE."IsPriority"%TYPE;
	v_Subject	MESSAGE."Subject"%TYPE;
	v_Text		MESSAGE.TEXT%TYPE;


	-- other variables
	v_PtName	VARCHAR2(128 );
	v_Time		VARCHAR2(128 );
	v_Clinic	CLINIC."Description"%TYPE;
	v_Chair		CHAIR."Description"%TYPE;
	
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


	-- check if automated message should fire
	IF MESSAGE_PKG.MSG_TRIGGER_CAN_FIRE('AUTOMSG_PTCHECKIN', v_Priority) = 0 THEN
		RETURN :new;
	END IF;


	-- Sender
		-- B77438 - SignInUser not always set
		if :NEW."User" > 0 then
			v_Sender := :NEW."User";
		else
			-- use the Provider's user id as the sender
			SELECT MIN("User")
			  INTO v_Sender
			  FROM USERS
			 WHERE "Producer" = :NEW."Producer"
				AND "Deleted" = 0;
		end if;

	-- Subject
	v_Subject := 'Patient Checked In';

	-- Text
	v_PtName := MESSAGE_PKG.GET_PATIENT_NAME(2, :NEW."Patient");

	v_Time := MESSAGE_PKG.FORMAT_TIME(3, :NEW."From");
	
	BEGIN
		SELECT CH."Description", CL."Description"
		  INTO v_Chair, v_Clinic
		  FROM CHAIR CH, CLINIC CL
		 WHERE CH."Chair" = :NEW."Chair"
		   AND CH."Clinic" = CL."Clinic"
		   AND ROWNUM = 1;
	EXCEPTION WHEN NO_DATA_FOUND THEN
		v_Chair := '';
		v_Clinic := '';
	END;
	

	v_Text := 'Patient ' || v_PtName || ' has checked in for his/her appointment at ' || v_Time || '.' || chr(13) || chr(10)
		|| chr(13) || chr(10)
		|| 'Clinic: ' || v_Clinic || chr(13) || chr(10)
		|| 'Chair: ' || v_Chair;



	-- Add the message
	MESSAGE_PKG.ADD_AUTOMESSAGE('AUTOMSG_PTCHECKIN', v_Sender, SYSDATE, v_Priority, v_Subject, v_Text, v_MessageId);


	-- Add the recipient
	MESSAGE_PKG.ADD_RECIPIENT_PROVIDER(v_MessageId, :NEW."Producer");


EXCEPTION WHEN OTHERS THEN
	RETURN :new;		
END$trigger$
 ;
CREATE TRIGGER automsg_ptlinfo AFTER INSERT ON ptlinfo FOR EACH ROW WHEN (new."PtLType" = 3::numeric)  $trigger$DECLARE

	-- message variables
	v_MessageId MESSAGE."Message"%TYPE;
	v_Sender	NUMBER;
	v_Priority	MESSAGE."IsPriority"%TYPE;
	v_Subject	MESSAGE."Subject"%TYPE;
	v_Text		MESSAGE.TEXT%TYPE;

	-- other variables
	v_AuditUser NUMBER;
	v_PtProd 	USERS."Producer"%TYPE;
	v_UGroup        UGROUP."UGroup"%TYPE;
	v_PtName	VARCHAR2(128 );
	v_HasAppts  NUMBER;
	v_AddProducer  NUMBER := 0;
	v_AddUser   NUMBER;

	CURSOR curFutureAppts (PPATIENT PATIENT."Patient"%TYPE) IS
		SELECT
			a.*
		FROM
			appoint   a,
			patient   p
		WHERE
			p."Patient" = pPatient
			AND p."Patient" = a."Patient"
			AND a."Type" IN (
				0,
				1
			)
			AND a."Date" BETWEEN TRUNC(SYSDATE) AND TRUNC(SYSDATE) + 7;
		
	-- AX-25911
	CURSOR curPrimaryProviders (pPatient PATIENT."Patient"%TYPE) IS
		SELECT
			p."Producer"
		FROM
			ptprod   p
		WHERE
			p."Patient"        = pPatient
			AND p."StartDate" <= TRUNC(SYSDATE)
			AND p."EndDate"   >= TRUNC(SYSDATE)
			AND p."IsPrimary"  > 0
			AND p."Deleted"    = 0
		;


BEGIN

   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

	-- check if automated message should fire
	IF MESSAGE_PKG.MSG_TRIGGER_CAN_FIRE('AUTOMSG_PTLINFO', v_Priority) = 0 THEN
		RETURN :new;
	END IF;
	
	-- get the AUDIT record
	SELECT "User"
	  INTO v_AuditUser
	  FROM AUDITHIS
	 WHERE "Audit" = :NEW."Audit";
 	
	-- Sender
	v_Sender := v_AuditUser;

	-- Subject
	v_Subject := 'A C-CDA document has been received from ';
	v_Subject := v_Subject || :NEW."ContentSource";

	-- Text
	-- basic message
	v_PtName := MESSAGE_PKG.GET_PATIENT_NAME(2, :NEW."Patient");
	v_Text := 'A C-CDA document has been received from ' || :NEW."ContentSource" || '.' || chr(13) || chr(10) || 'It has been attached to ' || v_PtName || '.' || chr(13) || chr(10);


	-- Add the message
	MESSAGE_PKG.ADD_AUTOMESSAGE('AUTOMSG_PTLINFO', v_Sender, SYSDATE, v_Priority, v_Subject, v_Text, v_MessageId);

	-- get the Primary Provider record...
	v_PtProd := '';
	v_HasAppts := 0;
	-- any appts in the nxt week?
	FOR cAppt in curFutureAppts(:NEW."Patient") LOOP
		v_HasAppts := 1;
		-- Add the recipient
		MESSAGE_PKG.ADD_RECIPIENT_PROVIDER(v_MessageId, cAppt."Producer");
	END LOOP;	

	IF v_HasAppts = 0 THEN
	
		-- AX-25911
		FOR pPrimaryProvider IN curPrimaryProviders(:NEW."Patient") LOOP

			v_AddProducer := 1;

			-- Add the recipient
			MESSAGE_PKG.ADD_RECIPIENT_PROVIDER(v_MessageId, pPrimaryProvider."Producer");
		
		END LOOP;
		
		IF v_AddProducer = 0 THEN
			BEGIN
				v_AddUser := 0;
				-- look in sysopts and grab that user...
				BEGIN
					SELECT CAST(s."Value" AS NUMBER)
					INTO v_AddUser
					FROM sysopts s
					WHERE s."Name" = 'CC_NotificationUser';
				EXCEPTION WHEN NO_DATA_FOUND THEN
					v_AddUser := 0;
				END;

				IF v_AddUser > 0 THEN
					-- Add the recipient
					MESSAGE_PKG.ADD_RECIPIENT_USER(v_MessageId, v_AddUser);
				ELSE
					BEGIN
						v_AddProducer := 1;
						-- look in sysopts and grab that msg group...
						BEGIN
							SELECT
								s."Value"
							INTO v_UGroup
							FROM
								sysopts s
							WHERE
								s."Name" = 'CC_NotificationMsgGroup';
						EXCEPTION WHEN NO_DATA_FOUND THEN
							v_AddProducer := 0;
						END;

						IF v_AddProducer = 1 THEN
							-- Add the recipient
							MESSAGE_PKG.ADD_RECIPIENT_UGROUP(v_MessageId, v_UGroup);
						END IF;
					END;
				END IF;
			END;
		END IF;
	END IF;

EXCEPTION WHEN OTHERS THEN
	RETURN :new;
END$trigger$
 ;
CREATE TRIGGER automsg_ptoverdue AFTER INSERT ON ptovrdue FOR EACH ROW WHEN (new."DaysOverdue" > new."Limit")  $trigger$DECLARE



	-- Group Leader cursor; E57272.2; E69003

	CURSOR CUR_GROUPLEADERS(PGroup CHAR) IS

	  	SELECT U."User"

	  	  FROM USERS U

	  	 WHERE U."IsGroupManager" = 1 

	  	   AND PGroup IN (SELECT UP."PGroup"

			  FROM UPGROUP UP WHERE UP."User" = U."User")

	  	   AND U."Deleted" = 0;		 



	-- Patient Care Manager cursor; E69003

	CURSOR CUR_PTMANAGERS(Patient NUMBER) IS

	  	SELECT U."User"

	  	  FROM USERS U, PTMANAGE PTM

	  	 WHERE U."IsManager" = 1 

	  	   AND U."Deleted" = 0

	  	   AND PTM."User" = U."User" 

	  	   AND PTM."Deleted" = 0

	  	   AND PTM."Patient" = Patient;		 



	-- Other recipients cursor

	CURSOR CUR_OTHERRECIPS(OdueMsg CHAR) IS

	  	SELECT U."User"

	  	  FROM USERS U, ODMSGRCP O

	  	 WHERE O."OdueMsg" = OdueMsg

	  	   AND O."User" > 0

	  	   AND O."User" = U."User"

	  	   AND U."Deleted" = 0

	  	UNION

	  	SELECT U."User"

	  	  FROM USERS U, ODMSGRCP O, UMEMBER UM

	  	 WHERE O."OdueMsg" = OdueMsg

	  	   AND O."User" = 0

	  	   AND O."UGroup" = UM."UGroup"

	  	   AND UM."User" = U."User"

	  	   AND U."Deleted" = 0;





	-- message variables

	v_MessageId MESSAGE."Message"%TYPE;

	v_Sender	USERS."User"%TYPE;

	v_Priority	MESSAGE."IsPriority"%TYPE;

	v_Subject	MESSAGE."Subject"%TYPE;

	v_Text		MESSAGE.TEXT%TYPE;



	-- other variables

	v_Overdue			OVERDUE%ROWTYPE;

	v_OdueMsg			ODUEMSG%ROWTYPE;

	v_AssignedProvider 	PRODUCER%ROWTYPE;

	v_AssignedUser		USERS."User"%TYPE;

	v_Expiry	DATE;

	v_DaysOver	NUMBER;

	v_Today 	DATE;

	v_PtName	 VARCHAR2(128);

	v_ProdName	 VARCHAR2(128);

	v_Date 		 VARCHAR2(64);

	v_Count		NUMBER;



BEGIN



   -- AX-24111 j.s added ability to disable triggers for the given sessions 

   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN 

      return :new; 

   END IF; 





	-- check if automated message should fire

	IF MESSAGE_PKG.MSG_TRIGGER_CAN_FIRE('AUTOMSG_PTOVERDUE', v_Priority) = 0 THEN

		return :new;

	END IF;





	--------------------------------------------

	-- get the information for the overdue condition

	--------------------------------------------

	

	-- get the Overdue and OdueMsg Records (if any require a message to be sent)

	BEGIN

		SELECT O.*

		  INTO v_Overdue

		  FROM OVERDUE O

		 WHERE O."Overdue" = :NEW."Overdue";

	EXCEPTION WHEN NO_DATA_FOUND THEN

		return :new;

	END;	   

	 

	BEGIN

		SELECT ODM.*

		  INTO v_OdueMsg

		  FROM ODUEMSG ODM

		 WHERE ODM."OdueMsg" = v_Overdue."MsgOnLimit"

		   AND (ODM."Producer" = 1 OR ODM."GroupLeader" = 1 OR ODM."PatientManager" = 1 OR ODM."OtherRecipients" = 1);

	EXCEPTION WHEN NO_DATA_FOUND THEN

		return :new;

	END;	   

	 

	-- check if there is an extension on the overdue condition

	v_DaysOver := :NEW."DaysOverdue";

	v_Today := TRUNC(SYSDATE);



	BEGIN

		SELECT MAX("ExpiryDate") 

		  INTO v_Expiry

		  FROM PTOVREXT 

		  WHERE "Patient" = :NEW."Patient"

			AND (("Overdue" = :NEW."Overdue" AND "Provider" = :NEW."Producer") OR "ForAll" = 1) 

			AND "ExpiryDate" >= (v_Today-v_DaysOver);

	EXCEPTION WHEN NO_DATA_FOUND THEN

		v_Expiry := NULL;

	END;

	



	-- if an extension has been granted, adjust the days overdue

	IF v_Expiry IS NOT NULL THEN

		v_DaysOver := :NEW."Limit" +  EXTRACT(DAY FROM v_Today - v_Expiry) + 1;

	END IF;

	

	-- if not still overdue then return

	IF v_DaysOver < :NEW."Limit" THEN

		return :new;

	END IF;

	



	--------------------------------------------

	-- start formatting fields for the messages

	--------------------------------------------



	-- get Patient Name

	v_PtName := MESSAGE_PKG.GET_PATIENT_NAME(2, :NEW."Patient");





	-- get assigned Producer 

	v_ProdName := '';

	

	IF NOT (TRIM(:NEW."Producer") IS NULL OR LENGTH(TRIM(:NEW."Producer")) = 0) THEN

	  BEGIN

		SELECT P.*

		  INTO v_AssignedProvider

		  FROM USERS U, PRODUCER P

		 WHERE U."Producer" = :NEW."Producer"

		   AND U."Producer" = P."Producer"

		   AND U."Deleted" = 0;



		SELECT U."User"

		  INTO v_AssignedUser

		  FROM USERS U

		 WHERE U."Producer" = :NEW."Producer"

		   AND U."Deleted" = 0;



		-- get assigned producer's name

		v_ProdName := ' assigned to ' || MESSAGE_PKG.GET_USER_NAME(2, v_AssignedUser);

	  END;

	END IF;

	

	

	-- format date 

	v_Date := MESSAGE_PKG.FORMAT_DATE(1, :NEW."Date");

	





	--------------------------------------------

	-- send the messages 

	--------------------------------------------

	

	-- send to the assigned provider

	IF NOT (TRIM(:NEW."Producer") IS NULL OR LENGTH(TRIM(:NEW."Producer")) = 0) AND v_OdueMsg."Producer" = 1 THEN

	  BEGIN

	  

	  	-- check if message has already been sent

	  	SELECT COUNT(*) 

	  	  INTO v_Count

	  	  FROM ODMSGSNT ODM, ODLIMITS ODL 

	  	 WHERE ODM."User" = v_AssignedUser 

	  	   AND ODM."Patient" = :NEW."Patient" 

	  	   AND ODM."Producer" = :NEW."Producer" 

	  	   AND ODM."Overdue" = :NEW."Overdue" 

	  	   AND ODM."Type" = 0

		   AND  ODM."Overdue" = ODL."Overdue" 

		   AND (ODL."Frequency" = 0 

		   		OR ODUE_PKG.DAYS_BETWEEN(ODM."Date", SYSDATE) < ODL."Frequency");

		   	

		IF v_Count = 0 THEN

		  BEGIN



			-- Sender

			v_Sender := v_AssignedUser;



			-- Subject

			v_Subject := 'Patient is Overdue';



			-- Text

			v_Text := 'A patient assigned to you is overdue.' || chr(13) || chr(10) || chr(13) || chr(10);

			v_Text := v_Text || 'Patient: ' || v_PtName || v_ProdName || chr(13) || chr(10);

			v_Text := v_Text || 'Reason: ' || TRIM(v_Overdue."Description") || chr(13) || chr(10);

			v_Text := v_Text || TO_CHAR(v_DaysOver) || ' days (' || TO_CHAR(v_DaysOver-:NEW."Limit") || ' over limit) as of ' || v_Date || '.'; 





			-- Add the message

			MESSAGE_PKG.ADD_AUTOMESSAGE('AUTOMSG_PTOVERDUE', v_Sender, SYSDATE, v_Priority, v_Subject, v_Text, v_MessageId);





			-- Add the recipient 

			MESSAGE_PKG.ADD_RECIPIENT_USER(v_MessageId, v_AssignedUser);





			-- Add message sent row

			INSERT INTO ODMSGSNT ("OdMsgSnt", "Patient", "Producer", "Overdue", "User", "Type", "Date")

			VALUES (ODMSGSNT_OdMsgSnt_SEQ.NextVal, :NEW."Patient", :NEW."Producer", :NEW."Overdue", v_AssignedUser, 0, TRUNC(SYSDATE));

			

		  END;

		END IF;



	  END;

	END IF;

	



	-- send to the assigned provider's group leaders

	IF NOT (TRIM(:NEW."Producer") IS NULL OR LENGTH(TRIM(:NEW."Producer")) = 0) 

		AND v_OdueMsg."GroupLeader" = 1 

		AND NOT (TRIM(v_AssignedProvider."PGroup") IS NULL OR LENGTH(TRIM(v_AssignedProvider."PGroup")) = 0)

	THEN

	  BEGIN

	  

	  	-- get the group leaders

		FOR rec IN CUR_GROUPLEADERS(v_AssignedProvider."PGroup") LOOP

		  BEGIN	  

		  

			-- check if message has already been sent

			SELECT COUNT(*) 

			  INTO v_Count

			  FROM ODMSGSNT ODM, ODLIMITS ODL 

			 WHERE ODM."User" = rec."User"

			   AND ODM."Patient" = :NEW."Patient" 

			   AND ODM."Producer" = :NEW."Producer" 

			   AND ODM."Overdue" = :NEW."Overdue" 

			   AND ODM."Type" = 1

			   AND  ODM."Overdue" = ODL."Overdue" 

			   AND (ODL."Frequency" = 0 

					OR ODUE_PKG.DAYS_BETWEEN(ODM."Date", SYSDATE) < ODL."Frequency");



			IF v_Count = 0 THEN

			  BEGIN

				-- Sender

				v_Sender := rec."User";



				-- Subject

				v_Subject := 'Patient is Overdue';



				-- Text

				v_Text := 'A patient assigned to a provider in your group is overdue.' || chr(13) || chr(10) || chr(13) || chr(10);

				v_Text := v_Text || 'Patient: ' || v_PtName || v_ProdName || chr(13) || chr(10);

				v_Text := v_Text || 'Reason: ' || TRIM(v_Overdue."Description") || chr(13) || chr(10);

				v_Text := v_Text || TO_CHAR(v_DaysOver) || ' days (' || TO_CHAR(v_DaysOver-:NEW."Limit") || ' over limit) as of ' || v_Date || '.'; 





				-- Add the message

				MESSAGE_PKG.ADD_AUTOMESSAGE('AUTOMSG_PTOVERDUE', v_Sender, SYSDATE, v_Priority, v_Subject, v_Text, v_MessageId);





				-- Add the recipient

				MESSAGE_PKG.ADD_RECIPIENT_USER(v_MessageId, rec."User");





				-- Add message sent row

				INSERT INTO ODMSGSNT ("OdMsgSnt", "Patient", "Producer", "Overdue", "User", "Type", "Date")

				VALUES (ODMSGSNT_OdMsgSnt_SEQ.NextVal, :NEW."Patient", :NEW."Producer", :NEW."Overdue", rec."User", 1, TRUNC(SYSDATE));

				

			  END;

			END IF;

		

		  END;

		END LOOP;

		

	  END;

	END IF;

	

	

	-- send to the patient's care manager

	IF v_OdueMsg."PatientManager" = 1 THEN

	  BEGIN



		-- get the patient care managers

		FOR rec IN CUR_PTMANAGERS(:NEW."Patient") LOOP

		  BEGIN	  



			-- check if message has already been sent

			SELECT COUNT(*) 

			  INTO v_Count

			  FROM ODMSGSNT ODM, ODLIMITS ODL 

			 WHERE ODM."User" = rec."User"

			   AND ODM."Patient" = :NEW."Patient" 

			   AND (ODM."Producer" = :NEW."Producer" 

			   		OR ((TRIM(ODM."Producer") IS NULL OR LENGTH(TRIM(ODM."Producer")) = 0) AND (TRIM(:NEW."Producer") IS NULL OR LENGTH(TRIM(:NEW."Producer")) = 0)))

			   AND ODM."Overdue" = :NEW."Overdue" 

			   AND ODM."Type" = 2

			   AND  ODM."Overdue" = ODL."Overdue" 

			   AND (ODL."Frequency" = 0 

					OR ODUE_PKG.DAYS_BETWEEN(ODM."Date", SYSDATE) < ODL."Frequency");



			IF v_Count = 0 THEN

			  BEGIN

				-- Sender

				v_Sender := rec."User";



				-- Subject

				v_Subject := 'Patient is Overdue';



				-- Text

				v_Text := 'A patient that you are managing is overdue.' || chr(13) || chr(10) || chr(13) || chr(10);

				v_Text := v_Text || 'Patient: ' || v_PtName || v_ProdName || chr(13) || chr(10);

				v_Text := v_Text || 'Reason: ' || TRIM(v_Overdue."Description") || chr(13) || chr(10);

				v_Text := v_Text || TO_CHAR(v_DaysOver) || ' days (' || TO_CHAR(v_DaysOver-:NEW."Limit") || ' over limit) as of ' || v_Date || '.'; 





				-- Add the message

				MESSAGE_PKG.ADD_AUTOMESSAGE('AUTOMSG_PTOVERDUE', v_Sender, SYSDATE, v_Priority, v_Subject, v_Text, v_MessageId);





				-- Add the recipient 

				MESSAGE_PKG.ADD_RECIPIENT_USER(v_MessageId, rec."User");





				-- Add message sent row

				INSERT INTO ODMSGSNT ("OdMsgSnt", "Patient", "Producer", "Overdue", "User", "Type", "Date")

				VALUES (ODMSGSNT_OdMsgSnt_SEQ.NextVal, :NEW."Patient", :NEW."Producer", :NEW."Overdue", rec."User", 2, TRUNC(SYSDATE));



			  END;

			END IF;



		  END;

		END LOOP;



	  END;

	END IF;



	

	-- send to explicit recipients

	IF v_OdueMsg."OtherRecipients" = 1 THEN

	  BEGIN



		-- get the patient care managers

		FOR rec IN CUR_OTHERRECIPS(v_OdueMsg."OdueMsg") LOOP

		  BEGIN	  



			-- check if message has already been sent

			SELECT COUNT(*) 

			  INTO v_Count

			  FROM ODMSGSNT ODM, ODLIMITS ODL 

			 WHERE ODM."User" = rec."User"

			   AND ODM."Patient" = :NEW."Patient" 

			   AND (ODM."Producer" = :NEW."Producer" 

			   		OR ((TRIM(ODM."Producer") IS NULL OR LENGTH(TRIM(ODM."Producer")) = 0) AND (TRIM(:NEW."Producer") IS NULL OR LENGTH(TRIM(:NEW."Producer")) = 0)))

			   AND ODM."Overdue" = :NEW."Overdue" 

			   AND ODM."Type" = 3

			   AND  ODM."Overdue" = ODL."Overdue" 

			   AND (ODL."Frequency" = 0 

					OR ODUE_PKG.DAYS_BETWEEN(ODM."Date", SYSDATE) < ODL."Frequency");



			IF v_Count = 0 THEN

			  BEGIN

				-- Sender

				v_Sender := rec."User";



				-- Subject

				v_Subject := 'Patient is Overdue';



				-- Text

				v_Text := 'A patient is overdue.' || chr(13) || chr(10) || chr(13) || chr(10);

				v_Text := v_Text || 'Patient: ' || v_PtName || v_ProdName || chr(13) || chr(10);

				v_Text := v_Text || 'Reason: ' || TRIM(v_Overdue."Description") || chr(13) || chr(10);

				v_Text := v_Text || TO_CHAR(v_DaysOver) || ' days (' || TO_CHAR(v_DaysOver-:NEW."Limit") || ' over limit) as of ' || v_Date || '.'; 





				-- Add the message

				MESSAGE_PKG.ADD_AUTOMESSAGE('AUTOMSG_PTOVERDUE', v_Sender, SYSDATE, v_Priority, v_Subject, v_Text, v_MessageId);





				-- Add the recipient 

				MESSAGE_PKG.ADD_RECIPIENT_USER(v_MessageId, rec."User");





				-- Add message sent row

				INSERT INTO ODMSGSNT ("OdMsgSnt", "Patient", "Producer", "Overdue", "User", "Type", "Date")

				VALUES (ODMSGSNT_OdMsgSnt_SEQ.NextVal, :NEW."Patient", :NEW."Producer", :NEW."Overdue", rec."User", 3, TRUNC(SYSDATE));



			  END;

			END IF;



		  END;

		END LOOP;



	  END;

	END IF;

	

	  



EXCEPTION WHEN OTHERS THEN

	return :new;

END$trigger$
 ;
CREATE TRIGGER automsg_ptovrext BEFORE INSERT OR UPDATE OF "Overdue", "Provider", "Date", "ExpiryDate", "ForAll", "Reason" ON ptovrext FOR EACH ROW WHEN (new."ExpiryDate" > trunc(sysdate))  $trigger$DECLARE

	-- Patient Overdues cursor
	CURSOR CUR_PTOVRDUE(Patient NUMBER, Overdue CHAR, Provider CHAR, ForAll NUMBER) IS
		SELECT *
		  FROM PTOVRDUE
		 WHERE "Patient" = Patient
		   AND (ForAll = 1 OR
		   		(((TRIM(Overdue) IS NULL OR LENGTH(TRIM(Overdue)) = 0) OR "Overdue" = Overdue)
		   		AND ((TRIM(Provider) IS NULL OR LENGTH(TRIM(Provider)) = 0) OR "Producer" = Provider)));

	-- Group Leader cursor; E57272.2; E69003
	CURSOR CUR_GROUPLEADERS(PGroup CHAR) IS
	  	SELECT U."User"
	  	  FROM USERS U
	  	 WHERE U."IsGroupManager" = 1
	  	   AND PGroup IN (SELECT UP."PGroup"
			  FROM UPGROUP UP WHERE UP."User" = U."User")
	  	   AND U."Deleted" = 0;		

	-- Patient Care Manager cursor; E69003
	CURSOR CUR_PTMANAGERS(Patient NUMBER) IS
	  	SELECT U."User"
	  	  FROM USERS U, PTMANAGE PTM
	  	 WHERE U."IsManager" = 1
	  	   AND U."Deleted" = 0
	  	   AND PTM."User" = U."User"
	  	   AND PTM."Deleted" = 0
	  	   AND PTM."Patient" = Patient;		

	-- Other recipients cursor
	CURSOR CUR_OTHERRECIPS(OdueMsg CHAR) IS
	  	SELECT U."User"
	  	  FROM USERS U, ODMSGRCP O
	  	 WHERE O."OdueMsg" = OdueMsg
	  	   AND O."User" > 0
	  	   AND O."User" = U."User"
	  	   AND U."Deleted" = 0
	  	UNION
	  	SELECT U."User"
	  	  FROM USERS U, ODMSGRCP O, UMEMBER UM
	  	 WHERE O."OdueMsg" = OdueMsg
	  	   AND O."User" = 0
	  	   AND O."UGroup" = UM."UGroup"
	  	   AND UM."User" = U."User"
	  	   AND U."Deleted" = 0;


	-- message variables
	v_MessageId MESSAGE."Message"%TYPE;
	v_Sender	USERS."User"%TYPE;
	v_Priority	MESSAGE."IsPriority"%TYPE;
	v_Subject	MESSAGE."Subject"%TYPE;
	v_Text		MESSAGE.TEXT%TYPE;

	-- other variables
	v_Overdue			OVERDUE%ROWTYPE;
	v_OdueMsg			ODUEMSG%ROWTYPE;
	v_AssignedProvider 	PRODUCER%ROWTYPE;
	v_AssignedUser		USERS."User"%TYPE;
	v_Expiry	DATE;
	v_DaysOver	NUMBER;
	v_Today 	DATE;
	v_PtName	VARCHAR2(128 );
	v_ProdName	VARCHAR2(128 );
	v_Date 		VARCHAR2(64 );	-- E50677
	v_ExpiryDate VARCHAR2(64 );
	v_Count		NUMBER;
	
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


	-- check if automated message should fire
	IF MESSAGE_PKG.MSG_TRIGGER_CAN_FIRE('AUTOMSG_PTOVREXT', v_Priority) = 0 THEN
		RETURN :new;
	END IF;


	--------------------------------------------
	-- for each overdue condition extended, send any potential messages
	--------------------------------------------
	FOR recPtOvrdue IN CUR_PTOVRDUE(:NEW."Patient", :NEW."Overdue", :NEW."Provider", :NEW."ForAll") LOOP
	  BEGIN
	
		-- get the Overdue and OdueMsg Records (if any require a message to be sent)
		BEGIN
			SELECT O.*
			  INTO v_Overdue
			  FROM OVERDUE O
			 WHERE O."Overdue" = recPtOvrdue."Overdue";
		EXCEPTION WHEN NO_DATA_FOUND THEN
			GOTO next_overdue;
		END;	

		BEGIN
			SELECT ODM.*
			  INTO v_OdueMsg
			  FROM ODUEMSG ODM
			 WHERE ODM."OdueMsg" = v_Overdue."MsgOnExtension"
			   AND (ODM."Producer" = 1 OR ODM."GroupLeader" = 1 OR ODM."PatientManager" = 1 OR ODM."OtherRecipients" = 1);
		EXCEPTION WHEN NO_DATA_FOUND THEN
			GOTO next_overdue;
		END;	


		-- check if there is an extension on the overdue condition
		-- because if there already was an extension then we don't really
		-- need to notify them again
		v_DaysOver := recPtOvrdue."DaysOverdue";
		v_Today := TRUNC(SYSDATE);

		BEGIN
			SELECT MAX("ExpiryDate")
			  INTO v_Expiry
			  FROM PTOVREXT
			  WHERE "Patient" = recPtOvrdue."Patient"
				AND (("Overdue" = recPtOvrdue."Overdue" AND "Provider" = recPtOvrdue."Producer") OR "ForAll" = 1)
				AND "ExpiryDate" >= (v_Today-v_DaysOver)
				AND "PtOvrExt" <> :NEW."PtOvrExt";
		EXCEPTION WHEN NO_DATA_FOUND THEN
			v_Expiry := NULL;
		END;


		-- if an extension has been granted, adjust the days overdue
		IF v_Expiry IS NOT NULL THEN
			v_DaysOver := recPtOvrdue."Limit" + (v_Today-v_Expiry) + 1;
		END IF;

		-- if not still overdue then go to the next overdue condition
		IF v_DaysOver < recPtOvrdue."Limit" THEN
			GOTO next_overdue;
		END IF;


		--------------------------------------------
		-- start formatting fields for the messages
		--------------------------------------------

		-- get Patient Name
		v_PtName := MESSAGE_PKG.GET_PATIENT_NAME(2, recPtOvrdue."Patient");


		-- get assigned Producer
		v_ProdName := '';

		IF NOT (TRIM(recPtOvrdue."Producer") IS NULL OR LENGTH(TRIM(recPtOvrdue."Producer")) = 0) THEN
		  BEGIN
			SELECT P.*
			  INTO v_AssignedProvider
			  FROM USERS U, PRODUCER P
			 WHERE U."Producer" = recPtOvrdue."Producer"
			   AND U."Producer" = P."Producer"
			   AND U."Deleted" = 0;

			SELECT U."User"
			  INTO v_AssignedUser
			  FROM USERS U
			 WHERE U."Producer" = recPtOvrdue."Producer"
			   AND U."Deleted" = 0;

			-- get assigned producer's name
			v_ProdName := ' assigned to ' || MESSAGE_PKG.GET_USER_NAME(2, v_AssignedUser);
		  END;
		END IF;


		-- format dates (E50677)
		v_Date := MESSAGE_PKG.FORMAT_DATE(1, :NEW."Date");
		v_ExpiryDate := MESSAGE_PKG.FORMAT_DATE(1, :NEW."ExpiryDate");



		--------------------------------------------
		-- send the messages
		--------------------------------------------

		-- send to the assigned provider
		IF NOT (TRIM(recPtOvrdue."Producer") IS NULL OR LENGTH(TRIM(recPtOvrdue."Producer")) = 0) AND v_OdueMsg."Producer" = 1 THEN
		  BEGIN

			-- Sender
			v_Sender := v_AssignedUser;

			-- Subject
			v_Subject := 'Overdue Patient Extension';

			-- Text (E50677)
			v_Text := 'An extension has been granted for an overdue patient assigned to you.' || chr(13) || chr(10) || chr(13) || chr(10);
			v_Text := v_Text || 'Overdue patient: ' || v_PtName || v_ProdName || chr(13) || chr(10);
			v_Text := v_Text || 'Overdue Reason: ' || TRIM(v_Overdue."Description") || chr(13) || chr(10);
			v_Text := v_Text || 'Extended between ' || v_Date || ' and ' || v_ExpiryDate; 			
			
			-- E50678
			if length(:NEW."Reason") > 0 then
				v_Text := v_Text || chr(13) || chr(10) || 'Extention Reason: ' || TRIM(:NEW."Reason");
			end if;


			-- Add the message
			MESSAGE_PKG.ADD_AUTOMESSAGE('AUTOMSG_PTOVREXT', v_Sender, SYSDATE, v_Priority, v_Subject, v_Text, v_MessageId);


			-- Add the recipient
			MESSAGE_PKG.ADD_RECIPIENT_USER(v_MessageId, v_AssignedUser);


			-- delete message sent row
			DELETE FROM ODMSGSNT
			 WHERE "Patient" = recPtOvrdue."Patient"
			   AND "Producer" = recPtOvrdue."Producer"
			   AND "Overdue" = recPtOvrdue."Overdue"
			   AND "Type" = 0;

		  END;
		END IF;


		-- send to the assigned provider's group leaders
		IF NOT (TRIM(recPtOvrdue."Producer") IS NULL OR LENGTH(TRIM(recPtOvrdue."Producer")) = 0)
			AND v_OdueMsg."GroupLeader" = 1
			AND NOT (TRIM(v_AssignedProvider."PGroup") IS NULL OR LENGTH(TRIM(v_AssignedProvider."PGroup")) = 0)
		THEN
		  BEGIN

			-- get the group leaders
			FOR rec IN CUR_GROUPLEADERS(v_AssignedProvider."PGroup") LOOP
			  BEGIN	

				-- Sender
				v_Sender := rec."User";

				-- Subject
				v_Subject := 'Overdue Patient Extension';

				-- Text (E50677)
				v_Text := 'An extension has been granted for an overdue patient assigned to a provider in your group.' || chr(13) || chr(10) || chr(13) || chr(10);
				v_Text := v_Text || 'Overdue patient: ' || v_PtName || v_ProdName || chr(13) || chr(10);
				v_Text := v_Text || 'Reason: ' || TRIM(v_Overdue."Description") || chr(13) || chr(10);
				v_Text := v_Text || 'Extended between ' || v_Date || ' and ' || v_ExpiryDate;

				-- E50678
				if length(:NEW."Reason") > 0 then
					v_Text := v_Text || chr(13) || chr(10) || 'Extention Reason: ' || TRIM(:NEW."Reason");
				end if;


				-- Add the message
				MESSAGE_PKG.ADD_AUTOMESSAGE('AUTOMSG_PTOVREXT', v_Sender, SYSDATE, v_Priority, v_Subject, v_Text, v_MessageId);


				-- Add the recipient
				MESSAGE_PKG.ADD_RECIPIENT_USER(v_MessageId, rec."User");


				-- delete message sent row
				DELETE FROM ODMSGSNT
				 WHERE "Patient" = recPtOvrdue."Patient"
				   AND "Producer" = recPtOvrdue."Producer"
				   AND "Overdue" = recPtOvrdue."Overdue"
				   AND "Type" = 1;

			  END;
			END LOOP;

		  END;
		END IF;


		-- send to the patient's care manager
		IF v_OdueMsg."PatientManager" = 1 THEN
		  BEGIN

			-- get the patient care managers
			FOR rec IN CUR_PTMANAGERS(recPtOvrdue."Patient") LOOP
			  BEGIN	

				-- Sender
				v_Sender := rec."User";

				-- Subject
				v_Subject := 'Overdue Patient Extension';

				-- Text (E50677)
				v_Text := 'An extension has been granted for an overdue patient that you are managing.' || chr(13) || chr(10) || chr(13) || chr(10);
				v_Text := v_Text || 'Overdue patient: ' || v_PtName || v_ProdName || chr(13) || chr(10);
				v_Text := v_Text || 'Reason: ' || TRIM(v_Overdue."Description") || chr(13) || chr(10);
				v_Text := v_Text || 'Extended between ' || v_Date || ' and ' || v_ExpiryDate;

				-- E50678
				if length(:NEW."Reason") > 0 then
					v_Text := v_Text || chr(13) || chr(10) || 'Extention Reason: ' || TRIM(:NEW."Reason");
				end if;


				-- Add the message
				MESSAGE_PKG.ADD_AUTOMESSAGE('AUTOMSG_PTOVREXT', v_Sender, SYSDATE, v_Priority, v_Subject, v_Text, v_MessageId);


				-- Add the recipient
				MESSAGE_PKG.ADD_RECIPIENT_USER(v_MessageId, rec."User");


				-- delete message sent row
				DELETE FROM ODMSGSNT
				 WHERE "Patient" = recPtOvrdue."Patient"
				   AND ("Producer" = recPtOvrdue."Producer" OR (TRIM(recPtOvrdue."Producer") IS NULL OR LENGTH(TRIM(recPtOvrdue."Producer")) = 0))
				   AND "Overdue" = recPtOvrdue."Overdue"
				   AND "Type" = 2;

			  END;
			END LOOP;

		  END;
		END IF;


		-- send to explicit recipients
		IF v_OdueMsg."OtherRecipients" = 1 THEN
		  BEGIN

			-- get the patient care managers
			FOR rec IN CUR_OTHERRECIPS(v_OdueMsg."OdueMsg") LOOP
			  BEGIN	

				-- Sender
				v_Sender := rec."User";

				-- Subject
				v_Subject := 'Overdue Patient Extension';

				-- Text (E50677)
				v_Text := 'An extension has been granted for an overdue patient.' || chr(13) || chr(10) || chr(13) || chr(10);
				v_Text := v_Text || 'Overdue patient: ' || v_PtName || v_ProdName || chr(13) || chr(10);
				v_Text := v_Text || 'Reason: ' || TRIM(v_Overdue."Description") || chr(13) || chr(10);
				v_Text := v_Text || 'Extended between ' || v_Date || ' and ' || v_ExpiryDate;

				-- E50678
				if length(:NEW."Reason") > 0 then
					v_Text := v_Text || chr(13) || chr(10) || 'Extention Reason: ' || TRIM(:NEW."Reason");
				end if;


				-- Add the message
				MESSAGE_PKG.ADD_AUTOMESSAGE('AUTOMSG_PTOVREXT', v_Sender, SYSDATE, v_Priority, v_Subject, v_Text, v_MessageId);


				-- Add the recipient
				MESSAGE_PKG.ADD_RECIPIENT_USER(v_MessageId, rec."User");


				-- delete message sent row
				DELETE FROM ODMSGSNT
				 WHERE "Patient" = recPtOvrdue."Patient"
				   AND ("Producer" = recPtOvrdue."Producer" OR (TRIM(recPtOvrdue."Producer") IS NULL OR LENGTH(TRIM(recPtOvrdue."Producer")) = 0))
				   AND "Overdue" = recPtOvrdue."Overdue"
				   AND "Type" = 3;

			  END;
			END LOOP;

		  END;
		END IF;

		<<next_overdue>>
		NULL; -- executable statement required after a goto label
	  END;
	END LOOP;
	
	
EXCEPTION WHEN OTHERS THEN
	RETURN :new;
END$trigger$
 ;
CREATE TRIGGER automsg_ptsignin AFTER INSERT OR UPDATE OF "IsIn" ON checkin FOR EACH ROW  $trigger$DECLARE

	-- appointment info

	CURSOR CUR_APPOINT IS

		SELECT A.*, CH."Description" "ChairDesc", CL."Description" "ClinicDesc"

		  FROM APPOINT A, CHAIR CH, CLINIC CL

		 WHERE A."Appointment" = :NEW."Appointment"

		   AND A."Chair" = CH."Chair" (+)

		   AND CH."Clinic" = CL."Clinic" (+);



	-- message variables

	v_MessageId MESSAGE."Message"%TYPE;

	v_Sender	USERS."User"%TYPE;

	v_Priority	MESSAGE."IsPriority"%TYPE;

	v_Subject	MESSAGE."Subject"%TYPE;

	v_Text		MESSAGE.TEXT%TYPE;





	-- other variables

	v_PtName	VARCHAR2(128 );

	v_Time		VARCHAR2(128 );

	

BEGIN



	-- Fail fast: exit if the condition is not met; AX-36765

	IF NOT ( :NEW."IsIn" = 2 AND ( :OLD."IsIn" <> 2 OR :OLD."IsIn" IS NULL ) ) THEN

		RETURN :new;

	END IF;	



	-- AX-24111 j.s added ability to disable triggers for the given sessions 

	IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN 

		RETURN :new; 

	END IF; 





	-- check if automated message should fire

	IF MESSAGE_PKG.MSG_TRIGGER_CAN_FIRE('AUTOMSG_PTSIGNIN', v_Priority) = 0 THEN

		RETURN :new;

	END IF;

	

	-- get appointment record

	FOR rec IN CUR_APPOINT LOOP



		-- Sender

		-- E50478 - use SignInUser

		-- B77438 - SignInUser not always set

		if :NEW."SignInUser" > 0 then

			v_Sender := :NEW."SignInUser";

		else

			-- use the Provider's user id as the sender

			SELECT MIN("User")

			  INTO v_Sender

			  FROM USERS

			 WHERE "Producer" = rec."Producer"

				AND "Deleted" = 0;

		end if;

		



		-- Subject

		v_Subject := 'Patient Signed In';



		-- Text

		v_PtName := MESSAGE_PKG.GET_PATIENT_NAME(2, :NEW."Patient");



		v_Time := MESSAGE_PKG.FORMAT_TIME(3, rec."From");





		v_Text := 'Patient ' || v_PtName || ' has signed in for his/her appointment at ' || v_Time || '.' || chr(13) || chr(10) 

			|| chr(13) || chr(10)

			|| 'Order Id: ' || :NEW."OrderId" || chr(13) || chr(10)

			|| 'Clinic: ' || rec."ClinicDesc" || chr(13) || chr(10)

			|| 'Chair: ' || rec."ChairDesc";







		-- Add the message, AX-11528.11628

		MESSAGE_PKG.ADD_AUTOMESSAGE('AUTOMSG_PTSIGNIN', v_Sender, SYSDATE, v_Priority, v_Subject, v_Text, v_MessageId);





		-- Add the recipient 

		MESSAGE_PKG.ADD_RECIPIENT_PROVIDER(v_MessageId, rec."Producer");

		

	END LOOP;

	EXCEPTION WHEN OTHERS THEN

	RETURN :new;		

END$trigger$
 ;
CREATE TRIGGER automsg_ptunassign2 AFTER INSERT ON ptprodh FOR EACH ROW WHEN (new."Deleted" = 1::numeric)  $trigger$DECLARE

	-- message variables
	v_MessageId MESSAGE."Message"%TYPE;
	v_Sender	USERS."User"%TYPE;
	v_Priority	MESSAGE."IsPriority"%TYPE;
	v_Subject	MESSAGE."Subject"%TYPE;
	v_Text		MESSAGE.TEXT%TYPE;

	-- other variables
	v_Today 	DATE;
	v_PtName	VARCHAR2(128 );
--	v_DateRange VARCHAR2(128 CHAR);
	v_ProviderName VARCHAR2(128 );

BEGIN

	   -- AX-24111 j.s added ability to disable triggers for the given sessions
	   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
	      RETURN :new;
	   END IF;

	-- check if automated message should fire
	IF MESSAGE_PKG.MSG_TRIGGER_CAN_FIRE('AUTOMSG_PTUNASSIGN', v_Priority) = 0 THEN
		RETURN :new;
	END IF;

	v_Today := TRUNC(SYSDATE);
 	
	-- Sender
	v_Sender := :NEW."User";

	v_Subject := 'Patient Unassigned';

	-- Text
	-- basic message
	v_PtName := MESSAGE_PKG.GET_PATIENT_NAME(2, :NEW."Patient");

	v_ProviderName := MESSAGE_PKG.GET_PROVIDER_NAME(2, :NEW."Producer");

--	v_DateRange := NVL(MESSAGE_PKG.FORMAT_DATE(1, v_PtProd."StartDate"), 'no start date')
--		|| ' to ' || NVL(MESSAGE_PKG.FORMAT_DATE(1, v_PtProd."EndDate"), 'no end date');

	v_Text := 'Patient ' || v_PtName || ' has been unassigned from ' || v_ProviderName || '.' || chr(13) || chr(10);

	-- Add the message
	MESSAGE_PKG.ADD_AUTOMESSAGE('AUTOMSG_PTUNASSIGN', v_Sender, SYSDATE, v_Priority, v_Subject, v_Text, v_MessageId);


	-- Add the recipient
	MESSAGE_PKG.ADD_RECIPIENT_PROVIDER(v_MessageId, :NEW."Producer");



	-- uncomment the following if you want them
	
	-- Add the provider's group leader(s) as recipients
	--MESSAGE_PKG.ADD_RECIPIENT_GROUPLEADER(v_MessageId, v_PtProd."Producer");
	
	-- Add the paitent's manager(s) as recipients
	--MESSAGE_PKG.ADD_RECIPIENT_PATIENTMANAGER(v_MessageId, v_PtProd."Patient");
	

EXCEPTION WHEN OTHERS THEN
	RETURN :new;
END$trigger$
 ;
CREATE TRIGGER automsg_refrequest AFTER INSERT OR UPDATE OF "AssignedUser", "AssignedUGroup" ON referral_request FOR EACH ROW WHEN (new."AssignedUser" <> 0::numeric OR NOT (TRIM(BOTH FROM new."AssignedUGroup") IS NULL OR length(TRIM(BOTH FROM new."AssignedUGroup")) = 0))  $trigger$DECLARE

	-- message variables
	v_MessageId 	MESSAGE."Message"%TYPE;
	v_Sender	NUMBER;
	v_Priority	MESSAGE."IsPriority"%TYPE;
	v_Subject	MESSAGE."Subject"%TYPE;
	v_Text		MESSAGE.TEXT%TYPE;

	-- other variables
	v_User 		NUMBER;
	v_PtName	VARCHAR2(512 );
	
BEGIN

   	IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      		RETURN :new;
	END IF;

	-- check if automated message should fire
	IF MESSAGE_PKG.MSG_TRIGGER_CAN_FIRE('AUTOMSG_REFREQUEST', v_Priority) = 0 THEN
		RETURN :new;
	END IF;
	
	-- get user id
	SELECT "OvernightUser"
	  INTO v_User
	  FROM AXIUMOPT;
 	
	-- get patient info
	SELECT TRIM("LastName") || ', ' || TRIM("FirstName")
	  INTO v_PtName
	  FROM PATIENT_REQUEST WHERE "Id" = :NEW."PatientRequestId";
 	
	-- Sender
	v_Sender := v_User;

	-- Subject
	v_Subject := 'An Incoming Inbound Referral has been received';

	-- Text
	-- basic message
	v_Text := 'An Incoming Inbound Referral has been received.' || chr(13) || chr(10) || 'Name: ' || v_PtName;


	-- Add the message
	MESSAGE_PKG.ADD_AUTOMESSAGE('AUTOMSG_REFREQUEST', v_Sender, SYSDATE, v_Priority, v_Subject, v_Text, v_MessageId);

	IF :NEW."AssignedUser" <> 0 THEN
		MESSAGE_PKG.ADD_RECIPIENT_USER(v_MessageId, :NEW."AssignedUser");
	END IF;

	IF :NEW."AssignedUGroup" IS NOT NULL THEN
		MESSAGE_PKG.ADD_RECIPIENT_UGROUP(v_MessageId, :NEW."AssignedUGroup");
	END IF;
	
EXCEPTION WHEN OTHERS THEN
	RETURN :new;
END$trigger$
 ;
CREATE TRIGGER cc_patient BEFORE UPDATE OF "Last", "First", "Middle", "Birth", "Address1", "Address2", "City", "Province", "Postal", "HomeArea", "HomePhone", "WorkArea", "WorkPhone", "WorkExt", "Sex", "Marital", "Sin", "AddressOther", "Email", "Country", "HomeExt", "MobileArea", "MobilePhone", "PrefLanguage", "RaceEthDeclined", "Ethnic" ON patient FOR EACH ROW  $trigger$BEGIN
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  IF (:NEW."HasExternalLink" = 1) THEN
	UPDATE EXTERNAL_LINK SET "AxiumChangeDateTime" = SYSDATE WHERE "PatientId" = :NEW."Patient" AND "Deleted" = 0;
  END IF;
END$trigger$
 ;
CREATE TRIGGER cc_ptrace AFTER INSERT ON ptrace FOR EACH ROW  $trigger$BEGIN
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

	UPDATE EXTERNAL_LINK SET "AxiumChangeDateTime" = SYSDATE WHERE "PatientId" = :NEW."Patient" AND "Deleted" = 0;
END$trigger$
 ;
CREATE TRIGGER cqcontractaddupd AFTER INSERT OR UPDATE OF "Date", "PtSig", "AtTab", "Consent", "ExpiryDate", "Deleted", "SigStatus", "Description" ON contract FOR EACH ROW  $trigger$DECLARE
  v_nEventType 	NUMBER (5) := 0;
  v_nEventStatus 	NUMBER (5) := 0;
  v_sConsent      VARCHAR2(4000) := ' ';

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

   -- carequality OFF or in Staging, ignore
   IF ( CAREQUALITY_PKG.GET_CAREQUALITY_STATUS() <> 2 ) THEN
      RETURN :new;
   END IF;

   -- check if deleting; if so, no need to add; AX-26704 added check on Denied falg
   IF :NEW."Deleted" = 1 OR :NEW."Denied" <> 0 THEN
      RETURN :new;
   END IF;

   -- check if expired; if so, no need to add
   IF :NEW."ExpiryDate" < trunc(sysdate) THEN
      RETURN :new;
   END IF;

   -- lookup sysopts settings
   SELECT TRIM(CAREQUALITY_PKG.GET_CAREQUALITY_CONSENTCODE()) INTO v_sConsent FROM DUAL;

   IF v_sConsent IS NULL  THEN
      -- not setup, no need to add
      RETURN :new;
   END IF;

   -- compare against the add/updated consent
   if (TRIM(:NEW."Consent") <> v_sConsent) THEN
      -- not the required consent, no need to add event
      RETURN :new;
   END IF;

	-- insert event record
   INSERT INTO CAREQUALITY_EVENT VALUES (
		:NEW."Patient",
		v_nEventType,
		sysdate,
		v_nEventStatus,
		0
	);
	EXCEPTION WHEN DUP_VAL_ON_INDEX THEN
		RETURN :new;		


END$trigger$
 ;
CREATE TRIGGER cqcreatecqeventhis AFTER INSERT OR UPDATE OF "Patient", "EventType", "EventDate", "Status", "OtherId" ON carequality_event FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

	-- insert CQ eventhis record
   INSERT INTO CAREQUALITY_EVENTHIS VALUES (
		CAREQUALITY_EVENTHIS_EVENTHIS_SEQ.nextval,
		:NEW."Patient",
		:NEW."EventType",
		:NEW."EventDate",
		:NEW."Status",
		sysdate,
		:NEW."OtherId"
	);

END$trigger$
 ;
CREATE TRIGGER cqnote2addupd AFTER INSERT OR UPDATE OF "Site", "Text", "User", "Status", "Phase", "Seq", "Custom1", "Custom2", "AppUser", "AppDate", "Date" ON notes2 FOR EACH ROW  $trigger$DECLARE
  v_nPatient		NUMBER(10) := 0;	
  v_nEventType 	NUMBER (5) := 3; -- AX-27011
  v_nEventStatus 	NUMBER (5) := 0;
  v_Date				DATE;

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

   -- carequality OFF or in Staging, ignore
	IF ( CAREQUALITY_PKG.GET_CAREQUALITY_STATUS() <> 2 ) THEN
      RETURN :new;
   END IF;

	-- not approved or not for Tx; ignore
	IF :NEW."AppUser" = 0 OR :NEW."TxId" = 0 THEN
		RETURN :new;
	END IF;

	-- strike out; ignored
	IF :NEW."Status" = 2 THEN
		RETURN :new;
	END IF;

	-- get patient Id; AX-26808.3
	SELECT P."PtxPId" INTO v_nPatient
			FROM PATIENT2 P WHERE P."Auto" = :NEW."PId";

   -- use exisitng note2's date
	v_Date := :NEW."Date";

	-- insert event record
   INSERT INTO CAREQUALITY_EVENT VALUES (
		v_nPatient,
		v_nEventType,
		v_Date,
		v_nEventStatus,
		0
	);
	EXCEPTION WHEN DUP_VAL_ON_INDEX  THEN
		RETURN :new;		

END$trigger$
 ;
CREATE TRIGGER cqpatientaddupd AFTER INSERT OR UPDATE OF "Last", "First", "Middle", "Birth", "Address1", "Address2", "City", "Province", "Postal", "HomeArea", "HomePhone", "WorkArea", "WorkPhone", "WorkExt", "OtherArea", "OtherPhone", "OtherExt", "Sex", "Marital", "Sin", "AddressOther", "Email", "MobileArea", "MobilePhone", "PrefLanguage", "RaceEthDeclined", "Ethnic" ON patient FOR EACH ROW  $trigger$DECLARE
  v_nEventType 	NUMBER (5) := 0;
  v_nEventStatus 	NUMBER (5) := 0;

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

   -- carequality OFF or in Staging, ignore
	IF ( CAREQUALITY_PKG.GET_CAREQUALITY_STATUS() <> 2 ) THEN
      RETURN :new;
   END IF;

	-- not a patient; ignore (AX-27199)
	IF ( :NEW."IsPatient" = 0 ) THEN
      RETURN :new;
   END IF;

   -- AX-27011
   IF UPDATING THEN
      v_nEventType := 1;
   END IF;

	-- insert event record
   INSERT INTO CAREQUALITY_EVENT VALUES (
		:NEW."Patient",
		v_nEventType,
		sysdate,
		v_nEventStatus,
		0
	);
	EXCEPTION WHEN DUP_VAL_ON_INDEX THEN
		RETURN :new;		

END$trigger$
 ;
CREATE TRIGGER cqptraceaddupd AFTER INSERT OR UPDATE OF "Race", "Deleted" ON ptrace FOR EACH ROW  $trigger$DECLARE
  v_nEventType 	NUMBER (5) := 1; -- AX-27011
  v_nEventStatus 	NUMBER (5) := 0;
  v_nIsPatient    NUMBER (5) := 0;

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

   -- carequality OFF or in Staging, ignore
	IF ( CAREQUALITY_PKG.GET_CAREQUALITY_STATUS() <> 2 ) THEN
      RETURN :new;
   END IF;

   -- not a patient; ignore (AX-27199)
	SELECT "IsPatient" INTO v_nIsPatient FROM PATIENT WHERE "Patient" = :NEW."Patient";
	IF ( v_nIsPatient = 0 ) THEN
      RETURN :new;
   END IF;

   -- insert event record
   INSERT INTO CAREQUALITY_EVENT VALUES (
		:NEW."Patient",
		v_nEventType,
		sysdate,
		v_nEventStatus,
		0
	);
	EXCEPTION WHEN DUP_VAL_ON_INDEX  THEN
		RETURN :new;		

END$trigger$
 ;
CREATE TRIGGER cqtreatme2addupd AFTER INSERT OR UPDATE OF "CodeId", "Days", "User", "Site", "Status", "Surface", "Deleted", "Site2", "Number", "Phase", "Seq", "Provider", "Custom1", "Custom2", "Discipline", "StationId", "Custom3", "Custom4", "AppUser", "Unit" ON treatme2 FOR EACH ROW  $trigger$DECLARE
  v_nPatient		NUMBER(10) := 0;	
  v_nEventType 	NUMBER (5) := 3; -- AX-27011
  v_nEventStatus 	NUMBER (5) := 0;
  v_Date				DATE;

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

	-- carequality OFF or in Staging, ignore
	IF ( CAREQUALITY_PKG.GET_CAREQUALITY_STATUS() <> 2 ) THEN
      RETURN :new;
   END IF;


	-- not approved; ignore
	IF :NEW."AppUser" = 0 THEN
		RETURN :new;
	END IF;


	-- not C or I, ignore
	IF :NEW."Status" <> 0 AND :NEW."Status" <> 1 THEN
		RETURN :new;
	END IF;

	-- strike out; ignored
	IF :NEW."Deleted" = 2 THEN
		RETURN :new;
	END IF;


	-- get patient Id; AX-26808.3
	SELECT P."PtxPId" INTO v_nPatient
			FROM PATIENT2 P WHERE P."Auto" = :NEW."PId";

	-- convert the date
	v_Date := TO_DATE ('1901-JAN-01', 'YYYY-MON-DD') + :NEW."Days";

   -- insert event record
   INSERT INTO CAREQUALITY_EVENT VALUES (
		v_nPatient,
		v_nEventType,
		v_Date,
		v_nEventStatus,
		0
	);
	EXCEPTION WHEN DUP_VAL_ON_INDEX  THEN
		RETURN :new;		

END$trigger$
 ;
CREATE TRIGGER createaddrnotify AFTER INSERT OR UPDATE OF "InfoNotify" ON patient FOR EACH ROW  $trigger$DECLARE

  GMTTotalOffset	NUMBER (10);

  GMTHourOffset	NUMBER (10);

  GMTMinuteOffset NUMBER (10);

	v_nCount		NUMBER := 0;								-- AX-26071



BEGIN



   -- AX-24111 j.s added ability to disable triggers for the given sessions 

   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN 

      RETURN :new; 

   END IF; 



   -- AX-26071 check for overriding custom trigger

   SELECT COUNT(1) INTO v_nCount FROM USER_TRIGGERS WHERE TRIGGER_NAME = 'CUSTOM_CREATEADDRNOTIFY';  

   IF v_nCount > 0 THEN

      -- custom trigger exists, let it do the work

      RETURN :new;

   END IF;



   SELECT EXTRACT(timezone_hour FROM SYSTIMESTAMP) INTO GMTHourOffset;

   SELECT EXTRACT(timezone_minute FROM SYSTIMESTAMP) INTO GMTMinuteOffset;



  GMTTotalOffset := 0 - (GMTHourOffset*60*60);

  

  IF (GMTHourOffset < 0) THEN

	 GMTTotalOffset := GMTTotalOffset + (GMTMinuteOffset*60);

  ELSE

    GMTTotalOffset := GMTTotalOffset - (GMTMinuteOffset*60);

  END IF;

  

  IF (:NEW."InfoNotify" = 1 AND :OLD."InfoNotify" = 0) THEN

    -- insert address notification 

    INSERT INTO AP_NOTE VALUES ( AP_NOTE_AP_NOTE_AUTODEC_SEQ.nextval,

											:NEW."Patient",

											3,							

											0,							

											SYSDATE, -- E125010

											SYSDATE, -- E125010

											40,							

											0,

											0,

											0,

											0,

											'The patient''s address information is not correct!',

											0,

											0,

											0,

											0

										 );

  END IF;

  

  IF (:NEW."InfoNotify" = 0 AND :OLD."InfoNotify" = 1) THEN

    -- de-activate address notification

    UPDATE AP_NOTE SET "AP_NOTE_Date2" = trunc(sysdate - 1 - to_date('01-01-1901','MM-DD-YYYY')), "AP_NOTE_Flag" = 32776

      WHERE "AP_NOTE_AppId" = :NEW."Patient" AND "AP_NOTE_Type" = 3 AND "AP_NOTE_Flag" = 40

      AND "AP_NOTE_Text" = 'The patient''s address information is not correct!';

  END IF;

END$trigger$
 ;
CREATE TRIGGER createalertp2his AFTER INSERT OR UPDATE OF "AddDateTime", "Flag", "Note" ON alertp2 FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  INSERT INTO ALERTP2H VALUES
    (
      ALERTP2H_AlertP2H_SEQ.nextval,
      :NEW."Auto",
      :NEW."PId",
      :NEW."AddDateTime",
      :NEW."AId",
      :NEW."User",
      :NEW."Flag",
      :NEW."Note",
      :NEW."Audit",
      PTALERTH_PtAlertH_SEQ.nextval,
      :NEW."PtAlert",
      :NEW."Patient",
      :NEW."AlertType",
      :NEW."Description",
      :NEW."Status"
    ) ;
END$trigger$
 ;
CREATE TRIGGER createallocath AFTER INSERT OR DELETE OR UPDATE OF "PayType", "PayId", "PayTreatment", "TrxType", "TrxId", "TrxTreatment", "PolicyId", "Amount" ON allocate FOR EACH ROW  $trigger$DECLARE
	bChanged Boolean := FALSE;
	UserToUse NUMBER(10) := 0;								--AX-9270.13435
   NewAllocateLinkId	NUMBER (10) := 0;                  --AX-26087.3
   LastTxHistoryId NUMBER(10) := 0;                       --AX-26087.3
   LastPmtHistoryId NUMBER(10) := 0;                       --AX-26087.3

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   UserToUse := :OLD."User";									--AX-9270.13435
   if UPDATING then
	   if (:OLD."PayType" <> :NEW."PayType"
			   OR :OLD."PayId" <> :NEW."PayId"
			   OR :OLD."PayTreatment" <> :NEW."PayTreatment"
			   OR :OLD."TrxType" <> :NEW."TrxType"
			   OR :OLD."TrxId" <> :NEW."TrxId"
			   OR :OLD."TrxTreatment" <> :NEW."TrxTreatment"
			   OR :OLD."PolicyId" <> :NEW."PolicyId"
			   OR ROUND(:OLD."Amount", 2) <> ROUND(:NEW."Amount",2)) then
		   bChanged := TRUE;
		   UserToUse := :NEW."User";							--AX-9270.13435
	   end if;
   end if;

   if DELETING or bChanged then

      -- AX-26087.3 added new AllocateLink record if being updated and changed
      if bChanged then
         SELECT ALLOCATELINK_LINK_SEQ.NEXTVAL INTO NewAllocateLinkId FROM DUAL;	
         SELECT MAX("History") INTO LastTxHistoryId FROM HISTORY WHERE "Type" = :OLD."TrxType"
               AND "Id" = :OLD."TrxId" AND "Treatment" = :OLD."TrxTreatment";
         SELECT MAX("History") INTO LastPmtHistoryId FROM HISTORY WHERE "Type" = :OLD."PayType"
               AND "Id" = :OLD."PayId" AND "Treatment" = :OLD."PayTreatment";
	      INSERT INTO ALLOCATELINK("AllocateLink", "TxHistoryId", "PmtHistoryId", "EntryDate")
         	   VALUES (NewAllocateLinkId, LastTxHistoryId, LastPmtHistoryId, SYSDATE);
      else -- no need as calling code should have updated it prior to delete
         NewAllocateLinkId := :OLD."AllocateLink";
      end if;

      INSERT INTO ALLOCATH VALUES (
            ALLOCATH_ALLOCATH_SEQ.nextval,
            :OLD."PayType",
            :OLD."PayId",
            :OLD."PayTreatment",
            :OLD."TrxType",
            :OLD."TrxId",
            :OLD."TrxTreatment",
            :OLD."PolicyId",
            -:OLD."Amount",
            SYSDATE,
	         UserToUse,								--AX-9270.13435						
	         NewAllocateLinkId);					--AX-25978; AX-26087.3
   end if;

   if INSERTING or bChanged then
      INSERT INTO ALLOCATH VALUES (
            ALLOCATH_ALLOCATH_SEQ.nextval,
            :NEW."PayType",
            :NEW."PayId",
            :NEW."PayTreatment",
            :NEW."TrxType",
            :NEW."TrxId",
            :NEW."TrxTreatment",
            :NEW."PolicyId",
            :NEW."Amount",
            SYSDATE,
            :NEW."User",
            :NEW."AllocateLink");							--AX-25978							
   end if;
END$trigger$
 ;
CREATE TRIGGER createappthis AFTER INSERT OR UPDATE OF "Assistant", "Cancel", "Chair", "Class", "Code", "Date", "Estimate", "From", "IsAsap", "IsConfirm", "IsOrtho", "IsRecall", "IsShortNotice", "OrthoStage", "Producer", "Rank", "Reason", "Status", "Time0", "Time1", "Time2", "Time3", "Time4", "Time5", "Type", "UStatus", "Unit0", "Unit1", "Unit2", "Unit3", "Unit4", "Unit5", "User", "Clinic", "Instructor", "CheckInTime", "TimeSeated", "SignInTime", "SecondaryMCBFlag", "NotBeforeDate", "PtEstimateStatus", "PtEstimate", "ExpertAdd", "CheckOutDate", "CheckOutTime", "PrimaryExclusive" ON appoint FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


IF (INSERTING AND (:NEW."Chair">0 or :NEW."Type"!=4)) OR (UPDATING AND ((:NEW."Type"!=4 OR :OLD."Type"!=4) OR
(:NEW."Type"=4 AND :OLD."Type"=4 AND :NEW."From"=:OLD."From"))) THEN
INSERT INTO APPTHIS VALUES (APPTHIS_APPTHIS_SEQ.nextval,
 :NEW."Appointment",
 :NEW."Date",
 :NEW."Chair",
 :NEW."Patient",
 :NEW."Type",
 :NEW."Producer",
 :NEW."From",
 :NEW."CreateDate",
 :NEW."Code",
 :NEW."Unit0",
 :NEW."Unit1",
 :NEW."Unit2",
 :NEW."Unit3",
 :NEW."Unit4",
 :NEW."Unit5",
 :NEW."Time0",
 :NEW."Time1",
 :NEW."Time2",
 :NEW."Time3",
 :NEW."Time4",
 :NEW."Time5",
 :NEW."Estimate",
 :NEW."Class",
 :NEW."ModifiedDateTime",
 :NEW."User",
 :NEW."IsRecall",
 :NEW."IsAsap",
 :NEW."IsConfirm",
 :NEW."IsShortNotice",
 :NEW."Status",
 :NEW."Request",
 :NEW."Rank",
 :NEW."UStatus",
 :NEW."Reserve",
 :NEW."OrthoStage",
 :NEW."IsOrtho",
 :NEW."Cancel",
 :NEW."Reason",
 :NEW."Assistant",
 :NEW."Clinic",
 :NEW."IsRequest",
 :NEW."Instructor",
 :NEW."IsNew",
 :NEW."CheckInTime",
 :NEW."TimeSeated",
 :NEW."Held",
 :NEW."SignInTime",
 :NEW."SecondaryMCBFlag",
 :NEW."NotBeforeDate",
 :NEW."PtEstimateStatus",
 :NEW."PtEstimate",
 :NEW."BookingOrder",
 :NEW."ExpertAdd",
 :NEW."CheckOutDate",		-- E68549
 :NEW."CheckOutTime",		-- E68549
 :NEW."PrimaryExclusive"	-- E131794
 );
END IF;
END$trigger$
 ;
CREATE TRIGGER createchairsth BEFORE INSERT OR UPDATE OF "CNState" ON chairst FOR EACH ROW  $trigger$DECLARE
  AuditId		NUMBER (10);
  HistoryType  NUMBER (5);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

	AuditId := :NEW."Audit";

	-- handle if action done outside of axium	
	IF :OLD."Audit" = :NEW."Audit" THEN
		SELECT AUDITHIS_AUDIT_SEQ.nextval INTO AuditId FROM DUAL;
		
		IF INSERTING THEN
			HistoryType := 1;
		ELSE
			HistoryType := 2;
		END IF;
		
		INSERT INTO AUDITHIS VALUES (
			AuditId,	
			trunc(sysdate),
			trunc(to_char(sysdate,'SSSSS')/60),	
			-1, -- UserId,
			0, -- StationId
			'CHAIRST',
			HistoryType
		);
		
		:NEW."Audit" := AuditId;
	END IF;	
	INSERT INTO CHAIRSTH VALUES (
		CHAIRSTH_CHAIRSTH_SEQ.nextval,
		:NEW."Chair",
		:NEW."ClinicTime",
    :NEW."CNState",
		:NEW."Audit"
	);
END$trigger$
 ;
CREATE TRIGGER createclaimcah BEFORE INSERT OR UPDATE OF "ClaimEOB", "Type", "Treatment", "CAReason", "Amount", "GroupCode" ON claimcas FOR EACH ROW  $trigger$DECLARE
  AuditId		NUMBER (10);
  HistoryType  NUMBER (5);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

	AuditId := :NEW."Audit";

	-- handle if action done outside of axium	
	IF :OLD."Audit" = :NEW."Audit" THEN
		SELECT AUDITHIS_AUDIT_SEQ.nextval INTO AuditId FROM DUAL;
		
		IF INSERTING THEN
			HistoryType := 1;
		ELSE
			HistoryType := 2;
		END IF;
		
		INSERT INTO AUDITHIS VALUES (
			AuditId,	
			trunc(sysdate),
			trunc(to_char(sysdate,'SSSSS')/60),	
			-1, -- UserId,  B37408
			0, -- StationId
			'CLAIMCAS',
			HistoryType
		);
		
		:NEW."Audit" := AuditId;
	END IF;	
	INSERT INTO CLAIMCAH VALUES (
		CLAIMCAH_ClaimCAH_SEQ.nextval,
		:NEW."ClaimCAS",
		:NEW."ClaimEOB",
		:NEW."Type",
		:NEW."Treatment",
		:NEW."CAReason",
		:NEW."Amount",
		:NEW."Audit",
		:NEW."GroupCode"
	);
END$trigger$
 ;
CREATE TRIGGER createcommenth AFTER INSERT OR UPDATE ON comment2 FOR EACH ROW  $trigger$DECLARE
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

	INSERT INTO COMMENTH VALUES
	(
		COMMENTH_CommentH_SEQ.nextval,
		:NEW."Auto",
		:NEW."Type",
		:NEW."Code",
		:NEW."Description",
		:NEW."SectionNo",
		:NEW."Level",
		:NEW."IsNode",
		:NEW."Deleted",
		:NEW."Heading",
		:NEW."FormCode",
		:NEW."Audit",
		:NEW.RTFDESCRIPTION
	);
END$trigger$
 ;
CREATE TRIGGER createcoverhis AFTER INSERT OR UPDATE ON coverage FOR EACH ROW  $trigger$DECLARE
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  INSERT INTO COVERHIS VALUES (
        COVERHIS_COVERHIS_SEQ.nextval,
		:NEW."Coverage",
		:NEW."Description",
    	:NEW."Audit",
    	:NEW."Order",
    	:NEW."Inactive",
    	:NEW."IsRider" -- E85560
    );
END$trigger$
 ;
CREATE TRIGGER createcovithis AFTER INSERT OR UPDATE ON coverit FOR EACH ROW  $trigger$DECLARE
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  INSERT INTO COVITHIS VALUES (
    COVITHIS_COVITHIS_SEQ.nextval,
	:NEW."Coverage",
	:NEW."Item",
	:NEW."Description",
	:NEW."Category",
	:NEW."FromProcedure",
	:NEW."ToProcedure",
	:NEW."Percent",
	:NEW."Frequency",
	:NEW."FrequencyFlag",
	:NEW."Times",
	:NEW."CoverIt",
	:NEW."HasCatLimit",
	:NEW."CatLimit",
	:NEW."CatPeriod",
	:NEW."CatFrequency",
	:NEW."HasItemLimit",
	:NEW."ItemLimit",
	:NEW."ItemPeriod",
	:NEW."ItemFrequency",
	:NEW."CatDeduct",
	:NEW."CatAffectFamily",
	:NEW."HasCategory",
    	:NEW."Audit",
	:NEW."ItemDeduct",
    	:NEW."ItemAffectFamily",
	:NEW."ItemPtChg",
    	:NEW."LimitOnPatient",
    	:NEW."AgeRules",
    	:NEW."AgeFrom",
    	:NEW."AgeTo",
	:NEW."SiteRules",
	:NEW."CatLimitChildOnly",
	:NEW."HasCatFamilyLimit",
	:NEW."CatFamilyLimit"
     );
END$trigger$
 ;
CREATE TRIGGER createcovsiteh AFTER INSERT OR DELETE ON covsite FOR EACH ROW  $trigger$DECLARE
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

	IF DELETING THEN
		INSERT INTO COVSITEH VALUES (
			COVSITEH_COVSITEH_SEQ.nextval,
			:OLD."CoverIt",
			:OLD."Site",
			:OLD."Audit"
			);
	ELSE
		INSERT INTO COVSITEH VALUES (
			COVSITEH_COVSITEH_SEQ.nextval,
			:NEW."CoverIt",
			:NEW."Site",
			:NEW."Audit"
			);
	END IF;
END$trigger$
 ;
CREATE TRIGGER createemphis AFTER INSERT OR UPDATE ON employer FOR EACH ROW  $trigger$DECLARE
  IdVal 		NUMBER(10);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  SELECT EMPHIS_ID_SEQ.nextval INTO IdVal FROM dual;
  INSERT INTO EMPHIS VALUES (IdVal,
    :NEW."Employer",
    :NEW."Name",
    :NEW."Address1",
    :NEW."Address2",
    :NEW."City",
    :NEW."Province",
    :NEW."Postal",
    :NEW."Area",
    :NEW."Telephone",
    :NEW."Ext",
    :NEW."Note",
    :NEW."AddressOther",
    :NEW."Deleted",
    :NEW."Audit" );
END$trigger$
 ;
CREATE TRIGGER creategraphhis AFTER INSERT OR DELETE OR UPDATE OF "Site", "ModifiedDateTime", "Start", "End", "Color", "Type", "Status", "Surface", "TxId", "FillStyle", "TxPTx" ON graphp2 FOR EACH ROW  $trigger$DECLARE
  GraphHisVal 		NUMBER(10);
  HistoryTypeVal 	NUMBER(5);
  DeleteVal             NUMBER(5);

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  SELECT GRAPHHIS_GRAPHHIS_SEQ.nextval INTO GraphHisVal FROM dual;

  IF INSERTING THEN
    HistoryTypeVal := 1;
    DeleteVal      := 0;
  ELSIF UPDATING THEN
    HistoryTypeVal := 2;
    DeleteVal      := 0;
  ELSIF DELETING THEN
    HistoryTypeVal := 4;
    DeleteVal      := 1;
  END IF;

  IF INSERTING OR UPDATING THEN
     INSERT INTO GRAPHHIS VALUES (GraphHisVal, HistoryTypeVal, DeleteVal,
   	:NEW."Auto",
   	:NEW."PId",
	:NEW."Site",
	:NEW."ModifiedDateTime",
	:NEW."Start",
	:NEW."End",
	:NEW."Color",
	:NEW."Type",
	:NEW."Status",
	:NEW."Surface",
	:NEW."TxId",
	:NEW."FillStyle",
	:NEW."Audit",
	:NEW."TxPTx" );
  ELSIF DELETING THEN
     INSERT INTO GRAPHHIS VALUES (GraphHisVal, HistoryTypeVal, DeleteVal,
   	:OLD."Auto",
   	:OLD."PId",
	:OLD."Site",
	:OLD."ModifiedDateTime",
	:OLD."Start",
	:OLD."End",
	:OLD."Color",
	:OLD."Type",
	:OLD."Status",
	:OLD."Surface",
	:OLD."TxId",
	:OLD."FillStyle",
	:OLD."Audit",
	:OLD."TxPTx" );
  END IF;
END$trigger$
 ;
CREATE TRIGGER createiaccesshis AFTER INSERT OR UPDATE OF "RespiUser", "Deleted", "Audit" ON iaccess FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  INSERT INTO IACCESSH VALUES
  (
	 IACCESSH_IACCESSH_SEQ.nextval,
    :NEW."iUser",
	 :NEW."RespiUser",
    :NEW."Deleted",
    :NEW."Audit"
   );
END$trigger$
 ;
CREATE TRIGGER createidlschh AFTER INSERT OR UPDATE ON idealsch FOR EACH ROW  $trigger$DECLARE
  IdlSchHVal 		NUMBER(10);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  SELECT IDLSCHH_IdlSchH_SEQ.nextval INTO IdlSchHVal FROM dual;
  INSERT INTO IDLSCHH VALUES (IdlSchHVal,
	:NEW."Id",
	:NEW."WschitemId",
	:NEW."StartTime",
	:NEW."EndTime",
	:NEW."Preferred",
	:NEW."Restricted1",
	:NEW."Restricted2",
	:NEW."Restricted3",
	:NEW."Restricted4",
	:NEW."Deleted",
	:NEW."AuditId",
	:NEW."Enforced",
	:NEW."MaxWaitDays",
	:NEW."HoldTime",
	:NEW."ReleaseDays",
	:NEW."ReleaseTime");
END$trigger$
 ;
CREATE TRIGGER createindicath AFTER INSERT OR DELETE OR UPDATE ON indicat FOR EACH ROW  $trigger$DECLARE
  vIndicatH  NUMBER(10):=0;
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  BEGIN
    IF :NEW."Indicat" IS NULL THEN
    INSERT INTO INDICATH ("IndicatH", "Indicat", "Description", "IndicatorType", "FunctionName", "RefreshTime", "PatientBased", "TextColor", "BackgroundColor", "Inactive", "Deleted", "IsIntervention", "ModifiedDate", "DetailFunction", "EventInputData", "RefreshType")
	      VALUES (INDICATH_IndiCatH_SEQ.NEXTVAL, :OLD."Indicat", :OLD."Description", :OLD."IndicatorType", :OLD."FunctionName", :OLD."RefreshTime", :OLD."PatientBased", :OLD."TextColor", :OLD."BackgroundColor", :OLD."Inactive", 1, :OLD."IsIntervention", SYSDATE, :OLD."DetailFunction", :OLD."EventInputData", :OLD."RefreshType");
    ELSE
    INSERT INTO INDICATH ("IndicatH", "Indicat", "Description", "IndicatorType", "FunctionName", "RefreshTime", "PatientBased", "TextColor", "BackgroundColor", "Inactive", "Deleted", "IsIntervention", "ModifiedDate", "DetailFunction", "EventInputData", "RefreshType")
	      VALUES (INDICATH_IndiCatH_SEQ.NEXTVAL, :NEW."Indicat", :NEW."Description", :NEW."IndicatorType", :NEW."FunctionName", :NEW."RefreshTime", :NEW."PatientBased", :NEW."TextColor", :NEW."BackgroundColor", :NEW."Inactive", 0, :NEW."IsIntervention", SYSDATE, :NEW."DetailFunction", :NEW."EventInputData", :NEW."RefreshType");
    END IF;
  END;
END$trigger$
 ;
CREATE TRIGGER createinidef AFTER INSERT ON txquest FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  IF :NEW."Module" = 1 THEN
		INSERT INTO INIDEF VALUES (
			INIDEF_Inidef_SEQ.nextval,
			'EHR',
			'Tx History Options',
			'Ortho Hide List Col'||TO_CHAR(100 + :NEW."TxQuest"),
			0,
			'Hide this Custom Question column in the Ortho Tx History',
			'0 - No,'||CHR(13)||CHR(10)||'1 - Yes',
			'1',
			'EHR Tx History Options',
			'Hide Columns',
			'',
			''
		);
  END IF;
END$trigger$
 ;
CREATE TRIGGER createiniset AFTER INSERT ON station FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  INSERT INTO INISET VALUES (
    INISET_Iniset_SEQ.nextval,
    0,
    SUBSTR(TRIM(:NEW."Terminal"), 1, 50),
    :NEW."StationId"
  );
END$trigger$
 ;
CREATE TRIGGER createiuserhis AFTER INSERT OR UPDATE OF "UserName", "Password", "IsTemp", "IsAgreed", "IsLocked", "Deleted", "PasswordQuestion1", "PasswordAnswer1", "PasswordQuestion2", "PasswordAnswer2", "PasswordQuestion3", "PasswordAnswer3", "PwdLastChanged", "MsgAccess", "IsNoAccess", "LastEmailDateTime", "PersonalInfoCorrect" ON iuser FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  INSERT INTO IUSERH VALUES
  (
		IUSERH_IUSERH_SEQ.nextval,
		:NEW."iUser",
		:NEW."Type",
		:NEW."Id",
		:NEW."UserName",
		:NEW."Password",
		:NEW."IsTemp",
		:NEW."IsAgreed",
		:NEW."IsLocked",
		:NEW."Audit",
		:NEW."Deleted",
		:NEW."PasswordQuestion1",
		:NEW."PasswordAnswer1",
		:NEW."PasswordQuestion2",
		:NEW."PasswordAnswer2",
		:NEW."PasswordQuestion3",
		:NEW."PasswordAnswer3",
		:NEW."FailedPWAttemptCount",
		:NEW."FailedPWAttemptDate",
		:NEW."FailedPWAttemptTime",
		:NEW."PwdLastChanged",
		:NEW."MsgAccess",
		:NEW."LastAccessDateTime",
		:NEW."IsNoAccess",	-- E136724
		:NEW."LastEmailDateTime",	-- AX-25371.5, AX-25373.5
		:NEW."PersonalInfoCorrect" -- AX-29988
   );
END$trigger$
 ;
CREATE TRIGGER createlabitemh AFTER INSERT OR UPDATE OF "LabOrder", "Item", "Provider", "Date", "Redo", "RedoItem", "ApprovalUser", "ApprovalDate", "ExpectedDate", "DateChanged", "LabOut", "DateOut", "TimeOut", "OutUser", "DateIn", "TimeIn", "User", "Deleted", "LabCode", "Audit" ON labitem FOR EACH ROW  $trigger$DECLARE
	vHisView NUMBER(5);
	vCount NUMBER;
  vAudit NUMBER(10);
  vLabItemH NUMBER(10);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;



vHisView := 0;
vAudit := :NEW."Audit";

IF INSERTING OR (:NEW."ApprovalUser" <> :OLD."ApprovalUser" OR :NEW."ApprovalDate" <> :OLD."ApprovalDate" OR :NEW."Deleted" <> :OLD."Deleted") THEN
	vHisView := 1;
END IF;

SELECT LABITEMH_LABITEMH_SEQ.nextval INTO vLabItemH from dual;

INSERT INTO LABITEMH VALUES
(
     vLabItemH,
      :NEW."LabOrder",
      :NEW."Item",
      :NEW."Provider",
      :NEW."Date",
      :NEW."Text",
      :NEW."Comment",
      :NEW."Redo",
      :NEW."RedoItem",
      :NEW."ApprovalUser",
      :NEW."ApprovalDate",
      :NEW."ExpectedDate",
      :NEW."DateChanged",
      :NEW."LabOut",
      :NEW."DateOut",
      :NEW."TimeOut",
      :NEW."OutUser",
      :NEW."DateIn",
      :NEW."TimeIn",
      :NEW."User",
      :NEW."Deleted",
      vAudit,
      :NEW."LabCode"               -- E123616
);

CreateLabOrdH (vLabItemH, vHisView, :NEW."LabOrder", vAudit);

END$trigger$
 ;
CREATE TRIGGER createlabordh AFTER INSERT OR UPDATE OF "LabOrder", "CaseNo", "Patient", "LabProcedure", "Discipline", "Date", "RemakeStudent", "RemakeStaff", "RemakeLabOrder", "WaiveCharges", "LabOut", "LabCode", "DateOut", "TimeOut", "User", "Deleted", "CurrentItem", "Status", "CompletionDate", "TotalCost", "TotalCharge", "IsOrtho", "OrigRecNo", "Audit", "IseLab" ON laborder FOR EACH ROW  $trigger$DECLARE
	vHisView NUMBER(5);
	vCount NUMBER;	
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;



vHisView := 0;

IF INSERTING OR (:NEW."Status" <> :OLD."Status" OR :NEW."LabOut" <> :OLD."LabOut" OR :NEW."CurrentItem" <> :OLD."CurrentItem" OR :NEW."Deleted" <> :OLD."Deleted") THEN
	vHisView := 1;
END IF;

SELECT COUNT(1) into vCount FROM LABORDH WHERE "LabOrder" = :NEW."LabOrder" AND "Audit" = :NEW."Audit";

IF (vCount = 0) THEN
	insert into LABORDH values
	    (
	      LABORDH_LABORDH_SEQ.nextval,
	      0,
	      vHisView,
	      :NEW."LabOrder",
	      :NEW."CaseNo",
	      :NEW."Patient",
	      :NEW."LabProcedure",
	      :NEW."Discipline",
	      :NEW."Date",
	      :NEW."RemakeStudent",
	      :NEW."RemakeStaff",
	      :NEW."RemakeLabOrder",
	      :NEW."WaiveCharges",
	      :NEW."LabOut",
	      :NEW."LabCode",
	      :NEW."DateOut",
	      :NEW."TimeOut",
	      :NEW."User",
	      :NEW."Deleted",
	      :NEW."CurrentItem",
	      :NEW."Status",
	      :NEW."CompletionDate",
	      :NEW."TotalCost",
	      :NEW."TotalCharge",
	      :NEW."IsOrtho",
	      :NEW."OrigRecNo",
	      :NEW."Audit",
		  :NEW."IseLab"
    );
  END IF;

END$trigger$
 ;
CREATE TRIGGER createlabotrxh AFTER INSERT OR UPDATE OF "LabOrder", "OrigRecNo", "Deleted" ON labotrx FOR EACH ROW  $trigger$DECLARE
	vHisView NUMBER(5);
  vAudit NUMBER(10);
  vLabOTrxH NUMBER(10);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;



vHisView := 0;
vAudit := :NEW."Audit";

SELECT LABOTRXH_LABOTRXH_SEQ.nextval INTO vLabOTrxH from dual;

INSERT INTO LABOTRXH VALUES
(
  vLabOTrxH,
  :NEW."LabOrder",
  :NEW."OrigRecNo",
  :NEW."Deleted",
  vAudit
);

CreateLabOrdH (0, vHisView, :NEW."LabOrder", vAudit);

END$trigger$
 ;
CREATE TRIGGER createlabsith AFTER INSERT OR UPDATE OF "LabSItem", "LabOrder", "Item", "Description", "Deleted" ON labsitem FOR EACH ROW  $trigger$DECLARE
	vHisView NUMBER(5);
  vAudit NUMBER(10);
  vLabSItH NUMBER(10);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


vHisView := 0;
vAudit := :NEW."Audit";


SELECT LABSITH_LABSITH_SEQ.nextval INTO vLabSItH from dual;

INSERT INTO LABSITH VALUES
(
    vLabSItH,
    :NEW."LabSItem",
    :NEW."LabOrder",
    :NEW."Item",
    :NEW."Description",
    :NEW."Deleted",
    vAudit
);


CreateLabOrdH (0, vHisView, :NEW."LabOrder", vAudit);

END$trigger$
 ;
CREATE TRIGGER createlinkinidef AFTER INSERT ON linkdef FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

	INSERT INTO INIDEF VALUES (
		INIDEF_Inidef_SEQ.nextval,
		'Other',
		'Links',
		'Link'||TO_CHAR(:NEW."LinkDef")||'Flag',
		0,
		'Hide or show this link in the program' || CHR(13) || CHR(10) || :NEW."Name" || CHR(13) || CHR(10) || substr(:NEW."Execute", 1, 2000),
		'0 - Hide,' || CHR(13) || CHR(10) || '1 - Show',
		'1',
		'Set Manually',
		'',
		'',
		''
	);
	
	INSERT INTO INIDEF VALUES (
		INIDEF_Inidef_SEQ.nextval,
		'Other',
		'Links',
		'Link'||TO_CHAR(:NEW."LinkDef")||'Path',
		1,
		'Override path for this link' || CHR(13) || CHR(10) || :NEW."Name" || CHR(13) || CHR(10) || substr(:NEW."Execute", 1, 2000),
		'',
		'',
		'',
		'',
		'',
		''
	);
END$trigger$
 ;
CREATE TRIGGER createneedreqhis AFTER INSERT OR UPDATE ON needreq FOR EACH ROW  $trigger$DECLARE
  NeedReqHisVal 	NUMBER(10);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  SELECT NEEDREQH_NEEDREQH_SEQ.nextval INTO NeedReqHisVal FROM dual;
  INSERT INTO NEEDREQH VALUES (NeedReqHisVal,
	   :NEW."NeedReq",
      :NEW."Provider",
      :NEW."Date",
      :NEW."Time",
      :NEW."Type",
      :NEW."NeedCode",
      :NEW."Procedure",
      :NEW."PatType",
      :NEW."Note",
      :NEW."Assigned",
      :NEW."AssignedDate",
	   :NEW."PtProdId",
	   :NEW."Deleted",
	   :NEW."AuditId");
END$trigger$
 ;
CREATE TRIGGER createonline_commenthis AFTER INSERT OR UPDATE OF "Date", "Comment", "Deleted", "Audit", "IsContactNote", "Time", "EntryUser" ON online_comment FOR EACH ROW  $trigger$DECLARE
  CommentHisId NUMBER(10);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

SELECT ONLINE_COMMENTHIS_Id_SEQ.nextval INTO CommentHisId
 from dual;
INSERT INTO ONLINE_COMMENTHIS VALUES (CommentHisId,
 :NEW."Id",
 :NEW."RequestId",
 :NEW."Date",
 :NEW."Comment",
 :NEW."Deleted",
 :NEW."Audit",
 :NEW."IsContactNote",			--AX-28483										
 :NEW."Time",				--AX-28483c
 :NEW."EntryUser");				--AX-28483c
END$trigger$
 ;
CREATE TRIGGER createonline_reqevent AFTER INSERT ON online_request FOR EACH ROW  $trigger$DECLARE
  EventId NUMBER(10);
  Event NUMBER(10);
  AuditId NUMBER(10);
  Details VARCHAR2(255 );
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

SELECT ONLINE_REQEVENT_Id_SEQ.nextval INTO EventId
 	from dual;
 Event := 1;             -- ONLINEREQ_ADD

 Details := 'Add Online Request:' || CHR(13) || CHR(10);
 Details := Details || 'Treatment Reason - ' || :NEW."Reason";

 SELECT AUDITHIS_AUDIT_SEQ.nextval INTO AuditId FROM DUAL;
 		
INSERT INTO AUDITHIS VALUES (
	AuditId,	
	trunc(sysdate),
	trunc(to_char(sysdate,'SSSSS')/60),	
	-1, -- UserId,
	0, -- StationId
	'ONLINE_R',
	0
);

INSERT INTO ONLINE_REQEVENT VALUES (EventId,
 :NEW."Id",
 Event,
 Details,
 AuditId);
END$trigger$
 ;
CREATE TRIGGER createpathis AFTER INSERT OR UPDATE OF "Family", "Last", "First", "Prefered", "Middle", "Title", "Birth", "Address1", "Address2", "City", "Province", "Postal", "HomeArea", "HomePhone", "WorkArea", "WorkPhone", "WorkExt", "OtherArea", "OtherPhone", "OtherExt", "ContactAt", "ContactTime", "Status", "Sex", "Marital", "IsPatient", "IsStudent", "IsHandicaped", "Chart", "Sin", "Office1", "Office2", "Office3", "Office4", "Office5", "Alert1", "Alert2", "Alert3", "Alert4", "Alert5", "Open", "Close", "Path", "School", "Health", "AccountStatus", "Assignment", "Statements", "IsFreeAccess", "Fee", "OtherLocation", "NoLocks", "CustomCode1", "CustomCode2", "CustomCode3", "CustomCode4", "CustomCode5", "CustomCode6", "CustomCode7", "CustomCode8", "CustomCode9", "CustomCode10", "Physician", "EmergLast", "EmergFirst", "EmergMiddle", "EmergAddress", "EmergAddress2", "EmergAddressOther", "EmergCity", "EmergProvince", "EmergPostal", "EmergArea", "EmergPhone", "EmergAltArea", "EmergAltPhone", "EmergRelation", "IsChartFixed", "IsOrtho", "OrthoSet", "AltChart", "AddressOther", "BankAccount", "EDIFlag", "StatusEndDate", "IsEmergency", "ActiveDate", "PartnerName", "BoxNumber", "Email", "ChartSort", "PartnerPrefix", "PrefApptTime", "XRayReceived", "DateXRayExpected", "DateXRayReceived", "Country", "XRayExposures", "MergedChart", "Deleted", "ChartSuffix", "ReleaseOnFile", "Audit", "EmergExt", "EmergAltExt", "FeeOverride", "DiscGrp", "RequireTxConsent", "PaperChart", "InfoNotify", "TaxExempt", "RecallDoctorToUse", "RecallHygToUse", "CustomText1", "CustomText2", "CustomText3", "CustomText4", "CustomText5", "MobileArea", "MobilePhone", "ApptFeesExempt", "PrefLanguage", "RaceEthDeclined", "Ethnic", "IsTrustedAudit", "SecondIDType", "SecondIDNumber", "Is2ndIdTrustedAudit", "HasExternalLink", "HasCarequality" ON patient FOR EACH ROW  $trigger$DECLARE
  IdVal 				NUMBER (10);
  UserAddedFlag	NUMBER (5);
  PtStatusFlag		NUMBER (5);
  PtNameFlag		NUMBER (5);
  PtAddressFlag 	NUMBER (5);
  PtOfficeFlag		NUMBER (5);
  PtAlertFlag		NUMBER (5);
  PtCustom1Flag 	NUMBER (5);
  PtCustom2Flag 	NUMBER (5);
  PtCustom3Flag 	NUMBER (5);
  PtCustom4Flag 	NUMBER (5);
  PtCustom5Flag 	NUMBER (5);
  PtCustom6Flag 	NUMBER (5);
  PtCustom7Flag 	NUMBER (5);
  PtCustom8Flag 	NUMBER (5);
  PtCustom9Flag 	NUMBER (5);
  PtCustom10Flag 	NUMBER (5);
  PtChartFlag		NUMBER (5);
  PtAddFlag			NUMBER (5);
  PtDeleteFlag  	NUMBER (5);
  PtCustom1TextFlag 	NUMBER (5);
  PtCustom2TextFlag 	NUMBER (5);
  PtCustom3TextFlag 	NUMBER (5);
  PtCustom4TextFlag 	NUMBER (5);
  PtCustom5TextFlag 	NUMBER (5);

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  IF (:NEW."Patient" = :NEW."Family") THEN

   SELECT PATHIS_ID_SEQ.nextval INTO IdVal FROM dual;

-- set change flags
   UserAddedFlag  := 0;
   PtStatusFlag   := 0;
   PtNameFlag     := 0;
   PtAddressFlag  := 0;
   PtOfficeFlag   := 0;
   PtAlertFlag    := 0;
   PtCustom1Flag  := 0;
   PtCustom2Flag  := 0;
   PtCustom3Flag  := 0;
   PtCustom4Flag  := 0;
   PtCustom5Flag  := 0;
   PtCustom6Flag  := 0;
   PtCustom7Flag  := 0;
   PtCustom8Flag  := 0;
   PtCustom9Flag  := 0;
   PtCustom10Flag := 0;
   PtChartFlag    := 0;
   PtAddFlag      := 0;
   PtDeleteFlag   := 0;

-- B77211 change flags
	PtCustom1TextFlag	:= 0;
	PtCustom2TextFlag	:= 0;
	PtCustom3TextFlag	:= 0;
	PtCustom4TextFlag	:= 0;
	PtCustom5TextFlag	:= 0;

   IF :OLD."Status" <> :NEW."Status" THEN
	PtStatusFlag := 1;
   END IF;

   IF :OLD."Last" <> :NEW."Last"
   OR :OLD."First" <> :NEW."First"
   OR :OLD."Middle" <> :NEW."Middle"
   OR :OLD."Prefered" <> :NEW."Prefered"
   OR :OLD."Title" <> :NEW."Title"
   THEN
	PtNameFlag := 1;
   END IF;

   IF :OLD."Address1" <> :NEW."Address1"
   OR :OLD."Address2" <> :NEW."Address2"
   OR :OLD."City" <> :NEW."City"
   OR :OLD."Province" <> :NEW."Province"
   OR :OLD."Postal" <> :NEW."Postal"
   OR :OLD."HomeArea" <> :NEW."HomeArea"
   OR :OLD."HomePhone" <> :NEW."HomePhone"
   OR :OLD."WorkArea" <> :NEW."WorkArea"
   OR :OLD."WorkPhone" <> :NEW."WorkPhone"
   OR :OLD."WorkExt" <> :NEW."WorkExt"
   OR :OLD."MobileArea" <> :NEW."MobileArea"										-- E99403
   OR :OLD."MobilePhone" <> :NEW."MobilePhone"									-- E99403
   OR :OLD."OtherArea" <> :NEW."OtherArea"
   OR :OLD."OtherPhone" <> :NEW."OtherPhone"
   OR :OLD."OtherExt" <> :NEW."OtherExt"
   OR :OLD."OtherLocation" <> :NEW."OtherLocation"
   OR :OLD."AddressOther" <> :NEW."AddressOther"
   THEN
	PtAddressFlag := 1;
   END IF;

   IF :OLD."Chart" <> :NEW."Chart" THEN
	PtChartFlag := 1;
   END IF;

   IF :OLD."Office1" <> :NEW."Office1"
   OR (:OLD."Office1" IS NULL AND :NEW."Office1" IS NOT NULL AND :NEW."Office1" <> ' ')
   OR :OLD."Office2" <> :NEW."Office2"
   OR (:OLD."Office2" IS NULL AND :NEW."Office2" IS NOT NULL AND :NEW."Office2" <> ' ')
   OR :OLD."Office3" <> :NEW."Office3"
   OR (:OLD."Office3" IS NULL AND :NEW."Office3" IS NOT NULL AND :NEW."Office3" <> ' ')
   OR :OLD."Office4" <> :NEW."Office4"
   OR (:OLD."Office4" IS NULL AND :NEW."Office4" IS NOT NULL AND :NEW."Office4" <> ' ')
   OR :OLD."Office5" <> :NEW."Office5"
   OR (:OLD."Office5" IS NULL AND :NEW."Office5" IS NOT NULL AND :NEW."Office5" <> ' ')
   THEN
	PtOfficeFlag := 1;
   END IF;

   IF :OLD."Alert1" <> :NEW."Alert1"
   OR (:OLD."Alert1" IS NULL AND :NEW."Alert1" IS NOT NULL AND :NEW."Alert1" <> ' ')
   OR :OLD."Alert2" <> :NEW."Alert2"
   OR (:OLD."Alert2" IS NULL AND :NEW."Alert2" IS NOT NULL AND :NEW."Alert2" <> ' ')
   OR :OLD."Alert3" <> :NEW."Alert3"
   OR (:OLD."Alert3" IS NULL AND :NEW."Alert3" IS NOT NULL AND :NEW."Alert3" <> ' ')
   OR :OLD."Alert4" <> :NEW."Alert4"
   OR (:OLD."Alert4" IS NULL AND :NEW."Alert4" IS NOT NULL AND :NEW."Alert4" <> ' ')
   OR :OLD."Alert5" <> :NEW."Alert5"
   OR (:OLD."Alert5" IS NULL AND :NEW."Alert5" IS NOT NULL AND :NEW."Alert5" <> ' ')
   THEN
	PtAlertFlag := 1;
   END IF;

   IF :OLD."CustomCode1" <> :NEW."CustomCode1"
   OR (:OLD."CustomCode1" IS NULL AND :NEW."CustomCode1" IS NOT NULL AND :NEW."CustomCode1" <> ' ')
   THEN
	PtCustom1Flag := 1;
   END IF;

   IF :OLD."CustomCode2" <> :NEW."CustomCode2"
   OR (:OLD."CustomCode2" IS NULL AND :NEW."CustomCode2" IS NOT NULL AND :NEW."CustomCode2" <> ' ')
   THEN
	PtCustom2Flag := 1;
   END IF;

   IF :OLD."CustomCode3" <> :NEW."CustomCode3"
   OR (:OLD."CustomCode3" IS NULL AND :NEW."CustomCode3" IS NOT NULL AND :NEW."CustomCode3" <> ' ')
   THEN
	PtCustom3Flag := 1;
   END IF;

   IF :OLD."CustomCode4" <> :NEW."CustomCode4"
   OR (:OLD."CustomCode4" IS NULL AND :NEW."CustomCode4" IS NOT NULL AND :NEW."CustomCode4" <> ' ')
   THEN
	PtCustom4Flag := 1;
   END IF;

   IF :OLD."CustomCode5" <> :NEW."CustomCode5"
   OR (:OLD."CustomCode5" IS NULL AND :NEW."CustomCode5" IS NOT NULL AND :NEW."CustomCode5" <> ' ')
   THEN
	PtCustom5Flag := 1;
   END IF;

   IF :OLD."CustomCode6" <> :NEW."CustomCode6"
   OR (:OLD."CustomCode6" IS NULL AND :NEW."CustomCode6" IS NOT NULL AND :NEW."CustomCode6" <> ' ')
   THEN
	PtCustom6Flag := 1;
   END IF;

   IF :OLD."CustomCode7" <> :NEW."CustomCode7"
   OR (:OLD."CustomCode7" IS NULL AND :NEW."CustomCode7" IS NOT NULL AND :NEW."CustomCode7" <> ' ')
   THEN
	PtCustom7Flag := 1;
   END IF;

   IF :OLD."CustomCode8" <> :NEW."CustomCode8"
   OR (:OLD."CustomCode8" IS NULL AND :NEW."CustomCode8" IS NOT NULL AND :NEW."CustomCode8" <> ' ')
   THEN
	PtCustom8Flag := 1;
   END IF;

   IF :OLD."CustomCode9" <> :NEW."CustomCode9"
   OR (:OLD."CustomCode9" IS NULL AND :NEW."CustomCode9" IS NOT NULL AND :NEW."CustomCode9" <> ' ')
   THEN
	PtCustom9Flag := 1;
   END IF;

   IF :OLD."CustomCode10" <> :NEW."CustomCode10"
   OR (:OLD."CustomCode10" IS NULL AND :NEW."CustomCode10" IS NOT NULL AND :NEW."CustomCode10" <> ' ')
   THEN
	PtCustom10Flag := 1;
   END IF;

   -- B77211
   IF :OLD."CustomText1" <> :NEW."CustomText1"
   OR (:OLD."CustomText1" IS NULL AND :NEW."CustomText1" IS NOT NULL AND :NEW."CustomText1" <> ' ')
   THEN
	PtCustom1TextFlag := 1;
   END IF;
   IF :OLD."CustomText2" <> :NEW."CustomText2"
   OR (:OLD."CustomText2" IS NULL AND :NEW."CustomText2" IS NOT NULL AND :NEW."CustomText2" <> ' ')
   THEN
	PtCustom2TextFlag := 1;
   END IF;
   IF :OLD."CustomText3" <> :NEW."CustomText3"
   OR (:OLD."CustomText3" IS NULL AND :NEW."CustomText3" IS NOT NULL AND :NEW."CustomText3" <> ' ')
   THEN
	PtCustom3TextFlag := 1;
   END IF;
   IF :OLD."CustomText4" <> :NEW."CustomText4"
   OR (:OLD."CustomText4" IS NULL AND :NEW."CustomText4" IS NOT NULL AND :NEW."CustomText4" <> ' ')
   THEN
	PtCustom4TextFlag := 1;
   END IF;
   IF :OLD."CustomText5" <> :NEW."CustomText5"
   OR (:OLD."CustomText5" IS NULL AND :NEW."CustomText5" IS NOT NULL AND :NEW."CustomText5" <> ' ')
   THEN
	PtCustom5TextFlag := 1;
   END IF;

   INSERT INTO PATHIS VALUES (
		IdVal,
		UserAddedFlag,
		PtStatusFlag,
		PtNameFlag,
		PtAddressFlag,
		PtOfficeFlag,
		PtAlertFlag,
		PtCustom1Flag,
		PtCustom2Flag,
		PtCustom3Flag,
		PtCustom4Flag,
		PtCustom5Flag,
		PtCustom6Flag,
		PtCustom7Flag,
		PtCustom8Flag,
		PtCustom9Flag,
		PtCustom10Flag,
		PtChartFlag,
		PtAddFlag,
		PtDeleteFlag,
		:NEW."Patient",
		:NEW."Family",
		:NEW."Last",
		:NEW."First",
		:NEW."Prefered",
		:NEW."Middle",
		:NEW."Title",
		:NEW."Birth",
		:NEW."Address1",
		:NEW."Address2",
		:NEW."City",
		:NEW."Province",
		:NEW."Postal",
		:NEW."HomeArea",
		:NEW."HomePhone",
		:NEW."WorkArea",
		:NEW."WorkPhone",
		:NEW."WorkExt",
		:NEW."OtherArea",
		:NEW."OtherPhone",
		:NEW."OtherExt",
		:NEW."ContactAt",
		:NEW."ContactTime",
		:NEW."Status",
		:NEW."Sex",
		:NEW."Marital",
		:NEW."IsPatient",
		:NEW."IsStudent",
		:NEW."IsHandicaped",
		:NEW."Chart",
		:NEW."Sin",
		:NEW."Office1",
		:NEW."Office2",
		:NEW."Office3",
		:NEW."Office4",
		:NEW."Office5",
		:NEW."Alert1",
		:NEW."Alert2",
		:NEW."Alert3",
		:NEW."Alert4",
		:NEW."Alert5",
		:NEW."Open",
		:NEW."Close",
		:NEW."Path",
		:NEW."School",
		:NEW."Health",
		:NEW."AccountStatus",
		:NEW."Assignment",
		:NEW."Statements",
		:NEW."IsFreeAccess",
		:NEW."Fee",
		:NEW."OtherLocation",
		:NEW."NoLocks",
		:NEW."CustomCode1",
		:NEW."CustomCode2",
		:NEW."CustomCode3",
		:NEW."CustomCode4",
		:NEW."CustomCode5",
		:NEW."CustomCode6",
		:NEW."CustomCode7",
		:NEW."CustomCode8",
		:NEW."CustomCode9",
		:NEW."CustomCode10",
		:NEW."Physician",
		:NEW."EmergLast",
		:NEW."EmergFirst",
		:NEW."EmergMiddle",
		:NEW."EmergAddress",
		:NEW."EmergAddress2",
		:NEW."EmergAddressOther",
		:NEW."EmergCity",
		:NEW."EmergProvince",
		:NEW."EmergPostal",
		:NEW."EmergArea",
		:NEW."EmergPhone",
		:NEW."EmergAltArea",
		:NEW."EmergAltPhone",
		:NEW."EmergRelation",
		:NEW."IsChartFixed",
		:NEW."IsOrtho",
		:NEW."OrthoSet",
		:NEW."AltChart",
		:NEW."AddressOther",
		:NEW."BankAccount",
		:NEW."EDIFlag",
		:NEW."StatusEndDate",
		:NEW."IsEmergency",
		:NEW."ActiveDate",
		:NEW."PartnerName",
		:NEW."BoxNumber",
		:NEW."Email",
		:NEW."ChartSort",
		:NEW."PartnerPrefix",
		:NEW."PrefApptTime",
		:NEW."XRayReceived",
		:NEW."DateXRayExpected",
		:NEW."DateXRayReceived",
		:NEW."Country",
		:NEW."XRayExposures",
		:NEW."MergedChart",
		:NEW."Deleted",
		:NEW."Audit",
		:NEW."ChartSuffix",
		:NEW."ReleaseOnFile",
		:NEW."EmergExt",
		:NEW."EmergAltExt",
		:NEW."FeeOverride",															-- E33838
		:NEW."DiscGrp",																-- E44293
		:NEW."RequireTxConsent",													-- E54824
		:NEW."PaperChart",															-- E55356
		:NEW."InfoNotify",															-- E37209
		:NEW."TaxExempt",																-- E72766
		:NEW."RecallDoctorToUse",													-- E73070.1
		:NEW."RecallHygToUse",														-- E73070.1
		:NEW."CustomText1",															-- E73405
		:NEW."CustomText2",															-- E73405
		:NEW."CustomText3",															-- E73405
		:NEW."CustomText4",															-- E73405
		:NEW."CustomText5",															-- E73405
		PtCustom1TextFlag,															-- B77211
		PtCustom2TextFlag,															-- B77211
		PtCustom3TextFlag,															-- B77211
		PtCustom4TextFlag,															-- B77211
		PtCustom5TextFlag,															-- B77211
		:NEW."MobileArea",															-- E99403
		:NEW."MobilePhone",															-- E99403
    :NEW."ApptFeesExempt",
    :NEW."PrefLanguage",															-- E135945
    :NEW."RaceEthDeclined",														-- E135943
		:NEW."Ethnic",																	-- E135943
    :NEW."IsTrustedAudit",															--AX-4546
    :NEW."SecondIDType",															--AX-4546
    :NEW."SecondIDNumber",
    :NEW."Is2ndIdTrustedAudit",															--AX-4546
	:NEW."HasExternalLink",																-- AX-23598
	:NEW."HasCarequality"																-- AX-26972
	);
  END IF;
END$trigger$
 ;
CREATE TRIGGER createpercdhis AFTER INSERT OR UPDATE OF "Order", "Color", "Chart", "Deleted", "SiteRestricted" ON percodis FOR EACH ROW  $trigger$DECLARE
  IdVal 		NUMBER(10);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  SELECT PERCDHIS_PERCDHIS_SEQ.nextval INTO IdVal FROM dual;
  INSERT INTO PERCDHIS VALUES (IdVal,
    :NEW."PerCondDis",
    :NEW."ProdType",
    :NEW."Provider",
    :NEW."PerCond",
    :NEW."Section",
    :NEW."Order",
    :NEW."Color",
    :NEW."Chart",
    :NEW."Deleted",
    :NEW."Audit",
    :NEW."SiteRestricted" );
END$trigger$
 ;
CREATE TRIGGER createpercohis AFTER INSERT OR UPDATE OF "PerCond", "Description", "ShortDesc", "AnsType", "Color", "DisplayType", "ChartType", "ChartMissing", "CondType", "Status" ON percond FOR EACH ROW  $trigger$DECLARE
  IdVal 		NUMBER(10);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  SELECT PERCOHIS_PERCOHIS_SEQ.nextval INTO IdVal FROM dual;
  INSERT INTO PERCOHIS VALUES (IdVal,
    :NEW."PerCond",
    :NEW."Description",
    :NEW."ShortDesc",
    :NEW."AnsType",
    :NEW."Color",
    :NEW."DisplayType",
    :NEW."ChartType",
    :NEW."ChartMissing",
    :NEW."CondType",
    :NEW."Status",
    :NEW."Audit" );
END$trigger$
 ;
CREATE TRIGGER createpersdhis AFTER INSERT OR UPDATE OF "PerSummDis", "ProdType", "Provider", "PerSumm", "Order", "Deleted" ON persudis FOR EACH ROW  $trigger$DECLARE
  IdVal 		NUMBER(10);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  SELECT PERSDHIS_PERSDHIS_SEQ.nextval INTO IdVal FROM dual;
  INSERT INTO PERSDHIS VALUES (IdVal,
    :NEW."PerSummDis",
    :NEW."ProdType",
    :NEW."Provider",
    :NEW."PerSumm",
    :NEW."Order",
    :NEW."Deleted",
    :NEW."Audit" );
END$trigger$
 ;
CREATE TRIGGER createphyshis AFTER INSERT OR UPDATE ON physicia FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  INSERT INTO PHYSHIS VALUES (PHYSHIS_ID_SEQ.nextval,
    :NEW."Physician",
    :NEW."Last",
    :NEW."First",
    :NEW."Address1",
    :NEW."Address2",
    :NEW."City",
    :NEW."Province",
    :NEW."Postal",
    :NEW."Area",
    :NEW."Phone",
    :NEW."Comment",
    :NEW."Middle",
    :NEW."AddressOther",
    :NEW."FaxArea",
    :NEW."FaxPhone",
    :NEW."Deleted",
    :NEW."Audit",
    :NEW."Extension",
    :NEW."PhysType",
    :NEW."Email" -- E132479
     );
END$trigger$
 ;
CREATE TRIGGER createpinvoich AFTER INSERT OR UPDATE OF "InvoiceNumber", "InvHold", "InvHoldAudit", "InvLetter1Audit", "InvLetter2Audit", "InvLetter3Audit", "Refund" ON pinvoice FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


	IF NOT (TRIM(:NEW."InvoiceNumber") IS NULL OR LENGTH(TRIM(:NEW."InvoiceNumber")) = 0) THEN
		INSERT INTO PINVOICH VALUES (
			PINVOICH_PINVOICH_SEQ.nextval,
			:NEW."PInvoice",
			:NEW."Patient",
			:NEW."InvoiceNumber",
			:NEW."Total",
			:NEW."InsTotal",
			:NEW."InsTransfer",
			:NEW."PtAdj",
			:NEW."Payed",
			:NEW."Audit",
			:NEW."PrintStatus",
			:NEW."Bank",
			:NEW."InvoiceDate",
			:NEW."InvHold",
			:NEW."InvHoldAudit",
			:NEW."PmtDueDate",
			:NEW."InvLetter1Audit",
			:NEW."InvLetter2Audit",
			:NEW."InvLetter3Audit",
			:NEW."Refund"
			);
	END IF;
END$trigger$
 ;
CREATE TRIGGER createplanfhis AFTER INSERT OR UPDATE OF "Type", "Date", "Amount", "TrxId", "TrxTreatment", "Procedure", "InsAmount", "Audit", "ClaimFlag", "CustomaryAmount" ON planfee FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  INSERT INTO PLANFHIS VALUES (PLANFHIS_PlanFHis_SEQ.nextval,
    :NEW."PlanId",
    :NEW."PlanItem",
    :NEW."Type",
    :NEW."Date",
    :NEW."Amount",
    :NEW."TrxId",
    :NEW."TrxTreatment",
    :NEW."Procedure",
    :NEW."InsAmount",
    :NEW."ClaimDate",
    :NEW."ClaimCreated",
    :NEW."Audit",
    :NEW."ClaimFlag",
    :NEW."CustomaryAmount" );
END$trigger$
 ;
CREATE TRIGGER createplanhis AFTER INSERT OR UPDATE OF "Type", "Total", "InitialFee", "InitialDate", "Period", "RegularStart", "RegularFee", "RegularCount", "FinalFee", "FinalDate", "Comment", "Status", "Contract", "VisitLimit", "RegularSch" ON payplan FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  INSERT INTO PLANHIS VALUES (PLANHIS_PlanHis_SEQ.nextval,
    :NEW."PlanId",
    :NEW."Patient",
    :NEW."Family",
    :NEW."Type",
    :NEW."Total",
    :NEW."InitialFee",
    :NEW."InitialDate",
    :NEW."Period",
    :NEW."RegularStart",
    :NEW."RegularFee",
    :NEW."RegularCount",
    :NEW."FinalFee",
    :NEW."FinalDate",
    :NEW."Comment",
    :NEW."Status",
    :NEW."ClosingBalance",
    :NEW."RespId",
    :NEW."CreationDate",
    :NEW."Contract",
    :NEW."Audit",
    :NEW."VisitLimit",
    :NEW."RegularSch" );
END$trigger$
 ;
CREATE TRIGGER createpolinsh AFTER INSERT OR UPDATE OF "Group", "Division", "FormsTo", "Company", "GovPolicy", "Fee", "Employer", "HasFamilyLimit", "FamilyDeduct", "FamilyLimit", "HasPatientLimit", "PatientDeduct", "PatientLimit", "YearEnd", "Assignment", "Signature", "ChangeDate", "CvgPct", "WriteOff", "Deleted", "PlanType", "MonthlyDeduct", "TrojanId", "YearEndDay", "ChildCoverage", "AdultCoverage", "Copay", "Description", "SharablePlan", "StartDate", "EndDate", "VisitFee", "CoverageAge", "CoverageAgeStud", "EDIFlag", "CoverageAgeYoungAdult", "YoungAdultCoverage", "CvgOnBirthChild", "CvgOnBirthStudent", "CvgOnBirthYoungAdult", "ChargeDedAndPtChg" ON polins FOR EACH ROW  $trigger$DECLARE
  PolInsHVal 		NUMBER(10);
  HistoryTypeVal 	NUMBER(5);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  SELECT POLINSH_POLINSH_SEQ.nextval INTO PolInsHVal FROM dual;
  IF INSERTING THEN
    HistoryTypeVal := 1;
  ELSIF UPDATING THEN
    IF :NEW."Deleted" = 0 THEN
      HistoryTypeVal := 2;
    ELSE
      HistoryTypeVal := 4;
    END IF;
  END IF;
  INSERT INTO POLINSH VALUES (PolInsHVal, HistoryTypeVal,
   	:NEW."PolIns",
	:NEW."Group",
	:NEW."Division",
	:NEW."FormsTo",
	:NEW."Company",
	:NEW."GovPolicy",
	:NEW."Fee",
	:NEW."Employer",
	:NEW."HasFamilyLimit",
	:NEW."FamilyDeduct",
	:NEW."FamilyLimit",
	:NEW."HasPatientLimit",
	:NEW."PatientDeduct",
	:NEW."PatientLimit",
	:NEW."YearEnd",
	:NEW."Assignment",
	:NEW."Signature",
	:NEW."ChangeDate",
	:NEW."CvgPct",
	:NEW."WriteOff",
	:NEW."Deleted",
	:NEW."PlanType",
	:NEW."MonthlyDeduct",
	:NEW."Date",
	:NEW."Time",
	:NEW."User",
	:NEW."StationId",
	:NEW."TrojanId",
	:NEW."YearEndDay",
    :NEW."ChildCoverage",
    :NEW."AdultCoverage",
    :NEW."Copay",
    :NEW."SharedEntryId",
    :NEW."Description",
    :NEW."SharablePlan",
    :NEW."StartDate",
    :NEW."EndDate",
    :NEW."VisitFee",
    :NEW."CoverageAge",
    :NEW."CoverageAgeStud",
    :NEW."OrigRecNo",
    :NEW."EDIFlag",
	 :NEW."CoverageAgeYoungAdult",											-- E142886 Age of young adult
    :NEW."YoungAdultCoverage",												-- E142886 Coverage.Coverage of template
    :NEW."CvgOnBirthChild",												-- E142886 Child: 0=Day,1=End of Month, 2=End of Year
    :NEW."CvgOnBirthStudent",												-- E142886 Student: 0=Day,1=End of Month, 2=End of Year
    :NEW."CvgOnBirthYoungAdult",											-- E142886 Young Adult: 0=Day,1=End of Month, 2=End of Year
    :NEW."ChargeDedAndPtChg"												-- AX-4268.4533
  );
END$trigger$
 ;
CREATE TRIGGER createpolinsorigrecno BEFORE INSERT ON polins FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

	IF (:NEW."OrigRecNo" = 0) THEN
		:NEW."OrigRecNo" := :NEW."PolIns";
	END IF;
END$trigger$
 ;
CREATE TRIGGER createprescrih BEFORE INSERT OR UPDATE OF "Date", "Practice", "Provider", "DrugDescription", "Dose", "DrugFrqDesc", "Total", "Refills", "Note", "IsPhoned", "Area", "Telephone", "Pharmacy", "Audit", "ApprovalUser", "ApprovalDate", "IsVoided", "VoidReason", "VoidAudit", "VoidAppUser", "Reference", "Custom1", "Custom2", "IsFaxed", "FaxArea", "FaxPhone", "PrescripType", "StartDate", "EndDate", "Deleted", "Drug", "eRxSyncAudit", "RxNorm", "RcopiaID", "DrugSchedule" ON prescrip FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

	
	 IF :NEW."eRxSyncAudit" > 0 THEN
		 -- check if anything of importance has been changed (in axium)
		 IF NVL(:OLD."RxNorm", ' ') <> NVL(:NEW."RxNorm", ' ')
			OR NVL(:OLD."Dose", ' ') <> NVL(:NEW."Dose", ' ')
			OR NVL(:OLD."DrugDescription", ' ') <> NVL(:NEW."DrugDescription", ' ')
			OR NVL(:OLD."Total", ' ') <> NVL(:NEW."Total", ' ')
			OR NVL(:OLD."Refills", 0) <> NVL(:NEW."Refills", 0)
			OR TO_CHAR(NVL(:OLD."StartDate", TO_DATE('01/01/1900', 'DD/MM/YYYY')), 'DD/MM/YYYY')
				<> TO_CHAR(NVL(:NEW."StartDate", TO_DATE('01/01/1900', 'DD/MM/YYYY')), 'DD/MM/YYYY')
			OR TO_CHAR(NVL(:OLD."EndDate", TO_DATE('01/01/1900', 'DD/MM/YYYY')), 'DD/MM/YYYY')
				<> TO_CHAR(NVL(:NEW."EndDate", TO_DATE('01/01/1900', 'DD/MM/YYYY')), 'DD/MM/YYYY')
			OR NVL(:OLD."Note", ' ') <> NVL(:NEW."Note", '')
			OR NVL(:OLD."DrugFrqDesc", '') <> NVL(:NEW."DrugFrqDesc", '')
			OR NVL(:OLD."Deleted", 0) <> NVL(:NEW."Deleted", 0)
			OR NVL(:OLD."ApprovalUser", 0) <> NVL(:NEW."ApprovalUser", 0)
		 THEN
			:NEW."eRxSyncAudit" := 0;
		 END IF;
    END IF;

	 IF :NEW."eRxSyncAudit" < 0 THEN
		 -- update from eRx so no need to send back to eRx
		 :NEW."eRxSyncAudit" := -:NEW."eRxSyncAudit";
	 END IF;

	 INSERT INTO PRESCRIH VALUES
	 (	PRESCRIH_PRESCRIPH_SEQ.nextval,
		:NEW."Prescription",
		:NEW."Patient",
		:NEW."Date",
		:NEW."Practice",
		:NEW."Provider",
		:NEW."DrugDescription",
		:NEW."Dose",
		:NEW."DrugFrqDesc",
		:NEW."Total",
		:NEW."Refills",
		:NEW."Note",
		:NEW."IsPhoned",
		:NEW."Area",
		:NEW."Telephone",
		:NEW."Pharmacy",
		:NEW."Audit",
		:NEW."ApprovalUser",
		:NEW."ApprovalDate",
		:NEW."IsVoided",
		:NEW."VoidReason",
		:NEW."VoidAudit",
		:NEW."VoidAppUser",
		:NEW."Reference",
		:NEW."Custom1",
		:NEW."Custom2",
		:NEW."IsFaxed",
		:NEW."FaxArea",
		:NEW."FaxPhone",
		:NEW."Drug",							-- B118954, B124475
		:NEW."PrescripType",
		:NEW."StartDate",
		:NEW."EndDate",
		:NEW."Deleted",
		:NEW."eRxSyncAudit",
		:NEW."RxNorm",
		:NEW."RcopiaID",
		:NEW."DrugSchedule",					-- E143159
		:NEW."IsSentEDI",						-- AX-18961.21207
		:NEW."IsPrinted"						-- AX-18961.21207
	);
	
END$trigger$
 ;
CREATE TRIGGER createprodhis BEFORE INSERT OR UPDATE OF "LastName", "FirstName", "MiddleName", "Title", "Address1", "Address2", "City", "Province", "Postal", "BArea", "BTel", "BExt", "HArea", "HTel", "Fee", "Specialist", "CDA", "EDI", "Color", "Type", "PrintOnClaim", "RequireGrading", "Year", "UnavailableBooking", "Chair", "Import", "CanComplete", "MultiChairs", "TypeCode", "EndDate", "PGroup", "CPRDate", "Standing", "Inactive", "RequireSteps", "Specialty", "PhaseCheck", "AddressOther", "Preferred", "FirstYear", "Box", "Manager", "DispLocked", "DispMaxHours", "NeedLocked", "SpecialtyCode", "DefaultPractice", "LabLocked", "ClaimLast", "ClaimFirst", "NameQual", "ClaimSpecCode", "RequireStartCheck", "IsTIN", "DispLockedUnappr", "Audit", "DoubleBooking", "MedNEICSpec", "MedSpecCode", "NPI", "NPI2", "ReviewExposures", "RequireTxConsent", "MaxApptMinutes", "TxLocked", "SchLocked", "SecondaryMCBFlag", "LimitedExams", "ExamCnt", "UnavailableGrace", "RequireCaseNote", "MaxSchDays", "SchToDate", "MUEligible", "DiagnosisNotReqd", "StartCheckMinutes" ON producer FOR EACH ROW  $trigger$DECLARE
  AuditId		NUMBER (10);
  HistoryType  NUMBER (5);

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


	AuditId := :NEW."Audit";

	-- handle if action done outside of axium	
	IF :OLD."Audit" = :NEW."Audit" THEN
		SELECT AUDITHIS_AUDIT_SEQ.nextval INTO AuditId FROM DUAL;
		
		IF INSERTING THEN
			HistoryType := 1;
		ELSE
			HistoryType := 2;
		END IF;
		
		INSERT INTO AUDITHIS VALUES (
			AuditId,	
			trunc(sysdate),
			trunc(to_char(sysdate,'SSSSS')/60),	
			-1, -- UserId,  B37408
			0, -- StationId
			'PRODUCER',
			HistoryType
		);
		
		:NEW."Audit" := AuditId;
	END IF;

	-- now add USERSHIS entry
   DECLARE
		CURSOR C1 IS SELECT * FROM USERS WHERE "Producer" = :NEW."Producer"
		  AND "Deleted" = 0 AND "Audit" <> :NEW."Audit";
	
   BEGIN
		FOR rec IN C1 LOOP
			INSERT INTO USERSHIS VALUES (
				USERSHIS_UsersHis_SEQ.nextval,
				rec."User",
				rec."Logon",
				rec."Name",
				rec."Password",
				rec."Level",
				rec."Producer",
				rec."Deleted",
				rec."ClaimDoctor",
				rec."Locked",
				rec."Scheduler",
				rec."RestrictDays",
				rec."First",
				rec."DisableAutoChart",
				rec."MaxChartOut",
				rec."MaxHoursOut",
				rec."EffDate",
				rec."ExpDate",
				rec."SwipeLogon",
				rec."SwipePassword",
				rec."PwdLastChanged",
				rec."MinSchHours",
				rec."Import",
				rec."MinContacts",
				rec."AddSteps",
				rec."ConsultantType",
				rec."IsManager",
				rec."RestrictedApproval",
				rec."Preferred",
				rec."Middle",
				rec."Sex",
				rec."Birth",
				rec."Address1",
				rec."Address2",
				rec."City",
				rec."Province",
				rec."Postal",
				rec."AddressOther",
				rec."HomeArea",
				rec."HomePhone",
				rec."AltArea",
				rec."AltPhone",
				rec."Email",
				rec."Note",
				rec."DeptCode",
				rec."DeptRoom",
				rec."DeptArea",
				rec."DeptPhone",
				rec."AddNotes",
				rec."EditNotes",
				rec."EditTxs",
				rec."RequireLabApp",
				rec."CanApproveLabs",
				rec."ApprovePlanTx",
				rec."ApproveCompTx",
				rec."ApproveExistingTx",
				rec."ExistingNeedsApp",
				rec."IsGroupManager",
				rec."Custom1",
				rec."Custom2",
				rec."Custom3",
				rec."Custom4",
				rec."Custom5",
				rec."Custom6",
				rec."Custom7",
				rec."Custom8",
				rec."Custom9",
				rec."Custom10",
				rec."ConditionNeedsApp",
				rec."ApproveConditionTx",
				rec."MobileId",
				rec."MobilePassword",
				rec."PerioNeedsApp",
				rec."ApprovePerio",
				rec."PerMeth",
				rec."ApproveOrthoV",
				rec."OrthoVNeedsApp",
				rec."DeleteTxs",
				rec."DrugsOnDemand",
				rec."RequireASAApproval",
				rec."SchClinic",
				rec."ApprovePrescript",
				rec."AutoLock",
				rec."DefaultBank",
				AuditId,
				rec."UseActiveDir",
				rec."ProblemsNeedApp",
				rec."ApproveProblems",
				rec."StartupMDI",
				rec."ApproveInvOrder",
				rec."ApproveNotes",
				rec."ApproveEHRForms",
				rec."ApproveStartChks",
				rec."AssignTxs",
				rec."ApproveNoTxConsent",
				rec."EditAppts",
				rec."CanAbortEvals",
				rec."IsInstructor",
				rec."CanEvaluate",
				rec."ApproveTxPlan",
				rec."ApproveDispLock",
				rec."ApproveUndefDrugs",
				rec."AutoLockErr",
				rec."PlanNeedsApp",
				rec."CompNeedsApp",
				rec."MsgRefreshRate",
				rec."NeedsTxPlanApp",
				rec."MaxSchDays",
				rec."MaxApptReqDays",
				rec."Credentials",
				rec."EditLabs",
				rec."LettersNeedApp",
				rec."ApproveLetters",
				rec."MsgAuthenticate",
				rec."MsgOutOfOffice",
				rec."MsgOutOfOfficeText",
				rec."DefaultInfoMgrTab",							-- E29423
				rec."EnforcePIN",										-- E80718
				rec."PIN",												-- E80718
				rec."PINLocked",										-- E80718
				rec."ProxyAppMode",									-- E72762
				rec."OpenSchClinicMode",							-- E58570
				rec."CanUseEmergMode",								-- E102642
				-- E79977
				rec."PrescribeCS",
				rec."PrescribeCSSchedule",
				rec."PrescribeNarcotic",
				rec."ApproveCS",
				rec."ApproveCSSchedule",
				rec."ApproveNarcotic",
				rec."CanUseERx",										-- E120324
				rec."PrescribeProxyMode",							-- E125820
				rec."AutoSpellChk",									-- E135371
				rec."MsgAccess",										-- E129605
				rec."EnterAlerts",									-- E126674
				rec."EnterAllergies",								-- E126674
				rec."EnterMedProb",								-- E126674
        rec."ChartLockDelay",          -- AX-1963
        rec."TempChartUnlock",      -- AX-2825
        rec."TempChartUnlockDays",  -- AX-2825
        rec."TempChartUnlockHours", -- AX-2825
        rec."CanTempChartUnlock",    -- AX-2825
        rec."EMailSubscribe",     -- AX-11524
        rec."EMailNotify",         -- AX-11524
    	rec."SurgeryNeedsApp",		-- AX-14377.16070
	rec."ApproveSurgery",		-- AX-14377.16070	
    	rec."ApproveDrugWaste",		-- AX-14377.16070
		rec."CallCenterId",			-- AX-18468.18814
		rec."CallCenterPrompt",		-- AX-18468.19037
		rec."EMailForward",			-- AX-21385
		rec."RequestApproval",           -- AX-21873.22007
	rec."MsgDismissHighPrior",       -- AX-23702
	rec."DeletePerioExam",			-- AX-24346
	rec."MsgOutOfOfficeStart",		-- AX-25510
	rec."MsgOutOfOfficeEnd"			-- AX-25510	

			);
		END LOOP;
 	END;
	
	INSERT INTO PRODHIS VALUES (
		PRODHIS_ProdHis_SEQ.nextval,
		:NEW."Producer",
		:NEW."LastName",
		:NEW."FirstName",
		:NEW."MiddleName",
		:NEW."Title",
		:NEW."Address1",
		:NEW."Address2",
		:NEW."City",
		:NEW."Province",
		:NEW."Postal",
		:NEW."BArea",
		:NEW."BTel",
		:NEW."BExt",
		:NEW."HArea",
		:NEW."HTel",
		:NEW."Fee",
		:NEW."Specialist",
		:NEW."CDA",
		:NEW."EDI",
		:NEW."Color",
		:NEW."Goal0",
		:NEW."Goal1",
		:NEW."Goal2",
		:NEW."Goal3",
		:NEW."Goal4",
		:NEW."Goal5",
		:NEW."Goal6",
		:NEW."Type",
		:NEW."PrintOnClaim",
		:NEW."RequireGrading",
		:NEW."Year",
		:NEW."UnavailableBooking",
		:NEW."Chair",
		:NEW."Import",
		:NEW."CanComplete",
		:NEW."MultiChairs",
		:NEW."TypeCode",
		:NEW."EndDate",
		:NEW."PGroup",
		:NEW."CPRDate",
		:NEW."Standing",
		:NEW."Inactive",
		:NEW."RequireSteps",
		:NEW."Specialty",
		:NEW."PhaseCheck",
		:NEW."AddressOther",
		:NEW."Preferred",
		:NEW."FirstYear",
		:NEW."Box",
		:NEW."Manager",
		:NEW."DispLocked",
		:NEW."DispMaxHours",
		:NEW."DispBalance",
		:NEW."NeedLocked",
		:NEW."SpecialtyCode",
		:NEW."DefaultPractice",
		:NEW."LabLocked",
		:NEW."ClaimLast",
		:NEW."ClaimFirst",
		:NEW."PatAssignOverdue",
		:NEW."OtherOverdue",
		:NEW."OverdueDate",
		:NEW."NameQual",
		:NEW."ClaimSpecCode",
		:NEW."RequireStartCheck",
		:NEW."IsTIN",
		:NEW."DispLockedUnappr",
		AuditId,
        :NEW."DoubleBooking",
        :NEW."MedNEICSpec",
        :NEW."MedSpecCode",
        :NEW."NPI",
        :NEW."NPI2",
        :NEW."ReviewExposures",
        :NEW."RequireTxConsent",
        :NEW."MaxApptMinutes",
        :NEW."TxLocked",
        :NEW."SchLocked",
        :NEW."SecondaryMCBFlag",
        :NEW."LimitedExams",
        :NEW."ExamCnt",
        :NEW."UnavailableGrace",									-- E85842
        :NEW."RequireCaseNote",									-- E39059
        :NEW."MaxSchDays",										-- E99410
        :NEW."SchToDate",										-- E99410
        :NEW."MUEligible",										-- E135084
        :NEW."DiagnosisNotReqd",								-- E136785
        :NEW."StartCheckMinutes"          -- AX-1665

	);
END$trigger$
 ;
CREATE TRIGGER createprodhisdelete BEFORE DELETE ON producer FOR EACH ROW  $trigger$DECLARE
  AuditId		NUMBER (10);
  HistoryType  NUMBER (5);
  RecCount     pls_integer;

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


	AuditId := :OLD."Audit";
	
	-- handle if deleted outside of axium
	SELECT "HistoryType" INTO HistoryType FROM AUDITHIS WHERE "Audit" = :OLD."Audit";
	IF HistoryType != 4 THEN
		SELECT AUDITHIS_AUDIT_SEQ.nextval INTO AuditId FROM DUAL;
		
		INSERT INTO AUDITHIS VALUES (
			AuditId,	
			trunc(sysdate),
			trunc(to_char(sysdate,'SSSSS')/60),	
			-1, -- UserId,  B37408
			0, -- StationId
			'PRODUCER',
			4
		);
	END IF;

	RecCount := 0;
	SELECT COUNT(*) INTO RecCount FROM PRODHIS WHERE "Producer" = :OLD."Producer" AND "Audit" = AuditId;
	
	IF RecCount = 0 THEN
		INSERT INTO PRODHIS VALUES (
			PRODHIS_ProdHis_SEQ.nextval,
			:OLD."Producer",
			:OLD."LastName",
			:OLD."FirstName",
			:OLD."MiddleName",
			:OLD."Title",
			:OLD."Address1",
			:OLD."Address2",
			:OLD."City",
			:OLD."Province",
			:OLD."Postal",
			:OLD."BArea",
			:OLD."BTel",
			:OLD."BExt",
			:OLD."HArea",
			:OLD."HTel",
			:OLD."Fee",
			:OLD."Specialist",
			:OLD."CDA",
			:OLD."EDI",
			:OLD."Color",
			:OLD."Goal0",
			:OLD."Goal1",
			:OLD."Goal2",
			:OLD."Goal3",
			:OLD."Goal4",
			:OLD."Goal5",
			:OLD."Goal6",
			:OLD."Type",
			:OLD."PrintOnClaim",
			:OLD."RequireGrading",
			:OLD."Year",
			:OLD."UnavailableBooking",
			:OLD."Chair",
			:OLD."Import",
			:OLD."CanComplete",
			:OLD."MultiChairs",
			:OLD."TypeCode",
			:OLD."EndDate",
			:OLD."PGroup",
			:OLD."CPRDate",
			:OLD."Standing",
			:OLD."Inactive",
			:OLD."RequireSteps",
			:OLD."Specialty",
			:OLD."PhaseCheck",
			:OLD."AddressOther",
			:OLD."Preferred",
			:OLD."FirstYear",
			:OLD."Box",
			:OLD."Manager",
			:OLD."DispLocked",
			:OLD."DispMaxHours",
			:OLD."DispBalance",
			:OLD."NeedLocked",
			:OLD."SpecialtyCode",
			:OLD."DefaultPractice",
			:OLD."LabLocked",
			:OLD."ClaimLast",
			:OLD."ClaimFirst",
			:OLD."PatAssignOverdue",
			:OLD."OtherOverdue",
			:OLD."OverdueDate",
			:OLD."NameQual",
			:OLD."ClaimSpecCode",
			:OLD."RequireStartCheck",
			:OLD."IsTIN",
			:OLD."DispLockedUnappr",
			AuditId,
            :OLD."DoubleBooking",
	        :OLD."MedNEICSpec",
    	    :OLD."MedSpecCode",
    	    :OLD."NPI",
    	    :OLD."NPI2",
    	    :OLD."ReviewExposures",
    	    :OLD."RequireTxConsent",
    	    :OLD."MaxApptMinutes",
    	    :OLD."TxLocked",
    	    :OLD."SchLocked",
          :OLD."SecondaryMCBFlag",
          :OLD."LimitedExams",
          :OLD."ExamCnt",
          :OLD."UnavailableGrace",
          :OLD."RequireCaseNote",							-- E39059
          :OLD."MaxSchDays",									-- E99410
			:OLD."SchToDate",										-- E99410
			:OLD."MUEligible",									-- E135084
			:OLD."DiagnosisNotReqd",								-- B142903
      :OLD."StartCheckMinutes"            -- AX-1665
		);
	END IF;
END$trigger$
 ;
CREATE TRIGGER createprovnoth BEFORE INSERT OR UPDATE OF "Provider", "Note", "StartDate", "EndDate", "Deleted" ON provnote FOR EACH ROW  $trigger$DECLARE
  AuditId		NUMBER (10);
  HistoryType  NUMBER (5);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

	AuditId := :NEW."Audit";

	-- handle if action done outside of axium	
	IF :OLD."Audit" = :NEW."Audit" THEN
		SELECT AUDITHIS_AUDIT_SEQ.nextval INTO AuditId FROM DUAL;
		
		IF INSERTING THEN
			HistoryType := 1;
		ELSE
			HistoryType := 2;
		END IF;
		
		INSERT INTO AUDITHIS VALUES (
			AuditId,	
			trunc(sysdate),
			trunc(to_char(sysdate,'SSSSS')/60),	
			-1, -- UserId,
			0, -- StationId
			'PROVNOTE',
			HistoryType
		);
		
		:NEW."Audit" := AuditId;
	END IF;	
	INSERT INTO PROVNOTH VALUES (
		PROVNOTH_PROVNOTH_SEQ.nextval,
		:NEW."ProvNote",
		:NEW."Provider",
		:NEW."Note",
		:NEW."StartDate",
		:NEW."EndDate",
		:NEW."Order",
    :NEW."Deleted",
		:NEW."Audit"
	);
END$trigger$
 ;
CREATE TRIGGER createptalerth BEFORE INSERT OR UPDATE OF "AlertType", "MedAlert", "Description", "Status", "OnsetDate", "Deleted", "User", "AddDateTime", "eRxSyncAudit", "RcopiaID", "NDCID", "SNOCode" ON ptalert FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  	
	 IF :NEW."eRxSyncAudit" > 0 THEN
		 -- check if anything of importance has been changed (in axium)
		 IF NVL(:OLD."Deleted", 0) <> NVL(:NEW."Deleted", 0)
			OR NVL(:OLD."Status", 0) <> NVL(:NEW."Status", 0)
			OR NVL(:OLD."MedAlert", 0) <> NVL(:NEW."MedAlert", 0)
			OR NVL(:OLD."SNOCode", ' ') <> NVL(:NEW."SNOCode", ' ')																
			OR NVL(:OLD."Description", ' ') <> NVL(:NEW."Description", ' ')
			OR NVL(:OLD."Reaction", ' ') <> NVL(:NEW."Reaction", ' ')
			OR TO_CHAR(NVL(:OLD."OnsetDate", TO_DATE('01/01/1900', 'DD/MM/YYYY')), 'DD/MM/YYYY')
				<> TO_CHAR(NVL(:NEW."OnsetDate", TO_DATE('01/01/1900', 'DD/MM/YYYY')), 'DD/MM/YYYY')
		 THEN
			:NEW."eRxSyncAudit" := 0;
		 END IF;
    END IF;

	 IF :NEW."eRxSyncAudit" < 0 THEN
		 -- update from eRx so no need to send back to eRx
		 :NEW."eRxSyncAudit" := -:NEW."eRxSyncAudit";
	 END IF;

    INSERT INTO PTALERTH VALUES
    (
      PTALERTH_PtAlertH_SEQ.nextval,
      :NEW."PtAlert",
      :NEW."Patient",
      :NEW."AlertType",
      :NEW."MedAlert",
      :NEW."Description",
      :NEW."Status",
      :NEW."OnsetDate",
      :NEW."Note",
      :NEW."Reaction",
      :NEW."Deleted",
      :NEW."User",
      :NEW."AddDateTime",
      :NEW."Audit",
      :NEW."eRxSyncAudit",
      :NEW."RcopiaID",
      :NEW."NDCID",
      :NEW."SNOCode"
    ) ;
END$trigger$
 ;
CREATE TRIGGER createptcasehis AFTER INSERT OR UPDATE OF "CaseType", "CreationDate", "SiteName", "ProdType", "ExamDate", "StartDate", "CompleteDate", "Deleted", "Audit" ON ptcase FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  INSERT INTO PTCASEH VALUES
  (
    PTCASEH_PtCaseh_SEQ.nextval,
    :NEW."PtCase",
    :NEW."Patient",
    :NEW."CaseType",
    :NEW."CreationDate",
    :NEW."SiteName",
    :NEW."ProdType",
    :NEW."ExamDate",
    :NEW."StartDate",
    :NEW."CompleteDate",
    :NEW."Deleted",
    :NEW."Audit"
   );
END$trigger$
 ;
CREATE TRIGGER createptconhis AFTER INSERT OR UPDATE OF "Date", "Time", "User", "StationId", "Note", "Deleted", "NoteCode", "ContactDate", "ContactTime", "ContactUser" ON ptcont FOR EACH ROW  $trigger$DECLARE
  PtConHisVal 		NUMBER(10);
  HistoryTypeVal 	NUMBER(5);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  SELECT PTCONHIS_CONTACTHIS_SEQ.nextval INTO PtConHisVal FROM dual;
  IF INSERTING THEN
    HistoryTypeVal := 1;
  ELSIF UPDATING THEN
    IF :NEW."Deleted" = 0 THEN
      HistoryTypeVal := 2;
    ELSE
      HistoryTypeVal := 4;
    END IF;
  END IF;
  INSERT INTO PTCONHIS VALUES (PtConHisVal, HistoryTypeVal,
    :NEW."Contact",
    :NEW."Patient",
    :NEW."Date",
    :NEW."Time",
    :NEW."User",
    :NEW."StationId",
    :NEW."Note",
    :NEW."Deleted",
    :NEW."NoteCode",
    :NEW."ContactDate",
    :NEW."ContactTime",
    :NEW."ContactUser");
END$trigger$
 ;
CREATE TRIGGER createptdephis AFTER INSERT OR UPDATE OF "Number", "IsCovered", "Relation", "Deleted", "MedicaidCoPay", "StartDate", "EndDate", "CardVerNo", "CorrectStatus" ON ptdepend FOR EACH ROW  $trigger$DECLARE
 PtDepHisVal 		NUMBER(10);
 HistoryTypeVal 	NUMBER(5);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

-- B27380
-- IF (:OLD."Number" <> :NEW."Number"
--      OR :OLD."Deleted" <> :NEW."Deleted"
--      OR :OLD."IsCovered" <> :NEW."IsCovered"
--      OR :OLD."Relation" <> :NEW."Relation") THEN
  SELECT PTDEPHIS_PtDepHis_SEQ.nextval INTO PtDepHisVal FROM dual;
  IF INSERTING THEN
    HistoryTypeVal := 1;
  ELSIF UPDATING THEN
    IF :NEW."Deleted" = 0 THEN
      HistoryTypeVal := 2;
    ELSE
      HistoryTypeVal := 4;
    END IF;
  END IF;
  INSERT INTO PTDEPHIS VALUES (PtDepHisVal, HistoryTypeVal,
    :NEW."PolicyId",
    :NEW."Patient",
    :NEW."Number",
    :NEW."IsCovered",
    :NEW."Relation",
    :NEW."HasPatientLimit",
    :NEW."PatientLimit",
    :NEW."PatientDeduct",
    :NEW."LimitBalance",
    :NEW."DeductBalance",
    :NEW."Date",
    :NEW."Time",
    :NEW."User",
    :NEW."StationId",
    :NEW."Deleted",
    :NEW."BillOrder",
    :NEW."VisitBalance",
    :NEW."MedicaidCoPay",
    :NEW."StartDate",
    :NEW."EndDate",
    :NEW."CardVerNo",                                     -- E00666.3.1
	:NEW."CorrectStatus");
-- B27380
-- END IF;
END$trigger$
 ;
CREATE TRIGGER createptemphis AFTER INSERT OR UPDATE OF "Primary", "Area", "Tel", "Ext", "Occupation", "Deleted", "EndDate" ON ptemploy FOR EACH ROW  $trigger$DECLARE
  PtEmpHisVal 		NUMBER(10);
  HistoryTypeVal 	NUMBER(5);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  SELECT PTEMPHIS_PtEmpHis_SEQ.nextval INTO PtEmpHisVal FROM dual;
  IF INSERTING THEN
    HistoryTypeVal := 1;
  ELSIF UPDATING THEN
    IF :NEW."Deleted" = 0 THEN
      HistoryTypeVal := 2;
    ELSE
      HistoryTypeVal := 4;
    END IF;
  END IF;
  INSERT INTO PTEMPHIS VALUES (PtEmpHisVal, HistoryTypeVal,
    :NEW."Patient",
    :NEW."Employer",
    :NEW."Primary",
    :NEW."Area",
    :NEW."Tel",
    :NEW."Ext",
    :NEW."Occupation",
    :NEW."Date",
    :NEW."Time",
    :NEW."User",
    :NEW."StationId",
    :NEW."Deleted",
    :NEW."EndDate");
END$trigger$
 ;
CREATE TRIGGER createptfaculh AFTER INSERT OR UPDATE OF "Faculty", "Discipline", "Deleted", "IsPrimary" ON ptfacul FOR EACH ROW  $trigger$DECLARE
  PtFaculHVal 		NUMBER(10);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  SELECT PTFACULH_PtFaculH_SEQ.nextval INTO PtFaculHVal FROM dual;
  INSERT INTO PTFACULH VALUES (PtFaculHVal,
    :NEW."PtFacul",
    :NEW."Patient",
    :NEW."Faculty",
    :NEW."Discipline",
    :NEW."Deleted",
    :NEW."Audit",
    :NEW."IsPrimary");
END$trigger$
 ;
CREATE TRIGGER createptgendrh AFTER INSERT OR UPDATE OF "PtSexOrient", "PtSOther", "PtSDeclined", "PtGenderId", "PtGOther", "PtGDeclined", "Audit", "PtPreferPronouns", "PtPronounsOther", "PtPronounsDeclined" ON ptgender FOR EACH ROW  $trigger$BEGIN



    -- AX-24111 j.s added ability to disable triggers for the given sessions 

    IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN 

      RETURN :new; 

    END IF; 



    -- AX-36275 gye Added insert check to ensure the first entry insert is recorded 

    IF INSERTING THEN 

      INSERT INTO PTGENDRH VALUES 

      (

        PTGENDRH_PTGENDRH_SEQ.nextval,

        :NEW."Patient",

        :NEW."PtSexOrient",

        :NEW."PtSOther",

        :NEW."PtSDeclined",

        :NEW."PtGenderId",

        :NEW."PtGOther",

        :NEW."PtGDeclined",

        :NEW."Audit",

        :NEW."PtPreferPronouns",

        :NEW."PtPronounsOther",

        :NEW."PtPronounsDeclined"

      );

    END IF;





    -- AX-35998 a.a Check if old values are not empty or null and also if they are different from new values

    -- AX-36275 gye Explicit check of updating record added to make sure no double up in the future 

    IF UPDATING THEN 

      IF (

        (COALESCE(:OLD."Patient", 0) <> COALESCE(:NEW."Patient", 0)) OR

        (COALESCE(:OLD."PtSexOrient", 0) <> COALESCE(:NEW."PtSexOrient", 0)) OR

        (COALESCE(:OLD."PtSOther", '') <> COALESCE(:NEW."PtSOther", '')) OR

        (COALESCE(:OLD."PtSDeclined", 0) <> COALESCE(:NEW."PtSDeclined", 0)) OR

        (COALESCE(:OLD."PtGenderId", 0) <> COALESCE(:NEW."PtGenderId", 0)) OR

        (COALESCE(:OLD."PtGOther", '') <> COALESCE(:NEW."PtGOther", '')) OR

        (COALESCE(:OLD."PtGDeclined", 0) <> COALESCE(:NEW."PtGDeclined", 0)) OR

        (COALESCE(:OLD."Audit", 0) <> COALESCE(:NEW."Audit", 0)) OR

        (COALESCE(:OLD."PtPreferPronouns", 0) <> COALESCE(:NEW."PtPreferPronouns", 0)) OR

        (COALESCE(:OLD."PtPronounsOther", '') <> COALESCE(:NEW."PtPronounsOther", '')) OR

        (COALESCE(:OLD."PtPronounsDeclined", 0) <> COALESCE(:NEW."PtPronounsDeclined", 0))

    ) THEN

        INSERT INTO PTGENDRH VALUES 

        (

        PTGENDRH_PTGENDRH_SEQ.nextval,

        :NEW."Patient",

        :NEW."PtSexOrient",

        :NEW."PtSOther",

        :NEW."PtSDeclined",

        :NEW."PtGenderId",

        :NEW."PtGOther",

        :NEW."PtGDeclined",

        :NEW."Audit",

        :NEW."PtPreferPronouns",

        :NEW."PtPronounsOther",

        :NEW."PtPronounsDeclined"

        );

      END IF;

    END IF;

  END$trigger$
 ;
CREATE TRIGGER createptguahis AFTER INSERT OR UPDATE OF "IsPrimaryGuarantor", "IsSecondaryGuarantor", "IsPolicyGuarantor", "RespRelation", "Deleted", "Inactive" ON ptguar FOR EACH ROW  $trigger$DECLARE
  IdVal NUMBER(10);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  SELECT PTGUAHIS_PTGUAHIS_SEQ.nextval INTO IdVal FROM dual;

  INSERT INTO PTGUAHIS VALUES (IdVal,
    :NEW."RespPatient",
    :NEW."Patient",
    :NEW."IsPrimaryGuarantor",
    :NEW."IsSecondaryGuarantor",
    :NEW."IsPolicyGuarantor",
    :NEW."RespRelation",
    :NEW."Deleted" ,
    :NEW."Audit",
	:NEW."Inactive" );
END$trigger$
 ;
CREATE TRIGGER createptimplnh AFTER INSERT OR UPDATE OF "Date", "Comment", "RawBarCode", "DeviceId", "SerialNumber", "LotNumber", "DistinctIdCode", "ManufacturedDate", "ExpiryDate", "IsRemoved", "Deleted", "CreateAudit", "Audit", "Sites", "RemovedDate" ON ptimplnt FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  INSERT INTO PTIMPLNH VALUES
  (
	 PTIMPLNH_PTIMPLNH_SEQ.nextval,
    :NEW."PtImplnt",
    :NEW."Patient",
    :NEW."Date",
    :NEW."Comment",
    :NEW."RawBarCode",
    :NEW."DeviceId",
    :NEW."SerialNumber",
    :NEW."LotNumber",
    :NEW."DistinctIdCode",
    :NEW."ManufacturedDate",
    :NEW."ExpiryDate",
    :NEW."IsRemoved",
    :NEW."Deleted",
    :NEW."CreateAudit",
    :NEW."Audit",
    :NEW."Sites",
	:NEW."RemovedDate"
   );
END$trigger$
 ;
CREATE TRIGGER createptneehis AFTER INSERT OR UPDATE OF "PtNeed", "NeedCode", "NeedDate", "Assigned", "AuditId", "Deleted", "Note", "NeedSts" ON ptneed FOR EACH ROW  $trigger$DECLARE
  PtNeedHisVal 	NUMBER(10);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  SELECT PTNEEHIS_PTNEEHIS_SEQ.nextval INTO PtNeedHisVal FROM dual;
  INSERT INTO PTNEEHIS VALUES (PtNeedHisVal,
      :NEW."PtNeed",
      :NEW."Patient",
      :NEW."NeedCode",
      :NEW."NeedDate",
      :NEW."Assigned",
      :NEW."AuditId",
      :NEW."Deleted",
      :NEW."Note",
      :NEW."NeedSts");
END$trigger$
 ;
CREATE TRIGGER createptnotehis AFTER INSERT OR UPDATE OF "Date", "User", "NoteCode", "Text", "Deleted" ON ptnote FOR EACH ROW  $trigger$DECLARE
  PtNoteHistoryVal NUMBER(10);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

SELECT PTNOTEH_PtNoteHistory_SEQ.nextval INTO PtNoteHistoryVal
 from dual;
INSERT INTO PTNOTEH VALUES (PtNoteHistoryVal,
 :NEW."PtNote",
 :NEW."Patient",
 :NEW."Date",
 :NEW."User",
 :NEW."EntryDate",
 :NEW."NoteCode",
 :NEW."Text",
 :NEW."Deleted",
 :NEW."IsClaimNote" );
END$trigger$
 ;
CREATE TRIGGER createptobjh AFTER INSERT OR UPDATE OF "Status", "TxPlan", "Deleted" ON ptobj FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


INSERT INTO PTOBJH VALUES (
									  PTOBJH_PtObjH_SEQ.nextval,
									  :NEW."PtObj",
									  :NEW."Patient",
									  :NEW."Description",
									  :NEW."Status",
									  :NEW."TxPlan",
									  :NEW."Deleted",
									  :NEW."Audit");
END$trigger$
 ;
CREATE TRIGGER createptperhis AFTER INSERT OR UPDATE OF "ChartDate", "AppUser", "AppDate", "Deleted", "Completed", "PerExam", "DelDate", "DelUser" ON ptperio FOR EACH ROW  $trigger$DECLARE
  IdVal 		NUMBER(10);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  SELECT PTPERHIS_Id_SEQ.nextval INTO IdVal FROM dual;
  INSERT INTO PTPERHIS VALUES (IdVal,
    :NEW."PtPerio",
    :NEW."Patient",
    :NEW."ChartDate",
    :NEW."AppUser",
    :NEW."AppDate",
    :NEW."Deleted",
    :NEW."Audit",
    :NEW."ChartByType",
    :NEW."ProdType",
    :NEW."Provider",
    :NEW."Completed",
    :NEW."PerExam",
    :NEW."OrigPtPerio",
	:NEW."DelDate",
	:NEW."DelUser"	);
END$trigger$
 ;
CREATE TRIGGER createptphyshis AFTER INSERT OR UPDATE OF "PtPhys", "Physician", "IsPrimary", "Deleted", "Audit" ON ptphys FOR EACH ROW  $trigger$DECLARE
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  INSERT INTO PTPHYSH VALUES
  (
    PTPHYSHIS_PtPhysHis_SEQ.nextval,
	:NEW."PtPhys",
	:NEW."Patient",
	:NEW."Physician",
	:NEW."IsPrimary",
	:NEW."Comment",
	:NEW."Deleted",
	:NEW."Audit"
  );
END$trigger$
 ;
CREATE TRIGGER createptpolh AFTER INSERT OR UPDATE OF "PolIns", "Patient", "Policy", "ResetDate", "StartDate", "Deleted" ON ptpol FOR EACH ROW  $trigger$DECLARE
  PtPolHVal 		NUMBER(10);
  HistoryTypeVal 	NUMBER(5);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  SELECT PTPOLH_PTPOLH_SEQ.nextval INTO PtPolHVal FROM dual;
  IF INSERTING THEN
    HistoryTypeVal := 1;
  ELSIF UPDATING THEN
    IF :NEW."Deleted" = 0 THEN
      HistoryTypeVal := 2;
    ELSE
      HistoryTypeVal := 4;
    END IF;
  END IF;
  INSERT INTO PTPOLH VALUES (PtPolHVal, HistoryTypeVal,
   	:NEW."PolicyId",
   	:NEW."PolIns",
   	:NEW."Family",
	:NEW."Patient",
	:NEW."Policy",
	:NEW."LimitBalance",
	:NEW."DeductBalance",
	:NEW."ResetDate",
	:NEW."StartDate",
	:NEW."YEResetDate",
	:NEW."MEResetDate",
	:NEW."Deleted",
	:NEW."Date",
	:NEW."Time",
	:NEW."User",
	:NEW."StationId",
	:NEW."SharedEntryId"
 );
END$trigger$
 ;
CREATE TRIGGER createptprbdxh AFTER INSERT OR UPDATE OF "PtPrb", "TxPDx", "Deleted" ON ptprbdx FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

INSERT INTO PTPRBDXH VALUES (PTPRBDXH_PtPrbDxH_SEQ.nextval,
									:NEW."PtPrb",				
									:NEW."TxPDx",				
									:NEW."Deleted",
									:NEW."Audit");
END$trigger$
 ;
CREATE TRIGGER createptprbh AFTER INSERT OR UPDATE OF "Problem", "Description", "ShortDesc", "Site", "Surface", "Status", "AreaFound", "AppUser", "AppDateTime", "Deleted", "Audit", "Date" ON ptprb FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

INSERT INTO PTPRBH VALUES (PTPRBH_PtPrbH_SEQ.nextval,
									:NEW."PtPrb",
									:NEW."Patient",
									:NEW."Problem",
									:NEW."Description",
									:NEW."ShortDesc",
									:NEW."Site",
									:NEW."Surface",
									:NEW."Note",
									:NEW."Status",
									:NEW."AreaFound",
									:NEW."AppUser",
									:NEW."AppDateTime",
									:NEW."Deleted",
									:NEW."Audit",
                  :NEW."Date"); -- E130137.rmt7
END$trigger$
 ;
CREATE TRIGGER createptprevhis AFTER INSERT OR UPDATE OF "PtPrev", "PrevCare", "DueDate", "Completed", "CompletedDate", "CompletedAppt", "Deleted", "Audit", "ExamState" ON ptprev FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  INSERT INTO PTPREVH VALUES
  (
	PTPREVH_PtPrevh_SEQ.nextval,
    :NEW."PtPrev",
    :NEW."Patient",
    :NEW."PrevCare",
    :NEW."DueDate",
    :NEW."Completed",
    :NEW."CompletedDate",
    :NEW."CompletedAppt",
    :NEW."Deleted",
    :NEW."Audit",
    :NEW."ExamState"
   );
END$trigger$
 ;
CREATE TRIGGER createptpsthis AFTER INSERT OR UPDATE OF "PerProg", "PerType", "PS1Score", "PS1Abnormal", "PS2Score", "PS2Abnormal", "PS3Score", "PS3Abnormal", "PS4Score", "PS4Abnormal", "PS5Score", "PS5Abnormal", "PS6Score", "PS6Abnormal" ON ptperst FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

   IF (INSERTING OR (:OLD."PerProg" <> :NEW."PerProg"
	   OR :OLD."PerType" <> :NEW."PerType"
	   OR :OLD."PS1Score" <> :NEW."PS1Score"
	   OR :OLD."PS1Abnormal" <> :NEW."PS1Abnormal"
	   OR :OLD."PS2Score" <> :NEW."PS2Score"
	   OR :OLD."PS2Abnormal" <> :NEW."PS2Abnormal"
	   OR :OLD."PS3Score" <> :NEW."PS3Score"
	   OR :OLD."PS3Abnormal" <> :NEW."PS3Abnormal"
	   OR :OLD."PS4Score" <> :NEW."PS4Score"
	   OR :OLD."PS4Abnormal" <> :NEW."PS4Abnormal"
	   OR :OLD."PS5Score" <> :NEW."PS5Score"
	   OR :OLD."PS5Abnormal" <> :NEW."PS5Abnormal"
	   OR :OLD."PS6Score" <> :NEW."PS6Score"
	   OR :OLD."PS6Abnormal" <> :NEW."PS6Abnormal"))
   THEN
	  INSERT INTO PTPSTHIS VALUES (PTPSTHIS_Id_SEQ.nextval,
		:NEW."PtPerSt",
		:NEW."Patient",
		:NEW."PerProg",
		:NEW."PerType",
		:NEW."PS1Score",
		:NEW."PS1Abnormal",
		:NEW."PS2Score",
		:NEW."PS2Abnormal",
		:NEW."PS3Score",
		:NEW."PS3Abnormal",
		:NEW."PS4Score",
		:NEW."PS4Abnormal",
		:NEW."PS5Score",
		:NEW."PS5Abnormal",
		:NEW."PS6Score",
		:NEW."PS6Abnormal",
		:NEW."Audit" );
   END IF;
END$trigger$
 ;
CREATE TRIGGER createptracehis AFTER INSERT OR UPDATE OF "Race", "Deleted", "Audit" ON ptrace FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  INSERT INTO PTRACEH VALUES
  (
	 PTRACEH_PtRaceH_SEQ.nextval,
    :NEW."Patient",
	 :NEW."Race",
    :NEW."Deleted",
    :NEW."Audit"
   );
END$trigger$
 ;
CREATE TRIGGER createptrcgrih AFTER INSERT OR UPDATE OF "Deleted" ON ptrcgrpi FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  INSERT INTO PTRCGRIH VALUES (PTRCGRIH_PTRCGRIH_SEQ.nextval,
    :NEW."PtRcGrp",
    :NEW."PtRecall",
    :NEW."Deleted",
    :NEW."Audit"
     );
END$trigger$
 ;
CREATE TRIGGER createptrcgrph AFTER INSERT OR UPDATE OF "Patient", "RcGroup", "Deleted" ON ptrcgrp FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  INSERT INTO PTRCGRPH VALUES (PTRCGRPH_PTRCGRPH_SEQ.nextval,
    :NEW."PtRcGrp",
    :NEW."Patient",
    :NEW."RcGroup",
    :NEW."Deleted",
    :NEW."Audit"
     );
END$trigger$
 ;
CREATE TRIGGER createptrechis AFTER INSERT OR UPDATE OF "Recall", "RecallDate", "Provider", "Status", "Comment", "Units", "ApptDate", "Booked", "User", "CreationDate", "RecallType", "Deleted", "Treatme2Id", "Clinic", "ApptCode", "IsDefault" ON ptrecall FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  INSERT INTO PTRECHIS VALUES (PTRECHIS_PtRecHis_SEQ.nextval,
    :NEW."Id",
    :NEW."Patient",
    :NEW."Recall",
    :NEW."RecallDate",
    :NEW."Provider",
    :NEW."Status",
    :NEW."Comment",
    :NEW."Units",
    :NEW."ApptDate",
    :NEW."Booked",
    :NEW."User",
    :NEW."CreationDate",
    :NEW."RecallType",
    :NEW."Deleted",
    :NEW."Audit",
    :NEW."Treatme2Id",
    :NEW."Clinic",
    :NEW."ApptCode",                                                          --E73066
    :NEW."IsDefault" ); -- AX-652
END$trigger$
 ;
CREATE TRIGGER createptrefhis AFTER INSERT OR UPDATE OF "Date", "Referral", "IsPrimary", "Note", "Deleted", "EndDate" ON ptrefer FOR EACH ROW  $trigger$DECLARE
  IdVal 		NUMBER(10);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  SELECT PTREFHIS_PTREFHIS_SEQ.nextval INTO IdVal FROM dual;
  INSERT INTO PTREFHIS VALUES (IdVal,
    :NEW."PtRefer",
    :NEW."Patient",
    :NEW."Date",
    :NEW."Referral",
    :NEW."IsPrimary",
    :NEW."FromToFlag",
    :NEW."Note",
    :NEW."Deleted",
    :NEW."Audit",
    :NEW."EndDate" );
END$trigger$
 ;
CREATE TRIGGER createptsdosehis AFTER INSERT OR UPDATE OF "PtSDrug", "EntryTime", "Amount", "Deleted", "Audit" ON ptsdose FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  INSERT INTO PTSDOSEH VALUES
  (
    PTSDOSEH_PtSDoseH_SEQ.nextval,
	:NEW."PtSDose",
	:NEW."PtSDrug",
	:NEW."EntryTime",
	:NEW."Amount",
	:NEW."Deleted",
	:NEW."Audit"
   );
END$trigger$
 ;
CREATE TRIGGER createptsdrughis AFTER INSERT OR UPDATE OF "Appointment", "Drug", "AnesUnit", "AnesDelv", "AnesGaug", "Deleted", "Audit", "Order", "OtherDrug", "WasteAudit", "IsContinued" ON ptsdrug FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  INSERT INTO PTSDRUGH VALUES
  (
    PTSDRUGH_PtSDrugH_SEQ.nextval,
	:NEW."PtSDrug",
	:NEW."Appointment",
	:NEW."Drug",
	:NEW."AnesUnit",
	:NEW."AnesDelv",
	:NEW."AnesGaug",
	:NEW."Deleted",
	:NEW."Audit",
	:NEW."Order",
	:NEW."OtherDrug",
	:NEW."Waste",
	:NEW."WasteAmount",
	:NEW."WasteDeleted",
	:NEW."WasteAudit",
	:NEW."SDrugHType",
	:NEW."IsContinued",
	:NEW."ShortName"
   );
END$trigger$
 ;
CREATE TRIGGER createptstagehis AFTER INSERT OR UPDATE OF "Appointment", "StageSet", "StageCode", "StageStart", "Audit" ON ptstage FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  INSERT INTO PTSTAGEH VALUES
  (
    PTSTAGEH_PtStageH_SEQ.nextval,
	:NEW."PtStage",
	:NEW."Appointment",
	:NEW."StageSet",
	:NEW."StageCode",
	:NEW."StageStart",
	:NEW."Audit"
   );
END$trigger$
 ;
CREATE TRIGGER createptsummh AFTER INSERT OR UPDATE OF "SummCode", "Value1", "Value2", "Value1Override", "Value2Override", "OverrideAudit" ON ptsumm FOR EACH ROW  $trigger$DECLARE
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

	INSERT INTO PTSUMMH VALUES
	(
		PTSUMMH_PtSummH_SEQ.nextval,
		:NEW."Patient",
		:NEW."SummCode",
		:NEW."Value1",
		:NEW."Value2",
		:NEW."Audit",
		:NEW."Value1Override",
		:NEW."Value2Override",
		:NEW."OverrideNote",
		:NEW."OverrideAudit"
	);
END$trigger$
 ;
CREATE TRIGGER createpttyphis AFTER INSERT OR UPDATE OF "PatType", "Deleted" ON pttypes FOR EACH ROW  $trigger$DECLARE
  IdVal 		NUMBER(10);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  SELECT PTTYPHIS_ID_SEQ.nextval INTO IdVal FROM dual;
  INSERT INTO PTTYPHIS VALUES (IdVal,
    :NEW."Patient",
    :NEW."PatType",
    :NEW."Deleted",
    :NEW."Audit" );
END$trigger$
 ;
CREATE TRIGGER createptvitalhis AFTER INSERT OR UPDATE OF "Appointment", "EntryMode", "EntryTime", "Error", "HeartRate", "Temperature", "RespRate", "SystolicBP", "DiastolicBP", "SpO2", "ECO2", "Audit", "VitMon", "Deleted" ON ptvital FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  INSERT INTO PTVITALH VALUES
  (
    PTVITALH_PtVitalH_SEQ.nextval,
	:NEW."PtVital",
	:NEW."Appointment",
	:NEW."EntryMode",
	:NEW."EntryTime",
	:NEW."Error",
	:NEW."Artifact",
	:NEW."HeartRate",
	:NEW."Temperature",
	:NEW."RespRate",
	:NEW."SystolicBP",
	:NEW."DiastolicBP",
	:NEW."SpO2",
	:NEW."ECO2",
	:NEW."Audit",
	:NEW."VitMon",
	:NEW."Deleted"
   );
END$trigger$
 ;
CREATE TRIGGER createptvtlarthis AFTER INSERT OR UPDATE OF "PtVital", "VitalType", "ArtifactText", "Audit" ON ptvtlart FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  INSERT INTO PTVTLARH VALUES
  (
    PTVTLARH_PtVtlArH_SEQ.nextval,
	:NEW."PtVtlArt",
	:NEW."PtVital",
	:NEW."VitalType",
	:NEW."ArtifactText",
	:NEW."Audit"
   );
END$trigger$
 ;
CREATE TRIGGER createptxrahis AFTER INSERT OR UPDATE OF "DateTaken", "Procedure", "ExposureCount", "AddedByUser", "Deleted", "OrigRecNo", "Description", "IsDigital" ON ptxray FOR EACH ROW  $trigger$DECLARE
  PtXraHisVal 		NUMBER(10);
  HistoryTypeVal 	NUMBER(5);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  SELECT PTXRAHIS_PtXRayHis_SEQ.nextval INTO PtXraHisVal FROM dual;
  IF INSERTING THEN
    HistoryTypeVal := 1;
  ELSIF UPDATING THEN
    IF :NEW."Deleted" = 0 THEN
      HistoryTypeVal := 2;
    ELSE
      HistoryTypeVal := 4;
    END IF;
  END IF;
  INSERT INTO PTXRAHIS VALUES (PtXraHisVal, HistoryTypeVal,
    :NEW."PtXRay",
    :NEW."Patient",
    :NEW."DateTaken",
    :NEW."Procedure",
    :NEW."ExposureCount",
    :NEW."AddedByUser",
    :NEW."Date",
    :NEW."Time",
    :NEW."User",
    :NEW."StationId",
    :NEW."Deleted",
    :NEW."OrigRecNo",
    :NEW."Description",
    :NEW."IsDigital"	-- E143172
    );
END$trigger$
 ;
CREATE TRIGGER createrefhis AFTER INSERT OR UPDATE ON referral FOR EACH ROW  $trigger$DECLARE
  IdVal 		NUMBER(10);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  SELECT REFHIS_ID_SEQ.nextval INTO IdVal FROM dual;
  INSERT INTO REFHIS VALUES (IdVal,
    :NEW."Referral",
    :NEW."Type",
    :NEW."Name",
    :NEW."Address1",
    :NEW."Address2",
    :NEW."City",
    :NEW."Province",
    :NEW."Postal",
    :NEW."Area",
    :NEW."Phone",
    :NEW."Ext",
    :NEW."Comment",
    :NEW."Clinical1",
    :NEW."Clinical2",
    :NEW."Clinical3",
    :NEW."Clinical4",
    :NEW."Clinical5",
    :NEW."Office1",
    :NEW."Office2",
    :NEW."Office3",
    :NEW."Office4",
    :NEW."Office5",
    :NEW."First",
    :NEW."Title",
    :NEW."Middle",
    :NEW."AddressOther",
    :NEW."IDNumber",
    :NEW."Deleted",
    :NEW."Audit",
    :NEW."FromTo",
    :NEW."ClaimSpecCode",
    :NEW."FaxArea",
    :NEW."FaxPhone",
    :NEW."Email",
	:NEW."NPI",
	:NEW."IsTIN" );
END$trigger$
 ;
CREATE TRIGGER createresphis AFTER INSERT OR UPDATE OF "Last", "First", "Middle", "Title", "Birth", "Address1", "Address2", "City", "Province", "Postal", "HomeArea", "HomePhone", "WorkArea", "WorkPhone", "Status", "Sex", "Marital", "AddressOther", "RespNumber", "Country", "Prefered", "Deleted", "HomeExt", "WorkExt", "EmancedMinor", "PrefLanguage", "Statements", "Email", "IsTrustedAudit", "Sin" ON patient FOR EACH ROW  $trigger$DECLARE
  RecCount  NUMBER;

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  SELECT COUNT(*) INTO RecCount FROM PTGUAR WHERE "RespPatient" = :NEW."Patient" AND "Deleted" = 0;

  IF RecCount > 0 THEN
   INSERT INTO RESPHIS VALUES (RESPHIS_RespHis_SEQ.nextval,
		:NEW."Patient",
		:NEW."Last",
		:NEW."First",
		:NEW."Middle",
		:NEW."Title",
		:NEW."Birth",
		:NEW."Address1",
		:NEW."Address2",
		:NEW."City",
		:NEW."Province",
		:NEW."Postal",
		:NEW."HomeArea",
		:NEW."HomePhone",
		:NEW."WorkArea",
		:NEW."WorkPhone",
		:NEW."Status",
		:NEW."Sex",
		:NEW."Marital",
		:NEW."AddressOther",
		:NEW."RespNumber",
		:NEW."Deleted",
		:NEW."Audit",
		:NEW."Country",
		:NEW."Prefered",
		:NEW."HomeExt",
		:NEW."WorkExt",
		:NEW."EmancedMinor",
		:NEW."PrefLanguage",
		:NEW."Statements",
		:NEW."Email",
    :NEW."IsTrustedAudit",
    :NEW."Sin"
		 );
  END IF;
END$trigger$
 ;
CREATE TRIGGER createslevrolh AFTER INSERT OR UPDATE OF "SLevel", "SRole", "Audit" ON slevrole FOR EACH ROW  $trigger$DECLARE
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


INSERT INTO SLEVROLH VALUES (
         SLEVROLH_SLEVROLH_SEQ.nextval,
         :NEW."SLevel",
         :NEW."SRole",
         :NEW."Audit");
END$trigger$
 ;
CREATE TRIGGER createstmthis AFTER INSERT OR UPDATE OF "LastStatementAmount" ON patient FOR EACH ROW  $trigger$DECLARE

BEGIN

  -- Fail fast: exit if the condition is not met; AX-36765
  IF NOT (
	    (:NEW."LastStatementAmount" <> NVL(:OLD."LastStatementAmount", 0)
	     OR :NEW."LastStatementDate" <> NVL(:OLD."LastStatementDate", TO_DATE('01/01/1900', 'DD/MM/YYYY')))
    	AND
	    :NEW."Family" = :NEW."Patient"
  ) THEN
  	  RETURN :new;
  END IF;

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


   INSERT INTO STATEMENT_HISTORY VALUES (
		STATEMENT_HISTORY_ID_SEQ.nextval,
		:NEW."Patient",
		SYSDATE
    );

END$trigger$
 ;
CREATE TRIGGER createtrxpolh AFTER INSERT OR UPDATE OF "PreAuth", "PreAuthStartDate", "PreAuthEndDate", "Received", "ReceiveDate", "Denied", "ServAuthException" ON trxpol FOR EACH ROW  $trigger$DECLARE
  IdVal 		NUMBER(10);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  IF (INSERTING AND ((:NEW."PreAuth" IS NOT NULL AND :NEW."PreAuth" <> ' ')
  OR :NEW."PreAuthStartDate" IS NOT NULL
  OR :NEW."PreAuthEndDate" IS NOT NULL
  OR :NEW."Received" = 1
  OR :NEW."ReceiveDate" IS NOT NULL
  OR :NEW."Denied" = 1
  OR :NEW."ServAuthException" > 0))
  OR (UPDATING AND (:NEW."PreAuth" <> :OLD."PreAuth"
  OR :NEW."PreAuthStartDate" <> :OLD."PreAuthStartDate"
  OR :NEW."PreAuthEndDate" <> :OLD."PreAuthEndDate"
  OR :NEW."Received" <> :OLD."Received"
  OR :NEW."ReceiveDate" <> :OLD."ReceiveDate"
  OR :NEW."Denied" <> :OLD."Denied"
  OR :NEW."ServAuthException" <> :OLD."ServAuthException")) THEN
    SELECT TRXPOLH_TrxPolH_SEQ.nextval INTO IdVal FROM dual;
    INSERT INTO TRXPOLH VALUES (IdVal,
      :NEW."TrxPol",
      :NEW."PolicyId",
      :NEW."Type",
      :NEW."Id",
      :NEW."Treatment",
      :NEW."PreAuth",
      :NEW."PreAuthStartDate",
      :NEW."PreAuthEndDate",
      :NEW."SubmitDate",
      :NEW."Submitted",
      :NEW."Received",
      :NEW."ReceiveDate",
      :NEW."Denied",
      :NEW."ServAuthException",
      :NEW."Audit" );
  END IF;
END$trigger$
 ;
CREATE TRIGGER createtxnohis AFTER INSERT OR UPDATE OF "Date", "Code", "Deleted", "Audit" ON txpnote FOR EACH ROW  $trigger$DECLARE
  TxPNoteHistoryVal NUMBER(10);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

SELECT TXPNOHIS_TxPNoteHistory_SEQ.nextval INTO TxPNoteHistoryVal
 from dual;
INSERT INTO TXPNOHIS VALUES (TxPNoteHistoryVal,
 :NEW."TxPNote",
 :NEW."Patient",
 :NEW."TxPlan",																						-- E130137.3
 :NEW."Date",
 :NEW."Code",
 :NEW."Text",
 :NEW."Deleted",
 :NEW."Audit" );
END$trigger$
 ;
CREATE TRIGGER createtxpdxh AFTER INSERT OR UPDATE OF "TxPlan", "DiagCode", "Description", "ShortDesc", "Order", "Deleted", "Audit" ON txpdx FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

INSERT INTO TXPDXH VALUES (TXPDXH_TxPDxH_SEQ.nextval,
									:NEW."TxPDx",				
									:NEW."TxPlan",				
									:NEW."DiagCode",					
									:NEW."Description",			
									:NEW."ShortDesc",			
									:NEW."Note",	
									:NEW."Order",	
									:NEW."Deleted",
									:NEW."Audit");
END$trigger$
 ;
CREATE TRIGGER createtxpdxtxh AFTER INSERT OR UPDATE OF "TxPDx", "TxPTx", "Deleted" ON txpdxtx FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

INSERT INTO TXPDXTXH VALUES (TXPDXTXH_TxPDxTxH_SEQ.nextval,
									:NEW."TxPDx",				
									:NEW."TxPTx",				
									:NEW."Deleted",
									:NEW."Audit");
END$trigger$
 ;
CREATE TRIGGER createtxplanh AFTER INSERT OR UPDATE OF "Description", "ChiefConcern", "Inactive", "InactiveAppUser", "Deleted", "Audit" ON txplan FOR EACH ROW  $trigger$DECLARE
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

INSERT INTO TXPLANH VALUES (
 TXPLANH_TxPlanH_SEQ.nextval,
 :NEW."TxPlan",
 :NEW."Patient",
 :NEW."Description",																						
 :NEW."ChiefConcern",
 :NEW."Inactive",
 :NEW."InactiveReason",
 :NEW."InactiveAppUser",
 :NEW."Deleted",
 :NEW."Audit" );
END$trigger$
 ;
CREATE TRIGGER createtxpopth AFTER INSERT OR UPDATE OF "TxPOpt", "TxPlan", "Description", "NeedsConsultantAppr", "InstructorApproved", "Total", "InsTotal", "AppUser", "AppDateTime", "AppNA", "Deleted" ON txpopt FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

INSERT INTO TXPOPTH VALUES (TXPOPTH_TxPOptH_SEQ.nextval,
									:NEW."TxPOpt",				
									:NEW."TxPlan",				
									:NEW."Description",			
									:NEW."NeedsConsultantAppr",				
									:NEW."InstructorApproved",				
									:NEW."Total",					
									:NEW."InsTotal",					
									:NEW."AppUser",				
									:NEW."AppDateTime",						
									:NEW."AppNA",				
									:NEW."Deleted",
									:NEW."Audit");
END$trigger$
 ;
CREATE TRIGGER createtxpprbh AFTER INSERT OR UPDATE OF "TxPlan", "PtPrb", "Deleted" ON txpprb FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

INSERT INTO TXPPRBH VALUES (TXPPRBH_TxPPrbH_SEQ.nextval,
									:NEW."TxPlan",				
									:NEW."PtPrb",				
									:NEW."Deleted",
									:NEW."Audit");
END$trigger$
 ;
CREATE TRIGGER createtxptxh AFTER INSERT OR UPDATE OF "TxPTx", "TxPOpt", "TxPlan", "TxPTxType", "TxPTxDateTime", "Order", "Provider", "Code", "Description", "MacroSeq", "Site", "Site2", "Surface", "Phase", "Sequence", "Status", "Total", "InsTotal", "HeldTotal", "ClaimDoctor", "Discipline", "Unit", "Custom1", "Custom2", "PtAccepted", "PtAcceptDateTime", "Treatme2Id", "Deleted", "Audit" ON txptx FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


IF INSERTING
  OR :OLD."TxPTx" <> :NEW."TxPTx"
  OR :OLD."TxPOpt" <> :NEW."TxPOpt"
  OR :OLD."TxPlan" <> :NEW."TxPlan"
  OR :OLD."TxPTxType" <> :NEW."TxPTxType"
  OR :OLD."Text" <> :NEW."Text"
  OR :OLD."TxPTxDateTime" <> :NEW."TxPTxDateTime"
  OR :OLD."Order" <> :NEW."Order"
  OR :OLD."Provider" <> :NEW."Provider"
  OR :OLD."Code" <> :NEW."Code"
  OR :OLD."Description" <> :NEW."Description"
  OR :OLD."MacroSeq" <> :NEW."MacroSeq"
  OR :OLD."Site" <> :NEW."Site"
  OR :OLD."Site2" <> :NEW."Site2"
  OR :OLD."Surface" <> :NEW."Surface"
  OR :OLD."Phase" <> :NEW."Phase"
  OR :OLD."Sequence" <> :NEW."Sequence"
  OR :OLD."Status" <> :NEW."Status"
  OR :OLD."Total" <> :NEW."Total"
  OR :OLD."InsTotal" <> :NEW."InsTotal"
  OR :OLD."HeldTotal" <> :NEW."HeldTotal"
  OR :OLD."ClaimDoctor" <> :NEW."ClaimDoctor"
  OR :OLD."Discipline" <> :NEW."Discipline"
  OR :OLD."Unit" <> :NEW."Unit"
  OR :OLD."Custom1" <> :NEW."Custom1"
  OR :OLD."Custom2" <> :NEW."Custom2"
  OR :OLD."PtAccepted" <> :NEW."PtAccepted"
  OR :OLD."PtAcceptDateTime" <> :NEW."PtAcceptDateTime"
  OR (:OLD."Treatme2Id" = 0 AND :NEW."Treatme2Id" <> 0)
  OR :OLD."Deleted" <> :NEW."Deleted"
  OR :OLD."Audit" <> :NEW."Audit"
  THEN

    INSERT INTO TXPTXH VALUES (TXPTXH_TXPTXH_SEQ.nextval,
									:NEW."TxPTx",
									:NEW."TxPOpt",
									:NEW."TxPlan",
									:NEW."TxPTxType",
									:NEW."Text",
									:NEW."TxPTxDateTime",
									:NEW."Order",
									:NEW."Provider",
									:NEW."Code",
									:NEW."Description",
									:NEW."MacroSeq",
									:NEW."Site",
									:NEW."Site2",
									:NEW."Surface",
									:NEW."Phase",
									:NEW."Sequence",
									:NEW."Status",
									:NEW."Total",
									:NEW."InsTotal",
									:NEW."HeldTotal",
									:NEW."ClaimDoctor",
									:NEW."Discipline",
									:NEW."Unit",
									:NEW."Custom1",
									:NEW."Custom2",
									:NEW."PtAccepted",
									:NEW."PtAcceptDateTime",
									:NEW."Treatme2Id",
									:NEW."Deleted",
									:NEW."Audit");
    END IF;
END$trigger$
 ;
CREATE TRIGGER createuhealhis AFTER INSERT OR UPDATE OF "Health", "Category", "Date", "ExpiryDate", "Deleted" ON uhealth FOR EACH ROW  $trigger$BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


	INSERT INTO UHEALHIS VALUES (
		UHEALHIS_UHealHis_SEQ.nextval,
		:NEW."UHealth",
		:NEW."User",
		:NEW."Health",
		:NEW."Category",
		:NEW."Date",
		:NEW."ExpiryDate",
		:NEW."Deleted",
		:NEW."Audit",
		:NEW."Note");
END$trigger$
 ;
CREATE TRIGGER createusershis BEFORE INSERT OR UPDATE OF "Logon", "Name", "Password", "Level", "Producer", "Deleted", "ClaimDoctor", "Locked", "Scheduler", "RestrictDays", "First", "DisableAutoChart", "MaxChartOut", "MaxHoursOut", "EffDate", "ExpDate", "SwipeLogon", "SwipePassword", "PwdLastChanged", "IsInstructor", "MaxSchDays", "MaxApptReqDays", "Credentials", "MinSchHours", "Import", "MinContacts", "AddSteps", "ConsultantType", "IsManager", "RestrictedApproval", "Preferred", "Middle", "Sex", "Birth", "Address1", "Address2", "City", "Province", "Postal", "AddressOther", "HomeArea", "HomePhone", "AltArea", "AltPhone", "Email", "Note", "DeptCode", "DeptRoom", "DeptArea", "DeptPhone", "AddNotes", "EditNotes", "EditTxs", "RequireLabApp", "CanApproveLabs", "ApprovePlanTx", "ApproveCompTx", "ApproveExistingTx", "ExistingNeedsApp", "IsGroupManager", "Custom1", "Custom2", "Custom3", "Custom4", "Custom5", "Custom6", "Custom7", "Custom8", "Custom9", "Custom10", "ConditionNeedsApp", "ApproveConditionTx", "MobileId", "MobilePassword", "PerioNeedsApp", "ApprovePerio", "PerMeth", "ApproveOrthoV", "OrthoVNeedsApp", "DeleteTxs", "DrugsOnDemand", "RequireASAApproval", "ApprovePrescript", "AutoLock", "DefaultBank", "UseActiveDir", "ProblemsNeedApp", "ApproveProblems", "StartupMDI", "ApproveInvOrder", "ApproveNotes", "ApproveEHRForms", "ApproveStartChks", "AssignTxs", "ApproveNoTxConsent", "EditAppts", "CanAbortEvals", "CanEvaluate", "ApproveTxPlan", "ApproveDispLock", "ApproveUndefDrugs", "AutoLockErr", "PlanNeedsApp", "CompNeedsApp", "MsgRefreshRate", "NeedsTxPlanApp", "EditLabs", "LettersNeedApp", "ApproveLetters", "MsgAuthenticate", "MsgOutOfOffice", "DefaultInfoMgrTab", "EnforcePIN", "PIN", "PINLocked", "ProxyAppMode", "OpenSchClinicMode", "CanUseEmergMode", "PrescribeCS", "PrescribeCSSchedule", "PrescribeNarcotic", "ApproveCS", "ApproveCSSchedule", "ApproveNarcotic", "CanUseERx", "AutoSpellChk", "PrescribeProxyMode", "MsgAccess", "EnterAlerts", "EnterAllergies", "EnterMedProb", "ChartLockDelay", "TempChartUnlock", "TempChartUnlockDays", "TempChartUnlockHours", "CanTempChartUnlock", "EMailSubscribe", "EMailNotify", "SurgeryNeedsApp", "ApproveSurgery", "ApproveDrugWaste", "CallCenterId", "CallCenterPrompt", "EMailForward", "RequestApproval", "MsgDismissHighPrior", "DeletePerioExam", "MsgOutOfOfficeStart", "MsgOutOfOfficeEnd" ON users FOR EACH ROW  $trigger$DECLARE
  AuditId			NUMBER (10);
  HistoryType		NUMBER (5);
  UsersHisCount	pls_integer;

BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


	IF (INSERTING OR (UPDATING AND
		(:OLD."Logon" <> :NEW."Logon"
		OR :OLD."Name" <> :NEW."Name"
		OR :OLD."Password" <> :NEW."Password"
		OR :OLD."Level" <> :NEW."Level"
		OR :OLD."Producer" <> :NEW."Producer"
		OR :OLD."Deleted" <> :NEW."Deleted"
		OR :OLD."ClaimDoctor" <> :NEW."ClaimDoctor"
		OR :OLD."Locked" <> :NEW."Locked"
		OR :OLD."Scheduler" <> :NEW."Scheduler"
		OR :OLD."RestrictDays" <> :NEW."RestrictDays"
		OR :OLD."First" <> :NEW."First"
		OR :OLD."DisableAutoChart" <> :NEW."DisableAutoChart"
		OR :OLD."MaxChartOut" <> :NEW."MaxChartOut"
		OR :OLD."MaxHoursOut" <> :NEW."MaxHoursOut"

    -- B118943
		OR :OLD."EffDate" <> :NEW."EffDate"
    OR (:OLD."EffDate" IS NOT NULL AND :NEW."EffDate" IS NULL)
    OR (:OLD."EffDate" IS NULL AND :NEW."EffDate" IS NOT NULL)
		OR :OLD."ExpDate" <> :NEW."ExpDate"
    OR (:OLD."ExpDate" IS NOT NULL AND :NEW."ExpDate" IS NULL)
    OR (:OLD."ExpDate" IS NULL AND :NEW."ExpDate" IS NOT NULL)

		OR :OLD."SwipeLogon" <> :NEW."SwipeLogon"
		OR :OLD."SwipePassword" <> :NEW."SwipePassword"
		OR (:OLD."PwdLastChanged" IS NULL AND  :NEW."PwdLastChanged" IS NOT NULL)
		OR (:OLD."PwdLastChanged" IS NOT NULL AND  :NEW."PwdLastChanged" IS NULL)
		OR :OLD."PwdLastChanged" <> :NEW."PwdLastChanged"
		OR :OLD."MinSchHours"				<> :NEW."MinSchHours"
		OR :OLD."Import"					<> :NEW."Import"
		OR :OLD."MinContacts"			<> :NEW."MinContacts"
		OR :OLD."AddSteps"				<> :NEW."AddSteps"
		OR :OLD."ConsultantType"		<> :NEW."ConsultantType"
		OR :OLD."IsManager"				<> :NEW."IsManager"
		OR :OLD."RestrictedApproval"	<> :NEW."RestrictedApproval"
		OR :OLD."Preferred"				<> :NEW."Preferred"
		OR :OLD."Middle"					<> :NEW."Middle"
		OR :OLD."Sex"						<> :NEW."Sex"
		OR :OLD."Birth"					<> :NEW."Birth"
		OR :OLD."Address1"				<> :NEW."Address1"
		OR :OLD."Address2"				<> :NEW."Address2"
		OR :OLD."City"						<> :NEW."City"
		OR :OLD."Province"				<> :NEW."Province"
		OR :OLD."Postal"					<> :NEW."Postal"
		OR :OLD."AddressOther"			<> :NEW."AddressOther"
		OR :OLD."HomeArea"				<> :NEW."HomeArea"
		OR :OLD."HomePhone"				<> :NEW."HomePhone"
		OR :OLD."AltArea"					<> :NEW."AltArea"
		OR :OLD."AltPhone"				<> :NEW."AltPhone"
		OR :OLD."Email"					<> :NEW."Email"
		OR :OLD."Note"						<> :NEW."Note"
		OR :OLD."DeptCode"				<> :NEW."DeptCode"
		OR :OLD."DeptRoom"				<> :NEW."DeptRoom"
		OR :OLD."DeptArea"				<> :NEW."DeptArea"
		OR :OLD."DeptPhone"				<> :NEW."DeptPhone"
		OR :OLD."AddNotes"				<> :NEW."AddNotes"
		OR :OLD."EditNotes"				<> :NEW."EditNotes"
		OR :OLD."EditTxs"					<> :NEW."EditTxs"
		OR :OLD."RequireLabApp"			<> :NEW."RequireLabApp"
		OR :OLD."CanApproveLabs"		<> :NEW."CanApproveLabs"
		OR :OLD."ApprovePlanTx"			<> :NEW."ApprovePlanTx"
		OR :OLD."ApproveCompTx"			<> :NEW."ApproveCompTx"
		OR :OLD."ApproveExistingTx"	<> :NEW."ApproveExistingTx"
		OR :OLD."ExistingNeedsApp"		<> :NEW."ExistingNeedsApp"
		OR :OLD."IsGroupManager"		<> :NEW."IsGroupManager"
		OR :OLD."Custom1"					<> :NEW."Custom1"
		OR :OLD."Custom2"					<> :NEW."Custom2"
		OR :OLD."Custom3"					<> :NEW."Custom3"
		OR :OLD."Custom4"					<> :NEW."Custom4"
		OR :OLD."Custom5"					<> :NEW."Custom5"
		OR :OLD."Custom6"					<> :NEW."Custom6"
		OR :OLD."Custom7"					<> :NEW."Custom7"
		OR :OLD."Custom8"					<> :NEW."Custom8"
		OR :OLD."Custom9"					<> :NEW."Custom9"
		OR :OLD."Custom10"				<> :NEW."Custom10"
		OR :OLD."ConditionNeedsApp"	<> :NEW."ConditionNeedsApp"
		OR :OLD."ApproveConditionTx"	<> :NEW."ApproveConditionTx"
		OR :OLD."MobileId"				<> :NEW."MobileId"
		OR :OLD."MobilePassword"		<> :NEW."MobilePassword"
		OR :OLD."PerioNeedsApp"			<> :NEW."PerioNeedsApp"
		OR :OLD."ApprovePerio"			<> :NEW."ApprovePerio"
		OR :OLD."PerMeth"					<> :NEW."PerMeth"
		OR :OLD."ApproveOrthoV"			<> :NEW."ApproveOrthoV"
		OR :OLD."OrthoVNeedsApp"		<> :NEW."OrthoVNeedsApp"
		OR :OLD."DeleteTxs"				<> :NEW."DeleteTxs"
		OR :OLD."DrugsOnDemand"			<> :NEW."DrugsOnDemand"
		OR :OLD."RequireASAApproval"	<> :NEW."RequireASAApproval"
--		OR :OLD."SchClinic"				<> :NEW."SchClinic"
		OR :OLD."ApprovePrescript"		<> :NEW."ApprovePrescript"
		OR :OLD."AutoLock"				<> :NEW."AutoLock"
		OR :OLD."DefaultBank"			<> :NEW."DefaultBank"
		OR :OLD."UseActiveDir"			<> :NEW."UseActiveDir"
		OR :OLD."ProblemsNeedApp"		<> :NEW."ProblemsNeedApp"
		OR :OLD."ApproveProblems"		<> :NEW."ApproveProblems"
		OR :OLD."StartupMDI"		      <> :NEW."StartupMDI"
		OR :OLD."ApproveInvOrder"		<> :NEW."ApproveInvOrder"
		OR :OLD."ApproveNotes"	      <> :NEW."ApproveNotes"
		OR :OLD."ApproveEHRForms"		<> :NEW."ApproveEHRForms"
		OR :OLD."ApproveStartChks"		<> :NEW."ApproveStartChks"
		OR :OLD."AssignTxs"	         <> :NEW."AssignTxs"
		OR :OLD."ApproveNoTxConsent"    <> :NEW."ApproveNoTxConsent"
		OR :OLD."EditAppts"	         <> :NEW."EditAppts"
		OR :OLD."CanAbortEvals"	      <> :NEW."CanAbortEvals"
		OR :OLD."IsInstructor"			<> :NEW."IsInstructor"
		OR :OLD."CanEvaluate"	      <> :NEW."CanEvaluate"
		OR :OLD."ApproveTxPlan"	      <> :NEW."ApproveTxPlan"
		OR :OLD."ApproveDispLock"	   <> :NEW."ApproveDispLock"
		OR :OLD."ApproveUndefDrugs"   <> :NEW."ApproveUndefDrugs"
		OR :OLD."AutoLockErr"			<> :NEW."AutoLockErr"
		OR :OLD."PlanNeedsApp"			<> :NEW."PlanNeedsApp"
		OR :OLD."CompNeedsApp"			<> :NEW."CompNeedsApp"
		OR :OLD."MsgRefreshRate"		<> :NEW."MsgRefreshRate"
		OR :OLD."NeedsTxPlanApp"		<> :NEW."NeedsTxPlanApp"
		OR :OLD."MaxSchDays"				<> :NEW."MaxSchDays"
		OR :OLD."MaxApptReqDays"		<> :NEW."MaxApptReqDays"
		OR NVL(:OLD."Credentials", ' ') <> NVL(:NEW."Credentials", ' ')
		OR :OLD."EditLabs"				<> :NEW."EditLabs"
		OR :OLD."LettersNeedApp"      <> :NEW."LettersNeedApp"
		OR :OLD."ApproveLetters"      <> :NEW."ApproveLetters"
		OR :OLD."MsgAuthenticate"		<> :NEW."MsgAuthenticate"
		OR :OLD."MsgOutOfOffice"		<> :NEW."MsgOutOfOffice"
		OR :OLD."MsgOutOfOfficeText"	<> :NEW."MsgOutOfOfficeText"
      OR :OLD."DefaultInfoMgrTab"	<> :NEW."DefaultInfoMgrTab"
      OR :OLD."EnforcePIN"				<> :NEW."EnforcePIN"
      OR NVL(:OLD."PIN", ' ')			<> NVL(:NEW."PIN", ' ')
      OR :OLD."PINLocked"				<> :NEW."PINLocked"
      OR :OLD."ProxyAppMode"			<>	:NEW."ProxyAppMode"
      OR :OLD."OpenSchClinicMode"	<>	:NEW."OpenSchClinicMode"	-- E58570
      OR :OLD."CanUseEmergMode"     <> :NEW."CanUseEmergMode"
      -- E79977
      OR :OLD."PrescribeCS"			<> :NEW."PrescribeCS"
      OR :OLD."PrescribeCSSchedule"	<> :NEW."PrescribeCSSchedule"
      OR :OLD."PrescribeNarcotic"	<> :NEW."PrescribeNarcotic"
      OR :OLD."ApproveCS"				<> :NEW."ApproveCS"
      OR :OLD."ApproveCSSchedule"	<> :NEW."ApproveCSSchedule"
      OR :OLD."ApproveNarcotic"		<> :NEW."ApproveNarcotic"
      OR :OLD."CanUseERx"				<> :NEW."CanUseERx"				-- E120324
      OR :OLD."AutoSpellChk"			<> :NEW."AutoSpellChk"			-- E135371
      OR :OLD."PrescribeProxyMode"	<> :NEW."PrescribeProxyMode"	-- E125820
		OR :OLD."MsgAccess"				<> :NEW."MsgAccess"				-- E129605
		OR :OLD."EnterAlerts"			<> :NEW."EnterAlerts"			-- E126674
		OR :OLD."EnterAllergies"		<> :NEW."EnterAllergies"		-- E126674
		OR :OLD."EnterMedProb"			<> :NEW."EnterMedProb"			-- E126674
    OR :OLD."ChartLockDelay"    <> :NEW."ChartLockDelay" -- AX-1963
    OR :OLD."TempChartUnlock"    <> :NEW."TempChartUnlock" -- AX-2825
    OR :OLD."TempChartUnlockDays"    <> :NEW."TempChartUnlockDays" -- AX-2825
    OR :OLD."TempChartUnlockHours"    <> :NEW."TempChartUnlock" -- AX-2825
    OR :OLD."CanTempChartUnlock"    <> :NEW."CanTempChartUnlock" -- AX-2825
    OR :OLD."EMailSubscribe"      <> :NEW."EMailSubscribe"      -- AX-11524
    OR :OLD."EMailNotify"         <> :NEW."EMailNotify"         -- AX-11524
        OR :OLD."SurgeryNeedsApp" <> :NEW."SurgeryNeedsApp"		-- AX-14377.16070
        OR :OLD."ApproveSurgery" <> :NEW."ApproveSurgery"		-- AX-14377.16070	
        OR :OLD."ApproveDrugWaste" <> :NEW."ApproveDrugWaste"		-- AX-14377.16070
		  OR :OLD."CallCenterId" <> :NEW."CallCenterId"					-- AX-18468.18814
		  OR :OLD."CallCenterPrompt" <> :NEW."CallCenterPrompt"		-- AX-18468.19037
		  OR :OLD."EMailForward" <> :NEW."EMailForward"					-- AX-21383
		  OR :OLD."RequestApproval" <> :NEW."RequestApproval"					-- AX-21873.22007
		OR :OLD."MsgDismissHighPrior" <> :NEW."MsgDismissHighPrior"			-- AX-23702
		OR :OLD."DeletePerioExam" <> :NEW."DeletePerioExam"			-- AX-24346
		OR :OLD."MsgOutOfOfficeStart"	<> :NEW."MsgOutOfOfficeStart"		--AX-25510
		OR :OLD."MsgOutOfOfficeEnd"	<> :NEW."MsgOutOfOfficeEnd"		--AX-25510	
		  			
		)))
	THEN
		AuditId := :NEW."Audit";

		-- handle if action done outside of axium	
		IF ((INSERTING AND AuditId = 0) OR (UPDATING AND :OLD."Audit" = :NEW."Audit")) THEN
			SELECT AUDITHIS_AUDIT_SEQ.nextval INTO AuditId FROM DUAL;

			IF INSERTING THEN			-- insert
				HistoryType := 1;
			ELSIF UPDATING THEN
				IF :NEW."Deleted" = 0 THEN
					HistoryType := 2;	-- edit
				ELSE
					HistoryType := 4;	-- delete
				END IF;
			END IF;
			
			INSERT INTO AUDITHIS VALUES (
				AuditId,	
				trunc(sysdate),
				trunc(to_char(sysdate,'SSSSS')/60),	
				-1, -- UserId,  B37408
				0, -- StationId
				'USERS',
				HistoryType
			);
			
			:NEW."Audit" := AuditId;
		END IF;
		
		-- if USERSHIS entry already exists for this Audit Id then update existing entry
		SELECT COUNT(*) INTO UsersHisCount FROM USERSHIS WHERE "User" = :NEW."User" AND "Audit" = AuditId;
		
		IF (UsersHisCount = 1) THEN
			UPDATE USERSHIS SET
				"Logon"					= :NEW."Logon",
				"Name"					= :NEW."Name",
				"Password"				= :NEW."Password",
				"Level"					= :NEW."Level",
				"Producer"				= :NEW."Producer",
				"Deleted"				= :NEW."Deleted",
				"ClaimDoctor"			= :NEW."ClaimDoctor",
				"Locked"					= :NEW."Locked",
				"Scheduler"				= :NEW."Scheduler",
				"RestrictDays"			= :NEW."RestrictDays",
				"First"					= :NEW."First",
				"DisableAutoChart"	= :NEW."DisableAutoChart",
				"MaxChartOut"			= :NEW."MaxChartOut",
				"MaxHoursOut"			= :NEW."MaxHoursOut",
				"EffDate"				= :NEW."EffDate",
				"ExpDate"				= :NEW."ExpDate",
				"SwipeLogon"			= :NEW."SwipeLogon",
				"SwipePassword"		= :NEW."SwipePassword",
				"PwdLastChanged"		= :NEW."PwdLastChanged",
				"MinSchHours"			= :NEW."MinSchHours",
				"Import"					= :NEW."Import",
				"MinContacts"			= :NEW."MinContacts",
				"AddSteps"				= :NEW."AddSteps",
				"ConsultantType"		= :NEW."ConsultantType",
				"IsManager"				= :NEW."IsManager",
				"RestrictedApproval" = :NEW."RestrictedApproval",
				"Preferred"				= :NEW."Preferred",
				"Middle"					= :NEW."Middle",
				"Sex"						= :NEW."Sex",
				"Birth"					= :NEW."Birth",
				"Address1"				= :NEW."Address1",
				"Address2"				= :NEW."Address2",
				"City"					= :NEW."City",
				"Province"				= :NEW."Province",
				"Postal"					= :NEW."Postal",
				"AddressOther"			= :NEW."AddressOther",
				"HomeArea"				= :NEW."HomeArea",
				"HomePhone"				= :NEW."HomePhone",
				"AltArea"				= :NEW."AltArea",
				"AltPhone"				= :NEW."AltPhone",
				"Email"					= :NEW."Email",
				"Note"					= :NEW."Note",
				"DeptCode"				= :NEW."DeptCode",
				"DeptRoom"				= :NEW."DeptRoom",
				"DeptArea"				= :NEW."DeptArea",
				"DeptPhone"				= :NEW."DeptPhone",
				"AddNotes"				= :NEW."AddNotes",
				"EditNotes"				= :NEW."EditNotes",
				"EditTxs"				= :NEW."EditTxs",
				"RequireLabApp"		= :NEW."RequireLabApp",
				"CanApproveLabs"		= :NEW."CanApproveLabs",
				"ApprovePlanTx"		= :NEW."ApprovePlanTx",
				"ApproveCompTx"		= :NEW."ApproveCompTx",
				"ApproveExistingTx"	= :NEW."ApproveExistingTx",
				"ExistingNeedsApp"	= :NEW."ExistingNeedsApp",
				"IsGroupManager"		= :NEW."IsGroupManager",
				"Custom1"				= :NEW."Custom1",
				"Custom2"				= :NEW."Custom2",
				"Custom3"				= :NEW."Custom3",
				"Custom4"				= :NEW."Custom4",
				"Custom5"				= :NEW."Custom5",
				"Custom6"				= :NEW."Custom6",
				"Custom7"				= :NEW."Custom7",
				"Custom8"				= :NEW."Custom8",
				"Custom9"				= :NEW."Custom9",
				"Custom10"				= :NEW."Custom10",
				"ConditionNeedsApp"	= :NEW."ConditionNeedsApp",
				"ApproveConditionTx" = :NEW."ApproveConditionTx",
				"MobileId"				= :NEW."MobileId",
				"MobilePassword"		= :NEW."MobilePassword",
				"PerioNeedsApp"		= :NEW."PerioNeedsApp",
				"ApprovePerio"			= :NEW."ApprovePerio",
				"PerMeth"				= :NEW."PerMeth",
				"ApproveOrthoV"		= :NEW."ApproveOrthoV",
				"OrthoVNeedsApp"		= :NEW."OrthoVNeedsApp",
				"DeleteTxs"				= :NEW."DeleteTxs",
				"DrugsOnDemand"		= :NEW."DrugsOnDemand",
				"RequireASAApproval" = :NEW."RequireASAApproval",
				"SchClinic"				= :NEW."SchClinic",
				"ApprovePrescript"	= :NEW."ApprovePrescript",
				"AutoLock"				= :NEW."AutoLock",
				"DefaultBank"			= :NEW."DefaultBank",
				"UseActiveDir"			= :NEW."UseActiveDir",
				"ProblemsNeedApp"		= :NEW."ProblemsNeedApp",
				"ApproveProblems"		= :NEW."ApproveProblems",
				"StartupMDI"	      = :NEW."StartupMDI",
				"ApproveInvOrder"		= :NEW."ApproveInvOrder",
		      "ApproveNotes"			= :NEW."ApproveNotes",
		      "ApproveEHRForms"		= :NEW."ApproveEHRForms",
		      "ApproveStartChks"	= :NEW."ApproveStartChks",
		      "AssignTxs"				= :NEW."AssignTxs",
		      "ApproveNoTxConsent" = :NEW."ApproveNoTxConsent",
		      "EditAppts"				= :NEW."EditAppts",
		      "CanAbortEvals"		= :NEW."CanAbortEvals",
				"IsInstructor"			= :NEW."IsInstructor",
		      "CanEvaluate"			= :NEW."CanEvaluate",
		      "ApproveTxPlan"		= :NEW."ApproveTxPlan",
		      "ApproveDispLock"		= :NEW."ApproveDispLock",
		      "ApproveUndefDrugs"  = :NEW."ApproveUndefDrugs",
		      "AutoLockErr"			= :NEW."AutoLockErr",
		      "PlanNeedsApp"			= :NEW."PlanNeedsApp",
		      "CompNeedsApp"			= :NEW."CompNeedsApp",
		      "MsgRefreshRate"		= :NEW."MsgRefreshRate",
		      "NeedsTxPlanApp"		= :NEW."NeedsTxPlanApp",
				"MaxSchDays" 			= :NEW."MaxSchDays",
				"MaxApptReqDays"		= :NEW."MaxApptReqDays",
				"Credentials"			= :NEW."Credentials",
		      "EditLabs"				= :NEW."EditLabs",
		      "LettersNeedApp"     = :NEW."LettersNeedApp",
		      "ApproveLetters"     = :NEW."ApproveLetters",
		      "MsgAuthenticate"		= :NEW."MsgAuthenticate",
		      "MsgOutOfOffice"     = :NEW."MsgOutOfOffice",
		      "MsgOutOfOfficeText"	= :NEW."MsgOutOfOfficeText",
            "DefaultInfoMgrTab"	= :NEW."DefaultInfoMgrTab",
            "EnforcePIN"			= :NEW."EnforcePIN",
            "PIN"						= :NEW."PIN",
            "PINLocked"				= :NEW."PINLocked",
            "ProxyAppMode"			= :NEW."ProxyAppMode",
            "OpenSchClinicMode"	= :NEW."OpenSchClinicMode",	-- E58570
            "CanUseEmergMode"    = :NEW."CanUseEmergMode",
            -- E79977
            "PrescribeCS" = :NEW."PrescribeCS",
            "PrescribeCSSchedule" = :NEW."PrescribeCSSchedule",
            "PrescribeNarcotic" = :NEW."PrescribeNarcotic",
            "ApproveCS" = :NEW."ApproveCS",
            "ApproveCSSchedule" = :NEW."ApproveCSSchedule",
            "ApproveNarcotic" = :NEW."ApproveNarcotic",
            "CanUseERx" = :NEW."CanUseERx",							-- E120324
            "AutoSpellChk" = :NEW."AutoSpellChk",					-- E135371
            "PrescribeProxyMode" = :NEW."PrescribeProxyMode",	-- E125820
            "MsgAccess"		=	:NEW."MsgAccess",						-- E135371
            "EnterAlerts"	=	:NEW."EnterAlerts",					-- E126674
            "EnterAllergies"	=	:NEW."EnterAllergies",			-- E126674
            "EnterMedProb"	=	:NEW."EnterMedProb",					-- E126674
            "ChartLockDelay" = :NEW."ChartLockDelay",        -- AX-1963
            "TempChartUnlock" = :NEW."TempChartUnlock",     -- AX-2825
            "TempChartUnlockDays" = :NEW."TempChartUnlockDays",     -- AX-2825
            "TempChartUnlockHours" = :NEW."TempChartUnlockHours",     -- AX-2825
            "CanTempChartUnlock" = :NEW."CanTempChartUnlock",     -- AX-2825
            "EMailSubscribe" = :NEW."EMailSubscribe",     -- AX-11524
            "EMailNotify" = :NEW."EMailNotify",            -- AX-11524
        "SurgeryNeedsApp" = :NEW."SurgeryNeedsApp",		-- AX-14377.16070
        "ApproveSurgery" = :NEW."ApproveSurgery",		-- AX-14377.16070	
        "ApproveDrugWaste" = :NEW."ApproveDrugWaste",		-- AX-14377.16070
		  "CallCenterId" = :NEW."CallCenterId",					-- AX-18468.18814
		  "CallCenterPrompt" = :NEW."CallCenterPrompt",		-- AX-18468.19037
		  "EMailForward" = :NEW."EMailForward",				-- AX-21383
		  "RequestApproval" = :NEW."RequestApproval",		-- AX-21873.22007
		  "MsgDismissHighPrior" = :NEW."MsgDismissHighPrior",	-- AX-23702
		  "DeletePerioExam" = :NEW."DeletePerioExam",	-- AX-24346
		      "MsgOutOfOfficeStart"	= :NEW."MsgOutOfOfficeStart",	--AX-25510
		      "MsgOutOfOfficeEnd"	= :NEW."MsgOutOfOfficeEnd"	--AX-25510	

			WHERE "User" = :NEW."User" AND "Audit" = AuditId;
		ELSE
			INSERT INTO USERSHIS VALUES (
				USERSHIS_UsersHis_SEQ.nextval,
				:NEW."User",
				:NEW."Logon",
				:NEW."Name",
				:NEW."Password",
				:NEW."Level",
				:NEW."Producer",
				:NEW."Deleted",
				:NEW."ClaimDoctor",
				:NEW."Locked",
				:NEW."Scheduler",
				:NEW."RestrictDays",
				:NEW."First",
				:NEW."DisableAutoChart",
				:NEW."MaxChartOut",
				:NEW."MaxHoursOut",
				:NEW."EffDate",
				:NEW."ExpDate",
				:NEW."SwipeLogon",
				:NEW."SwipePassword",
				:NEW."PwdLastChanged",
				:NEW."MinSchHours",
				:NEW."Import",
				:NEW."MinContacts",
				:NEW."AddSteps",
				:NEW."ConsultantType",
				:NEW."IsManager",
				:NEW."RestrictedApproval",
				:NEW."Preferred",
				:NEW."Middle",
				:NEW."Sex",
				:NEW."Birth",
				:NEW."Address1",
				:NEW."Address2",
				:NEW."City",
				:NEW."Province",
				:NEW."Postal",
				:NEW."AddressOther",
				:NEW."HomeArea",
				:NEW."HomePhone",
				:NEW."AltArea",
				:NEW."AltPhone",
				:NEW."Email",
				:NEW."Note",
				:NEW."DeptCode",
				:NEW."DeptRoom",
				:NEW."DeptArea",
				:NEW."DeptPhone",
				:NEW."AddNotes",
				:NEW."EditNotes",
				:NEW."EditTxs",
				:NEW."RequireLabApp",
				:NEW."CanApproveLabs",
				:NEW."ApprovePlanTx",
				:NEW."ApproveCompTx",
				:NEW."ApproveExistingTx",
				:NEW."ExistingNeedsApp",
				:NEW."IsGroupManager",
				:NEW."Custom1",
				:NEW."Custom2",
				:NEW."Custom3",
				:NEW."Custom4",
				:NEW."Custom5",
				:NEW."Custom6",
				:NEW."Custom7",
				:NEW."Custom8",
				:NEW."Custom9",
				:NEW."Custom10",
				:NEW."ConditionNeedsApp",
				:NEW."ApproveConditionTx",
				:NEW."MobileId",
				:NEW."MobilePassword",
				:NEW."PerioNeedsApp",
				:NEW."ApprovePerio",
				:NEW."PerMeth",
				:NEW."ApproveOrthoV",
				:NEW."OrthoVNeedsApp",
				:NEW."DeleteTxs",
				:NEW."DrugsOnDemand",
				:NEW."RequireASAApproval",
				:NEW."SchClinic",
				:NEW."ApprovePrescript",
				:NEW."AutoLock",
				:NEW."DefaultBank",
				AuditId,
				:NEW."UseActiveDir",
				:NEW."ProblemsNeedApp",
				:NEW."ApproveProblems",
				:NEW."StartupMDI",
				:NEW."ApproveInvOrder",
		      :NEW."ApproveNotes",
		      :NEW."ApproveEHRForms",
		      :NEW."ApproveStartChks",
		      :NEW."AssignTxs",
		      :NEW."ApproveNoTxConsent",
		      :NEW."EditAppts",
		      :NEW."CanAbortEvals",
		      :NEW."IsInstructor",
		      :NEW."CanEvaluate",
		      :NEW."ApproveTxPlan",
		      :NEW."ApproveDispLock",
		      :NEW."ApproveUndefDrugs",
		      :NEW."AutoLockErr",
		      :NEW."PlanNeedsApp",
		      :NEW."CompNeedsApp",
		      :NEW."MsgRefreshRate",
		      :NEW."NeedsTxPlanApp",
				:NEW."MaxSchDays",
				:NEW."MaxApptReqDays",
				:NEW."Credentials",
				:NEW."EditLabs",
				:NEW."LettersNeedApp",
				:NEW."ApproveLetters",
				:NEW."MsgAuthenticate",
				:NEW."MsgOutOfOffice",
				:NEW."MsgOutOfOfficeText",
				:NEW."DefaultInfoMgrTab",
				:NEW."EnforcePIN",
				:NEW."PIN",
				:NEW."PINLocked",
				:NEW."ProxyAppMode",
            :NEW."OpenSchClinicMode",	-- E58570
            :NEW."CanUseEmergMode",
            :NEW."PrescribeCS",
            :NEW."PrescribeCSSchedule",
            :NEW."PrescribeNarcotic",
            :NEW."ApproveCS",
            :NEW."ApproveCSSchedule",
            :NEW."ApproveNarcotic",
            :NEW."CanUseERx",				-- E120324
            :NEW."PrescribeProxyMode",	-- E125820
            :NEW."AutoSpellChk",			-- E135371
            :NEW."MsgAccess",				-- E129605
            :NEW."EnterAlerts",			-- E126674
            :NEW."EnterAllergies",		-- E126674
            :NEW."EnterMedProb",			-- E126674
            :NEW."ChartLockDelay",     -- AX-1963
            :NEW."TempChartUnlock",   -- AX-2825
            :NEW."TempChartUnlockDays",   -- AX-2825
            :NEW."TempChartUnlockHours",   -- AX-2825
            :NEW."CanTempChartUnlock",   -- AX-2825
            :NEW."EMailSubscribe",        -- AX-11524
            :NEW."EMailNotify",            -- AX-11524
        :NEW."SurgeryNeedsApp",		-- AX-14377.16070
        :NEW."ApproveSurgery",		-- AX-14377.16070	
        :NEW."ApproveDrugWaste",		-- AX-14377.16070
		  :NEW."CallCenterId",			-- AX-18468.18814
		  :NEW."CallCenterPrompt",		-- AX-18468.19037
		  :NEW."EMailForward",			-- AX-21383
		  :NEW."RequestApproval",		-- AX-21873.22007
	    :NEW."MsgDismissHighPrior",		-- AX-23702
		:NEW."DeletePerioExam",		-- AX-24346
		:NEW."MsgOutOfOfficeStart",		-- AX-25510
		:NEW."MsgOutOfOfficeEnd"		-- AX-25510	

			);
		END IF;
	END IF;
END$trigger$
 ;
CREATE TRIGGER createusersmsg AFTER INSERT OR DELETE OR UPDATE OF "Status" ON msgsent FOR EACH ROW  $trigger$DECLARE

	v_User			USERSMSG."User"%TYPE;
	
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


	-- get User
	IF DELETING THEN
		v_User := :OLD."User";
	ELSE
		v_User := :NEW."User";
	END IF;

	

	-- UPSERT into USERSMSG
	UPDATE USERSMSG
		SET "Time" = SYSDATE
		WHERE "User" = v_User;
	IF SQL%NOTFOUND THEN
		INSERT INTO USERSMSG VALUES (v_User, SYSDATE);
	END IF;


END$trigger$
 ;
CREATE TRIGGER createvacaseth AFTER INSERT OR UPDATE ON vacaset FOR EACH ROW  $trigger$DECLARE
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  IF :NEW."Type" = 0 THEN
	  INSERT INTO VACASETH VALUES (
        VACASETH_VacaSetH_SEQ.nextval,
		:NEW."VacaSet",
		:NEW."Type",
		:NEW."Provider",
		:NEW."User",
		:NEW."Description",
		:NEW."DisplayDesc",
		:NEW."StartDate",
		:NEW."EndDate",
		:NEW."StartTime",
		:NEW."EndTime",
		:NEW."Cycle",
		:NEW."CycleStart",
        :NEW."Monday",
        :NEW."Tuesday",
        :NEW."Wednesday",
        :NEW."Thursday",
        :NEW."Friday",
        :NEW."Saturday",
        :NEW."Sunday",
        :NEW."Imported",
		:NEW."Deleted",
		:NEW."Audit",
        :NEW."Color",
	    :NEW."CycleType",
	    :NEW."CycleFrq",
	    :NEW."IsBreak",
      :NEW."AvailableClinic"
        );
  END IF;
END$trigger$
 ;
CREATE TRIGGER createvacatnh AFTER INSERT OR UPDATE ON vacation FOR EACH ROW  $trigger$DECLARE
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  IF :NEW."Type" = 0 THEN
	  INSERT INTO VACATNH VALUES (
        VACATNH_VacatnH_SEQ.nextval,
		:NEW."Id",
		:NEW."Provider",
		:NEW."Description",
		:NEW."StartDate",
		:NEW."StartTime",
		:NEW."EndTime",
		:NEW."User",
		:NEW."Type",
		:NEW."DisplayDesc",
		:NEW."Deleted",
		:NEW."AuditId",
        :NEW."Color",
        :NEW."VacaSet",
        :NEW."SetException",
        :NEW."IsBreak",
        :NEW."AvailableClinic"
         );
  END IF;
END$trigger$
 ;
CREATE TRIGGER createwaitlhis BEFORE INSERT OR UPDATE OF "WaitRsn", "Priority", "Status" ON waitlist FOR EACH ROW  $trigger$DECLARE
  AuditId		NUMBER (10);
  HistoryType  NUMBER (5);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

	AuditId := :NEW."Audit";

	-- handle if action done outside of axium	
	IF :OLD."Audit" = :NEW."Audit" THEN
		SELECT AUDITHIS_AUDIT_SEQ.nextval INTO AuditId FROM DUAL;
		
		IF INSERTING THEN
			HistoryType := 1;
		ELSE
			HistoryType := 2;
		END IF;
		
		INSERT INTO AUDITHIS VALUES (
			AuditId,	
			trunc(sysdate),
			trunc(to_char(sysdate,'SSSSS')/60),	
			-1, -- UserId,  B37408
			0, -- StationId
			'WAITLIST',
			HistoryType
		);
		
		:NEW."Audit" := AuditId;
	END IF;	
	INSERT INTO WAITLHIS VALUES (
		WAITLHIS_WaitLHis_SEQ.nextval,
		:NEW."WaitList",
		:NEW."Appointment",
		:NEW."WaitRsn",
		:NEW."Priority",
		:NEW."Note",
		:NEW."Status",
		:NEW."CreateAudit",
		AuditId
	);
END$trigger$
 ;
CREATE TRIGGER createwrkschh AFTER INSERT OR UPDATE ON workschd FOR EACH ROW  $trigger$DECLARE
  WrkSchHVal 		NUMBER(10);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  IF :NEW."Type" = 0 THEN
  	SELECT WRKSCHH_WrkSchH_SEQ.nextval INTO WrkSchHVal FROM dual;
  	INSERT INTO WRKSCHH VALUES (WrkSchHVal,
  	  :NEW."Id",
  	  :NEW."Provider",
  	  :NEW."Description",
  	  :NEW."StartDate",
  	  :NEW."EndDate",
  	  :NEW."Monday",
  	  :NEW."Tuesday",
  	  :NEW."Wednesday",
  	  :NEW."Thursday",
  	  :NEW."Friday",
  	  :NEW."Saturday",
  	  :NEW."Sunday",
  	  :NEW."Cycle",
  	  :NEW."CycleStart",
  	  :NEW."WorkSchType",
  	  :NEW."ExcWorkSchId",
  	  :NEW."User",
  	  :NEW."Type",
  	  :NEW."Deleted",
  	  :NEW."AuditId",
  	  :NEW."CycleType",
	  :NEW."CycleFrq" );
  END IF;
END$trigger$
 ;
CREATE TRIGGER createwschitmh AFTER INSERT OR UPDATE ON wschitem FOR EACH ROW  $trigger$DECLARE
  WSchItmHVal 		NUMBER(10);
  TypeVal			NUMBER(5);
BEGIN

   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  SELECT "Type" INTO TypeVal FROM WORKSCHD WHERE "Id" = :NEW."WorkschdId";
  IF TypeVal = 0 THEN
	  SELECT WSCHITMH_WSchItmH_SEQ.nextval INTO WSchItmHVal FROM dual;
	  INSERT INTO WSCHITMH VALUES (WSchItmHVal,
		:NEW."Id",
		:NEW."WorkschdId",
		:NEW."Weekday",
		:NEW."StartTime",
		:NEW."EndTime",	
		:NEW."Clinic",	
		:NEW."NumChairs",
		:NEW."ClinicTime",	
		:NEW."PGroup",
		:NEW."Deleted",
		:NEW."AuditId",
        :NEW."ReserveChangeDate",
        :NEW."BreakT",
        :NEW."UseSharedChairs" );
  END IF;
END$trigger$
 ;
CREATE TRIGGER deletelinkinidef AFTER DELETE ON linkdef FOR EACH ROW  $trigger$BEGIN
	
   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

	DELETE FROM INIITEM II WHERE II."Inidef" IN (
		select ID."Inidef" from INIDEF ID
		where ID."Section" = 'Links'
		and ID."Key" = 'Link'||TO_CHAR(:OLD."LinkDef")||'Flag');
	
	DELETE FROM INIDEF ID
		where ID."Section" = 'Links'
		and ID."Key" = 'Link'||TO_CHAR(:OLD."LinkDef")||'Flag';


	DELETE FROM INIITEM II WHERE II."Inidef" IN (
		select ID."Inidef" from INIDEF ID
		where ID."Section" = 'Links'
		and ID."Key" = 'Link'||TO_CHAR(:OLD."LinkDef")||'Path');
	
	DELETE FROM INIDEF ID
		where ID."Section" = 'Links'
		and ID."Key" = 'Link'||TO_CHAR(:OLD."LinkDef")||'Path';
END$trigger$
 ;
CREATE TRIGGER faptwatch_trg BEFORE INSERT ON faptwatch FOR EACH ROW  $trigger$BEGIN
   -- AX-24111.24145 arr added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

	IF :NEW."Id" IS NULL THEN
		SELECT FAPTWATCH_FAPTWATCH_SEQ.nextval INTO :NEW."Id" FROM DUAL;
	END IF;
END$trigger$
 ;
CREATE TRIGGER ftaclexception_exceptionid BEFORE INSERT ON ftaclexception FOR EACH ROW  $trigger$BEGIN
  -- AX-24111.24145 arr added ability to disable triggers for the given sessions
  IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
     RETURN :new;
  END IF;

  SELECT FTACLEXCEPTION_EXCEPTIONID_SEQ.NEXTVAL INTO :new."ExceptionId" FROM dual;
END$trigger$
 ;
CREATE TRIGGER fuserticket_trg BEFORE INSERT ON fuserticket FOR EACH ROW  $trigger$BEGIN
	-- AX-24111.24145 arr added ability to disable triggers for the given sessions
	IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
		RETURN :new;
	END IF;
	
	IF :NEW."Id" IS NULL THEN
		SELECT FUSERTICKET_FUSERTICKET_SEQ.nextval INTO :NEW."Id" FROM DUAL;
	END IF;
END$trigger$
 ;
CREATE TRIGGER ilog_trg BEFORE INSERT ON ilog FOR EACH ROW  $trigger$BEGIN
   -- AX-24111.24145 arr added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

	IF :NEW."iLog" IS NULL THEN
		SELECT ILOG_ILOG_SEQ.nextval INTO :NEW."iLog" FROM DUAL;
	END IF;
END$trigger$
 ;
CREATE TRIGGER isecureq_trg BEFORE INSERT ON isecureq FOR EACH ROW  $trigger$BEGIN
   -- AX-24111.24145 arr added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


	IF :NEW."iSecureQ" IS NULL THEN
		SELECT ISECUREQ_ISECUREQ_SEQ.nextval INTO :NEW."iSecureQ" FROM DUAL;
	END IF;
END$trigger$
 ;
CREATE TRIGGER isetting_trg BEFORE INSERT ON isetting FOR EACH ROW  $trigger$BEGIN
	-- AX-24111.24145 arr added ability to disable triggers for the given sessions
	IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
		RETURN :new;
	END IF;

	IF :NEW."iSetting" IS NULL THEN
		SELECT ISETTING_ISETTING_SEQ.nextval INTO :NEW."iSetting" FROM DUAL;
	END IF;
END$trigger$
 ;
CREATE TRIGGER isettinggrp_trg BEFORE INSERT ON isettinggrp FOR EACH ROW  $trigger$BEGIN
	-- AX-24111.24145 arr added ability to disable triggers for the given sessions
	IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
		RETURN :new;
	END IF;

	IF :NEW."iSettingGrp" IS NULL THEN
		SELECT ISETTINGGRP_ISETTINGGRP_SEQ.nextval INTO :NEW."iSettingGrp" FROM DUAL;
	END IF;
END$trigger$
 ;
CREATE TRIGGER isettingovr_trg BEFORE INSERT ON isettingovr FOR EACH ROW  $trigger$BEGIN
	-- AX-24111.24145 arr added ability to disable triggers for the given sessions
	IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
		RETURN :new;
	END IF;
	
	IF :NEW."iSettingOvr" IS NULL THEN
		SELECT ISETTINGOVR_ISETTINGOVR_SEQ.nextval INTO :NEW."iSettingOvr" FROM DUAL;
	END IF;
END$trigger$
 ;
CREATE TRIGGER istickynote_trg BEFORE INSERT ON istickynote FOR EACH ROW  $trigger$BEGIN
   -- AX-24111.24145 arr added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;


	IF :NEW."Auto" IS NULL THEN
		SELECT ISTICKYNOTE_ISTICKYNOTE_SEQ.nextval INTO :NEW."Auto" FROM DUAL;
	END IF;
END$trigger$
 ;
CREATE TRIGGER iuserpwh_trg BEFORE INSERT ON iuserpwh FOR EACH ROW  $trigger$BEGIN
   -- AX-24111.24145 arr added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

	IF :NEW."iUserPwhId" IS NULL THEN
		SELECT IUSERPWH_IUSERPWH_SEQ.nextval INTO :NEW."iUserPwhId" FROM DUAL;
	END IF;
END$trigger$
 ;
CREATE TRIGGER pafiles_trg BEFORE INSERT ON pafiles FOR EACH ROW  $trigger$BEGIN
	-- AX-24111.24145 arr added ability to disable triggers for the given sessions
	IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
		RETURN :new;
	END IF;

	SELECT PAFILES_PAFILESID_SEQ.nextval INTO :NEW."PAFILESID" FROM DUAL;
END$trigger$
 ;
CREATE TRIGGER panav_trg BEFORE INSERT ON panav FOR EACH ROW  $trigger$BEGIN
	-- AX-24111.24145 arr added ability to disable triggers for the given sessions
	IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
		RETURN :new;
	END IF;

	SELECT PANAV_PANAVID_SEQ.nextval INTO :NEW."PANAVID" FROM DUAL;
END$trigger$
 ;
CREATE TRIGGER panavcontent_trg BEFORE INSERT ON panavcontent FOR EACH ROW  $trigger$BEGIN
	-- AX-24111.24145 arr added ability to disable triggers for the given sessions
	IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
		RETURN :new;
	END IF;

	SELECT PACONTENT_PACONTENTID_SEQ.nextval INTO :NEW."PANAVCONTENTID" FROM DUAL;
END$trigger$
 ;
CREATE TRIGGER patemplate_trg BEFORE INSERT ON patemplate FOR EACH ROW  $trigger$BEGIN
	-- AX-24111.24145 arr added ability to disable triggers for the given sessions
	IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
		RETURN :new;
	END IF;
	SELECT PATEMPLATE_PATEMPLATEID_SEQ.nextval INTO :NEW."PATEMPLATEID" FROM DUAL;
END$trigger$
 ;
CREATE TRIGGER ptinsert BEFORE INSERT ON patient FOR EACH ROW  $trigger$BEGIN
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

    IF (:NEW."ContactAt" = 0) THEN
      :NEW."ContactAt" := 1;
    END IF;
END$trigger$
 ;
CREATE TRIGGER "trg_elmah$error_bi" BEFORE INSERT ON "elmah$error" FOR EACH ROW  $trigger$BEGIN
	-- AX-24111.24145 arr added ability to disable triggers for the given sessions
	IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
		RETURN :new;
	END IF;

    SELECT elmah$error_seq.NEXTVAL INTO :new.sequencenumber FROM dual;
END$trigger$
 ;
CREATE TRIGGER updatelinkinidef AFTER UPDATE ON linkdef FOR EACH ROW  $trigger$BEGIN
   -- AX-24111 j.s added ability to disable triggers for the given sessions
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

	UPDATE INIDEF
	   SET "Description" = 'Hide or show this link in the program' || CHR(13) || CHR(10) || :NEW."Name" || CHR(13) || CHR(10) || substr(:NEW."Execute", 1, 2000)
	 WHERE "Section" = 'Links' AND "Key" = 'Link'||TO_CHAR(:NEW."LinkDef")||'Flag';
	
	UPDATE INIDEF
	   SET "Description" = 'Override path for this link' || CHR(13) || CHR(10) || :NEW."Name" || CHR(13) || CHR(10) || substr(:NEW."Execute", 1, 2000)
	 WHERE "Section" = 'Links' AND "Key" = 'Link'||TO_CHAR(:NEW."LinkDef")||'Path';

END$trigger$
 ;
CREATE TRIGGER updatetreatme2 BEFORE INSERT ON treatme2 FOR EACH ROW  $trigger$BEGIN
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

    IF (:NEW."ParentId" = 0) THEN
      :NEW."ParentId" := -:NEW."Auto";
    END IF;
END$trigger$
 ;
CREATE TRIGGER updateusers BEFORE UPDATE OF "Password" ON users FOR EACH ROW  $trigger$BEGIN
   IF ( ARCHIVE_PKG.GETDISABLETRIGGERSFLAG() = 1 ) THEN
      RETURN :new;
   END IF;

  IF (:NEW."Password" IS NOT NULL AND :NEW."Password" != ' 'AND :NEW."Password" != :OLD."Password") THEN
    :NEW."PwdLastChanged" := sysdate;
  END IF;
END$trigger$
 ;
 
-- VIEW TRIGGERS 
CREATE TRIGGER ptletter_insteadof INSTEAD OF INSERT OR DELETE OR UPDATE ON ptletter FOR EACH ROW  $trigger$BEGIN
  if INSERTING then
    -- insert a new PLTDETAILS first
    INSERT INTO PTLDETAILS("PtLetter", "Patient", "Description", "Date", "User", "Path", "Type", "Deleted", "StationId", "FileExt", "DelAudit", "AtTab", "Consent", "ExpiryDate", "Status", "OrigId", "AuditNumber", "DocTempl", "AppUser", "AppDate", "ModifiedDate", "OwnerType", "OwnerId", "AddDateTime")
    VALUES(:NEW."PtLetter", :NEW."Patient", :NEW."Description", :NEW."Date", :NEW."User", :NEW."Path", :NEW."Type", :NEW."Deleted", :NEW."StationId", :NEW."FileExt", :NEW."DelAudit", :NEW."AtTab", :NEW."Consent", :NEW."ExpiryDate", :NEW."Status", :NEW."OrigId", :NEW."AuditNumber", :NEW."DocTempl", :NEW."AppUser", :NEW."AppDate", :NEW."ModifiedDate", :NEW."OwnerType", :NEW."OwnerId", :NEW."AddDateTime");

    -- insert the PTLCONTENT
    INSERT INTO PTLCONTENT("PtLetter", CONTENT)
    VALUES(:NEW."PtLetter", :NEW.CONTENT);
  end if;

  if UPDATING then
    -- PLTCONENT first
    UPDATE PTLCONTENT SET CONTENT = :new.CONTENT WHERE "PtLetter" = :new."PtLetter";

    -- PTLDETAILS
    UPDATE PTLDETAILS SET
      --"PtLetter" = :new."PtLetter",
      "Patient" = :new."Patient",
      "Description" = :new."Description",
      "Date" = :new."Date",
      "User" = :new."User",
      "Path" = :new."Path",
      "Type" = :new."Type",
      "Deleted" = :new."Deleted",
      "StationId" = :new."StationId",
      "FileExt" = :new."FileExt",
      "DelAudit" = :new."DelAudit",
      "AtTab" = :new."AtTab",
      "Consent" = :new."Consent",
      "ExpiryDate" = :new."ExpiryDate",
      "Status" = :new."Status",
      "OrigId" = :new."OrigId",
      "AuditNumber" = :new."AuditNumber",
      "DocTempl" = :new."DocTempl",
      "AppUser" = :new."AppUser",
      "AppDate" = :new."AppDate",
      "ModifiedDate" = :new."ModifiedDate"
      WHERE "PtLetter" = :new."PtLetter";
  end if;

  if DELETING then
    -- delete PLTCONENT first
    DELETE FROM PTLCONTENT WHERE "PtLetter" = :old."PtLetter";

    -- delete the PTLDETAILS
    DELETE FROM PTLDETAILS WHERE "PtLetter" = :old."PtLetter";
  end if;

END$trigger$
 ;
 
-- FUNCTIONS 
CREATE OR REPLACE FUNCTION appointneeds(iappointment numeric, itype numeric, ifuturedates numeric)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
  Result NUMBER;

BEGIN
  Result := 0;
	
  BEGIN
	SELECT MIN(PT."PtPrev")
	INTO Result
	FROM PTPREV PT, PREVCARE P, APPOINT AP, APPTCODE AC WHERE
	AP. "Appointment" = iAppointment AND
	AP. "Patient" = PT. "Patient" AND
	AC. "ApptCode" = AP. "Code" AND
	AP. "Type" IN (0, 1, 2) AND
	AC. "IsHygiene" = 1 AND
	PT. "Completed" = 0 AND
	PT. "Deleted" = 0 AND
	PT. "PrevCare" = P. "PrevCare" AND
	P. "Type" = iType AND
	--(iFutureDates > 0 AND (SELECT current_date FROM dual) >= AP. "Date") AND
	(PT."DueDate" <= AP. "Date" + P. "WithinDays");
	EXCEPTION WHEN NO_DATA_FOUND THEN
		Result := 0;
  END;

  RETURN Result;	
END$function$
;
CREATE OR REPLACE FUNCTION appointneedsexam(iappointment numeric, ifuturedates numeric)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
	Result NUMBER;
BEGIN
	Result := AppointNeeds(iAppointment, 1, iFutureDates);
	RETURN Result;	
END$function$
;
CREATE OR REPLACE FUNCTION appointneedsxray(iappointment numeric, ifuturedates numeric)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
  Result NUMBER;
BEGIN
  Result := AppointNeeds(iAppointment, 2, iFutureDates);
  RETURN Result;	
END$function$
;
CREATE OR REPLACE FUNCTION apptind_hasadditionalappts(iappointment numeric)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
  nResult NUMBER;
BEGIN
   SELECT COUNT(1)
     INTO nResult
     FROM APPOINT A1,
    APPOINT A2
    WHERE A1."Appointment" = iAppointment
  AND A1."Appointment"    != A2."Appointment"
  AND A1. "Type"          IN (0, 1, 2)
  AND A2. "Type"          IN (0, 1, 2)
  AND A1."Patient"         = A2."Patient"
  AND A1."Date"            = A2."Date"
  AND A1."From"           <  A2."From";
  IF nResult > 0 THEN
  nResult := 1;
  ELSE
   nResult := 0;
  END IF;
  RETURN nResult;
END$function$
;
CREATE OR REPLACE FUNCTION apptind_haseligibility(iappointment numeric)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
  nResult NUMBER;
  nEligResult NUMBER;
	
  -- cursor to retrieve all policies that the patient is covered under on the day of the appointment
  -- by looking at treatments tied to the appointment
  CURSOR C1 IS
    SELECT P."PolIns", A."Patient", A."Date" FROM APPOINT A, POLICY P, PTDEPEND PD, INSURANC I
    	WHERE A."Appointment" = iAppointment
    	AND A."Patient" = PD."Patient" AND PD."PolicyId" = P."PolicyId"
    	AND P."Company" = I."Company"
    	AND P."Deleted" = 0 AND PD."Deleted" = 0 AND PD."IsCovered" > 0
    	AND A."Date" BETWEEN NVL(P."StartDate", A."Date") AND NVL(P."ResetDate", A."Date")
    	AND A."Date" BETWEEN NVL(PD."StartDate", A."Date") AND NVL(PD."EndDate", A."Date")
    	AND I."EligFormat" > 0
    ;

BEGIN

  nResult := 0;	

  FOR rec IN C1 LOOP
	
    -- look up the last eligibility check for the policy
    BEGIN
      SELECT "Result" INTO nEligResult
      FROM LASTEDIELIG_VIEW
      WHERE "Patient" = rec."Patient" AND "PolIns" = rec."PolIns"
      AND "Date" >= rec."Date"-30;
    EXCEPTION WHEN NO_DATA_FOUND THEN
      -- unknown
      nEligResult := 0;
    END;

    -- PROCESS RESULTS
    -- this policy is eligible
    IF nEligResult = 1 THEN

      -- if first policy processed
      IF nResult = 0 THEN
        -- indicate all eligible so far
        nResult := 1;

      END IF;

    -- this policy is any other status (unknown, not eligible, error, system error, not found)
    ELSE

      -- indicate at least 1 policy does not have a successful check
      nResult := 2;
      EXIT; -- stop loop, no need to continue processing

    END IF;

	
  END LOOP;


  RETURN nResult;	
	
END$function$
;
CREATE OR REPLACE FUNCTION apptind_hasinactivetx(iappointment numeric)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
	nResult NUMBER;
	nPtPrev NUMBER;
BEGIN

	nResult := 0;	
	
		BEGIN
			SELECT COUNT(1) INTO nResult FROM APPTRX A, TRX T, STATUS S WHERE A."Type" = T."Type" AND A."Id" = T."Id" AND
         A."Treatment" = T."Treatment" AND A."Appointment" = iAppointment and T."Deleted" = 0 AND T."TxStatus" = S."Status"
         AND S."Type" = 3 AND S."MakeInactive" = 1;
			EXCEPTION WHEN NO_DATA_FOUND THEN
				nResult := 0;
    END;
		
	IF nResult > 0 THEN
    nResult := 1;
  END IF;
	
	RETURN nResult;	
	
END$function$
;
CREATE OR REPLACE FUNCTION arasatproc(openasatdate timestamp without time zone, endasatdate timestamp without time zone)
 RETURNS TABLE(":B1" numeric, ":B2" numeric)
 LANGUAGE edbspl
AS $function$

  OPENAR NUMBER := 0.0;

  ENDAR NUMBER := 0.0;

BEGIN

  OPENAR := ARASAT_PKG.ARASAT(OpenAsAtDate);

  ENDAR := ARASAT_PKG.ARASAT(EndAsAtDate);



  RETURN QUERY

   select OPENAR ":B1", ENDAR ":B2" from dual;

END

$function$
;
CREATE OR REPLACE FUNCTION arasatproc_i(openasatdate timestamp without time zone, endasatdate timestamp without time zone)
 RETURNS TABLE(":B1" numeric, ":B2" numeric)
 LANGUAGE edbspl
AS $function$

  OPENAR NUMBER := 0.0;

  ENDAR NUMBER := 0.0;

BEGIN

  OPENAR := ARASAT_PKG.ARASAT_I(OpenAsAtDate);

  ENDAR := ARASAT_PKG.ARASAT_I(EndAsAtDate);



  RETURN QUERY

   select OPENAR ":B1", ENDAR ":B2" from dual;

END

$function$
;
CREATE OR REPLACE FUNCTION assignedbutnotxplan(patient numeric, provider character)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$ 

  days NUMBER;

  PtProdCount NUMBER;



BEGIN

  days := -1;



  SELECT COUNT("Producer") into PtProdCount FROM PtProd PT

    WHERE PT."Patient"=Patient and PT."Producer"=Provider and

          PT."StartDate" <= sysdate and PT."EndDate" >= sysdate and

          PT."StartDate" > (SELECT max(T."TreatmentDate") FROM Trx T 

          WHERE T."Patient"=Patient and T."Type" IN (1,5) and T."Deleted"=0 and

                T."TreatmentDate" <= sysdate and T."Producer"=PT."Producer");



  IF PtProdCount > 0 THEN

    SELECT CALCULATEDAYSDIFF_S(sysdate,max(PT."StartDate")) into days FROM PtProd PT -- AX39652

      WHERE PT."Patient"=Patient and PT."Producer"=Provider and

            PT."StartDate" <= sysdate and PT."EndDate" >= sysdate and

            PT."StartDate" > (SELECT max(T."TreatmentDate") FROM Trx T 

            WHERE T."Patient"=Patient and T."Type" IN (1,5) and T."Deleted"=0 and

                  T."TreatmentDate" <= sysdate and T."Producer"=PT."Producer");

  END IF;



  RETURN days;	

END$function$
;
CREATE OR REPLACE FUNCTION bleedcount(patientval numeric)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$

  CountVal    NUMBER;

  PtPerioVal  NUMBER;



  CURSOR C1 IS SELECT * FROM PERCOND WHERE "CondType" = 4 AND "Status" = 0;

BEGIN

  CountVal := 0;



  FOR rec IN C1 LOOP

    PtPerioVal := LastPtPerCo(PatientVal, rec."PerCond");		-- E33252

    CountVal := CountVal + GetCountPerioDValNE(PtPerioVal, rec."PerCond", 0.0);

  END LOOP;



  RETURN (CountVal);

END$function$
;
CREATE OR REPLACE FUNCTION calculatedaysdiff_s(enddate timestamp without time zone, startdate timestamp without time zone)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$

BEGIN

	RETURN EXTRACT(days from endDate - startDate); 

END

$function$
;
CREATE OR REPLACE FUNCTION cds_indicator(userid numeric, ppatient numeric)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
    vCalcVal         NUMBER :=0;
    vBP              NUMBER :=0;
    vBMI             NUMBER :=0;
    vSMK             NUMBER :=0;
    vPNE             NUMBER :=0;
    vFLU             NUMBER :=0;
    vASA             NUMBER :=0;

BEGIN
  BEGIN
    SELECT MU_CORE_PKG.CORE11_CDS_BP( pPatient )  INTO vBP  FROM DUAL;
    SELECT MU_CORE_PKG.CORE11_CDS_BMI( pPatient ) INTO vBMI FROM DUAL;
    SELECT MU_CORE_PKG.CORE11_CDS_SMK( pPatient ) INTO vSMK FROM DUAL;
    SELECT MU_CORE_PKG.CORE11_CDS_PNE( pPatient ) INTO vPNE FROM DUAL;
    SELECT MU_CORE_PKG.CORE11_CDS_FLU( pPatient ) INTO vFLU FROM DUAL;
    SELECT MU_CORE_PKG.CORE11_CDS_ASA( pPatient ) INTO vASA FROM DUAL;

    IF vBP > 0 OR vBMI > 0 OR vSMK > 0 OR vPNE > 0 OR vFLU > 0 OR vASA > 0 THEN
        vCalcVal := 1;
    ELSIF vBP + vBMI + vSMK + vPNE + vFLU + vASA = 0 THEN
        vCalcVal := 0;
    END IF;

    EXCEPTION
      WHEN OTHERS THEN
        RETURN 0;
  END;
  RETURN vCalcVal;
END$function$
;
CREATE OR REPLACE FUNCTION coverttoactualsite(arch numeric, site numeric, pos numeric)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$

  SiteNum   NUMBER(5);   

BEGIN

   if Arch = 0 THEN

      if Pos = 0 THEN

         SiteNUm := Site;

      ELSE

         SiteNUm := 17 - Site;

      END IF;

   ELSE

      if Pos = 0 THEN

         SiteNUm := 33 - Site;

      ELSE

         SiteNUm := 16 + Site;

      END IF;

   END IF;



   RETURN (SiteNum);

END$function$
;
CREATE OR REPLACE FUNCTION createalloctxs_p(pdepartment character varying, pfromdate timestamp without time zone, ptodate timestamp without time zone, pgroupby1 integer DEFAULT 0, pgroupby2 integer DEFAULT 0, pisdetailed integer DEFAULT 1, ppatient numeric DEFAULT 0, porigrecno numeric DEFAULT 0)
 RETURNS TABLE("AllocatH" numeric, "PayType" numeric, "TrxType" numeric, "TrxId" numeric, "TrxTreatment" numeric, "Amount" numeric, "AllocateLink" numeric, "TxHistoryId" numeric, "PmtHistoryId" numeric, "OrigRecNo" numeric, "History" numeric, "HistoryType" numeric, "Patient" numeric, "TxModifiedDate" timestamp without time zone, "Payed" numeric, "InsPayed" numeric, "PtAdj" numeric, "InsAdj" numeric, "InsTransfer" numeric, "Discipline" character, "Procedure" character, "Practice" numeric, "ClaimDoctor" character, "Location" character, "EntryUser" numeric, "AppUser" numeric, "Custom1" character, "Custom2" character, "Producer" character, "TypeCode" character, "PGroup" character, "Year" numeric, "CustomCode1" character, "CustomCode2" character, "CustomCode3" character, "CustomCode4" character, "CustomCode5" character, "CustomCode6" character, "CustomCode7" character, "CustomCode8" character, "CustomCode9" character, "CustomCode10" character, "Department" character, "HistoryTypeDescription" character, "GroupBy1" numeric, "GroupBy2" numeric, "PreviousHistory" numeric, "PreviousDiscipline" character, "PreviousProcedure" character, "PreviousPractice" numeric, "PreviousPracticeName" character, "PreviousClaimDoctor" character, "PreviousLocation" character, "PreviousEntryUser" numeric, "PreviousEntryUserLogon" character, "PreviousEntryUserFirstName" character, "PreviousEntryUserLastName" character, "PreviousAppUser" numeric, "PreviousAppUserLogon" character, "PreviousAppUserFirstName" character, "PreviousAppUserLastName" character, "PreviousCustom1" character, "PreviousCustom2" character, "PreviousProducer" character, "PreviousProducerFirstName" character, "PreviousProducerMiddleName" character, "PreviousProducerLastName" character, "PreviousTypeCode" character, "PreviousTypeCodeDescription" character, "PreviousPGroup" character, "PreviousYear" numeric, "PreviousCustomCode1" character, "PreviousCustomCode2" character, "PreviousCustomCode3" character, "PreviousCustomCode4" character, "PreviousCustomCode5" character, "PreviousCustomCode6" character, "PreviousCustomCode7" character, "PreviousCustomCode8" character, "PreviousCustomCode9" character, "PreviousCustomCode10" character, "PreviousDepartment" character, "PreviousPayed" numeric, "PreviousInsPayed" numeric, "PreviousPtAdj" numeric, "PreviousInsAdj" numeric, "GroupBy1Value" character, "GroupBy2Value" character, "PreviousGroupBy1Value" character, "PreviousGroupBy2Value" character, "TxPracticeName" character, "TxTypeCodeDescription" character, "TxPGroupDescription" character, "TxProducerFirstName" character, "TxProducerMiddleName" character, "TxProducerLastName" character, "TxEntryUserLogon" character, "TxEntryUserFirstName" character, "TxEntryUserLastName" character, "TxAppUserLogon" character, "TxAppUserFirstName" character, "TxAppUserLastName" character, "TxPatientChart" character, "TxPatientFirstName" character, "TxPatientMiddleName" character, "TxPatientLastName" character, "TxPatientPreferredName" character, "TxDeptDescription" character varying, "TxHistoryType" numeric, "TxType" numeric, "TxId" numeric, "TxTreatment" numeric, "TxOrigRecNo" numeric, "TxFamily" numeric, "TxStatus" character, "TxDate" timestamp without time zone, "TxTreatmentDate" timestamp without time zone, "TxCode" character, "TxCodeDescription" character varying, "TxSite" character, "TxSurface" character, "TxTotal" numeric, "TxInsTotal" numeric, "TxCompany1" character, "TxCompany1Name" character, "TxPolicy1" character varying, "TxAmount1" numeric, "TxDescription" character varying, "TxUser" numeric, "TxAppDate" timestamp without time zone, "TxStationId" numeric, "TxCustom3" character, "TxCustom4" character, "TxCustomaryTotal" numeric, "PmtHistoryType" numeric, "PmtType" numeric, "PmtId" numeric, "PmtTreatment" numeric, "PmtOrigRecNo" numeric, "PmtPatient" numeric, "PmtFamily" numeric, "PmtDate" timestamp without time zone, "PmtCode" character, "PmtCodeDescription" character varying, "PmtTotal" numeric, "PmtInsTotal" numeric, "PmtCompany1" character, "PmtCompany1Name" character, "PmtAmount1" numeric, "PmtDescription" character varying, "PmtBank" character, "PmtPayed" numeric, "PmtInsPayed" numeric, "PmtPtAdj" numeric, "PmtInsAdj" numeric, "PmtModifiedDate" timestamp without time zone, "PmtPatientFirstName" character, "PmtPatientMiddleName" character, "PmtPatientLastName" character, "PmtPatientPreferredName" character, "Batch" numeric)
 LANGUAGE edbspl
AS $function$

DECLARE

  cursor cOrigRecNo is

    select distinct gta1."OrigRecNo"

    from global_temp_alloc1 gta1

    where 1=1;



  cursor cOrigRecNo2 is

    select

      gta3.*,

      (select count(distinct gta3c."Department")

       from (select gta3a."Department" "Department"

             from global_temp_alloc3 gta3a

             where 1=1

             and gta3a."OrigRecNo" = gta3."OrigRecNo"

             union

             select gta3b."PreviousDepartment" "Department"

             from global_temp_alloc3 gta3b

             where 1=1

             and gta3b."OrigRecNo" = gta3."OrigRecNo") gta3c

       where 1=1)  "DeptCount",

      decode(gta3."HistoryType", 3, 0, nvl((select 1

                                            from (select

                                                    ah1."PayType",

                                                    ah1."PayId",

                                                    ah1."PayTreatment",

                                                    sum(ah1."Amount")

                                                  from

                                                    allocath ah1,

                                                    allocatelink al

                                                  where 1=1

                                                  and ah1."AllocateLink" = al."AllocateLink"

                                                  and ah1."ModifiedDate" < gta3."TxModifiedDate"

                                                  and ah1."TrxTreatment" = gta3."TrxTreatment"

                                                  and ah1."TrxId" = gta3."TrxId"

                                                  and ah1."TrxType" = gta3."TrxType"

                                                  and not exists (select 0

                                                                  from

                                                                    history h,

                                                                    adjust adj

                                                                  where 1=1

                                                                  and h."Code" = adj."Adjust"

                                                                  and adj."Transfer" = 1

                                                                  and h."History" = al."PmtHistoryId")

                                                  group by

                                                    ah1."PayType",

                                                    ah1."PayId",

                                                    ah1."PayTreatment"

                                                  having sum(ah1."Amount") <> 0)

                                            where 1=1

                                            and rownum = 1), 0)) "HasAllocation"

    from global_temp_alloc3 gta3

    where 1=1

    order by

      gta3."History",

      gta3."TxHistoryId",

      gta3."AllocatH";

      

  cursor cAllocatH (pTrxType allocath."TrxType"%type,

                    pTrxId allocath."TrxId"%type,

                    pTrxTreatment allocath."TrxTreatment"%type,

                    pModifiedDate date,

                    pOrigTrxType allocath."TrxType"%type,

                    pOrigTrxId allocath."TrxId"%type,

                    pOrigTrxTreatment allocath."TrxTreatment"%type) is

    with

    TmpAllocath1 as (

                     select

                       ah1."AllocatH",

                       ah1."PayType",

                       ah1."PayId",

                       ah1."PayTreatment",

                       ah1."Amount",

                       0 "MaxHistory"

                    from allocath ah1

                    where 1=1

                    and ah1."ModifiedDate" <= pModifiedDate

                    and ah1."TrxTreatment" = pTrxTreatment

                    and ah1."TrxId" = pTrxId

                    and ah1."TrxType" = pTrxType

                    and ah1."PayType" <> 7

                    union all

                    select

                       ah1b."AllocatH",

                       ah1b."PayType",

                       ah1b."PayId",

                       ah1b."PayTreatment",

                       ah1b."Amount",

                       0 "MaxHistory"

                    from allocath ah1b

                    where 1=1

                    and ah1b."ModifiedDate" <= pModifiedDate

                    and ah1b."TrxTreatment" = pOrigTrxTreatment

                    and ah1b."TrxId" = pOrigTrxId

                    and ah1b."TrxType" = pOrigTrxType

                    and ah1b."PayType" <> 7

                    union all

                    select

                       ah2."AllocatH",

                       ah2."PayType",

                       ah2."PayId",

                       ah2."PayTreatment",

                       ah2."Amount",

                       nvl((select max(h2."History")

                            from history h2

                            where 1=1

                            and h2."ModifiedDate" <= ah2."ModifiedDate"

                            and h2."Treatment" = ah2."PayTreatment"

                            and h2."Id" = ah2."PayId"

                            and h2."Type" = ah2."PayType"), 0) "MaxHistory"

                    from allocath ah2

                    where 1=1

                    and ah2."ModifiedDate" <= pModifiedDate

                    and ah2."TrxTreatment" = pTrxTreatment

                    and ah2."TrxId" = pTrxId

                    and ah2."TrxType" = pTrxType

                    and ah2."PayType" = 7

                    union all

                    select

                       ah2b."AllocatH",

                       ah2b."PayType",

                       ah2b."PayId",

                       ah2b."PayTreatment",

                       ah2b."Amount",

                       nvl((select max(h2b."History")

                            from history h2b

                            where 1=1

                            and h2b."ModifiedDate" <= ah2b."ModifiedDate"

                            and h2b."Treatment" = ah2b."PayTreatment"

                            and h2b."Id" = ah2b."PayId"

                            and h2b."Type" = ah2b."PayType"), 0) "MaxHistory"

                    from allocath ah2b

                    where 1=1

                    and ah2b."ModifiedDate" <= pModifiedDate

                    and ah2b."TrxTreatment" = pOrigTrxTreatment

                    and ah2b."TrxId" = pOrigTrxId

                    and ah2b."TrxType" = pOrigTrxType

                    and ah2b."PayType" = 7

                   ),

    TmpAllocath2 as (

                     select

                       tah1a."PayType",

                       tah1a."PayId",

                       tah1a."PayTreatment",

                       max(tah1a."AllocatH") "MaxAllocatH"

                     from TmpAllocath1 tah1a

                    where 1=1

                    and tah1a."PayType" <> 7

                    group by

                      tah1a."PayType",

                      tah1a."PayId",

                      tah1a."PayTreatment"

                    having sum(tah1a."Amount") <> 0

                    union all

                    select

                       tah1b."PayType",

                       tah1b."PayId",

                       tah1b."PayTreatment",

                       max(tah1b."AllocatH") "MaxAllocatH"

                     from

                       TmpAllocath1 tah1b,

                       history h1b,

                       adjust adj1b

                    where 1=1

                    and tah1b."MaxHistory" = h1b."History"

                    and h1b."Code" = adj1b."Adjust"

                    and adj1b."Transfer" <> 1

                    and tah1b."PayType" = 7

                    group by

                      tah1b."PayType",

                      tah1b."PayId",

                      tah1b."PayTreatment"

                    having sum(tah1b."Amount") <> 0

                   ),

    TmpAllocath3 as (

                     select

                       ah2."AllocatH",

                       ah2."PayType",

                       ah2."Amount",

                       ah2."AllocateLink",

                       nvl(al2."TxHistoryId", 0) "TxHistoryId",

                       nvl(al2."PmtHistoryId", 0) "PmtHistoryId"

                     from

                       allocatelink al2,

                       allocath ah2,

                       TmpAllocath2 tah2

                     where 1=1

                     and ah2."AllocateLink" = al2."AllocateLink" (+)

                     and ah2."AllocatH" = tah2."MaxAllocatH"

                    )

    select distinct tah3.*

    from TmpAllocath3 tah3

    where 1=1

    order by tah3."AllocatH";



  vDepartment dept."Department"%type := pDepartment;

  vFromDate date := trunc(pFromDate);

  vToDate date := (trunc(pToDate) + (86399/86400));                             -- one second before midnight

  vGroupBy1 global_temp_alloc1."GroupBy1"%type := nvl(pGroupBy1, 0);

  vGroupBy2 global_temp_alloc1."GroupBy2"%type := nvl(pGroupBy2, 0);

  vPatient patient."Patient"%type := nvl(pPatient, 0);

  vOrigRecNo history."OrigRecNo"%type := nvl(pOrigRecNo, 0);

  vNew global_temp_alloc3."HistoryTypeDescription"%type := 'New';

  vAllocate global_temp_alloc3."HistoryTypeDescription"%type := 'Allocate';

  vTransferIn global_temp_alloc3."HistoryTypeDescription"%type := 'Transfer In';

  vTransferOut global_temp_alloc3."HistoryTypeDescription"%type := 'Transfer Out';

  vDeptCount integer := 0;

  vAmount allocath."Amount"%type := 0;

  vCalculateDepartment integer := 0;

  

  -- variables for rebills

  vMaxHistory history."History"%type := 0;

  vOrigType history."Type"%type := 0;

  vOrigId history."Id"%type := 0;

  vOrigTreatment history."Treatment"%type := 0;

  

  vBatch ar_recon_saved_data_hdr."Batch"%type := 0;

  vSysdate date := sysdate;

  vExpiryDate date := trunc(sysdate);

  

  vStep integer := 0;

  

begin

    --

    -- reduce REDO/rollback segments used by GTTs (introduced in Oracle Database 12C Release 1 (12.1))

    --

    vStep := 10;

    

    begin

      execute immediate 'ALTER SESSION SET TEMP_UNDO_ENABLED = TRUE';

    exception

      when others then

        null;

    end;

    

    --

    -- clear staging tables

    --

    vStep := 20;

    

    execute immediate 'truncate table global_temp_alloc1';

    execute immediate 'truncate table global_temp_alloc2';

    execute immediate 'truncate table global_temp_alloc3';

    execute immediate 'truncate table global_temp_alloc4';



    -- needed for the temp table to work consistently

    execute immediate 'select * from global_temp_alloc1';

	execute immediate 'select * from global_temp_alloc2';

	execute immediate 'select * from global_temp_alloc3';

	execute immediate 'select * from global_temp_alloc4';



    --

    -- delete expired allocation type records from table AR_RECON_SAVED_DATA_HDR

    --

    vStep := 30;

    

    delete from ar_recon_saved_data_hdr

    where 1=1

    and "ReportType" = 1                                                          -- allocation type records

    and "ExpiryDate" < trunc(vSysdate);

    

    --

    -- delete records from table AR_RECON_SAVED_DATA_DTL where there is no equivalent records from table AR_RECON_SAVED_DATA_HDR

    --

    vStep := 40;

    

    delete from ar_recon_saved_data_dtl d

    where 1=1

    and not exists (select 1

                    from ar_recon_saved_data_hdr h

                    where 1=1

                    and h."Batch" = d."Batch");



    --

    -- check if allocations report using the same exact parameters were previously ran: if so, just update existing record.  if not, create a new record.

    --

    begin

      --

      -- check if data exists from table AR_RECON_SAVED_DATA_HDR

      --

      vStep := 50;

      

      select arh2."Batch"

      into vBatch

      from (

            select arh."Batch"

            from ar_recon_saved_data_hdr arh

            where 1=1

            and arh."ReportType" = 1                                                        -- allocation type records

            and arh."IncludeUnallocated" = 0

            and arh."GroupBy2" = vGroupBy2

            and arh."GroupBy1" = vGroupBy1

            and arh."ToDate" = vToDate

            and arh."FromDate" = vFromDate

            and arh."Department" = vDepartment

            order by arh."Batch" desc

          ) arh2

      where 1=1

      and rownum = 1;

      

      --

      -- update AR_RECON_SAVED_DATA_HDR with new information

      --

      vStep := 60;

      

      update ar_recon_saved_data_hdr

      set

        "ExpiryDate" = vExpiryDate,

        "LastRunDate" = vSysdate,

        "IsDetailed" = pIsDetailed,

        "StartDateTime" = vSysdate,

        "EndDateTime" = to_date(null)

      where 1=1

      and "ReportType" = 1                                                    -- allocation type records

      and "Batch" = vBatch;



    exception

      when no_data_found then

        --

        -- get new batch ID

        --

        vStep := 70;

    

        select ar_recon_saved_data_hdr_seq.nextval

        into vBatch

        from dual;



        --

        -- insert into AR_RECON_SAVED_DATA_HDR

        --

        vStep := 80;

      

        insert into ar_recon_saved_data_hdr

        select

          vBatch "Batch",

          vExpiryDate "ExpiryDate",

          vSysdate "FirstRunDate",

          vSysdate "LastRunDate",

          vDepartment "Department",

          vFromDate "FromDate",

          vToDate "ToDate",

          vGroupBy1 "GroupBy1",

          ar_dept_pkg.ar_get_group_by_desc_f (vGroupBy1) "GroupBy1Description",

          vGroupBy2 "GroupBy2",

          ar_dept_pkg.ar_get_group_by_desc_f (vGroupBy2) "GroupBy2Description",

          pIsDetailed "IsDetailed",

          0 "IncludeUnallocated",

          vPatient "Patient",

          vOrigRecNo "OrigRecNo",

          0 "BeginningBalance",

          0 "PeriodBalance",

          0 "EndingBalance",

          1 "ReportType",                                                             -- allocation type records

          vSysdate "StartDateTime",

          to_date(null) "EndDateTime"

        from dual

        where 1=1;

        

    end;



    --

    -- populate staging table #1 with the OrigRecNos of the allocation records for the period

    --

    if ((vPatient = 0) and (vOrigRecNo = 0)) then

      --

      -- populate staging table #1 with the OrigRecNos of the allocation records for the period (for all; not for a specific Patient or specific OrigRecNo)

      --

      vStep := 90;

    

      insert into global_temp_alloc1

      select

        ah."AllocatH",

        ah."PayType",

        ah."TrxType",

        ah."TrxId",

        ah."TrxTreatment",

        ah."Amount",

        ah."AllocateLink",

        al."TxHistoryId",

        al."PmtHistoryId",

        htx."OrigRecNo",

        htx."History",

        htx."HistoryType",

        htx."Patient",

        htx."ModifiedDate" "TxModifiedDate",

        htx."Payed",

        htx."InsPayed",

        htx."PtAdj",

        htx."InsAdj",

        htx."InsTransfer",

        htx."Discipline",

        htx."Procedure",

        htx."Practice",

        htx."ClaimDoctor",

        htx."Location",

        htx."EntryUser",

        htx."AppUser",

        htx."Custom1",

        htx."Custom2",

        htx."Producer",

        nvl(prod."TypeCode", ' ') "TypeCode",

        nvl(prod."PGroup", ' ') "PGroup",

        nvl(prod."Year", 0) "Year",

        pat."CustomCode1",

        pat."CustomCode2",

        pat."CustomCode3",

        pat."CustomCode4",

        pat."CustomCode5",

        pat."CustomCode6",

        pat."CustomCode7",

        pat."CustomCode8",

        pat."CustomCode9",

        pat."CustomCode10",

        ' ' "Department",

        ' ' "HistoryTypeDescription",

        vGroupBy1 "GroupBy1",

        vGroupBy2 "GroupBy2"

      from

        history htx,

        allocath ah,

        allocatelink al,

        patient pat,

        producer prod

      where 1=1

      and htx."Producer" = prod."Producer" (+)

      and ah."AllocateLink" = al."AllocateLink"

      and al."TxHistoryId" = htx."History"

      and htx."Patient" = pat."Patient"

      and ah."Amount" <> 0

      and ah."ModifiedDate" >= vFromDate

      and ah."ModifiedDate" <= vToDate

      union

      --

      -- populate staging table #1 with the OrigRecNos of the allocation records even if there are no allocations for the period but there are history changes for the period

      -- (for all; not for a specific Patient or specific OrigRecNo)

      --

      select

        ah2."AllocatH",

        ah2."PayType",

        ah2."TrxType",

        ah2."TrxId",

        ah2."TrxTreatment",

        ah2."Amount",

        ah2."AllocateLink",

        al2."TxHistoryId",

        al2."PmtHistoryId",

        htx2."OrigRecNo",

        htx2."History",

        htx2."HistoryType",

        htx2."Patient",

        htx2."ModifiedDate" "TxModifiedDate",

        htx2."Payed",

        htx2."InsPayed",

        htx2."PtAdj",

        htx2."InsAdj",

        htx2."InsTransfer",

        htx2."Discipline",

        htx2."Procedure",

        htx2."Practice",

        htx2."ClaimDoctor",

        htx2."Location",

        htx2."EntryUser",

        htx2."AppUser",

        htx2."Custom1",

        htx2."Custom2",

        htx2."Producer",

        nvl(prod2."TypeCode", ' ') "TypeCode",

        nvl(prod2."PGroup", ' ') "PGroup",

        nvl(prod2."Year", 0) "Year",

        pat2."CustomCode1",

        pat2."CustomCode2",

        pat2."CustomCode3",

        pat2."CustomCode4",

        pat2."CustomCode5",

        pat2."CustomCode6",

        pat2."CustomCode7",

        pat2."CustomCode8",

        pat2."CustomCode9",

        pat2."CustomCode10",

        ' ' "Department",

        ' ' "HistoryTypeDescription",

        vGroupBy1 "GroupBy1",

        vGroupBy2 "GroupBy2"

      from

        history htx2,

        allocath ah2,

        allocatelink al2,

        patient pat2,

        producer prod2

      where 1=1

      and htx2."Producer" = prod2."Producer" (+)

      and ah2."AllocateLink" = al2."AllocateLink"

      and al2."TxHistoryId" = htx2."History"

      and htx2."Patient" = pat2."Patient"

      and ah2."Amount" <> 0

      and exists (select null

                  from history h2

                  where 1=1

                  and h2."HistoryType" = 2

                  and h2."ModifiedDate" >= vFromDate

                  and h2."ModifiedDate" <= vToDate

                  and h2."OrigRecNo" = htx2."OrigRecNo");



    else

      --

      -- populate staging table #1 with the OrigRecNos of the allocation records for the period (for a specific Patient or specific OrigRecNo)

      --

      vStep := 100;

    

      insert into global_temp_alloc1

      select

        ah."AllocatH",

        ah."PayType",

        ah."TrxType",

        ah."TrxId",

        ah."TrxTreatment",

        ah."Amount",

        ah."AllocateLink",

        al."TxHistoryId",

        al."PmtHistoryId",

        htx."OrigRecNo",

        htx."History",

        htx."HistoryType",

        htx."Patient",

        htx."ModifiedDate" "TxModifiedDate",

        htx."Payed",

        htx."InsPayed",

        htx."PtAdj",

        htx."InsAdj",

        htx."InsTransfer",

        htx."Discipline",

        htx."Procedure",

        htx."Practice",

        htx."ClaimDoctor",

        htx."Location",

        htx."EntryUser",

        htx."AppUser",

        htx."Custom1",

        htx."Custom2",

        htx."Producer",

        nvl(prod."TypeCode", ' ') "TypeCode",

        nvl(prod."PGroup", ' ') "PGroup",

        nvl(prod."Year", 0) "Year",

        pat."CustomCode1",

        pat."CustomCode2",

        pat."CustomCode3",

        pat."CustomCode4",

        pat."CustomCode5",

        pat."CustomCode6",

        pat."CustomCode7",

        pat."CustomCode8",

        pat."CustomCode9",

        pat."CustomCode10",

        ' ' "Department",

        ' ' "HistoryTypeDescription",

        vGroupBy1 "GroupBy1",

        vGroupBy2 "GroupBy2"

      from

        history htx,

        allocath ah,

        allocatelink al,

        patient pat,

        producer prod

      where 1=1

      and htx."Producer" = prod."Producer" (+)

      and ah."AllocateLink" = al."AllocateLink"

      and al."TxHistoryId" = htx."History"

      and htx."Patient" = pat."Patient"

      and ah."Amount" <> 0

      and ah."ModifiedDate" >= vFromDate

      and ah."ModifiedDate" <= vToDate

      and htx."Patient" = decode(vPatient, 0, htx."Patient", vPatient)

      and htx."OrigRecNo" = decode(vOrigRecNo, 0, htx."OrigRecNo", vOrigRecNo)

      union

      --

      -- populate staging table #1 with the OrigRecNos of the allocation records even if there are no allocations for the period but there are history changes for the period

      --  (for a specific Patient or specific OrigRecNo)

      --

      select

        ah2."AllocatH",

        ah2."PayType",

        ah2."TrxType",

        ah2."TrxId",

        ah2."TrxTreatment",

        ah2."Amount",

        ah2."AllocateLink",

        al2."TxHistoryId",

        al2."PmtHistoryId",

        htx2."OrigRecNo",

        htx2."History",

        htx2."HistoryType",

        htx2."Patient",

        htx2."ModifiedDate" "TxModifiedDate",

        htx2."Payed",

        htx2."InsPayed",

        htx2."PtAdj",

        htx2."InsAdj",

        htx2."InsTransfer",

        htx2."Discipline",

        htx2."Procedure",

        htx2."Practice",

        htx2."ClaimDoctor",

        htx2."Location",

        htx2."EntryUser",

        htx2."AppUser",

        htx2."Custom1",

        htx2."Custom2",

        htx2."Producer",

        nvl(prod2."TypeCode", ' ') "TypeCode",

        nvl(prod2."PGroup", ' ') "PGroup",

        nvl(prod2."Year", 0) "Year",

        pat2."CustomCode1",

        pat2."CustomCode2",

        pat2."CustomCode3",

        pat2."CustomCode4",

        pat2."CustomCode5",

        pat2."CustomCode6",

        pat2."CustomCode7",

        pat2."CustomCode8",

        pat2."CustomCode9",

        pat2."CustomCode10",

        ' ' "Department",

        ' ' "HistoryTypeDescription",

        vGroupBy1 "GroupBy1",

        vGroupBy2 "GroupBy2"

      from

        history htx2,

        allocath ah2,

        allocatelink al2,

        patient pat2,

        producer prod2

      where 1=1

      and htx2."Producer" = prod2."Producer" (+)

      and ah2."AllocateLink" = al2."AllocateLink"

      and al2."TxHistoryId" = htx2."History"

      and htx2."Patient" = pat2."Patient"

      and ah2."Amount" <> 0

      and htx2."Patient" = decode(vPatient, 0, htx2."Patient", vPatient)

      and htx2."OrigRecNo" = decode(vOrigRecNo, 0, htx2."OrigRecNo", vOrigRecNo)

      and exists (select null

                  from history h2

                  where 1=1

                  and h2."HistoryType" = 2

                  and h2."ModifiedDate" >= vFromDate

                  and h2."ModifiedDate" <= vToDate

                  and h2."OrigRecNo" = htx2."OrigRecNo");

      

    end if;



    --

    -- determine if department needs to be calculated (may slow down processing time) or just use whatever department is passed to the procedure (can reduce processing time)

    --

    begin

      --

      -- check if department has corresponding department definition

      --

      vStep := 110;

    

      select 1

      into vCalculateDepartment

      from dept d

      where 1=1

      and exists (select 1

                  from deptdef dd

                  where 1=1

                  and dd."Department" = d."Department")

      and d."Department" = vDepartment;

      

    exception

      when no_data_found then

        --

        -- use whatever department is passed to the procedure

        --

        vStep := 120;

        

        vCalculateDepartment := 0;



    end;

    

    --

    -- do not process insurance transfers and deleted records

    --

    vStep := 130;

    

    delete from global_temp_alloc1 gta1

    where 1=1

    and ((gta1."HistoryType" = 4)

        or (gta1."PayType" = 7

            and exists (select 0

                        from

                          history h,

                          adjust adj

                        where 1=1

                        and h."Code" = adj."Adjust"

                        and adj."Transfer" = 1

                        and h."History" = gta1."PmtHistoryId")));

    

    --

    -- process each OrigRecNo

    --

    vStep := 140;

    

    for pOrigRecNo in cOrigRecNo loop

    

      if (vCalculateDepartment = 1) then

        --

        -- populate staging table #2 with all records for the current OrigRecNo (calculate department)

        --

        vStep := 150;



        insert into global_temp_alloc2

        select *

        from (

              with

              TmpGTA1 as (

                          --

                          -- all records on or before the reporting period end date for the current OrigRecNo

                          --

                          select

                            gta1."AllocatH",

                            gta1."PayType",

                            gta1."TrxType",

                            gta1."TrxId",

                            gta1."TrxTreatment",

                            gta1."Amount",

                            gta1."AllocateLink",

                            gta1."TxHistoryId",

                            gta1."PmtHistoryId",  

                            gta1."OrigRecNo",

                            htx1."History",

                            htx1."HistoryType",

                            htx1."Patient",

                            htx1."ModifiedDate" "TxModifiedDate",

                            htx1."Payed",

                            htx1."InsPayed",

                            htx1."PtAdj",

                            htx1."InsAdj",

                            htx1."InsTransfer",

                            htx1."Discipline",

                            htx1."Procedure",

                            htx1."Practice",

                            htx1."ClaimDoctor",

                            htx1."Location",

                            htx1."EntryUser",

                            htx1."AppUser",

                            htx1."Custom1",

                            htx1."Custom2",

                            htx1."Producer",

                            nvl(prod1."TypeCode", ' ') "TypeCode",

                            nvl(prod1."PGroup", ' ') "PGroup",

                            nvl(prod1."Year", 0) "Year",

                            pat1."CustomCode1",

                            pat1."CustomCode2",

                            pat1."CustomCode3",

                            pat1."CustomCode4",

                            pat1."CustomCode5",

                            pat1."CustomCode6",

                            pat1."CustomCode7",

                            pat1."CustomCode8",

                            pat1."CustomCode9",

                            pat1."CustomCode10",

                            ar_dept_pkg.ar_get_dept_f(vDepartment,

                                                      htx1."History",

                                                      htx1."Producer",

                                                      htx1."Patient") "Department",

                            gta1."HistoryTypeDescription",

                            gta1."GroupBy1",

                            gta1."GroupBy2"

                          from

                            history htx1,

                            global_temp_alloc1 gta1,

                            producer prod1,

                            patient pat1

                          where 1=1

                          and htx1."OrigRecNo" = gta1."OrigRecNo"

                          and htx1."Patient" = pat1."Patient"

                          and htx1."Producer" = prod1."Producer" (+)

                          and htx1."ModifiedDate" <= vToDate

                          and htx1."OrigRecNo" = pOrigRecNo."OrigRecNo"

                        ),

              TmpGTA1B as (

                          select distinct

                            gta1b."AllocatH",

                            gta1b."PayType",

                            gta1b."TrxType",

                            gta1b."TrxId",

                            gta1b."TrxTreatment",

                            gta1b."Amount",

                            gta1b."AllocateLink",

                            gta1b."TxHistoryId",

                            gta1b."PmtHistoryId",

                            tgta1."OrigRecNo",

                            tgta1."History",

                            tgta1."HistoryType",

                            tgta1."Patient",

                            tgta1."TxModifiedDate",

                            tgta1."Payed",

                            tgta1."InsPayed",

                            tgta1."PtAdj",

                            tgta1."InsAdj",

                            tgta1."InsTransfer",

                            tgta1."Discipline",

                            tgta1."Procedure",

                            tgta1."Practice",

                            tgta1."ClaimDoctor",

                            tgta1."Location",

                            tgta1."EntryUser",

                            tgta1."AppUser",

                            tgta1."Custom1",

                            tgta1."Custom2",

                            tgta1."Producer",

                            tgta1."TypeCode",

                            tgta1."PGroup",

                            tgta1."Year",

                            tgta1."CustomCode1",

                            tgta1."CustomCode2",

                            tgta1."CustomCode3",

                            tgta1."CustomCode4",

                            tgta1."CustomCode5",

                            tgta1."CustomCode6",

                            tgta1."CustomCode7",

                            tgta1."CustomCode8",

                            tgta1."CustomCode9",

                            tgta1."CustomCode10",

                            tgta1."Department",

                            tgta1."HistoryTypeDescription",

                            tgta1."GroupBy1",

                            tgta1."GroupBy2"

                          from

                            TmpGTA1 tgta1,

                            global_temp_alloc1 gta1b

                          where 1=1

                          and tgta1."History" = gta1b."History" (+)

                          and tgta1."OrigRecNo" = gta1b."OrigRecNo" (+)

                          )

              select

                nvl(nvl(tgta1b."AllocatH", lag(tgta1b."AllocatH") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "AllocatH",

                nvl(nvl(tgta1b."PayType", lag(tgta1b."PayType") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "PayType",

                nvl(nvl(tgta1b."TrxType", lag(tgta1b."TrxType") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "TrxType",

                nvl(nvl(tgta1b."TrxId", lag(tgta1b."TrxId") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "TrxId",

                nvl(nvl(tgta1b."TrxTreatment", lag(tgta1b."TrxTreatment") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "TrxTreatment",

                nvl(nvl(tgta1b."Amount", lag(tgta1b."Amount") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "Amount",

                nvl(nvl(tgta1b."AllocateLink", lag(tgta1b."AllocateLink") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "AllocateLink",

                nvl(nvl(tgta1b."TxHistoryId", lag(tgta1b."TxHistoryId") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "TxHistoryId",

                nvl(nvl(tgta1b."PmtHistoryId", lag(tgta1b."PmtHistoryId") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "PmtHistoryId",

                tgta1b."OrigRecNo",

                tgta1b."History",

                tgta1b."HistoryType",

                tgta1b."Patient",

                tgta1b."TxModifiedDate",

                tgta1b."Payed",

                tgta1b."InsPayed",

                tgta1b."PtAdj",

                tgta1b."InsAdj",

                tgta1b."InsTransfer",

                tgta1b."Discipline",

                tgta1b."Procedure",

                tgta1b."Practice",

                tgta1b."ClaimDoctor",

                tgta1b."Location",

                tgta1b."EntryUser",

                tgta1b."AppUser",

                tgta1b."Custom1",

                tgta1b."Custom2",

                tgta1b."Producer",

                tgta1b."TypeCode",

                tgta1b."PGroup",

                tgta1b."Year",

                tgta1b."CustomCode1",

                tgta1b."CustomCode2",

                tgta1b."CustomCode3",

                tgta1b."CustomCode4",

                tgta1b."CustomCode5",

                tgta1b."CustomCode6",

                tgta1b."CustomCode7",

                tgta1b."CustomCode8",

                tgta1b."CustomCode9",

                tgta1b."CustomCode10",

                tgta1b."Department",

                tgta1b."HistoryTypeDescription",

                tgta1b."GroupBy1",

                tgta1b."GroupBy2"

              from TmpGTA1B tgta1b

              where 1=1

            )

        where 1=1;



      else

        --

        -- populate staging table #2 with all records for the current OrigRecNo (use whatever department is passed to the procedure)

        --

        vStep := 160;



        insert into global_temp_alloc2

        select *

        from (

              with

              TmpGTA1 as (

                          --

                          -- all records on or before the reporting period end date for the current OrigRecNo

                          --

                          select

                            gta1."AllocatH",

                            gta1."PayType",

                            gta1."TrxType",

                            gta1."TrxId",

                            gta1."TrxTreatment",

                            gta1."Amount",

                            gta1."AllocateLink",

                            gta1."TxHistoryId",

                            gta1."PmtHistoryId", 

                            gta1."OrigRecNo",

                            htx1."History",

                            htx1."HistoryType",

                            htx1."Patient",

                            htx1."ModifiedDate" "TxModifiedDate",

                            htx1."Payed",

                            htx1."InsPayed",

                            htx1."PtAdj",

                            htx1."InsAdj",

                            htx1."InsTransfer",

                            htx1."Discipline",

                            htx1."Procedure",

                            htx1."Practice",

                            htx1."ClaimDoctor",

                            htx1."Location",

                            htx1."EntryUser",

                            htx1."AppUser",

                            htx1."Custom1",

                            htx1."Custom2",

                            htx1."Producer",

                            nvl(prod1."TypeCode", ' ') "TypeCode",

                            nvl(prod1."PGroup", ' ') "PGroup",

                            nvl(prod1."Year", 0) "Year",

                            pat1."CustomCode1",

                            pat1."CustomCode2",

                            pat1."CustomCode3",

                            pat1."CustomCode4",

                            pat1."CustomCode5",

                            pat1."CustomCode6",

                            pat1."CustomCode7",

                            pat1."CustomCode8",

                            pat1."CustomCode9",

                            pat1."CustomCode10",

                            vDepartment "Department",

                            gta1."HistoryTypeDescription",

                            gta1."GroupBy1",

                            gta1."GroupBy2"

                          from

                            history htx1,

                            global_temp_alloc1 gta1,

                            producer prod1,

                            patient pat1

                          where 1=1

                          and htx1."OrigRecNo" = gta1."OrigRecNo"

                          and htx1."Patient" = pat1."Patient"

                          and htx1."Producer" = prod1."Producer" (+)

                          and htx1."ModifiedDate" <= vToDate

                          and htx1."OrigRecNo" = pOrigRecNo."OrigRecNo"

                        ),

              TmpGTA1B as (

                          select distinct

                            gta1b."AllocatH",

                            gta1b."PayType",

                            gta1b."TrxType",

                            gta1b."TrxId",

                            gta1b."TrxTreatment",

                            gta1b."Amount",

                            gta1b."AllocateLink",

                            gta1b."TxHistoryId",

                            gta1b."PmtHistoryId",

                            tgta1."OrigRecNo",

                            tgta1."History",

                            tgta1."HistoryType",

                            tgta1."Patient",

                            tgta1."TxModifiedDate",

                            tgta1."Payed",

                            tgta1."InsPayed",

                            tgta1."PtAdj",

                            tgta1."InsAdj",

                            tgta1."InsTransfer",

                            tgta1."Discipline",

                            tgta1."Procedure",

                            tgta1."Practice",

                            tgta1."ClaimDoctor",

                            tgta1."Location",

                            tgta1."EntryUser",

                            tgta1."AppUser",

                            tgta1."Custom1",

                            tgta1."Custom2",

                            tgta1."Producer",

                            tgta1."TypeCode",

                            tgta1."PGroup",

                            tgta1."Year",

                            tgta1."CustomCode1",

                            tgta1."CustomCode2",

                            tgta1."CustomCode3",

                            tgta1."CustomCode4",

                            tgta1."CustomCode5",

                            tgta1."CustomCode6",

                            tgta1."CustomCode7",

                            tgta1."CustomCode8",

                            tgta1."CustomCode9",

                            tgta1."CustomCode10",

                            tgta1."Department",

                            tgta1."HistoryTypeDescription",

                            tgta1."GroupBy1",

                            tgta1."GroupBy2"

                          from

                            TmpGTA1 tgta1,

                            global_temp_alloc1 gta1b

                          where 1=1

                          and tgta1."History" = gta1b."History" (+)

                          and tgta1."OrigRecNo" = gta1b."OrigRecNo" (+)

                          )

              select

                nvl(nvl(tgta1b."AllocatH", lag(tgta1b."AllocatH") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "AllocatH",

                nvl(nvl(tgta1b."PayType", lag(tgta1b."PayType") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "PayType",

                nvl(nvl(tgta1b."TrxType", lag(tgta1b."TrxType") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "TrxType",

                nvl(nvl(tgta1b."TrxId", lag(tgta1b."TrxId") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "TrxId",

                nvl(nvl(tgta1b."TrxTreatment", lag(tgta1b."TrxTreatment") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "TrxTreatment",

                nvl(nvl(tgta1b."Amount", lag(tgta1b."Amount") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "Amount",

                nvl(nvl(tgta1b."AllocateLink", lag(tgta1b."AllocateLink") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "AllocateLink",

                nvl(nvl(tgta1b."TxHistoryId", lag(tgta1b."TxHistoryId") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "TxHistoryId",

                nvl(nvl(tgta1b."PmtHistoryId", lag(tgta1b."PmtHistoryId") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "PmtHistoryId",

                tgta1b."OrigRecNo",

                tgta1b."History",

                tgta1b."HistoryType",

                tgta1b."Patient",

                tgta1b."TxModifiedDate",

                tgta1b."Payed",

                tgta1b."InsPayed",

                tgta1b."PtAdj",

                tgta1b."InsAdj",

                tgta1b."InsTransfer",

                tgta1b."Discipline",

                tgta1b."Procedure",

                tgta1b."Practice",

                tgta1b."ClaimDoctor",

                tgta1b."Location",

                tgta1b."EntryUser",

                tgta1b."AppUser",

                tgta1b."Custom1",

                tgta1b."Custom2",

                tgta1b."Producer",

                tgta1b."TypeCode",

                tgta1b."PGroup",

                tgta1b."Year",

                tgta1b."CustomCode1",

                tgta1b."CustomCode2",

                tgta1b."CustomCode3",

                tgta1b."CustomCode4",

                tgta1b."CustomCode5",

                tgta1b."CustomCode6",

                tgta1b."CustomCode7",

                tgta1b."CustomCode8",

                tgta1b."CustomCode9",

                tgta1b."CustomCode10",

                tgta1b."Department",

                tgta1b."HistoryTypeDescription",

                tgta1b."GroupBy1",

                tgta1b."GroupBy2"

              from TmpGTA1B tgta1b

              where 1=1

            )

        where 1=1;

        

      end if;



      --

      -- delete records that does not have any allocations (does not need to be reported)

      --

      vStep := 170;



      delete from global_temp_alloc2 gta2

      where 1=1

      and gta2."HistoryType" in (2, 5)

      and ((gta2."PayType" = 3 and gta2."Payed" = 0)

          or (gta2."PayType" = 4 and gta2."InsPayed" = 0)

          or (gta2."PayType" = 6 and gta2."PtAdj" = 0)

          or (gta2."PayType" = 7 and gta2."InsAdj" = 0))

      and not exists (select

                        ah1."PayType",

                        ah1."PayId",

                        ah1."PayTreatment",

                        sum(ah1."Amount")

                      from

                        allocath ah1,

                        allocatelink al

                      where 1=1

                      and ah1."AllocateLink" = al."AllocateLink"

                      and ah1."ModifiedDate" < gta2."TxModifiedDate"

                      and ah1."TrxTreatment" = gta2."TrxTreatment"

                      and ah1."TrxId" = gta2."TrxId"

                      and ah1."TrxType" = gta2."TrxType"

                      and not exists (select 0

                                      from

                                        history h,

                                        adjust adj

                                      where 1=1

                                      and h."Code" = adj."Adjust"

                                      and adj."Transfer" = 1

                                      and h."History" = al."PmtHistoryId")

                      group by

                        ah1."PayType",

                        ah1."PayId",

                        ah1."PayTreatment"

                      having sum(ah1."Amount") <> 0);



      --

      -- populate 3rd temporary table with group by changes

      --

      vStep := 180;



      insert into global_temp_alloc3

      select

        gta2.*,

        nvl((lag(gta2."History") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."History") "PreviousHistory",

        nvl((lag(gta2."Discipline") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."Discipline") "PreviousDiscipline",

        nvl((lag(gta2."Procedure") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."Procedure") "PreviousProcedure",

        nvl((lag(gta2."Practice") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."Practice") "PreviousPractice",

        nvl((lag(gta2."ClaimDoctor") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."ClaimDoctor") "PreviousClaimDoctor",

        nvl((lag(gta2."Location") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."Location") "PreviousLocation",

        nvl((lag(gta2."EntryUser") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."EntryUser") "PreviousEntryUser",

        nvl((lag(gta2."AppUser") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."AppUser") "PreviousAppUser",

        nvl((lag(gta2."Custom1") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."Custom1") "PreviousCustom1",

        nvl((lag(gta2."Custom2") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."Custom2") "PreviousCustom2",

        nvl((lag(gta2."Producer") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."Producer") "PreviousProducer",

        nvl((lag(gta2."TypeCode") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."TypeCode") "PreviousTypeCode",

        nvl((lag(gta2."PGroup") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."PGroup") "PreviousPGroup",

        nvl((lag(gta2."Year") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."Year") "PreviousYear",

        nvl((lag(gta2."CustomCode1") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."CustomCode1") "PreviousCustomCode1",

        nvl((lag(gta2."CustomCode2") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."CustomCode2") "PreviousCustomCode2",

        nvl((lag(gta2."CustomCode3") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."CustomCode3") "PreviousCustomCode3",

        nvl((lag(gta2."CustomCode4") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."CustomCode4") "PreviousCustomCode4",

        nvl((lag(gta2."CustomCode5") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."CustomCode5") "PreviousCustomCode5",

        nvl((lag(gta2."CustomCode6") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."CustomCode6") "PreviousCustomCode6",

        nvl((lag(gta2."CustomCode7") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."CustomCode7") "PreviousCustomCode7",

        nvl((lag(gta2."CustomCode8") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."CustomCode8") "PreviousCustomCode8",

        nvl((lag(gta2."CustomCode9") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."CustomCode9") "PreviousCustomCode9",

        nvl((lag(gta2."CustomCode10") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."CustomCode10") "PreviousCustomCode10",

        nvl((lag(gta2."Department") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."Department") "PreviousDepartment",

        ' ' "GroupBy1Value",

        ' ' "GroupBy2Value",

        ' ' "PreviousGroupBy1Value",

        ' ' "PreviousGroupBy2Value"

      from global_temp_alloc2 gta2

      where 1=1

      order by

        gta2."History",

        gta2."AllocatH";



      --

      -- fix previous values (if there are multiple allocations during a modification or a rebill)

      --

      vStep := 190;

      

      update global_temp_alloc3 gta3

      set

        (gta3."PreviousHistory",

        gta3."PreviousDiscipline",

        gta3."PreviousProcedure",

        gta3."PreviousPractice",

        gta3."PreviousClaimDoctor",

        gta3."PreviousLocation",

        gta3."PreviousEntryUser",

        gta3."PreviousAppUser",

        gta3."PreviousCustom1",

        gta3."PreviousCustom2",

        gta3."PreviousProducer",

        gta3."PreviousTypeCode",

        gta3."PreviousPGroup",

        gta3."PreviousYear",

        gta3."PreviousCustomCode1",

        gta3."PreviousCustomCode2",

        gta3."PreviousCustomCode3",

        gta3."PreviousCustomCode4",

        gta3."PreviousCustomCode5",

        gta3."PreviousCustomCode6",

        gta3."PreviousCustomCode7",

        gta3."PreviousCustomCode8",

        gta3."PreviousCustomCode9",

        gta3."PreviousCustomCode10",

        gta3."PreviousDepartment") = (select

                                        gta3b."PreviousHistory",

                                        gta3b."PreviousDiscipline",

                                        gta3b."PreviousProcedure",

                                        gta3b."PreviousPractice",

                                        gta3b."PreviousClaimDoctor",

                                        gta3b."PreviousLocation",

                                        gta3b."PreviousEntryUser",

                                        gta3b."PreviousAppUser",

                                        gta3b."PreviousCustom1",

                                        gta3b."PreviousCustom2",

                                        gta3b."PreviousProducer",

                                        gta3b."PreviousTypeCode",

                                        gta3b."PreviousPGroup",

                                        gta3b."PreviousYear",

                                        gta3b."PreviousCustomCode1",

                                        gta3b."PreviousCustomCode2",

                                        gta3b."PreviousCustomCode3",

                                        gta3b."PreviousCustomCode4",

                                        gta3b."PreviousCustomCode5",

                                        gta3b."PreviousCustomCode6",

                                        gta3b."PreviousCustomCode7",

                                        gta3b."PreviousCustomCode8",

                                        gta3b."PreviousCustomCode9",

                                        gta3b."PreviousCustomCode10",

                                        gta3b."PreviousDepartment"

                                      from (select

                                              gta3c."History",

                                              gta3c."PreviousHistory",

                                              gta3c."PreviousDiscipline",

                                              gta3c."PreviousProcedure",

                                              gta3c."PreviousPractice",

                                              gta3c."PreviousClaimDoctor",

                                              gta3c."PreviousLocation",

                                              gta3c."PreviousEntryUser",

                                              gta3c."PreviousAppUser",

                                              gta3c."PreviousCustom1",

                                              gta3c."PreviousCustom2",

                                              gta3c."PreviousProducer",

                                              gta3c."PreviousTypeCode",

                                              gta3c."PreviousPGroup",

                                              gta3c."PreviousYear",

                                              gta3c."PreviousCustomCode1",

                                              gta3c."PreviousCustomCode2",

                                              gta3c."PreviousCustomCode3",

                                              gta3c."PreviousCustomCode4",

                                              gta3c."PreviousCustomCode5",

                                              gta3c."PreviousCustomCode6",

                                              gta3c."PreviousCustomCode7",

                                              gta3c."PreviousCustomCode8",

                                              gta3c."PreviousCustomCode9",

                                              gta3c."PreviousCustomCode10",

                                              gta3c."PreviousDepartment",

                                              (row_number() over (partition by

                                                                    gta3c."OrigRecNo",

                                                                    gta3c."History"

                                                                  order by

                                                                    gta3c."OrigRecNo",

                                                                    gta3c."History",

                                                                    gta3c."AllocatH")) "RowNumber"

                                            from global_temp_alloc3 gta3c

                                            where 1=1

                                            ) gta3b

                                      where 1=1

                                      and gta3b."History" = gta3."History"

                                      and gta3b."RowNumber" = 1)

      where 1=1;



      --

      -- delete unnecessary records

      --

      vStep := 200;

        

      delete from global_temp_alloc3 gta3

      where 1=1

      and (gta3."TrxType" not in (1, 2)

          or gta3."HistoryType" not in (1, 2, 3, 5)

          or (gta3."HistoryType" in (2, 5)

              and gta3."Payed" = 0

              and gta3."InsPayed" = 0

              and gta3."PtAdj" = 0

              and gta3."InsAdj" = 0

              and gta3."InsTransfer" = 0)

          or (gta3."HistoryType" = 1

              and gta3."Payed" = 0));



      --

      -- determine current and previous values if there is grouping by 1 or grouping by 2

      --

      if ((vGroupBy1 > 0) or (vGroupBy2 > 0)) then

        --

        -- determine current and previous values if there is grouping by 1

        --

        if (vGroupBy1 > 0) then

          --

          -- update current and previous group by 1 values

          --

          vStep := 210;

        

          update global_temp_alloc3 gta3

          set

            gta3."GroupBy1Value" = decode(gta3."GroupBy1", 0, ' ',

                                                          1, gta3."Producer",

                                                          2, gta3."PGroup",

                                                          3, gta3."TypeCode",

                                                          4, trim(to_char(gta3."Year")),

                                                          5, trim(to_char(gta3."AppUser")),

                                                          6, gta3."Custom1",

                                                          7, gta3."Custom2",

                                                          8, gta3."Discipline",

                                                          9, trim(to_char(gta3."EntryUser")),

                                                          10, gta3."Location",

                                                          11, gta3."ClaimDoctor",

                                                          12, trim(to_char(gta3."Practice")),

                                                          13, gta3."Procedure",

                                                          14, gta3."CustomCode1",

                                                          15, gta3."CustomCode2",

                                                          16, gta3."CustomCode3",

                                                          17, gta3."CustomCode4",

                                                          18, gta3."CustomCode5",

                                                          19, gta3."CustomCode6",

                                                          20, gta3."CustomCode7",

                                                          21, gta3."CustomCode8",

                                                          22, gta3."CustomCode9",

                                                          23, gta3."CustomCode10",

                                                          ' '),

            gta3."PreviousGroupBy1Value" = decode(gta3."GroupBy1", 0, ' ',

                                                                  1, gta3."PreviousProducer",

                                                                  2, gta3."PreviousPGroup",

                                                                  3, gta3."PreviousTypeCode",

                                                                  4, trim(to_char(gta3."PreviousYear")),

                                                                  5, trim(to_char(gta3."PreviousAppUser")),

                                                                  6, gta3."PreviousCustom1",

                                                                  7, gta3."PreviousCustom2",

                                                                  8, gta3."PreviousDiscipline",

                                                                  9, trim(to_char(gta3."PreviousEntryUser")),

                                                                  10, gta3."PreviousLocation",

                                                                  11, gta3."PreviousClaimDoctor",

                                                                  12, trim(to_char(gta3."PreviousPractice")),

                                                                  13, gta3."PreviousProcedure",

                                                                  14, gta3."PreviousCustomCode1",

                                                                  15, gta3."PreviousCustomCode2",

                                                                  16, gta3."PreviousCustomCode3",

                                                                  17, gta3."PreviousCustomCode4",

                                                                  18, gta3."PreviousCustomCode5",

                                                                  19, gta3."PreviousCustomCode6",

                                                                  20, gta3."PreviousCustomCode7",

                                                                  21, gta3."PreviousCustomCode8",

                                                                  22, gta3."PreviousCustomCode9",

                                                                  23, gta3."PreviousCustomCode10",

                                                                  ' ')

          where 1=1;

        

        end if;

        

        --

        -- determine current and previous values if there is grouping by 2

        --

        if (vGroupBy2 > 0) then

          --

          -- update current and previous group by 2 values

          --

          vStep := 220;

        

          update global_temp_alloc3 gta3

          set

            gta3."GroupBy2Value" = decode(gta3."GroupBy2", 0, ' ',

                                                          1, gta3."Producer",

                                                          2, gta3."PGroup",

                                                          3, gta3."TypeCode",

                                                          4, trim(to_char(gta3."Year")),

                                                          5, trim(to_char(gta3."AppUser")),

                                                          6, gta3."Custom1",

                                                          7, gta3."Custom2",

                                                          8, gta3."Discipline",

                                                          9, trim(to_char(gta3."EntryUser")),

                                                          10, gta3."Location",

                                                          11, gta3."ClaimDoctor",

                                                          12, trim(to_char(gta3."Practice")),

                                                          13, gta3."Procedure",

                                                          14, gta3."CustomCode1",

                                                          15, gta3."CustomCode2",

                                                          16, gta3."CustomCode3",

                                                          17, gta3."CustomCode4",

                                                          18, gta3."CustomCode5",

                                                          19, gta3."CustomCode6",

                                                          20, gta3."CustomCode7",

                                                          21, gta3."CustomCode8",

                                                          22, gta3."CustomCode9",

                                                          23, gta3."CustomCode10",

                                                          ' '),

            gta3."PreviousGroupBy2Value" = decode(gta3."GroupBy2", 0, ' ',

                                                                  1, gta3."PreviousProducer",

                                                                  2, gta3."PreviousPGroup",

                                                                  3, gta3."PreviousTypeCode",

                                                                  4, trim(to_char(gta3."PreviousYear")),

                                                                  5, trim(to_char(gta3."PreviousAppUser")),

                                                                  6, gta3."PreviousCustom1",

                                                                  7, gta3."PreviousCustom2",

                                                                  8, gta3."PreviousDiscipline",

                                                                  9, trim(to_char(gta3."PreviousEntryUser")),

                                                                  10, gta3."PreviousLocation",

                                                                  11, gta3."PreviousClaimDoctor",

                                                                  12, trim(to_char(gta3."PreviousPractice")),

                                                                  13, gta3."PreviousProcedure",

                                                                  14, gta3."PreviousCustomCode1",

                                                                  15, gta3."PreviousCustomCode2",

                                                                  16, gta3."PreviousCustomCode3",

                                                                  17, gta3."PreviousCustomCode4",

                                                                  18, gta3."PreviousCustomCode5",

                                                                  19, gta3."PreviousCustomCode6",

                                                                  20, gta3."PreviousCustomCode7",

                                                                  21, gta3."PreviousCustomCode8",

                                                                  22, gta3."PreviousCustomCode9",

                                                                  23, gta3."PreviousCustomCode10",

                                                                  ' ')

          where 1=1;

        

        end if;



      else

        --

        -- delete records that are outside of the reporting period

        --

        vStep := 225;

      

        delete from global_temp_alloc3 gta3

        where 1=1

        and (gta3."TxModifiedDate" < vFromDate

            or gta3."TxModifiedDate" > vToDate);



        --

        -- check if there is a change in department

        --

        vStep := 230;



        select count(distinct gta3c."Department")

        into vDeptCount

        from (select gta3a."Department" "Department"

              from global_temp_alloc3 gta3a

              where 1=1

              union

              select gta3b."PreviousDepartment" "Department"

              from global_temp_alloc3 gta3b

              where 1=1) gta3c

        where 1=1;

        

        --

        -- delete non-allocate records if there is no change in department

        --

        if (vDeptCount = 1) then

          --

          -- delete non-allocate records if there is no grouping by 1 and no grouping by 2 and there is no change in department

          --

          vStep := 240;



          delete from global_temp_alloc3 gta3

          where 1=1

          and (gta3."HistoryType" not in (1, 3)

              or (gta3."HistoryType" = 1

                  and gta3."Payed" = 0));

          

        end if;



      end if;



      --

      -- delete records that are outside of the reporting period

      --

      vStep := 255;

      

      delete from global_temp_alloc3 gta3

      where 1=1

      and (gta3."TxModifiedDate" < vFromDate

          or gta3."TxModifiedDate" > vToDate);

      

      --

      -- finalize records for the current OrigRecNo

      --

      vStep := 250;

      

      for pOrigRecNo2 in cOrigRecNo2 loop

        --

        -- get correct amount

        --

        vStep := 260;

        

        vAmount := (case pOrigRecNo2."PayType"

                      when 3 then pOrigRecNo2."Payed"

                      when 4 then pOrigRecNo2."InsPayed"

                      when 6 then pOrigRecNo2."PtAdj"

                      when 7 then pOrigRecNo2."InsAdj"

                      else pOrigRecNo2."Amount"

                    end);

                    

        --

        -- get original "Type", "Id" and "Treatment" if Rebill (HistoryType = 5)

        --

        if (pOrigRecNo2."HistoryType" = 5) then

          --

          -- get history ID from deletion that happened before the rebill

          --

          vStep := 270;

          

          select nvl(max(gta2."History"), 0)

          into vMaxHistory

          from global_temp_alloc2 gta2

          where 1=1

          and gta2."HistoryType" = 4

          and gta2."History" < pOrigRecNo2."History";



          --

          -- get original "Type", "Id" and "Treatment" from deletion that happened before the rebill

          --

          if (vMaxHistory > 0) then

            

            begin

              --

              -- get original "Type", "Id" and "Treatment" from deletion that happened before the rebill

              --

              vStep := 280;

            

              select

                h."Type",

                h."Id",

                h."Treatment"

              into

                vOrigType,

                vOrigId,

                vOrigTreatment

              from history h

              where 1=1

              and "History" = vMaxHistory;

              

            exception

              when others then

                --

                -- assign zeroes to the variables

                --

                vStep := 290;

          

                vOrigType := 0;

                vOrigId := 0;

                vOrigTreatment := 0;

                

            end;



          else

            --

            -- assign zeroes to the variables

            --

            vStep := 300;

          

            vOrigType := 0;

            vOrigId := 0;

            vOrigTreatment := 0;

            

          end if;



        else

          --

          -- assign zeroes to the variables

          --

          vStep := 310;

          

          vMaxHistory := 0;

          vOrigType := 0;

          vOrigId := 0;

          vOrigTreatment := 0;

    

        end if;

                    

        --

        -- insert into 4th staging table

        --

        if ((pOrigRecNo2."HistoryType" in (1, 3)) and (pOrigRecNo2."Department" = vDepartment)) then

          --

          -- insert into 4th staging table if allocation

          --

          vStep := 320;

          

          insert into global_temp_alloc4

          values (

                  pOrigRecNo2."AllocatH",

                  pOrigRecNo2."PayType",

                  pOrigRecNo2."TrxType",

                  pOrigRecNo2."TrxId",

                  pOrigRecNo2."TrxTreatment",

                  pOrigRecNo2."Amount",

                  pOrigRecNo2."AllocateLink",

                  pOrigRecNo2."TxHistoryId",

                  pOrigRecNo2."PmtHistoryId",

                  pOrigRecNo2."OrigRecNo",

                  pOrigRecNo2."History",

                  pOrigRecNo2."HistoryType",

                  pOrigRecNo2."Patient",

                  pOrigRecNo2."TxModifiedDate",

                  pOrigRecNo2."Payed",

                  pOrigRecNo2."InsPayed",

                  pOrigRecNo2."PtAdj",

                  pOrigRecNo2."InsAdj",

                  pOrigRecNo2."InsTransfer",

                  pOrigRecNo2."Discipline",

                  pOrigRecNo2."Procedure",

                  pOrigRecNo2."Practice",

                  pOrigRecNo2."ClaimDoctor",

                  pOrigRecNo2."Location",

                  pOrigRecNo2."EntryUser",

                  pOrigRecNo2."AppUser",

                  pOrigRecNo2."Custom1",

                  pOrigRecNo2."Custom2",

                  pOrigRecNo2."Producer",

                  pOrigRecNo2."TypeCode",

                  pOrigRecNo2."PGroup",

                  pOrigRecNo2."Year",

                  pOrigRecNo2."CustomCode1",

                  pOrigRecNo2."CustomCode2",

                  pOrigRecNo2."CustomCode3",

                  pOrigRecNo2."CustomCode4",

                  pOrigRecNo2."CustomCode5",

                  pOrigRecNo2."CustomCode6",

                  pOrigRecNo2."CustomCode7",

                  pOrigRecNo2."CustomCode8",

                  pOrigRecNo2."CustomCode9",

                  pOrigRecNo2."CustomCode10",

                  pOrigRecNo2."Department",

                  decode(pOrigRecNo2."HistoryType", 1, vNew, vAllocate),

                  pOrigRecNo2."GroupBy1",

                  pOrigRecNo2."GroupBy2",

                  pOrigRecNo2."PreviousHistory",

                  pOrigRecNo2."PreviousDiscipline",

                  pOrigRecNo2."PreviousProcedure",

                  pOrigRecNo2."PreviousPractice",

                  pOrigRecNo2."PreviousClaimDoctor",

                  pOrigRecNo2."PreviousLocation",

                  pOrigRecNo2."PreviousEntryUser",

                  pOrigRecNo2."PreviousAppUser",

                  pOrigRecNo2."PreviousCustom1",

                  pOrigRecNo2."PreviousCustom2",

                  pOrigRecNo2."PreviousProducer",

                  pOrigRecNo2."PreviousTypeCode",

                  pOrigRecNo2."PreviousPGroup",

                  pOrigRecNo2."PreviousYear",

                  pOrigRecNo2."PreviousCustomCode1",

                  pOrigRecNo2."PreviousCustomCode2",

                  pOrigRecNo2."PreviousCustomCode3",

                  pOrigRecNo2."PreviousCustomCode4",

                  pOrigRecNo2."PreviousCustomCode5",

                  pOrigRecNo2."PreviousCustomCode6",

                  pOrigRecNo2."PreviousCustomCode7",

                  pOrigRecNo2."PreviousCustomCode8",

                  pOrigRecNo2."PreviousCustomCode9",

                  pOrigRecNo2."PreviousCustomCode10",

                  pOrigRecNo2."PreviousDepartment",

                  pOrigRecNo2."GroupBy1Value",

                  pOrigRecNo2."GroupBy2Value",

                  pOrigRecNo2."PreviousGroupBy1Value",

                  pOrigRecNo2."PreviousGroupBy2Value"

                );



        else

          --

          --  create offset records (transfer in/out) if group by 1 changes

          --

          if ((pOrigRecNo2."GroupBy1" > 0) and (pOrigRecNo2."PreviousGroupBy1Value" <> pOrigRecNo2."GroupBy1Value")) then

            --

            -- create offset records (transfer in/out) if only one payment/allocation

            --

            if ((pOrigRecNo2."HasAllocation" = 0) and (pOrigRecNo2."PayType" in (3, 4)) and (pOrigRecNo2."Amount" <= 0)) then

              --

              -- insert into 4th staging table (transfer out)

              --

              vStep := 330;

              

              insert into global_temp_alloc4

              values (

                      pOrigRecNo2."AllocatH",

                      pOrigRecNo2."PayType",

                      pOrigRecNo2."TrxType",

                      pOrigRecNo2."TrxId",

                      pOrigRecNo2."TrxTreatment",

                      (vAmount * -1),

                      pOrigRecNo2."AllocateLink",

                      pOrigRecNo2."PreviousHistory",

                      pOrigRecNo2."PmtHistoryId",

                      pOrigRecNo2."OrigRecNo",

                      pOrigRecNo2."History",

                      pOrigRecNo2."HistoryType",

                      pOrigRecNo2."Patient",

                      pOrigRecNo2."TxModifiedDate",

                      pOrigRecNo2."Payed",

                      pOrigRecNo2."InsPayed",

                      pOrigRecNo2."PtAdj",

                      pOrigRecNo2."InsAdj",

                      pOrigRecNo2."InsTransfer",

                      pOrigRecNo2."Discipline",

                      pOrigRecNo2."Procedure",

                      pOrigRecNo2."Practice",

                      pOrigRecNo2."ClaimDoctor",

                      pOrigRecNo2."Location",

                      pOrigRecNo2."EntryUser",

                      pOrigRecNo2."AppUser",

                      pOrigRecNo2."Custom1",

                      pOrigRecNo2."Custom2",

                      pOrigRecNo2."Producer",

                      pOrigRecNo2."TypeCode",

                      pOrigRecNo2."PGroup",

                      pOrigRecNo2."Year",

                      pOrigRecNo2."CustomCode1",

                      pOrigRecNo2."CustomCode2",

                      pOrigRecNo2."CustomCode3",

                      pOrigRecNo2."CustomCode4",

                      pOrigRecNo2."CustomCode5",

                      pOrigRecNo2."CustomCode6",

                      pOrigRecNo2."CustomCode7",

                      pOrigRecNo2."CustomCode8",

                      pOrigRecNo2."CustomCode9",

                      pOrigRecNo2."CustomCode10",

                      pOrigRecNo2."Department",

                      vTransferOut,

                      pOrigRecNo2."GroupBy1",

                      pOrigRecNo2."GroupBy2",

                      pOrigRecNo2."PreviousHistory",

                      pOrigRecNo2."PreviousDiscipline",

                      pOrigRecNo2."PreviousProcedure",

                      pOrigRecNo2."PreviousPractice",

                      pOrigRecNo2."PreviousClaimDoctor",

                      pOrigRecNo2."PreviousLocation",

                      pOrigRecNo2."PreviousEntryUser",

                      pOrigRecNo2."PreviousAppUser",

                      pOrigRecNo2."PreviousCustom1",

                      pOrigRecNo2."PreviousCustom2",

                      pOrigRecNo2."PreviousProducer",

                      pOrigRecNo2."PreviousTypeCode",

                      pOrigRecNo2."PreviousPGroup",

                      pOrigRecNo2."PreviousYear",

                      pOrigRecNo2."PreviousCustomCode1",

                      pOrigRecNo2."PreviousCustomCode2",

                      pOrigRecNo2."PreviousCustomCode3",

                      pOrigRecNo2."PreviousCustomCode4",

                      pOrigRecNo2."PreviousCustomCode5",

                      pOrigRecNo2."PreviousCustomCode6",

                      pOrigRecNo2."PreviousCustomCode7",

                      pOrigRecNo2."PreviousCustomCode8",

                      pOrigRecNo2."PreviousCustomCode9",

                      pOrigRecNo2."PreviousCustomCode10",

                      pOrigRecNo2."PreviousDepartment",

                      pOrigRecNo2."GroupBy1Value",

                      pOrigRecNo2."GroupBy2Value",

                      pOrigRecNo2."PreviousGroupBy1Value",

                      pOrigRecNo2."PreviousGroupBy2Value"

                    );



              --

              -- insert into 4th staging table (transfer in)

              --

              vStep := 340;

            

              insert into global_temp_alloc4

              values (

                      pOrigRecNo2."AllocatH",

                      pOrigRecNo2."PayType",

                      pOrigRecNo2."TrxType",

                      pOrigRecNo2."TrxId",

                      pOrigRecNo2."TrxTreatment",

                      vAmount,

                      pOrigRecNo2."AllocateLink",

                      pOrigRecNo2."History",

                      pOrigRecNo2."PmtHistoryId",

                      pOrigRecNo2."OrigRecNo",

                      pOrigRecNo2."History",

                      pOrigRecNo2."HistoryType",

                      pOrigRecNo2."Patient",

                      pOrigRecNo2."TxModifiedDate",

                      pOrigRecNo2."Payed",

                      pOrigRecNo2."InsPayed",

                      pOrigRecNo2."PtAdj",

                      pOrigRecNo2."InsAdj",

                      pOrigRecNo2."InsTransfer",

                      pOrigRecNo2."Discipline",

                      pOrigRecNo2."Procedure",

                      pOrigRecNo2."Practice",

                      pOrigRecNo2."ClaimDoctor",

                      pOrigRecNo2."Location",

                      pOrigRecNo2."EntryUser",

                      pOrigRecNo2."AppUser",

                      pOrigRecNo2."Custom1",

                      pOrigRecNo2."Custom2",

                      pOrigRecNo2."Producer",

                      pOrigRecNo2."TypeCode",

                      pOrigRecNo2."PGroup",

                      pOrigRecNo2."Year",

                      pOrigRecNo2."CustomCode1",

                      pOrigRecNo2."CustomCode2",

                      pOrigRecNo2."CustomCode3",

                      pOrigRecNo2."CustomCode4",

                      pOrigRecNo2."CustomCode5",

                      pOrigRecNo2."CustomCode6",

                      pOrigRecNo2."CustomCode7",

                      pOrigRecNo2."CustomCode8",

                      pOrigRecNo2."CustomCode9",

                      pOrigRecNo2."CustomCode10",

                      pOrigRecNo2."Department",

                      vTransferIn,

                      pOrigRecNo2."GroupBy1",

                      pOrigRecNo2."GroupBy2",

                      pOrigRecNo2."PreviousHistory",

                      pOrigRecNo2."PreviousDiscipline",

                      pOrigRecNo2."PreviousProcedure",

                      pOrigRecNo2."PreviousPractice",

                      pOrigRecNo2."PreviousClaimDoctor",

                      pOrigRecNo2."PreviousLocation",

                      pOrigRecNo2."PreviousEntryUser",

                      pOrigRecNo2."PreviousAppUser",

                      pOrigRecNo2."PreviousCustom1",

                      pOrigRecNo2."PreviousCustom2",

                      pOrigRecNo2."PreviousProducer",

                      pOrigRecNo2."PreviousTypeCode",

                      pOrigRecNo2."PreviousPGroup",

                      pOrigRecNo2."PreviousYear",

                      pOrigRecNo2."PreviousCustomCode1",

                      pOrigRecNo2."PreviousCustomCode2",

                      pOrigRecNo2."PreviousCustomCode3",

                      pOrigRecNo2."PreviousCustomCode4",

                      pOrigRecNo2."PreviousCustomCode5",

                      pOrigRecNo2."PreviousCustomCode6",

                      pOrigRecNo2."PreviousCustomCode7",

                      pOrigRecNo2."PreviousCustomCode8",

                      pOrigRecNo2."PreviousCustomCode9",

                      pOrigRecNo2."PreviousCustomCode10",

                      pOrigRecNo2."PreviousDepartment",

                      pOrigRecNo2."GroupBy1Value",

                      pOrigRecNo2."GroupBy2Value",

                      pOrigRecNo2."PreviousGroupBy1Value",

                      pOrigRecNo2."PreviousGroupBy2Value"

                    );



            else          

              --

              -- create offset records (transfer in/out) if more than one/multiple payments/allocations

              --

              vStep := 350;

                              

              for pAllocatH in cAllocatH (pOrigRecNo2."TrxType",

                                          pOrigRecNo2."TrxId",

                                          pOrigRecNo2."TrxTreatment",

                                          pOrigRecNo2."TxModifiedDate",

                                          vOrigType,

                                          vOrigId,

                                          vOrigTreatment) loop

                --

                -- insert into 4th staging table (transfer out)

                --

                vStep := 360;

              

                insert into global_temp_alloc4

                values (

                        pAllocatH."AllocatH",

                        pAllocatH."PayType",

                        pOrigRecNo2."TrxType",

                        pOrigRecNo2."TrxId",

                        pOrigRecNo2."TrxTreatment",

                        (pAllocatH."Amount" * -1),

                        pAllocatH."AllocateLink",

                        pOrigRecNo2."PreviousHistory",

                        pAllocatH."PmtHistoryId",

                        pOrigRecNo2."OrigRecNo",

                        pOrigRecNo2."History",

                        pOrigRecNo2."HistoryType",

                        pOrigRecNo2."Patient",

                        pOrigRecNo2."TxModifiedDate",

                        pOrigRecNo2."Payed",

                        pOrigRecNo2."InsPayed",

                        pOrigRecNo2."PtAdj",

                        pOrigRecNo2."InsAdj",

                        pOrigRecNo2."InsTransfer",

                        pOrigRecNo2."Discipline",

                        pOrigRecNo2."Procedure",

                        pOrigRecNo2."Practice",

                        pOrigRecNo2."ClaimDoctor",

                        pOrigRecNo2."Location",

                        pOrigRecNo2."EntryUser",

                        pOrigRecNo2."AppUser",

                        pOrigRecNo2."Custom1",

                        pOrigRecNo2."Custom2",

                        pOrigRecNo2."Producer",

                        pOrigRecNo2."TypeCode",

                        pOrigRecNo2."PGroup",

                        pOrigRecNo2."Year",

                        pOrigRecNo2."CustomCode1",

                        pOrigRecNo2."CustomCode2",

                        pOrigRecNo2."CustomCode3",

                        pOrigRecNo2."CustomCode4",

                        pOrigRecNo2."CustomCode5",

                        pOrigRecNo2."CustomCode6",

                        pOrigRecNo2."CustomCode7",

                        pOrigRecNo2."CustomCode8",

                        pOrigRecNo2."CustomCode9",

                        pOrigRecNo2."CustomCode10",

                        pOrigRecNo2."Department",

                        vTransferOut,

                        pOrigRecNo2."GroupBy1",

                        pOrigRecNo2."GroupBy2",

                        pOrigRecNo2."PreviousHistory",

                        pOrigRecNo2."PreviousDiscipline",

                        pOrigRecNo2."PreviousProcedure",

                        pOrigRecNo2."PreviousPractice",

                        pOrigRecNo2."PreviousClaimDoctor",

                        pOrigRecNo2."PreviousLocation",

                        pOrigRecNo2."PreviousEntryUser",

                        pOrigRecNo2."PreviousAppUser",

                        pOrigRecNo2."PreviousCustom1",

                        pOrigRecNo2."PreviousCustom2",

                        pOrigRecNo2."PreviousProducer",

                        pOrigRecNo2."PreviousTypeCode",

                        pOrigRecNo2."PreviousPGroup",

                        pOrigRecNo2."PreviousYear",

                        pOrigRecNo2."PreviousCustomCode1",

                        pOrigRecNo2."PreviousCustomCode2",

                        pOrigRecNo2."PreviousCustomCode3",

                        pOrigRecNo2."PreviousCustomCode4",

                        pOrigRecNo2."PreviousCustomCode5",

                        pOrigRecNo2."PreviousCustomCode6",

                        pOrigRecNo2."PreviousCustomCode7",

                        pOrigRecNo2."PreviousCustomCode8",

                        pOrigRecNo2."PreviousCustomCode9",

                        pOrigRecNo2."PreviousCustomCode10",

                        pOrigRecNo2."PreviousDepartment",

                        pOrigRecNo2."GroupBy1Value",

                        pOrigRecNo2."GroupBy2Value",

                        pOrigRecNo2."PreviousGroupBy1Value",

                        pOrigRecNo2."PreviousGroupBy2Value"

                      );



                --

                -- insert into 4th staging table (transfer in)

                --

                vStep := 370;

            

                insert into global_temp_alloc4

                values (

                        pAllocatH."AllocatH",

                        pAllocatH."PayType",

                        pOrigRecNo2."TrxType",

                        pOrigRecNo2."TrxId",

                        pOrigRecNo2."TrxTreatment",

                        pAllocatH."Amount",

                        pAllocatH."AllocateLink",

                        pOrigRecNo2."History",

                        pAllocatH."PmtHistoryId",

                        pOrigRecNo2."OrigRecNo",

                        pOrigRecNo2."History",

                        pOrigRecNo2."HistoryType",

                        pOrigRecNo2."Patient",

                        pOrigRecNo2."TxModifiedDate",

                        pOrigRecNo2."Payed",

                        pOrigRecNo2."InsPayed",

                        pOrigRecNo2."PtAdj",

                        pOrigRecNo2."InsAdj",

                        pOrigRecNo2."InsTransfer",

                        pOrigRecNo2."Discipline",

                        pOrigRecNo2."Procedure",

                        pOrigRecNo2."Practice",

                        pOrigRecNo2."ClaimDoctor",

                        pOrigRecNo2."Location",

                        pOrigRecNo2."EntryUser",

                        pOrigRecNo2."AppUser",

                        pOrigRecNo2."Custom1",

                        pOrigRecNo2."Custom2",

                        pOrigRecNo2."Producer",

                        pOrigRecNo2."TypeCode",

                        pOrigRecNo2."PGroup",

                        pOrigRecNo2."Year",

                        pOrigRecNo2."CustomCode1",

                        pOrigRecNo2."CustomCode2",

                        pOrigRecNo2."CustomCode3",

                        pOrigRecNo2."CustomCode4",

                        pOrigRecNo2."CustomCode5",

                        pOrigRecNo2."CustomCode6",

                        pOrigRecNo2."CustomCode7",

                        pOrigRecNo2."CustomCode8",

                        pOrigRecNo2."CustomCode9",

                        pOrigRecNo2."CustomCode10",

                        pOrigRecNo2."Department",

                        vTransferIn,

                        pOrigRecNo2."GroupBy1",

                        pOrigRecNo2."GroupBy2",

                        pOrigRecNo2."PreviousHistory",

                        pOrigRecNo2."PreviousDiscipline",

                        pOrigRecNo2."PreviousProcedure",

                        pOrigRecNo2."PreviousPractice",

                        pOrigRecNo2."PreviousClaimDoctor",

                        pOrigRecNo2."PreviousLocation",

                        pOrigRecNo2."PreviousEntryUser",

                        pOrigRecNo2."PreviousAppUser",

                        pOrigRecNo2."PreviousCustom1",

                        pOrigRecNo2."PreviousCustom2",

                        pOrigRecNo2."PreviousProducer",

                        pOrigRecNo2."PreviousTypeCode",

                        pOrigRecNo2."PreviousPGroup",

                        pOrigRecNo2."PreviousYear",

                        pOrigRecNo2."PreviousCustomCode1",

                        pOrigRecNo2."PreviousCustomCode2",

                        pOrigRecNo2."PreviousCustomCode3",

                        pOrigRecNo2."PreviousCustomCode4",

                        pOrigRecNo2."PreviousCustomCode5",

                        pOrigRecNo2."PreviousCustomCode6",

                        pOrigRecNo2."PreviousCustomCode7",

                        pOrigRecNo2."PreviousCustomCode8",

                        pOrigRecNo2."PreviousCustomCode9",

                        pOrigRecNo2."PreviousCustomCode10",

                        pOrigRecNo2."PreviousDepartment",

                        pOrigRecNo2."GroupBy1Value",

                        pOrigRecNo2."GroupBy2Value",

                        pOrigRecNo2."PreviousGroupBy1Value",

                        pOrigRecNo2."PreviousGroupBy2Value"

                      );



              end loop pAllocatH;

              

            end if;

          

          end if;



          --

          --  create offset records (transfer in/out) if group by 2 changes

          --

          if ((pOrigRecNo2."GroupBy2" > 0) and (pOrigRecNo2."PreviousGroupBy2Value" <> pOrigRecNo2."GroupBy2Value")) then

            --

            -- create offset records (transfer in/out) if only one payment/allocation

            --

            if ((pOrigRecNo2."HasAllocation" = 0) and (pOrigRecNo2."PayType" in (3, 4)) and (pOrigRecNo2."Amount" <= 0)) then

              --

              -- insert into 4th staging table (transfer out)

              --

              vStep := 380;

              

              insert into global_temp_alloc4

              values (

                      pOrigRecNo2."AllocatH",

                      pOrigRecNo2."PayType",

                      pOrigRecNo2."TrxType",

                      pOrigRecNo2."TrxId",

                      pOrigRecNo2."TrxTreatment",

                      vAmount,

                      pOrigRecNo2."AllocateLink",

                      pOrigRecNo2."PreviousHistory",

                      pOrigRecNo2."PmtHistoryId",

                      pOrigRecNo2."OrigRecNo",

                      pOrigRecNo2."History",

                      pOrigRecNo2."HistoryType",

                      pOrigRecNo2."Patient",

                      pOrigRecNo2."TxModifiedDate",

                      pOrigRecNo2."Payed",

                      pOrigRecNo2."InsPayed",

                      pOrigRecNo2."PtAdj",

                      pOrigRecNo2."InsAdj",

                      pOrigRecNo2."InsTransfer",

                      pOrigRecNo2."Discipline",

                      pOrigRecNo2."Procedure",

                      pOrigRecNo2."Practice",

                      pOrigRecNo2."ClaimDoctor",

                      pOrigRecNo2."Location",

                      pOrigRecNo2."EntryUser",

                      pOrigRecNo2."AppUser",

                      pOrigRecNo2."Custom1",

                      pOrigRecNo2."Custom2",

                      pOrigRecNo2."Producer",

                      pOrigRecNo2."TypeCode",

                      pOrigRecNo2."PGroup",

                      pOrigRecNo2."Year",

                      pOrigRecNo2."CustomCode1",

                      pOrigRecNo2."CustomCode2",

                      pOrigRecNo2."CustomCode3",

                      pOrigRecNo2."CustomCode4",

                      pOrigRecNo2."CustomCode5",

                      pOrigRecNo2."CustomCode6",

                      pOrigRecNo2."CustomCode7",

                      pOrigRecNo2."CustomCode8",

                      pOrigRecNo2."CustomCode9",

                      pOrigRecNo2."CustomCode10",

                      pOrigRecNo2."Department",

                      vTransferOut,

                      pOrigRecNo2."GroupBy1",

                      pOrigRecNo2."GroupBy2",

                      pOrigRecNo2."PreviousHistory",

                      pOrigRecNo2."PreviousDiscipline",

                      pOrigRecNo2."PreviousProcedure",

                      pOrigRecNo2."PreviousPractice",

                      pOrigRecNo2."PreviousClaimDoctor",

                      pOrigRecNo2."PreviousLocation",

                      pOrigRecNo2."PreviousEntryUser",

                      pOrigRecNo2."PreviousAppUser",

                      pOrigRecNo2."PreviousCustom1",

                      pOrigRecNo2."PreviousCustom2",

                      pOrigRecNo2."PreviousProducer",

                      pOrigRecNo2."PreviousTypeCode",

                      pOrigRecNo2."PreviousPGroup",

                      pOrigRecNo2."PreviousYear",

                      pOrigRecNo2."PreviousCustomCode1",

                      pOrigRecNo2."PreviousCustomCode2",

                      pOrigRecNo2."PreviousCustomCode3",

                      pOrigRecNo2."PreviousCustomCode4",

                      pOrigRecNo2."PreviousCustomCode5",

                      pOrigRecNo2."PreviousCustomCode6",

                      pOrigRecNo2."PreviousCustomCode7",

                      pOrigRecNo2."PreviousCustomCode8",

                      pOrigRecNo2."PreviousCustomCode9",

                      pOrigRecNo2."PreviousCustomCode10",

                      pOrigRecNo2."PreviousDepartment",

                      pOrigRecNo2."GroupBy1Value",

                      pOrigRecNo2."GroupBy2Value",

                      pOrigRecNo2."PreviousGroupBy1Value",

                      pOrigRecNo2."PreviousGroupBy2Value"

                    );



              --

              -- insert into 4th staging table (transfer in)

              --

              vStep := 390;

            

              insert into global_temp_alloc4

              values (

                      pOrigRecNo2."AllocatH",

                      pOrigRecNo2."PayType",

                      pOrigRecNo2."TrxType",

                      pOrigRecNo2."TrxId",

                      pOrigRecNo2."TrxTreatment",

                      vAmount,

                      pOrigRecNo2."AllocateLink",

                      pOrigRecNo2."History",

                      pOrigRecNo2."PmtHistoryId",

                      pOrigRecNo2."OrigRecNo",

                      pOrigRecNo2."History",

                      pOrigRecNo2."HistoryType",

                      pOrigRecNo2."Patient",

                      pOrigRecNo2."TxModifiedDate",

                      pOrigRecNo2."Payed",

                      pOrigRecNo2."InsPayed",

                      pOrigRecNo2."PtAdj",

                      pOrigRecNo2."InsAdj",

                      pOrigRecNo2."InsTransfer",

                      pOrigRecNo2."Discipline",

                      pOrigRecNo2."Procedure",

                      pOrigRecNo2."Practice",

                      pOrigRecNo2."ClaimDoctor",

                      pOrigRecNo2."Location",

                      pOrigRecNo2."EntryUser",

                      pOrigRecNo2."AppUser",

                      pOrigRecNo2."Custom1",

                      pOrigRecNo2."Custom2",

                      pOrigRecNo2."Producer",

                      pOrigRecNo2."TypeCode",

                      pOrigRecNo2."PGroup",

                      pOrigRecNo2."Year",

                      pOrigRecNo2."CustomCode1",

                      pOrigRecNo2."CustomCode2",

                      pOrigRecNo2."CustomCode3",

                      pOrigRecNo2."CustomCode4",

                      pOrigRecNo2."CustomCode5",

                      pOrigRecNo2."CustomCode6",

                      pOrigRecNo2."CustomCode7",

                      pOrigRecNo2."CustomCode8",

                      pOrigRecNo2."CustomCode9",

                      pOrigRecNo2."CustomCode10",

                      pOrigRecNo2."Department",

                      vTransferIn,

                      pOrigRecNo2."GroupBy1",

                      pOrigRecNo2."GroupBy2",

                      pOrigRecNo2."PreviousHistory",

                      pOrigRecNo2."PreviousDiscipline",

                      pOrigRecNo2."PreviousProcedure",

                      pOrigRecNo2."PreviousPractice",

                      pOrigRecNo2."PreviousClaimDoctor",

                      pOrigRecNo2."PreviousLocation",

                      pOrigRecNo2."PreviousEntryUser",

                      pOrigRecNo2."PreviousAppUser",

                      pOrigRecNo2."PreviousCustom1",

                      pOrigRecNo2."PreviousCustom2",

                      pOrigRecNo2."PreviousProducer",

                      pOrigRecNo2."PreviousTypeCode",

                      pOrigRecNo2."PreviousPGroup",

                      pOrigRecNo2."PreviousYear",

                      pOrigRecNo2."PreviousCustomCode1",

                      pOrigRecNo2."PreviousCustomCode2",

                      pOrigRecNo2."PreviousCustomCode3",

                      pOrigRecNo2."PreviousCustomCode4",

                      pOrigRecNo2."PreviousCustomCode5",

                      pOrigRecNo2."PreviousCustomCode6",

                      pOrigRecNo2."PreviousCustomCode7",

                      pOrigRecNo2."PreviousCustomCode8",

                      pOrigRecNo2."PreviousCustomCode9",

                      pOrigRecNo2."PreviousCustomCode10",

                      pOrigRecNo2."PreviousDepartment",

                      pOrigRecNo2."GroupBy1Value",

                      pOrigRecNo2."GroupBy2Value",

                      pOrigRecNo2."PreviousGroupBy1Value",

                      pOrigRecNo2."PreviousGroupBy2Value"

                    );



            else          

              --

              -- create offset records (transfer in/out) if more than one/multiple payments/allocations

              --

              vStep := 400;

                                          

              for pAllocatH in cAllocatH (pOrigRecNo2."TrxType",

                                          pOrigRecNo2."TrxId",

                                          pOrigRecNo2."TrxTreatment",

                                          pOrigRecNo2."TxModifiedDate",

                                          vOrigType,

                                          vOrigId,

                                          vOrigTreatment) loop

                --

                -- insert into 4th staging table (transfer out)

                --

                vStep := 410;

              

                insert into global_temp_alloc4

                values (

                        pAllocatH."AllocatH",

                        pAllocatH."PayType",

                        pOrigRecNo2."TrxType",

                        pOrigRecNo2."TrxId",

                        pOrigRecNo2."TrxTreatment",

                        (pAllocatH."Amount" * -1),

                        pAllocatH."AllocateLink",

                        pOrigRecNo2."PreviousHistory",

                        pAllocatH."PmtHistoryId",

                        pOrigRecNo2."OrigRecNo",

                        pOrigRecNo2."History",

                        pOrigRecNo2."HistoryType",

                        pOrigRecNo2."Patient",

                        pOrigRecNo2."TxModifiedDate",

                        pOrigRecNo2."Payed",

                        pOrigRecNo2."InsPayed",

                        pOrigRecNo2."PtAdj",

                        pOrigRecNo2."InsAdj",

                        pOrigRecNo2."InsTransfer",

                        pOrigRecNo2."Discipline",

                        pOrigRecNo2."Procedure",

                        pOrigRecNo2."Practice",

                        pOrigRecNo2."ClaimDoctor",

                        pOrigRecNo2."Location",

                        pOrigRecNo2."EntryUser",

                        pOrigRecNo2."AppUser",

                        pOrigRecNo2."Custom1",

                        pOrigRecNo2."Custom2",

                        pOrigRecNo2."Producer",

                        pOrigRecNo2."TypeCode",

                        pOrigRecNo2."PGroup",

                        pOrigRecNo2."Year",

                        pOrigRecNo2."CustomCode1",

                        pOrigRecNo2."CustomCode2",

                        pOrigRecNo2."CustomCode3",

                        pOrigRecNo2."CustomCode4",

                        pOrigRecNo2."CustomCode5",

                        pOrigRecNo2."CustomCode6",

                        pOrigRecNo2."CustomCode7",

                        pOrigRecNo2."CustomCode8",

                        pOrigRecNo2."CustomCode9",

                        pOrigRecNo2."CustomCode10",

                        pOrigRecNo2."Department",

                        vTransferOut,

                        pOrigRecNo2."GroupBy1",

                        pOrigRecNo2."GroupBy2",

                        pOrigRecNo2."PreviousHistory",

                        pOrigRecNo2."PreviousDiscipline",

                        pOrigRecNo2."PreviousProcedure",

                        pOrigRecNo2."PreviousPractice",

                        pOrigRecNo2."PreviousClaimDoctor",

                        pOrigRecNo2."PreviousLocation",

                        pOrigRecNo2."PreviousEntryUser",

                        pOrigRecNo2."PreviousAppUser",

                        pOrigRecNo2."PreviousCustom1",

                        pOrigRecNo2."PreviousCustom2",

                        pOrigRecNo2."PreviousProducer",

                        pOrigRecNo2."PreviousTypeCode",

                        pOrigRecNo2."PreviousPGroup",

                        pOrigRecNo2."PreviousYear",

                        pOrigRecNo2."PreviousCustomCode1",

                        pOrigRecNo2."PreviousCustomCode2",

                        pOrigRecNo2."PreviousCustomCode3",

                        pOrigRecNo2."PreviousCustomCode4",

                        pOrigRecNo2."PreviousCustomCode5",

                        pOrigRecNo2."PreviousCustomCode6",

                        pOrigRecNo2."PreviousCustomCode7",

                        pOrigRecNo2."PreviousCustomCode8",

                        pOrigRecNo2."PreviousCustomCode9",

                        pOrigRecNo2."PreviousCustomCode10",

                        pOrigRecNo2."PreviousDepartment",

                        pOrigRecNo2."GroupBy1Value",

                        pOrigRecNo2."GroupBy2Value",

                        pOrigRecNo2."PreviousGroupBy1Value",

                        pOrigRecNo2."PreviousGroupBy2Value"

                      );



                --

                -- insert into 4th staging table (transfer in)

                --

                vStep := 420;

            

                insert into global_temp_alloc4

                values (

                        pAllocatH."AllocatH",

                        pAllocatH."PayType",

                        pOrigRecNo2."TrxType",

                        pOrigRecNo2."TrxId",

                        pOrigRecNo2."TrxTreatment",

                        pAllocatH."Amount",

                        pAllocatH."AllocateLink",

                        pOrigRecNo2."History",

                        pAllocatH."PmtHistoryId",

                        pOrigRecNo2."OrigRecNo",

                        pOrigRecNo2."History",

                        pOrigRecNo2."HistoryType",

                        pOrigRecNo2."Patient",

                        pOrigRecNo2."TxModifiedDate",

                        pOrigRecNo2."Payed",

                        pOrigRecNo2."InsPayed",

                        pOrigRecNo2."PtAdj",

                        pOrigRecNo2."InsAdj",

                        pOrigRecNo2."InsTransfer",

                        pOrigRecNo2."Discipline",

                        pOrigRecNo2."Procedure",

                        pOrigRecNo2."Practice",

                        pOrigRecNo2."ClaimDoctor",

                        pOrigRecNo2."Location",

                        pOrigRecNo2."EntryUser",

                        pOrigRecNo2."AppUser",

                        pOrigRecNo2."Custom1",

                        pOrigRecNo2."Custom2",

                        pOrigRecNo2."Producer",

                        pOrigRecNo2."TypeCode",

                        pOrigRecNo2."PGroup",

                        pOrigRecNo2."Year",

                        pOrigRecNo2."CustomCode1",

                        pOrigRecNo2."CustomCode2",

                        pOrigRecNo2."CustomCode3",

                        pOrigRecNo2."CustomCode4",

                        pOrigRecNo2."CustomCode5",

                        pOrigRecNo2."CustomCode6",

                        pOrigRecNo2."CustomCode7",

                        pOrigRecNo2."CustomCode8",

                        pOrigRecNo2."CustomCode9",

                        pOrigRecNo2."CustomCode10",

                        pOrigRecNo2."Department",

                        vTransferIn,

                        pOrigRecNo2."GroupBy1",

                        pOrigRecNo2."GroupBy2",

                        pOrigRecNo2."PreviousHistory",

                        pOrigRecNo2."PreviousDiscipline",

                        pOrigRecNo2."PreviousProcedure",

                        pOrigRecNo2."PreviousPractice",

                        pOrigRecNo2."PreviousClaimDoctor",

                        pOrigRecNo2."PreviousLocation",

                        pOrigRecNo2."PreviousEntryUser",

                        pOrigRecNo2."PreviousAppUser",

                        pOrigRecNo2."PreviousCustom1",

                        pOrigRecNo2."PreviousCustom2",

                        pOrigRecNo2."PreviousProducer",

                        pOrigRecNo2."PreviousTypeCode",

                        pOrigRecNo2."PreviousPGroup",

                        pOrigRecNo2."PreviousYear",

                        pOrigRecNo2."PreviousCustomCode1",

                        pOrigRecNo2."PreviousCustomCode2",

                        pOrigRecNo2."PreviousCustomCode3",

                        pOrigRecNo2."PreviousCustomCode4",

                        pOrigRecNo2."PreviousCustomCode5",

                        pOrigRecNo2."PreviousCustomCode6",

                        pOrigRecNo2."PreviousCustomCode7",

                        pOrigRecNo2."PreviousCustomCode8",

                        pOrigRecNo2."PreviousCustomCode9",

                        pOrigRecNo2."PreviousCustomCode10",

                        pOrigRecNo2."PreviousDepartment",

                        pOrigRecNo2."GroupBy1Value",

                        pOrigRecNo2."GroupBy2Value",

                        pOrigRecNo2."PreviousGroupBy1Value",

                        pOrigRecNo2."PreviousGroupBy2Value"

                      );



              end loop pAllocatH;

              

            end if;



          end if;



          --

          -- create department changes entries (transfer out)

          --

          if ((pOrigRecNo2."DeptCount" > 1) and (pOrigRecNo2."PreviousDepartment" <> pOrigRecNo2."Department") and (pOrigRecNo2."PreviousDepartment" = vDepartment)) then

            --

            -- create offset records (transfer out) if only one payment/allocation

            --

            if ((pOrigRecNo2."HasAllocation" = 0) and (pOrigRecNo2."PayType" in (3, 4)) and (pOrigRecNo2."Amount" <= 0)) then

              --

              -- insert into 4th staging table (transfer out)

              --

              vStep := 430;

          

              insert into global_temp_alloc4

              values (

                      pOrigRecNo2."AllocatH",

                      pOrigRecNo2."PayType",

                      pOrigRecNo2."TrxType",

                      pOrigRecNo2."TrxId",

                      pOrigRecNo2."TrxTreatment",

                      (vAmount * -1),

                      pOrigRecNo2."AllocateLink",

                      pOrigRecNo2."PreviousHistory",

                      pOrigRecNo2."PmtHistoryId",

                      pOrigRecNo2."OrigRecNo",

                      pOrigRecNo2."History",

                      pOrigRecNo2."HistoryType",

                      pOrigRecNo2."Patient",

                      pOrigRecNo2."TxModifiedDate",

                      pOrigRecNo2."Payed",

                      pOrigRecNo2."InsPayed",

                      pOrigRecNo2."PtAdj",

                      pOrigRecNo2."InsAdj",

                      pOrigRecNo2."InsTransfer",

                      pOrigRecNo2."Discipline",

                      pOrigRecNo2."Procedure",

                      pOrigRecNo2."Practice",

                      pOrigRecNo2."ClaimDoctor",

                      pOrigRecNo2."Location",

                      pOrigRecNo2."EntryUser",

                      pOrigRecNo2."AppUser",

                      pOrigRecNo2."Custom1",

                      pOrigRecNo2."Custom2",

                      pOrigRecNo2."Producer",

                      pOrigRecNo2."TypeCode",

                      pOrigRecNo2."PGroup",

                      pOrigRecNo2."Year",

                      pOrigRecNo2."CustomCode1",

                      pOrigRecNo2."CustomCode2",

                      pOrigRecNo2."CustomCode3",

                      pOrigRecNo2."CustomCode4",

                      pOrigRecNo2."CustomCode5",

                      pOrigRecNo2."CustomCode6",

                      pOrigRecNo2."CustomCode7",

                      pOrigRecNo2."CustomCode8",

                      pOrigRecNo2."CustomCode9",

                      pOrigRecNo2."CustomCode10",

                      pOrigRecNo2."Department",

                      vTransferOut,

                      pOrigRecNo2."GroupBy1",

                      pOrigRecNo2."GroupBy2",

                      pOrigRecNo2."PreviousHistory",

                      pOrigRecNo2."PreviousDiscipline",

                      pOrigRecNo2."PreviousProcedure",

                      pOrigRecNo2."PreviousPractice",

                      pOrigRecNo2."PreviousClaimDoctor",

                      pOrigRecNo2."PreviousLocation",

                      pOrigRecNo2."PreviousEntryUser",

                      pOrigRecNo2."PreviousAppUser",

                      pOrigRecNo2."PreviousCustom1",

                      pOrigRecNo2."PreviousCustom2",

                      pOrigRecNo2."PreviousProducer",

                      pOrigRecNo2."PreviousTypeCode",

                      pOrigRecNo2."PreviousPGroup",

                      pOrigRecNo2."PreviousYear",

                      pOrigRecNo2."PreviousCustomCode1",

                      pOrigRecNo2."PreviousCustomCode2",

                      pOrigRecNo2."PreviousCustomCode3",

                      pOrigRecNo2."PreviousCustomCode4",

                      pOrigRecNo2."PreviousCustomCode5",

                      pOrigRecNo2."PreviousCustomCode6",

                      pOrigRecNo2."PreviousCustomCode7",

                      pOrigRecNo2."PreviousCustomCode8",

                      pOrigRecNo2."PreviousCustomCode9",

                      pOrigRecNo2."PreviousCustomCode10",

                      pOrigRecNo2."PreviousDepartment",

                      pOrigRecNo2."GroupBy1Value",

                      pOrigRecNo2."GroupBy2Value",

                      pOrigRecNo2."PreviousGroupBy1Value",

                      pOrigRecNo2."PreviousGroupBy2Value"

                    );



            else          

              --

              -- create offset records (transfer out) if more than one/multiple payments/allocations

              --

              vStep := 440;

                                          

              for pAllocatH in cAllocatH (pOrigRecNo2."TrxType",

                                          pOrigRecNo2."TrxId",

                                          pOrigRecNo2."TrxTreatment",

                                          pOrigRecNo2."TxModifiedDate",

                                          vOrigType,

                                          vOrigId,

                                          vOrigTreatment) loop

                --

                -- insert into 4th staging table (transfer out)

                --

                vStep := 450;

              

                insert into global_temp_alloc4

                values (

                        pAllocatH."AllocatH",

                        pAllocatH."PayType",

                        pOrigRecNo2."TrxType",

                        pOrigRecNo2."TrxId",

                        pOrigRecNo2."TrxTreatment",

                        (pAllocatH."Amount" * -1),

                        pAllocatH."AllocateLink",

                        pOrigRecNo2."PreviousHistory",

                        pAllocatH."PmtHistoryId",

                        pOrigRecNo2."OrigRecNo",

                        pOrigRecNo2."History",

                        pOrigRecNo2."HistoryType",

                        pOrigRecNo2."Patient",

                        pOrigRecNo2."TxModifiedDate",

                        pOrigRecNo2."Payed",

                        pOrigRecNo2."InsPayed",

                        pOrigRecNo2."PtAdj",

                        pOrigRecNo2."InsAdj",

                        pOrigRecNo2."InsTransfer",

                        pOrigRecNo2."Discipline",

                        pOrigRecNo2."Procedure",

                        pOrigRecNo2."Practice",

                        pOrigRecNo2."ClaimDoctor",

                        pOrigRecNo2."Location",

                        pOrigRecNo2."EntryUser",

                        pOrigRecNo2."AppUser",

                        pOrigRecNo2."Custom1",

                        pOrigRecNo2."Custom2",

                        pOrigRecNo2."Producer",

                        pOrigRecNo2."TypeCode",

                        pOrigRecNo2."PGroup",

                        pOrigRecNo2."Year",

                        pOrigRecNo2."CustomCode1",

                        pOrigRecNo2."CustomCode2",

                        pOrigRecNo2."CustomCode3",

                        pOrigRecNo2."CustomCode4",

                        pOrigRecNo2."CustomCode5",

                        pOrigRecNo2."CustomCode6",

                        pOrigRecNo2."CustomCode7",

                        pOrigRecNo2."CustomCode8",

                        pOrigRecNo2."CustomCode9",

                        pOrigRecNo2."CustomCode10",

                        pOrigRecNo2."Department",

                        vTransferOut,

                        pOrigRecNo2."GroupBy1",

                        pOrigRecNo2."GroupBy2",

                        pOrigRecNo2."PreviousHistory",

                        pOrigRecNo2."PreviousDiscipline",

                        pOrigRecNo2."PreviousProcedure",

                        pOrigRecNo2."PreviousPractice",

                        pOrigRecNo2."PreviousClaimDoctor",

                        pOrigRecNo2."PreviousLocation",

                        pOrigRecNo2."PreviousEntryUser",

                        pOrigRecNo2."PreviousAppUser",

                        pOrigRecNo2."PreviousCustom1",

                        pOrigRecNo2."PreviousCustom2",

                        pOrigRecNo2."PreviousProducer",

                        pOrigRecNo2."PreviousTypeCode",

                        pOrigRecNo2."PreviousPGroup",

                        pOrigRecNo2."PreviousYear",

                        pOrigRecNo2."PreviousCustomCode1",

                        pOrigRecNo2."PreviousCustomCode2",

                        pOrigRecNo2."PreviousCustomCode3",

                        pOrigRecNo2."PreviousCustomCode4",

                        pOrigRecNo2."PreviousCustomCode5",

                        pOrigRecNo2."PreviousCustomCode6",

                        pOrigRecNo2."PreviousCustomCode7",

                        pOrigRecNo2."PreviousCustomCode8",

                        pOrigRecNo2."PreviousCustomCode9",

                        pOrigRecNo2."PreviousCustomCode10",

                        pOrigRecNo2."PreviousDepartment",

                        pOrigRecNo2."GroupBy1Value",

                        pOrigRecNo2."GroupBy2Value",

                        pOrigRecNo2."PreviousGroupBy1Value",

                        pOrigRecNo2."PreviousGroupBy2Value"

                      );



              end loop pAllocatH;

            

            end if;



          end if;



          --

          -- create department changes entries (transfer in)

          --

          if ((pOrigRecNo2."DeptCount" > 1) and (pOrigRecNo2."PreviousDepartment" <> pOrigRecNo2."Department") and (pOrigRecNo2."Department" = vDepartment)) then

            --

            -- create offset records (transfer in) if only one payment/allocation

            --

            if ((pOrigRecNo2."HasAllocation" = 0) and (pOrigRecNo2."PayType" in (3, 4)) and (pOrigRecNo2."Amount" <= 0)) then

              --

              -- insert into 4th staging table (transfer in)

              --

              vStep := 460;

          

              insert into global_temp_alloc4

              values (

                      pOrigRecNo2."AllocatH",

                      pOrigRecNo2."PayType",

                      pOrigRecNo2."TrxType",

                      pOrigRecNo2."TrxId",

                      pOrigRecNo2."TrxTreatment",

                      vAmount,

                      pOrigRecNo2."AllocateLink",

                      pOrigRecNo2."History",

                      pOrigRecNo2."PmtHistoryId",

                      pOrigRecNo2."OrigRecNo",

                      pOrigRecNo2."History",

                      pOrigRecNo2."HistoryType",

                      pOrigRecNo2."Patient",

                      pOrigRecNo2."TxModifiedDate",

                      pOrigRecNo2."Payed",

                      pOrigRecNo2."InsPayed",

                      pOrigRecNo2."PtAdj",

                      pOrigRecNo2."InsAdj",

                      pOrigRecNo2."InsTransfer",

                      pOrigRecNo2."Discipline",

                      pOrigRecNo2."Procedure",

                      pOrigRecNo2."Practice",

                      pOrigRecNo2."ClaimDoctor",

                      pOrigRecNo2."Location",

                      pOrigRecNo2."EntryUser",

                      pOrigRecNo2."AppUser",

                      pOrigRecNo2."Custom1",

                      pOrigRecNo2."Custom2",

                      pOrigRecNo2."Producer",

                      pOrigRecNo2."TypeCode",

                      pOrigRecNo2."PGroup",

                      pOrigRecNo2."Year",

                      pOrigRecNo2."CustomCode1",

                      pOrigRecNo2."CustomCode2",

                      pOrigRecNo2."CustomCode3",

                      pOrigRecNo2."CustomCode4",

                      pOrigRecNo2."CustomCode5",

                      pOrigRecNo2."CustomCode6",

                      pOrigRecNo2."CustomCode7",

                      pOrigRecNo2."CustomCode8",

                      pOrigRecNo2."CustomCode9",

                      pOrigRecNo2."CustomCode10",

                      pOrigRecNo2."Department",

                      vTransferIn,

                      pOrigRecNo2."GroupBy1",

                      pOrigRecNo2."GroupBy2",

                      pOrigRecNo2."PreviousHistory",

                      pOrigRecNo2."PreviousDiscipline",

                      pOrigRecNo2."PreviousProcedure",

                      pOrigRecNo2."PreviousPractice",

                      pOrigRecNo2."PreviousClaimDoctor",

                      pOrigRecNo2."PreviousLocation",

                      pOrigRecNo2."PreviousEntryUser",

                      pOrigRecNo2."PreviousAppUser",

                      pOrigRecNo2."PreviousCustom1",

                      pOrigRecNo2."PreviousCustom2",

                      pOrigRecNo2."PreviousProducer",

                      pOrigRecNo2."PreviousTypeCode",

                      pOrigRecNo2."PreviousPGroup",

                      pOrigRecNo2."PreviousYear",

                      pOrigRecNo2."PreviousCustomCode1",

                      pOrigRecNo2."PreviousCustomCode2",

                      pOrigRecNo2."PreviousCustomCode3",

                      pOrigRecNo2."PreviousCustomCode4",

                      pOrigRecNo2."PreviousCustomCode5",

                      pOrigRecNo2."PreviousCustomCode6",

                      pOrigRecNo2."PreviousCustomCode7",

                      pOrigRecNo2."PreviousCustomCode8",

                      pOrigRecNo2."PreviousCustomCode9",

                      pOrigRecNo2."PreviousCustomCode10",

                      pOrigRecNo2."PreviousDepartment",

                      pOrigRecNo2."GroupBy1Value",

                      pOrigRecNo2."GroupBy2Value",

                      pOrigRecNo2."PreviousGroupBy1Value",

                      pOrigRecNo2."PreviousGroupBy2Value"

                    );



            else

              --

              -- create offset records (transfer in) if more than one/multiple payments/allocations

              --

              vStep := 470;

                                          

              for pAllocatH in cAllocatH (pOrigRecNo2."TrxType",

                                          pOrigRecNo2."TrxId",

                                          pOrigRecNo2."TrxTreatment",

                                          pOrigRecNo2."TxModifiedDate",

                                          vOrigType,

                                          vOrigId,

                                          vOrigTreatment) loop

                --

                -- insert into 4th staging table (transfer in)

                --

                vStep := 480;

              

                insert into global_temp_alloc4

                values (              

                        pAllocatH."AllocatH",

                        pAllocatH."PayType",

                        pOrigRecNo2."TrxType",

                        pOrigRecNo2."TrxId",

                        pOrigRecNo2."TrxTreatment",

                        pAllocatH."Amount",

                        pAllocatH."AllocateLink",

                        pOrigRecNo2."History",

                        pAllocatH."PmtHistoryId",

                        pOrigRecNo2."OrigRecNo",

                        pOrigRecNo2."History",

                        pOrigRecNo2."HistoryType",

                        pOrigRecNo2."Patient",

                        pOrigRecNo2."TxModifiedDate",

                        pOrigRecNo2."Payed",

                        pOrigRecNo2."InsPayed",

                        pOrigRecNo2."PtAdj",

                        pOrigRecNo2."InsAdj",

                        pOrigRecNo2."InsTransfer",

                        pOrigRecNo2."Discipline",

                        pOrigRecNo2."Procedure",

                        pOrigRecNo2."Practice",

                        pOrigRecNo2."ClaimDoctor",

                        pOrigRecNo2."Location",

                        pOrigRecNo2."EntryUser",

                        pOrigRecNo2."AppUser",

                        pOrigRecNo2."Custom1",

                        pOrigRecNo2."Custom2",

                        pOrigRecNo2."Producer",

                        pOrigRecNo2."TypeCode",

                        pOrigRecNo2."PGroup",

                        pOrigRecNo2."Year",

                        pOrigRecNo2."CustomCode1",

                        pOrigRecNo2."CustomCode2",

                        pOrigRecNo2."CustomCode3",

                        pOrigRecNo2."CustomCode4",

                        pOrigRecNo2."CustomCode5",

                        pOrigRecNo2."CustomCode6",

                        pOrigRecNo2."CustomCode7",

                        pOrigRecNo2."CustomCode8",

                        pOrigRecNo2."CustomCode9",

                        pOrigRecNo2."CustomCode10",

                        pOrigRecNo2."Department",

                        vTransferIn,

                        pOrigRecNo2."GroupBy1",

                        pOrigRecNo2."GroupBy2",

                        pOrigRecNo2."PreviousHistory",

                        pOrigRecNo2."PreviousDiscipline",

                        pOrigRecNo2."PreviousProcedure",

                        pOrigRecNo2."PreviousPractice",

                        pOrigRecNo2."PreviousClaimDoctor",

                        pOrigRecNo2."PreviousLocation",

                        pOrigRecNo2."PreviousEntryUser",

                        pOrigRecNo2."PreviousAppUser",

                        pOrigRecNo2."PreviousCustom1",

                        pOrigRecNo2."PreviousCustom2",

                        pOrigRecNo2."PreviousProducer",

                        pOrigRecNo2."PreviousTypeCode",

                        pOrigRecNo2."PreviousPGroup",

                        pOrigRecNo2."PreviousYear",

                        pOrigRecNo2."PreviousCustomCode1",

                        pOrigRecNo2."PreviousCustomCode2",

                        pOrigRecNo2."PreviousCustomCode3",

                        pOrigRecNo2."PreviousCustomCode4",

                        pOrigRecNo2."PreviousCustomCode5",

                        pOrigRecNo2."PreviousCustomCode6",

                        pOrigRecNo2."PreviousCustomCode7",

                        pOrigRecNo2."PreviousCustomCode8",

                        pOrigRecNo2."PreviousCustomCode9",

                        pOrigRecNo2."PreviousCustomCode10",

                        pOrigRecNo2."PreviousDepartment",

                        pOrigRecNo2."GroupBy1Value",

                        pOrigRecNo2."GroupBy2Value",

                        pOrigRecNo2."PreviousGroupBy1Value",

                        pOrigRecNo2."PreviousGroupBy2Value"

                      );



              end loop pAllocatH;

              

            end if;

            

          end if;



        end if;

      

        --

        -- reset vAmount variable to zero

        --

        vStep := 490;

        

        vAmount := 0;



      end loop pOrigRecNo2;



      --

      -- clear temporary table 2

      --

      vStep := 500;

      

      delete from global_temp_alloc2;

      

      --

      -- clear temporary table 3

      --

      vStep := 510;

      

      delete from global_temp_alloc3;



      --

      -- delete duplicates from temporary table 4

      --

      vStep := 515;



      delete from global_temp_alloc4 gta4c

      where 1=1

      and gta4c.ctid not in (select gta4b."RowID"

                              from (select

                                      gta4.ctid "RowID",

                                      (row_number() over (partition by

                                                            gta4."AllocatH",

                                                            gta4."PayType",

                                                            gta4."TrxType",

                                                            gta4."TrxId",

                                                            gta4."TrxTreatment",

                                                            gta4."Amount",

                                                            gta4."AllocateLink",

                                                            gta4."TxHistoryId",

                                                            gta4."PmtHistoryId",

                                                            gta4."OrigRecNo",

                                                            gta4."History",

                                                            gta4."HistoryType",

                                                            gta4."Patient",

                                                            gta4."TxModifiedDate",

                                                            gta4."Payed",

                                                            gta4."InsPayed",

                                                            gta4."PtAdj",

                                                            gta4."InsAdj",

                                                            gta4."InsTransfer",

                                                            gta4."Discipline",

                                                            gta4."Procedure",

                                                            gta4."Practice",

                                                            gta4."ClaimDoctor",

                                                            gta4."Location",

                                                            gta4."EntryUser",

                                                            gta4."AppUser",

                                                            gta4."Custom1",

                                                            gta4."Custom2",

                                                            gta4."Producer",

                                                            gta4."TypeCode",

                                                            gta4."PGroup",

                                                            gta4."Year",

                                                            gta4."CustomCode1",

                                                            gta4."CustomCode2",

                                                            gta4."CustomCode3",

                                                            gta4."CustomCode4",

                                                            gta4."CustomCode5",

                                                            gta4."CustomCode6",

                                                            gta4."CustomCode7",

                                                            gta4."CustomCode8",

                                                            gta4."CustomCode9",

                                                            gta4."CustomCode10",

                                                            gta4."Department",

                                                            gta4."HistoryTypeDescription",

                                                            gta4."GroupBy1",

                                                            gta4."GroupBy2",

                                                            gta4."PreviousHistory",

                                                            gta4."PreviousDiscipline",

                                                            gta4."PreviousProcedure",

                                                            gta4."PreviousPractice",

                                                            gta4."PreviousClaimDoctor",

                                                            gta4."PreviousLocation",

                                                            gta4."PreviousEntryUser",

                                                            gta4."PreviousAppUser",

                                                            gta4."PreviousCustom1",

                                                            gta4."PreviousCustom2",

                                                            gta4."PreviousProducer",

                                                            gta4."PreviousTypeCode",

                                                            gta4."PreviousPGroup",

                                                            gta4."PreviousYear",

                                                            gta4."PreviousCustomCode1",

                                                            gta4."PreviousCustomCode2",

                                                            gta4."PreviousCustomCode3",

                                                            gta4."PreviousCustomCode4",

                                                            gta4."PreviousCustomCode5",

                                                            gta4."PreviousCustomCode6",

                                                            gta4."PreviousCustomCode7",

                                                            gta4."PreviousCustomCode8",

                                                            gta4."PreviousCustomCode9",

                                                            gta4."PreviousCustomCode10",

                                                            gta4."PreviousDepartment",

                                                            gta4."GroupBy1Value",

                                                            gta4."GroupBy2Value",

                                                            gta4."PreviousGroupBy1Value",

                                                            gta4."PreviousGroupBy2Value"

                                                          order by

                                                            gta4."AllocatH",

                                                            gta4."PayType",

                                                            gta4."TrxType",

                                                            gta4."TrxId",

                                                            gta4."TrxTreatment",

                                                            gta4."Amount",

                                                            gta4."AllocateLink",

                                                            gta4."TxHistoryId",

                                                            gta4."PmtHistoryId",

                                                            gta4."OrigRecNo",

                                                            gta4."History",

                                                            gta4."HistoryType",

                                                            gta4."Patient",

                                                            gta4."TxModifiedDate",

                                                            gta4."Payed",

                                                            gta4."InsPayed",

                                                            gta4."PtAdj",

                                                            gta4."InsAdj",

                                                            gta4."InsTransfer",

                                                            gta4."Discipline",

                                                            gta4."Procedure",

                                                            gta4."Practice",

                                                            gta4."ClaimDoctor",

                                                            gta4."Location",

                                                            gta4."EntryUser",

                                                            gta4."AppUser",

                                                            gta4."Custom1",

                                                            gta4."Custom2",

                                                            gta4."Producer",

                                                            gta4."TypeCode",

                                                            gta4."PGroup",

                                                            gta4."Year",

                                                            gta4."CustomCode1",

                                                            gta4."CustomCode2",

                                                            gta4."CustomCode3",

                                                            gta4."CustomCode4",

                                                            gta4."CustomCode5",

                                                            gta4."CustomCode6",

                                                            gta4."CustomCode7",

                                                            gta4."CustomCode8",

                                                            gta4."CustomCode9",

                                                            gta4."CustomCode10",

                                                            gta4."Department",

                                                            gta4."HistoryTypeDescription",

                                                            gta4."GroupBy1",

                                                            gta4."GroupBy2",

                                                            gta4."PreviousHistory",

                                                            gta4."PreviousDiscipline",

                                                            gta4."PreviousProcedure",

                                                            gta4."PreviousPractice",

                                                            gta4."PreviousClaimDoctor",

                                                            gta4."PreviousLocation",

                                                            gta4."PreviousEntryUser",

                                                            gta4."PreviousAppUser",

                                                            gta4."PreviousCustom1",

                                                            gta4."PreviousCustom2",

                                                            gta4."PreviousProducer",

                                                            gta4."PreviousTypeCode",

                                                            gta4."PreviousPGroup",

                                                            gta4."PreviousYear",

                                                            gta4."PreviousCustomCode1",

                                                            gta4."PreviousCustomCode2",

                                                            gta4."PreviousCustomCode3",

                                                            gta4."PreviousCustomCode4",

                                                            gta4."PreviousCustomCode5",

                                                            gta4."PreviousCustomCode6",

                                                            gta4."PreviousCustomCode7",

                                                            gta4."PreviousCustomCode8",

                                                            gta4."PreviousCustomCode9",

                                                            gta4."PreviousCustomCode10",

                                                            gta4."PreviousDepartment",

                                                            gta4."GroupBy1Value",

                                                            gta4."GroupBy2Value",

                                                            gta4."PreviousGroupBy1Value",

                                                            gta4."PreviousGroupBy2Value")) "RowNumber"

                                    from global_temp_alloc4 gta4

                                    where 1=1

                                    and gta4."OrigRecNo" = gta4c."OrigRecNo") gta4b

                              where 1=1

                              and gta4b."RowNumber" = 1)

      and gta4c."OrigRecNo" = pOrigRecNo."OrigRecNo";

      

    end loop pOrigRecNo;

      

    --

    -- remove unnecessary records

    --

    vStep := 520;

    

    delete from global_temp_alloc4 gta4

    where 1=1

    and (

        -- remove records that are not for the department (transfer in)  

        (gta4."HistoryTypeDescription" = vTransferIn

          and gta4."PreviousDepartment" = vDepartment

          and gta4."Department" <> vDepartment)

        or

        -- remove records that are not for the department (transfer out)

        (gta4."HistoryTypeDescription" = vTransferOut

          and gta4."PreviousDepartment" <> vDepartment

          and gta4."Department" = vDepartment)

        or

        -- remove records that are not for the department

        (gta4."PreviousDepartment" <> vDepartment

          and gta4."Department" <> vDepartment)

        or

        -- remove allocate type duplicate records (i.e.: TxHistoryId <> History)

        (gta4."TxHistoryId" <> gta4."History"

          and gta4."HistoryType" = 3)

          -- remove records allocated after the reporting period end date

          or exists (select null

                    from allocath ah4

                    where 1=1

                    and ah4."ModifiedDate" > vToDate

                    and ah4."AllocatH" = gta4."AllocatH")

        ); 



    --

    -- update "PreviousHistory" column with actual previous History ID

    --

    vStep := 530;

    

    update global_temp_alloc4 gta4

    set gta4."PreviousHistory" = (select nvl(max(h."History"), 0)

                                  from history h

                                  where 1=1

                                  and h."History" < gta4."History"

                                  and h."OrigRecNo" = gta4."OrigRecNo")

    where 1=1;



    --

    -- return cursor values from the view GLOBAL_TEMP_ALLOC_V (records that are within the reporting period only)

    --

    vStep := 540;



    return query

      select

        max(gtav."AllocatH") "AllocatH",

        gtav."PayType",

        gtav."TrxType",

        gtav."TrxId",

        gtav."TrxTreatment",

        sum(gtav."Amount") "Amount",

        max(gtav."AllocateLink") "AllocateLink",

        gtav."TxHistoryId",

        gtav."PmtHistoryId",

        gtav."OrigRecNo",

        gtav."History",

        gtav."HistoryType",

        gtav."Patient",

        gtav."TxModifiedDate",

        gtav."Payed",

        gtav."InsPayed",

        gtav."PtAdj",

        gtav."InsAdj",

        gtav."InsTransfer",

        gtav."Discipline",

        gtav."Procedure",

        gtav."Practice",

        gtav."ClaimDoctor",

        gtav."Location",

        gtav."EntryUser",

        gtav."AppUser",

        gtav."Custom1",

        gtav."Custom2",

        gtav."Producer",

        gtav."TypeCode",

        gtav."PGroup",

        gtav."Year",

        gtav."CustomCode1",

        gtav."CustomCode2",

        gtav."CustomCode3",

        gtav."CustomCode4",

        gtav."CustomCode5",

        gtav."CustomCode6",

        gtav."CustomCode7",

        gtav."CustomCode8",

        gtav."CustomCode9",

        gtav."CustomCode10",

        gtav."Department",

        gtav."HistoryTypeDescription",

        gtav."GroupBy1",

        gtav."GroupBy2",

        gtav."PreviousHistory",

        gtav."PreviousDiscipline",

        gtav."PreviousProcedure",

        gtav."PreviousPractice",

        gtav."PreviousPracticeName",

        gtav."PreviousClaimDoctor",

        gtav."PreviousLocation",

        gtav."PreviousEntryUser",

        gtav."PreviousEntryUserLogon",

        gtav."PreviousEntryUserFirstName",

        gtav."PreviousEntryUserLastName",

        gtav."PreviousAppUser",

        gtav."PreviousAppUserLogon",

        gtav."PreviousAppUserFirstName",

        gtav."PreviousAppUserLastName",

        gtav."PreviousCustom1",

        gtav."PreviousCustom2",

        gtav."PreviousProducer",

        gtav."PreviousProducerFirstName",

        gtav."PreviousProducerMiddleName",

        gtav."PreviousProducerLastName",

        gtav."PreviousTypeCode",

        gtav."PreviousTypeCodeDescription",

        gtav."PreviousPGroup",

        gtav."PreviousYear",

        gtav."PreviousCustomCode1",

        gtav."PreviousCustomCode2",

        gtav."PreviousCustomCode3",

        gtav."PreviousCustomCode4",

        gtav."PreviousCustomCode5",

        gtav."PreviousCustomCode6",

        gtav."PreviousCustomCode7",

        gtav."PreviousCustomCode8",

        gtav."PreviousCustomCode9",

        gtav."PreviousCustomCode10",

        gtav."PreviousDepartment",

        gtav."PreviousPayed",

        gtav."PreviousInsPayed",

        gtav."PreviousPtAdj",

        gtav."PreviousInsAdj",

        gtav."GroupBy1Value",

        gtav."GroupBy2Value",

        gtav."PreviousGroupBy1Value",

        gtav."PreviousGroupBy2Value",

        gtav."TxPracticeName",

        gtav."TxTypeCodeDescription",

        gtav."TxPGroupDescription",

        gtav."TxProducerFirstName",

        gtav."TxProducerMiddleName",

        gtav."TxProducerLastName",

        gtav."TxEntryUserLogon",

        gtav."TxEntryUserFirstName",

        gtav."TxEntryUserLastName",

        gtav."TxAppUserLogon",

        gtav."TxAppUserFirstName",

        gtav."TxAppUserLastName",

        gtav."TxPatientChart",

        gtav."TxPatientFirstName",

        gtav."TxPatientMiddleName",

        gtav."TxPatientLastName",

        gtav."TxPatientPreferredName",

        gtav."TxDeptDescription",

        gtav."TxHistoryType",

        gtav."TxType",

        gtav."TxId",

        gtav."TxTreatment",

        gtav."TxOrigRecNo",

        gtav."TxFamily",

        gtav."TxStatus",

        gtav."TxDate",

        gtav."TxTreatmentDate",

        gtav."TxCode",

        gtav."TxCodeDescription",

        gtav."TxSite",

        gtav."TxSurface",

        gtav."TxTotal",

        gtav."TxInsTotal",

        gtav."TxCompany1",

        gtav."TxCompany1Name",

        gtav."TxPolicy1",

        gtav."TxAmount1",

        gtav."TxDescription",

        gtav."TxUser",

        gtav."TxAppDate",

        gtav."TxStationId",

        gtav."TxCustom3",

        gtav."TxCustom4",

        gtav."TxCustomaryTotal",

        gtav."PmtHistoryType",

        gtav."PmtType",

        gtav."PmtId",

        gtav."PmtTreatment",

        gtav."PmtOrigRecNo",

        gtav."PmtPatient",

        gtav."PmtFamily",

        gtav."PmtDate",

        gtav."PmtCode",

        gtav."PmtCodeDescription",

        gtav."PmtTotal",

        gtav."PmtInsTotal",

        gtav."PmtCompany1",

        gtav."PmtCompany1Name",

        gtav."PmtAmount1",

        gtav."PmtDescription",

        gtav."PmtBank",

        gtav."PmtPayed",

        gtav."PmtInsPayed",

        gtav."PmtPtAdj",

        gtav."PmtInsAdj",

        gtav."PmtModifiedDate",

        gtav."PmtPatientFirstName",

        gtav."PmtPatientMiddleName",

        gtav."PmtPatientLastName",

        gtav."PmtPatientPreferredName",

        vBatch "Batch"

      from (SELECT "AllocatH", -- replaced global_temp_alloc_v view with the actual query since pgtt is not currently working with views

    "PayType",

    "TrxType",

    "TrxId",

    "TrxTreatment",

    "Amount",

    "AllocateLink",

    "TxHistoryId",

    "PmtHistoryId",

    "OrigRecNo",

    "History",

    "HistoryType",

    "Patient",

    "TxModifiedDate",

    "Payed",

    "InsPayed",

    "PtAdj",

    "InsAdj",

    "InsTransfer",

    "Discipline",

    "Procedure",

    "Practice",

    "ClaimDoctor",

    "Location",

    "EntryUser",

    "AppUser",

    "Custom1",

    "Custom2",

    "Producer",

    "TypeCode",

    "PGroup",

    "Year",

    "CustomCode1",

    "CustomCode2",

    "CustomCode3",

    "CustomCode4",

    "CustomCode5",

    "CustomCode6",

    "CustomCode7",

    "CustomCode8",

    "CustomCode9",

    "CustomCode10",

    "Department",

    "HistoryTypeDescription",

    "GroupBy1",

    "GroupBy2",

    "PreviousHistory",

    "PreviousDiscipline",

    "PreviousProcedure",

    "PreviousPractice",

    "PreviousPracticeName",

    "PreviousClaimDoctor",

    "PreviousLocation",

    "PreviousEntryUser",

    "PreviousEntryUserLogon",

    "PreviousEntryUserFirstName",

    "PreviousEntryUserLastName",

    "PreviousAppUser",

    "PreviousAppUserLogon",

    "PreviousAppUserFirstName",

    "PreviousAppUserLastName",

    "PreviousCustom1",

    "PreviousCustom2",

    "PreviousProducer",

    "PreviousProducerFirstName",

    "PreviousProducerMiddleName",

    "PreviousProducerLastName",

    "PreviousTypeCode",

    "PreviousTypeCodeDescription",

    "PreviousPGroup",

    "PreviousYear",

    "PreviousCustomCode1",

    "PreviousCustomCode2",

    "PreviousCustomCode3",

    "PreviousCustomCode4",

    "PreviousCustomCode5",

    "PreviousCustomCode6",

    "PreviousCustomCode7",

    "PreviousCustomCode8",

    "PreviousCustomCode9",

    "PreviousCustomCode10",

    "PreviousDepartment",

    "PreviousPayed",

    "PreviousInsPayed",

    "PreviousPtAdj",

    "PreviousInsAdj",

    "GroupBy1Value",

    "GroupBy2Value",

    "PreviousGroupBy1Value",

    "PreviousGroupBy2Value",

    "TxPracticeName",

    "TxTypeCodeDescription",

    "TxPGroupDescription",

    "TxProducerFirstName",

    "TxProducerMiddleName",

    "TxProducerLastName",

    "TxEntryUserLogon",

    "TxEntryUserFirstName",

    "TxEntryUserLastName",

    "TxAppUserLogon",

    "TxAppUserFirstName",

    "TxAppUserLastName",

    "TxPatientChart",

    "TxPatientFirstName",

    "TxPatientMiddleName",

    "TxPatientLastName",

    "TxPatientPreferredName",

    "TxDeptDescription",

    "TxHistoryType",

    "TxType",

    "TxId",

    "TxTreatment",

    "TxOrigRecNo",

    "TxFamily",

    "TxStatus",

    "TxDate",

    "TxTreatmentDate",

    "TxCode",

    "TxCodeDescription",

    "TxSite",

    "TxSurface",

    "TxTotal",

    "TxInsTotal",

    "TxCompany1",

    "TxCompany1Name",

    "TxPolicy1",

    "TxAmount1",

    "TxDescription",

    "TxUser",

    "TxAppDate",

    "TxStationId",

    "TxCustom3",

    "TxCustom4",

    "TxCustomaryTotal",

    "PmtHistoryType",

    "PmtType",

    "PmtId",

    "PmtTreatment",

    "PmtOrigRecNo",

    "PmtPatient",

    "PmtFamily",

    "PmtDate",

    "PmtCode",

    "PmtCodeDescription",

    "PmtTotal",

    "PmtInsTotal",

    "PmtCompany1",

    "PmtCompany1Name",

    "PmtAmount1",

    "PmtDescription",

    "PmtBank",

    "PmtPayed",

    "PmtInsPayed",

    "PmtPtAdj",

    "PmtInsAdj",

    "PmtModifiedDate",

    "PmtPatientFirstName",

    "PmtPatientMiddleName",

    "PmtPatientLastName",

    "PmtPatientPreferredName"

   FROM ( WITH tmpgta4 AS (

                 SELECT DISTINCT gta4."AllocatH",

                    gta4."PayType",

                    gta4."TrxType",

                    gta4."TrxId",

                    gta4."TrxTreatment",

                    gta4."Amount",

                    gta4."AllocateLink",

                    gta4."TxHistoryId",

                    gta4."PmtHistoryId",

                    gta4."OrigRecNo",

                    gta4."History",

                    gta4."HistoryType",

                    gta4."Patient",

                    gta4."TxModifiedDate",

                    gta4."Payed",

                    gta4."InsPayed",

                    gta4."PtAdj",

                    gta4."InsAdj",

                    gta4."InsTransfer",

                    gta4."Discipline",

                    gta4."Procedure",

                    gta4."Practice",

                    gta4."ClaimDoctor",

                    gta4."Location",

                    gta4."EntryUser",

                    gta4."AppUser",

                    gta4."Custom1",

                    gta4."Custom2",

                    gta4."Producer",

                    gta4."TypeCode",

                    gta4."PGroup",

                    gta4."Year",

                    gta4."CustomCode1",

                    gta4."CustomCode2",

                    gta4."CustomCode3",

                    gta4."CustomCode4",

                    gta4."CustomCode5",

                    gta4."CustomCode6",

                    gta4."CustomCode7",

                    gta4."CustomCode8",

                    gta4."CustomCode9",

                    gta4."CustomCode10",

                    gta4."Department",

                    gta4."HistoryTypeDescription",

                    gta4."GroupBy1",

                    gta4."GroupBy2",

                    gta4."PreviousHistory",

                    gta4."PreviousDiscipline",

                    gta4."PreviousProcedure",

                    gta4."PreviousPractice",

                    gta4."PreviousClaimDoctor",

                    gta4."PreviousLocation",

                    gta4."PreviousEntryUser",

                    gta4."PreviousAppUser",

                    gta4."PreviousCustom1",

                    gta4."PreviousCustom2",

                    gta4."PreviousProducer",

                    gta4."PreviousTypeCode",

                    gta4."PreviousPGroup",

                    gta4."PreviousYear",

                    gta4."PreviousCustomCode1",

                    gta4."PreviousCustomCode2",

                    gta4."PreviousCustomCode3",

                    gta4."PreviousCustomCode4",

                    gta4."PreviousCustomCode5",

                    gta4."PreviousCustomCode6",

                    gta4."PreviousCustomCode7",

                    gta4."PreviousCustomCode8",

                    gta4."PreviousCustomCode9",

                    gta4."PreviousCustomCode10",

                    gta4."PreviousDepartment",

                    gta4."GroupBy1Value",

                    gta4."GroupBy2Value",

                    gta4."PreviousGroupBy1Value",

                    gta4."PreviousGroupBy2Value"

                   FROM global_temp_alloc4 gta4

                  WHERE (1 = 1)

                ), tmppmthistory AS (

                 SELECT hpmt."History",

                    hpmt."HistoryType" AS "PmtHistoryType",

                    hpmt."Type" AS "PmtType",

                    hpmt."Id" AS "PmtId",

                    hpmt."Treatment" AS "PmtTreatment",

                    hpmt."OrigRecNo" AS "PmtOrigRecNo",

                    hpmt."Patient" AS "PmtPatient",

                    hpmt."Family" AS "PmtFamily",

                    hpmt."Date" AS "PmtDate",

                    hpmt."Code" AS "PmtCode",

                    nvl(

                        DECODE(  hpmt."Type"

                            , (2)::numeric

                            , (ocpmt."Description")::character varying

                            , (3)::numeric

                            , (pmtpmt."Description")::character varying

                            , (4)::numeric

                            , (pmtpmt."Description")::character varying

                            , (73)::numeric

                            , (pmtpmt."Description")::character varying

                            , (74)::numeric

                            , (pmtpmt."Description")::character varying

                            , (6)::numeric

                            , (adjpmt."Description")::character varying

                            , (7)::numeric

                            , (adjpmt."Description")::character varying

                            , (' '::text)::character varying

                        ), ' ') AS "PmtCodeDescription",

                    hpmt."Total" AS "PmtTotal",

                    hpmt."InsTotal" AS "PmtInsTotal",

                    hpmt."Company1" AS "PmtCompany1",

                    nvl(ipmt."Name", ' ') AS "PmtCompany1Name",

                    hpmt."Amount1" AS "PmtAmount1",

                    hpmt."Description" AS "PmtDescription",

                    hpmt."Bank" AS "PmtBank",

                    hpmt."Payed" AS "PmtPayed",

                    hpmt."InsPayed" AS "PmtInsPayed",

                    hpmt."PtAdj" AS "PmtPtAdj",

                    hpmt."InsAdj" AS "PmtInsAdj",

                    hpmt."ModifiedDate" AS "PmtModifiedDate",

                    nvl(ppmt."First", ' ') AS "PmtPatientFirstName",

                    nvl(ppmt."Middle", ' ') AS "PmtPatientMiddleName",

                    nvl(ppmt."Last", ' ') AS "PmtPatientLastName",

                    nvl(ppmt."Prefered", ' ') AS "PmtPatientPreferredName"

                   FROM (((((history hpmt

                     LEFT JOIN patient ppmt ON ((hpmt."Patient" = ppmt."Patient")))

                     LEFT JOIN adjust adjpmt ON ((hpmt."Code" = adjpmt."Adjust")))

                     LEFT JOIN payment pmtpmt ON ((hpmt."Code" = pmtpmt."Payment")))

                     LEFT JOIN ofcharge ocpmt ON ((hpmt."Code" = ocpmt."OfficeCharge")))

                     LEFT JOIN insuranc ipmt ON ((hpmt."Company1" = ipmt."Company")))

                  WHERE (1 = 1)

                ), tmpprevioushistory AS (

                 SELECT hprev."History",

                    hprev."Payed" AS "PreviousPayed",

                    hprev."InsPayed" AS "PreviousInsPayed",

                    hprev."PtAdj" AS "PreviousPtAdj",

                    hprev."InsAdj" AS "PreviousInsAdj"

                   FROM history hprev

                  WHERE (1 = 1)

                )

         SELECT tgta4a."AllocatH",

            tgta4a."PayType",

            tgta4a."TrxType",

            tgta4a."TrxId",

            tgta4a."TrxTreatment",

            tgta4a."Amount",

            tgta4a."AllocateLink",

            tgta4a."TxHistoryId",

            tgta4a."PmtHistoryId",

            tgta4a."OrigRecNo",

            tgta4a."History",

            tgta4a."HistoryType",

            tgta4a."Patient",

            tgta4a."TxModifiedDate",

            tgta4a."Payed",

            tgta4a."InsPayed",

            tgta4a."PtAdj",

            tgta4a."InsAdj",

            tgta4a."InsTransfer",

            tgta4a."Discipline",

            tgta4a."Procedure",

            tgta4a."Practice",

            tgta4a."ClaimDoctor",

            tgta4a."Location",

            tgta4a."EntryUser",

            tgta4a."AppUser",

            tgta4a."Custom1",

            tgta4a."Custom2",

            tgta4a."Producer",

            tgta4a."TypeCode",

            tgta4a."PGroup",

            tgta4a."Year",

            tgta4a."CustomCode1",

            tgta4a."CustomCode2",

            tgta4a."CustomCode3",

            tgta4a."CustomCode4",

            tgta4a."CustomCode5",

            tgta4a."CustomCode6",

            tgta4a."CustomCode7",

            tgta4a."CustomCode8",

            tgta4a."CustomCode9",

            tgta4a."CustomCode10",

            tgta4a."Department",

            tgta4a."HistoryTypeDescription",

            tgta4a."GroupBy1",

            tgta4a."GroupBy2",

            tgta4a."PreviousHistory",

            tgta4a."PreviousDiscipline",

            tgta4a."PreviousProcedure",

            tgta4a."PreviousPractice",

            nvl(prprev."Name", ' ') AS "PreviousPracticeName",

            tgta4a."PreviousClaimDoctor",

            tgta4a."PreviousLocation",

            tgta4a."PreviousEntryUser",

            nvl(euprev."Logon", ' ') AS "PreviousEntryUserLogon",

            nvl(euprev."First", ' ') AS "PreviousEntryUserFirstName",

            nvl(euprev."Name", ' ') AS "PreviousEntryUserLastName",

            tgta4a."PreviousAppUser",

            nvl(auprev."Logon", ' ') AS "PreviousAppUserLogon",

            nvl(auprev."First", ' ') AS "PreviousAppUserFirstName",

            nvl(auprev."Name", ' ') AS "PreviousAppUserLastName",

            tgta4a."PreviousCustom1",

            tgta4a."PreviousCustom2",

            tgta4a."PreviousProducer",

            nvl(prodprev."FirstName", ' ') AS "PreviousProducerFirstName",

            nvl(prodprev."MiddleName", ' ') AS "PreviousProducerMiddleName",

            nvl(prodprev."LastName", ' ') AS "PreviousProducerLastName",

            tgta4a."PreviousTypeCode",

            nvl(ptprev."Description", ' ') AS "PreviousTypeCodeDescription",

            tgta4a."PreviousPGroup",

            tgta4a."PreviousYear",

            tgta4a."PreviousCustomCode1",

            tgta4a."PreviousCustomCode2",

            tgta4a."PreviousCustomCode3",

            tgta4a."PreviousCustomCode4",

            tgta4a."PreviousCustomCode5",

            tgta4a."PreviousCustomCode6",

            tgta4a."PreviousCustomCode7",

            tgta4a."PreviousCustomCode8",

            tgta4a."PreviousCustomCode9",

            tgta4a."PreviousCustomCode10",

            tgta4a."PreviousDepartment",

            nvl(thprev."PreviousPayed", 0) AS "PreviousPayed",

            nvl(thprev."PreviousInsPayed", 0) AS "PreviousInsPayed",

            nvl(thprev."PreviousPtAdj", 0) AS "PreviousPtAdj",

            nvl(thprev."PreviousInsAdj", 0) AS "PreviousInsAdj",

            tgta4a."GroupBy1Value",

            tgta4a."GroupBy2Value",

            tgta4a."PreviousGroupBy1Value",

            tgta4a."PreviousGroupBy2Value",

            nvl(prtx."Name", ' ') AS "TxPracticeName",

            nvl(pttx."Description", ' ') AS "TxTypeCodeDescription",

            nvl(pgtx."Description", ' ') AS "TxPGroupDescription",

            nvl(prodtx."FirstName", ' ') AS "TxProducerFirstName",

            nvl(prodtx."MiddleName", ' ') AS "TxProducerMiddleName",

            nvl(prodtx."LastName", ' ') AS "TxProducerLastName",

            nvl(eutx."Logon", ' ') AS "TxEntryUserLogon",

            nvl(eutx."First", ' ') AS "TxEntryUserFirstName",

            nvl(eutx."Name", ' ') AS "TxEntryUserLastName",

            nvl(autx."Logon", ' ') AS "TxAppUserLogon",

            nvl(autx."First", ' ') AS "TxAppUserFirstName",

            nvl(autx."Name", ' ') AS "TxAppUserLastName",

            nvl(ptx."Chart", ' ') AS "TxPatientChart",

            nvl(ptx."First", ' ') AS "TxPatientFirstName",

            nvl(ptx."Middle", ' ') AS "TxPatientMiddleName",

            nvl(ptx."Last", ' ') AS "TxPatientLastName",

            nvl(ptx."Prefered", ' ') AS "TxPatientPreferredName",

            nvl(dtx."Description", ' ') AS "TxDeptDescription",

            htx."HistoryType" AS "TxHistoryType",

            htx."Type" AS "TxType",

            htx."Id" AS "TxId",

            htx."Treatment" AS "TxTreatment",

            htx."OrigRecNo" AS "TxOrigRecNo",

            htx."Family" AS "TxFamily",

            htx."Status" AS "TxStatus",

            htx."Date" AS "TxDate",

            htx."TreatmentDate" AS "TxTreatmentDate",

            htx."Code" AS "TxCode",

            nvl(

                DECODE(  htx."Type"

                    , (2)::numeric

                    , (octx."Description")::character varying

                    , (3)::numeric

                    , (pmttx."Description")::character varying

                    , (4)::numeric

                    , (pmttx."Description")::character varying

                    , (73)::numeric

                    , (pmttx."Description")::character varying

                    , (74)::numeric

                    , (pmttx."Description")::character varying

                    , (6)::numeric

                    , (adjtx."Description")::character varying

                    , (7)::numeric

                    , (adjtx."Description")::character varying

                    , (' '::text)::character varying

                ), ' ') AS "TxCodeDescription",

            htx."Site" AS "TxSite",

            htx."Surface" AS "TxSurface",

            htx."Total" AS "TxTotal",

            htx."InsTotal" AS "TxInsTotal",

            htx."Company1" AS "TxCompany1",

            nvl(itx."Name", ' ') AS "TxCompany1Name",

            htx."Policy1" AS "TxPolicy1",

            htx."Amount1" AS "TxAmount1",

            htx."Description" AS "TxDescription",

            htx."User" AS "TxUser",

            htx."AppDate" AS "TxAppDate",

            htx."StationId" AS "TxStationId",

            htx."Custom3" AS "TxCustom3",

            htx."Custom4" AS "TxCustom4",

            htx."CustomaryTotal" AS "TxCustomaryTotal",

            thpmt."PmtHistoryType",

            thpmt."PmtType",

            thpmt."PmtId",

            thpmt."PmtTreatment",

            thpmt."PmtOrigRecNo",

            thpmt."PmtPatient",

            thpmt."PmtFamily",

            thpmt."PmtDate",

            thpmt."PmtCode",

            thpmt."PmtCodeDescription",

            thpmt."PmtTotal",

            thpmt."PmtInsTotal",

            thpmt."PmtCompany1",

            thpmt."PmtCompany1Name",

            thpmt."PmtAmount1",

            thpmt."PmtDescription",

            thpmt."PmtBank",

            thpmt."PmtPayed",

            thpmt."PmtInsPayed",

            thpmt."PmtPtAdj",

            thpmt."PmtInsAdj",

            thpmt."PmtModifiedDate",

            thpmt."PmtPatientFirstName",

            thpmt."PmtPatientMiddleName",

            thpmt."PmtPatientLastName",

            thpmt."PmtPatientPreferredName"

           FROM ((((((((((((((((((((tmpgta4 tgta4a

             CROSS JOIN history htx)

             LEFT JOIN tmppmthistory thpmt ON ((tgta4a."PmtHistoryId" = thpmt."History")))

             LEFT JOIN tmpprevioushistory thprev ON ((tgta4a."PreviousHistory" = thprev."History")))

             LEFT JOIN practice prtx ON ((tgta4a."Practice" = prtx."Id")))

             LEFT JOIN prodtype pttx ON ((tgta4a."TypeCode" = pttx."Code")))

             LEFT JOIN pgroup pgtx ON ((tgta4a."PGroup" = pgtx."PGroup")))

             LEFT JOIN producer prodtx ON ((tgta4a."Producer" = prodtx."Producer")))

             LEFT JOIN users eutx ON ((tgta4a."EntryUser" = eutx."User")))

             LEFT JOIN users autx ON ((tgta4a."AppUser" = autx."User")))

             LEFT JOIN patient ptx ON ((tgta4a."Patient" = ptx."Patient")))

             LEFT JOIN dept dtx ON ((tgta4a."Department" = dtx."Department")))

             LEFT JOIN adjust adjtx ON ((htx."Code" = adjtx."Adjust")))

             LEFT JOIN payment pmttx ON ((htx."Code" = pmttx."Payment")))

             LEFT JOIN ofcharge octx ON ((htx."Code" = octx."OfficeCharge")))

             LEFT JOIN insuranc itx ON ((htx."Company1" = itx."Company")))

             LEFT JOIN practice prprev ON ((tgta4a."PreviousPractice" = prprev."Id")))

             LEFT JOIN users euprev ON ((tgta4a."PreviousEntryUser" = euprev."User")))

             LEFT JOIN users auprev ON ((tgta4a."PreviousAppUser" = auprev."User")))

             LEFT JOIN producer prodprev ON ((tgta4a."PreviousProducer" = prodprev."Producer")))

             LEFT JOIN prodtype ptprev ON ((tgta4a."PreviousTypeCode" = ptprev."Code")))

          WHERE ((1 = 1) AND (tgta4a."History" = htx."History"))) gtav

  WHERE (1 = 1)) as gtav

      where 1=1

      and gtav."TxModifiedDate" >= vFromDate

      and gtav."TxModifiedDate" <= vToDate

      group by

        gtav."PayType",

        gtav."TrxType",

        gtav."TrxId",

        gtav."TrxTreatment",

        gtav."TxHistoryId",

        gtav."PmtHistoryId",

        gtav."OrigRecNo",

        gtav."History",

        gtav."HistoryType",

        gtav."Patient",

        gtav."TxModifiedDate",

        gtav."Payed",

        gtav."InsPayed",

        gtav."PtAdj",

        gtav."InsAdj",

        gtav."InsTransfer",

        gtav."Discipline",

        gtav."Procedure",

        gtav."Practice",

        gtav."ClaimDoctor",

        gtav."Location",

        gtav."EntryUser",

        gtav."AppUser",

        gtav."Custom1",

        gtav."Custom2",

        gtav."Producer",

        gtav."TypeCode",

        gtav."PGroup",

        gtav."Year",

        gtav."CustomCode1",

        gtav."CustomCode2",

        gtav."CustomCode3",

        gtav."CustomCode4",

        gtav."CustomCode5",

        gtav."CustomCode6",

        gtav."CustomCode7",

        gtav."CustomCode8",

        gtav."CustomCode9",

        gtav."CustomCode10",

        gtav."Department",

        gtav."HistoryTypeDescription",

        gtav."GroupBy1",

        gtav."GroupBy2",

        gtav."PreviousHistory",

        gtav."PreviousDiscipline",

        gtav."PreviousProcedure",

        gtav."PreviousPractice",

        gtav."PreviousPracticeName",

        gtav."PreviousClaimDoctor",

        gtav."PreviousLocation",

        gtav."PreviousEntryUser",

        gtav."PreviousEntryUserLogon",

        gtav."PreviousEntryUserFirstName",

        gtav."PreviousEntryUserLastName",

        gtav."PreviousAppUser",

        gtav."PreviousAppUserLogon",

        gtav."PreviousAppUserFirstName",

        gtav."PreviousAppUserLastName",

        gtav."PreviousCustom1",

        gtav."PreviousCustom2",

        gtav."PreviousProducer",

        gtav."PreviousProducerFirstName",

        gtav."PreviousProducerMiddleName",

        gtav."PreviousProducerLastName",

        gtav."PreviousTypeCode",

        gtav."PreviousTypeCodeDescription",

        gtav."PreviousPGroup",

        gtav."PreviousYear",

        gtav."PreviousCustomCode1",

        gtav."PreviousCustomCode2",

        gtav."PreviousCustomCode3",

        gtav."PreviousCustomCode4",

        gtav."PreviousCustomCode5",

        gtav."PreviousCustomCode6",

        gtav."PreviousCustomCode7",

        gtav."PreviousCustomCode8",

        gtav."PreviousCustomCode9",

        gtav."PreviousCustomCode10",

        gtav."PreviousDepartment",

        gtav."PreviousPayed",

        gtav."PreviousInsPayed",

        gtav."PreviousPtAdj",

        gtav."PreviousInsAdj",

        gtav."GroupBy1Value",

        gtav."GroupBy2Value",

        gtav."PreviousGroupBy1Value",

        gtav."PreviousGroupBy2Value",

        gtav."TxPracticeName",

        gtav."TxTypeCodeDescription",

        gtav."TxPGroupDescription",

        gtav."TxProducerFirstName",

        gtav."TxProducerMiddleName",

        gtav."TxProducerLastName",

        gtav."TxEntryUserLogon",

        gtav."TxEntryUserFirstName",

        gtav."TxEntryUserLastName",

        gtav."TxAppUserLogon",

        gtav."TxAppUserFirstName",

        gtav."TxAppUserLastName",

        gtav."TxPatientChart",

        gtav."TxPatientFirstName",

        gtav."TxPatientMiddleName",

        gtav."TxPatientLastName",

        gtav."TxPatientPreferredName",

        gtav."TxDeptDescription",

        gtav."TxHistoryType",

        gtav."TxType",

        gtav."TxId",

        gtav."TxTreatment",

        gtav."TxOrigRecNo",

        gtav."TxFamily",

        gtav."TxStatus",

        gtav."TxDate",

        gtav."TxTreatmentDate",

        gtav."TxCode",

        gtav."TxCodeDescription",

        gtav."TxSite",

        gtav."TxSurface",

        gtav."TxTotal",

        gtav."TxInsTotal",

        gtav."TxCompany1",

        gtav."TxCompany1Name",

        gtav."TxPolicy1",

        gtav."TxAmount1",

        gtav."TxDescription",

        gtav."TxUser",

        gtav."TxAppDate",

        gtav."TxStationId",

        gtav."TxCustom3",

        gtav."TxCustom4",

        gtav."TxCustomaryTotal",

        gtav."PmtHistoryType",

        gtav."PmtType",

        gtav."PmtId",

        gtav."PmtTreatment",

        gtav."PmtOrigRecNo",

        gtav."PmtPatient",

        gtav."PmtFamily",

        gtav."PmtDate",

        gtav."PmtCode",

        gtav."PmtCodeDescription",

        gtav."PmtTotal",

        gtav."PmtInsTotal",

        gtav."PmtCompany1",

        gtav."PmtCompany1Name",

        gtav."PmtAmount1",

        gtav."PmtDescription",

        gtav."PmtBank",

        gtav."PmtPayed",

        gtav."PmtInsPayed",

        gtav."PmtPtAdj",

        gtav."PmtInsAdj",

        gtav."PmtModifiedDate",

        gtav."PmtPatientFirstName",

        gtav."PmtPatientMiddleName",

        gtav."PmtPatientLastName",

        gtav."PmtPatientPreferredName",

        vBatch;



    --

    -- update processing end date/time (will be performed again inside the Crystal report)

    --

    vStep := 550;

    

    update ar_recon_saved_data_hdr

    set "EndDateTime" = sysdate

    where 1=1

    and "Batch" = vBatch;



    --

    -- create a new savepoint

    --

    vStep := 560;

    begin

      --

      -- clear temporary tables 1, 2 and 3

      --



      vStep := 570;



      execute immediate 'truncate table global_temp_alloc1';

      execute immediate 'truncate table global_temp_alloc2';

      execute immediate 'truncate table global_temp_alloc3';

    exception

    when others then

    --

    -- rollback to last savepoint then log error

    --

    vStep := 570;

    ax_pkg.LogEvent_P((trim('ALLOC_PKG') || '.CreateAllocTxs_P'), (trim(sqlerrm) || ' (Error at step ' || vStep || ')')); -- AX-39259

  end;

exception

when others then

  --

  -- log error then rollback to starting savepoint

  --

  

  ax_pkg.LogEvent_P((trim('ALLOC_PKG') || '.CreateAllocTxs_P'), (trim(sqlerrm) || ' (Error at step ' || vStep || ')')); -- AX-39259

      

end;

$function$
;
CREATE OR REPLACE FUNCTION currentmedsboth(lpatient numeric)
 RETURNS character varying
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
szCurrentMeds 	 VARCHAR2(9000 );
szMedications    VARCHAR2(4000 );
szForms          VARCHAR2(4000 );
BEGIN
  szCurrentMeds := '';
  szMedications := CURRENTMEDSNEW(lPatient);
  szForms := CURRENTMEDS(lPatient);

  if (LENGTH(szMedications) > 0) THEN
    szCurrentMeds := '***Medications***' || CHR(10) || CHR(13) || szMedications;
  end if;

  if (LENGTH(szCurrentMeds) > 0 AND LENGTH(szForms) > 0) THEN
    szCurrentMeds := szCurrentMeds || ',' || CHR(10) || CHR(13) || ' ' || CHR(10) || CHR(13)  || '***Forms***' || CHR(10) || CHR(13) || szForms;
  elsif (LENGTH(szForms) > 0) THEN
    szCurrentMeds := '***Forms***' || CHR(10) || CHR(13)  || szForms;
  end if;

     	
   	/*trim it if too long */
   	if LENGTH(szCurrentMeds) > 4000
   	THEN
			szCurrentMeds := SUBSTR(szCurrentMeds, 1, 3996);
			szCurrentMeds := szCurrentMeds || CHR(13) || '...';
	END IF;

  RETURN szCurrentMeds;
END$function$
;
CREATE OR REPLACE FUNCTION currentmedsnew(lpatient numeric)
 RETURNS character varying
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$

	szCurrentMeds 	 VARCHAR2(9000 ); -- B87008
	szCurrentLoc	 VARCHAR2(256 );
  szDateFormat  VARCHAR2(32 );   -- B119350
  DateType      NUMBER(5);      -- B119350
	lastParent		 NUMBER(10);
	v_nCount		NUMBER := 0;								-- AX-26071
	
		-- B118707, E123395.7, B124378 removed unreferenced drug table
   	CURSOR 		PItemCur (lPat NUMBER)
   	IS
      	SELECT P.* FROM Prescrip P WHERE
          P."Patient" = lPat AND
          P."Deleted" = 0 AND (P."StartDate" IS NULL OR P."StartDate" <= TRUNC(Sysdate)) AND
          (P."EndDate" IS NULL OR P."EndDate" >= TRUNC(Sysdate)) AND
          P."PrescripType" = 0 AND
          P."ApprovalUser" <> 0
      		ORDER BY P."EndDate", P."Date", P."Prescription";
	
	
BEGIN
	szCurrentMeds := '';
	szCurrentLoc := '';
	lastParent := 0;
  szDateFormat := 'DD/MM/YYYY'; -- B119350

	/* no patient specified, nothing to return */
	if lPatient = 0 then
		return szCurrentMeds;
	end if;

	-- AX-26071 added to check if custom version exists
   SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_TYPE = 'FUNCTION' and OBJECT_NAME = 'CUSTOM_CURRENTMEDSNEW';
   IF v_nCount > 0 THEN
     -- custom function exists to get new current meds
     EXECUTE IMMEDIATE 'SELECT CUSTOM_CURRENTMEDSNEW('||lPatient||') FROM DUAL' INTO szCurrentMeds;
     RETURN szCurrentMeds;
   END IF;


-- B119350
  BEGIN
	SELECT MIN("DateType")
	INTO DateType
	FROM PRACTICE;
	EXCEPTION WHEN NO_DATA_FOUND THEN
	DateType := 0;
  END;

  -- B119350
  if DateType = 0 then
    szDateFormat := 'DD/MM/YYYY';
  else
    szDateFormat := 'MM/DD/YYYY';
  end if;


	/* loop thru and concatenate the answer string */
   	FOR PItemRec IN PItemCur (lPatient)
	LOOP

		/*date answer type, append Q and A */
		IF LENGTH(szCurrentMeds) > 0
		THEN
				szCurrentMeds := szCurrentMeds || CHR(13);	
		END IF;
		szCurrentMeds := szCurrentMeds || PItemRec."DrugDescription";

		IF LENGTH (trim(PItemRec."Dose")) > 0
		THEN
		  szCurrentMeds := szCurrentMeds ||', Dose: '|| trim(PItemRec."Dose");
		END IF;

		IF LENGTH (trim(PItemRec."DrugFrqDesc")) > 0
		THEN
		  szCurrentMeds := szCurrentMeds ||', Freq: '|| trim(PItemRec."DrugFrqDesc");
		END IF;

		IF LENGTH( trim(PItemRec."Total") ) > 0
		THEN
		  szCurrentMeds := szCurrentMeds || ', Total: '||trim(PItemRec."Total");
		END IF;

		IF LENGTH (trim(PItemRec."Note")) > 0
		THEN
		  szCurrentMeds := szCurrentMeds || ', Note: '||trim(PItemRec."Note");
		END IF;

		szCurrentMeds := szCurrentMeds || ', ' ||
			TO_CHAR(PItemRec."Date", szDateFormat);


			/* AX-915.3293  -  stop when hit the limit*/
			IF LENGTH(szCurrentMeds) > 4000
			THEN
				EXIT;
			END IF;

	END LOOP;
		
	
   	
   	/*trim it if too long */
   	if LENGTH(szCurrentMeds) > 4000
   	THEN
		szCurrentMeds := SUBSTR(szCurrentMeds, 1, 3996);
		szCurrentMeds := szCurrentMeds || CHR(13) || '...';
	END IF;
	
	--E133016.6
   	if szCurrentMeds IS NULL OR szCurrentMeds = '' OR LENGTH(szCurrentMeds) = 0
   	THEN
   		if HASNOMEDSREVIEW(lPatient) > 0
   		THEN
			szCurrentMeds := 'No current medications';
		END IF;
	END IF;
	
	
  	RETURN szCurrentMeds;
END$function$
;
CREATE OR REPLACE FUNCTION currentmedsnew_pa(lpatient numeric)
 RETURNS character varying
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$

	szCurrentMeds 	 VARCHAR2(9000 );
	szCurrentLoc	 VARCHAR2(256 );
	szDateFormat  	 VARCHAR2(32 );
	DateType      	 NUMBER(5);
	lastParent	 NUMBER(10);

	
	CURSOR PItemCur (lPat NUMBER) IS
		SELECT P.*
		FROM DRUG D, Prescrip P
		WHERE 1=1
			AND P."Patient" = lPat
			AND P."Drug" = D."Drug"
			AND P."Deleted" = 0
			AND (P."StartDate" IS NULL OR P."StartDate" <= TRUNC(Sysdate))
			AND (P."EndDate" IS NULL OR P."EndDate" >= TRUNC(Sysdate))
			AND P."ApprovalUser" <> 0
		ORDER BY P."EndDate", P."Date";


BEGIN
	szCurrentMeds := '';
	szCurrentLoc := '';
	lastParent := 0;
	szDateFormat := 'DD/MM/YYYY';

	

	if lPatient = 0 then
		return szCurrentMeds;
	end if;

	
	BEGIN
		SELECT MIN("DateType")
		INTO DateType
		FROM PRACTICE;

	EXCEPTION WHEN NO_DATA_FOUND THEN
		DateType := 0;
	END;

	
	if DateType = 0 then
		szDateFormat := 'DD/MM/YYYY';
	else
		szDateFormat := 'MM/DD/YYYY';
	end if;


	

	FOR PItemRec IN PItemCur (lPatient) LOOP

		

		IF LENGTH(szCurrentMeds) > 0 THEN
			szCurrentMeds := szCurrentMeds || CHR(13);	
		END IF;

		
		szCurrentMeds := szCurrentMeds
			|| '<b>' || PItemRec."DrugDescription" || '</b>'
			||', <i>Dose:</i> '|| NVL(trim(PItemRec."Dose"),'N/A')
			||', <i>Freq: </i>'||  NVL(trim(PItemRec."DrugFrqDesc"),'N/A')
			|| ', <i>Total:</i>'||  NVL(trim(PItemRec."Total"),'N/A')
			|| ', <i>Note: </i>'||  NVL(trim(PItemRec."Note"),'N/A');

	END LOOP;

	

	if LENGTH(szCurrentMeds) > 4000 THEN
		szCurrentMeds := SUBSTR(szCurrentMeds, 1, 3996);
		szCurrentMeds := szCurrentMeds || CHR(13) || '...';
	END IF;

	RETURN szCurrentMeds;
END$function$
;
CREATE OR REPLACE FUNCTION defaultnomedsstring(lpatient numeric)
 RETURNS character varying
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
	szCurrentMeds 	 VARCHAR2(4000 );
BEGIN
  szCurrentMeds := 'No current medications';	-- if having custom text, place it here!!!!!
						-- example: *** No Medications! ***

  RETURN szCurrentMeds;
END$function$
;
CREATE OR REPLACE FUNCTION dept_ar(department character, openasatdate timestamp without time zone, endasatdate timestamp without time zone)
 RETURNS TABLE(":B1" numeric, ":B2" numeric)
 LANGUAGE edbspl
AS $function$

  OPENAR NUMBER := 0.0;

  ENDAR NUMBER := 0.0;

BEGIN

  OPENAR := DEPT_PKG.ARAsAt_DEPT(OpenAsAtDate, Department);

  ENDAR := DEPT_PKG.ARAsAt_DEPT(EndAsAtDate, Department);

  

  RETURN QUERY

    select OPENAR ":B1", ENDAR ":B2" from dual;

END

$function$
;
CREATE OR REPLACE FUNCTION examdate(patientid numeric)
 RETURNS timestamp without time zone
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
	Result DATE;

BEGIN
  Result := NULL;

  BEGIN
	SELECT PT."DueDate"-P."WithinDays" INTO Result FROM PTPREV PT, PREVCARE P WHERE
	PT. "Patient" = PatientId AND PT."PrevCare" = P."PrevCare" AND
	PT. "Completed" = 0 AND
	P. "Type" = 1 AND
	PT. "Deleted" = 0 AND ROWNUM = 1;
	EXCEPTION WHEN NO_DATA_FOUND THEN
		Result := NULL;
  END;
	
	
  Return Result;
END$function$
;
CREATE OR REPLACE FUNCTION examrequired(patientid numeric, apptdate timestamp without time zone)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
  Result NUMBER;

BEGIN
  Result := 0;

  BEGIN
	SELECT COUNT(1) INTO Result FROM PTPREV PT, PREVCARE P WHERE
	PT. "Patient" = PatientId AND
	PT. "Completed" = 0 AND
	PT. "Deleted" = 0 AND
	PT."PrevCare" = P. "PrevCare" AND
	P. "Type" = 1 AND
	(PT."DueDate" <= ApptDate + P. "WithinDays");
	EXCEPTION WHEN NO_DATA_FOUND THEN
		Result := 0;
  END;

  IF Result = 0 THEN
  	RETURN 0;
  ELSE
  	RETURN 1;
  END IF;
END$function$
;
CREATE OR REPLACE FUNCTION furcationcount(patientval numeric)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$

  CountVal    NUMBER;

  PtPerioVal  NUMBER;

BEGIN

  PtPerioVal := LastPtPerCo(PatientVal, 'FURC');				-- E33252

  CountVal := GetCountPerioDValNE(PtPerioVal, 'FURC', 0.0);

  RETURN (CountVal);

END$function$
;
CREATE OR REPLACE FUNCTION getcontactnotes(patientid numeric)
 RETURNS TABLE("Type" integer, contact numeric, patient numeric, contactdate timestamp without time zone, contacttime numeric, stationid numeric, notetext character varying, "User" numeric, "Name" character, "First" character, middle character, deleted numeric)
 LANGUAGE edbspl
AS $function$

   sqlstmt   VARCHAR2 (4000 );

BEGIN

   sqlstmt :=

   	'SELECT 0 "Type", P."Contact",P."Patient",P."ContactDate",P."ContactTime",P."StationId",

   	P."Note" NOTETEXT, U."User", U."Name", U."First", U."Middle", P."Deleted"

   	FROM PTCONT P, USERS U

   	WHERE P."Patient" = $1 AND U."User"(+)=P."ContactUser" AND P."Deleted" = 0

   	UNION

   	SELECT 1 "Type", c."Id" "Contact", r."Patient", c."Date" "ContactDate", c."Time" "ContactTime",

   	a."StationId", c."Comment" notetext, u."User",  u."Name", u."First",	u."Middle", c."Deleted"

   	FROM ONLINE_COMMENT c, ONLINE_REQUEST r, audithis a, users u

   	WHERE c."RequestId" = r."Id"

   	and r."Patient" = $2  and c."Audit" = a."Audit" and c."EntryUser" = u."User"(+)

   	and c."IsContactNote" = 1  AND c."Deleted" = 0

   	ORDER BY "ContactDate", "ContactTime" ';                                -- AX-29370



   	RETURN QUERY EXECUTE

    sqlstmt USING patientid, patientid;

END

$function$
;
CREATE OR REPLACE FUNCTION getcontactphonenumber(m_contactat numeric, m_homearea character varying, m_workarea character varying, m_otherarea character varying, m_mobilearea character varying, m_homephone character varying, m_workphone character varying, m_otherphone character varying, m_mobilephone character varying, m_workext character varying, m_otherext character varying)
 RETURNS character varying
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
	contactAt		CHAR(3 );
	tmpAreaCode		VARCHAR2(32 );
	tmpPhone			VARCHAR2(32 );
	tmpExt			VARCHAR2(32 );
	resultPhone		VARCHAR2(32 );
BEGIN
	BEGIN
		SELECT DECODE(m_ContactAt, 1, 'H: ', 2, 'W: ', 3, 'O: ', 4, 'M: '),
				 DECODE(m_ContactAt, 1, m_HomeArea, 2, m_WorkArea, 3, m_OtherArea, 4, m_MobileArea),
				 DECODE(m_ContactAt, 1, m_HomePhone, 2, m_WorkPhone, 3, m_OtherPhone, 4, m_MobilePhone),
				 DECODE(m_ContactAt, 2, m_WorkExt, 3, m_OtherExt) INTO contactAt, tmpAreaCode, tmpPhone, tmpExt FROM DUAL;
	END;
		
	IF Length(TRIM(tmpAreaCode)) > 0 THEN
		resultPhone := contactAt || '(' || TRIM(tmpAreaCode) || ') ' || TRIM(tmpPhone);
	ELSE
		IF Length(TRIM(tmpPhone)) > 0 THEN
			resultPhone := contactAt || TRIM(tmpPhone);
		END IF;
	END IF;
	
	IF (Length(TRIM(tmpAreaCode)) <= 0 AND Length(TRIM(tmpPhone)) <= 0) THEN
		return ' ';
	END IF;
		
	IF Length(TRIM(tmpExt)) > 0 THEN
		resultPhone := resultPhone || ' x' || TRIM(tmpExt);	-- Ext.
	END IF;
	
	return resultPhone;
END$function$
;
CREATE OR REPLACE FUNCTION getcountperiodvalge(ptperio numeric, percond character, dvalue numeric)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$

  DValSum   NUMBER;



  CURSOR C1 IS

    SELECT * FROM PTPERIT WHERE "PtPerio" = PtPerio AND "PerCond" = PerCond;

BEGIN

  DValSum := 0;



  FOR rec IN C1 LOOP

    IF rec."DValue1" >= DValue THEN

      DValSum := DValSum + 1;

    END IF;

    IF rec."DValue2" >= DValue THEN

      DValSum := DValSum + 1;

    END IF;

    IF rec."DValue3" >= DValue THEN

      DValSum := DValSum + 1;

    END IF;

  END LOOP;



  RETURN (DValSum);

END$function$
;
CREATE OR REPLACE FUNCTION getcountperiodvalne(ptperio numeric, percond character, dvalue numeric)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$

  DValSum   NUMBER;



  CURSOR C1 IS

    SELECT * FROM PTPERIT WHERE "PtPerio" = PtPerio AND "PerCond" = PerCond;

BEGIN

  DValSum := 0;



  FOR rec IN C1 LOOP

    IF rec."DValue1" <> DValue THEN

      DValSum := DValSum + 1;

    END IF;

    IF rec."DValue2" <> DValue THEN

      DValSum := DValSum + 1;

    END IF;

    IF rec."DValue3" <> DValue THEN

      DValSum := DValSum + 1;

    END IF;

  END LOOP;



  RETURN (DValSum);

END$function$
;
CREATE OR REPLACE FUNCTION getcountteeth(tooth character varying, pri character varying, perm character varying)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$

  vCount NUMBER(5) := 0;

BEGIN

  IF tooth IS NULL OR replace(tooth,' ') IS NULL THEN

    RETURN 32;

  END IF;

   

  FOR i IN 1 .. 32 LOOP

    IF NOT IsToothMissing(substr(tooth,i,1),substr(pri,i,1),substr(perm,i,1)) THEN

      vCount := vCount + 1;

    END IF;

  END LOOP;

  RETURN vCount ;

END$function$
;
CREATE OR REPLACE FUNCTION getdhr(patientid numeric)
 RETURNS character
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
	Prov CHAR(10 );
BEGIN
	BEGIN
		SELECT PP."Producer" INTO Prov FROM PTPROD PP, PRODUCER P, PRODTYPE PT WHERE
		PP."Deleted" = 0 AND PP."StartDate" <= TRUNC(ROUND(Sysdate)) AND PP."EndDate" >= TRUNC(ROUND(Sysdate))
		AND PP."Patient" = PatientId AND PP."IsPrimary" = 1 AND P."Producer" = PP."Producer" AND P."TypeCode" = PT."Code"
		AND PT."SubType" IN (3, 4);
		EXCEPTION WHEN NO_DATA_FOUND THEN
			Prov := '';
	END;

	return Prov;
END$function$
;
CREATE OR REPLACE FUNCTION getdisplostitemdesc(m_displost numeric)
 RETURNS character varying
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
	itemDesc		VARCHAR2(128);
	dispLostRow		DISPLOST%ROWTYPE;
BEGIN
	BEGIN
		--SELECT "Type" INTO dispLostType FROM DISPLOST WHERE DISPLOST."DispLost" = m_dispLost;
		SELECT * INTO dispLostRow FROM DISPLOST WHERE DISPLOST."DispLost" = m_dispLost;
	EXCEPTION
	WHEN NO_DATA_FOUND THEN
		RETURN ' ';
	END;
	
	IF dispLostRow."Type" = 0 THEN
		BEGIN
			SELECT "Description" INTO itemDesc FROM KITTYPE KITTYPE WHERE KITTYPE."KitType" = (
				SELECT "KitType" FROM KIT WHERE KIT."Kit" = dispLostRow."Kit"
			);
		END;
	ELSIF dispLostRow."Type" = 1 THEN
		BEGIN
			SELECT "Description" INTO itemDesc FROM SUNDRY WHERE SUNDRY."Sundry" = dispLostRow."Sundry";
		END;
	ELSIF dispLostRow."Type" = 2 THEN
		BEGIN
			SELECT "Description" INTO itemDesc FROM INSTRUMT WHERE INSTRUMT."Instrument" = (
				SELECT "Instrument" FROM KITITEM WHERE KITITEM."Kit" = dispLostRow."Kit" AND KITITEM."Item" = dispLostRow."Item"
			);
		END;
	ELSE
		itemDesc := ' ';
	END IF;
	
	RETURN itemDesc;
END$function$
;
CREATE OR REPLACE FUNCTION getdor(patientid numeric)
 RETURNS character
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
	Prov CHAR(10 );
BEGIN
	BEGIN
		SELECT PP."Producer" INTO Prov FROM PTPROD PP, PRODUCER P, PRODTYPE PT WHERE
		PP."Deleted" = 0 AND PP."StartDate" <= TRUNC(ROUND(Sysdate)) AND PP."EndDate" >= TRUNC(ROUND(Sysdate))
		AND PP."Patient" = PatientId AND PP."IsPrimary" = 1 AND P."Producer" = PP."Producer" AND P."TypeCode" = PT."Code"
		AND PT."SubType" IN (1, 2) AND ROWNUM = 1;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			Prov := '';
	END;

	return Prov;
END$function$
;
CREATE OR REPLACE FUNCTION getepr(patientid numeric)
 RETURNS TABLE(pitem numeric, fitem numeric, pform numeric, formcode character varying, date timestamp without time zone, description character varying, ownerid numeric, ownertype numeric, noteovr numeric, noteovrtext character varying, page numeric, "Row" numeric, "Type" numeric, anstype numeric, text character varying, ptsig numeric, ptsigdate timestamp without time zone)
 LANGUAGE edbspl
AS $function$

   sqlstmt   VARCHAR2 (4000 );

BEGIN

   sqlstmt :=

      'SELECT   0 AS "PItem", f."FItem", pf."PForm", pf."FormCode", pf."Date",

         pf."Description", pf."OwnerId", pf."OwnerType", 0 AS "NoteOvr",

         '''' AS "NoteOvrText", f."Page", f."Row", f."Type", f."AnsType",

         f."Text", 0 AS "PtSig", SYSDATE AS "PtSigDate"

    FROM fitem f, pform pf

   WHERE f."FormCode" = pf."FormCode"

     AND pf."Patient" = $1

     AND f."Deleted" = 0

     AND NOT EXISTS (

            SELECT ''x''

              FROM pitem p

             WHERE p."FItem" = f."FItem" AND p."Status" = 0

                   AND p."Patient" = $2)

UNION ALL

SELECT   p."PItem", f."FItem", pf."PForm", pf."FormCode", pf."Date",

         pf."Description", pf."OwnerId", pf."OwnerType",

         NVL (novr."Id", 0) AS "NoteOvr", NVL (novr."Text",

                                               '''') AS "NoteOvrText", f."Page",

         f."Row", f."Type", f."AnsType", f."Text", 0 AS "PtSig",

         SYSDATE AS "PtSigDate"

    FROM fitem f, pitem p, pform pf, noteovr novr

   WHERE f."FItem" = p."FItem"

     AND p."PForm" = pf."PForm"

     AND pf."Patient" = p."Patient"

     AND novr."ParentId"(+) = p."PItem"

     AND novr."Patient"(+) = p."Patient"

     AND f."FormCode" = ANY (SELECT fc."Code"

                               FROM form fc

                              WHERE fc."Code" = p."FormCode")

     AND p."Patient" = $3

     AND p."Status" = 0

     AND novr."Type"(+) = 1

     AND novr."Deleted"(+) = 0

UNION ALL

SELECT   0 AS "PItem", pp."FItem", pp."PForm", f."FormCode" AS "FormCode",

         SYSDATE AS "Date", '''' AS "Description", pf."OwnerId", pf."OwnerType",

         0 AS "NoteOvr", '''' AS "NoteOvrText", f."Page", f."Row", 1234 as "Type",

         1234 AS "AnsType", NVL (pp."Comment", '' '') AS "Text", pp."PtSig",

         pp."PtSigDate"

    FROM ppage pp, fitem f, pform pf

   WHERE f."FItem" = pp."FItem" AND pp."PForm" = pf."PForm" and pp."Patient" = $4 AND pp."Status" = 0

UNION ALL

SELECT   0 AS "PItem", pp."FItem", pp."PForm", f."FormCode" AS "FormCode",

         SYSDATE AS "Date", '''' AS "Description", pf."OwnerId", pf."OwnerType",

         0 AS "NoteOvr", '''' AS "NoteOvrText", f."Page", f."Row", 10000+pps."PtSig" as "Type",

         pps."PPage" AS "AnsType", NVL (pp."Comment", '' '') AS "Text", pps."PtSig",

         pp."PtSigDate"

    FROM ppage pp, fitem f, pform pf, ppagesig pps

   WHERE f."FItem" = pp."FItem" AND pp."PForm" = pf."PForm" and pp."Patient" = $5 AND pp."Status" = 0 and pp."PPage" = pps."PPage"

ORDER BY "PItem" DESC';

   RETURN QUERY EXECUTE

    sqlstmt USING patientid, patientid, patientid, patientid, patientid;

END

$function$
;
CREATE OR REPLACE FUNCTION getgregorianorhijridatestring(vdate timestamp without time zone, vformat character varying)
 RETURNS character varying
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
  UseHijri NUMBER             := 0;
  Result   VARCHAR2(255 ) := '';
BEGIN
  BEGIN
    SELECT COUNT(1)
    INTO UseHijri
    FROM SYSOPTS
    WHERE "Name" = 'ShowHijriDates'
    AND "Value"  = '1';
  EXCEPTION
  WHEN NO_DATA_FOUND THEN
    UseHijri := 0;
  END;
IF UseHijri > 0 THEN
  SELECT TO_CHAR(vDate, 'dd/mm/yyyy', 'nls_calendar=''arabic hijrah')
  INTO Result
  FROM DUAL;
ELSE
  SELECT TO_CHAR(vDate, vFormat) INTO Result FROM DUAL;
END IF;
RETURN Result;
END$function$
;
CREATE OR REPLACE FUNCTION getlockhandle(lockname character varying)
 RETURNS character varying
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$

  lock_handle VARCHAR(255);

BEGIN

  CALL DBMS_LOCK.ALLOCATE_UNIQUE(lockname, lock_handle);

  RETURN lock_handle;

END$function$
;
CREATE OR REPLACE FUNCTION getminimalcutoffperiod()
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
BEGIN
  RETURN 5;
END$function$
;
CREATE OR REPLACE FUNCTION getnpapptcode(patientid numeric)
 RETURNS character
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
	ApptCode CHAR(15 );
	
BEGIN
	--ApptCode := 'NEWPT'; -- --E98397
	--ApptCode := 'NEWA';
	SELECT DECODE(COUNT(1),0,'NEWA','NEWA INT') INTO ApptCode FROM PATIENT WHERE "Patient"=PatientId AND "CustomCode3" IN ('INTEP','INTERP');
	
	return ApptCode;
END$function$
;
CREATE OR REPLACE FUNCTION getnpperiod(patientid numeric)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
	Result NUMBER := 36;
	Class CHAR(30 ) := NULL;
	Risk CHAR(30 ) := NULL;
	
BEGIN
	BEGIN
	 SELECT PT."Value1", PT."Value2" INTO Class, Risk FROM PTSUMM PT, SUMMCODE S WHERE
	 PT."Patient" = PatientId AND
	 PT."SummCode" = S."SummCode" AND
	 S."Type" = 2;
	 EXCEPTION WHEN NO_DATA_FOUND THEN
		Result := 36;
	END; 	
	
	IF Class = 'P1' THEN
		Result := 60;
	ELSIF Class = 'P2' THEN
	BEGIN
		IF Risk = 'Low' THEN
			Result := 60;
		ELSE
			Result := 48;
		END IF;
	END;
	ELSIF Class = 'P3' THEN
	BEGIN
		IF Risk = 'Low' THEN
			Result := 48;
		ELSE
			Result := 36;
		END IF;
	END;
	ELSIF Class = 'P4' THEN
		Result := 24;
	END IF;
	
	
	Return Result;
END$function$
;
CREATE OR REPLACE FUNCTION getonlinereqapptinfo(lappointid numeric)
 RETURNS character varying
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$

	szOnlineReqApptInfo 	VARCHAR2(5000 );
	v_AppointData		APPOINT%ROWTYPE;
	v_ChairData    		CHAIR%ROWTYPE;					--AX-28868x
        v_ClinicData  		CLINIC%ROWTYPE;					--AX-28868x			
	v_nCount                NUMBER := 0;
	v_nLength		NUMBER := 0;					--AX-28868x	
	
BEGIN
	szOnlineReqApptInfo := '';

	/* no patient specified, nothing to return */
	if lAppointId = 0 then
		return szOnlineReqApptInfo;
	end if;

	SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_TYPE = 'FUNCTION' and OBJECT_NAME = 'CUSTOM_GETONLINEREQAPPTINFO';
	IF v_nCount > 0 THEN
		-- custom function exists to get the appt info
		EXECUTE IMMEDIATE 'SELECT CUSTOM_GETONLINEREQAPPTINFO('||lAppointId||') FROM DUAL' INTO szOnlineReqApptInfo;
		RETURN szOnlineReqApptInfo;
	END IF;

	BEGIN
		SELECT * INTO v_AppointData FROM APPOINT WHERE "Appointment" = lAppointId;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			return szOnlineReqApptInfo;
	END;

	--szOnlineReqApptInfo := 'Appointment: ';
	
	IF (v_AppointData."Type" < 3) THEN
	
		--AX-28868x
		BEGIN
			SELECT * INTO v_ChairData FROM CHAIR WHERE "Chair" = v_AppointData."Chair";
			EXCEPTION WHEN NO_DATA_FOUND THEN
				return szOnlineReqApptInfo;
		END;

		--AX-28868x
		BEGIN
			SELECT * INTO v_ClinicData FROM CLINIC WHERE "Clinic" = v_ChairData."Clinic";
			EXCEPTION WHEN NO_DATA_FOUND THEN
				return szOnlineReqApptInfo;
		END;
	
		-- set the date / time of the appointment
		szOnlineReqApptInfo := szOnlineReqApptInfo || TRIM(TO_CHAR(v_AppointData."Date", 'MON DD,YYYY'));
		IF v_AppointData."From" > 0 THEN
			szOnlineReqApptInfo := szOnlineReqApptInfo || ' ' || TRIM(TO_CHAR(FLOOR(v_AppointData."From"/60),'09')) || ':' ||  TRIM(TO_CHAR(MOD(v_AppointData."From",60),'09'));
			--AX-28868x
			v_nLength := v_AppointData."Time0"+ v_AppointData."Time1"+ v_AppointData."Time2"+ v_AppointData."Time3"+ v_AppointData."Time4"+ v_AppointData."Time5";
			szOnlineReqApptInfo := szOnlineReqApptInfo || ' - ' || TRIM(TO_CHAR(FLOOR((v_AppointData."From" + v_nLength)/60),'09'));
			szOnlineReqApptInfo := szOnlineReqApptInfo || ':' || TRIM(TO_CHAR(MOD((v_AppointData."From" + v_nLength),60),'09'));
			--szOnlineReqApptInfo := szOnlineReqApptInfo || ' Code: ' || TRIM(TO_CHAR(v_AppointData."Code"));
			szOnlineReqApptInfo := szOnlineReqApptInfo || ' in Clinic: ' || TRIM(TO_CHAR(v_ClinicData."Description"));
			--szOnlineReqApptInfo := szOnlineReqApptInfo || ', chair: ' || TRIM(TO_CHAR(v_ChairData."Description")) 		
		END IF;
	ELSIF (v_AppointData."Type" = 3) THEN
		szOnlineReqApptInfo := szOnlineReqApptInfo || 'Pending';			
	ELSIF (v_AppointData."Type" = 4) THEN
		szOnlineReqApptInfo := szOnlineReqApptInfo || 'Reschedule';			
	ELSIF (v_AppointData."Type" = 5) THEN
		szOnlineReqApptInfo := szOnlineReqApptInfo || 'Failed';			
	ELSIF (v_AppointData."Type" = 6) THEN
		szOnlineReqApptInfo := szOnlineReqApptInfo || 'Cancelled';			
	ELSIF (v_AppointData."Type" = 7) THEN
		szOnlineReqApptInfo := szOnlineReqApptInfo || 'Deleted';			
	ELSIF (v_AppointData."Type" = 8) THEN
		szOnlineReqApptInfo := szOnlineReqApptInfo || 'Request';			
	ELSIF (v_AppointData."Type" = 9) THEN
		szOnlineReqApptInfo := szOnlineReqApptInfo || 'Ortho Request';			
	ELSIF (v_AppointData."Type" = 10) THEN
		szOnlineReqApptInfo := szOnlineReqApptInfo || 'Planned';			
	ELSE
		szOnlineReqApptInfo := szOnlineReqApptInfo || 'Unknown';			
	END IF;

  	RETURN szOnlineReqApptInfo;
END$function$
;
CREATE OR REPLACE FUNCTION getpatientage(lpatient numeric, templatecode character varying, thedate timestamp without time zone)
 RETURNS character varying
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$

  szAge VARCHAR2(200) := '';

  BirthDate DATE;

  nAge NUMBER;

  nResult NUMBER := 1;

	

BEGIN

  BEGIN

	  Select "Birth" into BirthDate from PATIENT where "Patient" = lPatient;

	  EXCEPTION WHEN NO_DATA_FOUND THEN

	  nResult := 0;

  END;



  If nResult = 1 THEN 

    nAge := TRUNC(months_between(TheDate, BirthDate)/12);

    szAge := TO_CHAR(nAge);

  END IF;

	

  RETURN szAge;

END$function$
;
CREATE OR REPLACE FUNCTION getpatientbirth(patientid numeric, hijri numeric DEFAULT 0)
 RETURNS timestamp without time zone
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
  Birth DATE;
  UseHijri NUMBER := 0; -- AX-21958
BEGIN
	  BEGIN
		SELECT "Birth" INTO Birth FROM PATIENT WHERE "Patient" = PatientId;
	  EXCEPTION
	  WHEN NO_DATA_FOUND THEN
		Birth := SYSDATE;
	  END;

	  -- AX-21958
	  IF Hijri > 0 THEN
		  BEGIN
			SELECT COUNT(1) INTO UseHijri
			FROM SYSOPTS WHERE "Name" = 'ShowHijriDates' AND "Value"  = '1';
		  EXCEPTION
		  WHEN NO_DATA_FOUND THEN
			UseHijri := 0;
		  END;
	END IF;

	-- AX-21958
	IF UseHijri = 1 THEN
		BEGIN
			SELECT TO_DATE(TO_CHAR(Birth, 'dd/mm/yyyy', 'nls_calendar=''arabic hijrah'), 'dd/mm/yyyy')
			INTO Birth FROM DUAL;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			UseHijri := 0;
		END;
	END IF;
RETURN Birth;
END$function$
;
CREATE OR REPLACE FUNCTION getpatientname(vpatientid numeric, vformat numeric DEFAULT 0, vdutchformat numeric DEFAULT 0, vincludechart numeric DEFAULT 0)
 RETURNS character varying
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
	Result VARCHAR2(255 ) := '';
	vLast  PATIENT."Last"%TYPE := '';
	vFirst PATIENT."First"%TYPE := '';
	vPreferred PATIENT."Prefered"%TYPE := '';
	vMiddle PATIENT."Middle"%TYPE := '';
	vPartnerPrefix PATIENT."PartnerPrefix"%TYPE := '';
	vPartnerName PATIENT."PartnerName"%TYPE := '';
	vChart PATIENT."Chart"%TYPE := '';
	vAltChart PATIENT."AltChart"%TYPE := '';
	vCountry PRACTICE."Country"%TYPE;
	vIsRTL BOOLEAN := FALSE;
BEGIN
	BEGIN
		SELECT "Country"
		INTO vCountry
		FROM PRACTICE
		WHERE ROWNUM = 1;
	EXCEPTION WHEN NO_DATA_FOUND THEN
		RETURN '';
	END;
	
	BEGIN
		SELECT "Last", "First",	"Prefered", "Middle", "PartnerPrefix", "PartnerName", "Chart", "AltChart"
		INTO vLast, vFirst, vPreferred, vMiddle, vPartnerPrefix, vPartnerName, vChart, vAltChart
		FROM PATIENT
		WHERE "Patient" = vPatientId;
	EXCEPTION WHEN NO_DATA_FOUND THEN
		RETURN '';
	END;
	
	
	IF vCountry = 2 AND vDutchFormat > 0 THEN -- dutch overrides
		-- Preferred Middle Last
		IF vDutchFormat = 1 THEN
			Result := TRIM(vPreferred) || ' ' || TRIM(vMiddle) || ' ' || TRIM(vLast);
			
		-- P. Middle Last
		ELSIF vDutchFormat = 2 THEN
			Result := SUBSTR(vPreferred, 0, 1) || '. ' || TRIM(vMiddle) || ' ' || TRIM(vLast);
			
		-- First Middle Last
		ELSIF vDutchFormat = 3 THEN
			Result := TRIM(vFirst) || ' ' || TRIM(vMiddle) || ' ' || TRIM(vLast);

		-- First Partner Last
		ELSIF vDutchFormat = 4 THEN
			Result := TRIM(vFirst) || ' ' || TRIM(vPartnerPrefix) || ' ' || TRIM(vPartnerName) || ' ' || TRIM(vMiddle) || ' ' || TRIM(vLast);

		-- Last, First Middle
		ELSIF vDutchFormat = 5 THEN
			Result := TRIM(vLast) || ', ' || TRIM(vFirst) || ' ' || TRIM(vMiddle);
				
		END IF;
		
	ELSE -- everyone else
	
		-- format the name
		
		-- Last, First
		IF vFormat = 0 THEN
			IF HasRTLCharacters(vLast) OR HasRTLCharacters(vFirst) THEN
				vIsRTL := TRUE;
				Result := UNISTR('\202B') || TRIM(vFirst) || UNISTR('\060C ') || TRIM(vLast) || UNISTR('\202C');
			ELSE
				Result := TRIM(vLast) || ', ' || TRIM(vFirst);
			END IF;
			
		-- Last, Preferred
		ELSIF vFormat = 1 THEN
			IF HasRTLCharacters(vLast) OR HasRTLCharacters(vPreferred) THEN
				vIsRTL := TRUE;
				Result := UNISTR('\202B') || TRIM(vPreferred) || UNISTR('\060C ') || TRIM(vLast) || UNISTR('\202C');
			ELSE
				Result := TRIM(vLast) || ', ' || TRIM(vPreferred);
			END IF;
		
		-- First Last (Arabic overrides to Last, First)
		ELSIF vFormat = 2 THEN
			IF HasRTLCharacters(vLast) OR HasRTLCharacters(vFirst) THEN
				vIsRTL := TRUE;
				Result := UNISTR('\202B') || TRIM(vFirst) || UNISTR('\060C ') || TRIM(vLast) || UNISTR('\202C');
			ELSE
				Result := TRIM(vFirst) || ' ' || TRIM(vLast);
			END IF;
		
		-- Preferred Last (Arabic overrides to Last, Preferred)
		ELSIF vFormat = 3 THEN
			IF HasRTLCharacters(vLast) OR HasRTLCharacters(vPreferred) THEN
				vIsRTL := TRUE;
				Result := UNISTR('\202B') || TRIM(vPreferred) || UNISTR('\060C ') || TRIM(vLast) || UNISTR('\202C');
			ELSE
				Result := TRIM(vPreferred) || ' ' || TRIM(vLast);
			END IF;
				
		-- First Middle Last (Arabic overrides to Last, First Middle)
		ELSIF vFormat = 4 THEN
			IF HasRTLCharacters(vLast) OR HasRTLCharacters(vFirst) OR HasRTLCharacters(vMiddle) THEN
				vIsRTL := TRUE;
				Result := UNISTR('\202B') || TRIM(vMiddle) || ' ' || TRIM(vFirst) || UNISTR('\060C ') || TRIM(vLast) || UNISTR('\202C');
			ELSE
				Result := TRIM(vFirst) || ' ' || TRIM(vMiddle) || ' ' || TRIM(vLast);
			END IF;
				
		-- Last, First Middle
		ELSIF vFormat = 5 THEN
			IF HasRTLCharacters(vLast) OR HasRTLCharacters(vFirst) THEN
				vIsRTL := TRUE;
				Result := UNISTR('\202B') || TRIM(vMiddle) || ' ' || TRIM(vFirst) || UNISTR('\060C ') || TRIM(vLast) || UNISTR('\202C');
			ELSE
				Result := TRIM(vLast) || ', ' || TRIM(vFirst) || ' ' || TRIM(vMiddle);
			END IF;
				
		END IF;
	END IF;
	
	-- Add the chart
	IF vIncludeChart > 0 THEN
	
		-- AltChart
		IF vIncludeChart = 2 AND LENGTH(TRIM(vAltChart)) > 0 THEN
			IF vIsRTL THEN
				Result := Result || UNISTR('\202A') || '(' || TRIM(vAltChart) || ') ' || UNISTR('\202C');
			ELSE
				Result := Result || ' (' || TRIM(vAltChart) || ')';
			END IF;

		-- Chart
		ELSIF vIncludeChart > 0 THEN
			IF vIsRTL THEN
				Result := Result || UNISTR('\202A') || '(' || TRIM(vChart) || ') ' || UNISTR('\202C')  ;
			ELSE
				Result := Result || ' (' || TRIM(vChart) || ')';
			END IF;
		
		END IF;
	END IF;		
	
	RETURN Result;
END$function$
;
CREATE OR REPLACE FUNCTION getpatientreqpreference(vonlinerequestid numeric)
 RETURNS character varying
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
	Preference		VARCHAR2(128 );
	ReturnString		VARCHAR2(128 );
	OnlineRequest		ONLINE_REQUEST%ROWTYPE;
BEGIN
	BEGIN
		SELECT * INTO OnlineRequest FROM ONLINE_REQUEST WHERE ONLINE_REQUEST."Id" = vOnlineRequestId;
	EXCEPTION
	WHEN NO_DATA_FOUND THEN
		RETURN 'M, T, W, Th, F';
	END;
	
	ReturnString := NULL;
	Preference := NULL;
	IF OnlineRequest."PreferMonday" = 1 THEN
		Preference := 'M(AM)';
	ELSIF OnlineRequest."PreferMonday" = 2 THEN
		Preference := 'M(PM)';
	ELSIF OnlineRequest."PreferMonday" = 3 THEN
		Preference := 'M';
	END IF;
	IF Preference IS NOT NULL THEN
		IF ReturnString IS NOT NULL THEN
			ReturnString := ReturnString || ', ';
		END IF;
		ReturnString := ReturnString || Preference;
	END IF;
	Preference := NULL;
	IF OnlineRequest."PreferTuesday" = 1 THEN
		Preference := Preference || 'T(AM)';
	ELSIF OnlineRequest."PreferTuesday" = 2 THEN
		Preference := Preference || 'T(PM)';
	ELSIF OnlineRequest."PreferTuesday" = 3 THEN
		Preference := Preference || 'T';
	END IF;
	IF Preference IS NOT NULL THEN
		IF ReturnString IS NOT NULL THEN
			ReturnString := ReturnString || ', ';
		END IF;
		ReturnString := ReturnString || Preference;
	END IF;
	Preference := NULL;
	IF OnlineRequest."PreferWednesday" = 1 THEN
		Preference := Preference || 'W(AM)';
	ELSIF OnlineRequest."PreferWednesday" = 2 THEN
		Preference := Preference || 'W(PM)';
	ELSIF OnlineRequest."PreferWednesday" = 3 THEN
		Preference := Preference || 'W';
	END IF;
	IF Preference IS NOT NULL THEN
		IF ReturnString IS NOT NULL THEN
			ReturnString := ReturnString || ', ';
		END IF;
		ReturnString := ReturnString || Preference;
	END IF;
	Preference := NULL;
	IF OnlineRequest."PreferThursday" = 1 THEN
		Preference := Preference || 'Th(AM)';
	ELSIF OnlineRequest."PreferThursday" = 2 THEN
		Preference := Preference || 'Th(PM)';
	ELSIF OnlineRequest."PreferThursday" = 3 THEN
		Preference := Preference || 'Th';
	END IF;
	IF Preference IS NOT NULL THEN
		IF ReturnString IS NOT NULL THEN
			ReturnString := ReturnString || ', ';
		END IF;
		ReturnString := ReturnString || Preference;
	END IF;
	Preference := NULL;
	IF OnlineRequest."PreferFriday" = 1 THEN
		Preference := Preference || 'F(AM)';
	ELSIF OnlineRequest."PreferFriday" = 2 THEN
		Preference := Preference || 'F(PM)';
	ELSIF OnlineRequest."PreferFriday" = 3 THEN
		Preference := Preference || 'F';
	END IF;
	IF Preference IS NOT NULL THEN
		IF ReturnString IS NOT NULL THEN
			ReturnString := ReturnString || ', ';
		END IF;
		ReturnString := ReturnString || Preference;
	END IF;
	Preference := NULL;
	IF OnlineRequest."PreferSaturday" = 1 THEN
		Preference := Preference || 'Sa(AM)';
	ELSIF OnlineRequest."PreferSaturday" = 2 THEN
		Preference := Preference || 'Sa(PM)';
	ELSIF OnlineRequest."PreferSaturday" = 3 THEN
		Preference := Preference || 'Sa';
	END IF;
	IF Preference IS NOT NULL THEN
		IF ReturnString IS NOT NULL THEN
			ReturnString := ReturnString || ', ';
		END IF;
		ReturnString := ReturnString || Preference;
	END IF;
	Preference := NULL;
	IF OnlineRequest."PreferSunday" = 1 THEN
		Preference := Preference || 'Su(AM)';
	ELSIF OnlineRequest."PreferSunday" = 2 THEN
		Preference := Preference || 'Su(PM)';
	ELSIF OnlineRequest."PreferSunday" = 3 THEN
		Preference := Preference || 'Su';
	END IF;
	IF Preference IS NOT NULL THEN
		IF ReturnString IS NOT NULL THEN
			ReturnString := ReturnString || ', ';
		END IF;
		ReturnString := ReturnString || Preference;
	END IF;
	

	RETURN ReturnString;
END$function$
;
CREATE OR REPLACE FUNCTION getphonewithoutareacode(m_contactat numeric, m_homephone character varying, m_workphone character varying, m_otherphone character varying, m_mobilephone character varying)
 RETURNS character varying
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
	tmpPhone			VARCHAR2(32 );
	resultPhone		VARCHAR2(32 );
BEGIN
	BEGIN
		SELECT DECODE(m_ContactAt, 1, m_HomePhone, 2, m_WorkPhone, 3, m_OtherPhone, 4, m_MobilePhone) INTO tmpPhone FROM DUAL;
	END;
	
	IF Length(TRIM(tmpPhone)) > 0 THEN
		resultPhone := TRIM(tmpPhone);
	ELSE
		return ' ';
	END IF;
	
	return resultPhone;
END$function$
;
CREATE OR REPLACE FUNCTION getsurfacesplaquebeingcharted(ptperio numeric, percond character, dvalue numeric, toothstateval character, primarystateval character, permanentstateval character)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$

  DValSum   NUMBER;



  CURSOR C1 IS

    SELECT * FROM PTPERIT WHERE "PtPerio" = PtPerio AND "PerCond" = PerCond;

BEGIN

  DValSum := 0;



  FOR rec IN C1 LOOP

      IF NOT IsToothMissing(substr(ToothStateVal,rec."Site",1),substr(PrimaryStateVal,rec."Site",1),substr(PermanentStateVal,rec."Site",1)) THEN

          IF rec."DValue1" >= DValue THEN

            DValSum := DValSum + 1;

          END IF;

          IF rec."DValue2" >= DValue THEN

            DValSum := DValSum + 1;

          END IF;

          IF rec."DValue3" >= DValue THEN

            DValSum := DValSum + 1;

          END IF;

      END IF;

  END LOOP;



  RETURN (DValSum);

END$function$
;
CREATE OR REPLACE FUNCTION getsurfacesplaquesetup(percond character, toothstateval character, primarystateval character, permanentstateval character)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$

  DValSum   NUMBER;

  SiteVal1   NUMBER(5);   

  SiteVal2   NUMBER(5);   

  CURSOR C1 IS

   SELECT * FROM PERSITE ps WHERE ps."PerCond" = PerCond ORDER BY "Site", "Arch";



BEGIN

  DValSum := 0;



  FOR rec IN C1 LOOP

      SiteVal1 := CovertToActualSite(rec."Arch", rec."Site", 0);

      SiteVal2 := CovertToActualSite(rec."Arch", rec."Site", 1);



      IF NOT IsToothMissing(substr(ToothStateVal,SiteVal1,1),substr(PrimaryStateVal,SiteVal1,1),substr(PermanentStateVal,SiteVal1,1)) THEN

         DValSum := DValSum + rec."Facial1" + rec."Facial2" + rec."Facial3" + rec."Lingual1" + rec."Lingual2" + rec."Lingual3";

      END IF;

      IF NOT IsToothMissing(substr(ToothStateVal,SiteVal2,1),substr(PrimaryStateVal,SiteVal2,1),substr(PermanentStateVal,SiteVal2,1)) THEN

         DValSum := DValSum + rec."Facial1" + rec."Facial2" + rec."Facial3" + rec."Lingual1" + rec."Lingual2" + rec."Lingual3";

      END IF;

  END LOOP;



  RETURN (DValSum);

END$function$
;
CREATE OR REPLACE FUNCTION gettoothcountperiodvalne(ptperio numeric, percond character, dvalue numeric)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$

  DValSum   NUMBER;

  SiteVal   NUMBER;



  CURSOR C1 IS

    SELECT * FROM PTPERIT WHERE "PtPerio" = PtPerio AND "PerCond" = PerCond;

BEGIN

  DValSum := 0;

  SiteVal := 0;



  FOR rec IN C1 LOOP

    IF rec."Site" <> SiteVal THEN

      SiteVal := rec."Site";



      IF rec."DValue1" <> DValue THEN

        DValSum := DValSum + 1;

      ELSIF rec."DValue2" <> DValue THEN

        DValSum := DValSum + 1;

      ELSIF rec."DValue3" <> DValue THEN

        DValSum := DValSum + 1;

      END IF;

    END IF;

  END LOOP;



  RETURN (DValSum);

END$function$
;
CREATE OR REPLACE FUNCTION getxrefphonenumber(m_contactat numeric, m_homearea character varying, m_workarea character varying, m_otherarea character varying, m_mobilearea character varying, m_homephone character varying, m_workphone character varying, m_otherphone character varying, m_mobilephone character varying, m_workext character varying, m_otherext character varying, m_criteria character varying)
 RETURNS character varying
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
	contactAt		CHAR(3 );
	tmpAreaCode		VARCHAR2(32 );
	tmpPhone		VARCHAR2(32 );
	tmpExt			VARCHAR2(32 );
	resultPhone		VARCHAR2(32 );
	
	tmpHome			VARCHAR2(32 );		-- New!
	tmpMobile		VARCHAR2(32 );		-- New!	
	tmpWork			VARCHAR2(32 );		-- New!
	tmpOther		VARCHAR2(32 );		-- New!
BEGIN
	BEGIN
		SELECT DECODE(1, 1, m_HomePhone), DECODE(1, 1, m_MobilePhone), DECODE(1, 1, m_WorkPhone), DECODE(1, 1, m_OtherPhone)
		INTO tmpHome, tmpMobile, tmpWork, tmpOther
		FROM DUAL
		WHERE m_HomePhone LIKE m_Criteria || '%' OR
				m_MobilePhone LIKE m_Criteria || '%' OR
				m_WorkPhone LIKE m_Criteria || '%' OR
				m_OtherPhone LIKE m_Criteria || '%';
				
		SELECT DECODE(m_ContactAt, 1, 'H: ', 2, 'W: ', 3, 'O: ', 4, 'M: '),
				DECODE(m_ContactAt, 1, m_HomeArea, 2, m_WorkArea, 3, m_OtherArea, 4, m_MobileArea),
				DECODE(m_ContactAt, 1, tmpHome, 2, tmpWork, 3, tmpOther, 4, tmpMobile),
				DECODE(m_ContactAt, 2, m_WorkExt, 3, m_OtherExt)
				INTO contactAt, tmpAreaCode, tmpPhone, tmpExt
				FROM DUAL;
	END;
	
	IF NOT(tmpPhone IS NOT NULL AND LENGTH(TRIM(tmpPhone)) > 0 AND INSTR(tmpPhone, m_Criteria) = 1) THEN
		IF tmpHome IS NOT NULL AND LENGTH(TRIM(tmpHome)) > 0 AND INSTR(tmpHome, m_Criteria) = 1 THEN
			-- use home phone
			contactAt := 'H: ';
			tmpPhone := tmpHome;
			tmpAreaCode := m_HomeArea;
			tmpExt := '';
		ELSE
			IF tmpMobile IS NOT NULL AND LENGTH(TRIM(tmpMobile)) > 0 AND INSTR(tmpMobile, m_Criteria) = 1 THEN
				-- use mobile instead
				contactAt := 'M: ';
				tmpPhone := tmpMobile;
				tmpAreaCode := m_MobileArea;
				tmpExt := '';
			ELSE
				IF tmpWork IS NOT NULL AND LENGTH(TRIM(tmpWork)) > 0 AND INSTR(tmpWork, m_Criteria) = 1 THEN
					-- use work phone instead
					contactAt := 'W: ';
					tmpPhone := tmpWork;
					tmpAreaCode := m_WorkArea;
					tmpExt := m_WorkExt;
				ELSE
					IF tmpOther IS NOT NULL AND LENGTH(TRIM(tmpOther)) > 0 AND INSTR(tmpOther, m_Criteria) = 1 THEN
						-- use other phone instead
						contactAt := 'O: ';
						tmpPhone := tmpOther;
						tmpAreaCode := m_OtherArea;
						tmpExt := m_OtherExt;
					ELSE
						BEGIN	
							SELECT DECODE(m_ContactAt, 1, 'H: ', 2, 'W: ', 3, 'O: ', 4, 'M: '),
									 DECODE(m_ContactAt, 1, m_HomeArea, 2, m_WorkArea, 3, m_OtherArea, 4, m_MobileArea),
									 DECODE(m_ContactAt, 1, tmpHome, 2, tmpWork, 3, tmpOther, 4, tmpMobile),
									 DECODE(m_ContactAt, 2, m_WorkExt, 3, m_OtherExt)
							INTO contactAt, tmpAreaCode, tmpPhone, tmpExt
							FROM DUAL;
						END;
					END IF;
				END IF;
			END IF;
		END IF;
	END IF;
		
	IF tmpPhone IS NULL OR LENGTH(TRIM(tmpPhone)) = 0 THEN
		IF LENGTH(TRIM(tmpOther)) > 0 THEN
			contactAt := 'O: ';
			tmpPhone := tmpOther;
			tmpAreaCode := m_OtherArea;
			tmpExt := m_OtherExt;
		END IF;
		
		IF tmpWork IS NOT NULL AND LENGTH(TRIM(tmpWork)) > 0 THEN
			contactAt := 'W: ';
			tmpPhone := tmpWork;
			tmpAreaCode := m_WorkArea;
			tmpExt := m_WorkExt;
		END IF;
		
		IF tmpMobile IS NOT NULL AND LENGTH(TRIM(tmpMobile)) > 0 THEN
			contactAt := 'M: ';
			tmpPhone := tmpMobile;
			tmpAreaCode := m_MobileArea;
			tmpExt := '';
		END IF;
		
		IF tmpHome IS NOT NULL AND LENGTH(TRIM(tmpHome)) > 0 THEN
			contactAt := 'H: ';
			tmpPhone := tmpHome;
			tmpAreaCode := m_HomeArea;
			tmpExt := '';
		END IF;
		
		IF tmpPhone IS NULL OR LENGTH(TRIM(tmpPhone)) = 0 THEN
			return ' ';
		END IF;
	END IF;
	
	-- Format the stuff to return
	IF Length(TRIM(tmpAreaCode)) > 0 THEN
		resultPhone := contactAt || '(' || TRIM(tmpAreaCode) || ') ' || TRIM(tmpPhone);
	ELSE
		IF Length(TRIM(tmpPhone)) > 0 THEN
			resultPhone := contactAt || TRIM(tmpPhone);
		END IF;
	END IF;
	
	IF (Length(TRIM(tmpAreaCode)) <= 0 AND Length(TRIM(tmpPhone)) <= 0) THEN
		return ' ';
	END IF;
		
	IF Length(TRIM(tmpExt)) > 0 THEN
		resultPhone := resultPhone || ' x' || TRIM(tmpExt);	-- Ext.
	END IF;
	
	return resultPhone;
END$function$
;
CREATE OR REPLACE FUNCTION getxrefphonenumberlite(m_contactat numeric, m_homephone character varying, m_workphone character varying, m_otherphone character varying, m_mobilephone character varying, m_workext character varying, m_otherext character varying, m_criteria character varying)
 RETURNS character varying
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
	contactAt		CHAR(3 );
	tmpAreaCode		VARCHAR2(32 );
	tmpPhone			VARCHAR2(32 );
	tmpExt			VARCHAR2(32 );
	resultPhone		VARCHAR2(32 );
	tmpHome			VARCHAR2(32 );		-- New!
	tmpMobile		VARCHAR2(32 );		-- New!	
	tmpWork			VARCHAR2(32 );		-- New!
	tmpOther			VARCHAR2(32 );		-- New!
BEGIN
	BEGIN
		SELECT DECODE(1, 1, m_HomePhone), DECODE(1, 1, m_MobilePhone), DECODE(1, 1, m_WorkPhone), DECODE(1, 1, m_OtherPhone)
		INTO tmpHome, tmpMobile, tmpWork, tmpOther
		FROM DUAL
		WHERE m_HomePhone LIKE m_Criteria || '%' OR
				m_MobilePhone LIKE m_Criteria || '%' OR
				m_WorkPhone LIKE m_Criteria || '%' OR
				m_OtherPhone LIKE m_Criteria || '%';
	END;
	
		IF tmpHome IS NOT NULL AND LENGTH(TRIM(tmpHome)) > 0 AND INSTR(tmpHome, m_Criteria) = 1 THEN
		-- use home phone
		contactAt := 'H: ';
		tmpPhone := tmpHome;
		tmpExt := '';
	ELSE
		IF tmpMobile IS NOT NULL AND LENGTH(TRIM(tmpMobile)) > 0 AND INSTR(tmpMobile, m_Criteria) = 1 THEN
			-- use mobile instead
			contactAt := 'M: ';
			tmpPhone := tmpMobile;
			tmpExt := '';
		ELSE
			IF tmpWork IS NOT NULL AND LENGTH(TRIM(tmpWork)) > 0 AND INSTR(tmpWork, m_Criteria) = 1 THEN
				-- use work phone instead
				contactAt := 'W: ';
				tmpPhone := tmpWork;
				tmpExt := m_WorkExt;
			ELSE
				IF tmpOther IS NOT NULL AND LENGTH(TRIM(tmpOther)) > 0 AND INSTR(tmpOther, m_Criteria) = 1 THEN
					-- use other phone instead
					contactAt := 'O: ';
					tmpPhone := tmpOther;
					tmpExt := m_OtherExt;
				ELSE
					BEGIN	
						SELECT DECODE(m_ContactAt, 1, tmpHome, 2, tmpWork, 3, tmpOther, 4, tmpMobile),
								 DECODE(m_ContactAt, 2, m_WorkExt, 3, m_OtherExt)
						INTO tmpPhone, tmpExt
						FROM DUAL;
					END;
				END IF;
			END IF;
		END IF;
	END IF;
	
	IF LENGTH(TRIM(tmpPhone)) = 0 OR tmpPhone IS NULL THEN
		IF LENGTH(TRIM(tmpOther)) > 0 THEN
			contactAt := 'O: ';
			tmpPhone := tmpOther;
			tmpExt := m_OtherExt;
		END IF;
		
		IF tmpWork IS NOT NULL AND LENGTH(TRIM(tmpWork)) > 0 THEN
			contactAt := 'W: ';
			tmpPhone := tmpWork;
			tmpExt := m_WorkExt;
		END IF;
		
		IF tmpMobile IS NOT NULL AND LENGTH(TRIM(tmpMobile)) > 0 THEN
			contactAt := 'M: ';
			tmpPhone := tmpMobile;
			tmpExt := '';
		END IF;
		
		IF tmpHome IS NOT NULL AND LENGTH(TRIM(tmpHome)) > 0 THEN
			contactAt := 'H: ';
			tmpPhone := tmpHome;
			tmpExt := '';
		END IF;
		
		IF tmpPhone IS NULL OR LENGTH(TRIM(tmpPhone)) = 0 THEN
			return ' ';
		END IF;
	END IF;
	
	resultPhone := tmpPhone || tmpExt;
	
	return resultPhone;
END$function$
;
CREATE OR REPLACE FUNCTION gregoriantohijri(vdate timestamp without time zone)
 RETURNS timestamp without time zone
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
  Result DATE;
BEGIN
  BEGIN
    SELECT TO_DATE(TO_CHAR(vDate, 'mm/dd/yyyy', 'nls_calendar=''arabic hijrah'), 'mm/dd/yyyy')
    INTO Result
    FROM DUAL;
  EXCEPTION
  WHEN OTHERS THEN -- handle that sneaky leap year...
    SELECT TO_DATE(TO_CHAR(vDate + 1, 'mm/dd/yyyy', 'nls_calendar=''arabic hijrah'), 'mm/dd/yyyy')
    INTO Result
    FROM DUAL;
  END;
RETURN Result;
END$function$
;
CREATE OR REPLACE FUNCTION hasnomedsreview(lpatient numeric)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
  Result NUMBER;

BEGIN

  BEGIN
    SELECT COUNT(1)
      INTO Result
      FROM EPREVIEW P
      WHERE P."Patient" = lPatient
        AND P."Type" = 0
        AND P."Deleted" = 0
        AND P."HasRecords" = 0
        AND P."EPReview" = (SELECT MAX(P2."EPReview")
        FROM EPREVIEW P2 WHERE
        P2."Patient" = P."Patient"
        AND P2."Type" = 0
        AND P2."Deleted" = 0);
  EXCEPTION WHEN NO_DATA_FOUND THEN
  	Result := 0;
  END;


  IF Result > 0 THEN
  	RETURN 1;
  ELSE
  	RETURN 0;
  END IF;

END$function$
;
CREATE OR REPLACE FUNCTION hasrtlcharacters(vinput character varying)
 RETURNS boolean
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
BEGIN
	-- currently looking for Arabic character set, can be enhanced to look for others
	RETURN vInput ~  UNISTR('[\0600-\06FF]');
END$function$
;
CREATE OR REPLACE FUNCTION hijritogregorian(vdate timestamp without time zone)
 RETURNS timestamp without time zone
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
  Result DATE;
BEGIN
  SELECT TO_DATE(TO_CHAR(TO_DATE(vDate, 'mm/dd/yyyy', 'nls_calendar=''arabic hijrah'''), 'mm/dd/yyyy', 'nls_calendar=''Gregorian'''))
  INTO Result
  FROM DUAL;
RETURN Result;
END$function$
;
CREATE OR REPLACE FUNCTION isrecallactive(patientrecallid numeric)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
  Result NUMBER;

BEGIN
  Result := 0;

  BEGIN
	SELECT COUNT(1)
	INTO Result
	FROM PTRECALL P
	WHERE P."Id" = PatientRecallId
	AND P."Deleted" = 0
	AND NOT EXISTS (SELECT 1 FROM STATUS S WHERE
	P."Status" = S."Status" AND S."Type" = 4
	AND S."MakeInactive" = 1);
	EXCEPTION WHEN NO_DATA_FOUND THEN
	Result := 0;
  END;


  IF Result = 0 THEN
  	RETURN 0;
  ELSE
  	RETURN 1;
  END IF;
END$function$
;
CREATE OR REPLACE FUNCTION istoothmissing(tooth_val character, pri_val character, perm_val character)
 RETURNS boolean
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$

BEGIN 

      IF tooth_val IN ('2','3') THEN

         return TRUE;

      END IF;

      

      IF tooth_val = '0' THEN -- is permanent tooth

        IF perm_val = '1' THEN -- tooth has been extracted

          RETURN TRUE;

        END IF;

        

        IF perm_val = '2' THEN -- tooth has been impacted

          RETURN TRUE;

        END IF;

      ELSIF tooth_val = '1' THEN -- is primary tooth

        IF pri_val = '1' THEN -- tooth has been extracted

          RETURN TRUE;

        END IF;

        

        IF pri_val = '2' THEN -- tooth has been impacted

          RETURN TRUE;

        END IF;

      END IF;

            

      RETURN FALSE;

END$function$
;
CREATE OR REPLACE FUNCTION lastappointtrx_proc(patient numeric)
 RETURNS TABLE(lasttrans timestamp without time zone, patientbalance numeric, lastcode character)
 LANGUAGE edbspl
AS $function$

  LastTrans DATE;

  LastCode  CHAR(8 );

  PatientBalance NUMBER := 0.0;

BEGIN

--  SELECT MAX("TreatmentDate") into LastTrans from TRX where "Patient"=Patient and "Deleted"=0;

  BEGIN

  SELECT "TreatmentDate",decode("Type",1,"Procedure","Code") into LastTrans, LastCode from

    (SELECT "TreatmentDate","Type","Procedure","Code" from TRX where "Patient"=Patient and "Deleted"=0 and

    "Type"  IN (1,2,3,6,73,74) order by "TreatmentDate" DESC) where rownum=1;			-- AX-24432

  EXCEPTION

   WHEN NO_DATA_FOUND THEN

     LastTrans := null;

     LastCode := '';

  END;

  PatientBalance := LASTAPPOINTTRX_PKG.PtBalance(Patient);



  RETURN QUERY

   select LastTrans as LastTrans, PatientBalance as PatientBalance, LastCode as LastCode from dual;

END

$function$
;
CREATE OR REPLACE FUNCTION lastptperco(patientval numeric, percond character)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$

	PtPerioVal		NUMBER;

	PtPerCondVal	NUMBER;  

BEGIN

	PtPerioVal := 0;

	PtPerCondVal := 0;

	

	SELECT MAX(PC."PtPerCo") INTO PtPerCondVal FROM PTPERCO PC WHERE PC."Patient" = PatientVal AND PC."PerCond" = PerCond AND PC."Deleted" = 0;



	SELECT PC."PtPerio" INTO PtPerioVal FROM PTPERCO PC WHERE PC."PtPerCo" = PtPerCondVal;

		

	RETURN (PtPerioVal);

EXCEPTION

	WHEN NO_DATA_FOUND THEN

		RETURN NULL;

END$function$
;
CREATE OR REPLACE FUNCTION ltr_char()
 RETURNS character
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
  ltrChar CHAR(1 );
BEGIN
  ltrChar := UNISTR('\200E');
  RETURN ltrChar;
END LTR_CHAR$function$
;
CREATE OR REPLACE FUNCTION maxsurgeryaudit(appointmentid numeric)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$ 

  Result NUMBER;

BEGIN

    Result := 0;

    

    select max("Audit") into Result from (

      select "Audit" from ptsurg where "Appointment" = AppointmentId

      union

      select "Audit" from ptvital where "Appointment" = AppointmentId

      union

      select "Audit" from ptsdrug where "Appointment" = AppointmentId

      union 

      select ptsdose."Audit" from ptsdose, ptsdrug where ptsdose."PtSDrug" = ptsdrug."PtSDrug" and ptsdrug."Appointment" = AppointmentId );



  RETURN Result;

END$function$
;
CREATE OR REPLACE FUNCTION mcappoint_t2neverdeleted(patid numeric, preid numeric)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
    vId      NUMBER := 0;
    vDeleted NUMBER := 0;
  BEGIN
    BEGIN
      SELECT "Auto",
        "Deleted"
      INTO vId,
        vDeleted
      FROM TREATME2
      WHERE "Auto" = (select max(t2."Auto") from treatme2 t2
      	where t2."PId" = PatId and t2."PreId" = PreId);
    EXCEPTION
    WHEN NO_DATA_FOUND THEN
      vId      := 0;
      vDeleted := 0;
    END;
    IF vId = 0 THEN
      RETURN 1;
    ELSE
      IF vDeleted = 1 THEN
        RETURN 0;
      ELSE
        RETURN mcappoint_T2NeverDeleted (PatId, vId) ;
      END IF;
    END IF;
  END$function$
;
CREATE OR REPLACE FUNCTION mobilcount(patientval numeric)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$

  CountVal    NUMBER;

  PtPerioVal  NUMBER;

BEGIN

  PtPerioVal := LastPtPerCo(PatientVal, 'MOBIL');				-- E33252

  CountVal := GetToothCountPerioDValNE(PtPerioVal, 'MOBIL', 0.0);

  RETURN (CountVal);

END$function$
;
CREATE OR REPLACE FUNCTION note_has_noteovr(noteid numeric)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
  Result NUMBER;

BEGIN
  Result := 0;

  BEGIN
	  SELECT COUNT(1)
		INTO Result
		FROM NOTEOVR
	   WHERE "Type" = 0
	     AND "ParentId" = NoteId
	     AND "Deleted" = 0;
  EXCEPTION WHEN NO_DATA_FOUND THEN
  	Result := 0;
  END;


  IF Result = 0 THEN
  	RETURN 0;
  ELSE
  	RETURN 1;
  END IF;

END$function$
;
CREATE OR REPLACE FUNCTION patienthasbalance(patientid numeric, cutoffdate timestamp without time zone)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
  Result NUMBER;
  PtTotal NUMBER;
  InsTotal NUMBER;
  Deleted NUMBER; 						--AX-24131.x

BEGIN
  Result := 0;

  BEGIN
	  SELECT P."PtTotal", P."InsTotal"
		  INTO PtTotal, InsTotal
		  FROM PTBAL P
		  WHERE P."Patient" = PatientId
			AND P."Batch" =  (SELECT PB."Batch"
			FROM PTBALBAT PB
			WHERE PB."Mode" = 0
			AND PB."AsAtDate" >= CutOffDate
			ORDER BY PB."AsAtDate" DESC FETCH FIRST 1 ROWS ONLY);
	  EXCEPTION WHEN NO_DATA_FOUND THEN
		--AX-24131.x; AX-24131.y 	
    		Result := 0;
		RETURN Result;
          END;

  IF (PtTotal != 0 OR InsTotal != 0) THEN
	Result := 1;
  ELSE
	Result := 0;
  END IF;

  RETURN Result;
END$function$
;
CREATE OR REPLACE FUNCTION patientinactive(patientid numeric)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$ 

  days NUMBER;

  InactivePtCount NUMBER;



BEGIN

  days := -1;



  SELECT COUNT("StatusStartDate") into InactivePtCount FROM Patient P, Status S

    WHERE P."Patient"=PatientId and P."StatusStartDate" <= sysdate and

          P."Status" = S."Status" (+) and S."MakeInactive" = 1; -- B122050



  IF InactivePtCount > 0 THEN

    SELECT CALCULATEDAYSDIFF_S(sysdate,min("StatusStartDate")) into days FROM Patient P, Status S -- AX39652

      WHERE P."Patient"=PatientId and P."StatusStartDate" <= sysdate and

            P."Status" = S."Status" (+) and S."MakeInactive" = 1; -- B122050

  END IF;



  RETURN days;	

END$function$
;
CREATE OR REPLACE FUNCTION patientnotseen(patient numeric, provider character)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$ 

  days NUMBER;

  LastTxCount NUMBER;



BEGIN

  days := -1;



  SELECT COUNT("TreatmentDate") into LastTxCount FROM Trx

    WHERE "Patient"=Patient and "Type"=1 and "Producer" = Provider and

          "Deleted"=0 and "TreatmentDate" <= sysdate;



  IF LastTxCount > 0 THEN

    SELECT  CALCULATEDAYSDIFF_S(sysdate,max("TreatmentDate")) into days FROM Trx -- AX39652

      WHERE "Patient"=Patient and "Type"=1 and "Producer" = Provider and

            "Deleted"=0 and "TreatmentDate" <= sysdate;

  END IF;



  RETURN days;	

END$function$
;
CREATE OR REPLACE FUNCTION pocket4plus(patientval numeric)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$

  PocketSum   NUMBER;

  PtPerioVal  NUMBER;



  CURSOR C1 IS SELECT * FROM PERCOND WHERE "CondType" = 2 AND "Status" = 0;

BEGIN

  PocketSum := 0;



  FOR rec IN C1 LOOP

    PtPerioVal := LastPtPerCo(PatientVal, rec."PerCond");		-- E33252

    PocketSum := PocketSum + GetCountPerioDValGE(PtPerioVal, rec."PerCond", 4.0);

  END LOOP;



  RETURN (PocketSum);

END$function$
;
CREATE OR REPLACE FUNCTION recallnotseen(patient numeric)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$ 

  days NUMBER;

  RecallCount NUMBER;



BEGIN

  days := -1;



  SELECT COUNT("RecallDate") into RecallCount FROM Ptrecall R, Status S

    WHERE R."Patient"=Patient and R."RecallDate" < sysdate and R."Deleted" = 0 and

          R."Status" = S."Status" (+) and (S."MakeInactive" = 0 or S."MakeInactive" IS NULL) and -- B122050

          R."RecallDate" > (SELECT max("TreatmentDate") FROM Trx T 

          WHERE T."Patient"=Patient and T."Type"=1 and T."Deleted"=0 and

                T."TreatmentDate" <= sysdate);





  IF RecallCount > 0 THEN

    SELECT CALCULATEDAYSDIFF_S(sysdate,min("RecallDate")) into days FROM Ptrecall R, Status S -- AX39652

      WHERE R."Patient"=Patient and R."RecallDate" < sysdate and R."Deleted" = 0 and

            R."Status" = S."Status" (+) and (S."MakeInactive" = 0 or S."MakeInactive" IS NULL) and -- B122050

            R."RecallDate" > (SELECT max("TreatmentDate") FROM Trx T 

            WHERE T."Patient"=Patient and T."Type"=1 and T."Deleted"=0 and

                  T."TreatmentDate" <= sysdate);

  END IF;



  RETURN days;	

END$function$
;
CREATE OR REPLACE FUNCTION regexpreplace_s(p_input character varying, p_pattern character varying, p_replace character varying)
 RETURNS character varying
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
BEGIN
    RETURN REGEXP_REPLACE(p_input, p_pattern, p_replace);
END$function$
;
CREATE OR REPLACE FUNCTION regexpreplace_s(p_input text, p_pattern text, p_replace text)
 RETURNS text
 LANGUAGE plpgsql
AS $function$

BEGIN

	RETURN regexp_replace(p_input, p_pattern, p_replace, 'g');

END

$function$
;
CREATE OR REPLACE FUNCTION returnbatchid_p(pbatch numeric)
 RETURNS TABLE("Batch" numeric)
 LANGUAGE edbspl
AS $function$

DECLARE vStep integer := 0;

begin 

	-- update processing end date/time

	--

	vStep := 10;

	update ar_recon_saved_data_hdr

	set "EndDateTime" = sysdate

	where 1 = 1

		and "Batch" = pBatch;

	vStep := 20;



	--

	-- create new savepoint

	--

	begin --

		-- clear temporary tables 1, 2 and 3

		--

		vStep := 30;

		execute immediate 'truncate table global_temp_alloc1';

		execute immediate 'truncate table global_temp_alloc2';

		execute immediate 'truncate table global_temp_alloc3';

		--

		-- open cursor

		--

		vStep := 40;

		return query

		select pBatch "Batch"

		from dual

		where 1 = 1;

	exception

		when others then

		--

		-- rollback to last savepoint then log error

		--

		ax_pkg.LogEvent_P((trim('ALLOC_PKG') || '.ReturnBatchID_P'), (trim(sqlerrm) || ' (Error at step ' || vStep || ')')); -- AX-39259

	end;

exception

when others then --    vStep := 50;

ax_pkg.LogEvent_P((trim('ALLOC_PKG') || '.ReturnBatchID_P'), (trim(sqlerrm) || ' (Error at step ' || vStep || ')')); -- AX-39259

end ReturnBatchID_P;

$function$
;
CREATE OR REPLACE FUNCTION round(input_interval interval)
 RETURNS numeric
 LANGUAGE plpgsql
 IMMUTABLE STRICT
AS $function$

BEGIN

    RETURN ROUND(EXTRACT(EPOCH FROM input_interval) / 86400.0);

END;

$function$
;
CREATE OR REPLACE FUNCTION save_patient_ptletter_p(ppatientid numeric, pdatefrom timestamp without time zone, pdateto timestamp without time zone, pshowdeleted numeric)
 RETURNS TABLE("FileName" character varying)
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$

  -- Mar 3, 2016  PQ  This procedure will export all non-image attachments from PTLETTER.

  --                  It was created for the purpose of exporting part of a patients record.

  --                  For this to work properly, you must first create an Oracle directory.

  --

  --                  Example: CREATE DIRECTORY CHRTEXP AS '\\ss-oracle\qaora12';

  --

  --                  You must then grant proper permissions to the DB User accessing that directory

  --

  --                  Example: GRANT READ, WRITE ON DIRECTORY CHRTEXP TO AXIUM;

  --

  --                  Required by Patient_Chart_Export_V2_SQL.rpt

  --

  -- Parameters:

  --   pRefCursor     Outbound parameter to determine if the procedure is successful or

  --                  if it failed (returns a result set that Crystal Report can use)

  --   pPatientId     The Patient Id that this procedure should run for

  --

  --  Requires AX_PKG for logging



  vFile           UTL_FILE.FILE_TYPE;



  vBuffer         RAW(32767);

  vReadSize       BINARY_INTEGER := 32767;

  vPosition       INTEGER        := 1;

  vBlob           BLOB;

  vBlobLength     INTEGER;

  vFileName       VARCHAR2(250);

  vSQLStmt        VARCHAR2(4000);



  -- Set your Oracle Directory name here

  vDirectory      VARCHAR2(128) := 'CHRTEXP';

  vDirectoryPath  VARCHAR2(512);



  vDateType       PRACTICE."DateType"%TYPE;

  vDateFormat     CHAR(10);



  vStep NUMBER := 0;



  -- Grab all attachments



  CURSOR Attachments

  IS

    SELECT PT."PtLetter"

    FROM PTLETTER PT

    WHERE 1            = 1

    AND PT."Patient"   = pPatientId

    AND PT."Date"     >= pDateFrom

    AND PT."Date"     <= pDateTo

    AND PT."Deleted"  IN (0, pShowDeleted)

    AND PT."Type"     <> 0;



  -- Grab all consents



  CURSOR Consents

  IS

    SELECT C."Contract"

    FROM CONTRACT C

    WHERE 1          = 1

    AND C."Patient"  = pPatientId

    AND C."Date"    >= pDateFrom

    AND C."Date"    <= pDateTo

    AND C."Deleted" IN (0, pShowDeleted);



  -- Grab all EHR Form attachments



  CURSOR EHRForms

  IS

    SELECT P."PItemImg"

    FROM PITEM P,

      PITEMIMG PI

    WHERE 1            = 1

    AND P."PItemImg"   = PI."PItemImg"

    AND P."Patient"    = pPatientId

    AND P."Date"      >= pDateFrom

    AND P."Date"      <= pDateTo

    AND P."Status"    IN (0, pShowDeleted)

    AND P."PItemImg"  <> 0

    AND P."AnsType"    = 8;



BEGIN



  -- Grab the date format to use

  vStep := 102;

  SELECT NVL(MIN("DateType"), 1) INTO vDateType FROM PRACTICE WHERE ROWNUM = 1;



  -- Apply proper format

  vStep := 103;

  IF (vDateType = 0) THEN

    vDateFormat := 'DD-MM-YYYY';

  ELSE

    vDateFormat := 'MM-DD-YYYY';

  END IF;



  -- Go through each attachment and output to oracle directory

  vStep := 103;

  FOR A IN Attachments LOOP



    -- Reset our variables

    vPosition := 1;

    vReadSize := 32767;



    -- Get BLOB files

    vStep := 104;

    SELECT PT.CONTENT,

      NVL(TRIM(P."Chart"), PT."Patient")

      || '_'

      || TRIM(TO_CHAR(PT."Date", vDateFormat)

      || '_'

      || REPLACE(PT."Description"

      || '_'

      || PT."PtLetter"

      || ''

      || NVL2(PT."ExpiryDate", ' (Expired ' || TO_CHAR(PT."ExpiryDate", vDateFormat) || ')', '')

      || '.'

      || LOWER(PT."FileExt"), LOWER(PT."FileExt")

      || '.'

      || LOWER(PT."FileExt"), LOWER(PT."FileExt"))) "FileName"

    INTO vBlob,

      vFileName

    FROM PTLETTER PT,

      PATIENT P

    WHERE 1           = 1

    AND PT."Patient"  = P."Patient"

    AND PT."PtLetter" = A."PtLetter";



    --remove illegal characters

    vFileName := translate(vFileName,'^*/\?:"<>|', '_');



    -- Check the BLOBG length

    vStep := 105;

    vBlobLength := DBMS_LOB.getlength(vBlob);



    -- Open the destination file.

    vStep := 106;

    vFile := UTL_FILE.FOPEN(vDirectory, vFileName, 'wb', 32767);



    -- Read chunks of the BLOB and write them to the file until complete.

    vStep := 107;

    WHILE vPosition < vBlobLength LOOP

      DBMS_LOB.READ(vBlob, vReadSize, vPosition, vBuffer);

      UTL_FILE.PUT_RAW(vFile, vBuffer, TRUE);



      vPosition := vPosition + vReadSize;

    END LOOP;



    -- Close the file.

    vStep := 108;

    UTL_FILE.FCLOSE(vFile);



  END LOOP;



  -- Go through each contract and output to oracle directory

  FOR C IN Consents LOOP



    -- Reset our variables

    vPosition := 1;

    vReadSize := 32767;



    vStep := 109;

    SELECT CT.CONTENT,

      NVL(TRIM(P."Chart"), CT."Patient")

      || '_'

      || TRIM(TO_CHAR(CT."Date", vDateFormat)

      || '_'

      || REPLACE(CT."Description"

      || '_'

      || CT."Contract"

      || ''

      || NVL2(CT."ExpiryDate", ' (Expires ' || TO_CHAR(CT."ExpiryDate", vDateFormat) || ')', '')

      || ''

      || DECODE(CT."Denied", 0, '', ' (Denied)')

      || '.'

      || LOWER(CT."FileExt"), LOWER(CT."FileExt")

      || '.'

      || LOWER(CT."FileExt"), LOWER(CT."FileExt"))) "FileName"

    INTO vBlob,

      vFileName

    FROM CONTRACT CT,

      PATIENT P

    WHERE 1           = 1

    AND CT."Patient"  = P."Patient"

    AND CT."Contract" = C."Contract";



    --remove illegal characters

    vFileName := translate(vFileName,'^*/\?:"<>|', '_');



    -- Check the BLOBG length

    vStep := 110;

    vBlobLength := DBMS_LOB.getlength(vBlob);



    -- Open the destination file.



    vStep := 111;

    vFile := UTL_FILE.FOPEN(vDirectory, vFileName, 'wb', 32767);



    -- Read chunks of the BLOB and write them to the file until complete.

    vStep := 112;

    WHILE vPosition < vBlobLength LOOP

      DBMS_LOB.READ(vBlob, vReadSize, vPosition, vBuffer);

      UTL_FILE.PUT_RAW(vFile, vBuffer, TRUE);



      vPosition := vPosition + vReadSize;

    END LOOP;



    -- Close the file.

    vStep := 113;

    UTL_FILE.FCLOSE(vFile);



  END LOOP;



  -- Go through each EHR Form question attachment and output to oracle directory

  vStep := 114;

  FOR E IN EHRForms LOOP



    -- Reset our variables

    vPosition := 1;

    vReadSize := 32767;



    vStep := 115;

    SELECT PI.IMAGE,

      NVL(TRIM(PT."Chart"), PT."Patient")

      || '_'

      || TRIM(TO_CHAR(P."Date", vDateFormat)

      || '_'

      || 'EHRForm_' || TRIM(FI."FormCode")

      || '_PITEM_'

      || P."PItem"

      || '.'

      || LOWER(PI."FileExt")) "FileName"

    INTO vBlob,

      vFileName

    FROM PITEM P,

      PITEMIMG PI,

      FITEM FI,

      PATIENT PT

    WHERE 1           = 1

    AND P."PItemImg"  = PI."PItemImg"

    AND P."FItem"     = FI."FItem"

    AND P."Patient"   = PT."Patient"

    AND P."PItemImg"  = E."PItemImg";



    --remove illegal characters

    vFileName := translate(vFileName,'^*/\?:"<>|', '_');



    -- Check the BLOBG length

    vStep := 116;

    vBlobLength := DBMS_LOB.getlength(vBlob);



    -- Open the destination file.

    vStep := 117;

    vFile := UTL_FILE.FOPEN(vDirectory, vFileName, 'wb', 32767);



    -- Read chunks of the BLOB and write them to the file until complete.

    vStep := 118;

    WHILE vPosition < vBlobLength LOOP

      DBMS_LOB.READ(vBlob, vReadSize, vPosition, vBuffer);

      UTL_FILE.PUT_RAW(vFile, vBuffer, TRUE);



      vPosition := vPosition + vReadSize;

    END LOOP;



    -- Close the file.

    vStep := 119;

    UTL_FILE.FCLOSE(vFile);



  END LOOP;



  -- Grab the directory path of the Oracle directory

  vStep := 120;

  SELECT DIRECTORY_PATH

  INTO vDirectoryPath

  FROM DBA_DIRECTORIES

  WHERE 1            = 1

  AND DIRECTORY_NAME = vDirectory;



  -- Build our output dataset which is location of each file

  vStep := 121;

  vSQLStmt := '

                SELECT $1

                  || ''\''

                  || NVL(TRIM(P."Chart"), PT."Patient")

                  || ''_''

                  || TRIM(TO_CHAR(PT."Date", $2)

                  || ''_''

                  || REPLACE(PT."Description"

                  || ''_''

                  || PT."PtLetter"

                  || ''''

                  || NVL2(PT."ExpiryDate", '' (Expires '' || TO_CHAR(PT."ExpiryDate", $3) || '')'', '''')

                  || ''.''

                  || LOWER(PT."FileExt"), LOWER(PT."FileExt")

                  || ''.''

                  || LOWER(PT."FileExt"), LOWER(PT."FileExt"))) "FileName"

                FROM PTLETTER PT,

                  PATIENT P

                WHERE 1           = 1

                AND PT."Patient"  = P."Patient"

                AND PT."Patient"  = $4

                AND PT."Date"    >= $5

                AND PT."Date"    <= $6

                AND PT."Deleted" IN (0, $7)

                AND PT."Type"    <> 0

                UNION ALL

                SELECT $8

                  || ''\''

                  || NVL(TRIM(P."Chart"), CT."Patient")

                  || ''_''

                  || TRIM(TO_CHAR(CT."Date", $9)

                  || ''_''

                  || REPLACE(CT."Description"

                  || ''_''

                  || CT."Contract"

                  || ''''

                  || NVL2(CT."ExpiryDate", '' (Expires '' || TO_CHAR(CT."ExpiryDate", $10) || '')'', '''')

                  || ''''

                  || DECODE(CT."Denied", 0, '''', '' (Denied)'')

                  || ''.''

                  || LOWER(CT."FileExt"), LOWER(CT."FileExt")

                  || ''.''

                  || LOWER(CT."FileExt"), LOWER(CT."FileExt"))) "FileName"

                FROM CONTRACT CT,

                  PATIENT P

                WHERE 1           = 1

                AND CT."Patient"  = P."Patient"

                AND CT."Patient"  = $11

                AND CT."Date"    >= $12

                AND CT."Date"    <= $13

                AND CT."Deleted" IN (0, $14)

                UNION ALL

                SELECT $15

                  || ''\''

                  || NVL(TRIM(PT."Chart"), PT."Patient")

                  || ''_''

                  || TRIM(TO_CHAR(P."Date", $16)

                  || ''_''

                  || ''EHRForm_'' || TRIM(FI."FormCode")

                  || ''_PITEM_''

                  || P."PItem"

                  || ''.''

                  || LOWER(PI."FileExt")) "FileName"

                FROM PITEM P,

                  PITEMIMG PI,

                  FITEM FI,

                  PATIENT PT

                WHERE 1           = 1

                AND P."PItemImg"  = PI."PItemImg"

                AND P."FItem"     = FI."FItem"

                AND P."Patient"   = PT."Patient"

                AND P."PItemImg" <> 0

                AND P."AnsType"   = 8

                AND P."Patient"   = $17

                AND P."Date"     >= $18

                AND P."Date"     <= $19

                AND P."Status"   IN (0, $20)

                ORDER BY 1

              ';



  -- Output the path that the files were saved to

  vStep := 122;

  RETURN QUERY EXECUTE vSQLStmt USING vDirectoryPath, vDateFormat, vDateFormat, pPatientId, pDateFrom, pDateTo, pShowDeleted, vDirectoryPath, vDateFormat, vDateFormat, pPatientId, pDateFrom, pDateTo, pShowDeleted, vDirectoryPath, vDateFormat, pPatientId, pDateFrom, pDateTo, pShowDeleted;



EXCEPTION

  WHEN OTHERS THEN



    --log the error

    ax_pkg.LogEvent_P(trim('$$PLSQL_UNIT'), trim(sqlerrm)||' (Error at step '||vStep||')');



    -- Close the file if something goes wrong.

    IF UTL_FILE.is_open(vFile) THEN

      UTL_FILE.fclose(vFile);

    END IF;



    RETURN QUERY

      SELECT 'Error'

      FROM DUAL;



END SAVE_PATIENT_PTLETTER_P

$function$
;
CREATE OR REPLACE FUNCTION selfconceptscore(lpatient numeric, formcode character varying, lpform numeric)
 RETURNS character varying
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
	szAnswer 	VARCHAR2(2000) := ' ';
	lScore		NUMBER := 0;
	lTotalScore	NUMBER := 0;
	szFormCode CHAR(6) := FormCode;
BEGIN

    IF lPatient = 0 OR lPForm = 0 OR nvl(length(szFormCode), 0) = 0 THEN
        RETURN 'Error';
    END IF;

    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC1'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore + lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC2'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore - lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC3'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore + lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC4'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore - lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC5'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore + lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC6'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore + lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC7'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore - lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC8'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore + lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC9'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore - lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC10'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore + lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC11'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore - lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC12'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore - lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC13'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore + lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC14'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore + lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC15'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore - lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC16'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore + lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC17'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore - lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC18'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore + lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC19'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore - lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC20'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore - lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC21'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore + lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC22'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore - lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC23'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore + lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC24'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore - lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC25'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore + lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC26'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore - lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC27'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore + lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC28'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore - lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC29'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore + lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC30'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore - lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC31'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore + lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC32'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore - lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC33'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore + lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC34'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore - lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC35'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore - lScore;

    	
    BEGIN
		SELECT DECODE(TRIM(P."AnsListDesc"), 'Always', 4,
				'Mostly', 3, 'Sometimes', 2, 'Never', 1, 0)
			INTO lScore
			FROM PITEM P, FITEM F
			WHERE P."Patient" = lPatient
			AND P."FormCode" = szFormCode
			AND P."PForm" = lPForm
			AND P."Status" = 0
			AND P."FItem" = F."FItem"
			AND F."Code" = 'SC36'
			AND F."Deleted" = 0;
		EXCEPTION WHEN NO_DATA_FOUND THEN
			lScore := 0;
	END;

	lTotalScore := lTotalScore + lScore;

    	
	szAnswer := TO_CHAR(lTotalScore);
  	RETURN NVL(szAnswer, 'Error');
END$function$
;
CREATE OR REPLACE FUNCTION startcheckedtx(appointment numeric, ltype numeric, id numeric, treatment numeric, procedur character)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
  lCount NUMBER := 0;

BEGIN
  SELECT Count(1) INTO lCount
  FROM STARTTRX T, STARTCHK S
   WHERE T."Type"=lType AND T."Id"=Id AND T."Treatment"=Treatment AND
   T."Procedure"=Procedur AND T."StartChk"=S."StartChk" AND S."Appointment"=Appointment;

   IF lCount IS NULL THEN
    lCount := 0;
   END IF;

   RETURN lCount;
END$function$
;
CREATE OR REPLACE FUNCTION startcheckrevokedtx(appointment numeric, ltype numeric, id numeric, treatment numeric, procedur character)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
  lCount NUMBER := 0;

BEGIN
  SELECT Count(1) INTO lCount
  FROM APPTRX T
   WHERE T."Appointment"=Appointment AND
   T."Type"=lType AND T."Id"=Id AND T."Treatment"=Treatment AND
   T."Procedure"=Procedur;

   IF lCount IS NULL OR lCount = 0 THEN
    	lCount := 1;
   ELSE
        lCount := 0;
   END IF;

   RETURN lCount;

END$function$
;
CREATE OR REPLACE FUNCTION suppcount(patientval numeric)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$

  CountVal    NUMBER;

  PtPerioVal  NUMBER;



  CURSOR C1 IS SELECT * FROM PERCOND WHERE "CondType" = 5 AND "Status" = 0;

BEGIN

  CountVal := 0;



  FOR rec IN C1 LOOP

    PtPerioVal := LastPtPerCo(PatientVal, rec."PerCond");		-- E33252

    CountVal := CountVal + GetCountPerioDValNE(PtPerioVal, rec."PerCond", 0.0);

  END LOOP;



  RETURN (CountVal);

END$function$
;
CREATE OR REPLACE FUNCTION to_datetime(dateonly timestamp without time zone, minutesfrommidnight numeric)
 RETURNS timestamp without time zone
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
begin
  return TRUNC(DateOnly) + MinutesFromMidnight/(60*24);
end$function$
;
CREATE OR REPLACE FUNCTION treatme2_has_form(txid numeric)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
  Result NUMBER;

BEGIN
  Result := 0;

  BEGIN
      -- B58930 - changed to lookup if a form exists on file
      -- instead of looking up if there is a form note to show
	  SELECT COUNT(1)
		INTO Result
		FROM PFORM
	   WHERE "OwnerType" = 4
	     AND "OwnerId" = TxId;
  EXCEPTION WHEN NO_DATA_FOUND THEN
  	Result := 0;
  END;


  IF Result = 0 THEN
  	RETURN 0;
  ELSE
  	RETURN 1;
  END IF;

END$function$
;
CREATE OR REPLACE FUNCTION treatme2_has_note(txid numeric, showdeleted numeric, showstrikeout numeric)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$
  Result NUMBER;

BEGIN
  Result := 0;

  BEGIN
	  SELECT COUNT(1)
		INTO Result
		FROM NOTES2
	   WHERE "TxId" = TxId
       AND "Status" IN (0, DECODE(ShowDeleted, 0, 0, 1), DECODE(ShowStrikeout, 0, 0, 2));
  EXCEPTION WHEN NO_DATA_FOUND THEN
  	Result := 0;
  END;


  IF Result = 0 THEN
  	RETURN 0;
  ELSE
  	RETURN 1;
  END IF;

END$function$
;
CREATE OR REPLACE FUNCTION trx_estimate_proc(trxtype numeric, trxid numeric, trxtreatment numeric, bindingquote numeric, billmethod numeric, calculateowing numeric, provider character)
 RETURNS TABLE(":B1" numeric)
 LANGUAGE edbspl
AS $function$



  TRX_ESTIMATE NUMBER := 0.0;

BEGIN

  TRX_ESTIMATE := split_pkg.TRX_ESTIMATE(TrxType, TrxId, TrxTreatment, BindingQuote, BillMethod, CalculateOwing, Provider, 0);

  

  RETURN QUERY

   select TRX_ESTIMATE as ":B1" from dual;

END

$function$
;
CREATE OR REPLACE FUNCTION txplanold(patient numeric)
 RETURNS numeric
 LANGUAGE edbspl
 SECURITY DEFINER
AS $function$ 

  days NUMBER;

  PlannedTxCount NUMBER;



BEGIN

  days := -1;



  SELECT COUNT("TreatmentDate") into PlannedTxCount FROM Trx T, Status S

    WHERE T."Patient"=Patient and T."Type"=5 and T."AppUser" > 0 and

          T."Deleted"=0 and T."TreatmentDate" <= sysdate and

          T."TxStatus" = S."Status" (+) and (S."MakeInactive" = 0 or S."MakeInactive" IS NULL); -- B122050



  IF PlannedTxCount > 0 THEN

    SELECT  CALCULATEDAYSDIFF_S(sysdate,min("TreatmentDate")) into days FROM Trx T, Status S -- AX39652

      WHERE T."Patient"=Patient and T."Type"=5 and T."AppUser" > 0 and

            T."Deleted"=0 and T."TreatmentDate" <= sysdate and

            T."TxStatus" = S."Status" (+) and (S."MakeInactive" = 0 or S."MakeInactive" IS NULL); -- B122050

  END IF;



  RETURN days;	

END$function$
;
CREATE OR REPLACE FUNCTION unallocatedadjustments(asatdate timestamp without time zone)
 RETURNS TABLE(treatmentdate timestamp without time zone, code character, total numeric, description character varying, payed numeric, modifieddate timestamp without time zone, chart character, "Last" character, middle character, prefered character)
 LANGUAGE edbspl
AS $function$



  SQLStmt  VARCHAR2(4000);

BEGIN

  -- E00691 added trunc on ModifiedDate

  -- B74933 added HISTORY_AR hint

  -- B74933.2 fixed hint

  SQLStmt := 'SELECT H."TreatmentDate", H."Code", H."Total", H."Description", H."Payed", H."ModifiedDate",

      P."Chart", P."Last", P."Middle", P."Prefered"

	  FROM HISTORY H, PATIENT P WHERE P."Patient" = H."Patient" AND H."Type"=6 AND H."Family"!=0

      AND H."TreatmentDate"<=$1 AND H."Deleted"=0 AND H."Payed"<>0 AND

      H."History"=(SELECT /*+index(H2 HISTORY_AR)*/ max(H2."History") FROM HISTORY H2 WHERE H2."OrigRecNo"=H."OrigRecNo"

      AND H2."Type" = H."Type" AND trunc(H2."ModifiedDate")<=$2)';



   RETURN QUERY EXECUTE

   SQLStmt using AsAtDate, AsAtDate;

END

$function$
;
CREATE OR REPLACE FUNCTION unallocatedinspayments(asatdate timestamp without time zone)
 RETURNS TABLE(date timestamp without time zone, treamentdate timestamp without time zone, code character, total numeric, description character varying, inspayed numeric, insadj numeric, modifieddate timestamp without time zone, company character, name character)
 LANGUAGE edbspl
AS $function$



  SQLStmt  VARCHAR2(4000);

BEGIN

  -- E00691 added trunc on ModifiedDate

  -- B74933 added HISTORY_AR hint

  -- B74933.2 fixed hint

  -- B76933 changed so that it includes over applied/adjusted payments

  SQLStmt := 'SELECT H."Date", H."TreatmentDate", H."Code", H."Total", H."Description", 

	  H."InsPayed", H."InsAdj", H."ModifiedDate", I."Company", I."Name"

      FROM HISTORY H, INSURANC I WHERE I."Company"(+) = H."Company1" AND H."Type"=4 

      AND H."TreatmentDate"<=$1 AND H."Deleted"=0 AND H."InsPayed"+H."InsAdj"<>0 AND

      H."History"=(SELECT /*+index(H2 HISTORY_AR)*/ max(H2."History") FROM HISTORY H2 WHERE H2."OrigRecNo"=H."OrigRecNo"

      AND H2."Type" = H."Type" AND trunc(H2."ModifiedDate")<=$2)';



  RETURN QUERY EXECUTE

  SQLStmt using AsAtDate, AsAtDate;

END

$function$
;
CREATE OR REPLACE FUNCTION unallocatedpayments(asatdate timestamp without time zone)
 RETURNS TABLE(treatmentdate timestamp without time zone, code character, total numeric, description character varying, payed numeric, ptadj numeric, modifieddate timestamp without time zone, chart character, "Last" character, "Middle" character, "Prefered" character)
 LANGUAGE edbspl
AS $function$

  SQLStmt  VARCHAR2(4000);

BEGIN

  -- E00691 added trunc on ModifiedDate

  -- B35739 handle over applied/allocated payments, changed Payed+PtAdj>0 to Payed+PtAdj!=0

  -- B74933 added HISTORY_AR hint

  -- B74933.2 fixed hint

  SQLStmt := 'SELECT H."TreatmentDate", H."Code", H."Total", H."Description", 

	  H."Payed", H."PtAdj", H."ModifiedDate", P."Chart", P."Last", P."Middle", P."Prefered"

      FROM HISTORY H, PATIENT P WHERE P."Patient" = H."Patient" AND H."Type"=3 AND H."Family"!=0

      AND H."TreatmentDate"<=$1 AND H."Deleted"=0 AND H."Payed"+H."PtAdj"!=0 AND

      H."History"=(SELECT /*+index(H2 HISTORY_AR)*/ max(H2."History") FROM HISTORY H2 WHERE H2."OrigRecNo"=H."OrigRecNo"

      AND H2."Type" = H."Type" AND trunc(H2."ModifiedDate")<=$2)';



  RETURN QUERY EXECUTE 

  SQLStmt using AsAtDate, AsAtDate;

END

$function$
;
 
-- PROCEDURES 
CREATE OR REPLACE PROCEDURE appoint_estimate_proc(INOUT appoint_estimate_cursor split_pkg.estimate_type, IN appointment numeric, IN bindingquote numeric, IN billmethod numeric, IN calculateowing numeric)
 SECURITY DEFINER
AS $procedure$

  APPOINT_ESTIMATE NUMBER := 0.0;

BEGIN

  APPOINT_ESTIMATE := split_pkg.APPOINT_ESTIMATE(Appointment, BindingQuote, BillMethod, CalculateOwing, 0);

  

  open APPOINT_ESTIMATE_Cursor for

   select APPOINT_ESTIMATE from dual;

END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE copytxplan(IN oldtxplanid numeric, IN newtxplanid numeric, IN auditid numeric)
 SECURITY DEFINER
AS $procedure$
  SessionID		NUMBER;
  NewAuditId	NUMBER (10);
  Error			NUMBER;													-- B142485
BEGIN
  Error := 0;																-- B142485
  SELECT COPYTXPLAN_SEQ.NEXTVAL INTO SessionID FROM DUAL;	-- B76990

  -- populate MAPTXPLAN with map Ids we will need
  BEGIN
	  INSERT INTO MAPTXPLAN SELECT 'TXPDX', SessionID, "TxPDx", TXPDX_TxPDx_SEQ.nextval
		 FROM TXPDX WHERE "TxPlan" = OldTxPlanId;							-- AX-11038.13237		
  EXCEPTION																	-- B142485
	  WHEN NO_DATA_FOUND THEN
		 Error := 1;														
  END;

  INSERT INTO MAPTXPLAN VALUES ('TXPDX', SessionID, 0, 0);

  -- every TxPlan has at least 1 TxPOpt so no need to check for NO_DATA_FOUND exception
  INSERT INTO MAPTXPLAN SELECT 'TXPOPT', SessionID, "TxPOpt", TXPOPT_TxPOpt_SEQ.nextval						-- E130137.3
    FROM TXPOPT WHERE "TxPlan" = OldTxPlanId;								--	 AX-11038.13237			

  BEGIN
	  INSERT INTO MAPTXPLAN SELECT 'TXPTX', SessionID, "TxPTx", TXPTX_TxPTx_SEQ.nextval						-- E130137.3
		 FROM TXPTX WHERE "TxPlan" = OldTxPlanId;							--  AX-11038.13237		
  EXCEPTION																	-- B142485
	  WHEN NO_DATA_FOUND THEN
		 Error := 1;														
  END;

	-- Copy TxPPrb																										-- E130137.3
	BEGIN
		INSERT INTO TXPPRB SELECT
		  NewTxPlanId,
		  P."PtPrb",
		  P."Deleted",
		  AuditId																												
		FROM TXPPRB P WHERE P."TxPlan" = OldTxPlanId;							-- AX-11038.13237
   EXCEPTION																	-- B142485
	  WHEN NO_DATA_FOUND THEN
		 Error := 1;														
   END;

	-- Copy PtObj
	--  first create new Audit entry
	SELECT AUDITHIS_AUDIT_SEQ.nextval INTO NewAuditId FROM dual;
	INSERT INTO AUDITHIS SELECT
	  NewAuditId,
	  A."Date",
	  A."Time",
	  A."User",
	  A."StationId",
	  'PTOBJ',
	  A."HistoryType"
	 FROM AUDITHIS A WHERE A."Audit" = AuditId;
	
	BEGIN
		INSERT INTO PTOBJ SELECT
		  PTOBJ_PTOBJ_SEQ.nextval,
		  O."Patient",
		  O."Description",
		  O."Status",
		  NewTxPlanId,
		  O."Deleted",
		  NewAuditId
		FROM PTOBJ O WHERE O."TxPlan" = OldTxPlanId;							-- AX-11038.13237
   EXCEPTION																	-- B142485
	  WHEN NO_DATA_FOUND THEN
		 Error := 1;														
   END;

	-- Copy TxPDx																										-- E130137.3
	BEGIN
		INSERT INTO TXPDX SELECT
		  (SELECT M."New" FROM MAPTXPLAN M WHERE M."TableName" = 'TXPDX' AND M."Session" = SessionID AND M."Old" = O."TxPDx"),
		  NewTxPlanId,
  		  O."DiagCode",
		  O."Description",
		  O."ShortDesc",
		  O."Note",
		  O."Order",	
		  O."Deleted",
		  AuditId																												
		FROM TXPDX O WHERE O."TxPlan" = OldTxPlanId;							-- AX-11038.13237
   EXCEPTION																	-- B142485
	  WHEN NO_DATA_FOUND THEN
		 Error := 1;														
   END;

	-- Copy PtPrbDx																										-- E130137.3
	BEGIN
		INSERT INTO PTPRBDX SELECT
		  O."PtPrb",
		  (SELECT M."New" FROM MAPTXPLAN M WHERE M."TableName" = 'TXPDX' AND M."Session" = SessionID AND M."Old" = O."TxPDx"),
		  O."Deleted",
		  AuditId																												
		FROM PTPRBDX O WHERE O."TxPDx" IN (SELECT D."TxPDx" FROM TXPDX D WHERE D."TxPlan" = OldTxPlanId) ;			-- AX-11038.13237
   EXCEPTION																	-- B142485
	  WHEN NO_DATA_FOUND THEN
		 Error := 1;														
   END;

	-- Copy TxPOpt
	INSERT INTO TXPOPT SELECT
		(SELECT M."New" FROM MAPTXPLAN M WHERE M."TableName" = 'TXPOPT' AND M."Session" = SessionID AND M."Old" = O."TxPOpt"),
		NewTxPlanId,
		O."Description",
		0,					-- NeedsConsultantAppr
		0,					-- InstructorApproved
		O."Total",
		O."InsTotal",
		0,					-- AppUser
		NULL,				-- AppDateTime
		0,					-- AppNA
		O."Deleted",
		AuditId
	FROM (SELECT * FROM TXPOPT WHERE "TxPlan" = OldTxPlanId ORDER BY "TxPOpt") O;	-- B13435; AX-11038.13237
	
	-- Copy TxPTx
	BEGIN
		INSERT INTO TXPTX SELECT
			(SELECT M."New" FROM MAPTXPLAN M WHERE M."TableName" = 'TXPTX' AND M."Session" = SessionID AND M."Old" = O."TxPTx"),
			(SELECT M."New" FROM MAPTXPLAN M WHERE M."TableName" = 'TXPOPT' AND M."Session" = SessionID AND M."Old" = O."TxPOpt"),
			NewTxPlanId,
			O."TxPTxType",
			O."Text",
			O."TxPTxDateTime",
			O."Order",
			O."Provider",
			O."Code",
			O."Description",
			O."MacroSeq",
			O."Site",
			O."Site2",
			O."Surface",
			O."Phase",
			O."Sequence",
			'P',					-- Status
			O."Total",
			O."InsTotal",
			O."HeldTotal",
			O."ClaimDoctor",
			O."Discipline",
			O."Unit",
			O."Custom1",
			O."Custom2",
			0,						-- PtAccepted
			NULL,					-- PtAcceptDateTime
			0,						-- Treatme2Id"
			O."Deleted",
			AuditId
		FROM TXPTX O WHERE O."TxPlan" = OldTxPlanId AND O."Deleted" = 0;							-- AX-11038.13237, AX-22374
   EXCEPTION																	-- B142485
	  WHEN NO_DATA_FOUND THEN
		 Error := 1;														
   END;

	-- Copy TxPDxTx																										-- E130137.3
	BEGIN
		INSERT INTO TXPDXTX SELECT
		  (SELECT M."New" FROM MAPTXPLAN M WHERE M."TableName" = 'TXPDX' AND M."Session" = SessionID AND M."Old" = O."TxPDx"),
		  (SELECT M."New" FROM MAPTXPLAN M WHERE M."TableName" = 'TXPTX' AND M."Session" = SessionID AND M."Old" = O."TxPTx"),
		  O."Deleted",
		  AuditId																												
		FROM TXPDXTX O WHERE O."TxPTx" IN (SELECT T."TxPTx" FROM TXPTX T WHERE T."TxPlan" = OldTxPlanId);		-- AX-11038.13237
   EXCEPTION																	-- B142485
	  WHEN NO_DATA_FOUND THEN
		 Error := 1;														
   END;

	-- Copy TxPNote
	--  first create new Audit entry
	SELECT AUDITHIS_AUDIT_SEQ.nextval INTO NewAuditId FROM dual;
	INSERT INTO AUDITHIS SELECT
	  NewAuditId,
	  A."Date",
	  A."Time",
	  A."User",
	  A."StationId",
	  'TXPNOTE',
	  A."HistoryType"
	 FROM AUDITHIS A WHERE A."Audit" = AuditId;

	BEGIN
		INSERT INTO TXPNOTE SELECT
		  TXPNOTE_TXPNOTE_SEQ.nextval,
		  O."Patient",
		  NewTxPlanId,
		  O."Date",
		  O."Code",
		  O."Text",
		  O."Deleted",
		  NewAuditId
		FROM TXPNOTE O WHERE O."TxPlan" = OldTxPlanId;							-- AX-11038.13237	
   EXCEPTION																	-- B142485
	  WHEN NO_DATA_FOUND THEN
		 Error := 1;														
   END;
		
  -- delete temporary rows
  DELETE MAPTXPLAN  WHERE "Session" = SessionID;		

END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE core10_details(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vColVal         NUMBER(10) := -1;
        vReportingYear  VARCHAR2(100) := '';
        vSQLStmt        VARCHAR2(2500) := '';
        vRefCode        VARCHAR2(10) := 'MU_CORE10';

    BEGIN
        vReportingYear := TO_CHAR(vRStartDate, 'MM/DD/YYYY')
                          || ' - ' ||
                          TO_CHAR(vREndDate, 'MM/DD/YYYY') ;

        BEGIN
              SELECT pi1."PItemCol" INTO vColVal
              FROM PITEM pi1, PFORM p1
              WHERE 1=1
              AND pi1."PForm" = p1."PForm"
              AND pi1."FItem" IN (
                                SELECT f1."FItem"
                                FROM FITEM f1
                                WHERE 1=1
                                AND f1."Code" = 'MU_RP'
                                AND f1."Deleted" = 0)
              AND pi1."AnsText" <> TRIM('+')
              AND pi1."Status" = 0
              AND pi1."AppDate" IS NOT NULL
              AND p1."OwnerId" = pUser
              AND TRIM(pi1."AnsText") = TRIM(vReportingYear);

            EXCEPTION WHEN NO_DATA_FOUND THEN
            vColVal := -1;
          END;

          vSQLStmt := '
                      SELECT  pi2."AnsYes", pi2."Date", u1."Name", u1."First", pi2."FormCode"
                      FROM PITEM pi2, PFORM p2, USERS u1
                      WHERE 1=1
                      AND pi2."FItem" = (
                                        SELECT f1."FItem"
                                        FROM FITEM f1
                                        WHERE 1=1
                                        AND TRIM(f1."Code") = '''||vRefCode||'''
                                        AND f1."Deleted" = 0)
                      AND pi2."Status" = 0
                      AND pi2."Patient" = 0
                      AND pi2."AppDate" IS NOT NULL
                      AND p2."OwnerId" = '||pUser||'
                      AND pi2."PForm" = p2."PForm"
                      AND pi2."PItemCol"= :1
                      AND pi2."User" = u1."User"
                    ';
        OPEN MUWeakCursor FOR vSQLStmt USING vColVal;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE core11_details(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vColVal         NUMBER(10) := -1;
        vReportingYear  VARCHAR2(100) := '';
        vSQLStmt        VARCHAR2(2500) := '';
        vRefCode        VARCHAR2(10) := 'MU_CORE11';

    BEGIN
        vReportingYear := TO_CHAR(vRStartDate, 'MM/DD/YYYY')
                          || ' - ' ||
                          TO_CHAR(vREndDate, 'MM/DD/YYYY') ;

        BEGIN
              SELECT pi1."PItemCol" INTO vColVal
              FROM PITEM pi1, PFORM p1
              WHERE 1=1
              AND pi1."PForm" = p1."PForm"
              AND pi1."FItem" IN (
                                SELECT f1."FItem"
                                FROM FITEM f1
                                WHERE 1=1
                                AND f1."Code" = 'MU_RP'
                                AND f1."Deleted" = 0)
              AND pi1."AnsText" <> TRIM('+')
              AND pi1."Status" = 0
              AND pi1."AppDate" IS NOT NULL
              AND p1."OwnerId" = pUser
              AND TRIM(pi1."AnsText") = TRIM(vReportingYear);

            EXCEPTION WHEN NO_DATA_FOUND THEN
            vColVal := -1;
          END;

          vSQLStmt := '
                      SELECT  pi2."AnsYes", pi2."Date", u1."Name", u1."First", pi2."FormCode"
                      FROM PITEM pi2, PFORM p2, USERS u1
                      WHERE 1=1
                      AND pi2."FItem" = (
                                        SELECT f1."FItem"
                                        FROM FITEM f1
                                        WHERE 1=1
                                        AND TRIM(f1."Code") = '''||vRefCode||'''
                                        AND f1."Deleted" = 0)
                      AND pi2."Status" = 0
                      AND pi2."Patient" = 0
                      AND pi2."AppDate" IS NOT NULL
                      AND p2."OwnerId" = '||pUser||'
                      AND pi2."PForm" = p2."PForm"
                      AND pi2."PItemCol"= :1
                      AND pi2."User" = u1."User"
                    ';
        OPEN MUWeakCursor FOR vSQLStmt USING vColVal;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE core12_details_d(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vProducer   CHAR(10 );
        vCalcEndDate  DATE;
        vSQLStmt    VARCHAR2(5000 );
        vProcCode  CHAR(10 ) := 'D0196';
        vProcStatusD  CHAR(1 ) := 'I';
        vProcStatusN  CHAR(1 ) := 'C';
    BEGIN

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        SELECT (TO_DATE(vREndDate) - (4 +  CASE WHEN (MU_CORE_PKG.COUNT_HDAYS(TO_DATE(vREndDate)-4, TO_DATE(vREndDate))) > 0 THEN 2 ELSE 0 END))
                INTO vCalcEndDate FROM DUAL;

        vSQLStmt := '
                      SELECT DISTINCT pt1."Patient", pt1."Last", pt1."First", pt1."Chart",
                        NVL((
                              SELECT DISTINCT 1
                              FROM TRX t2
                              WHERE 1=1
                              AND t2."Type" = 1
                              AND t2."Procedure" = '''||vProcCode||'''
                              AND t2."Status" = '''||vProcStatusN||'''
                              AND t2."Deleted" = 0
                              AND t2."Patient" = t1."Patient"
                              AND t2."Date" >= t1."Date"
                              AND t2."OrigRecNo" = t1."OrigRecNo"
                              AND ( CASE
                                    WHEN ((t1."Date" - t2."Date") BETWEEN -14 AND 0)
                                      THEN
                                        CASE
                                        WHEN ((t1."Date" -  t2."Date" + MU_CORE_PKG.COUNT_HDAYS(TO_DATE(t1."Date"), TO_DATE(t2."Date"))) BETWEEN -2 AND 0)
                                          THEN 1
                                          ELSE 0
                                        END
                                      ELSE 0
                                    END
                                  ) = 1
                              ),0) AS "Flag"
                      FROM TRX t1, PATIENT pt1
                      WHERE 1=1
                      AND t1."Patient" = pt1."Patient"
                      AND t1."Type" = 1
                      AND t1."Procedure" = '''||vProcCode||'''
                      AND t1."Status" = '''||vProcStatusD||'''
                      AND t1."Deleted" IN (0,2)
                      AND TRUNC(t1."Date") BETWEEN TRUNC(TO_DATE('''||vRStartDate||''')) AND TRUNC(TO_DATE(:1))
                      AND EXISTS (SELECT 1
                                  FROM PTPROD p1
                                  WHERE 1=1
                                  AND t1."Patient" = p1."Patient"
                                  AND p1."Producer" = '''||vProducer||'''
                                  AND p1."Deleted" = 0
                                  AND (
                                        (p1."StartDate" IS NULL OR p1."StartDate" <= t1."Date")
                                        AND
                                        (p1."EndDate" IS NULL OR p1."EndDate" >= t1."Date")
                                      )
                                  )
                    ';
        OPEN MUWeakCursor FOR vSQLStmt USING TRUNC(vCalcEndDate);
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE core13_details_d(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vProducer   CHAR(10 );
        vSQLStmt    VARCHAR2(2500 );
        vCheckList  VARCHAR2(150 ) := '%CLINICAL VISIT SUMMARY%';
    BEGIN

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                      SELECT a1."Appointment", a1."Date", a1."From", a1."Clinic", p1."Last", p1."First", p1."Chart",
                        NVL(( SELECT DISTINCT 1
                              FROM v_PTLETTER_MU pt1
                              WHERE 1=1
                              AND pt1."Patient" = a1."Patient"
                              AND pt1."Deleted" = 0
                              AND (UPPER(pt1."Description") LIKE '''||vCheckList||''')
                              AND TRUNC(pt1."Date")  BETWEEN TRUNC(TO_DATE(a1."Date")) AND TRUNC(TO_DATE('''||vREndDate||'''))
                              AND ( CASE WHEN (TRUNC(a1."Date") - TRUNC(pt1."Date") BETWEEN -14 AND 0)
                                    THEN
                                      CASE WHEN (TRUNC(TO_DATE(a1."Date")) - TRUNC(TO_DATE(pt1."Date")) + MU_CORE_PKG.COUNT_HDAYS(TO_DATE(a1."Date"), TO_DATE(pt1."Date")) BETWEEN -2 AND 0)
                                        THEN 1
                                        ELSE 0
                                      END
                                    ELSE 0
                                    END) = 1),0) as "Flag"
                      FROM APPOINT a1, PATIENT p1
                      WHERE 1=1
                      AND a1."Patient" = p1."Patient"
                      AND a1."Type" IN (0,1,2)
                      AND TRIM(a1."Producer") = TRIM(:1)
                      AND a1."Status" = 0
                      AND TRUNC(a1."Date") BETWEEN TRUNC(TO_DATE('''||vRStartDate||''')) AND TRUNC(TO_DATE('''||vREndDate||'''))
                    ';
        OPEN MUWeakCursor FOR vSQLStmt USING TRIM(vProducer);
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE core15_details(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vColVal         NUMBER(10) := -1;
        vReportingYear  VARCHAR2(100 ) := '';
        vSQLStmt        VARCHAR2(2500 ) := '';
        vRefCode        VARCHAR2(10 ) := 'MU_CORE15';

    BEGIN
        vReportingYear := TO_CHAR(vRStartDate, 'MM/DD/YYYY')
                          || ' - ' ||
                          TO_CHAR(vREndDate, 'MM/DD/YYYY') ;

        BEGIN
              SELECT pi1."PItemCol" INTO vColVal
              FROM PITEM pi1, PFORM p1
              WHERE 1=1
              AND pi1."PForm" = p1."PForm"
              AND pi1."FItem" IN (
                                SELECT f1."FItem"
                                FROM FITEM f1
                                WHERE 1=1
                                AND f1."Code" = 'MU_RP'
                                AND f1."Deleted" = 0)
              AND pi1."AnsText" <> TRIM('+')
              AND pi1."Status" = 0
              AND pi1."AppDate" IS NOT NULL
              AND p1."OwnerId" = pUser
              AND TRIM(pi1."AnsText") = TRIM(vReportingYear);

            EXCEPTION WHEN NO_DATA_FOUND THEN
            vColVal := -1;
          END;

          vSQLStmt := '
                        SELECT pi2."AnsYes", pi2."Date", u1."Name", u1."First", pi2."FormCode"
                        FROM PITEM pi2, PFORM p2, USERS u1
                        WHERE 1=1
                        AND pi2."PForm" = p2."PForm"
                        AND pi2."User" = u1."User"
                        AND pi2."FItem" = ( SELECT f2."FItem"
                                            FROM FITEM f2
                                            WHERE 1=1
                                            AND f2."Code" = TRIM('''||vRefCode||''')
                                            AND f2."Deleted" = 0)
                        AND pi2."Status" = 0
                        AND pi2."Patient" = 0
                        AND pi2."AppDate" IS NOT NULL
                        AND p2."OwnerId" = '||pUser||'
                        AND pi2."PItemCol"= :1
                    ';
        OPEN MUWeakCursor FOR vSQLStmt USING vColVal;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE core1_details_alt_d(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vProducer   CHAR(10 );
        vSQLStmt VARCHAR2(4000 );
    BEGIN

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                      SELECT DISTINCT
                        rx1."Patient",
                        p1."Last",
                        p1."First",
                        p1."Chart",
                        rx1."Prescription",
                        1 as "Flag"
                      FROM PRESCRIP rx1, PATIENT p1
                      WHERE 1=1
                      AND rx1."Patient" = p1."Patient"
                      AND rx1."PrescripType" IN (1,2)
                      AND rx1."Deleted" = 0
                      AND TRIM(rx1."Provider") = TRIM('''||vProducer||''')
                      AND TRUNC(rx1."Date") BETWEEN TRUNC(TO_DATE('''||vRStartDate||''')) AND TRUNC(TO_DATE('''||vREndDate||'''))
                    ';
				
        OPEN MUWeakCursor FOR vSQLStmt;

    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE core1_details_d(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vProducer   CHAR(10 );
        vSQLStmt VARCHAR2(4000 );
    BEGIN

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                      SELECT DISTINCT "Patient", "Last", "First", "Chart", MAX("Flag") "Flag"
                      FROM (
                        SELECT ap1."Patient", p1."Last", p1."First", p1."Chart",
                          NVL ((SELECT DISTINCT 1
                                FROM PRESCRIP rx1
                                WHERE 1=1
                                AND rx1."Patient" = ap1."Patient"
                                AND rx1."PrescripType" IN (1,2)
                                AND TRUNC(rx1."Date") <= TRUNC(TO_DATE('''||vREndDate||'''))
                                AND rx1."Deleted" = 0), 0
                                ) AS "Flag"
                        FROM APPOINT ap1, PATIENT p1
                        WHERE 1=1
                        AND ap1."Patient" = p1."Patient"
                        AND ap1."Type" IN (0,1,2)
                        AND TRIM(ap1."Producer") = TRIM('''||vProducer||''')
                        AND ap1."Status" = 0
                        AND TRUNC(ap1."Date") BETWEEN TRUNC(TO_DATE('''||vRStartDate||''')) AND TRUNC(TO_DATE('''||vREndDate||'''))
                        AND EXISTS (SELECT 1
                                    FROM PRESCRIP rx1
                                    WHERE 1=1
                                    AND rx1."Patient" = ap1."Patient"
                                    AND rx1."PrescripType" IN (0,1,2) --It is a medication order
                                    AND rx1."Deleted" = 0 --Only check to see if deleted
                                    AND TRUNC(rx1."Date") <= TRUNC(TO_DATE('''||vREndDate||''')) --Added before the end of the reporting period
                                    )
                        GROUP BY ap1."Patient", p1."Last", p1."First", p1."Chart"
                      )
                      GROUP BY "Patient", "Last", "First", "Chart"
                    ';

        OPEN MUWeakCursor FOR vSQLStmt;

    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE core1_details_n(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vProducer   CHAR(10);
        vSQLStmt VARCHAR2(2500);
    BEGIN

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                    SELECT p1."Patient", pt1."Last", pt1."First", pt1."Chart"
                    FROM APPOINT p1, PATIENT pt1
                    WHERE 1=1
                    AND p1."Patient" = pt1."Patient"
                    AND p1."Type" IN (0,1,2)
                    AND TRIM(p1."Producer") = TRIM('''||vProducer||''')
                    AND TRUNC(p1."Date") BETWEEN TRUNC(TO_DATE('''||vRStartDate||''')) AND TRUNC(TO_DATE('''||vREndDate||'''))
                    AND EXISTS (SELECT 1
                                FROM PRESCRIP p2
                                WHERE 1=1
                                AND p2."Patient" = p1."Patient"
                                AND p2."PrescripType" IN (1,2)
                                AND p2."Deleted" = 0
                                AND ((p2."StartDate" IS NULL) OR TRUNC(p2."StartDate") <= TRUNC(TO_DATE('''||vREndDate||''')))
                                AND ((p2."EndDate" IS NULL) OR TRUNC(p2."EndDate") >= TRUNC(TO_DATE('''||vRStartDate||''')))
                                GROUP BY p2."Patient"
                                )
                    GROUP BY p1."Patient", pt1."Last", pt1."First", pt1."Chart"
                    ';

        OPEN MUWeakCursor FOR vSQLStmt;

    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE core2_details(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vColVal         NUMBER(10) := -1;
        vReportingYear  VARCHAR2(100 ) := '';
        vSQLStmt        VARCHAR2(2500 ) := '';
        vRefCode        VARCHAR2(10 ) := 'MU_CORE2';

    BEGIN
        vReportingYear := TO_CHAR(vRStartDate, 'MM/DD/YYYY')
                          || ' - ' ||
                          TO_CHAR(vREndDate, 'MM/DD/YYYY') ;

        BEGIN
              SELECT pi1."PItemCol" INTO vColVal
              FROM PITEM pi1, PFORM p1
              WHERE 1=1
              AND pi1."PForm" = p1."PForm"
              AND pi1."FItem" IN (SELECT f1."FItem"
                                  FROM FITEM f1
                                  WHERE 1=1
                                  AND f1."Code" = 'MU_RP'
                                  AND f1."Deleted" = 0)
              AND pi1."AnsText" <> TRIM('+')
              AND pi1."Status" = 0
              AND pi1."AppDate" IS NOT NULL
              AND p1."OwnerId" = pUser
              AND TRIM(pi1."AnsText") = TRIM(vReportingYear);

            EXCEPTION WHEN NO_DATA_FOUND THEN
            vColVal := -1;
          END;

          vSQLStmt := '
                        SELECT pi2."AnsYes", pi2."Date", u1."Name", u1."First", pi2."FormCode"
                        FROM PITEM pi2, PFORM p2, USERS u1
                        WHERE 1=1
                        AND pi2."FItem" = ( SELECT f1."FItem"
                                            FROM FITEM f1
                                            WHERE 1=1
                                            AND TRIM(f1."Code") = '''||vRefCode||'''
                                            AND f1."Deleted" = 0)
                        AND pi2."Status" = 0
                        AND pi2."Patient" = 0
                        AND pi2."AppDate" IS NOT NULL
                        AND p2."OwnerId" = '||pUser||'
                        AND pi2."PForm" = p2."PForm"
                        AND pi2."PItemCol"= :1
                        AND pi2."User" = u1."User"
                    ';
        OPEN MUWeakCursor FOR vSQLStmt USING vColVal;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE core3_details_d(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vProducer   CHAR(10 );
        vSQLStmt VARCHAR2(5000 );
    BEGIN

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                      SELECT DISTINCT "Patient", "Last", "First", "Chart", MAX("Flag") "Flag"
                      FROM (
                        SELECT DISTINCT a1."Patient", pt1."Last", pt1."First", pt1."Chart",
                          NVL((SELECT DISTINCT 1
                               FROM EPREVIEW e1
                               WHERE 1=1
                               AND e1."Type" = 2
                               AND e1."Deleted" = 0
                               AND TRUNC(e1."ReviewDate") <= TRUNC(TO_DATE('''||vREndDate||'''))
                               AND e1."Patient" = a1."Patient"
                               ),0) as "Flag"
                        FROM APPOINT a1, PATIENT pt1
                        WHERE 1=1
                        AND a1."Patient" = pt1."Patient"
                        AND a1."Type" IN (0,1,2)
                        AND TRIM(a1."Producer") = :1
                        AND a1."Status" = 0
                        AND TRUNC(a1."Date") BETWEEN TRUNC(TO_DATE('''||vRStartDate||''')) AND TRUNC(TO_DATE('''||vREndDate||'''))
                      )
                      GROUP BY "Patient", "Last", "First", "Chart"
                    ';

        OPEN MUWeakCursor FOR vSQLStmt USING TRIM(vProducer) ;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE core3_details_n(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vProducer   CHAR(10);
        vSQLStmt VARCHAR2(2500);
    BEGIN

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                    SELECT DISTINCT a1."Patient", pt1."Last", pt1."First", pt1."Chart"
                    FROM APPOINT a1, PATIENT pt1
                    WHERE 1=1
                    AND a1."Patient" = pt1."Patient"
                    AND a1."Type" IN (0,1,2)
                    AND TRIM(a1."Producer") = :1
                    AND TRUNC(a1."Date") BETWEEN TRUNC(TO_DATE('''||vRStartDate||''')) AND TRUNC(TO_DATE('''||vREndDate||'''))
                    AND EXISTS(SELECT DISTINCT 1
                               FROM PROLIST p2
                               WHERE 1=1
                               AND p2."Patient" = a1."Patient"
                               AND NOT EXISTS (SELECT 1
                                               FROM PROLISTH ph2, PROSTS psts3, AUDITHIS ah3
                                               WHERE 1=1
                                               AND ph2."Patient" = a1."Patient"
                                               AND ph2."Status" = psts3."Code"(+)
                                               AND ph2."Audit" = ah3."Audit"
                                               AND ph2."Id" = p2."Id"
                                               AND (( ph2."Deleted" = 1) OR (psts3."Resolved" = 1))
                                               AND TRUNC(ah3."Date") <= TRUNC(TO_DATE('''||vREndDate||''')))
                              )';

        OPEN MUWeakCursor FOR vSQLStmt USING TRIM(vProducer);

    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE core4_details_d(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vProducer   CHAR(10 );
        vSQLStmt VARCHAR2(2500 );
        vNoDrug CHAR(1 ) := ' ';
    BEGIN

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                      SELECT DISTINCT rx1."Patient", p1."Last", p1."First", p1."Chart", rx1."Prescription",
                        ( CASE WHEN rx1."PrescripType" = 2 THEN
                            1
                          ELSE
                            0
                          END
                        ) AS "Flag"
                      FROM PRESCRIP rx1, PATIENT p1
                      WHERE 1=1
                      AND rx1."Patient" = p1."Patient"
                      AND rx1."PrescripType" IN (1,2)
                      AND TRIM(rx1."Provider") = :1 --prescribed by the provider
                      AND (rx1."DrugSchedule" IS NULL OR rx1."DrugSchedule" NOT IN (''1'',''2'',''3'',''4'',''5'',''scheduled'')) --ensure that it is not a controlled substance
                      AND rx1."Deleted" = 0 --Only check to see if deleted
                      AND TRUNC(rx1."Date") BETWEEN TRUNC(TO_DATE('''||vRStartDate||''')) AND TRUNC(TO_DATE('''||vREndDate||''')) --Added during the reporting period
                    ';
        OPEN MUWeakCursor FOR vSQLStmt USING TRIM(vProducer);
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE core4_details_n(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vProducer   CHAR(10);
        vSQLStmt VARCHAR2(2500);
    BEGIN

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                    SELECT p1."Patient", p2."Last", p2."First", p2."Chart", COUNT(p1."Prescription")
                    FROM PRESCRIP p1, PATIENT p2
                    WHERE 1=1
                    AND p1."Patient" = p2."Patient"
                    AND p1."PrescripType" IN (2)
                    AND p1."Deleted" = 0
                    AND ((TRIM(p1."Provider") IS NOT NULL)
                    AND TRIM(p1."Provider") = :1)
                    AND TRUNC(p1."Date") BETWEEN TRUNC(TO_DATE('''||vRStartDate||''')) AND TRUNC(TO_DATE('''||vREndDate||'''))
                    GROUP BY p1."Patient", p2."Last", p2."First", p2."Chart"
                    ';
        OPEN MUWeakCursor FOR vSQLStmt USING TRIM(vProducer);
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE core5_details_d(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vProducer   CHAR(10 );
        vSQLStmt VARCHAR2(2500 );
    BEGIN

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                      SELECT DISTINCT "Patient", "Last", "First", "Chart", MAX("Flag") "Flag"
                      FROM (
                        SELECT DISTINCT a1."Patient", p1."Last", p1."First", p1."Chart",
                          NVL((SELECT DISTINCT 1
                               FROM EPREVIEW e1
                               WHERE 1=1
                               AND e1."Type" = 0
                               AND e1."Deleted" = 0
                               AND TRUNC(e1."ReviewDate") <= TRUNC(TO_DATE('''||vREndDate||'''))
                               AND e1."Patient" = a1."Patient"
                               ),0) as "Flag"
                        FROM APPOINT a1, PATIENT p1
                        WHERE 1=1
                        AND a1."Patient" = p1."Patient"
                        AND a1."Type" IN (0,1,2)
                        AND TRIM(a1."Producer") = TRIM(:1)
                        AND a1."Status" = 0
                        AND TRUNC(a1."Date") BETWEEN TRUNC(TO_DATE('''||vRStartDate||''')) AND TRUNC(TO_DATE('''||vREndDate||'''))
                      )
                      GROUP BY "Patient", "Last", "First", "Chart"
                    ';
        OPEN MUWeakCursor FOR vSQLStmt USING TRIM(vProducer);
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE core5_details_n(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vProducer   CHAR(10);
        vSQLStmt VARCHAR2(2500);
    BEGIN

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                    SELECT DISTINCT a1."Patient", p1."Last", p1."First", p1."Chart"
                    FROM APPOINT a1, PATIENT p1
                    WHERE 1=1
                    AND a1."Patient" = p1."Patient"
                    AND a1."Type" IN (0,1,2)
                    AND TRIM(a1."Producer") = TRIM(:1)
                    AND TRUNC(a1."Date") BETWEEN TRUNC(TO_DATE('''||vRStartDate||''')) AND TRUNC(TO_DATE('''||vREndDate||'''))
                    AND EXISTS (SELECT 1
                                FROM EPREVIEW e1
                                WHERE 1=1
                                AND e1."Type" IN (0)
                                AND e1."Deleted" = 0
                                AND TRUNC(e1."ReviewDate") BETWEEN TRUNC(TO_DATE('''||vRStartDate||''')) AND TRUNC(TO_DATE('''||vREndDate||'''))
                                AND e1."Patient" = a1."Patient")
                    ';
        OPEN MUWeakCursor FOR vSQLStmt USING  TRIM(vProducer);
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE core6_details_d(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vProducer   CHAR(10 );
        vSQLStmt    VARCHAR2(5000 );
    BEGIN

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt :=  '
                      SELECT DISTINCT "Patient", "Last", "First", "Chart", MAX("Flag") "Flag"
                      FROM (
                        SELECT DISTINCT ap1."Patient", p2."Last", p2."First", p2."Chart",
                          NVL((SELECT DISTINCT 1
                               FROM EPREVIEW e1
                               WHERE 1=1
                               AND e1."Type" = 1
                               AND e1."Deleted" = 0
                               AND TRUNC(e1."ReviewDate") <= TRUNC(TO_DATE('''||vREndDate||'''))
                               AND e1."Patient" = ap1."Patient"
                               ),0) as "Flag"
                        FROM APPOINT ap1, PATIENT p2
                        WHERE 1=1
                        AND ap1."Patient" = p2."Patient"
                        AND ap1."Type" IN (0,1,2)
                        AND TRIM(ap1."Producer") = :1
                        AND ap1."Status" = 0
                        AND TRUNC(ap1."Date") BETWEEN TRUNC(TO_DATE('''||vRStartDate||''')) AND TRUNC(TO_DATE('''||vREndDate||'''))
                      )
                      GROUP BY "Patient", "Last", "First", "Chart"
                    ';
        OPEN MUWeakCursor FOR vSQLStmt USING TRIM(vProducer);
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE core7_details_d(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vProducer   CHAR(10 );
        vSQLStmt    VARCHAR2(5000 );
    BEGIN

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                      SELECT DISTINCT "Patient", "Last", "First", "Chart", MAX("Flag") "Flag"
                      FROM (
                        SELECT DISTINCT a1."Patient", pt1."Last", pt1."First", pt1."Chart",
                          NVL(( SELECT DISTINCT 1
                                FROM PATHIS p1
                                WHERE 1=1
                                AND p1."Patient" = a1."Patient"
                                AND p1."Birth" IS NOT NULL --Recorded Date of birth
                                AND p1."Sex" > 0 --Recorded Gender
                                AND TRIM(p1."PrefLanguage") IS NOT NULL --Recorded Preferred language
                                AND ( ( TRIM(p1."Ethnic") IS NOT NULL --Recorded Ethnicity
                                        AND EXISTS (SELECT 1 --Recorded Race
                                                    FROM PTRACEH PR1
                                                    WHERE PR1."Patient" = p1."Patient"
                                                    AND PR1."Deleted" = 0
                                                    AND PR1."Audit" = ( SELECT MAX(DISTINCT PR2."Audit") --Last Race information in the reporting period
                                                                        FROM PTRACEH PR2, AUDITHIS AH1
                                                                        WHERE 1=1
                                                                        AND PR2."Audit" = AH1."Audit"
                                                                        AND PR2."Patient" = PR1."Patient"
                                                                        AND PR2."Race" = PR1."Race"
                                                                        AND TRUNC(AH1."Date") <= TRUNC(TO_DATE('''||vREndDate||'''))
                                                                      )
                                                    )
                                      )
                                    OR p1."RaceEthDeclined" > 0 --Recorded a Delcined Race/Ethnicity
                                    )
                                AND p1."Id" = ( SELECT MAX(p2."Id")--Last Patient information in the reporting period
                                                FROM PATHIS p2, AUDITHIS AH2
                                                WHERE 1=1
                                                AND p2."Audit" = AH2."Audit"
                                                AND p2."Patient" = p1."Patient"
                                                AND TRUNC(AH2."Date") <= TRUNC(TO_DATE('''||vREndDate||'''))
                                                )
                              ),0) AS "Flag"
                        FROM APPOINT a1, PATIENT pt1
                        WHERE 1=1
                        AND a1."Patient" = pt1."Patient"
                        AND a1."Type" IN (0,1,2)
                        AND TRIM(a1."Producer") = :1
                        AND a1."Status" = 0
                        AND TRUNC(a1."Date") BETWEEN TRUNC(TO_DATE('''||vRStartDate||''')) AND TRUNC(TO_DATE('''||vREndDate||'''))
                      )
                      GROUP BY "Patient", "Last", "First", "Chart"
                    ';
        OPEN MUWeakCursor FOR vSQLStmt USING TRIM(vProducer);
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE core7_details_n(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vProducer   CHAR(10);
        vSQLStmt    VARCHAR2(2500);
    BEGIN

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                      SELECT DISTINCT a1."Patient", p1."Last", p1."First", p1."Chart"
                      FROM APPOINT a1, PATIENT p1
                      WHERE 1=1
                      AND a1."Patient" = p1."Patient"
                      AND a1."Type" IN (0,1,2)
                      AND TRIM(a1."Producer") = :1
                      AND TRUNC(a1."Date") BETWEEN TRUNC(TO_DATE('''||vRStartDate||''')) AND TRUNC(TO_DATE('''||vREndDate||'''))
                      AND EXISTS (SELECT 1 FROM PATHIS ph1
                                  WHERE 1=1
                                  AND ph1."Patient" = a1."Patient"
                                  AND ph1."Id" = (
                                                SELECT MAX(ph2."Id")
                                                FROM PATHIS ph2, AUDITHIS a2
                                                WHERE 1=1
                                                AND ph2."Audit" = a2."Audit"
                                                AND ph1."Patient" = ph2."Patient"
                                                AND TRUNC(a2."Date") BETWEEN TRUNC(TO_DATE('''||vRStartDate||''')) AND TRUNC(TO_DATE('''||vREndDate||'''))
                                                )
                                  GROUP BY p1."Patient"
                                  HAVING ((MAX(p1."Birth") IS NOT NULL) AND (MAX(p1."Sex") <> 0) AND (MAX(LENGTH(TRIM(p1."CustomCode1"))) IS NOT NULL)
                                          AND (MAX(LENGTH(TRIM(p1."CustomCode2"))) IS NOT NULL) AND (MAX(LENGTH(TRIM(p1."CustomCode3"))) IS NOT NULL))
                                  )
                    ';
        OPEN MUWeakCursor FOR vSQLStmt USING TRIM(vProducer);
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE core8_details_d(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vProducer   CHAR(10 );
        vSQLStmt    VARCHAR2(24000 );
        vBPCheck VARCHAR2(150 ) :=  'MDH_SBP'', ''MDH_DBP';
        vHTWTCheck VARCHAR2(150 ) := 'PT_STD_HT1'', ''PT_STD_HT2'', ''PT_STD_HT'',''PT_STD_WT'', ''PT_STD_BMI';
        vFormCode CHAR(6 ) := 'MUMDH';
    BEGIN

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
		SELECT DISTINCT "Patient", "Last", "First", "Chart", MAX("Flag") "Flag"
		FROM (
			SELECT DISTINCT
				p2."Patient",
				p1."Last",
				p1."First",
				p1."Chart",
				NVL
				(
					(
						SELECT DISTINCT 1 FROM DUAL
						WHERE 1=1
						AND
						(
							(
								(
									MU_CORE_PKG.CALC_PT_AGE(p2."Patient", p2."Date") < 3
									AND (
										MU_CORE_PKG.CORE8_302f_EX('''||pUser||''', '''||vRStartDate||''', '''||vREndDate||''') NOT IN (4)
									)
									AND EXISTS (
										SELECT 1
										FROM PITEM p3, FITEM f1
										WHERE 1=1
										--AND TRIM(p3."FormCode") = TRIM('''||vFormCode||''')
										AND p3."FItem" = f1."FItem"
										AND p3."Patient" = p2."Patient"
										AND TRUNC(p3."Date") <= TRUNC(TO_DATE('''||vREndDate||'''))
										AND TRIM(f1."Code") IN ('''||vHTWTCheck||''')
										AND TRIM(p3."AnsText") != ''Invalid inputs provided.''
										AND LENGTH(TRIM(p3."AnsText")) > 0
										AND p3."AuditNumber" = (
											SELECT MAX(p3n."AuditNumber") FROM
											PITEM p3n, FITEM f1n
											WHERE 1=1
											AND p3n."FormCode" = p3."FormCode"
											AND p3n."FItem" = f1n."FItem"
											AND p3n."Patient" = p3."Patient"
											AND f1n."Code" = f1."Code"
											AND p3n."AppUser" != 0
											AND TRUNC(p3n."Date") <= TRUNC(TO_DATE('''||vREndDate||''')) -- originally using appointment date: p2."Date"
											GROUP BY f1n."Code"
										)
										GROUP BY p3."Patient"
										HAVING COUNT(DISTINCT f1."Code") = 5
									)
								)
							)
							OR (
								MU_CORE_PKG.CALC_PT_AGE(p2."Patient", p2."Date") >= 3
								AND (((
											MU_CORE_PKG.CORE8_302f_EX('''||pUser||''', '''||vRStartDate||''', '''||vREndDate||''') IN (4)
										)
										OR EXISTS (
											SELECT 1
											FROM PITEM p3, FITEM f1
											WHERE 1=1
											--AND TRIM(p3."FormCode") = TRIM('''||vFormCode||''')
											AND p3."FItem" = f1."FItem"
											AND p3."Patient" = p2."Patient"
											AND TRUNC(p3."Date") <= TRUNC(TO_DATE('''||vREndDate||'''))
											AND TRIM(f1."Code") IN ('''||vHTWTCheck||''')
											AND TRIM(p3."AnsText") != ''Invalid inputs provided.''
											AND LENGTH(TRIM(p3."AnsText")) > 0
											AND p3."AuditNumber" = (
												SELECT MAX(p3n."AuditNumber") FROM
												PITEM p3n, FITEM f1n
												WHERE 1=1
												AND p3n."FormCode" = p3."FormCode"
												AND p3n."FItem" = f1n."FItem"
												AND p3n."Patient" = p3."Patient"
												AND f1n."Code" = f1."Code"
												AND p3n."AppUser" != 0
												AND TRUNC(p3n."Date") <= TRUNC(TO_DATE('''||vREndDate||''')) -- originally using appointment date: p2."Date"
												GROUP BY f1n."Code"
											)
											GROUP BY p3."Patient"
											HAVING COUNT(DISTINCT f1."Code") = 5
										)
									)
								AND ((
										MU_CORE_PKG.CORE8_302f_EX('''||pUser||''', '''||vRStartDate||''', '''||vREndDate||''') IN (3)
										OR EXISTS (
											SELECT 1
											FROM PITEM p3, FITEM f1
											WHERE 1=1
											--AND TRIM(p3."FormCode") = TRIM('''||vFormCode||''')
											AND p3."FItem" = f1."FItem"
											AND p3."Patient" = p2."Patient"
											AND TRUNC(p3."Date") <= TRUNC(TO_DATE('''||vREndDate||'''))
											AND TRIM(f1."Code") IN ('''||vBPCheck||''')
											AND TRIM(p3."AnsText") != ''Invalid inputs provided.''
											AND LENGTH(TRIM(p3."AnsText")) > 0
											AND p3."AuditNumber" = (
												SELECT MAX(p3n."AuditNumber") FROM
												PITEM p3n, FITEM f1n
												WHERE 1=1
												AND p3n."FormCode" = p3."FormCode"
												AND p3n."FItem" = f1n."FItem"
												AND p3n."Patient" = p3."Patient"
												AND f1n."Code" = f1."Code"
												AND p3n."AppUser" != 0
												AND TRUNC(p3n."Date") <= TRUNC(TO_DATE('''||vREndDate||''')) -- originally using appointment date: p2."Date"
												GROUP BY f1n."Code"
											)
											GROUP BY p3."Patient"
											HAVING COUNT(DISTINCT f1."Code") = 2
										)
									)
								)
							)
						)
					)
				),0) AS "Flag"
			FROM APPOINT p2, PATIENT p1
			WHERE 1=1
			AND p2."Patient" = p1."Patient"
			AND p2."Type" IN (0,1,2)
			AND TRIM(p2."Producer") = :1
			AND p2."Status" = 0
			AND TRUNC(p2."Date") BETWEEN TRUNC(TO_DATE('''||vRStartDate||''')) AND TRUNC(TO_DATE('''||vREndDate||'''))
			AND (
				MU_CORE_PKG.CORE8_302f_EX('''||pUser||''', '''||vRStartDate||''', '''||vREndDate||''') NOT IN (4)
				OR MU_CORE_PKG.CALC_PT_AGE(p2."Patient", p2."Date") >= 3
			)
		)
		GROUP BY "Patient", "Last", "First", "Chart"
		';
        OPEN MUWeakCursor FOR vSQLStmt USING TRIM(vProducer);
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE core9_details_d(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vProducer   CHAR(10 );
        vSQLStmt    VARCHAR2(2500 );
    BEGIN

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                      SELECT DISTINCT "Patient", "Last", "First", "Chart", MAX("Flag") "Flag"
                      FROM (
                        SELECT DISTINCT a1."Patient", p1."Last", p1."First", p1."Chart",
                          NVL(( SELECT DISTINCT 1
                                FROM PTALERTH ph1
                                WHERE 1=1
                                AND ph1."Patient" = a1."Patient"
                                AND ph1."AlertType" = 2
                                AND ph1."Status" = 0
                                AND ph1."Deleted" = 0
                                AND ph1."SNOCode" IN (''449868002'', ''428041000124106'', ''8517006'', ''266919005'',
                                                      ''77176002'', ''266927001'', ''428071000124103'', ''428061000124105'')
                                AND ph1."PtAlertH" = (SELECT MAX(ph2."PtAlertH")
                                                      FROM PTALERTH ph2, AUDITHIS ah3
                                                      WHERE 1=1
                                                      AND ph2."Patient" = ph1."Patient"
                                                      AND ph2."MedAlert" = ph1."MedAlert"
                                                      AND ph2."Audit" = ah3."Audit"
                                                      AND TRUNC(ah3."Date") <= TRUNC(TO_DATE('''||vREndDate||'''))
                                                    )
                              ),0) AS "Flag"
                        FROM APPOINT a1, PATIENT p1
                        WHERE 1=1
                        AND a1."Patient" = p1."Patient"
                        AND a1."Type" IN (0,1,2)
                        AND TRIM(a1."Producer") = :1
                        AND a1."Status" = 0
                        AND TRUNC(a1."Date") BETWEEN TRUNC(TO_DATE('''||vRStartDate||''')) AND TRUNC(TO_DATE('''||vREndDate||'''))
                        AND MU_CORE_PKG.CALC_PT_AGE(a1."Patient", a1."Date") >= 13
                      )
                      GROUP BY "Patient", "Last", "First", "Chart"
                    ';
        OPEN MUWeakCursor FOR vSQLStmt USING TRIM(vProducer);
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE cqm16_nqf0001_d(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vSQLStmt    VARCHAR2(5000 );
        vProducer     CHAR(10 ) := '';
        vCQMSDate     DATE;
        vCQMEDate     DATE;
        vMethod       CHAR := 'A';
        vFormCode CHAR(6 ) := 'MUMDH';
        vAlertCode CHAR(6 ) := 'ASTHMA';
        vRefCode CHAR(12 ) := 'MDH_DAY';
        vRefCode2 CHAR(12 ) := 'MDH_NIGHT';

    BEGIN
        IF vMethod = 'A' THEN
          vCQMSDate := TRUNC(TO_DATE(vREndDate),'YEAR');
          vCQMEDate := LAST_DAY(ADD_MONTHS(TO_DATE(vREndDate),12 - TO_NUMBER(TO_CHAR(TO_DATE(vREndDate),'mm'))));
        END IF;

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                    SELECT "Patient", "Last", "First", "Chart", MAX("Flag") as "Flag"
                    FROM
                    (
                            SELECT a1."Date" as "Date", a1."Patient" as "Patient", p1."Last" as "Last", p1."First" as "First", p1."Chart" as "Chart",
                                  NVL((SELECT DISTINCT 1
                                        FROM dual
                                        WHERE 2 = (SELECT count(*)
                                        FROM PITEM p3, FITEM f1
                                        WHERE 1=1
                                        AND TRIM(p3."FormCode") = TRIM('''||vFormCode||''')
                                        AND p3."FItem" = f1."FItem"
                                        AND p3."Patient" = p1."Patient"
                                        AND TRUNC(p3."Date") BETWEEN ADD_MONTHS(TO_DATE(a1."Date"), -12) AND TO_DATE(a1."Date")
                                        AND (TRIM(f1."Code") IN TRIM('''||vRefCode||''') OR TRIM(f1."Code") IN TRIM('''||vRefCode2||'''))
                                        AND p3."AnsYes" = 1
                                        AND p3."AuditNumber" = (SELECT MAX(p3n."AuditNumber") FROM
                                                            PITEM p3n, FITEM f1n
                                                            WHERE 1=1
                                                            AND TRIM(p3n."FormCode") = TRIM(p3."FormCode")
                                                            AND p3n."FItem" = f1n."FItem"
                                                            AND p3n."Patient" = p3."Patient"
                                                            AND p3n."AppDate" IS NOT NULL
                                                            AND TRIM(f1n."Code") = TRIM(f1."Code")
                                                            AND TRUNC(p3n."Date") <= TO_DATE(a1."Date")
                                                            GROUP BY f1n."Code"
                                                            )
                                        )
                                      ),0) AS "Flag"
                            FROM APPOINT a1, PATIENT p1
                            WHERE 1=1
                            AND a1."Patient" = p1."Patient"
                            AND a1."Type" IN (0,1,2)
                            AND TRIM(a1."Producer") = TRIM('''||vProducer||''')
                            AND a1."Status" = 0
                            AND (MU_CORE_PKG.CALC_PT_AGE(a1."Patient", TO_DATE('''||vCQMSDate||''') ) BETWEEN 5 AND 40)
                            AND TRUNC(a1."Date") BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
                            AND EXISTS( SELECT 1
                                        FROM ALERTP2 a2, PATIENT2 p2, ALERTD2 a3
                                        WHERE 1=1
                                        AND a2."PId" = p2."Auto"
                                        AND a2."AId" = a3."Auto"
                                        AND p2."PtxPId" = p1."Patient"
                                        AND TRIM(a3."Code") = '''||vAlertCode||'''
                                        AND TRUNC(a2."AddDateTime") <= TRUNC(TO_DATE(a1."Date"))
                                        AND NOT EXISTS (SELECT 1
														FROM ALERTP2H ah1, AUDITHIS ah3
														WHERE 1=1
														AND ah1."PId" = p2."Auto"
														AND ah1."AId" = a3."Auto"
														AND ah1."Auto" = a2."Auto"
														AND ah1."Audit" = ah3."Audit"
														AND ah1."Flag" = 1
														AND TRUNC(ah3."Date") <= TRUNC(TO_DATE(a1."Date"))
														)
                                      )
							AND EXISTS( SELECT 1
										  FROM APPOINT ap2
										  WHERE 1=1
										  AND ap2."Patient" = a1."Patient"
										  AND ap2."Type" IN (0,1,2)
										  AND TRIM(ap2."Producer") = TRIM(a1."Producer")
										  AND ap2."Status" = 0
										  AND TRUNC(ap2."Date")  BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
										  AND (MU_CORE_PKG.CALC_PT_AGE(a1."Patient", TO_DATE('''||vCQMSDate||''') ) BETWEEN 5 AND 40)
										  GROUP BY ap2."Patient"
										  HAVING (COUNT(DISTINCT ap2."Date") >=2))
                    )
                    GROUP BY "Patient", "Last", "First", "Chart"
                    HAVING COUNT(DISTINCT ("Date")) >= 2
                    ';
        OPEN MUWeakCursor FOR vSQLStmt;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE cqm16_nqf0001_n(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vSQLStmt    VARCHAR2(5000 );
        vProducer     CHAR(10 ) := '';
        vCQMSDate     DATE;
        vCQMEDate     DATE;
        vMethod       CHAR := 'A';
        vFormCode CHAR(6 ) := 'MUMDH';
        vAlertCode CHAR(6 ) := 'ASTHMA';
        vRefCode CHAR(12 ) := 'MDH_DAY';
        vRefCode2 CHAR(12 ) := 'MDH_NIGHT';

    BEGIN
        IF vMethod = 'A' THEN
          vCQMSDate := TRUNC(TO_DATE(vREndDate),'YEAR');
          vCQMEDate := LAST_DAY(ADD_MONTHS(TO_DATE(vREndDate),12 - TO_NUMBER(TO_CHAR(TO_DATE(vREndDate),'mm'))));
        END IF;

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                    SELECT "Last", "First", "Chart"
                    FROM
                    (
                            SELECT a1."Date" as "Date", p1."Last" as "Last", p1."First" as "First", p1."Chart" as "Chart",
                                  NVL((SELECT DISTINCT 1
                                        FROM dual
                                        WHERE 2 = (SELECT count(*)
                                        FROM PITEM p3, FITEM f1
                                        WHERE 1=1
                                        AND TRIM(p3."FormCode") = TRIM('''||vFormCode||''')
                                        AND p3."FItem" = f1."FItem"
                                        AND p3."Patient" = p1."Patient"
                                        AND TRUNC(p3."Date") BETWEEN ADD_MONTHS(TO_DATE(a1."Date"), -12) AND TO_DATE(a1."Date")
                                        AND (TRIM(f1."Code") IN TRIM('''||vRefCode||''') OR TRIM(f1."Code") IN TRIM('''||vRefCode2||'''))
                                        AND p3."AnsYes" = 1
                                        AND p3."AuditNumber" = (SELECT MAX(p3n."AuditNumber") FROM
                                                            PITEM p3n, FITEM f1n
                                                            WHERE 1=1
                                                            AND TRIM(p3n."FormCode") = TRIM(p3."FormCode")
                                                            AND p3n."FItem" = f1n."FItem"
                                                            AND p3n."Patient" = p3."Patient"
                                                            AND p3n."AppDate" IS NOT NULL
                                                            AND TRIM(f1n."Code") = TRIM(f1."Code")
                                                            AND TRUNC(p3n."Date") <= TO_DATE(a1."Date")
                                                            GROUP BY f1n."Code"
                                                            )
                                        )
                                      ),0) AS "Flag"
                            FROM APPOINT a1, PATIENT p1
                            WHERE 1=1
                            AND a1."Patient" = p1."Patient"
                            AND a1."Type" IN (0,1,2)
                            AND TRIM(a1."Producer") = TRIM('''||vProducer||''')
                            AND a1."Status" = 0
                            AND (MU_CORE_PKG.CALC_PT_AGE(a1."Patient", TO_DATE('''||vCQMSDate||''')) BETWEEN 5 AND 40)
                            AND TRUNC(a1."Date") BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
                            AND EXISTS( SELECT 1
                                        FROM ALERTP2 a2, PATIENT2 p2, ALERTD2 a3
                                        WHERE 1=1
                                        AND a2."PId" = p2."Auto"
                                        AND a2."AId" = a3."Auto"
                                        AND p2."PtxPId" = p1."Patient"
                                        AND TRIM(a3."Code") = '''||vAlertCode||'''
                                        AND TRUNC(a2."AddDateTime") <= TRUNC(TO_DATE(a1."Date"))
                                        AND NOT EXISTS (SELECT 1
														FROM ALERTP2H ah1, AUDITHIS ah3
														WHERE 1=1
														AND ah1."PId" = p2."Auto"
														AND ah1."AId" = a3."Auto"
														AND ah1."Auto" = a2."Auto"
														AND ah1."Audit" = ah3."Audit"
														AND ah1."Flag" = 1
														AND TRUNC(ah3."Date") <= TRUNC(TO_DATE(a1."Date"))
														)
                                      )
							AND EXISTS( SELECT 1
										  FROM APPOINT ap2
										  WHERE 1=1
										  AND ap2."Patient" = a1."Patient"
										  AND ap2."Type" IN (0,1,2)
										  AND TRIM(ap2."Producer") = TRIM(a1."Producer")
										  AND ap2."Status" = 0
										  AND TRUNC(ap2."Date")  BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
										  AND (MU_CORE_PKG.CALC_PT_AGE(a1."Patient", TO_DATE('''||vCQMSDate||''') ) BETWEEN 5 AND 40)
										  GROUP BY ap2."Patient"
										  HAVING (COUNT(DISTINCT ap2."Date") >=2))
                    )
                    GROUP BY "Last", "First", "Chart"
                    HAVING MAX("Flag") = 1
                    ';
        OPEN MUWeakCursor FOR vSQLStmt;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE cqm1_nqf0013_d(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vSQLStmt    VARCHAR2(5000 );
        vProducer     CHAR(10 ) := '';
        vCQMSDate     DATE;
        vCQMEDate     DATE;
        vCDate        DATE;
        vMethod       CHAR := 'A';
        vFormCode CHAR(6 ) := 'MUMDH';
        vCodeList  VARCHAR2(150 ) := 'MDH_SBP'',''MDH_DBP';
	vHypertensionCode VARCHAR2(50 ) := 'HTN'',''PREHTN';
    BEGIN
        IF vMethod = 'A' THEN
          vCQMSDate := TRUNC(TO_DATE(vREndDate),'YEAR');
          vCQMEDate := LAST_DAY(ADD_MONTHS(TO_DATE(vREndDate),12 - TO_NUMBER(TO_CHAR(TO_DATE(vREndDate),'mm'))));
        END IF;

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;
        SELECT TO_DATE('01-01-1970 00:00:00', 'DD-MM-YYYY HH24:MI:SS') INTO vCDate FROM DUAL;

        vSQLStmt := '
                      SELECT ap1."Appointment", ap1."Date", ap1."From", ap1."Clinic", p2."Last", p2."First", p2."Chart",
                        NVL(( SELECT DISTINCT 1 FROM
                              PITEM p4, FITEM f1
                              WHERE 1=1
                              AND TRIM(p4."FormCode") = TRIM('''||vFormCode||''')
                              AND p4."FItem" = f1."FItem"
                              AND p4."Patient" = ap1."Patient"
                              AND TRUNC(p4."Date") = TRUNC(ap1."Date")
                              AND TRIM(f1."Code") IN ('''||vCodeList||''')
                              AND p4."Status" = 0
                              AND LENGTH(TRIM(p4."AnsText")) > 0
                              AND p4."AuditNumber" = (SELECT MAX(p3n."AuditNumber")
                                                      FROM PITEM p3n, FITEM f1n
                                                      WHERE 1=1
                                                      AND p3n."FormCode" = p4."FormCode"
                                                      AND p3n."FItem" = f1n."FItem"
                                                      AND p3n."Patient" = p4."Patient"
                                                      AND f1n."Code" = f1."Code"
                                                      AND TRUNC(p3n."Date") <= TRUNC(TO_DATE(ap1."Date"))
                                                      GROUP BY f1n."Code"
                                                      )
                              GROUP BY p4."Patient"
                              HAVING  (COUNT(DISTINCT f1."Code") >=2)),0) as "Flag"
                      FROM APPOINT ap1, PATIENT p2
                      WHERE 1=1
                      AND ap1."Patient" = p2."Patient"
                      AND ap1."Type" IN (0,1,2)
                      AND TRIM(ap1."Producer") = TRIM('''||vProducer||''')
                      AND ap1."Status" = 0
                      AND TRUNC(ap1."Date")  BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
                      AND MU_CORE_PKG.CALC_PT_AGE(ap1."Patient", TO_DATE('''||vCQMSDate||''')) >= 18
                      AND EXISTS( SELECT 1
                                  FROM ALERTP2 a1, ALERTD2 a2, PATIENT2 p3
                                  WHERE 1=1
                                  AND p3."PtxPId" = ap1."Patient"
                                  AND a2."Auto" = a1."AId"
                                  AND a1."PId" = p3."Auto"
                                  AND TRIM(a2."Code") IN ('''||vHypertensionCode||''')
                                  AND TRUNC(a1."AddDateTime") <= TRUNC(TO_DATE(ap1."Date"))
                                  AND NOT EXISTS (SELECT 1
                                                  FROM ALERTP2H ah1, AUDITHIS ah3
                                                  WHERE 1=1
                                                  AND ah1."PId" = p3."Auto"
                                                  AND ah1."AId" = a2."Auto"
                                                  AND ah1."Auto" = a1."Auto"
                                                  AND ah1."Audit" = ah3."Audit"
                                                  AND ah1."Flag" = 1
                                                  AND TRUNC(ah3."Date") <= TRUNC(TO_DATE(ap1."Date"))
                                                  )
                                )
                      AND EXISTS( SELECT 1 FROM
                                  APPOINT ap2
                                  WHERE 1=1
                                  AND ap2."Patient" = ap1."Patient"
                                  AND ap2."Type" IN (0,1,2)
                                  AND TRIM(ap2."Producer") = TRIM(ap1."Producer")
                                  AND ap2."Status" = 0
                                  AND TRUNC(ap2."Date")  BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
                                  GROUP BY ap2."Patient"
                                  HAVING (COUNT(DISTINCT ap2."Date") >=2)
                                )
                    ';
        OPEN MUWeakCursor FOR vSQLStmt;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE cqm1_nqf0013_n(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vSQLStmt    VARCHAR2(5000 );
        vProducer     CHAR(10 ) := '';
        vCQMSDate     DATE;
        vCQMEDate     DATE;
        vCDate        DATE;
        vMethod       CHAR := 'A';
        vFormCode CHAR(6 ) := 'MUMDH';
	vHypertensionCode VARCHAR2(50 ) := 'HTN'',''PREHTN';
        vCodeList  VARCHAR2(150 ) := 'MDH_SBP'',''MDH_DBP';
    BEGIN
        IF vMethod = 'A' THEN
          vCQMSDate := TRUNC(TO_DATE(vREndDate),'YEAR');
          vCQMEDate := LAST_DAY(ADD_MONTHS(TO_DATE(vREndDate),12 - TO_NUMBER(TO_CHAR(TO_DATE(vREndDate),'mm'))));
        END IF;

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;
        SELECT TO_DATE('01-01-1970 00:00:00', 'DD-MM-YYYY HH24:MI:SS') INTO vCDate FROM DUAL;

        vSQLStmt := '
                    SELECT ap1."Appointment", ap1."Date", ap1."From", p2."Last", p2."First", p2."Chart"
                    FROM APPOINT ap1, PATIENT p2
                    WHERE 1=1
                    AND ap1."Patient" = p2."Patient"
                    AND ap1."Type" IN (0,1,2)
                    AND TRIM(ap1."Producer") = TRIM('''||vProducer||''')
                    AND ap1."Status" = 0
                    AND TRUNC(ap1."Date") BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
                    AND MU_CORE_PKG.CALC_PT_AGE(ap1."Patient", TO_DATE('''||vCQMSDate||''')) >= 18
                    AND EXISTS( SELECT 1
                                FROM ALERTP2 a1, ALERTD2 a2, PATIENT2 p3
                                WHERE 1=1
                                AND p3."PtxPId" = ap1."Patient"
                                AND a2."Auto" = a1."AId"
                                AND a1."PId" = p3."Auto"
                                AND TRIM(a2."Code") IN ('''||vHypertensionCode||''')
                                AND TRUNC(a1."AddDateTime") <= TRUNC(TO_DATE(ap1."Date"))
                                AND NOT EXISTS (SELECT 1
                                                FROM ALERTP2H ah1, AUDITHIS ah3
                                                WHERE 1=1
                                                AND ah1."PId" = p3."Auto"
                                                AND ah1."AId" = a2."Auto"
                                                AND ah1."Auto" = a1."Auto"
                                                AND ah1."Audit" = ah3."Audit"
                                                AND ah1."Flag" = 1
                                                AND TRUNC(ah3."Date") <= TRUNC(TO_DATE(ap1."Date"))
                                                )
                              )
                    AND EXISTS( SELECT  1 FROM
                                PITEM p4, FITEM f1
                                WHERE 1=1
                                AND TRIM(p4."FormCode") = TRIM('''||vFormCode||''')
                                AND p4."FItem" = f1."FItem"
                                AND p4."Patient" = ap1."Patient"
                                AND TRUNC(p4."Date") = TRUNC(ap1."Date")
                                AND TRIM(f1."Code") IN ('''||vCodeList||''')
                                AND p4."Status" = 0
								AND LENGTH(TRIM(p4."AnsText")) > 0
                                AND p4."AuditNumber" = (SELECT MAX(p3n."AuditNumber")
                                                        FROM PITEM p3n, FITEM f1n
                                                        WHERE 1=1
                                                        AND p3n."FormCode" = p4."FormCode"
                                                        AND p3n."FItem" = f1n."FItem"
                                                        AND p3n."Patient" = p4."Patient"
                                                        AND f1n."Code" = f1."Code"
                                                        AND TRUNC(p3n."Date") <= TRUNC(TO_DATE(ap1."Date"))
                                                        GROUP BY f1n."Code"
                                                        )
                                GROUP BY p4."Patient"
                                HAVING  (COUNT(DISTINCT f1."Code") >=2)
                              )
                    AND EXISTS( SELECT 1 FROM
                                APPOINT ap2
                                WHERE 1=1
                                AND ap2."Patient" = ap1."Patient"
                                AND ap2."Type" IN (0,1,2)
                                AND TRIM(ap2."Producer") = TRIM(ap1."Producer")
                                AND ap2."Status" = 0
                                AND TRUNC(ap2."Date") BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
                                AND MU_CORE_PKG.CALC_PT_AGE(ap2."Patient", TO_DATE('''||vCQMSDate||''')) >= 18
                                GROUP BY ap2."Patient"
                                HAVING (COUNT(DISTINCT ap2."Date") >=2)
                                )

                    ';
        OPEN MUWeakCursor FOR vSQLStmt;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE cqm21_nqf0027_d(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vSQLStmt    VARCHAR2(5000 );
        vProducer     CHAR(10 ) := '';
        vCQMSDate     DATE;
        vCQMEDate     DATE;
        vMethod       CHAR := 'A';
        vFormCode CHAR(6 ) := 'MUMDH';
        vCodeList  VARCHAR2(150 ) := 'MDH_SMK03';
        vRefCodeList  VARCHAR2(150 ) := 'MU_SMK_C1'',''MU_SMK_C2';
    BEGIN
        IF vMethod = 'A' THEN
          vCQMSDate := TRUNC(TO_DATE(vREndDate),'YEAR');
          vCQMEDate := LAST_DAY(ADD_MONTHS(TO_DATE(vREndDate),12 - TO_NUMBER(TO_CHAR(TO_DATE(vREndDate),'mm'))));
        END IF;

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                    SELECT DISTINCT a1."Patient", p2."Last", p2."First", p2."Chart",
                          NVL((SELECT DISTINCT 1 FROM
                                PITEM p3, FITEM f1
                                WHERE 1=1
                                AND TRIM(p3."FormCode") = TRIM('''||vFormCode||''')
                                AND p3."FItem" = f1."FItem"
                                AND p3."Patient" = a1."Patient"
                                AND TRUNC(p3."Date") BETWEEN ADD_MONTHS(TO_DATE('''||vCQMEDate||'''), -24) AND TO_DATE('''||vCQMEDate||''')
                                AND TRIM(f1."Code") IN ('''||vCodeList||''')
                                AND TRIM(p3."AnsListRefCode") IN ('''||vRefCodeList||''')
                                AND p3."AuditNumber" = (SELECT MAX(p3n."AuditNumber") FROM
                                                        PITEM p3n, FITEM f1n
                                                        WHERE 1=1
                                                        AND TRIM(p3n."FormCode") = TRIM(p3."FormCode")
                                                        AND p3n."FItem" = f1n."FItem"
                                                        AND p3n."Patient" = p3."Patient"
                                                        AND p3n."AppDate" IS NOT NULL
                                                        AND TRIM(f1n."Code") = TRIM(f1."Code")
                                                        AND TRUNC(p3n."Date") <= TO_DATE(a1."Date")
                                                        GROUP BY f1n."Code")),0) as "Flag"
                    FROM APPOINT a1, PATIENT p2
                    WHERE 1=1
                    AND a1."Patient" = p2."Patient"
                    AND a1."Type" IN (0,1,2)
                    AND TRIM(a1."Producer") = TRIM('''||vProducer||''')
                    AND a1."Status" = 0
                    AND TRUNC(a1."Date") BETWEEN ADD_MONTHS(TO_DATE('''||vCQMEDate||'''), -24) AND TO_DATE('''||vCQMEDate||''')
                    AND MU_CORE_PKG.CALC_PT_AGE(a1."Patient", ('''||vCQMSDate||''')) >= 17
                    ';
        OPEN MUWeakCursor FOR vSQLStmt;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE cqm21_nqf0027_n(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vSQLStmt    VARCHAR2(5000 );
        vProducer     CHAR(10 ) := '';
        vCQMSDate     DATE;
        vCQMEDate     DATE;
        vMethod       CHAR := 'A';
        vFormCode CHAR(6 ) := 'MUMDH';
        vCodeList  VARCHAR2(150 ) := 'MDH_SMK03';
        vRefCodeList  VARCHAR2(150 ) := 'MU_SMK_C1'',''MU_SMK_C2';
    BEGIN
        IF vMethod = 'A' THEN
          vCQMSDate := TRUNC(TO_DATE(vREndDate),'YEAR');
          vCQMEDate := LAST_DAY(ADD_MONTHS(TO_DATE(vREndDate),12 - TO_NUMBER(TO_CHAR(TO_DATE(vREndDate),'mm'))));
        END IF;

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                    SELECT DISTINCT a1."Patient", p2."Last", p2."First", p2."Chart"
                    FROM APPOINT a1, PATIENT p2
                    WHERE 1=1
                    AND a1."Patient" = p2."Patient"
                    AND a1."Type" IN (0,1,2)
                    AND TRIM(a1."Producer") = TRIM('''||vProducer||''')
                    AND a1."Status" = 0
                    AND TRUNC(a1."Date") BETWEEN ADD_MONTHS(TO_DATE('''||vCQMEDate||'''), -24) AND TO_DATE('''||vCQMEDate||''')
                    AND MU_CORE_PKG.CALC_PT_AGE(a1."Patient", ('''||vCQMSDate||''')) >= 17
                    AND EXISTS (SELECT 1 FROM
                                PITEM p3, FITEM f1
                                WHERE 1=1
                                AND TRIM(p3."FormCode") = TRIM('''||vFormCode||''')
                                AND p3."FItem" = f1."FItem"
                                AND p3."Patient" = a1."Patient"
                                AND TRUNC(p3."Date") BETWEEN ADD_MONTHS(TO_DATE('''||vCQMEDate||'''), -24) AND TO_DATE('''||vCQMEDate||''')
                                AND TRIM(f1."Code") IN ('''||vCodeList||''')
                                AND TRIM(p3."AnsListRefCode") IN ('''||vRefCodeList||''')
                                AND p3."AuditNumber" = (SELECT MAX(p3n."AuditNumber") FROM
                                                        PITEM p3n, FITEM f1n
                                                        WHERE 1=1
                                                        AND TRIM(p3n."FormCode") = TRIM(p3."FormCode")
                                                        AND p3n."FItem" = f1n."FItem"
                                                        AND p3n."Patient" = p3."Patient"
                                                        AND p3n."AppDate" IS NOT NULL
                                                        AND TRIM(f1n."Code") = TRIM(f1."Code")
                                                        AND TRUNC(p3n."Date") <= TO_DATE(a1."Date")
                                                        GROUP BY f1n."Code"))
                    ';
        OPEN MUWeakCursor FOR vSQLStmt;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE cqm21_nqf0027b_d(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vSQLStmt    VARCHAR2(5000 );
        vProducer     CHAR(10 ) := '';
        vCQMSDate     DATE;
        vCQMEDate     DATE;
        vMethod       CHAR := 'A';
        vFormCode CHAR(6 ) := 'MUMDH';
        vCodeList  VARCHAR2(150 ) := 'MDH_SMK03';
        vRefCodeList  VARCHAR2(150 ) := 'MU_SMK_C1'',''MU_SMK_C2';
        -- ADA Code for Tobacco Counselling
        vADACode      CHAR(7 ) := 'D1320';
    BEGIN
        IF vMethod = 'A' THEN
          vCQMSDate := TRUNC(TO_DATE(vREndDate),'YEAR');
          vCQMEDate := LAST_DAY(ADD_MONTHS(TO_DATE(vREndDate),12 - TO_NUMBER(TO_CHAR(TO_DATE(vREndDate),'mm'))));
        END IF;

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                    SELECT DISTINCT a1."Patient", p2."Last", p2."First", p2."Chart",
                          NVL((SELECT DISTINCT 1 FROM
                                PITEM p3, FITEM f1
                                WHERE 1=1
                                AND TRIM(p3."FormCode") = TRIM('''||vFormCode||''')
                                AND p3."FItem" = f1."FItem"
                                AND p3."Patient" = a1."Patient"
                                AND TRUNC(p3."Date") BETWEEN ADD_MONTHS(TO_DATE('''||vCQMEDate||'''), -24) AND TO_DATE('''||vCQMEDate||''')
                                AND TRIM(f1."Code") IN ('''||vCodeList||''')
                                AND TRIM(p3."AnsListRefCode") IN ('''||vRefCodeList||''')
                                AND p3."AuditNumber" = (SELECT MAX(p3n."AuditNumber") FROM
                                                        PITEM p3n, FITEM f1n
                                                        WHERE 1=1
                                                        AND TRIM(p3n."FormCode") = TRIM(p3."FormCode")
                                                        AND p3n."FItem" = f1n."FItem"
                                                        AND p3n."Patient" = p3."Patient"
                                                        AND p3n."AppDate" IS NOT NULL
                                                        AND TRIM(f1n."Code") = TRIM(f1."Code")
                                                        AND TRUNC(p3n."Date") <= TO_DATE(a1."Date")
                                                        GROUP BY f1n."Code")),0) as "Flag",
                          NVL((SELECT DISTINCT 1
                                FROM TRX t2
                                WHERE 1=1
                                AND TRIM(t2."Procedure") = TRIM('''||vADACode||''')
                                AND TRIM(t2."Status") = ''C''
                                AND t2."Deleted" = 0
                                AND t2."Patient" = a1."Patient"
                                AND TRUNC(t2."Date") BETWEEN ADD_MONTHS(TO_DATE('''||vCQMSDate||'''), -24) AND TO_DATE('''||vCQMEDate||''')),0) as "Flag2"
                    FROM APPOINT a1, PATIENT p2
                    WHERE 1=1
                    AND a1."Patient" = p2."Patient"
                    AND a1."Type" IN (0,1,2)
                    AND TRIM(a1."Producer") = TRIM('''||vProducer||''')
                    AND a1."Status" = 0
                    AND TRUNC(a1."Date") BETWEEN ADD_MONTHS(TO_DATE('''||vCQMEDate||'''), -24) AND TO_DATE('''||vCQMEDate||''')
                    AND MU_CORE_PKG.CALC_PT_AGE(a1."Patient", ('''||vCQMSDate||''')) >= 17
                    ';
        OPEN MUWeakCursor FOR vSQLStmt;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE cqm21_nqf0027b_n(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vSQLStmt    VARCHAR2(5000 );
        vProducer     CHAR(10 ) := '';
        vCQMSDate     DATE;
        vCQMEDate     DATE;
        vMethod       CHAR := 'A';
        vFormCode CHAR(6 ) := 'MUMDH';
        vCodeList  VARCHAR2(150 ) := 'MDH_SMK03';
        vRefCodeList  VARCHAR2(150 ) := 'MU_SMK_C1'',''MU_SMK_C2';
        -- ADA Code for Tobacco Counselling
        vADACode      CHAR(7 ) := 'D1320';
    BEGIN
        IF vMethod = 'A' THEN
          vCQMSDate := TRUNC(TO_DATE(vREndDate),'YEAR');
          vCQMEDate := LAST_DAY(ADD_MONTHS(TO_DATE(vREndDate),12 - TO_NUMBER(TO_CHAR(TO_DATE(vREndDate),'mm'))));
        END IF;

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                    SELECT DISTINCT a1."Patient", p2."Last", p2."First", p2."Chart"
                    FROM APPOINT a1, PATIENT p2
                    WHERE 1=1
                    AND a1."Patient" = p2."Patient"
                    AND a1."Type" IN (0,1,2)
                    AND TRIM(a1."Producer") = TRIM('''||vProducer||''')
                    AND a1."Status" = 0
                    AND TRUNC(a1."Date") BETWEEN ADD_MONTHS(TO_DATE('''||vCQMEDate||'''), -24) AND TO_DATE('''||vCQMEDate||''')
                    AND MU_CORE_PKG.CALC_PT_AGE(a1."Patient", ('''||vCQMSDate||''')) >= 17
                    AND EXISTS (SELECT 1 FROM
                                PITEM p3, FITEM f1
                                WHERE 1=1
                                AND TRIM(p3."FormCode") = TRIM('''||vFormCode||''')
                                AND p3."FItem" = f1."FItem"
                                AND p3."Patient" = a1."Patient"
                                AND TRUNC(p3."Date") BETWEEN ADD_MONTHS(TO_DATE('''||vCQMEDate||'''), -24) AND TO_DATE('''||vCQMEDate||''')
                                AND TRIM(f1."Code") IN ('''||vCodeList||''')
                                AND TRIM(p3."AnsListRefCode") IN ('''||vRefCodeList||''')
                                AND p3."AuditNumber" = (SELECT MAX(p3n."AuditNumber") FROM
                                                        PITEM p3n, FITEM f1n
                                                        WHERE 1=1
                                                        AND TRIM(p3n."FormCode") = TRIM(p3."FormCode")
                                                        AND p3n."FItem" = f1n."FItem"
                                                        AND p3n."Patient" = p3."Patient"
                                                        AND p3n."AppDate" IS NOT NULL
                                                        AND TRIM(f1n."Code") = TRIM(f1."Code")
                                                        AND TRUNC(p3n."Date") <= TO_DATE(a1."Date")
                                                        GROUP BY f1n."Code"))
                    AND EXISTS (SELECT 1
                                FROM TRX t2
                                WHERE 1=1
                                AND TRIM(t2."Procedure") = TRIM('''||vADACode||''')
                                AND TRIM(t2."Status") = ''C''
                                AND t2."Deleted" = 0
                                AND t2."Patient" = a1."Patient"
                                AND TRUNC(t2."Date") BETWEEN ADD_MONTHS(TO_DATE('''||vCQMSDate||'''), -24) AND TO_DATE('''||vCQMEDate||'''))
                    ';
        OPEN MUWeakCursor FOR vSQLStmt;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE cqm2_nqf0028a_d(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vSQLStmt    VARCHAR2(5000 );
        vProducer     CHAR(10 ) := '';
        vCQMSDate     DATE;
        vCQMEDate     DATE;
        vMethod       CHAR := 'A';
        vFormCode CHAR(6 ) := 'MUMDH';
        vCodeList  VARCHAR2(150 ) := 'MDH_SMK01';
    BEGIN
        IF vMethod = 'A' THEN
          vCQMSDate := TRUNC(TO_DATE(vREndDate),'YEAR');
          vCQMEDate := LAST_DAY(ADD_MONTHS(TO_DATE(vREndDate),12 - TO_NUMBER(TO_CHAR(TO_DATE(vREndDate),'mm'))));
        END IF;

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                    SELECT "Patient", "Last", "First", "Chart", MAX("Flag") as "Flag"
                    FROM
                    (
                          SELECT a1."Date", a1."Patient" as "Patient", p1."Last", p1."First", p1."Chart",
                          NVL((SELECT DISTINCT 1 FROM
                                PITEM p3, FITEM f1
                                WHERE 1=1
                                AND TRIM(p3."FormCode") = TRIM('''||vFormCode||''')
                                AND p3."FItem" = f1."FItem"
                                AND p3."Patient" = p1."Patient"
                                AND TRIM(f1."Code") IN ('''||vCodeList||''')
                                AND p3."Status" = 0
                                AND p3."AnsYes" <> -1
                                AND TRUNC(p3."Date") BETWEEN ADD_MONTHS(TO_DATE(a1."Date"), -24) AND TO_DATE(a1."Date")
                                AND p3."AuditNumber" = (SELECT MAX(p3n."AuditNumber")
                                                        FROM PITEM p3n, FITEM f1n
                                                        WHERE 1=1
                                                        AND p3n."FormCode" = p3."FormCode"
                                                        AND p3n."FItem" = f1n."FItem"
                                                        AND p3n."Patient" = p3."Patient"
                                                        AND f1n."Code" = f1."Code"
                                                        AND TRUNC(p3n."Date") <= TRUNC(TO_DATE(a1."Date"))
                                                        GROUP BY f1n."Code"
                                                        )
                                )
                               ,0) as "Flag"
                          FROM APPOINT a1, PATIENT p1
                          WHERE 1=1
                          AND a1."Patient" = p1."Patient"
                          AND a1."Type" IN (0,1,2)
                          AND TRIM(a1."Producer") = TRIM('''||vProducer||''')
                          AND a1."Status" = 0
                          AND TRUNC(a1."Date")  BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
                          AND MU_CORE_PKG.CALC_PT_AGE(a1."Patient", TO_DATE('''||vCQMSDate||''')) >= 18
                    )
                    GROUP BY "Patient", "Last", "First", "Chart"
                    HAVING COUNT(DISTINCT ("Date")) > 2
                    ';
        OPEN MUWeakCursor FOR vSQLStmt;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE cqm2_nqf0028a_n(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vSQLStmt    VARCHAR2(5000 );
        vProducer     CHAR(10 ) := '';
        vCQMSDate     DATE;
        vCQMEDate     DATE;
        vMethod       CHAR := 'A';
        vFormCode CHAR(6 ) := 'MUMDH';
        vCodeList  VARCHAR2(150 ) := 'MDH_SMK01';
    BEGIN
        IF vMethod = 'A' THEN
          vCQMSDate := TRUNC(TO_DATE(vREndDate),'YEAR');
          vCQMEDate := LAST_DAY(ADD_MONTHS(TO_DATE(vREndDate),12 - TO_NUMBER(TO_CHAR(TO_DATE(vREndDate),'mm'))));
        END IF;

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                    SELECT "Last", "First", "Chart"
                    FROM
                    (
                          SELECT a1."Date", p1."Last", p1."First", p1."Chart",
                          NVL((SELECT DISTINCT 1 FROM
                                PITEM p3, FITEM f1
                                WHERE 1=1
                                AND TRIM(p3."FormCode") = TRIM('''||vFormCode||''')
                                AND p3."FItem" = f1."FItem"
                                AND p3."Patient" = p1."Patient"
                                AND TRIM(f1."Code") IN ('''||vCodeList||''')
                                AND p3."Status" = 0
                                AND p3."AnsYes" <> -1
                                AND TRUNC(p3."Date") BETWEEN ADD_MONTHS(TO_DATE(a1."Date"), -24) AND TO_DATE(a1."Date")
                                AND p3."AuditNumber" = (SELECT MAX(p3n."AuditNumber")
                                                        FROM PITEM p3n, FITEM f1n
                                                        WHERE 1=1
                                                        AND p3n."FormCode" = p3."FormCode"
                                                        AND p3n."FItem" = f1n."FItem"
                                                        AND p3n."Patient" = p3."Patient"
                                                        AND f1n."Code" = f1."Code"
                                                        AND TRUNC(p3n."Date") <= TRUNC(TO_DATE(a1."Date"))
                                                        GROUP BY f1n."Code"
                                                        )
                                )
                               ,0) as "Flag"
                          FROM APPOINT a1, PATIENT p1
                          WHERE 1=1
                          AND a1."Patient" = p1."Patient"
                          AND a1."Type" IN (0,1,2)
                          AND TRIM(a1."Producer") = TRIM('''||vProducer||''')
                          AND a1."Status" = 0
                          AND TRUNC(a1."Date") BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
                          AND MU_CORE_PKG.CALC_PT_AGE(a1."Patient", TO_DATE('''||vCQMSDate||''')) >= 18
                    )
                    GROUP BY "Last", "First", "Chart"
                    HAVING COUNT(DISTINCT ("Date")) >= 2 AND MAX("Flag") = 1
                    ';
        OPEN MUWeakCursor FOR vSQLStmt;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE cqm2_nqf0028b_d(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vSQLStmt    VARCHAR2(5000 );
        vProducer     CHAR(10 ) := '';
        vCQMSDate     DATE;
        vCQMEDate     DATE;
        vMethod       CHAR := 'A';
        vFormCode CHAR(6 ) := 'MUMDH';
        vCodeList  VARCHAR2(150 ) := 'MDH_SMK01';
        -- ADA Code for Tobacco Counselling
        vADACode      CHAR(7 ) := 'D1320';
    BEGIN
        IF vMethod = 'A' THEN
          vCQMSDate := TRUNC(TO_DATE(vREndDate),'YEAR');
          vCQMEDate := LAST_DAY(ADD_MONTHS(TO_DATE(vREndDate),12 - TO_NUMBER(TO_CHAR(TO_DATE(vREndDate),'mm'))));
        END IF;

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                    SELECT "Patient", "Last", "First", "Chart", MAX("Flag") as "Flag"
                    FROM
                    (
                          SELECT a1."Date" as "Date", a1."Patient" as "Patient", p1."Last" as "Last", p1."First" as "First", p1."Chart" as "Chart",
                                NVL((SELECT DISTINCT 1
                                      FROM TRX t2
                                      WHERE 1=1
                                      AND TRIM(t2."Procedure") = TRIM('''||vADACode||''')
                                      AND TRIM(t2."Status") = ''C''
                                      AND t2."Deleted" = 0
                                      AND t2."Patient" = p1."Patient"
                                      AND TRUNC(t2."Date") BETWEEN ADD_MONTHS(TO_DATE(a1."Date"), -24) AND TO_DATE(a1."Date")),0) AS "Flag"
                          FROM APPOINT a1, PATIENT p1
                          WHERE 1=1
                          AND a1."Patient" = p1."Patient"
                          AND a1."Type" IN (0,1,2)
                          AND TRIM(a1."Producer") = TRIM('''||vProducer||''')
                          AND a1."Status" = 0
						  AND TRUNC(a1."Date") BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
                          AND MU_CORE_PKG.CALC_PT_AGE(p1."Patient", TO_DATE('''||vCQMSDate||''')) >= 18
                          AND EXISTS (SELECT 1 FROM
                                    PITEM p3, FITEM f1
                                    WHERE 1=1
                                    AND TRIM(p3."FormCode") = TRIM('''||vFormCode||''')
                                    AND p3."FItem" = f1."FItem"
                                    AND p3."Patient" = a1."Patient"
                                    AND TRIM(f1."Code") IN ('''||vCodeList||''')
									AND p3."AnsYes" = 1
                                    AND TRUNC(p3."Date") BETWEEN ADD_MONTHS(TO_DATE(a1."Date"), -24) AND TO_DATE(a1."Date")
                                    AND p3."Status" = 0
                                    AND p3."AuditNumber" = (SELECT MAX(p3n."AuditNumber") FROM
                                                            PITEM p3n, FITEM f1n
                                                            WHERE 1=1
                                                            AND TRIM(p3n."FormCode") = TRIM(p3."FormCode")
                                                            AND p3n."FItem" = f1n."FItem"
                                                            AND p3n."Patient" = p3."Patient"
                                                            AND p3n."AppDate" IS NOT NULL
                                                            AND TRIM(f1n."Code") = TRIM(f1."Code")
                                                            AND TRUNC(p3n."Date") <= TO_DATE(a1."Date")
                                                            GROUP BY f1n."Code")
                                    )
                        AND EXISTS( SELECT 1
                                    FROM APPOINT ap2
                                    WHERE 1=1
                                    AND ap2."Patient" = a1."Patient"
                                    AND ap2."Type" IN (0,1,2)
                                    AND TRIM(ap2."Producer") = TRIM('''||vProducer||''')
                                    AND ap2."Status" = 0
                                    AND TRUNC(ap2."Date")  BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
                                    AND MU_CORE_PKG.CALC_PT_AGE(a1."Patient", TO_DATE('''||vCQMEDate||''')) >= 18
                                    GROUP BY ap2."Patient"
                                    HAVING (COUNT(DISTINCT ap2."Date") >=2))
                    )
                    GROUP BY "Patient", "Last", "First", "Chart"
                    ';
        OPEN MUWeakCursor FOR vSQLStmt;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE cqm2_nqf0028b_n(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vSQLStmt    VARCHAR2(5000 );
        vProducer     CHAR(10 ) := '';
        vCQMSDate     DATE;
        vCQMEDate     DATE;
        vMethod       CHAR := 'A';
        vFormCode CHAR(6 ) := 'MUMDH';
        vCodeList  VARCHAR2(150 ) := 'MDH_SMK01';
        -- ADA Code for Tobacco Counselling
        vADACode      CHAR(7 ) := 'D1320';
    BEGIN
        IF vMethod = 'A' THEN
          vCQMSDate := TRUNC(TO_DATE(vREndDate),'YEAR');
          vCQMEDate := LAST_DAY(ADD_MONTHS(TO_DATE(vREndDate),12 - TO_NUMBER(TO_CHAR(TO_DATE(vREndDate),'mm'))));
        END IF;

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                    SELECT "Last", "First", "Chart"
                    FROM
                    (
                          SELECT a1."Date" as "Date", p1."Last" as "Last", p1."First" as "First", p1."Chart" as "Chart",
                                NVL((SELECT DISTINCT 1
                                      FROM TRX t2
                                      WHERE 1=1
                                      AND TRIM(t2."Procedure") = TRIM('''||vADACode||''')
                                      AND TRIM(t2."Status") = ''C''
                                      AND t2."Deleted" = 0
                                      AND t2."Patient" = a1."Patient"
                                      AND TRUNC(t2."Date") BETWEEN ADD_MONTHS(TO_DATE(a1."Date"), -24) AND TO_DATE(a1."Date")),0) AS "Flag"
                          FROM APPOINT a1, PATIENT p1
                          WHERE 1=1
                          AND a1."Patient" = p1."Patient"
                          AND a1."Type" IN (0,1,2)
                          AND TRIM(a1."Producer") = TRIM('''||vProducer||''')
                          AND a1."Status" = 0
                          AND TRUNC(a1."Date") BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
						  AND MU_CORE_PKG.CALC_PT_AGE(p1."Patient", TO_DATE('''||vCQMSDate||''')) >= 18
                          AND EXISTS (SELECT 1 FROM
                                    PITEM p3, FITEM f1
                                    WHERE 1=1
                                    AND TRIM(p3."FormCode") = TRIM('''||vFormCode||''')
                                    AND p3."FItem" = f1."FItem"
                                    AND p3."Patient" = a1."Patient"
                                    AND TRIM(f1."Code") IN ('''||vCodeList||''')
									AND p3."AnsYes" = 1
                                    AND TRUNC(p3."Date") BETWEEN ADD_MONTHS(TO_DATE(a1."Date"), -24) AND TO_DATE(a1."Date")
                                    AND p3."Status" = 0
                                    AND p3."AuditNumber" = (SELECT MAX(p3n."AuditNumber") FROM
                                                            PITEM p3n, FITEM f1n
                                                            WHERE 1=1
                                                            AND TRIM(p3n."FormCode") = TRIM(p3."FormCode")
                                                            AND p3n."FItem" = f1n."FItem"
                                                            AND p3n."Patient" = p3."Patient"
                                                            AND p3n."AppDate" IS NOT NULL
                                                            AND TRIM(f1n."Code") = TRIM(f1."Code")
                                                            AND TRUNC(p3n."Date") <= TO_DATE(a1."Date")
                                                            GROUP BY f1n."Code")
                                            )
                        AND EXISTS( SELECT 1
                                    FROM APPOINT ap2
                                    WHERE 1=1
                                    AND ap2."Patient" = a1."Patient"
                                    AND ap2."Type" IN (0,1,2)
                                    AND TRIM(ap2."Producer") = TRIM('''||vProducer||''')
                                    AND ap2."Status" = 0
                                    AND TRUNC(ap2."Date")  BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
                                    AND MU_CORE_PKG.CALC_PT_AGE(a1."Patient", TO_DATE('''||vCQMEDate||''')) >= 18
                                    GROUP BY ap2."Patient"
                                    HAVING (COUNT(DISTINCT ap2."Date") >=2))
                    )
                    GROUP BY "Last", "First", "Chart"
                    HAVING MAX("Flag") = 1
                    ';
        OPEN MUWeakCursor FOR vSQLStmt;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE cqm3_nqf0421a_d(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vSQLStmt    VARCHAR2(18000 );
        vProducer     CHAR(10 ) := '';
        vCQMSDate     DATE;
        vCQMEDate     DATE;
        vMethod       CHAR := 'A';
        vFormCode CHAR(6 ) := 'MUMDH';
        vCodeList  VARCHAR2(150 ) := 'PT_STD_BMI';
        vCodeList2  VARCHAR2(150 ) := 'MDH_PREG';
        vCodeList3  VARCHAR2(150 ) := 'MDH_TILL';
        vCodeList4  VARCHAR2(150 ) := 'MDH_PEXAM';
        vAnsListRef  VARCHAR2(150 ) := 'PEXAMD1'', ''PEXAMD2'', ''PEXAMD3';
        -- ADA Code for Nutrition Counselling
        vADACode      CHAR(7 ) := 'D1310';
    BEGIN
        IF vMethod = 'A' THEN
          vCQMSDate := TRUNC(TO_DATE(vREndDate),'YEAR');
          vCQMEDate := LAST_DAY(ADD_MONTHS(TO_DATE(vREndDate),12 - TO_NUMBER(TO_CHAR(TO_DATE(vREndDate),'mm'))));
        END IF;

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                    SELECT "Patient", "Last", "First", "Chart", MAX("Flag") as "Flag" FROM
                          (SELECT ap1."Patient" AS "Patient",  p1."Last" AS "Last", p1."First" AS "First", p1."Chart" AS "Chart",
                                NVL((SELECT DISTINCT 1
                                                  FROM PITEM p3, FITEM f1
                                                  WHERE 1=1
                                                  AND p3."FItem" = f1."FItem"
                                                  AND p3."Patient" = ap1."Patient"
                                                  AND TRIM(p3."FormCode") = TRIM('''||vFormCode||''')
                                                  AND TRUNC(p3."Date") BETWEEN ADD_MONTHS(TO_DATE(ap1."Date"), -6) AND TO_DATE(ap1."Date")
                                                  AND TRIM(f1."Code") IN TRIM('''||vCodeList||''')
                                                  AND NVL(TRIM(p3."AnsText"),''Invalid inputs provided.'') != ''Invalid inputs provided.''
												  AND p3."Status" = 0
                                                  AND (CASE WHEN (NVL(TRIM(p3."AnsText"),0) >= 22 AND NVL(TRIM(p3."AnsText"),''Invalid inputs provided.'') < 30) THEN 1
                                                            WHEN ((NVL(TRIM(p3."AnsText"),0) >= 30 OR
                                                                   NVL(TRIM(p3."AnsText"),0) < 22) AND
                                                                    EXISTS (SELECT 1
                                                                            FROM TRX t2
                                                                            WHERE 1=1
                                                                            AND TRIM(t2."Procedure") = TRIM('''||vADACode||''')
                                                                            AND TRIM(t2."Status") = ''C''
                                                                            AND t2."Deleted" = 0
                                                                            AND t2."Patient" = ap1."Patient"
                                                                            AND TRUNC(t2."Date") = TRUNC(p3."Date")))
                                                            THEN 1
                                                            ELSE 0
                                                       END) = 1
                                                 AND p3."AuditNumber" = (SELECT MAX(p3n."AuditNumber")
                                                                          FROM PITEM p3n, FITEM f1n
                                                                          WHERE 1=1
                                                                          AND TRIM(p3n."FormCode") = TRIM(p3."FormCode")
                                                                          AND p3n."FItem" = f1n."FItem"
                                                                          AND p3n."Patient" = p3."Patient"
                                                                          AND p3n."AppDate" IS NOT NULL
                                                                          AND TRIM(f1n."Code") = TRIM(f1."Code")
                                                                          AND TRUNC(p3n."Date")  = TO_DATE(p3."Date")
                                                                          GROUP BY f1n."Code")
                                      AND NOT EXISTS (SELECT 1
                                                      FROM APPOINT ap2
                                                      WHERE 1=1
                                                      AND ap2."Type" IN (0,1,2)
                                                      AND TRIM(ap2."Producer") = TRIM('''||vProducer||''')
                                                      AND ap2."Patient" = ap1."Patient"
                                                      AND ap2."Status" = 0
                                                      AND TRUNC(ap2."Date") BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
                                                      AND MU_CORE_PKG.CALC_PT_AGE(ap2."Patient",TO_DATE('''||vCQMSDate||''')) >= 65
                                                      AND NOT EXISTS (SELECT 1
                                                                      FROM PITEM p3, FITEM f1
                                                                      WHERE 1=1
                                                                      AND p3."FItem" = f1."FItem"
                                                                      AND p3."Patient" = ap2."Patient"
                                                                      AND TRIM(p3."FormCode") = TRIM('''||vFormCode||''')
                                                                      AND TRUNC(p3."Date") BETWEEN ADD_MONTHS(TO_DATE(ap2."Date"), -6) AND TO_DATE(ap2."Date")
                                                                      AND TRIM(f1."Code") IN TRIM('''||vCodeList||''')
                                                                      AND NVL(TRIM(p3."AnsText"),''Invalid inputs provided.'') != ''Invalid inputs provided.''
																	  AND p3."Status" = 0
                                                                      AND (CASE WHEN (NVL(TRIM(p3."AnsText"),0) >= 22 AND NVL(TRIM(p3."AnsText"),''Invalid inputs provided.'') < 30) THEN 1
                                                                                WHEN ((NVL(TRIM(p3."AnsText"),0) >= 30 OR
                                                                                       NVL(TRIM(p3."AnsText"),0) < 22) AND
                                                                                        EXISTS (SELECT 1
                                                                                                FROM TRX t2
                                                                                                WHERE 1=1
                                                                                                AND TRIM(t2."Procedure") = TRIM('''||vADACode||''')
                                                                                                AND TRIM(t2."Status") = ''C''
                                                                                                AND t2."Deleted" = 0
                                                                                                AND t2."Patient" = ap1."Patient"
                                                                                                AND TRUNC(t2."Date") = TRUNC(p3."Date")))
                                                                                THEN 1
                                                                                ELSE 0
                                                                           END) = 1
                                                                      AND p3."AuditNumber" = (SELECT MAX(p3n."AuditNumber")
                                                                                              FROM PITEM p3n, FITEM f1n
                                                                                              WHERE 1=1
                                                                                              AND TRIM(p3n."FormCode") = TRIM(p3."FormCode")
                                                                                              AND p3n."FItem" = f1n."FItem"
                                                                                              AND p3n."Patient" = p3."Patient"
                                                                                              AND p3n."AppDate" IS NOT NULL
                                                                                              AND TRIM(f1n."Code") = TRIM(f1."Code")
                                                                                              AND TRUNC(p3n."Date") = TO_DATE(p3."Date")
                                                                                              GROUP BY f1n."Code")
                                                                      )
                                                        )
                                  ),0) AS "Flag",
                                NVL((SELECT DISTINCT 1
                                      FROM APPOINT ap2
                                      WHERE 1=1
                                      AND ap2."Type" IN (0,1,2)
                                      AND TRIM(ap2."Producer") = TRIM('''||vProducer||''')
                                      AND ap2."Patient" = ap1."Patient"
                                      AND ap2."Status" = 0
                                      AND TRUNC(ap2."Date") BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
                                      AND MU_CORE_PKG.CALC_PT_AGE(ap2."Patient",TO_DATE('''||vCQMSDate||''')) >= 65
                                      AND (EXISTS (SELECT 1 FROM
                                                            PITEM p4, FITEM f2
                                                            WHERE 1=1
                                                            AND p4."FItem" = f2."FItem"
                                                            AND p4."Patient" = ap2."Patient"
                                                            AND TRIM(p4."FormCode") = TRIM('''||vFormCode||''')
                                                            AND TRIM(f2."Code") = TRIM('''||vCodeList2||''')
                                                            AND p4."AnsYes" = 1
                                                            AND TRUNC(p4."Date")  = (ap2."Date")
                                                            AND p4."AppDate" IS NOT NULL
                                                            AND p4."AuditNumber" = (SELECT MAX(p4n."AuditNumber") FROM
                                                                                    PITEM p4n, FITEM f2n
                                                                                    WHERE 1=1
                                                                                    AND TRIM(p4n."FormCode") = TRIM(p4."FormCode")
                                                                                    AND p4n."FItem" = f2n."FItem"
                                                                                    AND p4n."Patient" = p4."Patient"
                                                                                    AND p4n."AppDate" IS NOT NULL
                                                                                    AND TRIM(f2n."Code") = TRIM(f2."Code")
                                                                                    AND TRUNC(p4n."Date") = TO_DATE(ap2."Date")
                                                                                    GROUP BY f2n."Code")
                                                            )
                                            OR EXISTS (SELECT 1 FROM
                                                            PITEM p4, FITEM f2
                                                            WHERE 1=1
                                                            AND p4."FItem" = f2."FItem"
                                                            AND p4."Patient" = ap2."Patient"
                                                            AND TRIM(p4."FormCode") = TRIM('''||vFormCode||''')
                                                            AND TRIM(f2."Code") = TRIM('''||vCodeList3||''')
                                                            AND p4."AnsYes" = 1
                                                            AND TRUNC(p4."Date")  = (ap2."Date")
                                                            AND p4."AppDate" IS NOT NULL
                                                            AND p4."AuditNumber" = (SELECT MAX(p4n."AuditNumber") FROM
                                                                                    PITEM p4n, FITEM f2n
                                                                                    WHERE 1=1
                                                                                    AND TRIM(p4n."FormCode") = TRIM(p4."FormCode")
                                                                                    AND p4n."FItem" = f2n."FItem"
                                                                                    AND p4n."Patient" = p4."Patient"
                                                                                    AND p4n."AppDate" IS NOT NULL
                                                                                    AND TRIM(f2n."Code") = TRIM(f2."Code")
                                                                                    AND TRUNC(p4n."Date") = TO_DATE(ap2."Date")
                                                                                    GROUP BY f2n."Code")
                                                            )
                                            OR EXISTS (SELECT 1 FROM
                                                            PITEM p5, FITEM f3
                                                            WHERE 1=1
                                                            AND p5."FItem" = f3."FItem"
                                                            AND p5."Patient" = ap2."Patient"
                                                            AND TRIM(p5."FormCode") = TRIM('''||vFormCode||''')
                                                            AND TRIM(f3."Code") = TRIM('''||vCodeList4||''')
                                                            AND TRIM(p5."AnsListRefCode") IN ('''||vAnsListRef||''')
                                                            AND TRUNC(p5."Date")  = (ap2."Date")
                                                            AND p5."AppDate" IS NOT NULL
                                                            AND p5."AuditNumber" = (SELECT MAX(p5n."AuditNumber") FROM
                                                                                    PITEM p5n, FITEM f3n
                                                                                    WHERE 1=1
                                                                                    AND TRIM(p5n."FormCode") = TRIM(f3."FormCode")
                                                                                    AND p5n."FItem" = f3n."FItem"
                                                                                    AND p5n."Patient" = p5."Patient"
                                                                                    AND p5n."AppDate" IS NOT NULL
                                                                                    AND TRIM(f3n."Code") = TRIM(f3."Code")
                                                                                    AND TRUNC(p5n."Date") = TO_DATE(ap2."Date")
                                                                                    GROUP BY f3n."Code")
                                                            )
                                            )
                                    ),0) AS "Flag2"
                            FROM APPOINT ap1, PATIENT p1
                            WHERE 1=1
                            AND ap1."Patient" = p1."Patient"
                            AND ap1."Type" IN (0,1,2)
                            AND TRIM(ap1."Producer") = TRIM('''||vProducer||''')
                            AND ap1."Status" = 0
                            AND TRUNC(ap1."Date")  BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
                            AND MU_CORE_PKG.CALC_PT_AGE(ap1."Patient", TO_DATE('''||vCQMSDate||''')) >= 65
                            )
                    GROUP BY "Patient","Last", "First", "Chart"
                    HAVING MAX("Flag2") = 0
                    ';
        OPEN MUWeakCursor FOR vSQLStmt;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE cqm3_nqf0421a_n(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vSQLStmt    VARCHAR2(24000 );
        vProducer     CHAR(10 ) := '';
        vCQMSDate     DATE;
        vCQMEDate     DATE;
        vMethod       CHAR := 'A';
        vFormCode CHAR(6 ) := 'MUMDH';
        vCodeList  VARCHAR2(150 ) := 'PT_STD_BMI';
        vCodeList2  VARCHAR2(150 ) := 'MDH_PREG';
        vCodeList3  VARCHAR2(150 ) := 'MDH_TILL';
        vCodeList4  VARCHAR2(150 ) := 'MDH_PEXAM';
        vAnsListRef  VARCHAR2(150 ) := 'PEXAMD1'', ''PEXAMD2'', ''PEXAMD3';
        -- ADA Code for Nutrition Counselling
        vADACode      CHAR(7 ) := 'D1310';
    BEGIN
        IF vMethod = 'A' THEN
          vCQMSDate := TRUNC(TO_DATE(vREndDate),'YEAR');
          vCQMEDate := LAST_DAY(ADD_MONTHS(TO_DATE(vREndDate),12 - TO_NUMBER(TO_CHAR(TO_DATE(vREndDate),'mm'))));
        END IF;

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                    SELECT a1."Patient",  p1."Last", p1."First", p1."Chart"
                    FROM APPOINT a1, PATIENT p1
                    WHERE 1=1
                    AND a1."Patient" = p1."Patient"
                    AND a1."Type" IN (0,1,2)
                    AND TRIM(a1."Producer") = TRIM('''||vProducer||''')
                    AND a1."Status" = 0
                    AND TRUNC(a1."Date") BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
                    AND MU_CORE_PKG.CALC_PT_AGE(a1."Patient", TO_DATE('''||vCQMSDate||''')) >= 65
                    AND EXISTS (SELECT 1
                                FROM PITEM p3, FITEM f1
                                WHERE 1=1
                                AND p3."FItem" = f1."FItem"
                                AND p3."Patient" = a1."Patient"
                                AND TRIM(p3."FormCode") = TRIM('''||vFormCode||''')
                                AND TRUNC(p3."Date") BETWEEN ADD_MONTHS(TO_DATE(a1."Date"), -6) AND TO_DATE(a1."Date")
                                AND TRIM(f1."Code") IN TRIM('''||vCodeList||''')
                                AND NVL(TRIM(p3."AnsText"),''Invalid inputs provided.'') != ''Invalid inputs provided.''
                                AND (CASE WHEN (NVL(TRIM(p3."AnsText"),0) >= 22 AND NVL(TRIM(p3."AnsText"),''Invalid inputs provided.'') < 30) THEN 1
                                          WHEN ((NVL(TRIM(p3."AnsText"),0) >= 30 OR
                                                 NVL(TRIM(p3."AnsText"),0) < 22) AND
                                                EXISTS (SELECT 1
                                                        FROM TRX t2
                                                        WHERE 1=1
                                                        AND TRIM(t2."Procedure") = TRIM('''||vADACode||''')
                                                        AND TRIM(t2."Status") = ''C''
                                                        AND t2."Deleted" = 0
                                                        AND t2."Patient" = a1."Patient"
                                                        AND TRUNC(t2."Date") = TRUNC(p3."Date")))
                                          THEN 1
                                          ELSE 0
                                     END) = 1
                               AND p3."AuditNumber" = (SELECT MAX(p3n."AuditNumber")
                                                        FROM PITEM p3n, FITEM f1n
                                                        WHERE 1=1
                                                        AND TRIM(p3n."FormCode") = TRIM(p3."FormCode")
                                                        AND p3n."FItem" = f1n."FItem"
                                                        AND p3n."Patient" = p3."Patient"
                                                        AND p3n."AppDate" IS NOT NULL
                                                        AND TRIM(f1n."Code") = TRIM(f1."Code")
                                                        AND TRUNC(p3n."Date")  = TO_DATE(p3."Date")
                                                        GROUP BY f1n."Code")
                              )
                    AND NOT EXISTS (SELECT 1
                                    FROM APPOINT ap2
                                    WHERE 1=1
                                    AND ap2."Type" IN (0,1,2)
                                    AND TRIM(ap2."Producer") = TRIM('''||vProducer||''')
                                    AND ap2."Patient" = a1."Patient"
                                    AND ap2."Status" = 0
                                    AND TRUNC(ap2."Date") BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
                                    AND MU_CORE_PKG.CALC_PT_AGE(ap2."Patient",TO_DATE('''||vCQMSDate||''')) >= 65
                                    AND NOT EXISTS (SELECT 1
                                                    FROM PITEM p3, FITEM f1
                                                    WHERE 1=1
                                                    AND p3."FItem" = f1."FItem"
                                                    AND p3."Patient" = ap2."Patient"
                                                    AND TRIM(p3."FormCode") = TRIM('''||vFormCode||''')
                                                    AND TRUNC(p3."Date") BETWEEN ADD_MONTHS(TO_DATE(ap2."Date"), -6) AND TO_DATE(ap2."Date")
                                                    AND TRIM(f1."Code") IN TRIM('''||vCodeList||''')
                                                    AND NVL(TRIM(p3."AnsText"),''Invalid inputs provided.'') != ''Invalid inputs provided.''
                                                    AND (CASE WHEN (NVL(TRIM(p3."AnsText"),0) >= 22 AND NVL(TRIM(p3."AnsText"),''Invalid inputs provided.'') < 30) THEN 1
                                                              WHEN ((NVL(TRIM(p3."AnsText"),0) >= 30 OR
                                                                     NVL(TRIM(p3."AnsText"),0) < 22) AND
                                                                      EXISTS (SELECT 1
                                                                              FROM TRX t2
                                                                              WHERE 1=1
                                                                              AND TRIM(t2."Procedure") = TRIM('''||vADACode||''')
                                                                              AND TRIM(t2."Status") = ''C''
                                                                              AND t2."Deleted" = 0
                                                                              AND t2."Patient" = a1."Patient"
                                                                              AND TRUNC(t2."Date") = TRUNC(p3."Date")))
                                                              THEN 1
                                                              ELSE 0
                                                         END) = 1
                                                    AND p3."AuditNumber" = (SELECT MAX(p3n."AuditNumber")
                                                                            FROM PITEM p3n, FITEM f1n
                                                                            WHERE 1=1
                                                                            AND TRIM(p3n."FormCode") = TRIM(p3."FormCode")
                                                                            AND p3n."FItem" = f1n."FItem"
                                                                            AND p3n."Patient" = p3."Patient"
                                                                            AND p3n."AppDate" IS NOT NULL
                                                                            AND TRIM(f1n."Code") = TRIM(f1."Code")
                                                                            AND TRUNC(p3n."Date") = TO_DATE(p3."Date")
                                                                            GROUP BY f1n."Code")
                                                    )
                                      )
                    AND NOT EXISTS (SELECT 1
                                    FROM APPOINT ap2
                                    WHERE 1=1
                                    AND ap2."Type" IN (0,1,2)
                                    AND TRIM(ap2."Producer") = TRIM('''||vProducer||''')
                                    AND ap2."Patient" = a1."Patient"
                                    AND ap2."Status" = 0
                                    AND TRUNC(ap2."Date") BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
                                    AND MU_CORE_PKG.CALC_PT_AGE(ap2."Patient",TO_DATE('''||vCQMSDate||''')) >= 65
                                    AND NOT EXISTS (SELECT 1
                                                    FROM PITEM p3, FITEM f1
                                                    WHERE 1=1
                                                    AND p3."FItem" = f1."FItem"
                                                    AND p3."Patient" = ap2."Patient"
                                                    AND TRIM(p3."FormCode") = TRIM('''||vFormCode||''')
                                                    AND TRUNC(p3."Date") BETWEEN ADD_MONTHS(TO_DATE(ap2."Date"), -6) AND TO_DATE(ap2."Date")
                                                    AND TRIM(f1."Code") IN TRIM('''||vCodeList||''')
                                                    AND NVL(TRIM(p3."AnsText"),''Invalid inputs provided.'') != ''Invalid inputs provided.''
                                                    AND (CASE WHEN (NVL(TRIM(p3."AnsText"),0) >= 22 AND NVL(TRIM(p3."AnsText"),''Invalid inputs provided.'') < 30) THEN 1
                                                              WHEN ((NVL(TRIM(p3."AnsText"),0) >= 30 OR
                                                                     NVL(TRIM(p3."AnsText"),0) < 22) AND
                                                                      EXISTS (SELECT 1
                                                                              FROM TRX t2
                                                                              WHERE 1=1
                                                                              AND TRIM(t2."Procedure") = TRIM('''||vADACode||''')
                                                                              AND TRIM(t2."Status") = ''C''
                                                                              AND t2."Deleted" = 0
                                                                              AND t2."Patient" = a1."Patient"
                                                                              AND TRUNC(t2."Date") = TRUNC(p3."Date")))
                                                              THEN 1
                                                              ELSE 0
                                                         END) = 1
                                                    AND p3."AuditNumber" = (SELECT MAX(p3n."AuditNumber")
                                                                            FROM PITEM p3n, FITEM f1n
                                                                            WHERE 1=1
                                                                            AND TRIM(p3n."FormCode") = TRIM(p3."FormCode")
                                                                            AND p3n."FItem" = f1n."FItem"
                                                                            AND p3n."Patient" = p3."Patient"
                                                                            AND p3n."AppDate" IS NOT NULL
                                                                            AND TRIM(f1n."Code") = TRIM(f1."Code")
                                                                            AND TRUNC(p3n."Date") = TO_DATE(p3."Date")
                                                                            GROUP BY f1n."Code")
                                                    )
                                      )
                  AND NOT EXISTS (SELECT 1
                                  FROM APPOINT ap2
                                  WHERE 1=1
                                  AND ap2."Type" IN (0,1,2)
                                  AND TRIM(ap2."Producer") = TRIM('''||vProducer||''')
                                  AND ap2."Patient" = a1."Patient"
                                  AND ap2."Status" = 0
                                  AND TRUNC(ap2."Date") BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
                                  AND MU_CORE_PKG.CALC_PT_AGE(ap2."Patient",TO_DATE('''||vCQMSDate||''')) >= 65
                                  AND (EXISTS(SELECT 1 FROM
                                                        PITEM p4, FITEM f2
                                                        WHERE 1=1
                                                        AND p4."FItem" = f2."FItem"
                                                        AND p4."Patient" = ap2."Patient"
                                                        AND TRIM(p4."FormCode") = TRIM('''||vFormCode||''')
                                                        AND TRIM(f2."Code") = TRIM('''||vCodeList2||''')
                                                        AND p4."AnsYes" = 1
                                                        AND TRUNC(p4."Date")  = (ap2."Date")
                                                        AND p4."AppDate" IS NOT NULL
                                                        AND p4."AuditNumber" = (SELECT MAX(p4n."AuditNumber") FROM
                                                                                PITEM p4n, FITEM f2n
                                                                                WHERE 1=1
                                                                                AND TRIM(p4n."FormCode") = TRIM(p4."FormCode")
                                                                                AND p4n."FItem" = f2n."FItem"
                                                                                AND p4n."Patient" = p4."Patient"
                                                                                AND p4n."AppDate" IS NOT NULL
                                                                                AND TRIM(f2n."Code") = TRIM(f2."Code")
                                                                                AND TRUNC(p4n."Date") = TO_DATE(ap2."Date")
                                                                                GROUP BY f2n."Code")
                                                        )
                                        OR EXISTS (SELECT 1 FROM
                                                        PITEM p4, FITEM f2
                                                        WHERE 1=1
                                                        AND p4."FItem" = f2."FItem"
                                                        AND p4."Patient" = ap2."Patient"
                                                        AND TRIM(p4."FormCode") = TRIM('''||vFormCode||''')
                                                        AND TRIM(f2."Code") = TRIM('''||vCodeList3||''')
                                                        AND p4."AnsYes" = 1
                                                        AND TRUNC(p4."Date")  = (ap2."Date")
                                                        AND p4."AppDate" IS NOT NULL
                                                        AND p4."AuditNumber" = (SELECT MAX(p4n."AuditNumber") FROM
                                                                                PITEM p4n, FITEM f2n
                                                                                WHERE 1=1
                                                                                AND TRIM(p4n."FormCode") = TRIM(p4."FormCode")
                                                                                AND p4n."FItem" = f2n."FItem"
                                                                                AND p4n."Patient" = p4."Patient"
                                                                                AND p4n."AppDate" IS NOT NULL
                                                                                AND TRIM(f2n."Code") = TRIM(f2."Code")
                                                                                AND TRUNC(p4n."Date") = TO_DATE(ap2."Date")
                                                                                GROUP BY f2n."Code")
                                                        )
                                        OR EXISTS (SELECT 1 FROM
                                                        PITEM p5, FITEM f3
                                                        WHERE 1=1
                                                        AND p5."FItem" = f3."FItem"
                                                        AND p5."Patient" = ap2."Patient"
                                                        AND TRIM(p5."FormCode") = TRIM('''||vFormCode||''')
                                                        AND TRIM(f3."Code") = TRIM('''||vCodeList4||''')
                                                        AND TRIM(p5."AnsListRefCode") IN ('''||vAnsListRef||''')
                                                        AND TRUNC(p5."Date")  = (ap2."Date")
                                                        AND p5."AppDate" IS NOT NULL
                                                        AND p5."AuditNumber" = (SELECT MAX(p5n."AuditNumber") FROM
                                                                                PITEM p5n, FITEM f3n
                                                                                WHERE 1=1
                                                                                AND TRIM(p5n."FormCode") = TRIM(f3."FormCode")
                                                                                AND p5n."FItem" = f3n."FItem"
                                                                                AND p5n."Patient" = p5."Patient"
                                                                                AND p5n."AppDate" IS NOT NULL
                                                                                AND TRIM(f3n."Code") = TRIM(f3."Code")
                                                                                AND TRUNC(p5n."Date") = TO_DATE(ap2."Date")
                                                                                GROUP BY f3n."Code")
                                                        )
                                        )
                                )

                    GROUP BY a1."Patient", p1."Last", p1."First", p1."Chart"
                    ';
        OPEN MUWeakCursor FOR vSQLStmt;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE cqm3_nqf0421b_d(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vSQLStmt    VARCHAR2(18000 );
        vProducer     CHAR(10 ) := '';
        vCQMSDate     DATE;
        vCQMEDate     DATE;
        vMethod       CHAR := 'A';
        vFormCode CHAR(6 ) := 'MUMDH';
        vCodeList  VARCHAR2(150 ) := 'PT_STD_BMI';
        vCodeList2  VARCHAR2(150 ) := 'MDH_PREG';
        vCodeList3  VARCHAR2(150 ) := 'MDH_TILL';
        vCodeList4  VARCHAR2(150 ) := 'MDH_PEXAM';
        vAnsListRef  VARCHAR2(150 ) := 'PEXAMD1'', ''PEXAMD2'', ''PEXAMD3';
        -- ADA Code for Nutrition Counselling
        vADACode      CHAR(7 ) := 'D1310';
    BEGIN
        IF vMethod = 'A' THEN
          vCQMSDate := TRUNC(TO_DATE(vREndDate),'YEAR');
          vCQMEDate := LAST_DAY(ADD_MONTHS(TO_DATE(vREndDate),12 - TO_NUMBER(TO_CHAR(TO_DATE(vREndDate),'mm'))));
        END IF;

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                    SELECT "Patient", "Last", "First", "Chart", MAX("Flag") as "Flag" FROM
                          (SELECT ap1."Patient" AS "Patient",  p1."Last" AS "Last", p1."First" AS "First", p1."Chart" AS "Chart",
                                NVL((SELECT DISTINCT 1
                                                  FROM PITEM p3, FITEM f1
                                                  WHERE 1=1
                                                  AND p3."FItem" = f1."FItem"
                                                  AND p3."Patient" = ap1."Patient"
                                                  AND TRIM(p3."FormCode") = TRIM('''||vFormCode||''')
                                                  AND TRUNC(p3."Date") BETWEEN ADD_MONTHS(TO_DATE(ap1."Date"), -6) AND TO_DATE(ap1."Date")
                                                  AND TRIM(f1."Code") IN TRIM('''||vCodeList||''')
                                                  AND NVL(TRIM(p3."AnsText"),''Invalid inputs provided.'') != ''Invalid inputs provided.''
                                                  AND (CASE WHEN (NVL(TRIM(p3."AnsText"),0) >= 18.5 AND NVL(TRIM(p3."AnsText"),''Invalid inputs provided.'') < 25) THEN 1
                                                            WHEN ((NVL(TRIM(p3."AnsText"),0) >= 25 OR
                                                                   NVL(TRIM(p3."AnsText"),0) < 18.5) AND
                                                                    EXISTS (SELECT 1
                                                                            FROM TRX t2
                                                                            WHERE 1=1
                                                                            AND TRIM(t2."Procedure") = TRIM('''||vADACode||''')
                                                                            AND TRIM(t2."Status") = ''C''
                                                                            AND t2."Deleted" = 0
                                                                            AND t2."Patient" = ap1."Patient"
                                                                            AND TRUNC(t2."Date") = TRUNC(p3."Date")))
                                                            THEN 1
                                                            ELSE 0
                                                       END) = 1
                                                 AND p3."AuditNumber" = (SELECT MAX(p3n."AuditNumber")
                                                                          FROM PITEM p3n, FITEM f1n
                                                                          WHERE 1=1
                                                                          AND TRIM(p3n."FormCode") = TRIM(p3."FormCode")
                                                                          AND p3n."FItem" = f1n."FItem"
                                                                          AND p3n."Patient" = p3."Patient"
                                                                          AND p3n."AppDate" IS NOT NULL
                                                                          AND TRIM(f1n."Code") = TRIM(f1."Code")
                                                                          AND TRUNC(p3n."Date")  = TO_DATE(p3."Date")
                                                                          GROUP BY f1n."Code")
                                      AND NOT EXISTS (SELECT 1
                                                      FROM APPOINT ap2
                                                      WHERE 1=1
                                                      AND ap2."Type" IN (0,1,2)
                                                      AND TRIM(ap2."Producer") = TRIM('''||vProducer||''')
                                                      AND ap2."Patient" = ap1."Patient"
                                                      AND ap2."Status" = 0
                                                      AND TRUNC(ap2."Date") BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
                                                      AND MU_CORE_PKG.CALC_PT_AGE(ap2."Patient",TO_DATE('''||vCQMSDate||''')) BETWEEN 18 AND 64
                                                      AND NOT EXISTS (SELECT 1
                                                                      FROM PITEM p3, FITEM f1
                                                                      WHERE 1=1
                                                                      AND p3."FItem" = f1."FItem"
                                                                      AND p3."Patient" = ap2."Patient"
                                                                      AND TRIM(p3."FormCode") = TRIM('''||vFormCode||''')
                                                                      AND TRUNC(p3."Date") BETWEEN ADD_MONTHS(TO_DATE(ap2."Date"), -6) AND TO_DATE(ap2."Date")
                                                                      AND TRIM(f1."Code") IN TRIM('''||vCodeList||''')
                                                                      AND NVL(TRIM(p3."AnsText"),''Invalid inputs provided.'') != ''Invalid inputs provided.''
                                                                      AND (CASE WHEN (NVL(TRIM(p3."AnsText"),0) >= 18.5 AND NVL(TRIM(p3."AnsText"),''Invalid inputs provided.'') < 25) THEN 1
                                                                                WHEN ((NVL(TRIM(p3."AnsText"),0) >= 25 OR
                                                                                       NVL(TRIM(p3."AnsText"),0) < 18.5) AND
                                                                                        EXISTS (SELECT 1
                                                                                                FROM TRX t2
                                                                                                WHERE 1=1
                                                                                                AND TRIM(t2."Procedure") = TRIM('''||vADACode||''')
                                                                                                AND TRIM(t2."Status") = ''C''
                                                                                                AND t2."Deleted" = 0
                                                                                                AND t2."Patient" = ap1."Patient"
                                                                                                AND TRUNC(t2."Date") = TRUNC(p3."Date")))
                                                                                THEN 1
                                                                                ELSE 0
                                                                           END) = 1
                                                                      AND p3."AuditNumber" = (SELECT MAX(p3n."AuditNumber")
                                                                                              FROM PITEM p3n, FITEM f1n
                                                                                              WHERE 1=1
                                                                                              AND TRIM(p3n."FormCode") = TRIM(p3."FormCode")
                                                                                              AND p3n."FItem" = f1n."FItem"
                                                                                              AND p3n."Patient" = p3."Patient"
                                                                                              AND p3n."AppDate" IS NOT NULL
                                                                                              AND TRIM(f1n."Code") = TRIM(f1."Code")
                                                                                              AND TRUNC(p3n."Date") = TO_DATE(p3."Date")
                                                                                              GROUP BY f1n."Code")
                                                                      )
                                                        )
                                  ),0) AS "Flag",
                                NVL((SELECT DISTINCT 1
                                      FROM APPOINT ap2
                                      WHERE 1=1
                                      AND ap2."Type" IN (0,1,2)
                                      AND TRIM(ap2."Producer") = TRIM('''||vProducer||''')
                                      AND ap2."Patient" = ap1."Patient"
                                      AND ap2."Status" = 0
                                      AND TRUNC(ap2."Date") BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
                                      AND MU_CORE_PKG.CALC_PT_AGE(ap2."Patient",TO_DATE('''||vCQMSDate||''')) BETWEEN 18 AND 64
                                      AND (EXISTS (SELECT 1 FROM
                                                            PITEM p4, FITEM f2
                                                            WHERE 1=1
                                                            AND p4."FItem" = f2."FItem"
                                                            AND p4."Patient" = ap2."Patient"
                                                            AND TRIM(p4."FormCode") = TRIM('''||vFormCode||''')
                                                            AND TRIM(f2."Code") = TRIM('''||vCodeList2||''')
                                                            AND p4."AnsYes" = 1
                                                            AND TRUNC(p4."Date")  = (ap2."Date")
                                                            AND p4."AppDate" IS NOT NULL
                                                            AND p4."AuditNumber" = (SELECT MAX(p4n."AuditNumber") FROM
                                                                                    PITEM p4n, FITEM f2n
                                                                                    WHERE 1=1
                                                                                    AND TRIM(p4n."FormCode") = TRIM(p4."FormCode")
                                                                                    AND p4n."FItem" = f2n."FItem"
                                                                                    AND p4n."Patient" = p4."Patient"
                                                                                    AND p4n."AppDate" IS NOT NULL
                                                                                    AND TRIM(f2n."Code") = TRIM(f2."Code")
                                                                                    AND TRUNC(p4n."Date") = TO_DATE(ap2."Date")
                                                                                    GROUP BY f2n."Code")
                                                            )
                                            OR EXISTS (SELECT 1 FROM
                                                            PITEM p4, FITEM f2
                                                            WHERE 1=1
                                                            AND p4."FItem" = f2."FItem"
                                                            AND p4."Patient" = ap2."Patient"
                                                            AND TRIM(p4."FormCode") = TRIM('''||vFormCode||''')
                                                            AND TRIM(f2."Code") = TRIM('''||vCodeList3||''')
                                                            AND p4."AnsYes" = 1
                                                            AND TRUNC(p4."Date")  = (ap2."Date")
                                                            AND p4."AppDate" IS NOT NULL
                                                            AND p4."AuditNumber" = (SELECT MAX(p4n."AuditNumber") FROM
                                                                                    PITEM p4n, FITEM f2n
                                                                                    WHERE 1=1
                                                                                    AND TRIM(p4n."FormCode") = TRIM(p4."FormCode")
                                                                                    AND p4n."FItem" = f2n."FItem"
                                                                                    AND p4n."Patient" = p4."Patient"
                                                                                    AND p4n."AppDate" IS NOT NULL
                                                                                    AND TRIM(f2n."Code") = TRIM(f2."Code")
                                                                                    AND TRUNC(p4n."Date") = TO_DATE(ap2."Date")
                                                                                    GROUP BY f2n."Code")
                                                            )
                                            OR EXISTS (SELECT 1 FROM
                                                            PITEM p5, FITEM f3
                                                            WHERE 1=1
                                                            AND p5."FItem" = f3."FItem"
                                                            AND p5."Patient" = ap2."Patient"
                                                            AND TRIM(p5."FormCode") = TRIM('''||vFormCode||''')
                                                            AND TRIM(f3."Code") = TRIM('''||vCodeList4||''')
                                                            AND TRIM(p5."AnsListRefCode") IN ('''||vAnsListRef||''')
                                                            AND TRUNC(p5."Date")  = (ap2."Date")
                                                            AND p5."AppDate" IS NOT NULL
                                                            AND p5."AuditNumber" = (SELECT MAX(p5n."AuditNumber") FROM
                                                                                    PITEM p5n, FITEM f3n
                                                                                    WHERE 1=1
                                                                                    AND TRIM(p5n."FormCode") = TRIM(f3."FormCode")
                                                                                    AND p5n."FItem" = f3n."FItem"
                                                                                    AND p5n."Patient" = p5."Patient"
                                                                                    AND p5n."AppDate" IS NOT NULL
                                                                                    AND TRIM(f3n."Code") = TRIM(f3."Code")
                                                                                    AND TRUNC(p5n."Date") = TO_DATE(ap2."Date")
                                                                                    GROUP BY f3n."Code")
                                                            )
                                            )
                                    ),0) AS "Flag2"
                            FROM APPOINT ap1, PATIENT p1
                            WHERE 1=1
                            AND ap1."Patient" = p1."Patient"
                            AND ap1."Type" IN (0,1,2)
                            AND TRIM(ap1."Producer") = TRIM('''||vProducer||''')
                            AND ap1."Status" = 0
                            AND TRUNC(ap1."Date")  BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
                            AND MU_CORE_PKG.CALC_PT_AGE(ap1."Patient", TO_DATE('''||vCQMSDate||''')) BETWEEN 18 AND 64
                            )
                    GROUP BY "Patient","Last", "First", "Chart"
                    HAVING MAX("Flag2") = 0
                    ';
        OPEN MUWeakCursor FOR vSQLStmt;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE cqm3_nqf0421b_n(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vSQLStmt    VARCHAR2(24000 );
        vProducer     CHAR(10 ) := '';
        vCQMSDate     DATE;
        vCQMEDate     DATE;
        vMethod       CHAR := 'A';
        vFormCode CHAR(6 ) := 'MUMDH';
        vCodeList  VARCHAR2(150 ) := 'PT_STD_BMI';
        vCodeList2  VARCHAR2(150 ) := 'MDH_PREG';
        vCodeList3  VARCHAR2(150 ) := 'MDH_TILL';
        vCodeList4  VARCHAR2(150 ) := 'MDH_PEXAM';
        vAnsListRef  VARCHAR2(150 ) := 'PEXAMD1'', ''PEXAMD2'', ''PEXAMD3';
        -- ADA Code for Nutrition Counselling
        vADACode      CHAR(7 ) := 'D1310';
    BEGIN
        IF vMethod = 'A' THEN
          vCQMSDate := TRUNC(TO_DATE(vREndDate),'YEAR');
          vCQMEDate := LAST_DAY(ADD_MONTHS(TO_DATE(vREndDate),12 - TO_NUMBER(TO_CHAR(TO_DATE(vREndDate),'mm'))));
        END IF;

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                    SELECT a1."Patient",  p1."Last", p1."First", p1."Chart"
                    FROM APPOINT a1, PATIENT p1
                    WHERE 1=1
                    AND a1."Patient" = p1."Patient"
                    AND a1."Type" IN (0,1,2)
                    AND TRIM(a1."Producer") = TRIM('''||vProducer||''')
                    AND a1."Status" = 0
                    AND TRUNC(a1."Date") BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
                    AND MU_CORE_PKG.CALC_PT_AGE(a1."Patient", TO_DATE('''||vCQMSDate||''')) BETWEEN 18 AND 64
                    AND EXISTS (SELECT 1
                                FROM PITEM p3, FITEM f1
                                WHERE 1=1
                                AND p3."FItem" = f1."FItem"
                                AND p3."Patient" = a1."Patient"
                                AND TRIM(p3."FormCode") = TRIM('''||vFormCode||''')
                                AND TRUNC(p3."Date") BETWEEN ADD_MONTHS(TO_DATE(a1."Date"), -6) AND TO_DATE(a1."Date")
                                AND TRIM(f1."Code") IN TRIM('''||vCodeList||''')
                                AND NVL(TRIM(p3."AnsText"),''Invalid inputs provided.'') != ''Invalid inputs provided.''
                                AND (CASE WHEN (NVL(TRIM(p3."AnsText"),0) >= 18.5 AND NVL(TRIM(p3."AnsText"),''Invalid inputs provided.'') < 25) THEN 1
                                          WHEN ((NVL(TRIM(p3."AnsText"),0) >= 25 OR
                                                 NVL(TRIM(p3."AnsText"),0) < 18.5) AND
                                                  EXISTS (SELECT 1
                                                          FROM TRX t2
                                                          WHERE 1=1
                                                          AND TRIM(t2."Procedure") = TRIM('''||vADACode||''')
                                                          AND TRIM(t2."Status") = ''C''
                                                          AND t2."Deleted" = 0
                                                          AND t2."Patient" = a1."Patient"
                                                          AND TRUNC(t2."Date") = TRUNC(p3."Date")))
                                          THEN 1
                                          ELSE 0
                                     END) = 1
                               AND p3."AuditNumber" = (SELECT MAX(p3n."AuditNumber")
                                                        FROM PITEM p3n, FITEM f1n
                                                        WHERE 1=1
                                                        AND TRIM(p3n."FormCode") = TRIM(p3."FormCode")
                                                        AND p3n."FItem" = f1n."FItem"
                                                        AND p3n."Patient" = p3."Patient"
                                                        AND p3n."AppDate" IS NOT NULL
                                                        AND TRIM(f1n."Code") = TRIM(f1."Code")
                                                        AND TRUNC(p3n."Date")  = TO_DATE(p3."Date")
                                                        GROUP BY f1n."Code")
                              )
                    AND NOT EXISTS (SELECT 1
                                    FROM APPOINT ap2
                                    WHERE 1=1
                                    AND ap2."Type" IN (0,1,2)
                                    AND TRIM(ap2."Producer") = TRIM('''||vProducer||''')
                                    AND ap2."Patient" = a1."Patient"
                                    AND ap2."Status" = 0
                                    AND TRUNC(ap2."Date") BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
                                    AND MU_CORE_PKG.CALC_PT_AGE(ap2."Patient",TO_DATE('''||vCQMSDate||''')) BETWEEN 18 AND 64
                                    AND NOT EXISTS (SELECT 1
                                                    FROM PITEM p3, FITEM f1
                                                    WHERE 1=1
                                                    AND p3."FItem" = f1."FItem"
                                                    AND p3."Patient" = ap2."Patient"
                                                    AND TRIM(p3."FormCode") = TRIM('''||vFormCode||''')
                                                    AND TRUNC(p3."Date") BETWEEN ADD_MONTHS(TO_DATE(ap2."Date"), -6) AND TO_DATE(ap2."Date")
                                                    AND TRIM(f1."Code") IN TRIM('''||vCodeList||''')
                                                    AND NVL(TRIM(p3."AnsText"),''Invalid inputs provided.'') != ''Invalid inputs provided.''
                                                    AND (CASE WHEN (NVL(TRIM(p3."AnsText"),0) >= 18.5 AND NVL(TRIM(p3."AnsText"),''Invalid inputs provided.'') < 25) THEN 1
                                                              WHEN ((NVL(TRIM(p3."AnsText"),0) >= 25 OR
                                                                     NVL(TRIM(p3."AnsText"),0) < 18.5) AND
                                                                      EXISTS (SELECT 1
                                                                              FROM TRX t2
                                                                              WHERE 1=1
                                                                              AND TRIM(t2."Procedure") = TRIM('''||vADACode||''')
                                                                              AND TRIM(t2."Status") = ''C''
                                                                              AND t2."Deleted" = 0
                                                                              AND t2."Patient" = a1."Patient"
                                                                              AND TRUNC(t2."Date") = TRUNC(p3."Date")))
                                                              THEN 1
                                                              ELSE 0
                                                         END) = 1
                                                    AND p3."AuditNumber" = (SELECT MAX(p3n."AuditNumber")
                                                                            FROM PITEM p3n, FITEM f1n
                                                                            WHERE 1=1
                                                                            AND TRIM(p3n."FormCode") = TRIM(p3."FormCode")
                                                                            AND p3n."FItem" = f1n."FItem"
                                                                            AND p3n."Patient" = p3."Patient"
                                                                            AND p3n."AppDate" IS NOT NULL
                                                                            AND TRIM(f1n."Code") = TRIM(f1."Code")
                                                                            AND TRUNC(p3n."Date") = TO_DATE(p3."Date")
                                                                            GROUP BY f1n."Code")
                                                    )
                                      )
                    AND NOT EXISTS (SELECT 1
                                    FROM APPOINT ap2
                                    WHERE 1=1
                                    AND ap2."Type" IN (0,1,2)
                                    AND TRIM(ap2."Producer") = TRIM('''||vProducer||''')
                                    AND ap2."Patient" = a1."Patient"
                                    AND ap2."Status" = 0
                                    AND TRUNC(ap2."Date") BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
                                    AND MU_CORE_PKG.CALC_PT_AGE(ap2."Patient",TO_DATE('''||vCQMSDate||''')) BETWEEN 18 AND 64
                                    AND NOT EXISTS (SELECT 1
                                                    FROM PITEM p3, FITEM f1
                                                    WHERE 1=1
                                                    AND p3."FItem" = f1."FItem"
                                                    AND p3."Patient" = ap2."Patient"
                                                    AND TRIM(p3."FormCode") = TRIM('''||vFormCode||''')
                                                    AND TRUNC(p3."Date") BETWEEN ADD_MONTHS(TO_DATE(ap2."Date"), -6) AND TO_DATE(ap2."Date")
                                                    AND TRIM(f1."Code") IN TRIM('''||vCodeList||''')
                                                    AND NVL(TRIM(p3."AnsText"),''Invalid inputs provided.'') != ''Invalid inputs provided.''
                                                    AND (CASE WHEN (NVL(TRIM(p3."AnsText"),0) >= 18.5 AND NVL(TRIM(p3."AnsText"),''Invalid inputs provided.'') < 25) THEN 1
                                                              WHEN ((NVL(TRIM(p3."AnsText"),0) >= 25 OR
                                                                     NVL(TRIM(p3."AnsText"),0) < 18.5) AND
                                                                      EXISTS (SELECT 1
                                                                              FROM TRX t2
                                                                              WHERE 1=1
                                                                              AND TRIM(t2."Procedure") = TRIM('''||vADACode||''')
                                                                              AND TRIM(t2."Status") = ''C''
                                                                              AND t2."Deleted" = 0
                                                                              AND t2."Patient" = a1."Patient"
                                                                              AND TRUNC(t2."Date") = TRUNC(p3."Date")))
                                                              THEN 1
                                                              ELSE 0
                                                         END) = 1
                                                    AND p3."AuditNumber" = (SELECT MAX(p3n."AuditNumber")
                                                                            FROM PITEM p3n, FITEM f1n
                                                                            WHERE 1=1
                                                                            AND TRIM(p3n."FormCode") = TRIM(p3."FormCode")
                                                                            AND p3n."FItem" = f1n."FItem"
                                                                            AND p3n."Patient" = p3."Patient"
                                                                            AND p3n."AppDate" IS NOT NULL
                                                                            AND TRIM(f1n."Code") = TRIM(f1."Code")
                                                                            AND TRUNC(p3n."Date") = TO_DATE(p3."Date")
                                                                            GROUP BY f1n."Code")
                                                    )
                                      )
                  AND NOT EXISTS (SELECT 1
                                  FROM APPOINT ap2
                                  WHERE 1=1
                                  AND ap2."Type" IN (0,1,2)
                                  AND TRIM(ap2."Producer") = TRIM('''||vProducer||''')
                                  AND ap2."Patient" = a1."Patient"
                                  AND ap2."Status" = 0
                                  AND TRUNC(ap2."Date") BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
                                  AND MU_CORE_PKG.CALC_PT_AGE(ap2."Patient",TO_DATE('''||vCQMSDate||''')) BETWEEN 18 AND 64
                                  AND (EXISTS(SELECT 1 FROM
                                                        PITEM p4, FITEM f2
                                                        WHERE 1=1
                                                        AND p4."FItem" = f2."FItem"
                                                        AND p4."Patient" = ap2."Patient"
                                                        AND TRIM(p4."FormCode") = TRIM('''||vFormCode||''')
                                                        AND TRIM(f2."Code") = TRIM('''||vCodeList2||''')
                                                        AND p4."AnsYes" = 1
                                                        AND TRUNC(p4."Date")  = (ap2."Date")
                                                        AND p4."AppDate" IS NOT NULL
                                                        AND p4."AuditNumber" = (SELECT MAX(p4n."AuditNumber") FROM
                                                                                PITEM p4n, FITEM f2n
                                                                                WHERE 1=1
                                                                                AND TRIM(p4n."FormCode") = TRIM(p4."FormCode")
                                                                                AND p4n."FItem" = f2n."FItem"
                                                                                AND p4n."Patient" = p4."Patient"
                                                                                AND p4n."AppDate" IS NOT NULL
                                                                                AND TRIM(f2n."Code") = TRIM(f2."Code")
                                                                                AND TRUNC(p4n."Date") = TO_DATE(ap2."Date")
                                                                                GROUP BY f2n."Code")
                                                        )
                                        OR EXISTS (SELECT 1 FROM
                                                        PITEM p4, FITEM f2
                                                        WHERE 1=1
                                                        AND p4."FItem" = f2."FItem"
                                                        AND p4."Patient" = ap2."Patient"
                                                        AND TRIM(p4."FormCode") = TRIM('''||vFormCode||''')
                                                        AND TRIM(f2."Code") = TRIM('''||vCodeList3||''')
                                                        AND p4."AnsYes" = 1
                                                        AND TRUNC(p4."Date")  = (ap2."Date")
                                                        AND p4."AppDate" IS NOT NULL
                                                        AND p4."AuditNumber" = (SELECT MAX(p4n."AuditNumber") FROM
                                                                                PITEM p4n, FITEM f2n
                                                                                WHERE 1=1
                                                                                AND TRIM(p4n."FormCode") = TRIM(p4."FormCode")
                                                                                AND p4n."FItem" = f2n."FItem"
                                                                                AND p4n."Patient" = p4."Patient"
                                                                                AND p4n."AppDate" IS NOT NULL
                                                                                AND TRIM(f2n."Code") = TRIM(f2."Code")
                                                                                AND TRUNC(p4n."Date") = TO_DATE(ap2."Date")
                                                                                GROUP BY f2n."Code")
                                                        )
                                        OR EXISTS (SELECT 1 FROM
                                                        PITEM p5, FITEM f3
                                                        WHERE 1=1
                                                        AND p5."FItem" = f3."FItem"
                                                        AND p5."Patient" = ap2."Patient"
                                                        AND TRIM(p5."FormCode") = TRIM('''||vFormCode||''')
                                                        AND TRIM(f3."Code") = TRIM('''||vCodeList4||''')
                                                        AND TRIM(p5."AnsListRefCode") IN ('''||vAnsListRef||''')
                                                        AND TRUNC(p5."Date")  = (ap2."Date")
                                                        AND p5."AppDate" IS NOT NULL
                                                        AND p5."AuditNumber" = (SELECT MAX(p5n."AuditNumber") FROM
                                                                                PITEM p5n, FITEM f3n
                                                                                WHERE 1=1
                                                                                AND TRIM(p5n."FormCode") = TRIM(f3."FormCode")
                                                                                AND p5n."FItem" = f3n."FItem"
                                                                                AND p5n."Patient" = p5."Patient"
                                                                                AND p5n."AppDate" IS NOT NULL
                                                                                AND TRIM(f3n."Code") = TRIM(f3."Code")
                                                                                AND TRUNC(p5n."Date") = TO_DATE(ap2."Date")
                                                                                GROUP BY f3n."Code")
                                                        )
                                        )
                                )

                    GROUP BY a1."Patient", p1."Last", p1."First", p1."Chart"
                    ';
        OPEN MUWeakCursor FOR vSQLStmt;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE cqm5_nqf0041_d(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vSQLStmt    VARCHAR2(7500 );
        vProducer     CHAR(10 ) := '';
        vCQMSDate     DATE;
        vCQMEDate     DATE;
        vMethod       CHAR := 'A';
        vFormCode CHAR(6 ) := 'MUMDH';
        vCodeList  VARCHAR2(150 ) := 'MDH_FLU';
        vCodeList2  VARCHAR2(150 ) := 'MU_NFLU';
    BEGIN
        IF vMethod = 'A' THEN
          vCQMSDate := TRUNC(TO_DATE(vREndDate),'YEAR');
          vCQMEDate := LAST_DAY(ADD_MONTHS(TO_DATE(vREndDate),12 - TO_NUMBER(TO_CHAR(TO_DATE(vREndDate),'mm'))));
        END IF;

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                    SELECT "Patient", "Last", "First", "Chart", MAX("Flag") as "Flag"
                    FROM
                    (
                          SELECT a1."Date" as "Date", p2."Patient" as "Patient", p2."Last" as "Last", p2."First" as "First", p2."Chart" as "Chart",
                                NVL((SELECT DISTINCT 1 FROM
                                      PITEM p3, FITEM f1
                                      WHERE 1=1
                                      AND TRIM(p3."FormCode") = TRIM('''||vFormCode||''')
                                      AND p3."FItem" = f1."FItem"
                                      AND p3."Patient" = a1."Patient"
                                      AND p3."AnsYes" = 1
                                      AND p3."AppDate" IS NOT NULL
                                      AND TRIM(f1."Code") IN ('''||vCodeList||''')
                                      AND TRUNC(p3."Date") BETWEEN (TO_DATE('''||vCQMSDate||''')-122) AND (TO_DATE('''||vCQMEDate||''')+58)
                                      AND p3."AuditNumber" = (SELECT MAX(p3n."AuditNumber") FROM
                                                              PITEM p3n, FITEM f1n
                                                              WHERE 1=1
                                                              AND TRIM(p3n."FormCode") = TRIM(p3."FormCode")
                                                              AND p3n."FItem" = f1n."FItem"
                                                              AND p3n."Patient" = p3."Patient"
                                                              AND p3n."AppDate" IS NOT NULL
                                                              AND TRIM(f1n."Code") = TRIM(f1."Code")
                                                              AND TRUNC(p3n."Date") BETWEEN (TO_DATE('''||vCQMSDate||''')-122) AND (TO_DATE('''||vCQMEDate||''')+58)
                                                              GROUP BY f1n."Code")
                                      AND NOT EXISTS (SELECT 1 FROM
                                                      PITEM p4, FITEM f2
                                                      WHERE 1=1
                                                      AND TRIM(p4."FormCode") = TRIM('''||vFormCode||''')
                                                      AND p4."FItem" = f2."FItem"
                                                      AND p4."Patient" = a1."Patient"
                                                      AND p4."AppDate" IS NOT NULL
                                                      AND TRIM(f2."Code") IN ('''||vCodeList2||''')
                                                      AND TRIM(p4."AnsListRefCode") IS NOT NULL
                                                      AND TRUNC(p4."Date") BETWEEN (TO_DATE('''||vCQMSDate||''')-122) AND (TO_DATE('''||vCQMEDate||''')+58)
                                                      AND p4."AuditNumber" = (SELECT MAX(p4n."AuditNumber") FROM
                                                                              PITEM p4n, FITEM f2n
                                                                              WHERE 1=1
                                                                              AND TRIM(p4n."FormCode") = TRIM(p4."FormCode")
                                                                              AND p4n."FItem" = f2n."FItem"
                                                                              AND p4n."Patient" = p4."Patient"
                                                                              AND p4n."AppDate" IS NOT NULL
                                                                              AND TRIM(f2n."Code") = TRIM(f2."Code")
                                                                              AND TRUNC(p4n."Date") BETWEEN (TO_DATE('''||vCQMSDate||''')-122) AND (TO_DATE('''||vCQMEDate||''')+58)
                                                                              GROUP BY f2n."Code"))
                                      GROUP BY p3."Patient"),0) as "Flag"
                          FROM APPOINT a1, PATIENT p2
                          WHERE 1=1
                          AND a1."Patient" = p2."Patient"
                          AND a1."Type" IN (0,1,2)
                          AND TRIM(a1."Producer") = TRIM('''||vProducer||''')
                          AND a1."Status" = 0
                          AND TRUNC(a1."Date") BETWEEN (TO_DATE('''||vCQMSDate||''')-122) AND (TO_DATE('''||vCQMEDate||''')+58)
                          AND MU_CORE_PKG.CALC_PT_AGE(a1."Patient", TO_DATE('''||vCQMSDate||''')) >= 50
						  AND NOT EXISTS (SELECT 1
										  FROM APPOINT ap2
										  WHERE 1=1
										  AND ap2."Patient" = a1."Patient"
										  AND ap2."Type" IN (0,1,2)
										  AND ap2."Status" = 0
										  AND TRIM(ap2."Producer") = TRIM('''||vProducer||''')
										  AND TRUNC(ap2."Date") BETWEEN (TO_DATE('''||vCQMSDate||''')-122) AND (TO_DATE('''||vCQMEDate||''')+58)
										  AND MU_CORE_PKG.CALC_PT_AGE(ap2."Patient", TO_DATE('''||vCQMSDate||''')) >= 50
										  AND EXISTS (SELECT 1
													  FROM PITEM p4, FITEM f2
													  WHERE 1=1
													  AND p4."FItem" = f2."FItem"
													  AND TRIM(p4."FormCode") = TRIM('''||vFormCode||''')
													  AND p4."Patient" = ap2."Patient"
													  AND p4."AppDate" IS NOT NULL
													  AND TRIM(f2."Code") IN ('''||vCodeList2||''')
													  AND TRIM(p4."AnsListRefCode") IS NOT NULL
													  AND TRUNC(p4."Date") = ap2."Date"
													  AND p4."AuditNumber" = (SELECT MAX(p4n."AuditNumber")
																			  FROM PITEM p4n, FITEM f2n
																			  WHERE 1=1
																			  AND TRIM(p4n."FormCode") = TRIM(p4."FormCode")
																			  AND p4n."FItem" = f2n."FItem"
																			  AND p4n."Patient" = p4."Patient"
																			  AND p4n."AppDate" IS NOT NULL
																			  AND TRIM(f2n."Code") = TRIM(f2."Code")
																			  AND TRUNC(p4n."Date") <= TO_DATE(ap2."Date")
																			  GROUP BY f2n."Code"))
										)
						AND EXISTS( SELECT 1
									FROM APPOINT ap2
									WHERE 1=1
									AND ap2."Patient" = a1."Patient"
									AND ap2."Type" IN (0,1,2)
									AND TRIM(ap2."Producer") = TRIM('''||vProducer||''')
									AND ap2."Status" = 0
									AND TRUNC(a1."Date") BETWEEN (TO_DATE('''||vCQMSDate||''')-122) AND (TO_DATE('''||vCQMEDate||''')+58)
									AND MU_CORE_PKG.CALC_PT_AGE(a1."Patient", TO_DATE('''||vCQMSDate||''')) >= 50
									GROUP BY ap2."Patient"
									HAVING (COUNT(DISTINCT ap2."Date") >=2))
                    )
                    GROUP BY "Patient", "Last", "First", "Chart"
                    ';
        OPEN MUWeakCursor FOR vSQLStmt;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE cqm5_nqf0041_n(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vSQLStmt    VARCHAR2(7500 );
        vProducer     CHAR(10 ) := '';
        vCQMSDate     DATE;
        vCQMEDate     DATE;
        vMethod       CHAR := 'A';
        vFormCode CHAR(6 ) := 'MUMDH';
        vCodeList  VARCHAR2(150 ) := 'MDH_FLU';
        vCodeList2  VARCHAR2(150 ) := 'MU_NFLU';
    BEGIN
        IF vMethod = 'A' THEN
          vCQMSDate := TRUNC(TO_DATE(vREndDate),'YEAR');
          vCQMEDate := LAST_DAY(ADD_MONTHS(TO_DATE(vREndDate),12 - TO_NUMBER(TO_CHAR(TO_DATE(vREndDate),'mm'))));
        END IF;

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                    SELECT "Patient", "Last", "First", "Chart", MAX("Flag") as "Flag"
                    FROM
                    (
                          SELECT a1."Date" as "Date", p2."Patient" as "Patient", p2."Last" as "Last", p2."First" as "First", p2."Chart" as "Chart",
                                NVL((SELECT DISTINCT 1 FROM
                                      PITEM p3, FITEM f1
                                      WHERE 1=1
                                      AND TRIM(p3."FormCode") = TRIM('''||vFormCode||''')
                                      AND p3."FItem" = f1."FItem"
                                      AND p3."Patient" = a1."Patient"
                                      AND p3."AnsYes" = 1
                                      AND p3."AppDate" IS NOT NULL
                                      AND TRIM(f1."Code") IN ('''||vCodeList||''')
                                      AND TRUNC(p3."Date") = TO_DATE(a1."Date")
                                      AND p3."AuditNumber" = (SELECT MAX(p3n."AuditNumber") FROM
                                                              PITEM p3n, FITEM f1n
                                                              WHERE 1=1
                                                              AND TRIM(p3n."FormCode") = TRIM(p3."FormCode")
                                                              AND p3n."FItem" = f1n."FItem"
                                                              AND p3n."Patient" = p3."Patient"
                                                              AND p3n."AppDate" IS NOT NULL
                                                              AND TRIM(f1n."Code") = TRIM(f1."Code")
                                                              AND TRUNC(p3n."Date") <= (TO_DATE((a1."Date")))
                                                              GROUP BY f1n."Code")
                                      GROUP BY p3."Patient"),0) as "Flag"
                          FROM APPOINT a1, PATIENT p2
                          WHERE 1=1
                          AND a1."Patient" = p2."Patient"
                          AND a1."Type" IN (0,1,2)
                          AND TRIM(a1."Producer") = TRIM('''||vProducer||''')
                          AND a1."Status" = 0
                          AND TRUNC(a1."Date") BETWEEN (TO_DATE('''||vCQMSDate||''')-122) AND (TO_DATE('''||vCQMEDate||''')+58)
                          AND MU_CORE_PKG.CALC_PT_AGE(a1."Patient", TO_DATE('''||vCQMSDate||''')) >= 50
						  AND NOT EXISTS (SELECT 1
										  FROM APPOINT ap2
										  WHERE 1=1
										  AND ap2."Patient" = a1."Patient"
										  AND ap2."Type" IN (0,1,2)
										  AND ap2."Status" = 0
										  AND TRIM(ap2."Producer") = TRIM('''||vProducer||''')
										  AND TRUNC(ap2."Date") BETWEEN (TO_DATE('''||vCQMSDate||''')-122) AND (TO_DATE('''||vCQMEDate||''')+58)
										  AND MU_CORE_PKG.CALC_PT_AGE(ap2."Patient", TO_DATE('''||vCQMSDate||''')) >= 50
										  AND EXISTS (SELECT 1
													  FROM PITEM p4, FITEM f2
													  WHERE 1=1
													  AND p4."FItem" = f2."FItem"
													  AND TRIM(p4."FormCode") = TRIM('''||vFormCode||''')
													  AND p4."Patient" = ap2."Patient"
													  AND p4."AppDate" IS NOT NULL
													  AND TRIM(f2."Code") IN ('''||vCodeList2||''')
													  AND TRIM(p4."AnsListRefCode") IS NOT NULL
													  AND TRUNC(p4."Date") = ap2."Date"
													  AND p4."AuditNumber" = (SELECT MAX(p4n."AuditNumber")
																			  FROM PITEM p4n, FITEM f2n
																			  WHERE 1=1
																			  AND TRIM(p4n."FormCode") = TRIM(p4."FormCode")
																			  AND p4n."FItem" = f2n."FItem"
																			  AND p4n."Patient" = p4."Patient"
																			  AND p4n."AppDate" IS NOT NULL
																			  AND TRIM(f2n."Code") = TRIM(f2."Code")
																			  AND TRUNC(p4n."Date") <= TO_DATE(ap2."Date")
																			  GROUP BY f2n."Code"))
										)
						AND EXISTS( SELECT 1
									FROM APPOINT ap2
									WHERE 1=1
									AND ap2."Patient" = a1."Patient"
									AND ap2."Type" IN (0,1,2)
									AND TRIM(ap2."Producer") = TRIM('''||vProducer||''')
									AND ap2."Status" = 0
									AND TRUNC(a1."Date") BETWEEN (TO_DATE('''||vCQMSDate||''')-122) AND (TO_DATE('''||vCQMEDate||''')+58)
									AND MU_CORE_PKG.CALC_PT_AGE(a1."Patient", TO_DATE('''||vCQMSDate||''')) >= 50
									GROUP BY ap2."Patient"
									HAVING (COUNT(DISTINCT ap2."Date") >=2))
                    )
                    GROUP BY "Patient", "Last", "First", "Chart"
                    HAVING MAX("Flag") = 1
                    ';
        OPEN MUWeakCursor FOR vSQLStmt;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE cqm6_nqf0043_d(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vSQLStmt    VARCHAR2(5000 );
        vProducer     CHAR(10 ) := '';
        vCQMSDate     DATE;
        vCQMEDate     DATE;
        vMethod       CHAR := 'A';
        vFormCode CHAR(6 ) := 'MUMDH';
        vCodeList  VARCHAR2(150 ) := 'MDH_PNEUM';
    BEGIN
        IF vMethod = 'A' THEN
          vCQMSDate := TRUNC(TO_DATE(vREndDate),'YEAR');
          vCQMEDate := LAST_DAY(ADD_MONTHS(TO_DATE(vREndDate),12 - TO_NUMBER(TO_CHAR(TO_DATE(vREndDate),'mm'))));
        END IF;

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                    SELECT DISTINCT p2."Patient", p2."Last", p2."First", p2."Chart",
                          NVL((SELECT DISTINCT 1 FROM
                                PITEM p3, FITEM f1
                                WHERE 1=1
                                AND TRIM(p3."FormCode") = TRIM('''||vFormCode||''')
                                AND p3."FItem" = f1."FItem"
                                AND p3."Patient" = p1."Patient"
                                AND p3."AnsYes" = 1
                                AND p3."AppDate" IS NOT NULL
                                AND TRIM(f1."Code") IN ('''||vCodeList||''')
                                AND TRUNC(p3."Date") <= TO_DATE('''||vCQMEDate||''')
                                AND p3."AuditNumber" = (SELECT MAX(p3n."AuditNumber")
                                                        FROM PITEM p3n, FITEM f1n
                                                        WHERE 1=1
                                                        AND TRIM(p3n."FormCode") = TRIM(p3."FormCode")
                                                        AND p3n."FItem" = f1n."FItem"
                                                        AND p3n."Patient" = p3."Patient"
                                                        AND p3n."AppDate" IS NOT NULL
                                                        AND TRIM(f1n."Code") = TRIM(f1."Code")
                                                        AND TRUNC(p3n."Date") <= TO_DATE(p1."Date")
                                                        GROUP BY f1n."Code")),0) AS "Flag"
                    FROM APPOINT p1, PATIENT p2
                    WHERE 1=1
                    AND p1."Patient" = p2."Patient"
                    AND p1."Type" IN (0,1,2)
                    AND TRIM(p1."Producer") = TRIM('''||vProducer||''')
                    AND p1."Status" = 0
                    AND TRUNC(p1."Date") BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
                    AND MU_CORE_PKG.CALC_PT_AGE(p1."Patient", TO_DATE('''||vCQMSDate||''')) >= 64
                    ';
        OPEN MUWeakCursor FOR vSQLStmt;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE cqm6_nqf0043_n(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vSQLStmt    VARCHAR2(5000 );
        vProducer     CHAR(10 ) := '';
        vCQMSDate     DATE;
        vCQMEDate     DATE;
        vMethod       CHAR := 'A';
        vFormCode CHAR(6 ) := 'MUMDH';
        vCodeList  VARCHAR2(150 ) := 'MDH_PNEUM';
    BEGIN
        IF vMethod = 'A' THEN
          vCQMSDate := TRUNC(TO_DATE(vREndDate),'YEAR');
          vCQMEDate := LAST_DAY(ADD_MONTHS(TO_DATE(vREndDate),12 - TO_NUMBER(TO_CHAR(TO_DATE(vREndDate),'mm'))));
        END IF;

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                    SELECT DISTINCT p2."Patient", p2."Last", p2."First", p2."Chart"
                    FROM APPOINT p1, PATIENT p2
                    WHERE 1=1
                    AND p1."Patient" = p2."Patient"
                    AND p1."Type" IN (0,1,2)
                    AND TRIM(p1."Producer") = TRIM('''||vProducer||''')
                    AND p1."Status" = 0
                    AND TRUNC(p1."Date") BETWEEN TO_DATE('''||vCQMSDate||''') AND TO_DATE('''||vCQMEDate||''')
                    AND MU_CORE_PKG.CALC_PT_AGE(p1."Patient", TO_DATE('''||vCQMSDate||''')) >= 64
                    AND EXISTS (SELECT 1 FROM
                                PITEM p3, FITEM f1
                                WHERE 1=1
                                AND TRIM(p3."FormCode") = TRIM('''||vFormCode||''')
                                AND p3."FItem" = f1."FItem"
                                AND p3."Patient" = p1."Patient"
                                AND p3."AnsYes" = 1
                                AND p3."AppDate" IS NOT NULL
                                AND TRIM(f1."Code") IN ('''||vCodeList||''')
                                AND TRUNC(p3."Date") <= TO_DATE('''||vCQMEDate||''')
                                AND p3."AuditNumber" = (SELECT MAX(p3n."AuditNumber")
                                                        FROM PITEM p3n, FITEM f1n
                                                        WHERE 1=1
                                                        AND TRIM(p3n."FormCode") = TRIM(p3."FormCode")
                                                        AND p3n."FItem" = f1n."FItem"
                                                        AND p3n."Patient" = p3."Patient"
                                                        AND p3n."AppDate" IS NOT NULL
                                                        AND TRIM(f1n."Code") = TRIM(f1."Code")
                                                        AND TRUNC(p3n."Date") <= TO_DATE(p1."Date")
                                                        GROUP BY f1n."Code"))
                    ';
        OPEN MUWeakCursor FOR vSQLStmt;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE create_iuser_accounts()
 SECURITY DEFINER
AS $procedure$
  vOvernightUser NUMBER(10);
  viUser         NUMBER(10);
  vAuditHis      NUMBER(10);
  vTime          NUMBER(10);
  CURSOR c_PatientsSeen
  IS
    SELECT a1."Patient"
    FROM APPOINT a1
    WHERE 1        =1
    AND a1."Type"                       IN (0,1,2)
    AND a1."Date" BETWEEN (TRUNC(sysdate)-1) AND (TRUNC(sysdate))
    AND NOT EXISTS
      (SELECT 1 FROM IUSER i1 WHERE 1=1 AND i1."Id" = a1."Patient"
      )
  GROUP BY a1."Patient";
BEGIN
  SELECT "OvernightUser" INTO vOvernightUser FROM axiumopt;
  FOR patientRec IN c_PatientsSeen
  LOOP
    SELECT USERS_USER_SEQ.NEXTVAL INTO viUser FROM dual;
    SELECT AUDITHIS_AUDIT_SEQ.NEXTVAL INTO vAuditHis FROM DUAL;
    SELECT FLOOR(ROUND(TO_CHAR(sysdate, 'SSSSS'))/60) INTO vTime FROM DUAL;
    INSERT
    INTO AUDITHIS VALUES
      (
        vAuditHis,
        TRUNC(sysdate),
        vTime,
        vOvernightUser,
        0,
        'IUSER',
        1
      );
    INSERT
    INTO IUSER VALUES
      (
        viUser,
        0,
        patientRec."Patient",
        IPORTAL_PKG.CreateUserName(0, patientRec."Patient"),
        IPORTAL_PKG.HashPassword(IPORTAL_PKG.CreatePassword(0, patientRec."Patient"), patientRec."Patient"),
        1,0,0,
        vAuditHis,
        0,0,
        NULL,
        0,
        NULL,
        0,
        NULL,
        0,
        NULL,
        0,
        NULL,
        0,
        NULL,
        0,
		NULL,
		0		
      );
  END LOOP;
  COMMIT;
END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE createlabordh(IN llabitemh numeric, IN lhisview numeric, IN llaborder numeric, IN laudit numeric)
 SECURITY DEFINER
AS $procedure$
  vCount NUMBER;
  CURSOR C1 IS SELECT * FROM LABORDER WHERE "LabOrder" = lLabOrder;
BEGIN
 SELECT COUNT(1) into vCount FROM LABORDH WHERE "LabOrder" = lLabOrder AND "Audit" = lAudit;

IF (vCount = 0) THEN
  FOR labrec IN C1 LOOP
	insert into LABORDH values
	    (
	      LABORDH_LABORDH_SEQ.nextval,
	      lLabItemH,
	      lHisView,
	      labrec."LabOrder",
	      labrec."CaseNo",
	      labrec."Patient",
	      labrec."LabProcedure",
	      labrec."Discipline",
	      labrec."Date",
	      labrec."RemakeStudent",
	      labrec."RemakeStaff",
	      labrec."RemakeLabOrder",
	      labrec."WaiveCharges",
	      labrec."LabOut",
	      labrec."LabCode",
	      labrec."DateOut",
	      labrec."TimeOut",
	      labrec."User",
	      labrec."Deleted",
	      labrec."CurrentItem",
	      labrec."Status",
	      labrec."CompletionDate",
	      labrec."TotalCost",
	      labrec."TotalCharge",
	      labrec."IsOrtho",
	      labrec."OrigRecNo",
	      lAudit,
	      labrec."IseLab"
    );
    UPDATE LABORDER SET "Audit" = lAudit WHERE "LabOrder" = lLabOrder; -- trigger shouldn't fire because we already created a history record with this audit
																								-- B143270 added the WHERE clause		
    END LOOP;
  END IF;
END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE delete_txplan(IN txplanid numeric, IN auditid numeric)
 SECURITY DEFINER
AS $procedure$
BEGIN
  UPDATE TXPNOTE	SET "Deleted" = 1, "Audit" = AuditId WHERE "TxPlan" = TxPlanId;
  UPDATE TXPDXTX	SET "Deleted" = 1, "Audit" = AuditId WHERE "TxPDx" IN (SELECT D."TxPDx" FROM TXPDX D WHERE D."TxPlan" = TxPlanId);
  UPDATE TXPTX		SET "Deleted" = 1, "Audit" = AuditId WHERE "TxPlan" = TxPlanId;
  UPDATE TXPOPT	SET "Deleted" = 1, "Audit" = AuditId WHERE "TxPlan" = TxPlanId;
  UPDATE PTPRBDX	SET "Deleted" = 1, "Audit" = AuditId WHERE "TxPDx" IN (SELECT D."TxPDx" FROM TXPDX D WHERE D."TxPlan" = TxPlanId);
  UPDATE TXPDX		SET "Deleted" = 1, "Audit" = AuditId WHERE "TxPlan" = TxPlanId;
  UPDATE TXPPRB	SET "Deleted" = 1, "Audit" = AuditId WHERE "TxPlan" = TxPlanId;
  UPDATE PTOBJ		SET "Deleted" = 1, "Audit" = AuditId WHERE "TxPlan" = TxPlanId;
  UPDATE TXPLAN	SET "Deleted" = 1, "Audit" = AuditId WHERE "TxPlan" = TxPlanId;

  -- no auditing - we'll leave these orphaned (in case delete needs to be undone)
  --DELETE FROM TXPOPAP	WHERE "TxPOpt" IN (SELECT D."TxPOpt" FROM TXPOPT D WHERE D."TxPlan" = TxPlanId);
  --DELETE FROM GRAPHP2	WHERE "TxPTx" IN (SELECT D."TxPTx" FROM TXPTX D WHERE D."TxPlan" = TxPlanId);
  --DELETE FROM TXPLNCON	WHERE "TxPlan" = TxPlanId;

END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE dmft_score(INOUT ref_cursor cursor_pkg.weakcursor, IN patientval numeric)
 SECURITY DEFINER
AS $procedure$
   TYPE RefCurType IS REF CURSOR;
   CountMissing NUMBER := 0;
   CountDecay   NUMBER := 0;
   CountFilled  NUMBER := 0;
   TeethCount   NUMBER(5) := 0;

   ToothStateVal        PATIENT2."ToothState"%TYPE;
   PermanentStateVal    PATIENT2."PermanentState"%TYPE;
   PrimaryStateVal      PATIENT2."PrimaryState"%TYPE;
   Patient2Auto         PATIENT2."Auto"%TYPE;
   tooth_val            CHAR(1);
   perm_val             CHAR(1);
   pri_val              CHAR(1);

   cur1                 RefCurType;
   cur2                 RefCurType;
   vCount               NUMBER(5);
   vSite                TREATME2."Site"%TYPE;
   et                   VARCHAR2(96);
   vSql                 VARCHAR2(1000);
BEGIN
   IF PatientVal IS NULL THEN
      GOTO end_proc;
   END IF;

   BEGIN
      SELECT "Auto","ToothState","PermanentState","PrimaryState"
        INTO Patient2Auto, ToothStateVal, PermanentStateVal, PrimaryStateVal
        FROM patient2
       WHERE "PtxPId" = PatientVal;
   EXCEPTION WHEN NO_DATA_FOUND THEN
      GOTO end_proc;
   END;

   FOR i IN 1 .. 32 LOOP
      tooth_val := SUBSTR(ToothStateVal,i,1);
      perm_val := SUBSTR(PermanentStateVal,i,1);
      pri_val := SUBSTR(PrimaryStateVal,i,1);

      IF tooth_val = '2' THEN
         CountMissing := CountMissing + 1;
         GOTO cal_end;
      ELSE
         IF tooth_val = '3' THEN
            IF i NOT IN (1,2,3,14,15,16,17,18,19,30,31,32) THEN
               CountMissing := CountMissing + 1;
               GOTO cal_end;
            ELSE
               GOTO cal_end;
            END IF;
         END IF;
      END IF;

      IF tooth_val = '0' THEN -- is permanent tooth
         IF perm_val = '1' THEN -- tooth has been extracted
            CountMissing := CountMissing + 1;
            GOTO cal_end;
         ELSIF perm_val = '2' THEN -- tooth has been impacted
            CountMissing := CountMissing + 1;
            GOTO cal_end;
         ELSE
            teethcount := teethcount + 1;
            GOTO cal_not_missing;
         END IF;
      ELSIF tooth_val = '1' THEN -- is primary tooth
         IF pri_val = '1' THEN -- tooth has been extracted
            CountMissing := CountMissing + 1;
            GOTO cal_end;
         ELSIF pri_val = '2' THEN -- tooth has been impacted
            CountMissing := CountMissing + 1;
            GOTO cal_end;
         ELSE
            teethcount := teethcount + 1;
            GOTO cal_not_missing;
         END IF;
      END IF;

      <<cal_not_missing>>
         IF tooth_val = '0' THEN
            et := et || i || ',';
         ELSIF tooth_val = '1' THEN
            IF i > 16 THEN
               et := et || (i+35) || ',';
            ELSE
               et := et || (i+41) || ',';
            END IF;
         END IF;
      <<cal_end>>
      NULL;
   END LOOP;
   et := rtrim(et,',');

   vSql := 'SELECT DISTINCT "Site"
                 FROM treatme2
                WHERE "PId" = ' || Patient2Auto || '
                  AND "Surface" > 0
                  AND "CodeId" in (10061,10062,10063)
                  AND "Deleted"=0
                  AND "Site" IN (' || et || ')';

   IF TRIM(et) IS NOT NULL THEN
      OPEN cur1 FOR vSql;

      LOOP
         FETCH cur1 INTO vSite;
         EXIT WHEN cur1%NOTFOUND;

         CountDecay := CountDecay + 1;

         et := replace(et,vSite,'');
         et := REPLACE(et,',,',',');
      END LOOP;
      CLOSE cur1;
   END IF;

   et := LTRIM(RTRIM(et,','),',');

   vSql := 'SELECT DISTINCT "Site"
              FROM treatme2 t, procedur p
             WHERE p."Id" = t."CodeId"
               AND t."PId" = ' || Patient2Auto || '
               AND t."Surface" > 0
               AND t."Status" IN (0,3)
               AND t."Deleted" = 0
               AND (p."CodeType"=3 OR p."CodeType"=0 OR p."CodeType"=1)
               AND t."Site" in (' || et || ')';

   IF TRIM(et) IS NOT NULL THEN
      OPEN cur2 FOR vSql;

      LOOP
         FETCH cur2 INTO vSite;
         EXIT WHEN cur2%NOTFOUND;

         CountFilled := CountFilled + 1;
      END LOOP;
      CLOSE cur2;
   END IF;

   <<end_proc>>

   OPEN Ref_Cursor FOR
     select CountMissing "CountMissing", CountDecay "CountDecay",
            CountFilled "CountFilled", teethcount "CountTeeth" FROM dual;
END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE get_med_interacts_alert_pted(IN pmedication character varying, INOUT prefcursor cursor_pkg.weakcursor)
 SECURITY DEFINER
AS $procedure$
	vSQLStmt VARCHAR2(4000);
BEGIN
	-- build SQL statement
	vSQLStmt :=
		'
		SELECT
			DR."Severity",
			DR."Description" AS "ReactDesc",
			AD2."Description" AS "AlertDesc"
		FROM DRUGREAC DR, ALERTD2 AD2
		WHERE 1=1
			AND TRIM(DR."Drug") = :1
			AND TRIM(DR."ReactAlert") = TRIM(AD2."Code")
			AND DR."ReactType" = 1
		';
	
	-- open cursor
	OPEN pRefCursor FOR vSQLStmt USING pMedication; 	
END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE get_med_interacts_pted(IN pmedication character varying, INOUT prefcursor cursor_pkg.weakcursor)
 SECURITY DEFINER
AS $procedure$
	vSQLStmt VARCHAR2(4000);
BEGIN
	-- build SQL statement
	vSQLStmt :=
		'
		SELECT
			D."Description",
			DR."Severity",
			DR."Description"
		FROM DRUGREAC DR, DRUG D
		WHERE 1=1
			AND TRIM(DR."Drug") = :1
			AND DR."ReactDrug" = D."Drug"
			AND DR."ReactType" = 0
		';
	
	-- open cursor
	OPEN pRefCursor FOR vSQLStmt USING pMedication; 	
END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE get_pform_app_user(INOUT ref_cursor cursor_pkg.weakcursor, IN pform numeric, IN page_header character varying)
 SECURITY DEFINER
AS $procedure$
   sqlstmt   VARCHAR2 (4000 );
BEGIN
   sqlstmt :=
      'SELECT *	FROM
	  (SELECT DISTINCT u."Name", u."First", p."AppDate"
	   FROM pitem p, pform pf, users u
	   WHERE pf."PForm" = :1
	   AND p."PForm" = pf."PForm"
           AND u."User" = p."AppUser"
	   AND p."Status" = 0
	   AND p."AppUser" > 0
	   AND p."FItem" IN
	    (SELECT f2."FItem"
	     FROM fitem f2
	     WHERE f2."Type" IN(2,    3,    4)
	     AND f2."Deleted" = 0
	     AND f2."Page" =
	      (SELECT f."Page"
	       FROM fitem f
	       WHERE f."FormCode" = pf."FormCode"
	       AND f."Text" = :2
	       AND f."Type" = 0
	       AND f."Deleted" = 0)
	    )
	  ORDER BY p."AppDate" DESC)
	WHERE rownum < 2';

   OPEN ref_cursor
    FOR sqlstmt USING pform, page_header;
END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE get_pt_reminders_alert(IN palertcode character, IN pnumdays integer, INOUT prefcursor cursor_pkg.weakcursor)
 SECURITY DEFINER
AS $procedure$
	vSQLStmt VARCHAR2(4000);
BEGIN
	vSQLStmt :=
	'
	SELECT DISTINCT
		PT."Patient",
		PT."Chart",
		PT."Last",
		PT."First",
		PT."Sex",
		DECODE(PT."Sex", 0, ''U'', 1, ''M'', 2, ''F'', 3, ''T'', ''U'') AS "SexChar",
		TO_CHAR(SYSDATE,''YYYY'') - TO_CHAR(PT."Birth",''YYYY'') - CASE WHEN TO_CHAR(SYSDATE,''MMDD'') < TO_CHAR(PT."Birth",''MMDD'') THEN 1 ELSE 0 END AS "Age",
		PT."CustomCode4",
		PT."ContactAt",
		PT."HomeArea",
		PT."HomePhone",
		PT."WorkArea",
		PT."WorkPhone",
		PT."WorkExt",
		PT."OtherArea",
		PT."OtherPhone",
		PT."OtherExt",
		PT."MobileArea",
		PT."MobilePhone",
		PT."Email",
		PT."Address1",
		PT."Address2",
		PT."City",
		PT."Province",
		PT."Postal",
		PT."Country",
		TO_CHAR(AP."Date" + (AP."From"/1440),''DD-MON-YYYY HH24:MI:SS'') AS "ApptDateTime",
		AP."Code",
		AP."Producer",
		CL."Description"
	FROM APPOINT AP, PATIENT PT, CLINIC CL
	WHERE 1=1
		AND AP."Type" = 0
		AND CL."Clinic" = AP."Clinic"
		AND AP."Patient" = PT."Patient"
		AND PT."Deleted" = 0
		AND PT."IsPatient" = 1
		AND AP."Date" >= TRUNC(SYSDATE)+1
		AND AP."Date" <= TRUNC(SYSDATE)+:1
		AND HIT_RULE_PKG.ACTIVE_MEDALERT(PT."Patient", :2) = 1
	ORDER BY PT."Chart"
	';

	OPEN pRefCursor FOR vSQLStmt USING pNumDays, pAlertCode;
END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE get_pt_reminders_labresult(IN plabname character varying, IN plabresult character varying, IN plabresultop character varying, IN pnumdays integer, INOUT prefcursor cursor_pkg.weakcursor)
 SECURITY DEFINER
AS $procedure$
	vSQLStmt VARCHAR2(4000);
BEGIN
	vSQLStmt :=
	'
	SELECT DISTINCT
		PT."Patient",
		PT."Chart",
		PT."Last",
		PT."First",
		PT."Sex",
		DECODE(PT."Sex", 0, ''U'', 1, ''M'', 2, ''F'', 3, ''T'', ''U'') AS "SexChar",
		TO_CHAR(SYSDATE,''YYYY'') - TO_CHAR(PT."Birth",''YYYY'') - CASE WHEN TO_CHAR(SYSDATE,''MMDD'') < TO_CHAR(PT."Birth",''MMDD'') THEN 1 ELSE 0 END AS "Age",
		PT."CustomCode4",
		PT."ContactAt",
		PT."HomeArea",
		PT."HomePhone",
		PT."WorkArea",
		PT."WorkPhone",
		PT."WorkExt",
		PT."OtherArea",
		PT."OtherPhone",
		PT."OtherExt",
		PT."MobileArea",
		PT."MobilePhone",
		PT."Email",
		PT."Address1",
		PT."Address2",
		PT."City",
		PT."Province",
		PT."Postal",
		PT."Country",
		TO_CHAR(AP."Date" + (AP."From"/1440),''DD-MON-YYYY HH24:MI:SS'') AS "ApptDateTime",
		AP."Code",
		AP."Producer",
		CL."Description"
	FROM APPOINT AP, PATIENT PT, CLINIC CL
	WHERE 1=1
		AND AP."Type" = 0
		AND CL."Clinic" = AP."Clinic"
		AND AP."Patient" = PT."Patient"
		AND PT."Deleted" = 0
		AND PT."IsPatient" = 1
		AND AP."Date" >= TRUNC(SYSDATE)+1
		AND AP."Date" <= TRUNC(SYSDATE)+:1
		AND HIT_CLINICAL_PKG.GET_LABRESULT_NOUNITS(PT."Patient", :2) ' || TRIM(pLabResultOp) || ' TO_NUMBER(:3)
		AND HIT_CLINICAL_PKG.GET_LABRESULT_NOUNITS(PT."Patient", :4) != -1
	ORDER BY PT."Chart"
	';

	OPEN pRefCursor FOR vSQLStmt USING pNumDays, TRIM(pLabName), TRIM(pLabResult), TRIM(pLabName);
END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE get_pt_reminders_medication(IN pmedication character varying, IN pnumdays integer, INOUT prefcursor cursor_pkg.weakcursor)
 SECURITY DEFINER
AS $procedure$
	vSQLStmt VARCHAR2(4000);
BEGIN
	vSQLStmt :=
	'
	SELECT DISTINCT
		PT."Patient",
		PT."Chart",
		PT."Last",
		PT."First",
		PT."Sex",
		DECODE(PT."Sex", 0, ''U'', 1, ''M'', 2, ''F'', 3, ''T'', ''U'') AS "SexChar",
		TO_CHAR(SYSDATE,''YYYY'') - TO_CHAR(PT."Birth",''YYYY'') - CASE WHEN TO_CHAR(SYSDATE,''MMDD'') < TO_CHAR(PT."Birth",''MMDD'') THEN 1 ELSE 0 END AS "Age",
		PT."CustomCode4",
		PT."ContactAt",
		PT."HomeArea",
		PT."HomePhone",
		PT."WorkArea",
		PT."WorkPhone",
		PT."WorkExt",
		PT."OtherArea",
		PT."OtherPhone",
		PT."OtherExt",
		PT."MobileArea",
		PT."MobilePhone",
		PT."Email",
		PT."Address1",
		PT."Address2",
		PT."City",
		PT."Province",
		PT."Postal",
		PT."Country",
		TO_CHAR(AP."Date" + (AP."From"/1440),''DD-MON-YYYY HH24:MI:SS'') AS "ApptDateTime",
		AP."Code",
		AP."Producer",
		CL."Description"
	FROM APPOINT AP, PATIENT PT, CLINIC CL
	WHERE 1=1
		AND AP."Type" = 0
		AND CL."Clinic" = AP."Clinic"
		AND AP."Patient" = PT."Patient"
		AND PT."Deleted" = 0
		AND PT."IsPatient" = 1
		AND AP."Date" >= TRUNC(SYSDATE)+1
		AND AP."Date" <= TRUNC(SYSDATE)+:1
		AND HIT_RULE_PKG.CURRENT_MEDICATION(PT."Patient", :2) = 1
	ORDER BY PT."Chart"
	';

	OPEN pRefCursor FOR vSQLStmt USING pNumDays, pMedication;
END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE get_pt_reminders_problem(IN pprobcode character, IN pnumdays integer, INOUT prefcursor cursor_pkg.weakcursor)
 SECURITY DEFINER
AS $procedure$
	vSQLStmt VARCHAR2(4000);
BEGIN
	vSQLStmt :=
	'
	SELECT DISTINCT
		PT."Patient",
		PT."Chart",
		PT."Last",
		PT."First",
		PT."Sex",
		DECODE(PT."Sex", 0, ''U'', 1, ''M'', 2, ''F'', 3, ''T'', ''U'') AS "SexChar",
		TO_CHAR(SYSDATE,''YYYY'') - TO_CHAR(PT."Birth",''YYYY'') - CASE WHEN TO_CHAR(SYSDATE,''MMDD'') < TO_CHAR(PT."Birth",''MMDD'') THEN 1 ELSE 0 END AS "Age",
		PT."CustomCode4",
		PT."ContactAt",
		PT."HomeArea",
		PT."HomePhone",
		PT."WorkArea",
		PT."WorkPhone",
		PT."WorkExt",
		PT."OtherArea",
		PT."OtherPhone",
		PT."OtherExt",
		PT."MobileArea",
		PT."MobilePhone",
		PT."Email",
		PT."Address1",
		PT."Address2",
		PT."City",
		PT."Province",
		PT."Postal",
		PT."Country",
		TO_CHAR(AP."Date" + (AP."From"/1440),''DD-MON-YYYY HH24:MI:SS'') AS "ApptDateTime",
		AP."Code",
		AP."Producer",
		CL."Description"
	FROM APPOINT AP, PATIENT PT, CLINIC CL
	WHERE 1=1
		AND AP."Type" = 0
		AND CL."Clinic" = AP."Clinic"
		AND AP."Patient" = PT."Patient"
		AND PT."Deleted" = 0
		AND PT."IsPatient" = 1
		AND AP."Date" >= TRUNC(SYSDATE)+1
		AND AP."Date" <= TRUNC(SYSDATE)+:1
		AND HIT_RULE_PKG.ACTIVE_PROBLEM(PT."Patient", :2) = 1
	ORDER BY PT."Chart"
	';

	OPEN pRefCursor FOR vSQLStmt USING pNumDays, pProbCode;
END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE get_pt_reminders_sex(IN psex integer, IN pnumdays integer, INOUT prefcursor cursor_pkg.weakcursor)
 SECURITY DEFINER
AS $procedure$
	vSQLStmt VARCHAR2(4000);
BEGIN
	vSQLStmt :=
	'
	SELECT DISTINCT
		PT."Patient",
		PT."Chart",
		PT."Last",
		PT."First",
		PT."Sex",
		DECODE(PT."Sex", 0, ''U'', 1, ''M'', 2, ''F'', 3, ''T'', ''U'') AS "SexChar",
		TO_CHAR(SYSDATE,''YYYY'') - TO_CHAR(PT."Birth",''YYYY'') - CASE WHEN TO_CHAR(SYSDATE,''MMDD'') < TO_CHAR(PT."Birth",''MMDD'') THEN 1 ELSE 0 END AS "Age",
		PT."CustomCode4",
		PT."ContactAt",
		PT."HomeArea",
		PT."HomePhone",
		PT."WorkArea",
		PT."WorkPhone",
		PT."WorkExt",
		PT."OtherArea",
		PT."OtherPhone",
		PT."OtherExt",
		PT."MobileArea",
		PT."MobilePhone",
		PT."Email",
		PT."Address1",
		PT."Address2",
		PT."City",
		PT."Province",
		PT."Postal",
		PT."Country",
		TO_CHAR(AP."Date" + (AP."From"/1440),''DD-MON-YYYY HH24:MI:SS'') AS "ApptDateTime",
		AP."Code",
		AP."Producer",
		CL."Description"
	FROM APPOINT AP, PATIENT PT, CLINIC CL
	WHERE 1=1
		AND AP."Type" = 0
		AND CL."Clinic" = AP."Clinic"
		AND AP."Patient" = PT."Patient"
		AND PT."Deleted" = 0
		AND PT."IsPatient" = 1
		AND AP."Date" >= TRUNC(SYSDATE)+1
		AND AP."Date" <= TRUNC(SYSDATE)+:1
		AND PT."Sex" = :2
	ORDER BY PT."Chart"
	';

	OPEN pRefCursor FOR vSQLStmt USING pNumDays, pSex;
END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE getepr_allforms(INOUT ref_cursor cursor_pkg.weakcursor, IN patientid numeric)
 SECURITY DEFINER
AS $procedure$

   sqlstmt   VARCHAR2 (4000 );

BEGIN

   sqlstmt :=

      'SELECT   0 AS "PItem", f."FItem", pf."PForm", pf."FormCode", pf."Date",

         pf."Description", pf."OwnerId", pf."OwnerType", 0 AS "NoteOvr",

         '''' AS "NoteOvrText", f."Page", f."Row", f."Type", f."AnsType",

         f."Text", 0 AS "PtSig", SYSDATE AS "PtSigDate"

    FROM EFC_fitem f, EFC_pform pf

   WHERE f."FormCode" = pf."FormCode"

     AND pf."Patient" = $1

     AND f."Deleted" = 0

     AND NOT EXISTS (

            SELECT ''x''

              FROM EFC_pitem p

             WHERE p."FItem" = f."FItem" AND p."Status" = 0

                   AND p."Patient" = $2)

UNION ALL

SELECT   p."PItem", f."FItem", pf."PForm", pf."FormCode", pf."Date",

         pf."Description", pf."OwnerId", pf."OwnerType",

         NVL (novr."Id", 0) AS "NoteOvr", NVL (novr."Text",

                                               '''') AS "NoteOvrText", f."Page",

         f."Row", f."Type", f."AnsType", f."Text", 0 AS "PtSig",

         SYSDATE AS "PtSigDate"

    FROM EFC_fitem f, EFC_pitem p, EFC_pform pf, noteovr novr

   WHERE f."FItem" = p."FItem"

     AND p."PForm" = pf."PForm"

     AND pf."Patient" = p."Patient"

     AND novr."ParentId"(+) = p."PItem"

     AND novr."Patient"(+) = p."Patient"

     AND f."FormCode" = ANY (SELECT fc."Code"

                               FROM EFC_form fc

                              WHERE fc."Code" = p."FormCode")

     AND p."Patient" = $3

     AND p."Status" = 0

     AND novr."Type"(+) = 1

     AND novr."Deleted"(+) = 0

UNION ALL

SELECT   0 AS "PItem", pp."FItem", pp."PForm", f."FormCode" AS "FormCode",

         SYSDATE AS "Date", '''' AS "Description", pf."OwnerId", pf."OwnerType",

         0 AS "NoteOvr", '''' AS "NoteOvrText", f."Page", f."Row", 1234 as "Type",

         1234 AS "AnsType", NVL (pp."Comment", '' '') AS "Text", pp."PtSig",

         pp."PtSigDate"

    FROM EFC_ppage pp, EFC_fitem f, EFC_pform pf

   WHERE f."FItem" = pp."FItem" AND pp."PForm" = pf."PForm" and pp."Patient" = $4 AND pp."Status" = 0

UNION ALL

SELECT   0 AS "PItem", pp."FItem", pp."PForm", f."FormCode" AS "FormCode",

         SYSDATE AS "Date", '''' AS "Description", pf."OwnerId", pf."OwnerType",

         0 AS "NoteOvr", '''' AS "NoteOvrText", f."Page", f."Row", 10000+ABS(pps."PtSig") as "Type",

         pps."PPage" AS "AnsType", NVL (pp."Comment", '' '') AS "Text", pps."PtSig",

         pp."PtSigDate"

    FROM EFC_ppage pp, EFC_fitem f, EFC_pform pf, EFC_ppagesig pps

   WHERE f."FItem" = pp."FItem" AND pp."PForm" = pf."PForm" and pp."Patient" = $5 AND pp."Status" = 0 and pp."PPage" = pps."PPage"

ORDER BY "PItem" DESC';



   OPEN ref_cursor

    FOR sqlstmt USING patientid, patientid, patientid, patientid, patientid;

END

$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE menu3_details(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vColVal         NUMBER(10) := -1;
        vReportingYear  VARCHAR2(100 ) := '';
        vSQLStmt        VARCHAR2(2500 ) := '';
        vRefCode        VARCHAR2(10 ) := 'MU_MENU3';

    BEGIN
        vReportingYear := TO_CHAR(vRStartDate, 'MM/DD/YYYY')
                          || ' - ' ||
                          TO_CHAR(vREndDate, 'MM/DD/YYYY') ;

        BEGIN
              SELECT pi1."PItemCol" INTO vColVal
              FROM PITEM pi1, PFORM p1
              WHERE 1=1
              AND pi1."PForm" = p1."PForm"
              AND pi1."FItem" IN (
                                SELECT f1."FItem"
                                FROM FITEM f1
                                WHERE 1=1
                                AND f1."Code" = 'MU_MRP'
                                AND f1."Deleted" = 0)
              AND pi1."AnsText" <> TRIM('+')
              AND pi1."Status" = 0
              AND pi1."AppDate" IS NOT NULL
              AND p1."OwnerId" = pUser
              AND TRIM(pi1."AnsText") = TRIM(vReportingYear);

            EXCEPTION WHEN NO_DATA_FOUND THEN
            vColVal := -1;
          END;

          vSQLStmt := '
                        SELECT pi2."AnsYes", pi2."Date", u1."Name", u1."First", pi2."FormCode"
                        FROM PITEM pi2, PFORM p2, USERS u1
                        WHERE 1=1
                        AND pi2."FItem" = ( SELECT f1."FItem"
                                            FROM FITEM f1
                                            WHERE 1=1
                                            AND TRIM(f1."Code") = '''||vRefCode||'''
                                            AND f1."Deleted" = 0)
                        AND pi2."Status" = 0
                        AND pi2."Patient" = 0
                        AND pi2."AppDate" IS NOT NULL
                        AND p2."OwnerId" = '||pUser||'
                        AND pi2."PForm" = p2."PForm"
                        AND pi2."PItemCol"= :1
                        AND pi2."User" = u1."User"
                    ';
        OPEN MUWeakCursor FOR vSQLStmt USING vColVal;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE menu5_details_d(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vProducer   CHAR(10 );
        vSQLStmt VARCHAR2(2500 );
    BEGIN

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                      SELECT "Patient", "Last", "First", "Chart", MAX("Flag") as "Flag"
                      FROM (
                        SELECT DISTINCT a1."Patient", p1."Last", p1."First", p1."Chart",
                          NVL(( SELECT DISTINCT 1
                                FROM IUSER i1, AUDITHIS a2
                                WHERE 1=1
                                AND i1."Id" = a1."Patient"
                                AND i1."Audit" = a2."Audit"
                                AND i1."Deleted" = 0
                                AND i1."IsLocked" = 0
                                AND ( CASE WHEN ((TRUNC(a1."Date") -  TRUNC(a2."Date")) >= -14)
                                        THEN
                                          CASE WHEN (TRUNC(a1."Date") -  TRUNC(a2."Date") - MU_CORE_PKG.COUNT_HDAYS(TO_DATE(a1."Date"), TO_DATE(a2."Date")) > -3)
                                            THEN 1
                                            ELSE 0
                                          END
                                        ELSE 0
                                      END) = 1
                              ),0) as "Flag"
                        FROM APPOINT a1, PATIENT p1
                        WHERE 1=1
                        AND a1."Patient" = p1."Patient"
                        AND a1."Type" IN (0,1,2)
                        AND TRIM(a1."Producer") = TRIM(:1)
                        AND a1."Status" = 0
                        AND TRUNC(a1."Date") BETWEEN TRUNC(TO_DATE('''||vRStartDate||''')) AND TRUNC(TO_DATE('''||vREndDate||'''))
                      )
                      GROUP BY "Patient","Last", "First", "Chart"
                    ';
        OPEN MUWeakCursor FOR vSQLStmt USING  TRIM(vProducer);
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE menu5_details_n(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vProducer   CHAR(10);
        vSQLStmt VARCHAR2(2500);
    BEGIN

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                    SELECT DISTINCT a1."Patient", p1."Last", p1."First", p1."Chart"
                    FROM APPOINT a1, PATIENT p1
                    WHERE 1=1
                    AND a1."Patient" = p1."Patient"
                    AND a1."Type" IN (0,1,2)
                    AND TRIM(a1."Producer") = TRIM(:1)
                    AND TRUNC(a1."Date") BETWEEN TRUNC(TO_DATE(:2)) AND TRUNC(TO_DATE(:3))
                    AND EXISTS (SELECT 1
                                FROM IUSER i1, AUDITHIS a2
                                WHERE 1=1
                                AND i1."Id" = a1."Patient"
                                AND i1."CreateAudit" = a2."Audit"
                                AND i1."Deleted" = 0
                                AND i1."IsLocked" = 0
                                AND (CASE WHEN ((TRUNC(a1."Date") -  TRUNC(a2."Date")) >= -14)
                                               THEN
                                               CASE WHEN (TRUNC(a1."Date") -  TRUNC(a2."Date") - MU_CORE_PKG.COUNT_HDAYS(TO_DATE(a1."Date"), TO_DATE(a2."Date")) > -3)
                                                    THEN 1
                                                    ELSE 0
                                               END
                                               ELSE 0
                                           END) = 1)
                    ';
        OPEN MUWeakCursor FOR vSQLStmt USING  TRIM(vProducer), TRUNC(vRStartDate), TRUNC(vREndDate);
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE menu9_details(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vColVal         NUMBER(10) := -1;
        vReportingYear  VARCHAR2(100 ) := '';
        vSQLStmt        VARCHAR2(2500 ) := '';
        vRefCode        VARCHAR2(10 ) := 'MU_MENU9';

    BEGIN
        vReportingYear := TO_CHAR(vRStartDate, 'MM/DD/YYYY')
                          || ' - ' ||
                          TO_CHAR(vREndDate, 'MM/DD/YYYY') ;

        BEGIN
              SELECT pi1."PItemCol" INTO vColVal
              FROM PITEM pi1, PFORM p1
              WHERE 1=1
              AND pi1."PForm" = p1."PForm"
              AND pi1."FItem" IN (SELECT f1."FItem"
                                  FROM FITEM f1
                                  WHERE 1=1
                                  AND f1."Code" = 'MU_MRP'
                                  AND f1."Deleted" = 0)
              AND pi1."AnsText" <> TRIM('+')
              AND pi1."Status" = 0
              AND pi1."AppDate" IS NOT NULL
              AND p1."OwnerId" = pUser
              AND TRIM(pi1."AnsText") = TRIM(vReportingYear);

            EXCEPTION WHEN NO_DATA_FOUND THEN
            vColVal := -1;
          END;

          vSQLStmt := '
                        SELECT pi2."AnsListRefCode", pi2."Date", u1."Name", u1."First", p2."FormCode"
                        FROM PITEM pi2, PFORM p2, USERS u1
                        WHERE 1=1
                        AND pi2."FItem" = ( SELECT f1."FItem"
                                            FROM FITEM f1
                                            WHERE 1=1
                                            AND TRIM(f1."Code") = '''||vRefCode||'''
                                            AND f1."Deleted" = 0)
                        AND pi2."Status" = 0
                        AND pi2."Patient" = 0
                        AND pi2."AppDate" IS NOT NULL
                        AND p2."OwnerId" = '||pUser||'
                        AND pi2."PForm" = p2."PForm"
                        AND pi2."PItemCol"= :1
                        AND pi2."User" = u1."User"
                    ';
        OPEN MUWeakCursor FOR vSQLStmt USING vColVal;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE merge_epr(IN oldpatientid numeric, IN newpatientid numeric, OUT success numeric)
 SECURITY DEFINER
AS $procedure$
   CURSOR pitems_csr (pOldPatientId IN NUMBER, pNewPatientId NUMBER)
   IS
      SELECT   "PItem", "Patient", "FItem", "FormCode", "Date",
               "AuditNumber"
          FROM pitem
         WHERE "Patient" IN (pOldPatientId, pNewPatientId)
      ORDER BY "FormCode", "FItem", "Date" ASC, "PItem" ASC;

   CURSOR ppages_csr (pOldPatientId NUMBER, pNewPatientId NUMBER)
   IS
      SELECT   ROWID , "Patient", "FItem", "FormCode", "Date",
               "AuditNumber"
          FROM ppage
         WHERE "Patient" IN (pOldPatientId, pNewPatientId)
      ORDER BY "FormCode", "FItem", "Date" ASC, "AuditNumber" ASC;

   CURSOR pforms_csr (pNewPatientId NUMBER)
   IS
      SELECT *
        FROM pform
       WHERE "Patient" = pNewPatientId;

   vDate              DATE;
   vUser              NUMBER (10);
   vCurrentFItem      NUMBER (10);
   vCurrentFormCode   CHAR (6);
   vSeq               NUMBER (5);
   vStatus            NUMBER (1);
   vCount             NUMBER (5);
BEGIN
   -- Merge Pitems
   vCurrentFItem := 0;
   vCurrentFormCode := ' ';

   -- Update "AuditNumber" to a higher value to avoid Unique Key Constraints
   -- when resequencing
   UPDATE pitem
      SET "AuditNumber" = "AuditNumber" + 1000
    WHERE "Patient" IN (OldPatientId, NewPatientId);

   FOR pitem_rec IN pitems_csr (OldPatientId, NewPatientId)
   LOOP
      -- Set reset sequence to 1 and status to 1 whenever we switch to a
      -- different "FItem" or "FormCode"
      IF vCurrentFormCode != pitem_rec."FormCode" OR
         vCurrentFItem != pitem_rec."FItem"
      THEN
         vCurrentFormCode := pitem_rec."FormCode";
         vCurrentFItem := pitem_rec."FItem";
         vSeq := 1;
         vStatus := 1;

         SELECT COUNT (1)
           INTO vCount
           FROM pitem
          WHERE "Patient" IN (OldPatientId, NewPatientId)
            AND "FItem" = vCurrentFItem
            AND "FormCode" = vCurrentFormCode;
      END IF;

      IF vSeq = vCount
      THEN
         vStatus := 0;
      END IF;

      UPDATE pitem
         SET "Patient" = NewPatientId,
             "AuditNumber" = vSeq,
             "Status" = vStatus
       WHERE "PItem" = pitem_rec."PItem";

      vSeq := vSeq + 1;
   END LOOP;

   -- Start merge for ppage
   vCurrentFItem := 0;
   vCurrentFormCode := ' ';

   -- Update "AuditNumber" to a higher value to avoid Unique Key Constraints
   -- when resequencing
   UPDATE ppage
      SET "AuditNumber" = "AuditNumber" + 1000
    WHERE "Patient" IN (OldPatientId, NewPatientId);

   FOR ppage_rec IN ppages_csr (OldPatientId, NewPatientId)
   LOOP
      -- Set reset sequence to 1 and status to 1 whenever we switch to a
      -- different "FItem" or "FormCode"
      IF vCurrentFormCode != ppage_rec."FormCode" OR
         vCurrentFItem != ppage_rec."FItem"
      THEN
         vCurrentFormCode := ppage_rec."FormCode";
         vCurrentFItem := ppage_rec."FItem";
         vSeq := 1;
         vStatus := 1;

         -- Get the last value for the AuditNumber
         SELECT COUNT (1)
           INTO vCount
           FROM ppage
          WHERE "Patient" IN (OldPatientId, NewPatientId)
            AND "FItem" = vCurrentFItem
            AND "FormCode" = vCurrentFormCode;
      END IF;

      -- If sequence have reached the last AuditNumber, then set the status to 0
      IF vSeq = vCount
      THEN
         vStatus := 0;
      END IF;

      UPDATE ppage
         SET "Patient" = NewPatientId,
             "AuditNumber" = vSeq,
             "Status" = vStatus
       WHERE ROWID = ppage_rec.ROWID;

      vSeq := vSeq + 1;
   END LOOP;

   -- Start merge for pforms
   FOR pform_rec IN pforms_csr (NewPatientId)
   LOOP
      -- Get the Date of the old Patient FormCode
      BEGIN
         SELECT "Date", "User"
           INTO vDate, vUser
           FROM pform
          WHERE "Patient" = OldPatientId AND "FormCode" = pform_rec."FormCode";
      EXCEPTION
         WHEN NO_DATA_FOUND
         THEN
            vDate := NULL;
      END;

      -- Set Date and User of new patient FormCode to the earlier date.
      IF vDate < pform_rec."Date"
      THEN
         UPDATE pform
            SET "Date" = vDate, "User" = vUser
          WHERE "Patient" = NewPatientId AND "FormCode" = pform_rec."FormCode";
      END IF;

      DELETE FROM pform
            WHERE "Patient" = OldPatientId
              AND "FormCode" = pform_rec."FormCode";
   END LOOP;
   -- Convert any other old patient form to the new patient
   UPDATE pform
      SET "Patient" = NewPatientId
   WHERE "Patient" = OldPatientId;

   COMMIT;
   Success := 1;
   EXCEPTION
     WHEN OTHERS
     THEN
        ROLLBACK;
        Success := 0;
END MERGE_EPR$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE pp_open_bal_proc(INOUT pp_open_bal_cursor payplan_bal_pkg.pp_open_bal_type, IN patient numeric)
 SECURITY DEFINER
AS $procedure$
  AR NUMBER := 0.0;
BEGIN
  AR := PAYPLAN_BAL_PKG.PP_OPEN_BAL(Patient);

  open PP_OPEN_BAL_Cursor for
   select AR from dual;
END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE ptbal_over30(INOUT ptbal_cursor lastappointtrx_pkg.ptbal_type, IN patient numeric)
 SECURITY DEFINER
AS $procedure$
  PatientBalance NUMBER := 0.0;
BEGIN
  PatientBalance := LASTAPPOINTTRX_PKG.PtOver30Balance(Patient);

  open PTBAL_Cursor for
    select PatientBalance as PatientBalance from dual;
END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE stage1menu4_details(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vSQLStmt  VARCHAR2(2500 ) := '';

    BEGIN

        vSQLStmt := '
                      SELECT "Patient", "Last", "First", "Chart", MAX("Flag") as "Flag"
                      FROM (
                        SELECT DISTINCT pt1."Patient", pt1."Last", pt1."First", pt1."Chart",
                          NVL(( SELECT DISTINCT 1
                                FROM PTCONT ptc
                                WHERE 1=1
                                AND ptc."Patient" = pt1."Patient"
                                AND TRIM(ptc."NoteCode") IN (''EMAIL'', ''LETTER'',''PHONE'')
                                AND ptc."Deleted" = 0
                                AND ptc."ContactDate" BETWEEN TRUNC(TO_DATE('''||vRStartDate||''')) AND TRUNC(TO_DATE('''||vREndDate||'''))
                              ),0) as "Flag"
                        FROM PATIENT pt1
                        WHERE 1=1
                        AND pt1."Deleted" = 0
                        AND (MU_CORE_PKG.CALC_PT_AGE(pt1."Patient") >= 65 OR MU_CORE_PKG.CALC_PT_AGE(pt1."Patient") <= 5)
                      )
                      GROUP BY "Patient", "Last", "First", "Chart"
                    ';

        OPEN MUWeakCursor FOR vSQLStmt;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE stage1menu6_details_d(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vProducer   CHAR(10 );
        vSQLStmt    VARCHAR2(2500 );
    BEGIN

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                      SELECT DISTINCT "Patient", "Last", "First", "Chart", MAX("Flag") "Flag"
                      FROM (
                        SELECT DISTINCT a1."Patient", p1."Last", p1."First", p1."Chart",
                          NVL((SELECT 1 FROM
                             PITEM p3, FITEM f1
                             WHERE 1=1
                             AND p3."FItem" = f1."FItem"
                             AND p3."Patient" = a1."Patient"
                             --AND TRIM(p3."FormCode") IN (''MUMDH'')
                             AND TRIM(f1."Code") IN (''A15_YN'')
                             AND TRIM(p3."AnsYes") = 1
                             AND p3."AuditNumber" = ( SELECT MAX(p3n."AuditNumber")
                                                      FROM PITEM p3n, FITEM f1n
                                                      WHERE 1=1
                                                      AND p3n."PForm" = p3."PForm"
                                                      AND p3n."FItem" = f1n."FItem"
                                                      AND p3n."Patient" = p3."Patient"
                                                      AND f1n."Code" = f1."Code"
                                                      AND TRUNC(p3n."Date") <= TRUNC(TO_DATE('''||vREndDate||'''))
                                                      GROUP BY f1n."Code"
                                                      )),0) AS "Flag"
                         FROM APPOINT a1, PATIENT p1
                         WHERE 1=1
                         AND a1."Patient" = p1."Patient"
                         AND TRIM(a1."Producer") = TRIM('''||vProducer||''')
                         AND a1."Type" IN (0,1,2)
                         AND a1."Status" = 0
                         AND TRUNC(a1."Date") BETWEEN TRUNC(TO_DATE('''||vRStartDate||''')) AND TRUNC(TO_DATE('''||vREndDate||'''))
                      )
                      GROUP BY "Patient", "Last", "First", "Chart"
                    ';
        OPEN MUWeakCursor FOR vSQLStmt;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE stage1menu7_details_d(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vProducer   CHAR(10 );
        vSQLStmt    VARCHAR2(2500 );
        vProcCode  CHAR(10 ) := 'M99495';

    BEGIN

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                      SELECT p1."Patient", p1."Last", p1."First", p1."Chart",
                          NVL(( SELECT DISTINCT 1
                                FROM PTLINFO pti1, AUDITHIS ah1
                                WHERE 1=1
                                AND a1."Patient" = pti1."Patient"
                                AND pti1."Audit" = ah1."Audit"
                                AND pti1."PtLType" = 2
                                AND ah1."Date" <= TRUNC(TO_DATE('''||vREndDate||'''))
                                AND ah1."User" = '''|| pUser || '''
                              ),0) AS "Flag"
                         FROM APPOINT a1, APPTRX at1, PATIENT p1
                         WHERE 1=1
                         AND a1."Appointment" = at1."Appointment"
                         AND a1."Patient" = p1."Patient"
                         AND TRIM(a1."Producer") = TRIM('''||vProducer||''')
                         AND a1."Type" IN (0,1,2)
                         AND a1."Status" = 0
                         AND TRUNC(a1."Date") BETWEEN TRUNC(TO_DATE('''||vRStartDate||''')) AND TRUNC(TO_DATE('''||vREndDate||'''))
                         AND at1."Procedure" IN ('''||vProcCode||''')
                    ';

        OPEN MUWeakCursor FOR vSQLStmt;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE stage1menu8_details_d(INOUT muweakcursor cursor_pkg.weakcursor, IN puser numeric, IN vrstartdate timestamp without time zone, IN vrenddate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$
        vProducer   CHAR(10 );
        vSQLStmt    VARCHAR2(2500 );
    BEGIN

        SELECT TRIM(u1."Producer") INTO vProducer FROM USERS u1 WHERE u1."User" = pUser;

        vSQLStmt := '
                      SELECT "Patient", "Last", "First", "Chart", MAX("Flag") "Flag"
                      FROM (
                        SELECT DISTINCT pf1."Patient", pf1."PForm", p1."Last", p1."First", p1."Chart",
                          NVL(( SELECT DISTINCT 1
                                FROM PITEM pi2, FITEM fi2
                                WHERE 1=1
                                AND pi2."PForm" = pf1."PForm"
                                AND pi2."FItem" = fi2."FItem"
                                AND pi2."Patient" = pf1."Patient"
                                AND TRUNC(pi2."Date") <= TRUNC(TO_DATE('''||vREndDate||'''))
                                AND fi2."Code" IN (''MUREFSUM'')
                                AND pi2."AnsYes" = 1
                                AND pi2."AuditNumber" = ( SELECT MAX(pi3."AuditNumber")
                                                          FROM PITEM pi3, FITEM fi3
                                                          WHERE 1=1
                                                          AND pi3."FItem" = fi3."FItem"
                                                          AND pi3."PForm" = pi2."PForm"
                                                          AND pi3."Patient" = pi2."Patient"
                                                          AND fi3."Code" = fi2."Code"
                                                          --AND pi3."AppUser" != 0
                                                          AND TRUNC(pi3."Date") <= TRUNC(TO_DATE('''||vREndDate||'''))
                                                          GROUP BY fi3."Code"
                                                        )
                              ),0) AS "Flag"
                         FROM PFORM pf1, PATIENT p1
                         WHERE 1=1
                         AND pf1."Patient" = p1."Patient"
                         AND pf1."User" = '''|| pUser || '''
                         AND pf1."FormCode" IN (''MUREF'')
                         AND TRUNC(pf1."CreatedDate") BETWEEN TRUNC(TO_DATE('''||vRStartDate||''')) AND TRUNC(TO_DATE('''||vREndDate||'''))
                      )
                      GROUP BY "Patient", "PForm", "Last", "First", "Chart"
                    ';

        OPEN MUWeakCursor FOR vSQLStmt;
    END$procedure$
 LANGUAGE edbspl
;
CREATE OR REPLACE PROCEDURE trxdept_proc(INOUT ref_cursor cursor_pkg.weakcursor, IN department character, IN fromdate timestamp without time zone, IN todate timestamp without time zone)
 SECURITY DEFINER
AS $procedure$

  vSQLStmt VARCHAR (6000) := NULL;

BEGIN

  vSQLStmt      := 'SELECT trx."Type", trx."Id", trx."Treatment", :1 "Department" FROM trx, producer, patient WHERE trx."Producer" = producer."Producer"(+) AND trx."TreatmentDate" >= :2 AND trx."TreatmentDate" <= :3 AND trx."OrthoStatus" <> 1 AND trx."Status" = ''C'' AND trx."Deleted" = 0 AND trx."Type" = 1 AND trx."Patient" = patient."Patient"';

  IF Department <> ' ' THEN

    vSQLStmt    := vSQLStmt || ' AND ' || DEPT_PKG.DEPTWHERE (Department, 'trx', 'producer', 'patient');

  END IF;

  OPEN Ref_Cursor FOR vSQLStmt USING Department, FromDate, ToDate;

END

$procedure$
 LANGUAGE edbspl
;
 
-- VIEWS 
CREATE OR REPLACE VIEW all_arguments AS
 SELECT a.specific_schema AS schema_name,
    upper(substr(a.specific_name::text, 1::numeric, (instr(a.specific_name::character varying, '_'::character varying, '-1'::integer::numeric) - 1)::numeric))::character(255) AS object_name,
    a.ordinal_position AS "position",
        CASE
            WHEN a.data_type::text = 'numeric'::text THEN 'NUMBER'::text
            WHEN a.data_type::text = 'character'::text THEN 'CHAR'::text
            WHEN a.data_type::text = 'character varying'::text THEN 'VARCHAR2'::text
            WHEN a.data_type::text = 'date'::text THEN 'DATE'::text
            WHEN a.data_type::text = 'timestamp without time zone'::text THEN 'DATE'::text
            ELSE 'UNKNOWN'::text
        END AS data_type,
    a.parameter_name,
    a.parameter_mode AS in_out,
    p.object_id,
    0 AS data_level,
    upper((( SELECT pg_stat_activity.usename
           FROM pg_stat_activity
          WHERE pg_stat_activity.pid = pg_backend_pid()))::text) AS owner
   FROM information_schema.parameters a,
    user_procedures p
  WHERE a.specific_schema::name = (( SELECT "current_schema"() AS "current_schema")) AND upper(substr(a.specific_name::text, 1::numeric, (instr(a.specific_name::character varying, '_'::character varying, '-1'::integer::numeric) - 1)::numeric)) = p.object_name
UNION
 SELECT a.specific_schema AS schema_name,
    upper(substr(a.specific_name::text, 1::numeric, (instr(a.specific_name::character varying, '_'::character varying, '-1'::integer::numeric) - 1)::numeric))::character(255) AS object_name,
    a.ordinal_position AS "position",
        CASE
            WHEN a.data_type::text = 'numeric'::text THEN 'NUMBER'::text
            WHEN a.data_type::text = 'character'::text THEN 'CHAR'::text
            WHEN a.data_type::text = 'character varying'::text THEN 'VARCHAR2'::text
            WHEN a.data_type::text = 'date'::text THEN 'DATE'::text
            WHEN a.data_type::text = 'timestamp without time zone'::text THEN 'DATE'::text
            ELSE 'UNKNOWN'::text
        END AS data_type,
    a.parameter_name,
    a.parameter_mode AS in_out,
    p.object_id,
    0 AS data_level,
    upper((( SELECT pg_stat_activity.usename
           FROM pg_stat_activity
          WHERE pg_stat_activity.pid = pg_backend_pid()))::text) AS owner
   FROM information_schema.parameters a,
    user_procedures p
  WHERE upper(a.specific_schema::text) = p.object_name AND upper(substr(a.specific_name::text, 1::numeric, (instr(a.specific_name::character varying, '_'::character varying, '-1'::integer::numeric) - 1)::numeric)) = p.procedure_name
UNION
 SELECT n.nspname AS schema_name,
    upper(p.proname::text)::character(255) AS object_name,
    0 AS "position",
        CASE
            WHEN COALESCE(pg_get_function_result(p.oid), ''::text) = 'numeric'::text THEN 'NUMBER'::text
            WHEN COALESCE(pg_get_function_result(p.oid), ''::text) = 'character'::text THEN 'CHAR'::text
            WHEN COALESCE(pg_get_function_result(p.oid), ''::text) = 'character varying'::text THEN 'VARCHAR2'::text
            WHEN COALESCE(pg_get_function_result(p.oid), ''::text) = 'date'::text THEN 'DATE'::text
            WHEN COALESCE(pg_get_function_result(p.oid), ''::text) = 'timestamp without timezone'::text THEN 'DATE'::text
            ELSE 'UNKNOWN'::text
        END AS data_type,
    ' '::name AS parameter_name,
    'OUT'::character varying AS in_out,
    p.oid AS object_id,
    0 AS data_level,
    upper((( SELECT pg_stat_activity.usename
           FROM pg_stat_activity
          WHERE pg_stat_activity.pid = pg_backend_pid()))::text) AS owner
   FROM pg_proc p,
    pg_namespace n
  WHERE n.nspname = (( SELECT "current_schema"() AS "current_schema")) AND p.pronamespace = n.oid
  ORDER BY 1, 2, 3
;
CREATE OR REPLACE VIEW anesthetictotal_view AS
 SELECT "PtSDrug",
    sum("Amount") AS "Total"
   FROM ptsdose
  GROUP BY "PtSDrug"
;
CREATE OR REPLACE VIEW apexpert_bookopenhour_view AS
 SELECT "Date",
    "Clinic",
    "ClinicDesc",
    "Chair",
    "ChairDesc",
    "StartTime",
    "EndTime",
    "Type",
    "Id"
   FROM ( WITH tmpbookdet AS (
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From0" AS "StartTime",
                    bd."To0" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 2::numeric AND bd."Opened0" = 1::numeric AND bd."From0" > 0::numeric AND bd."To0" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From0Second" AS "StartTime",
                    bd."To0Second" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 2::numeric AND bd."Opened0" = 1::numeric AND bd."From0Second" > 0::numeric AND bd."To0Second" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From0Third" AS "StartTime",
                    bd."To0Third" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 2::numeric AND bd."Opened0" = 1::numeric AND bd."From0Third" > 0::numeric AND bd."To0Third" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From1" AS "StartTime",
                    bd."To1" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 3::numeric AND bd."Opened1" = 1::numeric AND bd."From1" > 0::numeric AND bd."To1" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From1Second" AS "StartTime",
                    bd."To1Second" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 3::numeric AND bd."Opened1" = 1::numeric AND bd."From1Second" > 0::numeric AND bd."To1Second" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From1Third" AS "StartTime",
                    bd."To1Third" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 3::numeric AND bd."Opened1" = 1::numeric AND bd."From1Third" > 0::numeric AND bd."To1Third" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From2" AS "StartTime",
                    bd."To2" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 4::numeric AND bd."Opened2" = 1::numeric AND bd."From2" > 0::numeric AND bd."To2" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From2Second" AS "StartTime",
                    bd."To2Second" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 4::numeric AND bd."Opened2" = 1::numeric AND bd."From2Second" > 0::numeric AND bd."To2Second" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From2Third" AS "StartTime",
                    bd."To2Third" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 4::numeric AND bd."Opened2" = 1::numeric AND bd."From2Third" > 0::numeric AND bd."To2Third" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From3" AS "StartTime",
                    bd."To3" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 5::numeric AND bd."Opened3" = 1::numeric AND bd."From3" > 0::numeric AND bd."To3" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From3Second" AS "StartTime",
                    bd."To3Second" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 5::numeric AND bd."Opened3" = 1::numeric AND bd."From3Second" > 0::numeric AND bd."To3Second" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From3Third" AS "StartTime",
                    bd."To3Third" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 5::numeric AND bd."Opened3" = 1::numeric AND bd."From3Third" > 0::numeric AND bd."To3Third" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From4" AS "StartTime",
                    bd."To4" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 6::numeric AND bd."Opened4" = 1::numeric AND bd."From4" > 0::numeric AND bd."To4" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From4Second" AS "StartTime",
                    bd."To4Second" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 6::numeric AND bd."Opened4" = 1::numeric AND bd."From4Second" > 0::numeric AND bd."To4Second" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From4Third" AS "StartTime",
                    bd."To4Third" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 6::numeric AND bd."Opened4" = 1::numeric AND bd."From4Third" > 0::numeric AND bd."To4Third" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From5" AS "StartTime",
                    bd."To5" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 7::numeric AND bd."Opened5" = 1::numeric AND bd."From5" > 0::numeric AND bd."To5" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From5Second" AS "StartTime",
                    bd."To5Second" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 7::numeric AND bd."Opened5" = 1::numeric AND bd."From5Second" > 0::numeric AND bd."To5Second" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From5Third" AS "StartTime",
                    bd."To5Third" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 7::numeric AND bd."Opened5" = 1::numeric AND bd."From5Third" > 0::numeric AND bd."To5Third" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From6" AS "StartTime",
                    bd."To6" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 1::numeric AND bd."Opened6" = 1::numeric AND bd."From6" > 0::numeric AND bd."To6" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From6Second" AS "StartTime",
                    bd."To6Second" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 1::numeric AND bd."Opened6" = 1::numeric AND bd."From6Second" > 0::numeric AND bd."To6Second" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From6Third" AS "StartTime",
                    bd."To6Third" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 1::numeric AND bd."Opened6" = 1::numeric AND bd."From6Third" > 0::numeric AND bd."To6Third" > 0::numeric
                )
         SELECT DISTINCT tbd."Date",
            c."Clinic",
            c."Description" AS "ClinicDesc",
            bc."Chair",
            ch."Name" AS "ChairDesc",
            tbd."StartTime",
            tbd."EndTime",
            'B'::character(1) AS "Type",
            tbd."Book" AS "Id"
           FROM tmpbookdet tbd,
            clinic c,
            chair ch,
            bookchr bc,
            book b
          WHERE 1 = 1 AND tbd."BookDetail" = bc."BookDetail" AND tbd."Book" = b."Book" AND b."Inactive" = 0::numeric AND bc."Chair" = ch."Chair" AND ch."Unavailable" = 0::numeric AND ch."IsOverflow" = 0::numeric AND ch."Clinic" = c."Clinic" AND c."Inactive" = 0::numeric) tbd2
  WHERE 1 = 1
;
CREATE OR REPLACE VIEW apexpert_bookopenhour_view2 AS
 SELECT "Date",
    "Clinic",
    "ClinicDesc",
    "Chair",
    "ChairDesc",
    "StartTime",
    "EndTime",
    "Type",
    "Id"
   FROM ( WITH tmpbookdet AS (
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From0" AS "StartTime",
                    bd."To0" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 2::numeric AND bd."Opened0" = 1::numeric AND bd."From0" > 0::numeric AND bd."To0" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From0Second" AS "StartTime",
                    bd."To0Second" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 2::numeric AND bd."Opened0" = 1::numeric AND bd."From0Second" > 0::numeric AND bd."To0Second" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From0Third" AS "StartTime",
                    bd."To0Third" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 2::numeric AND bd."Opened0" = 1::numeric AND bd."From0Third" > 0::numeric AND bd."To0Third" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From1" AS "StartTime",
                    bd."To1" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 3::numeric AND bd."Opened1" = 1::numeric AND bd."From1" > 0::numeric AND bd."To1" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From1Second" AS "StartTime",
                    bd."To1Second" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 3::numeric AND bd."Opened1" = 1::numeric AND bd."From1Second" > 0::numeric AND bd."To1Second" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From1Third" AS "StartTime",
                    bd."To1Third" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 3::numeric AND bd."Opened1" = 1::numeric AND bd."From1Third" > 0::numeric AND bd."To1Third" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From2" AS "StartTime",
                    bd."To2" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 4::numeric AND bd."Opened2" = 1::numeric AND bd."From2" > 0::numeric AND bd."To2" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From2Second" AS "StartTime",
                    bd."To2Second" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 4::numeric AND bd."Opened2" = 1::numeric AND bd."From2Second" > 0::numeric AND bd."To2Second" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From2Third" AS "StartTime",
                    bd."To2Third" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 4::numeric AND bd."Opened2" = 1::numeric AND bd."From2Third" > 0::numeric AND bd."To2Third" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From3" AS "StartTime",
                    bd."To3" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 5::numeric AND bd."Opened3" = 1::numeric AND bd."From3" > 0::numeric AND bd."To3" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From3Second" AS "StartTime",
                    bd."To3Second" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 5::numeric AND bd."Opened3" = 1::numeric AND bd."From3Second" > 0::numeric AND bd."To3Second" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From3Third" AS "StartTime",
                    bd."To3Third" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 5::numeric AND bd."Opened3" = 1::numeric AND bd."From3Third" > 0::numeric AND bd."To3Third" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From4" AS "StartTime",
                    bd."To4" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 6::numeric AND bd."Opened4" = 1::numeric AND bd."From4" > 0::numeric AND bd."To4" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From4Second" AS "StartTime",
                    bd."To4Second" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 6::numeric AND bd."Opened4" = 1::numeric AND bd."From4Second" > 0::numeric AND bd."To4Second" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From4Third" AS "StartTime",
                    bd."To4Third" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 6::numeric AND bd."Opened4" = 1::numeric AND bd."From4Third" > 0::numeric AND bd."To4Third" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From5" AS "StartTime",
                    bd."To5" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 7::numeric AND bd."Opened5" = 1::numeric AND bd."From5" > 0::numeric AND bd."To5" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From5Second" AS "StartTime",
                    bd."To5Second" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 7::numeric AND bd."Opened5" = 1::numeric AND bd."From5Second" > 0::numeric AND bd."To5Second" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From5Third" AS "StartTime",
                    bd."To5Third" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 7::numeric AND bd."Opened5" = 1::numeric AND bd."From5Third" > 0::numeric AND bd."To5Third" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From6" AS "StartTime",
                    bd."To6" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 1::numeric AND bd."Opened6" = 1::numeric AND bd."From6" > 0::numeric AND bd."To6" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From6Second" AS "StartTime",
                    bd."To6Second" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 1::numeric AND bd."Opened6" = 1::numeric AND bd."From6Second" > 0::numeric AND bd."To6Second" > 0::numeric
                UNION
                 SELECT ds.oneday AS "Date",
                    bd."Book",
                    bd."From6Third" AS "StartTime",
                    bd."To6Third" AS "EndTime",
                    bd."BookDetail"
                   FROM table_of_dates ds,
                    bookdet bd
                  WHERE 1 = 1 AND (bd."StartDate" <= ds.oneday OR bd."StartDate" IS NULL) AND (bd."EndDate" >= ds.oneday OR bd."EndDate" IS NULL) AND to_number(to_char(ds.oneday, 'D'::character varying)::text) = 1::numeric AND bd."Opened6" = 1::numeric AND bd."From6Third" > 0::numeric AND bd."To6Third" > 0::numeric
                )
         SELECT DISTINCT tbd."Date",
            c."Clinic",
            c."Description" AS "ClinicDesc",
            bc."Chair",
            ch."Name" AS "ChairDesc",
            tbd."StartTime",
            tbd."EndTime",
            'B'::character(1) AS "Type",
            tbd."Book" AS "Id"
           FROM tmpbookdet tbd,
            clinic c,
            chair ch,
            bookchr bc,
            book b
          WHERE 1 = 1 AND tbd."BookDetail" = bc."BookDetail" AND tbd."Book" = b."Book" AND b."Inactive" = 0::numeric AND bc."Chair" = ch."Chair" AND ch."Unavailable" = 0::numeric AND ch."Clinic" = c."Clinic" AND c."Inactive" = 0::numeric) tbd2
  WHERE 1 = 1
;
CREATE OR REPLACE VIEW ar_asof AS
 SELECT t."Type",
    t."Id",
    t."Treatment",
    t."Patient",
    t."Family",
    t."Producer",
    t."TreatmentDate",
    t."Date",
    t."ModifiedDate",
    t."Procedure",
    t."Code",
    t."Total",
    t."InsTotal",
    t."Payed",
    t."InsPayed",
    t."PtAdj",
    t."InsAdj",
    t."InsTransfer",
    t."PayPlanId",
    t."InDispute",
    t."AppUser",
    t."Custom1",
    t."Custom2",
    t."Discipline",
    t."EntryUser",
    t."Location",
    t."ClaimDoctor",
    t."Practice"
   FROM trx t,
    tx_audit ta
  WHERE (t."Type" = ANY (ARRAY[1::numeric, 2::numeric, 3::numeric, 4::numeric, 6::numeric, 7::numeric, 74::numeric])) AND t."Deleted" = 0::numeric AND t."OrthoStatus" <> 1::numeric AND trunc(t."ModifiedDate") < ta."AuditDate"
UNION
 SELECT h."Type",
    h."Id",
    h."Treatment",
    h."Patient",
    h."Family",
    h."Producer",
    h."TreatmentDate",
    h."Date",
    h."ModifiedDate",
    h."Procedure",
    h."Code",
    h."Total",
    h."InsTotal",
    h."Payed",
    h."InsPayed",
    h."PtAdj",
    h."InsAdj",
    h."InsTransfer",
    h."PayPlanId",
    h."InDispute",
    h."AppUser",
    h."Custom1",
    h."Custom2",
    h."Discipline",
    h."EntryUser",
    h."Location",
    h."ClaimDoctor",
    h."Practice"
   FROM trx t,
    history h,
    tx_audit ta
  WHERE (h."Type" = ANY (ARRAY[1::numeric, 2::numeric, 3::numeric, 4::numeric, 6::numeric, 7::numeric, 74::numeric])) AND h."OrigRecNo" = t."OrigRecNo" AND h."Deleted" = 0::numeric AND h."OrthoStatus" <> 1::numeric AND h."HistoryType" < 10::numeric AND (trunc(t."ModifiedDate") >= ta."AuditDate" OR t."DeletionDate" >= ta."AuditDate") AND h."History" = (( SELECT max(h2."History") AS max
           FROM history h2
          WHERE h2."OrigRecNo" = t."OrigRecNo" AND h2."Type" = t."Type" AND trunc(h2."ModifiedDate") < ta."AuditDate"))
;
CREATE OR REPLACE VIEW ar_asof_i AS
 SELECT t."Type",
    t."Id",
    t."Treatment",
    t."Patient",
    t."Family",
    t."Producer",
    t."TreatmentDate",
    t."Date",
    t."ModifiedDate",
    t."Procedure",
    t."Code",
    t."Total",
    t."InsTotal",
    t."Payed",
    t."InsPayed",
    t."PtAdj",
    t."InsAdj",
    t."InsTransfer",
    t."PayPlanId",
    t."InDispute",
    t."AppUser",
    t."Custom1",
    t."Custom2",
    t."Discipline",
    t."EntryUser",
    t."Location",
    t."ClaimDoctor",
    t."Practice"
   FROM trx t,
    tx_audit ta
  WHERE (t."Type" = ANY (ARRAY[1::numeric, 2::numeric, 3::numeric, 4::numeric, 6::numeric, 7::numeric])) AND t."Deleted" = 0::numeric AND t."OrthoStatus" <> 1::numeric AND trunc(t."ModifiedDate") < ta."AuditDate"
UNION
 SELECT h."Type",
    h."Id",
    h."Treatment",
    h."Patient",
    h."Family",
    h."Producer",
    h."TreatmentDate",
    h."Date",
    h."ModifiedDate",
    h."Procedure",
    h."Code",
    h."Total",
    h."InsTotal",
    h."Payed",
    h."InsPayed",
    h."PtAdj",
    h."InsAdj",
    h."InsTransfer",
    h."PayPlanId",
    h."InDispute",
    h."AppUser",
    h."Custom1",
    h."Custom2",
    h."Discipline",
    h."EntryUser",
    h."Location",
    h."ClaimDoctor",
    h."Practice"
   FROM trx t,
    history h,
    tx_audit ta
  WHERE (h."Type" = ANY (ARRAY[1::numeric, 2::numeric, 3::numeric, 4::numeric, 6::numeric, 7::numeric])) AND h."OrigRecNo" = t."OrigRecNo" AND h."Deleted" = 0::numeric AND h."OrthoStatus" <> 1::numeric AND h."HistoryType" < 10::numeric AND (trunc(t."ModifiedDate") >= ta."AuditDate" OR t."DeletionDate" >= ta."AuditDate") AND h."History" = (( SELECT max(h2."History") AS max
           FROM history h2
          WHERE h2."OrigRecNo" = t."OrigRecNo" AND h2."Type" = t."Type" AND trunc(h2."ModifiedDate") < ta."AuditDate"))
;
CREATE OR REPLACE VIEW ar_rec_his_match_dateview AS
 SELECT "History",
    "ModifiedDate",
    "TreatmentDate",
    nvl(( SELECT max(h3."History") AS max
           FROM history h3
          WHERE h3."History" < h1."History" AND h3."HistoryType" < 10::numeric AND h3."Deleted" <> 2::numeric AND h3."OrigRecNo" = h1."OrigRecNo" AND h3."Type" = h1."Type"), "History") AS h2
   FROM history h1
  WHERE "Deleted" <> 2::numeric AND "HistoryType" < 10::numeric
;
CREATE OR REPLACE VIEW ar_rec_his_match_julview AS
 SELECT "History",
    to_number(to_char(trunc("ModifiedDate"), 'J'::character varying)::text) AS "ModifiedJulian",
    to_number(to_char(trunc("TreatmentDate"), 'J'::character varying)::text) AS "TreatmentJulian",
    nvl(( SELECT max(h3."History") AS max
           FROM history h3
          WHERE h3."History" < history."History" AND h3."HistoryType" < 10::numeric AND h3."Deleted" <> 2::numeric AND h3."OrigRecNo" = history."OrigRecNo" AND h3."Type" = history."Type"), "History") AS h2
   FROM history
  WHERE "Deleted" <> 2::numeric AND "HistoryType" < 10::numeric
;
CREATE OR REPLACE VIEW attach_view AS
 SELECT 0 AS attachtype,
    0 AS id,
    0 AS patient,
    ' '::character(30) AS description,
    to_date(NULL::character varying) AS attachdate,
    0 AS attab,
    ' '::character(6) AS consent,
    to_date(NULL::character varying) AS expirydate,
    0 AS attachuser,
    0 AS deleted,
    ' '::character varying(254) AS path,
    ' '::character(3) AS fileext,
    0 AS denied,
    0 AS status,
    0 AS appuser,
    to_date(NULL::character varying) AS appdate,
    0 AS contentsize,
    0 AS sigstatus,
    0 AS delaudit,
    to_date(NULL::character varying) AS adddatetime
   FROM dual
  WHERE 0 = 1
UNION ALL
 SELECT
        DECODE(  p."Type"
            , 3::numeric
            , 2
            , 0
        ) AS attachtype,
    p."PtLetter" AS id,
    p."Patient" AS patient,
    p."Description"::character(30) AS description,
    p."Date" AS attachdate,
    p."AtTab" AS attab,
    p."Consent" AS consent,
    p."ExpiryDate" AS expirydate,
    p."User" AS attachuser,
    p."Deleted" AS deleted,
    p."Path" AS path,
    p."FileExt"::character(3) AS fileext,
    0 AS denied,
    p."Status" AS status,
    p."AppUser" AS appuser,
    p."AppDate" AS appdate,
    sys.dbms_lob.getlength(p.content) AS contentsize,
    2 AS sigstatus,
    0 AS delaudit,
    p."AddDateTime" AS adddatetime
   FROM ptletter p
  WHERE p."OwnerType" = 0::numeric
UNION ALL
 SELECT
        DECODE(  p."Type"
            , 3::numeric
            , 2
            , 0
        ) AS attachtype,
    p."PtLetter" AS id,
    p."Patient" AS patient,
    ((p."Description"::text ||
        DECODE(  i."PrintStatus"
            , 2::numeric
            , (' (Reprint)'::text ||
            DECODE(  length(ltrim(i."InvHold"::text))
                , NULL::text::integer
                , ''::text::character varying
                , ' (On Hold)'::text::character varying
            )::text)::character varying
            ,
            DECODE(  length(ltrim(i."InvHold"::text))
                , NULL::text::integer
                , ''::text::character varying
                , ' (On Hold)'::text::character varying
            )
        )::text))::character(30) AS description,
    p."Date" AS attachdate,
    p."AtTab" AS attab,
    p."Consent" AS consent,
    p."ExpiryDate" AS expirydate,
    p."User" AS attachuser,
    p."Deleted" AS deleted,
    p."Path" AS path,
    p."FileExt"::character(3) AS fileext,
    0 AS denied,
    p."Status" AS status,
    p."AppUser" AS appuser,
    p."AppDate" AS appdate,
    sys.dbms_lob.getlength(p.content) AS contentsize,
    2 AS sigstatus,
    0 AS delaudit,
    p."AddDateTime" AS adddatetime
   FROM ptletter p,
    pinvoice i
  WHERE 1 = nvl(( SELECT 1
           FROM practice
          WHERE practice."Country" = 2::numeric AND (rownum) = 1), 0) AND (p."OwnerType" = ANY (ARRAY[1::numeric, 2::numeric])) AND i."PInvoice" = p."OwnerId" AND NOT (p."PtLetter" IN ( SELECT min(ptletter."PtLetter") AS min
           FROM ptletter
          GROUP BY ptletter."OwnerId"))
UNION ALL
 SELECT
        DECODE(  p."Type"
            , 3::numeric
            , 2
            , 0
        ) AS attachtype,
    p."PtLetter" AS id,
    p."Patient" AS patient,
    ((p."Description"::text ||
        DECODE(  length(ltrim(i."InvHold"::text))
            , NULL::text::integer
            , ''::text::character varying
            , ' (On Hold)'::text::character varying
        )::text))::character(30) AS description,
    p."Date" AS attachdate,
    p."AtTab" AS attab,
    p."Consent" AS consent,
    p."ExpiryDate" AS expirydate,
    p."User" AS attachuser,
    p."Deleted" AS deleted,
    p."Path" AS path,
    p."FileExt"::character(3) AS fileext,
    0 AS denied,
    p."Status" AS status,
    p."AppUser" AS appuser,
    p."AppDate" AS appdate,
    sys.dbms_lob.getlength(p.content) AS contentsize,
    2 AS sigstatus,
    0 AS delaudit,
    p."AddDateTime" AS adddatetime
   FROM ptletter p,
    pinvoice i
  WHERE 1 = nvl(( SELECT 1
           FROM practice
          WHERE practice."Country" = 2::numeric AND (rownum) = 1), 0) AND (p."OwnerType" = ANY (ARRAY[1::numeric, 2::numeric])) AND i."PInvoice" = p."OwnerId" AND (p."PtLetter" IN ( SELECT min(ptletter."PtLetter") AS min
           FROM ptletter
          GROUP BY ptletter."OwnerId"))
UNION ALL
 SELECT 1 AS attachtype,
    c."Contract" AS id,
    c."Patient" AS patient,
        DECODE(  c."Type"
            , 0::numeric
            , 'Tx Estimate'::text::character varying
            , 1::numeric
            , 'Payment Plan'::text::character varying
            , 2::numeric
            , 'Tx Plan'::text::character varying
            , 3::numeric
            , t."Description"
            , NULL::character varying
        )::character(30) AS description,
    c."Date" AS attachdate,
    c."AtTab" AS attab,
    c."Consent" AS consent,
    c."ExpiryDate" AS expirydate,
    a."User" AS attachuser,
    c."Deleted" AS deleted,
    'PDF'::character varying(254) AS path,
    c."FileExt"::character(3) AS fileext,
    c."Denied" AS denied,
    3 AS status,
    0 AS appuser,
    to_date(NULL::character varying) AS appdate,
    sys.dbms_lob.getlength(c.content) AS contentsize,
    c."SigStatus" AS sigstatus,
    c."DelAudit" AS delaudit,
    c."AddDateTime" AS adddatetime
   FROM contract c
     LEFT JOIN audithis a ON a."Audit" = c."Audit"
     LEFT JOIN consent t ON t."Consent" = c."Consent"
;
CREATE OR REPLACE VIEW bookdays_view AS
 SELECT DISTINCT t.oneday AS "Date",
    b."Book"
   FROM table_of_dates t,
    book b,
    bookdet bt
  WHERE b."Book" = bt."Book" AND b."Inactive" = 0::numeric AND (t.oneday >= bt."StartDate" OR bt."StartDate" IS NULL) AND (t.oneday <= bt."EndDate" OR bt."EndDate" IS NULL) AND (to_char(t.oneday, 'D'::character varying)::text = 1::text AND bt."Opened6" = 1::numeric OR to_char(t.oneday, 'D'::character varying)::text = 2::text AND bt."Opened0" = 1::numeric OR to_char(t.oneday, 'D'::character varying)::text = 3::text AND bt."Opened1" = 1::numeric OR to_char(t.oneday, 'D'::character varying)::text = 4::text AND bt."Opened2" = 1::numeric OR to_char(t.oneday, 'D'::character varying)::text = 5::text AND bt."Opened3" = 1::numeric OR to_char(t.oneday, 'D'::character varying)::text = 6::text AND bt."Opened4" = 1::numeric OR to_char(t.oneday, 'D'::character varying)::text = 7::text AND bt."Opened5" = 1::numeric) AND (( SELECT count(1) AS count
           FROM holiday
          WHERE holiday."PartialDay" = 0::numeric AND holiday."StartDate" <= t.oneday AND t.oneday <= holiday."EndDate" AND holiday."Clinic" = 0::numeric)) = 0
;
CREATE OR REPLACE VIEW chairdays_view AS
 SELECT t.oneday AS "Date",
    c."Chair"
   FROM table_of_dates t,
    chair c,
    location l
  WHERE c."Location" = l."Location" AND l."Inactive" = 0::numeric AND (to_char(t.oneday, 'D'::character varying)::text = 1::text AND l."Sunday" = 1::numeric OR to_char(t.oneday, 'D'::character varying)::text = 2::text AND l."Monday" = 1::numeric OR to_char(t.oneday, 'D'::character varying)::text = 3::text AND l."Tuesday" = 1::numeric OR to_char(t.oneday, 'D'::character varying)::text = 4::text AND l."Wednesday" = 1::numeric OR to_char(t.oneday, 'D'::character varying)::text = 5::text AND l."Thursday" = 1::numeric OR to_char(t.oneday, 'D'::character varying)::text = 6::text AND l."Friday" = 1::numeric OR to_char(t.oneday, 'D'::character varying)::text = 7::text AND l."Saturday" = 1::numeric) AND (( SELECT count(1) AS count
           FROM holiday
          WHERE holiday."PartialDay" = 0::numeric AND holiday."StartDate" <= t.oneday AND t.oneday <= holiday."EndDate" AND (holiday."Clinic" = c."Clinic" OR holiday."Clinic" = 0::numeric))) = 0
;
CREATE OR REPLACE VIEW chart_export AS
 SELECT 'Patient Information'::character varying AS "Section"
   FROM dual
UNION ALL
 SELECT 'Patient Care Summary'::character varying AS "Section"
   FROM dual
UNION ALL
 SELECT 'Patient Alerts, Allergies & Problems'::character varying AS "Section"
   FROM dual
UNION ALL
 SELECT 'Patient Consents'::character varying AS "Section"
   FROM dual
UNION ALL
 SELECT 'Patient Attachments'::character varying AS "Section"
   FROM dual
UNION ALL
 SELECT 'Patient Contact Notes'::character varying AS "Section"
   FROM dual
UNION ALL
 SELECT 'Patient EHR Forms'::character varying AS "Section"
   FROM dual
UNION ALL
 SELECT 'Patient Treatment History'::character varying AS "Section"
   FROM dual
UNION ALL
 SELECT 'Patient X-Rays'::character varying AS "Section"
   FROM dual
UNION ALL
 SELECT 'Patient Appointments'::character varying AS "Section"
   FROM dual
UNION ALL
 SELECT 'Patient Transactions'::character varying AS "Section"
   FROM dual
UNION ALL
 SELECT 'Patient Transactions Notes'::character varying AS "Section"
   FROM dual
UNION ALL
 SELECT 'Patient Balances'::character varying AS "Section"
   FROM dual
UNION ALL
 SELECT 'Patient Prescriptions'::character varying AS "Section"
   FROM dual
UNION ALL
 SELECT 'Patient Medications'::character varying AS "Section"
   FROM dual
UNION ALL
 SELECT 'Patient Perio Exams'::character varying AS "Section"
   FROM dual
UNION ALL
 SELECT 'Patient Access Audit'::character varying AS "Section"
   FROM dual
;
CREATE OR REPLACE VIEW clinicdays_view AS
 SELECT DISTINCT t.oneday AS "Date",
    c."Clinic"
   FROM table_of_dates t,
    clinic c,
    clinict ct
  WHERE c."Clinic" = ct."Clinic" AND c."Inactive" = 0::numeric AND (t.oneday >= ct."StartDate" OR ct."StartDate" IS NULL) AND (t.oneday <= ct."EndDate" OR ct."EndDate" IS NULL) AND (to_char(t.oneday, 'D'::character varying)::text = 1::text AND ct."Sunday" = 1::numeric OR to_char(t.oneday, 'D'::character varying)::text = 2::text AND ct."Monday" = 1::numeric OR to_char(t.oneday, 'D'::character varying)::text = 3::text AND ct."Tuesday" = 1::numeric OR to_char(t.oneday, 'D'::character varying)::text = 4::text AND ct."Wednesday" = 1::numeric OR to_char(t.oneday, 'D'::character varying)::text = 5::text AND ct."Thursday" = 1::numeric OR to_char(t.oneday, 'D'::character varying)::text = 6::text AND ct."Friday" = 1::numeric OR to_char(t.oneday, 'D'::character varying)::text = 7::text AND ct."Saturday" = 1::numeric) AND (( SELECT count(1) AS count
           FROM holiday
          WHERE holiday."PartialDay" = 0::numeric AND holiday."StartDate" <= t.oneday AND t.oneday <= holiday."EndDate" AND (holiday."Clinic" = c."Clinic" OR holiday."Clinic" = 0::numeric))) = 0
;
CREATE OR REPLACE VIEW cq_pull_document_filtered_patients_view AS
 SELECT "Patient",
    "Family",
    "Last",
    "First",
    "Prefered",
    "Middle",
    "Title",
    "Birth",
    "Address1",
    "Address2",
    "City",
    "Province",
    "Postal",
    "HomeArea",
    "HomePhone",
    "WorkArea",
    "WorkPhone",
    "WorkExt",
    "OtherArea",
    "OtherPhone",
    "OtherExt",
    "OtherLoc",
    "ContactAt",
    "ContactTime",
    "Status",
    "Sex",
    "Marital",
    "IsPatient",
    "IsStudent",
    "IsHandicaped",
    "Doctor",
    "Hygienist",
    "Aux",
    "Chart",
    "Sin",
    "Office1",
    "Office2",
    "Office3",
    "Office4",
    "Office5",
    "Alert1",
    "Alert2",
    "Alert3",
    "Alert4",
    "Alert5",
    "Permenant",
    "Primary",
    "Flags",
    "Open",
    "Close",
    "FirstTreatment",
    "LastClaimDate",
    "LastClaimAmount",
    "Extra",
    "Path",
    "LastVisit",
    "Deleted",
    "School",
    "Health",
    "InsPt",
    "OpenBalance",
    "AccountStatus",
    "Assignment",
    "Statements",
    "Interest",
    "ChartIn",
    "Location",
    "UserOut",
    "DateOut",
    "TimeOut",
    "IsFreeAccess",
    "Fee",
    "OtherLocation",
    "NoLocks",
    "CustomCode1",
    "CustomCode2",
    "CustomCode3",
    "CustomCode4",
    "CustomCode5",
    "CustomCode6",
    "CustomCode7",
    "CustomCode8",
    "CustomCode9",
    "CustomCode10",
    "Physician",
    "EmergLast",
    "EmergFirst",
    "EmergMiddle",
    "EmergAddress",
    "EmergCity",
    "EmergProvince",
    "EmergPostal",
    "EmergArea",
    "EmergPhone",
    "EmergRelation",
    "IsChartFixed",
    "EmergAltArea",
    "EmergAltPhone",
    "IsOrtho",
    "OrthoSet",
    "IsIn",
    "EmergAddress2",
    "AltChart",
    "LastUpper",
    "PrefUpper",
    "AddressOther",
    "BankAccount",
    "RespNumber",
    "EmergAddressOther",
    "LastStatementDate",
    "LastStatementAmount",
    "EDIFlag",
    "StatusEndDate",
    "PatType",
    "IsEmergency",
    "ActiveDate",
    "PartnerName",
    "BoxNumber",
    "Email",
    "ChartSort",
    "PartnerPrefix",
    "PrefApptTime",
    "User",
    "StationId",
    "XRayReceived",
    "DateXRayExpected",
    "DateXRayReceived",
    "StatusStartDate",
    "Country",
    "XRayExposures",
    "LastPmtDate",
    "LastPaymentAmount",
    "Audit",
    "MergedChart",
    "ChartSuffix",
    "ReleaseOnFile",
    "EmergExt",
    "EmergAltExt",
    "HomeExt",
    "FeeOverride",
    "DiscGrp",
    "EmancedMinor",
    "RequireTxConsent",
    "PaperChart",
    "InfoNotify",
    "TaxExempt",
    "RecallDoctorToUse",
    "RecallHygToUse",
    "CustomText1",
    "CustomText2",
    "CustomText3",
    "CustomText4",
    "CustomText5",
    "MobileArea",
    "MobilePhone",
    "ApptFeesExempt",
    "PrefLanguage",
    "RaceEthDeclined",
    "Ethnic",
    "IsTrustedAudit",
    "SecondIDType",
    "SecondIDNumber",
    "Is2ndIdTrustedAudit",
    "HasExternalLink",
    "HasCarequality"
   FROM patient
  WHERE 1 = 0
;
CREATE OR REPLACE VIEW cust_qry_view AS
 WITH tmprpthis AS (
         SELECT rh."Cust_Qry_AutoDec",
            min(rh."Audit") AS "MinAudit",
            max(rh."Audit") AS "MaxAudit",
            count(*) AS "RunCount"
           FROM rpthis rh
          WHERE 1 = 1
          GROUP BY rh."Cust_Qry_AutoDec"
        ), tmpaudithis AS (
         SELECT trh."Cust_Qry_AutoDec",
            minah."Date" + minah."Time" / 1440::numeric AS "CreatedDateTime",
            (rtrim(uv."Last"::text) || ', '::text) || rtrim(uv."First"::text) AS "CreatedByUserName",
            maxah."Date" + maxah."Time" / 1440::numeric AS "LastRunDateTime",
            trh."RunCount"
           FROM tmprpthis trh,
            audithis minah,
            audithis maxah,
            user_view uv
          WHERE 1 = 1 AND trh."MinAudit" = minah."Audit" AND trh."MaxAudit" = maxah."Audit" AND minah."User" = uv."User"
        )
 SELECT r."CUST_QRY_AutoDec",
    r."CUST_QRY_Type",
    r."CUST_QRY_Description",
    r.cust_qry_data,
    r."CUST_QRY_Comment",
    r."CreateUser",
    r."CreateDate",
    tah."CreatedDateTime",
    tah."CreatedByUserName",
    tah."LastRunDateTime",
    tah."RunCount"
   FROM cust_qry r
     LEFT JOIN tmpaudithis tah ON r."CUST_QRY_AutoDec" = tah."Cust_Qry_AutoDec"
  WHERE 1 = 1
;
CREATE OR REPLACE VIEW cust_rpt_view AS
 WITH tmprpthis AS (
         SELECT rh."CustRpt",
            min(rh."Audit") AS "MinAudit",
            max(rh."Audit") AS "MaxAudit",
            count(*) AS "RunCount"
           FROM rpthis rh
          WHERE 1 = 1
          GROUP BY rh."CustRpt"
        ), tmpaudithis AS (
         SELECT trh."CustRpt",
            minah."Date" + numtodsinterval(minah."Time", 'MINUTE'::text) AS "CreatedDateTime",
            minah."User" AS "CreatedByUser",
            (rtrim(uv."Last"::text) || ', '::text) || rtrim(uv."First"::text) AS "CreatedByUserName",
            maxah."Date" + numtodsinterval(maxah."Time", 'MINUTE'::text) AS "LastRunDateTime",
            trh."RunCount"
           FROM tmprpthis trh,
            audithis minah,
            audithis maxah,
            user_view uv
          WHERE 1 = 1 AND trh."MinAudit" = minah."Audit" AND trh."MaxAudit" = maxah."Audit" AND minah."User" = uv."User"
        )
 SELECT r."CustRpt",
    r."Description",
    r."Type",
    r."CustRCat",
    r."Order",
    r."Inactive",
    r."IsCrystal",
    r."PassUser",
    TRIM(BOTH FROM rpad(r."Note"::text, 100))::character varying(100) AS notetext,
    c."Description" AS "Category",
    c."Order" AS "CustRCatOrder",
    r."PtAttachType",
    s."ReportName",
    tah."CreatedDateTime",
    tah."CreatedByUser",
    tah."CreatedByUserName",
    tah."LastRunDateTime",
    tah."RunCount"
   FROM custrpt r
     LEFT JOIN custrcat c ON r."CustRCat" = c."CustRCat"
     LEFT JOIN sreport s ON r."SReport" = s."SReport"
     LEFT JOIN tmpaudithis tah ON r."CustRpt" = tah."CustRpt"
  WHERE 1 = 1
;
CREATE OR REPLACE VIEW depttx_view AS
 SELECT d."Batch",
    d."Department",
    d."HistoryLast",
    d."InDeptLast",
    d."HistoryPrior",
    d."InDeptPrior",
    0 AS "SameDept",
        CASE
            WHEN h."Producer" <> h2."Producer" THEN 1
            ELSE 0
        END AS changeproducer,
        CASE
            WHEN p."PGroup" <> p2."PGroup" THEN 1
            ELSE 0
        END AS changepgroup,
        CASE
            WHEN p."TypeCode" <> p2."TypeCode" THEN 1
            ELSE 0
        END AS changetypecode,
        CASE
            WHEN p."Year" <> p2."Year" THEN 1
            ELSE 0
        END AS changeyear,
        CASE
            WHEN h."AppUser" <> h2."AppUser" THEN 1
            ELSE 0
        END AS changeappuser,
        CASE
            WHEN h."Custom1" <> h2."Custom1" THEN 1
            ELSE 0
        END AS changecustom1,
        CASE
            WHEN h."Custom2" <> h2."Custom2" THEN 1
            ELSE 0
        END AS changecustom2,
        CASE
            WHEN h."Discipline" <> h2."Discipline" THEN 1
            ELSE 0
        END AS changediscipline,
        CASE
            WHEN h."EntryUser" <> h2."EntryUser" THEN 1
            ELSE 0
        END AS changeentryuser,
        CASE
            WHEN h."Location" <> h2."Location" THEN 1
            ELSE 0
        END AS changelocation,
        CASE
            WHEN h."ClaimDoctor" <> h2."ClaimDoctor" THEN 1
            ELSE 0
        END AS changeclaimdoctor,
        CASE
            WHEN h."Practice" <> h2."Practice" THEN 1
            ELSE 0
        END AS changepractice,
        CASE
            WHEN h."Type" = 1::numeric AND h."Procedure" <> h2."Procedure" THEN 1
            ELSE
            CASE
                WHEN h."Type" = 2::numeric AND h."Code" <> h2."Code" THEN 1
                ELSE 0
            END
        END AS changeprocedure
   FROM depttx d
     LEFT JOIN history h ON d."HistoryLast" = h."History"
     LEFT JOIN history h2 ON d."HistoryPrior" = h2."History"
     LEFT JOIN producer p ON h."Producer" = p."Producer"
     LEFT JOIN producer p2 ON h2."Producer" = p2."Producer"
UNION
 SELECT d."Batch",
    d."Department",
    d."HistoryLast",
    d."InDeptLast",
    d."HistoryPrior",
    d."InDeptPrior",
    1 AS "SameDept",
        CASE
            WHEN h."Producer" <> h2."Producer" THEN 1
            ELSE 0
        END AS changeproducer,
        CASE
            WHEN p."PGroup" <> p2."PGroup" THEN 1
            ELSE 0
        END AS changepgroup,
        CASE
            WHEN p."TypeCode" <> p2."TypeCode" THEN 1
            ELSE 0
        END AS changetypecode,
        CASE
            WHEN p."Year" <> p2."Year" THEN 1
            ELSE 0
        END AS changeyear,
        CASE
            WHEN h."AppUser" <> h2."AppUser" THEN 1
            ELSE 0
        END AS changeappuser,
        CASE
            WHEN h."Custom1" <> h2."Custom1" THEN 1
            ELSE 0
        END AS changecustom1,
        CASE
            WHEN h."Custom2" <> h2."Custom2" THEN 1
            ELSE 0
        END AS changecustom2,
        CASE
            WHEN h."Discipline" <> h2."Discipline" THEN 1
            ELSE 0
        END AS changediscipline,
        CASE
            WHEN h."EntryUser" <> h2."EntryUser" THEN 1
            ELSE 0
        END AS changeentryuser,
        CASE
            WHEN h."Location" <> h2."Location" THEN 1
            ELSE 0
        END AS changelocation,
        CASE
            WHEN h."ClaimDoctor" <> h2."ClaimDoctor" THEN 1
            ELSE 0
        END AS changeclaimdoctor,
        CASE
            WHEN h."Practice" <> h2."Practice" THEN 1
            ELSE 0
        END AS changepractice,
        CASE
            WHEN h."Type" = 1::numeric AND h."Procedure" <> h2."Procedure" THEN 1
            ELSE
            CASE
                WHEN h."Type" = 2::numeric AND h."Code" <> h2."Code" THEN 1
                ELSE 0
            END
        END AS changeprocedure
   FROM depttx d
     LEFT JOIN history h ON d."HistoryLast" = h."History"
     LEFT JOIN history h2 ON d."HistoryPrior" = h2."History"
     LEFT JOIN producer p ON h."Producer" = p."Producer"
     LEFT JOIN producer p2 ON h2."Producer" = p2."Producer"
  WHERE d."InDeptLast" = 1::numeric AND d."InDeptPrior" = 1::numeric
;
CREATE OR REPLACE VIEW dispreq_view AS
 SELECT 0 AS dispreq,
    0 AS orderid,
    ' '::character(10) AS producer,
    ' '::character(30) AS lastname,
    ' '::character(30) AS firstname,
    ' '::character(30) AS middlename,
    to_date(NULL::character varying) AS dateout,
    0 AS timeout,
    0 AS itemtype,
    ' '::character(6) AS kittype,
    ' '::character(6) AS sundry,
    ' '::character(30) AS kdescription,
    ' '::character(30) AS sdescription,
    ' '::character(30) AS barcode,
    ' '::character(6) AS dispcode,
    0 AS appointment,
    0 AS prockit,
    0 AS apptrx,
    ' '::character(6) AS location,
    to_date(NULL::character varying) AS entrydate,
    0 AS entrytime
   FROM dual
  WHERE 0 = 1
UNION
 SELECT d."DispReq" AS dispreq,
    d."Order" AS orderid,
    p."Producer" AS producer,
    p."LastName" AS lastname,
    p."FirstName" AS firstname,
    p."MiddleName" AS middlename,
    d."DateOut" AS dateout,
    d."TimeOut" AS timeout,
    d."Type" AS itemtype,
    kt."KitType" AS kittype,
    s."Sundry" AS sundry,
    kt."Description" AS kdescription,
    s."Description" AS sdescription,
    s."BarCode" AS barcode,
    d."DispCode" AS dispcode,
    0 AS appointment,
    0 AS prockit,
    0 AS apptrx,
    ' '::character(6) AS location,
    d."Date" AS entrydate,
    d."Time" AS entrytime
   FROM dispreq d
     CROSS JOIN producer p
     LEFT JOIN kittype kt ON d."KitType" = kt."KitType"
     LEFT JOIN sundry s ON d."Sundry" = s."Sundry"
  WHERE d."Provider" = p."Producer"
UNION
 SELECT 0 AS dispreq,
    0 AS orderid,
    p."Producer" AS producer,
    p."LastName" AS lastname,
    p."FirstName" AS firstname,
    p."MiddleName" AS middlename,
    a."Date" AS dateout,
    a."From" AS timeout,
    0 AS itemtype,
    kt."KitType" AS kittype,
    ' '::character(6) AS sundry,
    kt."Description" AS kdescription,
    ' '::character(30) AS sdescription,
    ' '::character(30) AS barcode,
    l."DispCode" AS dispcode,
    a."Appointment" AS appointment,
    0 AS prockit,
    0 AS apptrx,
    l."Location" AS location,
    to_date(NULL::character varying) AS entrydate,
    0 AS entrytime
   FROM appoint a,
    apptrx t,
    producer p,
    prockit pk,
    kittype kt,
    chair c,
    location l
  WHERE a."Producer" = p."Producer" AND a."Appointment" = t."Appointment" AND t."Procedure" >= pk."ProcFrom" AND t."Procedure" <= pk."ProcTo" AND pk."KitType" = kt."KitType" AND a."Chair" = c."Chair" AND c."Location" = l."Location" AND a."Type" < 3::numeric AND (pk."ProvType" = p."TypeCode" OR pk."ProvType" IS NULL OR (pk."ProvType" = ANY (ARRAY[''::bpchar, ' '::bpchar]))) AND NOT (EXISTS ( SELECT 1
           FROM disphis d,
            kit k2
          WHERE 1 = 1 AND d."Appointment" = a."Appointment" AND k2."Kit" = d."Kit" AND k2."KitType" = kt."KitType"))
UNION
 SELECT 0 AS dispreq,
    0 AS orderid,
    p."Producer" AS producer,
    p."LastName" AS lastname,
    p."FirstName" AS firstname,
    p."MiddleName" AS middlename,
    a."Date" AS dateout,
    a."From" AS timeout,
    1 AS itemtype,
    ' '::character(6) AS kittype,
    s."Sundry" AS sundry,
    ' '::character(30) AS kdescription,
    s."Description" AS sdescription,
    s."BarCode" AS barcode,
    l."DispCode" AS dispcode,
    a."Appointment" AS appointment,
        DECODE(  pk."SundryFrq"
            , 1::numeric
            , pk."ProcKit"
            , 0::numeric
        ) AS prockit,
        DECODE(  pk."SundryFrq"
            , 1::numeric
            , t."AppTrx"
            , 0::numeric
        ) AS apptrx,
    l."Location" AS location,
    to_date(NULL::character varying) AS entrydate,
    0 AS entrytime
   FROM appoint a,
    apptrx t,
    producer p,
    prockit pk,
    sundry s,
    chair c,
    location l
  WHERE a."Producer" = p."Producer" AND a."Appointment" = t."Appointment" AND t."Procedure" >= pk."ProcFrom" AND t."Procedure" <= pk."ProcTo" AND pk."Sundry" = s."Sundry" AND a."Chair" = c."Chair" AND c."Location" = l."Location" AND a."Type" < 3::numeric AND (pk."ProvType" = p."TypeCode" OR pk."ProvType" IS NULL OR (pk."ProvType" = ANY (ARRAY[''::bpchar, ' '::bpchar]))) AND (( SELECT count(1) AS count
           FROM disphis d
          WHERE d."Appointment" = a."Appointment" AND d."Sundry" = s."Sundry")) < (1 + (( SELECT count(1) AS count
           FROM prockit pk2
          WHERE pk2."Sundry" = s."Sundry" AND (pk2."ProcKit" IN ( SELECT pk4."ProcKit"
                   FROM prockit pk4,
                    apptrx t4
                  WHERE t4."Appointment" = a."Appointment" AND t4."Procedure" >= pk4."ProcFrom" AND t4."Procedure" <= pk4."ProcTo" AND pk4."Sundry" = s."Sundry" AND pk4."SundryFrq" = 0::numeric)) AND pk2."ProcKit" < pk."ProcKit" AND (pk2."ProvType" = p."TypeCode" OR pk2."ProvType" IS NULL OR (pk2."ProvType" = ANY (ARRAY[''::bpchar, ' '::bpchar]))) AND pk2."SundryFrq" = 0::numeric)) + (( SELECT count(1) AS count
           FROM prockit pk3,
            apptrx t3
          WHERE pk3."Sundry" = s."Sundry" AND (pk3."ProcKit" IN ( SELECT pk4."ProcKit"
                   FROM prockit pk4,
                    apptrx t4
                  WHERE t4."Appointment" = a."Appointment" AND t4."Procedure" >= pk4."ProcFrom" AND t4."Procedure" <= pk4."ProcTo" AND pk4."Sundry" = s."Sundry" AND pk4."SundryFrq" = 1::numeric)) AND pk3."ProcKit" < pk."ProcKit" AND (pk3."ProvType" = p."TypeCode" OR pk3."ProvType" IS NULL OR (pk3."ProvType" = ANY (ARRAY[''::bpchar, ' '::bpchar]))) AND pk3."SundryFrq" = 1::numeric AND t3."Appointment" = a."Appointment" AND t3."Procedure" >= pk3."ProcFrom" AND t3."Procedure" <= pk3."ProcTo")) + (( SELECT
                DECODE(  pk."SundryFrq"
                    , 1::numeric
                    , count(1)
                    , 0::bigint
                ) AS decode
           FROM apptrx t2
          WHERE t2."Appointment" = a."Appointment" AND t2."AppTrx" < t."AppTrx" AND t2."Procedure" >= pk."ProcFrom" AND t2."Procedure" <= pk."ProcTo")))
;
CREATE OR REPLACE VIEW duplicate_patient_view AS
 SELECT "Patient",
    "Chart",
    "Last",
    "First",
    "Prefered" AS "Preferred",
    "Birth",
    "Address1",
    "Address2",
    "City",
    "Province" AS "State",
    "Postal" AS "Zip",
    "HomeArea",
    "HomePhone",
    "Status",
    "Sin" AS "ID",
        DECODE(  "Patient"
            , "Family"
            , 'Patient'::text::character varying
            , 'Guarantor'::text::character varying
        ) AS "PatientOrGuarantor"
   FROM patient p
  WHERE 1 = 1 AND "Deleted" = 0::numeric AND (EXISTS ( SELECT 1
           FROM patient p2
          WHERE 1 = 1 AND p."Patient" <> p2."Patient" AND p."Birth" = p2."Birth" AND p2."Deleted" = 0::numeric AND p."LastUpper" = p2."LastUpper" AND p."PrefUpper" = p2."PrefUpper"))
  ORDER BY "Last", "First", "Birth"
;
CREATE OR REPLACE VIEW entrytimestages_view AS
 SELECT DISTINCT ptsdose."EntryTime",
    ptsdrug."Appointment",
    ( SELECT max(ptstage."PtStage") AS max
           FROM ptstage
          WHERE ptstage."Appointment" = ptsdrug."Appointment" AND ptstage."StageStart" <= ptsdose."EntryTime") AS "PtStage"
   FROM ptsdose,
    ptsdrug
  WHERE ptsdose."PtSDrug" = ptsdrug."PtSDrug"
UNION
 SELECT DISTINCT ptvital."EntryTime",
    ptvital."Appointment",
    ( SELECT max(ptstage."PtStage") AS max
           FROM ptstage
          WHERE ptstage."Appointment" = ptvital."Appointment" AND ptstage."StageStart" <= ptvital."EntryTime") AS "PtStage"
   FROM ptvital
;
CREATE OR REPLACE VIEW form_spreadsheet_column_view AS
 SELECT p."Patient",
    p."FormCode",
    p."FItem",
    p."AnsType",
    p."AnsYes",
    p."AnsText",
    p."AnsList",
    p."AnsListDesc",
    p."Date",
    p."User",
    p."Status",
    p."AuditNumber",
    p."AppUser",
    p."AppDate",
    p."AnsDate",
    p."ASAType",
    p."ASAScore",
    p."PItem",
    p."Time",
    p."PForm",
    p."PItemImg",
    p."AnsListRefCode",
    p."EntryDateTime",
    p."AppDateTime",
    p."PItemCol"
   FROM pitem p,
    fitem f
  WHERE p."FItem" = f."FItem" AND p."PItemCol" > 0::numeric AND f."Type" = 5::numeric
;
CREATE OR REPLACE VIEW get_patient_attachments_view AS
 SELECT 'PtLetter'::character varying AS "TableType",
    p."Patient",
    p."AtTab",
    s."Order" AS "SectOrder",
    s."Description" AS "SectDesc",
    t."Order" AS "TabOrder",
    t."Description" AS "TabDesc",
    p."PtLetter",
    p."Description",
    p.content,
    0 AS "FileSize",
    p."Date",
    p."User",
    p."Path",
    p."Type",
    p."Deleted",
    p."StationId",
    p."FileExt",
    p."DelAudit",
    users."Name",
    users."First",
    users."Middle",
    p."Consent",
    p."ExpiryDate",
    0 AS "Denied",
    0 AS "SigStatus",
    p."Status",
    p."AppUser",
    p."AppDate",
    p."OrigId"
   FROM ptletter p,
    attab t,
    atsect s,
    users
  WHERE 1 = 2
UNION ALL
 SELECT 'PtLetter'::character varying AS "TableType",
    p."Patient",
    p."AtTab",
    s."Order" AS "SectOrder",
    s."Description" AS "SectDesc",
    t."Order" AS "TabOrder",
    t."Description" AS "TabDesc",
    p."PtLetter",
    p."Description",
    p.content,
    sys.dbms_lob.getlength(p.content) AS "FileSize",
    p."Date",
    p."User",
    p."Path",
    p."Type",
    p."Deleted",
    p."StationId",
    p."FileExt",
    p."DelAudit",
    users."Name",
    users."First",
    users."Middle",
    p."Consent",
    p."ExpiryDate",
    0 AS "Denied",
    0 AS "SigStatus",
    p."Status",
    p."AppUser",
    p."AppDate",
    p."OrigId"
   FROM ptletter p,
    attab t,
    atsect s,
    users
  WHERE p."AtTab" = t."AtTab" AND t."AtSect" = s."AtSect" AND users."User" = p."User" AND p."Deleted" = 0::numeric
UNION ALL
 SELECT 'Consent'::character varying AS "TableType",
    p."Patient",
    p."AtTab",
    s."Order" AS "SectOrder",
    s."Description" AS "SectDesc",
    t."Order" AS "TabOrder",
    t."Description" AS "TabDesc",
    p."Contract" AS "PtLetter",
    p."Description",
    p.content,
    sys.dbms_lob.getlength(p.content) AS "FileSize",
    p."Date",
    a."User",
    ''::character varying AS "Path",
    p."Type",
    p."Deleted",
    a."StationId",
    p."FileExt",
    p."DelAudit",
    users."Name",
    users."First",
    users."Middle",
    p."Consent",
    p."ExpiryDate",
    p."Denied",
    p."SigStatus",
    0 AS "Status",
    0 AS "AppUser",
    to_date(NULL::character varying) AS "AppDate",
    0 AS "OrigId"
   FROM contract p
     CROSS JOIN attab t
     CROSS JOIN atsect s
     LEFT JOIN consent c ON p."Consent" = c."Consent"
     LEFT JOIN audithis a ON p."Audit" = a."Audit"
     LEFT JOIN users ON users."User" = a."User"
  WHERE p."AtTab" = t."AtTab" AND t."AtSect" = s."AtSect" AND p."Deleted" = 0::numeric
;
CREATE OR REPLACE VIEW global_temp_alloc_v AS
 SELECT "AllocatH",
    "PayType",
    "TrxType",
    "TrxId",
    "TrxTreatment",
    "Amount",
    "AllocateLink",
    "TxHistoryId",
    "PmtHistoryId",
    "OrigRecNo",
    "History",
    "HistoryType",
    "Patient",
    "TxModifiedDate",
    "Payed",
    "InsPayed",
    "PtAdj",
    "InsAdj",
    "InsTransfer",
    "Discipline",
    "Procedure",
    "Practice",
    "ClaimDoctor",
    "Location",
    "EntryUser",
    "AppUser",
    "Custom1",
    "Custom2",
    "Producer",
    "TypeCode",
    "PGroup",
    "Year",
    "CustomCode1",
    "CustomCode2",
    "CustomCode3",
    "CustomCode4",
    "CustomCode5",
    "CustomCode6",
    "CustomCode7",
    "CustomCode8",
    "CustomCode9",
    "CustomCode10",
    "Department",
    "HistoryTypeDescription",
    "GroupBy1",
    "GroupBy2",
    "PreviousHistory",
    "PreviousDiscipline",
    "PreviousProcedure",
    "PreviousPractice",
    "PreviousPracticeName",
    "PreviousClaimDoctor",
    "PreviousLocation",
    "PreviousEntryUser",
    "PreviousEntryUserLogon",
    "PreviousEntryUserFirstName",
    "PreviousEntryUserLastName",
    "PreviousAppUser",
    "PreviousAppUserLogon",
    "PreviousAppUserFirstName",
    "PreviousAppUserLastName",
    "PreviousCustom1",
    "PreviousCustom2",
    "PreviousProducer",
    "PreviousProducerFirstName",
    "PreviousProducerMiddleName",
    "PreviousProducerLastName",
    "PreviousTypeCode",
    "PreviousTypeCodeDescription",
    "PreviousPGroup",
    "PreviousYear",
    "PreviousCustomCode1",
    "PreviousCustomCode2",
    "PreviousCustomCode3",
    "PreviousCustomCode4",
    "PreviousCustomCode5",
    "PreviousCustomCode6",
    "PreviousCustomCode7",
    "PreviousCustomCode8",
    "PreviousCustomCode9",
    "PreviousCustomCode10",
    "PreviousDepartment",
    "PreviousPayed",
    "PreviousInsPayed",
    "PreviousPtAdj",
    "PreviousInsAdj",
    "GroupBy1Value",
    "GroupBy2Value",
    "PreviousGroupBy1Value",
    "PreviousGroupBy2Value",
    "TxPracticeName",
    "TxTypeCodeDescription",
    "TxPGroupDescription",
    "TxProducerFirstName",
    "TxProducerMiddleName",
    "TxProducerLastName",
    "TxEntryUserLogon",
    "TxEntryUserFirstName",
    "TxEntryUserLastName",
    "TxAppUserLogon",
    "TxAppUserFirstName",
    "TxAppUserLastName",
    "TxPatientChart",
    "TxPatientFirstName",
    "TxPatientMiddleName",
    "TxPatientLastName",
    "TxPatientPreferredName",
    "TxDeptDescription",
    "TxHistoryType",
    "TxType",
    "TxId",
    "TxTreatment",
    "TxOrigRecNo",
    "TxFamily",
    "TxStatus",
    "TxDate",
    "TxTreatmentDate",
    "TxCode",
    "TxCodeDescription",
    "TxSite",
    "TxSurface",
    "TxTotal",
    "TxInsTotal",
    "TxCompany1",
    "TxCompany1Name",
    "TxPolicy1",
    "TxAmount1",
    "TxDescription",
    "TxUser",
    "TxAppDate",
    "TxStationId",
    "TxCustom3",
    "TxCustom4",
    "TxCustomaryTotal",
    "PmtHistoryType",
    "PmtType",
    "PmtId",
    "PmtTreatment",
    "PmtOrigRecNo",
    "PmtPatient",
    "PmtFamily",
    "PmtDate",
    "PmtCode",
    "PmtCodeDescription",
    "PmtTotal",
    "PmtInsTotal",
    "PmtCompany1",
    "PmtCompany1Name",
    "PmtAmount1",
    "PmtDescription",
    "PmtBank",
    "PmtPayed",
    "PmtInsPayed",
    "PmtPtAdj",
    "PmtInsAdj",
    "PmtModifiedDate",
    "PmtPatientFirstName",
    "PmtPatientMiddleName",
    "PmtPatientLastName",
    "PmtPatientPreferredName"
   FROM ( WITH tmpgta4 AS (
                 SELECT DISTINCT gta4."AllocatH",
                    gta4."PayType",
                    gta4."TrxType",
                    gta4."TrxId",
                    gta4."TrxTreatment",
                    gta4."Amount",
                    gta4."AllocateLink",
                    gta4."TxHistoryId",
                    gta4."PmtHistoryId",
                    gta4."OrigRecNo",
                    gta4."History",
                    gta4."HistoryType",
                    gta4."Patient",
                    gta4."TxModifiedDate",
                    gta4."Payed",
                    gta4."InsPayed",
                    gta4."PtAdj",
                    gta4."InsAdj",
                    gta4."InsTransfer",
                    gta4."Discipline",
                    gta4."Procedure",
                    gta4."Practice",
                    gta4."ClaimDoctor",
                    gta4."Location",
                    gta4."EntryUser",
                    gta4."AppUser",
                    gta4."Custom1",
                    gta4."Custom2",
                    gta4."Producer",
                    gta4."TypeCode",
                    gta4."PGroup",
                    gta4."Year",
                    gta4."CustomCode1",
                    gta4."CustomCode2",
                    gta4."CustomCode3",
                    gta4."CustomCode4",
                    gta4."CustomCode5",
                    gta4."CustomCode6",
                    gta4."CustomCode7",
                    gta4."CustomCode8",
                    gta4."CustomCode9",
                    gta4."CustomCode10",
                    gta4."Department",
                    gta4."HistoryTypeDescription",
                    gta4."GroupBy1",
                    gta4."GroupBy2",
                    gta4."PreviousHistory",
                    gta4."PreviousDiscipline",
                    gta4."PreviousProcedure",
                    gta4."PreviousPractice",
                    gta4."PreviousClaimDoctor",
                    gta4."PreviousLocation",
                    gta4."PreviousEntryUser",
                    gta4."PreviousAppUser",
                    gta4."PreviousCustom1",
                    gta4."PreviousCustom2",
                    gta4."PreviousProducer",
                    gta4."PreviousTypeCode",
                    gta4."PreviousPGroup",
                    gta4."PreviousYear",
                    gta4."PreviousCustomCode1",
                    gta4."PreviousCustomCode2",
                    gta4."PreviousCustomCode3",
                    gta4."PreviousCustomCode4",
                    gta4."PreviousCustomCode5",
                    gta4."PreviousCustomCode6",
                    gta4."PreviousCustomCode7",
                    gta4."PreviousCustomCode8",
                    gta4."PreviousCustomCode9",
                    gta4."PreviousCustomCode10",
                    gta4."PreviousDepartment",
                    gta4."GroupBy1Value",
                    gta4."GroupBy2Value",
                    gta4."PreviousGroupBy1Value",
                    gta4."PreviousGroupBy2Value"
                   FROM global_temp_alloc4 gta4
                  WHERE 1 = 1
                ), tmppmthistory AS (
                 SELECT hpmt."History",
                    hpmt."HistoryType" AS "PmtHistoryType",
                    hpmt."Type" AS "PmtType",
                    hpmt."Id" AS "PmtId",
                    hpmt."Treatment" AS "PmtTreatment",
                    hpmt."OrigRecNo" AS "PmtOrigRecNo",
                    hpmt."Patient" AS "PmtPatient",
                    hpmt."Family" AS "PmtFamily",
                    hpmt."Date" AS "PmtDate",
                    hpmt."Code" AS "PmtCode",
                    nvl(
                        DECODE(  hpmt."Type"
                            , 2::numeric
                            , ocpmt."Description"::character varying
                            , 3::numeric
                            , pmtpmt."Description"::character varying
                            , 4::numeric
                            , pmtpmt."Description"::character varying
                            , 73::numeric
                            , pmtpmt."Description"::character varying
                            , 74::numeric
                            , pmtpmt."Description"::character varying
                            , 6::numeric
                            , adjpmt."Description"::character varying
                            , 7::numeric
                            , adjpmt."Description"::character varying
                            , ' '::text::character varying
                        ), ' ') AS "PmtCodeDescription",
                    hpmt."Total" AS "PmtTotal",
                    hpmt."InsTotal" AS "PmtInsTotal",
                    hpmt."Company1" AS "PmtCompany1",
                    nvl(ipmt."Name", ' ') AS "PmtCompany1Name",
                    hpmt."Amount1" AS "PmtAmount1",
                    hpmt."Description" AS "PmtDescription",
                    hpmt."Bank" AS "PmtBank",
                    hpmt."Payed" AS "PmtPayed",
                    hpmt."InsPayed" AS "PmtInsPayed",
                    hpmt."PtAdj" AS "PmtPtAdj",
                    hpmt."InsAdj" AS "PmtInsAdj",
                    hpmt."ModifiedDate" AS "PmtModifiedDate",
                    nvl(ppmt."First", ' ') AS "PmtPatientFirstName",
                    nvl(ppmt."Middle", ' ') AS "PmtPatientMiddleName",
                    nvl(ppmt."Last", ' ') AS "PmtPatientLastName",
                    nvl(ppmt."Prefered", ' ') AS "PmtPatientPreferredName"
                   FROM history hpmt
                     LEFT JOIN patient ppmt ON hpmt."Patient" = ppmt."Patient"
                     LEFT JOIN adjust adjpmt ON hpmt."Code" = adjpmt."Adjust"
                     LEFT JOIN payment pmtpmt ON hpmt."Code" = pmtpmt."Payment"
                     LEFT JOIN ofcharge ocpmt ON hpmt."Code" = ocpmt."OfficeCharge"
                     LEFT JOIN insuranc ipmt ON hpmt."Company1" = ipmt."Company"
                  WHERE 1 = 1
                ), tmpprevioushistory AS (
                 SELECT hprev."History",
                    hprev."Payed" AS "PreviousPayed",
                    hprev."InsPayed" AS "PreviousInsPayed",
                    hprev."PtAdj" AS "PreviousPtAdj",
                    hprev."InsAdj" AS "PreviousInsAdj"
                   FROM history hprev
                  WHERE 1 = 1
                )
         SELECT tgta4a."AllocatH",
            tgta4a."PayType",
            tgta4a."TrxType",
            tgta4a."TrxId",
            tgta4a."TrxTreatment",
            tgta4a."Amount",
            tgta4a."AllocateLink",
            tgta4a."TxHistoryId",
            tgta4a."PmtHistoryId",
            tgta4a."OrigRecNo",
            tgta4a."History",
            tgta4a."HistoryType",
            tgta4a."Patient",
            tgta4a."TxModifiedDate",
            tgta4a."Payed",
            tgta4a."InsPayed",
            tgta4a."PtAdj",
            tgta4a."InsAdj",
            tgta4a."InsTransfer",
            tgta4a."Discipline",
            tgta4a."Procedure",
            tgta4a."Practice",
            tgta4a."ClaimDoctor",
            tgta4a."Location",
            tgta4a."EntryUser",
            tgta4a."AppUser",
            tgta4a."Custom1",
            tgta4a."Custom2",
            tgta4a."Producer",
            tgta4a."TypeCode",
            tgta4a."PGroup",
            tgta4a."Year",
            tgta4a."CustomCode1",
            tgta4a."CustomCode2",
            tgta4a."CustomCode3",
            tgta4a."CustomCode4",
            tgta4a."CustomCode5",
            tgta4a."CustomCode6",
            tgta4a."CustomCode7",
            tgta4a."CustomCode8",
            tgta4a."CustomCode9",
            tgta4a."CustomCode10",
            tgta4a."Department",
            tgta4a."HistoryTypeDescription",
            tgta4a."GroupBy1",
            tgta4a."GroupBy2",
            tgta4a."PreviousHistory",
            tgta4a."PreviousDiscipline",
            tgta4a."PreviousProcedure",
            tgta4a."PreviousPractice",
            nvl(prprev."Name", ' ') AS "PreviousPracticeName",
            tgta4a."PreviousClaimDoctor",
            tgta4a."PreviousLocation",
            tgta4a."PreviousEntryUser",
            nvl(euprev."Logon", ' ') AS "PreviousEntryUserLogon",
            nvl(euprev."First", ' ') AS "PreviousEntryUserFirstName",
            nvl(euprev."Name", ' ') AS "PreviousEntryUserLastName",
            tgta4a."PreviousAppUser",
            nvl(auprev."Logon", ' ') AS "PreviousAppUserLogon",
            nvl(auprev."First", ' ') AS "PreviousAppUserFirstName",
            nvl(auprev."Name", ' ') AS "PreviousAppUserLastName",
            tgta4a."PreviousCustom1",
            tgta4a."PreviousCustom2",
            tgta4a."PreviousProducer",
            nvl(prodprev."FirstName", ' ') AS "PreviousProducerFirstName",
            nvl(prodprev."MiddleName", ' ') AS "PreviousProducerMiddleName",
            nvl(prodprev."LastName", ' ') AS "PreviousProducerLastName",
            tgta4a."PreviousTypeCode",
            nvl(ptprev."Description", ' ') AS "PreviousTypeCodeDescription",
            tgta4a."PreviousPGroup",
            tgta4a."PreviousYear",
            tgta4a."PreviousCustomCode1",
            tgta4a."PreviousCustomCode2",
            tgta4a."PreviousCustomCode3",
            tgta4a."PreviousCustomCode4",
            tgta4a."PreviousCustomCode5",
            tgta4a."PreviousCustomCode6",
            tgta4a."PreviousCustomCode7",
            tgta4a."PreviousCustomCode8",
            tgta4a."PreviousCustomCode9",
            tgta4a."PreviousCustomCode10",
            tgta4a."PreviousDepartment",
            nvl(thprev."PreviousPayed", 0) AS "PreviousPayed",
            nvl(thprev."PreviousInsPayed", 0) AS "PreviousInsPayed",
            nvl(thprev."PreviousPtAdj", 0) AS "PreviousPtAdj",
            nvl(thprev."PreviousInsAdj", 0) AS "PreviousInsAdj",
            tgta4a."GroupBy1Value",
            tgta4a."GroupBy2Value",
            tgta4a."PreviousGroupBy1Value",
            tgta4a."PreviousGroupBy2Value",
            nvl(prtx."Name", ' ') AS "TxPracticeName",
            nvl(pttx."Description", ' ') AS "TxTypeCodeDescription",
            nvl(pgtx."Description", ' ') AS "TxPGroupDescription",
            nvl(prodtx."FirstName", ' ') AS "TxProducerFirstName",
            nvl(prodtx."MiddleName", ' ') AS "TxProducerMiddleName",
            nvl(prodtx."LastName", ' ') AS "TxProducerLastName",
            nvl(eutx."Logon", ' ') AS "TxEntryUserLogon",
            nvl(eutx."First", ' ') AS "TxEntryUserFirstName",
            nvl(eutx."Name", ' ') AS "TxEntryUserLastName",
            nvl(autx."Logon", ' ') AS "TxAppUserLogon",
            nvl(autx."First", ' ') AS "TxAppUserFirstName",
            nvl(autx."Name", ' ') AS "TxAppUserLastName",
            nvl(ptx."Chart", ' ') AS "TxPatientChart",
            nvl(ptx."First", ' ') AS "TxPatientFirstName",
            nvl(ptx."Middle", ' ') AS "TxPatientMiddleName",
            nvl(ptx."Last", ' ') AS "TxPatientLastName",
            nvl(ptx."Prefered", ' ') AS "TxPatientPreferredName",
            nvl(dtx."Description", ' ') AS "TxDeptDescription",
            htx."HistoryType" AS "TxHistoryType",
            htx."Type" AS "TxType",
            htx."Id" AS "TxId",
            htx."Treatment" AS "TxTreatment",
            htx."OrigRecNo" AS "TxOrigRecNo",
            htx."Family" AS "TxFamily",
            htx."Status" AS "TxStatus",
            htx."Date" AS "TxDate",
            htx."TreatmentDate" AS "TxTreatmentDate",
            htx."Code" AS "TxCode",
            nvl(
                DECODE(  htx."Type"
                    , 2::numeric
                    , octx."Description"::character varying
                    , 3::numeric
                    , pmttx."Description"::character varying
                    , 4::numeric
                    , pmttx."Description"::character varying
                    , 73::numeric
                    , pmttx."Description"::character varying
                    , 74::numeric
                    , pmttx."Description"::character varying
                    , 6::numeric
                    , adjtx."Description"::character varying
                    , 7::numeric
                    , adjtx."Description"::character varying
                    , ' '::text::character varying
                ), ' ') AS "TxCodeDescription",
            htx."Site" AS "TxSite",
            htx."Surface" AS "TxSurface",
            htx."Total" AS "TxTotal",
            htx."InsTotal" AS "TxInsTotal",
            htx."Company1" AS "TxCompany1",
            nvl(itx."Name", ' ') AS "TxCompany1Name",
            htx."Policy1" AS "TxPolicy1",
            htx."Amount1" AS "TxAmount1",
            htx."Description" AS "TxDescription",
            htx."User" AS "TxUser",
            htx."AppDate" AS "TxAppDate",
            htx."StationId" AS "TxStationId",
            htx."Custom3" AS "TxCustom3",
            htx."Custom4" AS "TxCustom4",
            htx."CustomaryTotal" AS "TxCustomaryTotal",
            thpmt."PmtHistoryType",
            thpmt."PmtType",
            thpmt."PmtId",
            thpmt."PmtTreatment",
            thpmt."PmtOrigRecNo",
            thpmt."PmtPatient",
            thpmt."PmtFamily",
            thpmt."PmtDate",
            thpmt."PmtCode",
            thpmt."PmtCodeDescription",
            thpmt."PmtTotal",
            thpmt."PmtInsTotal",
            thpmt."PmtCompany1",
            thpmt."PmtCompany1Name",
            thpmt."PmtAmount1",
            thpmt."PmtDescription",
            thpmt."PmtBank",
            thpmt."PmtPayed",
            thpmt."PmtInsPayed",
            thpmt."PmtPtAdj",
            thpmt."PmtInsAdj",
            thpmt."PmtModifiedDate",
            thpmt."PmtPatientFirstName",
            thpmt."PmtPatientMiddleName",
            thpmt."PmtPatientLastName",
            thpmt."PmtPatientPreferredName"
           FROM tmpgta4 tgta4a
             CROSS JOIN history htx
             LEFT JOIN tmppmthistory thpmt ON tgta4a."PmtHistoryId" = thpmt."History"
             LEFT JOIN tmpprevioushistory thprev ON tgta4a."PreviousHistory" = thprev."History"
             LEFT JOIN practice prtx ON tgta4a."Practice" = prtx."Id"
             LEFT JOIN prodtype pttx ON tgta4a."TypeCode" = pttx."Code"
             LEFT JOIN pgroup pgtx ON tgta4a."PGroup" = pgtx."PGroup"
             LEFT JOIN producer prodtx ON tgta4a."Producer" = prodtx."Producer"
             LEFT JOIN users eutx ON tgta4a."EntryUser" = eutx."User"
             LEFT JOIN users autx ON tgta4a."AppUser" = autx."User"
             LEFT JOIN patient ptx ON tgta4a."Patient" = ptx."Patient"
             LEFT JOIN dept dtx ON tgta4a."Department" = dtx."Department"
             LEFT JOIN adjust adjtx ON htx."Code" = adjtx."Adjust"
             LEFT JOIN payment pmttx ON htx."Code" = pmttx."Payment"
             LEFT JOIN ofcharge octx ON htx."Code" = octx."OfficeCharge"
             LEFT JOIN insuranc itx ON htx."Company1" = itx."Company"
             LEFT JOIN practice prprev ON tgta4a."PreviousPractice" = prprev."Id"
             LEFT JOIN users euprev ON tgta4a."PreviousEntryUser" = euprev."User"
             LEFT JOIN users auprev ON tgta4a."PreviousAppUser" = auprev."User"
             LEFT JOIN producer prodprev ON tgta4a."PreviousProducer" = prodprev."Producer"
             LEFT JOIN prodtype ptprev ON tgta4a."PreviousTypeCode" = ptprev."Code"
          WHERE 1 = 1 AND tgta4a."History" = htx."History") gtav
  WHERE 1 = 1
;
CREATE OR REPLACE VIEW instvacaset_view AS
 SELECT 0 AS rtype,
    v."User",
    v."VacaSet",
    TRIM(BOTH FROM v."Description") AS description,
    v."StartDate" AS startdate,
    v."EndDate" AS enddate,
    v."StartTime",
    v."EndTime",
    v."Monday",
    v."Tuesday",
    v."Wednesday",
    v."Thursday",
    v."Friday",
    v."Saturday",
    v."Sunday",
    v."Cycle",
    v."CycleStart",
    v."CycleType",
    v."CycleFrq",
    v."IsBreak",
    v."AvailableClinic",
    ( SELECT count(1) AS count
           FROM vacation
          WHERE vacation."VacaSet" = v."VacaSet" AND vacation."Deleted" = 0::numeric AND vacation."SetException" = 1::numeric) AS hasexcept
   FROM vacaset v
  WHERE v."Type" = 1::numeric AND v."Deleted" = 0::numeric
UNION
 SELECT 1 AS rtype,
    v."User",
    v."Id" AS "VacaSet",
    TRIM(BOTH FROM v."Description") AS description,
    v."StartDate" AS startdate,
    v."StartDate" AS enddate,
    v."StartTime",
    v."EndTime",
    0 AS "Monday",
    0 AS "Tuesday",
    0 AS "Wednesday",
    0 AS "Thursday",
    0 AS "Friday",
    0 AS "Saturday",
    0 AS "Sunday",
    0 AS "Cycle",
    NULL::timestamp without time zone AS "CycleStart",
    0 AS "CycleType",
    0 AS "CycleFrq",
    0 AS "IsBreak",
    0 AS "AvailableClinic",
    0 AS hasexcept
   FROM vacation v
  WHERE v."Type" = 1::numeric AND v."VacaSet" = 0::numeric AND v."Deleted" = 0::numeric
;
CREATE OR REPLACE VIEW invfill_view AS
 SELECT o."InvOrder" AS invorder,
    o."Inactive" AS inactive,
    o."Date" AS podate,
    i."InvOrdIt" AS invordit,
    i."Item" AS item,
    i."Status" AS status,
    i."PickList" AS picklist,
    i."Product" AS productid,
    p."ProductCode" AS productcode,
    i."Description" AS description,
    p."UPCCode" AS upccode,
    i."Quantity" AS orderqty,
    i."Unit" AS unit,
    i."QtyFilled" AS qtyfilled,
    i."WasBackOrdered" AS wasbackordered,
    t."InvItem" AS invitem,
    d."BatchId" AS batchid,
    d."Quantity" AS filled,
    pl."Bin" AS productbin
   FROM invorder o
     JOIN invordit i ON i."InvOrder" = o."InvOrder"
     LEFT JOIN product p ON i."Product" = p."Product"
     LEFT JOIN invitem t ON i."InvOrdIt" = t."InvOrdIt"
     LEFT JOIN invitdet d ON t."InvItem" = d."InvItem"
     LEFT JOIN prdloc pl ON i."Product" = pl."Product" AND o."InvLocFrom" = pl."InvLoc"
;
CREATE OR REPLACE VIEW invorder_view AS
 SELECT o."InvOrder" AS invorder,
    o."Inactive" AS inactive,
    o."PONumber" AS ponumber,
    o."Date" AS podate,
    v."Name" AS vendorname,
    i."InvOrdIt" AS invordit,
    i."Item" AS item,
    i."Status" AS status,
    i."Product" AS productid,
    c."Description" AS category,
    p."ProductCode" AS productcode,
    p."Description" AS description,
    p."UPCCode" AS upccode,
    i."Quantity" AS orderqty,
    i."Unit" AS unit,
    i."QtyFilled" AS qtyfilled
   FROM invorder o
     CROSS JOIN invordit i
     CROSS JOIN product p
     CROSS JOIN prdcat c
     LEFT JOIN vendor v ON o."Vendor" = v."Vendor"
  WHERE o."InvOrder" = i."InvOrder" AND i."Product" = p."Product" AND p."PrdType" = c."PrdType" AND p."PrdCat" = c."PrdCat"
;
CREATE OR REPLACE VIEW invreceipt_view AS
 SELECT r."InvRec" AS invrec,
    r."InvLoc" AS invloc,
    r."Date" AS invrecdate,
    r."PONumber" AS ponumber,
    r."PODate" AS podate,
    v."Name" AS vendorname,
    m."InvItem" AS invitem,
    m."Audit" AS item,
    m."Product" AS productid,
    c."Description" AS category,
    p."ProductCode" AS productcode,
    p."Description" AS description,
    p."UPCCode" AS upccode,
    i."Quantity" AS quantity,
    m."Unit" AS unit,
    m."ExpiryDate" AS expirydate,
    i."QtyFilled" AS qtyfilled,
    m."Quantity" AS recd
   FROM invrec r
     CROSS JOIN vendor v
     CROSS JOIN invitem m
     CROSS JOIN product p
     CROSS JOIN prdcat c
     LEFT JOIN invordit i ON m."InvOrdIt" = i."InvOrdIt"
  WHERE r."Vendor" = v."Vendor" AND r."InvRec" = m."InvRec" AND m."Type" = 0::numeric AND m."Product" = p."Product" AND p."PrdType" = c."PrdType" AND p."PrdCat" = c."PrdCat"
;
CREATE OR REPLACE VIEW invtransfer_view AS
 SELECT m."InvItem" AS invitem,
    m."InvLoc" AS invloc,
    m."Product" AS productid,
    c."Description" AS category,
    p."ProductCode" AS productcode,
    p."Description" AS description,
    p."UPCCode" AS upccode,
    m."Unit" AS unit,
    m."Quantity" AS scanned,
    m."Audit" AS auditid
   FROM invitem m,
    product p,
    prdcat c
  WHERE m."Type" = 1::numeric AND m."Product" = p."Product" AND p."PrdType" = c."PrdType" AND p."PrdCat" = c."PrdCat"
;
CREATE OR REPLACE VIEW lastedielig_view AS
 SELECT e."EDIElig",
    e."Patient",
    e."PolIns",
    e."ContentType",
    e.content,
    e."FileExtension",
    e."Result",
    a."Date",
    a."Time",
    a."User",
    a."StationId"
   FROM edielig e,
    audithis a
  WHERE e."Audit" = a."Audit" AND NOT (EXISTS ( SELECT 1
           FROM edielig e2
          WHERE e."Patient" = e2."Patient" AND e."PolIns" = e2."PolIns" AND e."EDIElig" < e2."EDIElig"))
;
CREATE OR REPLACE VIEW lastptedielig_view AS
 SELECT e."EDIElig",
    e."Patient",
    e."PolIns",
    e."ContentType",
    e.content,
    e."FileExtension",
    e."Result",
    a."Date",
    a."Time",
    a."User",
    a."StationId"
   FROM edielig e,
    audithis a
  WHERE e."Audit" = a."Audit" AND NOT (EXISTS ( SELECT 1
           FROM edielig e2
          WHERE e."Patient" = e2."Patient" AND e."EDIElig" < e2."EDIElig"))
;
CREATE OR REPLACE VIEW locationdays_view AS
 SELECT t.oneday AS "Date",
    l."Location"
   FROM table_of_dates t,
    location l
  WHERE l."Inactive" = 0::numeric AND (to_char(t.oneday, 'D'::character varying)::text = 1::text AND l."Sunday" = 1::numeric OR to_char(t.oneday, 'D'::character varying)::text = 2::text AND l."Monday" = 1::numeric OR to_char(t.oneday, 'D'::character varying)::text = 3::text AND l."Tuesday" = 1::numeric OR to_char(t.oneday, 'D'::character varying)::text = 4::text AND l."Wednesday" = 1::numeric OR to_char(t.oneday, 'D'::character varying)::text = 5::text AND l."Thursday" = 1::numeric OR to_char(t.oneday, 'D'::character varying)::text = 6::text AND l."Friday" = 1::numeric OR to_char(t.oneday, 'D'::character varying)::text = 7::text AND l."Saturday" = 1::numeric) AND (( SELECT count(1) AS count
           FROM holiday
          WHERE holiday."PartialDay" = 0::numeric AND holiday."StartDate" <= t.oneday AND t.oneday <= holiday."EndDate" AND holiday."Clinic" = 0::numeric)) = 0
;
CREATE OR REPLACE VIEW maxaudithisperappoint_view AS
 SELECT maxauditperappoint."Appointment",
    ah."Audit",
    ah."Date",
    ah."Time",
    ah."User",
    ah."StationId",
    ah."TableName",
    ah."HistoryType"
   FROM audithis ah,
    ( SELECT max(unnamed_subquery.auditid) AS auditid,
            unnamed_subquery."Appointment"
           FROM ( SELECT max(ptsurg."Audit") AS auditid,
                    ptsurg."Appointment"
                   FROM ptsurg
                  GROUP BY ptsurg."Appointment"
                UNION ALL
                 SELECT max(ptvital."Audit") AS auditid,
                    ptvital."Appointment"
                   FROM ptvital
                  GROUP BY ptvital."Appointment"
                UNION ALL
                 SELECT max(ptsdrug."Audit") AS auditid,
                    ptsdrug."Appointment"
                   FROM ptsdrug
                  GROUP BY ptsdrug."Appointment"
                UNION ALL
                 SELECT max(ptsdose."Audit") AS auditid,
                    ptsdrug."Appointment"
                   FROM ptsdose,
                    ptsdrug
                  WHERE ptsdose."PtSDrug" = ptsdrug."PtSDrug"
                  GROUP BY ptsdrug."Appointment") unnamed_subquery
          GROUP BY unnamed_subquery."Appointment") maxauditperappoint
  WHERE ah."Audit" = maxauditperappoint.auditid
;
CREATE OR REPLACE VIEW mcappoint_view AS
 SELECT DISTINCT patient."Chart",
    patient."Patient",
    appoint."Type",
    patient."Last",
    patient."Prefered",
    patient."Middle",
    appoint."Producer",
    appoint."Date",
    appoint."Status",
    appoint."Clinic"
   FROM appoint appoint,
    patient patient
  WHERE appoint."Patient" = patient."Patient" AND (appoint."Type" = ANY (ARRAY[0::numeric, 1::numeric, 2::numeric])) AND appoint."Status" = 0::numeric AND 0 = (( SELECT count(1) AS count
           FROM trx t2
          WHERE appoint."Patient" = t2."Patient" AND appoint."Date" = t2."TreatmentDate" AND (t2."Type" = ANY (ARRAY[1::numeric, 5::numeric])) AND t2."Deleted" <> 1::numeric)) AND 0 = (( SELECT count(1) AS count
           FROM treatme2 t2,
            patient2 p2
          WHERE appoint."Patient" = p2."PtxPId" AND p2."Auto" = t2."PId" AND (t2."Status" = 5::numeric AND t2."Deleted" = 0::numeric OR (t2."Status" = ANY (ARRAY[0::numeric, 1::numeric, 2::numeric])) AND t2."Deleted" = 2::numeric AND mcappoint_t2neverdeleted(t2."PId", t2."Auto") = 1::numeric) AND (to_date('01-JAN-1901'::character varying, 'DD-MON-YYYY'::character varying) + t2."Days") = appoint."Date"))
;
CREATE OR REPLACE VIEW msg_allusers_view AS
 SELECT 0::numeric(10,0) AS "User",
    0::numeric(10,0) AS "Patient",
    0 AS "IsFreeAccess",
    to_char(0::numeric)::character varying(30) AS "Name",
    to_char(0::numeric)::character varying(30) AS "First",
    to_char(0::numeric)::character varying(15) AS "Middle",
    to_char(0::numeric)::character varying(10) AS "Provider",
    to_char(0::numeric)::character varying(30) AS "Description",
    to_char(0::numeric)::character varying(12) AS "Logon",
    to_char(0::numeric)::character varying(6) AS "PGroup",
    0 AS "Year",
    0 AS "IsGroupManager",
    0 AS "Level"
   FROM dual
  WHERE 0 = 1
UNION ALL
 SELECT u."User",
    0::numeric(10,0) AS "Patient",
    0 AS "IsFreeAccess",
    TRIM(BOTH FROM u."Name") AS "Name",
    TRIM(BOTH FROM u."First") AS "First",
    TRIM(BOTH FROM u."Middle") AS "Middle",
    TRIM(BOTH FROM u."Producer") AS "Provider",
    TRIM(BOTH FROM s."Description") AS "Description",
    TRIM(BOTH FROM u."Logon") AS "Logon",
    TRIM(BOTH FROM p."PGroup") AS "PGroup",
    p."Year",
    u."IsGroupManager",
    u."Level"
   FROM slevel s
     CROSS JOIN users u
     LEFT JOIN producer p ON u."Producer" = p."Producer"
  WHERE u."Level" = s."SLevel"
UNION ALL
 SELECT i."iUser" AS "User",
    p."Patient",
    p."IsFreeAccess",
    TRIM(BOTH FROM p."Last") AS "Name",
    TRIM(BOTH FROM p."First") AS "First",
    TRIM(BOTH FROM p."Middle") AS "Middle",
    ''::character varying AS "Provider",
    ''::character varying AS "Description",
    ''::character varying AS "Logon",
    ''::character varying AS "PGroup",
    0 AS "Year",
    0 AS "IsGroupManager",
    0 AS "Level"
   FROM iuser i,
    patient p
  WHERE i."Type" = 0::numeric AND i."Id" = p."Patient" AND p."Patient" = p."Family"
;
CREATE OR REPLACE VIEW msg_user_view AS
 SELECT 0::numeric(10,0) AS "User",
    0::numeric(10,0) AS "Patient",
    0 AS "IsFreeAccess",
    to_char(0::numeric)::character varying(30) AS "Name",
    to_char(0::numeric)::character varying(30) AS "First",
    to_char(0::numeric)::character varying(15) AS "Middle",
    to_char(0::numeric)::character varying(10) AS "Provider",
    to_char(0::numeric)::character varying(30) AS "Description",
    to_char(0::numeric)::character varying(12) AS "Logon",
    to_char(0::numeric)::character varying(6) AS "PGroup",
    0 AS "Year",
    0 AS "IsGroupManager",
    0 AS "Level"
   FROM dual
  WHERE 0 = 1
UNION ALL
 SELECT u."User",
    0::numeric(10,0) AS "Patient",
    0 AS "IsFreeAccess",
    TRIM(BOTH FROM u."Name") AS "Name",
    TRIM(BOTH FROM u."First") AS "First",
    TRIM(BOTH FROM u."Middle") AS "Middle",
    TRIM(BOTH FROM u."Producer") AS "Provider",
    TRIM(BOTH FROM s."Description") AS "Description",
    TRIM(BOTH FROM u."Logon") AS "Logon",
    TRIM(BOTH FROM p."PGroup") AS "PGroup",
    p."Year",
    u."IsGroupManager",
    u."Level"
   FROM slevel s
     CROSS JOIN users u
     LEFT JOIN producer p ON u."Producer" = p."Producer"
  WHERE u."Deleted" = 0::numeric AND (u."ExpDate" > trunc(sysdate) OR u."ExpDate" IS NULL) AND u."Level" = s."SLevel"
UNION ALL
 SELECT i."iUser" AS "User",
    p."Patient",
    p."IsFreeAccess",
    TRIM(BOTH FROM p."Last") AS "Name",
    TRIM(BOTH FROM p."First") AS "First",
    TRIM(BOTH FROM p."Middle") AS "Middle",
    ''::character varying AS "Provider",
    ''::character varying AS "Description",
    ''::character varying AS "Logon",
    ''::character varying AS "PGroup",
    0 AS "Year",
    0 AS "IsGroupManager",
    0 AS "Level"
   FROM iuser i,
    patient p
  WHERE i."Deleted" = 0::numeric AND i."Type" = 0::numeric AND i."Id" = p."Patient" AND p."Patient" = p."Family" AND p."Deleted" = 0::numeric
;
CREATE OR REPLACE VIEW next1000days AS
 SELECT trunc(sysdate + (rownum)::numeric - 1) AS "Date"
   FROM dual CONNECT BY (level) <= 1000
;
CREATE OR REPLACE VIEW pathis_view AS
 SELECT 0 AS patient,
    0 AS newid,
    0 AS oldid
   FROM dual
  WHERE 0 = 1
UNION
 SELECT p1."Patient" AS patient,
    p1."Id" AS newid,
    nvl(( SELECT max(p2."Id") AS max
           FROM pathis p2
          WHERE p2."Patient" = p1."Patient" AND p2."Id" < p1."Id"), 0) AS oldid
   FROM pathis p1
;
CREATE OR REPLACE VIEW patient_age_ht_wt_view AS
 SELECT DISTINCT 2.20462262 AS "WeightFactor",
    0.393700787 AS "HeightFactor",
    patient."Patient",
    patient."First",
    patient."Last",
    patient."Chart",
    patient."Sex",
    pitem."Date" AS "CreatedDate",
    months_between(pitem."Date", patient."Birth") / 12::numeric AS "Age",
    nvl(( SELECT max(to_number(nvl(pi."AnsText", '0')::text)) AS max
           FROM pitem pi,
            fitem fi
          WHERE fi."FItem" = pi."FItem" AND fi."Code"::text = 'PT_STD_WT'::text AND pi."Patient" = pform."Patient" AND pi."PForm" = pform."PForm" AND pi."Date" = pitem."Date"), 0) / 2.20462262 AS "Weight",
    nvl(( SELECT max(to_number(nvl(pi2."AnsText", '0')::text)) AS max
           FROM pitem pi2,
            fitem fi2
          WHERE fi2."FItem" = pi2."FItem" AND fi2."Code"::text = 'PT_STD_HT'::text AND pi2."Patient" = pform."Patient" AND pi2."PForm" = pform."PForm" AND pi2."Date" = pitem."Date"), 0) / 0.393700787 AS "Height",
    nvl(( SELECT to_number(nvl(pi2."AnsText", '0')::text) AS to_number
           FROM pitem pi2,
            fitem fi2
          WHERE fi2."FItem" = pi2."FItem" AND fi2."Code"::text = 'MOTHER_HT'::text AND pi2."Patient" = pform."Patient" AND pi2."PForm" = pform."PForm" AND pi2."Status" = 0::numeric), 0) AS "MothersHeight",
    nvl(( SELECT to_number(nvl(pi2."AnsText", '0')::text) AS to_number
           FROM pitem pi2,
            fitem fi2
          WHERE fi2."FItem" = pi2."FItem" AND fi2."Code"::text = 'FATHER_HT'::text AND pi2."Patient" = pform."Patient" AND pi2."PForm" = pform."PForm" AND pi2."Status" = 0::numeric), 0) AS "FathersHeight"
   FROM patient,
    pform,
    pitem,
    fitem
  WHERE 1 = 1 AND pform."Patient" = patient."Patient" AND pitem."PForm" = pform."PForm" AND fitem."Code"::text = 'PT_STD_WT'::text AND pitem."FItem" = fitem."FItem" AND pform."Approved" = 1::numeric AND pform."Inactive" = 0::numeric AND patient."Birth" IS NOT NULL
;
CREATE OR REPLACE VIEW patient_ehr_summary AS
 SELECT pt."Patient",
    '1PatProb'::character varying AS "Type",
    pt."Description"
   FROM ptprb pt
  WHERE pt."Deleted" = 0::numeric AND NOT (EXISTS ( SELECT 1
           FROM prosts ps
          WHERE pt."Status" = ps."Code" AND (ps."Resolved" = 1::numeric OR ps."Inactive" = 1::numeric)))
UNION
 SELECT pt."Patient",
    '2MedProb'::character varying AS "Type",
    pt."Description"
   FROM ptalert pt
  WHERE pt."Deleted" = 0::numeric AND pt."AlertType" = 2::numeric AND pt."Status" = 0::numeric AND pt."Deleted" = 0::numeric
UNION
 SELECT pt."Patient",
    '3PatAllergies'::character varying AS "Type",
    pt."Description"
   FROM ptalert pt
  WHERE pt."Deleted" = 0::numeric AND pt."AlertType" = 1::numeric AND pt."Status" = 0::numeric AND pt."Deleted" = 0::numeric
UNION
 SELECT prescrip."Patient",
    '4PatMeds'::character varying AS "Type",
    (((prescrip."DrugDescription"::text || ' '::text) || prescrip."Dose"::text) || ' '::text) || prescrip."DrugFrqDesc"::text AS "Description"
   FROM prescrip
  WHERE prescrip."PrescripType" = 0::numeric AND prescrip."Deleted" = 0::numeric AND (prescrip."StartDate" IS NULL OR trunc(prescrip."StartDate") <= trunc(sysdate)) AND (prescrip."EndDate" IS NULL OR trunc(prescrip."EndDate") >= trunc(sysdate))
;
CREATE OR REPLACE VIEW patient_family_view AS
 SELECT p1."Patient",
    p."Patient" AS "PtFamily"
   FROM patient p1,
    patient p
  WHERE (p."Patient" IN ( SELECT ptguar."RespPatient"
           FROM ptguar
          WHERE ptguar."Inactive" = 0::numeric AND ptguar."Deleted" = 0::numeric AND ptguar."Patient" = p1."Patient"
        UNION ALL
         SELECT ptguar."Patient"
           FROM ptguar
          WHERE ptguar."Inactive" = 0::numeric AND ptguar."Deleted" = 0::numeric AND ptguar."RespPatient" = p1."Patient"
        UNION ALL
         SELECT pg1."Patient"
           FROM ptguar pg1,
            ptguar pg2
          WHERE pg1."Inactive" = 0::numeric AND pg1."Deleted" = 0::numeric AND pg2."Inactive" = 0::numeric AND pg2."Deleted" = 0::numeric AND pg1."RespPatient" = pg2."RespPatient" AND pg2."Patient" = p1."Patient"))
;
CREATE OR REPLACE VIEW pe_appoint_view AS
 SELECT a."Appointment",
    a."Date",
    a."Chair",
    a."Patient",
    a."Type",
    a."Producer",
    a."From",
    a."CreateDate",
    a."Code",
    a."Unit0",
    a."Unit1",
    a."Unit2",
    a."Unit3",
    a."Unit4",
    a."Unit5",
    a."Time0",
    a."Time1",
    a."Time2",
    a."Time3",
    a."Time4",
    a."Time5",
    a."Estimate",
    a."Class",
    a."ModifiedDateTime",
    a."User",
    a."IsRecall",
    a."IsAsap",
    a."IsConfirm",
    a."IsShortNotice",
    a."Status",
    a."Request",
    a."Rank",
    a."UStatus",
    a."Reserve",
    a."OrthoStage",
    a."IsOrtho",
    a."Cancel",
    a."Reason",
    a."Assistant",
    a."Clinic",
    a."IsRequest",
    a."Instructor",
    a."IsNew",
    a."CheckInTime",
    a."TimeSeated",
    a."Held",
    a."SignInTime",
    a."SecondaryMCBFlag",
    a."NotBeforeDate",
    a."PtEstimateStatus",
    a."PtEstimate",
    a."BookingOrder",
    a."ExpertAdd",
    a."CheckOutDate",
    a."CheckOutTime",
    a."PrimaryExclusive",
    (TRIM(BOTH FROM p."FirstName") || ' '::text) || p."LastName"::text AS "Provider_Name",
    c."Name" AS "P_Provider_Description"
   FROM appoint a
     LEFT JOIN chair c ON a."Chair" = c."Chair"
     LEFT JOIN producer p ON a."Producer" = p."Producer"
  WHERE (a."Type" = ANY (ARRAY[0::numeric, 1::numeric, 2::numeric])) AND a."Date" >= pe_custom_pkg.get_golive_date() AND (a."Chair" IN ( SELECT bc."Chair"
           FROM bookchr bc
          WHERE (bc."BookDetail" IN ( SELECT bd."BookDetail"
                   FROM bookdet bd
                  WHERE (bd."Book"::text IN ( SELECT regexp_substr(replace(pe_custom_pkg.get_books_touse(), ' '::character varying)::text, '[^,]+'::text, 1::numeric, (rownum)::numeric) AS regexp_substr
                           FROM dual
                          WHERE 1 = 1 CONNECT BY (level) <= (length(regexpreplace_s(pe_custom_pkg.get_books_touse(), '[^,]+'::character varying, ''::character varying)::text) + 1)))))))
;
CREATE OR REPLACE VIEW pe_calendar_block_view AS
 SELECT 1 AS "RecType",
    tod.oneday AS "Date",
    c."Name" AS "P_Provider_Description",
    to_char(tod.oneday + make_interval(mins => h."StartTime"::integer), 'HH24:MI'::character varying) AS "StartTime",
    to_char(tod.oneday + make_interval(mins =>
        CASE
            WHEN h."EndTime" = 0::numeric THEN 1439::numeric
            ELSE h."EndTime"
        END::integer), 'HH24:MI'::character varying) AS "EndTime",
    h."DisplayDesc" AS "Reason"
   FROM chair c,
    holiday h,
    table_of_dates tod
  WHERE 1 = 1 AND (c."Chair" IN ( SELECT bc."Chair"
           FROM bookchr bc
          WHERE 1 = 1 AND (bc."BookDetail" IN ( SELECT bd."BookDetail"
                   FROM bookdet bd
                  WHERE 1 = 1 AND tod.oneday >= nvl(bd."StartDate", trunc(sysdate - 1)) AND tod.oneday <= nvl(bd."EndDate", tod.oneday) AND (bd."Book"::text IN ( SELECT regexp_substr(replace(pe_custom_pkg.get_books_touse(), ' '::character varying)::text, '[^,]+'::text, 1::numeric, (rownum)::numeric) AS regexp_substr
                           FROM dual
                          WHERE 1 = 1 CONNECT BY (level) <= (length(regexpreplace_s(pe_custom_pkg.get_books_touse(), '[^,]+'::character varying, ''::character varying)::text) + 1))))))) AND tod.oneday >= h."StartDate" AND tod.oneday <= h."EndDate" AND tod.oneday >= trunc(sysdate) AND (h."Clinic" = 0::numeric OR h."Clinic" = c."Clinic")
UNION ALL
 SELECT 2 AS "RecType",
    r."Date",
    c."Name" AS "P_Provider_Description",
    to_char(r."Date" + make_interval(mins => r."Start"::integer), 'HH24:MI'::character varying) AS "StartTime",
    to_char(r."Date" + make_interval(mins => r."End"::integer), 'HH24:MI'::character varying) AS "EndTime",
    r."DisplayDesc" AS "Reason"
   FROM reserve r,
    chair c
  WHERE 1 = 1 AND r."Chair" = c."Chair" AND (r."Unavailable" = 1::numeric OR r."Closed" = 1::numeric) AND r."Date" >= trunc(sysdate) AND (r."Chair" IN ( SELECT bc."Chair"
           FROM bookchr bc
          WHERE 1 = 1 AND (bc."BookDetail" IN ( SELECT bd."BookDetail"
                   FROM bookdet bd
                  WHERE 1 = 1 AND r."Date" >= nvl(bd."StartDate", trunc(sysdate - 1)) AND r."Date" <= nvl(bd."EndDate", r."Date") AND (bd."Book"::text IN ( SELECT regexp_substr(replace(pe_custom_pkg.get_books_touse(), ' '::character varying)::text, '[^,]+'::text, 1::numeric, (rownum)::numeric) AS regexp_substr
                           FROM dual
                          WHERE 1 = 1 CONNECT BY (level) <= (length(regexp_replace(replace(pe_custom_pkg.get_books_touse(), ' '::character varying)::text, '[^,]+'::text, ''::text)) + 1)))))))
;
CREATE OR REPLACE VIEW pe_patient_view AS
 SELECT "Patient",
    "Family",
    "Last",
    "First",
    "Prefered",
    "Middle",
    "Title",
    "Birth",
    "Address1",
    "Address2",
    "City",
    "Province",
    "Postal",
    "HomeArea",
    "HomePhone",
    "WorkArea",
    "WorkPhone",
    "WorkExt",
    "OtherArea",
    "OtherPhone",
    "OtherExt",
    "OtherLoc",
    "ContactAt",
    "ContactTime",
    "Status",
    "Sex",
    "Marital",
    "IsPatient",
    "IsStudent",
    "IsHandicaped",
    "Doctor",
    "Hygienist",
    "Aux",
    "Chart",
    "Sin",
    "Office1",
    "Office2",
    "Office3",
    "Office4",
    "Office5",
    "Alert1",
    "Alert2",
    "Alert3",
    "Alert4",
    "Alert5",
    "Permenant",
    "Primary",
    "Flags",
    "Open",
    "Close",
    "FirstTreatment",
    "LastClaimDate",
    "LastClaimAmount",
    "Extra",
    "Path",
    "LastVisit",
    "Deleted",
    "School",
    "Health",
    "InsPt",
    "OpenBalance",
    "AccountStatus",
    "Assignment",
    "Statements",
    "Interest",
    "ChartIn",
    "Location",
    "UserOut",
    "DateOut",
    "TimeOut",
    "IsFreeAccess",
    "Fee",
    "OtherLocation",
    "NoLocks",
    "CustomCode1",
    "CustomCode2",
    "CustomCode3",
    "CustomCode4",
    "CustomCode5",
    "CustomCode6",
    "CustomCode7",
    "CustomCode8",
    "CustomCode9",
    "CustomCode10",
    "Physician",
    "EmergLast",
    "EmergFirst",
    "EmergMiddle",
    "EmergAddress",
    "EmergCity",
    "EmergProvince",
    "EmergPostal",
    "EmergArea",
    "EmergPhone",
    "EmergRelation",
    "IsChartFixed",
    "EmergAltArea",
    "EmergAltPhone",
    "IsOrtho",
    "OrthoSet",
    "IsIn",
    "EmergAddress2",
    "AltChart",
    "LastUpper",
    "PrefUpper",
    "AddressOther",
    "BankAccount",
    "RespNumber",
    "EmergAddressOther",
    "LastStatementDate",
    "LastStatementAmount",
    "EDIFlag",
    "StatusEndDate",
    "PatType",
    "IsEmergency",
    "ActiveDate",
    "PartnerName",
    "BoxNumber",
    "Email",
    "ChartSort",
    "PartnerPrefix",
    "PrefApptTime",
    "User",
    "StationId",
    "XRayReceived",
    "DateXRayExpected",
    "DateXRayReceived",
    "StatusStartDate",
    "Country",
    "XRayExposures",
    "LastPmtDate",
    "LastPaymentAmount",
    "Audit",
    "MergedChart",
    "ChartSuffix",
    "ReleaseOnFile",
    "EmergExt",
    "EmergAltExt",
    "HomeExt",
    "FeeOverride",
    "DiscGrp",
    "EmancedMinor",
    "RequireTxConsent",
    "PaperChart",
    "InfoNotify",
    "TaxExempt",
    "RecallDoctorToUse",
    "RecallHygToUse",
    "CustomText1",
    "CustomText2",
    "CustomText3",
    "CustomText4",
    "CustomText5",
    "MobileArea",
    "MobilePhone",
    "ApptFeesExempt",
    "PrefLanguage",
    "RaceEthDeclined",
    "Ethnic",
    "IsTrustedAudit",
    "SecondIDType",
    "SecondIDNumber",
    "Is2ndIdTrustedAudit",
    "HasExternalLink",
    "HasCarequality"
   FROM patient
  WHERE ("Patient" IN ( SELECT appoint."Patient"
           FROM appoint
          WHERE (appoint."Type" = ANY (ARRAY[0::numeric, 1::numeric, 2::numeric, 3::numeric, 4::numeric, 5::numeric, 6::numeric])) AND appoint."Date" >= pe_custom_pkg.get_golive_date() AND (appoint."Chair" IN ( SELECT bookchr."Chair"
                   FROM bookchr
                  WHERE (bookchr."BookDetail" IN ( SELECT bookdet."BookDetail"
                           FROM bookdet
                          WHERE (bookdet."Book"::text IN ( SELECT regexp_substr(replace(pe_custom_pkg.get_books_touse(), ' '::character varying)::text, '[^,]+'::text, 1::numeric, (rownum)::numeric) AS regexp_substr
                                   FROM dual
                                  WHERE 1 = 1 CONNECT BY (level) <= (length(regexpreplace_s(pe_custom_pkg.get_books_touse(), '[^,]+'::character varying, ''::character varying)::text) + 1)))))))))
;
CREATE OR REPLACE VIEW pe_phantomprovider_view AS
 SELECT c."Name" AS "Description",
    c."Name" AS "P_Provider_Description"
   FROM bookchr bc,
    chair c
  WHERE 1 = 1 AND bc."Chair" = c."Chair" AND (bc."BookDetail" IN ( SELECT bookdet."BookDetail"
           FROM bookdet
          WHERE (bookdet."Book"::text IN ( SELECT regexp_substr(replace(pe_custom_pkg.get_books_touse(), ' '::character varying)::text, '[^,]+'::text, 1::numeric, (rownum)::numeric) AS regexp_substr
                   FROM dual
                  WHERE 1 = 1 CONNECT BY (level) <= (length(regexp_replace(replace(pe_custom_pkg.get_books_touse(), ' '::character varying)::text, '[^,]+'::text, ''::text)) + 1)))))
;
CREATE OR REPLACE VIEW policy AS
 SELECT pt."PolicyId",
    pt."Family",
    pt."Policy",
    pt."Patient",
    p."Group",
    p."Division",
    p."FormsTo",
    p."Company",
    p."GovPolicy",
    p."Fee",
    p."Employer",
    p."HasFamilyLimit",
    p."FamilyDeduct",
    p."FamilyLimit",
    p."HasPatientLimit",
    p."PatientDeduct",
    p."PatientLimit",
    p."YearEnd",
    p."Assignment",
    p."Signature",
    p."ChangeDate",
    pt."LimitBalance",
    pt."DeductBalance",
    p."CvgPct",
    LEAST(nvl(pt."ResetDate", p."EndDate"), nvl(p."EndDate", pt."ResetDate")) AS "ResetDate",
    GREATEST(nvl(pt."StartDate", p."StartDate"), nvl(p."StartDate", pt."StartDate")) AS "StartDate",
    p."WriteOff",
    pt."Deleted",
    p."PlanType",
    p."MonthlyDeduct",
        CASE
            WHEN pt."Date" > p."Date" OR pt."Date" = p."Date" AND pt."Time" > p."Time" THEN pt."Date"
            ELSE p."Date"
        END AS "Date",
        CASE
            WHEN pt."Date" > p."Date" OR pt."Date" = p."Date" AND pt."Time" > p."Time" THEN pt."Time"
            ELSE p."Time"
        END AS "Time",
        CASE
            WHEN pt."Date" > p."Date" OR pt."Date" = p."Date" AND pt."Time" > p."Time" THEN pt."User"
            ELSE p."User"
        END AS "User",
        CASE
            WHEN pt."Date" > p."Date" OR pt."Date" = p."Date" AND pt."Time" > p."Time" THEN pt."StationId"
            ELSE p."StationId"
        END AS "StationId",
    p."TrojanId",
    pt."YEResetDate",
    pt."MEResetDate",
    p."YearEndDay",
    p."ChildCoverage",
    p."AdultCoverage",
    p."Copay",
    p."PolIns",
    p."Description",
    p."SharablePlan",
    p."VisitFee",
    p."CoverageAge",
    p."CoverageAgeStud",
    p."EndDate",
    p."EDIFlag",
    p."CoverageAgeYoungAdult",
    p."YoungAdultCoverage",
    p."CvgOnBirthChild",
    p."CvgOnBirthStudent",
    p."CvgOnBirthYoungAdult",
    p."ChargeDedAndPtChg"
   FROM ptpol pt,
    polins p
  WHERE pt."PolIns" = p."PolIns"
;
CREATE OR REPLACE VIEW prescrip_asat AS
 SELECT d.oneday,
    h."PrescripH",
    h."Prescription",
    h."Patient",
    h."Date",
    h."Practice",
    h."Provider",
    h."DrugDescription",
    h."Dose",
    h."DrugFrqDesc",
    h."Total",
    h."Refills",
    h."Note",
    h."IsPhoned",
    h."Area",
    h."Telephone",
    h."Pharmacy",
    h."Audit",
    h."ApprovalUser",
    h."ApprovalDate",
    h."IsVoided",
    h."VoidReason",
    h."VoidAudit",
    h."VoidAppUser",
    h."Reference",
    h."Custom1",
    h."Custom2",
    h."IsFaxed",
    h."FaxArea",
    h."FaxPhone",
    h."Drug",
    h."PrescripType",
    h."StartDate",
    h."EndDate",
    h."Deleted",
    h."eRxSyncAudit",
    h."RxNorm",
    h."RcopiaID"
   FROM prescrih h,
    audithis a,
    prescrip_dates d
  WHERE a."Date" < (d.oneday + 1) AND h."Audit" = a."Audit" AND NOT (EXISTS ( SELECT 'x'::text AS text
           FROM prescrih h2,
            audithis a2
          WHERE h2."Prescription" = h."Prescription" AND h2."Audit" = a2."Audit" AND (a2."Date" > a."Date" OR a2."Date" = a."Date" AND a2."Time" > a."Time" OR a2."Date" = a."Date" AND a2."Time" = a."Time" AND h2."PrescripH" > h."PrescripH") AND h2."PrescripH" <> h."PrescripH" AND h2."Date" < (d.oneday + 1)))
;
CREATE OR REPLACE VIEW preventivecare_view AS
 SELECT 0 AS patient,
    0 AS caretype,
    0 AS ptrecall,
    0 AS ptprev,
    0 AS completed,
    to_date(NULL::character varying) AS completeddate
   FROM dual
  WHERE 0 = 1
UNION
 SELECT pr."Patient" AS patient,
    0 AS caretype,
    pr."Id" AS ptrecall,
    0 AS ptprev,
        CASE
            WHEN nvl(st."Inactive", '-1'::integer) = 1::numeric THEN 1
            ELSE 0
        END AS completed,
        CASE
            WHEN nvl(st."Inactive", '-1'::integer) = 1::numeric THEN pr."RecallDate"
            ELSE NULL::timestamp without time zone
        END AS completeddate
   FROM rctype rc
     CROSS JOIN status st
     LEFT JOIN ptrecall pr ON st."Status" = pr."Status"
     LEFT JOIN apptrecl ar ON pr."Id" = ar."PtRecall"
     LEFT JOIN appoint a ON ar."Appointment" = a."Appointment"
  WHERE pr."RecallType" = rc."RecallType" AND rc."PreventiveCare" = 1::numeric AND st."Type" = 4::numeric
UNION
 SELECT pp."Patient" AS patient,
    pc."Type" AS caretype,
    0 AS ptrecall,
    pp."PtPrev" AS ptprev,
    pp."Completed" AS completed,
    pp."CompletedDate" AS completeddate
   FROM ptprev pp,
    prevcare pc
  WHERE pp."PrevCare" = pc."PrevCare"
;
CREATE OR REPLACE VIEW proccode_view AS
 SELECT "Procedure",
    "Insurance",
    "Description",
    "Print",
    "LabReq",
    "IsLab",
    "Factor",
    "Hygienist",
    "Units",
    "RelValue",
    "Global",
    "Local",
    "Type",
    "Zone",
    "MaxSurface",
    "Age",
    "Prompt",
    "ColorStart",
    "ColorEnd",
    "CanAttach",
    "IsOrthoFee",
    "Discipline",
    "Category",
    "Level",
    "LevelDesc",
    "IsProcedure",
    "Deleted",
    "Id",
    "RequireGrading",
    "IsStepParent",
    "IsStepChild",
    "ParentProcedure",
    "StepNumber",
    "OptionalStep",
    "CodeType",
    "PrintOnClaim",
    "BudgetCode",
    "ParentGroup",
    "CompLevel",
    "MaxRequests",
    "RequiresRecall",
    "IsRecall",
    "AlternateCode",
    "IsXRayExposure",
    "CorrespondCode",
    "FillStyle",
    "HasSymbol",
    "Symbol",
    "OldCode",
    "ExposureCount",
    "CondType",
    "AddLab",
    "DaysAtLab",
    "OrMoreSurfaces",
    "EDIExempt",
    "Inactive",
    "AdditionalInfo",
    "PreventInProc",
    "DefaultPhase",
    "RequireTxConsent",
    "PrintDesc",
    "IsRemoval",
    "DiagnosisNotReqd",
    TRIM(BOTH FROM "Insurance")::character varying(48) AS mycode
   FROM procedur p
  WHERE "Inactive" = 0::numeric AND "Id" = (( SELECT max(p2."Id") AS max
           FROM procedur p2
          WHERE p2."Inactive" = 0::numeric AND p2."Insurance" = p."Insurance"))
;
CREATE OR REPLACE VIEW proccons_view AS
 SELECT consreq."ConsReq",
    consreq."Description",
    consreq."RuleType",
    consreq."Consent",
    consreq."Function",
    crproc."Procedure",
    crptype."ProvType"
   FROM consreq,
    crproc,
    crptype
  WHERE consreq."ConsReq" = crproc."ConsReq" AND consreq."ConsReq" = crptype."ConsReq"
;
CREATE OR REPLACE VIEW provsched_view AS
 SELECT 0 AS schtype,
    ' '::character(10) AS provider,
    to_date(NULL::character varying) AS schdate,
    0 AS starttime,
    0 AS endtime,
    0 AS clinic,
    0 AS chair,
    ' '::character(30) AS description
   FROM dual
  WHERE 0 = 1
UNION
 SELECT 1 AS schtype,
    r."Producer" AS provider,
    r."Date" AS schdate,
    r."Start" AS starttime,
    r."End" AS endtime,
    c."Clinic" AS clinic,
    r."Chair" AS chair,
    nvl(NULLIF(rtrim(r."DisplayDesc"::text), ''::text), 'Chair Reservation')::character(30) AS description
   FROM reserve r,
    chair c
  WHERE r."Chair" = c."Chair" AND r."Vacation" = 0::numeric AND r."Holiday" = 0::numeric AND r."Unavailable" = 0::numeric AND r."Closed" = 0::numeric
UNION
 SELECT 1 AS schtype,
    r."Assistant" AS provider,
    r."Date" AS schdate,
    r."Start" AS starttime,
    r."End" AS endtime,
    c."Clinic" AS clinic,
    r."Chair" AS chair,
    nvl(NULLIF(rtrim(r."DisplayDesc"::text), ''::text), 'Chair Reservation')::character(30) AS description
   FROM reserve r,
    chair c
  WHERE (rtrim(r."Assistant"::text) IS NOT NULL OR length(rtrim(r."Assistant"::text)) = 0) AND r."Chair" = c."Chair" AND r."Vacation" = 0::numeric AND r."Holiday" = 0::numeric AND r."Unavailable" = 0::numeric
UNION
 SELECT 2 AS schtype,
    v."Provider" AS provider,
    v."StartDate" AS schdate,
    v."StartTime" AS starttime,
    v."EndTime" AS endtime,
    0 AS clinic,
    0 AS chair,
    nvl(NULLIF(rtrim(v."Description"::text), ''::text), 'Non-clinic Times')::character(30) AS description
   FROM vacation v
  WHERE v."Type" = 0::numeric AND v."Deleted" = 0::numeric
UNION
 SELECT 3 AS schtype,
    a."Producer" AS provider,
    a."Date" AS schdate,
    a."From" AS starttime,
    a."From" + a."Time0" + a."Time1" + a."Time2" + a."Time3" + a."Time4" + a."Time5" AS endtime,
    a."Clinic" AS clinic,
    a."Chair" AS chair,
    'Appointment'::character(30) AS description
   FROM appoint a
  WHERE (a."Type" = ANY (ARRAY[0::numeric, 1::numeric, 2::numeric])) AND a."Reserve" = 0::numeric
UNION
 SELECT 3 AS schtype,
    a."Assistant" AS provider,
    a."Date" AS schdate,
    a."From" AS starttime,
    a."From" + a."Time0" + a."Time1" + a."Time2" + a."Time3" + a."Time4" + a."Time5" AS endtime,
    a."Clinic" AS clinic,
    a."Chair" AS chair,
    'Appointment'::character(30) AS description
   FROM appoint a
  WHERE (a."Type" = ANY (ARRAY[0::numeric, 1::numeric, 2::numeric])) AND (rtrim(a."Assistant"::text) IS NOT NULL OR length(rtrim(a."Assistant"::text)) = 0) AND (a."Reserve" = 0::numeric OR NOT (EXISTS ( SELECT 1
           FROM reserve r
          WHERE a."Reserve" = r."Reserve" AND a."Assistant" = r."Assistant")))
UNION
 SELECT 4 AS schtype,
    ap."Provider" AS provider,
    a."Date" AS schdate,
    a."From" AS starttime,
    a."From" + a."Time0" + a."Time1" + a."Time2" + a."Time3" + a."Time4" + a."Time5" AS endtime,
    a."Clinic" AS clinic,
    a."Chair" AS chair,
    'Appointment'::character(30) AS description
   FROM appoint a,
    apptprov ap
  WHERE (a."Type" = ANY (ARRAY[0::numeric, 1::numeric, 2::numeric])) AND a."Appointment" = ap."Appointment"
;
CREATE OR REPLACE VIEW ptcare_alertp2_view AS
 SELECT a."Patient" AS patient,
    trunc(a."AddDateTime") AS trxdate,
        DECODE(  a."AlertType"
            , 0::numeric
            , 'Alert'::text::character varying
            , 1::numeric
            , 'Allergy'::text::character varying
            , 2::numeric
            , 'Medical Problem'::text::character varying
            , 'Alert'::text::character varying
        ) AS recordtype,
    'Active'::text AS status,
    TRIM(BOTH FROM d."Code") AS code,
    TRIM(BOTH FROM a."Description") AS description,
    a."PtAlert" AS recordid
   FROM ptalert a,
    medalert d
  WHERE a."Deleted" = 0::numeric AND a."Status" = 0::numeric AND d."MedAlert" = a."MedAlert"
;
CREATE OR REPLACE VIEW ptcare_answer2_view AS
 SELECT p2."PtxPId" AS patient,
    trunc(a."ModifiedDateTime") AS trxdate,
    'Patient Survey'::text AS recordtype,
    'Entered'::text AS status,
    TRIM(BOTH FROM d."Code") AS code,
    TRIM(BOTH FROM d."Description") AS description,
    a."Auto" AS recordid
   FROM answer2 a,
    survey2 s,
    surcode2 d,
    patient2 p2
  WHERE a."Status" = 0::numeric AND p2."Auto" = a."PId" AND s."Auto" = a."SId" AND d."Auto" = s."Category"
;
CREATE OR REPLACE VIEW ptcare_appoint_view AS
 SELECT "Patient" AS patient,
    "Date" AS trxdate,
    'Appointment'::text AS recordtype,
        DECODE(  "Type"
            , 0::numeric
            , 'Active'::text::character varying
            , 1::numeric
            , 'Checked-in'::text::character varying
            , 2::numeric
            , 'Checked-out'::text::character varying
            , 3::numeric
            , 'Pending'::text::character varying
            , 4::numeric
            , 'Rescheduled'::text::character varying
            , 5::numeric
            , 'Failed'::text::character varying
            , 6::numeric
            , 'Cancelled'::text::character varying
            , 7::numeric
            , 'Deleted'::text::character varying
            , 8::numeric
            , 'Request'::text::character varying
            , 9::numeric
            , 'Ortho'::text::character varying
            , 10::numeric
            , 'Planned'::text::character varying
            , NULL::character varying
        ) AS status,
    TRIM(BOTH FROM "Code") AS code,
    TRIM(BOTH FROM "Reason") AS description,
    "Appointment" AS recordid
   FROM appoint a
  WHERE "Status" = 0::numeric
;
CREATE OR REPLACE VIEW ptcare_charthis_view AS
 SELECT c."Patient" AS patient,
    c."Date" AS trxdate,
    'Paper Chart'::text AS recordtype,
        DECODE(  c."IsIn"
            , 0::numeric
            , 'Scanned Out'::text::character varying
            , 'Scanned In'::text::character varying
        ) AS status,
    TRIM(BOTH FROM l."Location") AS code,
    TRIM(BOTH FROM l."Description") AS description,
    c."ChartHis" AS recordid
   FROM charthis c
     LEFT JOIN location l ON l."Location" = c."Location"
;
CREATE OR REPLACE VIEW ptcare_claimhis_view AS
 SELECT DISTINCT t."Patient" AS patient,
    c."Date" AS trxdate,
    'Claim Created'::text AS recordtype,
        DECODE(  c."SendType"
            , 1::numeric
            , 'Paper'::text::character varying
            , 2::numeric
            , 'EDI Claim'::text::character varying
            , 'Unknown'::text::character varying
        ) AS status,
    TRIM(BOTH FROM c."Company") AS code,
    TRIM(BOTH FROM i."Name") AS description,
    c."ClaimHis" AS recordid
   FROM claimhis c,
    trx t,
    insuranc i
  WHERE t."Type" = c."Type" AND t."Id" = c."Id" AND i."Company" = c."Company"
;
CREATE OR REPLACE VIEW ptcare_complain_view AS
 SELECT "Patient" AS patient,
    "Time" AS trxdate,
    'Treatment Plan'::text AS recordtype,
    'Created'::text AS status,
    ''::text AS code,
    TRIM(BOTH FROM "Description") AS description
   FROM complain c
;
CREATE OR REPLACE VIEW ptcare_conditions_view AS
 SELECT p."PtxPId" AS patient,
    to_date('01/01/1901'::character varying, 'MM/DD/YYYY'::character varying) + t."Days" AS trxdate,
    'Conditions'::text AS recordtype,
    ' '::text AS status,
    pc."Procedure" AS code,
    TRIM(BOTH FROM pc."Description") AS description,
    t."Auto" AS recordid
   FROM patient2 p
     CROSS JOIN procedur pc
     LEFT JOIN treatme2 t ON t."CodeId" = pc."Id"
  WHERE t."PId" = p."Auto" AND t."Status" = 4::numeric AND t."Deleted" = 0::numeric
;
CREATE OR REPLACE VIEW ptcare_contract_view AS
 SELECT c."Patient" AS patient,
    c."Date" AS trxdate,
    'Contract'::text AS recordtype,
        CASE
            WHEN c."Denied" = 1::numeric THEN 'Denied'::character varying
            ELSE
            CASE
                WHEN c."ExpiryDate" < sysdate THEN 'Expired'::character varying
                ELSE
                DECODE(  c."Deleted"
                    , 1::numeric
                    , 'Deleted'::text::character varying
                    , NULL::character varying
                )
            END
        END AS status,
    TRIM(BOTH FROM c."Consent") AS code,
    c."Description" AS description,
    c."Contract" AS recordid
   FROM contract c
     LEFT JOIN consent t ON t."Consent" = c."Consent"
  WHERE c."SigStatus" <> 0::numeric
;
CREATE OR REPLACE VIEW ptcare_elaborder_view AS
 SELECT l."Patient" AS patient,
    l."Date" AS trxdate,
    'eLab Order'::text AS recordtype,
        DECODE(  l."Status"
            , 0::numeric
            , 'Pending'::text::character varying
            , 1::numeric
            , 'In Progress'::text::character varying
            , 2::numeric
            , 'Complete'::text::character varying
            , 3::numeric
            , 'Closed'::text::character varying
            , NULL::character varying
        ) AS status,
    'Case '::text || TRIM(BOTH FROM to_char(l."CaseNo")) AS code,
    TRIM(BOTH FROM e."ProcedureDescription") AS description,
    l."LabOrder" AS recordid
   FROM laborder l
     LEFT JOIN laboext e ON l."LabOrder" = e."LabOrder"
  WHERE l."Deleted" = 0::numeric AND l."IseLab" = 1::numeric
;
CREATE OR REPLACE VIEW ptcare_implant_view AS
 SELECT "Patient" AS patient,
    "Date" AS trxdate,
    'Implant'::text AS recordtype,
    'Active'::text AS status,
    TRIM(BOTH FROM "DeviceId") AS code,
    TRIM(BOTH FROM "Comment") AS description,
    "PtImplnt" AS recordid
   FROM ptimplnt i
  WHERE "Deleted" = 0::numeric
;
CREATE OR REPLACE VIEW ptcare_labitem_view AS
 SELECT l."Patient" AS patient,
    i."Date" AS trxdate,
    'Lab Activity'::text AS recordtype,
        DECODE(  i."LabOut"
            , 0::numeric
            , 'In'::text::character varying
            , 1::numeric
            , 'Out'::text::character varying
            , 2::numeric
            , 'Waiting'::text::character varying
            , NULL::character varying
        ) AS status,
    (('Case '::text || TRIM(BOTH FROM to_char(l."CaseNo"))) || ', Item '::text) || TRIM(BOTH FROM to_char(i."Item")) AS code,
    TRIM(BOTH FROM i."Text") AS description,
    l."LabOrder" AS recordid
   FROM laborder l,
    labitem i
  WHERE l."Deleted" = 0::numeric AND l."IseLab" = 0::numeric AND i."Deleted" = 0::numeric AND l."LabOrder" = i."LabOrder"
;
CREATE OR REPLACE VIEW ptcare_laborder_view AS
 SELECT l."Patient" AS patient,
    l."Date" AS trxdate,
    'Lab Order'::text AS recordtype,
        DECODE(  l."Status"
            , 0::numeric
            , 'Pending'::text::character varying
            , 1::numeric
            , 'In Progress'::text::character varying
            , 2::numeric
            , 'Complete'::text::character varying
            , 3::numeric
            , 'Closed'::text::character varying
            , NULL::character varying
        ) AS status,
    'Case '::text || TRIM(BOTH FROM to_char(l."CaseNo")) AS code,
    (TRIM(BOTH FROM l."LabProcedure") || ' '::text) || TRIM(BOTH FROM p."Description") AS description,
    l."LabOrder" AS recordid
   FROM laborder l
     LEFT JOIN procedur p ON p."Procedure" = l."LabProcedure"
  WHERE l."Deleted" = 0::numeric AND l."IseLab" = 0::numeric
;
CREATE OR REPLACE VIEW ptcare_materials_view AS
 SELECT p."PtxPId" AS patient,
    to_date('01/01/1901'::character varying, 'MM/DD/YYYY'::character varying) + t."Days" AS trxdate,
    'Materials'::text AS recordtype,
    ' '::text AS status,
    pc."Procedure" AS code,
    TRIM(BOTH FROM pc."Description") AS description,
    t."Auto" AS recordid
   FROM patient2 p
     CROSS JOIN procedur pc
     LEFT JOIN treatme2 t ON t."CodeId" = pc."Id"
  WHERE t."PId" = p."Auto" AND t."Status" = 3::numeric AND t."Deleted" = 0::numeric
;
CREATE OR REPLACE VIEW ptcare_mtest_view AS
 SELECT ord."Patient" AS patient,
    trunc(res."ObservationDateTime") AS trxdate,
    'Medical Test Results'::text AS recordtype,
    'Active'::text AS status,
    TRIM(BOTH FROM res."LOINC") AS code,
    TRIM(BOTH FROM l."LongCommonName") AS description,
    ord."MTestOrd" AS recordid
   FROM mtestord ord,
    mtestreq req,
    mtestres res,
    loinc l
  WHERE ord."MTestOrd" = req."MTestOrd" AND req."MTestReq" = res."MTestReq" AND res."LOINC" = l."LOINC" AND ord."Deleted" = 0::numeric AND req."Deleted" = 0::numeric AND res."Deleted" = 0::numeric
;
CREATE OR REPLACE VIEW ptcare_notes2_view AS
 SELECT p2."PtxPId" AS patient,
    n."Date" AS trxdate,
    'Clinical Note'::text AS recordtype,
    (TRIM(BOTH FROM u."Name") || ', '::text) || TRIM(BOTH FROM u."First") AS status,
    TRIM(BOTH FROM n."Code") AS code,
        DECODE(  n."Type"
            , 4::numeric
            , 'S: '::text::character varying
            , ''::text::character varying
        )::text || TRIM(BOTH FROM rpad(n."Text"::text, 3995)) AS description,
    n."Auto" AS recordid
   FROM notes2 n,
    patient2 p2,
    users u
  WHERE n."Status" = 0::numeric AND (n."Type" <> 4::numeric OR n."Type" = 4::numeric AND n."SectionNo" = 0::numeric) AND p2."Auto" = n."PId" AND u."User" = n."User"
;
CREATE OR REPLACE VIEW ptcare_objectives_view AS
 SELECT o."Patient" AS patient,
    a."Date" AS trxdate,
    'Objectives'::text AS recordtype,
    o."Status" AS status,
    ' '::text AS code,
    TRIM(BOTH FROM o."Description") AS description,
    o."PtObj" AS recordid
   FROM ptobj o,
    ptobjh h,
    audithis a
  WHERE o."PtObj" = h."PtObj" AND o."Deleted" = 0::numeric AND h."Audit" = a."Audit" AND a."HistoryType" = 1::numeric
;
CREATE OR REPLACE VIEW ptcare_pathis_view AS
 SELECT DISTINCT p."Patient" AS patient,
    a."Date" AS trxdate,
    'Patient Record'::character varying AS recordtype,
        DECODE(  a."HistoryType"
            , 1::numeric
            , 'Added'::text::character varying
            , 4::numeric
            , 'Deleted'::text::character varying
            , NULL::character varying
        ) AS status,
    ' '::character varying AS code,
    ((('Entry User: '::character varying::text || TRIM(BOTH FROM u."Name")) || ', '::character varying::text) || TRIM(BOTH FROM u."First"))::character varying AS description,
    p."Id" AS recordid
   FROM pathis p,
    audithis a,
    users u
  WHERE a."Audit" = p."Audit" AND u."User" = a."User" AND a."HistoryType" = 1::numeric
;
CREATE OR REPLACE VIEW ptcare_payplan_view AS
 SELECT p."Patient" AS patient,
        DECODE(  p."InitialDate"
            , NULL::text::timestamp without time zone
            , p."CreationDate"
            , p."InitialDate"
        ) AS trxdate,
    'Payment Plan'::text AS recordtype,
    'Tot: '::text || TRIM(BOTH FROM to_char(p."Total", '999999999.99'::text)) AS status,
    'Starts'::text AS code,
        DECODE(  p."Type"
            , 0::numeric
            , 'Future Charges'::text::character varying
            , 1::numeric
            , 'Outstanding Balance'::text::character varying
            , 2::numeric
            , 'Orthodontics'::text::character varying
            , NULL::character varying
        ) AS description,
    p."PlanId" AS recordid
   FROM payplan p
  WHERE p."Status" = ANY (ARRAY[0::numeric, 1::numeric])
UNION ALL
 SELECT p."Patient" AS patient,
    p."FinalDate" AS trxdate,
    'Payment Plan'::text AS recordtype,
    'Plan Total: '::text || TRIM(BOTH FROM to_char(p."Total", '999999999.99'::text)) AS status,
    'Ends'::text AS code,
        DECODE(  p."Type"
            , 0::numeric
            , 'Future Charges'::text::character varying
            , 1::numeric
            , 'Outstanding Balance'::text::character varying
            , 2::numeric
            , 'Orthodontics'::text::character varying
            , NULL::character varying
        ) AS description,
    p."PlanId" AS recordid
   FROM payplan p
  WHERE (p."Status" = ANY (ARRAY[0::numeric, 1::numeric])) AND p."FinalDate" IS NOT NULL
;
CREATE OR REPLACE VIEW ptcare_pform_view AS
 SELECT pf."Patient" AS patient,
    pf."Date" AS trxdate,
    'EPR Form Last Changed'::text AS recordtype,
    (TRIM(BOTH FROM u."Name") || ', '::text) || TRIM(BOTH FROM u."First") AS status,
    TRIM(BOTH FROM pf."FormCode") AS code,
    TRIM(BOTH FROM pf."Description") AS description,
    pf."PForm" AS recordid
   FROM pform pf
     LEFT JOIN users u ON u."User" = pf."User"
  WHERE pf."OwnerType" <> 6::numeric
;
CREATE OR REPLACE VIEW ptcare_pitem_view AS
 SELECT DISTINCT p."Patient" AS patient,
    p."Date" AS trxdate,
    'EPR Form Activity'::text AS recordtype,
    (TRIM(BOTH FROM u."Name") || ', '::text) || TRIM(BOTH FROM u."First") AS status,
    TRIM(BOTH FROM p."FormCode") AS code,
    TRIM(BOTH FROM pf."Description") AS description,
    pf."PForm" AS recordid
   FROM pitem p
     LEFT JOIN pform pf ON pf."PForm" = p."PForm"
     LEFT JOIN users u ON u."User" = p."User"
  WHERE pf."Date" <> p."Date" AND pf."OwnerType" <> 6::numeric
;
CREATE OR REPLACE VIEW ptcare_planfee_view AS
 SELECT p."Patient" AS patient,
    f."Date" AS trxdate,
    'Payment Plan Fee'::text AS recordtype,
    'Amt: '::text || TRIM(BOTH FROM to_char(f."Amount", '999999999.99'::text)) AS status,
        DECODE(  f."Type"
            , 0::numeric
            , 'Down Payment'::text::character varying
            , 1::numeric
            , 'Regular Payment'::text::character varying
            , 2::numeric
            , 'Final Payment'::text::character varying
            , 3::numeric
            , 'Other'::text::character varying
            , NULL::character varying
        ) AS code,
    ' '::text AS description,
    p."PlanId" AS recordid
   FROM payplan p,
    planfee f
  WHERE f."PlanId" = p."PlanId" AND (p."Status" = ANY (ARRAY[0::numeric, 1::numeric]))
;
CREATE OR REPLACE VIEW ptcare_policy_view AS
 SELECT d."Patient" AS patient,
    o."StartDate" AS trxdate,
    'Policy'::text AS recordtype,
    'Starts'::text AS status,
    TRIM(BOTH FROM o."Company") AS code,
    (('Subscriber #'::text || TRIM(BOTH FROM o."Policy")) || ', Cvg: '::text) || TRIM(BOTH FROM o."CvgPct") AS description,
    o."PolicyId" AS recordid
   FROM policy o,
    ptdepend d
  WHERE o."PolicyId" = d."PolicyId" AND o."Deleted" = 0::numeric AND d."IsCovered" = 1::numeric AND d."Deleted" = 0::numeric
UNION ALL
 SELECT d."Patient" AS patient,
    o."ResetDate" AS trxdate,
    'Policy'::text AS recordtype,
    'Ends'::text AS status,
    TRIM(BOTH FROM o."Company") AS code,
    (('Subscriber #'::text || TRIM(BOTH FROM o."Policy")) || ', Cvg: '::text) || TRIM(BOTH FROM o."CvgPct") AS description,
    o."PolicyId" AS recordid
   FROM policy o,
    ptdepend d
  WHERE o."PolicyId" = d."PolicyId" AND o."Deleted" = 0::numeric AND d."IsCovered" = 1::numeric AND d."Deleted" = 0::numeric AND o."ResetDate" IS NOT NULL
;
CREATE OR REPLACE VIEW ptcare_ppage_view AS
 SELECT DISTINCT p."Patient" AS patient,
    p."Date" AS trxdate,
    'EPR Page'::text AS recordtype,
        DECODE(  p."PtSig"
            , 0::numeric
            , 'Not signed'::text::character varying
            , 'Signed'::text::character varying
        ) AS status,
    TRIM(BOTH FROM p."FormCode") AS code,
    TRIM(BOTH FROM p."Comment") AS description,
    pf."PForm" AS recordid
   FROM ppage p
     LEFT JOIN pform pf ON pf."PForm" = p."PForm"
  WHERE p."Date" IS NOT NULL AND pf."OwnerType" <> 6::numeric
;
CREATE OR REPLACE VIEW ptcare_prescrip_view AS
 SELECT p."Patient" AS patient,
    p."Date" AS trxdate,
    'Prescription'::text AS recordtype,
        DECODE(  p."IsVoided"
            , 1::numeric
            , 'VOIDED - '::text::character varying
            , NULL::character varying
        )::text ||
        DECODE(  p."IsPhoned"
            , 0::numeric
            , 'Written'::text::character varying
            , 'Phoned In'::text::character varying
        )::text AS status,
    TRIM(BOTH FROM p."DrugDescription") AS code,
    (((((TRIM(BOTH FROM p."Dose") || ', '::text) || TRIM(BOTH FROM p."DrugFrqDesc")) || ', Total:'::text) || TRIM(BOTH FROM p."Total")) || ', '::text) || TRIM(BOTH FROM p."Note") AS description,
    p."Prescription" AS recordid
   FROM prescrip p
  WHERE p."PrescripType" <> 0::numeric
UNION ALL
 SELECT p."Patient" AS patient,
    p."Date" AS trxdate,
    'Medication'::text AS recordtype,
        DECODE(  p."IsVoided"
            , 1::numeric
            , 'VOIDED - '::text::character varying
            , NULL::character varying
        )::text || 'Added'::text AS status,
    TRIM(BOTH FROM p."DrugDescription") AS code,
    (((((TRIM(BOTH FROM p."Dose") || ', '::text) || TRIM(BOTH FROM p."DrugFrqDesc")) || ', Total:'::text) || TRIM(BOTH FROM p."Total")) || ', '::text) || TRIM(BOTH FROM p."Note") AS description,
    p."Prescription" AS recordid
   FROM prescrip p
  WHERE p."PrescripType" = 0::numeric AND p."Deleted" = 0::numeric
;
CREATE OR REPLACE VIEW ptcare_problems_view AS
 SELECT p."Patient" AS patient,
    a."Date" AS trxdate,
    'Problems'::text AS recordtype,
    p."Status" AS status,
    p."Problem" AS code,
    TRIM(BOTH FROM p."Description") AS description,
    p."PtPrb" AS recordid
   FROM ptprb p,
    ptprbh h,
    audithis a
  WHERE p."PtPrb" = h."PtPrb" AND p."Deleted" = 0::numeric AND h."Audit" = a."Audit" AND a."HistoryType" = 1::numeric
;
CREATE OR REPLACE VIEW ptcare_ptcase_view AS
 SELECT a."Patient" AS patient,
    a."CreationDate" AS trxdate,
    'Surgery Case'::text AS recordtype,
        DECODE(  a."Deleted"
            , 0::numeric
            , 'Active'::text::character varying
            , 1::numeric
            , 'Deleted'::text::character varying
            , NULL::character varying
        ) AS status,
    TRIM(BOTH FROM a."PtCase") AS code,
    TRIM(BOTH FROM c."Description") AS description,
    a."PtCase" AS recordid
   FROM ptcase a,
    casetype c
  WHERE a."CaseType" = c."CaseType"
;
CREATE OR REPLACE VIEW ptcare_ptcont_view AS
 SELECT p."Patient" AS patient,
    p."Date" AS trxdate,
    'Contact Note'::text AS recordtype,
    (TRIM(BOTH FROM u."Name") || ', '::text) || TRIM(BOTH FROM u."First") AS status,
    ''::text AS code,
    TRIM(BOTH FROM p."Note") AS description,
    p."Contact" AS recordid
   FROM ptcont p,
    users u
  WHERE p."Deleted" = 0::numeric AND u."User" = p."User"
;
CREATE OR REPLACE VIEW ptcare_ptfacul_view AS
 SELECT p."Patient" AS patient,
    a."Date" AS trxdate,
    'Assign Faculty'::text AS recordtype,
        DECODE(  p."IsPrimary"
            , 0::numeric
            , 'Not primary'::text::character varying
            , 'Primary'::text::character varying
        ) AS status,
    TRIM(BOTH FROM p."Discipline") AS code,
    (TRIM(BOTH FROM u."Name") || ', '::text) || TRIM(BOTH FROM u."First") AS description,
    p."PtFacul" AS recordid
   FROM ptfacul p,
    users u,
    audithis a
  WHERE p."Deleted" = 0::numeric AND u."User" = p."Faculty" AND a."Audit" = p."Audit"
;
CREATE OR REPLACE VIEW ptcare_ptletter_view AS
 SELECT "Patient" AS patient,
    "Date" AS trxdate,
    'Contract'::text AS recordtype,
        CASE
            WHEN "ExpiryDate" < sysdate THEN 'Expired'::character varying
            ELSE
            DECODE(  "Deleted"
                , 1::numeric
                , 'Deleted'::text::character varying
                , NULL::character varying
            )
        END AS status,
    TRIM(BOTH FROM "Consent") AS code,
    TRIM(BOTH FROM "Description") AS description,
    "PtLetter" AS recordid
   FROM ptletter p
;
CREATE OR REPLACE VIEW ptcare_ptmanage_view AS
 SELECT p."Patient" AS patient,
    p."CreateDate" AS trxdate,
    'Assign Manager'::text AS recordtype,
        DECODE(  p."IsPrimary"
            , 0::numeric
            , 'Not primary'::text::character varying
            , 'Primary'::text::character varying
        ) AS status,
    ''::text AS code,
    (TRIM(BOTH FROM u."Name") || ', '::text) || TRIM(BOTH FROM u."First") AS description,
    p."Patient" AS recordid
   FROM ptmanage p,
    users u
  WHERE p."Deleted" = 0::numeric AND u."User" = p."User"
;
CREATE OR REPLACE VIEW ptcare_ptneed_view AS
 SELECT "Patient" AS patient,
    "NeedDate" AS trxdate,
    'Need'::text AS recordtype,
        DECODE(  "Assigned"
            , 0::numeric
            , 'Not assigned'::text::character varying
            , 'Assigned'::text::character varying
        ) AS status,
    TRIM(BOTH FROM "NeedCode") AS code,
    TRIM(BOTH FROM "Note") AS description,
    "PtNeed" AS recordid
   FROM ptneed p
  WHERE "Deleted" = 0::numeric
;
CREATE OR REPLACE VIEW ptcare_ptnote_view AS
 SELECT p."Patient" AS patient,
    p."Date" AS trxdate,
    'Transaction Note'::text AS recordtype,
    (TRIM(BOTH FROM u."Name") || ', '::text) || TRIM(BOTH FROM u."First") AS status,
    TRIM(BOTH FROM p."NoteCode") AS code,
    TRIM(BOTH FROM p."Text") AS description,
    p."PtNote" AS recordid
   FROM ptnote p,
    users u
  WHERE p."Deleted" = 0::numeric AND u."User" = p."User"
;
CREATE OR REPLACE VIEW ptcare_ptovrdue_view AS
 SELECT p."Patient" AS patient,
    p."Date" AS trxdate,
    'Overdue Event'::text AS recordtype,
    to_char(p."DaysOverdue" - p."Limit") || ' days overdue'::text AS status,
    TRIM(BOTH FROM p."Overdue") AS code,
    TRIM(BOTH FROM o."Description") AS description,
    p."Patient" AS recordid
   FROM ptovrdue p,
    overdue o
  WHERE o."Overdue" = p."Overdue"
;
CREATE OR REPLACE VIEW ptcare_ptperio_view AS
 SELECT p."Patient" AS patient,
    p."ChartDate" AS trxdate,
    'Perio Chart'::text AS recordtype,
        DECODE(  p."Completed"
            , 0::numeric
            , 'In Process'::text::character varying
            , 'Complete'::text::character varying
        ) AS status,
    TRIM(BOTH FROM p."PerExam") AS code,
    TRIM(BOTH FROM pe."Description") AS description,
    p."PtPerio" AS recordid
   FROM ptperio p
     LEFT JOIN perexam pe ON pe."PerExam" = p."PerExam"
;
CREATE OR REPLACE VIEW ptcare_ptprod_view AS
 SELECT p."Patient" AS patient,
    p."StartDate" AS trxdate,
    'Assign Provider'::text AS recordtype,
    'Start'::text AS status,
    TRIM(BOTH FROM p."Producer") AS code,
    'Ends on '::text || to_char(p."EndDate", 'DD-MON-YYYY'::character varying)::text AS description,
    p."Patient" AS recordid
   FROM ptprod p,
    producer d
  WHERE p."Deleted" = 0::numeric AND d."Producer" = p."Producer"
UNION ALL
 SELECT p."Patient" AS patient,
    p."EndDate" AS trxdate,
    'Assign Provider'::text AS recordtype,
    'End'::text AS status,
    TRIM(BOTH FROM p."Producer") AS code,
    'Started on '::text || to_char(p."StartDate", 'DD-MON-YYYY'::character varying)::text AS description,
    p."Patient" AS recordid
   FROM ptprod p,
    producer d
  WHERE p."Deleted" = 0::numeric AND d."Producer" = p."Producer"
;
CREATE OR REPLACE VIEW ptcare_ptrecall_view AS
 SELECT "Patient" AS patient,
    "RecallDate" AS trxdate,
    'Recall'::text AS recordtype,
    TRIM(BOTH FROM "Status") AS status,
    (TRIM(BOTH FROM "RecallType") || '-'::text) || TRIM(BOTH FROM "Recall") AS code,
    TRIM(BOTH FROM "Comment") AS description,
    "Id" AS recordid
   FROM ptrecall a
  WHERE "Deleted" = 0::numeric
;
CREATE OR REPLACE VIEW ptcare_ptrefer_view AS
 SELECT p."Patient" AS patient,
    p."Date" AS trxdate,
    'Referral'::text AS recordtype,
        DECODE(  p."FromToFlag"
            , 0::numeric
            , 'From'::text::character varying
            , 1::numeric
            , 'To'::text::character varying
            , NULL::character varying
        ) AS status,
    TRIM(BOTH FROM r."Name") AS code,
    TRIM(BOTH FROM p."Note") AS description,
    p."PtRefer" AS recordid
   FROM ptrefer p
     LEFT JOIN referral r ON r."Referral" = p."Referral"
  WHERE p."Deleted" = 0::numeric
UNION ALL
 SELECT p."Patient" AS patient,
    p."EndDate" AS trxdate,
    'Referral'::text AS recordtype,
    'Ends'::character varying AS status,
    TRIM(BOTH FROM r."Name") AS code,
    TRIM(BOTH FROM p."Note") AS description,
    p."PtRefer" AS recordid
   FROM ptrefer p
     LEFT JOIN referral r ON r."Referral" = p."Referral"
  WHERE p."Deleted" = 0::numeric AND p."EndDate" IS NOT NULL
;
CREATE OR REPLACE VIEW ptcare_pttyphis_view AS
 SELECT p."Patient" AS patient,
    a."Date" AS trxdate,
    'Patient Type'::text AS recordtype,
        DECODE(  a."HistoryType"
            , 1::numeric
            , 'Assigned'::text::character varying
            , 4::numeric
            , 'Ended'::text::character varying
            , NULL::character varying
        ) AS status,
    TRIM(BOTH FROM p."PatType") AS code,
    TRIM(BOTH FROM t."Description") AS description,
    p."Patient" AS recordid
   FROM pttyphis p,
    audithis a,
    pattype t
  WHERE a."Audit" = p."Audit" AND t."PatType" = p."PatType" AND (a."HistoryType" = ANY (ARRAY[1::numeric, 4::numeric]))
;
CREATE OR REPLACE VIEW ptcare_ptxray_view AS
 SELECT "Patient" AS patient,
    "DateTaken" AS trxdate,
    'X-ray taken'::text AS recordtype,
    ''::text AS status,
    TRIM(BOTH FROM "Procedure") AS code,
    to_char("ExposureCount") || ' Exposures'::text AS description,
    "PtXRay" AS recordid
   FROM ptxray p
  WHERE "Deleted" = 0::numeric
;
CREATE OR REPLACE VIEW ptcare_request_view AS
 SELECT "Patient" AS patient,
    "DateOut" AS trxdate,
    'Chart Request'::text AS recordtype,
    ' '::text AS status,
    TRIM(BOTH FROM "Location") AS code,
    TRIM(BOTH FROM "Reason") AS description,
    "Request" AS recordid
   FROM request r
;
CREATE OR REPLACE VIEW ptcare_trx_insadjustment_view AS
 SELECT t."Patient" AS patient,
    t."TreatmentDate" AS trxdate,
    'Ins Adjustment'::text AS recordtype,
    TRIM(BOTH FROM to_char(t."Total", '999999999.99'::text)) AS status,
    TRIM(BOTH FROM t."Code") AS code,
    (TRIM(BOTH FROM i."Name") || '-'::text) || TRIM(BOTH FROM t."Description") AS description,
    t."ChartTrx" AS recordid
   FROM trx t,
    insuranc i
  WHERE t."Type" = 7::numeric AND t."Deleted" = 0::numeric AND i."Company" = t."Company1"
;
CREATE OR REPLACE VIEW ptcare_trx_inspayment_view AS
 SELECT t."Patient" AS patient,
    t."TreatmentDate" AS trxdate,
    'Ins Payment'::text AS recordtype,
    TRIM(BOTH FROM to_char(t."Total", '999999999.99'::text)) AS status,
    TRIM(BOTH FROM t."Code") AS code,
    (TRIM(BOTH FROM i."Name") || '-'::text) || TRIM(BOTH FROM t."Description") AS description,
    t."ChartTrx" AS recordid
   FROM trx t,
    insuranc i
  WHERE t."Type" = 74::numeric AND t."Deleted" = 0::numeric AND i."Company" = t."Company1"
;
CREATE OR REPLACE VIEW ptcare_trx_officecharge_view AS
 SELECT "Patient" AS patient,
    "TreatmentDate" AS trxdate,
    'Office Charge'::text AS recordtype,
    TRIM(BOTH FROM to_char("Total", '999999999.99'::text)) AS status,
    TRIM(BOTH FROM "Code") AS code,
    TRIM(BOTH FROM "Description") AS description,
    "ChartTrx" AS recordid
   FROM trx t
  WHERE "Type" = 2::numeric AND "Deleted" = 0::numeric
;
CREATE OR REPLACE VIEW ptcare_trx_plannedtx_view AS
 SELECT "Patient" AS patient,
    "TreatmentDate" AS trxdate,
    'Planned Treatment'::text AS recordtype,
    TRIM(BOTH FROM to_char("Total", '999999999.99'::text)) AS status,
    TRIM(BOTH FROM "Procedure") AS code,
    TRIM(BOTH FROM "Description") AS description,
    "ChartTrx" AS recordid
   FROM trx t
  WHERE "Type" = 5::numeric AND "Deleted" = 0::numeric
;
CREATE OR REPLACE VIEW ptcare_trx_ptadjustment_view AS
 SELECT "Family" AS patient,
    "TreatmentDate" AS trxdate,
    'Pt Adjustment'::text AS recordtype,
    TRIM(BOTH FROM to_char("Total", '999999999.99'::text)) AS status,
    TRIM(BOTH FROM "Code") AS code,
    TRIM(BOTH FROM "Description") AS description,
    "ChartTrx" AS recordid
   FROM trx t
  WHERE "Type" = 6::numeric AND "Deleted" = 0::numeric
;
CREATE OR REPLACE VIEW ptcare_trx_ptpayment_view AS
 SELECT "Family" AS patient,
    "TreatmentDate" AS trxdate,
    'Pt Payment'::text AS recordtype,
    TRIM(BOTH FROM to_char("Total", '999999999.99'::text)) AS status,
    TRIM(BOTH FROM "Code") AS code,
    TRIM(BOTH FROM "Description") AS description,
    "ChartTrx" AS recordid
   FROM trx t
  WHERE "Type" = 3::numeric AND "Deleted" = 0::numeric
;
CREATE OR REPLACE VIEW ptcare_trx_treatment_view AS
 SELECT t."Patient" AS patient,
    t."TreatmentDate" AS trxdate,
    'Treatment-Complete'::text AS recordtype,
    TRIM(BOTH FROM to_char(t."Total", '999999999.99'::text)) AS status,
    TRIM(BOTH FROM t."Procedure") AS code,
    TRIM(BOTH FROM t."Description") AS description,
    t."ChartTrx" AS recordid
   FROM trx t
  WHERE t."Type" = 1::numeric AND t."Status" = 'C'::bpchar AND t."Deleted" = 0::numeric
UNION ALL
 SELECT t."Patient" AS patient,
    t."TreatmentDate" AS trxdate,
    'Treatment-In Process'::text AS recordtype,
    TRIM(BOTH FROM to_char(t."Total", '999999999.99'::text)) AS status,
    TRIM(BOTH FROM t."Procedure") AS code,
    TRIM(BOTH FROM t."Description") AS description,
    t."ChartTrx" AS recordid
   FROM trx t
  WHERE t."Type" = 1::numeric AND t."Status" = 'I'::bpchar AND (t."Deleted" = ANY (ARRAY[0::numeric, 2::numeric]))
;
CREATE OR REPLACE VIEW ptcare_txplan_view AS
 SELECT c."Patient" AS patient,
    h."Date" AS trxdate,
    'Treatment Plan'::text AS recordtype,
    'Created'::text AS status,
    ''::text AS code,
    TRIM(BOTH FROM c."Description") AS description,
    c."TxPlan" AS recordid
   FROM txplan c,
    audithis h
  WHERE c."Audit" = h."Audit"
;
CREATE OR REPLACE VIEW ptcare_view AS
 SELECT 1 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_pathis_view r
UNION ALL
 SELECT 2 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_pttyphis_view r
UNION ALL
 SELECT 3 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_policy_view r
UNION ALL
 SELECT 4 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_ptcont_view r
UNION ALL
 SELECT 5 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_ptprod_view r
UNION ALL
 SELECT 6 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_ptmanage_view r
UNION ALL
 SELECT 7 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_ptfacul_view r
UNION ALL
 SELECT 8 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_ptneed_view r
UNION ALL
 SELECT 9 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_ptrefer_view r
UNION ALL
 SELECT 10 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_trx_treatment_view r
UNION ALL
 SELECT 11 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_trx_plannedtx_view r
UNION ALL
 SELECT 12 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_notes2_view r
UNION ALL
 SELECT 13 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_prescrip_view r
UNION ALL
 SELECT 14 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_alertp2_view r
UNION ALL
 SELECT 15 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_ptxray_view r
UNION ALL
 SELECT 16 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_ptperio_view r
UNION ALL
 SELECT 17 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_txplan_view r
UNION ALL
 SELECT 18 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_appoint_view r
UNION ALL
 SELECT 19 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_ptrecall_view r
UNION ALL
 SELECT 20 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_trx_officecharge_view r
UNION ALL
 SELECT 21 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_trx_ptpayment_view r
UNION ALL
 SELECT 22 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_trx_inspayment_view r
UNION ALL
 SELECT 23 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_trx_ptadjustment_view r
UNION ALL
 SELECT 24 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_trx_insadjustment_view r
UNION ALL
 SELECT 25 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_claimhis_view r
UNION ALL
 SELECT 26 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_ptnote_view r
UNION ALL
 SELECT 27 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_payplan_view r
UNION ALL
 SELECT 28 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_planfee_view r
UNION ALL
 SELECT 29 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_ptovrdue_view r
UNION ALL
 SELECT 30 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_laborder_view r
UNION ALL
 SELECT 31 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_labitem_view r
UNION ALL
 SELECT 32 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_pform_view r
UNION ALL
 SELECT 33 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_pitem_view r
UNION ALL
 SELECT 34 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_ppage_view r
UNION ALL
 SELECT 35 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_ptletter_view r
UNION ALL
 SELECT 36 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_contract_view r
UNION ALL
 SELECT 37 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_answer2_view r
UNION ALL
 SELECT 38 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_request_view r
UNION ALL
 SELECT 39 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_charthis_view r
UNION ALL
 SELECT 40 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_problems_view r
UNION ALL
 SELECT 41 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_objectives_view r
UNION ALL
 SELECT 42 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_materials_view r
UNION ALL
 SELECT 43 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_conditions_view r
UNION ALL
 SELECT 44 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_mtest_view r
UNION ALL
 SELECT 45 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_ptcase_view r
UNION ALL
 SELECT 46 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_elaborder_view r
UNION ALL
 SELECT 47 AS recordtypeid,
    r.patient,
    r.trxdate,
    r.recordtype,
    r.status,
    r.code,
    r.description,
    r.recordid
   FROM ptcare_implant_view r
;
CREATE OR REPLACE VIEW ptdates_view AS
 SELECT "Patient" AS patient,
    ( SELECT max(a1."Date") AS max
           FROM appoint a1
          WHERE a1."Patient" = p."Patient" AND (a1."Type" = ANY (ARRAY[0::numeric, 1::numeric, 2::numeric])) AND a1."Date" <= trunc(sysdate)) AS lastapptdate,
    ( SELECT min(a2."Date") AS min
           FROM appoint a2
          WHERE a2."Patient" = p."Patient" AND (a2."Type" = ANY (ARRAY[0::numeric, 1::numeric, 2::numeric])) AND a2."Date" > trunc(sysdate)) AS nextapptdate,
    ( SELECT max(r1."RecallDate") AS max
           FROM ptrecall r1
          WHERE r1."Patient" = p."Patient" AND r1."Deleted" = 0::numeric AND r1."RecallDate" <= trunc(sysdate)) AS lastrecalldate,
    ( SELECT min(r2."RecallDate") AS min
           FROM ptrecall r2
          WHERE r2."Patient" = p."Patient" AND isrecallactive(r2."Id") = 1::numeric AND r2."RecallDate" > trunc(sysdate)) AS nextrecalldate,
    ( SELECT max(t1."TreatmentDate") AS max
           FROM trx t1
          WHERE t1."Patient" = p."Patient" AND t1."Type" = 1::numeric AND t1."Deleted" = 0::numeric AND trx_pkg.isnonclinicaltx(t1."Procedure") = 0::numeric) AS lasttreatmentdate,
    ( SELECT max(t2."Date") AS max
           FROM trx t2
          WHERE t2."Patient" = p."Patient" AND t2."Deleted" = 0::numeric) AS lasttransactiondate,
    ( SELECT min(
                CASE
                    WHEN nvl(a."Type", '-1'::integer) >= 0::numeric AND nvl(a."Type", '-1'::integer) <= 2::numeric THEN a."Date"
                    ELSE pr."RecallDate"
                END) AS min
           FROM ptrecall pr
             CROSS JOIN rctype r
             LEFT JOIN apptrecl ar ON pr."Id" = ar."PtRecall"
             LEFT JOIN appoint a ON ar."Appointment" = a."Appointment"
          WHERE pr."Patient" = p."Patient" AND pr."RecallType" = r."RecallType" AND r."PreventiveCare" = 1::numeric AND isrecallactive(pr."Id") = 1::numeric) AS nexthygienedate,
    ( SELECT min(pp."DueDate") AS min
           FROM ptprev pp,
            prevcare pc
          WHERE pp."Patient" = p."Patient" AND pp."PrevCare" = pc."PrevCare" AND pp."Completed" = 0::numeric AND pp."Deleted" = 0::numeric AND pc."Type" = 1::numeric AND pp."DueDate" >= trunc(sysdate)) AS nextexamdate,
    ( SELECT min(pp."DueDate") AS min
           FROM ptprev pp,
            prevcare pc
          WHERE pp."Patient" = p."Patient" AND pp."PrevCare" = pc."PrevCare" AND pp."Completed" = 0::numeric AND pp."Deleted" = 0::numeric AND pc."Type" = 2::numeric AND pp."DueDate" >= trunc(sysdate)) AS nextxraydate,
        CASE
            WHEN (( SELECT max(a1."Date") AS max
               FROM appoint a1
              WHERE a1."Patient" = p."Patient" AND (a1."Type" = ANY (ARRAY[0::numeric, 1::numeric, 2::numeric])) AND a1."Date" <= trunc(sysdate))) > nvl(( SELECT max(t1."TreatmentDate") AS max
               FROM trx t1
              WHERE t1."Patient" = p."Patient" AND t1."Type" = 1::numeric AND t1."Deleted" = 0::numeric), to_date('1900-01-01'::character varying, 'YYYY-MM-DD'::character varying)) THEN ( SELECT max(a1."Date") AS max
               FROM appoint a1
              WHERE a1."Patient" = p."Patient" AND (a1."Type" = ANY (ARRAY[0::numeric, 1::numeric, 2::numeric])) AND a1."Date" <= trunc(sysdate))
            ELSE ( SELECT max(t1."TreatmentDate") AS max
               FROM trx t1
              WHERE t1."Patient" = p."Patient" AND t1."Type" = 1::numeric AND t1."Deleted" = 0::numeric)
        END AS lastvisit,
    ( SELECT to_date(NULL::character varying) AS to_date
           FROM dual) AS customdate1,
    ( SELECT to_date(NULL::character varying) AS to_date
           FROM dual) AS customdate2,
    ( SELECT to_date(NULL::character varying) AS to_date
           FROM dual) AS customdate3,
    ( SELECT to_date(NULL::character varying) AS to_date
           FROM dual) AS customdate4,
    ( SELECT to_date(NULL::character varying) AS to_date
           FROM dual) AS customdate5,
    ( SELECT to_date(NULL::character varying) AS to_date
           FROM dual) AS customdate6,
    ( SELECT to_date(NULL::character varying) AS to_date
           FROM dual) AS customdate7,
    ( SELECT to_date(NULL::character varying) AS to_date
           FROM dual) AS customdate8,
    ( SELECT to_date(NULL::character varying) AS to_date
           FROM dual) AS customdate9,
    ( SELECT to_date(NULL::character varying) AS to_date
           FROM dual) AS customdate10
   FROM patient p
;
CREATE OR REPLACE VIEW ptdepend_view AS
 SELECT p."PolicyId",
    p."Patient",
    p."Number",
    p."IsCovered",
    p."Relation",
    p."HasPatientLimit",
    p."PatientLimit",
    p."PatientDeduct",
    p."LimitBalance",
    p."DeductBalance",
    p."Date",
    p."Time",
    p."User",
    p."StationId",
    p."Deleted",
    p."BillOrder",
    p."VisitBalance",
    p."MedicaidCoPay",
    p."StartDate",
    p."EndDate",
    p."CardVerNo",
    p."CorrectStatus",
    p2."PolIns"
   FROM ptdepend p,
    ptpol p2
  WHERE p."PolicyId" = p2."PolicyId"
;
CREATE OR REPLACE VIEW ptsummary_view AS
 SELECT p."Patient",
    p."SummCode",
    s."Type",
    s."Description",
    s."Value1Desc",
    s."Value2Desc",
    s."AllowOverride",
    s."ShowInAlerts",
    s."Inactive",
        CASE
            WHEN p."Audit" > p."OverrideAudit" THEN p."Value1"
            ELSE p."Value1Override"
        END AS "Value1",
        CASE
            WHEN p."Audit" > p."OverrideAudit" THEN p."Value2"
            ELSE p."Value2Override"
        END AS "Value2",
        CASE
            WHEN p."Audit" > p."OverrideAudit" THEN p."Audit"
            ELSE p."OverrideAudit"
        END AS "Audit",
        CASE
            WHEN p."Audit" > p."OverrideAudit" THEN 0
            ELSE 1
        END AS "IsOverride"
   FROM summcode s,
    ptsumm p
  WHERE p."SummCode" = s."SummCode"
;
CREATE OR REPLACE VIEW pttype_reporting_view AS
 SELECT "Patient"::numeric(10,0) AS "Patient",
    "SLevel",
    "Reporting"
   FROM ( SELECT pt."Patient",
            pa."SLevel",
            pa."Reporting"
           FROM pttypes pt,
            patacces pa
          WHERE pt."PatType" = pa."PatType" AND pt."Deleted" = 0::numeric
        UNION
         SELECT p."Patient",
            sl."SLevel",
            1
           FROM patient p,
            slevel sl
          WHERE p."Deleted" = 0::numeric AND sl."Deleted" = 0::numeric AND NOT (EXISTS ( SELECT 1
                   FROM pttypes pt
                  WHERE p."Patient" = pt."Patient" AND pt."Deleted" = 0::numeric))
        UNION
         SELECT 0,
            slevel."SLevel",
            1
           FROM slevel) unnamed_subquery
;
CREATE OR REPLACE VIEW ptvitalsstages_view AS
 SELECT "PtVital",
    ( SELECT max(s."PtStage") AS "PtStage"
           FROM ptstage s
          WHERE s."Appointment" = v."Appointment" AND s."StageStart" <= v."EntryTime") AS "PtStage"
   FROM ptvital v
  WHERE 1 = 1
;
CREATE OR REPLACE VIEW startchk_notstartchktx_view AS
 SELECT "AppTrx",
    "Appointment",
    "Type",
    "Id",
    "Treatment",
    "Procedure",
    "Date"
   FROM apptrx t
  WHERE startcheckedtx("Appointment", "Type", "Id", "Treatment", "Procedure") = 0::numeric
;
CREATE OR REPLACE VIEW startchk_prevstartchktx_view AS
 SELECT t."StartTrx",
    t."StartChk",
    t."Type",
    t."Id",
    t."Treatment",
    t."OrigRecNo",
    t."Procedure",
    startcheckrevokedtx(s."Appointment", t."Type", t."Id", t."Treatment", t."Procedure") AS revoked
   FROM starttrx t,
    startchk s
  WHERE s."StartChk" = t."StartChk"
;
CREATE OR REPLACE VIEW stnopt_view AS
 SELECT i."Inidef" AS inidef,
    i."Module" AS module,
    i."Section" AS section,
    i."Key" AS key,
    i."Type" AS type,
    i."Iniset" AS iniset,
    i."IsTemplate" AS istemplate,
    i."Description" AS description,
    i."Station" AS station,
    ii."Iniset" AS iteminiset,
    ii."ValueNum" AS valuenum,
    ii."ValueStr" AS valuestr
   FROM ( SELECT inidef."Inidef",
            inidef."Module",
            inidef."Section",
            inidef."Key",
            inidef."Type",
            iniset."Iniset",
            iniset."IsTemplate",
            iniset."Description",
            iniset."Station"
           FROM inidef,
            iniset) i
     LEFT JOIN iniitem ii ON i."Inidef" = ii."Inidef" AND i."Iniset" = ii."Iniset"
;
CREATE OR REPLACE VIEW trx_asat AS
 SELECT d.oneday,
    h."History",
    h."HistoryType",
    h."Type",
    h."Id",
    h."Treatment",
    h."Patient",
    h."Family",
    h."Status",
    h."EDI",
    h."EDIStatus",
    h."Date",
    h."SubmitDate",
    h."ClaimDoctor",
    h."Submitted",
    h."TreatmentDate",
    h."CreationDate",
    h."Procedure",
    h."Code",
    h."Site",
    h."Surface",
    h."Unit",
    h."Producer",
    h."Total",
    h."InsTotal",
    h."Company1",
    h."Policy1",
    h."Category1",
    h."Item1",
    h."Deduct1",
    h."Assign1",
    h."Eligible1",
    h."Pct1",
    h."Amount1",
    h."InsPayed1",
    h."InsAdj1",
    h."Company2",
    h."Policy2",
    h."Category2",
    h."Item2",
    h."Assign2",
    h."Deduct2",
    h."Eligible2",
    h."Pct2",
    h."Amount2",
    h."InsPayed2",
    h."InsAdj2",
    h."Company3",
    h."Policy3",
    h."Category3",
    h."Item3",
    h."Assign3",
    h."Deduct3",
    h."Eligible3",
    h."Pct3",
    h."Amount3",
    h."InsPayed3",
    h."InsAdj3",
    h."Description",
    h."Deleted",
    h."Bank",
    h."Payed",
    h."InsPayed",
    h."PtAdj",
    h."InsAdj",
    h."EstimateF",
    h."Additional",
    h."TxStatus",
    h."User",
    h."PtWriteOff",
    h."PolicyId1",
    h."PolicyId2",
    h."PolicyId3",
    h."InsStatus1",
    h."InsStatus2",
    h."InsStatus3",
    h."IsBankDeposit",
    h."ChartTrx",
    h."PlanTotal",
    h."Phase",
    h."Seq",
    h."AppUser",
    h."AppDate",
    h."Grading",
    h."Site2",
    h."Custom1",
    h."Custom2",
    h."PayPlanId",
    h."Discipline",
    h."DiscountedPmtId",
    h."Location",
    h."OrigAssign1",
    h."OrigAssign2",
    h."OrigAssign3",
    h."InDispute",
    h."DisputeDate",
    h."DeletionDate",
    h."EDIPat",
    h."EDIPatStatus",
    h."InsTransfer1",
    h."InsTransfer2",
    h."InsTransfer3",
    h."InsTransfer",
    h."InsPmtId",
    h."StationId",
    h."Practice",
    h."Suspended",
    h."DelAppUser",
    h."DelAppDate",
    h."OrthoStatus",
    h."CvgType",
    h."ModifiedDate",
    h."OrigClaimDate",
    h."SubmitMode",
    h."Custom3",
    h."Custom4",
    h."CorrespondCode",
    h."InsCvgType1",
    h."InsCvgType2",
    h."InsCvgType3",
    h."OrigRecNo",
    h."EntryUser",
    h."PlanInProcTotal",
    h."TrxDep",
    h."CustomaryTotal",
    h."TaxRate",
    h."TaxAmount"
   FROM history h,
    table_of_dates d
  WHERE h."ModifiedDate" < (d.oneday + 1) AND NOT (EXISTS ( SELECT 'x'::text AS text
           FROM history h2
          WHERE h2."OrigRecNo" = h."OrigRecNo" AND h2."History" > h."History" AND h2."ModifiedDate" < (d.oneday + 1)))
;
CREATE OR REPLACE VIEW txplncon_quote_view AS
 SELECT "TxPlan",
    "Contract"
   FROM txplncon t
  WHERE NOT (EXISTS ( SELECT 1
           FROM txplncon t2
          WHERE t."TxPlan" = t2."TxPlan" AND t2."Contract" > t."Contract"))
;
CREATE OR REPLACE VIEW unapproveditems_view AS
 SELECT 0 AS rtype,
    0 AS id,
    to_date(NULL::character varying) AS txdate,
    0 AS userid,
    ' '::character(50) AS procedure,
    ' '::character(31) AS site,
    ' '::character(6) AS surface,
    ' '::character varying(80) AS description,
    ' '::character(6) AS status,
    ' '::character(15) AS discipline,
    0 AS patient,
    ' '::character(15) AS chart,
    ' '::character(31) AS last,
    ' '::character(31) AS first,
    ' '::character(31) AS middle,
    to_date(NULL::character varying) AS auditdatetime,
    0 AS audituser
   FROM dual
  WHERE 0 = 1
UNION
 SELECT 0 AS rtype,
    c."Id" AS id,
    c."TxDate" AS txdate,
    u."User" AS userid,
    c."Procedure" AS procedure,
    c."Site" AS site,
    c."Surface" AS surface,
    p."Description" AS description,
    c."Status" AS status,
    c."Discipline" AS discipline,
    pt."Patient" AS patient,
    pt."Chart" AS chart,
    pt."Last" AS last,
    pt."First" AS first,
    pt."Middle" AS middle,
        DECODE(  t2."Deleted"
            , 1::numeric
            , t2."DeletionDate"
            , t2."ModifiedDateTime"
        ) AS auditdatetime,
    c."User" AS audituser
   FROM chartlnk c
     CROSS JOIN treatme2 t2
     CROSS JOIN patient pt
     CROSS JOIN users u
     LEFT JOIN procedur p ON p."Procedure" = c."Procedure"
  WHERE c."Patient" = pt."Patient" AND c."Auto" = t2."Auto" AND c."Producer" = u."Producer" AND length(TRIM(BOTH FROM c."Producer")) > 0 AND substr(c."Status"::text, 1::numeric, 1::numeric) <> 'O'::text AND t2."Status" <> 5::numeric
UNION
 SELECT
        DECODE(  n."Type"
            , 4::numeric
            , 2
            , 1
        ) AS rtype,
    n."Auto" AS id,
    n."Date" AS txdate,
    n."User" AS userid,
    ''::bpchar AS procedure,
    ''::bpchar AS site,
    ''::bpchar AS surface,
        CASE
            WHEN n."Type" < 2::numeric AND n."IsTemplate" = 1::numeric THEN 'Template Note'::text
            WHEN n."Type" < 2::numeric AND n."IsTemplate" = 0::numeric THEN 'General Note'::text
            WHEN n."Type" = 2::numeric THEN 'Lab Note'::text
            WHEN n."Type" = 3::numeric THEN 'Ortho Visit'::text
            WHEN n."Type" = 4::numeric THEN 'SOAP Note'::text
            WHEN n."Type" = 5::numeric THEN 'Rx Note'::text
            WHEN n."Type" = 6::numeric THEN 'Surgery Note'::text
            ELSE ' '::text
        END AS description,
        DECODE(  n."Status"
            , 1::numeric
            , 'D'::text::character varying
            , ' '::text::character varying
        ) AS status,
    ''::bpchar AS discipline,
    p2."PtxPId" AS patient,
    p2."ChartId" AS chart,
    p2."LastName" AS last,
    p2."FirstName" AS first,
    p2."MidName" AS middle,
    n."ModifiedDateTime" AS auditdatetime,
    n."User" AS audituser
   FROM notes2 n,
    patient2 p2
  WHERE n."PId" = p2."Auto" AND (n."Type" <> 4::numeric OR n."SectionNo" = 0::numeric) AND n."Type" <> 3::numeric AND n."AppUser" = 0::numeric AND (n."Status" = ANY (ARRAY[0::numeric, 1::numeric]))
UNION
 SELECT 14 AS rtype,
    n."Auto" AS id,
    n."Date" AS txdate,
    n."User" AS userid,
    c."Procedure" AS procedure,
    ''::bpchar AS site,
    ''::bpchar AS surface,
    p."Description" AS description,
        DECODE(  n."Status"
            , 1::numeric
            , 'D'::text::character varying
            , ' '::text::character varying
        ) AS status,
    c."Discipline" AS discipline,
    p2."PtxPId" AS patient,
    p2."ChartId" AS chart,
    p2."LastName" AS last,
    p2."FirstName" AS first,
    p2."MidName" AS middle,
    n."ModifiedDateTime" AS auditdatetime,
    n."User" AS audituser
   FROM notes2 n
     CROSS JOIN patient2 p2
     CROSS JOIN treatme2 t
     CROSS JOIN procedur p
     LEFT JOIN chartlnk c ON n."TxId" = c."Auto"
  WHERE n."PId" = p2."Auto" AND n."Type" = 3::numeric AND n."AppUser" = 0::numeric AND (n."Status" = ANY (ARRAY[0::numeric, 1::numeric])) AND n."TxId" = t."Auto" AND t."Status" = 5::numeric AND c."Procedure" = p."Procedure"
UNION
 SELECT 3 AS rtype,
    pf."PForm" AS id,
    pf."CreatedDate" AS txdate,
    pi."User" AS userid,
    pf."FormCode" AS procedure,
    ''::bpchar AS site,
    ''::bpchar AS surface,
    pf."Description" AS description,
    ' '::bpchar AS status,
    ''::bpchar AS discipline,
    pt."Patient" AS patient,
    pt."Chart" AS chart,
    pt."Last" AS last,
    pt."First" AS first,
    pt."Middle" AS middle,
    nvl(pf."LastStartDateTime", pf."Date") AS auditdatetime,
    pi."User" AS audituser
   FROM pitem pi,
    pform pf,
    patient pt
  WHERE pi."PForm" = pf."PForm" AND pf."Inactive" = 0::numeric AND pf."OwnerType" <> 5::numeric AND pf."OwnerType" <> 6::numeric AND pi."Patient" = pt."Patient" AND pi."Status" = 0::numeric AND pi."AppUser" = 0::numeric AND pf."Approved" = 0::numeric AND pi."ASAType" = 0::numeric
UNION
 SELECT 4 AS rtype,
    p."PtPrb" AS id,
    p."Date" AS txdate,
    a."User" AS userid,
    p."Problem" AS procedure,
    p."Site" AS site,
    p."Surface" AS surface,
    p."Description" AS description,
    p."Status" AS status,
    ''::bpchar AS discipline,
    p."Patient" AS patient,
    pt."Chart" AS chart,
    pt."Last" AS last,
    pt."First" AS first,
    pt."Middle" AS middle,
    to_datetime(a."Date", a."Time") AS auditdatetime,
    a."User" AS audituser
   FROM ptprb p,
    patient pt,
    audithis a
  WHERE p."AppUser" = 0::numeric AND p."Deleted" = 0::numeric AND p."Patient" = pt."Patient" AND p."Audit" = a."Audit" AND a."TableName"::text = 'PTPRB'::text
UNION
 SELECT 5 AS rtype,
    p."PtPerio" AS id,
    p."ChartDate" AS txdate,
    a."User" AS userid,
    pe."PerExam" AS procedure,
    ''::bpchar AS site,
    ''::bpchar AS surface,
    pe."Description" AS description,
    ''::bpchar AS status,
    ''::bpchar AS discipline,
    p."Patient" AS patient,
    pt."Chart" AS chart,
    pt."Last" AS last,
    pt."First" AS first,
    pt."Middle" AS middle,
    to_datetime(a."Date", a."Time") AS auditdatetime,
    a."User" AS audituser
   FROM ptperio p
     CROSS JOIN patient pt
     CROSS JOIN audithis a
     LEFT JOIN perexam pe ON p."PerExam" = pe."PerExam"
  WHERE p."AppUser" = 0::numeric AND p."Deleted" = 0::numeric AND p."Patient" = pt."Patient" AND p."Audit" = a."Audit" AND a."TableName"::text = 'PTPERIO'::text
UNION
 SELECT 6 AS rtype,
    p."PtLetter" AS id,
    p."Date" AS txdate,
    p."User" AS userid,
    ''::bpchar AS procedure,
    ''::bpchar AS site,
    ''::bpchar AS surface,
    p."Description" AS description,
    ''::bpchar AS status,
    ''::bpchar AS discipline,
    p."Patient" AS patient,
    pt."Chart" AS chart,
    pt."Last" AS last,
    pt."First" AS first,
    pt."Middle" AS middle,
    nvl(p."ModifiedDate", p."Date") AS auditdatetime,
    p."User" AS audituser
   FROM ptletter p,
    patient pt
  WHERE p."Type" = 3::numeric AND p."AppUser" = 0::numeric AND p."Status" = 1::numeric AND p."Deleted" = 0::numeric AND p."Patient" = pt."Patient"
UNION
 SELECT 7 AS rtype,
    pf."PForm" AS id,
    pf."Date" AS txdate,
    pi."User" AS userid,
    pf."FormCode" AS procedure,
    ''::bpchar AS site,
    ''::bpchar AS surface,
    pf."Description" AS description,
    ' '::bpchar AS status,
    ''::bpchar AS discipline,
    0 AS patient,
    ''::bpchar AS chart,
    ''::bpchar AS last,
    ''::bpchar AS first,
    ''::bpchar AS middle,
    nvl(pf."LastStartDateTime", pf."Date") AS auditdatetime,
    pf."User" AS audituser
   FROM pitem pi,
    pform pf,
    users u
  WHERE pi."PForm" = pf."PForm" AND pf."Inactive" = 0::numeric AND pf."OwnerType" = 5::numeric AND pf."OwnerId" = u."User" AND pi."Status" = 0::numeric AND pi."AppUser" = 0::numeric AND pf."Approved" = 0::numeric AND pi."ASAType" = 0::numeric
UNION
 SELECT 8 AS rtype,
    lo."LabOrder" AS id,
    li."Date" AS txdate,
    li."User" AS userid,
    lo."LabProcedure" AS procedure,
    ''::bpchar AS site,
    ''::bpchar AS surface,
    p."Description" AS description,
        CASE
            WHEN lo."Status" = 0::numeric THEN 'P'::text
            WHEN lo."Status" = 1::numeric THEN 'I'::text
            WHEN lo."Status" = 2::numeric THEN 'C'::text
            WHEN lo."Status" = 3::numeric THEN 'X'::text
            ELSE ''::text
        END AS status,
    lo."Discipline" AS discipline,
    lo."Patient" AS patient,
    pt."Chart" AS chart,
    pt."Last" AS last,
    pt."First" AS first,
    pt."Middle" AS middle,
    to_datetime(a."Date", a."Time") AS auditdatetime,
    a."User" AS audituser
   FROM laborder lo
     CROSS JOIN labitem li
     CROSS JOIN patient pt
     CROSS JOIN audithis a
     LEFT JOIN labcode lc ON lo."LabCode" = lc."LabCode"
     LEFT JOIN procedur p ON lo."LabProcedure" = p."Procedure"
  WHERE lo."LabOrder" = li."LabOrder" AND lo."Patient" = pt."Patient" AND lo."IseLab" = 0::numeric AND lo."Deleted" = 0::numeric AND li."Deleted" = 0::numeric AND li."ApprovalUser" = 0::numeric AND (lo."CurrentItem" = li."Item" OR li."DateIn" IS NOT NULL) AND li."Audit" = a."Audit"
UNION
 SELECT DISTINCT 11 AS rtype,
    a."Appointment" AS id,
    a."Date" AS txdate,
    ah."User" AS userid,
    substr(a."Code"::text, 1::numeric, 7::numeric) AS procedure,
    c."SiteName" AS site,
    ''::text AS surface,
    ct."Description" AS description,
    ' '::text AS status,
    ''::text AS discipline,
    pt."Patient" AS patient,
    pt."Chart" AS chart,
    pt."Last" AS last,
    pt."First" AS first,
    pt."Middle" AS middle,
    to_datetime(ah."Date", ah."Time") AS auditdatetime,
    ah."User" AS audituser
   FROM ptcase c
     CROSS JOIN ptcasejt j
     CROSS JOIN casetype ct
     CROSS JOIN appoint a
     CROSS JOIN patient pt
     CROSS JOIN ptsurg ps
     CROSS JOIN audithis ah
     LEFT JOIN ptsdrug pd ON pd."WasteAudit" = ah."Audit"
  WHERE a."Appointment" = ps."Appointment" AND ps."Appointment" = pd."Appointment" AND ps."WasteApprovalUser" <= 0::numeric AND pd."Appointment" = a."Appointment" AND pd."Waste" > 1::numeric AND pd."Deleted" = 0::numeric AND a."Patient" = pt."Patient" AND c."Patient" = pt."Patient" AND c."PtCase" = j."PtCase" AND j."Type" = 0::numeric AND j."Id" = a."Appointment" AND c."CaseType" = ct."CaseType" AND sched_pkg.appointhasunapprovedwaste(a."Appointment", ah."User") > 0::numeric
UNION
 SELECT 10 AS rtype,
    a."Appointment" AS id,
    a."Date" AS txdate,
    u."User" AS userid,
    substr(a."Code"::text, 1::numeric, 7::numeric) AS procedure,
    c."SiteName" AS site,
    ''::bpchar AS surface,
    ct."Description" AS description,
    ' '::bpchar AS status,
    ''::bpchar AS discipline,
    pt."Patient" AS patient,
    pt."Chart" AS chart,
    pt."Last" AS last,
    pt."First" AS first,
    pt."Middle" AS middle,
    to_datetime(ah."Date", ah."Time") AS auditdatetime,
    ah."User" AS audituser
   FROM ptcase c
     CROSS JOIN ptcasejt j
     CROSS JOIN casetype ct
     CROSS JOIN appoint a
     CROSS JOIN users u
     CROSS JOIN patient pt
     CROSS JOIN ptsurg s
     LEFT JOIN maxaudithisperappoint_view ah ON ah."Appointment" = a."Appointment"
  WHERE a."Appointment" = s."Appointment" AND s."ApprovalUser" = 0::numeric AND ((EXISTS ( SELECT 1
           FROM ptvital v
          WHERE v."Appointment" = s."Appointment")) OR (EXISTS ( SELECT 1
           FROM ptsdrug d,
            ptsdose ds
          WHERE d."Appointment" = s."Appointment" AND d."PtSDrug" = ds."PtSDrug"))) AND a."Producer" = u."Producer" AND u."SurgeryNeedsApp" = 1::numeric AND a."Patient" = pt."Patient" AND c."Patient" = pt."Patient" AND c."PtCase" = j."PtCase" AND j."Type" = 0::numeric AND j."Id" = a."Appointment" AND c."CaseType" = ct."CaseType" AND sched_pkg.appointhasunapprovedwaste(s."Appointment", u."User") = 0::numeric
UNION
 SELECT 10 AS rtype,
    a."Appointment" AS id,
    a."Date" AS txdate,
    u."User" AS userid,
    substr(a."Code"::text, 1::numeric, 7::numeric) AS procedure,
    c."SiteName" AS site,
    ''::bpchar AS surface,
    ct."Description" AS description,
    ' '::bpchar AS status,
    ''::bpchar AS discipline,
    pt."Patient" AS patient,
    pt."Chart" AS chart,
    pt."Last" AS last,
    pt."First" AS first,
    pt."Middle" AS middle,
    to_datetime(ah."Date", ah."Time") AS auditdatetime,
    ah."User" AS audituser
   FROM ptcase c
     CROSS JOIN ptcasejt j
     CROSS JOIN casetype ct
     CROSS JOIN appoint a
     CROSS JOIN patient pt
     CROSS JOIN ptsurg s
     CROSS JOIN users u
     LEFT JOIN maxaudithisperappoint_view ah ON ah."Appointment" = a."Appointment"
  WHERE a."Appointment" = s."Appointment" AND s."ApprovalUser" = 0::numeric AND u."SurgeryNeedsApp" = 1::numeric AND a."Patient" = pt."Patient" AND c."Patient" = pt."Patient" AND c."PtCase" = j."PtCase" AND j."Type" = 0::numeric AND j."Id" = a."Appointment" AND c."CaseType" = ct."CaseType" AND sched_pkg.appointhasunapprovedwaste(s."Appointment", u."User") = 0::numeric AND sched_pkg.appointproviderhasunapproved(s."Appointment", u."User") = 0::numeric AND ((EXISTS ( SELECT 1
           FROM ptvital v,
            audithis ah_1,
            users u2
          WHERE v."Appointment" = a."Appointment" AND v."Audit" = ah_1."Audit" AND ah_1."User" = u2."User" AND u2."User" = u."User")) OR (EXISTS ( SELECT 1
           FROM ptsdrug d,
            ptsdose ds,
            audithis ah2,
            users u3
          WHERE d."Appointment" = s."Appointment" AND d."PtSDrug" = ds."PtSDrug" AND ds."Audit" = ah2."Audit" AND ah2."User" = u3."User" AND u3."User" = u."User")))
UNION
 SELECT 12 AS rtype,
    lo."LabOrder" AS id,
    li."Date" AS txdate,
    li."User" AS userid,
    lo."LabProcedure" AS procedure,
    ''::bpchar AS site,
    ''::bpchar AS surface,
    le."ProcedureDescription" AS description,
        CASE
            WHEN lo."Status" = 0::numeric THEN 'P'::text
            WHEN lo."Status" = 1::numeric THEN 'I'::text
            WHEN lo."Status" = 2::numeric THEN 'C'::text
            WHEN lo."Status" = 3::numeric THEN 'X'::text
            ELSE ''::text
        END AS status,
    lo."Discipline" AS discipline,
    lo."Patient" AS patient,
    pt."Chart" AS chart,
    pt."Last" AS last,
    pt."First" AS first,
    pt."Middle" AS middle,
    to_datetime(a."Date", a."Time") AS auditdatetime,
    a."User" AS audituser
   FROM laborder lo
     CROSS JOIN labitem li
     CROSS JOIN patient pt
     CROSS JOIN audithis a
     LEFT JOIN laboext le ON lo."LabOrder" = le."LabOrder"
     LEFT JOIN procedur p ON lo."LabProcedure" = p."Procedure"
  WHERE lo."LabOrder" = li."LabOrder" AND lo."Patient" = pt."Patient" AND lo."Deleted" = 0::numeric AND lo."IseLab" = 1::numeric AND li."Deleted" = 0::numeric AND li."ApprovalUser" = 0::numeric AND li."Audit" = a."Audit"
UNION
 SELECT 13 AS rtype,
    p."TxPlan" AS id,
    ah."Date" AS txdate,
    ah."User" AS userid,
    ''::bpchar AS procedure,
    ''::bpchar AS site,
    ''::bpchar AS surface,
    p."Description" AS description,
    ''::bpchar AS status,
    ''::bpchar AS discipline,
    p."Patient" AS patient,
    pt."Chart" AS chart,
    pt."Last" AS last,
    pt."First" AS first,
    pt."Middle" AS middle,
    to_datetime(ah."Date", ah."Time") AS auditdatetime,
    ah."User" AS audituser
   FROM txplan p,
    txpopt o,
    patient pt,
    audithis ah
  WHERE p."Patient" = pt."Patient" AND p."Deleted" = 0::numeric AND p."Inactive" = 0::numeric AND p."TxPlan" = o."TxPlan" AND o."Deleted" = 0::numeric AND NOT (EXISTS ( SELECT 1
           FROM txpopt
          WHERE txpopt."Deleted" = 0::numeric AND txpopt."InstructorApproved" = 1::numeric AND txpopt."NeedsConsultantAppr" = 0::numeric AND txpopt."TxPlan" = o."TxPlan")) AND (EXISTS ( SELECT 1
           FROM txptx
          WHERE txptx."TxPlan" = o."TxPlan" AND txptx."Deleted" = 0::numeric AND txptx."TxPTxType" = 0::numeric AND txptx."TxPOpt" = o."TxPOpt")) AND ah."Audit" = (( SELECT max(a."Audit") AS max
           FROM txpopt t2,
            audithis a
          WHERE t2."TxPlan" = p."TxPlan" AND t2."Audit" = a."Audit"))
;
CREATE OR REPLACE VIEW unapprovedsurgeryitems_view AS
 SELECT 0 AS rtype,
    0 AS id,
    to_date(NULL::character varying) AS txdate,
    0 AS userid,
    ' '::character(50) AS procedure,
    ' '::character(31) AS site,
    ' '::character(6) AS surface,
    ' '::character varying(80) AS description,
    ' '::character(6) AS status,
    ' '::character(15) AS discipline,
    0 AS patient,
    ' '::character(15) AS chart,
    ' '::character(31) AS last,
    ' '::character(31) AS first,
    ' '::character(31) AS middle,
    to_date(NULL::character varying) AS auditdatetime,
    0 AS audituser
   FROM dual
  WHERE 0 = 1
UNION
 SELECT 11 AS rtype,
    a."Appointment" AS id,
    a."Date" AS txdate,
    u."User" AS userid,
    substr(a."Code"::text, 1::numeric, 7::numeric) AS procedure,
    c."SiteName" AS site,
    ''::bpchar AS surface,
    ct."Description" AS description,
    ' '::bpchar AS status,
    ''::bpchar AS discipline,
    pt."Patient" AS patient,
    pt."Chart" AS chart,
    pt."Last" AS last,
    pt."First" AS first,
    pt."Middle" AS middle,
    to_datetime(ah."Date", ah."Time") AS auditdatetime,
    ah."User" AS audituser
   FROM ptcase c,
    ptcasejt j,
    casetype ct,
    appoint a,
    patient pt,
    ptsurg ps,
    ptsdrug pd,
    audithis ah,
    users u
  WHERE ps."Appointment" = a."Appointment" AND ps."WasteApprovalUser" <= 0::numeric AND ps."Appointment" = pd."Appointment" AND pd."Waste" > 1::numeric AND pd."Deleted" = 0::numeric AND a."Patient" = pt."Patient" AND c."Patient" = pt."Patient" AND c."PtCase" = j."PtCase" AND j."Type" = 0::numeric AND j."Id" = a."Appointment" AND c."CaseType" = ct."CaseType" AND pd."Audit" = (( SELECT max(a_1."Audit") AS max
           FROM audithis a_1,
            ptsdrug d
          WHERE d."Appointment" = ps."Appointment" AND d."Waste" > 1::numeric AND d."Deleted" = 0::numeric AND d."Audit" = a_1."Audit")) AND pd."Audit" = ah."Audit" AND u."User" = ah."User" AND (( SELECT count(1) AS count
           FROM ptsdrug
          WHERE ptsdrug."Appointment" = ps."Appointment" AND ptsdrug."Waste" > 0::numeric AND ptsdrug."Deleted" = 0::numeric AND ptsdrug."WasteAmount" > '-1'::integer::numeric AND ptsdrug."WasteDeleted" = 0::numeric)) > 0
UNION
 SELECT 10 AS rtype,
    a."Appointment" AS id,
    a."Date" AS txdate,
    u."User" AS userid,
    substr(a."Code"::text, 1::numeric, 7::numeric) AS procedure,
    c."SiteName" AS site,
    ''::bpchar AS surface,
    ct."Description" AS description,
    ' '::bpchar AS status,
    ''::bpchar AS discipline,
    pt."Patient" AS patient,
    pt."Chart" AS chart,
    pt."Last" AS last,
    pt."First" AS first,
    pt."Middle" AS middle,
    to_datetime(ah."Date", ah."Time") AS auditdatetime,
    ah."User" AS audituser
   FROM ptcase c
     CROSS JOIN ptcasejt j
     CROSS JOIN casetype ct
     CROSS JOIN appoint a
     CROSS JOIN users u
     CROSS JOIN patient pt
     CROSS JOIN ptsurg s
     LEFT JOIN maxaudithisperappoint_view ah ON ah."Appointment" = a."Appointment"
  WHERE a."Appointment" = s."Appointment" AND s."ApprovalUser" = 0::numeric AND ((EXISTS ( SELECT 1
           FROM ptvital v
          WHERE v."Appointment" = s."Appointment")) OR (EXISTS ( SELECT 1
           FROM ptsdrug d,
            ptsdose ds
          WHERE d."Appointment" = s."Appointment" AND d."PtSDrug" = ds."PtSDrug"))) AND a."Producer" = u."Producer" AND u."User" = ah."User" AND a."Patient" = pt."Patient" AND c."Patient" = pt."Patient" AND c."PtCase" = j."PtCase" AND j."Type" = 0::numeric AND j."Id" = a."Appointment" AND c."CaseType" = ct."CaseType"
UNION
 SELECT 10 AS rtype,
    a."Appointment" AS id,
    a."Date" AS txdate,
    u."User" AS userid,
    substr(a."Code"::text, 1::numeric, 7::numeric) AS procedure,
    c."SiteName" AS site,
    ''::bpchar AS surface,
    ct."Description" AS description,
    ' '::bpchar AS status,
    ''::bpchar AS discipline,
    pt."Patient" AS patient,
    pt."Chart" AS chart,
    pt."Last" AS last,
    pt."First" AS first,
    pt."Middle" AS middle,
    to_datetime(ah."Date", ah."Time") AS auditdatetime,
    ah."User" AS audituser
   FROM ptcase c
     CROSS JOIN ptcasejt j
     CROSS JOIN casetype ct
     CROSS JOIN appoint a
     CROSS JOIN patient pt
     CROSS JOIN ptsurg s
     CROSS JOIN users u
     LEFT JOIN maxaudithisperappoint_view ah ON ah."Appointment" = a."Appointment"
  WHERE a."Appointment" = s."Appointment" AND s."ApprovalUser" = 0::numeric AND u."User" = ah."User" AND a."Patient" = pt."Patient" AND c."Patient" = pt."Patient" AND c."PtCase" = j."PtCase" AND j."Type" = 0::numeric AND j."Id" = a."Appointment" AND c."CaseType" = ct."CaseType" AND ((EXISTS ( SELECT 1
           FROM ptvital v
          WHERE v."Appointment" = a."Appointment" AND v."Deleted" = 0::numeric)) OR (EXISTS ( SELECT 1
           FROM ptsdrug d,
            ptsdose ds
          WHERE d."Appointment" = s."Appointment" AND d."PtSDrug" = ds."PtSDrug" AND d."Deleted" = 0::numeric)))
;
CREATE OR REPLACE VIEW users2 AS
 SELECT "User" AS "UsersId",
    "MinSchHours",
    "Import",
    "MinContacts",
    "AddSteps",
    "ConsultantType",
    "IsManager",
    "RestrictedApproval",
    "Preferred",
    "Middle",
    "Sex",
    "Birth",
    "Address1",
    "Address2",
    "City",
    "Province",
    "Postal",
    "AddressOther",
    "HomeArea",
    "HomePhone",
    "AltArea",
    "AltPhone",
    "Email",
    "Note",
    "DeptCode",
    "DeptRoom",
    "DeptArea",
    "DeptPhone",
    "AddNotes",
    "EditNotes",
    "EditTxs",
    "RequireLabApp",
    "CanApproveLabs",
    "ApprovePlanTx",
    "ApproveCompTx",
    "ApproveExistingTx",
    "ExistingNeedsApp",
    "IsGroupManager",
    "Custom1",
    "Custom2",
    "Custom3",
    "Custom4",
    "Custom5",
    "Custom6",
    "Custom7",
    "Custom8",
    "Custom9",
    "Custom10",
    "ConditionNeedsApp",
    "ApproveConditionTx",
    "MobileId",
    "MobilePassword",
    "PerioNeedsApp",
    "ApprovePerio",
    "PerMeth",
    "ApproveOrthoV",
    "OrthoVNeedsApp",
    "DeleteTxs",
    "DrugsOnDemand",
    "RequireASAApproval",
    "SchClinic",
    "ApprovePrescript",
    "AutoLock",
    "DefaultBank",
    "Audit",
    "UseActiveDir",
    "ProblemsNeedApp",
    "ApproveProblems",
    "StartupMDI",
    "ApproveInvOrder",
    "ApproveNotes",
    "ApproveEHRForms",
    "ApproveStartChks",
    "AssignTxs",
    "ApproveNoTxConsent",
    "EditAppts",
    "CanAbortEvals",
    "CanEvaluate",
    "ApproveTxPlan",
    "ApproveDispLock",
    "ApproveUndefDrugs",
    "AutoLockErr",
    "PlanNeedsApp",
    "CompNeedsApp",
    "MsgRefreshRate",
    "NeedsTxPlanApp"
   FROM users
;
CREATE OR REPLACE VIEW v_instance AS
 SELECT 'EDB'::text AS instance_name,
    ( SELECT
                CASE pg_settings.setting
                    WHEN 'off'::text THEN 'STOPPED'::text
                    ELSE pg_settings.setting
                END AS archiver
           FROM pg_settings
          WHERE pg_settings.name = 'archive_mode'::text) AS archiver,
    inet_server_addr() AS host_name,
    version() AS version
   FROM dual
;
CREATE OR REPLACE VIEW v_session AS
 SELECT pid AS audsid,
    application_name AS program,
    usesysid AS ownerid,
    usename AS username,
    replace(usename::text, '_user'::text, ''::text) AS "schema#",
    usename AS osuser,
    NULL::text AS terminal,
    NULL::text AS machine
   FROM pg_stat_activity
;
CREATE OR REPLACE VIEW vacaset_view AS
 SELECT 0 AS rtype,
    v."Provider",
    v."VacaSet",
    TRIM(BOTH FROM v."Description") AS description,
    v."StartDate" AS startdate,
    v."EndDate" AS enddate,
    v."StartTime",
    v."EndTime",
    v."Monday",
    v."Tuesday",
    v."Wednesday",
    v."Thursday",
    v."Friday",
    v."Saturday",
    v."Sunday",
    v."Cycle",
    v."CycleStart",
    v."CycleType",
    v."CycleFrq",
    v."IsBreak",
    v."AvailableClinic",
    ( SELECT count(1) AS count
           FROM vacation
          WHERE vacation."VacaSet" = v."VacaSet" AND vacation."Deleted" = 0::numeric AND vacation."SetException" = 1::numeric) AS hasexcept
   FROM vacaset v
  WHERE v."Type" = 0::numeric AND v."Deleted" = 0::numeric
UNION
 SELECT 1 AS rtype,
    v."Provider",
    v."Id" AS "VacaSet",
    TRIM(BOTH FROM v."Description") AS description,
    v."StartDate" AS startdate,
    v."StartDate" AS enddate,
    v."StartTime",
    v."EndTime",
    0 AS "Monday",
    0 AS "Tuesday",
    0 AS "Wednesday",
    0 AS "Thursday",
    0 AS "Friday",
    0 AS "Saturday",
    0 AS "Sunday",
    0 AS "Cycle",
    to_date(NULL::character varying) AS "CycleStart",
    0 AS "CycleType",
    0 AS "CycleFrq",
    0 AS "IsBreak",
    0 AS "AvailableClinic",
    0 AS hasexcept
   FROM vacation v
  WHERE v."Type" = 0::numeric AND v."VacaSet" = 0::numeric AND v."Deleted" = 0::numeric
;
 
-- PACKAGE BODIES 
CREATE OR REPLACE PACKAGE BODY alloc_pkg IS



PROCEDURE createalloctxs_p(INOUT prefcursor cursor_pkg.weakcursor, IN pdepartment character, IN pfromdate timestamp without time zone, IN ptodate timestamp without time zone, IN pgroupby1 integer DEFAULT 0, IN pgroupby2 integer DEFAULT 0, IN pisdetailed integer DEFAULT 1, IN ppatient numeric DEFAULT 0, IN porigrecno numeric DEFAULT 0) IS



  cursor cOrigRecNo is

    select distinct gta1."OrigRecNo"

    from global_temp_alloc1 gta1

    where 1=1;



  cursor cOrigRecNo2 is

    select

      gta3.*,

      (select count(distinct gta3c."Department")

       from (select gta3a."Department" "Department"

             from global_temp_alloc3 gta3a

             where 1=1

             and gta3a."OrigRecNo" = gta3."OrigRecNo"

             union

             select gta3b."PreviousDepartment" "Department"

             from global_temp_alloc3 gta3b

             where 1=1

             and gta3b."OrigRecNo" = gta3."OrigRecNo") gta3c

       where 1=1)  "DeptCount",

      decode(gta3."HistoryType", 3, 0, nvl((select 1

                                            from (select

                                                    ah1."PayType",

                                                    ah1."PayId",

                                                    ah1."PayTreatment",

                                                    sum(ah1."Amount")

                                                  from

                                                    allocath ah1,

                                                    allocatelink al

                                                  where 1=1

                                                  and ah1."AllocateLink" = al."AllocateLink"

                                                  and ah1."ModifiedDate" < gta3."TxModifiedDate"

                                                  and ah1."TrxTreatment" = gta3."TrxTreatment"

                                                  and ah1."TrxId" = gta3."TrxId"

                                                  and ah1."TrxType" = gta3."TrxType"

                                                  and not exists (select 0

                                                                  from

                                                                    history h,

                                                                    adjust adj

                                                                  where 1=1

                                                                  and h."Code" = adj."Adjust"

                                                                  and adj."Transfer" = 1

                                                                  and h."History" = al."PmtHistoryId")

                                                  group by

                                                    ah1."PayType",

                                                    ah1."PayId",

                                                    ah1."PayTreatment"

                                                  having sum(ah1."Amount") <> 0)

                                            where 1=1

                                            and rownum = 1), 0)) "HasAllocation"

    from global_temp_alloc3 gta3

    where 1=1

    order by

      gta3."History",

      gta3."TxHistoryId",

      gta3."AllocatH";

      

  cursor cAllocatH (pTrxType allocath."TrxType"%type,

                    pTrxId allocath."TrxId"%type,

                    pTrxTreatment allocath."TrxTreatment"%type,

                    pModifiedDate date,

                    pOrigTrxType allocath."TrxType"%type,

                    pOrigTrxId allocath."TrxId"%type,

                    pOrigTrxTreatment allocath."TrxTreatment"%type) is

    with

    TmpAllocath1 as (

                     select

                       ah1."AllocatH",

                       ah1."PayType",

                       ah1."PayId",

                       ah1."PayTreatment",

                       ah1."Amount",

                       0 "MaxHistory"

                    from allocath ah1

                    where 1=1

                    and ah1."ModifiedDate" <= pModifiedDate

                    and ah1."TrxTreatment" = pTrxTreatment

                    and ah1."TrxId" = pTrxId

                    and ah1."TrxType" = pTrxType

                    and ah1."PayType" <> 7

                    union all

                    select

                       ah1b."AllocatH",

                       ah1b."PayType",

                       ah1b."PayId",

                       ah1b."PayTreatment",

                       ah1b."Amount",

                       0 "MaxHistory"

                    from allocath ah1b

                    where 1=1

                    and ah1b."ModifiedDate" <= pModifiedDate

                    and ah1b."TrxTreatment" = pOrigTrxTreatment

                    and ah1b."TrxId" = pOrigTrxId

                    and ah1b."TrxType" = pOrigTrxType

                    and ah1b."PayType" <> 7

                    union all

                    select

                       ah2."AllocatH",

                       ah2."PayType",

                       ah2."PayId",

                       ah2."PayTreatment",

                       ah2."Amount",

                       nvl((select max(h2."History")

                            from history h2

                            where 1=1

                            and h2."ModifiedDate" <= ah2."ModifiedDate"

                            and h2."Treatment" = ah2."PayTreatment"

                            and h2."Id" = ah2."PayId"

                            and h2."Type" = ah2."PayType"), 0) "MaxHistory"

                    from allocath ah2

                    where 1=1

                    and ah2."ModifiedDate" <= pModifiedDate

                    and ah2."TrxTreatment" = pTrxTreatment

                    and ah2."TrxId" = pTrxId

                    and ah2."TrxType" = pTrxType

                    and ah2."PayType" = 7

                    union all

                    select

                       ah2b."AllocatH",

                       ah2b."PayType",

                       ah2b."PayId",

                       ah2b."PayTreatment",

                       ah2b."Amount",

                       nvl((select max(h2b."History")

                            from history h2b

                            where 1=1

                            and h2b."ModifiedDate" <= ah2b."ModifiedDate"

                            and h2b."Treatment" = ah2b."PayTreatment"

                            and h2b."Id" = ah2b."PayId"

                            and h2b."Type" = ah2b."PayType"), 0) "MaxHistory"

                    from allocath ah2b

                    where 1=1

                    and ah2b."ModifiedDate" <= pModifiedDate

                    and ah2b."TrxTreatment" = pOrigTrxTreatment

                    and ah2b."TrxId" = pOrigTrxId

                    and ah2b."TrxType" = pOrigTrxType

                    and ah2b."PayType" = 7

                   ),

    TmpAllocath2 as (

                     select

                       tah1a."PayType",

                       tah1a."PayId",

                       tah1a."PayTreatment",

                       max(tah1a."AllocatH") "MaxAllocatH"

                     from TmpAllocath1 tah1a

                    where 1=1

                    and tah1a."PayType" <> 7

                    group by

                      tah1a."PayType",

                      tah1a."PayId",

                      tah1a."PayTreatment"

                    having sum(tah1a."Amount") <> 0

                    union all

                    select

                       tah1b."PayType",

                       tah1b."PayId",

                       tah1b."PayTreatment",

                       max(tah1b."AllocatH") "MaxAllocatH"

                     from

                       TmpAllocath1 tah1b,

                       history h1b,

                       adjust adj1b

                    where 1=1

                    and tah1b."MaxHistory" = h1b."History"

                    and h1b."Code" = adj1b."Adjust"

                    and adj1b."Transfer" <> 1

                    and tah1b."PayType" = 7

                    group by

                      tah1b."PayType",

                      tah1b."PayId",

                      tah1b."PayTreatment"

                    having sum(tah1b."Amount") <> 0

                   ),

    TmpAllocath3 as (

                     select

                       ah2."AllocatH",

                       ah2."PayType",

                       ah2."Amount",

                       ah2."AllocateLink",

                       nvl(al2."TxHistoryId", 0) "TxHistoryId",

                       nvl(al2."PmtHistoryId", 0) "PmtHistoryId"

                     from

                       allocatelink al2,

                       allocath ah2,

                       TmpAllocath2 tah2

                     where 1=1

                     and ah2."AllocateLink" = al2."AllocateLink" (+)

                     and ah2."AllocatH" = tah2."MaxAllocatH"

                    )

    select distinct tah3.*

    from TmpAllocath3 tah3

    where 1=1

    order by tah3."AllocatH";



  vDepartment dept."Department"%type := pDepartment;

  vFromDate date := trunc(pFromDate);

  vToDate date := (trunc(pToDate) + (86399/86400));                             -- one second before midnight

  vGroupBy1 global_temp_alloc1."GroupBy1"%type := nvl(pGroupBy1, 0);

  vGroupBy2 global_temp_alloc1."GroupBy2"%type := nvl(pGroupBy2, 0);

  vPatient patient."Patient"%type := nvl(pPatient, 0);

  vOrigRecNo history."OrigRecNo"%type := nvl(pOrigRecNo, 0);

  vNew global_temp_alloc3."HistoryTypeDescription"%type := 'New';

  vAllocate global_temp_alloc3."HistoryTypeDescription"%type := 'Allocate';

  vTransferIn global_temp_alloc3."HistoryTypeDescription"%type := 'Transfer In';

  vTransferOut global_temp_alloc3."HistoryTypeDescription"%type := 'Transfer Out';

  vDeptCount integer := 0;

  vAmount allocath."Amount"%type := 0;

  vCalculateDepartment integer := 0;

  

  -- variables for rebills

  vMaxHistory history."History"%type := 0;

  vOrigType history."Type"%type := 0;

  vOrigId history."Id"%type := 0;

  vOrigTreatment history."Treatment"%type := 0;

  

  vBatch ar_recon_saved_data_hdr."Batch"%type := 0;

  vSysdate date := sysdate;

  vExpiryDate date := trunc(sysdate);

  

  vStep integer := 0;

  

begin

  --

  -- reduce REDO/rollback segments used by GTTs (introduced in Oracle Database 12C Release 1 (12.1))

  --

  vStep := 10;

  

  begin

    execute immediate 'ALTER SESSION SET TEMP_UNDO_ENABLED = TRUE';

  exception

    when others then

      null;

  end;

  

  --

  -- clear staging tables

  --

  vStep := 20;

  

  execute immediate 'truncate table global_temp_alloc1';

  execute immediate 'truncate table global_temp_alloc2';

  execute immediate 'truncate table global_temp_alloc3';

  execute immediate 'truncate table global_temp_alloc4';



  --

  -- delete expired allocation type records from table AR_RECON_SAVED_DATA_HDR

  --

  vStep := 30;

  

  delete from ar_recon_saved_data_hdr

  where 1=1

  and "ReportType" = 1                                                          -- allocation type records

  and "ExpiryDate" < trunc(vSysdate);

  

  --

  -- delete records from table AR_RECON_SAVED_DATA_DTL where there is no equivalent records from table AR_RECON_SAVED_DATA_HDR

  --

  vStep := 40;

  

  delete from ar_recon_saved_data_dtl d

  where 1=1

  and not exists (select 1

                  from ar_recon_saved_data_hdr h

                  where 1=1

                  and h."Batch" = d."Batch");



  --

  -- check if allocations report using the same exact parameters were previously ran: if so, just update existing record.  if not, create a new record.

  --

  begin

    --

    -- check if data exists from table AR_RECON_SAVED_DATA_HDR

    --

    vStep := 50;

    

    select arh2."Batch"

    into vBatch

    from (

          select arh."Batch"

          from ar_recon_saved_data_hdr arh

          where 1=1

          and arh."ReportType" = 1                                                        -- allocation type records

          and arh."IncludeUnallocated" = 0

          and arh."GroupBy2" = vGroupBy2

          and arh."GroupBy1" = vGroupBy1

          and arh."ToDate" = vToDate

          and arh."FromDate" = vFromDate

          and arh."Department" = vDepartment

          order by arh."Batch" desc

         ) arh2

    where 1=1

    and rownum = 1;

    

    --

    -- update AR_RECON_SAVED_DATA_HDR with new information

    --

    vStep := 60;

    

    update ar_recon_saved_data_hdr

    set

      "ExpiryDate" = vExpiryDate,

      "LastRunDate" = vSysdate,

      "IsDetailed" = pIsDetailed,

      "StartDateTime" = vSysdate,

      "EndDateTime" = to_date(null)

    where 1=1

    and "ReportType" = 1                                                    -- allocation type records

    and "Batch" = vBatch;



  exception

    when no_data_found then

      --

      -- get new batch ID

      --

      vStep := 70;

  

      select ar_recon_saved_data_hdr_seq.nextval

      into vBatch

      from dual;



      --

      -- insert into AR_RECON_SAVED_DATA_HDR

      --

      vStep := 80;

    

      insert into ar_recon_saved_data_hdr

      select

        vBatch "Batch",

        vExpiryDate "ExpiryDate",

        vSysdate "FirstRunDate",

        vSysdate "LastRunDate",

        vDepartment "Department",

        vFromDate "FromDate",

        vToDate "ToDate",

        vGroupBy1 "GroupBy1",

        ar_dept_pkg.ar_get_group_by_desc_f (vGroupBy1) "GroupBy1Description",

        vGroupBy2 "GroupBy2",

        ar_dept_pkg.ar_get_group_by_desc_f (vGroupBy2) "GroupBy2Description",

        pIsDetailed "IsDetailed",

        0 "IncludeUnallocated",

        vPatient "Patient",

        vOrigRecNo "OrigRecNo",

        0 "BeginningBalance",

        0 "PeriodBalance",

        0 "EndingBalance",

        1 "ReportType",                                                             -- allocation type records

        vSysdate "StartDateTime",

        to_date(null) "EndDateTime"

      from dual

      where 1=1;

      

  end;



  --

  -- populate staging table #1 with the OrigRecNos of the allocation records for the period

  --

  if ((vPatient = 0) and (vOrigRecNo = 0)) then

    --

    -- populate staging table #1 with the OrigRecNos of the allocation records for the period (for all; not for a specific Patient or specific OrigRecNo)

    --

    vStep := 90;

  

    insert into global_temp_alloc1

    select

      ah."AllocatH",

      ah."PayType",

      ah."TrxType",

      ah."TrxId",

      ah."TrxTreatment",

      ah."Amount",

      ah."AllocateLink",

      al."TxHistoryId",

      al."PmtHistoryId",

      htx."OrigRecNo",

      htx."History",

      htx."HistoryType",

      htx."Patient",

      htx."ModifiedDate" "TxModifiedDate",

      htx."Payed",

      htx."InsPayed",

      htx."PtAdj",

      htx."InsAdj",

      htx."InsTransfer",

      htx."Discipline",

      htx."Procedure",

      htx."Practice",

      htx."ClaimDoctor",

      htx."Location",

      htx."EntryUser",

      htx."AppUser",

      htx."Custom1",

      htx."Custom2",

      htx."Producer",

      nvl(prod."TypeCode", ' ') "TypeCode",

      nvl(prod."PGroup", ' ') "PGroup",

      nvl(prod."Year", 0) "Year",

      pat."CustomCode1",

      pat."CustomCode2",

      pat."CustomCode3",

      pat."CustomCode4",

      pat."CustomCode5",

      pat."CustomCode6",

      pat."CustomCode7",

      pat."CustomCode8",

      pat."CustomCode9",

      pat."CustomCode10",

      ' ' "Department",

      ' ' "HistoryTypeDescription",

      vGroupBy1 "GroupBy1",

      vGroupBy2 "GroupBy2"

    from

      history htx,

      allocath ah,

      allocatelink al,

      patient pat,

      producer prod

    where 1=1

    and htx."Producer" = prod."Producer" (+)

    and ah."AllocateLink" = al."AllocateLink"

    and al."TxHistoryId" = htx."History"

    and htx."Patient" = pat."Patient"

    and ah."Amount" <> 0

    and ah."ModifiedDate" >= vFromDate

    and ah."ModifiedDate" <= vToDate

    union

    --

    -- populate staging table #1 with the OrigRecNos of the allocation records even if there are no allocations for the period but there are history changes for the period

    -- (for all; not for a specific Patient or specific OrigRecNo)

    --

    select

      ah2."AllocatH",

      ah2."PayType",

      ah2."TrxType",

      ah2."TrxId",

      ah2."TrxTreatment",

      ah2."Amount",

      ah2."AllocateLink",

      al2."TxHistoryId",

      al2."PmtHistoryId",

      htx2."OrigRecNo",

      htx2."History",

      htx2."HistoryType",

      htx2."Patient",

      htx2."ModifiedDate" "TxModifiedDate",

      htx2."Payed",

      htx2."InsPayed",

      htx2."PtAdj",

      htx2."InsAdj",

      htx2."InsTransfer",

      htx2."Discipline",

      htx2."Procedure",

      htx2."Practice",

      htx2."ClaimDoctor",

      htx2."Location",

      htx2."EntryUser",

      htx2."AppUser",

      htx2."Custom1",

      htx2."Custom2",

      htx2."Producer",

      nvl(prod2."TypeCode", ' ') "TypeCode",

      nvl(prod2."PGroup", ' ') "PGroup",

      nvl(prod2."Year", 0) "Year",

      pat2."CustomCode1",

      pat2."CustomCode2",

      pat2."CustomCode3",

      pat2."CustomCode4",

      pat2."CustomCode5",

      pat2."CustomCode6",

      pat2."CustomCode7",

      pat2."CustomCode8",

      pat2."CustomCode9",

      pat2."CustomCode10",

      ' ' "Department",

      ' ' "HistoryTypeDescription",

      vGroupBy1 "GroupBy1",

      vGroupBy2 "GroupBy2"

    from

      history htx2,

      allocath ah2,

      allocatelink al2,

      patient pat2,

      producer prod2

    where 1=1

    and htx2."Producer" = prod2."Producer" (+)

    and ah2."AllocateLink" = al2."AllocateLink"

    and al2."TxHistoryId" = htx2."History"

    and htx2."Patient" = pat2."Patient"

    and ah2."Amount" <> 0

    and exists (select null

                from history h2

                where 1=1

                and h2."HistoryType" = 2

                and h2."ModifiedDate" >= vFromDate

                and h2."ModifiedDate" <= vToDate

                and h2."OrigRecNo" = htx2."OrigRecNo");



  else

    --

    -- populate staging table #1 with the OrigRecNos of the allocation records for the period (for a specific Patient or specific OrigRecNo)

    --

    vStep := 100;

  

    insert into global_temp_alloc1

    select

      ah."AllocatH",

      ah."PayType",

      ah."TrxType",

      ah."TrxId",

      ah."TrxTreatment",

      ah."Amount",

      ah."AllocateLink",

      al."TxHistoryId",

      al."PmtHistoryId",

      htx."OrigRecNo",

      htx."History",

      htx."HistoryType",

      htx."Patient",

      htx."ModifiedDate" "TxModifiedDate",

      htx."Payed",

      htx."InsPayed",

      htx."PtAdj",

      htx."InsAdj",

      htx."InsTransfer",

      htx."Discipline",

      htx."Procedure",

      htx."Practice",

      htx."ClaimDoctor",

      htx."Location",

      htx."EntryUser",

      htx."AppUser",

      htx."Custom1",

      htx."Custom2",

      htx."Producer",

      nvl(prod."TypeCode", ' ') "TypeCode",

      nvl(prod."PGroup", ' ') "PGroup",

      nvl(prod."Year", 0) "Year",

      pat."CustomCode1",

      pat."CustomCode2",

      pat."CustomCode3",

      pat."CustomCode4",

      pat."CustomCode5",

      pat."CustomCode6",

      pat."CustomCode7",

      pat."CustomCode8",

      pat."CustomCode9",

      pat."CustomCode10",

      ' ' "Department",

      ' ' "HistoryTypeDescription",

      vGroupBy1 "GroupBy1",

      vGroupBy2 "GroupBy2"

    from

      history htx,

      allocath ah,

      allocatelink al,

      patient pat,

      producer prod

    where 1=1

    and htx."Producer" = prod."Producer" (+)

    and ah."AllocateLink" = al."AllocateLink"

    and al."TxHistoryId" = htx."History"

    and htx."Patient" = pat."Patient"

    and ah."Amount" <> 0

    and ah."ModifiedDate" >= vFromDate

    and ah."ModifiedDate" <= vToDate

    and htx."Patient" = decode(vPatient, 0, htx."Patient", vPatient)

    and htx."OrigRecNo" = decode(vOrigRecNo, 0, htx."OrigRecNo", vOrigRecNo)

    union

    --

    -- populate staging table #1 with the OrigRecNos of the allocation records even if there are no allocations for the period but there are history changes for the period

    --  (for a specific Patient or specific OrigRecNo)

    --

    select

      ah2."AllocatH",

      ah2."PayType",

      ah2."TrxType",

      ah2."TrxId",

      ah2."TrxTreatment",

      ah2."Amount",

      ah2."AllocateLink",

      al2."TxHistoryId",

      al2."PmtHistoryId",

      htx2."OrigRecNo",

      htx2."History",

      htx2."HistoryType",

      htx2."Patient",

      htx2."ModifiedDate" "TxModifiedDate",

      htx2."Payed",

      htx2."InsPayed",

      htx2."PtAdj",

      htx2."InsAdj",

      htx2."InsTransfer",

      htx2."Discipline",

      htx2."Procedure",

      htx2."Practice",

      htx2."ClaimDoctor",

      htx2."Location",

      htx2."EntryUser",

      htx2."AppUser",

      htx2."Custom1",

      htx2."Custom2",

      htx2."Producer",

      nvl(prod2."TypeCode", ' ') "TypeCode",

      nvl(prod2."PGroup", ' ') "PGroup",

      nvl(prod2."Year", 0) "Year",

      pat2."CustomCode1",

      pat2."CustomCode2",

      pat2."CustomCode3",

      pat2."CustomCode4",

      pat2."CustomCode5",

      pat2."CustomCode6",

      pat2."CustomCode7",

      pat2."CustomCode8",

      pat2."CustomCode9",

      pat2."CustomCode10",

      ' ' "Department",

      ' ' "HistoryTypeDescription",

      vGroupBy1 "GroupBy1",

      vGroupBy2 "GroupBy2"

    from

      history htx2,

      allocath ah2,

      allocatelink al2,

      patient pat2,

      producer prod2

    where 1=1

    and htx2."Producer" = prod2."Producer" (+)

    and ah2."AllocateLink" = al2."AllocateLink"

    and al2."TxHistoryId" = htx2."History"

    and htx2."Patient" = pat2."Patient"

    and ah2."Amount" <> 0

    and htx2."Patient" = decode(vPatient, 0, htx2."Patient", vPatient)

    and htx2."OrigRecNo" = decode(vOrigRecNo, 0, htx2."OrigRecNo", vOrigRecNo)

    and exists (select null

                from history h2

                where 1=1

                and h2."HistoryType" = 2

                and h2."ModifiedDate" >= vFromDate

                and h2."ModifiedDate" <= vToDate

                and h2."OrigRecNo" = htx2."OrigRecNo");

    

  end if;



  --

  -- determine if department needs to be calculated (may slow down processing time) or just use whatever department is passed to the procedure (can reduce processing time)

  --

  begin

    --

    -- check if department has corresponding department definition

    --

    vStep := 110;

  

    select 1

    into vCalculateDepartment

    from dept d

    where 1=1

    and exists (select 1

                from deptdef dd

                where 1=1

                and dd."Department" = d."Department")

    and d."Department" = vDepartment;

    

  exception

    when no_data_found then

      --

      -- use whatever department is passed to the procedure

      --

      vStep := 120;

      

      vCalculateDepartment := 0;



  end;

  

  --

  -- do not process insurance transfers and deleted records

  --

  vStep := 130;

  

  delete from global_temp_alloc1 gta1

  where 1=1

  and ((gta1."HistoryType" = 4)

       or (gta1."PayType" = 7

           and exists (select 0

                       from

                         history h,

                         adjust adj

                       where 1=1

                       and h."Code" = adj."Adjust"

                       and adj."Transfer" = 1

                       and h."History" = gta1."PmtHistoryId")));

  

  --

  -- process each OrigRecNo

  --

  vStep := 140;

  

  for pOrigRecNo in cOrigRecNo loop

  

    if (vCalculateDepartment = 1) then

      --

      -- populate staging table #2 with all records for the current OrigRecNo (calculate department)

      --

      vStep := 150;



      insert into global_temp_alloc2

      select *

      from (

            with

            TmpGTA1 as (

                        --

                        -- all records on or before the reporting period end date for the current OrigRecNo

                        --

                        select

                          gta1."AllocatH",

                          gta1."PayType",

                          gta1."TrxType",

                          gta1."TrxId",

                          gta1."TrxTreatment",

                          gta1."Amount",

                          gta1."AllocateLink",

                          gta1."TxHistoryId",

                          gta1."PmtHistoryId",  

                          gta1."OrigRecNo",

                          htx1."History",

                          htx1."HistoryType",

                          htx1."Patient",

                          htx1."ModifiedDate" "TxModifiedDate",

                          htx1."Payed",

                          htx1."InsPayed",

                          htx1."PtAdj",

                          htx1."InsAdj",

                          htx1."InsTransfer",

                          htx1."Discipline",

                          htx1."Procedure",

                          htx1."Practice",

                          htx1."ClaimDoctor",

                          htx1."Location",

                          htx1."EntryUser",

                          htx1."AppUser",

                          htx1."Custom1",

                          htx1."Custom2",

                          htx1."Producer",

                          nvl(prod1."TypeCode", ' ') "TypeCode",

                          nvl(prod1."PGroup", ' ') "PGroup",

                          nvl(prod1."Year", 0) "Year",

                          pat1."CustomCode1",

                          pat1."CustomCode2",

                          pat1."CustomCode3",

                          pat1."CustomCode4",

                          pat1."CustomCode5",

                          pat1."CustomCode6",

                          pat1."CustomCode7",

                          pat1."CustomCode8",

                          pat1."CustomCode9",

                          pat1."CustomCode10",

                          ar_dept_pkg.ar_get_dept_f(vDepartment,

                                                    htx1."History",

                                                    htx1."Producer",

                                                    htx1."Patient") "Department",

                          gta1."HistoryTypeDescription",

                          gta1."GroupBy1",

                          gta1."GroupBy2"

                        from

                          history htx1,

                          global_temp_alloc1 gta1,

                          producer prod1,

                          patient pat1

                        where 1=1

                        and htx1."OrigRecNo" = gta1."OrigRecNo"

                        and htx1."Patient" = pat1."Patient"

                        and htx1."Producer" = prod1."Producer" (+)

                        and htx1."ModifiedDate" <= vToDate

                        and htx1."OrigRecNo" = pOrigRecNo."OrigRecNo"

                       ),

            TmpGTA1B as (

                         select distinct

                           gta1b."AllocatH",

                           gta1b."PayType",

                           gta1b."TrxType",

                           gta1b."TrxId",

                           gta1b."TrxTreatment",

                           gta1b."Amount",

                           gta1b."AllocateLink",

                           gta1b."TxHistoryId",

                           gta1b."PmtHistoryId",

                           tgta1."OrigRecNo",

                           tgta1."History",

                           tgta1."HistoryType",

                           tgta1."Patient",

                           tgta1."TxModifiedDate",

                           tgta1."Payed",

                           tgta1."InsPayed",

                           tgta1."PtAdj",

                           tgta1."InsAdj",

                           tgta1."InsTransfer",

                           tgta1."Discipline",

                           tgta1."Procedure",

                           tgta1."Practice",

                           tgta1."ClaimDoctor",

                           tgta1."Location",

                           tgta1."EntryUser",

                           tgta1."AppUser",

                           tgta1."Custom1",

                           tgta1."Custom2",

                           tgta1."Producer",

                           tgta1."TypeCode",

                           tgta1."PGroup",

                           tgta1."Year",

                           tgta1."CustomCode1",

                           tgta1."CustomCode2",

                           tgta1."CustomCode3",

                           tgta1."CustomCode4",

                           tgta1."CustomCode5",

                           tgta1."CustomCode6",

                           tgta1."CustomCode7",

                           tgta1."CustomCode8",

                           tgta1."CustomCode9",

                           tgta1."CustomCode10",

                           tgta1."Department",

                           tgta1."HistoryTypeDescription",

                           tgta1."GroupBy1",

                           tgta1."GroupBy2"

                         from

                           TmpGTA1 tgta1,

                           global_temp_alloc1 gta1b

                         where 1=1

                         and tgta1."History" = gta1b."History" (+)

                         and tgta1."OrigRecNo" = gta1b."OrigRecNo" (+)

                        )

            select

              nvl(nvl(tgta1b."AllocatH", lag(tgta1b."AllocatH") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "AllocatH",

              nvl(nvl(tgta1b."PayType", lag(tgta1b."PayType") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "PayType",

              nvl(nvl(tgta1b."TrxType", lag(tgta1b."TrxType") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "TrxType",

              nvl(nvl(tgta1b."TrxId", lag(tgta1b."TrxId") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "TrxId",

              nvl(nvl(tgta1b."TrxTreatment", lag(tgta1b."TrxTreatment") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "TrxTreatment",

              nvl(nvl(tgta1b."Amount", lag(tgta1b."Amount") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "Amount",

              nvl(nvl(tgta1b."AllocateLink", lag(tgta1b."AllocateLink") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "AllocateLink",

              nvl(nvl(tgta1b."TxHistoryId", lag(tgta1b."TxHistoryId") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "TxHistoryId",

              nvl(nvl(tgta1b."PmtHistoryId", lag(tgta1b."PmtHistoryId") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "PmtHistoryId",

              tgta1b."OrigRecNo",

              tgta1b."History",

              tgta1b."HistoryType",

              tgta1b."Patient",

              tgta1b."TxModifiedDate",

              tgta1b."Payed",

              tgta1b."InsPayed",

              tgta1b."PtAdj",

              tgta1b."InsAdj",

              tgta1b."InsTransfer",

              tgta1b."Discipline",

              tgta1b."Procedure",

              tgta1b."Practice",

              tgta1b."ClaimDoctor",

              tgta1b."Location",

              tgta1b."EntryUser",

              tgta1b."AppUser",

              tgta1b."Custom1",

              tgta1b."Custom2",

              tgta1b."Producer",

              tgta1b."TypeCode",

              tgta1b."PGroup",

              tgta1b."Year",

              tgta1b."CustomCode1",

              tgta1b."CustomCode2",

              tgta1b."CustomCode3",

              tgta1b."CustomCode4",

              tgta1b."CustomCode5",

              tgta1b."CustomCode6",

              tgta1b."CustomCode7",

              tgta1b."CustomCode8",

              tgta1b."CustomCode9",

              tgta1b."CustomCode10",

              tgta1b."Department",

              tgta1b."HistoryTypeDescription",

              tgta1b."GroupBy1",

              tgta1b."GroupBy2"

            from TmpGTA1B tgta1b

            where 1=1

           )

      where 1=1;



    else

      --

      -- populate staging table #2 with all records for the current OrigRecNo (use whatever department is passed to the procedure)

      --

      vStep := 160;



      insert into global_temp_alloc2

      select *

      from (

            with

            TmpGTA1 as (

                        --

                        -- all records on or before the reporting period end date for the current OrigRecNo

                        --

                        select

                          gta1."AllocatH",

                          gta1."PayType",

                          gta1."TrxType",

                          gta1."TrxId",

                          gta1."TrxTreatment",

                          gta1."Amount",

                          gta1."AllocateLink",

                          gta1."TxHistoryId",

                          gta1."PmtHistoryId", 

                          gta1."OrigRecNo",

                          htx1."History",

                          htx1."HistoryType",

                          htx1."Patient",

                          htx1."ModifiedDate" "TxModifiedDate",

                          htx1."Payed",

                          htx1."InsPayed",

                          htx1."PtAdj",

                          htx1."InsAdj",

                          htx1."InsTransfer",

                          htx1."Discipline",

                          htx1."Procedure",

                          htx1."Practice",

                          htx1."ClaimDoctor",

                          htx1."Location",

                          htx1."EntryUser",

                          htx1."AppUser",

                          htx1."Custom1",

                          htx1."Custom2",

                          htx1."Producer",

                          nvl(prod1."TypeCode", ' ') "TypeCode",

                          nvl(prod1."PGroup", ' ') "PGroup",

                          nvl(prod1."Year", 0) "Year",

                          pat1."CustomCode1",

                          pat1."CustomCode2",

                          pat1."CustomCode3",

                          pat1."CustomCode4",

                          pat1."CustomCode5",

                          pat1."CustomCode6",

                          pat1."CustomCode7",

                          pat1."CustomCode8",

                          pat1."CustomCode9",

                          pat1."CustomCode10",

                          vDepartment "Department",

                          gta1."HistoryTypeDescription",

                          gta1."GroupBy1",

                          gta1."GroupBy2"

                        from

                          history htx1,

                          global_temp_alloc1 gta1,

                          producer prod1,

                          patient pat1

                        where 1=1

                        and htx1."OrigRecNo" = gta1."OrigRecNo"

                        and htx1."Patient" = pat1."Patient"

                        and htx1."Producer" = prod1."Producer" (+)

                        and htx1."ModifiedDate" <= vToDate

                        and htx1."OrigRecNo" = pOrigRecNo."OrigRecNo"

                       ),

            TmpGTA1B as (

                         select distinct

                           gta1b."AllocatH",

                           gta1b."PayType",

                           gta1b."TrxType",

                           gta1b."TrxId",

                           gta1b."TrxTreatment",

                           gta1b."Amount",

                           gta1b."AllocateLink",

                           gta1b."TxHistoryId",

                           gta1b."PmtHistoryId",

                           tgta1."OrigRecNo",

                           tgta1."History",

                           tgta1."HistoryType",

                           tgta1."Patient",

                           tgta1."TxModifiedDate",

                           tgta1."Payed",

                           tgta1."InsPayed",

                           tgta1."PtAdj",

                           tgta1."InsAdj",

                           tgta1."InsTransfer",

                           tgta1."Discipline",

                           tgta1."Procedure",

                           tgta1."Practice",

                           tgta1."ClaimDoctor",

                           tgta1."Location",

                           tgta1."EntryUser",

                           tgta1."AppUser",

                           tgta1."Custom1",

                           tgta1."Custom2",

                           tgta1."Producer",

                           tgta1."TypeCode",

                           tgta1."PGroup",

                           tgta1."Year",

                           tgta1."CustomCode1",

                           tgta1."CustomCode2",

                           tgta1."CustomCode3",

                           tgta1."CustomCode4",

                           tgta1."CustomCode5",

                           tgta1."CustomCode6",

                           tgta1."CustomCode7",

                           tgta1."CustomCode8",

                           tgta1."CustomCode9",

                           tgta1."CustomCode10",

                           tgta1."Department",

                           tgta1."HistoryTypeDescription",

                           tgta1."GroupBy1",

                           tgta1."GroupBy2"

                         from

                           TmpGTA1 tgta1,

                           global_temp_alloc1 gta1b

                         where 1=1

                         and tgta1."History" = gta1b."History" (+)

                         and tgta1."OrigRecNo" = gta1b."OrigRecNo" (+)

                        )

            select

              nvl(nvl(tgta1b."AllocatH", lag(tgta1b."AllocatH") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "AllocatH",

              nvl(nvl(tgta1b."PayType", lag(tgta1b."PayType") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "PayType",

              nvl(nvl(tgta1b."TrxType", lag(tgta1b."TrxType") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "TrxType",

              nvl(nvl(tgta1b."TrxId", lag(tgta1b."TrxId") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "TrxId",

              nvl(nvl(tgta1b."TrxTreatment", lag(tgta1b."TrxTreatment") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "TrxTreatment",

              nvl(nvl(tgta1b."Amount", lag(tgta1b."Amount") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "Amount",

              nvl(nvl(tgta1b."AllocateLink", lag(tgta1b."AllocateLink") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "AllocateLink",

              nvl(nvl(tgta1b."TxHistoryId", lag(tgta1b."TxHistoryId") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "TxHistoryId",

              nvl(nvl(tgta1b."PmtHistoryId", lag(tgta1b."PmtHistoryId") over (partition by tgta1b."OrigRecNo" order by tgta1b."History")), 0) "PmtHistoryId",

              tgta1b."OrigRecNo",

              tgta1b."History",

              tgta1b."HistoryType",

              tgta1b."Patient",

              tgta1b."TxModifiedDate",

              tgta1b."Payed",

              tgta1b."InsPayed",

              tgta1b."PtAdj",

              tgta1b."InsAdj",

              tgta1b."InsTransfer",

              tgta1b."Discipline",

              tgta1b."Procedure",

              tgta1b."Practice",

              tgta1b."ClaimDoctor",

              tgta1b."Location",

              tgta1b."EntryUser",

              tgta1b."AppUser",

              tgta1b."Custom1",

              tgta1b."Custom2",

              tgta1b."Producer",

              tgta1b."TypeCode",

              tgta1b."PGroup",

              tgta1b."Year",

              tgta1b."CustomCode1",

              tgta1b."CustomCode2",

              tgta1b."CustomCode3",

              tgta1b."CustomCode4",

              tgta1b."CustomCode5",

              tgta1b."CustomCode6",

              tgta1b."CustomCode7",

              tgta1b."CustomCode8",

              tgta1b."CustomCode9",

              tgta1b."CustomCode10",

              tgta1b."Department",

              tgta1b."HistoryTypeDescription",

              tgta1b."GroupBy1",

              tgta1b."GroupBy2"

            from TmpGTA1B tgta1b

            where 1=1

           )

      where 1=1;

      

    end if;



    --

    -- delete records that does not have any allocations (does not need to be reported)

    --

    vStep := 170;



    delete from global_temp_alloc2 gta2

    where 1=1

    and gta2."HistoryType" in (2, 5)

    and ((gta2."PayType" = 3 and gta2."Payed" = 0)

         or (gta2."PayType" = 4 and gta2."InsPayed" = 0)

         or (gta2."PayType" = 6 and gta2."PtAdj" = 0)

         or (gta2."PayType" = 7 and gta2."InsAdj" = 0))

    and not exists (select

                      ah1."PayType",

                      ah1."PayId",

                      ah1."PayTreatment",

                      sum(ah1."Amount")

                    from

                      allocath ah1,

                      allocatelink al

                    where 1=1

                    and ah1."AllocateLink" = al."AllocateLink"

                    and ah1."ModifiedDate" < gta2."TxModifiedDate"

                    and ah1."TrxTreatment" = gta2."TrxTreatment"

                    and ah1."TrxId" = gta2."TrxId"

                    and ah1."TrxType" = gta2."TrxType"

                    and not exists (select 0

                                    from

                                      history h,

                                      adjust adj

                                    where 1=1

                                    and h."Code" = adj."Adjust"

                                    and adj."Transfer" = 1

                                    and h."History" = al."PmtHistoryId")

                    group by

                      ah1."PayType",

                      ah1."PayId",

                      ah1."PayTreatment"

                    having sum(ah1."Amount") <> 0);



    --

    -- populate 3rd temporary table with group by changes

    --

    vStep := 180;



    insert into global_temp_alloc3

    select

      gta2.*,

      nvl((lag(gta2."History") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."History") "PreviousHistory",

      nvl((lag(gta2."Discipline") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."Discipline") "PreviousDiscipline",

      nvl((lag(gta2."Procedure") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."Procedure") "PreviousProcedure",

      nvl((lag(gta2."Practice") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."Practice") "PreviousPractice",

      nvl((lag(gta2."ClaimDoctor") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."ClaimDoctor") "PreviousClaimDoctor",

      nvl((lag(gta2."Location") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."Location") "PreviousLocation",

      nvl((lag(gta2."EntryUser") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."EntryUser") "PreviousEntryUser",

      nvl((lag(gta2."AppUser") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."AppUser") "PreviousAppUser",

      nvl((lag(gta2."Custom1") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."Custom1") "PreviousCustom1",

      nvl((lag(gta2."Custom2") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."Custom2") "PreviousCustom2",

      nvl((lag(gta2."Producer") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."Producer") "PreviousProducer",

      nvl((lag(gta2."TypeCode") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."TypeCode") "PreviousTypeCode",

      nvl((lag(gta2."PGroup") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."PGroup") "PreviousPGroup",

      nvl((lag(gta2."Year") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."Year") "PreviousYear",

      nvl((lag(gta2."CustomCode1") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."CustomCode1") "PreviousCustomCode1",

      nvl((lag(gta2."CustomCode2") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."CustomCode2") "PreviousCustomCode2",

      nvl((lag(gta2."CustomCode3") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."CustomCode3") "PreviousCustomCode3",

      nvl((lag(gta2."CustomCode4") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."CustomCode4") "PreviousCustomCode4",

      nvl((lag(gta2."CustomCode5") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."CustomCode5") "PreviousCustomCode5",

      nvl((lag(gta2."CustomCode6") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."CustomCode6") "PreviousCustomCode6",

      nvl((lag(gta2."CustomCode7") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."CustomCode7") "PreviousCustomCode7",

      nvl((lag(gta2."CustomCode8") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."CustomCode8") "PreviousCustomCode8",

      nvl((lag(gta2."CustomCode9") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."CustomCode9") "PreviousCustomCode9",

      nvl((lag(gta2."CustomCode10") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."CustomCode10") "PreviousCustomCode10",

      nvl((lag(gta2."Department") over (partition by gta2."OrigRecNo" order by gta2."History", gta2."AllocatH")), gta2."Department") "PreviousDepartment",

      ' ' "GroupBy1Value",

      ' ' "GroupBy2Value",

      ' ' "PreviousGroupBy1Value",

      ' ' "PreviousGroupBy2Value"

    from global_temp_alloc2 gta2

    where 1=1

    order by

      gta2."History",

      gta2."AllocatH";



    --

    -- fix previous values (if there are multiple allocations during a modification or a rebill)

    --

    vStep := 190;

    

    update global_temp_alloc3 gta3

    set

      (gta3."PreviousHistory",

       gta3."PreviousDiscipline",

       gta3."PreviousProcedure",

       gta3."PreviousPractice",

       gta3."PreviousClaimDoctor",

       gta3."PreviousLocation",

       gta3."PreviousEntryUser",

       gta3."PreviousAppUser",

       gta3."PreviousCustom1",

       gta3."PreviousCustom2",

       gta3."PreviousProducer",

       gta3."PreviousTypeCode",

       gta3."PreviousPGroup",

       gta3."PreviousYear",

       gta3."PreviousCustomCode1",

       gta3."PreviousCustomCode2",

       gta3."PreviousCustomCode3",

       gta3."PreviousCustomCode4",

       gta3."PreviousCustomCode5",

       gta3."PreviousCustomCode6",

       gta3."PreviousCustomCode7",

       gta3."PreviousCustomCode8",

       gta3."PreviousCustomCode9",

       gta3."PreviousCustomCode10",

       gta3."PreviousDepartment") = (select

                                       gta3b."PreviousHistory",

                                       gta3b."PreviousDiscipline",

                                       gta3b."PreviousProcedure",

                                       gta3b."PreviousPractice",

                                       gta3b."PreviousClaimDoctor",

                                       gta3b."PreviousLocation",

                                       gta3b."PreviousEntryUser",

                                       gta3b."PreviousAppUser",

                                       gta3b."PreviousCustom1",

                                       gta3b."PreviousCustom2",

                                       gta3b."PreviousProducer",

                                       gta3b."PreviousTypeCode",

                                       gta3b."PreviousPGroup",

                                       gta3b."PreviousYear",

                                       gta3b."PreviousCustomCode1",

                                       gta3b."PreviousCustomCode2",

                                       gta3b."PreviousCustomCode3",

                                       gta3b."PreviousCustomCode4",

                                       gta3b."PreviousCustomCode5",

                                       gta3b."PreviousCustomCode6",

                                       gta3b."PreviousCustomCode7",

                                       gta3b."PreviousCustomCode8",

                                       gta3b."PreviousCustomCode9",

                                       gta3b."PreviousCustomCode10",

                                       gta3b."PreviousDepartment"

                                     from (select

                                             gta3c."History",

                                             gta3c."PreviousHistory",

                                             gta3c."PreviousDiscipline",

                                             gta3c."PreviousProcedure",

                                             gta3c."PreviousPractice",

                                             gta3c."PreviousClaimDoctor",

                                             gta3c."PreviousLocation",

                                             gta3c."PreviousEntryUser",

                                             gta3c."PreviousAppUser",

                                             gta3c."PreviousCustom1",

                                             gta3c."PreviousCustom2",

                                             gta3c."PreviousProducer",

                                             gta3c."PreviousTypeCode",

                                             gta3c."PreviousPGroup",

                                             gta3c."PreviousYear",

                                             gta3c."PreviousCustomCode1",

                                             gta3c."PreviousCustomCode2",

                                             gta3c."PreviousCustomCode3",

                                             gta3c."PreviousCustomCode4",

                                             gta3c."PreviousCustomCode5",

                                             gta3c."PreviousCustomCode6",

                                             gta3c."PreviousCustomCode7",

                                             gta3c."PreviousCustomCode8",

                                             gta3c."PreviousCustomCode9",

                                             gta3c."PreviousCustomCode10",

                                             gta3c."PreviousDepartment",

                                             (row_number() over (partition by

                                                                   gta3c."OrigRecNo",

                                                                   gta3c."History"

                                                                 order by

                                                                   gta3c."OrigRecNo",

                                                                   gta3c."History",

                                                                   gta3c."AllocatH")) "RowNumber"

                                           from global_temp_alloc3 gta3c

                                           where 1=1

                                          ) gta3b

                                     where 1=1

                                     and gta3b."History" = gta3."History"

                                     and gta3b."RowNumber" = 1)

    where 1=1;



    --

    -- delete unnecessary records

    --

    vStep := 200;

      

    delete from global_temp_alloc3 gta3

    where 1=1

    and (gta3."TrxType" not in (1, 2)

         or gta3."HistoryType" not in (1, 2, 3, 5)

         or (gta3."HistoryType" in (2, 5)

             and gta3."Payed" = 0

             and gta3."InsPayed" = 0

             and gta3."PtAdj" = 0

             and gta3."InsAdj" = 0

             and gta3."InsTransfer" = 0)

         or (gta3."HistoryType" = 1

             and gta3."Payed" = 0));



    --

    -- determine current and previous values if there is grouping by 1 or grouping by 2

    --

    if ((vGroupBy1 > 0) or (vGroupBy2 > 0)) then

      --

      -- determine current and previous values if there is grouping by 1

      --

      if (vGroupBy1 > 0) then

        --

        -- update current and previous group by 1 values

        --

        vStep := 210;

      

        update global_temp_alloc3 gta3

        set

          gta3."GroupBy1Value" = decode(gta3."GroupBy1", 0, ' ',

                                                         1, gta3."Producer",

                                                         2, gta3."PGroup",

                                                         3, gta3."TypeCode",

                                                         4, trim(to_char(gta3."Year")),

                                                         5, trim(to_char(gta3."AppUser")),

                                                         6, gta3."Custom1",

                                                         7, gta3."Custom2",

                                                         8, gta3."Discipline",

                                                         9, trim(to_char(gta3."EntryUser")),

                                                         10, gta3."Location",

                                                         11, gta3."ClaimDoctor",

                                                         12, trim(to_char(gta3."Practice")),

                                                         13, gta3."Procedure",

                                                         14, gta3."CustomCode1",

                                                         15, gta3."CustomCode2",

                                                         16, gta3."CustomCode3",

                                                         17, gta3."CustomCode4",

                                                         18, gta3."CustomCode5",

                                                         19, gta3."CustomCode6",

                                                         20, gta3."CustomCode7",

                                                         21, gta3."CustomCode8",

                                                         22, gta3."CustomCode9",

                                                         23, gta3."CustomCode10",

                                                         ' '),

          gta3."PreviousGroupBy1Value" = decode(gta3."GroupBy1", 0, ' ',

                                                                 1, gta3."PreviousProducer",

                                                                 2, gta3."PreviousPGroup",

                                                                 3, gta3."PreviousTypeCode",

                                                                 4, trim(to_char(gta3."PreviousYear")),

                                                                 5, trim(to_char(gta3."PreviousAppUser")),

                                                                 6, gta3."PreviousCustom1",

                                                                 7, gta3."PreviousCustom2",

                                                                 8, gta3."PreviousDiscipline",

                                                                 9, trim(to_char(gta3."PreviousEntryUser")),

                                                                 10, gta3."PreviousLocation",

                                                                 11, gta3."PreviousClaimDoctor",

                                                                 12, trim(to_char(gta3."PreviousPractice")),

                                                                 13, gta3."PreviousProcedure",

                                                                 14, gta3."PreviousCustomCode1",

                                                                 15, gta3."PreviousCustomCode2",

                                                                 16, gta3."PreviousCustomCode3",

                                                                 17, gta3."PreviousCustomCode4",

                                                                 18, gta3."PreviousCustomCode5",

                                                                 19, gta3."PreviousCustomCode6",

                                                                 20, gta3."PreviousCustomCode7",

                                                                 21, gta3."PreviousCustomCode8",

                                                                 22, gta3."PreviousCustomCode9",

                                                                 23, gta3."PreviousCustomCode10",

                                                                 ' ')

        where 1=1;

      

      end if;

      

      --

      -- determine current and previous values if there is grouping by 2

      --

      if (vGroupBy2 > 0) then

        --

        -- update current and previous group by 2 values

        --

        vStep := 220;

      

        update global_temp_alloc3 gta3

        set

          gta3."GroupBy2Value" = decode(gta3."GroupBy2", 0, ' ',

                                                         1, gta3."Producer",

                                                         2, gta3."PGroup",

                                                         3, gta3."TypeCode",

                                                         4, trim(to_char(gta3."Year")),

                                                         5, trim(to_char(gta3."AppUser")),

                                                         6, gta3."Custom1",

                                                         7, gta3."Custom2",

                                                         8, gta3."Discipline",

                                                         9, trim(to_char(gta3."EntryUser")),

                                                         10, gta3."Location",

                                                         11, gta3."ClaimDoctor",

                                                         12, trim(to_char(gta3."Practice")),

                                                         13, gta3."Procedure",

                                                         14, gta3."CustomCode1",

                                                         15, gta3."CustomCode2",

                                                         16, gta3."CustomCode3",

                                                         17, gta3."CustomCode4",

                                                         18, gta3."CustomCode5",

                                                         19, gta3."CustomCode6",

                                                         20, gta3."CustomCode7",

                                                         21, gta3."CustomCode8",

                                                         22, gta3."CustomCode9",

                                                         23, gta3."CustomCode10",

                                                         ' '),

          gta3."PreviousGroupBy2Value" = decode(gta3."GroupBy2", 0, ' ',

                                                                 1, gta3."PreviousProducer",

                                                                 2, gta3."PreviousPGroup",

                                                                 3, gta3."PreviousTypeCode",

                                                                 4, trim(to_char(gta3."PreviousYear")),

                                                                 5, trim(to_char(gta3."PreviousAppUser")),

                                                                 6, gta3."PreviousCustom1",

                                                                 7, gta3."PreviousCustom2",

                                                                 8, gta3."PreviousDiscipline",

                                                                 9, trim(to_char(gta3."PreviousEntryUser")),

                                                                 10, gta3."PreviousLocation",

                                                                 11, gta3."PreviousClaimDoctor",

                                                                 12, trim(to_char(gta3."PreviousPractice")),

                                                                 13, gta3."PreviousProcedure",

                                                                 14, gta3."PreviousCustomCode1",

                                                                 15, gta3."PreviousCustomCode2",

                                                                 16, gta3."PreviousCustomCode3",

                                                                 17, gta3."PreviousCustomCode4",

                                                                 18, gta3."PreviousCustomCode5",

                                                                 19, gta3."PreviousCustomCode6",

                                                                 20, gta3."PreviousCustomCode7",

                                                                 21, gta3."PreviousCustomCode8",

                                                                 22, gta3."PreviousCustomCode9",

                                                                 23, gta3."PreviousCustomCode10",

                                                                 ' ')

        where 1=1;

      

      end if;



    else

      --

      -- delete records that are outside of the reporting period

      --

      vStep := 225;

    

      delete from global_temp_alloc3 gta3

      where 1=1

      and (gta3."TxModifiedDate" < vFromDate

           or gta3."TxModifiedDate" > vToDate);



      --

      -- check if there is a change in department

      --

      vStep := 230;



      select count(distinct gta3c."Department")

      into vDeptCount

      from (select gta3a."Department" "Department"

            from global_temp_alloc3 gta3a

            where 1=1

            union

            select gta3b."PreviousDepartment" "Department"

            from global_temp_alloc3 gta3b

            where 1=1) gta3c

      where 1=1;

      

      --

      -- delete non-allocate records if there is no change in department

      --

      if (vDeptCount = 1) then

        --

        -- delete non-allocate records if there is no grouping by 1 and no grouping by 2 and there is no change in department

        --

        vStep := 240;



        delete from global_temp_alloc3 gta3

        where 1=1

        and (gta3."HistoryType" not in (1, 3)

             or (gta3."HistoryType" = 1

                 and gta3."Payed" = 0));

        

      end if;



    end if;



    --

    -- delete records that are outside of the reporting period

    --

    vStep := 255;

    

    delete from global_temp_alloc3 gta3

    where 1=1

    and (gta3."TxModifiedDate" < vFromDate

         or gta3."TxModifiedDate" > vToDate);

     

    --

    -- finalize records for the current OrigRecNo

    --

    vStep := 250;

    

    for pOrigRecNo2 in cOrigRecNo2 loop

      --

      -- get correct amount

      --

      vStep := 260;

      

      vAmount := (case pOrigRecNo2."PayType"

                    when 3 then pOrigRecNo2."Payed"

                    when 4 then pOrigRecNo2."InsPayed"

                    when 6 then pOrigRecNo2."PtAdj"

                    when 7 then pOrigRecNo2."InsAdj"

                    else pOrigRecNo2."Amount"

                  end);

                  

      --

      -- get original "Type", "Id" and "Treatment" if Rebill (HistoryType = 5)

      --

      if (pOrigRecNo2."HistoryType" = 5) then

        --

        -- get history ID from deletion that happened before the rebill

        --

        vStep := 270;

        

        select nvl(max(gta2."History"), 0)

        into vMaxHistory

        from global_temp_alloc2 gta2

        where 1=1

        and gta2."HistoryType" = 4

        and gta2."History" < pOrigRecNo2."History";



        --

        -- get original "Type", "Id" and "Treatment" from deletion that happened before the rebill

        --

        if (vMaxHistory > 0) then

          

          begin

            --

            -- get original "Type", "Id" and "Treatment" from deletion that happened before the rebill

            --

            vStep := 280;

          

            select

              h."Type",

              h."Id",

              h."Treatment"

            into

              vOrigType,

              vOrigId,

              vOrigTreatment

            from history h

            where 1=1

            and "History" = vMaxHistory;

            

          exception

            when others then

              --

              -- assign zeroes to the variables

              --

              vStep := 290;

        

              vOrigType := 0;

              vOrigId := 0;

              vOrigTreatment := 0;

              

          end;



        else

          --

          -- assign zeroes to the variables

          --

          vStep := 300;

        

          vOrigType := 0;

          vOrigId := 0;

          vOrigTreatment := 0;

          

        end if;



      else

        --

        -- assign zeroes to the variables

        --

        vStep := 310;

        

        vMaxHistory := 0;

        vOrigType := 0;

        vOrigId := 0;

        vOrigTreatment := 0;

  

      end if;

                  

      --

      -- insert into 4th staging table

      --

      if ((pOrigRecNo2."HistoryType" in (1, 3)) and (pOrigRecNo2."Department" = vDepartment)) then

        --

        -- insert into 4th staging table if allocation

        --

        vStep := 320;

        

        insert into global_temp_alloc4

        values (

                pOrigRecNo2."AllocatH",

                pOrigRecNo2."PayType",

                pOrigRecNo2."TrxType",

                pOrigRecNo2."TrxId",

                pOrigRecNo2."TrxTreatment",

                pOrigRecNo2."Amount",

                pOrigRecNo2."AllocateLink",

                pOrigRecNo2."TxHistoryId",

                pOrigRecNo2."PmtHistoryId",

                pOrigRecNo2."OrigRecNo",

                pOrigRecNo2."History",

                pOrigRecNo2."HistoryType",

                pOrigRecNo2."Patient",

                pOrigRecNo2."TxModifiedDate",

                pOrigRecNo2."Payed",

                pOrigRecNo2."InsPayed",

                pOrigRecNo2."PtAdj",

                pOrigRecNo2."InsAdj",

                pOrigRecNo2."InsTransfer",

                pOrigRecNo2."Discipline",

                pOrigRecNo2."Procedure",

                pOrigRecNo2."Practice",

                pOrigRecNo2."ClaimDoctor",

                pOrigRecNo2."Location",

                pOrigRecNo2."EntryUser",

                pOrigRecNo2."AppUser",

                pOrigRecNo2."Custom1",

                pOrigRecNo2."Custom2",

                pOrigRecNo2."Producer",

                pOrigRecNo2."TypeCode",

                pOrigRecNo2."PGroup",

                pOrigRecNo2."Year",

                pOrigRecNo2."CustomCode1",

                pOrigRecNo2."CustomCode2",

                pOrigRecNo2."CustomCode3",

                pOrigRecNo2."CustomCode4",

                pOrigRecNo2."CustomCode5",

                pOrigRecNo2."CustomCode6",

                pOrigRecNo2."CustomCode7",

                pOrigRecNo2."CustomCode8",

                pOrigRecNo2."CustomCode9",

                pOrigRecNo2."CustomCode10",

                pOrigRecNo2."Department",

                decode(pOrigRecNo2."HistoryType", 1, vNew, vAllocate),

                pOrigRecNo2."GroupBy1",

                pOrigRecNo2."GroupBy2",

                pOrigRecNo2."PreviousHistory",

                pOrigRecNo2."PreviousDiscipline",

                pOrigRecNo2."PreviousProcedure",

                pOrigRecNo2."PreviousPractice",

                pOrigRecNo2."PreviousClaimDoctor",

                pOrigRecNo2."PreviousLocation",

                pOrigRecNo2."PreviousEntryUser",

                pOrigRecNo2."PreviousAppUser",

                pOrigRecNo2."PreviousCustom1",

                pOrigRecNo2."PreviousCustom2",

                pOrigRecNo2."PreviousProducer",

                pOrigRecNo2."PreviousTypeCode",

                pOrigRecNo2."PreviousPGroup",

                pOrigRecNo2."PreviousYear",

                pOrigRecNo2."PreviousCustomCode1",

                pOrigRecNo2."PreviousCustomCode2",

                pOrigRecNo2."PreviousCustomCode3",

                pOrigRecNo2."PreviousCustomCode4",

                pOrigRecNo2."PreviousCustomCode5",

                pOrigRecNo2."PreviousCustomCode6",

                pOrigRecNo2."PreviousCustomCode7",

                pOrigRecNo2."PreviousCustomCode8",

                pOrigRecNo2."PreviousCustomCode9",

                pOrigRecNo2."PreviousCustomCode10",

                pOrigRecNo2."PreviousDepartment",

                pOrigRecNo2."GroupBy1Value",

                pOrigRecNo2."GroupBy2Value",

                pOrigRecNo2."PreviousGroupBy1Value",

                pOrigRecNo2."PreviousGroupBy2Value"

               );



      else

        --

        --  create offset records (transfer in/out) if group by 1 changes

        --

        if ((pOrigRecNo2."GroupBy1" > 0) and (pOrigRecNo2."PreviousGroupBy1Value" <> pOrigRecNo2."GroupBy1Value")) then

          --

          -- create offset records (transfer in/out) if only one payment/allocation

          --

          if ((pOrigRecNo2."HasAllocation" = 0) and (pOrigRecNo2."PayType" in (3, 4)) and (pOrigRecNo2."Amount" <= 0)) then

            --

            -- insert into 4th staging table (transfer out)

            --

            vStep := 330;

            

            insert into global_temp_alloc4

            values (

                    pOrigRecNo2."AllocatH",

                    pOrigRecNo2."PayType",

                    pOrigRecNo2."TrxType",

                    pOrigRecNo2."TrxId",

                    pOrigRecNo2."TrxTreatment",

                    (vAmount * -1),

                    pOrigRecNo2."AllocateLink",

                    pOrigRecNo2."PreviousHistory",

                    pOrigRecNo2."PmtHistoryId",

                    pOrigRecNo2."OrigRecNo",

                    pOrigRecNo2."History",

                    pOrigRecNo2."HistoryType",

                    pOrigRecNo2."Patient",

                    pOrigRecNo2."TxModifiedDate",

                    pOrigRecNo2."Payed",

                    pOrigRecNo2."InsPayed",

                    pOrigRecNo2."PtAdj",

                    pOrigRecNo2."InsAdj",

                    pOrigRecNo2."InsTransfer",

                    pOrigRecNo2."Discipline",

                    pOrigRecNo2."Procedure",

                    pOrigRecNo2."Practice",

                    pOrigRecNo2."ClaimDoctor",

                    pOrigRecNo2."Location",

                    pOrigRecNo2."EntryUser",

                    pOrigRecNo2."AppUser",

                    pOrigRecNo2."Custom1",

                    pOrigRecNo2."Custom2",

                    pOrigRecNo2."Producer",

                    pOrigRecNo2."TypeCode",

                    pOrigRecNo2."PGroup",

                    pOrigRecNo2."Year",

                    pOrigRecNo2."CustomCode1",

                    pOrigRecNo2."CustomCode2",

                    pOrigRecNo2."CustomCode3",

                    pOrigRecNo2."CustomCode4",

                    pOrigRecNo2."CustomCode5",

                    pOrigRecNo2."CustomCode6",

                    pOrigRecNo2."CustomCode7",

                    pOrigRecNo2."CustomCode8",

                    pOrigRecNo2."CustomCode9",

                    pOrigRecNo2."CustomCode10",

                    pOrigRecNo2."Department",

                    vTransferOut,

                    pOrigRecNo2."GroupBy1",

                    pOrigRecNo2."GroupBy2",

                    pOrigRecNo2."PreviousHistory",

                    pOrigRecNo2."PreviousDiscipline",

                    pOrigRecNo2."PreviousProcedure",

                    pOrigRecNo2."PreviousPractice",

                    pOrigRecNo2."PreviousClaimDoctor",

                    pOrigRecNo2."PreviousLocation",

                    pOrigRecNo2."PreviousEntryUser",

                    pOrigRecNo2."PreviousAppUser",

                    pOrigRecNo2."PreviousCustom1",

                    pOrigRecNo2."PreviousCustom2",

                    pOrigRecNo2."PreviousProducer",

                    pOrigRecNo2."PreviousTypeCode",

                    pOrigRecNo2."PreviousPGroup",

                    pOrigRecNo2."PreviousYear",

                    pOrigRecNo2."PreviousCustomCode1",

                    pOrigRecNo2."PreviousCustomCode2",

                    pOrigRecNo2."PreviousCustomCode3",

                    pOrigRecNo2."PreviousCustomCode4",

                    pOrigRecNo2."PreviousCustomCode5",

                    pOrigRecNo2."PreviousCustomCode6",

                    pOrigRecNo2."PreviousCustomCode7",

                    pOrigRecNo2."PreviousCustomCode8",

                    pOrigRecNo2."PreviousCustomCode9",

                    pOrigRecNo2."PreviousCustomCode10",

                    pOrigRecNo2."PreviousDepartment",

                    pOrigRecNo2."GroupBy1Value",

                    pOrigRecNo2."GroupBy2Value",

                    pOrigRecNo2."PreviousGroupBy1Value",

                    pOrigRecNo2."PreviousGroupBy2Value"

                   );



            --

            -- insert into 4th staging table (transfer in)

            --

            vStep := 340;

          

            insert into global_temp_alloc4

            values (

                    pOrigRecNo2."AllocatH",

                    pOrigRecNo2."PayType",

                    pOrigRecNo2."TrxType",

                    pOrigRecNo2."TrxId",

                    pOrigRecNo2."TrxTreatment",

                    vAmount,

                    pOrigRecNo2."AllocateLink",

                    pOrigRecNo2."History",

                    pOrigRecNo2."PmtHistoryId",

                    pOrigRecNo2."OrigRecNo",

                    pOrigRecNo2."History",

                    pOrigRecNo2."HistoryType",

                    pOrigRecNo2."Patient",

                    pOrigRecNo2."TxModifiedDate",

                    pOrigRecNo2."Payed",

                    pOrigRecNo2."InsPayed",

                    pOrigRecNo2."PtAdj",

                    pOrigRecNo2."InsAdj",

                    pOrigRecNo2."InsTransfer",

                    pOrigRecNo2."Discipline",

                    pOrigRecNo2."Procedure",

                    pOrigRecNo2."Practice",

                    pOrigRecNo2."ClaimDoctor",

                    pOrigRecNo2."Location",

                    pOrigRecNo2."EntryUser",

                    pOrigRecNo2."AppUser",

                    pOrigRecNo2."Custom1",

                    pOrigRecNo2."Custom2",

                    pOrigRecNo2."Producer",

                    pOrigRecNo2."TypeCode",

                    pOrigRecNo2."PGroup",

                    pOrigRecNo2."Year",

                    pOrigRecNo2."CustomCode1",

                    pOrigRecNo2."CustomCode2",

                    pOrigRecNo2."CustomCode3",

                    pOrigRecNo2."CustomCode4",

                    pOrigRecNo2."CustomCode5",

                    pOrigRecNo2."CustomCode6",

                    pOrigRecNo2."CustomCode7",

                    pOrigRecNo2."CustomCode8",

                    pOrigRecNo2."CustomCode9",

                    pOrigRecNo2."CustomCode10",

                    pOrigRecNo2."Department",

                    vTransferIn,

                    pOrigRecNo2."GroupBy1",

                    pOrigRecNo2."GroupBy2",

                    pOrigRecNo2."PreviousHistory",

                    pOrigRecNo2."PreviousDiscipline",

                    pOrigRecNo2."PreviousProcedure",

                    pOrigRecNo2."PreviousPractice",

                    pOrigRecNo2."PreviousClaimDoctor",

                    pOrigRecNo2."PreviousLocation",

                    pOrigRecNo2."PreviousEntryUser",

                    pOrigRecNo2."PreviousAppUser",

                    pOrigRecNo2."PreviousCustom1",

                    pOrigRecNo2."PreviousCustom2",

                    pOrigRecNo2."PreviousProducer",

                    pOrigRecNo2."PreviousTypeCode",

                    pOrigRecNo2."PreviousPGroup",

                    pOrigRecNo2."PreviousYear",

                    pOrigRecNo2."PreviousCustomCode1",

                    pOrigRecNo2."PreviousCustomCode2",

                    pOrigRecNo2."PreviousCustomCode3",

                    pOrigRecNo2."PreviousCustomCode4",

                    pOrigRecNo2."PreviousCustomCode5",

                    pOrigRecNo2."PreviousCustomCode6",

                    pOrigRecNo2."PreviousCustomCode7",

                    pOrigRecNo2."PreviousCustomCode8",

                    pOrigRecNo2."PreviousCustomCode9",

                    pOrigRecNo2."PreviousCustomCode10",

                    pOrigRecNo2."PreviousDepartment",

                    pOrigRecNo2."GroupBy1Value",

                    pOrigRecNo2."GroupBy2Value",

                    pOrigRecNo2."PreviousGroupBy1Value",

                    pOrigRecNo2."PreviousGroupBy2Value"

                   );



          else          

            --

            -- create offset records (transfer in/out) if more than one/multiple payments/allocations

            --

            vStep := 350;

                             

            for pAllocatH in cAllocatH (pOrigRecNo2."TrxType",

                                        pOrigRecNo2."TrxId",

                                        pOrigRecNo2."TrxTreatment",

                                        pOrigRecNo2."TxModifiedDate",

                                        vOrigType,

                                        vOrigId,

                                        vOrigTreatment) loop

              --

              -- insert into 4th staging table (transfer out)

              --

              vStep := 360;

            

              insert into global_temp_alloc4

              values (

                      pAllocatH."AllocatH",

                      pAllocatH."PayType",

                      pOrigRecNo2."TrxType",

                      pOrigRecNo2."TrxId",

                      pOrigRecNo2."TrxTreatment",

                      (pAllocatH."Amount" * -1),

                      pAllocatH."AllocateLink",

                      pOrigRecNo2."PreviousHistory",

                      pAllocatH."PmtHistoryId",

                      pOrigRecNo2."OrigRecNo",

                      pOrigRecNo2."History",

                      pOrigRecNo2."HistoryType",

                      pOrigRecNo2."Patient",

                      pOrigRecNo2."TxModifiedDate",

                      pOrigRecNo2."Payed",

                      pOrigRecNo2."InsPayed",

                      pOrigRecNo2."PtAdj",

                      pOrigRecNo2."InsAdj",

                      pOrigRecNo2."InsTransfer",

                      pOrigRecNo2."Discipline",

                      pOrigRecNo2."Procedure",

                      pOrigRecNo2."Practice",

                      pOrigRecNo2."ClaimDoctor",

                      pOrigRecNo2."Location",

                      pOrigRecNo2."EntryUser",

                      pOrigRecNo2."AppUser",

                      pOrigRecNo2."Custom1",

                      pOrigRecNo2."Custom2",

                      pOrigRecNo2."Producer",

                      pOrigRecNo2."TypeCode",

                      pOrigRecNo2."PGroup",

                      pOrigRecNo2."Year",

                      pOrigRecNo2."CustomCode1",

                      pOrigRecNo2."CustomCode2",

                      pOrigRecNo2."CustomCode3",

                      pOrigRecNo2."CustomCode4",

                      pOrigRecNo2."CustomCode5",

                      pOrigRecNo2."CustomCode6",

                      pOrigRecNo2."CustomCode7",

                      pOrigRecNo2."CustomCode8",

                      pOrigRecNo2."CustomCode9",

                      pOrigRecNo2."CustomCode10",

                      pOrigRecNo2."Department",

                      vTransferOut,

                      pOrigRecNo2."GroupBy1",

                      pOrigRecNo2."GroupBy2",

                      pOrigRecNo2."PreviousHistory",

                      pOrigRecNo2."PreviousDiscipline",

                      pOrigRecNo2."PreviousProcedure",

                      pOrigRecNo2."PreviousPractice",

                      pOrigRecNo2."PreviousClaimDoctor",

                      pOrigRecNo2."PreviousLocation",

                      pOrigRecNo2."PreviousEntryUser",

                      pOrigRecNo2."PreviousAppUser",

                      pOrigRecNo2."PreviousCustom1",

                      pOrigRecNo2."PreviousCustom2",

                      pOrigRecNo2."PreviousProducer",

                      pOrigRecNo2."PreviousTypeCode",

                      pOrigRecNo2."PreviousPGroup",

                      pOrigRecNo2."PreviousYear",

                      pOrigRecNo2."PreviousCustomCode1",

                      pOrigRecNo2."PreviousCustomCode2",

                      pOrigRecNo2."PreviousCustomCode3",

                      pOrigRecNo2."PreviousCustomCode4",

                      pOrigRecNo2."PreviousCustomCode5",

                      pOrigRecNo2."PreviousCustomCode6",

                      pOrigRecNo2."PreviousCustomCode7",

                      pOrigRecNo2."PreviousCustomCode8",

                      pOrigRecNo2."PreviousCustomCode9",

                      pOrigRecNo2."PreviousCustomCode10",

                      pOrigRecNo2."PreviousDepartment",

                      pOrigRecNo2."GroupBy1Value",

                      pOrigRecNo2."GroupBy2Value",

                      pOrigRecNo2."PreviousGroupBy1Value",

                      pOrigRecNo2."PreviousGroupBy2Value"

                     );



              --

              -- insert into 4th staging table (transfer in)

              --

              vStep := 370;

          

              insert into global_temp_alloc4

              values (

                      pAllocatH."AllocatH",

                      pAllocatH."PayType",

                      pOrigRecNo2."TrxType",

                      pOrigRecNo2."TrxId",

                      pOrigRecNo2."TrxTreatment",

                      pAllocatH."Amount",

                      pAllocatH."AllocateLink",

                      pOrigRecNo2."History",

                      pAllocatH."PmtHistoryId",

                      pOrigRecNo2."OrigRecNo",

                      pOrigRecNo2."History",

                      pOrigRecNo2."HistoryType",

                      pOrigRecNo2."Patient",

                      pOrigRecNo2."TxModifiedDate",

                      pOrigRecNo2."Payed",

                      pOrigRecNo2."InsPayed",

                      pOrigRecNo2."PtAdj",

                      pOrigRecNo2."InsAdj",

                      pOrigRecNo2."InsTransfer",

                      pOrigRecNo2."Discipline",

                      pOrigRecNo2."Procedure",

                      pOrigRecNo2."Practice",

                      pOrigRecNo2."ClaimDoctor",

                      pOrigRecNo2."Location",

                      pOrigRecNo2."EntryUser",

                      pOrigRecNo2."AppUser",

                      pOrigRecNo2."Custom1",

                      pOrigRecNo2."Custom2",

                      pOrigRecNo2."Producer",

                      pOrigRecNo2."TypeCode",

                      pOrigRecNo2."PGroup",

                      pOrigRecNo2."Year",

                      pOrigRecNo2."CustomCode1",

                      pOrigRecNo2."CustomCode2",

                      pOrigRecNo2."CustomCode3",

                      pOrigRecNo2."CustomCode4",

                      pOrigRecNo2."CustomCode5",

                      pOrigRecNo2."CustomCode6",

                      pOrigRecNo2."CustomCode7",

                      pOrigRecNo2."CustomCode8",

                      pOrigRecNo2."CustomCode9",

                      pOrigRecNo2."CustomCode10",

                      pOrigRecNo2."Department",

                      vTransferIn,

                      pOrigRecNo2."GroupBy1",

                      pOrigRecNo2."GroupBy2",

                      pOrigRecNo2."PreviousHistory",

                      pOrigRecNo2."PreviousDiscipline",

                      pOrigRecNo2."PreviousProcedure",

                      pOrigRecNo2."PreviousPractice",

                      pOrigRecNo2."PreviousClaimDoctor",

                      pOrigRecNo2."PreviousLocation",

                      pOrigRecNo2."PreviousEntryUser",

                      pOrigRecNo2."PreviousAppUser",

                      pOrigRecNo2."PreviousCustom1",

                      pOrigRecNo2."PreviousCustom2",

                      pOrigRecNo2."PreviousProducer",

                      pOrigRecNo2."PreviousTypeCode",

                      pOrigRecNo2."PreviousPGroup",

                      pOrigRecNo2."PreviousYear",

                      pOrigRecNo2."PreviousCustomCode1",

                      pOrigRecNo2."PreviousCustomCode2",

                      pOrigRecNo2."PreviousCustomCode3",

                      pOrigRecNo2."PreviousCustomCode4",

                      pOrigRecNo2."PreviousCustomCode5",

                      pOrigRecNo2."PreviousCustomCode6",

                      pOrigRecNo2."PreviousCustomCode7",

                      pOrigRecNo2."PreviousCustomCode8",

                      pOrigRecNo2."PreviousCustomCode9",

                      pOrigRecNo2."PreviousCustomCode10",

                      pOrigRecNo2."PreviousDepartment",

                      pOrigRecNo2."GroupBy1Value",

                      pOrigRecNo2."GroupBy2Value",

                      pOrigRecNo2."PreviousGroupBy1Value",

                      pOrigRecNo2."PreviousGroupBy2Value"

                     );



            end loop pAllocatH;

            

          end if;

        

        end if;



        --

        --  create offset records (transfer in/out) if group by 2 changes

        --

        if ((pOrigRecNo2."GroupBy2" > 0) and (pOrigRecNo2."PreviousGroupBy2Value" <> pOrigRecNo2."GroupBy2Value")) then

          --

          -- create offset records (transfer in/out) if only one payment/allocation

          --

          if ((pOrigRecNo2."HasAllocation" = 0) and (pOrigRecNo2."PayType" in (3, 4)) and (pOrigRecNo2."Amount" <= 0)) then

            --

            -- insert into 4th staging table (transfer out)

            --

            vStep := 380;

            

            insert into global_temp_alloc4

            values (

                    pOrigRecNo2."AllocatH",

                    pOrigRecNo2."PayType",

                    pOrigRecNo2."TrxType",

                    pOrigRecNo2."TrxId",

                    pOrigRecNo2."TrxTreatment",

                    vAmount,

                    pOrigRecNo2."AllocateLink",

                    pOrigRecNo2."PreviousHistory",

                    pOrigRecNo2."PmtHistoryId",

                    pOrigRecNo2."OrigRecNo",

                    pOrigRecNo2."History",

                    pOrigRecNo2."HistoryType",

                    pOrigRecNo2."Patient",

                    pOrigRecNo2."TxModifiedDate",

                    pOrigRecNo2."Payed",

                    pOrigRecNo2."InsPayed",

                    pOrigRecNo2."PtAdj",

                    pOrigRecNo2."InsAdj",

                    pOrigRecNo2."InsTransfer",

                    pOrigRecNo2."Discipline",

                    pOrigRecNo2."Procedure",

                    pOrigRecNo2."Practice",

                    pOrigRecNo2."ClaimDoctor",

                    pOrigRecNo2."Location",

                    pOrigRecNo2."EntryUser",

                    pOrigRecNo2."AppUser",

                    pOrigRecNo2."Custom1",

                    pOrigRecNo2."Custom2",

                    pOrigRecNo2."Producer",

                    pOrigRecNo2."TypeCode",

                    pOrigRecNo2."PGroup",

                    pOrigRecNo2."Year",

                    pOrigRecNo2."CustomCode1",

                    pOrigRecNo2."CustomCode2",

                    pOrigRecNo2."CustomCode3",

                    pOrigRecNo2."CustomCode4",

                    pOrigRecNo2."CustomCode5",

                    pOrigRecNo2."CustomCode6",

                    pOrigRecNo2."CustomCode7",

                    pOrigRecNo2."CustomCode8",

                    pOrigRecNo2."CustomCode9",

                    pOrigRecNo2."CustomCode10",

                    pOrigRecNo2."Department",

                    vTransferOut,

                    pOrigRecNo2."GroupBy1",

                    pOrigRecNo2."GroupBy2",

                    pOrigRecNo2."PreviousHistory",

                    pOrigRecNo2."PreviousDiscipline",

                    pOrigRecNo2."PreviousProcedure",

                    pOrigRecNo2."PreviousPractice",

                    pOrigRecNo2."PreviousClaimDoctor",

                    pOrigRecNo2."PreviousLocation",

                    pOrigRecNo2."PreviousEntryUser",

                    pOrigRecNo2."PreviousAppUser",

                    pOrigRecNo2."PreviousCustom1",

                    pOrigRecNo2."PreviousCustom2",

                    pOrigRecNo2."PreviousProducer",

                    pOrigRecNo2."PreviousTypeCode",

                    pOrigRecNo2."PreviousPGroup",

                    pOrigRecNo2."PreviousYear",

                    pOrigRecNo2."PreviousCustomCode1",

                    pOrigRecNo2."PreviousCustomCode2",

                    pOrigRecNo2."PreviousCustomCode3",

                    pOrigRecNo2."PreviousCustomCode4",

                    pOrigRecNo2."PreviousCustomCode5",

                    pOrigRecNo2."PreviousCustomCode6",

                    pOrigRecNo2."PreviousCustomCode7",

                    pOrigRecNo2."PreviousCustomCode8",

                    pOrigRecNo2."PreviousCustomCode9",

                    pOrigRecNo2."PreviousCustomCode10",

                    pOrigRecNo2."PreviousDepartment",

                    pOrigRecNo2."GroupBy1Value",

                    pOrigRecNo2."GroupBy2Value",

                    pOrigRecNo2."PreviousGroupBy1Value",

                    pOrigRecNo2."PreviousGroupBy2Value"

                   );



            --

            -- insert into 4th staging table (transfer in)

            --

            vStep := 390;

          

            insert into global_temp_alloc4

            values (

                    pOrigRecNo2."AllocatH",

                    pOrigRecNo2."PayType",

                    pOrigRecNo2."TrxType",

                    pOrigRecNo2."TrxId",

                    pOrigRecNo2."TrxTreatment",

                    vAmount,

                    pOrigRecNo2."AllocateLink",

                    pOrigRecNo2."History",

                    pOrigRecNo2."PmtHistoryId",

                    pOrigRecNo2."OrigRecNo",

                    pOrigRecNo2."History",

                    pOrigRecNo2."HistoryType",

                    pOrigRecNo2."Patient",

                    pOrigRecNo2."TxModifiedDate",

                    pOrigRecNo2."Payed",

                    pOrigRecNo2."InsPayed",

                    pOrigRecNo2."PtAdj",

                    pOrigRecNo2."InsAdj",

                    pOrigRecNo2."InsTransfer",

                    pOrigRecNo2."Discipline",

                    pOrigRecNo2."Procedure",

                    pOrigRecNo2."Practice",

                    pOrigRecNo2."ClaimDoctor",

                    pOrigRecNo2."Location",

                    pOrigRecNo2."EntryUser",

                    pOrigRecNo2."AppUser",

                    pOrigRecNo2."Custom1",

                    pOrigRecNo2."Custom2",

                    pOrigRecNo2."Producer",

                    pOrigRecNo2."TypeCode",

                    pOrigRecNo2."PGroup",

                    pOrigRecNo2."Year",

                    pOrigRecNo2."CustomCode1",

                    pOrigRecNo2."CustomCode2",

                    pOrigRecNo2."CustomCode3",

                    pOrigRecNo2."CustomCode4",

                    pOrigRecNo2."CustomCode5",

                    pOrigRecNo2."CustomCode6",

                    pOrigRecNo2."CustomCode7",

                    pOrigRecNo2."CustomCode8",

                    pOrigRecNo2."CustomCode9",

                    pOrigRecNo2."CustomCode10",

                    pOrigRecNo2."Department",

                    vTransferIn,

                    pOrigRecNo2."GroupBy1",

                    pOrigRecNo2."GroupBy2",

                    pOrigRecNo2."PreviousHistory",

                    pOrigRecNo2."PreviousDiscipline",

                    pOrigRecNo2."PreviousProcedure",

                    pOrigRecNo2."PreviousPractice",

                    pOrigRecNo2."PreviousClaimDoctor",

                    pOrigRecNo2."PreviousLocation",

                    pOrigRecNo2."PreviousEntryUser",

                    pOrigRecNo2."PreviousAppUser",

                    pOrigRecNo2."PreviousCustom1",

                    pOrigRecNo2."PreviousCustom2",

                    pOrigRecNo2."PreviousProducer",

                    pOrigRecNo2."PreviousTypeCode",

                    pOrigRecNo2."PreviousPGroup",

                    pOrigRecNo2."PreviousYear",

                    pOrigRecNo2."PreviousCustomCode1",

                    pOrigRecNo2."PreviousCustomCode2",

                    pOrigRecNo2."PreviousCustomCode3",

                    pOrigRecNo2."PreviousCustomCode4",

                    pOrigRecNo2."PreviousCustomCode5",

                    pOrigRecNo2."PreviousCustomCode6",

                    pOrigRecNo2."PreviousCustomCode7",

                    pOrigRecNo2."PreviousCustomCode8",

                    pOrigRecNo2."PreviousCustomCode9",

                    pOrigRecNo2."PreviousCustomCode10",

                    pOrigRecNo2."PreviousDepartment",

                    pOrigRecNo2."GroupBy1Value",

                    pOrigRecNo2."GroupBy2Value",

                    pOrigRecNo2."PreviousGroupBy1Value",

                    pOrigRecNo2."PreviousGroupBy2Value"

                   );



          else          

            --

            -- create offset records (transfer in/out) if more than one/multiple payments/allocations

            --

            vStep := 400;

                                         

            for pAllocatH in cAllocatH (pOrigRecNo2."TrxType",

                                        pOrigRecNo2."TrxId",

                                        pOrigRecNo2."TrxTreatment",

                                        pOrigRecNo2."TxModifiedDate",

                                        vOrigType,

                                        vOrigId,

                                        vOrigTreatment) loop

              --

              -- insert into 4th staging table (transfer out)

              --

              vStep := 410;

            

              insert into global_temp_alloc4

              values (

                      pAllocatH."AllocatH",

                      pAllocatH."PayType",

                      pOrigRecNo2."TrxType",

                      pOrigRecNo2."TrxId",

                      pOrigRecNo2."TrxTreatment",

                      (pAllocatH."Amount" * -1),

                      pAllocatH."AllocateLink",

                      pOrigRecNo2."PreviousHistory",

                      pAllocatH."PmtHistoryId",

                      pOrigRecNo2."OrigRecNo",

                      pOrigRecNo2."History",

                      pOrigRecNo2."HistoryType",

                      pOrigRecNo2."Patient",

                      pOrigRecNo2."TxModifiedDate",

                      pOrigRecNo2."Payed",

                      pOrigRecNo2."InsPayed",

                      pOrigRecNo2."PtAdj",

                      pOrigRecNo2."InsAdj",

                      pOrigRecNo2."InsTransfer",

                      pOrigRecNo2."Discipline",

                      pOrigRecNo2."Procedure",

                      pOrigRecNo2."Practice",

                      pOrigRecNo2."ClaimDoctor",

                      pOrigRecNo2."Location",

                      pOrigRecNo2."EntryUser",

                      pOrigRecNo2."AppUser",

                      pOrigRecNo2."Custom1",

                      pOrigRecNo2."Custom2",

                      pOrigRecNo2."Producer",

                      pOrigRecNo2."TypeCode",

                      pOrigRecNo2."PGroup",

                      pOrigRecNo2."Year",

                      pOrigRecNo2."CustomCode1",

                      pOrigRecNo2."CustomCode2",

                      pOrigRecNo2."CustomCode3",

                      pOrigRecNo2."CustomCode4",

                      pOrigRecNo2."CustomCode5",

                      pOrigRecNo2."CustomCode6",

                      pOrigRecNo2."CustomCode7",

                      pOrigRecNo2."CustomCode8",

                      pOrigRecNo2."CustomCode9",

                      pOrigRecNo2."CustomCode10",

                      pOrigRecNo2."Department",

                      vTransferOut,

                      pOrigRecNo2."GroupBy1",

                      pOrigRecNo2."GroupBy2",

                      pOrigRecNo2."PreviousHistory",

                      pOrigRecNo2."PreviousDiscipline",

                      pOrigRecNo2."PreviousProcedure",

                      pOrigRecNo2."PreviousPractice",

                      pOrigRecNo2."PreviousClaimDoctor",

                      pOrigRecNo2."PreviousLocation",

                      pOrigRecNo2."PreviousEntryUser",

                      pOrigRecNo2."PreviousAppUser",

                      pOrigRecNo2."PreviousCustom1",

                      pOrigRecNo2."PreviousCustom2",

                      pOrigRecNo2."PreviousProducer",

                      pOrigRecNo2."PreviousTypeCode",

                      pOrigRecNo2."PreviousPGroup",

                      pOrigRecNo2."PreviousYear",

                      pOrigRecNo2."PreviousCustomCode1",

                      pOrigRecNo2."PreviousCustomCode2",

                      pOrigRecNo2."PreviousCustomCode3",

                      pOrigRecNo2."PreviousCustomCode4",

                      pOrigRecNo2."PreviousCustomCode5",

                      pOrigRecNo2."PreviousCustomCode6",

                      pOrigRecNo2."PreviousCustomCode7",

                      pOrigRecNo2."PreviousCustomCode8",

                      pOrigRecNo2."PreviousCustomCode9",

                      pOrigRecNo2."PreviousCustomCode10",

                      pOrigRecNo2."PreviousDepartment",

                      pOrigRecNo2."GroupBy1Value",

                      pOrigRecNo2."GroupBy2Value",

                      pOrigRecNo2."PreviousGroupBy1Value",

                      pOrigRecNo2."PreviousGroupBy2Value"

                     );



              --

              -- insert into 4th staging table (transfer in)

              --

              vStep := 420;

          

              insert into global_temp_alloc4

              values (

                      pAllocatH."AllocatH",

                      pAllocatH."PayType",

                      pOrigRecNo2."TrxType",

                      pOrigRecNo2."TrxId",

                      pOrigRecNo2."TrxTreatment",

                      pAllocatH."Amount",

                      pAllocatH."AllocateLink",

                      pOrigRecNo2."History",

                      pAllocatH."PmtHistoryId",

                      pOrigRecNo2."OrigRecNo",

                      pOrigRecNo2."History",

                      pOrigRecNo2."HistoryType",

                      pOrigRecNo2."Patient",

                      pOrigRecNo2."TxModifiedDate",

                      pOrigRecNo2."Payed",

                      pOrigRecNo2."InsPayed",

                      pOrigRecNo2."PtAdj",

                      pOrigRecNo2."InsAdj",

                      pOrigRecNo2."InsTransfer",

                      pOrigRecNo2."Discipline",

                      pOrigRecNo2."Procedure",

                      pOrigRecNo2."Practice",

                      pOrigRecNo2."ClaimDoctor",

                      pOrigRecNo2."Location",

                      pOrigRecNo2."EntryUser",

                      pOrigRecNo2."AppUser",

                      pOrigRecNo2."Custom1",

                      pOrigRecNo2."Custom2",

                      pOrigRecNo2."Producer",

                      pOrigRecNo2."TypeCode",

                      pOrigRecNo2."PGroup",

                      pOrigRecNo2."Year",

                      pOrigRecNo2."CustomCode1",

                      pOrigRecNo2."CustomCode2",

                      pOrigRecNo2."CustomCode3",

                      pOrigRecNo2."CustomCode4",

                      pOrigRecNo2."CustomCode5",

                      pOrigRecNo2."CustomCode6",

                      pOrigRecNo2."CustomCode7",

                      pOrigRecNo2."CustomCode8",

                      pOrigRecNo2."CustomCode9",

                      pOrigRecNo2."CustomCode10",

                      pOrigRecNo2."Department",

                      vTransferIn,

                      pOrigRecNo2."GroupBy1",

                      pOrigRecNo2."GroupBy2",

                      pOrigRecNo2."PreviousHistory",

                      pOrigRecNo2."PreviousDiscipline",

                      pOrigRecNo2."PreviousProcedure",

                      pOrigRecNo2."PreviousPractice",

                      pOrigRecNo2."PreviousClaimDoctor",

                      pOrigRecNo2."PreviousLocation",

                      pOrigRecNo2."PreviousEntryUser",

                      pOrigRecNo2."PreviousAppUser",

                      pOrigRecNo2."PreviousCustom1",

                      pOrigRecNo2."PreviousCustom2",

                      pOrigRecNo2."PreviousProducer",

                      pOrigRecNo2."PreviousTypeCode",

                      pOrigRecNo2."PreviousPGroup",

                      pOrigRecNo2."PreviousYear",

                      pOrigRecNo2."PreviousCustomCode1",

                      pOrigRecNo2."PreviousCustomCode2",

                      pOrigRecNo2."PreviousCustomCode3",

                      pOrigRecNo2."PreviousCustomCode4",

                      pOrigRecNo2."PreviousCustomCode5",

                      pOrigRecNo2."PreviousCustomCode6",

                      pOrigRecNo2."PreviousCustomCode7",

                      pOrigRecNo2."PreviousCustomCode8",

                      pOrigRecNo2."PreviousCustomCode9",

                      pOrigRecNo2."PreviousCustomCode10",

                      pOrigRecNo2."PreviousDepartment",

                      pOrigRecNo2."GroupBy1Value",

                      pOrigRecNo2."GroupBy2Value",

                      pOrigRecNo2."PreviousGroupBy1Value",

                      pOrigRecNo2."PreviousGroupBy2Value"

                     );



            end loop pAllocatH;

            

          end if;



        end if;



        --

        -- create department changes entries (transfer out)

        --

        if ((pOrigRecNo2."DeptCount" > 1) and (pOrigRecNo2."PreviousDepartment" <> pOrigRecNo2."Department") and (pOrigRecNo2."PreviousDepartment" = vDepartment)) then

          --

          -- create offset records (transfer out) if only one payment/allocation

          --

          if ((pOrigRecNo2."HasAllocation" = 0) and (pOrigRecNo2."PayType" in (3, 4)) and (pOrigRecNo2."Amount" <= 0)) then

            --

            -- insert into 4th staging table (transfer out)

            --

            vStep := 430;

        

            insert into global_temp_alloc4

            values (

                    pOrigRecNo2."AllocatH",

                    pOrigRecNo2."PayType",

                    pOrigRecNo2."TrxType",

                    pOrigRecNo2."TrxId",

                    pOrigRecNo2."TrxTreatment",

                    (vAmount * -1),

                    pOrigRecNo2."AllocateLink",

                    pOrigRecNo2."PreviousHistory",

                    pOrigRecNo2."PmtHistoryId",

                    pOrigRecNo2."OrigRecNo",

                    pOrigRecNo2."History",

                    pOrigRecNo2."HistoryType",

                    pOrigRecNo2."Patient",

                    pOrigRecNo2."TxModifiedDate",

                    pOrigRecNo2."Payed",

                    pOrigRecNo2."InsPayed",

                    pOrigRecNo2."PtAdj",

                    pOrigRecNo2."InsAdj",

                    pOrigRecNo2."InsTransfer",

                    pOrigRecNo2."Discipline",

                    pOrigRecNo2."Procedure",

                    pOrigRecNo2."Practice",

                    pOrigRecNo2."ClaimDoctor",

                    pOrigRecNo2."Location",

                    pOrigRecNo2."EntryUser",

                    pOrigRecNo2."AppUser",

                    pOrigRecNo2."Custom1",

                    pOrigRecNo2."Custom2",

                    pOrigRecNo2."Producer",

                    pOrigRecNo2."TypeCode",

                    pOrigRecNo2."PGroup",

                    pOrigRecNo2."Year",

                    pOrigRecNo2."CustomCode1",

                    pOrigRecNo2."CustomCode2",

                    pOrigRecNo2."CustomCode3",

                    pOrigRecNo2."CustomCode4",

                    pOrigRecNo2."CustomCode5",

                    pOrigRecNo2."CustomCode6",

                    pOrigRecNo2."CustomCode7",

                    pOrigRecNo2."CustomCode8",

                    pOrigRecNo2."CustomCode9",

                    pOrigRecNo2."CustomCode10",

                    pOrigRecNo2."Department",

                    vTransferOut,

                    pOrigRecNo2."GroupBy1",

                    pOrigRecNo2."GroupBy2",

                    pOrigRecNo2."PreviousHistory",

                    pOrigRecNo2."PreviousDiscipline",

                    pOrigRecNo2."PreviousProcedure",

                    pOrigRecNo2."PreviousPractice",

                    pOrigRecNo2."PreviousClaimDoctor",

                    pOrigRecNo2."PreviousLocation",

                    pOrigRecNo2."PreviousEntryUser",

                    pOrigRecNo2."PreviousAppUser",

                    pOrigRecNo2."PreviousCustom1",

                    pOrigRecNo2."PreviousCustom2",

                    pOrigRecNo2."PreviousProducer",

                    pOrigRecNo2."PreviousTypeCode",

                    pOrigRecNo2."PreviousPGroup",

                    pOrigRecNo2."PreviousYear",

                    pOrigRecNo2."PreviousCustomCode1",

                    pOrigRecNo2."PreviousCustomCode2",

                    pOrigRecNo2."PreviousCustomCode3",

                    pOrigRecNo2."PreviousCustomCode4",

                    pOrigRecNo2."PreviousCustomCode5",

                    pOrigRecNo2."PreviousCustomCode6",

                    pOrigRecNo2."PreviousCustomCode7",

                    pOrigRecNo2."PreviousCustomCode8",

                    pOrigRecNo2."PreviousCustomCode9",

                    pOrigRecNo2."PreviousCustomCode10",

                    pOrigRecNo2."PreviousDepartment",

                    pOrigRecNo2."GroupBy1Value",

                    pOrigRecNo2."GroupBy2Value",

                    pOrigRecNo2."PreviousGroupBy1Value",

                    pOrigRecNo2."PreviousGroupBy2Value"

                   );



          else          

            --

            -- create offset records (transfer out) if more than one/multiple payments/allocations

            --

            vStep := 440;

                                         

            for pAllocatH in cAllocatH (pOrigRecNo2."TrxType",

                                        pOrigRecNo2."TrxId",

                                        pOrigRecNo2."TrxTreatment",

                                        pOrigRecNo2."TxModifiedDate",

                                        vOrigType,

                                        vOrigId,

                                        vOrigTreatment) loop

              --

              -- insert into 4th staging table (transfer out)

              --

              vStep := 450;

            

              insert into global_temp_alloc4

              values (

                      pAllocatH."AllocatH",

                      pAllocatH."PayType",

                      pOrigRecNo2."TrxType",

                      pOrigRecNo2."TrxId",

                      pOrigRecNo2."TrxTreatment",

                      (pAllocatH."Amount" * -1),

                      pAllocatH."AllocateLink",

                      pOrigRecNo2."PreviousHistory",

                      pAllocatH."PmtHistoryId",

                      pOrigRecNo2."OrigRecNo",

                      pOrigRecNo2."History",

                      pOrigRecNo2."HistoryType",

                      pOrigRecNo2."Patient",

                      pOrigRecNo2."TxModifiedDate",

                      pOrigRecNo2."Payed",

                      pOrigRecNo2."InsPayed",

                      pOrigRecNo2."PtAdj",

                      pOrigRecNo2."InsAdj",

                      pOrigRecNo2."InsTransfer",

                      pOrigRecNo2."Discipline",

                      pOrigRecNo2."Procedure",

                      pOrigRecNo2."Practice",

                      pOrigRecNo2."ClaimDoctor",

                      pOrigRecNo2."Location",

                      pOrigRecNo2."EntryUser",

                      pOrigRecNo2."AppUser",

                      pOrigRecNo2."Custom1",

                      pOrigRecNo2."Custom2",

                      pOrigRecNo2."Producer",

                      pOrigRecNo2."TypeCode",

                      pOrigRecNo2."PGroup",

                      pOrigRecNo2."Year",

                      pOrigRecNo2."CustomCode1",

                      pOrigRecNo2."CustomCode2",

                      pOrigRecNo2."CustomCode3",

                      pOrigRecNo2."CustomCode4",

                      pOrigRecNo2."CustomCode5",

                      pOrigRecNo2."CustomCode6",

                      pOrigRecNo2."CustomCode7",

                      pOrigRecNo2."CustomCode8",

                      pOrigRecNo2."CustomCode9",

                      pOrigRecNo2."CustomCode10",

                      pOrigRecNo2."Department",

                      vTransferOut,

                      pOrigRecNo2."GroupBy1",

                      pOrigRecNo2."GroupBy2",

                      pOrigRecNo2."PreviousHistory",

                      pOrigRecNo2."PreviousDiscipline",

                      pOrigRecNo2."PreviousProcedure",

                      pOrigRecNo2."PreviousPractice",

                      pOrigRecNo2."PreviousClaimDoctor",

                      pOrigRecNo2."PreviousLocation",

                      pOrigRecNo2."PreviousEntryUser",

                      pOrigRecNo2."PreviousAppUser",

                      pOrigRecNo2."PreviousCustom1",

                      pOrigRecNo2."PreviousCustom2",

                      pOrigRecNo2."PreviousProducer",

                      pOrigRecNo2."PreviousTypeCode",

                      pOrigRecNo2."PreviousPGroup",

                      pOrigRecNo2."PreviousYear",

                      pOrigRecNo2."PreviousCustomCode1",

                      pOrigRecNo2."PreviousCustomCode2",

                      pOrigRecNo2."PreviousCustomCode3",

                      pOrigRecNo2."PreviousCustomCode4",

                      pOrigRecNo2."PreviousCustomCode5",

                      pOrigRecNo2."PreviousCustomCode6",

                      pOrigRecNo2."PreviousCustomCode7",

                      pOrigRecNo2."PreviousCustomCode8",

                      pOrigRecNo2."PreviousCustomCode9",

                      pOrigRecNo2."PreviousCustomCode10",

                      pOrigRecNo2."PreviousDepartment",

                      pOrigRecNo2."GroupBy1Value",

                      pOrigRecNo2."GroupBy2Value",

                      pOrigRecNo2."PreviousGroupBy1Value",

                      pOrigRecNo2."PreviousGroupBy2Value"

                     );



            end loop pAllocatH;

          

          end if;



        end if;



        --

        -- create department changes entries (transfer in)

        --

        if ((pOrigRecNo2."DeptCount" > 1) and (pOrigRecNo2."PreviousDepartment" <> pOrigRecNo2."Department") and (pOrigRecNo2."Department" = vDepartment)) then

          --

          -- create offset records (transfer in) if only one payment/allocation

          --

          if ((pOrigRecNo2."HasAllocation" = 0) and (pOrigRecNo2."PayType" in (3, 4)) and (pOrigRecNo2."Amount" <= 0)) then

            --

            -- insert into 4th staging table (transfer in)

            --

            vStep := 460;

        

            insert into global_temp_alloc4

            values (

                    pOrigRecNo2."AllocatH",

                    pOrigRecNo2."PayType",

                    pOrigRecNo2."TrxType",

                    pOrigRecNo2."TrxId",

                    pOrigRecNo2."TrxTreatment",

                    vAmount,

                    pOrigRecNo2."AllocateLink",

                    pOrigRecNo2."History",

                    pOrigRecNo2."PmtHistoryId",

                    pOrigRecNo2."OrigRecNo",

                    pOrigRecNo2."History",

                    pOrigRecNo2."HistoryType",

                    pOrigRecNo2."Patient",

                    pOrigRecNo2."TxModifiedDate",

                    pOrigRecNo2."Payed",

                    pOrigRecNo2."InsPayed",

                    pOrigRecNo2."PtAdj",

                    pOrigRecNo2."InsAdj",

                    pOrigRecNo2."InsTransfer",

                    pOrigRecNo2."Discipline",

                    pOrigRecNo2."Procedure",

                    pOrigRecNo2."Practice",

                    pOrigRecNo2."ClaimDoctor",

                    pOrigRecNo2."Location",

                    pOrigRecNo2."EntryUser",

                    pOrigRecNo2."AppUser",

                    pOrigRecNo2."Custom1",

                    pOrigRecNo2."Custom2",

                    pOrigRecNo2."Producer",

                    pOrigRecNo2."TypeCode",

                    pOrigRecNo2."PGroup",

                    pOrigRecNo2."Year",

                    pOrigRecNo2."CustomCode1",

                    pOrigRecNo2."CustomCode2",

                    pOrigRecNo2."CustomCode3",

                    pOrigRecNo2."CustomCode4",

                    pOrigRecNo2."CustomCode5",

                    pOrigRecNo2."CustomCode6",

                    pOrigRecNo2."CustomCode7",

                    pOrigRecNo2."CustomCode8",

                    pOrigRecNo2."CustomCode9",

                    pOrigRecNo2."CustomCode10",

                    pOrigRecNo2."Department",

                    vTransferIn,

                    pOrigRecNo2."GroupBy1",

                    pOrigRecNo2."GroupBy2",

                    pOrigRecNo2."PreviousHistory",

                    pOrigRecNo2."PreviousDiscipline",

                    pOrigRecNo2."PreviousProcedure",

                    pOrigRecNo2."PreviousPractice",

                    pOrigRecNo2."PreviousClaimDoctor",

                    pOrigRecNo2."PreviousLocation",

                    pOrigRecNo2."PreviousEntryUser",

                    pOrigRecNo2."PreviousAppUser",

                    pOrigRecNo2."PreviousCustom1",

                    pOrigRecNo2."PreviousCustom2",

                    pOrigRecNo2."PreviousProducer",

                    pOrigRecNo2."PreviousTypeCode",

                    pOrigRecNo2."PreviousPGroup",

                    pOrigRecNo2."PreviousYear",

                    pOrigRecNo2."PreviousCustomCode1",

                    pOrigRecNo2."PreviousCustomCode2",

                    pOrigRecNo2."PreviousCustomCode3",

                    pOrigRecNo2."PreviousCustomCode4",

                    pOrigRecNo2."PreviousCustomCode5",

                    pOrigRecNo2."PreviousCustomCode6",

                    pOrigRecNo2."PreviousCustomCode7",

                    pOrigRecNo2."PreviousCustomCode8",

                    pOrigRecNo2."PreviousCustomCode9",

                    pOrigRecNo2."PreviousCustomCode10",

                    pOrigRecNo2."PreviousDepartment",

                    pOrigRecNo2."GroupBy1Value",

                    pOrigRecNo2."GroupBy2Value",

                    pOrigRecNo2."PreviousGroupBy1Value",

                    pOrigRecNo2."PreviousGroupBy2Value"

                   );



          else

            --

            -- create offset records (transfer in) if more than one/multiple payments/allocations

            --

            vStep := 470;

                                         

            for pAllocatH in cAllocatH (pOrigRecNo2."TrxType",

                                        pOrigRecNo2."TrxId",

                                        pOrigRecNo2."TrxTreatment",

                                        pOrigRecNo2."TxModifiedDate",

                                        vOrigType,

                                        vOrigId,

                                        vOrigTreatment) loop

              --

              -- insert into 4th staging table (transfer in)

              --

              vStep := 480;

            

              insert into global_temp_alloc4

              values (              

                      pAllocatH."AllocatH",

                      pAllocatH."PayType",

                      pOrigRecNo2."TrxType",

                      pOrigRecNo2."TrxId",

                      pOrigRecNo2."TrxTreatment",

                      pAllocatH."Amount",

                      pAllocatH."AllocateLink",

                      pOrigRecNo2."History",

                      pAllocatH."PmtHistoryId",

                      pOrigRecNo2."OrigRecNo",

                      pOrigRecNo2."History",

                      pOrigRecNo2."HistoryType",

                      pOrigRecNo2."Patient",

                      pOrigRecNo2."TxModifiedDate",

                      pOrigRecNo2."Payed",

                      pOrigRecNo2."InsPayed",

                      pOrigRecNo2."PtAdj",

                      pOrigRecNo2."InsAdj",

                      pOrigRecNo2."InsTransfer",

                      pOrigRecNo2."Discipline",

                      pOrigRecNo2."Procedure",

                      pOrigRecNo2."Practice",

                      pOrigRecNo2."ClaimDoctor",

                      pOrigRecNo2."Location",

                      pOrigRecNo2."EntryUser",

                      pOrigRecNo2."AppUser",

                      pOrigRecNo2."Custom1",

                      pOrigRecNo2."Custom2",

                      pOrigRecNo2."Producer",

                      pOrigRecNo2."TypeCode",

                      pOrigRecNo2."PGroup",

                      pOrigRecNo2."Year",

                      pOrigRecNo2."CustomCode1",

                      pOrigRecNo2."CustomCode2",

                      pOrigRecNo2."CustomCode3",

                      pOrigRecNo2."CustomCode4",

                      pOrigRecNo2."CustomCode5",

                      pOrigRecNo2."CustomCode6",

                      pOrigRecNo2."CustomCode7",

                      pOrigRecNo2."CustomCode8",

                      pOrigRecNo2."CustomCode9",

                      pOrigRecNo2."CustomCode10",

                      pOrigRecNo2."Department",

                      vTransferIn,

                      pOrigRecNo2."GroupBy1",

                      pOrigRecNo2."GroupBy2",

                      pOrigRecNo2."PreviousHistory",

                      pOrigRecNo2."PreviousDiscipline",

                      pOrigRecNo2."PreviousProcedure",

                      pOrigRecNo2."PreviousPractice",

                      pOrigRecNo2."PreviousClaimDoctor",

                      pOrigRecNo2."PreviousLocation",

                      pOrigRecNo2."PreviousEntryUser",

                      pOrigRecNo2."PreviousAppUser",

                      pOrigRecNo2."PreviousCustom1",

                      pOrigRecNo2."PreviousCustom2",

                      pOrigRecNo2."PreviousProducer",

                      pOrigRecNo2."PreviousTypeCode",

                      pOrigRecNo2."PreviousPGroup",

                      pOrigRecNo2."PreviousYear",

                      pOrigRecNo2."PreviousCustomCode1",

                      pOrigRecNo2."PreviousCustomCode2",

                      pOrigRecNo2."PreviousCustomCode3",

                      pOrigRecNo2."PreviousCustomCode4",

                      pOrigRecNo2."PreviousCustomCode5",

                      pOrigRecNo2."PreviousCustomCode6",

                      pOrigRecNo2."PreviousCustomCode7",

                      pOrigRecNo2."PreviousCustomCode8",

                      pOrigRecNo2."PreviousCustomCode9",

                      pOrigRecNo2."PreviousCustomCode10",

                      pOrigRecNo2."PreviousDepartment",

                      pOrigRecNo2."GroupBy1Value",

                      pOrigRecNo2."GroupBy2Value",

                      pOrigRecNo2."PreviousGroupBy1Value",

                      pOrigRecNo2."PreviousGroupBy2Value"

                     );



            end loop pAllocatH;

            

          end if;

          

        end if;



      end if;

    

      --

      -- reset vAmount variable to zero

      --

      vStep := 490;

      

      vAmount := 0;



    end loop pOrigRecNo2;



    --

    -- clear temporary table 2

    --

    vStep := 500;

    

    delete from global_temp_alloc2;

    

    --

    -- clear temporary table 3

    --

    vStep := 510;

    

    delete from global_temp_alloc3;



    --

    -- delete duplicates from temporary table 4

    --

    vStep := 515;



    delete from global_temp_alloc4 gta4c

    where 1=1

    and gta4c.ctid not in (select gta4b."RowID"

                            from (select

                                    gta4.ctid "RowID",

                                    (row_number() over (partition by

                                                          gta4."AllocatH",

                                                          gta4."PayType",

                                                          gta4."TrxType",

                                                          gta4."TrxId",

                                                          gta4."TrxTreatment",

                                                          gta4."Amount",

                                                          gta4."AllocateLink",

                                                          gta4."TxHistoryId",

                                                          gta4."PmtHistoryId",

                                                          gta4."OrigRecNo",

                                                          gta4."History",

                                                          gta4."HistoryType",

                                                          gta4."Patient",

                                                          gta4."TxModifiedDate",

                                                          gta4."Payed",

                                                          gta4."InsPayed",

                                                          gta4."PtAdj",

                                                          gta4."InsAdj",

                                                          gta4."InsTransfer",

                                                          gta4."Discipline",

                                                          gta4."Procedure",

                                                          gta4."Practice",

                                                          gta4."ClaimDoctor",

                                                          gta4."Location",

                                                          gta4."EntryUser",

                                                          gta4."AppUser",

                                                          gta4."Custom1",

                                                          gta4."Custom2",

                                                          gta4."Producer",

                                                          gta4."TypeCode",

                                                          gta4."PGroup",

                                                          gta4."Year",

                                                          gta4."CustomCode1",

                                                          gta4."CustomCode2",

                                                          gta4."CustomCode3",

                                                          gta4."CustomCode4",

                                                          gta4."CustomCode5",

                                                          gta4."CustomCode6",

                                                          gta4."CustomCode7",

                                                          gta4."CustomCode8",

                                                          gta4."CustomCode9",

                                                          gta4."CustomCode10",

                                                          gta4."Department",

                                                          gta4."HistoryTypeDescription",

                                                          gta4."GroupBy1",

                                                          gta4."GroupBy2",

                                                          gta4."PreviousHistory",

                                                          gta4."PreviousDiscipline",

                                                          gta4."PreviousProcedure",

                                                          gta4."PreviousPractice",

                                                          gta4."PreviousClaimDoctor",

                                                          gta4."PreviousLocation",

                                                          gta4."PreviousEntryUser",

                                                          gta4."PreviousAppUser",

                                                          gta4."PreviousCustom1",

                                                          gta4."PreviousCustom2",

                                                          gta4."PreviousProducer",

                                                          gta4."PreviousTypeCode",

                                                          gta4."PreviousPGroup",

                                                          gta4."PreviousYear",

                                                          gta4."PreviousCustomCode1",

                                                          gta4."PreviousCustomCode2",

                                                          gta4."PreviousCustomCode3",

                                                          gta4."PreviousCustomCode4",

                                                          gta4."PreviousCustomCode5",

                                                          gta4."PreviousCustomCode6",

                                                          gta4."PreviousCustomCode7",

                                                          gta4."PreviousCustomCode8",

                                                          gta4."PreviousCustomCode9",

                                                          gta4."PreviousCustomCode10",

                                                          gta4."PreviousDepartment",

                                                          gta4."GroupBy1Value",

                                                          gta4."GroupBy2Value",

                                                          gta4."PreviousGroupBy1Value",

                                                          gta4."PreviousGroupBy2Value"

                                                        order by

                                                          gta4."AllocatH",

                                                          gta4."PayType",

                                                          gta4."TrxType",

                                                          gta4."TrxId",

                                                          gta4."TrxTreatment",

                                                          gta4."Amount",

                                                          gta4."AllocateLink",

                                                          gta4."TxHistoryId",

                                                          gta4."PmtHistoryId",

                                                          gta4."OrigRecNo",

                                                          gta4."History",

                                                          gta4."HistoryType",

                                                          gta4."Patient",

                                                          gta4."TxModifiedDate",

                                                          gta4."Payed",

                                                          gta4."InsPayed",

                                                          gta4."PtAdj",

                                                          gta4."InsAdj",

                                                          gta4."InsTransfer",

                                                          gta4."Discipline",

                                                          gta4."Procedure",

                                                          gta4."Practice",

                                                          gta4."ClaimDoctor",

                                                          gta4."Location",

                                                          gta4."EntryUser",

                                                          gta4."AppUser",

                                                          gta4."Custom1",

                                                          gta4."Custom2",

                                                          gta4."Producer",

                                                          gta4."TypeCode",

                                                          gta4."PGroup",

                                                          gta4."Year",

                                                          gta4."CustomCode1",

                                                          gta4."CustomCode2",

                                                          gta4."CustomCode3",

                                                          gta4."CustomCode4",

                                                          gta4."CustomCode5",

                                                          gta4."CustomCode6",

                                                          gta4."CustomCode7",

                                                          gta4."CustomCode8",

                                                          gta4."CustomCode9",

                                                          gta4."CustomCode10",

                                                          gta4."Department",

                                                          gta4."HistoryTypeDescription",

                                                          gta4."GroupBy1",

                                                          gta4."GroupBy2",

                                                          gta4."PreviousHistory",

                                                          gta4."PreviousDiscipline",

                                                          gta4."PreviousProcedure",

                                                          gta4."PreviousPractice",

                                                          gta4."PreviousClaimDoctor",

                                                          gta4."PreviousLocation",

                                                          gta4."PreviousEntryUser",

                                                          gta4."PreviousAppUser",

                                                          gta4."PreviousCustom1",

                                                          gta4."PreviousCustom2",

                                                          gta4."PreviousProducer",

                                                          gta4."PreviousTypeCode",

                                                          gta4."PreviousPGroup",

                                                          gta4."PreviousYear",

                                                          gta4."PreviousCustomCode1",

                                                          gta4."PreviousCustomCode2",

                                                          gta4."PreviousCustomCode3",

                                                          gta4."PreviousCustomCode4",

                                                          gta4."PreviousCustomCode5",

                                                          gta4."PreviousCustomCode6",

                                                          gta4."PreviousCustomCode7",

                                                          gta4."PreviousCustomCode8",

                                                          gta4."PreviousCustomCode9",

                                                          gta4."PreviousCustomCode10",

                                                          gta4."PreviousDepartment",

                                                          gta4."GroupBy1Value",

                                                          gta4."GroupBy2Value",

                                                          gta4."PreviousGroupBy1Value",

                                                          gta4."PreviousGroupBy2Value")) "RowNumber"

                                  from global_temp_alloc4 gta4

                                  where 1=1

                                  and gta4."OrigRecNo" = gta4c."OrigRecNo") gta4b

                            where 1=1

                            and gta4b."RowNumber" = 1)

    and gta4c."OrigRecNo" = pOrigRecNo."OrigRecNo";

    

  end loop pOrigRecNo;

    

  --

  -- remove unnecessary records

  --

  vStep := 520;

  

  delete from global_temp_alloc4 gta4

  where 1=1

  and (

       -- remove records that are not for the department (transfer in)  

       (gta4."HistoryTypeDescription" = vTransferIn

        and gta4."PreviousDepartment" = vDepartment

        and gta4."Department" <> vDepartment)

       or

       -- remove records that are not for the department (transfer out)

       (gta4."HistoryTypeDescription" = vTransferOut

        and gta4."PreviousDepartment" <> vDepartment

        and gta4."Department" = vDepartment)

       or

       -- remove records that are not for the department

       (gta4."PreviousDepartment" <> vDepartment

        and gta4."Department" <> vDepartment)

       or

       -- remove allocate type duplicate records (i.e.: TxHistoryId <> History)

       (gta4."TxHistoryId" <> gta4."History"

        and gta4."HistoryType" = 3)

        -- remove records allocated after the reporting period end date

        or exists (select null

                   from allocath ah4

                   where 1=1

                   and ah4."ModifiedDate" > vToDate

                   and ah4."AllocatH" = gta4."AllocatH")

      ); 



  --

  -- update "PreviousHistory" column with actual previous History ID

  --

  vStep := 530;

  

  update global_temp_alloc4 gta4

  set gta4."PreviousHistory" = (select nvl(max(h."History"), 0)

                                from history h

                                where 1=1

                                and h."History" < gta4."History"

                                and h."OrigRecNo" = gta4."OrigRecNo")

  where 1=1;



  --

  -- return cursor values from the view GLOBAL_TEMP_ALLOC_V (records that are within the reporting period only)

  --

  vStep := 540;



  open pRefCursor for

    select

      max(gtav."AllocatH") "AllocatH",

      gtav."PayType",

      gtav."TrxType",

      gtav."TrxId",

      gtav."TrxTreatment",

      sum(gtav."Amount") "Amount",

      max(gtav."AllocateLink") "AllocateLink",

      gtav."TxHistoryId",

      gtav."PmtHistoryId",

      gtav."OrigRecNo",

      gtav."History",

      gtav."HistoryType",

      gtav."Patient",

      gtav."TxModifiedDate",

      gtav."Payed",

      gtav."InsPayed",

      gtav."PtAdj",

      gtav."InsAdj",

      gtav."InsTransfer",

      gtav."Discipline",

      gtav."Procedure",

      gtav."Practice",

      gtav."ClaimDoctor",

      gtav."Location",

      gtav."EntryUser",

      gtav."AppUser",

      gtav."Custom1",

      gtav."Custom2",

      gtav."Producer",

      gtav."TypeCode",

      gtav."PGroup",

      gtav."Year",

      gtav."CustomCode1",

      gtav."CustomCode2",

      gtav."CustomCode3",

      gtav."CustomCode4",

      gtav."CustomCode5",

      gtav."CustomCode6",

      gtav."CustomCode7",

      gtav."CustomCode8",

      gtav."CustomCode9",

      gtav."CustomCode10",

      gtav."Department",

      gtav."HistoryTypeDescription",

      gtav."GroupBy1",

      gtav."GroupBy2",

      gtav."PreviousHistory",

      gtav."PreviousDiscipline",

      gtav."PreviousProcedure",

      gtav."PreviousPractice",

      gtav."PreviousPracticeName",

      gtav."PreviousClaimDoctor",

      gtav."PreviousLocation",

      gtav."PreviousEntryUser",

      gtav."PreviousEntryUserLogon",

      gtav."PreviousEntryUserFirstName",

      gtav."PreviousEntryUserLastName",

      gtav."PreviousAppUser",

      gtav."PreviousAppUserLogon",

      gtav."PreviousAppUserFirstName",

      gtav."PreviousAppUserLastName",

      gtav."PreviousCustom1",

      gtav."PreviousCustom2",

      gtav."PreviousProducer",

      gtav."PreviousProducerFirstName",

      gtav."PreviousProducerMiddleName",

      gtav."PreviousProducerLastName",

      gtav."PreviousTypeCode",

      gtav."PreviousTypeCodeDescription",

      gtav."PreviousPGroup",

      gtav."PreviousYear",

      gtav."PreviousCustomCode1",

      gtav."PreviousCustomCode2",

      gtav."PreviousCustomCode3",

      gtav."PreviousCustomCode4",

      gtav."PreviousCustomCode5",

      gtav."PreviousCustomCode6",

      gtav."PreviousCustomCode7",

      gtav."PreviousCustomCode8",

      gtav."PreviousCustomCode9",

      gtav."PreviousCustomCode10",

      gtav."PreviousDepartment",

      gtav."PreviousPayed",

      gtav."PreviousInsPayed",

      gtav."PreviousPtAdj",

      gtav."PreviousInsAdj",

      gtav."GroupBy1Value",

      gtav."GroupBy2Value",

      gtav."PreviousGroupBy1Value",

      gtav."PreviousGroupBy2Value",

      gtav."TxPracticeName",

      gtav."TxTypeCodeDescription",

      gtav."TxPGroupDescription",

      gtav."TxProducerFirstName",

      gtav."TxProducerMiddleName",

      gtav."TxProducerLastName",

      gtav."TxEntryUserLogon",

      gtav."TxEntryUserFirstName",

      gtav."TxEntryUserLastName",

      gtav."TxAppUserLogon",

      gtav."TxAppUserFirstName",

      gtav."TxAppUserLastName",

      gtav."TxPatientChart",

      gtav."TxPatientFirstName",

      gtav."TxPatientMiddleName",

      gtav."TxPatientLastName",

      gtav."TxPatientPreferredName",

      gtav."TxDeptDescription",

      gtav."TxHistoryType",

      gtav."TxType",

      gtav."TxId",

      gtav."TxTreatment",

      gtav."TxOrigRecNo",

      gtav."TxFamily",

      gtav."TxStatus",

      gtav."TxDate",

      gtav."TxTreatmentDate",

      gtav."TxCode",

      gtav."TxCodeDescription",

      gtav."TxSite",

      gtav."TxSurface",

      gtav."TxTotal",

      gtav."TxInsTotal",

      gtav."TxCompany1",

      gtav."TxCompany1Name",

      gtav."TxPolicy1",

      gtav."TxAmount1",

      gtav."TxDescription",

      gtav."TxUser",

      gtav."TxAppDate",

      gtav."TxStationId",

      gtav."TxCustom3",

      gtav."TxCustom4",

      gtav."TxCustomaryTotal",

      gtav."PmtHistoryType",

      gtav."PmtType",

      gtav."PmtId",

      gtav."PmtTreatment",

      gtav."PmtOrigRecNo",

      gtav."PmtPatient",

      gtav."PmtFamily",

      gtav."PmtDate",

      gtav."PmtCode",

      gtav."PmtCodeDescription",

      gtav."PmtTotal",

      gtav."PmtInsTotal",

      gtav."PmtCompany1",

      gtav."PmtCompany1Name",

      gtav."PmtAmount1",

      gtav."PmtDescription",

      gtav."PmtBank",

      gtav."PmtPayed",

      gtav."PmtInsPayed",

      gtav."PmtPtAdj",

      gtav."PmtInsAdj",

      gtav."PmtModifiedDate",

      gtav."PmtPatientFirstName",

      gtav."PmtPatientMiddleName",

      gtav."PmtPatientLastName",

      gtav."PmtPatientPreferredName",

      vBatch "Batch"

    from global_temp_alloc_v gtav

    where 1=1

    and gtav."TxModifiedDate" >= vFromDate

    and gtav."TxModifiedDate" <= vToDate

    group by

      gtav."PayType",

      gtav."TrxType",

      gtav."TrxId",

      gtav."TrxTreatment",

      gtav."TxHistoryId",

      gtav."PmtHistoryId",

      gtav."OrigRecNo",

      gtav."History",

      gtav."HistoryType",

      gtav."Patient",

      gtav."TxModifiedDate",

      gtav."Payed",

      gtav."InsPayed",

      gtav."PtAdj",

      gtav."InsAdj",

      gtav."InsTransfer",

      gtav."Discipline",

      gtav."Procedure",

      gtav."Practice",

      gtav."ClaimDoctor",

      gtav."Location",

      gtav."EntryUser",

      gtav."AppUser",

      gtav."Custom1",

      gtav."Custom2",

      gtav."Producer",

      gtav."TypeCode",

      gtav."PGroup",

      gtav."Year",

      gtav."CustomCode1",

      gtav."CustomCode2",

      gtav."CustomCode3",

      gtav."CustomCode4",

      gtav."CustomCode5",

      gtav."CustomCode6",

      gtav."CustomCode7",

      gtav."CustomCode8",

      gtav."CustomCode9",

      gtav."CustomCode10",

      gtav."Department",

      gtav."HistoryTypeDescription",

      gtav."GroupBy1",

      gtav."GroupBy2",

      gtav."PreviousHistory",

      gtav."PreviousDiscipline",

      gtav."PreviousProcedure",

      gtav."PreviousPractice",

      gtav."PreviousPracticeName",

      gtav."PreviousClaimDoctor",

      gtav."PreviousLocation",

      gtav."PreviousEntryUser",

      gtav."PreviousEntryUserLogon",

      gtav."PreviousEntryUserFirstName",

      gtav."PreviousEntryUserLastName",

      gtav."PreviousAppUser",

      gtav."PreviousAppUserLogon",

      gtav."PreviousAppUserFirstName",

      gtav."PreviousAppUserLastName",

      gtav."PreviousCustom1",

      gtav."PreviousCustom2",

      gtav."PreviousProducer",

      gtav."PreviousProducerFirstName",

      gtav."PreviousProducerMiddleName",

      gtav."PreviousProducerLastName",

      gtav."PreviousTypeCode",

      gtav."PreviousTypeCodeDescription",

      gtav."PreviousPGroup",

      gtav."PreviousYear",

      gtav."PreviousCustomCode1",

      gtav."PreviousCustomCode2",

      gtav."PreviousCustomCode3",

      gtav."PreviousCustomCode4",

      gtav."PreviousCustomCode5",

      gtav."PreviousCustomCode6",

      gtav."PreviousCustomCode7",

      gtav."PreviousCustomCode8",

      gtav."PreviousCustomCode9",

      gtav."PreviousCustomCode10",

      gtav."PreviousDepartment",

      gtav."PreviousPayed",

      gtav."PreviousInsPayed",

      gtav."PreviousPtAdj",

      gtav."PreviousInsAdj",

      gtav."GroupBy1Value",

      gtav."GroupBy2Value",

      gtav."PreviousGroupBy1Value",

      gtav."PreviousGroupBy2Value",

      gtav."TxPracticeName",

      gtav."TxTypeCodeDescription",

      gtav."TxPGroupDescription",

      gtav."TxProducerFirstName",

      gtav."TxProducerMiddleName",

      gtav."TxProducerLastName",

      gtav."TxEntryUserLogon",

      gtav."TxEntryUserFirstName",

      gtav."TxEntryUserLastName",

      gtav."TxAppUserLogon",

      gtav."TxAppUserFirstName",

      gtav."TxAppUserLastName",

      gtav."TxPatientChart",

      gtav."TxPatientFirstName",

      gtav."TxPatientMiddleName",

      gtav."TxPatientLastName",

      gtav."TxPatientPreferredName",

      gtav."TxDeptDescription",

      gtav."TxHistoryType",

      gtav."TxType",

      gtav."TxId",

      gtav."TxTreatment",

      gtav."TxOrigRecNo",

      gtav."TxFamily",

      gtav."TxStatus",

      gtav."TxDate",

      gtav."TxTreatmentDate",

      gtav."TxCode",

      gtav."TxCodeDescription",

      gtav."TxSite",

      gtav."TxSurface",

      gtav."TxTotal",

      gtav."TxInsTotal",

      gtav."TxCompany1",

      gtav."TxCompany1Name",

      gtav."TxPolicy1",

      gtav."TxAmount1",

      gtav."TxDescription",

      gtav."TxUser",

      gtav."TxAppDate",

      gtav."TxStationId",

      gtav."TxCustom3",

      gtav."TxCustom4",

      gtav."TxCustomaryTotal",

      gtav."PmtHistoryType",

      gtav."PmtType",

      gtav."PmtId",

      gtav."PmtTreatment",

      gtav."PmtOrigRecNo",

      gtav."PmtPatient",

      gtav."PmtFamily",

      gtav."PmtDate",

      gtav."PmtCode",

      gtav."PmtCodeDescription",

      gtav."PmtTotal",

      gtav."PmtInsTotal",

      gtav."PmtCompany1",

      gtav."PmtCompany1Name",

      gtav."PmtAmount1",

      gtav."PmtDescription",

      gtav."PmtBank",

      gtav."PmtPayed",

      gtav."PmtInsPayed",

      gtav."PmtPtAdj",

      gtav."PmtInsAdj",

      gtav."PmtModifiedDate",

      gtav."PmtPatientFirstName",

      gtav."PmtPatientMiddleName",

      gtav."PmtPatientLastName",

      gtav."PmtPatientPreferredName",

      vBatch;



  --

  -- update processing end date/time (will be performed again inside the Crystal report)

  --

  vStep := 550;

  

  update ar_recon_saved_data_hdr

  set "EndDateTime" = sysdate

  where 1=1

  and "Batch" = vBatch;



  --

  -- save changes

  --

  vStep := 560;

  

  commit;



  --

  -- clear temporary tables 1, 2 and 3

  --

  vStep := 570;



  execute immediate 'truncate table global_temp_alloc1';

  execute immediate 'truncate table global_temp_alloc2';

  execute immediate 'truncate table global_temp_alloc3';



exception

  when others then

    --

    -- log error then rollback

    --

--    vStep := 570;

    

    ax_pkg.LogEvent_P((trim('ALLOC_PKG') || '.CreateAllocTxs_P'), (trim(sqlerrm) || ' (Error at step ' || vStep || ')')); -- AX-39259

    

    rollback;

    

end CreateAllocTxs_P;



PROCEDURE returnbatchid_p(INOUT prefcursor cursor_pkg.weakcursor, IN pbatch numeric) IS



  vStep integer := 0;

  

begin

  --

  -- update processing end date/time

  --

  vStep := 10;

  

  update ar_recon_saved_data_hdr

  set "EndDateTime" = sysdate

  where 1=1

  and "Batch" = pBatch;



  --

  -- save changes

  --

  vStep := 20;

  

  commit;



  --

  -- clear temporary tables 1, 2 and 3

  --

  vStep := 30;



  execute immediate 'truncate table global_temp_alloc1';

  execute immediate 'truncate table global_temp_alloc2';

  execute immediate 'truncate table global_temp_alloc3';



  --

  -- open cursor

  --

  vStep := 40;

  

  open pRefCursor for

    select pBatch "Batch"

    from dual

    where 1=1;

    

exception

  when others then

    --

    -- log error then rollback

    --

--    vStep := 50;

    

    ax_pkg.LogEvent_P((trim('ALLOC_PKG') || '.ReturnBatchID_P'), (trim(sqlerrm) || ' (Error at step ' || vStep || ')')); -- AX-39259

    

    rollback;



end ReturnBatchID_P;



END;
CREATE OR REPLACE PACKAGE BODY ar_dept_pkg IS



/* Original (before AX-30762)

--

-- create function to get the department

--

function ar_get_dept_f (pDepartment char,

                        pHistory number,

                        pProducer char,

                        pPatient number) return char

--

-- AX-27025    rpc Modified Jun. 23, 2022 - Modified to eliminate the error "ORA-06502: PL/SQL: numeric or value error: number precision too large"

--                                        - if there are too many department definition entries (DEPTDEF) for a department (DEPT)

--

is



  cursor cSQLStmt is

    select

      "Department",

      "Type",

      table_name,

      column_name,

      condition,

      count(*) over (partition by "Department", "Type") condition_count,

      'and ' || column_name || condition || chr(13) || chr(10) "Stmt"

    from (select

            dd."Department",

            dd."Type",

            case

              when dd."Type" between 0 and 8 then

                'history h'

              when dd."Type" between 9 and 12 then      

                'producer prod'

              when dd."Type" between 13 and 22 then

                'patient pat'

              else 'DUAL'

            end table_name,

            case

              when dd."Type" = 0 then

                'h."Discipline"'

              when dd."Type" = 1 then

                'h."Procedure"'

              when dd."Type" = 2 then

                'h."Practice"'

              when dd."Type" = 3 then

                'h."ClaimDoctor"'

              when dd."Type" = 4 then

                'h."Location"'

              when dd."Type" = 5 then

                'h."EntryUser"'

              when dd."Type" = 6 then

                'h."AppUser"'

              when dd."Type" = 7 then

                'h."Custom1"'

              when dd."Type" = 8 then

                'h."Custom2"'

              when dd."Type" = 9 then

                'h."Producer"'

              when dd."Type" = 10 and dd."Condition" = 2 then			--AX-7995.10620

                '(prod."TypeCode"'

              when dd."Type" = 10 then

                'prod."TypeCode"'

              when dd."Type" = 11 and dd."Condition" = 2 then			--AX-7995.10620

                '(prod."PGroup"'

              when dd."Type" = 11 then

                'prod."PGroup"'

              when dd."Type" = 12 and dd."Condition" = 2 then			--AX-7995.10620	

                '(prod."Year"'

              when dd."Type" = 12 then

                'prod."Year"'

              when dd."Type" = 13 then

                'pat."CustomCode1"'

              when dd."Type" = 14 then

                'pat."CustomCode2"'

              when dd."Type" = 15 then

                'pat."CustomCode3"'

              when dd."Type" = 16 then

                'pat."CustomCode4"'

              when dd."Type" = 17 then

                'pat."CustomCode5"'

              when dd."Type" = 18 then

                'pat."CustomCode6"'

              when dd."Type" = 19 then

                'pat."CustomCode7"'

              when dd."Type" = 20 then

                'pat."CustomCode8"'

              when dd."Type" = 21 then

                'pat."CustomCode9"'

              when dd."Type" = 22 then

                'pat."CustomCode10"'

              else '1'

            end column_name,

            case

              when dd."Condition" = 0 then

                ' = ' || '''' || "Criteria1" || ''''

              when dd."Condition" = 2 and dd."Type" = 10 then										--AX-7995.10620

				' <> ' || '''' || "Criteria1" || ''' OR (TRIM (prod."TypeCode") IS NULL OR length(TRIM (prod."TypeCode")) = 0)) '

              when dd."Condition" = 2 and dd."Type" = 11 then										--AX-7995.10620

				' <> ' || '''' || "Criteria1" || ''' OR (TRIM (prod."PGroup") IS NULL OR length(TRIM (prod."PGroup")) = 0)) '

              when dd."Condition" = 2 and dd."Type" = 12 then										--AX-7995.10620

				' <> ' || '''' || "Criteria1" || ''' OR (TRIM (prod."Year") IS NULL OR length(TRIM (prod."Year")) = 0)) '

              when dd."Condition" = 2 then

				' <> ' || '''' || "Criteria1" || ''''

              when dd."Condition" = 1 then

                ' between ' || '''' || dd."Criteria1" || ''' and ' || '''' || dd."Criteria2" || ''''

              else '=1'

            end condition

          from 

            deptdef dd,

            dept d

          where 1=1

          and dd."Department" = d."Department"

          and d."Department" = pDepartment

          order by

            d."Department",

            dd."Type",

            dd."Condition"

         )

    where 1=1;

    

--  vOrigSQLStmt  VARCHAR2(4000) := 'select :1                              -- AX-27025 

  vOrigSQLStmt  VARCHAR2(32767) :=

'select *+ index(h HISTORY_PRIMARY)

            index(prod PRODUCER_PRIMARY)

            index(pat PATIENT_PRIMARY) * :1

from

  history h,

  producer prod,

  patient pat

where 1=1

and h."Producer" = prod."Producer" (+)

and h."Patient" = pat."Patient"

and h."History" = :2

and h."Producer" = :3

and pat."Patient" = :4

';



--  vSQLStmt  VARCHAR2(4000);                                               -- AX-27025

--  vTmpSQLStmt  VARCHAR2(4000);                                            -- AX-27025

  vSQLStmt  VARCHAR2(32767);

  vTmpSQLStmt  VARCHAR2(32767);



  vDepartment dept."Department"%type := 'zzzzzz';    

  vOldDepartment dept."Department"%type;

  vOldType deptdef."Type"%type;

  

--  vOldConditionCount number(2) := 1;

--  vEnteredOR number(1) := 0;

  vOldConditionCount integer := 1;                                       -- AX-27025

  vEnteredOR integer := 0;                                               -- AX-27025

  

--  v_step number(2) := 0;                                                      -- AX-27025

  v_step integer := 0;



begin

  --

  -- return department if department = 'zzzzzz'

  --

  v_step := 10;

  

  if (trim(pDepartment) = 'zzzzzz') then

    return vDepartment;

  end if;

  

  --

  -- create SQL script to get the department

  --

  v_step := 20;

  

  for pSQLStmt in cSQLStmt loop

        

      vTmpSQLStmt := pSQLStmt."Stmt";

      

      if ((vOldConditionCount = 1) and  (pSQLStmt.condition_count > 1)) then

        --vTmpSQLStmt := replace(vTmpSQLStmt, 'and ', 'and (' || chr(13) || chr(10));

        vTmpSQLStmt := replace(replace(vTmpSQLStmt, 'and ', 'and (' || chr(13) || chr(10)), ' and (' || chr(13) || chr(10), ' and ');     -- E134137        

      end if;

            

      if ((vOldDepartment = pSQLStmt."Department") and (vOldType = pSQLStmt."Type")) then

      

        -- AX-10872

        if (pSQLStmt."Type" <> 10) then

          vTmpSQLStmt := replace(replace(vTmpSQLStmt, 'and ', 'or '), ' or ', ' and ');

        end if;

        

        vEnteredOR := 1;

        

      else

      

        if (vEnteredOR = 1) then

      

          if (pSQLStmt.condition_count > 1) then

            --vTmpSQLStmt := replace(vTmpSQLStmt, 'and ', 'and (' || chr(13) || chr(10));

            vTmpSQLStmt := replace(replace(vTmpSQLStmt, 'and ', 'and (' || chr(13) || chr(10)), ' and (' || chr(13) || chr(10), ' and ');     -- E134137                    

          end if;

          

          vTmpSQLStmt := ') '|| chr(13) || chr(10) || vTmpSQLStmt;

          vEnteredOR := 0;

          vOldConditionCount := 1;

          

        end if;

        

      end if;

      

      vSQLStmt := vSQLStmt || vTmpSQLStmt;

      

      vOldDepartment := pSQLStmt."Department";

      vOldType := pSQLStmt."Type";

      

      vOldConditionCount := pSQLStmt.condition_count;



  end loop;



  if (vEnteredOR = 1) then

    vSQLStmt := vSQLStmt || ')';

  end if;

  

  vTmpSQLStmt := vSQLStmt;

  vSQLStmt := vOrigSQLStmt || vSQLStmt;



  --

  -- return where clause SQL script if pHistory, pProducer and pPatient are zero (0)

  --

  v_step := 30;

  

  if ((pHistory = 0) and (pProducer is null) and (pPatient = 0)) then

    return (vTmpSQLStmt);

  end if;

 

  --

  -- execute SQL script to get the department

  --

  begin

    --

    -- get department

    --

    v_step := 40;

  

    execute immediate vSQLStmt into vDepartment using pDepartment,

                                                      pHistory,

                                                      pProducer,

                                                      pPatient;

                                                          

  exception

    when no_data_found then

    --

    -- assign 'zzzzzz' department

    --

    v_step := 50;



    vDepartment := 'zzzzzz';

  end;

  

  --

  -- return department

  --

  v_step := 60;



  return vDepartment;



exception

  when others then

    --

    -- log error to AX_LOG table

    -- 

--    v_step := 70;

    

    ax_pkg.LogEvent_P(trim('AR_DEPT_PKG')||'.ar_get_dept_f', trim(sqlerrm)||' (Error at step '||v_step||')'); -- AX-39259

 

end ar_get_dept_f;

*/



FUNCTION ar_get_dept_f(pdepartment character, phistory numeric, pproducer character, ppatient numeric) RETURN character IS



  cursor cSQLStmt (pDepartment2 dept."Department"%type) is

    select (listagg(ddd2."Stmt", (chr(13) || chr(10))) within group (order by

                                                                       ddd2."Condition2",

                                                                       ddd2."Type",

                                                                       ddd2."RowNumber")) "Stmt"

    from (

          select

            ddd."Condition2",

            ddd."Type",

            ddd."RowNumber",

            (case

               when (ddd."Condition2" = 2) then

                 ('and ' || ddd."ColumnName" || ddd."ConditionText")

               when (ddd."RowCount" = 1) then

                 ('and ' || ddd."ColumnName" || ddd."ConditionText")

               else

                 decode(ddd."RowNumber", 1, ('and (' || ddd."ColumnName" || ddd."ConditionText"),

                                            ('or ' || ddd."ColumnName" || ddd."ConditionText" || decode(ddd."RowNumber", ddd."RowCount", ')', '')))

             end) "Stmt"

          from (

                select

                  -- start: AX-30762

                  decode(dd."Condition", 2, 2, 1) "Condition2",

                  dd."Type",

                  (row_number() over (partition by

                                        decode(dd."Condition", 2, 2, 1),

                                        dd."Type"

                                      order by                                  

                                        dd."Criteria1",

                                        dd."Criteria2")) "RowNumber",

                  (count(*) over (partition by

                                    decode(dd."Condition", 2, 2, 1),

                                    dd."Type")) "RowCount",                 

                  -- end: AX-30762

                  (case

                     when (dd."Type" = 0) then

                       'h."Discipline"'

                     when (dd."Type" = 1) then

                       'h."Procedure"'

                     when (dd."Type" = 2) then

                       'h."Practice"'

                     when (dd."Type" = 3) then

                       'h."ClaimDoctor"'

                     when (dd."Type" = 4) then

                       'h."Location"'

                     when (dd."Type" = 5) then

                       'h."EntryUser"'

                     when (dd."Type" = 6) then

                       'h."AppUser"'

                     when (dd."Type" = 7) then

                       'h."Custom1"'

                     when (dd."Type" = 8) then

                       'h."Custom2"'

                     when (dd."Type" = 9) then

                       'h."Producer"'

                     when ((dd."Type" = 10) and (dd."Condition" = 2)) then			--AX-7995.10620

                       '(prod."TypeCode"'

                     when (dd."Type" = 10) then

                       'prod."TypeCode"'

                     when ((dd."Type" = 11) and (dd."Condition" = 2)) then			--AX-7995.10620

                       '(prod."PGroup"'

                     when (dd."Type" = 11) then

                       'prod."PGroup"'

                     when ((dd."Type" = 12) and (dd."Condition" = 2)) then			--AX-7995.10620	

                       '(prod."Year"'

                     when (dd."Type" = 12) then

                       'prod."Year"'

                     when (dd."Type" = 13) then

                       'pat."CustomCode1"'

                     when (dd."Type" = 14) then

                       'pat."CustomCode2"'

                     when (dd."Type" = 15) then

                       'pat."CustomCode3"'

                     when (dd."Type" = 16) then

                       'pat."CustomCode4"'

                     when (dd."Type" = 17) then

                       'pat."CustomCode5"'

                     when (dd."Type" = 18) then

                       'pat."CustomCode6"'

                     when (dd."Type" = 19) then

                       'pat."CustomCode7"'

                     when (dd."Type" = 20) then

                       'pat."CustomCode8"'

                     when (dd."Type" = 21) then

                       'pat."CustomCode9"'

                     when (dd."Type" = 22) then

                       'pat."CustomCode10"'

                     else

                       '1'

                   end) "ColumnName",

                  (case

                     -- start: AX-30762 (avoid explicit datatype conversion)

                     when ((dd."Condition" = 0) and ((dd."Type" = 2) or (dd."Type" = 5) or (dd."Type" = 6) or (dd."Type" = 12))) then

                       ' = ' || "Criteria1"

                     when ((dd."Condition" = 1) and ((dd."Type" = 2) or (dd."Type" = 5) or (dd."Type" = 6) or (dd."Type" = 12))) then

                       ' between ' || dd."Criteria1" || ' and ' || dd."Criteria2"

                     when ((dd."Condition" = 2) and ((dd."Type" = 2) or (dd."Type" = 5) or (dd."Type" = 6))) then

	  			             ' <> ' || "Criteria1"  

                     -- end: AX-30762 (avoid explicit datatype conversion)                    

                     when (dd."Condition" = 0) then

                       ' = ' || '''' || "Criteria1" || ''''

                     when (dd."Condition" = 1) then

                       ' between ' || '''' || dd."Criteria1" || ''' and ' || '''' || dd."Criteria2" || ''''

                     when ((dd."Condition" = 2) and (dd."Type" = 10)) then										--AX-7995.10620

	 	      		         ' <> ' || '''' || "Criteria1" || ''' or (trim(prod."TypeCode") is null OR length(trim(prod."TypeCode")) = 0))'

                     when ((dd."Condition" = 2) and (dd."Type" = 11)) then										--AX-7995.10620

		 	 	               ' <> ' || '''' || "Criteria1" || ''' or (trim(prod."PGroup") is null OR length(trim(prod."PGroup")) = 0))'

                     when ((dd."Condition" = 2) and (dd."Type" = 12)) then										--AX-7995.10620

		     	 	           ' <> ' || "Criteria1" || ' or (trim(prod."Year") is null OR length(trim(prod."Year")) = 0))'   --AX-30762

                     when (dd."Condition" = 2) then

 			                 ' <> ' || '''' || "Criteria1" || ''''               

                     else '=1'

                   end) "ConditionText"

                from

                  deptdef dd,

                  dept d

                where 1=1

                and dd."Department" = d."Department"

                and d."Department" = pDepartment2

                order by

                  1,

                  2,

                  3,

                  dd."Criteria1",

                  dd."Criteria2"

               ) ddd

         where 1=1) ddd2

    where 1=1;



  vOrigSQLStmt  VARCHAR2(32767) :=

'select /*+ index(h HISTORY_PRIMARY)

            index(prod PRODUCER_PRIMARY)

            index(pat PATIENT_PRIMARY) */ :1

from

  history h,

  producer prod,

  patient pat

where 1=1

and h."Producer" = prod."Producer" (+)

and h."Patient" = pat."Patient"

and h."History" = :2

and h."Producer" = :3

and pat."Patient" = :4

';



  vTmpSQLStmt  VARCHAR2(32767);

  vDepartment dept."Department"%type := 'zzzzzz';  

  vStep integer := 0;



begin

  --

  -- return department if department = 'zzzzzz'

  --

  vStep := 10;

  

  if (trim(pDepartment) = 'zzzzzz') then

    return vDepartment;

  end if;

  

  --

  -- create SQL script to get the department

  --

  vStep := 20;



  for pSQLStmt in cSQLStmt (pDepartment) loop

    --

    -- compose the where clause to be added to the original statement

    --

    vStep := 30;

    

    vTmpSQLStmt := (vTmpSQLStmt || pSQLStmt."Stmt");

    

  end loop;



  --

  -- concatenate where clause to the original SQL

  --

  vStep := 40;

  

  vOrigSQLStmt := (vOrigSQLStmt || vTmpSQLStmt);

  

  --

  -- return where clause SQL script if pHistory, pProducer and pPatient are zero (0)

  --

  vStep := 50;



  if ((pHistory = 0) and (pProducer is null OR pProducer = '') and (pPatient = 0)) then

    return (vTmpSQLStmt);

  end if;

 

  --

  -- execute SQL script to get the department

  --

  begin

    --

    -- get department

    --

    vStep := 60;



    execute immediate vOrigSQLStmt into vDepartment using pDepartment,

                                                          pHistory,

                                                          pProducer,

                                                          pPatient;



  exception

    when no_data_found then

    --

    -- assign 'zzzzzz' department

    --

    vStep := 70;



    vDepartment := 'zzzzzz';

    

  end;

  

  --

  -- return department

  --

  vStep := 80;



  return vDepartment;



exception

  when others then

    --

    -- log error to AX_LOG table

    -- 

    vStep := 90;

    

    ax_pkg.LogEvent_P(trim('AR_DEPT_PKG')||'.ar_get_dept_f', trim(sqlerrm)||' (Error at step ' || vStep || ')'); -- AX-39259



end ar_get_dept_f;



--

-- create function to return the group by description

--

FUNCTION ar_get_group_by_desc_f(pgroupby numeric) RETURN character IS



  vGroupByDesc history_ar_global_temp."ReportGroupBy1Description"%type := ' ';

  v_step number(2) := 0;

  

begin

  --

  -- return blank if no group by

  --

  v_step := 10;

  

  if (pGroupBy = 0) then

    return ' ';

  end if;

  

  --

  -- get group by description

  --

  v_step := 20;

  

  select

    case

      when (pGroupBy = 1) then 'Provider Code'

      when (pGroupBy = 2) then 'Provider Group'

      when (pGroupBy = 3) then 'Provider Type'

      when (pGroupBy = 4) then 'Provider Year'

      when (pGroupBy = 5) then 'Tx Approving Instructor'

      when (pGroupBy = 6) then 'Tx Notes 1'

      when (pGroupBy = 7) then 'Tx Notes 2'

      when (pGroupBy = 8) then 'Tx Discipline'

      when (pGroupBy = 9) then 'Tx Entry User'

      when (pGroupBy = 10) then 'Tx Facility'

      when (pGroupBy = 11) then 'Tx Fee Guide/Billing Dr'

      when (pGroupBy = 12) then 'Tx Practice'

      when (pGroupBy = 13) then 'Tx Procedure'

      when (pGroupBy between 14 and 23) then

        (select 'Pt '||"Description"

        from custtype

        where 1=1

        and "Type" = (pGroupBy - 14))

    else ' ' end

  into vGroupByDesc

  from dual;



  --

  -- return group by description

  --

  v_step := 30;

  

  return vGroupByDesc;

    

exception

  when others then

    --

    -- log error to AX_LOG table then return a single space

    -- 

--    v_step := 40;

    

    ax_pkg.LogEvent_P(trim('AR_DEPT_PKG')||'.ar_get_group_by_desc_f', trim(sqlerrm)||' (Error at step '||v_step||')'); -- AX-39259

    

    return ' ';

    

end ar_get_group_by_desc_f;



--

-- create function to return the group by column name

--

FUNCTION ar_get_group_by_column_name_f(pgroupby numeric, pisorigcolumnname numeric) RETURN character varying IS



  vGroupByColumnName  VARCHAR2(30) := 'NoGroupChange';

  v_step number(2) := 0;

  

begin  

  

  if (pIsOrigColumnName) = 1 then

    --

    -- get original column name

    --

    v_step := 10;

  

    select

      case

        when (pGroupBy = 0) then 'NoGroupChange'

        when (pGroupBy = 1) then 'Producer'

        when (pGroupBy = 2) then 'Producer_PGroup'

        when (pGroupBy = 3) then 'Producer_TypeCode'

        when (pGroupBy = 4) then 'Producer_Year'

        when (pGroupBy = 5) then 'AppUser'

        when (pGroupBy = 6) then 'Custom1'

        when (pGroupBy = 7) then 'Custom2'

        when (pGroupBy = 8) then 'Discipline'

        when (pGroupBy = 9) then 'EntryUser'

        when (pGroupBy = 10) then 'Location'

        when (pGroupBy = 11) then 'ClaimDoctor'

        when (pGroupBy = 12) then 'Practice'

        when (pGroupBy = 13) then 'Procedure'        

        when (pGroupBy = 14) then 'Patient_CustomCode1'

        when (pGroupBy = 15) then 'Patient_CustomCode2'

        when (pGroupBy = 16) then 'Patient_CustomCode3'

        when (pGroupBy = 17) then 'Patient_CustomCode4'

        when (pGroupBy = 18) then 'Patient_CustomCode5'

        when (pGroupBy = 19) then 'Patient_CustomCode6'

        when (pGroupBy = 20) then 'Patient_CustomCode7'

        when (pGroupBy = 21) then 'Patient_CustomCode8'

        when (pGroupBy = 22) then 'Patient_CustomCode9'

        when (pGroupBy = 23) then 'Patient_CustomCode10'

      else 'NoGroupChange' end

    into vGroupByColumnName

    from dual;

    

  else

    --

    -- get report column name

    --

    v_step := 20;

  

    select

      case

        when (pGroupBy = 0) then 'NoGroupChange'

        when (pGroupBy = 1) then 'ReportProducer'

        when (pGroupBy = 2) then 'ReportPGroup'

        when (pGroupBy = 3) then 'ReportTypeCode'

        when (pGroupBy = 4) then 'ReportYear'

        when (pGroupBy = 5) then 'ReportAppUser'

        when (pGroupBy = 6) then 'ReportCustom1'

        when (pGroupBy = 7) then 'ReportCustom2'

        when (pGroupBy = 8) then 'ReportDiscipline'

        when (pGroupBy = 9) then 'ReportEntryUser'

        when (pGroupBy = 10) then 'ReportLocation'

        when (pGroupBy = 11) then 'ReportClaimDoctor'

        when (pGroupBy = 12) then 'ReportPractice'

        when (pGroupBy = 13) then 'ReportProcedure'

        when (pGroupBy = 14) then 'ReportCustomCode1'

        when (pGroupBy = 15) then 'ReportCustomCode2'

        when (pGroupBy = 16) then 'ReportCustomCode3'

        when (pGroupBy = 17) then 'ReportCustomCode4'

        when (pGroupBy = 18) then 'ReportCustomCode5'

        when (pGroupBy = 19) then 'ReportCustomCode6'

        when (pGroupBy = 20) then 'ReportCustomCode7'

        when (pGroupBy = 21) then 'ReportCustomCode8'

        when (pGroupBy = 22) then 'ReportCustomCode9'

        when (pGroupBy = 23) then 'ReportCustomCode10'

      else 'NoGroupChange' end

    into vGroupByColumnName

    from dual;

    

  end if;



  --

  -- return column name

  --

  v_step := 30;

  

  return vGroupByColumnName;



exception

  when others then

    --

    -- log error to AX_LOG table then return 'NoGroupChange'

    -- 

--    v_step := 40;

    

    ax_pkg.LogEvent_P(trim('AR_DEPT_PKG')||'.ar_get_group_by_column_name_f', trim(sqlerrm)||' (Error at step '||v_step||')'); -- AX-39259

    

    return 'NoGroupChange';



end ar_get_group_by_column_name_f;



--

-- function to get the department AR As At Total

--

FUNCTION ar_get_dept_asat_f(pdepartment character, pasatdate timestamp without time zone, ppatient numeric DEFAULT 0, porigrecno numeric DEFAULT 0, precalculate integer DEFAULT 0) RETURN numeric IS



  

  -- E133231

  cursor cHistoryHints is

    select UserHint

    from (

          select

            1 UserOrder,

            'index(h3, '||trim(uic.index_name)||') ' UserHint

          from user_ind_columns uic

          where 1=1

          and exists (select null

                      from user_indexes ui

                      where 1=1

                      and ui.table_name = 'HISTORY'

                      and ui.status = 'VALID'

                      and ui.index_name = uic.index_name)

          and uic.column_name in ('Discipline',

                                  'Procedure',

                                  'Practice',

                                  'ClaimDoctor',

                                  'Location',

                                  'EntryUser',

                                  'AppUser',

                                  'Custom1',

                                  'Custom2',

                                  'Producer',

                                  'Patient')

          and uic.column_position = 1

          and not exists (select null

                          from user_ind_columns uic2

                          where 1=1

                          and uic2.column_position > 1

                          and uic2.index_name = uic.index_name)

          union all

          select

            1 UserOrder,

            'no_index(h3, '||trim(uic.index_name)||') ' UserHint

          from user_ind_columns uic

          where 1=1

          and exists (select null

                      from user_indexes ui

                      where 1=1

                      and ui.table_name = 'HISTORY'

                      and ui.status = 'VALID'

                      and ui.index_name = uic.index_name)

          and uic.column_name in ('Discipline',

                                  'Procedure',

                                  'Practice',

                                  'ClaimDoctor',

                                  'Location',

                                  'EntryUser',

                                  'AppUser',

                                  'Custom1',

                                  'Custom2',

                                  'Producer',

                                  'Patient',

                                  'Type',

                                  'TreatmentDate',

                                  'OrthoStatus',

                                  'Deleted')

          and uic.column_position = 1

          and exists (select null

                      from user_ind_columns uic2

                      where 1=1

                      and uic2.column_position > 1

                      and uic2.index_name = uic.index_name)

         )

    order by UserOrder;

      

  -- E133231

  cursor cPatProdHints is

    select decode(patprod.UserRowNum, 1, patprod.UserText||patprod.UserHint, patprod.UserHint) UserHint

    from (

          select

            uic.table_name,

            uic.index_name,

            'index(pat, '||trim(uic.index_name)||') ' UserHint,

            row_number() over (partition by uic.table_name order by uic.table_name, uic.index_name) UserRowNum,

            'full(pat) ' UserText

          from user_ind_columns uic

          where 1=1

          and exists (select null

                      from user_indexes ui

                      where 1=1

                      and ui.table_name = 'PATIENT'

                      and ui.status = 'VALID'

                      and ui.index_name = uic.index_name)

          and uic.column_name in ('CustomCode1',

                                  'CustomCode2',

                                  'CustomCode3',

                                  'CustomCode4',

                                  'CustomCode5',

                                  'CustomCode6',

                                  'CustomCode7',

                                  'CustomCode8',

                                  'CustomCode9',

                                  'CustomCode10')

          and uic.column_position = 1

          and not exists (select null

                          from user_ind_columns uic2

                          where 1=1

                          and uic2.column_position > 1

                          and uic2.index_name = uic.index_name)

          union all

          select

           uic.table_name,

            uic.index_name,

            'index(prod, '||trim(uic.index_name)||') ' UserHint,

            row_number() over (partition by uic.table_name order by uic.table_name, uic.index_name) UserRowNum,

            'full(prod) ' UserText    

          from user_ind_columns uic

          where 1=1

          and exists (select null

                      from user_indexes ui

                      where 1=1

                      and ui.table_name = 'PRODUCER'

                      and ui.status = 'VALID'

                      and ui.index_name = uic.index_name)

          and uic.column_name in ('TypeCode',

                                  'PGroup',

                                  'Year')

          and uic.column_position = 1

          and not exists (select null

                          from user_ind_columns uic2

                          where 1=1

                          and uic2.column_position > 1

                          and uic2.index_name = uic.index_name)

         ) patprod

    where 1=1

    order by

      patprod.table_name,

      patprod.index_name;

  

  -- E133231  

  vHint  VARCHAR2(2000) := '/*+ full(h3) xxxReplaceMexxx*/';

  vHint2  VARCHAR2(2000);

  vEnteredLoop number(1) := 0;

  

  vPtTotal number := 0;

  vInsTotal number := 0;

  vTotal number := 0;

  vDepartment history_ar_global_temp."Department"%type := trim(pDepartment);

  vAsAtDate date := (trunc(pAsAtDate) + (23.9998/24));



  vIndexType user_indexes.index_type%type;

  

  vOrigSQLStmt  VARCHAR2(32767) :=

'with

maxhistory as

(select /*+ index_ffs(h2, HISTORY_AR) */

   h2."OrigRecNo",

   max(h2."History") "MaxHistory"

 from history h2

 where 1=1

 and trunc(h2."ModifiedDate") <= :1

 group by h2."OrigRecNo"),

tmphistory as

(select /*+ full(h3) */

   h3."Discipline",

   h3."Procedure",

   h3."Practice",

   h3."ClaimDoctor",

   h3."Location",

   h3."EntryUser",

   h3."AppUser",

   h3."Custom1",

   h3."Custom2",

   h3."Producer",

   h3."Patient",

   (h3."Total" - h3."InsTotal" + h3."PtAdj" + h3."InsTransfer" - h3."Payed") "PtTotal",

   (h3."InsTotal" - h3."InsAdj" - h3."InsTransfer" - h3."InsPayed") "InsTotal",

   h3."Deleted",

   h3."OrthoStatus",

   h3."TreatmentDate",

   h3."Type"

 from

   history h3,

   maxhistory h1

 where 1=1

 and h3."OrigRecNo" = h1."OrigRecNo"

 and h3."History" = h1."MaxHistory")

select /*+ full(pat)

           full(prod) */

  nvl(sum(h."PtTotal"), 0),

  nvl(sum(h."InsTotal"), 0)

from

  tmphistory h,

  patient pat,

  producer prod

where 1=1

and h."OrthoStatus" in (0, 2)

and h."Deleted" = 0       

and h."TreatmentDate" <= :2

and h."Type" in (1, 2)

and h."Producer" = prod."Producer" (+)

and h."Patient" = pat."Patient" (+)

';

                                  

  vSQLStmt  VARCHAR2(32767);

  

  v_step number(3) := 0;

  vSysdate date := sysdate;							-- AX-26491.js

  

begin

  --

  -- force parallel execution if possible to improve performance (SF-00278253)

  --

--  v_step := 1;



--  execute immediate 'ALTER SESSION FORCE PARALLEL DML PARALLEL 4';            -- AX-26491 (commented-out)

--  execute immediate 'ALTER SESSION FORCE PARALLEL QUERY PARALLEL 4';          -- AX-27416 (commented out)



  --

  -- reduce REDO/rollback segments used by GTTs (introduced in Oracle Database 12C Release 1 (12.1))

  --

  v_step := 1;

  

  begin

    execute immediate 'ALTER SESSION SET TEMP_UNDO_ENABLED = TRUE';

  exception

    when others then

      null;

  end;

  

  --

  -- get AsAt balance if computed before and is available from the table AR_RECON_SAVED_DATA_HDR (SF-00278253)

  --

  if (pRecalculate = 0) then



    begin

      --

      -- get AsAtBalance if computed before (BeginningBalance)

      --

      v_step := 2;

      

      select arh2."BeginningBalance"

      into vTotal

      from (

            select arh."BeginningBalance"

            from ar_recon_saved_data_hdr arh

            where 1=1

            and arh."ReportType" = 0                                            -- AX-26491

            and arh."BeginningBalance" <> 0

            and arh."EndingBalance" <> 0

            and arh."Patient" = pPatient

            and arh."OrigRecNo" = pOrigRecNo

            and arh."FromDate" = (trunc(vAsAtDate) + 1)

            and arh."Department" = vDepartment

            and arh."ExpiryDate" >= trunc(vSysdate)                             -- AX-26491.js; only care about non-expired record

            order by arh."Batch" desc

           ) arh2

      where 1=1

      and rownum = 1;

  

      return vTotal;



    exception

      when no_data_found then

        --

        -- get AsAtBalance if computed before (EndingBalance)

        --

        v_step := 3;

  

        begin

    

          select arh2."EndingBalance"

          into vTotal

          from (

                select arh."EndingBalance"

                from ar_recon_saved_data_hdr arh

                where 1=1

                and arh."ReportType" = 0                                        -- AX-26491

                and arh."BeginningBalance" <> 0

                and arh."EndingBalance" <> 0

                and arh."Patient" = pPatient

                and arh."OrigRecNo" = pOrigRecNo

                and arh."ToDate" = vAsAtDate

                and arh."Department" = vDepartment

                and arh."ExpiryDate" >= trunc(vSysdate)                          -- AX-26491.js; only care about non-expired record

                order by arh."Batch" desc

               ) arh2

          where 1=1

          and rownum = 1;



          return vTotal;



        exception

          when others then

            null;

        end;



    when others then

       null;

    end;



  end if;



/*

start:  AX-27637 (commented out)



  --

  -- E133231: create hinted text

  --

  v_step := 5;

  

  for pHistoryHints in cHistoryHints loop

  

    vHint2 := vHint2 || pHistoryHints.UserHint;

    

  end loop;

  

  vHint := replace(vHint, 'xxxReplaceMexxx', vHint2);

  vOrigSQLStmt := replace(vOrigSQLStmt, '*+ full(h3) *', vHint);

  

  vHint := '*+ xxxReplaceMexxx*';

  vHint2 := '';

  

  for pPatProdHints in cPatProdHints loop

  

    vHint2 := vHint2 || pPatProdHints.UserHint;

    vEnteredLoop := 1;

    

  end loop;



  if (vEnteredLoop = 1) then



    vHint := replace(vHint, 'xxxReplaceMexxx', vHint2);

    vOrigSQLStmt := replace(vOrigSQLStmt, '* xxxReplaceMexxx*', vHint);

    

  else

  

    vOrigSQLStmt := replace(vOrigSQLStmt, '* xxxReplaceMexxx*', ' ');

    

  end if;



end:  AX-27637 (commented out)

*/

  

  --

  -- clear global temporary table

  --

  v_step := 10;

  

  execute immediate 'truncate table history_ar_global_temp4';

  

  --

  --  get patient and insurance totals

  --

  if ((pPatient = 0) and (pOrigRecNo = 0)) then

    --

    -- check index type and use correct SQL based on index type

    --

    begin

      --

      -- get index type

      --

      v_step := 20;

  

      select index_type

      into vIndexType

      from user_indexes

      where 1=1

      and table_name = 'HISTORY'

      and index_name = 'HISTORY_AR'

      and status = 'VALID'

      and rownum = 1;

      

      if (vIndexType = 'NORMAL') then

        --

        -- do not put TRUNC as index is NORMAL (non function based)

        --

        v_step := 35;      



        -- E133231

        vOrigSQLStmt := replace(vOrigSQLStmt, 'trunc(h2."ModifiedDate")', 'h2."ModifiedDate"');

                

      end if;

      

    exception

      when others then

        --

        -- do not put TRUNC as index is probably NORMAL (non function based)

        --

        v_step := 55;



        -- E133231        

        vOrigSQLStmt := replace(vOrigSQLStmt, 'trunc(h2."ModifiedDate")', 'h2."ModifiedDate"');

        

    end;

    

    --

    -- get latest history record for each OrigRecNo

    --

    if (vDepartment = 'zzzzzz') then

      --

      -- do not call AR_GET_DEPT_F

      --

      v_step := 60;

 

      -- E133231

      execute immediate vOrigSQLStmt 

      into 

        vPtTotal,

        vInsTotal 

      using 

        vAsAtDate, 

        vAsAtDate;

                                      

    else

      --

      -- call AR_GET_DEPT_F

      --

      v_step := 70;

    

      vSQLStmt := vOrigSQLStmt || ar_dept_pkg.ar_get_dept_f (vDepartment, 0, '', 0);



      --

      -- execute built SQL statement

      --

      v_step := 75;



      execute immediate vSQLStmt 

      into 

        vPtTotal,

        vInsTotal 

      using

        vAsAtDate,

        vAsAtDate;

      

    end if;

    

  else

    --

    -- for particular patient or OrigRecNo

    --

    v_step := 80;

    

    select

      nvl(sum(h."Total" - h."InsTotal" + h."PtAdj" + h."InsTransfer" - h."Payed"), 0),

      nvl(sum(h."InsTotal" - h."InsAdj" - h."InsTransfer" - h."InsPayed"), 0)

    into

      vPtTotal,

      vInsTotal

    from

      history h,

      (select max(h3."History") "History"

       from history h3

       where 1=1

       and h3."ModifiedDate" <= vAsAtDate

       and h3."OrigRecNo" = decode(pOrigRecNo, 0, h3."OrigRecNo", pOrigRecNo)

       and h3."Patient" = decode(pPatient, 0, h3."Patient", pPatient)           

       group by h3."OrigRecNo") h2

    where 1=1

    and h."OrigRecNo" = decode(pOrigRecNo, 0, h."OrigRecNo", pOrigRecNo)

    and h."Patient" = decode(pPatient, 0, h."Patient", pPatient)    

    and vDepartment = ar_dept_pkg.ar_get_dept_f (vDepartment,

                                                 h."History",

                                                 h."Producer",

                                                 h."Patient")

    and exists (select null

                from patient p

                where 1=1

                and p."Patient" = h."Patient")

    and (h."OrthoStatus" < 1

         or h."OrthoStatus" > 1)                

    and h."Deleted" = 0                 

    and h."TreatmentDate" <= vAsAtDate                

    and (h."Type" = 1 

         or h."Type" = 2)                 

    and h."History" = h2."History";

    

  end if;



  --

  -- save changes then empty global temporary tables HISTORY_AR_GLOBAL_TEMP, HISTORY_AR_GLOBAL_TEMP2, HISTORY_AR_GLOBAL_TEMP4

  --

  v_step := 90;

  

  begin



    -- AX-27637  

    execute immediate 'truncate table history_ar_global_temp';

    execute immediate 'truncate table history_ar_global_temp2';

    execute immediate 'truncate table history_ar_global_temp4';

    

    --

    -- return results

    --

    v_step := 100;

    

    vTotal := vPtTotal + vInsTotal;   



    --

    -- delete records from AR_RECON_SAVED_DATA_HDR and AR_RECON_SAVED_DATA_DTL if balances are not correct (SF-00278253)

    --

    v_step := 105;

    

    delete from ar_recon_saved_data_hdr arh

    where 1=1

    and arh."ReportType" = 0                                                      -- AX-26491

    and arh."BeginningBalance" <> vTotal

    and arh."BeginningBalance" <> 0

    and arh."EndingBalance" <> 0

    and arh."Patient" = pPatient

    and arh."OrigRecNo" = pOrigRecNo

    and arh."FromDate" = (trunc(vAsAtDate) + 1)

    and arh."Department" = vDepartment

    and arh."ExpiryDate" >= trunc(vSysdate);                   -- AX-26491.js; no need to touch expired record; won't be used

    

    

    v_step := 110;

    

    delete from ar_recon_saved_data_hdr arh

    where 1=1

    and arh."ReportType" = 0                                                      -- AX-26491

    and arh."EndingBalance" <> vTotal

    and arh."BeginningBalance" <> 0

    and arh."EndingBalance" <> 0

    and arh."Patient" = pPatient

    and arh."OrigRecNo" = pOrigRecNo

    and arh."ToDate" = vAsAtDate

    and arh."Department" = vDepartment

    and arh."ExpiryDate" >= trunc(vSysdate);                   -- AX-26491.js; no need to touch expired record; won't be used

    

    v_step := 115;

    

    -- AX-26491.js altered the query as header will still be around from above

    delete from ar_recon_saved_data_dtl ard

    where 1=1

    and exists (select null

                from ar_recon_saved_data_hdr arh

                where 1=1

                and arh."Batch" = ard."Batch"

                and arh."ExpiryDate" < trunc(vSysdate));



  

  return vTotal;

  exception

    when others then

      ax_pkg.LogEvent_P(trim('AR_DEPT_PKG')||'.ar_get_dept_asat_f', trim(sqlerrm)||' (Error at step '||v_step||')'); -- AX-39259

      

  end;

exception

  when others then

    --

    -- log error to AX_LOG table

    -- 

--    v_step := 120;

    

    ax_pkg.LogEvent_P(trim('AR_DEPT_PKG')||'.ar_get_dept_asat_f', trim(sqlerrm)||' (Error at step '||v_step||')'); -- AX-39259

    

end ar_get_dept_asat_f;



--

-- create procedure to get unallocated payments

--

PROCEDURE ar_create_unallocated_txs_p(IN pfromdate timestamp without time zone, IN ptodate timestamp without time zone, IN pgroupby1 numeric, IN preportgroupby1description character, IN pgroupby2 numeric, IN preportgroupby2description character, IN pisdetailed numeric, IN pincludeunallocated numeric, IN ppatient numeric, IN porigrecno numeric) IS         

  

  -- constants

  vUnallocated history_ar_global_temp2."ReportPeriod"%type := 'UNALLOCATED';

  vUnallocatedPayments history_ar_global_temp3."ReportHistoryTypeDescription"%type := 'Unallocated Payments';

  vUnallocatedAdjustments history_ar_global_temp3."ReportHistoryTypeDescription"%type := 'Unallocated Adjustments';

  vUnallocatedInsurancePayments history_ar_global_temp3."ReportHistoryTypeDescription"%type := 'Unallocated Insurance Payments';

  vUnknown history_ar_global_temp3."ReportHistoryTypeDescription"%type := 'Unknown';



  vIndexType user_indexes.index_type%type;

  

  v_step number(3) := 0;

  

begin

  --

  -- clear global temporary table

  --

  v_step := 10;

  

  execute immediate 'truncate table history_ar_global_temp4';

  

  if ((pPatient = 0) and (pOrigRecNo = 0)) then

    --

    -- get unallocated transactions (AX-27637)

    --

    v_step := 15;

    

    insert into history_ar_global_temp

    with 

    maxhistory as (select /*+ index_ffs(h2, HISTORY_AR) */ max(h2."History") "MaxHistory"

                   from history h2

                   where 1=1

                   and (h2."Type" = 3

                        or h2."Type" = 6

                        or h2."Type" = 4)

                   and trunc(h2."ModifiedDate") <= pToDate

                   group by

                     h2."OrigRecNo",

                     h2."Type")

    select /*+ full(h) */

      h.*,

      vUnallocated "ReportPeriod",

      ' ' "Department",

      ' ' "Producer_TypeCode",

      ' ' "Producer_PGroup",

      0 "Producer_Year",

      ' ' "Patient_CustomCode1",

      ' ' "Patient_CustomCode2",

      ' ' "Patient_CustomCode3",

      ' ' "Patient_CustomCode4",

      ' ' "Patient_CustomCode5",

      ' ' "Patient_CustomCode6",

      ' ' "Patient_CustomCode7",

      ' ' "Patient_CustomCode8",

      ' ' "Patient_CustomCode9",

      ' ' "Patient_CustomCode10",

      pGroupBy1,

      pReportGroupBy1Description,

      pGroupBy2,

      pReportGroupBy2Description,

      pFromDate,

      pToDate,

      pIsDetailed,

      pIncludeUnallocated

    from

      history h,

      maxhistory h1

    where 1=1

    -- exclude unnecessary payment records

--    and decode(h."Type", 3, (h."Payed" + h."PtAdj"), 1) <> 0

    -- exclude unnecessary adjustment records

--    and decode(h."Type", 6, h."Payed", 1) <> 0

    -- exclude unnecessary insurance payment records

--    and decode(h."Type", 4, (h."InsPayed" + h."InsAdj"), 1) <> 0  

    and decode(h."Type", 3, (h."Payed" + h."PtAdj"),

                         4, (h."InsPayed" + h."InsAdj"),

                         6, h."Payed") <> 0      

    and h."TreatmentDate" <= pToDate

    and h."Deleted" = 0 

    and h."History" = h1."MaxHistory";



  else

    --

    -- get the latest history ID for each OrigRecNo for the unallocated transactions

    --

    v_step := 60;   



    -- E133231      

    insert into history_ar_global_temp

    with 

    maxhistory as

    (

     select /*+ parallel(h2, 2) */

       max(h2."History") "MaxHistory"

     from history h2

     where 1=1

     and h2."OrigRecNo" = decode(pOrigRecNo, 0, h2."OrigRecNo", pOrigRecNo)

     and h2."Patient" = decode(pPatient, 0, h2."Patient", pPatient)    

     and (h2."Type" = 3

          or h2."Type" = 6

          or h2."Type" = 4)

     and trunc(h2."ModifiedDate") <= pToDate

     and h2."ModifiedDate" <= pToDate

     group by 

       h2."OrigRecNo",

       h2."Type"

    )

    select /*+ parallel(h, 2)

               parallel(h1, 2) */

      h.*,

      vUnallocated "ReportPeriod",

      ' ' "Department",

      ' ' "Producer_TypeCode",

      ' ' "Producer_PGroup",

      0 "Producer_Year",

      ' ' "Patient_CustomCode1",

      ' ' "Patient_CustomCode2",

      ' ' "Patient_CustomCode3",

      ' ' "Patient_CustomCode4",

      ' ' "Patient_CustomCode5",

      ' ' "Patient_CustomCode6",

      ' ' "Patient_CustomCode7",

      ' ' "Patient_CustomCode8",

      ' ' "Patient_CustomCode9",

      ' ' "Patient_CustomCode10",

      pGroupBy1,

      pReportGroupBy1Description,

      pGroupBy2,

      pReportGroupBy2Description,

      pFromDate,

      pToDate,

      pIsDetailed,

      pIncludeUnallocated

    from 

      maxhistory h1,

      history h

    where 1=1        

    and h."OrigRecNo" = decode(pOrigRecNo, 0, h."OrigRecNo", pOrigRecNo)

    and h."Patient" = decode(pPatient, 0, h."Patient", pPatient)           

    -- exclude unnecessary payment records

    and decode(h."Type", 3, (h."Payed" + h."PtAdj"), 1) <> 0

    -- exclude unnecessary adjustment records

    and decode(h."Type", 6, h."Payed", 1) <> 0

    -- exclude unnecessary insurance payment records

    and decode(h."Type", 4, (h."InsPayed" + h."InsAdj"), 1) <> 0  

    and h."TreatmentDate" <= pToDate

    and h."Deleted" = 0 

    and (h."Type" = 3

         or h."Type" = 6

         or h."Type" = 4)

    and h."History" = h1."MaxHistory";

      

  end if;

   

  --

  -- removed invalid patients

  --  

  v_step := 70;

  

  delete from history_ar_global_temp h

  where 1=1

  and (h."Type" = 3

       or h."Type" = 6)

  and not exists (select null

                  from patient p

                  where 1=1

                  and p."Patient" = h."Patient");



  --

  -- insert records into 2nd temporary table

  --

  v_step := 80;

  

  insert into history_ar_global_temp2

  select 

    h.*,

    decode(h."Type", 3, vUnallocatedPayments,

                     6, vUnallocatedAdjustments,

                     4, vUnallocatedInsurancePayments,

                     vUnknown),

    h."Total",

    h."InsTotal",

    h."Payed",

    h."InsPayed",

    h."PtAdj",

    h."InsAdj",

    h."InsTransfer",    

    h."Department",

    h."Discipline",

    h."Procedure",

    h."Practice",

    h."ClaimDoctor",

    h."Location",

    h."EntryUser",

    h."AppUser",

    h."Custom1",

    h."Custom2",

    h."Producer",

    h."Producer_TypeCode",

    h."Producer_PGroup",

    h."Producer_Year",

    h."Patient_CustomCode1",

    h."Patient_CustomCode2",

    h."Patient_CustomCode3",

    h."Patient_CustomCode4",

    h."Patient_CustomCode5",

    h."Patient_CustomCode6",

    h."Patient_CustomCode7",

    h."Patient_CustomCode8",

    h."Patient_CustomCode9",

    h."Patient_CustomCode10"

  from history_ar_global_temp h

  where 1=1;

  

  --

  -- insert records into final report table

  --

  v_step := 90;  

      

  insert into history_ar_global_temp3

  select

    "History",

    "HistoryType",

    "OrigRecNo",

    "Type",

    "Id",

    "Treatment",

    "ModifiedDate",

    "TreatmentDate",

    "Producer",

    "Procedure",

    "Patient",

    "Family",

    "Code",

    "Description",  

    "Company1",    

    "ReportDepartment",

    "ReportDiscipline",

    "ReportProcedure",

    "ReportPractice",

    "ReportClaimDoctor",

    "ReportLocation",

    "ReportEntryUser",

    "ReportAppUser",

    "ReportCustom1",

    "ReportCustom2",

    "ReportProducer",

    "ReportTypeCode",

    "ReportPGroup",

    "ReportYear",

    "ReportCustomCode1",

    "ReportCustomCode2",

    "ReportCustomCode3",

    "ReportCustomCode4",

    "ReportCustomCode5",

    "ReportCustomCode6",

    "ReportCustomCode7",

    "ReportCustomCode8",

    "ReportCustomCode9",

    "ReportCustomCode10",

    "ReportGroupBy1",

    "ReportGroupBy1Description",

    "ReportGroupBy2",

    "ReportGroupBy2Description",

    "ReportFromDate",

    "ReportToDate",

    "ReportIsDetailed",

    "ReportIncludeUnallocated",

    "ReportHistoryTypeDescription",

    sum("ReportOldTotal") "ReportOldTotal",

    sum("ReportTotal") "ReportTotal",

    (sum("ReportTotal") - sum("ReportOldTotal")) "ReportTotalChange",

    sum("ReportOldInsTotal") "ReportOldInsTotal",

    sum("ReportInsTotal") "ReportInsTotal",

    (sum("ReportInsTotal") - sum("ReportOldInsTotal")) "ReportInsTotalChange",

    sum("ReportOldPayed") "ReportOldPayed",

    sum("ReportPayed") "ReportPayed",

    (sum("ReportPayed") - sum("ReportOldPayed")) "ReportPayedChange",

    sum("ReportOldInsPayed") "ReportOldInsPayed",

    sum("ReportInsPayed") "ReportInsPayed",

    (sum("ReportInsPayed") - sum("ReportOldInsPayed")) "ReportInsPayedChange",

    sum("ReportOldPtAdj") "ReportOldPtAdj",

    sum("ReportPtAdj") "ReportPtAdj",

    (sum("ReportPtAdj") - sum("ReportOldPtAdj")) "ReportPtAdjChange",

    sum("ReportOldInsAdj") "ReportOldInsAdj",

    sum("ReportInsAdj") "ReportInsAdj",

    (sum("ReportInsAdj") - sum("ReportOldInsAdj")) "ReportInsAdjChange",

    sum("ReportOldInsTransfer") "ReportOldInsTransfer",

    sum("ReportInsTransfer") "ReportInsTransfer",

    (sum("ReportInsTransfer") - sum("ReportOldInsTransfer")) "ReportInsTransferChange",

    0 "PreviousHistory"                                                         -- AX-28014

  from 

    (select 

       h. "History",

       h."HistoryType",

       h."OrigRecNo",

       h."Type",       

       h."Id",

       h."Treatment",     

       h."ModifiedDate",

       h."TreatmentDate",

       h."Producer",

       h."Procedure",

       h."Patient",

       h."Family",

       h."Code",

       h."Description",  

       h."Company1",

       h."ReportDepartment",

       h."ReportDiscipline",

       h."ReportProcedure",

       h."ReportPractice",

       h."ReportClaimDoctor",

       h."ReportLocation",

       h."ReportEntryUser",

       h."ReportAppUser",

       h."ReportCustom1",

       h."ReportCustom2",

       h."ReportProducer",

       h."ReportTypeCode",

       h."ReportPGroup",

       h."ReportYear",

       h."ReportCustomCode1",

       h."ReportCustomCode2",

       h."ReportCustomCode3",

       h."ReportCustomCode4",

       h."ReportCustomCode5",

       h."ReportCustomCode6",

       h."ReportCustomCode7",

       h."ReportCustomCode8",

       h."ReportCustomCode9",

       h."ReportCustomCode10",

       h."ReportGroupBy1",

       h."ReportGroupBy1Description",

       h."ReportGroupBy2",  

       h."ReportGroupBy2Description",

       h."ReportFromDate",

       h."ReportToDate",

       h."ReportIsDetailed",

       h."ReportIncludeUnallocated",

       h."ReportHistoryTypeDescription",

       0 "ReportOldTotal",

       h."ReportTotal" "ReportTotal",

       0 "ReportOldInsTotal",

       h."ReportInsTotal" "ReportInsTotal",

       0 "ReportOldPayed",

       h."ReportPayed" "ReportPayed",

       0 "ReportOldInsPayed",

       h."ReportInsPayed" "ReportInsPayed",

       0 "ReportOldPtAdj",

       h."ReportPtAdj" "ReportPtAdj",

       0 "ReportOldInsAdj",

       h."ReportInsAdj" "ReportInsAdj",

       0 "ReportOldInsTransfer",

       h."ReportInsTransfer" "ReportInsTransfer"

     from history_ar_global_temp2 h

     where 1=1

    )

  where 1=1

  group by

    "History",

    "HistoryType",

    "OrigRecNo",

    "Type",

    "Id",

    "Treatment",

    "ModifiedDate",

    "TreatmentDate",

    "Producer",

    "Procedure",

    "Patient",

    "Family",

    "Code",

    "Description",  

    "Company1",

    "ReportDepartment",

    "ReportDiscipline",

    "ReportProcedure",

    "ReportPractice",

    "ReportClaimDoctor",

    "ReportLocation",

    "ReportEntryUser",

    "ReportAppUser",

    "ReportCustom1",

    "ReportCustom2",

    "ReportProducer",

    "ReportTypeCode",

    "ReportPGroup",

    "ReportYear",

    "ReportCustomCode1",

    "ReportCustomCode2",

    "ReportCustomCode3",

    "ReportCustomCode4",

    "ReportCustomCode5",

    "ReportCustomCode6",

    "ReportCustomCode7",

    "ReportCustomCode8",

    "ReportCustomCode9",

    "ReportCustomCode10",

    "ReportGroupBy1",

    "ReportGroupBy1Description",

    "ReportGroupBy2",

    "ReportGroupBy2Description",

    "ReportFromDate",

    "ReportToDate",

    "ReportIsDetailed",

    "ReportIncludeUnallocated",

    "ReportHistoryTypeDescription";    

    

  --

  -- save changes then empty global temporary tables HISTORY_AR_GLOBAL_TEMP, HISTORY_AR_GLOBAL_TEMP2, HISTORY_AR_GLOBAL_TEMP4

  --

  v_step := 100;

  

  commit;



  -- AX-27637  

  execute immediate 'truncate table history_ar_global_temp';

  execute immediate 'truncate table history_ar_global_temp2';

  execute immediate 'truncate table history_ar_global_temp4';



exception

  when others then

    --

    -- log error to AX_LOG table

    -- 

--    v_step := 110;

    

    ax_pkg.LogEvent_P(trim('AR_DEPT_PKG')||'.ar_create_unallocated_txs_p', trim(sqlerrm)||' (Error at step '||v_step||')'); -- AX-39259



end ar_create_unallocated_txs_p;

                                        

--

-- create procedure to process group by changes

--

PROCEDURE ar_create_dept_txs_changes_p(IN porigrecno numeric, IN pfamily numeric, IN phistory numeric, IN pperiod character, IN pchangecolumn1 character varying, IN pgroupcolumn1 character varying, IN pchangecolumn2 character varying, IN pgroupcolumn2 character varying) IS



  cursor cEnteredGroup (pOrigRecNo2 history_ar_global_temp."OrigRecNo"%type,

                        pFamily2 history_ar_global_temp."Family"%type,

                        pHistory2 history_ar_global_temp."History"%type) is

    select /*+ index(h history_ar_global_temp_idx2) */

      h."ReportPeriod",

      h."History",

      h.ctid                                                                   -- AX-27637

    from history_ar_global_temp h

    where 1=1

    and (h."HistoryType" < 4

         or h."HistoryType" > 4)

    and h."Type" < 5

    and h."History" < pHistory2

    and h."Family" = pFamily2

    and h."OrigRecNo" = pOrigRecNo2;

    

  cursor cMinHistory (pOrigRecNo3 history_ar_global_temp."OrigRecNo"%type,

                      pHistory3 history_ar_global_temp."History"%type) is

    select /*+ index(h1 history_ar_global_temp_idx2) */

      h1."Family",

      min(h1."History") "History"

    from history_ar_global_temp h1

    where 1=1

    and h1."Type" < 5

    and h1."History" > pHistory3

    and h1."OrigRecNo" = pOrigRecNo3

    group by h1."Family";    



  vSQLStmt  VARCHAR2(32767) :=

'insert into history_ar_global_temp2

select /*+ index(h history_ar_global_temp_idx2) */

  h.*,

  decode(h."HistoryType", 1, ''New'', 2, :1, 3, ''Allocate'', 4, ''Delete'', 5, :2),

  h3."ReportTotal",

  h3."ReportInsTotal",

  h3."ReportPayed",

  h3."ReportInsPayed",

  h3."ReportPtAdj",

  h3."ReportInsAdj",

  h3."ReportInsTransfer",

  h."Department",

  h."Discipline",

  h."Procedure",

  h."Practice",

  h."ClaimDoctor",

  h."Location",

  h."EntryUser",

  h."AppUser",

  h."Custom1",

  h."Custom2",

  h."Producer",

  h."Producer_TypeCode",

  h."Producer_PGroup",

  h."Producer_Year",

  h."Patient_CustomCode1",

  h."Patient_CustomCode2",

  h."Patient_CustomCode3",

  h."Patient_CustomCode4",

  h."Patient_CustomCode5",

  h."Patient_CustomCode6",

  h."Patient_CustomCode7",

  h."Patient_CustomCode8",

  h."Patient_CustomCode9",

  h."Patient_CustomCode10"

from

  history_ar_global_temp h,

  (select

     h2."Department",

     h2."Discipline",

     h2."Procedure",

     h2."Practice",

     h2."ClaimDoctor",

     h2."Location",

     h2."EntryUser",

     h2."AppUser",

     h2."Custom1",

     h2."Custom2",

     h2."Producer",

     h2."Producer_TypeCode",

     h2."Producer_PGroup",

     h2."Producer_Year",

     h2."Patient_CustomCode1",

     h2."Patient_CustomCode2",

     h2."Patient_CustomCode3",

     h2."Patient_CustomCode4",

     h2."Patient_CustomCode5",

     h2."Patient_CustomCode6",

     h2."Patient_CustomCode7",

     h2."Patient_CustomCode8",

     h2."Patient_CustomCode9",

     h2."Patient_CustomCode10",

     (h2."Total" * -1) "ReportTotal",

     (h2."InsTotal" * -1) "ReportInsTotal",

     (h2."Payed" * -1) "ReportPayed",

     (h2."InsPayed" * -1) "ReportInsPayed",

     (h2."PtAdj" * -1) "ReportPtAdj",

     (h2."InsAdj" * - 1) "ReportInsAdj",

     (h2."InsTransfer" * -1) "ReportInsTransfer"

   from history_ar_global_temp h2

   where h2.ctid = :3) h3

where h."History" = :4

and h."Family" = :5

and h."OrigRecNo" = :6';



    vSQLStmt3  VARCHAR2(32767) :=

'update /*+ index(h3 history_ar_global_temp2_idx1) */ history_ar_global_temp2 h3


where 1=1

and h3."History" in (select /*+ index(h history_ar_global_temp2_idx1) */ h."History"

                     from history_ar_global_temp2 h

                     where 1=1

                     and h."History" in (select /*+ index(h2 history_ar_global_temp2_idx2) */ h2."History"

                                         from history_ar_global_temp2 h2

                                         where 1=1

                                         and (h2."HistoryType" = 2

                                              or h2."HistoryType" = 5)

                                         and (h2."ReportHistoryTypeDescription" = ''Transfer In''

                                              or h2."ReportHistoryTypeDescription" = ''Transfer Out'')

                                         and h2."Family" = :1

                                         and h2."OrigRecNo" = :2

                                         group by h2."History"

                                         having count(*) > 1)

                     group by h."History"

                     having count(distinct h."XXChangeMeXX1" || h."XXChangeMeXX2" || h."XXChangeMeXX3") = 1)';



  -- constants

  vCurrent history_ar_global_temp2."ReportPeriod"%type := 'CURRENT    ';

  vPrevious history_ar_global_temp2."ReportPeriod"%type := 'PREVIOUS   ';

  vNew history_ar_global_temp2."ReportHistoryTypeDescription"%type := 'New';

  vModified history_ar_global_temp3."ReportHistoryTypeDescription"%type := 'Modified';

  vAllocate history_ar_global_temp3."ReportHistoryTypeDescription"%type := 'Allocate';

  vDelete history_ar_global_temp3."ReportHistoryTypeDescription"%type := 'Delete';

  vTransferIn history_ar_global_temp3."ReportHistoryTypeDescription"%type := 'Transfer In';

  vTransferOut history_ar_global_temp3."ReportHistoryTypeDescription"%type := 'Transfer Out';

  vToOrthoPlan history_ar_global_temp3."ReportHistoryTypeDescription"%type := 'To Ortho Plan';

  vFromOrthoPlan history_ar_global_temp3."ReportHistoryTypeDescription"%type := 'From Ortho Plan';  

  vUnknown history_ar_global_temp3."ReportHistoryTypeDescription"%type := 'Unknown';                                                  

  vNoChange  VARCHAR2(30) := 'NoGroupChange';

  vGroupChanged integer := 1;



  vSQLStmt21  VARCHAR2(50);               

  vChangeMe21  VARCHAR2(50);       

  vSQLStmt22  VARCHAR2(50);               

  vChangeMe22  VARCHAR2(50);       

  vSQLStmt23  VARCHAR2(50);               

  vChangeMe23  VARCHAR2(50);       

  

  vChangeMeToo1  VARCHAR2(50) := 'XXChangeMeXX1';       

  vChangeMeToo2  VARCHAR2(50) := 'XXChangeMeXX2';       

  vChangeMeToo3  VARCHAR2(50) := 'XXChangeMeXX3';       



  vChangeDepartment  VARCHAR2(30) := 'Department';

  vGroupDepartment  VARCHAR2(30) := 'ReportDepartment';

  vDeptCount integer := 0;

  

  vSqlStmt4  VARCHAR2(32767) :=

'select /*+ index(h history_ar_global_temp_idx2) */ count(distinct h."' || pChangeColumn1 || '")

from history_ar_global_temp h

where 1=1

and h."Type" < 5

and h."Family" = :1

and h."OrigRecNo" = :2';

                              

  vSqlStmt5  VARCHAR2(32767) :=

'select /*+ index(h history_ar_global_temp_idx2) */ count(distinct h."' || pChangeColumn2 || '")

from history_ar_global_temp h

where 1=1

and h."Type" < 5

and h."Family" = :1

and h."OrigRecNo" = :2';

                              

  vGroupBy1Count integer := 0;

  vGroupBy2Count integer := 0;



  v_step integer := 0;



  -- AX-27637

  vReportHistoryTypeDescriptionIn history_ar_global_temp2."ReportHistoryTypeDescription"%type := ' ';

  vReportHistoryTypeDescriptionOut history_ar_global_temp2."ReportHistoryTypeDescription"%type := ' ';

  vMultiplier integer := 0;



begin  

  --

  -- determine if there's grouping

  --

  v_step := 10;



  select /*+ index(h history_ar_global_temp_idx2) */ count(distinct h."Department")

  into vDeptCount

  from history_ar_global_temp h

  where 1=1

  and h."Type" < 5

  and h."Family" = pFamily

  and h."OrigRecNo" = pOrigRecNo;



  if (vDeptCount < 2) then

  

    if ((pGroupColumn1 = vNoChange) and (pGroupColumn2 = vNoChange)) then

  

      vGroupChanged := 0;  

    

    else

  

      if (pGroupColumn1 <> vNoChange) then

        --

        -- determine if there is a change in grouping 1

        --

        v_step := 13;

        

        execute immediate vSQLStmt4 

        into vGroupBy1Count 

        using pFamily,

              pOrigRecNo;



        if (vGroupBy1Count < 2) then

        

          if (pGroupColumn2 <> vNoChange) then

            --

            -- determine if there is a change in grouping 2

            --

            v_step := 16;

            

            execute immediate vSQLStmt5

            into vGroupBy2Count 

            using pFamily,

                  pOrigRecNo;



            if (vGroupBy2count < 2) then

            

              vGroupChanged := 0;

              

            end if;

            

          else

            

            vGroupChanged := 0;

            

          end if;

        

        end if;

            

      end if;

                                                                        

    end if;

  

  end if;



  --

  -- correct column name that changed

  --

  v_step := 20;

  

  vSQLStmt21 := 'h3."'|| vChangeDepartment || '"';               

  vChangeMe21 := 'h."' || vChangeDepartment || '"';    

  vSQLStmt22 := 'h3."'|| pChangeColumn1 || '"';               

  vChangeMe22 := 'h."' || pChangeColumn1 || '"';       

  vSQLStmt23 := 'h3."'|| pChangeColumn2 || '"';               

  vChangeMe23 := 'h."' || pChangeColumn2 || '"';    

  

  vSQLStmt := replace(vSQLStmt, vChangeMe21, vSQLStmt21);

  vSQLStmt := replace(vSQLStmt, vChangeMe22, vSQLStmt22);

  vSQLStmt := replace(vSQLStmt, vChangeMe23, vSQLStmt23);



  --

  -- determine the history type description to use (AX-27637)

  --

  v_step := 23;

  

  if (vGroupChanged = 0) then

    vReportHistoryTypeDescriptionIn := vModified;

    vReportHistoryTypeDescriptionOut := vModified;

  else

    vReportHistoryTypeDescriptionIn := vTransferIn;

    vReportHistoryTypeDescriptionOut := vTransferOut;

  end if;



  --

  -- process changes in group

  --

  for pEnteredGroup in cEnteredGroup (pOrigRecNo,

                                      pFamily,

                                      pHistory) loop

    --

    -- determine if amounts will be positive or negative (AX-27637)

    --

    v_step := 26;

    

    if (pEnteredGroup."ReportPeriod" = pPeriod) then

      vMultiplier := -1;

    else

      vMultiplier := 1;

    end if;

    

    --

    -- create add records for changes in group

    --

    v_step := 30;

    

    insert into history_ar_global_temp2

    select

      h.*,

      decode(h."HistoryType", 1, vNew,

                              2, vReportHistoryTypeDescriptionIn,

                              3, vAllocate,

                              4, vDelete,

                              5, vReportHistoryTypeDescriptionIn),

      (h."Total" * vMultiplier),

      (h."InsTotal" * vMultiplier),

      (h."Payed" * vMultiplier),

      (h."InsPayed" * vMultiplier),

      (h."PtAdj" * vMultiplier),

      (h."InsAdj" * vMultiplier),

      (h."InsTransfer" * vMultiplier),

      h."Department",

      h."Discipline",

      h."Procedure",

      h."Practice",

      h."ClaimDoctor",

      h."Location",

      h."EntryUser",

      h."AppUser",

      h."Custom1",

      h."Custom2",

      h."Producer",

      h."Producer_TypeCode",

      h."Producer_PGroup",

      h."Producer_Year",

      h."Patient_CustomCode1",

      h."Patient_CustomCode2",

      h."Patient_CustomCode3",

      h."Patient_CustomCode4",

      h."Patient_CustomCode5",

      h."Patient_CustomCode6",

      h."Patient_CustomCode7",

      h."Patient_CustomCode8",

      h."Patient_CustomCode9",

      h."Patient_CustomCode10"

    from history_ar_global_temp h

    where h.ctid = pEnteredGroup.ctid;

    

    --

    -- create minus records for changes in group

    --

    v_step := 40;



    for pMinHistory in cMinHistory (pOrigRecNo,

                                    pEnteredGroup."History") loop

                                    

      execute immediate vSQLStmt using vReportHistoryTypeDescriptionOut,

                                       vReportHistoryTypeDescriptionOut,

                                       pEnteredGroup.ctid,

                                       pMinHistory."History",

                                       pMinHistory."Family",

                                       pOrigRecNo;



    end loop;   -- pMinHistory



  end loop;   -- pEnteredGroup

  

  --

  -- update to Transfer In when there's equivalent Transfer Out

  --

  v_step := 50;

  

  update /*+ index(h history_ar_global_temp2_idx1) */ history_ar_global_temp2 h

  set h."ReportHistoryTypeDescription" = vTransferIn

  where 1=1

  and h."ReportHistoryTypeDescription" = ' '

  and exists (select /*+ index(h2 history_ar_global_temp2_idx1) */ null

              from history_ar_global_temp2 h2

              where 1=1                       

              and h2."HistoryType" = h."HistoryType"

              and h2."ReportHistoryTypeDescription" = vTransferOut

              and (h2."HistoryType" = 2

                   or h2."HistoryType" = 5)

              and h2."History" = h."History")

  and h."History" = pHistory;

                                                   

  --

  -- update to Transfer Out when there's equivalent Transfer In

  --

  v_step := 60;

         

  update  /*+ index(h history_ar_global_temp2_idx1) */  history_ar_global_temp2 h

  set h."ReportHistoryTypeDescription" = vTransferOut

  where 1=1

  and h."ReportHistoryTypeDescription" = ' '

  and exists (select /*+ index(h2 history_ar_global_temp2_idx1) */ null

              from history_ar_global_temp2 h2

              where 1=1

              and h2."HistoryType" = h."HistoryType"

              and h2."ReportHistoryTypeDescription" = vTransferIn

              and (h2."HistoryType" = 2

                   or h2."HistoryType" = 5)

              and h2."History" = h."History")

  and h."History" = pHistory;

              

  --

  -- update to Modified all Transfer In and Transfer Out when there is no grouping

  --  

  if (vGroupChanged > 0) then

    --

    -- correct group column name

    --

    v_step := 70;

    

    vSQLStmt3 := replace(vSQLStmt3, vChangeMeToo1, vGroupDepartment);

    vSQLStmt3 := replace(vSQLStmt3, vChangeMeToo2, pGroupColumn1);

    vSQLStmt3 := replace(vSQLStmt3, vChangeMeToo3, pGroupColumn2);

    vSQLStmt3 := replace(vSQLStmt3, vNoChange, vGroupDepartment);



    --

    -- perform actual update

    --

    v_step := 80;

    

    execute immediate vSQLStmt3 using pFamily,

                                      pOrigRecNo;



  end if;



exception

  when others then

    --

    -- log error to AX_LOG table

    -- 

--    v_step := 90;

    

    ax_pkg.LogEvent_P(trim('AR_DEPT_PKG')||'.ar_create_dept_txs_changes_p', trim(sqlerrm)||' (Error at step '||v_step||')'); -- AX-39259

    

end ar_create_dept_txs_changes_p;



--

-- create function to populate the temporary tables with report data

--

FUNCTION ar_create_dept_txs_f(pdepartment character, pfromdate timestamp without time zone, ptodate timestamp without time zone, pgroupby1 numeric, pgroupby2 numeric, pisdetailed numeric, pincludeunallocated numeric, ppatient numeric DEFAULT 0, porigrecno numeric DEFAULT 0, precalculate integer DEFAULT 0, pexpirydate timestamp without time zone DEFAULT trunc(sysdate), pupdateexpirydateifnotnewdata integer DEFAULT 0) RETURN numeric IS



  pragma autonomous_transaction;



  cursor cMaxHistory2 is

    select 

      h2."ReportPeriod",

      h2."OrigRecNo",

      h2."Family",

      max(h2."History") "History"

    from history_ar_global_temp h2

    where 1=1

    and h2."Type" < 5

    group by

      h2."ReportPeriod",

      h2."OrigRecNo",

      h2."Family"

    order by 2, 4;



  cursor cMaxHistory (pReportPeriod history_ar_global_temp."ReportPeriod"%type,

                      pOrigRecNo history_ar_global_temp."OrigRecNo"%type,

                      pFamily history_ar_global_temp."Family"%type,

                      pHistory history_ar_global_temp."History"%type) is

    select /*+ index(h history_ar_global_temp_idx2) */

      h."HistoryType",

      h."OrthoStatus"

    from history_ar_global_temp h

    where 1=1

    and h."Type" < 5

    and h."ReportPeriod" = pReportPeriod

    and h."OrigRecNo" = pOrigRecNo

    and h."Family" = pFamily

    and h."History" = pHistory;



  cursor cChanges (pOrigRecNo history_ar_global_temp."OrigRecNo"%type,

                   pFamily history_ar_global_temp."Family"%type) is

    select /*+ index(h history_ar_global_temp_idx2) */

      count(distinct h."Department") "DepartmentCount",

      count(distinct h."Producer") "ProducerCount",

      count(distinct h."Producer_PGroup") "PGroupCount",

      count(distinct h."Producer_TypeCode") "TypeCodeCount",

      count(distinct h."Producer_Year") "YearCount",

      count(distinct h."AppUser") "AppUserCount",

      count(distinct h."Custom1") "Custom1Count",

      count(distinct h."Custom2") "Custom2Count",      

      count(distinct h."Discipline") "DisciplineCount",

      count(distinct h."EntryUser") "EntryUserCount",

      count(distinct h."Location") "LocationCount",

      count(distinct h."ClaimDoctor") "ClaimDoctorCount",

      count(distinct h."Practice") "PracticeCount",

      count(distinct h."Procedure") "ProcedureCount",

      count(distinct h."Patient_CustomCode1") "CustomCode1Count",

      count(distinct h."Patient_CustomCode2") "CustomCode2Count",

      count(distinct h."Patient_CustomCode3") "CustomCode3Count",

      count(distinct h."Patient_CustomCode4") "CustomCode4Count",

      count(distinct h."Patient_CustomCode5") "CustomCode5Count",

      count(distinct h."Patient_CustomCode6") "CustomCode6Count",

      count(distinct h."Patient_CustomCode7") "CustomCode7Count",

      count(distinct h."Patient_CustomCode8") "CustomCode8Count",

      count(distinct h."Patient_CustomCode9") "CustomCode9Count",

      count(distinct h."Patient_CustomCode10") "CustomCode10Count",

      count(distinct h."OrthoStatus") "OrthoStatusCount"

    from history_ar_global_temp h

    where 1=1

    and h."Type" < 5

    and h."Family" = pFamily

    and h."OrigRecNo" = pOrigRecNo;

      

  cursor cSumTotals is

    select

      "History",

      "HistoryType",

      "OrigRecNo",

      "Type",

      "Id",

      "Treatment",

      "ModifiedDate",

      "TreatmentDate",

      "Producer",

      "Procedure",

      "Patient",

      "Family",

      "Code",

      "Description",     

      "Company1",

      "ReportDepartment",

      "ReportDiscipline",

      "ReportProcedure",

      "ReportPractice",

      "ReportClaimDoctor",

      "ReportLocation",

      "ReportEntryUser",

      "ReportAppUser",

      "ReportCustom1",

      "ReportCustom2",

      "ReportProducer",

      "ReportTypeCode",

      "ReportPGroup",

      "ReportYear",

      "ReportCustomCode1",

      "ReportCustomCode2",

      "ReportCustomCode3",

      "ReportCustomCode4",

      "ReportCustomCode5",

      "ReportCustomCode6",

      "ReportCustomCode7",

      "ReportCustomCode8",

      "ReportCustomCode9",

      "ReportCustomCode10",  

      "ReportGroupBy1",

      "ReportGroupBy1Description",

      "ReportGroupBy2",

      "ReportGroupBy2Description",

      "ReportFromDate",

      "ReportToDate",

      "ReportIsDetailed",

      "ReportIncludeUnallocated",

      "ReportHistoryTypeDescription",

      sum("ReportOldTotal") "ReportOldTotal",

      sum("ReportTotal") "ReportTotal",

      sum("ReportTotalChange") "ReportTotalChange",

      sum("ReportOldInsTotal") "ReportOldInsTotal",

      sum("ReportInsTotal") "ReportInsTotal",

      sum("ReportInsTotalChange") "ReportInsTotalChange",

      sum("ReportOldPayed") "ReportOldPayed",

      sum("ReportPayed") "ReportPayed",

      sum("ReportPayedChange") "ReportPayedChange",

      sum("ReportOldInsPayed") "ReportOldInsPayed",

      sum("ReportInsPayed") "ReportInsPayed",

      sum("ReportInsPayedChange") "ReportInsPayedChange",

      sum("ReportOldPtAdj") "ReportOldPtAdj",

      sum("ReportPtAdj") "ReportPtAdj",

      sum("ReportPtAdjChange") "ReportPtAdjChange",

      sum("ReportOldInsAdj") "ReportOldInsAdj",

      sum("ReportInsAdj") "ReportInsAdj",

      sum("ReportInsAdjChange") "ReportInsAdjChange",

      sum("ReportOldInsTransfer") "ReportOldInsTransfer",

      sum("ReportInsTransfer") "ReportInsTransfer",

      sum("ReportInsTransferChange") "ReportInsTransferChange"

    from history_ar_global_temp3

    where 1=1

    group by

      "History",

      "HistoryType",

      "OrigRecNo",

      "Type",

      "Id",

      "Treatment",

      "ModifiedDate",

      "TreatmentDate",

      "Producer",

      "Procedure",

      "Patient",

      "Family",

      "Code",

      "Description",

      "Company1",

      "ReportDepartment",

      "ReportDiscipline",

      "ReportProcedure",

      "ReportPractice",

      "ReportClaimDoctor",

      "ReportLocation",

      "ReportEntryUser",

      "ReportAppUser",

      "ReportCustom1",

      "ReportCustom2",

      "ReportProducer",

      "ReportTypeCode",

      "ReportPGroup",

      "ReportYear",

      "ReportCustomCode1",

      "ReportCustomCode2",

      "ReportCustomCode3",

      "ReportCustomCode4",

      "ReportCustomCode5",

      "ReportCustomCode6",

      "ReportCustomCode7",

      "ReportCustomCode8",

      "ReportCustomCode9",

      "ReportCustomCode10",  

      "ReportGroupBy1",

      "ReportGroupBy1Description",

      "ReportGroupBy2",

      "ReportGroupBy2Description",

      "ReportFromDate",

      "ReportToDate",

      "ReportIsDetailed",

      "ReportIncludeUnallocated",

      "ReportHistoryTypeDescription"

    having count(*) > 1;

    

  cursor cComputeBuckets is    

    select

      ctid,

      "History",

      "History2"

    from (select 

            h3.ctid,

            h3."History",

            (select /*+ index(h2 history_ar_global_temp3_idx2) */

               max(h2."History")

             from history_ar_global_temp3 h2

             where 1=1

             and h2."History" < h3."History"

             and h2."HistoryType" = h3."HistoryType"

             and h2."OrigRecNo" = h3."OrigRecNo"

             and h2."Type" = h3."Type") "History2"

          from (select /*+ full (h) */

                  h.ctid,

                  h."History",

                  h."HistoryType",

                  h."OrigRecNo",

                  h."Type"

                from history_ar_global_temp3 h

                where 1=1

                and h."HistoryType" = 3) h3

          where 1=1)

    where 1=1

    and "History2" is not null

    order by

      "History",

      "History2";

      

  cursor cOrthoTrx (pOrigRecNo history_ar_global_temp2."OrigRecNo"%type,

                    pFamily history_ar_global_temp2."Family"%type) is

    select

      min("ToHistory") "ToHistory",

      "FromHistory"

    from (select 

            h."History" "ToHistory",

            (select /*+ index(h2 history_ar_global_temp2_idx2) */ min(h2."History")

             from history_ar_global_temp2 h2

             where 1=1

             and h2."OrthoStatus" = 0

             and h2."OrigRecNo" = pOrigRecNo

             and h2."Family" = pFamily

             and h2."History" > h."History") "FromHistory"

          from (select /*+ index(h3 history_ar_global_temp2_idx2) */ distinct h3."History"

                from history_ar_global_temp2 h3

                where 1=1

                and h3."OrthoStatus" = 1

                and h3."Family" = pFamily

                and h3."OrigRecNo" = pOrigRecNo) h

          where 1=1)    

    where 1=1

    group by "FromHistory"        

    order by 1, 2;



  vFromDate date := trunc(pFromDate);

  vToDate date := (trunc(pToDate) + (23.9998/24));



  vChangeColumn1  VARCHAR2(30);

  vGroupColumn1  VARCHAR2(30);

  vChangeColumn2  VARCHAR2(30);

  vGroupColumn2  VARCHAR2(30);  

  vReportGroupBy1Description history_ar_global_temp."ReportGroupBy1Description"%type;

  vReportGroupBy2Description history_ar_global_temp."ReportGroupBy2Description"%type;

  

  vGroupChanged number(1) := 0;

  vDeptCount number(1) := 0;

  

  -- constants

  vCurrent history_ar_global_temp2."ReportPeriod"%type := 'CURRENT    ';

  vPrevious history_ar_global_temp2."ReportPeriod"%type := 'PREVIOUS   ';

  vNew history_ar_global_temp2."ReportHistoryTypeDescription"%type := 'New';

  vModified history_ar_global_temp3."ReportHistoryTypeDescription"%type := 'Modified';

  vAllocate history_ar_global_temp3."ReportHistoryTypeDescription"%type := 'Allocate';

  vDelete history_ar_global_temp3."ReportHistoryTypeDescription"%type := 'Delete';

  vTransferIn history_ar_global_temp3."ReportHistoryTypeDescription"%type := 'Transfer In';

  vTransferOut history_ar_global_temp3."ReportHistoryTypeDescription"%type := 'Transfer Out';

  vToOrthoPlan history_ar_global_temp3."ReportHistoryTypeDescription"%type := 'To Ortho Plan';

  vFromOrthoPlan history_ar_global_temp3."ReportHistoryTypeDescription"%type := 'From Ortho Plan';  

  vUnknown history_ar_global_temp3."ReportHistoryTypeDescription"%type := 'Unknown';

  

  vMinHistory history_ar_global_temp2."History"%type;

  vMaxHistory history_ar_global_temp."History"%type;

  vTemp number := 0;

  vOut number := 0;

  

  v_step number(3) := 0;



  --

  -- AX-20468 (make it easy to troubleshoot issue with AX-659)

  --

  vHistory history_ar_global_temp3."History"%type := 0;

  vHistory2 history_ar_global_temp3."History"%type := 0;

  ora_01427 exception;

  pragma exception_init(ora_01427, -1427);



  -- SF-00278253

  vSysdate date := sysdate;

  vBatch ar_recon_saved_data_hdr."Batch"%type := 0;

  vIsDetailed integer := 0;

  vBeginningBalance ar_recon_saved_data_hdr."BeginningBalance"%type := 0;

  vEndingBalance ar_recon_saved_data_hdr."EndingBalance"%type := 0;

  vExpiryDate date := nvl(trunc(pExpiryDate), trunc(sysdate));

  vReturnBatch ar_recon_saved_data_hdr."Batch"%type := 0;



  --

  -- AX-27637

  --

  vCounter integer := 0;

  vCalculateDepartment integer := 0;

  vSQLStmt  VARCHAR2(32767) :=

'update /*+ full(h) parallel(h, 4) */ history_ar_global_temp h


where 1=1

';

  

begin

  --

  -- reduce REDO/rollback segments used by GTTs (introduced in Oracle Database 12C Release 1 (12.1))

  --

  v_step := 5;

  

  begin

    execute immediate 'ALTER SESSION SET TEMP_UNDO_ENABLED = TRUE';

  exception

    when others then

      null;

  end;



  --

  -- truncate temporary tables; shouldn't be necessary when global temporary table is created

  --

  v_step := 10;

                                        

  execute immediate 'truncate table history_ar_global_temp';

  execute immediate 'truncate table history_ar_global_temp2';

  execute immediate 'truncate table history_ar_global_temp3';

  execute immediate 'truncate table history_ar_global_temp4';



  --

  -- force parallel execution if possible to improve performance (SF-00278253)

  --

  v_step := 15;

  

--  execute immediate 'ALTER SESSION FORCE PARALLEL DML PARALLEL 4';            -- AX-26491 (commented-out)

--  execute immediate 'ALTER SESSION FORCE PARALLEL QUERY PARALLEL 4';          -- AX-27416 (commented out) 

  

  --

  -- delete expired records from table AR_RECON_SAVED_DATA_HDR

  -- AX-26491.js commented this step out; leave the header records around for reporting purposes

  --

  v_step := 17;

  

  -- delete from ar_recon_saved_data_hdr

  -- where 1=1

  -- and "ReportType" = 0                                                          -- AX-26491

  -- and "ExpiryDate" < trunc(vSysdate);

  

  --

  -- delete expired records from table AR_RECON_SAVED_DATA_DTL

  -- AX-26491.js altered the query as header will still be around from above

  --

  v_step := 18;

  

  delete from ar_recon_saved_data_dtl d

  where 1=1

  and exists (select null

              from ar_recon_saved_data_hdr h

              where 1=1

              and h."Batch" = d."Batch"

              and h."ExpiryDate" < trunc(vSysdate));

                  

  --

  -- delete records from table AR_RECON_SAVED_DATA_HDR where there are no equivalent records from AR_RECON_SAVED_DATA_DTL

  -- AX-26491.js commented this out; want to leave the header records around

  --

  v_step := 19;

  

  -- delete from ar_recon_saved_data_hdr h

  -- where 1=1

  -- and h."ReportType" = 0                                                        -- AX-26491

  -- and not exists (select null

  --                from ar_recon_saved_data_dtl d

  --                where 1=1

  --                and d."Batch" = h."Batch");



  --

  -- get group by column names

  --

  v_step := 20;

  

  select 

    ar_dept_pkg.ar_get_group_by_column_name_f (pGroupBy1, 1),

    ar_dept_pkg.ar_get_group_by_column_name_f (pGroupBy1, 0),

    ar_dept_pkg.ar_get_group_by_column_name_f (pGroupBy2, 1),

    ar_dept_pkg.ar_get_group_by_column_name_f (pGroupBy2, 0),

    ar_dept_pkg.ar_get_group_by_desc_f (pGroupBy1),

    ar_dept_pkg.ar_get_group_by_desc_f (pGroupBy2)

  into

    vChangeColumn1,

    vGroupColumn1,

    vChangeColumn2,

    vGroupColumn2,

    vReportGroupBy1Description,

    vReportGroupBy2Description

  from dual

  where 1=1;



  --

  -- check if report data exists in tables AR_RECON_SAVED_DATA_HDR and AR_RECON_SAVED_DATA_HDR for the same parameters (SF-00278253)

  --

  if (pRecalculate = 1) then

    --

    -- check and delete data from tables AR_RECON_SAVED_DATA_HDR and AR_RECON_SAVED_DATA_HDR if they exists

    --

    begin

    

      v_step := 21;

          

      select arh."Batch"

      into vBatch

      from ar_recon_saved_data_hdr arh

      where 1=1

      and arh."ReportType" = 0                                                  -- AX-26491

      and arh."IncludeUnallocated" = pIncludeUnallocated

      and arh."GroupBy2" = pGroupBy2

      and arh."GroupBy1" = pGroupBy1

      and arh."ToDate" = vToDate

      and arh."FromDate" = vFromDate

      and arh."Department" = pDepartment

      and arh."ExpiryDate" >= trunc(sysdate);					-- AX-26491.js only care about non-expired records



      v_step := 22;

          

      delete from ar_recon_saved_data_hdr arh

      where 1=1

      and arh."ReportType" = 0                                                  -- AX-26491

      and arh."Batch" = vBatch;

    

      v_step := 23;

      

      -- AX-26491.js altered the query to delete details for teh given batch only

      delete from ar_recon_saved_data_dtl ard

      where 1=1

      and ard."Batch" = vBatch;

      

    exception

      when others then

        null;

    end;

  

    --

    -- insert into AR_RECON_SAVED_DATA_HDR; AX-26473; AX-26473.2

    --

    v_step := 24;

    

    insert into ar_recon_saved_data_hdr

    select

      ar_recon_saved_data_hdr_seq.nextval "Batch",

      vExpiryDate "ExpiryDate",

      vSysdate "FirstRunDate",

      vSysdate "LastRunDate",

      pDepartment "Department",

      vFromDate "FromDate",

      vToDate "ToDate",

      pGroupBy1 "GroupBy1",

      vReportGroupBy1Description "GroupBy1Description",

      pGroupBy2 "GroupBy2",

      vReportGroupBy2Description "GroupBy2Description",

      pIsDetailed "IsDetailed",

      pIncludeUnallocated "IncludeUnallocated",

      pPatient "Patient",

      pOrigRecNo "OrigRecNo",

      0 "BeginningBalance",

      0 "PeriodBalance",

      0 "EndingBalance",

      0 "ReportType",

      vSysdate "StartDateTime",

      to_date(null) "EndDateTime"

    from dual

    where 1=1;

    

    vBatch := ar_recon_saved_data_hdr_seq.currval;

    vReturnBatch := vBatch;



  else



    begin

      --

      -- check if data exists from tables AR_RECON_SAVED_DATA_HDR and AR_RECON_SAVED_DATA_HDR and, if they exists, use existing data for the report

      --

      v_step := 25;

      

      select

        arh."Batch",

        arh."IsDetailed"

      into

        vBatch,

        vIsDetailed

      from ar_recon_saved_data_hdr arh

      where 1=1

      and arh."ReportType" = 0                                                  -- AX-26491

      and exists (select null

                  from ar_recon_saved_data_dtl ard

                  where 1=1

                  and ard."Batch" = arh."Batch")

      and arh."IncludeUnallocated" = pIncludeUnallocated

      and arh."GroupBy2" = pGroupBy2

      and arh."GroupBy1" = pGroupBy1

      and arh."ToDate" = vToDate

      and arh."FromDate" = vFromDate

      and arh."Department" = pDepartment

      and arh."ExpiryDate" >= trunc(vSysdate);                                 -- AX-26491.js

    

      if (vIsDetailed <> pIsDetailed) then

    

        v_step := 26;

        

        update ar_recon_saved_data_dtl ard

        set ard."ReportIsDetailed" = pIsDetailed

        where 1=1

        and ard."Batch" = vBatch;

    

      end if;

    

      --

      -- copy existing report data into HISTORY_AR_GLOBAL_TEMP3

      --

      v_step := 27;

      

      insert into history_ar_global_temp3

      select

        ard."History",

        ard."HistoryType",

        ard."OrigRecNo",

        ard."Type",

        ard."Id",

        ard."Treatment",

        ard."ModifiedDate",

        ard."TreatmentDate",

        ard."Producer",

        ard."Procedure",

        ard."Patient",

        ard."Family",

        ard."Code",

        ard."Description",  

        ard."Company1",    

        ard."ReportDepartment",

        ard."ReportDiscipline",

        ard."ReportProcedure",

        ard."ReportPractice",

        ard."ReportClaimDoctor",

        ard."ReportLocation",

        ard."ReportEntryUser",

        ard."ReportAppUser",

        ard."ReportCustom1",

        ard."ReportCustom2",

        ard."ReportProducer",

        ard."ReportTypeCode",

        ard."ReportPGroup",

        ard."ReportYear",

        ard."ReportCustomCode1",

        ard."ReportCustomCode2",

        ard."ReportCustomCode3",

        ard."ReportCustomCode4",

        ard."ReportCustomCode5",

        ard."ReportCustomCode6",

        ard."ReportCustomCode7",

        ard."ReportCustomCode8",

        ard."ReportCustomCode9",

        ard."ReportCustomCode10",

        ard."ReportGroupBy1",

        ard."ReportGroupBy1Description",

        ard."ReportGroupBy2",

        ard."ReportGroupBy2Description",

        ard."ReportFromDate",

        ard."ReportToDate",

        ard."ReportIsDetailed",

        ard."ReportIncludeUnallocated",

        ard."ReportHistoryTypeDescription",

        ard."ReportOldTotal",

        ard."ReportTotal",

        ard."ReportTotalChange",

        ard."ReportOldInsTotal",

        ard."ReportInsTotal",

        ard."ReportInsTotalChange",

        ard."ReportOldPayed",

        ard."ReportPayed",

        ard."ReportPayedChange",

        ard."ReportOldInsPayed",

        ard."ReportInsPayed",

        ard."ReportInsPayedChange",

        ard."ReportOldPtAdj",

        ard."ReportPtAdj",

        ard."ReportPtAdjChange",

        ard."ReportOldInsAdj",

        ard."ReportInsAdj",

        ard."ReportInsAdjChange",

        ard."ReportOldInsTransfer",

        ard."ReportInsTransfer",

        ard."ReportInsTransferChange",

        ard."PreviousHistory"                                                   -- AX-28014

      from ar_recon_saved_data_dtl ard

      where 1=1

      and ard."Batch" = vBatch;



      v_step := 28;

      

      update ar_recon_saved_data_hdr arh

      set

        arh."ExpiryDate" = decode(pUpdateExpiryDateIfNotNewData, 0, arh."ExpiryDate", vExpiryDate),

        arh."LastRunDate" = vSysdate,

        arh."IsDetailed" = pIsDetailed

      where 1=1

      and arh."ReportType" = 0                                                  -- AX-26491

      and arh."Batch" = vBatch;



      vReturnBatch := vBatch;  

      vBatch := 0;



    exception

      when no_data_found then

        --

        -- insert into AR_RECON_SAVED_DATA_HDR; AX-26473; AX-26473.2

        --

        v_step := 29;

        

        insert into ar_recon_saved_data_hdr

        select

          ar_recon_saved_data_hdr_seq.nextval "Batch",

          vExpiryDate "ExpiryDate",

          vSysdate "FirstRunDate",

          vSysdate "LastRunDate",

          pDepartment "Department",

          vFromDate "FromDate",

          vToDate "ToDate",

          pGroupBy1 "GroupBy1",

          vReportGroupBy1Description "GroupBy1Description",

          pGroupBy2 "GroupBy2",

          vReportGroupBy2Description "GroupBy2Description",

          pIsDetailed "IsDetailed",

          pIncludeUnallocated "IncludeUnallocated",

          pPatient "Patient",

          pOrigRecNo "OrigRecNo",

          0 "BeginningBalance",

          0 "PeriodBalance",

          0 "EndingBalance",

          0 "ReportType",

          vSysdate "StartDateTime",

          to_date(null) "EndDateTime"

        from dual

        where 1=1;

      

        vBatch := ar_recon_saved_data_hdr_seq.currval;

        vReturnBatch := vBatch;



    end;



  end if;



if (vBatch > 0) then     -- SF-00278253 (reprocess report data)



  --

  -- get the history records for the period

  --

  v_step := 30;

  

  if ((pOrigRecNo = 0) and (pPatient = 0)) then

  

    insert into history_ar_global_temp

    select /*+ parallel(h, 4) */

      h.*,

      vCurrent "ReportPeriod",

      ' ' "Department",

      ' ' "Producer_TypeCode",

      ' ' "Producer_PGroup",

      0 "Producer_Year",

      ' ' "Patient_CustomCode1",

      ' ' "Patient_CustomCode2",

      ' ' "Patient_CustomCode3",

      ' ' "Patient_CustomCode4",

      ' ' "Patient_CustomCode5",

      ' ' "Patient_CustomCode6",

      ' ' "Patient_CustomCode7",

      ' ' "Patient_CustomCode8",

      ' ' "Patient_CustomCode9",

      ' ' "Patient_CustomCode10",

      pGroupBy1,

      vReportGroupBy1Description,

      pGroupBy2,

      vReportGroupBy2Description,

      vFromDate,

      vToDate,

      pIsDetailed,

      pIncludeUnallocated

    from history h

    where 1=1

    and (h."Type" = 1

         or h."Type" = 2

         or (h."Type" = 5 and h."OrthoStatus" = 0))

    and h."ModifiedDate" between vFromDate and vToDate

    and trunc(h."ModifiedDate") between vFromDate and vToDate

    and

    -- Added by Jon Dawes 2016-03-11.

    (--

    --

    h."TreatmentDate" <= vToDate

    --

    -- Added by Jon Dawes 2016-03-11.

    or h."Type" = 2)

    --

    order by     -- SF-00278253

      h."OrigRecNo",

      h."Family",

      h."History"

    ;



    --

    -- AX-20468 (insert post-dated office charges)

    --

    v_step := 32;

    

    insert into history_ar_global_temp

    select /*+ parallel(h, 4) */

      h.*,

      vCurrent "ReportPeriod",

      ' ' "Department",

      ' ' "Producer_TypeCode",

      ' ' "Producer_PGroup",

      0 "Producer_Year",

      ' ' "Patient_CustomCode1",

      ' ' "Patient_CustomCode2",

      ' ' "Patient_CustomCode3",

      ' ' "Patient_CustomCode4",

      ' ' "Patient_CustomCode5",

      ' ' "Patient_CustomCode6",

      ' ' "Patient_CustomCode7",

      ' ' "Patient_CustomCode8",

      ' ' "Patient_CustomCode9",

      ' ' "Patient_CustomCode10",

      pGroupBy1,

      vReportGroupBy1Description,

      pGroupBy2,

      vReportGroupBy2Description,

      vFromDate,

      vToDate,

      pIsDetailed,

      pIncludeUnallocated

    from history h

    where 1=1

    and h."Type" = 2

    and ((h."ModifiedDate" between vFromDate and vToDate

          and trunc(h."ModifiedDate") between vFromDate and vToDate)

         or (h."TreatmentDate" between vFromDate and vToDate

             and trunc(h."TreatmentDate") between vFromDate and vToDate))

    and not exists (select null

                    from history_ar_global_temp h2

                    where 1=1

                    and h2."History" = h."History")

    order by     -- SF-00278253

      h."OrigRecNo",

      h."Family",

      h."History"

;



  else

  

    insert into history_ar_global_temp

    select /*+ parallel(h, 4) */

      h.*,

      vCurrent "ReportPeriod",

      ' ' "Department",

      ' ' "Producer_TypeCode",

      ' ' "Producer_PGroup",

      0 "Producer_Year",

      ' ' "Patient_CustomCode1",

      ' ' "Patient_CustomCode2",

      ' ' "Patient_CustomCode3",

      ' ' "Patient_CustomCode4",

      ' ' "Patient_CustomCode5",

      ' ' "Patient_CustomCode6",

      ' ' "Patient_CustomCode7",

      ' ' "Patient_CustomCode8",

      ' ' "Patient_CustomCode9",

      ' ' "Patient_CustomCode10",

      pGroupBy1,

      vReportGroupBy1Description,

      pGroupBy2,

      vReportGroupBy2Description,

      vFromDate,

      vToDate,

      pIsDetailed,

      pIncludeUnallocated

    from history h

    where 1=1

    and h."OrigRecNo" = decode(pOrigRecNo, 0, h."OrigRecNo", pOrigRecNo)

    and h."Patient" = decode(pPatient, 0, h."Patient", pPatient)  

    and (h."Type" = 1

         or h."Type" = 2

         or (h."Type" = 5 and h."OrthoStatus" = 0))

    and h."ModifiedDate" between vFromDate and vToDate

    and trunc(h."ModifiedDate") between vFromDate and vToDate

    and

    -- Added by Jon Dawes 2016-03-11.

    (--

    --

    h."TreatmentDate" <= vToDate

    --

    -- Added by Jon Dawes 2016-03-11.

    or h."Type" = 2)

    --

    order by     -- SF-00278253

      h."OrigRecNo",

      h."Family",

      h."History"

    ;    



    --

    -- AX-20468 (insert post-dated office charges)

    --

    v_step := 34;



    insert into history_ar_global_temp

    select /*+ parallel(h, 4) */

      h.*,

      vCurrent "ReportPeriod",

      ' ' "Department",

      ' ' "Producer_TypeCode",

      ' ' "Producer_PGroup",

      0 "Producer_Year",

      ' ' "Patient_CustomCode1",

      ' ' "Patient_CustomCode2",

      ' ' "Patient_CustomCode3",

      ' ' "Patient_CustomCode4",

      ' ' "Patient_CustomCode5",

      ' ' "Patient_CustomCode6",

      ' ' "Patient_CustomCode7",

      ' ' "Patient_CustomCode8",

      ' ' "Patient_CustomCode9",

      ' ' "Patient_CustomCode10",

      pGroupBy1,

      vReportGroupBy1Description,

      pGroupBy2,

      vReportGroupBy2Description,

      vFromDate,

      vToDate,

      pIsDetailed,

      pIncludeUnallocated

    from history h

    where 1=1

    and h."OrigRecNo" = decode(pOrigRecNo, 0, h."OrigRecNo", pOrigRecNo)

    and h."Patient" = decode(pPatient, 0, h."Patient", pPatient)

    and h."Type" = 2

    and ((h."ModifiedDate" between vFromDate and vToDate

          and trunc(h."ModifiedDate") between vFromDate and vToDate)

         or (h."TreatmentDate" between vFromDate and vToDate

             and trunc(h."TreatmentDate") between vFromDate and vToDate))

    and not exists (select null

                    from history_ar_global_temp h2

                    where 1=1

                    and h2."History" = h."History")

    order by     -- SF-00278253

      h."OrigRecNo",

      h."Family",

      h."History"

;



  end if;

  

  --

  -- get the last history records prior to the period for each OrigRecNo

  --

  v_step := 40;



  insert into history_ar_global_temp4

  select /*+ full(h)

             parallel(h, 4)

             full(h2)

             parallel(h2, 4) */

    max(h."History")

  from 

    history h,

    history_ar_global_temp h2

  where 1=1

  and h."ModifiedDate" < vFromDate

  and h."TreatmentDate" < vFromDate

  and h2."Type" < 5

  and h2."OrigRecNo" = h."OrigRecNo"

  group by 

    h."Type",

    h."OrigRecNo";



  --

  -- get the last history records prior to the period

  --

  v_step := 50;

  

  if (pPatient = 0) then

  

    insert into history_ar_global_temp

    select

      h.*,

      vPrevious "ReportPeriod",

      ' ' "Department",

      ' ' "Producer_TypeCode",

      ' ' "Producer_PGroup",

      0 "Producer_Year",

      ' ' "Patient_CustomCode1",

      ' ' "Patient_CustomCode2",

      ' ' "Patient_CustomCode3",

      ' ' "Patient_CustomCode4",

      ' ' "Patient_CustomCode5",

      ' ' "Patient_CustomCode6",

      ' ' "Patient_CustomCode7",

      ' ' "Patient_CustomCode8",

      ' ' "Patient_CustomCode9",

      ' ' "Patient_CustomCode10",

      pGroupBy1,

      vReportGroupBy1Description,

      pGroupBy2,

      vReportGroupBy2Description,

      vFromDate,

      vToDate,

      pIsDetailed,

      pIncludeUnallocated

    from 

      history h,

      history_ar_global_temp4 h2

    where 1=1

    and (h."Type" = 1

         or h."Type" = 2)

    and h2."History" = h."History"

    order by     -- SF-00278253

      h."OrigRecNo",

      h."Family",

      h."History"

;

  

  else

  

    insert into history_ar_global_temp

    select

      h.*,

      vPrevious "ReportPeriod",

      ' ' "Department",

      ' ' "Producer_TypeCode",

      ' ' "Producer_PGroup",

      0 "Producer_Year",

      ' ' "Patient_CustomCode1",

      ' ' "Patient_CustomCode2",

      ' ' "Patient_CustomCode3",

      ' ' "Patient_CustomCode4",

      ' ' "Patient_CustomCode5",

      ' ' "Patient_CustomCode6",

      ' ' "Patient_CustomCode7",

      ' ' "Patient_CustomCode8",

      ' ' "Patient_CustomCode9",

      ' ' "Patient_CustomCode10",

      pGroupBy1,

      vReportGroupBy1Description,

      pGroupBy2,

      vReportGroupBy2Description,

      vFromDate,

      vToDate,

      pIsDetailed,

      pIncludeUnallocated

    from 

      history h,

      history_ar_global_temp4 h2

    where 1=1

    and h."Patient" = pPatient

    and (h."Type" = 1

         or h."Type" = 2)

    and h2."History" = h."History"

    order by     -- SF-00278253

      h."OrigRecNo",

      h."Family",

      h."History"

;

  

  end if;

   

  --

  -- removed striked-out records

  --

  v_step := 60;

  

  delete from history_ar_global_temp h

  where 1=1

  and h."HistoryType" = 4

  and h."Deleted" = 2;

  

  --

  -- removed invalid patients

  --  

  v_step := 70;

  

  delete from history_ar_global_temp h

  where 1=1

  and not exists (select null

                  from patient p

                  where 1=1

                  and p."Patient" = h."Patient");

                  

  --

  -- remove striked-out records

  --

  v_step := 80;

  

  delete from history_ar_global_temp h

  where 1=1

  and h."History" > (select min(h2."History")

                     from history_ar_global_temp h2

                     where 1=1

                     and h2."OrigRecNo" = h."OrigRecNo"

                     and h2."HistoryType" = 4

                     and h2."Deleted" = 1);

     

  --

  -- remove unnecessary ortho records

  --

  v_step := 90;

  

  delete from history_ar_global_temp h3

  where 1=1

  and h3."OrthoStatus" = 1

  and (h3."OrigRecNo",

       h3."Family",

       h3."History") not in (select

                               "OrigRecNo",

                               "Family",

                               min("ToHistory") "ToHistory"

                             from (select

                                     h."OrigRecNo",

                                     h."Family",

                                     h."History" "ToHistory",

                                     (select min(h2."History")

                                      from history_ar_global_temp h2

                                      where 1=1

                                      and h2."OrthoStatus" = 0

                                      and h2."OrigRecNo" = h."OrigRecNo"

                                      and h2."Family" = h."Family"

                                      and h2."History" > h."History") "FromHistory"

                                   from (select 

                                           "OrigRecNo",

                                           "Family",

                                           "History"

                                         from history_ar_global_temp

                                         where 1=1

                                         and "OrthoStatus" = 1) h

                                   where 1=1)

                             where 1=1

                             group by

                               "OrigRecNo",

                               "Family",    

                               "FromHistory");

  --

  -- Added by Jon Dawes 2016-03-11

  -- Remove all post dated office charge history records that are not

  -- immediately preceded by records that are not post dated.

  --

  v_step := 95;

  

  delete from history_ar_global_temp h

  where 1=1

  and h."Type" = 2

  and h."TreatmentDate" > vToDate

  and not exists (select null

                  from history_ar_global_temp h1

                  where 1=1

                  and h1."OrigRecNo" = h1."OrigRecNo"

                  and h1."TreatmentDate" <= vToDate

                  and h1."History" < h."History"

                  and not exists (select null

                                  from history_ar_global_temp h2

                                  where 1=1

                                  and h2."OrigRecNo" = h."OrigRecNo"

                                  and h2."TreatmentDate" <= vToDate

                                  and h2."History" < h."History"

                                  and h2."History" > h1."History"));

  --



  --

  -- Added by Jon Dawes 2016-03-11

  -- Modify post dated office charges to remove the amount on all non-insurance

  -- buckets.

  --

  v_step := 96;

  

  update history_ar_global_temp h

  set

    h."Total" = 0, 

    h."Payed" = 0, 

    h."PtAdj" = 0

  where 1=1

  and h."Type" = 2

  and h."TreatmentDate" > vToDate;



  --

  -- AX-20468 (remove office charge records that were modified after the reporting period)

  --

  v_step := 97;

  

  delete from history_ar_global_temp

  where 1=1

  and "Type" = 2

  and "TreatmentDate" between vFromDate and vToDate

  and "ModifiedDate" > vToDate;



  --

  -- AX-27637: determine if department needs to be calculated (may slow down processing time) or just use whatever department is passed to the procedure (can reduce processing time)

  --

  begin

    --

    -- check if department has corresponding department definition

    --

    v_step := 98;

  

    select 1

    into vCalculateDepartment

    from dept d

    where 1=1

    and exists (select null

                from deptdef dd

                where 1=1

                and dd."Department" = d."Department")

    and d."Department" = pDepartment;

    

  exception

    when no_data_found then

      --

      -- use whatever department is passed to the procedure

      --

      v_step := 99;

      

      vCalculateDepartment := 0;



  end;



  --

  -- update provider, patient, department, group by information

  --

--  if (pDepartment = 'zzzzzz') then

  if ((pDepartment = 'zzzzzz') or (vCalculateDepartment = 0)) then

    --

    -- do not call AR_GET_DEPT_F

    --

    v_step := 100;



    update /*+ full(h)

               parallel(h, 4) */ history_ar_global_temp h

    set

      (h."Producer_TypeCode",

       h."Producer_PGroup",

       h."Producer_Year") = (select /*+ index(prod, PRODUCER_PRIMARY) */

                               prod."TypeCode", 

                               prod."PGroup", 

                               prod."Year"

                             from producer prod

                             where 1=1

                             and prod."Producer" = h."Producer"),      

      (h."Patient_CustomCode1",

       h."Patient_CustomCode2",

       h."Patient_CustomCode3",

       h."Patient_CustomCode4",

       h."Patient_CustomCode5",

       h."Patient_CustomCode6",

       h."Patient_CustomCode7",

       h."Patient_CustomCode8",

       h."Patient_CustomCode9",

       h."Patient_CustomCode10") = (select /*+ index(pat, PATIENT_PRIMARY) */

                                      pat."CustomCode1",

                                      pat."CustomCode2",

                                      pat."CustomCode3",

                                      pat."CustomCode4",

                                      pat."CustomCode5",

                                      pat."CustomCode6",

                                      pat."CustomCode7",

                                      pat."CustomCode8",

                                      pat."CustomCode9",

                                      pat."CustomCode10"

                                    from patient pat

                                    where 1=1

                                    and pat."Patient" = h."Patient"),

      h."Department" = pDepartment

    where 1=1;



  else

    --

    -- update PRODUCER and PATIENT related fields

    --

    v_step := 101;

    

    update /*+ full(h)

               parallel(h, 4) */ history_ar_global_temp h

    set

      (h."Producer_TypeCode",

       h."Producer_PGroup",

       h."Producer_Year") = (select /*+ index(prod, PRODUCER_PRIMARY) */

                               prod."TypeCode", 

                               prod."PGroup", 

                               prod."Year"

                             from producer prod

                             where 1=1

                             and prod."Producer" = h."Producer"),

      (h."Patient_CustomCode1",

       h."Patient_CustomCode2",

       h."Patient_CustomCode3",

       h."Patient_CustomCode4",

       h."Patient_CustomCode5",

       h."Patient_CustomCode6",

       h."Patient_CustomCode7",

       h."Patient_CustomCode8",

       h."Patient_CustomCode9",

       h."Patient_CustomCode10") = (select /*+ index(pat, PATIENT_PRIMARY) */

                                      pat."CustomCode1",

                                      pat."CustomCode2",

                                      pat."CustomCode3",

                                      pat."CustomCode4",

                                      pat."CustomCode5",

                                      pat."CustomCode6",

                                      pat."CustomCode7",

                                      pat."CustomCode8",

                                      pat."CustomCode9",

                                      pat."CustomCode10"

                                    from patient pat

                                    where 1=1

                                    and pat."Patient" = h."Patient"),

      h."Department" = 'zzzzzz'                                                 -- AX-27637

    where 1=1;



    --

    -- update department

    --

    begin

      --

      -- build SQL statement to update the department

      --

      v_step := 102;

    

      vSQLStmt := (vSQLStmt || ar_dept_pkg.ar_get_dept_f (pDepartment, 0, '', 0));

      

      --

      -- replace PRODUCER and PATIENT related strings to correct the SQL statement

      --

      v_step := 103;

      

      vSQLStmt := replace(vSQLStmt, 'prod."TypeCode"', 'h."Producer_TypeCode"');

      vSQLStmt := replace(vSQLStmt, 'prod."PGroup"', 'h."Producer_PGroup"');

      vSQLStmt := replace(vSQLStmt, 'prod."Year"', 'h."Producer_Year"');

      vSQLStmt := replace(vSQLStmt, 'pat."CustomCode1"', 'h."Patient_CustomCode1"');

      vSQLStmt := replace(vSQLStmt, 'pat."CustomCode2"', 'h."Patient_CustomCode2"');

      vSQLStmt := replace(vSQLStmt, 'pat."CustomCode3"', 'h."Patient_CustomCode3"');

      vSQLStmt := replace(vSQLStmt, 'pat."CustomCode4"', 'h."Patient_CustomCode4"');

      vSQLStmt := replace(vSQLStmt, 'pat."CustomCode5"', 'h."Patient_CustomCode5"');

      vSQLStmt := replace(vSQLStmt, 'pat."CustomCode6"', 'h."Patient_CustomCode6"');

      vSQLStmt := replace(vSQLStmt, 'pat."CustomCode7"', 'h."Patient_CustomCode7"');

      vSQLStmt := replace(vSQLStmt, 'pat."CustomCode8"', 'h."Patient_CustomCode8"');

      vSQLStmt := replace(vSQLStmt, 'pat."CustomCode9"', 'h."Patient_CustomCode9"');

      vSQLStmt := replace(vSQLStmt, 'pat."CustomCode10"', 'h."Patient_CustomCode10"');



      --

      -- execute SQL statement to update the department

      --

      v_step := 104;

  

      execute immediate vSQLStmt using pDepartment;



    exception

      when others then

        --

        -- update department using the original process

        --

        v_step := 105;



        update /*+ full(h) parallel(h, 4) */ history_ar_global_temp h

        set h."Department" = ar_dept_pkg.ar_get_dept_f (pDepartment, 

                                                        h."History", 

                                                        h."Producer", 

                                                        h."Patient")

        where 1=1;



    end;



  end if;



  --

  -- consider no change if one of the departments is 'zzzzzz'

  --

  v_step := 108;

          

  select count(*)

  into vDeptCount

  from history_ar_global_temp h

  where 1=1

  and h."Type" < 5

  and h."Department" = 'zzzzzz'

  and rownum = 1;  



  --

  -- insert latest transactions per OrigRecNo and offset records for deleted records into temp table (AX-27637:  moved outside of the cursor so inserts happen all at once instead of row by row)

  --

  v_step := 110;

  

  insert into history_ar_global_temp2

  with

  TmpMaxHistory as (

                    select 

                      h2."ReportPeriod",

                      h2."OrigRecNo",

                      h2."Family",

                      max(h2."History") "History"

                    from history_ar_global_temp h2

                    where 1=1

                    and h2."Type" < 5

                    group by

                      h2."ReportPeriod",

                      h2."OrigRecNo",

                      h2."Family"

                   )

  --

  -- latest transactions per OrigRecNo

  --

  select

     h.*,

     ' ' "ReportHistoryTypeDescription",

     h."Total",

     h."InsTotal",

     h."Payed",

     h."InsPayed",

     h."PtAdj",

     h."InsAdj",

     h."InsTransfer",    

     h."Department",

     h."Discipline",

     h."Procedure",

     h."Practice",

     h."ClaimDoctor",

     h."Location",

     h."EntryUser",

     h."AppUser",

     h."Custom1",

     h."Custom2",

     h."Producer",

     h."Producer_TypeCode",

     h."Producer_PGroup",

     h."Producer_Year",

     h."Patient_CustomCode1",

     h."Patient_CustomCode2",

     h."Patient_CustomCode3",

     h."Patient_CustomCode4",

     h."Patient_CustomCode5",

     h."Patient_CustomCode6",

     h."Patient_CustomCode7",

     h."Patient_CustomCode8",

     h."Patient_CustomCode9",

     h."Patient_CustomCode10"

   from

     history_ar_global_temp h,

     TmpMaxHistory tmh

   where 1=1

   and h."ReportPeriod" = tmh."ReportPeriod"

   and h."OrigRecNo" = tmh."OrigRecNo"

   and h."Family" = tmh."Family"

   and h."History" = tmh."History"

   union all

   --

   -- offset records for deleted records

   --

   select

     h3.*,

     decode(h3."OrthoStatus", 1, vToOrthoPlan, vDelete),

     (h3."Total" * -1),

     (h3."InsTotal" * -1),

     (h3."Payed" * -1),

     (h3."InsPayed" * -1),

     (h3."PtAdj" * -1),

     (h3."InsAdj" * -1),

     (h3."InsTransfer" * -1),

     h3."Department",

     h3."Discipline",

     h3."Procedure",

     h3."Practice",

     h3."ClaimDoctor",

     h3."Location",

     h3."EntryUser",

     h3."AppUser",

     h3."Custom1",

     h3."Custom2",

     h3."Producer",

     h3."Producer_TypeCode",

     h3."Producer_PGroup",

     h3."Producer_Year",

     h3."Patient_CustomCode1",

     h3."Patient_CustomCode2",

     h3."Patient_CustomCode3",

     h3."Patient_CustomCode4",

     h3."Patient_CustomCode5",

     h3."Patient_CustomCode6",

     h3."Patient_CustomCode7",

     h3."Patient_CustomCode8",

     h3."Patient_CustomCode9",

     h3."Patient_CustomCode10"

   from

     history_ar_global_temp h3,

     TmpMaxHistory tmh3

   where 1=1

   and h3."HistoryType" = 4

   and h3."Deleted" = 1

   and h3."ReportPeriod" = tmh3."ReportPeriod"

   and h3."OrigRecNo" = tmh3."OrigRecNo"

   and h3."Family" = tmh3."Family"

   and h3."History" = tmh3."History"   

   order by 120, 1;



   --

   -- save changes (AX-27637)

   --

   v_step := 120;



   commit;



  --

  -- create records for the AR report

  --

  for pMaxHistory2 in cMaxHistory2 loop

      --

      -- process changes

      --

      for pChanges in cChanges (pMaxHistory2."OrigRecNo",

                                pMaxHistory2."Family") loop

                              

        --

        -- initialize change flag; process change in department

        --

        v_step := 130;

      

        vGroupChanged := 0;

      

        if ((pChanges."DepartmentCount" > 1) and (vGroupChanged = 0)) then

          

          if (((pChanges."DepartmentCount" - vDeptCount) > 1) and (vGroupChanged = 0)) then



            ar_create_dept_txs_changes_p (pMaxHistory2."OrigRecNo",

                                          pMaxHistory2."Family",

                                          pMaxHistory2."History",

                                          vPrevious,    

                                          vChangeColumn1,

                                          vGroupColumn1,

                                          vChangeColumn2,

                                          vGroupColumn2);



            vGroupChanged := 1;

            

          end if;

          

        end if;

         

        --

        -- process change in group

        --

        v_step := 150;



        if (((pGroupBy1 > 0) or (pGroupBy2 > 0)) and ((pChanges."ProducerCount" > 1) or

                                                      (pChanges."PGroupCount" > 1) or

                                                      (pChanges."TypeCodeCount" > 1) or

                                                      (pChanges."YearCount" > 1) or

                                                      (pChanges."AppUserCount" > 1) or

                                                      (pChanges."Custom1Count" > 1) or

                                                      (pChanges."Custom2Count" > 1) or

                                                      (pChanges."DisciplineCount" > 1) or

                                                      (pChanges."EntryUserCount" > 1) or

                                                      (pChanges."LocationCount" > 1) or

                                                      (pChanges."ClaimDoctorCount" > 1) or

                                                      (pChanges."PracticeCount" > 1) or  

                                                      (pChanges."ProcedureCount" > 1) or

                                                      (pChanges."CustomCode1Count" > 1) or

                                                      (pChanges."CustomCode2Count" > 1) or

                                                      (pChanges."CustomCode3Count" > 1) or

                                                      (pChanges."CustomCode4Count" > 1) or

                                                      (pChanges."CustomCode5Count" > 1) or

                                                      (pChanges."CustomCode6Count" > 1) or

                                                      (pChanges."CustomCode7Count" > 1) or

                                                      (pChanges."CustomCode8Count" > 1) or

                                                      (pChanges."CustomCode9Count" > 1) or

                                                      (pChanges."CustomCode10Count" > 1) or

                                                      (pChanges."OrthoStatusCount" > 1)) and (vGroupChanged = 0)) then



          ar_create_dept_txs_changes_p (pMaxHistory2."OrigRecNo",

                                        pMaxHistory2."Family",

                                        pMaxHistory2."History",

                                        vPrevious,    

                                        vChangeColumn1,

                                        vGroupColumn1,

                                        vChangeColumn2,

                                        vGroupColumn2);



          vGroupChanged := 1;   

          

        end if;



        --

        -- process new and edited treatments within the same current period

        --

        v_step := 160;



        if (vGroupChanged = 0) then

        

          ar_create_dept_txs_changes_p (pMaxHistory2."OrigRecNo",

                                        pMaxHistory2."Family",

                                        pMaxHistory2."History",

                                        vPrevious,    

                                        vChangeColumn1,

                                        vGroupColumn1,

                                        vChangeColumn2,

                                        vGroupColumn2);

        else

        

          if ((pGroupBy1 = 0) and (pGroupBy2 = 0) and (pMaxHistory2."ReportPeriod" = vCurrent)) then

          

            for pMaxHistory in cMaxHistory (pMaxHistory2."ReportPeriod",

                                            pMaxHistory2."OrigRecNo",

                                            pMaxHistory2."Family",

                                            pMaxHistory2."History") loop

          

              if ((pMaxHistory."OrthoStatus" <> 1) and ((pMaxHistory."HistoryType" = 2) or ((pMaxHistory."HistoryType" = 5) and (pMaxHistory."OrthoStatus" = 0)))) then



                ar_create_dept_txs_changes_p (pMaxHistory2."OrigRecNo",

                                              pMaxHistory2."Family",

                                              pMaxHistory2."History",

                                              vPrevious,    

                                              vChangeColumn1,

                                              vGroupColumn1,

                                              vChangeColumn2,

                                              vGroupColumn2);



              end if;

              

            end loop;     -- pMaxHistory



          end if;

  

        end if;

        

        --

        --  change modify to new if origrecno is changed from P to I or C in current period

        --

        v_step := 170;



        select /*+ index(h2 history_ar_global_temp2_idx2) */ min(h2."History")

        into vMinHistory

        from history_ar_global_temp2 h2

        where 1=1

        and h2."Family" = pMaxHistory2."Family"

        and h2."OrigRecNo" = pMaxHistory2."OrigRecNo";

        

        if (vMinHistory is not null) then

        

          select /*+ index(h4 history_ar_global_temp_idx2) */ max(h4."History")

          into vMaxHistory

          from history_ar_global_temp h4

          where 1=1

          and (h4."HistoryType" < 4

               or h4."HistoryType" > 4)

          and h4."History" < vMinHistory

          and h4."Family" = pMaxHistory2."Family"

          and h4."OrigRecNo" = pMaxHistory2."OrigRecNo";

          

          if (vMaxHistory is not null) then

                                               

            begin

            

              begin

              

                select /*+ index(h3 history_ar_global_temp_idx1) */ 1

                into vTemp

                from history_ar_global_temp h3

                where 1=1

                and (h3."HistoryType" = 1

                     or ((h3."HistoryType" = 5) and (h3."OrthoStatus" = 0)))

                and h3."History" = vMaxHistory

                and rownum = 1;

                

              exception

                when no_data_found then

                  select /*+ index(h4 history_ar_global_temp_idx2) */ 1

                  into vTemp

                  from history_ar_global_temp h4

                  where 1=1

                  and (h4."HistoryType" < 4

                       or h4."HistoryType" > 4)                            

                  and (h4."Status" = 'P'

                       or h4."Status" = 'I')

                  and not exists (select /*+ index(h5 history_ar_global_temp_idx2) */ null

                                  from history_ar_global_temp h5

                                  where 1=1

                                  and (h5."HistoryType" < 4

                                       or h5."HistoryType" > 4)                                            

                                  and h5."Status" = 'C'

                                  and h5."History" < vMinHistory

                                  and h5."Family" = h4."Family"

                                  and h5."OrigRecNo" = h4."OrigRecNo")

                  and h4."History" < vMinHistory

                  and h4."Family" = pMaxHistory2."Family"

                  and h4."OrigRecNo" = pMaxHistory2."OrigRecNo"

                  and rownum = 1;

                  

              end;              

                        

              update /*+ index(h history_ar_global_temp2_idx1) */ history_ar_global_temp2 h

              set "ReportHistoryTypeDescription" = vNew

              where 1=1

              and (h."ReportHistoryTypeDescription" = vModified

                   or h."ReportHistoryTypeDescription" = vTransferIn

                   or h."ReportHistoryTypeDescription" = vTransferOut

                   or h."ReportHistoryTypeDescription" = ' ')

              and h."HistoryType" = 2

              and h."History" = vMinHistory;

--              and h."Family" = pMaxHistory2."Family"

--              and h."OrigRecNo" = pMaxHistory2."OrigRecNo";



            exception

              when no_data_found then

                null;

            end;

          

          end if;

          

        end if;        



        --

        -- process negative values

        --

        v_step := 180;



        update /*+ index(h history_ar_global_temp2_idx2) */ history_ar_global_temp2 h

        set 

          h."ReportPeriod" = vPrevious,

          h."ReportTotal" = (h."ReportTotal" * -1),

          h."ReportInsTotal" = (h."ReportInsTotal" * -1),

          h."ReportPayed" = (h."ReportPayed" * -1),

          h."ReportInsPayed" = (h."ReportInsPayed" * -1),

          h."ReportPtAdj" = (h."ReportPtAdj" * -1),

          h."ReportInsAdj" = (h."ReportInsAdj" * -1),

          h."ReportInsTransfer" = (h."ReportInsTransfer" * -1)

        where 1=1

        and h."ReportPeriod" = vCurrent

        and (h."ReportHistoryTypeDescription" = vTransferOut

             or h."ReportHistoryTypeDescription" = vModified

             or h."ReportHistoryTypeDescription" = vDelete)

--        and sign(h."ReportTotal") = -1

        and h."ReportTotal" < 0

        and ((h."OrthoStatus" = 0        

              and h."HistoryType" = 5)

             or h."HistoryType" = 2)

        and h."Family" = pMaxHistory2."Family"

        and h."OrigRecNo" = pMaxHistory2."OrigRecNo";



      end loop;   -- pChanges

            

      --

      -- process Ortho treatments

      --

      for pOrthoTrx in cOrthoTrx (pMaxHistory2."OrigRecNo",

                                  pMaxHistory2."Family") loop

      

        --

        -- update to To Ortho Plan

        --

        v_step := 190;



        update /*+ index(h history_ar_global_temp2_idx1) */ history_ar_global_temp2 h

        set   

          h."ReportHistoryTypeDescription" = vToOrthoPlan,

          h."ReportTotal" = decode(h."ReportPeriod", vPrevious, h."ReportTotal", 0),

          h."ReportInsTotal" = decode(h."ReportPeriod", vPrevious, h."ReportInsTotal", 0),

          h."ReportPayed" = decode(h."ReportPeriod", vPrevious, h."ReportPayed", 0),

          h."ReportInsPayed" = decode(h."ReportPeriod", vPrevious, h."ReportInsPayed", 0),

          h."ReportPtAdj" = decode(h."ReportPeriod", vPrevious, h."ReportPtAdj", 0),

          h."ReportInsAdj" = decode(h."ReportPeriod", vPrevious, h."ReportInsAdj", 0),

          h."ReportInsTransfer" = decode(h."ReportPeriod", vPrevious, h."ReportInsTransfer", 0)   

        where 1=1

        and h."History" = pOrthoTrx."ToHistory";

      

        --

        -- update to From Ortho Plan

        --

        v_step := 200;

  

        update /*+ index(h history_ar_global_temp2_idx1) */ history_ar_global_temp2 h

        set 

          h."ReportHistoryTypeDescription" = vFromOrthoPlan,

          h."ReportTotal" = decode(h."ReportPeriod", vCurrent, h."ReportTotal", 0),

          h."ReportInsTotal" = decode(h."ReportPeriod", vCurrent, h."ReportInsTotal", 0),

          h."ReportPayed" = decode(h."ReportPeriod", vCurrent, h."ReportPayed", 0),

          h."ReportInsPayed" = decode(h."ReportPeriod", vCurrent, h."ReportInsPayed", 0),

          h."ReportPtAdj" = decode(h."ReportPeriod", vCurrent, h."ReportPtAdj", 0),

          h."ReportInsAdj" = decode(h."ReportPeriod", vCurrent, h."ReportInsAdj", 0),

          h."ReportInsTransfer" = decode(h."ReportPeriod", vCurrent, h."ReportInsTransfer", 0)             

        where 1=1

        and h."History" = pOrthoTrx."FromHistory";

         

      end loop;   -- pOrthoTrx



    --

    -- increment counter; reset counter to zero (0) if 50K then perform a commit (AX-27637)

    --

    v_step := 203;

    

    vCounter := (vCounter + 1);

    

    if (vCounter = 50000) then

      vCounter := 0;

      commit;      

    end if;

    

  end loop;   -- pMaxHistory2

                         

  --

  -- update report history type description

  --

  v_step := 210;

  

  update history_ar_global_temp2 h

  set

    h."ReportHistoryTypeDescription" = decode(h."HistoryType", 1, vNew,

                                                               2, vModified,

                                                               3, vAllocate,

                                                               4, vDelete,

                                                               5, vModified,

                                                               vUnknown)

  where 1=1

  and h."ReportHistoryTypeDescription" = ' ';



  --

  -- AX-20468 (delete office charges records that says for previous period but actually has equivalent record for the current period)

  --

  v_step := 212;



  delete from history_ar_global_temp2 h2a

  where 1=1

  and h2a."TreatmentDate" < vFromDate

  and h2a."ModifiedDate" < h2a."TreatmentDate"

  and h2a."HistoryType" = 2

  and h2a."Type" = 2

  and h2a."ReportPeriod" = vPrevious

  and h2a."ReportHistoryTypeDescription" = vModified

  and exists (select null

              from history_ar_global_temp2 h2b

              where 1=1

              and h2b."ReportPeriod" = vCurrent

              and h2b."ReportHistoryTypeDescription" = h2a."ReportHistoryTypeDescription"

              and h2b."OrigRecNo" = h2a."OrigRecNo"

              and h2b."Treatment" = h2a."Treatment"

              and h2b."Id" = h2a."Id"

              and h2b."Type" = h2a."Type"

              and h2b."HistoryType" = h2a."HistoryType"

              and h2b."History" = h2a."History")

  and not exists (select null

                  from history_ar_global_temp2 h2c

                  where 1=1

                  and h2c."ReportPeriod" = vCurrent

                  and h2c."ReportHistoryTypeDescription" = h2a."ReportHistoryTypeDescription"

                  and h2c."OrigRecNo" = h2a."OrigRecNo"

                  and h2c."Treatment" = h2a."Treatment"

                  and h2c."Id" = h2a."Id"

                  and h2c."Type" = h2a."Type"

                  and h2c."HistoryType" = h2a."HistoryType"

                  and h2c."History" < h2a."History");



  --

  -- AX-20468 (delete office charges records that says for previous period but actually has equivalent record for the current period)

  --

  v_step := 214;



  delete from history_ar_global_temp2 h2a

  where 1=1

  and h2a."TreatmentDate" between vFromDate and vToDate

  and h2a."ModifiedDate" < vFromDate

  and h2a."ModifiedDate" < h2a."TreatmentDate"

  and h2a."HistoryType" = 2

  and h2a."Type" = 2

  and h2a."ReportPeriod" = vPrevious

  and h2a."ReportHistoryTypeDescription" = vModified

  and exists (select null

              from history_ar_global_temp2 h2b

              where 1=1

              and h2b."ReportPeriod" = vCurrent

              and h2b."ReportHistoryTypeDescription" = h2a."ReportHistoryTypeDescription"

              and h2b."OrigRecNo" = h2a."OrigRecNo"

              and h2b."Treatment" = h2a."Treatment"

              and h2b."Id" = h2a."Id"

              and h2b."Type" = h2a."Type"

              and h2b."HistoryType" = h2a."HistoryType"

              and h2b."History" = h2a."History")

  and not exists (select null

                  from history_ar_global_temp2 h2c

                  where 1=1

                  and h2c."ReportPeriod" = vCurrent

                  and h2c."ReportHistoryTypeDescription" = h2a."ReportHistoryTypeDescription"

                  and h2c."OrigRecNo" = h2a."OrigRecNo"

                  and h2c."Treatment" = h2a."Treatment"

                  and h2c."Id" = h2a."Id"

                  and h2c."Type" = h2a."Type"

                  and h2c."HistoryType" = h2a."HistoryType"

                  and h2c."History" < h2a."History");



  --

  -- AX-20468 (delete deleted office charges records for the current period that is supposed to be $0.00 but is not)

  --

  v_step := 216;

  

  delete from history_ar_global_temp2 h2a

  where 1=1

  and h2a."TreatmentDate" > vToDate

  and h2a."HistoryType" = 4

  and h2a."Type" = 2

  and h2a."ReportPeriod" = vCurrent

  and h2a."ReportHistoryTypeDescription" = vDelete

  and h2a."ReportTotal" < 0

  and exists (select null

              from history_ar_global_temp2 h2b

              where 1=1

              and h2b."ReportTotal" = 0

              and h2b."ReportPeriod" = vCurrent

              and h2b."ReportHistoryTypeDescription" = h2a."ReportHistoryTypeDescription"

              and h2b."OrigRecNo" = h2a."OrigRecNo"

              and h2b."Treatment" = h2a."Treatment"

              and h2b."Id" = h2a."Id"

              and h2b."Type" = h2a."Type"

              and h2b."HistoryType" = h2a."HistoryType"

              and h2b."History" = h2a."History")

  and not exists (select null

                  from history_ar_global_temp2 h2c

                  where 1=1

                  and h2c."ReportPeriod" = vCurrent

                  and h2c."ReportHistoryTypeDescription" = h2a."ReportHistoryTypeDescription"

                  and h2c."OrigRecNo" = h2a."OrigRecNo"

                  and h2c."Treatment" = h2a."Treatment"

                  and h2c."Id" = h2a."Id"

                  and h2c."Type" = h2a."Type"

                  and h2c."HistoryType" = h2a."HistoryType"

                  and h2c."History" < h2a."History");



  --

  -- insert into final report table

  --

  v_step := 220;

  

  insert into history_ar_global_temp3

  select

    "History",

    "HistoryType",

    "OrigRecNo",

    "Type",

    "Id",

    "Treatment",

    "ModifiedDate",

    "TreatmentDate",

    "Producer",

    "Procedure",

    "Patient",

    "Family",

    "Code",

    "Description",

    "Company1",

    "ReportDepartment",

    "ReportDiscipline",

    "ReportProcedure",

    "ReportPractice",

    "ReportClaimDoctor",

    "ReportLocation",

    "ReportEntryUser",

    "ReportAppUser",

    "ReportCustom1",

    "ReportCustom2",

    "ReportProducer",

    "ReportTypeCode",

    "ReportPGroup",

    "ReportYear",

    "ReportCustomCode1",

    "ReportCustomCode2",

    "ReportCustomCode3",

    "ReportCustomCode4",

    "ReportCustomCode5",

    "ReportCustomCode6",

    "ReportCustomCode7",

    "ReportCustomCode8",

    "ReportCustomCode9",

    "ReportCustomCode10",

    "ReportGroupBy1",

    "ReportGroupBy1Description",

    "ReportGroupBy2",

    "ReportGroupBy2Description",

    "ReportFromDate",

    "ReportToDate",

    "ReportIsDetailed",

    "ReportIncludeUnallocated",

    "ReportHistoryTypeDescription",

    sum("ReportOldTotal") "ReportOldTotal",

    sum("ReportTotal") "ReportTotal",

    (sum("ReportTotal") - sum("ReportOldTotal")) "ReportTotalChange",

    sum("ReportOldInsTotal") "ReportOldInsTotal",

    sum("ReportInsTotal") "ReportInsTotal",

    (sum("ReportInsTotal") - sum("ReportOldInsTotal")) "ReportInsTotalChange",

    sum("ReportOldPayed") "ReportOldPayed",

    sum("ReportPayed") "ReportPayed",

    (sum("ReportPayed") - sum("ReportOldPayed")) "ReportPayedChange",

    sum("ReportOldInsPayed") "ReportOldInsPayed",

    sum("ReportInsPayed") "ReportInsPayed",

    (sum("ReportInsPayed") - sum("ReportOldInsPayed")) "ReportInsPayedChange",

    sum("ReportOldPtAdj") "ReportOldPtAdj",

    sum("ReportPtAdj") "ReportPtAdj",

    (sum("ReportPtAdj") - sum("ReportOldPtAdj")) "ReportPtAdjChange",

    sum("ReportOldInsAdj") "ReportOldInsAdj",

    sum("ReportInsAdj") "ReportInsAdj",

    (sum("ReportInsAdj") - sum("ReportOldInsAdj")) "ReportInsAdjChange",

    sum("ReportOldInsTransfer") "ReportOldInsTransfer",

    sum("ReportInsTransfer") "ReportInsTransfer",

    (sum("ReportInsTransfer") - sum("ReportOldInsTransfer")) "ReportInsTransferChange",

    0 "PreviousHistory"                                                         -- AX-28014

  from 

    (select 

       h. "History",

       h."HistoryType",

       h."OrigRecNo",

       h."Type",       

       h."Id",

       h."Treatment",     

       h."ModifiedDate",

       h."TreatmentDate",

       h."Producer",

       h."Procedure",

       h."Patient",

       h."Family",

       h."Code",

       h."Description",  

       h."Company1",

       h."ReportDepartment",

       h."ReportDiscipline",

       h."ReportProcedure",

       h."ReportPractice",

       h."ReportClaimDoctor",

       h."ReportLocation",

       h."ReportEntryUser",

       h."ReportAppUser",

       h."ReportCustom1",

       h."ReportCustom2",

       h."ReportProducer",

       h."ReportTypeCode",

       h."ReportPGroup",

       h."ReportYear",

       h."ReportCustomCode1",

       h."ReportCustomCode2",

       h."ReportCustomCode3",

       h."ReportCustomCode4",

       h."ReportCustomCode5",

       h."ReportCustomCode6",

       h."ReportCustomCode7",

       h."ReportCustomCode8",

       h."ReportCustomCode9",

       h."ReportCustomCode10",

       h."ReportGroupBy1",

       h."ReportGroupBy1Description",

       h."ReportGroupBy2",  

       h."ReportGroupBy2Description",

       h."ReportFromDate",

       h."ReportToDate",

       h."ReportIsDetailed",

       h."ReportIncludeUnallocated",

       h."ReportHistoryTypeDescription",

       decode(h."ReportPeriod", vPrevious, h."ReportTotal", 0) "ReportOldTotal",

       decode(h."ReportPeriod", vCurrent, h."ReportTotal", 0) "ReportTotal",

       decode(h."ReportPeriod", vPrevious, h."ReportInsTotal", 0) "ReportOldInsTotal",

       decode(h."ReportPeriod", vCurrent, h."ReportInsTotal", 0) "ReportInsTotal",

       decode(h."ReportPeriod", vPrevious, h."ReportPayed", 0) "ReportOldPayed",

       decode(h."ReportPeriod", vCurrent, h."ReportPayed", 0) "ReportPayed",

       decode(h."ReportPeriod", vPrevious, h."ReportInsPayed", 0) "ReportOldInsPayed",

       decode(h."ReportPeriod", vCurrent, h."ReportInsPayed", 0) "ReportInsPayed",

       decode(h."ReportPeriod", vPrevious, h."ReportPtAdj", 0) "ReportOldPtAdj",

       decode(h."ReportPeriod", vCurrent, h."ReportPtAdj", 0) "ReportPtAdj",

       decode(h."ReportPeriod", vPrevious, h."ReportInsAdj", 0) "ReportOldInsAdj",

       decode(h."ReportPeriod", vCurrent, h."ReportInsAdj", 0) "ReportInsAdj",

       decode(h."ReportPeriod", vPrevious, h."ReportInsTransfer", 0) "ReportOldInsTransfer",

       decode(h."ReportPeriod", vCurrent, h."ReportInsTransfer", 0) "ReportInsTransfer"

     from history_ar_global_temp2 h

     where 1=1

    )

  where 1=1

  group by

    "History",

    "HistoryType",

    "OrigRecNo",

    "Type",

    "Id",

    "Treatment",

    "ModifiedDate",

    "TreatmentDate",

    "Producer",

    "Procedure",

    "Patient",

    "Family",

    "Code",

    "Description",

    "Company1",

    "ReportDepartment",

    "ReportDiscipline",

    "ReportProcedure",

    "ReportPractice",

    "ReportClaimDoctor",

    "ReportLocation",

    "ReportEntryUser",

    "ReportAppUser",

    "ReportCustom1",

    "ReportCustom2",

    "ReportProducer",

    "ReportTypeCode",

    "ReportPGroup",

    "ReportYear",

    "ReportCustomCode1",

    "ReportCustomCode2",

    "ReportCustomCode3",

    "ReportCustomCode4",

    "ReportCustomCode5",

    "ReportCustomCode6",

    "ReportCustomCode7",

    "ReportCustomCode8",

    "ReportCustomCode9",

    "ReportCustomCode10",

    "ReportGroupBy1",

    "ReportGroupBy1Description",

    "ReportGroupBy2",

    "ReportGroupBy2Description",

    "ReportFromDate",

    "ReportToDate",

    "ReportIsDetailed",

    "ReportIncludeUnallocated",

    "ReportHistoryTypeDescription";    

                         

  --

  -- save changes then empty global temporary tables HISTORY_AR_GLOBAL_TEMP, HISTORY_AR_GLOBAL_TEMP2, HISTORY_AR_GLOBAL_TEMP4

  --

  v_step := 230;

  

  commit;



  -- AX-27637  

  execute immediate 'truncate table history_ar_global_temp';

  execute immediate 'truncate table history_ar_global_temp2';

  execute immediate 'truncate table history_ar_global_temp4';



  --

  -- remove unnecessary records

  --

  v_step := 240;

  

  delete from history_ar_global_temp3

  where 1=1

  and "ReportTotalChange" = 0

  and "ReportInsTotalChange" = 0

  and "ReportPayedChange" = 0

  and "ReportInsPayedChange" = 0

  and "ReportPtAdjChange" = 0

  and "ReportInsAdjChange" = 0

  and "ReportInsTransferChange" = 0

  and "ReportHistoryTypeDescription" not in (vNew, vTransferIn, vTransferOut, vDelete);

                          

  --

  -- remove records where changes does not involve dollar amount

  -- only when there is no group by

  --

  v_step := 250;

  

  if (vGroupChanged = 0) then

  

    delete from history_ar_global_temp3 h

    where 1=1

    and h."OrigRecNo" in (select h2."OrigRecNo"

                          from history_ar_global_temp3 h2

                          where 1=1

                          group by h2."OrigRecNo"

                          having 1=1

                          and sum(h2."ReportTotalChange") = 0

                          and sum(h2."ReportInsTotalChange") = 0

                          and sum(h2."ReportPayedChange") = 0

                          and sum(h2."ReportInsPayedChange") = 0

                          and sum(h2."ReportPtAdjChange") = 0

                          and sum(h2."ReportInsAdjChange") = 0

                          and sum(h2."ReportInsTransferChange") = 0)

    and not exists (select null

                    from history_ar_global_temp3 h3

                    where 1=1

                    and h3."OrigRecNo" = h."OrigRecNo"

                    and (h3."ReportHistoryTypeDescription" = vNew

                         or h3."ReportHistoryTypeDescription" = vTransferIn

                         or h3."ReportHistoryTypeDescription" = vTransferOut

                         or h3."ReportHistoryTypeDescription" = vToOrthoPlan

                         or h3."ReportHistoryTypeDescription" = vFromOrthoPlan

                         or h3."ReportHistoryTypeDescription" = vDelete));



  end if;

                               

  --

  -- summarize output

  --

  for pSumTotals in cSumTotals loop

    --

    -- delete detail records

    --

    v_step := 260;

  

    delete from history_ar_global_temp3 h

    where 1=1

    and h."History" = pSumTotals."History"

    and h."HistoryType" = pSumTotals."HistoryType"

    and h."OrigRecNo" = pSumTotals."OrigRecNo"

    and h."Type" = pSumTotals."Type"

    and h."Id" = pSumTotals."Id"

    and h."Treatment" = pSumTotals."Treatment"

    and h."ModifiedDate" = pSumTotals."ModifiedDate"

    and h."TreatmentDate" = pSumTotals."TreatmentDate"

    and h."Producer" = pSumTotals."Producer"

    and h."Procedure" = pSumTotals."Procedure"

    and h."Patient" = pSumTotals."Patient"

    and h."Family" = pSumTotals."Family"

    and h."Code" = pSumTotals."Code"

    and h."Description" = pSumTotals."Description"

    and h."Company1" = pSumTotals."Company1"

    and h."ReportDepartment" = pSumTotals."ReportDepartment"

    and h."ReportDiscipline" = pSumTotals."ReportDiscipline"

    and h."ReportProcedure" = pSumTotals."ReportProcedure"

    and h."ReportPractice" = pSumTotals."ReportPractice"

    and h."ReportClaimDoctor" = pSumTotals."ReportClaimDoctor"

    and h."ReportLocation" = pSumTotals."ReportLocation"

    and h."ReportEntryUser" = pSumTotals."ReportEntryUser"

    and h."ReportAppUser" = pSumTotals."ReportAppUser"

    and h."ReportCustom1" = pSumTotals."ReportCustom1"

    and h."ReportCustom2" = pSumTotals."ReportCustom2"

    and h."ReportProducer" = pSumTotals."ReportProducer"

    and h."ReportTypeCode" = pSumTotals."ReportTypeCode"

    and h."ReportPGroup" = pSumTotals."ReportPGroup"

    and h."ReportYear" = pSumTotals."ReportYear"

    and h."ReportCustomCode1" = pSumTotals."ReportCustomCode1"

    and h."ReportCustomCode2" = pSumTotals."ReportCustomCode2"

    and h."ReportCustomCode3" = pSumTotals."ReportCustomCode3"

    and h."ReportCustomCode4" = pSumTotals."ReportCustomCode4"

    and h."ReportCustomCode5" = pSumTotals."ReportCustomCode5"

    and h."ReportCustomCode6" = pSumTotals."ReportCustomCode6"

    and h."ReportCustomCode7" = pSumTotals."ReportCustomCode7"

    and h."ReportCustomCode8" = pSumTotals."ReportCustomCode8"

    and h."ReportCustomCode9" = pSumTotals."ReportCustomCode9"

    and h."ReportCustomCode10" = pSumTotals."ReportCustomCode10"

    and h."ReportGroupBy1" = pSumTotals."ReportGroupBy1"

    and h."ReportGroupBy1Description" = pSumTotals."ReportGroupBy1Description"

    and h."ReportGroupBy2" = pSumTotals."ReportGroupBy2"

    and h."ReportGroupBy2Description" = pSumTotals."ReportGroupBy2Description"

    and h."ReportFromDate" = pSumTotals."ReportFromDate"

    and h."ReportToDate" = pSumTotals."ReportToDate"

    and h."ReportIsDetailed" = pSumTotals."ReportIsDetailed"

    and h."ReportIncludeUnallocated" = pSumTotals."ReportIncludeUnallocated"

    and h."ReportHistoryTypeDescription" = pSumTotals."ReportHistoryTypeDescription";

    

    --

    -- insert back summary records

    --

    v_step := 270;

    

    insert into history_ar_global_temp3

    values (

            pSumTotals."History",

            pSumTotals."HistoryType",

            pSumTotals."OrigRecNo",

            pSumTotals."Type",

            pSumTotals."Id",

            pSumTotals."Treatment",

            pSumTotals."ModifiedDate",

            pSumTotals."TreatmentDate",

            pSumTotals."Producer",

            pSumTotals."Procedure",

            pSumTotals."Patient",

            pSumTotals."Family",

            pSumTotals."Code",

            pSumTotals."Description",

            pSumTotals."Company1",

            pSumTotals."ReportDepartment",

            pSumTotals."ReportDiscipline",

            pSumTotals."ReportProcedure",

            pSumTotals."ReportPractice",

            pSumTotals."ReportClaimDoctor",

            pSumTotals."ReportLocation",

            pSumTotals."ReportEntryUser",

            pSumTotals."ReportAppUser",

            pSumTotals."ReportCustom1",

            pSumTotals."ReportCustom2",

            pSumTotals."ReportProducer",

            pSumTotals."ReportTypeCode",

            pSumTotals."ReportPGroup",

            pSumTotals."ReportYear",

            pSumTotals."ReportCustomCode1",

            pSumTotals."ReportCustomCode2",

            pSumTotals."ReportCustomCode3",

            pSumTotals."ReportCustomCode4",

            pSumTotals."ReportCustomCode5",

            pSumTotals."ReportCustomCode6",

            pSumTotals."ReportCustomCode7",

            pSumTotals."ReportCustomCode8",

            pSumTotals."ReportCustomCode9",

            pSumTotals."ReportCustomCode10",

            pSumTotals."ReportGroupBy1",

            pSumTotals."ReportGroupBy1Description",

            pSumTotals."ReportGroupBy2",

            pSumTotals."ReportGroupBy2Description",

            pSumTotals."ReportFromDate",

            pSumTotals."ReportToDate",

            pSumTotals."ReportIsDetailed",

            pSumTotals."ReportIncludeUnallocated",

            pSumTotals."ReportHistoryTypeDescription",

            pSumTotals."ReportOldTotal",

            pSumTotals."ReportTotal",

            pSumTotals."ReportTotalChange",

            pSumTotals."ReportOldInsTotal",

            pSumTotals."ReportInsTotal",

            pSumTotals."ReportInsTotalChange",

            pSumTotals."ReportOldPayed",

            pSumTotals."ReportPayed",

            pSumTotals."ReportPayedChange",

            pSumTotals."ReportOldInsPayed",

            pSumTotals."ReportInsPayed",

            pSumTotals."ReportInsPayedChange",

            pSumTotals."ReportOldPtAdj",

            pSumTotals."ReportPtAdj",

            pSumTotals."ReportPtAdjChange",

            pSumTotals."ReportOldInsAdj",

            pSumTotals."ReportInsAdj",

            pSumTotals."ReportInsAdjChange",

            pSumTotals."ReportOldInsTransfer",

            pSumTotals."ReportInsTransfer",

            pSumTotals."ReportInsTransferChange",

            0                                                                   -- "PreviousHistory" (AX-28014)

           );

           

  end loop;   -- pSumTotals



  --

  -- compute buckets

  --

  for pComputeBuckets in cComputeBuckets loop

  

    if (pComputeBuckets."History2" is not null) then

      --

      -- AX-20468 (make it easy to troubleshoot issue with AX-659)

      -- set variables to current record values

      --

      v_step := 272;

      

      vHistory := pComputeBuckets."History";

      vHistory2 := pComputeBuckets."History2";



      --

      -- update old totals

      --

      v_step := 280;

      

      update history_ar_global_temp3 h

      set

        (h."ReportOldPayed",

         h."ReportOldInsPayed",

         h."ReportOldPtAdj",

         h."ReportOldInsAdj",

         h."ReportOldInsTransfer") = (select 

                                        (h."ReportOldPayed" + h2."ReportPayed"),

                                        (h."ReportOldInsPayed" + h2."ReportInsPayed"),

                                        (h."ReportOldPtAdj" + h2."ReportPtAdj"),

                                        (h."ReportOldInsAdj" + h2."ReportInsAdj"),

                                        (h."ReportOldInsTransfer" + h2."ReportInsTransfer")

                                      from history_ar_global_temp3 h2

                                      where 1=1

                                      and h2."HistoryType" = h."HistoryType"

                                      and h2."History" = pComputeBuckets."History2")

      where 1=1

      and ctid = pComputeBuckets.ctid;

      

      --

      -- update new totals

      --

      v_step := 290;

      

      update history_ar_global_temp3 h

      set

        h."ReportPayed" = (h."ReportPayed" + h."ReportOldPayed"),

        h."ReportInsPayed" = (h."ReportInsPayed" + h."ReportOldInsPayed"),

        h."ReportPtAdj" = (h."ReportPtAdj" + h."ReportOldPtAdj"),

        h."ReportInsAdj" = (h."ReportInsAdj" + h."ReportOldInsAdj"),

        h."ReportInsTransfer" = (h."ReportInsTransfer" + h."ReportOldInsTransfer")

      where 1=1

      and ctid = pComputeBuckets.ctid;

      

    end if;

    

  end loop;   -- pComputeBuckets

  

  --

  -- delete records that are not for the department

  --

  v_step := 300;

  

  delete from history_ar_global_temp3

  where 1=1

  and "ReportDepartment" <> pDepartment;

  

  --

  -- delete records that are outside of the reporting period

  --

  v_step := 305;

  

  delete from history_ar_global_temp3

  where 1=1

  and ("ModifiedDate" < "ReportFromDate"

       or "ModifiedDate" > "ReportToDate")

  --

  -- AX-20468 (do not delete post-dated office charges)

  --

  and ("TreatmentDate" < "ReportFromDate"

       or "TreatmentDate" < "ReportFromDate");

   

  --

  -- process unallocated transactions

  --

  v_step := 310;

  

  if (pIncludeUnallocated = 1) then

    

    ar_create_unallocated_txs_p (vFromDate,

                                 vToDate,

                                 pGroupBy1,

                                 vReportGroupBy1Description,

                                 pGroupBy2,

                                 vReportGroupBy2Description,

                                 pIsDetailed,

                                 pIncludeUnallocated,

                                 pPatient,

                                 pOrigRecNo);

                                       

  end if;

  

  --

  -- E139522: switch old and new total values for Deleted transactions

  --

  v_step := 315;

  

  update history_ar_global_temp3

  set

    "ReportOldTotal" = (-1 * "ReportTotal"),

    "ReportTotal" = (-1 * "ReportOldTotal"),

    "ReportOldInsTotal" = (-1 * "ReportInsTotal"),

    "ReportInsTotal" = (-1 * "ReportOldInsTotal"),

    "ReportOldPayed" = (-1 * "ReportPayed"),

    "ReportPayed" = (-1 * "ReportOldPayed"),

    "ReportOldInsPayed" = (-1 * "ReportInsPayed"),

    "ReportInsPayed" = (-1 * "ReportOldInsPayed"),

    "ReportOldPtAdj" = (-1 * "ReportPtAdj"),

    "ReportPtAdj" = (-1 * "ReportOldPtAdj"),

    "ReportOldInsAdj" = (-1 * "ReportInsAdj"),

    "ReportInsAdj" = (-1 * "ReportOldInsAdj"),

    "ReportOldInsTransfer" = (-1 * "ReportInsTransfer"),

    "ReportInsTransfer" = (-1 * "ReportOldInsTransfer")

  where 1=1

  and "ReportHistoryTypeDescription" = vDelete

  and "HistoryType" = 4;  



  --

  -- update "PreviousHistory" column with actual previous History ID (AX-28014)

  --

  v_step := 317;

  

  update history_ar_global_temp3 h3

  set h3."PreviousHistory" = (select nvl(max(h."History"), 0)

                              from history h

                              where 1=1

                              and h."History" < h3."History"

                              and h."OrigRecNo" = h3."OrigRecNo")

  where 1=1;

  

  --

  -- save changes then empty global temporary tables HISTORY_AR_GLOBAL_TEMP, HISTORY_AR_GLOBAL_TEMP2, HISTORY_AR_GLOBAL_TEMP4

  --

  v_step := 320;

  

  commit;



  -- AX-27637  

  execute immediate 'truncate table history_ar_global_temp';

  execute immediate 'truncate table history_ar_global_temp2';

  execute immediate 'truncate table history_ar_global_temp4';



  --

  -- insert report data into AR_RECON_SAVED_DATA_DTL (SF-00278253)

  --

  v_step := 325;



  insert into ar_recon_saved_data_dtl

  select

    vBatch,

    h3.*

  from history_ar_global_temp3 h3

  where 1=1;

  

  --

  -- return total change

  --

  v_step := 330;

  

  select sum(nvl("ReportTotalChange", 0) - nvl("ReportPayedChange", 0) + nvl("ReportPtAdjChange", 0) - nvl("ReportInsPayedChange", 0) - nvl("ReportInsAdjChange", 0))

  into vOut

  from history_ar_global_temp3

  where 1=1

  and "ReportDepartment" = pDepartment;



  --

  -- update AR_RECON_SAVED_DATA_HDR with correct balances information (SF-00278253)

  --

  v_step := 331;



  select

    ar_dept_pkg.ar_get_dept_asat_f(pDepartment,

                                   (vFromDate - 1),

                                   pPatient,

                                   pOrigRecNo,

                                   pRecalculate)

  into vBeginningBalance

  from dual;

                                                            

  select ar_dept_pkg.ar_get_dept_asat_f(pDepartment,

                                        vTodate,

                                        pPatient,

                                        pOrigRecNo,

                                        pRecalculate)

  into vEndingBalance

  from dual;



  update ar_recon_saved_data_hdr adh

  set

    adh."BeginningBalance" = vBeginningBalance, /*ar_dept_pkg.ar_get_dept_asat_f(pDepartment,

                                                            (vFromDate - 1),

                                                            pPatient,

                                                            pOrigRecNo,

                                                            pRecalculate),*/

    adh."PeriodBalance" = nvl(vOut, 0),

    adh."EndingBalance" = vEndingBalance, /*ar_dept_pkg.ar_get_dept_asat_f(pDepartment,

                                                         vToDate,

                                                         pPatient,

                                                         pOrigRecNo,

                                                         pRecalculate)*/

    adh."EndDateTime" = nvl(adh."EndDateTime", sysdate)                         -- AX-26473.2

  where 1=1

  and adh."ReportType" = 0                                                      -- AX-26491

  and adh."Batch" = vBatch;



else

  --

  -- return total change

  --

  v_step := 330;

  

  select sum(nvl("ReportTotalChange", 0) - nvl("ReportPayedChange", 0) + nvl("ReportPtAdjChange", 0) - nvl("ReportInsPayedChange", 0) - nvl("ReportInsAdjChange", 0))

  into vOut

  from history_ar_global_temp3

  where 1=1

  and "ReportDepartment" = pDepartment;



end if;     -- SF-00278253



  --

  -- save changes

  --

  v_step := 320;

    

  commit;



--  return nvl(vOut, 0);

  return nvl(vReturnBatch, 0);

  

exception

  when ora_01427 then

    --

    -- AX-20468 (make it easy to troubleshoot issue with AX-659)

    -- keep only records that causes the process to error out; delete the other records

    --

    v_step := 332;

    

    delete from history_ar_global_temp3

    where 1=1

    and "History" not in (vHistory, vHistory2);

    

    --

    -- save changes then empty global temporary tables HISTORY_AR_GLOBAL_TEMP, HISTORY_AR_GLOBAL_TEMP2, HISTORY_AR_GLOBAL_TEMP4

    --

    v_step := 334;

  

    commit;



    -- AX-27637  

    execute immediate 'truncate table history_ar_global_temp';

    execute immediate 'truncate table history_ar_global_temp2';

    execute immediate 'truncate table history_ar_global_temp4'; 



    --

    -- return total change

    --

    v_step := 336;

  

    select sum(nvl("ReportTotalChange", 0) - nvl("ReportPayedChange", 0) + nvl("ReportPtAdjChange", 0) - nvl("ReportInsPayedChange", 0) - nvl("ReportInsAdjChange", 0))

    into vOut

    from history_ar_global_temp3

    where 1=1;

  

--    return nvl(vOut, 0);

    return nvl(vReturnBatch, 0);



/*

  when others then

    rollback;

--    return 0;

    return nvl(vReturnBatch, 0);

*/



  when others then

    --

    -- rollback then log error to AX_LOG table then return batch number

    -- 

--    v_step := 340;

  

    rollback;  

    ax_pkg.LogEvent_P(trim('AR_DEPT_PKG')||'.ar_create_dept_txs_f', trim(sqlerrm)||' (Error at step '||v_step||')'); -- AX-39259

    return nvl(vReturnBatch, 0);

    

end ar_create_dept_txs_f;



--

-- create procedure to populate the temporary tables with report data

--

PROCEDURE ar_create_dept_txs_p(OUT pbatchid numeric, OUT pisnewbatchid numeric, IN pdepartment character, IN pfromdate timestamp without time zone, IN ptodate timestamp without time zone, IN pgroupby1 numeric, IN pgroupby2 numeric, IN pisdetailed numeric, IN pincludeunallocated numeric, IN ppatient numeric DEFAULT 0, IN porigrecno numeric DEFAULT 0, IN precalculate integer DEFAULT 0, IN pexpirydate timestamp without time zone DEFAULT trunc(sysdate), IN pupdateexpirydateifnotnewdata integer DEFAULT 0) IS



  pragma autonomous_transaction;



  cursor cMaxHistory2 is

    select 

      h2."ReportPeriod",

      h2."OrigRecNo",

      h2."Family",

      max(h2."History") "History"

    from history_ar_global_temp h2

    where 1=1

    and h2."Type" < 5

    group by

      h2."ReportPeriod",

      h2."OrigRecNo",

      h2."Family"

    order by 2, 4;



  cursor cMaxHistory (pReportPeriod history_ar_global_temp."ReportPeriod"%type,

                      pOrigRecNo history_ar_global_temp."OrigRecNo"%type,

                      pFamily history_ar_global_temp."Family"%type,

                      pHistory history_ar_global_temp."History"%type) is

    select /*+ index(h history_ar_global_temp_idx2) */

      h."HistoryType",

      h."OrthoStatus"

    from history_ar_global_temp h

    where 1=1

    and h."Type" < 5

    and h."ReportPeriod" = pReportPeriod

    and h."OrigRecNo" = pOrigRecNo

    and h."Family" = pFamily

    and h."History" = pHistory;



  cursor cChanges (pOrigRecNo history_ar_global_temp."OrigRecNo"%type,

                   pFamily history_ar_global_temp."Family"%type) is

    select /*+ index(h history_ar_global_temp_idx2) */

      count(distinct h."Department") "DepartmentCount",

      count(distinct h."Producer") "ProducerCount",

      count(distinct h."Producer_PGroup") "PGroupCount",

      count(distinct h."Producer_TypeCode") "TypeCodeCount",

      count(distinct h."Producer_Year") "YearCount",

      count(distinct h."AppUser") "AppUserCount",

      count(distinct h."Custom1") "Custom1Count",

      count(distinct h."Custom2") "Custom2Count",      

      count(distinct h."Discipline") "DisciplineCount",

      count(distinct h."EntryUser") "EntryUserCount",

      count(distinct h."Location") "LocationCount",

      count(distinct h."ClaimDoctor") "ClaimDoctorCount",

      count(distinct h."Practice") "PracticeCount",

      count(distinct h."Procedure") "ProcedureCount",

      count(distinct h."Patient_CustomCode1") "CustomCode1Count",

      count(distinct h."Patient_CustomCode2") "CustomCode2Count",

      count(distinct h."Patient_CustomCode3") "CustomCode3Count",

      count(distinct h."Patient_CustomCode4") "CustomCode4Count",

      count(distinct h."Patient_CustomCode5") "CustomCode5Count",

      count(distinct h."Patient_CustomCode6") "CustomCode6Count",

      count(distinct h."Patient_CustomCode7") "CustomCode7Count",

      count(distinct h."Patient_CustomCode8") "CustomCode8Count",

      count(distinct h."Patient_CustomCode9") "CustomCode9Count",

      count(distinct h."Patient_CustomCode10") "CustomCode10Count",

      count(distinct h."OrthoStatus") "OrthoStatusCount"

    from history_ar_global_temp h

    where 1=1

    and h."Type" < 5

    and h."Family" = pFamily

    and h."OrigRecNo" = pOrigRecNo;

      

  cursor cSumTotals is

    select

      "History",

      "HistoryType",

      "OrigRecNo",

      "Type",

      "Id",

      "Treatment",

      "ModifiedDate",

      "TreatmentDate",

      "Producer",

      "Procedure",

      "Patient",

      "Family",

      "Code",

      "Description",     

      "Company1",

      "ReportDepartment",

      "ReportDiscipline",

      "ReportProcedure",

      "ReportPractice",

      "ReportClaimDoctor",

      "ReportLocation",

      "ReportEntryUser",

      "ReportAppUser",

      "ReportCustom1",

      "ReportCustom2",

      "ReportProducer",

      "ReportTypeCode",

      "ReportPGroup",

      "ReportYear",

      "ReportCustomCode1",

      "ReportCustomCode2",

      "ReportCustomCode3",

      "ReportCustomCode4",

      "ReportCustomCode5",

      "ReportCustomCode6",

      "ReportCustomCode7",

      "ReportCustomCode8",

      "ReportCustomCode9",

      "ReportCustomCode10",  

      "ReportGroupBy1",

      "ReportGroupBy1Description",

      "ReportGroupBy2",

      "ReportGroupBy2Description",

      "ReportFromDate",

      "ReportToDate",

      "ReportIsDetailed",

      "ReportIncludeUnallocated",

      "ReportHistoryTypeDescription",

      sum("ReportOldTotal") "ReportOldTotal",

      sum("ReportTotal") "ReportTotal",

      sum("ReportTotalChange") "ReportTotalChange",

      sum("ReportOldInsTotal") "ReportOldInsTotal",

      sum("ReportInsTotal") "ReportInsTotal",

      sum("ReportInsTotalChange") "ReportInsTotalChange",

      sum("ReportOldPayed") "ReportOldPayed",

      sum("ReportPayed") "ReportPayed",

      sum("ReportPayedChange") "ReportPayedChange",

      sum("ReportOldInsPayed") "ReportOldInsPayed",

      sum("ReportInsPayed") "ReportInsPayed",

      sum("ReportInsPayedChange") "ReportInsPayedChange",

      sum("ReportOldPtAdj") "ReportOldPtAdj",

      sum("ReportPtAdj") "ReportPtAdj",

      sum("ReportPtAdjChange") "ReportPtAdjChange",

      sum("ReportOldInsAdj") "ReportOldInsAdj",

      sum("ReportInsAdj") "ReportInsAdj",

      sum("ReportInsAdjChange") "ReportInsAdjChange",

      sum("ReportOldInsTransfer") "ReportOldInsTransfer",

      sum("ReportInsTransfer") "ReportInsTransfer",

      sum("ReportInsTransferChange") "ReportInsTransferChange"

    from history_ar_global_temp3

    where 1=1

    group by

      "History",

      "HistoryType",

      "OrigRecNo",

      "Type",

      "Id",

      "Treatment",

      "ModifiedDate",

      "TreatmentDate",

      "Producer",

      "Procedure",

      "Patient",

      "Family",

      "Code",

      "Description",

      "Company1",

      "ReportDepartment",

      "ReportDiscipline",

      "ReportProcedure",

      "ReportPractice",

      "ReportClaimDoctor",

      "ReportLocation",

      "ReportEntryUser",

      "ReportAppUser",

      "ReportCustom1",

      "ReportCustom2",

      "ReportProducer",

      "ReportTypeCode",

      "ReportPGroup",

      "ReportYear",

      "ReportCustomCode1",

      "ReportCustomCode2",

      "ReportCustomCode3",

      "ReportCustomCode4",

      "ReportCustomCode5",

      "ReportCustomCode6",

      "ReportCustomCode7",

      "ReportCustomCode8",

      "ReportCustomCode9",

      "ReportCustomCode10",  

      "ReportGroupBy1",

      "ReportGroupBy1Description",

      "ReportGroupBy2",

      "ReportGroupBy2Description",

      "ReportFromDate",

      "ReportToDate",

      "ReportIsDetailed",

      "ReportIncludeUnallocated",

      "ReportHistoryTypeDescription"

    having count(*) > 1;

    

  cursor cComputeBuckets is    

    select

      ctid,

      "History",

      "History2"

    from (select 

            h3.ctid,

            h3."History",

            (select /*+ index(h2 history_ar_global_temp3_idx2) */

               max(h2."History")

             from history_ar_global_temp3 h2

             where 1=1

             and h2."History" < h3."History"

             and h2."HistoryType" = h3."HistoryType"

             and h2."OrigRecNo" = h3."OrigRecNo"

             and h2."Type" = h3."Type") "History2"

          from (select /*+ full (h) */

                  h.ctid,

                  h."History",

                  h."HistoryType",

                  h."OrigRecNo",

                  h."Type"

                from history_ar_global_temp3 h

                where 1=1

                and h."HistoryType" = 3) h3

          where 1=1)

    where 1=1

    and "History2" is not null

    order by

      "History",

      "History2";

      

  cursor cOrthoTrx (pOrigRecNo history_ar_global_temp2."OrigRecNo"%type,

                    pFamily history_ar_global_temp2."Family"%type) is

    select

      min("ToHistory") "ToHistory",

      "FromHistory"

    from (select 

            h."History" "ToHistory",

            (select /*+ index(h2 history_ar_global_temp2_idx2) */ min(h2."History")

             from history_ar_global_temp2 h2

             where 1=1

             and h2."OrthoStatus" = 0

             and h2."OrigRecNo" = pOrigRecNo

             and h2."Family" = pFamily

             and h2."History" > h."History") "FromHistory"

          from (select /*+ index(h3 history_ar_global_temp2_idx2) */ distinct h3."History"

                from history_ar_global_temp2 h3

                where 1=1

                and h3."OrthoStatus" = 1

                and h3."Family" = pFamily

                and h3."OrigRecNo" = pOrigRecNo) h

          where 1=1)    

    where 1=1

    group by "FromHistory"        

    order by 1, 2;



  vFromDate date := trunc(pFromDate);

  vToDate date := (trunc(pToDate) + (23.9998/24));



  vChangeColumn1  VARCHAR2(30);

  vGroupColumn1  VARCHAR2(30);

  vChangeColumn2  VARCHAR2(30);

  vGroupColumn2  VARCHAR2(30);  

  vReportGroupBy1Description history_ar_global_temp."ReportGroupBy1Description"%type;

  vReportGroupBy2Description history_ar_global_temp."ReportGroupBy2Description"%type;

  

  vGroupChanged number(1) := 0;

  vDeptCount number(1) := 0;

  

  -- constants

  vCurrent history_ar_global_temp2."ReportPeriod"%type := 'CURRENT    ';

  vPrevious history_ar_global_temp2."ReportPeriod"%type := 'PREVIOUS   ';

  vNew history_ar_global_temp2."ReportHistoryTypeDescription"%type := 'New';

  vModified history_ar_global_temp3."ReportHistoryTypeDescription"%type := 'Modified';

  vAllocate history_ar_global_temp3."ReportHistoryTypeDescription"%type := 'Allocate';

  vDelete history_ar_global_temp3."ReportHistoryTypeDescription"%type := 'Delete';

  vTransferIn history_ar_global_temp3."ReportHistoryTypeDescription"%type := 'Transfer In';

  vTransferOut history_ar_global_temp3."ReportHistoryTypeDescription"%type := 'Transfer Out';

  vToOrthoPlan history_ar_global_temp3."ReportHistoryTypeDescription"%type := 'To Ortho Plan';

  vFromOrthoPlan history_ar_global_temp3."ReportHistoryTypeDescription"%type := 'From Ortho Plan';  

  vUnknown history_ar_global_temp3."ReportHistoryTypeDescription"%type := 'Unknown';

  

  vMinHistory history_ar_global_temp2."History"%type;

  vMaxHistory history_ar_global_temp."History"%type;

  vTemp number := 0;

  vOut number := 0;

  

  v_step number(3) := 0;



  --

  -- AX-20468 (make it easy to troubleshoot issue with AX-659)

  --

  vHistory history_ar_global_temp3."History"%type := 0;

  vHistory2 history_ar_global_temp3."History"%type := 0;

  ora_01427 exception;

  pragma exception_init(ora_01427, -1427);



  -- SF-00278253

  vSysdate date := sysdate;

  vBatch ar_recon_saved_data_hdr."Batch"%type := 0;

  vIsDetailed integer := 0;

  vBeginningBalance ar_recon_saved_data_hdr."BeginningBalance"%type := 0;

  vEndingBalance ar_recon_saved_data_hdr."EndingBalance"%type := 0;

  vExpiryDate date := nvl(trunc(pExpiryDate), trunc(sysdate));

  vReturnBatch ar_recon_saved_data_hdr."Batch"%type := 0;

  vIsNewBatchID integer := 0;



  --

  -- AX-27637

  --

  vCounter integer := 0;

  vCalculateDepartment integer := 0;

  vSQLStmt  VARCHAR2(32767) :=

'update /*+ full(h) parallel(h, 4) */ history_ar_global_temp h


where 1=1

';

  

begin

  --

  -- reduce REDO/rollback segments used by GTTs (introduced in Oracle Database 12C Release 1 (12.1))

  --

  v_step := 5;

  

  begin

    execute immediate 'ALTER SESSION SET TEMP_UNDO_ENABLED = TRUE';

  exception

    when others then

      null;

  end;



  --

  -- truncate temporary tables; shouldn't be necessary when global temporary table is created

  --

  v_step := 10;

                                        

  execute immediate 'truncate table history_ar_global_temp';

  execute immediate 'truncate table history_ar_global_temp2';

  execute immediate 'truncate table history_ar_global_temp3';

  execute immediate 'truncate table history_ar_global_temp4';



  --

  -- force parallel execution if possible to improve performance (SF-00278253)

  --

  v_step := 15;

  

--  execute immediate 'ALTER SESSION FORCE PARALLEL DML PARALLEL 4';            -- AX-26491 (commented-out)

--  execute immediate 'ALTER SESSION FORCE PARALLEL QUERY PARALLEL 4';          -- AX-27416 (commented out) 

  

  --

  -- delete expired records from table AR_RECON_SAVED_DATA_HDR

  -- AX-26491.js commented this step out; leave the header records around for reporting purposes

  --

  v_step := 17;

  

  --delete from ar_recon_saved_data_hdr

  --where 1=1

  --and "ReportType" = 0                                                          -- AX-26491

  --and "ExpiryDate" < trunc(vSysdate);

  

  --

  -- delete expired records from table AR_RECON_SAVED_DATA_DTL

  -- AX-26491.js altered the query as header will still be around from above

  --

  v_step := 18;

  delete from ar_recon_saved_data_dtl d

  where 1=1

  and exists (select null

              from ar_recon_saved_data_hdr h

              where 1=1

              and h."Batch" = d."Batch"

              and h."ExpiryDate" < trunc(vSysdate));



  --

  -- delete records from table AR_RECON_SAVED_DATA_HDR where there are no equivalent records from AR_RECON_SAVED_DATA_DTL

  -- AX-26491.js commented this out; want to leave the header records around

  --

  v_step := 19;

  

  --delete from ar_recon_saved_data_hdr h

  --where 1=1

  --and h."ReportType" = 0                                                        -- AX-26491

  --and not exists (select null

  --                from ar_recon_saved_data_dtl d

  --                where 1=1

  --                and d."Batch" = h."Batch");



  --

  -- get group by column names

  --

  v_step := 20;

  

  select 

    ar_dept_pkg.ar_get_group_by_column_name_f (pGroupBy1, 1),

    ar_dept_pkg.ar_get_group_by_column_name_f (pGroupBy1, 0),

    ar_dept_pkg.ar_get_group_by_column_name_f (pGroupBy2, 1),

    ar_dept_pkg.ar_get_group_by_column_name_f (pGroupBy2, 0),

    ar_dept_pkg.ar_get_group_by_desc_f (pGroupBy1),

    ar_dept_pkg.ar_get_group_by_desc_f (pGroupBy2)

  into

    vChangeColumn1,

    vGroupColumn1,

    vChangeColumn2,

    vGroupColumn2,

    vReportGroupBy1Description,

    vReportGroupBy2Description

  from dual

  where 1=1;



  --

  -- check if report data exists in tables AR_RECON_SAVED_DATA_HDR and AR_RECON_SAVED_DATA_HDR for the same parameters (SF-00278253)

  --

  if (pRecalculate = 1) then

    --

    -- check and delete data from tables AR_RECON_SAVED_DATA_HDR and AR_RECON_SAVED_DATA_HDR if they exists

    --

    begin

    

      v_step := 21;

          

      select arh."Batch"

      into vBatch

      from ar_recon_saved_data_hdr arh

      where 1=1

      and arh."ReportType" = 0                                                  -- AX-26491

      and arh."IncludeUnallocated" = pIncludeUnallocated

      and arh."GroupBy2" = pGroupBy2

      and arh."GroupBy1" = pGroupBy1

      and arh."ToDate" = vToDate

      and arh."FromDate" = vFromDate

      and arh."Department" = pDepartment

      and arh."ExpiryDate" >= trunc(vSysdate);                                 -- AX-26491.js



      v_step := 22;

          

      delete from ar_recon_saved_data_hdr arh

      where 1=1

      and arh."ReportType" = 0                                                  -- AX-26491

      and arh."Batch" = vBatch;

    

      v_step := 23;

      

      -- AX-26491.js altered the query to delete details for teh given batch only

      delete from ar_recon_saved_data_dtl ard

      where 1=1

      and ard."Batch" = vBatch;

      

    exception

      when others then

        null;

    end;

  

    --

    -- insert into AR_RECON_SAVED_DATA_HDR; AX-26473; AX-26473.2

    --

    v_step := 24;

    

    insert into ar_recon_saved_data_hdr

    select

      ar_recon_saved_data_hdr_seq.nextval "Batch",

      vExpiryDate "ExpiryDate",

      vSysdate "FirstRunDate",

      vSysdate "LastRunDate",

      pDepartment "Department",

      vFromDate "FromDate",

      vToDate "ToDate",

      pGroupBy1 "GroupBy1",

      vReportGroupBy1Description "GroupBy1Description",

      pGroupBy2 "GroupBy2",

      vReportGroupBy2Description "GroupBy2Description",

      pIsDetailed "IsDetailed",

      pIncludeUnallocated "IncludeUnallocated",

      pPatient "Patient",

      pOrigRecNo "OrigRecNo",

      0 "BeginningBalance",

      0 "PeriodBalance",

      0 "EndingBalance",

      0 "ReportType",

      vSysdate "StartDateTime",

      to_date(null) "EndDateTime"

    from dual

    where 1=1;

    

    vBatch := ar_recon_saved_data_hdr_seq.currval;

    vReturnBatch := vBatch;

    vIsNewBatchID := 1;



  else



    begin

      --

      -- check if data exists from tables AR_RECON_SAVED_DATA_HDR and AR_RECON_SAVED_DATA_HDR and, if they exists, use existing data for the report

      --

      v_step := 25;

      

      select

        arh."Batch",

        arh."IsDetailed"

      into

        vBatch,

        vIsDetailed

      from ar_recon_saved_data_hdr arh

      where 1=1

      and arh."ReportType" = 0                                                  -- AX-26491

      and exists (select null

                  from ar_recon_saved_data_dtl ard

                  where 1=1

                  and ard."Batch" = arh."Batch")

      and arh."IncludeUnallocated" = pIncludeUnallocated

      and arh."GroupBy2" = pGroupBy2

      and arh."GroupBy1" = pGroupBy1

      and arh."ToDate" = vToDate

      and arh."FromDate" = vFromDate

      and arh."Department" = pDepartment

      and arh."ExpiryDate" >= trunc(vSysdate);                                 -- AX-26491.js

    

      if (vIsDetailed <> pIsDetailed) then

    

        v_step := 26;

        

        update ar_recon_saved_data_dtl ard

        set ard."ReportIsDetailed" = pIsDetailed

        where 1=1

        and ard."Batch" = vBatch;

    

      end if;

    

      --

      -- copy existing report data into HISTORY_AR_GLOBAL_TEMP3

      --

      v_step := 27;

      

      insert into history_ar_global_temp3

      select

        ard."History",

        ard."HistoryType",

        ard."OrigRecNo",

        ard."Type",

        ard."Id",

        ard."Treatment",

        ard."ModifiedDate",

        ard."TreatmentDate",

        ard."Producer",

        ard."Procedure",

        ard."Patient",

        ard."Family",

        ard."Code",

        ard."Description",  

        ard."Company1",    

        ard."ReportDepartment",

        ard."ReportDiscipline",

        ard."ReportProcedure",

        ard."ReportPractice",

        ard."ReportClaimDoctor",

        ard."ReportLocation",

        ard."ReportEntryUser",

        ard."ReportAppUser",

        ard."ReportCustom1",

        ard."ReportCustom2",

        ard."ReportProducer",

        ard."ReportTypeCode",

        ard."ReportPGroup",

        ard."ReportYear",

        ard."ReportCustomCode1",

        ard."ReportCustomCode2",

        ard."ReportCustomCode3",

        ard."ReportCustomCode4",

        ard."ReportCustomCode5",

        ard."ReportCustomCode6",

        ard."ReportCustomCode7",

        ard."ReportCustomCode8",

        ard."ReportCustomCode9",

        ard."ReportCustomCode10",

        ard."ReportGroupBy1",

        ard."ReportGroupBy1Description",

        ard."ReportGroupBy2",

        ard."ReportGroupBy2Description",

        ard."ReportFromDate",

        ard."ReportToDate",

        ard."ReportIsDetailed",

        ard."ReportIncludeUnallocated",

        ard."ReportHistoryTypeDescription",

        ard."ReportOldTotal",

        ard."ReportTotal",

        ard."ReportTotalChange",

        ard."ReportOldInsTotal",

        ard."ReportInsTotal",

        ard."ReportInsTotalChange",

        ard."ReportOldPayed",

        ard."ReportPayed",

        ard."ReportPayedChange",

        ard."ReportOldInsPayed",

        ard."ReportInsPayed",

        ard."ReportInsPayedChange",

        ard."ReportOldPtAdj",

        ard."ReportPtAdj",

        ard."ReportPtAdjChange",

        ard."ReportOldInsAdj",

        ard."ReportInsAdj",

        ard."ReportInsAdjChange",

        ard."ReportOldInsTransfer",

        ard."ReportInsTransfer",

        ard."ReportInsTransferChange",

        ard."PreviousHistory"                                                 

      from ar_recon_saved_data_dtl ard

      where 1=1

      and ard."Batch" = vBatch;



      v_step := 28;

      

      update ar_recon_saved_data_hdr arh

      set

        arh."ExpiryDate" = decode(pUpdateExpiryDateIfNotNewData, 0, arh."ExpiryDate", vExpiryDate),

        arh."LastRunDate" = vSysdate,

        arh."IsDetailed" = pIsDetailed

      where 1=1

      and arh."ReportType" = 0                                                  -- AX-26491

      and arh."Batch" = vBatch;



      vReturnBatch := vBatch;  

      vBatch := 0;



    exception

      when no_data_found then

        --

        -- insert into AR_RECON_SAVED_DATA_HDR; AX-26473; AX-26473.2

        --

        v_step := 29;

        

        insert into ar_recon_saved_data_hdr

        select

          ar_recon_saved_data_hdr_seq.nextval "Batch",

          vExpiryDate "ExpiryDate",

          vSysdate "FirstRunDate",

          vSysdate "LastRunDate",

          pDepartment "Department",

          vFromDate "FromDate",

          vToDate "ToDate",

          pGroupBy1 "GroupBy1",

          vReportGroupBy1Description "GroupBy1Description",

          pGroupBy2 "GroupBy2",

          vReportGroupBy2Description "GroupBy2Description",

          pIsDetailed "IsDetailed",

          pIncludeUnallocated "IncludeUnallocated",

          pPatient "Patient",

          pOrigRecNo "OrigRecNo",

          0 "BeginningBalance",

          0 "PeriodBalance",

          0 "EndingBalance",

          0 "ReportType",

          vSysdate "StartDateTime",

          to_date(null) "EndDateTime"

        from dual

        where 1=1;

      

        vBatch := ar_recon_saved_data_hdr_seq.currval;

        vReturnBatch := vBatch;

        vIsNewBatchID := 1;



    end;



  end if;



if (vBatch > 0) then     -- SF-00278253 (reprocess report data)



  --

  -- get the history records for the period

  --

  v_step := 30;

  

  if ((pOrigRecNo = 0) and (pPatient = 0)) then

  

    insert into history_ar_global_temp

    select /*+ parallel(h, 4) */

      h.*,

      vCurrent "ReportPeriod",

      ' ' "Department",

      ' ' "Producer_TypeCode",

      ' ' "Producer_PGroup",

      0 "Producer_Year",

      ' ' "Patient_CustomCode1",

      ' ' "Patient_CustomCode2",

      ' ' "Patient_CustomCode3",

      ' ' "Patient_CustomCode4",

      ' ' "Patient_CustomCode5",

      ' ' "Patient_CustomCode6",

      ' ' "Patient_CustomCode7",

      ' ' "Patient_CustomCode8",

      ' ' "Patient_CustomCode9",

      ' ' "Patient_CustomCode10",

      pGroupBy1,

      vReportGroupBy1Description,

      pGroupBy2,

      vReportGroupBy2Description,

      vFromDate,

      vToDate,

      pIsDetailed,

      pIncludeUnallocated

    from history h

    where 1=1

    and (h."Type" = 1

         or h."Type" = 2

         or (h."Type" = 5 and h."OrthoStatus" = 0))

    and h."ModifiedDate" between vFromDate and vToDate

    and trunc(h."ModifiedDate") between vFromDate and vToDate

    and

    -- Added by Jon Dawes 2016-03-11.

    (--

    --

    h."TreatmentDate" <= vToDate

    --

    -- Added by Jon Dawes 2016-03-11.

    or h."Type" = 2)

    --

    order by     -- SF-00278253

      h."OrigRecNo",

      h."Family",

      h."History"

    ;



    --

    -- AX-20468 (insert post-dated office charges)

    --

    v_step := 32;

    

    insert into history_ar_global_temp

    select /*+ parallel(h, 4) */

      h.*,

      vCurrent "ReportPeriod",

      ' ' "Department",

      ' ' "Producer_TypeCode",

      ' ' "Producer_PGroup",

      0 "Producer_Year",

      ' ' "Patient_CustomCode1",

      ' ' "Patient_CustomCode2",

      ' ' "Patient_CustomCode3",

      ' ' "Patient_CustomCode4",

      ' ' "Patient_CustomCode5",

      ' ' "Patient_CustomCode6",

      ' ' "Patient_CustomCode7",

      ' ' "Patient_CustomCode8",

      ' ' "Patient_CustomCode9",

      ' ' "Patient_CustomCode10",

      pGroupBy1,

      vReportGroupBy1Description,

      pGroupBy2,

      vReportGroupBy2Description,

      vFromDate,

      vToDate,

      pIsDetailed,

      pIncludeUnallocated

    from history h

    where 1=1

    and h."Type" = 2

    and ((h."ModifiedDate" between vFromDate and vToDate

          and trunc(h."ModifiedDate") between vFromDate and vToDate)

         or (h."TreatmentDate" between vFromDate and vToDate

             and trunc(h."TreatmentDate") between vFromDate and vToDate))

    and not exists (select null

                    from history_ar_global_temp h2

                    where 1=1

                    and h2."History" = h."History")

    order by     -- SF-00278253

      h."OrigRecNo",

      h."Family",

      h."History"

;



  else

  

    insert into history_ar_global_temp

    select /*+ parallel(h, 4) */

      h.*,

      vCurrent "ReportPeriod",

      ' ' "Department",

      ' ' "Producer_TypeCode",

      ' ' "Producer_PGroup",

      0 "Producer_Year",

      ' ' "Patient_CustomCode1",

      ' ' "Patient_CustomCode2",

      ' ' "Patient_CustomCode3",

      ' ' "Patient_CustomCode4",

      ' ' "Patient_CustomCode5",

      ' ' "Patient_CustomCode6",

      ' ' "Patient_CustomCode7",

      ' ' "Patient_CustomCode8",

      ' ' "Patient_CustomCode9",

      ' ' "Patient_CustomCode10",

      pGroupBy1,

      vReportGroupBy1Description,

      pGroupBy2,

      vReportGroupBy2Description,

      vFromDate,

      vToDate,

      pIsDetailed,

      pIncludeUnallocated

    from history h

    where 1=1

    and h."OrigRecNo" = decode(pOrigRecNo, 0, h."OrigRecNo", pOrigRecNo)

    and h."Patient" = decode(pPatient, 0, h."Patient", pPatient)  

    and (h."Type" = 1

         or h."Type" = 2

         or (h."Type" = 5 and h."OrthoStatus" = 0))

    and h."ModifiedDate" between vFromDate and vToDate

    and trunc(h."ModifiedDate") between vFromDate and vToDate

    and

    -- Added by Jon Dawes 2016-03-11.

    (--

    --

    h."TreatmentDate" <= vToDate

    --

    -- Added by Jon Dawes 2016-03-11.

    or h."Type" = 2)

    --

    order by     -- SF-00278253

      h."OrigRecNo",

      h."Family",

      h."History"

    ;    



    --

    -- AX-20468 (insert post-dated office charges)

    --

    v_step := 34;



    insert into history_ar_global_temp

    select /*+ parallel(h, 4) */

      h.*,

      vCurrent "ReportPeriod",

      ' ' "Department",

      ' ' "Producer_TypeCode",

      ' ' "Producer_PGroup",

      0 "Producer_Year",

      ' ' "Patient_CustomCode1",

      ' ' "Patient_CustomCode2",

      ' ' "Patient_CustomCode3",

      ' ' "Patient_CustomCode4",

      ' ' "Patient_CustomCode5",

      ' ' "Patient_CustomCode6",

      ' ' "Patient_CustomCode7",

      ' ' "Patient_CustomCode8",

      ' ' "Patient_CustomCode9",

      ' ' "Patient_CustomCode10",

      pGroupBy1,

      vReportGroupBy1Description,

      pGroupBy2,

      vReportGroupBy2Description,

      vFromDate,

      vToDate,

      pIsDetailed,

      pIncludeUnallocated

    from history h

    where 1=1

    and h."OrigRecNo" = decode(pOrigRecNo, 0, h."OrigRecNo", pOrigRecNo)

    and h."Patient" = decode(pPatient, 0, h."Patient", pPatient)

    and h."Type" = 2

    and ((h."ModifiedDate" between vFromDate and vToDate

          and trunc(h."ModifiedDate") between vFromDate and vToDate)

         or (h."TreatmentDate" between vFromDate and vToDate

             and trunc(h."TreatmentDate") between vFromDate and vToDate))

    and not exists (select null

                    from history_ar_global_temp h2

                    where 1=1

                    and h2."History" = h."History")

    order by     -- SF-00278253

      h."OrigRecNo",

      h."Family",

      h."History"

;



  end if;

  

  --

  -- get the last history records prior to the period for each OrigRecNo

  --

  v_step := 40;



  insert into history_ar_global_temp4

  select /*+ full(h)

             parallel(h, 4)

             full(h2)

             parallel(h2, 4) */

    max(h."History")

  from 

    history h,

    history_ar_global_temp h2

  where 1=1

  and h."ModifiedDate" < vFromDate

  and h."TreatmentDate" < vFromDate

  and h2."Type" < 5

  and h2."OrigRecNo" = h."OrigRecNo"

  group by 

    h."Type",

    h."OrigRecNo";



  --

  -- get the last history records prior to the period

  --

  v_step := 50;

  

  if (pPatient = 0) then

  

    insert into history_ar_global_temp

    select

      h.*,

      vPrevious "ReportPeriod",

      ' ' "Department",

      ' ' "Producer_TypeCode",

      ' ' "Producer_PGroup",

      0 "Producer_Year",

      ' ' "Patient_CustomCode1",

      ' ' "Patient_CustomCode2",

      ' ' "Patient_CustomCode3",

      ' ' "Patient_CustomCode4",

      ' ' "Patient_CustomCode5",

      ' ' "Patient_CustomCode6",

      ' ' "Patient_CustomCode7",

      ' ' "Patient_CustomCode8",

      ' ' "Patient_CustomCode9",

      ' ' "Patient_CustomCode10",

      pGroupBy1,

      vReportGroupBy1Description,

      pGroupBy2,

      vReportGroupBy2Description,

      vFromDate,

      vToDate,

      pIsDetailed,

      pIncludeUnallocated

    from 

      history h,

      history_ar_global_temp4 h2

    where 1=1

    and (h."Type" = 1

         or h."Type" = 2)

    and h2."History" = h."History"

    order by     -- SF-00278253

      h."OrigRecNo",

      h."Family",

      h."History"

;

  

  else

  

    insert into history_ar_global_temp

    select

      h.*,

      vPrevious "ReportPeriod",

      ' ' "Department",

      ' ' "Producer_TypeCode",

      ' ' "Producer_PGroup",

      0 "Producer_Year",

      ' ' "Patient_CustomCode1",

      ' ' "Patient_CustomCode2",

      ' ' "Patient_CustomCode3",

      ' ' "Patient_CustomCode4",

      ' ' "Patient_CustomCode5",

      ' ' "Patient_CustomCode6",

      ' ' "Patient_CustomCode7",

      ' ' "Patient_CustomCode8",

      ' ' "Patient_CustomCode9",

      ' ' "Patient_CustomCode10",

      pGroupBy1,

      vReportGroupBy1Description,

      pGroupBy2,

      vReportGroupBy2Description,

      vFromDate,

      vToDate,

      pIsDetailed,

      pIncludeUnallocated

    from 

      history h,

      history_ar_global_temp4 h2

    where 1=1

    and h."Patient" = pPatient

    and (h."Type" = 1

         or h."Type" = 2)

    and h2."History" = h."History"

    order by     -- SF-00278253

      h."OrigRecNo",

      h."Family",

      h."History"

;

  

  end if;

   

  --

  -- removed striked-out records

  --

  v_step := 60;

  

  delete from history_ar_global_temp h

  where 1=1

  and h."HistoryType" = 4

  and h."Deleted" = 2;

  

  --

  -- removed invalid patients

  --  

  v_step := 70;

  

  delete from history_ar_global_temp h

  where 1=1

  and not exists (select null

                  from patient p

                  where 1=1

                  and p."Patient" = h."Patient");

                  

  --

  -- remove striked-out records

  --

  v_step := 80;

  

  delete from history_ar_global_temp h

  where 1=1

  and h."History" > (select min(h2."History")

                     from history_ar_global_temp h2

                     where 1=1

                     and h2."OrigRecNo" = h."OrigRecNo"

                     and h2."HistoryType" = 4

                     and h2."Deleted" = 1);

     

  --

  -- remove unnecessary ortho records

  --

  v_step := 90;

  

  delete from history_ar_global_temp h3

  where 1=1

  and h3."OrthoStatus" = 1

  and (h3."OrigRecNo",

       h3."Family",

       h3."History") not in (select

                               "OrigRecNo",

                               "Family",

                               min("ToHistory") "ToHistory"

                             from (select

                                     h."OrigRecNo",

                                     h."Family",

                                     h."History" "ToHistory",

                                     (select min(h2."History")

                                      from history_ar_global_temp h2

                                      where 1=1

                                      and h2."OrthoStatus" = 0

                                      and h2."OrigRecNo" = h."OrigRecNo"

                                      and h2."Family" = h."Family"

                                      and h2."History" > h."History") "FromHistory"

                                   from (select 

                                           "OrigRecNo",

                                           "Family",

                                           "History"

                                         from history_ar_global_temp

                                         where 1=1

                                         and "OrthoStatus" = 1) h

                                   where 1=1)

                             where 1=1

                             group by

                               "OrigRecNo",

                               "Family",    

                               "FromHistory");

  --

  -- Added by Jon Dawes 2016-03-11

  -- Remove all post dated office charge history records that are not

  -- immediately preceded by records that are not post dated.

  --

  v_step := 95;

  

  delete from history_ar_global_temp h

  where 1=1

  and h."Type" = 2

  and h."TreatmentDate" > vToDate

  and not exists (select null

                  from history_ar_global_temp h1

                  where 1=1

                  and h1."OrigRecNo" = h1."OrigRecNo"

                  and h1."TreatmentDate" <= vToDate

                  and h1."History" < h."History"

                  and not exists (select null

                                  from history_ar_global_temp h2

                                  where 1=1

                                  and h2."OrigRecNo" = h."OrigRecNo"

                                  and h2."TreatmentDate" <= vToDate

                                  and h2."History" < h."History"

                                  and h2."History" > h1."History"));

  --



  --

  -- Added by Jon Dawes 2016-03-11

  -- Modify post dated office charges to remove the amount on all non-insurance

  -- buckets.

  --

  v_step := 96;

  

  update history_ar_global_temp h

  set

    h."Total" = 0, 

    h."Payed" = 0, 

    h."PtAdj" = 0

  where 1=1

  and h."Type" = 2

  and h."TreatmentDate" > vToDate;



  --

  -- AX-20468 (remove office charge records that were modified after the reporting period)

  --

  v_step := 97;

  

  delete from history_ar_global_temp

  where 1=1

  and "Type" = 2

  and "TreatmentDate" between vFromDate and vToDate

  and "ModifiedDate" > vToDate;



  --

  -- AX-27637: determine if department needs to be calculated (may slow down processing time) or just use whatever department is passed to the procedure (can reduce processing time)

  --

  begin

    --

    -- check if department has corresponding department definition

    --

    v_step := 98;

  

    select 1

    into vCalculateDepartment

    from dept d

    where 1=1

    and exists (select 1

                from deptdef dd

                where 1=1

                and dd."Department" = d."Department")

    and d."Department" = pDepartment;

    

  exception

    when no_data_found then

      --

      -- use whatever department is passed to the procedure

      --

      v_step := 99;

      

      vCalculateDepartment := 0;



  end;



  --

  -- update provider, patient, department, group by information

  --

--  if (pDepartment = 'zzzzzz') then

  if ((pDepartment = 'zzzzzz') or (vCalculateDepartment = 0)) then

    --

    -- do not call AR_GET_DEPT_F

    --

    v_step := 100;



    update /*+ full(h)

               parallel(h, 4) */ history_ar_global_temp h

    set

      (h."Producer_TypeCode",

       h."Producer_PGroup",

       h."Producer_Year") = (select /*+ index(prod, PRODUCER_PRIMARY) */

                               prod."TypeCode", 

                               prod."PGroup", 

                               prod."Year"

                             from producer prod

                             where 1=1

                             and prod."Producer" = h."Producer"),      

      (h."Patient_CustomCode1",

       h."Patient_CustomCode2",

       h."Patient_CustomCode3",

       h."Patient_CustomCode4",

       h."Patient_CustomCode5",

       h."Patient_CustomCode6",

       h."Patient_CustomCode7",

       h."Patient_CustomCode8",

       h."Patient_CustomCode9",

       h."Patient_CustomCode10") = (select /*+ index(pat, PATIENT_PRIMARY) */

                                      pat."CustomCode1",

                                      pat."CustomCode2",

                                      pat."CustomCode3",

                                      pat."CustomCode4",

                                      pat."CustomCode5",

                                      pat."CustomCode6",

                                      pat."CustomCode7",

                                      pat."CustomCode8",

                                      pat."CustomCode9",

                                      pat."CustomCode10"

                                    from patient pat

                                    where 1=1

                                    and pat."Patient" = h."Patient"),

      h."Department" = pDepartment

    where 1=1;



  else

    --

    -- update PRODUCER and PATIENT related fields

    --

    v_step := 101;

    

    update /*+ full(h)

               parallel(h, 4) */ history_ar_global_temp h

    set

      (h."Producer_TypeCode",

       h."Producer_PGroup",

       h."Producer_Year") = (select /*+ index(prod, PRODUCER_PRIMARY) */

                               prod."TypeCode", 

                               prod."PGroup", 

                               prod."Year"

                             from producer prod

                             where 1=1

                             and prod."Producer" = h."Producer"),

      (h."Patient_CustomCode1",

       h."Patient_CustomCode2",

       h."Patient_CustomCode3",

       h."Patient_CustomCode4",

       h."Patient_CustomCode5",

       h."Patient_CustomCode6",

       h."Patient_CustomCode7",

       h."Patient_CustomCode8",

       h."Patient_CustomCode9",

       h."Patient_CustomCode10") = (select /*+ index(pat, PATIENT_PRIMARY) */

                                      pat."CustomCode1",

                                      pat."CustomCode2",

                                      pat."CustomCode3",

                                      pat."CustomCode4",

                                      pat."CustomCode5",

                                      pat."CustomCode6",

                                      pat."CustomCode7",

                                      pat."CustomCode8",

                                      pat."CustomCode9",

                                      pat."CustomCode10"

                                    from patient pat

                                    where 1=1

                                    and pat."Patient" = h."Patient"),

      h."Department" = 'zzzzzz'                                                 -- AX-27637

    where 1=1;



    --

    -- update department

    --

    begin

      --

      -- build SQL statement to update the department

      --

      v_step := 102;

    

      vSQLStmt := (vSQLStmt || ar_dept_pkg.ar_get_dept_f (pDepartment, 0, '', 0));

      

      --

      -- replace PRODUCER and PATIENT related strings to correct the SQL statement

      --

      v_step := 103;

      

      vSQLStmt := replace(vSQLStmt, 'prod."TypeCode"', 'h."Producer_TypeCode"');

      vSQLStmt := replace(vSQLStmt, 'prod."PGroup"', 'h."Producer_PGroup"');

      vSQLStmt := replace(vSQLStmt, 'prod."Year"', 'h."Producer_Year"');

      vSQLStmt := replace(vSQLStmt, 'pat."CustomCode1"', 'h."Patient_CustomCode1"');

      vSQLStmt := replace(vSQLStmt, 'pat."CustomCode2"', 'h."Patient_CustomCode2"');

      vSQLStmt := replace(vSQLStmt, 'pat."CustomCode3"', 'h."Patient_CustomCode3"');

      vSQLStmt := replace(vSQLStmt, 'pat."CustomCode4"', 'h."Patient_CustomCode4"');

      vSQLStmt := replace(vSQLStmt, 'pat."CustomCode5"', 'h."Patient_CustomCode5"');

      vSQLStmt := replace(vSQLStmt, 'pat."CustomCode6"', 'h."Patient_CustomCode6"');

      vSQLStmt := replace(vSQLStmt, 'pat."CustomCode7"', 'h."Patient_CustomCode7"');

      vSQLStmt := replace(vSQLStmt, 'pat."CustomCode8"', 'h."Patient_CustomCode8"');

      vSQLStmt := replace(vSQLStmt, 'pat."CustomCode9"', 'h."Patient_CustomCode9"');

      vSQLStmt := replace(vSQLStmt, 'pat."CustomCode10"', 'h."Patient_CustomCode10"');



      --

      -- execute SQL statement to update the department

      --

      v_step := 104;

  

      execute immediate vSQLStmt using pDepartment;



    exception

      when others then

        --

        -- update department using the original process

        --

        v_step := 105;



        update /*+ full(h) parallel(h, 4) */ history_ar_global_temp h

        set h."Department" = ar_dept_pkg.ar_get_dept_f (pDepartment, 

                                                        h."History", 

                                                        h."Producer", 

                                                        h."Patient")

        where 1=1;



    end;



  end if;

  

  --

  -- consider no change if one of the departments is 'zzzzzz'

  --

  v_step := 108;

          

  select count(*)

  into vDeptCount

  from history_ar_global_temp h

  where 1=1

  and h."Type" < 5

  and h."Department" = 'zzzzzz'

  and rownum = 1;  



  --

  -- insert latest transactions per OrigRecNo and offset records for deleted records into temp table (AX-27637:  moved outside of the cursor so inserts happen all at once instead of row by row)

  --

  v_step := 110;

  

  insert into history_ar_global_temp2

  with

  TmpMaxHistory as (

                    select 

                      h2."ReportPeriod",

                      h2."OrigRecNo",

                      h2."Family",

                      max(h2."History") "History"

                    from history_ar_global_temp h2

                    where 1=1

                    and h2."Type" < 5

                    group by

                      h2."ReportPeriod",

                      h2."OrigRecNo",

                      h2."Family"

                   )

  --

  -- latest transactions per OrigRecNo

  --

  select

     h.*,

     ' ' "ReportHistoryTypeDescription",

     h."Total",

     h."InsTotal",

     h."Payed",

     h."InsPayed",

     h."PtAdj",

     h."InsAdj",

     h."InsTransfer",    

     h."Department",

     h."Discipline",

     h."Procedure",

     h."Practice",

     h."ClaimDoctor",

     h."Location",

     h."EntryUser",

     h."AppUser",

     h."Custom1",

     h."Custom2",

     h."Producer",

     h."Producer_TypeCode",

     h."Producer_PGroup",

     h."Producer_Year",

     h."Patient_CustomCode1",

     h."Patient_CustomCode2",

     h."Patient_CustomCode3",

     h."Patient_CustomCode4",

     h."Patient_CustomCode5",

     h."Patient_CustomCode6",

     h."Patient_CustomCode7",

     h."Patient_CustomCode8",

     h."Patient_CustomCode9",

     h."Patient_CustomCode10"

   from

     history_ar_global_temp h,

     TmpMaxHistory tmh

   where 1=1

   and h."ReportPeriod" = tmh."ReportPeriod"

   and h."OrigRecNo" = tmh."OrigRecNo"

   and h."Family" = tmh."Family"

   and h."History" = tmh."History"

   union all

   --

   -- offset records for deleted records

   --

   select

     h3.*,

     decode(h3."OrthoStatus", 1, vToOrthoPlan, vDelete),

     (h3."Total" * -1),

     (h3."InsTotal" * -1),

     (h3."Payed" * -1),

     (h3."InsPayed" * -1),

     (h3."PtAdj" * -1),

     (h3."InsAdj" * -1),

     (h3."InsTransfer" * -1),

     h3."Department",

     h3."Discipline",

     h3."Procedure",

     h3."Practice",

     h3."ClaimDoctor",

     h3."Location",

     h3."EntryUser",

     h3."AppUser",

     h3."Custom1",

     h3."Custom2",

     h3."Producer",

     h3."Producer_TypeCode",

     h3."Producer_PGroup",

     h3."Producer_Year",

     h3."Patient_CustomCode1",

     h3."Patient_CustomCode2",

     h3."Patient_CustomCode3",

     h3."Patient_CustomCode4",

     h3."Patient_CustomCode5",

     h3."Patient_CustomCode6",

     h3."Patient_CustomCode7",

     h3."Patient_CustomCode8",

     h3."Patient_CustomCode9",

     h3."Patient_CustomCode10"

   from

     history_ar_global_temp h3,

     TmpMaxHistory tmh3

   where 1=1

   and h3."HistoryType" = 4

   and h3."Deleted" = 1

   and h3."ReportPeriod" = tmh3."ReportPeriod"

   and h3."OrigRecNo" = tmh3."OrigRecNo"

   and h3."Family" = tmh3."Family"

   and h3."History" = tmh3."History"   

   order by 120, 1;



   --

   -- save changes (AX-27637)

   --

   v_step := 120;



   commit;



  --

  -- create records for the AR report

  --

  for pMaxHistory2 in cMaxHistory2 loop

      --

      -- process changes

      --

      for pChanges in cChanges (pMaxHistory2."OrigRecNo",

                                pMaxHistory2."Family") loop

                              

        --

        -- initialize change flag; process change in department

        --

        v_step := 130;

      

        vGroupChanged := 0;

      

        if ((pChanges."DepartmentCount" > 1) and (vGroupChanged = 0)) then

          

          if (((pChanges."DepartmentCount" - vDeptCount) > 1) and (vGroupChanged = 0)) then



            ar_create_dept_txs_changes_p (pMaxHistory2."OrigRecNo",

                                          pMaxHistory2."Family",

                                          pMaxHistory2."History",

                                          vPrevious,    

                                          vChangeColumn1,

                                          vGroupColumn1,

                                          vChangeColumn2,

                                          vGroupColumn2);



            vGroupChanged := 1;

            

          end if;

          

        end if;

         

        --

        -- process change in group

        --

        v_step := 150;



        if (((pGroupBy1 > 0) or (pGroupBy2 > 0)) and ((pChanges."ProducerCount" > 1) or

                                                      (pChanges."PGroupCount" > 1) or

                                                      (pChanges."TypeCodeCount" > 1) or

                                                      (pChanges."YearCount" > 1) or

                                                      (pChanges."AppUserCount" > 1) or

                                                      (pChanges."Custom1Count" > 1) or

                                                      (pChanges."Custom2Count" > 1) or

                                                      (pChanges."DisciplineCount" > 1) or

                                                      (pChanges."EntryUserCount" > 1) or

                                                      (pChanges."LocationCount" > 1) or

                                                      (pChanges."ClaimDoctorCount" > 1) or

                                                      (pChanges."PracticeCount" > 1) or  

                                                      (pChanges."ProcedureCount" > 1) or

                                                      (pChanges."CustomCode1Count" > 1) or

                                                      (pChanges."CustomCode2Count" > 1) or

                                                      (pChanges."CustomCode3Count" > 1) or

                                                      (pChanges."CustomCode4Count" > 1) or

                                                      (pChanges."CustomCode5Count" > 1) or

                                                      (pChanges."CustomCode6Count" > 1) or

                                                      (pChanges."CustomCode7Count" > 1) or

                                                      (pChanges."CustomCode8Count" > 1) or

                                                      (pChanges."CustomCode9Count" > 1) or

                                                      (pChanges."CustomCode10Count" > 1) or

                                                      (pChanges."OrthoStatusCount" > 1)) and (vGroupChanged = 0)) then



          ar_create_dept_txs_changes_p (pMaxHistory2."OrigRecNo",

                                        pMaxHistory2."Family",

                                        pMaxHistory2."History",

                                        vPrevious,    

                                        vChangeColumn1,

                                        vGroupColumn1,

                                        vChangeColumn2,

                                        vGroupColumn2);



          vGroupChanged := 1;   

          

        end if;



        --

        -- process new and edited treatments within the same current period

        --

        v_step := 160;



        if (vGroupChanged = 0) then

        

          ar_create_dept_txs_changes_p (pMaxHistory2."OrigRecNo",

                                        pMaxHistory2."Family",

                                        pMaxHistory2."History",

                                        vPrevious,    

                                        vChangeColumn1,

                                        vGroupColumn1,

                                        vChangeColumn2,

                                        vGroupColumn2);

        else

        

          if ((pGroupBy1 = 0) and (pGroupBy2 = 0) and (pMaxHistory2."ReportPeriod" = vCurrent)) then

          

            for pMaxHistory in cMaxHistory (pMaxHistory2."ReportPeriod",

                                            pMaxHistory2."OrigRecNo",

                                            pMaxHistory2."Family",

                                            pMaxHistory2."History") loop

          

              if ((pMaxHistory."OrthoStatus" <> 1) and ((pMaxHistory."HistoryType" = 2) or ((pMaxHistory."HistoryType" = 5) and (pMaxHistory."OrthoStatus" = 0)))) then



                ar_create_dept_txs_changes_p (pMaxHistory2."OrigRecNo",

                                              pMaxHistory2."Family",

                                              pMaxHistory2."History",

                                              vPrevious,    

                                              vChangeColumn1,

                                              vGroupColumn1,

                                              vChangeColumn2,

                                              vGroupColumn2);



              end if;

              

            end loop;     -- pMaxHistory



          end if;

  

        end if;



        --

        --  change modify to new if origrecno is changed from P to I or C in current period

        --

        v_step := 170;



        select /*+ index(h2 history_ar_global_temp2_idx2) */ min(h2."History")

        into vMinHistory

        from history_ar_global_temp2 h2

        where 1=1

        and h2."Family" = pMaxHistory2."Family"

        and h2."OrigRecNo" = pMaxHistory2."OrigRecNo";

        

        if (vMinHistory is not null) then

        

          select /*+ index(h4 history_ar_global_temp_idx2) */ max(h4."History")

          into vMaxHistory

          from history_ar_global_temp h4

          where 1=1

          and (h4."HistoryType" < 4

               or h4."HistoryType" > 4)

          and h4."History" < vMinHistory

          and h4."Family" = pMaxHistory2."Family"

          and h4."OrigRecNo" = pMaxHistory2."OrigRecNo";

          

          if (vMaxHistory is not null) then

                                               

            begin

            

              begin

              

                select /*+ index(h3 history_ar_global_temp_idx1) */ 1

                into vTemp

                from history_ar_global_temp h3

                where 1=1

                and (h3."HistoryType" = 1

                     or ((h3."HistoryType" = 5) and (h3."OrthoStatus" = 0)))

                and h3."History" = vMaxHistory

                and rownum = 1;

                

              exception

                when no_data_found then

                  select /*+ index(h4 history_ar_global_temp_idx2) */ 1

                  into vTemp

                  from history_ar_global_temp h4

                  where 1=1

                  and (h4."HistoryType" < 4

                       or h4."HistoryType" > 4)                            

                  and (h4."Status" = 'P'

                       or h4."Status" = 'I')

                  and not exists (select /*+ index(h5 history_ar_global_temp_idx2) */ null

                                  from history_ar_global_temp h5

                                  where 1=1

                                  and (h5."HistoryType" < 4

                                       or h5."HistoryType" > 4)                                            

                                  and h5."Status" = 'C'

                                  and h5."History" < vMinHistory

                                  and h5."Family" = h4."Family"

                                  and h5."OrigRecNo" = h4."OrigRecNo")

                  and h4."History" < vMinHistory

                  and h4."Family" = pMaxHistory2."Family"

                  and h4."OrigRecNo" = pMaxHistory2."OrigRecNo"

                  and rownum = 1;

                  

              end;              

                        

              update /*+ index(h history_ar_global_temp2_idx1) */ history_ar_global_temp2 h

              set "ReportHistoryTypeDescription" = vNew

              where 1=1

              and (h."ReportHistoryTypeDescription" = vModified

                   or h."ReportHistoryTypeDescription" = vTransferIn

                   or h."ReportHistoryTypeDescription" = vTransferOut

                   or h."ReportHistoryTypeDescription" = ' ')

              and h."HistoryType" = 2

              and h."History" = vMinHistory;

--              and h."Family" = pMaxHistory2."Family" 

--              and h."OrigRecNo" = pMaxHistory2."OrigRecNo";



            exception

              when no_data_found then

                null;

            end;

          

          end if;

          

        end if;        



        --

        -- process negative values

        --

        v_step := 180;

    

        update /*+ index(h history_ar_global_temp2_idx2) */ history_ar_global_temp2 h

        set 

          h."ReportPeriod" = vPrevious,

          h."ReportTotal" = (h."ReportTotal" * -1),

          h."ReportInsTotal" = (h."ReportInsTotal" * -1),

          h."ReportPayed" = (h."ReportPayed" * -1),

          h."ReportInsPayed" = (h."ReportInsPayed" * -1),

          h."ReportPtAdj" = (h."ReportPtAdj" * -1),

          h."ReportInsAdj" = (h."ReportInsAdj" * -1),

          h."ReportInsTransfer" = (h."ReportInsTransfer" * -1)

        where 1=1

        and h."ReportPeriod" = vCurrent

        and (h."ReportHistoryTypeDescription" = vTransferOut

             or h."ReportHistoryTypeDescription" = vModified

             or h."ReportHistoryTypeDescription" = vDelete)

--        and sign(h."ReportTotal") = -1

        and h."ReportTotal" < 0

        and ((h."OrthoStatus" = 0        

              and h."HistoryType" = 5)

             or h."HistoryType" = 2)

        and h."Family" = pMaxHistory2."Family"

        and h."OrigRecNo" = pMaxHistory2."OrigRecNo";

        

      end loop;   -- pChanges

            

      --

      -- process Ortho treatments

      --

      for pOrthoTrx in cOrthoTrx (pMaxHistory2."OrigRecNo",

                                  pMaxHistory2."Family") loop

      

        --

        -- update to To Ortho Plan

        --

        v_step := 190;



        update /*+ index(h history_ar_global_temp2_idx1) */ history_ar_global_temp2 h

        set   

          h."ReportHistoryTypeDescription" = vToOrthoPlan,

          h."ReportTotal" = decode(h."ReportPeriod", vPrevious, h."ReportTotal", 0),

          h."ReportInsTotal" = decode(h."ReportPeriod", vPrevious, h."ReportInsTotal", 0),

          h."ReportPayed" = decode(h."ReportPeriod", vPrevious, h."ReportPayed", 0),

          h."ReportInsPayed" = decode(h."ReportPeriod", vPrevious, h."ReportInsPayed", 0),

          h."ReportPtAdj" = decode(h."ReportPeriod", vPrevious, h."ReportPtAdj", 0),

          h."ReportInsAdj" = decode(h."ReportPeriod", vPrevious, h."ReportInsAdj", 0),

          h."ReportInsTransfer" = decode(h."ReportPeriod", vPrevious, h."ReportInsTransfer", 0)   

        where 1=1

        and h."History" = pOrthoTrx."ToHistory";

      

        --

        -- update to From Ortho Plan

        --

        v_step := 200;

  

        update /*+ index(h history_ar_global_temp2_idx1) */ history_ar_global_temp2 h

        set 

          h."ReportHistoryTypeDescription" = vFromOrthoPlan,

          h."ReportTotal" = decode(h."ReportPeriod", vCurrent, h."ReportTotal", 0),

          h."ReportInsTotal" = decode(h."ReportPeriod", vCurrent, h."ReportInsTotal", 0),

          h."ReportPayed" = decode(h."ReportPeriod", vCurrent, h."ReportPayed", 0),

          h."ReportInsPayed" = decode(h."ReportPeriod", vCurrent, h."ReportInsPayed", 0),

          h."ReportPtAdj" = decode(h."ReportPeriod", vCurrent, h."ReportPtAdj", 0),

          h."ReportInsAdj" = decode(h."ReportPeriod", vCurrent, h."ReportInsAdj", 0),

          h."ReportInsTransfer" = decode(h."ReportPeriod", vCurrent, h."ReportInsTransfer", 0)             

        where 1=1

        and h."History" = pOrthoTrx."FromHistory";

         

      end loop;   -- pOrthoTrx

    

    --

    -- increment counter; reset counter to zero (0) if 50K then perform a commit (AX-27637)

    --

    v_step := 203;

    

    vCounter := (vCounter + 1);

    

    if (vCounter = 50000) then

      vCounter := 0;

      commit;      

    end if;

    

  end loop;   -- pMaxHistory2



  --

  -- update report history type description

  --

  v_step := 210;

  

  update history_ar_global_temp2 h

  set

    h."ReportHistoryTypeDescription" = decode(h."HistoryType", 1, vNew,

                                                               2, vModified,

                                                               3, vAllocate,

                                                               4, vDelete,

                                                               5, vModified,

                                                               vUnknown)

  where 1=1

  and h."ReportHistoryTypeDescription" = ' ';



  --

  -- AX-20468 (delete office charges records that says for previous period but actually has equivalent record for the current period)

  --

  v_step := 212;



  delete from history_ar_global_temp2 h2a

  where 1=1

  and h2a."TreatmentDate" < vFromDate

  and h2a."ModifiedDate" < h2a."TreatmentDate"

  and h2a."HistoryType" = 2

  and h2a."Type" = 2

  and h2a."ReportPeriod" = vPrevious

  and h2a."ReportHistoryTypeDescription" = vModified

  and exists (select null

              from history_ar_global_temp2 h2b

              where 1=1

              and h2b."ReportPeriod" = vCurrent

              and h2b."ReportHistoryTypeDescription" = h2a."ReportHistoryTypeDescription"

              and h2b."OrigRecNo" = h2a."OrigRecNo"

              and h2b."Treatment" = h2a."Treatment"

              and h2b."Id" = h2a."Id"

              and h2b."Type" = h2a."Type"

              and h2b."HistoryType" = h2a."HistoryType"

              and h2b."History" = h2a."History")

  and not exists (select null

                  from history_ar_global_temp2 h2c

                  where 1=1

                  and h2c."ReportPeriod" = vCurrent

                  and h2c."ReportHistoryTypeDescription" = h2a."ReportHistoryTypeDescription"

                  and h2c."OrigRecNo" = h2a."OrigRecNo"

                  and h2c."Treatment" = h2a."Treatment"

                  and h2c."Id" = h2a."Id"

                  and h2c."Type" = h2a."Type"

                  and h2c."HistoryType" = h2a."HistoryType"

                  and h2c."History" < h2a."History");



  --

  -- AX-20468 (delete office charges records that says for previous period but actually has equivalent record for the current period)

  --

  v_step := 214;



  delete from history_ar_global_temp2 h2a

  where 1=1

  and h2a."TreatmentDate" between vFromDate and vToDate

  and h2a."ModifiedDate" < vFromDate

  and h2a."ModifiedDate" < h2a."TreatmentDate"

  and h2a."HistoryType" = 2

  and h2a."Type" = 2

  and h2a."ReportPeriod" = vPrevious

  and h2a."ReportHistoryTypeDescription" = vModified

  and exists (select null

              from history_ar_global_temp2 h2b

              where 1=1

              and h2b."ReportPeriod" = vCurrent

              and h2b."ReportHistoryTypeDescription" = h2a."ReportHistoryTypeDescription"

              and h2b."OrigRecNo" = h2a."OrigRecNo"

              and h2b."Treatment" = h2a."Treatment"

              and h2b."Id" = h2a."Id"

              and h2b."Type" = h2a."Type"

              and h2b."HistoryType" = h2a."HistoryType"

              and h2b."History" = h2a."History")

  and not exists (select null

                  from history_ar_global_temp2 h2c

                  where 1=1

                  and h2c."ReportPeriod" = vCurrent

                  and h2c."ReportHistoryTypeDescription" = h2a."ReportHistoryTypeDescription"

                  and h2c."OrigRecNo" = h2a."OrigRecNo"

                  and h2c."Treatment" = h2a."Treatment"

                  and h2c."Id" = h2a."Id"

                  and h2c."Type" = h2a."Type"

                  and h2c."HistoryType" = h2a."HistoryType"

                  and h2c."History" < h2a."History");



  --

  -- AX-20468 (delete deleted office charges records for the current period that is supposed to be $0.00 but is not)

  --

  v_step := 216;



  delete from history_ar_global_temp2 h2a

  where 1=1

  and h2a."TreatmentDate" > vToDate

  and h2a."HistoryType" = 4

  and h2a."Type" = 2

  and h2a."ReportPeriod" = vCurrent

  and h2a."ReportHistoryTypeDescription" = vDelete

  and h2a."ReportTotal" < 0

  and exists (select null

              from history_ar_global_temp2 h2b

              where 1=1

              and h2b."ReportTotal" = 0

              and h2b."ReportPeriod" = vCurrent

              and h2b."ReportHistoryTypeDescription" = h2a."ReportHistoryTypeDescription"

              and h2b."OrigRecNo" = h2a."OrigRecNo"

              and h2b."Treatment" = h2a."Treatment"

              and h2b."Id" = h2a."Id"

              and h2b."Type" = h2a."Type"

              and h2b."HistoryType" = h2a."HistoryType"

              and h2b."History" = h2a."History")

  and not exists (select null

                  from history_ar_global_temp2 h2c

                  where 1=1

                  and h2c."ReportPeriod" = vCurrent

                  and h2c."ReportHistoryTypeDescription" = h2a."ReportHistoryTypeDescription"

                  and h2c."OrigRecNo" = h2a."OrigRecNo"

                  and h2c."Treatment" = h2a."Treatment"

                  and h2c."Id" = h2a."Id"

                  and h2c."Type" = h2a."Type"

                  and h2c."HistoryType" = h2a."HistoryType"

                  and h2c."History" < h2a."History");



  --

  -- insert into final report table

  --

  v_step := 220;

  

  insert into history_ar_global_temp3

  select

    "History",

    "HistoryType",

    "OrigRecNo",

    "Type",

    "Id",

    "Treatment",

    "ModifiedDate",

    "TreatmentDate",

    "Producer",

    "Procedure",

    "Patient",

    "Family",

    "Code",

    "Description",

    "Company1",

    "ReportDepartment",

    "ReportDiscipline",

    "ReportProcedure",

    "ReportPractice",

    "ReportClaimDoctor",

    "ReportLocation",

    "ReportEntryUser",

    "ReportAppUser",

    "ReportCustom1",

    "ReportCustom2",

    "ReportProducer",

    "ReportTypeCode",

    "ReportPGroup",

    "ReportYear",

    "ReportCustomCode1",

    "ReportCustomCode2",

    "ReportCustomCode3",

    "ReportCustomCode4",

    "ReportCustomCode5",

    "ReportCustomCode6",

    "ReportCustomCode7",

    "ReportCustomCode8",

    "ReportCustomCode9",

    "ReportCustomCode10",

    "ReportGroupBy1",

    "ReportGroupBy1Description",

    "ReportGroupBy2",

    "ReportGroupBy2Description",

    "ReportFromDate",

    "ReportToDate",

    "ReportIsDetailed",

    "ReportIncludeUnallocated",

    "ReportHistoryTypeDescription",

    sum("ReportOldTotal") "ReportOldTotal",

    sum("ReportTotal") "ReportTotal",

    (sum("ReportTotal") - sum("ReportOldTotal")) "ReportTotalChange",

    sum("ReportOldInsTotal") "ReportOldInsTotal",

    sum("ReportInsTotal") "ReportInsTotal",

    (sum("ReportInsTotal") - sum("ReportOldInsTotal")) "ReportInsTotalChange",

    sum("ReportOldPayed") "ReportOldPayed",

    sum("ReportPayed") "ReportPayed",

    (sum("ReportPayed") - sum("ReportOldPayed")) "ReportPayedChange",

    sum("ReportOldInsPayed") "ReportOldInsPayed",

    sum("ReportInsPayed") "ReportInsPayed",

    (sum("ReportInsPayed") - sum("ReportOldInsPayed")) "ReportInsPayedChange",

    sum("ReportOldPtAdj") "ReportOldPtAdj",

    sum("ReportPtAdj") "ReportPtAdj",

    (sum("ReportPtAdj") - sum("ReportOldPtAdj")) "ReportPtAdjChange",

    sum("ReportOldInsAdj") "ReportOldInsAdj",

    sum("ReportInsAdj") "ReportInsAdj",

    (sum("ReportInsAdj") - sum("ReportOldInsAdj")) "ReportInsAdjChange",

    sum("ReportOldInsTransfer") "ReportOldInsTransfer",

    sum("ReportInsTransfer") "ReportInsTransfer",

    (sum("ReportInsTransfer") - sum("ReportOldInsTransfer")) "ReportInsTransferChange",

    0 "PreviousHistory"                                                         -- AX-28014

  from 

    (select 

       h. "History",

       h."HistoryType",

       h."OrigRecNo",

       h."Type",       

       h."Id",

       h."Treatment",     

       h."ModifiedDate",

       h."TreatmentDate",

       h."Producer",

       h."Procedure",

       h."Patient",

       h."Family",

       h."Code",

       h."Description",  

       h."Company1",

       h."ReportDepartment",

       h."ReportDiscipline",

       h."ReportProcedure",

       h."ReportPractice",

       h."ReportClaimDoctor",

       h."ReportLocation",

       h."ReportEntryUser",

       h."ReportAppUser",

       h."ReportCustom1",

       h."ReportCustom2",

       h."ReportProducer",

       h."ReportTypeCode",

       h."ReportPGroup",

       h."ReportYear",

       h."ReportCustomCode1",

       h."ReportCustomCode2",

       h."ReportCustomCode3",

       h."ReportCustomCode4",

       h."ReportCustomCode5",

       h."ReportCustomCode6",

       h."ReportCustomCode7",

       h."ReportCustomCode8",

       h."ReportCustomCode9",

       h."ReportCustomCode10",

       h."ReportGroupBy1",

       h."ReportGroupBy1Description",

       h."ReportGroupBy2",  

       h."ReportGroupBy2Description",

       h."ReportFromDate",

       h."ReportToDate",

       h."ReportIsDetailed",

       h."ReportIncludeUnallocated",

       h."ReportHistoryTypeDescription",

       decode(h."ReportPeriod", vPrevious, h."ReportTotal", 0) "ReportOldTotal",

       decode(h."ReportPeriod", vCurrent, h."ReportTotal", 0) "ReportTotal",

       decode(h."ReportPeriod", vPrevious, h."ReportInsTotal", 0) "ReportOldInsTotal",

       decode(h."ReportPeriod", vCurrent, h."ReportInsTotal", 0) "ReportInsTotal",

       decode(h."ReportPeriod", vPrevious, h."ReportPayed", 0) "ReportOldPayed",

       decode(h."ReportPeriod", vCurrent, h."ReportPayed", 0) "ReportPayed",

       decode(h."ReportPeriod", vPrevious, h."ReportInsPayed", 0) "ReportOldInsPayed",

       decode(h."ReportPeriod", vCurrent, h."ReportInsPayed", 0) "ReportInsPayed",

       decode(h."ReportPeriod", vPrevious, h."ReportPtAdj", 0) "ReportOldPtAdj",

       decode(h."ReportPeriod", vCurrent, h."ReportPtAdj", 0) "ReportPtAdj",

       decode(h."ReportPeriod", vPrevious, h."ReportInsAdj", 0) "ReportOldInsAdj",

       decode(h."ReportPeriod", vCurrent, h."ReportInsAdj", 0) "ReportInsAdj",

       decode(h."ReportPeriod", vPrevious, h."ReportInsTransfer", 0) "ReportOldInsTransfer",

       decode(h."ReportPeriod", vCurrent, h."ReportInsTransfer", 0) "ReportInsTransfer"

     from history_ar_global_temp2 h

     where 1=1

    )

  where 1=1

  group by

    "History",

    "HistoryType",

    "OrigRecNo",

    "Type",

    "Id",

    "Treatment",

    "ModifiedDate",

    "TreatmentDate",

    "Producer",

    "Procedure",

    "Patient",

    "Family",

    "Code",

    "Description",

    "Company1",

    "ReportDepartment",

    "ReportDiscipline",

    "ReportProcedure",

    "ReportPractice",

    "ReportClaimDoctor",

    "ReportLocation",

    "ReportEntryUser",

    "ReportAppUser",

    "ReportCustom1",

    "ReportCustom2",

    "ReportProducer",

    "ReportTypeCode",

    "ReportPGroup",

    "ReportYear",

    "ReportCustomCode1",

    "ReportCustomCode2",

    "ReportCustomCode3",

    "ReportCustomCode4",

    "ReportCustomCode5",

    "ReportCustomCode6",

    "ReportCustomCode7",

    "ReportCustomCode8",

    "ReportCustomCode9",

    "ReportCustomCode10",

    "ReportGroupBy1",

    "ReportGroupBy1Description",

    "ReportGroupBy2",

    "ReportGroupBy2Description",

    "ReportFromDate",

    "ReportToDate",

    "ReportIsDetailed",

    "ReportIncludeUnallocated",

    "ReportHistoryTypeDescription";    

                         

  --

  -- save changes then empty global temporary tables HISTORY_AR_GLOBAL_TEMP, HISTORY_AR_GLOBAL_TEMP2, HISTORY_AR_GLOBAL_TEMP4

  --

  v_step := 230;

  

  commit;



  -- AX-27637  

  execute immediate 'truncate table history_ar_global_temp';

  execute immediate 'truncate table history_ar_global_temp2';

  execute immediate 'truncate table history_ar_global_temp4';



  --

  -- remove unnecessary records

  --

  v_step := 240;

  

  delete from history_ar_global_temp3

  where 1=1

  and "ReportTotalChange" = 0

  and "ReportInsTotalChange" = 0

  and "ReportPayedChange" = 0

  and "ReportInsPayedChange" = 0

  and "ReportPtAdjChange" = 0

  and "ReportInsAdjChange" = 0

  and "ReportInsTransferChange" = 0

  and "ReportHistoryTypeDescription" not in (vNew, vTransferIn, vTransferOut, vDelete);

                          

  --

  -- remove records where changes does not involve dollar amount

  -- only when there is no group by

  --

  v_step := 250;

  

  if (vGroupChanged = 0) then

  

    delete from history_ar_global_temp3 h

    where 1=1

    and h."OrigRecNo" in (select h2."OrigRecNo"

                          from history_ar_global_temp3 h2

                          where 1=1

                          group by h2."OrigRecNo"

                          having 1=1

                          and sum(h2."ReportTotalChange") = 0

                          and sum(h2."ReportInsTotalChange") = 0

                          and sum(h2."ReportPayedChange") = 0

                          and sum(h2."ReportInsPayedChange") = 0

                          and sum(h2."ReportPtAdjChange") = 0

                          and sum(h2."ReportInsAdjChange") = 0

                          and sum(h2."ReportInsTransferChange") = 0)

    and not exists (select null

                    from history_ar_global_temp3 h3

                    where 1=1

                    and h3."OrigRecNo" = h."OrigRecNo"

                    and (h3."ReportHistoryTypeDescription" = vNew

                         or h3."ReportHistoryTypeDescription" = vTransferIn

                         or h3."ReportHistoryTypeDescription" = vTransferOut

                         or h3."ReportHistoryTypeDescription" = vToOrthoPlan

                         or h3."ReportHistoryTypeDescription" = vFromOrthoPlan

                         or h3."ReportHistoryTypeDescription" = vDelete));



  end if;

                               

  --

  -- summarize output

  --

  for pSumTotals in cSumTotals loop

    --

    -- delete detail records

    --

    v_step := 260;

  

    delete from history_ar_global_temp3 h

    where 1=1

    and h."History" = pSumTotals."History"

    and h."HistoryType" = pSumTotals."HistoryType"

    and h."OrigRecNo" = pSumTotals."OrigRecNo"

    and h."Type" = pSumTotals."Type"

    and h."Id" = pSumTotals."Id"

    and h."Treatment" = pSumTotals."Treatment"

    and h."ModifiedDate" = pSumTotals."ModifiedDate"

    and h."TreatmentDate" = pSumTotals."TreatmentDate"

    and h."Producer" = pSumTotals."Producer"

    and h."Procedure" = pSumTotals."Procedure"

    and h."Patient" = pSumTotals."Patient"

    and h."Family" = pSumTotals."Family"

    and h."Code" = pSumTotals."Code"

    and h."Description" = pSumTotals."Description"

    and h."Company1" = pSumTotals."Company1"

    and h."ReportDepartment" = pSumTotals."ReportDepartment"

    and h."ReportDiscipline" = pSumTotals."ReportDiscipline"

    and h."ReportProcedure" = pSumTotals."ReportProcedure"

    and h."ReportPractice" = pSumTotals."ReportPractice"

    and h."ReportClaimDoctor" = pSumTotals."ReportClaimDoctor"

    and h."ReportLocation" = pSumTotals."ReportLocation"

    and h."ReportEntryUser" = pSumTotals."ReportEntryUser"

    and h."ReportAppUser" = pSumTotals."ReportAppUser"

    and h."ReportCustom1" = pSumTotals."ReportCustom1"

    and h."ReportCustom2" = pSumTotals."ReportCustom2"

    and h."ReportProducer" = pSumTotals."ReportProducer"

    and h."ReportTypeCode" = pSumTotals."ReportTypeCode"

    and h."ReportPGroup" = pSumTotals."ReportPGroup"

    and h."ReportYear" = pSumTotals."ReportYear"

    and h."ReportCustomCode1" = pSumTotals."ReportCustomCode1"

    and h."ReportCustomCode2" = pSumTotals."ReportCustomCode2"

    and h."ReportCustomCode3" = pSumTotals."ReportCustomCode3"

    and h."ReportCustomCode4" = pSumTotals."ReportCustomCode4"

    and h."ReportCustomCode5" = pSumTotals."ReportCustomCode5"

    and h."ReportCustomCode6" = pSumTotals."ReportCustomCode6"

    and h."ReportCustomCode7" = pSumTotals."ReportCustomCode7"

    and h."ReportCustomCode8" = pSumTotals."ReportCustomCode8"

    and h."ReportCustomCode9" = pSumTotals."ReportCustomCode9"

    and h."ReportCustomCode10" = pSumTotals."ReportCustomCode10"

    and h."ReportGroupBy1" = pSumTotals."ReportGroupBy1"

    and h."ReportGroupBy1Description" = pSumTotals."ReportGroupBy1Description"

    and h."ReportGroupBy2" = pSumTotals."ReportGroupBy2"

    and h."ReportGroupBy2Description" = pSumTotals."ReportGroupBy2Description"

    and h."ReportFromDate" = pSumTotals."ReportFromDate"

    and h."ReportToDate" = pSumTotals."ReportToDate"

    and h."ReportIsDetailed" = pSumTotals."ReportIsDetailed"

    and h."ReportIncludeUnallocated" = pSumTotals."ReportIncludeUnallocated"

    and h."ReportHistoryTypeDescription" = pSumTotals."ReportHistoryTypeDescription";

    

    --

    -- insert back summary records

    --

    v_step := 270;

    

    insert into history_ar_global_temp3

    values (

            pSumTotals."History",

            pSumTotals."HistoryType",

            pSumTotals."OrigRecNo",

            pSumTotals."Type",

            pSumTotals."Id",

            pSumTotals."Treatment",

            pSumTotals."ModifiedDate",

            pSumTotals."TreatmentDate",

            pSumTotals."Producer",

            pSumTotals."Procedure",

            pSumTotals."Patient",

            pSumTotals."Family",

            pSumTotals."Code",

            pSumTotals."Description",

            pSumTotals."Company1",

            pSumTotals."ReportDepartment",

            pSumTotals."ReportDiscipline",

            pSumTotals."ReportProcedure",

            pSumTotals."ReportPractice",

            pSumTotals."ReportClaimDoctor",

            pSumTotals."ReportLocation",

            pSumTotals."ReportEntryUser",

            pSumTotals."ReportAppUser",

            pSumTotals."ReportCustom1",

            pSumTotals."ReportCustom2",

            pSumTotals."ReportProducer",

            pSumTotals."ReportTypeCode",

            pSumTotals."ReportPGroup",

            pSumTotals."ReportYear",

            pSumTotals."ReportCustomCode1",

            pSumTotals."ReportCustomCode2",

            pSumTotals."ReportCustomCode3",

            pSumTotals."ReportCustomCode4",

            pSumTotals."ReportCustomCode5",

            pSumTotals."ReportCustomCode6",

            pSumTotals."ReportCustomCode7",

            pSumTotals."ReportCustomCode8",

            pSumTotals."ReportCustomCode9",

            pSumTotals."ReportCustomCode10",

            pSumTotals."ReportGroupBy1",

            pSumTotals."ReportGroupBy1Description",

            pSumTotals."ReportGroupBy2",

            pSumTotals."ReportGroupBy2Description",

            pSumTotals."ReportFromDate",

            pSumTotals."ReportToDate",

            pSumTotals."ReportIsDetailed",

            pSumTotals."ReportIncludeUnallocated",

            pSumTotals."ReportHistoryTypeDescription",

            pSumTotals."ReportOldTotal",

            pSumTotals."ReportTotal",

            pSumTotals."ReportTotalChange",

            pSumTotals."ReportOldInsTotal",

            pSumTotals."ReportInsTotal",

            pSumTotals."ReportInsTotalChange",

            pSumTotals."ReportOldPayed",

            pSumTotals."ReportPayed",

            pSumTotals."ReportPayedChange",

            pSumTotals."ReportOldInsPayed",

            pSumTotals."ReportInsPayed",

            pSumTotals."ReportInsPayedChange",

            pSumTotals."ReportOldPtAdj",

            pSumTotals."ReportPtAdj",

            pSumTotals."ReportPtAdjChange",

            pSumTotals."ReportOldInsAdj",

            pSumTotals."ReportInsAdj",

            pSumTotals."ReportInsAdjChange",

            pSumTotals."ReportOldInsTransfer",

            pSumTotals."ReportInsTransfer",

            pSumTotals."ReportInsTransferChange",

            0                                                                   -- "PreviousHistory" (AX-28014)

           );

           

  end loop;



  --

  -- compute buckets

  --

  for pComputeBuckets in cComputeBuckets loop

  

    if (pComputeBuckets."History2" is not null) then

     --

      -- AX-20468 (make it easy to troubleshoot issue with AX-659)

      -- set variables to current record values

      --

      v_step := 272;



      vHistory := pComputeBuckets."History";

      vHistory2 := pComputeBuckets."History2";



      --

      -- update old totals

      --

      v_step := 280;

      

      update history_ar_global_temp3 h

      set

        (h."ReportOldPayed",

         h."ReportOldInsPayed",

         h."ReportOldPtAdj",

         h."ReportOldInsAdj",

         h."ReportOldInsTransfer") = (select 

                                        (h."ReportOldPayed" + h2."ReportPayed"),

                                        (h."ReportOldInsPayed" + h2."ReportInsPayed"),

                                        (h."ReportOldPtAdj" + h2."ReportPtAdj"),

                                        (h."ReportOldInsAdj" + h2."ReportInsAdj"),

                                        (h."ReportOldInsTransfer" + h2."ReportInsTransfer")

                                      from history_ar_global_temp3 h2

                                      where 1=1

                                      and h2."HistoryType" = h."HistoryType"

                                      and h2."History" = pComputeBuckets."History2")

      where 1=1

      and ctid = pComputeBuckets.ctid;

      

      --

      -- update new totals

      --

      v_step := 290;

      

      update history_ar_global_temp3 h

      set

        h."ReportPayed" = (h."ReportPayed" + h."ReportOldPayed"),

        h."ReportInsPayed" = (h."ReportInsPayed" + h."ReportOldInsPayed"),

        h."ReportPtAdj" = (h."ReportPtAdj" + h."ReportOldPtAdj"),

        h."ReportInsAdj" = (h."ReportInsAdj" + h."ReportOldInsAdj"),

        h."ReportInsTransfer" = (h."ReportInsTransfer" + h."ReportOldInsTransfer")

      where 1=1

      and ctid = pComputeBuckets.ctid;

      

    end if;

    

  end loop;

  

  --

  -- delete records that are not for the department

  --

  v_step := 300;

  

  delete from history_ar_global_temp3

  where 1=1

  and "ReportDepartment" <> pDepartment;  

  

  --

  -- delete records that are outside of the reporting period

  --

  v_step := 305;

  

  delete from history_ar_global_temp3

  where 1=1

  and ("ModifiedDate" < "ReportFromDate"

       or "ModifiedDate" > "ReportToDate")

  --

  -- AX-20468 (do not delete post-dated office charges)

  --

  and ("TreatmentDate" < "ReportFromDate"

       or "TreatmentDate" < "ReportFromDate");

   

  --

  -- process unallocated transactions

  --

  v_step := 310;

  

  if (pIncludeUnallocated = 1) then

    

    ar_create_unallocated_txs_p (vFromDate,

                                 vToDate,

                                 pGroupBy1,

                                 vReportGroupBy1Description,

                                 pGroupBy2,

                                 vReportGroupBy2Description,

                                 pIsDetailed,

                                 pIncludeUnallocated,

                                 pPatient,

                                 pOrigRecNo);

                                       

  end if;

  

  --

  -- E139522: switch old and new total values for Deleted transactions

  --

  v_step := 315;

  

  update history_ar_global_temp3

  set

    "ReportOldTotal" = (-1 * "ReportTotal"),

    "ReportTotal" = (-1 * "ReportOldTotal"),

    "ReportOldInsTotal" = (-1 * "ReportInsTotal"),

    "ReportInsTotal" = (-1 * "ReportOldInsTotal"),

    "ReportOldPayed" = (-1 * "ReportPayed"),

    "ReportPayed" = (-1 * "ReportOldPayed"),

    "ReportOldInsPayed" = (-1 * "ReportInsPayed"),

    "ReportInsPayed" = (-1 * "ReportOldInsPayed"),

    "ReportOldPtAdj" = (-1 * "ReportPtAdj"),

    "ReportPtAdj" = (-1 * "ReportOldPtAdj"),

    "ReportOldInsAdj" = (-1 * "ReportInsAdj"),

    "ReportInsAdj" = (-1 * "ReportOldInsAdj"),

    "ReportOldInsTransfer" = (-1 * "ReportInsTransfer"),

    "ReportInsTransfer" = (-1 * "ReportOldInsTransfer")

  where 1=1

  and "ReportHistoryTypeDescription" = 'Delete'

  and "HistoryType" = 4;



  --

  -- update "PreviousHistory" column with actual previous History ID (AX-28014)

  --

  v_step := 317;

  

  update history_ar_global_temp3 h3

  set h3."PreviousHistory" = (select nvl(max(h."History"), 0)

                              from history h

                              where 1=1

                              and h."History" < h3."History"

                              and h."OrigRecNo" = h3."OrigRecNo")

  where 1=1;



  --

  -- save changes then empty global temporary tables HISTORY_AR_GLOBAL_TEMP, HISTORY_AR_GLOBAL_TEMP2, HISTORY_AR_GLOBAL_TEMP4

  --

  v_step := 320;

  

  commit;



  -- AX-27637  

  execute immediate 'truncate table history_ar_global_temp';

  execute immediate 'truncate table history_ar_global_temp2';

  execute immediate 'truncate table history_ar_global_temp4';



  --

  -- insert report data into AR_RECON_SAVED_DATA_DTL (SF-00278253)

  --

  v_step := 325;



  insert into ar_recon_saved_data_dtl

  select

    vBatch,

    h3.*

  from history_ar_global_temp3 h3

  where 1=1;

  

  --

  -- return total change

  --

  v_step := 330;

  

  select sum(nvl("ReportTotalChange", 0) - nvl("ReportPayedChange", 0) + nvl("ReportPtAdjChange", 0) - nvl("ReportInsPayedChange", 0) - nvl("ReportInsAdjChange", 0))

  into vOut

  from history_ar_global_temp3

  where 1=1

  and "ReportDepartment" = pDepartment;



  --

  -- update AR_RECON_SAVED_DATA_HDR with correct balances information (SF-00278253)

  --

  v_step := 331;



  select

    ar_dept_pkg.ar_get_dept_asat_f(pDepartment,

                                   (vFromDate - 1),

                                   pPatient,

                                   pOrigRecNo,

                                   pRecalculate)

  into vBeginningBalance

  from dual;

                                                            

  select ar_dept_pkg.ar_get_dept_asat_f(pDepartment,

                                        vToDate,

                                        pPatient,

                                        pOrigRecNo,

                                        pRecalculate)

  into vEndingBalance

  from dual;



  update ar_recon_saved_data_hdr adh

  set

    adh."BeginningBalance" = vBeginningBalance, /*ar_dept_pkg.ar_get_dept_asat_f(pDepartment,

                                                            (vFromDate - 1),

                                                            pPatient,

                                                            pOrigRecNo,

                                                            pRecalculate),*/

    adh."PeriodBalance" = nvl(vOut, 0),

    adh."EndingBalance" = vEndingBalance, /*ar_dept_pkg.ar_get_dept_asat_f(pDepartment,

                                                         vToDate,

                                                         pPatient,

                                                         pOrigRecNo,

                                                         pRecalculate)*/

    adh."EndDateTime" = nvl(adh."EndDateTime", sysdate)                         -- AX-26473.2

  where 1=1

  and adh."ReportType" = 0                                                      -- AX-26491

  and adh."Batch" = vBatch;



else

  --

  -- return total change

  --

  v_step := 330;

  

  select sum(nvl("ReportTotalChange", 0) - nvl("ReportPayedChange", 0) + nvl("ReportPtAdjChange", 0) - nvl("ReportInsPayedChange", 0) - nvl("ReportInsAdjChange", 0))

  into vOut

  from history_ar_global_temp3

  where 1=1

  and "ReportDepartment" = pDepartment;



end if;     -- SF-00278253



  --

  -- save changes

  --

  v_step := 320;

    

  commit;



--  return nvl(vOut, 0);

--  return nvl(vReturnBatch, 0);

  pBatchID := nvl(vReturnBatch, 0);

  pIsNewBatchID := nvl(vIsNewBatchID, 0);

  

exception

  when ora_01427 then

    --

    -- AX-20468 (make it easy to troubleshoot issue with AX-659)

    -- keep only records that causes the process to error out; delete the other records

    --

    v_step := 332;

    

    delete from history_ar_global_temp3

    where 1=1

    and "History" not in (vHistory, vHistory2);

    

    --

    -- save changes then empty global temporary tables HISTORY_AR_GLOBAL_TEMP, HISTORY_AR_GLOBAL_TEMP2, HISTORY_AR_GLOBAL_TEMP4

    --

    v_step := 334;

  

    commit;



    -- AX-27637  

    execute immediate 'truncate table history_ar_global_temp';

    execute immediate 'truncate table history_ar_global_temp2';

    execute immediate 'truncate table history_ar_global_temp4';



    --

    -- return total change

    --

    v_step := 336;

  

    select sum(nvl("ReportTotalChange", 0) - nvl("ReportPayedChange", 0) + nvl("ReportPtAdjChange", 0) - nvl("ReportInsPayedChange", 0) - nvl("ReportInsAdjChange", 0))

    into vOut

    from history_ar_global_temp3

    where 1=1;

  

--    return nvl(vOut, 0);

--    return nvl(vReturnBatch, 0);

    pBatchID := nvl(vReturnBatch, 0);

    pIsNewBatchID := nvl(vIsNewBatchID, 0);



/*

  when others then

    rollback;

--    return 0;

--    return nvl(vReturnBatch, 0);

    pBatchID := nvl(vReturnBatch, 0);

    pIsNewBatchID := nvl(vIsNewBatchID, 0);

*/



  when others then

    --

    -- rollback then log error to AX_LOG table then return batch number

    -- 

--    v_step := 340;

  

    rollback;  

    ax_pkg.LogEvent_P(trim('AR_DEPT_PKG')||'.ar_create_dept_txs_p', trim(sqlerrm)||' (Error at step '||v_step||')'); -- AX-39259

    pBatchID := nvl(vReturnBatch, 0);

    pIsNewBatchID := nvl(vIsNewBatchID, 0);

    

end ar_create_dept_txs_p;



END;
CREATE OR REPLACE PACKAGE BODY arasat_pkg IS

-- ARASAT Function
FUNCTION arasat(asatdate timestamp without time zone) RETURN numeric IS
  AR NUMBER := 0;
  ArchAmt NUMBER := 0;																	--AX-23922d
  GoodAuditDate DATE;

BEGIN

 BEGIN
   SELECT "AuditDate" INTO GoodAuditDate FROM Tx_Audit;
 EXCEPTION
   WHEN NO_DATA_FOUND THEN
    GoodAuditDate := sysdate;
 END;

 IF AsAtDate>=GoodAuditDate THEN
   BEGIN
     SELECT SUM(H."Total") INTO AR
      FROM HISTORY H WHERE H."Type" IN (1,2,3,6,7,74) AND H."HistoryType"<10 AND H."Family"!=0
      AND H."TreatmentDate"<=AsAtDate AND H."Deleted"=0 AND H."OrthoStatus"<>1 AND
      H."History"=(SELECT max(H2."History") FROM HISTORY H2 WHERE H2."OrigRecNo"=H."OrigRecNo"
      AND H2."Type" = H."Type" AND trunc(H2."ModifiedDate")<=AsAtDate);
   EXCEPTION
     WHEN NO_DATA_FOUND THEN
       AR := 0;
   END;
 ELSE
   BEGIN
     SELECT SUM(H."Total") INTO AR
      FROM AR_ASOF H WHERE H."Type" IN (1,2,3,6,7,74) AND H."Family"!=0
      AND H."TreatmentDate"<=AsAtDate;
   EXCEPTION
     WHEN NO_DATA_FOUND THEN
       AR := 0;
   END;
 END IF;

 IF AR IS NULL THEN
   AR := 0;
 END IF;

 --AX-23922d
   BEGIN
	 SELECT SUM(A."ArchivedAmt") INTO ArchAmt
      FROM TRXARCHAMT A WHERE A."Type" = 3;
   EXCEPTION
     WHEN NO_DATA_FOUND THEN
       ArchAmt := 0;
   END;

	IF ArchAmt IS NULL THEN
		ArchAmt := 0;
	END IF;

	AR := AR - ArchAmt;

 RETURN AR;
END;

-- ARASAT_I Function
-- 12/23/2002 created to report on all financial activity including held ins pmts
FUNCTION arasat_i(asatdate timestamp without time zone) RETURN numeric IS
  AR NUMBER := 0;
  ArchAmt NUMBER := 0;																	--AX-23922d
  GoodAuditDate DATE;

BEGIN

 BEGIN
   SELECT "AuditDate" INTO GoodAuditDate FROM Tx_Audit;
 EXCEPTION
   WHEN NO_DATA_FOUND THEN
    GoodAuditDate := sysdate;
 END;

 IF AsAtDate>=GoodAuditDate THEN
   BEGIN
     SELECT SUM(H."Total") INTO AR
      FROM HISTORY H WHERE H."Type" IN (1,2,3,4,6,7) AND H."HistoryType"<10 AND
      (H."Family"!=0 OR H."Type" IN (4,7))
      AND H."TreatmentDate"<=AsAtDate AND H."Deleted"=0 AND H."OrthoStatus"<>1 AND
      H."History"=(SELECT max(H2."History") FROM HISTORY H2 WHERE H2."OrigRecNo"=H."OrigRecNo"
      AND H2."Type" = H."Type" AND trunc(H2."ModifiedDate")<=AsAtDate);
   EXCEPTION
     WHEN NO_DATA_FOUND THEN
       AR := 0;
   END;
 ELSE
   BEGIN
     SELECT SUM(H."Total") INTO AR
      FROM AR_ASOF H WHERE H."Type" IN (1,2,3,4,6,7) AND
      (H."Family"!=0 OR H."Type" IN (4,7)) AND H."TreatmentDate"<=AsAtDate;
   EXCEPTION
     WHEN NO_DATA_FOUND THEN
       AR := 0;
   END;
 END IF;

 IF AR IS NULL THEN
   AR := 0;
 END IF;

	
	 --AX-23922d
   BEGIN
	 SELECT SUM(A."ArchivedAmt") INTO ArchAmt
      FROM TRXARCHAMT A WHERE A."Type" IN (3, 4);
   EXCEPTION
     WHEN NO_DATA_FOUND THEN
       ArchAmt := 0;
   END;

	IF ArchAmt IS NULL THEN
		ArchAmt := 0;
	END IF;

	AR := AR - ArchAmt;

 RETURN AR;
END;

END;
CREATE OR REPLACE PACKAGE BODY archive_pkg IS

-- AX-24111
PROCEDURE setdisabletriggers(IN ndisableflag numeric) IS
BEGIN

	v_nDisableTriggersFlag := nDisableFlag;

END SetDisableTriggers;


-- AX-24111
FUNCTION getdisabletriggersflag() RETURN numeric IS
BEGIN

	RETURN v_nDisableTriggersFlag;

END GetDisableTriggersFlag;
	

-- AX-24047.24059
PROCEDURE makepathisentry(IN npatientid numeric, IN nauditid numeric, IN cstatus character varying) IS
	vpathisrow		pathis%rowtype;
	
BEGIN
		--AX-24090x
		BEGIN		
			select * into vpathisrow from pathis where
					pathis."Patient" = nPatientId order by 1 desc FETCH FIRST 1 ROWS ONLY;
		EXCEPTION
		WHEN NO_DATA_FOUND THEN
			RETURN;
		END;

		vpathisrow."Id" := pathis_id_seq.nextval;
		vpathisrow."Audit" := nAuditId;
		vpathisrow."PtStatusFlag" := 1;
		vpathisrow."Status" := cStatus;
		insert into pathis values vpathisrow;

END MakePatHisEntry;


/*****************************************************************************/
END;
CREATE OR REPLACE PACKAGE BODY auditlog_pkg IS



PROCEDURE setlogparameters(IN nsecurelog numeric, IN nuserid numeric, IN nstationid numeric, IN csecretkey character varying, IN capplication character varying, OUT nsessioninit numeric) IS

BEGIN



	v_nSecureLog := nSecureLog;

	v_nUserId := nUserId;

	v_nStationId := nStationId;

	v_cSecretKey := cSecretKey;

	v_cApplication := cApplication;				-- E143149.js5

	

	-- B142694 (E141297.drb20) - return session init flag, then set it to indicate the session is not new

	nSessionInit := v_nSessionInit;

	v_nSessionInit := 1;

	

END SetLogParameters;



--E143149.jsx (to be taken out eventually!!!)

PROCEDURE setlogparameters(IN nsecurelog numeric, IN nuserid numeric, IN nstationid numeric, IN csecretkey character varying, OUT nsessioninit numeric) IS

BEGIN



	v_nSecureLog := nSecureLog;

	v_nUserId := nUserId;

	v_nStationId := nStationId;

	v_cSecretKey := cSecretKey;

	v_cApplication := 'axiUm';

	

	nSessionInit := v_nSessionInit;

	v_nSessionInit := 1;

	

END SetLogParameters;



FUNCTION getsecurelog() RETURN numeric IS

BEGIN

	RETURN v_nSecureLog;

END GetSecureLog;

	

	

FUNCTION getuserid() RETURN numeric IS

BEGIN

	RETURN v_nUserId;

END GetUserId;

	

FUNCTION getstationid() RETURN numeric IS

BEGIN

	RETURN v_nStationId;

END GetStationId;

	

	

FUNCTION getsecretkey() RETURN character varying IS 

BEGIN

	RETURN v_cSecretKey;

END GetSecretKey;





--E143149.js5

FUNCTION getapplicationstring() RETURN character varying IS

BEGIN

	RETURN v_cApplication;

END GetApplicationString;

	



FUNCTION gethashvalue(npatientid numeric, ddate timestamp without time zone, nuser numeric, nstation numeric, nactiontype numeric, ctablename character varying, cprimaryinfo character varying, cadditionalinfo character varying, csecretkey character varying) RETURN character varying IS	

	cData		VARCHAR2(2000);

	rawDataIn BYTEA;

	rawDataKey BYTEA;

	rawDataOut BYTEA;

	rawDataOut2 BYTEA;

    	cEncrypted TEXT;

	cResult VARCHAR2(45) := ' ';

BEGIN

	cData := TRIM(TO_CHAR(nPatientId)) 

				|| TRIM(TO_CHAR(dDate, 'YYYYMMDDHH24MISS'))

				|| TRIM(TO_CHAR(nUser)) 

				|| TRIM(TO_CHAR(nStation)) 

				|| TRIM(TO_CHAR(nActionType)) 

				|| cTableName

				|| cPrimaryInfo

				|| cAdditionalInfo;

			

	rawDataIn := convert_to(cData, 'ISO_8859_1');

	rawDataKey := convert_to(cSecretKey, 'ISO_8859_1');

	rawDataOut := hmac(rawDataIn, rawDataKey, 'sha1');

	rawDataOut2 := encode(rawDataOut, 'base64');

	cEncrypted := convert_from(rawDataOut2::bytea, 'ISO_8859_1');		

	

	--select encode(pgp_sym_encrypt(cData,cSecretKey),'BASE64') INTO cEncrypted;

	cResult := SUBSTRING(cEncrypted, 1, 45);



	RETURN cResult;

	

END GetHashValue;

	

PROCEDURE insertauditlog(IN npatientid numeric, IN nactiontype numeric, IN ctablename character varying, IN cprimaryinfo character varying, IN cadditionalinfo character varying) IS 

--	tsTimeStamp		TIMESTAMP := systimestamp;

--	dtDate			DATE := TO_DATE(TO_CHAR(tsTimeStamp, 'YYYY-MON-DD HH24:MI:SS'), 'YYYY-MON-DD HH24:MI:SS');

--	nMilliSec		NUMBER(10) := TO_NUMBER(TO_CHAR(tsTimeStamp, 'FF'));

	dtDate			DATE;

	nMilliSec		NUMBER(5);																		--E135970.21

	

BEGIN



	--E135970.21

	SELECT TO_DATE(TO_CHAR(systimestamp, 'YYYY-MON-DD HH24:MI:SS'), 'YYYY-MON-DD HH24:MI:SS'), 

					MOD(EXTRACT(second from systimestamp), 1)*1000 INTO dtDate, nMilliSec FROM DUAL;

	

   INSERT INTO AUDITLOG

    (

      "Patient"             ,

      "Date"                ,

      "User"					 ,

      "Station"             ,

      "ActionType"          ,

      "TableName"           ,

      "PrimaryInfo"         ,

      "AdditionalInfo"      ,

      "HashValue"				 ,

      "SecondarySortKey",

-- AX-18069.19112

      "Auditlog"

    )

    VALUES

    (

      nPatientId				,

      dtDate		         ,

      GetUserId()				, 

      GetStationId()			,

		nActionType				,

		cTableName				,

		cPrimaryInfo			,

		cAdditionalInfo		,

      GetHashValue(

			nPatientId,

			dtDate,

			GetUserId(),

			GetStationId(),

			nActionType,

			cTableName,

			cPrimaryInfo,

			cAdditionalInfo,

			GetSecretKey()

      )							,

      nMilliSec,

-- AX-18069.19112

      AUDITLOG_AUDITLOG_SEQ.nextval

    );

	EXCEPTION

		WHEN OTHERS THEN

			RETURN;



END InsertAuditLog;



--E135970.16 added

FUNCTION getappointdescription(nappttype numeric) RETURN character varying IS 

	szResult		 VARCHAR2(255);

	szSubType	 VARCHAR2(81);

BEGIN

	IF ( nApptType = 8 ) THEN

		szResult := 'Patient Appointment Request';

	ELSIF ( nApptType = 9 ) THEN

		szResult := 'Patient Ortho Appointment Request';

	ELSIF ( nApptType = 10 ) THEN

		szResult := 'Patient Planned Appointment';

	ELSE 

		if ( nApptType = 7 ) THEN

			szSubType := 'Deleted';

		ELSIF ( nApptType = 6 ) THEN

			szSubType := 'Cancelled';

		ELSIF ( nApptType = 5 ) THEN

			szSubType := 'Failed';

		ELSIF ( nApptType = 4 ) THEN

			szSubType := 'Rescheduled';

		ELSIF ( nApptType = 3 ) THEN

			szSubType := 'Pending';

		ELSIF ( nApptType = 2 ) THEN

			szSubType := 'Checked-out';

		ELSIF ( nApptType = 1 ) THEN

			szSubType := 'Checked-in';

		ELSE -- ( nApptType = 0 )

			szSubType := 'Active';

		END IF;

		szResult := 'Patient Appointment' || ' (' || szSubType || ')';

	END IF;

	

	RETURN szResult;

	

END GetAppointDescription;

	

--E135970.16 added

FUNCTION getappointadditionalinfo(szcode character varying, szreason character varying, nappttype numeric, ddate timestamp without time zone, nfrom numeric) RETURN character varying IS 

	szResult		 VARCHAR2(255) := '';

BEGIN



	szResult := TRIM(szCode);

	IF ( NOT (TRIM(szReason) IS NULL OR length(TRIM(szReason)) = 0) )  THEN

		szResult := szResult || ' - ' || TRIM(szReason);

	END IF;



	IF ( nApptType <> 4 and nApptType <> 10 ) THEN

			szResult := szResult || ' ' || TRIM(TO_CHAR(dDate, 'MON DD,YYYY'));				--B142155

			IF nFrom > 0 THEN

				szResult := szResult || ' ' || TRIM(TO_CHAR(FLOOR(nFrom/60),'09')) || ':' ||  TRIM(TO_CHAR(MOD(nFrom,60),'09'));

			END IF;

	END IF;

	

	RETURN szResult;

	

END GetAppointAdditionalInfo;



--E135970.17 added

FUNCTION gettrxdescription(ntrxtype numeric, ntrxid numeric, sztrxstatus character varying, nplantotal numeric) RETURN character varying IS 

	szResult		 VARCHAR2(255) := '';

BEGIN

	IF ( nTrxType = 1 ) THEN

		szResult := 'Treatment';

		IF ( TRIM(szTrxStatus) = 'C' ) THEN

			szResult := szResult || ' (Complete)';

		ELSE

			szResult := szResult || ' (In Process)';

		END IF;

	ELSIF ( nTrxType = 5 ) THEN

		szResult := 'Planned Treatment';

	ELSIF ( nTrxType = 2 ) THEN

		if ( nPlanTotal > 0 ) THEN

			szResult := 'Pre-payment';

		ELSE

			szResult := 'Office Charge';

		END IF;

	ELSIF ( nTrxType = 3 ) THEN

		szResult := 'Pt Payment';

	ELSIF ( nTrxType = 73 ) THEN

		szResult := 'Payment Allocation';

	ELSIF ( nTrxType = 6 ) THEN

		szResult := 'Pt Adjustment';

	ELSIF ( nTrxType = 7 ) THEN

		szResult := 'Ins Adjustment';

	ELSIF ( nTrxType = 74 ) THEN

		szResult := 'Ins Payment Allocation';

	END IF;



	--E135970.18; E135970.23 decided not to include id

	--if ( NOT (TRIM(szResult) IS NULL OR length(TRIM(szResult)) = 0) ) THEN

   --		szResult := szResult || ' #' || TRIM(TO_CHAR(nTrxId));

	--END IF;

	

	RETURN szResult;

	

END GetTrxDescription;





--E135970.19 added

FUNCTION gettreatme2description(nstatus numeric) RETURN character varying IS 

	szResult		 VARCHAR2(255) := '';

BEGIN



	IF ( nStatus = 0 ) THEN

		szResult := 'Clinical Tx (Complete)';

	ELSIF ( nStatus = 1 ) THEN

		szResult := 'Clinical Tx (In Process)';

	ELSIF ( nStatus = 2 ) THEN

		szResult := 'Clinical Tx (Plan)';

	ELSIF ( nStatus = 3 ) THEN

		szResult := 'Pre-existing Tx';

	ELSIF ( nStatus = 4 ) THEN

		szResult := 'Conditions';

	ELSIF ( nStatus = 5 ) THEN

		szResult := 'Ortho Visit';

	END IF;



	RETURN szResult;

	

END GetTreatme2Description;



--E135970.19 added

FUNCTION gettreatme2additionalinfo(nstatus numeric, ncodeid numeric, ndays numeric, nsite numeric, nsite2 numeric, nsurfaces numeric) RETURN character varying IS 

	szResult		 VARCHAR2(255) := '';

BEGIN



	--E135970.23; swapped the order

	IF nStatus <> 2 THEN

		szResult := TREATME2_PKG.DISPLAY_DATE(nDays) || ' ' ;

	END IF;

	

	szResult := szResult || TRIM( TREATME2_PKG.DISPLAY_CODE(nCodeId));

	

	IF nSite <> 0 THEN

		szResult := szResult || ' ' || TREATME2_PKG.DISPLAY_SITE(nSite);

		IF nSite2 <> 0 THEN

			szResult := szResult || ' - ' || TREATME2_PKG.DISPLAY_SITE(nSite2);

		END IF;

	END IF;

	IF nSurfaces <> 0 THEN

		szResult := szResult || ' ' || TREATME2_PKG.DISPLAY_SURFACE(nSite, nSurfaces);

	END IF;



	RETURN szResult;



END GetTreatme2AdditionalInfo;



FUNCTION getnotes2description(ntype numeric, nsection numeric) RETURN character varying IS 

	szResult		 VARCHAR2(255) := '';

BEGIN



	IF ( nType = 0 ) THEN

		szResult := 'General Note';

	ELSIF ( nType = 1 ) THEN

		szResult := 'Tx Note';

	ELSIF ( nType = 2 ) THEN

		szResult := 'Lab Note';

	ELSIF ( nType = 3 ) THEN

		szResult := 'Ortho Note';

	ELSIF ( nType = 4 ) THEN

		szResult := 'Soap Note';

		IF ( nSection = 0 ) THEN

			szResult := szResult || ' (Subjective)';

		ELSIF ( nSection = 1 ) THEN

			szResult := szResult || ' (Objective)';

		ELSIF ( nSection = 2 ) THEN

			szResult := szResult || ' (Assessment)';

		ELSIF ( nSection = 3 ) THEN

			szResult := szResult || ' (Planned)';

		END IF;

	ELSIF ( nType = 5 ) THEN

		szResult := 'Rx Note';

	END IF;



	RETURN szResult;

	

END GetNotes2Description;



--E135970.20 added

FUNCTION getpformdescription(nownertype numeric) RETURN character varying IS 

	szResult		 VARCHAR2(255) := '';

BEGIN



	IF ( nOwnerType = 0 ) THEN

		szResult := 'Patient EPR/Ortho Form';

	ELSIF ( nOwnerType = 1 ) THEN

		szResult := 'Patient Lab Order Form';

	ELSIF ( nOwnerType = 2 ) THEN

		szResult := 'Patient Referral Form';

	ELSIF ( nOwnerType = 3 ) THEN

		szResult := 'Patient Provider Form';

	ELSIF ( nOwnerType = 4 ) THEN

		szResult := 'Patient Clincial Tx Form';

	ELSIF ( nOwnerType = 5 ) THEN

		szResult := 'User Form';

	ELSIF ( nOwnerType = 6 ) THEN

		szResult := 'Patient Clinical Note Form';

	END IF;



	RETURN szResult;

	

END GetPFormDescription;



-- E135970.22

FUNCTION getapnotedescription(napnotetype numeric) RETURN character varying IS 

	szResult	 VARCHAR2(255);

BEGIN

	IF ( nApNoteType = 0 ) THEN

		szResult := 'Appointment Note';

	ELSIF ( nApNoteType = 3 ) THEN

		szResult := 'Patient Note';

	ELSIF ( nApNoteType = 4 ) THEN

		szResult := 'Patient Treatment Note';

	ELSIF ( nApNoteType = 5 ) THEN

		szResult := 'General Treatment Note';

	ELSIF ( nApNoteType = 6 ) THEN

		szResult := 'Treatment Note';

	ELSIF ( nApNoteType = 7 ) THEN

		szResult := 'Planned Treatment Note';

	ELSIF ( nApNoteType = 8 ) THEN

		szResult := 'Office Charge Note';

	ELSIF ( nApNoteType = 9 ) THEN

		szResult := 'Payment Note';

	ELSIF ( nApNoteType = 10 ) THEN

		szResult := 'Adjustment Note';

	ELSE

		szResult := '';

	END IF;

	

	RETURN szResult;

	

END GetApNoteDescription;





-- E135970.22

FUNCTION getapnotepatid(napnotetype numeric, napnotetreatment numeric, napnotepatid numeric, napnoteappid numeric) RETURN numeric IS

	nId	NUMBER := 0;

BEGIN



   IF (nApNoteType = 0 OR ((nApNoteType = 6 OR nApNoteType = 7 OR nApNoteType = 8 OR nApNoteType = 9 OR nApNoteType = 10) AND nApNoteTreatment > 0)) THEN

		nId := nApNotePatId;

	ELSIF (nApNoteType = 3 OR nApNoteType = 4 OR nApNoteType = 5) THEN

		nId := nApNoteAppId;

	END IF;



	RETURN nId;

	

END GetApNotePatId;





-- E135970.22

FUNCTION getpthistdescription(ntype numeric, nrecid numeric) RETURN character varying IS 

	szResult			 VARCHAR2(255) := '';

	v_Treatme2Data	TREATME2%ROWTYPE;

	v_Notes2Data	NOTES2%ROWTYPE;

	v_AppointData	APPOINT%ROWTYPE;

BEGIN

   IF (nType = 0) THEN -- Treatment

		BEGIN

			SELECT * INTO v_Treatme2Data FROM TREATME2 WHERE "Auto" = nRecId;

 			EXCEPTION WHEN NO_DATA_FOUND THEN

				v_Treatme2Data."Auto" := 0;

 		END; 

		

		IF (v_Treatme2Data."Auto" > 0) THEN

			szResult := GetTreatme2Description(v_Treatme2Data."Status");

		END IF;

	ELSIF (nType = 1) THEN -- Note

		BEGIN

			SELECT * INTO v_Notes2Data FROM NOTES2 WHERE "Auto" = nRecId;

 			EXCEPTION WHEN NO_DATA_FOUND THEN

				v_Notes2Data."Auto" := 0;

 		END; 

		

		IF (v_Notes2Data."Auto" > 0) THEN

			szResult := GetNotes2Description(v_Notes2Data."Type", v_Notes2Data."SectionNo");

		END IF;

	ELSIF (nType = 2) THEN -- Appointment

		BEGIN

			SELECT * INTO v_AppointData FROM APPOINT WHERE "Appointment" = nRecId;

 			EXCEPTION WHEN NO_DATA_FOUND THEN

				v_AppointData."Appointment" := 0;

 		END; 



		IF (v_AppointData."Appointment" > 0) THEN

			szResult := GetAppointAdditionalInfo(v_AppointData."Code", v_AppointData."Reason", v_AppointData."Type", v_AppointData."Date", v_AppointData."From");

		END IF;

		

	ELSE -- nType = 3

		 szResult := 'Patient Recall';

	END IF;

	

	RETURN szResult;

	

END GetPtHistDescription;



-- E135970.22

FUNCTION getpthistinfo(ntype numeric, nrecid numeric) RETURN character varying IS 

	szResult			 VARCHAR2(255) := '';

	v_Treatme2Data	TREATME2%ROWTYPE;

	v_Notes2Data	NOTES2%ROWTYPE;

	v_AppointData	APPOINT%ROWTYPE;

	v_PtRecallData	PTRECALL%ROWTYPE;

BEGIN

   IF (nType = 0) THEN -- Treatment

		BEGIN

			SELECT * INTO v_Treatme2Data FROM TREATME2 WHERE "Auto" = nRecId;

 			EXCEPTION WHEN NO_DATA_FOUND THEN

				v_Treatme2Data."Auto" := 0;

 		END; 

		

		IF (v_Treatme2Data."Auto" > 0) THEN

			szResult := GetTreatme2AdditionalInfo(v_Treatme2Data."Status", v_Treatme2Data."CodeId", v_Treatme2Data."Days", v_Treatme2Data."Site", v_Treatme2Data."Site2", v_Treatme2Data."Surface");

		END IF;

	ELSIF (nType = 1) THEN -- Note

		BEGIN

			SELECT * INTO v_Notes2Data FROM NOTES2 WHERE "Auto" = nRecId;

 			EXCEPTION WHEN NO_DATA_FOUND THEN

				v_Notes2Data."Auto" := 0;

 		END; 

		

		IF (v_Notes2Data."Auto" > 0) THEN

			IF (LENGTH(TRIM(v_Notes2Data."Text")) < 50) THEN

				szResult := TRIM(v_Notes2Data."Text");

			ELSE

				szResult := RPAD(v_Notes2Data."Text", 50) || '...';

			END IF;

		END IF;

	ELSIF (nType = 2) THEN -- Appointment

		BEGIN

			SELECT * INTO v_AppointData FROM APPOINT WHERE "Appointment" = nRecId;

 			EXCEPTION WHEN NO_DATA_FOUND THEN

				v_AppointData."Appointment" := 0;

 		END; 



		IF (v_AppointData."Appointment" > 0) THEN

			szResult := GetAppointAdditionalInfo(v_AppointData."Code", v_AppointData."Reason", v_AppointData."Type", v_AppointData."Date", v_AppointData."From");

		END IF;

	ELSE -- (nType = 3) THEN -- Recall

		BEGIN

			SELECT * INTO v_PtRecallData FROM PTRECALL WHERE "Id" = nRecId;

 			EXCEPTION WHEN NO_DATA_FOUND THEN

				v_PtRecallData."Id" := 0;

 		END; 

	

		IF (v_PtRecallData."Id" > 0) THEN

			szResult := TRIM(v_PtRecallData."RecallType") ||  ' - ' || TRIM(v_PtRecallData."Recall") || ' - ' || TRIM(TO_CHAR(v_PtRecallData."RecallDate", 'MON D,YYYY'));

		END IF;

	END IF;

	

	RETURN szResult;

	

END GetPtHistInfo;



-- E136724

FUNCTION getiuserpatid(niuserid numeric) RETURN numeric IS

	nId	NUMBER := 0;

BEGIN



	BEGIN

		SELECT "Patient" INTO nId FROM MSG_ALLUSERS_VIEW WHERE "User" = niUserId;

		EXCEPTION WHEN NO_DATA_FOUND THEN

			nId := 0;

	END; 



	RETURN nId;

	

END GetiUserPatId;



-- E136724

FUNCTION getiuserinfo(niuserid numeric) RETURN character varying IS 

	szResult 	 VARCHAR2(255) := '';

	v_Data		MSG_ALLUSERS_VIEW%ROWTYPE;

BEGIN



	BEGIN

		SELECT * INTO v_Data FROM MSG_ALLUSERS_VIEW WHERE "User" = niUserId;

		EXCEPTION WHEN NO_DATA_FOUND THEN

			v_Data."User" := 0;

	END; 



	IF (v_Data."User" > 0) THEN

		szResult := v_Data."Name" || ', ' || v_Data."First";

	END IF;



	RETURN szResult;

	

END GetiUserInfo;



-- B142339

FUNCTION getindicatordescription(nindicatid numeric) RETURN character varying IS 

	szResult 	 VARCHAR2(255) := '';

	v_Data		INDICAT%ROWTYPE;

BEGIN



	BEGIN

		SELECT * INTO v_Data FROM INDICAT WHERE "Indicat" = nIndicatId;

		EXCEPTION WHEN NO_DATA_FOUND THEN

			v_Data."Indicat" := 0;

	END; 



	IF (v_Data."Indicat" > 0) THEN

		szResult := v_Data."Description";

	END IF;



	RETURN szResult;

	

END GetIndicatorDescription;



-- B142339

FUNCTION getindlogstate(nstate numeric) RETURN character varying IS 

	szResult 	 VARCHAR2(255) := '';

BEGIN



	IF (nState = 1) THEN

		szResult := 'Detected - ';

	ELSIF (nState = 2) THEN

		szResult := 'Displayed - ';

	ELSIF (nState = 3) THEN

		szResult := 'Dismissed - ';

	ELSE

		szResult := '';

	END IF;



	RETURN szResult;

	

END GetIndlogState;



-- B142339

FUNCTION getindlogseverity(nseverity numeric) RETURN character varying IS 

	szResult 	 VARCHAR2(255) := '';

BEGIN



	IF (nSeverity = 0) THEN

		szResult := 'Mild';

	ELSIF (nSeverity = 1) THEN

		szResult := 'Moderate';

	ELSIF (nSeverity = 2) THEN

		szResult := 'Severe';

	ELSE

		szResult := '';

	END IF;



	RETURN szResult;

	

END GetIndlogSeverity;



-- E142678.grt3

FUNCTION getptlinfotype(ntype numeric) RETURN character varying IS 

	szResult 	 VARCHAR2(255) := '';

BEGIN



	IF (nType = 0) THEN

		szResult := 'Import';

	ELSIF (nType = 1) THEN

		szResult := 'Export';

	ELSIF (nType = 2) THEN

		szResult := 'Reconciled';

	ELSE

		szResult := '';

	END IF;



	RETURN szResult;

	

END GetPtLInfoType;





-- AX-14733.16052

FUNCTION getosvitmonaudituser(nptvital numeric, naudit numeric) RETURN character varying IS 

	szResult 	 VARCHAR2(255) := '';

	v_PtVitalData	PTVITAL%ROWTYPE;

	v_nUser		NUMBER;

	v_szDesc 	 VARCHAR2(30) := '';

BEGIN



	BEGIN

		SELECT * INTO v_PtVitalData FROM PTVITAL WHERE "PtVital" = nPtVital;

 			EXCEPTION WHEN NO_DATA_FOUND THEN

				v_PtVitalData."PtVital" := 0;

	END; 

	IF (v_PtVitalData."PtVital" <> 0) THEN

		IF (v_PtVitalData."EntryMode" = 0) THEN   -- manual entry; show user name

			BEGIN

				SELECT "User" INTO v_nUser FROM AUDITHIS WHERE "Audit" = nAudit;

 					EXCEPTION WHEN NO_DATA_FOUND THEN

						v_nUser := 0;

			END; 

			szResult := GetiUserInfo(v_nUser);

		ELSE   -- EntryMode = 1 (timer), 2 - (spot check)

			BEGIN

				SELECT "Description" INTO v_szDesc FROM OSVITMON WHERE "VitMon" = v_PtVitalData."VitMon";

 					EXCEPTION WHEN NO_DATA_FOUND THEN

						v_szDesc := ' ';

			END; 

			szResult := TRIM(v_PtVitalData."VitMon") || ' - ' || v_szDesc;

		END IF;

	END IF;





	RETURN szResult;

	

END GetOSVitMonAuditUser;



-- AX-18069.19112 

FUNCTION ishashvalid(npatientid numeric, crowid character varying, csecretkey character varying) RETURN numeric IS 

	rowAuditLog AUDITLOG%ROWTYPE;

BEGIN



	SELECT * INTO rowAuditLog FROM AUDITLOG WHERE "Auditlog" = CAST(RPAD(cRowId, 28) AS VARCHAR2(28));	--AX-36498 need casting for EDB



	IF rowAuditLog."HashValue"= GetHashValue(rowAuditLog."Patient",rowAuditLog."Date",rowAuditLog."User",rowAuditLog."Station",rowAuditLog."ActionType",rowAuditLog."TableName",rowAuditLog."PrimaryInfo",rowAuditLog."AdditionalInfo",cSecretKey) THEN

		RETURN 1;

	END IF;

	

	RETURN 0;

	

END IsHashValid;



/*****************************************************************************/

END;
CREATE OR REPLACE PACKAGE BODY ax_appoint_pkg IS



  -- returns information about this package, or its procedures

  PROCEDURE help(IN pobjectname character varying DEFAULT NULL::character varying) IS

    vReturn CLOB;

  begin

    -- Writes the help to the DBMS_OUTPUT

	-- AX-39259

    vReturn := ax_pkg.Help_F('AX_APPOINT_PKG',pObjectName);

  end Help;

  

  PROCEDURE initializeappoint_p(INOUT pvappointrow appoint, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

  vParams ax_pkg.tParams := pParams;

  BEGIN

    ax_pkg.InitializeParams_P(vParams);

    -- Setup

    pvAppointRow."User" := vParams."User";



    -- Set to Default Values

    pvAppointRow."Appointment" := 0;    

    pvAppointRow."Date" := null;

    pvAppointRow."Chair" := 0;

    pvAppointRow."Patient" := 0;

    pvAppointRow."Type" := 0;

    pvAppointRow."Producer" := ' ';

    pvAppointRow."From" := 0;

    pvAppointRow."CreateDate" := trunc(sysdate);

    pvAppointRow."Code" := ' ';

    pvAppointRow."Unit0" := 0;

    pvAppointRow."Unit1" := 0;

    pvAppointRow."Unit2" := 0;

    pvAppointRow."Unit3" := 0;

    pvAppointRow."Unit4" := 0;

    pvAppointRow."Unit5" := 0;

    pvAppointRow."Time0" := 0;

    pvAppointRow."Time1" := 0;

    pvAppointRow."Time2" := 0;

    pvAppointRow."Time3" := 0;

    pvAppointRow."Time4" := 0;

    pvAppointRow."Time5" := 0;

    pvAppointRow."Estimate" := 0;

    pvAppointRow."Class" := ' ';

    pvAppointRow."ModifiedDateTime" := sysdate;

    pvAppointRow."IsRecall" := 0;

    pvAppointRow."IsAsap" := 0;

    pvAppointRow."IsConfirm" := 0;

    pvAppointRow."IsShortNotice" := 0;

    pvAppointRow."Status" := 0;

    pvAppointRow."Request" := 0;

    pvAppointRow."Rank" := 0;

    pvAppointRow."UStatus" := ' ';

    pvAppointRow."Reserve" := 0;

    pvAppointRow."OrthoStage" := ' ';

    pvAppointRow."IsOrtho" := 0;

    pvAppointRow."Cancel" := ' ';

    pvAppointRow."Reason" := '';

    pvAppointRow."Assistant" := ' ';

    pvAppointRow."Clinic" := 0;

    pvAppointRow."IsRequest" := 0;

    pvAppointRow."Instructor" := 0;

    pvAppointRow."IsNew" := 0;

    pvAppointRow."CheckInTime" := 0;

    pvAppointRow."TimeSeated" := 0;

    pvAppointRow."Held" := 0;

    pvAppointRow."SignInTime" := 0;

    pvAppointRow."SecondaryMCBFlag" := 0;

    pvAppointRow."NotBeforeDate" := null;

    pvAppointRow."PtEstimateStatus" := 0;

    pvAppointRow."PtEstimate" := 0;

    pvAppointRow."BookingOrder" := 0;

    pvAppointRow."ExpertAdd" := 0;

    pvAppointRow."CheckOutDate" := null;

    pvAppointRow."CheckOutTime" := 0;

    pvAppointRow."PrimaryExclusive" := 0;

  

  END initializeAppoint_P;





  -- AX-26266 added to validate a given appointment

  FUNCTION isvalidappoint_p(papptid numeric) RETURN boolean IS

      vcounter INT := 0;

  BEGIN

  		SELECT COUNT(1) INTO vcounter from APPOINT where APPOINT."Appointment" = pApptId;

      IF vcounter > 0 THEN

         RETURN true;

      ELSE 

         RETURN false;

      END IF;

  END isValidAppoint_P;



  -- AX-26266 added to validate a given user

  FUNCTION isvaliduser_p(puserid numeric) RETURN boolean IS

      vcounter INT := 0;

  BEGIN

  		SELECT COUNT(1) INTO vcounter from USERS where USERS."User" = pUserId;

      IF vcounter > 0 THEN

         RETURN true;

      ELSE 

         RETURN false;

      END IF;

  END isValidUser_P;



  -- AX-26266 added to validate a given cancellation code

  FUNCTION isvalidcancelcode_p(pcancelcode character varying) RETURN boolean IS

      vcounter INT := 0;

  BEGIN

      SELECT COUNT(1) INTO vcounter from CANCEL where TRIM(CANCEL."Cancel") = TRIM(pCancelCode);	--AX-26400

      IF vcounter > 0 THEN

         RETURN true;

      ELSE 

         RETURN false;

      END IF;

  END isValidCancelCode_P;



  -- AX-26266 added to validate a given status code; blank is OK

  FUNCTION isvalidstatuscode_p(pstatuscode character varying) RETURN boolean IS

      vcounter INT := 0;

  BEGIN

      IF pStatusCode IS NULL THEN

         RETURN true;

      END IF;



      SELECT COUNT(1) INTO vcounter from STATUS where TRIM(STATUS."Status") = TRIM(pStatusCode);	--AX-26400	

      IF vcounter > 0 THEN

         RETURN true;

      ELSE 

         RETURN false;

      END IF;

  END isValidStatusCode_P;



  -- AX-26266 added to cancel a given appointment

  FUNCTION cancelappoint_p(papptid numeric, puserid numeric, pcancelcode character varying, prclstatusunsch character varying DEFAULT NULL::character varying) RETURN boolean IS

      vAuditId NUMBER;

  BEGIN



      -- validate the pass in information are valid

      IF (NOT isValidAppoint_P(pApptId) OR NOT isValidUser_P(pUserId)

            OR NOT isValidCancelCode_P(pCancelCode)

            OR NOT isValidStatusCode_P(pRclStatusUnSch)) THEN 

         RETURN false;

      END IF;



      -- cancel the appointment as requested

		UPDATE APPOINT SET APPOINT."Type" = 6,

            APPOINT."Cancel" = pCancelCode,

		      APPOINT."User" = pUserId,

		      APPOINT."ModifiedDateTime" = sysdate

		   WHERE APPOINT."Appointment" = pApptId;



      -- delete the reservation record if applicable

      DELETE FROM RESERVE WHERE RESERVE."Appointment" = pApptId;



      -- delete the chart request tied to the given appointment

      DELETE FROM REQUEST WHERE REQUEST."Request" = 

         (SELECT APPOINT."Request" FROM APPOINT WHERE appoint."Appointment" = pApptId); 



      -- create appropriate audithis entry

      SELECT audithis_audit_seq.nextval into vAuditId from dual;

		INSERT INTO audithis values(

            vAuditId,

				trunc(sysdate),

				to_number ( to_char ( sysdate, 'HH24' ) ) * 60 + to_number ( to_char ( sysdate, 'MI' ) ),

				pUserId,

				0,

				'PTRECALL',

				2);



      -- update appropriate patient recall records

      if pRclStatusUnSch IS NULL THEN

         UPDATE PTRECALL SET PTRECALL."ApptDate" = CAST(NULL AS DATE),

               PTRECALL."Booked" = 0,

               PTRECALL."Audit" = vAuditId

            WHERE PTRECALL."Id" IN (SELECT APPTRECL."PtRecall" FROM APPTRECL WHERE APPTRECL."Appointment" = pApptId)

               AND PTRECALL."Deleted" = 0;

      ELSE

         UPDATE PTRECALL SET PTRECALL."Status" = pRclStatusUnSch,

               PTRECALL."ApptDate" = CAST(NULL AS DATE),

               PTRECALL."Booked" = 0,

               PTRECALL."Audit" = vAuditId

            WHERE PTRECALL."Id" IN (SELECT APPTRECL."PtRecall" FROM APPTRECL WHERE APPTRECL."Appointment" = pApptId)

               AND PTRECALL."Deleted" = 0;

      END IF;



      RETURN true;



  END cancelAppoint_P;



  -- AX-26266 added to confirm a given appointment

  FUNCTION confirmappoint_p(papptid numeric, puserid numeric) RETURN boolean IS 

  BEGIN



      -- validate the pass in information are valid

      IF (NOT isValidAppoint_P(pApptId) OR NOT isValidUser_P(pUserId)) THEN 

         RETURN false;

      END IF;

      

      -- confirm the appointment as requested

		UPDATE APPOINT SET APPOINT."IsConfirm" = 1,

		      APPOINT."User" = pUserId,

		      APPOINT."ModifiedDateTime" = sysdate

		   WHERE APPOINT."Appointment" = pApptId;



      RETURN true;



  END confirmAppoint_P;





END;
CREATE OR REPLACE PACKAGE BODY ax_assign_pkg IS



  -- returns information about this package, or its procedures

  PROCEDURE help(IN pobjectname character varying DEFAULT NULL::character varying) IS

    vReturn CLOB;

  begin

    -- Writes the help to the DBMS_OUTPUT

	-- AX-39259

    vReturn := ax_pkg.Help_F('AX_ASSIGN_PKG',pObjectName);

  end Help;





  PROCEDURE initializeptprod_p(INOUT pvptprodrow ptprod, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    -- Setup

    pvPtProdRow."Id" := 0;

    pvPtProdRow."User" := nvl(pvPtProdRow."User",vParams."User");

    pvPtProdRow."StationId" := nvl(pvPtProdRow."StationId",vParams."StationId");

     

    -- Set to Default Values  

    pvPtProdRow."Patient" := 0;

    pvPtProdRow."Producer" := ' ';

    pvPtProdRow."StartDate" := trunc(sysdate);

    pvPtProdRow."EndDate" := trunc(current_date) + 365.25;

    pvPtProdRow."IsRestricted" := 0;

    pvPtProdRow."IsPrimary" := 0;

    pvPtProdRow."Discipline" := ' ';

    pvPtProdRow."NeedReq" := 0;

    pvPtProdRow."CreateDate" := trunc(sysdate);

    pvPtProdRow."Deleted" := 0;

    pvPtProdRow."Note" := ' ';

  end InitializePtProd_P;

  



  PROCEDURE initializeptmanage_p(INOUT pvptmanagerow ptmanage, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

  --Setup Default

    pvPtManageRow."Patient" := 0;

    pvPtManageRow."User" := 0;

    pvPtManageRow."IsPrimary" := 0;

    pvPtManageRow."CreateDate" := trunc(sysdate);

    pvPtManageRow."AuditUser" := vParams."User";

    pvPtManageRow."StationId" := vParams."StationId";

    pvPtManageRow."Deleted" := 0; 

  end InitializePtManage_P;

 

 

  PROCEDURE initializeptfacul_p(INOUT pvptfaculrow ptfacul, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

  begin

  --Setup Default

    pvPtFaculRow."PtFacul" := 0;

    pvPtFaculRow."Patient" := 0;

    pvPtFaculRow."Faculty" := 0;

    pvPtFaculRow."Discipline" := ' ';

    pvPtFaculRow."Deleted" := 0;

    pvPtFaculRow."Audit" := 0;

    pvPtFaculRow."IsPrimary" := 0;

  end InitializePtFacul_P;

 

 

  PROCEDURE insertptprod_p(INOUT pvptprodrow ptprod, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN poverride boolean DEFAULT true) IS

    vExists number;

    vOldPtProdRec ptprod%rowtype;    

    exDuplicate exception;

    exNoChange exception;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

   

    begin

      -- Make sure we are not creating a duplicate record

      select *  into vOldPtProdRec from ptprod

      where

        "Patient" = pvPtProdRow."Patient" and

        "Producer" = pvPtProdRow."Producer" and

        ("Discipline" = pvPtProdRow."Discipline" 

        or ((trim(pvPtProdRow."Discipline") is null OR length(trim(pvPtProdRow."Discipline")) = 0) 

        and (trim("Discipline") is null OR length(trim("Discipline")) = 0) )) and

        "Deleted" = 0 and

        (

          (pvPtProdRow."StartDate" >= "StartDate" and pvPtProdRow."StartDate" <= "EndDate") or

          (pvPtProdRow."EndDate" >= "StartDate" and pvPtProdRow."EndDate" <= "EndDate")

        )

      ;

      -- If this is reached, and pOverride is true, we need to update instead of insert  

      if pOverride then 

        -- Take into account the existing data

        pvPtProdRow."StartDate" := least(pvPtProdRow."StartDate",vOldPtProdRec."StartDate");

        pvPtProdRow."EndDate" := greatest(pvPtProdRow."EndDate",vOldPtProdRec."EndDate");

        pvPtProdRow."IsPrimary" := greatest(pvPtProdRow."IsPrimary",vOldPtProdRec."IsPrimary");

        pvPtProdRow."IsRestricted" := greatest(pvPtProdRow."IsRestricted",vOldPtProdRec."IsRestricted");

        pvPtProdRow."NeedReq" := greatest(pvPtProdRow."NeedReq",vOldPtProdRec."NeedReq");

        if (trim(pvPtProdRow."Note") is null OR length(trim(pvPtProdRow."Note")) = 0) then

          pvPtProdRow."Note" := vOldPtProdRec."Note";

        end if;

        pvPtProdRow."Id" := vOldPtProdRec."Id";

   

        -- Make sure that the record has changed

        if 

          pvPtProdRow."IsPrimary" = vOldPtProdRec."IsPrimary" and

          pvPtProdRow."StartDate" = vOldPtProdRec."StartDate" and

          pvPtProdRow."EndDate" = vOldPtProdRec."EndDate" and

          pvPtProdRow."IsRestricted" = vOldPtProdRec."IsRestricted" and

          pvPtProdRow."NeedReq" = vOldPtProdRec."NeedReq" and

          pvPtProdRow."Note" = vOldPtProdRec."Note"

        then       

            raise exDuplicate;

        end if;

        

        -- Now update the record

        update ptprod set row = pvPtProdRow where "Id" = vOldPtProdRec."Id";

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptprod rows updated.',vParams);

         

        -- And insert a history record

        insert into ptprodh values (

          ptprodh_ptprodhistory_seq.nextval, -- PtProdHistory

          pvPtProdRow."Patient",

          pvPtProdRow."Producer",

          trunc(sysdate), -- Date

          2, -- Action

          pvPtProdRow."StartDate",

          pvPtProdRow."EndDate",

          pvPtProdRow."IsRestricted",

          pvPtProdRow."IsPrimary",

          pvPtProdRow."Discipline",

          to_number(to_char(sysdate, 'HH24'))* 60 + to_number(to_char(sysdate, 'MI')), -- Time

          pvPtProdRow."CreateDate",

          pvPtProdRow."User",

          pvPtProdRow."StationId",

          pvPtProdRow."Id",

          pvPtProdRow."Note",

          pvPtProdRow."Deleted"

        );

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptprodh rows inserted.',vParams);

      else

        raise exNoChange;        

      end if;

    exception

      when no_data_found then

        -- Insert new

        if pvPtProdRow."Id" = 0 or pvPtProdRow."Id" is null then

          select ptprod_id_seq.nextval into pvPtProdRow."Id" from dual;

        end if;

        

        insert into ptprod values pvPtProdRow;

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptprod rows inserted.',vParams);

         

        insert into ptprodh values (

          ptprodh_ptprodhistory_seq.nextval, -- PtProdHistory

          pvPtProdRow."Patient",

          pvPtProdRow."Producer",

          trunc(sysdate), -- Date

          0, -- Action

          pvPtProdRow."StartDate",

          pvPtProdRow."EndDate",

          pvPtProdRow."IsRestricted",

          pvPtProdRow."IsPrimary",

          pvPtProdRow."Discipline",

          to_number(to_char(sysdate, 'HH24'))* 60 + to_number(to_char(sysdate, 'MI')), -- Time

          pvPtProdRow."CreateDate",

          pvPtProdRow."User",

          pvPtProdRow."StationId",

          pvPtProdRow."Id",

          pvPtProdRow."Note",

          pvPtProdRow."Deleted"

        );

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptprodh rows inserted.',vParams);

    end;

     

    if pvPtProdRow."IsPrimary" = 1 then

      begin

        -- Make sure there is only One Primary Provider per Type for this date range

        select ptprod.* into vOldPtProdRec from ptprod, 

          producer new, 

          producer old, 

          prodtype pnew, 

          prodtype pold

        where

          ptprod."Patient" = pvPtProdRow."Patient" and

          ptprod."Id" <> pvPtProdRow."Id" and

          ptprod."IsPrimary" <> 0 and

          ptprod."Producer" = old."Producer" and

          old."TypeCode" = pold."Code" and

          new."Producer" = pvPtProdRow."Producer" and

          new."TypeCode" = pnew."Code" and

          (pnew."SubType" = pold."SubType" or (pnew."SubType" = 3 and pold."SubType" = 4) or (pnew."SubType" = 4 and pold."SubType" = 3)) and

          pvPtProdRow."EndDate" > ptprod."StartDate" and

          pvPtProdRow."StartDate" < ptprod."EndDate" and

          ptprod."Deleted" = 0

        ;

        -- If this is reached, we have to make another provider non-primary for the patient

        update ptprod set "IsPrimary" = 0 where "Id" = vOldPtProdRec."Id";

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptprod rows updated.',vParams);

         

        insert into ptprodh values (

          ptprodh_ptprodhistory_seq.nextval, -- PtProdHistory

          vOldPtProdRec."Patient",

          vOldPtProdRec."Producer",

          trunc(sysdate), -- Date

          2, -- Action

          vOldPtProdRec."StartDate",

          vOldPtProdRec."EndDate",

          vOldPtProdRec."IsRestricted",

          vOldPtProdRec."IsPrimary",

          vOldPtProdRec."Discipline",

          to_number(to_char(sysdate, 'HH24'))* 60 + to_number(to_char(sysdate, 'MI')), -- Time

          vOldPtProdRec."CreateDate",

          vOldPtProdRec."User",

          vOldPtProdRec."StationId",

          vOldPtProdRec."Id",

          vOldPtProdRec."Note",

          vOldPtProdRec."Deleted"

        );

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptprodh rows inserted.',vParams);

         

      exception

        when no_data_found then

          -- No other Primary Provider found, nothing to do!

          null;

      end;

    end if; -- IsPrimary    

  exception

    when exNoChange then

      -- nothing to do!

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_INFO,'ptprod record already exists, not updating.',vParams);

    when exDuplicate then

      -- nothing to do!

      null;

  end InsertPtProd_P;



  

  -- Insert a PtManage record

  PROCEDURE insertptmanage_p(INOUT pvptmanagerow ptmanage, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN poverride boolean DEFAULT true) IS

    --variable

    vOldPtManageRec ptmanage%rowtype;    

    exDuplicate exception;

    exNoChange exception;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

  --any rules?

    begin

      -- Make sure we are not creating a duplicate record

      select *  into vOldPtManageRec from ptmanage

      where

        "Patient" = pvPtManageRow."Patient" and

        "User" = pvPtManageRow."User" and

        "Deleted" = 0 

      ;

     -- If this is reached, and pOverride is true, we need to update instead of insert  

      if pOverride then 

        -- Make sure that the record has changed

        if 

          pvPtManageRow."IsPrimary" = vOldPtManageRec."IsPrimary" 

        then       

            raise exDuplicate;

        end if;

        

        -- Now update the record

        update ptmanage set row = pvPtManageRow where "Patient" = vOldPtManageRec."Patient" and "User" = vOldPtManageRec."User" and "Deleted"= 0;

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptmanage rows updated.',vParams);

        

      else

        raise exNoChange;        

      end if;

    exception

      when no_data_found then

    --inserting        

        insert into ptmanage values pvPtManageRow;

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptmanage rows inserted.',vParams);

    end;

     

    if pvPtManageRow."IsPrimary" = 1 then

      begin

        -- Make sure there is only One Primary Manager for this px

        select ptmanage.* into vOldPtManageRec from ptmanage

        where

          "Patient" = vOldPtManageRec."Patient" and

          "IsPrimary" <> 0 and

          "User" <> pvPtManageRow."User" and

          "Deleted" = 0

        ;

        -- If this is reached, we have to make another manager non-primary for the patient

        update ptmanage set "IsPrimary" = 0 where "Patient" = vOldPtManageRec."Patient" and "User" = vOldPtManageRec."User" and "Deleted" = 0;

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptmanage rows updated.',vParams);

         

      exception

        when no_data_found then

          -- No other Primary Manager found, no altering needed!

          null;

      end;

    end if; -- IsPrimary    

  exception

    when exNoChange then

      -- nothing to do!

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_INFO,'ptmanage record already exists, not updating.',vParams);

    when exDuplicate then

      -- nothing to do!

      null;

  end InsertPtManage_P;

  

  

  -- Insert a PtFacul record

  PROCEDURE insertptfacul_p(INOUT pvptfaculrow ptfacul, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN poverride boolean DEFAULT true) IS

    --variable

    vOldPtFaculRec ptfacul%rowtype;    

    exDuplicate exception;

    exNoChange exception;

    vAuditHisRow audithis%rowtype;  

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    vAuditHisRow."TableName" := 'PTFACUL';

    begin

      -- Make sure we are not creating a duplicate record

      select *  into vOldPtFaculRec from ptfacul where

        "Patient" = pvPtFaculRow."Patient" and

        "Faculty" = pvPtFaculRow."Faculty" and

        ("Discipline" = pvPtFaculRow."Discipline" 

        or ((trim(pvPtFaculRow."Discipline") is null OR length(trim(pvPtFaculRow."Discipline")) = 0) 

        and (trim("Discipline") is null OR length(trim("Discipline")) = 0) )) and

        "Deleted" = 0 

      ;

    -- If this is reached, and pOverride is true, we need to update instead of insert  

      if pOverride then 

         pvPtFaculRow."PtFacul" := vOldPtFaculRec."PtFacul";

    

     -- Make sure that the record has changed

        if 

           pvPtFaculRow."IsPrimary" = vOldPtFaculRec."IsPrimary" and

           pvPtFaculRow."Discipline" = vOldPtFaculRec."Discipline" 

        then       

          raise exDuplicate;

        end if;

    

    -- Create an audit history record

        vAuditHisRow."HistoryType" := ax_pkg.AUDIT_UPDATE;

        ax_pkg.CreateAuditHis_P(vAuditHisRow,vParams);

        pvPtFaculRow."Audit" := vAuditHisRow."Audit";

    

    -- Now update the record

        update ptfacul set row = pvPtFaculRow where "PtFacul" = vOldPtFaculRec."PtFacul";

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptfacul rows updated.',vParams);

      else

        raise exNoChange;        

      end if;

    exception

      when no_data_found then

        -- Insert new

        if pvPtFaculRow."PtFacul" = 0 or pvPtFaculRow."PtFacul" is null then

          select ptfacul_ptfacul_seq.nextval into pvPtFaculRow."PtFacul" from dual;

        end if;

        

        vAuditHisRow."HistoryType" := ax_pkg.AUDIT_ADD;

        ax_pkg.CreateAuditHis_P(vAuditHisRow,vParams);

        pvPtFaculRow."Audit" := vAuditHisRow."Audit";

        

        insert into ptfacul values pvPtFaculRow;

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptfacul rows inserted.',vParams);

     end;

   

    if pvPtFaculRow."IsPrimary" = 1 then

      begin

        --make sure there is one active Primary faculty 

        select ptfacul.* into pvPtFaculRow from ptfacul

        where

          "Patient" = pvPtFaculRow."Patient" and

          "IsPrimary" <> 0 and

          "Faculty" <> pvPtFaculRow."Faculty"      and

          "Deleted" = 0

        ;

        

  -- Create an audit history record

        vAuditHisRow."HistoryType" := ax_pkg.AUDIT_UPDATE;

        ax_pkg.CreateAuditHis_P(vAuditHisRow,vParams);

    

     -- If this is reached, we have to make another manager non-primary for the patient

        update ptfacul set "IsPrimary" = 0, "Audit" = vAuditHisRow."Audit" where "Patient" = vOldPtFaculRec."Patient" and "Faculty" = vOldPtFaculRec."Faculty" and "Deleted" = 0;

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptfacul rows updated.',vParams);

         

      exception

        when no_data_found then

          -- No other Primary Faculty found, no altering needed!

          null;

      end;

    end if; -- IsPrimary    

  exception

    when exNoChange then

      -- nothing to do!

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_INFO,'ptfacul record already exists, not updating.',vParams);

    when exDuplicate then

      -- nothing to do!

      null;

  end InsertPtFacul_P;

  

 

  PROCEDURE ptprodassign_p(IN ppatient numeric, IN pproducers character varying, IN pareprimary character varying DEFAULT '0'::character varying, IN pstartdate timestamp without time zone DEFAULT sysdate, IN penddate timestamp without time zone DEFAULT NULL::timestamp without time zone, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN poverride boolean DEFAULT true) IS

    vStart date;

    vIsFirst boolean := true;

    vPtProdRec   ptprod%rowtype;

    vCount1 number;

    vCount2 number;

    cursor curPtProd(pProdStr varchar2) is

      select

        pe."Producer",

        case pArePrimary

          when null then '-1'

          when '0' then '0'

          when '1' then '1'

          else ar."IsPrimary"

        end "IsPrimary",          

        least(nvl(pe."EndDate",trunc(current_date) + 365.25),nvl(ue."ExpDate",trunc(current_date) + 365.25)) "NewEndDate"

      from

        producer pe

        inner join (

          select

            trim(regexp_substr(pProducers,'[^,]+', 1, LEVEL)) "Producer", 

            trim(regexp_substr(pArePrimary ,'[^,]+', 1, LEVEL)) "IsPrimary"

          FROM dual 

            connect by regexp_substr(pProducers , '[^,]+', 1, level) is not null

        ) ar on ar."Producer" = trim(pe."Producer")

        left outer join users ue on ue."Producer" = pe."Producer"

    ;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    -- Compare the Array Lengths

    select

      (length(pProducers) - nvl(length(replace(pProducers,',','')),0))/length(','),

      (length(pArePrimary) - nvl(length(replace(pArePrimary,',','')),0))/length(',')

    into

      vCount1,

      vCount2

    from

      dual

    ;

   

    if vCount1 is null then

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DEBUG,'No Producers Provided, so no assignments will be made for Patient ' || pPatient || '.',vParams);

      return;

    elsif vCount1 <> vCount2 and vCount2 is not null then

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_WARNING,'pProducers and pArePrimary are different lengths, results may not be as expected.',vParams);

    end if;

   

    if (pStartDate is null) then

      vStart := trunc(current_date); 

    else

      vStart := trunc(pStartDate);

    end if;

 

    for cPtProd in curPtProd(pProducers) loop

      InitializePtProd_P(vPtProdRec,vParams);

      vPtProdRec."User" := vParams."User";

      vPtProdRec."StationId" := vParams."StationId";

      vPtProdRec."Patient" := pPatient;

      vPtProdRec."Producer" := cPtProd."Producer";

      if (pEndDate is null) then

        vPtProdRec."EndDate" := trunc(cPtProd."NewEndDate");

      else

        vPtProdRec."EndDate" := trunc(pEndDate);

      end if;

      if (vStart > vPtProdRec."EndDate") then

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DEBUG,'Producer Stat Date is Greater than End Date.',vParams);

        vPtProdRec."StartDate" := vPtProdRec."EndDate" - 1;

      else

        vPtProdRec."StartDate" := vStart;

      end if;

      if (cPtProd."IsPrimary" = '1' or (vIsFirst and cPtProd."IsPrimary" = '-1')) then

        vPtProdRec."IsPrimary" := 1;

        vIsFirst := false;

      else

        vPtProdRec."IsPrimary" := 0;

      end if;

      InsertPtProd_P(vPtProdRec,vParams,pOverride);

    end loop;

  end PtProdAssign_P;

  

  

  PROCEDURE ptmanageassign_p(IN ppatient numeric, IN pusers character varying, IN pareprimary character varying DEFAULT '0'::character varying, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN poverride boolean DEFAULT true) IS

  

  --variables

    vStart date;

    vIsFirst boolean := true;

    vPtManageRow   ptmanage%rowtype;

    vCount1 number;

    vCount2 number;

  

    cursor curPtManage(pMgrStr varchar2) is

      select

        us."User",

        case pArePrimary

          when null then '-1'

          when '0' then '0'

          when '1' then '1'

          else ar."IsPrimary"

        end "IsPrimary"         

      from

        users us

        inner join (

          select

            trim(regexp_substr(pUsers,'[^,]+', 1, LEVEL)) "User", 

            trim(regexp_substr(pArePrimary ,'[^,]+', 1, LEVEL)) "IsPrimary"

          from dual 

            connect by regexp_substr(pUsers , '[^,]+', 1, level) is not null

        ) ar on ar."User" = us."User"

    ;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

   -- Compare the Array Lengths

     select

    (length(pUsers) - nvl(length(replace(pUsers,',','')),0))/length(','),

      (length(pArePrimary) - nvl(length(replace(pArePrimary,',','')),0))/length(',')

      into

        vCount1,

        vCount2

     from dual;

    

    if vCount1 is null then

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DEBUG,'No Users Provided, so no assignments will be made for Patient ' || pPatient || '.',vParams);

      return;

    elsif vCount1 <> vCount2 and vCount2 is not null then

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_WARNING,'pUsers and pArePrimary are different lengths, results may not be as expected.',vParams);

    end if;

   

    for cPtManage in curPtManage(pUsers) loop

      InitializePtManage_P(vPtManageRow,vParams);

      vPtManageRow."AuditUser" := vParams."User";

      vPtManageRow."StationId" := vParams."StationId";

      vPtManageRow."Patient" := pPatient;

      vPtManageRow."User" := cPtManage."User";

      if (cPtManage."IsPrimary" = '1' or (vIsFirst and cPtManage."IsPrimary" = '-1')) then

        vPtManageRow."IsPrimary" := 1;

        vIsFirst := false;

      else

        vPtManageRow."IsPrimary" := 0;

      end if;

      InsertPtManage_P(vPtManageRow,vParams,pOverride);

    end loop;

  end PtManageAssign_P;

   

   

  PROCEDURE ptfaculassign_p(IN ppatient numeric, IN pusers character varying, IN pareprimary character varying DEFAULT '0'::character varying, IN pdiscipline character DEFAULT ' '::bpchar, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN poverride boolean DEFAULT true) IS

  

  --variables

    vStart date;

    vIsFirst boolean := true;

    vPtFaculRec   ptfacul%rowtype;

    vCount1 number;

    vCount2 number;

  

    cursor curPtFacul( pFacStr varchar2) is

      select

        us."User",

        case pArePrimary

          when null then '-1'

          when '0' then '0'

          when '1' then '1'

          else ar."IsPrimary"

        end "IsPrimary"         

      from

        users us

        inner join (

          select

            trim(regexp_substr(pUsers,'[^,]+', 1, LEVEL)) "User", 

            trim(regexp_substr(pArePrimary ,'[^,]+', 1, LEVEL)) "IsPrimary"

          FROM dual 

            connect by regexp_substr(pUsers , '[^,]+', 1, level) is not null

        ) ar on ar."User" = us."User"

    ;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

   -- Compare the Array Lengths

     select

      (length(pUsers) - nvl(length(replace(pUsers,',','')),0))/length(','),

      (length(pArePrimary) - nvl(length(replace(pArePrimary,',','')),0))/length(',')

      into

        vCount1,

        vCount2

     from dual;

    

    if vCount1 is null then

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DEBUG,'No Users Provided, so no assignments will be made for Patient ' || pPatient || '.',vParams);

      return;

    elsif vCount1 <> vCount2 and vCount2 is not null then

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_WARNING,'pUsers and pArePrimary are different lengths, results may not be as expected.',vParams);

    end if;

   

    for cPtFacul in curPtFacul(pUsers) loop

      InitializePtFacul_P(vPtFaculRec,vParams);

      vPtFaculRec."Patient" := pPatient;

      vPtFaculRec."Faculty" := cPtFacul."User";

      vPtFaculRec."Discipline" := pDiscipline;

      if (cPtFacul."IsPrimary" = '1' or (vIsFirst and cPtFacul."IsPrimary" = '-1')) then

        vPtFaculRec."IsPrimary" := 1;

        vIsFirst := false;

      else

        vPtFaculRec."IsPrimary" := 0;

      end if;

      InsertPtFacul_P(vPtFaculRec,vParams,pOverride);

    end loop;   

  end PtFaculAssign_P;

  

  

  PROCEDURE initializeneedreq_p(INOUT pvneedreqrow needreq, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

  begin

    pvNeedReqRow."NeedReq" := 0;

    pvNeedReqRow."Provider" := ' ';

    pvNeedReqRow."Date" := trunc(sysdate);

    pvNeedReqRow."Time" := to_number(to_char(sysdate, 'HH24'))* 60 + to_number(to_char(sysdate, 'MI'));

    pvNeedReqRow."Type" := 0;

    pvNeedReqRow."NeedCode" := ' ';

    pvNeedReqRow."Procedure" := ' ';

    pvNeedReqRow."PatType" := ' ';

    pvNeedReqRow."Note" := ' ';

    pvNeedReqRow."Assigned" := 0;

    pvNeedReqRow."AssignedDate" := null;

    pvNeedReqRow."PtProdId" := 0;

    pvNeedReqRow."Deleted" := 0;

    pvNeedReqRow."AuditId" := 0;

  end;

  

  

  PROCEDURE insertneedreq_p(INOUT pvneedreqrow needreq, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vAuditHisRow audithis%rowtype;

    exAlreadyExists exception;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    -- Get NeedReq from sequence

    if pvNeedReqRow."NeedReq" is null or pvNeedReqRow."NeedReq" = 0 then

      select needreq_needreq_seq.nextval into pvNeedReqRow."NeedReq" from dual;

    else

      begin

        select "NeedReq" into pvNeedReqRow."NeedReq" from needreq where "NeedReq" = pvNeedReqRow."NeedReq";        

        raise exAlreadyExists;

      exception

        when others then

          null;

      end;

    end if;

  

    -- Create Audit History Record

    if pvNeedReqRow."AuditId" is null or pvNeedReqRow."AuditId" = 0 then

      vAuditHisRow."TableName" := 'NEEDSREQ';

      vAuditHisRow."HistoryType" := ax_pkg.AUDIT_ADD;

      ax_pkg.CreateAuditHis_P(vAuditHisRow,vParams);

      pvNeedReqRow."AuditId" := vAuditHisRow."Audit";

    end if;



    -- Check values

    if pvNeedReqRow."AssignedDate" is null and pvNeedReqRow."Assigned" != 0 then

      pvNeedReqRow."AssignedDate" := trunc(sysdate);

    end if;



    -- Insert into NeedReq

    insert into needreq values pvNeedReqRow; 

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' needreq rows inserted.',vParams);

    -- NeedReqH created by CreateNeedReqHis trigger    

  exception

    when exAlreadyExists then

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_ERROR,' NeedReq already exists! Cannot Insert.',vParams);

  end InsertNeedReq_P;

  

  

  PROCEDURE copyproviderneedreq_p(IN psourceprovider character, IN pdestprovider character, IN pdate timestamp without time zone DEFAULT sysdate, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    --check input make sure pDestProvider exists

    vExists number;



    vNeedReqRow needreq%rowtype;

    vAuditHisRow audithis%rowtype;

    vCount number := 0;

    vTime number;

   

    --only take the unassigned need requests.

    cursor curNeedReqs is

      select *

      from needReq

      where "Provider" = pSourceProvider

      and "Assigned"   = 0

      and "Deleted"    = 0;   

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    select 1 into vExists from producer where "Producer" = pDestProvider;

     

    ax_pkg.InitializeAuditHis_P(vAuditHisRow, vParams);

    vAuditHisRow."TableName" := 'NEEDREQ';

    vAuditHisRow."HistoryType" := ax_pkg.AUDIT_ADD;

    vCount := 0;

     

    for curNeedReq in curNeedReqs loop

      if(vCount = 0) then

        ax_pkg.CreateAuditHis_P(vAuditHisRow, vParams);

      end if;

       

      ax_assign_pkg.InitializeNeedReq_P(vNeedReqRow);

       

      --set the need request characteristics.

      vNeedReqRow."Provider"  := pDestProvider;

      vNeedReqRow."Date"      := trunc(nvl(pDate,vNeedReqRow."Date"));

      vNeedReqRow."NeedCode"  := curNeedReq."NeedCode";

      -- vNeedReq."AssignedDate"  := curNeedReq."AssignedDate"; fixed in ax_assign

      vNeedReqRow."Procedure" := curNeedReq."Procedure";

      vNeedReqRow."PatType"   := curNeedReq."PatType";

      vNeedReqRow."Note"      := curNeedReq."Note";

      vNeedReqRow."AuditId"   := vAuditHisRow."Audit";

      vNeedReqRow."Type"      := curNeedReq."Type";

       

      ax_assign_pkg.InsertNeedReq_P(vNeedReqRow, vParams);

      vCount := vCount + 1;

    end loop;

    

    ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO, vCount || ' Provider Needs created for ' || pDestProvider );

  exception

    when no_data_found then -- handles no data found error

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_ERROR, 'Invalid Provider supplied : ' || pDestProvider );

  end CopyProviderNeedReq_P;

  

  

  -- Insert a new NeedReq based on a PItem Record

  --  Procedure assumes that PItem is tied to a User form

  PROCEDURE addneedfrompitem_p(IN ppitemrow pitem, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS 

    -- variables

    vParams ax_pkg.tParams := pParams;

    vNeedReqRow needreq%rowtype;

    vLogRow ax_log%rowtype;

    vAnsText pitem."AnsText"%type;

    vUser users."User"%type;

    exUserNotProvider exception;

    exUserNotFound exception;

    

    pragma autonomous_transaction;

  begin

  -- Initialization

    if not vParams."IsInit" then

      vParams."VerboseType" := ax_pkg.SHOW_NONE; -- Assume this is come from a trigger, where the output is not shown

    end if;

    ax_pkg.InitializeParams_P(vParams);

  

    vLogRow."Source" := 'ax_assign_pkg.AddNeedFromPItem_P';

    vLogRow."Request" := 'P189-145120';

    InitializeNeedReq_P(vNeedReqRow);

  

  -- Exit unless the Item Code is a valid NEED Code (otherwise raise NO DATA FOUND) 

    select 

      n."NeedCode" into vNeedReqRow."NeedCode" 

    from fitem i

    inner join needcode n on trim(n."NeedCode") = trim(i."Code") and n."Inactive" = 0

    where

      i."FItem" = pPItemRow."FItem" and

      rownum = 1;

  

  -- Get Note from next FItem

    begin

      select 

        a."AnsText" into vAnsText

      from pitem a

      left outer join fitem i on i."FItem" = a."FItem"

      where

        a."Patient" = pPItemRow."Patient" and

        a."PForm" = pPItemRow."PForm" and

        a."Status" = 0 and

        i."AnsType" in (1,5) and -- Text/Long Text

        i."ParentFItem" = pPitemRow."FItem" and

        --a."AppDateTime" is not null and

        rownum = 1

      ;

    exception

      when no_data_found then

        -- no text was filled out, but no need to raise an error

        null;

    end;

    

    vNeedReqRow."Note" := ax_pkg.CropToFieldSize_F(vAnsText,'NEEDREQ','Note',vParams);

  

  -- Get Provider from Users table

    begin

      select 

        u."Producer",u."User" into vNeedReqRow."Provider",vUser

      from users u

      inner join pform f on f."OwnerId" = u."User" and f."OwnerType" = 5 -- 5=User

      where

        f."PForm" = pPItemRow."PForm" and

        u."Deleted" = 0 and

        (u."ExpDate" >= sysdate or u."ExpDate" is null) and

        rownum = 1

      ;

    exception

      when no_data_found then

        raise exUserNotFound;

    end;

    

  -- Error, if User is not a Provider

    if (trim(vNeedReqRow."Provider") is null OR length(trim(vNeedReqRow."Provider")) = 0) then

      raise exUserNotProvider;

    end if;

    

    -- Create the Need Request

    InsertNeedReq_P(vNeedReqRow,vParams);

    

    -- Optionally log that the Need was assigned, this should only be needed for debugging

    if vParams."VerboseType" >= ax_pkg.MSG_INFO then

      vLogRow."Log" := 'Need ' || vNeedReqRow."NeedCode" || '  assigned to' || vNeedReqRow."Provider";

      ax_pkg.Log_P(vLogRow,ax_pkg.MSG_INFO,vParams); 

    end if;

    

    -- pragma autonomous_transaction requires a commit

    commit;

  exception

    when no_data_found then

      -- Item Reference Code is not a valid Need, so there is no need to create a Needs Request

      commit;

    when exUserNotFound then

      vLogRow."Log" := 'User ' || vUser || ' does not exist, or is expired. Need not assigned.';

      ax_pkg.Log_P(vLogRow,ax_pkg.MSG_ERROR,vParams);

      commit;

    when exUserNotProvider then

      vLogRow."Log" := 'User ' || vUser || ' is not a Provider. Need not assigned.';

      ax_pkg.Log_P(vLogRow,ax_pkg.MSG_ERROR,vParams);

      commit;

    when others then

      ax_pkg.LogEvent_P(vLogRow."Source",sqlerrm,vParams);  

      commit;

  end AddNeedFromPItem_P;  

  

 

  PROCEDURE transferptfacul_p(IN pfromuser numeric, IN ptousers character varying, IN pmove boolean DEFAULT true, IN pareprimary character varying DEFAULT '0'::character varying, IN pdiscipline character DEFAULT ' '::bpchar, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN poverride boolean DEFAULT true) IS

    cursor curPatients is select * from ptfacul where "Faculty" = pFromUser and "Deleted" = 0;

    vCount number := 0;

    vParams ax_pkg.tParams := pParams;

    vAuditHisRow audithis%rowtype;

    vLogRow ax_log%rowtype;

  begin

    ax_pkg.InitializeParams_P(vParams);

    vLogRow."Source" := 'ax_assign_pkg.TransferPtFacul_P';

    vLogRow."Request" := '';

    

    if pMove then

      for cPatient in curPatients loop

        PtFaculAssign_P(cPatient."Patient",pToUsers,cPatient."IsPrimary",cPatient."Discipline",vParams,pOverride);

        vCount := vCount + 1;

      end loop;

    else

      for cPatient in curPatients loop

        PtFaculAssign_P(cPatient."Patient",pToUsers,pArePrimary,pDiscipline,vParams,pOverride);

        vCount := vCount + 1;

      end loop;

    end if;

    if pMove then

      if(vCount > 0) then

        ax_pkg.InitializeAuditHis_P(vAuditHisRow, vParams);

        vAuditHisRow."TableName" := 'PTFACUL';

        vAuditHisRow."HistoryType" := ax_pkg.AUDIT_DELETE;

        ax_pkg.CreateAuditHis_P(vAuditHisRow, vParams);

        update ptfacul set "Deleted" = 1, "Audit" = vAuditHisRow."Audit" where "Faculty" = pFromUser and "Deleted" = 0;

      end if;      

    end if;

    vLogRow."Log" := vCount || ' Patients transfered from Faculty User ' || pFromUser || ' to ' || pToUsers;

    ax_pkg.Log_P(vLogRow,ax_pkg.MSG_INFO,vParams);

  end TransferPtFacul_P;

  

  

  PROCEDURE transferptmanage_p(IN pfromuser numeric, IN ptousers character varying, IN pmove boolean DEFAULT true, IN pareprimary character varying DEFAULT '0'::character varying, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN poverride boolean DEFAULT true) IS

    cursor curPatients is select * from ptmanage where "User" = pFromUser and "Deleted" = 0;

    vCount number := 0;

    vParams ax_pkg.tParams := pParams;

    vAuditHisRow audithis%rowtype;

    vLogRow ax_log%rowtype;

  begin

    ax_pkg.InitializeParams_P(vParams);

    vLogRow."Source" := 'ax_assign_pkg.TransferPtManage_P';

    vLogRow."Request" := '';

    

    if pMove then

      for cPatient in curPatients loop

        PtManageAssign_P(cPatient."Patient",pToUsers,cPatient."IsPrimary",vParams,pOverride);

        vCount := vCount + 1;

      end loop;

    else

      for cPatient in curPatients loop

        PtManageAssign_P(cPatient."Patient",pToUsers,pArePrimary,vParams,pOverride);

        vCount := vCount + 1;

      end loop;

    end if;

    if pMove then

      if(vCount > 0) then

        ax_pkg.InitializeAuditHis_P(vAuditHisRow, vParams);

        vAuditHisRow."TableName" := 'PTMANAGE';

        vAuditHisRow."HistoryType" := ax_pkg.AUDIT_DELETE;

        ax_pkg.CreateAuditHis_P(vAuditHisRow, vParams);        

        for cPatient in curPatients loop          

          insert into ptmanagh ("PtManageHist","Type","Time","Date","Patient","User","IsPrimary","CreateDate","AuditUser","StationId","Deleted")

          values (

              ptmanagh_ptmanagehist_seq.nextval,

              2,

              round(to_char(sysdate,'SSSSS')/60),

              trunc(sysdate),

              cPatient."Patient",

              pFromUser,

              cPatient."IsPrimary",

              cPatient."CreateDate",

              vAuditHisRow."User",

              vAuditHisRow."StationId",

              1              

          );

        end loop;

        update ptmanage set "Deleted" = 1 where "User" = pFromUser and "Deleted" = 0;

      end if;      

    end if;

    vLogRow."Log" := vCount || ' Managed Patients transfered from User ' || pFromUser || ' to ' || pToUsers;

    ax_pkg.Log_P(vLogRow,ax_pkg.MSG_INFO,vParams);

  end TransferPtManage_P;

  

  

  PROCEDURE transferptprod_p(IN pfromprovider character, IN ptoproviders character varying, IN pmove boolean DEFAULT true, IN pareprimary character varying DEFAULT '0'::character varying, IN pstartdate timestamp without time zone DEFAULT sysdate, IN penddate timestamp without time zone DEFAULT NULL::timestamp without time zone, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN poverride boolean DEFAULT true) IS

    -- look at current date for the EndDate, because the old provider assignment may already be expired before this is called

    cursor curPatients is select * from ptprod where "Producer" = pFromProvider and "Deleted" = 0 and "EndDate" >= sysdate;

    cursor curUpdatePatients is select * from ptprod where "Producer" = pFromProvider and "EndDate" >= nvl(pStartDate,sysdate);

    vCount number := 0;

    vAuditHisRow audithis%rowtype;

    vParams ax_pkg.tParams := pParams;

    vLogRow ax_log%rowtype;

  begin

    ax_pkg.InitializeParams_P(vParams);

    vLogRow."Source" := 'ax_assign_pkg.TransferPtProd_P';

    vLogRow."Request" := '';

    

    if pMove then

      for cPatient in curPatients loop

        PtProdAssign_P(cPatient."Patient",pToProviders,cPatient."IsPrimary",pStartDate,pEndDate,vParams,pOverride);

        vCount := vCount + 1;

      end loop;

    else

      for cPatient in curPatients loop

        PtProdAssign_P(cPatient."Patient",pToProviders,pArePrimary,pStartDate,pEndDate,vParams,pOverride);

        vCount := vCount + 1;

      end loop;

    end if;

    if pMove then

      if(vCount > 0) then

        ax_pkg.InitializeAuditHis_P(vAuditHisRow, vParams);

        vAuditHisRow."TableName" := 'PTPROD';

        vAuditHisRow."HistoryType" := ax_pkg.AUDIT_EDIT;

        ax_pkg.CreateAuditHis_P(vAuditHisRow, vParams);

        for cPatient in curUpdatePatients loop

          insert into ptprodh ("PtProdHistory","Patient","Producer","Date","Action","StartDate","EndDate","IsRestricted","IsPrimary","Discipline","Time","CreateDate","User","StationId","Id","Note","Deleted")

          values (

            ptprodh_ptprodhistory_seq.nextval,

            cPatient."Patient",

            cPatient."Producer",

            trunc(sysdate),

            2,

            cPatient."StartDate",

            nvl(pStartDate,sysdate),

            cPatient."IsRestricted",

            cPatient."IsPrimary",

            cPatient."Discipline",

            round(to_char(sysdate,'SSSSS')/60),

            cPatient."CreateDate",

            vAuditHisRow."User",

            vAuditHisRow."StationId",

            cPatient."Id",

            cPatient."Note",

            cPatient."Deleted"

          );

        end loop;

        update ptprod

        set "EndDate" = nvl(pStartDate,sysdate),

          "User" = vAuditHisRow."User",

          "StationId" = vAuditHisRow."StationId"

        where "Producer" = pFromProvider

          and "EndDate" >= nvl(pStartDate,sysdate);

      end if;      

    end if;

    vLogRow."Log" := vCount || ' Patients transfered from Provider ' || pFromProvider || ' to ' || pToProviders;

    ax_pkg.Log_P(vLogRow,ax_pkg.MSG_INFO,vParams);

  end TransferPtProd_P;

  

 

END;
CREATE OR REPLACE PACKAGE BODY ax_copy_pkg IS



  -- returns information about this package, or its procedures

  PROCEDURE help(IN pobjectname character varying DEFAULT NULL::character varying) IS

    vReturn CLOB;

  begin

    -- Writes the help to the DBMS_OUTPUT

	-- AX-39259

    vReturn := ax_pkg.Help_F('AX_COPY_PKG',pObjectName);

  end Help;



  -- Copy over basic Patient information

  PROCEDURE copypatientrecords_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN psourcepatient numeric, INOUT pvtargetpatient numeric, INOUT pvmapaudit numeric, IN pcopyparams tcopyparams DEFAULT ax_copy_pkg.ax_copy_params, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    -- cursors

    cursor curPicture(pId number) is

      select * from picture where "Patient" = pId;

    cursor curPtAlert(pId number) is

      select * from ptalert where "Patient" = pId and "Deleted" = 0;

    cursor curAnswer2(pId number) is 

      select * from answer2 where "PId" = pId; 

    cursor curPat2His(pId number) is 

      select * from pat2his where "Auto" = pId;     

    cursor curPtEmploy(pId number) is 

      select * from ptemploy where "Patient" = pId; 

    cursor curPrescrip(pId number) is

      select * from prescrip where "Patient" = pId and "Deleted" = 0;

    cursor curPtGuar(pId number) is 

      select * from ptguar where "Patient" = pId and "RespPatient" = pId; 

    cursor curPtManage(pId number) is 

      select * from ptmanage where "Patient" = pId and "Deleted" = 0;

    cursor curPtFacul(pId number) is 

      select * from ptfacul where "Patient" = pId and "Deleted" = 0;

    cursor curPtManagH(pId number) is 

      select ptmh.* from 

        ptmanagh ptmh 

        inner join ptmanage ptm on ptm."User" = ptmh."User" and ptm."Patient" = ptmh."Patient"

      where 

        ptm."Patient" = pId and 

        ptm."Deleted" = 0;

    cursor curPtNeed(pId number) is

      select * from ptneed where "Patient" = pId and "Deleted" = 0;

    cursor curPtNote(pId number) is

      select * from ptnote where "Patient" = pId and "Deleted" = 0 and "IsClaimNote" = 0;

    cursor curPtTypes(pId number) is

      select * from pttypes where "Patient" = pId; 

    cursor curPtRefer(pId number) is

      select * from ptrefer where "Patient" = pId and "Deleted" = 0; 

    cursor curPtXRay(pId number) is

      select * from ptxray where "Patient" = pId and "Deleted" = 0;

    cursor curPtRace(pId number) is 

      select * from ptrace where "Patient" = pId and "Deleted" = 0;  

    cursor curPtSumm(pId number) is

      select * from ptsumm where "Patient" = pId;

    cursor curPtPrev(pId number) is

      select * from ptprev where "Patient" = pId and "Deleted" = 0;

    cursor curPtPhys(pId number) is

      select * from ptphys where "Patient" = pId and "Deleted" = 0;

    -- P189-155143 changed cursor to use map records for PTRECALL

    cursor curPtRecallMap(pAudit audithis."Audit"%type) is

      select 

        Oldptr."Id" "OldId",

        Newptr."TargetId" "Id",

        nvl(NewT2."TargetId",0) "Treatme2Id"

      from

        ptrecall Oldptr

        inner join AX_Map Newptr on Newptr."SourceId" = Oldptr."Id" and Newptr."TableName" = 'PTRECALL' and Newptr."Audit" = pAudit

        left outer join ax_Map NewT2 on  NewT2."TableName" = 'TREATME2' and NewT2."SourceId" = Oldptr."Treatme2Id" and NewT2."Audit" = pAudit

    ;  

    -- P189-155143 added

    cursor curPtRcGrpMap(pAudit audithis."Audit"%type) is

      select 

        OldRcGrp."PtRcGrp" "OldId",

        NewRcGrp."TargetId" "NewId"

      from

        ptrcgrp OldRcGrp

        inner join AX_Map NewRcGrp on NewRcGrp."SourceId" = OldRcGrp."PtRcGrp" and NewRcGrp."TableName" = 'PTRCGRP' and NewRcGrp."Audit" = pAudit

    ;  

    -- P189-155143 added

    cursor curPtRcGrpIMap(pAudit audithis."Audit"%type,pPtRcGrp ptrcgrpi."PtRcGrp"%type) is

      select 

        OldRcGrpI."PtRcGrp" "OldPtRcGrp",

        NewPtr."SourceId" "OldPtRecall",

        NewPtr."TargetId" "NewPtRecall"

      from

        ptrcgrpi OldRcGrpI

        inner join AX_Map Newptr on Newptr."SourceId" = OldRcGrpI."PtRecall" and Newptr."TableName" = 'PTRECALL' and Newptr."Audit" = pAudit

      where

        OldRcGrpI."PtRcGrp" = pPtRcGrp

    ;  

    -- Records

    vPatient2Row patient2%rowtype;

    vTargetPatientRow patient%rowtype;

    vPtRecallRow ptrecall%rowtype;

    vXRayInfoRow xrayinfo%rowtype;

    vAuditHisRow audithis%rowtype;

    vAuditHisRow2 audithis%rowtype; -- P189-155143

    vPtRcGrpRow ptrcgrp%rowtype; -- P189-155143

    vPtRcGrpIRow ptrcgrpi%rowtype; -- P189-155143

    -- Variables

    vSourcePatient2 patient2."Auto"%type;

    vTargetChart patient."Chart"%type;

    vLast patient."Last"%type;

    vFirst patient."First"%type;

    vMiddle patient."Middle"%type;

    vCount number;

    vCount2 number;

    vPos number;

    vCurrentId number;

    vDefaultNeed needsts."Code"%type;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    pvMapAudit := ax_pkg.GetMapAudit_F(pvMapAudit,vParams);



    -- Get source Patient2

    begin

      select * into vPatient2Row from patient2 where "PtxPId" = pSourcePatient;

    exception 

      when no_data_found then

        ax_Patient_Pkg.AddPatient2_P(pSourcePatient,vParams);

        select * into vPatient2Row from patient2 where "PtxPId" = pSourcePatient;

    end;

    vSourcePatient2 := vPatient2Row."Auto";

    

    -- Initalize Target Patient

    select * into vTargetPatientRow from patient where "Patient" = pSourcePatient;



    -- Parse % in parameters

      -- For pTargetChart any suffix is ignored, only prefixes are allowed

    vPos := instr(pCopyParams."TargetChart",'%');

    if pCopyParams."TargetChart" is not null and vPos > 0 then

      vTargetChart := substr(pCopyParams."TargetChart",1,vPos-1);

    elsif pCopyParams."TargetChart" is null then

      vTargetChart := ' ';

    else

      vTargetChart := pCopyParams."TargetChart";

      vPos := 0;

    end if;

    vLast := ax_pkg.CropToFieldSize_F(replace(pCopyParams."Last", '%',vTargetPatientRow."Last"),'Patient','Last',vParams);

    vFirst := ax_pkg.CropToFieldSize_F(replace(pCopyParams."First", '%',vTargetPatientRow."First"),'Patient','First',vParams);

    vMiddle := ax_pkg.CropToFieldSize_F(replace(pCopyParams."Middle", '%',vTargetPatientRow."Middle"),'Patient','Middle',vParams);

            

    -- Check to make sure target Chart is not in use

    if pCopyParams."TargetChart" is not null and vPos = 0 then

      begin

        select "Chart" into vTargetPatientRow."Chart" from patient where "Chart" = vTargetChart;

        -- if this is reached, then there is already a patient with pTargetChart 

        ax_pkg.AppendString_P(pvMessage,'There is already a patient with a Chart of ''' || vTargetChart || '''!',true,' ',ax_pkg.MSG_INFO,vParams);

        pvSuccess := false;

        return;

      exception

        when no_data_found then

        -- Initalize Target Chart

          vTargetPatientRow."Chart" := pCopyParams."TargetChart";

      end;

    else

      vTargetPatientRow."Chart" := ax_Patient_Pkg.GetNextChart_F(vTargetChart,pParams);

    end if;

    

    -- Scramble Patient Information

    if pCopyParams."Scramble" = '1' then

      if vTargetPatientRow."Sex" = 1 then

        vTargetPatientRow."First" := 'John';

        vTargetPatientRow."Last" := 'Doe';

      elsif vTargetPatientRow."Sex" = 2 then

        vTargetPatientRow."First" := 'Jane';

        vTargetPatientRow."Last" := 'Doe';

      else

        vTargetPatientRow."First" := 'Jackie';

        vTargetPatientRow."Last" := 'Joe';

      end if;

      vTargetPatientRow."Prefered" := 'First';

      vTargetPatientRow."Middle" := vTargetPatientRow."First";

      -- vTargetPatientRow."Sex" := 0;

      if (months_between(trunc(sysdate),vTargetPatientRow."Birth")/12 < 15) then

        vTargetPatientRow."Birth" := sysdate+dbms_random.value(-3650,0)-1825;

      else

        vTargetPatientRow."Birth" := sysdate+dbms_random.value(-21900,0)-5475;

      end if;

      vTargetPatientRow."AltChart"          := ' ';

      vTargetPatientRow."Sin"               := ' ';

      vTargetPatientRow."Address1"          := 

        regexp_substr('Fifth,Sixth,Seventh,Eighth,Ninth,Tenth,Main,Maple,Pine,Oak,View,Lake,Hill,First,Second,Third,Park,Cedar,Elm,Fourth','([^,]+)',1,round(dbms_random.value(1,20))) ||

        ' ' || regexp_substr('St,Ave,Rd,Way','([^,]+)',1,round(dbms_random.value(1,4)));

      vTargetPatientRow."Address2"          := ' ';

      vTargetPatientRow."AddressOther"      := ' ';

      vTargetPatientRow."City"              := ' ';

      vTargetPatientRow."Province"          := ' ';

      vTargetPatientRow."Postal"            := ' ';

      vTargetPatientRow."HomeArea"          := '503';

      vTargetPatientRow."HomePhone"         := '555-5555';

      vTargetPatientRow."WorkArea"          := '503';

      vTargetPatientRow."WorkPhone"         := '777-7777';

      vTargetPatientRow."OtherArea"         := '503';

      vTargetPatientRow."OtherPhone"        := '999-9999';

      vTargetPatientRow."Email"             := ' ';

      vTargetPatientRow."IsTrustedAudit"    := 0;    -- SF-00134678

      vTargetPatientRow."SecondIDNumber"    := '';   -- SF-00134678

      vTargetPatientRow."Is2ndIdTrustedAudit" := 0;  -- SF-00134678



    end if;

    if pCopyParams."Scramble" = '1' or pCopyParams."CopyEmergencyContact" = '0' then

      vTargetPatientRow."EmergLast"         := ' ';

      vTargetPatientRow."EmergFirst"        := ' ';

      vTargetPatientRow."EmergMiddle"       := ' ';

      vTargetPatientRow."EmergAddress"      := ' ';

      vTargetPatientRow."EmergAddress2"     := ' ';

      vTargetPatientRow."EmergAddressOther" := ' ';

      vTargetPatientRow."EmergCity"         := ' ';

      vTargetPatientRow."EmergProvince"     := ' ';

      vTargetPatientRow."EmergArea"         := '503';

      vTargetPatientRow."EmergPhone"        := '333-3333';

      vTargetPatientRow."EmergRelation"     := ' ';

      vTargetPatientRow."EmergAltArea"      := ' ';

      vTargetPatientRow."EmergAltPhone"     := ' ';

    end if;

    

    if pCopyParams."StatusCode" is not null then

      begin

        select 1 into vCount from status where "Status" = pCopyParams."StatusCode" and "Inactive" = 0 and "Type" = 2;

        vTargetPatientRow."Status" := pCopyParams."StatusCode";

      exception

        when no_data_found then

          null; -- Do not change the status if the code is invalid

      end;

    end if;

  

    -- Get the new Patient Id

    select patient_Patient_seq.nextval into vTargetPatientRow."Patient" from dual;

    pvTargetPatient := vTargetPatientRow."Patient";

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_INFO,'New Patient: ' || vTargetPatientRow."Patient",vParams);

    insert into ax_map values (pvMapAudit,'PATIENT',pSourcePatient,vTargetPatientRow."Patient",null,null);  

    

    -- Update pTargetPatient  

    if (pCopyParams."LoopAudit" is null or pCopyParams."LoopAudit" = 0) then

      vAuditHisRow."TableName" := 'PATIENT';

      vAuditHisRow."HistoryType" := ax_pkg.AUDIT_ADD;      

      ax_pkg.CreateAuditHis_P(vAuditHisRow, vParams);

      vTargetPatientRow."Audit" := vAuditHisRow."Audit";

    else

      vTargetPatientRow."Audit" := pCopyParams."LoopAudit";

    end if;

    

    -- Patient Value Overrides

    if pCopyParams."Last" <> '%' then

      vTargetPatientRow."Last" := nvl(vLast,vTargetPatientRow."Last");

    end if;  

    if pCopyParams."First" <> '%' then

      vTargetPatientRow."First" := nvl(vFirst,vTargetPatientRow."First");

      vTargetPatientRow."Prefered" := nvl(vFirst,vTargetPatientRow."Prefered");

    end if;

    if pCopyParams."Middle" <> '%' then

      vTargetPatientRow."Middle" := nvl(vMiddle,vTargetPatientRow."Middle");

    end if;

    vTargetPatientRow."Email" := nvl(pCopyParams."Email",vTargetPatientRow."Email");

    vTargetPatientRow."Address1" := nvl(pCopyParams."Address1",vTargetPatientRow."Address1");

    vTargetPatientRow."Address2" := nvl(pCopyParams."Address2",vTargetPatientRow."Address2");

    vTargetPatientRow."City" := nvl(pCopyParams."City",vTargetPatientRow."City");

    vTargetPatientRow."Province" := nvl(pCopyParams."Province",vTargetPatientRow."Province");

    vTargetPatientRow."Postal" := nvl(pCopyParams."Postal",vTargetPatientRow."Postal");

    vTargetPatientRow."HomeArea" := nvl(pCopyParams."HomeArea",vTargetPatientRow."HomeArea");

    vTargetPatientRow."HomePhone" := nvl(pCopyParams."HomePhone",vTargetPatientRow."HomePhone");

    vTargetPatientRow."HomeExt" := nvl(pCopyParams."HomeExt",vTargetPatientRow."HomeExt");

    vTargetPatientRow."Birth" := nvl(pCopyParams."Birth",vTargetPatientRow."Birth");

    vTargetPatientRow."Sex" := nvl(pCopyParams."Sex",vTargetPatientRow."Sex");

    vTargetPatientRow."AltChart" := nvl(pCopyParams."AltChart",' ');

    

    vTargetPatientRow."CustomCode1" := nvl(pCopyParams."CustomCode1",vTargetPatientRow."CustomCode1");

    vTargetPatientRow."CustomCode2" := nvl(pCopyParams."CustomCode1",vTargetPatientRow."CustomCode2");

    vTargetPatientRow."CustomCode3" := nvl(pCopyParams."CustomCode1",vTargetPatientRow."CustomCode3");

    vTargetPatientRow."CustomCode4" := nvl(pCopyParams."CustomCode1",vTargetPatientRow."CustomCode4");

    vTargetPatientRow."CustomCode5" := nvl(pCopyParams."CustomCode1",vTargetPatientRow."CustomCode5");

    vTargetPatientRow."CustomCode6" := nvl(pCopyParams."CustomCode1",vTargetPatientRow."CustomCode6");

    vTargetPatientRow."CustomCode7" := nvl(pCopyParams."CustomCode1",vTargetPatientRow."CustomCode7");

    vTargetPatientRow."CustomCode8" := nvl(pCopyParams."CustomCode1",vTargetPatientRow."CustomCode8");

    vTargetPatientRow."CustomCode9" := nvl(pCopyParams."CustomCode1",vTargetPatientRow."CustomCode9");

    vTargetPatientRow."CustomCode10" := nvl(pCopyParams."CustomCode1",vTargetPatientRow."CustomCode10");  

  

    vTargetPatientRow."Family" := vTargetPatientRow."Patient";

    vTargetPatientRow."Deleted" := 0;

    vTargetPatientRow."LastUpper" := upper(vTargetPatientRow."Last");

    vTargetPatientRow."PrefUpper" := upper(vTargetPatientRow."Prefered");

    

    vTargetPatientRow."User" := vParams."User";

    vTargetPatientRow."StationId" := vParams."StationId";



    -- SF-00241331 Set flag indicating one or more EXTERNAL_LINK records to 0 since these records are not being copied

    vTargetPatientRow."HasExternalLink" := 0;

    vTargetPatientRow."HasCarequality" := 0;  -- AX-35969



   -- AX-35969

    begin



      -- Add the new Patient Record  

      insert into patient values vTargetPatientRow;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' patient rows inserted.',vParams);



      -- Update pathis to show that the patient was added, and not an update like the trigger set it to be

      update pathis set "PtAddFlag" = 1 where "Patient" = vTargetPatientRow."Patient";

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' pathis rows updated.',vParams);



      -- Create RespHis Record

      ax_Patient_Pkg.InsertRespHis_P(vTargetPatientRow,vParams);



    exception

      when others then

	  	-- AX-39259

        ax_pkg.LogEvent_P(trim('AX_COPY_PKG')||'.CopyPatientRecords_P', trim(sqlerrm));

    end;



    -- Create Patient 2 Record

    select patient2_auto_seq.nextval into vPatient2Row."Auto" from dual;

    vPatient2Row."ChartId" := vTargetPatientRow."Chart";

    vPatient2Row."FirstName" := vTargetPatientRow."First";

    vPatient2Row."LastName" := vTargetPatientRow."Last";

    vPatient2Row."MidName" := vTargetPatientRow."Middle";  

    vPatient2Row."PtxPId" := vTargetPatientRow."Patient"; 

    insert into patient2 values vPatient2Row;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' patient2 rows inserted.',vParams);

    

  -- Create Picture Records

    if pCopyParams."Scramble" = '0' then

      vCount := 0;

      for cPicture in curPicture(pSourcePatient) loop

        cPicture."Patient" := vTargetPatientRow."Patient";

        insert into picture values cPicture;

        vCount := vCount + 1;

      end loop;      

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' picture rows inserted.',vParams);

    end if;  

    

    -- Create PtAlert Records

    vAuditHisRow."TableName" := 'PTALERT';

    vAuditHisRow."HistoryType" := ax_pkg.AUDIT_ADD;      

    ax_pkg.CreateAuditHis_P(vAuditHisRow, vParams);

     

    vCount := 0;

    for cPtAlert in curPtAlert(pSourcePatient) loop

      select ptalert_ptalert_seq.nextval into cPtAlert."PtAlert" from dual;

      cPtAlert."Patient" := vTargetPatientRow."Patient";

      cPtAlert."Audit" := vAuditHisRow."Audit";

      insert into ptalert values cPtAlert;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ptalert rows inserted.',vParams);

  

    -- Create Answer2 Records     

    vCount := 0;

    for cAnswer2 in curAnswer2(vSourcePatient2) loop

      select Answer2_auto_seq.nextval into cAnswer2."Auto" from dual;

      cAnswer2."PId" := vPatient2Row."Auto";

      insert into Answer2 values cAnswer2;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' answer2 rows inserted.',vParams);

    

    -- Create PtRecall Records  

    -- P189-155143 change how ptrecalls are converted so they can be linked to a PTRCGRPI record

    -- Map PtRecall Records

    insert into ax_map (

      select 

        pvMapAudit,

        'PTRECALL', 

        "Id", 

        ptrecall_id_seq.nextval 

        ,null,null

      from ptrecall 

      where "Patient" = pSourcePatient

      and "Deleted" = 0

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

     

    vAuditHisRow."TableName" := 'PTRECALL';

    vAuditHisRow."HistoryType" := ax_pkg.AUDIT_ADD;      

    ax_pkg.CreateAuditHis_P(vAuditHisRow, vParams);

    

    vCount := 0;

    for cPtRecallMap in curPtRecallMap(pvMapAudit) loop

      select * into vPtRecallRow from ptrecall where "Id" = cPtRecallMap."OldId";

      vPtRecallRow."Id" := cPtRecallMap."Id";

      vPtRecallRow."Patient" := vTargetPatientRow."Patient";

      vPtRecallRow."Provider" := ' ';

      vPtRecallRow."CreationDate" := sysdate;

      vPtRecallRow."Audit" := vAuditHisRow."Audit";

      vPtRecallRow."Treatme2Id" := cPtRecallMap."Treatme2Id";

      insert into ptrecall values vPtRecallRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ptrecall rows inserted.',vParams);

    

    -- P189-155143 added to create PTRCGRP and PTRCGRPI records

    -- Create PtRcGrp records

    

    -- Map PtRcGrp records

    insert into ax_map (

      select 

        pvMapAudit,

        'PTRCGRP', 

        "PtRcGrp", 

        ptrcgrp_ptrcgrp_seq.nextval 

        ,null,null

      from ptrcgrp 

      where "Patient" = pSourcePatient

      and "Deleted" = 0

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);



    vAuditHisRow."TableName" := 'PTRCGRP';

    vAuditHisRow."HistoryType" := ax_pkg.AUDIT_ADD;      

    ax_pkg.CreateAuditHis_P(vAuditHisRow, vParams);



    vAuditHisRow2."TableName" := 'PTRCGRPI';

    vAuditHisRow2."HistoryType" := ax_pkg.AUDIT_ADD;      

    ax_pkg.CreateAuditHis_P(vAuditHisRow2, vParams);

    

    vCount := 0;

    vCount2 := 0;

    for cPtRcGrpMap in curPtRcGrpMap(pvMapAudit) loop

      select * into vPtRcGrpRow from ptrcgrp where "PtRcGrp" = cPtRcGrpMap."OldId";

      vPtRcGrpRow."PtRcGrp" := cPtRcGrpMap."NewId";

      vPtRcGrpRow."Patient" := vTargetPatientRow."Patient";

      vPtRcGrpRow."Audit" := vAuditHisRow."Audit";

      insert into ptrcgrp values vPtRcGrpRow;

      vCount := vCount + 1;



      for cPtRcGrpIMap in curPtRcGrpIMap(pvMapAudit,cPtRcGrpMap."OldId") loop

        select * into vPtRcGrpIRow from ptrcgrpi where "PtRcGrp" = cPtRcGrpIMap."OldPtRcGrp" and "PtRecall" = cPtRcGrpIMap."OldPtRecall";

        vPtRcGrpIRow."PtRcGrp" := cPtRcGrpMap."NewId";

        vPtRcGrpIRow."PtRecall" := cPtRcGrpIMap."NewPtRecall";

        vPtRcGrpIRow."Audit" := vAuditHisRow2."Audit";

        insert into ptrcgrpi values vPtRcGrpIRow;

        vCount2 := vCount2 + 1;

      end loop;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ptrcgrp rows inserted.',vParams);

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount2 || ' ptrcgrpi rows inserted.',vParams);

    

    -- Create Pat2His records

    vCount := 0;

    for cPat2His in curPat2His(vSourcePatient2) loop

      select pat2his_Pat2his_seq.nextval into cPat2His."Pat2His" from dual;

      cPat2His."Auto" := vPatient2Row."Auto";

      cPat2His."ChartId" := vTargetPatientRow."Chart";

      cPat2His."LastName" := vTargetPatientRow."Last";

      cPat2His."FirstName" := vTargetPatientRow."First";

      cPat2His."MidName" := vTargetPatientRow."Middle";

      insert into pat2his values cPat2His;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount|| ' pat2his rows inserted.',vParams);

    

    -- Create pttypes records

    vCount := 0;

    for cPtTypes in curPtTypes(pSourcePatient) loop

      cPtTypes."Patient" := vTargetPatientRow."Patient";

      insert into pttypes values cPtTypes;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' pttypes rows inserted.',vParams);

  

    -- Create ptrace records

    vCount := 0;

    for cPtRace in curPtRace(vSourcePatient2) loop

      cPtRace."Patient" := vTargetPatientRow."Patient";

      insert into ptrace values cPtRace;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ptrace rows inserted.',vParams);



    -- Create ptsumm Records  

    vCount := 0;

    for cPtSumm in curPtSumm(pSourcePatient) loop

      cPtSumm."Patient" := vTargetPatientRow."Patient";

      insert into ptsumm values cPtSumm;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ptsumm rows inserted.',vParams);

    

    -- Create ptsummh records

      -- created by trigger on ptsumm

    

    -- Create ptprev Records    

    vCount := 0;

    vCount2 := 0;

    for cPtPrev in curPtPrev(pSourcePatient) loop

      begin

        select 

          * into vXRayInfoRow 

        from 

          xrayinfo 

        where 

          "Patient" = pSourcePatient and

          "PtPrev" = cPtPrev."PtPrev" and

          rownum = 1

        order by

          "XRayInfo" desc;

        vCurrentId := 1;

      exception

        when no_data_found then

          vCurrentId := 0;

      end;



      select ptprev_Ptprev_seq.nextval into cPtPrev."PtPrev" from dual;

      cPtPrev."Patient" := vTargetPatientRow."Patient";

      insert into ptprev values cPtPrev;

      vCount := vCount + 1;

      

      if vCurrentId = 1 then

        select xrayinfo_xrayinfo_seq.nextval into vXRayInfoRow."XRayInfo" from dual;

        vXRayInfoRow."PtPrev" := cPtPrev."PtPrev";

        vXRayInfoRow."Patient" := vTargetPatientRow."Patient";

        insert into xrayinfo values vXRayInfoRow;

        vCount2 := vCount2 + 1;

      end if;



    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ptprev rows inserted.',vParams);

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount2 || ' xrayinfo rows inserted.',vParams);

    

    -- Create ptprevh records

      -- created by trigger on ptprev

    

    -- Create ptphys Records    

    for cPtPhys in curPtPhys(pSourcePatient) loop

      cPtPhys."PtPhys" := ptphys_Ptphys_seq.nextval;

      cPtPhys."Patient" := vTargetPatientRow."Patient";

      insert into ptphys values cPtPhys;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptphys rows inserted.',vParams);

    

    -- Create ptemploy Records

    vCount := 0;

    for cPtEmploy in curPtEmploy(pSourcePatient) loop

      cPtEmploy."Patient" := vTargetPatientRow."Patient";

      vCount := vCount + 1;

      insert into ptemploy values cPtEmploy;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ptemploy rows inserted.',vParams);

    

    -- Create Prescription Records

    vCount := 0;

    for cPrescrip in curPrescrip(pSourcePatient) loop

      cPrescrip."Prescription" := prescrip_Prescription_seq.nextval;

      cPrescrip."Patient" := vTargetPatientRow."Patient";

      vCount := vCount + 1;

      insert into prescrip values cPrescrip;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' prescrip rows inserted.',vParams);

    

    -- Create ptguar Records

    --  Only copy 'Self' Relationships

    vCount := 0;

    for cPtGuar in curPtGuar(pSourcePatient) loop

      cPtGuar."Patient" := vTargetPatientRow."Patient";

      cPtGuar."RespPatient" := vTargetPatientRow."Patient";

      insert into ptguar values cPtGuar;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ptguar rows inserted.',vParams);

  

    -- Create ptmanage Records

    vCount := 0;

    for cPtManage in curPtManage(pSourcePatient) loop

      cPtManage."Patient" := vTargetPatientRow."Patient";

      insert into ptmanage values cPtManage;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ptmanage rows inserted.',vParams);

  

    -- Create ptmanagh Records

    vCount := 0;

    for cPtManagH in curPtManagH(pSourcePatient) loop

      cPtManagH."Patient" := vTargetPatientRow."Patient";

      cPtManagH."PtManageHist" := ptmanagh_Ptmanagehist_seq.nextval;

      insert into ptmanagh values cPtManagH;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ptmanagh rows inserted.',vParams);

    

    -- Create ptfacul Records

    vCount := 0;

    for cPtFacul in curPtFacul(pSourcePatient) loop

      cPtFacul."PtFacul" := ptfacul_Ptfacul_seq.nextval;

      cPtFacul."Patient" := vTargetPatientRow."Patient";

      insert into ptfacul values cPtFacul;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ptfacul rows inserted.',vParams);

    

    -- Create ptneed Records

    begin

      select "Code" into vDefaultNeed from needsts where "IsDefault" = 1 and "Inactive" = 0;

    exception

      when no_data_found then

        vDefaultNeed := ' ';

    end;

    vCount := 0;

    for cPtNeed in curPtNeed(pSourcePatient) loop

      cPtNeed."PtNeed" := ptneed_Ptneed_seq.nextval;

      cPtNeed."Patient" := vTargetPatientRow."Patient";

      cPtNeed."Assigned" := 0;

      cPtNeed."NeedSts" := vDefaultNeed;

      insert into ptneed values cPtNeed;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ptneed rows inserted.',vParams);

    

    -- Create ptneehis Records

      -- Created by trigger on ptneed

  

    -- Create ptnote Records

    vCount := 0;

    for cPtNote in curPtNote(pSourcePatient) loop

      cPtNote."PtNote" := ptnote_Ptnote_seq.nextval;

      cPtNote."Patient" := vTargetPatientRow."Patient";

      insert into ptnote values cPtNote;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ptnote rows inserted.',vParams);

    

    -- Create ptnoteh Records

      -- Created by trigger on ptnote

      /*

    insert into ptnoteh (

      select 

        ptnotehRecords_Ptnotehistory_seq.nextval,

        ptn.*

      from

        ptnote ptn

      where

        ptn."Patient" = vTargetPatientRow."Patient"

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptnoteh rows inserted.',vParams);

    */

    

    -- Create ptrefer Records

    vCount := 0;

    for cPtRefer in curPtRefer(pSourcePatient) loop

      cPtRefer."PtRefer" := ptrefer_Ptrefer_seq.nextval;

      cPtRefer."Patient" := vTargetPatientRow."Patient";

      insert into ptrefer values cPtRefer;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ptrefer rows inserted.',vParams);

    

    -- Create ptrefhis Records

    /* Created by a trigger on ptrefer

    insert into ptrefhis (

      select 

        ptrefhiRecords_Ptrefhis_seq.nextval,

        ptr.*

      from

        ptrefer ptr

      where

        ptr."Patient" = vTargetPatientRow."Patient"

    );

    */

    

    -- Create ptxray Records

    vCount := 0;

    for cPtXRay in curPtXRay(pSourcePatient) loop

      cPtXRay."PtXRay" := ptxray_Ptxray_seq.nextval;

      cPtXRay."Patient" := vTargetPatientRow."Patient";

      insert into ptxray values cPtXRay;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ptxray rows inserted.',vParams);

    

    -- Create ptxrahis Records

    /* Created by a Trigger on ptxray

    insert into ptxrahis (

      select 

        ptxrahiRecords_Ptxrahis_seq.nextval,

        1,

        ptx.*

      from

        ptxray ptx

      where

        ptx."Patient" = vTargetPatientRow."Patient"

    );

    */

    

    pvSuccess := true;

  end CopyPatientRecords_P;



  -- Copy treatme2, trx and associated records from pSourcePatient to pTargetPatient

  PROCEDURE copytreatmentrecords_p(IN psourcepatient numeric, IN ptargetpatient numeric, INOUT pvmapaudit numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN pcopyinsurance character varying DEFAULT '0'::character varying) IS

    -- cursors

    cursor curDetail2(pId number) is 

      select * from detail2 where "PId" = pId;  

    cursor curDepLimit(pId number) is

      select * from deplimit where "Patient" = pId;

    cursor curTreatme2Map(pAudit audithis."Audit"%type) is

      select

        OldT2."Auto" "OldId",

        NewT2."TargetId" "Auto",

        nvl(PreT2."TargetId",0) "PreId",

        decode(substr(OldT2."ParentId",1,1),'-',-NewT2."TargetId",ParentT2."TargetId") "ParentId",

        nvl(NewDtx."TargetId",0) "TxPTx"  -- SF-00152633

      from 

        treatme2 OldT2

        inner join AX_Map NewT2 on NewT2."SourceId" = OldT2."Auto" and NewT2."TableName" = 'TREATME2' and NewT2."Audit" = pAudit

        left outer join AX_Map PreT2 on PreT2."SourceId" = OldT2."PreId" and PreT2."TableName" = 'TREATME2' and PreT2."Audit" = pAudit

        left outer join AX_Map ParentT2 on ParentT2."SourceId" = OldT2."ParentId" and ParentT2."TableName" = 'TREATME2' and ParentT2."Audit" = pAudit

        left outer join ax_map NewDtx on NewDtx."SourceId" = OldT2."TxPTx" and NewDtx."TableName" = 'TXPTX' and NewDtx."Audit" = pAudit  -- SF-00152633

    ;  

    cursor curChartLnkMap(pAudit audithis."Audit"%type) is

      select

        cl."Id" "SourceId",

        NewCL."TargetId",

        NewT2A."TargetId" "Auto",

        NewT2P."TargetId" "Previous"

      from 

        chartlnk cl

        inner join AX_Map NewCL on NewCL."SourceId" = cl."Id" and NewCL."TableName" = 'CHARTLNK' and NewCL."Audit" = pAudit

        inner join AX_Map NewT2A on NewT2A."SourceId" = cl."Auto" and NewT2A."TableName" = 'TREATME2' and NewT2A."Audit" = pAudit

        left outer join AX_Map NewT2P on NewT2P."SourceId" = cl."Previous" and NewT2P."TableName" = 'TREATME2' and NewT2P."Audit" = pAudit

    ;

    cursor curGraphHisMap(pAudit audithis."Audit"%type) is

      select

        gh."GraphHis",

        NewGP2."SourceId",

        NewGP2."TargetId",

        NewT2."TargetId" "TxId",

        NewDtx."TargetId" "TxPTx" 

      from

        (

          select

            max(ghs."GraphHis") over (partition by ghs."Auto") "MaxGraphHis",

            ghs.*

          from

            graphhis ghs

        ) gh

        inner join ax_map NewGP2 on NewGP2."SourceId" = gh."Auto" and NewGP2."TableName" = 'GRAPHP2' and NewGP2."Audit" = pAudit

        inner join ax_map NewT2 on NewT2."SourceId" = gh."TxId" and NewT2."TableName" = 'TREATME2' and NewT2."Audit" = pAudit

        left outer join ax_map NewDtx on NewDtx."SourceId" = gh."TxPTx" and NewDtx."TableName" = 'TXPTX' and NewDtx."Audit" = pAudit

      where

        gh."GraphHis" <> gh."MaxGraphHis" or

        gh."Deleted" = 1

    ;  

    cursor curGraphP2Map(pAudit audithis."Audit"%type) is

      select

        NewGP2."SourceId",

        NewGP2."TargetId",

        NewT2."TargetId" "TxId",

        NewDtx."TargetId" "TxPTx"

      from

        graphp2 gp2

        inner join ax_map NewGP2 on NewGP2."SourceId" = gp2."Auto" and NewGP2."TableName" = 'GRAPHP2' and NewGP2."Audit" = pAudit

        left outer join ax_map NewT2 on NewT2."SourceId" = gp2."TxId" and NewT2."TableName" = 'TREATME2' and NewT2."Audit" = pAudit

        left outer join ax_map NewDtx on NewDtx."SourceId" = gp2."TxPTx" and NewDtx."TableName" = 'TXPTX' and NewDtx."Audit" = pAudit

    ;  

    cursor curPtPolMap(pAudit audithis."Audit"%type) is

      select

        NewP."SourceId",

        NewP."TargetId"

      from

        ax_map NewP

      where

        NewP."TableName" = 'PTPOL' and

        NewP."Audit" = pAudit

    ;

    cursor curTRXMap(pAudit audithis."Audit"%type,pId number) is

      select

        trx."Id",

        trx."Type",

        trx."Treatment",

        NewOrigRow."TargetId" "OrigRecNo",

        nvl(NewPol1."TargetId",0) "PolicyId1",

        nvl(NewPol2."TargetId",0) "PolicyId2",

        nvl(NewPol3."TargetId",0) "PolicyId3",

        NewT2."TargetId" "Treatme2",

        NewTT."TargetId" "TRXTreatment",

        NewTP."TargetId" "TRXPlanned"

      from

        trx trx

        inner join ax_map NewOrigRow on NewOrigRow."SourceId" = trx."OrigRecNo" and NewOrigRow."TableName" = 'ORIGREC' and NewOrigRow."Audit" = pAudit

        left outer join ax_map NewPol1 on NewPol1."SourceId" = trx."PolicyId1" and NewPol1."TableName" = 'PTPOL' and NewPol1."Audit" = pAudit

        left outer join ax_map NewPol2 on NewPol2."SourceId" = trx."PolicyId2" and NewPol2."TableName" = 'PTPOL' and NewPol2."Audit" = pAudit

        left outer join ax_map NewPol3 on NewPol3."SourceId" = trx."PolicyId3" and NewPol3."TableName" = 'PTPOL' and NewPol3."Audit" = pAudit

        left outer join ax_map NewT2 on NewT2."SourceId" = trx."ChartTrx" and NewT2."TableName" = 'TREATME2' and NewT2."Audit" = pAudit

        left outer join ax_map NewTT on NewTT."SourceId" = trx."Id" and NewTT."TableName" = 'TRXTREATMENT' and NewTT."Audit" = pAudit and trx."Type" = 1

        left outer join ax_map NewTP on NewTP."SourceId" = trx."Id" and NewTP."TableName" = 'TRXPLANNED' and NewTP."Audit" = pAudit and trx."Type" = 5

      where

        trx."Patient" = pId and

        trx."Type" in (1,5)

    ; 

    cursor curTrxContMap(pAudit audithis."Audit"%type) is

      select 

        tc."OrigRecNo" "OldOrigRecNo",

        NewOrigRow."TargetId" "NewOrigRecNo",

        tc."Contract" "OldContract",

        NewC."TargetId" "NewContract"

      from

        trxcont tc

        inner join ax_map NewOrigRow on NewOrigRow."SourceId" = tc."OrigRecNo" and NewOrigRow."TableName" = 'ORIGREC' and NewOrigRow."Audit" = pAudit

        inner join ax_map NewC on NewC."SourceId" = tc."Contract" and NewC."TableName" = 'CONTRACT' and NewC."Audit" = pAudit

    ;

    cursor curTRXMedMap(pAudit audithis."Audit"%type,pId number) is

      select 

        trx."Id",

        trx."Type",

        trx."Treatment",

        trxm."ChartLnk" "OldChartLnk",

        NewTT."TargetId" "TRXTreatment",

        NewTP."TargetId" "TRXPlanned",

        nvl(NewCL."TargetId",0) "NewChartLnk"

      from

        trx trx

        inner join trxmed trxm on trxm."Type" = trx."Type" and trxm."Id" = trx."Id" and trxm."Treatment" = trx."Treatment"

        left outer join ax_map NewTT on NewTT."SourceId" = trx."Id" and NewTT."TableName" = 'TRXTREATMENT' and NewTT."Audit" = pAudit and trx."Type" = 1

        left outer join ax_map NewTP on NewTP."SourceId" = trx."Id" and NewTP."TableName" = 'TRXPLANNED' and NewTP."Audit" = pAudit and trx."Type" = 5

        left outer join ax_map NewCL on NewCL."SourceId" = trxm."ChartLnk" and NewCL."TableName" = 'CHARTLNK' and NewCL."Audit" = pAudit

      where

        trx."Patient" = pId and

        trx."Type" in (1,5)

    ;

    cursor curLabOrderMap(pAudit audithis."Audit"%type) is

      select 

        NewLO."SourceId",

        NewLO."TargetId",

        nvl(NewOrigRow."TargetId",0) "OrigRecNo"

      from 

        laborder lo

        inner join ax_map NewLO on NewLO."SourceId" = lo."LabOrder" and NewLO."TableName" = 'LABORDER' and NewLO."Audit" = pAudit

        left outer join ax_map NewOrigRow on NewOrigRow."SourceId" = lo."OrigRecNo" and NewOrigRow."TableName" = 'ORIGREC' and NewOrigRow."Audit" = pAudit

    ;   

    cursor curLabOTRXMap(pAudit audithis."Audit"%type) is

      select 

        NewLO."SourceId" "OldLabOrder",

        NewLO."TargetId" "NewLabOrder",

        nvl(NewOrigRow."SourceId",0) "OldOrigRecNo",

        nvl(NewOrigRow."TargetId",0) "NewOrigRecNo"

      from 

        labotrx lo

        inner join ax_map NewLO on NewLO."SourceId" = lo."LabOrder" and NewLO."TableName" = 'LABORDER' and NewLO."Audit" = pAudit

        left outer join ax_map NewOrigRow on NewOrigRow."SourceId" = lo."OrigRecNo" and NewOrigRow."TableName" = 'ORIGREC' and NewOrigRow."Audit" = pAudit

    ;   

    -- P189-155143 added

    cursor curFamLimit(pPolicyId ptpol."PolicyId"%type) is

      select * from famlimit where "PolicyId" = pPolicyId;

      

    -- Records

    vChartLnkRow chartlnk%rowtype;

    vGraphP2Row  graphp2%rowtype;

    vGraphHisRow graphhis%rowtype;

    vLabOrderRow laborder%rowtype;

    vLabOTrxRow labotrx%rowtype;

    vPtDependRow ptdepend%rowtype;

    vPtPolRow ptpol%rowtype;    

    vTreatme2Row treatme2%rowtype;

    vTRXRow trx%rowtype;

    vTRXAddlRow trxaddl%rowtype;

    vTRXContRow trxcont%rowtype;

    vTRXMedRow trxmed%rowtype;

    -- Variables

    vCount number;

    vCount2 number;

    vCount3 number; -- P189-155143

    vSourcePatient2 patient2."Auto"%type;

    vTargetPatient2 patient2."Auto"%type;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    pvMapAudit := ax_pkg.GetMapAudit_F(pvMapAudit,vParams);

    

    select "Auto" into vSourcePatient2 from patient2 where "PtxPId" = pSourcePatient;

    select "Auto" into vTargetPatient2 from patient2 where "PtxPId" = pTargetPatient;

    

  -- Create Detail2 Records -- details on chart

    vCount := 0;

    for cDetail2 in curDetail2(vSourcePatient2) loop

      cDetail2."Auto" := detail2_auto_seq.nextval;

      cDetail2."PId" := vTargetPatient2;

      insert into Detail2 values cDetail2;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' detail2 rows inserted.',vParams);

  

    -- Map Treatme2 Records

    begin

      select 1 into vCount from ax_map where "Audit" = pvMapAudit and "TableName" = 'TREATME2' and rownum = 1;

    exception

      when no_data_found then

        insert into ax_map (

          select 

            pvMapAudit,

            'TREATME2', 

            "Auto", 

            treatme2_auto_seq.nextval 

            ,null,null

          from treatme2 

          where "PId" = vSourcePatient2

        );

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

    end;

    

    -- Create treatme2 Records

    vCount := 0;

    for cTreatme2Map in curTreatme2Map(pvMapAudit) loop

      select * into vTreatme2Row from treatme2 where "Auto" = cTreatme2Map."OldId";

      vTreatme2Row."Auto" := cTreatme2Map."Auto";

      vTreatme2Row."PreId" := cTreatme2Map."PreId";

      vTreatme2Row."ParentId" := cTreatme2Map."ParentId";

      vTreatme2Row."PId" := vTargetPatient2;

      vTreatme2Row."TxPTx" := cTreatme2Map."TxPTx";  -- SF-00152633

      insert into treatme2 values vTreatme2Row;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' treatme2 rows inserted.',vParams);

     

    -- Map ChartLnk Records

    insert into ax_map (

      select 

        pvMapAudit,

        'CHARTLNK', 

        "Id", 

        chartlnk_id_seq.nextval 

        ,null,null

      from chartlnk 

      where "Patient" = pSourcePatient

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

     

    -- Create chartlnk Records

    for cChartLnkMap in curChartLnkMap(pvMapAudit) loop

      select * into vChartLnkRow from chartlnk where "Id" = cChartLnkMap."SourceId";

      vChartLnkRow."Id" := cChartLnkMap."TargetId";

      vChartLnkRow."Auto" := cChartLnkMap."Auto";

      vChartLnkRow."Previous" := cChartLnkMap."Previous";

      vChartLnkRow."Patient" := pTargetPatient;

      insert into chartlnk values vChartLnkRow;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' chartlnk rows inserted.',vParams);

    

    -- Map graphp2 Records

    insert into ax_map (

      select 

        pvMapAudit,

        'GRAPHP2', 

        g."Auto", 

        graphp2_auto_seq.nextval 

        ,null,null

      from 

        (

          select distinct

            "Auto"

          from

            graphhis          

          where

            "PId" = vSourcePatient2

        ) g

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

  

    -- Create GraphHis Records

    vCount := 0;

    for cGraphHisMap in curGraphHisMap(pvMapAudit) loop

      select * into vGraphHisRow from graphhis where "GraphHis" = cGraphHisMap."GraphHis";

      vGraphHisRow."GraphHis" := graphhis_graphhis_seq.nextval;    

      vGraphHisRow."Auto" := cGraphHisMap."TargetId";

      vGraphHisRow."PId" := vTargetPatient2;

      vGraphHisRow."TxId" := cGraphHisMap."TxId";

      vGraphHisRow."TxPTx" := cGraphHisMap."TxPTx";

      insert into graphhis values vGraphHisRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' graphhis rows inserted.',pParams);

       

    -- Create graphp2 Records

    vCount := 0;

    for cGraphP2Map in curGraphP2Map(pvMapAudit) loop

      select * into vGraphP2Row from graphp2 where "Auto" = cGraphP2Map."SourceId";

      vGraphP2Row."Auto" := cGraphP2Map."TargetId";

      vGraphP2Row."PId" := vTargetPatient2;

      vGraphP2Row."TxId" := cGraphP2Map."TxId";

      vGraphP2Row."TxPTx" := cGraphP2Map."TxPTx";

      insert into graphp2 values vGraphP2Row;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' graphp2 rows inserted.',pParams);

     

    -- Update graphhis Records Created by Trigger on GraphP2, so that the Add/Edit flags are correct

    update graphhis

    set "HistoryType" = 2

    where "GraphHis" in (

      select

        "GraphHis"

      from

        graphhis

      where

        "PId" = vSourcePatient2 and

        "HistoryType" = 1 and

        "GraphHis" not in (

          select 

            min("GraphHis") over (partition by "Auto")

          from 

            graphhis

          where

            "PId" = vSourcePatient2 and

            "HistoryType" = 1

        )

    );



    -- Map OrigrecNo values (treatments and planned treatments)

    insert into ax_map (

      select

        pvMapAudit,

        'ORIGREC', 

        "OrigRecNo", 

        trx_origrecno_seq.nextval 

        ,null,null

      from 

        (

          select 

            distinct("OrigRecNo")

          from

            trx    

          where    

            "Patient" = pSourcePatient and

            "Type" in (1,5)

        )      

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

    -- Map Id values (planned treatments)

    insert into ax_map (

      select

        pvMapAudit,

        'TRXTREATMENT', 

        "Id", 

        trx_id_treatment_seq.nextval

        ,null,null

      from 

        (

          select 

            distinct("Id")

          from

            trx    

          where    

            "Patient" = pSourcePatient and

            "Type" = 1

        )      

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

    -- Map Id values (planned treatments)

    insert into ax_map (

      select

        pvMapAudit,

        'TRXPLANNED', 

        "Id", 

        trx_id_Plannedtreatment_seq.nextval

        ,null,null

      from 

        (

          select 

            distinct("Id")

          from

            trx    

          where    

            "Patient" = pSourcePatient and

            "Type" = 5

        )      

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

    

  -- Insurance

    if pCopyInsurance = '1' then

      -- Map ptpol Records

      insert into ax_map (

        select 

          pvMapAudit,

          'PTPOL', 

          "PolicyId", 

          ptpol_Policyid_seq.nextval 

          ,null,null

        from 

          ptpol

        where

          "Patient" = pSourcePatient

      );

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

       

      -- Create ptpol Records    

      vCount := 0;

      vCount2 := 0;

      for cPtPolMap in curPtPolMap(pvMapAudit) loop

        select * into vPtPolRow from ptpol where "PolicyId" = cPtPolMap."SourceId";

        vPtPolRow."PolicyId" := cPtPolMap."TargetId";

        vPtPolRow."Family" := pTargetPatient;    

        vPtPolRow."Patient" := pTargetPatient;

        vPtPolRow."SharedEntryId" := policy_sharedentryid_seq.nextval;    

        insert into ptpol values vPtPolRow;

        

        --POLINRecords_PKG.InsertCatLimits(pTargetPatient, pTargetPatient, cPtPolMap."TargetId");

        --POLINRecords_PKG.InsertItemLimits(pTargetPatient, pTargetPatient, cPtPolMap."TargetId");

        --POLINRecords_PKG.InsertCatLimitsUsingTempl(pTargetPatient, pTargetPatient, cPtPolMap."TargetId");

        --POLINRecords_PKG.InsertItemLimitsUsingTempl(pTargetPatient, pTargetPatient, cPtPolMap."TargetId");

        

        vCount := vCount + 1;

        -- Create ptdepend Record

        begin

          select * into vPtDependRow from ptdepend where "PolicyId" = cPtPolMap."SourceId" and "Patient" = pSourcePatient and "Deleted" = 0;

          vPtDependRow."Patient" := pTargetPatient;    

          vPtDependRow."PolicyId" := cPtPolMap."TargetId";

          insert into ptdepend values vPtDependRow;

          vCount2 := vCount2 + 1;

        exception

          when no_data_found then

            null; -- only need to add record if source exists

        end;

        

        -- P189-155143 added to create famlimit records

        vCount3 := 0;

        for cFamLimit in curFamLimit(cPtPolMap."SourceId") loop

          cFamLimit."PolicyId" := cPtPolMap."TargetId";

          insert into famlimit values cFamLimit;

          vCount3 := vCount3 + 1;

        end loop;

      end loop;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ptpol rows inserted.',vParams);

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount2 || ' ptdepend rows inserted.',vParams);

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount3 || ' famlimit rows inserted.',vParams); -- P189-155143

  

      -- Create deplimit Records

      vCount := 0;

      for cDepLimit in curDepLimit(pSourcePatient) loop

        cDepLimit."Patient" := pTargetPatient;

        cDepLimit."DeductBalance" := cDepLimit."Deduct";

        cDepLimit."LimitBalance" := cDepLimit."Limit";

        insert into deplimit values cDepLimit;

        vCount := vCount + 1;

      end loop;    

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' deplimit rows inserted.',vParams);

    end if; -- pCopyInsurance

    

    -- Create trx Records

    vCount := 0;

    vCount2 := 0;

    for cTRXMap in curTRXMap(pvMapAudit,pSourcePatient) loop

      select * into vTRXRow from trx where "Type" = cTRXMap."Type" and "Id" = cTRXMap."Id" and "Treatment" = cTRXMap."Treatment";

      if cTRXMap."Type" = 5 then

        vTRXRow."Id" := cTRXMap."TRXPlanned";

      elsif cTRXMap."Type" = 1 then

        vTRXRow."Id" := cTRXMap."TRXTreatment";

      end if;

      vTRXRow."OrigRecNo" := cTRXMap."OrigRecNo";

      vTRXRow."Patient" := pTargetPatient;

      vTRXRow."Family" := pTargetPatient;

      vTRXRow."ChartTrx" := cTRXMap."Treatme2";

      -- Insurance Links

      if pCopyInsurance = '1' then

        -- Insurance One

        vTRXRow."PolicyId1" := cTRXMap."PolicyId1";      

        -- Insurance Two

        vTRXRow."PolicyId2" := cTRXMap."PolicyId2";

        -- Insurance Three

        vTRXRow."PolicyId3" := cTRXMap."PolicyId3";

      else -- if no insurance

        vTRXRow."PolicyId1" := 0;

        vTRXRow."Deduct1" := 0;

        vTRXRow."Assign1" := 0;

        vTRXRow."Amount1" := 0;  -- SF-00148848

        -- Insurance Two

        vTRXRow."PolicyId2" := 0;

        vTRXRow."Deduct2" := 0;

        vTRXRow."Assign2" := 0;

        vTRXRow."Amount2" := 0;  -- SF-00148848

        -- Insurance Three

        vTRXRow."PolicyId3" := 0;

        vTRXRow."Deduct3" := 0;

        vTRXRow."Assign3" := 0;

        vTRXRow."Amount3" := 0;  -- SF-00148848

        -- Fields based on Insurance

        vTRXRow."CustomaryTotal" := 0;

        vTRXRow."InsTotal" := 0;

        vTRXRow."TrxDep" := 0;           -- should we bring this over?

      end if;

      -- Balances

      -- SF-00148848 Clear all amount fields on in process and completed treatment

      if vTRXRow."Type" = 1 then

        vTRXRow."CustomaryTotal" := 0;

        vTRXRow."Total" := 0;

        vTRXRow."InsTotal" := 0;

        vTRXRow."Amount1" := 0;

        vTRXRow."Amount2" := 0;

        vTRXRow."Amount3" := 0;

      end if;

      vTRXRow."Payed" := 0;

      vTRXRow."InsPayed" := 0;



      vTRXRow."InsPayed1" := 0;

      vTRXRow."InsAdj1" := 0;

      vTRXRow."InsPayed2" := 0;

      vTRXRow."InsAdj2" := 0;

      vTRXRow."InsPayed3" := 0;

      vTRXRow."InsAdj3" := 0;

      vTRXRow."PtAdj" := 0;

      vTRXRow."InsAdj" := 0;    

      vTRXRow."InsTransfer1" := 0;

      vTRXRow."InsTransfer2" := 0;

      vTRXRow."InsTransfer3" := 0;

      vTRXRow."InsTransfer" := 0;

      -- Other Cleared Information

      vTRXRow."Grading" := 0;          -- No need to carry over past grades

      vTRXRow."PayPlanId" := 0;        -- Pay Plans not carried over

      vTRXRow."DiscountedPmtId" := 0;  -- Should be 0 anyway, not used for type 1 or 5

      vTRXRow."InsPmtId" := 0;         -- Not carrying over insurance payments

      insert into trx values vTRXRow;

      vCount := vCount + 1;

      begin

        select * into vTRXAddlRow from trxaddl where "Type" = cTRXMap."Type" and "Id" = cTRXMap."Id" and "Treatment" = cTRXMap."Treatment";

        vTRXAddlRow."Id" := vTRXRow."Id";

        insert into trxaddl values vTRXAddlRow;

        vCount2 := vCount2 + 1;

      exception

        when no_data_found then

          null;

      end;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' trx rows inserted.',vParams);

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount2 || ' trxaddl rows inserted.',vParams);

  

    -- Create history Records

    insert into history (

      select 

        history_history_seq.nextval,

        1,

        trx.*

      from

        trx trx

      where

        trx."Patient" = pTargetPatient and

        trx."Type" in (1,5)

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' history rows inserted.',vParams);

    

    -- Create trxcont Records

    vCount := 0;

    for cTrxContMap in curTrxContMap(pvMapAudit) loop

      select * into vTrxContRow from trxcont where "OrigRecNo" = cTrxContMap."OldOrigRecNo" and "Contract" = cTrxContMap."OldContract";

      vTrxContRow."OrigRecNo" := cTrxContMap."NewOrigRecNo";

      vTrxContRow."Contract" := cTrxContMap."NewContract";

      vTrxContRow."TrxCont" := trxcont_trxcont_seq.nextval;

      vCount := vCount + 1;

      insert into trxcont values vTrxContRow;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' trxcont rows inserted.',vParams);

    

    -- Create trxmed Records

    vCount := 0;

    for cTrxMedMap in curTRXMedMap(pvMapAudit,pSourcePatient) loop

      select * into vTrxMedRow from trxmed where "Type" = cTrxMedMap."Type" and "Id" = cTrxMedMap."Id" and "Treatment" = cTrxMedMap."Treatment" and "ChartLnk" = cTrxMedMap."OldChartLnk";

      vTrxMedRow."Patient" := pTargetPatient;

      if cTrxMedMap."Type" = 1 then

        vTrxMedRow."Id" := cTrxMedMap."TRXTreatment";

      elsif cTrxMedMap."Type" = 5 then

        vTrxMedRow."Id" := cTrxMedMap."TRXPlanned";

      end if;          

      vTrxMedRow."ChartLnk" := cTrxMedMap."NewChartLnk";

      vCount := vCount + 1;

      insert into trxmed values vTrxMedRow;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' trxmed rows inserted.',vParams);

    

    -- Map LabOrder Records

    insert into ax_map (

      select 

        pvMapAudit,

        'LABORDER', 

        "LabOrder", 

        laborder_laborder_seq.nextval 

        ,null,null

      from laborder 

      where 

        "Patient" = pSourcePatient and

        "RemakeLabOrder" = 0 -- do not copy remakes        

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

    

    -- Create laborder Records

    vCount := 0;

    for cLabOrderMap in curLabOrderMap(pvMapAudit) loop

      select * into vLabOrderRow from laborder where "LabOrder" = cLabOrderMap."SourceId";

      vLabOrderRow."LabOrder" := cLabOrderMap."TargetId";

      vLabOrderRow."OrigRecNo" := cLabOrderMap."OrigRecNo";

      vLabOrderRow."Patient" := pTargetPatient;

      -- Reset

      vLabOrderRow."LabOut" := 0;

      vLabOrderRow."DateOut" := null;

      vLabOrderRow."TimeOut" := 0;

      vLabOrderRow."CurrentItem" := 1;

      if vLabOrderRow."Status" = 1 then

        vLabOrderRow."Status" := 0; -- Reset In Progress Orders to Unapproved Status -- confirm this

      end if;

      vCount := vCount + 1;

      insert into laborder values vLabOrderRow;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' laborder rows inserted.',vParams);

      

    -- Create labotrx Records

    vCount := 0;

    for cLabOTRXMap in curLabOTRXMap(pvMapAudit) loop

      select * into vLabOTrxRow from labotrx where "LabOrder" = cLabOTRXMap."OldLabOrder" and "OrigRecNo" = cLabOTRXMap."OldOrigRecNo";

      vLabOTrxRow."LabOrder" := cLabOTRXMap."NewLabOrder";

      vLabOTrxRow."OrigRecNo" := cLabOTRXMap."NewOrigRecNo";

      vCount := vCount + 1;

      insert into labotrx values vLabOTrxRow;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' labotrx rows inserted.',vParams);



    -- SF-00152633 Create txdiag records

    insert into txdiag (

      select 

        NewT2."TargetId",

        "DiagCode"

      from

        txdiag txd

        inner join ax_map NewT2 on NewT2."SourceId" = txd."ChartTrx" and NewT2."TableName" = 'TREATME2' and NewT2."Audit" = pvMapAudit

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,sql%rowcount || ' txdiag rows inserted.',vParams);



  end CopyTreatmentRecords_P;





  -- Copy Perio

  PROCEDURE copyperiorecords_p(IN psourcepatient numeric, IN ptargetpatient numeric, INOUT pvmapaudit numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN pcopyinsurance character varying DEFAULT '0'::character varying) IS

    -- Cursors

    cursor curPtPerioMap(pAudit audithis."Audit"%type) is

      select

        NewP."TargetId",

        NewP."SourceId"

      from

        ax_map NewP

      where

        NewP."TableName" = 'PTPERIO' and

        NewP."Audit" = pAudit

    ;

    cursor curPtPerCoMap(pAudit audithis."Audit"%type,pId number) is

      select

        pc."PtPerCo",

        NewP."TargetId" "PtPerio"

      from

        ptperco pc 

        inner join ax_map NewP on NewP."SourceId" = pc."PtPerio" and NewP."TableName" = 'PTPERIO' and NewP."Audit" = pAudit

      where

        pc."Patient" = pId and

        pc."Deleted" = 0

    ;

    cursor curPtPerItMap(pAudit audithis."Audit"%type,pId number) is

      select

        pi."PtPerio" "OldPtPerio",

        pi."PerCond",

        pi."Site",

        pi."Section",

        NewP."TargetId" "PtPerio"

      from

        ptperit pi 

        inner join ptperio ptp on ptp."PtPerio" = pi."PtPerio"

        inner join ax_map NewP on NewP."SourceId" = pi."PtPerio" and NewP."TableName" = 'PTPERIO' and NewP."Audit" = pAudit

      where

        ptp."Patient" = pId and

        ptp."Deleted" = 0 and

        pi."Deleted" = 0

    ;  

    cursor curPtPerStMap(pAudit audithis."Audit"%type) is

      select

        NewPPS."TargetId",

        NewPPS."SourceId"

      from

        ax_map NewPPS

      where

        NewPPS."TableName" = 'PTPERST' and

        NewPPS."Audit" = pAudit

    ;

    -- Records

    vPtPerioRow  ptperio%rowtype;

    vPtPerCoRow  ptperco%rowtype;

    vPtPeritRow  ptperit%rowtype;

    vPtPerstRow  ptperst%rowtype;

    vPtpstHisRow ptpsthis%rowtype;

    -- Variables

    vCount number;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    pvMapAudit := ax_pkg.GetMapAudit_F(pvMapAudit,vParams);

    

    -- Map ptperio Records

    insert into ax_map (

      select 

        pvMapAudit,

        'PTPERIO', 

        "PtPerio", 

        ptperio_Ptperio_seq.nextval 

        ,null,null

      from 

        ptperio

      where

        "Patient" = pSourcePatient and

        "Deleted" = 0

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

    

    -- Create pitemcol Records

    vCount := 0;

    for cPtPerioMap in curPtPerioMap(pvMapAudit) loop

      select * into vPtPerioRow from ptperio where "PtPerio" = cPtPerioMap."SourceId";

      vPtPerioRow."PtPerio" := cPtPerioMap."TargetId";

      vPtPerioRow."Patient" := pTargetPatient;

      vPtPerioRow."OrigPtPerio" := cPtPerioMap."TargetId";

      insert into ptperio values vPtPerioRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ptperio rows inserted.',vParams);

    

    -- Create ptperhis Records

      -- created by trigger on ptperio

    /*

    insert into ptperhis (

      select 

        ptperhis_id_seq.nextval,

        ptp.*

      from

        ptperio ptp

      where

        ptp."Patient" = pTargetPatient

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptperhis rows inserted.',vParams);

    */

    

    -- Create ptpercol Records

    vCount := 0;

    for cPtPerCoMap in curPtPerCoMap(pvMapAudit,pSourcePatient) loop

      select * into vPtPerCoRow from ptperco where "PtPerCo" = cPtPerCoMap."PtPerCo";

      vPtPerCoRow."PtPerCo" := ptperco_Ptperco_seq.nextval;

      vPtPerCoRow."PtPerio" := cPtPerCoMap."PtPerio";

      vPtPerCoRow."Patient" := pTargetPatient;

      insert into ptperco values vPtPerCoRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ptperco rows inserted.',vParams);

    

    -- Create ptperit Records

    vCount := 0;

    for cPtPerItMap in curPtPerItMap(pvMapAudit,pSourcePatient) loop

      select * into 

        vPtPerItRow from ptperit 

      where 

        "PtPerio" = cPtPerItMap."OldPtPerio" and 

        "PerCond" = cPtPerItMap."PerCond" and 

        "Site" = cPtPerItMap."Site" and 

        "Section" = cPtPerItMap."Section" 

      ;

      vPtPerItRow."PtPerio" := cPtPerItMap."PtPerio";

      insert into ptperit values vPtPerItRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ptperit rows inserted.',vParams);

    

    -- Map ptperst Records

    insert into ax_map (

      select 

        pvMapAudit,

        'PTPERST', 

        "PtPerSt", 

        ptperst_Ptperst_seq.nextval 

        ,null,null

      from 

        ptperst

      where

        "Patient" = pSourcePatient

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

    

    -- Create ptperst Records

    vCount := 0;

    for cPtPerStMap in curPtPerStMap(pvMapAudit) loop

      select * into vPtPerStRow from ptperst where "PtPerSt" = cPtPerStMap."SourceId";

      vPtPerStRow."PtPerSt" := cPtPerStMap."TargetId";

      vPtPerStRow."Patient" := pTargetPatient;

      insert into ptperst values vPtPerStRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ptperst rows inserted.',vParams);

    

    -- Create ptpsthis Records

      -- Created by trigger on ptpsthis

      /*

    insert into ptpsthis (

      select 

        ptpsthis_id_seq.nextval,

        ptps.*

      from

        ptperst ptps

      where

        ptps."Patient" = pSourcePatient

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptpsthis rows inserted.',vParams);

    */

  end CopyPerioRecords_P;

  



  -- Copy General Notes

    -- If you wish to copy notes tied to other records, make sure to copy those records FIRST

  PROCEDURE copynotes2records_p(IN psourcepatient numeric, IN ptargetpatient numeric, INOUT pvmapaudit numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    -- Cursors

    cursor curNotes2Map(pAudit audithis."Audit"%type) is 

      select 

        NewN2."SourceId",

        NewN2."TargetId",

        n2."OtherId",

        NewLO."TargetId" "LabOrder"

      from 

        notes2 n2

        inner join ax_map NewN2 on NewN2."SourceId" = n2."Auto" and NewN2."TableName" = 'NOTES2' and NewN2."Audit" = pAudit

        left outer join ax_map NewLO on NewLO."SourceId" = n2."OtherId" and n2."Type" = 2 and NewLO."TableName" = 'LABORDER' and NewLO."Audit" = pAudit

      order by "OtherId"

    ;   

    cursor curNoteOvrMap0(pAudit audithis."Audit"%type,pId number) is

      select

        NewN."SourceId",

        NewN."TargetId",

        nto."Id"

      from

        noteovr nto 

        inner join ax_map NewN on NewN."SourceId" = nto."ParentId" and NewN."TableName" = 'NOTES2' and NewN."Audit" = pAudit

      where

        nto."Patient" = pId and

        nto."Deleted" = 0 and

        nto."Type" = 0

    ;

    -- Records

    vNotes2Row   notes2%rowtype;

    vNoteOvrRow  noteovr%rowtype;

    -- Variables

    vCount number;

    vSourcePatient2 patient2."Auto"%type;

    vTargetPatient2 patient2."Auto"%type;

    vPreviousId number;

    vCurrentId number;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    pvMapAudit := ax_pkg.GetMapAudit_F(pvMapAudit,vParams);

    

    select "Auto" into vSourcePatient2 from patient2 where "PtxPId" = pSourcePatient;

    select "Auto" into vTargetPatient2 from patient2 where "PtxPId" = pTargetPatient;

    

    -- Map Notes2 Records

    insert into ax_map (

      select 

        pvMapAudit,

        'NOTES2', 

        "Auto", 

        notes2_auto_seq.nextval 

        ,null,null

      from notes2 

      where "PId" = vSourcePatient2

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

    

    -- Create Notes2 Records

    vCount := 0;

    for cNotes2Map in curNotes2Map(pvMapAudit) loop    

      select * into vNotes2Row from notes2 where "Auto" = cNotes2Map."SourceId";

    

      -- Populate TxId from previous Treatme2 mapping, if not 0

      if vNotes2Row."TxId" != 0 then

        select "TargetId" into vNotes2Row."TxId" from AX_Map where "TableName" = 'TREATME2' and "SourceId" = vNotes2Row."TxId"

		and "Audit" = pvMapAudit;

      end if;    

      

      -- Does not handle Types 5

      if vNotes2Row."Type"=4 then

        if (vPreviousId = 0 or vPreviousId != vNotes2Row."OtherId") then

          vPreviousId := vNotes2Row."OtherId";

          select notes2_clinicalnote_seq.nextval into vCurrentId from dual;

        end if;

      elsif vNotes2Row."Type"=2 then

        vCurrentId := vNotes2Row."OtherId";

      else

        vCurrentId := cNotes2Map."LabOrder";

      end if;

      

      vNotes2Row."Auto" := cNotes2Map."TargetId";

      vNotes2Row."PId" := vTargetPatient2;

      vNotes2Row."OtherId" := vCurrentId;

      vNotes2Row."OrigId" := vNotes2Row."Auto";

      insert into notes2 values vNotes2Row;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' notes2 rows inserted.',vParams);

    

    -- Create noteovr Records

    vCount := 0;

    for cNoteOverMap in curNoteOvrMap0(pvMapAudit,pSourcePatient) loop

      select * into vNoteOvrRow from noteovr where "Id" = cNoteOverMap."Id"; 

      select noteovr_id_seq.nextval into vNoteOvrRow."Id" from dual;

      vNoteOvrRow."ParentId" := cNoteOverMap."TargetId";

      vNoteOvrRow."Patient" := pTargetPatient;

      insert into noteovr values vNoteOvrRow;

      vCount := vCount + 1;

    end loop;

  end CopyNotes2Records_P;





  -- Copy Contact Notes

  PROCEDURE copycontactnoterecords_p(IN psourcepatient numeric, IN ptargetpatient numeric, INOUT pvmapaudit numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    cursor curPtCont(pId number) is

      select * from ptcont where "Patient" = pId and "Deleted" = 0;

    vCount number;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    pvMapAudit := ax_pkg.GetMapAudit_F(pvMapAudit,vParams);

  -- Create ptcont Records

    vCount := 0;

    for cPtCont in curPtCont(pSourcePatient) loop

      select ptcont_contact_seq.nextval into cPtCont."Contact" from dual;

      cPtCont."Patient" := pTargetPatient;

      insert into ptcont values cPtCont;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ptcont rows inserted.',vParams);

  end CopyContactNoteRecords_P;



 

-- Copy Treatment Planning

  PROCEDURE copytreatmentplanningrecords_p(IN psourcepatient numeric, IN ptargetpatient numeric, INOUT pvmapaudit numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    -- Cursors

/* P189-156750 start

    cursor curComplainMap(pAudit audithis."Audit"%type) is 

      select "TargetId", "SourceId" from ax_map where "TableName" = 'COMPLAIN' and "Audit" = pAudit;

    cursor curProlistMap(pAudit audithis."Audit"%type) is

      select

        NewPL."TargetId",

        NewPL."SourceId",

        nvl(NewC."TargetId",0) "Complaint"

      from

        ax_map NewPL

        inner join prolist OldPL on OldPL."Id" = NewPL."SourceId"

        left outer join ax_map NewC on NewC."SourceId" = OldPL."Complaint" and NewC."TableName" = 'COMPLAIN' and NewC."Audit" = pAudit

      where

        NewPL."TableName" = 'PROLIST' and

        NewPL."Audit" = pAudit

    ;

    cursor curDiagnoseMap(pAudit audithis."Audit"%type) is

      select

        NewD."TargetId",

        NewD."SourceId",

        nvl(NewC."TargetId",0) "Complaint"

      from

        ax_map NewD

        inner join diagnose OldD on OldD."Auto" = NewD."SourceId"

        left outer join ax_map NewC on NewC."SourceId" = OldD."Complaint" and NewC."TableName" = 'COMPLAIN' and NewC."Audit" = pAudit

      where

        NewD."TableName" = 'DIAGNOSE' and

        NewD."Audit" = pAudit

    ;

    cursor curGtxOptMap(pAudit audithis."Audit"%type) is

      select

        NewG."TargetId",

        NewG."SourceId",

        nvl(NewC."TargetId",0) "Complaint"

      from

        ax_map NewG

        inner join gtxopt OldG on OldG."Option" = NewG."SourceId"

        left outer join ax_map NewC on NewC."SourceId" = OldG."Complaint" and NewC."TableName" = 'COMPLAIN' and NewC."Audit" = pAudit

      where

        NewG."TableName" = 'GTXOPT' and

        NewG."Audit" = pAudit

    ;

    cursor curGtxAppIdMap(pAudit audithis."Audit"%type) is

      select

        NewG."TargetId",

        NewG."SourceId",

        gai."ConsultantType"

      from

        gtxappid gai

        inner join ax_map NewG on NewG."SourceId" = gai."Option"

        inner join gtxopt OldG on OldG."Option" = NewG."SourceId"

      where

        NewG."TableName" = 'GTXAPPID' and

        NewG."Audit" = pAudit

    ;

    cursor curGtxPlanMap(pAudit audithis."Audit"%type) is

      select

        NewGP."TargetId",

        NewGP."SourceId",

        NewGO."TargetId" "Option",

        nvl(NewC."TargetId",0) "Complaint"

      from

        ax_map NewGP

        inner join gtxplan OldGP on OldGP."Id" = NewGP."SourceId"

        left outer join ax_map NewGO on NewGO."SourceId" = OldGP."Option" and NewGO."TableName" = 'GTXOPT' and NewGO."Audit" = pAudit

        left outer join ax_map NewC on NewC."SourceId" = OldGP."Complaint" and NewC."TableName" = 'COMPLAIN' and NewC."Audit" = pAudit

      where

        NewGP."TableName" = 'GTXPLAN' and

        NewGP."Audit" = pAudit

    ;

    cursor curDtxOptMap(pAudit audithis."Audit"%type) is

      select

        NewD."TargetId",

        NewD."SourceId",

        nvl(NewC."TargetId",0) "Complaint"

      from

        ax_map NewD

        inner join dtxopt OldD on OldD."Option" = NewD."SourceId"

        left outer join ax_map NewC on NewC."SourceId" = OldD."Complaint" and NewC."TableName" = 'COMPLAIN' and NewC."Audit" = pAudit

      where

        NewD."TableName" = 'DTXOPT' and

        NewD."Audit" = pAudit

    ;

    cursor curDtxAppIdMap(pAudit audithis."Audit"%type) is

      select

        NewD."TargetId",

        NewD."SourceId",

        dai."ConsultantType"

      from

        dtxappid dai

        inner join ax_map NewD on NewD."SourceId" = dai."Option"

        inner join dtxopt OldD on OldD."Option" = NewD."SourceId"

      where

        NewD."TableName" = 'DTXAPPID' and

        NewD."Audit" = pAudit

    ;

    cursor curDtxPlanMap(pAudit audithis."Audit"%type) is

      select

        NewDP."TargetId",

        NewDP."SourceId",

        NewDO."TargetId" "Option",

        nvl(NewC."TargetId",0) "Complaint",

        nvl(NewT."TargetId",0) "Treatmen2Id",

        nvl(NewGP."TargetId",0) "GtxPlanId",

        nvl(NewD."TargetId",0) "Diagnose"

      from

        ax_map NewDP

        inner join dtxplan OldDP on OldDP."Id" = NewDP."SourceId"

        left outer join ax_map NewDO on NewDO."SourceId" = OldDP."Option" and NewDO."TableName" = 'DTXOPT' and NewDO."Audit" = pAudit

        left outer join ax_map NewC on NewC."SourceId" = OldDP."Complaint" and NewC."TableName" = 'COMPLAIN' and NewC."Audit" = pAudit

        left outer join ax_map NewT on NewT."SourceId" = OldDP."Treatmen2Id" and NewT."TableName" = 'TREATME2' and NewT."Audit" = pAudit

        left outer join ax_map NewGP on NewGP."SourceId" = OldDP."GtxPlanId" and NewGP."TableName" = 'GTXPLAN' and NewGP."Audit" = pAudit

        left outer join ax_map NewD on NewD."SourceId" = OldDP."Diagnose" and NewD."TableName" = 'DIAGNOSE' and NewD."Audit" = pAudit

      where

        NewDP."TableName" = 'DTXPLAN' and

        NewDP."Audit" = pAudit

    ;

    cursor curGtxProMap(pAudit audithis."Audit"%type) is

      select

        gp."GtxPro",

        nvl(NewGP."TargetId",0) "GtxPlan",

        nvl(NewP."TargetId",0) "ProList",

        nvl(NewC."TargetId",0) "Complain"

      from

        gtxpro gp

        inner join ax_map NewGP on NewGP."SourceId" = gp."GtxPlan" and NewGP."TableName" = 'GTXPLAN' and NewGP."Audit" = pAudit

        left outer join ax_map NewP on NewP."SourceId" = gp."ProList" and NewP."TableName" = 'PROLIST'  and NewP."Audit" = pAudit and gp."Type" = 0

        left outer join ax_map NewC on NewC."SourceId" = gp."Complain" and NewC."TableName" = 'COMPLAIN'  and NewC."Audit" = pAudit and gp."Type" = 1

    ;

    cursor curObjListMap(pAudit audithis."Audit"%type) is

      select

        NewOL."SourceId",

        NewOL."TargetId",

        nvl(NewC."TargetId",0) "Complaint"

      from

        ax_map NewOL

        inner join objlist OldOL on OldOL."ObjList" = NewOL."SourceId"

        left outer join ax_map NewC on NewC."SourceId" = OldOL."Complaint" and NewC."TableName" = 'COMPLAIN' and NewC."Audit" = pAudit

      where

        NewOL."TableName" = 'OBJLIST' and

        NewOL."Audit" = pAudit

    ;  

P189-156750 end */    

    cursor curTxpNoteMap(pAudit audithis."Audit"%type) is

      select

        NewTN."SourceId",

        NewTN."TargetId",

        NewC."TargetId" "TxPlan"

      from

        txpnote tpn

        inner join ax_map NewTN on NewTN."SourceId" = tpn."TxPNote" and NewTN."TableName" = 'TXPNOTE' and NewTN."Audit" = pAudit

        inner join ax_map NewC on NewC."SourceId" = tpn."TxPlan" and NewC."TableName" = 'TXPLAN' and NewC."Audit" = pAudit

    ;  

    cursor curNoteOvrMap2(pAudit audithis."Audit"%type,pId number) is

      select

        NewTXN."SourceId",

        NewTXN."TargetId",

        nto."Id"

      from

        noteovr nto 

        inner join ax_map NewTXN on NewTXN."SourceId" = nto."ParentId" and NewTXN."TableName" = 'TXPNOTE' and NewTXN."Audit" = pAudit

      where

        nto."Patient" = pId and

        nto."Deleted" = 0 and

        nto."Type" = 2

    ;

    cursor curTxPlnConMap(pAudit audithis."Audit"%type) is

      select

        tpc."TxPlan" "OldTxPlan",

        tpc."Contract" "OldContract",

        NewC1."TargetId" "NewTxPlan",

        NewC2."TargetId" "NewContract"

      from

        txplncon tpc

        inner join ax_map NewC1 on NewC1."SourceId" = tpc."TxPlan" and NewC1."TableName" = 'TXPLAN' and NewC1."Audit" = pAudit

        inner join ax_map NewC2 on NewC2."SourceId" = tpc."Contract" and NewC2."TableName" = 'CONTRACT' and NewC2."Audit" = pAudit

    ;

    cursor curTxPlanMap(pAudit audithis."Audit"%type) is

      select

        NewT."SourceId",

        NewT."TargetId"

      from

        txplan t

        inner join ax_map NewT on NewT."SourceId" = t."TxPlan" and NewT."TableName" = 'TXPLAN' and NewT."Audit" = pAudit

    ; 

    cursor curPtPrbMap(pAudit audithis."Audit"%type) is

      select

        NewT."SourceId",

        NewT."TargetId"

      from

        PtPrb t

        inner join ax_map NewT on NewT."SourceId" = t."PtPrb" and NewT."TableName" = 'PTPRB' and NewT."Audit" = pAudit

    ; 

    cursor curTxPDxMap(pAudit audithis."Audit"%type) is

      select

        NewT."SourceId",

        NewT."TargetId",

        NewTxP."TargetId" "TxPlan"

      from

        TxPDx t

        inner join ax_map NewT on NewT."SourceId" = t."TxPDx" and NewT."TableName" = 'TXPDX' and NewT."Audit" = pAudit

        inner join ax_map NewTxP on NewTxP."SourceId" = t."TxPlan" and NewTxP."TableName" = 'TXPLAN' and NewTxP."Audit" = pAudit

      where

        t."Deleted" = 0

    ; 

    cursor curPtPrbDxMap(pAudit audithis."Audit"%type) is

      select

        NewP."SourceId" "OldPtPrb",

        NewD."SourceId" "OldTxPDx",

        NewP."TargetId" "NewPtPrb",

        NewD."TargetId" "NewTxPDx"

      from

        PtPrbDx t

        inner join ax_map NewP on NewP."SourceId" = t."PtPrb" and NewP."TableName" = 'PTPRB' and NewP."Audit" = pAudit

        inner join ax_map NewD on NewD."SourceId" = t."TxPDx" and NewD."TableName" = 'TXPDX' and NewD."Audit" = pAudit

      where

        t."Deleted" = 0

    ; 

    cursor curTxPOptMap(pAudit audithis."Audit"%type) is

      select

        NewT."SourceId",

        NewT."TargetId",

        NewTxP."TargetId" "TxPlan"

      from

        TxPOpt t

        inner join ax_map NewT on NewT."SourceId" = t."TxPOpt" and NewT."TableName" = 'TXPOPT' and NewT."Audit" = pAudit

        inner join ax_map NewTxP on NewTxP."SourceId" = t."TxPlan" and NewTxP."TableName" = 'TXPLAN' and NewTxP."Audit" = pAudit

      where

        t."Deleted" = 0

    ; 

    cursor curTxPOpApMap(pAudit audithis."Audit"%type) is

      select

        NewT."SourceId",

        NewT."TargetId",

        t."ConsultantType"

      from

        TxPOpAp t

        inner join ax_map NewT on NewT."SourceId" = t."TxPOpt" and NewT."TableName" = 'TXPOPT' and NewT."Audit" = pAudit

    ; 

    cursor curTxPPrbMap(pAudit audithis."Audit"%type) is

      select

        NewP."SourceId" "OldPtPrb",

        NewTxP."SourceId" "OldTxPlan",

        NewP."TargetId" "NewPtPrb",

        NewTxP."TargetId" "NewTxPlan"

      from

        TxPPrb t

        inner join ax_map NewP on NewP."SourceId" = t."PtPrb" and NewP."TableName" = 'PTPRB' and NewP."Audit" = pAudit

        inner join ax_map NewTxP on NewTxP."SourceId" = t."TxPlan" and NewTxP."TableName" = 'TXPLAN' and NewTxP."Audit" = pAudit

      where

        t."Deleted" = 0

    ; 

    cursor curTxPtxMap(pAudit audithis."Audit"%type) is

      select

        t."TxPTx",

        NewTxPTx."TargetId" "NewTxPTx",  -- SF-00152633

        NewTxP."TargetId" "TxPlan",

        NewO."TargetId" "TxPOpt",

        NewT2."TargetId" "Treatme2Id"

      from

        TxPtx t

        inner join ax_map NewTxPTx on NewTxPTx."SourceId" = t."TxPTx" and NewTxPTx."TableName" = 'TXPTX' and NewTxPTx."Audit" = pAudit  -- SF-00152633

        inner join ax_map NewTxP on NewTxP."SourceId" = t."TxPlan" and NewTxP."TableName" = 'TXPLAN' and NewTxP."Audit" = pAudit

        inner join ax_map NewO on NewO."SourceId" = t."TxPOpt" and NewO."TableName" = 'TXPOPT' and NewO."Audit" = pAudit

        left outer join ax_map NewT2 on NewT2."SourceId" = t."Treatme2Id" and NewT2."TableName" = 'TREATME2' and NewT2."Audit" = pAudit

      where

        t."Deleted" = 0

    ; 

    cursor curTxPdxTxMap(pAudit audithis."Audit"%type) is

      select

        NewPDx."SourceId" "OldTxPDx",

        NewPDx."TargetId" "NewTxPDx",

        NewPTx."SourceId" "OldTxPTx",

        NewPTx."TargetId" "NewTxPTx"

      from

        TxPdxTx t

        inner join ax_map NewPDx on NewPDx."SourceId" = t."TxPDx" and NewPDx."TableName" = 'TXPDX' and NewPDx."Audit" = pAudit

        inner join ax_map NewPTx on NewPTx."SourceId" = t."TxPTx" and NewPTx."TableName" = 'TXPTX' and NewPTx."Audit" = pAudit

      where

        "Deleted" = 0

    ; 

    cursor curPtObjMap(pAudit audithis."Audit"%type) is

      select

        t."PtObj",

        NewTxP."TargetId" "TxPlan"

      from

        ptobj t

        inner join ax_map NewTxP on NewTxP."SourceId" = t."TxPlan" and NewTxP."TableName" = 'TXPLAN' and NewTxP."Audit" = pAudit

    ; 

    -- Records   

/* P189-156750 start

    vComplainRow complain%rowtype;

    vProListRow  prolist%rowtype;

    vDiagnoseRow diagnose%rowtype;

    vGtxOptRow   gtxopt%rowtype;

    vGtxAppidRow gtxappid%rowtype;

    vGtxPlanRow  gtxplan%rowtype;

    vDtxOptRow   dtxopt%rowtype;

    vDtxAppidRow dtxappid%rowtype;

    vDtxPlanRow  dtxplan%rowtype;

    vDtxAppRow   dtxapp%rowtype;

    vGtxProRow   gtxpro%rowtype;

    vObjListRow  objlist%rowtype;

P189-156750 end */

    vTxPlnConRow txplncon%rowtype;

    vTxpNoteRow  txpnote%rowtype;

    vNoteOvrRow  noteovr%rowtype;

    vPtPrbRow    ptprb%rowtype;

    vTxPlanRow   txplan%rowtype;

    vTxPdxRow    txpdx%rowtype;

    vPtprbdxRow  ptprbdx%rowtype;

    vTxpoptRow   txpopt%rowtype;

    vTxpprbRow   txpprb%rowtype;

    vTxptxRow    txptx%rowtype;

    vTxpdxtxRow  txpdxtx%rowtype;

    vTxPopApRow  txpopap%rowtype;

    vPtObjRow    ptobj%rowtype;    

    -- Variables

    vCount number;

    vCount2 number;

    vSourcePatient2 patient2."Auto"%type;

    vTargetPatient2 patient2."Auto"%type;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    pvMapAudit := ax_pkg.GetMapAudit_F(pvMapAudit,vParams);



    select "Auto" into vTargetPatient2 from patient2 where "PtxPId" = pTargetPatient;

    select "Auto" into vSourcePatient2 from patient2 where "PtxPId" = pSourcePatient;



    -- Map Treatme2 Records

    begin

      select 1 into vCount from ax_map where "Audit" = pvMapAudit and "TableName" = 'TREATME2' and rownum = 1;

    exception

      when no_data_found then

        insert into ax_map (

          select 

            pvMapAudit,

            'TREATME2', 

            "Auto", 

            treatme2_auto_seq.nextval 

            ,null,null

          from treatme2 

          where "PId" = vSourcePatient2

        );

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

    end;



/* P189-156750 start

    -- Map Complain Records

    insert into ax_map (

      select 

        pvMapAudit,

        'COMPLAIN', 

        c."Auto", 

        complain_auto_seq.nextval 

        ,null,null

      from complain c

      where 

        c."Patient" = pSourcePatient

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

P189-156750 end */



    -- Map TxPlan Records

    insert into ax_map (

      select

        pvMapAudit,

        'TXPLAN', 

        t."TxPlan", 

        txplan_txplan_seq.nextval 

        ,null,null

      from TxPlan t

      where

        t."Patient" = pSourcePatient

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',pParams);

      

/* P189-156750 start

    -- Create Complain Records

    vCount := 0;

    for cComplainMap in curComplainMap(pvMapAudit) loop

      select * into vComplainRow from complain where "Auto" = cComplainMap."SourceId";

      vComplainRow."Auto" := cComplainMap."TargetId";

      vComplainRow."Patient" := pTargetPatient; 

      insert into complain values vComplainRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' complain rows inserted.',vParams);



    -- Map Prolist Records

    insert into ax_map (

      select 

        pvMapAudit,

        'PROLIST', 

        pl."Id", 

        prolist_id_seq.nextval 

        ,null,null

      from prolist pl

      where 

        pl."Patient" = pSourcePatient

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

    

    -- Create prolist Records

    vCount := 0;

    for cProlistMap in curProlistMap(pvMapAudit) loop

      select * into vProlistRow from Prolist where "Id" = cProlistMap."SourceId";

      vProlistRow."Id" := cProlistMap."TargetId";

      vProlistRow."Complaint" := cProlistMap."Complaint";    

      vProlistRow."Patient" := pTargetPatient; 

      insert into prolist values vProlistRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' prolist rows inserted.',vParams);

    

    -- Create prolisth Records

      -- depreciated table

    

    -- Map diagnose Records

    insert into ax_map (

      select 

        pvMapAudit,

        'DIAGNOSE', 

        d."Auto", 

        diagnose_auto_seq.nextval 

        ,null,null

      from 

        diagnose d

        inner join complain c on c."Auto" = d."Complaint"

      where

        c."Patient" = pSourcePatient

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

    

    -- Create diagnose Records

    vCount := 0;

    for cDiagnoseMap in curDiagnoseMap(pvMapAudit) loop

      select * into vDiagnoseRow from diagnose where "Auto" = cDiagnoseMap."SourceId";

      vDiagnoseRow."Auto" := cDiagnoseMap."TargetId";

      vDiagnoseRow."Complaint" := cDiagnoseMap."Complaint";  

      insert into diagnose values vDiagnoseRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' diagnose rows inserted.',vParams);

    

    -- Map gtxopt Records

    insert into ax_map (

      select 

        pvMapAudit,

        'GTXOPT', 

        g."Option", 

        gtxopt_option_seq.nextval 

        ,null,null

      from 

        gtxopt g

        inner join complain c on c."Auto" = g."Complaint"

      where

        c."Patient" = pSourcePatient

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

    

    -- Create gtxopt Records

    vCount := 0;

    for cGtxOptMap in curGtxOptMap(pvMapAudit) loop

      select * into vGtxOptRow from gtxopt where "Option" = cGtxOptMap."SourceId";

      vGtxOptRow."Option" := cGtxOptMap."TargetId";

      vGtxOptRow."Complaint" := cGtxOptMap."Complaint";  

      insert into gtxopt values vGtxOptRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' gtxopt rows inserted.',vParams);

    

    -- Create gtxappid Records    

    vCount := 0;

    for cGtxAppIdMap in curGtxAppIdMap(pvMapAudit) loop

      select * into vGtxAppIdRow from gtxappid where "Option" = cGtxAppIdMap."SourceId" and "ConsultantType" = cGtxAppIdMap."ConsultantType";

      vGtxAppIdRow."Option" := cGtxAppIdMap."TargetId";

      insert into gtxappid values vGtxAppIdRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' gtxappid rows inserted.',vParams);

    

    -- Map gtxplan Records

    insert into ax_map (

      select 

        pvMapAudit,

        'GTXPLAN', 

        g."Id", 

        gtxplan_id_seq.nextval 

        ,null,null

      from 

        gtxplan g

        inner join complain c on c."Auto" = g."Complaint"

      where

        c."Patient" = pSourcePatient

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

    

    -- Create gtxopt Records

    vCount := 0;

    for cGtxPlanMap in curGtxPlanMap(pvMapAudit) loop

      select * into vGtxPlanRow from gtxplan where "Id" = cGtxPlanMap."SourceId";

      vGtxPlanRow."Id" := cGtxPlanMap."TargetId";

      vGtxPlanRow."Option" := cGtxPlanMap."Option";

      vGtxPlanRow."Complaint" := cGtxPlanMap."Complaint";  

      insert into gtxplan values vGtxPlanRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' gtxplan rows inserted.',vParams);

      

    -- Create gtxpro Records

    vCount := 0;

    for cGtxProMap in curGtxProMap(pvMapAudit) loop

      select * into vGtxProRow from gtxpro where "GtxPro" = cGtxProMap."GtxPro";

      vGtxProRow."GtxPro" := gtxpro_gtxPro_seq.nextval;

      vGtxProRow."GtxPlan" := cGtxProMap."GtxPlan";

      vGtxProRow."ProList" := cGtxProMap."ProList";  

      vGtxProRow."Complain" := cGtxProMap."Complain";  

      insert into gtxpro values vGtxProRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' gtxpro rows inserted.',vParams);

    

    -- Map objlist Records

    insert into ax_map (

      select 

        pvMapAudit,

        'OBJLIST', 

        "ObjList", 

        objlist_objlist_seq.nextval 

        ,null,null

      from 

        objlist

      where

        "Patient" = pSourcePatient

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

    

    -- Create objlist Records    

    vCount := 0;

    for cObjListMap in curObjListMap(pvMapAudit) loop

      select * into vObjListRow from objlist where "ObjList" = cObjListMap."SourceId";

      vObjListRow."ObjList" := cObjListMap."TargetId";

      vObjListRow."Complaint" := cObjListMap."Complaint";

      vObjListRow."Patient" := pTargetPatient;

      insert into objlist values vObjListRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' objlist rows inserted.',vParams);

    

    -- Create objlisth Records    

      -- depreciated table

P189-156750 end */

    

    -- Map txpnote Records

    insert into ax_map (

      select 

        pvMapAudit,

        'TXPNOTE', 

        "TxPNote", 

        txpnote_txpnote_seq.nextval 

        ,null,null

      from 

        txpnote

      where

        "Patient" = pSourcePatient

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

    

    -- Create txpnote Records

    vCount := 0;

    for cTxpNoteMap in curTxpNoteMap(pvMapAudit) loop

      select * into vTxpNoteRow from txpnote where "TxPNote" = cTxpNoteMap."SourceId";

      vTxpNoteRow."TxPNote" := cTxpNoteMap."TargetId";

      vTxpNoteRow."Patient" := pTargetPatient ;

      vTxpNoteRow."TxPlan" := cTxpNoteMap."TxPlan";

      insert into txpnote values vTxpNoteRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' txpnote rows inserted.',vParams);

    

    -- Create txpnohis Records    

      -- Created by trigger on txpnote

      

    -- Map Patient Problem Records

    insert into ax_map (

      select

        pvMapAudit,

        'PTPRB', 

        p."PtPrb", 

        ptprb_ptprb_seq.nextval 

        ,null,null

      from ptprb p

      where

        p."Patient" = pSourcePatient

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

    

    -- Create Patient Problem Records

    vCount := 0;

    for cPtPrbMap in curPtPrbMap(pvMapAudit) loop

      select * into vPtPrbRow from PtPrb where "PtPrb" = cPtPrbMap."SourceId";

      vPtPrbRow."PtPrb" := cPtPrbMap."TargetId";

      vPtPrbRow."Patient" := pTargetPatient; 

      insert into PtPrb values vPtPrbRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ptprb rows inserted.',vParams);

   

    -- Create TxPlan Records

    vCount := 0;

    for cTxPlanMap in curTxPlanMap(pvMapAudit) loop

      select * into vTxPlanRow from TxPlan where "TxPlan" = cTxPlanMap."SourceId";

      vTxPlanRow."TxPlan" := cTxPlanMap."TargetId";

      vTxPlanRow."Patient" := pTargetPatient; 

      insert into TxPlan values vTxPlanRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' txplan rows inserted.',vParams);

      

    -- Map TxPDx Records

    insert into ax_map (

      select

        pvMapAudit,

        'TXPDX', 

        t."TxPDx", 

        txpdx_txpdx_seq.nextval 

        ,null,null

      from TxPDx t

      where

        t."TxPlan" in (select "TxPlan" from txplan where "Patient" = pSourcePatient)

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

    

    -- Create TxPDx Records

    vCount := 0;

    for cTxPDxMap in curTxPDxMap(pvMapAudit) loop

      select * into vTxPDxRow from TxPDx where "TxPDx" = cTxPDxMap."SourceId";

      vTxPDxRow."TxPDx" := cTxPDxMap."TargetId";

      vTxPDxRow."TxPlan" := cTxPDxMap."TxPlan";

      insert into TxPDx values vTxPDxRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' txpdx rows inserted.',vParams);

      

    -- Create PtPrbDx Records

    vCount := 0;

    for cPtPrbDxMap in curPtPrbDxMap(pvMapAudit) loop

      select * into vPtPrbDxRow from PtPrbDx where "PtPrb" = cPtPrbDxMap."OldPtPrb" and "TxPDx" = cPtPrbDxMap."OldTxPDx";

      vPtPrbDxRow."PtPrb" := cPtPrbDxMap."NewPtPrb";

      vPtPrbDxRow."TxPDx" := cPtPrbDxMap."NewTxPDx";

      insert into PtPrbDx values vPtPrbDxRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ptprbdx rows inserted.',vParams);

      

    -- Map TxPOpt Records

    insert into ax_map (

      select

        pvMapAudit,

        'TXPOPT', 

        t."TxPOpt", 

        txpopt_txpopt_seq.nextval 

        ,null,null

      from TxPOpt t

      where

        t."TxPlan" in (select "TxPlan" from txplan where "Patient" = pSourcePatient)

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

      

    -- Create TxPOpt Records

    vCount := 0;

    for cTxPOptMap in curTxPOptMap(pvMapAudit) loop

      select * into vTxPOptRow from TxPOpt where "TxPOpt" = cTxPOptMap."SourceId";

      vTxPOptRow."TxPOpt" := cTxPOptMap."TargetId";

      vTxPOptRow."TxPlan" := cTxPOptMap."TxPlan";

      insert into TxPOpt values vTxPOptRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' txpopt rows inserted.',vParams);

      

    -- Create TxPPrb Records

    vCount := 0;

    for cTxPPrbMap in curTxPPrbMap(pvMapAudit) loop

      select * into vTxPPrbRow from TxPPrb where "TxPlan" = cTxPPrbMap."OldTxPlan" and "PtPrb" = cTxPPrbMap."OldPtPrb";

      vTxPPrbRow."TxPlan" := cTxPPrbMap."NewTxPlan";

      vTxPPrbRow."PtPrb" := cTxPPrbMap."NewPtPrb";      

      insert into TxPPrb values vTxPPrbRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' txpprb rows inserted.',vParams);

      

    -- Map TxPOpt Records

    insert into ax_map (

      select

        pvMapAudit,

        'TXPTX', 

        t."TxPTx", 

        txptx_txptx_seq.nextval 

        ,null,null

      from TxPtx t

      where

        t."TxPlan" in (select "TxPlan" from txplan where "Patient" = pSourcePatient)

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

      

    -- Create TxPtx Records

    vCount := 0;

    for cTxPtxMap in curTxPtxMap(pvMapAudit) loop

      select * into vTxPtxRow from TxPtx where "TxPTx" = cTxPtxMap."TxPTx";

--      vTxPtxRow."TxPTx" := txptx_txptx_seq.nextval;  -- SF-00152633

      vTxPtxRow."TxPTx" := cTxPtxMap."NewTxPTx";  -- SF-00152633

      vTxPtxRow."TxPlan" := cTxPtxMap."TxPlan";

      vTxPtxRow."TxPOpt" := cTxPtxMap."TxPOpt";

      vTxPtxRow."Treatme2Id" := cTxPtxMap."Treatme2Id";

      insert into TxPtx values vTxPtxRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' txptx rows inserted.',vParams);

      

    -- Create TxPdxTx Records

    vCount := 0;

    for crTxPdxTxMap in curTxPdxTxMap(pvMapAudit) loop

      select * into vTxPdxTxRow from txpdxtx where "TxPTx" = crTxPdxTxMap."OldTxPTx" and "TxPDx" = crTxPdxTxMap."OldTxPDx";

      vTxPdxTxRow."TxPTx" := crTxPdxTxMap."NewTxPTx";

      vTxPdxTxRow."TxPDx" := crTxPdxTxMap."NewTxPDx";

      insert into txpdxtx values vTxPdxTxRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' txpdxtx rows inserted.',vParams);

      

    -- Create PtObj Records

    vCount := 0;

    for cPtObjMap in curPtObjMap(pvMapAudit) loop

      select * into vPtObjRow from PtObj where "PtObj" = cPtObjMap."PtObj";

      vPtObjRow."PtObj" := ptobj_ptobj_seq.nextval;

      vPtObjRow."TxPlan" := cPtObjMap."TxPlan";

      insert into PtObj values vPtObjRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ptobj rows inserted.',vParams);

  

/* SF-00152633 comment out this because it was updating the TxPTx ids on the source patient

    -- now have to update the DtxPlanId pointers in TREATME2 for new patient, could not do this before

    -- because TXPTX also points to Treatme2

    if vSourcePatient2 is not null then

      update treatme2 

      set

        "TxPTx" = (select nvl("TargetId",0) from AX_Map where "TableName" = 'TXPTX' and "Audit" = pvMapAudit and "SourceId" = "TxPTx") 

      where

        "PId" = vSourcePatient2 and "TxPTx" != 0;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' treatme2 rows updated.',vParams);

    end if;

*/



    -- Create txplncon Records

    vCount := 0;

    for cTxPlnConMap in curTxPlnConMap(pvMapAudit) loop

      select * into vTxPlnConRow from txplncon where "TxPlan" = cTxPlnConMap."OldTxPlan" and "Contract" = cTxPlnConMap."OldContract";

      vTxPlnConRow."TxPlan" := cTxPlnConMap."NewTxPlan";

      vTxPlnConRow."Contract" := cTxPlnConMap."NewContract";

      vCount := vCount + 1;

      insert into txplncon values vTxPlnConRow;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' txplncon rows inserted.',vParams);

    

    -- Create noteovr Records

    for cNoteOverMap in curNoteOvrMap2(pvMapAudit,pSourcePatient) loop

      select * into vNoteOvrRow from noteovr where "Id" = cNoteOverMap."Id"; 

      select noteovr_id_seq.nextval into vNoteOvrRow."Id" from dual;

      vNoteOvrRow."ParentId" := cNoteOverMap."TargetId";

      vNoteOvrRow."Patient" := pTargetPatient;

      insert into noteovr values vNoteOvrRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' noteovr rows inserted.',vParams);

    

  end CopyTreatmentPlanningRecords_P;





  -- Copy Sticky Notes

  PROCEDURE copystickynoterecords_p(IN psourcepatient numeric, IN ptargetpatient numeric, INOUT pvmapaudit numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    cursor curAP_Note(pId number) is 

      select * from ap_note where ("AP_NOTE_AppId" = pId and "AP_NOTE_Type" = 3) or ("AP_NOTE_PatientId" = pId);

    vCount number;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    pvMapAudit := ax_pkg.GetMapAudit_F(pvMapAudit,vParams);

  -- Create AP_Note records

    vCount := 0;

    for cAP_Note in curAP_Note(pSourcePatient) loop

      select ap_note_ap_note_autodec_seq.nextval into cAP_Note."AP_NOTE_AutoDec" from dual;

      if cAP_Note."AP_NOTE_Type" = 3 then

        cAP_Note."AP_NOTE_AppId" := pTargetPatient;

      end if;      

      if cAP_Note."AP_NOTE_Type" not in (1,2,3,13,16) then

        cAP_Note."AP_NOTE_PatientId" := pTargetPatient;

      end if;

      vCount := vCount + 1;

      insert into ap_note values cAP_Note;

    end loop;  

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ap_note rows inserted.',vParams);

  end CopyStickyNoteRecords_P;





  -- Copy Attachments

    -- Note that this procedure must be called BEFORE any other procedure which may copy section specific attachments

    -- If called out of order, you may be missing attachments or links to attachments

  PROCEDURE copyattachmentrecords_p(IN psourcepatient numeric, IN ptargetpatient numeric, INOUT pvmapaudit numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    cursor curPtSigMap(pAudit audithis."Audit"%type) is

      select "TargetId", "SourceId" from ax_map where "TableName" = 'PTSIG(C)' and "Audit" = pAudit;  

    cursor curContractMap(pAudit audithis."Audit"%type) is

      select "TargetId", "SourceId" from ax_map where "TableName" = 'CONTRACT' and "Audit" = pAudit;

    cursor curPtLetter(pId number) is 

      select * from ptletter where "Patient" = pId and "Deleted" = 0;

    cursor curContSigMap(pAudit audithis."Audit"%type) is

      select 

        NewC."TargetId" "NewContract",

        NewC."SourceId" "OldContract",

        NewS."TargetId" "NewPtSig",

        NewS."SourceId" "OldPtSig"

      from

        contsig c

        inner join ax_map NewC on NewC."SourceId" = c."Contract" and NewC."TableName" = 'CONTRACT' and NewC."Audit" = pAudit

        inner join ax_map NewS on NewS."SourceId" = c."PtSig" and NewS."TableName" = 'PTSIG(C)' and NewS."Audit" = pAudit      

    ;

      

    vContractRow contract%rowtype;

    vPtSigRow ptsig%rowtype;

    vContSigRow contsig%rowtype;

    vCount number;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    pvMapAudit := ax_pkg.GetMapAudit_F(pvMapAudit,vParams);

    -- Creat Mapping Records

      -- Map ptsig Records for contracts



    insert into ax_map (

      select 

        pvMapAudit,

        'PTSIG(C)', 

        s."PtSig", 

        ptsig_ptsig_seq.nextval 

        ,null,null

      from 

        (

          select distinct

            sig."PtSig"

          from

            contract c            

            left outer join contsig cs on cs."Contract" = c."Contract"

            left outer join ptsig sig on sig."PtSig" = c."PtSig" or sig."PtSig" = cs."PtSig"

          where 

            c."Patient" = pSourcePatient and

            sig."PtSig" is not null

        ) s

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

      

  -- Create ptsig Records

    vCount := 0;

    for cPtSigMap in curPtSigMap(pvMapAudit) loop

      select * into vPtSigRow from ptsig where "PtSig" = cPtSigMap."SourceId";

      vPtSigRow."PtSig" := cPtSigMap."TargetId";

      vCount := vCount + 1;

      insert into ptsig values vPtSigRow;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ptsig rows inserted.',vParams);



  -- Map Contract Records

    insert into ax_map (

      select 

        pvMapAudit,

        'CONTRACT', 

        c."Contract", 

        contract_contract_seq.nextval 

        ,null,null

      from contract c

      where 

        c."Patient" = pSourcePatient

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

    

  -- Create contract Records

    vCount := 0;

    for cContractMap in curContractMap(pvMapAudit) loop

      select * into vContractRow from contract where "Contract" = cContractMap."SourceId";

      vContractRow."Contract" := cContractMap."TargetId";

      vContractRow."Patient" := pTargetPatient;

      vCount := vCount + 1;

      insert into contract values vContractRow;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' contract rows inserted.',vParams);

    

  -- Create contsig Records

    vCount := 0;

    for cContSigMap in curContSigMap(pvMapAudit) loop

      select * into vContSigRow from contsig where "Contract" = cContSigMap."OldContract" and "PtSig" = cContSigMap."OldPtSig";

      vContSigRow."Contract" := cContSigMap."NewContract";

      vContSigRow."PtSig" := cContSigMap."NewPtSig";

      vCount := vCount + 1;

      insert into contsig values vContSigRow;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' contsig rows inserted.',vParams);

      

  -- Create ptletter Records

    vCount := 0;

    for cPtLetter in curPtLetter(pSourcePatient) loop

      select ptletter_Ptletter_seq.nextval into cPtLetter."PtLetter" from dual;

      cPtLetter."OrigId" := cPtLetter."PtLetter";

      cPtLetter."Patient" := pTargetPatient;

      vCount := vCount + 1;

      insert into ptletter values cPtLetter;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ptletter rows inserted.',vParams);



  end CopyAttachmentRecords_P;





  -- Copy EPR Forms

  PROCEDURE copyeprformrecords_p(IN psourcepatient numeric, IN ptargetpatient numeric, INOUT pvmapaudit numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    -- Cursors

    cursor curPtSigMap(pAudit audithis."Audit"%type) is

      select "TargetId", "SourceId" from ax_map where "TableName" = 'PTSIG(F)' and "Audit" = pAudit;  

    cursor curPFormMap(pAudit audithis."Audit"%type) is

      select

        NewF."TargetId",

        NewF."SourceId",

        pf."FormCode",

        pf."Patient",

        pf."PForm"

      from 

        ax_map NewF

        inner join pform pf on pf."PForm" = NewF."SourceId"

      where

        NewF."TableName" = 'PFORM' and

        NewF."Audit" = pAudit

    ;

    cursor curPPageMap(pAudit audithis."Audit"%type) is

      select 

        NewP."TargetId",

        NewP."SourceId",

        NewF."TargetId" "PForm",

        nvl(NewS."TargetId",0) "PtSig"

      from

        ax_map NewP

        inner join ppage pp on pp."PPage" = NewP."SourceId"

        inner join ax_map NewF on NewF."SourceId" = pp."PForm" and NewF."TableName" = 'PFORM' and NewF."Audit" = pAudit

        left outer join ax_map NewS on NewS."SourceId" = pp."PtSig" and NewS."TableName" = 'PTSIG(F)' and NewS."Audit" = pAudit

      where

        NewP."TableName" = 'PPAGE' and 

        NewP."Audit" = pAudit

    ;

    cursor curPPageSigMap(pAudit audithis."Audit"%type) is

      select 

        NewP."TargetId" "NewPPage",

        NewP."SourceId" "OldPPage",

        NewS."TargetId" "NewPtSig",

        NewS."SourceId" "OldPtSig"

      from

        ax_map NewP

        inner join ppage pp on pp."PPage" = NewP."SourceId"

        inner join ppagesig pps on pps."PPage" = pp."PPage"

        inner join ax_map NewS on NewS."SourceId" = pps."PtSig" and NewS."TableName" = 'PTSIG(F)' and NewS."Audit" = pAudit

      where

        NewP."TableName" = 'PPAGE' and

        NewP."Audit" = pAudit

    ;

  

    cursor curPItemImgMap(pAudit audithis."Audit"%type) is

      select

        NewPI."TargetId",

        NewPI."SourceId"

      from

        ax_map NewPI

      where

        NewPI."TableName" = 'PITEMIMG' and

        NewPI."Audit" = pAudit

    ;

    cursor curPItemColMap(pAudit audithis."Audit"%type) is

      select

        NewPIC."TargetId",

        NewPIC."SourceId",

        NewPF."TargetId" "PForm",

        NVL(NewOPIC."TargetId",0) "OrgPItemCol"  -- SF-00257739

      from

        ax_map NewPIC

        inner join pitemcol pic on pic."PItemCol" = NewPIC."SourceId"

        inner join ax_map NewPF on NewPF."SourceId" = pic."PForm" and NewPF."TableName" = 'PFORM' and NewPF."Audit" = pAudit

        left outer join ax_map NewOPIC on NewOPIC."SourceId" = pic."OrgPItemCol" and NewOPIC."TableName" = 'PITEMCOL' and NewOPIC."Audit" = pAudit

      where

        NewPIC."TableName" = 'PITEMCOL' and

        NewPIC."Audit" = pAudit

    ;

    cursor curPItemMap(pAudit audithis."Audit"%type,pId number) is

      select   

        pi."PItem" "OrigPItem",

        NewPI."TargetId" "NewPItem",

        pi."AuditNumber",

        pi."PItemCol" "OrigPItemCol",

        pi."PForm" "OrigPForm",

        pi."FormCode" "OrigFormCode",

        pi."FItem" "OrigFItem",        

        NewF."TargetId" "PForm",

        nvl(NewII."TargetId",0) "PItemImg",

        nvl(NewIC."TargetId",0) "PItemCol"

      from

        pitem pi

        inner join ax_map NewPI on NewPI."SourceId" = pi."PItem" and NewPI."TableName" = 'PITEM' and NewPI."Audit" = pAudit

        left outer join ax_map NewF on NewF."SourceId" = pi."PForm" and NewF."TableName" = 'PFORM' and NewF."Audit" = pAudit

        left outer join ax_map NewII on NewII."SourceId" = pi."PItemImg" and NewII."TableName" = 'PITEMIMG' and NewII."Audit" = pAudit

        left outer join ax_map NewIC on NewIC."SourceId" = pi."PItemCol" and NewIC."TableName" = 'PITEMCOL' and NewIC."Audit" = pAudit

      where

        pi."Status" = 0

--        pi."PItemCol" = nvl(NewIC."TargetId",0)        -- SF-00257739

    ;

    cursor curNoteOvrMap1(pAudit audithis."Audit"%type,pId number) is

      select

        NewPI."SourceId",

        NewPI."TargetId",

        nto."Id"

      from

        noteovr nto 

        inner join ax_map NewPI on NewPI."SourceId" = nto."ParentId" and NewPI."TableName" = 'PITEM' and NewPI."Audit" = pAudit

      where

        nto."Patient" = pId and

        nto."Deleted" = 0 and

        nto."Type" = 1

    ;

    -- Records

    vPFormRow    pform%rowtype;

    vPPageRow    ppage%rowtype;

    vPPageSigRow ppagesig%rowtype;

    vPItemImgRow pitemimg%rowtype;

    vPItemRow    pitem%rowtype;

    vPItemColRow pitemcol%rowtype;

    vNoteOvrRow  noteovr%rowtype;

    vPtSigRow    ptsig%rowtype;

    -- Variables

    vCount number;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    pvMapAudit := ax_pkg.GetMapAudit_F(pvMapAudit,vParams);

    

    -- Map pform Records

    insert into ax_map (

      select 

        pvMapAudit,

        'PFORM', 

        "PForm", 

        pform_Pform_seq.nextval 

        ,null,null

      from 

        pform

      where

        "Patient" = pSourcePatient and

        "Inactive" = 0

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

    

    -- Create pform records

    vCount := 0;

    for cPFormMap in curPFormMap(pvMapAudit) loop

      select * into vPFormRow 

      from pform 

      where 

        "FormCode" = cPFormMap."FormCode" and 

        "Patient" = pSourcePatient and 

        "PForm" = cPFormMap."SourceId";

      vPFormRow."PForm" := cPFormMap."TargetId";

      vPFormRow."Patient" := pTargetPatient;

      insert into pform values vPFormRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' pform rows inserted.',vParams);

    

    -- Map ppage Records

    insert into ax_map (

      select 

        pvMapAudit,

        'PPAGE', 

        "PPage", 

        ppage_Ppage_seq.nextval 

        ,null,null

      from 

        ppage

      where

        "Patient" = pSourcePatient and

        "Status" = 0

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);



    -- Map ptsig Records for ppage and ppagesig

    insert into ax_map (

      select 

        pvMapAudit,

        'PTSIG(F)', 

        s."PtSig", 

        ptsig_Ptsig_seq.nextval 

        ,null,null

      from 

        (

          select distinct

            sig."PtSig"

          from

            ppage p

            left outer join ppagesig ps on ps."PPage" = p."PPage"

            left outer join ptsig sig on sig."PtSig" = p."PtSig" or sig."PtSig" = ps."PtSig"      

          where 

            p."Patient" = pSourcePatient and

            sig."PtSig" is not null

        ) s

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

    

    -- Create ppage Records

    vCount := 0;

    for cPPageMap in curPPageMap(pvMapAudit) loop

      select * into vPPageRow from ppage where "PPage" = cPPageMap."SourceId";

      vPPageRow."PPage" := cPPageMap."TargetId";

      vPPageRow."Patient" := pTargetPatient;    

      vPPageRow."PtSig" := cPPageMap."PtSig";

      vPPageRow."PForm" := cPPageMap."PForm";    

      insert into ppage values vPPageRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ppage rows inserted.',vParams);

    

    -- Create ppagesig Records

    vCount := 0;

    for cPPageSigMap in curPPageSigMap(pvMapAudit) loop

      select * into vPPageSigRow from ppagesig where "PPage" = cPPageSigMap."OldPPage" and "PtSig" = cPPageSigMap."OldPtSig";

      vPPageSigRow."PPage" := cPPageSigMap."NewPPage";

      vPPageSigRow."PtSig" := cPPageSigMap."NewPtSig";

      insert into ppagesig values vPPageSigRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ppagesig rows inserted.',vParams);

  

    -- Map pitemimg Records

    insert into ax_map (

      select 

        pvMapAudit,

        'PITEMIMG', 

        pii."PItemImg", 

        pitemimg_Pitemimg_seq.nextval 

        ,null,null

      from 

        pitemimg pii

        inner join pitem pi on pi."PItemImg" = pii."PItemImg"

      where

        pi."Patient" = pSourcePatient and

        pi."Status" = 0

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

    

    -- Create pitemimg Records

    vCount := 0;

    for cPItemImgMap in curPItemImgMap(pvMapAudit) loop

      select * into vPItemImgRow from pitemimg where "PItemImg" = cPItemImgMap."SourceId";

      vPItemImgRow."PItemImg" := cPItemImgMap."TargetId";

      insert into pitemimg values vPItemImgRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' pitemimg rows inserted.',vParams);

    

    -- Map pitemcol Records

    insert into ax_map (

      select 

        pvMapAudit,

        'PITEMCOL', 

        pic."PItemCol", 

        pitemcol_Pitemcol_seq.nextval 

        ,null,null

      from 

        pitemcol pic

        inner join ax_map NewPF on NewPF."SourceId" = pic."PForm" and NewPF."Audit" = pvMapAudit and NewPF."TableName" = 'PFORM'

      where

        pic."Patient" = pSourcePatient

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

    

    -- Create pitemcol Records

    vCount := 0;

    for cPItemColMap in curPItemColMap(pvMapAudit) loop

      select * into vPItemColRow from pitemcol where "PItemCol" = cPItemColMap."SourceId";

      vPItemColRow."PItemCol" := cPItemColMap."TargetId";

      vPItemColRow."Patient" := pTargetPatient;

      vPItemColRow."PForm" := cPItemColMap."PForm";

      vPItemColRow."OrgPItemCol" := cPItemColMap."OrgPItemCol";

      insert into pitemcol values vPItemColRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' pitemcol rows inserted.',vParams);

    

    -- Map pitem Records

    insert into ax_map (

      select 

        pvMapAudit,

        'PITEM', 

        pi."PItem", 

        pitem_Pitem_seq.nextval 

        ,null,null

      from 

        pitem pi

        inner join ax_map NewPF on NewPF."SourceId" = pi."PForm" and NewPF."Audit" = pvMapAudit and NewPF."TableName" = 'PFORM'

      where

        pi."Patient" = pSourcePatient and

        pi."Status" = 0

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

    

    -- Create pitem Records

    vCount := 0;

    for cPItemMap in curPItemMap(pvMapAudit,pSourcePatient) loop

      select * into vPItemRow 

      from 

        pitem 

      where 

        "FormCode" = cPItemMap."OrigFormCode" and

        "Patient" = pSourcePatient and

        "PForm" = cPItemMap."OrigPForm" and

        "PItem" = cPItemMap."OrigPItem" and

        "FItem" = cPItemMap."OrigFItem" and

        "Status" = 0 and

        "AuditNumber" = cPItemMap."AuditNumber" and

        "PItemCol" = cPItemMap."OrigPItemCol"

      ;

      begin

        vPItemRow."Patient" := pTargetPatient;

        vPItemRow."PItem" := cPItemMap."NewPItem";

        vPItemRow."PItemImg" := cPItemMap."PItemImg";

        vPItemRow."PItemCol" := cPItemMap."PItemCol";

        vPItemRow."PForm" := cPItemMap."PForm";

        insert into pitem values vPItemRow;

        vCount := vCount + 1;

      exception

        when dup_val_on_index then

          ax_pkg.dbmsoutput_P(ax_pkg.MSG_ERROR,'bad data detected, check pitem and pitemcol tables for bad data. Not all records copied.',vParams);

      end;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' pitem rows inserted.',vParams);

    

    -- Create ptsig Records

    vCount := 0;

    for cPtSigMap in curPtSigMap(pvMapAudit) loop

      select * into vPtSigRow from ptsig where "PtSig" = cPtSigMap."SourceId";

      vPtSigRow."PtSig" := cPtSigMap."TargetId";

      insert into ptsig values vPtSigRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' ptsig rows inserted.',vParams);

    

    -- Create noteovr Records

    for cNoteOverMap in curNoteOvrMap1(pvMapAudit,pSourcePatient) loop

      select * into vNoteOvrRow from noteovr where "Id" = cNoteOverMap."Id"; 

      vNoteOvrRow."Id" := noteovr_id_seq.nextval;

      vNoteOvrRow."ParentId" := cNoteOverMap."TargetId";

      vNoteOvrRow."Patient" := pTargetPatient;

      insert into noteovr values vNoteOvrRow;

      vCount := vCount + 1;

    end loop;



  end CopyEPRFormRecords_P;

  

  

  -- Populate the Copy Params from the ax_setting table 

  PROCEDURE getcopysettings_p(INOUT pvcopyparams tcopyparams, INOUT pvisproduction character varying, IN poverridevalues boolean DEFAULT false, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vSettingRow ax_setting%rowtype;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    ax_pkg.InitializeSetting_P(vSettingRow);    

    -- Copy Params

    vSettingRow."Key" := 'CopyPatient.StatusCode';

    vSettingRow."Value" := trim(pvCopyParams."StatusCode");

    vSettingRow."Description" := 'set this to anything other than null to set the Status Code of copied patients';

    if pOverrideValues then

      pvCopyParams."StatusCode" := nvl(pvCopyParams."StatusCode",ax_pkg.GetSetting_F(vSettingRow,null,vParams));

    else

      pvCopyParams."StatusCode" := ax_pkg.GetSetting_F(vSettingRow,pvCopyParams."StatusCode",vParams);

    end if;



    vSettingRow."Key" := 'CopyPatient.Scramble';

    vSettingRow."Value" := nvl(trim(pvCopyParams."Scramble"),'0');

    vSettingRow."Description" := 'set to 1 to scramble basic contact information';

    if pOverrideValues then

      pvCopyParams."Scramble" := nvl(pvCopyParams."Scramble",ax_pkg.GetSetting_F(vSettingRow,null,vParams));

    else

      pvCopyParams."Scramble" := ax_pkg.GetSetting_F(vSettingRow,pvCopyParams."Scramble",vParams);

    end if;



    vSettingRow."Key" := 'CopyPatient.CopyGeneralNotes';

    vSettingRow."Value" := nvl(trim(pvCopyParams."CopyGeneralNotes"),'1');

    vSettingRow."Description" := 'set to 0 to skip copying of General Notes';

    if pOverrideValues then

      pvCopyParams."CopyGeneralNotes" := nvl(pvCopyParams."CopyGeneralNotes",ax_pkg.GetSetting_F(vSettingRow,null,vParams));

    else

      pvCopyParams."CopyGeneralNotes" := ax_pkg.GetSetting_F(vSettingRow,pvCopyParams."CopyGeneralNotes",vParams);

    end if;



    vSettingRow."Key" := 'CopyPatient.CopyTreatmentPlanning';

    vSettingRow."Value" := nvl(trim(pvCopyParams."CopyTreatmentPlanning"),'1');

    vSettingRow."Description" := 'set to 0 to skip copying of Treatment Planning';

    if pOverrideValues then

      pvCopyParams."CopyTreatmentPlanning" := nvl(pvCopyParams."CopyTreatmentPlanning",ax_pkg.GetSetting_F(vSettingRow,null,vParams));

    else

      pvCopyParams."CopyTreatmentPlanning" := ax_pkg.GetSetting_F(vSettingRow,pvCopyParams."CopyTreatmentPlanning",vParams);

    end if;



    vSettingRow."Key" := 'CopyPatient.CopyStickyNotes';

    vSettingRow."Value" := nvl(trim(pvCopyParams."CopyStickyNotes"),'1');

    vSettingRow."Description" := 'set to 0 to skip copying of Sticky Notes';

    if pOverrideValues then

      pvCopyParams."CopyStickyNotes" := nvl(pvCopyParams."CopyStickyNotes",ax_pkg.GetSetting_F(vSettingRow,null,vParams));

    else

      pvCopyParams."CopyStickyNotes" := ax_pkg.GetSetting_F(vSettingRow,pvCopyParams."CopyStickyNotes",vParams);

    end if;



    vSettingRow."Key" := 'CopyPatient.CopyAttachments';

    vSettingRow."Value" := nvl(trim(pvCopyParams."CopyAttachments"),'1');

    vSettingRow."Description" := 'set to 0 to skip copying of Attachments';

    if pOverrideValues then

      pvCopyParams."CopyAttachments" := nvl(pvCopyParams."CopyAttachments",ax_pkg.GetSetting_F(vSettingRow,null,vParams));

    else

      pvCopyParams."CopyAttachments" := ax_pkg.GetSetting_F(vSettingRow,pvCopyParams."CopyAttachments",vParams);

    end if;



    vSettingRow."Key" := 'CopyPatient.CopyEPRForms';

    vSettingRow."Value" := nvl(trim(pvCopyParams."CopyEPRForms"),'1');

    vSettingRow."Description" := 'set to 0 to skip copying of EPR Forms';

    if pOverrideValues then

      pvCopyParams."CopyEPRForms" := nvl(pvCopyParams."CopyEPRForms",ax_pkg.GetSetting_F(vSettingRow,null,vParams));

    else

      pvCopyParams."CopyEPRForms" := ax_pkg.GetSetting_F(vSettingRow,pvCopyParams."CopyEPRForms",vParams);

    end if;



    vSettingRow."Key" := 'CopyPatient.CopyInsurance';

    vSettingRow."Value" := nvl(trim(pvCopyParams."CopyInsurance"),'1');

    vSettingRow."Description" := 'set to 0 to skip copying of Insurance';

    if pOverrideValues then

      pvCopyParams."CopyInsurance" := nvl(pvCopyParams."CopyInsurance",ax_pkg.GetSetting_F(vSettingRow,null,vParams));

    else

      pvCopyParams."CopyInsurance" := ax_pkg.GetSetting_F(vSettingRow,pvCopyParams."CopyInsurance",vParams);

    end if;



    vSettingRow."Key" := 'CopyPatient.CopyContactNotes';

    vSettingRow."Value" := nvl(trim(pvCopyParams."CopyContactNotes"),'1');

    vSettingRow."Description" := 'set to 0 to skip copying of Contact Notes';

    if pOverrideValues then

      pvCopyParams."CopyContactNotes" := nvl(pvCopyParams."CopyContactNotes",ax_pkg.GetSetting_F(vSettingRow,null,vParams));

    else

      pvCopyParams."CopyContactNotes" := ax_pkg.GetSetting_F(vSettingRow,pvCopyParams."CopyContactNotes",vParams);

    end if;



    vSettingRow."Key" := 'CopyPatient.CopyEmergencyContact';

    vSettingRow."Value" := nvl(trim(pvCopyParams."CopyEmergencyContact"),'1');

    vSettingRow."Description" := 'set to 0 to skip copying of Emergency Contact Information';

    if pOverrideValues then

      pvCopyParams."CopyEmergencyContact" := nvl(pvCopyParams."CopyEmergencyContact",ax_pkg.GetSetting_F(vSettingRow,null,vParams));

    else

      pvCopyParams."CopyEmergencyContact" := ax_pkg.GetSetting_F(vSettingRow,pvCopyParams."CopyEmergencyContact",vParams);

    end if;

    

    vSettingRow."Key" := 'CopyPatient.CopyPerio';

    vSettingRow."Value" := nvl(trim(pvCopyParams."CopyPerio"),'1');

    vSettingRow."Description" := 'set to 0 to skip copying of Perio Information';

    if pOverrideValues then

      pvCopyParams."CopyPerio" := nvl(pvCopyParams."CopyPerio",ax_pkg.GetSetting_F(vSettingRow,null,vParams));

    else

      pvCopyParams."CopyPerio" := ax_pkg.GetSetting_F(vSettingRow,pvCopyParams."CopyPerio",vParams);

    end if;

    

    vSettingRow."Key" := 'CopyPatient.CopyTreatments';

    vSettingRow."Value" := nvl(trim(pvCopyParams."CopyTreatments"),'1');

    vSettingRow."Description" := 'set to 0 to skip copying of Treatments';

    if pOverrideValues then

      pvCopyParams."CopyTreatments" := nvl(pvCopyParams."CopyTreatments",ax_pkg.GetSetting_F(vSettingRow,null,vParams));

    else

      pvCopyParams."CopyTreatments" := ax_pkg.GetSetting_F(vSettingRow,pvCopyParams."CopyTreatments",vParams);

    end if;

    

    -- Is Production

    vSettingRow."Key" := 'Environment.IsProduction';

    vSettingRow."Value" := nvl(trim(pvIsProduction),'1');

    vSettingRow."Description" := 'If this is a Production Database, this should be set to 1. Otherwise 0.';

    if pOverrideValues then

      pvIsProduction := nvl(pvIsProduction,ax_pkg.GetSetting_F(vSettingRow,null,vParams));

    else

      pvIsProduction := ax_pkg.GetSetting_F(vSettingRow,pvIsProduction,vParams);

    end if;    

  end GetCopySettings_P;

  

  

 -- Copy a Patient Record

  PROCEDURE copypatient_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN psourcepatient numeric, IN pcopyparams tcopyparams DEFAULT ax_copy_pkg.ax_copy_params, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

  -- Variables

    vTargetPatient patient."Patient"%type;

    vMapAudit audithis."Audit"%type;

    vExists number;

    vSuccess boolean;

    vLogId ax_log."LogId"%type := null;

    vLogRow ax_log%rowtype;

    vParams ax_pkg.tParams := pParams;

    vCopyParams tCopyParams := pCopyParams;

    vIsProduction ax_setting."Value"%type;

    vUsersRow users%rowtype;

    vTitle patient."Title"%type;

    vPos number;

    vProvider varchar(2000);

  -- Exceptions

    exNoPatient exception;

    exTooManyPatients exception;

    exCopyFailed exception;

    exInvalidUser exception;

    exIsProduction exception;

  begin

    -- If anything fails, return a false Success

    pvSuccess := false;

    ax_pkg.InitializeParams_P(vParams);

	-- AX-39259

    vLogRow."Source" := 'AX_COPY_PKG' || '.CopyPatient_P';

    

    vLogRow."Log" := 'Copying Patient ' || pSourcePatient;

    ax_pkg.log_p(vLogRow,ax_pkg.MSG_INFO,vParams);



  -- Load Settings (null parameter values will be overwritten by data in the ax_setting table)  

    GetCopySettings_P(vCopyParams,vIsProduction,false,vParams);

 

    if vIsProduction <> '0' then

      raise exIsProduction;

    end if;

  

    -- Set vUser

    if vParams."User" is null then

      raise exInvalidUser;

    end if;

    

    -- Find Source Patient Record

    if pSourcePatient is not null then

      begin    

       select 1,"Title" into vExists,vTitle from patient where "Patient" = pSourcePatient;     

      exception

        when no_data_found then

          raise exNoPatient;

        when too_many_rows then

          raise exTooManyPatients;

      end;

    end if;

  

  -- Validate vStatusCode

    if trim(vCopyParams."StatusCode") is not null then

      begin

        select "Status" into vCopyParams."StatusCode" from status where "Type" = 2 and "Status" = vCopyParams."StatusCode" and "Inactive" = 0;

      exception

        when no_data_found then

			-- AX-39259

          vLogRow."Source" := 'AX_COPY_PKG'|| '.CopyPatient_P';

          vLogRow."Log" := 'Patient Status ' || vCopyParams."StatusCode" || ' is invalid.';

          ax_pkg.log_p(vLogRow,ax_pkg.MSG_WARNING,vParams);   

          vCopyParams."StatusCode" := null;

      end;

    end if;



  -- Copy the Main Patient Information

    -- vMapAudit is set here, then used in later functions to tie it all together

    CopyPatientRecords_P(

      vSuccess,

      pvMessage,

      pSourcePatient,

      vTargetPatient,

      vMapAudit,

      vCopyParams,

      vParams

    );

    

    if vParams."VerboseType" = ax_pkg.SHOW_DEBUG then

      vLogRow."Log" := 'Batch Audit Number is ' || vMapAudit;

      ax_pkg.log_p(vLogRow,ax_pkg.MSG_INFO,vParams);

    end if;    

   

    if not vSuccess then

      raise exCopyFailed;

    end if;

    

  -- Copy Additional Patient Information, based on the associated Settings

    -- Provider Demographics

    if vCopyParams."CopyFirstProviderDemographics" and trim(vCopyParams."Providers") is not null then

      begin

        -- Find Provider Code

        vPos := instr(vCopyParams."Providers",',');

        if vPos = 0 then

          vProvider := trim(vCopyParams."Providers");

        else

          vProvider := trim(substr(vCopyParams."Providers",1,vPos-1));

        end if;

        -- Gather User Information based on Provider Code

        select * into vUsersRow from users where 

          trim("Producer") = trim(vProvider) and

          "Deleted" = 0 and

          (

            "EffDate" is null or 

            nvl(vCopyParams."ProdStartDate",sysdate) >= "EffDate"

          ) and (

            "ExpDate" is null or 

            "ExpDate" >= nvl(vCopyParams."ProdEndDate",sysdate) 

          );

        -- Adjust Patient."Title"

          -- But only if it is one of the standard Gender based titles

        if upper(trim(vTitle)) in (

          'MR.',

          'MR',

          'MISS.',

          'MISS',

          'MRS.',

          'MRS',

          'MS',

          'MS.'

        ) then

          -- Male User

          if vUsersRow."Sex" = 1 then

            begin

              select "Title" into vTitle from title where upper("Title") like 'MR%' and "DefaultSex" = 1 and rownum = 1;

            exception

              when no_data_found then

                null; -- leave title as is

            end;

          -- Female User

          elsif vUsersRow."Sex" = 2 then

            begin

              select "Title" into vTitle from title where upper("Title") like 'MISS%' and "DefaultSex" = 2 and rownum = 1;

            exception

              when no_data_found then

                -- If Miss does not exist, look for Ms.

                begin

                  select "Title" into vTitle from title where upper("Title") like 'MS%' and "DefaultSex" = 2 and rownum = 1;

                exception

                  when no_data_found then

                    null; -- leave title as is

                end;

            end;

          -- Unknown or Transgendered User

          else

            null; -- leave title as is

          end if;

        end if;

      dbms_output.put_line(vTitle);

        -- Update the Patient Record with values from the Users Record

        update patient set

          "Last" = ax_pkg.CropToFieldSize_F(vUsersRow."Name",'Patient','Last'),

          "First" = ax_pkg.CropToFieldSize_F(vUsersRow."First",'Patient','First'),

          "Prefered" = ax_pkg.CropToFieldSize_F(vUsersRow."Preferred",'Patient','Prefered'),

          "Birth" = vUsersRow."Birth",

          "Address1" = ax_pkg.CropToFieldSize_F(vUsersRow."Address1",'Patient','Address1'),

          "Address2" = ax_pkg.CropToFieldSize_F(vUsersRow."Address2",'Patient','Address2'),

          "City" = ax_pkg.CropToFieldSize_F(vUsersRow."City",'Patient','City'),

          "Province" = ax_pkg.CropToFieldSize_F(vUsersRow."Province",'Patient','Province'),

          "Postal" = ax_pkg.CropToFieldSize_F(vUsersRow."Postal",'Patient','Postal'),

          "HomeArea" = ax_pkg.CropToFieldSize_F(vUsersRow."HomeArea",'Patient','HomeArea'),

          "HomePhone" = ax_pkg.CropToFieldSize_F(vUsersRow."HomePhone",'Patient','HomePhone'),

          "HomeExt" = '',

          "Sex" = vUsersRow."Sex",

          "Title" = vTitle

        where

          "Patient" = vTargetPatient;

      exception

        when no_data_found then

          null; -- Nothing to copy

          -- append to pvMessage

      end;    

    end if;

  

    -- attachments

      -- This should come before CopyTreatments and CopyTreatmentPlanning

    if vCopyParams."CopyAttachments" = '1' then

      CopyAttachmentRecords_P(pSourcePatient,vTargetPatient,vMapAudit,vParams);  

    end if;

    -- treatment planning records

      -- This should come before CopyTreatments but after CopyAttachments

    if vCopyParams."CopyTreatmentPlanning" = '1' then

      CopyTreatmentPlanningRecords_P(pSourcePatient,vTargetPatient,vMapAudit,vParams);        

    end if;

    -- treatme2 and trx records

    if vCopyParams."CopyTreatments" = '1' then

      -- This should come after CopyTreatmentPlanning and CopyAttachments

      CopyTreatmentRecords_P(pSourcePatient,vTargetPatient,vMapAudit,vParams,vCopyParams."CopyInsurance");  

    end if;    

    -- perio records

    if vCopyParams."CopyPerio" = '1' then

      CopyPerioRecords_P(pSourcePatient,vTargetPatient,vMapAudit,vParams,vCopyParams."CopyInsurance");

    end if;

    -- EPR Forms

    if vCopyParams."CopyEPRForms" = '1' then

      CopyEPRFormRecords_P(pSourcePatient,vTargetPatient,vMapAudit,vParams);    

    end if;

    -- Contact Notes

    if vCopyParams."CopyContactNotes" = '1' then

      CopyContactNoteRecords_P(pSourcePatient,vTargetPatient,vMapAudit,vParams);    

    end if;

    -- Sticky Notes

    if vCopyParams."CopyStickyNotes" = '1' then

      CopyStickyNoteRecords_P(pSourcePatient,vTargetPatient,vMapAudit,vParams);    

    end if;

    -- General Notes

      -- This should come last

    if vCopyParams."CopyGeneralNotes" = '1' then

      CopyNotes2Records_P(pSourcePatient,vTargetPatient,vMapAudit,vParams);  

    end if;

    

  -- Set Provider Assignments based on pProducers

    ax_assign_pkg.PtProdAssign_P(

      vTargetPatient,

      vCopyParams."Providers", -- comma delimited list of producer."Producer"

      vCopyParams."ArePrimary",

      vCopyParams."ProdStartDate",

      vCopyParams."ProdEndDate",

      vParams

    );



  -- Cleanup the ax_map table, leave on the Patient record to show that a Copy was performed

    -- leave the records there if running in Debug Mode

    if vParams."VerboseType" <> ax_pkg.SHOW_DEBUG then

      delete from ax_map where "Audit" = vMapAudit and "TableName" <> 'PATIENT';

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' rows deleted from ax_map.',vParams);

    end if; 



  -- All done!

    vLogRow."Log" := 'Patient ' || pSourcePatient || ' successfully copied to Patient ' || vTargetPatient;

    ax_pkg.log_p(vLogRow,ax_pkg.MSG_INFO,vParams);    

    pvSuccess := true;

  

  exception

    when exIsProduction then

    -- Script should not run on a production database

      vLogRow."Log" := 'This procedure will not run on a production database. ax_setting."Value" must be set to 0 where "Key"=''Environment.IsProduction''';

      ax_pkg.log_p(vLogRow,ax_pkg.MSG_ERROR,vParams);     

    when exNoPatient then

    -- check pSourcePatient and change message accordingly

      vLogRow."Log" := 'No Patient found to copy.';

      ax_pkg.log_p(vLogRow,ax_pkg.MSG_ERROR,vParams);     

      rollback;        

    when exTooManyPatients then 

    -- check pSourcePatient and change message accordingly

      vLogRow."Log" := 'Too many patients found, try providing the Patient Id.';

      ax_pkg.log_p(vLogRow,ax_pkg.MSG_ERROR,vParams);    

      rollback;        

    when exCopyFailed then

      vLogRow."Log" := pvMessage;

      ax_pkg.log_p(vLogRow,ax_pkg.MSG_ERROR,vParams);    

      rollback;        

    when exInvalidUser then

      vLogRow."Log" := pParams."User" || ' is an invalid user.';

      ax_pkg.log_p(vLogRow,ax_pkg.MSG_ERROR,vParams);    

      rollback;

    when others then 

      vLogRow."Log" := SQLERRM || ' ' || DBMS_UTILITY.FORMAT_ERROR_BACKTRACE;

      ax_pkg.log_p(vLogRow,ax_pkg.MSG_ERROR,vParams);

      if vParams."VerboseType" <> ax_pkg.SHOW_DEBUG then

        rollback;

      end if;

  end CopyPatient_P;

  

  

  -- Copy a Patient Record

    -- short override

  PROCEDURE copypatient_p(IN psourcepatient numeric, IN pcopyparams tcopyparams DEFAULT ax_copy_pkg.ax_copy_params, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vSuccess boolean;

    vMessage  VARCHAR2(4000);

  begin

    CopyPatient_P(vSuccess,vMessage,pSourcePatient,pCopyParams,pParams);

    if not vSuccess then

      raise_application_error(-20000, vMessage);

    end if;   

  end CopyPatient_P;

  



 -- Copy a Patient Record

    -- to be depreciated  

  PROCEDURE copypatient_p(INOUT pvsuccess numeric, IN psourcepatient numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN ppatientloopaudit numeric DEFAULT 0, IN ptargetchart character DEFAULT '%'::bpchar, IN plast character DEFAULT '%'::bpchar, IN pfirst character DEFAULT '%'::bpchar, IN pmiddle character DEFAULT '%'::bpchar, IN pproducers character varying DEFAULT NULL::character varying, IN pareprimary character varying DEFAULT '1'::character varying, IN pprodassignstartdate timestamp without time zone DEFAULT NULL::timestamp without time zone, IN pprodassignenddate timestamp without time zone DEFAULT NULL::timestamp without time zone, IN pstatuscode character varying DEFAULT NULL::character varying, IN pscramble character varying DEFAULT NULL::character varying, IN pcopygeneralnotes character varying DEFAULT NULL::character varying, IN pcopytreatmentplanning character varying DEFAULT NULL::character varying, IN pcopystickynotes character varying DEFAULT NULL::character varying, IN pcopyattachments character varying DEFAULT NULL::character varying, IN pcopyeprforms character varying DEFAULT NULL::character varying, IN pcopyinsurance character varying DEFAULT NULL::character varying, IN pcopycontactnotes character varying DEFAULT NULL::character varying, IN pcopyemergencycontact character varying DEFAULT NULL::character varying) IS

    vCopyParams tCopyParams := AX_COPY_PARAMS;

    vMessage varchar(4000);

    vSuccess boolean;

  begin  

    -- Set vCopyParams

    vCopyParams."LoopAudit" := pPatientLoopAudit;

    vCopyParams."TargetChart" := pTargetChart;

    vCopyParams."Last" := pLast; 

    vCopyParams."First" := pFirst;

    vCopyParams."Middle" := pMiddle;    

    vCopyParams."Providers" := pProducers;

    vCopyParams."ArePrimary" := pArePrimary;

    vCopyParams."ProdStartDate" := pProdAssignStartDate;

    vCopyParams."ProdEndDate" := pProdAssignEndDate;

    vCopyParams."StatusCode" := pStatusCode;

    vCopyParams."Scramble" := pScramble;

    vCopyParams."CopyGeneralNotes" := pCopyGeneralNotes;

    vCopyParams."CopyTreatmentPlanning" := pCopyTreatmentPlanning;

    vCopyParams."CopyStickyNotes" := pCopyStickyNotes;

    vCopyParams."CopyAttachments" := pCopyAttachments;

    vCopyParams."CopyEPRForms" := pCopyEPRForms;

    vCopyParams."CopyInsurance" := pCopyInsurance;

    vCopyParams."CopyContactNotes" := pCopyContactNotes;

    vCopyParams."CopyEmergencyContact" := pCopyEmergencyContact;

    

    -- Call Parent Procedure

    CopyPatient_P(

      vSuccess,

      vMessage,

      pSourcePatient,

      vCopyParams,

      pParams

    );

    

    if vSuccess then

      pvSuccess := 1;

    else

      pvSuccess := 0;

    end if;

  end CopyPatient_P;

  



  -- Cleanup ax_map table after running in debug mode

  PROCEDURE ax_clearax_map_p(IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

  begin

     -- Retain 1 record for each CopyPatient_P or CopyMappedAnswers_P

     delete from ax_map m where 

         m."TableName" not in ('PATIENT','FORM') or

         (

           m."TableName" = 'FORM' and

           exists ( select 1 from ax_map s where s."Audit" = m."Audit" and s."TableName" = 'PATIENT' )

          )

     ; 

  end AX_ClearAX_Map_P;

  

  

  -- This procedure copies answers from one form to another

  -- This procedure differs from CopyEPRFormRecords_P in that it is copying from one Type of Form to Another

  -- Matching the FItem."Code" values

  PROCEDURE copymappedanswers_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN pmapaudit numeric, IN poverwriteexisting boolean DEFAULT false, IN pclearmapping boolean DEFAULT false, IN pfstatus character DEFAULT NULL::bpchar, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    cursor curPForms(pAudit audithis."Audit"%type) is

      select 

        pf."Patient",

        pf."FormCode",

        pf."PForm"

      from

        pform pf

        inner join ax_map m on m."TargetId" = pf."PForm" and m."TableName" = 'PFORM' and m."Audit" = pAudit

    ;  

    cursor curPItemImgMap(pAudit audithis."Audit"%type) is

      select

        NewPI."TargetId",

        NewPI."SourceId"

      from

        ax_map NewPI

      where

        NewPI."TableName" = 'PITEMIMG' and

        NewPI."Audit" = pAudit

    ;    

    cursor curPItemColMap(pAudit audithis."Audit"%type) is

      select

        NewPIC."TargetId",

        NewPIC."SourceId",

        NewPF."TargetId" "PForm",

        NewOPIC."TargetId" "OrgPItemCol"

      from

        ax_map NewPIC

        inner join pitemcol pic on pic."PItemCol" = NewPIC."SourceId"

        inner join ax_map NewPF on NewPF."SourceId" = pic."PForm" and NewPF."TableName" = 'PFORM' and NewPF."Audit" = pAudit

        left outer join ax_map NewOPIC on NewOPIC."SourceId" = pic."OrgPItemCol" and NewOPIC."TableName" = 'PITEMCOL' and NewOPIC."Audit" = pAudit

      where

        NewPIC."TableName" = 'PITEMCOL' and

        NewPIC."Audit" = pAudit

    ;  

    cursor curNoteOvrMap1(pAudit audithis."Audit"%type) is

      select

        NewPI."SourceId",

        NewPI."TargetId",

        nto."Id"

      from

        noteovr nto 

        inner join ax_map NewPI on NewPI."SourceId" = nto."ParentId" and NewPI."TableName" = 'PITEM' and NewPI."Audit" = pAudit

      where

        nto."Deleted" = 0 and

        nto."Type" = 1

    ;

    -- Do not filter source by deleted, to make sure all active answer are included

    cursor curQuestions(

      pTargetForm form."Code"%type,

      pSourceForm form."Code"%type,

      pMapAudit audithis."Audit"%type

    )is

      select 

        s."Code"    "Code", 

        s."FItem"   "SourceFItem",

        t."FItem"   "TargetFItem",

        s."AnsType" "SourceType",

        t."AnsType" "TargetType",

        s."AnsList" "SourceList",

        t."AnsList" "TargetList"

      from 

        ax_map q

        inner join fitem s on

          s."FormCode" = pSourceForm and

          s."Code" = q."SourceCode" and

          s."Deleted" = 0

        inner join fitem t on 

          t."FormCode" = pTargetForm and 

          t."Code" = q."TargetCode" and

          t."Deleted" = 0

      where 

        q."Audit" = pMapAudit and

        q."TableName" = 'FITEM' and

        s."FormCode" = pSourceForm

      order by

        s."Code"

    ;    

    vTargetForm form."Code"%type;

    vSourceForm form."Code"%type;    

    

    vParams ax_pkg.tParams := pParams;

    vSourceCanHaveMultiple form."Multiple"%type;

    vTargetCanHaveMultiple form."Multiple"%type;

    vLastRefCode fitem."Code"%type := ' ';

    

    vAuditHisRow audithis%rowtype;

    vLogRow ax_log%rowtype;

    vPPageRow ppage%rowtype;

    vPItemImgRow pitemimg%rowtype;

    vSourceList fitem."AnsList"%type;

    vTargetList fitem."AnsList"%type;

    vPItemColRow pitemcol%rowtype;

    vNoteOvrRow noteovr%rowtype;



    vExists number;

    vCount number;

    

    vItemSuccess boolean;

    vItemMessage  VARCHAR2(4000);

    

    exSourceNotFound exception;

    exTargetNotFound exception;

    exNothingToCopy  exception;

    exNotCompatible  exception;

    exMappingNotFound exception;

    exBadData exception;

  begin

    pvSuccess := false;

    ax_pkg.InitializeParams_P(vParams);

    if not pParams."IsInit" then

      vParams."VerboseType" := ax_pkg.SHOW_INFO;

    end if;

	-- AX-39259

    vLogRow."Source" := 'AX_COPY_PKG' || '.CopyMappedAnswers_P';



    -- Get the Source and Target forms from the ax_map table

    begin

      select 

        "SourceCode","TargetCode" into vSourceForm, vTargetForm

      from ax_map

      where

        "Audit" = pMapAudit and 

        "TableName" = 'FORM';

    exception

      when no_data_found then

        raise exMappingNotFound;

    end;

       

    -- Error Checks

    

    -- Check to see if SourceForm Exists

    begin

      -- It does not matter if the source form is inactive, 

      --  as it may have been inactivated for this migration

      select 

        "Multiple" into vSourceCanHaveMultiple

      from 

        form

      where

        "Code" = vSourceForm;

    exception

      when no_data_found then

        raise exSourceNotFound;

    end;

    

    -- Check to see if TargetForm Exists

    begin

      -- It does not matter if the source form is inactive, 

      --  as it may not be made active until after this migration

      select 

        "Multiple" into vTargetCanHaveMultiple

      from 

        form

      where

        "Code" = vTargetForm;

    exception

      when no_data_found then

        raise exTargetNotFound;

    end;        

    

    -- If the Source form can have multiple, but the Target form cannot

    --   then we cannot move forward

    begin

      -- Make sure that there are multiple copies of the source form

      select 1 into vExists 

      from

        pform pf1

      inner join pform pf2 on 

        pf1."FormCode" = pf2."FormCode" and

        pf1."OwnerId" = pf2."OwnerId" and

        pf1."Inactive" = pf2."Inactive" and

        pf1."PForm" > pf2."PForm"

      where

        pf1."FormCode" = vSourceForm and

        pf1."Inactive" = 0 and

        rownum = 1;

      raise exNotCompatible;

    exception

      when no_data_found then

        -- this means we can continue anyway

        null;

    end;

          

    if vSourceCanHaveMultiple > vTargetCanHaveMultiple and vExists = 1 then

      raise exNotCompatible;

    elsif vSourceForm = vTargetForm and vExists = 1 then

      raise exBadData;  

    end if;

      

    -- passed error checks  

      

    if vParams."VerboseType" > ax_pkg.SHOW_NONE then

      vLogRow."Log" := 'Copying Answers from ' || vSourceForm || ' to ' || vTargetForm;

      ax_pkg.log_p(vLogRow,ax_pkg.MSG_INFO,vParams);

    end if;





   --------------

    -- Copy PForm

    --------------

    

    -- Only do this if the form can have multiples 

    -- -or- 

    -- the target patient does not have a copy of this form yet

   

    -- Map new pform Records

    insert into ax_map (

      select 

        pMapAudit,

        'PFORM', 

        "PForm", 

        pform_Pform_seq.nextval

        ,null,null

      from 

        pform pf1

      where

        "FormCode" = vSourceForm and

        "Inactive" = 0 and

        (

          vTargetCanHaveMultiple = 1 or

          not exists ( 

            select 

              1

            from

              pform pf2

            where

              pf2."FormCode" = vTargetForm and

              pf1."OwnerId" = pf2."OwnerId" and

              pf1."Inactive" = pf2."Inactive" and

              rownum = 1

          )

        )

    );

    vCount := SQL%rowcount;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(vCount) || ' ax_map rows inserted.',vParams);  

    --------------

    -- Map Existing PForms

    --------------

    if vTargetCanHaveMultiple = 0 then

      insert into ax_map (

        select 

          pMapAudit,

          'PFORM', 

          pf1."PForm", 

          pf2."PForm"

          ,null,null

        from 

          pform pf1

          inner join pform pf2 on 

            pf2."FormCode" = vTargetForm and

            pf1."OwnerId" = pf2."OwnerId" and

            pf1."Inactive" = pf2."Inactive"

        where

          pf1."FormCode" = vSourceForm and

          pf1."Inactive" = 0 and

          pf1."PForm" not in (

            select 

              "SourceId"

            from

              ax_map

            where

              "Audit" = pMapAudit and

              "SourceId" = pf1."PForm"

          )

      );

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);     

    end if;

    --------------

    -- Copy PPageSig

    --------------        

    -- Do not copy signatures, as the patient signed a different version of the form

    

    ----------------

    -- Copy PItemImg

    ---------------- 

    

    -- Map pitemimg Records

    insert into ax_map (

      select 

        pMapAudit,

        'PITEMIMG', 

        pii."PItemImg", 

        pitemimg_Pitemimg_seq.nextval 

        ,null,null

      from 

        pitemimg pii

        inner join pitem pi on pi."PItemImg" = pii."PItemImg"

        inner join ax_map m on m."SourceId" = pi."PForm" and m."TableName" = 'PFORM' and m."Audit" = pMapAudit

      where

        pi."Status" = 0

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);





    ----------------

    -- Copy PItemCol

    ----------------    

    -- Map pitemcol Records

    insert into ax_map (

      select 

        pMapAudit,

        'PITEMCOL', 

        pic."PItemCol", 

        pitemcol_Pitemcol_seq.nextval 

        ,null,null

      from 

        pitemcol pic

        inner join ax_map NewPF on NewPF."SourceId" = pic."PForm" and NewPF."Audit" = pMapAudit and NewPF."TableName" = 'PFORM'

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);



    --------------

    -- Copy PForm

    --------------

    

    -- find this?

 --   if vCount = 0 then

--      raise exNothingToCopy;

    -- end if;

    

      insert into pform (

        select

          s."Patient", -- Patient

          vTargetForm, -- FormCode

          trunc(sysdate), -- Date

          vParams."User", -- User

          t."TargetId", -- PForm

          s."Description", -- Description

          s."OwnerType", -- OwnerType

          s."OwnerId", -- OwnerId

          s."CreatedDate", -- CreatedDate

          s."Approved", -- Approved

          s."LastAppUser", -- LastAppUser

          s."LastAppDate", -- LastAppDate

          s."Inactive", -- Inactive

          s."InactiveAppUser", -- InactiveAppUser

          s."InactiveAppDate", -- InactiveAppDate

          s."InactiveReason", -- InactiveReason

          nvl(nvl(pFStatus,fs."FStatus"),ds."FStatus"), -- FStatus -- Use pFStatus, then s."FStatus" if it has a matching value for the new form, then the default status for the new form

          s."AssignedUser", -- AssignedUser

          s."AssignedUGroup", -- AssignedUGroup

          s."LastStartDateTime"

        from

          pform s

          inner join ax_map t on t."SourceId" = s."PForm" and t."TableName" = 'PFORM' and t."Audit" = pMapAudit

          left outer join pform tf on tf."PForm" = t."TargetId"

          left outer join fstatus fs on fs."FormCode" = vTargetForm and fs."FStatus" = s."FStatus" and fs."Inactive" = 0

          left outer join fstatus ds on ds."FormCode" = vTargetForm and ds."Inactive" = 0 and ds."IsDefault" = 1

        where

          s."FormCode" = vSourceForm and

          s."Inactive" = 0 and

          tf."PForm" is null

      );

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' pform rows inserted.',vParams);

    

  --  end if;

    

    --------------

    -- Create PPage

    --------------

    -- Create ppage Records

    vCount := 0;

    for cPForm in curPForms(pMapAudit) loop

      insert into ppage (

        select

          cPForm."Patient",

          cPForm."FormCode",

          fi."FItem",

          'Copied from ' || vSourceForm,

          trunc(sysdate),

          vParams."User",

          0,

          1,

          fi."FItem",

          0,

          null,

          cPForm."PForm",

          ppage_Ppage_seq.nextval,

          sysdate,

          null

        from

          fitem fi          

        where

          fi."FormCode" = vTargetForm and

          fi."Type" = 0 and

          fi."Deleted" = 0 and 

          fi."FItem" not in (

            select 

              "FItem"

            from

              ppage pp

            where

              pp."FormCode" = cPForm."FormCode" and

              pp."Patient" = cPForm."Patient" and

              pp."PForm" = cPForm."PForm" and

              pp."AuditNumber" = 1 and

              pp."FItem" = fi."FItem"

          )

      );

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ppage rows inserted.',vParams);

    end loop;

    

    --------------

    -- Copy PPageSig

    --------------        

    -- Do not copy signatures, as the patient signed a different version of the form

    

    ----------------

    -- Copy PItemImg

    ---------------- 

    

    -- Create pitemimg Records

    vCount := 0;

    for cPItemImgMap in curPItemImgMap(pMapAudit) loop

      select * into vPItemImgRow from pitemimg where "PItemImg" = cPItemImgMap."SourceId";

      vPItemImgRow."PItemImg" := cPItemImgMap."TargetId";

      insert into pitemimg values vPItemImgRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' pitemimg rows inserted.',vParams);

    

    ----------------

    -- Copy PItemCol

    ----------------    

    -- Create pitemcol Records

    vCount := 0;

    for cPItemColMap in curPItemColMap(pMapAudit) loop

      select * into vPItemColRow from pitemcol where "PItemCol" = cPItemColMap."SourceId";

      vPItemColRow."PItemCol" := cPItemColMap."TargetId";

      vPItemColRow."PForm" := cPItemColMap."PForm";

      vPItemColRow."FormCode" := vTargetForm;

      vPItemColRow."OrgPItemCol" := cPItemColMap."OrgPItemCol";

      insert into pitemcol values vPItemColRow;

      vCount := vCount + 1;

    end loop;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' pitemcol rows inserted.',vParams);

    

    for cQuestions in curQuestions(

      vTargetForm,

      vSourceForm,

      pMapAudit

    ) loop

    

    vLogRow."Request" := 'Copying Answers';

    vLogRow."Source" := 'ax_copy_pkg.CopyMappedAnswers_P';

    vLogRow."Log" := 

      cQuestions."Code" || ',' || 

      cQuestions."SourceFItem" || ',' ||

      cQuestions."TargetFItem" || ',' ||

      cQuestions."SourceType" || ',' ||

      cQuestions."TargetType" || ',' ||

      cQuestions."SourceList" || ',' ||

      cQuestions."TargetList";

    ax_pkg.log_p(vLogRow,ax_pkg.MSG_INFO); -- log the message

    

      if (cQuestions."SourceType" = ax_pkg.ANSWER_LIST and cQuestions."TargetType" = ax_pkg.ANSWER_LIST) then

        begin

          select "AnsList" into vSourceList from fitem

          where 

            "FormCode" = vSourceForm and

            "Code" = cQuestions."Code" and 

            "Deleted" = 0;        

        exception

          when no_data_found then

            raise exSourceNotFound;

        end;   

        begin

          select "AnsList" into vTargetList from fitem

          where 

            "FormCode" = vTargetForm and

            "Code" = cQuestions."Code" and 

            "Deleted" = 0;        

        exception

          when no_data_found then

            raise exTargetNotFound;

        end;     

      end if;

      

      --------------

      -- Copy PPageSig

      --------------        

      -- Do not copy signatures, as the patient signed a different version of the form

        

      commit;  

        

      --------------

      -- Copy PItem

      --------------   

  

      if (  

         -- List Type Questions must also have the same List Type

           --  If the List Type does not match, we can attempt to convert based on Reference Codes (see below)

           cQuestions."SourceType" = ax_pkg.ANSWER_LIST and

           cQuestions."TargetType" = ax_pkg.ANSWER_LIST and

           vSourceList = vTargetList 

         ) or (

           -- Questions are the exact same type

           cQuestions."SourceType" = cQuestions."TargetType" and

           cQuestions."SourceType" <> ax_pkg.ANSWER_LIST

         ) or (

           -- Image to Attachment

           cQuestions."SourceType" = ax_pkg.ANSWER_IMAGE and

           cQuestions."TargetType" = ax_pkg.ANSWER_ATTACHMENT

         ) or (         

           -- Answers are all stored in the AnsText field

           (

             cQuestions."SourceType" = ax_pkg.ANSWER_TEXT or

             cQuestions."SourceType" = ax_pkg.ANSWER_LONG_TEXT or 

             cQuestions."SourceType" = ax_pkg.ANSWER_CALCULATED or 

             cQuestions."SourceType" = ax_pkg.ANSWER_NUMBER

           ) and (

             cQuestions."TargetType" = ax_pkg.ANSWER_TEXT or

             cQuestions."TargetType" = ax_pkg.ANSWER_LONG_TEXT or 

             cQuestions."TargetType" = ax_pkg.ANSWER_CALCULATED        

           )

         )

      then

        -- The Questions are the same type, or close enough

        insert into pitem (

          select

            pi."Patient", -- Patient

            vTargetForm, -- FormCode

            t."FItem", -- FItem

            t."AnsType", -- AnsType

            pi."AnsYes", -- AnsYes

            pi."AnsText", -- AnsText

            pi."AnsList", -- AnsList

            pi."AnsListDesc", -- AnsListDesc

            pi."Date", -- Date

            vParams."User", -- User

            pi."Status", -- Status

            pi."AuditNumber", -- AuditNumber

            pi."AppUser", -- AppUser

            pi."AppDate", -- AppDate

            pi."AnsDate", -- AnsDate

            pi."ASAType", -- ASAType

            pi."ASAScore", -- ASAScore

            PItem_PItem_seq.nextval, -- PItem

            pi."Time", -- Time

            m."TargetId", -- PForm

            nvl(pii."TargetId",0), -- PItemImg

            pi."AnsListRefCode", -- AnsListRefCode

            pi."EntryDateTime", -- EntryDateTime

            pi."AppDateTime", -- AppDateTime

            nvl(pic."TargetId",0) -- PItemCol

          from

            pitem pi

            inner join fitem s on s."FItem" = pi."FItem"

            inner join fitem t on t."FormCode" = vTargetForm and t."FItem" = cQuestions."TargetFItem" and t."Deleted" = 0

            inner join ax_map m on m."SourceId" = pi."PForm" and m."TableName" = 'PFORM' and m."Audit" = pMapAudit

            left outer join ax_map pii on pii."SourceId" = pi."PItemImg" and pii."TableName" = 'PITEMIMG' and pii."Audit" = pMapAudit

            left outer join ax_map pic on pic."SourceId" = pi."PItemCol" and pic."TableName" = 'PITEMCOL' and pic."Audit" = pMapAudit

          where

            s."FormCode" = vSourceForm and

            s."FItem" = cQuestions."SourceFItem" and 

            s."Deleted" = 0 and

            pi."Status" = 0 and

            t."FItem" not in (

              select 

                "FItem"

              from

                pitem tpi

              where

                tpi."FormCode" = vTargetForm and

                tpi."Patient" = pi."Patient" and

                tpi."PForm" = m."TargetId" and

                tpi."FItem" = t."FItem"

            )

        );

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ' || cQuestions."Code" || ' pitem rows inserted.',vParams);

      elsif (

        cQuestions."SourceType" = ax_pkg.ANSWER_LIST and 

        (

          cQuestions."TargetType" = ax_pkg.ANSWER_TEXT or

          cQuestions."TargetType" = ax_pkg.ANSWER_LONG_TEXT or 

          cQuestions."TargetType" = ax_pkg.ANSWER_CALCULATED            

        )

      ) then

        -- Copy from an Answer List into a Text Field

        insert into pitem (

          select

            pi."Patient", -- Patient

            vTargetForm, -- FormCode

            t."FItem", -- FItem

            t."AnsType", -- AnsType

            pi."AnsYes", -- AnsYes

            nvl(trim(pi."AnsListDesc"),pi."AnsList"), -- AnsText

            ' ', -- AnsList

            null, -- AnsListDesc

            pi."Date", -- Date

            vParams."User", -- User

            pi."Status", -- Status

            pi."AuditNumber", -- AuditNumber

            pi."AppUser", -- AppUser

            pi."AppDate", -- AppDate

            pi."AnsDate", -- AnsDate

            pi."ASAType", -- ASAType

            pi."ASAScore", -- ASAScore

            PItem_PItem_seq.nextval, -- PItem

            pi."Time", -- Time

            m."TargetId", -- PForm

            0, -- PItemImg

            pi."AnsListRefCode", -- AnsListRefCode

            pi."EntryDateTime", -- EntryDateTime

            pi."AppDateTime", -- AppDateTime

            nvl(pic."TargetId",0) -- PItemCol

          from

            pitem pi

            inner join fitem s on s."FItem" = pi."FItem"

            inner join fitem t on t."FormCode" = vTargetForm and t."FItem" = cQuestions."TargetFItem" and t."Deleted" = 0

            inner join ax_map m on m."SourceId" = pi."PForm" and m."TableName" = 'PFORM' and m."Audit" = pMapAudit

            left outer join ax_map pic on pic."SourceId" = pi."PItemCol" and pic."TableName" = 'PITEMCOL' and pic."Audit" = pMapAudit

          where

            s."FormCode" = vSourceForm and

            s."FItem" = cQuestions."SourceFItem" and 

            s."Deleted" = 0 and

            pi."Status" = 0 and

            t."FItem" not in (

              select 

                "FItem"

              from

                pitem tpi

              where

                tpi."FormCode" = vTargetForm and

                tpi."Patient" = pi."Patient" and

                tpi."PForm" = m."TargetId" and

                tpi."FItem" = t."FItem"

            )

        );

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ' || cQuestions."Code" || ' pitem rows inserted.',vParams);

      elsif (

        cQuestions."TargetType" = ax_pkg.ANSWER_LIST and 

        (

          cQuestions."SourceType" = ax_pkg.ANSWER_TEXT or

          cQuestions."SourceType" = ax_pkg.ANSWER_LONG_TEXT or 

          cQuestions."SourceType" = ax_pkg.ANSWER_CALCULATED           

        )      

      ) then

        -- Convert AnsText to AnsListDesc

        insert into pitem (

          select

            pi."Patient", -- Patient

            vTargetForm, -- FormCode

            t."FItem", -- FItem

            t."AnsType", -- AnsType

            pi."AnsYes", -- AnsYes

            null, -- AnsText

            t."AnsList", -- AnsList

            li."Description", -- AnsListDesc

            pi."Date", -- Date

            vParams."User", -- User

            pi."Status", -- Status

            pi."AuditNumber", -- AuditNumber

            pi."AppUser", -- AppUser

            pi."AppDate", -- AppDate

            pi."AnsDate", -- AnsDate

            pi."ASAType", -- ASAType

            pi."ASAScore", -- ASAScore

            PItem_PItem_seq.nextval, -- PItem

            pi."Time", -- Time

            m."TargetId", -- PForm

            0, -- PItemImg

            pi."AnsListRefCode", -- AnsListRefCode

            pi."EntryDateTime", -- EntryDateTime

            pi."AppDateTime", -- AppDateTime

            nvl(pic."TargetId",0) -- PItemCol

          from

            pitem pi

            inner join fitem s on s."FItem" = pi."FItem"

            inner join fitem t on t."FormCode" = vTargetForm and t."FItem" = cQuestions."TargetFItem" and t."Deleted" = 0

            inner join ax_map m on m."SourceId" = pi."PForm" and m."TableName" = 'PFORM' and m."Audit" = pMapAudit

            left outer join listitem li on li."ListCode" = t."AnsList" and trim(upper(li."Description")) = trim(upper(pi."AnsText"))

            left outer join ax_map pic on pic."SourceId" = pi."PItemCol" and pic."TableName" = 'PITEMCOL' and pic."Audit" = pMapAudit

          where

            s."FormCode" = vSourceForm and

            s."FItem" = cQuestions."SourceFItem" and 

            s."Deleted" = 0 and

            pi."Status" = 0 and

            t."FItem" not in (

              select 

                "FItem"

              from

                pitem tpi

              where

                tpi."FormCode" = vTargetForm and

                tpi."Patient" = pi."Patient" and

                tpi."PForm" = m."TargetId" and

                tpi."FItem" = t."FItem"

            )

        );

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ' || cQuestions."Code" || ' pitem rows inserted.',vParams);

      elsif (

        cQuestions."SourceType" = ax_pkg.ANSWER_YES_NO and 

        (

          cQuestions."TargetType" = ax_pkg.ANSWER_TEXT or

          cQuestions."TargetType" = ax_pkg.ANSWER_LONG_TEXT or 

          cQuestions."TargetType" = ax_pkg.ANSWER_CALCULATED           

        )    

      ) then

        -- Convert AnsYes to AnsText 

        -- 0 = No, 1 = Yes, -1 = Unanswered, 2 = Do not know

        insert into pitem (

          select

            pi."Patient", -- Patient

            vTargetForm, -- FormCode

            t."FItem", -- FItem

            t."AnsType", -- AnsType

            0, -- AnsYes

            decode(pi."AnsYes",

              0,'No',

              1,'Yes',

              2,'Do not know',

              'Unanswered'

            ), -- AnsText

            pi."AnsList", -- AnsList

            pi."AnsListDesc", -- AnsListDesc

            pi."Date", -- Date

            vParams."User", -- User

            pi."Status", -- Status

            pi."AuditNumber", -- AuditNumber

            pi."AppUser", -- AppUser

            pi."AppDate", -- AppDate

            pi."AnsDate", -- AnsDate

            pi."ASAType", -- ASAType

            pi."ASAScore", -- ASAScore

            PItem_PItem_seq.nextval, -- PItem

            pi."Time", -- Time

            m."TargetId", -- PForm

            0, -- PItemImg

            pi."AnsListRefCode", -- AnsListRefCode

            pi."EntryDateTime", -- EntryDateTime

            pi."AppDateTime", -- AppDateTime

            nvl(pic."TargetId",0) -- PItemCol

          from

            pitem pi

            inner join fitem s on s."FItem" = pi."FItem"

            inner join fitem t on t."FormCode" = vTargetForm and t."FItem" = cQuestions."TargetFItem" and t."Deleted" = 0

            inner join ax_map m on m."SourceId" = pi."PForm" and m."TableName" = 'PFORM' and m."Audit" = pMapAudit

            left outer join ax_map pic on pic."SourceId" = pi."PItemCol" and pic."TableName" = 'PITEMCOL' and pic."Audit" = pMapAudit

          where

            s."FormCode" = vSourceForm and

            s."FItem" = cQuestions."SourceFItem" and 

            s."Deleted" = 0 and

            pi."Status" = 0 and

            t."FItem" not in (

              select 

                "FItem"

              from

                pitem tpi

              where

                tpi."FormCode" = vTargetForm and

                tpi."Patient" = pi."Patient" and

                tpi."PForm" = m."TargetId" and

                tpi."FItem" = t."FItem"

            )

        );

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ' || cQuestions."Code" || ' pitem rows inserted.',vParams);

      elsif (

        cQuestions."TargetType" = ax_pkg.ANSWER_YES_NO and 

        (

          cQuestions."SourceType" = ax_pkg.ANSWER_TEXT or

          cQuestions."SourceType" = ax_pkg.ANSWER_LONG_TEXT or 

          cQuestions."SourceType" = ax_pkg.ANSWER_CALCULATED           

        )    

      ) then

        -- Convert AnsText to AnsYes 

        -- 0 = No, 1 = Yes, -1 = Unanswered, 2 = Do not know    

        insert into pitem (

          select

            pi."Patient", -- Patient

            vTargetForm, -- FormCode

            t."FItem", -- FItem

            t."AnsType", -- AnsType

            decode(trim(upper(pi."AnsText")),

              'N',0,

              'NO',0,

              'NOT',0,

              'NOPE',0,

              'NEGATIVE',0,

              'NEVER',0,

              'NAY',0,

              'NIX',0,

              'NOT AT ALL',0,

              'NOT BY ANY MEANS',0,

              'BY NO MEANS',0,

              'ABSOLUTELY NOT',0,

              'FALSE',0,

              '0',0,

              'Y',1,

              'YES',1,

              'YEP',1,

              'YUP',1,

              'YEA',1,

              'ALWAYS',1,

              'POSITIVE',1,

              'POSITIVELY',1,

              'CERTAINLY',1,

              'AYE',1,

              'ABSOLUTELY',1,

              'DEFINATELY',1,

              'TRUE',1,

              '1',1,

              'D',2,

              'DO NOT KNOW',2,

              'DON''T KNOW',2,

              'I DO NOT KNOW',2,

              'I DON''T KNOW',2,

              'NOT SURE',2,

              'UNSURE',2,

              'UNKNOWN',2,

              '2',2,

              -1

            ), -- AnsYes

            pi."AnsText", -- AnsText

            pi."AnsList", -- AnsList

            pi."AnsListDesc", -- AnsListDesc

            pi."Date", -- Date

            vParams."User", -- User

            pi."Status", -- Status

            pi."AuditNumber", -- AuditNumber -- should we check if there is an existing answer, and update it?

            pi."AppUser", -- AppUser

            pi."AppDate", -- AppDate

            pi."AnsDate", -- AnsDate

            pi."ASAType", -- ASAType

            pi."ASAScore", -- ASAScore

            PItem_PItem_seq.nextval, -- PItem

            pi."Time", -- Time

            m."TargetId", -- PForm

            0, -- PItemImg

            pi."AnsListRefCode", -- AnsListRefCode

            pi."EntryDateTime", -- EntryDateTime

            pi."AppDateTime", -- AppDateTime

            nvl(pic."TargetId",0) -- PItemCol

          from

            pitem pi

            inner join fitem s on s."FItem" = pi."FItem"

            inner join fitem t on t."FormCode" = vTargetForm and t."FItem" = cQuestions."TargetFItem" and t."Deleted" = 0

            inner join ax_map m on m."SourceId" = pi."PForm" and m."TableName" = 'PFORM' and m."Audit" = pMapAudit

            left outer join ax_map pic on pic."SourceId" = pi."PItemCol" and pic."TableName" = 'PITEMCOL' and pic."Audit" = pMapAudit

          where

            s."FormCode" = vSourceForm and

            s."FItem" = cQuestions."SourceFItem" and 

            s."Deleted" = 0 and

            pi."Status" = 0 and

            t."FItem" not in (

              select 

                "FItem"

              from

                pitem tpi

              where

                tpi."FormCode" = vTargetForm and

                tpi."Patient" = pi."Patient" and

                tpi."PForm" = m."TargetId" and

                tpi."FItem" = t."FItem"

            )

        );

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ' || cQuestions."Code" || ' pitem rows inserted.',vParams);

      elsif (

        cQuestions."TargetType" = ax_pkg.ANSWER_NUMBER and 

        (

          cQuestions."SourceType" = ax_pkg.ANSWER_TEXT or

          cQuestions."SourceType" = ax_pkg.ANSWER_LONG_TEXT or 

          cQuestions."SourceType" = ax_pkg.ANSWER_CALCULATED           

        )    

      ) then

        -- Convert AnsText to a number 

        insert into pitem (

          select

            pi."Patient", -- Patient

            vTargetForm, -- FormCode

            t."FItem", -- FItem

            t."AnsType", -- AnsType

            pi."AnsYes", -- AnsYes

            ax_pkg.ConvertToNumber_F(pi."AnsText",null), -- AnsText

            pi."AnsList", -- AnsList

            pi."AnsListDesc", -- AnsListDesc

            pi."Date", -- Date

            vParams."User", -- User

            pi."Status", -- Status

            pi."AuditNumber", -- AuditNumber

            pi."AppUser", -- AppUser

            pi."AppDate", -- AppDate

            pi."AnsDate", -- AnsDate

            pi."ASAType", -- ASAType

            pi."ASAScore", -- ASAScore

            PItem_PItem_seq.nextval, -- PItem

            pi."Time", -- Time

            m."TargetId", -- PForm

            0, -- PItemImg

            pi."AnsListRefCode", -- AnsListRefCode

            pi."EntryDateTime", -- EntryDateTime

            pi."AppDateTime", -- AppDateTime

            nvl(pic."TargetId",0) -- PItemCol

          from

            pitem pi

            inner join fitem s on s."FItem" = pi."FItem"

            inner join fitem t on t."FormCode" = vTargetForm and t."FItem" = cQuestions."TargetFItem" and t."Deleted" = 0

            inner join ax_map m on m."SourceId" = pi."PForm" and m."TableName" = 'PFORM' and m."Audit" = pMapAudit

            left outer join ax_map pic on pic."SourceId" = pi."PItemCol" and pic."TableName" = 'PITEMCOL' and pic."Audit" = pMapAudit

          where

            s."FormCode" = vSourceForm and

            s."FItem" = cQuestions."SourceFItem" and 

            s."Deleted" = 0 and

            pi."Status" = 0 and

            t."FItem" not in (

              select 

                "FItem"

              from

                pitem tpi

              where

                tpi."FormCode" = vTargetForm and

                tpi."Patient" = pi."Patient" and

                tpi."PForm" = m."TargetId" and

                tpi."FItem" = t."FItem"

            )

        );

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ' || cQuestions."Code" || ' pitem rows inserted.',vParams);

      elsif (

        cQuestions."SourceType" = ax_pkg.ANSWER_DATE and 

        (

          cQuestions."TargetType" = ax_pkg.ANSWER_TEXT or

          cQuestions."TargetType" = ax_pkg.ANSWER_LONG_TEXT or 

          cQuestions."TargetType" = ax_pkg.ANSWER_CALCULATED           

        )    

      ) then

        -- Convert AnsDate to AnsText       

       insert into pitem (

          select

            pi."Patient", -- Patient

            vTargetForm, -- FormCode

            t."FItem", -- FItem

            t."AnsType", -- AnsType

            pi."AnsYes", -- AnsYes

            to_char(pi."AnsDate",ax_pkg.DESCRIPTIVE_DATE_FORMAT), -- AnsText

            pi."AnsList", -- AnsList

            pi."AnsListDesc", -- AnsListDesc

            pi."Date", -- Date

            vParams."User", -- User

            pi."Status", -- Status

            pi."AuditNumber", -- AuditNumber

            pi."AppUser", -- AppUser

            pi."AppDate", -- AppDate

            pi."AnsDate", -- AnsDate

            pi."ASAType", -- ASAType

            pi."ASAScore", -- ASAScore

            PItem_PItem_seq.nextval, -- PItem

            pi."Time", -- Time

            m."TargetId", -- PForm

            0, -- PItemImg

            pi."AnsListRefCode", -- AnsListRefCode

            pi."EntryDateTime", -- EntryDateTime

            pi."AppDateTime", -- AppDateTime

            nvl(pic."TargetId",0) -- PItemCol

          from

            pitem pi

            inner join fitem s on s."FItem" = pi."FItem"

            inner join fitem t on t."FormCode" = vTargetForm and t."FItem" = cQuestions."TargetFItem" and t."Deleted" = 0

            inner join ax_map m on m."SourceId" = pi."PForm" and m."TableName" = 'PFORM' and m."Audit" = pMapAudit

            left outer join ax_map pic on pic."SourceId" = pi."PItemCol" and pic."TableName" = 'PITEMCOL' and pic."Audit" = pMapAudit

          where

            s."FormCode" = vSourceForm and

            s."FItem" = cQuestions."SourceFItem" and 

            s."Deleted" = 0 and

            pi."Status" = 0 and

            t."FItem" not in (

              select 

                "FItem"

              from

                pitem tpi

              where

                tpi."FormCode" = vTargetForm and

                tpi."Patient" = pi."Patient" and

                tpi."PForm" = m."TargetId" and

                tpi."FItem" = t."FItem"

            )

        );

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ' || cQuestions."Code" || ' pitem rows inserted.',vParams);

      elsif (

        cQuestions."TargetType" = ax_pkg.ANSWER_DATE and 

        (

          cQuestions."SourceType" = ax_pkg.ANSWER_TEXT or

          cQuestions."SourceType" = ax_pkg.ANSWER_LONG_TEXT or 

          cQuestions."SourceType" = ax_pkg.ANSWER_CALCULATED           

        )    

      ) then

        -- Convert AnsText to AnsDate

       insert into pitem (

          select

            pi."Patient", -- Patient

            vTargetForm, -- FormCode

            t."FItem", -- FItem

            t."AnsType", -- AnsType

            pi."AnsYes", -- AnsYes

            pi."AnsText", -- AnsText

            pi."AnsList", -- AnsList

            pi."AnsListDesc", -- AnsListDesc

            pi."Date", -- Date

            vParams."User", -- User

            pi."Status", -- Status

            pi."AuditNumber", -- AuditNumber

            pi."AppUser", -- AppUser

            pi."AppDate", -- AppDate

            ax_pkg.ConvertToDate_F(pi."AnsText"), -- AnsDate

            pi."ASAType", -- ASAType

            pi."ASAScore", -- ASAScore

            PItem_PItem_seq.nextval, -- PItem

            pi."Time", -- Time

            m."TargetId", -- PForm

            0, -- PItemImg

            pi."AnsListRefCode", -- AnsListRefCode

            pi."EntryDateTime", -- EntryDateTime

            pi."AppDateTime", -- AppDateTime

            nvl(pic."TargetId",0) -- PItemCol

          from

            pitem pi

            inner join fitem s on s."FItem" = pi."FItem"

            inner join fitem t on t."FormCode" = vTargetForm and t."FItem" = cQuestions."TargetFItem" and t."Deleted" = 0

            inner join ax_map m on m."SourceId" = pi."PForm" and m."TableName" = 'PFORM' and m."Audit" = pMapAudit

            left outer join ax_map pic on pic."SourceId" = pi."PItemCol" and pic."TableName" = 'PITEMCOL' and pic."Audit" = pMapAudit

          where

            s."FormCode" = vSourceForm and

            s."FItem" = cQuestions."SourceFItem" and 

            s."Deleted" = 0 and

            pi."Status" = 0 and

            t."FItem" not in (

              select 

                "FItem"

              from

                pitem tpi

              where

                tpi."FormCode" = vTargetForm and

                tpi."Patient" = pi."Patient" and

                tpi."PForm" = m."TargetId" and

                tpi."FItem" = t."FItem"

            )

        );        

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ' || cQuestions."Code" || ' pitem rows inserted.',vParams);

      elsif (

        cQuestions."SourceType" = ax_pkg.ANSWER_YES_NO and 

        cQuestions."TargetType" = ax_pkg.ANSWER_NUMBER           

      ) then

        -- Convert AnsYes to AnsText as a number       

       insert into pitem (

          select

            pi."Patient", -- Patient

            vTargetForm, -- FormCode

            t."FItem", -- FItem

            t."AnsType", -- AnsType

            0, -- AnsYes

            to_char(pi."AnsYes"), -- AnsText

            pi."AnsList", -- AnsList

            pi."AnsListDesc", -- AnsListDesc

            pi."Date", -- Date

            vParams."User", -- User

            pi."Status", -- Status

            pi."AuditNumber", -- AuditNumber

            pi."AppUser", -- AppUser

            pi."AppDate", -- AppDate

            pi."AnsDate", -- AnsDate

            pi."ASAType", -- ASAType

            pi."ASAScore", -- ASAScore

            PItem_PItem_seq.nextval, -- PItem

            pi."Time", -- Time

            m."TargetId", -- PForm

            0, -- PItemImg

            pi."AnsListRefCode", -- AnsListRefCode

            pi."EntryDateTime", -- EntryDateTime

            pi."AppDateTime", -- AppDateTime

            nvl(pic."TargetId",0) -- PItemCol

          from

            pitem pi

            inner join fitem s on s."FItem" = pi."FItem"

            inner join fitem t on t."FormCode" = vTargetForm and t."FItem" = cQuestions."TargetFItem" and t."Deleted" = 0

            inner join ax_map m on m."SourceId" = pi."PForm" and m."TableName" = 'PFORM' and m."Audit" = pMapAudit

            left outer join ax_map pic on pic."SourceId" = pi."PItemCol" and pic."TableName" = 'PITEMCOL' and pic."Audit" = pMapAudit

          where

            s."FormCode" = vSourceForm and

            s."FItem" = cQuestions."SourceFItem" and 

            s."Deleted" = 0 and

            pi."Status" = 0 and

            t."FItem" not in (

              select 

                "FItem"

              from

                pitem tpi

              where

                tpi."FormCode" = vTargetForm and

                tpi."Patient" = pi."Patient" and

                tpi."PForm" = m."TargetId" and

                tpi."FItem" = t."FItem"

            )

        );        

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ' || cQuestions."Code" || ' pitem rows inserted.',vParams);

      elsif (

        cQuestions."SourceType" = ax_pkg.ANSWER_NUMBER and 

        cQuestions."TargetType" = ax_pkg.ANSWER_YES_NO           

      ) then

        -- Convert AnsText as number to AnsYes  

          -- Only conver number values lower than 3

       insert into pitem (

          select

            pi."Patient", -- Patient

            vTargetForm, -- FormCode

            t."FItem", -- FItem

            t."AnsType", -- AnsType

            case  

              when ax_pkg.ConvertToNumber_F(pi."AnsText") < 3 then ax_pkg.ConvertToNumber_F(pi."AnsText") 

              else -1 

            end, -- AnsYes

            pi."AnsText", -- AnsText

            pi."AnsList", -- AnsList

            pi."AnsListDesc", -- AnsListDesc

            pi."Date", -- Date

            vParams."User", -- User

            pi."Status", -- Status

            pi."AuditNumber", -- AuditNumber

            pi."AppUser", -- AppUser

            pi."AppDate", -- AppDate

            pi."AnsDate", -- AnsDate

            pi."ASAType", -- ASAType

            pi."ASAScore", -- ASAScore

            PItem_PItem_seq.nextval, -- PItem

            pi."Time", -- Time

            m."TargetId", -- PForm

            0, -- PItemImg

            pi."AnsListRefCode", -- AnsListRefCode

            pi."EntryDateTime", -- EntryDateTime

            pi."AppDateTime", -- AppDateTime

            nvl(pic."TargetId",0) -- PItemCol

          from

            pitem pi

            inner join fitem s on s."FItem" = pi."FItem"

            inner join fitem t on t."FormCode" = vTargetForm and t."FItem" = cQuestions."TargetFItem" and t."Deleted" = 0

            inner join ax_map m on m."SourceId" = pi."PForm" and m."TableName" = 'PFORM' and m."Audit" = pMapAudit

            left outer join ax_map pic on pic."SourceId" = pi."PItemCol" and pic."TableName" = 'PITEMCOL' and pic."Audit" = pMapAudit

          where

            s."FormCode" = vSourceForm and

            s."FItem" = cQuestions."SourceFItem" and 

            s."Deleted" = 0 and

            pi."Status" = 0 and

            t."FItem" not in (

              select 

                "FItem"

              from

                pitem tpi

              where

                tpi."FormCode" = vTargetForm and

                tpi."Patient" = pi."Patient" and

                tpi."PForm" = m."TargetId" and

                tpi."FItem" = t."FItem"

            )

        );   

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ' || cQuestions."Code" || ' pitem rows inserted.',vParams);

      elsif (

        cQuestions."TargetType" = ax_pkg.ANSWER_LIST and 

        cQuestions."SourceType" = ax_pkg.ANSWER_YES_NO

      ) then

        -- Convert Yes/No to List

        --   Map Yes,No,Do not know,Unanswered to List Description

        insert into pitem (

          select

            pi."Patient", -- Patient

            vTargetForm, -- FormCode

            t."FItem", -- FItem

            t."AnsType", -- AnsType

            pi."AnsYes", -- AnsYes

            pi."AnsText", -- AnsText

            t."AnsList", -- AnsList

            li."Description", -- AnsListDesc

            pi."Date", -- Date

            vParams."User", -- User

            pi."Status", -- Status

            pi."AuditNumber", -- AuditNumber

            pi."AppUser", -- AppUser

            pi."AppDate", -- AppDate

            pi."AnsDate", -- AnsDate

            pi."ASAType", -- ASAType

            pi."ASAScore", -- ASAScore

            PItem_PItem_seq.nextval, -- PItem

            pi."Time", -- Time

            m."TargetId", -- PForm

            0, -- PItemImg

            pi."AnsListRefCode", -- AnsListRefCode

            pi."EntryDateTime", -- EntryDateTime

            pi."AppDateTime", -- AppDateTime

            nvl(pic."TargetId",0) -- PItemCol

          from

            pitem pi

            inner join fitem s on s."FItem" = pi."FItem"

            inner join fitem t on t."FormCode" = vTargetForm and t."FItem" = cQuestions."TargetFItem" and t."Deleted" = 0

            inner join ax_map m on m."SourceId" = pi."PForm" and m."TableName" = 'PFORM' and m."Audit" = pMapAudit

            left outer join ax_map pic on pic."SourceId" = pi."PItemCol" and pic."TableName" = 'PITEMCOL' and pic."Audit" = pMapAudit

            left outer join listitem li on 

              li."ListCode" = t."AnsList" and

              (

                (

                  trim(upper(li."Description")) = 'YES' and

                  pi."AnsYes" = 1

                ) or (

                  trim(upper(li."Description")) = 'NO' and

                  pi."AnsYes" = 0

                ) or (

                  trim(upper(li."Description")) = 'DO NOT KNOW' and

                  pi."AnsYes" = 2

                ) or (

                  trim(upper(li."Description")) = 'UNKNOWN' and

                  pi."AnsYes" = -1

                )

              )

          where

            s."FormCode" = vSourceForm and

            s."FItem" = cQuestions."SourceFItem" and 

            s."Deleted" = 0 and

            pi."Status" = 0 and

            t."FItem" not in (

              select 

                "FItem"

              from

                pitem tpi

              where

                tpi."FormCode" = vTargetForm and

                tpi."Patient" = pi."Patient" and

                tpi."PForm" = m."TargetId" and

                tpi."FItem" = t."FItem"

            )

        );

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ' || cQuestions."Code" || ' pitem rows inserted.',vParams);

        commit;

      else

        -- conversion not supported

          -- Only display if not called from a loop

        ax_pkg.AppendString_P(pvMessage,'Answer Types not currently supported. Cannot copy ' ||

          ax_pkg.GetAnswerType_F(cQuestions."SourceType") || ' type answers into ' ||

          ax_pkg.GetAnswerType_F(cQuestions."TargetType") || ' type answers.'

        ,' ',ax_pkg.MSG_ERROR,pParams);

        pvSuccess := false;

      end if;

      

      if (not vItemSuccess and (vLastRefCode <> cQuestions."Code")) then

        -- Only display errors once for each Reference Code

        ax_pkg.AppendString_P(pvMessage,vItemMessage,' ',ax_pkg.MSG_ERROR,pParams);

      end if;

      vItemMessage := null;

      vLastRefCode := cQuestions."Code";

    end loop;



/*

    for cQuestions in curQuestions loop

      CopySingleAnswer_P(

        vItemSuccess,

        vItemMessage,  

        pSourceForm,

        cQuestions."Code",

        pTargetForm,

        cQuestions."Code",

        vParams,

        cQuestions."SourceType",

        cQuestions."TargetType",

        vMapAudit

      );

      if (not vItemSuccess and (vLastRefCode <> cQuestions."Code")) then

        -- Only display errors once for each Reference Code

        ax_pkg.AppendString_P(pvMessage,vItemMessage,' ',ax_pkg.MSG_ERROR,pParams);

      end if;

      vItemMessage := null;

      vLastRefCode := cQuestions."Code";

    end loop;

    */

    

   ----------------

    -- Adjust PItemImg Type

    ----------------

    update pitemimg set 

      "Type" = 1,

      "FileExt" = 'jpeg'

    where "PItemImg" in (

      select 

        pii."PItemImg"

      from

        pitemimg pii

        inner join pitem p on p."PItemImg" = pii."PItemImg" and p."AnsType" = 8

      where

        pii."Type" = 0

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount)  || ' pitemimg rows updated.',vParams);

        

    ----------------

    -- Copy PtSig

    ---------------- 

    -- Do not copy signatures, as the patient signed a different version of the form

    

    ----------------

    -- Copy NoteOvr

    ----------------   

    -- Create noteovr Records

    for cNoteOverMap in curNoteOvrMap1(pMapAudit) loop

      select * into vNoteOvrRow from noteovr where "Id" = cNoteOverMap."Id"; 

      select noteovr_id_seq.nextval into vNoteOvrRow."Id" from dual;

      vNoteOvrRow."ParentId" := cNoteOverMap."TargetId";

      insert into noteovr values vNoteOvrRow;

      vCount := vCount + 1;

    end loop;        

    

    ----------------

    -- Cleanup orphans not needed

    ----------------   

    -- delete pitemimg, pitemcol where mapped, but not used

    

    ----------------

    -- Cleanup mapping records based on a parameter

    ----------------   

    -- Cleanup the ax_map table, leave on the Form record to show that a Copy was performed

    if pClearMapping then

      delete from ax_map where "Audit" = pMapAudit and "TableName" <> 'FORM';

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' rows deleted from ax_map.',vParams);

    end if;



    vLogRow."Log" := 'Answers from Form ' || vSourceForm || ' copied to Form ' || vTargetForm;

    ax_pkg.log_p(vLogRow,ax_pkg.MSG_INFO,vParams);  

    

    pvSuccess := true;

  exception

    when exBadData then

      ax_pkg.AppendString_P(pvMessage,'Form is marked to not allow multiples, but multiples exist. Cannot continue.',' ',ax_pkg.MSG_ERROR,pParams);

    when exMappingNotFound then

      ax_pkg.AppendString_P(pvMessage,'No mapping records found with an Audit of ' || pMapAudit || '. 

 Before calling this procedure you must create the proper mapping records in ax_map. 

 If copying answers from one form to another, where the reference codes match, call ax_copy_pkg.CopyAnswers_P instead, which handles the mapping step for you.',' ',ax_pkg.MSG_ERROR,pParams);

    when exNotCompatible then

      ax_pkg.AppendString_P(pvMessage,'Forms not compatible. Cannot copy a form that can have multiple to a form that cannot.',' ',ax_pkg.MSG_ERROR,pParams);

    when exSourceNotFound then

      ax_pkg.AppendString_P(pvMessage,'Source form ' || vSourceForm || ' not found!',' ',ax_pkg.MSG_ERROR,pParams);

    when exTargetNotFound then

      ax_pkg.AppendString_P(pvMessage,'Target form ' || vTargetForm || ' not found!',' ',ax_pkg.MSG_ERROR,pParams);

    when exNothingToCopy then

      ax_pkg.AppendString_P(pvMessage,'Nothing found to copy! Make sure that:',' ',ax_pkg.MSG_ERROR,pParams);

      ax_pkg.AppendString_P(pvMessage,'  * At least one Question in each form has a matching Reference Code',' ',ax_pkg.MSG_ERROR,pParams);

      ax_pkg.AppendString_P(pvMessage,'  * There are patients with the source form filled out',' ',ax_pkg.MSG_ERROR,pParams);

      ax_pkg.AppendString_P(pvMessage,'  * The target form does not exist for some patients or is set to allow multiple',' ',ax_pkg.MSG_ERROR,pParams);

  end CopyMappedAnswers_P;  

  

  

  -- overload

  PROCEDURE copymappedanswers_p(IN pmapaudit numeric, IN poverwriteexisting boolean DEFAULT false, IN pclearmapping boolean DEFAULT false, IN pfstatus character DEFAULT NULL::bpchar, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vMessage  VARCHAR2(4000);

    vSuccess boolean;

  begin

    CopyMappedAnswers_P(vSuccess,vMessage,pMapAudit,pOverwriteExisting,pClearMapping,pFStatus,pParams);

    if not vSuccess then

      raise_application_error(-20000, vMessage);

    end if;

  end CopyMappedAnswers_P;

  



  -- This procedure copies answers from one form to another

  -- This procedure differs from CopyEPRFormRecords_P in that it is copying from one Type of Form to Another

  -- Matching the FItem."Code" values

  PROCEDURE copyanswers_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN psourceform character, IN ptargetform character, IN poverwriteexisting boolean DEFAULT false, IN pfstatus character DEFAULT NULL::bpchar, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

  /*

  

    cursor curPForms(pAudit audithis."Audit"%type) is

      select 

        pf."Patient",

        pf."FormCode",

        pf."PForm"

      from

        pform pf

        inner join ax_map m on m."TargetId" = pf."PForm" and m."TableName" = 'PFORM' and m."Audit" = pAudit

    ;  

    cursor curPItemImgMap(pAudit audithis."Audit"%type) is

      select

        NewPI."TargetId",

        NewPI."SourceId"

      from

        ax_map NewPI

      where

        NewPI."TableName" = 'PITEMIMG' and

        NewPI."Audit" = pAudit

    ;    

    cursor curPItemColMap(pAudit audithis."Audit"%type) is

      select

        NewPIC."TargetId",

        NewPIC."SourceId",

        NewPF."TargetId" "PForm",

        NewOPIC."TargetId" "OrgPItemCol"

      from

        ax_map NewPIC

        inner join pitemcol pic on pic."PItemCol" = NewPIC."SourceId"

        inner join ax_map NewPF on NewPF."SourceId" = pic."PForm" and NewPF."TableName" = 'PFORM' and NewPF."Audit" = pAudit

        left outer join ax_map NewOPIC on NewOPIC."SourceId" = pic."OrgPItemCol" and NewOPIC."TableName" = 'PITEMCOL' and NewOPIC."Audit" = pAudit

      where

        NewPIC."TableName" = 'PITEMCOL' and

        NewPIC."Audit" = pAudit

    ;  

    cursor curNoteOvrMap1(pAudit audithis."Audit"%type) is

      select

        NewPI."SourceId",

        NewPI."TargetId",

        nto."Id"

      from

        noteovr nto 

        inner join ax_map NewPI on NewPI."SourceId" = nto."ParentId" and NewPI."TableName" = 'PITEM' and NewPI."Audit" = pAudit

      where

        nto."Deleted" = 0 and

        nto."Type" = 1

    ;

    -- Do not filter source by deleted, to make sure all active answer are included

    cursor curQuestions is

      select 

        s."Code"    "Code", 

        s."FItem"   "SourceFItem",

        t."FItem"   "TargetFItem",

        s."AnsType" "SourceType",

        t."AnsType" "TargetType",

        s."AnsList" "SourceList",

        t."AnsList" "TargetList"

      from 

        fitem s

        inner join fitem t on 

          t."FormCode" = pTargetForm and 

          t."Code" = s."Code" and

          t."Deleted" = 0

      where 

        s."FormCode" = pSourceForm

      order by

        s."Code"

    ;    

    */

    vParams ax_pkg.tParams := pParams;

    vSourceCanHaveMultiple form."Multiple"%type;

    vTargetCanHaveMultiple form."Multiple"%type;

    vLastRefCode fitem."Code"%type := ' ';

    

    vAuditHisRow audithis%rowtype;

    vLogRow ax_log%rowtype;

    vPPageRow ppage%rowtype;

    vPItemImgRow pitemimg%rowtype;

    vSourceList fitem."AnsList"%type;

    vTargetList fitem."AnsList"%type;

    vPItemColRow pitemcol%rowtype;

    vNoteOvrRow noteovr%rowtype;

    

    vMapAudit audithis."Audit"%type;

    vExists number;

    vCount number;

    

    vItemSuccess boolean;

    vItemMessage  VARCHAR2(4000);

    

    exSourceNotFound exception;

    exTargetNotFound exception;

    exNothingToCopy  exception;

    exNotCompatible  exception;

  begin

    pvSuccess := false;

    ax_pkg.InitializeParams_P(vParams);

    if not pParams."IsInit" then

      vParams."VerboseType" := ax_pkg.SHOW_INFO;

    end if;

	-- AX-39259

    vLogRow."Source" := 'AX_COPY_PKG' || '.CopyAnswers_P';

       

    -- Make sure there is at least one matching fitem reference code

    if vParams."VerifyLevel" >= ax_pkg.VERIFY_ALL then

      begin

        select

          1 into vExists

        from 

          fitem f1

          inner join fitem f2 on f1."Code" = f2."Code" and f2."Code" is not null

        where

          f1."FormCode" = pSourceForm and

          f2."FormCode" = pTargetForm and

          rownum = 1

        ;

      exception

        when no_data_found then

          raise exNothingToCopy;

      end;

    end if;

      

    -- passed error checks  

    

    -- Create AuditHis record

    vMapAudit := ax_pkg.GetMapAudit_F(vMapAudit,vParams);



    insert into ax_map values (

      vMapAudit,

      'FORM',

      null,

      null,

      pSourceForm,

      pTargetForm

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

     

    ----------------

    -- Copy Questions

    ---------------- 

    -- Map new FItem Records    

    insert into ax_map (

      select 

        vMapAudit,

        'FITEM',

        s."FItem",

        t."FItem",

        s."Code",

        t."Code"

      from 

        fitem s

        inner join fitem t on 

          t."FormCode" = pTargetForm and 

          t."Code" = s."Code" and

          t."Deleted" = 0

      where 

        s."FormCode" = pSourceForm and

        s."Deleted" = 0

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

    

    --if vCount = 0 then

--      raise exNothingToCopy;

    --end if;

    

    /*

    

    insert into pform (

      select

        s."Patient", -- Patient

        pTargetForm, -- FormCode

        trunc(sysdate), -- Date

        vParams."User", -- User

        t."TargetId", -- PForm

        s."Description", -- Description

        s."OwnerType", -- OwnerType

        s."OwnerId", -- OwnerId

        s."CreatedDate", -- CreatedDate

        s."Approved", -- Approved

        s."LastAppUser", -- LastAppUser

        s."LastAppDate", -- LastAppDate

        s."Inactive", -- Inactive

        s."InactiveAppUser", -- InactiveAppUser

        s."InactiveAppDate", -- InactiveAppDate

        s."InactiveReason", -- InactiveReason

        nvl(nvl(pFStatus,fs."FStatus"),ds."FStatus"), -- FStatus -- Use pFStatus, then s."FStatus" if it has a matching value for the new form, then the default status for the new form

        s."AssignedUser", -- AssignedUser

        s."AssignedUGroup" -- AssignedUGroup

      from

        pform s

        inner join ax_map t on t."SourceId" = s."PForm" and t."TableName" = 'PFORM' and t."Audit" = vMapAudit

        left outer join fstatus fs on fs."FormCode" = pTargetForm and fs."FStatus" = s."FStatus" and fs."Inactive" = 0

        left outer join fstatus ds on ds."FormCode" = pTargetForm and ds."Inactive" = 0 and ds."IsDefault" = 1

      where

        s."FormCode" = pSourceForm and

        s."Inactive" = 0

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' pform rows inserted.',vParams);

    

    

    

    --------------

    -- Create PPage

    --------------

    -- Create ppage Records

    vCount := 0;

    for cPForm in curPForms(vMapAudit) loop

      insert into ppage (

        select

          cPForm."Patient",

          cPForm."FormCode",

          fi."FItem",

          'Copied from ' || pSourceForm,

          trunc(sysdate),

          vParams."User",

          0,

          1,

          fi."FItem",

          0,

          null,

          cPForm."PForm",

          ppage_Ppage_seq.nextval,

          sysdate,

          null

        from

          fitem fi

        where

          fi."FormCode" = pTargetForm and

          fi."Type" = 0 and

          fi."Deleted" = 0 

      );

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ppage rows inserted.',vParams);

    end loop;

    

    */

 



    -- vParams."VerboseType" <> ax_pkg.SHOW_DEBUG

    CopyMappedAnswers_P(

      pvSuccess,

      pvMessage,

      vMapAudit,

      pOverwriteExisting,

      false, -- Clear Mapping

      pFStatus,

      vParams

    );



/*



    for cQuestions in curQuestions loop

      if (cQuestions."SourceType" = ax_pkg.ANSWER_LIST and cQuestions."TargetType" = ax_pkg.ANSWER_LIST) then

        begin

          select "AnsList" into vSourceList from fitem

          where 

            "FormCode" = pSourceForm and

            "Code" = cQuestions."Code" and 

            "Deleted" = 0;        

        exception

          when no_data_found then

            raise exSourceNotFound;

        end;   

        begin

          select "AnsList" into vTargetList from fitem

          where 

            "FormCode" = pTargetForm and

            "Code" = cQuestions."Code" and 

            "Deleted" = 0;        

        exception

          when no_data_found then

            raise exTargetNotFound;

        end;     

      end if;

      

      if vExists = 0 then */

        --------------

        -- Copy PForm

        --------------

        

        -- Only do this if the form can have multiples 

        -- -or- 

        -- the target patient does not have a copy of this form yet

       /*

        -- Map new pform Records

        insert into ax_map (

          select 

            vMapAudit,

            'PFORM', 

            "PForm", 

            pform_Pform_seq.nextval

          from 

            pform pf1

          where

            "FormCode" = pSourceForm and

            "Inactive" = 0 and

            (

              vTargetCanHaveMultiple = 1 or

              not exists ( 

                select 

                  1

                from

                  pform pf2

                where

                  pf2."FormCode" = pTargetForm and

                  pf1."OwnerId" = pf2."OwnerId" and

                  pf1."Inactive" = pf2."Inactive" and

                  rownum = 1

              )

            )

        );

        vCount := SQL%rowcount;

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(vCount) || ' ax_map rows inserted.',vParams);  

        

        if vCount = 0 then

          raise exNothingToCopy;

        end if;

        

        insert into pform (

          select

            s."Patient", -- Patient

            pTargetForm, -- FormCode

            trunc(sysdate), -- Date

            vParams."User", -- User

            t."TargetId", -- PForm

            s."Description", -- Description

            s."OwnerType", -- OwnerType

            s."OwnerId", -- OwnerId

            s."CreatedDate", -- CreatedDate

            s."Approved", -- Approved

            s."LastAppUser", -- LastAppUser

            s."LastAppDate", -- LastAppDate

            s."Inactive", -- Inactive

            s."InactiveAppUser", -- InactiveAppUser

            s."InactiveAppDate", -- InactiveAppDate

            s."InactiveReason", -- InactiveReason

            nvl(nvl(pFStatus,fs."FStatus"),ds."FStatus"), -- FStatus -- Use pFStatus, then s."FStatus" if it has a matching value for the new form, then the default status for the new form

            s."AssignedUser", -- AssignedUser

            s."AssignedUGroup" -- AssignedUGroup

          from

            pform s

            inner join ax_map t on t."SourceId" = s."PForm" and t."TableName" = 'PFORM' and t."Audit" = vMapAudit

            left outer join fstatus fs on fs."FormCode" = pTargetForm and fs."FStatus" = s."FStatus" and fs."Inactive" = 0

            left outer join fstatus ds on ds."FormCode" = pTargetForm and ds."Inactive" = 0 and ds."IsDefault" = 1

          where

            s."FormCode" = pSourceForm and

            s."Inactive" = 0

        );

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' pform rows inserted.',vParams);

        

        

        */

        /*

        --------------

        -- Create PPage

        --------------

        -- Create ppage Records

        vCount := 0;

        for cPForm in curPForms(vMapAudit) loop

          insert into ppage (

            select

              cPForm."Patient",

              cPForm."FormCode",

              fi."FItem",

              'Copied from ' || pSourceForm,

              trunc(sysdate),

              vParams."User",

              0,

              1,

              fi."FItem",

              0,

              null,

              cPForm."PForm",

              ppage_Ppage_seq.nextval,

              sysdate,

              null

            from

              fitem fi

            where

              fi."FormCode" = pTargetForm and

              fi."Type" = 0 and

              fi."Deleted" = 0 

          );

          ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ppage rows inserted.',vParams);

        end loop;

        

        --------------

        -- Copy PPageSig

        --------------        

        -- Do not copy signatures, as the patient signed a different version of the form

        

        ----------------

        -- Copy PItemImg

        ---------------- 

        

        -- Map pitemimg Records

        insert into ax_map (

          select 

            vMapAudit,

            'PITEMIMG', 

            pii."PItemImg", 

            pitemimg_Pitemimg_seq.nextval 

            ,null,null

          from 

            pitemimg pii

            inner join pitem pi on pi."PItemImg" = pii."PItemImg"

            inner join ax_map m on m."SourceId" = pi."PForm" and m."TableName" = 'PFORM' and m."Audit" = vMapAudit

          where

            pi."Status" = 0

        );

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

        

        -- Create pitemimg Records

        vCount := 0;

        for cPItemImgMap in curPItemImgMap(vMapAudit) loop

          select * into vPItemImgRow from pitemimg where "PItemImg" = cPItemImgMap."SourceId";

          vPItemImgRow."PItemImg" := cPItemImgMap."TargetId";

          insert into pitemimg values vPItemImgRow;

          vCount := vCount + 1;

        end loop;

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' pitemimg rows inserted.',vParams);

        

        ----------------

        -- Copy PItemCol

        ----------------    

        -- Map pitemcol Records

        insert into ax_map (

          select 

            vMapAudit,

            'PITEMCOL', 

            pic."PItemCol", 

            pitemcol_Pitemcol_seq.nextval 

            ,null,null

          from 

            pitemcol pic

            inner join ax_map NewPF on NewPF."SourceId" = pic."PForm" and NewPF."Audit" = vMapAudit and NewPF."TableName" = 'PFORM'

        );

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

        

        -- Create pitemcol Records

        vCount := 0;

        for cPItemColMap in curPItemColMap(vMapAudit) loop

          select * into vPItemColRow from pitemcol where "PItemCol" = cPItemColMap."SourceId";

          vPItemColRow."PItemCol" := cPItemColMap."TargetId";

          vPItemColRow."PForm" := cPItemColMap."PForm";

          vPItemColRow."FormCode" := pTargetForm;

          vPItemColRow."OrgPItemCol" := cPItemColMap."OrgPItemCol";

          insert into pitemcol values vPItemColRow;

          vCount := vCount + 1;

        end loop;

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,vCount || ' pitemcol rows inserted.',vParams);

      end if;

      --------------

      -- Copy PItem

      --------------   

  

      if (  

         -- List Type Questions must also have the same List Type

           --  If the List Type does not match, we can attempt to convert based on Reference Codes (see below)

           cQuestions."SourceType" = ax_pkg.ANSWER_LIST and

           cQuestions."TargetType" = ax_pkg.ANSWER_LIST and

           vSourceList = vTargetList 

         ) or (

           -- Questions are the exact same type

           cQuestions."SourceType" = cQuestions."TargetType" and

           cQuestions."SourceType" <> ax_pkg.ANSWER_LIST

         ) or (

           -- Image to Attachment

           cQuestions."SourceType" = ax_pkg.ANSWER_IMAGE and

           cQuestions."TargetType" = ax_pkg.ANSWER_ATTACHMENT

         ) or (         

           -- Answers are all stored in the AnsText field

           (

             cQuestions."SourceType" = ax_pkg.ANSWER_TEXT or

             cQuestions."SourceType" = ax_pkg.ANSWER_LONG_TEXT or 

             cQuestions."SourceType" = ax_pkg.ANSWER_CALCULATED or 

             cQuestions."SourceType" = ax_pkg.ANSWER_NUMBER

           ) and (

             cQuestions."TargetType" = ax_pkg.ANSWER_TEXT or

             cQuestions."TargetType" = ax_pkg.ANSWER_LONG_TEXT or 

             cQuestions."TargetType" = ax_pkg.ANSWER_CALCULATED        

           )

         )

      then

        -- The Questions are the same type, or close enough

        insert into pitem (

          select

            pi."Patient", -- Patient

            pTargetForm, -- FormCode

            t."FItem", -- FItem

            t."AnsType", -- AnsType

            pi."AnsYes", -- AnsYes

            pi."AnsText", -- AnsText

            pi."AnsList", -- AnsList

            pi."AnsListDesc", -- AnsListDesc

            pi."Date", -- Date

            vParams."User", -- User

            pi."Status", -- Status

            pi."AuditNumber", -- AuditNumber

            pi."AppUser", -- AppUser

            pi."AppDate", -- AppDate

            pi."AnsDate", -- AnsDate

            pi."ASAType", -- ASAType

            pi."ASAScore", -- ASAScore

            PItem_PItem_seq.nextval, -- PItem

            pi."Time", -- Time

            m."TargetId", -- PForm

            nvl(pii."TargetId",0), -- PItemImg

            pi."AnsListRefCode", -- AnsListRefCode

            pi."EntryDateTime", -- EntryDateTime

            pi."AppDateTime", -- AppDateTime

            nvl(pic."TargetId",0) -- PItemCol

          from

            pitem pi

            inner join fitem s on s."FItem" = pi."FItem"

            inner join fitem t on t."FormCode" = pTargetForm and t."Code" = cQuestions."Code" and t."Deleted" = 0

            inner join ax_map m on m."SourceId" = pi."PForm" and m."TableName" = 'PFORM' and m."Audit" = vMapAudit

            left outer join ax_map pii on pii."SourceId" = pi."PItemImg" and pii."TableName" = 'PITEMIMG' and pii."Audit" = vMapAudit

            left outer join ax_map pic on pic."SourceId" = pi."PItemCol" and pic."TableName" = 'PITEMCOL' and pic."Audit" = vMapAudit

          where

            s."FormCode" = pSourceForm and

            s."FItem" = cQuestions."SourceFItem" and 

            s."Deleted" = 0 and

            pi."Status" = 0

        );

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ' || cQuestions."Code" || ' pitem rows inserted.',vParams);

      elsif (

        cQuestions."SourceType" = ax_pkg.ANSWER_LIST and 

        (

          cQuestions."TargetType" = ax_pkg.ANSWER_TEXT or

          cQuestions."TargetType" = ax_pkg.ANSWER_LONG_TEXT or 

          cQuestions."TargetType" = ax_pkg.ANSWER_CALCULATED            

        )

      ) then

        -- Copy from an Answer List into a Text Field

        insert into pitem (

          select

            pi."Patient", -- Patient

            pTargetForm, -- FormCode

            t."FItem", -- FItem

            t."AnsType", -- AnsType

            pi."AnsYes", -- AnsYes

            nvl(trim(pi."AnsListDesc"),pi."AnsList"), -- AnsText

            ' ', -- AnsList

            null, -- AnsListDesc

            pi."Date", -- Date

            vParams."User", -- User

            pi."Status", -- Status

            pi."AuditNumber", -- AuditNumber

            pi."AppUser", -- AppUser

            pi."AppDate", -- AppDate

            pi."AnsDate", -- AnsDate

            pi."ASAType", -- ASAType

            pi."ASAScore", -- ASAScore

            PItem_PItem_seq.nextval, -- PItem

            pi."Time", -- Time

            m."TargetId", -- PForm

            0, -- PItemImg

            pi."AnsListRefCode", -- AnsListRefCode

            pi."EntryDateTime", -- EntryDateTime

            pi."AppDateTime", -- AppDateTime

            nvl(pic."TargetId",0) -- PItemCol

          from

            pitem pi

            inner join fitem s on s."FItem" = pi."FItem"

            inner join fitem t on t."FormCode" = pTargetForm and t."Code" = cQuestions."Code" and t."Deleted" = 0

            inner join ax_map m on m."SourceId" = pi."PForm" and m."TableName" = 'PFORM' and m."Audit" = vMapAudit

            left outer join ax_map pic on pic."SourceId" = pi."PItemCol" and pic."TableName" = 'PITEMCOL' and pic."Audit" = vMapAudit

          where

            s."FormCode" = pSourceForm and

            s."Code" = cQuestions."Code" and 

            s."Deleted" = 0 and

            pi."Status" = 0

        );

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ' || cQuestions."Code" || ' pitem rows inserted.',vParams);

      elsif (

        cQuestions."TargetType" = ax_pkg.ANSWER_LIST and 

        (

          cQuestions."SourceType" = ax_pkg.ANSWER_TEXT or

          cQuestions."SourceType" = ax_pkg.ANSWER_LONG_TEXT or 

          cQuestions."SourceType" = ax_pkg.ANSWER_CALCULATED           

        )      

      ) then

        -- Convert AnsText to AnsListDesc

        insert into pitem (

          select

            pi."Patient", -- Patient

            pTargetForm, -- FormCode

            t."FItem", -- FItem

            t."AnsType", -- AnsType

            pi."AnsYes", -- AnsYes

            null, -- AnsText

            t."AnsList", -- AnsList

            li."Description", -- AnsListDesc

            pi."Date", -- Date

            vParams."User", -- User

            pi."Status", -- Status

            pi."AuditNumber", -- AuditNumber

            pi."AppUser", -- AppUser

            pi."AppDate", -- AppDate

            pi."AnsDate", -- AnsDate

            pi."ASAType", -- ASAType

            pi."ASAScore", -- ASAScore

            PItem_PItem_seq.nextval, -- PItem

            pi."Time", -- Time

            m."TargetId", -- PForm

            0, -- PItemImg

            pi."AnsListRefCode", -- AnsListRefCode

            pi."EntryDateTime", -- EntryDateTime

            pi."AppDateTime", -- AppDateTime

            nvl(pic."TargetId",0) -- PItemCol

          from

            pitem pi

            inner join fitem s on s."FItem" = pi."FItem"

            inner join fitem t on t."FormCode" = pTargetForm and t."Code" = cQuestions."Code" and t."Deleted" = 0

            inner join ax_map m on m."SourceId" = pi."PForm" and m."TableName" = 'PFORM' and m."Audit" = vMapAudit

            left outer join listitem li on li."ListCode" = t."AnsList" and trim(upper(li."Description")) = trim(upper(pi."AnsText"))

            left outer join ax_map pic on pic."SourceId" = pi."PItemCol" and pic."TableName" = 'PITEMCOL' and pic."Audit" = vMapAudit

          where

            s."FormCode" = pSourceForm and

            s."Code" = cQuestions."Code" and 

            s."Deleted" = 0 and

            pi."Status" = 0

        );

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ' || cQuestions."Code" || ' pitem rows inserted.',vParams);

      elsif (

        cQuestions."SourceType" = ax_pkg.ANSWER_YES_NO and 

        (

          cQuestions."TargetType" = ax_pkg.ANSWER_TEXT or

          cQuestions."TargetType" = ax_pkg.ANSWER_LONG_TEXT or 

          cQuestions."TargetType" = ax_pkg.ANSWER_CALCULATED           

        )    

      ) then

        -- Convert AnsYes to AnsText 

        -- 0 = No, 1 = Yes, -1 = Unanswered, 2 = Do not know

        insert into pitem (

          select

            pi."Patient", -- Patient

            pTargetForm, -- FormCode

            t."FItem", -- FItem

            t."AnsType", -- AnsType

            0, -- AnsYes

            decode(pi."AnsYes",

              0,'No',

              1,'Yes',

              2,'Do not know',

              'Unanswered'

            ), -- AnsText

            pi."AnsList", -- AnsList

            pi."AnsListDesc", -- AnsListDesc

            pi."Date", -- Date

            vParams."User", -- User

            pi."Status", -- Status

            pi."AuditNumber", -- AuditNumber

            pi."AppUser", -- AppUser

            pi."AppDate", -- AppDate

            pi."AnsDate", -- AnsDate

            pi."ASAType", -- ASAType

            pi."ASAScore", -- ASAScore

            PItem_PItem_seq.nextval, -- PItem

            pi."Time", -- Time

            m."TargetId", -- PForm

            0, -- PItemImg

            pi."AnsListRefCode", -- AnsListRefCode

            pi."EntryDateTime", -- EntryDateTime

            pi."AppDateTime", -- AppDateTime

            nvl(pic."TargetId",0) -- PItemCol

          from

            pitem pi

            inner join fitem s on s."FItem" = pi."FItem"

            inner join fitem t on t."FormCode" = pTargetForm and t."Code" = cQuestions."Code" and t."Deleted" = 0

            inner join ax_map m on m."SourceId" = pi."PForm" and m."TableName" = 'PFORM' and m."Audit" = vMapAudit

            left outer join ax_map pic on pic."SourceId" = pi."PItemCol" and pic."TableName" = 'PITEMCOL' and pic."Audit" = vMapAudit

          where

            s."FormCode" = pSourceForm and

            s."Code" = cQuestions."Code" and 

            s."Deleted" = 0 and

            pi."Status" = 0

        );

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ' || cQuestions."Code" || ' pitem rows inserted.',vParams);

      elsif (

        cQuestions."TargetType" = ax_pkg.ANSWER_YES_NO and 

        (

          cQuestions."SourceType" = ax_pkg.ANSWER_TEXT or

          cQuestions."SourceType" = ax_pkg.ANSWER_LONG_TEXT or 

          cQuestions."SourceType" = ax_pkg.ANSWER_CALCULATED           

        )    

      ) then

        -- Convert AnsText to AnsYes 

        -- 0 = No, 1 = Yes, -1 = Unanswered, 2 = Do not know    

        insert into pitem (

          select

            pi."Patient", -- Patient

            pTargetForm, -- FormCode

            t."FItem", -- FItem

            t."AnsType", -- AnsType

            decode(trim(upper(pi."AnsText")),

              'NO',0,

              'NOT',0,

              'NOPE',0,

              'NEGATIVE',0,

              'NEVER',0,

              'NAY',0,

              'NIX',0,

              'NOT AT ALL',0,

              'NOT BY ANY MEANS',0,

              'BY NO MEANS',0,

              'ABSOLUTELY NOT',0,

              'FALSE',0,

              '0',0,

              'YES',1,

              'YEP',1,

              'YUP',1,

              'YEA',1,

              'ALWAYS',1,

              'POSITIVE',1,

              'POSITIVELY',1,

              'CERTAINLY',1,

              'AYE',1,

              'ABSOLUTELY',1,

              'DEFINATELY',1,

              'TRUE',1,

              '1',1,

              'DO NOT KNOW',2,

              'DON''T KNOW',2,

              'I DO NOT KNOW',2,

              'I DON''T KNOW',2,

              'NOT SURE',2,

              'UNSURE',2,

              'UNKNOWN',2,

              '2',2,

              -1

            ), -- AnsYes

            pi."AnsText", -- AnsText

            pi."AnsList", -- AnsList

            pi."AnsListDesc", -- AnsListDesc

            pi."Date", -- Date

            vParams."User", -- User

            pi."Status", -- Status

            pi."AuditNumber", -- AuditNumber

            pi."AppUser", -- AppUser

            pi."AppDate", -- AppDate

            pi."AnsDate", -- AnsDate

            pi."ASAType", -- ASAType

            pi."ASAScore", -- ASAScore

            PItem_PItem_seq.nextval, -- PItem

            pi."Time", -- Time

            m."TargetId", -- PForm

            0, -- PItemImg

            pi."AnsListRefCode", -- AnsListRefCode

            pi."EntryDateTime", -- EntryDateTime

            pi."AppDateTime", -- AppDateTime

            nvl(pic."TargetId",0) -- PItemCol

          from

            pitem pi

            inner join fitem s on s."FItem" = pi."FItem"

            inner join fitem t on t."FormCode" = pTargetForm and t."Code" = cQuestions."Code" and t."Deleted" = 0

            inner join ax_map m on m."SourceId" = pi."PForm" and m."TableName" = 'PFORM' and m."Audit" = vMapAudit

            left outer join ax_map pic on pic."SourceId" = pi."PItemCol" and pic."TableName" = 'PITEMCOL' and pic."Audit" = vMapAudit

          where

            s."FormCode" = pSourceForm and

            s."Code" = cQuestions."Code" and 

            s."Deleted" = 0 and

            pi."Status" = 0

        );

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ' || cQuestions."Code" || ' pitem rows inserted.',vParams);

      elsif (

        cQuestions."TargetType" = ax_pkg.ANSWER_NUMBER and 

        (

          cQuestions."SourceType" = ax_pkg.ANSWER_TEXT or

          cQuestions."SourceType" = ax_pkg.ANSWER_LONG_TEXT or 

          cQuestions."SourceType" = ax_pkg.ANSWER_CALCULATED           

        )    

      ) then

        -- Convert AnsText to a number 

        insert into pitem (

          select

            pi."Patient", -- Patient

            pTargetForm, -- FormCode

            t."FItem", -- FItem

            t."AnsType", -- AnsType

            pi."AnsYes", -- AnsYes

            ax_pkg.ConvertToNumber_F(pi."AnsText",null), -- AnsText

            pi."AnsList", -- AnsList

            pi."AnsListDesc", -- AnsListDesc

            pi."Date", -- Date

            vParams."User", -- User

            pi."Status", -- Status

            pi."AuditNumber", -- AuditNumber

            pi."AppUser", -- AppUser

            pi."AppDate", -- AppDate

            pi."AnsDate", -- AnsDate

            pi."ASAType", -- ASAType

            pi."ASAScore", -- ASAScore

            PItem_PItem_seq.nextval, -- PItem

            pi."Time", -- Time

            m."TargetId", -- PForm

            0, -- PItemImg

            pi."AnsListRefCode", -- AnsListRefCode

            pi."EntryDateTime", -- EntryDateTime

            pi."AppDateTime", -- AppDateTime

            nvl(pic."TargetId",0) -- PItemCol

          from

            pitem pi

            inner join fitem s on s."FItem" = pi."FItem"

            inner join fitem t on t."FormCode" = pTargetForm and t."Code" = cQuestions."Code" and t."Deleted" = 0

            inner join ax_map m on m."SourceId" = pi."PForm" and m."TableName" = 'PFORM' and m."Audit" = vMapAudit

            left outer join ax_map pic on pic."SourceId" = pi."PItemCol" and pic."TableName" = 'PITEMCOL' and pic."Audit" = vMapAudit

          where

            s."FormCode" = pSourceForm and

            s."Code" = cQuestions."Code" and 

            s."Deleted" = 0 and

            pi."Status" = 0

        );

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ' || cQuestions."Code" || ' pitem rows inserted.',vParams);

      elsif (

        cQuestions."SourceType" = ax_pkg.ANSWER_DATE and 

        (

          cQuestions."TargetType" = ax_pkg.ANSWER_TEXT or

          cQuestions."TargetType" = ax_pkg.ANSWER_LONG_TEXT or 

          cQuestions."TargetType" = ax_pkg.ANSWER_CALCULATED           

        )    

      ) then

        -- Convert AnsDate to AnsText       

       insert into pitem (

          select

            pi."Patient", -- Patient

            pTargetForm, -- FormCode

            t."FItem", -- FItem

            t."AnsType", -- AnsType

            pi."AnsYes", -- AnsYes

            to_char(pi."AnsDate",ax_pkg.DESCRIPTIVE_DATE_FORMAT), -- AnsText

            pi."AnsList", -- AnsList

            pi."AnsListDesc", -- AnsListDesc

            pi."Date", -- Date

            vParams."User", -- User

            pi."Status", -- Status

            pi."AuditNumber", -- AuditNumber

            pi."AppUser", -- AppUser

            pi."AppDate", -- AppDate

            pi."AnsDate", -- AnsDate

            pi."ASAType", -- ASAType

            pi."ASAScore", -- ASAScore

            PItem_PItem_seq.nextval, -- PItem

            pi."Time", -- Time

            m."TargetId", -- PForm

            0, -- PItemImg

            pi."AnsListRefCode", -- AnsListRefCode

            pi."EntryDateTime", -- EntryDateTime

            pi."AppDateTime", -- AppDateTime

            nvl(pic."TargetId",0) -- PItemCol

          from

            pitem pi

            inner join fitem s on s."FItem" = pi."FItem"

            inner join fitem t on t."FormCode" = pTargetForm and t."Code" = cQuestions."Code" and t."Deleted" = 0

            inner join ax_map m on m."SourceId" = pi."PForm" and m."TableName" = 'PFORM' and m."Audit" = vMapAudit

            left outer join ax_map pic on pic."SourceId" = pi."PItemCol" and pic."TableName" = 'PITEMCOL' and pic."Audit" = vMapAudit

          where

            s."FormCode" = pSourceForm and

            s."Code" = cQuestions."Code" and 

            s."Deleted" = 0 and

            pi."Status" = 0

        );

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ' || cQuestions."Code" || ' pitem rows inserted.',vParams);

      elsif (

        cQuestions."TargetType" = ax_pkg.ANSWER_DATE and 

        (

          cQuestions."SourceType" = ax_pkg.ANSWER_TEXT or

          cQuestions."SourceType" = ax_pkg.ANSWER_LONG_TEXT or 

          cQuestions."SourceType" = ax_pkg.ANSWER_CALCULATED           

        )    

      ) then

        -- Convert AnsText to AnsDate

       insert into pitem (

          select

            pi."Patient", -- Patient

            pTargetForm, -- FormCode

            t."FItem", -- FItem

            t."AnsType", -- AnsType

            pi."AnsYes", -- AnsYes

            pi."AnsText", -- AnsText

            pi."AnsList", -- AnsList

            pi."AnsListDesc", -- AnsListDesc

            pi."Date", -- Date

            vParams."User", -- User

            pi."Status", -- Status

            pi."AuditNumber", -- AuditNumber

            pi."AppUser", -- AppUser

            pi."AppDate", -- AppDate

            ax_pkg.ConvertToDate_F(pi."AnsText"), -- AnsDate

            pi."ASAType", -- ASAType

            pi."ASAScore", -- ASAScore

            PItem_PItem_seq.nextval, -- PItem

            pi."Time", -- Time

            m."TargetId", -- PForm

            0, -- PItemImg

            pi."AnsListRefCode", -- AnsListRefCode

            pi."EntryDateTime", -- EntryDateTime

            pi."AppDateTime", -- AppDateTime

            nvl(pic."TargetId",0) -- PItemCol

          from

            pitem pi

            inner join fitem s on s."FItem" = pi."FItem"

            inner join fitem t on t."FormCode" = pTargetForm and t."Code" = cQuestions."Code" and t."Deleted" = 0

            inner join ax_map m on m."SourceId" = pi."PForm" and m."TableName" = 'PFORM' and m."Audit" = vMapAudit

            left outer join ax_map pic on pic."SourceId" = pi."PItemCol" and pic."TableName" = 'PITEMCOL' and pic."Audit" = vMapAudit

          where

            s."FormCode" = pSourceForm and

            s."Code" = cQuestions."Code" and 

            s."Deleted" = 0 and

            pi."Status" = 0

        );        

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ' || cQuestions."Code" || ' pitem rows inserted.',vParams);

      elsif (

        cQuestions."SourceType" = ax_pkg.ANSWER_YES_NO and 

        cQuestions."TargetType" = ax_pkg.ANSWER_NUMBER           

      ) then

        -- Convert AnsYes to AnsText as a number       

       insert into pitem (

          select

            pi."Patient", -- Patient

            pTargetForm, -- FormCode

            t."FItem", -- FItem

            t."AnsType", -- AnsType

            0, -- AnsYes

            to_char(pi."AnsYes"), -- AnsText

            pi."AnsList", -- AnsList

            pi."AnsListDesc", -- AnsListDesc

            pi."Date", -- Date

            vParams."User", -- User

            pi."Status", -- Status

            pi."AuditNumber", -- AuditNumber

            pi."AppUser", -- AppUser

            pi."AppDate", -- AppDate

            pi."AnsDate", -- AnsDate

            pi."ASAType", -- ASAType

            pi."ASAScore", -- ASAScore

            PItem_PItem_seq.nextval, -- PItem

            pi."Time", -- Time

            m."TargetId", -- PForm

            0, -- PItemImg

            pi."AnsListRefCode", -- AnsListRefCode

            pi."EntryDateTime", -- EntryDateTime

            pi."AppDateTime", -- AppDateTime

            nvl(pic."TargetId",0) -- PItemCol

          from

            pitem pi

            inner join fitem s on s."FItem" = pi."FItem"

            inner join fitem t on t."FormCode" = pTargetForm and t."Code" = cQuestions."Code" and t."Deleted" = 0

            inner join ax_map m on m."SourceId" = pi."PForm" and m."TableName" = 'PFORM' and m."Audit" = vMapAudit

            left outer join ax_map pic on pic."SourceId" = pi."PItemCol" and pic."TableName" = 'PITEMCOL' and pic."Audit" = vMapAudit

          where

            s."FormCode" = pSourceForm and

            s."Code" = cQuestions."Code" and 

            s."Deleted" = 0 and

            pi."Status" = 0

        );        

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ' || cQuestions."Code" || ' pitem rows inserted.',vParams);

      elsif (

        cQuestions."SourceType" = ax_pkg.ANSWER_NUMBER and 

        cQuestions."TargetType" = ax_pkg.ANSWER_YES_NO           

      ) then

        -- Convert AnsText as number to AnsYes  

          -- Only conver number values lower than 3

       insert into pitem (

          select

            pi."Patient", -- Patient

            pTargetForm, -- FormCode

            t."FItem", -- FItem

            t."AnsType", -- AnsType

            case  

              when ax_pkg.ConvertToNumber_F(pi."AnsText") < 3 then ax_pkg.ConvertToNumber_F(pi."AnsText") 

              else -1 

            end, -- AnsYes

            pi."AnsText", -- AnsText

            pi."AnsList", -- AnsList

            pi."AnsListDesc", -- AnsListDesc

            pi."Date", -- Date

            vParams."User", -- User

            pi."Status", -- Status

            pi."AuditNumber", -- AuditNumber

            pi."AppUser", -- AppUser

            pi."AppDate", -- AppDate

            pi."AnsDate", -- AnsDate

            pi."ASAType", -- ASAType

            pi."ASAScore", -- ASAScore

            PItem_PItem_seq.nextval, -- PItem

            pi."Time", -- Time

            m."TargetId", -- PForm

            0, -- PItemImg

            pi."AnsListRefCode", -- AnsListRefCode

            pi."EntryDateTime", -- EntryDateTime

            pi."AppDateTime", -- AppDateTime

            nvl(pic."TargetId",0) -- PItemCol

          from

            pitem pi

            inner join fitem s on s."FItem" = pi."FItem"

            inner join fitem t on t."FormCode" = pTargetForm and t."Code" = cQuestions."Code" and t."Deleted" = 0

            inner join ax_map m on m."SourceId" = pi."PForm" and m."TableName" = 'PFORM' and m."Audit" = vMapAudit

            left outer join ax_map pic on pic."SourceId" = pi."PItemCol" and pic."TableName" = 'PITEMCOL' and pic."Audit" = vMapAudit

          where

            s."FormCode" = pSourceForm and

            s."Code" = cQuestions."Code" and 

            s."Deleted" = 0 and

            pi."Status" = 0

        );   

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ' || cQuestions."Code" || ' pitem rows inserted.',vParams);

      elsif (

        cQuestions."TargetType" = ax_pkg.ANSWER_LIST and 

        cQuestions."SourceType" = ax_pkg.ANSWER_YES_NO

      ) then

        -- Convert Yes/No to List

        --   Map Yes,No,Do not know,Unanswered to List Description

        insert into pitem (

          select

            pi."Patient", -- Patient

            pTargetForm, -- FormCode

            t."FItem", -- FItem

            t."AnsType", -- AnsType

            pi."AnsYes", -- AnsYes

            pi."AnsText", -- AnsText

            t."AnsList", -- AnsList

            li."Description", -- AnsListDesc

            pi."Date", -- Date

            vParams."User", -- User

            pi."Status", -- Status

            pi."AuditNumber", -- AuditNumber

            pi."AppUser", -- AppUser

            pi."AppDate", -- AppDate

            pi."AnsDate", -- AnsDate

            pi."ASAType", -- ASAType

            pi."ASAScore", -- ASAScore

            PItem_PItem_seq.nextval, -- PItem

            pi."Time", -- Time

            m."TargetId", -- PForm

            0, -- PItemImg

            pi."AnsListRefCode", -- AnsListRefCode

            pi."EntryDateTime", -- EntryDateTime

            pi."AppDateTime", -- AppDateTime

            nvl(pic."TargetId",0) -- PItemCol

          from

            pitem pi

            inner join fitem s on s."FItem" = pi."FItem"

            inner join fitem t on t."FormCode" = pTargetForm and t."Code" = cQuestions."Code" and t."Deleted" = 0

            inner join ax_map m on m."SourceId" = pi."PForm" and m."TableName" = 'PFORM' and m."Audit" = vMapAudit

            left outer join ax_map pic on pic."SourceId" = pi."PItemCol" and pic."TableName" = 'PITEMCOL' and pic."Audit" = vMapAudit

            left outer join listitem li on 

              li."ListCode" = t."AnsList" and

              (

                (

                  trim(upper(li."Description")) = 'YES' and

                  pi."AnsYes" = 1

                ) or (

                  trim(upper(li."Description")) = 'NO' and

                  pi."AnsYes" = 0

                ) or (

                  trim(upper(li."Description")) = 'DO NOT KNOW' and

                  pi."AnsYes" = 2

                ) or (

                  trim(upper(li."Description")) = 'UNKNOWN' and

                  pi."AnsYes" = -1

                )

              )

          where

            s."FormCode" = pSourceForm and

            s."Code" = cQuestions."Code" and 

            s."Deleted" = 0 and

            pi."Status" = 0

        );

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ' || cQuestions."Code" || ' pitem rows inserted.',vParams);

      else

        -- conversion not supported

          -- Only display if not called from a loop

        ax_pkg.AppendString_P(pvMessage,'Answer Types not currently supported. Cannot copy ' ||

          ax_pkg.GetAnswerType_F(cQuestions."SourceType") || ' type answers into ' ||

          ax_pkg.GetAnswerType_F(cQuestions."TargetType") || ' type answers.'

        ,' ',ax_pkg.MSG_ERROR,pParams);

        pvSuccess := false;

      end if;

      

      if (not vItemSuccess and (vLastRefCode <> cQuestions."Code")) then

        -- Only display errors once for each Reference Code

        ax_pkg.AppendString_P(pvMessage,vItemMessage,' ',ax_pkg.MSG_ERROR,pParams);

      end if;

      vItemMessage := null;

      vLastRefCode := cQuestions."Code";

    end loop;

*/

/*

    for cQuestions in curQuestions loop

      CopySingleAnswer_P(

        vItemSuccess,

        vItemMessage,  

        pSourceForm,

        cQuestions."Code",

        pTargetForm,

        cQuestions."Code",

        vParams,

        cQuestions."SourceType",

        cQuestions."TargetType",

        vMapAudit

      );

      if (not vItemSuccess and (vLastRefCode <> cQuestions."Code")) then

        -- Only display errors once for each Reference Code

        ax_pkg.AppendString_P(pvMessage,vItemMessage,' ',ax_pkg.MSG_ERROR,pParams);

      end if;

      vItemMessage := null;

      vLastRefCode := cQuestions."Code";

    end loop;

    */

    /*

   ----------------

    -- Adjust PItemImg Type

    ----------------

    update pitemimg set 

      "Type" = 1,

      "FileExt" = 'jpeg'

    where "PItemImg" in (

      select 

        pii."PItemImg"

      from

        pitemimg pii

        inner join pitem p on p."PItemImg" = pii."PItemImg" and p."AnsType" = 8

      where

        pii."Type" = 0

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount)  || ' pitemimg rows updated.',vParams);

        

    ----------------

    -- Copy PtSig

    ---------------- 

    -- Do not copy signatures, as the patient signed a different version of the form

    

    ----------------

    -- Copy NoteOvr

    ----------------   

    -- Create noteovr Records

    for cNoteOverMap in curNoteOvrMap1(vMapAudit) loop

      select * into vNoteOvrRow from noteovr where "Id" = cNoteOverMap."Id"; 

      select noteovr_id_seq.nextval into vNoteOvrRow."Id" from dual;

      vNoteOvrRow."ParentId" := cNoteOverMap."TargetId";

      insert into noteovr values vNoteOvrRow;

      vCount := vCount + 1;

    end loop;    

    

    

    ----------------

    -- Cleanup orphans not needed

    ----------------   

    -- delete pitemimg, pitemcol where mapped, but not used

    -- delete ax_map records



    vLogRow."Log" := 'Answers from Form ' || pSourceForm || ' copied to Form ' || pTargetForm;

    ax_pkg.log_p(vLogRow,ax_pkg.MSG_INFO,vParams);  

    

    pvSuccess := true;

    */

  exception

    when exNotCompatible then

      ax_pkg.AppendString_P(pvMessage,'Forms not compatible. Cannot copy a form that can have multiple to a form that cannot.',' ',ax_pkg.MSG_ERROR,pParams);

    when exSourceNotFound then

      ax_pkg.AppendString_P(pvMessage,'Source form ' || pSourceForm || ' not found!',' ',ax_pkg.MSG_ERROR,pParams);

    when exTargetNotFound then

      ax_pkg.AppendString_P(pvMessage,'Target form ' || pTargetForm || ' not found!',' ',ax_pkg.MSG_ERROR,pParams);

    when exNothingToCopy then

      ax_pkg.AppendString_P(pvMessage,'Nothing found to copy! Make sure that:',' ',ax_pkg.MSG_ERROR,pParams);

      ax_pkg.AppendString_P(pvMessage,'  * At least one Question in each form has a matching Reference Code',' ',ax_pkg.MSG_ERROR,pParams);

      ax_pkg.AppendString_P(pvMessage,'  * There are patients with the source form filled out',' ',ax_pkg.MSG_ERROR,pParams);

      ax_pkg.AppendString_P(pvMessage,'  * The target form does not exist for some patients or is set to allow multiple',' ',ax_pkg.MSG_ERROR,pParams);

  end CopyAnswers_P;  

  

  

  -- overload

  PROCEDURE copyanswers_p(IN psourceform character, IN ptargetform character, IN poverwriteexisting boolean DEFAULT false, IN pfstatus character DEFAULT NULL::bpchar, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vMessage  VARCHAR2(4000);

    vSuccess boolean;

  begin

    CopyAnswers_P(vSuccess,vMessage,pSourceForm,pTargetForm,pOverwriteExisting,pFStatus,pParams);

    if not vSuccess then

      raise_application_error(-20000, vMessage);

    end if;

  end CopyAnswers_P;

  

END;
CREATE OR REPLACE PACKAGE BODY ax_email_pkg IS



  -- returns information about this package, or its procedures

  PROCEDURE help(IN pobjectname character varying DEFAULT NULL::character varying) IS

    vReturn CLOB;

  begin

    -- Writes the help to the DBMS_OUTPUT

	-- AX-39259

    vReturn := ax_pkg.Help_F('AX_EMAIL_PKG',pObjectName);

  end Help;



  -- Sends an email, as long as the SMTP service is properly configured

  PROCEDURE sendemail_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, INOUT pvemailparams temailparams, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

  --

  --  send mail from the Oracle Server

  --  Assumptions: SMTP service is properly configured on the Oracle Server

  --               Delimiter used is either , (comma) or ; (semi-colon)

    

    vMailConnection utl_smtp.connection;

    vRecipientList  VARCHAR2(4000);

    vRecipient  VARCHAR2(255);

    vDelimiter  CHAR(1) := ',';

    vPosition number(4) := 0;

    vStep pls_integer := 12000; -- make sure you set a multiple of 3 not higher than 24573

    

    vBoundary  VARCHAR2(50) := '----=*#abc1234321cba#*=';

    

    vDebugNumber pls_integer := 0;

    

    vParams ax_pkg.tParams := pParams;

    

    exNoMailHostKey exception;

    exNoSender exception;

    exTooManyAttachments exception;

    exNoBody exception;

  begin

    

    vDebugNumber := 1;

    

    ax_pkg.InitializeParams_P(vParams);

  

    vDebugNumber := 5;

  

    if pvEmailParams."MailHost" is null then

      begin

        select "Value" into pvEmailParams."MailHost" from ax_setting where "Key" = 'Email.Server';

      exception

        when no_data_found then

          raise exNoMailHostKey;

      end;

    end if;



    vDebugNumber := 10;

     

    if (trim(pvEmailParams."Sender") is null OR length(trim(pvEmailParams."Sender")) = 0) then

      select "Value" into pvEmailParams."Sender" from ax_setting where "Key" = 'Email.DefaultSender';

    end if;

  

    vDebugNumber := 15;

  

    if (trim(pvEmailParams."Sender") is null OR length(trim(pvEmailParams."Sender")) = 0) then

      raise exNoSender;

    end if;

    

    vDebugNumber := 20;

    

    if pvEmailParams."AttachBlob" is not null and pvEmailParams."AttachClob" is not null then

      raise exTooManyAttachments;

    end if;

    

    vDebugNumber := 25;

    

    if pvEmailParams."TextMessage" is null and pvEmailParams."HTMLMessage" is null  then

      raise exNoBody;

    end if;

  

    vDebugNumber := 30;

  

    vMailConnection := utl_smtp.open_connection(pvEmailParams."MailHost", 25);

    utl_smtp.helo(vMailConnection, pvEmailParams."MailHost");

    utl_smtp.mail(vMailConnection, pvEmailParams."Sender");

  

    vDebugNumber := 35;

  

  -- process recipient list



    -- remove spaces; replace ; (semi-colon) with , (comma)

    vRecipientList := replace(replace(pvEmailParams."Recipient", ' '), ';', pvEmailParams."Delimiter");

    vPosition := instr(vRecipientList, pvEmailParams."Delimiter", 1, 1);

    

    vDebugNumber := 40;

    

    while (vPosition != 0) loop  

      -- get recipient

      vRecipient := substr(vRecipientList, 1, vPosition - 1);

    

      -- remove recipient from list

      vRecipientList := substr(vRecipientList, vPosition + 1, length(vRecipientList));



      utl_smtp.rcpt(vMailConnection, vRecipient);



      -- get position of next recipient

      vPosition := instr(vRecipientList, vDelimiter, 1, 1);

    end loop;

    

    -- get last recipient

    if (vPosition = 0) then

      vRecipient := vRecipientList;

      utl_smtp.rcpt(vMailConnection, vRecipient);

    end if;

   

  -- process CCrecipient list



    vDebugNumber := 45;



    -- remove spaces; replace ; (semi-colon) with , (comma)

    vRecipientList := replace(replace(pvEmailParams."CCRecipient", ' '), ';', vDelimiter);

    vPosition := instr(vRecipientList, vDelimiter, 1, 1);

    

    while (vPosition != 0) loop  

      -- get recipient

      vRecipient := substr(vRecipientList, 1, vPosition - 1);

    

      -- remove recipient from list

      vRecipientList := substr(vRecipientList, vPosition + 1, length(vRecipientList));



      utl_smtp.rcpt(vMailConnection, vRecipient);



      -- get position of next recipient

      vPosition := instr(vRecipientList, vDelimiter, 1, 1);

    end loop;

    

    -- get last recipient

    if (vPosition = 0) then

      vRecipient := vRecipientList;

      utl_smtp.rcpt(vMailConnection, vRecipient);

    end if;

    

  -- process BCCrecipient list



    vDebugNumber := 50;



    -- remove spaces; replace ; (semi-colon) with , (comma)

    vRecipientList := replace(replace(pvEmailParams."BCCRecipient", ' '), ';', vDelimiter);

    vPosition := instr(vRecipientList, vDelimiter, 1, 1);

    

    while (vPosition != 0) loop  

      -- get recipient

      vRecipient := substr(vRecipientList, 1, vPosition - 1);

    

      -- remove recipient from list

      vRecipientList := substr(vRecipientList, vPosition + 1, length(vRecipientList));



      utl_smtp.rcpt(vMailConnection, vRecipient);



      -- get position of next recipient

      vPosition := instr(vRecipientList, vDelimiter, 1, 1);

    end loop;

  

    -- get last recipient

    if (vPosition = 0) then

      vRecipient := vRecipientList;

      utl_smtp.rcpt(vMailConnection, vRecipient);

    end if;

    

    vDebugNumber := 55;

    

    -- send message    

    utl_smtp.open_data(vMailConnection); 

    

    vDebugNumber := 56;    

    

    utl_smtp.write_data(vMailConnection, 'Date: ' || to_char(sysdate, 'DD-MON-YYYY HH24:MI:SS') || utl_tcp.crlf);

    utl_smtp.write_data(vMailConnection, 'To: ' || pvEmailParams."Recipient" || utl_tcp.crlf);

    utl_smtp.write_data(vMailConnection, 'CC: ' || pvEmailParams."CCRecipient" || utl_tcp.crlf);

    utl_smtp.write_data(vMailConnection, 'From: ' || pvEmailParams."Sender" || utl_tcp.crlf);

    utl_smtp.write_data(vMailConnection, 'Subject: ' || pvEmailParams."Subject" || utl_tcp.crlf);

    utl_smtp.write_data(vMailConnection, 'Reply-To: ' || pvEmailParams."Sender" || utl_tcp.crlf);

    utl_smtp.write_data(vMailConnection, 'MIME-Version: 1.0' || utl_tcp.crlf);

    utl_smtp.write_data(vMailConnection, 'Content-Type: multipart/alternative; boundary="' || vBoundary || '"' || utl_tcp.crlf || utl_tcp.crlf);

    

    vDebugNumber := 60;

    

    if pvEmailParams."TextMessage" is not null then

      utl_smtp.write_data(vMailConnection, '--' || vBoundary || utl_tcp.crlf);

      utl_smtp.write_data(vMailConnection, 'Content-Type: text/plain; charset="iso-8859-1"' || utl_tcp.crlf || utl_tcp.crlf);

  

      utl_smtp.write_data(vMailConnection, replace(pvEmailParams."TextMessage", chr(13) || chr(10), chr(13) || chr(10) || '  '));

      utl_smtp.write_data(vMailConnection, utl_tcp.crlf || utl_tcp.crlf);

    end if;

  

    vDebugNumber := 65;

  

    if pvEmailParams."HTMLMessage" is not null then

      utl_smtp.write_data(vMailConnection, '--' || vBoundary || utl_tcp.crlf);

      utl_smtp.write_data(vMailConnection, 'Content-Type: text/html; charset="iso-8859-1"' || utl_tcp.crlf || utl_tcp.crlf);

  

      utl_smtp.write_data(vMailConnection, pvEmailParams."HTMLMessage");

      utl_smtp.write_data(vMailConnection, utl_tcp.crlf || utl_tcp.crlf);

    end if;

  

    vDebugNumber := 70;

    

    if pvEmailParams."AttachClob" is not null then

      if pvEmailParams."AttachName" is null then

        ax_pkg.LogEvent_P('ax_email_pkg.SendEmail_P','No Attachment Name, email sent without attachment!',vParams);

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_ERROR,'ax_email_pkg.SendEmail_P: ' || 'No Attachment Name, email sent without attachment!',vParams);

      elsif pvEmailParams."AttachMime" is null then

        ax_pkg.LogEvent_P('ax_email_pkg.SendEmail_P','No Attachment Mime, email sent without attachment!',vParams);

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_ERROR,'ax_email_pkg.SendEmail_P: ' || 'No Attachment Mime, email sent without attachment!',vParams);

      else      

        utl_smtp.write_data(vMailConnection, '--' || vBoundary || utl_tcp.crlf);

        utl_smtp.write_data(vMailConnection, 'Content-Type: ' || pvEmailParams."AttachMime" || '; name="' || pvEmailParams."AttachName" || '"' || utl_tcp.crlf);

        utl_smtp.write_data(vMailConnection, 'Content-Disposition: attachment; filename="' || pvEmailParams."AttachName" || '"' || utl_tcp.crlf || utl_tcp.crlf);

     

        for i in 0 .. trunc((dbms_lob.getlength(pvEmailParams."AttachClob") - 1 )/vStep) loop

          utl_smtp.write_data(vMailConnection, dbms_lob.substr(pvEmailParams."AttachClob", vStep, i * vStep + 1));

        end loop;

    

        utl_smtp.write_data(vMailConnection, utl_tcp.crlf || utl_tcp.crlf);

      end if;

    end if;

    

    vDebugNumber := 75;

    

    if pvEmailParams."AttachBlob" is not null then

      if pvEmailParams."AttachName" is null then

        ax_pkg.LogEvent_P('ax_email_pkg.SendEmail_P','No Attachment Name, email sent without attachment!',vParams);

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_ERROR,'ax_email_pkg.SendEmail_P: ' || 'No Attachment Name, email sent without attachment!',vParams);

      elsif pvEmailParams."AttachMime" is null then

        ax_pkg.LogEvent_P('ax_email_pkg.SendEmail_P','No Attachment Mime, email sent without attachment!',vParams);

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_ERROR,'ax_email_pkg.SendEmail_P: ' || 'No Attachment Mime, email sent without attachment!',vParams);

      else      

        utl_smtp.write_data(vMailConnection, '--' || vBoundary || utl_tcp.crlf);

        utl_smtp.write_data(vMailConnection, 'Content-Type: ' || pvEmailParams."AttachMime" || '; name="' || pvEmailParams."AttachName" || '"' || utl_tcp.crlf);

        utl_smtp.write_data(vMailConnection, 'Content-Transfer-Encoding: base64' || utl_tcp.crlf);

        utl_smtp.write_data(vMailConnection, 'Content-Disposition: attachment; filename="' || pvEmailParams."AttachName" || '"' || utl_tcp.crlf || utl_tcp.crlf);

     

        for i in 0 .. trunc((dbms_lob.getlength(pvEmailParams."AttachBlob") - 1 )/vStep) loop

          utl_smtp.write_data(vMailConnection, utl_raw.cast_to_varchar2(utl_encode.base64_encode(dbms_lob.substr(pvEmailParams."AttachBlob", vStep, i * vStep + 1))));

        end loop;

    

        utl_smtp.write_data(vMailConnection, utl_tcp.crlf || utl_tcp.crlf);

      end if;

    end if;



    vDebugNumber := 80;

  

    utl_smtp.write_data(vMailConnection, '--' || vBoundary || '--' || utl_tcp.crlf);

    utl_smtp.close_data(vMailConnection);  

    utl_smtp.quit(vMailConnection);   

    

    vDebugNumber := 85;

    

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_INFO,'Email sent to ' || pvEmailParams."Recipient",vParams);

    pvSuccess := true;

  exception

  /*

    WHEN UTL_SMTP.INVALID_OPERATION THEN

    INSERT INTO SDM_LOG VALUES(SDM_LOG_ID.NEXTVAL, 'Invalid Operation', 'SDM_EXCH_MAIL', SYSDATE);

  WHEN UTL_SMTP.TRANSIENT_ERROR THEN

    INSERT INTO SDM_LOG VALUES(SDM_LOG_ID.NEXTVAL, 'Transient Error', 'SDM_EXCH_MAIL', SYSDATE); 

  WHEN UTL_SMTP.PERMANENT_ERROR THEN

    INSERT INTO SDM_LOG VALUES(SDM_LOG_ID.NEXTVAL,'Permanent Error', 'SDM_EXCH_MAIL', SYSDATE); 

    */

    when exNoBody then

      ax_pkg.LogEvent_P('ax_email_pkg.S "endEmail_P','No Email Body!',vParams);

      ax_pkg.AppendString_P(pvMessage,'No Email Body!',' ',ax_pkg.MSG_ERROR,vParams);

      pvSuccess := false;

    when exTooManyAttachments then

      ax_pkg.LogEvent_P('ax_email_pkg.SendEmail_P','Only one attachment may be sent at a time.',vParams);

      ax_pkg.AppendString_P(pvMessage,'Only one attachment may be sent at a time.',' ',ax_pkg.MSG_ERROR,vParams);

      pvSuccess := false;

    when exNoMailHostKey then

      ax_pkg.LogEvent_P('ax_email_pkg.SendEmail_P','No MailHost set in ax_setting under ''Email.Server''.',vParams);

      ax_pkg.AppendString_P(pvMessage,'No MailHost set in ax_setting under ''Email.Server''.',' ',ax_pkg.MSG_ERROR,vParams);

      pvSuccess := false;

    when exNoSender then

      ax_pkg.LogEvent_P('ax_email_pkg.SendEmail_P','No Sender sent, or set in ax_setting under ''Email.DefaultSender''.',vParams);

      ax_pkg.AppendString_P(pvMessage,'No Sender sent, or set in ax_setting under ''Email.DefaultSender''.',' ',ax_pkg.MSG_ERROR,vParams);

      pvSuccess := false;

    when others then

      begin

        utl_smtp.quit(vMailConnection);

      exception

        when others then

          null; -- if we can not quit, then we probably do not need to

      end;  

      ax_pkg.LogEvent_P('ax_email_pkg.SendEmail_P','DebugNum=' || vDebugNumber || ' - ' || sqlerrm,vParams);

      ax_pkg.AppendString_P(pvMessage,'DebugNum=' || vDebugNumber || ' - ' || sqlerrm,' ',ax_pkg.MSG_ERROR,vParams); 

      pvSuccess := false;

  end SendEmail_P;

  

  

  -- overload

  PROCEDURE sendemail_p(INOUT pvemailparams temailparams, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vSuccess boolean;

    vMessage  VARCHAR2(4000);

  begin

    SendEmail_P(vSuccess,vMessage,pvEmailParams,pParams);

    if not vSuccess then

      raise_application_error(-20000, vMessage);

    end if;    

  end SendEmail_P;

  

  

  -- Send an email to an axiUm User to an axiUm User

   -- calls SendEmail_P

  PROCEDURE senduseremail_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN psenderuser numeric, IN precipientuser numeric, INOUT pvemailparams temailparams, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

  --

  --  script to create a procedure that can send mail from the Oracle Server

  --  Assumptions: SMTP service is properly configured on the Oracle Server

  --               Delimiter used is either , (comma) or ; (semi-colon)

  --

    

  begin

  

    -- Get the Sender Email

    begin

      select "Email" into pvEmailParams."Sender" from users where "User" = pSenderUser;

    exception

      when no_data_found then

        -- If the Sender Email cannot be found, then use the Default No Reply email

        pvEmailParams."Sender" := null;

    end;

    

    -- Get the Recipient Email

    begin 

      select "Email" into pvEmailParams."Recipient" from users where "User" = pRecipientUser;

      

      SendEmail_P(pvSuccess,pvMessage,pvEmailParams,pParams);

     

    exception

      -- If the Recipient Email is not found, then do not continue

      when no_data_found then

        ax_pkg.AppendString_P(pvMessage,'No recipient email found for user ' || pRecipientUser,' ',ax_pkg.MSG_WARNING,pParams);

        pvSuccess := false;

    end;

  end SendUserEmail_P;





  -- Overload

  PROCEDURE senduseremail_p(IN psenderuser numeric, IN precipientuser numeric, INOUT pvemailparams temailparams, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vSuccess boolean;

    vMessage  VARCHAR2(4000);

  begin

    SendUserEmail_P(vSuccess,vMessage,pSenderUser,pRecipientUser,pvEmailParams,pParams);

    if not vSuccess then

      raise_application_error(-20000, vMessage);

    end if;    

  end SendUserEmail_P;





  -- Sends an email from a User to a Patient

    -- calls SendEmail_P

  PROCEDURE sendpatientemail_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN psenderuser numeric, IN precipientpatient numeric, INOUT pvemailparams temailparams, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

  --

  --  script to create a procedure that can send mail from the Oracle Server

  --  Assumptions: SMTP service is properly configured on the Oracle Server

  --               Delimiter used is either , (comma) or ; (semi-colon)

  --    

  begin

    -- Get the Sender Email

    begin

      select "Email" into pvEmailParams."Sender" from users where "User" = pSenderUser;

    exception

      when no_data_found then

        -- If the Sender Email cannot be found, then use the Default No Reply email

        pvEmailParams."Sender" := null;

    end;

    

    -- Get the Recipient Email

    begin 

      select "Email" into pvEmailParams."Recipient" from patient where "Patient" = pRecipientPatient;

      

      SendEmail_P(pvSuccess,pvMessage,pvEmailParams,pParams);

    exception

      -- If the Recipient Email is not found, then do not continue

      when no_data_found then

        ax_pkg.AppendString_P(pvMessage,'No recipient email found for patient ' || pRecipientPatient,' ',ax_pkg.MSG_WARNING,pParams);

        pvSuccess := false;

    end;

  end SendPatientEmail_P;

  

  

  -- Overload

  PROCEDURE sendpatientemail_p(IN psenderuser numeric, IN precipientpatient numeric, INOUT pvemailparams temailparams, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vSuccess boolean;

    vMessage  VARCHAR2(4000);

  begin

    SendPatientEmail_P(vSuccess,vMessage,pSenderUser,pRecipientPatient,pvEmailParams,pParams);

    if not vSuccess then

      raise_application_error(-20000, vMessage);

    end if;    

  end SendPatientEmail_P;  

  

  

  -- Sends an email from a user to a User Group

   -- calls SendUserEmail_P

  PROCEDURE sendugroupemail_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN psenderuser numeric, IN precipientugroup character, INOUT pvemailparams temailparams, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS  

	-- cursor to get users in the group

  	cursor curUGroup is

      select 

        U.* 

      from umember U 

      where 

        U."UGroup" = pRecipientUGroup;  

    v boolean;

    vGroupDesc ugroup."Description"%type;

  begin

    pvSuccess := true;

    -- Add the Group Name to the Subject Line

    select "Description" into vGroupDesc from ugroup where "UGroup" = pRecipientUGroup;

    pvEmailParams."Subject" := vGroupDesc || ': ' || pvEmailParams."Subject";

    -- Loop through the members in the user group, sending out emails

      -- Could be updated to create an email list, then send out only once.

    for cUGroup in curUGroup loop

      SendUserEmail_P(pvSuccess,pvMessage,pSenderUser,cUGroup."User",pvEmailParams,pParams);

    end loop;

  exception

    when no_data_found then

      ax_pkg.AppendString_P(pvMessage,'UGroup Invalid: ' || pRecipientUGroup,' ',ax_pkg.MSG_ERROR,pParams); 

      pvSuccess := false;    

  end SendUGroupEmail_P;

  



  -- Overload

  PROCEDURE sendugroupemail_p(IN psenderuser numeric, IN precipientugroup character, INOUT pvemailparams temailparams, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vSuccess boolean;

    vMessage  VARCHAR2(4000);

  begin

    SendUGroupEmail_P(vSuccess,vMessage,pSenderUser,pRecipientUGroup,pvEmailParams,pParams);

    if not vSuccess then

      raise_application_error(-20000, vMessage);

    end if;    

  end SendUGroupEmail_P;

  

  

  -- Send Notification Email to Patient that they have a new axiUm message

  PROCEDURE sendpatientnewmessageemail_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN precipientpatient numeric, IN pemailparams temailparams DEFAULT ax_email_pkg.ax_email_params, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vSettingRow ax_setting%rowtype;

    vNoteParams ax_note_pkg.tNoteParams;

    vPtContRow ptcont%rowtype;

    vParams ax_pkg.tParams := pParams;

    vEmailParams tEmailParams := pEmailParams;

    vNoteSuccess boolean;

    vNoteMessage  VARCHAR2(4000);

    exAddNoteFailed exception;

  begin

    pvSuccess := false;

    ax_pkg.InitializeParams_P(vParams);

    

    vParams."VerboseType" := ax_pkg.SHOW_ALL;

  

    vSettingRow."Key" := 'Email.PatientNewMessageSubject';

    vSettingRow."Description" := 'This is the subject of the email message that should be sent when a patient recieves an axiUm message.';

    vEmailParams."Subject" := ax_pkg.GetSetting_F(vSettingRow,null,vParams);

  

    vSettingRow."Key" := 'Email.PatientNewMessageText';

    vSettingRow."Description" := 'This is the Text email message that should be sent when a patient recieves an axiUm message.';

    vEmailParams."TextMessage" := ax_pkg.GetSetting_F(vSettingRow,null,vParams);



    vSettingRow."Key" := 'Email.PatientNewMessageHTML';

    vSettingRow."Description" := 'This is the HTML email message that should be sent when a patient recieves an axiUm message.';

    vEmailParams."HTMLMessage" := ax_pkg.GetSetting_F(vSettingRow,null,vParams);



    vSettingRow."Key" := 'Email.PatientNewMessageContactNote';

    vSettingRow."Description" := 'This is the NoteCode (notecode."NoteCode" where "Type" = 3) of the Contact Note copy, if you wish to record that the New Message email has been sent.';

    vPtContRow."NoteCode" := ax_pkg.GetSetting_F(vSettingRow,null,vParams);



    -- Get the Recipient Email

    begin 

      select "Email" into vEmailParams."Recipient" from patient where "Patient" = pRecipientPatient;

      

      SendEmail_P(pvSuccess,pvMessage,vEmailParams,pParams);

    exception

      -- If the Recipient Email is not found, then do not continue

      when no_data_found then

        ax_pkg.AppendString_P(pvMessage,'No recipient email found for patient ' || pRecipientPatient,' ',ax_pkg.MSG_WARNING,pParams);

        pvSuccess := false;

    end;    

    

    -- Add the Contact Note

    if pvSuccess and NOT (trim(vPtContRow."NoteCode") is null OR length(trim(vPtContRow."NoteCode")) = 0) then

      vNoteParams."Action" := ax_note_pkg.NOTE_ADD_ALWAYS;

      vPtContRow."Note" := nvl(vEmailParams."TextMessage",vEmailParams."HTMLMessage");

      ax_note_pkg.ContactNote_P(vNoteSuccess,vNoteMessage,pRecipientPatient,vPtContRow,vNoteParams,vParams);

      

      if not vNoteSuccess then

        raise exAddNoteFailed;

      end if;

    elsif not pvSuccess and NOT (trim(vPtContRow."NoteCode") is null OR length(trim(vPtContRow."NoteCode")) = 0) then

      vNoteParams."Action" := ax_note_pkg.NOTE_ADD_ALWAYS;

      vPtContRow."Note" := 'Patient was sent a Message, but there was an error sending the notification email. The Patient was NOT notified.';

      ax_note_pkg.ContactNote_P(vNoteSuccess,vNoteMessage,pRecipientPatient,vPtContRow,vNoteParams,vParams);

      commit;

    end if;

  exception

    when exAddNoteFailed then

      ax_pkg.AppendString_P(pvMessage,'Email sent, but Adding Contact Note Failed: ' || vNoteMessage,' ',ax_pkg.MSG_WARNING,pParams); 

  end SendPatientNewMessageEmail_P;

  

  

  -- Send Notification Email to Patient that they have a new axiUm message

    -- overload

  PROCEDURE sendpatientnewmessageemail_p(IN precipientpatient numeric, IN pemailparams temailparams DEFAULT ax_email_pkg.ax_email_params, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vSuccess boolean;

    vMessage  VARCHAR2(4000);

  begin

    SendPatientNewMessageEmail_P(vSuccess,vMessage,pRecipientPatient,pEmailParams,pParams);

    if not vSuccess then

      raise_application_error(-20000, vMessage);

    end if;    

  end SendPatientNewMessageEmail_P;

  

  

END;
CREATE OR REPLACE PACKAGE BODY ax_forms_pkg IS



  -- returns information about this package, or its procedures

  PROCEDURE help(IN pobjectname character varying DEFAULT NULL::character varying) IS

    vReturn CLOB;

  begin

    -- Writes the help to the DBMS_OUTPUT

	-- AX-39259

    vReturn := ax_pkg.Help_F('AX_FORMS_PKG',pObjectName);

  end Help;

  



  -- Delete a comment 2 record by ID or Code, and create the proper audit trail, but only if it exists

  PROCEDURE deletecomment2_p(IN pcomment2row comment2, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vAuto comment2."Auto"%type;

    vAudit comment2."Audit"%type;

    vAuditHisRow audithis%rowtype;

    exInfoNotProvided exception;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    

    -- Check to see if the record exists, if not raise an error

    if pComment2Row."Type" is not null and pComment2Row."Code" is not null then

      select "Auto" into vAuto from comment2 where "Type" = pComment2Row."Type" and "Code" = pComment2Row."Code" and "Deleted" = 0 and rownum=1;

    elsif pComment2Row."Auto" is not null then

      select "Auto" into vAuto from comment2 where "Auto" = pComment2Row."Auto" and "Deleted" = 0;

    else

      raise exInfoNotProvided;

    end if;

    

    -- create audit history, if needed

    if pComment2Row."Audit" is null then    

      vAuditHisRow."TableName" := 'COMMENT2';

      vAuditHisRow."HistoryType" := ax_pkg.AUDIT_DELETE; 

      ax_pkg.CreateAuditHis_P(vAuditHisRow,vParams);

      vAudit := vAuditHisRow."Audit";

    else

      vAudit := pComment2Row."Audit";

    end if;

    

    -- delete comment2

    if pComment2Row."Type" is not null and pComment2Row."Code" is not null then

      update comment2 set "Deleted" = '1', "Audit" = vAudit where "Type" = pComment2Row."Type" and "Code" = pComment2Row."Code" and "Deleted" = 0;

    else

      update comment2 set "Deleted" = '1', "Audit" = vAudit where "Auto" = vAuto and "Deleted" = 0;

    end if;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' comment2 rows deleted.',vParams);

    

  exception 

    when exInfoNotProvided then

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_ERROR,'Not enough information provided to delete comment2 record.',vParams);

    when no_data_found then

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_WARNING,'No comment2 record found to delete.',vParams);

  end DeleteComment2_P;

  



  -- Return the Text for an Anwer Type

  FUNCTION getanswertypedesc_f(panstype numeric) RETURN character varying IS

  begin

    return ax_pkg.GetAnswerType_F(pAnsType);

  end GetAnswerTypeDesc_F;

  

  

  -- Return a Form Answer by RefCode

  FUNCTION getformanswer_f(INOUT pvsuccess boolean, INOUT pvmessage character varying, ppatient numeric, pform character, prefcode character varying, panstype numeric DEFAULT NULL::numeric, ppform numeric DEFAULT NULL::numeric, ppage numeric DEFAULT NULL::numeric, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, ponlyapproved numeric DEFAULT 1) RETURN character varying IS  

    vAnsType fitem."AnsType"%type;

    vAnsList fitem."AnsList"%type;

    vPItem pitem."PItem"%type;

    vExists number;

    vReturn  VARCHAR2(4000);

    vPForm number;

    exNoRefCode exception;

    exNoForm exception;

    exNoQuestion exception;

    exTypeMismatch exception;

    exNotSupported exception;

    pragma autonomous_transaction; -- This is to avoid mutating table errors when used from triggers.

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    pvSuccess := false;

    -- Cannot proceed unless there is a pRefCode

    if pRefCode is null then

      raise exNoRefCode;

    end if;

    -- Make sure we know what Instance of the Form to look at

    if pPForm is null then

      begin

        select 

          max("PForm") into vPForm 

        from pform 

        where 

          "FormCode" = pForm and 

          "Patient" = pPatient and

          "Inactive" = 0

        order by 

          "CreatedDate" desc

          --"LastStartDateTime" desc -- added in 6.00

        ;

      exception

        when no_data_found then

          -- Form does not exist

          raise exNoForm;

      end;

    else

      vPForm := pPForm;

    end if;

    -- Make sure we know what the answer type is

    if pAnsType is null then

      begin

        select 

          "AnsType",

          "AnsList"

        into 

          vAnsType,

          vAnsList

        from fitem

        where

          "FormCode" = pForm and

          trim(upper("Code")) = trim(upper(pRefCode)) and

          (pPage is null or "Page" = pPage) and

          "Deleted" = 0;

      exception

        when no_data_found then

          raise exNoQuestion;

      end;

    elsif vParams."VerifyLevel" >= ax_pkg.VERIFY_ALL then

      -- make sure the answer type matches the answer type from the form

      begin

        select 

          "AnsType",

          "AnsList"

        into 

          vAnsType,

          vAnsList

        from fitem

        where

          "FormCode" = pForm and

          trim(upper("Code")) = trim(upper(pRefCode)) and

          (pPage is null or "Page" = pPage) and

          "Deleted" = 0;

      exception

        when no_data_found then

          raise exNoQuestion;

      end;

      if vAnsType <> pAnsType then

        raise exTypeMismatch;      

      end if;    

    else

      vAnsType := pAnsType;

    end if;

    

    -- Return the answer, based on vAnsType

    if vAnsType = ANSWER_YES_NO then

      select

        decode("AnsYes",0,'No',1,'Yes',-1,'Unanswered',2,'Do not know') into vReturn

      from pitem A

      left outer join fitem Q on Q."FItem" = A."FItem"

      where

        A."PForm" = vPForm and

        ( 

          pOnlyApproved = 0 or

          (

            A."AppUser" is not null and

            A."AppUser" > 0

          )

        ) and

        A."AnsType" = vAnsType and

        Q."FormCode" = pForm and

        (pPage is null or Q."Page" = pPage) and

        A."Patient" = pPatient and

        Q."Deleted" = 0 and

        trim(upper(Q."Code")) = trim(upper(pRefCode)) and

        A."Status" = 0;           

    elsif vAnsType = ANSWER_TEXT then

      select

        "AnsText" into vReturn

      from pitem A

      left outer join fitem Q on Q."FItem" = A."FItem"

      where

        A."PForm" = vPForm and

        ( 

          pOnlyApproved = 0 or

          (

            A."AppUser" is not null and

            A."AppUser" > 0

          )

        ) and

        A."AnsType" = vAnsType and

        Q."FormCode" = pForm and

        (pPage is null or Q."Page" = pPage) and

        A."Patient" = pPatient and

        Q."Deleted" = 0 and

        trim(upper(Q."Code")) = trim(upper(pRefCode)) and

        A."Status" = 0;    

    elsif vAnsType = ANSWER_NUMBER then

      select

        "AnsText" into vReturn

      from pitem A

      left outer join fitem Q on Q."FItem" = A."FItem"

      where

        A."PForm" = vPForm and

        ( 

          pOnlyApproved = 0 or

          (

            A."AppUser" is not null and

            A."AppUser" > 0

          )

        ) and

        A."AnsType" = vAnsType and

        Q."FormCode" = pForm and

        (pPage is null or Q."Page" = pPage) and

        A."Patient" = pPatient and

        Q."Deleted" = 0 and

        trim(upper(Q."Code")) = trim(upper(pRefCode)) and

        A."Status" = 0;       

    elsif vAnsType = ANSWER_LIST then

      select

        A."AnsListDesc" into vReturn

      from pitem A

      left outer join fitem Q on Q."FItem" = A."FItem"

      where

        A."PForm" = vPForm and

        ( 

          pOnlyApproved = 0 or

          (

            A."AppUser" is not null and

            A."AppUser" > 0

          )

        ) and

        A."AnsType" = vAnsType and

        Q."FormCode" = pForm and

        (pPage is null or Q."Page" = pPage) and

        A."Patient" = pPatient and

        Q."Deleted" = 0 and

        trim(upper(Q."Code")) = trim(upper(pRefCode)) and

        A."Status" = 0;        

    elsif vAnsType = ANSWER_DATE then

      select

        to_char(A."AnsDate",ax_pkg.DATE_FORMAT) into vReturn -- No Time Element

      from pitem A

      left outer join fitem Q on Q."FItem" = A."FItem"

      where

        A."PForm" = vPForm and

        ( 

          pOnlyApproved = 0 or

          (

            A."AppUser" is not null and

            A."AppUser" > 0

          )

        ) and

        A."AnsType" = vAnsType and

        Q."FormCode" = pForm and

        (pPage is null or Q."Page" = pPage) and

        A."Patient" = pPatient and

        Q."Deleted" = 0 and

        trim(upper(Q."Code")) = trim(upper(pRefCode)) and

        A."Status" = 0;      

    elsif vAnsType = ANSWER_LONG_TEXT then

      select

        A."AnsText",A."PItem" into vReturn,vPItem

      from pitem A

      left outer join fitem Q on Q."FItem" = A."FItem"

      where

        A."PForm" = vPForm and

        ( 

          pOnlyApproved = 0 or

          (

            A."AppUser" is not null and

            A."AppUser" > 0

          )

        ) and

        A."AnsType" = vAnsType and

        Q."FormCode" = pForm and

        (pPage is null or Q."Page" = pPage) and

        A."Patient" = pPatient and

        Q."Deleted" = 0 and

        trim(upper(Q."Code")) = trim(upper(pRefCode)) and

        A."Status" = 0;   

      if vParams."VerifyLevel" >= ax_pkg.VERIFY_ALL then

        begin

          -- check to see if there is more text in NoteOvr

          select 1 into vExists 

          from noteovr

          where

            "Patient" = pPatient and

            "Deleted" = 0 and

            "Type" = 1 and

            "ParentId" = vPItem and

            rownum = 1;

          ax_pkg.AppendString_P(pvMessage,'Only first 4000 characters shown.',' ',ax_pkg.MSG_WARNING,vParams);  

        exception

          when no_data_found then

            null; -- nothing to report

        end;

      end if;

    elsif vAnsType = ANSWER_IMAGE then

     raise exNotSupported;

    elsif vAnsType = ANSWER_CALCULATED then

      select

        A."AnsText" into vReturn

      from pitem A

      left outer join fitem Q on Q."FItem" = A."FItem"

      where

        A."PForm" = vPForm and

        ( 

          pOnlyApproved = 0 or

          (

            A."AppUser" is not null and

            A."AppUser" > 0

          )

        ) and

        A."AnsType" = vAnsType and

        Q."FormCode" = pForm and

        (pPage is null or Q."Page" = pPage) and

        A."Patient" = pPatient and

        Q."Deleted" = 0 and

        trim(upper(Q."Code")) = trim(upper(pRefCode)) and

        A."Status" = 0;      

    elsif vAnsType = ANSWER_ATTACHMENT then

      raise exNotSupported;    

    elsif vAnsType = ANSWER_SPREADSHEET then

      raise exNotSupported;

    end if;

    

    pvSuccess := true;

    return trim(vReturn);

  exception

    when no_data_found then

      ax_pkg.AppendString_P(pvMessage,'PItem Not found.',' ',ax_pkg.MSG_WARNING,vParams); 

      return null;

    when exNotSupported then

      ax_pkg.AppendString_P(pvMessage,GetAnswerTypeDesc_F(vAnsType) || 'Spreadsheet type answers not suppored by this function.',' ',ax_pkg.MSG_ERROR,vParams); 

      return null;    

    when exNoRefCode then

      ax_pkg.AppendString_P(pvMessage,'No Reference Code Provided.',' ',ax_pkg.MSG_ERROR,vParams); 

      return null;

    when exNoForm then

      ax_pkg.AppendString_P(pvMessage,'PForm Not found.',' ',ax_pkg.MSG_WARNING,vParams); 

      return null;

    when exNoQuestion then

      ax_pkg.AppendString_P(pvMessage,'FItem Not found.',' ',ax_pkg.MSG_ERROR,vParams); 

      return null;

    when exTypeMismatch then

      ax_pkg.AppendString_P(pvMessage,'Provided Answer Type does not match fitem."AnsType".',' ',ax_pkg.MSG_ERROR,vParams); 

      return null;

  end GetFormAnswer_F;

  

  

  -- Overload

  FUNCTION getformanswer_f(ppatient numeric, pform character, prefcode character varying, panstype numeric DEFAULT NULL::numeric, ppform numeric DEFAULT NULL::numeric, ppage numeric DEFAULT NULL::numeric, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, ponlyapproved numeric DEFAULT 1) RETURN character varying IS

    vSuccess boolean;

    vMessage  VARCHAR2(4000);

  begin

    return GetFormAnswer_F(vSuccess,vMessage,pPatient,pForm,pRefCode,pAnsType,pPForm,pPage,pParams,pOnlyApproved);

  end GetFormAnswer_F;

  

  

  -- Returns a comma delimited list of Reference Codes which have been answered, 

    -- out of a comma delimited list of total Reference Codes provided

    -- For YesNo answer types, only the Yes answers will be included

  FUNCTION getquestionsanswered_f(INOUT pvsuccess boolean, INOUT pvmessage character varying, ppatient numeric, pform character, prefcodes character varying, panstype numeric DEFAULT NULL::numeric, ppform numeric DEFAULT NULL::numeric, ppage numeric DEFAULT NULL::numeric, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN character varying IS

    cursor curQuestions(pCurPForm in number) is

      select Q."Code" 

      from pitem A

      left outer join fitem Q on Q."FItem" = A."FItem"

      where

        A."PForm" = pCurPForm and

        A."AppUser" is not null and

        A."AppUser" > 0 and

        (pPage is null or Q."Page" = pPage) and

        Q."FormCode" = pForm and

        A."Patient" = pPatient and

        Q."Deleted" = 0 and        

        trim(upper(',' || pRefCodes || ',')) like trim(upper('%,' || Q."Code" || ',%')) and

        A."Status" = 0 and

        (pAnsType is null or Q."AnsType" = pAnsType) and

        (

          (A."AnsType" = ANSWER_YES_NO and A."AnsYes" = 1) or 

          (A."AnsType" = ANSWER_DATE and A."AnsDate" is not null) or

          (A."AnsType" = ANSWER_LIST and A."AnsList" is not null) or

          (trim(A."AnsText") is not null)

        );

    vReturnString  VARCHAR2(4000) := null;

    vPForm number;

    exNoRefCode exception;

    exNoForm exception;

    pragma autonomous_transaction; -- This is to avoid mutating table errors when used from triggers.

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    pvSuccess := false;

    -- Cannot proceed unless there is a pRefCode

    if pRefCodes is null then

      raise exNoRefCode;

    end if;

    -- Make sure we know what Instance of the Form to look at

    if pPForm is null then

      begin

        select 

          max("PForm") into vPForm 

        from pform 

        where 

          "FormCode" = pForm and 

          "Patient" = pPatient and

          "Inactive" = 0

        order by 

          "CreatedDate" desc

          --"LastStartDateTime" desc -- added in 6.00

        ;

      exception

        when no_data_found then

          -- Form does not exist

          raise exNoForm;

      end;

    else

      vPForm := pPForm;

    end if;

    

    -- Loop through cursor to find out which Reference Codes have been answered

    for cQuestion in curQuestions(vPForm) loop

      ax_pkg.AppendString_P(vReturnString,cQuestion."Code",',');

    end loop;    

    

    pvSuccess := true;  

    return vReturnString;

  exception

    when exNoRefCode then

      ax_pkg.AppendString_P(pvMessage,'No Reference Code Provided.',' ',ax_pkg.MSG_WARNING,vParams); 

      return null;

    when exNoForm then

      ax_pkg.AppendString_P(pvMessage,'PForm Not found.',' ',ax_pkg.MSG_WARNING,vParams); 

      return null;    

  end GetQuestionsAnswered_F;

  

  

  -- Overload

  FUNCTION getquestionsanswered_f(ppatient numeric, pform character, prefcodes character varying, panstype numeric DEFAULT NULL::numeric, ppform numeric DEFAULT NULL::numeric, ppage numeric DEFAULT NULL::numeric, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN character varying IS

    vSuccess boolean;

    vMessage  VARCHAR2(4000);

  begin

    return GetQuestionsAnswered_F(vSuccess,vMessage,pPatient,pForm,pRefCodes,pAnsType,pPForm,pPage,pParams);

  end GetQuestionsAnswered_F;

  

END;
CREATE OR REPLACE PACKAGE BODY ax_lang_pkg IS



  -- returns information about this package, or its procedures

  PROCEDURE help(IN pobjectname character varying DEFAULT NULL::character varying) IS

    vReturn CLOB;

  begin

    -- Writes the help to the DBMS_OUTPUT

	-- AX-39259

    vReturn := ax_pkg.Help_F('AX_LANG_PKG',pObjectName);

  end Help;



END;
CREATE OR REPLACE PACKAGE BODY ax_note_pkg IS



  -- returns information about this package, or its procedures

  PROCEDURE help(IN pobjectname character varying DEFAULT NULL::character varying) IS

    vReturn CLOB;

  begin

    -- Writes the help to the DBMS_OUTPUT

	-- AX-39259

    vReturn := ax_pkg.Help_F('AX_NOTE_PKG',pObjectName);

  end Help;

  



  PROCEDURE stickynote_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, INOUT pvappnoterow ap_note, IN pnoteparams tnoteparams DEFAULT ax_note_pkg.ax_note_params, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vParams ax_pkg.tParams := pParams;

    vMatchText number := 0;

    vMatchUser number := 0;

    vMatchStationId number := 0;

    vMatchDate number := 0;

    

    vExistingRow ap_note%rowtype;

    vLen number;     

    

    -- Used for various note types

    vAppId ap_note."AP_NOTE_AppId"%Type;

    vNotePatientId ap_note."AP_NOTE_PatientId"%Type;

     

    -- Dates to display note - days since jan 1, 1901

    vDate1 number;

    vDate2 number;

    

    exVersionMismatch exception;

  begin

    pvSuccess := false;

    -- Error checking

    if vParams."VerifyLevel" >= ax_pkg.VERIFY_ERRORS then

      if not ax_pkg.VersionMatch_F(AXIUM_VERSION) then

        raise exVersionMismatch;

      end if;  

    end if;

  

    -- Set Defaults

    ax_pkg.InitializeParams_P(vParams);

    pvAppNoteRow."AP_NOTE_AppId" := nvl(pvAppNoteRow."AP_NOTE_AppId",0); -- saved in appid for types other than 3

    pvAppNoteRow."AP_NOTE_Type" := nvl(pvAppNoteRow."AP_NOTE_Type",STICKY_NOTE_PATIENT);   -- 3 = Patient 

    pvAppNoteRow."AP_NOTE_Flag" := nvl(pvAppNoteRow."AP_NOTE_Flag",STICKY_EVENT_SELECT_PATIENT);  -- 32 = When select patient

    pvAppNoteRow."AP_NOTE_Treatment" := nvl(pvAppNoteRow."AP_NOTE_Treatment",0); 

    if pNoteParams."MatchText" and pNoteParams."Action" not in(NOTE_APPEND_START,NOTE_APPEND_END) then

      vMatchText := 1;

    end if;

    if pNoteParams."MatchUser" or pNoteParams."Action" = NOTE_DELETE_SAME_USER then

      vMatchUser := 1;

    end if;

    if pNoteParams."MatchStationId" then

      vMatchStationId := 1;

    end if; 

    if pNoteParams."MatchDate" then

      vMatchDate := 1;

    end if;    

  

    -- see if the sticky note already exists

    if pNoteParams."Action" <> NOTE_ADD_ALWAYS then

      begin

        -- only grab the most recent record

        select * into vExistingRow from (

          select

            *

          from

             ap_note note

          where

            (

              note."AP_NOTE_AppId" = pvAppNoteRow."AP_NOTE_AppId" or 

              note."AP_NOTE_AppId" = pPatient or

              (

                note."AP_NOTE_PatientId" = pPatient and

                note."AP_NOTE_Type" not in (1, 2, 3, 13, 16)

              )

            ) and

            note."AP_NOTE_Type" = pvAppNoteRow."AP_NOTE_Type" and

            note."AP_NOTE_Flag" = pvAppNoteRow."AP_NOTE_Flag" and

            note."AP_NOTE_Treatment" = pvAppNoteRow."AP_NOTE_Treatment" and

            (

              vMatchText = 0 or

              (

                trim(note."AP_NOTE_Text") = trim(pvAppNoteRow."AP_NOTE_Text") or

                (

                  (trim(note."AP_NOTE_Text") is null OR length(trim(note."AP_NOTE_Text")) = 0) and 

                  (trim(pvAppNoteRow."AP_NOTE_Text") is null OR length(trim(pvAppNoteRow."AP_NOTE_Text")) = 0)

                )

              )

            ) and

            (

              vMatchUser = 0 or 

              (

                note."CreationUser" = nvl(pvAppNoteRow."CreationUser",vParams."User") and

                note."ModifiedUser" = nvl(pvAppNoteRow."ModifiedUser",vParams."User")

              )

            ) and

            (

              vMatchStationId = 0 or 

              note."StationId" = nvl(pvAppNoteRow."StationId",vParams."StationId")

            ) and

            (

              vMatchDate = 0 or 

              trunc(note."ModifiedDateTime") = trunc(pvAppNoteRow."ModifiedDateTime")

            )                 

          order by

          -- if axiUm Version >= 5.11

            "ModifiedDateTime" desc

          -- else

          -- "AP_NOTE_LTime" desc

        ) where rownum = 1;

      exception

        when no_data_found then

          ax_pkg.AppendString_P(pvMessage,'No matching sticky note!',true,' ',ax_pkg.MSG_ERROR,vParams);

          vExistingRow."AP_NOTE_AutoDec" := 0;

      end; -- check if note exists

    else

      vExistingRow."AP_NOTE_AutoDec" := 0;

    end if;



       

    -- See if there is room to append

    if pNoteParams."Action" in (NOTE_APPEND_START,NOTE_APPEND_END) then

       

      ax_pkg.AppendString_P(pvMessage,'Appending note',true,' ',ax_pkg.MSG_ERROR,vParams);

       

      vLen := length(pvAppNoteRow."AP_NOTE_Text" || ' ' || vExistingRow."AP_NOTE_Text");

       

      if vLen > ax_pkg.TypeLength_F('ap_note','AP_NOTE_Text') then

        -- New text would not fit on existing note, so add a new one

        vExistingRow := null;

        vExistingRow."AP_NOTE_AutoDec" := 0;

      end if;

    end if;      

    

    -- Add New Sticky Note

    if 

      pNoteParams."Action" in (

        1,

        NOTE_ADD_IF_NEW,

        NOTE_ADD_REPLACE,

        NOTE_APPEND_START,

        NOTE_APPEND_END,

        NOTE_ADD_ALWAYS

      ) and 

      vExistingRow."AP_NOTE_AutoDec" = 0 

    then

      -- get new note id

      select ap_note_ap_note_autodec_seq.nextval into vExistingRow."AP_NOTE_AutoDec" from dual;

       

      -- set date values

      if pNoteParams."DisplayDate" is not null then

        vDate1 := to_char(trunc(pNoteParams."DisplayDate")-to_date('01/01/1901','mm/dd/yyyy'));

      else

        vDate1 := nvl(pvAppNoteRow."AP_NOTE_Date1",0);

      end if;

      if pNoteParams."ExpireDate" is not null then

        vDate2 := to_char(trunc(pNoteParams."ExpireDate")-to_date('01/01/1901','mm/dd/yyyy'));

      else

        vDate2 := nvl(pvAppNoteRow."AP_NOTE_Date2",0);

      end if;

       

      -- Patient Note types

      if pvAppNoteRow."AP_NOTE_Type" = STICKY_NOTE_PATIENT then

        vAppId := pPatient;

        vNotePatientId := 0;

      -- Patient = 0 types

      elsif pvAppNoteRow."AP_NOTE_Type" in (

        STICKY_NOTE_SCHEDULER,

        STICKY_NOTE_ROLODEX,

        STICKY_NOTE_BOOK,

        STICKY_NOTE_AVAILABILITY

      ) then

        vAppId := pvAppNoteRow."AP_NOTE_AppId";

        vNotePatientId := 0;

      else

        vAppId := pvAppNoteRow."AP_NOTE_AppId";

        vNotePatientId := pPatient;      

      end if;

 

      -- if axiUm Version >= 5.11

        -- AddDateTime, ModifiedDateTime

      insert into ap_note

        values (

          vExistingRow."AP_NOTE_AutoDec",   -- AP_NOTE_AutoDec          

          vAppId,          -- AP_NOTE_AppId

          pvAppNoteRow."AP_NOTE_Type",       -- AP_NOTE_Type

          vNotePatientId,  -- AP_NOTE_PatientId

          nvl(pvAppNoteRow."AddDateTime",sysdate),        -- AddDateTime          

          sysdate,         -- ModifiedDateTime

          pvAppNoteRow."AP_NOTE_Flag",       -- AP_NOTE_Flag

          vDate1,          -- AP_NOTE_Date1

          vDate2,          -- AP_NOTE_Date2

          nvl(pvAppNoteRow."AP_NOTE_PAmount",0),               -- AP_NOTE_PAmount

          nvl(pvAppNoteRow."AP_NOTE_IAmount",0),               -- AP_NOTE_IAmount

          pvAppNoteRow."AP_NOTE_Text",       -- AP_NOTE_Text

          nvl(pvAppNoteRow."AP_NOTE_Treatment",0),  -- AP_NOTE_Treatment

          nvl(pvAppNoteRow."CreationUser",vParams."User"),  -- CreationUser

          nvl(pvAppNoteRow."ModifiedUser",vParams."User"),  -- ModifiedUser

          nvl(pvAppNoteRow."StationId",vParams."StationId") -- StationId

        );

               

      --else

      /*

        -- AP_NOTE_FTime, AP_NOTE_LTime

      

      insert into ap_note

        values (

          vExistingRow."AP_NOTE_AutoDec",   -- AP_NOTE_AutoDec          

          vAppId,          -- AP_NOTE_AppId

          pvAppNoteRow."AP_NOTE_Type",       -- AP_NOTE_Type

          vNotePatientId,  -- AP_NOTE_PatientId

          to_char(trunc(sysdate)-to_date('01/01/1970','mm/dd/yyyy')) * 86400,         -- AP_NOTE_FTime          

          to_char(trunc(sysdate)-to_date('01/01/1970','mm/dd/yyyy')) * 86400,         -- AP_NOTE_LTime

          pvAppNoteRow."AP_NOTE_Flag",       -- AP_NOTE_Flag

          vDate1,          -- AP_NOTE_Date1

          vDate2,          -- AP_NOTE_Date2

          nvl(pvAppNoteRow."AP_NOTE_PAmount",0),               -- AP_NOTE_PAmount

          nvl(pvAppNoteRow."AP_NOTE_IAmount",0),               -- AP_NOTE_IAmount

          pvAppNoteRow."AP_NOTE_Text",       -- AP_NOTE_Text

          nvl(pvAppNoteRow."AP_NOTE_Treatment",0),  -- AP_NOTE_Treatment

          nvl(pvAppNoteRow."CreationUser",vParams."User"),           -- CreationUser

          nvl(pvAppNoteRow."ModifiedUser",vParams."User"),           -- ModifiedUser

          nvl(pvAppNoteRow."StationId",vParams."StationId")      -- StationId

        );

      */

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ap_note rows inserted.',vParams);

 

    -- Replace/Append Existing Note

    elsif pNoteParams."Action" in (NOTE_ADD_REPLACE,NOTE_APPEND_START,NOTE_APPEND_END) then

 

      -- Append to Beginning

      if pNoteParams."Action" = NOTE_APPEND_START then

        vExistingRow."AP_NOTE_Text" := substr(pvAppNoteRow."AP_NOTE_Text" || ' ' || vExistingRow."AP_NOTE_Text",1,ax_pkg.TypeLength_F('ap_note','AP_NOTE_Text'));

       

      -- Append to End

      elsif pNoteParams."Action" = NOTE_APPEND_END then

        vExistingRow."AP_NOTE_Text" := substr(vExistingRow."AP_NOTE_Text" || ' ' || pvAppNoteRow."AP_NOTE_Text",1,ax_pkg.TypeLength_F('ap_note','AP_NOTE_Text'));

      else

        vExistingRow."AP_NOTE_Text" := pvAppNoteRow."AP_NOTE_Text";

      end if;

       

      -- Update note with new text

       

      -- if axiUm Version >= 5.11

        update ap_note set

          "ModifiedDateTime" = sysdate,        

          "AP_NOTE_Date1" = nvl(pvAppNoteRow."AP_NOTE_Date1",vExistingRow."AP_NOTE_Date1"),

          "AP_NOTE_Date2" = nvl(pvAppNoteRow."AP_NOTE_Date2",vExistingRow."AP_NOTE_Date2"),

          "AP_NOTE_PAmount" = nvl(pvAppNoteRow."AP_NOTE_PAmount",vExistingRow."AP_NOTE_PAmount"),

          "AP_NOTE_IAmount" = nvl(pvAppNoteRow."AP_NOTE_IAmount",vExistingRow."AP_NOTE_IAmount"),        

          "AP_NOTE_Text" = vExistingRow."AP_NOTE_Text",         

          "ModifiedUser" = nvl(pvAppNoteRow."ModifiedUser",vParams."User"),          

          "StationId" = nvl(pvAppNoteRow."StationId",vParams."StationId")

        where

          "AP_NOTE_AutoDec" = vExistingRow."AP_NOTE_AutoDec";    

      -- else

      /*

        update ap_note set

          "AP_NOTE_LTime" = to_char(trunc(sysdate)-to_date('01/01/1970','mm/dd/yyyy')) * 86400,        

          "AP_NOTE_Date1" = nvl(ppvAppNoteRow."AP_NOTE_Date1",vExistingRow."AP_NOTE_Date1"),

          "AP_NOTE_Date2" = nvl(ppvAppNoteRow."AP_NOTE_Date2",vExistingRow."AP_NOTE_Date2"),

          "AP_NOTE_PAmount" = nvl(ppvAppNoteRow."AP_NOTE_PAmount",vExistingRow."AP_NOTE_PAmount"),

          "AP_NOTE_IAmount" = nvl(ppvAppNoteRow."AP_NOTE_IAmount",vExistingRow."AP_NOTE_IAmount"),        

          "AP_NOTE_Text" = vExistingRow."AP_NOTE_Text",         

          "ModifiedUser" = nvl(pvAppNoteRow."ModifiedUser",vParams."User"),          

          "StationId" = nvl(pvAppNoteRow."StationId",vParams."StationId")        

        where

          "AP_NOTE_AutoDec" = vExistingRow."AP_NOTE_AutoDec";    

      */

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ap_note rows updated.',vParams);

    -- Delete Note

    elsif pNoteParams."Action" in (NOTE_DELETE,NOTE_DELETE_SAME_USER) and vExistingRow."AP_NOTE_AutoDec" <> 0 then

      -- Remove Sticky Note

      delete from ap_note

      where

        "AP_NOTE_AutoDec" = vExistingRow."AP_NOTE_AutoDec";

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' rows deleted from ap_note.',vParams);

    end if; -- check action 

    pvSuccess := true;

  exception 

    when exVersionMismatch then

      ax_pkg.AppendString_P(pvMessage,'AX_NOTE_PKG version mismatch',true,' ',ax_pkg.MSG_ERROR,vParams);

  end StickyNote_P;

  

  

  PROCEDURE stickynote_p(IN ppatient numeric, INOUT pvappnoterow ap_note, IN pnoteparams tnoteparams DEFAULT ax_note_pkg.ax_note_params, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vSuccess boolean;

    vMessage  VARCHAR2(4000);

  begin

    StickyNote_P(vSuccess,vMessage,pPatient,pvAppNoteRow,pNoteParams,pParams);

    if not vSuccess then

      raise_application_error(-20000, vMessage);

    end if;

  end StickyNote_P;

  



  PROCEDURE contactnote_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, INOUT pvptcontrow ptcont, IN pnoteparams tnoteparams DEFAULT ax_note_pkg.ax_note_params, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vParams ax_pkg.tParams := pParams;

    vMatchText number := 0;

    vMatchUser number := 0;

    vMatchStationId number := 0;

    vMatchDate number := 0;

    vExists number;

    vExistingRow ptcont%rowtype;

    vLen number;

    vTime number;

    exVersionMismatch exception;

    exInvalidNoteCode exception;

  begin

    pvSuccess := false;

    -- Error checking

    if vParams."VerifyLevel" >= ax_pkg.VERIFY_ERRORS then

      if not ax_pkg.VersionMatch_F(AXIUM_VERSION) then

        raise exVersionMismatch;

      end if;  

    end if;

    if vParams."VerifyLevel" >= ax_pkg.VERIFY_ALL then

      if pvPtContRow."NoteCode" is not null then

        begin

          select 1 into vExists from notecode where "NoteCode" = pvPtContRow."NoteCode" and "Type" = 3;

        exception

          when no_data_found then

            raise exInvalidNoteCode;

        end;

      end if;  

    end if;      

    -- Set Defaults

    ax_pkg.InitializeParams_P(vParams);  

    if pNoteParams."MatchText" and pNoteParams."Action" not in(NOTE_APPEND_START,NOTE_APPEND_END) then

      vMatchText := 1;

    end if;

    if pNoteParams."MatchUser" or pNoteParams."Action" = NOTE_DELETE_SAME_USER then

      vMatchUser := 1;

    end if;

    if pNoteParams."MatchStationId" then

      vMatchStationId := 1;

    end if;        

    if pNoteParams."MatchDate" then

      vMatchDate := 1;

    end if;    

  

    -- see if the note already exists

    if pNoteParams."Action" <> NOTE_ADD_ALWAYS then

      begin

        -- only grab the most recent record

       select * into vExistingRow from (

          select

            *

          from

            ptcont note

          where

            note."Patient" = pPatient and

            (

              trim(note."NoteCode") = trim(pvPtContRow."NoteCode") or

              (

                (trim(note."NoteCode") is null OR length(trim(note."NoteCode")) = 0) and

                (trim(pvPtContRow."NoteCode") is null OR length(trim(pvPtContRow."NoteCode")) = 0)

              )

            ) and      

            note."Deleted" = 0 and

            (



              vMatchText = 0 or

              trim(note."Note") = trim(pvPtContRow."Note")

            ) and

            (

              vMatchUser = 0 or 

              note."User" = nvl(pvPtContRow."User",vParams."User")

            ) and

            (

              vMatchStationId = 0 or 

              note."StationId" = nvl(pvPtContRow."StationId",vParams."StationId")

            ) and

            (

              vMatchDate = 0 or 

              trunc(note."Date") = trunc(pvPtContRow."Date")

            )     

          order by

            "Date" desc, "Time" desc

        ) where rownum = 1;

      exception

        when no_data_found then

          vExistingRow."Contact" := 0;

      end; -- check if note exists

    else

      vExistingRow."Contact" := 0;

    end if;

       

    -- set time value

    vTime := to_number(to_char(sysdate, 'HH24'))* 60 + to_number(to_char(sysdate, 'MI'));

       

    -- See if there is room to append

    if pNoteParams."Action" in (NOTE_APPEND_START,NOTE_APPEND_END) then

       

      vLen := length(pvPtContRow."Note" || ' ' || vExistingRow."Note");

       

      if vLen > ax_pkg.TypeLength_F('ptcont','Note') then

        -- New text would not fit on existing note, so add a new one

        vExistingRow := null;

        vExistingRow."Contact" := 0;

      end if;

    end if;

       

    -- Add New Note

    if pNoteParams."Action" in (NOTE_ADD_IF_NEW,NOTE_ADD_REPLACE,NOTE_APPEND_START,NOTE_APPEND_END,NOTE_ADD_ALWAYS) and vExistingRow."Contact" = 0 then

      -- get new note id

      select ptcont_contact_seq.nextval into vExistingRow."Contact" from dual;

 

      insert into ptcont

      values (

        vExistingRow."Contact",        -- Contact          

        pPatient,  -- Patient

        trunc(sysdate),  -- Date

        vTime,           -- Time

        nvl(pvPtContRow."User",vParams."User"),           -- User

        nvl(pvPtContRow."StationId",vParams."StationId"),      -- StationId

        pvPtContRow."Note",       -- Note

        0,               -- Deleted

        nvl(pvPtContRow."NoteCode",' '),       -- NoteCode

        trunc(nvl(pNoteParams."DisplayDate",sysdate)), -- ContactDate

        to_char(nvl(pNoteParams."DisplayDate",sysdate),'sssss')/60,  -- ContactTime

        vParams."User"            -- ContactUser

      );

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptcont rows inserted.',vParams);

 

    -- Replace/Append Existing Note

    elsif pNoteParams."Action" in (NOTE_ADD_REPLACE,NOTE_APPEND_START,NOTE_APPEND_END) then

        

      -- Append to Beginning

      if pNoteParams."Action" = NOTE_APPEND_START then

        vExistingRow."Note" := substr(pvPtContRow."Note" || ' ' || vExistingRow."Note",1,ax_pkg.TypeLength_F('ptcont','Note'));

       

      -- Append to End

      elsif pNoteParams."Action" = NOTE_APPEND_END then

        vExistingRow."Note" := substr(vExistingRow."Note" || ' ' || pvPtContRow."Note",1,ax_pkg.TypeLength_F('ptcont','Note'));

      else

        vExistingRow."Note" := pvPtContRow."Note";

      end if;

       

      -- Update note with new text

       

      update ptcont set

        "Date" = nvl(pvPtContRow."Date",vExistingRow."Date"),

        "Time" = nvl(pvPtContRow."Time",vExistingRow."Time"),

        "User" = nvl(pvPtContRow."User",vParams."User"),

        "StationId" = nvl(pvPtContRow."StationId",vParams."StationId"),

        "Note" = vExistingRow."Note",

        "Deleted" = nvl(pvPtContRow."Deleted",vExistingRow."Deleted"),

        "ContactDate" = nvl(pvPtContRow."ContactDate",vExistingRow."ContactDate"),

        "ContactTime" = nvl(pvPtContRow."ContactTime",vExistingRow."ContactTime")

      where

        "Contact" = vExistingRow."Contact";

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptcont rows updated.',vParams);

 

    -- Delete Note

    elsif pNoteParams."Action" in (NOTE_DELETE,NOTE_DELETE_SAME_USER) and vExistingRow."Contact" <> 0 then

      -- Remove Note

      update

        ptcont        

      set

        "Deleted" = 1

      where

        "Contact" = vExistingRow."Contact";

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptcont rows updated.',vParams);

    end if; -- check action 

    pvSuccess := true;

  exception 

    when exInvalidNoteCode then

      ax_pkg.AppendString_P(pvMessage,pvPtContRow."NoteCode" || ' is an invalid note code',true,' ',ax_pkg.MSG_ERROR,vParams);

    when exVersionMismatch then

      ax_pkg.AppendString_P(pvMessage,'AX_NOTE_PKG version mismatch',true,' ',ax_pkg.MSG_ERROR,vParams);    

  end ContactNote_P;





  PROCEDURE contactnote_p(IN ppatient numeric, INOUT pvptcontrow ptcont, IN pnoteparams tnoteparams DEFAULT ax_note_pkg.ax_note_params, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vSuccess boolean;

    vMessage  VARCHAR2(4000);

  begin

    ContactNote_P(vSuccess,vMessage,pPatient,pvPtContRow,pNoteParams,pParams);

    if not vSuccess then

      raise_application_error(-20000, vMessage);

    end if;

  end ContactNote_P;





  PROCEDURE transactionnote_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, INOUT pvptnoterow ptnote, IN pnoteparams tnoteparams DEFAULT ax_note_pkg.ax_note_params, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vParams ax_pkg.tParams := pParams;

    vMatchText number := 0;

    vMatchUser number := 0;

    vMatchStationId number := 0;

    vMatchDate number := 0;

    vExists number;

    vExistingRow ptnote%rowtype;

    vLen number;

    vTime number;

    exVersionMismatch exception;

    exInvalidNoteCode exception;

  begin

    pvSuccess := false;

    -- Error checking

    if vParams."VerifyLevel" >= ax_pkg.VERIFY_ERRORS then

      if not ax_pkg.VersionMatch_F(AXIUM_VERSION) then

        raise exVersionMismatch;

      end if;  

    end if;

    if vParams."VerifyLevel" >= ax_pkg.VERIFY_ALL then

      if pvPtNoteRow."NoteCode" is not null then

        begin

          select 1 into vExists from notecode where "NoteCode" = pvPtNoteRow."NoteCode" and "Type" = 0;

        exception

          when no_data_found then

            raise exInvalidNoteCode;

        end;

      end if;  

    end if;    

    -- Set Defaults

    ax_pkg.InitializeParams_P(vParams);  

    if pNoteParams."MatchText" and pNoteParams."Action" not in(NOTE_APPEND_START,NOTE_APPEND_END) then

      vMatchText := 1;

    end if;

    if pNoteParams."MatchUser" or pNoteParams."Action" = NOTE_DELETE_SAME_USER then

      vMatchUser := 1;

    end if;

    if pNoteParams."MatchStationId" then

      vMatchStationId := 1;

    end if;   

    if pNoteParams."MatchDate" then

      vMatchDate := 1;

    end if;    

    

    -- see if the note already exists

    if pNoteParams."Action" <> NOTE_ADD_ALWAYS then

      begin

        -- only grab the most recent record

        --select "PtNote","Text" into vPtNote,vCurrentNote from (

        select * into vExistingRow from (

          select

            *

          from

            ptnote note

          where

            note."Patient" = pvPtNoteRow."Patient" and

            note."NoteCode" = pvPtNoteRow."NoteCode" and    

            note."Deleted" = 0 and 

            (

              vMatchText = 0 or

              trim(note."Text") = trim(pvPtNoteRow."Text")

            ) and

            (

              vMatchUser = 0 or 

              note."User" = nvl(pvPtNoteRow."User",vParams."User")

            ) and

            (

              vMatchDate = 0 or 

              trunc(note."Date") = trunc(pvPtNoteRow."Date")

            )    

          order by

            "Date" desc, "EntryDate" desc

        ) where rownum = 1;

      exception

        when no_data_found then

          vExistingRow."PtNote" := 0;

      end; -- check if note exists

    else

      vExistingRow."PtNote" := 0;

    end if;

       

    -- set time value

    vTime := to_number(to_char(nvl(pNoteParams."DisplayDate",sysdate), 'HH24'))* 60 + to_number(to_char(nvl(pNoteParams."DisplayDate",sysdate), 'MI'));

       

    -- See if there is room to append

    if pNoteParams."Action" in (NOTE_APPEND_START,NOTE_APPEND_END) then

       

      vLen := length(pvPtNoteRow."Text" || ' ' || vExistingRow."Text");

       

      if vLen > ax_pkg.TypeLength_F('ptnote','Text') then

        -- New text would not fit on existing note, so add a new one

        vExistingRow := null;

        vExistingRow."PtNote" := 0;

      end if;

    end if;

       

    -- Add New Note

    if pNoteParams."Action" in (NOTE_ADD_IF_NEW,NOTE_ADD_REPLACE,NOTE_APPEND_START,NOTE_APPEND_END,NOTE_ADD_ALWAYS) and vExistingRow."PtNote" = 0 then

      -- get new note id

      select ptnote_ptnote_seq.nextval into vExistingRow."PtNote" from dual;

 

      insert into ptnote

      values (

        vExistingRow."PtNote",         -- PtNote

        pPatient,      -- Patient

        nvl(pvPtNoteRow."Date",sysdate),       -- Date

        nvl(pvPtNoteRow."User",vParams."User"),           -- User

        nvl(pNoteParams."DisplayDate",sysdate),         -- EntryDate

        nvl(pvPtNoteRow."NoteCode",' '),       -- NoteCode

        pvPtNoteRow."Text",       -- Text

        nvl(pvPtNoteRow."Deleted",0),               -- Deleted

        pvPtNoteRow."IsClaimNote"     -- IsClaimNote

      );

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptnote rows inserted.',vParams);

 

    -- Replace/Append Existing Note

    elsif pNoteParams."Action" in (NOTE_ADD_REPLACE,NOTE_APPEND_START,NOTE_APPEND_END) then

        

      -- Append to Beginning

      if pNoteParams."Action" = NOTE_APPEND_START then

        vExistingRow."Text" := substr(pvPtNoteRow."Text" || ' ' || vExistingRow."Text",1,ax_pkg.TypeLength_F('ptnote','Text'));

       

      -- Append to End

      elsif pNoteParams."Action" = NOTE_APPEND_END then

        vExistingRow."Text" := substr(vExistingRow."Text" || ' ' || pvPtNoteRow."Text",1,ax_pkg.TypeLength_F('ptnote','Text'));

      else

        vExistingRow."Text" := pvPtNoteRow."Text";

      end if;

       

      -- Update note with new text       

        update ptnote

        set

          "Date" = nvl(pvPtNoteRow."Date",vExistingRow."Date"),

          "User" = nvl(pvPtNoteRow."User",vParams."User"),

          "EntryDate" = nvl(pvPtNoteRow."EntryDate",nvl(pNoteParams."DisplayDate",sysdate)),

          "Text" = vExistingRow."Text",

          "Deleted" = nvl(pvPtNoteRow."Deleted",vExistingRow."Deleted"),

          "IsClaimNote" = nvl(pvPtNoteRow."IsClaimNote",vExistingRow."IsClaimNote") 

        where

          "PtNote" = vExistingRow."PtNote";

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptnote rows updated.',vParams);

 

    -- Delete Note

    elsif pNoteParams."Action" in(NOTE_DELETE,NOTE_DELETE_SAME_USER) and vExistingRow."PtNote" <> 0 then

      -- Remove Note

      update ptnote        

      set

        "Deleted" = 1

      where

        "PtNote" = vExistingRow."PtNote";

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptnote rows updated.',vParams);

    end if; -- check action 

     pvSuccess := true;

  exception 

    when exInvalidNoteCode then

      ax_pkg.AppendString_P(pvMessage,pvPtNoteRow."NoteCode" || ' is an invalid note code',true,' ',ax_pkg.MSG_ERROR,vParams);  

    when exVersionMismatch then

      ax_pkg.AppendString_P(pvMessage,'AX_NOTE_PKG version mismatch',true,' ',ax_pkg.MSG_ERROR,vParams);     

  end TransactionNote_P;





  PROCEDURE transactionnote_p(IN ppatient numeric, INOUT pvptnoterow ptnote, IN pnoteparams tnoteparams DEFAULT ax_note_pkg.ax_note_params, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vSuccess boolean;

    vMessage  VARCHAR2(4000);

  begin

    TransactionNote_P(vSuccess,vMessage,pPatient,pvPtNoteRow,pNoteParams,pParams);

    if not vSuccess then

      raise_application_error(-20000, vMessage);

    end if;

  end TransactionNote_P;



END;
CREATE OR REPLACE PACKAGE BODY ax_patient_pkg IS



  -- returns information about this package, or its procedures

  PROCEDURE help(IN pobjectname character varying DEFAULT NULL::character varying) IS

    vReturn CLOB;

  begin

    -- Writes the help to the DBMS_OUTPUT

    vReturn := ax_pkg.Help_F('AX_PATIENT_PKG', pObjectName); --AX-39259

  end Help;



  -- Initilize a new Patient Record

  PROCEDURE initializepatient_p(INOUT pvpatientrow patient, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    -- Setup

    pvPatientRow."User" := vParams."User";

    pvPatientRow."StationId" := vParams."StationId";



    -- Set to Default Values

    pvPatientRow."Family" := pvPatientRow."Patient";

    pvPatientRow."Last" := ' ';

    pvPatientRow."First" := ' ';

    pvPatientRow."Prefered" := ' ';

    pvPatientRow."Middle" := ' ';

    pvPatientRow."Title" := ' ';

    pvPatientRow."Birth" := null;

    pvPatientRow."Address1" := ' ';

    pvPatientRow."Address2" := ' ';

    pvPatientRow."City" := ' ';

    pvPatientRow."Province" := ' ';

    pvPatientRow."Postal" := ' ';

    pvPatientRow."HomeArea" := ' ';

    pvPatientRow."HomePhone" := ' ';

    pvPatientRow."WorkArea" := ' ';

    pvPatientRow."WorkPhone" := ' ';

    pvPatientRow."WorkExt" := null;

    pvPatientRow."OtherArea" := ' ';

    pvPatientRow."OtherPhone" := ' ';

    pvPatientRow."OtherExt" := null;

    pvPatientRow."OtherLoc" := ' ';

    pvPatientRow."ContactAt" := 1;

    pvPatientRow."ContactTime" := ' ';

    pvPatientRow."Status" := ' ';

    pvPatientRow."Sex" := 0;

    pvPatientRow."Marital" := 0;

    pvPatientRow."IsPatient" := 1;

    pvPatientRow."IsStudent" := 0;

    pvPatientRow."IsHandicaped" := 0;

    pvPatientRow."Doctor" := ' ';

    pvPatientRow."Hygienist" := ' ';

    pvPatientRow."Aux" := ' ';

    pvPatientRow."Chart" := ' ';

    pvPatientRow."Sin" := ' ';

    pvPatientRow."Office1" := ' ';

    pvPatientRow."Office2" := ' ';

    pvPatientRow."Office3" := ' ';

    pvPatientRow."Office4" := ' ';

    pvPatientRow."Office5" := ' ';

    pvPatientRow."Alert1" := ' ';

    pvPatientRow."Alert2" := ' ';

    pvPatientRow."Alert3" := ' ';

    pvPatientRow."Alert4" := ' ';

    pvPatientRow."Alert5" := ' ';

    pvPatientRow."Permenant" := 0;

    pvPatientRow."Primary" := 0;

    pvPatientRow."Flags" := 0;

    pvPatientRow."Open" := trunc(sysdate);

    pvPatientRow."Close" := null;

    pvPatientRow."FirstTreatment" := null;

    pvPatientRow."LastClaimDate" := null;

    pvPatientRow."LastClaimAmount" := 0;

    pvPatientRow."Extra" := 0;

    pvPatientRow."Path" := 0;

    pvPatientRow."LastVisit" := trunc(sysdate);

    pvPatientRow."Deleted" := 0;

    pvPatientRow."School" := null;

    pvPatientRow."Health" := ' ';

    pvPatientRow."InsPt" := 0;

    pvPatientRow."OpenBalance" := 0;

    pvPatientRow."AccountStatus" := ' ';

    pvPatientRow."Assignment" := 1;

    pvPatientRow."Statements" := 1;

    pvPatientRow."Interest" := 1;

    pvPatientRow."ChartIn" := 1;

    pvPatientRow."Location" := ' ';

    pvPatientRow."UserOut" := 0;

    pvPatientRow."DateOut" := null;

    pvPatientRow."TimeOut" := 0;

    pvPatientRow."IsFreeAccess" := 0;

    pvPatientRow."Fee" := ' ';

    pvPatientRow."OtherLocation" := ' ';

    pvPatientRow."NoLocks" := 0;

    pvPatientRow."CustomCode1" := ' ';

    pvPatientRow."CustomCode2" := ' ';

    pvPatientRow."CustomCode3" := ' ';

    pvPatientRow."CustomCode4" := ' ';

    pvPatientRow."CustomCode5" := ' ';

    pvPatientRow."CustomCode6" := ' ';

    pvPatientRow."CustomCode7" := ' ';

    pvPatientRow."CustomCode8" := ' ';

    pvPatientRow."CustomCode9" := ' ';

    pvPatientRow."CustomCode10" := ' ';

    pvPatientRow."Physician" := 0;

    pvPatientRow."EmergLast" := ' ';

    pvPatientRow."EmergFirst" := ' ';

    pvPatientRow."EmergMiddle" := ' ';

    pvPatientRow."EmergAddress" := ' ';

    pvPatientRow."EmergCity" := ' ';

    pvPatientRow."EmergProvince" := ' ';

    pvPatientRow."EmergPostal" := ' ';

    pvPatientRow."EmergArea" := ' ';

    pvPatientRow."EmergPhone" := ' ';

    pvPatientRow."EmergRelation" := ' ';

    pvPatientRow."IsChartFixed" := 0;

    pvPatientRow."EmergAltArea" := ' ';

    pvPatientRow."EmergAltPhone" := ' ';

    pvPatientRow."IsOrtho" := 0;

    pvPatientRow."OrthoSet" := ' ';

    pvPatientRow."IsIn" := 0;

    pvPatientRow."EmergAddress2" := ' ';

    pvPatientRow."AltChart" := ' ';

    pvPatientRow."LastUpper" := ' ';

    pvPatientRow."PrefUpper" := ' ';

    pvPatientRow."AddressOther" := ' ';

    pvPatientRow."BankAccount" := ' ';

    pvPatientRow."RespNumber" := ' ';

    pvPatientRow."EmergAddressOther" := ' ';

    pvPatientRow."LastStatementDate" := null;

    pvPatientRow."LastStatementAmount" := 0;

    pvPatientRow."EDIFlag" := 0;

    pvPatientRow."StatusEndDate" := null;

    pvPatientRow."PatType" := ' ';

    pvPatientRow."IsEmergency" := 0;

    pvPatientRow."ActiveDate" := trunc(sysdate);

    pvPatientRow."PartnerName" := ' ';

    pvPatientRow."BoxNumber" := ' ';

    pvPatientRow."Email" := null;

    pvPatientRow."ChartSort" := ' ';

    pvPatientRow."PartnerPrefix" := ' ';

    pvPatientRow."PrefApptTime" := ' ';

    pvPatientRow."XRayReceived" := 0;

    pvPatientRow."DateXRayExpected" := null;

    pvPatientRow."DateXRayReceived" := null;

    pvPatientRow."StatusStartDate" := trunc(sysdate);

    pvPatientRow."Country" := ' ';

    pvPatientRow."XRayExposures" := 0;

    pvPatientRow."LastPmtDate" := null;

    pvPatientRow."LastPaymentAmount" := 0;

    pvPatientRow."Audit" := 0;

    pvPatientRow."MergedChart" := ' ';

    pvPatientRow."ChartSuffix" := ' ';

    pvPatientRow."ReleaseOnFile" := 0;

    pvPatientRow."EmergExt" := null;

    pvPatientRow."EmergAltExt" := null;

    pvPatientRow."HomeExt" := null;

    pvPatientRow."FeeOverride" := 0;

    pvPatientRow."DiscGrp" := ' ';

    pvPatientRow."EmancedMinor" := 0;

    pvPatientRow."RequireTxConsent" := 1;

    pvPatientRow."PaperChart" := 0;

    pvPatientRow."InfoNotify" := 0;

    pvPatientRow."TaxExempt" := 0;

    pvPatientRow."RecallDoctorToUse" := 0;

    pvPatientRow."RecallHygToUse" := 0;

    pvPatientRow."CustomText1" := null;

    pvPatientRow."CustomText2" := null;

    pvPatientRow."CustomText3" := null;

    pvPatientRow."CustomText4" := null;

    pvPatientRow."CustomText5" := null;

    pvPatientRow."MobileArea" := ' ';

    pvPatientRow."MobilePhone" := ' ';    

    pvPatientRow."ApptFeesExempt" := 0;

    pvPatientRow."PrefLanguage" := ' ';

    pvPatientRow."RaceEthDeclined" := 0;

    pvPatientRow."Ethnic" := ' ';

    pvPatientRow."IsTrustedAudit" := 0;      -- SF-00134678

    pvPatientRow."SecondIDType" := 0;        -- SF-00134678

    pvPatientRow."SecondIDNumber" := '';     -- SF-00134678

    pvPatientRow."Is2ndIdTrustedAudit" := 0; -- SF-00134678

    pvPatientRow."HasExternalLink" := 0;     -- SF-00241331

    pvPatientRow."HasCarequality" := 0;      -- AX-27767



  end InitializePatient_P;





  -- Initilize a new PtGuar Record

  PROCEDURE initializeptguar_p(INOUT pvptguarrow ptguar, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

  begin

    -- Set to Default Values

    pvPtGuarRow."RespPatient" := 0;

    pvPtGuarRow."Patient" := 0;

    pvPtGuarRow."IsPrimaryGuarantor" := 1;

    pvPtGuarRow."IsSecondaryGuarantor" := 0;

    pvPtGuarRow."RespRelation" := '';

    pvPtGuarRow."Deleted" := 0;

    pvPtGuarRow."Audit" := 0;

    pvPtGuarRow."Inactive" := 0;

  end InitializePtGuar_P;





  -- routine to add patient2 information

  PROCEDURE addpatient2_p(IN ppatient numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vUser users."User"%type;

    vPatient2Auto patient2."Auto"%type;

    vBirth patient."Birth"%type;

    vAge number;

    vExists number;

    vChart patient."Chart"%type;

    vFirst patient."First"%type;

    vLast patient."Last"%type;

    vMiddle patient."Middle"%type;

    vParams ax_pkg.tParams := pParams;

    exPatient2Exists exception;

  begin

    ax_pkg.InitializeParams_P(vParams);



    -- See if the patient2 record already exists



    if vParams."VerifyLevel" >= ax_pkg.VERIFY_ERRORS then

      begin

        select 1 into vExists from patient2 where "PtxPId" = pPatient;

        raise exPatient2Exists;

      exception

        when no_data_found then

          null;

      end;

    end if;



    -- Setup

    select

      "Birth","Chart","First","Last","Middle"

    into

      vBirth,vChart,vFirst,vLast,vMiddle

    from

      patient

    where

      "Patient" = pPatient;



    if vParams."User" is null then

      select "OvernightUser" into vUser from axiumopt where rownum = 1;

    else

      vUser := vParams."User";

    end if;



    --- insert patient2 record

    select patient2_auto_seq.nextval into vPatient2Auto from dual;



    --- calculate the patients age

    select to_char(sysdate,'YYYY') - to_char(vBirth,'YYYY') - case when to_char(sysdate,'MMDD') < to_char(vBirth,'MMDD') then 1 else 0 end

      into vAge

      from dual;



    if vAge >= 9 then -- use permanent dentition

      insert into patient2(

        "Auto", "ChartId", "LastName", "FirstName",

        "MidName", "Status", "User", "PtxPId", "ToothState",

        "PermanentState", "PrimaryState", "Date", "StationId"

      ) values (

        vPatient2Auto,  -- Auto                  not null      number(10)

        vChart, -- ChartId                                     char(15)

        vLast, -- LastName             char(31)

        vFirst, -- FirstName             char(31)

        vMiddle, -- MidName              char(31)

        0, -- Status                                           number(10)

        vUser, -- User                                    number(10)

        pPatient, -- PtxPId                                  number(10)

        '00000000000000000000000000000000', -- ToothState      char(32)

        '00000000000000000000000000000000', -- PermanentState  char(32)

        '00000000000000000000000000000000', -- PrimaryState    char(32)

        trunc(sysdate), -- Date                                date

        vParams."StationId" -- StationId  number(10)

      );

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' patient2 rows inserted.',vParams);

    else -- patient is <= 8 YO, use primary dentition

      insert into patient2(

        "Auto", "ChartId", "LastName", "FirstName",

        "MidName", "Status", "User", "PtxPId", "ToothState",

        "PermanentState", "PrimaryState", "Date", "StationId"

      ) values (

        vPatient2Auto,  -- Auto                  not null      number(10)

        vChart, -- ChartId                                     char(15)

        vLast, -- LastName             char(31)

        vFirst, -- FirstName             char(31)

        vMiddle, -- MidName              char(31)

        0, -- Status                                           number(10)

        vUser, -- User                                    number(10)

        pPatient, -- PtxPId                                  number(10)

        '33311111111113333331111111111333', -- ToothState      char(32)

        '00000000000000000000000000000000', -- PermanentState  char(32)

        '00000000000000000000000000000000', -- PrimaryState    char(32)

        trunc(sysdate), -- Date                                date

        vParams."StationId" -- StationId  number(10)

      );

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' patient2 rows inserted.',vParams);

    end if;



    insert into pat2his

      select

        pat2his_pat2his_seq.nextval,

        1,        -- add

        p2.*

      from

        patient2 p2

      where

        "Auto" = vPatient2Auto;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' pat2his rows inserted.',vParams);

  exception

    when exPatient2Exists then

      raise_application_error(-20000, 'Patient2 Record already exists!');

  end AddPatient2_P;





  -- Insert Patient Record

  --   This procedure assumes the patient row has already been Initialized

  PROCEDURE insertpatient_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, INOUT pvpatientrow patient, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN pprefix character varying DEFAULT NULL::character varying) IS

    vAuditRow audithis%rowtype;

    vCityRow city%rowtype;

    vSuccess boolean;

    vMessage  VARCHAR2(4000);

    vCountry province."Country"%type;

    exNoFirstLast exception;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    pvSuccess := false;

    if NOT (trim(pvPatientRow."First") is null OR length(trim(pvPatientRow."First")) = 0) 

            and  NOT (trim(pvPatientRow."Last") is null OR length(trim(pvPatientRow."Last")) = 0) then

      if (trim(pvPatientRow."Prefered") is null OR length(trim(pvPatientRow."Prefered")) = 0) then

        pvPatientRow."Prefered" := pvPatientRow."First";

      end if;



      pvPatientRow."LastUpper" := upper(pvPatientRow."Last");

      pvPatientRow."PrefUpper" := upper(pvPatientRow."Prefered");



      if (trim(pvPatientRow."Chart") is null OR length(trim(pvPatientRow."Chart")) = 0) and pvPatientRow."IsPatient" = 1 then

        pvPatientRow."Chart" := trim(GetNextChart_F(pPrefix));

      end if;



      if (trim(pvPatientRow."Status") is null OR length(trim(pvPatientRow."Status")) = 0) and pvPatientRow."IsPatient" = 1 then

        begin

          select "Status" into pvPatientRow."Status" from status where "Type" = 2 and "Default" = 1 and "Inactive" = 0;

        exception

          when no_data_found then

            pvPatientRow."Status" := ' ';

        end;

      end if;



      if pvPatientRow."User" is null then

        select "OvernightUser" into pvPatientRow."User" from axiumopt where rownum = 1;

      end if;



      select patient_patient_seq.nextval into pvPatientRow."Patient" from dual;



      if pvPatientRow."Family" is null or pvPatientRow."IsPatient" = 1 then

        pvPatientRow."Family" := pvPatientRow."Patient";

      end if;



      -- Make sure that dates which should not have a time element are truncated - P189-148766

      pvPatientRow."Birth" := trunc(pvPatientRow."Birth");

      pvPatientRow."Open" := trunc(pvPatientRow."Open");

      pvPatientRow."Close" := trunc(pvPatientRow."Close");

      pvPatientRow."FirstTreatment" := trunc(pvPatientRow."FirstTreatment");

      pvPatientRow."LastClaimDate" := trunc(pvPatientRow."LastClaimDate");

      pvPatientRow."LastVisit" := trunc(pvPatientRow."LastVisit");

      pvPatientRow."DateOut" := trunc(pvPatientRow."DateOut");

      pvPatientRow."LastStatementDate" := trunc(pvPatientRow."LastStatementDate");

      pvPatientRow."StatusEndDate" := trunc(pvPatientRow."StatusEndDate");

      pvPatientRow."ActiveDate" := trunc(pvPatientRow."ActiveDate");

      pvPatientRow."DateXRayExpected" := trunc(pvPatientRow."DateXRayExpected");

      pvPatientRow."DateXRayReceived" := trunc(pvPatientRow."DateXRayReceived");

      pvPatientRow."StatusStartDate" := trunc(pvPatientRow."StatusStartDate");

      pvPatientRow."LastPmtDate" := trunc(pvPatientRow."LastPmtDate");



      -- audithis for patient

      vAuditRow."TableName" := 'PATIENT';

      vAuditRow."HistoryType" := ax_pkg.AUDIT_ADD;

      ax_pkg.CreateAuditHis_P(vAuditRow,vParams);

      pvPatientRow."Audit" := vAuditRow."Audit";



      insert into patient values pvPatientRow;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' patient rows inserted.',vParams);



      -- set patient history to show this was a patient add

      update pathis

      set

        "PtAddFlag" = 1

      where

        "Patient" = pvPatientRow."Patient" and

        "Audit" = vAuditRow."Audit"

      ;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' pathis rows updated.',vParams);



      -- Create RespHis Record

      InsertRespHis_P(pvPatientRow,vParams);



      -- PTGUAR for self

      vAuditRow."TableName" := 'PTGUAR';

      vAuditRow."HistoryType" := ax_pkg.AUDIT_ADD;

      ax_pkg.CreateAuditHis_P(vAuditRow,vParams);



      -- add PTGUAR for 'SELF'

      -- always make this the primary guarantor

      insert into ptguar values (

        pvPatientRow."Patient", -- RespPatient

        pvPatientRow."Patient",  -- Patient

        1,  -- IsPrimaryGuarantor

        0,  -- IsSecondaryGuarantor

        1,  -- IsPolicyGuarantor

        'Self',  -- RespRelation

        0,  -- Deleted

        vAuditRow."Audit", -- Audit

        0  -- Inactive

      );

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptguar rows inserted.',vParams);



      AddPatient2_P(pvPatientRow."Patient",vParams);



      -- Add City Record

      vCityRow."Postal" := pvPatientRow."Postal";

      vCityRow."City" := pvPatientRow."City";

      vCityRow."Province" := pvPatientRow."Province";

      vCityRow."AddressOther" := pvPatientRow."AddressOther";

      AddCity_P(vSuccess,vMessage,vCityRow,vCountry,vParams);



      if vSuccess and vMessage is not null then

        ax_pkg.AppendString_P(pvMessage,vMessage,' ',ax_pkg.MSG_INFO,vParams);

      else

        ax_pkg.AppendString_P(pvMessage,vMessage,' ',ax_pkg.MSG_WARNING,vParams);

      end if;



    else

      raise exNoFirstLast;

    end if;

    pvSuccess := true;

  exception

    when exNoFirstLast then

      ax_pkg.AppendString_P(pvMessage,'Patient First and Last name are required.',' ',ax_pkg.MSG_ERROR,vParams);

  end InsertPatient_P;





  -- Insert Patient Record

  --   Overload

  PROCEDURE insertpatient_p(INOUT pvpatientrow patient, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vSuccess boolean;

    vMessage  VARCHAR2(4000);

  begin

    InsertPatient_P(vSuccess,vMessage,pvPatientRow,pParams);

    if not vSuccess then

      raise_application_error(-20000, vMessage);

    end if;

  end InsertPatient_P;





  -- Insert a Responsible Party History Record

    -- Called by InsertPatient

  PROCEDURE insertresphis_p(INOUT pvpatientrow patient, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vAuditRow audithis%rowtype;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    -- audithis for resphis

    vAuditRow."TableName" := 'RESPHIS';			--AX-27219

    vAuditRow."HistoryType" := ax_pkg.AUDIT_ADD;

    ax_pkg.CreateAuditHis_P(vAuditRow,vParams);



    -- Make sure that dates which should not have a time element are truncated - P189-148766

    pvPatientRow."Birth" := trunc(pvPatientRow."Birth");



    -- add changes to responsible party in patient record

    insert into resphis values (

      resphis_resphis_seq.nextval,  -- RespHis

      pvPatientRow."Patient",       -- Patient

      pvPatientRow."Last",          -- Last

      pvPatientRow."First",         -- First

      pvPatientRow."Middle",        -- Middle

      pvPatientRow."Title",         -- Title

      pvPatientRow."Birth",         -- Birth

      pvPatientRow."Address1",      -- Address1

      pvPatientRow."Address2",      -- Address2

      pvPatientRow."City",          -- City

      pvPatientRow."Province",      -- Province

      pvPatientRow."Postal",        -- Postal

      pvPatientRow."HomeArea",      -- Home Area

      pvPatientRow."HomePhone",     -- Home Phone

      pvPatientRow."WorkArea",      -- Work Area

      pvPatientRow."WorkPhone",     -- Work Phone

      pvPatientRow."Status",        -- Status

      pvPatientRow."Sex",           -- Sex

      pvPatientRow."Marital",       -- Marital

      pvPatientRow."AddressOther",  -- AddressOther

      pvPatientRow."RespNumber",    -- RespNumber

      0,                            -- Deleted

      vAuditRow."Audit",            -- Audit

      pvPatientRow."Country",       -- Country

      pvPatientRow."Prefered",      -- Preferred

      pvPatientRow."HomeExt",       -- HomeExt

      pvPatientRow."WorkExt",       -- WorkExt

      pvPatientRow."EmancedMinor",  -- EmancedMinor

      pvPatientRow."PrefLanguage",  -- Preferred Language

      pvPatientRow."Statements",    -- Statements

      pvPatientRow."Email",         -- Email

      pvPatientRow."IsTrustedAudit",-- IsTrustedAudit  -- SF-00134678

      pvPatientRow."Sin"            -- Sin             -- SF-00134678

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' resphis rows inserted.',vParams);

  end InsertRespHis_P;





   -- Compare two Patient Records to see if they match

  FUNCTION patientsequal_f(pvpatientrow1 patient, pvpatientrow2 patient, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN boolean IS

  begin

    case

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Patient",pvPatientRow2."Patient") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Family",pvPatientRow2."Family") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Last",pvPatientRow2."Last") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."First",pvPatientRow2."First") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Prefered",pvPatientRow2."Prefered") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Middle",pvPatientRow2."Middle") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Title",pvPatientRow2."Title") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Birth",pvPatientRow2."Birth") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Address1",pvPatientRow2."Address1") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Address2",pvPatientRow2."Address2") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."City",pvPatientRow2."City") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Province",pvPatientRow2."Province") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Postal",pvPatientRow2."Postal") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."HomeArea",pvPatientRow2."HomeArea") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."HomePhone",pvPatientRow2."HomePhone") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."WorkArea",pvPatientRow2."WorkArea") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."WorkPhone",pvPatientRow2."WorkPhone") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."WorkExt",pvPatientRow2."WorkExt") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."OtherArea",pvPatientRow2."OtherArea") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."OtherPhone",pvPatientRow2."OtherPhone") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."OtherExt",pvPatientRow2."OtherExt") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."OtherLoc",pvPatientRow2."OtherLoc") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."ContactAt",pvPatientRow2."ContactAt") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."ContactTime",pvPatientRow2."ContactTime") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Status",pvPatientRow2."Status") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Sex",pvPatientRow2."Sex") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Marital",pvPatientRow2."Marital") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."IsPatient",pvPatientRow2."IsPatient") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."IsStudent",pvPatientRow2."IsStudent") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."IsHandicaped",pvPatientRow2."IsHandicaped") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Doctor",pvPatientRow2."Doctor") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Hygienist",pvPatientRow2."Hygienist") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Aux",pvPatientRow2."Aux") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Chart",pvPatientRow2."Chart") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Sin",pvPatientRow2."Sin") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Office1",pvPatientRow2."Office1") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Office2",pvPatientRow2."Office2") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Office3",pvPatientRow2."Office3") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Office4",pvPatientRow2."Office4") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Office5",pvPatientRow2."Office5") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Alert1",pvPatientRow2."Alert1") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Alert2",pvPatientRow2."Alert2") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Alert3",pvPatientRow2."Alert3") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Alert4",pvPatientRow2."Alert4") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Alert5",pvPatientRow2."Alert5") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Permenant",pvPatientRow2."Permenant") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Primary",pvPatientRow2."Primary") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Flags",pvPatientRow2."Flags") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Open",pvPatientRow2."Open") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Close",pvPatientRow2."Close") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."FirstTreatment",pvPatientRow2."FirstTreatment") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."LastClaimDate",pvPatientRow2."LastClaimDate") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."LastClaimAmount",pvPatientRow2."LastClaimAmount") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Extra",pvPatientRow2."Extra") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Path",pvPatientRow2."Path") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."LastVisit",pvPatientRow2."LastVisit") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Deleted",pvPatientRow2."Deleted") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."School",pvPatientRow2."School") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Health",pvPatientRow2."Health") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."InsPt",pvPatientRow2."InsPt") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."OpenBalance",pvPatientRow2."OpenBalance") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."AccountStatus",pvPatientRow2."AccountStatus") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Assignment",pvPatientRow2."Assignment") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Statements",pvPatientRow2."Statements") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Interest",pvPatientRow2."Interest") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."ChartIn",pvPatientRow2."ChartIn") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Location",pvPatientRow2."Location") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."UserOut",pvPatientRow2."UserOut") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."DateOut",pvPatientRow2."DateOut") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."TimeOut",pvPatientRow2."TimeOut") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."IsFreeAccess",pvPatientRow2."IsFreeAccess") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Fee",pvPatientRow2."Fee") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."OtherLocation",pvPatientRow2."OtherLocation") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."NoLocks",pvPatientRow2."NoLocks") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."CustomCode1",pvPatientRow2."CustomCode1") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."CustomCode2",pvPatientRow2."CustomCode2") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."CustomCode3",pvPatientRow2."CustomCode3") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."CustomCode4",pvPatientRow2."CustomCode4") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."CustomCode5",pvPatientRow2."CustomCode5") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."CustomCode6",pvPatientRow2."CustomCode6") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."CustomCode7",pvPatientRow2."CustomCode7") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."CustomCode8",pvPatientRow2."CustomCode8") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."CustomCode9",pvPatientRow2."CustomCode9") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."CustomCode10",pvPatientRow2."CustomCode10") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Physician",pvPatientRow2."Physician") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."EmergLast",pvPatientRow2."EmergLast") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."EmergFirst",pvPatientRow2."EmergFirst") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."EmergMiddle",pvPatientRow2."EmergMiddle") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."EmergAddress",pvPatientRow2."EmergAddress") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."EmergCity",pvPatientRow2."EmergCity") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."EmergProvince",pvPatientRow2."EmergProvince") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."EmergPostal",pvPatientRow2."EmergPostal") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."EmergArea",pvPatientRow2."EmergArea") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."EmergPhone",pvPatientRow2."EmergPhone") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."EmergRelation",pvPatientRow2."EmergRelation") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."IsChartFixed",pvPatientRow2."IsChartFixed") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."EmergAltArea",pvPatientRow2."EmergAltArea") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."EmergAltPhone",pvPatientRow2."EmergAltPhone") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."IsOrtho",pvPatientRow2."IsOrtho") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."OrthoSet",pvPatientRow2."OrthoSet") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."IsIn",pvPatientRow2."IsIn") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."EmergAddress2",pvPatientRow2."EmergAddress2") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."AltChart",pvPatientRow2."AltChart") then return false;

      --when not ax_pkg.ValuesEqual_F(pvPatientRow1."LastUpper",pvPatientRow2."LastUpper") then return false;

      --when not ax_pkg.ValuesEqual_F(pvPatientRow1."PrefUpper",pvPatientRow2."PrefUpper") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."AddressOther",pvPatientRow2."AddressOther") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."BankAccount",pvPatientRow2."BankAccount") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."RespNumber",pvPatientRow2."RespNumber") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."EmergAddressOther",pvPatientRow2."EmergAddressOther") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."LastStatementDate",pvPatientRow2."LastStatementDate") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."LastStatementAmount",pvPatientRow2."LastStatementAmount") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."EDIFlag",pvPatientRow2."EDIFlag") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."StatusEndDate",pvPatientRow2."StatusEndDate") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."PatType",pvPatientRow2."PatType") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."IsEmergency",pvPatientRow2."IsEmergency") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."ActiveDate",pvPatientRow2."ActiveDate") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."PartnerName",pvPatientRow2."PartnerName") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."BoxNumber",pvPatientRow2."BoxNumber") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Email",pvPatientRow2."Email") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."ChartSort",pvPatientRow2."ChartSort") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."PartnerPrefix",pvPatientRow2."PartnerPrefix") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."PrefApptTime",pvPatientRow2."PrefApptTime") then return false;

      --when not ax_pkg.ValuesEqual_F(pvPatientRow1."User",pvPatientRow2."User") then return false;

      --when not ax_pkg.ValuesEqual_F(pvPatientRow1."StationId",pvPatientRow2."StationId") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."XRayReceived",pvPatientRow2."XRayReceived") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."DateXRayExpected",pvPatientRow2."DateXRayExpected") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."DateXRayReceived",pvPatientRow2."DateXRayReceived") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."StatusStartDate",pvPatientRow2."StatusStartDate") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Country",pvPatientRow2."Country") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."XRayExposures",pvPatientRow2."XRayExposures") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."LastPmtDate",pvPatientRow2."LastPmtDate") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."LastPaymentAmount",pvPatientRow2."LastPaymentAmount") then return false;

      --when not ax_pkg.ValuesEqual_F(pvPatientRow1."Audit",pvPatientRow2."Audit") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."MergedChart",pvPatientRow2."MergedChart") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."ChartSuffix",pvPatientRow2."ChartSuffix") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."ReleaseOnFile",pvPatientRow2."ReleaseOnFile") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."EmergExt",pvPatientRow2."EmergExt") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."EmergAltExt",pvPatientRow2."EmergAltExt") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."HomeExt",pvPatientRow2."HomeExt") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."FeeOverride",pvPatientRow2."FeeOverride") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."DiscGrp",pvPatientRow2."DiscGrp") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."EmancedMinor",pvPatientRow2."EmancedMinor") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."RequireTxConsent",pvPatientRow2."RequireTxConsent") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."PaperChart",pvPatientRow2."PaperChart") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."InfoNotify",pvPatientRow2."InfoNotify") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."TaxExempt",pvPatientRow2."TaxExempt") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."RecallDoctorToUse",pvPatientRow2."RecallDoctorToUse") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."RecallHygToUse",pvPatientRow2."RecallHygToUse") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."CustomText1",pvPatientRow2."CustomText1") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."CustomText2",pvPatientRow2."CustomText2") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."CustomText3",pvPatientRow2."CustomText3") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."CustomText4",pvPatientRow2."CustomText4") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."CustomText5",pvPatientRow2."CustomText5") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."MobileArea",pvPatientRow2."MobileArea") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."MobilePhone",pvPatientRow2."MobilePhone") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."ApptFeesExempt",pvPatientRow2."ApptFeesExempt") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."PrefLanguage",pvPatientRow2."PrefLanguage") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."RaceEthDeclined",pvPatientRow2."RaceEthDeclined") then return false;

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Ethnic",pvPatientRow2."Ethnic") then return false;      

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."IsTrustedAudit",pvPatientRow2."IsTrustedAudit") then return false;            -- SF-00134678

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."SecondIDType",pvPatientRow2."SecondIDType") then return false;                -- SF-00134678

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."SecondIDNumber",pvPatientRow2."SecondIDNumber") then return false;            -- SF-00134678

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."Is2ndIdTrustedAudit",pvPatientRow2."Is2ndIdTrustedAudit") then return false;  -- SF-00134678

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."HasExternalLink",pvPatientRow2."HasExternalLink") then return false;          -- SF-00241331

      when not ax_pkg.ValuesEqual_F(pvPatientRow1."HasCarequality",pvPatientRow2."HasCarequality") then return false;            -- AX-27767

      else return true;

    end case;

  end PatientsEqual_F;





  -- Update an Existing Patient Record

  PROCEDURE updatepatient_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, INOUT pvpatientrow patient, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN pprefix character varying DEFAULT NULL::character varying) IS

    vAuditRow audithis%rowtype;

	vCityRow  city%rowtype;

	vCountry province."Country"%type;

    vSuccess boolean;

    vMessage  VARCHAR2(4000);

    vOldPatientRow patient%rowtype;

    exNoChange exception;

    exNoFirstLast exception;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    pvSuccess := false;

    if NOT (trim(pvPatientRow."First") is null OR length(trim(pvPatientRow."First")) = 0) 

        and NOT (trim(pvPatientRow."Last") is null OR length(trim(pvPatientRow."Last")) = 0) then



      select * into vOldPatientRow from patient where "Patient" = pvPatientRow."Patient";



      if PatientsEqual_F(vOldPatientRow,pvPatientRow) then

        raise exNoChange;

      end if;



      if (trim(pvPatientRow."Prefered") is null OR length(trim(pvPatientRow."Prefered")) = 0) then

        pvPatientRow."Prefered" := pvPatientRow."First";

      end if;



      pvPatientRow."LastUpper" := upper(pvPatientRow."Last");

      pvPatientRow."PrefUpper" := upper(pvPatientRow."Prefered");



      if pvPatientRow."Chart" = ' ' and pvPatientRow."IsPatient" = 1 then

        pvPatientRow."Chart" := trim(GetNextChart_F(pPrefix));

      end if;



      if pvPatientRow."Status" = ' ' and pvPatientRow."IsPatient" = 1 then

        begin

          select "Status" into pvPatientRow."Status" from status where "Type" = 2 and "Default" = 1 and "Inactive" = 0;

        exception

          when no_data_found then

            pvPatientRow."Status" := ' ';

        end;

      end if;



      if pvPatientRow."User" is null then

        select "OvernightUser" into pvPatientRow."User" from axiumopt where rownum = 1;

      end if;



      if pvPatientRow."Family" is null then

        pvPatientRow."Family" := pvPatientRow."Patient";

      end if;



      -- audithis for patient

      vAuditRow."TableName" := 'PATIENT';

      vAuditRow."HistoryType" := ax_pkg.AUDIT_EDIT;

      ax_pkg.CreateAuditHis_P(vAuditRow,vParams);



      pvPatientRow."Audit" := vAuditRow."Audit";

      pvPatientRow."User" := vParams."User";

      pvPatientRow."StationId" := vParams."StationId";



      -- Make sure that dates which should not have a time element are truncated - P189-148766

      pvPatientRow."Birth" := trunc(pvPatientRow."Birth");

      pvPatientRow."Open" := trunc(pvPatientRow."Open");

      pvPatientRow."Close" := trunc(pvPatientRow."Close");

      pvPatientRow."FirstTreatment" := trunc(pvPatientRow."FirstTreatment");

      pvPatientRow."LastClaimDate" := trunc(pvPatientRow."LastClaimDate");

      pvPatientRow."LastVisit" := trunc(pvPatientRow."LastVisit");

      pvPatientRow."DateOut" := trunc(pvPatientRow."DateOut");

      pvPatientRow."LastStatementDate" := trunc(pvPatientRow."LastStatementDate");

      pvPatientRow."StatusEndDate" := trunc(pvPatientRow."StatusEndDate");

      pvPatientRow."ActiveDate" := trunc(pvPatientRow."ActiveDate");

      pvPatientRow."DateXRayExpected" := trunc(pvPatientRow."DateXRayExpected");

      pvPatientRow."DateXRayReceived" := trunc(pvPatientRow."DateXRayReceived");

      pvPatientRow."StatusStartDate" := trunc(pvPatientRow."StatusStartDate");

      pvPatientRow."LastPmtDate" := trunc(pvPatientRow."LastPmtDate");



      update patient

      set

        row = pvPatientRow

      where

        "Patient" = pvPatientRow."Patient";

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' patient rows updated.',vParams);

    else

      raise exNoFirstLast;

    end if;

	

	-- Add city Record if necessary

    vCityRow."Postal" := pvPatientRow."Postal";

    vCityRow."City" := pvPatientRow."City";

    vCityRow."Province" := pvPatientRow."Province";

    vCityRow."AddressOther" := pvPatientRow."AddressOther";

    AddCity_P(vSuccess,vMessage,vCityRow,vCountry,vParams);



    if vSuccess and vMessage is not null then

      ax_pkg.AppendString_P(pvMessage,vMessage,' ',ax_pkg.MSG_INFO,vParams);

    else

      ax_pkg.AppendString_P(pvMessage,vMessage,' ',ax_pkg.MSG_WARNING,vParams);

    end if;

	

    pvSuccess := true;

  exception

    when exNoChange then

      if vParams."VerboseType" > ax_pkg.MSG_INFO then

        ax_pkg.AppendString_P(pvMessage,'Patient record unchanged, nothing to update.',' ',ax_pkg.MSG_INFO,vParams);

      end if;

      pvSuccess := true; -- nothing to do

    when exNoFirstLast then

      ax_pkg.AppendString_P(pvMessage,'Patient First and Last name are required.',' ',ax_pkg.MSG_ERROR,vParams);

    when no_data_found then

      ax_pkg.AppendString_P(pvMessage,'Patient not found.',' ',ax_pkg.MSG_ERROR,vParams);

  end UpdatePatient_P;





  -- Update an Existing Patient Record

    -- Overload

  PROCEDURE updatepatient_p(INOUT pvpatientrow patient, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vSuccess boolean;

    vMessage  VARCHAR2(4000);

  begin

    UpdatePatient_P(vSuccess,vMessage,pvPatientRow,pParams);

    if not vSuccess then

      raise_application_error(-20000, vMessage);

    end if;

  end UpdatePatient_P;





  -- Update/Insert PtGuar record for a Patients Guarantor

  PROCEDURE updateptguar_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN pguarantor numeric, IN pptguarrow ptguar, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vExists number := 0;

    vIsSecondaryGuarantor ptguar."IsSecondaryGuarantor"%type;

    vPtGuarRow ptguar%rowtype;

    vAuditRow audithis%rowtype;

    exNoPatient exception;

    exNoGuarantor exception;

    exNoRelationship exception;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    pvSuccess := false;

    -- Data Checking

    if vParams."VerifyLevel" >= ax_pkg.VERIFY_ERRORS then

      -- make sure that the Patient exists

      begin

        select 1 into vExists from patient where "Patient" = pPatient;

      exception

        when no_data_found then

          raise exNoPatient;

      end;

      -- make sure that the Guarantor exists

      begin

        select 1 into vExists from patient where "Patient" = pGuarantor;

      exception

        when no_data_found then

          raise exNoGuarantor;

      end;

      if NOT (trim(pPtGuarRow."RespRelation") is null OR length(trim(pPtGuarRow."RespRelation")) = 0) then

        -- make sure that the Relationship exists

        begin

          select 1 into vExists from relation where upper(trim(pPtGuarRow."RespRelation")) = upper(trim("Relation"));

        exception

          when no_data_found then

            raise exNoRelationship;

        end;

      end if;

    end if;



    -- See if the PtGuar record exists

    begin

      select * into vPtGuarRow from ptguar where "Patient" = pPatient and "RespPatient" = pGuarantor;

      vExists := 1;

    exception

      when no_data_found then

        vExists := 0;

    end;



    -- Set pIsSecondaryGuarantor, if needed

    if pPtGuarRow."IsSecondaryGuarantor" is null and pPtGuarRow."IsPrimaryGuarantor" = 1 then

      vIsSecondaryGuarantor := 0;

    elsif pPtGuarRow."IsSecondaryGuarantor" is null and pPtGuarRow."IsPrimaryGuarantor" = 0 then

      vIsSecondaryGuarantor := 1;

    elsif pPtGuarRow."IsSecondaryGuarantor" = 0 and pPtGuarRow."IsPrimaryGuarantor" = 1 then

      vIsSecondaryGuarantor := 0;

    elsif pPtGuarRow."IsSecondaryGuarantor" = 1 and pPtGuarRow."IsPrimaryGuarantor" = 0 then

      vIsSecondaryGuarantor := 1;

    end if;



    -- if the PtGuar Record does not exist, create it

    if vExists = 0 then



      -- audithis for ptguar

      vAuditRow."TableName" := 'PTGUAR';

      vAuditRow."HistoryType" := ax_pkg.AUDIT_ADD;

      ax_pkg.CreateAuditHis_P(vAuditRow,vParams);



      -- add ptguar record

      insert into ptguar values (

        pGuarantor,                             -- RespPatient

        pPatient,                               -- Patient

        nvl(pPtGuarRow."IsPrimaryGuarantor",0), -- IsPrimaryGuarantor

        nvl(vIsSecondaryGuarantor,0),           -- IsSecondaryGuarantor

        nvl(pPtGuarRow."IsPolicyGuarantor",0),  -- IsPolicyGuarantor

        nvl(pPtGuarRow."RespRelation",' '),     -- RespRelation

        0,                                      -- Deleted

        vAuditRow."Audit",                      -- Audit

        0                                       -- Inactive

      );

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptguar rows inserted.',vParams);



    -- if the PtGuar Record does exist, then update it

    else



      -- audithis for ptguar

      vAuditRow."TableName" := 'PTGUAR';

      vAuditRow."HistoryType" := ax_pkg.AUDIT_EDIT;

      ax_pkg.CreateAuditHis_P(vAuditRow,vParams);



      -- update ptguar record

      update ptguar set

        "IsPrimaryGuarantor" = nvl(pPtGuarRow."IsPrimaryGuarantor",vPtGuarRow."IsPrimaryGuarantor"),

        "IsSecondaryGuarantor" = nvl(pPtGuarRow."IsSecondaryGuarantor",vIsSecondaryGuarantor),

        "IsPolicyGuarantor" = nvl(pPtGuarRow."IsPolicyGuarantor",vPtGuarRow."IsPolicyGuarantor"),

        "RespRelation" = nvl(pPtGuarRow."RespRelation",vPtGuarRow."RespRelation"),

        "Deleted" = nvl(pPtGuarRow."Deleted",vPtGuarRow."Deleted"),

        "Audit" = vAuditRow."Audit",

        "Inactive" = nvl(pPtGuarRow."Inactive",vPtGuarRow."Inactive")

      where

        "Patient" = pPatient and

        "RespPatient" = pGuarantor;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptguar rows updated.',vParams);



    end if;



    -- Only one ptguar record can be Primary, so set all others to not be primary if this one was

    if pPtGuarRow."IsPrimaryGuarantor" = 1 then

      begin

        -- This query will fail if there is nothing to update

        select 1 into vExists from ptguar where "Patient" = pPatient and "RespPatient" <> pGuarantor and "IsPrimaryGuarantor" = 1 and "Deleted" =0;



        -- audithis for ptguar

        vAuditRow."TableName" := 'PTGUAR';

        vAuditRow."HistoryType" := ax_pkg.AUDIT_EDIT;

        ax_pkg.CreateAuditHis_P(vAuditRow,vParams);



        -- update ptguar records

        update ptguar set

          "IsPrimaryGuarantor" = 0,

          "IsSecondaryGuarantor" = 1,

          "Audit" = vAuditRow."Audit"

        where

          "Patient" = pPatient and

          "RespPatient" <> pGuarantor and

          "IsPrimaryGuarantor" = 1 and

          "Deleted" = 0;

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptguar rows updated.',vParams);



      exception

        when no_data_found then

          vAuditRow := vAuditRow;

      end;

    end if; -- end if pIsPrimary

    pvSuccess := true;

  exception

    when exNoPatient then

      ax_pkg.AppendString_P(pvMessage,'Patient ' || pPatient || ' Not Found.',' ',ax_pkg.MSG_ERROR,vParams);

    when exNoGuarantor then

      ax_pkg.AppendString_P(pvMessage,'Guarantor ' || pGuarantor || ' Not Found.',' ',ax_pkg.MSG_ERROR,vParams);

    when exNoRelationship then

      ax_pkg.AppendString_P(pvMessage,'Relationship ' || trim(pPtGuarRow."RespRelation") || ' Not Found.',' ',ax_pkg.MSG_ERROR,vParams);

  end UpdatePtGuar_P;





  -- Update/Insert PtGuar record for a Patients Guarantor

   -- Overload

  PROCEDURE updateptguar_p(IN ppatient numeric, IN pguarantor numeric, IN pptguarrow ptguar, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vSuccess boolean;

    vMessage  VARCHAR2(4000);

  begin

    UpdatePtGuar_P(vSuccess,vMessage,pPatient,pGuarantor,pPtGuarRow,pParams);

    if not vSuccess then

      raise_application_error(-20000, vMessage);

    end if;

  end UpdatePtGuar_P;





  -- Uncheck the IsPolicyGuarantor flag for all Guarantors tied to a patient

    -- Used when client only wants one guarantor to have the "IsPolicyGuarantor" checked

  PROCEDURE clearispolicyguarantor_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vExists number;

    vAuditRow audithis%rowtype;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    pvSuccess := false;



    --make sure that we will be changing records

    select 1 into vExists

    from ptguar

    where "IsPolicyGuarantor" = 1 and

      "Patient" = pPatient and

      "Deleted" = 0 and

      rownum = 1;



    -- audithis for ptguar

    vAuditRow."TableName" := 'PTGUAR';

    vAuditRow."HistoryType" := ax_pkg.AUDIT_EDIT;

    ax_pkg.CreateAuditHis_P(vAuditRow,vParams);



    -- update ptguar records

    update ptguar set

      "IsPolicyGuarantor" = 0,

      "Audit" = vAuditRow."Audit"

    where

      "Patient" = pPatient and

      "Deleted" = 0;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptguar rows updated.',vParams);



    pvSuccess := true;

  exception

    when no_data_found then

      -- nothing to change

      pvSuccess := true;

  end ClearIsPolicyGuarantor_P;





  -- Uncheck the IsPolicyGuarantor flag for all Guarantors tied to a patient

    -- Overload

  PROCEDURE clearispolicyguarantor_p(IN ppatient numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vSuccess boolean;

    vMessage  VARCHAR2(4000);

  begin

    ClearIsPolicyGuarantor_P(vSuccess,vMessage,pPatient,pParams);

    if not vSuccess then

      raise_application_error(-20000, vMessage);

    end if;

  end ClearIsPolicyGuarantor_P;





  -- Insert Patient Record for a Guarantor

  --   This procedure assumes the patient row has already been Initialized, and the Family has been set

  PROCEDURE insertguarantor_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, INOUT pvpatientrow patient, IN pfamily numeric, IN pptguarrow ptguar, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vAuditRow audithis%rowtype;

    vCityRow city%rowtype;

    vSuccess boolean;

    vMessage  VARCHAR2(4000);

    vCountry province."Country"%type;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    pvSuccess := false;

    if NOT (trim(pvPatientRow."First") is null OR length(trim(pvPatientRow."First")) = 0) 

            and NOT (trim(pvPatientRow."Last") is null OR length(trim(pvPatientRow."Last")) = 0) then

       -- audithis for patient

      vAuditRow."TableName" := 'PATIENT';

      vAuditRow."HistoryType" := ax_pkg.AUDIT_EDIT;

      ax_pkg.CreateAuditHis_P(vAuditRow,vParams);



      if (trim(pvPatientRow."Prefered") is null OR length(trim(pvPatientRow."Prefered")) = 0) then

        pvPatientRow."Prefered" := pvPatientRow."First";

      end if;



      select patient_patient_seq.nextval into pvPatientRow."Patient" from dual;



      pvPatientRow."LastUpper" := upper(pvPatientRow."Last");

      pvPatientRow."PrefUpper" := upper(pvPatientRow."Prefered");

      pvPatientRow."Audit" := vAuditRow."Audit";



      if pvPatientRow."User" is null then

        select "OvernightUser" into pvPatientRow."User" from axiumopt where rownum = 1;

      end if;



      pvPatientRow."Family" := pFamily;



      insert into patient values pvPatientRow;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' patient rows inserted.',vParams);



    -- Create additional required records



      -- set patient history to show this was a patient add

      update pathis

      set

        "PtAddFlag" = 1

      where

        "Patient" = pvPatientRow."Patient" and

        "Audit" = pvPatientRow."Audit"

      ;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' pathis rows updated.',vParams);



      -- audithis for resphis

      vAuditRow."TableName" := 'RESPHIS';

      vAuditRow."HistoryType" := ax_pkg.AUDIT_ADD;

      ax_pkg.CreateAuditHis_P(vAuditRow,vParams);



      -- add changes to responsible party in patient record

      insert into resphis values (

        resphis_resphis_seq.nextval,  -- RespHis

        pvPatientRow."Patient",       -- Patient

        pvPatientRow."Last",          -- Last

        pvPatientRow."First",         -- First

        pvPatientRow."Middle",        -- Middle

        pvPatientRow."Title",         -- Title

        pvPatientRow."Birth",         -- Birth

        pvPatientRow."Address1",      -- Address1

        pvPatientRow."Address2",      -- Address2

        pvPatientRow."City",          -- City

        pvPatientRow."Province",      -- Province

        pvPatientRow."Postal",        -- Postal

        pvPatientRow."HomeArea",      -- Home Area

        pvPatientRow."HomePhone",     -- Home Phone

        pvPatientRow."WorkArea",      -- Work Area

        pvPatientRow."WorkPhone",     -- Work Phone

        pvPatientRow."Status",        -- Status

        pvPatientRow."Sex",           -- Sex

        pvPatientRow."Marital",       -- Marital

        pvPatientRow."AddressOther",  -- AddressOther

        pvPatientRow."RespNumber",    -- RespNumber

        0,                            -- Deleted

        vAuditRow."Audit",            -- Audit

        pvPatientRow."Country",       -- Country

        pvPatientRow."Prefered",      -- Preferred

        pvPatientRow."HomeExt",       -- HomeExt

        pvPatientRow."WorkExt",       -- WorkExt

        pvPatientRow."EmancedMinor",  -- EmancedMinor

        pvPatientRow."PrefLanguage",  -- Preferred Language

        pvPatientRow."Statements",    -- Statements

        pvPatientRow."Email",         -- Email

        pvPatientRow."IsTrustedAudit",-- IsTrustedAudit  -- SF-00134678

        pvPatientRow."Sin"            -- Sin             -- SF-00134678

      );

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' resphis rows inserted.',vParams);



      -- Create Patient2 Record

      AddPatient2_P(pvPatientRow."Patient",vParams);



      -- Create PtGuar Record

      UpdatePtGuar_P(pFamily,pvPatientRow."Patient",pPtGuarRow,vParams);



      -- Add City Record

      vCityRow."Postal" := pvPatientRow."Postal";

      vCityRow."City" := pvPatientRow."City";

      vCityRow."Province" := pvPatientRow."Province";

      vCityRow."AddressOther" := pvPatientRow."AddressOther";

      AddCity_P(vSuccess,vMessage,vCityRow,vCountry,vParams);

    else

      raise no_data_found;

    end if;

    pvSuccess := true;

  exception

    when no_data_found then

      ax_pkg.AppendString_P(pvMessage,'Patient First and Last name are required.',' ',ax_pkg.MSG_ERROR,vParams);

  end InsertGuarantor_P;





  -- Insert Patient Record for a Guarantor

  --   Overload

  PROCEDURE insertguarantor_p(INOUT pvpatientrow patient, IN pfamily numeric, IN pptguarrow ptguar, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vSuccess boolean;

    vMessage  VARCHAR2(4000);

  begin

    InsertGuarantor_P(vSuccess,vMessage,pvPatientRow,pFamily,pPtGuarRow,pParams);

    if not vSuccess then

      raise_application_error(-20000, vMessage);

    end if;

  end InsertGuarantor_P;





  -- Get the next available chart number

  FUNCTION getnextchart_f(pprefix character varying DEFAULT NULL::character varying, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN character IS

    pragma autonomous_transaction;

    vChartNum char(10) := '0';

    vNewChart char(10);

    vValidChart boolean := false;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    -- Get the current max chart

    if (trim(pPrefix) is null OR length(trim(pPrefix)) = 0) then

      select patient."Chart" into vChartNum from patient where patient."Patient" =

       (select max(p."Patient") from patient p where (trim(translate(p."Chart", '0123456789', ' ')) is null OR length(trim(translate(p."Chart", '0123456789', ' '))) = 0) and p."Patient" = p."Family");

    else

      begin

        select substr(patient."Chart",length(pPrefix)+1) into vChartNum from patient where patient."Patient" =

--         (select max(p."Patient") from patient p where p."Chart" like pPrefix || '%' and p."Patient" = p."Family");  --Feb 22, 2021 replaced with following line

         (select max(p."Patient") from patient p where p."Chart" like pPrefix || '%' and length(trim(p."Chart")) > length(trim(pPrefix)) 

            and (trim(translate(substr("Chart", length(pPrefix)+1, length("Chart")-1), '0123456789', ' ')) is null OR length(trim(translate(substr("Chart", length(pPrefix)+1, length("Chart")-1), '0123456789', ' '))) = 0) and p."Patient" = p."Family");

        if trim(vChartNum) is null then

          vChartNum := 0;

        end if;

      exception

        when no_data_found then

          vChartNum := 0;

      end;

    end if;



    -- find the next available chart

    while not vValidChart loop

      begin

        vChartNum := vChartNum + 1;

        vNewChart := rpad(trim(pPrefix) || to_char(vChartNum),10);

        -- check patient table

        begin

          select "Chart" into vNewChart from patient where "Chart" = vNewChart;

          vValidChart := false;

        exception

          when no_data_found then

            -- check propcid2 table

            begin

              select "ChartId" into vNewChart from propcid2 where "ChartId" = vNewChart;

              vValidChart := false;

            exception

              when no_data_found then

                -- insert into propcid2 table, and save right away to mark the chart as in use

                insert into propcid2 values (vNewChart);

                ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' propcid2 rows inserted.',vParams);

                commit;

                vValidChart := true;

            end; -- check propcid table

        end; -- check patient table

      end;

    end loop;



    ax_pkg.dbmsoutput_P(ax_pkg.MSG_INFO,'Next Chart Number: ' || vNewChart,vParams);



    return vNewChart;

  end GetNextChart_F;



  -- Returns True if pPatient exists.

  FUNCTION patientexists_f(INOUT pvmessage character varying, ppatient numeric, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN boolean IS

    vExists number;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    select 1 into vExists from patient where "Patient" = pPatient and "Deleted" = 0;

    return true;

  exception

    when no_data_found then

      ax_pkg.AppendString_P(pvMessage,ax_lang_pkg.IDS_PATIENTNOTFOUND,' ',ax_pkg.MSG_ERROR,vParams);

      return false;

    when too_many_rows then

      ax_pkg.AppendString_P(pvMessage,ax_lang_pkg.IDS_TOOMANYPATIENTSFOUND,' ',ax_pkg.MSG_ERROR,vParams);

      return false;

  end PatientExists_F;





  -- returns True if pPatient has no open appointments

  FUNCTION noappointments_f(INOUT pvmessage character varying, ppatient numeric, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN boolean IS

    vExists number;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    select

      1 into vExists

    from

      appoint a

    where

      a."Patient" = pPatient and

      (a."Date" >= sysdate or a."Type" = 3) and

      a."Type" not in (6,7) and

      (a."Type" not in (8,9) or a."Status" != 2)

    ;

    ax_pkg.AppendString_P(pvMessage,ax_lang_pkg.IDS_PATIENTHASAPPOINTMENT,' ',ax_pkg.MSG_ERROR,vParams);

    return false;

  exception

    when no_data_found then

      return true;

    when too_many_rows then

      ax_pkg.AppendString_P(pvMessage,ax_lang_pkg.IDS_PATIENTHASAPPOINTMENT,' ',ax_pkg.MSG_ERROR,vParams);

      return false;

  end NoAppointments_F;





  -- returns True if pPatient has no Transactions from today

  FUNCTION notransactionstoday_f(INOUT pvmessage character varying, ppatient numeric, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN boolean IS

    vExists number;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    select 1 into vExists from trx where "Patient" = pPatient and trunc("Date") = trunc(sysdate) and "Deleted" = 0;

    ax_pkg.AppendString_P(pvMessage,ax_lang_pkg.IDS_PATIENTHASTRX,' ',ax_pkg.MSG_ERROR,vParams);

    return false;

  exception

    when no_data_found then

      return true;

    when too_many_rows then

      ax_pkg.AppendString_P(pvMessage,ax_lang_pkg.IDS_PATIENTHASTRX,' ',ax_pkg.MSG_ERROR,vParams);

      return false;

  end NoTransactionsToday_F;





  -- returns True if pPatient has items that still need approval

  FUNCTION hasunapproveditems_f(INOUT pvmessage character varying, ppatient numeric, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN boolean IS

    vExists number;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    --  Note that this differs from the axiUm check, which would have been:

    --    select "Patient" into vPatientId from chartlnk where "Patient" = pPatient;

    select 1 into vExists from unapproveditems_view where "PATIENT" = pPatient;

    ax_pkg.AppendString_P(pvMessage,ax_lang_pkg.IDS_PATIENTHASCHARTLNK,' ',ax_pkg.MSG_ERROR,vParams);

    return true;

  exception

    when no_data_found then

      return false;

    when too_many_rows then

      ax_pkg.AppendString_P(pvMessage,ax_lang_pkg.IDS_PATIENTHASCHARTLNK,' ',ax_pkg.MSG_ERROR,vParams);

      return true;

  end HasUnapprovedItems_F;





-- returns True if pPatient is a Guarantor

  FUNCTION isguarantor_f(INOUT pvmessage character varying, ppatient numeric, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN boolean IS

    vExists number;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    select 1 into vExists from ptguar p where p."RespPatient" = pPatient and p."Patient" != pPatient and p."Deleted" = 0 and p."Inactive" = 0;

    ax_pkg.AppendString_P(pvMessage,ax_lang_pkg.IDS_PATIENTHASPTGUAR,' ',ax_pkg.MSG_ERROR,vParams);

    return true;

  exception

    when no_data_found then

      return false;

    when too_many_rows then

      ax_pkg.AppendString_P(pvMessage,ax_lang_pkg.IDS_PATIENTHASPTGUAR,' ',ax_pkg.MSG_ERROR,vParams);

      return true;

  end IsGuarantor_F;





-- returns the patient and insurance overall Balance

  FUNCTION getoverallbalance_f(ppatient numeric, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN numeric IS

    vBalance number;

  begin

    select

      nvl(sum(decode(T."Type",3,T."Payed",T."Total")),0)

    into

      vBalance

    from

      TRX T

    where

      T."Family" = pPatient

      and T."Type" in (1,2,3,6,7,73,74)

      and T."Deleted" = 0

      and T."OrthoStatus" != 1;

    return vBalance;

  exception

    when no_data_found then

      return 0;

  end GetOverallBalance_F;





-- returns the patient Balance

  FUNCTION getpatientbalance_f(ppatient numeric, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN numeric IS

    vBalance number;

  begin

    select

      nvl(sum(decode(T."Type",3,T."Payed",T."Total"-T."InsTotal")),0)

    into

      vBalance

    from

      TRX T

    where

      T."Family" = pPatient

      and T."Type" in (1,2,3,6,7,73)

      and T."Deleted" = 0

      and T."OrthoStatus" != 1;

    return vBalance;

  exception

    when no_data_found then

      return 0;

  end;





  -- Find out if a patient record can be deleted safely

  -- parent

  FUNCTION candeletepatient_f(INOUT pvmessage character varying, ppatient numeric, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN boolean IS

    vPatientId patient."Patient"%type;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    -- Check Patient Exists

    if not PatientExists_F(pvMessage,pPatient,vParams) then

      return false;

    end if;



    -- Check Appointments

    if not NoAppointments_F(pvMessage,pPatient,vParams) then

      return false;

    end if;



    -- Check Transactions For Today

    if not NoTransactionsToday_F(pvMessage,pPatient,vParams) then

      return false;

    end if;



    -- Check Unapproved Items

    if HasUnapprovedItems_F(pvMessage,pPatient,vParams) then

      return false;

    end if;



    -- Check to see if patient is a Guarantor

    if IsGuarantor_F(pvMessage,pPatient,vParams) then

      return false;

    end if;



    -- Check Overall Balance

    if GetOverallBalance_F(pPatient,vParams) > 0 then

      ax_pkg.AppendString_P(pvMessage,ax_lang_pkg.IDS_PATIENTHASBALANCE,' ',ax_pkg.MSG_ERROR,vParams);

      return false;

    end if;



    -- Check Patient Balance

    if GetPatientBalance_F(pPatient,vParams) > 0 then

      ax_pkg.AppendString_P(pvMessage,ax_lang_pkg.IDS_PATIENTHASBALANCE,' ',ax_pkg.MSG_ERROR,vParams);

      return false;

    end if;



    -- Conditions not checked!!!!!!!!!!

    -- IDS_PATIENTHASBALANCE          VARCHAR2(50) := 'Cannot delete a patient with a balance'; -- may need a request to expose more information in ptbal_pkg

    --

    -- IDS_CANNOTDELETEACCOUNTHOLDER  VARCHAR2(50) := 'Cannot delete the account holder of a family';  -- does not seem to be referenced in axiUm

    -- IDS_PERSONHASBALANCE           VARCHAR2(50) := 'Cannot delete. This person has a transaction on file';  -- does not seem to be referenced in axiUm



    return true;

  end CanDeletePatient_F;





  -- Find out if a patient record can be deleted safely

  -- overload

  FUNCTION candeletepatient_f(ppatient numeric, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN boolean IS

    vMessage  VARCHAR2(75);

  begin

    return CanDeletePatient_F(vMessage,pPatient,pParams);

  end CanDeletePatient_F;





  -- Find out if a patient record can be deleted safely

  -- overload

  FUNCTION candeletepatient_f(INOUT pvmessage character varying, pchart character, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN boolean IS

    vPatientId patient."Patient"%type;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    select "Patient" into vPatientId from patient where "Chart" = pChart;

    return CanDeletePatient_F(pvMessage,vPatientId);

  exception

    when no_data_found then

      ax_pkg.AppendString_P(pvMessage,ax_lang_pkg.IDS_PATIENTNOTFOUND,' ',ax_pkg.MSG_ERROR,vParams);

      return false;

    when too_many_rows then

      ax_pkg.AppendString_P(pvMessage,ax_lang_pkg.IDS_TOOMANYCHARTSFOUND,' ',ax_pkg.MSG_ERROR,vParams);

      return false;

  end CanDeletePatient_F;





  -- Delete a patient - calls CanDeletePatient_F then deletes the patient as per axiUm rules if it passes the checks

  -- parent

  PROCEDURE deletepatient_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vCanDelete boolean;

    vAuditRow audithis%rowtype;

    vParams ax_pkg.tParams := pParams;

    -- P189-157650 Added cursors and variables to handle deleting of iaccess records

    cursor curiUser is

      select * from iuser where "Type" = 0 and "Id" = pPatient;

    cursor curiAccess(piUser iuser."iUser"%type) is

      select ctid from iaccess where ("iUser" = piUser or "RespiUser" = piUser) and "Deleted" = 0;

    viUserAudit iUser."Audit"%type;

    viAccessAudit iAccess."Audit"%type;

    viUserCount number := 0;

    viAccessCount number := 0;

  begin

    ax_pkg.InitializeParams_P(vParams);

    pvSuccess := false;

    if vParams."VerifyLevel" >= ax_pkg.VERIFY_ERRORS then

      -- Check to make sure the patient can be deleted

      vCanDelete := CanDeletePatient_F(pvMessage,pPatient,vParams);

    else

      vCanDelete := true;

    end if;



    -- if they can be, continue

    if vCanDelete then

      vAuditRow."TableName" := 'PATIENT';

      vAuditRow."HistoryType" := ax_pkg.AUDIT_DELETE;

      ax_pkg.CreateAuditHis_P(vAuditRow,vParams);



      -- Mark Patient Record as Deleted

      update patient

      set

        "Deleted" = '1',

        "User" = vParams."User",

        "StationId" = vParams."StationId",

        "Audit" = vAuditRow."Audit"

      where

        "Patient" = pPatient;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' patient rows updated.',vParams);



      -- Update Patient History

      update pathis

      set

        "PtDeleteFlag" = 1

      where

        "Patient" = pPatient AND

        "Audit" = vAuditRow."Audit";

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' pathis rows updated.',vParams);



      -- Delete Employment Records

      update ptemploy

      set

        "Deleted" = 1,

        "Date" = trunc(sysdate),

        "Time" = trunc(to_char(sysdate, 'SSSSS')/60),

        "User" = vParams."User",

        "StationId" = vParams."StationId"

      where

        "Patient" = pPatient AND

        "Deleted" = 0;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptemploy rows updated.',vParams);



      -- Delete Patient Insurance Policy Records

      update ptpol

      set

        "Deleted" = 1,

        "Date" = trunc(sysdate),

        "Time" = trunc(to_char(sysdate, 'SSSSS')/60),

        "User" = vParams."User",

        "StationId" = vParams."StationId",

        "SharedEntryId" = policy_SharedEntryId_seq.nextval

      where

        "Patient" = pPatient AND

        "Deleted" = 0;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptpol rows updated.',vParams);



      -- Delete Provider Assignments

      update ptprod

      set

        ptprod."EndDate" = trunc(sysdate) - 1

      where

        ptprod."Patient" = pPatient AND

        ptprod."Deleted" = 0;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptprod rows updated.',vParams);



      vAuditRow."TableName" := 'PTGUAR';

      vAuditRow."HistoryType" := ax_pkg.AUDIT_DELETE;

      ax_pkg.CreateAuditHis_P(vAuditRow,vParams);



      -- Delete Guarantors

      update ptguar

      set

        "Deleted" = 1,

        "Audit" = vAuditRow."Audit"

      where

        "Patient" = pPatient;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptguar rows updated.',vParams);



      -- P189-157650 Delete Guarantor access PatientAccess Record and change deletion of iUser record so that it adds an audit and does not delete records that are already deleted

      for ciUser in curiUser loop

      

        for ciAccess in curiAccess (ciUser."iUser") loop



          if viAccessAudit is null then

            vAuditRow."TableName" := 'IACCESS';

            vAuditRow."HistoryType" := ax_pkg.AUDIT_DELETE;

            ax_pkg.CreateAuditHis_P(vAuditRow,vParams);

            viAccessAudit := vAuditRow."Audit";

          end if;



          update iaccess set "Deleted" = 1, "Audit"=viAccessAudit where ctid = ciAccess.ctid;

          viAccessCount := viAccessCount + sql%rowcount;



        end loop;

        

        if ciUser."Deleted" = 0 then

        

          if viUserAudit is null then

            vAuditRow."TableName" := 'IUSER';

            vAuditRow."HistoryType" := ax_pkg.AUDIT_DELETE;

            ax_pkg.CreateAuditHis_P(vAuditRow,vParams);

            viUserAudit := vAuditRow."Audit";

          end if;



          update iuser set "Deleted" = 1, "Audit" = viUserAudit where "iUser" = ciUser."iUser";

          viUserCount := viUserCount + sql%rowcount;

        

        end if;



      end loop;

      

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(viAccessCount) || ' iaccess rows updated.',vParams);



      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(viUserCount) || ' iuser rows updated.',vParams);



      -- Removed from Selected list

      delete

        selected

      where

        selected."Patient" = pPatient;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' rows deleted from selected.',vParams);



      pvSuccess := true;

    end if; -- if vCanDelete

  exception

    when no_data_found then

      null;

  end DeletePatient_P;





  -- Delete a patient - calls CanDeletePatient_F then deletes the patient as per axiUm rules if it passes the checks

  -- overload

  PROCEDURE deletepatient_p(IN ppatient numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vMessage  VARCHAR2(75);

    vSuccess boolean;

  begin

    DeletePatient_P(vSuccess, vMessage, pPatient, pParams);

    if not vSuccess then

      raise_application_error(-20000, vMessage);

    end if;

  end DeletePatient_P;





  -- Delete a patient - calls CanDeletePatient_F then deletes the patient as per axiUm rules if it passes the checks

  -- overload

  PROCEDURE deletepatient_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN pchart character, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vPatientId patient."Patient"%type;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    select "Patient" into vPatientId from patient where "Chart" = pChart;

    DeletePatient_P(pvSuccess, pvMessage, vPatientId, vParams);

  exception

    when no_data_found then

      ax_pkg.AppendString_P(pvMessage,ax_lang_pkg.IDS_PATIENTNOTFOUND,' ',ax_pkg.MSG_ERROR,vParams);

      pvSuccess := false;

    when too_many_rows then

      ax_pkg.AppendString_P(pvMessage,ax_lang_pkg.IDS_TOOMANYCHARTSFOUND,' ',ax_pkg.MSG_ERROR,vParams);

      pvSuccess := false;

  end DeletePatient_P;





  -- Undelete a patient

  -- parent

  PROCEDURE undeletepatient_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vDeleteDate date;

    vCanUndelete number := 0;

    vAuditRow audithis%rowtype;

    vDeletedAudit audithis."Audit"%type := null;

    exNotDeleted exception;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    -- Check to make sure the patient can be undeleted

    begin

      select 1 into vCanUndelete from patient where "Patient" = pPatient and "Deleted" = 1;

    exception

      when no_data_found then

        raise exNotDeleted;

    end;



    -- Find out what date the patient was deleted

    begin

      select

        "Date"

      into

        vDeleteDate

      from

        audithis

      where

        "TableName" = 'PATIENT' and

        "HistoryType" = ax_pkg.AUDIT_DELETE and

        "Audit" = (select max("Audit") from pathis where "Patient" = pPatient and "PtDeleteFlag" = 1) and

        rownum = 1

      order by

        "Date" desc, "Time" desc;

    exception

      when no_data_found then

        null;

    end;



    -- if they can be, continue

    if vCanUndelete = 1 then



      vAuditRow."TableName" := 'PATIENT';

      vAuditRow."HistoryType" := ax_pkg.AUDIT_EDIT;

      ax_pkg.CreateAuditHis_P(vAuditRow,vParams);

      -- Mark Patient Record as Deleted

      update patient

      set

        "Deleted" = '0',

        "User" = vParams."User",

        "StationId" = vParams."StationId",

        "Audit" = vAuditRow."Audit"

      where

        "Patient" = pPatient;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' patient rows updated.',vParams);



      -- Undelete Employment Records

      update ptemploy

      set

        "Deleted" = 0,

        "Date" = trunc(sysdate),

        "Time" = trunc(to_char(sysdate, 'SSSSS')/60),

        "User" = vParams."User",

        "StationId" = vParams."StationId"

      where

        "Patient" = pPatient and

        "Deleted" = 1 and

        trunc("Date") = trunc(vDeleteDate);

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptemploy rows updated.',vParams);



      -- Undelete Patient Insurance Policy Records

      update ptpol

      set

        "Deleted" = 0,

        "Date" = trunc(sysdate),

        "Time" = trunc(to_char(sysdate, 'SSSSS')/60),

        "User" = vParams."User",

        "StationId" = vParams."StationId",

        "SharedEntryId" = policy_SharedEntryId_seq.nextval

      where

        "Patient" = pPatient and

        "Deleted" = 1 and

        trunc("Date") = trunc(vDeleteDate);

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptpol rows updated.',vParams);



      vAuditRow."TableName" := 'PTGUAR';

      vAuditRow."HistoryType" := ax_pkg.AUDIT_EDIT;

      ax_pkg.CreateAuditHis_P(vAuditRow,vParams);



      select

        max(ah."Audit") into vDeletedAudit

      from

        audithis ah

        inner join ptguar pg on pg."Audit" = ah."Audit" and pg."Patient" = pPatient and "Deleted" = 1;



      -- Undelete Guarantors

      update ptguar

      set

        "Deleted" = 0,

        "Audit" = vAuditRow."Audit"

      where

        "Patient" = pPatient and

        "Deleted" = 1 and

        "Audit" = vDeletedAudit;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptguar rows updated.',vParams);



      pvSuccess := true;

    else

      pvSuccess := false;

    end if; -- if vCanUnDelete



    ax_pkg.dbmsoutput_P(ax_pkg.MSG_WARNING,

      'Patient may have had Provider Assignments, or Internet Access before they were deleted. That data has not been restored.',vParams);



  exception

    when exNotDeleted then

      pvSuccess := false;

      ax_pkg.AppendString_P(pvMessage,'Deleted Patient Not Found.',' ',ax_pkg.MSG_ERROR,vParams);

  end UndeletePatient_P;





  -- Undelete a patient

  -- overload

  PROCEDURE undeletepatient_p(IN ppatient numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vMessage  VARCHAR2(75);

    vSuccess boolean;

  begin

    UndeletePatient_P(vSuccess, vMessage, pPatient, pParams);

    if not vSuccess then

      raise_application_error(-20000, vMessage);

    end if;

  end UndeletePatient_P;





  -- Undelete a patient

  -- overload

  PROCEDURE undeletepatient_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN pchart character, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vPatientId patient."Patient"%type;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    select "Patient" into vPatientId from patient where "Chart" = pChart;

    UndeletePatient_P(pvSuccess, pvMessage, vPatientId, vParams);

  exception

    when no_data_found then

      ax_pkg.AppendString_P(pvMessage,ax_lang_pkg.IDS_PATIENTNOTFOUND,' ',ax_pkg.MSG_ERROR,vParams);

      pvSuccess := false;

    when too_many_rows then

      ax_pkg.AppendString_P(pvMessage,ax_lang_pkg.IDS_TOOMANYCHARTSFOUND,' ',ax_pkg.MSG_ERROR,vParams);

      pvSuccess := false;

  end UndeletePatient_P;





  -- Change a patient status

  PROCEDURE changepatientstatus_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN pnewstatus character, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vExists number;

    vvAuditRow audithis%rowtype;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    pvSuccess := false;

    -- Validation

    if vParams."VerifyLevel" >= ax_pkg.VERIFY_ERRORS then

      begin

      -- Make sure that pNewStatus exists

        select 1 into vExists

        from status

        where

          "Status" = pNewStatus and

          "Type" = 2 and -- 2 = Patient

          "Inactive" = 0 and

          rownum = 1;

      exception

        when no_data_found then

          -- Status does not exist

          ax_pkg.AppendString_P(pvMessage,pNewStatus || ' is not a valid value patient status.',' ',ax_pkg.MSG_ERROR,vParams);

          return;

      end;

    end if;



    -- change the patient status

    update patient

    set

      "Status" = pNewStatus,

      "StatusStartDate" = trunc(sysdate),

      "Audit" = audithis_audit_seq.nextval,

      "User" = vParams."User",

      "StationId" = vParams."StationId"

    where 1=1

      and "Patient" = pPatient

      and "Status" != pNewStatus;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' patient rows updated.',vParams);



    -- if a record was updated create an audithis

    if sql%rowcount > 0 then

       select audithis_audit_seq.currval into  vvAuditRow."Audit" from dual;

       vvAuditRow."TableName" := 'PATIENT';

       vvAuditRow."HistoryType" := ax_pkg.AUDIT_UPDATE;

       ax_pkg.InsertAuditHis_P(vvAuditRow,vParams);

    end if;

    -- Note that this will return successful even if the patient already had that pNewStatus

    pvSuccess := true;

  end ChangePatientStatus_P;





   -- Change a patient status

    -- Overload

  PROCEDURE changepatientstatus_p(IN ppatient numeric, IN pnewstatus character, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vSuccess boolean;

    vMessage  VARCHAR2(4000);

  begin

    ChangePatientStatus_P(vSuccess,vMessage,pPatient,pNewStatus,pParams);

    if not vSuccess then

      raise_application_error(-20000, vMessage);

    end if;

  end ChangePatientStatus_P;





  -- Change a patient chart number from one value to another value

  PROCEDURE changechart_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN poldchart character, IN pnewchart character, IN pincludehistory boolean DEFAULT false, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vAuditRow audithis%rowtype;

    vExists number := 0;

    vChart  VARCHAR2(4000);

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    -- Verifications



    if vParams."VerifyLevel" >= ax_pkg.VERIFY_ERRORS then

      -- Make sure pPatient is found

      begin

        select 1 into vExists from patient where "Patient" = pPatient and trim(upper("Chart")) = upper(pOldChart);

      exception

        when no_data_found then

          ax_pkg.AppendString_P(pvMessage,'Patient record not found.',' ',ax_pkg.MSG_ERROR,vParams);

          pvSuccess := false;

          return;

      end;



      -- Make sure pNewChart patient is NOT found

      begin

        select "Patient" into vExists from patient where "Chart" = pNewChart;

        ax_pkg.AppendString_P(pvMessage,'Chart ' || pNewChart || ' in use.',' ',ax_pkg.MSG_ERROR,vParams);

        pvSuccess := false;

        return;

      exception

        when no_data_found then

          null;

      end;

    end if;



    -- Change pOldChart to pNewChart for pPatient



    -- patient.Chart

    vAuditRow."TableName" := 'PATIENT';

    vAuditRow."HistoryType" := ax_pkg.AUDIT_EDIT;

    ax_pkg.CreateAuditHis_P(vAuditRow,vParams);



    vChart := ax_pkg.CropToFieldSize_F(pNewChart,'patient','Chart');



    update patient

    set

      "Chart" = vChart,

      "User" = vParams."User",

      "StationId" = vParams."StationId",

      "Audit" = vAuditRow."Audit"

    where

      "Patient" = pPatient;



    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' patient rows updated.',vParams);



    -- request.Chart

    update request

    set

      "Chart" = vChart

    where

      "Patient" = pPatient;



    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' request rows updated.',vParams);



    -- Make it so that pPatients Chart was always pNewChart

    if not pIncludeHistory then



      -- patient2.ChartId

      update patient2

      set

        "ChartId" = vChart,

        "User" = vParams."User",

        "StationId" = vParams."StationId",

        "Date" = trunc(sysdate)

      where

        "PtxPId" = pPatient;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' patient2 rows updated.',vParams);



    else -- pIncludeHistory



      ax_pkg.dbmsoutput_P(ax_pkg.MSG_WARNING,'ax_patient_pkg.ChangeChart_P:' || ' Audit and History Records not created for all changes.',vParams);



      -- patient2.ChartId

      update patient2

      set

        "ChartId" = vChart

      where

        "PtxPId" = pPatient;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' patient2 rows updated.',vParams);



      -- pathis.Chart

      update pathis

      set

        "Chart" = vChart

      where

        "Chart" = pOldChart;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' pathis rows updated.',vParams);



      -- charthis.Chart

      update charthis

      set

        "Chart" = vChart

      where

        "Patient" = pPatient;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' charthis rows updated.',vParams);



      -- pat2his.ChartId

      update pat2his

      set

        "ChartId" = vChart

      where

        "ChartId" = pOldChart;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' pat2his rows updated.',vParams);

    end if; -- if pIncludeHistory



    pvSuccess := true;

  end ChangeChart_P;





  -- Change a patient chart number from one value to another value

  -- overload

  PROCEDURE changechart_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN poldchart character, IN pnewchart character, IN pincludehistory boolean DEFAULT false, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vPatient patient."Patient"%type;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    select "Patient" into vPatient from patient where "Chart" = pOldChart;

    ChangeChart_P(pvSuccess, pvMessage, vPatient, pOldChart, pNewChart, pIncludeHistory, vParams);

  exception

    when no_data_found then

      ax_pkg.AppendString_P(pvMessage,ax_lang_pkg.IDS_PATIENTNOTFOUND,' ',ax_pkg.MSG_ERROR,vParams);

      pvSuccess := false;

    when too_many_rows then

      ax_pkg.AppendString_P(pvMessage,ax_lang_pkg.IDS_TOOMANYCHARTSFOUND,' ',ax_pkg.MSG_ERROR,vParams);

      pvSuccess := false;

  end ChangeChart_P;





  -- Change a patient chart number from one value to another value

  -- overload

  PROCEDURE changechart_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN pnewchart character, IN pincludehistory boolean DEFAULT false, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vChart patient."Chart"%type;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    select "Chart" into vChart from patient where "Patient" = pPatient;

    ChangeChart_P(pvSuccess, pvMessage, pPatient, vChart, pNewChart, pIncludeHistory, vParams);

  exception

    when no_data_found then

      ax_pkg.AppendString_P(pvMessage,ax_lang_pkg.IDS_PATIENTNOTFOUND,' ',ax_pkg.MSG_ERROR,vParams);

      pvSuccess := false;

    when too_many_rows then

      ax_pkg.AppendString_P(pvMessage,ax_lang_pkg.IDS_TOOMANYCHARTSFOUND,' ',ax_pkg.MSG_ERROR,vParams);

      pvSuccess := false;

  end ChangeChart_P;





  -- This procedure updates the ptrace table for pPatient to the pRaceList provided, where pRaceList is a comma delimited list  

  PROCEDURE updaterace_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN pracelist character varying, IN pappendonly boolean DEFAULT false, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vAuditRow audithis%rowtype;

    vRemainingRaces  VARCHAR2(4000);

    vCurrentRace race."Race"%type;

    vPos number;    

    vExists number;

    vDeleted number;

    vValidRace number := 0;

    vEditCount number := 0;

    vAddCount number := 0;

  begin

    -- Warning Check

    if length(pRaceList) > 4000 then

      ax_pkg.AppendString_P(pvMessage,'pRaceList > 4000 Characters, some entries ignored.',true,' ',ax_pkg.MSG_WARNING,pParams);

      vRemainingRaces := substr(pRaceList,1,instr(pRaceList, ',',-1));

    else 

      vRemainingRaces := pRaceList;

    end if;

 

    -- Loop through the List of Races provided, adding or reinstating each one

    while NOT (trim(vRemainingRaces) is null OR length(trim(vRemainingRaces)) = 0) 

    loop

      vPos := instr(vRemainingRaces,',');

      if vPos = 0 then

        vCurrentRace := trim(ax_pkg.CropToFieldSize_F(vRemainingRaces,'race','Race'));

        vRemainingRaces := null;

      else

        vCurrentRace := trim(ax_pkg.CropToFieldSize_F(substr(vRemainingRaces,1,vPos - 1),'race','Race'));

        vRemainingRaces := substr(vRemainingRaces,vPos + 1);

      end if;

      

      vValidRace := 0;

      vExists := 0;

      vDeleted := 0;

      begin

        select 1 into vValidRace from race where trim("Race") = trim(vCurrentRace) and "Inactive" = 0 and rownum = 1;

        -- If this is reached, then the Race exists

        select 1 into vExists from ptrace where "Patient" = pPatient and trim("Race") = trim(vCurrentRace) and rownum = 1;

        -- If this is reached, then the patient already has this race

        select 1 into vDeleted from ptrace where "Patient" = pPatient and trim("Race") = trim(vCurrentRace) and "Deleted" = 1 and rownum = 1;

        -- If this is reached, then the patient had this race, but it was previously deleted

        if NOT (trim(vCurrentRace) is null OR length(trim(vCurrentRace)) = 0) then

          vAuditRow."TableName" := 'PTRACE';

          vAuditRow."HistoryType" := ax_pkg.AUDIT_EDIT;

          ax_pkg.CreateAuditHis_P(vAuditRow,pParams);            

          update ptrace

          set

            "Deleted" = 0,

            "Audit" = vAuditRow."Audit"

          where

            "Patient" = pPatient and

            trim("Race") = trim(vCurrentRace)

          ;

          vEditCount := vEditCount + 1;

        end if;

      exception

        when no_data_found then

          if vValidRace = 0 then

            -- If this is reached, then the Race is not valid

            ax_pkg.AppendString_P(pvMessage,trim(vCurrentRace) || ' is an invalid Race.',' ',ax_pkg.MSG_ERROR,pParams);

          elsif vExists = 0 and NOT (trim(vCurrentRace) is null OR length(trim(vCurrentRace)) = 0) then

            -- If this is reached, then the patient never had this Race

            vAuditRow."TableName" := 'PTRACE';

            vAuditRow."HistoryType" := ax_pkg.AUDIT_ADD;

            ax_pkg.CreateAuditHis_P(vAuditRow,pParams);                

            insert into ptrace (

              "Patient",

              "Race",

              "Deleted",

              "Audit"

            )

            values (

              pPatient,

              trim(vCurrentRace),

              0,

              vAuditRow."Audit"

            );

            vAddCount := vAddCount + 1;

          end if;

          -- If vExists = 1 then the patient already has this race AND it is currently active, so there is nothing to be done.

      end;      

    end loop; 

    if vEditCount > 0 then

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(vEditCount) || ' ptrace rows updated.',pParams);

    end if;

    if vAddCount > 0 then

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(vAddCount) || ' ptrace rows inserted.',pParams);

    end if;

     

    -- Delete any Races previously listed for the Patient

      -- This section is ignored if the list is a partial list

    if not pAppendOnly then

      begin

        select 

          1 into vExists 

        from

          ptrace 

        where

          "Patient" = pPatient and

          "Deleted" = 0 and

          upper(',' || pRaceList || ',') not like upper('%,' || trim("Race") || ',%') and

          rownum = 1

        ;        

        -- If this is reached, then there are Races that are listed for this patient that should not be

        vAuditRow."TableName" := 'PTRACE';

        vAuditRow."HistoryType" := ax_pkg.AUDIT_DELETE;

        ax_pkg.CreateAuditHis_P(vAuditRow,pParams);            

        update ptrace

        set

          "Deleted" = 1,

          "Audit" = vAuditRow."Audit"

        where

          "Patient" = pPatient and

          upper(',' || pRaceList || ',') not like upper('%,' || trim("Race") || ',%')

        ;

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptrace rows updated (deleted).');

      exception

        when no_data_found then

          -- If this is reached, there is nothing to delete

          null;

      end;

    end if; -- pIsPartialList

     

    pvSuccess := true;    

  end UpdateRace_P;





   -- This procedure updates the ptrace table for pPatient to the pRaceList provided, where pRaceList is a comma delimited list

     -- Overload

  PROCEDURE updaterace_p(IN ppatient numeric, IN pracelist character varying, IN pappendonly boolean DEFAULT false, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vSuccess boolean;

    vMessage  VARCHAR2(4000);

  begin

    UpdateRace_P(vSuccess,vMessage,pPatient,pRaceList,pAppendOnly,pParams);

  end UpdateRace_P;





  -- This function checks to see if pPatient has pAlert in any of the 5 patient.Alert fields

    -- Set pOnlyValid to false if you do not care if the alert is active or inactive, otherwise leave pOnlyValid as true

    --

    -- -2 is returned if pPatient is invalid

    -- -1 is returned if pAlert is invalid

    -- 0 is returned if the patient does not have pAlert

    -- 1-5 is returned if the patient has the alert, the number signifying which field number

    -- Additionally, the optional pvNextFree value is set to the first Null alert position

  FUNCTION haspatientalert_f(ppatient numeric, palert character, INOUT pvnextfree numeric, plocation numeric DEFAULT 0, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN numeric IS

    vReturn number;

    exOutOfRange exception;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    -- first check to ensure that pAlert is valid

    if vParams."VerifyLevel" >= ax_pkg.VERIFY_ERRORS then

      begin

        select 1 into vReturn

        from

          Alert

        where

          trim("Alert") = trim(pAlert) and

          "Inactive" = 0 and

          rownum = 1;

      exception

        when no_data_found then

          return -1;

      end;

    end if;



    -- If the alert is valid, then check to see if the patient has the alert

    begin

      if pLocation = 0 then

        select

          case

            when "Alert1" = pAlert then 1

            when "Alert2" = pAlert then 2

            when "Alert3" = pAlert then 3

            when "Alert4" = pAlert then 4

            when "Alert5" = pAlert then 5

            else 0

          end,

          case

            when (trim("Alert1") is null OR length(trim("Alert1")) = 0) then 1

            when (trim("Alert2") is null OR length(trim("Alert2")) = 0) then 2

            when (trim("Alert3") is null OR length(trim("Alert3")) = 0) then 3

            when (trim("Alert4") is null OR length(trim("Alert4")) = 0) then 4

            when (trim("Alert5") is null OR length(trim("Alert5")) = 0) then 5

            else -1

          end

        into

          vReturn,

          pvNextFree

        from

          patient

        where

          "Patient" = pPatient;

      elsif pLocation = 1 then

        select "Alert1" into vReturn from patient where "Patient" = pPatient;

        if vReturn is null then

          pvNextFree := pLocation;

        else

          pvNextFree := -1;

        end if;

      elsif pLocation = 2 then

        select "Alert2" into vReturn from patient where "Patient" = pPatient;

        if vReturn is null then

          pvNextFree := pLocation;

        else

          pvNextFree := -1;

        end if;

      elsif pLocation = 3 then

        select "Alert3" into vReturn from patient where "Patient" = pPatient;

        if vReturn is null then

          pvNextFree := pLocation;

        else

          pvNextFree := -1;

        end if;

      elsif pLocation = 4 then

        select "Alert4" into vReturn from patient where "Patient" = pPatient;

        if vReturn is null then

          pvNextFree := pLocation;

        else

          pvNextFree := -1;

        end if;

      elsif pLocation = 5 then

        select "Alert5" into vReturn from patient where "Patient" = pPatient;

        if vReturn is null then

          pvNextFree := pLocation;

        else

          pvNextFree := -1;

        end if;

      else

        raise exOutOfRange;

      end if;

      return vReturn;

    exception

      when exOutOfRange then

        ax_pkg.dbmsoutput_p(ax_pkg.MSG_ERROR,'Patient Alert Location Out of Range',vParams);

        return -3;

      when no_data_found then

        -- This would signify that the Patient does not exist

        return -2;

    end;

  end HasPatientAlert_F;





  -- Overload (this allows for pvNextFree to be an optional parameter)

  FUNCTION haspatientalert_f(ppatient numeric, palert character, plocation numeric DEFAULT 0, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN numeric IS

    vNextFree number;

  begin

    return HasPatientAlert_F(pPatient,pAlert,vNextFree,pLocation,pParams);

  end HasPatientAlert_F;





  -- Insert a Patient Alert into the next available position

  PROCEDURE insertpatientalert_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN palert character, IN plocation numeric DEFAULT 0, IN paudit numeric DEFAULT NULL::numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vHasAlert number;

    vNextFree number;

    vAuditRow audithis%rowtype;

    vSQL  VARCHAR2(255);

    vExists number;



  --         Sep 13, 2011 hlr Created

  -- E134008 Jan 29, 2011 am added check for invalid alert codes

  --         Dec 02, 2013 hlr Updated to use HasPatientAlert_F

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    -- Initilization

    pvSuccess := true;



    if vParams."VerifyLevel" >= ax_pkg.VERIFY_ERRORS then

      -- Do some initial error checks

      if pPatient is null then

        ax_pkg.AppendString_P(pvMessage,'No Patient id! - Alert: ' || pAlert || ' Patient: ' || pPatient,' ',ax_pkg.MSG_ERROR,vParams);

        pvSuccess := false;

        return;

      elsif ((vParams."User" is null or vParams."StationId" is null) and (pAudit is null)) then

        ax_pkg.AppendString_P(pvMessage,'No Audit id! - Alert: ' || pAlert || ' Patient: ' || pPatient,' ',ax_pkg.MSG_ERROR,vParams);

        pvSuccess := false;

        return;

      elsif (vParams."User" is null or vParams."StationId" is null) then

        begin

          -- If the User or StationId is null, but we have an AuditId, then get the User and Station from the audithis record

          select 1 into vExists from audithis where "Audit" = pAudit;

        exception

          when no_data_found then

            ax_pkg.AppendString_P(pvMessage,'audithis record not found! - Alert: ' || pAlert || ' Patient: ' || pPatient,' ',ax_pkg.MSG_ERROR,vParams);

            pvSuccess := false;

            return;

        end;

      end if;

    end if;



    -- Find out if the patient already has this alert

    vHasAlert := HasPatientAlert_F(pPatient,pAlert,vNextFree,pLocation,vParams);

    if vHasAlert = -2 then

        ax_pkg.AppendString_P(pvMessage,'Patient Not Found! - Alert: ' || pAlert || ' Patient: ' || pPatient,' ',ax_pkg.MSG_ERROR,vParams);

        pvSuccess := false;

        return;

    elsif vHasAlert = -1 then

      ax_pkg.AppendString_P(pvMessage,'Invalid or Inactivated Alert Entered! - Alert: ' || pAlert || ' Patient: ' || pPatient,' ',ax_pkg.MSG_ERROR,vParams);

      pvSuccess := false;

      return;

    elsif vHasAlert > 0 then

      if vParams."VerboseType" >= ax_pkg.MSG_INFO then

        ax_pkg.AppendString_P(pvMessage,'Patient Already has Alert! - Alert: ' || pAlert || ' Patient: ' || pPatient,' ',ax_pkg.MSG_INFO,vParams);

      end if;

      pvSuccess := true;

      return;

    elsif vNextFree = -1 then

      ax_pkg.AppendString_P(pvMessage,'No room for more alerts! - Alert: ' || pAlert || ' Patient: ' || pPatient,' ',ax_pkg.MSG_ERROR,vParams);

      pvSuccess := false;

      return;

    end if;



    -- The patient does not have the alert, time to add it

    if (pAudit is null) then

      vAuditRow."TableName" := 'PATIENT';

      vAuditRow."HistoryType" := ax_pkg.AUDIT_EDIT;

      ax_pkg.CreateAuditHis_P(vAuditRow,vParams);

    else

      vAuditRow."Audit" := pAudit;

    end if;

    vSQL := 'update patient set "Alert' || vNextFree || '" = ''' || pAlert ||

      ''', "Audit" = ' || vAuditRow."Audit" ||

      ', "StationId" = ' || vParams."StationId" ||

      ', "User" = ' || vParams."User" ||

      ' where "Patient" = ' || pPatient;

    execute immediate vSQL;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' patient rows updated.',vParams);

  end InsertPatientAlert_P;





  -- Insert a Patient Alert into the next available position

    -- Overload

  PROCEDURE insertpatientalert_p(IN ppatient numeric, IN palert character, IN plocation numeric DEFAULT 0, IN paudit numeric DEFAULT NULL::numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vSuccess boolean;

    vMessage  VARCHAR2(4000);

  begin

    InsertPatientAlert_P(vSuccess,vMessage,pPatient,pAlert,pLocation,pAudit,pParams);

    if not vSuccess then

      raise_application_error(-20000, vMessage);

    end if;

  end InsertPatientAlert_P;





  -- remove a patient alert from any existing position

  PROCEDURE removepatientalert_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN palert character, IN plocation numeric DEFAULT 0, IN paudit numeric DEFAULT NULL::numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vHasAlert number;

    vAuditRow audithis%rowtype;

    vSQL  VARCHAR2(255);

    vExists number;

  -- Function written March/22/2012

  --         Dec 02, 2013 hlr Updated to use HasPatientAlert_F

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    -- Initilization

    pvSuccess := true;



    -- Do some initial error checks

    if vParams."VerifyLevel" >= ax_pkg.VERIFY_ERRORS then

      if pPatient is null then

        ax_pkg.AppendString_P(pvMessage,'No Patient id! - Alert: ' || pAlert || ' Patient: ' || pPatient,' ',ax_pkg.MSG_ERROR,vParams);

        pvSuccess := false;

        return;

      elsif ((vParams."User" is null and vParams."StationId" is null) and (pAudit is null)) then

        ax_pkg.AppendString_P(pvMessage,'No Audit id! - Alert: ' || pAlert || ' Patient: ' || pPatient,' ',ax_pkg.MSG_ERROR,vParams);

        pvSuccess := false;

        return;

      elsif (vParams."User" is null or vParams."StationId" is null) then

        begin

          -- If the User or StationId is null, but we have an AuditId, then get the User and Station from the audithis record

          select 1 into vExists from audithis where "Audit" = pAudit;

        exception

          when no_data_found then

            ax_pkg.AppendString_P(pvMessage,'audithis record not found! - Alert: ' || pAlert || ' Patient: ' || pPatient,' ',ax_pkg.MSG_ERROR,vParams);

            pvSuccess := false;

            return;

        end;

      end if;

    end if;



    -- Find out if the patient already has this alert

    vHasAlert := HasPatientAlert_F(pPatient,pAlert,pLocation,vParams);

    if vHasAlert = -2 then

        ax_pkg.AppendString_P(pvMessage,'Patient Not Found! - Alert: ' || pAlert || ' Patient: ' || pPatient,' ',ax_pkg.MSG_ERROR,vParams);

        pvSuccess := false;

        return;

    elsif vHasAlert = -1 then

      ax_pkg.AppendString_P(pvMessage,'Invalid Alert Entered! - Alert: ' || pAlert || ' Patient: ' || pPatient,' ',ax_pkg.MSG_ERROR,vParams);

      pvSuccess := false;

      return;

    elsif vHasAlert = 0 then

      if vParams."VerboseType" >= ax_pkg.MSG_INFO then

        ax_pkg.AppendString_P(pvMessage,'Patient does not have Alert to remove! - Alert: ' || pAlert || ' Patient: ' || pPatient,' ',ax_pkg.MSG_INFO,vParams);

      end if;

      pvSuccess := true;

      return;

    end if;



    -- The patient does have the alert, time to remove it

    if (pAudit is null) then

      vAuditRow."TableName" := 'PATIENT';

      vAuditRow."HistoryType" := ax_pkg.AUDIT_EDIT;

      ax_pkg.CreateAuditHis_P(vAuditRow,vParams);

    else

      vAuditRow."Audit" := pAudit;

    end if;

    vSQL := 'update patient set "Alert' || vHasAlert || '" = ''' || '      ' ||

      ''', "Audit" = ' || vAuditRow."Audit" ||

      ', "StationId" = ' || vParams."StationId" ||

      ', "User" = ' || vParams."User" ||

      'where "Patient" = ' || pPatient;

    execute immediate vSQL;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' patient rows updated.',vParams);

  end RemovePatientAlert_P;





  -- Inserts or Removes a Patient Alert depending on if pCurrentValue equals pAddValue

  PROCEDURE updatepatientalert_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN palert character, IN pcurrentvalue character varying, IN paddvalue character varying, IN plocation numeric DEFAULT 0, IN paudit numeric DEFAULT NULL::numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

  begin

    if trim(upper(pCurrentValue)) = trim(upper(pAddValue))  then

      InsertPatientAlert_P(pvSuccess, pvMessage, pPatient, pAlert, pLocation, pAudit, pParams);

    else

      RemovePatientAlert_P(pvSuccess, pvMessage, pPatient, pAlert, pLocation, pAudit, pParams);

    end if;

  end UpdatePatientAlert_P;





  -- This function checks to see if pPatient has pOffice in any of the 5 patient.OfficeCode fields

    -- Set pOnlyValid to false if you do not care if the OfficeCode is active or inactive, otherwise leave pOnlyValid as true

    --

    -- -2 is returned if pPatient is invalid

    -- -1 is returned if pOffice is invalid

    -- 0 is returned if the patient does not have pOffice

    -- 1-5 is returned if the patient has the office code, the number signifying which field number

    -- Additionally, the optional pvNextFree value is set to the first Null office code position

  FUNCTION hasofficecode_f(ppatient numeric, poffice character, INOUT pvnextfree numeric, plocation numeric DEFAULT 0, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN numeric IS

    vReturn number;

    exOutOfRange exception;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    -- first check to ensure that pOffice is valid

    if vParams."VerifyLevel" >= ax_pkg.VERIFY_ERRORS then

      begin

        select 1 into vReturn

        from

          office

        where

          trim("Office") = trim(pOffice) and

          "Inactive" = 0 and

          rownum = 1;

      exception

        when no_data_found then

          return -1;

      end;

    end if;



    -- If the alert is valid, then check to see if the patient has the office code

    begin

      if pLocation = 0 then

        select

          case

            when "Office1" = pOffice then 1

            when "Office2" = pOffice then 2

            when "Office3" = pOffice then 3

            when "Office4" = pOffice then 4

            when "Office5" = pOffice then 5

            else 0

          end,

          case

            when (trim("Office1") is null OR length(trim("Office1")) = 0) then 1

            when (trim("Office2") is null OR length(trim("Office2")) = 0) then 2

            when (trim("Office3") is null OR length(trim("Office3")) = 0) then 3

            when (trim("Office4") is null OR length(trim("Office4")) = 0) then 4

            when (trim("Office5") is null OR length(trim("Office5")) = 0) then 5

            else -1

          end

        into

          vReturn,

          pvNextFree

        from

          patient

        where

          "Patient" = pPatient;

      elsif pLocation = 1 then

        select "Office1" into vReturn from patient where "Patient" = pPatient;

        if vReturn is null then

          pvNextFree := pLocation;

        else

          pvNextFree := -1;

        end if;

      elsif pLocation = 2 then

        select "Office2" into vReturn from patient where "Patient" = pPatient;

        if vReturn is null then

          pvNextFree := pLocation;

        else

          pvNextFree := -1;

        end if;

      elsif pLocation = 3 then

        select "Office3" into vReturn from patient where "Patient" = pPatient;

        if vReturn is null then

          pvNextFree := pLocation;

        else

          pvNextFree := -1;

        end if;

      elsif pLocation = 4 then

        select "Office4" into vReturn from patient where "Patient" = pPatient;

        if vReturn is null then

          pvNextFree := pLocation;

        else

          pvNextFree := -1;

        end if;

      elsif pLocation = 5 then

        select "Office5" into vReturn from patient where "Patient" = pPatient;

        if vReturn is null then

          pvNextFree := pLocation;

        else

          pvNextFree := -1;

        end if;

      else

        raise exOutOfRange;

      end if;

      return vReturn;

    exception

      when exOutOfRange then

        ax_pkg.dbmsoutput_p(ax_pkg.MSG_ERROR,'Office Code Location Out of Range',vParams);

        return -3;

      when no_data_found then

        -- This would signify that the Patient does not exist

        return -2;

    end;

  end HasOfficeCode_F;





  -- Overload (this allows for pvNextFree to be an optional parameter

  FUNCTION hasofficecode_f(ppatient numeric, poffice character, plocation numeric DEFAULT 0, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN numeric IS

    vNextFree number;

  begin

    return HasOfficeCode_F(pPatient,pOffice,vNextFree,pLocation,pParams);

  end HasOfficeCode_F;





  -- Insert an Office Code into the next available position

  PROCEDURE insertofficecode_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN poffice character, IN plocation numeric DEFAULT 0, IN paudit numeric DEFAULT NULL::numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vHasOfficeCode number;

    vAuditRow audithis%rowtype;

    vExists number;

    vNextFree number;

    vSQL  VARCHAR2(255);

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    -- Initilization

    pvSuccess := true;



    -- Do some initial error checks

    if vParams."VerifyLevel" >= ax_pkg.VERIFY_ERRORS then

      if pPatient is null then

        ax_pkg.AppendString_P(pvMessage,'No Patient id! - OfficeCode: ' || pOffice || ' Patient: ' || pPatient,' ',ax_pkg.MSG_ERROR,vParams);

        pvSuccess := false;

        return;

      elsif ((vParams."User" is null and vParams."StationId" is null) and (pAudit is null)) then

        ax_pkg.AppendString_P(pvMessage,'No Audit id! - OfficeCode: ' || pOffice || ' Patient: ' || pPatient,' ',ax_pkg.MSG_ERROR,vParams);

        pvSuccess := false;

        return;

      elsif (vParams."User" is null or vParams."StationId" is null) then

        begin

          -- If the User or StationId is null, but we have an AuditId, then get the User and Station from the audithis record

          select 1 into vExists from audithis where "Audit" = pAudit;

        exception

          when no_data_found then

            ax_pkg.AppendString_P(pvMessage,'audithis record not found! - Alert: ' || pOffice || ' Patient: ' || pPatient,' ',ax_pkg.MSG_ERROR,vParams);

            pvSuccess := false;

            return;

        end;

      end if;

    end if;



    -- Find out if the patient already has this Office Code

    vHasOfficeCode := HasOfficeCode_F(pPatient,pOffice,vNextFree,pLocation,vParams);

    if vHasOfficeCode = -2 then

        ax_pkg.AppendString_P(pvMessage,'Patient Not Found! - OfficeCode: ' || pOffice || ' Patient: ' || pPatient,' ',ax_pkg.MSG_ERROR,vParams);

        pvSuccess := false;

        return;

    elsif vHasOfficeCode = -1 then

      ax_pkg.AppendString_P(pvMessage,'Invalid or Inactivated OfficeCode Entered! - OfficeCode: ' || pOffice || ' Patient: ' || pPatient,' ',ax_pkg.MSG_ERROR,vParams);

      pvSuccess := false;

      return;

    elsif vHasOfficeCode > 0 then

      if vParams."VerboseType" >= ax_pkg.MSG_INFO then

        ax_pkg.AppendString_P(pvMessage,'Patient Already has OfficeCode! - OfficeCode: ' || pOffice || ' Patient: ' || pPatient,' ',ax_pkg.MSG_INFO,vParams);

      end if;

      pvSuccess := true;

      return;

    elsif vNextFree = -1 then

      ax_pkg.AppendString_P(pvMessage,'No room for more alerts! - OfficeCode: ' || pOffice || ' Patient: ' || pPatient,' ',ax_pkg.MSG_ERROR,vParams);

      pvSuccess := false;

      return;

    end if;



    -- The patient does not have the Office Code, time to add it

    if (pAudit is null) then

      vAuditRow."TableName" := 'PATIENT';

      vAuditRow."HistoryType" := ax_pkg.AUDIT_EDIT;

      ax_pkg.CreateAuditHis_P(vAuditRow,vParams);

    else

      vAuditRow."Audit" := pAudit;

    end if;

    vSQL := 'update patient set "Office' || vNextFree || '" = ''' || pOffice ||

      ''', "Audit" = ' || vAuditRow."Audit" ||

      ', "StationId" = ' || vParams."StationId" ||

      ', "User" = ' || vParams."User" ||

      ' where "Patient" = ' || pPatient;

    execute immediate vSQL;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' patient rows updated.',vParams);

  end InsertOfficeCode_P;





  -- remove a patient OfficeCode from any existing position

  PROCEDURE removeofficecode_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN poffice character, IN plocation numeric DEFAULT 0, IN paudit numeric DEFAULT NULL::numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vHasOfficeCode number;

    vAuditRow audithis%rowtype;

    vSQL  VARCHAR2(255);

    vExists number;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    -- Initilization

    pvSuccess := true;



    -- Do some initial error checks

    if vParams."VerifyLevel" >= ax_pkg.VERIFY_ERRORS then

      if pPatient is null then

        ax_pkg.AppendString_P(pvMessage,'No Patient id! - OfficeCode: ' || pOffice || ' Patient: ' || pPatient,' ',ax_pkg.MSG_ERROR,vParams);

        pvSuccess := false;

        return;

      elsif ((vParams."User" is null and vParams."StationId" is null) and (pAudit is null)) then

        ax_pkg.AppendString_P(pvMessage,'No Audit id! - OfficeCode: ' || pOffice || ' Patient: ' || pPatient,' ',ax_pkg.MSG_ERROR,vParams);

        pvSuccess := false;

        return;

      elsif (vParams."User" is null or vParams."StationId" is null) then

        begin

          -- If the User or StationId is null, but we have an AuditId, then get the User and Station from the audithis record

          select 1 into vExists from audithis where "Audit" = pAudit;

        exception

          when no_data_found then

            ax_pkg.AppendString_P(pvMessage,'audithis record not found! - Alert: ' || pOffice || ' Patient: ' || pPatient,' ',ax_pkg.MSG_ERROR,vParams);

            pvSuccess := false;

            return;

        end;

      end if;

    end if;



    -- Find out if the patient already has this Office Code

    vHasOfficeCode := HasOfficeCode_F(pPatient,pOffice,pLocation,vParams);

    if vHasOfficeCode = -2 then

        ax_pkg.AppendString_P(pvMessage,'Patient Not Found! - OfficeCode: ' || pOffice || ' Patient: ' || pPatient,' ',ax_pkg.MSG_ERROR,vParams);

        pvSuccess := false;

        return;

    elsif vHasOfficeCode = -1 then

      ax_pkg.AppendString_P(pvMessage,'Invalid OfficeCode Entered! - OfficeCode: ' || pOffice || ' Patient: ' || pPatient,' ',ax_pkg.MSG_ERROR,vParams);

      pvSuccess := false;

      return;

    elsif vHasOfficeCode = 0 then

      if vParams."VerboseType" >= ax_pkg.MSG_INFO then

        ax_pkg.AppendString_P(pvMessage,'Patient does not have OfficeCode to remove! - OfficeCode: ' || pOffice || ' Patient: ' || pPatient,' ',ax_pkg.MSG_INFO,vParams);

      end if;

      pvSuccess := true;

      return;

    end if;



    -- The patient does have the Office Code, time to remove it

    if (pAudit is null) then

      vAuditRow."TableName" := 'PATIENT';

      vAuditRow."HistoryType" := ax_pkg.AUDIT_EDIT;

      ax_pkg.CreateAuditHis_P(vAuditRow,vParams);

    else

      vAuditRow."Audit" := pAudit;

    end if;

    vSQL := 'update patient set "Office' || vHasOfficeCode || '" = ''' || '      ' ||

      ''', "Audit" = ' || vAuditRow."Audit" ||

      ', "StationId" = ' || vParams."StationId" ||

      ', "User" = ' || vParams."User" ||

      ' where "Patient" = ' || pPatient;

    execute immediate vSQL;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' patient rows updated.',vParams);

  end RemoveOfficeCode_P;





  -- Inserts or Removes an Office Code depending on if pCurrentValue equals pAddValue

  PROCEDURE updateofficecode_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN poffice character, IN pcurrentvalue character varying, IN paddvalue character varying, IN plocation numeric DEFAULT 0, IN paudit numeric DEFAULT NULL::numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

  begin

    if trim(upper(pCurrentValue)) = trim(upper(pAddValue))  then

      InsertOfficeCode_P(pvSuccess, pvMessage, pPatient,pOffice,pLocation,pAudit,pParams);

    else

      RemoveOfficeCode_P(pvSuccess, pvMessage, pPatient,pOffice,pLocation,pAudit,pParams);

    end if;

  end UpdateOfficeCode_P;





  -- Inserts a Patient Type

  PROCEDURE addpatienttype_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN ppattype character, IN paudit numeric DEFAULT NULL::numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vExists number;

    vAuditRow audithis%rowtype;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    -- make sure the patient type exists

    select "Inactive" into vExists from pattype where "PatType" = pPatType;



    if vExists = 1 then

      pvSuccess := false;

      ax_pkg.AppendString_P(pvMessage,'Patient Type is Inactive!',' ',ax_pkg.MSG_ERROR,vParams);

      return;

    end if;



    begin

      -- see if the patient already has the patient type

      select "Deleted" into vExists from pttypes where "Patient" = pPatient and "PatType" = pPatType;



      if vExists <> 0 then

        -- If the record exists, but is deleted, then undelete it

        if pAudit is not null then

          update pttypes set "Deleted" = 0, "Audit" = pAudit where "Patient" = pPatient and "PatType" = pPatType;

          ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' pttypes rows updated.',vParams);

        else

          vAuditRow."TableName" := 'PTTYPES';

          vAuditRow."HistoryType" := ax_pkg.AUDIT_EDIT;

          ax_pkg.CreateAuditHis_P(vAuditRow,vParams);



          update pttypes set "Deleted" = 0, "Audit" = vAuditRow."Audit" where "Patient" = pPatient and "PatType" = pPatType;

          ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' pttypes rows updated.',vParams);

        end if;

      else

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_INFO,'Patient ' || pPatient || ' already has pattype ' || pPatType || '.',vParams);

      end if;



    exception

      when no_data_found then

        if pAudit is not null then

          -- add the patient type

          insert into pttypes values (pPatient,pPatType,0,pAudit);

          ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' pttypes rows inserted.',vParams);

        elsif vParams."User" is not null and vParams."StationId" is not null then

          -- create audit history

          vAuditRow."TableName" := 'PTTYPES';

          vAuditRow."HistoryType" := ax_pkg.AUDIT_ADD;

          ax_pkg.CreateAuditHis_P(vAuditRow,vParams);

          -- add the patient type

          insert into pttypes values (pPatient,pPatType,0,vAuditRow."Audit");

          ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' pttypes rows inserted.',vParams);

        else

          ax_pkg.AppendString_P(pvMessage,'No Audit Information Supplied, Patient Type not added',' ',ax_pkg.MSG_ERROR,vParams);

          pvSuccess := false;

        end if;

    end;

  exception

    when no_data_found then

      pvSuccess := false;

      ax_pkg.AppendString_P(pvMessage,pPatType || ' is an Invalid Patient Type.',' ',ax_pkg.MSG_ERROR,vParams);

  end AddPatientType_P;





  -- Removes a Patient Type from a patient

  --  returns null if successful

  PROCEDURE removepatienttype_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN ppatient numeric, IN ppattype character, IN paudit numeric DEFAULT NULL::numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vExists number;

    vAuditRow audithis%rowtype;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    -- make sure the patient type exists

    select 1 into vExists from pattype where "PatType" = pPatType;



    -- Do not check Inactive state, because you may want to remove Inactive Patient Types



    begin

      -- see if the patient already has the patient type

      select "Deleted" into vExists from pttypes where "Patient" = pPatient and "PatType" = pPatType;



      -- if so, delete it

      if vExists = 0 then

        if pAudit is not null then

          -- delete the patient type

          update pttypes set "Deleted" = 1, "Audit" = pAudit where "Patient" = pPatient and "PatType" = pPatType;

          ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' pttypes rows updated.',vParams);

        elsif vParams."User" is not null and vParams."StationId" is not null then

          -- create audit history

          vAuditRow."TableName" := 'PTTYPES';

          vAuditRow."HistoryType" := ax_pkg.AUDIT_DELETE;

          ax_pkg.CreateAuditHis_P(vAuditRow,vParams);

          -- add the patient type

          update pttypes set "Deleted" = 1, "Audit" = vAuditRow."Audit" where "Patient" = pPatient and "PatType" = pPatType;

          ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' pttypes rows updated.',vParams);

        else

          ax_pkg.AppendString_P(pvMessage,'No Audit Information Supplied, Patient Type not deleted',' ',ax_pkg.MSG_ERROR,vParams);

          pvSuccess := false;

        end if;

      else

        -- record exists, but it is already deleted

         null;

      end if;

    exception

      when no_data_found then

        -- patient type does not exist to delete, do nothing

        null;

    end;

  exception

    when no_data_found then

      pvSuccess := false;

      ax_pkg.AppendString_P(pvMessage,pPatType || ' is an Invalid Patient Type.',' ',ax_pkg.MSG_ERROR,vParams);

  end RemovePatientType_P;





  -- Add City, but Only if it does not exist already

  --  Update City,Province,AddressOther if it does exist

  --  Returns a message if any errors encountered (or null if successful)

  PROCEDURE addcity_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, INOUT pvcityrow city, INOUT pvcountry character, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    exStringTooLong exception;

    -- Map custom Exception to ORA Error

    pragma exception_init(exStringTooLong, -1461);

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    pvSuccess := false;



    if NOT (trim(pvCityRow."Postal") is null OR length(trim(pvCityRow."Postal")) = 0) 

            and NOT (trim(pvCityRow."City") is null OR length(trim(pvCityRow."City")) = 0) then

      begin

        select

          "City", "Province", "AddressOther"

        into

          pvCityRow."City", pvCityRow."Province", pvCityRow."AddressOther"

        from

          City

        where

          trim(upper("Postal")) = trim(upper(pvCityRow."Postal")) and

          trim(upper("City")) = trim(upper(pvCityRow."City"));



        begin

          if NOT (trim(pvCityRow."Province") is null OR length(trim(pvCityRow."Province")) = 0) then

            select

              "Country"

            into

              pvCountry

            from

              province

            where

              "Province" = pvCityRow."Province";

          end if;

        exception

          when no_data_found then

            if NOT (trim(pvCountry) is null OR length(trim(pvCountry)) = 0) then

              insert into province

                ("Province","Description","Country")

              values

                (

                  ax_pkg.CropToFieldSize_F(pvCityRow."Province",'province','Province'),

                  ax_pkg.CropToFieldSize_F(pvCityRow."Province",'province','Description'),

                  ax_pkg.CropToFieldSize_F(pvCountry,'province','Country')

                );

              ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' province rows inserted.',vParams);

            end if;

        end;



        pvSuccess := true;



      exception

        when no_data_found then

          insert into city values pvCityRow;

          ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' city rows inserted.',vParams);

          pvSuccess := true;

        when too_many_rows then

          ax_pkg.AppendString_P(pvMessage,'Too many cities found for Postal Code: ' || trim(pvCityRow."Postal"),' ',ax_pkg.MSG_ERROR,vParams);

      end;

    elsif NOT (trim(pvCityRow."Postal") is null OR length(trim(pvCityRow."Postal")) = 0) then

      begin

        select

          "City", "Province", "AddressOther"

        into

          pvCityRow."City", pvCityRow."Province", pvCityRow."AddressOther"

        from

          City

        where

          trim(upper("Postal")) = trim(upper(pvCityRow."Postal"));



        begin

        if NOT (trim(pvCityRow."Province") is null OR length(trim(pvCityRow."Province")) = 0) then

            select

              "Country"

            into

              pvCountry

            from

              province

            where

              "Province" = pvCityRow."Province";

          end if;

        exception

          when no_data_found then

            if NOT (trim(pvCountry) is null OR length(trim(pvCountry)) = 0) then

              insert into province

                ("Province","Description","Country")

              values

                (

                  ax_pkg.CropToFieldSize_F(pvCityRow."Province",'province','Province'),

                  ax_pkg.CropToFieldSize_F(pvCityRow."Province",'province','Description'),

                  ax_pkg.CropToFieldSize_F(pvCountry,'province','Country')

                );

              ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' province rows inserted.',vParams);

            end if;

        end;

        pvSuccess := true;



      exception

        when no_data_found then

          ax_pkg.AppendString_P(pvMessage,'Not enough information to add City for Postal Code: ' || trim(pvCityRow."Postal"),' ',ax_pkg.MSG_ERROR,vParams);

        when too_many_rows then

          ax_pkg.AppendString_P(pvMessage,'Too many cities found for Postal Code: ' || trim(pvCityRow."Postal"),' ',ax_pkg.MSG_ERROR,vParams);

      end;

    else

      ax_pkg.AppendString_P(pvMessage,'No Postal Code Provided',' ',ax_pkg.MSG_ERROR,vParams);

    end if;

  exception

    when exStringTooLong then

      ax_pkg.AppendString_P(pvMessage,'Error:String Too Long (more than 4000 Characters)',' ',ax_pkg.MSG_ERROR,vParams);

      pvSuccess := false;

  end AddCity_P;





  -- overload to make pvCountry optional

  PROCEDURE addcity_p(INOUT pvcityrow city, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vSuccess boolean;

    vMessage  VARCHAR2(4000);

    vCountry province."Country"%type;

  begin

    AddCity_P(vSuccess,vMessage,pvCityRow,vCountry,pParams);

    if not vSuccess then

      raise_application_error(-20000, vMessage);

    end if;

  end AddCity_P;





  -- Inititalize an Employer Record

  PROCEDURE initializeemployer_p(INOUT pvemployerrow employer) IS

  begin

    pvEmployerRow."Employer" := null;

    pvEmployerRow."Name" := ' ';

    pvEmployerRow."Address1" := ' ';

    pvEmployerRow."Address2" := ' ';

    pvEmployerRow."AddressOther" := ' ';

    pvEmployerRow."City" := ' ';

    pvEmployerRow."Province" := ' ';

    pvEmployerRow."Postal" := ' ';

    pvEmployerRow."Area" := ' ';

    pvEmployerRow."Telephone" := ' ';

    pvEmployerRow."Ext" := ' ';

    pvEmployerRow."Note" := ' ';

    pvEmployerRow."Deleted" := 0;

    pvEmployerRow."Audit" := 0;

  end InitializeEmployer_P;





  -- Add Employer, but Only if it does not exist already

  --  Sets pvEmployerId to a new Employer Id Value (if null or 0 and a new record added)

  PROCEDURE addemployer_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, INOUT pvemployerrow employer, IN ppatient numeric, IN pprimary numeric DEFAULT 1, IN pmatchonaddress boolean DEFAULT true, IN pupdate numeric DEFAULT 1, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vAuditRow audithis%rowtype;

    vCityRow city%rowtype;

    vPatient patient."Patient"%type;

    vCountry province."Country"%type;

    vReturn  VARCHAR2(50);

    vCitySuccess boolean;

    vUpdate boolean default true;

    exStringTooLong exception;

    -- Map custom Exception to ORA Error

    pragma exception_init(exStringTooLong, -1461);

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    pvSuccess := true;

    -- Error Checking

    if vParams."VerifyLevel" >= ax_pkg.VERIFY_ERRORS then

      if (trim(pvEmployerRow."Name") is null OR length(trim(pvEmployerRow."Name")) = 0) then

        ax_pkg.AppendString_P(pvMessage,'No Employer Name Provided',' ',ax_pkg.MSG_ERROR,vParams);

        pvSuccess := false;

        return;

      end if;



      if pvEmployerRow."Employer" is not null and pvEmployerRow."Employer" > 0 then

        begin

          select "Employer" into pvEmployerRow."Employer" from employer where "Employer" = pvEmployerRow."Employer" and "Deleted" = 0;

        exception

          when no_data_found then

            ax_pkg.AppendString_P(pvMessage,'Employer not found',' ',ax_pkg.MSG_ERROR,vParams);

            pvSuccess := false;

            return;

        end;

      end if;

    end if;



    -- Get Employer Id

    if pMatchOnAddress then

      begin

        select * into pvEmployerRow from

        (

          select * from employer

          where

            nvl(upper(trim("Name")), ' ') = nvl(upper(trim(pvEmployerRow."Name")), ' ') and

            nvl(upper(trim("Address1")), ' ') = nvl(upper(trim(pvEmployerRow."Address1")), ' ') and

            nvl(upper(trim("City")), ' ') = nvl(upper(trim(pvEmployerRow."City")), ' ') and

            nvl(upper(trim("Postal")), ' ') = nvl(upper(trim(pvEmployerRow."Postal")), ' ') and

            "Deleted" = 0

          order by

            "Employer"

        );

      exception

        when no_data_found then

          pvEmployerRow."Employer" := 0;

      end;

    else

      begin

        select * into pvEmployerRow from

        (

          select * from employer

          where

            trim("Name") = trim(pvEmployerRow."Name") and

            "Deleted" = 0

          order by

            "Employer"

        )

        where rownum = 1;

      exception

        when no_data_found then

          pvEmployerRow."Employer" := 0;

      end;

    end if;



    -- Add New Employer Record

    if pvEmployerRow."Employer" = 0 then



      -- Add City Record

      vCityRow."Postal" := pvEmployerRow."Postal";

      vCityRow."City" := pvEmployerRow."City";

      vCityRow."Province" := pvEmployerRow."Province";

      vCityRow."AddressOther" := pvEmployerRow."AddressOther";

      

      -- make sure required fields are set

      if NOT (trim(vCityRow."Postal") is null OR length(trim(vCityRow."Postal")) = 0) 

            and NOT (trim(vCityRow."City") is null OR length(trim(vCityRow."City")) = 0) then

        AddCity_P(vCitySuccess,pvMessage,vCityRow,vCountry,vParams);

      end if;



      pvEmployerRow."City" := nvl(pvEmployerRow."City",vCityRow."City");

      pvEmployerRow."Province" := nvl(pvEmployerRow."Province",vCityRow."Province");

      pvEmployerRow."AddressOther" := nvl(pvEmployerRow."AddressOther",vCityRow."AddressOther");



      -- get a new Employer Id

      select employer_employer_seq.nextval into pvEmployerRow."Employer" from dual;



      -- Create the Audit History

      vAuditRow."TableName" := 'EMPLOYER';

      vAuditRow."HistoryType" := ax_pkg.AUDIT_ADD;

      ax_pkg.CreateAuditHis_P(vAuditRow,vParams);

      -- Insert Employer

      pvEmployerRow."Audit" := vAuditRow."Audit";

      pvEmployerRow."Deleted" := 0;





      insert into employer values pvEmployerRow;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' employer rows inserted.',vParams);



      vUpdate := false;



    -- Update Employer Information - but only if this is the only Patient tied to that record

    elsif pUpdate = 1 then

      if pPatient <= 0 or pPatient is null then

        ax_pkg.AppendString_P(pvMessage,'No Patient Provided.',' ',ax_pkg.MSG_ERROR,vParams);

        pvSuccess := false;

        return;

      end if;



      begin

        select "Patient" into vPatient from ptemploy where "Employer"=pvEmployerRow."Employer" and "Deleted" = 0 and "Patient" <> pPatient and rownum=1;

        -- if this query does not fail, that means that there are other patients tied to this employer so we should not attempt to update.

        vUpdate := false;

      exception

        when no_data_found then

          -- continue!

          vUpdate := true;

      end;

    -- Update Employer Information

    elsif pUpdate = 2 then

      vUpdate := true;

    end if;



    if vUpdate then

      -- Add City Record

      vCityRow."Postal" := pvEmployerRow."Postal";

      vCityRow."City" := pvEmployerRow."City";

      vCityRow."Province" := pvEmployerRow."Province";

      vCityRow."AddressOther" := pvEmployerRow."AddressOther";

      

      -- make sure required fields are set

      if NOT (trim(vCityRow."Postal") is null OR length(trim(vCityRow."Postal")) = 0) 

            and NOT (trim(vCityRow."City") is null OR length(trim(vCityRow."City")) = 0) then

        AddCity_P(vCitySuccess,pvMessage,vCityRow,vCountry,vParams);

      end if;



      -- Create the Audit History

      vAuditRow."TableName" := 'PTTYPES';

      vAuditRow."HistoryType" := ax_pkg.AUDIT_EDIT;

      ax_pkg.CreateAuditHis_P(vAuditRow,vParams);

      -- Update Employer

      update employer set

        "Address1" = ax_pkg.CropToFieldSize_F(pvEmployerRow."Address1",'employer','Address1'),

        "Address2" = ax_pkg.CropToFieldSize_F(pvEmployerRow."Address2",'employer','Address2'),

        "AddressOther" = ax_pkg.CropToFieldSize_F(pvEmployerRow."AddressOther",'employer','AddressOther'),

        "City" = ax_pkg.CropToFieldSize_F(pvEmployerRow."City",'employer','City'),

        "Province" = ax_pkg.CropToFieldSize_F(pvEmployerRow."Province",'employer','Province'),

        "Postal" = ax_pkg.CropToFieldSize_F(pvEmployerRow."Postal",'employer','Postal'),

        "Area" = ax_pkg.CropToFieldSize_F(pvEmployerRow."Area",'employer','Area'),

        "Telephone" = ax_pkg.CropToFieldSize_F(pvEmployerRow."Telephone",'employer','Telephone'),

        "Ext" = ax_pkg.CropToFieldSize_F(pvEmployerRow."Ext",'employer','Ext'),

        "Note" = ax_pkg.CropToFieldSize_F(pvEmployerRow."Note",'employer','Note'),

        "Audit" = vAuditRow."Audit"

      where

        "Employer" = pvEmployerRow."Employer";

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' employer rows updated.',vParams);



    end if;



    if pPatient > 0 and pPatient is not null then

      -- Add Employment Record

      Polins_PKG.AddPatientEmployer(pPatient, pvEmployerRow."Employer",pPrimary,vParams."User",vParams."StationId");

    end if;



    pvSuccess := true;



  exception

    when exStringTooLong then

      ax_pkg.AppendString_P(pvMessage,'Error:String Too Long (more than 4000 Characters)',' ',ax_pkg.MSG_ERROR,vParams);

      pvSuccess := false;

  end AddEmployer_P;



END;
CREATE OR REPLACE PACKAGE BODY ax_pkg IS



 --** local **--



  -- Oracle compatibility function for raise_application_error

  PROCEDURE raise_application_error(IN error_number integer, IN message text, IN keep_errors boolean DEFAULT false) IS

  begin

    raise exception using errcode = error_number, message = message::varchar2;

  end raise_application_error;



  -- Overload for varchar2 messages

  PROCEDURE raise_application_error(IN error_number integer, IN message character varying, IN keep_errors boolean DEFAULT false) IS

  begin

    raise exception using errcode = error_number, message = message;

  end raise_application_error;



  -- This is a copy of OWA_UTIL.who_called_me

    -- Only for internal use in case the OWA_UTIL package is not available to the axium user  

   /*  NL_CHAR can be computed from a Unicode string in a portable manner. */

   nl_char CONSTANT character varying(10) DEFAULT chr(10);

   /* Constant is set here instead of owachars to avoid invalid objects */

   cr_char CONSTANT character varying(10) DEFAULT chr(13);

     /******************************************************************/

    /* Procedure to get owner and name of the PL/SQL procedure        */

   /******************************************************************/

  PROCEDURE who_called_me(OUT owner character varying, OUT name character varying, OUT lineno numeric, OUT caller_t character varying) IS

      call_stack   VARCHAR2(4096) default dbms_utility.format_call_stack;

      n           number;

      found_stack BOOLEAN default FALSE;

      line         VARCHAR2(255);

      t            VARCHAR2(255);

      cnt         number := 0;

  begin

  --

      loop

          n := instr( call_stack, NL_CHAR );

          exit when ( cnt = 3 or n is NULL or n = 0 );

  --

          line := ltrim(substr( call_stack, 1, n-1 ));

          call_stack := substr( call_stack, n+1 );

  --

          if ( NOT found_stack ) then

              if ( line like '%handle%number%name%' ) then

                  found_stack := TRUE;

              end if;

          else

              cnt := cnt + 1;

              -- cnt = 1 is ME

              -- cnt = 2 is MY Caller

              -- cnt = 3 is Their Caller

              if ( cnt = 3 ) then

                  -- Fix 718865

                  --lineno := to_number(substr( line, 13, 6 ));

                  --line   := substr( line, 21 );

                  n := instr(line, ' ');

                  if (n > 0)

                  then

                      t := ltrim(substr(line, n));

                      n := instr(t, ' ');

                  end if;

                  if (n > 0)

                  then

                     lineno := to_number(substr(t, 1, n - 1));

                     line := ltrim(substr(t, n));

                  else

                      lineno := 0;

                  end if;

                  if ( line like 'pr%' ) then

                      n := length( 'procedure ' );

                  elsif ( line like 'fun%' ) then

                      n := length( 'function ' );

                  elsif ( line like 'package body%' ) then

                      n := length( 'package body ' );

                  elsif ( line like 'pack%' ) then

                      n := length( 'package ' );

            else

                n := length( 'anonymous block ' );

                  end if;

            caller_t := ltrim(rtrim(upper(substr( line, 1, n-1 ))));

                  line := substr( line, n );

                  n := instr( line, '.' );

                  owner := ltrim(rtrim(substr( line, 1, n-1 )));

                  name  := ltrim(rtrim(substr( line, n+1 )));

              end if;

          end if;

      end loop;

  end who_called_me;

        

        

  --** public **--



  -- Add a new setting to the ax_setting table

  PROCEDURE addsetting_p(INOUT pvsettingrec ax_setting, IN poverridevalues boolean DEFAULT false, IN pparams tparams DEFAULT ax_pkg.ax_params) IS

    vSettingGroup ax_setting."axSettingGrp"%Type;

    vKey  VARCHAR2(4000);

    vValue  VARCHAR2(4000);

    vDescription  VARCHAR2(4000);

    pragma autonomous_transaction; -- This allows you to log errors even from functions called from select statements

  begin

    if pvSettingRec."axSetting" is null or pvSettingRec."axSetting" = 0 then

      select AX_SETTING_AXSETTING_SEQ.nextval into pvSettingRec."axSetting" from dual;

    end if;

    

    if pvSettingRec."axSettingGrp" is null or pvSettingRec."axSettingGrp" = 0 then

      pvSettingRec."axSettingGrp" := pvSettingRec."axSetting";

    end if;

    

    begin   

      select "Value" into vValue from ax_setting where "Key" = pvSettingRec."Key" and "SettingType" = pvSettingRec."SettingType" and "Priority" = pvSettingRec."Priority";

      

      -- if this is reached, the record exists

      if vValue <> pvSettingRec."Value" and pOverrideValues then

        -- we need to update the existing value

         update ax_setting set "Value" = pvSettingRec."Value" where "Key" = pvSettingRec."Key";

         dbmsoutput_P(MSG_DML::integer,(to_char(SQL%rowcount) || ' ax_setting rows updated.')::varchar2,pParams);

      elsif pOverrideValues then

        -- Setting already exists, with the same value

        dbmsoutput_P(MSG_INFO::integer,('ax_setting ' || pvSettingRec."Key" || ' already exists.')::varchar2,pParams);

      end if;

    exception

      when no_data_found then

      -- the setting record does not exist and we need to add it

      --   if this insert errors then the user is trying to insert a record that exists, 

      --   but has a different type or priority, 

      --   a unique constraint error will be raised, which is expected behavior

        begin      

          insert into AX_Setting values(

            pvSettingRec."axSetting",

            pvSettingRec."Key",

            nvl(pvSettingRec."SettingType",0),

            pvSettingRec."axSettingGrp",

            nvl(pvSettingRec."Priority",1),    

            nvl(pvSettingRec."Value",' '),

            nvl(pvSettingRec."Description",pvSettingRec."Key")

          );    

          dbmsoutput_P(MSG_DML::integer,(to_char(SQL%rowcount) || ' ax_setting rows inserted.')::varchar2,pParams);

          dbms_output.put_line('2');

        exception

          when dup_val_on_index then

            begin

              -- The primary key was a duplicate, so assume that it was not reset as an oversight

              insert into AX_Setting values(

                AX_SETTING_AXSETTING_SEQ.nextval,

                pvSettingRec."Key",

                nvl(pvSettingRec."SettingType",0),

                pvSettingRec."axSettingGrp",

                nvl(pvSettingRec."Priority",1),    

                nvl(pvSettingRec."Value",' '),

                nvl(pvSettingRec."Description",pvSettingRec."Key")

              );    

              dbmsoutput_P(MSG_DML::integer,(to_char(SQL%rowcount) || ' ax_setting rows inserted.')::varchar2,pParams);

            exception

              when dup_val_on_index then

                dbmsoutput_P(MSG_ERROR::integer,(pvSettingRec."Key" || ' already exists! Skipping.')::varchar2,pParams);

            end;

        end;

    end;

    -- Commit required for pragma autonomous_transaction

    commit;

  end AddSetting_P;

  

  

  -- returns information from ax_help, if the table exists

  FUNCTION ax_gethelpinfo_f(ppackagename character varying, pobjectname character varying DEFAULT NULL::character varying) RETURN character varying IS

    vReturnValue  VARCHAR2(4000) := null;

  begin

    if (trim(pObjectName) is null OR length(trim(pObjectName)) = 0) then

      execute immediate('select "Description" from ax_help where "PackageName" = ''' || trim(pPackageName) ||''' and "ObjectName" is null') into vReturnValue;

    else

      execute immediate('select "Description" from ax_help where "PackageName" = ''' || trim(pPackageName) ||''' and "ObjectName"= ''' || trim(pObjectName) ||'''') into vReturnValue;

    end if;

    return vReturnValue;

  exception

    when others then

      return null; -- just fail silently if the table, or record, does not exist

  end AX_GetHelpInfo_F;

  

  

  -- Returns the version of the provided AXSO package

  FUNCTION ax_getpkgversion_f(ppackagename character varying) RETURN character varying IS

    vReturnValue  VARCHAR2(10);

  begin

    execute immediate 'begin :x := trim(to_char(' || pPackageName || '.VERSION,''99.99'')) || ''.'' || trim(to_char(' || pPackageName || 

      '.AXIUM_VERSION,''99.99'')); end;' using out vReturnValue;

    return vReturnValue;

  exception

    when others then

      return null;

  end; 

  

  

  FUNCTION ax_getaxsoversion_f(pparams tparams DEFAULT ax_pkg.ax_params) RETURN character varying IS

    vResultString  VARCHAR2(4000);

    vLineBreak  VARCHAR2(10) := chr(13) || chr(10);

    vVersion  VARCHAR2(50);



    type axso_array is varray(10) of  VARCHAR2(50);

    vAXSO axso_array := axso_array(

      'ax_lang_pkg   ',

      'ax_email_pkg  ',

      'ax_patient_pkg',

      'ax_assign_pkg ',

      'ax_copy_pkg   ',

      'ax_forms_pkg  ',

      'ax_trx_pkg    ',

      'ax_users_pkg  ',

      'ax_ins_pkg    ',

      'ax_note_pkg   '

    );    

  begin

    -- ax_pkg

    AppendString_P(vResultString,'ax_pkg        : ' || trim(to_char(ax_pkg.VERSION,'99.99')) || '.' || trim(to_char(ax_pkg.AXIUM_VERSION,'99.99')),vLineBreak,MSG_INFO,pParams);

    -- other packages

    for i in 1..vAXSO.count loop

      vVersion := AX_GetPKGVersion_F(upper(vAXSO(i)));

      if vVersion is not null then

        AppendString_P(vResultString,vAXSO(i) || ': ' || vVersion,vLineBreak,MSG_INFO,pParams);

      end if;      

    end loop;

    return vResultString;

  end AX_GetAXSOVersion_F;

  

  

  -- returns information about pPackageName, or its procedures   

  FUNCTION help_f(ppackagename character varying, pobjectname character varying DEFAULT NULL::character varying, pparams tparams DEFAULT ax_pkg.ax_params) RETURN clob IS

    -- List of Procedures

    cursor curProcedures(pPackage varchar2,pProcedure varchar2) is

      select 

        o.OBJECT_NAME,

        p.PROCEDURE_NAME,

        p.OVERLOAD

      from 

        sys.ALL_OBJECTS o

        inner join sys.ALL_PROCEDURES p on 

          o.OBJECT_NAME = p.OBJECT_NAME and 

          o.OBJECT_TYPE = 'PACKAGE' and 

          o.OWNER = user and 

          p.PROCEDURE_NAME IS NOT NULL

      where 

        o.OBJECT_NAME = pPackage and

        o.OBJECT_NAME like 'AX_%' and

        (

          p.PROCEDURE_NAME = pProcedure or

          pProcedure is null or

          pPackage || '.' || p.PROCEDURE_NAME = pProcedure

        ) and

        p.PROCEDURE_NAME not like 'AX_%';

     

    -- List of Parameters    

    cursor curParameters(pPackage varchar2,pProcedure varchar2, pOverload number) is 

      select *

      from 

        sys.ALL_ARGUMENTS

      where 

        PACKAGE_NAME = pPackage and

        ( 

          OBJECT_NAME = pProcedure or

          pPackage || '.' || OBJECT_NAME = pProcedure

        ) and

        (

          OVERLOAD = pOverload or

          pOverload is null

        ) and

        pPackage like 'AX_%' and

        pProcedure not like 'AX_%'

      order by 

        OBJECT_NAME,

        OVERLOAD,

        SEQUENCE,

        POSITION;

    vFound boolean := false;    

    vIndent  VARCHAR2(10) := ' ';

    vDescription  VARCHAR2(4000);

    vReturnString CLOB;

    vLineBreak  VARCHAR2(10) := chr(13) || chr(10);

    vParams tParams := pParams;

  begin

    if not vParams."IsInit" then

      InitializeParams_P(vParams);

      vParams."VerboseType" := SHOW_INFO;

    end if;

    

    -- List Package Procedures and Functions

    if (trim(pObjectName) is null OR length(trim(pObjectName)) = 0) then

      AppendString_P(vReturnString,'For the parameters of a command use .Help(''command-name'')',vLineBreak,MSG_INFO,vParams);

      AppendString_P(vReturnString,'For all commands and parameters or descriptions use .Help(''FULL'') or .Help(''DESC'')' || vLineBreak,vLineBreak,MSG_INFO,vParams);

      vDescription := AX_GetHelpInfo_F(upper(pPackageName));

      AppendString_P(vReturnString,upper(pPackageName) || ' ' || AX_GetPKGVersion_F(upper(pPackageName)) || ':',vLineBreak,MSG_INFO,vParams);

      if vDescription is not null then

        AppendString_P(vReturnString,vDescription,vLineBreak,MSG_INFO,vParams);

      end if;

      AppendString_P(vReturnString,vLineBreak,' ',MSG_NONE,vParams);

      for cProcedure in curProcedures(trim(upper(pPackageName)),null) loop

        vFound := true;

        if cProcedure.OVERLOAD is null or cProcedure.OVERLOAD = 1 then

          AppendString_P(vReturnString,cProcedure.OBJECT_NAME || '.' || cProcedure.PROCEDURE_NAME,vLineBreak,MSG_INFO,vParams);

        end if;

      end loop;

      if vDescription is null and not vFound then

        AppendString_P(vReturnString,upper(pPackageName) || ' not found.',vLineBreak,MSG_INFO,vParams);

      end if;

    elsif trim(upper(pObjectName)) = 'AXSO' then

      AppendString_P(vReturnString,'For all commands without parameters use package_name.Help()',vLineBreak,MSG_INFO,vParams);

      AppendString_P(vReturnString,'For the parameters of a command use package_name.Help(''command-name'')',vLineBreak,MSG_INFO,vParams);

      AppendString_P(vReturnString,'For all commands and parameters or descriptions use .Help(''FULL'') or .Help(''DESC'')' || vLineBreak,vLineBreak,MSG_INFO,vParams);    

      vDescription := AX_GetHelpInfo_F('AXSO');

      if vDescription is not null then

        AppendString_P(vReturnString,vDescription,vLineBreak,MSG_INFO,vParams);

      end if;      

      AppendString_P(vReturnString,vLineBreak,' ',MSG_NONE,vParams);

      dbmsoutput_P(MSG_INFO,' ',vParams);

      AppendString_P(vReturnString,AX_GetAXSOVersion_F(pParams),vLineBreak,MSG_INFO,vParams);

    elsif trim(upper(pObjectName)) = 'DESC' then

      vDescription := AX_GetHelpInfo_F(upper(pPackageName));

      AppendString_P(vReturnString,upper(pPackageName) || ' ' || AX_GetPKGVersion_F(upper(pPackageName)) || ':',vLineBreak,MSG_INFO,vParams);

      if vDescription is not null then

        AppendString_P(vReturnString,vDescription,vLineBreak,MSG_INFO,vParams);

      end if;

      AppendString_P(vReturnString,vLineBreak,' ',MSG_NONE,vParams);

      dbmsoutput_P(MSG_INFO,' ',vParams);

      for cProcedure in curProcedures(trim(upper(pPackageName)),null) loop

        vFound := true;

        if cProcedure.OVERLOAD is null or cProcedure.OVERLOAD = 1 then

          AppendString_P(vReturnString,cProcedure.OBJECT_NAME || '.' || cProcedure.PROCEDURE_NAME,vLineBreak,MSG_INFO,vParams);

          vDescription := AX_GetHelpInfo_F(upper(pPackageName),upper(cProcedure.PROCEDURE_NAME));

          if NOT (trim(vDescription) is null OR length(trim(vDescription)) = 0) then

            AppendString_P(vReturnString,vDescription,vLineBreak,MSG_INFO,vParams);

          end if;

          AppendString_P(vReturnString,vLineBreak,' ',MSG_NONE,vParams);

          dbmsoutput_P(MSG_INFO,' ',vParams);

        end if;

      end loop;

      if not vFound then

        AppendString_P(vReturnString,upper(pPackageName) || ' not found.',vLineBreak,MSG_INFO,vParams);

      end if;

    elsif trim(upper(pObjectName)) = 'FULL' then

      AppendString_P(vReturnString,'For all commands without parameters use .Help()',vLineBreak,MSG_INFO,vParams);

      AppendString_P(vReturnString,'For the parameters of a command use .Help(''command-name'')' || vLineBreak,vLineBreak,MSG_INFO,vParams);

      vDescription := AX_GetHelpInfo_F(upper(pPackageName));

      AppendString_P(vReturnString,upper(pPackageName) || ' ' || AX_GetPKGVersion_F(upper(pPackageName)) || ':',vLineBreak,MSG_INFO,vParams);

      if vDescription is not null then

        AppendString_P(vReturnString,vDescription,vLineBreak,MSG_INFO,vParams);

      end if;      

      AppendString_P(vReturnString,vLineBreak,' ',MSG_NONE,vParams);

      dbmsoutput_P(MSG_INFO,' ',vParams);

    -- List Package Procedures and Functions with parameters

      for cProcedure in curProcedures(trim(upper(pPackageName)),null) loop

        vFound := true;

        if cProcedure.OVERLOAD is null or cProcedure.OVERLOAD = 1 then

          AppendString_P(vReturnString,cProcedure.OBJECT_NAME || '.' || cProcedure.PROCEDURE_NAME,vLineBreak,MSG_INFO,vParams);

        else

          AppendString_P(vReturnString,cProcedure.OBJECT_NAME || '.' || cProcedure.PROCEDURE_NAME || ' overload',vLineBreak,MSG_INFO,vParams);

        end if;

        for cParameter in curParameters (cProcedure.OBJECT_NAME,cProcedure.PROCEDURE_NAME,cProcedure.OVERLOAD) loop

          if cParameter.DATA_LEVEL = 0 then

            vIndent := '  ';

            if cParameter.DEFAULTED = 'N' and cParameter.IN_OUT = 'IN' then

              AppendString_P(vReturnString,vIndent || cParameter.ARGUMENT_NAME || ' (' || lower(cParameter.DATA_TYPE) || ')',vLineBreak,MSG_INFO,vParams);

            elsif cParameter.DEFAULTED = 'Y' and cParameter.IN_OUT = 'IN' then

              AppendString_P(vReturnString,vIndent || cParameter.ARGUMENT_NAME || ' (' || lower(cParameter.DATA_TYPE) || ') optional ' || cParameter.DEFAULT_VALUE,vLineBreak,MSG_INFO,vParams);

            elsif cParameter.IN_OUT = 'OUT' then

              AppendString_P(vReturnString,' return (' || lower(cParameter.DATA_TYPE) || ')',vLineBreak,MSG_INFO,vParams);

            elsif cParameter.IN_OUT = 'IN/OUT' then

              AppendString_P(vReturnString,vIndent || cParameter.ARGUMENT_NAME || ' (' || lower(cParameter.DATA_TYPE) || ') in/out',vLineBreak,MSG_INFO,vParams);

            else

              AppendString_P(vReturnString,vIndent || cParameter.ARGUMENT_NAME || ' (' || lower(cParameter.DATA_TYPE) || ')',vLineBreak,MSG_INFO,vParams);

            end if;

          end if;

        end loop;

        AppendString_P(vReturnString,vLineBreak,' ',MSG_NONE,vParams);

        dbmsoutput_P(MSG_INFO,' ',vParams);           

      end loop;

      if vDescription is null and not vFound then

        AppendString_P(vReturnString,upper(pPackageName) || ' not found.',vLineBreak,MSG_INFO,vParams);

      end if;      

    else

      AppendString_P(vReturnString,'For all commands without parameters use .Help()',vLineBreak,MSG_INFO,vParams);

      AppendString_P(vReturnString,'For all commands and parameters or descriptions use .Help(''FULL'') or .Help(''DESC'')' || vLineBreak,vLineBreak,MSG_INFO,vParams);

    -- List Procedure/Function Parameters

      for cProcedure in curProcedures(trim(upper(pPackageName)),trim(upper(pObjectName))) loop

        vFound := true;

        if cProcedure.OVERLOAD is null or cProcedure.OVERLOAD = 1 then

          vDescription := AX_GetHelpInfo_F(upper(pPackageName),upper(cProcedure.PROCEDURE_NAME));

          if vDescription is not null then

            AppendString_P(vReturnString,vDescription,vLineBreak,MSG_INFO,vParams);

            AppendString_P(vReturnString,vLineBreak,' ',MSG_NONE,vParams);

            dbmsoutput_P(MSG_INFO,' ',vParams);

          end if;      

          AppendString_P(vReturnString,cProcedure.OBJECT_NAME || '.' || cProcedure.PROCEDURE_NAME,vLineBreak,MSG_INFO,vParams);

        else

          AppendString_P(vReturnString,cProcedure.OBJECT_NAME || '.' || cProcedure.PROCEDURE_NAME || ' overload',vLineBreak,MSG_INFO,vParams);

        end if;

        for cParameter in curParameters (cProcedure.OBJECT_NAME,cProcedure.PROCEDURE_NAME,cProcedure.OVERLOAD) loop

          if cParameter.DATA_LEVEL = 0 then

            vIndent := '  ';

          elsif cParameter.DATA_LEVEL = 1 then

            vIndent := '    ';

          else 

            vIndent := '      ';

          end if;

          if cParameter.DEFAULTED = 'N' and cParameter.IN_OUT = 'IN' then

            AppendString_P(vReturnString,vIndent || cParameter.ARGUMENT_NAME || ' (' || lower(cParameter.DATA_TYPE) || ')',vLineBreak,MSG_INFO,vParams);

          elsif cParameter.DEFAULTED = 'Y' and cParameter.IN_OUT = 'IN' then

            AppendString_P(vReturnString,vIndent || cParameter.ARGUMENT_NAME || ' (' || lower(cParameter.DATA_TYPE) || ') optional ' || cParameter.DEFAULT_VALUE,vLineBreak,MSG_INFO,vParams);

          elsif cParameter.IN_OUT = 'OUT' then

            AppendString_P(vReturnString,' return (' || lower(cParameter.DATA_TYPE) || ')',vLineBreak,MSG_INFO,vParams);

          elsif cParameter.IN_OUT = 'IN/OUT' then

            AppendString_P(vReturnString,vIndent || cParameter.ARGUMENT_NAME || ' (' || lower(cParameter.DATA_TYPE) || ') in/out',vLineBreak,MSG_INFO,vParams);

          else

            AppendString_P(vReturnString,vIndent || cParameter.ARGUMENT_NAME || ' (' || lower(cParameter.DATA_TYPE) || ') ',vLineBreak,MSG_INFO,vParams);

          end if;

        end loop;

        AppendString_P(vReturnString,vLineBreak,' ',MSG_NONE,vParams);

        dbmsoutput_P(MSG_INFO,' ',vParams); 

      end loop;

      if vDescription is null and not vFound then

        AppendString_P(vReturnString,upper(pPackageName) || '.' || upper(pObjectName) || ' not found.',vLineBreak,MSG_INFO,vParams);

      end if;      

    end if;

    return vReturnString;

  end HELP_F;

  

  

  -- returns information about this package, or its procedures

  PROCEDURE help(IN pobjectname character varying DEFAULT NULL::character varying) IS

    vReturn CLOB;

  begin

    -- Writes the help to the DBMS_OUTPUT

	-- AX-39259

    vReturn := ax_pkg.Help_F('AX_PKG',pObjectName);

  end Help;





  -- This function returns if the provided version matches the axiUm version

  FUNCTION versionmatch_f(pversion numeric) RETURN boolean IS

    vMatch number;

  begin

    select 1 into vMatch from 

      practice 

    where 

      to_number("Version") >= pVersion * 10000 and 

      to_number("Version") <= (pVersion * 10000) + 99 and

      rownum=1;

    return true;

  exception

    when no_data_found then

      return false;

  end VersionMatch_F;

  

  

  -- This function returns a true or false based on if pInstance is the current database instance

  FUNCTION databaseinstancematch_f(pinstance character varying, piscasesensative boolean DEFAULT true) RETURN boolean IS

  cursor 

    checkinstance is select INSTANCE_NAME from v_instance;

    vInstanceName  VARCHAR2(16);

  begin

    open checkinstance;

    fetch checkinstance into vInstanceName;

    if pIsCaseSensative and (checkinstance%notfound or vInstanceName != pInstance) then

      return false;

    elsif checkinstance%notfound or upper(vInstanceName) != upper(pInstance) then

      return false;

    else

      return true;

    end if;

  end DatabaseInstanceMatch_F;





-- Report on the versions of products installed in the database

  FUNCTION versionreport_f(pdetailed numeric DEFAULT 0, pparams tparams DEFAULT ax_pkg.ax_params) RETURN character varying IS

    vMessage  VARCHAR2(4000);

    vVersion  VARCHAR2(50);

    vDate  VARCHAR2(50);

    vLineBreak  VARCHAR2(10) := chr(13) || chr(10);

 

  begin

    -- Report Header

    if pDetailed = 1 then

      AppendString_P(vMessage,vLineBreak || '**** axiUm Detailed Version Report  ****' || vLineBreak,vLineBreak,MSG_INFO,pParams);

    else

      AppendString_P(vMessage,vLineBreak || '**** axiUm Version Report  ****' || vLineBreak,vLineBreak,MSG_INFO,pParams);

    end if;

  

    -- Database

    select host_name,version into vDate, vVersion from v_instance;        

    AppendString_P(vMessage,'Database: ' || vDate,vLineBreak,MSG_INFO,pParams);

    AppendString_P(vMessage,'Oracle Version: ' || vVersion,vLineBreak,MSG_INFO,pParams);

    

    if pDetailed = 1 then

      select archiver into vVersion from v_instance;    

      if vVersion = 'STOPPED' then

        AppendString_P(vMessage,'Archiving? No',vLineBreak,MSG_INFO,pParams);

      else

        AppendString_P(vMessage,'Archiving? Yes',vLineBreak,MSG_INFO,pParams);

      end if;

    end if;



    AppendString_P(vMessage,vLineBreak,' ',MSG_INFO,pParams);

  

    -- axiUm    

      -- should always exist

    select "Version" into vVersion from practice where rownum = 1;  

    AppendString_P(vMessage,'axiUm: ' || vVersion,vLineBreak,MSG_INFO,pParams);

    

    if pDetailed = 1 then

      select to_char(max("Date"),'FMMonth ddth, YYYY') into vDate from audithis 

      where 

        "TableName"='VERSION' and 

        "User" = vVersion 

      group by "User";

      AppendString_P(vMessage,'axiUm Updated: ' || vDate,vLineBreak,MSG_INFO,pParams);

    end if;

    

    AppendString_P(vMessage,vLineBreak,' ',MSG_INFO,pParams);

    

    -- FacultyAccess

    begin

      execute immediate('select "Value" from FSETTING where "Key" = ''FP.General.Version''') into vVersion;

      AppendString_P(vMessage,'FacultyAccess: ' || vVersion,vLineBreak,MSG_INFO,pParams);

      if pDetailed = 1 then

        execute immediate(' select to_char(max("Date"),''' || DESCRIPTIVE_DATE_FORMAT || ''') from audithis where "TableName"=''FVERSION''') into vDate;

        AppendString_P(vMessage,'FacultyAccess Updated: ' || vDate || vLineBreak,vLineBreak,MSG_INFO,pParams);

      end if;

    exception

      when others then

        AppendString_P(vMessage,'FacultyAccess not installed',vLineBreak,MSG_INFO,pParams);

    end;



   -- PatientAccess  

    begin

      execute immediate('select "Value" from ISETTING where "Key" = ''Gen.VersionPatientAccess''') into vVersion;

      AppendString_P(vMessage,'PatientAccess: ' || vVersion,vLineBreak,MSG_INFO,pParams);

      if pDetailed = 1 then

        execute immediate(' select to_char(max("Date"),''' || DESCRIPTIVE_DATE_FORMAT || ''') from audithis where "TableName"=''PVERSION''') into vDate;

        AppendString_P(vMessage,'PatientAccess Updated: ' || vDate || vLineBreak,vLineBreak,MSG_INFO,pParams);

      end if;

    exception

      when others then

        AppendString_P(vMessage,'PatientAccess not installed',vLineBreak,MSG_INFO,pParams);

    end;



    -- Meaningful Use Dashboard

    begin

      execute immediate('select "Value" from MSETTING where "Key" = ''MU.General.Version''') into vVersion;

      AppendString_P(vMessage,'Meaningful Use Dashboard: ' || vVersion,vLineBreak,MSG_INFO,pParams);

      if pDetailed = 1 then

        execute immediate(' select to_char(max("Date"),''' || DESCRIPTIVE_DATE_FORMAT || ''') from audithis where "TableName"=''MVERSION''') into vDate;

        AppendString_P(vMessage,'Meaningful Use Dashboard Updated: ' || vDate || vLineBreak,vLineBreak,MSG_INFO,pParams);

      end if;

    exception

      when others then

        AppendString_P(vMessage,'Meaningful Use Dashboard not installed',vLineBreak,MSG_INFO,pParams);

    end;

    

    AppendString_P(vMessage,vLineBreak,' ',MSG_INFO,pParams);

    

    -- AXSO

    AppendString_P(vMessage,AX_GetAXSOVersion_F(pParams),' ',MSG_INFO,pParams);    

    

    return vMessage;

  end VersionReport_F;



  -- This procedure gets the overnight user. 

  -- It throws an exception if the user is not found or has been deleted.

  FUNCTION getovernightuser_f() RETURN numeric IS

  

    vOvernightUser users."User"%type := 0;



  begin

  

    select "OvernightUser" into vOvernightUser

	from axiumopt ao 

	join users u on ao."OvernightUser" = u."User"

	where u."Deleted" = 0

	  and rownum = 1;



	return vOvernightUser;

	

  exception

    when no_data_found then

      raise_application_error(-20002, 'Overnight user not found or deleted.', true);  

	  return vOvernightUser;

	  when others then

	  raise_application_error(-20099, 'Error getting the overnight user.', true);  

	  return vOvernightUser;	

  end GetOvernightUser_F;

  

  -- This procedure populates the User and Station for pvParams     

  PROCEDURE getstationuser_p(INOUT pvparams tparams) IS

    vUser users."User"%type;

    vStationId station."StationId"%type;

  begin

    -- If both fields are already populated, exit early

    if pvParams."User" is not null and pvParams."StationId" is not null then 

      return;

    end if;

    -- Otherwise, get variables from the session

    begin

      -- Get Currently Logged in axiUm User

      begin

        select 

          case when l."AuditUser" != 0 then l."AuditUser" else l."User" end "AuditUser", 

          case when l."AuditUser" != 0 then l."AuditStationId" else l."StationId" end "AuditStationId"

        into 

          vUser, 

          vStationId 

        from log l

        where

          l."AudSID" = pg_backend_pid() and

          l."Action" = 1

          and exists 

            (

              select 1

              from v_session s

              where 1=1

                and 

                (

                  lower(s.program) like '%axium%'

                  or lower(s.program) like '%a2.exe%'

                  or lower(s.program) like '%poweradm%'

                )

                and s.audsid = l."AudSID"

            );

      exception

        -- If the first check returns too many values, we have to narrow down the search

        --   This can come up when Oracle itself reuses the SESSIONID

        when too_many_rows then

          -- Check to see where this SESSIONID is tied to an axiUm session where the user has logged in, but not logged out

          begin

            select 

              "AuditUser", 

              "AuditStationId" 

            into 

              vUser, 

              vStationId 

            from 

              (

                select 

                  case when l."AuditUser" != 0 then l."AuditUser" else l."User" end "AuditUser", 

                  case when l."AuditUser" != 0 then l."AuditStationId" else l."StationId" end "AuditStationId"

                from log l

                where

                  l."Action" = 1 and

                  l."AudSID" = pg_backend_pid() and

                  not exists 

                    (

                      select 1

                      from log l2

                      where

                        l2."Action" = 2 and

                        l2."LoginHistory" > l."LoginHistory" and

                        l2."AudSID" = l."AudSID"

                    )

                  and exists 

                    (

                      select 1

                      from v_session s

                      where 1=1

                        and 

                        (

                          lower(s.program) like '%axium%'

                          or lower(s.program) like '%a2.exe%'

                          or lower(s.program) like '%poweradm%'

                        )

                        and s.audsid = l."AudSID"

                    )

                order by l."LoginHistory" desc

              )

            where 

              rownum = 1;

          exception

            -- If we narrowed down the results too much, just check the most recent Login

            when no_data_found then

              select 

                "AuditUser", 

                "AuditStationId" 

              into 

                vUser, 

                vStationId 

              from 

                (

                  select 

                    case when l."AuditUser" != 0 then l."AuditUser" else l."User" end "AuditUser", 

                    case when l."AuditUser" != 0 then l."AuditStationId" else l."StationId" end "AuditStationId"

                  from log l

                  where

                    l."Action" = 1 and

                    l."AudSID" = pg_backend_pid()

                    and exists 

                      (

                        select 1

                        from v_session s

                        where 1=1

                          and 

                          (

                            lower(s.program) like '%axium%'

                            or lower(s.program) like '%a2.exe%'

                            or lower(s.program) like '%poweradm%'

                          )

                          and s.audsid = l."AudSID"

                      )

                  order by l."LoginHistory" desc

                ) 

              where

                rownum = 1;

          end; 

      end;

    exception

      when no_data_found then

        begin

          -- There is no axiUm User, so assume that this is being run from the overnight package

          select "OvernightUser" into vUser from axiumopt;

        exception

          when no_data_found then

            -- there is no overnight user, so cannot make any assumptions

            vUser := null;

          when too_many_rows then

            -- there is no overnight user, so cannot make any assumptions

            vUser := null;            

        end;

        -- If axiUm User check was unsuccessful, assume that the script is being run from outside of axiUm

          -- This is usually indicated by a -1 StationId

        vStationId := -1;

    end;

    -- The nvl checks are in case one was set, but not the other.

    pvParams."User" := nvl(pvParams."User",vUser);

    pvParams."StationId" := nvl(pvParams."StationId",vStationId);

  end GetStationUser_P;

  

  

  -- Compare two strings, taking Null values into account

  FUNCTION valuesequal_f(pstring1 character varying, pstring2 character varying) RETURN boolean IS

  begin

    if pString1 is null and pString2 is null then

      return true;

    elsif pString1 is null and pString2 is not null then

      return false;

    elsif pString1 is not null and pString2 is null then

      return false;

    elsif pString1 = pString2 then

      return true;

    else

      return false;

    end if;

  end ValuesEqual_F;

  

  

  -- This procedure sets any null tParams to current or default values

  PROCEDURE initializeparams_p(INOUT pvparams tparams, IN pinitparams tparams DEFAULT NULL::tparams) IS

  begin

    if pInitParams."IsInit" is not null then

      pvParams := pInitParams;

    end if;

    if not pvParams."IsInit" then

      pvParams."VerboseType" := nvl(pvParams."VerboseType",SHOW_ERRORS);

      pvParams."VerifyLevel" := nvl(pvParams."VerifyLevel",VERIFY_ALL);

      GetStationUser_P(pvParams);

      pvParams."IsInit" := true;

    end if;

  end InitializeParams_P;

  

  

  -- This procedure initializes an ax_log record

  PROCEDURE initializelog_p(INOUT pvlogrow ax_log, IN pparams tparams DEFAULT ax_pkg.ax_params) IS

    vParams tParams;

    vOwner  VARCHAR2(50);

    vLineNo number;

    vCaller_T  VARCHAR2(50);

  begin

    vParams := pParams;    

    GetStationUser_P(vParams);

    

    pvLogRow."LogId" := null; -- Set in ax_log_p

    pvLogRow."LogSetId" := null; -- Set in ax_log_p

    pvLogRow."DateTime" := systimestamp;

    who_called_me(vOwner,pvLogRow."Source",vLineNo,vCaller_T);

    pvLogRow."Request" := '';

    pvLogRow."User" := vParams."User";

    pvLogRow."StationId" := vParams."StationId";

    pvLogRow."Log" := '';    

  end InitializeLog_P;

  

  

  -- This procedure writes to the dbms output

    --  but only if the Verbose Type is greater than or equal to the Message Type

  PROCEDURE dbmsoutput_p(IN pmessagetype integer, IN pmessage character varying, IN pparams tparams DEFAULT ax_pkg.ax_params) IS

    vOwner  VARCHAR2(50);

    vSource  VARCHAR2(255);

    vLineNo number;

    vCaller_T  VARCHAR2(50);  

    vShow boolean := false;

    vParams tParams := pParams;

    exBufferOverflow exception;

    pragma exception_init(exBufferOverflow, -20000); 

      -- dbms_output can actually return two different -20000 errors

        -- However, one is more likely to be as a PLS-00172: string literal too long before this point

     vLog ax_log%rowtype;

  begin

    if (trim(pMessage) is null OR length(trim(pMessage)) = 0) then

      dbms_output.put_line(' ');

      return;

    end if;

  

    InitializeParams_P(vParams);

    -- Calculate if message should be shown

    if vParams."VerboseType" = SHOW_CODE_GEN then  

      if pMessageType = MSG_CODE then

        vShow := true;

      end if;

    elsif vParams."VerboseType" >= pMessageType then

      vShow := true;

    end if;

    -- Show messages

    if vShow then

      if vParams."ShowSource" = DBMS_HIDE_SOURCE then

        dbms_output.put_line(pMessage);

      elsif vParams."ShowSource" = DBMS_SHOW_SOURCE then

        who_called_me(vOwner,vSource,vLineNo,vCaller_T);

        dbms_output.put_line(vSource || ': ' || pMessage);

      elsif vParams."ShowSource" = DBMS_SHOW_STEP then 

        who_called_me(vOwner,vSource,vLineNo,vCaller_T);

        dbms_output.put_line(vSource || '^' || vParams."Step" || ': ' || pMessage);        

      elsif vParams."ShowSource" = DBMS_SHOW_LINE then 

        who_called_me(vOwner,vSource,vLineNo,vCaller_T);

        dbms_output.put_line(vSource || '.' || vLineNo || ': ' || pMessage);

      else 

        who_called_me(vOwner,vSource,vLineNo,vCaller_T);

        dbms_output.put_line(vSource || '.' || vLineNo || ': ' || pMessage);

      end if;

    end if;



  exception

    when exBufferOverflow then

      -- Purge the dbms_output buffer

      dbms_output.disable;

      -- Start a new dbms_output buffer

      dbms_output.enable;

      dbms_output.put_line(SQLERRM);

      dbms_output.put_line('AXSO: Buffer purged and reset');

  end dbmsoutput_P;



  -- Overloaded procedure for numeric message type

  PROCEDURE dbmsoutput_p(IN pmessagetype numeric, IN pmessage character varying, IN pparams tparams DEFAULT ax_pkg.ax_params) IS

  begin

    -- Call the original procedure with type conversion

    dbmsoutput_P(pMessageType::integer, pMessage, pParams);

  end dbmsoutput_P;



  -- This function returns the max length of a field type based on Table and Field names.

  FUNCTION typelength_f(ptable character varying, pfield character varying) RETURN numeric IS

    vDataType  VARCHAR2(255);

    vLength number;

  begin

  

    select data_type into vDataType from user_tab_columns where table_name = upper(pTable) and column_name = pField; 

    

    if vDataType in ('CHAR', 'VARCHAR2', 'NCHAR', 'NVARCHAR2') then

      select data_length into vLength from user_tab_columns where table_name = upper(pTable) and column_name = pField; 

    elsif vDataType in ('NUMBER', 'FLOAT') then

      select nvl(data_precision, 38) into vLength from user_tab_columns where table_name = upper(pTable) and column_name = pField; 

    else 

      select data_length into vLength from user_tab_columns where table_name = upper(pTable) and column_name = pField; 

    end if;



    return vLength;



  end TypeLength_F;





  -- Remove Label

    -- This function removes sub strings from a string, based on open/close delimiters

  FUNCTION removelabels_f(pstring character varying, popendelimiter character varying DEFAULT '('::character varying, pclosedelimiter character varying DEFAULT ')'::character varying) RETURN character varying IS

    vPosOpen number := 1;

    vPosClose number;

    vLabel  VARCHAR2(4000);

    vReturn  VARCHAR2(4000);

  begin

    vReturn := pString;

    vPosOpen := instr(vReturn,pOpenDelimiter);

    while vPosOpen > 0 loop

      vPosClose := instr(vReturn,pCloseDelimiter,vPosOpen);

      if vPosClose > vPosOpen then

        vLabel := substr(vReturn,vPosOpen,vPosClose - vPosOpen + 1);

        vReturn := Replace(vReturn,vLabel);

        vPosOpen := instr(vReturn,pOpenDelimiter,vPosOpen);

      else

        vPosOpen := 0;

      end if;    

    end loop;

    return vReturn;

  end RemoveLabels_F;





  -- This function accepts a string value, then returns the same value cropped down to the length of the provided field.

  FUNCTION croptofieldsize_f(pstring character varying, ptable character varying, pfield character varying, pparams tparams DEFAULT ax_pkg.ax_params) RETURN character varying IS

  

      vLength number;    

      vDataType  VARCHAR2(20);

      

      exNotAString exception;

      

  begin    

    select data_length,data_type into vLength,vDataType from user_tab_columns where table_name = upper(pTable) and column_name = pField;

    

    if pString is not null then

      if vDataType not in ('CHAR', 'VARCHAR2', 'NCHAR', 'NVARCHAR2') then



        raise exNotAString;

      end if;

      

      if length(trim(pString)) > vLength then

        dbmsoutput_P(MSG_WARNING::integer, ('Value ' || trim(pString) || ' Longer than ' || pTable || '.' || pField || ' length, some data may be lost.')::varchar2,pParams);

      end if;

      

      If vDataType = 'CHAR' then 

        return substr(rpad(pString, vLength::integer),1,vLength);

      else

        return substr(trim(pString),1,vLength);

      end if;

    elsif vDataType = 'CHAR' then

      return rpad(' ', vLength::integer);

    else

      return null;

    end if;    

  exception

    when no_data_found then

      dbmsoutput_P(MSG_ERROR::integer, (pTable || '.' || pField || ' not found. pString NOT cropped.')::varchar2,pParams);

      return pString;

    when exNotAString then

      dbmsoutput_P(MSG_ERROR::integer, (pTable || '.' || pField || ' is not a text data type. pString NOT cropped.')::varchar2,pParams);

      return pString;

  end CropToFieldSize_F;

  

  

  /*

    Summary

    --------------------

    This function returns a partial list of columns for a table, formatted for use in a dynamic SQL statement.

    All column names from pTable will be provided, starting with pStartCol and ending with pEndCol allowing you to easily skip columns from the beginning or end.

    If the fields you need to skip are somewhere in the middle, then you can provide them in pExcludeList in a comma delimited list. 

    Note that the exclude list IS case sensative.

    

    Change log

    --------------------

  

    138357  7/05/2013  hlr  created to assist in creating dynamic SQL

  */

  FUNCTION getcols_f(ptable character varying, pstartcol numeric DEFAULT 1, pendcol numeric DEFAULT 0, pexcludelist character varying DEFAULT NULL::character varying, palias character varying DEFAULT NULL::character varying) RETURN character varying IS

    vCols  VARCHAR2(4000) := '';

    vIsNotFirst boolean := false;

    vExcluded number :=0;

    vAlias  VARCHAR2(50) := null;

    

    cursor curCols_StartRow(pTable varchar2,pStartCol number) is 

      select 

        column_name as "Col",

        column_id as "RowNumber"

      from 

        user_tab_columns 

      where 

        table_name = pTable and

        column_id >= pStartCol

      order by 

        column_id

      ;

      

    cursor curCols_EndRow(pTable varchar2,pStartCol number,pEndCol number) is 

      select 

        column_name as "Col",

        column_id as "RowNumber"

      from 

        user_tab_columns 

      where 

        table_name = pTable and

        column_id >= pStartCol and

        column_id >= pEndCol

      order by 

        column_id

      ;

      

  begin

    if pAlias is not null then

      vAlias := pAlias || '.';

    end if;

   

    if pEndCol > 0 then

      for cCol in curCols_EndRow(pTable,pStartCol,pEndCol) Loop

        --if instr col in exceptions then skip

        if pExcludeList is not null then

          vExcluded := instr(',' || pExcludeList || ',',',' || cCol."Col" || ',');

        end if;

        if vExcluded = 0 and vExcluded is not null then

          if vIsNotFirst then

            vCols := vCols || ',';

          end if;

          vCols := vCols || vAlias || '"' || cCol."Col" || '"'; 

          vIsNotFirst := true;

        end if;

      end loop;

    else

      for cCol in curCols_StartRow(pTable,pStartCol) Loop

        --if instr col in exceptions then skip

        if pExcludeList is not null then

          vExcluded := instr(',' || pExcludeList || ',',',' || cCol."Col" || ',');

        end if;

        if vExcluded = 0 and vExcluded is not null then

          if vIsNotFirst then

            vCols := vCols || ',';

          end if;

          vCols := vCols || vAlias || '"' || cCol."Col" || '"'; 

          vIsNotFirst := true;

        end if;

      end loop;

    end if;

    

    return vCols;

  end GetCols_F;





  -- Append String, adding leading spaces if needed 

   -- depreciated

  PROCEDURE appendstring_p(INOUT pvbasestring character varying, IN pnewstring character varying, IN pleadingdelimiter boolean, IN pdelimiter character varying, IN pmessagetype numeric, IN pparams tparams) IS

    vOwner  VARCHAR2(50);

    vSource  VARCHAR2(255);

    vLineNo number;

    vCaller_T  VARCHAR2(50);  

    vNewString  VARCHAR2(4000);

    vShow boolean := false;

    vParams tParams := pParams;

  begin

    if (trim(pNewString) is null OR length(trim(pNewString)) = 0) then

      return;

    end if;

    -- Initialize Params

    InitializeParams_P(vParams);

    -- Calculate if message should be shown

    if vParams."VerboseType" = SHOW_CODE_GEN then  

      if pMessageType = MSG_CODE then

        vShow := true;

      end if;

    elsif vParams."VerboseType" >= pMessageType then

      vShow := true;

    end if;

    -- Account for dbmsoutput_P Settings

    if vShow then      

      if vParams."ShowSource" = DBMS_HIDE_SOURCE then

        vNewString := pNewString;

      elsif vParams."ShowSource" = DBMS_SHOW_SOURCE then

        who_called_me(vOwner,vSource,vLineNo,vCaller_T);

        vNewString := substr(vSource || ': ' || pNewString,1,4000);

      elsif vParams."ShowSource" = DBMS_SHOW_STEP then 

        who_called_me(vOwner,vSource,vLineNo,vCaller_T);

        vNewString := substr(vSource || '^' || vParams."Step" || ': ' || pNewString,1,4000);

      else 

        who_called_me(vOwner,vSource,vLineNo,vCaller_T);

        vNewString := substr(vSource || '.' || vLineNo || ': ' || pNewString,1,4000);

      end if;

    else

      vNewString := pNewString;

    end if;

    -- Append the String

    if (trim(pNewString) is null OR length(trim(pNewString)) = 0) then

      pvBaseString := pvBaseString;

    elsif NOT (trim(pvBaseString) is null OR length(trim(pvBaseString)) = 0) and pLeadingDelimiter then

      pvBaseString := substr(pvBaseString || pDelimiter || vNewString,1,4000);

    else

      pvBaseString := substr(pvBaseString || vNewString,1,4000);

    end if;

    -- Call dbmsoutput_P

    dbmsoutput_P(pMessageType,pNewString,vParams); 

  end;  

  

  

  -- Append String, adding leading spaces if needed 

  PROCEDURE appendstring_p(INOUT pvbasestring character varying, IN pnewstring character varying, IN pdelimiter character varying DEFAULT ' '::character varying, IN pmessagetype numeric DEFAULT ax_pkg.msg_info, IN pparams tparams DEFAULT ax_pkg.ax_params) IS

    vOwner  VARCHAR2(50);

    vSource  VARCHAR2(255);

    vLineNo number;

    vCaller_T  VARCHAR2(50);  

    vNewString  VARCHAR2(4000);

    vShow boolean := false;

    vParams tParams := pParams;

  begin

    if (trim(pNewString) is null OR length(trim(pNewString)) = 0) then

      return;

    end if;

    InitializeParams_P(vParams);

    -- Calculate if message should be shown

    if vParams."VerboseType" = SHOW_CODE_GEN then  

      if pMessageType = MSG_CODE then

        vShow := true;

      end if;

    elsif vParams."VerboseType" >= pMessageType then

      vShow := true;

    end if;

    -- Account for dbmsoutput_P Settings

    if vShow then

      if vParams."ShowSource" = DBMS_HIDE_SOURCE then

        vNewString := pNewString;

      elsif vParams."ShowSource" = DBMS_SHOW_SOURCE then

        who_called_me(vOwner,vSource,vLineNo,vCaller_T);

        vNewString := substr(vSource || ': ' || vNewString,1,4000);

      elsif vParams."ShowSource" = DBMS_SHOW_STEP then 

        who_called_me(vOwner,vSource,vLineNo,vCaller_T);

        vNewString := substr(vSource || '^' || vParams."Step" || ': ' || vNewString,1,4000);

      else 

        who_called_me(vOwner,vSource,vLineNo,vCaller_T);

        vNewString := substr(vSource || '.' || vLineNo || ': ' || vNewString,1,4000);

      end if;

    else

      vNewString := pNewString;

    end if;

    -- Append the String

    if (trim(pNewString) is null OR length(trim(pNewString)) = 0) then

      pvBaseString := pvBaseString;

    elsif NOT (trim(pvBaseString) is null OR length(trim(pvBaseString)) = 0) then

      pvBaseString := substr(pvBaseString || pDelimiter || vNewString,1,4000);

    else

      pvBaseString := substr(pvBaseString || vNewString,1,4000);

    end if;

    -- Call dbmsoutput_P

    dbmsoutput_P(pMessageType,pNewString,vParams);    

  end;    

  

  

  -- Make a string safe for other formats

  PROCEDURE safestring_p(INOUT pvstring character varying, IN poutputtype character varying DEFAULT 'sql'::character varying) IS

  begin

    -- Universal Sanatations

    pvString := replace(pvString,'''','''''');

    -- SQL

    -- HTML

    --if upper(pOutputType) = 'HTML' then

    

   -- end if;

  end;





  -- Log a Custom Script Error

  PROCEDURE logevent_p(IN pobjectname character varying, IN pinfotext character varying, IN pparams tparams DEFAULT ax_pkg.ax_params, IN peventtype character varying DEFAULT 'CUSTOM SCRIPT FAILED'::character varying, IN pmessagetype integer DEFAULT ax_pkg.msg_debug) IS

    pragma autonomous_transaction;

    vLogId number;

    vEventType  VARCHAR2(4000);

    vParams tParams := pParams;

  begin

    InitializeParams_P(vParams);

  

    select AX_LOG_LogId_SEQ.nextval into vLogId from dual; 

  

    -- The Event Type may be a different length than ax_log."Log"

    vEventType := CropToFieldSize_F(pEventType || ':' || pInfoText,'ax_log','Log');

  

    -- This keeps us from having to call dbmsoutput seperately

    dbmsoutput_P(pMessageType,vEventType,vParams);

  

    -- For now, insert into ax_log instead of eventlog

    insert into AX_LOG values(

      vLogId,

      vLogId,

      systimestamp,

      pObjectName,

      0,    -- Request

      vParams."User",

      vParams."StationId",

      vEventType

    );

    dbmsoutput_P(MSG_DML::integer,(to_char(SQL%rowcount) || ' ax_log rows inserted.')::varchar2,vParams);

  

  /*

    -- eventlog cannot handle more than one entry per second

    insert into 

      eventlog

    values (

      sysdate, -- Date

      pUser,

      vParams."User",

      vParams."StationId",

      vInfoText

    );      

    dbmsoutput_P(MSG_DML::integer,(to_char(SQL%rowcount) || ' eventlog rows inserted.')::varchar2,vParams);

  */

    -- Commit required for pragma autonomous_transaction 

    commit;

  end LogEvent_P;

  

     

  -- Log a Custom Script Message into the ax_log table

  PROCEDURE log_p(INOUT pvlogrow ax_log, IN pmessagetype integer DEFAULT ax_pkg.msg_debug, IN pparams tparams DEFAULT ax_pkg.ax_params) IS  

    vParams tParams := pParams;

    pragma autonomous_transaction; -- This allows you to log errors even from functions called from select statements

  begin

    InitializeParams_P(vParams);

    -- You should never manually set the pvLogRow."LogId" before calling this procedure

      -- Setting this value each time allows you to call the procedure multiple times without dup index errors  

    select AX_LOG_LogId_SEQ.nextval into pvLogRow."LogId" from dual; 



    if pvLogRow."LogSetId" = 0 or pvLogRow."LogSetId" is null then

      pvLogRow."LogSetId" := pvLogRow."LogId";

    end if;

    

    -- Get User and StationId from vParams, but allow for overrides

    pvLogRow."User" := nvl(pvLogRow."User",vParams."User");

    pvLogRow."StationId" := nvl(pvLogRow."StationId",vParams."StationId");

  

    -- This keeps us from having to call dbmsoutput seperately

    dbmsoutput_P(pMessageType,pvLogRow."Log",vParams);

  

    -- Save Log

    insert into AX_LOG values(

      pvLogRow."LogId",

      pvLogRow."LogSetId",

      systimestamp,

      pvLogRow."Source",

      pvLogRow."Request",    

      pvLogRow."User",

      pvLogRow."StationId",

      pvLogRow."Log"

    );

    dbmsoutput_P(MSG_DML::integer,(to_char(SQL%rowcount) || ' ax_log rows inserted.')::varchar2,vParams);    

    

    -- Commit required for pragma autonomous_transaction

    commit;

  end Log_P;

  

  -- Overloaded procedure for numeric message type

  PROCEDURE log_p(INOUT pvlogrow ax_log, IN pmessagetype numeric, IN pparams tparams DEFAULT ax_pkg.ax_params) IS

  begin

    -- Call the original procedure with type conversion

    Log_P(pvLogRow, pMessageType::integer, pParams);

  end Log_P;

  

  -- Set default values for an ax_setting record

  PROCEDURE initializesetting_p(INOUT pvsettingrow ax_setting, IN pparams tparams DEFAULT ax_pkg.ax_params) IS

  begin

    pvSettingRow."Key" := null;

    pvSettingRow."SettingType" := 0;

    pvSettingRow."axSettingGrp" := pvSettingRow."axSetting";

    pvSettingRow."Priority" := 1;

    pvSettingRow."Value" := null;

    pvSettingRow."Description" := ' ';

  end InitializeSetting_P;  



   

  -- Get a setting value from the ax_setting table

  FUNCTION getsetting_f(pkey character varying, pparams tparams DEFAULT ax_pkg.ax_params) RETURN character varying IS

    vReturn ax_setting."Value"%Type;

    vLogRow ax_log%rowtype;

    vOwner  VARCHAR2(50);

    vLineNo number;

    vCaller_T  VARCHAR2(50);

  begin

    select "Value" into vReturn from ax_setting where "Key" = pKey;

    return vReturn;

  exception

    when no_data_found then

      who_called_me(vOwner,vLogRow."Source",vLineNo,vCaller_T);

      vLogRow."Log" := 'AX_Setting ''' || pKey || ''' does not exist';

      Log_P(vLogRow,MSG_ERROR,pParams);

      return null;

  end GetSetting_F;

  

  

  -- Get a setting value from the ax_setting table

   -- Overload

  FUNCTION getsetting_f(INOUT pvsettingrow ax_setting, poverridevalue character varying DEFAULT NULL::character varying, pparams tparams DEFAULT ax_pkg.ax_params) RETURN character varying IS

    vSettingId ax_setting."axSetting"%Type;

    vReturn ax_setting."Value"%Type;

  begin

    if pOverrideValue is not null then

      return pOverrideValue;

    end if;

    select "Value" into vReturn from ax_setting where "Key" = pvSettingRow."Key";

    return vReturn;

  exception

    when no_data_found then

      pvSettingRow."axSetting" := null;

      AddSetting_P(pvSettingRow,false,pParams);

      return pvSettingRow."Value";

  end GetSetting_F;





  -- Initialize a AuditHis record

  PROCEDURE initializeaudithis_p(INOUT pvaudithisrow audithis, IN pparams tparams DEFAULT ax_pkg.ax_params) IS

  begin

    pvAuditHisRow."Date" := trunc(sysdate);

    pvAuditHisRow."Time" := to_number(to_char(sysdate, 'HH24'))* 60 + to_number(to_char(sysdate, 'MI'));    

    pvAuditHisRow."User" := nvl(pvAuditHisRow."User",pParams."User");

    pvAuditHisRow."StationId" := nvl(pvAuditHisRow."StationId",pParams."StationId"); 

  end InitializeAuditHis_P;





  FUNCTION converttodate_f(pstring character varying, pdefault timestamp without time zone DEFAULT NULL::timestamp without time zone, pformat character varying DEFAULT NULL::character varying) RETURN timestamp without time zone IS 

    vReturnString  VARCHAR2(4000) := upper(trim(pString));

    vDateFormat  VARCHAR2(4000);

    vReturnDate date;

  begin  

    -- If a format is provided, try that

    if NOT (trim(pFormat) is null OR length(trim(pFormat)) = 0) then

      begin

        vReturnDate := to_date(vReturnString,pFormat);

        return vReturnDate;

      exception

        when others then

          null;

      end;

    else    

      -- Otherwise, try converting based on date format constants

        -- Remove number suffixes

      vReturnString := replace(vReturnString,'ST','');

      vReturnString := replace(vReturnString,'ND','');

      vReturnString := replace(vReturnString,'RD','');

      vReturnString := replace(vReturnString,'TH','');

      -- remove the word "of"

      vReturnString := replace(vReturnString,' OF ',' ');

        -- Normal Date Format with no Time Element

      begin

        vReturnDate := to_date(vReturnString,DATE_FORMAT);

        return vReturnDate;

      exception

        when others then

          null;

      end;

        -- Descritive Date Format, with Month spelled out

      begin

        vDateFormat := DESCRIPTIVE_DATE_FORMAT;

        vDateFormat := replace(vDateFormat,'ddth','dd');

        vReturnDate := to_date(vReturnString,vDateFormat);

        return vReturnDate;

      exception

        when others then

          null;

      end;    

        -- Date Format for situations where the string will be ordered by

      begin

        vReturnDate := to_date(vReturnString,ORDERED_DATE_FORMAT);

        return vReturnDate;

      exception

        when others then

          null;

      end;

        -- Date Format with a Time Element

      begin

        vReturnDate := to_date(vReturnString,DATE_TIME_FORMAT);

        return vReturnDate;

      exception

        when others then

          null;

      end;

        -- Date Format with a 24 hour Time Element

      begin

        vReturnDate := to_date(vReturnString,DATE_TIME_24H_FORMAT);

        return vReturnDate;

      exception

        when others then

          null;

      end;

        -- Date and Time format where the string will be ordered by

      begin

        vReturnDate := to_date(vReturnString,ORDERED_DATE_TIME_FORMAT);

        return vReturnDate;



      exception

        when others then

          null;

      end;

        -- default system format

      begin

        vReturnDate := to_date(vReturnString);

        return vReturnDate;

      exception

        when others then

          null;

      end;     

    end if;

    return pDefault;

  end ConvertToDate_F;  





  -- Returns a 0 if pString cannot be converted

  FUNCTION converttonumber_f(pstring character varying, pdefault numeric DEFAULT 0) RETURN numeric IS

     vReturnString  VARCHAR2(4000) := upper(pString);

   begin

     -- remove commas

     vReturnString := replace(vReturnString,',','');

     -- remove extra spaces

     vReturnString := replace(vReturnString,' ','');

     -- replace one through ten

     vReturnString := replace(vReturnString,'ONE','1');

     vReturnString := replace(vReturnString,'TWO','2');

     vReturnString := replace(vReturnString,'THREE','3');

     vReturnString := replace(vReturnString,'FOUR','4');

     vReturnString := replace(vReturnString,'FIVE','5');

     vReturnString := replace(vReturnString,'SIX','6');

     vReturnString := replace(vReturnString,'SEVEN','7');

     vReturnString := replace(vReturnString,'EIGHT','8');

     vReturnString := replace(vReturnString,'NINE','9');

     vReturnString := replace(vReturnString,'TEN','10');

     -- remove number suffixes

     vReturnString := replace(vReturnString,'ST','');

     vReturnString := replace(vReturnString,'ND','');

     vReturnString := replace(vReturnString,'RD','');

     vReturnString := replace(vReturnString,'TH','');

     -- return the result of to_number on our altered string,

     --  return pDefault if the conversion still fails

     return nvl(to_number(trim(vReturnString)),pDefault);

   exception

     when value_error then

       return pDefault;

   end ConvertToNumber_F;





  -- Create AuditHis Record

  PROCEDURE createaudithis_p(INOUT pvaudithisrow audithis, IN pparams tparams DEFAULT ax_pkg.ax_params) IS

  begin

    -- Grab next sequence value

    select audithis_audit_seq.nextval into pvAuditHisRow."Audit" from dual;

        

    -- Save audithis record

    InsertAuditHis_P(pvAuditHisRow,pParams);

  end CreateAuditHis_P;

  

  

  PROCEDURE insertaudithis_p(INOUT pvaudithisrow audithis, IN pparams tparams DEFAULT ax_pkg.ax_params) IS

    vParams tParams := pParams;

    exNoUser exception;

    exNoStationId exception;

    exNoTable exception;

    exNoHisType exception;

  begin    

    -- Initialization

    InitializeParams_P(vParams);

    InitializeAuditHis_P(pvAuditHisRow,vParams);   

  

    -- Validation

    if vParams."VerifyLevel" >= VERIFY_ERRORS then

      if vParams."User" is null then

        raise exNoUser;

      elsif vParams."StationId" is null then

        raise exNoStationId;

      elsif (trim(pvAuditHisRow."TableName") is null OR length(trim(pvAuditHisRow."TableName")) = 0) then

        raise exNoTable;

      elsif pvAuditHisRow."HistoryType" is null then

        raise exNoHisType;

      end if;

    end if;

    

    -- Grab next sequence value

    if pvAuditHisRow."Audit" is null then

      select audithis_audit_seq.nextval into pvAuditHisRow."Audit" from dual;

    end if;    

    

    -- Save audithis record

    insert into audithis 

    values (

      pvAuditHisRow."Audit",

      trunc(sysdate),

      to_number(to_char(sysdate, 'HH24'))* 60 + to_number(to_char(sysdate, 'MI')),

      pvAuditHisRow."User",

      pvAuditHisRow."StationId",

      upper(pvAuditHisRow."TableName"),

      pvAuditHisRow."HistoryType"

    );

    dbmsoutput_P(MSG_DML::integer,(to_char(SQL%rowcount) || ' audithis rows inserted.')::varchar2,vParams);



  exception 

    when exNoUser then

      dbmsoutput_P(MSG_ERROR,' No User Provided',vParams);

    when exNoStationId then

      dbmsoutput_P(MSG_ERROR,' No StationId Provided',vParams);

    when exNoTable then

      dbmsoutput_P(MSG_ERROR,' No Table Provided',vParams);

    when exNoHisType then

      dbmsoutput_P(MSG_ERROR,' No History Type Provided',vParams);

  end InsertAuditHis_P;

  



  -- Translate fitem."AnsType" into a string

  FUNCTION getanswertype_f(panstype numeric) RETURN character varying IS

    vReturnString  VARCHAR2(50);

  begin

    select decode(pAnsType, 

      ANSWER_YES_NO,'Yes/No',

      ANSWER_TEXT,'Text',

      ANSWER_NUMBER,'Number',

      ANSWER_LIST,'List',

      ANSWER_DATE,'Date',

      ANSWER_LONG_TEXT,'Long Text',

      ANSWER_IMAGE,'Image',

      ANSWER_CALCULATED,'Calculated',    

      ANSWER_ATTACHMENT,'Attachment',

      ANSWER_SPREADSHEET,'Spreadsheet',

      'Unknown'

    ) 

    into 

      vReturnString 

    from 

      dual;

    return vReturnString;

  end;      

  

  

  -- Translate audithis."HistoryType" into a string

  FUNCTION getaudithistype_f(phistorytype numeric) RETURN character varying IS

    vReturnString  VARCHAR2(50);

  begin

    select decode(pHistoryType, 

      AUDIT_UNKNOWN,'Unknown',

      AUDIT_ADD,'Insert',

      AUDIT_UPDATE,'Update',

      AUDIT_DELETE,'Delete',

      AUDIT_REBILL,'Rebill',

      AUDIT_MERGE,'Merge',

      AUDIT_CONVERTED,'Converted',

      AUDIT_ASAT,'As At',    

      null

    ) 

    into 

      vReturnString 

    from 

      dual;

    return vReturnString;

  end;

  

  

  -- Get the value of a Station Option, based on the Station and the Station Option ID

    -- Note that the function always returns a varchar2, even if the value type is Number, so convert to number accordingly

  FUNCTION getstationoption_f(pstationid numeric, pinidef numeric) RETURN character varying IS

    vReturnStr iniitem."ValueStr"%type;

    vReturnNum iniitem."ValueNum"%type;

    vType inidef."Type"%type;

  begin

    -- Get the value tied to this Station

    begin

      select

        ini."ValueNum",

        ini."ValueStr",

        ind."Type"

      into

        vReturnNum,

        vReturnStr,

        vType

      from

        iniitem ini

        inner join iniset ins on ins."Iniset" = ini."Iniset"

        inner join inidef ind on ind."Inidef" = ini."Inidef"

      where

        ins."Station" = pStationId and

        ind."Inidef" = pInidef

      ;

    exception

      when no_data_found then

      -- Get the value based on the Default

      select

        case when ind."Type" = 0 then to_number(ind."Default")

             else 0

        end "DefaultNum",

        ind."Default",

        ind."Type"

      into

        vReturnNum,

        vReturnStr,

        vType

      from

        inidef ind

      where

        ind."Inidef" = pInidef

      ;

    end;  

  

    if vType = 0 then

      return vReturnNum;

    else

      return vReturnStr;

    end if;  

  exception

    when no_data_found then

      -- this covers when the Default query returns a no_data_found

      return null;

  end GetStationOption_F;  

  

  

  -- Overload

    -- Allows you to check a station option by name

  FUNCTION getstationoption_f(pstationid numeric, pmodule character varying, psection character varying, pkey character varying) RETURN character varying IS

    vInidef inidef."Inidef"%type;

  begin

    -- Find the Inidef value

    select 

      "Inidef" into vInidef 

    from 

      inidef

    where

      "Module" = pModule and

      "Section" = pSection and

      "Key" = pKey;

    -- Call the parent function

    return GetStationOption_F(pStationId,vInidef);

  exception

    when no_data_found then

      return null;

  end GetStationOption_F;

  

  

  -- Creates an audithis record and returns the Audit value, if pMapAudit is null.

  FUNCTION getmapaudit_f(pmapaudit numeric DEFAULT NULL::numeric, pparams tparams DEFAULT ax_pkg.ax_params) RETURN numeric IS

    vAuditHisRow audithis%rowtype;

  begin

    if pMapAudit is null then

    -- Create Mapping Audit Record    

      vAuditHisRow."TableName" := 'AX_MAP';

      vAuditHisRow."HistoryType" := ax_pkg.AUDIT_ADD;

      ax_pkg.CreateAuditHis_P(vAuditHisRow,pParams);

      return vAuditHisRow."Audit";

    else

      return pMapAudit;

    end if;

  end GetMapAudit_F;



END;
CREATE OR REPLACE PACKAGE BODY ax_trx_pkg IS



  -- returns information about this package, or its procedures

  PROCEDURE help(IN pobjectname character varying DEFAULT NULL::character varying) IS

    vReturn CLOB;

  begin

    -- Writes the help to the DBMS_OUTPUT

	-- AX-39259

    vReturn := ax_pkg.Help_F('AX_TRX_PKG',pObjectName);

  end Help;





  FUNCTION gettrxid_f(ptrxrowtype numeric) RETURN numeric IS

  /**************************

  Author:       Brian Boicey

  Parameters:   Accepts -> TRX Type

                Returns -> TRX Id

  Description : This function determines the correct sequence based on the transaction Type

                and returns the next ID from that sequence

  

  ***************************/

    vTrxId trx."Id"%type;

  begin

       if pTrxRowType = 1 then --> Treatment

            select TRX_ID_TREATMENT_SEQ.nextval into vTrxId from dual;

            

       elsif pTrxRowType = 2 then --> Office charge

             select TRX_ID_OFFICECHARGES_SEQ.nextval into vTrxId from dual;

             

       elsif pTrxRowType = 3 then --> Patient Payment

            select TRX_ID_PAYMENT_SEQ.nextval into vTrxId from dual;

            

       elsif pTrxRowType = 4 then --> insurance Payment

            select TRX_ID_PAYMENT_SEQ.nextval into vTrxId from dual;   

            

       elsif pTrxRowType = 5 then -->Planned treatment

            select TRX_ID_PLANNEDTREATMENT_SEQ.nextval into vTrxId from dual;

                    

       elsif pTrxRowType = 6 then --> Adjustment

          select TRX_ID_ADJUSTMENT_SEQ.nextval into vTrxId from dual;

  

       elsif pTrxRowType = 7 then --> Insurance Adjustment

          select TRX_ID_INSADJUSTMENT_SEQ.nextval into vTrxId from dual;

  

       else  --Invalid TrxRowType

        vTrxId := 0;

       end if;

     

     return vTrxId;

  

  end GetTrxId_F;





  -- This procedure writes off an Insurance Balance

  -- pvTrxRec should contain the treatment record being written off with a couple of changes. 

  --   Bank should contain the bank code used if an insurance payment needs to be created. 

  --   User should contain the user that will be used on the TRX and ALLOCATE records that are updated/created

  --   StationId should contain the station that will be used on the TRX records that are updated/created

  --

  -- DO NOT USE FOR TREATMENTS ON PAYMENT PLANS (OrthoStatus = 1) or Unapproved Treatments (have existing chartlnk record)

  --

  PROCEDURE writeoffinsurancebalances_p(INOUT pvtrxrec trx, IN pnewpaymentmode numeric DEFAULT 0, IN pinsurancebucket numeric, IN ppaymentcode character, IN ppaymentdescription character varying, IN padjustmentcode character, IN padjustmentdescription character varying, IN padjustmentbalance numeric, INOUT pvinspaymentid numeric, INOUT pvinspaymenttotal numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN ppractice numeric DEFAULT 0) IS

    vInsAdjId trx."Id"%type := 0;

    vInsAdjTreatment number :=0;

    vOrigRecNo trx."OrigRecNo"%type;

    vToday date;

    vTodayTime date;

    vPaymentDate date;

    vPaymentCode payment."Payment"%type := pPaymentCode;

    vPaymentCompany trx."Company1"%type := pvTrxRec."Company1";

    vBank trx."Bank"%type := pvTrxRec."Bank";

    vTreatmentCount number;

    vTreatment number(5);

    vChart patient."Chart"%type;



    -- P189-155706.1

    vCompany trx."Company1"%type;

    vPolicy trx."Policy1"%type;

    vPolicyId trx."PolicyId1"%type;



    vStep number := 0;

  

    rowTrx trx%rowtype;

    

    vCheck number := 0;

	

	TxHistoryId         NUMBER(10);		--AX-26086

	PmtHistoryId        NUMBER(10);		--AX-26086

	AdjHistoryId        NUMBER(10);		--AX-26086	

	AllocateLinkId      NUMBER(10);		--AX-26086

	AdjAllocateLinkId   NUMBER(10);		--AX-26086

    ModifiedDate        DATE;           --AX-26086

    

    exFailedValidation exception;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

  

-- First Do Data Integrity checks

    if vParams."VerifyLevel" >= ax_pkg.VERIFY_ALL then



      begin

        select 1 into vCheck from bank where "Bank" = pvTrxRec."Bank";

      exception

        when no_data_found then

          ax_pkg.dbmsoutput_P(ax_pkg.MSG_WARNING,'Provided Bank Code of ' || pvTrxRec."Bank" || ' is invalid.',vParams);

          raise exFailedValidation;

      end;



      begin

        select 1 into vCheck from payment where "Payment" = pPaymentCode;

      exception

        when no_data_found then

          ax_pkg.dbmsoutput_P(ax_pkg.MSG_WARNING,'Provided Payment Code of ' || pPaymentCode || ' is invalid.',vParams);

          raise exFailedValidation;

      end;

      

      begin

        select 1 into vCheck from adjust where "Adjust" = pAdjustmentCode;

      exception

        when no_data_found then

          ax_pkg.dbmsoutput_P(ax_pkg.MSG_WARNING,'Provided Adjustment Code of ' || pAdjustmentCode || ' is invalid.',vParams);

          raise exFailedValidation;

      end;

      

      -- can also check Company and PolicyId

    end if; -- VERIFY_ALL Data Integrity Checks

    

    if vParams."VerifyLevel" >= ax_pkg.VERIFY_ERRORS then

      vStep := 5;

      select * into rowTrx from trx where "Type" = pvTrxRec."Type" and "Id" = pvTrxRec."Id" and "Treatment" = pvTrxRec."Treatment";

      

      -- If OrthoStatus = 1 then this treatment is on a Payment Plan, and should be ignored

      if rowTrx."OrthoStatus" = 1 then

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_WARNING,'Treatment is an Ortho Treatment on a Payment Plan.',vParams);

        raise exFailedValidation;

      end if;

      

      -- If treatment has a chartlnk record then it is linked to an unapproved treatment in the EHR

        -- The approval it is waiting for may be a Delete action

      if rowTrx."ChartTrx" != 0 then  -- P189-155706 added

        begin

          select 1 into vCheck from dual where exists (

            select 1 from chartlnk c 

            where 

              c."Previous" = rowTrx."ChartTrx" or 

              c."Auto"= rowTrx."ChartTrx");

          ax_pkg.dbmsoutput_P(ax_pkg.MSG_WARNING,'Treatment has unapproved changes (an existing chartlnk record).',vParams);

          raise exFailedValidation;

        exception

          when no_data_found then

            null;

        end;

      end if;

  

    end if; -- VERIFY_ERRORS Data Integrity Checks



    vToday := trunc(sysdate);

    vTodayTime := sysdate;

    pvInsPaymentTotal := pvInsPaymentTotal - pAdjustmentBalance; -- too many parameters taken away??



   -- P189-155706.1

   if pInsuranceBucket = 1 then

     vCompany := pvTrxRec."Company1";

     vPolicy := pvTrxRec."Policy1";

     vPolicyId := pvTrxRec."PolicyId1";

   elsif pInsuranceBucket = 2 then

     vCompany := pvTrxRec."Company2";

     vPolicy := pvTrxRec."Policy2";

     vPolicyId := pvTrxRec."PolicyId2";

   elsif pInsuranceBucket = 3 then

     vCompany := pvTrxRec."Company3";

     vPolicy := pvTrxRec."Policy3";

     vPolicyId := pvTrxRec."PolicyId3";

   end if;

   

   if pInsuranceBucket in (1,2,3) then  -- P189-155706.1

    

  -- 1.  Find last Type 4 Insurance payment for this company

      if pNewPaymentMode > 0 then

        select 

          nvl(max("Id"),0) into pvInsPaymentId 

        from trx 

        where 

          "Type"=4 and -- Insurance Payment

          "Deleted"=0 and -- Not Deleted

          -- Will always only be Bucket 1 for type 4

          "Company1" in ( -- Company must be the same company provided, or a parent/child of that company

            -- P189-155706.7 do not allow companies under the same parent from being used

            select "ParentCompany" from insgroup where "Company" = vCompany

            union select vCompany from dual

          ) and 

          "Code" = pPaymentCode and 

          "Total" = 0 and (

            pNewPaymentMode = 2 or   -- Use a previous Payment regardless of date

            "Date" = vToday  -- Use a previous Payment only if it is from today

          );

      end if;

      

      -- If we are not editing a previous payment, then create a new one

      if pvInsPaymentId =0 then

        -- Get Sequence Values

        select TRX_ORIGRECNO_SEQ.nextval into vOrigRecNo from dual;

        select TRX_ID_PAYMENT_SEQ.nextval into pvInsPaymentId from dual;

        -- Create trx record

        trx_pkg.InitializeTrx(rowTrx);

        -- Edit trx record

        rowTrx."Type" := 4;

        rowTrx."Id" := pvInsPaymentId;

        rowTrx."Treatment" := 1;

        rowTrx."TreatmentDate" := vToday; 

        vPaymentDate := vToday;

        rowTrx."Code" := pPaymentCode;

        rowTrx."Company1" := vCompany;  -- P189-155706.1

        vPaymentCompany := vCompany; -- P189-155706.2 added

        rowTrx."Description" := pPaymentDescription;

        rowTrx."Bank" := pvTrxRec."Bank";

        rowTrx."User" := nvl(pvTrxRec."User",vParams."User");

        rowTrx."StationId" := nvl(pvTrxRec."StationId",vParams."StationId");

        rowTrx."OrigRecNo" := vOrigRecNo;

        rowTrx."PayPlanId" := pvTrxRec."PayPlanId";

        rowTrx."EntryUser" := nvl(pvTrxRec."User",vParams."User");

        rowTrx."ModifiedDate" := vTodayTime;

        rowTrx."Practice" := pPractice;			-- AX-26015

		-- Save trx record

        trx_pkg.InsertTrx(rowTrx);



        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' trx rows inserted.',vParams);



    	-- AX-26086 Getting payment history id while inserting

		ax_trx_pkg.InsertHistory(rowTrx, PmtHistoryId);

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' history rows inserted.',vParams);

      else

      -- We are editing a previous payment, so find which one

        select 

          "TreatmentDate", "Code", "Company1", "Bank" into 

          vPaymentDate, vPaymentCode, vPaymentCompany, vBank

        from trx 

        where 

          "Type"=4 and 

          "Id"=pvInsPaymentId;

		  

        -- AX-26086

		select MAX("History") into PmtHistoryId from History where "Type"=4 and "Id"=pvInsPaymentId;



      end if;

      -- Find what the Treatment value should be

      select nvl(max("Treatment"),0) into vTreatmentCount from trx where "Type"=74 and "Id"=pvInsPaymentId;

        

  -- 2.  Create or find a Type 74 record for this patient

      select nvl(max("Treatment"),0) into vTreatment from trx where "Type"=74 and "Id"=pvInsPaymentId and "Patient"=pvTrxRec."Patient" and "PayPlanId"=pvTrxRec."PayPlanId";

  

     -- If no Type 74 is found, we need to create one

      if vTreatment = 0 then

        vTreatmentCount := vTreatmentCount + 1;

        vTreatment := vTreatmentCount;

        -- Get Sequence Values

        select TRX_ORIGRECNO_SEQ.nextval into vOrigRecNo from dual;

        -- Create trx record

        trx_pkg.InitializeTrx(rowTrx);

        -- Edit trx record

        rowTrx."Type" := 74;

        rowTrx."Id" := pvInsPaymentId;

        rowTrx."Treatment" := vTreatment;

        rowTrx."Patient" := pvTrxRec."Patient";

        rowTrx."Family" := pvTrxRec."Patient";

        rowTrx."Date" := vPaymentDate;

        rowTrx."TreatmentDate" := vPaymentDate; 

        rowTrx."CreationDate" := vPaymentDate; 

        rowTrx."Code" := vPaymentCode;      

        rowTrx."Company1" := vPaymentCompany;      

        rowTrx."Description" := pPaymentDescription;      

        rowTrx."Bank" := vBank;      

        rowTrx."User" := nvl(pvTrxRec."User",vParams."User");

        rowTrx."StationId" := nvl(pvTrxRec."StationId",vParams."StationId");      

        rowTrx."OrigRecNo" := vOrigRecNo;   

        rowTrx."PayPlanId" := pvTrxRec."PayPlanId";

        rowTrx."EntryUser" := nvl(pvTrxRec."User",vParams."User");

        rowTrx."ModifiedDate" := vTodayTime;

        -- Save trx record

        trx_pkg.InsertTrx(rowTrx);

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' trx rows inserted.',vParams);

        

		-- Create History Record

        trx_pkg.InsertHistory(rowTrx);

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' history rows inserted.',vParams);

      else

        -- P189-155706.9 if a Type 74 already exists update it

        update trx

        set "ModifiedDate" = vTodayTime,

          "User" = nvl(pvTrxRec."User",vParams."User"),

          "StationId" = nvl(pvTrxRec."StationId",vParams."StationId"),

          "Deleted" = 0,

          "DeletionDate" = null

        where 1=1

          and "Type" = 74 

          and "Id" = pvInsPaymentId 

          and "Patient" = pvTrxRec."Patient" 

          and "PayPlanId" = pvTrxRec."PayPlanId"

          and "Treatment" = vTreatment;

          

        insert into history (

          select history_history_seq.nextval,

            3,

            trx.*

          from trx

          where 1=1

            and "Type" = 74 

            and "Id" = pvInsPaymentId 

            and "Patient" = pvTrxRec."Patient" 

            and "PayPlanId" = pvTrxRec."PayPlanId"

            and "Treatment" = vTreatment

        );

      end if;

      

	  -- 3.  Add ALLOCATE for insurance pmt apply to Treatment

      SELECT ALLOCATELINK_LINK_SEQ.NEXTVAL INTO AllocateLinkId FROM dual;	-- AX-26086



	  begin

        

		-- Create a new Allocate Record

        insert into allocate values (

          4,             -- PayType, 4 = Insurance Payment

          pvInsPaymentId, -- PayId

          1,             -- PayTreatment

          pvTrxRec."Type",         -- TrxType

          pvTrxRec."Id",           -- TrxId

          pvTrxRec."Treatment",    -- TrxTreatment

          vPolicyId,    -- PolicyId  -- P189-155706.2

          0,             -- Amount

          nvl(pvTrxRec."User",vParams."User"),          -- User

          AllocateLinkId              --AllocateLink id (AX-25978.2), AX-26086

        );

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' allocate rows inserted.',vParams);

      exception

      when DUP_VAL_ON_INDEX then

        -- Allocate Record already exists, so update the one that is there

		update allocate 

        set 

          "User"=nvl(pvTrxRec."User",vParams."User"),

		  "AllocateLink" = AllocateLinkId

        where 

          "PayType"=4 and 

          "PayId"=pvInsPaymentId and 

          "PayTreatment"=1 and 

          "TrxType"=pvTrxRec."Type" and

          "TrxId"=pvTrxRec."Id" and 

          "TrxTreatment"=pvTrxRec."Treatment" and

          "PolicyId" = vPolicyId;  -- P189-155706.2

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' allocate rows updated.',vParams);

      end;



  -- 4.  Add TRX for insurance adjustment

      -- Get Sequence Values

      select TRX_ID_INSADJUSTMENT_SEQ.nextval into vInsAdjId from dual;  

      select TRX_ORIGRECNO_SEQ.nextval into vOrigRecNo from dual;

      -- Calculate the Adjustment Treatment Value

      vInsAdjTreatment := 3 * pvTrxRec."Treatment" + pInsuranceBucket - 1;

      -- Create trx record

      trx_pkg.InitializeTrx(rowTrx);

      -- Edit trx record

      rowTrx."Type" := 7;

      rowTrx."Id" := vInsAdjId;

      rowTrx."Treatment" := vInsAdjTreatment;

      rowTrx."Patient" := pvTrxRec."Patient";

      rowTrx."Family" := pvTrxRec."Patient";

      rowTrx."Date" := vToday;

      rowTrx."TreatmentDate" := vToday;    

      rowTrx."CreationDate" := vToday;

      rowTrx."Code" := pAdjustmentCode;

      rowTrx."Total" := -pAdjustmentBalance;

      rowTrx."InsTotal" := -pAdjustmentBalance;

      rowTrx."Company1" := vCompany;  -- P189-155706.2

      rowTrx."Policy1" := vPolicy;  -- P189-155706.4 Set Policy1 correctly 

      rowTrx."PolicyId1" := vPolicyId;  -- P189-155706.4 added to set PolicyId1

      rowTrx."Description" := pAdjustmentDescription;

      rowTrx."User" := nvl(pvTrxRec."User",vParams."User");

      rowTrx."StationId" := nvl(pvTrxRec."StationId",vParams."StationId");      

      rowTrx."OrigRecNo" := vOrigRecNo;

      rowTrx."PayPlanId" := pvTrxRec."PayPlanId";

      rowTrx."InsPmtId" := pvInsPaymentId;

      rowTrx."EntryUser" := nvl(pvTrxRec."User",vParams."User");

      rowTrx."ModifiedDate" := vTodayTime;

      rowTrx."Practice" := pPractice;			-- AX-26015

	  -- Save trx record

      trx_pkg.InsertTrx(rowTrx);

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' trx rows inserted.',vParams);

      -- Create History Record

	  

	  ax_trx_pkg.InsertHistory(rowTrx, AdjHistoryId);	-- AX-26086

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' history rows inserted.',vParams);

  -- 5.  Add ALLOCATE for insurance adj apply to Treatment

      begin



        -- Create a new Allocate Record

        SELECT ALLOCATELINK_LINK_SEQ.NEXTVAL INTO AdjAllocateLinkId FROM dual; 	--AX-26086

		

        insert into allocate values (

          7,                   -- PayType, 7 = Insurance Adjustment

          vInsAdjId,           -- PayId

          vInsAdjTreatment,    -- PayTreatment

          pvTrxRec."Type",               -- TrxType

          pvTrxRec."Id",                 -- TrxId

          pvTrxRec."Treatment",          -- TrxTreatment

          vPolicyId,           -- PolicyId  -- P189-155706.2

          -pAdjustmentBalance, -- Amount

          nvl(pvTrxRec."User",vParams."User"),                -- User

          AdjAllocateLinkId              --AllocateLink id (AX-25978.2), AX-26086

        );



        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' allocate rows inserted.',vParams);

      exception

      when DUP_VAL_ON_INDEX then

        -- Allocate Record already exists, so update the one that is there

        update allocate 

        set 

          "Amount" = "Amount" - pAdjustmentBalance,        

          "User"=nvl(pvTrxRec."User",vParams."User"),

		  "AllocateLink" = AdjAllocateLinkId	--AX-26086

        where 

          "PayType"=7 and 

          "PayId"=vInsAdjId and 

          "PayTreatment"=vInsAdjTreatment and 

          "TrxType"=pvTrxRec."Type" and

          "TrxId"=pvTrxRec."Id" and 

          "TrxTreatment"=pvTrxRec."Treatment" and

          "PolicyId" = vPolicyId;  -- P189-155706.2

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' allocate rows updated.',vParams);

      end;

      

  -- new 6 for Reserve Funds?    

      

  -- 6.  Update the Treatment record



      -- P189-155706.2

      if pInsuranceBucket = 1 then

        update trx set 

          "InsAdj1"= "InsAdj1" + pAdjustmentBalance,

          "InsAdj"="InsAdj" + pAdjustmentBalance,

          "InsStatus1"=2,

          "User"=nvl(pvTrxRec."User",vParams."User"), 

          "StationId"=nvl(pvTrxRec."StationId",vParams."StationId"), 

          "ModifiedDate"=vTodayTime,

          "Submitted"=1

        where 

          "Type"=pvTrxRec."Type" and

          "Id"=pvTrxRec."Id" and 

          "Treatment"=pvTrxRec."Treatment";

      elsif pInsuranceBucket = 2 then

        update trx set 

          "InsAdj2"= "InsAdj2" + pAdjustmentBalance,

          "InsAdj"="InsAdj" + pAdjustmentBalance,

          "InsStatus2"=2,

          "User"=nvl(pvTrxRec."User",vParams."User"), 

          "StationId"=nvl(pvTrxRec."StationId",vParams."StationId"), 

          "ModifiedDate"=vTodayTime,

          "Submitted"=1

        where 

          "Type"=pvTrxRec."Type" and

          "Id"=pvTrxRec."Id" and 

          "Treatment"=pvTrxRec."Treatment";

      elsif pInsuranceBucket = 3 then

        update trx set 

          "InsAdj3"= "InsAdj3" + pAdjustmentBalance,

          "InsAdj"="InsAdj" + pAdjustmentBalance,

          "InsStatus3"=2,

          "User"=nvl(pvTrxRec."User",vParams."User"), 

          "StationId"=nvl(pvTrxRec."StationId",vParams."StationId"), 

          "ModifiedDate"=vTodayTime,

          "Submitted"=1

        where 

          "Type"=pvTrxRec."Type" and

          "Id"=pvTrxRec."Id" and 

          "Treatment"=pvTrxRec."Treatment";

      end if;



      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' trx rows updated.',vParams);



      -- AX-26086

	  SELECT HISTORY_HISTORY_SEQ.nextval INTO TxHistoryId FROM dual;



      insert into HISTORY (

        select TxHistoryId, 3, trx.* from trx where "Type"=pvTrxRec."Type" and

        "Id"=pvTrxRec."Id" and 

        "Treatment"=pvTrxRec."Treatment"

      );



      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' history rows inserted.',vParams);



	  -- AX-26086

      SELECT sysdate into ModifiedDate from dual;

	  insert into AllocateLink values (AllocateLinkId, TxHistoryId, PmtHistoryId, ModifiedDate);

	  insert into AllocateLink values (AdjAllocateLinkId, TxHistoryId, AdjHistoryId, ModifiedDate);



    end if; -- pInsuranceBucket in (1,2,3)

    

  exception

    when exFailedValidation then

      if vParams."VerboseType" >= ax_pkg.SHOW_INFO and pvTrxRec."Patient" > 0 then

        select "Chart" into vChart from patient where "Patient" = pvTrxRec."Patient";

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_ERROR,

          'Validation Checks Failed. Not Writing Off Balance. Chart=' || vChart || ' Type=' || pvTrxRec."Type" || ' Id=' || pvTrxRec."Id" || ' Treatment=' || pvTrxRec."Treatment",

          vParams);

      else

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_ERROR,

          'Validation Checks Failed. Not Writing Off Balance. Type=' || pvTrxRec."Type" || ' Id=' || pvTrxRec."Id" || ' Treatment=' || pvTrxRec."Treatment",

          vParams);

      end if;

	  when others then

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_ERROR,

          'Exception at Step ' || vStep || ':' || sqlerrm,

          vParams);

      rollback;	

  end WriteOffInsuranceBalances_P;

  

  

  -- 

  PROCEDURE updateinsurancepaymenttotal_p(IN pinspaymentid numeric, IN pinspaymenttotal numeric, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    -- update the total on type 4 ins payment

    update TRX set 

      "Total"=pInsPaymentTotal, 

      "InsTotal"=pInsPaymentTotal,

      "User"=vParams."User",

      "StationId"=vParams."StationId",

      "ModifiedDate"=sysdate

    where 

      "Type"=4 and 

      "Id"=pInsPaymentId;

      

    if SQL%rowcount < 1 then

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_WARNING,

          'Insurance Payment Not Found. Id=' || pInsPaymentId,vParams);

    end if;

      

    update HISTORY set 

      "Total"=pInsPaymentTotal, 

      "InsTotal"=pInsPaymentTotal, 

      "InsPayed"=pInsPaymentTotal 

    where 

      "Type"=4 and 

      "Id"=pInsPaymentId and 

      "HistoryType"=1;

      

    insert into HISTORY (

      select

        HISTORY_HISTORY_SEQ.nextval,

        3,

        trx.*

      from TRX 

      where 

        "Type"=4 and 

        "Id"=pInsPaymentId

    );

  end UpdateInsurancePaymentTotal_P;

  

  

  PROCEDURE writeoffpatientpayments_p(INOUT pvtrxrec trx, INOUT pvadjustment numeric, IN padjustmentbalance numeric, IN padjustmentcode character, IN padjustmentdescription character varying, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN ppractice numeric DEFAULT 0) IS

    vOrigRecNo trx."OrigRecNo"%type;  

    vToday date;

    vTodayTime date := sysdate;  -- P189-158456

    vChart patient."Chart"%type;

    rowTrx trx%rowtype;

    

    vCheck number := 0;

    exFailedValidation exception;

    vParams ax_pkg.tParams := pParams;

	

	PmtHistoryId        NUMBER(10);		--AX-26086

	AdjHistoryId        NUMBER(10);		--AX-26086

	AllocateLinkId      NUMBER(10);		--AX-26086

    ModifiedDate        DATE;           --AX-26086



  begin

    ax_pkg.InitializeParams_P(vParams);

  

-- First Do Data Integrity checks

    if vParams."VerifyLevel" >= ax_pkg.VERIFY_ALL then

      begin

        select 1 into vCheck from adjust where "Adjust" = pAdjustmentCode;

      exception

        when no_data_found then

          ax_pkg.dbmsoutput_P(ax_pkg.MSG_WARNING,'Provided Adjustment Code of ' || pAdjustmentCode || ' is invalid.',vParams);

          raise exFailedValidation;

      end;

    end if; -- VERIFY_ALL Data Integrity Checks



  

    vToday := trunc(sysdate);

-- 1. Create/Edit W/O adjustment record

    

    if pvAdjustment is null or pvAdjustment = 0 then

    --Adjustment does not exist, create it

      -- Get Sequence Values

      select TRX_ID_ADJUSTMENT_SEQ.nextval into pvAdjustment from dual;

      select TRX_ORIGRECNO_SEQ.nextval into vOrigRecNo from dual;

      -- Create trx record

      trx_pkg.InitializeTrx(rowTrx);

      -- Edit trx record

      rowTrx."Type" := 6;

      rowTrx."Id" := pvAdjustment;

      rowTrx."Treatment" := 1;

      rowTrx."Patient" := pvTrxRec."Patient";

      rowTrx."Family" := pvTrxRec."Patient";    

      rowTrx."TreatmentDate" := vToday;

      rowTrx."CreationDate" := vToday;    

      rowTrx."Code" := pAdjustmentCode;    

      rowTrx."Total" := pAdjustmentBalance;

      rowTrx."Description" := pAdjustmentDescription;

      rowTrx."User" := nvl(pvTrxRec."User",vParams."User");

      rowTrx."StationId" := nvl(pvTrxRec."StationId",vParams."StationId");      

      rowTrx."OrigRecNo" := vOrigRecNo;

      rowTrx."PayPlanId" := pvTrxRec."PayPlanId";

      rowTrx."EntryUser" := nvl(pvTrxRec."User",vParams."User");      

      rowTrx."ModifiedDate" := vTodayTime;  -- P189-158456

	  rowTrx."Practice" := pPractice;		-- AX-26015

      -- Save trx record

      trx_pkg.InsertTrx(rowTrx);

      

	  -- Create History Record

	  ax_trx_pkg.InsertHistory(rowTrx, AdjHistoryId);		-- AX-26086

    else

      update trx

      set 

        "Total"="Total" - pAdjustmentBalance,

        "User"=nvl(pvTrxRec."User",vParams."User"), 

        "StationId"=nvl(pvTrxRec."StationId",vParams."StationId"), 

--        "ModifiedDate"=sysdate   -- P189-158456

        "ModifiedDate"=vTodayTime  -- P189-158456

      where 

        "Type"=6 and 

        "Id"=pvAdjustment and 

        "Treatment"=1;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' trx rows updated.',vParams);

      

	  SELECT HISTORY_HISTORY_SEQ.nextval INTO AdjHistoryId FROM dual;	-- AX-26086



	  insert into history (

        select

          AdjHistoryId,  --History

          2,        --HistoryType

          t.* 

        from 

          trx t 

        where 

          "Type"=6 and 

          "Id"=pvAdjustment and 

          "Treatment"=1

      );

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' history rows inserted.',vParams);

    end if;

    

	-- 2. Create ALLOCATE record

    begin

	

      -- Create a new Allocate Record

      SELECT ALLOCATELINK_LINK_SEQ.NEXTVAL INTO AllocateLinkId FROM dual; 	--AX-26086



      insert into allocate values (

        6,                   -- PayType, 7 = Insurance Adjustment

        pvAdjustment,        -- PayId

        1,                   -- PayTreatment

        pvTrxRec."Type",               -- TrxType

        pvTrxRec."Id",                 -- TrxId

        pvTrxRec."Treatment",          -- TrxTreatment

        0,                   -- PolicyId

        pAdjustmentBalance, -- Amount  -- SF-00247556 changed from -pAdjustmentBalance

        nvl(pvTrxRec."User",vParams."User"),                -- User

        AllocateLinkId              --AllocateLink id (AX-25978.2), AX-26086

      );

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' allocate rows inserted.',vParams);

    exception

    when DUP_VAL_ON_INDEX then

      -- Allocate Record already exists, so update the one that is there

	  update allocate 

      set 

        "Amount" = "Amount" + pAdjustmentBalance,        -- SF-00247556 changed from - to +

        "User"=nvl(pvTrxRec."User",vParams."User"),

        "AllocateLink" = AllocateLinkId					--AX-26086

	  where 

        "PayType"=6 and 

        "PayId"=pvAdjustment and 

        "PayTreatment"=1 and 

        "TrxType"=pvTrxRec."Type" and

        "TrxId"=pvTrxRec."Id" and 

        "TrxTreatment"=pvTrxRec."Treatment" and

        "PolicyId" = 0;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' allocate rows updated.',vParams);

    end;

-- 3. Update PtAdj on trx record

    update trx 

    set 

      "PtAdj" = "PtAdj" + pAdjustmentBalance,  -- SF-00247556 changed from - to +

      "User"=nvl(pvTrxRec."User",vParams."User"), 

      "StationId"=nvl(pvTrxRec."StationId",vParams."StationId"), 

--      "ModifiedDate"=sysdate   -- P189-158456

      "ModifiedDate"=vTodayTime  -- P189-158456

    where 

      "Type"=pvTrxRec."Type" and

      "Id"=pvTrxRec."Id" and 

      "Treatment"=pvTrxRec."Treatment";

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' trx rows updated.',vParams);

   

	SELECT HISTORY_HISTORY_SEQ.nextval INTO PmtHistoryId FROM dual;		    -- AX-26086



    insert into history (

      select

        PmtHistoryId,  --History

        2,        --HistoryType

        t.* 

      from 

        trx t 

      where 

        "Type"=pvTrxRec."Type" and

        "Id"=pvTrxRec."Id" and 

        "Treatment"=pvTrxRec."Treatment"

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' history rows inserted.',vParams);



	SELECT sysdate into ModifiedDate from dual;								--AX-26086.26282

	insert into AllocateLink values (AllocateLinkId, PmtHistoryId, AdjHistoryId, ModifiedDate);		--AX-26086



  exception

    when exFailedValidation then

      if vParams."VerboseType" >= ax_pkg.SHOW_INFO and pvTrxRec."Patient" > 0 then

        select "Chart" into vChart from patient where "Patient" = pvTrxRec."Patient";

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_ERROR,

          'Validation Checks Failed. Not Writing Off Balance. Chart=' || vChart || ' Type=' || pvTrxRec."Type" || ' Id=' || pvTrxRec."Id" || ' Treatment=' || pvTrxRec."Treatment",

          vParams);

      else

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_ERROR,

          'Validation Checks Failed. Not Writing Off Balance. Type=' || pvTrxRec."Type" || ' Id=' || pvTrxRec."Id" || ' Treatment=' || pvTrxRec."Treatment",

          vParams);

      end if;

  end WriteOffPatientPayments_P;

  



  -- Write off patient balances on the passed in Type 1 or Type 2 transaction

  -- pvTrxRec : the treatment or office charge that is being written off

  -- pvAdjustment : TRX.Id of the adjustment. If null or 0 a new adjustment will be created, otherwise the passed in adjustment will be edited

  -- pAdjustmentAmount : Amount of the adjustment. For a write off this should be a negative value

  -- pAdjustmentCode : Adjustment code to use

  -- pAdjustmentDescription : Description to be used if creating a new adjustment

  -- pParams : parameters that define the detail of verifying to be done and amount of logging to be done

  PROCEDURE writeoffpatientbalances_p(INOUT pvtrxrec trx, INOUT pvadjustment numeric, IN padjustmentamount numeric, IN padjustmentcode character, IN padjustmentdescription character varying, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN ppractice numeric DEFAULT 0) IS

    vOrigRecNo trx."OrigRecNo"%type;  

    vToday date;

    vTodayTime date := sysdate;  -- P189-158456

    vChart patient."Chart"%type;

    rowTrx trx%rowtype;

  

	TxHistoryId			NUMBER(10);		--AX-26086

	AdjHistoryId        NUMBER(10);		--AX-26086

	AllocateLinkId      NUMBER(10);		--AX-26086

    ModifiedDate        DATE;           --AX-26086



    vCheck number := 0;

    exFailedValidation exception;

  begin

  

-- First Do Data Integrity checks

    if pParams."VerifyLevel" >= ax_pkg.VERIFY_ALL then

      begin

        select 1 into vCheck from adjust where "Adjust" = pAdjustmentCode;

      exception

        when no_data_found then

          ax_pkg.dbmsoutput_P(ax_pkg.MSG_WARNING,'Provided Adjustment Code of ' || pAdjustmentCode || ' is invalid.',pParams);

          raise exFailedValidation;

      end;

    end if; -- VERIFY_ALL Data Integrity Checks



    if pParams."VerifyLevel" >= ax_pkg.VERIFY_ERRORS then

    

      -- verify the passed in record is a type 1 or 2

      if pvTrxRec."Type" not in (1,2) then

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_WARNING,'Transaction is not a treatment or office charge.',pParams);

        raise exFailedValidation;

      end if;

      

      -- If OrthoStatus = 1 then this treatment is on a Payment Plan, and should be ignored

      if pvTrxRec."OrthoStatus" = 1 then

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_WARNING,'Treatment is an Ortho Treatment on a Payment Plan.',pParams);

        raise exFailedValidation;

      end if;

      

      -- If treatment has a chartlnk record then it is linked to an unapproved treatment in the EHR

        -- The approval it is waiting for may be a Delete action

      if pvTrxRec."ChartTrx" != 0 then

        begin

          select 1 into vCheck from dual where exists (

            select 1 from chartlnk c 

            where 

              c."Previous" = pvTrxRec."ChartTrx" or 

              c."Auto"= pvTrxRec."ChartTrx");

          ax_pkg.dbmsoutput_P(ax_pkg.MSG_WARNING,'Treatment has unapproved changes (an existing chartlnk record).',pParams);

          raise exFailedValidation;

        exception

          when no_data_found then

            null;

        end;

      end if;

  

      -- if an office charge (Type=2) make sure it is not a pre-pay

      if pvTrxRec."Type" = 2 then

        begin

          select 1 into vCheck from ofcharge o where o."OfficeCharge"=pvTrxRec."Code" and o."IsPrepay"=1;

          ax_pkg.dbmsoutput_P(ax_pkg.MSG_WARNING,'Office charge is a pre-payment.',pParams);

          raise exFailedValidation;

        exception

          when no_data_found then

            null;

        end;

      end if;

      

      -- verify pvAdjustment points to a valid adjustment record

      if pvAdjustment != 0 then

        begin

          select 1 into vCheck from trx where 

            "Type"=6 and 

            "Id"=pvAdjustment and 

            "Treatment"=1 and

            "Family" = pvTrxRec."Family" and

            "PayPlanId" = pvTrxRec."PayPlanId" and

            "Deleted"=0;

        exception

        when no_data_found then

          ax_pkg.dbmsoutput_P(ax_pkg.MSG_WARNING,'Adjustment with id ' || pvAdjustment || ' does not exist or has invalid payplanid for patient' || pvTrxRec."Family",pParams);

          raise exFailedValidation;

        end;

      end if;

      

    end if; -- VERIFY_ERRORS Data Integrity Checks



  

    vToday := trunc(sysdate);

-- 1. Create/Edit W/O adjustment record

    

    if pvAdjustment is null or pvAdjustment = 0 then

    --Adjustment does not exist, create it

      -- Get Sequence Values

      select TRX_ID_ADJUSTMENT_SEQ.nextval into pvAdjustment from dual;

      select TRX_ORIGRECNO_SEQ.nextval into vOrigRecNo from dual;

      -- Create trx record

      trx_pkg.InitializeTrx(rowTrx);

      -- Edit trx record

      rowTrx."Type" := 6;

      rowTrx."Id" := pvAdjustment;

      rowTrx."Treatment" := 1;

      rowTrx."Patient" := pvTrxRec."Patient";

      rowTrx."Family" := pvTrxRec."Patient";    

      rowTrx."TreatmentDate" := vToday;

      rowTrx."CreationDate" := vToday;    

      rowTrx."Code" := pAdjustmentCode;    

      rowTrx."Total" := pAdjustmentAmount;

      rowTrx."Description" := pAdjustmentDescription;

      rowTrx."User" := nvl(pvTrxRec."User",pParams."User");

      rowTrx."StationId" := nvl(pvTrxRec."StationId",pParams."StationId");      

      rowTrx."OrigRecNo" := vOrigRecNo;

      rowTrx."PayPlanId" := pvTrxRec."PayPlanId";

      rowTrx."EntryUser" := nvl(pvTrxRec."User",pParams."User");      

      rowTrx."ModifiedDate" := vTodayTime;  -- P189-158456

      rowTrx."Practice" := pPractice;		-- AX-26015

	  -- Save trx record

      trx_pkg.InsertTrx(rowTrx);



      -- Create History Record

	  ax_trx_pkg.InsertHistory(rowTrx, AdjHistoryId);		--AX-26086

    else



      update trx

      set 

        "Total"="Total" + pAdjustmentAmount,

        "User"=nvl(pvTrxRec."User",pParams."User"), 

        "StationId"=nvl(pvTrxRec."StationId",pParams."StationId"), 

--        "ModifiedDate"=sysdate   -- P189-158456

        "ModifiedDate"=vTodayTime  -- P189-158456

      where 

        "Type"=6 and 

        "Id"=pvAdjustment and 

        "Treatment"=1;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' trx rows updated.',pParams);

      

	  SELECT HISTORY_HISTORY_SEQ.nextval INTO AdjHistoryId FROM dual;	-- AX-26086



	  insert into history (

        select

          AdjHistoryId,  --History, AX-26086

          2,        --HistoryType

          t.* 

        from 

          trx t 

        where 

          "Type"=6 and 

          "Id"=pvAdjustment and 

          "Treatment"=1

      );

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' history rows inserted.',pParams);

    end if;

    

-- 2. Create ALLOCATE record

    begin

	

      -- Create a new Allocate Record

      SELECT ALLOCATELINK_LINK_SEQ.NEXTVAL INTO AllocateLinkId FROM dual; 	--AX-26086



      insert into allocate values (

        6,                   -- PayType, 6 = Insurance Adjustment

        pvAdjustment,        -- PayId

        1,                   -- PayTreatment

        pvTrxRec."Type",     -- TrxType

        pvTrxRec."Id",       -- TrxId

        pvTrxRec."Treatment",-- TrxTreatment

        0,                   -- PolicyId

        pAdjustmentAmount,   -- Amount

        nvl(pvTrxRec."User",pParams."User"),                -- User

        AllocateLinkId              --AllocateLink id (AX-25978.2), AX-26086

      );

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' allocate rows inserted.',pParams);

    exception

    when DUP_VAL_ON_INDEX then

	

      -- Allocate Record already exists, so update the one that is there

      update allocate 

      set 

        "Amount" = "Amount" + pAdjustmentAmount,        

        "User"=nvl(pvTrxRec."User",pParams."User"),

		"AllocateLink" = AllocateLinkId			--AX-26086

      where 

        "PayType"=6 and 

        "PayId"=pvAdjustment and 

        "PayTreatment"=1 and 

        "TrxType"=pvTrxRec."Type" and

        "TrxId"=pvTrxRec."Id" and 

        "TrxTreatment"=pvTrxRec."Treatment" and

        "PolicyId" = 0;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' allocate rows updated.',pParams);

    end;

-- 3. Update PtAdj on trx record

    update trx 

    set 

      "PtAdj" = "PtAdj" + pAdjustmentAmount,

      "User"=nvl(pvTrxRec."User",pParams."User"), 

      "StationId"=nvl(pvTrxRec."StationId",pParams."StationId"), 

--      "ModifiedDate"=sysdate   -- P189-158456

      "ModifiedDate"=vTodayTime  -- P189-158456

    where 

      "Type"=pvTrxRec."Type" and

      "Id"=pvTrxRec."Id" and 

      "Treatment"=pvTrxRec."Treatment";

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' trx rows updated.',pParams);

      

	SELECT HISTORY_HISTORY_SEQ.nextval INTO TxHistoryId FROM dual;	-- AX-26086



    insert into history (

      select

        TxHistoryId,  --History, AX-26086

        3,        --HistoryType

        t.* 

      from 

        trx t 

      where 

        "Type"=pvTrxRec."Type" and

        "Id"=pvTrxRec."Id" and 

        "Treatment"=pvTrxRec."Treatment"

    );

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' history rows inserted.',pParams);



	SELECT sysdate into ModifiedDate from dual;								--AX-26086.26282

	insert into AllocateLink values (AllocateLinkId, TxHistoryId, AdjHistoryId, ModifiedDate);		--AX-26086



  exception

    when exFailedValidation then

      if pParams."VerboseType" >= ax_pkg.SHOW_INFO and pvTrxRec."Patient" > 0 then

        select "Chart" into vChart from patient where "Patient" = pvTrxRec."Patient";

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_ERROR,

          'Validation Checks Failed. Not Writing Off Balance. Chart=' || vChart || ' Type=' || pvTrxRec."Type" || ' Id=' || pvTrxRec."Id" || ' Treatment=' || pvTrxRec."Treatment",

          pParams);

      else

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_ERROR,

          'Validation Checks Failed. Not Writing Off Balance. Type=' || pvTrxRec."Type" || ' Id=' || pvTrxRec."Id" || ' Treatment=' || pvTrxRec."Treatment",

          pParams);

      end if;

  end WriteOffPatientBalances_P;  





  -- Initilize a new PolIns Record

  PROCEDURE initializepolins_p(INOUT pvpolinsrow polins, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    -- Setup

    select polins_polins_seq.nextval into pvPolInsRow."PolIns" from dual;

    select policy_SharedEntryId_seq.nextval into pvPolInsRow."SharedEntryId" from dual;

    

    pvPolInsRow."User" := vParams."User";

    pvPolInsRow."StationId" := vParams."StationId";

  

    -- Set to Default Values  

    pvPolInsRow."Group" := '';

    pvPolInsRow."Division" := '';

    pvPolInsRow."FormsTo" := 0;

    pvPolInsRow."Company" := '';

    pvPolInsRow."GovPolicy" := '';

    pvPolInsRow."Fee" := '';

    pvPolInsRow."Employer" := 0;

    pvPolInsRow."HasFamilyLimit" := 0;

    pvPolInsRow."FamilyDeduct" := 0;

    pvPolInsRow."FamilyLimit" := 0;

    pvPolInsRow."HasPatientLimit" := 0;

    pvPolInsRow."PatientDeduct" := 0;

    pvPolInsRow."PatientLimit" := 0;

    pvPolInsRow."YearEnd" := 1;

    pvPolInsRow."Assignment" := 1;

    pvPolInsRow."Signature" := 0;

    pvPolInsRow."ChangeDate" := sysdate;

    pvPolInsRow."CvgPct" := '';

    pvPolInsRow."WriteOff" := 0;

    pvPolInsRow."Deleted" := 0;

    pvPolInsRow."PlanType" := 0;

    pvPolInsRow."MonthlyDeduct" := 0;

    pvPolInsRow."Date" := trunc(sysdate);

    pvPolInsRow."Time" :=  (to_number(to_char(sysdate,'HH24')) * 60) + to_number(to_char(sysdate,'MI'));

    pvPolInsRow."TrojanId" := '';

    pvPolInsRow."YearEndDay" := 1;

    pvPolInsRow."ChildCoverage" := 0;

    pvPolInsRow."AdultCoverage" := 0;

    pvPolInsRow."Copay" := 0;

    --pvPolInsRow."SharedEntryId" := 0;

    pvPolInsRow."Description" := '';

    pvPolInsRow."SharablePlan" := 1;

    pvPolInsRow."StartDate" := null;

    pvPolInsRow."EndDate" := null;

    pvPolInsRow."VisitFee" := 0;

    pvPolInsRow."CoverageAge" := 0;

    pvPolInsRow."CoverageAgeStud" := 0;

    pvPolInsRow."OrigRecNo" := pvPolInsRow."PolIns";

    pvPolInsRow."EDIFlag" := 0;    

    -- P189-155143 added following

    pvPolInsRow."CoverageAgeYoungAdult" := 0;

    pvPolInsRow."YoungAdultCoverage" := 0;

    pvPolInsRow."CvgOnBirthChild" := 0;

    pvPolInsRow."CvgOnBirthStudent" := 0;

    pvPolInsRow."CvgOnBirthYoungAdult" := 0;

    pvPolInsRow."ChargeDedAndPtChg" := 0;

  end InitializePolIns_P;

  



  -- This procedure copies a Benefit Plan based on pvSourcePolIns."PolIns"

  --  This replaces InitializePolIns_P for the pvTargetPolInsRow

  -- The new Benefit Plan must have one of these differences set in pvTargetPolInsRow

    -- pvTargetPolInsRow."Company"

  PROCEDURE copybenefitplan_p(INOUT pvsuccess boolean, IN psourcepolins numeric, INOUT pvtargetpolinsrow polins, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    cursor curPolRange (pPolIns polrange."PolIns"%type)

    is

    select *

    from polrange

    where 1=1

      and "PolIns" = pPolIns;



    cursor curVisitFee (pPolIns polrange."PolIns"%type)

    is

    select *

    from visitfee

    where 1=1

      and "PolIns" = pPolIns;

      

    cursor curPolRider (pPolIns polrange."PolIns"%type)

    is

    select *

    from polrider

    where 1=1

      and "PolIns" = pPolIns;  



    -- P189-155143 added

    cursor curCvgProc (pPolIns cvgproc."PolIns"%type)

    is

    select *

    from cvgproc

    where 1=1

      and "PolIns" = pPolIns;  

  

    vSourcePolInsRow polins%rowtype;

    vExists number;

    exPlanExists exception;

    exInvalidCompany exception;

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    pvSuccess := false;

    

    select * into vSourcePolInsRow from polins where "PolIns" = pSourcePolIns;

  

    -- Setup

    if pvTargetPolInsRow."PolIns" is null then

      select polins_polins_seq.nextval into pvTargetPolInsRow."PolIns" from dual;

      pvTargetPolInsRow."OrigRecNo" := pvTargetPolInsRow."PolIns";  -- P189-146342

    end if;

    if pvTargetPolInsRow."SharedEntryId" is null then

      select policy_SharedEntryId_seq.nextval into pvTargetPolInsRow."SharedEntryId" from dual;

    end if;

    if pvTargetPolInsRow."User" is null then

      pvTargetPolInsRow."User" := nvl(vSourcePolInsRow."User",vParams."User");

    end if;

    if pvTargetPolInsRow."StationId" is null then

      pvTargetPolInsRow."StationId" := nvl(vSourcePolInsRow."StationId",vParams."StationId");

    end if;

  

    -- Set Null values in pvTargetPolInsRow to the values in pSourcePolInsRow

      -- This allows for an "override" on any involved fields before calling this procedure.

    pvTargetPolInsRow."Group" := nvl(pvTargetPolInsRow."Group",vSourcePolInsRow."Group");

    pvTargetPolInsRow."Division" := nvl(pvTargetPolInsRow."Division",vSourcePolInsRow."Division");

    pvTargetPolInsRow."FormsTo" := nvl(pvTargetPolInsRow."FormsTo",vSourcePolInsRow."FormsTo");

    pvTargetPolInsRow."Company" := nvl(pvTargetPolInsRow."Company",vSourcePolInsRow."Company");

    pvTargetPolInsRow."GovPolicy" := nvl(pvTargetPolInsRow."GovPolicy",vSourcePolInsRow."GovPolicy");

    pvTargetPolInsRow."Fee" := nvl(pvTargetPolInsRow."Fee",vSourcePolInsRow."Fee");

    pvTargetPolInsRow."Employer" := nvl(pvTargetPolInsRow."Employer",vSourcePolInsRow."Employer");

    pvTargetPolInsRow."HasFamilyLimit" := nvl(pvTargetPolInsRow."HasFamilyLimit",vSourcePolInsRow."HasFamilyLimit");

    pvTargetPolInsRow."FamilyDeduct" := nvl(pvTargetPolInsRow."FamilyDeduct",vSourcePolInsRow."FamilyDeduct");

    pvTargetPolInsRow."FamilyLimit" := nvl(pvTargetPolInsRow."FamilyLimit",vSourcePolInsRow."FamilyLimit");

    pvTargetPolInsRow."HasPatientLimit" := nvl(pvTargetPolInsRow."HasPatientLimit",vSourcePolInsRow."HasPatientLimit");

    pvTargetPolInsRow."PatientDeduct" := nvl(pvTargetPolInsRow."PatientDeduct",vSourcePolInsRow."PatientDeduct");

    pvTargetPolInsRow."PatientLimit" := nvl(pvTargetPolInsRow."PatientLimit",vSourcePolInsRow."PatientLimit");

    pvTargetPolInsRow."YearEnd" := nvl(pvTargetPolInsRow."YearEnd",vSourcePolInsRow."YearEnd");

    pvTargetPolInsRow."Assignment" := nvl(pvTargetPolInsRow."Assignment",vSourcePolInsRow."Assignment");

    pvTargetPolInsRow."Signature" := nvl(pvTargetPolInsRow."Signature",vSourcePolInsRow."Signature");

    pvTargetPolInsRow."ChangeDate" := nvl(pvTargetPolInsRow."ChangeDate",vSourcePolInsRow."ChangeDate");

    pvTargetPolInsRow."CvgPct" := nvl(pvTargetPolInsRow."CvgPct",vSourcePolInsRow."CvgPct");

    pvTargetPolInsRow."WriteOff" := nvl(pvTargetPolInsRow."WriteOff",vSourcePolInsRow."WriteOff");

    pvTargetPolInsRow."Deleted" := nvl(pvTargetPolInsRow."Deleted",vSourcePolInsRow."Deleted");

    pvTargetPolInsRow."PlanType" := nvl(pvTargetPolInsRow."PlanType",vSourcePolInsRow."PlanType");

    pvTargetPolInsRow."MonthlyDeduct" := nvl(pvTargetPolInsRow."MonthlyDeduct",vSourcePolInsRow."MonthlyDeduct");

    pvTargetPolInsRow."Date" := nvl(pvTargetPolInsRow."Date",trunc(sysdate));

    pvTargetPolInsRow."Time" :=  nvl(pvTargetPolInsRow."Time",(to_number(to_char(sysdate,'HH24')) * 60) + to_number(to_char(sysdate,'MI')));

    pvTargetPolInsRow."TrojanId" := nvl(pvTargetPolInsRow."TrojanId",vSourcePolInsRow."TrojanId");

    pvTargetPolInsRow."YearEndDay" := nvl(pvTargetPolInsRow."YearEndDay",vSourcePolInsRow."YearEndDay");

    pvTargetPolInsRow."ChildCoverage" := nvl(pvTargetPolInsRow."ChildCoverage",vSourcePolInsRow."ChildCoverage");

    pvTargetPolInsRow."AdultCoverage" := nvl(pvTargetPolInsRow."AdultCoverage",vSourcePolInsRow."AdultCoverage");

    pvTargetPolInsRow."Copay" := nvl(pvTargetPolInsRow."Copay",vSourcePolInsRow."Copay");

    pvTargetPolInsRow."Description" := nvl(pvTargetPolInsRow."Description",vSourcePolInsRow."Description");

    pvTargetPolInsRow."SharablePlan" := nvl(pvTargetPolInsRow."SharablePlan",vSourcePolInsRow."SharablePlan");

    pvTargetPolInsRow."StartDate" := nvl(pvTargetPolInsRow."StartDate",vSourcePolInsRow."StartDate");

    pvTargetPolInsRow."EndDate" := nvl(pvTargetPolInsRow."EndDate",vSourcePolInsRow."EndDate");

    pvTargetPolInsRow."VisitFee" := nvl(pvTargetPolInsRow."VisitFee",vSourcePolInsRow."VisitFee");

    pvTargetPolInsRow."CoverageAge" := nvl(pvTargetPolInsRow."CoverageAge",vSourcePolInsRow."CoverageAge");

    pvTargetPolInsRow."CoverageAgeStud" := nvl(pvTargetPolInsRow."CoverageAgeStud",vSourcePolInsRow."CoverageAgeStud");

    pvTargetPolInsRow."OrigRecNo" := nvl(pvTargetPolInsRow."OrigRecNo",vSourcePolInsRow."OrigRecNo");

    pvTargetPolInsRow."EDIFlag" := nvl(pvTargetPolInsRow."EDIFlag",vSourcePolInsRow."EDIFlag");    

    -- P189-155143 added following

    pvTargetPolInsRow."CoverageAgeYoungAdult" := nvl(pvTargetPolInsRow."CoverageAgeYoungAdult",vSourcePolInsRow."CoverageAgeYoungAdult");    

    pvTargetPolInsRow."YoungAdultCoverage" := nvl(pvTargetPolInsRow."YoungAdultCoverage",vSourcePolInsRow."YoungAdultCoverage");    

    pvTargetPolInsRow."CvgOnBirthChild" := nvl(pvTargetPolInsRow."CvgOnBirthChild",vSourcePolInsRow."CvgOnBirthChild");    

    pvTargetPolInsRow."CvgOnBirthStudent" := nvl(pvTargetPolInsRow."CvgOnBirthStudent",vSourcePolInsRow."CvgOnBirthStudent");    

    pvTargetPolInsRow."CvgOnBirthYoungAdult" := nvl(pvTargetPolInsRow."CvgOnBirthYoungAdult",vSourcePolInsRow."CvgOnBirthYoungAdult");    

    pvTargetPolInsRow."ChargeDedAndPtChg" := nvl(pvTargetPolInsRow."ChargeDedAndPtChg",vSourcePolInsRow."ChargeDedAndPtChg");    

    

    -- Validation    

    if vParams."VerifyLevel" >= ax_pkg.VERIFY_ERRORS then    

      -- Does the company exist?

      begin 

        select 1 into vExists

        from insuranc

        where

          "Company" = pvTargetPolInsRow."Company" and

          "Inactive" = 0

        ;

      exception

        when no_data_found then

          raise exInvalidCompany;

      end;

      -- Duplicate Check

      begin

        select 1 into vExists 

        from polins

        where

          ("Company" = pvTargetPolInsRow."Company" or ("Company" is null and pvTargetPolInsRow."Company" is null)) and

          ("Group" = pvTargetPolInsRow."Group" or ("Group" is null and pvTargetPolInsRow."Group" is null) )and

          ("Division" = pvTargetPolInsRow."Division" or ("Division" is null and pvTargetPolInsRow."Division" is null) )and

          ("EndDate" is null or "EndDate" >= pvTargetPolInsRow."EndDate") and

          ("StartDate" is null or "StartDate" <= pvTargetPolInsRow."StartDate") and

          "Deleted" = 0 and

          "SharablePlan" =  pvTargetPolInsRow."SharablePlan";

        raise exPlanExists;

      exception

        when no_data_found then

          null; -- This means that no benefit plan was found with the same company, group, division

        when others then

          raise exPlanExists;

      end;

    end if;

    

    -- Insert the new Records    

    insert into polins values pvTargetPolInsRow;

    ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' polins rows inserted.',vParams);

    

    -- P189-146342 added copying of polrange, visitfee, and polrider records

    -- insert the polrange records

    for cPolRange in curPolRange (pSourcePolIns) loop

      cPolRange."PolIns" := pvTargetPolInsRow."PolIns";

      insert into polrange values cPolRange;

    end loop;

    

    -- insert the visitfee recrods

    for cVisitFee in curVisitFee (pSourcePolIns) loop

      cVisitFee."PolIns" := pvTargetPolInsRow."PolIns";

      insert into visitfee values cVisitFee;

    end loop;

    

    -- insert the polrider records

    for cPolRider in curPolrider (pSourcePolIns) loop

      select polrider_polrider_seq.nextval into cPolRider."PolRider" from dual;

      cPolRider."PolIns" := pvTargetPolInsRow."PolIns";

      insert into polrider values cPolRider;

    end loop;



    -- P189-155143 added

    -- insert the cvgproc records

    for cCvgProc in curCvgProc (pSourcePolIns) loop

      cCvgProc."PolIns" := pvTargetPolInsRow."PolIns";

      insert into cvgproc values cCvgProc;

    end loop;

    

    -- All done!

    pvSuccess := true;

    

    exception 

      when dup_val_on_index then

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_ERROR,

          'Benefit Plan Already Exists.',

          vParams);

      when exPlanExists then

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_ERROR,

          'A Benefit Plan already exists with the same Insurance Company, Group and Division.',

          vParams);

      when exInvalidCompany then

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_ERROR,

          'Invalid Company.',

          vParams);

      when others then        

        raise;

  end CopyBenefitPlan_P;

  



  PROCEDURE movepolbillorder_p(IN pinsurance character, IN pdebug boolean DEFAULT false, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

--

--This procedure re-orders the billing policy that shows on the Patient Info Window -> Insurance Tab at the bottom, 

--   so that the provided Insurance company's policies show last in the list.

--   

--It will look at every patient who has a policy through the provided Insurance Company, and if they have not already been manually ordered it will

--    automatically order them based on the order that axiUm displays them in normally.

--   

--If pDebug is true, then it will rollback any changes it would have made (set pParams."VerboseType" to SHOW_CODE_GEN or SHOW_ALL)

--



    vNewBillOrder number;

    vOldBillOrder number;

    vFoundRecords number;

    vReorderCount number;

    

    -- select all ptdepend records where the provided insurance code appears, and there is more than one entry for that patient

    cursor curPtDependAll is select D."PolicyId",D."Patient",D."BillOrder",O."Company",MaxPTD."MaxBillOrder",MaxPTD."MinBillOrder"

                         from PATIENT P, PTDEPEND D, POLICY O,

                         (select D."Patient",count(*) as "MaxBillOrder",min("BillOrder") as "MinBillOrder" from PATIENT P, PTDEPEND D, POLICY O

                              where D."Patient" = P."Patient" and D."Deleted" = 0 and O."PolicyId" = D."PolicyId" and D."IsCovered" = 1 and

                              O."StartDate" <= sysdate and (O."Deleted" = 0 or O."Date" is null or O."Date" > sysdate)

                              group by D."Patient") MaxPTD

                          where D."Patient" = P."Patient" and D."Deleted" = 0 and MaxPTD."Patient" = D."Patient" and O."PolicyId" = D."PolicyId" and D."IsCovered" = 1 and

                          O."StartDate" <= sysdate and (O."Deleted" = 0 or O."Date" is null or O."Date" > sysdate) and O."Company" = pInsurance

                          order by D."Patient", D."BillOrder";

      -- This is based the query that axiUm uses to determine billing order

    cursor curBirthdayRule (vPatient patient."Patient"%type) is SELECT D."PolicyId", D."BillOrder", TO_CHAR (H."Birth", 'MM') "HolderMonth",TO_CHAR (H."Birth", 'DD') "HolderDay"

                         from  PATIENT P, PTDEPEND D, POLICY O, PATIENT H, INSURANC I, BILLING B, EMPLOYER E

                         where P."Patient" = vPatient and D."Patient" = P."Patient" and D."Deleted" = 0 and  O."PolicyId" = D."PolicyId" and D."IsCovered" = 1 and

                         O."StartDate" <= sysdate and (O."Deleted" = 0 OR O."Date" IS NULL OR O."Date" > sysdate)  and H."Patient" = O."Patient" and

                         I."Company" (+)= O."Company" and  E."Employer" (+)= O."Employer" and E."Deleted" (+) = 0 and B."Company" (+)= O."Company" and

                         B."Producer" (+)= ' '

                         order by LEAST(D."BillOrder", 1) DESC, D."BillOrder", D."Relation",  "HolderMonth", "HolderDay", (select t."Primary" from ptemploy t

                         where t."Patient" = O."Patient" and t."Employer" = O."Employer") DESC,

                         O."Company", O."Group", O."Division", O."Policy", O."PolicyId";

    vParams ax_pkg.tParams := pParams;

  begin

    ax_pkg.InitializeParams_P(vParams);

    vFoundRecords := 0;

    vReorderCount := 0;

    

    BEGIN

      -- Debug mode will automatically rollback all changes

      -- Handle transaction at procedure level

      

      ----------------------------------------------------------------------------

      -- Reorder ALL records, if they have been manually ordered or not.

      --   - this section tries to duplicate the Birthday Rule that axiUm uses

      ----------------------------------------------------------------------------

      for recPtDepend in curPtDependAll Loop

        -- Only continue if there is more than one policy for this patient, and the policy in question is not already last

        if (recPtDepend."MaxBillOrder" > 1 and recPtDepend."BillOrder" <> recPtDepend."MaxBillOrder") or (recPtDepend."MinBillOrder" = 0) then

          -- if records are not ordered already, order them before the next step

          if recPtDepend."MinBillOrder" = 0 then

            vNewBillOrder := 1;

            for recPtDepend2 in curBirthdayRule(recPtDepend."Patient") Loop

              update PTDEPEND set "BillOrder" = vNewBillOrder  where "Patient" = recPtDepend."Patient" and "PolicyId"=  recPtDepend2."PolicyId";

              ax_pkg.dbmsoutput_P(

                ax_pkg.MSG_CODE,

                'UPDATE PTDEPEND SET "BillOrder" = ' || vNewBillOrder  || ' WHERE "Patient" = ' || recPtDepend."Patient" || ' AND "PolicyId" = ' || recPtDepend2."PolicyId" || ';',

                vParams

              );

              vFoundRecords := 1;

              vNewBillOrder := vNewBillOrder + 1;

            end loop;

          end if;

    

          -- at this point all records should have an order, and we need to move the specified records to last in the billing order

          select "BillOrder" into vNewBillOrder from ptdepend where "Patient" = recPtDepend."Patient" and "PolicyId" = recPtDepend."PolicyId";

          while vNewBillOrder < recPtDepend."MaxBillOrder" Loop

            vOldBillOrder := vNewBillOrder + 1;

            ax_pkg.dbmsoutput_P(

              ax_pkg.MSG_CODE,

              'UPDATE PTDEPEND SET "BillOrder" = ' || vNewBillOrder || ' WHERE "Patient" = ' || recPtDepend."Patient" || ' AND "BillOrder" = ' || vOldBillOrder || ' AND "PolicyId" <> ' || recPtDepend."PolicyId" || ' ;',

              vParams

            );

            UPDATE PTDEPEND SET "BillOrder" = vNewBillOrder  WHERE "Patient" = recPtDepend."Patient"  AND "BillOrder" =  vOldBillOrder AND "PolicyId" <>  recPtDepend."PolicyId";

            vNewBillOrder := vNewBillOrder + 1;

          end loop;

    

          ax_pkg.dbmsoutput_P(

            ax_pkg.MSG_CODE,

            'UPDATE PTDEPEND SET "BillOrder" = ' || recPtDepend."MaxBillOrder"  || ' WHERE "Patient" = ' || recPtDepend."Patient" || ' AND "PolicyId" = ' || recPtDepend."PolicyId" || ';',

            vParams

          );

          vFoundRecords := 1; 

          vReorderCount := vReorderCount + 1;

          UPDATE PTDEPEND SET "BillOrder" = recPtDepend."MaxBillOrder"  WHERE "PolicyId" =recPtDepend."PolicyId"  AND "Patient" =  recPtDepend."Patient";

        end if;

      end loop;

    

      if (vFoundRecords = 0) then

        ax_pkg.dbmsoutput_P(

         ax_pkg.MSG_CODE,

         '-- move_pol_bill_order:No Records Found to Update!',

         vParams

        );

      else

        ax_pkg.dbmsoutput_P(

          ax_pkg.MSG_CODE,

          '-- move_pol_bill_order: Changed Billing Order for ' || vReorderCount || ' policies.',

          vParams

        );

      end if;

      

      -- In debug mode, rollback all changes

      if (pDebug) then

        rollback;

      else

        commit;

      end if;



    EXCEPTION

      WHEN no_data_found THEN

        rollback;

        ax_pkg.dbmsoutput_P(ax_pkg.MSG_CODE,'-- move_pol_bill_order:no_data_found for ' || pInsurance,vParams);

      WHEN OTHERS THEN

        rollback;

        RAISE;

    END;

  end MovePolBillOrder_P;



  

  -- Set trx row defaults

  PROCEDURE initializetrx_p(INOUT pvtrxrow trx, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vParams ax_pkg.tParams := pParams;

  begin

    -- Get proper User/StationId

    ax_pkg.InitializeParams_P(vParams);

    -- Set TRX Defaults

    trx_pkg.InitializeTrx(pvTrxRow);

    -- Correct User/StationId

    pvTrxRow."User" := vParams."User";

    pvTrxRow."StationId" := vParams."StationId";

  end InitializeTrx_P;

  

  

  -- Insert TRX record, and matching History record

  PROCEDURE inserttrx_p(INOUT pvtrxrow trx, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vParams ax_pkg.tParams := pParams;

  begin

    -- Set User/Station correctly, if not already set

    ax_pkg.InitializeParams_P(vParams);    

    pvTrxRow."User" := nvl(pvTrxRow."User",vParams."User");

    pvTrxRow."StationId" := nvl(pvTrxRow."StationId",vParams."StationId");

    -- Create TRX Record

    trx_pkg.InsertTrx(pvTrxRow);

    -- Create History Record

    InsertHistory_P(

      pvTrxRow,    

      ax_pkg.HISTORY_ADD,

      pParams

    );

  end InsertTrx_P;

  

  

  -- Insert History record, based on existing TRX record

  PROCEDURE inserthistory_p(INOUT pvtrxrow trx, IN phistorytype numeric DEFAULT ax_pkg.history_add, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

  begin

    insert into history(

      select 

        history_history_seq.nextval,

        pHistoryType,

        trx.* 

      from trx

      where

        "Id" = pvTrxRow."Id" and

			  "Type" = pvTrxRow."Type" and

			  "Treatment" = pvTrxRow."Treatment"

	  );

  end InsertHistory_P;



  PROCEDURE addunapprovedtrx_p(OUT psuccess numeric, IN ppatient numeric, IN pprocedure character, IN pstatus character, IN ptxdate timestamp without time zone DEFAULT trunc(sysdate), IN pproducer character DEFAULT ' '::bpchar, IN pdiscipline character DEFAULT ' '::bpchar, IN pcustom1 character DEFAULT ' '::bpchar, IN pcustom2 character DEFAULT ' '::bpchar, IN pcustom3 character DEFAULT ' '::bpchar, IN pcustom4 character DEFAULT ' '::bpchar, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

  

    vTreatme2Auto treatme2."Auto"%type := 0;

    vChartlnkId chartlnk."Id"%type := 0;

    vPatient2Auto patient2."Auto"%type := 0;

    vProcedurId procedur."Id"%type := 0;

    vStatus treatme2."Status"%type;

    vProducer producer."Producer"%type := pProducer;

    vTxDate chartlnk."TxDate"%type := pTxDate;

    vDiscipline treatme2."Discipline"%type := pDiscipline;

    vToday date := trunc(sysdate);

    vSuccess integer:= 0;

    vParams ax_pkg.tParams := pParams;

  

    vStep integer:= 0;

  

  begin



    vStep := 10;



    ax_pkg.InitializeParams_P(vParams);

  

    --

    -- make sure status is valid (P, I or C are the only ones valid)

    --

    vStep := 20;

  

    select decode(trim(pStatus), 'P', 2,

                                 'I', 1,

                                 'C', 0,

                                 -1)

    into vStatus

    from dual

    where 1=1

    and pStatus in ('P', 'I', 'C');

  

    --

    -- make sure treatment date is not null

    --

    vStep := 30;

  

    if (pTxDate is null) then

      vTxDate := vToday;

    end if;

  

    --

    -- make sure patient is valid (actual patient, active)

    --

    vStep := 40;

  

    select p2."Auto"

    into vPatient2Auto

    from

      patient p,

      patient2 p2

    where 1=1

    and p2."PtxPId" = p."Patient"

    and p."Patient" = p."Family"      -- actual patient

    and p."IsPatient" = 1

    and p."Deleted" = 0

    and (p."Close" is null

         or p."Close" >= vTxDate)

    and not exists (select 1

                    from status s

                    where 1=1

                    and s."Type" = 2    -- patient

                    and s."MakeInactive" = 1

                    and s."Status" = p."Status")

    and p2."PtxPId" = pPatient;

  

    --

    -- make sure procedure is valid

    --

    vStep := 50;

  

    select

      "Id",

      "Discipline"

    into

      vProcedurId,

      vDiscipline

    from procedur

    where 1=1

    and "IsProcedure" = 1

    and "Deleted" = 0

    and "Global" = 0          -- N/A (no location/site)

    and "Local" = 0           -- N/A (no location/site)

    and "Type" = 0            -- Text

    and "Zone" = 0            -- N/A

    and "Procedure" = pProcedure;

  

    --

    -- make sure producer is valid

    --

    if (trim(pProducer) is not null) then

      --

      -- make sure producer is active

      --

      vStep := 60;

  

      select prod."Producer"

      into vProducer

      from

        producer prod,

        users u

      where 1=1

      and (prod."EndDate" is null

           or prod."EndDate" >= vTxDate)

      and prod."Producer" = u."Producer"

      and u."Deleted" = 0

      and (u."EffDate" is null

           or u."EffDate" <= vTxDate)

      and (u."ExpDate" is null

           or u."ExpDate" >= vTxDate)

      and prod."Producer" = pProducer;

  

    else

      --

      -- make sure producer is not null

      --

      vStep := 70;

  

      vProducer := nvl(pProducer, ' ');

  

    end if;

  

    --

    -- make sure discipline is valid

    --

    if (trim(pDiscipline) is not null) then

      --

      -- make sure Discipline is valid

      --

      vStep := 80;

  

      select "Class"

      into vDiscipline

      from class

      where 1=1

      and "Class" = pDiscipline;

  

    else

      --

      -- make sure discipline is not null

      --

      vStep := 90;

  

      vDiscipline := nvl(vDiscipline, ' ');

  

    end if;

  

    --

    -- get TREATME2."Auto"

    --

    vStep := 120;

  

    select treatme2_auto_seq.nextval

    into vTreatme2Auto

    from dual;

  

    --

    -- create the TREATME2 record

    --

    vStep := 130;

  

    insert into treatme2 values

    (

     vTreatme2Auto,              --"Auto",

     vPatient2Auto,              --"PId",

     vProcedurId,                --"CodeId",

     (trunc(vTxDate) - TO_DATE('01-JAN-1901', 'DD-MON-RRRR')),          --"Days",

     sysdate,                    --"ModifiedDateTime",

     0,                          --"PreId",

     vParams."User",             --"User",

     0,                          --"Site",

     vStatus,                    --"Status",

     0,                          --"Surface",

     0,                          --"Deleted",

     0,                          --"Site2",

     ' ',                        --"Number",

     ' ',                        --"Phase",

     0,                          --"Seq",

     vProducer,                  --"Provider",

     pCustom1,

     pCustom2,

     (vTreatme2Auto * -1),       --"ParentId",

     vDiscipline,                --"Discipline",

     0,                          --"TxPTx",

     vParams."StationId",        --"StationId",

     pCustom3,

     pCustom4,

     null,                       --"DeletionDate",

     sysdate,                    --"AddDateTime",

     0,                          --"AppUser",

     null,                       --"AppDate",

     0,                          --"DelAppUser",

     null,                       --"DelAppDate",

     0                           --"Unit"

    );

  

    --

    -- get CHARTLNK."Id"

    --

    vStep := 140;

  

    select chartlnk_id_seq.nextval

    into vChartlnkId

    from dual;

  

    --

    -- create the CHARTLNK record

    --

    vStep := 150;

  

    insert into chartlnk values

    (

     vChartlnkId,               --"Id",

     vTreatme2Auto,             --"Auto",

     vParams."User",            --"User",

     vTxDate,                   --"TxDate",

     ' ',                       --"ChartId",

     vProducer,

     pProcedure,                --"Procedure",

     ' ',                       --"Site",

     ' ',                       --"Surface",

     pStatus,                   --"Status",

     0,                         --"Previous",

     0,                         --"Action",

     ' ',                       --"PlanPhase",

     0,                         --"PlanSeq",

     ' ',                       --"Site2",

     pCustom1,                  --"Custom1",

     pCustom2,                  --"Custom2",

     0,                         --"Total",

     0,                         --"InsTotal",

     vDiscipline,               --"Discipline",

     ' ',                       --"Additional",

     vParams."StationId",       --"StationId",

     pPatient,                  --"Patient",

     pCustom3,                  --"Custom3",

     pCustom4,                  --"Custom4",

     0,                         --"BillTotal",

     0,                         --"XCount",

     0                          --"Unit"

    );

  

    --

    -- save changes and return success

    --

    vStep := 170;

  

  --  commit;

  

    pSuccess := 1;

  

  exception

    when no_data_found then

      --

      -- either status is not valid or patient is not valid or procedure is not valid or producer is not valid or discipline is not valid

      --

      vStep := 190;

  

      pSuccess := 0;

  

    when others then

      --

      -- log error to AX_LOG table and return fail

      --

  --    vStep := 200;

	  -- AX-39259

      ax_pkg.LogEvent_P(trim('AX_TRX_PKG')||'.AddUnApprovedTrx_P', trim(sqlerrm)||' (Error at step '||vStep||')');

  

      pSuccess := 0;

  

  end AddUnApprovedTrx_P;



  PROCEDURE initializetrxmed_p(INOUT pvtrxmedrow trxmed) IS

  

  begin



    pvTrxMedRow."Patient" := 0;

    pvTrxMedRow."Type" := 0;

    pvTrxMedRow."Id" := 0;

    pvTrxMedRow."Treatment" := 0;

    pvTrxMedRow."ICDCode1" := ' ';

    pvTrxMedRow."ICDCode2" := ' ';

    pvTrxMedRow."ICDCode3" := ' ';

    pvTrxMedRow."ICDCode4" := ' ';

    pvTrxMedRow."ICDIsTx1" := 0;

    pvTrxMedRow."ICDIsTx2" := 0;

    pvTrxMedRow."ICDIsTx3" := 0;

    pvTrxMedRow."ICDIsTx4" := 0;

    pvTrxMedRow."PlaceCode" := ' ';

    pvTrxMedRow."Modifier" := ' ';

    pvTrxMedRow."DateTo" := TRUNC(SYSDATE);

    pvTrxMedRow."Modifier2" := ' ';

    pvTrxMedRow."AnesMin" := 0;

    pvTrxMedRow."Referral" := 0;

    pvTrxMedRow."ChartLnk" := 0;

    pvTrxMedRow."ICDType" := 1;  -- ICD 10

    pvTrxMedRow."IsAccident" := 0;

    pvTrxMedRow."ICDCode5" := ' ';

    pvTrxMedRow."ICDCode6" := ' ';

    pvTrxMedRow."ICDCode7" := ' ';

    pvTrxMedRow."ICDCode8" := ' ';

    pvTrxMedRow."ICDCode9" := ' ';

    pvTrxMedRow."ICDCode10" := ' ';

    pvTrxMedRow."ICDCode11" := ' ';

    pvTrxMedRow."ICDCode12" := ' ';

    pvTrxMedRow."ICDIsTx5" := 0;

    pvTrxMedRow."ICDIsTx6" := 0;

    pvTrxMedRow."ICDIsTx7" := 0;

    pvTrxMedRow."ICDIsTx8" := 0;

    pvTrxMedRow."ICDIsTx9" := 0;

    pvTrxMedRow."ICDIsTx10" := 0;

    pvTrxMedRow."ICDIsTx11" := 0;

    pvTrxMedRow."ICDIsTx12" := 0;

    pvTrxMedRow."Modifier3" := ' ';

    pvTrxMedRow."Modifier4" := ' ';

  

  end InitializeTrxMed_P;



  PROCEDURE inserthistory(IN row_trx trx, OUT historyid numeric) IS

  BEGIN

   select HISTORY_HISTORY_SEQ.nextval into historyId from dual;

   INSERT INTO history

      (

        SELECT historyId,

        1                              ,

        trx.* FROM trx

          WHERE "Id"		 = row_Trx."Id"

			  AND "Type"      = row_Trx."Type"

			  AND "Treatment" = row_Trx."Treatment"

	   );

  END InsertHistory;



END;
CREATE OR REPLACE PACKAGE BODY ax_users_pkg IS



  -- returns information about this package, or its procedures

  PROCEDURE help(IN pobjectname character varying DEFAULT NULL::character varying) IS

    vReturn CLOB;

  begin

    -- Writes the help to the DBMS_OUTPUT

	-- AX-39259

    vReturn := ax_pkg.Help_F('AX_USERS_PKG',pObjectName);

  end Help;



  -- Returns a 1 or 0, based on if the user has access to log into axiUm 

  -- on the specified day and hour

  FUNCTION checkaccesshour_f(puser numeric, pday numeric, ptime numeric) RETURN numeric IS

    vHours  VARCHAR2(24);

    vHour number;

  begin

    if pDay = 1 then

      select "Sunday" into vHours from uaccess where "User" = pUser;

    elsif pDay = 2 then 

      select "Monday" into vHours from uaccess where "User" = pUser;

    elsif pDay = 3 then 

      select "Tuesday" into vHours from uaccess where "User" = pUser;

    elsif pDay = 4 then 

      select "Wednesday" into vHours from uaccess where "User" = pUser;

    elsif pDay = 5 then 

      select "Thursday" into vHours from uaccess where "User" = pUser;

    elsif pDay = 6 then 

      select "Friday" into vHours from uaccess where "User" = pUser;

    elsif pDay = 7 then 

      select "Saturday" into vHours from uaccess where "User" = pUser;

    end if;

    

    vHour := trunc(pTime/60);

    

    return to_number(substr(vHours,vHour,1));

    

  end CheckAccessHour_F;

  

 -- Overload

 -- Returns a 1 or 0, based on if the user has access to log into axiUm 

  -- on the specified date value 

  FUNCTION checkaccesshour_f(puser numeric, pdatetime timestamp without time zone) RETURN numeric IS

    vDay number;  

    vHours  VARCHAR2(24);

    vHour number;

  begin

    vDay := to_number(to_char(pDateTime,'D'));

    if vDay = 1 then

      select "Sunday" into vHours from uaccess where "User" = pUser;

    elsif vDay = 2 then 

      select "Monday" into vHours from uaccess where "User" = pUser;

    elsif vDay = 3 then 

      select "Tuesday" into vHours from uaccess where "User" = pUser;

    elsif vDay = 4 then 

      select "Wednesday" into vHours from uaccess where "User" = pUser;

    elsif vDay = 5 then 

      select "Thursday" into vHours from uaccess where "User" = pUser;

    elsif vDay = 6 then 

      select "Friday" into vHours from uaccess where "User" = pUser;

    elsif vDay = 7 then 

      select "Saturday" into vHours from uaccess where "User" = pUser;

    end if;

    

    vHour := to_number(to_char(pDateTime,'HH24')) + 1;

    

    return to_number(substr(vHours,vHour,1));

    

  end CheckAccessHour_F;

  

  

  -- Returns a True or False, on if a user should be locked

  -- Based on the number of failed attempts, which is set in the ax_setting table

  FUNCTION lockoutcheck_f(plogon character varying, plogonhistory numeric, pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) RETURN boolean IS

    vNumFailedForLockout number;  -- set by client requirements; the number of failed login attempts that triggers a lockout.

    vFailCount           number := 0;  -- used to count the number of sequential logon failures for this attempt

    vAuditHisRow audithis%rowtype;     -- Audit History Record

    vParams ax_pkg.tParams := pParams; -- Common Parameters

    vSettingRow ax_setting%rowtype;    -- Setting Record

    exVersionMismatch exception;       -- Exception

  begin

    -- Set Defaults

    ax_pkg.InitializeParams_P(vParams);

    

    -- Get Settings

    vSettingRow."Key" := 'Lockout.MaxAttempts';

    vSettingRow."Value" := '5';

    vSettingRow."Description" := 'The number of failed login attempts that triggers a lockout.';

    vNumFailedForLockout := to_number(ax_pkg.GetSetting_F(vSettingRow));



  

    -- find out if the user should be locked out

    begin    

      select count(1) into vFailCount

      from 

        log l

      where 

        l."Logon" = pLogon and

        l."LoginHistory" < pLogonHistory and

        l."Action" = 0 and

        CheckAccessHour_F(l."User",to_char(l."Date",'D'),l."Time") = 1 and

        l."Time" >= round(to_char(sysdate,'SSSSS') / 60) - 120 and

        not exists (

          select 1 from log l2

            where

              l2."LoginHistory" > l."LoginHistory" and

              l."Logon"         = l2."Logon" and

              l2."Action"       = 1

        )

      ;

    exception

      when no_data_found then

        vFailCount := 0;

    end;

    

    -- lock the account, if needed

    if (vFailCount + 1) >= vNumFailedForLockout then

      return true;

    else

      return false;

    end if;



    

  exception 

    when exVersionMismatch then

      ax_pkg.LogEvent_P('ax_users_pkg.LockoutCheck_F','AX_USERS_PKG version mismatch',vParams);

  end LockoutCheck_F;

  

  

  -- Locks a User account by setting the Expire Date to yesterday

  PROCEDURE lockoutlock_p(IN plogon character varying, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vNumMinutesToLockout number; -- set by client requirements; the number of minutes before the account is unlocked.

    vNumFailedForLockout number;  -- set by client requirements; the number of failed login attempts that triggers a lockout.

    vJobNo               number;       -- holds job number to be used for reset (ignored)

    vJobString            VARCHAR2(400);-- holds the job procedure call

    vDoLock              number := 0;  -- used to check if we actually locked or not

    vAuditHisRow audithis%rowtype;     -- Audit History Record

    vParams ax_pkg.tParams := pParams; -- Common Parameters

    vSettingRow ax_setting%rowtype;    -- Setting Record

    vLogRow ax_log%rowtype;            -- Log Record

    exVersionMismatch exception;       -- Exception

    vUser               users."User"%type; -- User Id used in storing the current ExpDate

    vExpDate            users."ExpDate"%type; -- User Expiry Date

  begin

    -- Error checking

    if vParams."VerifyLevel" >= ax_pkg.VERIFY_ERRORS then

      if not ax_pkg.VersionMatch_F(AXIUM_VERSION) then

        raise exVersionMismatch;

      end if;  

    end if;

  

    -- Set Defaults

    ax_pkg.InitializeParams_P(vParams);

  

    -- Get Settings

    vSettingRow."Key" := 'Lockout.LockedOutTime';

    vSettingRow."Value" := '15';

    vSettingRow."Description" := 'The number of minutes before the account is unlocked.';

    vNumMinutesToLockout := to_number(ax_pkg.GetSetting_F(vSettingRow));

    

    vSettingRow."Key" := 'Lockout.MaxAttempts';

    vSettingRow."Value" := '5';

    vSettingRow."Description" := 'The number of failed login attempts that triggers a lockout.';

    vNumFailedForLockout := to_number(ax_pkg.GetSetting_F(vSettingRow));



    -- check if we need to actually lock the person out

    begin

      select 1 into vDoLock

      from users

      where 

        trim("Logon") = trim(pLogon) and

        "Deleted" = 0 and

        (

          "ExpDate" >= trunc(sysdate) or

          "ExpDate" is null

        )

      ;

    exception

      when no_data_found then

        vDoLock := 0; -- happens when user does not exist

    end;

  

    -- need this check because we only want to unlock people that we actually locked

    if vDoLock = 1 then

      -- record the current ExpDate for later reference

      select "User", "ExpDate" into vUser, vExpDate from users where "Logon" = pLogon;   

      delete ax_log where "Source" = 'ExpDate' and "User" = vUser;    

      if vExpDate is not null then 

        vLogRow."Request" := '148509';

        vLogRow."Source" := 'ExpDate';

        vLogRow."Log" := to_char(vExpDate,'mm/dd/yyyy');

        vLogRow."User" := vUser;

        ax_pkg.log_p(vLogRow,ax_pkg.MSG_NONE,vParams); -- log the message

      end if;

    

      -- create an audithis

      vAuditHisRow."TableName" := 'USERS';

      vAuditHisRow."HistoryType" := ax_pkg.AUDIT_EDIT;

      ax_pkg.CreateAuditHis_P(vAuditHisRow,vParams);

      

      -- expire the user account if it is not already deleted or expired

      update users  set 

        "ExpDate" = trunc(sysdate)-1,

        "Audit" = vAuditHisRow."Audit"

      where

        trim("Logon") = trim(pLogon) and

        "Deleted" = 0 and

        (

          "ExpDate" >= trunc(sysdate) or

          "ExpDate" is null

        )

      ;

      -- create a one-time job that will unlock the account after the wait

      vJobString := 'ax_users_pkg.LockoutUnlock_P(''' || trim(pLogon) || ''');';

      dbms_job.submit(vJobNo, vJobString, (sysdate + (vNumMinutesToLockout/1440)) );

      

      -- Log that the user has been locked out because of this script

      vLogRow := null;

      vLogRow."Request" := '148509';

      vLogRow."Source" := 'ax_users_pkg.LockoutLock_P';

      vLogRow."Log" := 'User: ' || trim(pLogon) || ' has been locked out for ' || to_char(vNumMinutesToLockout) || ' minutes because of more than ' || to_char(vNumFailedForLockout) || ' incorrect logon attempts';

      ax_pkg.log_p(vLogRow,ax_pkg.MSG_INFO,vParams); -- log the message

    end if; -- if vDoLock = 1

    

  exception 

    when exVersionMismatch then

      ax_pkg.LogEvent_P('ax_users_pkg.Lockout_Lock_P','AX_USERS_PKG version mismatch',vParams);

  end LockoutLock_P;

  

  

  -- Unlocks a User account by clearing the Expire Date

  PROCEDURE lockoutunlock_p(IN plogon character, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

    vAuditHisRow audithis%rowtype;

    vLogRow ax_log%rowtype;            -- Log Record

    vParams ax_pkg.tParams := pParams;

    vUser users."User"%type; -- User ID

    vExpDate ax_log."Log"%type; -- Expiry Date, must be converted to date type    

  begin

    -- Set Defaults

    ax_pkg.InitializeParams_P(vParams);

  

    -- create an audithis

    vAuditHisRow."TableName" := 'USERS';

    vAuditHisRow."HistoryType" := ax_pkg.AUDIT_EDIT;   

    ax_pkg.CreateAuditHis_P(vAuditHisRow,vParams);

    

    -- gather the previous expire date

    select "User" into vUser from users where "Logon" = pLogon;    

    begin

      select "Log" into vExpDate from ax_log where "User" = vUser and "Source" = 'ExpDate';

      -- un-expire the user by setting ExpDate to what it was before

      update users set

          "ExpDate" = to_date(vExpDate,'mm/dd/yyyy'), 

          "Audit" = vAuditHisRow."Audit"

        where

          trim("Logon") = trim(pLogon)

          and "Deleted" = 0

          and "ExpDate" is not null;    

    exception

      when no_data_found then

        -- un-expire the user by clearing the expiry date

        update users set

          "ExpDate" = '', 

          "Audit" = vAuditHisRow."Audit"

        where

          trim("Logon") = trim(pLogon)

          and "Deleted" = 0

          and "ExpDate" is not null;        

    end;

      

    -- Log that the user has been Unlocked

    vLogRow."Request" := '148509';

    vLogRow."Source" := 'ax_users_pkg.LockoutUnlock_P';

    vLogRow."Log" := 'Logon Lock has been removed for User: ' || trim(pLogon);

    ax_pkg.log_p(vLogRow,ax_pkg.MSG_INFO,vParams); -- log the message



  exception

   when others then

     ax_pkg.LogEvent_P('ax_users_pkg.Lockout_Unlock_P',sqlerrm,vParams);

  end LockoutUnlock_P;





  PROCEDURE inactivateprovidergroup_p(IN ppgroup character, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params) IS

  begin

    ax_pkg.LogEvent_P('ax_users_pkg.InactivateProviderGroup_P','Procedure not yet implemented',pParams);

  end InactivateProviderGroup_P;





  PROCEDURE changeprovider_p(INOUT pvsuccess boolean, INOUT pvmessage character varying, IN poldprovider character, IN pnewprovider character, IN pparams ax_pkg.tparams DEFAULT ax_pkg.ax_params, IN pasofdate timestamp without time zone DEFAULT NULL::timestamp without time zone, IN pchangehistory boolean DEFAULT false, IN pskiptables character varying DEFAULT NULL::character varying) IS

  

    cursor curPtProd is 

     select * from ptprod where "Producer" = pOldProvider and (pAsOfDate is null or "StartDate" >= pAsOfDate) and "Deleted" = 0;  

    vTable  VARCHAR2(30);

    vSkipTable pls_integer;

    vSkipBilling boolean := false;

    vNewProviderExists boolean := false;

    vAuditHisRow audithis%rowtype;

    vPtProdRow ptprod%rowtype;

    vProducerRow producer%rowtype;

    vMapAudit audithis."Audit"%type;    

    vParams ax_pkg.tParams := pParams;

    

    vAsOfDate boolean := false;

    vCopyProfile boolean := false;

    vFullUpdate boolean := false;

    

    exOldProviderDoesNotExist exception;

    exNewProviderExists exception;

  begin

    -- pvMessage := 'Procedure not yet implemented';

    --ax_pkg.LogEvent_P('ax_users_pkg.ChangeProvider_P',pvMessage,vParams);

    --return;

  

  

  -- Review Change History Logic

  --  some places would only update current values, not historical

  

  -- Ensure that script still works when copying - if the record already exists

  

    -- Handle pParams

    ax_pkg.InitializeParams_P(vParams,pParams);

    -- If pParams was not initialized, then default the VerboseType to show the messages from this procedure

    if not pParams."IsInit" then

      vParams."VerboseType" := ax_pkg.SHOW_INFO;

    end if;

    

    -- Look for Table Group names

    select instrb(upper(pSkipTables) || ',', 'SKIPBILLING' || ',', 1, 1) into vSkipTable from dual;

    if vSkipTable > 0 then

      vSkipBilling := true;

    end if;    

    

    -- Find out if the old provider exists

    begin

      select 1 into vSkipTable from producer where "Producer" = pOldProvider;

      -- if so, all is well

    exception 

      when no_data_found then

        -- If there is no pOldProvider, then we have nothing to do

        raise exOldProviderDoesNotExist;

    end;

    

    -- Find out if the new provider exists

    begin

      select 1 into vSkipTable from producer where "Producer" = pNewProvider;

      vNewProviderExists := true;

    exception

      when no_data_found then

        vNewProviderExists := false;

    end;

    

    -- If the New Provider Exists, and we are checking for errors, then stop here

    --  If you want to proceed past this point anyway, lower the vParams."VerifyLevel"

    if vNewProviderExists and vParams."VerifyLevel" >= ax_pkg.VERIFY_ERRORS then

      raise exNewProviderExists;    

    end if;    

    

    -- Figure out the plan (centralize logic statements)    

    if pAsOfDate is not null then

      -- If we are setting things only as of a specific date, that means we have to be more careful with our updates

      --  and take the date into account

      vAsOfDate := true;

    end if;

    if not vAsOfDate then

      -- If we are setting things so that pOldProvider always was pNewProvider, then we have to update profile type records

      vFullUpdate := true;

    end if;

    if vAsOfDate and not vNewProviderExists then

      -- If you are copying As of a Date, and the New Provider does not exist, then we need to make sure and COPY profile type records, 

      --  to ensure that all the records axiUm expects to be there are there

      vCopyProfile := true;

      -- Create ax_map record

      vMapAudit := ax_pkg.GetMapAudit_F(null,vParams);      

    end if;

    

    -- Start Changing data 

    ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'Starting to Change Provider Codes from ' || pOldProvider || ' to ' || pNewProvider || '...',vParams);

    if pAsOfDate is not null then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'  as of' || to_char('mm/dd/yyyy',pAsOfDate) || '...',vParams);

    end if;

      

    -- Producer

     -- Profile Record

    vTable := 'PRODUCER';

    if (vCopyProfile) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Copying ' || vTable || '...',vParams);

      

      -- Create AuditHis Record

      vAuditHisRow."TableName" := vTable;

      vAuditHisRow."HistoryType" := ax_pkg.AUDIT_ADD; 

      ax_pkg.CreateAuditHis_P(vAuditHisRow,vParams);

      

      -- Copy existing producer record

      select * into vProducerRow from producer where "Producer" = pOldProvider;

      -- Update record with new (or blank) values      

      vProducerRow."Producer" := pNewProvider;

      vProducerRow."LastName" := pOldProvider;

      vProducerRow."FirstName" := 'Copy';

      vProducerRow."MiddleName" := 'Of';

      vProducerRow."Preferred" := 'CopyOf' || pOldProvider;

      vProducerRow."Import" := ' ';

      vProducerRow."Audit" := vAuditHisRow."Audit";

      -- insert new record

      insert into producer values vProducerRow;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows inserted.',vParams);   

      

    elsif (vFullUpdate and vNewProviderExists) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Copying ' || vTable || '...',vParams);

      

      -- Create AuditHis Record

      vAuditHisRow."TableName" := vTable;

      vAuditHisRow."HistoryType" := ax_pkg.AUDIT_ADD; 

      ax_pkg.CreateAuditHis_P(vAuditHisRow,vParams);

      

      -- Copy existing producer record

      select * into vProducerRow from producer where "Producer" = pOldProvider;

      -- Update record with new (or blank) values      

      vProducerRow."Producer" := pNewProvider;

      vProducerRow."Import" := ' ';

      vProducerRow."Audit" := vAuditHisRow."Audit";

      -- insert new record

      insert into producer values vProducerRow;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows inserted.',vParams);   



    end if;

      

    -- Appointment Code Limits

     -- Profile Record

    vTable := 'APCDMAX';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then 

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update APCDMAX set "Provider"=pNewProvider where "Provider"= pOldProvider;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vCopyProfile and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Copying ' || vTable || '...',vParams);

      insert into APCDMAX (select apcdmax_apcdmax_seq.nextval,pNewProvider,"ApptCode","StartTime","EndTime","Limit","AllowBacktoBack" from apcdmax where "Provider" = pOldProvider);

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows inserted.',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;



    -- Appointments

    vTable := 'APPOINT';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vAsOfDate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || ' as of ' || to_char(pAsOfDate,'mm/dd/yyyy') || '...',vParams);

      -- Primary Provider

      update APPOINT set 

        "Producer"=pNewProvider,

        "ModifiedDateTime" = sysdate,

        "User" = vParams."User"

      where 

        "Producer"= pOldProvider and 

        "Date" >= pAsOfDate and

        "Status" = 0;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated (Producer).',vParams);

      -- Secondary Provider

      update APPOINT set 

        "Assistant"=pNewProvider,

        "ModifiedDateTime" = sysdate,

        "User" = vParams."User"

      where 

        "Assistant"= pOldProvider and 

        "Date" >= pAsOfDate and

        "Status" = 0;      

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated (Producer).',vParams);

    elsif (vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      -- Primary Provider

      update APPOINT set "Producer"=pNewProvider where "Producer"= pOldProvider;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated (Assistant).',vParams);

      -- Secondary Provider

      update APPOINT set "Assistant"=pNewProvider where "Assistant"= pOldProvider;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated (Assistant).',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;



    -- Appointment Expert Searches

      -- after Appoint      

    vTable := 'APEXPERT';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then 

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update APEXPERT set "Provider"=pNewProvider where "Provider"= pOldProvider;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vAsOfDate and vSkipTable = 0) then

      -- Update records where the provider on the Appoint record changed

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || ' as of ' || to_char(pAsOfDate,'mm/dd/yyyy') || '...',vParams);

      update APEXPERT set "Provider"=pNewProvider where "Provider"= pOldProvider and "ApptNum" in          

        (select "Appointment" from appoint where "Provider" = pNewProvider and "Date" >= pAsOfDate)

      ;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Appointment Code Access by Provider Type

    vTable := 'APPTACC';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update APPTACC set "Provider"=pNewProvider where "Provider"= pOldProvider;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vCopyProfile and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Copying ' || vTable || '...',vParams);

      insert into APPTACC (select "ApptCode","ProdType","Access","Type",pNewProvider from apptacc where "Provider" = pOldProvider and "Type" = 1);

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows inserted.',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Appointment History

      -- After Appoint

    vTable := 'APPTHIS';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and pChangeHistory and vSkipTable = 0) then 

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update APPTHIS set "Producer"=pNewProvider where "Producer"= pOldProvider;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vAsOfDate and pChangeHistory and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || ' as of ' || to_char(pAsOfDate,'mm/dd/yyyy') || '...',vParams);

      update APPTHIS set "Producer"=pNewProvider where "Producer"= pOldProvider and "Date" >= pAsOfDate;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;



    -- Additional providers/attendess for a given appointment

      -- After Appoint

    vTable := 'APPTPROV';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vAsOfDate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || ' as of ' || to_char(pAsOfDate,'mm/dd/yyyy') || '...',vParams);

      update APPTPROV set "Provider"=pNewProvider where "Provider"= pOldProvider and "Appointment" in 

        (select "Appointment" from appoint where "Provider" = pNewProvider and "Date" >= pAsOfDate);

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vFullUpdate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update APPTPROV set "Provider"=pNewProvider where "Provider"= pOldProvider;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Billing Definitions

    vTable := 'BILLDEF';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then 

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update BILLDEF set "BillDoctor"=pNewProvider where "BillDoctor"= pOldProvider;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif(vAsOfDate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_WARNING,'    Billing Definitions for ' || pNewProvider || ' may need to be defined!',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Billing Exceptions

    vTable := 'BILLEXC';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then  

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update BILLEXC set "Producer"=pNewProvider where "Producer"= pOldProvider;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif(vAsOfDate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_WARNING,'    Billing Exceptions for ' || pNewProvider || ' may need to be defined!',vParams);      

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Billing Numbers

      -- Record has to be added if it does not exist

    vTable := 'BILLING';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (pAsOfDate is null and vSkipTable = 0 and not vSkipBilling) then 

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update BILLING set "Producer"=pNewProvider where "Producer"= pOldProvider; 

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vCopyProfile and vSkipTable = 0 and not vSkipBilling) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Inserting into ' || vTable || '...',vParams);

      insert into BILLING (

        select 

          "Company",

          pNewProvider,

          ' ',

          ' ',

          0,

          ' ',

          0,

          ' ',

          ' ',

          ' ',

          0,

          0,

          ' ',

          ' ',

          ' '

        from

          INSURANC

      );

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows inserted.',vParams);    

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- List of providers belonging to a book

    vTable := 'BOOKPROV';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then  

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update BOOKPROV p set "Provider" = pNewProvider where "Provider" = pOldProvider and not exists (select 1 from bookprov p2 where p."BookDetail"=p2."BookDetail" and p2."Provider"=pNewProvider);

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vCopyProfile and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Copying ' || vTable || '...',vParams);

      insert into BOOKPROV (

        select 

          "BookDetail", 

          pNewProvider, 

          max("Order") + 1

        from 

          bookprov 

        where 

          "BookDetail" in (select "BookDetail" from bookprov where "Provider" = pOldProvider)

        group by

          "BookDetail"

      );

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows inserted.',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Chair Layout

    vTable := 'CHAIRL';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then  

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update CHAIRL set "Producer"=pNewProvider where "Producer"= pOldProvider;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Temporary Unapproved Treatments

    vTable := 'CHARTLNK';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then  

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update CHARTLNK set "Producer"=pNewProvider where "Producer"= pOldProvider; 

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif(vAsOfDate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || ' as of ' || to_char(pAsOfDate,'mm/dd/yyyy') || '...',vParams);

      update CHARTLNK set 

        "Producer"=pNewProvider,

        "User"=vParams."User",

        "StationId"=vParams."StationId"

      where 

        "Producer"= pOldProvider and 

        "TxDate" >= pAsOfDate

      ;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Account for pAsOfDate *and* pSkipBilling

    -- DELETE any non-submitted claims that we would normally be updating

    -- These should be re-batched

    --  Also delete from Claimt

    vTable := 'CLAIM';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (not vSkipBilling and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Deleting from ' || vTable || '...',vParams);

      --update CLAIM set "Doctor"=pNewProvider where "Doctor"= pOldProvider; 

      delete CLAIM where "Doctor" = pOldProvider and "Status" = 0 and "EDIStatus" = 0;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows deleted.',vParams);

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_WARNING,'    Unsubmitted Claims for ' || pOldProvider || ' have been removed, and will need to be rebatched for ' || pNewProvider || '!',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Clinic - Default Provider to Charge

    vTable := 'CLINIC';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then  

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update CLINIC set "Provider"=pNewProvider where "Provider"= pOldProvider;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Dispensary History

    vTable := 'DISPHIS';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0 and pChangeHistory) then 

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update DISPHIS set "Provider"=pNewProvider where "Provider"= pOldProvider;  

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif(vAsOfDate and vSkipTable = 0 and pChangeHistory) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || ' as of ' || to_char(pAsOfDate,'mm/dd/yyyy') || '...',vParams);

      update DISPHIS set 

        "Provider"=pNewProvider 

      where 

        "Provider"= pOldProvider and

        "DateOut" >= trunc(pAsOfDate);

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Lost Dispensary Items

    vTable := 'DISPLOST';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then  

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update DISPLOST set "Provider"=pNewProvider where "Provider"= pOldProvider; 

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif(vAsOfDate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || ' as of ' || to_char(pAsOfDate,'mm/dd/yyyy') || '...',vParams);

      update DISPLOST set "Provider"=pNewProvider where "Provider"= pOldProvider and "Date" >= pAsOfDate;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Account for pAsOfDate *and* pChangeHistory

    

    -- Dispensary Requests

    vTable := 'DISPREQ';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then  

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update DISPREQ set "Provider"=pNewProvider where "Provider"= pOldProvider; 

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vAsOfDate and vSkipTable = 0) then

       ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || ' as of ' || to_char(pAsOfDate,'mm/dd/yyyy') || '...',vParams);

      update DISPREQ set "Provider"=pNewProvider where "Provider"= pOldProvider and "DateOut" >= pAsOfDate;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);   

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Account for pAsOfDate *and* pChangeHistory

    

    -- Dispensary Transactions

    --  After DISPLOST

    vTable := 'DISPTRX';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then  

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update DISPTRX set "Provider"=pNewProvider where "Provider"= pOldProvider; 

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vAsOfDate and vSkipTable = 0) then

       ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || ' as of ' || to_char(pAsOfDate,'mm/dd/yyyy') || '...',vParams);

      update DISPTRX set "Provider"=pNewProvider where "Provider"= pOldProvider and "DispLost" in (

        select "DispLost" from displost where "Provider" = pNewProvider

      );

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);        

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Dispensary Template

      -- Profile

    vTable := 'DISTEMPL';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update DISTEMPL set "Provider"=pNewProvider where "Provider"= pOldProvider; 

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vCopyProfile and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Copying ' || vTable || '...',vParams);

      insert into DISTEMPL (select pNewProvider,"Template","Description" from DISTEMPL where "Provider" = pOldProvider);

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows inserted.',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Dispensary Template Item

     -- Profile

    vTable := 'DISTITEM';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update DISTITEM set "Provider"=pNewProvider where "Provider"= pOldProvider;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vCopyProfile and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Copying ' || vTable || '...',vParams);

      insert into DISTITEM (select pNewProvider,"Template","Item","Type","KitType","Sundry" from DISTITEM where "Provider" = pOldProvider);

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows inserted.',vParams);      

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Appointment Codes for an Individual Provider

      -- Profile

    vTable := 'DRAPPTCD';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update DRAPPTCD set "Provider"=pNewProvider where "Provider"= pOldProvider;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vCopyProfile and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Copying ' || vTable || '...',vParams);

      insert into DRAPPTCD (select "ApptCode",pNewProvider,"Unit0","Unit1","Unit2","Unit3","Unit4","Unit5","Time0","Time1","Time2","Time3","Time4","Time5","PrimaryExclusive" from DRAPPTCD where "Provider" = pOldProvider);

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows inserted.',vParams);      

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Student Evaluation Records

    vTable := 'GRADING';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update GRADING set "Producer"=pNewProvider where "Producer"= pOldProvider;  

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vAsOfDate and vSkipTable = 0) then

       ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || ' as of ' || to_char(pAsOfDate,'mm/dd/yyyy') || '...',vParams);

      update GRADING set "Producer"=pNewProvider where "Producer"= pOldProvider and "CreateDate" >= pAsOfDate;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);        

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    vTable := 'HISTORY';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0 and pChangeHistory) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update HISTORY set "Producer"=pNewProvider where "Producer"= pOldProvider; 

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Dispensary Kit Information Record

    vTable := 'KIT';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then

      vTable := 'KIT';

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update KIT set "ProviderOut"=pNewProvider where "ProviderOut"= pOldProvider;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vAsOfDate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || ' as of ' || to_char(pAsOfDate,'mm/dd/yyyy') || '...',vParams);

      update KIT set "ProviderOut"=pNewProvider where "ProviderOut"= pOldProvider and "DateOut" >= pAsOfDate;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);        

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

        

    -- History of Lab Requests

    vTable := 'LABHIS';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0 and pChangeHistory) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update LABHIS set "Provider"=pNewProvider where "Provider"= pOldProvider;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vAsOfDate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || ' as of ' || to_char(pAsOfDate,'mm/dd/yyyy') || '...',vParams);

      update LABHIS set "Provider"=pNewProvider where "Provider"= pOldProvider and "DateOut" >= pAsOfDate;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);    

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Lab Item Details

    vTable := 'LABITEM';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update LABITEM set "Provider"=pNewProvider where "Provider"= pOldProvider;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vAsOfDate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || ' as of ' || to_char(pAsOfDate,'mm/dd/yyyy') || '...',vParams);

      -- Create AuditHis Record

      vAuditHisRow."TableName" := vTable;

      vAuditHisRow."HistoryType" := ax_pkg.AUDIT_EDIT; 

      ax_pkg.CreateAuditHis_P(vAuditHisRow,vParams);

      

      update LABITEM set 

        "Provider"=pNewProvider,

        "Audit"=vAuditHisRow."Audit",

        "User"=vParams."User"

      where 

        "Provider"= pOldProvider and 

        "DateOut" >= pAsOfDate;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);   

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Lab Item History

    vTable := 'LABITEMH';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update LABITEMH set "Provider"=pNewProvider where "Provider"= pOldProvider;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',pParams);

    elsif (vAsOfDate) then

      -- If vAsOfDate then new LABITEMH records should have been created via the LABITEM updates

      -- Which means it was not skipped.

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    ' || vTable || ' records created via trigger, if LABITEM updated...',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

      

    -- Need Requests  

    vTable := 'NEEDREQ';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update NEEDREQ set "Provider"=pNewProvider where "Provider"= pOldProvider;  

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vAsOfDate and vSkipTable = 0) then

      -- Create AuditHis Record

      vAuditHisRow."TableName" := vTable;

      vAuditHisRow."HistoryType" := ax_pkg.AUDIT_EDIT; 

      ax_pkg.CreateAuditHis_P(vAuditHisRow,vParams);

    

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || ' as of ' || to_char(pAsOfDate,'mm/dd/yyyy') || '...',vParams);

      update NEEDREQ set 

        "Provider"=pNewProvider,

        "AuditId" = vAuditHisRow."Audit"

      where 

        "Provider"= pOldProvider and 

        "Date" >= pAsOfDate;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);    

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Need Requests History

    vTable := 'NEEDREQH';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0 and pChangeHistory) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update NEEDREQH set "Provider"=pNewProvider where "Provider"= pOldProvider; 

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vAsOfDate) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    ' || vTable || ' records created via trigger, if NEEDREQ updated...',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;    

    

    -- Record of overdue messages that have been sent

    vTable := 'ODMSGSNT';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then  

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update ODMSGSNT set "Producer"=pNewProvider where "Producer"= pOldProvider; 

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vAsOfDate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || ' as of ' || to_char(pAsOfDate,'mm/dd/yyyy') || '...',vParams);

      update ODMSGSNT set "Producer"=pNewProvider where "Producer"= pOldProvider and "Date" >= pAsOfDate;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);  

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Charting Conditions Displayed per provider type

     -- Profile

    vTable := 'PERCODIS';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update PERCODIS set "Provider"=pNewProvider where "Provider"= pOldProvider; 

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vCopyProfile and vSkipTable = 0) then

      -- Create AuditHis Record

      vAuditHisRow."TableName" := vTable;

      vAuditHisRow."HistoryType" := ax_pkg.AUDIT_ADD; 

      ax_pkg.CreateAuditHis_P(vAuditHisRow,vParams);

      

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Copying ' || vTable || '...',vParams);

      insert into PERCODIS (

        select

          percodis_perconddis_seq.nextval,

          "ProdType",

          pNewProvider,

          "PerCond",

          "Section",

          "Order",

          "Color",

          "Chart",

          "Deleted",

          vAuditHisRow."Audit",

          "SiteRestricted"

        from

          PERCODIS

        where

          "Provider" = pOldProvider and

          "Deleted" = 0

        );

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows inserted.',vParams);  

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;



    -- Audit History for PERCODIS table   

    vTable := 'PERCDHIS';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0 and pChangeHistory) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update PERCDHIS set "Provider"=pNewProvider where "Provider"= pOldProvider; 

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vAsOfDate) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    ' || vTable || ' records created via trigger, if PERCODIS updated...',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Perio Options

      -- Profile

    vTable := 'PEROPTS';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update PEROPTS set "Provider"=pNewProvider where "Provider"= pOldProvider;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vCopyProfile and vSkipTable = 0) then

      -- Create AuditHis Record

      vAuditHisRow."TableName" := vTable;

      vAuditHisRow."HistoryType" := ax_pkg.AUDIT_ADD; 

      ax_pkg.CreateAuditHis_P(vAuditHisRow,vParams);

      

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Copying ' || vTable || '...',vParams);

      insert into PEROPTS (

        select

          peropts_peropts_seq.nextval,

          "ProdType",

          pNewProvider,

          "ShowGraphics",

          "ShowBorders",

          "CalculateScores",

          "Deleted",

          vAuditHisRow."Audit",

          "RequireExam",

          "ApprovalMethod",

          "CalculateAttach",

          "NewExamCopy"

        from

          PEROPTS

        where

          "Provider" = pOldProvider and

          "Deleted" = 0

        );

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows inserted.',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Summary/Stats displayed per Provider Type

      -- Profile

    vTable := 'PERSUDIS';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update PERSUDIS set "Provider"=pNewProvider where "Provider"= pOldProvider;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vCopyProfile and vSkipTable = 0) then

      -- Create AuditHis Record

      vAuditHisRow."TableName" := vTable;

      vAuditHisRow."HistoryType" := ax_pkg.AUDIT_ADD; 

      ax_pkg.CreateAuditHis_P(vAuditHisRow,vParams);

      

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Copying ' || vTable || '...',vParams);

      insert into PERSUDIS (

        select

          persudis_persummdis_seq.nextval,

          "ProdType",

          pNewProvider,

          "PerSumm",

          "Order",

          "Deleted",

          vAuditHisRow."Audit"

        from

          PERSUDIS

        where

          "Provider" = pOldProvider and

          "Deleted" = 0

        );

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows inserted.',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;



    -- Audit history for PERSUDIS

    -- account for pAsOfDate - link date via audithis

    vTable := 'PERSDHIS';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0 and pChangeHistory) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update PERSDHIS set "Provider"=pNewProvider where "Provider"= pOldProvider;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vAsOfDate) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    ' || vTable || ' records created via trigger, if PERSUDIS updated...',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Practice Information

    vTable := 'PRACTICE';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update PRACTICE set "DefaultDoctor"=pNewProvider where "DefaultDoctor"= pOldProvider;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- if change history, still don't change..

      --- Prescript

      --- Claim

      --- Alerts that go to rcopia

    

    -- Prescriptions    

      -- Skip if PrescriptType <> 0

       -- otherwise, historical medication record

    vTable := 'PRESCRIP';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then

      -- Create AuditHis Record

      vAuditHisRow."TableName" := vTable;

      vAuditHisRow."HistoryType" := ax_pkg.AUDIT_EDIT; 

      ax_pkg.CreateAuditHis_P(vAuditHisRow,vParams);

    

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update PRESCRIP set 

        "Provider" = pNewProvider,

        "Audit" = vAuditHisRow."Audit"

      where 

        "Provider"= pOldProvider and

        "eRxSyncAudit" = 0 and

        "PrescripType" in (0,2) and

        "Deleted" = 0

      ;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    -- as of

      -- potentially void record, and add a new one??

      

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Provider Competency Levels

    vTable := 'PRLEVEL';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update PRLEVEL set "Provider"=pNewProvider where "Provider"= pOldProvider; 

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif(vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_WARNING,'    Provider Levels for ' || pNewProvider || ' may need to be defined!',vParams);

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_WARNING,'    Maintenance -> Office tab -> Users -> Select User -> Edit Record -> Provider Tab -> Levels',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Provider

    vTable := 'PRODUCER';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update PRODUCER set "Producer"=pNewProvider, "TypeCode"=RPAD(pNewProvider,1) where "Producer"= pOldProvider; 

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (not vCopyProfile) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;



    -- History records for the PRODUCER table

    vTable := 'PRODHIS';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update PRODHIS set "Producer"=pNewProvider where "Producer"= pOldProvider; 

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vCopyProfile) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    ' || vTable || ' records created via trigger...',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Provider Signatures

    vTable := 'PROVSIG';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update PROVSIG set "Provider"=pNewProvider where "Provider"= pOldProvider;  

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vAsOfDate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || ' as of ' || to_char(pAsOfDate,'mm/dd/yyyy') || '...',vParams);

      update PROVSIG set 

        "Provider"=pNewProvider,

        "Date"=trunc(sysdate),

        "User" = vParams."User",

        "StationId" = vParams."StationId"

      where 

        "Provider"= pOldProvider and 

        "Date" >= pAsOfDate;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);  

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Audit Trail of PROVSIG

    vTable := 'PROVSIGH';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vSkipTable = 0 and pChangeHistory) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update PROVSIGH set "Provider"=pNewProvider where "Provider"= pOldProvider; 

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vAsOfDate and vSkipTable = 0) then

      -- NOT created by a trigger

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Creating ' || vTable || ' records...',vParams);

      insert into PROVSIGH (

        select

          provsigh_provsigh_seq.nextval,

          2,

          "Provider",

          SIGNATURE,

          trunc(sysdate),

          vParams."User",

          vParams."StationId"

        from

          PROVSIG

        where

          "Provider" = pNewProvider and

          "User" = vParams."User" and

          "StationId" = vParams."StationId" and

          "Date" = trunc(sysdate)

        );

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows inserted.',vParams);      

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Overdue Calculations

    vTable := 'PTOVRDUE';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update PTOVRDUE set "Producer"=pNewProvider where "Producer"= pOldProvider;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif(vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_WARNING,'    Overdue Conditions for ' || pNewProvider || ' may need to be recalculated!',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Extensions for Overdue Patients

    vTable := 'PTOVREXT';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update PTOVREXT set "Provider"=pNewProvider where "Provider"= pOldProvider;  

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vAsOfDate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || ' as of ' || to_char(pAsOfDate,'mm/dd/yyyy') || '...',vParams);

      update PTOVREXT set 

        "Provider"=pNewProvider

      where 

        "Provider"= pOldProvider and 

        "Date" >= pAsOfDate;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);  

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;



    -- Patient Perio Chart

    vTable := 'PTPERIO';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update PTPERIO set "Provider"=pNewProvider where "Provider"= pOldProvider; 

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif(vAsOfDate and vSkipTable = 0) then

      -- Create AuditHis Record

      vAuditHisRow."TableName" := vTable;

      vAuditHisRow."HistoryType" := ax_pkg.AUDIT_EDIT; 

      ax_pkg.CreateAuditHis_P(vAuditHisRow,vParams);

    

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || ' as of ' || to_char(pAsOfDate,'mm/dd/yyyy') || '...',vParams);

      update PTPERIO set 

        "Provider"=pNewProvider,

        "ChartDate"=trunc(sysdate),

        "Audit" = vAuditHisRow."Audit"

      where 

        "Provider"= pOldProvider and 

        "ChartDate" >= pAsOfDate;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);    

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;



    -- account for pAsOfDate

    vTable := 'PTPERHIS';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0 and pChangeHistory) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update PTPERHIS set "Provider"=pNewProvider where "Provider"= pOldProvider;  

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vAsOfDate) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    ' || vTable || ' records created via trigger, if PTPERIO updated...',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    

    -- Also look at Faculty assignements

    

    -- Student Assignments

    vTable := 'PTPROD';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update PTPROD set "Producer"=pNewProvider where "Producer"= pOldProvider;  

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif(vAsOfDate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Copying ' || vTable || '...',vParams);

      

      -- First we need to copy the PtProd records from the pOldProvider to the pNewProvider

      for cPtProd in curPtProd loop

        vPtProdRow := cPtProd;

        vPtProdRow."Producer" := pNewProvider;

        vPtProdRow."StartDate" := greatest(vPtProdRow."StartDate",pAsOfDate);

        ax_assign_pkg.InsertPtProd_P(vPtProdRow,vParams,true);

      end loop;



      -- Then we need to delete any records that would be invalid

      update ptprod set 

        "Deleted" = 1,

        "User" = vParams."User",

        "StationId" = vParams."StationId",

        "CreateDate" = trunc(sysdate)

      where

        "Producer" = pOldProvider and

        "StartDate" >= pAsOfDate and

        (

          "EndDate" >= pAsOfDate or 

          "EndDate" is null

        ) and

        "Deleted" = 0

      ;    

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams); 



      -- Finally we need to end-date the pOldProvider ptprod records to the pAsOfDate

      update ptprod set 

        "EndDate" = pAsOfDate,

        "User" = vParams."User",

        "StationId" = vParams."StationId",

        "CreateDate" = trunc(sysdate)

      where

        "Producer" = pOldProvider and          

        (

          "EndDate" >= pAsOfDate or 

          "EndDate" is null

        ) and

        "Deleted" = 0

      ;    

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);      



    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- PtProd History

    vTable := 'PTPRODH';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (pAsOfDate is null and vSkipTable = 0 and pChangeHistory) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update PTPRODH set "Producer"=pNewProvider where "Producer"= pOldProvider; 

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vAsOfDate) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Adding ' || vTable || '...',vParams);

      -- Insert History records are handled by ax_assign_pkg.InsertPtProd_P

      insert into ptprodh (

        select

          ptprodh_PtProdHistory_seq.nextval,

          "Patient",

          "Producer",

          trunc(sysdate), -- Date

          1, -- deleted

          "StartDate",

          "EndDate",

          "IsRestricted",

          "IsPrimary",

          "Discipline",

          round(to_char(sysdate,'SSSSS') / 60), -- Time

          "CreateDate",

          "User",

          "StationId",

          "Id",

          "Note",

          "Deleted"

        from

          ptprod

        where

          "Producer" = pOldProvider and

          "StartDate" >= pAsOfDate and

          (

            "EndDate" >= pAsOfDate or 

            "EndDate" is null

          ) and

          "User" = vParams."User" and

          "StationId" = vParams."StationId" and

          "CreateDate" = trunc(sysdate) and

          "Deleted" = 1

      );

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptprodh rows inserted.',vParams);

      insert into ptprodh (

        select

          ptprodh_PtProdHistory_seq.nextval,

          "Patient",

          "Producer",

          trunc(sysdate), -- Date

          2, -- edited

          "StartDate",

          "EndDate",

          "IsRestricted",

          "IsPrimary",

          "Discipline",

          round(to_char(sysdate,'SSSSS') / 60), -- Time

          "CreateDate",

          "User",

          "StationId",

          "Id",

          "Note",

          "Deleted"

        from

          ptprod

        where

          "Producer" = pOldProvider and

          (

            "EndDate" >= pAsOfDate or 

            "EndDate" is null

          ) and

          "User" = vParams."User" and

          "StationId" = vParams."StationId" and

          "CreateDate" = trunc(sysdate) and

          "Deleted" = 0

      );

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ptprodh rows inserted.',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Patient Recalls

    vTable := 'PTRECALL';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update PTRECALL set "Provider"=pNewProvider where "Provider"= pOldProvider; 

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vAsOfDate and vSkipTable = 0) then

      -- Create AuditHis Record

      vAuditHisRow."TableName" := vTable;

      vAuditHisRow."HistoryType" := ax_pkg.AUDIT_EDIT; 

      ax_pkg.CreateAuditHis_P(vAuditHisRow,vParams);

    

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || ' as of ' || to_char(pAsOfDate,'mm/dd/yyyy') || '...',vParams);

      update PTRECALL set 

        "Provider"=pNewProvider,

        "Audit" = vAuditHisRow."Audit"

      where 

        "Provider"= pOldProvider and 

        "RecallDate" >= pAsOfDate and 

        "Deleted" = 0;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);  

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Patient Recall History

    vTable := 'PTRECHIS';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vSkipTable = 0 and pChangeHistory) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update PTRECHIS set "Provider"=pNewProvider where "Provider"= pOldProvider; 

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vAsOfDate) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    ' || vTable || ' records created via trigger, if PTRECALL updated...',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Record of start checks processed

    vTable := 'STARTCHK';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update STARTCHK set "Provider"=pNewProvider where "Provider"= pOldProvider;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vAsOfDate and vSkipTable = 0) then  

      -- Create AuditHis Record

      vAuditHisRow."TableName" := vTable;

      vAuditHisRow."HistoryType" := ax_pkg.AUDIT_EDIT; 

      ax_pkg.CreateAuditHis_P(vAuditHisRow,vParams);

      

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || ' based on Appointments...',vParams);

      update STARTCHK ck set 

        ck."Provider"=pNewProvider, 

        ck."Audit" = vAuditHisRow."Audit" 

      where 

        ck."Provider"= pOldProvider and

        pNewProvider = (select "Provider" from appoint a where a."Appointment" = ck."Appointment")

      ;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Temporary Table used by Appointment Expert

    vTable := 'TEMPAPPT';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update TEMPAPPT set "Assistant"=pNewProvider where "Assistant"= pOldProvider;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- YOU ARE HERE

    

    -- Treatments on Chart

    -- account for pAsOfDate

     -- only change history if pChangeHistory

     -- After TxPTx

    vTable := 'TREATME2';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0 and pChangeHistory) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update TREATME2 set "Provider"=pNewProvider where "Provider"= pOldProvider;  

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif(vAsOfDate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || ' as of ' || to_char(pAsOfDate,'mm/dd/yyyy') || '...',vParams);

      update TREATME2 set 

        "Provider"=pNewProvider 

      where 

        "Provider"= pOldProvider and

        "Days" = to_char(trunc(pAsOfDate)-to_date('01-jan-1901'))

      ;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- account for pAsOfDate - create new History records (not trigger)

    vTable := 'TRX';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0 and pChangeHistory) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update TRX set "Producer"=pNewProvider where "Producer"= pOldProvider; 

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vFullUpdate and vSkipTable = 0) then

      -- Only update in process/planned treatments

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || ' (in process/planned only)...',vParams);

    

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update TRX set "Producer"=pNewProvider where "Producer"= pOldProvider; 

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

      

      -- Create History Records

      

      

    elsif(vAsOfDate and vSkipTable = 0) then

      -- Only update in process/planned treatments

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || ' as of ' || to_char(pAsOfDate,'mm/dd/yyyy') || ' (in process/planned only)...',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- account for pAsOfDate

    vTable := 'TXPTX';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vSkipTable = 0 and pChangeHistory) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update TXPTX set "Provider"=pNewProvider where "Provider"= pOldProvider;  

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',pParams);



      

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Users Table

    vTable := 'USERS';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update USERS set "Producer"=pNewProvider where "Producer"= pOldProvider;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Users History

    vTable := 'USERSHIS';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update USERSHIS set "Producer"=pNewProvider where "Producer"= pOldProvider; 

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Vacation

    vTable := 'VACATION';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update VACATION set "Provider"=pNewProvider where "Provider"= pOldProvider;  

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif(vAsOfDate and vSkipTable = 0) then  

      -- First we need to copy the workschd records from the pOldProvider to the pNewProvider

      -- Create AuditHis Record

      vAuditHisRow."TableName" := vTable;

      vAuditHisRow."HistoryType" := ax_pkg.AUDIT_ADD; 

      ax_pkg.CreateAuditHis_P(vAuditHisRow,vParams);

      

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Copying ' || vTable || '...',vParams);

      insert into VACATION (

        select

          vacation_id_seq.nextval,

          pNewProvider,

          "Description",

          pAsOfDate,

          "StartTime",

          "EndTime",

          "User",

          "Type",

          "DisplayDesc",

          "Deleted",

          vAuditHisRow."Audit",

          "Color",

          "VacaSet",

          "SetException",

          "IsBreak",

          "AvailableClinic"          

        from

          vacation

        where

          "Provider" = pOldProvider and          

          "StartDate" >= pAsOfDate and

          "Deleted" = 0

        );

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows inserted.',vParams);  



      -- Create AuditHis Record

      vAuditHisRow."TableName" := vTable;

      vAuditHisRow."HistoryType" := ax_pkg.AUDIT_EDIT; 

      ax_pkg.CreateAuditHis_P(vAuditHisRow,vParams);



      -- Then we need to delete any records that would be invalid

      update vacation set 

        "Deleted" = 1,

        "AuditId" = vAuditHisRow."Audit"

      where

        "Provider" = pOldProvider and

        "StartDate" >= pAsOfDate and

        "Deleted" = 0

      ;    

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams); 

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Vacation History Records

    vTable := 'VACATNH';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0 and pChangeHistory) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update VACATNH set "Provider"=pNewProvider where "Provider"= pOldProvider; 

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vAsOfDate) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    ' || vTable || ' records created via trigger, if VACATION updated...',vParams);        

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Work Schedules

    vTable := 'WORKSCHD';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update WORKSCHD set "Provider"=pNewProvider where "Provider"= pOldProvider; 

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vAsOfDate and vSkipTable = 0) then

      -- First we need to copy the workschd records from the pOldProvider to the pNewProvider

      

      -- Create mapping records

      insert into ax_map (

        select 

          vMapAudit,

          vTable, 

          "Id", 

          workschd_id_seq.nextval,

          '',

          ''

        from workschd 

        where "Provider" = pOldProvider and          

          (

            "EndDate" >= pAsOfDate or 

            "EndDate" is null

          ) and

          "Deleted" = 0

      );

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' ax_map rows inserted.',vParams);

      

      -- Create AuditHis Record

      vAuditHisRow."TableName" := vTable;

      vAuditHisRow."HistoryType" := ax_pkg.AUDIT_ADD; 

      ax_pkg.CreateAuditHis_P(vAuditHisRow,vParams);

      

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Copying ' || vTable || '...',vParams);

      insert into workschd (

        select

          m."TargetId",

          pNewProvider,

          w."Description",

          greatest(w."StartDate",pAsOfDate),

          w."EndDate",

          w."Monday",

          w."Tuesday",

          w."Wednesday",

          w."Thursday",

          w."Friday",

          w."Saturday",

          w."Sunday",

          w."Cycle",

          w."CycleStart",

          w."WorkSchType",

          w."ExcWorkSchId",          

          w."User",

          w."Type",

          w."Deleted",

          vAuditHisRow."Audit",

          w."CycleType",

          w."CycleFrq"          

        from

          workschd w

          inner join ax_map m on m."SourceId" = w."Id"

      );

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows inserted.',vParams);  



      -- Create AuditHis Record

      vAuditHisRow."TableName" := vTable;

      vAuditHisRow."HistoryType" := ax_pkg.AUDIT_EDIT; 

      ax_pkg.CreateAuditHis_P(vAuditHisRow,vParams);



      -- Then we need to delete any records that would be invalid

      update workschd set 

        "Deleted" = 1,

        "AuditId" = vAuditHisRow."Audit"

      where

        "Provider" = pOldProvider and

        "StartDate" >= pAsOfDate and

        (

          "EndDate" >= pAsOfDate or 

          "EndDate" is null

        ) and

        "Deleted" = 0

      ;    

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams); 



      -- Finally we need to end-date the pOldProvider workschd records to the pAsOfDate

      update workschd set 

        "EndDate" = pAsOfDate,        

        "AuditId" = vAuditHisRow."Audit"

      where

        "Provider" = pOldProvider and          

        (

          "EndDate" >= pAsOfDate or 

          "EndDate" is null

        ) and

        "Deleted" = 0

      ;    

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams); 

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Work Schedule History

    vTable := 'WRKSCHH';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0 and pChangeHistory) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update WRKSCHH set "Provider"=pNewProvider where "Provider"= pOldProvider;  

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vAsOfDate) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    ' || vTable || ' records created via trigger, if WORKSCHD updated...',vParams);      

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    

    -- Work Schedule Items    

    vTable := 'WSCHITEM';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vAsOfDate and vSkipTable = 0) then

      -- First we need to copy the workschd records from the pOldProvider to the pNewProvider

      -- Create AuditHis Record

      vAuditHisRow."TableName" := vTable;

      vAuditHisRow."HistoryType" := ax_pkg.AUDIT_ADD; 

      ax_pkg.CreateAuditHis_P(vAuditHisRow,vParams);

      

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Copying ' || vTable || ' not yet implemented...',vParams);

      

  /*    ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Copying ' || vTable || '...',vParams);

      insert into WSCHITEM (

        select

          wschitem_id_seq.nextval,

          i."WorkschdId",

          i."Weekday",

          i."StartTime",

          i."EndTime",

          i."Clinic",

          i."NumChairs",

          i."ClinicTime",

          i."PGroup",

          i."Deleted",

          vAuditHisRow."Audit",

          i."ReserveChangeDate",

          i."BreakT",

          i."UseSharedChairs"          

        from

          WSCHITEM i

          

        where

          "Id" in (select "Id" from 

          "Deleted" = 0

        );

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows inserted.',vParams);  



*/



      -- Create AuditHis Record

      vAuditHisRow."TableName" := vTable;

      vAuditHisRow."HistoryType" := ax_pkg.AUDIT_EDIT; 

      ax_pkg.CreateAuditHis_P(vAuditHisRow,vParams);



      -- Then we need to delete any records that would be invalid

      update workschd set 

        "Deleted" = 1,

        "AuditId" = vAuditHisRow."Audit"

      where

        "Provider" = pOldProvider and

        "StartDate" >= pAsOfDate and

        (

          "EndDate" >= pAsOfDate or 

          "EndDate" is null

        ) and

        "Deleted" = 0

      ;    

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams); 



      -- Finally we need to end-date the pOldProvider workschd records to the pAsOfDate

      update workschd set 

        "EndDate" = pAsOfDate,        

        "AuditId" = vAuditHisRow."Audit"

      where

        "Provider" = pOldProvider and          

        (

          "EndDate" >= pAsOfDate or 

          "EndDate" is null

        ) and

        "Deleted" = 0

      ;    

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams); 

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;

    



    -- Chair Reservations

      -- After Holiday,Vacation,WSCHITEM,GroupL

      -- use ax_map

    vTable := 'RESERVE';

    select instrb(upper(pSkipTables) || ',', vTable || ',', 1, 1) into vSkipTable from dual;

    if (vFullUpdate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || '...',vParams);

      update RESERVE set "Producer"=pNewProvider where "Producer"= pOldProvider; 

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

      update RESERVE set "Assistant"=pNewProvider where "Assistant"= pOldProvider; 

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || lower(vTable) || ' rows updated.',vParams);

    elsif (vAsOfDate and vSkipTable = 0) then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'    Updating ' || vTable || ' as of ' || to_char(pAsOfDate,'mm/dd/yyyy') || ' (in process/planned only)...',vParams);

-- account for mapping

    

    else

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_DEBUG,'    Skipping ' || vTable || '...',vParams);

    end if;



    -- All Done!

    ax_pkg.dbmsoutput_p(ax_pkg.MSG_INFO,'Completed changing Provider Codes without error.');     

    

    if (vCopyProfile) then

      delete from ax_map where "Audit" = vMapAudit;

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_DML,to_char(SQL%rowcount) || ' rows deleted from ax_map.',vParams);    

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_WARNING,'User still has to be issued Provider Code ' || pNewProvider || ' in axiUm. Click "Yes" on the window that starts with:',vParams);   

      ax_pkg.dbmsoutput_P(ax_pkg.MSG_WARNING,'This Provider Type and ID was previously in use by CopyOf ' || pOldProvider,vParams);   

    end if;    

     

  exception     

    when exOldProviderDoesNotExist then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_ERROR,'Provider ' || pOldProvider || ' does not exist, cannot continue!',vParams);

    when exNewProviderExists then

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_ERROR,'Provider ' || pNewProvider || ' already exists, cannot continue!',vParams);

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_ERROR,'To bypass this error, run again with pParams."VerifyLevel" = ax_pkg.VERIFY_NONE.',vParams);

    when others then  -- handles all other errors

      ax_pkg.dbmsoutput_p(ax_pkg.MSG_ERROR,vTable || ', ' || sqlerrm,vParams);

  end ChangeProvider_P;



END;
CREATE OR REPLACE PACKAGE BODY carequality_pkg IS
FUNCTION get_carequality_status() RETURN numeric IS
	v_nCQStatus NUMBER(5) := 0;
BEGIN
	BEGIN
		SELECT TO_NUMBER("Value") INTO v_nCQStatus
			FROM SYSOPTS WHERE "Name" = 'CQ_CarequalityConnection';
		EXCEPTION
		WHEN NO_DATA_FOUND THEN
			v_nCQStatus := 0;
	END;
		
	return v_nCQStatus;
END;

FUNCTION get_carequality_consentcode() RETURN character varying IS
	v_CQConsent VARCHAR2(4000) := ' ';
BEGIN
	BEGIN
      SELECT TRIM("Value") INTO v_CQConsent
            FROM SYSOPTS WHERE "Name" = 'CQ_PatientConsent';
      EXCEPTION
      WHEN NO_DATA_FOUND THEN
            v_CQConsent := ' ';
   END;

   return v_CQConsent;
END;

-- AX-27011, AX-36837
FUNCTION get_carequality_patient_has_consent(vpatient numeric) RETURN numeric IS
	v_PatientHasConsent NUMBER := 0;
BEGIN
	BEGIN
		SELECT COUNT(1) INTO v_PatientHasConsent
		FROM
			SYSOPTS S,
			CONTRACT C
		WHERE
			S."Name" = 'CQ_PatientConsent'
			AND C."Deleted" = 0
			AND C."Denied" = 0
			AND (C."ExpiryDate" IS NULL OR C."ExpiryDate" >= TRUNC(SYSDATE))
			AND C."Patient" = vPatient
			AND TRIM(S."Value") = TRIM(C."Consent");
    EXCEPTION
    	WHEN NO_DATA_FOUND THEN
            v_PatientHasConsent := 0;
    END;

    return v_PatientHasConsent;
END;


END;
CREATE OR REPLACE PACKAGE BODY ccda_cfg_pkg IS



  -- make sure this directory exists before running the export!

  FUNCTION getexportdir() RETURN character varying IS 

    vExportDir  VARCHAR2(255);

	 v_nCount		NUMBER := 0;								-- AX-26071.2



  BEGIN



		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetExportDir');

		IF v_nCount > 0 THEN

		  -- custom package function exists 

		  EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetExportDir FROM DUAL' INTO vExportDir;

		  RETURN vExportDir;

		END IF;

	

    vExportDir := 'CCDA_EXPORT_DIR';

    RETURN vExportDir;

  END;



  FUNCTION getpracticeid(vpid numeric, vuserid numeric, vstationid numeric) RETURN numeric IS

  

    vResult NUMBER := 0;

	 v_nCount		NUMBER := 0;								-- AX-26071.2

    

  BEGIN



		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetPracticeId');

		IF v_nCount > 0 THEN

		  -- custom package function exists 

		  EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetPracticeId('||vPId||', '||vUserId||', '||vStationId||') FROM DUAL' INTO vResult;

		  RETURN vResult;

		END IF;

	

    -- this is a stub

    SELECT "Id" INTO vResult FROM PRACTICE WHERE ROWNUM = 1;

    

    RETURN vResult;

  

  END;



  --E143263.3 added optional 2nd parameter

  FUNCTION getpatientidentifier(vpid numeric, vbshowinfo boolean DEFAULT true) RETURN character varying IS

    vResult  VARCHAR2(30);

	 v_nCount		NUMBER := 0;								-- AX-26071.2

  BEGIN

  

		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetPatientIdentifier');

		IF v_nCount > 0 THEN

		  -- custom package function exists 

		  EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetPatientIdentifier(:1, :2) FROM DUAL' INTO vResult

						USING vPId, vbShowInfo;

		  RETURN vResult;

		END IF;

	

	 --E143263.3 

	 IF  NOT vbShowInfo THEN

  		vResult := 'UNK';

	 ELSE

		-- currently SSN

		SELECT TRIM("Sin") into vResult FROM PATIENT WHERE "Patient" = vPId;

    

		IF vResult IS NULL THEN -- B142580

    		vResult := 'UNK';

		END IF;

	END IF;

    

    return vResult;

  END;



  FUNCTION getpatientidentifiertype() RETURN character varying IS

    vResult  VARCHAR2(100);

	 v_nCount		NUMBER := 0;								-- AX-26071.2

  BEGIN



		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetPatientIdentifierType');

		IF v_nCount > 0 THEN

		  -- custom package function exists 

		  EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetPatientIdentifierType FROM DUAL' INTO vResult;

		  RETURN vResult;

		END IF;

	

    -- currently SSN

    vResult := '2.16.840.1.113883.4.1';

    return vResult;

  END;

  

  

	--E143263.3 added optional 2nd parameter

	FUNCTION getuseridentifier(vuserid numeric, vbshowinfo boolean DEFAULT true) RETURN character varying IS

		vResult  VARCHAR2(30);

		vType NUMBER;

	   v_nCount		NUMBER := 0;								-- AX-26071.2

	BEGIN



		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetUserIdentifier');

		IF v_nCount > 0 THEN

		  -- custom package function exists 

		  EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetUserIdentifier(:1, :2) FROM DUAL' INTO vResult

							USING vUserId, vbShowInfo;

		  RETURN vResult;

		END IF;

	

		-- currently NPI

		--E143263.3 

		IF  NOT vbShowInfo THEN

			vResult := 'UNK';

		ELSE

			BEGIN

				SELECT "Type" INTO vType FROM USER_VIEW WHERE "User" = vUserId;



				IF vType = 0 THEN

					BEGIN

						SELECT NVL(TRIM(P."NPI"), 'UNK') into vResult FROM USERS U, PRODUCER P  WHERE U."Producer" = P."Producer" and U."User" = vUserId;



					EXCEPTION WHEN NO_DATA_FOUND THEN

						vResult := 'UNK';

					END;

				ELSE -- patient won't have NPI

					vResult := 'NA';

				END IF;

			

			EXCEPTION WHEN NO_DATA_FOUND THEN

				vResult := 'UNK';

			END;

		END IF;



		return vResult;

	END;

  

  FUNCTION getuseridentifiertype() RETURN character varying IS

      vResult  VARCHAR2(100);

	   v_nCount		NUMBER := 0;								-- AX-26071.2

  BEGIN



		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetUserIdentifierType');

		IF v_nCount > 0 THEN

		  -- custom package function exists 

		  EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetUserIdentifierType FROM DUAL' INTO vResult;

		  RETURN vResult;

		END IF;

	

    -- currently NPI

    vResult := '2.16.840.1.113883.4.6';

    return vResult;

  END;

  

  FUNCTION getracecode(vustype numeric) RETURN character varying IS

    vResult  VARCHAR2(10);

	   v_nCount		NUMBER := 0;								-- AX-26071.2



  BEGIN



		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetRaceCode');

		IF v_nCount > 0 THEN

		  -- custom package function exists 

		  EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetRaceCode('||vUSType||') FROM DUAL' INTO vResult;

		  RETURN vResult;

		END IF;



    IF vUSType = 0 THEN

      vResult := '1002-5';

    ELSIF vUSType = 1 THEN

      vResult := '2028-9';

    ELSIF vUSType = 2 THEN

      vResult := '2054-5';

    ELSIF vUSType = 3 THEN

      vResult := '2076-8';

    ELSIF vUSType = 4 THEN

      vResult := '2106-3';

    END IF;

    

    return vResult;

  END;

  

  FUNCTION getethniccode(vustype numeric) RETURN character varying IS

    vResult  VARCHAR2(10);

	   v_nCount		NUMBER := 0;								-- AX-26071.2

  BEGIN



		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetEthnicCode');

		IF v_nCount > 0 THEN

		  -- custom package function exists 

		  EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetEthnicCode('||vUSType||') FROM DUAL' INTO vResult;

		  RETURN vResult;

		END IF;



    IF vUSType = 0 THEN

      vResult := '2135-2';

    ELSIF vUSType = 1 THEN

      vResult := '2186-5';

    END IF;

    

    return vResult;

  END;



	-- Encounters - a list of all historical appointments for the patient, and their encounter diagnoses.

	--  Rncounter diagnoses are those medical problems which were added on the date of the appointment and

	--  tagged with a special code in their Note field.

	-- AX-18945.19095

	FUNCTION getencounterssection(vpid numeric, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob IS

		-- clobs

		vResult CLOB := '';

		vText CLOB := '';

		vEntries CLOB := '';

		

		vHasAppt NUMBER := 0; -- counter for appts

		

		-- cursor of historical appointments (including the ones for today)

		CURSOR curAppts IS

			SELECT AP."Date",

				AP."From",

				htf.escape_sc(AP."Reason") AS "Reason",

				CL."Description",

				AP."Appointment"

			FROM APPOINT AP, CLINIC CL

			WHERE 1=1

				AND AP."Patient" = vPId

				AND AP."Status" = 0

				AND AP."Type" IN (0, 1, 2)

				AND AP."Date" <= TRUNC(SYSDATE)

				AND AP."Clinic" = CL."Clinic"

				-- AX-18945.19095

			AND 

			(

				(vDate1 IS NOT NULL AND vDate2 IS NOT NULL

					AND AP."Date" >= TRUNC(vDate1) 

					AND (AP."Date" = TRUNC(vDate1) AND AP."From" >= TRUNC(TO_CHAR(vDate1, 'SSSSS') / 60) OR (AP."Date" <> TRUNC(vDate1)))

					AND AP."Date" <= TRUNC(vDate2) 

					AND (AP."Date" = TRUNC(vDate2) AND AP."From" <= TRUNC(TO_CHAR(vDate2, 'SSSSS') / 60) OR (AP."Date" <> TRUNC(vDate2)))

					)



				OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 

					AND AP."Date" >= TRUNC(vDate1) 

					AND (AP."Date" = TRUNC(vDate1) AND AP."From" >= TRUNC(TO_CHAR(vDate1, 'SSSSS') / 60) OR (AP."Date" <> TRUNC(vDate1)))

					)

				OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0

					AND AP."Date" <= TRUNC(vDate1) 

					AND (AP."Date" = TRUNC(vDate1) AND AP."From" <= TRUNC(TO_CHAR(vDate1, 'SSSSS') / 60) OR (AP."Date" <> TRUNC(vDate1)))

					)

				OR (vDate1 IS NULL) 

			)	

			ORDER BY AP."Date", AP."From";

		

		

		vEncounterDiagNoteTag  VARCHAR2(4) := '[ED]'; -- tag that must be present in the notes of a medical problem for it to be considered an encounter diagnosis

		vEncounterDiagApptNoteTag  VARCHAR2(4) := '[SD]'; -- tag that must be present in the notes of an appointment for it to be considered an encounter diagnosis

		vEncounterDiagString  VARCHAR2(4000) := NULL; -- display string for the encounter diagnoses in the text section

		vEncounterDiags NUMBER := 0; -- counter for encounter diagnoses

		

		-- cursor of encounter diagnoses for an appointment date

		CURSOR curEncounterDiags (cpApptDate IN DATE) IS 

			SELECT 

				PA."Description",

				PA."SNOCode",

				PA."AddDateTime",

				PA."OnsetDate"

			FROM PTALERT PA

			WHERE 1=1

				AND PA."Patient" = vPId

				AND PA."AlertType" = 2

				AND PA."Deleted" = 0

				AND PA."Note" LIKE '%' || vEncounterDiagNoteTag || '%'

				AND TRUNC(PA."AddDateTime") = TRUNC(cpApptDate);



		-- AX-21879b

		CURSOR curEncounterApptNoteDiags (cpAppt IN APPOINT."Appointment"%TYPE) IS 

			SELECT * FROM REQNOTE RN, SNOCODE S

			WHERE 1=1

				AND RN."Appointment" = cpAppt

				AND RN."Note" LIKE '%' || vEncounterDiagApptNoteTag || '%'

				AND TRIM(S."SNOCode") = SUBSTR(RN."Note", 6); -- compare everything after "[SD] "



	   v_nCount		NUMBER := 0;								-- AX-26071.2

	

	BEGIN



		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetEncountersSection');

		IF v_nCount > 0 THEN

		  -- custom package function exists; AX-27290

		  EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetEncountersSection(:1, :2, :3, :4) FROM DUAL' INTO vResult

					USING vPId, vIsDateFrom, vDate1, vDate2;

		  RETURN vResult;

		END IF;





		dbms_lob_s.createtemporary (vResult, TRUE);

		dbms_lob_s.createtemporary (vText, TRUE);

		dbms_lob_s.createtemporary (vEntries, TRUE);



		-- section header

		-- AX-18696.19077

		dbms_lob_s.append(vResult, '

			<component>

				<section>

					<!-- *** Encounters section (entries required) (V3) *** -->

					<templateId root="2.16.840.1.113883.10.20.22.2.22.1" extension="2015-08-01"/>

					<templateId root="2.16.840.1.113883.10.20.22.2.22.1"/>

					<code code="46240-8" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="History of encounters"/>

					<title>Encounters</title>');

         

		FOR cAppt IN curAppts LOOP

			-- setup the text section

			IF vHasAppt = 0 THEN 		

					dbms_lob_s.append(vText, '

						<text>

						<table border="1">

							<thead>

								<tr>

									<th colspan="5">Past/Current Appointments</th>

								</tr>

								<tr>

									<th>Clinic</th>

									<th>Date</th>

									<th>Time</th>

									<th>Reason</th>

									<th>Encounter Diagnoses</th>

								</tr>

							</thead>

							<tbody>');

			

			

			END IF;

		

			vHasAppt := vHasAppt + 1; 

			vEncounterDiagString := NULL; -- reset encounter diag

			

			FOR cEncounterDiag IN curEncounterDiags( cAppt."Date" ) LOOP

				IF vEncounterDiagString IS NULL THEN

					vEncounterDiagString := vEncounterDiagString || cEncounterDiag."Description";

				ELSE

					vEncounterDiagString := vEncounterDiagString || ', ' || cEncounterDiag."Description";

				END IF;

			END LOOP;



			-- AX-21879b

			FOR cApptNoteDiag IN curEncounterApptNoteDiags( cAppt."Appointment" ) LOOP

				vEncounterDiagString := htf.escape_sc(TRIM(cApptNoteDiag."Description"));

			END LOOP;

						

			-- text section

			dbms_lob_s.append(vText, '

								<tr>

									<td>' || htf.escape_sc(TRIM(cAppt."Description")) || '</td>

									<td>' || TO_CHAR(cAppt."Date", 'MM/DD/YYYY') || '</td>

									<td>' || FLOOR(cAppt."From"/60) || ':'|| LPAD(MOD(cAppt."From", 60), 2, '0') || '</td>

									<td>' || TRIM(cAppt."Reason") || '</td>

									<td>' || htf.escape_sc(vEncounterDiagString) || '</td>

								</tr>');	

			-- coded section

			-- encounter header

			-- AX-18696.19077

			dbms_lob_s.append(vEntries, '

					<entry typeCode="DRIV">

						<!-- Encounter Activities -->

						<encounter classCode="ENC" moodCode="EVN">

							<!-- ** Encounter Activity (V3) ** -->

							<templateId root="2.16.840.1.113883.10.20.22.4.49" extension="2015-08-01"/>

							<templateId root="2.16.840.1.113883.10.20.22.4.49"/>

							<id root="2.16.840.1.113883.4.8155" />

							<code code="99234" displayName="Observation or Inpatient Hospital care" codeSystemName="CPT-4" codeSystem="2.16.840.1.113883.6.12">

								<translation code="IMP" codeSystem="2.16.840.1.113883.5.4" displayName="Inpatient" codeSystemName="HL7 ActEncounterCode" />

							</code>

							<effectiveTime value="' || TO_CHAR(cAppt."Date", 'YYYYMMDD') ||'"/>

							<entryRelationship typeCode="SUBJ">

								<act classCode="ACT" moodCode="EVN">

									<!-- ** Encounter Diagnosis (V3)** -->

									<templateId root="2.16.840.1.113883.10.20.22.4.80" extension="2015-08-01"/>

									<templateId root="2.16.840.1.113883.10.20.22.4.80"/>  

									<id root="2.16.840.1.113883.4.8155" />

									<code xsi:type="CE" 

										code="29308-4"

										codeSystem="2.16.840.1.113883.6.1" 

										codeSystemName="LOINC"

										displayName="ENCOUNTER DIAGNOSIS"/>

									<effectiveTime>

										<low value="' || TO_CHAR(cAppt."Date", 'YYYYMMDD') ||'"/>

									</effectiveTime>');

			

			-- add each encounter diagnosis

			vEncounterDiags := 0;

			

			FOR cEncounterDiag IN curEncounterDiags( cAppt."Date" ) LOOP

				vEncounterDiags := vEncounterDiags + 1;

				

				-- AX-18696.19077

				dbms_lob_s.append(vEntries, '

									<entryRelationship typeCode="SUBJ" inversionInd="false">

										<!-- Problem Observation (V3) -->

										<observation classCode="OBS" moodCode="EVN">

											<templateId root="2.16.840.1.113883.10.20.22.4.4" extension="2015-08-01"/>

											<templateId root="2.16.840.1.113883.10.20.22.4.4"/>

											<id root="2.16.840.1.113883.4.8155" />

											<code code="404684003" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" displayName="Complaint">

												<translation code="75321-0" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Clinical finding"/>

											</code>

											<statusCode code="completed"/>

											<effectiveTime>

												<low value="' || TO_CHAR(NVL(cEncounterDiag."OnsetDate", cEncounterDiag."AddDateTime"), 'YYYYMMDD') || '"/>

											</effectiveTime>

											<value xsi:type="CD" code="' || TRIM(cEncounterDiag."SNOCode") || '" codeSystem="2.16.840.1.113883.6.96" 

												codeSystemName="SNOMED CT" displayName="' || htf.escape_sc(TRIM(cEncounterDiag."Description")) || '"/>

										</observation>

									</entryRelationship>');									

			END LOOP;



			-- AX-21879b

			FOR cApptNoteDiag IN curEncounterApptNoteDiags( cAppt."Appointment" ) LOOP

				vEncounterDiags := vEncounterDiags + 1;



				dbms_lob_s.append(vEntries, '

									<entryRelationship typeCode="SUBJ" inversionInd="false">

										<!-- Problem Observation (V3) -->

										<observation classCode="OBS" moodCode="EVN">

											<templateId root="2.16.840.1.113883.10.20.22.4.4" extension="2015-08-01"/>

											<templateId root="2.16.840.1.113883.10.20.22.4.4"/>

											<id root="2.16.840.1.113883.4.8155" />

											<code code="404684003" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" displayName="Complaint">

												<translation code="75321-0" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Clinical finding"/>

											</code>

											<statusCode code="completed"/>

											<effectiveTime>

												<low value="' || TO_CHAR(cApptNoteDiag."Date", 'YYYYMMDD') || '"/>

											</effectiveTime>

											<value xsi:type="CD" code="' || TRIM(cApptNoteDiag."SNOCode") || '" codeSystem="2.16.840.1.113883.6.96" 

												codeSystemName="SNOMED CT" displayName="' || htf.escape_sc(TRIM(cApptNoteDiag."Description")) || '"/>

										</observation>

									</entryRelationship>');									

			END LOOP;

			

			IF vEncounterDiags = 0 THEN

				-- handle case where there is no encounter diagnosis

				-- AX-18696.19077

				dbms_lob_s.append(vEntries, '

									<entryRelationship typeCode="SUBJ" inversionInd="false">

										<!-- Problem Observation (V3) -->

										<observation classCode="OBS" moodCode="EVN">

											<templateId root="2.16.840.1.113883.10.20.22.4.4" extension="2015-08-01"/>

											<templateId root="2.16.840.1.113883.10.20.22.4.4"/>

											 <id root="2.16.840.1.113883.4.8155" />

											<code code="ASSERTION" codeSystem="2.16.840.1.113883.5.4" codeSystemName="HL7ActCode">

												<translation code="75321-0" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Clinical finding"/>

											</code>

											<statusCode code="completed" /> 

											<effectiveTime>

												<low nullFlavor="NA"/>

											</effectiveTime>

											<value xsi:type="CD" 

												code="55607006" 

												codeSystem="2.16.840.1.113883.6.96" 

												codeSystemName="SNOMED CT" 

												displayName="Problem" /> 

										</observation>

									</entryRelationship>');

			

			END IF;

									

			-- encounter footer						

			dbms_lob_s.append(vEntries, '						

								</act>

							</entryRelationship>

						</encounter>

					</entry>');

							

		END LOOP;



		IF vHasAppt = 0 THEN -- the patient has no historical appointments

			-- text section

			dbms_lob_s.append(vText, '

					<text>No past encounters.</text>');

			-- AX-18945.19094d

				dbms_lob_s.append(vEntries, '

						<entry typeCode="DRIV">

						<!-- Encounter Activities -->

						<encounter classCode="ENC" moodCode="EVN">

							<!-- ** Encounter Activity (V3) ** -->

							<templateId root="2.16.840.1.113883.10.20.22.4.49" extension="2015-08-01"/>

							<templateId root="2.16.840.1.113883.10.20.22.4.49"/>

							<id root="2.16.840.1.113883.4.8155" />

							<code code="ASSERTION" displayName="Observation or Inpatient Hospital care" codeSystemName="CPT-4" codeSystem="2.16.840.1.113883.6.12">

								<translation code="IMP" codeSystem="2.16.840.1.113883.5.4" displayName="Inpatient" codeSystemName="HL7 ActEncounterCode" />

							</code>

							<effectiveTime>

								<low nullFlavor="NA"/>

							</effectiveTime>

							<entryRelationship typeCode="SUBJ" inversionInd="false">

								<!-- Problem Observation (V3) -->

								<observation classCode="OBS" moodCode="EVN">

									<templateId root="2.16.840.1.113883.10.20.22.4.4" extension="2015-08-01"/>

									<templateId root="2.16.840.1.113883.10.20.22.4.4"/>

									 <id root="2.16.840.1.113883.4.8155" />

									<code code="ASSERTION" codeSystem="2.16.840.1.113883.5.4" codeSystemName="HL7ActCode">

										<translation code="75321-0" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Clinical finding"/>

									</code>

									<statusCode code="completed" /> 

									<effectiveTime>

										<low nullFlavor="NA"/>

									</effectiveTime>

									<value xsi:type="CD" 

										code="55607006" 

										codeSystem="2.16.840.1.113883.6.96" 

										codeSystemName="SNOMED CT" 

										displayName="Problem" /> 

								</observation>

							</entryRelationship>

						</encounter>

					</entry>

				');	

		

		ELSE

			-- end the text section

			dbms_lob_s.append(vText, '

							</tbody>

						</table>

					</text>');

		END IF;



		-- put it all together

		dbms_lob_s.append(vResult, vText);

		dbms_lob_s.append(vResult, vEntries);

		

		-- section footer

		dbms_lob_s.append(vResult, '

				</section>

			</component>

			');



		-- return result

		return vResult;

	END;







	-- E142539 - satisfies smoking status requirement. See E136707

	-- AX-18945.19095

	FUNCTION getsocialhistorysection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob IS

		vResult CLOB := '';

		vText CLOB := '';

		vEntries CLOB := '';

		vGender  VARCHAR2(4000) := ''; -- AX-21637

		vHadProb NUMBER := 0;

		vHadGender NUMBER := 0;			-- AX-21637



		-- AX-18696.19020

		vPtSex NUMBER := 0;					

		vbHasTextElement BOOLEAN := false;

		

		CURSOR curSmokingProb IS

		SELECT  PA."Description", PA."OnsetDate", PA."Note", PA."SNOCode", PA."AddDateTime"

		FROM PTALERT PA 

		WHERE 1=1 

			AND PA ."AlertType" = 2 

			AND PA ."Deleted" = 0 

			AND PA ."Status" = 0

			AND PA ."Patient" = vPId

			AND PA ."SNOCode" IN ('449868002', '428041000124106', '8517006', '266919005', '77176002', '266927001', '428071000124103', '428061000124105')

			-- AX-18945.19095

			AND 

			(

				(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND PA."AddDateTime" >= vDate1 AND PA."AddDateTime" <= vDate2)

				OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND PA."AddDateTime" >= vDate1)

				OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND PA."AddDateTime" <= vDate1) 

				OR (vDate1 IS NULL)

			)

			AND ROWNUM = 1;



		-- AX-21637

		CURSOR curGender IS

			SELECT G.* 

			FROM PTGENDER G, AUDITHIS A

			WHERE 1=1

				AND G."Patient" = vPId 

				AND G."Audit" = A."Audit"

				AND 

				(

					(vDate1 IS NOT NULL AND vDate2 IS NOT NULL

						AND A."Date" >= TRUNC(vDate1) 

						AND (A."Date" = TRUNC(vDate1) AND A."Time" >= TRUNC(TO_CHAR(vDate1, 'SSSSS') / 60) OR (A."Date" <> TRUNC(vDate1)))

						AND A."Date" <= TRUNC(vDate2) 

						AND (A."Date" = TRUNC(vDate2) AND A."Time" <= TRUNC(TO_CHAR(vDate2, 'SSSSS') / 60) OR (A."Date" <> TRUNC(vDate2)))

						)



					OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 

						AND A."Date" >= TRUNC(vDate1) 

						AND (A."Date" = TRUNC(vDate1) AND A."Time" >= TRUNC(TO_CHAR(vDate1, 'SSSSS') / 60) OR (A."Date" <> TRUNC(vDate1)))

						)

					OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0

						AND A."Date" <= TRUNC(vDate1) 

						AND (A."Date" = TRUNC(vDate1) AND A."Time" <= TRUNC(TO_CHAR(vDate1, 'SSSSS') / 60)) OR (A."Date" <> TRUNC(vDate1))

						)

					OR (vDate1 IS NULL) 

				)

			ORDER BY A."Audit" DESC;



	   v_nCount		NUMBER := 0;								-- AX-26071.2



	BEGIN



		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetSocialHistorySection');

		IF v_nCount > 0 THEN

		  -- custom package function exists; AX-27290

		  EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetSocialHistorySection(:1, :2, :3, :4, :5) FROM DUAL' INTO vResult

							USING vPId, vbShowInfo, vIsDateFrom, vDate1, vDate2;

		  RETURN vResult;

		END IF;





		dbms_lob_s.createtemporary (vResult, TRUE);

		dbms_lob_s.createtemporary (vText, TRUE);

		dbms_lob_s.createtemporary (vEntries, TRUE);



		dbms_lob_s.append(vResult, '

			<component>

			  <section>

			    <templateId root="2.16.840.1.113883.10.20.22.2.17" extension="2015-08-01"/>

				<templateId root="2.16.840.1.113883.10.20.22.2.17"/>

			    <!--  ********  Social history section template   ******** -->

			    <code code="29762-2" codeSystem="2.16.840.1.113883.6.1" displayName="Social History"/>

			    <title>Social History</title>');

         



		IF vbShowInfo THEN												--E143263.4

			FOR cSmokingStatus IN curSmokingProb LOOP

				vHadProb := 1;

				

				-- AX-18696.19020

				IF vbHasTextElement = false THEN

					vbHasTextElement := true;

					dbms_lob_s.append(vText, '

						<text>

						');

				END IF;



				-- text

				dbms_lob_s.append(vText, '

							<table border="1" width="100%">

								<thead>

									<tr>

										<th>Smoking Status</th>

										<th>Onset Date</th>

									</tr>

								</thead>

								<tbody>

									<tr>

										<td>' || htf.escape_sc(TRIM(cSmokingStatus."Description")) || '</td>

										<td>' || TO_CHAR(NVL(cSmokingStatus."OnsetDate", cSmokingStatus."AddDateTime"), 'MM/DD/YYYY') || '</td>

									</tr>

								</tbody>

							</table>');

						--</text>'); -- AX-18696.19020

						

				-- entry

				-- AX-18696.19066

				dbms_lob_s.append(vEntries, '

							 <entry>

						  <observation classCode="OBS" moodCode="EVN">

							  <!-- Smoking status observation template -->

							  <templateId root="2.16.840.1.113883.10.20.22.4.78" extension="2014-06-09"/>

							  <templateId root="2.16.840.1.113883.10.20.22.4.78"/>

							  <id root="2.16.840.1.113883.4.8155" />

							  <code code="72166-2" codeSystem="2.16.840.1.113883.6.1"/>

							  <statusCode code="completed"/>

							  <effectiveTime xsi:type="IVL_TS" value="' ||  TO_CHAR(NVL(cSmokingStatus."OnsetDate", cSmokingStatus."AddDateTime"), 'YYYYMMDD') || '" />

							  <value xsi:type="CD" code="' || TRIM(cSmokingStatus."SNOCode") || '" displayName="' || htf.escape_sc(TRIM(cSmokingStatus."Description")) || '"

							codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT"/>

						  </observation>

							 </entry>

					');

			END LOOP;

			

			IF vHadProb = 0 THEN --case when the patient didn't have any smoking status problems on file



				-- text

				dbms_lob_s.append(vText, '

						<text>

							<table border="1" width="100%">

								<thead>

									<tr>

										<th>Smoking Status</th>

									</tr>

								</thead>

								<tbody>

									<tr>

										<td>Unknown if ever smoked.</td>

									</tr>

								</tbody>

							</table>');

						--</text>'); -- AX-18696.19020

			

				-- entry

				-- AX-18696.19066

				dbms_lob_s.append(vEntries, '

				       <entry>

					  <observation classCode="OBS" moodCode="EVN">

					     <!-- Smoking status observation template -->

							<templateId root="2.16.840.1.113883.10.20.22.4.78" extension="2014-06-09"/>

							<templateId root="2.16.840.1.113883.10.20.22.4.78"/>

							<id root="2.16.840.1.113883.4.8155" />

							<code code="72166-2" codeSystem="2.16.840.1.113883.6.1"/>

					     <statusCode code="completed"/>

					     <effectiveTime xsi:type="IVL_TS" nullFlavor="UNK"/>

					     <value xsi:type="CD" code="266927001" displayName="Unknown if ever smoked."

						codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT"/>

					  </observation>

				       </entry>

				');

				

			END IF;



			-- AX-18696.19020

			SELECT "Sex" INTO vPtSex FROM PATIENT WHERE "Patient" = vPId;

			

			IF vPtSex = 1 OR vPtSex = 2 THEN



				-- text

				dbms_lob_s.append(vText, '

							<table border="1" width="100%">

								<thead>

									<tr>

										<th>Sex Assigned At Birth</th>

									</tr>

								</thead>

								<tbody>

									<tr>

									');



				IF vPtSex = 2 THEN

					dbms_lob_s.append(vText, '<td> Female </td>');

				ELSE

					dbms_lob_s.append(vText, '<td> Male </td>');

				END IF;



				dbms_lob_s.append(vText, '

									</tr>

								</tbody>

							</table>

						');

						

				-- entry

				dbms_lob_s.append(vEntries, '

				<!-- Add Birth Sex entry -->

				<entry>

					<observation classCode="OBS" moodCode="EVN">

					  <templateId root="2.16.840.1.113883.10.20.22.4.200" extension="2016-06-01"/>

					  <templateId root="2.16.840.1.113883.10.20.22.4.200"/>

					  <code code="76689-9" codeSystem="2.16.840.1.113883.6.1" displayName="Sex Assigned At Birth"/>

					  <statusCode code="completed"/>

				');



				IF vPtSex = 2 THEN

					dbms_lob_s.append(vEntries, '<value xsi:type="CD" codeSystem="2.16.840.1.113883.5.1" codeSystemName="AdministrativeGender" code="F" displayName="Female">');

				ELSE

					dbms_lob_s.append(vEntries, '<value xsi:type="CD" codeSystem="2.16.840.1.113883.5.1" codeSystemName="AdministrativeGender" code="M" displayName="Male">');

				END IF;



				dbms_lob_s.append(vEntries, '

						</value>

					</observation>

				</entry>

				');



			ELSE



				-- AX-18945.19094c

				-- text

				dbms_lob_s.append(vText, '

							<table border="1" width="100%">

								<thead>

									<tr>

										<th>Sex Assigned At Birth</th>

									</tr>

								</thead>

								<tbody>

									<tr>

									');



				dbms_lob_s.append(vText, '<td> Unknown </td>');



				dbms_lob_s.append(vText, '

									</tr>

								</tbody>

							</table>

						');



				-- entry

				dbms_lob_s.append(vEntries, '

					<!-- Birth Sex observation template -->

					<entry>

						<observation classCode="OBS" moodCode="EVN">

						  <templateId root="2.16.840.1.113883.10.20.22.4.200" extension="2016-06-01"/>

						  <templateId root="2.16.840.1.113883.10.20.22.4.200"/>

						  <code code="76689-9" codeSystem="2.16.840.1.113883.6.1"/>

						  <statusCode code="completed"/>

					     <value xsi:type="CD" nullFlavor="UNK"/>

						</observation>

					</entry>

					');

			END IF;



			-- AX-21637 - Gender Identity / Sexual Orientation...

			vHadGender := 0;

			FOR recGender IN curGender LOOP

				

				vHadGender := 1;

				IF recGender."PtGDeclined" > 0 OR recGender."PtGenderId" > 0 OR recGender."PtGOther" IS NOT NULL THEN



					-- text

					dbms_lob_s.append(vText, '

								<table border="1" width="100%">

									<thead>

										<tr>

											<th>Gender Identity</th>

										</tr>

									</thead>

									<tbody>

										<tr>

										');





					IF recGender."PtGDeclined" > 0 THEN

						dbms_lob_s.append(vText, '<td> Choose not to disclose </td>');	

					ELSE

						IF BITAND(recGender."PtGenderId", 1) = 1 THEN

							vGender := 'Male';

						END IF;



						IF BITAND(recGender."PtGenderId", 2) = 2 THEN

							if LENGTH(vGender) > 0 THEN

								vGender := vGender || ', ';

							END IF;

							vGender := vGender || 'Female';

						END IF;



						IF BITAND(recGender."PtGenderId", 4) = 4 THEN

							IF LENGTH(vGender) > 0 THEN

								vGender := vGender || ', ';

							END IF;

							vGender := vGender || 'Transgender Male';

						END IF;



						IF BITAND(recGender."PtGenderId", 8) = 8 THEN

							if LENGTH(vGender) > 0 THEN

								vGender := vGender || ', ';

							END IF;

							vGender := vGender || 'Transgender Female';

						END IF;



						IF BITAND(recGender."PtGenderId", 16) = 16 THEN

							if LENGTH(vGender) > 0 THEN

								vGender := vGender || ', ';

							END IF;

							vGender := vGender || 'Genderqueer';

						END IF;



						IF recGender."PtGOther" IS NOT NULL THEN

							if LENGTH(vGender) > 0 THEN

								vGender := vGender || ', ';

							END IF;

							vGender := vGender || TRIM(recGender."PtGOther");

						END IF;



						dbms_lob_s.append(vText, '<td> ' || vGender || ' </td>');



					END IF;

					

					dbms_lob_s.append(vText, '

										</tr>

									</tbody>

								</table>

							');



					IF recGender."PtGenderId" > 0 THEN

						IF BITAND(recGender."PtGenderId", 1) = 1 THEN

							-- entry

							dbms_lob_s.append(vEntries, '

							<!-- Add Gender Identity entry -->

							<entry>

								<observation classCode="OBS" moodCode="EVN">

									<templateId root="2.16.840.1.113883.10.20.22.4.38"/>

									<id root="2.16.840.1.113883.4.8155" />

									<code code="76691-5" codeSystem="2.16.840.1.113883.6.1" displayName="Gender Identity"/>

									<statusCode code="completed"/>

									<value xsi:type="CD" codeSystem="2.16.840.1.114222.4.11.756" codeSystemName="Gender Identity" code="446151000124109" displayName="Male">

									</value>

								</observation>

							</entry>

							');

						END IF;



						IF BITAND(recGender."PtGenderId", 2) = 2 THEN

							-- entry

							dbms_lob_s.append(vEntries, '

							<!-- Add Gender Identity entry -->

							<entry>

								<observation classCode="OBS" moodCode="EVN">

									<templateId root="2.16.840.1.113883.10.20.22.4.38"/>

									<id root="2.16.840.1.113883.4.8155" />

									<code code="76691-5" codeSystem="2.16.840.1.113883.6.1" displayName="Gender Identity"/>

									<statusCode code="completed"/>

									<value xsi:type="CD" codeSystem="2.16.840.1.114222.4.11.756" codeSystemName="Gender Identity" code="446141000124107" displayName="Female">

									</value>

								</observation>

							</entry>

							');

						END IF;



						IF BITAND(recGender."PtGenderId", 4) = 4 THEN

							-- entry

							dbms_lob_s.append(vEntries, '

							<!-- Add Gender Identity entry -->

							<entry>

								<observation classCode="OBS" moodCode="EVN">

									<templateId root="2.16.840.1.113883.10.20.22.4.38"/>

									<id root="2.16.840.1.113883.4.8155" />

									<code code="76691-5" codeSystem="2.16.840.1.113883.6.1" displayName="Gender Identity"/>

									<statusCode code="completed"/>

									<value xsi:type="CD" codeSystem="2.16.840.1.114222.4.11.756" codeSystemName="Gender Identity" code="407377005" displayName="Transgender Male">

									</value>

								</observation>

							</entry>

							');

						END IF;



						IF BITAND(recGender."PtGenderId", 8) = 8 THEN

							-- entry

							dbms_lob_s.append(vEntries, '

							<!-- Add Gender Identity entry -->

							<entry>

								<observation classCode="OBS" moodCode="EVN">

									<templateId root="2.16.840.1.113883.10.20.22.4.38"/>

									<id root="2.16.840.1.113883.4.8155" />

									<code code="76691-5" codeSystem="2.16.840.1.113883.6.1" displayName="Gender Identity"/>

									<statusCode code="completed"/>

									<value xsi:type="CD" codeSystem="2.16.840.1.114222.4.11.756" codeSystemName="Gender Identity" code="407376001" displayName="Transgender Female">

									</value>

								</observation>

							</entry>

							');	

						END IF;



						IF BITAND(recGender."PtGenderId", 16) = 16 THEN

							-- entry

							dbms_lob_s.append(vEntries, '

							<!-- Add Gender Identity entry -->

							<entry>

								<observation classCode="OBS" moodCode="EVN">

									<templateId root="2.16.840.1.113883.10.20.22.4.38"/>

									<id root="2.16.840.1.113883.4.8155" />

									<code code="76691-5" codeSystem="2.16.840.1.113883.6.1" displayName="Gender Identity"/>

									<statusCode code="completed"/>

									<value xsi:type="CD" codeSystem="2.16.840.1.114222.4.11.756" codeSystemName="Gender Identity" code="446131000124102" displayName="Genderqueer">

									</value>

								</observation>

							</entry>

							');	

						END IF;

					ELSIF

						recGender."PtGDeclined" > 0 THEN

							-- entry

							dbms_lob_s.append(vEntries, '

							<!-- Add Gender Identity entry -->

							<entry>

								<observation classCode="OBS" moodCode="EVN">

									<templateId root="2.16.840.1.113883.10.20.22.4.38"/>

									<id root="2.16.840.1.113883.4.8155" />

									<code code="76691-5" codeSystem="2.16.840.1.113883.6.1" displayName="Gender Identity"/>

									<statusCode code="completed"/>

									<value xsi:type="CD" nullFlavor="ASKU"/>

								</observation>

							</entry>

							');

					ELSIF

						recGender."PtGOther" IS NOT NULL THEN

							-- entry

							dbms_lob_s.append(vEntries, '

							<!-- Add Gender Identity entry -->

							<entry>

								<observation classCode="OBS" moodCode="EVN">

									<templateId root="2.16.840.1.113883.10.20.22.4.38"/>

									<id root="2.16.840.1.113883.4.8155" />

									<code code="76691-5" codeSystem="2.16.840.1.113883.6.1" displayName="Gender Identity"/>

									<statusCode code="completed"/>

									<value xsi:type="CD" nullFlavor="OTH"/>

								</observation>

							</entry>

							');

					END IF;

	

				ELSE

					-- text

					dbms_lob_s.append(vText, '

								<table border="1" width="100%">

									<thead>

										<tr>

											<th>Gender Identity</th>

										</tr>

									</thead>

									<tbody>

										<tr>

										');



					dbms_lob_s.append(vText, '<td> Unknown </td>');



					dbms_lob_s.append(vText, '

										</tr>

									</tbody>

								</table>

							');



					-- entry

					dbms_lob_s.append(vEntries, '

						<!-- Gender Identity observation template -->

						<entry>

							<observation classCode="OBS" moodCode="EVN">

							  <templateId root="2.16.840.1.113883.10.20.22.4.38"/>

							  <id root="2.16.840.1.113883.4.8155" />

							  <code code="76691-5" codeSystem="2.16.840.1.113883.6.1" displayName="Gender Identity"/>

							  <statusCode code="completed"/>

							  <value xsi:type="CD" nullFlavor="UNK"/>

							</observation>

						</entry>

						');

				END IF;



				IF recGender."PtSDeclined" > 0 OR recGender."PtSexOrient" > 0 OR recGender."PtSOther" IS NOT NULL THEN



					-- text

					dbms_lob_s.append(vText, '

								<table border="1" width="100%">

									<thead>

										<tr>

											<th>Sexual Orientation</th>

										</tr>

									</thead>

									<tbody>

										<tr>

										');



					IF recGender."PtSexOrient" = 1 THEN

						dbms_lob_s.append(vText, '<td> Straight/Heterosexual </td>');

					ELSIF 

						recGender."PtSexOrient" = 2 THEN 

							dbms_lob_s.append(vText, '<td> Lesbian/Gay </td>');

					ELSIF 

						recGender."PtSexOrient" = 3 THEN 

							dbms_lob_s.append(vText, '<td> Bisexual </td>');

					ELSIF 

						recGender."PtSexOrient" = 4 THEN 

							dbms_lob_s.append(vText, '<td> Do not know </td>');

					ELSIF 

						recGender."PtSDeclined" > 0 THEN 

							dbms_lob_s.append(vText, '<td> Choose not to disclose </td>');

					ELSIF 

						recGender."PtSOther" IS NOT NULL THEN 

							dbms_lob_s.append(vText, '<td> ' || TRIM(recGender."PtSOther") || ' </td>');

					END IF;



					dbms_lob_s.append(vText, '

										</tr>

									</tbody>

								</table>

							');

						

					-- entry

					dbms_lob_s.append(vEntries, '

						<!-- Add Sexual Orientation entry -->

						<entry>

							<observation classCode="OBS" moodCode="EVN">

							  <templateId root="2.16.840.1.113883.10.20.22.4.38"/>

							  <id root="2.16.840.1.113883.4.8155" />

							  <code code="76690-7" codeSystem="2.16.840.1.113883.6.1" displayName="Sexual Orientation"/>

							  <statusCode code="completed"/>

					');



					IF recGender."PtSexOrient" = 1 THEN

						dbms_lob_s.append(vEntries, '			<value xsi:type="CD" codeSystem="2.16.840.1.114222.4.11.7563" codeSystemName="Sexual Orientation" code="20430005" displayName="Straight or heterosexual"/>');

					ELSIF 

						recGender."PtSexOrient" = 2 THEN 

							dbms_lob_s.append(vEntries, '		<value xsi:type="CD" codeSystem="2.16.840.1.114222.4.11.7563" codeSystemName="Sexual Orientation" code="38628009" displayName="Lesbian, gay or homosexual"/>');

					ELSIF 

						recGender."PtSexOrient" = 3 THEN 

							dbms_lob_s.append(vEntries, '		<value xsi:type="CD" codeSystem="2.16.840.1.114222.4.11.7563" codeSystemName="Sexual Orientation" code="42035005" displayName="Bisexual"/>');

					ELSIF 

						recGender."PtSexOrient" = 4 THEN 

							dbms_lob_s.append(vEntries, '		<value xsi:type="CD" nullFlavor="UNK"/>');

					ELSIF 

						recGender."PtSDeclined" > 0 THEN 

							dbms_lob_s.append(vEntries, '		<value xsi:type="CD" nullFlavor="ASKU"/>');

					ELSIF 

						recGender."PtSOther" IS NOT NULL THEN 

							dbms_lob_s.append(vEntries, '		<value xsi:type="CD" nullFlavor="OTH"/>');

					END IF;



					dbms_lob_s.append(vEntries, '

						</observation>

					</entry>

				');



				ELSE

					-- text

					dbms_lob_s.append(vText, '

								<table border="1" width="100%">

									<thead>

										<tr>

											<th>Sexual Orientation</th>

										</tr>

									</thead>

									<tbody>

										<tr>

										');



					dbms_lob_s.append(vText, '<td> Unknown </td>');



					dbms_lob_s.append(vText, '

										</tr>

									</tbody>

								</table>

							');



					-- entry

					dbms_lob_s.append(vEntries, '

						<!-- Sexual Orientation observation template -->

						<entry>

							<observation classCode="OBS" moodCode="EVN">

							  <templateId root="2.16.840.1.113883.10.20.22.4.38"/>

							  <id root="2.16.840.1.113883.4.8155" />

							  <code code="76690-7" codeSystem="2.16.840.1.113883.6.1" displayName="Sexual Orientation"/>

							  <statusCode code="completed"/>

							  <value xsi:type="CD" nullFlavor="UNK"/>

							</observation>

						</entry>

					');



				END IF;



			END LOOP;



			if vHadGender = 0 THEN

									-- text

					dbms_lob_s.append(vText, '

								<table border="1" width="100%">

									<thead>

										<tr>

											<th>Gender Identity</th>

										</tr>

									</thead>

									<tbody>

										<tr>

										');



					dbms_lob_s.append(vText, '<td> Unknown </td>');



					dbms_lob_s.append(vText, '

										</tr>

									</tbody>

								</table>

							');



					-- entry

					dbms_lob_s.append(vEntries, '

						<!-- Gender Identity observation template -->

						<entry>

							<observation classCode="OBS" moodCode="EVN">

							  <templateId root="2.16.840.1.113883.10.20.22.4.38"/>

							  <id root="2.16.840.1.113883.4.8155" />

							  <code code="76691-5" codeSystem="2.16.840.1.113883.6.1" displayName="Gender Identity"/>

							  <statusCode code="completed"/>

							  <value xsi:type="CD" nullFlavor="UNK"/>

							</observation>

						</entry>

						');



											-- text

					dbms_lob_s.append(vText, '

								<table border="1" width="100%">

									<thead>

										<tr>

											<th>Sexual Orientation</th>

										</tr>

									</thead>

									<tbody>

										<tr>

										');



					dbms_lob_s.append(vText, '<td> Unknown </td>');



					dbms_lob_s.append(vText, '

										</tr>

									</tbody>

								</table>

							');



					-- entry

					dbms_lob_s.append(vEntries, '

						<!-- Sexual Orientation observation template -->

						<entry>

							<observation classCode="OBS" moodCode="EVN">

							  <templateId root="2.16.840.1.113883.10.20.22.4.38"/>

							  <id root="2.16.840.1.113883.4.8155" />

							  <code code="76690-7" codeSystem="2.16.840.1.113883.6.1" displayName="Sexual Orientation"/>

							  <statusCode code="completed"/>

							  <value xsi:type="CD" nullFlavor="UNK"/>

							</observation>

						</entry>

					');



				END IF;



			dbms_lob_s.append(vText, '

				</text>');

		

		--E143263.4

		ELSE	

		

				dbms_lob_s.append(vText, '<text></text>');

		

				-- entry

				-- AX-18696.19066

				dbms_lob_s.append(vEntries, '

				       <entry>

					  <observation classCode="OBS" moodCode="EVN">

					     <!-- Smoking status observation template -->

					     <templateId root="2.16.840.1.113883.10.20.22.4.78"/>

						  <id root="2.16.840.1.113883.4.8155" />

					     <code code="ASSERTION" codeSystem="2.16.840.1.113883.5.4"/>

					     <statusCode code="completed"/>

					     <effectiveTime xsi:type="IVL_TS" nullFlavor="UNK"/>

					     <value xsi:type="CD" nullFlavor="UNK"/>

					  </observation>

				       </entry>

				');



				-- AX-18696.19020

				dbms_lob_s.append(vEntries, '

					<!-- Birth Sex observation template -->

					<entry>

						<observation classCode="OBS" moodCode="EVN">

						  <templateId root="2.16.840.1.113883.10.20.22.4.200" extension="2016-06-01"/>

						  <templateId root="2.16.840.1.113883.10.20.22.4.200"/>

						  <code code="76689-9" codeSystem="2.16.840.1.113883.6.1"/>

						  <statusCode code="completed"/>

					     <value xsi:type="CD" nullFlavor="UNK"/>

						</observation>

					</entry>

					');



					--todo: add null gender and sexual identity...

					-- AX-21637

					dbms_lob_s.append(vEntries, '

					<!-- Gender Identity observation template -->

					<entry>

						<observation classCode="OBS" moodCode="EVN">

						  <templateId root="2.16.840.1.113883.10.20.22.4.38"/>

						  <id root="2.16.840.1.113883.4.8155" />

						  <code code="76691-5" codeSystem="2.16.840.1.113883.6.1" displayName="Gender Identity"/>

						  <statusCode code="completed"/>

					      <value xsi:type="CD" nullFlavor="UNK"/>

						</observation>

					</entry>

					');



					dbms_lob_s.append(vEntries, '

					<!-- Sexual Orientation observation template -->

					<entry>

						<observation classCode="OBS" moodCode="EVN">

						  <templateId root="2.16.840.1.113883.10.20.22.4.38"/>

						  <id root="2.16.840.1.113883.4.8155" />

						  <code code="76690-7" codeSystem="2.16.840.1.113883.6.1" displayName="Sexual Orientation"/>

						  <statusCode code="completed"/>

					      <value xsi:type="CD" nullFlavor="UNK"/>

						</observation>

					</entry>

					');



		END IF;



		dbms_lob_s.append(vResult, vText);



		dbms_lob_s.append(vResult, vEntries);



		dbms_lob_s.append(vResult,

			'</section>

			</component>

			');



		return vResult;

	END;

  

	FUNCTION getproblemsection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob IS

		vResult CLOB := '';

		CURSOR curProblems IS

			SELECT 

				AP."PtAlert", 

				AP."MedAlert", 

				AP."AlertType", 

				AP."Description", 

				AP."Status", 

				AP."OnsetDate", 

				AP."Deleted", 

				AC."Code", 

				AC."Color", 

				AP."SNOCode", 

				AP."AddDateTime" 

			FROM PTALERT AP LEFT JOIN MEDALERT AC ON AP."MedAlert" = AC."MedAlert" 

			WHERE 1=1

				AND AP."Patient" = vPId 

				AND AP."AlertType" = 2  

				AND AP."Deleted" = 0

				AND AP."SNOCode" NOT IN ('449868002', '428041000124106', '8517006', '266919005', '77176002', '266927001', '428071000124103', '428061000124105')

				-- AX-18945.19095

				AND 

				(

					(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND AP."AddDateTime" >= vDate1 AND AP."AddDateTime" <= vDate2)

					OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND AP."AddDateTime" >= vDate1)

					OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND AP."AddDateTime" <= vDate1) 

					OR (vDate1 IS NULL)

				)

			ORDER BY AP."Audit", AP."AddDateTime";



		vText CLOB := '';

		vEntries CLOB := '';

		vCount NUMBER := 0;

		vStatus  VARCHAR2(32) := '';

		vStatusCode  VARCHAR2(32) := '';

		

		vProblemsOnFile NUMBER := -1;

		vReviewsOnFile NUMBER := -1;

		vNoKnownProblems NUMBER := -1;

	   v_nCount		NUMBER := 0;								-- AX-26071.2



	BEGIN



		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetProblemSection');

		IF v_nCount > 0 THEN

		  -- custom package function exists; AX-27290 

		  EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetProblemSection(:1, :2, :3, :4, :5) FROM DUAL' INTO vResult

							USING vPId, vbShowInfo, vIsDateFrom, vDate1, vDate2;

		  RETURN vResult;

		END IF;



		-- init clobs

		dbms_lob_s.createtemporary (vResult, TRUE);

		dbms_lob_s.createtemporary (vText, TRUE);

		dbms_lob_s.createtemporary (vEntries, TRUE);

		

		--B142586 - check for 0 rows and handle both reviewed and not reviewed cases

  		SELECT COUNT(1) INTO vProblemsOnFile

  		FROM PTALERT AP LEFT JOIN MEDALERT AC ON AP."MedAlert" = AC."MedAlert" 

		WHERE 1=1

			AND AP."Patient" = vPId 

			AND AP."AlertType" = 2  

			AND AP."Deleted" = 0

			-- AX-20334.20664

			AND AP."SNOCode" NOT IN ('449868002', '428041000124106', '8517006', '266919005', '77176002', '266927001', '428071000124103', '428061000124105')

			-- AX-18945.19095

			AND 

			(

				(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND AP."AddDateTime" >= vDate1 AND AP."AddDateTime" <= vDate2)

				OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND AP."AddDateTime" >= vDate1)

				OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND AP."AddDateTime" <= vDate1) 

				OR (vDate1 IS NULL)

			);

  			

  		IF vProblemsOnFile = 0 THEN

  			-- check if we've reviewed them

  			SELECT COUNT(1) INTO vReviewsOnFile

  			FROM EPREVIEW

  			WHERE 1=1 

  				AND "Patient" = vPId 

  				AND "Deleted" = 0

  				AND "Type" = 2;

  				

  			-- check if the most recent review indicates No Known Problems

  			IF vReviewsOnFile > 0 THEN

  			

  				SELECT "HasRecords" INTO vNoKnownProblems

  				FROM EPREVIEW

  				WHERE 1=1 

  					AND "EPReview" = (

  						SELECT MAX("EPReview") 

  						FROM EPREVIEW

  						WHERE 1=1

							AND "Patient" = vPId

							AND "Type" = 2

							AND "Deleted" = 0

							);

  			END IF;

		END IF;

  

		-- problems section header

		dbms_lob_s.append(vResult, '

			<component>

			<section>

					<templateId root="2.16.840.1.113883.10.20.22.2.5.1" extension="2015-08-01"/>

					<templateId root="2.16.840.1.113883.10.20.22.2.5.1"/>

			       <code

				  code="11450-4"

				  codeSystem="2.16.840.1.113883.6.1"

				  codeSystemName="LOINC"

				  displayName="Problem List"/>

			      <title>Problems</title>');



		--E143263.4

		IF NOT vbShowInfo THEN

		

			dbms_lob_s.append(vText, '<text></text>');

			dbms_lob_s.append(vEntries, '

				<!-- Problem Concern Act -->

				<entry>

					<!-- Problem Concern Act template -->

					<act classCode="ACT" moodCode="EVN">

						<templateId root="2.16.840.1.113883.10.20.22.4.3" extension="2015-08-01" />

						<templateId root="2.16.840.1.113883.10.20.22.4.3" />

						<id root="2.16.840.1.113883.4.8155" />

						<code code="CONC" 

							displayName="Concern" 

							codeSystem="2.16.840.1.113883.5.6"

							codeSystemName="HL7ActClass"/> 

						<statusCode code="active"/>

						<effectiveTime>

							<low nullFlavor="NA"/>

						</effectiveTime>

						<entryRelationship typeCode="SUBJ">

							<!-- Problem Observation template -->

							<observation classCode="OBS" moodCode="EVN" negationInd="true"> 

								<templateId root="2.16.840.1.113883.10.20.22.4.4" extension="2015-08-01"/>

								<templateId root="2.16.840.1.113883.10.20.22.4.4"/>

								 <id root="2.16.840.1.113883.4.8155" />

								<code code="55607006" displayName="Problem" codeSystemName="SNOMED-CT" codeSystem="2.16.840.1.113883.6.96">

									<!-- This code SHALL contain at least one [1..*] translation, which SHOULD be selected from ValueSet Problem Type (LOINC) -->

									<translation code="75326-9" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Problem"/>

								</code>	

								<statusCode code="completed" /> 

								<effectiveTime>

									<low nullFlavor="NA"/>

								</effectiveTime>

								<value xsi:type="CD" 

									nullFlavor="UNK"/> 

							</observation>

						</entryRelationship>

					</act>

				</entry>');

		

		ELSIF vNoKnownProblems = 0 THEN -- no known problems case

			-- human-readable part

			dbms_lob_s.append(vText, '<text>The patient has no known medical problems.</text>');

			

			-- machine-readable part

			-- 

			/*

			SAMIR_BOUDJEBLA 

			I replaced the entire <ACT tag 

			with

			 	the value displayed below				

              */

			dbms_lob_s.append(vEntries, '

				<!-- Problem Concern Act -->

				<entry>

					<!-- Problem Concern Act template -->

					<act classCode="ACT" moodCode="EVN">

                        <templateId root="2.16.840.1.113883.10.20.22.4.3" extension="2015-08-01" />

                        <templateId root="2.16.840.1.113883.10.20.22.4.3" />

                        <id root="2.16.840.1.113883.4.8155" />

                        <code code="CONC" 

                            displayName="Concern" 

                            codeSystem="2.16.840.1.113883.5.6"

                            codeSystemName="HL7ActClass"/> 

                        <statusCode code="active"/>

                        <effectiveTime>

                            <low nullFlavor="NA"/>

                        </effectiveTime>

                        <entryRelationship typeCode="SUBJ">

                            <!-- Problem Observation template -->

                            <observation classCode="OBS" moodCode="EVN" negationInd="true"> 

                                <templateId root="2.16.840.1.113883.10.20.22.4.4" extension="2015-08-01"/>

                                <templateId root="2.16.840.1.113883.10.20.22.4.4"/>

                                 <id root="2.16.840.1.113883.4.8155" />

                                <code code="55607006" displayName="Problem" codeSystemName="SNOMED-CT" codeSystem="2.16.840.1.113883.6.96">

                                        <!-- This code SHALL contain at least one [1..*] translation, which SHOULD be selected from ValueSet Problem Type (LOINC) -->

                                        <translation code="75326-9" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Problem"/>

                                    </code>

                                <statusCode code="completed" /> 

                                <effectiveTime>

                                    <low nullFlavor="NA"/>

                                </effectiveTime>

                                <value xsi:type="CD" 

                                    code="55607006" 

                                    codeSystem="2.16.840.1.113883.6.96" 

                                    codeSystemName="SNOMED CT" 

                                    displayName="Problem" /> 

                            </observation>

                        </entryRelationship>

                    </act>

				</entry>');

			

		ELSIF vProblemsOnFile = 0 THEN -- no problems, but not reviewed either

			-- human-readable part

			dbms_lob_s.append(vText, '<text>The patient has no medical problems on file, but this has not been reviewed.</text>');

			

			/*

			SAMIR_BOUDJEBLA 

			I replaced the entire <ACT tag 

			with

			 	the value displayed below

			*/

			-- machine-readable part

			dbms_lob_s.append(vEntries, '

				<!-- Problem Concern Act -->

				<entry>

					<!-- Problem Concern Act template -->

<act classCode="ACT" moodCode="EVN">

                        <templateId root="2.16.840.1.113883.10.20.22.4.3" extension="2015-08-01" />

                        <templateId root="2.16.840.1.113883.10.20.22.4.3" />

                        <id root="2.16.840.1.113883.4.8155" />

                        <code code="CONC" 

                            displayName="Concern" 

                            codeSystem="2.16.840.1.113883.5.6"

                            codeSystemName="HL7ActClass"/> 

                        <statusCode code="active"/>

                        <effectiveTime>

                            <low nullFlavor="NA"/>

                        </effectiveTime>

                        <entryRelationship typeCode="SUBJ">

                            <!-- Problem Observation template -->

                            <observation classCode="OBS" moodCode="EVN" negationInd="true"> 

                                <templateId root="2.16.840.1.113883.10.20.22.4.4" extension="2015-08-01"/>

                                <templateId root="2.16.840.1.113883.10.20.22.4.4"/>

                                 <id root="2.16.840.1.113883.4.8155" />

                                <code code="55607006" displayName="Problem" codeSystemName="SNOMED-CT" codeSystem="2.16.840.1.113883.6.96">

                                        <!-- This code SHALL contain at least one [1..*] translation, which SHOULD be selected from ValueSet Problem Type (LOINC) -->

                                        <translation code="75326-9" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Problem"/>

                                    </code>

                                <statusCode code="completed" /> 

                                <effectiveTime>

                                    <low nullFlavor="NA"/>

                                </effectiveTime>

                                <value xsi:type="CD" 

                                    code="55607006" 

                                    codeSystem="2.16.840.1.113883.6.96" 

                                    codeSystemName="SNOMED CT" 

                                    displayName="Problem" /> 

                            </observation>

                        </entryRelationship>

                    </act>

				</entry>');

			

		ELSE -- have problems

			-- table for human-readable data

			dbms_lob_s.append(vText, '

				<text>

					<table border="1" width="100%">

						<thead>

							<tr>

								<th>Problem</th>

								<th>Onset Date</th>

								<th>Status</th>

							</tr>

						</thead>

						<tbody>

				');

				

				  

			-- loop thru the problems..

			  for probRec in curProblems

			  LOOP

			    IF probRec."Status" = 0 THEN

			      vStatus := 'Active';

			      vStatusCode := 'active';

			    ELSIF probRec."Status" = 1 THEN

			      vStatus := 'Inactive';

			      vStatusCode := 'aborted';

			    ELSIF probRec."Status" = 2 THEN

			      vStatus := 'Resolved';

			      vStatusCode := 'completed';

			    END IF;



			    vCount := vCount + 1;

			    

			    -- text entry for the problem

			    dbms_lob_s.append(vText, '

							<tr>

								<td><content ID="problem' || vCount || '">' || htf.escape_sc(probRec."Description") || '</content></td>

								<td>' || TO_CHAR(NVL(probRec."OnsetDate", probRec."AddDateTime"), 'MM/DD/YYYY') || '</td>

								<td>' || vStatus || '</td>

							</tr>

					');



			    -- coded entry for the problem

			    dbms_lob_s.append(vEntries, '

			    <entry>

			      <act classCode="ACT" moodCode="EVN">

				<templateId root="2.16.840.1.113883.10.20.22.4.3" extension="2015-08-01" />

				<templateId root="2.16.840.1.113883.10.20.22.4.3" />

				<id root="2.16.840.1.113883.4.8155" />

				<code code="CONC" codeSystem="2.16.840.1.113883.5.6"/>

				<statusCode code="' || vStatusCode || '"/>

				<effectiveTime>

				      <low value="' || TO_CHAR(NVL(probRec."OnsetDate", probRec."AddDateTime"), 'YYYYMMDD') || '"/>

				</effectiveTime>

				<entryRelationship typeCode="SUBJ">

				  <observation classCode="OBS" moodCode="EVN">

				    <templateId root="2.16.840.1.113883.10.20.22.4.4" extension="2015-08-01"/>

					<templateId root="2.16.840.1.113883.10.20.22.4.4"/>

				    <id root="2.16.840.1.113883.4.8155" />  

				    <code code="33999-4" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC"/>

				    <statusCode code="' || 'completed' || '"/>

				    <effectiveTime>

				      <low value="' || TO_CHAR(NVL(probRec."OnsetDate", probRec."AddDateTime"), 'YYYYMMDD') || '"/>

				    </effectiveTime>

				    <value

							    xsi:type="CD"

							    code="' || TRIM(probRec."SNOCode") ||'"

							    codeSystem="2.16.840.1.113883.6.96"

							    codeSystemName="SNOMED CT"

							    displayName="' || htf.escape_sc(probRec."Description") || '"/>

				  </observation>

				</entryRelationship>

			      </act>

			    </entry>

			    ');



			  END LOOP;



			  -- footer for the text section

			  dbms_lob_s.append(vText, '

						</tbody>

					</table>

				</text>

				');

		END IF;

     

		-- put it all together

		dbms_lob_s.append(vResult, vText);  

		dbms_lob_s.append(vResult, vEntries);              



		-- section footer

		dbms_lob_s.append(vResult,

			'</section>

			</component>');



		return vResult;

	END;

  



	-- E142547 - immunizations

	-- this uses the IMMUN form developed for 2014 CE

	-- AX-18945.19095

	FUNCTION getimmunizationsection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob IS

		vResult CLOB := '';

		vImmunFormName PFORM."FormCode"%TYPE := 'IMMUN';

		

		-- cursor of fully approved immunization forms for this patient. 

		CURSOR curImmForms IS

			SELECT PF."PForm"

			FROM PFORM PF

			WHERE 1=1 

				AND PF."FormCode" = vImmunFormName

				AND PF."Patient" = vPId

				AND PF."Approved" = 1

				AND PF."Inactive" = 0

				-- AX-18945.19095

				AND 

				(

					(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PF."Date") >= TRUNC(vDate1) AND TRUNC(PF."Date") <= TRUNC(vDate2))

					OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PF."Date") >= TRUNC(vDate1))

					OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PF."Date") <= TRUNC(vDate1)) 

					OR (vDate1 IS NULL)

				)

			ORDER BY PF."CreatedDate" DESC;



		vText CLOB := '';

		vEntries CLOB := '';

		vCount NUMBER := 0;

		vHasImmun NUMBER := 0;

		

		vVaccName PITEM."AnsListDesc"%TYPE := NULL;

		vVaccCVXCode PITEM."AnsListDesc"%TYPE := NULL;

		vImmDate PITEM."AnsDate"%TYPE := NULL;

		vRefusalReason PITEM."AnsListDesc"%TYPE := NULL;

		vRefNegInd  VARCHAR2(5) := NULL;

	   v_nCount		NUMBER := 0;								-- AX-26071.2



	BEGIN



		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetImmunizationSection');

		IF v_nCount > 0 THEN

		  -- custom package function exists; AX-27290 

		  EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetImmunizationSection(:1, :2, :3, :4, :5) FROM DUAL' INTO vResult

							USING vPId, vbShowInfo, vIsDateFrom, vDate1, vDate2;

		  RETURN vResult;

		END IF;



		-- init clobs

		dbms_lob_s.createtemporary (vResult, TRUE);

		dbms_lob_s.createtemporary (vText, TRUE);

		dbms_lob_s.createtemporary (vEntries, TRUE);

	

		-- section header

		dbms_lob_s.append(vResult, '

			<component>

			  <section>

			    <!--  ********  Immunizations (entries required) section template   ******** -->

			    <templateId root="2.16.840.1.113883.10.20.22.2.2.1"/>

			    <code code="11369-6" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="History of immunizations"/>

			    <title>Immunizations</title>');	

	

		-- check if the patient has any immunizations

		SELECT COUNT(1) INTO vHasImmun

		FROM PFORM PF

		WHERE 1=1 

			AND PF."FormCode" = vImmunFormName

			AND PF."Patient" = vPId

			AND PF."Approved" = 1

			AND PF."Inactive" = 0

			-- AX-18945.19095

			AND 

			(

				(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PF."Date") >= TRUNC(vDate1) AND TRUNC(PF."Date") <= TRUNC(vDate2))

				OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PF."Date") >= TRUNC(vDate1))

				OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PF."Date") <= TRUNC(vDate1)) 

				OR (vDate1 IS NULL)

			); 



		IF NOT vbShowInfo OR vHasImmun = 0 THEN							--E143263.4

		

			--E143263.4; B143328.3

			IF vbShowInfo THEN

				-- patient has no immunizations

				dbms_lob_s.append(vText, '

					<text>No immunizations on file.</text>

					');

			ELSE

				dbms_lob_s.append(vText, '

					<text></text>

					');

			END IF;

				

			dbms_lob_s.append(vEntries, '

					<entry typeCode="DRIV">

						<!-- using negationInd="true" to signify that there are no known immunizations -->

						<substanceAdministration classCode="SBADM" moodCode="EVN" negationInd="true">

							<!-- ** Immunization Activity (V3) ** -->

							<templateId root="2.16.840.1.113883.10.20.22.4.52" extension="2015-08-01"/>

							<templateId root="2.16.840.1.113883.10.20.22.4.52"/>

							<id root="de10790f-1496-4729-8fe6-f1b87b6219f7"/>

							<statusCode code="active"/>

							<effectiveTime nullFlavor="NA"/>

							<routeCode nullFlavor="NA"/>

							<consumable>

								<manufacturedProduct classCode="MANU">

									<!-- ** Immunization Medication Information (V2) ** -->

									<templateId root="2.16.840.1.113883.10.20.22.4.54" extension="2014-06-09"/>

									<templateId root="2.16.840.1.113883.10.20.22.4.54"/>

									<manufacturedMaterial>

										<!-- there is no generic vaccine code and no known recommended way to do this - 

										leaving generic flu for now just as an example. Not sure if it makes more sense to apply a nullFlavor? -db -->

										<code nullFlavor="OTH">

											<!-- Optional original text -->

											<originalText>Vaccination</originalText>

											<translation code="71181003" displayName="vaccine"

												codeSystem="2.16.840.1.113883.6.96"

												codeSystemName="SNOMED CT"/>

										</code>

										<!-- NA since there is no immunization data -db -->

										<lotNumberText nullFlavor="NA"/>

									</manufacturedMaterial>

								</manufacturedProduct>

							</consumable>

						</substanceAdministration>

					</entry>');

		ELSE

			-- patient has one or more immunizations

			

			-- text header

			dbms_lob_s.append(vText, '

				<text>

				  <table border="1" width="100%">

				    <thead>

				      <tr>

				        <th>Vaccine</th>

				        <th>Date</th>

				        <th>Refusal Reason</th>

				      </tr>

				    </thead>

				  <tbody>');

				  

			FOR cImmForm in curImmForms LOOP

				vCount := vCount + 1;

				

				-- get the info for this immunization from the form	

				-- vaccine name

				BEGIN

					SELECT 

						NLS_UPPER(SUBSTR(PI."AnsListDesc", INSTR(PI."AnsListDesc", '-')+2)),

						SUBSTR(PI."AnsListDesc", 1, INSTR(PI."AnsListDesc", '-')-2)

						INTO vVaccName, vVaccCVXCode		

					FROM PITEM PI, FITEM FI

					WHERE 1=1 

						AND PI."FItem" = FI."FItem"

						AND PI."Patient" = vPId

						AND PI."FormCode" = vImmunFormName

						AND PI."PForm" = cImmForm."PForm"

						AND FI."Deleted" = 0

						AND PI."Status" = 0

						AND PI."AppDate" IS NOT NULL

						AND FI."Code" = 'IMMCVXCODE'

						-- AX-18945.19095

						AND 

						(

							(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

							OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

							OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

							OR (vDate1 IS NULL)

						);

						

				EXCEPTION WHEN OTHERS THEN

					vVaccName := NULL;

					vVaccCVXCode := NULL;

				END;			

				

				-- immunization date

				BEGIN

					SELECT PI."AnsDate" INTO vImmDate

					FROM PITEM PI, FITEM FI

					WHERE 1=1 

						AND PI."FItem" = FI."FItem"

						AND PI."Patient" = vPId

						AND PI."FormCode" = vImmunFormName

						AND PI."PForm" = cImmForm."PForm"

						AND FI."Deleted" = 0

						AND PI."Status" = 0

						AND PI."AppDate" IS NOT NULL

						AND FI."Code" = 'IMMDATES'

						-- AX-18945.19095

						AND 

						(

							(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

							OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

							OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

							OR (vDate1 IS NULL)

						);

						

				EXCEPTION WHEN OTHERS THEN

					vImmDate := NULL;

				END;				

				

				-- refusal reason

				BEGIN

					SELECT SUBSTR(PI."AnsListDesc", INSTR(PI."AnsListDesc", '-')+2) INTO vRefusalReason

					FROM PITEM PI, FITEM FI

					WHERE 1=1 

						AND PI."FItem" = FI."FItem"

						AND PI."Patient" = vPId

						AND PI."FormCode" = vImmunFormName

						AND PI."PForm" = cImmForm."PForm"

						AND FI."Deleted" = 0

						AND PI."Status" = 0

						AND PI."AppDate" IS NOT NULL

						AND FI."Code" = 'IMMRUFUSAL'

						-- AX-18945.19095

						AND 

						(

							(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

							OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

							OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

							OR (vDate1 IS NULL)

						);

						

					IF vRefusalReason IS NULL THEN

						vRefNegInd := 'false';

					ELSE

						vRefNegInd := 'true';

					END IF;

						

				EXCEPTION WHEN OTHERS THEN

					vRefusalReason := NULL;

					vRefNegInd := 'false';

				END;

				

			

				-- text 

				dbms_lob_s.append(vText, '

					<tr>

					  <td><content ID="immunization' || vCount || '">' || NVL(vVaccName, ' ') || '</content></td>

					  <td>' || NVL(TO_CHAR(vImmDate, 'MM/DD/YYYY'), ' ') || '</td>

					  <td>' || NVL(vRefusalReason, ' ') ||'</td>

					</tr>');

					

				-- entry

				dbms_lob_s.append(vEntries, '

					<entry>

						<substanceAdministration classCode="SBADM" moodCode="EVN" negationInd="' || vRefNegInd || '">

					     <templateId root="2.16.840.1.113883.10.20.22.4.52" extension="2015-08-01"/>

						 <templateId root="2.16.840.1.113883.10.20.22.4.52"/>

						 <!-- **** Immunization Activity Template **** -->

						  <id root="2.16.840.1.113883.4.8155" />

						  <text>

						    <reference value="#immunization' || vCount ||'"/>

						  </text>

						  <statusCode code="completed"/>');



						  -- AX-18945.19094e

						  	IF vImmDate IS NULL THEN

								dbms_lob_s.append(vEntries, '

								<effectiveTime nullFlavor="UNK"/>');

							ELSE

								dbms_lob_s.append(vEntries, '

								<effectiveTime xsi:type="IVL_TS" value="' || NVL(TO_CHAR(vImmDate,'YYYYMMDD'),' ') || '"/>');

							END IF;



						  dbms_lob_s.append(vEntries, '

						  <consumable typeCode="CSM">

						  	<manufacturedProduct classCode="MANU">

						  		<templateId root="2.16.840.1.113883.10.20.22.4.54" extension="2014-06-09"/>

								<templateId root="2.16.840.1.113883.10.20.22.4.54"/>

						  		<manufacturedMaterial classCode="MMAT" determinerCode="KIND">

						  			<code code="' || NVL(vVaccCVXCode, ' ') || '" 

						  			   codeSystem="2.16.840.1.113883.12.292" 

						  			   codeSystemName="CVX" 

						  			   displayName="' || htf.escape_sc(NVL(vVaccName, ' ')) || '">

						  				<originalText>

						  					<reference value="#immunization' || vCount ||'"/>

						  				</originalText>

						  			</code>

						  		</manufacturedMaterial>

						  	</manufacturedProduct>

						  </consumable>

						</substanceAdministration>

					</entry>');

			

			END LOOP;

				  

		  	-- text footer

			dbms_lob_s.append(vText, '

				    </tbody>

				  </table>

				</text>');

		  	

		END IF;



		-- put it all together

		dbms_lob_s.append(vResult, vText);

		dbms_lob_s.append(vResult, vEntries);

		

		-- section footer

		dbms_lob_s.append(vResult, '

			  </section>

			</component>');



		RETURN vResult;

	END;

	

  

   -- E142434 - allergies

	-- AX-18945.19095

	FUNCTION getallergiessection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob IS

		vResult CLOB := '';

		vText CLOB := '';

		vEntries CLOB := '';

		vCount NUMBER := 0;

		vCodedCount NUMBER := 0;

		

		vAllergiesOnFile NUMBER := -1;

		vReviewsOnFile NUMBER := -1;

		vNoKnownAllergies NUMBER := -1;



		-- cursor containing the allergies

		CURSOR curPtAllergies IS

			SELECT 

				htf.escape_sc(PA."Description") as "Description",

				htf.escape_sc(PA."Reaction") as "Reaction",

				PA."Status",

				PA."OnsetDate",

				PA."Note", 

				PA."AddDateTime",

				CASE 

					WHEN "Status" = 0 THEN 'Active'

					WHEN "Status" = 1 THEN 'Inactive' 

					END AS "StatusText",

				CASE 

					WHEN "Status" = 0 THEN 'active'

					WHEN "Status" = 1 THEN 'aborted' 

					END AS "ProblemActStatus",

				RN."RxNorm"

			FROM PTALERT PA LEFT OUTER JOIN RXNNDC RN ON PA."NDCID" = RN."NDC"

			WHERE 1=1 

				AND PA."AlertType" = 1

				AND PA."Status" IN (0,1)

				AND PA."Deleted" = 0

				AND PA."Patient" = vPId

				-- AX-18945.19095

				AND 

				(

					(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND PA."AddDateTime" >= vDate1 AND PA."AddDateTime" <= vDate2)

					OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND PA."AddDateTime" >= vDate1)

					OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND PA."AddDateTime" <= vDate1) 

					OR (vDate1 IS NULL)

				)

			ORDER BY PA."Status" ASC, PA."AddDateTime" DESC;

	   v_nCount		NUMBER := 0;								-- AX-26071.2



	BEGIN



		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetAllergiesSection');

		IF v_nCount > 0 THEN

		  -- custom package function exists; AX-27290b 

		  EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetAllergiesSection(:1, :2, :3, :4, :5) FROM DUAL' INTO vResult

							USING vPId, vbShowInfo, vIsDateFrom, vDate1, vDate2;

		  RETURN vResult;

		END IF;



		dbms_lob_s.createtemporary (vResult, TRUE);

		dbms_lob_s.createtemporary (vText, TRUE);

		dbms_lob_s.createtemporary (vEntries, TRUE);

			

		-- check if there are actually any allergies

		SELECT COUNT(1) INTO vAllergiesOnFile

		FROM PTALERT 

		WHERE 1=1

			AND "Patient" = vPId 

			AND "AlertType" = 1

			AND "Deleted" = 0

			-- AX-18945.19095

			AND 

			(

				(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND "AddDateTime" >= vDate1 AND "AddDateTime" <= vDate2)

				OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND "AddDateTime" >= vDate1)

				OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND "AddDateTime" <= vDate1) 

				OR (vDate1 IS NULL)

			);

			

		IF vAllergiesOnFile = 0 THEN

			-- check if we've reviewed them

			SELECT COUNT(1) INTO vReviewsOnFile

			FROM EPREVIEW

			WHERE 1=1 

				AND "Patient" = vPId 

				AND "Deleted" = 0

				AND "Type" = 1;

				

			-- check if the most recent review indicates No Known Allergies

			IF vReviewsOnFile > 0 THEN

			

				SELECT "HasRecords" INTO vNoKnownAllergies

				FROM EPREVIEW

				WHERE 1=1 

					AND "EPReview" = (

						SELECT MAX("EPReview") 

						FROM EPREVIEW

						WHERE 1=1

						AND "Patient" = vPId

						AND "Type" = 1

						AND "Deleted" = 0);

			END IF;

		END IF;



		dbms_lob_s.append(vResult, '

		<component>

		<section>

			<!-- *** Allergies and Intolerances Section (entries required) (V3) *** -->

			<templateId root="2.16.840.1.113883.10.20.22.2.6.1"/>

			<templateId root="2.16.840.1.113883.10.20.22.2.6.1" extension="2015-08-01"/>

			<code code="48765-2" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC"/>

			<title>Allergies, Adverse Reactions, Alerts</title>');



		--E143263.4

		IF NOT vbShowInfo THEN										



			-- human-readable part

			dbms_lob_s.append(vText, '<text></text>');

			

			-- machine-readable part 

			-- AX-18696.19033

			-- AX-18696.19070

			dbms_lob_s.append(vEntries, '

			<entry typeCode="DRIV">

				<!-- Allergy Concern Act (NOT vbShowInfo) -->

				<act classCode="ACT" moodCode="EVN">

					<templateId root="2.16.840.1.113883.10.20.22.4.30"/>

					<templateId root="2.16.840.1.113883.10.20.22.4.30" extension="2015-08-01"/>

					<id root="2.16.840.1.113883.4.8155" />

					<code code="CONC" codeSystem="2.16.840.1.113883.5.6"/>

					<statusCode code="active"/>

					<effectiveTime>

						<low nullFlavor="NA"/>

					</effectiveTime>



					<entryRelationship typeCode="SUBJ">

							<!-- No Known Allergies -->

							<!-- The negationInd = true negates the observation/value -->

							<!-- The use of negationInd corresponds with the newer Observation.valueNegationInd -->

							<observation classCode="OBS" moodCode="EVN" negationInd="true">

								<!-- allergy - intolerance observation template -->

								<templateId root="2.16.840.1.113883.10.20.22.4.7"/>

								<templateId root="2.16.840.1.113883.10.20.22.4.7" extension="2014-06-09"/>

								<id root="2.16.840.1.113883.4.8155" />

								<code code="ASSERTION" codeSystem="2.16.840.1.113883.5.4"/>

								<statusCode code="completed"/>

								<effectiveTime>

									<low nullFlavor="NA"/>

									<high nullFlavor="UNK"/>

								</effectiveTime>

								<value xsi:type="CD" code="419199007"

									displayName="Allergy to substance (disorder)"

									codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT"/>



								<!-- In C-CDA R2.1 the participant is required. -->

							  <participant typeCode="CSM">

									<participantRole classCode="MANU">

											<playingEntity classCode="MMAT">

												<code nullFlavor="NA"/>

											</playingEntity>

									</participantRole>

								</participant>

							</observation>				      

					</entryRelationship>

				</act>

			</entry> ');

	

		ELSIF vNoKnownAllergies = 0 THEN -- no known allergies case

			-- human-readable part

			dbms_lob_s.append(vText, '<text>The patient has no known allergies.</text>');

			

			-- machine-readable part

			-- AX-18696.19033

			-- AX-18696.19070

			dbms_lob_s.append(vEntries, '

					 <entry typeCode="DRIV">

						  <!-- Allergy Concern Act (no known allergies case) -->

						  <act classCode="ACT" moodCode="EVN">

								<templateId root="2.16.840.1.113883.10.20.22.4.30"/>

								<templateId root="2.16.840.1.113883.10.20.22.4.30" extension="2015-08-01"/>

								<id root="2.16.840.1.113883.4.8155" />

								<code code="CONC" codeSystem="2.16.840.1.113883.5.6"/>

								<statusCode code="active"/>

								<effectiveTime>

									<low nullFlavor="NA"/>

								</effectiveTime>



								<entryRelationship typeCode="SUBJ">

									<!-- No Known Allergies -->

									<!-- The negationInd = true negates the observation/value -->

									<!-- The use of negationInd corresponds with the newer Observation.valueNegationInd -->

									<observation classCode="OBS" moodCode="EVN" negationInd="true">

										<!-- allergy - intolerance observation template -->

										<templateId root="2.16.840.1.113883.10.20.22.4.7"/>

										<templateId root="2.16.840.1.113883.10.20.22.4.7" extension="2014-06-09"/>

										<id root="2.16.840.1.113883.4.8155" />

										<code code="ASSERTION" codeSystem="2.16.840.1.113883.5.4"/>

										<statusCode code="completed"/>

										<effectiveTime>

											<low nullFlavor="NA"/>

											<high nullFlavor="UNK"/>

										</effectiveTime>

										<value xsi:type="CD" code="419199007"

											displayName="Allergy to substance (disorder)"

											codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT"/>



									  <!-- In C-CDA R2.1 the participant is required. -->

									  <participant typeCode="CSM">

											<participantRole classCode="MANU">

													<playingEntity classCode="MMAT">

														<code nullFlavor="NA"/>

													</playingEntity>

											</participantRole>

										</participant>

									</observation>				      

							</entryRelationship>

						</act>

					</entry> ');

		

		ELSIF vAllergiesOnFile = 0 THEN -- no allergies, but not reviewed either

			-- human-readable part

			dbms_lob_s.append(vText, '<text>The patient has no allergies on file, but this has not been reviewed.</text>');

						

			-- machine-readable part

			-- AX-18696.19033

			-- AX-18696.19070

			dbms_lob_s.append(vEntries, '

				<entry typeCode="DRIV">

					<!-- Allergy Concern Act (no allergies, but not reviewed either) -->

					<act classCode="ACT" moodCode="EVN">

						<templateId root="2.16.840.1.113883.10.20.22.4.30"/>

						<templateId root="2.16.840.1.113883.10.20.22.4.30" extension="2015-08-01"/>

						<id root="2.16.840.1.113883.4.8155" />

						<code code="CONC" codeSystem="2.16.840.1.113883.5.6"/>

						<statusCode code="active"/>

						<effectiveTime>

							<low nullFlavor="NA"/>

						</effectiveTime>



						<entryRelationship typeCode="SUBJ">

							<!-- No Known Allergies -->

							<!-- The negationInd = true negates the observation/value -->

							<!-- The use of negationInd corresponds with the newer Observation.valueNegationInd -->

							<observation classCode="OBS" moodCode="EVN" negationInd="true">

								<!-- allergy - intolerance observation template -->

								<templateId root="2.16.840.1.113883.10.20.22.4.7"/>

								<templateId root="2.16.840.1.113883.10.20.22.4.7" extension="2014-06-09"/>

								<id root="2.16.840.1.113883.4.8155" />

								<code code="ASSERTION" codeSystem="2.16.840.1.113883.5.4"/>

								<statusCode code="completed"/>

								<effectiveTime>

									<low nullFlavor="NA"/>

									<high nullFlavor="UNK"/>

								</effectiveTime>

								<value xsi:type="CD" code="419199007"

									displayName="Allergy to substance (disorder)"

									codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT"/>



								<!-- In C-CDA R2.1 the participant is required. -->

								<participant typeCode="CSM">

									<participantRole classCode="MANU">

											<playingEntity classCode="MMAT">

												<code nullFlavor="NA"/>

											</playingEntity>

									</participantRole>

								</participant>

							</observation>				      

				      </entryRelationship>

				   </act>

				</entry> ');

			

		ELSE -- have allergies

		

			-- table for human-readable data

			dbms_lob_s.append(vText, '

				<text>

				<table border="1" width="100%">

				  <thead>

				    <tr>

				      <th>Substance</th>

				      <th>Reaction</th>

				      <th>Status</th>

				      <th>Onset Date</th>

				    </tr>

				  </thead>

				  <tbody>');



			FOR allergyRec in curPtAllergies LOOP



				-- human-readable data in vText

				vCount := vCount + 1;

				dbms_lob_s.append(vText, '

					<tr>

					  <td><content ID="allergy' || vCount  || '">' || TRIM(allergyRec."Description") || '</content></td>

					  <td>' || TRIM(allergyRec."Reaction") || '</td><td>' || TRIM(allergyRec."StatusText") || '</td><td>' || TO_CHAR(allergyRec."OnsetDate", 'MM/DD/YYYY') || '</td>

					</tr>');



				-- machine-readable data in vEntries - only for those that have RxNorm codes (they have to look at human-readable part to see other types of allergies)

				IF allergyRec."RxNorm" IS NOT NULL THEN 

					vCodedCount := vCodedCount + 1;

				

				-- AX-18696.19033

					dbms_lob_s.append(vEntries, '

					<entry typeCode="DRIV">

						<!-- Allergy Concern Act (have allergies) -->

						<act classCode="ACT" moodCode="EVN">

							<templateId root="2.16.840.1.113883.10.20.22.4.30"/>

							<templateId root="2.16.840.1.113883.10.20.22.4.30" extension="2015-08-01"/>

							<id root="2.16.840.1.113883.4.8155" extension="' || vCount || '" />

							<code code="CONC" codeSystem="2.16.840.1.113883.5.6"/>

							<statusCode code="' || TRIM(allergyRec."ProblemActStatus") ||'" />

							<effectiveTime>

								<low value="' ||  TO_CHAR(NVL(allergyRec."OnsetDate", allergyRec."AddDateTime"), 'YYYYMMDD') || '" />

							</effectiveTime>



						   <entryRelationship typeCode="SUBJ">

								<observation classCode="OBS" moodCode="EVN">

								 <!-- allergy - intolerance observation template -->

									<templateId root="2.16.840.1.113883.10.20.22.4.7"/>

									<templateId root="2.16.840.1.113883.10.20.22.4.7" extension="2014-06-09"/>

								  <id root="2.16.840.1.113883.4.8155" extension="' || vCount || '" />

								  <code code="ASSERTION" codeSystem="2.16.840.1.113883.5.4"/>

								  <statusCode code="completed"/>

									<effectiveTime>

										<low value="' ||  TO_CHAR(NVL(allergyRec."OnsetDate", allergyRec."AddDateTime"), 'YYYYMMDD') || '" />

									</effectiveTime>

								  <value xsi:type="CD" code="416098002" displayName="drug allergy"

									 codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT">

									 <originalText>

										<reference value="#allergy' || vCount || '"/>

									 </originalText>

								  </value>

									<!-- Specific RxNorm-coded drug that the patient is allergic to -->

									<participant typeCode="CSM">

										<participantRole classCode="MANU">

											 <playingEntity classCode="MMAT">

												 <code code="' || TRIM(allergyRec."RxNorm") || '" displayName="' || TRIM(allergyRec."Description") || '"

													 codeSystem="2.16.840.1.113883.6.88" codeSystemName="RxNorm">

													 <originalText>

												  <reference value="#allergy' || vCount || '"/>

													 </originalText>

												 </code>

											 </playingEntity>

										</participantRole>

									</participant>

								</observation>

							</entryRelationship>

						</act>

					</entry> ');

				END IF;



			END LOOP;

			

			-- end table for human-readable data

			dbms_lob_s.append(vText, '

				  </tbody>

				</table>

				</text>');

				

			--handle corner case where there were allergies, but none of them were coded

			IF vCodedCount = 0 THEN

				-- machine-readable part

				-- AX-18696.19033

				dbms_lob_s.append(vEntries, '

				<entry typeCode="DRIV">

					<!-- Allergy Concern Act (there were allergies, but none of them were coded) -->

					<act classCode="ACT" moodCode="EVN">

						<templateId root="2.16.840.1.113883.10.20.22.4.30"/>

						<templateId root="2.16.840.1.113883.10.20.22.4.30" extension="2015-08-01"/>

						<id root="2.16.840.1.113883.4.8155" />

						<code code="CONC" codeSystem="2.16.840.1.113883.5.6"/>

						<statusCode code="active"/>

						<effectiveTime>

							<low nullFlavor="NA"/>

						</effectiveTime>

					

						<entryRelationship typeCode="SUBJ">

							<!-- No Known Allergies -->

							<!-- The negationInd = true negates the observation/value -->

							<!-- The use of negationInd corresponds with the newer Observation.valueNegationInd -->

							<observation classCode="OBS" moodCode="EVN" negationInd="true">

								<!-- allergy - intolerance observation template -->

								<templateId root="2.16.840.1.113883.10.20.22.4.7"/>

								<templateId root="2.16.840.1.113883.10.20.22.4.7" extension="2014-06-09"/>

								<id root="2.16.840.1.113883.4.8155" />

								<code code="ASSERTION" codeSystem="2.16.840.1.113883.5.4"/>

								<statusCode code="completed"/>

								<effectiveTime>

									<low nullFlavor="NA"/>

									<high nullFlavor="UNK"/>

								</effectiveTime>

								<value xsi:type="CD" code="419199007"

									displayName="Allergy to substance (disorder)"

									codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT"/>



								<!-- In C-CDA R2.1 the participant is required. -->

								<participant typeCode="CSM">

									<participantRole classCode="MANU">

											<playingEntity classCode="MMAT">

												<code nullFlavor="NA"/>

											</playingEntity>

									</participantRole>

								</participant>

							</observation>				      

						</entryRelationship>

					</act>

				</entry> ');	

			END IF;



			

		END IF;



		-- put it all together

		dbms_lob_s.append(vResult, vText);

		dbms_lob_s.append(vResult, vEntries);

		

		-- section footer

		dbms_lob_s.append(vResult, '

			</section>

			</component>');

			

		return vResult;

	END;

  

  

  -- AX-18945.19095

	FUNCTION getmedicationsection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob IS

		vResult CLOB := '';

		vText CLOB := '';

		vEntries CLOB := '';

		vCount NUMBER := 0;

    vTemp NUMBER := 0;



		CURSOR curMeds IS

			SELECT P.*, 

				PR."Name", 

				PR."City", 

				PR."Province", 

				PR."Postal", 

				PR."NPI", 

				PR."Area" AS "PracticeArea", 

				PR."Phone" AS "PracticePhone",

				DF."Value" as "Value",

				--- Samir_Boudjebla added the 5 lines below 

				DF."UnitCode" as "UnitCode",

				DF."SystemCode" as "SystemCode", 	

				RD."Code" as "RouteCode", 

				RD."CodeSystemName" as "RouteCodeSystemName", 

				RD."DisplayName" as "RouteDisplayName", 

				RD."SystemCode" as "RouteSystemCode"

			FROM Prescrip P, Practice PR 

			-- Samir_Boudjebla added 2 lines below, link to a new table which translates the DrugFrqDesc to values/units expected by the CCDA format

			, DrugFrqReferential DF

			, DrugRouteCode RD

            WHERE

				P."Patient" = vPId AND

				P."Deleted" = 0 AND

				P."PrescripType" = 0 AND

				P."ApprovalUser" <> 0 AND

				-- Samir_Boudjebla added the link below

				-- AX-25180 - made optional joins...

				p."DrugFrqDesc" like  ('%' || df."DrugFrqDescLike" (+)) and 

				P."RxNorm"= RD."RxNorm" (+) and

				P."Practice" = PR."Id" (+)

				-- AX-18945.19095

				AND 

				(

					(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(P."Date") >= TRUNC(vDate1) AND TRUNC(P."Date") <= TRUNC(vDate2))

					OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(P."Date") >= TRUNC(vDate1))

					OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(P."Date") <= TRUNC(vDate1)) 

					OR (vDate1 IS NULL)

				)

			ORDER BY P."EndDate", P."Date", P."Prescription";



		vMedicationsOnFile NUMBER := -1;

		vReviewsOnFile NUMBER := -1;

		vNoKnownMedications NUMBER := -1;

		vMedStatus  VARCHAR2(10) := NULL;



	   v_nCount		NUMBER := 0;								-- AX-26071.2

	BEGIN



		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetMedicationSection');

		IF v_nCount > 0 THEN

		  -- custom package function exists; AX-27290b 

		  EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetMedicationSection(:1, :2, :3, :4, :5) FROM DUAL' INTO vResult

							USING vPId, vbShowInfo, vIsDateFrom, vDate1, vDate2;

		  RETURN vResult;

		END IF;



		-- init clobs  

		dbms_lob_s.createtemporary (vResult, TRUE);

		dbms_lob_s.createtemporary (vText, TRUE);

		dbms_lob_s.createtemporary (vEntries, TRUE);



		--E143263.4 added

		IF NOT vbShowInfo THEN

			RETURN vResult;

		END IF;

		

		--B142586 - check for 0 rows and handle both reviewed and not reviewed cases

  		SELECT COUNT(1) INTO vMedicationsOnFile

		FROM Prescrip P, Practice PR WHERE

			P."Patient" = vPId AND

			P."Deleted" = 0 AND

			P."PrescripType" = 0 AND

			P."ApprovalUser" <> 0 AND

			P."Practice" = PR."Id" (+)

			-- AX-18945.19095

			AND 

			(

				(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(P."Date") >= TRUNC(vDate1) AND TRUNC(P."Date") <= TRUNC(vDate2))

				OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(P."Date") >= TRUNC(vDate1))

				OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND P."Date" <= vDate1) 

				OR (vDate1 IS NULL)

			);

  			

  		IF vMedicationsOnFile = 0 THEN

  			-- check if we've reviewed them

  			SELECT COUNT(1) INTO vReviewsOnFile

  			FROM EPREVIEW

  			WHERE 1=1 

  				AND "Patient" = vPId 

  				AND "Deleted" = 0

  				AND "Type" = 0;

  				

  			-- check if the most recent review indicates No Known Medications

  			IF vReviewsOnFile > 0 THEN

  			

  				SELECT "HasRecords" INTO vNoKnownMedications

  				FROM EPREVIEW

  				WHERE 1=1 

  					AND "EPReview" = (

  						SELECT MAX("EPReview") 

  						FROM EPREVIEW

  						WHERE 1=1

							AND "Patient" = vPId

							AND "Type" = 0

							AND "Deleted" = 0);

  			END IF;

		END IF;

  

		-- medications section header

		dbms_lob_s.append(vResult,

		'<component>

		    <section>

				<templateId root="2.16.840.1.113883.10.20.22.2.1.1" extension="2014-06-09"/>

				<templateId root="2.16.840.1.113883.10.20.22.2.1.1"/>

		       <code

			  code="10160-0"

			  codeSystem="2.16.840.1.113883.6.1"

			  codeSystemName="LOINC"

			  displayName="HISTORY OF MEDICATION USE"/>

		       <title>Medications</title>');

		       

		IF vNoKnownMedications = 0 THEN -- No known medications case

			--human readable part

			dbms_lob_s.append(vText, '<text>The patient has no known medications.</text>');

			

			--machine-readable part

			dbms_lob_s.append(vEntries, '

				<entry typeCode="DRIV">

				 <substanceAdministration moodCode="EVN" classCode="SBADM" negationInd="true">

				<templateId root="2.16.840.1.113883.10.20.22.4.16" extension="2014-06-09"/>

				<templateId root="2.16.840.1.113883.10.20.22.4.16"/>

				 <id root="2.16.840.1.113883.4.8155" />

				 <statusCode code="completed"/>

				 <effectiveTime xsi:type="IVL_TS">

				 	<low nullFlavor="NA"/>

				 	<high nullFlavor="NA"/>

				 </effectiveTime>

				 <doseQuantity nullFlavor="UNK"/>

				  <consumable>

				  <manufacturedProduct classCode="MANU">

				    <templateId root="2.16.840.1.113883.10.20.22.4.23" extension="2014-06-09"/>

					<templateId root="2.16.840.1.113883.10.20.22.4.23"/>

				    <manufacturedMaterial>

				     <code nullFlavor="NA"/>

				    </manufacturedMaterial>

				   </manufacturedProduct>

				  </consumable>

				 </substanceAdministration>

				</entry>');	

				

		ELSIF vMedicationsOnFile = 0 THEN -- No medications, but no reviews either

			--human readable part

			dbms_lob_s.append(vText, '<text>The patient has no medications on file, but this has not been reviewed.</text>');

			

			--machine-readable part		

			dbms_lob_s.append(vEntries, '

				<entry typeCode="DRIV">

				 <substanceAdministration moodCode="EVN" classCode="SBADM" negationInd="true">

				 <templateId root="2.16.840.1.113883.10.20.22.4.16" extension="2014-06-09"/>

				<templateId root="2.16.840.1.113883.10.20.22.4.16"/>

				 <id root="2.16.840.1.113883.4.8155" />

				 <statusCode code="completed"/>

				 <effectiveTime xsi:type="IVL_TS">

				 	<low nullFlavor="NA"/>

				 	<high nullFlavor="NA"/>	

				 </effectiveTime>

				 <doseQuantity nullFlavor="UNK"/>

				  <consumable>

				  <manufacturedProduct classCode="MANU">

				    <templateId root="2.16.840.1.113883.10.20.22.4.23" extension="2014-06-09"/>

					<templateId root="2.16.840.1.113883.10.20.22.4.23"/>

					<manufacturedMaterial>

				     <code nullFlavor="NA"/>

				    </manufacturedMaterial>

				   </manufacturedProduct>

				  </consumable>

				 </substanceAdministration>

				</entry>');		

					

		ELSE -- have medications



			--loop thru the meds

			FOR medRec in curMeds LOOP

				vCount := vCount + 1;

				

				IF vCount = 1 THEN

				  -- table for human-readable part

				  dbms_lob_s.append(vText, '           

					<text>

						<table border="1" width="100%">

							<thead>

								<tr>

									<th>Medication</th>

									<th>Sig</th>

									<th>Start Date</th>

									<th>End Date</th>

									<th>Status</th>

								</tr>

							</thead>

							<tbody>');

				END IF;



			    

			    --determine status

			    IF medRec."IsVoided" = 1 THEN

			    	vMedStatus := 'Voided';			

			    ELSIF TRUNC(NVL(medRec."StartDate", SYSDATE-1)) > SYSDATE THEN

			    	vMedStatus := 'Pending';

			    ELSIF TRUNC(NVL(medRec."EndDate", SYSDATE+1)) < SYSDATE THEN 

			    	vMedStatus := 'Completed';

			    ELSE

			    	vMedStatus := 'Active';

			    END IF;

			    

			    -- text section

			    dbms_lob_s.append(vText, '

						    <tr>

							<td><content ID="med' || vCount  || '">' || htf.escape_sc(medRec."DrugDescription") || '</content></td>

							<td><content ID="frq-med' || vCount  || '">' || htf.escape_sc(medRec."DrugFrqDesc") || '</content></td>

							<td>' || TO_CHAR(medRec."StartDate", 'MM/DD/YYYY') || '</td>

							<td>' || TO_CHAR(medRec."EndDate", 'MM/DD/YYYY') || '</td>

							<td>' || vMedStatus || '</td>		

						    </tr>

			    	');



		            --coded entry section

			    dbms_lob_s.append(vEntries, '

			    <entry typeCode="DRIV">

			      <substanceAdministration classCode="SBADM" moodCode="EVN">

				<templateId root="2.16.840.1.113883.10.20.22.4.16" extension="2014-06-09"/>

				<templateId root="2.16.840.1.113883.10.20.22.4.16"/>

				<id root="2.16.840.1.113883.4.8155" />

				<text><reference value="#med' || vCount  || '"/>' || htf.escape_sc(medRec."DrugDescription") || ' - ' || htf.escape_sc(medRec."Dose") || '</text>

				<statusCode code="completed"/>

				<effectiveTime xsi:type="IVL_TS"> ');



			    IF medRec."StartDate" IS NOT NULL THEN

			    dbms_lob_s.append(vEntries, '

				  <low value="' || TO_CHAR(medRec."StartDate", 'YYYYMMDD') || '"/>');

			    ELSE

			    dbms_lob_s.append(vEntries, '

				  <low nullFlavor="UNK"/>');

			    END IF;





			    IF medRec."EndDate" IS NOT NULL THEN

			    dbms_lob_s.append(vEntries, '

				  <high value="' || TO_CHAR(medRec."EndDate", 'YYYYMMDD') || '"/>');

			    ELSE

			    dbms_lob_s.append(vEntries, '

				  <high nullFlavor="UNK"/>');

			    END IF;



			    dbms_lob_s.append(vEntries, '

				</effectiveTime>');

--------- Samir_Boudjebla need to change this line to reflect the doses and units and frequencies

--- Probably need to replace the code below if medRef."Dose" ........

/*

        

							<td><content ID="med' || vCount  || '">' || htf.escape_sc(medRec."DrugDescription") || '</content></td>

							<td><content ID="frq-med' || vCount  || '">' || htf.escape_sc(medRec."DrugFrqDesc") || '</content></td>



*/

        IF medRec."Dose" IS NOT NULL AND LENGTH(TRIM(medRec."Dose")) > 0 THEN

            IF medRec."SystemCode"='2.16.840.1.113883.5.139'THEN   

                dbms_lob_s.append(vEntries, '

                <effectiveTime xsi:type="EIVL_TS" operator="A">

                        <event code="' || medRec."UnitCode" || '"/>

				</effectiveTime>'	

								);

            Else

                dbms_lob_s.append(vEntries, '

                 <effectiveTime xsi:type="PIVL_TS" operator="A">

							<period value="' || medRec."Value" || '" unit="'|| medRec."UnitCode"|| '"/>

                </effectiveTime>');    

            END IF;

		ELSE

			dbms_lob_s.append(vEntries, '

			<doseQuantity nullFlavor="UNK"/>');

        END IF;



------ Route Code <routeCode code="C38288" codeSystem="2.16.840.1.113883.3.26.1.1" codeSystemName="NCI Thesaurus" displayName="ORAL"/>

        IF medRec."RouteCode" IS NOT NULL  THEN

            dbms_lob_s.append(vEntries, '

                <routeCode code="' || medRec."RouteCode" || '"  codeSystem="'|| medRec."RouteSystemCode" ||'" codeSystemName="'

                || medRec."RouteCodeSystemName" ||'"  displayName="'|| medRec."RouteDisplayName"|| '" />'	

								);

        END IF;





  -------SAMIR_Boudjebla - end of the modifictions     --------------------------------------------------------------------------







        IF medRec."Dose" IS NOT NULL AND LENGTH(TRIM(medRec."Dose")) > 0 THEN

          -- check for space. Assume before = value, unit = after

          SELECT INSTR(medRec."Dose", ' ') INTO vTemp FROM DUAL;

        

				-- AX-18945.19094g

          IF vTemp > 0 THEN

            dbms_lob_s.append(vEntries, '

            <doseQuantity value="' || 1 || '"/>');

          ELSE

           dbms_lob_s.append(vEntries, '

           <doseQuantity value="' || 1 || '"/>');

          END IF;

		ELSE

			dbms_lob_s.append(vEntries, '

			<doseQuantity nullFlavor="UNK"/>');

        END IF;

        

        dbms_lob_s.append(vEntries, '

				<consumable>

				  <manufacturedProduct classCode="MANU">

				    <templateId root="2.16.840.1.113883.10.20.22.4.23" extension="2014-06-09"/>

					<templateId root="2.16.840.1.113883.10.20.22.4.23"/>

		

				      <manufacturedMaterial>

				      <code code="' || NVL(trim(medRec."RxNorm"), 'UNK') || '" codeSystem="2.16.840.1.113883.6.88" displayName="'|| htf.escape_sc(medRec."DrugDescription") || '">

					<originalText><reference value="#med' || vCount  || '"/></originalText>

					  <translation code="' || NVL(trim(medRec."RxNorm"), 'UNK') || '"

							    displayName="' || htf.escape_sc(medRec."DrugDescription") || '"

							    codeSystem="2.16.840.1.113883.6.88"

							    codeSystemName="RxNorm"/>

				      </code>

				      </manufacturedMaterial>

				      </manufacturedProduct>

				  </consumable>

          

          <entryRelationship typeCode="SUBJ" inversionInd="true">

								<act classCode="ACT" moodCode="INT">

									<templateId root="2.16.840.1.113883.10.20.22.4.20"/>

									<code code="423564006" displayName="Provider instructions for treatment" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT"/>

									<text>

										<reference value="#frq-med' || vCount  || '"/>

									</text>

									<statusCode code="completed"/>

								</act>

							</entryRelationship>

				</substanceAdministration>

			      </entry>');



			  END LOOP;



            IF vCount > 0 THEN

			   dbms_lob_s.append(vText, '

						</tbody>

					</table>

				</text>');

			END IF;

		

		END IF;

                  

                -- put it all together

		dbms_lob_s.append(vResult, vText);

		dbms_lob_s.append(vResult, vEntries);



		-- section footer

		dbms_lob_s.append(vResult, '

		</section>

		</component>');



		return vResult;

	END;

  

	-- E142551 - Reason for Referral 

	-- Looks for the most recently created 'referral' form, and uses the most recently approved referral reason on that form

	-- AX-18945.19095

	FUNCTION getreasonforreferralsection(vpid numeric, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob IS

		vResult CLOB := '';

		

		-- reference codes used

		vFormCode PFORM."FormCode"%TYPE := 'MUREF';

		vRefReasonRefCode FITEM."Code"%TYPE := 'MUREFR';

		vRefDateRefCode FITEM."Code"%TYPE := 'MUREFDATE';

		vRefDocNameRefCode FITEM."Code"%TYPE := 'MUREFDOC';

		vRefDocAddr1RefCode FITEM."Code"%TYPE := 'MUREFADDR1';

		vRefDocAddr2RefCode FITEM."Code"%TYPE := 'MUREFADDR2';

		vRefDocCityRefCode FITEM."Code"%TYPE := 'MUREFCITY';

		vRefDocStateRefCode FITEM."Code"%TYPE := 'MUREFSTATE';

		vRefDocZIPRefCode FITEM."Code"%TYPE := 'MUREFZIP';

		vRefDocPhoneRefCode FITEM."Code"%TYPE := 'MUREFPHONE';



		-- local vars

		vHasReferral NUMBER := 0;

		vMostRecentRefForm PFORM."PForm"%TYPE := NULL;

		

		vRefReasonText PITEM."AnsText"%TYPE := NULL;

		vRefDateText PITEM."AnsText"%TYPE := NULL;

		vRefDocNameText PITEM."AnsText"%TYPE := NULL;

		vRefDocAddr1Text PITEM."AnsText"%TYPE := NULL;

		vRefDocAddr2Text PITEM."AnsText"%TYPE := NULL;

		vRefDocCityText PITEM."AnsText"%TYPE := NULL;

		vRefDocStateText PITEM."AnsText"%TYPE := NULL;

		vRefDocZIPText PITEM."AnsText"%TYPE := NULL;

		vRefDocPhoneText PITEM."AnsText"%TYPE := NULL;

	   v_nCount		NUMBER := 0;								-- AX-26071.2



	BEGIN



		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetReasonForReferralSection');

		IF v_nCount > 0 THEN

		  -- custom package function exists; AX-27290b 

		  EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetReasonForReferralSection(:1, :2, :3, :4) FROM DUAL' INTO vResult

						USING vPId, vIsDateFrom, vDate1, vDate2;

		  RETURN vResult;

		END IF;



		-- init clob

		dbms_lob_s.createtemporary (vResult, TRUE);



		-- check if the patient actually has any referrals on file

		BEGIN

			SELECT COUNT(PF."PForm") INTO vHasReferral

			FROM PFORM PF

			WHERE 1=1

				AND PF."Patient" = vPId

				AND PF."FormCode"= vFormCode

				-- AX-18945.19095

				AND 

				(

					(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PF."Date") >= TRUNC(vDate1) AND TRUNC(PF."Date") <= TRUNC(vDate2))

					OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PF."Date") >= TRUNC(vDate1))

					OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PF."Date") <= TRUNC(vDate1)) 

					OR (vDate1 IS NULL)

				);

		

		EXCEPTION WHEN OTHERS THEN

			vHasReferral := 0; -- some error, we can't find a referral

		END;

		

		IF vHasReferral > 0 THEN

			-- has at least one referral on file - find the latest one.

			BEGIN

				SELECT MAX(PF."PForm") INTO vMostRecentRefForm

				FROM PFORM PF

				WHERE 1=1

					AND PF."Patient" = vPId

					AND PF."FormCode" = vFormCode

					-- AX-18945.19095

					AND 

					(

						(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PF."Date") >= TRUNC(vDate1) AND TRUNC(PF."Date") <= TRUNC(vDate2))

						OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PF."Date") >= TRUNC(vDate1))

						OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PF."Date") <= TRUNC(vDate1)) 

						OR (vDate1 IS NULL)

					);

			END;

			

			-- get the referral reason - assumes this is stored in a long-text question on a form 

			BEGIN

				SELECT TRIM(htf.escape_sc(PI."AnsText")) INTO vRefReasonText

				FROM PITEM PI, FITEM FI

				WHERE 1=1 

					AND PI."FItem" = FI."FItem"

					AND PI."Patient" = vPId

					AND FI."Code" = vRefReasonRefCode  

					AND PI."PForm" = vMostRecentRefForm

					AND PI."AuditNumber" =     

						(SELECT MAX(PI2."AuditNumber")

						FROM PITEM PI2, FITEM FI2

						WHERE 1=1 

							AND PI2."FItem" = FI2."FItem"

							AND PI2."Patient" = vPId

							AND FI2."Code" = vRefReasonRefCode 

							AND FI2."Deleted" = 0

							AND PI2."AppDate" IS NOT NULL

							AND PI2."PForm" = vMostRecentRefForm

							-- AX-18945.19095

							AND 

							(

								(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

								OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

								OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

								OR (vDate1 IS NULL)

							));





			EXCEPTION WHEN OTHERS THEN

				vRefReasonText := NULL;

			END;



			-- get the referral planned date - assumes this is stored in a date question on a form 

			BEGIN

				SELECT TO_CHAR(PI."AnsDate", 'MM/DD/YYYY') INTO vRefDateText

				FROM PITEM PI, FITEM FI

				WHERE 1=1 

					AND PI."FItem" = FI."FItem"

					AND PI."Patient" = vPId

					AND FI."Code" = vRefDateRefCode  

					AND PI."PForm" = vMostRecentRefForm

					AND PI."AuditNumber" =     

						(SELECT MAX(PI2."AuditNumber")

						FROM PITEM PI2, FITEM FI2

						WHERE 1=1 

							AND PI2."FItem" = FI2."FItem"

							AND PI2."Patient" = vPId

							AND FI2."Code" = vRefDateRefCode 

							AND FI2."Deleted" = 0

							AND PI2."AppDate" IS NOT NULL

							AND PI2."PForm" = vMostRecentRefForm

							-- AX-18945.19095

							AND 

							(

								(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

								OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

								OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

								OR (vDate1 IS NULL)

							));



			EXCEPTION WHEN OTHERS THEN

				vRefDateText := NULL;

			END;



			-- get the name of the provider that the patient is being referred to - assumes stored in text question on form

			BEGIN

				SELECT TRIM(htf.escape_sc(PI."AnsText")) INTO vRefDocNameText

				FROM PITEM PI, FITEM FI

				WHERE 1=1 

					AND PI."FItem" = FI."FItem"

					AND PI."Patient" = vPId

					AND FI."Code" = vRefDocNameRefCode  

					AND PI."PForm" = vMostRecentRefForm

					AND PI."AuditNumber" =     

						(SELECT MAX(PI2."AuditNumber")

						FROM PITEM PI2, FITEM FI2

						WHERE 1=1 

							AND PI2."FItem" = FI2."FItem"

							AND PI2."Patient" = vPId

							AND FI2."Code" = vRefDocNameRefCode 

							AND FI2."Deleted" = 0

							AND PI2."AppDate" IS NOT NULL

							AND PI2."PForm" = vMostRecentRefForm

							-- AX-18945.19095

							AND 

							(

								(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

								OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

								OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

								OR (vDate1 IS NULL)

							));



			EXCEPTION WHEN OTHERS THEN

				vRefDocNameText := NULL;

			END;



			-- get the first address line of the provider that the patient is being referred to - assumes stored in text question on form

			BEGIN

				SELECT TRIM(htf.escape_sc(PI."AnsText")) INTO vRefDocAddr1Text

				FROM PITEM PI, FITEM FI

				WHERE 1=1 

					AND PI."FItem" = FI."FItem"

					AND PI."Patient" = vPId

					AND FI."Code" = vRefDocAddr1RefCode  

					AND PI."PForm" = vMostRecentRefForm

					AND PI."AuditNumber" =     

						(SELECT MAX(PI2."AuditNumber")

						FROM PITEM PI2, FITEM FI2

						WHERE 1=1 

							AND PI2."FItem" = FI2."FItem"

							AND PI2."Patient" = vPId

							AND FI2."Code" = vRefDocAddr1RefCode 

							AND FI2."Deleted" = 0

							AND PI2."AppDate" IS NOT NULL

							AND PI2."PForm" = vMostRecentRefForm

							-- AX-18945.19095

							AND 

							(

								(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

								OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

								OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

								OR (vDate1 IS NULL)

							));



			EXCEPTION WHEN OTHERS THEN

				vRefDocAddr1Text := NULL;

			END;		



			-- get the second address line of the provider that the patient is being referred to - assumes stored in text question on form

			BEGIN

				SELECT TRIM(htf.escape_sc(PI."AnsText")) INTO vRefDocAddr2Text

				FROM PITEM PI, FITEM FI

				WHERE 1=1 

					AND PI."FItem" = FI."FItem"

					AND PI."Patient" = vPId

					AND FI."Code" = vRefDocAddr2RefCode  

					AND PI."PForm" = vMostRecentRefForm

					AND PI."AuditNumber" =     

						(SELECT MAX(PI2."AuditNumber")

						FROM PITEM PI2, FITEM FI2

						WHERE 1=1 

							AND PI2."FItem" = FI2."FItem"

							AND PI2."Patient" = vPId

							AND FI2."Code" = vRefDocAddr2RefCode 

							AND FI2."Deleted" = 0

							AND PI2."AppDate" IS NOT NULL

							AND PI2."PForm" = vMostRecentRefForm

							-- AX-18945.19095

							AND 

							(

								(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

								OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

								OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

								OR (vDate1 IS NULL)

							));



			EXCEPTION WHEN OTHERS THEN

				vRefDocAddr2Text := NULL;

			END;	



			-- get the city of the provider that the patient is being referred to - assumes stored in text question on form

			BEGIN

				SELECT TRIM(htf.escape_sc(PI."AnsText")) INTO vRefDocCityText

				FROM PITEM PI, FITEM FI

				WHERE 1=1 

					AND PI."FItem" = FI."FItem"

					AND PI."Patient" = vPId

					AND FI."Code" = vRefDocCityRefCode  

					AND PI."PForm" = vMostRecentRefForm

					AND PI."AuditNumber" =     

						(SELECT MAX(PI2."AuditNumber")

						FROM PITEM PI2, FITEM FI2

						WHERE 1=1 

							AND PI2."FItem" = FI2."FItem"

							AND PI2."Patient" = vPId

							AND FI2."Code" = vRefDocCityRefCode 

							AND FI2."Deleted" = 0

							AND PI2."AppDate" IS NOT NULL

							AND PI2."PForm" = vMostRecentRefForm

							-- AX-18945.19095

							AND 

							(

								(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

								OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

								OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

								OR (vDate1 IS NULL)

							));



			EXCEPTION WHEN OTHERS THEN

				vRefDocCityText := NULL;

			END;



			-- get the state of the provider that the patient is being referred to - assumes stored in text question on form

			BEGIN

				SELECT TRIM(htf.escape_sc(PI."AnsText")) INTO vRefDocStateText

				FROM PITEM PI, FITEM FI

				WHERE 1=1 

					AND PI."FItem" = FI."FItem"

					AND PI."Patient" = vPId

					AND FI."Code" = vRefDocStateRefCode  

					AND PI."PForm" = vMostRecentRefForm

					AND PI."AuditNumber" =     

						(SELECT MAX(PI2."AuditNumber")

						FROM PITEM PI2, FITEM FI2

						WHERE 1=1 

							AND PI2."FItem" = FI2."FItem"

							AND PI2."Patient" = vPId

							AND FI2."Code" = vRefDocStateRefCode 

							AND FI2."Deleted" = 0

							AND PI2."AppDate" IS NOT NULL

							AND PI2."PForm" = vMostRecentRefForm

							-- AX-18945.19095

							AND 

							(

								(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

								OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

								OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

								OR (vDate1 IS NULL)

							));



			EXCEPTION WHEN OTHERS THEN

				vRefDocStateText := NULL;

			END;



			-- get the ZIP of the provider that the patient is being referred to - assumes stored in text question on form

			BEGIN

				SELECT TRIM(htf.escape_sc(PI."AnsText")) INTO vRefDocZIPText

				FROM PITEM PI, FITEM FI

				WHERE 1=1 

					AND PI."FItem" = FI."FItem"

					AND PI."Patient" = vPId

					AND FI."Code" = vRefDocZIPRefCode  

					AND PI."PForm" = vMostRecentRefForm

					AND PI."AuditNumber" =     

						(SELECT MAX(PI2."AuditNumber")

						FROM PITEM PI2, FITEM FI2

						WHERE 1=1 

							AND PI2."FItem" = FI2."FItem"

							AND PI2."Patient" = vPId

							AND FI2."Code" = vRefDocZIPRefCode 

							AND FI2."Deleted" = 0

							AND PI2."AppDate" IS NOT NULL

							AND PI2."PForm" = vMostRecentRefForm

							-- AX-18945.19095

							AND 

							(

								(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

								OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

								OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

								OR (vDate1 IS NULL)

							));



			EXCEPTION WHEN OTHERS THEN

				vRefDocZIPText := NULL;

			END;		



			-- get the phone number of the provider that the patient is being referred to - assumes stored in text question on form

			BEGIN

				SELECT TRIM(htf.escape_sc(PI."AnsText")) INTO vRefDocPhoneText

				FROM PITEM PI, FITEM FI

				WHERE 1=1 

					AND PI."FItem" = FI."FItem"

					AND PI."Patient" = vPId

					AND FI."Code" = vRefDocPhoneRefCode  

					AND PI."PForm" = vMostRecentRefForm

					AND PI."AuditNumber" =     

						(SELECT MAX(PI2."AuditNumber")

						FROM PITEM PI2, FITEM FI2

						WHERE 1=1 

							AND PI2."FItem" = FI2."FItem"

							AND PI2."Patient" = vPId

							AND FI2."Code" = vRefDocPhoneRefCode 

							AND FI2."Deleted" = 0

							AND PI2."AppDate" IS NOT NULL

							AND PI2."PForm" = vMostRecentRefForm

							-- AX-18945.19095

							AND 

							(

								(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

								OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

								OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

								OR (vDate1 IS NULL)

							));



			EXCEPTION WHEN OTHERS THEN

				vRefDocPhoneText := NULL;

			END;				

		END IF;

		

		-- write out XML

		dbms_lob_s.append(vResult, '

			 <component>

			    <section>

			       <templateId

				  root="1.3.6.1.4.1.19376.1.5.3.1.3.1"/>

			       <!-- ** Reason for Referral Section Template ** -->

			       <code

				  codeSystem="2.16.840.1.113883.6.1"

				  codeSystemName="LOINC"

				  code="42349-1"

				  displayName="REASON FOR REFERRAL"/>

			       <title>Reason for Referral</title>');

		

			-- text section

			IF vHasReferral = 0 THEN

				-- no referral on file. 

				dbms_lob_s.append(vResult, '

					<text>No referral information is available.</text>');

			ELSE

				-- have a referral, show the details of it

				

				dbms_lob_s.append(vResult, '

					<text>

						<table border="1" width="100%">

							<tbody>

								<tr>

									<th colspan="2">Referral Information</th>

								</tr>

								<tr>

									<th align="left">Referral Reason</th>

									<td>' || NVL(vRefReasonText, ' ') ||'</td>

								</tr>

								<tr>

									<th align="left">Referred To</th>

									<td>' || NVL(vRefDocNameText, ' ') ||'</td>

								</tr>

								<tr>

									<th rowspan="3" align="left">Address</th>

									<td>' || NVL(vRefDocAddr1Text, ' ') || '</td>

								</tr>

									<tr><td>' || NVL(vRefDocAddr2Text, ' ') || '</td></tr> 

									<tr><td>' || NVL(vRefDocCityText, ' ') || ', ' || NVL(vRefDocStateText, ' ') || ' ' || NVL(vRefDocZIPText, ' ') || '</td></tr>

								

								<tr>

									<th align="left">Phone</th>

									<td>' || NVL(vRefDocPhoneText, ' ') ||'</td>

								</tr>

								<tr>

									<th align="left">Referral Date</th>

									<td>' || NVL(vRefDateText, ' ') ||'</td>

								</tr>

							</tbody>

						</table>

					</text>');

	

			END IF;

		

		dbms_lob_s.append(vResult, '

			    </section>

			 </component>');



		RETURN vResult;

		

	END;

  

  

   

  FUNCTION getreasonforvisitsection(vapptid numeric, vbshowinfo boolean DEFAULT true) RETURN clob IS

    vResult CLOB := '';

    vReason CLOB := '';

	   v_nCount		NUMBER := 0;								-- AX-26071.2



  BEGIN



	--AX-26071.2

	SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetReasonForVisitSection');

	IF v_nCount > 0 THEN

		-- custom package function exists 

		EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetReasonForVisitSection('||vApptId||',:1) FROM DUAL' INTO vResult

							USING vbShowInfo;

		RETURN vResult;

	END IF;



  

  dbms_lob_s.createtemporary (vResult, TRUE);

  dbms_lob_s.createtemporary (vReason, TRUE);

  

  SELECT htf.escape_sc("Reason") into vReason FROM APPOINT WHERE "Appointment" = vApptId;

  

  

  -- E143263.4 added

  IF NOT vbShowInfo THEN 



		dbms_lob_s.append(vResult, '

		 <component>

            <section>

               <templateId root="2.16.840.1.113883.10.20.22.2.12"/>

                    <id root="2.16.840.1.113883.4.8155" />

                    <code nullFlavor="UNK"/>

                    <title>Reason for Visit</title>

                    <text>

                    </text>

            </section>

         </component>');



  ELSE 

		dbms_lob_s.append(vResult, '

		<component>

            <section>

               <templateId root="2.16.840.1.113883.10.20.22.2.12"/>

                    <id root="2.16.840.1.113883.4.8155" />

                    <code code="29299-5" displayName="Reason for Visit"

                        codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC"/>

                    <title>Reason for Visit</title>

                    <text>' || vReason || '</text>

            </section>

         </component>');

         

  END IF;

  

  return vResult;

  END;

  

  			

	-- helper function to return the rows for referrals in the clinical visit summary

	FUNCTION getreferralinfovisit(vpid numeric, vpform numeric) RETURN character varying IS

		-- reference codes used

		vFormCode PFORM."FormCode"%TYPE := 'MUREF';

		vRefReasonRefCode FITEM."Code"%TYPE := 'MUREFR';

		vRefDateRefCode FITEM."Code"%TYPE := 'MUREFDATE';

		vRefDocNameRefCode FITEM."Code"%TYPE := 'MUREFDOC';

		vRefDocAddr1RefCode FITEM."Code"%TYPE := 'MUREFADDR1';

		vRefDocAddr2RefCode FITEM."Code"%TYPE := 'MUREFADDR2';

		vRefDocCityRefCode FITEM."Code"%TYPE := 'MUREFCITY';

		vRefDocStateRefCode FITEM."Code"%TYPE := 'MUREFSTATE';

		vRefDocZIPRefCode FITEM."Code"%TYPE := 'MUREFZIP';

		vRefDocPhoneRefCode FITEM."Code"%TYPE := 'MUREFPHONE';

	

		-- for holding the answer

		vRefDoctor PITEM."AnsText"%TYPE := '';

		vRefPhone PITEM."AnsText"%TYPE := '';

		vRefAddr1 PITEM."AnsText"%TYPE := '';

		vRefAddr2 PITEM."AnsText"%TYPE := '';

		vRefCity PITEM."AnsText"%TYPE := '';

		vRefState PITEM."AnsText"%TYPE := '';

		vRefZIP PITEM."AnsText"%TYPE := '';

		vRefDate PITEM."AnsDate"%TYPE := NULL;

		vRefReason PITEM."AnsText"%TYPE := '';

		

	    vResult  VARCHAR2(4000);

   	 v_nCount		NUMBER := 0;								-- AX-26071.2

BEGIN



		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetReferralInfoVisit');

		IF v_nCount > 0 THEN

			-- custom package function exists 

			EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetReferralInfoVisit('||vPId||','||vPForm||') FROM DUAL' INTO vResult;

			RETURN vResult;

		END IF;



		-- get the data

		-- referral doctor

		BEGIN

			SELECT TRIM(htf.escape_sc(PI."AnsText")) INTO vRefDoctor

			FROM PITEM PI, FITEM FI

			WHERE 1=1 

				AND PI."FItem" = FI."FItem"

				AND PI."Patient" = vPId

				AND FI."Code" = vRefDocNameRefCode  

				AND PI."PForm" = vPForm

				AND PI."AuditNumber" =     

					(SELECT MAX(PI2."AuditNumber")

					FROM PITEM PI2, FITEM FI2

					WHERE 1=1 

						AND PI2."FItem" = FI2."FItem"

						AND PI2."Patient" = vPId

						AND FI2."Code" = vRefDocNameRefCode 

						AND FI2."Deleted" = 0

						AND PI2."AppDate" IS NOT NULL

						AND PI2."PForm" = vPForm);



		EXCEPTION WHEN OTHERS THEN

			vRefDoctor := '';

		END;

		

		-- referral phone

		BEGIN

			SELECT TRIM(htf.escape_sc(PI."AnsText")) INTO vRefPhone

			FROM PITEM PI, FITEM FI

			WHERE 1=1 

				AND PI."FItem" = FI."FItem"

				AND PI."Patient" = vPId

				AND FI."Code" = vRefDocPhoneRefCode  

				AND PI."PForm" = vPForm

				AND PI."AuditNumber" =     

					(SELECT MAX(PI2."AuditNumber")

					FROM PITEM PI2, FITEM FI2

					WHERE 1=1 

						AND PI2."FItem" = FI2."FItem"

						AND PI2."Patient" = vPId

						AND FI2."Code" = vRefDocPhoneRefCode 

						AND FI2."Deleted" = 0

						AND PI2."AppDate" IS NOT NULL

						AND PI2."PForm" = vPForm);



		EXCEPTION WHEN OTHERS THEN

			vRefPhone := '';

		END;

		

		-- addr1

		BEGIN

			SELECT TRIM(htf.escape_sc(PI."AnsText")) INTO vRefAddr1

			FROM PITEM PI, FITEM FI

			WHERE 1=1 

				AND PI."FItem" = FI."FItem"

				AND PI."Patient" = vPId

				AND FI."Code" = vRefDocAddr1RefCode  

				AND PI."PForm" = vPForm

				AND PI."AuditNumber" =     

					(SELECT MAX(PI2."AuditNumber")

					FROM PITEM PI2, FITEM FI2

					WHERE 1=1 

						AND PI2."FItem" = FI2."FItem"

						AND PI2."Patient" = vPId

						AND FI2."Code" = vRefDocAddr1RefCode 

						AND FI2."Deleted" = 0

						AND PI2."AppDate" IS NOT NULL

						AND PI2."PForm" = vPForm);



		EXCEPTION WHEN OTHERS THEN

			vRefAddr1 := '';

		END;

		

		-- addr2

		BEGIN

			SELECT TRIM(htf.escape_sc(PI."AnsText")) INTO vRefAddr2

			FROM PITEM PI, FITEM FI

			WHERE 1=1 

				AND PI."FItem" = FI."FItem"

				AND PI."Patient" = vPId

				AND FI."Code" = vRefDocAddr2RefCode  

				AND PI."PForm" = vPForm

				AND PI."AuditNumber" =     

					(SELECT MAX(PI2."AuditNumber")

					FROM PITEM PI2, FITEM FI2

					WHERE 1=1 

						AND PI2."FItem" = FI2."FItem"

						AND PI2."Patient" = vPId

						AND FI2."Code" = vRefDocAddr2RefCode 

						AND FI2."Deleted" = 0

						AND PI2."AppDate" IS NOT NULL

						AND PI2."PForm" = vPForm);



		EXCEPTION WHEN OTHERS THEN

			vRefAddr2 := '';

		END;		

		



		-- city

		BEGIN

			SELECT TRIM(htf.escape_sc(PI."AnsText")) INTO vRefCity

			FROM PITEM PI, FITEM FI

			WHERE 1=1 

				AND PI."FItem" = FI."FItem"

				AND PI."Patient" = vPId

				AND FI."Code" = vRefDocCityRefCode  

				AND PI."PForm" = vPForm

				AND PI."AuditNumber" =     

					(SELECT MAX(PI2."AuditNumber")

					FROM PITEM PI2, FITEM FI2

					WHERE 1=1 

						AND PI2."FItem" = FI2."FItem"

						AND PI2."Patient" = vPId

						AND FI2."Code" = vRefDocCityRefCode 

						AND FI2."Deleted" = 0

						AND PI2."AppDate" IS NOT NULL

						AND PI2."PForm" = vPForm);



		EXCEPTION WHEN OTHERS THEN

			vRefCity := '';

		END;



		-- state

		BEGIN

			SELECT TRIM(htf.escape_sc(PI."AnsText")) INTO vRefState

			FROM PITEM PI, FITEM FI

			WHERE 1=1 

				AND PI."FItem" = FI."FItem"

				AND PI."Patient" = vPId

				AND FI."Code" = vRefDocStateRefCode  

				AND PI."PForm" = vPForm

				AND PI."AuditNumber" =     

					(SELECT MAX(PI2."AuditNumber")

					FROM PITEM PI2, FITEM FI2

					WHERE 1=1 

						AND PI2."FItem" = FI2."FItem"

						AND PI2."Patient" = vPId

						AND FI2."Code" = vRefDocStateRefCode 

						AND FI2."Deleted" = 0

						AND PI2."AppDate" IS NOT NULL

						AND PI2."PForm" = vPForm);



		EXCEPTION WHEN OTHERS THEN

			vRefState := '';

		END;



		-- zip

		BEGIN

			SELECT TRIM(htf.escape_sc(PI."AnsText")) INTO vRefZIP

			FROM PITEM PI, FITEM FI

			WHERE 1=1 

				AND PI."FItem" = FI."FItem"

				AND PI."Patient" = vPId

				AND FI."Code" = vRefDocZIPRefCode  

				AND PI."PForm" = vPForm

				AND PI."AuditNumber" =     

					(SELECT MAX(PI2."AuditNumber")

					FROM PITEM PI2, FITEM FI2

					WHERE 1=1 

						AND PI2."FItem" = FI2."FItem"

						AND PI2."Patient" = vPId

						AND FI2."Code" = vRefDocZIPRefCode 

						AND FI2."Deleted" = 0

						AND PI2."AppDate" IS NOT NULL

						AND PI2."PForm" = vPForm);



		EXCEPTION WHEN OTHERS THEN

			vRefZIP := '';

		END;



		-- referral date

		BEGIN

			SELECT PI."AnsDate" INTO vRefDate

			FROM PITEM PI, FITEM FI

			WHERE 1=1 

				AND PI."FItem" = FI."FItem"

				AND PI."Patient" = vPId

				AND FI."Code" = vRefDateRefCode  

				AND PI."PForm" = vPForm

				AND PI."AuditNumber" =     

					(SELECT MAX(PI2."AuditNumber")

					FROM PITEM PI2, FITEM FI2

					WHERE 1=1 

						AND PI2."FItem" = FI2."FItem"

						AND PI2."Patient" = vPId

						AND FI2."Code" = vRefDateRefCode 

						AND FI2."Deleted" = 0

						AND PI2."AppDate" IS NOT NULL

						AND PI2."PForm" = vPForm);



		EXCEPTION WHEN OTHERS THEN

			vRefDate := NULL;

		END;

		

		-- referral reason

		BEGIN

			SELECT TRIM(htf.escape_sc(PI."AnsText")) INTO vRefReason

			FROM PITEM PI, FITEM FI

			WHERE 1=1 

				AND PI."FItem" = FI."FItem"

				AND PI."Patient" = vPId

				AND FI."Code" = vRefReasonRefCode  

				AND PI."PForm" = vPForm

				AND PI."AuditNumber" =     

					(SELECT MAX(PI2."AuditNumber")

					FROM PITEM PI2, FITEM FI2

					WHERE 1=1 

						AND PI2."FItem" = FI2."FItem"

						AND PI2."Patient" = vPId

						AND FI2."Code" = vRefReasonRefCode 

						AND FI2."Deleted" = 0

						AND PI2."AppDate" IS NOT NULL

						AND PI2."PForm" = vPForm);



		EXCEPTION WHEN OTHERS THEN

			vRefReason := '';

		END;

	

		-- construct the text entry

		RETURN '

			<tr>

				<td>' || TRIM(vRefDoctor) || '</td>

				<td>' || TRIM(vRefPhone) || '</td>

				<td>' || TRIM(vRefAddr1) || ' ' || TRIM(vRefAddr2) || ', ' || TRIM(vRefCity) || ', ' || TRIM(vRefState) || ' ' || TRIM(vRefZIP) || '</td>

				<td>' || TO_CHAR(vRefDate, 'MM/DD/YYYY') || '</td>

				<td>' || TRIM(vRefReason) || '</td>

			</tr>';

	

	END;

	

  	

  	-- scheduled imaging

 	FUNCTION getschedimginfovisit(vpid numeric, vpform numeric) RETURN character varying IS

		-- reference codes used

		vFormCode PFORM."FormCode"%TYPE := 'O_RADI';

		vSchedTypeRefCode FITEM."Code"%TYPE := 'O_RADIDETL';

		vSchedDateRefCode FITEM."Code"%TYPE := 'O_RADISDAT';

	

		-- for holding the answer

		vSchedType PITEM."AnsText"%TYPE := '';

		vSchedDate PITEM."AnsDate"%TYPE := NULL;



      vResult  VARCHAR2(4000);

 		v_nCount		NUMBER := 0;								-- AX-26071.2

BEGIN



		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetSchedImgInfoVisit');

		IF v_nCount > 0 THEN

			-- custom package function exists 

			EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetSchedImgInfoVisit('||vPId||','||vPForm||') FROM DUAL' INTO vResult;

			RETURN vResult;

		END IF;



		-- type

		BEGIN

			SELECT TRIM(htf.escape_sc(PI."AnsText")) INTO vSchedType

			FROM PITEM PI, FITEM FI

			WHERE 1=1 

				AND PI."FItem" = FI."FItem"

				AND PI."Patient" = vPId

				AND FI."Code" = vSchedTypeRefCode  

				AND PI."PForm" = vPForm

				AND PI."AuditNumber" =     

					(SELECT MAX(PI2."AuditNumber")

					FROM PITEM PI2, FITEM FI2

					WHERE 1=1 

						AND PI2."FItem" = FI2."FItem"

						AND PI2."Patient" = vPId

						AND FI2."Code" = vSchedTypeRefCode 

						AND FI2."Deleted" = 0

						AND PI2."AppDate" IS NOT NULL

						AND PI2."PForm" = vPForm);



		EXCEPTION WHEN OTHERS THEN

			vSchedType := '';

		END;



		-- date

		BEGIN

			SELECT PI."AnsDate" INTO vSchedDate

			FROM PITEM PI, FITEM FI

			WHERE 1=1 

				AND PI."FItem" = FI."FItem"

				AND PI."Patient" = vPId

				AND FI."Code" = vSchedDateRefCode  

				AND PI."PForm" = vPForm

				AND PI."AuditNumber" =     

					(SELECT MAX(PI2."AuditNumber")

					FROM PITEM PI2, FITEM FI2

					WHERE 1=1 

						AND PI2."FItem" = FI2."FItem"

						AND PI2."Patient" = vPId

						AND FI2."Code" = vSchedDateRefCode 

						AND FI2."Deleted" = 0

						AND PI2."AppDate" IS NOT NULL

						AND PI2."PForm" = vPForm);



		EXCEPTION WHEN OTHERS THEN

			vSchedDate := NULL;

		END;

 	

		-- construct the text entry

		RETURN '

			<tr>

				<td>' || TRIM(vSchedType) || '</td>

				<td>' || TO_CHAR(vSchedDate, 'MM/DD/YYYY') || '</td>

			</tr>';

 	END;

  	

  	-- scheduled labs

  	FUNCTION getschedlabinfovisit(vpid numeric, vpform numeric) RETURN character varying IS

		-- reference codes used

		vFormCode PFORM."FormCode"%TYPE := 'M_LABS';

		vSchedTypeRefCode FITEM."Code"%TYPE := 'M_LABSDESC';

		vSchedDateRefCode FITEM."Code"%TYPE := 'M_LABSDATE';



		-- for holding the answer

		vSchedType PITEM."AnsText"%TYPE := '';

		vSchedDate PITEM."AnsDate"%TYPE := NULL;



      vResult  VARCHAR2(4000);

	   v_nCount		NUMBER := 0;								-- AX-26071.2

  	BEGIN



		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetSchedLabInfoVisit');

		IF v_nCount > 0 THEN

			-- custom package function exists 

			EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetSchedLabInfoVisit('||vPId||','||vPForm||') FROM DUAL' INTO vResult;

			RETURN vResult;

		END IF;





		-- type

		BEGIN

			SELECT TRIM(htf.escape_sc(PI."AnsText")) INTO vSchedType

			FROM PITEM PI, FITEM FI

			WHERE 1=1 

				AND PI."FItem" = FI."FItem"

				AND PI."Patient" = vPId

				AND FI."Code" = vSchedTypeRefCode  

				AND PI."PForm" = vPForm

				AND PI."AuditNumber" =     

					(SELECT MAX(PI2."AuditNumber")

					FROM PITEM PI2, FITEM FI2

					WHERE 1=1 

						AND PI2."FItem" = FI2."FItem"

						AND PI2."Patient" = vPId

						AND FI2."Code" = vSchedTypeRefCode 

						AND FI2."Deleted" = 0

						AND PI2."AppDate" IS NOT NULL

						AND PI2."PForm" = vPForm);



		EXCEPTION WHEN OTHERS THEN

			vSchedType := '';

		END;



		-- date

		BEGIN

			SELECT PI."AnsDate" INTO vSchedDate

			FROM PITEM PI, FITEM FI

			WHERE 1=1 

				AND PI."FItem" = FI."FItem"

				AND PI."Patient" = vPId

				AND FI."Code" = vSchedDateRefCode  

				AND PI."PForm" = vPForm

				AND PI."AuditNumber" =     

					(SELECT MAX(PI2."AuditNumber")

					FROM PITEM PI2, FITEM FI2

					WHERE 1=1 

						AND PI2."FItem" = FI2."FItem"

						AND PI2."Patient" = vPId

						AND FI2."Code" = vSchedDateRefCode 

						AND FI2."Deleted" = 0

						AND PI2."AppDate" IS NOT NULL

						AND PI2."PForm" = vPForm);



		EXCEPTION WHEN OTHERS THEN

			vSchedDate := NULL;

		END;

  

		-- construct the text entry

		RETURN '

			<tr>

				<td>' || TRIM(vSchedType) || '</td>

				<td>' || TO_CHAR(vSchedDate, 'MM/DD/YYYY') || '</td>

			</tr>';

 	END;

  	

  

  	-- PLAN OF CARE SECTION FOR VISIT SUMMARIES

  	-- contents:

  	-- 	Objectives (as-of Appt Date)

  	-- 	Future Appts (as-of Appt Date)

  	--	Referrals (as-of Appt Date)

  	-- 	Future Scheduled Tests (as-of Appt Date)

  	--		- labs

  	--		- imaging

  	--		- procedures

  	-- 	Diagnostic Tests Pending (as-of Appt Date)

  	-- 	

  	--	CCDA indicates that all of these don't need to be coded, so text entries are fine!!!!

  	FUNCTION getplanofcaresectionvisit(vpid numeric, vapptdate timestamp without time zone, vbshowobjinfo boolean DEFAULT true, vbshowapptinfo boolean DEFAULT true, vbshowdiagtestspending boolean DEFAULT true, vbshowfutureschedtests boolean DEFAULT true, vbshowfuturereferrals boolean DEFAULT true) RETURN clob IS

		-- clobs for the various sections

		vResult CLOB := '';

		vPtObj CLOB := '';

		vAppts CLOB := '';

		vDiagTestsPending CLOB := '';

		vFutureSchedImaging CLOB := '';

		vFutureSchedLabs CLOB := '';

		vFutureSchedProcs CLOB := '';

		vFutureReferrals CLOB := '';

		

		-- cursor of patient objectives

		CURSOR curObj IS

			SELECT OL.* 

			FROM PTOBJ OL, OBJSTS OS 

			WHERE 1=1

				AND OL."Patient" = vPId 

				AND OL."Status" = OS."Code" 

				AND OL."Deleted" = 0 

				AND OS."Show" = 1 

				AND OS."Resolved" = 0

			ORDER BY OL."Audit" DESC, OL."PtObj" DESC;



		-- cursor of future appointments 

		CURSOR curAppt IS

			SELECT 

				A."Date", 

				A."From", 

				htf.escape_sc(A."Reason") AS "Reason", 

				C."Description",

				A."Producer",

				TRIM(P."Title") || ' ' || TRIM(P."FirstName") || ' ' || TRIM(P."LastName") AS "Provider"

			FROM APPOINT A, CLINIC C, PRODUCER P 

			WHERE 1=1 

				AND A."Patient" = vPId 

				AND A."Type" IN (0,1,2) 

				AND A."Date" > TRUNC(vApptDate)

				AND A."Clinic" = C."Clinic"

				AND A."Producer" = P."Producer"

			ORDER BY A."Date", A."From";				

			

		-- cursor of PForms for future scheduled imaging

		CURSOR curImgs IS

			SELECT DISTINCT PI."PForm" AS "PForm"

			FROM PITEM PI, FITEM FI

			WHERE 1=1

				AND PI."FItem" = FI."FItem"

				AND PI."FormCode" = 'O_RADI'

				AND PI."Patient" = vPId

				AND FI."Code" = 'O_RADISDAT'

				AND PI."AnsDate" > TRUNC(vApptDate)

				AND PI."AuditNumber" =     

					(SELECT MAX(PI2."AuditNumber")

					FROM PITEM PI2, FITEM FI2

					WHERE 1=1 

						AND PI2."FItem" = FI2."FItem"

						AND PI2."Patient" = vPId

						AND FI2."Code" = 'O_RADISDAT'

						AND FI2."Deleted" = 0

						AND PI2."AppDate" IS NOT NULL

						AND PI2."PForm" = PI."PForm")

			ORDER BY PI."PForm";			

			

		-- cursor of PForms for future scheduled lab tests

		CURSOR curLabs IS

			SELECT DISTINCT PI."PForm" AS "PForm"

			FROM PITEM PI, FITEM FI

			WHERE 1=1

				AND PI."FItem" = FI."FItem"

				AND PI."FormCode" = 'M_LABS'

				AND PI."Patient" = vPId

				AND FI."Code" = 'M_LABSDATE'

				AND PI."AnsDate" > TRUNC(vApptDate)

				AND PI."AuditNumber" =     

					(SELECT MAX(PI2."AuditNumber")

					FROM PITEM PI2, FITEM FI2

					WHERE 1=1 

						AND PI2."FItem" = FI2."FItem"

						AND PI2."Patient" = vPId

						AND FI2."Code" = 'M_LABSDATE'

						AND FI2."Deleted" = 0

						AND PI2."AppDate" IS NOT NULL

						AND PI2."PForm" = PI."PForm")

			ORDER BY PI."PForm";

						

		-- cursor of scheduled future procedures

		CURSOR curProc IS

			SELECT 

				htf.escape_sc(T."Description") as "Description", 

				T."Procedure", T."TreatmentDate", 

				T."Producer", 

				T."Status", 

				U."User" AS "UserId", 

				U."Name" AS "UserLast", 

				U."First" AS "UserFirst",

				PR."Name", 

				PR."City", 

				PR."Province", 

				PR."Postal", 

				PR."NPI", 

				PR."Area" AS "Area", 

				PR."Phone", 

				PR."Address1", 

				PR."Address2",

				CASE 

					WHEN P."Category" IN (0,1,2,3,4,5,6,7,8,9) THEN '2.16.840.1.113883.6.13'

					WHEN P."Category" IN (10, 11, 12, 13, 14, 15, 16, 17, 18) THEN '2.16.840.1.113883.6.12'

				END AS "CodeSystem",

				CASE 

					WHEN P."Category" IN (0,1,2,3,4,5,6,7,8,9) THEN 'CDT'

					WHEN P."Category" IN (10, 11, 12, 13, 14, 15, 16, 17, 18) THEN 'CPT-4'

				END AS "CodeSystemName"

			FROM trx T, procedur P, users U, PRACTICE PR

			WHERE 1=1 

				AND T."Patient" = vPId 

				and T."Type" IN (1,5) 

				and T."Deleted" = 0 

				and P."Procedure" = T."Procedure" 

				AND P."IsStepChild" = 0

				and (NOT (TRIM(U."Producer") IS NULL OR length(TRIM(U."Producer")) = 0)

				AND T."Producer" = U."Producer") 

				AND T."Practice" = PR."Id"

				AND P."Category" NOT IN (20, 30) 

				AND TRUNC(T."TreatmentDate") > TRUNC(vApptDate)

			ORDER BY T."TreatmentDate", T."Id", T."Treatment";

			

		-- cursor of PForms for future referrals to other providers

		CURSOR curRefs IS

			SELECT DISTINCT PI."PForm" AS "PForm"

			FROM PITEM PI, FITEM FI

			WHERE 1=1

				AND PI."FItem" = FI."FItem"

				AND PI."FormCode" = 'MUREF'

				AND PI."Patient" = vPId

				AND FI."Code" = 'MUREFDATE'

				AND PI."AnsDate" > TRUNC(vApptDate)

				AND PI."AuditNumber" =     

					(SELECT MAX(PI2."AuditNumber")

					FROM PITEM PI2, FITEM FI2

					WHERE 1=1 

						AND PI2."FItem" = FI2."FItem"

						AND PI2."Patient" = vPId

						AND FI2."Code" = 'MUREFDATE'

						AND FI2."Deleted" = 0

						AND PI2."AppDate" IS NOT NULL

						AND PI2."PForm" = PI."PForm")

			ORDER BY PI."PForm";

						

		-- cursor of diagnostic tests pending (MTESTREQ's that aren't F/C status and aren't after the appointment)

		CURSOR curDiagPend IS		

			SELECT 

				TRIM(LC."LongCommonName") AS "Type",

				TRUNC(MR."RequestDateTime") AS "LabDate"

			FROM MTESTORD MO, MTESTREQ MR, LOINC LC

			WHERE 1=1

				AND MO."Patient" = vPId

				AND MO."Deleted" = 0

				AND MO."MTestOrd" = MR."MTestOrd"

				AND TRUNC(MR."RequestDateTime") <= TRUNC(vApptDate)

				AND MR."LOINC" = LC."LOINC"

				AND TRIM(NVL(MR."Status",'NULL')) NOT IN ('F','C')

			ORDER BY MR."RequestDateTime";

				



		vObjCount NUMBER := 0; -- counter of patient objectives

		vApptCount NUMBER := 0; -- counter of appointments

		vDiagTestCount NUMBER := 0; -- counter of pending diagnostic (LOINC) tests

		vSchedImagingCount NUMBER := 0; -- counter of future scheduled imaging orders

		vSchedLabCount NUMBER := 0; -- counter of future scheduled lab orders

		vSchedProcCount NUMBER := 0; -- counter of future scheduled procedures

		vRefCount NUMBER := 0; -- counter of future scheduled referrals to other providers

		

		vProvAddr  VARCHAR2(4000) := '';

		

	   v_nCount		NUMBER := 0;								-- AX-26071.2



	BEGIN



		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetPlanOfCareSectionVisit');

		IF v_nCount > 0 THEN

			-- custom package function exists; AX-27290 

			EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetPlanOfCareSectionVisit(:1, :2, :3, :4, :5, :6, :7) FROM DUAL' INTO vResult

							USING vPId, vApptDate, vbShowObjInfo, vbShowApptInfo, vbShowDiagTestsPending, vbShowFutureSchedTests, vbShowFutureReferrals;

			RETURN vResult;

		END IF;





		-- init clobs

		dbms_lob_s.createtemporary (vResult, TRUE);

		dbms_lob_s.createtemporary (vPtObj, TRUE);

		dbms_lob_s.createtemporary (vAppts, TRUE);

		dbms_lob_s.createtemporary (vDiagTestsPending, TRUE);

		dbms_lob_s.createtemporary (vFutureSchedImaging, TRUE);

		dbms_lob_s.createtemporary (vFutureSchedLabs, TRUE);

		dbms_lob_s.createtemporary (vFutureSchedProcs, TRUE);

		dbms_lob_s.createtemporary (vFutureReferrals, TRUE);



		-- section header

		dbms_lob_s.append(vResult, '

			<component>

			  <section>

			  <!-- ** Plan of Care Section Template -->

			  <templateId root="2.16.840.1.113883.10.20.22.2.10"/>

			  <!-- CCDA Plan of Care Section definition requires this code -->

			  <code code="18776-5" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Treatment plan"/>

			  <title>Plan of Care</title>

			  <text>');

		

	

		-- objectives section 

		IF vbShowObjInfo THEN															--E143263.4

		

			-- loop thru all patient objectives and dump the text, if it exists

			dbms_lob_s.append(vPtObj, '

				<table border="1" width="100%">

					<thead>

						<tr>

							<th>Objectives</th>

						</tr>

					</thead>

					<tbody>');

					

			FOR objRec IN curObj LOOP   

				vObjCount := vObjCount + 1;

			

				IF NOT (trim(objRec."Description") IS NULL or length(trim(objRec."Description")) = 0) THEN

					dbms_lob_s.append(vPtObj, '

						<tr>

							<td>' || htf.escape_sc(objRec."Description") || '</td>

						</tr>');

				END IF;

			END LOOP;



			dbms_lob_s.append(vPtObj, '

					</tbody>

				</table>');

				

		END IF;





		-- future appts section

		IF vbShowApptInfo THEN															--E143263.4

			-- loop thru all future appointments and dump the text

			dbms_lob_s.append(vAppts, '

				<table border="1">

					<thead>

						<tr>

							<th colspan="5">Future Appointments</th>

						</tr>

						<tr>

							<th>Provider</th>

							<th>Location</th>

							<th>Date</th>

							<th>Time</th>

							<th>Reason</th>

						</tr>

					</thead>

					<tbody>

				');



			FOR apptRec IN curAppt LOOP    

				vApptCount := vApptCount + 1;

				

				--get the address information

				BEGIN

					SELECT TRIM(US."Address1") || TRIM( ' ' || TRIM(US."Address2")) || ', ' || TRIM(US."City") || ', ' || TRIM(US."Province") || ' ' || TRIM(US."Postal")

					INTO vProvAddr

					FROM PRODUCER PR, USERS US

					WHERE 1=1

						AND TRIM(PR."Producer") = TRIM(US."Producer")

						AND TRIM(PR."Producer") = TRIM(apptRec."Producer")

						AND ROWNUM = 1;

						

				EXCEPTION WHEN OTHERS THEN

					vProvAddr := 'N/A';

				END;

				

			

				dbms_lob_s.append(vAppts, '

					<tr>

						<td>' || TRIM(apptRec."Provider") || '</td>

						<td>' || TRIM(vProvAddr) || '</td>

						<td>' || TO_CHAR(apptRec."Date", 'MM/DD/YYYY') || '</td>

						<td>' || FLOOR(apptRec."From"/60) || ':'|| LPAD(MOD(apptRec."From", 60), 2, '0') || '</td>

						<td>' || TRIM(apptRec."Reason") || '</td>

					</tr>

					');   

			END LOOP;



			dbms_lob_s.append(vAppts, '

					</tbody>

				</table>

				');

			

		END IF;

		

		-- diagnostic tests pending section

		IF vbShowDiagTestsPending THEN	

			-- header

			dbms_lob_s.append(vDiagTestsPending, '

				<table border="1">

					<thead>

						<tr>

							<th colspan="4">Diagnostic Tests Pending</th>

						</tr>

						<tr>

							<th>Type</th>

							<th>Date</th>

						</tr>

					</thead>

					<tbody>

				');

			

			-- content

			FOR cDiagPend IN curDiagPend LOOP

				vDiagTestCount := vDiagTestCount + 1;

				dbms_lob_s.append(vDiagTestsPending, '

					<tr>

						<td>' || cDiagPend."Type" || '</td>

						<td>' || TO_CHAR(cDiagPend."LabDate", 'MM/DD/YYYY') || '</td>

					</tr>

					'); 

			END LOOP;

			

			-- footer

			dbms_lob_s.append(vDiagTestsPending, '

					</tbody>

				</table>

				');			

		END IF;

		

		-- future scheduled tests section

		IF vbShowFutureSchedTests THEN	

		

			-- future scheduled imaging 

			-- header

			dbms_lob_s.append(vFutureSchedImaging, '

				<table border="1">

					<thead>

						<tr>

							<th colspan="4">Scheduled Imaging</th>

						</tr>

						<tr>

							<th>Type</th>

							<th>Date</th>

						</tr>

					</thead>

					<tbody>

				');



			-- content

			FOR cImg IN curImgs LOOP  

				vSchedImagingCount := vSchedImagingCount + 1;

				dbms_lob_s.append(vFutureSchedImaging, GetSchedImgInfoVisit(vPId, cImg."PForm"));

			END LOOP;

	

			-- footer

			dbms_lob_s.append(vFutureSchedImaging, '

					</tbody>

				</table>

				');

				

				

			-- future scheduled lab tests

			-- header

			dbms_lob_s.append(vFutureSchedLabs, '

				<table border="1">

					<thead>

						<tr>

							<th colspan="4">Scheduled Lab Tests</th>

						</tr>

						<tr>

							<th>Type</th>

							<th>Date</th>

						</tr>

					</thead>

					<tbody>

				');



			-- content

			FOR cLab IN curLabs LOOP  

				vSchedLabCount := vSchedLabCount + 1;

				dbms_lob_s.append(vFutureSchedLabs, GetSchedLabInfoVisit(vPId, cLab."PForm"));

			END LOOP;



			-- footer

			dbms_lob_s.append(vFutureSchedLabs, '

					</tbody>

				</table>

				');	

			

			

			-- future scheduled procedures

			-- header

			dbms_lob_s.append(vFutureSchedProcs, '

				<table border="1">

					<thead>

						<tr>

							<th colspan="4">Scheduled Procedures</th>

						</tr>

						<tr>

							<th>Type</th>

							<th>Date</th>

						</tr>

					</thead>

					<tbody>

				');

			

			-- content

			FOR cProc IN curProc LOOP  

				vSchedProcCount := vSchedProcCount + 1;

				dbms_lob_s.append(vFutureSchedProcs, '

					<tr>

						<td>' || cProc."Description" || '</td>

						<td>' || TO_CHAR(cProc."TreatmentDate", 'MM/DD/YYYY') || '</td>

					</tr>

				'); 

			END LOOP;

			

			-- footer

			dbms_lob_s.append(vFutureSchedProcs, '

					</tbody>

				</table>

				');	

		END IF;

		

		-- future scheduled referrals to other providers

		IF vbShowFutureReferrals THEN

			-- header

			dbms_lob_s.append(vFutureReferrals, '

				<table border="1">

					<thead>

						<tr>

							<th colspan="5">Referrals to Other Providers</th>

						</tr>

						<tr>

							<th>Provider</th>

							<th>Tel</th>

							<th>Addr</th>

							<th>Date</th>

							<th>Reason</th>

						</tr>

					</thead>

					<tbody>

				');

			

			-- content

			

			FOR cRef IN curRefs LOOP

				vRefCount := vRefCount + 1;

				dbms_lob_s.append(vFutureReferrals, GetReferralInfoVisit(vPId, cRef."PForm"));

			END LOOP;

						

			-- footer

			dbms_lob_s.append(vFutureReferrals, '

					</tbody>

				</table>

				');				

		END IF;



		-- put it all together

		IF vbShowObjInfo THEN															--E143263.4			

			IF vObjCount > 0 THEN

				dbms_lob_s.append(vResult, vPtObj);

			ELSE 

				-- there were no objectives (that had descriptions)

				dbms_lob_s.append(vResult, '

					<table border="1" width="100%">

						<thead>

							<tr>

								<th>Objectives</th>

							</tr>

						</thead>

						<tbody>');



				dbms_lob_s.append(vResult, '

					<tr><td>No objectives are on file.</td></tr>

					');



				dbms_lob_s.append(vResult, '

					</tbody>

				</table>');

			END IF;

		END IF;

		

		IF vbShowDiagTestsPending THEN															--E143263.4

			IF vDiagTestCount > 0 THEN

				dbms_lob_s.append(vResult, vDiagTestsPending);

			ELSE

				-- there were no diagnostic tests pending

				dbms_lob_s.append(vResult, '

					<table border="1">

						<thead>

							<tr>

								<th>Diagnostic Tests Pending</th>

							</tr>

						</thead>

						<tbody>

					');



				dbms_lob_s.append(vResult, '

					<tr><td>No diagnostic tests pending are on file.</td></tr>

					');



				dbms_lob_s.append(vResult, '

					</tbody>

				</table>');

			END IF;

		END IF;





		IF vbShowFutureSchedTests THEN															--E143263.4

			IF vSchedImagingCount > 0 THEN

				dbms_lob_s.append(vResult, vFutureSchedImaging);

			ELSE

				-- there were no future scheduled imaging order

				dbms_lob_s.append(vResult, '

					<table border="1">

						<thead>

							<tr>

								<th>Scheduled Imaging</th>

							</tr>

						</thead>

						<tbody>

					');



				dbms_lob_s.append(vResult, '

					<tr><td>No scheduled imaging is on file.</td></tr>

					');



				dbms_lob_s.append(vResult, '

					</tbody>

				</table>');

			END IF;



			IF vSchedLabCount > 0 THEN

				dbms_lob_s.append(vResult, vFutureSchedLabs);

			ELSE

				-- there were no future scheduled lab orders

				dbms_lob_s.append(vResult, '

					<table border="1">

						<thead>

							<tr>

								<th>Scheduled Lab Tests</th>

							</tr>

						</thead>

						<tbody>

					');



				dbms_lob_s.append(vResult, '

					<tr><td>No scheduled lab tests are on file.</td></tr>

					');



				dbms_lob_s.append(vResult, '

					</tbody>

				</table>');

			END IF;



			IF vSchedProcCount > 0 THEN

				dbms_lob_s.append(vResult, vFutureSchedProcs);

			ELSE

				-- there were no future scheduled procedures (planned procedures)



				dbms_lob_s.append(vResult, '

					<table border="1">

						<thead>

							<tr>

								<th>Scheduled Procedures</th>

							</tr>

						</thead>

						<tbody>

					');



				dbms_lob_s.append(vResult, '

					<tr><td>No scheduled procedures are on file.</td></tr>

					');



				dbms_lob_s.append(vResult, '

					</tbody>

				</table>');

			END IF;

		END IF;



		IF vbShowApptInfo THEN															--E143263.4

			IF vApptCount > 0 THEN

				dbms_lob_s.append(vResult, vAppts);

			ELSE

				-- there were no future appointments

				dbms_lob_s.append(vResult, '

					<table border="1">

						<thead>

							<tr>

								<th>Future Appointments</th>

							</tr>

						</thead>

						<tbody>

					');



				dbms_lob_s.append(vResult, '

					<tr><td>No future appointments are on file.</td></tr>

					');



				dbms_lob_s.append(vResult, '

					</tbody>

				</table>');

			END IF;

		END IF;



		IF vbShowFutureReferrals THEN															--E143263.4

			IF vRefCount > 0 THEN

				dbms_lob_s.append(vResult, vFutureReferrals);

			ELSE

				-- there were no future scheduled referrals to other providers.

				dbms_lob_s.append(vResult, '

					<table border="1">

						<thead>

							<tr>

								<th colspan="5">Referrals to Other Providers</th>

							</tr>

						</thead>

						<tbody>

					');



				dbms_lob_s.append(vResult, '

					<tr><td colspan="5">No future referrals to other providers are on file.</td></tr>

					');



				dbms_lob_s.append(vResult, '

						</tbody>

					</table>');

			END IF;

		END IF;



		-- section footer

		dbms_lob_s.append(vResult, '            

			    </text>

			  </section>

			</component>');



		return vResult;

	END;

  	

  

	-- Assessment and Plan Section - patient objectives and future appointments

	-- AX-18945.19095

	FUNCTION getplanofcaresection(vpid numeric, vbshowobjinfo boolean DEFAULT true, vbshowapptinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob IS

		vResult CLOB := '';

		vResultAssess CLOB := '';

		vResultObj CLOB := '';

		vPtAsmt CLOB := '';

		vRefCode FITEM."Code"%TYPE := 'MUASMT';

				



		-- cursor of future appointments 

		CURSOR curAppt IS

			SELECT A."Date", A."From", htf.escape_sc(A."Reason") AS "Reason", C."Description"

			FROM APPOINT A, CLINIC C 

			WHERE A."Patient" = vPId AND A."Type" IN (0,1,2) 

			AND TRUNC(A."Date") > TRUNC(SYSDATE)

			-- AX-18945.19095, AX-18945.19094d

			AND 

			(

				(vDate1 IS NOT NULL AND vDate2 IS NOT NULL

					AND A."Date" >= TRUNC(vDate1) 

					AND (A."Date" = TRUNC(vDate1) AND A."From" >= TRUNC(TO_CHAR(vDate1, 'SSSSS') / 60) OR (A."Date" <> TRUNC(vDate1)))

					AND A."Date" <= TRUNC(vDate2) 

					AND (A."Date" = TRUNC(vDate2) AND A."From" <= TRUNC(TO_CHAR(vDate2, 'SSSSS') / 60) OR (A."Date" <> TRUNC(vDate2)))

					)



				OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 

					AND A."Date" >= TRUNC(vDate1) 

					AND (A."Date" = TRUNC(vDate1) AND A."From" >= TRUNC(TO_CHAR(vDate1, 'SSSSS') / 60) OR (A."Date" <> TRUNC(vDate1)))

					)

				OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0

					AND A."Date" <= TRUNC(vDate1) 

					AND (A."Date" = TRUNC(vDate1) AND A."From" <= TRUNC(TO_CHAR(vDate1, 'SSSSS') / 60) OR (A."Date" <> TRUNC(vDate1)))

					)

				OR (vDate1 IS NULL) 

			)

			AND A."Clinic" = C."Clinic"

			ORDER BY A."Date", A."From";



		-- cursor of assessments...

		CURSOR curAssessments IS

			SELECT TRIM(htf.escape_sc(PI."AnsText")) "AnsText"

			FROM PITEM PI, FITEM FI

			WHERE 1=1 

				AND PI."FItem" = FI."FItem"

				AND PI."Patient" = vPId

				AND FI."Code" = vRefCode

				AND PI."AuditNumber" =     

					(SELECT MAX(PI2."AuditNumber")

					FROM PITEM PI2, FITEM FI2

					WHERE 1=1 

						AND PI2."FItem" = FI2."FItem"

						AND PI2."Patient" = vPId

						AND FI2."Code" = vRefCode

						AND FI2."Deleted" = 0

						AND PI2."AppDate" IS NOT NULL

						AND 

						(

							(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

							OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

							OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

							OR (vDate1 IS NULL)

						));

		

		vAsmtCount NUMBER := 0; -- counter of patient assessments

		vApptCount NUMBER := 0; -- counter of appointments



	   v_nCount		NUMBER := 0;								-- AX-26071.2



	BEGIN



		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetPlanOfCareSection');

		IF v_nCount > 0 THEN

			-- custom package function exists; AX-27290 

			EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetPlanOfCareSection(:1, :2, :3, :4, :5, :6) FROM DUAL' INTO vResult

								USING vPId, vbShowObjInfo, vbShowApptInfo, vIsDateFrom, vDate1, vDate2;

			RETURN vResult;

		END IF;





		-- init clobs

		dbms_lob_s.createtemporary (vResult, TRUE);

		dbms_lob_s.createtemporary (vResultAssess, TRUE);

		dbms_lob_s.createtemporary (vResultObj, TRUE);

		dbms_lob_s.createtemporary (vPtAsmt, TRUE);



----------------- section ASSESSMENTS header

		dbms_lob_s.append(vResultAssess, '

			<component>

			  <section>

                <!-- ** Assessment Section -->

                <!-- There is no R2.1 (or 2.0) version of Assessment Section, using R1.1 templateId only -db -->

                <templateId root="2.16.840.1.113883.10.20.22.2.8"/>

                <code codeSystem="2.16.840.1.113883.6.1" 

                     codeSystemName="LOINC" code="51848-0" 

                     displayName="Assessment and Plan"/>

                <title>Assessment and Plan</title>

                <text>');		

	

                dbms_lob_s.append(vPtAsmt, '

                    <table border="1" width="100%">

                        <thead>

                            <tr>

                                <th>Assessment</th>

                            </tr>

                        </thead>

                        <tbody>');

                        

                FOR asmtRec IN curAssessments LOOP   

                    vAsmtCount := vAsmtCount + 1;

                

                    IF NOT (trim(asmtRec."AnsText") IS NULL OR length(trim(asmtRec."AnsText")) = 0) THEN

                        dbms_lob_s.append(vPtAsmt, '

                            <tr>

                                <td>' || htf.escape_sc(asmtRec."AnsText") || '</td>

                            </tr>');

                    END IF;

                END LOOP;

                

            dbms_lob_s.append(vResultAssess, vPtAsmt);

            IF vAsmtCount = 0 then 

                                dbms_lob_s.append(vResultAssess, '

                                    <tr><td>No assessments are on file.</td></tr>

                                    ');

                            end if;



                    dbms_lob_s.append(vResultAssess, '

                        </tbody>

                    </table>

                    </text>

				</section>

			</component>');

	

----------- Samir_Boudjebla - Assessment Section end



        

        dbms_lob_s.append(vResultAssess, vResult);

		return vResultAssess;

	END;

  



    -- AX-26388

	FUNCTION gettreatmentplansection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob IS

		vResult CLOB := '';

		vResultAssess CLOB := '';

		vResultObj CLOB := '';

		vPtObj CLOB := '';

		--vPtAsmt CLOB := '';

		vLabs CLOB := '';

		--vRefCode FITEM."Code"%TYPE := 'MUASMT';



		-- AX-21879b

		-- cursor of medical tests with no results - MTESTREQ

		CURSOR curTestsNoRslts IS

			SELECT 

				MT."MTestReq", 

				MT."LOINC", 

				MT."Status", 

				HTF.ESCAPE_SC(LC."LongCommonName") AS "Description",

				MT."RequestDateTime"

			FROM MTESTREQ MT, MTESTORD MO, LOINC LC

			WHERE 1=1

				AND MT."MTestOrd" = MO."MTestOrd"

				AND MO."Deleted" = 0

				AND MO."Patient" = vPId

				AND MT."LOINC" = LC."LOINC"

				AND MT."Status" NOT IN ('X')

				AND MT."MTestReq" NOT IN (SELECT "MTestReq" FROM MTESTRES WHERE "MTestReq" = MT."MTestReq" AND "Deleted" = 0)

				AND 

				(

					(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND MT."RequestDateTime" >= vDate1 AND MT."RequestDateTime" <= vDate2)

					OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND MT."RequestDateTime" >= vDate1)

					OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND MT."RequestDateTime" <= vDate1) 

					OR (vDate1 IS NULL)

				)

			ORDER BY MT."RequestDateTime" DESC;



		-- cursor of patient objectives

		CURSOR curObj IS

			SELECT OL.* 

			FROM PTOBJ OL, OBJSTS OS, AUDITHIS A

			WHERE 1=1

				AND OL."Patient" = vPId 

				AND OL."Status" = OS."Code" 

				AND OL."Deleted" = 0 

				AND OS."Show" = 1 

				AND OS."Resolved" = 0

				-- AX-18945.19095, AX-18945.19094d

				AND OL."Audit" = A."Audit"

				AND 

				(

					(vDate1 IS NOT NULL AND vDate2 IS NOT NULL

						AND A."Date" >= TRUNC(vDate1) 

						AND (A."Date" = TRUNC(vDate1) AND A."Time" >= TRUNC(TO_CHAR(vDate1, 'SSSSS') / 60) OR (A."Date" <> TRUNC(vDate1)))

						AND A."Date" <= TRUNC(vDate2) 

						AND (A."Date" = TRUNC(vDate2) AND A."Time" <= TRUNC(TO_CHAR(vDate2, 'SSSSS') / 60) OR (A."Date" <> TRUNC(vDate2)))

						)



					OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 

						AND A."Date" >= TRUNC(vDate1) 

						AND (A."Date" = TRUNC(vDate1) AND A."Time" >= TRUNC(TO_CHAR(vDate1, 'SSSSS') / 60) OR (A."Date" <> TRUNC(vDate1)))

						)

					OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0

						AND A."Date" <= TRUNC(vDate1) 

						AND (A."Date" = TRUNC(vDate1) AND A."Time" <= TRUNC(TO_CHAR(vDate1, 'SSSSS') / 60)) OR (A."Date" <> TRUNC(vDate1))

						)

					OR (vDate1 IS NULL) 

				)

			ORDER BY OL."Audit" DESC, OL."PtObj" DESC;



		vObjCount NUMBER := 0; -- counter of patient objectives

		vLabCount NUMBER := 0; -- counter of Labs loinc



	   v_nCount		NUMBER := 0;								-- AX-26071.2



	BEGIN

	

		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetTreatmentPlanSection');

		IF v_nCount > 0 THEN

			-- custom package function exists; AX-27290

			EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetTreatmentPlanSection(:1, :2, :3, :4, :5) FROM DUAL' INTO vResult

									USING vPId, vbShowInfo, vIsDateFrom, vDate1, vDate2;

			RETURN vResult;

		END IF;





		-- init clobs

		dbms_lob_s.createtemporary (vResult, TRUE);

		dbms_lob_s.createtemporary (vResultObj, TRUE);

		dbms_lob_s.createtemporary (vResultAssess, TRUE);

		dbms_lob_s.createtemporary (vPtObj, TRUE);

		dbms_lob_s.createtemporary (vLabs, TRUE);

	

-----------Samir_Boudjebla - Start Plan of Treatment --------------

-- section header ---- 

		dbms_lob_s.append(vResult, '

			<component>

                <section>

                    <!--  **** Plan of Treatment Section (V2) **** -->

                    <templateId root="2.16.840.1.113883.10.20.22.2.10" extension="2014-06-09"/>

                    <templateId root="2.16.840.1.113883.10.20.22.2.10"/>

                    <code code="18776-5" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Treatment plan"/>

                    <title>Treatment Plan</title>

                   ');

		IF vbShowInfo THEN															--E143263.4

			-- loop thru all patient objectives and dump the text, if it exists

			dbms_lob_s.append(vPtObj, '

                    <text>

                        <table border="1" width="100%">

                            <thead>

                                <tr>

                                    <th>Objectives</th>

                                </tr>

                            </thead>

                            <tbody>');



			FOR objRec IN curObj LOOP   

				IF NOT (trim(objRec."Description") IS NULL or length(trim(objRec."Description")) = 0) THEN

                    vObjCount := vObjCount + 1;

					dbms_lob_s.append(vPtObj, '

                                    <tr>

                                        <td>' || htf.escape_sc(objRec."Description") || '</td>

                                    </tr>');

				END IF;

			END LOOP;



--------- loop for labs

			FOR testRec IN curTestsNoRslts LOOP   

				IF NOT (trim(testRec.LOINC) IS NULL OR length(trim(testRec.LOINC)) = 0) THEN

                    vLabCount := vLabCount + 1;	

					dbms_lob_s.append(vPtObj, ' 

                                    <tr>

                                        <td> ('  || htf.escape_sc(testRec."LOINC") || ') ' || htf.escape_sc(testRec."Description") ||'('|| TO_CHAR(testRec."RequestDateTime", 'YYYYMMDD')|| ') </td>

                                    </tr>');

                                    

				END IF;

			END LOOP;



-------------------------------

            IF vObjCount = 0 and vLabCount=0 THEN  -- there were no objectives (that had descriptions)

                                    dbms_lob_s.append(vPtObj, '

                                        <tr><th>No Plan of Treatment Information.</th></tr>

                                        ');             

             END IF;

                          dbms_lob_s.append(vPtObj, '

                             </tbody>

                        </table>

                    </text>');

             dbms_lob_s.append(vResult, vPtObj);



            vLabCount:=0;

			FOR testRec IN curTestsNoRslts LOOP   

				IF NOT (trim(testRec.LOINC) IS NULL OR length(trim(testRec.LOINC)) = 0) THEN

                    vLabCount := vLabCount + 1;		

					dbms_lob_s.append(vLabs, '<entry>

                        <!-- For lab, this should be an RQO -->

                        <observation classCode="OBS" moodCode="RQO">

                        <!-- Planned Observation (V2) -> Plan Of Care Activity Observation -->

                        <templateId root="2.16.840.1.113883.10.20.22.4.44" extension="2014-06-09"/>

                        <templateId root="2.16.840.1.113883.10.20.22.4.44"/>

                        <id root="b52bee94-c34b-4e2c-8c15-5ad9d6def513" />

                        <code code="' || htf.escape_sc(testRec."LOINC") || '"  

                            codeSystem="2.16.840.1.113883.6.1" 

                            codeSystemName="LOINC" 

                            displayName="' || htf.escape_sc(testRec."Description") || '"/>

                        <statusCode code="active" />

							<effectiveTime value="' || TO_CHAR(testRec."RequestDateTime", 'YYYYMMDD') || '"/>

					</observation>

					</entry>');

				END IF;

			END LOOP;

                IF vLabCount>0 then dbms_lob_s.append(vResult, vLabs);

                END IF;



        END IF;

		

		dbms_lob_s.append(vResult,

            '</section>

            </component>');

        

        IF (vObjCount=0) and (vLabCount=0) THEN 

                dbms_lob_s.createtemporary (vResult, TRUE);                

                dbms_lob_s.append(vResult,'<component>

                <section nullFlavor="NI">

                    <!--  **** Plan of Treatment Section (V2) **** -->

                    <templateId root="2.16.840.1.113883.10.20.22.2.10" extension="2014-06-09"/>

                    <templateId root="2.16.840.1.113883.10.20.22.2.10"/>

                    <code code="18776-5" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Treatment plan"/>

                    <title>Treatment Plan</title>

                    <text>No Plan of Treatment Information</text>

                </section>

            </component>');        

        END IF;

            

        dbms_lob_s.append(vResultAssess, vResult);

		return vResultAssess;

	END;

 

  	-- Procedures section for Visit Summary C-CDAs - contains only completed procedures for today or in the past. 

  	FUNCTION getproceduresectionvisit(vpid numeric, vapptdate timestamp without time zone, vbshowinfo boolean DEFAULT true) RETURN clob IS

		vPracticeRec PRACTICE%ROWTYPE;

		vResult CLOB := '';

		vText CLOB := '';

		vEntries CLOB := '';

		vNote CLOB := '';

		vCount NUMBER := 0;

		vTxNoteCount NUMBER := 0; -- AX-26344

		vLastNoteDate DATE := NULL;

		vStatusCode  VARCHAR2(32) := '';

		vLastId NUMBER := 0;



		-- B142392

		CURSOR curProc IS

			SELECT 

				T."ChartTrx", -- AX-26344

				htf.escape_sc(T."Description") as "Description", 

				T."Procedure", T."TreatmentDate", 

				T."Producer", 

				T."Status", 

				U."User" AS "UserId", 

				U."Name" AS "UserLast", 

				U."First" AS "UserFirst",

				PR."Name", 

				PR."City", 

				PR."Province", 

				PR."Postal", 

				PR."NPI", 

				PR."Area" AS "Area", 

				PR."Phone", 

				PR."Address1", 

				PR."Address2",

				CASE 

					WHEN P."Category" IN (0,1,2,3,4,5,6,7,8,9) THEN '2.16.840.1.113883.6.13'

					WHEN P."Category" IN (10, 11, 12, 13, 14, 15, 16, 17, 18) THEN '2.16.840.1.113883.6.12'

				END AS "CodeSystem",

				CASE 

					WHEN P."Category" IN (0,1,2,3,4,5,6,7,8,9) THEN 'CDT'

					WHEN P."Category" IN (10, 11, 12, 13, 14, 15, 16, 17, 18) THEN 'CPT-4'

				END AS "CodeSystemName"

			FROM trx T, procedur P, users U, PRACTICE PR

			WHERE 1=1 

				AND T."Patient" = vPId 

				and T."Type" = 1 

				and T."Deleted" = 0 

				and P."Procedure" = T."Procedure" 

				AND P."IsStepChild" = 0

				and (NOT (TRIM(U."Producer") IS NULL OR length(TRIM(U."Producer")) = 0)

				AND T."Producer" = U."Producer") 

				AND T."Practice" = PR."Id"

				AND P."Category" NOT IN (20, 30) 

				AND TRUNC(T."Date") <= TRUNC(vApptDate)

			ORDER BY T."TreatmentDate", T."Id", T."Treatment";



		-- AX-26344

		CURSOR curTxNotes(cpTrxId NUMBER) IS

			SELECT DISTINCT

				n."Auto", -- AX-26430

				n."Type", -- AX-26430

				n."Text",    

				n."Date",  

				n."AddDateTime",    

				n."User", 

				n."SectionNo",

				n."OtherId",

				u."First", 

				u."Name"

			FROM 

			    notes2 n,

				trx    t,

				USERS   u

			WHERE 1=1 

				AND t."ChartTrx" > 0

				AND t."ChartTrx" = cpTrxId

				AND t."ChartTrx" = n."TxId" (+)

				AND n."Status" = 0

				AND n."AppUser" > 0

				AND n."Text" IS NOT NULL

				AND n."User" = u."User" (+)

			ORDER BY n."Auto" desc, "SectionNo"; -- AX-26430

			

	   v_nCount		NUMBER := 0;								-- AX-26071.2



	BEGIN

	

		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetProcedureSectionVisit');

		IF v_nCount > 0 THEN

			-- custom package function exists; AX-27290 

			EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetProcedureSectionVisit(:1, :2, :3) FROM DUAL' INTO vResult

									USING vPId, vApptDate, vbShowInfo;

			RETURN vResult;

		END IF;



		-- init clobs

		dbms_lob_s.createtemporary (vResult, TRUE);

		dbms_lob_s.createtemporary (vText, TRUE);

		dbms_lob_s.createtemporary (vEntries, TRUE);

		dbms_lob_s.createtemporary (vNote, TRUE);



		-- section header

		vResult := '

		<component>

		    <section>

		       <templateId root="2.16.840.1.113883.10.20.22.2.7.1"/>

		       <!-- Procedures section template -->

		       <code code="47519-4" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC"

			  displayName="HISTORY OF PROCEDURES"/>

		       <title>Procedures</title>';



		IF vbShowInfo THEN								--E143263.4

			-- loop thru all the procedures

			FOR procRec IN curProc LOOP                 

				

				vCount := vCount + 1;

				

				IF vCount = 1 THEN 

					-- add the list header if this is the first record

					-- AX-26344 - add notes...

					dbms_lob_s.append(vText, '

						<text>

							<table border="1" width="100%">

								<thead>

									<tr>

										<th>Procedure</th>

										<th>Date</th>

										<th>Notes</th>

									</tr>

								</thead>

								<tbody>		       			

						');				

				END IF;

				

				IF NOT (trim(procRec."Description") IS NULL or length(trim(procRec."Description")) = 0) THEN

					dbms_lob_s.append(vText, '

									<tr>

										<td><content ID="procedure' || vCount || '">' || htf.escape_sc(procRec."Description") || '</content></td>

										<td>' || TO_CHAR(procRec."TreatmentDate", 'MM/DD/YYYY') || '</td>

						');	



					-- AX-26344	- start

					dbms_lob_s.append(vText, '

										<td>

						');	

					

					-- AX-26430

					IF procRec."ChartTrx" > 0 THEN

						FOR cTxNote IN curTxNotes(procRec."ChartTrx") LOOP



							-- AX-26430

							IF vLastNoteDate IS NULL OR vLastNoteDate <> cTxNote."Date" THEN

								GetTxSOAPNotes(vPId, cTxNote."Date", procRec."ChartTrx", vText, vEntries, vTxNoteCount);

							END IF;



							IF NOT (trim(cTxNote."Text") IS NULL OR length(trim(cTxNote."Text")) = 0)  AND cTxNote."Type" <> 4 THEN



								vTxNoteCount := vTxNoteCount + 1;

							

								SELECT REPLACE(cTxNote."Text", Chr(39), Chr(39)||Chr(39)) INTO vNote FROM DUAL;

								SELECT REPLACE(vNote, Chr(34), Chr(39)||Chr(39)) INTO vNote FROM DUAL;

								SELECT REPLACE(vNote, Chr(96), Chr(39)||Chr(39)) INTO vNote FROM DUAL;

								

								-- AX-26461

								dbms_lob_s.append(vText, '

												' || TO_CHAR(cTxNote."Date", 'MM/DD/YYYY') || '<br />

												<content ID="procnote' || vTxNoteCount || '">');	



								FOR Lines IN (select regexp_substr (vNote, '[^' || CHR(10)|| ']+', 1, rownum) Txt from dual 

									connect by level <= regexp_count (vNote, '[^' || CHR(10)|| ']+'))

								LOOP

									dbms_lob_s.append(vText, '

													' || htf.escape_sc(Lines.Txt) || '<br />

									');	

								END LOOP;	



								dbms_lob_s.append(vText, '

												</content>

								');	



								IF vTxNoteCount > 0 THEN 

									dbms_lob_s.append(vText, '

												<br />

									');	

								END IF;



							END IF;



							vLastNoteDate := cTxNote."Date";



						END LOOP;

					END IF;



					dbms_lob_s.append(vText, '

										</td>

									</tr>

						');	

					-- AX-26344	- end



					IF trim(procRec."Status") = 'C' THEN 

						vStatusCode := 'completed';

					ELSE

						vStatusCode := 'active';

					END IF;



					dbms_lob_s.append(vEntries, '

						<entry>

							  <procedure classCode="PROC" moodCode="EVN">

								  <!-- Procedure  Activity Procedure Template -->

								  <templateId root="2.16.840.1.113883.10.20.22.4.14"/>

								  <id root="2.16.840.1.113883.4.8155" />

								  <code xsi:type="CE" code="' || SUBSTR(TRIM(procRec."Procedure"),2) ||'" codeSystem="' || TRIM(procRec."CodeSystem") ||'"

								displayName="' || TRIM(procRec."Description") ||'"

								codeSystemName="' || TRIM(procRec."CodeSystemName") ||'">

								<originalText>

									<reference value="#procedure' || vCount || '"/>

								</originalText>

								  </code>

								  <statusCode code="' || vStatusCode || '"/>');



						dbms_lob_s.append(vEntries, '

								 <performer typeCode="PRF">

								<assignedEntity>

									<id extension="' || GetUserIdentifier(procRec."UserId") ||'" root="' ||GetUserIdentifierType ||'"/>');



					dbms_lob_s.append(vEntries, '

								<addr>');



					IF NOT (trim(procRec."Address1") IS NULL or length(trim(procRec."Address1")) = 0) THEN

						dbms_lob_s.append(vEntries, '

							<streetAddressLine>' || htf.escape_sc(trim(procRec."Address1")) || '</streetAddressLine>');

					-- AX-18945.19094e

					ELSE

						-- no street address entered

						dbms_lob_s.append(vEntries, '

							<streetAddressLine nullFlavor="UNK"/>');

					END IF;



					IF NOT (trim(procRec."Address2") IS NULL or length(trim(procRec."Address2")) = 0) THEN

						dbms_lob_s.append(vEntries, '

							<streetAddressLine>' || htf.escape_sc(trim(procRec."Address2")) || '</streetAddressLine>');

					END IF;



					IF NOT (trim(procRec."City") IS NULL or length(trim(procRec."City")) = 0) THEN

						dbms_lob_s.append(vEntries, '

							<city>' || htf.escape_sc(trim(procRec."City")) || '</city>');

		  			-- AX-18945.19094e

					ELSE

						-- patient city unknown

						dbms_lob_s.append(vEntries, '

							<city nullFlavor="UNK"/>');

					END IF;



					IF NOT (trim(procRec."Province") IS NULL or length(trim(procRec."Province")) = 0) THEN

						dbms_lob_s.append(vEntries, '

							<state>' || htf.escape_sc(trim(procRec."Province")) || '</state>');

		 			-- AX-18945.19094e

					ELSE

						--state unknown

						dbms_lob_s.append(vEntries, '

							<state nullFlavor="UNK"/>');

					END IF;



					IF NOT (trim(procRec."Postal") IS NULL or length(trim(procRec."Postal")) = 0) THEN

						dbms_lob_s.append(vEntries, '

							<postalCode>' || htf.escape_sc(trim(procRec."Postal")) || '</postalCode>');

		 			-- AX-18945.19094e

					ELSE

						dbms_lob_s.append(vEntries, '

							<postalCode nullFlavor="UNK"/>');

					END IF;





					dbms_lob_s.append(vEntries, '

							<country>' || 'US' || '</country>');



					dbms_lob_s.append(vEntries, '

							</addr>'); 



					IF NOT (trim(procRec."Phone") IS NULL or length(trim(procRec."Phone")) = 0) THEN

						dbms_lob_s.append(vEntries, '

							<telecom use="WP" value="');



						IF NOT (trim(procRec."Area") IS NULL or length(trim(procRec."Area")) = 0) THEN

							dbms_lob_s.append(vEntries, TRIM(procRec."Area") || '-');

						END IF;



						dbms_lob_s.append(vEntries, TRIM(procRec."Phone") ||'"/>');

					ELSE

						--case where no phone number entered

						dbms_lob_s.append(vEntries, '

							<telecom use="WP" nullFlavor="UNK"/>');					

					END IF;



					dbms_lob_s.append(vEntries, '

								<assignedPerson>

									<name>

								 <given>' || htf.escape_sc(TRIM(procRec."UserFirst")) || '</given>

								 <family>' || htf.escape_sc(TRIM(procRec."UserLast")) || '</family>

									</name>

								</assignedPerson>

								<representedOrganization>

									<id root="1.1.1.1.1.1.1.1.4"/>

									<name>

								 ' || htf.escape_sc(TRIM(procRec."Name")) || '

									</name>');



					IF NOT (trim(procRec."Phone") IS NULL or length(trim(procRec."Phone")) = 0) THEN

						dbms_lob_s.append(vEntries, '

							<telecom use="WP" value="');



						IF NOT (trim(procRec."Area") IS NULL or length(trim(procRec."Area")) = 0) THEN

							dbms_lob_s.append(vEntries, TRIM(procRec."Area") || '-');

						END IF;



						dbms_lob_s.append(vEntries, TRIM(procRec."Phone") ||'"/>');

					ELSE

						--case where no phone number entered

						dbms_lob_s.append(vEntries, '

							<telecom use="WP" nullFlavor="UNK"/>');					

					END IF;

				

					dbms_lob_s.append(vEntries, '

						<addr>');



					IF NOT (trim(procRec."Address1") IS NULL or length(trim(procRec."Address1")) = 0) THEN

					dbms_lob_s.append(vEntries, '

					<streetAddressLine>' || htf.escape_sc(trim(procRec."Address1")) || '</streetAddressLine>');

					-- AX-18945.19094e

					ELSE

						-- no street address entered

						dbms_lob_s.append(vEntries, '

							<streetAddressLine nullFlavor="UNK"/>');

					END IF;



					IF NOT (trim(procRec."Address2") IS NULL or length(trim(procRec."Address2")) = 0) THEN

					dbms_lob_s.append(vEntries, '

					<streetAddressLine>' || htf.escape_sc(trim(procRec."Address2")) || '</streetAddressLine>');

					END IF;





					IF NOT (trim(procRec."City") IS NULL or length(trim(procRec."City")) = 0) THEN

					dbms_lob_s.append(vEntries, '

					<city>' || htf.escape_sc(trim(procRec."City")) || '</city>');

					-- AX-18945.19094e

					ELSE

					-- patient city unknown

					dbms_lob_s.append(vEntries, '

					<city nullFlavor="UNK"/>');

					END IF;





					IF NOT (trim(procRec."Province") IS NULL or length(trim(procRec."Province")) = 0) THEN

					dbms_lob_s.append(vEntries, '

					<state>' || htf.escape_sc(trim(procRec."Province")) || '</state>');

					-- AX-18945.19094e

					ELSE

						--state unknown

						dbms_lob_s.append(vEntries, '

							<state nullFlavor="UNK"/>');

					END IF;



					IF NOT (trim(procRec."Postal") IS NULL or length(trim(procRec."Postal")) = 0) THEN

					dbms_lob_s.append(vEntries, '

					<postalCode>' || htf.escape_sc(trim(procRec."Postal")) || '</postalCode>');

		 			-- AX-18945.19094e

					ELSE

						dbms_lob_s.append(vEntries, '

							<postalCode nullFlavor="UNK"/>');

					END IF;





					dbms_lob_s.append(vEntries, '

					<country>' || 'US' || '</country>');



					dbms_lob_s.append(vEntries, '

					</addr>'); 



					dbms_lob_s.append(vEntries, '

								</representedOrganization>

							</assignedEntity>

							  </performer>');



					-- AX-26344

					-- loop through cursor...

					vTxNoteCount := 0;

					vLastId := 0;

					FOR cTxNote IN curTxNotes(procRec."ChartTrx") LOOP

						vTxNoteCount := vTxNoteCount + 1;



						IF cTxNote."Type" <> 4 OR (cTxNote."Type" = 4 AND vLastId <> cTxNote."OtherId") THEN

							dbms_lob_s.append(vEntries, '

								<!-- Note Activity entry -->

								<entryRelationship typeCode="COMP">

									<act classCode="ACT" moodCode="EVN">

										<templateId root="2.16.840.1.113883.10.20.22.4.202" extension="2016-11-01"/>

										<code code="34109-9" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC"

											displayName="Note">

											<translation code="28570-0" codeSystem="2.16.840.1.113883.6.1"

												codeSystemName="LOINC" displayName="Procedure note"/>

										</code>

										<text>

											<reference value="#procnote' || vTxNoteCount || '"/>

										</text>

										<statusCode code="completed"/>

										<!-- Clinically-relevant time of the note -->

										<effectiveTime value="' || TO_CHAR(cTxNote."Date", 'MM/DD/YYYY') || '"/>

										<!-- Author Participation -->

										<author>

											<templateId root="2.16.840.1.113883.10.20.22.4.119"/>

											<!-- Time note was actually written -->

											<time value="' || TO_CHAR(cTxNote."AddDateTime", 'MM/DD/YYYY HH:MM') || '"/>

											<assignedAuthor>

												<id extension="' || GetUserIdentifier(cTxNote."User") ||'" root="' ||GetUserIdentifierType ||'"/>

												<name>' || htf.escape_sc(TRIM(cTxNote."First")) || htf.escape_sc(TRIM(cTxNote."Name")) || '</name>

											</assignedAuthor>

										</author>

										<!-- Reference to encounter -->

										<entryRelationship nullFlavor="NA"/>

									</act>

								</entryRelationship>');

							END IF;



							IF cTxNote."Type" = 4 THEN

								vLastId := cTxNote."OtherId";

							END IF;

					END LOOP;





					dbms_lob_s.append(vEntries, '

						  </procedure>

						</entry>');



				END IF;

			END LOOP;

			

		END IF;



		IF vCount > 0 THEN

			--close the list

			dbms_lob_s.append(vText, '

							</tbody>	

						</table>

					</text>	

					');	

		ELSE

		

			IF vbShowInfo THEN					--B143328.3

				--handle case where there were no procedures

				-- human readable text

				dbms_lob_s.append(vText, '<text>No procedures are on file.</text>');

			ELSE

				dbms_lob_s.append(vText, '<text></text>');

			END IF;

			

			-- machine readable XML

			dbms_lob_s.append(vEntries, '

				 <entry typeCode="DRIV">

				    <procedure classCode="PROC" moodCode="EVN" negationInd="true">

					<templateId root="2.16.840.1.113883.10.20.22.4.14"/>

					<id root="2.16.840.1.113883.4.8155" />

					  <code nullFlavor="NA"/>

					  <statusCode code="completed"/>

					  <effectiveTime>

					    <low nullFlavor="UNK"/>

					  </effectiveTime>

				    </procedure>

				 </entry>

				');

				

		END IF;



		dbms_lob_s.append(vResult, vText);



		dbms_lob_s.append(vResult, vEntries);



		dbms_lob_s.append(vResult, '

		    </section>

		 </component>');



		return vResult;

	END;

  

 	-- Procedures section - contains details of all CDA/CPT procedures (conditions and findings are not shown)

	-- AX-18945.19095

	FUNCTION getproceduresection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob IS

		vPracticeRec PRACTICE%ROWTYPE;

		vResult CLOB := '';

		vText CLOB := '';

		vEntries CLOB := '';

		vCount NUMBER := 0;

		vTxNoteCount NUMBER := 0; -- AX-26344

		vNote CLOB := '';

		vLastNoteDate DATE := NULL;

		vStatusCode  VARCHAR2(32) := '';

		vFormName PFORM."FormCode"%TYPE := 'MUSMPR';

		vSnoMedProcName PITEM."AnsText"%TYPE := NULL;

		vSnoMedProcDate PITEM."AnsDate"%TYPE := NULL;

		vSnoMedProcDescription SNOCODE."Description"%TYPE := NULL;

		vLastId NUMBER := 0;



		-- B142392

		CURSOR curProc IS

			SELECT 

				T."ChartTrx", -- AX-26344

				htf.escape_sc(T."Description") as "Description", 

				T."Procedure", 

				T."TreatmentDate", 

				T."Producer", 

				T."Status", 

				U."User" AS "UserId", 

				U."Name" AS "UserLast", 

				U."First" AS "UserFirst",

				PR."Name", 

				PR."City", 

				PR."Province", 

				PR."Postal", 

				PR."NPI", 

				PR."Area" AS "Area", 

				PR."Phone", 

				PR."Address1", 

				PR."Address2",

				CASE 

					WHEN P."Category" IN (0,1,2,3,4,5,6,7,8,9) THEN '2.16.840.1.113883.6.13'

					WHEN P."Category" IN (10, 11, 12, 13, 14, 15, 16, 17, 18) THEN '2.16.840.1.113883.6.12'

				END AS "CodeSystem",

				CASE 

					WHEN P."Category" IN (0,1,2,3,4,5,6,7,8,9) THEN 'CDT'

					WHEN P."Category" IN (10, 11, 12, 13, 14, 15, 16, 17, 18) THEN 'CPT-4'

				END AS "CodeSystemName"

			FROM trx T, procedur P, users U, PRACTICE PR

			WHERE 1=1 

				AND T."Patient" = vPId 

				and T."Type" IN (1,5) 

				and T."Deleted" = 0 

				and P."Procedure" = T."Procedure" 

				AND P."IsStepChild" = 0

				and (NOT (TRIM(U."Producer") IS NULL OR length(TRIM(U."Producer")) = 0)

				AND T."Producer" = U."Producer") 

				AND T."Practice" = PR."Id"

				AND P."Category" NOT IN (20, 30) 

				-- AX-18945.19095

				AND 

				(

					(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(T."TreatmentDate") >= TRUNC(vDate1) AND TRUNC(T."TreatmentDate") <= TRUNC(vDate2))

					OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(T."TreatmentDate") >= TRUNC(vDate1))

					OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(T."TreatmentDate") <= TRUNC(vDate1)) 

					OR (vDate1 IS NULL)

				)

			ORDER BY T."TreatmentDate", T."Id", T."Treatment";



		CURSOR curSnowMedProcs IS

			SELECT PF."PForm"

			FROM PFORM PF

			WHERE 1=1 

				AND PF."FormCode" = vFormName

				AND PF."Patient" = vPId

				AND PF."Approved" = 1

				AND PF."Inactive" = 0

				AND 

				(

					(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PF."Date") >= TRUNC(vDate1) AND TRUNC(PF."Date") <= TRUNC(vDate2))

					OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PF."Date") >= TRUNC(vDate1))

					OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PF."Date") <= TRUNC(vDate1)) 

					OR (vDate1 IS NULL)

				)

			ORDER BY PF."CreatedDate" DESC;



		-- AX-26344

		CURSOR curTxNotes(cpTrxId NUMBER) IS

			SELECT DISTINCT

				n."Auto", -- AX-26430

				n."Type", -- AX-26430

				n."SectionNo",

				n."Text",    

				n."Date",  

				n."AddDateTime",    

				n."OtherId",

				n."User", 

				u."First", 

				u."Name"

			FROM 

			    notes2 n,

				trx    t,

				USERS   u

			WHERE 1=1 

				AND t."ChartTrx" > 0

				AND t."ChartTrx" = cpTrxId

				AND t."ChartTrx" = n."TxId" (+)

				AND n."Status" = 0

				AND n."AppUser" > 0

				AND n."User" = u."User" (+)

			ORDER BY n."Auto" desc, "SectionNo"; -- AX-26430

			

	   v_nCount		NUMBER := 0;								-- AX-26071.2



	BEGIN

	

		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetProcedureSection');

		IF v_nCount > 0 THEN

			-- custom package function exists ; AX-27290

			EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetProcedureSection(:1, :2, :3, :4, :5) FROM DUAL' INTO vResult

									USING vPId, vbShowInfo, vIsDateFrom, vDate1, vDate2;

			RETURN vResult;

		END IF;



		-- init clobs

		dbms_lob_s.createtemporary (vResult, TRUE);

		dbms_lob_s.createtemporary (vText, TRUE);

		dbms_lob_s.createtemporary (vEntries, TRUE);

		dbms_lob_s.createtemporary (vNote, TRUE);



		-- section header

		vResult := '

		<component>

		    <section>

		       <templateId root="2.16.840.1.113883.10.20.22.2.7.1"/>

		       <!-- Procedures section template -->

		       <code code="47519-4" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC"

			  displayName="HISTORY OF PROCEDURES"/>

		       <title>Procedures</title>';



		IF vbShowInfo THEN								--E143263.4

			-- loop thru all the procedures

			FOR procRec IN curProc LOOP                 

				

				vCount := vCount + 1;

				

				IF vCount = 1 THEN 

					-- add the list header if this is the first record

					-- AX-26344 - add notes...

					dbms_lob_s.append(vText, '

						<text>

							<table border="1" width="100%">

								<thead>

									<tr>

										<th>Procedure</th>

										<th>Date</th>

										<th>Notes</th>

									</tr>

								</thead>

								<tbody>		       			

						');				

				END IF;

				

				IF NOT (trim(procRec."Description") IS NULL or length(trim(procRec."Description")) = 0) THEN

					dbms_lob_s.append(vText, '

									<tr>

										<td><content ID="procedure' || vCount || '">' || htf.escape_sc(procRec."Description") || '</content></td>

										<td>' || TO_CHAR(procRec."TreatmentDate", 'MM/DD/YYYY') || '</td>

						');	



					-- AX-26344	- start

					dbms_lob_s.append(vText, '

										<td>

						');	

					

					-- AX-26430

					IF procRec."ChartTrx" > 0 THEN

						FOR cTxNote IN curTxNotes(procRec."ChartTrx") LOOP



							-- AX-26430

							IF vLastNoteDate IS NULL OR vLastNoteDate <> cTxNote."Date" THEN

								GetTxSOAPNotes(vPId, cTxNote."Date", procRec."ChartTrx", vText, vEntries, vTxNoteCount);

							END IF;



							IF NOT (trim(cTxNote."Text") IS NULL OR length(trim(cTxNote."Text")) = 0) AND cTxNote."Type" <> 4 THEN



								vTxNoteCount := vTxNoteCount + 1;

							

								SELECT REPLACE(cTxNote."Text", Chr(39), Chr(39)||Chr(39)) INTO vNote FROM DUAL;

								SELECT REPLACE(vNote, Chr(34), Chr(39)||Chr(39)) INTO vNote FROM DUAL;

								SELECT REPLACE(vNote, Chr(96), Chr(39)||Chr(39)) INTO vNote FROM DUAL;

								

								-- AX-26461

								dbms_lob_s.append(vText, '

												' || TO_CHAR(cTxNote."Date", 'MM/DD/YYYY') || '<br />

												<content ID="procnote' || vTxNoteCount || '">');	



								FOR Lines IN (select regexp_substr (vNote, '[^' || CHR(10)|| ']+', 1, rownum) Txt from dual 

									connect by level <= regexp_count (vNote, '[^' || CHR(10)|| ']+'))

								LOOP

									dbms_lob_s.append(vText, '

													' || htf.escape_sc(Lines.Txt) || '<br />

									');	

								END LOOP;	



								dbms_lob_s.append(vText, '

												</content>

								');	



								IF vTxNoteCount > 0 THEN 

									dbms_lob_s.append(vText, '

												<br />

									');	

								END IF;



							END IF;



							vLastNoteDate := cTxNote."Date";



						END LOOP;

					END IF;



					dbms_lob_s.append(vText, '

										</td>

									</tr>

						');	

					-- AX-26344	- end



					IF trim(procRec."Status") = 'C' THEN 

						vStatusCode := 'completed';

					ELSE

						vStatusCode := 'active';

					END IF;



					dbms_lob_s.append(vEntries, '

						<entry>

							  <procedure classCode="PROC" moodCode="EVN">

								  <!-- Procedure  Activity Procedure Template -->

								  <templateId root="2.16.840.1.113883.10.20.22.4.14"/>

								  <id root="2.16.840.1.113883.4.8155" />

								  <code xsi:type="CE" code="' || SUBSTR(TRIM(procRec."Procedure"),2) ||'" codeSystem="' || TRIM(procRec."CodeSystem") ||'"

								displayName="' || TRIM(procRec."Description") ||'"

								codeSystemName="' || TRIM(procRec."CodeSystemName") ||'">

								<originalText>

									<reference value="#procedure' || vCount || '"/>

								</originalText>

								  </code>

								  <statusCode code="' || vStatusCode || '"/>');



						dbms_lob_s.append(vEntries, '

								 <performer typeCode="PRF">

								<assignedEntity>

									<id extension="' || GetUserIdentifier(procRec."UserId") ||'" root="' ||GetUserIdentifierType ||'"/>');



					dbms_lob_s.append(vEntries, '

								<addr>');



					IF NOT (trim(procRec."Address1") IS NULL or length(trim(procRec."Address1")) = 0) THEN

						dbms_lob_s.append(vEntries, '

							<streetAddressLine>' || htf.escape_sc(trim(procRec."Address1")) || '</streetAddressLine>');

					-- AX-18945.19094e

					ELSE

						-- no street address entered

						dbms_lob_s.append(vEntries, '

							<streetAddressLine nullFlavor="UNK"/>');

					END IF;



					IF NOT (trim(procRec."Address2") IS NULL or length(trim(procRec."Address2")) = 0) THEN

						dbms_lob_s.append(vEntries, '

							<streetAddressLine>' || htf.escape_sc(trim(procRec."Address2")) || '</streetAddressLine>');

					END IF;



					IF NOT (trim(procRec."City") IS NULL or length(trim(procRec."City")) = 0) THEN

						dbms_lob_s.append(vEntries, '

							<city>' || htf.escape_sc(trim(procRec."City")) || '</city>');

					-- AX-18945.19094e

					ELSE

					-- patient city unknown

					dbms_lob_s.append(vEntries, '

					<city nullFlavor="UNK"/>');

					END IF;



					IF NOT (trim(procRec."Province") IS NULL or length(trim(procRec."Province")) = 0) THEN

						dbms_lob_s.append(vEntries, '

							<state>' || htf.escape_sc(trim(procRec."Province")) || '</state>');

					-- AX-18945.19094e

					ELSE

						--state unknown

						dbms_lob_s.append(vEntries, '

							<state nullFlavor="UNK"/>');

					END IF;



					IF NOT (trim(procRec."Postal") IS NULL or length(trim(procRec."Postal")) = 0) THEN

						dbms_lob_s.append(vEntries, '

							<postalCode>' || htf.escape_sc(trim(procRec."Postal")) || '</postalCode>');

		 			-- AX-18945.19094e

					ELSE

						dbms_lob_s.append(vEntries, '

							<postalCode nullFlavor="UNK"/>');

					END IF;





					dbms_lob_s.append(vEntries, '

							<country>' || 'US' || '</country>');



					dbms_lob_s.append(vEntries, '

							</addr>'); 



					IF NOT (trim(procRec."Phone") IS NULL or length(trim(procRec."Phone")) = 0) THEN

						dbms_lob_s.append(vEntries, '

							<telecom use="WP" value="');



						IF NOT (trim(procRec."Area") IS NULL or length(trim(procRec."Area")) = 0) THEN

							dbms_lob_s.append(vEntries, TRIM(procRec."Area") || '-');

						END IF;



						dbms_lob_s.append(vEntries, TRIM(procRec."Phone") ||'"/>');

					ELSE

						--case where no phone number entered

						dbms_lob_s.append(vEntries, '

							<telecom use="WP" nullFlavor="UNK"/>');					

					END IF;



					dbms_lob_s.append(vEntries, '

								<assignedPerson>

									<name>

								 <given>' || htf.escape_sc(TRIM(procRec."UserFirst")) || '</given>

								 <family>' || htf.escape_sc(TRIM(procRec."UserLast")) || '</family>

									</name>

								</assignedPerson>

								<representedOrganization>

									<id root="1.1.1.1.1.1.1.1.4"/>

									<name>

								 ' || htf.escape_sc(TRIM(procRec."Name")) || '

									</name>');



					IF NOT (trim(procRec."Phone") IS NULL or length(trim(procRec."Phone")) = 0) THEN

						dbms_lob_s.append(vEntries, '

							<telecom use="WP" value="');



						IF NOT (trim(procRec."Area") IS NULL or length(trim(procRec."Area")) = 0) THEN

							dbms_lob_s.append(vEntries, TRIM(procRec."Area") || '-');

						END IF;



						dbms_lob_s.append(vEntries, TRIM(procRec."Phone") ||'"/>');

					ELSE

						--case where no phone number entered

						dbms_lob_s.append(vEntries, '

							<telecom use="WP" nullFlavor="UNK"/>');					

					END IF;

				

					dbms_lob_s.append(vEntries, '

						<addr>');



					IF NOT (trim(procRec."Address1") IS NULL or length(trim(procRec."Address1")) = 0) THEN

					dbms_lob_s.append(vEntries, '

					<streetAddressLine>' || htf.escape_sc(trim(procRec."Address1")) || '</streetAddressLine>');

					-- AX-18945.19094e

					ELSE

						-- no street address entered

						dbms_lob_s.append(vEntries, '

							<streetAddressLine nullFlavor="UNK"/>');

					END IF;



					IF NOT (trim(procRec."Address2") IS NULL or length(trim(procRec."Address2")) = 0) THEN

					dbms_lob_s.append(vEntries, '

					<streetAddressLine>' || htf.escape_sc(trim(procRec."Address2")) || '</streetAddressLine>');

					END IF;





					IF NOT (trim(procRec."City") IS NULL or length(trim(procRec."City")) = 0) THEN

					dbms_lob_s.append(vEntries, '

					<city>' || htf.escape_sc(trim(procRec."City")) || '</city>');

					-- AX-18945.19094e

					ELSE

					-- patient city unknown

					dbms_lob_s.append(vEntries, '

					<city nullFlavor="UNK"/>');

					END IF;





					IF NOT (trim(procRec."Province") IS NULL or length(trim(procRec."Province")) = 0) THEN

					dbms_lob_s.append(vEntries, '

					<state>' || htf.escape_sc(trim(procRec."Province")) || '</state>');

					-- AX-18945.19094e

					ELSE

						--state unknown

						dbms_lob_s.append(vEntries, '

							<state nullFlavor="UNK"/>');

					END IF;



					IF NOT (trim(procRec."Postal") IS NULL or length(trim(procRec."Postal")) = 0) THEN

					dbms_lob_s.append(vEntries, '

					<postalCode>' || htf.escape_sc(trim(procRec."Postal")) || '</postalCode>');

		 			-- AX-18945.19094e

					ELSE

						dbms_lob_s.append(vEntries, '

							<postalCode nullFlavor="UNK"/>');

					END IF;





					dbms_lob_s.append(vEntries, '

					<country>' || 'US' || '</country>');



					dbms_lob_s.append(vEntries, '

					</addr>'); 



					dbms_lob_s.append(vEntries, '

								</representedOrganization>

							</assignedEntity>

							  </performer>');



					-- AX-26344

					-- loop through cursor...

					vTxNoteCount := 0;

					vLastId := 0;

					FOR cTxNote IN curTxNotes(procRec."ChartTrx") LOOP

						vTxNoteCount := vTxNoteCount + 1;



						IF cTxNote."Type" <> 4 OR (cTxNote."Type" = 4 AND vLastId <> cTxNote."OtherId") THEN

							dbms_lob_s.append(vEntries, '

								<!-- Note Activity entry -->

								<entryRelationship typeCode="COMP">

									<act classCode="ACT" moodCode="EVN">

										<templateId root="2.16.840.1.113883.10.20.22.4.202" extension="2016-11-01"/>

										<code code="34109-9" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC"

											displayName="Note">

											<translation code="28570-0" codeSystem="2.16.840.1.113883.6.1"

												codeSystemName="LOINC" displayName="Procedure note"/>

										</code>

										<text>

											<reference value="#procnote' || vTxNoteCount || '"/>

										</text>

										<statusCode code="completed"/>

										<!-- Clinically-relevant time of the note -->

										<effectiveTime value="' || TO_CHAR(cTxNote."Date", 'MM/DD/YYYY') || '"/>

										<!-- Author Participation -->

										<author>

											<templateId root="2.16.840.1.113883.10.20.22.4.119"/>

											<!-- Time note was actually written -->

											<time value="' || TO_CHAR(cTxNote."AddDateTime", 'MM/DD/YYYY HH:MM') || '"/>

											<assignedAuthor>

												<id extension="' || GetUserIdentifier(cTxNote."User") ||'" root="' ||GetUserIdentifierType ||'"/>

												<name>' || htf.escape_sc(TRIM(cTxNote."First")) || htf.escape_sc(TRIM(cTxNote."Name")) || '</name>

											</assignedAuthor>

										</author>

										<!-- Reference to encounter -->

										<entryRelationship nullFlavor="NA"/>

									</act>

								</entryRelationship>');

							END IF;



							IF cTxNote."Type" = 4 THEN

								vLastId := cTxNote."OtherId";

							END IF;

					END LOOP;



					dbms_lob_s.append(vEntries, '

						  </procedure>

						</entry>');



				END IF;

			END LOOP;



			-- AX-21739

			FOR cForm in curSnowMedProcs LOOP

				vCount := vCount + 1;

				

				-- get the info for this SNOMED procedure from the form...

				-- code

				BEGIN

					SELECT 

						TRIM(htf.escape_sc(PI."AnsText")) ,

						TRIM(htf.escape_sc(S."Description"))

					INTO vSnoMedProcName, vSnoMedProcDescription		

					FROM PITEM PI, FITEM FI, SNOCODE S

					WHERE 1=1 

						AND PI."FItem" = FI."FItem"

						AND PI."Patient" = vPId

						AND PI."FormCode" = vFormName

						AND PI."PForm" = cForm."PForm"

						AND FI."Deleted" = 0

						AND PI."Status" = 0

						AND PI."AppDate" IS NOT NULL

						AND FI."Code" = 'MUSMPROC'

						AND TRIM(PI."AnsText") = TRIM(S."SNOCode")

						AND 

						(

							(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

							OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

							OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

							OR (vDate1 IS NULL)

						);

						

				EXCEPTION WHEN OTHERS THEN

					vSnoMedProcName := NULL;

				END;			

				

				-- date

				BEGIN

					SELECT PI."AnsDate" INTO vSnoMedProcDate

					FROM PITEM PI, FITEM FI

					WHERE 1=1 

						AND PI."FItem" = FI."FItem"

						AND PI."Patient" = vPId

						AND PI."FormCode" = vFormName

						AND PI."PForm" = cForm."PForm"

						AND FI."Deleted" = 0

						AND PI."Status" = 0

						AND PI."AppDate" IS NOT NULL

						AND FI."Code" = 'MUSMDATE'

						AND 

						(

							(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

							OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

							OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

							OR (vDate1 IS NULL)

						);

						

				EXCEPTION WHEN OTHERS THEN

					vSnoMedProcDate := NULL;

				END;				

				

				IF vCount = 1 THEN 

					-- add the list header if this is the first record

					dbms_lob_s.append(vText, '

						<text>

							<table border="1" width="100%">

								<thead>

									<tr>

										<th>Procedure</th>

										<th>Date</th>

									</tr>

								</thead>

								<tbody>		       			

						');				

				END IF;

				

				IF NOT (trim(vSnoMedProcName) IS NULL OR length(trim(vSnoMedProcName)) = 0) THEN

					dbms_lob_s.append(vText, '

									<tr>

										<td><content ID="procedure' || vCount || '">' || htf.escape_sc(vSnoMedProcDescription) || '</content></td>

										<td>' || TO_CHAR(vSnoMedProcDate, 'MM/DD/YYYY') || '</td>

									</tr>

						');	



					dbms_lob_s.append(vEntries, '

						<entry>

							<procedure classCode="PROC" moodCode="EVN">

								<!-- Procedure  Activity Procedure Template -->

								<templateId root="2.16.840.1.113883.10.20.22.4.14"/>

								<id root="2.16.840.1.113883.4.8155" />

								<code xsi:type="CE" code="' || vSnoMedProcName ||'" codeSystem="2.16.840.1.113883.6.96"

									displayName="' || vSnoMedProcDescription ||'"

									codeSystemName="SNOMED CT">

									<originalText>

										<reference value="#procedure' || vCount || '"/>

									</originalText>

								</code>

									<statusCode code="completed"/>

							</procedure>

						</entry>');

				END IF;

			END LOOP;

			

		END IF;



		IF vCount > 0 THEN

			--close the list

			dbms_lob_s.append(vText, '

							</tbody>	

						</table>

					</text>	

					');	

		ELSE

		

			IF vbShowInfo THEN					--B143328.3

				--handle case where there were no procedures

				-- human readable text

				dbms_lob_s.append(vText, '<text>No procedures are on file.</text>');

			ELSE

				dbms_lob_s.append(vText, '<text></text>');

			END IF;

			

			-- machine readable XML

			dbms_lob_s.append(vEntries, '

				 <entry typeCode="DRIV">

				    <procedure classCode="PROC" moodCode="EVN" negationInd="true">

					<templateId root="2.16.840.1.113883.10.20.22.4.14"/>

					<id root="2.16.840.1.113883.4.8155" />

					  <code nullFlavor="NA"/>

					  <statusCode code="completed"/>

					  <effectiveTime>

					    <low nullFlavor="UNK"/>

					  </effectiveTime>

				    </procedure>

				 </entry>

				');

				

		END IF;



		dbms_lob_s.append(vResult, vText);



		dbms_lob_s.append(vResult, vEntries);



		dbms_lob_s.append(vResult, '

		    </section>

		 </component>');



		return vResult;

	END;  

  

  	-- E142544 - vital signs section

	-- AX-18945.19095

	FUNCTION getvitalsignssection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob IS

		vResult CLOB := '';

		vText CLOB := '';

		vEntries CLOB := '';

		

		vHeight PITEM."AnsText"%TYPE := '';

		vWeight PITEM."AnsText"%TYPE := '';

		vBMI PITEM."AnsText"%TYPE := '';

		vBPD PITEM."AnsText"%TYPE := '';

		vBPS PITEM."AnsText"%TYPE := '';



		-- AX-21119

		vHeartRate PITEM."AnsText"%TYPE := '';

		vRespRate PITEM."AnsText"%TYPE := '';

		vBodyTemp PITEM."AnsText"%TYPE := '';

		vO2Concentration PITEM."AnsText"%TYPE := '';

		vO2Oximetry PITEM."AnsText"%TYPE := '';	-- AX-21119b



		-- AX-21586.21907

		vHeightDate PITEM."Date"%TYPE := NULL;

		vWeightDate PITEM."Date"%TYPE := NULL;

		vBMIDate PITEM."Date"%TYPE := NULL;

		vBPDDate PITEM."Date"%TYPE := NULL;

		vBPSDate PITEM."Date"%TYPE := NULL;

		vHeartRateDate PITEM."Date"%TYPE := NULL;

		vRespRateDate PITEM."Date"%TYPE := NULL;

		vBodyTempDate PITEM."Date"%TYPE := NULL;

		vO2ConcentrationDate PITEM."Date"%TYPE := NULL;

		vO2OximetryDate PITEM."Date"%TYPE := NULL;

				

	   v_nCount		NUMBER := 0;								-- AX-26071.2



	BEGIN

		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetVitalSignsSection');

		IF v_nCount > 0 THEN

			-- custom package function exists; AX-27290 

			EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetVitalSignsSection(:1, :2, :3, :4, :5) FROM DUAL' INTO vResult

									USING vPId, vbShowInfo, vIsDateFrom, vDate1, vDate2;

			RETURN vResult;

		END IF;



		dbms_lob_s.createtemporary (vResult, TRUE);

		dbms_lob_s.createtemporary (vText, TRUE);

		dbms_lob_s.createtemporary (vEntries, TRUE);





		-- get the vital sign data from EPR form questions

		-- height

		BEGIN

			SELECT TRIM(P."AnsText"), P."Date" INTO vHeight, vHeightDate

			FROM PITEM P

			WHERE 1=1 

			  AND P."PItem" = (

			    SELECT MAX(PI."PItem")

			    FROM PITEM PI, FITEM FI

			    WHERE 1=1 

			      AND PI."FItem" = FI."FItem"

			      AND PI."Patient" = vPId

			      AND FI."Code" = 'PT_STD_HT'

			      AND PI."AppDate" IS NOT NULL

					-- AX-18945.19095

					AND 

					(

						(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

						OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

						OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

						OR (vDate1 IS NULL)

					));

			      

		EXCEPTION WHEN NO_DATA_FOUND THEN

			vHeight := NULL;

		END;

		

		IF (LENGTH(TRIM(vHeight)) = 0) THEN

			vHeight := NULL;

		END IF;



		-- weight

		BEGIN

			SELECT TRIM(P."AnsText"), P."Date" INTO vWeight, vWeightDate

			FROM PITEM P

			WHERE 1=1 

			  AND P."PItem" = (

			    SELECT MAX(PI."PItem")

			    FROM PITEM PI, FITEM FI

			    WHERE 1=1 

			      AND PI."FItem" = FI."FItem"

			      AND PI."Patient" = vPId

			      AND FI."Code" = 'PT_STD_WT'

			      AND PI."AppDate" IS NOT NULL

					-- AX-18945.19095

					AND 

					(

						(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

						OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

						OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

						OR (vDate1 IS NULL)

					));

			      

		EXCEPTION WHEN NO_DATA_FOUND THEN

			vWeight := NULL;

		END;

		

		IF (LENGTH(TRIM(vWeight)) = 0) THEN

			vWeight := NULL;

		END IF;



		-- bmi		

		BEGIN

			SELECT TRIM(P."AnsText"), P."Date" INTO vBMI, vBMIDate

			FROM PITEM P

			WHERE 1=1 

			  AND P."PItem" = (

			    SELECT MAX(PI."PItem")

			    FROM PITEM PI, FITEM FI

			    WHERE 1=1 

			      AND PI."FItem" = FI."FItem"

			      AND PI."Patient" = vPId

			      AND FI."Code" = 'PT_STD_BMI'

			      AND PI."AppDate" IS NOT NULL

					-- AX-18945.19095

					AND 

					(

						(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

						OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

						OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

						OR (vDate1 IS NULL)

					));

			      

		EXCEPTION WHEN NO_DATA_FOUND THEN

			vBMI := NULL;

		END;



		IF (LENGTH(TRIM(vBMI)) = 0) OR (vBMI = 'Invalid inputs provided.') THEN

			vBMI := NULL;

		END IF;

		

		-- blood pressure - systolic		

		BEGIN

			SELECT TRIM(P."AnsText"), P."Date" INTO vBPS, vBPSDate

			FROM PITEM P

			WHERE 1=1 

			  AND P."PItem" = (

			    SELECT MAX(PI."PItem")

			    FROM PITEM PI, FITEM FI

			    WHERE 1=1 

			      AND PI."FItem" = FI."FItem"

			      AND PI."Patient" = vPId

			      AND FI."Code" = 'MDH_SBP'

			      AND PI."AppDate" IS NOT NULL

					-- AX-18945.19095

					AND 

					(

						(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

						OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

						OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

						OR (vDate1 IS NULL)

					));

			      

		EXCEPTION WHEN NO_DATA_FOUND THEN

			vBPS := NULL;

		END;



		IF (LENGTH(TRIM(vBPS)) = 0) THEN

			vBPS := NULL;

		END IF;

		

		-- blood pressure - diastolic		

		BEGIN

			SELECT TRIM(P."AnsText"), P."Date" INTO vBPD, vBPDDate

			FROM PITEM P

			WHERE 1=1 

			  AND P."PItem" = (

			    SELECT MAX(PI."PItem")

			    FROM PITEM PI, FITEM FI

			    WHERE 1=1 

			      AND PI."FItem" = FI."FItem"

			      AND PI."Patient" = vPId

			      AND FI."Code" = 'MDH_DBP'

			      AND PI."AppDate" IS NOT NULL

					-- AX-18945.19095

					AND 

					(

						(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

						OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

						OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

						OR (vDate1 IS NULL)

					));

			      

		EXCEPTION WHEN NO_DATA_FOUND THEN

			vBPD := NULL;

		END;



		IF (LENGTH(TRIM(vBPD)) = 0) THEN

			vBPD := NULL;

		END IF;



		-- AX-21119

		-- heart rate

		BEGIN

			SELECT TRIM(P."AnsText"), P."Date" INTO vHeartRate, vHeartRateDate

			FROM PITEM P

			WHERE 1=1 

			  AND P."PItem" = (

			    SELECT MAX(PI."PItem")

			    FROM PITEM PI, FITEM FI

			    WHERE 1=1 

			      AND PI."FItem" = FI."FItem"

			      AND PI."Patient" = vPId

			      AND FI."Code" = 'PT_STD_HR'

			      AND PI."AppDate" IS NOT NULL

					AND 

					(

						(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

						OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

						OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

						OR (vDate1 IS NULL)

					));

			      

		EXCEPTION WHEN NO_DATA_FOUND THEN

			vHeartRate := NULL;

		END;

		

		IF (LENGTH(TRIM(vHeartRate)) = 0) THEN

			vHeartRate := NULL;

		END IF;



		-- AX-21119

		-- respiratory  rate

		BEGIN

			SELECT TRIM(P."AnsText") , P."Date" INTO vRespRate, vRespRateDate

			FROM PITEM P

			WHERE 1=1 

			  AND P."PItem" = (

			    SELECT MAX(PI."PItem")

			    FROM PITEM PI, FITEM FI

			    WHERE 1=1 

			      AND PI."FItem" = FI."FItem"

			      AND PI."Patient" = vPId

			      AND FI."Code" = 'PT_STD_RR'

			      AND PI."AppDate" IS NOT NULL

					AND 

					(

						(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

						OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

						OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

						OR (vDate1 IS NULL)

					));

			      

		EXCEPTION WHEN NO_DATA_FOUND THEN

			vRespRate := NULL;

		END;

		

		IF (LENGTH(TRIM(vRespRate)) = 0) THEN

			vRespRate := NULL;

		END IF;



		-- AX-21119

		-- body temperature

		BEGIN

			SELECT TRIM(P."AnsText"), P."Date" INTO vBodyTemp, vBodyTempDate

			FROM PITEM P

			WHERE 1=1 

			  AND P."PItem" = (

			    SELECT MAX(PI."PItem")

			    FROM PITEM PI, FITEM FI

			    WHERE 1=1 

			      AND PI."FItem" = FI."FItem"

			      AND PI."Patient" = vPId

			      AND FI."Code" = 'PT_STD_BT'

			      AND PI."AppDate" IS NOT NULL

					AND 

					(

						(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

						OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

						OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

						OR (vDate1 IS NULL)

					));

			      

		EXCEPTION WHEN NO_DATA_FOUND THEN

			vBodyTemp := NULL;

		END;

		

		IF (LENGTH(TRIM(vBodyTemp)) = 0) THEN

			vBodyTemp := NULL;

		END IF;



		-- AX-21119b

		-- O2 % BldC Oximetry

		BEGIN

			SELECT TRIM(P."AnsText"), P."Date" INTO vO2Oximetry, vO2OximetryDate

			FROM PITEM P

			WHERE 1=1 

			  AND P."PItem" = (

			    SELECT MAX(PI."PItem")

			    FROM PITEM PI, FITEM FI

			    WHERE 1=1 

			      AND PI."FItem" = FI."FItem"

			      AND PI."Patient" = vPId

			      AND FI."Code" = 'PT_STD_SPO'

			      AND PI."AppDate" IS NOT NULL

					AND 

					(

						(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

						OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

						OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

						OR (vDate1 IS NULL)

					));

			      

		EXCEPTION WHEN NO_DATA_FOUND THEN

			vO2Oximetry := NULL;

		END;

		

		IF (LENGTH(TRIM(vO2Concentration)) = 0) THEN

			vO2Oximetry := NULL;

		END IF;





		-- AX-21119

		-- inhaled oxygen concentration

		BEGIN

			SELECT TRIM(P."AnsText"), P."Date" INTO vO2Concentration, vO2ConcentrationDate

			FROM PITEM P

			WHERE 1=1 

			  AND P."PItem" = (

			    SELECT MAX(PI."PItem")

			    FROM PITEM PI, FITEM FI

			    WHERE 1=1 

			      AND PI."FItem" = FI."FItem"

			      AND PI."Patient" = vPId

			      AND FI."Code" = 'PT_STD_IOC'

			      AND PI."AppDate" IS NOT NULL

					AND 

					(

						(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

						OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

						OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

						OR (vDate1 IS NULL)

					));

			      

		EXCEPTION WHEN NO_DATA_FOUND THEN

			vO2Concentration := NULL;

		END;

		

		IF (LENGTH(TRIM(vO2Concentration)) = 0) THEN

			vO2Concentration := NULL;

		END IF;





		-- XML

		dbms_lob_s.append(vResult, '

			<component>

			  <section>

			    <!-- Vital Signs (entries optional) -->

			    <templateId root="2.16.840.1.113883.10.20.22.2.4.1" extension="2015-08-01"/>

				 <templateId root="2.16.840.1.113883.10.20.22.2.4.1"/>

			    <code code="8716-3" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="VITAL SIGNS"/>

			    <title>Vital Signs</title>

			    ');

			

		--B143328.3

		-- AX-21119     

		IF NOT vbShowInfo THEN

			dbms_lob_s.append(vText, '

				<text>

					<table border="1" width="100%">

						<thead>

							<tr>

								<th>Vital Sign</th>

								<th>Measurement</th>

								<th>Units</th>

								<th>Date</th>

							</tr>

						</thead>

						<tbody>

							<tr>

								<td><content ID="vit1">Height</content></td>

								<td></td>

								<td>cm</td>

								<td></td>

							</tr>

							<tr>

								<td><content ID="vit2">Weight</content></td>

								<td></td>

								<td>kg</td>

								<td></td>

							</tr>

							<tr>

								<td><content ID="vit3">BMI</content></td>

								<td></td>

								<td>kg/m2</td>

								<td></td>

							</tr>

							<tr>

								<td><content ID="vit4">Systolic Blood Pressure</content></td>

								<td></td>

								<td>mmHg</td>

								<td></td>

							</tr>

							<tr>

								<td><content ID="vit5">Diastolic Blood Pressure</content></td>

								<td></td>

								<td>mmHg</td>

								<td></td>

							</tr>		

							<tr>

								<td><content ID="vit6">Heart Rate</content></td>

								<td></td>

								<td>min</td>

								<td></td>

							</tr>	

							<tr>

								<td><content ID="vit7">Respiratory Rate</content></td>

								<td></td>

								<td>min</td>

								<td></td>

							</tr>	

							<tr>

								<td><content ID="vit8">Body Temperature</content></td>

								<td></td>

								<td>cel</td>

								<td></td>

							</tr>	

							<tr>

								<td><content ID="vit10">Oxygen Saturation (SPO2)</content></td>

								<td></td>

								<td>%</td>

								<td></td>

							</tr>			

							<tr>

								<td><content ID="vit11">Inhaled Oxygen Concentration (FIO2)</content></td>

								<td></td>

								<td>%</td>

								<td></td>

							</tr>				

						</tbody>

					</table>

				</text>

			    ');

		ELSE

		

			dbms_lob_s.append(vText, '

				<text>

					<table border="1" width="100%">

						<thead>

							<tr>

								<th>Vital Sign</th>

								<th>Measurement</th>

								<th>Units</th>

								<th>Date</th>

							</tr>

						</thead>

						<tbody>

							<tr>

								<td><content ID="vit1">Height</content></td>

								<td>'|| NVL(vHeight,'Unknown') ||'</td>

								<td>cm</td>

								<td>'|| NVL(TO_CHAR(vHeightDate, 'MM/DD/YYYY'),'') ||'</td>

							</tr>

							<tr>

								<td><content ID="vit2">Weight</content></td>

								<td>'|| NVL(vWeight,'Unknown') ||'</td>

								<td>kg</td>

								<td>'|| NVL(TO_CHAR(vWeightDate, 'MM/DD/YYYY'),'') ||'</td>

							</tr>

							<tr>

								<td><content ID="vit3">BMI</content></td>

								<td>'|| NVL(vBMI,'Unknown') ||'</td>

								<td>kg/m2</td>

								<td>'|| NVL(TO_CHAR(vBMIDate, 'MM/DD/YYYY'),'') ||'</td>

							</tr>

							<tr>

								<td><content ID="vit4">Systolic Blood Pressure</content></td>

								<td>'|| NVL(vBPS,'Unknown') ||'</td>

								<td>mmHg</td>

								<td>'|| NVL(TO_CHAR(vBPSDate, 'MM/DD/YYYY'),'') ||'</td>

							</tr>

							<tr>

								<td><content ID="vit5">Diastolic Blood Pressure</content></td>

								<td>'|| NVL(vBPD,'Unknown') ||'</td>

								<td>mmHg</td>

								<td>'|| NVL(TO_CHAR(vBPDDate, 'MM/DD/YYYY'),'') ||'</td>

							</tr>		

							<tr>

								<td><content ID="vit6">Heart Rate</content></td>

								<td>'|| NVL(vHeartRate,'Unknown') ||'</td>

								<td>min</td>

								<td>'|| NVL(TO_CHAR(vHeartRateDate, 'MM/DD/YYYY'),'') ||'</td>

							</tr>	

							<tr>

								<td><content ID="vit7">Respiratory Rate</content></td>

								<td>'|| NVL(vRespRate,'Unknown') ||'</td>

								<td>min</td>

								<td>'|| NVL(TO_CHAR(vRespRateDate, 'MM/DD/YYYY'),'') ||'</td>

							</tr>	

							<tr>

								<td><content ID="vit8">Body Temperature</content></td>

								<td>'|| NVL(vBodyTemp,'Unknown') ||'</td>

								<td>cel</td>

								<td>'|| NVL(TO_CHAR(vBodyTempDate, 'MM/DD/YYYY'),'') ||'</td>

							</tr>	

							<tr>

								<td><content ID="vit10">Oxygen Saturation (SPO2)</content></td>

								<td>'|| NVL(vO2Oximetry,'Unknown') ||'</td>

								<td>%</td>

								<td>'|| NVL(TO_CHAR(vO2OximetryDate, 'MM/DD/YYYY'),'') ||'</td>

							</tr>			

							<tr>

								<td><content ID="vit11">Inhaled Oxygen Concentration (FIO2)</content></td>

								<td>'|| NVL(vO2Concentration,'Unknown') ||'</td>

								<td>%</td>

								<td>'|| NVL(TO_CHAR(vO2ConcentrationDate, 'MM/DD/YYYY'),'') ||'</td>

							</tr>				

						</tbody>

					</table>

				</text>

			    ');

		END IF;

			

		-- organizer header

		-- AX-18696.19067

		dbms_lob_s.append(vEntries, '

		           <entry>

				<organizer classCode="CLUSTER" moodCode="EVN">

				  <!-- Vital signs organizer template -->

				  <templateId root="2.16.840.1.113883.10.20.22.4.26" extension="2015-08-01"/>

				  <templateId root="2.16.840.1.113883.10.20.22.4.26"/>

				  <id root="2.16.840.1.113883.4.8155" />



				  <code code="46680005" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" displayName="Vital Signs">

						<translation code="74728-7" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Vital Signs"/>

				  </code>

				  <statusCode code="completed"/>

				  <effectiveTime nullFlavor="UNK"/>');

		

		-- vital sign entries - height

		dbms_lob_s.append(vEntries, '

		                     <component>

		                        <observation classCode="OBS" moodCode="EVN">

		                           <templateId root="2.16.840.1.113883.10.20.22.4.27" extension="2014-06-09"/>

											<templateId root="2.16.840.1.113883.10.20.22.4.27"/>

		                           <!-- Vital Sign Observation template -->

		                           <id root="2.16.840.1.113883.4.8155" />

		                           <code code="8302-2" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Height"/>

		                           <text><reference value="#vit1"/></text>

		                           <statusCode code="completed"/>

		                           <effectiveTime nullFlavor="UNK"/>');

		IF NOT vbShowInfo OR vHeight IS NULL THEN						--E143263.4

			dbms_lob_s.append(vEntries, '

					   <value xsi:type="PQ" nullFlavor="UNK"/>');

		ELSE	

			dbms_lob_s.append(vEntries, '

					   <value xsi:type="PQ" value="'|| vHeight ||'" unit="cm"/>'); -- AX-18945.19094e, -- AX-21804

		END IF;

		                           

		                           

		dbms_lob_s.append(vEntries, '                           

		                        </observation>

		                     </component>');



		-- vital sign entries - weight

		-- AX-21804

		dbms_lob_s.append(vEntries, '

				    <component>

					<observation classCode="OBS" moodCode="EVN">

					   <templateId root="2.16.840.1.113883.10.20.22.4.27" extension="2014-06-09"/>

						<templateId root="2.16.840.1.113883.10.20.22.4.27"/>

					   <!-- Vital Sign Observation template -->

					   <id root="2.16.840.1.113883.4.8155" />

					   <code code="29463-7" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Weight measured"/> 

					   <text><reference value="#vit2"/></text>

					   <statusCode code="completed"/>

					   <effectiveTime nullFlavor="UNK"/>');

		IF NOT vbShowInfo OR vWeight IS NULL THEN						--E143263.4

			dbms_lob_s.append(vEntries, '

					    <value xsi:type="PQ" nullFlavor="UNK"/>');

		ELSE	

			dbms_lob_s.append(vEntries, '

					   <value xsi:type="PQ" value="'|| vWeight ||'" unit="kg"/>'); -- AX-18945.19094e, AX-21804

		END IF;

		                           

		                           

		dbms_lob_s.append(vEntries, '                           

		                        </observation>

		                     </component>');		

		                     

		-- vital sign entries - bmi

		dbms_lob_s.append(vEntries, '

					<component>

					  <observation classCode="OBS" moodCode="EVN">

					   <templateId root="2.16.840.1.113883.10.20.22.4.27" extension="2014-06-09"/>

						<templateId root="2.16.840.1.113883.10.20.22.4.27"/>

					   <!-- Vital Sign Observation template -->

					   <id root="2.16.840.1.113883.4.8155" />

					   <code code="39156-5" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="BMI"/>

					   <text><reference value="#vit3"/></text>

					   <statusCode code="completed"/>

					   <effectiveTime nullFlavor="UNK"/>');

					

		IF NOT vbShowInfo OR vBMI IS NULL THEN							--E143263.4

			dbms_lob_s.append(vEntries, '

					   <value xsi:type="PQ" nullFlavor="UNK"/>');

		ELSE	

			dbms_lob_s.append(vEntries, '

					   <value xsi:type="PQ" value="'|| vBMI ||'" unit="kg/m2"/>');

		END IF;

		                           

		                           

		dbms_lob_s.append(vEntries, '                           

		                        </observation>

		                     </component>');	

		                     

		-- vital sign entries - systolic BP

		dbms_lob_s.append(vEntries, '

		                    <component>

					<observation classCode="OBS" moodCode="EVN">

					   <templateId root="2.16.840.1.113883.10.20.22.4.27" extension="2014-06-09"/>

						<templateId root="2.16.840.1.113883.10.20.22.4.27"/>

					   <!-- Vital Sign Observation template -->

					   <id root="2.16.840.1.113883.4.8155" />

					   <code code="8480-6" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="BP Systolic"/>

					   <text><reference value="#vit4"/></text>

					   <statusCode code="completed"/>

					   <effectiveTime nullFlavor="UNK"/>');

				     

		IF NOT vbShowInfo OR vBPS IS NULL THEN						--E143263.4

			dbms_lob_s.append(vEntries, '

					    <value xsi:type="PQ" nullFlavor="UNK"/>');

		ELSE	

			dbms_lob_s.append(vEntries, '

					   <value xsi:type="PQ" value="'|| vBPS ||'" unit="mm[Hg]"/>'); -- AX-18945.19094e 

		END IF;

		                           

		                           

		dbms_lob_s.append(vEntries, '                           

		                        </observation>

		                     </component>');					 

		                     

		-- vital sign entries - diastolic BP

		-- AX-21804

		dbms_lob_s.append(vEntries, '

				     <component>

					<observation classCode="OBS" moodCode="EVN">

					   <templateId root="2.16.840.1.113883.10.20.22.4.27" extension="2014-06-09"/>

						<templateId root="2.16.840.1.113883.10.20.22.4.27"/>

					   <!-- Vital Sign Observation template -->

					   <id root="2.16.840.1.113883.4.8155" />

					   <code code="8462-4" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="BP Diastolic"/>

					   <text><reference value="#vit5"/></text>

					   <statusCode code="completed"/>

					   <effectiveTime nullFlavor="UNK"/>');

					   

		IF NOT vbShowInfo OR vBPD IS NULL THEN					--E143263.4

			dbms_lob_s.append(vEntries, '

					   <value xsi:type="PQ" nullFlavor="UNK"/>');

		ELSE	

			dbms_lob_s.append(vEntries, '

					   <value xsi:type="PQ" value="'|| vBPD ||'" unit="mm[Hg]"/>'); -- AX-18945.19094e 

		END IF;

		                           

		                           

		dbms_lob_s.append(vEntries, '                           

		                        </observation>

		                     </component>');		

									

		-- AX-21119

		-- vital sign entries - heart rate

		dbms_lob_s.append(vEntries, '

				     <component>

					<observation classCode="OBS" moodCode="EVN">

					   <templateId root="2.16.840.1.113883.10.20.22.4.27" extension="2014-06-09"/>

						<templateId root="2.16.840.1.113883.10.20.22.4.27"/>

					   <!-- Vital Sign Observation template -->

					   <id root="2.16.840.1.113883.4.8155" />

					   <code code="8867-4" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Heart Rate"/>

					   <text><reference value="#vit6"/></text>

					   <statusCode code="completed"/>

					   <effectiveTime nullFlavor="UNK"/>');

					   

		IF NOT vbShowInfo OR vHeartRate IS NULL THEN

			dbms_lob_s.append(vEntries, '

					   <value xsi:type="PQ" nullFlavor="UNK"/>');

		ELSE	

			dbms_lob_s.append(vEntries, '

					   <value xsi:type="PQ" value="'|| vHeartRate ||'" unit="/min"/>');

		END IF;

		                           

		dbms_lob_s.append(vEntries, '                           

		                        </observation>

		                     </component>');										

		

		-- AX-21119

		-- vital sign entries - respiratory rate

		dbms_lob_s.append(vEntries, '

				     <component>

					<observation classCode="OBS" moodCode="EVN">

					   <templateId root="2.16.840.1.113883.10.20.22.4.27" extension="2014-06-09"/>

						<templateId root="2.16.840.1.113883.10.20.22.4.27"/>

					   <!-- Vital Sign Observation template -->

					   <id root="2.16.840.1.113883.4.8155" />

					   <code code="9279-1" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Respiratory Rate"/>

					   <text><reference value="#vit7"/></text>

					   <statusCode code="completed"/>

					   <effectiveTime nullFlavor="UNK"/>');

					   

		IF NOT vbShowInfo OR vRespRate IS NULL THEN

			dbms_lob_s.append(vEntries, '

					   <value xsi:type="PQ" nullFlavor="UNK"/>');

		ELSE	

			dbms_lob_s.append(vEntries, '

					   <value xsi:type="PQ" value="'|| vRespRate ||'" unit="/min"/>');

		END IF;

		                           

		dbms_lob_s.append(vEntries, '                           

		                        </observation>

		                     </component>');	



		-- AX-21119

		-- vital sign entries - body temperature

		dbms_lob_s.append(vEntries, '

				     <component>

					<observation classCode="OBS" moodCode="EVN">

					   <templateId root="2.16.840.1.113883.10.20.22.4.27" extension="2014-06-09"/>

						<templateId root="2.16.840.1.113883.10.20.22.4.27"/>

					   <!-- Vital Sign Observation template -->

					   <id root="2.16.840.1.113883.4.8155" />

					   <code code="8310-5" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Body Temperature"/>

					   <text><reference value="#vit8"/></text>

					   <statusCode code="completed"/>

					   <effectiveTime nullFlavor="UNK"/>');

					   

		IF NOT vbShowInfo OR vBodyTemp IS NULL THEN

			dbms_lob_s.append(vEntries, '

					   <value xsi:type="PQ" nullFlavor="UNK"/>');

		ELSE	

			dbms_lob_s.append(vEntries, '

					   <value xsi:type="PQ" value="'|| vBodyTemp ||'" unit="Cel"/>'); -- AX-21804

		END IF;

		                           

		dbms_lob_s.append(vEntries, '                           

		                        </observation>

		                     </component>');	



		-- AX-21119b

		-- vital sign entries - O2 % BldC Oximetry

		dbms_lob_s.append(vEntries, '

				     <component>

					<observation classCode="OBS" moodCode="EVN">

					   <templateId root="2.16.840.1.113883.10.20.22.4.27" extension="2014-06-09"/>

						<templateId root="2.16.840.1.113883.10.20.22.4.27"/>

					   <!-- Vital Sign Observation template -->

					   <id root="2.16.840.1.113883.4.8155" />

					   <code code="59408-5" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="O2 % BlodC Oximetry"/>

					   <text><reference value="#vit10"/></text>

					   <statusCode code="completed"/>

					   <effectiveTime nullFlavor="UNK"/>');

					   

		IF NOT vbShowInfo OR vO2Oximetry IS NULL THEN

			dbms_lob_s.append(vEntries, '

					   <value xsi:type="PQ" nullFlavor="UNK"/>');

		ELSE	

			dbms_lob_s.append(vEntries, '

					   <value xsi:type="PQ" value="'|| vO2Oximetry ||'" unit="%"/>');

		END IF;

		                           

		dbms_lob_s.append(vEntries, '                           

		                        </observation>

		                     </component>');	



		-- AX-21119, AX-21804

		-- vital sign entries - inhaled oxygen concentration

		dbms_lob_s.append(vEntries, '

				     <component>

					<observation classCode="OBS" moodCode="EVN">

					   <templateId root="2.16.840.1.113883.10.20.22.4.27" extension="2014-06-09"/>

						<templateId root="2.16.840.1.113883.10.20.22.4.27"/>

					   <!-- Vital Sign Observation template -->

					   <id root="2.16.840.1.113883.4.8155" />

					   <code code="3150-0" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Inhaled Oxygen Concentration"/>

					   <text><reference value="#vit11"/></text>

					   <statusCode code="completed"/>

					   <effectiveTime nullFlavor="UNK"/>');

					   

		IF NOT vbShowInfo OR vO2Concentration IS NULL THEN

			dbms_lob_s.append(vEntries, '

					   <value xsi:type="PQ" nullFlavor="UNK"/>');

		ELSE	

			dbms_lob_s.append(vEntries, '

					   <value xsi:type="PQ" value="'|| vO2Concentration ||'" unit="%"/>');

		END IF;

		                           

		dbms_lob_s.append(vEntries, '                           

		                        </observation>

		                     </component>');	



		-- organizer footer

		dbms_lob_s.append(vEntries, '

				</organizer>

			   </entry>');

			

		dbms_lob_s.append(vResult, vText);

		dbms_lob_s.append(vResult, vEntries);



		dbms_lob_s.append(vResult, '               

			  </section>

			</component>');



		return vResult;

	END;

	

  	-- E142548 - Medical Test Results section

	-- shows complete history of finalized or correct medical tests and their results, in descending order by date

	-- AX-18945.19095

	FUNCTION getresultssection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob IS

		vResult CLOB := '';

		vText CLOB := '';

		vEntries CLOB := '';

	

		-- cursor of finalized medical tests - MTESTREQ

		CURSOR curTests IS

			SELECT 

				MT."MTestReq", 

				MT."LOINC", 

				MT."Status", 

				HTF.ESCAPE_SC(LC."LongCommonName") AS "Description",

				MT."RequestDateTime"

			FROM MTESTREQ MT, MTESTORD MO, LOINC LC

			WHERE 1=1

				AND MT."MTestOrd" = MO."MTestOrd"

				AND MO."Deleted" = 0

				AND MO."Patient" = vPId

				AND MT."LOINC" = LC."LOINC"

				AND MT."Status" IN ('F','C')

				-- AX-18945.19095

				AND 

				(

					(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND MT."RequestDateTime" >= vDate1 AND MT."RequestDateTime" <= vDate2)

					OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND MT."RequestDateTime" >= vDate1)

					OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND MT."RequestDateTime" <= vDate1) 

					OR (vDate1 IS NULL)

				)

			ORDER BY MT."RequestDateTime" DESC;

		

		

		-- parameterized cursor of medical test results - MTESTRES

		CURSOR curResults (cpMTestReq MTESTREQ."MTestReq"%TYPE) IS

			SELECT 

				MR."ResultNumber", 

				MR."LOINC",

				HTF.ESCAPE_SC(LC."LongCommonName") AS "Description",

				TO_CHAR(MR."AnalysisDateTime",'YYYYMMDD') AS "EffTime",

				HTF.ESCAPE_SC(MR."ResultValue") AS "ResultValue",

				HTF.ESCAPE_SC(MR."ResultUnits")  AS "ResultUnits", 

				MR."Abnormal",

				CASE

					WHEN MR."Abnormal" = 'N' THEN 'Normal'

					WHEN MR."Abnormal" = 'L' THEN 'Below low normal'

					WHEN MR."Abnormal" = 'H' THEN 'Above high normal'

					WHEN MR."Abnormal" = 'LL' THEN 'Below lower panic limits'

					WHEN MR."Abnormal" = 'HH' THEN 'Above upper panic limits'

					WHEN MR."Abnormal" = 'LESS' THEN 'Below absolute low - off instrument scale'

					WHEN MR."Abnormal" = 'GREATER' THEN 'Above absolute high - off instrument scale'

					WHEN MR."Abnormal" = 'A' THEN 'Abnormal'

					WHEN MR."Abnormal" = 'AA' THEN 'Very abnormal'

					WHEN MR."Abnormal" = 'U' THEN 'Significant change up'

					WHEN MR."Abnormal" = 'D' THEN 'Significant change down'

					WHEN MR."Abnormal" = 'B' THEN 'Better'

					WHEN MR."Abnormal" = 'W' THEN 'Worse'

					WHEN MR."Abnormal" = 'AC' THEN 'Anti-complementary substances present'

					WHEN MR."Abnormal" = 'TOX' THEN 'Cytotoxic substance present'

					WHEN MR."Abnormal" = 'DET' THEN 'Detected'

					WHEN MR."Abnormal" = 'IND' THEN 'Indeterminate'

					WHEN MR."Abnormal" = 'I' THEN 'Intermediate'

					WHEN MR."Abnormal" = 'MS' THEN 'Moderately susceptible'

					WHEN MR."Abnormal" = 'NEG' THEN 'Negative'

					WHEN MR."Abnormal" = 'NULL' THEN 'No range defined or normal ranges don''t apply'

					WHEN MR."Abnormal" = 'NR' THEN 'Non-reactive'

					WHEN MR."Abnormal" = 'ND' THEN 'Not Detected'

					WHEN MR."Abnormal" = 'POS' THEN 'Positive'

					WHEN MR."Abnormal" = 'QCF' THEN 'Quality Control Failure'

					WHEN MR."Abnormal" = 'RR' THEN 'Reactive'

					WHEN MR."Abnormal" = 'R' THEN 'Resistant'

					WHEN MR."Abnormal" = 'S' THEN 'Susceptible'

					WHEN MR."Abnormal" = 'VS' THEN 'Very susceptible'

					WHEN MR."Abnormal" = 'WR' THEN 'Weakly reactive'

					ELSE MR."Abnormal"

					END AS "Interpretation",

				HTF.ESCAPE_SC(MR."ReferenceRange")  AS "ReferenceRange",

				ML.*

			FROM MTESTRES MR, MTESTREQ MT, LOINC LC, MTESTLAB ML

			WHERE 1=1

				AND MR."MTestReq" = MT."MTestReq"

				AND MR."MTestReq" = cpMTestReq

				AND MR."Deleted" = 0

				AND MR."LOINC" = LC."LOINC"

				AND MR."MTestLab" = ML."MTestLab"

				-- AX-18945.19095

				AND 

				(

					(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND MR."ObservationDateTime" >= vDate1 AND MR."ObservationDateTime" <= vDate2)

					OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND MR."ObservationDateTime" >= vDate1)

					OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND MR."ObservationDateTime" <= vDate1) 

					OR (vDate1 IS NULL)

				)

			ORDER BY MR."ResultNumber";

  

		--flags

		vTestCount NUMBER := 0;

		vResultCount NUMBER := 0;

		vHasResults NUMBER := 0;



		vLabName  VARCHAR2(4000) := ''; 

		vLabAddress  VARCHAR2(4000) := ''; 

		vLabCity  VARCHAR2(4000) := ''; 

		vLabProvince  VARCHAR2(4000) := ''; 

		vLabPostal  VARCHAR2(4000) := ''; 

		vDiagCode PITEM."AnsText"%TYPE := ''; 

		vDiagCodeText PITEM."AnsText"%TYPE := ''; 

		vDiagCodeDate PITEM."AnsDate"%TYPE := NULL;

                -- SAMIR_BOUDJEBLA addded the lignes below



        vDiagCodeTextDetail PITEM."AnsText"%TYPE := ''; 

                -- SAMIR_BOUDJEBLA addded the lignes Above





		vResultValue  VARCHAR2(4000) := ''; 

	

	   v_nCount		NUMBER := 0;								-- AX-26071.2



	BEGIN

		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetResultsSection');

		IF v_nCount > 0 THEN

			-- custom package function exists ; AX-27290

			EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetResultsSection(:1, :2, :3, :4, :5) FROM DUAL' INTO vResult

							USING vPId, vbShowInfo, vIsDateFrom, vDate1, vDate2;

			RETURN vResult;

		END IF;



		-- init clobs

		dbms_lob_s.createtemporary (vResult, TRUE);

		dbms_lob_s.createtemporary (vText, TRUE);

		dbms_lob_s.createtemporary (vEntries, TRUE);

				

		--section header

		dbms_lob_s.append(vResult, '

			<component>

			  <section>

			    <!-- Results Section with Entries Required -->

			    <templateId root="2.16.840.1.113883.10.20.22.2.3.1" extension="2015-08-01"/>

				<templateId root="2.16.840.1.113883.10.20.22.2.3.1"/>

			    <code code="30954-2" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="RESULTS"/>

			    <title>Results</title>

			    <text>');



		IF vbShowInfo THEN

		

			-- go through the most recent versions of the tests on file

			FOR cTest IN curTests LOOP



				vTestCount := vTestCount + 1;



				SELECT COUNT(1) INTO vHasResults

  				FROM MTESTRES MR, MTESTREQ MT, LOINC LC

				WHERE 1=1

				AND MR."MTestReq" = MT."MTestReq"

				AND MR."MTestReq" = cTest."MTestReq"

				AND MR."Deleted" = 0

				AND MR."LOINC" = LC."LOINC";



				IF vHasResults > 0 THEN



					FOR cLab IN curResults(cTest."MTestReq") LOOP



						vLabName := cLab."Name";

						vLabAddress := cLab."Address1";

						vLabCity := cLab."City";

						vLabProvince := cLab."Province";

						vLabPostal := cLab."Postal";

					END LOOP;

				

					-- human-readable text for the test

					dbms_lob_s.append(vText, '

						<list listType="ordered">

						<caption>' || cTest."Description" || ' (' || TO_CHAR(cTest."RequestDateTime", 'YYYYMMDD') || ') | LAB: ' || vLabName || ' ADDRESS: ' || vLabAddress || ', ' || vLabCity || ', ' || vLabProvince || ', ' || vLabPostal || '</caption>

						');

					

					-- machine-readable XML for the test

					dbms_lob_s.append(vEntries, '

								<entry typeCode="DRIV">

									<organizer classCode="BATTERY" moodCode="EVN">

										<!-- Result organizer template -->

										<templateId root="2.16.840.1.113883.10.20.22.4.1" extension="2015-08-01"/>

										<templateId root="2.16.840.1.113883.10.20.22.4.1"/>

										<id root="2.16.840.1.113883.4.8155" />

										<code xsi:type="CE" code="' || TRIM(cTest."LOINC") || '"

											displayName="' || TRIM(cTest."Description") || '"

											codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC"/>

                     				<statusCode code="completed"/>

									<effectiveTime xsi:type="IVL_TS">

										<low value="' || TO_CHAR(cTest."RequestDateTime", 'YYYYMMDD') || '"/>

										<high value="' || TO_CHAR(cTest."RequestDateTime", 'YYYYMMDD') || '"/>

									</effectiveTime>

                     				<performer typeCode="PRF">

									<assignedEntity>

									<id root="2.16.840.1.113883.19.5"/>

									<representedOrganization>

										<name>' || vLabName || '</name>

											<addr>

												<streetAddressLine>' || vLabAddress || '</streetAddressLine>

												<city>' || vLabCity || '</city>

												<state>' || vLabProvince || '</state>

												<postalCode>' || vLabPostal || '</postalCode>

											</addr>

									</representedOrganization>

									</assignedEntity>

									</performer>

						');



					-- go thru the results (assumes that all tests of F or C status have results) 			

					FOR cResult IN curResults(cTest."MTestReq") LOOP



						vResultCount := vResultCount + 1;

					

						-- human-readable text for the result

						dbms_lob_s.append(vText, '

							<item><content ID="test' || vTestCount || 'result' || vResultCount || '">' || TRIM(cResult."Description") || ' - ' || cResult."ResultValue" || ' ' || cResult."ResultUnits" || ' (' || cResult."Interpretation" || ')' || '</content></item>

						');

					

						IF cResult."ResultValue" is not null THEN

							SELECT RegexpReplace_s(cResult."ResultValue", '(^[[:cntrl:]^\t]+)|([[:cntrl:]^\t]+$)','') INTO vResultValue FROM DUAL; --AX-37012

						ELSE

							vResultValue := 'NA';

						END IF;





						-- machine-readable XML for the result

						-- SAMIR_BOUDJEBLA: replaced this code TO_CHAR(cResult."EffTime", 'YYYYMMDD') with this code NVL(cResult."EffTime",'')

						dbms_lob_s.append(vEntries, '

							<component>

								<observation classCode="OBS" moodCode="EVN">

									<!-- Result observation template -->

									<templateId root="2.16.840.1.113883.10.20.22.4.2" extension="2015-08-01"/>

									<templateId root="2.16.840.1.113883.10.20.22.4.2"/>

									<id root="2.16.840.1.113883.4.8155" />

									<code xsi:type="CE" code="' || TRIM(cResult."LOINC") || '"

										displayName="' || TRIM(cResult."Description") || '"

										codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC"/>

									<text>

										<reference value="#test' || vResultCount || 'result' || cResult."ResultNumber" || '"/>

									</text>

									<statusCode code="completed"/>

									<effectiveTime value="' || NVL(cResult."EffTime",'')|| '"/>

									<value xsi:type="ST">' || TRIM(vResultValue) || '</value>

									<interpretationCode code="' || NVL(TRIM(cResult."Abnormal"), 'NA') || '" displayName="' || NVL(TRIM(cResult."Interpretation"), 'NA') || '"

										codeSystem="2.16.840.1.113883.5.83"

										codeSystemName="ObservationInterpretation"/>

									<referenceRange>

										<observationRange>

											<value xsi:type="ST">' || cResult."ReferenceRange" || '</value>

										</observationRange>

									</referenceRange>

								</observation>

                     		</component>

						');

				

					END LOOP;



					--close test list

					dbms_lob_s.append(vText, '

							</list>

						');

	

				

					--close result organizer

					dbms_lob_s.append(vEntries, '

									 </organizer>

               						</entry>

						');

				END IF;

			

			END LOOP;



			-- AX-21879d - Diagnostic Imaging Info...

			BEGIN

				SELECT TRIM(htf.escape_sc(PI."AnsText")) INTO vDiagCode

					FROM PITEM PI, FITEM FI, LOINC L

					WHERE 1=1 

						AND PI."FItem" = FI."FItem"

						AND PI."Patient" = vPId

						AND FI."Code" = 'MUDIAGIMGL'  

						AND TRIM(htf.escape_sc(PI."AnsText")) = TRIM(htf.escape_sc(L."LOINC"))

						AND PI."AuditNumber" =     

							(SELECT MAX(PI2."AuditNumber")

							FROM PITEM PI2, FITEM FI2

							WHERE 1=1 

								AND PI2."FItem" = FI2."FItem"

								AND PI2."Patient" = vPId

								AND FI2."Code" = 'MUDIAGIMGL' 

								AND FI2."Deleted" = 0

								AND PI2."AppDate" IS NOT NULL

								AND 

								(

									(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

									OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

									OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

									OR (vDate1 IS NULL)

								));

				EXCEPTION WHEN NO_DATA_FOUND THEN

					vDiagCode := NULL;

				END;



				IF vDiagCode IS NOT NULL THEN

					vTestCount := vTestCount + 1;

					vResultCount := vResultCount + 1;



					BEGIN

						SELECT TRIM(htf.escape_sc(PI."AnsText")) INTO vDiagCodeText

						FROM PITEM PI, FITEM FI

						WHERE 1=1 

							AND PI."FItem" = FI."FItem"

							AND PI."Patient" = vPId

							AND FI."Code" = 'MUDIAGIMGN'    

							AND PI."AuditNumber" =     

								(SELECT MAX(PI2."AuditNumber")

								FROM PITEM PI2, FITEM FI2

								WHERE 1=1 

									AND PI2."FItem" = FI2."FItem"

									AND PI2."Patient" = vPId

									AND FI2."Code" = 'MUDIAGIMGN'   

									AND FI2."Deleted" = 0

									AND PI2."AppDate" IS NOT NULL

									AND 

									(

										(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

										OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

										OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

										OR (vDate1 IS NULL)

									));



						EXCEPTION WHEN NO_DATA_FOUND THEN

							vDiagCodeText := NULL;

					END;

                  -- SAMIR_BOUDJEBLA addded the lignes below



                    BEGIN

						SELECT TRIM(htf.escape_sc(PI."AnsText")) INTO vDiagCodeTextDetail

						FROM PITEM PI, FITEM FI

						WHERE 1=1 

							AND PI."FItem" = FI."FItem"

							AND PI."Patient" = vPId

							AND FI."Code" = 'MUDIAGIMGI'    

							AND PI."AuditNumber" =     

								(SELECT MAX(PI2."AuditNumber")

								FROM PITEM PI2, FITEM FI2

								WHERE 1=1 

									AND PI2."FItem" = FI2."FItem"

									AND PI2."Patient" = vPId

									AND FI2."Code" = 'MUDIAGIMGI'   

									AND FI2."Deleted" = 0

									AND PI2."AppDate" IS NOT NULL

									AND 

									(

										(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

										OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

										OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

										OR (vDate1 IS NULL)

									));



						EXCEPTION WHEN NO_DATA_FOUND THEN

							vDiagCodeTextDetail := NULL;

					END;



                -- SAMIR_BOUDJEBLA addded the lignes Above                  



					BEGIN

						SELECT PI."AnsDate" INTO vDiagCodeDate -- This throw Invalid Month in some cases when playing with Ambularoty Summary so date become empty: SELECT TO_CHAR(PI."AnsDate", 'MM/DD/YYYY') INTO vDiagCodeDate

						FROM PITEM PI, FITEM FI

						WHERE 1=1 

							AND PI."FItem" = FI."FItem"

							AND PI."Patient" = vPId

							AND FI."Code" = 'MUDIAGIMGD'  

							AND PI."AuditNumber" =     

								(SELECT MAX(PI2."AuditNumber")

								FROM PITEM PI2, FITEM FI2

								WHERE 1=1 

									AND PI2."FItem" = FI2."FItem"

									AND PI2."Patient" = vPId

									AND FI2."Code" = 'MUDIAGIMGD'   

									AND FI2."Deleted" = 0

									AND PI2."AppDate" IS NOT NULL



									AND 

									(

										(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

										OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

										OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

										OR (vDate1 IS NULL)

									));



						EXCEPTION 

					              WHEN OTHERS THEN

					                 vDiagCodeDate := '';

						END;



						-- human-readable text for the test

						dbms_lob_s.append(vText, '

							<list listType="ordered">

							<caption>' || vDiagCodeText || ' (' || TO_CHAR(vDiagCodeDate, 'MM/DD/YYYY') || ') | Diagnostic Imaging</caption>

							');

					

						-- machine-readable XML for the test

						dbms_lob_s.append(vEntries, '

               					<entry typeCode="DRIV">

									<organizer classCode="BATTERY" moodCode="EVN">

										<!-- Result organizer template -->

										<templateId root="2.16.840.1.113883.10.20.22.4.1" extension="2015-08-01" />

										<templateId root="2.16.840.1.113883.10.20.22.4.1" />

										<id root="2.16.840.1.113883.4.8155" />

										<code xsi:type="CE" code="' || vDiagCode || '" displayName="' || vDiagCodeText || '" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" />

										<statusCode code="completed" />

                						<effectiveTime xsi:type="IVL_TS">

											<low value="' || TO_CHAR(vDiagCodeDate, 'YYYYMMDD') || '"/>

											<high value="' || TO_CHAR(vDiagCodeDate, 'YYYYMMDD') || '"/>

										</effectiveTime>

										<component>

											<observation classCode="OBS" moodCode="EVN">

												<!-- Result observation template -->

												<templateId root="2.16.840.1.113883.10.20.22.4.2" extension="2015-08-01" />

												<templateId root="2.16.840.1.113883.10.20.22.4.2" />

												<id root="2.16.840.1.113883.4.8155" />

												<code xsi:type="CE" code="' || vDiagCode || '" displayName="' || vDiagCodeText || '" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" />

												<text>

													<reference value="#' || vResultCount || '" />

												</text>

												<statusCode code="completed" />

												<effectiveTime value="' || TO_CHAR(vDiagCodeDate, 'YYYYMMDD') || '" />

												<value xsi:type="ED">

												<reference value="#' || vResultCount || '" />

												</value>

												<interpretationCode nullFlavor="NI"/>

											</observation>

										</component>

							');

                  -- SAMIR_BOUDJEBLA addded the lignes below



							-- human-readable text for the result

								dbms_lob_s.append(vText, '

									<item><content ID="result' || vResultCount || '">' || vDiagCodeTextDetail || '</content></item>

								');

                -- SAMIR_BOUDJEBLA addded the lignes Above                  



					--close test list

					dbms_lob_s.append(vText, '

								</list>

						');



					--close result organizer

					dbms_lob_s.append(vEntries, '

										</organizer>

               						</entry>

						');



				END IF;

			

		END IF; -- show nfo...

		

		-- handle 'no tests' case

		IF vTestCount = 0 THEN

		

			IF vbShowInfo THEN

				-- human-readable text 

				-- SAMIR_BOUDJEBLA addded the lignes below

				dbms_lob_s.createtemporary (vResult, TRUE);

                    --section header

                dbms_lob_s.append(vResult, '

                    <component>

                        <section nullFlavor="NI">

                        <!-- Results Section with Entries Required -->

                        <templateId root="2.16.840.1.113883.10.20.22.2.3.1" extension="2015-08-01"/>

                        <templateId root="2.16.840.1.113883.10.20.22.2.3.1"/>

                        <code code="30954-2" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="RESULTS"/>

                        <title>Results</title>

                        <text>');

            -- SAMIR_BOUDJEBLA end of the changes  

				dbms_lob_s.append(vText, 'No medical test results are on file.');

			END IF;



						-- machine-readable XML 



			/* SAMIR_BOUDJEBLA Commented this section

			dbms_lob_s.append(vEntries, '

				   <entry>

				      <organizer classCode="CLUSTER" moodCode="EVN">

					 <templateId root="2.16.840.1.113883.10.20.22.4.1" extension="2015-08-01"/>

					<templateId root="2.16.840.1.113883.10.20.22.4.1"/>

					 <id nullFlavor="NA"/>

					 <code nullFlavor="NA"/>

					 <statusCode code="completed"/>

					 <effectiveTime>

						<low value="' || TO_CHAR(SYSDATE, 'YYYYMMDDHH24MI') || '"/>

						<high value="' || TO_CHAR(SYSDATE, 'YYYYMMDDHH24MI') || '"/>

					</effectiveTime>

					 <component>

					    <observation classCode="OBS" moodCode="EVN" negationInd="true">

						<templateId root="2.16.840.1.113883.10.20.22.4.2" extension="2015-08-01"/>

						<templateId root="2.16.840.1.113883.10.20.22.4.2"/>

						<id nullFlavor="NA"/>

						<code code="26436-6" codeSystem="2.16.840.1.113883.6.1"

						      displayName="Laboratory Studies" codeSystemName="LOINC"/>

						<statusCode code="completed"/>

						<effectiveTime value="' || TO_CHAR(SYSDATE, 'YYYYMMDDHH24MI') || '"/>

						<value xsi:type="PQ" nullFlavor="UNK"/> 

					    </observation>

					  </component>

				      </organizer>

				  </entry>

				');

*/

		END IF;		

		

		--close text tag

		dbms_lob_s.append(vText, '</text>');

		

		-- put it all together

		dbms_lob_s.append(vResult, vText);

		dbms_lob_s.append(vResult, vEntries);



		-- section footer

		dbms_lob_s.append(vResult, '

			  </section>

			</component>');



		RETURN vResult;

	END;



  -- AX-21879f

  	FUNCTION getcognitivestatussection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob IS

		vResult CLOB := '';

		vText CLOB := '';

		vEntries CLOB := '';

		vCount NUMBER := 0;



		CURSOR curStatus IS

			SELECT S."SNOCode", S."Description", PI."AppDate" 

			FROM PITEM PI, FITEM FI, SNOCODE S

			WHERE 1=1 

				AND PI."FItem" = FI."FItem"

				AND TRIM(S."SNOCode") =  TRIM(htf.escape_sc(PI."AnsText"))

				AND PI."Patient" = vPId

				AND FI."Code" = 'MUCOGSTAT'

				AND PI."AuditNumber" =     

					(SELECT MAX(PI2."AuditNumber")

					FROM PITEM PI2, FITEM FI2

					WHERE 1=1 

						AND PI2."FItem" = FI2."FItem"

						AND PI2."Patient" = vPId

						AND FI2."Code" = 'MUCOGSTAT'

						AND FI2."Deleted" = 0

						AND PI2."AppDate" IS NOT NULL

						AND 

						(

							(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

							OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

							OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

							OR (vDate1 IS NULL)

						));



	   v_nCount		NUMBER := 0;								-- AX-26071.2



	BEGIN

		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetCognitiveStatusSection');

		IF v_nCount > 0 THEN

			-- custom package function exists; AX-27290 

			EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetCognitiveStatusSection(:1, :2, :3, :4, :5) FROM DUAL' INTO vResult

								USING vPId, vbShowInfo, vIsDateFrom, vDate1, vDate2;

			RETURN vResult;

		END IF;



		-- init clobs

		dbms_lob_s.createtemporary (vResult, TRUE);

		dbms_lob_s.createtemporary (vText, TRUE);

		dbms_lob_s.createtemporary (vEntries, TRUE);



		-- section header

		vResult := '

		<component>

		    <section>

			<templateId root="2.16.840.1.113883.10.20.22.2.56" />

			<templateId root="2.16.840.1.113883.10.20.22.2.56" extension="2015-08-01" />

			<code code="10190-7" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Cognitive Status" />

			<title>Cognitive Status</title>';



		IF vbShowInfo THEN



			-- loop thru all the implants...

			FOR statusRec IN curStatus LOOP                 

				

				vCount := vCount + 1;

				

				IF vCount = 1 THEN 

					-- add the list header if this is the first record

					dbms_lob_s.append(vText, '

						<text>

							<table border="1" width="100%">

								<thead>

									<tr>

										<th>Assessment</th>

										<th>Date</th>

										<th>Results</th>

									</tr>

								</thead>

								<tbody>		       			

						');				

				END IF;



				dbms_lob_s.append(vText, '

								<tr>

									<td ID="MS_Type' || vCount || '">Cognitive Status</td>

									<td>' || TO_CHAR(statusRec."AppDate", 'MM/DD/YYYY') || '</td>

									<td ID="MS_Finding' || vCount || '">' || statusRec."Description" || '</td> 

								</tr>

					');	



					dbms_lob_s.append(vEntries, '

					<entry>

						<!-- Template for Mental Status Result Observation. Note other templates may apply. -->

						<observation classCode="OBS" moodCode="EVN">

							<templateId root="2.16.840.1.113883.10.20.22.4.74"/>

							<templateId root="2.16.840.1.113883.10.20.22.4.74" extension="2015-08-01"/>

							<id root="faa09c19-fa1f-4a6c-ae79-10a3b711550f"/>

							<!-- In C-CDA R2.1 August 2015 this is a fixed code. SDWG may change to a value set in STU comment 1367 -->

							<code codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" code="373930000" displayName="Cognitive function finding">

								<originalText>

									<reference value="#MS_Type' || vCount || '"></reference>

								</originalText>

								<translation code="75275-8" 

									displayName="Cognitive function"

									codeSystem="2.16.840.1.113883.6.1"

									codeSystemName="LOINC"/>

							</code>

							<text>

								<reference value="#MS_Narrative' || vCount || '"/>

							</text>

							<statusCode code="completed"/>

							<effectiveTime>

								<low value="' || TO_CHAR(statusRec."AppDate", 'YYYYMMDD') || '"/>

							</effectiveTime>

							<value xsi:type="CD" code="' || TRIM(statusRec."SNOCode") || '" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" displayName="' || statusRec."Description" || '">

								<originalText>

									<reference value="#MS_Finding' || vCount || '"/>

								</originalText>

							</value>

						</observation>

					</entry>');



			END LOOP;

			

		END IF;



		IF vCount > 0 THEN

			--close the list

			dbms_lob_s.append(vText, '

							</tbody>	

						</table>

					</text>	

					');	

		ELSE

		

			IF vbShowInfo THEN

				-- human readable text

				dbms_lob_s.append(vText, '<text>Patient has no history of cognitive impairment.</text>');

			ELSE

				dbms_lob_s.append(vText, '<text></text>');

			END IF;

			

			-- machine readable XML

			dbms_lob_s.append(vEntries, '

				<entry>

					<!-- Template for Mental Status Observation. Note other templates may apply. -->

					<observation classCode="OBS" moodCode="EVN">

						<templateId root="2.16.840.1.113883.10.20.22.4.74"/>

						<templateId root="2.16.840.1.113883.10.20.22.4.74" extension="2015-08-01"/>

						<id root="faa09c19-fa1f-4a6c-ae79-10a3b711550f"/>

						<code codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" code="373930000" displayName="Cognitive function finding">

							<originalText>

								<reference value="#MS_Type1"></reference>

							</originalText>

							<translation code="75275-8" 

								displayName="Cognitive function"

								codeSystem="2.16.840.1.113883.6.1"

								codeSystemName="LOINC"/>

						</code>

						<text>

							<reference value="#MS_Narrative1"/>

						</text>

						<statusCode code="completed"/>

						<effectiveTime>

							<low value="' || TO_CHAR(SYSDATE, 'YYYYMMDD') || '"/>

						</effectiveTime>

						<value xsi:type="CD" code="66557003" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" displayName="No Impairment">

							<originalText>

								<reference value="#MS_Finding1"/>

							</originalText>

						</value>

					</observation>

				</entry>

			');

				

		END IF;



		dbms_lob_s.append(vResult, vText);

		dbms_lob_s.append(vResult, vEntries);

		dbms_lob_s.append(vResult, '

		    </section>

		 </component>');



		return vResult;

	END;



	  

   	-- E142549 - Functional Status

		-- AX-18945.19095

	FUNCTION getfunctionalstatussection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob IS

		vResult CLOB := '';

		vContent CLOB := '';

		vEntries CLOB := ''; -- AX-21586.21972

		

		vRefCode FITEM."Code"%TYPE := 'MUFUNCSTAT';

		vFuncStatText PITEM."AnsText"%TYPE := NULL;

		vFuncStatDate PITEM."AppDate"%TYPE := NULL;

		vSNOCode SNOCODE."SNOCode"%TYPE := '';

		vDescription SNOCODE."Description"%TYPE := '';



	   v_nCount		NUMBER := 0;								-- AX-26071.2



	BEGIN

		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetFunctionalStatusSection');

		IF v_nCount > 0 THEN

			-- custom package function exists ; AX-27290

			EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetFunctionalStatusSection(:1, :2, :3, :4, :5) FROM DUAL' INTO vResult

									USING vPId, vbShowInfo, vIsDateFrom, vDate1, vDate2;

			RETURN vResult;

		END IF;



		-- init clobs

		dbms_lob_s.createtemporary (vResult, TRUE);

		dbms_lob_s.createtemporary (vContent, TRUE);

		dbms_lob_s.createtemporary (vEntries, TRUE); -- AX-21586.21972



		-- E143263.4

		IF NOT vbShowInfo THEN

			return vResult;

		END IF;

		

		-- get the status - assumes this is stored in a long-text question on a form 

		BEGIN

			SELECT S."SNOCode", S."Description", PI."AppDate" 

			INTO vSNOCode, vDescription, vFuncStatDate

			FROM PITEM PI, FITEM FI, SNOCODE S

			WHERE 1=1 

				AND PI."FItem" = FI."FItem"

				AND TRIM(S."SNOCode") =  TRIM(htf.escape_sc(PI."AnsText"))

				AND PI."Patient" = vPId

				AND FI."Code" = vRefCode

				AND PI."AuditNumber" =     

					(SELECT MAX(PI2."AuditNumber")

					FROM PITEM PI2, FITEM FI2

					WHERE 1=1 

						AND PI2."FItem" = FI2."FItem"

						AND PI2."Patient" = vPId

						AND FI2."Code" = vRefCode

						AND FI2."Deleted" = 0

						AND PI2."AppDate" IS NOT NULL

						AND 

						(

							(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

							OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

							OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

							OR (vDate1 IS NULL)

						));

		EXCEPTION WHEN OTHERS THEN

			vDescription := NULL;

		END;



		-- write out XML

		-- AX-21586.21972

		dbms_lob_s.append(vResult, '

			<component>

			<section>

			<templateId root="2.16.840.1.113883.10.20.22.2.14"/>

			<templateId root="2.16.840.1.113883.10.20.22.2.14" extension="2014-06-09"/>

			<code code="47420-5" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Functional Status"/>

			<title>Functional Status</title>

			');

			

		IF vDescription IS NULL THEN

			dbms_lob_s.append(vContent, '<text>No functional status has been recorded.</text>');



			-- AX-21586.21972

			-- machine readable XML

			dbms_lob_s.append(vEntries, '

				<entry>

					<observation classCode="OBS" moodCode="EVN">

						<!-- Template for Functional Status Observation. Note other templates may apply. -->

						<templateId root="2.16.840.1.113883.10.20.22.4.67"/>

						<templateId root="2.16.840.1.113883.10.20.22.4.67" extension="2014-06-09"/>

						<id root="e4f9eb37-52ca-4e95-90f3-570dace107e6"/>

						<code code="54522-8" displayName="Functional status" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC">

							<originalText>

								<reference value="#FS_Type1"></reference>

							</originalText>

						</code>

						<text>

							<reference value="#FS_Narrative1"/>

						</text>

						<statusCode code="completed"/>

						<effectiveTime>

							<low value="' || TO_CHAR(SYSDATE, 'YYYYMMDD') || '"/>

						</effectiveTime>

						<value xsi:type="CD" code="66557003" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" displayName="No Impairment">

							<originalText>

								<reference value="#MS_Finding1"/>

							</originalText>

						</value>

					</observation>

				</entry>

			');



		ELSE

			-- need to fake it as structured data - always active, date is when the 

			-- functional/cognitive status was approved

			dbms_lob_s.append(vContent, '

				<text>

					<table border="1" width="100%">

						<thead>

							<tr ID="FS_Narrative1">

								<th>Assessment</th>

								<th>Date</th>

								<th>Results</th>

							</tr>

						</thead>

						<tbody>

							<tr>

								<td ID="FS_Type1">Functional Status</td>

								<td>' || TO_CHAR(vFuncStatDate, 'MM/DD/YYYY') || '</td>

								<td ID="FS_Finding1">' || htf.escape_sc(vDescription) || '</td>

							</tr>

						</tbody>

					</table>

				</text>

				');



				-- AX-21586.21972

				-- machine readable XML

			dbms_lob_s.append(vEntries, '

				<entry>

					<observation classCode="OBS" moodCode="EVN">

						<!-- Template for Functional Status Observation. Note other templates may apply. -->

						<templateId root="2.16.840.1.113883.10.20.22.4.67"/>

						<templateId root="2.16.840.1.113883.10.20.22.4.67" extension="2014-06-09"/>

						<id root="e4f9eb37-52ca-4e95-90f3-570dace107e6"/>

						<code code="54522-8" displayName="Functional status" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC">

							<originalText>

								<reference value="#FS_Type1"></reference>

							</originalText>

						</code>

						<text>

							<reference value="#FS_Narrative1"/>

						</text>

						<statusCode code="completed"/>

						<effectiveTime>

							<!-- Some systems may just report this to day rather than hour and minute timestamp. Both of which are acceptable. -->

							<low value="' || TO_CHAR(vFuncStatDate, 'YYYYMMDD') || '"/>

						</effectiveTime>

							<value xsi:type="CD" code="' || TRIM(vSNOCode) || '" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" displayName="' || vDescription || '">

							<originalText>

								<reference value="#FS_Finding1"/>

							</originalText>

						</value>

					</observation>

				</entry>

			');



		END IF; 



		-- AX-21586.21972

		dbms_lob_s.append(vResult, vContent);

		dbms_lob_s.append(vResult, vEntries);

		dbms_lob_s.append(vResult, '

		    </section>

		 </component>');



		return vResult;

	END;



  -- kind of a stub, but might be acceptable as-is

  FUNCTION getnucctype(vprov character varying) RETURN character varying IS

    vResult  VARCHAR2(32) := '';

	   v_nCount		NUMBER := 0;								-- AX-26071.2



  BEGIN



		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetNUCCType');

		IF v_nCount > 0 THEN

			-- custom package function exists 

			EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetNUCCType('''||vProv||''') FROM DUAL' INTO vResult;

			RETURN vResult;

		END IF;





    --126800000X	Dental Assistant [Dental Providers]

    --124Q00000X	Dental Hygienist [Dental Providers]

    --292200000X	Dental Laboratory [Laboratories]

    --126900000X	Dental Laboratory Technician [Dental Providers]

    --1223D0001X	Dental Public Health [Dental Providers\Dentist]

    --125J00000X	Dental Therapist [Dental Providers]

    --122300000X	Dentist [Dental Providers]

    --122400000X	Denturist [Dental Providers]	Denturist [Dental Providers]

    --120000000X  Dental Providers

    

    RETURN '120000000X'; -- if not detailed enough, map to types listed above



  

  END;

  

  



 	-- E142550 - Instructions - simply pulls the info from long-text form questions

	FUNCTION getinstructionssection(vapptid numeric, vbshowptdecinfo boolean DEFAULT true, vbshowinfo boolean DEFAULT true) RETURN clob IS

		vResult CLOB := '';

		vContent CLOB := '';

		vPId PATIENT."Patient"%TYPE := NULL;

		

		vInstructionRefCode FITEM."Code"%TYPE := 'MUINSTRUCT';

		vInstructionText PITEM."AnsText"%TYPE := NULL;	

		

		vPtDecAidRefCode FITEM."Code"%TYPE := 'MUPTDECAID';

		vPtDecAidText PITEM."AnsText"%TYPE := NULL;	

		

	   v_nCount		NUMBER := 0;								-- AX-26071.2

	BEGIN



		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetInstructionsSection');

		IF v_nCount > 0 THEN

			-- custom package function exists 

			EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetInstructionsSection('||vApptId||', :1, :2) FROM DUAL' INTO vResult

								USING vbShowPtDecInfo, vbShowInfo;

			RETURN vResult;

		END IF;



		-- init clobs

		dbms_lob_s.createtemporary (vResult, TRUE);

		dbms_lob_s.createtemporary (vContent, TRUE);



		-- get the instructions - assumes this is stored in a long-text question on a form 

		BEGIN

			-- get the patient for the appointment

			SELECT AP."Patient" INTO vPId

			FROM APPOINT AP

			WHERE 1=1

				AND AP."Appointment" = vApptId;

		

			-- get the instructions for this patient

			SELECT TRIM(htf.escape_sc(PI."AnsText")) INTO vInstructionText

			FROM PITEM PI, FITEM FI

			WHERE 1=1 

				AND PI."FItem" = FI."FItem"

				AND PI."Patient" = vPId

				AND FI."Code" = vInstructionRefCode

				AND PI."AuditNumber" =     

					(SELECT MAX(PI2."AuditNumber")

					FROM PITEM PI2, FITEM FI2

					WHERE 1=1 

						AND PI2."FItem" = FI2."FItem"

						AND PI2."Patient" = vPId

						AND FI2."Code" = vInstructionRefCode

						AND FI2."Deleted" = 0

						AND PI2."AppDate" IS NOT NULL);



			-- get the recommended patient decision aids for this patient

			SELECT TRIM(htf.escape_sc(PI."AnsText")) INTO vPtDecAidText

			FROM PITEM PI, FITEM FI

			WHERE 1=1 

				AND PI."FItem" = FI."FItem"

				AND PI."Patient" = vPId

				AND FI."Code" = vPtDecAidRefCode

				AND PI."AuditNumber" =     

					(SELECT MAX(PI2."AuditNumber")

					FROM PITEM PI2, FITEM FI2

					WHERE 1=1 

						AND PI2."FItem" = FI2."FItem"

						AND PI2."Patient" = vPId

						AND FI2."Code" = vPtDecAidRefCode

						AND FI2."Deleted" = 0

						AND PI2."AppDate" IS NOT NULL);



		EXCEPTION WHEN OTHERS THEN

			vInstructionText := NULL;

		END;



		-- write out XML

		dbms_lob_s.append(vResult, '

			<component>

			<section>

			<!-- Instructions template ID -->

			<templateId root="2.16.840.1.113883.10.20.22.2.45"/>

			<code code="69730-0" codeSystem="2.16.840.1.113883.6.1" codeSystemVersion="LOINC"

			  displayName="Instructions"/>

			<title>Instructions</title>

			<text>');

			

		IF vbShowInfo THEN						--E143263.4; B143328.2

			-- show the instructions

			dbms_lob_s.append(vContent, '

				<table border="1" width="100%">

					<thead>

						<tr>

							<th>Clinical Instructions</th>

						</tr>

					</thead>

					<tbody>

						<tr>

							<td>' || htf.escape_sc(TRIM(NVL(vInstructionText, 'No instructions have been recorded.'))) || '</td>

						</tr>

					</tbody>

				</table>

				');

		

		END IF;

		

		IF vbShowPtDecInfo THEN

			-- show the recommended patient decision aids

			dbms_lob_s.append(vContent, '

				<table border="1" width="100%">

					<thead>

						<tr>

							<th>Recommended Patient Decision Aids</th>

						</tr>

					</thead>

					<tbody>

						<tr>

							<td>' || htf.escape_sc(TRIM(NVL(vPtDecAidText, 'No recommended patient decision aids have been recorded.'))) || '</td>

						</tr>

					</tbody>

				</table>

				');

			

		END IF;



		dbms_lob_s.append(vResult, vContent || '              

			</text>

			</section>

			</component>');



		return vResult;

	END;



		FUNCTION getmedicalequipmentsection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob IS

		vPracticeRec PRACTICE%ROWTYPE;

		vResult CLOB := '';



		vText CLOB := '';

		vEntries CLOB := '';

		vCount NUMBER := 0;



		--AX-21361.21368

		vComment  VARCHAR2(4000) := ''; 

		vBarCode  VARCHAR2(4000) := ''; 



		-- AX-21822b

		CURSOR curImplant IS

			SELECT PI.*,

			  IA."Description",

			  IA."BrandName",

			  IA."VersionNumber",

			  IA."CompanyName",

			  PA."ReadableBarCode"

			FROM PTIMPLNT PI,

			  IMPLNADD IA,

			  PTIMPADD PA

			WHERE PI."Patient" = vPId

			AND PI."DeviceId" = IA."DeviceId" (+)

			AND PI."Deleted" = 0

			AND PI."PtImplnt" = PA."PtImplnt" (+)

			AND 

			(

				(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND PI."Date" >= vDate1 AND PI."Date" <= vDate2)

				OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND PI."Date" >= vDate1)

				OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND PI."Date" <= vDate1) 

				OR (vDate1 IS NULL)

			)

			ORDER BY PI."Date";

		

	   v_nCount		NUMBER := 0;								-- AX-26071.2



	BEGIN

		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetMedicalEquipmentSection');

		IF v_nCount > 0 THEN

			-- custom package function exists ; AX-27290

			EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetMedicalEquipmentSection(:1, :2, :3, :4, :5) FROM DUAL' INTO vResult

									USING vPId, vbShowInfo, vIsDateFrom, vDate1, vDate2;

			RETURN vResult;

		END IF;



		-- init clobs

		dbms_lob_s.createtemporary (vResult, TRUE);

		dbms_lob_s.createtemporary (vText, TRUE);

		dbms_lob_s.createtemporary (vEntries, TRUE);



		-- section header

		vResult := '

		<component>

		    <section>

			   <!-- Medical Equipment Section (V2) template -->

		      <templateId root="2.16.840.1.113883.10.20.22.2.23"/>

				<templateId root="2.16.840.1.113883.10.20.22.2.23" extension="2014-06-09"/>

				<code code="46264-8" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Medical Equipment"/>

				<title>Medical Equipment</title>';



		IF vbShowInfo THEN

			-- loop thru all the implants...

			FOR implantRec IN curImplant LOOP                 

				

				vCount := vCount + 1;

				

				IF vCount = 1 THEN 

					-- add the list header if this is the first record

					dbms_lob_s.append(vText, '

						<text>

							<table border="1" width="100%">

								<thead>

									<tr>

										<th>Implanted</th>

										<th>Area</th>

										<th>Manufacturer</th>

										<th>Device Identifier</th>

										<th>Date</th>

										<th>Assigning Authority</th>	

									</tr>

								</thead>

								<tbody>		       			

						');				

				END IF;

				

				IF NOT (trim(implantRec."DeviceId") IS NULL OR length(trim(implantRec."DeviceId")) = 0) THEN

					--AX-21361.21368

					vComment := '';

					IF NOT (trim(implantRec."Sites") IS NULL OR length(trim(implantRec."Sites")) = 0) THEN

						vComment := 'Sites ' || trim(implantRec."Sites");		-- AX-23328 Use Sites

					END IF;

					IF NOT (trim(implantRec."Comment") IS NULL OR length(trim(implantRec."Comment")) = 0) THEN

						IF NOT (trim(vComment) IS NULL OR length(trim(vComment)) = 0) THEN

							vComment := vComment || '; ';

						END IF;

						 vComment := vComment || implantRec."Comment";

					END IF;



					-- AX-24915	- moved from below...

					-- AX-21822b

					-- blow off CRLFs...

					IF implantRec."ReadableBarCode" IS NOT NULL THEN

						SELECT RegexpReplace_s(implantRec."ReadableBarCode", '(^[[:cntrl:]^\t]+)|([[:cntrl:]^\t]+$)','') INTO vBarCode FROM DUAL; --AX-37012

					ELSE

						SELECT RegexpReplace_s(implantRec."RawBarCode", '(^[[:cntrl:]^\t]+)|([[:cntrl:]^\t]+$)','') INTO vBarCode FROM DUAL; --AX-37012

					END IF;



					vBarCode := htf.escape_sc(TRIM(vBarCode));



					-- AX-24915

					dbms_lob_s.append(vText, '

									<tr>

										<td ID="implant' || vCount || '">' || htf.escape_sc(implantRec."Description") || '</td>

										<td ID="implantsite' || vCount || '">' || htf.escape_sc(vComment) || '</td> 

										<td>' || htf.escape_sc(implantRec."CompanyName") || '</td>

										<td>' || vBarCode || '</td>

										<td>' || TO_CHAR(implantRec."Date", 'MM/DD/YYYY') || '</td>

										<td>FDA</td>

									</tr>

						');	

						





						-- AX-21806

						dbms_lob_s.append(vEntries, '

						<entry>

							<procedure classCode="PROC" moodCode="EVN">

								 <templateId root="2.16.840.1.113883.10.20.22.4.14" extension="2014-06-09"/>

								 <templateId root="2.16.840.1.113883.10.20.22.4.14"/>

								 <id extension="2746" root="1.2.840.114350.1.13.5552.1.7.2.737780"/>

								 <code nullFlavor="UNK"/>

								 <statusCode code="completed"/>

								 <effectiveTime>

									  <low value="' || TO_CHAR(implantRec."Date", 'YYYYMMDD') ||'"/>

								 </effectiveTime>

								<!-- Example where targetSiteCode is not mapped -->

								<targetSiteCode nullFlavor="UNK">

									<originalText>

										<reference value="#implantsite' || vCount || '"/>

									</originalText>

								</targetSiteCode>

								<participant typeCode="DEV">

									<participantRole classCode="MANU">

										<templateId root="2.16.840.1.113883.10.20.22.4.37"/>

										<id assigningAuthorityName="FDA" extension="' || htf.escape_sc(TRIM(vBarCode)) || '" root="2.16.840.1.113883.3.3719"/>

										<playingDevice>

												<code nullFlavor="UNK">

													<originalText>

														<reference value="#implant' || vCount || '"/>

													</originalText>

												</code>

										</playingDevice>

										<!-- From Product Instance template: 

																The scopingEntity/id should correspond to FDA or the appropriate issuing agency. -->

										<scopingEntity>

												<id root="2.16.840.1.113883.3.3719"/>

										</scopingEntity>

									</participantRole>

								</participant>

							  </procedure>

							</entry>');



					END IF;

			END LOOP;

			

		END IF;



		IF vCount > 0 THEN

			--close the list

			dbms_lob_s.append(vText, '

							</tbody>	

						</table>

					</text>	

					');	

		ELSE

		

			IF vbShowInfo THEN

				--handle case where there were no implants

				-- human readable text

				dbms_lob_s.append(vText, '<text>Patient has no history of implantable devices.</text>');

			ELSE

				dbms_lob_s.append(vText, '<text></text>');

			END IF;

			

			-- machine readable XML

			dbms_lob_s.append(vEntries, '

							<entry>

								<procedure classCode="PROC" moodCode="EVN" negationInd="true">

										<!-- Procedure Activity Procedure V2-->

										<templateId root="2.16.840.1.113883.10.20.22.4.14"/>

										<templateId root="2.16.840.1.113883.10.20.22.4.14" extension="2014-06-09"/>

										<id root="d5b614bd-01ce-410d-8726-e1fd01dcc72a" />

										<code code="71388002" codeSystem="2.16.840.1.113883.6.96"   

											displayName="Procedure"/>

										<text>

											<reference value="#Proc"/>

										</text>

										<statusCode code="completed" />

										<effectiveTime nullFlavor="NA" />

										<participant typeCode="DEV">

											<participantRole classCode="MANU">

												<templateId root="2.16.840.1.113883.10.20.22.4.37"/>

												<!-- UDI is not applicable since no procedure -->

												<id nullFlavor="NA" root="2.16.840.1.113883.3.3719"/>  

												<playingDevice>

														<code code="40388003" codeSystem="2.16.840.1.113883.6.96"   

															displayName="Implant"/>

												</playingDevice>

												<scopingEntity>

														<id root="2.16.840.1.113883.3.3719"/>

												</scopingEntity>

											</participantRole>

										</participant>	

								</procedure>

							</entry>

							');

				

		END IF;



		dbms_lob_s.append(vResult, vText);

		dbms_lob_s.append(vResult, vEntries);

		dbms_lob_s.append(vResult, '

		    </section>

		 </component>');



		return vResult;

	END;  



  

	-- Medications Administered section - prescriptions written on the visit date

	FUNCTION getmedadministeredsection(vapptid numeric, vbshowinfo boolean DEFAULT true) RETURN clob IS

		vResult CLOB := '';

		vText CLOB := '';

		vEntries CLOB := '';

		vCount NUMBER := 0;

    		vTemp NUMBER := 0;

    		vMedStatus  VARCHAR2(10) := NULL;



		-- cursor of prescriptions from the appointment date

		CURSOR curMeds IS

			SELECT 

				P.*, 

				PR."Name", 

				PR."City", 

				PR."Province", 

				PR."Postal", 

				PR."NPI", 

				PR."Area" AS "PracticeArea", 

				PR."Phone" AS "PracticePhone"

			FROM Prescrip P, Practice PR, APPOINT A 

			WHERE 1=1

				AND P."Patient" = A."Patient" 

				AND A."Appointment" = vApptId 

				AND A."Date" = P."Date" 

				AND P."Deleted" = 0 

				-- AX-19342

				--AND P."PrescripType" IN (1,2) 

				AND P."PrescripType" = 0 

				AND P."ApprovalUser" <> 0 

				AND P."Practice" = PR."Id" (+)

			ORDER BY P."EndDate", P."Date", P."Prescription";



	   v_nCount		NUMBER := 0;								-- AX-26071.2



	BEGIN

		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetMedAdministeredSection');

		IF v_nCount > 0 THEN

			-- custom package function exists 

			EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetMedAdministeredSection('||vApptId||', :1) FROM DUAL' INTO vResult

								USING vbShowInfo;

			RETURN vResult;

		END IF;



		--init clobs

		dbms_lob_s.createtemporary (vResult, TRUE);

		dbms_lob_s.createtemporary (vText, TRUE);

		dbms_lob_s.createtemporary (vEntries, TRUE);



		--section header

		dbms_lob_s.append(vResult, '

			<component>

			<section>

			<templateId root="2.16.840.1.113883.10.20.22.2.38"/>

			<code code="29549-3" displayName="Medications Administered"

			codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC"/>

			<title>Medications Administered</title>');





		IF vbShowInfo THEN					--E143263.4

			-- loop thru the prescriptions from the appointment date

			FOR medRec in curMeds LOOP

				vCount := vCount + 1;

							

				IF vCount = 1 THEN

					-- add the table heading if this is the first record

					dbms_lob_s.append(vText, '

						<text>

						  <table border="1" width="100%">

							 <thead>

								<tr>

								<th>Medication</th>

								<th>Sig</th>

								<th>Start Date</th>

								<th>End Date</th>

								<th>Status</th>

								</tr>

							 </thead>

						  <tbody>');				

				END IF;

				

				--determine status

				IF medRec."IsVoided" = 1 THEN

					vMedStatus := 'Voided';			

				ELSIF TRUNC(NVL(medRec."StartDate", SYSDATE-1)) > SYSDATE THEN

					vMedStatus := 'Pending';

				ELSIF TRUNC(NVL(medRec."EndDate", SYSDATE+1)) < SYSDATE THEN 

					vMedStatus := 'Completed';

				ELSE

					vMedStatus := 'Active';

				END IF;



				-- text section

				dbms_lob_s.append(vText, '

							 <tr>

							<td><content ID="amed' || vCount  || '">' || htf.escape_sc(medRec."DrugDescription") || '</content></td>

							<td>' || htf.escape_sc(medRec."DrugFrqDesc") || '</td>

							<td>' || TO_CHAR(medRec."StartDate", 'MM/DD/YYYY') || '</td>

							<td>' || TO_CHAR(medRec."EndDate", 'MM/DD/YYYY') || '</td>

							<td>' || vMedStatus || '</td>		

							 </tr>');

				

				-- coded entries section

				dbms_lob_s.append(vEntries, '

					<entry typeCode="DRIV">

					  <substanceAdministration classCode="SBADM" moodCode="INT">

					  <templateId root="2.16.840.1.113883.10.20.22.4.16" extension="2014-06-09"/>

						<templateId root="2.16.840.1.113883.10.20.22.4.16"/>

					  <id root="2.16.840.1.113883.4.8155" />

					  <text><reference value="#amed' || vCount  || '"/>' || htf.escape_sc(medRec."DrugDescription") || ' - ' || htf.escape_sc(medRec."Dose") || '</text>

					  <statusCode code="completed"/>

					  <effectiveTime xsi:type="IVL_TS"> ');

	          

				IF medRec."StartDate" IS NOT NULL THEN

					dbms_lob_s.append(vEntries, '

						<low value="' || TO_CHAR(medRec."StartDate", 'YYYYMMDD') || '"/>');

				ELSE

					dbms_lob_s.append(vEntries, '

						<low nullFlavor="UNK"/>');

				END IF;



				IF medRec."EndDate" IS NOT NULL THEN

					dbms_lob_s.append(vEntries, '

						<high value="' || TO_CHAR(medRec."EndDate", 'YYYYMMDD') || '"/>');

				ELSE

					dbms_lob_s.append(vEntries, '

						<high nullFlavor="UNK"/>');

				END IF;



				dbms_lob_s.append(vEntries, '

					</effectiveTime>');



				IF medRec."Dose" IS NOT NULL AND LENGTH(TRIM(medRec."Dose")) > 0 THEN

				  -- check for space. Assume before = value, unit = after

				  SELECT INSTR(medRec."Dose", ' ') INTO vTemp FROM DUAL;



				  -- AX-18945.19094g

				  IF vTemp > 0 THEN

					  dbms_lob_s.append(vEntries, '

						 <doseQuantity value="' || 1 ||'"/>');

				  ELSE

					 dbms_lob_s.append(vEntries, '

					 <doseQuantity value="' || medRec."Dose" || '"/>');

				  END IF;

				ELSE

					dbms_lob_s.append(vEntries, '

					<doseQuantity nullFlavor="UNK"/>');

				END IF;



				dbms_lob_s.append(vEntries, '

					<consumable>

					<manufacturedProduct classCode="MANU">

					<templateId root="2.16.840.1.113883.10.20.22.4.23" extension="2014-06-09"/>

					<templateId root="2.16.840.1.113883.10.20.22.4.23"/>



					<manufacturedMaterial>

					<code code="' || NVL(trim(medRec."RxNorm"), 'UNK') || '" codeSystem="2.16.840.1.113883.6.88" displayName="'|| htf.escape_sc(medRec."DrugDescription") || '">

					<originalText><reference value="#amed' || vCount  || '"/></originalText>

					<translation code="' || NVL(trim(medRec."RxNorm"), 'UNK') || '"

					displayName="' || htf.escape_sc(medRec."DrugDescription") || '"

					codeSystem="2.16.840.1.113883.6.88"

					codeSystemName="RxNorm"/>

					</code>

					</manufacturedMaterial>

					</manufacturedProduct>

					</consumable>

					</substanceAdministration>

					</entry>');



			END LOOP;

			

		END IF;



		IF vCount > 0 THEN

			-- close text section

			dbms_lob_s.append(vText, '

				</tbody>

				</table>

				</text>');

		ELSE

		

			IF vbShowInfo THEN

				-- handle the case where there were no prescriptions written

				-- human-readable part

				dbms_lob_s.append(vText, '

					<text>No prescriptions were written for this visit.</text>');

			ELSE

				dbms_lob_s.append(vText, '

					<text></text>');

			END IF;

			

				

			-- machine-readable XML

			dbms_lob_s.append(vEntries, '

				<entry typeCode="DRIV">

				  <substanceAdministration classCode="SBADM" moodCode="INT" negationInd="true">

				  <templateId root="2.16.840.1.113883.10.20.22.4.16" extension="2014-06-09"/>

					<templateId root="2.16.840.1.113883.10.20.22.4.16"/>

				    <id root="2.16.840.1.113883.4.8155" />

				    <statusCode code="completed"/>

				    <effectiveTime xsi:type="IVL_TS">

				      <low nullFlavor="NA"/>

				      <high nullFlavor="NA"/>	

				    </effectiveTime>

					<doseQuantity nullFlavor="UNK"/>

				    <consumable>

				      <manufacturedProduct classCode="MANU">

				      <templateId root="2.16.840.1.113883.10.20.22.4.23" extension="2014-06-09"/>

					<templateId root="2.16.840.1.113883.10.20.22.4.23"/>

				      <manufacturedMaterial>

				      <code nullFlavor="NA"/>

				      </manufacturedMaterial>

				      </manufacturedProduct>

				    </consumable>

				  </substanceAdministration>

				</entry>

				');

		END IF;



		-- put it all together

		dbms_lob_s.append(vResult, vText);

		dbms_lob_s.append(vResult, vEntries);

		

		-- section footer

		dbms_lob_s.append(vResult, '

			</section>

			</component>');



		return vResult;

	END;



	

		-- AX-21739

	FUNCTION getgoalssection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob IS

		vResult CLOB := '';

		vText CLOB := '';

		vEntries CLOB := '';

		vCount NUMBER := 0;



		vRefCode FITEM."Code"%TYPE := 'MUGOAL';



		CURSOR curGoals IS

			SELECT TRIM(htf.escape_sc(PI."AnsText")) "AnsText"

			FROM PITEM PI, FITEM FI

			WHERE 1=1 

				AND PI."FItem" = FI."FItem"

				AND PI."Patient" = vPId

				AND FI."Code" = vRefCode

				AND PI."AuditNumber" =     

					(SELECT MAX(PI2."AuditNumber")

					FROM PITEM PI2, FITEM FI2

					WHERE 1=1 

						AND PI2."FItem" = FI2."FItem"

						AND PI2."Patient" = vPId

						AND FI2."Code" = vRefCode

						AND FI2."Deleted" = 0

						AND PI2."AppDate" IS NOT NULL

						AND 

						(

							(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

							OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

							OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

							OR (vDate1 IS NULL)

						));

		

	   v_nCount		NUMBER := 0;								-- AX-26071.2



	BEGIN

		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetGoalsSection');

		IF v_nCount > 0 THEN

			-- custom package function exists ; AX-27290

			EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetGoalsSection(:1, :2, :3, :4, :5) FROM DUAL' INTO vResult

									USING vPId, vbShowInfo, vIsDateFrom, vDate1, vDate2;

			RETURN vResult;

		END IF;



		-- init clobs

		dbms_lob_s.createtemporary (vResult, TRUE);

		dbms_lob_s.createtemporary (vText, TRUE);

		dbms_lob_s.createtemporary (vEntries, TRUE);



		-- section header

		vResult := '

		<component>

		    <section>

			    <!-- Goals Section -->

				<templateId root="2.16.840.1.113883.10.20.22.2.60"/>

				<code code="61146-7" displayName="Goals" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC"/>

				<title>Goals</title>';



		IF vbShowInfo THEN

			-- loop thru all the goals...

			FOR goalRec IN curGoals LOOP                 

				

				vCount := vCount + 1;

				

				IF vCount = 1 THEN 

					-- add the list header if this is the first record

					dbms_lob_s.append(vText, '

						<text>

							<table border="1" width="100%">

								<thead>

									<tr>

										<th>Goal</th>

									</tr>

								</thead>

								<tbody>		       			

						');				

				END IF;

				

				dbms_lob_s.append(vText, '

								<tr>

									<td ID="goal' || vCount || '">' || htf.escape_sc(goalRec."AnsText") || '</td>

								</tr>

					');	

						

				dbms_lob_s.append(vEntries, '

				<entry>

					<!-- Goal Observation -->

					<observation classCode="OBS" moodCode="GOL">

						<!-- Goal Observation -->

						<templateId root="2.16.840.1.113883.10.20.22.4.121"/>

						<!-- If you have an id for your goal, include here -->

						<id nullFlavor="UNK"/>

						<code nullFlavor="UNK"/>

						<text><reference value="#goal' || vCount || '"></reference></text>

						<statusCode code="active"/>

					</observation>

					</entry>');



			END LOOP;

			

		END IF;



		IF vCount > 0 THEN

			--close the list

			dbms_lob_s.append(vText, '

							</tbody>	

						</table>

					</text>	

					');	

		ELSE

		

			IF vbShowInfo THEN

				-- handle case where there were no goals...

				-- human readable text

				dbms_lob_s.append(vText, '<text>The patient has no Goals on file.</text>');

			ELSE

				dbms_lob_s.append(vText, '<text></text>');

			END IF;

			

			-- machine readable XML

			dbms_lob_s.append(vEntries, '

							<entry>

								<!-- Goal Observation -->

								<observation classCode="OBS" moodCode="GOL">

									<!-- Goal Observation -->

									<templateId root="2.16.840.1.113883.10.20.22.4.121"/>

									<!-- If you have an id for your goal, include here -->

									<id nullFlavor="UNK"/>

									<code nullFlavor="UNK"/>

									<text><reference value="#goal"></reference></text>

									<statusCode nullFlavor="UNK"/>

								</observation>

							</entry>

							');

				

		END IF;



		dbms_lob_s.append(vResult, vText);

		dbms_lob_s.append(vResult, vEntries);

		dbms_lob_s.append(vResult, '

		    </section>

		 </component>');



		return vResult;

	END;  



	-- AX-21739

	FUNCTION gethealthconcernssection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob IS

		vResult CLOB := '';

		vText CLOB := '';

		vEntries CLOB := '';

		vCount NUMBER := 0;



		vRefCode FITEM."Code"%TYPE := 'MUHC';



		CURSOR curGoals IS

			SELECT TRIM(htf.escape_sc(PI."AnsText")) "AnsText"

			FROM PITEM PI, FITEM FI

			WHERE 1=1 

				AND PI."FItem" = FI."FItem"

				AND PI."Patient" = vPId

				AND FI."Code" = vRefCode

				AND PI."AuditNumber" =     

					(SELECT MAX(PI2."AuditNumber")

					FROM PITEM PI2, FITEM FI2

					WHERE 1=1 

						AND PI2."FItem" = FI2."FItem"

						AND PI2."Patient" = vPId

						AND FI2."Code" = vRefCode

						AND FI2."Deleted" = 0

						AND PI2."AppDate" IS NOT NULL

						AND 

						(

							(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(PI."Date") >= TRUNC(vDate1) AND TRUNC(PI."Date") <= TRUNC(vDate2))

							OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(PI."Date") >= TRUNC(vDate1))

							OR(vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(PI."Date") <= TRUNC(vDate1)) 

							OR (vDate1 IS NULL)

						));

		

	   v_nCount		NUMBER := 0;								-- AX-26071.2



	BEGIN

		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetHealthConcernsSection');

		IF v_nCount > 0 THEN

			-- custom package function exists ; AX-27290

			EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetHealthConcernsSection(:1, :2, :3, :4, :5) FROM DUAL' INTO vResult

									USING vPId, vbShowInfo, vIsDateFrom, vDate1, vDate2;

			RETURN vResult;

		END IF;



		-- init clobs

		dbms_lob_s.createtemporary (vResult, TRUE);

		dbms_lob_s.createtemporary (vText, TRUE);

		dbms_lob_s.createtemporary (vEntries, TRUE);



		-- section header

		vResult := '

		<component>

		    <section>

				<!-- Health Concerns Section -->

				<templateId root="2.16.840.1.113883.10.20.22.2.58" extension="2015-08-01"/>

				<code code="75310-3" displayName="Health Concerns Document" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC"/>

				<title>Health Concerns</title>';



		IF vbShowInfo THEN

			-- loop thru all the goals...

			FOR goalRec IN curGoals LOOP                 

				

				vCount := vCount + 1;

				

				IF vCount = 1 THEN 

					-- add the list header if this is the first record

					dbms_lob_s.append(vText, '

						<text>

							<table border="1" width="100%">

								<thead>

									<tr>

										<th>Health Concern</th>

									</tr>

								</thead>

								<tbody>		       			

						');				

				END IF;

				

				dbms_lob_s.append(vText, '

								<tr>

									<td ID="concern' || vCount || '">' || htf.escape_sc(goalRec."AnsText") || '</td>

								</tr>

					');	

						

				dbms_lob_s.append(vEntries, '

				<entry>

					<!-- Health Concern Act -->

					<act classCode="ACT" moodCode="EVN">

						<templateId root="2.16.840.1.113883.10.20.22.4.132" extension="2015-08-01"/>

						<id nullFlavor="UNK"/>

						<!-- Fixed act/code in C-CDA -->

						<code code="75310-3" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Health Concern"/>

						<text><reference value="#concern' || vCount || '"></reference></text>

						<statusCode code="active"/>

					</act>

				</entry>');



			END LOOP;

			

		END IF;



		IF vCount > 0 THEN

			--close the list

			dbms_lob_s.append(vText, '

							</tbody>	

						</table>

					</text>	

					');	

		ELSE

		

			IF vbShowInfo THEN

				-- handle case where there were no goals...

				-- human readable text

				dbms_lob_s.append(vText, '<text>The patient has no Health Concerns on file.</text>');

			ELSE

				dbms_lob_s.append(vText, '<text></text>');

			END IF;

			

			-- machine readable XML

			dbms_lob_s.append(vEntries, '

							<entry>

								<!-- Health Concern Act -->

								<act classCode="ACT" moodCode="EVN">

									<templateId root="2.16.840.1.113883.10.20.22.4.132" extension="2015-08-01"/>

									<id nullFlavor="UNK"/>

									<!-- Fixed act/code in C-CDA -->

									<code code="75310-3" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Health Concern"/>

									<text><reference value="#concern"></reference></text>

									<statusCode nullFlavor="UNK"/>

								</act>

							</entry>

							');

				

		END IF;



		dbms_lob_s.append(vResult, vText);

		dbms_lob_s.append(vResult, vEntries);

		dbms_lob_s.append(vResult, '

		    </section>

		 </component>');



		return vResult;

	END;  





	-- AX-26344

	FUNCTION getclinicalnotessection(vpid numeric, vbshowinfo boolean DEFAULT true, visdatefrom numeric DEFAULT 0, vdate1 timestamp without time zone DEFAULT NULL::timestamp without time zone, vdate2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob IS

		vResult CLOB := '';

		vText CLOB := '';

		vEntries CLOB := '';

		vNote CLOB := '';

		vCount NUMBER := 0;

		vLastNoteDate DATE := NULL;



		CURSOR curNote IS

			SELECT

				n."Type",

				n."Text",

				n."Date",  

				n."AddDateTime",    

				n."User", 

				u."First", 

				u."Name"

			FROM 

			    notes2 n,

				patient2 p2,

				USERS u

			WHERE 1=1 

				AND p2."PtxPId" = vPId

				AND p2."Auto" = n."PId"

				AND n."Status" = 0

				AND n."Type" IN (0,3,4,6)

				AND n."TxId" = 0

				AND n."AppUser" > 0

				AND n."User" = u."User"

				AND 

				(

					(vDate1 IS NOT NULL AND vDate2 IS NOT NULL AND TRUNC(n."Date") >= TRUNC(vDate1) AND TRUNC(n."Date") <= TRUNC(vDate2))

					OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 1 AND TRUNC(n."Date") >= TRUNC(vDate1))

					OR (vDate1 IS NOT NULL AND vDate2 IS NULL AND vIsDateFrom = 0 AND TRUNC(n."Date") <= TRUNC(vDate1)) 

					OR (vDate1 IS NULL)

				)

			ORDER BY n."Date" ASC, n."AddDateTime" ASC, n."SectionNo";



	   v_nCount		NUMBER := 0;								-- AX-26071.2

		

	BEGIN

		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetClinicalNotesSection');

		IF v_nCount > 0 THEN

			-- custom package function exists ; AX-27290

			EXECUTE IMMEDIATE 'SELECT CUSTOM_CCDA_CFG_PKG.GetClinicalNotesSection(:1, :2, :3, :4, :5) FROM DUAL' INTO vResult

									USING vPId, vbShowInfo, vIsDateFrom, vDate1, vDate2;

			RETURN vResult;

		END IF;



		-- init clobs

		dbms_lob_s.createtemporary (vResult, TRUE);

		dbms_lob_s.createtemporary (vText, TRUE);

		dbms_lob_s.createtemporary (vEntries, TRUE);

		dbms_lob_s.createtemporary (vNote, TRUE);



		-- section header

		vResult := '

		<component>

		    <section>

		       <templateId root="2.16.840.1.113883.10.20.22.2.65" extension="2016-11-01"/>

		       <!-- Notes Section -->

		       <code code="11488-4" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC"

			  	displayName="CLINICAL NOTES"/>

		       <title>Clinical Notes</title>';



		IF vbShowInfo THEN

			-- loop thru all the notes...

			FOR noteRec IN curNote LOOP                 

				

				vCount := vCount + 1;

				

				IF vCount = 1 THEN

					dbms_lob_s.append(vText, '

						<text>

							<list>

						');			

				END IF;	



				-- AX-26430

				IF vLastNoteDate IS NULL OR vLastNoteDate <> noteRec."Date" THEN

					GetSOAPNotes(vPId, noteRec."Date", vText, vEntries, vCount);

				END IF;

			

				IF NOT (trim(noteRec."Text") IS NULL OR length(trim(noteRec."Text")) = 0) AND noteRec."Type" <> 4 THEN



					SELECT REPLACE(noteRec."Text", Chr(39), Chr(39)||Chr(39)) INTO vNote FROM DUAL;

					SELECT REPLACE(vNote, Chr(34), Chr(39)||Chr(39)) INTO vNote FROM DUAL;

					SELECT REPLACE(vNote, Chr(96), Chr(39)||Chr(39)) INTO vNote FROM DUAL;



					-- AX-26461

					dbms_lob_s.append(vText, '

							<item ID="note' || vCount || '">	 

								<paragraph>' || TO_CHAR(noteRec."Date", 'MM/DD/YYYY') || '</paragraph>   	

							');	



					FOR Lines IN (select regexp_substr (vNote, '[^' || CHR(10)|| ']+', 1, rownum) Txt from dual 

						connect by level <= regexp_count (vNote, '[^' || CHR(10)|| ']+'))

			   		LOOP

						dbms_lob_s.append(vText, '

								<paragraph>' || htf.escape_sc(Lines.Txt) || '</paragraph>   

							');	

			   		END LOOP;						



					dbms_lob_s.append(vText, '

								<paragraph> </paragraph>   

							</item>

							');	



					dbms_lob_s.append(vEntries, '

						<entry>

							<!-- Note Activity entry -->

								<act classCode="ACT" moodCode="EVN">

									<templateId root="2.16.840.1.113883.10.20.22.4.202" extension="2016-11-01"/>

									<code code="34109-9" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC"

										displayName="Note">

										<!-- Code must match or be equivalent to section code -->

										<translation code="11488-4" codeSystem="2.16.840.1.113883.6.1"

											codeSystemName="LOINC" displayName="Consultation note"/>

									</code>

									<text>

										<reference value="#note' || vCount || '"/>

									</text>

									<statusCode code="completed"/>

									<!-- Clinically-relevant time of the note -->

									<effectiveTime value="' || TO_CHAR(noteRec."Date", 'MM/DD/YYYY') || '"/>

									<!-- Author Participation -->

									<author>

										<templateId root="2.16.840.1.113883.10.20.22.4.119"/>

										<!-- Time note was actually written -->

										<time value="' || TO_CHAR(noteRec."AddDateTime", 'MM/DD/YYYY HH:MM') || '"/>

										<assignedAuthor>

											<id extension="' || GetUserIdentifier(noteRec."User") ||'" root="' ||GetUserIdentifierType ||'"/>

											<assignedPerson>

												<name>' || htf.escape_sc(TRIM(noteRec."First")) || htf.escape_sc(TRIM(noteRec."Name")) || '</name>

											</assignedPerson>

										</assignedAuthor>

									</author>

									<!-- Reference to encounter -->

									<entryRelationship nullFlavor="NA"/>	

								</act>

							</entry>');



				END IF;



				vLastNoteDate := noteRec."Date";



			END LOOP;

			

		END IF;



		IF vCount > 0 THEN

			dbms_lob_s.append(vText, '

						</list>

					</text>		

			');



		ELSE

		

			IF vbShowInfo THEN

				dbms_lob_s.append(vText, '<text>No Clinical Notes are on file.</text>');

			ELSE

				dbms_lob_s.append(vText, '<text></text>');

			END IF;

			

			-- machine readable XML

			dbms_lob_s.append(vEntries, '

				 <entry typeCode="DRIV">

				    <act classCode="ACT" moodCode="EVN" negationInd="true">

					<templateId root="2.16.840.1.113883.10.20.22.4.202" extension="2016-11-01"/>

					  <code nullFlavor="NA"/>

					  <statusCode code="completed"/>

					  <effectiveTime>

					    <low nullFlavor="UNK"/>

					  </effectiveTime>

					  <author nullFlavor="NA"/>

					  <entryRelationship nullFlavor="NA"/>	

				    </act>

				 </entry>

				');

				

		END IF;



		dbms_lob_s.append(vResult, vText);



		dbms_lob_s.append(vResult, vEntries);



		dbms_lob_s.append(vResult, '

		    </section>

		 </component>');



		return vResult;

	END; 



	-- AX-26430

	PROCEDURE getsoapnotes(IN vpid numeric, IN vnotedate timestamp without time zone, INOUT vtext clob, INOUT ventries clob, INOUT vcount numeric) IS

		vNote CLOB := '';

		vSOAPLabel CLOB := '';

		vLastId NUMBER := 0;

		vSOAPCount NUMBER := 0;



		CURSOR curSOAPNote IS

			SELECT

				n."SectionNo",

				n."Text",

				n."Date",  

				n."AddDateTime",    

				n."User", 

				n."OtherId", 

				u."First", 

				u."Name"

			FROM 

				notes2 n,

				patient2 p2,

				USERS u

			WHERE 1=1 

				AND p2."PtxPId" = vPId

				AND p2."Auto" = n."PId"

				AND n."Status" = 0

				AND n."Type" = 4

				AND n."TxId" = 0

				AND n."Date" = vNoteDate

				AND n."Text" IS NOT NULL

				AND n."AppUser" > 0

				AND n."User" = u."User"

			ORDER BY n."Auto" DESC, n."SectionNo";

			

	   v_nCount		NUMBER := 0;								-- AX-26071.2

		v_sqlBlock  VARCHAR2(1000);                     -- AX-26071.2



	BEGIN



		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetSOAPNotes');

		IF v_nCount > 0 THEN

		  -- custom package function exists; AX-27307; AX-27429 

		  v_sqlBlock := 'BEGIN CUSTOM_CCDA_CFG_PKG.GetSOAPNotes(:1, :2, :3, :4, :5); END;';

        EXECUTE IMMEDIATE v_sqlBlock USING in vPId, in vNoteDate, in out vText, in out vEntries, in out vCount;

		  RETURN;

		END IF;





		-- init clobs

		dbms_lob_s.createtemporary (vNote, TRUE);

		dbms_lob_s.createtemporary (vSOAPLabel, TRUE);



		vSOAPLabel := '';

		vLastId := 0;

		vSOAPCount := 0;



		FOR soapRec IN curSOAPNote LOOP



			IF vLastId <> soapRec."OtherId" THEN



				IF vSOAPCount > 0 THEN

					-- close off the last one...

					dbms_lob_s.append(vText, '

							<paragraph> </paragraph>   

						</item>

						');

				END IF;	



				vSOAPCount := vSOAPCount + 1;



				-- start new note...

				dbms_lob_s.append(vText, '

						<item ID="note' || vCount || '">	 

							<paragraph>' || TO_CHAR(soapRec."Date", 'MM/DD/YYYY') || '</paragraph>   	

						');	



				dbms_lob_s.append(vEntries, '

						<entry>

							<!-- Note Activity entry -->

								<act classCode="ACT" moodCode="EVN">

									<templateId root="2.16.840.1.113883.10.20.22.4.202" extension="2016-11-01"/>

									<code code="34109-9" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC"

										displayName="Note">

										<!-- Code must match or be equivalent to section code -->

										<translation code="11488-4" codeSystem="2.16.840.1.113883.6.1"

											codeSystemName="LOINC" displayName="Consultation note"/>

									</code>

									<text>

										<reference value="#note' || vSOAPCount || '"/>

									</text>

									<statusCode code="completed"/>

									<!-- Clinically-relevant time of the note -->

									<effectiveTime value="' || TO_CHAR(soapRec."Date", 'MM/DD/YYYY') || '"/>

									<!-- Author Participation -->

									<author>

										<templateId root="2.16.840.1.113883.10.20.22.4.119"/>

										<!-- Time note was actually written -->

										<time value="' || TO_CHAR(soapRec."AddDateTime", 'MM/DD/YYYY HH:MM') || '"/>

										<assignedAuthor>

											<id extension="' || GetUserIdentifier(soapRec."User") ||'" root="' ||GetUserIdentifierType ||'"/>

											<assignedPerson>

												<name>' || htf.escape_sc(TRIM(soapRec."First")) || htf.escape_sc(TRIM(soapRec."Name")) || '</name>

											</assignedPerson>

										</assignedAuthor>

									</author>

									<!-- Reference to encounter -->

									<entryRelationship nullFlavor="NA"/>	

								</act>

							</entry>');

			END IF;



			SELECT REPLACE(soapRec."Text", Chr(39), Chr(39)||Chr(39)) INTO vNote FROM DUAL;

			SELECT REPLACE(vNote, Chr(34), Chr(39)||Chr(39)) INTO vNote FROM DUAL;

			SELECT REPLACE(vNote, Chr(96), Chr(39)||Chr(39)) INTO vNote FROM DUAL;



			IF soapRec."SectionNo" = 0 THEN

				vSOAPLabel := 'Subjective: ' || vNote;

			ELSIF soapRec."SectionNo" = 1 THEN

				vSOAPLabel := 'Objective: ' || vNote;

			ELSIF soapRec."SectionNo" = 2 THEN

				vSOAPLabel := 'Assessment: ' || vNote;

			ELSIF soapRec."SectionNo" = 3 THEN

				vSOAPLabel := 'Planned: ' || vNote;

			END IF;

			

			dbms_lob_s.append(vText, '

					<paragraph>' || htf.escape_sc(vSOAPLabel) || '</paragraph>   

				');	



			vLastId := soapRec."OtherId";



		END LOOP;



		IF vSOAPCount > 0 THEN

			dbms_lob_s.append(vText, '

					<paragraph> </paragraph>   

					</item>

			');



			vCount := vCount + vSOAPCount;

		END IF;	



	END;



	-- AX-26430

	PROCEDURE gettxsoapnotes(IN vpid numeric, IN vnotedate timestamp without time zone, IN vcharttrx numeric, INOUT vtext clob, INOUT ventries clob, INOUT vcount numeric) IS

		vNote CLOB := '';

		vSOAPLabel CLOB := '';

		vLastId NUMBER := 0;

		vSOAPCount NUMBER := 0;



		CURSOR curSOAPNote IS

			SELECT

				n."SectionNo",

				n."Text",

				n."Date",  

				n."AddDateTime",    

				n."User", 

				n."OtherId", 

				u."First", 

				u."Name"

			FROM 

				notes2 n,

				patient2 p2,

				USERS u

			WHERE 1=1 

				AND p2."PtxPId" = vPId

				AND p2."Auto" = n."PId"

				AND n."Status" = 0

				AND n."Type" = 4

				AND n."TxId" = vChartTrx

				AND n."Date" = vNoteDate

				AND n."Text" IS NOT NULL

				AND n."AppUser" > 0

				AND n."User" = u."User"

			ORDER BY n."Auto" DESC, n."SectionNo";

			

	   v_nCount		NUMBER := 0;								-- AX-26071.2

		v_sqlBlock  VARCHAR2(1000);                     -- AX-26071.2



	BEGIN



		--AX-26071.2

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_CCDA_CFG_PKG' and PROCEDURE_NAME = UPPER('GetTxSOAPNotes');

		IF v_nCount > 0 THEN

		  -- custom package function exists ; AX-27307; AX-27429

	     v_sqlBlock := 'BEGIN CUSTOM_CCDA_CFG_PKG.GetTxSOAPNotes(:1, :2, :3, :4, :5, :6); END;';

		  EXECUTE IMMEDIATE v_sqlBlock USING in vPId, in vNoteDate, in vChartTrx, in out vText, in out vEntries, in out vCount;

		  RETURN;

		END IF;



		-- init clobs

		dbms_lob_s.createtemporary (vNote, TRUE);

		dbms_lob_s.createtemporary (vSOAPLabel, TRUE);



		vSOAPLabel := '';

		vLastId := 0;

		vSOAPCount := 0;



		FOR soapRec IN curSOAPNote LOOP



			IF vLastId <> soapRec."OtherId" THEN



				IF vSOAPCount > 0 THEN

					dbms_lob_s.append(vText, '

								<br />

					');	

				END IF;	



				vSOAPCount := vSOAPCount + 1;

				dbms_lob_s.append(vText, '

								' || TO_CHAR(soapRec."Date", 'MM/DD/YYYY') || '<br />');	

			END IF;



			SELECT REPLACE(soapRec."Text", Chr(39), Chr(39)||Chr(39)) INTO vNote FROM DUAL;

			SELECT REPLACE(vNote, Chr(34), Chr(39)||Chr(39)) INTO vNote FROM DUAL;

			SELECT REPLACE(vNote, Chr(96), Chr(39)||Chr(39)) INTO vNote FROM DUAL;



			IF soapRec."SectionNo" = 0 THEN

				vSOAPLabel := 'Subjective: ' || vNote;

			ELSIF soapRec."SectionNo" = 1 THEN

				vSOAPLabel := 'Objective: ' || vNote;

			ELSIF soapRec."SectionNo" = 2 THEN

				vSOAPLabel := 'Assessment: ' || vNote;

			ELSIF soapRec."SectionNo" = 3 THEN

				vSOAPLabel := 'Planned: ' || vNote;

			END IF;

		

			dbms_lob_s.append(vText, '

					<content ID="procnote' || vSOAPCount ||  '">' || htf.escape_sc(vSOAPLabel) || '</content><br />

				');	



			vLastId := soapRec."OtherId";



		END LOOP;



		IF vSOAPCount > 0 THEN

			dbms_lob_s.append(vText, '

						<br />

			');	

			vCount := vCount + vSOAPCount;

		END IF;	



	END;



END;
CREATE OR REPLACE PACKAGE BODY ccda_pkg IS



	-- E143263 added; E143263.4

	-- Patient Demographic Information

	patdateofbirth_section CONSTANT numeric(5,0) DEFAULT 0;

	patethnicity_section CONSTANT numeric(5,0) DEFAULT 1;

	patname_section CONSTANT numeric(5,0) DEFAULT 2;

	patlanguage_section CONSTANT numeric(5,0) DEFAULT 3;

	patrace_section CONSTANT numeric(5,0) DEFAULT 4;

	patsex_section CONSTANT numeric(5,0) DEFAULT 5;

	-- Conditions   Concerns

	reasonforvisit_section CONSTANT numeric(5,0) DEFAULT 6;

	problems_section CONSTANT numeric(5,0) DEFAULT 7;

	-- Allergies, Adverse Reactions, Alerts

	medallergies_section CONSTANT numeric(5,0) DEFAULT 8;

	-- Medications   Immunizations

	activemed_section CONSTANT numeric(5,0) DEFAULT 9;

	medadminvisit_section CONSTANT numeric(5,0) DEFAULT 10;

	immunizations_section CONSTANT numeric(5,0) DEFAULT 11;

	-- Observations   Results

	vitalsigns_section CONSTANT numeric(5,0) DEFAULT 12;

	socialhistory_section CONSTANT numeric(5,0) DEFAULT 13;

	functionalstatus_section CONSTANT numeric(5,0) DEFAULT 14;

	labtestresults_section CONSTANT numeric(5,0) DEFAULT 15;

	-- Procedures

	procedures_section CONSTANT numeric(5,0) DEFAULT 16;

	-- Encounter   Care team

	dateofvisit_section CONSTANT numeric(5,0) DEFAULT 17;

	careteam_section CONSTANT numeric(5,0) DEFAULT 18;

	locationofvisit_section CONSTANT numeric(5,0) DEFAULT 19;

	-- Care Planning

	goalandinstruction_section CONSTANT numeric(5,0) DEFAULT 20;

	clininstruction_section CONSTANT numeric(5,0) DEFAULT 21;

	patdecisionaids_section CONSTANT numeric(5,0) DEFAULT 22;

	futureappts_section CONSTANT numeric(5,0) DEFAULT 23;

	referralstoother_section CONSTANT numeric(5,0) DEFAULT 24;

	plannedprocedures_section CONSTANT numeric(5,0) DEFAULT 25;

	pendinglabtest_section CONSTANT numeric(5,0) DEFAULT 26;

	medicalequipment_section CONSTANT numeric(5,0) DEFAULT 27;	--	AX-21118

	-- Clinical Notes

	clinicalnotes_section CONSTANT numeric(5,0) DEFAULT 28;	--	AX-26344



--E143263.3

FUNCTION showinfoinsection(sectionstr character varying, section numeric) RETURN boolean IS



BEGIN

	IF SUBSTR(SectionStr, Section+1, 1) = '1' THEN

		RETURN TRUE;

	ELSE

		RETURN FALSE;

	END IF;

END;





--E143263.3 added last two optional parameters; E143263.4

FUNCTION getccdaheader(patientid numeric, practiceid numeric, userid numeric, title character varying, selsections character varying DEFAULT NULL::character varying) RETURN clob IS



FileContent CLOB;

    vPatientRec PATIENT%ROWTYPE;

    vPracticeRec PRACTICE%ROWTYPE;

    vMaritalText  VARCHAR2(30) := '';

    vMarital  CHAR(1);



    vUserFirst USER_VIEW."First"%TYPE;

    vUserLast USER_VIEW."Last"%TYPE;



    vEnterFirst USER_VIEW."First"%TYPE;

    vEnterLast USER_VIEW."Last"%TYPE;

    vUserId NUMBER;



	vLang  CHAR(3) := '';

	vPUser NUMBER := 0;



    CURSOR curRaces IS

      SELECT R."USType", R."Description"

      FROM RACE R, PTRACE P

      WHERE P."Patient" = PatientId

      AND R."Race" = P."Race"

      AND P."Deleted" = 0;





    CURSOR curEthnic IS

      SELECT E."USType", E."Description"

      FROM ETHNIC E, PATIENT P

      WHERE P."Ethnic" = E."Ethnic" AND P."Patient" = PatientId;





     vRaceCount NUMBER := 0;

     vEthnicCount NUMBER := 0;

     vPtPhoneCount NUMBER := 0;



     --E143263.4

     vbShowPatDOB BOOLEAN := true;

     vbShowEthnicity BOOLEAN := true;

     vbShowPatName BOOLEAN := true;

     vbShowLanguage BOOLEAN := true;

     vbShowPatRace BOOLEAN := true;

     vbShowPatSex BOOLEAN := true;



	 vRaceDescription  VARCHAR2(255) := '';

	 vRaceCode  VARCHAR2(255) := '';



	 vSuffix PITEM."AnsText"%TYPE := NULL; -- AX-21879



	  -- AX-21879c

	 vGivenQualifier PITEM."AnsText"%TYPE := NULL;

	 vGiven PITEM."AnsText"%TYPE := NULL;

	 vFamilyQualifier PITEM."AnsText"%TYPE := NULL;



--     vbShowCareTeam BOOLEAN := true;



BEGIN



     --E143263.4

     if SelSections IS NOT NULL THEN

	     vbShowPatDOB := ShowInfoInSection(SelSections, PATDATEOFBIRTH_SECTION);

	     vbShowEthnicity := ShowInfoInSection(SelSections, PATETHNICITY_SECTION);

		  vbShowPatName := ShowInfoInSection(SelSections, PATNAME_SECTION);

		  vbShowLanguage := ShowInfoInSection(SelSections, PATLANGUAGE_SECTION);

        vbShowPatRace := ShowInfoInSection(SelSections, PATRACE_SECTION);

        vbShowPatSex := ShowInfoInSection(SelSections, PATSEX_SECTION);



--        vbShowCareTeam := ShowInfoInSection(SelSections, CARETEAM_SECTION);

     END IF;



  vUserId := UserId;

  dbms_lob_s.createtemporary (FileContent, TRUE);



 SELECT * INTO vPatientRec FROM PATIENT WHERE "Patient" = PatientId;

    SELECT * INTO vPracticeRec FROM PRACTICE 

    WHERE 1 = 1 

        AND CASE PracticeId WHEN 0 THEN 0 ELSE "Id" END = PracticeId

		AND "Inactive" = 0

        AND ROWNUM = 1;



    BEGIN

		IF UserId = 0 THEN

			-- When called from MU API

			BEGIN

				SELECT u."User" INTO vPUser 

				FROM ptprod pt

					inner join users u on pt."Producer" = u."Producer"

				WHERE pt."Patient" = PatientId

					AND ((pt."IsPrimary" = 1) OR (pt."EndDate" > sysdate) OR (pt."EndDate" < sysdate) OR (1=1)) AND pt."Deleted" = 0

				ORDER BY pt."IsPrimary" DESC, pt."EndDate" DESC

				FETCH FIRST 1 ROW ONLY; 

			EXCEPTION

				WHEN NO_DATA_FOUND THEN

				vPUser := 0;

			END;        

		  

			IF vPUser IS NULL OR vPUser = 0 THEN

				SELECT "User" INTO vPUser FROM Users 

				WHERE "Deleted" = 0

				FETCH FIRST 1 ROW ONLY;   

			END IF;



			SELECT "Last", "First" INTO vUserLast, vUserFirst 

			FROM USER_VIEW WHERE "User" = vPUser AND "Deleted" = 0;

		ELSE

			SELECT "Last", "First" INTO vUserLast, vUserFirst FROM USER_VIEW WHERE "User" = UserId;

		END IF;

        

		EXCEPTION WHEN NO_DATA_FOUND THEN

			SELECT "Last", "First" INTO vUserLast, vUserFirst FROM USER_VIEW WHERE "User" = vPatientRec."User";

			vUserId := vPatientRec."User";

    END;



    BEGIN

      SELECT "Last", "First" INTO vEnterLast, vEnterFirst FROM USER_VIEW WHERE "User" = vPatientRec."User";



      EXCEPTION WHEN NO_DATA_FOUND THEN

        vEnterLast := vUserLast;

        vEnterFirst := vUserFirst;

    END;



    BEGIN

	 -- AX-19341

		SELECT "ISO639_1" INTO vLang FROM ISOMAP WHERE "ISO639_2B" =

		(SELECT LOWER("ISOCode") FROM LANGCD L WHERE L."LangCd" = vPatientRec."PrefLanguage");



      EXCEPTION WHEN NO_DATA_FOUND THEN

        vLang := '';

		  

    END;





    dbms_lob_s.append(FileContent, '<?xml version="1.0"?>

    <?xml-stylesheet type="text/xsl" href="CDA.xsl"?>

      <ClinicalDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:schemaLocation="urn:hl7-org:v3 ../../../CDA%20R2/cda-schemas-and-samples/infrastructure/cda/CDA.xsd"

  xmlns="urn:hl7-org:v3"

  xmlns:cda="urn:hl7-org:v3"

  xmlns:sdtc="urn:hl7-org:sdtc">');



    dbms_lob_s.append(FileContent, '

    <realmCode

      code="US"/>

   <typeId

      root="2.16.840.1.113883.1.3"

      extension="POCD_HD000040"/>');



	 -- AX-18696.19084

    dbms_lob_s.append(FileContent, '

    <!-- US General Header Template -->

   <!-- CONF 5252 -->

   <templateId root="2.16.840.1.113883.10.20.22.1.1" extension="2015-08-01"/>

	<templateId root="2.16.840.1.113883.10.20.22.1.1"/>

	<!-- CCD template ID-->

	<templateId root="2.16.840.1.113883.10.20.22.1.2" extension="2015-08-01"/>

	<templateId root="2.16.840.1.113883.10.20.22.1.2"/>



   <!-- CONF:1198-5363 - This id *SHALL* be a globally unique identifier for the document. -->

   <id root="2.16.840.1.113883.4.8155"/>



   <!-- CONF 5253 "CCD document" -->

   <code

      codeSystem="2.16.840.1.113883.6.1"

      codeSystemName="LOINC"

      code="34133-9"

      displayName="Summarization of Episode Note"/>



   <!-- CONF 5254 -->

   <title>' || Title || '</title>



   <!-- CONF 5256 -->

   <effectiveTime

      value="' || TO_CHAR(sysdate, 'YYYYMMDD') ||'"/>



   <!-- 5259 -->

   <confidentialityCode

      code="N"

      codeSystem="2.16.840.1.113883.5.25"/>



   <!-- 5372 -->

   <languageCode

      code="en-US"/>');



    dbms_lob_s.append(FileContent, '

    <recordTarget>

      <patientRole>');



    dbms_lob_s.append(FileContent, '

    <!-- CONF 5268-->

     <id

       root="' || CCDA_CFG_PKG.GetPatientIdentifierType || '"

       extension="'|| CCDA_CFG_PKG.GetPatientIdentifier(PatientId, true) ||'"/>');		--E143263.3; E143263.4



	--E143263.3

	IF  NOT true THEN																					--E143263.4 always show

     dbms_lob_s.append(FileContent, '

		<addr nullFlavor="UNK"/>');



	ELSE

	  -- AX-18696.19084

     dbms_lob_s.append(FileContent, '

     <addr use="HP">');



		-- patient address

		IF  NOT (trim(vPatientRec."Address1") IS NULL OR length(trim(vPatientRec."Address1")) = 0)  THEN

			dbms_lob_s.append(FileContent, '

				<streetAddressLine>' ||  htf.escape_sc(trim(vPatientRec."Address1")) || '</streetAddressLine>');



			IF NOT (trim(vPatientRec."Address2") IS NULL OR length(trim(vPatientRec."Address2")) = 0)THEN

				dbms_lob_s.append(FileContent, '

					<streetAddressLine>' ||  htf.escape_sc(trim(vPatientRec."Address2")) || '</streetAddressLine>');

			END IF;

		ELSE

			--no address entered

			dbms_lob_s.append(FileContent, '

				<streetAddressLine nullFlavor="UNK"/>');

		END IF;



		-- patient city

		IF NOT (trim(vPatientRec."City") IS NULL OR length(trim(vPatientRec."City")) = 0) THEN

			dbms_lob_s.append(FileContent, '

				<city>' ||  htf.escape_sc(trim(vPatientRec."City")) || '</city>');

		ELSE

			-- no city entered

			dbms_lob_s.append(FileContent, '

				<city nullFlavor="UNK"/>');

		END IF;



		-- state/province

		IF NOT (trim(vPatientRec."Province") IS NULL OR length(trim(vPatientRec."Province")) = 0) THEN

			dbms_lob_s.append(FileContent, '

				<state>' ||  htf.escape_sc(trim(vPatientRec."Province")) || '</state>');

		ELSE

			-- no state entered

			dbms_lob_s.append(FileContent, '

				<state nullFlavor="UNK"/>');

		END IF;



		-- zip/postal code

		IF NOT (trim(vPatientRec."Postal") IS NULL OR length(trim(vPatientRec."Postal")) = 0) THEN

			dbms_lob_s.append(FileContent, '

				<postalCode>' ||  htf.escape_sc(trim(vPatientRec."Postal")) || '</postalCode>');

		ELSE

			--no zip/postal entered

			dbms_lob_s.append(FileContent, '

				<postalCode nullFlavor="UNK"/>');

		END IF;



  			-- country - always US since this is for CE only

		dbms_lob_s.append(FileContent, '

			<country>' || 'US' || '</country>');



		dbms_lob_s.append(FileContent, '

			</addr>');



   END IF;



	-- telephone numbers

	--E143263.3

	IF  NOT true THEN																		--E143263.4 always show

	     dbms_lob_s.append(FileContent, '

			<telecom nullFlavor="UNK"/>');

	ELSE



			IF NOT (trim(vPatientRec."HomePhone") IS NULL OR length(trim(vPatientRec."HomePhone")) = 0) THEN

				vPtPhoneCount := vPtPhoneCount + 1;



				dbms_lob_s.append(FileContent, '

					<telecom use="HP" value="tel:');



				IF NOT (trim(vPatientRec."HomeArea") IS NULL OR length(trim(vPatientRec."HomeArea")) = 0) THEN

		 			dbms_lob_s.append(FileContent,  htf.escape_sc(trim(vPatientRec."HomeArea")) || '-');

				END IF;



				dbms_lob_s.append(FileContent,  htf.escape_sc(trim(vPatientRec."HomePhone")));

				dbms_lob_s.append(FileContent, '" />');

			END IF;



			IF NOT (trim(vPatientRec."WorkPhone") IS NULL OR length(trim(vPatientRec."WorkPhone")) = 0) THEN

				vPtPhoneCount := vPtPhoneCount + 1;



				dbms_lob_s.append(FileContent, '

					<telecom use="WP" value="tel:');



				IF NOT (trim(vPatientRec."WorkArea") IS NULL OR length(trim(vPatientRec."WorkArea")) = 0) THEN

					dbms_lob_s.append(FileContent,  htf.escape_sc(trim(vPatientRec."WorkArea")) || '-');

				END IF;



				dbms_lob_s.append(FileContent,  htf.escape_sc(trim(vPatientRec."WorkPhone")));



				dbms_lob_s.append(FileContent,'" />');

			END IF;



			-- AX-26307

			IF NOT (trim(vPatientRec."Email") IS NULL OR length(trim(vPatientRec."Email")) = 0) THEN

				vPtPhoneCount := vPtPhoneCount + 1;



				dbms_lob_s.append(FileContent, '

					<telecom use="H" value="mailto:');



				dbms_lob_s.append(FileContent,  htf.escape_sc(trim(vPatientRec."Email")));

				dbms_lob_s.append(FileContent,'" />');

			END IF;



			IF vPtPhoneCount = 0 THEN

				--patient didn't have a home or work phone number entered..

				dbms_lob_s.append(FileContent, '

					<telecom use="HP" nullFlavor="UNK"/>');

			END IF;

	END IF;



    dbms_lob_s.append(FileContent, '

    <patient>');



    dbms_lob_s.append(FileContent, '

    <name use="L">');



    IF vbShowPatName THEN						--E143263.3

		dbms_lob_s.append(FileContent, '

		<given>' || htf.escape_sc(trim(vPatientRec."First")) || '</given>');

	ELSE

		dbms_lob_s.append(FileContent, '

		<given nullFlavor="UNK"/>');

	END IF;



    -- B142432 added middle name

    IF (vbShowPatName  AND  NOT (trim(vPatientRec."Middle") IS NULL OR length(vPatientRec."Middle") = 0)) THEN		--E143263.3

      dbms_lob_s.append(FileContent, '

        <given>' ||htf.escape_sc( trim(vPatientRec."Middle")) || '</given>');

    END IF;



    IF vbShowPatName THEN						--E143263.3

	    dbms_lob_s.append(FileContent, '

		 <family>' ||htf.escape_sc( trim(vPatientRec."Last")) || '</family>');

	 ELSE

		dbms_lob_s.append(FileContent, '

		<family nullFlavor="UNK"/>');

	 END IF;



	 -- AX-21879

	IF vbShowPatName THEN



		-- get the suffix from the MUDEMNMSF reference code

		BEGIN

			SELECT TRIM(htf.escape_sc(PI."AnsText")) INTO vSuffix

			FROM PITEM PI, FITEM FI

			WHERE 1=1 

				AND PI."FItem" = FI."FItem"

				AND PI."Patient" = vPatientRec."Patient"

				AND FI."Code" = 'MUDEMNMSF'  

				AND PI."AuditNumber" =     

					(SELECT MAX(PI2."AuditNumber")

					FROM PITEM PI2, FITEM FI2

					WHERE 1=1 

						AND PI2."FItem" = FI2."FItem"

						AND PI2."Patient" = vPatientRec."Patient"

						AND FI2."Code" = 'MUDEMNMSF' 

						AND FI2."Deleted" = 0

						AND PI2."AppDate" IS NOT NULL);



		EXCEPTION WHEN OTHERS THEN

			vSuffix := NULL;

		END;



		IF vSuffix is not null THEN

			dbms_lob_s.append(FileContent, '

			<suffix>' ||htf.escape_sc( trim(vSuffix)) || '</suffix>');

		ELSE

			dbms_lob_s.append(FileContent, '

			<suffix nullFlavor="UNK"/>');

		END IF;

	 ELSE

			dbms_lob_s.append(FileContent, '

			<suffix nullFlavor="UNK"/>');

	 END IF;



    dbms_lob_s.append(FileContent, '

    </name>');



	-- AX-21879c

	dbms_lob_s.append(FileContent, '

    <name>');



		-- given qualifier...

		BEGIN

			SELECT TRIM(htf.escape_sc(PI."AnsText")) INTO vGivenQualifier

			FROM PITEM PI, FITEM FI

			WHERE 1=1 

				AND PI."FItem" = FI."FItem"

				AND PI."Patient" = vPatientRec."Patient"

				AND FI."Code" = 'MUDEMPRFN'  

				AND PI."AuditNumber" =     

					(SELECT MAX(PI2."AuditNumber")

					FROM PITEM PI2, FITEM FI2

					WHERE 1=1 

						AND PI2."FItem" = FI2."FItem"

						AND PI2."Patient" = vPatientRec."Patient"

						AND FI2."Code" = 'MUDEMPRFN' 

						AND FI2."Deleted" = 0

						AND PI2."AppDate" IS NOT NULL);



		EXCEPTION WHEN OTHERS THEN

			vGivenQualifier := NULL;

		END;



		IF vGivenQualifier is not null THEN

			dbms_lob_s.append(FileContent, '

			<given qualifier="BR">' ||htf.escape_sc( trim(vGivenQualifier)) || '</given> <!-- BR = Birth name-->');

		ELSE

			dbms_lob_s.append(FileContent, '

			<given>' ||htf.escape_sc( trim(vPatientRec."First")) || '</given> <!-- BR = Birth name-->');

		END IF;



	 -- given

		BEGIN

			SELECT TRIM(htf.escape_sc(PI."AnsText")) INTO vGiven

			FROM PITEM PI, FITEM FI

			WHERE 1=1 

				AND PI."FItem" = FI."FItem"

				AND PI."Patient" = vPatientRec."Patient"

				AND FI."Code" = 'MUDEMPRMN'  

				AND PI."AuditNumber" =     

					(SELECT MAX(PI2."AuditNumber")

					FROM PITEM PI2, FITEM FI2

					WHERE 1=1 

						AND PI2."FItem" = FI2."FItem"

						AND PI2."Patient" = vPatientRec."Patient"

						AND FI2."Code" = 'MUDEMPRMN' 

						AND FI2."Deleted" = 0

						AND PI2."AppDate" IS NOT NULL);



		EXCEPTION WHEN OTHERS THEN

			vGiven := NULL;

		END;



		IF vGiven is not null THEN

			dbms_lob_s.append(FileContent, '

			<given>' ||htf.escape_sc( trim(vGiven)) || '</given>');

		ELSE

			IF NOT (trim(vPatientRec."Middle") IS NULL OR length(trim(vPatientRec."Middle")) = 0) THEN

				dbms_lob_s.append(FileContent, '

				<given>' ||htf.escape_sc( trim(vPatientRec."Middle")) || '</given>');

			ELSE

				dbms_lob_s.append(FileContent, '

				<given nullFlavor="UNK"/>');

			END IF;

		END IF;



	 -- family qualifier...

		BEGIN

			SELECT TRIM(htf.escape_sc(PI."AnsText")) INTO vFamilyQualifier

			FROM PITEM PI, FITEM FI

			WHERE 1=1 

				AND PI."FItem" = FI."FItem"

				AND PI."Patient" = vPatientRec."Patient"

				AND FI."Code" = 'MUDEMPRLN'  

				AND PI."AuditNumber" =     

					(SELECT MAX(PI2."AuditNumber")

					FROM PITEM PI2, FITEM FI2

					WHERE 1=1 

						AND PI2."FItem" = FI2."FItem"

						AND PI2."Patient" = vPatientRec."Patient"

						AND FI2."Code" = 'MUDEMPRLN' 

						AND FI2."Deleted" = 0

						AND PI2."AppDate" IS NOT NULL);



		EXCEPTION WHEN OTHERS THEN

			vFamilyQualifier := NULL;

		END;



		IF vFamilyQualifier is not null THEN

			dbms_lob_s.append(FileContent, '

			<family qualifier="BR">' ||htf.escape_sc( trim(vFamilyQualifier)) || '</family> <!-- BR = Birth name-->');

		ELSE

			dbms_lob_s.append(FileContent, '

			<family>' ||htf.escape_sc( trim(vPatientRec."Last")) || '</family> <!-- BR = Birth name-->');

		END IF;



	dbms_lob_s.append(FileContent, '

    </name>');





    IF vbShowPatSex  AND  vPatientRec."Sex" = 2 THEN				--E143263.3

		dbms_lob_s.append(FileContent, '

		<administrativeGenderCode code="F" displayName="Female"

                    codeSystem="2.16.840.1.113883.5.1" codeSystemName="AdministrativeGender"/>');

    ELSIF vbShowPatSex  AND  vPatientRec."Sex" = 1 THEN			--E143263.3

		dbms_lob_s.append(FileContent, '

		<administrativeGenderCode code="M" displayName="Male"

                    codeSystem="2.16.840.1.113883.5.1" codeSystemName="AdministrativeGender"/>');



    ELSE

		dbms_lob_s.append(FileContent, '

		<administrativeGenderCode code="UN" displayName="Undifferentiated"

                    codeSystem="2.16.840.1.113883.5.1" codeSystemName="AdministrativeGender"/>');

    END IF;



	-- date of birth

	IF vbShowPatDOB  AND  TRIM(TO_CHAR(vPatientRec."Birth", 'YYYYMMDD')) IS NOT NULL THEN		--E143263.3

		dbms_lob_s.append(FileContent, '

			<birthTime value="' || TO_CHAR(vPatientRec."Birth", 'YYYYMMDD') || '"/>');

	ELSE

		-- no DOB entered

		dbms_lob_s.append(FileContent, '

			<birthTime nullFlavor="UNK"/>');

	END IF;



    --Patient's marital status (0=Unknown, 1=Single, 2=Married, 3=Divorced, 4=Common-Law, 5=Seperated, 6=Widowed, 7=Domestic Partner)

    -- where does common law fall under?

    IF true THEN												--E143263.3; E143263.4 always show

		 IF vPatientRec."Marital" = 1 THEN

			vMaritalText := 'Never Married';

			vMarital := 'S';

		 ELSIF vPatientRec."Marital" = 2 THEN

			vMaritalText := 'Married';

			vMarital := 'M';

		 ELSIF vPatientRec."Marital" = 3 THEN

			vMaritalText := 'Divorced';

			vMarital := 'D';

		 ELSIF vPatientRec."Marital" = 5 THEN

			vMaritalText := 'Legally Separated';

			vMarital := 'L';

		 ELSIF vPatientRec."Marital" = 6 THEN

			vMaritalText := 'Widowed';

			vMarital := 'W';

		 ELSIF vPatientRec."Marital" = 7 THEN

			vMaritalText := 'Domestic Partner';

			vMarital := 'T';

		 END IF;

    END IF;



    IF vMaritalText IS NOT NULL THEN

      dbms_lob_s.append(FileContent, '

      <maritalStatusCode

               code="' || vMarital ||'"

               displayName="' || vMaritalText || '"

               codeSystem="2.16.840.1.113883.5.2"

               codeSystemName="MaritalStatusCode"/>');

    END IF;



    IF vbShowPatRace THEN												--E143263.3

		 -- B142580 - correct handling for multiracial patients

		 FOR raceRec IN curRaces

		 LOOP



    		vRaceCount := vRaceCount + 1;



			-- AX-21734b

			vRaceDescription := raceRec."Description"; 

			vRaceCode := CCDA_CFG_PKG.GetRaceCode(raceRec."USType");



			IF INSTR(vRaceDescription, ')') > 0 THEN

				vRaceDescription := SUBSTR(raceRec."Description", INSTR(raceRec."Description", ')')+2);

				vRaceCode := SUBSTR(raceRec."Description", INSTR(raceRec."Description", '(') + 1, INSTR(raceRec."Description", ')') - 2);

			END IF;



    		IF vRaceCount = 1 THEN

    			-- first race code needs to use standard CDA code

    				dbms_lob_s.append(FileContent, '

				<raceCode

					 code="' || vRaceCode || '"

					 displayName="' || htf.escape_sc(vRaceDescription) || '"

					 codeSystem="2.16.840.1.113883.6.238"

					 codeSystemName="Race and Ethnicity - CDC"/>');

    		ELSE

    			-- patient is multiracial, subsequent race codes need to use the extension

				dbms_lob_s.append(FileContent, '

					<sdtc:raceCode

						 code="' || vRaceCode || '"

						 displayName="' || htf.escape_sc(vRaceDescription) || '"

						 codeSystem="2.16.840.1.113883.6.238"

						 codeSystemName="Race and Ethnicity - CDC"/>');

    		END IF;

		 END LOOP;

	END IF;



    -- case where no race was entered

    IF vRaceCount = 0 THEN

			dbms_lob_s.append(FileContent, '

					<raceCode nullFlavor="UNK"/>');

    END IF;



    IF vbShowEthnicity THEN												--E143263.3

		 FOR ethnicRec IN curEthnic

		 LOOP

    		vEthnicCount := vEthnicCount + 1;



			dbms_lob_s.append(FileContent, '

			<ethnicGroupCode

					 code="' || CCDA_CFG_PKG.GetEthnicCode(ethnicRec."USType") || '"

					 displayName="' || ethnicRec."Description" || '"

					 codeSystem="2.16.840.1.113883.6.238"

					 codeSystemName="Race and Ethnicity - CDC"/>');



		 END LOOP;

	END IF;



    -- case where no ethnicity was entered

    IF vEthnicCount = 0 THEN

			dbms_lob_s.append(FileContent, '

				<ethnicGroupCode nullFlavor="UNK"/>');

    END IF;



    IF vbShowLanguage AND NOT (TRIM(vLang) IS NULL OR length(TRIM(vLang)) = 0) THEN			--E143263.3

	 -- AX-18696.19084

      dbms_lob_s.append(FileContent, '

	      <languageCommunication>

				<languageCode code="' || TRIM(vLang) || '"/>

				<preferenceInd value="true"/> 

	      </languageCommunication>');



    ELSE

    	-- case where no primary language was entered

	dbms_lob_s.append(FileContent, '

	      <languageCommunication>

		<languageCode nullFlavor="UNK"/>

	      </languageCommunication>');

    END IF;



    dbms_lob_s.append(FileContent, '

    </patient>');



    /*

    FileContent := FileContent || '

    <providerOrganization>';

    FileContent := FileContent || '

      <id root="2.16.840.1.113883.4.6" extension="' || NVL(TRIM(vPracticeRec."NPI"), 'UNK') ||'"/>';



    FileContent := FileContent || '

      <name>' || TRIM(vPracticeRec."Name") ||'</name>';



    IF NOT (TRIM(vPracticeRec."Phone") IS NULL OR length(TRIM(vPracticeRec."Phone")) = 0) THEN

    FileContent := FileContent || '

      <telecom use="WP" value="';

      IF NOT (TRIM(vPracticeRec."Area") IS NULL OR length(TRIM(vPracticeRec."Area")) = 0) THEN

        FileContent := FileContent || TRIM(vPracticeRec."Area") || '-';

      END IF;

      FileContent := FileContent || TRIM(vPracticeRec."Phone") ||'"/>';

    END IF;





    FileContent := FileContent || '

     <addr>';



     IF NOT (trim(vPracticeRec."Address1") IS NULL OR length(trim(vPracticeRec."Address1")) = 0) THEN

        FileContent := FileContent || '

     <streetAddressLine>' || trim(vPracticeRec."Address1") || '</streetAddressLine>';

     END IF;



     IF NOT (trim(vPracticeRec."Address2") IS NULL OR length(trim(vPracticeRec."Address2")) = 0) THEN

        FileContent := FileContent || '

     <streetAddressLine>' || trim(vPracticeRec."Address2") || '</streetAddressLine>';

     END IF;





     IF NOT (trim(vPracticeRec."City") IS NULL OR length(trim(vPracticeRec."City")) = 0) THEN

        FileContent := FileContent || '

     <city>' || trim(vPracticeRec."City") || '</city>';

     END IF;





     IF NOT (trim(vPracticeRec."Province") IS NULL OR length(trim(vPracticeRec."Province")) = 0)  THEN

        FileContent := FileContent || '

     <state>' || trim(vPracticeRec."Province") || '</state>';

     END IF;



     IF NOT (trim(vPracticeRec."Postal") IS NULL OR length(trim(vPracticeRec."Postal")) = 0) THEN

        FileContent := FileContent || '

     <postalCode>' || trim(vPracticeRec."Postal") || '</postalCode>';

     END IF;





     FileContent := FileContent || '

     <country>' || 'US' || '</country>';



     FileContent := FileContent || '

     </addr>';



    FileContent := FileContent || '

    </providerOrganization>';

    */





     dbms_lob_s.append(FileContent, '

    </patientRole>

  </recordTarget>');





  -- author; E143263.3 as per Paul, this section need to be shown regardless

    dbms_lob_s.append(FileContent, '

  <author>

  <time value="' || TO_CHAR(SYSDATE, 'YYYYMMDD') || '"/>

  <assignedAuthor>');

    dbms_lob_s.append(FileContent, '

    <id root="'|| CCDA_CFG_PKG.GetUserIdentifierType ||'" extension="' ||

						NVL(CCDA_CFG_PKG.GetUserIdentifier(vUserId), 'UNK') ||'"/>');



  	-- address

	dbms_lob_s.append(FileContent, '

		<addr use="WP">');



	IF NOT (trim(vPracticeRec."Address1") IS NULL OR length(trim(vPracticeRec."Address1")) = 0) THEN

		dbms_lob_s.append(FileContent, '

			<streetAddressLine>' ||  htf.escape_sc(trim(vPracticeRec."Address1")) || '</streetAddressLine>');

	ELSE

		-- no street address entered

		dbms_lob_s.append(FileContent, '

			<streetAddressLine nullFlavor="UNK"/>');

	END IF;



	IF NOT (trim(vPracticeRec."Address2") IS NULL OR length(trim(vPracticeRec."Address2")) = 0) THEN

		dbms_lob_s.append(FileContent, '

			<streetAddressLine>' ||  htf.escape_sc(trim(vPracticeRec."Address2")) || '</streetAddressLine>');

	END IF;



	-- city

	IF NOT (trim(vPracticeRec."City") IS NULL OR length(trim(vPracticeRec."City")) = 0) THEN

		dbms_lob_s.append(FileContent, '

			<city>' ||  htf.escape_sc(trim(vPracticeRec."City")) || '</city>');

	ELSE

		-- patient city unknown

		dbms_lob_s.append(FileContent, '

			<city nullFlavor="UNK"/>');

	END IF;



    	--state

	IF NOT (trim(vPracticeRec."Province") IS NULL OR length(trim(vPracticeRec."Province")) = 0) THEN

		dbms_lob_s.append(FileContent, '

			<state>' ||  htf.escape_sc(trim(vPracticeRec."Province")) || '</state>');

	ELSE

		--state unknown

		dbms_lob_s.append(FileContent, '

			<state nullFlavor="UNK"/>');

	END IF;



     	-- postal/zip code

	IF NOT (trim(vPracticeRec."Postal") IS NULL OR length(trim(vPracticeRec."Postal")) = 0) THEN

		dbms_lob_s.append(FileContent, '

			<postalCode>' ||  htf.escape_sc(trim(vPracticeRec."Postal")) || '</postalCode>');

	ELSE

		dbms_lob_s.append(FileContent, '

			<postalCode nullFlavor="UNK"/>');

	END IF;



   	--country - always US since this is only for CE

	dbms_lob_s.append(FileContent, '

		<country>' || 'US' || '</country>');

	dbms_lob_s.append(FileContent, '

		</addr>');



  	--telephone numbers

	IF NOT (TRIM(vPracticeRec."Phone") IS NULL OR length(TRIM(vPracticeRec."Phone")) = 0) THEN

		dbms_lob_s.append(FileContent, '

			<telecom use="WP" value="');



		IF NOT (TRIM(vPracticeRec."Area") IS NULL OR length(TRIM(vPracticeRec."Area")) = 0) THEN

			dbms_lob_s.append(FileContent,  htf.escape_sc(TRIM(vPracticeRec."Area")) || '-');

		END IF;



		dbms_lob_s.append(FileContent,  htf.escape_sc(TRIM(vPracticeRec."Phone")) ||'"/>');

	ELSE

		-- no phone number

		dbms_lob_s.append(FileContent, '

			<telecom use="WP" nullFlavor="UNK"/>');

	END IF;



	dbms_lob_s.append(FileContent, '

	 <assignedPerson>

				<name>

					<given>' || htf.escape_sc(trim(vUserFirst)) || '</given>

					<family>' || htf.escape_sc(trim(vUserLast)) || '</family>

				</name>

	 </assignedPerson>');



    dbms_lob_s.append(FileContent, '

  </assignedAuthor>

  </author>');



  -- data enterer, using most recent audit user

  dbms_lob_s.append(FileContent, '

  <dataEnterer>

      <assignedEntity>

         <id root="'|| CCDA_CFG_PKG.GetUserIdentifierType ||'" extension="' ||

								NVL(CCDA_CFG_PKG.GetUserIdentifier(vPatientRec."User"), 'UNK') ||'"/>');



	-- E143263.3

	IF NOT true THEN												-- E143263.4 always show

			dbms_lob_s.append(FileContent, '

			 <addr nullFlavor="UNK"/>');

	ELSE

				dbms_lob_s.append(FileContent, '

		  <addr use="WP">');



		  IF NOT (trim(vPracticeRec."Address1") IS NULL OR length(trim(vPracticeRec."Address1")) = 0) THEN

			  dbms_lob_s.append(FileContent, '

			 <streetAddressLine>' ||  htf.escape_sc(trim(vPracticeRec."Address1")) || '</streetAddressLine>');

			-- AX-18945.19094e

			ELSE

				-- no street address entered

				dbms_lob_s.append(FileContent, '

					<streetAddressLine nullFlavor="UNK"/>');

			END IF;



		  IF NOT (trim(vPracticeRec."Address2") IS NULL OR length(trim(vPracticeRec."Address2")) = 0) THEN

			  dbms_lob_s.append(FileContent, '

				<streetAddressLine>' ||  htf.escape_sc(trim(vPracticeRec."Address2")) || '</streetAddressLine>');

		  END IF;





		  IF NOT (trim(vPracticeRec."City") IS NULL OR length(trim(vPracticeRec."City")) = 0) THEN

			  dbms_lob_s.append(FileContent, '

				<city>' ||  htf.escape_sc(trim(vPracticeRec."City")) || '</city>');

		  	-- AX-18945.19094e

			ELSE

				-- patient city unknown

				dbms_lob_s.append(FileContent, '

					<city nullFlavor="UNK"/>');

			END IF;





		  IF NOT (trim(vPracticeRec."Province") IS NULL OR length(trim(vPracticeRec."Province")) = 0) THEN

			  dbms_lob_s.append(FileContent, '

				<state>' ||  htf.escape_sc(trim(vPracticeRec."Province")) || '</state>');

		 		-- AX-18945.19094e

			ELSE

				--state unknown

				dbms_lob_s.append(FileContent, '

					<state nullFlavor="UNK"/>');

			END IF;



		  IF NOT (trim(vPracticeRec."Postal") IS NULL OR length(trim(vPracticeRec."Postal")) = 0) THEN

			  dbms_lob_s.append(FileContent, '

				<postalCode>' ||  htf.escape_sc(trim(vPracticeRec."Postal")) || '</postalCode>');

		 	-- AX-18945.19094e

			ELSE

				dbms_lob_s.append(FileContent, '

					<postalCode nullFlavor="UNK"/>');

			END IF;



		  dbms_lob_s.append(FileContent, '

		  <country>' || 'US' || '</country>');

		  dbms_lob_s.append(FileContent, '

		  </addr>');

	END IF;



     IF true AND NOT (TRIM(vPracticeRec."Phone") IS NULL OR length(TRIM(vPracticeRec."Phone")) = 0) THEN					--E143263.3; E143263.4 always show if applicable

			dbms_lob_s.append(FileContent, '

			<telecom use="WP" value="');

			IF NOT (TRIM(vPracticeRec."Area") IS NULL OR length(TRIM(vPracticeRec."Area")) = 0) THEN

				dbms_lob_s.append(FileContent,  htf.escape_sc(TRIM(vPracticeRec."Area")) || '-');

			END IF;

			dbms_lob_s.append(FileContent,  htf.escape_sc(TRIM(vPracticeRec."Phone")) ||'"/>');

		-- AX-18945.19094e

		ELSE

			-- no phone number

			dbms_lob_s.append(FileContent, '

				<telecom use="WP" nullFlavor="UNK"/>');

		END IF;



		IF true	THEN																			--E143263.3; E143263.4 always show

			dbms_lob_s.append(FileContent, '

         <assignedPerson>

            <name>

               <given>' || htf.escape_sc(trim(vEnterFirst)) ||'</given>

               <family>' || htf.escape_sc(trim(vEnterLast)) || '</family>

            </name>

         </assignedPerson>');

      END IF;



		dbms_lob_s.append(FileContent, '

				</assignedEntity>

			</dataEnterer>');







  -- custodian

    dbms_lob_s.append(FileContent, '

  <custodian>

  <assignedCustodian>

    <representedCustodianOrganization>');

      dbms_lob_s.append(FileContent, '

      <id root="2.16.840.1.113883.4.6" extension="');



      --E143263.3

      IF true THEN																--E143263.4 always show

	      dbms_lob_s.append(FileContent, NVL(TRIM(vPracticeRec."NPI"), 'UNK') ||'"/>');

	    ELSE

	      dbms_lob_s.append(FileContent, 'UNK' ||'"/>');

	    END IF;



      IF true THEN																	--E143263.3; E143263.4 always show

	       dbms_lob_s.append(FileContent, '

		   <name>'||  htf.escape_sc(TRIM(vPracticeRec."Name")) ||'</name>');

      ELSE

			dbms_lob_s.append(FileContent, '<name nullFlavor="UNK"/>');

		END IF;



    IF true AND NOT (TRIM(vPracticeRec."Phone") IS NULL OR length(TRIM(vPracticeRec."Phone")) = 0) THEN				--E143263.3; E143263.4 always show

		dbms_lob_s.append(FileContent, '

      <telecom use="WP" value="');

      IF NOT (TRIM(vPracticeRec."Area") IS NULL OR length(TRIM(vPracticeRec."Area")) = 0) THEN

        dbms_lob_s.append(FileContent,  htf.escape_sc(TRIM(vPracticeRec."Area")) || '-');

      END IF;

      dbms_lob_s.append(FileContent,  htf.escape_sc(trim(vPracticeRec."Phone")) ||'"/>');

    	-- AX-18945.19094e

		ELSE

			-- no phone number

			dbms_lob_s.append(FileContent, '

				<telecom use="WP" nullFlavor="UNK"/>');

		END IF;



	-- E143263.3

	IF NOT true THEN																		--E143263.4 always show

			dbms_lob_s.append(FileContent, '

			 <addr nullFlavor="UNK"/>');

	ELSE



			 dbms_lob_s.append(FileContent, '

			  <addr use="WP">');



			  IF NOT (trim(vPracticeRec."Address1") IS NULL OR length(trim(vPracticeRec."Address1")) = 0) THEN

				  dbms_lob_s.append(FileContent, '

			  <streetAddressLine>' ||  htf.escape_sc(trim(vPracticeRec."Address1")) || '</streetAddressLine>');

			 	-- AX-18945.19094e

				ELSE

					-- no street address entered

					dbms_lob_s.append(FileContent, '

						<streetAddressLine nullFlavor="UNK"/>');

				END IF;



			  IF NOT (trim(vPracticeRec."Address2") IS NULL OR length(trim(vPracticeRec."Address2")) = 0) THEN

				  dbms_lob_s.append(FileContent, '

			  <streetAddressLine>' ||  htf.escape_sc(trim(vPracticeRec."Address2")) || '</streetAddressLine>');

			  END IF;





			  IF NOT (trim(vPracticeRec."City") IS NULL OR length(trim(vPracticeRec."City")) = 0) THEN

				  dbms_lob_s.append(FileContent, '

			  <city>' ||  htf.escape_sc(trim(vPracticeRec."City")) || '</city>');

			  -- AX-18945.19094e

				ELSE

					-- patient city unknown

					dbms_lob_s.append(FileContent, '

					<city nullFlavor="UNK"/>');

				END IF;

				

			  IF NOT (trim(vPracticeRec."Province") IS NULL OR length(trim(vPracticeRec."Province")) = 0) THEN

				  dbms_lob_s.append(FileContent, '

			  <state>' ||  htf.escape_sc(trim(vPracticeRec."Province")) || '</state>');

			 -- AX-18945.19094e

				ELSE

				--state unknown

				dbms_lob_s.append(FileContent, '

				<state nullFlavor="UNK"/>');

				END IF;





			  IF NOT (trim(vPracticeRec."Postal") IS NULL OR length(trim(vPracticeRec."Postal")) = 0) THEN

				  dbms_lob_s.append(FileContent, '

			  <postalCode>' ||  htf.escape_sc(trim(vPracticeRec."Postal")) || '</postalCode>');

			  -- AX-18945.19094e

				ELSE

				dbms_lob_s.append(FileContent, '

				<postalCode nullFlavor="UNK"/>');

				END IF;





			  dbms_lob_s.append(FileContent, '

			  <country>' || 'US' || '</country>');



			  dbms_lob_s.append(FileContent, '

			  </addr>');



	END IF;



    dbms_lob_s.append(FileContent, '

    </representedCustodianOrganization>

  </assignedCustodian>

  </custodian>');



  -- AX-18696.19084

   dbms_lob_s.append(FileContent, '

  <legalAuthenticator>

	  <time value="' || TO_CHAR(SYSDATE, 'YYYYMMDD') || '"/>

	  <signatureCode code="S"/>

	  <assignedEntity>');

  dbms_lob_s.append(FileContent, '

    <id root="'|| CCDA_CFG_PKG.GetUserIdentifierType ||'" extension="' ||

						NVL(CCDA_CFG_PKG.GetUserIdentifier(vUserId), 'UNK') ||'"/>');



	dbms_lob_s.append(FileContent, '

		<addr use="WP">');



	IF NOT (trim(vPracticeRec."Address1") IS NULL OR length(trim(vPracticeRec."Address1")) = 0) THEN

		dbms_lob_s.append(FileContent, '

			<streetAddressLine>' ||  htf.escape_sc(trim(vPracticeRec."Address1")) || '</streetAddressLine>');

	ELSE

		dbms_lob_s.append(FileContent, '

			<streetAddressLine nullFlavor="UNK"/>');

	END IF;



	IF NOT (trim(vPracticeRec."Address2") IS NULL OR length(trim(vPracticeRec."Address2")) = 0) THEN

		dbms_lob_s.append(FileContent, '

			<streetAddressLine>' ||  htf.escape_sc(trim(vPracticeRec."Address2")) || '</streetAddressLine>');

	END IF;



	IF NOT (trim(vPracticeRec."City") IS NULL OR length(trim(vPracticeRec."City")) = 0) THEN

		dbms_lob_s.append(FileContent, '

			<city>' ||  htf.escape_sc(trim(vPracticeRec."City")) || '</city>');

	ELSE

		dbms_lob_s.append(FileContent, '

			<city nullFlavor="UNK"/>');

	END IF;



	IF NOT (trim(vPracticeRec."Province") IS NULL OR length(trim(vPracticeRec."Province")) = 0) THEN

		dbms_lob_s.append(FileContent, '

			<state>' ||  htf.escape_sc(trim(vPracticeRec."Province")) || '</state>');

	ELSE

		dbms_lob_s.append(FileContent, '

			<state nullFlavor="UNK"/>');

	END IF;



	IF NOT (trim(vPracticeRec."Postal") IS NULL OR length(trim(vPracticeRec."Postal")) = 0) THEN

		dbms_lob_s.append(FileContent, '

			<postalCode>' ||  htf.escape_sc(trim(vPracticeRec."Postal")) || '</postalCode>');

	ELSE

		dbms_lob_s.append(FileContent, '

			<postalCode nullFlavor="UNK"/>');

	END IF;



	dbms_lob_s.append(FileContent, '

			<country>' || 'US' || '</country>');

	dbms_lob_s.append(FileContent, '

		</addr>');



	IF NOT (TRIM(vPracticeRec."Phone") IS NULL OR length(TRIM(vPracticeRec."Phone")) = 0) THEN

		dbms_lob_s.append(FileContent, '

			<telecom use="WP" value="');



		IF NOT (TRIM(vPracticeRec."Area") IS NULL OR length(TRIM(vPracticeRec."Area")) = 0) THEN

			dbms_lob_s.append(FileContent,  htf.escape_sc(TRIM(vPracticeRec."Area")) || '-');

		END IF;



		dbms_lob_s.append(FileContent,  htf.escape_sc(TRIM(vPracticeRec."Phone")) ||'"/>');

	ELSE

		dbms_lob_s.append(FileContent, '

			<telecom use="WP" nullFlavor="UNK"/>');

	END IF;



	dbms_lob_s.append(FileContent, '

			<assignedPerson>

				<name>

					<given>' || htf.escape_sc(trim(vUserFirst)) || '</given>

					<family>' || htf.escape_sc(trim(vUserLast)) || '</family>

				</name>

			</assignedPerson>

		</assignedEntity>

	</legalAuthenticator>');



  RETURN FileContent;

END;



	-- Transition of Care Summary

	-- AX-18945.19094 - added new date/time range params...

	-- AX-21837 - added param for sections to display and their order...

	FUNCTION ccdatocsummary(patientid numeric, practiceid numeric, userid numeric, sections character varying DEFAULT 'ALL'::character varying, isdatefrom numeric DEFAULT 0, date1 timestamp without time zone DEFAULT NULL::timestamp without time zone, date2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob IS



		FileContent CLOB;



		vUserFirst USER_VIEW."First"%TYPE;

		vUserLast USER_VIEW."Last"%TYPE;

		vPUser NUMBER := 0;



		-- cursor of assigned primary providers -- AX-10463

		CURSOR curAssignedPrimary IS

			SELECT

				P."FirstName",

				P."LastName",

				P."NPI",

				U."Address1",

				U."Address2",

				U."City",

				U."Province",

				U."Postal",

				U."AltArea",

				U."AltPhone"

			FROM PTPROD PP, PRODUCER P, USERS U

			WHERE 1=1

				AND PP."Patient" = PatientId

				AND PP."Deleted" = 0

				AND PP."StartDate" <= TRUNC(SYSDATE)

				AND PP."EndDate" >= TRUNC(SYSDATE)

				AND PP."IsPrimary" = 1

				AND PP."Producer" = P."Producer"

				AND U."User" = (SELECT U2."User" FROM USERS U2 WHERE U2."Producer" = P."Producer" AND U."Deleted" = 0 AND U2."First" = P."FirstName" AND U2."Name" = P."LastName" AND ROWNUM=1)

			ORDER BY PP."StartDate";



		vHasPrimary NUMBER := 0;



		-- cursor of non-primary assigned providers -- AX-10463

		CURSOR curAssignedNonPrimary IS

			SELECT

				P."FirstName",

				P."LastName",

				P."NPI",

				U."Address1",

				U."Address2",

				U."City",

				U."Province",

				U."Postal",

				U."AltArea",

				U."AltPhone"

			FROM PTPROD PP, PRODUCER P, USERS U

			WHERE 1=1

				AND PP."Patient" = PatientId

				AND PP."Deleted" = 0

				AND PP."StartDate" <= TRUNC(SYSDATE)

				AND PP."EndDate" >= TRUNC(SYSDATE)

				AND PP."IsPrimary" = 0

				AND PP."Producer" = P."Producer"

				AND U."User" = (SELECT U2."User" FROM USERS U2 WHERE U2."Producer" = P."Producer" AND U."Deleted" = 0 AND U2."First" = P."FirstName" AND U2."Name" = P."LastName" AND ROWNUM=1)

			ORDER BY PP."StartDate";



		-- practice contact info

		vPracticeName PRACTICE."Name"%TYPE := NULL;

		vPracticeAddr1 PRACTICE."Address1"%TYPE := NULL;

		vPracticeAddr2 PRACTICE."Address2"%TYPE := NULL;

		vPracticeCity PRACTICE."City"%TYPE := NULL;

		vPracticeState PRACTICE."Province"%TYPE := NULL;

		vPracticeZIP PRACTICE."Postal"%TYPE := NULL;

		vPracticeArea PRACTICE."Area"%TYPE := NULL;

		vPracticePhone PRACTICE."Phone"%TYPE := NULL;





	BEGIN

		-- get the info for the practice

		BEGIN

			SELECT

				TRIM(P."Name"),

				P."Address1",

				P."Address2",

				P."City",

				P."Province",

				P."Postal",

				TRIM(P."Area"),

				TRIM(P."Phone")

			INTO vPracticeName, vPracticeAddr1, vPracticeAddr2, vPracticeCity, vPracticeState, vPracticeZIP, vPracticeArea, vPracticePhone

			FROM PRACTICE P

			WHERE 1=1

                AND CASE PracticeId WHEN 0 THEN 0 ELSE P."Id" END = PracticeId

				AND ROWNUM = 1;

		END;



		dbms_lob_s.createtemporary (FileContent, TRUE);



		IF UserId = 0 THEN

			-- When called from MU API

			BEGIN

				SELECT u."User" INTO vPUser 

				FROM ptprod pt

					inner join users u on pt."Producer" = u."Producer"

				WHERE pt."Patient" = PatientId

					AND ((pt."IsPrimary" = 1) OR (pt."EndDate" > sysdate) OR (pt."EndDate" < sysdate) OR (1=1)) AND pt."Deleted" = 0

				ORDER BY pt."IsPrimary" DESC, pt."EndDate" DESC

				FETCH FIRST 1 ROW ONLY; 

			EXCEPTION

				WHEN NO_DATA_FOUND THEN

				vPUser := 0;

			END;    

		 

			IF vPUser IS NULL OR vPUser = 0 THEN

				SELECT "User" INTO vPUser FROM Users

				WHERE "Deleted" = 0

				FETCH FIRST 1 ROW ONLY;   

			END IF;



			SELECT "Last", "First" INTO vUserLast, vUserFirst 

			FROM USER_VIEW WHERE "User" = vPUser AND "Deleted" = 0;

		ELSE

			SELECT "Last", "First" INTO vUserLast, vUserFirst FROM USER_VIEW WHERE "User" = UserId;

		END IF;



		dbms_lob_s.append(FileContent,GetCCDAHeader(PatientId, PracticeId, UserId, 'Transition of Care Summary'));



		dbms_lob_s.append(FileContent, '

			<documentationOf typeCode="DOC">

				<serviceEvent classCode="PCPR" moodCode="EVN">

					 <effectiveTime>

						<low value="' || TO_CHAR(SYSDATE, 'YYYYMMDDHH24MI') || '"/>

						<high value="' || TO_CHAR(SYSDATE, 'YYYYMMDDHH24MI') || '"/>

					</effectiveTime>');



		-- primary provider -- AX-10463

		FOR cPProv IN curAssignedPrimary LOOP



			dbms_lob_s.append(FileContent, '

				<performer typeCode="PRF">

				  <templateId root="2.16.840.1.113883.3.88.11.83.4" />

				  <templateId root="1.3.6.1.4.1.19376.1.5.3.1.2.3" />

				  <functionCode code="PP" displayName="Primary Care Provider" codeSystem="2.16.840.1.113883.12.443" codeSystemName="Provider Role" />

				  <time nullFlavor="UNK">

					<low nullFlavor="UNK" />

					<high nullFlavor="UNK" />

				  </time>

				  <assignedEntity>

					<id root="2.16.840.1.113883.4.6" extension="UNK" />

					<addr>

						<streetAddressLine>' || htf.escape_sc(cPProv."Address1") || '</streetAddressLine>');



			IF NOT (TRIM(cPProv."Address2") IS NULL OR length(TRIM(cPProv."Address2")) = 0) THEN

				dbms_lob_s.append(FileContent, '

						<streetAddressLine>' || htf.escape_sc(cPProv."Address2") || '</streetAddressLine>');

			END IF;



			-- AX-18945.19094e

				IF NOT (trim(cPProv."City") IS NULL OR length(trim(cPProv."City")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<city>' ||  htf.escape_sc(trim(cPProv."City")) || '</city>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<city nullFlavor="UNK"/>');

				END IF;



				IF NOT (trim(cPProv."Province") IS NULL OR length(trim(cPProv."Province")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<state>' ||  htf.escape_sc(trim(cPProv."Province")) || '</state>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<state nullFlavor="UNK"/>');

				END IF;



				IF NOT (trim(cPProv."Postal") IS NULL OR length(trim(cPProv."Postal")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<postalCode>' ||  htf.escape_sc(trim(cPProv."Postal")) || '</postalCode>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<postalCode nullFlavor="UNK"/>');

				END IF;





			dbms_lob_s.append(FileContent, '

						<country>US</country>

					</addr>

					<telecom use="WP" value="' || TRIM(cPProv."AltArea") || '-' || TRIM(cPProv."AltPhone") || '"/>

					<assignedPerson classCode="PSN" determinerCode="INSTANCE">');



			IF cPProv."FirstName" IS NOT NULL THEN

				dbms_lob_s.append(FileContent, '

					  <name>

						<given>' || htf.escape_sc(trim(cPProv."FirstName")) || '</given>

						<family>' || htf.escape_sc(trim(cPProv."LastName")) || '</family>

					  </name>');



			ELSE

				dbms_lob_s.append(FileContent, '

					  <name nullFlavor="UNK" />');



			END IF;



			dbms_lob_s.append(FileContent, '

					</assignedPerson>

				    </assignedEntity>

				</performer>');



			vHasPrimary := 1;

		END LOOP;



		-- handle case where have no primary provider

		IF vHasPrimary = 0 THEN

			dbms_lob_s.append(FileContent, '

				<performer typeCode="PRF">

					  <templateId root="2.16.840.1.113883.3.88.11.83.4" />

					  <templateId root="1.3.6.1.4.1.19376.1.5.3.1.2.3" />

					  <functionCode code="PP" displayName="Primary Care Provider" codeSystem="2.16.840.1.113883.12.443" codeSystemName="Provider Role" />

					  <time nullFlavor="UNK">

						<low nullFlavor="UNK" />

						<high nullFlavor="UNK" />

					  </time>

					  <assignedEntity>

						<id root="2.16.840.1.113883.4.6" extension="UNK" />

						<addr nullFlavor="UNK" />

						<telecom use="WP" nullFlavor="UNK" />

						<assignedPerson classCode="PSN" determinerCode="INSTANCE">

						  <name nullFlavor="UNK" />

						</assignedPerson>

					  </assignedEntity>

				</performer>');

		END IF;



		-- nonprimary assigned providers -- AX-10463

		FOR cProv IN curAssignedNonPrimary LOOP



			dbms_lob_s.append(FileContent, '

					<performer typeCode="PRF">

						<templateId root="2.16.840.1.113883.3.88.11.83.4" />

						<templateId root="1.3.6.1.4.1.19376.1.5.3.1.2.3" />

						<assignedEntity>

							<id root="2.16.840.1.113883.4.6" extension="UNK" />

							<code code="-1" displayName="PCP" codeSystemName="GMTDynamic" />

							<addr>

								<streetAddressLine>' || htf.escape_sc(cProv."Address1") || '</streetAddressLine>');



			IF NOT (TRIM(cProv."Address2") IS NULL OR length(TRIM(cProv."Address2")) = 0) THEN

				dbms_lob_s.append(FileContent, '

						<streetAddressLine>' || htf.escape_sc(cProv."Address2") || '</streetAddressLine>');

			END IF;



						-- AX-18945.19094e

				IF NOT (trim(cProv."City") IS NULL OR length(trim(cProv."City")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<city>' ||  htf.escape_sc(trim(cProv."City")) || '</city>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<city nullFlavor="UNK"/>');

				END IF;



				IF NOT (trim(cProv."Province") IS NULL OR length(trim(cProv."Province")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<state>' ||  htf.escape_sc(trim(cProv."Province")) || '</state>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<state nullFlavor="UNK"/>');

				END IF;



				IF NOT (trim(cProv."Postal") IS NULL OR length(trim(cProv."Postal")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<postalCode>' ||  htf.escape_sc(trim(cProv."Postal")) || '</postalCode>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<postalCode nullFlavor="UNK"/>');

				END IF;



			dbms_lob_s.append(FileContent, '



								<country>US</country>

							</addr>

							<telecom use="WP" value="' || TRIM(cProv."AltArea") || '-' || TRIM(cProv."AltPhone") || '"/>

							<assignedPerson classCode="PSN" determinerCode="INSTANCE">

								<name>

									<given>' || htf.escape_sc(trim(cProv."FirstName")) || '</given>

									<family>' || htf.escape_sc(trim(cProv."LastName")) || '</family>

								</name>

							</assignedPerson>

						</assignedEntity>

					</performer>');

		END LOOP;



		-- section footer

		dbms_lob_s.append(FileContent, '

				</serviceEvent>

			</documentationOf>');



		dbms_lob_s.append(FileContent, '

			<component>

			<structuredBody>');





		-- AX-21837

		IF Sections = 'ALL' THEN



			-- AX-18945.19095 - adding new params...			

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetMedicalEquipmentSection(PatientId, true, IsDateFrom, Date1, Date2)); --	AX-21118

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetImmunizationSection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetReasonForReferralSection(PatientId, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetProblemSection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetSocialHistorySection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetMedicationSection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetAllergiesSection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetPlanOfCareSection(PatientId, true, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetTreatmentPlanSection(PatientId, true, IsDateFrom, Date1, Date2));	-- AX-26388	

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetProcedureSection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetCognitiveStatusSection(PatientId, true, IsDateFrom, Date1, Date2));	-- AX-21879f

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetFunctionalStatusSection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetVitalSignsSection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetResultsSection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetEncountersSection(PatientId, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetGoalsSection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetHealthConcernsSection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetClinicalNotesSection(PatientId, true, IsDateFrom, Date1, Date2));	-- AX-26344	



		ELSE



			-- loop through Sections and add appropriate....

			   FOR Section IN (select regexp_substr (Sections, '[^,]+',1, rownum) Txt from dual 

								connect by level <= regexp_count (Sections, '[^,]+'))

			   LOOP

					IF Section.Txt = '1' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetMedicalEquipmentSection(PatientId, true, IsDateFrom, Date1, Date2)); 

					ELSIF Section.Txt = '2' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetImmunizationSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '3' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetReasonForReferralSection(PatientId, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '4' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetProblemSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '5' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetSocialHistorySection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '6' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetMedicationSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '7' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetAllergiesSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '8' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetPlanOfCareSection(PatientId, true, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '9' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetTreatmentPlanSection(PatientId, true, IsDateFrom, Date1, Date2));	-- AX-26388

					ELSIF Section.Txt = '10' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetProcedureSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '11' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetCognitiveStatusSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '12' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetFunctionalStatusSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '13' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetVitalSignsSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '14' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetResultsSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '15' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetEncountersSection(PatientId, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '16' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetGoalsSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '17' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetHealthConcernsSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '18' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetClinicalNotesSection(PatientId, true, IsDateFrom, Date1, Date2)); -- AX-26344

					END IF;

				  

			   END LOOP;



		END IF;

		

		dbms_lob_s.append(FileContent, '

			</structuredBody>

			</component>');



		dbms_lob_s.append(FileContent, '

			</ClinicalDocument>');



		return FileContent;

	END;



    -- MU3 Api

	FUNCTION ccdatocsecsummary(patientid numeric, practiceid numeric, userid numeric, isdatefrom numeric DEFAULT 0, date1 timestamp without time zone DEFAULT NULL::timestamp without time zone, date2 timestamp without time zone DEFAULT NULL::timestamp without time zone, sections character varying DEFAULT NULL::character varying) RETURN clob IS



		FileContent CLOB;



		vUserFirst USER_VIEW."First"%TYPE;

		vUserLast USER_VIEW."Last"%TYPE;

		vPUser NUMBER := 0;



		-- cursor of assigned primary providers -- AX-10463

		CURSOR curAssignedPrimary IS

			SELECT

				P."FirstName",

				P."LastName",

				P."NPI",

				U."Address1",

				U."Address2",

				U."City",

				U."Province",

				U."Postal",

				U."AltArea",

				U."AltPhone"

			FROM PTPROD PP, PRODUCER P, USERS U

			WHERE 1=1

				AND PP."Patient" = PatientId

				AND PP."Deleted" = 0

				AND PP."StartDate" <= TRUNC(SYSDATE)

				AND PP."EndDate" >= TRUNC(SYSDATE)

				AND PP."IsPrimary" = 1

				AND PP."Producer" = P."Producer"

				AND U."User" = (SELECT U2."User" FROM USERS U2 WHERE U2."Producer" = P."Producer" AND U."Deleted" = 0 AND U2."First" = P."FirstName" AND U2."Name" = P."LastName" AND ROWNUM=1)

			ORDER BY PP."StartDate";



		vHasPrimary NUMBER := 0;



		-- cursor of non-primary assigned providers -- AX-10463

		CURSOR curAssignedNonPrimary IS

			SELECT

				P."FirstName",

				P."LastName",

				P."NPI",

				U."Address1",

				U."Address2",

				U."City",

				U."Province",

				U."Postal",

				U."AltArea",

				U."AltPhone"

			FROM PTPROD PP, PRODUCER P, USERS U

			WHERE 1=1

				AND PP."Patient" = PatientId

				AND PP."Deleted" = 0

				AND PP."StartDate" <= TRUNC(SYSDATE)

				AND PP."EndDate" >= TRUNC(SYSDATE)

				AND PP."IsPrimary" = 0

				AND PP."Producer" = P."Producer"

				AND U."User" = (SELECT U2."User" FROM USERS U2 WHERE U2."Producer" = P."Producer" AND U."Deleted" = 0 AND U2."First" = P."FirstName" AND U2."Name" = P."LastName" AND ROWNUM=1)

			ORDER BY PP."StartDate";



		-- practice contact info

		vPracticeName PRACTICE."Name"%TYPE := NULL;

		vPracticeAddr1 PRACTICE."Address1"%TYPE := NULL;

		vPracticeAddr2 PRACTICE."Address2"%TYPE := NULL;

		vPracticeCity PRACTICE."City"%TYPE := NULL;

		vPracticeState PRACTICE."Province"%TYPE := NULL;

		vPracticeZIP PRACTICE."Postal"%TYPE := NULL;

		vPracticeArea PRACTICE."Area"%TYPE := NULL;

		vPracticePhone PRACTICE."Phone"%TYPE := NULL;





	BEGIN

		-- get the info for the practice

		BEGIN

			SELECT

				TRIM(P."Name"),

				P."Address1",

				P."Address2",

				P."City",

				P."Province",

				P."Postal",

				TRIM(P."Area"),

				TRIM(P."Phone")

			INTO vPracticeName, vPracticeAddr1, vPracticeAddr2, vPracticeCity, vPracticeState, vPracticeZIP, vPracticeArea, vPracticePhone

			FROM PRACTICE P

			WHERE 1=1

                AND CASE PracticeId WHEN 0 THEN 0 ELSE P."Id" END = PracticeId

				AND ROWNUM = 1;

		END;



		dbms_lob_s.createtemporary (FileContent, TRUE);



		IF UserId = 0 THEN

			-- When called from MU API

			BEGIN

				SELECT u."User" INTO vPUser 

				FROM ptprod pt

					inner join users u on pt."Producer" = u."Producer"

				WHERE pt."Patient" = PatientId

					AND ((pt."IsPrimary" = 1) OR (pt."EndDate" > sysdate) OR (pt."EndDate" < sysdate) OR (1=1)) AND pt."Deleted" = 0

				ORDER BY pt."IsPrimary" DESC, pt."EndDate" DESC

				FETCH FIRST 1 ROW ONLY; 

			EXCEPTION

				WHEN NO_DATA_FOUND THEN

				vPUser := 0;

			END;           

		  

			IF vPUser IS NULL OR vPUser = 0 THEN

				SELECT "User" INTO vPUser FROM Users 

				WHERE "Deleted" = 0

				FETCH FIRST 1 ROW ONLY;   

			END IF;



			SELECT "Last", "First" INTO vUserLast, vUserFirst 

			FROM USER_VIEW WHERE "User" = vPUser AND "Deleted" = 0;

		ELSE

			SELECT "Last", "First" INTO vUserLast, vUserFirst FROM USER_VIEW WHERE "User" = UserId;

		END IF;



		dbms_lob_s.append(FileContent,GetCCDAHeader(PatientId, PracticeId, UserId, 'Transition of Care Summary'));



		dbms_lob_s.append(FileContent, '

			<documentationOf typeCode="DOC">

				<serviceEvent classCode="PCPR" moodCode="EVN">

					 <effectiveTime>

						<low value="' || TO_CHAR(SYSDATE, 'YYYYMMDDHH24MI') || '"/>

						<high value="' || TO_CHAR(SYSDATE, 'YYYYMMDDHH24MI') || '"/>

					</effectiveTime>');



		-- primary provider -- AX-10463

		FOR cPProv IN curAssignedPrimary LOOP



			dbms_lob_s.append(FileContent, '

				<performer typeCode="PRF">

				  <templateId root="2.16.840.1.113883.3.88.11.83.4" />

				  <templateId root="1.3.6.1.4.1.19376.1.5.3.1.2.3" />

				  <functionCode code="PP" displayName="Primary Care Provider" codeSystem="2.16.840.1.113883.12.443" codeSystemName="Provider Role" />

				  <time nullFlavor="UNK">

					<low nullFlavor="UNK" />

					<high nullFlavor="UNK" />

				  </time>

				  <assignedEntity>

					<id root="2.16.840.1.113883.4.6" extension="UNK" />

					<addr>

						<streetAddressLine>' || htf.escape_sc(cPProv."Address1") || '</streetAddressLine>');



			IF NOT (TRIM(cPProv."Address2") IS NULL OR length(TRIM(cPProv."Address2")) = 0) THEN

				dbms_lob_s.append(FileContent, '

						<streetAddressLine>' || htf.escape_sc(cPProv."Address2") || '</streetAddressLine>');

			END IF;



			-- AX-18945.19094e

				IF NOT (trim(cPProv."City") IS NULL OR length(trim(cPProv."City")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<city>' ||  htf.escape_sc(trim(cPProv."City")) || '</city>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<city nullFlavor="UNK"/>');

				END IF;



				IF NOT (trim(cPProv."Province") IS NULL OR length(trim(cPProv."Province")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<state>' ||  htf.escape_sc(trim(cPProv."Province")) || '</state>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<state nullFlavor="UNK"/>');

				END IF;



				IF NOT (trim(cPProv."Postal") IS NULL OR length(trim(cPProv."Postal")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<postalCode>' ||  htf.escape_sc(trim(cPProv."Postal")) || '</postalCode>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<postalCode nullFlavor="UNK"/>');

				END IF;





			dbms_lob_s.append(FileContent, '

						<country>US</country>

					</addr>

					<telecom use="WP" value="' || TRIM(cPProv."AltArea") || '-' || TRIM(cPProv."AltPhone") || '"/>

					<assignedPerson classCode="PSN" determinerCode="INSTANCE">');



			IF cPProv."FirstName" IS NOT NULL THEN

				dbms_lob_s.append(FileContent, '

					  <name>

						<given>' || htf.escape_sc(trim(cPProv."FirstName")) || '</given>

						<family>' || htf.escape_sc(trim(cPProv."LastName")) || '</family>

					  </name>');



			ELSE

				dbms_lob_s.append(FileContent, '

					  <name nullFlavor="UNK" />');



			END IF;



			dbms_lob_s.append(FileContent, '

					</assignedPerson>

				    </assignedEntity>

				</performer>');



			vHasPrimary := 1;

		END LOOP;



		-- handle case where have no primary provider

		IF vHasPrimary = 0 THEN

			dbms_lob_s.append(FileContent, '

				<performer typeCode="PRF">

					  <templateId root="2.16.840.1.113883.3.88.11.83.4" />

					  <templateId root="1.3.6.1.4.1.19376.1.5.3.1.2.3" />

					  <functionCode code="PP" displayName="Primary Care Provider" codeSystem="2.16.840.1.113883.12.443" codeSystemName="Provider Role" />

					  <time nullFlavor="UNK">

						<low nullFlavor="UNK" />

						<high nullFlavor="UNK" />

					  </time>

					  <assignedEntity>

						<id root="2.16.840.1.113883.4.6" extension="UNK" />

						<addr nullFlavor="UNK" />

						<telecom use="WP" nullFlavor="UNK" />

						<assignedPerson classCode="PSN" determinerCode="INSTANCE">

						  <name nullFlavor="UNK" />

						</assignedPerson>

					  </assignedEntity>

				</performer>');

		END IF;



		-- nonprimary assigned providers -- AX-10463

		FOR cProv IN curAssignedNonPrimary LOOP



			dbms_lob_s.append(FileContent, '

					<performer typeCode="PRF">

						<templateId root="2.16.840.1.113883.3.88.11.83.4" />

						<templateId root="1.3.6.1.4.1.19376.1.5.3.1.2.3" />

						<assignedEntity>

							<id root="2.16.840.1.113883.4.6" extension="UNK" />

							<code code="-1" displayName="PCP" codeSystemName="GMTDynamic" />

							<addr>

								<streetAddressLine>' || htf.escape_sc(cProv."Address1") || '</streetAddressLine>');



			IF NOT (TRIM(cProv."Address2") IS NULL OR length(TRIM(cProv."Address2")) = 0) THEN

				dbms_lob_s.append(FileContent, '

						<streetAddressLine>' || htf.escape_sc(cProv."Address2") || '</streetAddressLine>');

			END IF;



						-- AX-18945.19094e

				IF NOT (trim(cProv."City") IS NULL OR length(trim(cProv."City")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<city>' ||  htf.escape_sc(trim(cProv."City")) || '</city>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<city nullFlavor="UNK"/>');

				END IF;



				IF NOT (trim(cProv."Province") IS NULL OR length(trim(cProv."Province")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<state>' ||  htf.escape_sc(trim(cProv."Province")) || '</state>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<state nullFlavor="UNK"/>');

				END IF;



				IF NOT (trim(cProv."Postal") IS NULL OR length(trim(cProv."Postal")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<postalCode>' ||  htf.escape_sc(trim(cProv."Postal")) || '</postalCode>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<postalCode nullFlavor="UNK"/>');

				END IF;



			dbms_lob_s.append(FileContent, '



								<country>US</country>

							</addr>

							<telecom use="WP" value="' || TRIM(cProv."AltArea") || '-' || TRIM(cProv."AltPhone") || '"/>

							<assignedPerson classCode="PSN" determinerCode="INSTANCE">

								<name>

									<given>' || htf.escape_sc(trim(cProv."FirstName")) || '</given>

									<family>' || htf.escape_sc(trim(cProv."LastName")) || '</family>

								</name>

							</assignedPerson>

						</assignedEntity>

					</performer>');

		END LOOP;



		-- section footer

		dbms_lob_s.append(FileContent, '

				</serviceEvent>

			</documentationOf>');



		dbms_lob_s.append(FileContent, '

			<component>

			<structuredBody>');



		-- AX-18945.19095 - adding new params...			

		IF INSTR(Sections, 'DEMOGRAPHICS') = 0 THEN

			IF INSTR(REPLACE(Sections,'''',','), ',' || 'MEDICALEQUIPMENT' || ',') > 0 THEN

			   dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetMedicalEquipmentSection(PatientId, true, IsDateFrom, Date1, Date2));

			END IF;        

			IF INSTR(REPLACE(Sections,'''',','), ',' || 'IMMUNIZATIONS' || ',') > 0 THEN

			   dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetImmunizationSection(PatientId, true, IsDateFrom, Date1, Date2));

			END IF;        

			IF INSTR(REPLACE(Sections,'''',','), ',' || 'PROBLEMS' || ',') > 0 THEN

			   dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetProblemSection(PatientId, true, IsDateFrom, Date1, Date2));

			END IF;        

			IF INSTR(REPLACE(Sections,'''',','), ',' || 'SOCIALHISTORY' || ',') > 0 THEN

			   dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetSocialHistorySection(PatientId, true, IsDateFrom, Date1, Date2));

			END IF;        

			IF INSTR(REPLACE(Sections,'''',','), ',' || 'MEDICATIONS' || ',') > 0 THEN

			   dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetMedicationSection(PatientId, true, IsDateFrom, Date1, Date2));

			END IF;        

			IF INSTR(REPLACE(Sections,'''',','), ',' || 'ALLERGIES' || ',') > 0 THEN

			   dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetAllergiesSection(PatientId, true, IsDateFrom, Date1, Date2));

			END IF;        

			IF INSTR(REPLACE(Sections,'''',','), ',' || 'ASSESSMENTPLAN' || ',') > 0 THEN

			   dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetPlanOfCareSection(PatientId, true, true, IsDateFrom, Date1, Date2));

			END IF;        

			IF INSTR(REPLACE(Sections,'''',','), ',' || 'PROCEDURES' || ',') > 0 THEN

			   dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetProcedureSection(PatientId, true, IsDateFrom, Date1, Date2));

			END IF;        

			IF INSTR(REPLACE(Sections,'''',','), ',' || 'VITALSIGNS' || ',') > 0 THEN

			   dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetVitalSignsSection(PatientId, true, IsDateFrom, Date1, Date2));

			END IF;        

			IF INSTR(REPLACE(Sections,'''',','), ',' || 'RESULTS' || ',') > 0 THEN

			   dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetResultsSection(PatientId, true, IsDateFrom, Date1, Date2));

			END IF;   

			IF INSTR(REPLACE(Sections,'''',','), ',' || 'FUNCTIONALSTATUS' || ',') > 0 THEN

			   dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetFunctionalStatusSection(PatientId, true, IsDateFrom, Date1, Date2));

			END IF;    

			IF INSTR(REPLACE(Sections,'''',','), ',' || 'COGNITIVESTATUS' || ',') > 0 THEN

			   dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetCognitiveStatusSection(PatientId, true, IsDateFrom, Date1, Date2)); -- AX-21879f

			END IF;      

			IF INSTR(REPLACE(Sections,'''',','), ',' || 'ENCOUNTER' || ',') > 0 THEN

			   dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetEncountersSection(PatientId, IsDateFrom, Date1, Date2));

			END IF;		

			IF INSTR(REPLACE(Sections,'''',','), ',' || 'GOALS' || ',') > 0 THEN

			   dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetGoalsSection(PatientId, true, IsDateFrom, Date1, Date2));

			END IF;

			IF INSTR(REPLACE(Sections,'''',','), ',' || 'HEALTHCONCERNS' || ',') > 0 THEN

			   dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetHealthConcernsSection(PatientId, true, IsDateFrom, Date1, Date2));

			END IF;      

			-- AX-26344

			IF INSTR(REPLACE(Sections,'''',','), ',' || 'CLINICALNOTES' || ',') > 0 THEN

			   dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetClinicalNotesSection(PatientId, true, IsDateFrom, Date1, Date2));

			END IF;     

		END IF;		

		

		dbms_lob_s.append(FileContent, '

			</structuredBody>

			</component>');



		dbms_lob_s.append(FileContent, '

			</ClinicalDocument>');



		return FileContent;

	END;

	



  	-- Export Summary

	-- AX-18945.19094 - added new date/time range params...

	FUNCTION ccdaexportsummary(patientid numeric, practiceid numeric, userid numeric, sections character varying DEFAULT 'ALL'::character varying, isdatefrom numeric DEFAULT 0, date1 timestamp without time zone DEFAULT NULL::timestamp without time zone, date2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob IS



		FileContent CLOB;



		vUserFirst USER_VIEW."First"%TYPE;

		vUserLast USER_VIEW."Last"%TYPE;



-- cursor of assigned primary providers -- AX-10463

		CURSOR curAssignedPrimary IS

			SELECT

				P."FirstName",

				P."LastName",

				P."NPI",

				U."Address1",

				U."Address2",

				U."City",

				U."Province",

				U."Postal",

				U."AltArea",

				U."AltPhone"

			FROM PTPROD PP, PRODUCER P, USERS U

			WHERE 1=1

				AND PP."Patient" = PatientId

				AND PP."Deleted" = 0

				AND PP."StartDate" <= TRUNC(SYSDATE)

				AND PP."EndDate" >= TRUNC(SYSDATE)

				AND PP."IsPrimary" = 1

				AND PP."Producer" = P."Producer"

				AND U."User" = (SELECT U2."User" FROM USERS U2 WHERE U2."Producer" = P."Producer" AND U."Deleted" = 0 AND U2."First" = P."FirstName" AND U2."Name" = P."LastName" AND ROWNUM=1)

			ORDER BY PP."StartDate";



		vHasPrimary NUMBER := 0;



		-- cursor of non-primary assigned providers -- AX-10463

		CURSOR curAssignedNonPrimary IS

			SELECT

				P."FirstName",

				P."LastName",

				P."NPI",

				U."Address1",

				U."Address2",

				U."City",

				U."Province",

				U."Postal",

				U."AltArea",

				U."AltPhone"

			FROM PTPROD PP, PRODUCER P, USERS U

			WHERE 1=1

				AND PP."Patient" = PatientId

				AND PP."Deleted" = 0

				AND PP."StartDate" <= TRUNC(SYSDATE)

				AND PP."EndDate" >= TRUNC(SYSDATE)

				AND PP."IsPrimary" = 0

				AND PP."Producer" = P."Producer"

				AND U."User" = (SELECT U2."User" FROM USERS U2 WHERE U2."Producer" = P."Producer" AND U."Deleted" = 0 AND U2."First" = P."FirstName" AND U2."Name" = P."LastName" AND ROWNUM=1)

			ORDER BY PP."StartDate";



		-- practice contact info

		vPracticeName PRACTICE."Name"%TYPE := NULL;

		vPracticeAddr1 PRACTICE."Address1"%TYPE := NULL;

		vPracticeAddr2 PRACTICE."Address2"%TYPE := NULL;

		vPracticeCity PRACTICE."City"%TYPE := NULL;

		vPracticeState PRACTICE."Province"%TYPE := NULL;

		vPracticeZIP PRACTICE."Postal"%TYPE := NULL;

		vPracticeArea PRACTICE."Area"%TYPE := NULL;

		vPracticePhone PRACTICE."Phone"%TYPE := NULL;



	BEGIN

		-- get the info for the practice

		BEGIN

			SELECT

				TRIM(P."Name"),

				P."Address1",

				P."Address2",

				P."City",

				P."Province",

				P."Postal",

				TRIM(P."Area"),

				TRIM(P."Phone")

			INTO vPracticeName, vPracticeAddr1, vPracticeAddr2, vPracticeCity, vPracticeState, vPracticeZIP, vPracticeArea, vPracticePhone

			FROM PRACTICE P

			WHERE 1=1

				AND P."Id" = PracticeId

				AND ROWNUM = 1;

		END;



		dbms_lob_s.createtemporary (FileContent, TRUE);



		SELECT "Last", "First" INTO vUserLast, vUserFirst FROM USER_VIEW WHERE "User" = UserId;



		dbms_lob_s.append(FileContent, GetCCDAHeader(PatientId, PracticeId, UserId, 'Export Summary'));



		dbms_lob_s.append(FileContent, '

			<documentationOf typeCode="DOC">

				<serviceEvent classCode="PCPR" moodCode="EVN">

					 <effectiveTime>

						<low value="' || TO_CHAR(SYSDATE, 'YYYYMMDDHH24MI') || '"/>

						<high value="' || TO_CHAR(SYSDATE, 'YYYYMMDDHH24MI') || '"/>

					</effectiveTime>');



		-- primary provider -- AX-10463

		FOR cPProv IN curAssignedPrimary LOOP



			dbms_lob_s.append(FileContent, '

				<performer typeCode="PRF">

				  <templateId root="2.16.840.1.113883.3.88.11.83.4" />

				  <templateId root="1.3.6.1.4.1.19376.1.5.3.1.2.3" />

				  <functionCode code="PP" displayName="Primary Care Provider" codeSystem="2.16.840.1.113883.12.443" codeSystemName="Provider Role" />

				  <time nullFlavor="UNK">

					<low nullFlavor="UNK" />

					<high nullFlavor="UNK" />

				  </time>

				  <assignedEntity>

					<id root="2.16.840.1.113883.4.6" extension="UNK" />

					<addr>

						<streetAddressLine>' || htf.escape_sc(cPProv."Address1") || '</streetAddressLine>');



			IF NOT (TRIM(cPProv."Address2") IS NULL OR length(TRIM(cPProv."Address2")) = 0) THEN

				dbms_lob_s.append(FileContent, '

						<streetAddressLine>' || htf.escape_sc(cPProv."Address2") || '</streetAddressLine>');

			END IF;



									-- AX-18945.19094e

				IF NOT (trim(cPProv."City") IS NULL OR length(trim(cPProv."City")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<city>' ||  htf.escape_sc(trim(cPProv."City")) || '</city>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<city nullFlavor="UNK"/>');

				END IF;



				IF NOT (trim(cPProv."Province") IS NULL OR length(trim(cPProv."Province")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<state>' ||  htf.escape_sc(trim(cPProv."Province")) || '</state>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<state nullFlavor="UNK"/>');

				END IF;



				IF NOT (trim(cPProv."Postal") IS NULL OR length(trim(cPProv."Postal")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<postalCode>' ||  htf.escape_sc(trim(cPProv."Postal")) || '</postalCode>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<postalCode nullFlavor="UNK"/>');

				END IF;



			dbms_lob_s.append(FileContent, '

						<country>US</country>

					</addr>

					<telecom use="WP" value="' || TRIM(cPProv."AltArea") || '-' || TRIM(cPProv."AltPhone") || '"/>

					<assignedPerson classCode="PSN" determinerCode="INSTANCE">');



			IF cPProv."FirstName" IS NOT NULL THEN

				dbms_lob_s.append(FileContent, '

					  <name>

						<given>' || htf.escape_sc(trim(cPProv."FirstName")) || '</given>

						<family>' || htf.escape_sc(trim(cPProv."LastName")) || '</family>

					  </name>');



			ELSE

				dbms_lob_s.append(FileContent, '

					  <name nullFlavor="UNK" />');



			END IF;



			dbms_lob_s.append(FileContent, '

					</assignedPerson>

				    </assignedEntity>

				</performer>');



			vHasPrimary := 1;

		END LOOP;



		-- handle case where have no primary provider

		IF vHasPrimary = 0 THEN

			dbms_lob_s.append(FileContent, '

				<performer typeCode="PRF">

					  <templateId root="2.16.840.1.113883.3.88.11.83.4" />

					  <templateId root="1.3.6.1.4.1.19376.1.5.3.1.2.3" />

					  <functionCode code="PP" displayName="Primary Care Provider" codeSystem="2.16.840.1.113883.12.443" codeSystemName="Provider Role" />

					  <time nullFlavor="UNK">

						<low nullFlavor="UNK" />

						<high nullFlavor="UNK" />

					  </time>

					  <assignedEntity>

						<id root="2.16.840.1.113883.4.6" extension="UNK" />

						<addr nullFlavor="UNK" />

						<telecom use="WP" nullFlavor="UNK" />

						<assignedPerson classCode="PSN" determinerCode="INSTANCE">

						  <name nullFlavor="UNK" />

						</assignedPerson>

					  </assignedEntity>

				</performer>');

		END IF;



		-- nonprimary assigned providers -- AX-10463

		FOR cProv IN curAssignedNonPrimary LOOP



			dbms_lob_s.append(FileContent, '

					<performer typeCode="PRF">

						<templateId root="2.16.840.1.113883.3.88.11.83.4" />

						<templateId root="1.3.6.1.4.1.19376.1.5.3.1.2.3" />

						<assignedEntity>

							<id root="2.16.840.1.113883.4.6" extension="UNK" />

							<code code="-1" displayName="PCP" codeSystemName="GMTDynamic" />

							<addr>

								<streetAddressLine>' || htf.escape_sc(cProv."Address1") || '</streetAddressLine>');



			IF NOT (TRIM(cProv."Address2") IS NULL OR length(TRIM(cProv."Address2")) = 0) THEN

				dbms_lob_s.append(FileContent, '

						<streetAddressLine>' || htf.escape_sc(cProv."Address2") || '</streetAddressLine>');

			END IF;



												-- AX-18945.19094e

				IF NOT (trim(cProv."City") IS NULL OR length(trim(cProv."City")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<city>' ||  htf.escape_sc(trim(cProv."City")) || '</city>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<city nullFlavor="UNK"/>');

				END IF;



				IF NOT (trim(cProv."Province") IS NULL OR length(trim(cProv."Province")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<state>' ||  htf.escape_sc(trim(cProv."Province")) || '</state>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<state nullFlavor="UNK"/>');

				END IF;



				IF NOT (trim(cProv."Postal") IS NULL OR length(trim(cProv."Postal")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<postalCode>' ||  htf.escape_sc(trim(cProv."Postal")) || '</postalCode>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<postalCode nullFlavor="UNK"/>');

				END IF;



			dbms_lob_s.append(FileContent, '

								<country>US</country>

							</addr>

							<telecom use="WP" value="' || TRIM(cProv."AltArea") || '-' || TRIM(cProv."AltPhone") || '"/>

							<assignedPerson classCode="PSN" determinerCode="INSTANCE">

								<name>

									<given>' || htf.escape_sc(trim(cProv."FirstName")) || '</given>

									<family>' || htf.escape_sc(trim(cProv."LastName")) || '</family>

								</name>

							</assignedPerson>

						</assignedEntity>

					</performer>');

		END LOOP;



		-- section footer

		dbms_lob_s.append(FileContent, '

				</serviceEvent>

			</documentationOf>');



		dbms_lob_s.append(FileContent, '

			<component>

			<structuredBody>');



				-- AX-21837

		IF Sections = 'ALL' THEN

			-- AX-18945.19095 - adding new params...

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetMedicalEquipmentSection(PatientId, true, IsDateFrom, Date1, Date2)); --	AX-21118

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetImmunizationSection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetReasonForReferralSection(PatientId, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetProblemSection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetSocialHistorySection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetMedicationSection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetAllergiesSection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetPlanOfCareSection(PatientId, true, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetTreatmentPlanSection(PatientId, true, IsDateFrom, Date1, Date2));	-- AX-26388	

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetProcedureSection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetCognitiveStatusSection(PatientId, true, IsDateFrom, Date1, Date2));	-- AX-21879f

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetFunctionalStatusSection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetVitalSignsSection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetResultsSection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetEncountersSection(PatientId, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetGoalsSection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetHealthConcernsSection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetClinicalNotesSection(PatientId, true, IsDateFrom, Date1, Date2)); -- AX-26344



		ELSE



			-- loop through Sections and add appropriate....

			   FOR Section IN (select regexp_substr (Sections, '[^,]+',1, rownum) Txt from dual 

								connect by level <= regexp_count (Sections, '[^,]+'))

			   LOOP

					IF Section.Txt = '1' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetMedicalEquipmentSection(PatientId, true, IsDateFrom, Date1, Date2)); 

					ELSIF Section.Txt = '2' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetImmunizationSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '3' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetReasonForReferralSection(PatientId, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '4' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetProblemSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '5' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetSocialHistorySection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '6' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetMedicationSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '7' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetAllergiesSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '8' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetPlanOfCareSection(PatientId, true, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '9' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetTreatmentPlanSection(PatientId, true, IsDateFrom, Date1, Date2));	-- AX-26388

					ELSIF Section.Txt = '10' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetProcedureSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '11' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetCognitiveStatusSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '12' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetFunctionalStatusSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '13' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetVitalSignsSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '14' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetResultsSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '15' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetEncountersSection(PatientId, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '16' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetGoalsSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '17' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetHealthConcernsSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '18' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetClinicalNotesSection(PatientId, true, IsDateFrom, Date1, Date2)); -- AX-26344

					END IF;

				  

			   END LOOP;



		END IF;



		dbms_lob_s.append(FileContent, '

			</structuredBody>

			</component>');



		dbms_lob_s.append(FileContent, '

			</ClinicalDocument>');



		return FileContent;

	END;





  	-- Ambulatory Summary

	-- AX-18945.19094 - added new date/time range params...

	FUNCTION ccdaambulatorysummary(patientid numeric, practiceid numeric, userid numeric, sections character varying DEFAULT 'ALL'::character varying, isdatefrom numeric DEFAULT 0, date1 timestamp without time zone DEFAULT NULL::timestamp without time zone, date2 timestamp without time zone DEFAULT NULL::timestamp without time zone) RETURN clob IS

		FileContent CLOB;



-- cursor of assigned primary providers -- AX-10463

		CURSOR curAssignedPrimary IS

			SELECT

				P."FirstName",

				P."LastName",

				P."NPI",

				U."Address1",

				U."Address2",

				U."City",

				U."Province",

				U."Postal",

				U."AltArea",

				U."AltPhone"

			FROM PTPROD PP, PRODUCER P, USERS U

			WHERE 1=1

				AND PP."Patient" = PatientId

				AND PP."Deleted" = 0

				AND PP."StartDate" <= TRUNC(SYSDATE)

				AND PP."EndDate" >= TRUNC(SYSDATE)

				AND PP."IsPrimary" = 1

				AND PP."Producer" = P."Producer"

				AND U."User" = (SELECT U2."User" FROM USERS U2 WHERE U2."Producer" = P."Producer" AND U."Deleted" = 0 AND U2."First" = P."FirstName" AND U2."Name" = P."LastName" AND ROWNUM=1)

			ORDER BY PP."StartDate";



		vHasPrimary NUMBER := 0;



		-- cursor of non-primary assigned providers -- AX-10463

		CURSOR curAssignedNonPrimary IS

			SELECT

				P."FirstName",

				P."LastName",

				P."NPI",

				U."Address1",

				U."Address2",

				U."City",

				U."Province",

				U."Postal",

				U."AltArea",

				U."AltPhone"

			FROM PTPROD PP, PRODUCER P, USERS U

			WHERE 1=1

				AND PP."Patient" = PatientId

				AND PP."Deleted" = 0

				AND PP."StartDate" <= TRUNC(SYSDATE)

				AND PP."EndDate" >= TRUNC(SYSDATE)

				AND PP."IsPrimary" = 0

				AND PP."Producer" = P."Producer"

				AND U."User" = (SELECT U2."User" FROM USERS U2 WHERE U2."Producer" = P."Producer" AND U."Deleted" = 0 AND U2."First" = P."FirstName" AND U2."Name" = P."LastName" AND ROWNUM=1)

			ORDER BY PP."StartDate";



		-- practice contact info

		vPracticeName PRACTICE."Name"%TYPE := NULL;

		vPracticeAddr1 PRACTICE."Address1"%TYPE := NULL;

		vPracticeAddr2 PRACTICE."Address2"%TYPE := NULL;

		vPracticeCity PRACTICE."City"%TYPE := NULL;

		vPracticeState PRACTICE."Province"%TYPE := NULL;

		vPracticeZIP PRACTICE."Postal"%TYPE := NULL;

		vPracticeArea PRACTICE."Area"%TYPE := NULL;

		vPracticePhone PRACTICE."Phone"%TYPE := NULL;

	BEGIN

		-- get the info for the practice

		BEGIN

			SELECT

				TRIM(P."Name"),

				P."Address1",

				P."Address2",

				P."City",

				P."Province",

				P."Postal",

				TRIM(P."Area"),

				TRIM(P."Phone")

			INTO vPracticeName, vPracticeAddr1, vPracticeAddr2, vPracticeCity, vPracticeState, vPracticeZIP, vPracticeArea, vPracticePhone

			FROM PRACTICE P

			WHERE 1=1

				AND P."Id" = PracticeId

				AND ROWNUM = 1;

		END;



		dbms_lob_s.createtemporary (FileContent, TRUE);







		dbms_lob_s.append(FileContent, GetCCDAHeader(PatientId, PracticeId, UserId, 'Ambulatory Summary'));



		dbms_lob_s.append(FileContent, '

		<documentationOf typeCode="DOC">

			<serviceEvent classCode="PCPR" moodCode="EVN">

					 <effectiveTime>

						<low value="' || TO_CHAR(SYSDATE, 'YYYYMMDDHH24MI') || '"/>

						<high value="' || TO_CHAR(SYSDATE, 'YYYYMMDDHH24MI') || '"/>

					</effectiveTime>');



		-- primary provider -- AX-10463

		FOR cPProv IN curAssignedPrimary LOOP



			dbms_lob_s.append(FileContent, '

				<performer typeCode="PRF">

				  <templateId root="2.16.840.1.113883.3.88.11.83.4" />

				  <templateId root="1.3.6.1.4.1.19376.1.5.3.1.2.3" />

				  <functionCode code="PP" displayName="Primary Care Provider" codeSystem="2.16.840.1.113883.12.443" codeSystemName="Provider Role" />

				  <time nullFlavor="UNK">

					<low nullFlavor="UNK" />

					<high nullFlavor="UNK" />

				  </time>

				  <assignedEntity>

					<id root="2.16.840.1.113883.4.6" extension="UNK" />

					<addr>

						<streetAddressLine>' || htf.escape_sc(cPProv."Address1") || '</streetAddressLine>');



			IF NOT (TRIM(cPProv."Address2") IS NULL OR length(TRIM(cPProv."Address2")) = 0) THEN

				dbms_lob_s.append(FileContent, '

						<streetAddressLine>' || htf.escape_sc(cPProv."Address2") || '</streetAddressLine>');

			END IF;



						-- AX-18945.19094e

				IF NOT (trim(cPProv."City") IS NULL OR length(trim(cPProv."City")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<city>' ||  htf.escape_sc(trim(cPProv."City")) || '</city>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<city nullFlavor="UNK"/>');

				END IF;



				IF NOT (trim(cPProv."Province") IS NULL OR length(trim(cPProv."Province")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<state>' ||  htf.escape_sc(trim(cPProv."Province")) || '</state>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<state nullFlavor="UNK"/>');

				END IF;



				IF NOT (trim(cPProv."Postal") IS NULL OR length(trim(cPProv."Postal")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<postalCode>' ||  htf.escape_sc(trim(cPProv."Postal")) || '</postalCode>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<postalCode nullFlavor="UNK"/>');

				END IF;



			dbms_lob_s.append(FileContent, '

							<country>US</country>

					</addr>

					<telecom use="WP" value="' || TRIM(cPProv."AltArea") || '-' || TRIM(cPProv."AltPhone") || '"/>

					<assignedPerson classCode="PSN" determinerCode="INSTANCE">');



			IF cPProv."FirstName" IS NOT NULL THEN

				dbms_lob_s.append(FileContent, '

					  <name>

						<given>' || htf.escape_sc(trim(cPProv."FirstName")) || '</given>

						<family>' || htf.escape_sc(trim(cPProv."LastName")) || '</family>

					  </name>');



			ELSE

				dbms_lob_s.append(FileContent, '

					  <name nullFlavor="UNK" />');



			END IF;



			dbms_lob_s.append(FileContent, '

					</assignedPerson>

				    </assignedEntity>

				</performer>');



			vHasPrimary := 1;

		END LOOP;



		-- handle case where have no primary provider

		IF vHasPrimary = 0 THEN

			dbms_lob_s.append(FileContent, '

				<performer typeCode="PRF">

					  <templateId root="2.16.840.1.113883.3.88.11.83.4" />

					  <templateId root="1.3.6.1.4.1.19376.1.5.3.1.2.3" />

					  <functionCode code="PP" displayName="Primary Care Provider" codeSystem="2.16.840.1.113883.12.443" codeSystemName="Provider Role" />

					  <time nullFlavor="UNK">

						<low nullFlavor="UNK" />

						<high nullFlavor="UNK" />

					  </time>

					  <assignedEntity>

						<id root="2.16.840.1.113883.4.6" extension="UNK" />

						<addr nullFlavor="UNK" />

						<telecom use="WP" nullFlavor="UNK" />

						<assignedPerson classCode="PSN" determinerCode="INSTANCE">

						  <name nullFlavor="UNK" />

						</assignedPerson>

					  </assignedEntity>

				</performer>');

		END IF;



		-- nonprimary assigned providers -- AX-10463

		FOR cProv IN curAssignedNonPrimary LOOP



			dbms_lob_s.append(FileContent, '

					<performer typeCode="PRF">

						<templateId root="2.16.840.1.113883.3.88.11.83.4" />

						<templateId root="1.3.6.1.4.1.19376.1.5.3.1.2.3" />

						<assignedEntity>

							<id root="2.16.840.1.113883.4.6" extension="UNK" />

							<code code="-1" displayName="PCP" codeSystemName="GMTDynamic" />

							<addr>

								<streetAddressLine>' || htf.escape_sc(cProv."Address1") || '</streetAddressLine>');



			IF NOT (TRIM(cProv."Address2") IS NULL OR length(TRIM(cProv."Address2")) = 0) THEN

				dbms_lob_s.append(FileContent, '

						<streetAddressLine>' || htf.escape_sc(cProv."Address2") || '</streetAddressLine>');

			END IF;



			-- AX-18945.19094e

				IF NOT (trim(cProv."City") IS NULL OR length(trim(cProv."City")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<city>' ||  htf.escape_sc(trim(cProv."City")) || '</city>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<city nullFlavor="UNK"/>');

				END IF;



				IF NOT (trim(cProv."Province") IS NULL OR length(trim(cProv."Province")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<state>' ||  htf.escape_sc(trim(cProv."Province")) || '</state>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<state nullFlavor="UNK"/>');

				END IF;



				IF NOT (trim(cProv."Postal") IS NULL OR length(trim(cProv."Postal")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<postalCode>' ||  htf.escape_sc(trim(cProv."Postal")) || '</postalCode>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<postalCode nullFlavor="UNK"/>');

				END IF;



			dbms_lob_s.append(FileContent, '

									<country>US</country>

							</addr>

							<telecom use="WP" value="' || TRIM(cProv."AltArea") || '-' || TRIM(cProv."AltPhone") || '"/>

							<assignedPerson classCode="PSN" determinerCode="INSTANCE">

								<name>

									<given>' || htf.escape_sc(trim(cProv."FirstName")) || '</given>

									<family>' || htf.escape_sc(trim(cProv."LastName")) || '</family>

								</name>

							</assignedPerson>

						</assignedEntity>

					</performer>');

		END LOOP;





		-- section footer

		dbms_lob_s.append(FileContent, '

				</serviceEvent>

			</documentationOf>');



		dbms_lob_s.append(FileContent, '

			<component>

			<structuredBody>');



				-- AX-21837

		IF Sections = 'ALL' THEN

			-- AX-18945.19095 - adding new params...

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetMedicalEquipmentSection(PatientId, true, IsDateFrom, Date1, Date2)); --	AX-21118	

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetReasonForReferralSection(PatientId, IsDateFrom, Date1, Date2));	

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetProblemSection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetSocialHistorySection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetMedicationSection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetAllergiesSection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetPlanOfCareSection(PatientId, true, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetTreatmentPlanSection(PatientId, true, IsDateFrom, Date1, Date2));	-- AX-26388	

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetProcedureSection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetVitalSignsSection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetResultsSection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetGoalsSection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetHealthConcernsSection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetImmunizationSection(PatientId, true, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetEncountersSection(PatientId, IsDateFrom, Date1, Date2));

			dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetClinicalNotesSection(PatientId, true, IsDateFrom, Date1, Date2)); -- AX-26344

			

		ELSE



			-- loop through Sections and add appropriate....

			   FOR Section IN (select regexp_substr (Sections, '[^,]+',1, rownum) Txt from dual 

								connect by level <= regexp_count (Sections, '[^,]+'))

			   LOOP

					IF Section.Txt = '1' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetMedicalEquipmentSection(PatientId, true, IsDateFrom, Date1, Date2)); 

					ELSIF Section.Txt = '2' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetImmunizationSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '3' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetReasonForReferralSection(PatientId, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '4' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetProblemSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '5' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetSocialHistorySection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '6' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetMedicationSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '7' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetAllergiesSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '8' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetPlanOfCareSection(PatientId, true, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '9' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetTreatmentPlanSection(PatientId, true, IsDateFrom, Date1, Date2));	-- AX-26388

					ELSIF Section.Txt = '10' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetProcedureSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '13' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetVitalSignsSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '14' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetResultsSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '15' THEN

					dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetEncountersSection(PatientId, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '16' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetGoalsSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '17' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetHealthConcernsSection(PatientId, true, IsDateFrom, Date1, Date2));

					ELSIF Section.Txt = '18' THEN

						dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetClinicalNotesSection(PatientId, true, IsDateFrom, Date1, Date2)); -- AX-26344

					END IF;

				  

			   END LOOP;



		END IF;



		dbms_lob_s.append(FileContent, '

			</structuredBody>

			</component>');



		dbms_lob_s.append(FileContent, '

			</ClinicalDocument>');



		return FileContent;

	END;





-- E143263 added last optional parameter, SelSections, to control what to include/exclude from the resulting export file;

--					bascially it's a string of 0's   1's to indicate whether a given section a suppose to be exclude / included respectively

--

FUNCTION ccdavisitsummary(patientid numeric, practiceid numeric, userid numeric, apptid numeric, selsections character varying DEFAULT NULL::character varying) RETURN clob IS



  FileContent CLOB := '';



  --E143263

  SelSectionsToUse  VARCHAR2(81) := '';

  DefaultSelSections  VARCHAR2(81) := '11111111111111111111111111111';			-- default to only export the "required" section



  --E143263.3; E143263.4

  vbShowDateOfVisitInfo BOOLEAN;

  vbShowCareTeamInfo BOOLEAN;

  vbShowVisitLocationInfo BOOLEAN;



  vProv1First PRODUCER."FirstName"%TYPE;

  vProv1Last PRODUCER."LastName"%TYPE;

  vProv1User USERS."User"%TYPE;



  vProv2First PRODUCER."FirstName"%TYPE;

  vProv2Last PRODUCER."LastName"%TYPE;

  vProv2User USERS."User"%TYPE;



  vUserFirst USER_VIEW."First"%TYPE;

  vUserLast USER_VIEW."Last"%TYPE;



  vPracticeRec PRACTICE%ROWTYPE;





  vAppoint APPOINT%ROWTYPE;



  BEGIN



  --E143263 added

  if SelSections IS NOT NULL

  THEN

		SelSectionsToUse := SelSections;

  ELSE

		SelSectionsToUse := DefaultSelSections;

  END IF;



  dbms_lob_s.createtemporary (FileContent, TRUE);



  BEGIN

    SELECT * INTO vAppoint FROM APPOINT WHERE "Appointment" = ApptId AND "Type" IN (0,1,2);

  EXCEPTION WHEN NO_DATA_FOUND THEN

				RETURN FileContent;

  END;



  SELECT * INTO vPracticeRec FROM PRACTICE WHERE "Id" = PracticeId AND "Inactive" = 0;



  SELECT "Last", "First" INTO vUserLast, vUserFirst FROM USER_VIEW WHERE "User" = UserId;



  IF NOT (trim(vAppoint."Producer") IS NULL OR length(trim(vAppoint."Producer")) = 0) THEN

    SELECT P."LastName", P."FirstName", U."User" INTO vProv1Last, vProv1First, vProv1User FROM PRODUCER P, USERS U WHERE P."Producer" = vAppoint."Producer" AND U."Producer" = P."Producer" AND U."Deleted" = 0 and ROWNUM = 1;

  END IF;



  IF NOT (trim(vAppoint."Assistant") IS NULL OR length(trim(vAppoint."Assistant")) = 0) THEN

    SELECT P."LastName", P."FirstName", U."User" INTO vProv2Last, vProv2First, vProv2User FROM PRODUCER P, USERS U WHERE P."Producer" = vAppoint."Assistant" AND U."Producer" = P."Producer" AND U."Deleted" = 0 and ROWNUM = 1;

  END IF;





    --E143263.3

  vbShowDateOfVisitInfo := ShowInfoInSection(SelSectionsToUse, DATEOFVISIT_SECTION);

  vbShowCareTeamInfo := ShowInfoInSection(SelSectionsToUse, CARETEAM_SECTION);

  vbShowVisitLocationInfo := ShowInfoInSection(SelSectionsToUse, LOCATIONOFVISIT_SECTION);



  dbms_lob_s.append(FileContent, GetCCDAHeader(PatientId, PracticeId, UserId, 'Clinical Visit Summary', SelSectionsToUse));	--E143263.3



  -- need some sort of event / encounter section



    dbms_lob_s.append(FileContent, '

    <documentationOf typeCode="DOC">

		<serviceEvent classCode="PCPR" moodCode="EVN">

				<effectiveTime>

				<low value="' || TO_CHAR(SYSDATE, 'YYYYMMDDHH24MI') || '"/>

				<high value="' || TO_CHAR(SYSDATE, 'YYYYMMDDHH24MI') || '"/>

			</effectiveTime>

			<performer typeCode="PRF">

				<templateId root="2.16.840.1.113883.3.88.11.83.4" />

				<templateId root="1.3.6.1.4.1.19376.1.5.3.1.2.3" />

				<functionCode code="PP" displayName="Primary CareProvider" codeSystem="2.16.840.1.113883.12.443" codeSystemName="Provider Role" />

				<time nullFlavor="UNK">

					<low nullFlavor="UNK" />

					<high nullFlavor="UNK" />

				</time>

				<assignedEntity>

					<id extension="'|| CCDA_CFG_PKG.GetUserIdentifier(vProv1User, vbShowCareTeamInfo)

					||'" root="'|| CCDA_CFG_PKG.GetUserIdentifierType ||'"/>');	--E143263.3



	IF vbShowCareTeamInfo THEN					--E143263.3

	    dbms_lob_s.append(FileContent, '

					<addr>

						<streetAddressLine>' || htf.escape_sc(TRIM(vPracticeRec."Name")) || '</streetAddressLine>');



			IF NOT (TRIM(vPracticeRec."Address1") IS NULL OR length(TRIM(vPracticeRec."Address1")) = 0) THEN

				dbms_lob_s.append(FileContent, '

								<streetAddressLine>' || htf.escape_sc(vPracticeRec."Address1") || '</streetAddressLine>');

			END IF;



			IF NOT (TRIM(vPracticeRec."Address2") IS NULL OR length(TRIM(vPracticeRec."Address2")) = 0) THEN

				dbms_lob_s.append(FileContent, '

								<streetAddressLine>' || htf.escape_sc(vPracticeRec."Address2") || '</streetAddressLine>');

			END IF;



						-- AX-18945.19094e

				IF NOT (trim(vPracticeRec."City") IS NULL OR length(trim(vPracticeRec."City")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<city>' ||  htf.escape_sc(trim(vPracticeRec."City")) || '</city>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<city nullFlavor="UNK"/>');

				END IF;



				IF NOT (trim(vPracticeRec."Province") IS NULL OR length(trim(vPracticeRec."Province")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<state>' ||  htf.escape_sc(trim(vPracticeRec."Province")) || '</state>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<state nullFlavor="UNK"/>');

				END IF;



				IF NOT (trim(vPracticeRec."Postal") IS NULL OR length(trim(vPracticeRec."Postal")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<postalCode>' ||  htf.escape_sc(trim(vPracticeRec."Postal")) || '</postalCode>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<postalCode nullFlavor="UNK"/>');

				END IF;



			dbms_lob_s.append(FileContent, '

								<country>US</country>

							</addr>

							<telecom use="WP" value="' || TRIM(vPracticeRec."Area") || '-' || TRIM(vPracticeRec."Phone") || '"/>

							<assignedPerson classCode="PSN" determinerCode="INSTANCE">

								<name>

									<given>' || htf.escape_sc(trim(vProv1First)) || '</given>

									<family>' || htf.escape_sc(trim(vProv1Last)) || '</family>

								</name>

							</assignedPerson>');



	ELSE

	    dbms_lob_s.append(FileContent, '

					<addr nullFlavor="UNK"/>

					<telecom nullFlavor="UNK"/>

					<assignedPerson classCode="PSN" determinerCode="INSTANCE">

						<name>

							<given nullFlavor="NA"/>

							<family nullFlavor="NA"/>

						</name>

					</assignedPerson>');

	END IF;

   dbms_lob_s.append(FileContent, '

				</assignedEntity>

			</performer>');





      IF  vbShowCareTeamInfo AND NOT (trim(vAppoint."Assistant") IS NULL OR length(trim(vAppoint."Assistant")) = 0) THEN			--E143263.3

        dbms_lob_s.append(FileContent, '

			<performer typeCode="PRF">

				<templateId root="2.16.840.1.113883.3.88.11.83.4" />

				<templateId root="1.3.6.1.4.1.19376.1.5.3.1.2.3" />

				<assignedEntity>

					<id extension="'|| CCDA_CFG_PKG.GetUserIdentifier(vProv2User) ||'" root="'|| CCDA_CFG_PKG.GetUserIdentifierType ||'"/>

					<code code="-1" displayName="PCP" codeSystemName="GMTDynamic" />

					<addr>

						<streetAddressLine>' || htf.escape_sc(TRIM(vPracticeRec."Name")) || '</streetAddressLine>

						<streetAddressLine>' || htf.escape_sc(vPracticeRec."Address1") || '</streetAddressLine>');



			IF NOT (TRIM(vPracticeRec."Address2") IS NULL OR length(TRIM(vPracticeRec."Address2")) = 0) THEN

				dbms_lob_s.append(FileContent, '

						<streetAddressLine>' || htf.escape_sc(vPracticeRec."Address2") || '</streetAddressLine>');

			END IF;



									-- AX-18945.19094e

				IF NOT (trim(vPracticeRec."City") IS NULL OR length(trim(vPracticeRec."City")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<city>' ||  htf.escape_sc(trim(vPracticeRec."City")) || '</city>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<city nullFlavor="UNK"/>');

				END IF;



				IF NOT (trim(vPracticeRec."Province") IS NULL OR length(trim(vPracticeRec."Province")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<state>' ||  htf.escape_sc(trim(vPracticeRec."Province")) || '</state>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<state nullFlavor="UNK"/>');

				END IF;



				IF NOT (trim(vPracticeRec."Postal") IS NULL OR length(trim(vPracticeRec."Postal")) = 0) THEN

					dbms_lob_s.append(FileContent, '

						<postalCode>' ||  htf.escape_sc(trim(vPracticeRec."Postal")) || '</postalCode>');

				ELSE

					dbms_lob_s.append(FileContent, '

						<postalCode nullFlavor="UNK"/>');

				END IF;



			dbms_lob_s.append(FileContent, '

						<country>US</country>

					</addr>

					<telecom use="WP" value="' || TRIM(vPracticeRec."Area") || '-' || TRIM(vPracticeRec."Phone") || '"/>

					<assignedPerson classCode="PSN" determinerCode="INSTANCE">

						<name>

							<given>' || htf.escape_sc(trim(vProv2First)) || '</given>

							<family>' || htf.escape_sc(trim(vProv2Last)) || '</family>

						</name>

					</assignedPerson>

				</assignedEntity>

			</performer>');

      END IF;



    dbms_lob_s.append(FileContent, '

		</serviceEvent>

	</documentationOf>');



    dbms_lob_s.append(FileContent, '

    <componentOf>

      <encompassingEncounter>

         <id root="UNK"/>

         <effectiveTime>');



    IF vbShowDateOfVisitInfo THEN			--E143263.3

	 -- AX-18945.19094f

	    dbms_lob_s.append(FileContent, '

            <low value="' || TO_CHAR(vAppoint."Date", 'YYYYMMDD') || LPAD(TRUNC(vAppoint."From" / 60), 2, '0') || LPAD(MOD(vAppoint."From", 60), 2, '0')  ||'"/>

            <high value="' || TO_CHAR(vAppoint."Date", 'YYYYMMDD') || LPAD(TRUNC((vAppoint."From" + vAppoint."Time0" + vAppoint."Time1"+ vAppoint."Time2"+ vAppoint."Time3"+ vAppoint."Time4"+ vAppoint."Time5") / 60), 2, '0') || LPAD(MOD((vAppoint."From" + vAppoint."Time0" + vAppoint."Time1"+ vAppoint."Time2"+ vAppoint."Time3"+ vAppoint."Time4"+ vAppoint."Time5"), 60), 2, '0')  ||'"/>');

    ELSE

	    dbms_lob_s.append(FileContent, '

            <low nullFlavor="NA"/>

            <high nullFlavor="NA"/>');

    END IF;



    dbms_lob_s.append(FileContent, '

         </effectiveTime>

         <responsibleParty>

            <assignedEntity>

               <id extension="'|| CCDA_CFG_PKG.GetUserIdentifier(vProv1User, vbShowCareTeamInfo) ||'" root="'|| CCDA_CFG_PKG.GetUserIdentifierType ||'"/>

               <code code="' || CCDA_CFG_PKG.GetNUCCType(vAppoint."Producer") || '" codeSystem="2.16.840.1.113883.6.101"

                  displayName="Dental Providers" codeSystemName="NUCC"/>');				--E143263.3



	  IF vbShowCareTeamInfo THEN					--E143263.3

          dbms_lob_s.append(FileContent, '

		     <addr>');

			  IF NOT (trim(vPracticeRec."Address1") IS NULL OR length(trim(vPracticeRec."Address1")) = 0) THEN

				  dbms_lob_s.append(FileContent, '

			  <streetAddressLine>' ||  htf.escape_sc(trim(vPracticeRec."Address1")) || '</streetAddressLine>');

			  END IF;



			  IF NOT (trim(vPracticeRec."Address2") IS NULL OR length(trim(vPracticeRec."Address2")) = 0) THEN

				  dbms_lob_s.append(FileContent, '

			  <streetAddressLine>' ||  htf.escape_sc(trim(vPracticeRec."Address2")) || '</streetAddressLine>');

			  END IF;





			  IF NOT (trim(vPracticeRec."City") IS NULL OR length(trim(vPracticeRec."City")) = 0) THEN

				  dbms_lob_s.append(FileContent, '

			  <city>' ||  htf.escape_sc(trim(vPracticeRec."City")) || '</city>');

			  END IF;





			  IF NOT (trim(vPracticeRec."Province") IS NULL OR length(trim(vPracticeRec."Province")) = 0) THEN

				  dbms_lob_s.append(FileContent, '

			  <state>' ||  htf.escape_sc(trim(vPracticeRec."Province")) || '</state>');

			  END IF;



			  IF NOT (trim(vPracticeRec."Postal") IS NULL OR length(trim(vPracticeRec."Postal")) = 0) THEN

				  dbms_lob_s.append(FileContent, '

			  <postalCode>' ||  htf.escape_sc(trim(vPracticeRec."Postal")) || '</postalCode>');

			  END IF;



		     dbms_lob_s.append(FileContent, '

				<country>' || 'US' || '</country>');



				dbms_lob_s.append(FileContent, '

				</addr>');

	  ELSE

	    dbms_lob_s.append(FileContent, '

				<addr nullFlavor="UNK"/>');



	  END IF;





     IF vbShowCareTeamInfo AND NOT (TRIM(vPracticeRec."Phone") IS NULL OR length(TRIM(vPracticeRec."Phone")) = 0) THEN			--E143263.3

			dbms_lob_s.append(FileContent, '

				<telecom use="WP" value="');

			IF NOT (TRIM(vPracticeRec."Area") IS NULL OR length(TRIM(vPracticeRec."Area")) = 0) THEN

				dbms_lob_s.append(FileContent,  htf.escape_sc(TRIM(vPracticeRec."Area")) || '-');

			END IF;

				dbms_lob_s.append(FileContent,  htf.escape_sc(trim(vPracticeRec."Phone")) ||'"/>');

	  END IF;



    dbms_lob_s.append(FileContent, '

               <assignedPerson>

                  <name>');

     IF vbShowCareTeamInfo  THEN			--E143263.3

			dbms_lob_s.append(FileContent, '

                     <given>' || htf.escape_sc(trim(vUserFirst)) || '</given>

                     <family>' || htf.escape_sc(trim(vUserLast)) || '</family>');

     ELSE

			dbms_lob_s.append(FileContent, '

                     <given nullFlavor="NA"/>

                     <family nullFlavor="NA"/>');

     END IF;



	  dbms_lob_s.append(FileContent, '

                  </name>

               </assignedPerson>

            </assignedEntity>

         </responsibleParty>

         <location>

            <healthCareFacility>

               <id root="2.16.840.1.113883.4.6" extension="');



     IF vbShowCareTeamInfo  THEN			--E143263.3

		  dbms_lob_s.append(FileContent,

                NVL(TRIM(vPracticeRec."NPI"), 'UNK') ||'"/>');

     ELSE

		  dbms_lob_s.append(FileContent, 'UNK'||'"/>');

     END IF;



	  dbms_lob_s.append(FileContent, '

               <code code="' || CCDA_CFG_PKG.GetNUCCType(vAppoint."Producer") || '" codeSystem="2.16.840.1.113883.6.101"

                  displayName="Dental Providers" codeSystemName="NUCC"/>

               <location>');



     IF vbShowVisitLocationInfo  THEN			--E143263.3

	      dbms_lob_s.append(FileContent, '

		   <name>' ||  htf.escape_sc(TRIM(vPracticeRec."Name")) ||'</name>');

		ELSE

	      dbms_lob_s.append(FileContent, '<name nullFlavor="NA"/>');

		END IF;



     IF vbShowVisitLocationInfo  THEN			--E143263.3

			dbms_lob_s.append(FileContent, '

		  <addr>');



	     IF NOT (trim(vPracticeRec."Address1") IS NULL OR length(trim(vPracticeRec."Address1")) = 0) THEN

		     dbms_lob_s.append(FileContent, '

			<streetAddressLine>' ||  htf.escape_sc(trim(vPracticeRec."Address1")) || '</streetAddressLine>');

		  END IF;



		  IF NOT (trim(vPracticeRec."Address2") IS NULL OR length(trim(vPracticeRec."Address2")) = 0) THEN

				dbms_lob_s.append(FileContent, '

			<streetAddressLine>' ||  htf.escape_sc(trim(vPracticeRec."Address2")) || '</streetAddressLine>');

		  END IF;



	     IF NOT (trim(vPracticeRec."City") IS NULL OR length(trim(vPracticeRec."City")) = 0) THEN

		     dbms_lob_s.append(FileContent, '

			<city>' ||  htf.escape_sc(trim(vPracticeRec."City")) || '</city>');

		  END IF;



		  IF NOT (trim(vPracticeRec."Province") IS NULL OR length(trim(vPracticeRec."Province")) = 0) THEN

				dbms_lob_s.append(FileContent, '

			<state>' ||  htf.escape_sc(trim(vPracticeRec."Province")) || '</state>');

		  END IF;



		  IF NOT (trim(vPracticeRec."Postal") IS NULL OR length(trim(vPracticeRec."Postal")) = 0) THEN

          dbms_lob_s.append(FileContent, '

         <postalCode>' ||  htf.escape_sc(trim(vPracticeRec."Postal")) || '</postalCode>');

        END IF;



	     dbms_lob_s.append(FileContent, '

		  <country>' || 'US' || '</country>');



			dbms_lob_s.append(FileContent, '

			</addr>');



     ELSE

	    dbms_lob_s.append(FileContent, '

				<addr nullFlavor="UNK"/>');



     END IF;





     dbms_lob_s.append(FileContent, '

               </location>

               <serviceProviderOrganization>');



      dbms_lob_s.append(FileContent, '

      <id root="2.16.840.1.113883.4.6" extension="');



      --E143263.3

      IF vbShowVisitLocationInfo THEN

	      dbms_lob_s.append(FileContent, NVL(TRIM(vPracticeRec."NPI"), 'UNK') ||'"/>');

	    ELSE

	      dbms_lob_s.append(FileContent, 'UNK' ||'"/>');

	    END IF;



     IF vbShowVisitLocationInfo  THEN			--E143263.3

	      dbms_lob_s.append(FileContent, '

		   <name>' ||  htf.escape_sc(TRIM(vPracticeRec."Name")) ||'</name>');

		ELSE

	      dbms_lob_s.append(FileContent, '<name nullFlavor="NA"/>');

		END IF;



     IF vbShowVisitLocationInfo AND NOT (TRIM(vPracticeRec."Phone") IS NULL OR length(TRIM(vPracticeRec."Phone")) = 0) THEN				--E143263.3

			dbms_lob_s.append(FileContent, '

			<telecom use="WP" value="');

			IF NOT (TRIM(vPracticeRec."Area") IS NULL OR length(TRIM(vPracticeRec."Area")) = 0) THEN

				dbms_lob_s.append(FileContent,  htf.escape_sc(TRIM(vPracticeRec."Area")) || '-');

			END IF;

			dbms_lob_s.append(FileContent,  htf.escape_sc(trim(vPracticeRec."Phone")) ||'"/>');



	  ELSE

			dbms_lob_s.append(FileContent, '

				<telecom nullFlavor="UNK"/>');

	  END IF;



     IF vbShowVisitLocationInfo  THEN			--E143263.3



			dbms_lob_s.append(FileContent, '

		  <addr>');



	     IF NOT (trim(vPracticeRec."Address1") IS NULL OR length(trim(vPracticeRec."Address1")) = 0) THEN

		     dbms_lob_s.append(FileContent, '

				<streetAddressLine>' ||  htf.escape_sc(trim(vPracticeRec."Address1")) || '</streetAddressLine>');

		  END IF;



		  IF NOT (trim(vPracticeRec."Address2") IS NULL OR length(trim(vPracticeRec."Address2")) = 0) THEN

				dbms_lob_s.append(FileContent, '

				<streetAddressLine>' ||  htf.escape_sc(trim(vPracticeRec."Address2")) || '</streetAddressLine>');

		  END IF;





		  IF NOT (trim(vPracticeRec."City") IS NULL OR length(trim(vPracticeRec."City")) = 0) THEN

			  dbms_lob_s.append(FileContent, '

		  <city>' ||  htf.escape_sc(trim(vPracticeRec."City")) || '</city>');

		  END IF;





		  IF NOT (trim(vPracticeRec."Province") IS NULL OR length(trim(vPracticeRec."Province")) = 0) THEN

			  dbms_lob_s.append(FileContent, '

		  <state>' ||  htf.escape_sc(trim(vPracticeRec."Province")) || '</state>');

		  END IF;



		  IF NOT (trim(vPracticeRec."Postal") IS NULL OR length(vPracticeRec."Postal") = 0) THEN

			  dbms_lob_s.append(FileContent, '

		  <postalCode>' ||  htf.escape_sc(trim(vPracticeRec."Postal")) || '</postalCode>');

		  END IF;



	     dbms_lob_s.append(FileContent, '

		  <country>' || 'US' || '</country>');



			dbms_lob_s.append(FileContent, '

			</addr>');



     ELSE



	    dbms_lob_s.append(FileContent, '

				<addr nullFlavor="UNK"/>');



     END IF;





     dbms_lob_s.append(FileContent, '

                  <standardIndustryClassCode code="120000000X" displayName="Dental Providers" codeSystem="2.16.840.1.113883.6.101" codeSystemName="NUCC"/>

               </serviceProviderOrganization>

            </healthCareFacility>

         </location>

      </encompassingEncounter>

   </componentOf>');





    dbms_lob_s.append(FileContent, '

  <component>

  <structuredBody>');



	dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetReasonForVisitSection(ApptId,

							ShowInfoInSection(SelSectionsToUse, REASONFORVISIT_SECTION)));



   dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetProblemSection(PatientId,

							ShowInfoInSection(SelSectionsToUse, PROBLEMS_SECTION)));



	dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetAllergiesSection(PatientId,

							ShowInfoInSection(SelSectionsToUse, MEDALLERGIES_SECTION)));



	dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetMedicationSection(PatientId,

							ShowInfoInSection(SelSectionsToUse, ACTIVEMED_SECTION)));



   dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetMedAdministeredSection(ApptId,

							ShowInfoInSection(SelSectionsToUse, MEDADMINVISIT_SECTION)));



	dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetImmunizationSection(PatientId,

							ShowInfoInSection(SelSectionsToUse, IMMUNIZATIONS_SECTION)));



	dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetVitalSignsSection(PatientId,

							ShowInfoInSection(SelSectionsToUse, VITALSIGNS_SECTION)));



	dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetSocialHistorySection(PatientId,

							ShowInfoInSection(SelSectionsToUse, SOCIALHISTORY_SECTION)));



	dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetResultsSection(PatientId,

							ShowInfoInSection(SelSectionsToUse, LABTESTRESULTS_SECTION)));



   dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetProcedureSectionVisit(PatientId, vAppoint."Date",

							ShowInfoInSection(SelSectionsToUse, PROCEDURES_SECTION)));



	dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetPlanOfCareSectionVisit(PatientId, vAppoint."Date",

							ShowInfoInSection(SelSectionsToUse, GOALANDINSTRUCTION_SECTION),

							ShowInfoInSection(SelSectionsToUse, FUTUREAPPTS_SECTION),

							ShowInfoInSection(SelSectionsToUse, PENDINGLABTEST_SECTION),

							ShowInfoInSection(SelSectionsToUse, PLANNEDPROCEDURES_SECTION),

							ShowInfoInSection(SelSectionsToUse, REFERRALSTOOTHER_SECTION)));



	dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetInstructionsSection(ApptId,

							ShowInfoInSection(SelSectionsToUse, PATDECISIONAIDS_SECTION),

							ShowInfoInSection(SelSectionsToUse, CLININSTRUCTION_SECTION)));



	-- AX-26604

	dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetMedicalEquipmentSection(PatientId,

							ShowInfoInSection(SelSectionsToUse, MEDICALEQUIPMENT_SECTION)));



	-- AX-26344

	dbms_lob_s.append(FileContent, CCDA_CFG_PKG.GetClinicalNotesSection(PatientId,

							ShowInfoInSection(SelSectionsToUse, CLINICALNOTES_SECTION)));							



    dbms_lob_s.append(FileContent, '

  </structuredBody>

  </component>');



    dbms_lob_s.append(FileContent, '

</ClinicalDocument>');



    return FileContent;

  END;







  PROCEDURE infomanagerexport(IN patientid numeric, IN userid numeric, IN stationid numeric) IS



    FileContent CLOB;

    PracticeId NUMBER;

    vPtChart PATIENT."Chart"%TYPE;



    vOutputFile UTL_FILE.FILE_TYPE;	-- file object

    vOutputFileName  VARCHAR2(255); -- name of the output file

    chnksz pls_integer;

  BEGIN



    dbms_lob_s.createtemporary (FileContent, TRUE);



    SELECT TRIM("Chart") INTO vPtChart FROM PATIENT WHERE "Patient" = PatientId;



    -- determine a 'unique' filename

    vOutputFileName := 'CCDA_Export_' || TRIM(vPtChart) || '_' || ROUND((SYSDATE - TO_DATE('01/01/1970 00:00:00', 'MM-DD-YYYY HH24:MI:SS'))*24*60*60) || '.xml';



    -- open the file for writing

    BEGIN

      vOutputFile := UTL_FILE.FOPEN(TRIM(CCDA_CFG_PKG.GetExportDir), TRIM(vOutputFileName), 'wb');

    END;



    PracticeId := CCDA_CFG_PKG.GetPracticeId(PatientId, UserId, StationId);

    FileContent := CCDAExportSummary(PatientId, PracticeId, UserId);



    chnksz := 3000;

    for i in 1 .. ceil( length( FileContent ) / chnksz )

    loop

    dbms_output.put_line( i );

      utl_file.put_raw( vOutputFile, utl_raw.cast_to_raw( substr( FileContent, ( i - 1 ) * chnksz + 1, chnksz ) ) );

      utl_file.fflush(vOutputFile);

    end loop;



    UTL_FILE.FCLOSE(vOutputFile);

  END;

  

    PROCEDURE ccdatocsummaryproc(IN patientid numeric, IN practiceid numeric, IN userid numeric, IN isdatefrom numeric DEFAULT 0, IN date1 timestamp without time zone DEFAULT NULL::timestamp without time zone, IN date2 timestamp without time zone DEFAULT NULL::timestamp without time zone, IN sections character varying DEFAULT NULL::character varying, OUT tocsummary clob) IS

    TOCProcSummary CLOB;

    BEGIN

        IF Sections IS NULL THEN

            TOCProcSummary := CCDATOCSummary(PatientId, PracticeId, UserId, 'ALL', IsDateFrom, Date1, Date2);

        ELSE

            TOCProcSummary := CCDATOCSecSummary(PatientId, PracticeId, UserId, IsDateFrom, Date1, Date2, Sections);

        END IF;

        TOCSummary := TOCProcSummary;

    END;  





	-- AX-21643.21710d

	PROCEDURE executeccdaschedjob(IN ccdaschid numeric, IN practiceid numeric, IN audituser numeric) IS

		vCCDASchRec CCDASCH%ROWTYPE;

	    CURSOR vPatToExport IS

			SELECT *

			FROM CCDAPAT P

			WHERE P."CCDASch" = CCDASchId;

	    vSqlQuery  VARCHAR2(4000) := '';

	    vExportOutput CLOB;

	    vPtChart PATIENT."Chart"%TYPE;



	    vOutputFile UTL_FILE.FILE_TYPE;	-- file object

	    vOutputFileName  VARCHAR2(255); -- name of the output file

		chnksz pls_integer;



	BEGIN

		SELECT * INTO vCCDASchRec FROM CCDASCH WHERE "CCDASch" = CCDASchId;

		FOR vptId IN vPatToExport

		LOOP

    		IF vCCDASchRec."CCDAType" = 1 THEN

				vSqlQuery := 'SELECT CCDA_PKG.CCDAAmbulatorySummary(';

    		ELSIF vCCDASchRec."CCDAType" = 2 THEN

				vSqlQuery := 'SELECT CCDA_PKG.CCDAExportSummary(';

			ELSE

				vSqlQuery := 'SELECT CCDA_PKG.CCDATOCSummary(';

    		END IF;

			vSqlQuery := vSqlQuery || TO_CHAR(trunc(vptId."PatientId")) || ', ';

			vSqlQuery := vSqlQuery || TO_CHAR(trunc(PracticeId)) || ', ';

			vSqlQuery := vSqlQuery || TO_CHAR(trunc(AuditUser));

    		IF vCCDASchRec."HasDateTimeRange" = 1 THEN

				vSqlQuery := vSqlQuery || ', 1';

				IF vCCDASchRec."FromDate" IS NOT NULL THEN

					vSqlQuery := vSqlQuery || ', TO_DATE(''' || TO_CHAR(vCCDASchRec."FromDate", 'DD/MM/YYYY');

					vSqlQuery := vSqlQuery || ' ' || TO_CHAR(TRUNC(vCCDASchRec."FromTime"/60)) || ':' || TO_CHAR(MOD(vCCDASchRec."FromTime", 60)) || ':00'',' || ' ''DD/MM/YYYY HH24:MI:SS'')';

				END IF;

				IF vCCDASchRec."ToDate" IS NOT NULL THEN

					vSqlQuery := vSqlQuery || ', TO_DATE(''' || TO_CHAR(vCCDASchRec."ToDate", 'DD/MM/YYYY');

					vSqlQuery := vSqlQuery || ' ' || TO_CHAR(TRUNC(vCCDASchRec."ToTime"/60)) || ':' || TO_CHAR(MOD(vCCDASchRec."ToTime", 60)) || ':00'',' || ' ''DD/MM/YYYY HH24:MI:SS'')';

				END IF;

			END IF;

			vSqlQuery := vSqlQuery || ') FROM DUAL';



		    dbms_lob_s.createtemporary (vExportOutput, TRUE);

			EXECUTE IMMEDIATE vSqlQuery INTO vExportOutput;





			SELECT TRIM("Chart") INTO vPtChart FROM PATIENT WHERE "Patient" = vptId."PatientId";



			-- determine a 'unique' filename; AX-21643.21710g

			IF LENGTH(TRIM(vCCDASchRec."FilePrefix")) > 0 THEN

				vOutputFileName := vCCDASchRec."FilePrefix" || '_'  || TRIM(vPtChart) || '_' || TO_CHAR(SYSDATE, 'YYYYMMDDHH24MI') || '.xml';

			ELSE

				vOutputFileName := 'CCDAEXPORT_'  || TRIM(vPtChart) || '_' || TO_CHAR(SYSDATE, 'YYYYMMDDHH24MI') || '.xml';

			END IF;



			-- open the file for writing

			BEGIN

				vOutputFile := UTL_FILE.FOPEN(vCCDASchRec."OracleDir", vOutputFileName, 'wb');												--AX-21643.21710g

			END;

		    chnksz := 3000;

			for i in 1 .. ceil( length( vExportOutput ) / chnksz )

			loop

				dbms_output.put_line( i );

				utl_file.put_raw( vOutputFile, utl_raw.cast_to_raw( substr( vExportOutput, ( i - 1 ) * chnksz + 1, chnksz ) ) );

				utl_file.fflush(vOutputFile);

			end loop;



			UTL_FILE.FCLOSE(vOutputFile);



		    IF ( AUDITLOG_PKG.GetSecureLog() <> 0 ) THEN

				  AUDITLOG_PKG.InsertAuditLog(vptId."PatientId", AUDITLOG_PKG.c_nActionCopy, '', 'Schedule Summary of Care', vPtChart);

			END IF;

		END LOOP;

	END;



END;
CREATE OR REPLACE PACKAGE BODY chart_pkg IS





PROCEDURE verifychart(IN chartid character) IS

  vPId     NUMBER  := 0;

  vTooth   NUMBER  := 0;

  vPrimary BOOLEAN := FALSE;

  vError   BOOLEAN := FALSE;

  vState   NUMBER  := 0;

  vCurrentState NUMBER  := 0;

  vCurrentTeeth  CHAR(32);

  vPermanentTeeth  CHAR(32);

  vPrimaryTeeth  CHAR(32);

  vOneTooth  CHAR(1);

BEGIN

  -- get patient info

  SELECT "Auto", "ToothState", "PrimaryState", "PermanentState" 

    INTO vPId, vCurrentTeeth, vPrimaryTeeth, vPermanentTeeth 

    FROM PATIENT2 WHERE "ChartId" = ChartId;



  IF vPId > 0 THEN

    -- handle state fields not being initialized

    IF (TRIM(vCurrentTeeth) IS NULL OR length(TRIM(vCurrentTeeth)) = 0) THEN

      vCurrentTeeth := '00000000000000000000000000000000';

    END IF;

    IF (TRIM(vPrimaryTeeth) IS NULL OR length(TRIM(vPrimaryTeeth)) = 0)  THEN

      vPrimaryTeeth := '00000000000000000000000000000000';

    END IF;

    IF (TRIM(vPermanentTeeth) IS NULL OR length(TRIM(vPermanentTeeth)) = 0) THEN

      vPermanentTeeth := '00000000000000000000000000000000';

    END IF;

  

    -- do permanent teeth

    FOR i IN 1 .. 32 LOOP  

      ToothFromSite(i, vTooth, vPrimary, vError);

      

      IF vError = FALSE AND vPrimary = FALSE THEN

        vOneTooth := SUBSTRB(vCurrentTeeth, vTooth, 1);

        vCurrentState := TO_NUMBER(vOneTooth);

        vOneTooth := SUBSTRB(vPermanentTeeth, vTooth, 1);

        vState    := TO_NUMBER(vOneTooth);

    

        VerifySite(vPId, i, vCurrentState, vState);

      

        vOneTooth := TO_CHAR(vState);

        vPermanentTeeth := SUBSTRB(vPermanentTeeth, 1, vTooth - 1) || vOneTooth || SUBSTR(vPermanentTeeth, vTooth + 1);

      END IF;

    END LOOP;

  

    -- do primary teeth

    FOR i IN 45 .. 64 LOOP  

      ToothFromSite(i, vTooth, vPrimary, vError);

      

      IF vError = FALSE AND vPrimary = TRUE THEN

        vOneTooth := SUBSTRB(vCurrentTeeth, vTooth, 1);

        vCurrentState := TO_NUMBER(vOneTooth);

        vOneTooth := SUBSTRB(vPrimaryTeeth, vTooth, 1);

        vState    := TO_NUMBER(vOneTooth);

    

        VerifySite(vPId, i, vCurrentState, vState);

      

        vOneTooth := TO_CHAR(vState);

        vPrimaryTeeth := SUBSTRB(vPrimaryTeeth, 1, vTooth - 1) || vOneTooth || SUBSTR(vPrimaryTeeth, vTooth + 1);

      END IF;

    END LOOP;

  

    UPDATE PATIENT2 SET "ToothState" = vCurrentTeeth, "PrimaryState" = vPrimaryTeeth, "PermanentState" = vPermanentTeeth WHERE "Auto" = vPId;

    INSERT INTO PAT2HIS (SELECT PAT2HIS_PAT2HIS_SEQ.nextval, 2, P2.* FROM PATIENT2 P2 WHERE "Auto" = vPId);

    COMMIT;

  END IF;    

END;





-- any changes to ToothFromSite should also be made to CMainApp tooth routines

PROCEDURE toothfromsite(IN site numeric, OUT tooth numeric, OUT isprimary boolean, OUT error boolean) IS

  vSite NUMBER := 0;

BEGIN

  Tooth := 0;

  IsPrimary := FALSE;

  Error := FALSE;

 

  -- get the index into the array

  vSite := Site - 1;



  IF vSite > 32 THEN	

    IsPrimary := true;																				

    Tooth := vSite - 44;

  

    IF Tooth >= 10 THEN

      Tooth := Tooth + 9;

    ELSE

      Tooth := Tooth + 3;

    END IF;

  ELSE

    Tooth := vSite;

  END IF;



  -- safeguard array bounds												

  IF Tooth > 31 OR Tooth < 0 THEN

    Error := TRUE;

  END IF;

  

  -- SQL string arrays use 1 based index

  Tooth := Tooth + 1;

END;





PROCEDURE verifysite(IN pid numeric, IN site numeric, IN currentstate numeric, INOUT state numeric) IS

BEGIN

  -- check if tooth is missing

  IF BITAND(CurrentState, 2) = 2 THEN

    -- make sure planned extraction bit is off

    IF BITAND(State, 4) = 4 THEN

      State := State - 4;

    END IF;

    

    -- make sure impacted bit is off

    IF BITAND(State, 2) = 2 THEN

      State := State - 2;

    END IF;

  

    -- make sure extraction bit is off

    IF BITAND(State, 1) = 1 THEN

      State := State - 1;

    END IF;

  ELSE

    -- set planned extraction bit

    IF HasPlanRemoved(PId, Site) THEN

      IF BITAND(State, 4) = 0 THEN

        State := State + 4;

      END IF;

    ELSE 

      -- no planned extractions

      IF BITAND(State, 4) = 4 THEN

        State := State - 4;

      END IF;

    END IF;



    -- set impacted bit

    IF HasImpacted(PId, Site) THEN

      IF BITAND(State, 2) = 0 THEN

        State := State + 2;

      END IF;

      -- no planned extractions

      -- don't clear as older versions did not add a treatme2

    END IF;



    -- set extraction bit

    IF HasRemoved(PId, Site) THEN

      IF BITAND(State, 1) = 0 THEN

        State := State + 1;

      END IF;

    

      -- make sure planned extraction bit is off

      IF BITAND(State, 4) = 4 THEN

        State := State - 4;

      END IF;

    

      -- make sure impacted bit is off

      IF BITAND(State, 2) = 2 THEN

        State := State - 2;

      END IF;

    ELSE 

      -- no extractions

      IF BITAND(State, 1) = 1 THEN

        State := State - 1;

      END IF;

    END IF;

  END IF;

  

END;





-- any changes to HasRemoved should also be made to CMainApp::has_removed

FUNCTION hasremoved(pid numeric, site numeric) RETURN boolean IS

 vFound BOOLEAN := FALSE;

 vCount NUMBER  := 0;

BEGIN

 SELECT COUNT(T."Auto") INTO vCount FROM TREATME2 T, PROCEDUR P  

  WHERE T."PId" = PId AND T."Site" = Site AND T."Deleted" = 0 

  AND (T."Status" = 0 OR T."Status" = 3) AND T."CodeId" = P."Id" 

  AND P."Type" = 3 AND rownum < 2;



 IF vCount > 0 THEN

  vFound := TRUE;

 END IF;



 RETURN vFound;

END;





FUNCTION hasimpacted(pid numeric, site numeric) RETURN boolean IS

 vFound BOOLEAN := FALSE;

 vCount NUMBER  := 0;

BEGIN

 SELECT COUNT(T."Auto") INTO vCount FROM TREATME2 T, PROCEDUR P  

  WHERE T."PId" = PId AND T."Site" = Site AND T."Deleted" = 0 

  AND T."Status" <> 2 AND T."CodeId" = P."Id" 

  AND P."Type" = 5 AND rownum < 2;



 IF vCount > 0 THEN

  vFound := TRUE;

 END IF;



 RETURN vFound;

END;





-- any changes to HasPlanRemoved should also be made to CMainApp::has_plan_removed

FUNCTION hasplanremoved(pid numeric, site numeric) RETURN boolean IS

 vFound BOOLEAN := FALSE;

 vCount NUMBER  := 0;

BEGIN

 SELECT COUNT(T."Auto") INTO vCount FROM TREATME2 T, PROCEDUR P  

  WHERE T."PId" = PId AND T."Site" = Site AND T."Deleted" = 0 AND T."Status" = 2

  AND T."CodeId" = P."Id" AND P."Type" = 3 AND rownum < 2;



 IF vCount > 0 THEN

  vFound := TRUE;

 END IF;



 RETURN vFound;

END;



END;
CREATE OR REPLACE PACKAGE BODY consent_pkg IS





-- E57005 - created for use by future enhancements

FUNCTION trx_significant_change(proc1 character, proc2 character, site1 character, site2 character) RETURN numeric IS

  Result NUMBER;

  

BEGIN



  -- see if procedures and sites "match" (no significant change)

  -- E131417 - Added ROWNUM clause

 SELECT COUNT(1)

	INTO Result

	FROM PROCEDUR P1, PROCEDUR P2

	WHERE P1."Procedure" = Proc1

	  AND P2."Procedure" = Proc2

	  AND NVL(TRIM(Site1), '   ') = NVL(TRIM(Site2), '   ')

	  AND (P1."Procedure" = P2."Procedure" 

		OR (P1."Category" = P2."Category" 

			AND P1."ParentGroup" = P2."ParentGroup"))

	  AND ROWNUM = 1;														





  -- if "match" found, then no significant change

  IF Result > 0 THEN

  	RETURN 0;

  ELSE

  	RETURN 1;

  END IF;



END;









-- E128792.4 - rewrote to return consent code(s) of missing consents

-- E45729 - returns 1 if treatment has all required consents on file, 0 otherwise

-- E57005 - check to make sure site hasn't changed

-- E128792.3 - rewrite to look up required consent rules and test each accordingly

FUNCTION trx_has_consent(origrecno numeric, procedur character, site character, patientid numeric, providertype character, returnall numeric DEFAULT 0, initializedata numeric DEFAULT 1, site2 character DEFAULT NULL::bpchar) RETURN character varying IS

 

  Result  VARCHAR2(4000);

  ContractCount NUMBER;

  i NUMBER;

  vConsent  VARCHAR2(255);

  vSql  VARCHAR2(2000);



  

  CURSOR ProcConsCursor(vProcedure VARCHAR2, vProvType VARCHAR2) IS

  	SELECT * FROM PROCCONS_VIEW 

  	WHERE "Procedure" = vProcedure AND ((TRIM(vProvType) IS NULL OR length(TRIM(vProvType)) = 0) OR "ProvType" = vProvType)

  	ORDER BY "RuleType";





BEGIN



  -- clear the array

  IF InitializeData = 1 THEN

	  v_ConsentTable.DELETE;

  END IF;







  -- lookup required consent rules 

  FOR vProcConsRec IN ProcConsCursor(Procedur, ProviderType) 

  LOOP

  		ContractCount := 0;

  

  		IF vProcConsRec."RuleType" = 0 THEN



			-- any tx consent

			

			-- don't keep checking for any tx consent if this 

			-- rule has already been verified to be missing

			IF find_element('Any Treatment Based Consent') = 0 THEN

				-- E56392.3 make sure SigStatus is not 0

				-- B129486 make sure blob is not empty

				-- B99020

        		-- E96625

        		-- E131417 - Added ROWNUM clause

				SELECT COUNT(1)

				INTO ContractCount

				FROM TRXCONT TC, ATTACH_VIEW C

				WHERE ((TC."Contract" = C.Id  

         AND TC."ConsentType" = 0 ) OR ( TC."PtLetter" = C.Id  

         AND TC."ConsentType" = 1 ))

				 AND TC."OrigRecNo" = OrigRecNo

				 AND C.Patient = PatientId

				 AND C.Denied = 0 

				 AND C.Deleted = 0 

				 AND C.SigStatus <> 0

				 AND C.ContentSize > 0

				 AND (C.ExpiryDate >= TRUNC(SYSDATE) OR C.ExpiryDate IS NULL) 

				 AND (trx_significant_change(Procedur, TC."Procedure", Site, TC."Site") = 0

				 OR (NOT (TRIM(Site2) IS NULL OR length(TRIM(Site2)) = 0) AND trx_significant_change(Procedur, TC."Procedure", Site2, TC."Site") = 0))		--AX-2784.10633

				 AND ROWNUM = 1;



				-- add result to shared table

				IF ContractCount = 0 THEN

					i := add_element('Any Treatment Based Consent');

				END IF;

			END IF;

			

		ELSIF vProcConsRec."RuleType" = 1 THEN

  	

			-- specific consent

			

			-- don't keep checking for any tx consent if this 

			-- consent has already been verified to be missing

		  	-- E131417 - Added ROWNUM clause

			IF find_element(vProcConsRec."Consent") = 0 THEN

				SELECT COUNT(1)

				INTO ContractCount

				FROM ATTACH_VIEW C, CONSENT C2

				WHERE C.Consent = C2."Consent"

				AND C.Consent = vProcConsRec."Consent"

				AND C.Patient = PatientId

				AND C.Denied = 0 

				AND C.Deleted = 0 

				AND C.SigStatus <> 0

				AND C.ContentSize > 0

				AND (C.ExpiryDate >= TRUNC(SYSDATE) OR C.ExpiryDate IS NULL)

				AND (C2."TxBased" = 0 OR EXISTS(select 1 from TRXCONT TC

					where (( TC."Contract" = C.Id

          and TC."ConsentType" = 0) OR ( TC."PtLetter" = C.Id

          and TC."ConsentType" = 1) )

					and TC."OrigRecNo" = OrigRecNo

					and (trx_significant_change(Procedur, TC."Procedure", Site, TC."Site") = 0

					or trx_significant_change(Procedur, TC."Procedure", Site2, TC."Site") = 0) ))			--AX-2784.10633

				AND ROWNUM = 1;



				-- add result to shared table

				IF ContractCount = 0 THEN

					i := add_element(vProcConsRec."Consent");

				END IF;

			END IF;

			

		ELSIF vProcConsRec."RuleType" = 2 THEN

 	

	  		-- custom function

				

			-- get consent from the custom function

			vSql := 'select ' || vProcConsRec."Function" || '(:1, :2) FROM DUAL';

			EXECUTE IMMEDIATE vSql INTO vConsent USING PatientId, OrigRecNo;





			IF NOT (TRIM(vConsent) IS NULL OR length(TRIM(vConsent)) = 0) THEN

				-- don't keep checking for any tx consent if this 

				-- consent has already been verified to be missing

				IF find_element(vConsent) = 0 THEN

					-- B130231 - added trim on consent code

			 	 	-- E131417 - Added ROWNUM clause

					SELECT COUNT(1)

					INTO ContractCount

					FROM ATTACH_VIEW C, CONSENT C2

					WHERE C.Consent = C2."Consent"

					AND TRIM(C.Consent) = TRIM(vConsent)

					AND C.Patient = PatientId

					AND C.Denied = 0 

					AND C.Deleted = 0 

					AND C.SigStatus <> 0

					AND C.ContentSize > 0

					AND (C.ExpiryDate >= TRUNC(SYSDATE) OR C.ExpiryDate IS NULL)

					AND (C2."TxBased" = 0 OR EXISTS(select 1 from TRXCONT TC

						where (( TC."Contract" = C.Id 

            and TC."ConsentType" = 0 ) OR (TC."PtLetter" = C.Id 

            and TC."ConsentType" = 1 ))

						and TC."OrigRecNo" = OrigRecNo

						and (trx_significant_change(Procedur, TC."Procedure", Site, TC."Site") = 0

						or trx_significant_change(Procedur, TC."Procedure", Site2, TC."Site") = 0) ))			--AX-2784.10633

					AND ROWNUM = 1;



					-- add result to shared table

					IF ContractCount = 0 THEN

						i := add_element(vConsent);

					END IF;

				END IF;

			END IF;

	  	END IF;

  	

  	

		-- consent missing, don't keep searching

		EXIT WHEN ReturnAll = 0 AND v_ConsentTable.COUNT > 0;	   

  	

  END LOOP;





  -- required consents were not on file

  Result := get_results();

  RETURN Result;

  

END;







-- E128792.4 - rewrote to return consent code(s) of missing consents

-- E45729 - returns 1 if the patient needs a treatment consent

-- E54824 - added PATIENT.RequireTxConsent requirement

-- E57005 - check to make sure site hasn't changed

FUNCTION pt_needs_tx_consent(patientid numeric, returnall numeric DEFAULT 0) RETURN character varying IS

  Result  VARCHAR2(4000);

  TempResult  VARCHAR2(4000);

  

  CURSOR TrxCur IS

	SELECT TRX."OrigRecNo", TRX."Procedure", TRX."Site", TRX."Site2", TRX."Patient", TRX."Producer"					--AX-2784.10633

      FROM PATIENT PT, TRX TRX, PROCEDUR P, PRODUCER D

	 WHERE PT."Patient" = PatientId

	   AND PT."Patient" = TRX."Patient"

	   AND TRX."Procedure" = P."Procedure"

	   AND TRX."Producer" = D."Producer" (+)

	   AND TRX."Type" IN (1,5)

	   AND TRX."Status" IN ('P','I')

	   AND TRX."Deleted" = 0

	   AND PT."RequireTxConsent" = 1

	   AND P."RequireTxConsent" = 1

	   AND NVL(D."RequireTxConsent", 1) = 1;

  



BEGIN

  Result := '';



  -- clear the array

  v_ConsentTable.DELETE;



  -- loop through all trx's for the patient

  FOR TrxRec in TrxCur

  LOOP

  

  		-- repeated calls to this routine will build up the shared table of missing consents

	   TempResult := trx_has_consent(TrxRec."OrigRecNo", TrxRec."Procedure", TrxRec."Site", TrxRec."Patient", SUBSTR(TrxRec."Producer", 1, 1), ReturnAll, 0, TrxRec."Site2");			--AX-2784.10633



		EXIT WHEN ReturnAll =0 AND v_ConsentTable.COUNT > 0;	   



  END LOOP;



  -- get result string

  Result := get_results();

  RETURN Result;

  

END;









-- B53917 - returns 1 if the trx needs a treatment consent

-- E54824 - added PATIENT.RequireTxConsent requirement

-- E57005 - check to make sure site hasn't changed

FUNCTION trx_needs_tx_consent(trxtype numeric, trxid numeric, trxtreatment numeric, includestatusc numeric) RETURN numeric IS

  Result NUMBER;



BEGIN

  Result := 0;



  -- clear the array

  v_ConsentTable.DELETE;



-- E131417 - Added ROWNUM clause

SELECT /*+ index(TRX, TRX_PRIMARY) */ COUNT(1)

  INTO Result

	FROM TRX TRX, PATIENT PT, PROCEDUR P, PRODUCER D

 WHERE TRX."Type" = TrxType

	AND TRX."Id" = TrxId

	AND TRX."Treatment" = TrxTreatment

	AND TRX."Patient" = PT."Patient"

	AND TRX."Procedure" = P."Procedure"

	AND TRX."Producer" = D."Producer" (+)

	AND TRX."Type" IN (1,5)

	AND (TRX."Status" IN ('P','I') 

		 OR (TRX."Status" = 'C' and IncludeStatusC <> 0))

	AND TRX."Deleted" = 0

	AND PT."RequireTxConsent" = 1

	AND P."RequireTxConsent" = 1

	AND NVL(D."RequireTxConsent", 1) = 1

	AND NOT (TRIM(trx_has_consent(TRX."OrigRecNo", TRX."Procedure", TRX."Site", TRX."Patient", SUBSTR(TRX."Producer", 1, 1), 0, 0, TRX."Site2")) IS NULL				--AX-2784.10633

	OR length(TRIM(trx_has_consent(TRX."OrigRecNo", TRX."Procedure", TRX."Site", TRX."Patient", SUBSTR(TRX."Producer", 1, 1), 0, 0, TRX."Site2"))) = 0)

	AND ROWNUM = 1;





  IF Result = 0 THEN

  	RETURN 0;

  ELSE 

  	RETURN 1;

  END IF;

  

END;









FUNCTION find_element(value character) RETURN numeric IS

	Result NUMBER;

BEGIN



	Result := 0;

	

  FOR i IN 1..v_ConsentTable.COUNT LOOP

      

      IF trim(v_ConsentTable(i)) = trim(value) THEN

      	Result := i;

      END IF;

      

      EXIT WHEN Result > 0;

      

  END LOOP;

	

  RETURN Result;	

END;







FUNCTION add_element(value character) RETURN numeric IS

	Result NUMBER;

	Found NUMBER;

BEGIN



	Result := -1;

	Found := find_element(value);

	



  IF Found = 0 THEN

		v_ConsentTable.EXTEND;

		v_ConsentTable(v_ConsentTable.COUNT) := trim(value);

  END IF;

  

  RETURN v_ConsentTable.COUNT;

	

END;







FUNCTION get_results() RETURN character varying IS

	Result  VARCHAR2(4000);



BEGIN

  Result := '';

  

  -- loop through results to build result string

  FOR i IN 1..v_ConsentTable.COUNT LOOP

      

      IF LENGTH(Result) > 0 THEN

      	Result := Result || ',';

      END IF;

      

      Result := Result || TRIM(v_ConsentTable(i));

      

  END LOOP;

  

  return Result;

END;







END;
;
CREATE OR REPLACE PACKAGE BODY custom_pa2template_pkg IS


FUNCTION custom_pa2template_html() RETURN clob IS
  Result1 CLOB;
  vFavicon VARCHAR2(50 );
  vOrganizationLogo VARCHAR2(50 );
BEGIN
   BEGIN
      SELECT REPLACE("Value", '~', '..')
      INTO vOrganizationLogo
      FROM ISETTING_PA2
      WHERE "Key" = 'SiteSetting.OrganizationLogo';
   END;

   BEGIN
      SELECT REPLACE("Value", '~', '..')
      INTO vFavicon
      FROM ISETTING_PA2
      WHERE "Key" = 'SiteSetting.Favicon';
   END;

  Result1 := ' <!DOCTYPE html>
<html lang=en>
<head>
    <link rel=icon type="image/x-icon" href="/PatientAccess/PAAdmin/Handler/ImageHandler.ashx?ImgId=' || vFavicon ||'" />
    <!--- <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel=stylesheet
          integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin=anonymous /> -->
     <link rel=stylesheet href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.0/css/all.min.css" rel=stylesheet>
    <link href="./Includes/Css/spinner.css" rel=stylesheet type="text/css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" type="text/javascript"></script>

    <!-- Bootstrap Icons CSS -->
    <link rel=stylesheet href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" />
    <script src="https://kit.fontawesome.com/95fbe47167.js" crossorigin=anonymous></script>

    <script src="./Includes/Scripts/spin.min.js" type="text/javascript"></script>
    <script src="./Includes/Scripts/general.240530.js" type="text/javascript"></script>
    <script src="./Includes/Scripts/iframe.231520.js" type="text/javascript"></script>

    <style>
        @import url("https://fonts.cdnfonts.com/css/helvetica-neue-55");
    </style>

    <meta name=viewport content="width=device-width, initial-scale=1">

    <link rel=stylesheet href="./Includes/Css/PA2.0/common.css" />
    <style type="text/css">
        /*Default CSS Replacement Area*/
        .dashboard-nav {
            position: fixed; left: 0; top: 0; bottom: 0; overflow: auto;
        }
    </style>
    <title></title>

    <script src="./Includes/Scripts/PA2.0/common.js" type="text/javascript"></script>
    <script type="text/javascript">
        // Default JS Replacement Area
    </script>

</head>
<body>

    <div class="dashboard-nav">

        <header>
            <a href="#!" class="menu-toggle"><i class="fas fa-bars"></i></a>
            <div class="university-logo-img-container">
                <img class="university-logo-img" src="/PatientAccess/PAAdmin/Handler/ImageHandler.ashx?ImgId=' || vOrganizationLogo || '" />
            <div/>
        </header>


        <nav class="dashboard-nav-list" style="flex-grow: 1;">

            <div class="dashboard-nav-list-items">

                <!-- Sidebar Section Items Replacement Area -->

                <hr id="sidebarDivider" class="text-gray" />

                <a href="#" onclick="submitLogoutForm()" class="dashboard-nav-item">
                    <i class="fa fa-right-from-bracket"></i> Sign out
                </a>
            </div>


        </nav>

        <div class="card p-2">
            <span id="firstLetter" class="profile-user-badge"></span>
            <span id="loggedInUserName" class=username><!--Logged In User Replacement String--></span>
        </div>


    </div>
    <div class="dashboard-app">
        <header class="dashboard-toolbar">
            <a href="#!" class="menu-toggle">
                <i class="fas fa-bars"></i>
            </a>
            <img class="university-logo-img" src="/PatientAccess/PAAdmin/Handler/ImageHandler.ashx?ImgId=' || vOrganizationLogo || '" />
        </header>
        <div class="dashboard-content">
            <div class="page-header">
                <span id=pagetitle></span>
                <style>
                    #AuthorRepresentDrp option:checked {
                        color: var(--pa2-text-color) !important;
                        background-color: var(--pa2-primary-color) !important;
                    }

                    #AuthorRepresentDrp option:hover {
                        color: var(--pa2-text-color) !important;
                        background-color: var(--pa2-primary-color) !important;
                    }
                </style>
                <div id="AuthorRepresentDiv" class="form-group">
                    <label for="AuthorRepresentDrp" id="AuthorRepresentDrpLbl" class="col-form-label form-label">View</label>
                    <select name="AuthorRepresentDrp" id="AuthorRepresentDrp" onchange="processDropdownChanged(this)" class="form-control">
                    </select>
                </div>
            </div>

            <div class="iframe-container">
                <!--Main Content Replacement Area-->
            </div>

            <span class=copyright>Copyright &copy; 2023 Henry Schein One, Exan Enterprises. All rights reserved.</span>

        </div>
    </div>

    <form id="logoutForm" method=post>
        <input type=hidden name="action" value=logout />
    </form>


</body>
</html>

 ';

  RETURN Result1;
END;


FUNCTION custom_pa2template_css() RETURN clob IS
  Result1 CLOB;
  vPrimaryColor VARCHAR2(50 );
  vTextColor VARCHAR2(50 );
BEGIN

    BEGIN
       SELECT "Value"
       INTO vPrimaryColor
       FROM ISETTING_PA2
       WHERE "Key" = 'SiteSetting.PrimaryColor';
    END;

    BEGIN
       SELECT "Value"
       INTO vTextColor
       FROM ISETTING_PA2
       WHERE "Key" = 'SiteSetting.TextColor';
    END;

  Result1 := '         :root {
            --pa2-primary-color: ' || vPrimaryColor || ';
            --pa2-text-color: ' || vTextColor || ';
            font-family: "Helvetica Neue" !important;
        }

        *, *::before, *::after {
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
        }

        iframe {
            border: 0;
        }

        html {
            font-family: "Helvetica Neue" !important;
            line-height: 1.15;
            -webkit-text-size-adjust: 100%;
            -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
            min-height: 100%;
            display: flex;
            flex-direction: column;
        }

        nav {
            display: block;
        }

        body {
            margin: 0;
            font-size: 1rem;
            font-weight: 400;
            line-height: 1.5;
            color: #000000;
            text-align: left;
            background-color: #F2F5FA;
            flex-grow: 1;
        }

        a {
            color: #3f84fc;
            text-decoration: none;
            background-color: transparent;
        }

        .dashboard-app {
            display: -webkit-box;
            display: -webkit-flex;
            display: -ms-flexbox;
            display: flex;
            -webkit-box-orient: vertical;
            -webkit-box-direction: normal;
            -webkit-flex-direction: column;
            -ms-flex-direction: column;
            flex-direction: column;
            -webkit-box-flex: 2;
            -webkit-flex-grow: 2;
            -ms-flex-positive: 2;
            flex-grow: 2;
            margin-top: 10px;
        }

        .dashboard-content {
            -webkit-box-flex: 2;
            -webkit-flex-grow: 2;
            -ms-flex-positive: 2;
            flex-grow: 2;
            height: 98vh;
            display: flex;
            flex-direction: column;
        }

        .dashboard-nav {
            width: 350px;
            position: fixed;
            left: 0;
            top: 0;
            bottom: 0;
            overflow: auto;
            background-color: #FFFFFF;
        }

        .dashboard-compact .dashboard-nav {
            display: none;
        }

        .dashboard-nav header {
            /*min-height: 84px;*/
            /*padding: 8px 27px;*/
            display: -webkit-box;
            display: -webkit-flex;
            display: -ms-flexbox;
            display: flex;
            -webkit-box-pack: center;
            -webkit-justify-content: center;
            -ms-flex-pack: center;
            justify-content: center;
            -webkit-box-align: center;
            -webkit-align-items: center;
            -ms-flex-align: center;
            align-items: center;
        }

        .dashboard-nav header .menu-toggle {
            display: none;
            margin-right: auto;
        }

        .dashboard-nav a {
            color: inherit;
        }

        .university-logo-img-container {
            /* width: 200px; */
        }

        .university-logo-img {
            /* max-width: 100%;
            max-height: 100%; */
            overflow: hidden;
            object-fit: contain;
        }

        .dashboard-nav-list {
            display: -webkit-box;
            display: -webkit-flex;
            display: -ms-flexbox;
            display: flex;
            -webkit-box-orient: vertical;
            -webkit-box-direction: normal;
            -webkit-flex-direction: column;
            -ms-flex-direction: column;
            flex-direction: column;
            justify-content: space-between;
            margin-top: 5%;
        }

        .dashboard-nav-item {
            min-height: 50px;
            padding: 8px 20px 8px 70px;
            display: -webkit-box;
            display: -webkit-flex;
            display: -ms-flexbox;
            display: flex;
            -webkit-box-align: center;
            -webkit-align-items: center;
            -ms-flex-align: center;
            align-items: center;
            letter-spacing: 0.02em;
            transition: ease-out 0.5s;
            border-radius: 10px;
            margin: 0 10px;
        }

        .dashboard-nav-item i {
            width: 36px;
            font-size: 19px;
            margin-left: -40px;
        }

        .active {
            background: var(--pa2-primary-color);
            color: var(--pa2-text-color) !important;
        }

        .dashboard-nav-dropdown {
            display: -webkit-box;
            display: -webkit-flex;
            display: -ms-flexbox;
            display: flex;
            -webkit-box-orient: vertical;
            -webkit-box-direction: normal;
            -webkit-flex-direction: column;
            -ms-flex-direction: column;
            flex-direction: column;
        }

        .dashboard-nav-dropdown.show {
            background: rgba(255, 255, 255, 0.04);
        }


        .dashboard-nav-dropdown.show > .dashboard-nav-dropdown-toggle:after {
            -webkit-transform: none;
            -o-transform: none;
            transform: none;
        }

        .dashboard-nav-dropdown.show > .dashboard-nav-dropdown-menu {
            display: -webkit-box;
            display: -webkit-flex;
            display: -ms-flexbox;
            display: flex;
        }

        .dashboard-nav-dropdown-toggle:after {
            content: "";
            margin-left: auto;
            display: inline-block;
            width: 0;
            height: 0;
            border-left: 7px solid transparent;
            border-right: 7px solid transparent;
            border-top: 7px solid rgba(81, 81, 81, 0.8);
            -webkit-transform: rotate(90deg);
            -o-transform: rotate(90deg);
            transform: rotate(90deg);
        }

        .dashboard-nav .dashboard-nav-dropdown-toggle:after {
            border-top-color: inherit;
            cursor: pointer;
        }

        .dashboard-nav-dropdown-menu {
            display: none;
            -webkit-box-orient: vertical;
            -webkit-box-direction: normal;
            -webkit-flex-direction: column;
            -ms-flex-direction: column;
            flex-direction: column;
            border-radius: 10px;
            margin: 0 10px;
        }

        .dashboard-nav-dropdown-item {
            min-height: 40px;
            padding: 8px 20px 8px 70px;
            display: -webkit-box;
            display: -webkit-flex;
            display: -ms-flexbox;
            display: flex;
            -webkit-box-align: center;
            -webkit-align-items: center;
            -ms-flex-align: center;
            align-items: center;
            transition: ease-out 0.5s;
            border-radius: 10px;
            margin: 0 10px;
        }

        .menu-toggle {
            position: relative;
            width: 42px;
            height: 42px;
            display: -webkit-box;
            display: -webkit-flex;
            display: -ms-flexbox;
            display: flex;
            -webkit-box-align: center;
            -webkit-align-items: center;
            -ms-flex-align: center;
            align-items: center;
            -webkit-box-pack: center;
            -webkit-justify-content: center;
            -ms-flex-pack: center;
            justify-content: center;
            color: #443ea2;
        }

        .menu-toggle:active, .menu-toggle:focus {
            text-decoration: none;
            color: #875de5;
        }

        .menu-toggle i {
            font-size: 20px;
        }

        .dashboard-toolbar {
            min-height: 84px;
            background-color: #FFFFFF;
            display: -webkit-box;
            display: -webkit-flex;
            display: -ms-flexbox;
            display: flex;
            -webkit-box-align: center;
            -webkit-align-items: center;
            -ms-flex-align: center;
            align-items: center;
            padding: 8px 27px;
            position: fixed;
            top: 0;
            right: 0;
            left: 0;
            z-index: 1000;
        }

        .nav-item-divider {
            height: 1px;
            margin: 1rem 0;
            overflow: hidden;
            background-color: rgba(236, 238, 239, 0.3);
        }

        .card {
            margin: 25px 20px 5px 25px;
            display: flex;
            flex-direction: row;
            justify-content: flex-start;
            align-items: center;
            margin-top: auto;
        }

        .profile-user-badge {
            display: inline-block;
            background-color: var(--pa2-primary-color);
            color: var(--pa2-text-color);
            border-radius: 50%;
            font-size: 20px;
            line-height: 30px;
            width: 30px;
            height: 30px;
            text-align: center;
            text-transform: uppercase;
        }

        .username {
            padding-left: 1rem;
        }

        .page-header {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            align-items: center;
            margin: 1.5%;
        }

        .iframe-container {
            height: 83%;
            width: 97%;
            margin: 0px 1.5%;
            padding: 0;
        }

        .copyright {
            font-size: 11px;
            text-align: center;
            margin-top: auto;
        }

        #pagetitle {
            font-family: inherit;
            font-size: 26px;
            font-weight: 500;
            line-height: 40px;
        }

        #AuthorRepresentDiv {
            display: none;
        }

        #AuthorRepresentDrp,
        #AuthorRepresentDrp option,
        #AuthorRepresentDrpLbl {
            font-weight: 400;
        }

        #AuthorRepresentDrp,
        #AuthorRepresentDrp option {
            padding-right: 5px;
        }

        #AuthorRepresentDrpLbl {
            margin-right: 0.5rem;
        }

        @media (max-width: 1200px) {
            #AuthorRepresentDrp,
            #AuthorRepresentDrp option {
                text-overflow: ellipsis;
                max-width: 88%;
            }

            #AuthorRepresentDiv {
                justify-content: flex-end;
                overflow-x: auto;
                margin: 10px 0;
            }

            .page-header {
                display: block;
            }
        }

        @media (max-width: 992px) {
            .dashboard-nav {
                display: none;
                position: fixed;
                top: 0;
                right: 0;
                left: 0;
                bottom: 0;
                /*z-index: 1070;*/
                width: 100%;
            }

            .dashboard-nav.mobile-show {
                display: flex;
                flex-direction: column;
            }

            .dashboard-nav header {
                justify-content: flex-start;
            }

            .page-header {
                margin: 80px 10px 10px 1.5%;
            }

            .dashboard-nav header .menu-toggle {
                display: -webkit-box;
                display: -webkit-flex;
                display: -ms-flexbox;
                display: flex;
                margin-right: initial;
            }
        }

        @media (min-width: 992px) {
            .dashboard-toolbar {
                display: none;
            }

            .dashboard-compact .dashboard-toolbar {
                left: 0;
            }

            .dashboard-nav {
                display: flex;
                flex-direction: column;
            }

            .dashboard-app {
                margin-left: 350px;
            }

            .dashboard-compact .dashboard-app {
                margin-left: 0;
            }
        }

        @media only screen and (max-width: 575.98px) {
            .university-logo-container {
                text-align: center;
                height: 12%;
                align-items: center;
                justify-content: center;
                display: flex;
            }

            .university-logo-img {
                width: auto;
                height: 5rem;
            }
        }

        @media (min-width: 576px) {
            .university-logo-container {
                width: auto;
                overflow: hidden;
                display: flex;
                flex-direction: column-reverse;
                align-items: center;
                margin-top: 13%;
            }

            .university-logo-img {
                width: auto;
                height: 5rem;
            }
        }
        @media (max-height: 900px) {
            .dashboard-nav.mobile-show {
                display: flex;
                flex-direction: column;
            }
        }
 ';

  RETURN Result1;
END;


FUNCTION custom_pa2template_js() RETURN clob IS
  Result1 CLOB;
BEGIN

  Result1 := '         const mobileScreen = window.matchMedia("(max-width: 990px )");
        $(document).ready(function () {
            document.getElementById(pagetitle).innerHTML = document.title;

            $("#firstLetter").text($("#loggedInUserName").text().charAt(0));

            $(".dashboard-nav-dropdown-toggle").click(function () {
                $(this).closest(".dashboard-nav-dropdown")
                    .toggleClass("show")
                    .find(".dashboard-nav-dropdown")
                    .removeClass("show");
                $(this).parent()
                    .siblings()
                    .removeClass("show");
            });

            $(".menu-toggle").click(function () {
                if (mobileScreen.matches) {
                    $(".dashboard-nav").toggleClass("mobile-show");
                } else {
                    $(".dashboard").toggleClass("dashboard-compact");
                }
            });

            var users = $("#AuthorRepresentDrp");
            var viewDiv = $("#AuthorRepresentDiv");
            $.ajax({
                url: "/PatientAccess/Default.aspx/GetAuthorizedRepresentatives",
                dataType: json,
                type: POST,
                contentType: "application/json;charset=utf-8",
                success: function (data) {
                    if (data.d[2].length > 0) {
                        $(data.d[2]).each(function (index, obj) {
                            var user = $("<option></option>");
                            user.attr(value, obj.FullName);
                            user.text(obj.FullName);
                            user.val(obj.Iuser);
                            users.append(user);
                        });
                        users.val(parseInt(data.d[1].iUserCurrent));
                        viewDiv.css(display, flex);
                    }
                },
                error: function (err) {
                    console.log(err);
                    alert("An error occurred while retrieving patient list. ");
                }
            });
        });

        function processDropdownChanged(element) {

            var elementVal = { "AuthorRepresentDrpVal": element.value };
            $.ajax({
                url: "/PatientAccess/Default.aspx/AuthorRepresentDrpChanged",
                dataType: json,
                type: POST,
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(elementVal),
                success: function (data) {
                    element.value = parseInt(data.d);
                },
                error: function (err) {
                    console.log(err);
                    alert("An error occurred while changing users.");
                }
            });
            if (newCheckCanLeavePage()) {
                refreshIFrame();
            }
            // else { //May be useful later if we rework the Confirm window and it returns true/false instead of returning nothing
            //     $.ajax({
            //         url: "/PatientAccess/Default.aspx/GetCurrentUserId",
            //         dataType: json,
            //         type: POST,
            //         contentType: "application/json; charset=utf-8",
            //         success: function (data) {
            //                 element.value = data.d;
            //         },
            //         error: function (err) {
            //             console.log(err);
            //             alert("An error occurred while changing users.");
            //         }
            //     });

            // }
        }

        function refreshIFrame() {
        parent.window.location.href = "/PatientAccess/Default.aspx";
        window.location.reload();
        }

        function submitLogoutForm() {
            document.getElementById("logoutForm").submit();
            return false;
        }

        function cancelPageRedirects() {
            if (mobileScreen.matches) {
                $(".dashboard-nav").toggleClass("mobile-show");
            } else {
                $(".dashboard").toggleClass("dashboard-compact");
            }
        }
 ';

  RETURN Result1;
END;


END;
CREATE OR REPLACE PACKAGE BODY dbms_lob_s IS



  PROCEDURE createtemporary(INOUT lob_loc clob, IN cache boolean, IN dur integer DEFAULT 0) IS

  BEGIN

		lob_loc := '';

  END;



  PROCEDURE append(INOUT dest_lob clob, IN src_lob clob) IS

  BEGIN

		dest_lob := dest_lob || src_lob; 

  END;



END;
CREATE OR REPLACE PACKAGE BODY dept_pkg IS



-- Function to create the "where clause" for a defined Department

-- Input: Department - Department to run for (from DEPT table)

--        t_alias - Table Alias to use for TRX/HISTORY

--	  p_alias - Table Alias to use for PRODUCER

--    pt_alias - Table Alias to use for PATIENT (E32116)

-- Output: Returns a string representing the "where clause" to use in SQL queries



FUNCTION deptwhere(department character, t_alias character, p_alias character, pt_alias character) RETURN clob IS

  TYPE field_array IS VARRAY (25) of VARCHAR2(100);

  PrevType NUMBER := -1;

  WhereStr CLOB := NULL;

  FieldName field_array;

  OpenBracket BOOLEAN := FALSE;

  

CURSOR C1 IS

 SELECT * FROM DEPTDEF WHERE "Department"=Department order by "Type","Condition";



BEGIN

  FieldName := field_array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23);

  FieldName(1) := t_alias || '."Discipline"';

  FieldName(2) := t_alias || '."Procedure"';

  FieldName(3) := t_alias || '."Practice"';

  FieldName(4) := t_alias || '."ClaimDoctor"';

  FieldName(5) := t_alias || '."Location"';

  FieldName(6) := t_alias || '."EntryUser"';

  FieldName(7) := t_alias || '."AppUser"';

  FieldName(8) := t_alias || '."Custom1"';

  FieldName(9) := t_alias || '."Custom2"';

  FieldName(10) := t_alias || '."Producer"';

  FieldName(11) := p_alias || '."TypeCode"';

  FieldName(12) := p_alias || '."PGroup"';

  FieldName(13) := p_alias || '."Year"';

  FieldName(14) := pt_alias || '."CustomCode1"';

  FieldName(15) := pt_alias || '."CustomCode2"';

  FieldName(16) := pt_alias || '."CustomCode3"';

  FieldName(17) := pt_alias || '."CustomCode4"';

  FieldName(18) := pt_alias || '."CustomCode5"';

  FieldName(19) := pt_alias || '."CustomCode6"';

  FieldName(20) := pt_alias || '."CustomCode7"';

  FieldName(21) := pt_alias || '."CustomCode8"';

  FieldName(22) := pt_alias || '."CustomCode9"';

  FieldName(23) := pt_alias || '."CustomCode10"';

  

  for p in C1 LOOP

    

    if PrevType = p."Type" then

    

      if p."Condition" = 0 then

        WhereStr := WhereStr || ' OR ' ||FieldName(CAST(p."Type" AS INTEGER)+1)||'=''' ||p."Criteria1"||'''';

      elsif p."Condition" = 1 then

      	WhereStr := WhereStr || ' OR ' ||FieldName(CAST(p."Type" AS INTEGER)+1)||' BETWEEN ''' ||p."Criteria1"||''' AND '''||p."Criteria2"||'''';

      else

        if OpenBracket then

          WhereStr := WhereStr || ')';

          OpenBracket := FALSE;

        end if;

		if p."Type" = 10 or p."Type" = 11 or p."Type" = 12 then											--AX-7995.10620; AX-7995.10799

			WhereStr := WhereStr || ' AND (' ||FieldName(CAST(p."Type" AS INTEGER)+1)|| '!=''' ||p."Criteria1"||''' OR TRIM(' ||FieldName(CAST(p."Type" AS INTEGER)+1)||') IS NULL )';

		else

			WhereStr := WhereStr || ' AND (' ||FieldName(CAST(p."Type" AS INTEGER)+1)|| '!=''' ||p."Criteria1"||''')';

		end if;

      end if;

    

    else

    

      if PrevType >= 0 then

	if OpenBracket then

	  WhereStr := WhereStr || ')';

	  OpenBracket := FALSE;

        end if;

        WhereStr := WhereStr || ' AND ';

      end if;

      

      if p."Condition" < 2 then

 	WhereStr := WhereStr || '(';

 	OpenBracket :=TRUE;

      end if;

      

      if p."Condition" = 0 then

        WhereStr := WhereStr ||FieldName(CAST(p."Type" AS INTEGER)+1)||'=''' ||p."Criteria1"||'''';

      elsif p."Condition" = 1 then

      	WhereStr := WhereStr ||FieldName(CAST(p."Type" AS INTEGER)+1)||' BETWEEN ''' ||p."Criteria1"||''' AND '''||p."Criteria2"||'''';

      else

  		if p."Type" = 10 or p."Type" = 11 or p."Type" = 12 then											--AX-7995.10620; AX-7995.10799

	        WhereStr := WhereStr || ' (' ||FieldName(CAST(p."Type" AS INTEGER)+1)|| '!=''' ||p."Criteria1"||''' OR TRIM(' ||FieldName(CAST(p."Type" AS INTEGER)+1)||') IS NULL)';

		else

	        WhereStr := WhereStr ||FieldName(CAST(p."Type" AS INTEGER)+1)|| '!=''' ||p."Criteria1"||'''';

		end if; 

      end if;

    

    end if;

    

    PrevType := p."Type";

    

   END LOOP;

   

   if PrevType >= 0 and OpenBracket then

     WhereStr := WhereStr || ')';

     OpenBracket := FALSE;

   end if;

   

--   if PrevType >= 0 then

--     WhereStr := '(' || WhereStr || ')';

--   end if;



   IF WhereStr IS NULL THEN	-- E63541

	 WhereStr := '1=1';

   END IF;

     

 RETURN WhereStr;

END;





-- Function to create the "where clause" for a defined Department 

--  Formatted to work with Crystal Reports Selection formula

-- Input: Department - Department to run for (from DEPT table)

--        t_alias - Table Alias to use for TRX/HISTORY

--	  p_alias - Table Alias to use for PRODUCER

--    pt_alias - Table Alias to use for PATIENT (E32116)

-- Output: Returns a string representing the "where clause" to use in SQL queries



FUNCTION deptwherecrystal(department character, t_alias character, p_alias character, pt_alias character) RETURN clob IS

  TYPE field_array IS VARRAY (25) of VARCHAR2(100);

  PrevType NUMBER := -1;

  WhereStr CLOB := NULL;

  FieldName field_array;

  FieldType field_array;	-- 1 = string, 2 = number

  OpenBracket BOOLEAN := FALSE;

  

CURSOR C1 IS

 SELECT * FROM DEPTDEF WHERE "Department"=Department order by "Type","Condition";



BEGIN

  FieldName := field_array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23);

  FieldName(1) := '{' || t_alias || '.Discipline}';

  FieldName(2) := '{' || t_alias || '.Procedure}';

  FieldName(3) := '{' || t_alias || '.Practice}';

  FieldName(4) := '{' || t_alias || '.ClaimDoctor}';

  FieldName(5) := '{' || t_alias || '.Location}';

  FieldName(6) := '{' || t_alias || '.EntryUser}';

  FieldName(7) := '{' || t_alias || '.AppUser}';

  FieldName(8) := '{' || t_alias || '.Custom1}';

  FieldName(9) := '{' || t_alias || '.Custom2}';

  FieldName(10) := '{' || t_alias || '.Producer}';

  FieldName(11) := '{' || p_alias || '.TypeCode}';

  FieldName(12) := '{' || p_alias || '.PGroup}';

  FieldName(13) := '{' || p_alias || '.Year}';

  FieldName(14) := '{' || pt_alias || '.CustomCode1}';

  FieldName(15) := '{' || pt_alias || '.CustomCode2}';

  FieldName(16) := '{' || pt_alias || '.CustomCode3}';

  FieldName(17) := '{' || pt_alias || '.CustomCode4}';

  FieldName(18) := '{' || pt_alias || '.CustomCode5}';

  FieldName(19) := '{' || pt_alias || '.CustomCode6}';

  FieldName(20) := '{' || pt_alias || '.CustomCode7}';

  FieldName(21) := '{' || pt_alias || '.CustomCode8}';

  FieldName(22) := '{' || pt_alias || '.CustomCode9}';

  FieldName(23) := '{' || pt_alias || '.CustomCode10}';



  FieldType := field_array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23);

  FieldType(1) := 1;

  FieldType(2) := 1;

  FieldType(3) := 2;

  FieldType(4) := 1;

  FieldType(5) := 1;

  FieldType(6) := 2;

  FieldType(7) := 2;

  FieldType(8) := 1;

  FieldType(9) := 1;

  FieldType(10) :=1;

  FieldType(11) := 1;

  FieldType(12) := 1;

  FieldType(13) := 2;

  FieldType(14) := 1;

  FieldType(15) := 1;

  FieldType(16) := 1;

  FieldType(17) := 1;

  FieldType(18) := 1;

  FieldType(19) := 1;

  FieldType(20) := 1;

  FieldType(21) := 1;

  FieldType(22) := 1;

  FieldType(23) := 1;



  for p in C1 LOOP

    

    if PrevType = p."Type" then

    

      if FieldType(CAST(p."Type" AS INTEGER)+1) = 1 then

		  if p."Condition" = 0 then

			WhereStr := WhereStr || ' OR ' ||FieldName(CAST(p."Type" AS INTEGER)+1)||'=''' ||p."Criteria1"||'''';

		  elsif p."Condition" = 1 then

			WhereStr := WhereStr || ' OR ' ||FieldName(CAST(p."Type" AS INTEGER)+1)||' >= ''' ||p."Criteria1"||''' AND '||FieldName(CAST(p."Type" AS INTEGER)+1)||' <= ''' ||p."Criteria2"||'''';

		  else

			if OpenBracket then

			  WhereStr := WhereStr || ')';

			  OpenBracket := FALSE;

			end if;

	  		if p."Type" = 10 or p."Type" = 11 or p."Type" = 12 then											--AX-7995.10620; AX-7995.10799; AX-jso

				WhereStr := WhereStr || ' AND ( IsNull(' ||FieldName(CAST(p."Type" AS INTEGER)+1)||') OR ' ||FieldName(CAST(p."Type" AS INTEGER)+1)|| '<>''' ||p."Criteria1"||''')';

			else

				WhereStr := WhereStr || ' AND (' ||FieldName(CAST(p."Type" AS INTEGER)+1)|| '<>''' ||p."Criteria1"||''')';

			end if;

		  end if;

 	  else

		  if p."Condition" = 0 then

			WhereStr := WhereStr || ' OR ' ||FieldName(CAST(p."Type" AS INTEGER)+1)||'=' ||p."Criteria1";

		  elsif p."Condition" = 1 then

			WhereStr := WhereStr || ' OR ' ||FieldName(CAST(p."Type" AS INTEGER)+1)||' >= ' ||p."Criteria1"||' AND '||FieldName(CAST(p."Type" AS INTEGER)+1)||' <= '||p."Criteria2";

		  else

			if OpenBracket then

			  WhereStr := WhereStr || ')';

			  OpenBracket := FALSE;

			end if;

	  		if p."Type" = 10 or p."Type" = 11 or p."Type" = 12 then											--AX-7995.10620; AX-7995.10799; AX-1995.10820

				WhereStr := WhereStr || ' AND (IsNull('||FieldName(CAST(p."Type" AS INTEGER)+1)|| ') OR' ||FieldName(CAST(p."Type" AS INTEGER)+1)|| '<>' ||p."Criteria1"||'  )';

			else

				WhereStr := WhereStr || ' AND (' ||FieldName(CAST(p."Type" AS INTEGER)+1)|| '<>' ||p."Criteria1"||')';

			end if;

		  end if;

	  end if; 	  

    

    else

    

      if PrevType >= 0 then

	if OpenBracket then

	  WhereStr := WhereStr || ')';

	  OpenBracket := FALSE;

        end if;

        WhereStr := WhereStr || ' AND ';

      end if;

      

      if p."Condition" < 2 then

 	WhereStr := WhereStr || '(';

 	OpenBracket :=TRUE;

      end if;

      

      if FieldType(CAST(p."Type" AS INTEGER)+1) = 1 then

		  if p."Condition" = 0 then

			WhereStr := WhereStr ||FieldName(CAST(p."Type" AS INTEGER)+1)||'=''' ||p."Criteria1"||'''';

		  elsif p."Condition" = 1 then

			WhereStr := WhereStr ||FieldName(CAST(p."Type" AS INTEGER)+1)||' >= ''' ||p."Criteria1"||''' AND '||FieldName(CAST(p."Type" AS INTEGER)+1)||' <= '''||p."Criteria2"||'''';

		  else

	  		if p."Type" = 10 or p."Type" = 11 or p."Type" = 12 then											--AX-7995.10620; AX-7995.10799; AX-1995.10820

				WhereStr := WhereStr || ' ( IsNull(' ||FieldName(CAST(p."Type" AS INTEGER)+1)||') OR' ||FieldName(CAST(p."Type" AS INTEGER)+1)|| '<>''' ||p."Criteria1"||''')';

			else

				WhereStr := WhereStr ||FieldName(CAST(p."Type" AS INTEGER)+1)|| '<>''' ||p."Criteria1"||'''';

			end if;

		  end if;

      else	

		  if p."Condition" = 0 then

			WhereStr := WhereStr ||FieldName(CAST(p."Type" AS INTEGER)+1)||'=' ||p."Criteria1";

		  elsif p."Condition" = 1 then

			WhereStr := WhereStr ||FieldName(CAST(p."Type" AS INTEGER)+1)||' >= ' ||p."Criteria1"||' AND '||FieldName(CAST(p."Type" AS INTEGER)+1)||' <= ' ||p."Criteria2";

		  else

	  		if p."Type" = 10 or p."Type" = 11 or p."Type" = 12 then											--AX-7995.10620; AX-7995.10799; AX-1995.10820

				WhereStr := WhereStr ||' (IsNull('||FieldName(CAST(p."Type" AS INTEGER)+1)|| ') OR ' ||FieldName(CAST(p."Type" AS INTEGER)+1)|| '<>' ||p."Criteria1" ||' )';

			else

				WhereStr := WhereStr ||FieldName(CAST(p."Type" AS INTEGER)+1)|| '<>' ||p."Criteria1";

			end if;

		  end if;

      end if;

      

    end if;

    

    PrevType := p."Type";

    

   END LOOP;

   

   if PrevType >= 0 and OpenBracket then

     WhereStr := WhereStr || ')';

     OpenBracket := FALSE;

   end if;

   

   IF WhereStr IS NULL THEN	-- E63541

	 WhereStr := '1=1';

   END IF;

     

 RETURN WhereStr;

END;





-- Function that returns a Department's AR as at a specified date.

-- Input: AsAtDate - date to run for

--	  Department - Department to run for (from DEPT table)

-- Output: Returns single value representing Patient + Insurance AR for the date

-- E32116 - added patient custom codes

FUNCTION arasat_dept(asatdate timestamp without time zone, department character) RETURN numeric IS

  PtTotal NUMBER := 0;

  InsTotal NUMBER := 0;

  AR NUMBER := 0;

  WhereStr CLOB;

  SQLStmt CLOB;

      

BEGIN



 BEGIN

  SELECT DEPTWHERE (Department, 'H', 'P', 'PT') into WhereStr from dual;

 EXCEPTION

   WHEN NO_DATA_FOUND THEN

     RETURN 0;

 END;

 IF WhereStr IS NULL THEN

   RETURN 0;

 END IF;

 

 BEGIN

  -- E00691 added trunc on ModifiedDate, E63541 added /*+ PARALLEL(H) */

  -- B74933 added HISTORY_AR hint

  -- B74933.2 fixed hint

  SQLStmt := 'SELECT /*+ PARALLEL(H) */ SUM(H."Total"-H."InsTotal"+H."PtAdj"+H."InsTransfer"-H."Payed"),

    SUM(H."InsTotal"-H."InsAdj"-H."InsTransfer"-H."InsPayed")

    FROM HISTORY H, PRODUCER P, PATIENT PT WHERE H."Type"in(1,2) AND P."Producer"(+)=H."Producer" 

    AND PT."Patient" = H."Patient" AND H."TreatmentDate"<=:1 AND H."Deleted"=0 AND H."OrthoStatus"<>1

    AND H."History"=(SELECT /*+index(H2 HISTORY_AR)*/ max(H2."History") FROM HISTORY H2 WHERE H2."OrigRecNo"=H."OrigRecNo"

    AND trunc(H2."ModifiedDate")<=:2) AND '|| WhereStr;

 EXECUTE IMMEDIATE SQLStmt INTO PtTotal, InsTotal USING AsAtDate,AsAtDate;

 EXCEPTION

   WHEN NO_DATA_FOUND THEN

    PtTotal := 0;

    InsTotal := 0;

 END;



 IF PtTotal IS NULL THEN

    PtTotal := 0; 

 END IF;

 IF InsTotal IS NULL THEN

    InsTotal := 0; 

 END IF;

 

 AR := PtTotal + InsTotal;       

 RETURN AR;

END;



-- E69509

-- Function that returns the last History record prior to a cutoffdate for a given OrigRecNo

-- Input: OrigRecNo - OrigRecNo of History record

--		CutoffDate - date that the last HISTORY record's modified date must be less than

-- Output: returns number which points to last History record prior to curoff date for given OrigRecNo

FUNCTION historyprev(origrecno numeric, cutoffdate timestamp without time zone) RETURN numeric IS

	vHistoryPrev HISTORY."History"%TYPE;

BEGIN



	SELECT /*+index(H4 HISTORY_AR)*/ MAX(H4."History") INTO vHistoryPrev FROM HISTORY H4 WHERE 

	   H4."OrigRecNo"=OrigRecNo AND H4."Type" in (1,2) AND TRUNC(H4."ModifiedDate") < TRUNC(CutoffDate);

	RETURN NVL(vHistoryPrev,0);



END;



-- E32116 - added patient custom codes

PROCEDURE create_dept_txs(IN batch numeric, IN fromdate timestamp without time zone, IN todate timestamp without time zone, IN department character varying) IS

  WhereStr CLOB;

  WhereStr2 CLOB;

  WhereStr3 CLOB;

  SQLStmt CLOB;

  TYPE DeptTxCurTyp IS REF CURSOR;

  depttx_cv   DeptTxCurTyp;

  HistoryL NUMBER;

  InDeptL NUMBER; 

  HistoryP NUMBER;

  InDeptP NUMBER;

  loopcnt pls_integer;

  iHasProdCond  NUMBER := 0;	--E63541

  

BEGIN

 BEGIN

  SELECT DEPTWHERE (Department, 'H', 'P', 'PT') into WhereStr from dual;

 EXCEPTION

   WHEN NO_DATA_FOUND THEN

     RETURN;

 END;

 IF WhereStr IS NULL THEN

   RETURN;

 END IF;



 SELECT REPLACE (WhereStr, 'H."', 'H2."') into WhereStr2 from dual;

 SELECT REPLACE (WhereStr2, 'P."', 'P2."') into WhereStr2 from dual;

 SELECT REPLACE (WhereStr2, 'PT."', 'PT2."') into WhereStr2 from dual;

 SELECT REPLACE (WhereStr, '''', '''''') into WhereStr3 from dual;



 SELECT INSTR (WhereStr, 'P."') into iHasProdCond from dual;	--E63541

 

 BEGIN

   

--Last History in range for DEPT (merged 2 statements into 1)

  -- E00691 added trunc on ModifiedDate

  -- E63541 added if iHasProdCond = 0

  -- B65376 added in patient table

  -- B74933 added HISTORY_AR hint

  if iHasProdCond = 0 then



   SQLStmt := 'Select H."History", 1, DEPT_PKG.HistoryPrev(H."OrigRecNo", :1), DEPT_PKG.TxInDept(DEPT_PKG.HistoryPrev(H."OrigRecNo",:2),'''||WhereStr3||''')

	from history H, patient PT

	where

	 PT."Patient"=H."Patient" and

	 H."History"=(SELECT /*+index(H3 HISTORY_AR)*/ max(H3."History") FROM HISTORY H3 WHERE 

	  H3."OrigRecNo"=H."OrigRecNo" AND H3."Type" in (1,2) AND trunc(H3."ModifiedDate") BETWEEN :3 AND :4)

	 AND '||WhereStr;



  else



  SQLStmt := 'Select H."History", 1, DEPT_PKG.HistoryPrev(H."OrigRecNo", :1), DEPT_PKG.TxInDept(DEPT_PKG.HistoryPrev(H."OrigRecNo", :2),'''||WhereStr3||''')

  from history H, producer P, patient PT

   where

    P."Producer"(+)=H."Producer" and PT."Patient"=H."Patient" and 

    H."History"=(SELECT /*+index(H3 HISTORY_AR)*/ max(H3."History") FROM HISTORY H3 WHERE 

      H3."OrigRecNo"=H."OrigRecNo" AND H3."Type" in (1,2) AND trunc(H3."ModifiedDate") BETWEEN :3 AND :4)

    AND '||WhereStr;

  end if;



  OPEN depttx_cv FOR SQLStmt USING FromDate, FromDate, FromDate, ToDate;

  LOOP

    FETCH depttx_cv INTO HistoryL, InDeptL, HistoryP, InDeptP;

    EXIT WHEN depttx_cv%NOTFOUND;

    EXECUTE IMMEDIATE 'INSERT INTO DEPTTX VALUES (:1,:2,:3,:4,:5,:6)' 

      USING Batch, Department, HistoryL, InDeptL, HistoryP, InDeptP;



    loopcnt:=loopcnt+1;

    if mod(loopcnt,5000)=0 then

      commit;

    end if;

      

  END LOOP;

  CLOSE depttx_cv;

    

 END;



 BEGIN

   

--Last History in range not for DEPT, with History prior to range for DEPT

  -- E00691 added trunc on ModifiedDate, E63541 added if iHasProdCond = 0, B65376 added in patient PT and patient PT2

  -- B74933 added index hint

  -- B74933.2 fixed hint

  if iHasProdCond = 0 then



   SQLStmt := 'select H."History", 0, H2."History", 1

	from history H, history H2, patient PT, patient PT2 

	where 

	 H2."OrigRecNo"=H."OrigRecNo"

	 and PT."Patient" = H."Patient" and PT2."Patient" = H2."Patient"

	 AND H."History"=(SELECT /*+index(H3 HISTORY_AR)*/ max(H3."History") FROM HISTORY H3 WHERE 

	 H3."OrigRecNo"=H."OrigRecNo" AND H3."Type" in (1,2) AND trunc(H3."ModifiedDate") BETWEEN :1 AND :2)

	 AND NOT ('|| WhereStr ||')

	 AND H2."History"=(SELECT /*+index(H4 HISTORY_AR)*/ max(H4."History") FROM HISTORY H4 WHERE 

	 H4."OrigRecNo"=H2."OrigRecNo" AND H4."Type" in (1,2) AND trunc(H4."ModifiedDate") < :3)

	 AND '|| WhereStr2;



  else  

  

  SQLStmt := 'select H."History", 0, H2."History", 1

 from history H, producer P, history H2, producer P2, patient PT, patient PT2

 where P."Producer"(+)=H."Producer" and P2."Producer"(+)=H2."Producer" 

 and PT."Patient" = H."Patient" and PT2."Patient" = H2."Patient"

 and H2."OrigRecNo"=H."OrigRecNo"

 AND H."History"=(SELECT /*+index(H3 HISTORY_AR)*/ max(H3."History") FROM HISTORY H3 WHERE 

 H3."OrigRecNo"=H."OrigRecNo" AND H3."Type" in (1,2) AND trunc(H3."ModifiedDate") BETWEEN :1 AND :2)

 AND NOT ('|| WhereStr ||')

 AND H2."History"=(SELECT /*+index(H4 HISTORY_AR)*/ max(H4."History") FROM HISTORY H4 WHERE 

 H4."OrigRecNo"=H2."OrigRecNo" AND H4."Type" in (1,2) AND trunc(H4."ModifiedDate") < :3)

 AND '|| WhereStr2;



  end if;

  

  OPEN depttx_cv FOR SQLStmt USING FromDate, ToDate, FromDate;

  LOOP

    FETCH depttx_cv INTO HistoryL, InDeptL, HistoryP, InDeptP;

    EXIT WHEN depttx_cv%NOTFOUND;

    EXECUTE IMMEDIATE 'INSERT INTO DEPTTX VALUES (:1,:2,:3,:4,:5,:6)' 

      USING Batch, Department, HistoryL, InDeptL, HistoryP, InDeptP;



    loopcnt:=loopcnt+1;

    if mod(loopcnt,5000)=0 then

      commit;

    end if;



  END LOOP;

  CLOSE depttx_cv;

    

 END;

 commit; 

END;





PROCEDURE delete_dept_txs(IN batch numeric) IS

 loopcnt pls_integer;

 batchcnt pls_integer;

BEGIN

 SELECT ceil(COUNT(*)/5000) INTO batchcnt FROM DEPTTX WHERE "Batch"=Batch;

 for loopcnt in 1..batchcnt LOOP

  DELETE FROM DEPTTX WHERE "Batch"=Batch and rownum<5000;

  commit;

 END LOOP;

END;





-- E32116 - added patient custom codes

FUNCTION txindept(historyid numeric, wherestr character) RETURN numeric IS

  InDept NUMBER := 1;

  HistoryRecId NUMBER;

  SQLStmt CLOB;

    

BEGIN

   

 IF HistoryId = 0 THEN

    RETURN 0;

 END IF;



 IF WhereStr = '1=1' THEN	-- E63541

	RETURN 1;

 END IF;



 BEGIN

  SQLStmt := 'SELECT H."History" FROM HISTORY H, PRODUCER P, PATIENT PT WHERE 

   H."History"=:1 AND P."Producer"(+)=H."Producer" AND PT."Patient" = H."Patient" AND  '|| WhereStr;

  EXECUTE IMMEDIATE SQLStmt INTO HistoryRecId USING HistoryId;



  EXCEPTION

   WHEN NO_DATA_FOUND THEN

    InDept := 0;

 END;



 RETURN InDept;

END;



END;
CREATE OR REPLACE PACKAGE BODY dpsi_pkg IS


FUNCTION getptpsr(patientid numeric, sextant numeric) RETURN numeric IS
 PtPerioId NUMBER := 0;
 PSRScore  NUMBER := 0;
BEGIN
 SELECT max(P."PtPerio") INTO PtPerioId FROM PTPERIO P			-- E33252
 WHERE  P."Patient"=PatientId AND P."Deleted"=0 AND P."ChartDate" =
 (SELECT max(P2."ChartDate") FROM PTPERIO P2 where P2."Patient"=PatientId AND P2."Deleted"=0);


 IF TRUE = IsCode4 (PtPerioId, Sextant) THEN
  PSRScore := 4;
 ELSIF TRUE = IsCode3 (PtPerioId, Sextant) THEN
  PSRScore := 3;
 ELSIF TRUE = IsCode2 (PatientId, PtPerioId, Sextant) THEN
  PSRScore := 2;
 ELSIF TRUE = IsCode1 (PatientId, PtPerioId, Sextant) THEN
  PSRScore := 1;
 END IF;

 RETURN PSRScore;
END;

--AX-24528.2
FUNCTION getptpsrbydate(chartdate timestamp without time zone, patientid numeric, sextant numeric) RETURN numeric IS
 PtPerioId NUMBER := 0;
 PSRScore  NUMBER := 0;
BEGIN
 BEGIN	
	SELECT P."PtPerio" INTO PtPerioId FROM PTPERIO P		
 	WHERE  P."Patient"=PatientId AND P."Deleted"=0 AND P."Audit" =
	 (SELECT max(P2."Audit") FROM PTPERIO P2, AUDITHIS A where P2."Patient"=PatientId
 	AND P2."Deleted"=0 AND P2."Audit" = A."Audit" AND trunc(A."Date") = ChartDate);
 EXCEPTION
 WHEN NO_DATA_FOUND THEN
 	RETURN PSRScore;
 END;


 IF TRUE = IsCode4 (PtPerioId, Sextant) THEN
  PSRScore := 4;
 ELSIF TRUE = IsCode3 (PtPerioId, Sextant) THEN
  PSRScore := 3;
 ELSIF TRUE = IsCode2 (PatientId, PtPerioId, Sextant) THEN
  PSRScore := 2;
 ELSIF TRUE = IsCode1 (PatientId, PtPerioId, Sextant) THEN
  PSRScore := 1;
 END IF;

 RETURN PSRScore;
END;


FUNCTION iscode4(ptperioid numeric, sextant numeric) RETURN boolean IS
 IsCode     BOOLEAN := FALSE;
 CodeCount  NUMBER  := 0;
 UpperBound NUMBER  := 0;
 LowerBound NUMBER  := 0;
BEGIN
 IF Sextant = 1 THEN
  LowerBound := 1;
  UpperBound := 5;
 ELSIF Sextant = 2 THEN
  LowerBound := 6;
  UpperBound := 11;
 ELSIF Sextant = 3 THEN
  LowerBound := 12;
  UpperBound := 16;
 ELSIF Sextant = 4 THEN
  LowerBound := 17;
  UpperBound := 21;
 ELSIF Sextant = 5 THEN
  LowerBound := 22;
  UpperBound := 27;
 ELSIF Sextant = 6 THEN
  LowerBound := 28;
  UpperBound := 32;
-- ELSE
-- error!
 END IF;

 SELECT COUNT(*) INTO CodeCount FROM PTPERIT PI, PERCOND C
 WHERE C."CondType"=2 AND C."Status"=0 AND PI."PtPerio"=PtPerioId
 AND PI."PerCond"=C."PerCond" AND PI."Deleted"!=1					-- E33252
 AND PI."Site">=LowerBound AND PI."Site"<=UpperBound
 AND (PI."DValue1">=5.5 OR PI."DValue2">=5.5 OR PI."DValue3">=5.5);

 IF CodeCount > 0 THEN
  IsCode := TRUE;
 END IF;

 RETURN IsCode;
END;


FUNCTION iscode3(ptperioid numeric, sextant numeric) RETURN boolean IS
 IsCode     BOOLEAN := FALSE;
 CodeCount  NUMBER  := 0;
 UpperBound NUMBER  := 0;
 LowerBound NUMBER  := 0;
BEGIN
 IF Sextant = 1 THEN
  LowerBound := 1;
  UpperBound := 5;
 ELSIF Sextant = 2 THEN
  LowerBound := 6;
  UpperBound := 11;
 ELSIF Sextant = 3 THEN
  LowerBound := 12;
  UpperBound := 16;
 ELSIF Sextant = 4 THEN
  LowerBound := 17;
  UpperBound := 21;
 ELSIF Sextant = 5 THEN
  LowerBound := 22;
  UpperBound := 27;
 ELSIF Sextant = 6 THEN
  LowerBound := 28;
  UpperBound := 32;
-- ELSE
-- error!
 END IF;

 SELECT COUNT(*) INTO CodeCount FROM PTPERIT PI, PERCOND C
 WHERE C."CondType"=2 AND C."Status"=0 AND PI."PtPerio"=PtPerioId
 AND PI."PerCond"=C."PerCond" AND PI."Deleted"!=1					-- E33252
 AND PI."Site">=LowerBound AND PI."Site"<=UpperBound
 AND (PI."DValue1">=3.5 OR PI."DValue2">=3.5 OR PI."DValue3">=3.5);

 IF CodeCount > 0 THEN
  IsCode := TRUE;
 END IF;

 RETURN IsCode;
END;


FUNCTION iscode2(patientid numeric, ptperioid numeric, sextant numeric) RETURN boolean IS
 IsCode     BOOLEAN := FALSE;
 CodeCount1  NUMBER := 0;
 CodeCount2  NUMBER := 0;
 CodeCount3  NUMBER := 0;
 CodeCount4  NUMBER := 0;
 CodeCount5  NUMBER := 0;
 CodeCount6  NUMBER := 0;
 UpperBound  NUMBER := 0;
 LowerBound  NUMBER := 0;
 PUpperBound NUMBER := 0;
 PLowerBound NUMBER := 0;
BEGIN
 IF Sextant = 1 THEN
  LowerBound  := 1;
  UpperBound  := 5;
  PLowerBound := 45;
  PUpperBound := 46;
 ELSIF Sextant = 2 THEN
  LowerBound  := 6;
  UpperBound  := 11;
  PLowerBound := 47;
  PUpperBound := 52;
 ELSIF Sextant = 3 THEN
  LowerBound  := 12;
  UpperBound  := 16;
  PLowerBound := 53;
  PUpperBound := 54;
 ELSIF Sextant = 4 THEN
  LowerBound  := 17;
  UpperBound  := 21;
  PLowerBound := 55;
  PUpperBound := 56;
 ELSIF Sextant = 5 THEN
  LowerBound  := 22;
  UpperBound  := 27;
  PLowerBound := 57;
  PUpperBound := 62;
 ELSIF Sextant = 6 THEN
  LowerBound  := 28;
  UpperBound  := 32;
  PLowerBound := 63;
  PUpperBound := 64;
-- ELSE
-- error!
 END IF;

 SELECT COUNT(*) INTO CodeCount1 FROM TREATME2 T, PATIENT2 P2, PROCEDUR P
 WHERE P2."PtxPId"=PatientId AND P2."Auto"=T."PId" AND T."CodeId"=P."Id" AND P."CondType"=6
 AND T."Site">=LowerBound AND T."Site"<=UpperBound AND T."Status"=4
 AND ((T."Deleted"=0 AND 0 = (SELECT COUNT(*) FROM CHARTLNK L WHERE L."Auto" = T."Auto" and L."Status" = 'D'))
 OR (T."Deleted"=1 AND 0 < (SELECT COUNT(*) FROM CHARTLNK L WHERE L."Auto" = T."Auto" and L."Status" = 'D')));

 SELECT COUNT(*) INTO CodeCount2 FROM TREATME2 T, PATIENT2 P2, PROCEDUR P
 WHERE P2."PtxPId"=PatientId AND P2."Auto"=T."PId" AND T."CodeId"=P."Id" AND P."CondType"=7
 AND T."Site">=LowerBound AND T."Site"<=UpperBound AND T."Status"=4
 AND ((T."Deleted"=0 AND 0 = (SELECT COUNT(*) FROM CHARTLNK L WHERE L."Auto" = T."Auto" and L."Status" = 'D'))
 OR (T."Deleted"=1 AND 0 < (SELECT COUNT(*) FROM CHARTLNK L WHERE L."Auto" = T."Auto" and L."Status" = 'D')));

 SELECT COUNT(*) INTO CodeCount3 FROM TREATME2 T, PATIENT2 P2, PROCEDUR P
 WHERE P2."PtxPId"=PatientId AND P2."Auto"=T."PId" AND T."CodeId"=P."Id" AND P."CondType"=6
 AND T."Site">=PLowerBound AND T."Site"<=PUpperBound AND T."Status"=4
 AND ((T."Deleted"=0 AND 0 = (SELECT COUNT(*) FROM CHARTLNK L WHERE L."Auto" = T."Auto" and L."Status" = 'D'))
 OR (T."Deleted"=1 AND 0 < (SELECT COUNT(*) FROM CHARTLNK L WHERE L."Auto" = T."Auto" and L."Status" = 'D')));

 SELECT COUNT(*) INTO CodeCount4 FROM TREATME2 T, PATIENT2 P2, PROCEDUR P
 WHERE P2."PtxPId"=PatientId AND P2."Auto"=T."PId" AND T."CodeId"=P."Id" AND P."CondType"=7
 AND T."Site">=PLowerBound AND T."Site"<=PUpperBound AND T."Status"=4
 AND ((T."Deleted"=0 AND 0 = (SELECT COUNT(*) FROM CHARTLNK L WHERE L."Auto" = T."Auto" and L."Status" = 'D'))
 OR (T."Deleted"=1 AND 0 < (SELECT COUNT(*) FROM CHARTLNK L WHERE L."Auto" = T."Auto" and L."Status" = 'D')));

 SELECT COUNT(*) INTO CodeCount5 FROM PTPERIT PI, PERCOND C
 WHERE C."CondType"=6 AND C."Status"=0 AND PI."PtPerio"=PtPerioId
 AND PI."PerCond"=C."PerCond" AND PI."Deleted"!=1					-- E33252
 AND PI."Site">=LowerBound AND PI."Site"<=UpperBound
 AND (PI."DValue1"=1 OR PI."DValue2"=1 OR PI."DValue3"=1);

 SELECT COUNT(*) INTO CodeCount6 FROM PTPERIT PI, PERCOND C
 WHERE C."CondType"=7 AND C."Status"=0 AND PI."PtPerio"=PtPerioId
 AND PI."PerCond"=C."PerCond" AND PI."Deleted"!=1					-- E33252
 AND PI."Site">=LowerBound AND PI."Site"<=UpperBound
 AND (PI."DValue1"=1 OR PI."DValue2"=1 OR PI."DValue3"=1);

 IF CodeCount1 > 0 OR CodeCount2 > 0 OR CodeCount3 > 0
 OR CodeCount4 > 0 OR CodeCount5 > 0 OR CodeCount6 > 0 THEN
  IsCode := TRUE;
 END IF;

 RETURN IsCode;
END;


FUNCTION iscode1(patientid numeric, ptperioid numeric, sextant numeric) RETURN boolean IS
 IsCode     BOOLEAN := FALSE;
 CodeCount1 NUMBER  := 0;
 CodeCount2 NUMBER  := 0;
 CodeCount3  NUMBER := 0;
 UpperBound NUMBER  := 0;
 LowerBound NUMBER  := 0;
 PUpperBound NUMBER := 0;
 PLowerBound NUMBER := 0;
BEGIN
 IF Sextant = 1 THEN
  LowerBound  := 1;
  UpperBound  := 5;
  PLowerBound := 45;
  PUpperBound := 46;
 ELSIF Sextant = 2 THEN
  LowerBound  := 6;
  UpperBound  := 11;
  PLowerBound := 47;
  PUpperBound := 52;
 ELSIF Sextant = 3 THEN
  LowerBound  := 12;
  UpperBound  := 16;
  PLowerBound := 53;
  PUpperBound := 54;
 ELSIF Sextant = 4 THEN
  LowerBound  := 17;
  UpperBound  := 21;
  PLowerBound := 55;
  PUpperBound := 56;
 ELSIF Sextant = 5 THEN
  LowerBound  := 22;
  UpperBound  := 27;
  PLowerBound := 57;
  PUpperBound := 62;
 ELSIF Sextant = 6 THEN
  LowerBound  := 28;
  UpperBound  := 32;
  PLowerBound := 63;
  PUpperBound := 64;
-- ELSE
-- error!
 END IF;

 SELECT COUNT(*) INTO CodeCount1 FROM TREATME2 T, PATIENT2 P2, PROCEDUR P
 WHERE P2."PtxPId"=PatientId AND P2."Auto"=T."PId" AND T."CodeId"=P."Id" AND P."CondType"=4
 AND T."Site">=LowerBound AND T."Site"<=UpperBound AND T."Status"=4
 AND ((T."Deleted"=0 AND 0 = (SELECT COUNT(*) FROM CHARTLNK L WHERE L."Auto" = T."Auto" and L."Status" = 'D'))
 OR (T."Deleted"=1 AND 0 < (SELECT COUNT(*) FROM CHARTLNK L WHERE L."Auto" = T."Auto" and L."Status" = 'D')));

 SELECT COUNT(*) INTO CodeCount2 FROM TREATME2 T, PATIENT2 P2, PROCEDUR P
 WHERE P2."PtxPId"=PatientId AND P2."Auto"=T."PId" AND T."CodeId"=P."Id" AND P."CondType"=4
 AND T."Site">=PLowerBound AND T."Site"<=PUpperBound AND T."Status"=4
 AND ((T."Deleted"=0 AND 0 = (SELECT COUNT(*) FROM CHARTLNK L WHERE L."Auto" = T."Auto" and L."Status" = 'D'))
 OR (T."Deleted"=1 AND 0 < (SELECT COUNT(*) FROM CHARTLNK L WHERE L."Auto" = T."Auto" and L."Status" = 'D')));

 SELECT COUNT(*) INTO CodeCount3 FROM PTPERIT PI, PERCOND C
 WHERE C."CondType"=4 AND C."Status"=0 AND PI."PtPerio"=PtPerioId
 AND PI."PerCond"=C."PerCond" AND PI."Deleted"!=1					-- E33252
 AND PI."Site">=LowerBound AND PI."Site"<=UpperBound
 AND (PI."DValue1"=1 OR PI."DValue2"=1 OR PI."DValue3"=1);

 IF CodeCount1 > 0 OR CodeCount2 > 0 OR CodeCount3 > 0 THEN
  IsCode := TRUE;
 END IF;

 RETURN IsCode;
END;


END;
CREATE OR REPLACE PACKAGE BODY ehr_pkg IS

   PROCEDURE delete_eprform(IN pformid numeric) IS

      vSql      VARCHAR2(2000);

      vCount    NUMBER;

      vMultiple NUMBER(5);

   BEGIN



      ----store records for future auditing/recovering



      INSERT

         INTO pitemimg_deleted

            (SELECT * FROM pitemimg g WHERE g."PItemImg" IN

            (SELECT p."PItemImg" FROM pitem p WHERE p."PForm" = PFormId));



      INSERT

         INTO ptsig_deleted

            (SELECT * FROM ptsig g WHERE g."PtSig" IN

            (SELECT p."PtSig" FROM ppage p WHERE p."PForm"  = PFormId AND p."PtSig" > 0));



      INSERT

         INTO ptsig_deleted

            (SELECT * FROM ptsig g WHERE g."PtSig" IN 

            (SELECT s."PtSig" FROM ppage p, ppagesig s WHERE p."PForm"  = PFormId AND s."PPage" = p."PPage" AND s."PtSig" > 0));



      INSERT

         INTO ppagesig_deleted

            (SELECT * FROM ppagesig g WHERE g."PPage" IN

            (SELECT p."PPage" FROM ppage p WHERE p."PForm" = PFormId));



      INSERT

         INTO ppage_deleted

            (SELECT * FROM ppage WHERE "PForm" = PFormId);



      INSERT

         INTO pitem_deleted

            (SELECT * FROM pitem WHERE "PForm" = PFormId);



      INSERT

         INTO pitemtmp_deleted

            (SELECT * FROM pitemtmp WHERE "PForm" = PFormId);



      INSERT

         INTO pformevt_deleted

            (SELECT * FROM pformevt g WHERE g."PForm" = PFormId);



      INSERT

         INTO pitemcol_deleted

            (SELECT * FROM pitemcol g WHERE g."PForm" = PFormId);



      ----delete PITEM, PPAGE, PTSIG, PPAGESIG, PITEMTMP, PITEMIMG, PFORMEVT,PITEMCOL 

      delete pitemimg g where g."PItemImg" in (select p."PItemImg" from pitem p where p."PForm"=PFormId);

      delete ptsig g where g."PtSig" in (select p."PtSig" from ppage p where p."PForm"=PFormId and p."PtSig">0);

      delete ptsig g where g."PtSig" in (select s."PtSig" from ppage p, ppagesig s

        where p."PForm"=PFormId and s."PPage"=p."PPage" and s."PtSig">0);

      delete ppagesig g where g."PPage" in (select p."PPage" from ppage p where p."PForm"=PFormId);

      delete ppage where "PForm"=PFormId;

      delete pitem where "PForm"=PFormId;

      delete pitemtmp where "PForm"=PFormId;

      delete pformevt where "PForm"=PFormId;	-- E72774.2

      delete pitemcol where "PForm"=PFormId;	-- B142363



      ----delete IPTFORM (optional table)

      SELECT COUNT(1) INTO vCount

         FROM user_tables WHERE table_name = 'IPTFORM';



      IF vCount = 1 THEN



         SELECT f."Multiple" INTO vMultiple FROM form f, pform pf

            WHERE f."Code" = pf."FormCode" AND pf."PForm" = PFormId;



         IF vMultiple = 1 THEN

            INSERT

                INTO iptform_deleted

            (SELECT * FROM iptform g WHERE g."PForm" = PFormId);

            vSql     := 'delete iptform where "PForm" = :1';

         ELSE

            vSql := 'update iptform set "PForm" = 0 where "PForm" = :1';

         END IF;

         EXECUTE IMMEDIATE vSql USING PFormId;



      END IF;



      ----insert record of delete pform

      INSERT

         INTO pform_deleted

            (SELECT * FROM pform WHERE "PForm" = PFormId);



      ----lastly, delete PFORM



      DELETE pform WHERE "PForm" = PFormId;

      COMMIT;



   -- AX-22939, SF-00241583 This error occurs when the form has already been deleted by another user.

   EXCEPTION WHEN NO_DATA_FOUND THEN

     DBMS_OUTPUT.PUT_LINE ('No Data found - delete_eprform  ');



   END;

--

-- fucntion to recursively determine if one FITEM (FItemChild)

-- is a decsendant of another (FItemParent)

-- return 1 if yes, 0 if no

--



   FUNCTION isfitemdescendant(fitemparent numeric, fitemchild numeric) RETURN numeric IS

      m_ParentFItem FITEM."ParentFItem"%TYPE;

      v_FItemChild fitem."FItem"       %type := NVL(FItemChild, 0);

      v_FItemParent fitem."ParentFItem"%type := NVL(FItemParent,0);

   BEGIN

      m_ParentFItem := 0;

      -- find child fitem's parent

      BEGIN



         SELECT "ParentFItem"

            INTO m_ParentFItem

            FROM FITEM

            WHERE "FItem" = v_FItemChild;



      EXCEPTION



      WHEN NO_DATA_FOUND THEN

         m_ParentFItem := 0;



      END;

      -- if the child fitem's parent is the parent then we've found it!

      -- otherwise keep looking

      -- bail if we get to an fitem that has no parent



      IF m_ParentFItem = v_FItemParent THEN



         RETURN 1;



      ELSIF m_ParentFItem = 0 THEN



         RETURN 0;



      ELSE



         RETURN IsFItemDescendant(v_FItemParent, m_ParentFItem);



      END IF;



   END;



END;
CREATE OR REPLACE PACKAGE BODY fportal_pkg IS



	/**

  * Procedure used to get all appointments start checked today by selected instructor

	* param: vUserId INPUT: USERS.User

	* param: vClinicId INPUT: Clinic ID to filter the appointments - If set to 0, the list will be filtered by all clinics the instructor has an access to.

	* param: vClinicTimeId INPUT: Clinic Time ID to filter the appointments - If set to 0, the list will contain all clinic times the clinic has.

	* param: vStationId INPUT: Station ID used to get Server Time zone offset.

	* param: vIncludeNoNotification INPUT: Include/exclude appointments without chair notification state.

	* param: vSearchKeyword INPUT: Keyword for filtering the appointments.

	* param: vSearchType INPUT: Field to search using the keyword (Provider First/Last Name, Code, Patient First/Last Name)

	* param: vFilterNotification INPUT: list of chair state notification IDs to include in the appointment list (separated by comma)

	* param: vOrderBy INPUT: keyword to order the list by.

	* param: vNumRows INPUT: total number of rows for the list

	* param: vPage INPUT: page number for the paginated list (requested)

	* param: vCurrentPage OUTPUT: actual page number for the paginated list (retrieved)

	* param: vTotalPage OUTPUT: total number of pages available for given criteria

	* param: vResults OUTPUT: Weak cursor containing list of appointments matching given criteria

  */

	PROCEDURE getapptmylist(IN vuserid integer, IN vclinicid integer, IN vclinictimeid integer, IN vincludenonotification integer, IN vsearchkeyword character varying, IN vsearchtype character varying, IN vfilternotification character varying, IN vorderby character varying, OUT vresults cursor_pkg.weakcursor) IS

	BEGIN



		OPEN vResults FOR



		SELECT

		X.*,

    CN."Priority" AS "CNPriority",

		CN."BkgColor" AS "CNBkgColor",

    AH."Date" AS "CNDate",

    AH."Time" AS "CNTime"



		FROM (



			SELECT

			CL."Clinic" AS "MYCLINICID",



			PT."Patient", PT."Last", PT."First", PT."Sex",

			PR."FirstName", PR."LastName", PR."Year",

			AP."Appointment", AP."Clinic", AP."Reason",



			TRIM(PR."Producer")                                     AS "Producer",

			TO_NUMBER(TRIM(AP."From"))                              AS "StartTime",

			TO_NUMBER(AP."Time0" + AP."Time1" + AP."Time2" +

			AP."Time3" + AP."Time4" + AP."Time5")                   AS "ApptLength",

			CT."Description"                                        AS "ClinicTimeName",

			CH."Chair"                                              AS "ChairId",

			CH."Name"                                               AS "Chair",

			AP."Type"                                               AS "ApptType",

			AP."IsConfirm"                                          AS "ApptIsConfirm",

			TO_CHAR(FLOOR(MONTHS_BETWEEN(SYSDATE,PT."Birth")))      AS "Birth",

			SUBSTR(TRIM(PT."First"),1,1) || TRIM(PT."Last")         AS "FLast",

			TRIM(PT."Last") || SUBSTR(TRIM(PT."First"),1,1)         AS "LFirst",

			SUBSTR(TRIM(PR."FirstName"),1,1) || TRIM(PR."LastName") AS "FLastName",

			TRIM(PR."LastName") || SUBSTR(TRIM(PR."FirstName"),1,1) AS "LFirstName",



			CASE

			WHEN GREATEST(NVL(CS1."Audit",0), NVL(CS2."Audit",0)) = CS1."Audit" THEN CS1."CNState"

			ELSE CS2."CNState"

			END AS "CNState",



			GREATEST(NVL(CS1."Audit",0), NVL(CS2."Audit",0)) AS "CNAudit"



			FROM

			(

				SELECT AP."Appointment", MAX(SC."StartChk") AS "StartChk"

				FROM APPOINT AP

				JOIN STARTCHK SC ON SC."Appointment" = AP."Appointment"

				WHERE AP."Date" = TRUNC(SYSDATE)

				AND AP."Status" = 0

				AND AP."Type" IN (0,1,2)

				GROUP BY AP."Appointment"

			) S



			JOIN APPOINT AP ON AP."Appointment" = S."Appointment"

			JOIN CLINIC CL ON CL."Clinic" = AP."Clinic"

			JOIN STARTCHK SC ON SC."StartChk" = S."StartChk"

			JOIN CLINICT CT ON CT."Clinic" = AP."Clinic"

			JOIN AUDITHIS SCAH ON SCAH."Audit" = SC."Audit"



			JOIN PATIENT PT        ON PT."Patient" = AP."Patient"

			JOIN PRODUCER PR       ON PR."Producer" = AP."Producer" AND PR."Inactive" = 0

			JOIN CHAIR CH          ON AP."Chair" = CH."Chair"

			LEFT JOIN PRODUCER PR2 ON AP."Assistant" = PR2."Producer" AND PR2."Inactive" = 0 AND ROWNUM = 1



			LEFT JOIN CHAIRST CS1 ON CS1."Chair" = AP."Chair" AND CS1."ClinicTime" = 0

			LEFT JOIN CHAIRST CS2 ON CS2."Chair" = AP."Chair" AND CS2."ClinicTime" = CT."ClinicTime"



			WHERE SC."AppUser" = vUserId

			AND SCAH."Date" = TRUNC(SYSDATE)

			AND AP."Clinic" = vClinicId

			AND AP."Date" = TRUNC(SYSDATE)

			AND AP."Status" = 0

			AND AP."Type" IN (0,1,2)



			AND AP."From" BETWEEN CT."Start" AND CT."End" - 1

			AND

			(

				(CT."Monday" = 1 AND TRIM(TO_CHAR(AP."Date",'Day')) = 'Monday') OR

				(CT."Tuesday" = 1 AND TRIM(TO_CHAR(AP."Date",'Day')) = 'Tuesday') OR

				(CT."Wednesday" = 1 AND TRIM(TO_CHAR(AP."Date",'Day')) = 'Wednesday') OR

				(CT."Thursday" = 1 AND TRIM(TO_CHAR(AP."Date",'Day')) = 'Thursday') OR

				(CT."Friday" = 1 AND TRIM(TO_CHAR(AP."Date",'Day')) = 'Friday') OR

				(CT."Saturday" = 1 AND TRIM(TO_CHAR(AP."Date",'Day')) = 'Saturday') OR

				(CT."Sunday" = 1 AND TRIM(TO_CHAR(AP."Date",'Day')) = 'Sunday')

			)

			AND

			(

				(CT."StartDate" <= TRUNC(SYSDATE) AND CT."EndDate" >= TRUNC(SYSDATE)) OR

				(CT."StartDate" IS NULL AND CT."EndDate" >= TRUNC(SYSDATE)) OR

				(CT."StartDate" <= TRUNC(SYSDATE) AND CT."EndDate" IS NULL) OR

				(CT."StartDate" IS NULL AND CT."EndDate" IS NULL )

			)



			-- Filter list by start and end time

			AND (vClinicTimeId = 0 OR CT."ClinicTime" = vClinicTimeId)



			-- Filter list by keyword

			AND (



				-- IF keyword search is set to search for First Name field

				(NLS_UPPER(TRIM(vSearchType)) = 'PROVIDERFIRSTNAME' AND

					(NLS_UPPER(TRIM(PR."FirstName")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(PR."FirstName") IS NULL OR LENGTH(TRIM(PR."FirstName")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



				-- IF keyword search is set to search for Last Name field

				OR (NLS_UPPER(TRIM(vSearchType)) = 'PROVIDERLASTNAME' AND

					(NLS_UPPER(TRIM(PR."LastName")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(PR."LastName") IS NULL OR LENGTH(TRIM(PR."LastName")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



				-- IF keyword search is set to search for Provider Code field

				OR (NLS_UPPER(TRIM(vSearchType)) = 'PRODUCER' AND

					(NLS_UPPER(TRIM(PR."Producer")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(PR."Producer") IS NULL OR LENGTH(TRIM(PR."Producer")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



				-- IF keyword search is set to search for First Name field

				OR (NLS_UPPER(TRIM(vSearchType)) = 'PATIENTFIRSTNAME' AND

					(NLS_UPPER(TRIM(PT."First")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(PT."First") IS NULL OR LENGTH(TRIM(PT."First")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



				-- IF keyword search is set to search for Last Name field

				OR (NLS_UPPER(TRIM(vSearchType)) = 'PATIENTLASTNAME' AND

					(NLS_UPPER(TRIM(PT."Last")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(PT."Last") IS NULL OR LENGTH(TRIM(PT."Last")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



			)



		) X



		LEFT JOIN AUDITHIS AH  ON AH."Audit" = X."CNAudit"

		LEFT JOIN CNSTATE CN   ON CN."CNState" = X."CNState"



		-- Filter list by Chair state

		WHERE ( (vIncludeNoNotification = 1 AND (TRIM(X."CNState") IS NULL OR LENGTH(TRIM(X."CNState")) = 0))

		OR TRIM(X."CNState") IN (select regexp_substr(vFilterNotification,'[^,]+', 1, level) from dual connect by regexp_substr(vFilterNotification,'[^,]+', 1, level) is not null))



		-- Order list

		ORDER BY



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERFIRST_ASC' THEN NLS_UPPER("FLastName" || "Producer" || "Year") END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERFIRST_ASC' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERFIRST_ASC' THEN "ApptLength" END ASC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERFIRST_DESC' THEN NLS_UPPER("FLastName" || "Producer" || "Year") END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERFIRST_DESC' THEN "StartTime" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERFIRST_DESC' THEN "ApptLength" END DESC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERLAST_ASC' THEN NLS_UPPER("LFirstName" || "Producer" || "Year") END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERLAST_ASC' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERLAST_ASC' THEN "ApptLength" END ASC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERLAST_DESC' THEN NLS_UPPER("LFirstName" || "Producer" || "Year") END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERLAST_DESC' THEN "StartTime" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERLAST_DESC' THEN "ApptLength" END DESC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMEFIRST_ASC' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMEFIRST_ASC' THEN "ApptLength" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMEFIRST_ASC' THEN NLS_UPPER("FLastName" || "Producer" || "Year") END ASC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMEFIRST_DESC' THEN "StartTime" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMEFIRST_DESC' THEN "ApptLength" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMEFIRST_DESC' THEN NLS_UPPER("FLastName" || "Producer" || "Year") END DESC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMELAST_ASC' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMELAST_ASC' THEN "ApptLength" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMELAST_ASC' THEN NLS_UPPER("LFirstName" || "Producer" || "Year") END ASC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMELAST_DESC' THEN "StartTime" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMELAST_DESC' THEN "ApptLength" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMELAST_DESC' THEN NLS_UPPER("LFirstName" || "Producer" || "Year") END DESC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CLINIC_ASC' THEN NLS_UPPER("Chair") END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CLINIC_ASC' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CLINIC_ASC' THEN "ApptLength" END ASC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CLINIC_DESC' THEN NLS_UPPER("Chair") END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CLINIC_DESC' THEN "StartTime" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CLINIC_DESC' THEN "ApptLength" END DESC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTFIRST_ASC' THEN NLS_UPPER("FLast" || "Sex" || "Birth") END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTFIRST_ASC' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTFIRST_ASC' THEN "ApptLength" END ASC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTFIRST_DESC' THEN NLS_UPPER("FLast" || "Sex" || "Birth") END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTFIRST_DESC' THEN "StartTime" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTFIRST_DESC' THEN "ApptLength" END DESC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTLAST_ASC' THEN NLS_UPPER("LFirst" || "Sex" || "Birth") END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTLAST_ASC' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTLAST_ASC' THEN "ApptLength" END ASC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTLAST_DESC' THEN NLS_UPPER("LFirst" || "Sex" || "Birth") END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTLAST_DESC' THEN "StartTime" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTLAST_DESC' THEN "ApptLength" END DESC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CHAIRSTATE' THEN NVL(CN."Priority", -1) END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CHAIRSTATE' THEN AH."Date" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CHAIRSTATE' THEN AH."Time" END ASC,

    CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CHAIRSTATE' THEN AH."Audit" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CHAIRSTATE' THEN NLS_UPPER("Chair") END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CHAIRSTATE' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CHAIRSTATE' THEN "ApptLength" END ASC;



	END;



	/**

  * Procedure used to get all appointments watched by selected instructor

	* param: vUserId INPUT: USERS.User

	* param: vClinicId INPUT: Clinic ID to filter the appointments - If set to 0, the list will be filtered by all clinics the instructor has an access to.

	* param: vClinicTimeId INPUT: Clinic Time ID to filter the appointments - If set to 0, the list will contain all clinic times the clinic has.

	* param: vStationId INPUT: Station ID used to get Server Time zone offset.

	* param: vIncludeNoNotification INPUT: Include/exclude appointments without chair notification state.

	* param: vSearchKeyword INPUT: Keyword for filtering the appointments.

	* param: vSearchType INPUT: Field to search using the keyword (Provider First/Last Name, Code, Patient First/Last Name)

	* param: vFilterNotification INPUT: list of chair state notification IDs to include in the appointment list (separated by comma)

	* param: vOrderBy INPUT: keyword to order the list by.

	* param: vNumRows INPUT: total number of rows for the list

	* param: vPage INPUT: page number for the paginated list (requested)

	* param: vCurrentPage OUTPUT: actual page number for the paginated list (retrieved)

	* param: vTotalPage OUTPUT: total number of pages available for given criteria

	* param: vResults OUTPUT: Weak cursor containing list of appointments matching given criteria

  */

	PROCEDURE getapptwatchedlist(IN vuserid integer, IN vclinicid integer, IN vclinictimeid integer, IN vincludenonotification integer, IN vsearchkeyword character varying, IN vsearchtype character varying, IN vfilternotification character varying, IN vorderby character varying, OUT vresults cursor_pkg.weakcursor) IS

	BEGIN



		OPEN vResults FOR



		SELECT

		X.*,

    CN."Priority" AS "CNPriority",

		CN."BkgColor" AS "CNBkgColor",

    AH."Date" AS "CNDate",

    AH."Time" AS "CNTime"



		FROM (



			SELECT



			UC."Clinic" AS "MYCLINICID",



			PT."Patient", PT."Last", PT."First", PT."Sex",

			PR."FirstName", PR."LastName", PR."Year",

			AP."Appointment", AP."Clinic", AP."Reason",



			TRIM(PR."Producer")                                     AS "Producer",

			TO_NUMBER(TRIM(AP."From"))                              AS "StartTime",

			TO_NUMBER(AP."Time0" + AP."Time1" + AP."Time2" +

			AP."Time3" + AP."Time4" + AP."Time5")                   AS "ApptLength",

			CT."Description"                                        AS "ClinicTimeName",

			CH."Chair"                                              AS "ChairId",

			CH."Name"                                               AS "Chair",

			AP."Type"                                               AS "ApptType",

			AP."IsConfirm"                                          AS "ApptIsConfirm",

			TO_CHAR(FLOOR(MONTHS_BETWEEN(SYSDATE,PT."Birth")))      AS "Birth",

			SUBSTR(TRIM(PT."First"),1,1) || TRIM(PT."Last")         AS "FLast",

			TRIM(PT."Last") || SUBSTR(TRIM(PT."First"),1,1)         AS "LFirst",

			SUBSTR(TRIM(PR."FirstName"),1,1) || TRIM(PR."LastName") AS "FLastName",

			TRIM(PR."LastName") || SUBSTR(TRIM(PR."FirstName"),1,1) AS "LFirstName",



			CASE

			WHEN GREATEST(NVL(CS1."Audit",0), NVL(CS2."Audit",0)) = CS1."Audit" THEN CS1."CNState"

			ELSE CS2."CNState"

			END AS "CNState",



			GREATEST(NVL(CS1."Audit",0), NVL(CS2."Audit",0)) AS "CNAudit"



			FROM UCLINIC UC

			JOIN CLINIC CL ON UC."Clinic" = CL."Clinic"

			JOIN CLINICT CT ON CT."Clinic" = UC."Clinic"

			JOIN APPOINT AP ON UC."Clinic" = AP."Clinic"

      JOIN FAPTWATCH W ON AP."Appointment" = W."Appointment" AND AP."Date" = W."Date"



			JOIN PATIENT PT        ON PT."Patient" = AP."Patient"

			JOIN PRODUCER PR       ON PR."Producer" = AP."Producer" AND PR."Inactive" = 0

			JOIN CHAIR CH          ON AP."Chair" = CH."Chair"

			LEFT JOIN PRODUCER PR2 ON AP."Assistant" = PR2."Producer" AND PR2."Inactive" = 0 AND ROWNUM = 1



			LEFT JOIN CHAIRST CS1 ON CS1."Chair" = AP."Chair" AND CS1."ClinicTime" = 0

			LEFT JOIN CHAIRST CS2 ON CS2."Chair" = AP."Chair" AND CS2."ClinicTime" = CT."ClinicTime"



			WHERE W."Instructor" = vUserId

      AND UC."User" = vUserId

			AND UC."Clinic" = vClinicId

			AND AP."Date" = TRUNC(SYSDATE)

			AND AP."Status" = 0

			AND AP."Type" IN (0,1,2)



			AND AP."From" BETWEEN CT."Start" AND CT."End" - 1

			AND

			(

				(CT."Monday" = 1 AND TRIM(TO_CHAR(AP."Date",'Day')) = 'Monday') OR

				(CT."Tuesday" = 1 AND TRIM(TO_CHAR(AP."Date",'Day')) = 'Tuesday') OR

				(CT."Wednesday" = 1 AND TRIM(TO_CHAR(AP."Date",'Day')) = 'Wednesday') OR

				(CT."Thursday" = 1 AND TRIM(TO_CHAR(AP."Date",'Day')) = 'Thursday') OR

				(CT."Friday" = 1 AND TRIM(TO_CHAR(AP."Date",'Day')) = 'Friday') OR

				(CT."Saturday" = 1 AND TRIM(TO_CHAR(AP."Date",'Day')) = 'Saturday') OR

				(CT."Sunday" = 1 AND TRIM(TO_CHAR(AP."Date",'Day')) = 'Sunday')

			)

			AND

			(

				(CT."StartDate" <= TRUNC(SYSDATE) AND CT."EndDate" >= TRUNC(SYSDATE)) OR

				(CT."StartDate" IS NULL AND CT."EndDate" >= TRUNC(SYSDATE)) OR

				(CT."StartDate" <= TRUNC(SYSDATE) AND CT."EndDate" IS NULL) OR

				(CT."StartDate" IS NULL AND CT."EndDate" IS NULL )

			)



			-- Filter list by start and end time

			AND (vClinicTimeId = 0 OR CT."ClinicTime" = vClinicTimeId)



			-- Filter list by keyword

			AND (



				-- IF keyword search is set to search for First Name field

				(NLS_UPPER(TRIM(vSearchType)) = 'PROVIDERFIRSTNAME' AND

					(NLS_UPPER(TRIM(PR."FirstName")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(PR."FirstName") IS NULL OR LENGTH(TRIM(PR."FirstName")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



				-- IF keyword search is set to search for Last Name field

				OR (NLS_UPPER(TRIM(vSearchType)) = 'PROVIDERLASTNAME' AND

					(NLS_UPPER(TRIM(PR."LastName")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(PR."LastName") IS NULL OR LENGTH(TRIM(PR."LastName")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



				-- IF keyword search is set to search for Provider Code field

				OR (NLS_UPPER(TRIM(vSearchType)) = 'PRODUCER' AND

					(NLS_UPPER(TRIM(PR."Producer")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(PR."Producer") IS NULL OR LENGTH(TRIM(PR."Producer")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



				-- IF keyword search is set to search for First Name field

				OR (NLS_UPPER(TRIM(vSearchType)) = 'PATIENTFIRSTNAME' AND

					(NLS_UPPER(TRIM(PT."First")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(PT."First") IS NULL OR LENGTH(TRIM(PT."First")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



				-- IF keyword search is set to search for Last Name field

				OR (NLS_UPPER(TRIM(vSearchType)) = 'PATIENTLASTNAME' AND

					(NLS_UPPER(TRIM(PT."Last")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(PT."Last") IS NULL OR LENGTH(TRIM(PT."Last")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



			)



		) X



		LEFT JOIN AUDITHIS AH  ON AH."Audit" = X."CNAudit"

		LEFT JOIN CNSTATE CN   ON CN."CNState" = X."CNState"



		-- Filter list by Chair state

		WHERE ( (vIncludeNoNotification = 1 AND (TRIM(X."CNState") IS NULL OR LENGTH(TRIM(X."CNState")) = 0))

		OR TRIM(X."CNState") IN (select regexp_substr(vFilterNotification,'[^,]+', 1, level) from dual connect by regexp_substr(vFilterNotification,'[^,]+', 1, level) is not null))



		-- Order list

		ORDER BY



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERFIRST_ASC' THEN NLS_UPPER("FLastName" || "Producer" || "Year") END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERFIRST_ASC' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERFIRST_ASC' THEN "ApptLength" END ASC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERFIRST_DESC' THEN NLS_UPPER("FLastName" || "Producer" || "Year") END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERFIRST_DESC' THEN "StartTime" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERFIRST_DESC' THEN "ApptLength" END DESC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERLAST_ASC' THEN NLS_UPPER("LFirstName" || "Producer" || "Year") END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERLAST_ASC' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERLAST_ASC' THEN "ApptLength" END ASC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERLAST_DESC' THEN NLS_UPPER("LFirstName" || "Producer" || "Year") END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERLAST_DESC' THEN "StartTime" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERLAST_DESC' THEN "ApptLength" END DESC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMEFIRST_ASC' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMEFIRST_ASC' THEN "ApptLength" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMEFIRST_ASC' THEN NLS_UPPER("FLastName" || "Producer" || "Year") END ASC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMEFIRST_DESC' THEN "StartTime" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMEFIRST_DESC' THEN "ApptLength" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMEFIRST_DESC' THEN NLS_UPPER("FLastName" || "Producer" || "Year") END DESC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMELAST_ASC' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMELAST_ASC' THEN "ApptLength" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMELAST_ASC' THEN NLS_UPPER("LFirstName" || "Producer" || "Year") END ASC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMELAST_DESC' THEN "StartTime" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMELAST_DESC' THEN "ApptLength" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMELAST_DESC' THEN NLS_UPPER("LFirstName" || "Producer" || "Year") END DESC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CLINIC_ASC' THEN NLS_UPPER("Chair") END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CLINIC_ASC' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CLINIC_ASC' THEN "ApptLength" END ASC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CLINIC_DESC' THEN NLS_UPPER("Chair") END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CLINIC_DESC' THEN "StartTime" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CLINIC_DESC' THEN "ApptLength" END DESC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTFIRST_ASC' THEN NLS_UPPER("FLast" || "Sex" || "Birth") END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTFIRST_ASC' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTFIRST_ASC' THEN "ApptLength" END ASC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTFIRST_DESC' THEN NLS_UPPER("FLast" || "Sex" || "Birth") END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTFIRST_DESC' THEN "StartTime" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTFIRST_DESC' THEN "ApptLength" END DESC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTLAST_ASC' THEN NLS_UPPER("LFirst" || "Sex" || "Birth") END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTLAST_ASC' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTLAST_ASC' THEN "ApptLength" END ASC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTLAST_DESC' THEN NLS_UPPER("LFirst" || "Sex" || "Birth") END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTLAST_DESC' THEN "StartTime" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTLAST_DESC' THEN "ApptLength" END DESC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CHAIRSTATE' THEN NVL(CN."Priority", -1) END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CHAIRSTATE' THEN AH."Date" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CHAIRSTATE' THEN AH."Time" END ASC,

    CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CHAIRSTATE' THEN AH."Audit" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CHAIRSTATE' THEN NLS_UPPER("Chair") END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CHAIRSTATE' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CHAIRSTATE' THEN "ApptLength" END ASC;



	END;



	PROCEDURE getapptalllistwithstartcheck(IN vuserid integer, IN vclinicid integer, IN vclinictimeid integer, IN vhidepast integer, IN vincludenonotification integer, IN vsearchkeyword character varying, IN vsearchtype character varying, IN vfilternotification character varying, IN vorderby character varying, OUT vresults cursor_pkg.weakcursor) IS

	BEGIN



		OPEN vResults FOR



		SELECT

		X.*,

    CN."Priority" AS "CNPriority",

		CN."BkgColor" AS "CNBkgColor",

    AH."Date" AS "CNDate",

    AH."Time" AS "CNTime"



		FROM (



			SELECT



			UC."Clinic" AS "MYCLINICID",



			PT."Patient", PT."Last", PT."First", PT."Sex",

			PR."FirstName", PR."LastName", PR."Year",

			AP."Appointment", AP."Clinic", AP."Reason",



			CASE

			WHEN

			(

				(

					SELECT COUNT(1)

					FROM PTTYPES PT

					WHERE PT."Patient" = AP."Patient"

					AND PT."Deleted" = 0

				) > 0

				AND (

					SELECT COUNT(1)

					FROM PTTYPES PT, PATTYPE PTC

					WHERE PT."Patient" = AP."Patient"

					AND PT."Deleted" = 0

					AND PT."PatType" = PTC."PatType"

					AND PTC."StartChkRequired" = 1

				) = 0

			) OR SCHED_PKG.RequiresStartChk(AP."Appointment") = 0 THEN 0



			WHEN CL."StartChkMethod" = 1 THEN PR."RequireStartCheck"

			WHEN CL."StartChkMethod" = 2 AND (PR."RequireStartCheck" = 1 OR PR2."RequireStartCheck" = 1) THEN 1

			ELSE 0 END                                              AS "RequireStartCheck",



			TRIM(PR."Producer")                                     AS "Producer",

			TO_NUMBER(TRIM(AP."From"))                              AS "StartTime",

			TO_NUMBER(AP."Time0" + AP."Time1" + AP."Time2" +

			AP."Time3" + AP."Time4" + AP."Time5")                   AS "ApptLength",

			CT."Description"                                        AS "ClinicTimeName",

			CH."Chair"                                              AS "ChairId",

			CH."Name"                                               AS "Chair",

			AP."Type"                                               AS "ApptType",

			AP."IsConfirm"                                          AS "ApptIsConfirm",

			TO_CHAR(FLOOR(MONTHS_BETWEEN(SYSDATE,PT."Birth")))      AS "Birth",

			SUBSTR(TRIM(PT."First"),1,1) || TRIM(PT."Last")         AS "FLast",

			TRIM(PT."Last") || SUBSTR(TRIM(PT."First"),1,1)         AS "LFirst",

			SUBSTR(TRIM(PR."FirstName"),1,1) || TRIM(PR."LastName") AS "FLastName",

			TRIM(PR."LastName") || SUBSTR(TRIM(PR."FirstName"),1,1) AS "LFirstName",



			CASE

			WHEN GREATEST(NVL(CS1."Audit",0), NVL(CS2."Audit",0)) = CS1."Audit" THEN CS1."CNState"

			ELSE CS2."CNState"

			END AS "CNState",



			GREATEST(NVL(CS1."Audit",0), NVL(CS2."Audit",0)) AS "CNAudit"



			FROM UCLINIC UC

			JOIN CLINIC CL ON UC."Clinic" = CL."Clinic"

			JOIN CLINICT CT ON CT."Clinic" = UC."Clinic"

			JOIN APPOINT AP ON UC."Clinic" = AP."Clinic" AND AP."From" BETWEEN CT."Start" AND CT."End" - 1



			JOIN PATIENT PT        ON PT."Patient" = AP."Patient"

			JOIN PRODUCER PR       ON PR."Producer" = AP."Producer" AND PR."Inactive" = 0

			JOIN CHAIR CH          ON AP."Chair" = CH."Chair"

			LEFT JOIN PRODUCER PR2 ON AP."Assistant" = PR2."Producer" AND PR2."Inactive" = 0 AND ROWNUM = 1



			LEFT JOIN CHAIRST CS1 ON CS1."Chair" = AP."Chair" AND CS1."ClinicTime" = 0

			LEFT JOIN CHAIRST CS2 ON CS2."Chair" = AP."Chair" AND CS2."ClinicTime" = CT."ClinicTime"



			WHERE UC."User" = vUserId

			AND UC."Clinic" = vClinicId

			AND AP."Date" = TRUNC(SYSDATE)

			AND AP."Status" = 0

			AND AP."Type" IN (0,1,2)



			AND

			(

				(CT."Monday" = 1 AND TRIM(TO_CHAR(AP."Date",'Day')) = 'Monday') OR

				(CT."Tuesday" = 1 AND TRIM(TO_CHAR(AP."Date",'Day')) = 'Tuesday') OR

				(CT."Wednesday" = 1 AND TRIM(TO_CHAR(AP."Date",'Day')) = 'Wednesday') OR

				(CT."Thursday" = 1 AND TRIM(TO_CHAR(AP."Date",'Day')) = 'Thursday') OR

				(CT."Friday" = 1 AND TRIM(TO_CHAR(AP."Date",'Day')) = 'Friday') OR

				(CT."Saturday" = 1 AND TRIM(TO_CHAR(AP."Date",'Day')) = 'Saturday') OR

				(CT."Sunday" = 1 AND TRIM(TO_CHAR(AP."Date",'Day')) = 'Sunday')

			)

			AND

			(

				(CT."StartDate" <= TRUNC(SYSDATE) AND CT."EndDate" >= TRUNC(SYSDATE)) OR

				(CT."StartDate" IS NULL AND CT."EndDate" >= TRUNC(SYSDATE)) OR

				(CT."StartDate" <= TRUNC(SYSDATE) AND CT."EndDate" IS NULL) OR

				(CT."StartDate" IS NULL AND CT."EndDate" IS NULL )

			)



			-- Filter list by start and end time

			AND (vClinicTimeId = 0 OR CT."ClinicTime" = vClinicTimeId)



			-- Filter list by keyword

			AND (



				-- IF keyword search is set to search for First Name field

				(NLS_UPPER(TRIM(vSearchType)) = 'PROVIDERFIRSTNAME' AND

					(NLS_UPPER(TRIM(PR."FirstName")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(PR."FirstName") IS NULL OR LENGTH(TRIM(PR."FirstName")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



				-- IF keyword search is set to search for Last Name field

				OR (NLS_UPPER(TRIM(vSearchType)) = 'PROVIDERLASTNAME' AND

					(NLS_UPPER(TRIM(PR."LastName")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(PR."LastName") IS NULL OR LENGTH(TRIM(PR."LastName")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



				-- IF keyword search is set to search for Provider Code field

				OR (NLS_UPPER(TRIM(vSearchType)) = 'PRODUCER' AND

					(NLS_UPPER(TRIM(PR."Producer")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(PR."Producer") IS NULL OR LENGTH(TRIM(PR."Producer")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



				-- IF keyword search is set to search for First Name field

				OR (NLS_UPPER(TRIM(vSearchType)) = 'PATIENTFIRSTNAME' AND

					(NLS_UPPER(TRIM(PT."First")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(PT."First") IS NULL OR LENGTH(TRIM(PT."First")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



				-- IF keyword search is set to search for Last Name field

				OR (NLS_UPPER(TRIM(vSearchType)) = 'PATIENTLASTNAME' AND

					(NLS_UPPER(TRIM(PT."Last")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(PT."Last") IS NULL OR LENGTH(TRIM(PT."Last")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



			)



		) X



		LEFT JOIN AUDITHIS AH  ON AH."Audit" = X."CNAudit"

		LEFT JOIN CNSTATE CN   ON CN."CNState" = X."CNState"



		-- Filter list by Hide Past status

		WHERE (vHidePast = 0 OR ("StartTime" + "ApptLength") >= (TO_CHAR(SYSDATE, 'HH24') * 60 + TO_CHAR(SYSDATE, 'MI')))



		-- Filter list by Require Start Check status

		AND "RequireStartCheck" = 1



		-- Filter list by Chair state

		AND ( (vIncludeNoNotification = 1 AND (TRIM(X."CNState") IS NULL OR LENGTH(TRIM(X."CNState")) = 0))

		OR TRIM(X."CNState") IN (select regexp_substr(vFilterNotification,'[^,]+', 1, level) from dual connect by regexp_substr(vFilterNotification,'[^,]+', 1, level) is not null))



		-- Order list

		ORDER BY



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERFIRST_ASC' THEN NLS_UPPER("FLastName" || "Producer" || "Year") END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERFIRST_ASC' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERFIRST_ASC' THEN "ApptLength" END ASC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERFIRST_DESC' THEN NLS_UPPER("FLastName" || "Producer" || "Year") END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERFIRST_DESC' THEN "StartTime" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERFIRST_DESC' THEN "ApptLength" END DESC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERLAST_ASC' THEN NLS_UPPER("LFirstName" || "Producer" || "Year") END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERLAST_ASC' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERLAST_ASC' THEN "ApptLength" END ASC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERLAST_DESC' THEN NLS_UPPER("LFirstName" || "Producer" || "Year") END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERLAST_DESC' THEN "StartTime" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERLAST_DESC' THEN "ApptLength" END DESC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMEFIRST_ASC' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMEFIRST_ASC' THEN "ApptLength" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMEFIRST_ASC' THEN NLS_UPPER("FLastName" || "Producer" || "Year") END ASC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMEFIRST_DESC' THEN "StartTime" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMEFIRST_DESC' THEN "ApptLength" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMEFIRST_DESC' THEN NLS_UPPER("FLastName" || "Producer" || "Year") END DESC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMELAST_ASC' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMELAST_ASC' THEN "ApptLength" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMELAST_ASC' THEN NLS_UPPER("LFirstName" || "Producer" || "Year") END ASC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMELAST_DESC' THEN "StartTime" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMELAST_DESC' THEN "ApptLength" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMELAST_DESC' THEN NLS_UPPER("LFirstName" || "Producer" || "Year") END DESC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CLINIC_ASC' THEN NLS_UPPER("Chair") END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CLINIC_ASC' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CLINIC_ASC' THEN "ApptLength" END ASC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CLINIC_DESC' THEN NLS_UPPER("Chair") END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CLINIC_DESC' THEN "StartTime" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CLINIC_DESC' THEN "ApptLength" END DESC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTFIRST_ASC' THEN NLS_UPPER("FLast" || "Sex" || "Birth") END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTFIRST_ASC' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTFIRST_ASC' THEN "ApptLength" END ASC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTFIRST_DESC' THEN NLS_UPPER("FLast" || "Sex" || "Birth") END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTFIRST_DESC' THEN "StartTime" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTFIRST_DESC' THEN "ApptLength" END DESC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTLAST_ASC' THEN NLS_UPPER("LFirst" || "Sex" || "Birth") END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTLAST_ASC' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTLAST_ASC' THEN "ApptLength" END ASC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTLAST_DESC' THEN NLS_UPPER("LFirst" || "Sex" || "Birth") END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTLAST_DESC' THEN "StartTime" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTLAST_DESC' THEN "ApptLength" END DESC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CHAIRSTATE' THEN NVL(CN."Priority", -1) END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CHAIRSTATE' THEN AH."Date" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CHAIRSTATE' THEN AH."Time" END ASC,

    CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CHAIRSTATE' THEN AH."Audit" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CHAIRSTATE' THEN NLS_UPPER("Chair") END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CHAIRSTATE' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CHAIRSTATE' THEN "ApptLength" END ASC;



	END;



	/**

  * Procedure used to get all appointments available

	* param: vUserId INPUT: USERS.User

	* param: vClinicId INPUT: Clinic ID to filter the appointments - If set to 0, the list will be filtered by all clinics the instructor has an access to.

	* param: vClinicTimeId INPUT: Clinic Time ID to filter the appointments - If set to 0, the list will contain all clinic times the clinic has.

	* param: vHidePast INPUT: Include/exclude past appointments (time passed).

	* param: vShowOnlyReqStartChk INPUT: Include/exclude appointment that does not require Start Check

	* param: vIncludeNoNotification INPUT: Include/exclude appointments without chair notification state.

	* param: vSearchKeyword INPUT: Keyword for filtering the appointments.

	* param: vSearchType INPUT: Field to search using the keyword (Provider First/Last Name, Code, Patient First/Last Name)

	* param: vFilterNotification INPUT: list of chair state notification IDs to include in the appointment list (separated by comma)

	* param: vOrderBy INPUT: keyword to order the list by.

	* param: vResults OUTPUT: Weak cursor containing list of appointments matching given criteria

  */

	PROCEDURE getapptalllist(IN vuserid integer, IN vclinicid integer, IN vclinictimeid integer, IN vhidepast integer, IN vincludenonotification integer, IN vsearchkeyword character varying, IN vsearchtype character varying, IN vfilternotification character varying, IN vorderby character varying, OUT vresults cursor_pkg.weakcursor) IS

	BEGIN



		OPEN vResults FOR



		SELECT

		X.*,

    CN."Priority" AS "CNPriority",

		CN."BkgColor" AS "CNBkgColor",

    AH."Date" AS "CNDate",

    AH."Time" AS "CNTime"



		FROM (



			SELECT



			UC."Clinic" AS "MYCLINICID",



			PT."Patient", PT."Last", PT."First", PT."Sex",

			PR."FirstName", PR."LastName", PR."Year",

			AP."Appointment", AP."Clinic", AP."Reason",



			TRIM(PR."Producer")                                     AS "Producer",

			TO_NUMBER(TRIM(AP."From"))                              AS "StartTime",

			TO_NUMBER(AP."Time0" + AP."Time1" + AP."Time2" +

			AP."Time3" + AP."Time4" + AP."Time5")                   AS "ApptLength",

			CT."Description"                                        AS "ClinicTimeName",

			CH."Chair"                                              AS "ChairId",

			CH."Name"                                               AS "Chair",

			AP."Type"                                               AS "ApptType",

			AP."IsConfirm"                                          AS "ApptIsConfirm",

			TO_CHAR(FLOOR(MONTHS_BETWEEN(SYSDATE,PT."Birth")))      AS "Birth",

			SUBSTR(TRIM(PT."First"),1,1) || TRIM(PT."Last")         AS "FLast",

			TRIM(PT."Last") || SUBSTR(TRIM(PT."First"),1,1)         AS "LFirst",

			SUBSTR(TRIM(PR."FirstName"),1,1) || TRIM(PR."LastName") AS "FLastName",

			TRIM(PR."LastName") || SUBSTR(TRIM(PR."FirstName"),1,1) AS "LFirstName",



			CASE

			WHEN GREATEST(NVL(CS1."Audit",0), NVL(CS2."Audit",0)) = CS1."Audit" THEN CS1."CNState"

			ELSE CS2."CNState"

			END AS "CNState",



			GREATEST(NVL(CS1."Audit",0), NVL(CS2."Audit",0)) AS "CNAudit"



			FROM UCLINIC UC

			JOIN CLINIC CL ON UC."Clinic" = CL."Clinic"

			JOIN CLINICT CT ON CT."Clinic" = UC."Clinic"

			JOIN APPOINT AP ON UC."Clinic" = AP."Clinic" AND AP."From" BETWEEN CT."Start" AND CT."End" - 1



			JOIN PATIENT PT        ON PT."Patient" = AP."Patient"

			JOIN PRODUCER PR       ON PR."Producer" = AP."Producer" AND PR."Inactive" = 0

			JOIN CHAIR CH          ON AP."Chair" = CH."Chair"

			LEFT JOIN PRODUCER PR2 ON AP."Assistant" = PR2."Producer" AND PR2."Inactive" = 0 AND ROWNUM = 1



			LEFT JOIN CHAIRST CS1 ON CS1."Chair" = AP."Chair" AND CS1."ClinicTime" = 0

			LEFT JOIN CHAIRST CS2 ON CS2."Chair" = AP."Chair" AND CS2."ClinicTime" = CT."ClinicTime"



			WHERE UC."User" = vUserId

			AND UC."Clinic" = vClinicId

			AND AP."Date" = TRUNC(SYSDATE)

			AND AP."Status" = 0

			AND AP."Type" IN (0,1,2)



			AND

			(

				(CT."Monday" = 1 AND TRIM(TO_CHAR(AP."Date",'Day')) = 'Monday') OR

				(CT."Tuesday" = 1 AND TRIM(TO_CHAR(AP."Date",'Day')) = 'Tuesday') OR

				(CT."Wednesday" = 1 AND TRIM(TO_CHAR(AP."Date",'Day')) = 'Wednesday') OR

				(CT."Thursday" = 1 AND TRIM(TO_CHAR(AP."Date",'Day')) = 'Thursday') OR

				(CT."Friday" = 1 AND TRIM(TO_CHAR(AP."Date",'Day')) = 'Friday') OR

				(CT."Saturday" = 1 AND TRIM(TO_CHAR(AP."Date",'Day')) = 'Saturday') OR

				(CT."Sunday" = 1 AND TRIM(TO_CHAR(AP."Date",'Day')) = 'Sunday')

			)

			AND

			(

				(CT."StartDate" <= TRUNC(SYSDATE) AND CT."EndDate" >= TRUNC(SYSDATE)) OR

				(CT."StartDate" IS NULL AND CT."EndDate" >= TRUNC(SYSDATE)) OR

				(CT."StartDate" <= TRUNC(SYSDATE) AND CT."EndDate" IS NULL) OR

				(CT."StartDate" IS NULL AND CT."EndDate" IS NULL )

			)



			-- Filter list by start and end time

			AND (vClinicTimeId = 0 OR CT."ClinicTime" = vClinicTimeId)



			-- Filter list by keyword

			AND (



				-- IF keyword search is set to search for First Name field

				(NLS_UPPER(TRIM(vSearchType)) = 'PROVIDERFIRSTNAME' AND

					(NLS_UPPER(TRIM(PR."FirstName")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(PR."FirstName") IS NULL OR LENGTH(TRIM(PR."FirstName")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



				-- IF keyword search is set to search for Last Name field

				OR (NLS_UPPER(TRIM(vSearchType)) = 'PROVIDERLASTNAME' AND

					(NLS_UPPER(TRIM(PR."LastName")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(PR."LastName") IS NULL OR LENGTH(TRIM(PR."LastName")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



				-- IF keyword search is set to search for Provider Code field

				OR (NLS_UPPER(TRIM(vSearchType)) = 'PRODUCER' AND

					(NLS_UPPER(TRIM(PR."Producer")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(PR."Producer") IS NULL OR LENGTH(TRIM(PR."Producer")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



				-- IF keyword search is set to search for First Name field

				OR (NLS_UPPER(TRIM(vSearchType)) = 'PATIENTFIRSTNAME' AND

					(NLS_UPPER(TRIM(PT."First")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(PT."First") IS NULL OR LENGTH(TRIM(PT."First")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



				-- IF keyword search is set to search for Last Name field

				OR (NLS_UPPER(TRIM(vSearchType)) = 'PATIENTLASTNAME' AND

					(NLS_UPPER(TRIM(PT."Last")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(PT."Last") IS NULL OR LENGTH(TRIM(PT."Last")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



			)



		) X



		LEFT JOIN AUDITHIS AH  ON AH."Audit" = X."CNAudit"

		LEFT JOIN CNSTATE CN   ON CN."CNState" = X."CNState"



		-- Filter list by Hide Past status

		WHERE (vHidePast = 0 OR ("StartTime" + "ApptLength") >= (TO_CHAR(SYSDATE, 'HH24') * 60 + TO_CHAR(SYSDATE, 'MI')))



		-- Filter list by Chair state

		AND ( (vIncludeNoNotification = 1 AND (TRIM(X."CNState") IS NULL OR LENGTH(TRIM(X."CNState")) = 0))

		OR TRIM(X."CNState") IN (SELECT regexp_substr(vFilterNotification,'[^,]+', 1, level) from dual connect by regexp_substr(vFilterNotification,'[^,]+', 1, level) is not null))



		-- Order list

		ORDER BY



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERFIRST_ASC' THEN NLS_UPPER("FLastName" || "Producer" || "Year") END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERFIRST_ASC' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERFIRST_ASC' THEN "ApptLength" END ASC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERFIRST_DESC' THEN NLS_UPPER("FLastName" || "Producer" || "Year") END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERFIRST_DESC' THEN "StartTime" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERFIRST_DESC' THEN "ApptLength" END DESC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERLAST_ASC' THEN NLS_UPPER("LFirstName" || "Producer" || "Year") END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERLAST_ASC' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERLAST_ASC' THEN "ApptLength" END ASC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERLAST_DESC' THEN NLS_UPPER("LFirstName" || "Producer" || "Year") END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERLAST_DESC' THEN "StartTime" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PROVIDERLAST_DESC' THEN "ApptLength" END DESC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMEFIRST_ASC' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMEFIRST_ASC' THEN "ApptLength" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMEFIRST_ASC' THEN NLS_UPPER("FLastName" || "Producer" || "Year") END ASC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMEFIRST_DESC' THEN "StartTime" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMEFIRST_DESC' THEN "ApptLength" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMEFIRST_DESC' THEN NLS_UPPER("FLastName" || "Producer" || "Year") END DESC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMELAST_ASC' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMELAST_ASC' THEN "ApptLength" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMELAST_ASC' THEN NLS_UPPER("LFirstName" || "Producer" || "Year") END ASC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMELAST_DESC' THEN "StartTime" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMELAST_DESC' THEN "ApptLength" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'TIMELAST_DESC' THEN NLS_UPPER("LFirstName" || "Producer" || "Year") END DESC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CLINIC_ASC' THEN NLS_UPPER("Chair") END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CLINIC_ASC' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CLINIC_ASC' THEN "ApptLength" END ASC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CLINIC_DESC' THEN NLS_UPPER("Chair") END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CLINIC_DESC' THEN "StartTime" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CLINIC_DESC' THEN "ApptLength" END DESC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTFIRST_ASC' THEN NLS_UPPER("FLast" || "Sex" || "Birth") END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTFIRST_ASC' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTFIRST_ASC' THEN "ApptLength" END ASC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTFIRST_DESC' THEN NLS_UPPER("FLast" || "Sex" || "Birth") END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTFIRST_DESC' THEN "StartTime" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTFIRST_DESC' THEN "ApptLength" END DESC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTLAST_ASC' THEN NLS_UPPER("LFirst" || "Sex" || "Birth") END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTLAST_ASC' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTLAST_ASC' THEN "ApptLength" END ASC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTLAST_DESC' THEN NLS_UPPER("LFirst" || "Sex" || "Birth") END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTLAST_DESC' THEN "StartTime" END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'PATIENTLAST_DESC' THEN "ApptLength" END DESC,



		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CHAIRSTATE' THEN NVL(CN."Priority", -1) END DESC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CHAIRSTATE' THEN AH."Date" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CHAIRSTATE' THEN AH."Time" END ASC,

    CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CHAIRSTATE' THEN AH."Audit" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CHAIRSTATE' THEN NLS_UPPER("Chair") END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CHAIRSTATE' THEN "StartTime" END ASC,

		CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'CHAIRSTATE' THEN "ApptLength" END ASC;



	END;





  /**

  * Procedure to count all unapproved items for the appointment<p/>

  * param: vAppointment IN: Appointment ID<p/>

  * param: results_cur OUT: Results cursor containing row of counts:<p/>

  * <li>NumTrx - Count of Treatments <br />

  * <li>NumNotes - Count of Notes <br />

  * <li>TxMissingStartChk - check if there are treatments missing start check <br />

  * <li>LastStartChkUser - Last Start Checked USER ID<br />

  */

  PROCEDURE getapptapprovecount(IN vappointment integer, OUT results_cur cursor_pkg.weakcursor) IS

  BEGIN

    OPEN results_cur FOR

    SELECT

		FPORTAL_PKG.GetApptRequireStartCheck(vAppointment)	AS "RequireStartCheck",

    FPORTAL_PKG.GetApptTrxCount(vAppointment)           AS "NumTrx",

    FPORTAL_PKG.GetApptOrthoVisitCount(vAppointment)    AS "NumOrthoVisit",

    FPORTAL_PKG.GetApptTrxNoteCount(vAppointment)       AS "NumNotes",

    FPORTAL_PKG.GetApptOrthoVisitNoteCount(vAppointment) AS "NumOrthoVisitNotes",

    FPORTAL_PKG.HasApptTxMissingStartChk(vAppointment)  AS "TxMissingStartChk",

    FPORTAL_PKG.GetApptStartChkUser(vAppointment)       AS "LastStartChkUser"

    FROM DUAL;

    EXCEPTION WHEN NO_DATA_FOUND THEN

    results_cur := NULL;

  END;



  /**

  * Procedure used to get all provider StartChecked by current instructor

  * param: vUserId INPUT: Instructor ID<p/>

  * param: vClinicId INPUT: ID of Clinic to view list of appointments from (0 = all clinics)<p/>

  * param: vClinicTimeId INPUT: ID of Clinic Time to view list of appointment from (0 = all clinic times)<p/>

  * param: vSearchKeyword INPUT: Keyword to search list<p/>

  * param: vSearchType INPUT: Field used to search keyword<p/>

  * param: vProviderType INPUT: Provider Type to search list<p/>

  * param: vProviderGroup INPUT: Provider Group to search list<p/>

  * param: vOrderBy INPUT: DESC OR ASC<p/>

  * param: vNumRows INPUT: Number of rows to return<p/>

  * param: vPage INPUT: Number of page to return (page is a group of rows)<p/>

  * param: vCurrentPage OUTPUT: Actual page of the list<p/>

  * param: vTotalPage OUTPUT: Total number of pages available<p/>

  * param: vResults OUTPUT: Weak cursor to contain the data retrieved<p/>

  */

  PROCEDURE getprovmylist(IN vuserid integer, IN vclinicid integer, IN vclinictimeid integer, IN vsearchkeyword character varying, IN vsearchtype character varying, IN vprovidertype character varying, IN vprovidergroup character varying, IN vorderby character varying, IN vnumrows integer, IN vpage integer, OUT vcurrentpage integer, OUT vtotalpage integer, OUT vresults cursor_pkg.weakcursor) IS



		vStartTime INTEGER;

		vEndTime INTEGER;



		vMinRow INTEGER; -- minimum item row number allowed based on current page/ number of items per page

		vMaxRow INTEGER; -- maximum item row number allowed based on current page/ number of items per page



	BEGIN



		-- Define Clinic Time based on Clinic Time ID

		IF vClinicTimeId = 0 THEN

			vStartTime := 0; -- 00:00:00

			vEndTime := 1440; -- 24:00:00

		ELSE

			SELECT "Start", "End"

			INTO vStartTime, vEndTime

			FROM CLINICT

			WHERE "ClinicTime" = vClinicTimeId

			AND ROWNUM = 1;

		END IF;



		-- Get Total Number of pages available

		SELECT CEIL(COUNT(1)/vNumRows) INTO vTotalPage

		FROM

		(

			SELECT DISTINCT AP."Appointment"



			FROM APPOINT AP

			JOIN STARTCHK SC ON SC."Appointment" = AP."Appointment" AND AP."Producer" = SC."Provider"

			JOIN AUDITHIS AH ON SC."Audit" = AH."Audit"

			JOIN USERS UR ON SC."Provider" = UR."Producer"

			JOIN PRODUCER PR ON PR."Producer" = SC."Provider"

			JOIN PRODTYPE PT ON PR."TypeCode" = PT."Code"



			WHERE AP."Date" = TRUNC(SYSDATE)

			AND AH."Date" = TRUNC(SYSDATE)

			AND AP."Type" IN (0,1,2)

			AND SC."AppUser" = vUserId



			-- Filter list by clinic ID

			-- If clinic ID is defined, filter by the clinic ID

			-- If the ID is NOT defined, filter by all clinics that user has access to

			AND ((vClinicId = 0 AND (AP."Clinic" IN (SELECT UC."Clinic" FROM UCLINIC UC WHERE UC."User" = vUserId))) OR AP."Clinic" = vClinicId)



			-- Filter list by start and end time

			AND (vClinicTimeId = 0 OR FPORTAL_PKG.GetClinicTime(AP."Appointment") = vClinicTimeId)



			-- Filter list by provider type

			-- If provider type is defined, filter list by provider type begins with the field

			-- If provider type is NOT defined, get all

			AND (NLS_UPPER(TRIM(PR."TypeCode")) LIKE NLS_UPPER(TRIM(vProviderType)) || '%' OR (TRIM(vProviderType) IS NULL OR LENGTH(TRIM(vProviderType)) = 0))



			-- Filter list by provider group

			-- If provider group is defined, filter list by provider group starting with the field

			-- If provider group is NOT defined, get all

			AND (NLS_UPPER(TRIM(PR."PGroup")) LIKE NLS_UPPER(TRIM(vProviderGroup)) || '%' OR (TRIM(vProviderGroup) IS NULL OR LENGTH(TRIM(vProviderGroup)) = 0))



			-- Filter list by keyword

			AND (



				-- IF keyword search is set to search for First Name field

				(NLS_UPPER(TRIM(vSearchType)) = 'FIRSTNAME' AND

					(NLS_UPPER(TRIM(UR."First")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(UR."First") IS NULL OR LENGTH(TRIM(UR."First")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



				-- IF keyword search is set to search for Last Name field

				OR (NLS_UPPER(TRIM(vSearchType)) = 'LASTNAME' AND

					(NLS_UPPER(TRIM(UR."Name")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(UR."Name") IS NULL OR LENGTH(TRIM(UR."Name")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



				-- IF keyword search is set to search for Provider Code field

				OR (NLS_UPPER(TRIM(vSearchType)) = 'PRODUCER' AND

					(NLS_UPPER(TRIM(UR."Producer")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(UR."Producer") IS NULL OR LENGTH(TRIM(UR."Producer")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



				-- IF keyword search is set to search for Provider Year field

				OR (NLS_UPPER(TRIM(vSearchType)) = 'YEAR' AND

					(NLS_UPPER(TRIM(PR."Year")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(PR."Year") IS NULL OR LENGTH(TRIM(PR."Year")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



			)

		);



		-- Calculate current page number based on total pages allowed by search criteria.

		-- If page number input is greater than total pages allowed for the search criteria,

		-- Current page will be the last page of the list

		IF vTotalPage < vPage THEN

			vCurrentPage := vTotalPage;



		-- If page number input is invalid (less than 1),

		-- Current page will be the first page of the list

		ELSIF vPage < 1 THEN

			vCurrentPage := 1;



		-- If page number input is valid, current page will be same as input value

		ELSE

			vCurrentPage := vPage;

		END IF;



		-- Calculate minimum and maximum row number based on current page number

		vMinRow := (vCurrentPage - 1) * vNumRows + 1;

		vMaxRow := vCurrentPage * vNumRows;



		-- Generate list

		OPEN vResults FOR



		SELECT R1.* FROM

		(

			SELECT R2.*, ROWNUM AS "RowNum" FROM

			(

				SELECT DISTINCT

					UR."User",

					TRIM(UR."First") AS "FirstName",

					TRIM(UR."Name") AS "LastName",

					SUBSTR(TRIM(UR."First"),1,1) || TRIM(UR."Name") AS "FLast",

					TRIM(UR."Name") || SUBSTR(TRIM(UR."First"),1,1) AS "LFirst",

					UR."Producer" AS "Producer",

					TRIM(PR."Year") AS "Year",

					TRIM(PR."TypeCode") AS "TypeCode",

					TRIM(PR."PGroup") AS "PGroup"



				FROM APPOINT AP

				JOIN STARTCHK SC ON SC."Appointment" = AP."Appointment" AND AP."Producer" = SC."Provider"

				JOIN AUDITHIS AH ON SC."Audit" = AH."Audit"

				JOIN USERS UR ON SC."Provider" = UR."Producer"

				JOIN PRODUCER PR ON PR."Producer" = SC."Provider"

				JOIN PRODTYPE PT ON PR."TypeCode" = PT."Code"



				WHERE AP."Date" = TRUNC(SYSDATE)

				AND AH."Date" = TRUNC(SYSDATE)

				AND AP."Type" IN (0,1,2)

				AND SC."AppUser" = vUserId



				-- Filter list by clinic ID

				-- If clinic ID is defined, filter by the clinic ID

				-- If the ID is NOT defined, filter by all clinics that user has access to

				AND ((vClinicId = 0 AND (AP."Clinic" IN (SELECT UC."Clinic" FROM UCLINIC UC WHERE UC."User" = vUserId))) OR AP."Clinic" = vClinicId)



				-- Filter list by start and end time

				AND (vClinicTimeId = 0 OR FPORTAL_PKG.GetClinicTime(AP."Appointment") = vClinicTimeId)



				-- Filter list by provider type

				-- If provider type is defined, filter list by provider type begins with the field

				-- If provider type is NOT defined, get all

				AND (NLS_UPPER(TRIM(PR."TypeCode")) LIKE NLS_UPPER(TRIM(vProviderType)) || '%' OR (TRIM(vProviderType) IS NULL OR LENGTH(TRIM(vProviderType)) = 0))



				-- Filter list by provider group

				-- If provider group is defined, filter list by provider group starting with the field

				-- If provider group is NOT defined, get all

				AND (NLS_UPPER(TRIM(PR."PGroup")) LIKE NLS_UPPER(TRIM(vProviderGroup)) || '%' OR (TRIM(vProviderGroup) IS NULL OR LENGTH(TRIM(vProviderGroup)) = 0))



				-- Filter list by keyword

				AND (



					-- IF keyword search is set to search for First Name field

					(NLS_UPPER(TRIM(vSearchType)) = 'FIRSTNAME' AND

						(NLS_UPPER(TRIM(UR."First")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(UR."First") IS NULL OR LENGTH(TRIM(UR."First")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



					-- IF keyword search is set to search for Last Name field

					OR (NLS_UPPER(TRIM(vSearchType)) = 'LASTNAME' AND

						(NLS_UPPER(TRIM(UR."Name")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(UR."Name") IS NULL OR LENGTH(TRIM(UR."Name")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



					-- IF keyword search is set to search for Provider Code field

					OR (NLS_UPPER(TRIM(vSearchType)) = 'PRODUCER' AND

						(NLS_UPPER(TRIM(UR."Producer")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(UR."Producer") IS NULL OR LENGTH(TRIM(UR."Producer")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



					-- IF keyword search is set to search for Provider Year field

					OR (NLS_UPPER(TRIM(vSearchType)) = 'YEAR' AND

						(NLS_UPPER(TRIM(PR."Year")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(PR."Year") IS NULL OR LENGTH(TRIM(PR."Year")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))

				)



				-- Order list

				ORDER BY

				CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'FIRST_ASC' THEN NLS_UPPER("FLast" || "Producer" || "Year") END ASC,

				CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'FIRST_DESC' THEN NLS_UPPER("FLast" || "Producer" || "Year") END DESC,

				CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'LAST_ASC' THEN NLS_UPPER("LFirst" || "Producer" || "Year") END ASC,

				CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'LAST_DESC' THEN NLS_UPPER("LFirst" || "Producer" || "Year") END DESC



			) R2

			WHERE ROWNUM <= vMaxRow



		) R1

		WHERE "RowNum" >= vMinRow;



	END;



  /**

  * Procedure to count all unapproved items for the provider<p/>

  * param: vUser IN: User ID of the provider<p/>

  * param: vProducer IN: Provider Code in USERS."Producer"<p/>

  * param: vMedicaidCode IN: list of procedure codes defined as Medicaid code<p/>

  * param: results_cur OUT: Results cursor containing row of counts:<p/>

  * - TxCount: unapproved treatment count<p/>

  * - NoteCount: unapproved note count<p/>

  * - FormCount: unapproved forms count<p/>

  * - FindingCount: unapproved findings/conditions count<p/>

  * - PerioCount: unapproved perio count<p/>

  * - LetterCount: unapproved letter attachments count<p/>

  */

  PROCEDURE getprovapprovecount(IN vuser integer, IN vproducer character varying, IN vmedicaidcode character varying, OUT results_cur cursor_pkg.weakcursor) IS

  BEGIN

    OPEN results_cur FOR

    SELECT

    FPORTAL_PKG.CountTx(vProducer, vMedicaidCode) AS "TxCount",

    FPORTAL_PKG.CountNote(vUser) AS "NoteCount",

    FPORTAL_PKG.CountForm(vUser) AS "FormCount",

    FPORTAL_PKG.CountFind(vProducer, vMedicaidCode) AS "FindingCount",

    FPORTAL_PKG.CountPerio(vUser) AS "PerioCount",

    FPORTAL_PKG.CountLetter(vUser) AS "LetterCount",

    FPORTAL_PKG.CountOrthoVisits(vProducer) AS "OrthoVisitsCount"

    FROM DUAL;



    EXCEPTION WHEN NO_DATA_FOUND THEN

    results_cur := NULL;

  END;



  /**

  * Procedure used to get all provider reserved in clinic the instructor has access to

  * param: vUserId INPUT: Instructor ID<p/>

  * param: vClinicId INPUT: ID of Clinic to view list of appointments from (0 = all clinics)<p/>

  * param: vClinicTimeId INPUT: ID of Clinic Time to view list of appointment from (0 = all clinic times)<p/>

  * param: vSearchKeyword INPUT: Keyword to search list<p/>

  * param: vSearchType INPUT: Field used to search keyword<p/>

  * param: vProviderType INPUT: Provider Type to search list<p/>

  * param: vProviderGroup INPUT: Provider Group to search list<p/>

  * param: vOrderBy INPUT: DESC OR ASC<p/>

  * param: vNumRows INPUT: Number of rows to return<p/>

  * param: vPage INPUT: Number of page to return (page is a group of rows)<p/>

  * param: vCurrentPage OUTPUT: Actual page of the list<p/>

  * param: vTotalPage OUTPUT: Total number of pages available<p/>

  * param: vResults OUTPUT: Weak cursor to contain the data retrieved<p/>

  */

  --AX-40621

	PROCEDURE getprovalllist(IN vuserid integer, IN vclinicid integer, IN vclinictimeid integer, IN vsearchkeyword character varying, IN vsearchtype character varying, IN vprovidertype character varying, IN vprovidergroup character varying, IN vorderby character varying, IN vnumrows integer, IN vpage integer, OUT vcurrentpage integer, OUT vtotalpage integer, OUT vresults cursor_pkg.weakcursor) IS



		vStartTime INTEGER;

		vEndTime INTEGER;



		vMinRow INTEGER; -- minimum item row number allowed based on current page/ number of items per page

		vMaxRow INTEGER; -- maximum item row number allowed based on current page/ number of items per page



	BEGIN



		-- Define Clinic Time based on Clinic Time ID

		IF vClinicTimeId = 0 THEN

			vStartTime := 0; -- 00:00:00

			vEndTime := 1440; -- 24:00:00

		ELSE

			SELECT "Start", "End"

			INTO vStartTime, vEndTime

			FROM CLINICT

			WHERE "ClinicTime" = vClinicTimeId

			AND ROWNUM = 1;

		END IF;



		-- Get Total Number of pages available

		SELECT CEIL(COUNT(1)/vNumRows) INTO vTotalPage

		FROM

		(

			SELECT DISTINCT UR."User"



			FROM RESERVE RE

			JOIN CHAIR CH ON RE."Chair" = CH."Chair"

			JOIN USERS UR ON RE."Producer" = UR."Producer"

			JOIN PRODUCER PR ON RE."Producer" = PR."Producer"



			WHERE LENGTH(TRIM(RE."Producer")) > 0

			AND RE."Date" = TRUNC(SYSDATE)

			AND RE."Cancelled" = 0

			AND RE."Unavailable" = 0

			AND RE."Closed" = 0

			AND RE."Holiday" = 0

			AND RE."Vacation" = 0

			AND UR."Deleted" = 0



			-- Filter list by clinic ID

			-- If clinic ID is defined, filter by the clinic ID

			-- If the ID is NOT defined, filter by all clinics that user has access to

			AND ((vClinicId = 0 AND (CH."Clinic" IN (SELECT UC."Clinic" FROM UCLINIC UC WHERE UC."User" = vUserId))) OR CH."Clinic" = vClinicId)



			-- Filter list by start and end time

			AND (RE."Start" < vEndTime AND RE."End" > vStartTime)



			-- Filter list by provider type

			-- If provider type is defined, filter list by provider type begins with the field

			-- If provider type is NOT defined, get all

			AND (NLS_UPPER(TRIM(PR."TypeCode")) LIKE NLS_UPPER(TRIM(vProviderType)) || '%' OR (TRIM(vProviderType) IS NULL OR LENGTH(TRIM(vProviderType)) = 0))



			-- Filter list by provider group

			-- If provider group is defined, filter list by provider group starting with the field

			-- If provider group is NOT defined, get all

			AND (NLS_UPPER(TRIM(PR."PGroup")) LIKE NLS_UPPER(TRIM(vProviderGroup)) || '%' OR (TRIM(vProviderGroup) IS NULL OR LENGTH(TRIM(vProviderGroup)) = 0))



			-- Filter list by keyword

			AND (



				-- IF keyword search is set to search for First Name field

				(NLS_UPPER(TRIM(vSearchType)) = 'FIRSTNAME' AND

					(NLS_UPPER(TRIM(UR."First")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(UR."First") IS NULL OR LENGTH(TRIM(UR."First")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



				-- IF keyword search is set to search for Last Name field

				OR (NLS_UPPER(TRIM(vSearchType)) = 'LASTNAME' AND

					(NLS_UPPER(TRIM(UR."Name")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(UR."Name") IS NULL OR LENGTH(TRIM(UR."Name")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



				-- IF keyword search is set to search for Provider Code field

				OR (NLS_UPPER(TRIM(vSearchType)) = 'PRODUCER' AND

					(NLS_UPPER(TRIM(RE."Producer")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(RE."Producer") IS NULL OR LENGTH(TRIM(RE."Producer")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



				-- IF keyword search is set to search for Provider Year field

				OR (NLS_UPPER(TRIM(vSearchType)) = 'YEAR' AND

					(NLS_UPPER(TRIM(PR."Year")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(PR."Year") IS NULL OR LENGTH(TRIM(PR."Year")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



			)

		);



		-- Calculate current page number based on total pages allowed by search criteria.

		-- If page number input is greater than total pages allowed for the search criteria,

		-- Current page will be the last page of the list

		IF vTotalPage < vPage THEN

			vCurrentPage := vTotalPage;



		-- If page number input is invalid (less than 1),

		-- Current page will be the first page of the list

		ELSIF vPage < 1 THEN

			vCurrentPage := 1;



		-- If page number input is valid, current page will be same as input value

		ELSE

			vCurrentPage := vPage;

		END IF;



		-- Calculate minimum and maximum row number based on current page number

		vMinRow := (vCurrentPage - 1) * vNumRows + 1;

		vMaxRow := vCurrentPage * vNumRows;



		-- Generate list

		OPEN vResults FOR



		SELECT R1.* FROM

		(

			SELECT R2.*, ROWNUM AS "RowNum" FROM

			(

				SELECT DISTINCT

					UR."User",

					TRIM(UR."First") AS "FirstName",

					TRIM(UR."Name") AS "LastName",

					SUBSTR(TRIM(UR."First"),1,1) || TRIM(UR."Name") AS "FLast",

					TRIM(UR."Name") || SUBSTR(TRIM(UR."First"),1,1) AS "LFirst",

					RE."Producer" AS "Producer",

					TRIM(PR."Year") AS "Year",

					TRIM(PR."TypeCode") AS "TypeCode",

					TRIM(PR."PGroup") AS "PGroup"



				FROM RESERVE RE

				JOIN CHAIR CH ON RE."Chair" = CH."Chair"

				JOIN USERS UR ON RE."Producer" = UR."Producer"

				JOIN PRODUCER PR ON RE."Producer" = PR."Producer"



				WHERE LENGTH(TRIM(RE."Producer")) > 0

				AND RE."Date" = TRUNC(SYSDATE)

				AND RE."Cancelled" = 0

				AND RE."Unavailable" = 0

				AND RE."Closed" = 0

				AND RE."Holiday" = 0

				AND RE."Vacation" = 0

				AND UR."Deleted" = 0



				-- Filter list by clinic ID

				-- If clinic ID is defined, filter by the clinic ID

				-- If the ID is NOT defined, filter by all clinics that user has access to

				AND ((vClinicId = 0 AND (CH."Clinic" IN (SELECT UC."Clinic" FROM UCLINIC UC WHERE UC."User" = vUserId))) OR CH."Clinic" = vClinicId)



				-- Filter list by start and end time

				AND (RE."Start" < vEndTime AND RE."End" > vStartTime)



				-- Filter list by provider type

				-- If provider type is defined, filter list by provider type begins with the field

				-- If provider type is NOT defined, get all

				AND (NLS_UPPER(TRIM(PR."TypeCode")) LIKE NLS_UPPER(TRIM(vProviderType)) || '%' OR (TRIM(vProviderType) IS NULL OR LENGTH(TRIM(vProviderType)) = 0))



				-- Filter list by provider group

				-- If provider group is defined, filter list by provider group starting with the field

				-- If provider group is NOT defined, get all

				AND (NLS_UPPER(TRIM(PR."PGroup")) LIKE NLS_UPPER(TRIM(vProviderGroup)) || '%' OR (TRIM(vProviderGroup) IS NULL OR LENGTH(TRIM(vProviderGroup)) = 0))



				-- Filter list by keyword

				AND (



					-- IF keyword search is set to search for First Name field

					(NLS_UPPER(TRIM(vSearchType)) = 'FIRSTNAME' AND

						(NLS_UPPER(TRIM(UR."First")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(UR."First") IS NULL OR LENGTH(TRIM(UR."First")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



					-- IF keyword search is set to search for Last Name field

					OR (NLS_UPPER(TRIM(vSearchType)) = 'LASTNAME' AND

						(NLS_UPPER(TRIM(UR."Name")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(UR."Name") IS NULL OR LENGTH(TRIM(UR."Name")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



					-- IF keyword search is set to search for Provider Code field

					OR (NLS_UPPER(TRIM(vSearchType)) = 'PRODUCER' AND

						(NLS_UPPER(TRIM(RE."Producer")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(RE."Producer") IS NULL OR LENGTH(TRIM(RE."Producer")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))



					-- IF keyword search is set to search for Provider Year field

					OR (NLS_UPPER(TRIM(vSearchType)) = 'YEAR' AND

						(NLS_UPPER(TRIM(PR."Year")) LIKE NLS_UPPER(TRIM(vSearchKeyword)) || '%' OR ((TRIM(PR."Year") IS NULL OR LENGTH(TRIM(PR."Year")) = 0) AND (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0))))

				)



				-- Order list

				ORDER BY

				CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'FIRST_ASC' THEN NLS_UPPER(SUBSTR(TRIM(UR."First"),1,1) || TRIM(UR."Name")  || PR."Producer" || PR."Year") END ASC,

				CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'FIRST_DESC' THEN NLS_UPPER(SUBSTR(TRIM(UR."First"),1,1) || TRIM(UR."Name") || PR."Producer" || PR."Year") END DESC,

				CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'LAST_ASC' THEN NLS_UPPER(TRIM(UR."Name") || SUBSTR(TRIM(UR."First"),1,1) || PR."Producer" || PR."Year") END ASC,

				CASE WHEN NLS_UPPER(TRIM(vOrderBy)) = 'LAST_DESC' THEN NLS_UPPER(TRIM(UR."Name") || SUBSTR(TRIM(UR."First"),1,1) || PR."Producer" || PR."Year") END DESC



			) R2

			WHERE ROWNUM <= vMaxRow



		) R1

		WHERE "RowNum" >= vMinRow;



	END;



  /**

  * Helpter function to count number of unapproved treatments a provider has

  * param: vProducer INPUT: Provider Code in USERS."Producer"

	* param: vMedicaidCode INPUT: List of procedure codes that are defined as a Medicaid code

  * return: number of unapproved treatments

  */

  FUNCTION counttx(vproducer character varying, vmedicaidcode character varying) RETURN integer IS

  vCount INTEGER;

  BEGIN

		IF vProducer IS NOT NULL THEN

			BEGIN

				SELECT COUNT(DISTINCT CL."Auto") INTO vCount

				FROM CHARTLNK CL, PROCEDUR PR, TREATME2 T2

				WHERE PR."Procedure" (+)= CL."Procedure"

				AND T2."Auto" (+)= CL."Auto"

				AND LENGTH(TRIM(CL."Producer")) > 0

				AND CL."Producer" = vProducer

				AND ((CL."Previous" != 0 AND SUBSTR(CL."Status",1,1) NOT IN ('0','A','E'))

					OR (CL."Previous" = 0 AND SUBSTR(CL."Status",1,1) NOT IN ('0','A','E','D')))

				AND PR."CodeType" NOT IN (2,3)

				AND T2."Status" <> 5 -- Ortho visits

				AND (vMedicaidCode is null or (PR."Procedure" NOT IN (select regexp_substr(vMedicaidCode,'[^,]+', 1, level) from dual connect by  regexp_substr(vMedicaidCode,'[^,]+', 1, level) is not null)));

				EXCEPTION WHEN NO_DATA_FOUND THEN vCount := 0;

			END;

		ELSE

			vCount := 0;

		END IF;

    RETURN vCount;

  END;



  /**

  * Helper function to count number of unapproved notes a provider has

  * param: vUser INPUT: User ID

  * return: number of unapproved notes

  */

  FUNCTION countnote(vuser integer) RETURN integer IS

  vCount INTEGER;

  BEGIN

    IF vUser IS NOT NULL THEN

      BEGIN

        EXECUTE IMMEDIATE 'SELECT COUNT(N."Auto")

        FROM NOTES2 N

        WHERE

        (

          N."Type" = 0 OR

          N."Type" = 1 OR

          (N."Type" = 4 AND N."SectionNo" = 0)

        )

        AND N."User" = :1

        AND N."AppUser" = 0

        AND N."Status" IN (0,1)' INTO vCount USING vUser;

        EXCEPTION WHEN NO_DATA_FOUND THEN vCount := 0;

      END;

    ELSE

      vCount := 0;

    END IF;

    RETURN vCount;

  END;



  /**

  * Helper function to count number of unapproved forms a provider has

  * param: vUser INPUT: User ID

  * return: number of unapproved forms

  */

  FUNCTION countform(vuser integer) RETURN integer IS

  vCount INTEGER;

  BEGIN

    IF vUser IS NOT NULL THEN

      BEGIN

        EXECUTE IMMEDIATE 'SELECT COUNT(DISTINCT PF."PForm")

        FROM PITEM PI, PFORM PF

        WHERE PI."PForm" = PF."PForm"

        AND PI."Patient" = PF."Patient"

        AND PI."FormCode" = PF."FormCode"

        AND PI."Status" = 0

        AND PI."User" = :u

        AND PI."AppUser" = 0

        AND PI."ASAType" = 0

        AND PF."Inactive" = 0

        AND PF."OwnerType" != 5

        AND PF."OwnerType" != 6

        AND PF."Approved" = 0' INTO vCount USING vUser;

        EXCEPTION WHEN NO_DATA_FOUND THEN vCount := 0;

      END;

    ELSE

      vCount := 0;

    END IF;

    RETURN vCount;

  END;



  /**

  * Helper function to count number of unapproved findings/conditions a provider has

  * param: vProducer INPUT: Provider Code in USERS."Producer"

	* param: vMedicaidCode INPUT: List of procedure codes that are defined as a Medicaid code

  * return: number of unapproved findings/conditions

  */

  FUNCTION countfind(vproducer character varying, vmedicaidcode character varying) RETURN integer IS

  vCount INTEGER;

  BEGIN

		IF vProducer IS NOT NULL THEN

			BEGIN

				SELECT COUNT(CL."Auto")

				INTO vCount

				FROM CHARTLNK CL, PROCEDUR PR, TREATME2 T2

				WHERE CL."Producer" = vProducer

				AND PR."Procedure" (+)= CL."Procedure"

				AND CL."Previous" = 0

				AND CL."Auto" = T2."Auto"

				AND (CL."Status" = 'A' OR CL."Status" = 'E' OR CL."Status" = 'D')

				AND T2."Status" IN (3, 4)

				AND (vMedicaidCode is null or (PR."Procedure" NOT IN ( select regexp_substr(vMedicaidCode,'[^,]+', 1, level) from dual connect by regexp_substr(vMedicaidCode,'[^,]+', 1, level) is not null)));

				EXCEPTION WHEN NO_DATA_FOUND THEN vCount := 0;

			END;

		ELSE

			vCount := 0;

		END IF;

    RETURN vCount;

  END;



  /**

  * Helpter function to count number of unapproved perio charts a provider has

  * param: vUser INPUT: User ID

  * return: number of unapproved perio charts

  */

  FUNCTION countperio(vuser integer) RETURN integer IS

  vCount INTEGER;

  BEGIN

    IF vUser IS NOT NULL THEN

      BEGIN

        EXECUTE IMMEDIATE 'SELECT COUNT(P."PtPerio")

        FROM PTPERIO P, AUDITHIS AH

        WHERE P."AppUser" = 0

        AND P."Deleted" = 0

        AND P."Audit" = AH."Audit"

        AND AH."TableName" = ''PTPERIO''

        AND AH."User" = :1' INTO vCount USING vUser;

        EXCEPTION WHEN NO_DATA_FOUND THEN vCount := 0;

      END;

    ELSE

      vCount := 0;

    END IF;

    RETURN vCount;

  END;



  /**

  * Helpter function to count number of unapproved letter attachments a provider has

  * param: vUser INPUT: User ID

  * return: number of unapproved letter attachments

  */

  FUNCTION countletter(vuser integer) RETURN integer IS

  vCount INTEGER;

  BEGIN

    IF vUser IS NOT NULL THEN

      BEGIN

        EXECUTE IMMEDIATE 'SELECT COUNT(P."PtLetter")

        FROM PTLDETAILS P

        WHERE P."Type" = 3

        AND P."AppUser" = 0

        AND P."Status" = 1

        AND P."Deleted" = 0

        AND P."User" = :1' INTO vCount USING vUser;

        EXCEPTION WHEN NO_DATA_FOUND THEN vCount := 0;

      END;

    ELSE

      vCount := 0;

    END IF;

    RETURN vCount;

  END;



  /**

  * Helpter function to count number of ortho visits unapproved treatments a provider has

  * param: vProducer INPUT: Provider Code in USERS."Producer"

  * return: number of unapproved ortho visits

  */

  FUNCTION countorthovisits(vproducer character varying) RETURN integer IS

  vCount INTEGER;

  BEGIN

		IF vProducer IS NOT NULL THEN

			BEGIN

				SELECT COUNT(DISTINCT  T2."Auto")

				INTO vCount

				FROM CHARTLNK CL

				LEFT JOIN TREATME2 T2 ON CL."Auto" = T2."Auto"

				WHERE CL."Producer" = vProducer

				AND T2."Status" = 5

				AND ((T2."Deleted" = 0 AND T2."AppUser" = 0) OR (T2."Deleted" = 1 AND T2."DelAppUser" = 0));



				EXCEPTION WHEN NO_DATA_FOUND THEN vCount := 0;

			END;

		ELSE

			vCount := 0;

		END IF;

    RETURN vCount;

  END;





/**

* Procedure used to create log entries in the ILOG table during a session.<p/>

*

* param: vUserName INPUT: Username entered by the user at login.<p/>

* param: vAction INPUT: Action type for the log entry.<br/>

*	<li>0= Failure.<br/>

*	<li>1= Login.<br/>

*	<li>2= Logout.<p/>

* param: viUser INPUT: User ID of the user for this ILOG entry (USERS.User)<p/>

*/

PROCEDURE loglogin(IN vusername character varying, IN vaction integer, IN viuser integer) IS

  SqlStmt  VARCHAR2(5000);

  viLogID NUMBER(10);

BEGIN

SELECT ILOG_ILOG_SEQ.nextval INTO viLogID from dual;

  SqlStmt := 'INSERT INTO ILOG ("iLog","UserName", "Action", "Date", "Time", "Terminal", "iUser")

  VALUES (:1,:2, :3, trunc(sysdate), to_char(sysdate, ''hh24'')*60 + to_char(sysdate, ''mi''),''FacultyAccess'', :4)';

  EXECUTE IMMEDIATE SqlStmt USING viLogID, vUserName, vAction, viUser;

  commit;

END;



/**

* Procedure to open user ticket for Faculty Portal

* param: vUserId INPUT: User ID

* param: vTicketId OUTPUT: Ticket ID of ticket being created

*/

PROCEDURE openticket(IN vuserid numeric, OUT vticketid numeric) IS

  --vTicketId NUMBER(10);

BEGIN

  SELECT FUSERTICKET_FUSERTICKET_SEQ.nextval INTO vTicketId FROM DUAL;



  INSERT INTO FUSERTICKET ("Id", "User", "Date")

  VALUES (vTicketId, vUserId, CURRENT_DATE);



  COMMIT;

END;





/**

* Procedure to close user ticket for Faculty Portal

* param: vTicketId INPUT: Ticket ID

*/

PROCEDURE closeticket(IN vticketid numeric) IS

  BEGIN

  DELETE FROM FUSERTICKET WHERE "Id" = vTicketId;

  --UPDATE FUSERTICKET SET "CloseDate" = CURRENT_DATE, "Status" = 2 WHERE "Id" = vTicketId;

  COMMIT;

END;



/**

* Procedure to get user associated with the ticket for Faculty Portal

* param: vTicketId INPUT: Ticket ID

* param: results_cur OUTPUT: User Row containing:

*  - User, Pin, Password, PINLocked, Logon, Name, Deleted, EffDate, ExpDate, IsInstructor, ApprovePlanTx, ApproveCompTx

*    ApproveExistingTx, ApproveNotes, ApproveEHRForms, ApproveStartChks, ApproveLetters, ApprovePerio, ApproveConditionTx

*/

PROCEDURE getuserfromticket(IN vticketid numeric, OUT results_cur cursor_pkg.weakcursor) IS

  vUserId NUMBER(10);

BEGIN

  SELECT "User" INTO vUserId FROM FUSERTICKET WHERE "Id" = vTicketId AND ROWNUM = 1;

  IF vUserId IS NOT NULL OR vUserId != 0 THEN

  BEGIN

  OPEN results_cur FOR

    SELECT

    "User",

		"PIN",

    "Password",

		"PINLocked",

    "Logon",

		trim("First") || ' ' || trim("Name") as "Name",

		"Deleted",

		NVL("EffDate", trunc(sysdate)-1),

		NVL("ExpDate", trunc(sysdate)+1),

		"IsInstructor",

		"ApprovePlanTx",

		"ApproveCompTx",

		"ApproveExistingTx",

		"ApproveNotes",

		"ApproveEHRForms",

		"ApproveProblems",

		"ApproveStartChks",

		"ApproveLetters",

		"ApprovePerio",

    "ApproveConditionTx"

    FROM USERS WHERE "User" = vUserId AND ROWNUM = 1;

  EXCEPTION WHEN NO_DATA_FOUND THEN

    results_cur := NULL;

  END;

  ELSE

  results_cur := NULL;

  END IF;

END;





/**

* Procedure to check user ticket for Faculty Portal

* param: vTicketId INPUT: Ticket ID

* param: vResult OUTPUT: result of check (0=Ticket Closed, 1= Ticket Open)

*/

PROCEDURE checkticket(IN vticketid numeric, OUT vresult integer) IS

  vValid INTEGER := 0;

BEGIN

  SELECT COUNT(*) INTO vValid FROM FUSERTICKET WHERE "Id" = vTicketId AND "Date" = TRUNC(SYSDATE);

  vResult := vValid;

END;



/**

* Function that checks whether or not an appointment has previously been start checked today.<p/>

*

* param: vAppointment INPUT: Appointment ID of the appointment to check (APPOINT.Appointment).<p/>

* return: Value indicating whether or not the appointment has been start checked today (0=no start check, 1+=User ID of the last person to start check it).<p/>

*/

FUNCTION hasprevstartcheck(vappointment integer) RETURN integer IS

	vUser INTEGER;

BEGIN

	BEGIN

		SELECT USERID

		INTO vUser

		FROM

		(

			SELECT

				SC."StartChk",

				US."User" USERID

			FROM STARTCHK SC, USERS US, AUDITHIS AH

			WHERE 1=1

				AND SC."Appointment" = vAppointment

				AND SC."AppUser"=US."User"

				AND AH."Audit" = SC."Audit"

				AND AH."Date" = TRUNC(SYSDATE)

			ORDER BY SC."StartChk" DESC

		)

		WHERE ROWNUM < 2;



	EXCEPTION WHEN NO_DATA_FOUND THEN

		vUser := 0;

	END;



	RETURN vUser;

END;





/**

* Function that checks whether or not a patient requires consent for treatment.<p/>

*

* param: vPatient INPUT: Patient ID of the appointment patient (PATIENT.Patient).<p/>

* return: Flag indicating whether or not the patient requires consent (0=no, 1=yes).<p/>

*/

FUNCTION ptrequiresconsent(vpatientid integer) RETURN integer IS

	vPatientNeedsConsent INTEGER;

BEGIN

	BEGIN

		-- check if the patient needs consents

		SELECT PT."RequireTxConsent"

		INTO vPatientNeedsConsent

		FROM PATIENT PT

		WHERE 1=1

			AND PT."Patient" = vPatientId;



	EXCEPTION WHEN NO_DATA_FOUND THEN

		vPatientNeedsConsent := 0; -- didn't find the patient

	END;



	RETURN vPatientNeedsConsent;

END;



/**

* Function that checks whether or not a provider requires consent to perform treatment.<p/>

*

* param: vProducer INPUT: Provider ID of the the provider (USERS.Producer).<p/>

* return: Flag indicating whether or not the provider requires consent (0=no, 1=yes).<p/>

*/

FUNCTION prodrequiresconsent(vproducer character) RETURN integer IS

	vProdNeedsConsent INTEGER;

BEGIN

	BEGIN

		-- check if the provider needs consents

		SELECT PR."RequireTxConsent"

		INTO vProdNeedsConsent

		FROM PRODUCER PR

		WHERE 1=1

			AND PR."Producer" = vProducer;



	EXCEPTION WHEN NO_DATA_FOUND THEN

		vProdNeedsConsent := 0; -- didn't find the patient

	END;



	RETURN vProdNeedsConsent;

END;



/**

* Function that checks whether or not a procedure code requires patient consent.<p/>

*

* param: vProcCode INPUT: Procedure code of the procedure (PROCEDUR.Procedure). <p/>

* return: Flag indicating whether or not the procedure requires consent (0=no, 1=yes).<p/>

*/

FUNCTION procrequiresconsent(vproccode character) RETURN integer IS

	vProcNeedsConsent INTEGER;

BEGIN

	BEGIN

		-- check if the procedure needs consents

		SELECT PR."RequireTxConsent"

		INTO vProcNeedsConsent

		FROM PROCEDUR PR

		WHERE 1=1

			AND PR."Procedure" = vProcCode;



	EXCEPTION WHEN NO_DATA_FOUND THEN

		vProcNeedsConsent := 0; -- didn't find the patient

	END;



	RETURN vProcNeedsConsent;

END;



/**

* Function that checks whether or not the treatments on an appointment require consent, and if so, whether or not they have all been

*  consented to by the patient.<p/>

*

* param: vAppointment INPUT: Appointment ID of the appointment to check (APPOINT.Appointment).<p/>

* return: Flag indicating whether or not the appointment has been fully consented to (0=needs consent and one or more consents missing, 1=need consent, and has all consents, 2=no consent is needed).<p/>

*/

FUNCTION appthasptconsent(vappointment integer) RETURN integer IS

  -- local variables for internal operation

  vProducer  CHAR(10); -- Producer code of the primary appointment provider

  vPatient NUMBER(10); -- Patient ID of the appointment

  vStartChkTxConsent INTEGER; -- Clinic setting for Start Check options (0-Appt, 1-Tx, 2-Both)

  vProviderNeedConsent INTEGER := 0; -- Result of check if provider needs a consent

  vPatientNeedConsent INTEGER := 0; -- Result of check if appointment patient needs a consent

  vProcedureNeedConsent INTEGER := 0; -- Result of check if procedure requires a consent

  vTxNeedConsent INTEGER; -- Result of check if appointment treatments have consents

  vTxHasConsent  VARCHAR2(4000);

  vNeedConsent INTEGER := 0;

  vTempOutput  VARCHAR2(4000); -- Temporary output



  -- cursors for all treatments belonging to the appointment

  CURSOR curApptTx IS

    SELECT

      TR."Producer",

      TR."Procedure",

      TR."OrigRecNo",

      TR."Site",

      TR."Type",

      TR."Id",

      TR."Treatment",

      TR."Status"

    FROM APPTRX APT, TRX TR

    WHERE APT."Appointment" = vAppointment

    AND TR."Type" = APT."Type"

    AND TR."Id" = APT."Id"

    AND TR."Treatment" = APT."Treatment"

    AND TR."Deleted" = 0;

BEGIN

  -- Get the appointment information using the ID provided

  -- Following data is retrieved:

  -- + APPOINT.Producer

  -- + APPOINT.Patient

  -- + CLINIC.StartChkTxConsent - to validate primary/assigned provider for the operation

  SELECT

    AP."Producer",

    AP."Patient",

    NVL(CL."StartChkTxConsent", 0)

  INTO

    vProducer,

    vPatient,

    vStartChkTxConsent

  FROM APPOINT AP

  LEFT JOIN CLINIC CL ON AP."Clinic" = CL."Clinic"

  WHERE AP."Appointment" = vAppointment;



  -- Get clinic's flag "Start Check's Missing Consent Checks Based On" (0-Appt, 1-Tx, 2-Both)

  -- Check for appointment provider if clinic is set to check for appointment provider or both

  IF vStartChkTxConsent = 0 OR vStartChkTxConsent = 2 THEN

    vProviderNeedConsent := FPORTAL_PKG.ProdRequiresConsent(vProducer);

  END IF;



  -- Check for treatment provider if:

  -- 1. Consent is not needed AND

  -- 2. Clinic is set to check for treatment provider of both

  IF vProviderNeedConsent = 0 AND (vStartChkTxConsent = 1 OR vStartChkTxConsent = 2) THEN



    -- Looping through all treatment assigned to the appointment

    -- Check for if treatment provider requires a patient consent

    -- If the provider needs a consent, terminate farther checks

    FOR txItem IN curApptTx LOOP

      vProviderNeedConsent := FPORTAL_PKG.ProdRequiresConsent(txItem."Producer");

      IF vProviderNeedConsent = 1 THEN

        EXIT;

      END IF;

    END LOOP;

  END IF;



  -- Terminate current process if appointment/treatment provider

  -- does not need a patient consent

  IF vProviderNeedConsent = 0 THEN

    RETURN 2; -- The provider doesn't need a consent

  END IF;



  -- Check if patient needs a consent

  vPatientNeedConsent := FPORTAL_PKG.PtRequiresConsent(vPatient);

  IF vPatientNeedConsent = 0 THEN

    RETURN 1; -- Others don't need a consent (patient)

  END IF;



  -- Check if treatment needs a consent

  -- If the treatment needs a consent, it needs to check if it has a consent

  -- provider needs consent, so need to check each appointment treatment

  FOR txItem IN curApptTx LOOP

    vProcedureNeedConsent :=  FPORTAL_PKG.ProcRequiresConsent(txItem."Procedure");

    vTxNeedConsent := CONSENT_PKG.TRX_NEEDS_TX_CONSENT(txItem."Type", txItem."Id", txItem."Treatment", 0);

    vTxHasConsent := CONSENT_PKG.TRX_HAS_CONSENT(txItem."OrigRecNo", txItem."Procedure", txItem."Site", vPatient, SUBSTR(txItem."Producer",1,1));



    IF (vProcedureNeedConsent = 1 OR vTxNeedConsent = 1) AND vTxHasConsent IS NOT NULL THEN

      vNeedConsent := 1;

    END IF;

  END LOOP;



	IF vNeedConsent = 0 THEN

		RETURN 1; -- no consents are needed (1)

	ELSE

		RETURN 0; -- we are missing consents (0)

	END IF;

END;



/**

* Function that checks whether or not the treatments on an appointment are in phase order or out of phase order.

*

* param: vAppointment INPUT: Appointment ID of the appointment to check (APPOINT.Appointment).<p/>

* return: Flag indicating what the phase order of the appointment treatments is (0=needs phase order, out of phase order, 1=needs phase order, in phase order, 2=phase check not req'd).<p/>

*/

FUNCTION hascorrectphaseorder(vappointment integer) RETURN integer IS

	vProdPhaseCheck INTEGER;

	vLowPhase INTEGER;



	-- cursor containing information about the appointment treatments

	CURSOR curApptTxCur IS

		SELECT TO_NUMBER(TRIM(TR."Phase")) "Phase"

		FROM APPTRX APT, TRX TR

		WHERE 1=1

			AND APT."Appointment" = vAppointment

			AND APT."Type" = TR."Type"

			AND APT."Id" = TR."Id"

			AND APT."Treatment" = TR."Treatment"

			AND TR."Deleted" = 0;



BEGIN

	-- check if producer should be checked for phase order

	SELECT PR."PhaseCheck"

	INTO vProdPhaseCheck

	FROM APPOINT AP, PRODUCER PR

	WHERE 1=1

		AND AP."Appointment" = vAppointment

		AND AP."Producer" = PR."Producer";



	IF vProdPhaseCheck = 0 THEN

		RETURN 2; -- no phase check needed

	ELSE

		-- get the lowest phase number of the planned treatments that are NOT in this appointment

		-- ignore those that have a non-numeric or missing phase

		SELECT MIN(TO_NUMBER(NVL(TRIM(TR."Phase"),0)))

		INTO vLowPhase

		FROM TRX TR, APPOINT AP

		WHERE 1=1

			AND TR."Type" = 5

			AND TR."Deleted" = 0

			AND (TRIM(TR."Type") || ',' || TRIM(TR."Id") || ',' || TRIM(TR."Treatment")) NOT IN

				(SELECT (TRIM(APT."Type") || ',' || TRIM(APT."Id") || ',' || TRIM(APT."Treatment"))

				FROM APPTRX APT

				WHERE APT."Appointment" = vAppointment)

			AND AP."Appointment" = vAppointment

			AND TR."Patient" = AP."Patient"

                        AND LENGTH(TRIM(TRANSLATE(TR."Phase", ' +-.0123456789', ' '))) IS NULL

                        AND NOT (TRIM(TR."Phase") IS NULL OR LENGTH(TRIM(TR."Phase")) = 0);



		IF vLowPhase IS NULL THEN

			RETURN 1;-- either all the planned tx are in this appt or the ones not in the appt don't have a phase defined.

		ELSE

			-- check each treatment in the appointment

			FOR cApptTrx IN curApptTxCur LOOP

				IF cApptTrx."Phase" > vLowPhase THEN

					RETURN 0; -- found an out-of-phase treatment in this appointment

				END IF;

	 		END LOOP;

	 		RETURN 1; -- all treatments in the appointment are in phase with other planned tx for the patient.

		END IF;

	END IF;

END;



/**

* Procedure to retrieve the text that should be displayed to all users when performing start checks. Note: this

*  text is defined in axiUm in Maint -> Basic tab -> Custom Text.<p/>

*

* param: vStartCheckText OUTPUT: String containing the text to be displayed.<p/>

*/

PROCEDURE getstartchecktext(OUT vstartchecktext character varying) IS

BEGIN

	BEGIN

		SELECT TRIM("Text")

		INTO vStartCheckText FROM CustText WHERE "Type" = 0;



	EXCEPTION WHEN NO_DATA_FOUND THEN

		vStartCheckText := '';

	END;

END;



/**

* Function that checks whether or not the appointment is within the correct window for start checks (window starts 30 mins before appointment, ends when appointment ends).<p/>

*

* param: vAppointment INPUT: Appointment ID of the appointment to check (APPOINT.Appointment).<p/>

* param: vStartCheckMinutes For window starts, instead of fixed 30 minutes.<p/>

* param: vEarlyTimeToStartCheck OUTPUT: Early time the user can Start Check.<p/>

* return: Flag indicating if the appointment lies within the start check window (-1=too early, 0=within window, 1=too late).<p/>

*/

FUNCTION withinstartchkwindow(vappointment integer, vstartcheckminutes integer, OUT vearlytimetostartcheck integer) RETURN integer IS

	vMinutes APPOINT."From"%TYPE;

	vTooSoon APPOINT."From"%TYPE;

	vTooLate APPOINT."From"%TYPE;

BEGIN

	-- calculate time window

	SELECT ((TO_NUMBER(TO_CHAR(SYSDATE,'HH24')) * 60) + TO_NUMBER(TO_CHAR(SYSDATE,'MI')))

	INTO vMinutes FROM DUAL;



	SELECT "From"-vStartCheckMinutes, "From"+"Time0"+"Time1"+"Time2"+"Time3"+"Time4"+"Time5"

	INTO vTooSoon, vTooLate FROM APPOINT WHERE "Appointment" = vAppointment; /* AX-2489 Instead of 30 minutes use vStartCheckMinutes */



	vEarlyTimeToStartCheck := vTooSoon;



	-- do check

	IF vMinutes < vTooSoon THEN

		RETURN -1; -- too soon

	ELSIF vMinutes > vTooLate THEN

		RETURN 1; -- too late

	ELSE

		RETURN 0; -- within window

	END IF;

END;





/**

* Function that checks whether or not the logged-in user has system access at the current date/time as defined via PowerAdmin -> Users -> Access Times.<p/>

*

* param: vUser INPUT: User ID of the logged-in user (USERS.User).<p/>

* return: Flag indicating if the user has system access at this time (0=no access, 1=has access).<p/>

*/

FUNCTION userhasaccess(vuser integer) RETURN integer IS

	vDayOfWeek INTEGER;

	vDayAccess INTEGER;

	vHasAccess INTEGER;

BEGIN

	BEGIN

		SELECT TO_CHAR(SYSDATE,'D') INTO vDayOfWeek FROM DUAL;



		SELECT CASE

			WHEN vDayOfWeek = 1 THEN "Sunday"

			WHEN vDayOfWeek = 2 THEN "Monday"

			WHEN vDayOfWeek = 3 THEN "Tuesday"

			WHEN vDayOfWeek = 4 THEN "Wednesday"

			WHEN vDayOfWeek = 5 THEN "Thursday"

			WHEN vDayOfWeek = 6 THEN "Friday"

			WHEN vDayOfWeek = 7 THEN "Saturday"

			END

		INTO vDayAccess

		FROM UACCESS WHERE "User" = vUser;



		SELECT SUBSTR(TRIM(vDayAccess),(TO_CHAR(SYSDATE,'HH24')),1)

		INTO vHasAccess FROM DUAL;



		RETURN vHasAccess; -- return access right for this date/time



	EXCEPTION WHEN NO_DATA_FOUND THEN

		RETURN 1; -- no access restriction defined

	END;

END;



/**

* Function that checks whether or not the logged-in user has the right to approve start checks.<p/>

*

* param: vInstructor INPUT: User ID of the logged-in user (USERS.User).<p/>

* return: Flag indicating if the user is able to approve start checks (0=can't approve, 1=can approve).<p/>

*/

FUNCTION instructorcanappstartchks(vinstructor integer) RETURN integer IS

	vCanApprove INTEGER;

BEGIN

	BEGIN

		SELECT "ApproveStartChks" INTO vCanApprove FROM USERS where "User" = vInstructor;

		RETURN vCanApprove;



	EXCEPTION WHEN NO_DATA_FOUND THEN

		RETURN 0; -- didn't find the user

	END;

END;





/**

* Function that checks whether or not the logged-in user has the right to approve start checks without consent.<p/>

*

* param: vInstructor INPUT: User ID of the logged-in user (USERS.User).<p/>

* return: Flag indicating if the user is able to approve start checks without consent(0=can't approve, 1=can approve).<p/>

*/

FUNCTION startchkswithoutconsent(vinstructor integer) RETURN integer IS



	vCanApproveStartWithOutConsent INTEGER;

BEGIN

	BEGIN

		SELECT "ApproveNoTxConsent" INTO vCanApproveStartWithOutConsent FROM USERS where "User" = vInstructor;

		RETURN vCanApproveStartWithOutConsent;



	EXCEPTION WHEN NO_DATA_FOUND THEN

		RETURN 0; -- didn't find the user

	END;

END;





/**

* Function to check if given criteria requires grading

*/

FUNCTION requiregrading(vprovrequiregrading integer, vprocrequiregrading integer, vdiscipline character varying) RETURN integer IS

  vReturnValue INTEGER;

  vCount INTEGER := 0;

BEGIN

  IF vProcRequireGrading = 1 AND vProvRequireGrading > 0 THEN

    IF (TRIM(vDiscipline) IS NULL OR LENGTH(TRIM(vDiscipline)) = 0) THEN

      vReturnValue := 1;

    ELSE

      BEGIN

        SELECT COUNT(1) INTO vCount

        FROM DISCIPL D WHERE D."Class" = vDiscipline;

        IF vCount = 0 THEN

          vReturnValue := 1;

        ELSE

          IF vProvRequireGrading = 2 THEN

            BEGIN

              SELECT COUNT(1) INTO vCount

              FROM DISCIPL D

              WHERE D."Class" = vDiscipline

              AND D."GradingType" = 1;

              IF vCount = 0 THEN

                vReturnValue := 0;

              ELSE

                vReturnValue := 1;

              END IF;

            END;

          ELSIF vProcRequireGrading = 1 THEN

            BEGIN

              SELECT COUNT(1) INTO vCount

              FROM DISCIPL D

              WHERE D."Class" = vDiscipline

              AND D."GradingType" IN (0,1);

              IF vCount = 0 THEN

                vReturnValue := 0;

              ELSE

                vReturnValue := 1;

              END IF;

            END;

          ELSE

            vReturnValue := 0;

          END IF;

        END IF;

      END;

    END IF;

  ELSE

    vReturnValue := 0;

  END IF;

  /*

  IF vProvRequireGrading = 0 OR vProcRequireGrading = 0 THEN

    vReturnValue := 0;

  ELSIF (TRIM(vDiscipline) IS NULL OR LENGTH(TRIM(vDiscipline)) = 0) THEN

    vReturnValue := 1;

  ELSIF vProvRequireGrading = 2 THEN

    BEGIN

      SELECT COUNT(1) INTO vCount

      FROM DISCIPL D

      WHERE D."Class" = vDiscipline

      AND D."GradingType" = 1;

      IF vCount = 0 THEN

        vReturnValue := 0;

      ELSE

        vReturnValue := 1;

      END IF;

    END;

  ELSIF vProvRequireGrading = 1 THEN

    BEGIN

      SELECT COUNT(1) INTO vCount

      FROM DISCIPL D

      WHERE D."Class" = vDiscipline

      AND D."GradingType" IN (0,1);

      IF vCount = 0 THEN

        vReturnValue := 0;

      ELSE

        vReturnValue := 1;

      END IF;

    END;

  ELSE

    BEGIN

      SELECT COUNT(1) INTO vCount

      FROM DISCIPL D

      WHERE D."Class" = vDiscipline;

      IF vCount = 0 THEN

        vReturnValue := 1;

      ELSE

        vReturnValue := 0;

      END IF;

    END;

  END IF;

  */



  RETURN vReturnValue;

END;



/**

* Function that checks whether or not a particular treatment has been start checked today.<p/>

*

* param: vType INPUT: Type of the treatment being checked (APPTRX.Type).<p/>

* param: vId INPUT: ID of the treatment being checked (APPTRX.Id).<p/>

* param: vTreatment INPUT: Treatment # of the treatment being checked (APPTRX.Treatment).<p/>

* return: Value indicating whether or not the appointment has been start checked today (0=no start check, 1+=User ID of the last person to start check it).<p/>

*/

FUNCTION hasprevstartchecktx(vappointment integer, vtype integer, vid integer, vtreatment integer, vprocedure character varying) RETURN integer IS

	vAppUser INTEGER;

BEGIN

	BEGIN

		SELECT "AppUser"

		INTO vAppUser

      FROM

      (

        SELECT

          SC."StartChk",

          "AppUser"

          FROM STARTCHK SC, STARTTRX ST, AUDITHIS AH

          WHERE 1=1

            AND AH."Audit" = SC."Audit"

            AND SC."StartChk" = ST."StartChk"

            AND TRUNC(AH."Date") = TRUNC(SYSDATE)

            AND SC."Appointment" = vAppointment

            AND ST."Type" = vType

            AND ST."Id" = vId

            AND ST."Treatment" = vTreatment

            AND TRIM(ST."Procedure") = TRIM(vProcedure)

            ORDER BY SC."StartChk" DESC

      )

      WHERE ROWNUM = 1;



  	EXCEPTION WHEN NO_DATA_FOUND THEN

  		vAppUser := 0;

  	END;



  	RETURN vAppUser;

END;





/**

* Function that checks whether or not the logged-in user has restricted access to perform approvals for a particular provider or provider group.<p/>

*

* param: vInstructor INPUT: User ID of the logged-in user (USERS.User).<p/>

* param: vProducer INPUT: Provider ID of the provider to check for (PRODUCER.Producer).<p/>

* param: vPGroup INPUT: Provider group code to check for (PGROUP.PGroup).<p/>

* return: Flag indicating if the user has restricted access for the provider or group (0=no restriction,1=restricted access).<p/>

*/

FUNCTION isinstrestrictprov(vinstructor integer, vproducer character, vpgroup character) RETURN integer IS

	vRestrictedApproval INTEGER;

  vWhiteListCount INTEGER;

	vMatchCount INTEGER;

	vProdType  CHAR(1);

	vIsRestricted INTEGER;

BEGIN

	BEGIN

	-- check if user has restricted approvals enabled.

	SELECT "RestrictedApproval"

	INTO vRestrictedApproval

	FROM USERS

	WHERE 1=1

		AND "User" = vInstructor;



	IF vRestrictedApproval = 0 THEN

		vIsRestricted := 0; -- restricted approvals disabled

	ELSE

    -- check if user has whitelist filled

    SELECT COUNT(1)

    INTO vWhiteListCount

    FROM UAPPROVE

    WHERE 1=1

    AND "Type" = 1

    AND "User" = vInstructor;



    IF vWhiteListCount = 0 THEN

      vIsRestricted := 0;

    ELSE

      -- Check if Producer provided is non-provider

      IF vProducer IS NULL THEN

        SELECT COUNT(1)

        INTO vMatchCount

        FROM UAPPROVE UA

        WHERE 1 =1

          AND "Type" = 1

          AND "User" = vInstructor

          AND ((TRIM("ProdType") IS NULL OR LENGTH(TRIM("ProdType")) = 0) OR "ProdType" = '*');

      ELSE

        -- get the provider's type

        SELECT "TypeCode"

        INTO vProdType

        FROM PRODUCER

        WHERE 1=1

          AND TRIM("Producer") = TRIM(vProducer);



        -- check if this combination is allowed

        SELECT COUNT(1)

        INTO vMatchCount

        FROM UAPPROVE UA

        WHERE 1=1

          AND "Type" = 1

          AND "User" = vInstructor

          AND ("ProdType" = vProdType OR "ProdType" = '*')

          AND (TRIM("PGroup") = TRIM(vPGroup) OR "PGroup" = '*');

      END IF;



      IF vMatchCount = 0 THEN

        vIsRestricted := 1;

      ELSE

        vIsRestricted := 0;

      END IF;

    END IF;

	END IF;



	EXCEPTION WHEN NO_DATA_FOUND THEN

		vIsRestricted := 0;

	END;



	RETURN vIsRestricted;

END;





/**

* Procedure that checks whether or not the logged-in user has restricted access to perform approvals for the provider on a particular appointment.<p/>

*

* param: vInstructor INPUT: User ID of the logged-in user (USERS.User).<p/>

* param: vAppointment INPUT: Appointment ID of the appointment to check (APPOINT.Appointment).<p/>

* param: vIsRestricted OUTPUT: Flag indicating if the user has restricted access for the appointment provider or their group (0=no restriction,1=restricted access).<p/>

* param: vApptProvType OUTPUT: 1-character provider type code of the appointment provider.<p/>

* param: vApptProvGroup OUTPUT: Provider group of the appointment provider.<p/>

*/

PROCEDURE apptinstrestrictprov(IN vinstructor integer, IN vappointment integer, OUT visrestricted integer, OUT vapptprovtype character varying, OUT vapptprovgroup character varying) IS

  vProducer  VARCHAR2(50);

BEGIN

	BEGIN

		-- get appt provider type and provider group

		SELECT

			AP."Producer",

      PR."TypeCode",

			PR."PGroup"

		INTO vProducer, vApptProvType, vApptProvGroup

		FROM APPOINT AP, PRODUCER PR

		WHERE 1=1

			AND AP."Producer" = PR."Producer"

			AND AP."Appointment" = vAppointment;



		-- check if this combination is allowed

		vIsRestricted := FPORTAL_PKG.IsInstRestrictProv(vInstructor, vProducer, vApptProvGroup);



	EXCEPTION WHEN NO_DATA_FOUND THEN

		vIsRestricted := 0;

	END;

END;



/**

* Function that checks whether or not the logged-in user has the right to approve start checks.<p/>

*

* param: vInstructor INPUT: User ID of the logged-in user (USERS.User).<p/>

* param: vDiscipline INPUT: Discipline code to check. (DISCIPL.Discipline).<p/>

* return: Flag indicating if the logged-in user has restricted approvals for that discipline (0=no restriction, 1=restricted access).<p/>

*/

FUNCTION isinstrestrictdisc(vinstructor integer, vdiscipline character) RETURN integer IS

	vRestrictedApproval INTEGER;

  vWhiteListCount INTEGER;

	vMatchCount INTEGER;

	vIsRestricted INTEGER;

BEGIN

	BEGIN

		-- check if user has restricted approvals enabled.

		SELECT "RestrictedApproval"

		INTO vRestrictedApproval

		FROM USERS

		WHERE 1=1

			AND "User" = vInstructor;



		IF vRestrictedApproval = 0 THEN

			vIsRestricted := 0; -- restricted approvals disabled

		ELSE

      -- check if user has whitelist filled

      SELECT COUNT(1)

      INTO vWhiteListCount

      FROM UAPPROVE

      WHERE 1=1

        AND "Type" = 0

        AND "User" = vInstructor;



      IF vWhiteListCount = 0 THEN

        vIsRestricted := 0;

      ELSE

        -- check if this discipline can be approved by this user

        SELECT COUNT(1)

        INTO vMatchCount

        FROM UAPPROVE

        WHERE 1=1

          AND "Type" = 0

          AND "User" = vInstructor

          AND TRIM("Discipline") = TRIM(vDiscipline);



        IF vMatchCount = 0 THEN

          vIsRestricted := 1;

        ELSE

          vIsRestricted := 0;

        END IF;

      END IF;

		END IF;



	EXCEPTION WHEN NO_DATA_FOUND THEN

		vIsRestricted := 0;

	END;



	RETURN vIsRestricted;

END;



/**

* Procedure that checked whether or not the logged-in user has restricted access to perform approvals for the treatment disciplines of the treatments on a particular appointment.<p/>

*

* param: vInstructor INPUT: User ID of the logged-in user (USERS.User).<p/>

* param: vAppointment INPUT: Appointment ID of the appointment to check (APPOINT.Appointment).<p/>

* param: vIsRestricted OUTPUT: Flag indicating if the user has restricted access one or more of the disciplines of an appointment treatment (0=no restriction,1=restricted access).<p/>

* param: vLastBlockedDisp OUTPUT: Discipline code of the first restricted discipline that this procedure encountered, if any.<p/>

*/

PROCEDURE apptinstrestrictdisc(IN vinstructor integer, IN vappointment integer, OUT visrestricted integer, OUT vlastblockeddisp character varying) IS

	-- cursor containing disciplines for all appointment tx

	CURSOR curApptTxCur IS

		SELECT TR."Discipline"

		FROM APPTRX APT, TRX TR

		WHERE 1=1

			AND APT."Appointment" = vAppointment

			AND APT."Type" = TR."Type"

			AND APT."Id" = TR."Id"

			AND APT."Treatment" = TR."Treatment"

			AND TR."Deleted" = 0;



	vFoundRestrict INTEGER;

BEGIN

	vIsRestricted := 0;



	-- check each appt tx against each allowed disciplines

	FOR cDisc IN curApptTxCur LOOP



    IF NOT (TRIM(cDisc."Discipline") IS NULL OR LENGTH(TRIM(cDisc."Discipline")) = 0) THEN

      vFoundRestrict := FPORTAL_PKG.IsInstRestrictDisc( vInstructor, cDisc."Discipline");



      IF vFoundRestrict = 1 THEN

        vIsRestricted := 1;

        vLastBlockedDisp := TRIM(cDisc."Discipline");

      END IF;

    END IF;



		EXIT WHEN vIsRestricted = 1;

	END LOOP;

END;





/**

* Procedure that checked whether or not Status has MakeInactive Status.<p/>

*

* param: vTxStatus INPUT: TxStatus (TRX.RxStatus).<p/>

* param: vMakeInactiveStatus OUTPUT: Flag indicating if the Status of MakeInactive<p/>

*/

FUNCTION makeinactivestatus(vtxstatus character) RETURN integer IS

	vMakeInactiveStatus INTEGER;

BEGIN

	BEGIN

		                                        

		SELECT ST."MakeInactive"

		INTO vMakeInactiveStatus

		FROM STATUS ST

		WHERE 1=1

			AND ST."Type" = 3

			AND ST."Status" = vTxStatus;



	EXCEPTION WHEN NO_DATA_FOUND THEN

		vMakeInactiveStatus := 0;                           

	END;



	RETURN vMakeInactiveStatus;

END;

				   

/**

* Procedure that checked whether or not a trx has Inactive status.<p/>

*

* param: vAppointment INPUT: Appointment ID of the appointment to check (APPOINT.Appointment).<p/>

* param: vMakeInactiveStatus OUTPUT: Flag indicating if the Trx has MakeInactive<p/>

*/

FUNCTION makeinactivetrx(vappointment integer) RETURN integer IS



  vMakeInactiveStatus INTEGER := 0;            



  CURSOR curApptTx IS

    SELECT

      TR."Id",

      TR."TxStatus"

    FROM APPTRX APT, TRX TR

    WHERE APT."Appointment" = vAppointment

    AND TR."Type" = APT."Type"

    AND TR."Id" = APT."Id"

    AND TR."Treatment" = APT."Treatment"

    AND TR."Deleted" = 0;

BEGIN



  FOR txItem IN curApptTx LOOP

    vMakeInactiveStatus :=  FPORTAL_PKG.MakeInactiveStatus(txItem."TxStatus");



    IF vMakeInactiveStatus = 1 THEN

      EXIT;

    END IF;

  END LOOP;



  RETURN vMakeInactiveStatus;



END;





/**

* Procedure to retrieve all warning and error conditions present that may prevent the logged-in user from performing a start check

*  on a particular appointment. Returns these as a set of flags which are checked by the application to determine if a start check

*  should proceed.<p/>

*

* param: vInstructor INPUT: User ID of the logged-in user (USERS.User).<p/>

* param: vAppointment INPUT: Appointment ID of the appointment to check (APPOINT.Appointment).<p/>

* param: vStartCheckMinutes INPUT: Value for Start Check time before the scheduled appointment begins (original was 30 min). <p/>

* param: vTiming OUTPUT: Flag indicating if its' too early or too late to do the start check (-1= too early, 0=within window, 1=too late).<p/>

* param: vCanApprove OUTPUT: Flag indicating if the user has the ability to approve start checks (0= cannot approve, 1= can approve).<p/>

* param: vCanApproveStartWithOutConsent OUTPUT: Flag indicating if the user has the ability to approve start checks w/out consent (0= cannot approve, 1= can approve).<p/>

* param: vHasAccess OUTPUT: Flag indicating if the user has system access at this time, as setup in Power Admin -> Users -> Access Times (0=no access, 1=has access).<p/>

* param: vAlreadyStartChecked OUTPUT: Flag indicating if this appointment has already been start checked (0=not start checked, 1+= User ID of last user to start check the appt).<p/>

* param: vHasConsent OUTPUT: Flag indicating if the appointment contains treatments that the provider needs consent for and whether or not consent has been given (0=needs consent, and consent is missing, 1=needs consent, and has all consents, 2=doesn't require consent).<p/>

* param: vPhaseOrder OUTPUT: Flag indicating if the appointment treatments are in or out of phase order, and whether or not the provider requires a phase order check (0=check req'd and out of phase, 1=check req'd and in phase, 2=check not req'd).<p/>

* param: vIsRestrictedProv OUTPUT: Flag indicating if the appointment's provider is a restricted provider for the logged in user, as setup in Restricted Approvals (0=not restricted, 1=restricted).<p/>

* param: vRestProvType OUTPUT: If the user is restricted for the provider, returns the provider's 1-character provider type.<p/>

* param: vRestProvGroup OUTPUT: If the user is restricted for the provider, returns the provider's provider group code.<p/>

* param: vIsRestrictedDisc OUTPUT: Flag indicating if the appointment treatments have disciplines that the logged in user is restricted from approving, as setup in Restricted Approvals (0=not restricted, 1=restricted).<p/>

* param: vLastBlockedDisc OUTPUT: If the user is restricted on a discipline, returns the first discipline code found that was restricted.<p/>

* param: vEarlyTimeToStartCheck OUTPUT: Early time the user can Start Check.<p/>

* param: vMakeInactive OUTPUT: Inactive Status.<p/>

*/

PROCEDURE prestartchk(IN vinstructor integer, IN vappointment integer, IN vstartcheckminutes integer, OUT vtiming integer, OUT vcanapprove integer, OUT vcanapprovestartwithoutconsent integer, OUT vhasaccess integer, OUT valreadystartchecked integer, OUT vhasconsent integer, OUT vphaseorder integer, OUT visrestrictedprov integer, OUT vrestprovtype character varying, OUT vrestprovgroup character varying, OUT visrestricteddisc integer, OUT vlastblockeddisc character varying, OUT vearlytimetostartcheck integer, OUT vmakeinactive integer) IS

BEGIN

	-- ERRORS - user cannot continue past these



	-- check if it's too early or too late to do a start check

	vTiming := FPORTAL_PKG.WithinStartChkWindow(vAppointment, vStartCheckMinutes, vEarlyTimeToStartCheck);



	-- check if the instructor has system access at this time

	vHasAccess := FPORTAL_PKG.UserHasAccess(vInstructor);



	-- check if the instructor has authorization to start check appointments

	vCanApprove := FPORTAL_PKG.InstructorCanAppStartChks(vInstructor);



	-- check if the instructor has authorization to start check appointments without consent

	vCanApproveStartWithOutConsent := FPORTAL_PKG.StartChksWithOutConsent(vInstructor);



	-- check if the instructor has any restricted approvals that would prevent approval

	ApptInstRestrictProv( vInstructor, vAppointment,vIsRestrictedProv, vRestProvType, vRestProvGroup);

	ApptInstRestrictDisc( vInstructor, vAppointment,vIsRestrictedDisc, vLastBlockedDisc );



	-- check if the provider has consent, if required - warning in axiUm but needs to be an error in Faculty Portal

	vHasConsent := FPORTAL_PKG.ApptHasPtConsent(vAppointment);



	-- check that the appointment tx in phase order, if required - warning in axiUm but needs to be an error in Faculty Portal

	vPhaseOrder := FPORTAL_PKG.HasCorrectPhaseOrder(vAppointment);



	-- Check if trx has MakeInactive Status

	vMakeInactive := FPORTAL_PKG.MakeInactiveTrx(vAppointment);



	-- WARNINGS - user can continue past these



	-- check if the appointment has already been start checked

	vAlreadyStartChecked := FPORTAL_PKG.HasPrevStartCheck(vAppointment);

END;





/**

* Procedure to perform a start check. This procedure assumes that the user's ability to perform a start check has already been validated (via PreStartChk) and

*  that it should be start checked by the logged-in user.<p/>

*

* param: vInstructor INPUT: User ID of the logged-in user (USERS.User).<p/>

* param: vAppointment INPUT: Appointment ID of the appointment to start check (APPOINT.Appointment).<p/>

* param: vProviderUser INPUT: User ID of the appointment provider (USERS.User).<p/>

* param: vPatient INPUT: Patient ID of the appointment patient (PATIENT.Patient).<p/>

* param: vResult OUTPUT: Flag to indicate if the appointment was successfully start checked (0=yes,-1=error encountered).<p/>

*/

PROCEDURE dostartchk(IN vinstructor integer, IN vappointment integer, IN vprovideruser integer, IN vpatient integer, OUT vresult integer) IS

	vAudit			AUDITHIS."Audit"%TYPE;			-- audit history

	vProvider		PRODUCER."Producer"%TYPE;		-- student's producer ID, eg 'S1234'.



	vStartChk		STARTCHK."StartChk"%TYPE;		-- unique sequence id for STARTCHK.StartChk

	vStartTrx		STARTTRX."StartTrx"%TYPE;		-- unique sequence id for STARTTRX.StartTrx



	vParentType		TRX."Type"%TYPE;			-- TRX.Type of parent procedure, for step APPTRX

	vParentTreatment	TRX."Treatment"%TYPE;			-- TRX.Treatment of parent procedure, for step APPTRX

	vParentOrigRecNo	TRX."OrigRecNo"%TYPE;			-- TRX.OrigRecNo of parent procedure, for step APPTRX



  vStartChkMethod CLINIC."StartChkMethod"%TYPE;

  vSecondaryProvider PRODUCER."Producer"%TYPE;

  vSecondaryProviderUser USERS."User"%TYPE;



	-- cursor containing all treatments linked to an appointment (via apptrx) that don't have a start check yet

	CURSOR cAppTreatments(cpAppointment APPTRX."Appointment"%TYPE) IS

		SELECT

      AP."Type",

      AP."Id",

      AP."Treatment",

      TR."OrigRecNo",

      PR."IsStepChild",

      PR."ParentProcedure",

			TR."CreationDate",

      AP."Procedure"

		FROM AppTrx AP, Trx TR, Procedur PR

		WHERE 1=1

      /*

			AND AP."Type" = TR."Type"

			AND AP."Id" = TR."Id"

			AND AP."Treatment" = TR."Treatment"

      */

      AND TR."OrigRecNo" = (SELECT TR2."OrigRecNo" FROM TRX TR2 WHERE TR2."Type" = AP."Type" AND TR2."Id" = AP."Id" AND TR2."Treatment" = AP."Treatment" AND ROWNUM = 1)

			AND TR."Deleted" = 0

			AND AP."Appointment" = cpAppointment

			AND PR."Procedure" = AP."Procedure"

			AND NOT EXISTS

      (

				SELECT 1

				FROM STARTCHK SC, STARTTRX ST, AUDITHIS AH

				WHERE 1=1

          AND AH."Audit" = SC."Audit"

          AND SC."StartChk" = ST."StartChk"

          AND TRUNC(AH."Date") = TRUNC(SYSDATE)

					AND SC."Appointment" = AP."Appointment"

					AND ST."Type" = AP."Type"

					AND ST."Id" = AP."Id"

					AND ST."Treatment" = AP."Treatment"

          AND ST."Procedure" = AP."Procedure"

      )



    UNION



    SELECT

      Ap."Type",

      AP."AppTrx",

      Ap."Treatment",

      0 AS "OrigRecNo",

      0 AS "IsStepChild",

      null AS "ParentProcedure",

      null AS "CreationDate",

      Ap."Procedure"

    FROM APPTRX AP

    WHERE 1=1



      AND AP."Type" = 0

      AND AP."Id" = 0

      AND AP."Treatment" = 0

			AND AP."Appointment" = cpAppointment

      AND NOT EXISTS

      (

				SELECT 1

				FROM STARTCHK SC, STARTTRX ST, AUDITHIS AH

				WHERE 1=1

          AND AH."Audit" = SC."Audit"

          AND SC."StartChk" = ST."StartChk"

          AND TRUNC(AH."Date") = TRUNC(SYSDATE)

					AND SC."Appointment" = AP."Appointment"

					AND ST."Type" = AP."Type"

					AND ST."Id" = AP."Id"

					AND ST."Treatment" = AP."Treatment"

          AND ST."Procedure" = AP."Procedure"

      );

BEGIN

	BEGIN

    SELECT CL."StartChkMethod", AP."Assistant", UR."User"

    INTO vStartChkMethod, vSecondaryProvider, vSecondaryProviderUser

    FROM APPOINT AP

    JOIN CLINIC CL ON CL."Clinic" = AP."Clinic"

    LEFT JOIN USERS UR ON AP."Assistant" = UR."Producer" AND NOT (TRIM(AP."Assistant") IS NULL OR LENGTH(TRIM(AP."Assistant")) = 0)

    WHERE AP."Appointment" = vAppointment

    AND ROWNUM = 1;



		-- add STARTCHK record

		SELECT "Producer"

		INTO vProvider FROM USERS WHERE "User" = vProviderUser;



		-- add an audit history

		vAudit := FPORTAL_PKG.AddAuditHis(vProviderUser, 'STARTCHK', 1);



		SELECT STARTCHK_STARTCHK_SEQ.nextVal

		INTO vStartChk FROM DUAL;



		INSERT INTO StartChk VALUES

		(

			vStartChk,			-- STARTCHK.StartChk

			vPatient,			-- STARTCHK.Patient

			vAppointment,			-- STARTCHK.Appointment

			vProvider,			-- STARTCHK.Provider

			vInstructor,			-- STARTCHK.AppUser

			vAudit 				-- STARTCHK.Audit

		);



		FOR appTrx IN cAppTreatments(vAppointment) LOOP



			-- add STARTTRX records

			SELECT STARTTRX_STARTTRX_SEQ.nextVal

			INTO vStartTrx FROM DUAL;



			INSERT INTO StartTrx VALUES

			(

				vStartTrx,		-- STARTTRX.StartTrx

				vStartChk,		-- STARTTRX.StartChk

				appTrx."Type",		-- STARTTRX.Type

				appTrx."Id",		-- STARTTRX.Id

				appTrx."Treatment",	-- STARTTRX.Treatment

				appTrx."OrigRecNo",	-- STARTTRX.OrigRecNo

				appTrx."Procedure"	-- STARTTRX.Procedure

			);



			-- add parent procedure line if appointment trx is a step.

			IF (appTrx."IsStepChild" = 1 AND NOT (TRIM(appTrx."ParentProcedure") IS NULL OR LENGTH(TRIM(appTrx."ParentProcedure")) = 0)) THEN



				-- get the treatment line for the parent

				SELECT MAX("Treatment")

				INTO vParentTreatment FROM TRX

				WHERE 1=1

					AND "Id" = appTrx."Id"

					AND "Deleted" = 0

					AND "CreationDate" =  appTrx."CreationDate"

					AND "Procedure" = appTrx."ParentProcedure"

					AND "Treatment" < appTrx."Treatment";



				BEGIN



					SELECT "Type", "OrigRecNo"

					INTO vParentType, vParentOrigRecNo FROM TRX

					WHERE 1=1

						AND "Id" = appTrx."Id"

						AND "Deleted" = 0

						AND "CreationDate" =  appTrx."CreationDate"

						AND "Procedure" = appTrx."ParentProcedure"

						AND "Treatment" = vParentTreatment;



					-- add it

					SELECT STARTTRX_STARTTRX_SEQ.nextVal

					INTO vStartTrx FROM DUAL;



					INSERT INTO StartTrx VALUES

					(

						vStartTrx,		-- STARTTRX.StartTrx

						vStartChk,		-- STARTTRX.StartChk

						vParentType,		-- STARTTRX.Type

						appTrx."Id",		-- STARTTRX.Id

						vParentTreatment,	-- STARTTRX.Treatment

						vParentOrigRecNo,	-- STARTTRX.OrigRecNo

						' '			-- STARTTRX.Procedure

					);



				EXCEPTION WHEN NO_DATA_FOUND THEN

					NULL; -- couldn't find the parent, this stepcode was added manually

				END;

			END IF;

		END LOOP;



    IF vStartChkMethod = 1 AND vSecondaryProviderUser IS NOT NULL THEN

      BEGIN

        SELECT STARTCHK_STARTCHK_SEQ.nextVal

        INTO vStartChk FROM DUAL;



        -- add an audit history

        vAudit := FPORTAL_PKG.AddAuditHis(vSecondaryProviderUser, 'STARTCHK', 1);



    		INSERT INTO StartChk VALUES

        (

          vStartChk,			-- STARTCHK.StartChk

          vPatient,			-- STARTCHK.Patient

          vAppointment,			-- STARTCHK.Appointment

          vSecondaryProvider,			-- STARTCHK.Provider

          vInstructor,			-- STARTCHK.AppUser

          vAudit 				-- STARTCHK.Audit

        );

      END;

    END IF;



		COMMIT;

		vResult := 0;



	EXCEPTION WHEN OTHERS THEN

		vResult := -1;

	END;

END;



/**

* Procedure gets the current, next, or previous appointment for a provider for today. If the provider has an appointment at the current time, returns the current

*  appointment. Otherwise, returns the next appointment if the provider has an appointment scheduled later in the day, or the last appointment if there are no

*  appointments scheduled later in the day and there was a previous appointment.<p/>

*

* param: vUserId INPUT: User ID of the provider to check (USERS.User).<p/>

* param: vApptType OUTPUT: Type of the appointment being returned (-1=no appts found, 0=current appt, 1=next appt, 2=previous appt).<p/>

* param: vAppoint OUTPUT: Appointment ID of the next/current/previous appointment, or null if no appointments today for the provider.<p/>

*/

PROCEDURE getcurrentapptloc(IN vuserid integer, OUT vappttype integer, OUT vappoint integer) IS

  vApptId APPOINT."Appointment"%TYPE;

  vProducer USERS."Producer"%TYPE;



  vCurrentTime NUMBER;



BEGIN

	-- get producer ID

	BEGIN

		SELECT TRIM("Producer")

		INTO vProducer

		FROM USERS

		WHERE "User" = vUserId;

	EXCEPTION WHEN NO_DATA_FOUND THEN

		vApptId := NULL;

		vProducer := NULL;

		vApptType := -1;

	END;



	IF vProducer IS NOT NULL THEN



		-- calculate the time in minutes from midnight

		SELECT FLOOR(TO_NUMBER(TO_CHAR(SYSDATE,'SSSSS'))/60)

		INTO vCurrentTime FROM DUAL;



		-- check if there is an appointment happening right now

		BEGIN

			SELECT "Appointment"

			INTO vApptId

			FROM APPOINT

			WHERE 1=1

				AND TRIM("Producer") = TRIM(vProducer)

				AND "Date" = TRUNC(SYSDATE)

				AND "Type" IN (0,1,2)

				AND "Status" = 0

				AND FLOOR(TO_NUMBER(TO_CHAR(SYSDATE,'SSSSS'))/60) BETWEEN "From" AND ("From" + "Time0" + "Time1" + "Time2" + "Time3" + "Time4" + "Time5")

				AND ROWNUM <= 1; -- don't want to handle double-booking at this point



			vApptType := 0;



		EXCEPTION WHEN NO_DATA_FOUND THEN

			vApptId := NULL;

			vApptType := -1;

		END;



		IF vApptId IS NULL THEN

			-- get the next appointment

			BEGIN

				SELECT "Appointment"

				INTO vApptId

				FROM APPOINT

					WHERE 1=1

					AND TRIM("Producer") = TRIM(vProducer)

					AND "Date" = TRUNC(SYSDATE)

					AND "Type" IN (0,1,2)

					AND "Status" = 0

					AND FLOOR(TO_NUMBER(TO_CHAR(SYSDATE,'SSSSS'))/60) < "From"

					AND "From" = (

						SELECT MIN("From")

						FROM APPOINT

						WHERE 1=1

							AND TRIM("Producer") = TRIM(vProducer)

							AND "Date" = TRUNC(SYSDATE)

							AND "Type" IN (0,1,2)

							AND "Status" = 0

							AND FLOOR(TO_NUMBER(TO_CHAR(SYSDATE,'SSSSS'))/60) < "From")

					AND ROWNUM <= 1; -- don't want to handle double-booking at this point



				vApptType := 1;



			EXCEPTION WHEN NO_DATA_FOUND THEN

				vApptId := NULL;

				vApptType := -1;

			END;

		END IF;



		IF vApptId IS NULL THEN

			-- get the previous appointment

			BEGIN

				SELECT "Appointment"

				INTO vApptId

				FROM APPOINT

					WHERE 1=1

					AND TRIM("Producer") = TRIM(vProducer)

					AND "Date" = TRUNC(SYSDATE)

					AND "Type" IN (0,1,2)

					AND "Status" = 0

					AND FLOOR(TO_NUMBER(TO_CHAR(SYSDATE,'SSSSS'))/60) > "From"

					AND ("From" + "Time0" + "Time1" + "Time2" + "Time3" + "Time4" + "Time5") = (

						SELECT MAX("From" + "Time0" + "Time1" + "Time2" + "Time3" + "Time4" + "Time5")

						FROM APPOINT

						WHERE 1=1

							AND TRIM("Producer") = TRIM(vProducer)

							AND "Date" = TRUNC(SYSDATE)

							AND "Type" IN (0,1,2)

							AND "Status" = 0

							AND FLOOR(TO_NUMBER(TO_CHAR(SYSDATE,'SSSSS'))/60) > ("From"+ "Time0" + "Time1" + "Time2" + "Time3" + "Time4" + "Time5"))

					AND ROWNUM <= 1; -- don't want to handle double-booking at this point



				vApptType := 2;



			EXCEPTION WHEN NO_DATA_FOUND THEN

				vApptId := NULL;

				vApptType := -1;

			END;

		END IF;

	END IF;





  	-- get the appointment information

	IF vApptId IS NOT NULL THEN

		vAppoint := vApptId;

	END IF;

END;





/**

* Procedure that gets the station that a user is currently logged into. <p/>

*

* param: vUserId INPUT: User ID of the user to check (USERS.User).<p/>

* param: vStation OUPUT: Station name of the station that the user is currently logged into, or null if not currently logged into axiUm.<p/>

*/

PROCEDURE getcurrentstnloc(IN vuserid integer, OUT vstation character varying) IS

	vTerminal  VARCHAR2(128);

	vSessionLogin NUMBER(10);

  	vSessionLogout NUMBER(10);

BEGIN

	-- find the most recent login that hasn't been logged out

  	BEGIN

		SELECT TRIM(STN), LOGIN

		INTO vTerminal, vSessionLogin

		FROM

		(

			SELECT

				"Terminal" STN,

				MAX("LoginHistory") LOGIN

			FROM LOG

			WHERE 1=1

				AND "AuditUser" = vUserId

				AND "Date" = TRUNC(SYSDATE)

				AND "Action" = 1

			GROUP BY "Terminal"

			ORDER BY MAX("LoginHistory") DESC

		)

		WHERE ROWNUM <= 1;



	EXCEPTION WHEN NO_DATA_FOUND THEN

		-- didn't find any logins for this user

		vSessionLogin := 0;

	END;



  	-- check if this login has logged out yet

  	IF vSessionLogin > 0 THEN

		BEGIN

			SELECT LOGOUT

			INTO vSessionLogout

			FROM

			(

				SELECT

					MAX("LoginHistory") LOGOUT

				FROM LOG

				WHERE 1=1

					AND "User" = vUserId

					AND "Date" = TRUNC(SYSDATE)

					AND "Action" = 2

					AND TRIM("Terminal") = vTerminal

				GROUP BY "Terminal"

				ORDER BY MAX("LoginHistory") DESC

			)

			WHERE ROWNUM <= 1;



		EXCEPTION WHEN NO_DATA_FOUND THEN

			-- didn't find any logouts for this user

			vSessionLogout := 0;

		END;

  	END IF;



  	IF vSessionLogin > vSessionLogout THEN

  		vStation := vTerminal; -- they haven't logged out yet

  	ELSE

  		vStation := NULL; -- logged out of most recent session

  	END IF;

END;



/**

* Procedure that retrieves the type and value of an FSETTING. The value of the FSETTING is converted by this procedure to the correct data type when returned. <p/>

*

* param: vUser INPUT: User ID that this FSETTING applies to (0=everyone, 1+= unique user ID (USERS.User)).<p/>

* param: vKey INPUT: Unique key of the FSETTING to retrieve (FSETTING.Key).<p/>

* param: vScope OUTPUT: Scope of the FSETTING (0=general, 1=user).<p/>

* param: vType OUTPUT: Type of the FSETTING (-1=key not found, 0=text,1=number,2=date).<p/>

* param: vTextVal OUTPUT: Value of the key, if it referenced a text type FSETTING. <p/>

* param: vIntVal OUTPUT: Value of the key, if it referenced an integer type FSETTING. <p/>

* param: vDateVal OUTPUT: Value of the key, if it referenced a date type FSETTING. <p/>

* param: vShortDescription OUTPUT: Value of the short description. <p/>

* param: vLongDescription OUTPUT: Value of the long description. <p/>

* param: vDefaultValue OUTPUT: Value of the default value. <p/>

* param: vRules OUTPUT: Value of the rules value. <p/>

*/

PROCEDURE getfsetting(IN vuser integer, IN vkey character varying, OUT vscope integer, OUT vtype integer, OUT vtextval character varying, OUT vintval numeric, OUT vdateval timestamp without time zone, OUT vshortdescription character varying, OUT vlongdescription character varying, OUT vdefaultvalue character varying, OUT vrules character varying) IS

BEGIN

	BEGIN

    -- get the scope, setting type, Short Description, Long Description, Default Value and Rules

    SELECT "Scope", "SettingType", "ShortDescription", "LongDescription", "DefaultValue", "Rules"

    INTO vScope, vType, vShortDescription, vLongDescription, vDefaultValue, vRules

    FROM FSETTING

    WHERE 1=1

     AND "User" = vUser

     AND "Key" = vKey;



		IF vType = 0 THEN

			-- text value

			SELECT TRIM("Value")

			INTO vTextVal

			FROM FSETTING

			WHERE 1=1

				AND "User" = vUser

				AND "Key" = vKey;



		ELSIF vType = 1 THEN

			-- number value

			SELECT TO_NUMBER(TRIM("Value"))

			INTO vIntVal

			FROM FSETTING

			WHERE 1=1

				AND "User" = vUser

				AND "Key" = vKey;



		ELSIF vType = 2 THEN

			-- date value in dd-mon-yyyy

			SELECT TO_DATE(TRIM("Value"),'MON DD, YYYY')

			INTO vDateVal

			FROM FSETTING

			WHERE 1=1

				AND "User" = vUser

				AND "Key" = vKey;



		END IF;



	EXCEPTION WHEN NO_DATA_FOUND THEN

		vType := -1; -- couldn't find the key

	END;

END;





/**

* Procedure to change FSetting <p/>

*

* param: vUserId INPUT: User ID of the setting to change the value (0 = general, 1+ = FSETTING.User).<p/>

* param: vKey INPUT: Key of the setting to change the value (FSETTING.Key).<p/>

* param: vValue INPUT: Value of the setting (FSETTING.Value).<p/>

*/

PROCEDURE setfsetting(IN vuserid integer, IN vkey character varying, IN vvalue character varying) IS

BEGIN

	UPDATE FSETTING SET

		"Value" = vValue

	WHERE 1=1

		AND "User" = vUserId

		AND "Key" = vKey;

	COMMIT;

END;





/**

* Procedure to add FSetting <p/>

*

* param: vUserId INPUT: User ID (0 = general, 1+ = FSETTING.User).<p/>

* param: vKey INPUT: Key of the setting (FSETTING.Key).<p/>

* param: vSettingType INPUT: Setting type of the setting (0=Text, 1=Number, 2=Date).<p/>

* param: vValue INPUT: Value of the setting (FSETTING.Value).<p/>

* param: vScope INPUT: Scope of the setting (0=General, 1=User).<p/>

*/

PROCEDURE addfsetting(IN vuserid integer, IN vkey character varying, IN vsettingtype integer, IN vvalue character varying, IN vscope integer) IS

  SqlStmt  VARCHAR2(4000);

  vRowCount INTEGER;

BEGIN



    INSERT INTO FSETTING ("User", "Key", "SettingType", "Value", "Scope")

    VALUES (vUserId, vKey, vSettingType, vValue, vScope);

  COMMIT;

END;



/**

* Add General FSetting

*/

PROCEDURE addgeneralfsetting(IN vkey character varying, IN vscope integer, IN vtype integer, IN vshortdesc character varying, IN vlongdesc character varying, IN vdefaultvalue character varying, IN vrules character varying) IS

  vCount INTEGER;

BEGIN



  SELECT COUNT(1) INTO vCount FROM FSETTING WHERE "Key" = vKey;



  IF vCount = 0 THEN

		BEGIN

    INSERT INTO FSETTING

    (

      "User",

      "Key",

      "Scope",

      "SettingType",

      "Value",

      "ShortDescription",

      "LongDescription",

      "DefaultValue",

      "Rules"

    )

    VALUES

    (

      0,

      vKey,

      vScope,

      vType,

      vDefaultValue,

      vShortDesc,

      vLongDesc,

      vDefaultValue,

      vRules

    );

    COMMIT;

		END;

	ELSE

		BEGIN

		UPDATE FSETTING

		SET "Scope" = vScope, "SettingType" = vType, "ShortDescription" = vShortDesc, "LongDescription" = vLongDesc, "DefaultValue" = vDefaultValue, "Rules" = vRules

		WHERE "Key" = vKey;

		COMMIT;

		END;

  END IF;

END;



/**

* Procedure to delete FSetting <p/>

* param: vUserId INPUT: User ID of setting to delete. <p/>

* param: vKey INPUT: Key of setting to delete. <p/>

*/

PROCEDURE deletefsetting(IN vuserid integer, IN vkey character varying) IS

  SqlStmt  VARCHAR(4000);

BEGIN

  SqlStmt := 'DELETE FROM FSETTING WHERE "User" = :1 AND "Key" = :2';

  EXECUTE IMMEDIATE SqlStmt USING vUserId, vKey;

  COMMIT;

END;



/**

* Procedure to get a name of Practice

* param: vPracticeId INPUT: ID of the practice PRACTICE.Id<p/>

* param: vName OUTPUT: name of the practice PRACTICE.Name

*/

PROCEDURE getpracticename(IN vpracticeid integer, OUT vname character varying) IS

BEGIN

  SELECT "Name"

  INTO vName

  FROM PRACTICE

  WHERE "Id" = vPracticeId;



  EXCEPTION WHEN NO_DATA_FOUND THEN

  vName := NULL;

END;



/**

* Procedure to get list of practices

* param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

*	<li>Id - Numeric ID of the Practice. <br/>

*	<li>Name - Name of the practice.<br/>

*/

PROCEDURE getpractices(OUT results_cur cursor_pkg.weakcursor) IS

	SQLStmt  VARCHAR2(4000);

BEGIN

	SQLStmt :=

		'

		SELECT

			"Id",

			"Name"

		FROM PRACTICE

    WHERE "Inactive" = 0

		';

	BEGIN

		OPEN results_cur FOR SQLStmt;

	EXCEPTION WHEN NO_DATA_FOUND THEN

		results_cur := NULL;

	END;

END;



/**

* Procedure to check if the practice is a valid active practice

* param: vPracticeId INPUT: Practice ID (PRACTICE."Id")

* param: vInactive OUTPUT: State of practice ID (0=active, 1=inactive/none-valid)

*/

PROCEDURE checkpractice(IN vpracticeid integer, OUT vinactive integer) IS

BEGIN

  SELECT "Inactive"

  INTO vInactive

  FROM PRACTICE

  WHERE "Id" = vPracticeId;



  EXCEPTION WHEN NO_DATA_FOUND THEN

		vInactive := 1;

END;



/**

* Procedure to get default practice set in axiUm </p>

* param: vStationID INPUT: station id to get default value from. </p>

* param: vPracticeID OUTPUT: practice ID set in axiUm.</p>

*/

PROCEDURE getdefaultpractice(IN vstationid integer, OUT vpracticeid integer) IS

BEGIN

  SELECT INI."ValueNum"

  INTO vPracticeID

  FROM INISET INS, INIITEM INI, INIDEF IND

  WHERE 1 = 1

  AND INS."Iniset" = INI."Iniset"

  AND INI."Inidef" = IND."Inidef"

  AND INS."Station" = vStationID

  AND IND."Inidef" = 293;



  EXCEPTION WHEN NO_DATA_FOUND THEN



  BEGIN

    SELECT IND."Default"

    INTO vPracticeID

    FROM INIDEF IND

    WHERE IND."Inidef" = 293;



    EXCEPTION WHEN NO_DATA_FOUND THEN

    vPracticeID := NULL;

  END;

END;



/**

* Procedure to get the Country id for the practice

* param: vPracticeId INPUT: Practice ID (PRACTICE."Id")

* param: vCountryId OUTPUT: Country id

*/

PROCEDURE getpracticecountry(IN vpracticeid integer, OUT vcountryid integer) IS

BEGIN

  SELECT "Country"

  INTO vCountryId

  FROM PRACTICE

  WHERE "Id" = vPracticeId;



  EXCEPTION WHEN NO_DATA_FOUND THEN

		vCountryId := 1;

END;



/**

* Procedure to get the axiUm Minimum Version for the practice

* param: vVersion OUTPUT: version

*/

PROCEDURE getpracticeminversion(OUT vversion character varying) IS

BEGIN

  SELECT MIN("Version") INTO vVersion FROM PRACTICE;



  EXCEPTION WHEN NO_DATA_FOUND THEN

		vVersion := NULL;

END;



/**

* Procedure to get the axiUm Maximum Version for the practice

* param: vVersion OUTPUT: version

*/

PROCEDURE getpracticemaxversion(OUT vversion character varying) IS

BEGIN

  SELECT MAX("Version") INTO vVersion FROM PRACTICE;



  EXCEPTION WHEN NO_DATA_FOUND THEN

		vVersion := NULL;

END;



/**

* Function to count the number of treatment notes that are attached to a particular treatment.<p/>

*

* param: vType INPUT: The type of the treatment (TRX.Type).<p/>

* param: vId INPUT: The ID of the treatment (TRX.Id).<p/>

* param: vTreatment INPUT: The treatment # of the treatment (TRX.Treatment).<p/>

* return: Count of the number of treatment notes attached to the treatment.<p/>

*/

FUNCTION gettrxnotecount(vtype integer, vid integer, vtreatment integer) RETURN integer IS

	vNoteCount INTEGER;

	vNoteCountSOAP INTEGER;

BEGIN

	BEGIN

		-- get count of general and template notes

		SELECT COUNT( DISTINCT N2."Auto" )

		INTO vNoteCount

		FROM NOTES2 N2, TRX TR, CHARTLNK CL

		WHERE 1=1

			AND TR."Deleted" = 0

			AND TR."Type" = vType

			AND TR."Id" = vId

			AND TR."Treatment" = vTreatment

			AND (N2."TxId" = TR."ChartTrx"

            OR (CL."Previous" = TR."ChartTrx" AND N2."TxId" = CL."Auto"))

			AND N2."Status" = 0

			AND N2."Type" = 1

      AND N2."AppUser" = 0;



		-- get count of SOAP notes

		SELECT COUNT( DISTINCT "OtherId")

		INTO vNoteCountSOAP

		FROM NOTES2 N2, TRX TR, CHARTLNK CL

		WHERE 1=1

			AND TR."Deleted" = 0

			AND TR."Type" = vType

			AND TR."Id" = vId

			AND TR."Treatment" = vTreatment

        		AND (N2."TxId" = TR."ChartTrx"

          			OR (CL."Previous" = TR."ChartTrx" AND N2."TxId" = CL."Auto"))

			AND N2."Status" = 0

			AND N2."Type" = 4

      AND N2."AppUser" = 0;





	EXCEPTION WHEN NO_DATA_FOUND THEN

		vNoteCount := 0;

		vNoteCountSOAP := 0;

	END;



	RETURN vNoteCount + vNoteCountSOAP;

END;





/**

* Function to count the number of treatment notes that are attached to treatments on an appointment.<p/>

*

* param: vAppoint INPUT: Appointment ID of the appointment (APPOINT.Appointment)<br/>

* return: Count of the number of treatment notes attached to treatments on the appointment.<br/>

*/

FUNCTION getappttrxnotecount(vappoint integer) RETURN integer IS

	vNoteCount INTEGER;



	CURSOR cAppTrxCur IS

		SELECT

    MIN(APT."Id") AS "Id",

    MIN(APT."AppTrx") AS "AppTrx",

    MIN(APT."Appointment") AS "Appointment",

    MIN(APT."Type") AS "Type",

    MIN(APT."Treatment") AS "Treatment",

    MIN(APT."Procedure") AS "Procedure",

    MIN(APT."Date") AS "Date"

    FROM APPTRX APT, TRX TR

    WHERE "Appointment" = vAppoint

    AND APT."Id" = TR."Id"

    AND APT."Treatment" = TR."Treatment"

    AND APT."Type" = TR."Type"

    GROUP BY TR."ChartTrx";

BEGIN



	vNoteCount := 0;



	FOR cAppTrx IN cAppTrxCur LOOP

		vNoteCount := vNoteCount + FPORTAL_PKG.GetTrxNoteCount(cAppTrx."Type", cAppTrx."Id", cAppTrx."Treatment");

	END LOOP;



	RETURN vNoteCount;

END;



/**

* Procedure to generate and return the list of line items (treatments on the appointment, and notes tied to those

*  treatments) to be shown when an appointment is viewed in any of the Appointment subtabs (My Appts, Watch, All Appts).<p/>

*

* param: vAppointment INPUT: Appointment ID of the appointment (APPOINT.Appointment)<p/>

* param: vPracticeId INPUT: Practice ID<p/>

* param: vHideConsent INPUT: 1 = skip consent check<p/>

* param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

*	<li>Description - Description of the line item. For treatments, this is the procedure code and part of the procedure description. For notes, the type of note. <br/>

*	<li>TxStatus - For treatments, the status of the treatment line (P,I,C,P*,I*,etc). Not used for notes.<br/>

*	<li>Site - The site (tooth#) that the treatment or note applies to. <br/>

*	<li>Site2 - The ending site (tooth#) for bridge-type procedure.<br />

*	<li>Surface - The surface(s) that the treatment applies to. Not used for notes.<br/>

*	<li>TxDate - Treatment date of treatments or entry date for notes, as a string formatted MON DD YYYY.<br/>

*	<li>LineType - Type of the line item (-1=dummy tx, 0=unapproved tx, 1=approved tx, 2=general tx note, 3=template tx note, 4=SOAP tx note).<br/>

*	<li>TrxTreatme2 - For treatments, ptr to corresponding TREATME2.Auto. For treatment notes, same value as the treatment that it is attached to. <br/>

*	<li>Approved - Flag indicating if this line is approved (0=no, 1=yes).<br/>

*	<li>ItemKey - Unique key to use to get the details for this line item (treatments: TRX.ChartTrx, general/template notes: NOTES2.Auto, SOAP notes: NOTES2.OtherId).<br/>

*	<li>StartChkUser - For treatments, User ID (USERS.User) of last user to start check this treatment. For notes, same as trx it's tied to. <br/>

*	<li>TxHasReqConsent - Flag indicating if this treatment needs/has consent (0=needs it but doesn't have it, 1=either has it or doesn't need it) <p/>

*	<li>ChartLnk - ChartLnk ID (treatments/findings: CHARTLNK.Id, general/template notes: 0, SOAP notes: 0).<p/>

*/

PROCEDURE getapptlines(IN vappointment integer, IN vpracticeid integer, IN vhideconsent integer, OUT results_cur cursor_pkg.weakcursor) IS

  vCountryName  VARCHAR2(100);

  vDays INTEGER;

BEGIN



  -- Get country information

  BEGIN

    SELECT

      CASE WHEN "Country" = 0 THEN 'Canada'

      ELSE 'USA'

      END AS "CountryName"

      INTO vCountryName

    FROM PRACTICE

    WHERE "Id" = vPracticeId;



    EXCEPTION WHEN NO_DATA_FOUND THEN

      vCountryName := 'Canada';

  END;



  BEGIN

    SELECT CALCULATEDAYSDIFF_S(TRUNC(SYSDATE), TO_DATE('01-JAN-1901', 'DD-MON-YYYY')) INTO vDays FROM DUAL; -- AX39652

  END;



  -- 1st select block: unapproved appt tx

  -- 2nd select block: approved appt tx

  -- 3rd select block: dummy appt tx

  -- 4th select block: tx notes (general   SOAP) attached to appt tx

  -- 5th select block: ortho visits (unapproved/approved)

  -- 6th select block: treatment notes associated with ortho visit





  /*

  Calling style for Treatment include "IsOrthoNote" from FP_2.00.50.03.83+

  If error is found for this procedure, refer back to FP_2.00.50.03.82

  */

  OPEN results_cur FOR

	SELECT * FROM

    (

      -- 1st select block: unapproved appt tx

      SELECT

      MIN(FPORTAL_PKG.GetProcedureName(CL."Procedure")) AS "Description",

      MIN(TRIM(CL."Status")) AS "TxStatus",

      MIN(TRIM(CL."Site")) AS "Site",

      CASE WHEN LENGTH(TRIM(TRANSLATE(MIN(NVL( TRIM(CL."Site"), 'ZZZZ')), ' +-.0123456789',' '))) >= 1 THEN  MIN(NVL( TRIM(CL."Site"), 'ZZZZ')) ELSE LPAD(MIN(TRIM(CL."Site")),'4','0') END AS "SiteAsNumber",

      MAX(TRIM(CL."Site2")) AS "Site2",

      CASE WHEN LENGTH(TRIM(TRANSLATE(MAX(NVL( TRIM(CL."Site2"), 'ZZZZ')), ' +-.0123456789',' '))) >= 1 THEN  MAX(NVL( TRIM(CL."Site2"), 'ZZZZ')) ELSE LPAD(MAX(TRIM(CL."Site2")),'4','0') END AS "Site2AsNumber",

      MIN(TRIM(CL."Surface")) AS "Surface",

      MIN(TO_CHAR(CL."TxDate",'MON DD, YYYY')) AS "TxDate",

      0 AS "LineType",

      MIN(CL."Auto") AS "TrxTreatme2",

      0 AS "Approved",

      TR."ChartTrx" AS "ItemKey",

      MAX(FPORTAL_PKG.HasPrevStartCheckTx(APT."Appointment",APT."Type",APT."Id",APT."Treatment",APT."Procedure")) AS "StartChkUser",

      CASE WHEN MIN(CL."Status") = 'D' THEN 1 WHEN vHideConsent > 0 THEN 1 ELSE MAX(FPORTAL_PKG.TxHasReqConsent(TR."Type",TR."Id",TR."Treatment",CL."Patient",CL."Producer",CL."Procedure", CL."Site")) END AS "TxHasReqConsent",

      MIN(CL."Id") AS "ChartLnk",

      MIN(TR."Patient") AS "Patient",

      MIN(PR."RequireGrading") AS "RequireGrading",

      FPORTAL_PKG.RequireGrading(MIN(PRD."RequireGrading"), MIN(PR."RequireGrading"), MIN(TR."Discipline") ) AS "GeneralRequireGrading",

      CASE WHEN MIN(N2."Auto") IS NULL THEN 0 ELSE 1 END AS "IsOrthoNote",

      '' AS "DateTimeOrder"

      FROM APPTRX APT

      JOIN TRX TR ON

      (

        (APT."Type" = TR."Type" AND APT."Id" = TR."Id" AND APT."Treatment" = TR."Treatment")

        OR

        (TR."OrigRecNo" = ( SELECT TR2."OrigRecNo"

                  FROM TRX TR2

                  WHERE APT."Type" = TR2."Type"

                  AND APT."Id" = TR2."Id"

                  AND APT."Treatment" = TR2."Treatment"

                  AND TR2."Deleted" = 2))

      ) AND TR."Deleted" = 0

      JOIN PROCEDUR PR ON TR."Procedure" = PR."Procedure"

      JOIN CHARTLNK CL ON TR."ChartTrx" = DECODE(CL."Previous",0,NULL,CL."Previous") AND TR."Patient" = CL."Patient"

      JOIN PRODUCER PRD ON TR."Producer" = PRD."Producer"

      LEFT JOIN DISCIPL DIS ON TR."Discipline" = DIS."Class"

      LEFT JOIN NOTES2 N2 ON CL."Auto" = N2."TxId" AND N2."Type" = 3

      WHERE APT."Appointment" = vAppointment

      GROUP BY TR."ChartTrx"



      UNION ALL



      -- 2nd select block: approved appt tx

      SELECT

      MIN(FPORTAL_PKG.GetProcedureName(TR."Procedure")) AS "Description",

      MIN(TRIM(TR."Status") || DECODE((SELECT "MakeInactive" FROM STATUS ST WHERE ST."Status" = TR."TxStatus" AND ST."Type" = 3),0,'',1,'*')) AS "TxStatus",

      MIN(TRIM(TR."Site")) AS "Site",

      CASE WHEN LENGTH(TRIM(TRANSLATE(MIN(NVL( TRIM(TR."Site"), 'ZZZZ')), ' +-.0123456789',' '))) >= 1 THEN  MIN(NVL( TRIM(TR."Site"), 'ZZZZ')) ELSE LPAD(MIN(TRIM(TR."Site")),'4','0') END AS "SiteAsNumber",

      MAX(TRIM(TR."Site2")) AS "Site2",

      CASE WHEN LENGTH(TRIM(TRANSLATE(MAX(NVL( TRIM(TR."Site2"), 'ZZZZ')), ' +-.0123456789',' '))) >= 1 THEN  MAX(NVL( TRIM(TR."Site2"), 'ZZZZ')) ELSE LPAD(MAX(TRIM(TR."Site2")),'4','0') END AS "Site2AsNumber",

      MIN(TRIM(TR."Surface")) AS "Surface",

      MIN(TO_CHAR(TR."TreatmentDate",'MON DD, YYYY')) AS "TxDate",

      1 AS "LineType",

      TR."ChartTrx" AS "TrxTreatme2",

      1 AS "Approved",

      TR."ChartTrx" AS "ItemKey",

      MAX(FPORTAL_PKG.HasPrevStartCheckTx(APT."Appointment",APT."Type",APT."Id",APT."Treatment",APT."Procedure")) AS "StartChkUser",

      CASE WHEN vHideConsent > 0 THEN 1 ELSE MAX(FPORTAL_PKG.TxHasReqConsent(TR."Type",TR."Id",TR."Treatment",TR."Patient",TR."Producer",TR."Procedure", TR."Site")) END AS "TxHasReqConsent",

      0 AS "ChartLnk",

      MIN(TR."Patient") AS "Patient",

      MIN(PR."RequireGrading") AS "RequireGrading",

      FPORTAL_PKG.RequireGrading(MIN(PRD."RequireGrading"), MIN(PR."RequireGrading"), MIN(TR."Discipline") ) AS "GeneralRequireGrading",

      CASE WHEN MIN(N2."Auto") IS NULL THEN 0 ELSE 1 END AS "IsOrthoNote",

      '' AS "DateTimeOrder"



      FROM APPTRX APT

      JOIN TRX TR ON

      (

        (APT."Type" = TR."Type" AND APT."Id" = TR."Id" AND APT."Treatment" = TR."Treatment")

        OR

        (TR."OrigRecNo" = ( SELECT TR2."OrigRecNo"

                  FROM TRX TR2

                  WHERE APT."Type" = TR2."Type"

                  AND APT."Id" = TR2."Id"

                  AND APT."Treatment" = TR2."Treatment"

                  AND TR2."Deleted" = 2))

      ) AND TR."Deleted" = 0

      JOIN PROCEDUR PR ON TR."Procedure" = PR."Procedure"

      JOIN PRODUCER PRD ON TR."Producer" = PRD."Producer"

      LEFT JOIN DISCIPL DIS ON TR."Discipline" = DIS."Class"

      LEFT JOIN NOTES2 N2 ON TR."ChartTrx" = N2."TxId" AND N2."Type" = 3

      WHERE APT."Appointment" = vAppointment

      AND NOT EXISTS (SELECT 1 FROM CHARTLNK CL WHERE CL."Patient" = TR."Patient" AND CL."Previous" = TR."ChartTrx")

      GROUP BY TR."ChartTrx"



      UNION ALL



      -- 3rd select block: dummy appt tx

      SELECT DISTINCT

      FPORTAL_PKG.GetProcedureName(APT."Procedure") AS "Description",

      '' AS "TxStatus",

      '' AS "Site",

      '' AS "SiteAsNumber",

      '' AS "Site2",

      '' AS "Site2AsNumber",

      '' AS "Surface",

      TO_CHAR(TRUNC(SYSDATE),'MON DD, YYYY') AS "TxDate",

      -1 AS "LineType",

      0 AS "TrxTreatme2",

      -1 AS "Approved",

      0 AS "ItemKey",

      FPORTAL_PKG.HasPrevStartCheckTx(APT."Appointment",APT."Type",APT."AppTrx",APT."Treatment",APT."Procedure") AS "StartChkUser",

      CASE WHEN vHideConsent > 0 THEN 1 ELSE FPORTAL_PKG.PlannedProcHasReqConsent(AP."Patient",AP."Producer",APT."Procedure") END AS "TxHasReqConsent",

      0 AS "ChartLnk",

      AP."Patient",

      PR."RequireGrading" AS "RequireGrading",

      0 AS "GeneralRequireGrading",

      0 AS "IsOrthoNote",

      '' AS "DateTimeOrder"

      FROM APPTRX APT, PROCEDUR PR, APPOINT AP

      WHERE 1=1

      AND APT."Appointment" = AP."Appointment"

      AND APT."Type" = 0

      AND APT."Id" = 0

      AND APT."Treatment" = 0

      AND APT."Appointment" = vAppointment

      AND APT."Procedure" = PR."Procedure"



      UNION ALL



      -- 4th select block: tx notes (general   SOAP) attached to appt tx

      SELECT DISTINCT

      CASE

        WHEN N2."Type" = 1 THEN 'NOTE (' || FPORTAL_PKG.GetProcedureCodeByTxId(N2."TxId") || ')'

        WHEN N2."Type" = 4 THEN 'SOAP NOTE (' || FPORTAL_PKG.GetProcedureCodeByTxId(N2."TxId") || ')'

      END AS "Description",

      CASE

        WHEN N2."Status" = 0 THEN NULL

        ELSE 'D'

      END AS "TxStatus",

      (SELECT SR."Value" FROM FSITEREF SR WHERE SR."Id" = N2."Site" AND SR."Country" = vCountryName AND ROWNUM = 1) AS "Site",

      CASE

         WHEN LENGTH(TRIM(TRANSLATE(NVL(TRIM((SELECT SR."Value" FROM FSITEREF SR WHERE SR."Id" = N2."Site" AND SR."Country" = vCountryName AND ROWNUM = 1)), 'ZZZZ'), ' +-.0123456789',' '))) >= 1

         THEN  NVL( TRIM((SELECT SR."Value" FROM FSITEREF SR WHERE SR."Id" = N2."Site" AND SR."Country" = vCountryName AND ROWNUM = 1)), 'ZZZZ')

         ELSE LPAD(TRIM((SELECT SR."Value" FROM FSITEREF SR WHERE SR."Id" = N2."Site" AND SR."Country" = vCountryName AND ROWNUM = 1)),'4','0')

      END AS "SiteAsNumber",

      '' AS "Site2",

      '' AS "Site2AsNumber",

      NULL AS "Surface",

      TO_CHAR(N2."Date",'MON DD, YYYY') AS "TxDate",

      CASE

        WHEN N2."Type" = 4 THEN 4

        WHEN N2."IsTemplate" = 0 THEN 2

        WHEN N2."IsTemplate" = 1 THEN 3

      END AS "LineType",

      N2."TxId" AS "TrxTreatme2",

      CASE

        WHEN N2."AppUser" = 0 THEN 0

        ELSE 1

      END AS "Approved",

      CASE

        WHEN N2."Type" = 1 THEN N2."Auto" -- Note

        WHEN N2."Type" = 4 THEN N2."OtherId" -- Soap Note

      END AS "ItemKey",

      FPORTAL_PKG.HasPrevStartCheckTx(APT."Appointment",APT."Type",APT."Id",APT."Treatment",APT."Procedure") AS "StartChkUser",

      1 AS "TxHasReqConsent",

      0 AS "ChartLnk",

      TR."Patient",

      0 AS "RequireGrading",

      0 AS "GeneralRequireGrading",

      0 AS "IsOrthoNote",

      TO_CHAR("AddDateTime", 'YYYY-MM-DD HH24:MI:SS') AS "DateTimeOrder"

      FROM APPTRX APT, TRX TR, NOTES2 N2

      WHERE 1=1

	  AND            

	  -- AX-21506 consolidated - no OR  

        TR."OrigRecNo" IN ( SELECT TR2."OrigRecNo"

                    FROM TRX TR2

                    WHERE APT."Type" = TR2."Type"

                    AND APT."Id" = TR2."Id"

                    AND APT."Treatment" = TR2."Treatment"

                    AND TR2."Deleted" IN (0, 2))

      AND TR."Deleted" = 0

      AND APT."Appointment" = vAppointment

      AND N2."Type" IN (1, 4)

      AND (

          N2."Status" = 0

          OR

          (N2."Status" = 1 AND N2."AppUser" = 0)

        )

      -- AX-21506

      AND(

          N2."TxId"in ( select  TR3."ChartTrx" from trx TR3 where TR3."Type" = TR."Type" and TR3."Id" = TR."Id" and TR."Treatment" = TR3."Treatment"          

         union SELECT CL."Auto" FROM CHARTLNK CL WHERE CL."Patient" = TR."Patient" AND CL."Previous" = TR."ChartTrx" AND ROWNUM = 1)

        )

      AND N2."SectionNo" = 0



      UNION ALL



      -- 5th select block: ortho visits (unapproved/approved)

      SELECT

      '***Ortho Visit***' AS "Description",

      CASE WHEN T2."Deleted" = 0 THEN 'V' ELSE 'D' END AS "TxStatus",

      TRIM(T2."Site") AS "Site",

      CASE WHEN LENGTH(TRIM(TRANSLATE(NVL( TRIM(T2."Site"), 'ZZZZ'), ' +-.0123456789',' '))) >= 1

        THEN NVL( TRIM(T2."Site"), 'ZZZZ')

        ELSE LPAD(TRIM(T2."Site"),'4','0')

        END AS "SiteAsNumber",

      TRIM(T2."Site2") AS "Site2",

      CASE WHEN LENGTH(TRIM(TRANSLATE(NVL( TRIM(T2."Site2"), 'ZZZZ'), ' +-.0123456789',' '))) >= 1

        THEN NVL( TRIM(T2."Site2"), 'ZZZZ')

        ELSE LPAD(TRIM(T2."Site2"),'4','0')

        END AS "Site2AsNumber",

      FPORTAL_PKG.GetSurface(TRIM(T2."Site"),TRIM(T2."Surface")) AS "Surface",

      TO_CHAR(T2."ModifiedDateTime",'MON DD, YYYY') AS "TxDate",

      CASE WHEN T2."AppUser" = 0 THEN 14 ELSE 15 END AS "LineType",

      T2."Auto" AS "TrxTreatme2",

      CASE

        WHEN T2."Deleted" = 0 AND T2."AppUser" = 0 THEN 0

        WHEN T2."Deleted" = 0 AND T2."AppUser" != 0 THEN 1

        WHEN T2."Deleted" = 1 AND T2."DelAppUser" = 0 THEN 0

        WHEN T2."Deleted" = 1 AND T2."DelAppUser" != 0 THEN 1

        ELSE 0

        END AS "Approved",

      T2."Auto" AS "ItemKey",

      0 AS "StartChkUser",

      1 AS "TxHasReqConsent",

      CASE WHEN CL."Id" > 0 THEN CL."Id" ELSE 0 END AS "ChartLnk",

      P2."PtxPId" AS "Patient",

      0 AS "RequireGrading",

      0 AS "GeneralRequireGrading",

      1 AS "IsOrthoNote",

      TO_CHAR(T2."ModifiedDateTime", 'YYYY-MM-DD HH24:MI:SS') AS "DateTimeOrder"

      FROM APPOINT AP

      JOIN TREATME2 T2 ON AP."Producer" = T2."Provider" OR AP."Assistant" = T2."Provider"

      JOIN PATIENT2 P2 ON T2."PId" = P2."Auto"

      JOIN PATIENT PT ON P2."PtxPId" = PT."Patient" AND PT."Patient" = AP."Patient"

      JOIN PROCEDUR PR ON T2."CodeId" = PR."Id"

      JOIN PRODUCER PRD ON T2."Provider" = PRD."Producer"

      LEFT JOIN CHARTLNK CL ON T2."Auto" = CL."Auto"

      WHERE AP."Appointment" = vAppointment

      AND ((T2."AppUser" = 0 AND T2."Deleted" = 0) OR (T2."Deleted" = 1 AND T2."DelAppUser" = 0) OR (T2."Deleted" = 0 AND T2."AppUser" != 0 AND T2."AppDate" = TRUNC(SYSDATE)))

      AND T2."Status" = 5

	  AND T2."Days" = vDays



      UNION ALL



      -- 6th select block: treatment notes associated with ortho visit

      SELECT



        CASE

          WHEN N2."Type" = 1 THEN 'NOTE (' || FPORTAL_PKG.GetProcedureCodeByTxId(N2."TxId") || ')'

          WHEN N2."Type" = 4 THEN 'SOAP NOTE (' || FPORTAL_PKG.GetProcedureCodeByTxId(N2."TxId") || ')'

        END AS "Description",

        CASE WHEN N2."Status" = 0 THEN NULL ELSE 'D' END AS "TxStatus",

        ( SELECT SR."Value" FROM FSITEREF SR WHERE SR."Id" = N2."Site" AND SR."Country" = vCountryName AND ROWNUM = 1) AS "Site",

        CASE

          WHEN LENGTH(TRIM(TRANSLATE(NVL(TRIM((SELECT SR."Value" FROM FSITEREF SR WHERE SR."Id" = N2."Site" AND SR."Country" = vCountryName AND ROWNUM = 1)), 'ZZZZ'), ' +-.0123456789',' '))) >= 1

            THEN  NVL( TRIM((SELECT SR."Value" FROM FSITEREF SR WHERE SR."Id" = N2."Site" AND SR."Country" = vCountryName AND ROWNUM = 1)), 'ZZZZ')

          ELSE LPAD(TRIM((SELECT SR."Value" FROM FSITEREF SR WHERE SR."Id" = N2."Site" AND SR."Country" = vCountryName AND ROWNUM = 1)),'4','0')

        END AS "SiteAsNumber",

        '' AS "Site2",

        '' AS "Site2AsNumber",

        NULL AS "Surface",

        TO_CHAR(N2."Date",'MON DD, YYYY') AS "TxDate",

        CASE

          WHEN N2."Type" = 4 THEN 4

          WHEN N2."IsTemplate" = 0 THEN 2

          WHEN N2."IsTemplate" = 1 THEN 3

        END AS "LineType",

        N2."TxId" AS "TrxTreatme2",

        CASE

          WHEN N2."AppUser" = 0 THEN 0

          ELSE 1

        END AS "Approved",

        CASE

          WHEN N2."Type" = 1 THEN N2."Auto" -- Note

          WHEN N2."Type" = 4 THEN N2."OtherId" -- Soap Note

        END AS "ItemKey",

        0 AS "StartChkUser",

        1 AS "TxHasReqConsent",

        0 AS "ChartLnk",

        AP."Patient",

        0 AS "RequireGrading",

        0 AS "GeneralRequireGrading",

        0 AS "IsOrthoNote",

        TO_CHAR(N2."AddDateTime", 'YYYY-MM-DD HH24:MI:SS') AS "DateTimeOrder"



      FROM APPOINT AP

      JOIN TREATME2 T2 ON AP."Producer" = T2."Provider" OR AP."Assistant" = T2."Provider"

      JOIN PATIENT2 P2 ON T2."PId" = P2."Auto" AND P2."PtxPId" = AP."Patient"

      JOIN NOTES2 N2 ON N2."TxId" = T2."Auto"

      LEFT JOIN CHARTLNK CL ON T2."Auto" = CL."Auto"

      WHERE AP."Appointment" = vAppointment

      AND ((T2."AppUser" = 0 AND T2."Deleted" = 0) OR (T2."Deleted" = 1 AND T2."DelAppUser" = 0) OR (T2."Deleted" = 0 AND T2."AppUser" != 0 AND T2."AppDate" = TRUNC(SYSDATE)))

      AND T2."Status" = 5

	  AND T2."Days" = vDays

      AND N2."Type" IN (1,4)

      AND ( N2."Status" = 0 OR (N2."Status" = 1 AND N2."AppUser" = 0))

      AND N2."SectionNo" = 0

    )

    ORDER BY "LineType",

      CASE WHEN "LineType" = 4 THEN "ItemKey" END ASC,

      CASE WHEN "LineType" = 2 OR "LineType" = 3 THEN "ItemKey" END DESC, "SiteAsNumber", "Site2AsNumber", "Surface";

  EXCEPTION WHEN NO_DATA_FOUND THEN

    results_cur := null;

END;



/**

* Procedure to retrieve list of diagnoses associated with a treatement<p/>

* param: vChartTrx INPUT: ID for approved treatments TRX.ChartTrx<p/>

* param: vChartLnk INPUT: ID for unapproved treatments CHARTLNK.Auto<p/>

* param: vType INPUT: Flag indicating if this treatment is approved or not approved (0 = unapproved with trx record, 1 = approved, 2 = unapproved with no trx record)<p/>

* param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

* <li>Description - Diagnosis description (DIAGCODE.Description).<br/>

*/

PROCEDURE getdiagnosesfortreatment(IN vcharttrx integer, IN vchartlnk integer, IN vtype integer, OUT results_cur cursor_pkg.weakcursor) IS

  vId INTEGER;

BEGIN

  IF vType = 0 OR vType = 2 THEN

    BEGIN

      SELECT "Auto" INTO vId

      FROM CHARTLNK

      WHERE "Id" = vChartLnk;



      EXCEPTION WHEN NO_DATA_FOUND THEN

      vId := 0;

    END;

  ELSE

    vId := vChartTrx;

  END IF;



  OPEN results_cur FOR

    SELECT DC.*

    FROM TXDIAG TXD, DIAGCODE DC

    WHERE TXD."ChartTrx" = vId

    AND TXD."DiagCode" = DC."DiagCode"

    ORDER BY DC."Description";



  EXCEPTION WHEN NO_DATA_FOUND THEN

    results_cur := NULL;



END;





/**

* 35485977 Procedure to retrieve Missing Consents Codes with a treatement<p/>

* param: vChartTrx INPUT: ID for approved treatments TRX.ChartTrx<p/>

* param: vChartLnk INPUT: ID for unapproved treatments CHARTLNK.Auto<p/>

* param: vType INPUT: Flag indicating if this treatment is approved or not approved (0 = unapproved with trx record, 1 = approved, 2 = unapproved with no trx record)<p/>

* param: results OUTPUT: VARCHAR2 with Missing Consent Codes Separated by commas<br/>

*/

PROCEDURE getconsentcodesfortrx(IN vcharttrx integer, IN vchartlnk integer, IN vtype integer, OUT results character varying) IS

  vProcedure  VARCHAR2(7);

	vSite  VARCHAR2(10);

	vPatient NUMBER(10);

	vProducer  VARCHAR2(100);

	vOrigRecNo NUMBER(10);

BEGIN

  IF vType = 0 THEN -- unapproved tx

    BEGIN

      SELECT DISTINCT

        TR."Procedure",

        TR."Site",

        TR."Patient",

        TR."Producer"

      INTO vProcedure, vSite, vPatient, vProducer

      FROM CHARTLNK CL

      JOIN TRX TR ON TR."ChartTrx" = DECODE(CL."Previous", 0, NULL, CL."Previous")

      WHERE CL."Previous" = vChartTrx

      AND CL."Id" = vChartLnk

      AND ROWNUM = 1;



      EXCEPTION WHEN NO_DATA_FOUND THEN

      vPatient := 0;

    END;

	ELSIF vType = 1 THEN -- approved tx

    BEGIN

      SELECT DISTINCT

        TR."Procedure",

        TR."Site",

        TR."Patient",

        TR."Producer",

				TR."OrigRecNo"

			INTO vProcedure, vSite, vPatient, vProducer, vOrigRecNo

      FROM TRX TR

      WHERE TR."ChartTrx" = vChartTrx

      AND ROWNUM = 1;



      EXCEPTION WHEN NO_DATA_FOUND THEN

				vPatient := 0;

    END;

  ELSE

    vPatient := 0;

  END IF;



	IF vPatient > 0 THEN

		BEGIN

			SELECT CONSENT_PKG.TRX_HAS_CONSENT(vOrigRecNo, vProcedure, vSite, vPatient, SUBSTR(vProducer, 1,1), 1) INTO results FROM DUAL;



			EXCEPTION WHEN NO_DATA_FOUND THEN

				results := '';

		END;

	ELSE

		results := '';

	END IF;

END;



/**

* 35485977 Procedure to retrieve Missing Consents Codes with a treatement<p/>

* param: vMissingCodes INPUT: VARCHAR2 with Missing Consent Codes Separated by commas<p/>

* param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

  *	<li>Consent - Consent Code (CONSENT.Consent).<br/>

  *	<li>Description - Consent description (CONSENT.Description).<br/>

*/

PROCEDURE getconsentlistfortrx(IN vmissingcodes character varying, OUT results_cur cursor_pkg.weakcursor) IS

BEGIN

	OPEN results_cur FOR

		SELECT C."Consent", C."Description"

		FROM CONSENT C

		WHERE C."Inactive" = 0

		AND (C."TxBased" = 1 OR C."Consent" IN (vMissingCodes))

		ORDER BY "Consent";



	EXCEPTION WHEN NO_DATA_FOUND THEN

		results_cur := NULL;

END;





/**

* Procedure that retrieves the details for a treatment line (in Appt tab or Provider tab).<p/>

*

* param: vChartTrx INPUT: ID for the CHARTLNK row associated with this treatment (unapproved = CHARTLNK.Previous, approved = TRX.ChartTrx)<p/>

* param: vType INPUT: Flag indicating if this treatment is approved or not approved (0=not approved, 1=approved, 2=planned not-approved)<p/>

* param: vDescription OUTPUT: String containing the line description, returned outside cursor for safety.<p/>

* param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

*	<li>Discipline - Treatment discipline code (TRX.Discipline).<br/>

*	<li>Diagnosis - Treatment diagnosis code (TRX.DiagCode).<br/>

*	<li>Phase - Treatment phase (TRX.Phase).<br/>

*	<li>Sequence - Treatment sequence (TRX.Seq).<br/>

*	<li>Custom1Name - Name of the first custom field.<br/>

*	<li>Custom1Val - Value of the first custom field.<br/>

*	<li>Custom2Name - Name of the second custom field.<br/>

*	<li>Custom2Val - Value of the second custom field.<br/>

*	<li>Custom3Name - Name of the third custom field.<br/>

*	<li>Custom3Val - Value of the third custom field.<br/>

*	<li>Custom4Name - Name of the fourth custom field.<br/>

*	<li>Custom4Val - Value of the fourth custom field.<br/>

*	<li>PatientName - Name of the patient for this treatment, as a string formatted like 'F. LastName'.<br/>

*	<li>EntryUserName - Name of the entry user for this treatment, as a string formatted like 'F. LastName'.<br/>

*	<li>EntryDate - Entry/modified date for this treatment, as a string formatted like 'MON DD, YYYY'.<br/>

*	<li>AppUserName - Name of the approval user for this treatment, as a string formatted like 'F. LastName'.<br/>

*	<li>AppDate - Approval date for this treatment, as a string formatted like 'MON DD, YYYY'.<br/>

*	<li>Status - Status of the treatment, eg P, I C, P*, I*.<br/>

*	<li>Site - Tooth number for the treatment (TRX.Site).<br/>

*	<li>Surface - Surfaces for the treatment (TRX.Surface).<p/>

*/

PROCEDURE getlinedetailtreatment(IN vcharttrx integer, IN vchartlnk integer, IN vtype integer, OUT vdescription character varying, OUT vorthonote character varying, OUT results_cur cursor_pkg.weakcursor) IS

    SQLStmt  VARCHAR2(4000);



    vCustom1Name CUSTTYPE."Description"%TYPE;

    vCustom2Name CUSTTYPE."Description"%TYPE;

    vCustom3Name CUSTTYPE."Description"%TYPE;

    vCustom4Name CUSTTYPE."Description"%TYPE;



    txInfo rec_TxDetail;

    ptInfo rec_PatientDetail;

    provInfo rec_UserDetail;

    provInfo2 rec_UserDetail;

    appInfo rec_UserDetail;

    evalInfo rec_UserDetail;

BEGIN

    -- get custom field names

    GetCustomFieldNames(vCustom1Name,vCustom2Name,vCustom3Name,vCustom4Name);



    -- get the treatment details

    txInfo := GetTreatmentDetail(vChartTrx, vChartLnk, vType);



    IF txInfo.TxChartTrx != -1 THEN

      -- get the patient details

      ptInfo := GetPatientDetail(txInfo.TxPatientId);



      -- get the entry user details

      provInfo := GetUserDetail(txInfo.TxEntryUser);



      -- get the provider details

      provInfo2 := GetProviderDetail(txInfo.TxProducer);



      -- get the approval user details

      appInfo := GetUserDetail(txInfo.TxAppUser);

    END IF;



    IF txInfo.TxEvalUser != 0 AND txInfo.TxEvalUser IS NOT NULL THEN

      evalInfo := GetUserDetail(txInfo.TxEvalUser);

    END IF;



    -- return the description as a separate parameter

    vDescription := txInfo.TxProcCode || ' - ' || txInfo.TxProcDesc;

    vOrthoNote := txInfo.TxOrthoNote;



    BEGIN

      OPEN results_cur FOR

        SELECT

          txInfo.TxChartId AS "ChartLnk",

          txInfo.TxId AS "TxId",

          txInfo.TxDiscipline AS "Discipline",

          txInfo.TxDiagnosis AS "Diagnosis",

          txInfo.TxPhase AS "Phase",

          NVL(txInfo.TxSequence,0) AS "Sequence",

          vCustom1Name AS "Custom1Name",

          txInfo.TxCustomVal1 AS "Custom1Val",

          vCustom2Name AS "Custom2Name",

          txInfo.TxCustomVal2 AS "Custom2Val",

          vCustom3Name AS "Custom3Name",

          txInfo.TxCustomVal3 AS "Custom3Val",

          vCustom4Name AS "Custom4Name",

          txInfo.TxCustomVal4 AS "Custom4Val",

          ptInfo.PtName AS "PatientName",

          ptInfo.PtFirst AS "PatientFirstName",

          ptInfo.PtLast AS "PatientLastName",

          ptInfo.PtAgeSex AS "PatientAgeSex",

          ptInfo.PtChart AS "PatientChart",

          txInfo.TxProducer AS "Producer",

          provInfo.UIsProvider AS "EntryUserIsProvider",

          provInfo.UProviderId AS "EntryUserProvId",

          provInfo.UName AS "EntryUserName",

          provInfo.UFirst AS "EntryUserFirstName",

          provInfo.ULast AS "EntryUserLastName",

          provInfo2.UName AS "ProducerName",

          provInfo2.UFirst AS "ProducerFirstName",

          provInfo2.ULast AS "ProducerLastName",

          txInfo.TxEntryDate AS "EntryDate",

					appInfo.UIsProvider AS "AppUserIsProvider",

					appInfo.UProviderId AS "AppUserProvId",

          appInfo.UName AS "AppUserName",

          appInfo.UFirst AS "AppUserFirstName",

          appInfo.ULast AS "AppUserLastName",

          txInfo.TxAppDate AS "AppDate",

          txInfo.TxDate AS "TxDate",

          txInfo.TxStatus AS "Status",

          txInfo.TxSite AS "Site",

          txInfo.TxSurface AS "Surface",



          txInfo.TxGrading AS "Grading",

          evalInfo.UName AS "EvalUserName",

          evalInfo.UFirst AS "EvalUserFirstName",

          evalInfo.ULast AS "EvalUserLastName",

          evalInfo.UIsProvider AS "EvalUserIsProvider",

          evalInfo.UProviderId AS "EvalUserProvId",

          txInfo.TxEvalDate AS "EvalDate",

          txInfo.TxEvalForm AS "EvalForm",

		  txInfo.TxIsOrthoTreatment AS "IsOrthoTreatment"

        FROM DUAL;

      EXCEPTION WHEN NO_DATA_FOUND THEN

      results_cur := null;

    END;

 END;



/**

* Procedure that retrieves the details for a note (general or template) line (in Appt tab or Provider tab).<p/>

*

* param: vAuto INPUT: ID of the note (NOTES2.Auto).<p/>

* param: vCountryName INPUT: Name of country.<p/>

* param: vNoteText OUTPUT: The text of the note, returned outside cursor for safety (NOTES2.Text).<p/>

* param: vDescription OUTPUT: String containing the line description, returned outside cursor for safety.<p/>

* param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

*	<li>Phase - Note phase (TRX.Phase).<br/>

*	<li>Sequence - Note sequence (TRX.Seq).<br/>

*	<li>Custom1Name - Name of the first custom field.<br/>

*	<li>Custom1Val - Value of the first custom field.<br/>

*	<li>Custom2Name - Name of the second custom field.<br/>

*	<li>Custom2Val - Value of the second custom field.<br/>

*	<li>NoteCode - Note code for the note (NOTES2.Code).<br/>

*	<li>PatientName - Name of the patient for this note, as a string formatted like 'F. LastName'.<br/>

*	<li>EntryUserName - Name of the entry user for this note, as a string formatted like 'F. LastName'.<br/>

*	<li>EntryDate - Entry/modified date for this note, as a string formatted like 'MON DD, YYYY'.<br/>

*	<li>AppUserName - Name of the approval user for this note, as a string formatted like 'F. LastName'.<br/>

*	<li>AppDate - Approval date for this note, as a string formatted like 'MON DD, YYYY'.<br/>

*	<li>Site - Tooth number for the note (TRX.Site).<p/>

*/

PROCEDURE getlinedetailnote(IN vauto integer, IN vcountryname character varying, OUT vnotetext character varying, OUT vdescription character varying, OUT results_cur cursor_pkg.weakcursor) IS

  	SQLStmt  VARCHAR2(4000);



  	vCustom1Name CUSTTYPE."Description"%TYPE;

  	vCustom2Name CUSTTYPE."Description"%TYPE;

  	vCustom3Name CUSTTYPE."Description"%TYPE;

  	vCustom4Name CUSTTYPE."Description"%TYPE;



  	noteInfo rec_NoteDetail;

  	ptInfo rec_PatientDetail;

  	provInfo rec_UserDetail;

  	appInfo rec_UserDetail;

BEGIN

	-- get custom field names

	GetCustomFieldNames(vCustom1Name,vCustom2Name,vCustom3Name,vCustom4Name);



	-- get note details

	noteInfo := GetNoteDetail(vAuto, vCountryName);



	IF noteInfo.NtAuto != -1 THEN

		-- get the patient details

		ptInfo := GetPatientDetail(noteInfo.NtPatientId);



		-- get the provider details

		provInfo := GetUserDetail(noteInfo.NtEntryUser);



		-- get the approval user details

		appInfo := GetUserDetail(noteInfo.NtAppUser);



		-- handle the text separately to preserve formatting

		vNoteText := noteInfo.NtNoteText;

	END IF;



	-- return the description as a separate parameter

	vDescription := noteInfo.NtDesc;



	-- return the results

	BEGIN

		OPEN results_cur FOR

    SELECT

      noteInfo.NtTxId AS "TxId",

			noteInfo.NtPhase AS "Phase",

			NVL(noteInfo.NtSequence,0) AS "Sequence",

			vCustom1Name AS "Custom1Name",

			noteInfo.NtCustomVal1 AS "Custom1Val",

			vCustom2Name AS "Custom2Name",

			noteInfo.NtCustomVal2 AS "Custom2Val",

			noteInfo.NtNoteCode AS "NoteCode",

			ptInfo.PtName AS "PatientName",

      ptInfo.PtFirst AS "PatientFirstName",

      ptInfo.PtLast AS "PatientLastName",

      ptInfo.PtAgeSex AS PatientAgeSex,

			ptInfo.PtChart AS "PatientChart",

      provInfo.UIsProvider AS "EntryUserIsProvider",

      provInfo.UProviderId AS "EntryUserProvId",

      provInfo.UPK AS "EntryUserId",

			provInfo.UName AS "EntryUserName",

      provInfo.UFirst AS "EntryUserFirstName",

      provInfo.ULast AS "EntryUserLastName",

			noteInfo.NtEntryDate AS "EntryDate",

      appInfo.UIsProvider AS "AppUserIsProvider",

      appInfo.UProviderId AS "AppUserProvId",

			appInfo.UName AS "AppUserName",

      appInfo.UFirst AS "AppUserFirstName",

      appInfo.ULast AS "AppUserLastName",

			noteInfo.NtAppDate AS "AppDate",

			noteInfo.NtSite AS "Site",

      noteInfo.NtStatus AS "Status"

		FROM DUAL;



    EXCEPTION WHEN NO_DATA_FOUND THEN

      results_cur := null;

	END;

END;





/**

* Procedure that retrieves the details for a note (SOAP) line (in Appt tab or Provider tab).<p/>

*

* param: vOtherId INPUT: ID of the SOAP note (NOTES2.OtherId).<p/>

* param: vCountryName INPUT: Name of country.<p/>

* param: vNoteTextS OUTPUT: The 'Subjective' text of the note, returned outside cursor for safety (NOTES2.Text).<p/>

* param: vNoteTextO OUTPUT: The 'Objective' text of the note, returned outside cursor for safety (NOTES2.Text).<p/>

* param: vNoteTextA OUTPUT: The 'Assessment' text of the note, returned outside cursor for safety (NOTES2.Text).<p/>

* param: vNoteTextP OUTPUT: The 'Planned' text of the note, returned outside cursor for safety (NOTES2.Text).<p/>

* param: vDescription OUTPUT: String containing the line description, returned outside cursor for safety.<p/>

* param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

*	<li>Phase - Note phase (TRX.Phase).<br/>

*	<li>Sequence - Note sequence (TRX.Seq).<br/>

*	<li>Custom1Name - Name of the first custom field.<br/>

*	<li>Custom1Val - Value of the first custom field.<br/>

*	<li>Custom2Name - Name of the second custom field.<br/>

*	<li>Custom2Val - Value of the second custom field.<br/>

*	<li>NoteCode - Note code for the note (NOTES2.Code).<br/>

*	<li>PatientName - Name of the patient for this note, as a string formatted like 'F. LastName'.<br/>

*	<li>EntryUserName - Name of the entry user for this note, as a string formatted like 'F. LastName'.<br/>

*	<li>EntryDate - Entry/modified date for this note, as a string formatted like 'MON DD, YYYY'.<br/>

*	<li>AppUserName - Name of the approval user for this note, as a string formatted like 'F. LastName'.<br/>

*	<li>AppDate - Approval date for this note, as a string formatted like 'MON DD, YYYY'.<br/>

*	<li>Site - Tooth number for the note (TRX.Site).<p/>

*/

PROCEDURE getlinedetailsoapnote(IN votherid integer, IN vcountryname character varying, OUT vnotetexts character varying, OUT vnotetexto character varying, OUT vnotetexta character varying, OUT vnotetextp character varying, OUT vdescription character varying, OUT results_cur cursor_pkg.weakcursor) IS

  	SQLStmt  VARCHAR2(4000);



  	vCustom1Name CUSTTYPE."Description"%TYPE;

  	vCustom2Name CUSTTYPE."Description"%TYPE;

  	vCustom3Name CUSTTYPE."Description"%TYPE;

  	vCustom4Name CUSTTYPE."Description"%TYPE;



  	noteInfo rec_SOAPNoteDetail;

  	ptInfo rec_PatientDetail;

  	provInfo rec_UserDetail;

  	appInfo rec_UserDetail;



BEGIN

	-- get custom field names

	GetCustomFieldNames(vCustom1Name,vCustom2Name,vCustom3Name,vCustom4Name);



	-- get note details

	noteInfo := GetSOAPNoteDetail(vOtherId, vCountryName);



	IF noteInfo.NtOtherId != -1 THEN

		-- get the patient details

		ptInfo := GetPatientDetail(noteInfo.NtPatientId);



		-- get the provider details

		provInfo := GetUserDetail(noteInfo.NtEntryUser);



		-- get the approval user details

		appInfo := GetUserDetail(noteInfo.NtAppUser);



		-- handle the text separately to preserve formatting

		vNoteTextS := noteInfo.NtNoteTextS;

		vNoteTextO := noteInfo.NtNoteTextO;

		vNoteTextA := noteInfo.NtNoteTextA;

		vNoteTextP := noteInfo.NtNoteTextP;

	END IF;



	-- return the description as a separate parameter

	vDescription := noteInfo.NtDesc;



	-- return the results

	BEGIN

		OPEN results_cur FOR

      SELECT

			noteInfo.NtPhase AS "Phase",

      noteInfo.NtTxId AS "TxId",

			NVL(noteInfo.NtSequence,0) AS "Sequence",

			vCustom1Name AS "Custom1Name",

			noteInfo.NtCustomVal1 AS "Custom1Val",

			vCustom2Name AS "Custom2Name",

			noteInfo.NtCustomVal2 AS "Custom2Val",

			noteInfo.NtNoteCode AS "NoteCode",

			ptInfo.PtName AS "PatientName",

      ptInfo.PtFirst AS "PatientFirstName",

      ptInfo.PtLast AS "PatientLastName",

      ptInfo.PtAgeSex AS "PatientAgeSex",

			ptInfo.PtChart AS "PatientChart",

      provInfo.UIsProvider AS "EntryUserIsProvider",

      provInfo.UProviderId AS "EntryUserProvId",

      provInfo.UPK AS "EntryUserId",

			provInfo.UName AS "EntryUserName",

      provInfo.UFirst AS "EntryUserFirstName",

      provInfo.ULast AS "EntryUserLastName",

			noteInfo.NtEntryDate AS "EntryDate",

      appInfo.UIsProvider AS "AppUserIsProvider",

      appInfo.UProviderId AS "AppUserProvId",

			appInfo.UName AS "AppUserName",

      appInfo.UFirst AS "AppUserFirstName",

      appInfo.ULast AS "AppUserLastName",

			noteInfo.NtAppDate AS "AppDate",

			noteInfo.NtSite AS "Site",

      noteInfo.NtStatus AS "Status",

      noteInfo.NtDate AS "Date"

      FROM DUAL;



    EXCEPTION WHEN NO_DATA_FOUND THEN

      results_cur := null;

	END;

END;





/**

* Procedure to retrieve the picture data and format of a user picture.<p/>

*

* param: vUserId INPUT: User ID of the user to get the picture for (USERS.User).<p/>

* param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

*	<li>FileExt - Format of the image, eg. 'jpg' (UPICTURE.FileExt).<br/>

* 	<li>PICTURE - BLOB containing the picture data (UPICTURE.PICTURE).<p/>

*/

PROCEDURE getuserpicture(IN vuserid integer, OUT results_cur cursor_pkg.weakcursor) IS

	SQLStmt  VARCHAR2(4000);

BEGIN

	SQLStmt :=

	'

		SELECT

			"FileExt",

			"PICTURE"

		FROM UPICTURE UP

		WHERE UP."User" = '||vUserId||'

	';



	BEGIN

		OPEN results_cur FOR SQLStmt;



	EXCEPTION WHEN NO_DATA_FOUND THEN

		results_cur := NULL;

	END;

END;





/**

* Procedure to retrieve the picture data and format of a patient picture.<p/>

*

* param: vPatientId INPUT: Patient ID of the patient to get the picture for (PATIENT.Patient).<p/>

* param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

*	<li>FileExt - Format of the image, eg. 'jpg' (PICTURE.FileExt).<br/>

* 	<li>PICTURE - BLOB containing the picture data (PICTURE.PICTURE).<p/>

*/

PROCEDURE getpatientpicture(IN vpatientid integer, OUT results_cur cursor_pkg.weakcursor) IS

	SQLStmt  VARCHAR2(4000);

BEGIN

	SQLStmt :=

	'

		SELECT

			"FileExt",

			"PICTURE"

		FROM PICTURE PI

		WHERE PI."Patient" = '|| vPatientId ||'

	';



	BEGIN

		OPEN results_cur FOR SQLStmt;



	EXCEPTION WHEN NO_DATA_FOUND THEN

		results_cur := NULL;

	END;

END;







/**

* Function to retrieve data about a particular patient and return it as a rec_PatientDetail RECORD type.<p/>

*

* param: vPatientId INPUT: Patient ID of the patient to fetch the data for (PATIENT.Patient).<p/>

* return: rec_PatientDetail record containing the patient data.<p/>

*/

FUNCTION getpatientdetail(vpatientid integer) RETURN rec_patientdetail IS

	ptInfo rec_PatientDetail;

BEGIN

	BEGIN

		SELECT

			PT."Patient",

			TRIM(PT."Chart"),

			SUBSTR(TRIM(PT."Prefered"),1,1),

			TRIM(PT."Prefered"),

			TRIM(PT."Last"),

			FLOOR(TO_CHAR(MONTHS_BETWEEN(SYSDATE, PT."Birth"))),

			TRIM(PT."Sex"),

			TRIM(PT."First") || ' ' || TRIM(PT."Last"),

      CASE WHEN PT."Sex" = 0 THEN 'U' WHEN PT."Sex" = 1 THEN 'M' WHEN PT."Sex" = 2 THEN 'F' WHEN PT."Sex" = 3 THEN 'T' WHEN PT."Sex" = 4 THEN 'X' WHEN PT."Sex" = 5 THEN 'O' END || FLOOR(TO_CHAR(MONTHS_BETWEEN(SYSDATE, PT."Birth")/12))

		INTO ptInfo.PtPK, ptInfo.PtChart, ptInfo.PtFirstInitial, ptInfo.PtFirst, ptInfo.PtLast, ptInfo.PtAgeMonths, ptInfo.PtSex, ptInfo.PtName, ptInfo.PtAgeSex

		FROM PATIENT PT

		WHERE 1=1

			AND PT."Patient" = vPatientId;



	EXCEPTION WHEN NO_DATA_FOUND THEN

		ptInfo := NULL;

	END;



	RETURN ptInfo;

END;





/**

* Function to retrieve data about a particular user and return it as a rec_UserDetail RECORD type.<p/>

*

* param: vUserId INPUT: User ID of the user to fetch the data for (USERS.User).<p/>

* return: rec_UserDetail record containing the user data.<p/>

*/

FUNCTION getuserdetail(vuserid integer) RETURN rec_userdetail IS

	userInfo rec_UserDetail;

BEGIN

	BEGIN

		SELECT

			US."User",

			SUBSTR(TRIM(US."First"),1,1),

			TRIM(US."First"),

			TRIM(US."Name"),

			US."IsInstructor",

			CASE WHEN (TRIM(US."Producer") IS NULL OR LENGTH(TRIM(US."Producer")) = 0) THEN 0 ELSE 1 END,

			TRIM(US."Producer"),

			TRIM(PR."PGroup"),

			PR."Year",

			TRIM(PT."Description"),

			SUBSTR(TRIM(US."First"),1,1) || '. ' || TRIM(US."Name"),

      PR."RequireGrading"

		INTO userInfo.UPK, userInfo.UFirstInitial, userInfo.UFirst, userInfo.ULast, userInfo.UIsInstructor, userInfo.UIsProvider,

			userInfo.UProviderId, userInfo.UProviderGroup, userInfo.UProviderYear, userInfo.UProviderTypeDesc, userInfo.UName, userInfo.URequireGrading

		FROM USERS US

			LEFT JOIN PRODUCER PR ON PR."Producer" = US."Producer"

			LEFT JOIN PRODTYPE PT ON PR."TypeCode" = PT."Code"

		WHERE 1=1

			AND US."User" = vUserId

      AND ROWNUM = 1;



	EXCEPTION WHEN NO_DATA_FOUND THEN

		userInfo := NULL;

	END;



	RETURN userInfo;

END;



/**

* Function to retrieve data about a particular provider and return it as a rec_UserDetail RECORD type.<p/>

*

* param: vProducer INPUT: Producer of the user to fetch the data for (PRODUCER.Producer).<p/>

* return: rec_UserDetail record containing the user data.<p/>

*/

FUNCTION getproviderdetail(vproducer character varying) RETURN rec_userdetail IS

  userInfo rec_UserDetail;

BEGIN

	BEGIN

		SELECT

			NVL(US."User", 0),

			SUBSTR(TRIM(PR."FirstName"),1,1),

			TRIM(PR."FirstName"),

			TRIM(PR."LastName"),

			CASE WHEN US."IsInstructor" IS NULL THEN 0 ELSE US."IsInstructor" END AS "IsInstructor",

			CASE WHEN (TRIM(US."Producer") IS NULL OR LENGTH(TRIM(US."Producer")) = 0) THEN 0 ELSE 1 END,

			TRIM(PR."Producer"),

			TRIM(PR."PGroup"),

			PR."Year",

			TRIM(PT."Description"),

			SUBSTR(TRIM(PR."FirstName"),1,1) || '. ' || TRIM(PR."LastName"),

			PR."RequireGrading",

			PR."Inactive"

		INTO userInfo.UPK, userInfo.UFirstInitial, userInfo.UFirst, userInfo.ULast, userInfo.UIsInstructor, userInfo.UIsProvider,

			userInfo.UProviderId, userInfo.UProviderGroup, userInfo.UProviderYear, userInfo.UProviderTypeDesc, userInfo.UName, userInfo.URequireGrading, userInfo.UInactive

		FROM PRODUCER PR

			LEFT JOIN USERS US ON PR."Producer" = US."Producer"

			LEFT JOIN PRODTYPE PT ON PR."TypeCode" = PT."Code"

		WHERE 1=1

			AND PR."Producer" = CAST(vProducer AS  CHAR(10))

      AND ROWNUM = 1;



	EXCEPTION WHEN NO_DATA_FOUND THEN

		userInfo := NULL;

	END;



	RETURN userInfo;

END;



/**

* Procedure to retrieve Provider Type and Group.<p/>

* param: vUser INPUT: USER ID.<br/>

* return: results_cur OUTPUT: weak cursor containing:

* <li>TypeCode - Provider Type Code <br/>

* <li>PGroup - Provider Group <br/>

*/

PROCEDURE getprovtypegroup(IN vuser integer, OUT results_cur cursor_pkg.weakcursor) IS

BEGIN

  OPEN results_cur FOR

  SELECT PR."TypeCode", PR."PGroup"

  FROM USERS UR, PRODUCER PR

  WHERE UR."User" = vUser

  AND UR."Producer" = PR."Producer"

  AND LENGTH(TRIM(UR."Producer")) > 0

  AND ROWNUM = 1;

END;



/**

* Function to retrieve name of user group by their key UGroup.<p/>

*

* param: vUGroup INPUT: UGroup."UGroup".<p/>

* return: rec_UserDetail record containing the user data.<p/>

*/

FUNCTION getugroupname(vugroup character) RETURN character varying IS

  vUGroupName  VARCHAR2(100);

BEGIN

  BEGIN

    SELECT UG."Description"

    INTO vUGroupName

    FROM UGROUP UG

    WHERE UG."UGroup" = vUGroup;



    EXCEPTION WHEN NO_DATA_FOUND THEN

      vUGroupName := '';

  END;



  RETURN vUGroupName;

END;



/**

* Procedure to retrieve the name and provider ID for a user.<p/>

*

* param: vUserId INPUT: User ID of the user to get the name for (USERS.User).<p/>

* param: vNameString OUTPUT: User's name as a string like 'F. LastName'.<p/>

* param: vLastName OUTPUT: User's last name (USERS.Name).<p/>

* param: vFirstName OUTPUT: User's first name (USERS.First).<p/>

* param: vProducer OUTPUT: User's provider ID (USERS.Producer).<p/>

*/

PROCEDURE getusername(IN vuserid integer, OUT vnamestring character varying, OUT vlastname character varying, OUT vfirstname character varying, OUT vproducer character varying) IS

	userInfo rec_UserDetail;

BEGIN

	userInfo := FPORTAL_PKG.GetUserDetail(vUserId);



	vNameString := userInfo.UName;

	vLastName := userInfo.ULast;

	vFirstName := userInfo.UFirst;

	vProducer := userInfo.UProviderId;

END;



/**

* Function to retrieve data about a particular appointment and return it as a rec_ApptDetail RECORD type.<p/>

*

* param: vApptId INPUT: Appointment ID of the appointment to fetch the data for (APPOINT.Appointment).<p/>

* return: rec_ApptDetail record containing the appointment data.<p/>

*/

FUNCTION getapptdetail(vapptid integer) RETURN rec_apptdetail IS

	apptInfo rec_ApptDetail;

BEGIN

	BEGIN

		SELECT

			AP."Appointment",

			TRIM( AP."Code" ),

			TRIM( AP."Class" ),

			TRIM( CL."Description" ),

            CL."StartChkMethod",

            CH."Chair",

			TRIM( CH."Name" ),

			TO_CHAR( AP."Date", 'MON DD, YYYY'),

      CASE

      WHEN AP."Type" = 4 THEN

        AP."Time0" + AP."Time1" + AP."Time2" + AP."Time3" + AP."Time4" + AP."Time5" || ' Minutes'

      WHEN AP."From" > 1440 OR (AP."Time0" + AP."Time1" + AP."Time2" + AP."Time3" + AP."Time4" + AP."Time5") > 1440 THEN

        '00:00 - 00:00'

      ELSE

        TO_CHAR(TO_DATE( AP."From"*60,'SSSSS'),'HH24:MI') || ' - ' ||

			  TO_CHAR(TO_DATE(( AP."From" + AP."Time0" + AP."Time1" + AP."Time2" +

			  AP."Time3" + AP."Time4" + AP."Time5")*60,'SSSSS'),'HH24:MI')

      END,

			TO_CHAR( AP."CreateDate", 'MON DD, YYYY'),

			AP."Patient",

			TRIM( AP."Reason" ),

			TRIM( AP."Producer" ),

      AP."Assistant",

			US."User",

      AP."Type",

      AP."IsConfirm",

			CASE WHEN TRUNC(AH."Date") = TRUNC(SYSDATE) THEN 1 ELSE 0 END,

      CASE WHEN TRUNC(AH."Date") = TRUNC(SYSDATE) THEN SC."StartChk" ELSE 0 END,

      CASE WHEN TRUNC(AH."Date") = TRUNC(SYSDATE) THEN SC."AppUser" ELSE 0 END,

      CASE WHEN TRUNC(AH."Date") = TRUNC(SYSDATE) THEN AH."Time" ELSE 0 END,

      sched_pkg.RequiresStartChk(AP."Appointment"),

      CASE

        WHEN (SELECT COUNT(1) FROM PTTYPES PT WHERE PT."Patient" = AP."Patient" AND PT."Deleted" = 0) = 0 OR

        (SELECT COUNT(1) FROM PTTYPES PT, PATTYPE PTC WHERE PT."Patient" = AP."Patient" AND PT."Deleted" = 0 AND PT."PatType" = PTC."PatType" AND PTC."StartChkRequired" = 1) > 0

        THEN 1 ELSE 0

      END,

      AP."IsOrtho",

      AP."OrthoStage",

      ST."Description"

		INTO apptInfo.ApptPK, apptInfo.ApptCode, apptInfo.ApptDiscipline, apptInfo.ApptClinic, apptInfo.ApptClinicStartChkMethod, apptInfo.ApptChairId, apptInfo.ApptChair, apptInfo.ApptDate,

			apptInfo.ApptTime, apptInfo.ApptBookDate, apptInfo.ApptPatient, apptInfo.ApptReason, apptInfo.ApptProvider, apptInfo.ApptAssistant,

			apptInfo.ApptProviderUser, apptInfo.ApptType, apptInfo.ApptConfirm, apptInfo.ApptStartChecked, apptInfo.ApptStartCheck, apptInfo.ApptStartCheckUser, apptInfo.ApptStartCheckTime,

      apptInfo.ApptRequiresStartChk, apptInfo.ApptPtRequiresStartChk, apptInfo.ApptIsOrtho, apptInfo.ApptOrthoStage, apptInfo.ApptOrthoStageDesc

		FROM APPOINT AP

		     JOIN CLINIC CL ON CL."Clinic" = AP."Clinic"

		     JOIN CHAIR CH ON CH."Chair" = AP."Chair"

		     JOIN USERS US ON US."Producer" = AP."Producer"

		     LEFT JOIN STARTCHK SC ON SC."Appointment" = AP."Appointment"

		     LEFT JOIN AUDITHIS AH ON AH."Audit" = SC."Audit"

         LEFT JOIN STAGE ST ON ST."Code" = AP."OrthoStage"

		WHERE 1=1

			AND AP."Appointment" = vApptId

			AND (SC."StartChk" IS NULL OR SC."StartChk" = (SELECT MAX(SM."StartChk") FROM STARTCHK SM WHERE SM."Appointment" = SC."Appointment"))

      AND ROWNUM = 1 ;



	EXCEPTION WHEN NO_DATA_FOUND THEN

		apptInfo := NULL;

	END;



	RETURN apptInfo;

END;



/**

* Procedure that returns the line items (all unapproved items, and items approved today) to be shown

*  when an provider is opened from Providers tab -> My Prov or All Prov. <p/>

*

* param: vUserId INPUT: User ID of the provider (USERS.User)<p/>

* param: vCountryName INPUT: Name of country.<p/>

* param: vSortDir INPUT: sorting direction 0 - ptFirstName -> ptLastName; 1 = ptLastName -> ptFirstName

* param: vHideConsent INPUT: 1 = skip consent check<p/>

* param: vMedicaidCode INPUT: List of procedure codes that are defined as a Medicaid code

* param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

*	<li>Description - Description of the line item. For treatments/findings, this is the procedure code and part of the procedure description. For notes, the type of note. <br/>

*	<li>Status - For treatments/findings, the status of the treatment line (P,I,C,P*,I*,A,E, etc). Not used for notes.

*	<li>Site - The site (tooth#) that the treatment/finding or note applies to. <br/>

* <li>Site2 - The ending site (tooth#) for bridge-type procedure.<br />

*	<li>Surface - The surface(s) that the treatment/finding applies to. Not used for notes.<br/>

*	<li>TxDate - Treatment date of treatments/findings or entry date for notes, as a string formatted MON DD YYYY.<br/>

*	<li>LineType - Type of the line item (0=unapproved I/C tx, 1=tx approved today, 2=unapproved planned tx,  3=general note, 4=template note, 5=SOAP note, 6=unapproved finding, 7=finding approved today).<br/>

*	<li>TrxTreatme2 - For treatments/findings, ptr to corresponding TREATME2.Auto. For treatment notes, same value as the treatment that it is attached to. <br/>

*	<li>Approved - Flag indicating if this line is approved (0=no, 1=yes).<br/>

*	<li>ItemKey - Unique key to use to get the details for this line item (treatments/findings: TRX.ChartTrx, general/template notes: NOTES2.Auto, SOAP notes: NOTES2.OtherId).<p/>

*	<li>ChartLnk - ChartLnk ID (treatments/findings: CHARTLNK.Id, general/template notes: 0, SOAP notes: 0).<p/>

*/

PROCEDURE getprovlines(IN vuserid integer, IN vcountryname character varying, IN vsortdir integer, IN vhideconsent integer, IN vmedicaidcode character varying, OUT results_cur cursor_pkg.weakcursor) IS

  vProducer  VARCHAR2(50);

	SQLStmt  VARCHAR2(32000);

BEGIN

  SELECT UR."Producer" INTO vProducer FROM USERS UR WHERE UR."User" = vUserId AND ROWNUM = 1;



	-- select block 1: unapproved I/C tx -- optimized by renold

	-- select block 2: tx which were approved today

	-- select block 3: unapproved planned tx

	-- select block 4: general or template notes (approved today/unapproved)

	-- select block 5: SOAP notes (approved today/unapproved)

	-- select block 6: unapproved findings

	-- select block 7: findings approved today

	-- select block 8: unapproved forms

    -- select block 9: forms approved today

    -- select block 10: unapproved perio   perio approved today

    -- select block 11: unapproved letters

    -- select block 12: letters approved today

    -- select block 13: Ortho Visits approved today or unapproved

  /*

  Calling style for Treatment include "IsOrthoNote" from FP_2.00.50.03.83+

  If error is found for this procedure, refer back to FP_2.00.50.03.82

  */

  SQLStmt := '

  SELECT * FROM

  (

    -- select block 1: unapproved I/C tx -- optimized by renold

    SELECT

      MIN(TRIM(CL."Procedure")) AS "Code",

      CASE WHEN TRIM(MIN(TR."Additional")) IS NULL OR MIN(PR."Prompt") = 0 THEN

        MIN(TRIM(CL."Procedure")) || '' - '' || MIN(PR."Description")

      ELSE

        MIN(TRIM(CL."Procedure")) || '' - '' || MIN(PR."Description") || '' ('' || TRIM(MIN(TR."Additional")) || '')''

      END AS "Description",

      MIN(TRIM(CL."Status")) AS "Status",

      MIN(TRIM(CL."Site")) AS "Site",

      CASE WHEN LENGTH(TRIM(TRANSLATE(MIN(NVL( TRIM(CL."Site"), ''ZZZZ'')), '' +-.0123456789'','' ''))) >= 1 THEN  MIN(NVL( TRIM(CL."Site"), ''ZZZZ'')) ELSE LPAD(MIN(TRIM(CL."Site")),''4'',''0'') END AS "SiteAsNumber",

      MAX(TRIM(CL."Site2")) AS "Site2",

      CASE WHEN LENGTH(TRIM(TRANSLATE(MAX(NVL( TRIM(CL."Site2"), ''ZZZZ'')), '' +-.0123456789'','' ''))) >= 1 THEN  MAX(NVL( TRIM(CL."Site2"), ''ZZZZ'')) ELSE LPAD(MAX(TRIM(CL."Site2")),''4'',''0'') END AS "Site2AsNumber",

      MIN(TRIM(CL."Surface")) AS "Surface",

      MIN(TO_CHAR(CL."TxDate",''MON DD, YYYY'')) AS "TxDate",

      0 AS "LineType",

      MIN(CL."Auto") AS "TrxTreatme2",

      0 AS "Approved",

      TR."ChartTrx" AS "ItemKey",

      MIN(CL."Id") AS "ChartLnk",

      CASE WHEN MIN(CL."Status") = ''D'' THEN

        1

      WHEN ' || vHideConsent || ' > 0 THEN

        1

      ELSE

        MAX(FPORTAL_PKG.TxHasReqConsent(TR."Type",TR."Id",TR."Treatment",CL."Patient",CL."Producer",CL."Procedure", CL."Site"))

      END AS "TxHasReqConsent",

      MIN(CL."Patient") AS "Patient",

      TRIM(MIN(PT."First")) || '' '' || TRIM(MIN(PT."Last")) AS "PtFullName",

      MIN(PT."First") AS "PtFirstName",

      MIN(PT."Last") AS "PtLastName",

      MIN(PT."Chart") AS "PtChart",

      TO_CHAR(FLOOR(MONTHS_BETWEEN(SYSDATE,MIN(PT."Birth")) / 12)) AS "PtAge",

      DECODE(MIN(PT."Sex"),0,''U'',1,''M'',2,''F'',3,''T'',4,''X'',5,''O'','''') AS "PtGender",

      MIN(PR."RequireGrading") AS "RequireGrading",

      FPORTAL_PKG.RequireGrading(MIN(PRD."RequireGrading"), MIN(PR."RequireGrading"), MIN(TR."Discipline") ) AS "GeneralRequireGrading",

      CASE WHEN MIN(N2."Auto") IS NULL THEN 0 ELSE 1 END AS "IsOrthoNote"

    FROM CHARTLNK CL

    JOIN TREATME2 T2 ON CL."Auto" = T2."Auto"

    JOIN TRX TR ON TR."ChartTrx" = DECODE(CL."Previous", 0, NULL, CL."Previous")

    JOIN PATIENT PT ON CL."Patient" = PT."Patient"

    JOIN PRODUCER PRD ON CL."Producer" = PRD."Producer"

    LEFT JOIN DISCIPL DIS ON CL."Discipline" = DIS."Class"

    LEFT JOIN PROCEDUR PR ON CL."Procedure" = PR."Procedure"

    LEFT JOIN NOTES2 N2 ON CL."Auto" = N2."TxId" AND N2."Type" = 3

    WHERE LENGTH(TRIM(CL."Producer")) > 0

    AND CL."Producer" = :1

    AND SUBSTR(CL."Status",1,1) NOT IN (''0'', ''A'', ''E'')

    AND PR."CodeType" NOT IN (2,3)

    AND T2."Status" <> 5	                                                       -- Ortho visits

		AND (''' || vMedicaidCode || ''' is null or (PR."Procedure" NOT IN ( select regexp_substr(''' || vMedicaidCode || ''',''[^,]+'', 1, level) from dual connect by regexp_substr(''' || vMedicaidCode || ''',''[^,]+'', 1, level) is not null)))

    GROUP BY TR."ChartTrx"



    -- select block 2: tx which were approved today

    UNION

    SELECT R."Code", R."Description", R."Status", R."Site", "SiteAsNumber", R."Site2", "Site2AsNumber",

    R."Surface", R."TxDate", R."LineType", R."TrxTreatme2", R."Approved",

    R."ItemKey", R."ChartLnk", R."TxHasReqConsent", R."Patient", R."PtFullName", R."PtFirstName", R."PtLastName", R."PtChart", R."PtAge", R."PtGender",

    R."RequireGrading", R."GeneralRequireGrading", R."IsOrthoNote"

    FROM

    (

      SELECT

        MIN(TRIM(PR."Procedure")) AS "Code",

        CASE WHEN TRIM(MIN(TR."Additional")) IS NULL OR MIN(PR."Prompt") = 0 THEN

          MIN(TRIM(PR."Procedure")) || '' - '' || MIN(PR."Description")

        ELSE

          MIN(TRIM(PR."Procedure")) || '' - '' || MIN(PR."Description") || '' ('' || TRIM(MIN(TR."Additional")) || '')''

        END AS "Description",

        MIN(TRIM(TR."Status")) AS "Status",

        MIN(TRIM(TR."Site")) AS "Site",

        CASE WHEN LENGTH(TRIM(TRANSLATE(MIN(NVL( TRIM(TR."Site"), ''ZZZZ'')), '' +-.0123456789'','' ''))) >= 1 THEN  MIN(NVL( TRIM(TR."Site"), ''ZZZZ'')) ELSE LPAD(MIN(TRIM(TR."Site")),''4'',''0'') END AS "SiteAsNumber",

        MAX(TRIM(TR."Site2")) AS "Site2",

        CASE WHEN LENGTH(TRIM(TRANSLATE(MAX(NVL( TRIM(TR."Site2"), ''ZZZZ'')), '' +-.0123456789'','' ''))) >= 1 THEN  MAX(NVL( TRIM(TR."Site2"), ''ZZZZ'')) ELSE LPAD(MAX(TRIM(TR."Site2")),''4'',''0'') END AS "Site2AsNumber",

        MIN(TRIM(TR."Surface")) AS "Surface",

        MIN(TO_CHAR(TR."TreatmentDate",''MON DD, YYYY'')) AS "TxDate",

        1 AS "LineType",

        TR."ChartTrx" AS "TrxTreatme2",

        1 AS "Approved",

        TR."ChartTrx" AS "ItemKey",

        0 AS "ChartLnk",

        CASE WHEN ' || vHideConsent || ' > 0 THEN

        1

        ELSE

        MAX(FPORTAL_PKG.TxHasReqConsent(TR."Type",TR."Id",TR."Treatment",TR."Patient",TR."Producer",TR."Procedure", TR."Site")) END AS "TxHasReqConsent",

        MIN(TR."Patient") AS "Patient",

        TRIM(MIN(PT."First")) || '' '' || TRIM(MIN(PT."Last")) AS "PtFullName",

        MIN(PT."First") AS "PtFirstName",

        MIN(PT."Last") AS "PtLastName",

        MIN(PT."Chart") AS "PtChart",

        TO_CHAR(FLOOR(MONTHS_BETWEEN(SYSDATE,MIN(PT."Birth")) / 12)) AS "PtAge",

        DECODE(MIN(PT."Sex"),0,''U'',1,''M'',2,''F'',3,''T'',4,''X'',5,''O'','''') AS "PtGender",

        MIN(PR."RequireGrading") AS "RequireGrading",

        FPORTAL_PKG.RequireGrading(MIN(PRD."RequireGrading"), MIN(PR."RequireGrading"), MIN(TR."Discipline") ) AS "GeneralRequireGrading",

        CASE WHEN MIN(N2."Auto") IS NULL THEN 0 ELSE 1 END AS "IsOrthoNote",

        MAX(TR."Deleted") AS "Deleted"

      FROM TRX TR

      JOIN PATIENT PT ON TR."Patient" = PT."Patient"

      JOIN PRODUCER PRD ON TR."Producer" = PRD."Producer"

      LEFT JOIN PROCEDUR PR ON TR."Procedure" = PR."Procedure"

      LEFT JOIN DISCIPL DIS ON TR."Discipline" = DIS."Class"

      LEFT JOIN NOTES2 N2 ON TR."ChartTrx" = N2."TxId" AND N2."Type" = 3

      WHERE TR."Producer" = :2

      AND TR."AppDate" = TRUNC(SYSDATE)

      AND TR."Type" IN (1,5)

      AND TR."AppUser" > 0

      AND NOT EXISTS (SELECT 1 FROM CHARTLNK CL WHERE CL."Patient" = TR."Patient" AND CL."Previous" = TR."ChartTrx")

			AND (''' || vMedicaidCode || ''' is null or (PR."Procedure" NOT IN ( select regexp_substr(''' || vMedicaidCode || ''',''[^,]+'', 1, level) from dual connect by regexp_substr(''' || vMedicaidCode || ''',''[^,]+'', 1, level) is not null)))

      GROUP BY TR."ChartTrx"

    ) R WHERE R."Deleted" = 0



    -- select block 3: unapproved planned tx

    UNION

    SELECT

      MIN(TRIM(CL."Procedure")) AS "Code",

      CASE WHEN TRIM(MIN(T2."Number")) IS NULL OR MIN(PR."Prompt") = 0 THEN

        MIN(TRIM(CL."Procedure")) || '' - '' || MIN(PR."Description")

      ELSE

        MIN(TRIM(CL."Procedure")) || '' - '' || MIN(PR."Description") || '' ('' || TRIM(MIN(T2."Number")) || '')''

      END AS "Description",

      MIN(TRIM(CL."Status")) AS "Status",

      MIN(TRIM(CL."Site")) AS "Site",

      CASE WHEN LENGTH(TRIM(TRANSLATE(MIN(NVL( TRIM(CL."Site"), ''ZZZZ'')), '' +-.0123456789'','' ''))) >= 1 THEN  MIN(NVL( TRIM(CL."Site"), ''ZZZZ'')) ELSE LPAD(MIN(TRIM(CL."Site")),''4'',''0'') END AS "SiteAsNumber",

      MAX(TRIM(CL."Site2")) AS "Site2",

      CASE WHEN LENGTH(TRIM(TRANSLATE(MAX(NVL( TRIM(CL."Site2"), ''ZZZZ'')), '' +-.0123456789'','' ''))) >= 1 THEN  MAX(NVL( TRIM(CL."Site2"), ''ZZZZ'')) ELSE LPAD(MAX(TRIM(CL."Site2")),''4'',''0'') END AS "Site2AsNumber",

      MIN(TRIM(CL."Surface")) AS "Surface",

      MIN(TO_CHAR(CL."TxDate",''MON DD, YYYY'')) AS "TxDate",

      2 AS "LineType",

      CL."Auto" AS "TrxTreatme2",

      0 AS "Approved",

      MIN(CL."Id") AS "ItemKey",

      MIN(CL."Id") AS "ChartLnk",

      1 AS "TxHasReqConsent",

      MIN(CL."Patient") AS "Patient",

      TRIM(MIN(PT."First")) || '' '' || TRIM(MIN(PT."Last")) AS "PtFullName",

      MIN(PT."First") AS "PtFirstName",

      MIN(PT."Last") AS "PtLastName",

      MIN(PT."Chart") AS "PtChart",

      TO_CHAR(FLOOR(MONTHS_BETWEEN(SYSDATE,MIN(PT."Birth")) / 12)) AS "PtAge",

      DECODE(MIN(PT."Sex"),0,''U'',1,''M'',2,''F'',3,''T'',4,''X'',5,''O'','''') AS "PtGender",

      MIN(PR."RequireGrading") AS "RequireGrading",

      FPORTAL_PKG.RequireGrading(MIN(PRD."RequireGrading"), MIN(PR."RequireGrading"), MIN(T2."Discipline") ) AS "GeneralRequireGrading",

      CASE WHEN MIN(N2."Auto") IS NULL THEN 0 ELSE 1 END AS "IsOrthoNote"

    FROM CHARTLNK CL

    JOIN TREATME2 T2 ON CL."Auto" = T2."Auto"

    JOIN USERS UR ON CL."Producer" = UR."Producer"

    JOIN PATIENT PT ON CL."Patient" = PT."Patient"

    JOIN PRODUCER PRD ON CL."Producer" = PRD."Producer"

    LEFT JOIN DISCIPL DIS ON T2."Discipline" = DIS."Class"

    LEFT JOIN PROCEDUR PR ON CL."Procedure" = PR."Procedure"

    LEFT JOIN NOTES2 N2 ON T2."Auto" = N2."TxId" AND N2."Type" = 3

    WHERE LENGTH(TRIM(CL."Producer")) > 0

    AND SUBSTR(CL."Status",1,1) NOT IN (''0'', ''A'', ''E'', ''D'')

    AND PR."CodeType" NOT IN (2,3)

    AND CL."Previous" = 0

    AND CL."Producer" = :3

    AND T2."Status" <> 5                                            -- Ortho Visits

		AND (''' || vMedicaidCode || ''' is null or (PR."Procedure" NOT IN ( select regexp_substr(''' || vMedicaidCode || ''',''[^,]+'', 1, level) from dual connect by regexp_substr(''' || vMedicaidCode || ''',''[^,]+'', 1, level) is not null)))

    GROUP BY CL."Auto"



    -- select block 4: general or template notes (approved today/unapproved)

    UNION

    SELECT

      '''' AS "Code",

      CASE

        WHEN N2."TxId" = 0 THEN ''NOTE''

        ELSE ''NOTE ('' || FPORTAL_PKG.GetProcedureCodeByTxId(N2."TxId") || '')''

      END AS "Description",

      CASE

        WHEN N2."Status" = 0 THEN NULL

        ELSE ''D''

      END AS "TxStatus",

      (SELECT SR."Value" FROM FSITEREF SR WHERE SR."Id" = N2."Site" AND SR."Country" = :4 AND ROWNUM = 1) AS "Site",

	  '''' AS "SiteAsNumber",

      '''' AS "Site2",

	  '''' AS "Site2AsNumber",

      NULL AS "Surface",

      TO_CHAR(N2."Date",''MON DD, YYYY'') AS "TxDate",

      CASE

        WHEN N2."IsTemplate" = 0 THEN 3

        WHEN N2."IsTemplate" = 1 THEN 4

        END AS "LineType",

      N2."TxId" AS "TrxTreatme2",

      CASE

        WHEN N2."AppUser" = 0 THEN 0

        ELSE 1

        END AS "Approved",

      N2."Auto" AS "ItemKey",

      0 AS "ChartLnk",

      1 AS "TxHasReqConsent",

      P2."PtxPId" AS "Patient",

      TRIM(PT."First") || '' '' || TRIM(PT."Last") AS "PtFullName",

      PT."First" AS "PtFirstName",

      PT."Last" AS "PtLastName",

      PT."Chart" AS "PtChart",

      TO_CHAR(FLOOR(MONTHS_BETWEEN(SYSDATE, PT."Birth") / 12)) AS "PtAge",

      DECODE(PT."Sex",0,''U'',1,''M'',2,''F'',3,''T'',4,''X'',5,''O'','''') AS "PtGender",

      0 AS "RequireGrading",

      0 AS "GeneralRequireGrading",

      0 AS "IsOrthoNote"

    FROM NOTES2 N2, PATIENT2 P2, PATIENT PT

    WHERE N2."PId" = P2."Auto"

    AND P2."PtxPId" = PT."Patient"

    AND N2."User" = :5

    AND N2."Type" IN (0,1)

    AND ((N2."Status" = 0) OR (N2."Status" = 1 AND N2."AppUser" = 0))

    AND ((N2."AppUser" = 0 AND N2."AppDate" IS NULL) OR (N2."AppUser" > 0  AND N2."AppDate" = TRUNC(SYSDATE)))



    -- select block 5: SOAP notes (approved today/unapproved)

    UNION

    SELECT DISTINCT

      '''' AS "Code",

      CASE

        WHEN N2."TxId" = 0 THEN ''SOAP NOTE''

        ELSE ''SOAP NOTE ('' || FPORTAL_PKG.GetProcedureCodeByTxId(N2."TxId") || '')''

      END AS "Description",

      CASE

        WHEN N2."Status" = 0  THEN NULL

        ELSE ''D''

      END AS "TxStatus",

      CASE

        WHEN N2."TxId" = 0 THEN ''''

        ELSE (SELECT SR."Value" FROM FSITEREF SR WHERE SR."Id" = N2."Site" AND SR."Country" = :6 AND ROWNUM = 1)

      END AS "Site",

	  '''' AS "SiteAsNumber",

      NULL AS "Site2",

	  '''' AS "Site2AsNumber",

      NULL AS "Surface",

      TO_CHAR(N2."Date",''MON DD, YYYY'') AS "TxDate",

      5 AS "LineType",

      N2."TxId" AS "TrxTreatme2",

      CASE

        WHEN N2."AppUser" = 0 THEN 0

        ELSE 1

      END AS "Approved",

      N2."OtherId" AS "ItemKey",

      0 AS "ChartLnk",

      1 AS "TxHasReqConsent",

      P2."PtxPId" AS "Patient",

      TRIM(PT."First") || '' '' || TRIM(PT."Last") AS "PtFullName",

      PT."First" AS "PtFirstName",

      PT."Last" AS "PtLastName",

      PT."Chart" AS "PtChart",

      TO_CHAR(FLOOR(MONTHS_BETWEEN(SYSDATE, PT."Birth") / 12)) AS "PtAge",

      DECODE(PT."Sex",0,''U'',1,''M'',2,''F'',3,''T'',4,''X'',5,''O'','''') AS "PtGender",

      0 AS "RequireGrading",

      0 AS "GeneralRequireGrading",

      0 AS "IsOrthoNote"

    FROM NOTES2 N2, PATIENT2 P2, PATIENT PT

    WHERE N2."PId" = P2."Auto"

    AND P2."PtxPId" = PT."Patient"

    AND N2."User" = :7

    AND N2."Type" = 4

    AND ((N2."Status" = 0) OR (N2."Status" = 1 AND N2."AppUser" = 0))

    AND ((N2."AppUser" = 0 AND N2."AppDate" IS NULL) OR (N2."AppUser" > 0  AND N2."AppDate" = TRUNC(SYSDATE)))



    -- select block 6: unapproved findings

    UNION

    SELECT

      MIN(TRIM(CL."Procedure")) AS "Code",

      MIN(TRIM(CL."Procedure")) || '' - '' || MIN(TRIM(PR."Description")) AS "Description",

      MIN(TRIM(CL."Status")) AS "Status",

      MIN(TRIM(CL."Site")) AS "Site",

      CASE WHEN LENGTH(TRIM(TRANSLATE(MIN(NVL( TRIM(CL."Site"), ''ZZZZ'')), '' +-.0123456789'','' ''))) >= 1 THEN  MIN(NVL( TRIM(CL."Site"), ''ZZZZ'')) ELSE LPAD(MIN(TRIM(CL."Site")),''4'',''0'') END AS "SiteAsNumber",

      MAX(TRIM(CL."Site2")) AS "Site2",

      CASE WHEN LENGTH(TRIM(TRANSLATE(MAX(NVL( TRIM(CL."Site2"), ''ZZZZ'')), '' +-.0123456789'','' ''))) >= 1 THEN  MAX(NVL( TRIM(CL."Site2"), ''ZZZZ'')) ELSE LPAD(MAX(TRIM(CL."Site2")),''4'',''0'') END AS "Site2AsNumber",

      MIN(TRIM(CL."Surface")) AS "Surface",

      MIN(TO_CHAR(CL."TxDate",''MON DD, YYYY'')) AS "TxDate",

      6 AS "LineType",

      CL."Auto" AS "TrxTreatme2",

      0 AS "Approved",

      CL."Auto" AS "ItemKey",

      MIN(CL."Id") AS "ChartLnk",

      1 AS "TxHasReqConsent",

      MIN(CL."Patient") AS "Patient",

      TRIM(MIN(PT."First")) || '' '' || TRIM(MIN(PT."Last")) AS "PtFullName",

      MIN(PT."First") AS "PtFirstName",

      MIN(PT."Last") AS "PtLastName",

      MIN(PT."Chart") AS "PtChart",

      TO_CHAR(FLOOR(MONTHS_BETWEEN(SYSDATE,MIN(PT."Birth")) / 12)) AS "PtAge",

      DECODE(MIN(PT."Sex"),0,''U'',1,''M'',2,''F'',3,''T'',4,''X'',5,''O'','''') AS "PtGender",

      0 AS "RequireGrading",

      0 AS "GeneralRequireGrading",

      0 AS "IsOrthoNote"

    FROM CHARTLNK CL, PROCEDUR PR, TREATME2 T2, PATIENT PT

    WHERE CL."Producer" = :8

    AND PR."Procedure" (+)= CL."Procedure"

    AND CL."Previous" = 0

    AND CL."Auto" = T2."Auto"

    AND CL."Patient" = PT."Patient"

    AND (CL."Status" = ''A'' OR CL."Status" = ''E'' OR CL."Status" = ''D'')

    AND T2."Status" IN (3, 4)

		AND (''' || vMedicaidCode || ''' is null or (PR."Procedure" NOT IN ( select regexp_substr(''' || vMedicaidCode || ''',''[^,]+'', 1, level) from dual connect by regexp_substr(''' || vMedicaidCode || ''',''[^,]+'', 1, level) is not null)))

    GROUP BY CL."Auto"



    -- select block 7: findings approved today

    UNION

    SELECT

      TRIM(PR."Procedure") AS "Code",

      TRIM(PR."Procedure") || '' - '' || TRIM(PR."Description") AS "Description",

      DECODE(T2."Status",3,''E'',4,''A'') AS "TxStatus",

      TRIM(T2."Site") AS "Site",

	  '''' AS "SiteAsNumber",

      TRIM("Site2") AS "Site2",

	  '''' AS "Site2AsNumber",

      FPORTAL_PKG.GetSurface(TRIM(T2."Site"),TRIM(T2."Surface")) AS "Surface",

      TO_CHAR(T2."ModifiedDateTime",''MON DD, YYYY'') AS "TxDate",

      7 AS "LineType",

      T2."Auto" AS "TrxTreatme2",

      1 AS "Approved",

      T2."Auto" AS "ItemKey",

      0 AS "ChartLnk",

      1 AS "TxHasReqConsent",

      P2."PtxPId" AS "Patient",

      TRIM(PT."First") || '' '' || TRIM(PT."Last") AS "PtFullName",

      PT."First" AS "PtFirstName",

      PT."Last" AS "PtLastName",

      PT."Chart" AS "PtChart",

      TO_CHAR(FLOOR(MONTHS_BETWEEN(SYSDATE, PT."Birth") / 12)) AS "PtAge",

      DECODE(PT."Sex",0,''U'',1,''M'',2,''F'',3,''T'',4,''X'',5,''O'','''') AS "PtGender",

      0 AS "RequireGrading",

      0 AS "GeneralRequireGrading",

      0 AS "IsOrthoNote"

    FROM TREATME2 T2, PROCEDUR PR, PATIENT2 P2, PATIENT PT

    WHERE T2."Provider" = :9

    AND P2."PtxPId" = PT."Patient"

    AND T2."CodeId" = PR."Id"

    AND T2."PId" = P2."Auto"

    AND T2."Deleted" = 0

    AND T2."AppDate" = TRUNC(SYSDATE)

    AND T2."Status" IN (3,4)

    AND NOT EXISTS (SELECT 1 FROM CHARTLNK CL WHERE CL."Auto" = T2."Auto")

		AND (''' || vMedicaidCode || ''' is null or (PR."Procedure" NOT IN ( select regexp_substr(''' || vMedicaidCode || ''',''[^,]+'', 1, level) from dual connect by regexp_substr(''' || vMedicaidCode || ''',''[^,]+'', 1, level) is not null)))



    -- select block 8: unapproved forms -- AX-23759 Remove all EF_ tables from axiUm DB



    -- select block 9: forms approved today -- AX-23759 Remove all EF_ tables from axiUm DB



		 -- select block 8.5: unapproved classic forms

	UNION

	SELECT

		TRIM(PF."FormCode") AS "Code",

		CASE WHEN F."Multiple" = 0 THEN

			TRIM(PF."FormCode") || '' - '' || TRIM(PF."Description")

		ELSE

			TRIM(PF."FormCode") || '' - '' || TRIM(PF."Description") || '' - '' || TO_CHAR(PF."CreatedDate",''MON DD, YYYY'')

		END AS "Description",

		NULL AS "TxStatus",

		NULL AS "Site",

	'''' AS "SiteAsNumber",

		NULL AS "Site2",

	'''' AS "Site2AsNumber",

		NULL AS "Surface",

		TO_CHAR(PF."Date",''MON DD, YYYY'') AS "TxDate",

		16 AS "LineType",

		0 AS "TrxTreatme2",

		0 AS "Approved",

		PF."PForm" AS "ItemKey",

		0 AS "ChartLnk",

		1 AS "TxHasReqConsent",

		PI."Patient",

		TRIM(PT."First") || '' '' || TRIM(PT."Last") AS "PtFullName",

		PT."First" AS "PtFirstName",

		PT."Last" AS "PtLastName",

		PT."Chart" AS "PtChart",

		TO_CHAR(FLOOR(MONTHS_BETWEEN(SYSDATE, PT."Birth") / 12)) AS "PtAge",

		DECODE(PT."Sex",0,''U'',1,''M'',2,''F'',3,''T'',4,''X'',5,''O'','''') AS "PtGender",

		0 AS "RequireGrading",

		0 AS "GeneralRequireGrading",

		0 AS "IsOrthoNote"

	FROM PITEM PI, PFORM PF, FORM F, PATIENT PT

	WHERE PI."PForm"    = PF."PForm"

	AND PF."FormCode" = F."Code"

	AND PI."Patient" = PT."Patient"

	AND PI."Status"     = 0

	AND PI."User" = :10					-- AX-23759

	AND PI."AppUser" = 0

	AND PI."ASAType"  = 0

	AND PF."Inactive"   = 0

	AND PF."OwnerType" != 5

	AND PF."OwnerType" != 6

	AND PF."Approved" = 0



	-- select block 9.5: classic forms approved today

	UNION

	SELECT

		TRIM(PF."FormCode") AS "Code",

		CASE WHEN F."Multiple" = 0 THEN

			TRIM(PF."FormCode") || '' '' || TRIM(PF."Description")

		ELSE

			TRIM(PF."FormCode") || '' '' || TRIM(PF."Description") || '' - '' || TO_CHAR(PF."CreatedDate",''MON DD, YYYY'')

		END AS "Description",

		NULL AS "TxStatus",

		NULL AS "Site",

	'''' AS "SiteAsNumber",

		NULL AS "Site2",

	'''' AS "Site2AsNumber",

		NULL AS "Surface",

		TO_CHAR(PF."Date",''MON DD, YYYY'') AS "TxDate",

		17 AS "LineType",

		0 AS "TrxTreatme2",

		PF."Approved",

		PF."PForm" AS "ItemKey",

		0 AS "ChartLnk",

		1 AS "TxHasReqConsent",

		PI."Patient",

		TRIM(PT."First") || '' '' || TRIM(PT."Last") AS "PtFullName",

		PT."First" AS "PtFirstName",

		PT."Last" AS "PtLastName",

		PT."Chart" AS "PtChart",

		TO_CHAR(FLOOR(MONTHS_BETWEEN(SYSDATE, PT."Birth") / 12)) AS "PtAge",

		DECODE(PT."Sex",0,''U'',1,''M'',2,''F'',3,''T'',4,''X'',5,''O'','''') AS "PtGender",

		0 AS "RequireGrading",

		0 AS "GeneralRequireGrading",

		0 AS "IsOrthoNote"

	FROM PITEM PI, PFORM PF, FORM F, PATIENT PT

	WHERE PI."PForm"    = PF."PForm"

	AND PI."Patient" = PT."Patient"

	AND PF."FormCode" = F."Code"

	AND PI."Status"     = 0

	AND PI."User" = :11						-- AX-23759

	AND PI."AppDate" = TRUNC(SYSDATE)

	AND PI."ASAType"  = 0

	AND PF."Inactive"   = 0

	AND PF."OwnerType" != 5

	AND PF."OwnerType" != 6

	AND PF."Approved" = 1

	AND PF."LastAppDate" = TRUNC(SYSDATE)





    -- select block 10: unapproved perio & perio approved today

    UNION

    SELECT

      '''' AS "Code",

      CASE WHEN P."PerExam" != '' '' THEN

        ''Perio Chart ('' || (SELECT PE."Description" FROM PEREXAM PE WHERE P."PerExam" = PE."PerExam" AND ROWNUM = 1 ) || '' - '' || TO_CHAR(P."ChartDate",''MON DD, YYYY'') || '')''

      ELSE

        ''Perio Chart ('' || TO_CHAR(P."ChartDate",''MON DD, YYYY'') || '')''

      END AS "Description",

      NULL AS "TxStatus",

      NULL AS "Site",

	  '''' AS "SiteAsNumber",

      NULL AS "Site2",

	  '''' AS "Site2AsNumber",

      NULL AS "Surface",

      TO_CHAR(P."ChartDate",''MON DD, YYYY'') AS "TxDate",

      10 AS "LineType",

      0 AS "TrxTreatme2",

      CASE

        WHEN P."AppUser" = 0 THEN 0

        ELSE 1

      END AS "Approved",

      P."PtPerio" AS "ItemKey",

      0 AS "ChartLnk",

      1 AS "TxHasReqConsent",

      P."Patient",

      TRIM(PT."First") || '' '' || TRIM(PT."Last") AS "PtFullName",

      PT."First" AS "PtFirstName",

      PT."Last" AS "PtLastName",

      PT."Chart" AS "PtChart",

      TO_CHAR(FLOOR(MONTHS_BETWEEN(SYSDATE, PT."Birth") / 12)) AS "PtAge",

      DECODE(PT."Sex",0,''U'',1,''M'',2,''F'',3,''T'',4,''X'',5,''O'','''') AS "PtGender",

      0 AS "RequireGrading",

      0 AS "GeneralRequireGrading",

      0 AS "IsOrthoNote"

    FROM PTPERIO P, AUDITHIS AH, PATIENT PT

    WHERE P."Audit" = AH."Audit"

    AND P."Patient" = PT."Patient"

    AND AH."User" = :12									-- AX-23759

    AND AH."TableName" = ''PTPERIO''

    AND P."Deleted" = 0

    AND ( P."AppUser" = 0 OR (P."AppUser" != 0 AND P."AppDate" = TRUNC(SYSDATE)))



    -- select block 11: unapproved letters

    UNION

    SELECT

      '''' AS "Code",

      ''LETTER - '' || P."Description" AS "Description",

      NULL AS "TxStatus",

      NULL AS "Site",

	  '''' AS "SiteAsNumber",

      NULL AS "Site2",

	  '''' AS "Site2AsNumber",

      NULL AS "Surface",

      TO_CHAR(P."Date",''MON DD, YYYY'') AS "TxDate",

      12 AS "LineType",

      0 AS "TrxTreatme2",

      0 AS "Approved",

      P."PtLetter" AS "ItemKey",

      0 AS "ChartLnk",

      1 AS "TxHasReqConsent",

      P."Patient",

      TRIM(PT."First") || '' '' || TRIM(PT."Last") AS "PtFullName",

      PT."First" AS "PtFirstName",

      PT."Last" AS "PtLastName",

      PT."Chart" AS "PtChart",

      TO_CHAR(FLOOR(MONTHS_BETWEEN(SYSDATE, PT."Birth") / 12)) AS "PtAge",

      DECODE(PT."Sex",0,''U'',1,''M'',2,''F'',3,''T'',4,''X'',5,''O'','''') AS "PtGender",

      0 AS "RequireGrading",

      0 AS "GeneralRequireGrading",

      0 AS "IsOrthoNote"

    FROM PTLDETAILS P, PATIENT PT						-- AX-25708

    WHERE 1=1

    AND P."Patient" = PT."Patient"

    AND P."AppUser" = 0

    AND P."Deleted" = 0

    AND P."User" = :13									-- AX-23759

    AND P."Type" = 3

    AND P."Status" = 1



    -- select block 12: letters approved today

    UNION

    SELECT

      '''' AS "Code",

      ''LETTER - '' || P."Description" AS "Description",

      NULL AS "TxStatus",

      NULL AS "Site",

	  '''' AS "SiteAsNumber",

      NULL AS "Site2",

	  '''' AS "Site2AsNumber",

      NULL AS "Surface",

      TO_CHAR(P."Date",''MON DD, YYYY'') AS "TxDate",

      13 AS "LineType",

      0 AS "TrxTreatme2",

      1 AS "Approved",

      P."PtLetter" AS "ItemKey",

      0 AS "ChartLnk",

      1 AS "TxHasReqConsent",

      P."Patient",

      TRIM(PT."First") || '' '' || TRIM(PT."Last") AS "PtFullName",

      PT."First" AS "PtFirstName",

      PT."Last" AS "PtLastName",

      PT."Chart" AS "PtChart",

      TO_CHAR(FLOOR(MONTHS_BETWEEN(SYSDATE, PT."Birth") / 12)) AS "PtAge",

      DECODE(PT."Sex",0,''U'',1,''M'',2,''F'',3,''T'',4,''X'',5,''O'','''') AS "PtGender",

      0 AS "RequireGrading",

      0 AS "GeneralRequireGrading",

      0 AS "IsOrthoNote"

    FROM PTLDETAILS P, PATIENT PT						-- AX-25708

    WHERE 1=1

    AND P."Patient" = PT."Patient"

    AND P."AppUser" != 0

    AND P."AppDate" = TRUNC(SYSDATE)

    AND P."Deleted" = 0

    AND P."User" = :14									-- AX-23759	

    AND P."Type" = 3

    AND P."Status" = 1



	-- select block 13: Ortho Visits UnApproved or Approved Today

	UNION

    SELECT

      MIN(TRIM(PR."Procedure")) AS "Code",

      ''***Ortho Visit***'' AS "Description",

      CASE WHEN MIN(T2."Deleted") = 0 THEN ''V'' ELSE ''D'' END AS "Status",                   -- 59373934 Ortho Notes

      MIN(TRIM(T2."Site")) AS "Site",

      CASE WHEN LENGTH(TRIM(TRANSLATE(MIN(NVL( TRIM(T2."Site"), ''ZZZZ'')), '' +-.0123456789'','' ''))) >= 1 THEN  MIN(NVL( TRIM(T2."Site"), ''ZZZZ'')) ELSE LPAD(MIN(TRIM(T2."Site")),''4'',''0'') END AS "SiteAsNumber",

      MIN(TRIM(T2."Site2")) AS "Site2",

      CASE WHEN LENGTH(TRIM(TRANSLATE(MAX(NVL( TRIM(T2."Site2"), ''ZZZZ'')), '' +-.0123456789'','' ''))) >= 1 THEN  MAX(NVL( TRIM(T2."Site2"), ''ZZZZ'')) ELSE LPAD(MAX(TRIM(T2."Site2")),''4'',''0'') END AS "Site2AsNumber",

      FPORTAL_PKG.GetSurface(MIN(TRIM(T2."Site")),MIN(TRIM(T2."Surface"))) AS "Surface",

      MIN(TO_CHAR(T2."ModifiedDateTime",''MON DD, YYYY'')) AS "TxDate",

      CASE WHEN MIN(T2."AppUser") = 0 THEN 14 ELSE 15 END AS "LineType",    	  	  	       -- 59373934 Ortho notes LineType 14 - Unapproved or 15 - Approved Today

      MIN(T2."Auto") AS "TrxTreatme2",

      CASE

        WHEN MIN(T2."Deleted") = 0 AND MIN(T2."AppUser") = 0 THEN 0

        WHEN MIN(T2."Deleted") = 0 AND MIN(T2."AppUser") != 0 THEN 1

        WHEN MIN(T2."Deleted") = 1 AND MIN(T2."DelAppUser") = 0 THEN 0

        WHEN MIN(T2."Deleted") = 1 AND MIN(T2."DelAppUser") != 0 THEN 1

        ELSE 0

        END AS "Approved",

      MIN(T2."Auto") AS "ItemKey",

      CASE WHEN MIN(CL."Id") > 0 THEN MIN(CL."Id") ELSE 0 END AS "ChartLnk",

      1 AS "TxHasReqConsent",

      MIN(P2."PtxPId") AS "Patient",

      MIN(TRIM(PT."First")) || '' '' || MIN(TRIM(PT."Last")) AS "PtFullName",

      MIN(PT."First") AS "PtFirstName",

      MIN(PT."Last") AS "PtLastName",

      MIN(PT."Chart") AS "PtChart",

      MIN(TO_CHAR(FLOOR(MONTHS_BETWEEN(SYSDATE, PT."Birth") / 12))) AS "PtAge",

      MIN(DECODE(PT."Sex",0,''U'',1,''M'',2,''F'',3,''T'',4,''X'',5,''O'','''')) AS "PtGender",

      MIN(PR."RequireGrading") AS "RequireGrading",

      FPORTAL_PKG.RequireGrading(MIN(PRD."RequireGrading"), MIN(PR."RequireGrading"), MIN(T2."Discipline") ) AS "GeneralRequireGrading",

      1 AS "IsOrthoNote"                                                                    -- 59373934 Ortho notes

    FROM TREATME2 T2

    JOIN PROCEDUR PR ON T2."CodeId" = PR."Id"

    JOIN PATIENT2 P2 ON T2."PId" = P2."Auto"

    JOIN PATIENT PT ON P2."PtxPId" = PT."Patient"

    JOIN PRODUCER PRD ON T2."Provider" = PRD."Producer"

    JOIN NOTES2 N2 ON T2."Auto" = N2."TxId" AND N2."Type" = 3

    LEFT JOIN CHARTLNK CL ON T2."Auto" = CL."Auto"

    WHERE T2."Provider" = :15								-- AX-23759		

    AND ((T2."AppUser" = 0 AND T2."Deleted" = 0) OR (T2."Deleted" = 1 AND T2."DelAppUser" = 0) OR (T2."Deleted" = 0 AND T2."AppUser" != 0 AND T2."AppDate" = TRUNC(SYSDATE)))

    AND T2."Status" = 5                                                                    -- 59373934 Include 5 - Ortho visits approved by axium

    GROUP BY T2."Auto"



  )';

  DBMS_OUTPUT.ENABLE (buffer_size => NULL);

  DBMS_OUTPUT.PUT_LINE(SQLStmt);



  IF vSortDir = 0 THEN

  SQLStmt := SQLStmt || ' ORDER BY "PtFullName", "Approved", "Description" ASC, "SiteAsNumber", "Site2AsNumber", "Surface" ';

  ELSIF vSortDir = 1 THEN

  SQLStmt := SQLStmt || ' ORDER BY "PtLastName", "PtFirstName", "Approved", "Description" ASC, "SiteAsNumber", "Site2AsNumber", "Surface" ';

  END IF;



  OPEN results_cur FOR SQLStmt USING vProducer, vProducer, vProducer, vCountryName, vUserId, vCountryName, vUserId, vProducer, vProducer, vUserId, vUserId, vUserId, vUserId, vUserId, vProducer;

	EXCEPTION WHEN NO_DATA_FOUND THEN

		results_cur := NULL;

END;



/**

* Procedure to generate and return the data to show in the appointment details pane of the Appointments tab.<p/>

*

* param: vApptId INPUT: Appointment ID of the appointment (APPOINT.Appointment)<p/>

* param: vApptReason OUTPUT: Appointment reason text, returned separately to preserve formatting.<p/>

* param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

*	<li>PTNAMEAGESEX - String containing the patient's name, age, and gender, formatted like F.LastName(M50).<br/>

*	<li>PTCHART - Patient's chart # (PATIENT.Chart).<br/>

*	<li>APPTCODE - Appointment code of the appointment (APPOINT.Code).<br/>

*	<li>APPTDISCIPLINE - Discipline of the appointment. (APPOINT.Discipline).<br/>

*	<li>APPTCLINIC - Name of the clinic that this appointment is in (CLINIC.Description).<br/>

*	<li>APPTCHAIR - Name of the chair that this appointment is in (CHAIR.Name).<br/>

*	<li>APPTDATE - Date of the appointment, as a string formatted MON DD YYYY (APPOINT.Date).<br/>

*	<li>APPTTIME - Time of the appointment, as a string formatted HH:MI - HH:MI.<br/>

*	<li>APPTBOOKDATE - Date the appointment was created, as a string formatted MON DD YYYY (APPOINT.CreateDate).<br/>

*	<li>APPTSTARTCHKD - Flag indicating if the appointment has been start checked or not today (0=No, 1=Yes).<br/>

*	<li>APPTSTARTCHECKUSER - User ID of the last user to start check this appointment. (USERS.User).<br/>

*	<li>APPTSTARTCHECKTIME - Time of the last start check for this appointment, in minutes from midnight.<p/>

*/

PROCEDURE getappttabdetail(IN vapptid integer, OUT vapptreason character varying, OUT results_cur cursor_pkg.weakcursor) IS

	SQLStmt  VARCHAR2(4000);



	-- appointment record

	apptInfo rec_ApptDetail;



	-- patient fields

	ptInfo rec_PatientDetail;



  -- assistant fields

  assInfo rec_UserDetail;

BEGIN

	-- get appointment details

	apptInfo := GetApptDetail( vApptId );



	IF apptInfo.ApptPK IS NOT NULL THEN

		-- get patient details

		ptInfo := GetPatientDetail( apptInfo.ApptPatient );

	END IF;



  IF NOT (TRIM(apptInfo.ApptAssistant) IS NULL OR LENGTH(TRIM(apptInfo.ApptAssistant)) = 0) THEN

    -- get assistant details

    assInfo := GetProviderDetail(apptInfo.ApptAssistant);

  END IF;





	-- return appt reason separately, as it's freetext and might have naughty characters like '

	vApptReason := apptInfo.ApptReason;



	BEGIN

		OPEN results_cur FOR

    SELECT

			apptInfo.ApptProviderUser AS "USER",

			apptInfo.ApptProvider AS "PROVIDER",

      assInfo.UPK AS "ASSID",

      assInfo.UFirst AS "ASSFIRST",

      assInfo.ULast AS "ASSLAST",

      assInfo.UName AS "ASSFULL",

      apptInfo.ApptAssistant AS "ASSCODE",

      ptInfo.PtPK AS "PTID",

      ptInfo.PtFirstInitial || '. ' || ptInfo.PtLast AS "PTFULL",

			ptInfo.PtName AS "PTNAME",

      ptInfo.PtFirst AS "PTFIRST",

      ptInfo.PtLast AS "PTLAST",

			ptInfo.PtAgeSex AS "PTAGESEX",

			ptInfo.PtChart AS "PTCHART",

			apptInfo.ApptCode AS "APPTCODE",

			apptInfo.ApptDiscipline AS "APPTDISCIPLINE",

			apptInfo.ApptClinic AS "APPTCLINIC",

			apptInfo.ApptClinicStartChkMethod AS "APPTCLINICSTARTCHKMETHOD",

			apptInfo.ApptChairId AS "APPTCHAIRID",

			apptInfo.ApptChair AS "APPTCHAIR",

			apptInfo.ApptDate AS "APPTDATE",

			apptInfo.ApptTime AS "APPTTIME",

			apptInfo.ApptBookDate AS "APPTBOOKDATE",

      DECODE(apptInfo.ApptConfirm,

            0, 'No',

            1, 'Yes',

            'No'

      ) AS "APPTCONFIRMED",

      DECODE(apptInfo.ApptType,

            0,'Active',

            1,'Checked In',

            2,'Checked Out',

            3,'Pending',

            4,'Rescheduled',

            5,'Failed',

            6,'Cancelled',

            7,'Deleted',

            8,'Requested',

            9,'Ortho',

            10,'Planned',

            NULL

      ) AS "APPTTYPE",

			NVL(apptInfo.ApptStartChecked,0) AS "APPTSTARTCHKD",

			NVL(apptInfo.ApptStartCheckUser,0) AS "APPTSTARTCHECKUSER",

			NVL(apptInfo.ApptStartCheckTime,0) AS "APPTSTARTCHECKTIME",

      NVL(apptInfo.ApptRequiresStartChk,0) AS "APPTREQUIRESSTARTCHK",

      NVL(apptInfo.ApptPtRequiresStartChk,0) AS "APPTPTREQUIRESSTARTCHK",

      NVL(apptInfo.ApptIsOrtho, 0) AS "APPTISORTHO",

      apptInfo.ApptOrthoStage AS "APPTORTHOSTAGE",

      apptInfo.ApptOrthoStageDesc AS "APPTORTHOSTAGEDESC"

		FROM DUAL;



	EXCEPTION WHEN NO_DATA_FOUND THEN

		results_cur := NULL;

	END;



END;





/**

* Procedure that returns the data to show in the provider details pane of the Providers subtabs, and Messages tab.<p/>

*

* param: vUserId INPUT: User ID of the provider/user (USERS.User)<p/>

* param: vApptReason OUTPUT: Appointment reason code for the providers next/current/prev appointment, if any (APPOINT.Reason).<p/>

* param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

*	<li>ISPROVIDER - Flag indicating if this user is also a provider (0=no, 1=yes).<br/>

* 	<li>STATION - Name of the station that this user is currently logged in on, if any (LOG.Terminal).<br/>

* 	<li>PROVIDERID - Provider ID of the provider (PRODUCER.Producer).<br/>

* 	<li>PROVIDERTYPE - Text description of the provider's type (PRODTYPE.Description).<br/>

* 	<li>PROVIDERGROUP - Provider group of the provider (PRODUCER.PGroup).<br/>

* 	<li>PROVIDERYEAR - Year of the provider (PRODUCER.Year).<br/>

* 	<li>APPTTYPE - Flag indicating if the appointment info being shown is that of the next, current, or previous appt (-1 = no appointment found, 0 = current, 1 = next, 2 = previous).<br/>

* 	<li>PTNAMEAGESEX - String containing the patient's name, age, and gender, formatted like F.LastName(M50).<br/>

* 	<li>PTCHART - Patient's chart # (PATIENT.Chart).<br/>

* 	<li>APPTCODE - Appointment code of the appointment (APPOINT.Code).<br/>

*	<li>APPTDISCIPLINE - Discipline of the appointment. (APPOINT.Discipline).<br/>

*	<li>APPTCLINIC - Name of the clinic that this appointment is in (CLINIC.Description).<br/>

*	<li>APPTCHAIR - Name of the chair that this appointment is in (CHAIR.Name).<br/>

*	<li>APPTDATE - Date of the appointment, as a string formatted MON DD YYYY (APPOINT.Date).<br/>

*	<li>APPTTIME - Time of the appointment, as a string formatted HH:MI - HH:MI.<br/>

* 	<li>APPTBOOKDATE - Date the appointment was created, as a string formatted MON DD YYYY (APPOINT.CreateDate).<p/>

*/

PROCEDURE getprovtabdetail(IN vuserid integer, OUT vapptreason character varying, OUT results_cur cursor_pkg.weakcursor) IS

	SQLStmt  VARCHAR2(4000);



	-- appointment record

	apptInfo rec_ApptDetail;



	-- patient fields

	ptInfo rec_PatientDetail;



	-- user fields

	userInfo rec_UserDetail;



	-- station

	Station  VARCHAR2(128);



	-- next/current/planned

	vApptType INTEGER;

	vApptId INTEGER;

BEGIN

	-- get user details

	userInfo := GetUserDetail( vUserId );



	IF userInfo.UPK IS NOT NULL THEN



		-- if they are a producer, check if they have an appt

		IF userInfo.UIsProvider = 1 THEN

			GetCurrentApptLoc( vUserId, vApptType, vApptId );

			IF vApptType != -1 THEN



				-- get appointment details

				apptInfo := GetApptDetail( vApptId );



				IF apptInfo.ApptPK IS NOT NULL THEN



					-- get patient details

					ptInfo := GetPatientDetail( apptInfo.ApptPatient );

				END IF;

			END IF;

		END IF;



		-- get the login station

		GetCurrentStnLoc( vUserId, Station );



		-- return appt reason separately

		vApptReason := apptInfo.ApptReason;



		BEGIN

			--OPEN results_cur FOR SQLStmt;

      OPEN results_cur FOR

      SELECT

        userInfo.UIsProvider AS "ISPROVIDER",

        Station AS "STATION",

        userInfo.UProviderId AS "PROVIDERID",

        userInfo.UFirst AS "PROVIDERFIRST",

        userInfo.ULast AS "PROVIDERLAST",

				userInfo.UProviderTypeDesc AS "PROVIDERTYPE",

				userInfo.UProviderGroup AS "PROVIDERGROUP",

				userInfo.UProviderYear AS "PROVIDERYEAR",

        userInfo.URequireGrading AS "PROVIDERREQUIREGRADING",

				NVL(vApptType,-1) AS "APPTTYPE",

        ptInfo.PtPK AS "PTID",

				ptInfo.PtName AS "PTNAME",

        ptInfo.PtFirst AS "PTFIRST",

        ptInfo.PtLast AS "PTLAST",

				ptInfo.PtAgeSex AS "PTAGESEX",

				ptInfo.PtChart AS "PTCHART",

				apptInfo.ApptCode AS "APPTCODE",

				apptInfo.ApptDiscipline AS "APPTDISCIPLINE",

				apptInfo.ApptClinic AS "APPTCLINIC",

                apptInfo.ApptChairId AS "APPTCHAIRID",

				apptInfo.ApptChair AS "APPTCHAIR",

				apptInfo.ApptDate AS "APPTDATE",

				apptInfo.ApptTime AS "APPTTIME",

				apptInfo.ApptBookDate AS "APPTBOOKDATE",

        NVL(apptInfo.ApptIsOrtho, 0) AS "APPTISORTHO",

        apptInfo.ApptOrthoStage AS "APPTORTHOSTAGE",

        apptInfo.ApptOrthoStageDesc AS "APPTORTHOSTAGEDESC"

        FROM DUAL;





		EXCEPTION WHEN NO_DATA_FOUND THEN

			results_cur := NULL;

		END;

	ELSE

		results_cur := NULL;

	END IF;

END;



/**

* Procedure that returns the data to show in the provider details pane of the Providers subtabs.<p/>

*

* param: vProdId INPUT: ID of the producer/user (Producer.Producer)<p/>

* param: results_cur OUTPUT: Weak cursor to contain the data retrieved<br/>

*/

PROCEDURE getprodtabdetail(IN vprodid character varying, OUT results_cur cursor_pkg.weakcursor) IS

	-- user fields

	userInfo rec_UserDetail;

BEGIN

	-- get user details

	userInfo := GetProviderDetail( vProdId );



    BEGIN

      --OPEN results_cur FOR SQLStmt;

      OPEN results_cur FOR

      SELECT

        userInfo.UIsProvider AS "ISPROVIDER",

        NULL AS "STATION",

        userInfo.UProviderId AS "PROVIDERID",

        userInfo.UFirst AS "PROVIDERFIRST",

        userInfo.ULast AS "PROVIDERLAST",

        userInfo.UProviderTypeDesc AS "PROVIDERTYPE",

        userInfo.UProviderGroup AS "PROVIDERGROUP",

        userInfo.UProviderYear AS "PROVIDERYEAR",

        userInfo.URequireGrading AS "PROVIDERREQUIREGRADING",

		userInfo.UInactive AS "PROVIDERINACTIVE"

        FROM DUAL;



		EXCEPTION WHEN NO_DATA_FOUND THEN

			results_cur := NULL;

    END;

END;



FUNCTION getapptrequirestartcheck(vappoint integer) RETURN integer IS

	vRequireStartCheck INTEGER;

BEGIN



	SELECT

		CASE

		WHEN

		(

			(

				SELECT COUNT(1)

				FROM PTTYPES PT

				WHERE PT."Patient" = AP."Patient"

				AND PT."Deleted" = 0

			) > 0

			AND (

				SELECT COUNT(1)

				FROM PTTYPES PT, PATTYPE PTC

				WHERE PT."Patient" = AP."Patient"

				AND PT."Deleted" = 0

				AND PT."PatType" = PTC."PatType"

				AND PTC."StartChkRequired" = 1

			) = 0

		) OR SCHED_PKG.RequiresStartChk(AP."Appointment") = 0 THEN 0



		WHEN CL."StartChkMethod" = 1 THEN PR."RequireStartCheck"

		WHEN CL."StartChkMethod" = 2 AND (PR."RequireStartCheck" = 1 OR PR2."RequireStartCheck" = 1) THEN 1

		ELSE 0

		END INTO vRequireStartCheck

	FROM APPOINT AP

	JOIN CLINIC CL ON CL."Clinic" = AP."Clinic"

	JOIN PRODUCER PR ON PR."Producer" = AP."Producer"

	LEFT JOIN PRODUCER PR2 ON PR2."Producer" = AP."Assistant" AND NOT (TRIM(AP."Assistant") IS NULL OR LENGTH(TRIM(AP."Assistant")) = 0)

	WHERE AP."Appointment" = vAppoint;



	RETURN vRequireStartCheck;

END;



/**

* Function to count the number of treatments on an appointment.<p/>

*

* param: vAppoint INPUT: Appointment ID of the appointment (APPOINT.Appointment)<br/>

* return: Count of the number of treatments on the appointment.<br/>

*/

FUNCTION getappttrxcount(vappoint integer) RETURN integer IS

	vTrxCount INTEGER;

BEGIN

	BEGIN

    SELECT COUNT( DISTINCT TR."ChartTrx")

    INTO vTrxCount

    FROM APPTRX APT, TRX TR, CHARTLNK CL

    WHERE APT."Appointment" = vAppoint

    AND CL."Patient" = TR."Patient"

    AND DECODE(CL."Previous",0,NULL,CL."Previous") = TR."ChartTrx"

    AND

    (

      (APT."Type" = TR."Type" AND APT."Id" = TR."Id" AND APT."Treatment" = TR."Treatment")

      OR

      (TR."OrigRecNo" = ( SELECT TR2."OrigRecNo"

                          FROM TRX TR2

                          WHERE APT."Type" = TR2."Type"

                          AND APT."Id" = TR2."Id"

                          AND APT."Treatment" = TR2."Treatment"

                          AND TR2."Deleted" = 2)

      )

    );



	EXCEPTION WHEN NO_DATA_FOUND THEN

		vTrxCount := 0;

	END;



	RETURN vTrxCount;

END;



/**

* Function to count the number of ortho visit on an appointment.<p/>

*

* param: vAppoint INPUT: Appointment ID of the appointment (APPOINT.Appointment)<br/>

* return: Count of the number of ortho visits on the appointment.<br/>

*/

FUNCTION getapptorthovisitcount(vappoint integer) RETURN integer IS

  vOrthoCount INTEGER;

  vDays INTEGER;

BEGIN



  BEGIN

    SELECT CALCULATEDAYSDIFF_S(TRUNC(SYSDATE), TO_DATE('01-JAN-1901', 'DD-MON-YYYY')) INTO vDays FROM DUAL; -- AX39652

  END;



  vOrthoCount := 0;



  BEGIN

    SELECT COUNT(1) INTO vOrthoCount

      FROM APPOINT AP

      JOIN TREATME2 T2 ON AP."Producer" = T2."Provider" OR AP."Assistant" = T2."Provider"

      JOIN PATIENT2 P2 ON T2."PId" = P2."Auto"

      JOIN PATIENT PT ON P2."PtxPId" = PT."Patient" AND PT."Patient" = AP."Patient"

      JOIN PROCEDUR PR ON T2."CodeId" = PR."Id"

      JOIN PRODUCER PRD ON T2."Provider" = PRD."Producer"

      LEFT JOIN CHARTLNK CL ON T2."Auto" = CL."Auto"

      WHERE AP."Appointment" = vAppoint

      AND ((T2."Deleted" = 0 AND T2."AppUser" = 0) OR (T2."Deleted" = 1 AND T2."DelAppUser" = 0))

      AND T2."Status" = 5

      AND T2."Days" = vDays;

  END;



	RETURN vOrthoCount;

END;







/**

* Function to count the number of ortho visit notes that are attached to ortho visits on an appointment.<p/>

*

* param: vAppoint INPUT: Appointment ID of the appointment (APPOINT.Appointment)<br/>

* return: Count of the number of ortho visit notes attached to ortho visits on the appointment.<br/>

*/

FUNCTION getapptorthovisitnotecount(vappoint integer) RETURN integer IS

  vNoteCount INTEGER;

  vDays INTEGER;

BEGIN



  BEGIN

    SELECT CALCULATEDAYSDIFF_S(TRUNC(SYSDATE), TO_DATE('01-JAN-1901', 'DD-MON-YYYY')) INTO vDays FROM DUAL; -- AX39652

  END;



  vNoteCount := 0;



  SELECT

    COUNT(1) INTO vNoteCount

      FROM APPOINT AP

      JOIN TREATME2 T2 ON AP."Producer" = T2."Provider" OR AP."Assistant" = T2."Provider"

      JOIN PATIENT2 P2 ON T2."PId" = P2."Auto" AND P2."PtxPId" = AP."Patient"

      JOIN NOTES2 N2 ON N2."TxId" = T2."Auto"

      LEFT JOIN CHARTLNK CL ON T2."Auto" = CL."Auto"

      WHERE AP."Appointment" = vAppoint

      AND ((T2."AppUser" = 0 AND T2."Deleted" = 0) OR (T2."Deleted" = 1 AND T2."DelAppUser" = 0) OR (T2."Deleted" = 0 AND T2."AppUser" != 0 AND T2."AppDate" = TRUNC(SYSDATE)))

      AND T2."Status" = 5

      AND T2."Days" = vDays

      AND N2."Type" IN (1,4)

      AND ( N2."Status" = 0 OR (N2."Status" = 1 AND N2."AppUser" = 0))

      AND N2."SectionNo" = 0

      AND N2."AppUser" = 0;



	RETURN vNoteCount;

END;



/**

* Procedure to retrieve the names of the custom fields defined for treatments and notes via Maint -> Basic -> Custom Fields.<p/>

*

* param: vName1 OUTPUT: Name of the the Treatment(Clinical1) field.<p/>

* param: vName2 OUTPUT: Name of the the Treatment(Clinical2) field.<p/>

* param: vName3 OUTPUT: Name of the the Treatment/Note1 field.<p/>

* param: vName4 OUTPUT: Name of the the Treatment/Note2 field.<p/>

*/

PROCEDURE getcustomfieldnames(OUT vname1 character, OUT vname2 character, OUT vname3 character, OUT vname4 character) IS

BEGIN

	-- get custom field names

	BEGIN

		SELECT "Description"

		INTO vName1

		FROM CUSTTYPE

		WHERE "Type" = 10;

	EXCEPTION WHEN NO_DATA_FOUND THEN

		vName1 := NULL;

	END;



	BEGIN

		SELECT "Description"

		INTO vName2

		FROM CUSTTYPE

		WHERE "Type" = 11;

	EXCEPTION WHEN NO_DATA_FOUND THEN

		vName2 := NULL;

	END;



	BEGIN

		SELECT "Description"

		INTO vName3

		FROM CUSTTYPE

		WHERE "Type" = 22;

	EXCEPTION WHEN NO_DATA_FOUND THEN

		vName3 := NULL;

	END;



	BEGIN

		SELECT "Description"

		INTO vName4

		FROM CUSTTYPE

		WHERE "Type" = 23;

	EXCEPTION WHEN NO_DATA_FOUND THEN

		vName4 := NULL;

	END;

END;



/**

* Procedure to retrieve the ValidateField and RequiredField of the custom fields defined for treatments and notes via Maint -> Basic -> Custom Fields.<p/>

*

* param: vType INPUT: Type Id field.<p/>

* param: vValidate OUTPUT: Validatefield field.<p/>

* param: vRequiredField OUTPUT: vRequiredField field.<p/>

*/

PROCEDURE getcustomvalidaterequired(IN vtype integer, OUT results_cur cursor_pkg.weakcursor) IS

	SQLStmt  VARCHAR2(4000);

BEGIN

	SQLStmt := '

		SELECT "Validatefield", "RequiredField"

		FROM CUSTTYPE

		WHERE "Type" = :1

	';

  OPEN results_cur FOR SQLStmt USING vType;

  EXCEPTION WHEN NO_DATA_FOUND THEN

		results_cur := null;

END;





/**

* Procedure to retrieve the custom codes for a specific vType.<p/>

*

* param: vType INPUT: Type Id field.<p/>

* param: results_cur OUTPUT: Weak cursor to contain the data retrieved.</p>

*/

PROCEDURE getcustomcodes(IN vtype integer, OUT results_cur cursor_pkg.weakcursor) IS

	SQLStmt  VARCHAR2(4000);

BEGIN

	SQLStmt :=

		'

		SELECT "Code", "Description"

		FROM CUSTCODE

		WHERE "Type" = :1 and "Inactive" != 1

		ORDER BY "Type", "Code"

		';

	OPEN results_cur FOR SQLStmt USING vType;

	EXCEPTION WHEN NO_DATA_FOUND THEN

		results_cur := null;

END;



/**

* Function to retrieve data about a particular treatment and return it as a rec_TxDetail RECORD type.<p/>

*

* param: vChartTrx INPUT: ID for the CHARTLNK row associated with this treatment (unapproved = CHARTLNK.Previous, approved = TRX.ChartTrx)<p/>

* param: vType INPUT: Flag indicating if this treatment is approved or not approved (0=not approved, 1=approved, 2=not-approved planned)<p/>

* return: rec_TxDetail record containing the treatment data.<p/>

*/

FUNCTION gettreatmentdetail(vcharttrx integer, vchartlnk integer, vtype integer) RETURN rec_txdetail IS

  txInfo rec_TxDetail;

  vTxCount INTEGER;

  vEvalCount INTEGER;

  vNoteAuto INTEGER;



  vTxType INTEGER := 0;

  vTxId INTEGER := 0;

  vTxTreatment INTEGER := 0;

  vOrigRecNo INTEGER := 0;



  CURSOR curNoteOvr(vAuto INTEGER) IS

    SELECT * FROM NOTEOVR

    WHERE "ParentId" = vAuto

    AND "Deleted" = 0

    ORDER BY "Order" ASC;

  vNoteOvrRecord NOTEOVR%ROWTYPE;



BEGIN

  BEGIN

    SELECT COUNT(*) INTO vTxCount FROM CHARTLNK CL

    WHERE CL."Auto" = (SELECT CL2."Auto" FROM CHARTLNK CL2 WHERE CL2."Id" = vChartLnk AND ROWNUM = 1);

  END;

  IF vType = 0 THEN -- unapproved tx, use chartlnk version

    BEGIN

      SELECT DISTINCT

        vChartTrx,

        vType,

        CL."Id",

        CASE WHEN CL."Previous" IS NOT NULL AND CL."Previous" <> 0 THEN

          (SELECT TR."Id" FROM TRX TR WHERE TR."ChartTrx" = CL."Previous" AND ROWNUM = 1)

        ELSE

          0

        END AS "TxId",

        TRIM(CL."Discipline"),

        '' AS "DiagCode", --TRIM(CL."DiagCode"),

        CL."PlanPhase",

        CL."PlanSeq",

        TRIM(CL."Custom1"),

        TRIM(CL."Custom2"),

        TRIM(CL."Custom3"),

        TRIM(CL."Custom4"),

        CL."Patient",

        CL."User",

        TO_CHAR(TM."AddDateTime",'MON DD, YYYY'),

        NULL,

        NULL,

        TO_CHAR(CL."TxDate",'MON DD, YYYY'),

        TRIM(CL."Procedure"),

        CASE WHEN (TRIM(TM."Number") IS NULL OR LENGTH(TRIM(TM."Number")) = 0) OR PR."Prompt" = 0 THEN

          PR."Description"

        ELSE

          PR."Description" || ' (' || TRIM(TM."Number") || ')'

        END AS "Description",

        TRIM(CL."Status"),

        CASE WHEN vTxCount = 2 OR (TRIM(CL."Site2") IS NULL OR LENGTH(TRIM(CL."Site2")) = 0) THEN

          TRIM(CL."Site")

        ELSE

          TRIM(CL."Site") || ', ' || TRIM(CL."Site2")

        END,

        TRIM(CL."Surface"),

        CL."Producer",

        N2."Text",

        N2."Auto",

        G."Grading",

        TO_CHAR(G."CreateDate",'MON DD, YYYY'),

        G."Instructor",

        G."Template",

        TR."Type",

        TR."Id",

        TR."Treatment",

        CASE WHEN (SELECT COUNT(1) FROM NOTES2 WHERE NOTES2."TxId" = TM."Auto" AND NOTES2."Type" = 3) > 0 THEN

          1

        ELSE

          0

        END

      INTO txInfo.TxChartTrx, txInfo.TxType, txInfo.TxChartId, txInfo.TxId, txInfo.TxDiscipline, txInfo.TxDiagnosis, txInfo.TxPhase, txInfo.TxSequence,

           txInfo.TxCustomVal1, txInfo.TxCustomVal2, txInfo.TxCustomVal3,

           txInfo.TxCustomVal4, txInfo.TxPatientId, txInfo.TxEntryUser, txInfo.TxEntryDate, txInfo.TxAppUser, txInfo.TxAppDate, txInfo.TxDate,

           txInfo.TxProcCode, txInfo.TxProcDesc, txInfo.TxStatus, txInfo.TxSite, txInfo.TxSurface, txInfo.TxProducer, txInfo.TxOrthoNote, vNoteAuto,

           txInfo.TxGrading, txInfo.TxEvalDate, txInfo.TxEvalUser, txInfo.TxEvalForm, vTxType, vTxId, vTxTreatment, txInfo.TxIsOrthoTreatment

      FROM CHARTLNK CL

      JOIN TRX TR ON TR."ChartTrx" = DECODE(CL."Previous", 0, NULL, CL."Previous")

      JOIN PROCEDUR PR ON CL."Procedure" = PR."Procedure"

      JOIN TREATME2 TM ON CL."Auto" = TM."Auto"

      LEFT JOIN NOTES2 N2 ON TM."Auto" = N2."TxId" AND N2."Type" = 3

      LEFT JOIN GRADING G ON TR."Grading" = G."Grading" AND G."Deleted" = 0

      WHERE CL."Previous" = vChartTrx

      AND CL."Id" = vChartLnk

      AND ROWNUM = 1;



      IF vNoteAuto != 0 THEN

        FOR vNoteOvrRecord IN curNoteOvr(vNoteAuto) LOOP

          txInfo.TxOrthoNote := txInfo.TxOrthoNote || vNoteOvrRecord."Text";

        END LOOP;

      END IF;



      EXCEPTION WHEN NO_DATA_FOUND THEN

        txInfo := NULL;

    END;



  ELSIF vType = 1 THEN -- approved tx, use trx version

    BEGIN

      SELECT DISTINCT

        vChartTrx,

        vType,

        NULL,

        TR."Id",

        TRIM(TR."Discipline"),

        '' AS "DiagCode", --TRIM(TR."DiagCode"),

        TR."Phase",

        TR."Seq",

        TRIM(TR."Custom1"),

        TRIM(TR."Custom2"),

        TRIM(TR."Custom3"),

        TRIM(TR."Custom4"),

        TR."Patient",

        TR."EntryUser",

        TO_CHAR(TR."ModifiedDate",'MON DD, YYYY'),

        TR."AppUser",

        TO_CHAR(TR."AppDate",'MON DD, YYYY'),

        TO_CHAR(TR."Date",'MON DD, YYYY'),

        TRIM(TR."Procedure"),

        CASE WHEN (TRIM(TR."Additional") IS NULL OR LENGTH(TRIM(TR."Additional")) = 0) OR PR."Prompt" = 0 THEN

          PR."Description"

        ELSE

          PR."Description" || ' (' || TRIM(TR."Additional") || ')'

        END AS "Description",

        TRIM(TR."Status") || DECODE((SELECT "MakeInactive" FROM STATUS ST WHERE ST."Status" = TR."TxStatus" AND ST."Type" = 3),0,'',1,'*'),

        TRIM(TR."Site"),

        TRIM(TR."Surface"),

        TR."Producer",

        N2."Text",

        N2."Auto",

        G."Grading",

        TO_CHAR(G."CreateDate",'MON DD, YYYY'),

        G."Instructor",

        G."Template",

        TR."Type",

        TR."Id",

        TR."Treatment",

        CASE WHEN (SELECT COUNT(1) FROM NOTES2 WHERE NOTES2."TxId" = TR."ChartTrx" AND NOTES2."Type" = 3) > 0 THEN

          1

        ELSE

          0

        END

      INTO txInfo.TxChartTrx, txInfo.TxType,

           txInfo.TxChartId, txInfo.TxId, txInfo.TxDiscipline, txInfo.TxDiagnosis, txInfo.TxPhase, txInfo.TxSequence,

           txInfo.TxCustomVal1, txInfo.TxCustomVal2, txInfo.TxCustomVal3, txInfo.TxCustomVal4,

           txInfo.TxPatientId, txInfo.TxEntryUser, txInfo.TxEntryDate, txInfo.TxAppUser, txInfo.TxAppDate, txInfo.TxDate,

           txInfo.TxProcCode, txInfo.TxProcDesc, txInfo.TxStatus, txInfo.TxSite, txInfo.TxSurface, txInfo.TxProducer, txInfo.TxOrthoNote, vNoteAuto,

           txInfo.TxGrading, txInfo.TxEvalDate, txInfo.TxEvalUser, txInfo.TxEvalForm, vTxType, vTxId, vTxTreatment, txInfo.TxIsOrthoTreatment

      FROM TRX TR

      LEFT JOIN PROCEDUR PR ON TR."Procedure" = PR."Procedure"

      LEFT JOIN NOTES2 N2 ON TR."ChartTrx" = N2."TxId" AND N2."Type" = 3

      LEFT JOIN GRADING G ON TR."Grading" = G."Grading" AND G."Deleted" = 0

      WHERE TR."ChartTrx" = vChartTrx

      AND ROWNUM = 1;



      IF vNoteAuto != 0 THEN

        FOR vNoteOvrRecord IN curNoteOvr(vNoteAuto) LOOP

          txInfo.TxOrthoNote := txInfo.TxOrthoNote || vNoteOvrRecord."Text";

        END LOOP;

      END IF;



      EXCEPTION WHEN NO_DATA_FOUND THEN

        txInfo := NULL;

      END;



  ELSIF vType = 2 THEN -- planned unapproved tx, use chartlnk version

    BEGIN

      SELECT DISTINCT

        vChartTrx,

        vType,

        CL."Id",

        TRIM(CL."Discipline"),

        '' AS "DiagCode", --TRIM(CL."DiagCode"),

        CL."PlanPhase",

        CL."PlanSeq",

        TRIM(CL."Custom1"),

        TRIM(CL."Custom2"),

        TRIM(CL."Custom3"),

        TRIM(CL."Custom4"),

        CL."Patient",

        CL."User",

        TO_CHAR(TM."AddDateTime",'MON DD, YYYY'),

        NULL,

        NULL,

        TO_CHAR(CL."TxDate",'MON DD, YYYY'),

        TRIM(CL."Procedure"),

        CASE WHEN (TRIM(TM."Number") IS NULL OR LENGTH(TRIM(TM."Number")) = 0) OR PR."Prompt" = 0 THEN

          PR."Description"

        ELSE

          PR."Description" || ' (' || TRIM(TM."Number") || ')'

        END AS "Description",

        TRIM(CL."Status"),

        CASE WHEN vTxCount = 2 OR (TRIM(CL."Site2") IS NULL OR LENGTH(TRIM(CL."Site2")) = 0) THEN

          TRIM(CL."Site")

        ELSE

          TRIM(CL."Site") || ', ' || TRIM(CL."Site2")

        END,

        TRIM(CL."Surface"),

        CL."Producer",

        N2."Text",

        N2."Auto",

        CASE WHEN (SELECT COUNT(1) FROM NOTES2 WHERE NOTES2."TxId" = TM."Auto" AND NOTES2."Type" = 3) > 0 THEN

          1

        ELSE

          0

        END

      INTO txInfo.TxChartTrx, txInfo.TxType, txInfo.TxChartId, txInfo.TxDiscipline, txInfo.TxDiagnosis, txInfo.TxPhase, txInfo.TxSequence,

           txInfo.TxCustomVal1, txInfo.TxCustomVal2, txInfo.TxCustomVal3, txInfo.TxCustomVal4,

           txInfo.TxPatientId, txInfo.TxEntryUser, txInfo.TxEntryDate, txInfo.TxAppUser, txInfo.TxAppDate, txInfo.TxDate,

           txInfo.TxProcCode, txInfo.TxProcDesc, txInfo.TxStatus, txInfo.TxSite, txInfo.TxSurface, txInfo.TxProducer, txInfo.TxOrthoNote, vNoteAuto, txInfo.TxIsOrthoTreatment

      FROM CHARTLNK CL

      JOIN PROCEDUR PR ON CL."Procedure" = PR."Procedure"

      JOIN TREATME2 TM ON CL."Auto" = TM."Auto"

      LEFT JOIN NOTES2 N2 ON TM."Auto" = N2."TxId" AND N2."Type" = 3

      WHERE CL."Id" = vChartLnk

      AND ROWNUM = 1;



      IF vNoteAuto != 0 THEN

        FOR vNoteOvrRecord IN curNoteOvr(vNoteAuto) LOOP

          txInfo.TxOrthoNote := txInfo.TxOrthoNote || vNoteOvrRecord."Text";

        END LOOP;

      END IF;



      EXCEPTION WHEN NO_DATA_FOUND THEN

        txInfo := NULL;

    END;

  END IF;



  IF (txInfo.TxGrading = 0 OR txInfo.TxGrading IS NULL) AND vTxType != 0 AND vTxId != 0 AND vTxTreatment != 0 THEN

    BEGIN

      SELECT "OrigRecNo"

      INTO vOrigRecNo

      FROM TRX

      WHERE "Type" = vTxType

      AND "Id" = vTxId

      AND "Treatment" = vTxTreatment

      AND ROWNUM = 1;



      IF vOrigRecNo != 0 THEN

        BEGIN

          SELECT COUNT(1)

          INTO vEvalCount

          FROM TRXGRADE TG

          JOIN GRADING G ON TG."Grading" = G."Grading"

          JOIN TRX TR ON TG."Type" = TR."Type" AND TG."Id" = TR."Id" AND TG."Treatment" = TR."Treatment"

          WHERE TR."OrigRecNo" = vOrigRecNo

          AND G."Deleted" <> 1;



          IF vEvalCount > 0 THEN

            BEGIN

              SELECT R."Grading", R."CreateDate", R."Instructor", R."Template"

              INTO txInfo.TxGrading, txInfo.TxEvalDate, txInfo.TxEvalUser, txInfo.TxEvalForm

              FROM

              (

                SELECT

                  G."Grading",

                  TO_CHAR(G."CreateDate",'MON DD, YYYY') AS "CreateDate",

                  G."Instructor",

                  G."Template"

                FROM TRXGRADE TG

                JOIN GRADING G ON TG."Grading" = G."Grading"

                JOIN TRX TR ON TG."Type" = TR."Type" AND TG."Id" = TR."Id" AND TG."Treatment" = TR."Treatment"

                WHERE TR."OrigRecNo" = vOrigRecNo

                AND G."Deleted" <> 1

                ORDER BY G."CreateDate" DESC

              ) R

              WHERE ROWNUM = 1;

            END;

          END IF;

        END;

      END IF;

    END;

  END IF;



  RETURN txInfo;

END;





/**

* Function to retrieve data about a particular note (general or template) and return it as a rec_NoteDetail RECORD type.<p/>

*

* param: vAuto INPUT: ID for the note (NOTES2.Auto).<p/>

* param: vCountryName INPUT: Name of country.<p/>

* return: rec_NoteDetail record containing the note data.<p/>

*/

FUNCTION getnotedetail(vauto integer, vcountryname character varying) RETURN rec_notedetail IS

	noteInfo rec_NoteDetail;



  CURSOR vNoteOvrRecords IS

    SELECT * FROM NOTEOVR

    WHERE "ParentId" = vAuto

    AND "Deleted" = 0

    ORDER BY "Order" ASC;

  vNoteOvrRecord NOTEOVR%ROWTYPE;

BEGIN

	BEGIN

		SELECT

			N2."Auto",

			TRIM(N2."Phase"),

			TRIM(N2."Seq"),

			TRIM(N2."Custom1"),

			TRIM(N2."Custom2"),

			TRIM(N2."Code"),

			TRIM(N2."Text"),

			P2."PtxPId",

			N2."User",

			TO_CHAR(N2."ModifiedDateTime",'MON DD, YYYY'),

			N2."AppUser",

			TO_CHAR(N2."AppDate",'MON DD, YYYY'),

			N2."TxId",

			CASE

        WHEN N2."TxId" = 0 THEN 'NOTE'

        ELSE 'NOTE (' || FPORTAL_PKG.GetProcedureCodeByTxId(N2."TxId") || ')'

      END AS "Description",

      (SELECT SR."Value" FROM FSITEREF SR WHERE SR."Id" = N2."Site" AND SR."Country" = vCountryName AND ROWNUM = 1),

      CASE

          WHEN N2."Status" = 0 THEN NULL

          ELSE 'D'

      END AS "Status"

		INTO noteInfo.NtAuto, noteInfo.NtPhase, noteInfo.NtSequence, noteInfo.NtCustomVal1, noteInfo.NtCustomVal2,

			noteInfo.NtNoteCode, noteInfo.NtNoteText, noteInfo.NtPatientId, noteInfo.NtEntryUser, noteInfo.NtEntryDate,

			noteInfo.NtAppUser, noteInfo.NtAppDate, noteInfo.NtTxId, noteInfo.NtDesc, noteInfo.NtSite, noteInfo.NtStatus

		FROM NOTES2 N2, PATIENT2 P2

		WHERE 1=1

			AND N2."Auto" = vAuto

			AND N2."Type" in (0,1,3)

			AND P2."Auto" = N2."PId"

      AND ROWNUM = 1;



  FOR vNoteOvrRecord IN vNoteOvrRecords LOOP

    noteInfo.NtNoteText := noteInfo.NtNoteText || vNoteOvrRecord."Text";

  END LOOP;



	EXCEPTION WHEN NO_DATA_FOUND THEN

		noteInfo := NULL;

	END;



	RETURN noteInfo;

END;





/**

* Function to retrieve data about a particular note (SOAP) and return it as a rec_SOAPNoteDetail RECORD type.<p/>

*

* param: vOtherId INPUT: ID for the SOAP note (NOTES2.OtherId).<p/>

* param: vCountryName INPUT: Name of country.<p/>

* return: rec_SOAPNoteDetail record containing the note data.<p/>

*/

FUNCTION getsoapnotedetail(votherid integer, vcountryname character varying) RETURN rec_soapnotedetail IS

	noteInfo rec_SOAPNoteDetail;



	vNoteTextS  VARCHAR2(32767);

	vNoteTextO  VARCHAR2(32767);

	vNoteTextA  VARCHAR2(32767);

	vNoteTextP  VARCHAR2(32767);



  CURSOR vNoteOvrRecordsS IS

    SELECT NR.* FROM NOTES2 N2, NOTEOVR NR

    WHERE N2."OtherId" = vOtherId

    AND N2."Type" = 4

    AND N2."SectionNo" = 0

    AND N2."Auto" = NR."ParentId"

    AND NR."Deleted" = 0

    ORDER BY "Order" ASC;



  CURSOR vNoteOvrRecordsO IS

    SELECT NR.* FROM NOTES2 N2, NOTEOVR NR

    WHERE N2."OtherId" = vOtherId

    AND N2."Type" = 4

    AND N2."SectionNo" = 1

    AND N2."Auto" = NR."ParentId"

    AND NR."Deleted" = 0

    ORDER BY "Order" ASC;



  CURSOR vNoteOvrRecordsA IS

    SELECT NR.* FROM NOTES2 N2, NOTEOVR NR

    WHERE N2."OtherId" = vOtherId

    AND N2."Type" = 4

    AND N2."SectionNo" = 2

    AND N2."Auto" = NR."ParentId"

    AND NR."Deleted" = 0

    ORDER BY "Order" ASC;



  CURSOR vNoteOvrRecordsP IS

    SELECT NR.* FROM NOTES2 N2, NOTEOVR NR

    WHERE N2."OtherId" = vOtherId

    AND N2."Type" = 4

    AND N2."SectionNo" = 3

    AND N2."Auto" = NR."ParentId"

    AND NR."Deleted" = 0

    ORDER BY "Order" ASC;



  vNoteOvrRecord NOTEOVR%ROWTYPE;

BEGIN

	-- get the note text from each of S,O,A,P notes

	BEGIN

		SELECT N2."Text"

		INTO noteInfo.NtNoteTextS

		FROM NOTES2 N2

		WHERE 1=1

			AND N2."OtherId" = vOtherId

			AND N2."Type" = 4

			AND N2."SectionNo" = 0

      AND N2."Status" IN (0, 1)

      AND ROWNUM = 1;



    FOR vNoteOvrRecord IN vNoteOvrRecordsS LOOP

      noteInfo.NtNoteTextS := noteInfo.NtNoteTextS || vNoteOvrRecord."Text";

    END LOOP;



		EXCEPTION WHEN NO_DATA_FOUND THEN

			vNoteTextS := NULL;

	END;



	BEGIN

		SELECT N2."Text"

		INTO noteInfo.NtNoteTextO

		FROM NOTES2 N2

		WHERE 1=1

			AND N2."OtherId" = vOtherId

			AND N2."Type" = 4

			AND N2."SectionNo" = 1

      AND N2."Status" IN (0, 1)

      AND ROWNUM = 1;



    FOR vNoteOvrRecord IN vNoteOvrRecordsO LOOP

      noteInfo.NtNoteTextO := noteInfo.NtNoteTextO || vNoteOvrRecord."Text";

    END LOOP;



		EXCEPTION WHEN NO_DATA_FOUND THEN

			vNoteTextO := NULL;

	END;



	BEGIN

		SELECT N2."Text"

		INTO noteInfo.NtNoteTextA

		FROM NOTES2 N2

		WHERE 1=1

			AND N2."OtherId" = vOtherId

			AND N2."Type" = 4

			AND N2."SectionNo" = 2

      AND N2."Status" IN (0, 1)

      AND ROWNUM = 1;



    FOR vNoteOvrRecord IN vNoteOvrRecordsA LOOP

      noteInfo.NtNoteTextA := noteInfo.NtNoteTextA || vNoteOvrRecord."Text";

    END LOOP;



		EXCEPTION WHEN NO_DATA_FOUND THEN

			vNoteTextA := NULL;

	END;



	BEGIN

		SELECT N2."Text"

		INTO noteInfo.NtNoteTextP

		FROM NOTES2 N2

		WHERE 1=1

			AND N2."OtherId" = vOtherId

			AND N2."Type" = 4

			AND N2."SectionNo" = 3

      AND N2."Status" IN (0, 1)

      AND ROWNUM = 1;



    FOR vNoteOvrRecord IN vNoteOvrRecordsP LOOP

      noteInfo.NtNoteTextP := noteInfo.NtNoteTextP || vNoteOvrRecord."Text";

    END LOOP;



		EXCEPTION WHEN NO_DATA_FOUND THEN

			vNoteTextP := NULL;

	END;



	-- get the rest of the data for the overall SOAP note

	BEGIN

		SELECT DISTINCT

			N2."OtherId",

			TRIM(N2."Phase"),

			TRIM(N2."Seq"),

			TRIM(N2."Custom1"),

			TRIM(N2."Custom2"),

			NULL,

			P2."PtxPId",

			N2."User",

			TO_CHAR(N2."ModifiedDateTime",'MON DD, YYYY'),

			N2."AppUser",

			TO_CHAR(N2."AppDate",'MON DD, YYYY'),

      N2."TxId",

      CASE

        WHEN N2."TxId" = 0 THEN 'SOAP NOTE'

        ELSE 'SOAP NOTE (' || FPORTAL_PKG.GetProcedureCodeByTxId(N2."TxId") || ')'

      END,

			(SELECT SR."Value" FROM FSITEREF SR WHERE SR."Id" = N2."Site" AND SR."Country" = vCountryName AND ROWNUM = 1),

      CASE

        WHEN N2."Status" = 0 THEN NULL

        ELSE 'D'

      END,

	  N2."Date"

		INTO noteInfo.NtOtherId, noteInfo.NtPhase, noteInfo.NtSequence, noteInfo.NtCustomVal1, noteInfo.NtCustomVal2,

			noteInfo.NtNoteCode,

			noteInfo.NtPatientId, noteInfo.NtEntryUser, noteInfo.NtEntryDate,

			noteInfo.NtAppUser, noteInfo.NtAppDate, noteInfo.NtTxId, noteInfo.NtDesc, noteInfo.NtSite, noteInfo.NtStatus, noteInfo.NtDate

		FROM NOTES2 N2, PATIENT2 P2

		WHERE 1=1

			AND N2."OtherId" = vOtherId

			AND N2."Type" = 4

			AND P2."Auto" = N2."PId"

      AND ROWNUM = 1;



	EXCEPTION WHEN NO_DATA_FOUND THEN

		noteInfo := NULL;

	END;



	RETURN noteInfo;

END;





/**

* Function that checks if a treatment needs consent, and if it has been consented to.<p/>

*

* param: vType INPUT: Type of the treatment (TRX.Type).<p/>

* param: vId INPUT: ID of the treatment (TRX.Id).<p/>

* param: vTreatment INPUT: Treatment # of the treatment (TRX.Treatment).<p/>

* return: Flag indicating if the treament has/needs consent (0=need consent and don't have it, 1=either don't need consent or have consent).<p/>

*/

FUNCTION txhasreqconsent(vtype integer, vid integer, vtreatment integer, vpatient integer, vproducer character, vprocedure character, vsite character) RETURN integer IS

	vPatientNeedsConsent INTEGER;	-- whether or not the patient requires consent

	vProdNeedsConsent INTEGER; 	-- whether or not the producer requires pt consent

	vProcNeedsConsent INTEGER;	-- whether or not the tx procedure needs consent

	vTxHasConsent  VARCHAR(4000); -- whether or not the tx has a consent

  vTxDeleted INTEGER; -- whether or not the tx is deleted

  vTxStatus  CHAR(6);

BEGIN

	BEGIN

		-- get the patient, producer, and tx info for this treatment

    SELECT FPORTAL_PKG.PtRequiresConsent(vPatient) INTO vPatientNeedsConsent FROM DUAL;

    SELECT FPORTAL_PKG.ProdRequiresConsent(vProducer) INTO vProdNeedsConsent FROM DUAL;

    SELECT FPORTAL_PKG.ProcRequiresConsent(vProcedure) INTO vProcNeedsConsent FROM DUAL;



		SELECT

			CONSENT_PKG.TRX_HAS_CONSENT("OrigRecNo", vProcedure, vSite, vPatient, SUBSTR(vProducer, 1,1)),

      "Deleted", "Status"

		INTO vTxHasConsent, vTxDeleted, vTxStatus

		FROM TRX

		WHERE 1=1

			AND "Type" = vType

			AND "Id" = vId

			AND "Treatment" = vTreatment;



    IF vTxDeleted = 1 OR vTxStatus = 'C' THEN

      RETURN 1;

    ELSIF vPatientNeedsConsent = 1 AND vProdNeedsConsent = 1 AND vProcNeedsConsent = 1 THEN

			-- check if we have the needed consent; (Now CONSENT_PKG.TRX_HAS_CONSENT could include string values)

			IF (TRIM(vTxHasConsent) IS NULL OR LENGTH(TRIM(vTxHasConsent)) = 0) THEN

				RETURN 1; -- we have it

			ELSE

				RETURN 0; -- need consent but don't have it.

			END IF;

		ELSE

			RETURN 1; -- don't need consent

		END IF;



	EXCEPTION WHEN NO_DATA_FOUND THEN

		RETURN 1; -- error finding this tx

	END;

END;



/**

* 35486199 Function that checks if planned procedure (dummy appt tx) needs consent, and if it has been consented to.<p/>

*

* return: Flag indicating if the planned procedure has/needs consent (0=need consent and don't have it, 1=either don't need consent or have consent).<p/>

*/

FUNCTION plannedprochasreqconsent(vpatient integer, vproducer character, vprocedure character) RETURN integer IS

  vPatientNeedsConsent INTEGER;	-- whether or not the patient requires consent

  vProdNeedsConsent INTEGER; 	-- whether or not the producer requires pt consent

  vProcNeedsConsent INTEGER;	-- whether or not the tx procedure needs consent

  vTxHasConsent  VARCHAR(4000); -- whether or not the tx has a consent

BEGIN

    BEGIN

		-- get the patient, producer, and procedure info for this treatment

    SELECT FPORTAL_PKG.PtRequiresConsent(vPatient) INTO vPatientNeedsConsent FROM DUAL;

    SELECT FPORTAL_PKG.ProdRequiresConsent(vProducer) INTO vProdNeedsConsent FROM DUAL;

    SELECT FPORTAL_PKG.ProcRequiresConsent(vProcedure) INTO vProcNeedsConsent FROM DUAL;



    SELECT CONSENT_PKG.TRX_HAS_CONSENT(0,vProcedure,'', vPatient, SUBSTR(vProducer, 1,1)) INTO vTxHasConsent FROM DUAL;



    IF vPatientNeedsConsent = 1 AND vProdNeedsConsent = 1 AND vProcNeedsConsent = 1 THEN

        -- check if we have the needed consent; (Now CONSENT_PKG.TRX_HAS_CONSENT could include string values)

        IF (TRIM(vTxHasConsent) IS NULL OR LENGTH(TRIM(vTxHasConsent)) = 0) THEN

            RETURN 1; -- we have it

        ELSE

            RETURN 0; -- need consent but don't have it.

        END IF;

    ELSE

        RETURN 1; -- don't need consent

    END IF;



    EXCEPTION WHEN NO_DATA_FOUND THEN

        RETURN 1; -- error finding this planned procedure

    END;

END;



/**

* Function to retrieve data about a particular finding (condition or material) and return it as a rec_FindingDetail RECORD type.<p/>

*

* param: vAuto INPUT: ID of the finding to get the details for (TREATME2.Auto).<p/>

* param: vType INPUT: Flag indicating if the finding is approved or unapproved (0=unapproved, 1=approved).<p/>

* return: rec_FindingDetail record containing the finding data.<p/>

*/

FUNCTION getfindingdetail(vauto integer, vchartlnk integer, vtype integer) RETURN rec_findingdetail IS

	findInfo rec_FindingDetail;

  vTxCount INTEGER;

BEGIN

  BEGIN

    SELECT COUNT(*) INTO vTxCount FROM CHARTLNK CL

    WHERE CL."Auto" = (SELECT CL2."Auto" FROM CHARTLNK CL2 WHERE CL2."Id" = vChartLnk AND ROWNUM = 1);

  END;



	IF vType = 0 THEN -- unapproved, use chartlnk version

	BEGIN

		SELECT

			vAuto,

			vType,

      CL."Id",

			CL."Patient",

			CL."User",

      TO_CHAR(TM."AddDateTime",'MON DD, YYYY'),

			NULL,

			NULL,

			TO_CHAR(CL."TxDate",'MON DD, YYYY'),

			TRIM(CL."Procedure"),

			TRIM(PR."Description"),

			TRIM(CL."Status"),

      CASE

        WHEN vTxCount = 2 OR (TRIM(CL."Site2") IS NULL OR LENGTH(TRIM(CL."Site2")) = 0) THEN

          TRIM(CL."Site")

        ELSE

          TRIM(CL."Site") || ', ' || TRIM(CL."Site2")

        END,

			TRIM(CL."Surface"),

      TM."Status"

		INTO findInfo.FAuto, findInfo.FType, findInfo.FChartId, findInfo.FPatientId, findInfo.FEntryUser, findInfo.FEntryDate, findInfo.FAppUser, findInfo.FAppDate, findInfo.FTxDate,

			findInfo.FProcCode, findInfo.FProcDesc, findInfo.FStatus, findInfo.FSite, findInfo.FSurface, findInfo.FPrevStatus

		FROM CHARTLNK CL, PROCEDUR PR, TREATME2 TM

		WHERE 1=1

			AND CL."Auto" = vAuto

      AND CL."Id" = vChartLnk

			AND PR."Procedure" = CL."Procedure"

      AND CL."Auto" = TM."Auto"

      AND ROWNUM = 1;



		EXCEPTION WHEN NO_DATA_FOUND THEN

			findInfo := NULL;

		END;



	ELSIF vType = 1 THEN -- approved, use treatme2 version

		BEGIN



		SELECT

			vAuto,

			vType,

      NULL,

			P2."PtxPId",

			TR."User",

			TO_CHAR(TR."ModifiedDateTime",'MON DD, YYYY'),

			TR."AppUser",

			TO_CHAR(TR."AppDate",'MON DD, YYYY'),

      --TO_CHAR(TR."AddDateTime",'MON DD, YYYY'),

      TO_CHAR(TO_DATE('01-JAN-1901', 'DD-MON-YYYY') + TR."Days", 'MON DD, YYYY'),

			TRIM(PR."Procedure"),

			TRIM(PR."Description"),

			DECODE(TR."Status",0,'C',1,'I',2,'P',3,'E',4,'C',' '),

			TO_CHAR(TR."Site"),

			TO_CHAR(TR."Surface")

		INTO findInfo.FAuto, findInfo.FType, findInfo.FChartId, findInfo.FPatientId, findInfo.FEntryUser, findInfo.FEntryDate, findInfo.FAppUser, findInfo.FAppDate, findInfo.FTxDate,

			findInfo.FProcCode, findInfo.FProcDesc, findInfo.FStatus, findInfo.FSite, findInfo.FSurface

		FROM TREATME2 TR, PATIENT2 P2, PROCEDUR PR

		WHERE 1=1

			AND P2."Auto" = TR."PId"

			AND TR."DeletionDate" IS NULL

			AND TR."Auto" = vAuto

			AND PR."Id" = TR."CodeId"

      AND ROWNUM = 1;



		EXCEPTION WHEN NO_DATA_FOUND THEN

			findInfo := NULL;

		END;



	END IF;



	RETURN findInfo;

END;





/**

* Function to retrieve data about a particular form and return it as a rec_FormDetail RECORD type.<p/>

*

* param: vPForm INPUT: ID of the finding to get the details for.<p/>

* return: rec_FormDetail record containing the form data.<p/>

*/

FUNCTION getformdetail(vpform integer) RETURN rec_formdetail IS

	formInfo rec_FormDetail;

BEGIN

  BEGIN

  SELECT

    vPForm,

    F."Code",

      CASE WHEN F."Multiple" = 0 THEN

        TRIM(PF."Description")

      ELSE

        TRIM(PF."Description") || ' - ' || TO_CHAR(PF."CreatedDate",'MON DD, YYYY')

      END AS "Description",

    TO_CHAR(PF."CreatedDate",'MON DD, YYYY'),

    PF."FStatus",

    PF."AssignedUser",

    PF."AssignedUGroup",

    PF."Patient",

    PF."User",

    TO_CHAR(PF."Date",'MON DD, YYYY'),

    PF."LastAppUser",

    TO_CHAR(PF."LastAppDate", 'MON DD, YYYY')

  INTO formInfo.FPForm, formInfo.FCode, formInfo.FDesc, formInfo.FTxDate, formInfo.FStatus, formInfo.FAssignedUser, formInfo.FAssignedUGroup,

        formInfo.FPatientId, formInfo.FEntryUser, formInfo.FEntryDate, formInfo.FAppUser,

        formInfo.FAppDate

  FROM FORM F, PFORM PF

	WHERE 1=1

    AND PF."FormCode" = F."Code"

		AND PF."PForm" = vPForm

    AND ROWNUM = 1;



	EXCEPTION WHEN NO_DATA_FOUND THEN

		formInfo := NULL;

	END;



	RETURN formInfo;

END;



/**

* Function to retrieve data about a particular Perio and return it as a rec_PerioDetail RECORD type.<p/>

*

* param: vPtPerio INPUT: ID of the perio to get the details for.<p/>

* return: rec_PerioDetail record containing the perio data.<p/>

*/

FUNCTION getperiodetail(vptperio integer) RETURN rec_periodetail IS

  perioInfo rec_PerioDetail;

BEGIN

  BEGIN

  SELECT

    vPtPerio,

    CASE WHEN P."PerExam" != ' ' THEN

      'Perio Chart (' || (SELECT PE."Description" FROM PEREXAM PE WHERE P."PerExam" = PE."PerExam" AND ROWNUM = 1 ) || ' - ' || TO_CHAR(P."ChartDate",'MON DD, YYYY') || ')'

    ELSE

      'Perio Chart (' || TO_CHAR(P."ChartDate",'MON DD, YYYY') || ')'

    END,

    TO_CHAR(P."ChartDate",'MON DD, YYYY'),

    P."Patient",

    AH."User",

    TO_CHAR(AH."Date", 'MON DD, YYYY'),

    P."AppUser",

    TO_CHAR(P."AppDate", 'MON DD, YYYY'),

    P."Completed"



    INTO perioInfo.PPtPerio, perioInfo.PDesc, perioInfo.PDate, perioInfo.PPatientId, perioInfo.PEntryUser, perioInfo.PEntryDate,

          perioInfo.PAppUser, perioInfo.PAppDate, perioInfo.PStatus

    FROM PTPERIO P, AUDITHIS AH

    WHERE P."PtPerio" = vPtPerio

      AND P."Audit" = AH."Audit"

      AND AH."TableName" = 'PTPERIO'

      AND ROWNUM = 1;



    EXCEPTION WHEN NO_DATA_FOUND THEN

      perioInfo := NULL;



    END;

    RETURN perioInfo;

END;



/**

* Function to retrieve data about a particular Letter and return it as a rec_LetterDetail RECORD type.<p/>

*

* param: vPtLetter INPUT: ID of the letter to get the details for.<p/>

* return: rec_LetterDetail record containing the letter data.<p/>

*/

FUNCTION getletterdetail(vptletter integer) RETURN rec_letterdetail IS

  letterInfo rec_LetterDetail;

BEGIN

  BEGIN

    SELECT

      vPtLetter,

      TO_CHAR(P."Date",'MON DD, YYYY'),

      'LETTER - ' || P."Description",

      P."FileExt",

      P."Status",

      P."Patient",

      P."User",

      TO_CHAR(P."ModifiedDate",'MON DD, YYYY'),

      P."AppUser",

      TO_CHAR(P."AppDate",'MON DD, YYYY')

    INTO

      letterInfo.PPtLetter,

      letterInfo.PDate,

      letterInfo.PDesc,

      letterInfo.PFileType,

      letterInfo.PStatus,

      letterInfo.PPatientId,

      letterInfo.PEntryUser,

      letterInfo.PEntryDate,

      letterInfo.PAppUser,

      letterInfo.PAppDate

    FROM PTLDETAILS P					-- AX-25708

    WHERE P."PtLetter" = vPtLetter

    AND ROWNUM = 1;



  EXCEPTION WHEN NO_DATA_FOUND THEN

    letterInfo := NULL;

  END;

  RETURN letterInfo;

END;



/**

* Procedure that retrieves the details for a finding line (in Appt tab or Provider tab).<p/>

*

* param: vAuto INPUT: ID for the TREATME2 row associated with this finding (TREATME2.Auto).<p/>

* param: vType INPUT: Flag indicating if this treatment is approved or not approved (0=not approved, 1=approved)<p/>

* param: vDescription OUTPUT: String containing the line description, returned outside cursor for safety.<p/>

* param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

*	<li>PatientName - Name of the patient for this treatment, as a string formatted like 'F. LastName'.<br/>

*	<li>EntryUserName - Name of the entry user for this treatment, as a string formatted like 'F. LastName'.<br/>

*	<li>EntryDate - Entry/modified date for this treatment, as a string formatted like 'MON DD, YYYY'.<br/>

*	<li>AppUserName - Name of the approval user for this treatment, as a string formatted like 'F. LastName'.<br/>

*	<li>AppDate - Approval date for this treatment, as a string formatted like 'MON DD, YYYY'.<br/>

*	<li>Status - Status of the treatment, eg P, I C, P*, I*.<br/>

*	<li>Site - Tooth number for the treatment (TRX.Site).<br/>

*	<li>Surface - Surfaces for the treatment (TRX.Surface).<p/>

*/

PROCEDURE getlinedetailfinding(IN vauto integer, IN vchartlnk integer, IN vtype integer, OUT vdescription character varying, OUT results_cur cursor_pkg.weakcursor) IS

  	SQLStmt  VARCHAR2(8000);



  	findInfo rec_FindingDetail;

  	ptInfo rec_PatientDetail;

  	provInfo rec_UserDetail;

  	appInfo rec_UserDetail;

BEGIN

	-- get the finding details

	findInfo := GetFindingDetail(vAuto, vChartLnk, vType);



	IF findInfo.FAuto != -1 THEN

		-- get the patient details

		ptInfo := GetPatientDetail(findInfo.FPatientId);



		-- get the provider details

		provInfo := GetUserDetail(findInfo.FEntryUser);



		-- get the approval user details

		appInfo := GetUserDetail(findInfo.FAppUser);

	END IF;



	-- return description separately

	vDescription := findInfo.FProcCode || ' - ' || findInfo.FProcDesc;



	BEGIN

		OPEN results_cur FOR

    SELECT

      findInfo.FChartId AS "ChartLnk",

			ptInfo.PtName AS "PatientName",

      ptInfo.PtFirst AS "PatientFirstName",

      ptInfo.PtLast AS "PatientLastName",

      ptInfo.PtAgeSex AS PatientAgeSex,

			ptInfo.PtChart AS "PatientChart",

      provInfo.UIsProvider AS "EntryUserIsProvider",

      provInfo.UProviderId AS "EntryUserProvId",

			provInfo.UName AS "EntryUserName",

      provInfo.UFirst AS "EntryUserFirstName",

      provInfo.ULast AS "EntryUserLastName",

      findInfo.FEntryDate AS "EntryDate",

      appInfo.UIsProvider AS "AppUserIsProvider",

      appInfo.UProviderId AS "AppUserProvId",

			appInfo.UName AS "AppUserName",

      appInfo.UFirst AS "AppUserFirstName",

      appInfo.ULast AS "AppUserLastName",

			findInfo.FAppDate AS "AppDate",

			findInfo.FTxDate AS "TxDate",

			findInfo.FStatus AS "Status",

			findInfo.FSite AS "Site",

			findInfo.FSurface AS "Surface",

      findInfo.FPrevStatus AS "PrevStatus"

		FROM DUAL;



    EXCEPTION WHEN NO_DATA_FOUND THEN

      results_cur := null;

	END;

END;



/**

* Procedure that retrieves the details for a finding line (in Appt tab or Provider tab).<p/>

*

* param: vAuto INPUT: ID for the TREATME2 row associated with this finding (TREATME2.Auto).<p/>

* param: vType INPUT: Flag indicating if this treatment is approved or not approved (0=not approved, 1=approved)<p/>

* param: vDescription OUTPUT: String containing the line description, returned outside cursor for safety.<p/>

* param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

*	<li>PatientName - Name of the patient for this treatment, as a string formatted like 'F. LastName'.<br/>

*	<li>EntryUserName - Name of the entry user for this treatment, as a string formatted like 'F. LastName'.<br/>

*	<li>EntryDate - Entry/modified date for this treatment, as a string formatted like 'MON DD, YYYY'.<br/>

*	<li>AppUserName - Name of the approval user for this treatment, as a string formatted like 'F. LastName'.<br/>

*	<li>AppDate - Approval date for this treatment, as a string formatted like 'MON DD, YYYY'.<br/>

*	<li>Status - Status of the treatment, eg P, I C, P*, I*.<br/>

*	<li>Site - Tooth number for the treatment (TRX.Site).<br/>

*	<li>Surface - Surfaces for the treatment (TRX.Surface).<p/>

*/

PROCEDURE getlinedetailform(IN vpform integer, OUT vdescription character varying, OUT vugroup character varying, OUT results_cur cursor_pkg.weakcursor) IS

  	SQLStmt  VARCHAR2(4000);



  	formInfo rec_FormDetail;

  	ptInfo rec_PatientDetail;

  	provInfo rec_UserDetail;

    appInfo rec_UserDetail;

    assignedInfo rec_UserDetail;

BEGIN

	-- get the finding details

	formInfo := GetFormDetail(vPForm);



	IF formInfo.FPForm != -1 THEN

		-- get the patient details

		ptInfo := GetPatientDetail(formInfo.FPatientId);

		-- get the provider details

		provInfo := GetUserDetail(formInfo.FEntryUser);

		-- get the instuctor details

		appInfo := GetUserDetail(formInfo.FAppUser);

    -- get the assined to User details

    assignedInfo := GetUserDetail(formInfo.FAssignedUser);

	END IF;



	-- return description separately

	vDescription := formInfo.FCode || ' - ' || formInfo.FDesc;



  -- return uGroup Name seperately

  vUGroup := GetUGroupName(formInfo.FAssignedUGroup);



	BEGIN

		OPEN results_cur FOR

    SELECT

			ptInfo.PtName AS "PatientName",

      ptInfo.PtFirst AS "PatientFirstName",

      ptInfo.PtLast AS "PatientLastName",

      ptInfo.PtAgeSex AS PatientAgeSex,

			ptInfo.PtChart AS "PatientChart",

      provInfo.UIsProvider AS "EntryUserIsProvider",

      provInfo.UProviderId AS "EntryUserProvId",

			provInfo.UName AS "EntryUserName",

      provInfo.UFirst AS "EntryUserFirstName",

      provInfo.ULast AS "EntryUserLastName",

			formInfo.FEntryDate AS "EntryDate",

      appInfo.UIsProvider AS "AppUserIsProvider",

      appInfo.UProviderId AS "AppUserProvId",

      appInfo.UName AS "AppUserName",

      appInfo.UFirst AS "AppUserFirstName",

      appInfo.ULast AS "AppUserLastName",

			formInfo.FAppDate AS "AppDate",

			formInfo.FTxDate AS "TxDate",

			formInfo.FStatus AS "Status",

			assignedInfo.UName AS "AssignedUserName",

      assignedInfo.UFirst AS "AssignedUserFirstName",

      assignedInfo.ULast AS "AssignedUserLastName",

			formInfo.FCode AS "FormCode",

			formInfo.FPatientId AS "Patient",

			formInfo.FPForm AS "PForm",

			formInfo.FEntryUser AS "Provider"

		FROM DUAL;



    EXCEPTION WHEN NO_DATA_FOUND THEN

      results_cur := null;

	END;

END;



/**

* Procedure that retrieves the details for a perio line (in Appt tab or Provider tab).<p/>

*

* param: vPtPerio INPUT: ID for the PTPERIO row associated with this Perio.<p/>

* param: vDescription OUTPUT: String containing the line description, returned outside cursor for safety.<p/>

* param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

*	<li>Date - Date of the perio<br/>

*	<li>Status - Status of the perio<br/>

*	<li>ProviderType - Provider Type.<br/>

*	<li>PatientName - Patient Name.<br/>

*	<li>PatientAgeSex - Patient's Age and Sex in code.<br/>

*	<li>EntryUserName - Entry User's name.<br/>

*	<li>EntryDate - Date of Entry.<br/>

*	<li>AppUserName - Approved user's name.<p/>

*	<li>AppDate - Approved date.<p/>

*/

PROCEDURE getlinedetailperio(IN vptperio integer, OUT vdescription character varying, OUT results_cur cursor_pkg.weakcursor) IS

  SQLStmt  VARCHAR2(4000);



  perioInfo rec_PerioDetail;

  provInfo rec_UserDetail;

  appInfo rec_UserDetail;

  ptInfo rec_PatientDetail;



BEGIN

  -- get the perio details

  perioInfo := GetPerioDetail(vPtPerio);

  IF perioInfo.PPatientId != 0 THEN

		ptInfo := GetPatientDetail(perioInfo.PPatientId);

  END IF;



  IF perioInfo.PEntryUser != 0 THEN

    provInfo := GetUserDetail(perioInfo.PEntryUser);

  END IF;



  IF perioInfo.PAppUser != 0 OR perioInfo.PAppUser IS NOT NULL THEN

    appInfo := GetUserDetail(perioInfo.PAppUser);

  END IF;



  IF perioInfo.PPatientId != 0 THEN

		ptInfo := GetPatientDetail(perioInfo.PPatientId);

  END IF;



  vDescription := perioInfo.PDesc;



	BEGIN

		OPEN results_cur FOR

    SELECT

      perioInfo.PDate AS "Date",

      perioInfo.PStatus AS "Status",

      provInfo.UProviderTypeDesc AS "ProviderType",

      ptInfo.PtName AS "PatientName",

      ptInfo.PtFirst AS "PatientFirstName",

      ptInfo.PtLast AS "PatientLastName",

      ptInfo.PtAgeSex AS PatientAgeSex,

      ptInfo.PtChart AS "PatientChart",

      provInfo.UIsProvider AS "EntryUserIsProvider",

      provInfo.UProviderId AS "EntryUserProvId",

      provInfo.UName AS "EntryUserName",

      provInfo.UFirst AS "EntryUserFirstName",

      provInfo.ULast AS "EntryUserLastName",

      perioInfo.PEntryDate AS "EntryDate",

      appInfo.UIsProvider AS "AppUserIsProvider",

      appInfo.UProviderId AS "AppUserProvId",

      appInfo.UName AS "AppUserName",

      appInfo.UFirst AS "AppUserFirstName",

      appInfo.ULast AS "AppUserLastName",

			perioInfo.PAppDate AS "AppDate"

		FROM DUAL;



    EXCEPTION WHEN NO_DATA_FOUND THEN

      results_cur := null;

	END;

END;



/**

* Procedure that retrieves the details for a letter line (in Appt tab or Provider tab).<p/>

*

* param: vPtLetter INPUT: ID for the PTLDETAILS row associated with this Perio.<p/>

* param: vDescription OUTPUT: String containing the line description, returned outside cursor for safety.<p/>

* param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

*	<li>Date - Date of the letter<br/>

*	<li>Status - Status of the letter<br/>

*	<li>FileType - Type of Letter<br/>

*	<li>PatientName - Patient Name.<br/>

*	<li>PatientAgeSex - Patient's Age and Sex in code.<br/>

*	<li>PatientChart - Patient Chart.<br/>

*	<li>EntryUserName - Entry User's name.<br/>

*	<li>EntryDate - Date of Entry.<br/>

*	<li>AppUserName - Approved user's name.<p/>

*	<li>AppDate - Approved date.<p/>

*/

PROCEDURE getlinedetailletter(IN vptletter integer, OUT vdescription character varying, OUT results_cur cursor_pkg.weakcursor) IS

  SQLStmt  VARCHAR2(16000);



  letterInfo rec_LetterDetail;

  ptInfo rec_PatientDetail;

  provInfo rec_UserDetail;

  appInfo rec_UserDetail;

BEGIN

  -- get the Letter details

  letterInfo := GetLetterDetail(vPtLetter);

  IF letterInfo.PEntryUser != 0 THEN

    provInfo := GetUserDetail(letterInfo.PEntryUser);

  END IF;



  IF letterInfo.PAppUser != 0 OR letterInfo.PAppUser IS NOT NULL THEN

    appInfo := GetUserDetail(letterInfo.PAppUser);

  END IF;



  IF letterInfo.PPatientId != 0 THEN

    ptInfo := GetPatientDetail(letterInfo.PPatientId);

  END IF;



  vDescription := letterInfo.PDesc;



	BEGIN

		OPEN results_cur FOR

    SELECT

      letterInfo.PDate AS "Date",

      letterInfo.PStatus AS "Status",

      letterInfo.PFileType AS "FileType",

      ptInfo.PtName AS "PatientName",

      ptInfo.PtFirst AS "PatientFirstName",

      ptInfo.PtLast AS "PatientLastName",

      ptInfo.PtAgeSex AS PatientAgeSex,

      ptInfo.PtChart AS "PatientChart",

      provInfo.UIsProvider AS "EntryUserIsProvider",

      provInfo.UProviderId AS "EntryUserProvId",

      provInfo.UName AS "EntryUserName",

      provInfo.UFirst AS "EntryUserFirstName",

      provInfo.ULast AS "EntryUserLastName",

      letterInfo.PEntryDate AS "EntryDate",

      appInfo.UIsProvider AS "AppUserIsProvider",

      appInfo.UProviderId AS "AppUserProvId",

      appInfo.UName AS "AppUserName",

      appInfo.UFirst AS "AppUserFirstName",

      appInfo.ULast AS "AppUserLastName",

      letterInfo.PAppDate AS "AppDate"

		FROM DUAL;



    EXCEPTION WHEN NO_DATA_FOUND THEN

      results_cur := null;

	END;

END;



/**

* Function that creates an audit history and returns the ID of the created AUDITHIS record.<p/>

*

* param: vAuditUser INPUT: User ID of the user that the audit history is for (USERS.User).<p/>

* param: vAuditTable INPUT: Name of the table that this audit history is for.<p/>

* param: vHistoryType INPUT: Type of the audit history (0=undefined, 1=add, 2=edit, 4=delete).<p/>

* return: Audit ID of the AUDITHIS row that was inserted (AUDITHIS.Audit).<p/>

*/

FUNCTION addaudithis(vaudituser integer, vaudittable character varying, vhistorytype integer) RETURN integer IS

	vAudit 			AUDITHIS."Audit"%TYPE;			-- unique sequence id for AUDITHIS.Audit

	vAuditMinutes 		AUDITHIS."Time"%TYPE;			-- used to calculate AUDITHIS.Time

	vAuditStation	 	AUDITHIS."StationId"%TYPE := -1;	-- station to use for the audit

BEGIN

	-- add AUDITHIS record

	SELECT AUDITHIS_AUDIT_SEQ.nextVal

	INTO vAudit FROM DUAL;



	SELECT ((TO_NUMBER(TO_CHAR(SYSDATE,'HH24')) * 60) + TO_NUMBER(TO_CHAR(SYSDATE,'MI')))

	INTO vAuditMinutes FROM DUAL;



	SELECT TO_NUMBER(TRIM("Value"))

	INTO vAuditStation FROM FSETTING WHERE TRIM("Key") = 'FP.General.AuditStation';



	INSERT INTO AuditHis VALUES

	(

		vAudit,				-- AUDITHIS.Audit

		TRUNC(SYSDATE),			-- AUDITHIS.Date

		vAuditMinutes,			-- AUDITHIS.Time

		vAuditUser,			-- AUDITHIS.User

		vAuditStation,			-- AUDITHIS.StationId

		TRIM(vAuditTable),		-- AUDITHIS.TableName

		vHistoryType			-- AUDITHIS.HistoryType

	);



	-- return the audit ID

	RETURN vAudit;

END;



/**

* Procedure that gets the appointment IDs of all of the appointments for a provider for the current day.<p/>

*

* param: vUserId INPUT: User ID of the provider. (USERS.User)<p/>

* param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

*	<li>AP."Appointment" - Appointment ID of an appointment (APPOINT.Appointment).<p/>

*/

PROCEDURE getproviderappointments(IN vuserid integer, OUT results_cur cursor_pkg.weakcursor) IS

  	SQLStmt  VARCHAR2(4000);

BEGIN

	SQLStmt :=

	'

		SELECT AP."Appointment"

		FROM APPOINT AP, USERS US

		WHERE 1=1

			AND US."Producer" = AP."Producer"

			AND US."User" = :1

			AND TRUNC(AP."Date") = TRUNC(SYSDATE)

			AND AP."Type" IN (0,1,2)

	';



	BEGIN

		OPEN results_cur FOR SQLStmt USING vUserId;



	EXCEPTION WHEN NO_DATA_FOUND THEN

		results_cur := null;

	END;

END;



/**

* Function that checks whether or not an appointment contains any treatments that have not yet been start checked today.<p/>

*

* param: vAppointment INPUT: Appointment ID of the appointment to check (APPOINT.Appointment).<p/>

* return: Count of the number of appointment treatments on the appointment that have not been start checked today.<p/>

*/

FUNCTION hasappttxmissingstartchk(vappointment integer) RETURN integer IS

	vMissingCount INTEGER;

BEGIN

	BEGIN

		SELECT COUNT( DISTINCT APT."Id" || '.' || APT."Type" || '.' || APT."Treatment")

		INTO vMissingCount

		FROM APPOINT AP, APPTRX APT, TRX TR, STARTCHK SC, AUDITHIS AH

		WHERE

      (

        (APT."Type" = TR."Type" AND APT."Id" = TR."Id" AND APT."Treatment" = TR."Treatment")

        OR

        (TR."OrigRecNo" = ( SELECT TR2."OrigRecNo"

                            FROM TRX TR2

                            WHERE APT."Type" = TR2."Type"

                            AND APT."Id" = TR2."Id"

                            AND APT."Treatment" = TR2."Treatment"

                            AND TR2."Deleted" = 2))

      )

      AND TR."Deleted" = 0

			AND AP."Appointment" = vAppointment

			AND APT."Appointment" = AP."Appointment"

			AND SC."Appointment" = AP."Appointment"

			AND AH."Audit" = SC."Audit"

			AND AH."Date" = TRUNC(SYSDATE)

			AND NOT EXISTS

      (

				SELECT 1

				FROM STARTTRX ST, STARTCHK SC2

				WHERE 1=1

          AND SC2."Appointment" = vAppointment

          AND ST."StartChk" = SC2."StartChk"

          AND ST."Type" = APT."Type"

          AND ST."Id" = APT."Id"

          AND ST."Treatment" = APT."Treatment"

          AND ST."Procedure" = APT."Procedure"

      );



	EXCEPTION WHEN NO_DATA_FOUND THEN

		vMissingCount := 0;

	END;



	RETURN vMissingCount;

END;



/**

* Function that gets the latest start checked user for an appointment.<p/>

*

* param: vAppointment INPUT: Appointment ID of the appointment to check (APPOINT.Appointment).<p/>

* return: User ID of the latest StartChecked user.<p/>

*/

FUNCTION getapptstartchkuser(vappointment integer) RETURN integer IS

  vUser INTEGER;

BEGIN

  BEGIN

    SELECT

      CASE WHEN TRUNC(AH."Date") = TRUNC(SYSDATE) THEN SC."AppUser" ELSE 0 END

    INTO vUser

    FROM APPOINT AP

    LEFT JOIN STARTCHK SC ON SC."Appointment" = AP."Appointment"

    LEFT JOIN AUDITHIS AH ON AH."Audit" = SC."Audit"

    WHERE AP."Appointment" = vAppointment

    AND (SC."StartChk" IS NULL OR SC."StartChk" = (SELECT MAX(SM."StartChk") FROM STARTCHK SM WHERE SM."Appointment" = SC."Appointment"))

    AND ROWNUM = 1;

  END;

  RETURN vUser;

END;



/**

* Check if user can evaluate or not

* param: vInstructor INPUT: user id of the instructor<p/>

* param: vResult OUTPUT: result of the validation (0 = cannot evaluate, 1 = can evaluate)

*/

PROCEDURE getcanevaluate(IN vinstructor integer, OUT vresult integer) IS

BEGIN

  SELECT "CanEvaluate"

  INTO vResult

  FROM USERS

  WHERE "User" = vInstructor;

END;



/**

* Procedure to get list of items the instuctor can approve FROM USERS<p/>

* param: vInstructor INPUT: User ID of the instructor<p/>

* param: results_cur OUTPUT: row containing following rows:<p/>

* - ApprovePlanTx<p/>

* - ApproveCompTx<p/>

* - ApproveExistingTx<p/>

* - ApproveNotes<p/>

* - ApproveEHRForms<p/>

* - ApproveProblems<p/>

* - ApproveStartChks<p/>

* - ApproveLetters<p/>

* - ApprovePerio<p/>

* - ApproveConditionTx<p/>

* - ApproveOrthoV<p/>

*/

PROCEDURE getcanapprove(IN vinstructor integer, IN vstudent integer, OUT results_cur cursor_pkg.weakcursor) IS

  vRestrictProv INTEGER;

  vProducer  VARCHAR2(100);

  vPGroup  VARCHAR2(100);

BEGIN

  -- get provider code and provider group

  BEGIN

  SELECT UR."Producer", PR."PGroup"

  INTO vProducer, vPGroup

  FROM USERS UR, PRODUCER PR

  WHERE UR."Producer" = PR."Producer"

  AND LENGTH(TRIM(UR."Producer")) > 0

  AND "User" = vStudent;



  EXCEPTION WHEN NO_DATA_FOUND THEN

  vProducer := NULL;

  vPGroup := NULL;

  END;



  --IF NOT (TRIM(vProducer) IS NULL OR LENGTH(TRIM(vProducer)) = 0) THEN

    vRestrictProv := FPORTAL_PKG.IsInstRestrictProv(vInstructor, vProducer, vPGroup);

  --ELSE

  --  vRestrictProv := NULL;

  --END IF;



  IF vRestrictProv IS NULL OR vRestrictProv = 1 THEN

    BEGIN

      OPEN results_cur FOR

      SELECT

        -1 AS "ApprovePlanTx",

        -1 AS "ApproveCompTx",

        -1 AS "ApproveExistingTx",

        -1 AS "ApproveNotes",

        -1 AS "ApproveEHRForms",

        -1 AS "ApproveProblems",

        -1 AS "ApproveStartChks",

        -1 AS "ApproveLetters",

        -1 AS "ApprovePerio",

        -1 AS "ApproveConditionTx",

        -1 AS "ApproveOrthoV"

      FROM DUAL;

    END;

  ELSE

    BEGIN

      OPEN results_cur FOR

      SELECT

        "ApprovePlanTx",

        "ApproveCompTx",

        "ApproveExistingTx",

        "ApproveNotes",

        "ApproveEHRForms",

        "ApproveProblems",

        "ApproveStartChks",

        "ApproveLetters",

        "ApprovePerio",

        "ApproveConditionTx",

        "ApproveOrthoV"

      FROM USERS

      WHERE "User" = vInstructor

      AND ROWNUM = 1;

      EXCEPTION WHEN NO_DATA_FOUND THEN

      results_cur := NULL;

    END;

  END IF;

END;



/**

* Procedure to perform a Note Approval.<p/>

*

* param: vAuto INPUT: ID of NOTES2 to approve (NOTES2.Auto).<p/>

* param: vInstructor INPUT: User ID of the logged-in user (USERS.User).<p/>

* param: vResult OUTPUT: Flag to indicate if the note was successfully approved (0=yes,-1=error encountered).<p/>

*/

PROCEDURE doapprovenotes(IN vauto integer, IN vinstructor integer, OUT vresult integer) IS

BEGIN

  UPDATE NOTES2 SET

    "AppUser" = vInstructor,

    "AppDate" = TRUNC(SYSDATE)

  WHERE 1=1

    AND "Auto" = vAuto;



  COMMIT;

    vResult := 0;

  EXCEPTION WHEN OTHERS THEN

    vResult := -1;



END;



/**

* Procedure to perform a SOAP Note approval.<p/>

*

* param: vOtherId INPUT: ID shared by a set of SOAP notes to approve (NOTES2.OtherId).<p/>

* param: vInstructor INPUT: User ID of the logged-in user.<p/>

* param: vResult OUTPUT: Flag to indicate if the SOAP note was successfully approved (0=yes, -1=error encountered).<p/>

*/

PROCEDURE doapprovesoapnotes(IN votherid integer, IN vinstructor integer, OUT vresult integer) IS

  vAutoId 			NOTES2."Auto"%TYPE;			-- unique sequence id for NOTES2."Auto"

  vId           NOTEOVR."Id"%TYPE;      -- unique sequence id for NOTEOVR."Id"

  CURSOR vNotesRecords IS

    SELECT * FROM NOTES2

    WHERE "Type" = 4

    AND "OtherId" = vOtherId;

  vNotesRecord NOTES2%ROWTYPE;



  CURSOR vNoteOvrRecords IS

    SELECT * FROM NOTEOVR

    WHERE "ParentId"

    IN (

      SELECT N."Auto"

      FROM NOTES2 N

      WHERE N."Type" = 4

      AND N."OtherId" = vOtherId

    );

  vNoteOvrRecord NOTEOVR%ROWTYPE;



  vLiamTest INTEGER := 0;



BEGIN

  FOR vNotesRecord IN vNotesRecords LOOP

    SELECT NOTES2_AUTO_SEQ.nextVal

    INTO vAutoId FROM DUAL;



    INSERT INTO NOTES2

    VALUES

    (

      vAutoId,

      vNotesRecord."PId",

      vNotesRecord."ModifiedDateTime",

      vNotesRecord."TxId",

      vNotesRecord."Site",

      vNotesRecord."Text",

      vNotesRecord."User",

      vNotesRecord."Status",

      vNotesRecord."Phase",

      vNotesRecord."Seq",

      vNotesRecord."Custom1",

      vNotesRecord."Custom2",

      vInstructor,

      TRUNC(SYSDATE),

      vNotesRecord."Code",

      vNotesRecord."Type",

      vNotesRecord."OtherId",

      vNotesRecord."Module",

      vNotesRecord."SectionNo",

      vNotesRecord."Date",

      null,

      vNotesRecord."OrigId",

      vNotesRecord."AddDateTime",

      vNotesRecord."IsTemplate",

		vNotesRecord."RTFTEXT",	-- AX-20107.20559b

		0

    );

    FOR vNoteOvrRecord IN vNoteOvrRecords LOOP

      IF vNotesRecord."Auto" = vNoteOvrRecord."ParentId" THEN

	    DELETE FROM NOTEOVR

        WHERE "Id" = vNoteOvrRecord."Id";



        SELECT NOTEOVR_ID_SEQ.nextVal

        INTO vId FROM DUAL;



        INSERT INTO NOTEOVR

        VALUES

        (

          vId,

          vNoteOvrRecord."Patient",

          vNoteOvrRecord."Type",

          vAutoId,

          vNoteOvrRecord."Order",

          vNoteOvrRecord."Text",

          vNoteOvrRecord."Deleted",

          vNoteOvrRecord."Audit"

        );

      END IF;

    END LOOP;

	-- Delete note at the end

    DELETE FROM NOTES2

    WHERE "Auto" = vNotesRecord."Auto";



  END LOOP;



  COMMIT;



  vResult := 0;



  EXCEPTION WHEN OTHERS THEN

  vResult := -1;

END;





/**

* Procedure to perform a Condition approval (Status A).<p/>

*

* param: vChartLnk INPUT: ChartLnk ID of the condition (CHARTLNK.Id).<p/>

* param: vAuto INPUT: ID of TREATME2.Auto.<p/>

* param: vInstructor INPUT: User ID of the logged-in user.<p/>

* param: vResult OUTPUT: Flag to indicate if the condition was successfully approved (0=yes, -1=error encountered).<p/>

*/

PROCEDURE doapproveconditions(IN vchartlnk integer, IN vauto integer, IN vinstructor integer, OUT vresult integer) IS

  vDeleted INTEGER;

	vAudit AUDITHIS."Audit"%TYPE;			-- audit history

BEGIN

  DELETE FROM CHARTLNK WHERE "Id" = vChartLnk;



  SELECT "Deleted" INTO vDeleted FROM TREATME2 WHERE "Auto" = vAuto AND ROWNUM = 1;



  IF vDeleted = 0 THEN

    UPDATE TREATME2

    SET

    "AppUser" = vInstructor,

    "AppDate" = TRUNC(SYSDATE)

    WHERE "Auto" = vAuto;

  ELSE

    UPDATE TREATME2

    SET

    "DelAppUser" = vInstructor,

    "DelAppDate" = TRUNC(SYSDATE)

    WHERE "Auto" = vAuto;

  END IF;



  vAudit := FPORTAL_PKG.AddAuditHis(vInstructor, 'PTPERST', 2);



  UPDATE PTPERST

  SET "Audit" = vAudit

  WHERE "Patient" = (SELECT "User" FROM TREATME2 WHERE "Auto" = vAuto);

  COMMIT;

    vResult := 0;



  EXCEPTION WHEN OTHERS THEN

    vResult := -1;

END;



/**

* Procedure to perform a Findings approval (Status E).<p/>

*

* param: vChartLnk INPUT: ChartLnk ID of the finding (CHARTLNK.Id).<p/>

* param: vAuto INPUT: ID of TREATME2.Auto.<p/>

* param: vInstructor INPUT: User ID of the logged-in user.<p/>

* param: vResult OUTPUT: Flag to indicate if the finding was successfully approved (0=yes, -1=error encountered).<p/>

*/

PROCEDURE doapprovefindings(IN vchartlnk integer, IN vauto integer, IN vinstructor integer, OUT vresult integer) IS

  vDeleted INTEGER;

BEGIN

  DELETE FROM CHARTLNK WHERE "Id" = vChartLnk;



  SELECT "Deleted" INTO vDeleted FROM TREATME2 WHERE "Auto" = vAuto AND ROWNUM = 1;



  IF vDeleted = 0 THEN

    UPDATE TREATME2

    SET

    "AppUser" = vInstructor,

    "AppDate" = TRUNC(SYSDATE)

    WHERE "Auto" = vAuto;

  ELSE

    UPDATE TREATME2

    SET

    "DelAppUser" = vInstructor,

    "DelAppDate" = TRUNC(SYSDATE)

    WHERE "Auto" = vAuto;

  END IF;

  COMMIT;

    vResult := 0;

  EXCEPTION WHEN OTHERS THEN

    vResult := -1;

END;



/**

* Procedure to perform validation for a Form

*

* param: vFormCode INPUT: PITEM.FormCode.<p/>

* param: vPatient INPUT: PITEM.Patient.<p/>

* param: vInstructor INPUT: User ID approving the form (PITEM.AppUser).<p/>

* param: vCanApprove OUTPUT: Flag to indicate if the form can be approved (1=yes, 0=no).<p/>

* param: vRequiredBlank OUTPUT: Number of required answers not yet answered.<p/>

*/

PROCEDURE preapproveforms(IN vformcode character varying, IN vpform integer, IN vpatient integer, IN vinstructor integer, OUT vcanapprove integer, OUT vrequiredblank integer) IS

BEGIN

    BEGIN

    SELECT NVL(MIN(FI."CanApprove"), 0)

    INTO vCanApprove

    FROM FIACCESS FI, USERS U, FITEM F

    WHERE 1=1

    AND FI."FormCode"= vFormCode

    AND FI."FormCode"	= F."FormCode"

    AND FI."FItem" = F."FItem"

    AND F."Type" = 0

    AND F."Deleted" = 0

    AND FI."SLevel" = U."Level"

    AND U."User" = vInstructor

    AND F."Page" IN

    (

      SELECT DISTINCT FI."Page"

      FROM PITEM PI, FITEM FI

      WHERE 1=1

      AND PI."FItem" = FI."FItem"

      AND PI."AppUser" = 0

      AND PI."FormCode" = vFormCode

      AND PI."Patient" = vPatient

      AND PI."PForm" = vPForm

    );

    EXCEPTION WHEN NO_DATA_FOUND THEN

		vCanApprove := 0;

    vRequiredBlank :=0;

    END;



    BEGIN



    SELECT COUNT(1) INTO vRequiredBlank FROM FITEMREQ RQ, PFORM PF WHERE

    PF."PForm" = vPForm AND

    RQ."FStatus" = PF."FStatus" AND RQ."FItem" IN

    (

      SELECT DISTINCT FI."FItem"

      FROM  FITEM FI

      WHERE 1=1

      AND FI."Deleted" = 0

      AND FI."FormCode" = vFormCode

      AND FI."Type" IN (2,4)

      AND NOT EXISTS

      (

        SELECT PI."FItem" FROM PITEM PI WHERE 1=1

        AND PI."FormCode" = vFormCode

        AND PI."Patient" = vPatient

        AND PI."FItem" = FI."FItem"

        AND PI."PForm" = vPForm

        AND PI."Status" = 0

        AND

        (CASE

          WHEN PI."AnsType" = 0 AND PI."AnsYes" <> -1 THEN 1

          WHEN PI."AnsType" = 4 AND PI."AnsDate" IS NOT NULL THEN 1

          WHEN PI."AnsType" IN (1,2,5,7,9) AND NOT (TRIM(PI."AnsText") IS NULL OR LENGTH(TRIM(PI."AnsText")) = 0) THEN 1

          WHEN PI."AnsType" = 3 AND NOT (TRIM(PI."AnsListDesc") IS NULL OR LENGTH(TRIM(PI."AnsListDesc")) = 0) THEN 1

          WHEN PI."AnsType" IN (6,8) AND PI."PItemImg" <> 0 THEN 1

          ELSE 0

        END) = 1 )



       AND (FI."ParentFItem" = 0 OR EXISTS(select 1 from pitem pi2, fitem fi3 where pi2."PForm" = vPForm

       				and fi3."FItem" = pi2."FItem" AND fi3."Deleted" = 0

		                 and pi2."FItem" = FI."ParentFItem" and pi2."Status" = 0

								and pi2."AnsYes" = fi3."SubQAnswer")));



    EXCEPTION WHEN NO_DATA_FOUND THEN

      vRequiredBlank :=0;

    END;



END;



/**

* Procedure to add all Alerts (alert, allergies, and medical problems) and Needs

* for a patient item, if they are missing on approving an answer.

* If validation checks out, calls AddPtAlert procedure.

*

* param: vPatientItemId INPUT: PITEM.PItem.<p/>

* param: vInstructorId INPUT: USERS.User.<p/>

*/

PROCEDURE addalertsandneeds(IN vpatientitemid numeric, IN vinstructorid numeric) IS



  CURSOR curFormItemAdd IS

  SELECT

    PI."Patient",

    PI."AnsYes",

    PI."AnsText",

    PI."AnsListDesc",

    FI."AnsType",

    FA."AddAlert",

    FA."AlertType",

		FA."AddPtNeed",

		FA."NeedCode",

    FA."Answer",

    FA."NumFlag",

    FA."NumValue1",

    FA."NumValue2",

    FA."MedAlert"

  FROM PITEM PI

  JOIN FITEM FI ON PI."FItem" = FI."FItem"

  JOIN FITEMADD FA ON PI."FItem" = FA."FItem"

  WHERE PI."PItem" = vPatientItemId;



  isValidAddAlert NUMBER;

	isValidAddNeed NUMBER;

  isValidAnswer NUMBER;



BEGIN



  -- GET list of all medical alerts and allergy alerts for the item

  FOR formItemAdd IN curFormItemAdd LOOP



    -- Validate if need to add alert

    -- 0 = No, 1 = Yes, 2 = Prompt

    isValidAddAlert := 0;

    IF formItemAdd."AddAlert" = 1 OR formItemAdd."AddAlert" = 2

    THEN

      isValidAddAlert := 1;

    END IF;



		-- Validate if need to add Need

		-- 0 = No, 1 = Yes, 2 = Prompt

		isValidAddNeed := 0;

		IF formItemAdd."AddPtNeed" = 1 OR formItemAdd."AddPtNeed" = 2

		THEN

			isValidAddNeed := 1;

		END IF;



    -- Check answer

    -- 0 = Y, N, Don't Know

    -- 2 = Number (NumFlag 1 = less than, 2 = greater than, 3 = between)

    -- 3 = List

    isValidAnswer := 0;

    IF formItemAdd."AnsType" = 0 THEN

      IF (formItemAdd."AnsYes" = 0 AND formItemAdd."Answer" = 'N')

      OR (formItemAdd."AnsYes" = 1 AND formItemAdd."Answer" = 'Y')

      OR (formItemAdd."AnsYes" = 2 AND formItemAdd."Answer" = 'Don''t Know')

      THEN

        isValidAnswer := 1;

      END IF;

    ELSIF formItemAdd."AnsType" = 2 THEN

      IF (formItemAdd."NumFlag" = 1 AND FPORTAL_PKG.SafeToNumber(formItemAdd."AnsText") < formItemAdd."NumValue1")

      OR (formItemAdd."NumFlag" = 2 AND FPORTAL_PKG.SafeToNumber(formItemAdd."AnsText") > formItemAdd."NumValue1")

      OR (formItemAdd."NumFlag" = 3 AND FPORTAL_PKG.SafeToNumber(formItemAdd."AnsText") BETWEEN formItemAdd."NumValue1" AND formItemAdd."NumValue2")

      THEN

        isValidAnswer := 1;

      END IF;

    ELSIF formItemAdd."AnsType" = 3 THEN

      IF formItemAdd."Answer" = formItemAdd."AnsListDesc"

      THEN

        isValidAnswer := 1;

      END IF;

    END IF;



    IF isValidAddAlert = 1 AND isValidAnswer = 1

    THEN

      FPORTAL_PKG.AddPtAlert(formItemAdd."MedAlert", formItemAdd."AlertType", formItemAdd."Patient", vInstructorId);

    END IF;



		IF isValidAddNeed = 1 AND isValidAnswer = 1

		THEN

      FPORTAL_PKG.AddPtNeed(formItemAdd."NeedCode", formItemAdd."Patient", vInstructorId);

		END IF;



  END LOOP;

END;



/**

* Procedure to add an alert.

* Checks smoke status, adds audit history and patient item records

*

* param: vMedAlert INPUT: PTALERT.MedAlert.<p/>

* param: vAlertType INPUT: PTALERT.AlertType. 0 = clinical alert, 1 = allergy, 2 = medical problem<p/>

* param: vPatient INPUT: PTALERT.Patient.<p/>

* param: vUser INPUT: User entering the data (approving user). PTALERT.User.<p/>

*/

PROCEDURE addptalert(IN vmedalert integer, IN valerttype integer, IN vpatient integer, IN vuser integer) IS

  vCount INTEGER := 0;



  vAudit AUDITHIS."Audit"%TYPE;			-- audit history



  -- variables for existing smoking status codes

  vSmPtAlert INTEGER := 0;

  vSmDesc  VARCHAR2(255);

  vSmCode  VARCHAR2(255);

  vSmUser INTEGER := 0;

  vSmMedAlert INTEGER := 0;



  vIsSmoking INTEGER := 0;

BEGIN



  -- check if pt alert with same information already exists

  SELECT COUNT(1) INTO vCount

  FROM PTALERT

  WHERE "MedAlert" = vMedAlert

  AND "AlertType" = vAlertType

  AND "Patient" = vPatient

  AND "Deleted" = 0;



  IF vCount = 0 THEN

    BEGIN

			-- if med problem, need to make sure there will be only 1 smoking status

			IF vAlertType = 2 THEN

				SELECT PATIENT_PKG.ISSMOKINGPROBLEM(vMedAlert) INTO vIsSmoking FROM DUAL;



				IF vIsSmoking > 0 THEN

					PATIENT_PKG.GetSmokingStatus(vPatient, vSmMedAlert, vSmUser, vSmCode, vSmDesc, vSmPtAlert);



					IF (vSmPtAlert > 0) THEN

						vAudit := FPORTAL_PKG.AddAuditHis(vUser, 'PTALERT', 2);

						UPDATE PTALERT SET "Status" = 1, "Audit" = vAudit WHERE "PtAlert" = vSmPtAlert;

					END IF;

				END IF;

			END IF;



			vAudit := FPORTAL_PKG.AddAuditHis(vUser, 'PTALERT', 1);

			INSERT INTO PTALERT

			(

				"PtAlert",

				"Patient",

				"AlertType",

				"MedAlert",

				"Description",

				"Status",

				"OnsetDate",

				"Note",

				"Reaction",

				"Deleted",

				"User",

				"AddDateTime",

				"Audit",

				"eRxSyncAudit",

				"RcopiaID",

				"NDCID",

				"SNOCode"

			)



			SELECT PTALERT_PTALERT_SEQ.nextval,

			vPatient,

			vAlertType,

			M."MedAlert",

			M."Description",

			0,

			null,

			M."Note",

			null,

			0,

			vUser,

			Sysdate,

			vAudit,

			M."eRxSyncAudit",

			M."RcopiaID",

			null,

			M."SNOCode" FROM MEDALERT M WHERE "MedAlert" = vMedAlert;



    END;

  END IF;

END;



/**

* Procedure to delete an alert.

*

* param: vPtAlert INPUT: PTALERT.PtAlert.<p/>

* param: vUser INPUT: User entering the data (approving user). PTALERT.User.<p/>

*/

PROCEDURE deleteptalert(IN vptalert integer, IN vuser integer) IS

  vAudit AUDITHIS."Audit"%TYPE;			-- audit history

BEGIN

	vAudit := FPORTAL_PKG.AddAuditHis(vUser, 'PTALERT', 4); -- Delete

  UPDATE PTALERT P1

  SET P1."Deleted" = 1, P1."Audit" = vAudit

  WHERE

  EXISTS (

    SELECT 1 FROM PTALERT P2 WHERE

    P2."PtAlert" = vPtAlert AND P2."MedAlert" = P1."MedAlert" AND P2."AlertType" = P1."AlertType" AND P1."Patient" = P2."Patient"

    )

  AND P1."Deleted" = 0;

  COMMIT;

END;





PROCEDURE getptalertstodeletefromform(IN vformcode character varying, IN vpform integer, IN valerttype integer, IN vpatient integer, OUT results_cur cursor_pkg.weakcursor) IS

BEGIN



  OPEN results_cur FOR

    SELECT * FROM PTALERT WHERE

    "Patient" = vPatient AND "Deleted" = 0 AND "Status" = 0 AND "AlertType" = vAlertType AND

    "MedAlert" IN

    -- find answer where latest unapproved answer doesn't match FITEMADD and previous approved does match

    (

      SELECT DISTINCT FA."MedAlert"

      FROM PITEM PI, FITEM FI, FITEMADD FA, USER_VIEW U

      WHERE 1=1

      AND PI."FItem" = FI."FItem"

      AND FI."Deleted" = 0

      AND PI."FormCode" = vFormCode

      AND PI."Patient" = vPatient

      AND PI."PForm" = vPForm

      AND FI."Type" IN (2,3,4,6)

      AND PI."Status" = 0

      AND FI."FItem" = FA."FItem"

      AND FA."AddAlert" > 0

      AND FA."AlertType" = vAlertType

      AND PI."AppUser" = 0

      AND PI."AnsType" IN (0,2,3)

      AND PI."User" = U."User" AND U."Type" > 0

      AND

      (

        CASE

          WHEN PI."AnsType" = 0 AND DECODE(PI."AnsYes", 0, 'N', 1, 'Y', 2, 'Don''t Know', '')  = FA."Answer" THEN 1

          WHEN PI."AnsType" = 2 AND

            ((FA."NumFlag" = 1 AND TO_NUMBER(PI."AnsText") < FA."NumValue1")

            OR (FA."NumFlag" = 2 AND TO_NUMBER(PI."AnsText") > FA."NumValue1")

						OR (FA."NumFlag" = 3 AND TO_NUMBER(PI."AnsText") BETWEEN FA."NumValue1" AND FA."NumValue2"))

          THEN 1

          WHEN PI."AnsType" = 3 AND PI."AnsListDesc" = FA."Answer" THEN 1

          ELSE 0

        END

      ) = 0

      -- find most recent PITEM that's either approved or entered by an axiUm user and check if it matches FITEMADD

      AND EXISTS (SELECT 1 FROM FITEM FI2, PITEM PI2 WHERE

        PI2."FItem" = FI2."FItem"

        AND FI2."FItem" = FI."FItem"

        AND FI2."Deleted" = 0

        AND PI2."FormCode" = vFormCode

        AND PI2."Patient" = vPatient

        AND PI2."PForm" = vPForm

        AND PI2."AuditNumber" = (

          SELECT MAX(PI3."AuditNumber") FROM FITEM FI3, PITEM PI3, USER_VIEW U3 WHERE

          PI3."FItem" = FI3."FItem"

          AND FI2."FItem" = FI3."FItem"

          AND FI3."Deleted" = 0

          AND PI3."FormCode" = vFormCode

          AND PI3."Patient" = vPatient

          AND PI3."PForm" = vPForm

          AND PI3."User" = U3."User"

          AND (PI3."AppUser" > 0 OR U3."Type" = 0)

          )



        AND

        (

          CASE

            WHEN PI2."AnsType" = 0 AND DECODE(PI2."AnsYes", 0, 'N', 1, 'Y', 2, 'Don''t Know', '')  = FA."Answer" THEN 1

            WHEN PI2."AnsType" = 2 AND

              ((FA."NumFlag" = 1 AND TO_NUMBER(PI2."AnsText") < FA."NumValue1")

              OR (FA."NumFlag" = 2 AND TO_NUMBER(PI2."AnsText") > FA."NumValue1")

              OR (FA."NumFlag" = 3 AND TO_NUMBER(PI2."AnsText") BETWEEN FA."NumValue1" AND FA."NumValue2"))

            THEN 1

            WHEN PI2."AnsType" = 3 AND PI2."AnsListDesc" = FA."Answer" THEN 1

            ELSE 0

          END

          ) = 1

        )

      -- another current answer that may have/will add it

      AND NOT EXISTS

      (

        SELECT 1 FROM FITEM FI4, PITEM PI4, USER_VIEW U4, FITEMADD FA4

        WHERE 1=1

      AND PI4."FItem" = FI4."FItem"

      AND FI4."Deleted" = 0

      AND PI4."Patient" = vPatient



      AND FI4."Type" IN (2,3,4,6)

      AND (

      (PI4."Status" = 0 AND PI4."PForm" = vPForm) OR

      PI4."AuditNumber" = (SELECT MAX (PI5."AuditNumber") FROM PITEM PI5, USER_VIEW U5 WHERE

          PI5."PForm" = PI4."PForm" AND PI5."FItem" = PI4."FItem" AND PI4."PForm" <> vPForm

          AND (PI5."AppUser" > 0 OR

          ( PI5."User" = U5."User" AND U5."Type" = 0))



      ))

      --AND PI4."AppUser" = 0

      AND PI4."AnsType" IN (0,2,3)

      /*

      AND (PI4."PForm" = vPForm OR PI4."AppUser" > 0 OR

      ( PI4."User" = U4."User" AND U4."Type" = 0))*/

      AND FI4."FItem" <> FI."FItem"

      AND FI4."FItem" = FA4."FItem"

      AND FA4."AddAlert" > 0

      AND FA4."AlertType" = vAlertType

      AND FA4."MedAlert" = FA."MedAlert"

      AND

      (

        CASE

          WHEN PI4."AnsType" = 0 AND DECODE(PI4."AnsYes", 0, 'N', 1, 'Y', 2, 'Don''t Know', '')  = FA4."Answer" THEN 1

          WHEN PI4."AnsType" = 2 AND

            ((FA4."NumFlag" = 1 AND TO_NUMBER(PI4."AnsText") < FA4."NumValue1")

            OR (FA4."NumFlag" = 2 AND TO_NUMBER(PI4."AnsText") > FA4."NumValue1")

						OR (FA4."NumFlag" = 3 AND TO_NUMBER(PI4."AnsText") BETWEEN FA4."NumValue1" AND FA4."NumValue2"))

          THEN 1

          WHEN PI4."AnsType" = 3 AND PI4."AnsListDesc" = FA4."Answer" THEN 1

          ELSE 0

        END

      ) = 1



      )



    )



		ORDER BY TRIM("Description");





END;



/**

* Procedure to get user associated with the ticket for Faculty Portal

* param: vFormCode INPUT: PITEM.FormCode.<p/>

* param: vPatient INPUT: PITEM.Patient.<p/>

* param: results_cur OUTPUT: Medical problem (PTALERT) row.

*

*/

PROCEDURE getmedproblemstodeletefromform(IN vformcode character varying, IN vpform integer, IN vpatient integer, OUT results_cur cursor_pkg.weakcursor) IS

BEGIN

  GetPtAlertsToDeleteFromForm(vFormCode, vPForm, 2, vPatient, results_cur);

END;



/**

* Procedure to get user associated with the ticket for Faculty Portal

* param: vFormCode INPUT: PITEM.FormCode.<p/>

* param: vPatient INPUT: PITEM.Patient.<p/>

* param: results_cur OUTPUT: Alert (PTALERT) row.

*

*/

PROCEDURE getalertstodeletefromform(IN vformcode character varying, IN vpform integer, IN vpatient integer, OUT results_cur cursor_pkg.weakcursor) IS

BEGIN

  GetPtAlertsToDeleteFromForm(vFormCode, vPForm, 0, vPatient, results_cur);

END;





/**

* Procedure to get user associated with the ticket for Faculty Portal

* param: vFormCode INPUT: PITEM.FormCode.<p/>

* param: vPatient INPUT: PITEM.Patient.<p/>

* param: results_cur OUTPUT: Allergy (PTALERT) row.

*

*/

PROCEDURE getallergiestodeletefromform(IN vformcode character varying, IN vpform integer, IN vpatient integer, OUT results_cur cursor_pkg.weakcursor) IS

BEGIN

  GetPtAlertsToDeleteFromForm(vFormCode, vPForm, 1, vPatient, results_cur);

END;



/**

* Procedure to add a need.

* Adds audit history and patient item records

*

* param: vNeedCode INPUT: PTNEED.NeedCode.<p/>

* param: vPatient INPUT: PTNEED.Patient.<p/>

* param: vUser INPUT: User entering the data (approving user). PTNEED.User.<p/>

*/

PROCEDURE addptneed(IN vneedcode character, IN vpatient integer, IN vuser integer) IS

  vCount INTEGER := 0;

  vAudit AUDITHIS."Audit"%TYPE;			-- audit history

BEGIN



  -- check if pt alert with same information already exists

  SELECT COUNT(1) INTO vCount

  FROM PTNEED

  WHERE "Patient" = vPatient

  AND "NeedCode" = vNeedCode

  AND "Deleted" = 0;



	IF vCount = 0 THEN

		BEGIN

      vAudit := FPORTAL_PKG.AddAuditHis(vUser, 'PTNEED', 1);

			INSERT INTO PTNEED

			(

				"PtNeed",

				"Patient",

				"NeedCode",

				"NeedDate",

				"Assigned",

				"AuditId",

				"Deleted",

				"Note",

				"NeedSts"

			)



			SELECT PTNEED_PTNEED_SEQ.nextval,

			vPatient,

			NC."NeedCode",

			SYSDATE,

			0,

			vAudit,

			0,

			NULL,

			'ACTIVE'

			FROM NEEDCODE NC WHERE NC."NeedCode" = vNeedCode;

		END;

	END IF;



END;



/**

* Procedure to delete a need.

*

* param: vPtNeed INPUT: PTNEED.PtNeed.<p/>

* param: vUser INPUT: User entering the data (approving user). PTNEED.User.<p/>

*/

PROCEDURE deleteptneed(IN vptneed integer, IN vuser integer) IS

  vAudit AUDITHIS."Audit"%TYPE;			-- audit history

BEGIN

  vAudit := FPORTAL_PKG.AddAuditHis(vUser, 'PTNEED', 4); -- Delete

  UPDATE PTNEED

  SET "Deleted" = 1, "AuditId" = vAudit

  WHERE "PtNeed" = vPtNeed;

  COMMIT;

END;



/**

  * Procedure to get user associated with the ticket for Faculty Portal

  * param: vFormCode INPUT: PITEM.FormCode.<p/>

  * param: vPatient INPUT: PITEM.Patient.<p/>

  * param: results_cur OUTPUT: Need (PTNEED) row.

  *

  */

PROCEDURE getneedstodeletefromform(IN vformcode character varying, IN vpform integer, IN vpatient integer, OUT results_cur cursor_pkg.weakcursor) IS



BEGIN

  OPEN results_cur FOR

    SELECT N.*, NC."Description" FROM PTNEED N

    LEFT JOIN NEEDCODE NC ON N."NeedCode" = NC."NeedCode"

    WHERE N."Patient" = vPatient

		AND N."Deleted" = 0

		AND N."NeedCode" IN

    -- find answer where latest unapproved answer doesn't match FITEMADD and previous approved does match

    (

      SELECT DISTINCT FA."NeedCode"

      FROM PITEM PI, FITEM FI, FITEMADD FA, USER_VIEW U

      WHERE 1=1

      AND PI."FItem" = FI."FItem"

      AND FI."Deleted" = 0

      AND PI."FormCode" = vFormCode

      AND PI."Patient" = vPatient

      AND PI."PForm" = vPForm

      AND FI."Type" IN (2,3,4,6)

      AND PI."Status" = 0

      AND FI."FItem" = FA."FItem"

      AND FA."AddPtNeed" > 0

      AND PI."AppUser" = 0

      AND PI."AnsType" IN (0,2,3)

      AND PI."User" = U."User" AND U."Type" > 0

      AND

      (

        CASE

          WHEN PI."AnsType" = 0 AND DECODE(PI."AnsYes", 0, 'N', 1, 'Y', 2, 'Don''t Know', '')  = FA."Answer" THEN 1

          WHEN PI."AnsType" = 2 AND

            ((FA."NumFlag" = 1 AND TO_NUMBER(PI."AnsText") < FA."NumValue1")

            OR (FA."NumFlag" = 2 AND TO_NUMBER(PI."AnsText") > FA."NumValue1")

						OR (FA."NumFlag" = 3 AND TO_NUMBER(PI."AnsText") BETWEEN FA."NumValue1" AND FA."NumValue2"))

          THEN 1

          WHEN PI."AnsType" = 3 AND PI."AnsListDesc" = FA."Answer" THEN 1

          ELSE 0

        END

      ) = 0

      -- find most recent PITEM that's either approved or entered by an axiUm user and check if it matches FITEMADD

      AND EXISTS (SELECT 1 FROM FITEM FI2, PITEM PI2 WHERE

        PI2."FItem" = FI2."FItem"

        AND FI2."FItem" = FI."FItem"

        AND FI2."Deleted" = 0

        AND PI2."FormCode" = vFormCode

        AND PI2."Patient" = vPatient

        AND PI2."PForm" = vPForm

        AND PI2."AuditNumber" = (

          SELECT MAX(PI3."AuditNumber") FROM FITEM FI3, PITEM PI3, USER_VIEW U3 WHERE

          PI3."FItem" = FI3."FItem"

          AND FI2."FItem" = FI3."FItem"

          AND FI3."Deleted" = 0

          AND PI3."FormCode" = vFormCode

          AND PI3."Patient" = vPatient

          AND PI3."PForm" = vPForm

          AND PI3."User" = U3."User"

          AND (PI3."AppUser" > 0 OR U3."Type" = 0)

          )



        AND

        (

          CASE

            WHEN PI2."AnsType" = 0 AND DECODE(PI2."AnsYes", 0, 'N', 1, 'Y', 2, 'Don''t Know', '')  = FA."Answer" THEN 1

            WHEN PI2."AnsType" = 2 AND

              ((FA."NumFlag" = 1 AND TO_NUMBER(PI2."AnsText") < FA."NumValue1")

              OR (FA."NumFlag" = 2 AND TO_NUMBER(PI2."AnsText") > FA."NumValue1")

              OR (FA."NumFlag" = 3 AND TO_NUMBER(PI2."AnsText") BETWEEN FA."NumValue1" AND FA."NumValue2"))

            THEN 1

            WHEN PI2."AnsType" = 3 AND PI2."AnsListDesc" = FA."Answer" THEN 1

            ELSE 0

          END

          ) = 1

        )

      -- another current answer that may have/will add it

      AND NOT EXISTS

      (

        SELECT 1 FROM FITEM FI4, PITEM PI4, USER_VIEW U4, FITEMADD FA4

        WHERE 1=1

      AND PI4."FItem" = FI4."FItem"

      AND FI4."Deleted" = 0

      AND PI4."Patient" = vPatient



      AND FI4."Type" IN (2,3,4,6)

      AND (

      (PI4."Status" = 0 AND PI4."PForm" = vPForm) OR

      PI4."AuditNumber" = (SELECT MAX (PI5."AuditNumber") FROM PITEM PI5, USER_VIEW U5 WHERE

          PI5."PForm" = PI4."PForm" AND PI5."FItem" = PI4."FItem" AND PI4."PForm" <> vPForm

          AND (PI5."AppUser" > 0 OR

          ( PI5."User" = U5."User" AND U5."Type" = 0))



      ))

      AND PI4."AnsType" IN (0,2,3)

      /*

      AND (PI4."PForm" = vPForm OR PI4."AppUser" > 0 OR

      ( PI4."User" = U4."User" AND U4."Type" = 0))*/

      AND FI4."FItem" <> FI."FItem"

      AND FI4."FItem" = FA4."FItem"

      AND FA4."AddPtNeed" > 0

      AND FA4."NeedCode" = FA."NeedCode"

      AND

      (

        CASE

          WHEN PI4."AnsType" = 0 AND DECODE(PI4."AnsYes", 0, 'N', 1, 'Y', 2, 'Don''t Know', '')  = FA4."Answer" THEN 1

          WHEN PI4."AnsType" = 2 AND

            ((FA4."NumFlag" = 1 AND TO_NUMBER(PI4."AnsText") < FA4."NumValue1")

            OR (FA4."NumFlag" = 2 AND TO_NUMBER(PI4."AnsText") > FA4."NumValue1")

						OR (FA4."NumFlag" = 3 AND TO_NUMBER(PI4."AnsText") BETWEEN FA4."NumValue1" AND FA4."NumValue2"))

          THEN 1

          WHEN PI4."AnsType" = 3 AND PI4."AnsListDesc" = FA4."Answer" THEN 1

          ELSE 0

        END

      ) = 1



      )



    )



		ORDER BY TRIM(NC."Description");

END;







/**

* Procedure to perform a Form approval

*

* param: vFormCode INPUT: PITEM.FormCode.<p/>

* param: vPForm INPUT: PITEM.PForm.<p/>

* param: vPatient INPUT: PITEM.Patient.<p/>

* param: vInstructor INPUT: User ID approving the form (PITEM.AppUser).<p/>

* param: vResult OUTPUT: Flag to indicate if the finding was successfully approved (0=yes, -1=error encountered).<p/>

*/

PROCEDURE doapproveforms(IN vformcode character varying, IN vpform integer, IN vpatient integer, IN vinstructor integer, OUT vresult integer) IS

  CURSOR curPatientItem IS

  SELECT P."PItem"

  FROM PITEM P

  WHERE P."FormCode" = vFormCode

  AND P."Patient" = vPatient

  AND P."PForm" = vPForm

  AND P."AppUser" = 0

	AND P."Status" = 0 -- only the latest (not archived) answer should be approved

  AND P."FItem" IN

  (

		SELECT F."FItem"

		FROM FITEM F

		WHERE

			F."FormCode" = P."FormCode"	AND

			F."Type" >= 2               AND  --IN (2,3,4)         AND --46951099 Update Spreadsheet rows 6 and Headers 5 (as in axium compare >= 2)

			F."Page" IN

			(

				SELECT F2."Page"

				FROM FITEM F2, FIACCESS FI, USERS U

				WHERE

					F2."FormCode"   = FI."FormCode" AND

					F2."FItem"      = FI."FItem"    AND

					U."User"        = vInstructor 	AND

					F2."FormCode"   = P."FormCode" 	AND

					F2."Type" 	    = 0             AND

					F2."Deleted"    = 0             AND

					FI."SLevel"     = U."Level"     AND

					FI."CanApprove" = 1

			)

  );

BEGIN



  FOR patientItem IN curPatientItem LOOP

    UPDATE PITEM P

    SET P."AppUser" = vInstructor,

    P."AppDate" = TRUNC(SYSDATE)

    WHERE P."PItem" = patientItem."PItem";



    FPORTAL_PKG.AddAlertsAndNeeds(patientItem."PItem", vInstructor);

  END LOOP;



  UPDATE PFORM

  SET

	"Approved" 	  = 1,

	"LastAppUser" = vInstructor,

	"LastAppDate" = TRUNC(SYSDATE)

  WHERE

	"FormCode" 	  = vFormCode AND

	"Patient"     = vPatient  AND

	"PForm"       = vPForm    AND

	(  -- 46951099 Check if there is items to be Approval

      SELECT COUNT(1)

      FROM PITEM P, FITEM F

      WHERE P."FItem" = F."FItem"     AND

            P."Patient" = vPatient    AND

            P."FormCode" = vFormCode  AND

            P."PForm" = vPForm        AND

            P."Status" = 0            AND

            P."AppUser" = 0           AND

            P."ASAType"=0             AND

            F."Deleted" = 0           AND

            F."Type" >= 2

    ) <= 0;



  COMMIT;

    vResult := 0;

  EXCEPTION WHEN OTHERS THEN

    vResult := -1;

END;



/**

* Procedure to perform a Perio Approval.<p/>

*

* param: vPtPerio INPUT: Perio ID (PTPERIO.PtPerio).<p/>

* param: vInstructor INPUT: User ID of the logged-in user.<p/>

* param: vResult OUTPUT: Flag to indicate if the finding was successfully approved (0=yes, -1=error encountered).<p/>

*/

PROCEDURE doapproveperio(IN vptperio integer, IN vinstructor integer, OUT vresult integer) IS

BEGIN

  UPDATE PTPERIO

  SET

    "AppUser" = vInstructor,

    "AppDate" = TRUNC(SYSDATE)

  WHERE

    "PtPerio" = vPtPerio;

  COMMIT;

    vResult := 0;

  EXCEPTION WHEN OTHERS THEN

    vResult := -1;

END;



/**

* Procedure to perform a Letter Approval.<p/>

*

* param: vPtLetter INPUT: Letter ID (PTLDETAILS.PtLetter).<p/>

* param: vInstructor INPUT: User ID of the logged-in user.<p/>

* param: vResult OUTPUT: Flag to indicate if the finding was successfully approved (0=yes, -1=error encountered).<p/>

*/

PROCEDURE doapproveletter(IN vptletter integer, IN vinstructor integer, OUT vresult integer) IS

BEGIN

  UPDATE PTLDETAILS						-- AX-25708

  SET

    "AppUser" = vInstructor,

    "AppDate" = TRUNC(SYSDATE)

  WHERE

    "PtLetter" = vPtLetter;

  COMMIT;

    vResult := 0;

  EXCEPTION WHEN OTHERS THEN

    vResult := -1;

END;



/**

* Helper function to validate and get full procedure name

* param: vCode INPUT: Procedure name<p/>

* return: procedure name if the procedure is valid, if not return 'Procedure Code - Not on File'

*/

FUNCTION getprocedurename(vcode character varying) RETURN character varying IS

  vProcedureName  VARCHAR2(4000);

BEGIN

  BEGIN

    SELECT TRIM("Procedure") || ' - ' || TRIM("Description")

    INTO vProcedureName

    FROM PROCEDUR

    WHERE TRIM("Procedure") = TRIM(vCode);



    EXCEPTION WHEN NO_DATA_FOUND THEN

    vProcedureName := 'Procedure Code - Not on File';

  END;

  RETURN vProcedureName;

END;



/**

* Helper function to get session time of the appointment

* param: vAppoint INPUT: ID of appointment

* return: ID of clinic time CLINICT."ClinicTime"

*/

FUNCTION getclinictime(vappoint integer) RETURN integer IS

  vClinicTime INTEGER;

  vClinic     CLINIC."Clinic"%TYPE;

  vAppDate    APPOINT."Date"%TYPE;

  vFrom       APPOINT."From"%TYPE;

  vTime0      APPOINT."Time0"%TYPE;

  vTime1      APPOINT."Time1"%TYPE;

  vTime2      APPOINT."Time2"%TYPE;

  vTime3      APPOINT."Time3"%TYPE;

  vTime4      APPOINT."Time4"%TYPE;

  vTime5      APPOINT."Time5"%TYPE;

BEGIN

  SELECT

    AP."Date",

    AP."Clinic",

    AP."From",

    AP."Time0",

    AP."Time1",

    AP."Time2",

    AP."Time3",

    AP."Time4",

    AP."Time5"

  INTO vAppDate, vClinic, vFrom, vTime0, vTime1, vTime2, vTime3, vTime4, vTime5

  FROM APPOINT AP

  WHERE AP."Appointment" = vAppoint

  AND ROWNUM = 1;



  BEGIN

  SELECT "ClinicTime"

  INTO vClinicTime

  FROM

  (

    SELECT CT."ClinicTime"

    FROM CLINICT CT

    WHERE CT."Clinic" = vClinic

    AND vFrom < CT."End" AND (vFrom + vTime0 + vTime1 + vTime2 + vTime3 + vTime4 + vTime5) > CT."Start"

    AND

    (

      (CT."Monday" = 1 AND TRIM(TO_CHAR(vAppDate,'Day')) = 'Monday') OR

      (CT."Tuesday" = 1 AND TRIM(TO_CHAR(vAppDate,'Day')) = 'Tuesday') OR

      (CT."Wednesday" = 1 AND TRIM(TO_CHAR(vAppDate,'Day')) = 'Wednesday') OR

      (CT."Thursday" = 1 AND TRIM(TO_CHAR(vAppDate,'Day')) = 'Thursday') OR

      (CT."Friday" = 1 AND TRIM(TO_CHAR(vAppDate,'Day')) = 'Friday') OR

      (CT."Saturday" = 1 AND TRIM(TO_CHAR(vAppDate,'Day')) = 'Saturday') OR

      (CT."Sunday" = 1 AND TRIM(TO_CHAR(vAppDate,'Day')) = 'Sunday')

    )

	AND ((CT."StartDate" <= vAppDate AND CT."EndDate" >= vAppDate)

      OR (CT."StartDate" is null AND CT."EndDate" >= vAppDate)

      OR (CT."StartDate" <= vAppDate AND CT."EndDate" is null)

      OR (CT."StartDate" is null AND CT."EndDate" is null ))

    ORDER BY CT."Start" DESC

  )

  WHERE ROWNUM = 1;



  EXCEPTION WHEN NO_DATA_FOUND THEN

  vClinicTime := 0;

  END;

  RETURN vClinicTime;

END;



/**

* Gets all the clinic the user has access to

* param: vUserId INPUT: User ID<p/>

* return: results_cur OUTPUT: list of clinics with Clinic ID and description<p/>

*/

PROCEDURE getcliniclist(IN vuserid integer, OUT results_cur cursor_pkg.weakcursor) IS

BEGIN

	BEGIN

		OPEN results_cur FOR

      SELECT

        CL."Clinic", CL."Description", UC."IsDefault"

      FROM UCLINIC UC, CLINIC CL

      WHERE UC."Clinic" = CL."Clinic"

        AND UC."User" = vUserId

		AND CL."Inactive" = 0

      ORDER BY CL."Description";

	EXCEPTION WHEN NO_DATA_FOUND THEN

		results_cur := null;

	END;

END;



/**

* Gets name of the clinic

* param: vClinic INPUT: Clinic ID<p/>

* return: vDescription OUTPUT: Clinic description<p/>

*/

PROCEDURE getclinicname(IN vclinic integer, OUT vdescription character varying) IS

BEGIN

  SELECT "Description"

  INTO vDescription

  FROM CLINIC

  WHERE "Clinic" = vClinic;



  EXCEPTION WHEN NO_DATA_FOUND THEN

  vDescription := NULL;

END;





/**

* Gets name of the clinic

* param: vClinic INPUT: Clinic ID<p/>

* return: vDescription OUTPUT: Clinic description<p/>

*/

PROCEDURE getclinictimename(IN vclinictime integer, OUT vdescription character varying) IS

BEGIN

  SELECT "Description"

  INTO vDescription

  FROM CLINICT

  WHERE "ClinicTime" = vClinicTime;



  EXCEPTION WHEN NO_DATA_FOUND THEN

  vDescription := NULL;

END;



/**

* Gets sessions for a clinic

* param: vClinic INPUT: Clinic ID<p/>

* return: results_cur OUTPUT: List of sessions for the clinic<p/>

*/

PROCEDURE getclinictimelist(IN vclinic integer, OUT results_cur cursor_pkg.weakcursor) IS

  vToday  VARCHAR2(20) := TRUNC(SYSDATE);

  vDOW  VARCHAR2(20) := NLS_UPPER(TRIM(TO_CHAR(TRUNC(SYSDATE),'Day')));

BEGIN

  OPEN results_cur FOR

  SELECT

    "ClinicTime",

    TRIM("Description") || ' (' || LPAD(FLOOR("Start"/60), '2', '0') || ':' || LPAD(MOD("Start", 60),'2', '0')

	                    || ' - ' || LPAD(FLOOR("End"/60), '2', '0') || ':' || LPAD(MOD("End", 60),'2', '0') || ')' AS "Description"

  FROM CLINICT CT

  WHERE "Clinic" = vClinic

  AND ("StartDate" <= vToday OR "StartDate" IS NULL)

  AND ("EndDate" >= vToday OR "EndDate" IS NULL)

  AND

  (

      (CT."Monday" = 1 AND vDOW = 'MONDAY') OR

      (CT."Tuesday" = 1 AND vDOW = 'TUESDAY') OR

      (CT."Wednesday" = 1 AND vDOW = 'WEDNESDAY') OR

      (CT."Thursday" = 1 AND vDOW = 'THURSDAY') OR

      (CT."Friday" = 1 AND vDOW = 'FRIDAY') OR

      (CT."Saturday" = 1 AND vDOW = 'SATURDAY') OR

      (CT."Sunday" = 1 AND vDOW = 'SUNDAY')

  )

  ORDER BY "Start";

  EXCEPTION WHEN NO_DATA_FOUND THEN

  results_cur := null;

END;



/**

* AX-25304 Gets Inactive of the clinic

* param: vClinic INPUT: Clinic ID<p/>

* return: vInactive OUTPUT: Clinic Inactive flag<p/>

*/

PROCEDURE getclinicinactive(IN vclinic integer, OUT vinactive integer) IS

BEGIN

  SELECT "Inactive"

  INTO vInactive

  FROM CLINIC

  WHERE "Clinic" = vClinic;



  EXCEPTION WHEN NO_DATA_FOUND THEN

  vInactive := 0;

END;



/**

* Helper function that returns all clinics a provider belongs to

* param: vProviderId INPUT: Provider ID

*/

FUNCTION getproviderclinics(vproducer character varying) RETURN character varying IS

  vString  VARCHAR2(4000);

  vStringTmp  VARCHAR2(400);

  CURSOR vReserves IS

    SELECT DISTINCT * FROM RESERVE RE

    WHERE TRIM(RE."Producer") = TRIM(vProducer)

    AND RE."Cancelled" = 0

    AND RE."Unavailable" = 0

    AND RE."Closed" = 0

    AND RE."Date" = TRUNC(SYSDATE)

    AND NOT EXISTS

    (

      SELECT HD."Id" FROM HOLIDAY HD

      WHERE HD."Id" = RE."Holiday"

      AND TRUNC(SYSDATE) BETWEEN TRUNC("StartDate") AND TRUNC("EndDate")

      AND (

            (HD."PartialDay" = 1 AND RE."Start" >= HD."StartTime" AND RE."End" <= HD."EndTime")

            OR

            (HD."PartialDay" = 0)

          )

    )

    AND NOT EXISTS

    (

      SELECT VA."Id" FROM VACATION VA

      WHERE VA."Id" = RE."Vacation"

      AND TRUNC(SYSDATE) = TRUNC("StartDate")

      AND RE."Start" >= VA."StartTime" AND RE."End" <= VA."EndTime"

      AND VA."Deleted" = 0

    );



  vReserve RESERVE%ROWTYPE;

BEGIN

  FOR vReserve IN vReserves LOOP

    vStringTmp := NULL;



    IF vReserve."ClinicTime" != 0 THEN

      SELECT "Clinic"

      INTO vStringTmp

      FROM CLINICT

      WHERE "ClinicTime" = vReserve."ClinicTime"

      AND ROWNUM = 1;

    ELSIF vReserve."WschitemId" != 0 THEN

      SELECT "Clinic"

      INTO vStringTmp

      FROM WSCHITEM

      WHERE "Id" = vReserve."WschitemId"

      AND ROWNUM = 1;

    ELSIF vReserve."Chair" != 0 THEN

      SELECT "Clinic"

      INTO vStringTmp

      FROM CHAIR

      WHERE "Chair" = vReserve."Chair"

      AND ROWNUM = 1;

    END IF;



    IF vStringTmp IS NOT NULL THEN

      IF vString IS NOT NULL THEN

        vString := vString || ',';

      END IF;



      vString := vString || '(' || vStringTmp || ')';

    END IF;

  END LOOP;

  RETURN vString;

END;





/**

* Helper function that returns all clinic Times a provider belongs to

* param: vProviderId INPUT: Provider ID

*/

FUNCTION getproviderclinictimes(vproducer character varying) RETURN character varying IS

  vString  VARCHAR2(4000);

  vStringTmp  VARCHAR2(400);

  CURSOR vReserves IS

    SELECT DISTINCT * FROM RESERVE RE

    WHERE TRIM(RE."Producer") = TRIM(vProducer)

    AND RE."Cancelled" = 0

    AND RE."Unavailable" = 0

    AND RE."Closed" = 0

    AND RE."Date" = TRUNC(SYSDATE)

    AND NOT EXISTS

    (

      SELECT HD."Id" FROM HOLIDAY HD

      WHERE HD."Id" = RE."Holiday"

      AND TRUNC(SYSDATE) BETWEEN TRUNC("StartDate") AND TRUNC("EndDate")

      AND (

            (HD."PartialDay" = 1 AND RE."Start" >= HD."StartTime" AND RE."End" <= HD."EndTime")

            OR

            (HD."PartialDay" = 0)

          )

    )

    AND NOT EXISTS

    (

      SELECT VA."Id" FROM VACATION VA

      WHERE VA."Id" = RE."Vacation"

      AND TRUNC(SYSDATE) = TRUNC("StartDate")

      AND RE."Start" >= VA."StartTime" AND RE."End" <= VA."EndTime"

      AND VA."Deleted" = 0

    );



  vReserve RESERVE%ROWTYPE;

BEGIN

  FOR vReserve IN vReserves LOOP

    vStringTmp := NULL;



    IF vReserve."ClinicTime" != 0 THEN

      vStringTmp := vReserve."ClinicTime";

    ELSIF vReserve."WschitemId" != 0 THEN

      SELECT "ClinicTime"

      INTO vStringTmp

      FROM WSCHITEM

      WHERE "Id" = vReserve."WschitemId"

      AND "ClinicTime" != 0

      AND ROWNUM = 1;

    END IF;



    IF vStringTmp IS NOT NULL THEN

      IF vString IS NOT NULL THEN

        vString := vString || ',';

      END IF;



      vString := vString || '(' || vStringTmp || ')';

    END IF;

  END LOOP;

  RETURN vString;

END;



/**

* Gets active provider group list

* return: results_cur OUTPUT: list of provider groups<p/>

*/

PROCEDURE getprovidergrouplist(OUT results_cur cursor_pkg.weakcursor) IS

  BEGIN

    BEGIN

    OPEN results_cur FOR

      SELECT

        "PGroup",

        TRIM("PGroup") || ' - ' || TRIM("Description") AS "Description"

      FROM PGROUP

      WHERE "Inactive" = 0

      ORDER BY "Description";

    EXCEPTION WHEN NO_DATA_FOUND THEN

      results_cur := NULL;

  END;

END;



/**

* Gets provider type list

* return: results_cur OUTPUT: list of provider typws<p/>

*/

PROCEDURE getprovidertypelist(OUT results_cur cursor_pkg.weakcursor) IS

BEGIN

  BEGIN

    OPEN results_cur FOR

      SELECT "Code", "Description"

      FROM PRODTYPE

      WHERE "Type" IN (0, 1)

      ORDER BY "Description";

    EXCEPTION WHEN NO_DATA_FOUND THEN

      results_cur := NULL;

  END;

END;



/**

* Get rows of Treatments that are linked together with supplied vChartLnk

* param: vChartLnk INPUT: CHARTLNK."Id"<p/>

* return: results_cur OUTPUT: List of treatements that are bridged<p/>

*/

PROCEDURE getbridgetreatments(IN vchartlnk integer, OUT results_cur cursor_pkg.weakcursor) IS

BEGIN

  BEGIN

    OPEN results_cur FOR

    SELECT CL."Id", CL."Previous" FROM CHARTLNK CL

    WHERE CL."Auto" = (SELECT CL2."Auto" FROM CHARTLNK CL2 WHERE CL2."Id" = vChartLnk AND ROWNUM = 1);

    EXCEPTION WHEN NO_DATA_FOUND THEN

    results_cur := null;

  END;

END;



/**

* Get all ChartLnk that are linked with supplied vChartLnk sorted by Status Desc, TxDate Asc and Id Asc

* param: vChartLnk INPUT: CHARTLNK."Id"<p/>

* return: results_cur OUTPUT: List of treatements that are bridged<p/>

*/

PROCEDURE getchartlnks(IN vchartlnk character varying, OUT results_cur cursor_pkg.weakcursor) IS

  SQLStmt  VARCHAR2(4000);

BEGIN

     SQLStmt := '

      SELECT CL."Id", CL."TxDate", CL."Status", TRIM(PT."First") || '' '' || TRIM(PT."Last") AS "PtFullName"

	  FROM CHARTLNK CL

      JOIN PATIENT PT ON PT."Patient" = CL."Patient"

      WHERE CL."Id" IN (' || vChartLnk || ')

      ORDER BY "PtFullName", CL."Status" DESC, CL."TxDate" ASC, CL."Id" ASC';



    OPEN results_cur FOR SQLStmt;

    EXCEPTION WHEN NO_DATA_FOUND THEN

    results_cur := null;

END;



/**

* Helper function that gets Surface for NOTES

* param: vSite: Site ID<p/>

* param: vSurface: Surface Code<p/>

* return: VARCHAR2 of proper matching Surface code<p/>

*/

FUNCTION getsurface(vsite character varying, vsurface integer) RETURN character varying IS

  vOutput  VARCHAR2(20);

  vNumber INTEGER;

  vB  VARCHAR2(1);

  vD  VARCHAR2(1);

  vL  VARCHAR2(1);

  vM  VARCHAR2(1);

  vO  VARCHAR2(1);

BEGIN

  vNumber := vSurface;



  IF vNumber >= 16 THEN

    IF vSite IN ('6','7','8','9','10','11','27','26','25','24','23','22') THEN

    vO := 'I';

    ELSE

    vO := 'O';

    END IF;

    vNumber := vNumber - 16;

  END IF;



  IF vNumber >= 8 THEN

    vM := 'M';

    vNumber := vNumber - 8;

  END IF;



  IF vNumber >= 4 THEN

    vL := 'L';

    vNumber := vNumber - 4;

  END IF;



  IF vNumber >= 2 THEN

    vD := 'D';

    vNumber := vNumber - 2;

  END IF;



  IF vNumber >= 1 THEN

    IF vSite IN ('6','7','8','9','10','11','27','26','25','24','23','22') THEN

      vB := 'F';

    ELSE

      vB := 'B';

    END IF;

    vNumber := vNumber - 1;

  END IF;



  IF vNumber = 0 THEN

    vOutput := vM || vO || vD || vB || vL;

  ELSE

    vOutput := NULL;

  END IF;



  RETURN vOutput;

END;



/**

* Procedure to get instructor detail

* return: instructor row

*/

PROCEDURE getinstructordetail(IN vuser integer, OUT results_cur cursor_pkg.weakcursor) IS

BEGIN

  OPEN results_cur FOR

  SELECT

    UR."User",

    UR."Name" AS "LastName",

    UR."First" AS "FirstName",

    UR."Level" AS "Level"

  FROM USERS UR

  WHERE UR."User" = vUser;



  EXCEPTION WHEN NO_DATA_FOUND THEN

  results_cur := NULL;

END;



/**

* Procedure to get provider detail

* return: provider row

*/

PROCEDURE getprovdetail(IN vuser integer, OUT results_cur cursor_pkg.weakcursor) IS

BEGIN

  OPEN results_cur FOR

  SELECT

    UR."User",

    UR."Name" AS "LastName",

    UR."First" AS "FirstName",

    UR."Producer" AS "Code",

    UR."Level" AS "Level",

    PR."Year",

    PR."RequireGrading",

    PR."RequireStartCheck",

		PR."StartCheckMinutes"

  FROM USERS UR, PRODUCER PR

  WHERE UR."Producer" = PR."Producer"

  AND UR."User" = vUser;



  EXCEPTION WHEN NO_DATA_FOUND THEN

  results_cur := NULL;

END;



/**

* Procedure to get provider detail from Producer code

* return: provider row

*/

PROCEDURE getprovdetailwithcode(IN vproducer character varying, OUT results_cur cursor_pkg.weakcursor) IS

BEGIN

  OPEN results_cur FOR

  SELECT

    UR."User",

    UR."Level" AS "Level",

    PR."LastName" AS "LastName",

    PR."FirstName" AS "FirstName",

    PR."Producer" AS "Code",

    PR."Year",

    PR."RequireGrading",

    PR."RequireStartCheck",

		PR."StartCheckMinutes"

  FROM PRODUCER PR

  LEFT JOIN USERS UR ON PR."Producer" = UR."Producer"

  WHERE TRIM(PR."Producer") = TRIM(vProducer)

  AND ROWNUM = 1;



  EXCEPTION WHEN NO_DATA_FOUND THEN

  results_cur := NULL;

END;



/**

* Procedure to get patient detail

* return: patient row

*/

PROCEDURE getpatient(IN vpatient integer, OUT results_cur cursor_pkg.weakcursor) IS

BEGIN

  OPEN results_cur FOR

  SELECT

    PT."Patient" AS "Patient",

    PT."First" AS "FirstName",

    PT."Last" AS "LastName",

    PT."Chart" AS "Chart",

    TO_CHAR(FLOOR(MONTHS_BETWEEN(SYSDATE,PT."Birth") / 12)) AS "Age",

    DECODE(PT."Sex",0,'U',1,'M',2,'F',3,'T',4,'X',5,'O','') AS "Gender"

  FROM PATIENT PT

  WHERE PT."Patient" = vPatient;



  EXCEPTION WHEN NO_DATA_FOUND THEN

  results_cur := NULL;

END;



/**

* Procedure to get discipline List for Sessional evaluations

* return: Discipline PK and Description<p/>

*/

PROCEDURE getevaldiscipllist(IN vyear integer, OUT results_cur cursor_pkg.weakcursor) IS

BEGIN

  OPEN results_cur FOR

  SELECT

  "Discipline",

  "Description",

  FPORTAL_PKG.GetDefaultTemplate("Discipline",vYear) AS "Template"

  FROM DISCIPL

  WHERE "GradingType" = 1

  ORDER BY "Discipline";



  EXCEPTION WHEN NO_DATA_FOUND THEN

  results_cur := NULL;

END;



/**

* Procedure to get Template List for Sessional evaluations

* AX-1945 Check if there is Access for SLevel

* return: Template PK and Description<p/>

*/

PROCEDURE getevaltemplatelist(IN vlevel integer, OUT results_cur cursor_pkg.weakcursor) IS

BEGIN

  OPEN results_cur FOR

  SELECT TM."Template", TM."Description", TM."IsDefaultSessional"

  FROM TEMPLATE TM

  WHERE TM."Type" = 1

  AND TM."IsExam" = 0

  AND TM."IsDefaultPeriodic" = 0

  AND TM."SelfEval" = 0

  AND TM."InActive" = 0

  AND (SELECT COUNT(1) FROM TEMPLACC TA WHERE TA."Template" = TM."Template" AND TA."SLevel" = vLevel AND TA."Access" = 0) = 0

  ORDER BY TM."Template";



  EXCEPTION WHEN NO_DATA_FOUND THEN

  results_cur := NULL;

END;



/**

* Procedure to get template information

* AX-1945  Check if there is Access for SLevel

*/

PROCEDURE getevaltemplatedetail(IN vtemplate character varying, IN vlevel integer, OUT results_cur cursor_pkg.weakcursor) IS

BEGIN

  OPEN results_cur FOR

  SELECT

    T."Template",

    T."Description",

    T."IsDefaultSessional",

    T."Qualifier",

    T."Incomplete",

    T."OnlyEvalDisplayedTx",

    NVL((SELECT TA."Access" FROM TEMPLACC TA WHERE TA."Template" = T."Template" AND TA."SLevel" = vLevel), 1) AS "Access"

  FROM TEMPLATE T

  WHERE TRIM(T."Template") = TRIM(vTemplate);



  EXCEPTION WHEN NO_DATA_FOUND THEN

  results_cur := NULL;

END;



/**

* Helper function to get default template used for a discipline

*/

FUNCTION getdefaulttemplate(vdiscipline character varying, vyear integer) RETURN character varying IS

  vDefault  VARCHAR2(100);

BEGIN

  BEGIN

  SELECT DT."Template"

  INTO vDefault

  FROM DTEMPLAT DT, TEMPLATE T

  WHERE DT."Template" = T."Template"

  AND TRIM(DT."Discipline") = TRIM(vDiscipline)

  AND DT."Year" = vYear

  AND T."Type" = 1

  AND T."IsExam" = 0

  AND T."IsDefaultPeriodic" = 0

  AND T."SelfEval" = 0

  AND T."InActive" = 0

  AND ROWNUM = 1;



  EXCEPTION WHEN NO_DATA_FOUND THEN

    vDefault := '';

  END;

  RETURN vDefault;

END;



/**

* Procedure to get list of general questions for evaluation

*/

PROCEDURE getevalgeneralquestions(IN vtemplate character varying, OUT results_cur cursor_pkg.weakcursor) IS

BEGIN

  OPEN results_cur FOR

  SELECT TI."Item",

  TI."Row",

  TI."IsHeading",

  TI."Template",

  TI."Question",

  TI."QuestionText",

  TI.INSTRUCTION,                                   --AX-26600; AX-40621

  TI."IsRequired",

  TI."Scheme",

  TI."Marking",

  TI."TrxSpecific",

  Q."Description",

  S."MarkScheme",

  S."Min",

  S."Max",

  ABS(S."Increment") AS "Increment",

  S."Validate"

  FROM TITEM TI, QUESTION Q, SCHEME S

  WHERE Q."Question" (+)= TI."Question"

  AND S."Scheme" (+) = TI."Scheme"

  AND TRIM(TI."Template") = TRIM(vTemplate)

  AND TI."TrxSpecific" = 0

  ORDER BY TI."Row";



  EXCEPTION WHEN NO_DATA_FOUND THEN

  results_cur := NULL;

END;



/**

* Procedure to get list of treatment specific questions for evaluation

*/

PROCEDURE getevaltxquestions(IN vtemplate character varying, IN vproccode character varying, OUT results_cur cursor_pkg.weakcursor) IS

BEGIN

  OPEN results_cur FOR

  SELECT TI."Item",

  TI."Row",

  TI."IsHeading",

  TI."Template",

  TI."Question",

  TI."QuestionText",

  TI.INSTRUCTION,                       --AX-26600; AX-40621

  TI."IsRequired",

  TI."Scheme",

  TI."Marking",

  TI."TrxSpecific",

  Q."Description",

  S."MarkScheme",

  S."Min",

  S."Max",

  ABS(S."Increment") AS "Increment",

  S."Validate"

  FROM TITEM TI, QUESTION Q, SCHEME S

  WHERE Q."Question" (+)= TI."Question"

  AND S."Scheme" (+) = TI."Scheme"

  AND TRIM(TI."Template") = TRIM(vTemplate)

  AND TI."TrxSpecific" = 1

  AND

  (

    TI."IsLimited" = 0

    OR

    EXISTS (

      SELECT 1

      FROM TITEMPR

      WHERE "Item" = TI."Item"

      AND

      (

        TRIM(vProcCode) BETWEEN "ProcFrom" AND "ProcTo"

        OR

        TRIM(vProcCode) = TRIM("ProcFrom")

        OR

        TRIM(vProcCode) = TRIM("ProcTo")

      )

    )

  )

  ORDER BY TI."Row";



  EXCEPTION WHEN NO_DATA_FOUND THEN

  results_cur := NULL;

END;



/**

* Procedure to check if a treatment can be added to a new evaluation

* param: vGrading INPUT: Grading ID of an existing evaluation

* param: vType INPUT: trx Type of the treatment being validted (TRX.Type)

* param: vId INPUT: trx ID of the treatment being validated (TRX.Id)

* param: vTreatment INPUT: trx Treatment of the treatment being validated (TRX.Treatment)

* param: vResult OUTPUT: (0 = invalid; 1 = valid;)

*/

PROCEDURE validatetemplatetreatment(IN vtemplate character varying, IN vtype integer, IN vid integer, IN vtreatment integer, OUT vresult integer) IS

  vProcedure  VARCHAR2(100);

  vOnlyEvalDisplayedTx INTEGER;

  vCountTItem INTEGER;

BEGIN

  SELECT T."OnlyEvalDisplayedTx"

  INTO vOnlyEvalDisplayedTx

  FROM TEMPLATE T

  WHERE TRIM("Template") = TRIM(vTemplate)

  AND ROWNUM = 1;



  SELECT "Procedure"

  INTO vProcedure

  FROM TRX

  WHERE "Type" = vType

  AND "Id" = vId

  AND "Treatment" = vTreatment

  AND ROWNUM = 1;



  IF vProcedure IS NOT NULL THEN

    BEGIN

      SELECT COUNT(1) INTO vCountTItem

      FROM TITEM TI

      WHERE TRIM("Template") = TRIM(vTemplate)

      AND "TrxSpecific" = 1

      AND

      (

        "IsLimited" = 0

        OR

        EXISTS (

          SELECT 1

          FROM TITEMPR

          WHERE "Item" = TI."Item"

          AND

          (

            TRIM(vProcedure) BETWEEN "ProcFrom" AND "ProcTo"

            OR

            TRIM(vProcedure) = TRIM("ProcFrom")

            OR

            TRIM(vProcedure) = TRIM("ProcTo")

          )

        )

      );

      IF vCountTItem > 0 THEN

        vResult := 1;

      ELSIF vOnlyEvalDisplayedTx = 0 THEN

        vResult := 2;

      ELSE

        vResult := 0;

      END IF;

    END;

  ELSE

    vResult := 2;

  END IF;



  EXCEPTION WHEN NO_DATA_FOUND THEN

  vResult := -1;

END;



/**

* Procedure to check if a treatment can be added to an existing evaluation

* param: vGrading INPUT: Grading ID of an existing evaluation

* param: vType INPUT: trx Type of the treatment being validted (TRX.Type)

* param: vId INPUT: trx ID of the treatment being validated (TRX.Id)

* param: vTreatment INPUT: trx Treatment of the treatment being validated (TRX.Treatment)

* param: vResult OUTPUT: (0 = invalid; 1 = valid;)

* - invalid can be because the existing evaluation already has the treatment, or it does not process the treatment.

*/

PROCEDURE validateevaltreatment(IN vgrading integer, IN vtype integer, IN vid integer, IN vtreatment integer, OUT vresult integer) IS

  vProcedure  VARCHAR2(100);

  vOrigRecNo INTEGER;

  vTemplate  VARCHAR2(100);

  vOnlyEvalDisplayedTx INTEGER;

  vCountTrxGrade INTEGER;

  vCountTItem INTEGER;

BEGIN

  SELECT

    T."Template",

    T."OnlyEvalDisplayedTx"

  INTO

    vTemplate,

    vOnlyEvalDisplayedTx

  FROM GRADING G

  JOIN TEMPLATE T ON G."Template" = T."Template"

  WHERE "Grading" = vGrading

  AND ROWNUM = 1;



  SELECT "Procedure", "OrigRecNo"

  INTO vProcedure, vOrigRecNo

  FROM TRX

  WHERE "Type" = vType

  AND "Id" = vId

  AND "Treatment" = vTreatment

  AND ROWNUM = 1;



  IF vTemplate IS NOT NULL AND vProcedure IS NOT NULL THEN

    BEGIN

      SELECT COUNT(1) INTO vCountTrxGrade

      FROM TRXGRADE TG

      JOIN TRX T ON TG."Type" = T."Type" AND TG."Id" = T."Id" AND TG."Treatment" = T."Treatment"

      WHERE T."OrigRecNo" = vOrigRecNo

      AND TG."Grading" = vGrading;

      --AND TG."Status" = 1;



      IF vCountTrxGrade = 0 THEN

        BEGIN

          SELECT COUNT(1) INTO vCountTItem

          FROM TITEM TI

          WHERE "Template" = vTemplate

          AND "TrxSpecific" = 1

          AND

          (

            "IsLimited" = 0

            OR

            EXISTS (

              SELECT 1

              FROM TITEMPR

              WHERE "Item" = TI."Item"

              AND

              (

                TRIM(vProcedure) BETWEEN "ProcFrom" AND "ProcTo"

                OR

                TRIM(vProcedure) = TRIM("ProcFrom")

                OR

                TRIM(vProcedure) = TRIM("ProcTo")

              )

            )

          );

          IF vCountTItem > 0 THEN

            vResult := 1;

          ELSIF vOnlyEvalDisplayedTx = 0 THEN

            vResult := 2;

          ELSE

            vResult := 0;

          END IF;

        END;

      ELSE

        vResult := 0;

      END IF;

    END;

  ELSE

    vResult := 2;

  END IF;



  EXCEPTION WHEN NO_DATA_FOUND THEN

  vResult := -1;

END;



FUNCTION countevaltxquestions(vitem integer, vproccode character varying) RETURN integer IS

  vCount INTEGER;

BEGIN

  BEGIN

  SELECT COUNT(1)

  INTO vCount

  FROM TITEMPR

  WHERE "Item" = vItem

  AND TRIM(vProcCode) BETWEEN "ProcFrom" AND "ProcTo";



  EXCEPTION WHEN NO_DATA_FOUND THEN

  vCount := 0;

  END;

  RETURN vCount;

END;





/**

* Procedure to get list of scheme items used in particular Template Item

*/

PROCEDURE getevalschemeitem(IN vscheme character varying, OUT results_cur cursor_pkg.weakcursor) IS

BEGIN

  OPEN results_cur FOR

  SELECT * FROM SITEM

  WHERE TRIM("Scheme") = TRIM(vScheme)

  ORDER BY "OrderIdx";

  EXCEPTION WHEN NO_DATA_FOUND THEN

  results_cur := NULL;

END;



/**

* Procedure to get trx

*/

PROCEDURE gettrx(IN vcharttrx integer, OUT results_cur cursor_pkg.weakcursor) IS

BEGIN

  OPEN results_cur FOR

  SELECT

  TR."Type" AS "Type",

  TR."Id" AS "Id",

  TR."Treatment" AS "Treatment",

  TR."Status" AS "Status",

  TR."Site" AS "Site",

  TR."Site2" AS "Site2",

  TR."Surface" AS "Surface",

  TR."Additional" AS "Additional",

  TR."ChartTrx" AS "ChartTrx",

  PT."Patient" AS "Patient",

  PT."First" AS "PtFirstName",

  PT."Last" AS "PtLastName",

  PT."Chart" AS "PtChart",

  TO_CHAR(FLOOR(MONTHS_BETWEEN(SYSDATE,PT."Birth") / 12)) AS "PtAge",

  DECODE(PT."Sex",0,'U',1,'M',2,'F',3,'T',4,'X',5,'O','') AS "PtGender",

  UR."User" AS "Provider",

  UR."First" AS "ProvFirstName",

  UR."Name" AS "ProvLastName",

  UR."Producer" AS "ProvCode",

  PR."Year" AS "ProvYear",

  PRC."Procedure" AS "Procedure",

  PRC."Description" AS "ProcDescription",

  PRC."RequireGrading" AS "RequireGrading",

  PRC."RelValue" AS "RelValue",

  PRC."RequireGrading" AS "ProcRequireGrading",

  PR."RequireGrading" AS "ProvRequireGrading",

  FPORTAL_PKG.RequireGrading(PR."RequireGrading", PRC."RequireGrading", TR."Discipline") AS "GeneralRequireGrading"

  FROM TRX TR, PATIENT PT, PRODUCER PR, USERS UR, PROCEDUR PRC

  WHERE TR."ChartTrx" = vChartTrx

  AND TR."Patient" = PT."Patient"

  AND TR."Producer" = PR."Producer"

  AND TR."Producer" = UR."Producer"

  AND TR."Procedure" = PRC."Procedure"

  AND TR."Deleted" = 0;

  EXCEPTION WHEN NO_DATA_FOUND THEN

  results_cur := NULL;

END;



/*

* Procedure to get trx with Type, ID, and Treatment

*/

PROCEDURE gettrx2(IN vtype integer, IN vid integer, IN vtreatment integer, OUT results_cur cursor_pkg.weakcursor) IS

BEGIN

  OPEN results_cur FOR

  SELECT

  TR."Type" AS "Type",

  TR."Id" AS "Id",

  TR."Treatment" AS "Treatment",

  TR."Status" AS "Status",

  TR."Site" AS "Site",

  TR."Site2" AS "Site2",

  TR."Surface" AS "Surface",

  TR."Additional" AS "Additional",

  TR."ChartTrx" AS "ChartTrx",

  PT."Patient" AS "Patient",

  PT."First" AS "PtFirstName",

  PT."Last" AS "PtLastName",

  PT."Chart" AS "PtChart",

  TO_CHAR(FLOOR(MONTHS_BETWEEN(SYSDATE,PT."Birth") / 12)) AS "PtAge",

  DECODE(PT."Sex",0,'U',1,'M',2,'F',3,'T',4,'X',5,'O','') AS "PtGender",

  UR."User" AS "Provider",

  UR."First" AS "ProvFirstName",

  UR."Name" AS "ProvLastName",

  UR."Producer" AS "ProvCode",

  PR."Year" AS "ProvYear",

  PRC."Procedure" AS "Procedure",

  PRC."Description" AS "ProcDescription",

  PRC."RequireGrading" AS "RequireGrading",

  PRC."RelValue" AS "RelValue",

  PRC."RequireGrading" AS "ProcRequireGrading",

  PR."RequireGrading" AS "ProvRequireGrading",

  FPORTAL_PKG.RequireGrading(PR."RequireGrading", PRC."RequireGrading", TR."Discipline") AS "GeneralRequireGrading"

  FROM TRX TR, PATIENT PT, PRODUCER PR, USERS UR, PROCEDUR PRC

  WHERE TR."Type" = vType

  AND TR."Id" = vID

  AND TR."Treatment" = vTreatment

  AND TR."Patient" = PT."Patient"

  AND TR."Producer" = PR."Producer"

  AND TR."Producer" = UR."Producer"

  AND TR."Procedure" = PRC."Procedure"

  AND TR."Deleted" = 0

  AND ROWNUM = 1;

  EXCEPTION WHEN NO_DATA_FOUND THEN

  results_cur := NULL;

END;



/**

* Procedure to update Grading table in editing mode

*/

PROCEDURE doeditgrading(IN vgrading integer, IN vdate character varying, IN vprovider character varying, IN vinstructor integer, IN vcompetency integer, IN vtimespent double precision, IN vdiscipline character varying, IN vcomment character varying, IN vpassed integer, OUT vresult integer) IS

BEGIN

  UPDATE GRADING

  SET

    "CreateDate" = SYSDATE,

    "Date" = TO_DATE(vDate),						-- AX-40609

    "Producer" = vProvider,

    "Instructor" = vInstructor,

    "IsCompetency" = vCompetency,

    "TimeSpent" = vTimeSpent,

    "Discipline" = vDiscipline,

    "Comment" = vComment,

    "Passed" = vPassed

  WHERE "Grading" = vGrading;

  vResult := 1;

  EXCEPTION WHEN OTHERS THEN

    vResult := 0;

END;



/**

* Procedure to insert into GRADITEM table

*/

PROCEDURE doeditgraditem(IN vgrading integer, IN vtrxspecific integer, IN vrow integer, IN vanswer character varying, IN vcomment character varying, IN vuser integer, OUT vresult integer) IS

  vText  VARCHAR2(40);

  vNote  VARCHAR(4000);

BEGIN

  SELECT "Text", "Note" INTO vText, vNote

  FROM GRADITEM

  WHERE "Grading" = vGrading

  AND "TrxSpecific" = vTrxSpecific

  AND "Row" = vRow;



  IF TRIM(vText) != TRIM(vAnswer) OR ((TRIM(vText) IS NULL OR LENGTH(TRIM(vText)) = 0) AND (TRIM(vAnswer) IS NULL OR LENGTH(TRIM(vAnswer)) = 0)) THEN

    UPDATE GRADITEM

    SET "Text" = vAnswer, "Note" = vComment, "User" = vUser, "Date" = SYSDATE

    WHERE "Grading" = vGrading

    AND "TrxSpecific" = vTrxSpecific

    AND "Row" = vRow;

  ELSE

    UPDATE GRADITEM

    SET "Text" = vAnswer, "Note" = vComment, "User" = vUser

    WHERE "Grading" = vGrading

    AND "TrxSpecific" = vTrxSpecific

    AND "Row" = vRow;

  END IF;



  vResult := 1;

  EXCEPTION WHEN OTHERS THEN

    vResult := 0;

END;



/**

* Procedure to update Grading table in resume mode

*/

PROCEDURE doresumegrading(IN vgrading integer, IN vinstructor integer, IN vincomplete integer, IN vheldforuser integer, IN vtimespent double precision, IN vcomment character varying, IN vpassed integer, OUT vresult integer) IS

  vNewGrading GRADING."Grading"%TYPE;

  vToday      DATE := SYSDATE;

  vProducer GRADING."Producer"%TYPE;

  vYear     GRADING."Year"%TYPE;

  vDate     GRADING."Date"%TYPE;

  vPatient     GRADING."Patient"%TYPE;

  vDiscipline GRADING."Discipline"%TYPE;

  vTemplate     GRADING."Template"%TYPE;

  vPeriod     GRADING."Period"%TYPE;

  vInstructor2     GRADING."Instructor2"%TYPE;

  vInstructor3     GRADING."Instructor3"%TYPE;

  vCompetency     GRADING."IsCompetency"%TYPE;

  vSelfEval     GRADING."SelfEval"%TYPE;

BEGIN

  -- get next sequence of Grading ID

  SELECT GRADING_GRADING_SEQ.nextVal

  INTO vNewGrading FROM DUAL;



  SELECT "Producer", "Year", "Date", "Patient", "Discipline", "Template", "Period", "Instructor2", "Instructor3", "IsCompetency", "SelfEval"

  INTO vProducer, vYear, vDate, vPatient, vDiscipline, vTemplate, vPeriod, vInstructor2, vInstructor3, vCompetency, vSelfEval

  FROM GRADING WHERE "Grading" = vGrading;



  BEGIN

    UPDATE GRADING SET "CreateDate" = vToday, "Deleted" = 1 WHERE "Grading" = vGrading;

  END;



  BEGIN

    INSERT INTO GRADING ("Grading", "Producer", "Year", "Date", "CreateDate",

                         "Instructor", "Patient", "Discipline", "Template", "Deleted",

                         "TimeSpent", "Period", "Instructor2", "Instructor3", "Passed",

                         "Comment", "IsCompetency", "Incomplete", "HeldForUser", "SelfEval")

    VALUES (vNewGrading, vProducer, vYear, vDate, vToday,

            vInstructor, vPatient, vDiscipline, vTemplate, 0,

            vTimeSpent, vPeriod, vInstructor2, vInstructor3, vPassed,

            vComment, vCompetency, vIncomplete, vHeldForUser, vSelfEval);



    vResult := vNewGrading;

  END;



  EXCEPTION WHEN OTHERS THEN

    vResult := 0;

END;



/**

* Procedure to insert into GRADITEM table

*/

PROCEDURE doresumegraditem(IN vgrading integer, IN vnewgrading integer, IN vtrxspecific integer, IN vrow integer, IN vanswer character varying, IN vcomment character varying, IN vuser integer, OUT vresult integer) IS

  vText  VARCHAR2(40);

  vNote  VARCHAR(4000);

  vToday DATE := SYSDATE;

  vIsHeading GRADITEM."IsHeading"%TYPE;

  vQuestionText GRADITEM."QuestionText"%TYPE;

  vType GRADITEM."Type"%TYPE;

  vId GRADITEM."Id"%TYPE;

  vTreatment GRADITEM."Treatment"%TYPE;

  vRelValue GRADITEM."RelValue"%TYPE;

  vScheme GRADITEM."Scheme"%TYPE;

  vDate GRADITEM."Date"%TYPE;

  vItem GRADITEM."Item"%TYPE;

  vTrxGradeCount INTEGER;

BEGIN

  SELECT "Text", "Note", "IsHeading", "QuestionText", "Type", "Id", "Treatment", "RelValue", "Scheme", "Date", "Item"

  INTO vText, vNote, vIsHeading, vQuestionText, vType, vId, vTreatment, vRelValue, vScheme, vDate, vItem

  FROM GRADITEM

  WHERE "Grading" = vGrading

  AND "TrxSpecific" = vTrxSpecific

  AND "Row" = vRow;



  IF TRIM(vText) != TRIM(vAnswer) OR ((TRIM(vText) IS NULL OR LENGTH(TRIM(vText)) = 0) AND (TRIM(vAnswer) IS NULL OR LENGTH(TRIM(vAnswer)) = 0)) THEN

    vDate := vToday;

  END IF;



  BEGIN

    INSERT INTO GRADITEM ("Grading", "TrxSpecific", "Row", "IsHeading", "QuestionText",

                              "Text", "Type", "Id", "Treatment", "RelValue",

                              "Scheme", "User", "Date", "Note", "Item")

        VALUES ( vNewGrading, vTrxSpecific, vRow, vIsHeading, vQuestionText,

                 vAnswer, vType, vID, vTreatment, vRelValue,

                 vScheme, vUser, vDate, vComment, vItem);



    IF vType != 0 AND vID != 0 AND vTreatment != 0 THEN

      BEGIN

        UPDATE TRX

        SET "Grading" = vNewGrading, "ModifiedDate" = TRUNC(SYSDATE)

        WHERE "Type" = vType

        AND "Id" = vID

        AND "Treatment" = vTreatment;

      END;

    END IF;

  END;



  --Check if TRXGRADE exist

  SELECT COUNT(1)

  INTO vTrxGradeCount

  FROM TRXGRADE

  WHERE "Type" = vType

  AND "Id" = vID

  AND "Treatment" = vTreatment

  AND "Grading" = vNewGrading;



  IF vTrxGradeCount = 0 THEN

    BEGIN

      INSERT INTO TRXGRADE ("Type", "Id", "Treatment", "Grading", "Status")

      VALUES ( vType, vID, vTreatment, vNewGrading, 1);

    END;

  END IF;



  vResult := 1;



  EXCEPTION WHEN OTHERS THEN

  vResult := 0;

END;



/**

* Procedure to delete existing evaluation

*/

PROCEDURE deletegrading(IN vgrading integer, OUT vresult integer) IS

BEGIN

  UPDATE GRADING SET "Deleted" = 1 WHERE "Grading" = vGrading;

  vResult := 1;

  EXCEPTION WHEN OTHERS THEN

  vResult := 0;

END;



/**

* Procedure to insert into GRADING table

*/

PROCEDURE dograding(IN vproducer character varying, IN vdate timestamp without time zone, IN vinstructor integer, IN vpatient integer, IN vdiscipline character varying, IN vtemplate character varying, IN vtimespent double precision, IN vpassed integer, IN vcomment character varying, IN vcompetency integer, IN vincomplete integer, IN vheldforuser integer, OUT vresult integer) IS

  vGrading      GRADING."Grading"%TYPE;     -- unique sequence id for GRADING.Grading

  vProducerId   PRODUCER."Producer"%TYPE;		-- student's producer ID, eg 'S1234'.

  vYear         PRODUCER."Year"%TYPE;       -- student's year of study, usually 1~4

  vCreateDate   DATE := SYSDATE;     -- submition date

  vDeleted      INTEGER := 0;

  vPeriod       INTEGER := 0;

  vInstructor2  INTEGER := 0;

  vInstructor3  INTEGER := 0;

  vSelfEval     INTEGER := 0;

BEGIN

  BEGIN

    -- get next sequence of Grading ID

    SELECT GRADING_GRADING_SEQ.nextVal

    INTO vGrading FROM DUAL;

    /*

    -- add Producer info

    SELECT PR."Producer", PR."Year"

    INTO vProducer, vYear

    FROM USERS UR, PRODUCER PR

    WHERE UR."Producer" = PR."Producer"

    AND UR."User" = vStudent

    AND ROWNUM = 1;

    */

    SELECT PR."Producer", PR."Year"

    INTO vProducerId, vYear

    FROM PRODUCER PR

    WHERE TRIM(PR."Producer") = TRIM(vProducer)

    AND ROWNUM = 1;



    INSERT INTO GRADING ("Grading", "Producer", "Year", "Date", "CreateDate",

                         "Instructor", "Patient", "Discipline", "Template", "Deleted",

                         "TimeSpent", "Period", "Instructor2", "Instructor3", "Passed",

                         "Comment", "IsCompetency", "Incomplete", "HeldForUser", "SelfEval")

    VALUES (vGrading, vProducerId, vYear, vDate, vCreateDate,

            vInstructor, vPatient, vDiscipline, vTemplate, vDeleted,

            vTimeSpent, vPeriod, vInstructor2, vInstructor3, vPassed,

            vComment, vCompetency, vIncomplete, vHeldForUser, vSelfEval);



    vResult := vGrading;



    EXCEPTION WHEN OTHERS THEN

    vResult := 0;

  END;

END;



/**

* Procedure to insert into GRADITEM table

*/

PROCEDURE dograditem(IN vgrading integer, IN vtrxspecific integer, IN vrow integer, IN vitem integer, IN vtype integer, IN vid integer, IN vtreatment integer, IN vanswer character varying, IN vuser integer, IN vdate timestamp without time zone, IN vcomment character varying, OUT vresult integer) IS

  vIsHeading    TITEM."IsHeading"%TYPE;

  vQuestionText  VARCHAR2(40);

  vRelValue     PROCEDUR."RelValue"%TYPE := 0;

  vScheme       TITEM."Scheme"%TYPE;



  isValid       INTEGER := 1;

  vTrxGradeCount INTEGER;

BEGIN

  --get TemplateItem detail

  SELECT TI."IsHeading", TI."Scheme", CASE WHEN TI."IsHeading" = 2 THEN Q."Description" ELSE TI."QuestionText" END

  INTO vIsHeading, vScheme, vQuestionText

  FROM TITEM TI, QUESTION Q

  WHERE Q."Question" (+)= TI."Question"

  AND "Item" = vItem

  AND ROWNUM = 1;



  IF vTrxSpecific = 0 THEN

    BEGIN

      INSERT INTO GRADITEM ("Grading", "TrxSpecific", "Row", "IsHeading", "QuestionText",

                            "Text", "Type", "Id", "Treatment", "RelValue",

                            "Scheme", "User", "Date", "Note", "Item")

      VALUES ( vGrading, vTrxSpecific, vRow, vIsHeading, vQuestionText,

               vAnswer, vType, vID, vTreatment, vRelValue,

               vScheme, vUser, vDate, vComment, vItem);

    END;

  ELSE

    -- validate if TRX is valid

    BEGIN

      SELECT PR."RelValue"

      INTO VRelValue

      FROM TRX TR, PROCEDUR PR

      WHERE TR."Procedure" = PR."Procedure"

      AND TR."Type" = vType

      AND TR."Id" = vID

      AND TR."Treatment" = vTreatment

      AND ROWNUM = 1;



      EXCEPTION WHEN NO_DATA_FOUND THEN

      isValid := 0;

    END;



    IF isValid = 1 THEN

      BEGIN

        INSERT INTO GRADITEM ("Grading", "TrxSpecific", "Row", "IsHeading", "QuestionText",

                              "Text", "Type", "Id", "Treatment", "RelValue",

                              "Scheme", "User", "Date", "Note", "Item")

        VALUES ( vGrading, vTrxSpecific, vRow, vIsHeading, vQuestionText,

                 vAnswer, vType, vID, vTreatment, vRelValue,

                 vScheme, vUser, vDate, vComment, vItem);



        UPDATE TRX

        SET "Grading" = vGrading, "ModifiedDate" = TRUNC(SYSDATE)

        WHERE "Type" = vType

        AND "Id" = vID

        AND "Treatment" = vTreatment;



        --Check if TRXGRADE exist

        SELECT COUNT(1)

        INTO vTrxGradeCount

        FROM TRXGRADE

        WHERE "Type" = vType

        AND "Id" = vID

        AND "Treatment" = vTreatment

        AND "Grading" = vGrading;



        IF vTrxGradeCount = 0 THEN

          BEGIN

            INSERT INTO TRXGRADE ("Type", "Id", "Treatment", "Grading", "Status")

            VALUES ( vType, vID, vTreatment, vGrading, 1);

          END;

        END IF;

      END;

    END IF;

  END IF;



  vResult := 1;



  EXCEPTION WHEN OTHERS THEN

  vResult := 0;

END;



/**

* PROCEDURE to copy TRXGRADE FROM one grading to another

*/

PROCEDURE copytrxgrade(IN vprevgrading integer, IN vnewgrading integer) IS

  CURSOR curTrxGrade IS

    SELECT T1.* FROM TRXGRADE T1

    WHERE T1."Grading" = vPrevGrading

    AND NOT EXISTS

    (

      SELECT 1

      FROM TRXGRADE T2

      WHERE T2."Grading" = vNewGrading

      AND T2."Type" = T1."Type"

      AND T2."Id" = T1."Id"

      AND T2."Treatment" = T1."Treatment"

    );

BEGIN

  FOR cTrxGrade IN curTrxGrade

  LOOP

    INSERT INTO TRXGRADE ("Type", "Id", "Treatment", "Grading", "Status")

    VALUES ( cTrxGrade."Type", cTrxGrade."Id", cTrxGrade."Treatment", vNewGrading, cTrxGrade."Status");

  END LOOP;

  COMMIT;

END;



/**

* PROCEDURE to mark TRXGRADE to processed for trx items not listed in TITEM

*/

PROCEDURE updatetrxgrade(IN vtype integer, IN vid integer, IN vtreatment integer, IN vgrading integer, IN vstatus integer, OUT vresult integer) IS

  vTrxGradeCount INTEGER;

BEGIN

  BEGIN

    UPDATE TRX

    SET "Grading" = vGrading, "ModifiedDate" = TRUNC(SYSDATE)

    WHERE "Type" = vType

    AND "Id" = vID

    AND "Treatment" = vTreatment;



    --Check if TRXGRADE exist

    SELECT COUNT(1)

    INTO vTrxGradeCount

    FROM TRXGRADE

    WHERE "Type" = vType

    AND "Id" = vID

    AND "Treatment" = vTreatment

    AND "Grading" = vGrading;



    IF vTrxGradeCount = 0 THEN

      BEGIN

        INSERT INTO TRXGRADE ("Type", "Id", "Treatment", "Grading", "Status")

        VALUES ( vType, vID, vTreatment, vGrading, vStatus);

      END;

    END IF;



    vResult := 1;



    EXCEPTION WHEN OTHERS THEN

    vResult := 0;

  END;

END;



/**

* Procedure to return a list of axium providers that meet the search criteria. <p/>

* param: vSearchString INPUT: string to conduct the search on.<p/>

* param: vSearchOn INPUT: Field in the producer table to search on (0 = Provider #, 1 = LastName, 2 = FirstName, 3 = Year, 4 = Group).</p>

* param: vSearchInactive INPUT: to include inactive providers in the search result (0 = no, 1 = yes)<p/>

* param: vSearchRequireGrading INPUT: to get list of provider based on RequireGrading setting (0 = all, 1 = sessional, 2 = periodic, 3 = sessional and periodic)<p/>

* param: vSortBy INPUT: Sort on (0 = Provider #, 1 = LastName, 2 = FirstName, 3 = Year, 4 = Group)<p/>

* param: vSortDir INPUT: Sort Direction (0 = ASC, 1 = DESC)<p/>

* param: vNumRows INPUT: number of records to return<p/>

* param: vPage INPUT: set of rows (eg. page-3 and numRows-20 = 40 ~ 59 rows)<p/>

* param: vCurrentPage OUTPUT: page number of current records<p/>

* param: vTotalPage OUTPUT: total page numbers of current search criteria<p/>

* param: results_cur OUTPUT: Weak cursor to contain the data retrieved<br/>

*/

-- AX-40621

PROCEDURE doevalprovidersearch(IN vsearchstring character varying, IN vsearchon integer, IN vsearchinactive integer, IN vsearchrequiregrading integer, IN vsortby integer, IN vsortdir integer, IN vnumrows integer, IN vpage integer, OUT vcurrentpage integer, OUT vtotalpage integer, OUT results_cur cursor_pkg.weakcursor) IS

  vMaxRow INTEGER;

  vMinRow INTEGER;

  vKeyword  VARCHAR2(100);

BEGIN

  vKeyword := NLS_UPPER(TRIM(vSearchString));



  SELECT CEIL(COUNT(1)/vNumRows) INTO vTotalPage

  FROM PRODUCER PRD, USERS UR

  WHERE PRD."Producer" = UR."Producer"(+)

  /* AND PRD."RequireGrading" > 0 */

  AND PRD."TypeCode" IN (SELECT PRT."Code" FROM PRODTYPE PRT WHERE PRT."Type" IN (0,1))

  AND

  (

    vKeyword IS NULL OR

    (vSearchOn = 0 AND NLS_UPPER(PRD."Producer") LIKE vKeyword || '%') OR

    (vSearchOn = 1 AND NLS_UPPER(PRD."LastName") LIKE vKeyword || '%') OR

    (vSearchOn = 2 AND NLS_UPPER(PRD."FirstName") LIKE vKeyword || '%') OR

    (vSearchOn = 3 AND NLS_UPPER(PRD."Year") LIKE vKeyword || '%') OR

    (vSearchOn = 4 AND NLS_UPPER(PRD."PGroup") LIKE vKeyword || '%')

  )

  AND

  (

    (vSearchInactive = 0 AND PRD."Inactive" = 0) OR

    (vSearchInactive = 1)

  )

  AND

  (

    (vSearchRequireGrading = 0) OR

    (vSearchRequireGrading = PRD."RequireGrading") OR

    (vSearchRequireGrading = 3 AND PRD."RequireGrading" IN (1,2))

  );



  IF vTotalPage < vPage THEN

  vCurrentPage := vTotalPage;

  ELSIF vPage < 1 THEN

  vCurrentPage := 1;

  ELSE

  vCurrentPage := vPage;

  END IF;



  vMaxRow := vCurrentPage * vNumRows;

  vMinRow := (vCurrentPage - 1) * vNumRows + 1;



  OPEN results_cur FOR

    SELECT R1.* FROM

    (

      SELECT R2.*, ROWNUM AS "RowNum" FROM

      (

        SELECT

          PRD."Producer",

          SUBSTR(TRIM(PRD."FirstName"),1,1) || '. ' || TRIM(PRD."LastName") AS "FullName",

          TRIM(PRD."LastName") AS "LastName",

          TRIM(PRD."FirstName") AS "FirstName",

          PRD."Year",

          PRD."PGroup",

          PRD."Inactive",

          PRD."RequireGrading",

          UR."User"

        FROM PRODUCER PRD, USERS UR

        WHERE PRD."Producer" = UR."Producer"(+)

        /* AND PRD."RequireGrading" > 0 */

        AND PRD."TypeCode" IN (SELECT PRT."Code" FROM PRODTYPE PRT WHERE PRT."Type" IN (0,1))

        AND

        (

          vKeyword IS NULL OR

          (vSearchOn = 0 AND NLS_UPPER(PRD."Producer") LIKE vKeyword || '%') OR

          (vSearchOn = 1 AND NLS_UPPER(PRD."LastName") LIKE vKeyword || '%') OR

          (vSearchOn = 2 AND NLS_UPPER(PRD."FirstName") LIKE vKeyword || '%') OR

          (vSearchOn = 3 AND NLS_UPPER(PRD."Year") LIKE vKeyword || '%') OR

          (vSearchOn = 4 AND NLS_UPPER(PRD."PGroup") LIKE vKeyword || '%')

        )

        AND

        (

          (vSearchInactive = 0 AND PRD."Inactive" = 0) OR

          (vSearchInactive = 1)

        )

        AND

        (

          (vSearchRequireGrading = 0) OR

          (vSearchRequireGrading = PRD."RequireGrading") OR

          (vSearchRequireGrading = 3 AND PRD."RequireGrading" IN (1,2))

        )

        ORDER BY

        --Primary Sort

        CASE WHEN vSortDir = 0 AND vSortBy = 0 THEN NLS_UPPER(PRD."Producer") END ASC,

        CASE WHEN vSortDir = 1 AND vSortBy = 0 THEN NLS_UPPER(PRD."Producer") END DESC,

        CASE WHEN vSortDir = 0 AND vSortBy = 1 THEN NLS_UPPER(PRD."LastName") END ASC,

        CASE WHEN vSortDir = 1 AND vSortBy = 1 THEN NLS_UPPER(PRD."LastName") END DESC,

        CASE WHEN vSortDir = 0 AND vSortBy = 2 THEN NLS_UPPER(PRD."FirstName") END ASC,

        CASE WHEN vSortDir = 1 AND vSortBy = 2 THEN NLS_UPPER(PRD."FirstName") END DESC,

        CASE WHEN vSortDir = 0 AND vSortBy = 3 THEN NLS_UPPER(PRD."Year") END ASC,

        CASE WHEN vSortDir = 1 AND vSortBy = 3 THEN NLS_UPPER(PRD."Year") END DESC,

        CASE WHEN vSortDir = 0 AND vSortBy = 4 THEN NLS_UPPER(PRD."PGroup") END ASC,

        CASE WHEN vSortDir = 1 AND vSortBy = 4 THEN NLS_UPPER(PRD."PGroup") END DESC,

        CASE WHEN vSortDir = 0 AND vSortBy = 5 THEN DECODE(PRD."RequireGrading", 0, 2, 1, 0, 2, 1, 3) END ASC,

        CASE WHEN vSortDir = 1 AND vSortBy = 5 THEN DECODE(PRD."RequireGrading", 0, 2, 1, 0, 2, 1, 3) END DESC,



        --Secondary Sort

        CASE WHEN vSortDir = 0 THEN NLS_UPPER(PRD."FirstName") END ASC,

        CASE WHEN vSortDir = 1 THEN NLS_UPPER(PRD."FirstName") END DESC,



        --Tertiary Sort

        CASE WHEN vSortDir = 0 THEN NLS_UPPER(PRD."LastName") END ASC,

        CASE WHEN vSortDir = 1 THEN NLS_UPPER(PRD."LastName") END DESC,



        --Quaternary Sort

        CASE WHEN vSortDir = 0 THEN NLS_UPPER(PRD."Producer") END ASC,

        CASE WHEN vSortDir = 1 THEN NLS_UPPER(PRD."Producer") END DESC

      ) R2

      WHERE ROWNUM <= vMaxRow

    ) R1

    WHERE "RowNum" >= vMinRow;

END;

/**

* Procedure to return a list of axiUm instructors that meet a search criteria.<p/>

*

* param: vSearchString INPUT: String to conduct the search on.<p/>

* param: vSearchOn INPUT: Field in the user table to search on (0 = user, 1 = logon, 2 = lastName, 3 = firstName, 4 = userLevel, 5 = producer)<p/>

* param: vSearchDeleted INPUT: to include deleted instructors in the search result (0 = no, 1 = yes)<p/>

* param: vSearchExpired INPUT: to include expired instructors in the search result (0 = no, 1 = yes)<p/>

* param: vSortBy INPUT: Sort on (0 = user, 1 = logon, 2 = lastName, 3 = firstName, 4 = userLevel, 5 = producer)<p/>

* param: vSortDir INPUT: Sort Direction (0 = ASC, 1 = DESC)<p/>

* param: vNumRows INPUT: number of records to return<p/>

* param: vPage INPUT: set of rows (eg. page-3 and numRows-20 = 40 ~ 59 rows)<p/>

* param: vCurrentPage OUTPUT: page number of current records<p/>

* param: vTotalPage OUTPUT: total page numbers of current search criteria<p/>

* param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

*/

---- AX-40621

PROCEDURE doevalinstructorsearch(IN vsearchstring character varying, IN vsearchon integer, IN vsearchdeleted integer, IN vsearchexpired integer, IN vsortby integer, IN vsortdir integer, IN vnumrows integer, IN vpage integer, OUT vcurrentpage integer, OUT vtotalpage integer, OUT results_cur cursor_pkg.weakcursor) IS

  vMaxRow INTEGER;

  vMinRow INTEGER;

BEGIN

  SELECT CEIL(COUNT(1)/vNumRows) INTO vTotalPage

  FROM USERS UR, SLEVEL SL

  WHERE UR."Level" = SL."SLevel"

  AND UR."IsInstructor" = 1

  AND UR."CanEvaluate" = 1

  AND

  (

    (vSearchOn = 0 AND UR."User" LIKE vSearchString || '%') OR

    (vSearchOn = 1 AND NLS_UPPER(TRIM(UR."Logon")) LIKE NLS_UPPER(TRIM(vSearchString)) || '%') OR

    (vSearchOn = 2 AND NLS_UPPER(TRIM(UR."Name")) LIKE NLS_UPPER(TRIM(vSearchString)) || '%') OR

    (vSearchOn = 3 AND NLS_UPPER(TRIM(UR."First")) LIKE NLS_UPPER(TRIM(vSearchString)) || '%') OR

    (vSearchOn = 4 AND NLS_UPPER(TRIM(SL."Description")) LIKE NLS_UPPER(TRIM(vSearchString)) || '%') OR

    (vSearchOn = 5 AND NLS_UPPER(TRIM(UR."Producer")) LIKE NLS_UPPER(TRIM(vSearchString)) || '%')

  )

  AND

  (

    (vSearchDeleted = 0 AND UR."Deleted" = 0) OR

    (vSearchDeleted = 1)

  )

  AND

  (

    (vSearchExpired = 0 AND (UR."EffDate" <= TRUNC(SYSDATE) OR UR."EffDate" IS NULL) AND (UR."ExpDate" >= TRUNC(SYSDATE) OR UR."ExpDate" IS NULL)) OR

    (vSearchExpired = 1)

  );



  IF vTotalPage < vPage THEN

  vCurrentPage := vTotalPage;

  ELSIF vPage < 1 THEN

  vCurrentPage := 1;

  ELSE

  vCurrentPage := vPage;

  END IF;



  vMaxRow := vCurrentPage * vNumRows;

  vMinRow := (vCurrentPage - 1) * vNumRows + 1;



  OPEN results_cur FOR

    SELECT U1.* FROM

    (

      SELECT U2.*, ROWNUM AS "RowNum" FROM

      (

        SELECT

          UR."User",

          TRIM(UR."Logon") AS "Logon",

          TRIM(UR."Name") AS "LastName",

          TRIM(UR."First") AS "FirstName",

          SUBSTR(TRIM(UR."First"),1,1) || '. ' || TRIM(UR."Name") AS "FullName",

          NVL(TRIM(SL."Description"),'') AS "Level",

          TRIM(UR."Producer") AS "Producer",

          UR."Deleted",

          CASE WHEN (UR."EffDate" <= TRUNC(SYSDATE) OR UR."EffDate" IS NULL) THEN 0 ELSE 1 END AS "NotEffective",

          CASE WHEN (UR."ExpDate" >= TRUNC(SYSDATE) OR UR."ExpDate" IS NULL) THEN 0 ELSE 1 END AS "Expired"

        FROM USERS UR, SLEVEL SL

        WHERE UR."Level" = SL."SLevel"

        AND UR."IsInstructor" = 1

        AND UR."CanEvaluate" = 1

        AND

        (

          (vSearchOn = 0 AND UR."User" LIKE vSearchString || '%') OR

          (vSearchOn = 1 AND NLS_UPPER(TRIM(UR."Logon")) LIKE NLS_UPPER(TRIM(vSearchString)) || '%') OR

          (vSearchOn = 2 AND NLS_UPPER(TRIM(UR."Name")) LIKE NLS_UPPER(TRIM(vSearchString)) || '%') OR

          (vSearchOn = 3 AND NLS_UPPER(TRIM(UR."First")) LIKE NLS_UPPER(TRIM(vSearchString)) || '%') OR

          (vSearchOn = 4 AND NLS_UPPER(TRIM(SL."Description")) LIKE NLS_UPPER(TRIM(vSearchString)) || '%') OR

          (vSearchOn = 5 AND NLS_UPPER(TRIM(UR."Producer")) LIKE NLS_UPPER(TRIM(vSearchString)) || '%')

        )

        AND

        (

          (vSearchDeleted = 0 AND UR."Deleted" = 0) OR

          (vSearchDeleted = 1)

        )

        AND

        (

          (vSearchExpired = 0 AND (UR."EffDate" <= TRUNC(SYSDATE) OR UR."EffDate" IS NULL) AND (UR."ExpDate" >= TRUNC(SYSDATE) OR UR."ExpDate" IS NULL)) OR

          (vSearchExpired = 1)

        )

        ORDER BY

        --Primary Sort

        CASE WHEN vSortDir = 0 AND vSortBy = 0 THEN UR."User" END ASC,

        CASE WHEN vSortDir = 1 AND vSortBy = 0 THEN UR."User" END DESC,

        CASE WHEN vSortDir = 0 AND vSortBy = 1 THEN NLS_UPPER("Logon") END ASC,

        CASE WHEN vSortDir = 1 AND vSortBy = 1 THEN NLS_UPPER("Logon") END DESC,

        CASE WHEN vSortDir = 0 AND vSortBy = 2 THEN NLS_UPPER("Name") END ASC,

        CASE WHEN vSortDir = 1 AND vSortBy = 2 THEN NLS_UPPER("Name") END DESC,

        CASE WHEN vSortDir = 0 AND vSortBy = 3 THEN NLS_UPPER("First") END ASC,

        CASE WHEN vSortDir = 1 AND vSortBy = 3 THEN NLS_UPPER("First") END DESC,

        CASE WHEN vSortDir = 0 AND vSortBy = 4 THEN NLS_UPPER("Level") END ASC,

        CASE WHEN vSortDir = 1 AND vSortBy = 4 THEN NLS_UPPER("Level") END DESC,

        CASE WHEN vSortDir = 0 AND vSortBy = 5 THEN NLS_UPPER(UR."Producer") END ASC,

        CASE WHEN vSortDir = 1 AND vSortBy = 5 THEN NLS_UPPER(UR."Producer") END DESC,



        --Secondary Sort

        CASE WHEN vSortDir = 0 THEN NLS_UPPER("First") END ASC,

        CASE WHEN vSortDir = 1 THEN NLS_UPPER("First") END DESC,



        --Tertiary Sort

        CASE WHEN vSortDir = 0 THEN NLS_UPPER("Name") END ASC,

        CASE WHEN vSortDir = 1 THEN NLS_UPPER("Name") END DESC,



        --Quaternary Sort

        CASE WHEN vSortDir = 0 THEN UR."User" END ASC,

        CASE WHEN vSortDir = 1 THEN UR."User" END DESC

      ) U2

      WHERE ROWNUM <= vMaxRow

    ) U1

    WHERE "RowNum" >= vMinRow;

  EXCEPTION WHEN NO_DATA_FOUND THEN

  results_cur := NULL;

END;



/**

* Procedure to return a list of axiUm instructors that meet a search criteria.<p/>

*

* param: vSearchString INPUT: String to conduct the search on.<p/>

* param: vSearchOn INPUT: Field in the user table to search on (0 = lastName, 1 = firstName, 2 = chart)<p/>

* param: vSortBy INPUT: Sort on (0 = lastName, 1 = firstName, 2 = chart, 3 = gender)<p/>

* param: vSortDir INPUT: Sort Direction (0 = ASC, 1 = DESC)<p/>

* param: vNumRows INPUT: number of records to return<p/>

* param: vPage INPUT: set of rows (eg. page-3 and numRows-20 = 40 ~ 59 rows)<p/>

* param: vCurrentPage OUTPUT: page number of current records<p/>

* param: vTotalPage OUTPUT: total page numbers of current search criteria<p/>

* param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br/>

*/

-- AX-40621

PROCEDURE dopatientsearch(IN vsearchstring character varying, IN vsearchon integer, IN vsortby integer, IN vsortdir integer, IN vnumrows integer, IN vpage integer, OUT vcurrentpage integer, OUT vtotalpage integer, OUT results_cur cursor_pkg.weakcursor) IS

  vMaxRow INTEGER;

  vMinRow INTEGER;

BEGIN

  SELECT CEIL(COUNT(1)/vNumRows) INTO vTotalPage

  FROM PATIENT PT

  WHERE PT."Deleted" = 0

  AND PT."IsPatient" = 1

  AND

  (

    (vSearchOn = 0 AND NLS_UPPER(TRIM(PT."Last")) LIKE NLS_UPPER(TRIM(vSearchString)) || '%') OR

    (vSearchOn = 1 AND NLS_UPPER(TRIM(PT."First")) LIKE NLS_UPPER(TRIM(vSearchString)) || '%') OR

    (vSearchOn = 2 AND NLS_UPPER(TRIM(PT."Chart")) LIKE NLS_UPPER(TRIM(vSearchString)) || '%')

  );



  IF vTotalPage < vPage THEN

  vCurrentPage := vTotalPage;

  ELSIF vPage < 1 THEN

  vCurrentPage := 1;

  ELSE

  vCurrentPage := vPage;

  END IF;



  vMaxRow := vCurrentPage * vNumRows;

  vMinRow := (vCurrentPage - 1) * vNumRows + 1;



  OPEN results_cur FOR

    SELECT P1.* FROM

    (

      SELECT P2.*, ROWNUM AS "RowNum" FROM

      (

        SELECT

          PT."Patient",

          TRIM(PT."Last") AS "LastName",

          TRIM(PT."First") AS "FirstName",

          PT."Chart",

          PT."Sex" AS "Gender",

          SUBSTR(TRIM(PT."First"),1,1) || '. ' || TRIM(PT."Last") AS "FullName"

        FROM PATIENT PT

        WHERE PT."Deleted" = 0

        AND PT."IsPatient" = 1

        AND

        (

          (vSearchOn = 0 AND NLS_UPPER(TRIM(PT."Last")) LIKE NLS_UPPER(TRIM(vSearchString)) || '%') OR

          (vSearchOn = 1 AND NLS_UPPER(TRIM(PT."First")) LIKE NLS_UPPER(TRIM(vSearchString)) || '%') OR

          (vSearchOn = 2 AND NLS_UPPER(TRIM(PT."Chart")) LIKE NLS_UPPER(TRIM(vSearchString)) || '%')

        )

        ORDER BY

        --Primary Sort

        CASE WHEN vSortDir = 0 AND vSortBy = 0 THEN NLS_UPPER("Last") END ASC,

        CASE WHEN vSortDir = 1 AND vSortBy = 0 THEN NLS_UPPER("Last") END DESC,

        CASE WHEN vSortDir = 0 AND vSortBy = 1 THEN NLS_UPPER("First") END ASC,

        CASE WHEN vSortDir = 1 AND vSortBy = 1 THEN NLS_UPPER("First") END DESC,

        CASE WHEN vSortDir = 0 AND vSortBy = 2 THEN NLS_UPPER("Chart") END ASC,

        CASE WHEN vSortDir = 1 AND vSortBy = 2 THEN NLS_UPPER("Chart") END DESC,

        CASE WHEN vSortDir = 0 AND vSortBy = 3 THEN NLS_UPPER("Sex") END ASC,

        CASE WHEN vSortDir = 1 AND vSortBy = 3 THEN NLS_UPPER("Sex") END DESC,



        --Secondary Sort

        CASE WHEN vSortDir = 0 THEN "First" END ASC,

        CASE WHEN vSortDir = 1 THEN "First" END DESC,



        --Tertiary Sort

        CASE WHEN vSortDir = 0 THEN "Last" END ASC,

        CASE WHEN vSortDir = 1 THEN "Last" END DESC,



        --Quaternary Sort

        CASE WHEN vSortDir = 0 THEN PT."Patient" END ASC,

        CASE WHEN vSortDir = 1 THEN PT."Patient" END DESC

      ) P2

      WHERE ROWNUM <= vMaxRow

    ) P1

    WHERE "RowNum" >= vMinRow;

  EXCEPTION WHEN NO_DATA_FOUND THEN

  results_cur := NULL;

END;



/**

* Procedure to GET a list of unevaluted treatments for the indicated date<p/>

*

* param: vSearchProviderString INPUT: Provider keyword to conduct search on. Checks TRX.Producer<p/>

* param: vSearchProviderOn INPUT: Provider field to conduct search on. (0 = lastName, 1 = firstName, 2 = provider #)<p/>

* param: vSearchInstructorString INPUT: Instructor keyword to conduct search on. Checks TRX.AppUser<p/>

* param: vSearchInstructorOn INPUT: Instructor field to conduct search on. (0 = lastName, 1 = firstName)<p/>

* param: vDateFrom INPUT: Begining approved date to filter the list in DD-MMM-YY format (eg. 03-MAR-2010)<p/>

* param: vDateTo INPUT: Ending approved date to filter the list in DD-MMM-YY format (eg. 03-MAR-2010)<p/>

* param: vGroupBy INPUT: criteria in the table to group by (0 = no group, 1 = patient, 2 = provider, 3 = instructor)<p/>

* param: vGroupDir INPUT: Group Direction (0 = ASC, 1 = DESC)<p/>

* param: vSortBy INPUT: Sort on (0 = ProviderCode, 1 = ProviderName, 2 = TxDate, 3 = Instructor, 4 = Procedure, 5 = TxDescription, 6 = TxStatus, 7 = TxSite, 8 = Patient, 9 = PatientChart, 10 = TxClaim#, 11 = ApprovalDate)<p/>

* param: vSortDir INPUT: Sort Direction (0 = ASC, 1 = DESC)<p/>

* param: vMedicaidCode IN: list of procedure codes defined as Medicaid code<p/>

* param: results_cur OUTPUT: Weak cursor to contain the data retrieved<br/>

*/

--AX-40621

PROCEDURE getunevaluatedtxlist(IN vproducer character varying, IN vinstructor integer, IN vpatient integer, IN vdatefrom character varying, IN vdateto character varying, IN vgroupby integer, IN vgroupdir integer, IN vsortby integer, IN vsortdir integer, IN vmedicaidcode character varying, OUT results_cur cursor_pkg.weakcursor) IS

BEGIN



  OPEN results_cur FOR

		SELECT

			SUBSTR(TRIM(PROD."FirstName"),1,1) || '. ' || TRIM(PROD."LastName") AS "ProvFullName",

			SUBSTR(TRIM(PT."First"),1,1) || '. ' || TRIM(PT."Last") AS "PtFullName",

			SUBSTR(TRIM(IUR."First"),1,1) || '. ' || TRIM(IUR."Name") AS "InstFullName",

			SUBSTR(TRIM(PROD."FirstName"),1,1) || TRIM(PROD."LastName") AS "ProvFLast",

			TRIM(PROD."LastName") || SUBSTR(TRIM(PROD."FirstName"),1,1) AS "ProvLFirst",

			SUBSTR(TRIM(PT."First"),1,1) || TRIM(PT."Last") AS "PtFLast",

			TRIM(PT."Last") || SUBSTR(TRIM(PT."First"),1,1) AS "PtLFirst",

			SUBSTR(TRIM(IUR."First"),1,1) || TRIM(IUR."Name") AS "InstFLast",

			TRIM(IUR."Name") || SUBSTR(TRIM(IUR."First"),1,1) AS "InstLFirst",

			PROD."Producer" AS "Producer",

			PROD."FirstName" AS "ProvFirstName",

			PROD."LastName" AS "ProvLastName",

			PT."Patient",

			PT."Chart" AS "PtChart",

			TO_CHAR(FLOOR(MONTHS_BETWEEN(SYSDATE,PT."Birth") / 12)) AS "PtAge",

			DECODE(PT."Sex",0,'U',1,'M',2,'F',3,'T',4,'X',5,'O','') AS "PtGender",

			PT."First" AS "PtFirstName",

			PT."Last" AS "PtLastName",

			IUR."User" AS "Instructor",

			IUR."First" AS "InstFirstName",

			IUR."Name" AS "InstLastName",

			PROC."Procedure" AS "Procedure",

			PROC."Description" AS "Description",

			TR."Additional" AS "Additional",

			TR."Type",

			TR."Id",

			TR."ChartTrx",

			TR."Treatment",

			TR."Status" AS "Status",

			TR."Site",

			TR."Surface",

			TO_CHAR(TR."TreatmentDate",'MON DD, YYYY') AS "TxDate",

			TO_CHAR(TR."AppDate",'MON DD, YYYY') AS "AppDate"

		FROM TRX TR, PROCEDUR PROC, PRODUCER PROD, USERS IUR, PATIENT PT, DISCIPL DIS, GRADING G

		WHERE PROC."Procedure" (+)= TR."Procedure"

		AND PROD."Producer" (+)= TR."Producer"

		AND IUR."User" (+)= TR."AppUser"

		AND DIS."Class"(+)= TR."Discipline"

		AND G."Grading" (+)= TR."Grading"

		AND TR."Patient" = PT."Patient"

		AND TR."Status" IN ('C','I')

		AND TR."Deleted" = 0

		AND TR."Type" = 1

		AND (vMedicaidCode is null or (PROC."Procedure" NOT IN ( select regexp_substr(vMedicaidCode,'[^,]+', 1, level) from dual connect by regexp_substr(vMedicaidCode,'[^,]+', 1, level) is not null)))

		AND PROC."RequireGrading" = 1

		AND PROD."RequireGrading" > 0

		AND

		(

			TR."Grading" = 0

			OR

			(

				G."Deleted" = 1 AND

				0 = (SELECT COUNT(*) FROM GRADING

					WHERE "Deleted" = 0

					AND "Grading" IN

					(

						SELECT DISTINCT "Grading"

						FROM TRXGRADE TG

						WHERE TG."Type" = TR."Type"

						AND TG."Id" = TR."Id"

						AND TG."Treatment" = TR."Treatment"

					)

				)

			)

		)

		AND

		(

			DIS."GradingType" = 1 OR

			(DIS."GradingType" = 0 AND PROD."RequireGrading" = 1) OR

			TR."Discipline" = ' ' OR

			0 = (SELECT COUNT(1) FROM DISCIPL D WHERE D."Class" = TR."Discipline")

		)

		AND

		(

			(TRIM(vProducer) IS NULL OR LENGTH(TRIM(vProducer)) = 0) OR

			TRIM(TR."Producer") = TRIM(vProducer)

		)

		AND

		(

			0 = vInstructor OR

			IUR."User" = vInstructor

		)

		AND

		(

			0 = vPatient OR

			TR."Patient" = vPatient

		)

		AND

		(

			TR."TreatmentDate" BETWEEN vDateFrom AND vDateTo

		)

		GROUP BY PROD."FirstName", PROD."LastName", PT."First", PT."Last", IUR."First", IUR."Name", PROD."Producer", PROD."FirstName",

			PROD."LastName", PT."Patient", PT."Chart", PT."Birth", PT."Sex", PT."First", PT."Last", IUR."User", IUR."First", IUR."Name",

			PROC."Procedure", PROC."Description", TR."Additional", TR."Type", TR."Id", TR."ChartTrx",

			TR."Treatment", TR."Status", TR."Site", TR."Surface", TR."TreatmentDate", TR."AppDate"





		ORDER BY

		--Primary Sort

		CASE WHEN vGroupBy = 1 AND vGroupDir = 0 THEN NLS_UPPER(TRIM(PT."First" || PT."Last" || PT."Chart")) END ASC,

		CASE WHEN vGroupBy = 1 AND vGroupDir = 1 THEN NLS_UPPER(TRIM(PT."First" || PT."Last" || PT."Chart")) END DESC,

		CASE WHEN vGroupBy = 1 AND vGroupDir = 2 THEN NLS_UPPER(TRIM(PT."Last" || PT."First" || PT."Chart")) END ASC,

		CASE WHEN vGroupBy = 1 AND vGroupDir = 3 THEN NLS_UPPER(TRIM(PT."Last" || PT."First" || PT."Chart")) END DESC,

		CASE WHEN vGroupBy = 2 AND vGroupDir = 0 THEN NLS_UPPER(TRIM(PROD."FirstName" || PROD."LastName" || PROD."Producer")) END ASC,

		CASE WHEN vGroupBy = 2 AND vGroupDir = 1 THEN NLS_UPPER(TRIM(PROD."FirstName" || PROD."LastName" || PROD."Producer")) END DESC,

		CASE WHEN vGroupBy = 2 AND vGroupDir = 2 THEN NLS_UPPER(TRIM(PROD."LastName" || PROD."FirstName" || PROD."Producer")) END ASC,

		CASE WHEN vGroupBy = 2 AND vGroupDir = 3 THEN NLS_UPPER(TRIM(PROD."LastName" || PROD."FirstName" || PROD."Producer")) END DESC,

		CASE WHEN vGroupBy = 3 AND vGroupDir = 0 THEN NLS_UPPER(TRIM(IUR."First" || IUR."Name")) END ASC,

		CASE WHEN vGroupBy = 3 AND vGroupDir = 1 THEN NLS_UPPER(TRIM(IUR."First" || IUR."Name")) END DESC,

		CASE WHEN vGroupBy = 3 AND vGroupDir = 2 THEN NLS_UPPER(TRIM(IUR."Name" || IUR."First")) END ASC,

		CASE WHEN vGroupBy = 3 AND vGroupDir = 3 THEN NLS_UPPER(TRIM(IUR."Name" || IUR."First")) END DESC,



		--Secondary Sort

		CASE WHEN vSortBy = 0 AND (vSortDir = 0 OR vSortDir = 2) THEN NLS_UPPER(TRIM(PROD."Producer")) END ASC,

		CASE WHEN vSortBy = 0 AND (vSortDir = 1 OR vSortDir = 3) THEN NLS_UPPER(TRIM(PROD."Producer")) END DESC,

		CASE WHEN vSortBy = 1 AND vSortDir = 0 THEN NLS_UPPER(TRIM(SUBSTR(TRIM(PROD."FirstName"),1,1) || TRIM(PROD."LastName"))) END ASC,

		CASE WHEN vSortBy = 1 AND vSortDir = 1 THEN NLS_UPPER(TRIM(SUBSTR(TRIM(PROD."FirstName"),1,1) || TRIM(PROD."LastName"))) END DESC,

		CASE WHEN vSortBy = 1 AND vSortDir = 2 THEN NLS_UPPER(TRIM(TRIM(PROD."LastName") || SUBSTR(TRIM(PROD."FirstName"),1,1))) END ASC,

		CASE WHEN vSortBy = 1 AND vSortDir = 3 THEN NLS_UPPER(TRIM(TRIM(PROD."LastName") || SUBSTR(TRIM(PROD."FirstName"),1,1))) END DESC,

		CASE WHEN vSortBy = 2 AND (vSortDir = 0 OR vSortDir = 2) THEN TR."TreatmentDate" END ASC,

		CASE WHEN vSortBy = 2 AND (vSortDir = 1 OR vSortDir = 3) THEN TR."TreatmentDate" END DESC,

		CASE WHEN vSortBy = 3 AND vSortDir = 0 THEN NLS_UPPER(TRIM(SUBSTR(TRIM(IUR."First"),1,1) || '. ' || TRIM(IUR."Name"))) END ASC,

		CASE WHEN vSortBy = 3 AND vSortDir = 1 THEN NLS_UPPER(TRIM(SUBSTR(TRIM(IUR."First"),1,1) || '. ' || TRIM(IUR."Name"))) END DESC,

		CASE WHEN vSortBy = 3 AND vSortDir = 2 THEN NLS_UPPER(TRIM(TRIM(IUR."Name") || SUBSTR(TRIM(IUR."First"),1,1))) END ASC,

		CASE WHEN vSortBy = 3 AND vSortDir = 3 THEN NLS_UPPER(TRIM(TRIM(IUR."Name") || SUBSTR(TRIM(IUR."First"),1,1))) END DESC,

		CASE WHEN vSortBy = 4 AND (vSortDir = 0 OR vSortDir = 2) THEN NLS_UPPER(TRIM(TR."Procedure")) END ASC,

		CASE WHEN vSortBy = 4 AND (vSortDir = 1 OR vSortDir = 3) THEN NLS_UPPER(TRIM(TR."Procedure")) END DESC,

		CASE WHEN vSortBy = 5 AND (vSortDir = 0 OR vSortDir = 2) THEN NLS_UPPER(TRIM(TR."Description")) END ASC,

		CASE WHEN vSortBy = 5 AND (vSortDir = 1 OR vSortDir = 3) THEN NLS_UPPER(TRIM(TR."Description")) END DESC,

		CASE WHEN vSortBy = 6 AND (vSortDir = 0 OR vSortDir = 2) THEN NLS_UPPER(TRIM(TR."Status")) END ASC,

		CASE WHEN vSortBy = 6 AND (vSortDir = 1 OR vSortDir = 3) THEN NLS_UPPER(TRIM(TR."Status")) END DESC,

		CASE WHEN vSortBy = 7 AND (vSortDir = 0 OR vSortDir = 2) THEN TR."Site" END ASC,

		CASE WHEN vSortBy = 7 AND (vSortDir = 1 OR vSortDir = 3) THEN TR."Site" END DESC,

		CASE WHEN vSortBy = 8 AND vSortDir = 0 THEN NLS_UPPER(TRIM(SUBSTR(TRIM(PT."First"),1,1) || TRIM(PT."Last"))) END ASC,

		CASE WHEN vSortBy = 8 AND vSortDir = 1 THEN NLS_UPPER(TRIM(SUBSTR(TRIM(PT."First"),1,1) || TRIM(PT."Last"))) END DESC,

		CASE WHEN vSortBy = 8 AND vSortDir = 2 THEN NLS_UPPER(TRIM(TRIM(PT."Last") || SUBSTR(TRIM(PT."First"),1,1))) END ASC,

		CASE WHEN vSortBy = 8 AND vSortDir = 3 THEN NLS_UPPER(TRIM(TRIM(PT."Last") || SUBSTR(TRIM(PT."First"),1,1))) END DESC,

		CASE WHEN vSortBy = 9 AND (vSortDir = 0 OR vSortDir = 2) THEN NLS_UPPER(TRIM(PT."Chart")) END ASC,

		CASE WHEN vSortBy = 9 AND (vSortDir = 1 OR vSortDir = 3) THEN NLS_UPPER(TRIM(PT."Chart")) END DESC,

		CASE WHEN vSortBy = 10 AND (vSortDir = 0 OR vSortDir = 2) THEN TR."Id" END ASC,

		CASE WHEN vSortBy = 10 AND (vSortDir = 1 OR vSortDir = 3) THEN TR."Id" END DESC,

		CASE WHEN vSortBy = 11 AND (vSortDir = 0 OR vSortDir = 2) THEN TR."AppDate" END ASC,

		CASE WHEN vSortBy = 11 AND (vSortDir = 1 OR vSortDir = 3) THEN TR."AppDate" END DESC,



		--Tertiary Sort

		CASE WHEN vSortDir = 0 THEN PROC."Procedure" END ASC,

		CASE WHEN vSortDir = 1 THEN PROC."Procedure" END DESC,



		--Quaternary Sort

		CASE WHEN vSortDir = 0 THEN TR."Site" END ASC,

		CASE WHEN vSortDir = 1 THEN TR."Site" END DESC;



    EXCEPTION WHEN NO_DATA_FOUND THEN

  results_cur := NULL;

END;



/**

* Procedure to GET a list of evaluated forms from Grading table.<p/>

*

* param: vProvider INPUT: Producer ID of the provider graded. (blank = search all, else = PRODUCER.Producer)<p/>

* param: vInstructor INPUT: User ID of the instructor grading the form. (0 = search all, 1+ = GRADING.Instructor)<p/>

* param: vPatient INPUT: Patient ID of the form. (0 = search all, 1+ = GRADING.Patient)<p/>

* param: vDiscipline INPUT: Discipline the student was working on. (Blank = search all, else = find exact match)<p/>

* param: vShowGeneral INPUT: Show General/Patient evaluation (0 = show all, 1 = show general only, 2 = show patient only).<p/>

* param: vTemplate INPUT: Template ID used for grading prt to TEMPLATE.Template.<p/>

* param: vIsExam INPUT: Search criteria if the template is exam<p/>

* param: vIsCompetency INPUT: Search criteria if the grading is competency evaluation<p/>

* param: vIsEvaluation INPUT: Search criteria if the grading is regular evaluation<p/>

* param: vIncomplete INPUT: Search criteria if the grading is held (0 = completed, 1 = incomplete, 2 = all)<p/>

* param: vHeldForUser INPUT: Search criteria for held instructor if the form is incomplete<p/>

* param: vDateFrom INPUT: Begining grading date to filter the list in DD-MMM-YY format (eg. 03-MAR-2010)<p/>

* param: vDateTo INPUT: Ending grading date to filter the list in DD-MMM-YY format (eg. 03-MAR-2010)<p/>

* param: vDeleted INPUT: filter option to show deleted evaluations as well (0 = do not show deleted, 1 = show deleted)<p/>

* param: vLevel INPUT: SLevel to check if has access to the Evaluation<p/>

* param: vNumRows INPUT: number of records to return<p/>

* param: vPage INPUT: page numer - set of rows (eg. page-3 and numRows-20 = 40 ~ 59 rows)<p/>

* param: vCurrentPage OUTPUT: actual page number of current records<p/>

* param: vTotalPage OUTPUT: total page number<p/>

* param: results_cur OUTPUT: Weak cursor to contain the data retrieved<br/>

*/

PROCEDURE getevaluationlist(IN vproducer character varying, IN vinstructor integer, IN vpatient integer, IN vdiscipline character varying, IN vtemplate character varying, IN vshowgeneral integer, IN visexam integer, IN viscompetency integer, IN visevaluation integer, IN vincomplete integer, IN vheldforuser integer, IN vdatefrom character varying, IN vdateto character varying, IN vdeleted integer, IN vlevel integer, IN vnumrows integer, IN vpage integer, OUT vcurrentpage integer, OUT vtotalpage integer, OUT results_cur cursor_pkg.weakcursor) IS

  vMaxRow INTEGER;

  vMinRow INTEGER;

BEGIN

  SELECT CEIL(COUNT(1)/vNumRows) INTO vTotalPage

  FROM GRADING GR, TEMPLATE T

  WHERE GR."Template" = T."Template"

  AND GR."Date" BETWEEN vDateFrom AND vDateTo

  AND

  (

    0 = vShowGeneral OR

    (1 = vShowGeneral AND GR."Patient" = 0) OR

    (2 = vShowGeneral AND GR."Patient" != 0 AND (0 = vPatient OR GR."Patient" = vPatient))

  )

  AND

  (

    0 < vDeleted OR

    GR."Deleted" = vDeleted

  )

  AND

  (

    (TRIM(vProducer) IS NULL OR LENGTH(TRIM(vProducer)) = 0) OR

    TRIM(GR."Producer") = TRIM(vProducer)

  )

  AND

  (

    0 = vInstructor OR

    GR."Instructor" = vInstructor

  )

  AND

  (

    (TRIM(vDiscipline) IS NULL OR LENGTH(TRIM(vDiscipline)) = 0) OR

    TRIM(GR."Discipline") = TRIM(vDiscipline)

  )

  AND

  (

    (TRIM(vTemplate) IS NULL OR LENGTH(TRIM(vTemplate)) = 0) OR

    TRIM(GR."Template") = TRIM(vTemplate)

  )

  AND

  (

    2 = vIncomplete OR

    (0 = vIncomplete AND GR."Incomplete" = 0) OR

    (

      1 = vIncomplete AND

      GR."Incomplete" = 1 AND

      (

        0 = vHeldForUser OR

        GR."HeldForUser" = vHeldForUser

      )

    )

  )

  AND

  (

    (1 = vIsExam AND 1 = vIsCompetency AND 1 = vIsEvaluation) OR

    (1 = vIsExam AND 1 = vIsCompetency AND 0 = vIsEvaluation AND (GR."IsCompetency" = 1 OR T."IsExam" = 1)) OR

    (1 = vIsExam AND 0 = vIsCompetency AND 1 = vIsEvaluation AND (GR."IsCompetency" = 0 OR T."IsExam" = 1)) OR

    (0 = vIsExam AND 1 = vIsCompetency AND 1 = vIsEvaluation AND (T."IsExam" = 0)) OR

    (1 = vIsExam AND 0 = vIsCompetency AND 0 = vIsEvaluation AND (T."IsExam" = 1)) OR

    (0 = vIsExam AND 1 = vIsCompetency AND 0 = vIsEvaluation AND (GR."IsCompetency" = 1)) OR

    (0 = vIsExam AND 0 = vIsCompetency AND 1 = vIsEvaluation AND (GR."IsCompetency" = 0 AND T."IsExam" = 0))

  );



  IF vTotalPage < vPage THEN

  vCurrentPage := vTotalPage;

  ELSIF vPage < 1 THEN

  vCurrentPage := 1;

  ELSE

  vCurrentPage := vPage;

  END IF;



  vMaxRow := vCurrentPage * vNumRows;

  vMinRow := (vCurrentPage - 1) * vNumRows + 1;



  OPEN results_cur FOR

    SELECT T2.* FROM

    (

      SELECT T1.*, ROWNUM AS "RowNum" FROM

      (

        SELECT

          SUBSTR(TRIM(PR."FirstName"),1,1) || '. ' || TRIM(PR."LastName") AS "ProvFullName",

          SUBSTR(TRIM(UR."First"),1,1) || '. ' || TRIM(UR."Name") AS "InstFullName",

          SUBSTR(TRIM(PT."First"),1,1) || '. ' || TRIM(PT."Last") AS "PtFullName",

          SUBSTR(TRIM(HU."First"),1,1) || '. ' || TRIM(HU."Name") AS "HeldFullName",

          PR."Producer" AS "Producer",

          TRIM(PR."FirstName") AS "ProvFirstName",

          TRIM(PR."LastName") AS "ProvLastName",

          TRIM(UR."First") AS "InstFirstName",

          TRIM(UR."Name") AS "InstLastName",

          TRIM(PT."First") AS "PtFirstName",

          TRIM(PT."Last") AS "PtLastName",

          TRIM(PT."Chart") AS "PtChart",

          TO_CHAR(FLOOR(MONTHS_BETWEEN(SYSDATE,PT."Birth") / 12)) AS "PtAge",

          DECODE(PT."Sex",0,'U',1,'M',2,'F',3,'T',4,'X',5,'O','') AS "PtGender",

          GR."HeldForUser" AS "HeldForUser",

          TRIM(HU."First") AS "HeldFirstName",

          TRIM(HU."Name") AS "HeldLastName",

          TO_CHAR(GR."Date",'MON DD, YYYY') AS "EvalDate",

          GR."TimeSpent" AS "TimeSpent",

          GR."Discipline" AS "Discipline",

          T."Template" AS "Template",

          GR."IsCompetency" AS "IsCompetency",

          GR."Incomplete" AS "IsIncomplete",

          GR."Grading" AS "Grading",

          T."IsExam" AS "IsExam",

          GR."Deleted" AS "IsDeleted",

          NVL((SELECT TA."Access" FROM TEMPLACC TA WHERE TA."Template" = T."Template" AND TA."SLevel" = vLevel), 1) AS "Access"



        FROM GRADING GR, PRODUCER PR, PATIENT PT, USERS UR, TEMPLATE T, USERS HU

        WHERE GR."Patient" = PT."Patient" (+)

        AND GR."Producer" = PR."Producer"

        AND GR."HeldForUser" = HU."User" (+)

        AND GR."Instructor" = UR."User" (+)

        AND GR."Template" = T."Template"

        AND GR."Date" BETWEEN vDateFrom AND vDateTo

        AND

        (

          0 = vShowGeneral OR

          (1 = vShowGeneral AND GR."Patient" = 0) OR

          (2 = vShowGeneral AND GR."Patient" != 0 AND (0 = vPatient OR GR."Patient" = vPatient))

        )

        AND

        (

          0 < vDeleted OR

          GR."Deleted" = vDeleted

        )

        AND

        (

          (TRIM(vProducer) IS NULL OR LENGTH(TRIM(vProducer)) = 0) OR

          TRIM(GR."Producer") = TRIM(vProducer)

        )

        AND

        (

          0 = vInstructor OR

          GR."Instructor" = vInstructor

        )

        AND

        (

          (TRIM(vDiscipline) IS NULL OR LENGTH(TRIM(vDiscipline)) = 0) OR

          TRIM(GR."Discipline") = TRIM(vDiscipline)

        )

        AND

        (

          (TRIM(vTemplate) IS NULL OR LENGTH(TRIM(vTemplate)) = 0) OR

          TRIM(GR."Template") = TRIM(vTemplate)

        )

        AND

        (

          2 = vIncomplete OR

          (0 = vIncomplete AND GR."Incomplete" = 0) OR

          (

            1 = vIncomplete AND

            GR."Incomplete" = 1 AND

            (

              0 = vHeldForUser OR

              GR."HeldForUser" = vHeldForUser

            )

          )

        )

        AND

        (

          (1 = vIsExam AND 1 = vIsCompetency AND 1 = vIsEvaluation) OR

          (1 = vIsExam AND 1 = vIsCompetency AND 0 = vIsEvaluation AND (GR."IsCompetency" = 1 OR T."IsExam" = 1)) OR

          (1 = vIsExam AND 0 = vIsCompetency AND 1 = vIsEvaluation AND (GR."IsCompetency" = 0 OR T."IsExam" = 1)) OR

          (0 = vIsExam AND 1 = vIsCompetency AND 1 = vIsEvaluation AND (T."IsExam" = 0)) OR

          (1 = vIsExam AND 0 = vIsCompetency AND 0 = vIsEvaluation AND (T."IsExam" = 1)) OR

          (0 = vIsExam AND 1 = vIsCompetency AND 0 = vIsEvaluation AND (GR."IsCompetency" = 1)) OR

          (0 = vIsExam AND 0 = vIsCompetency AND 1 = vIsEvaluation AND (GR."IsCompetency" = 0 AND T."IsExam" = 0))

        )

        ORDER BY GR."Grading" DESC

      ) T1

      WHERE ROWNUM <= vMaxRow

    ) T2

    WHERE "RowNum" >= vMinRow;



  EXCEPTION WHEN NO_DATA_FOUND THEN

    results_cur := NULL;

END;



/**

* Procedure to GET a list of treatments evaluted for a specified Evaluation.<p/>

*

* param: vGrading INPUT: GRADING."Grading"<p/>

* param: results_cur OUTPUT: Weak cursor to contain the data retrieved<br/>

*/

PROCEDURE getevaluatedtxlist(IN vgrading integer, OUT results_cur cursor_pkg.weakcursor) IS

BEGIN

  OPEN results_cur FOR

    SELECT

      TR."Type" AS "Type",

      TR."Id" AS "Id",

      TR."Treatment" AS "Treatment",

      TR."Status" AS "Status",

      TR."Site" AS "Site",

      TR."Site2" AS "Site2",

      TR."Surface" AS "Surface",

      TR."Additional" AS "Additional",

      TR."ChartTrx" AS "ChartTrx",

      PR."Procedure" AS "Procedure",

      PR."Description" AS "ProcDescription",

      PR."RelValue" AS "RelValue",

      TG."Status" AS "TrxGradeStatus",

      TR."Producer"

    FROM TRXGRADE TG, TRX TR, PROCEDUR PR

    WHERE TG."Id" = TR."Id"

    AND TG."Type" = TR."Type"

    AND TG."Treatment" = TR."Treatment"

    AND TR."Procedure" = PR."Procedure"



    AND TG."Grading" = vGrading

    --AND TG."Status" = 1

    ORDER BY PR."Procedure", TR."Site";



    EXCEPTION WHEN NO_DATA_FOUND THEN results_cur := NULL;

END;



/**

* Procedure to GET a detail of an evaluation from GRADING table.<p/>

*

* param: vGrading INPUT: GRADING."Grading"<p/>

* param: vLevel INPUT: SLevel to check if has access to the Evaluation<p/>

* param: results_cur OUTPUT: Weak cursor to contain the data retrieved<br/>

*/

PROCEDURE getgradingdetail(IN vgrading integer, IN vlevel integer, OUT results_cur cursor_pkg.weakcursor) IS

BEGIN

  OPEN results_cur FOR

    SELECT

      T."Template",

      T."Description",

      T."IsDefaultSessional",

      T."Qualifier",

      T."Incomplete" AS "TempIncomplete",

      T."OnlyEvalDisplayedTx",

      PU."User" AS "ProvID",

      P."Producer" AS "Producer",

      P."FirstName" AS "ProvFirstName",

      P."LastName" AS "ProvLastName",

      P."Year" AS "ProvYear",

      P."RequireGrading" AS "ProvRequireGrading",

      IU."User" AS "InstID",

      IU."First" AS "InstFirstName",

      IU."Name" AS "InstLastName",

      G."HeldForUser" AS "HeldForUser",

      HU."First" AS "HeldFirstName",

      HU."Name" AS "HeldLastName",

      G."Patient" AS "Patient",

      PT."First" AS "PtFirstName",

      PT."Last" AS "PtLastName",

      PT."Chart" AS "PtChart",

      TO_CHAR(FLOOR(MONTHS_BETWEEN(SYSDATE,PT."Birth") / 12)) AS "PtAge",

      DECODE(PT."Sex",0,'U',1,'M',2,'F',3,'T',4,'X',5,'O','') AS "PtGender",

      G."Template",

      G."Discipline",

      G."Year",

      G."IsCompetency",

      G."Incomplete",

      G."Passed",

      G."TimeSpent",

      TO_CHAR(G."Date",'MON DD, YYYY') AS "Date",

      G."Comment",

      G."Deleted",

      NVL((SELECT TA."Access" FROM TEMPLACC TA WHERE TA."Template" = T."Template" AND TA."SLevel" = vLevel), 1) AS "Access"



    FROM GRADING G, PRODUCER P, USERS PU, USERS IU, USERS HU, PATIENT PT, TEMPLATE T

    WHERE G."Grading" = vGrading

    AND G."Producer" = P."Producer"(+)

    AND G."Producer" = PU."Producer"(+)

    AND G."Instructor" = IU."User"(+)

    AND G."HeldForUser" = HU."User"(+)

    AND G."Patient" = PT."Patient"(+)

    AND G."Template" = T."Template"

    AND ROWNUM = 1;

  EXCEPTION WHEN NO_DATA_FOUND THEN results_cur := NULL;

END;



/**

* Procedure to GET a list of grade items for a indicated evaluation from GRADITEM table.<p/>

*

* param: vGrading INPUT: GRADING."Grading"<p/>

* param: results_cur OUTPUT: Weak cursor to contain the data retrieved<br/>

*/

PROCEDURE getgradingitemlist(IN vgrading integer, OUT results_cur cursor_pkg.weakcursor) IS

BEGIN

  OPEN results_cur FOR

    SELECT

      GI."Grading",

      GI."TrxSpecific",

      GI."Row",

      GI."IsHeading",

      GI."QuestionText",

      GI."Text",

      TR."Type" AS "Type",

      TR."Id" AS "Id",

      TR."Treatment" AS "Treatment",

      TR."Status" AS "Status",

      TR."Site" AS "Site",

      TR."Site2" AS "Site2",

      TR."Surface" AS "Surface",

      TR."Additional" AS "Additional",

      TR."ChartTrx" AS "ChartTrx",

      PR."Procedure" AS "Procedure",

      PR."Description" AS "ProcDescription",

      GI."RelValue" AS "RelValue",

      GI."Scheme" AS "Scheme",

      IU."User" AS "InstID",

      IU."First" AS "InstFirstName",

      IU."Name" AS "InstLastName",

      TO_CHAR(GI."Date",'MON DD, YYYY') AS "Date",

      GI."Note" AS "Note",

      GI."Item" AS "Item",

      TI."IsRequired" AS "IsRequired",

      TI."Marking" AS "MarkingType",

      TI.INSTRUCTION AS "Instruction",                          --AX-26600; AX-40621

      S."MarkScheme" AS "Marking",

      S."Min",

      S."Max",

      ABS(S."Increment") AS "Increment",

      S."Validate"



    FROM GRADITEM GI

    LEFT JOIN TRX TR ON GI."Type" = TR."Type" AND GI."Id" = TR."Id" AND GI."Treatment" = TR."Treatment"

    LEFT JOIN PROCEDUR PR ON TR."Procedure" = PR."Procedure"

    LEFT JOIN USERS IU ON GI."User" = IU."User"

    LEFT JOIN TITEM TI ON GI."Item" = TI."Item"

    LEFT JOIN SCHEME S ON GI."Scheme" = S."Scheme"

    WHERE GI."Grading" = vGrading



    ORDER BY GI."TrxSpecific", GI."Row";

  EXCEPTION WHEN NO_DATA_FOUND THEN results_cur := NULL;

END;



/**

* Procedure to get a detail of a grade item for cumulative (trx based on OrigRecNo):

* param: vGrading INPUT: Grading ID<p/>

* param: vType INPUT: Type of treatment if the grade item is treatment specific<p/>

* param: vId INPUT: Id of treatment if the grade item is treatment specific<p/>

* param: vTreatment INPUT: Treatment type of trx if the grade item is treatment specific<p/>

* param: vItem INPUT: Item id of the grade item it is based on GRADITEM."Item"<p/>

* param: results_cur OUTPUT: weak-cursor outputing a GRADITEM row<p/>

*/

PROCEDURE getdefaultcumulativegraditem(IN vgrading integer, IN vtype integer, IN vid integer, IN vtreatment integer, IN vitem integer, OUT results_cur cursor_pkg.weakcursor) IS

  vOrigRecNo INTEGER;

BEGIN

  SELECT "OrigRecNo"

  INTO vOrigRecNo

  FROM TRX

  WHERE "Type" = vType

  AND "Id" = vId

  AND "Treatment" = vTreatment

  AND ROWNUM = 1;



  IF vOrigRecNo IS NOT NULL THEN

    OPEN results_cur FOR

      SELECT

        GI."Grading",

        GI."TrxSpecific",

        GI."Row",

        GI."IsHeading",

        GI."QuestionText",

        GI."Text",

        TR."Type" AS "Type",

        TR."Id" AS "Id",

        TR."Treatment" AS "Treatment",

        TR."Status" AS "Status",

        TR."Site" AS "Site",

        TR."Site2" AS "Site2",

        TR."Surface" AS "Surface",

        TR."Additional" AS "Additional",

        TR."ChartTrx" AS "ChartTrx",

        PR."Procedure" AS "Procedure",

        PR."Description" AS "ProcDescription",

        GI."RelValue" AS "RelValue",

        GI."Scheme" AS "Scheme",

        IU."User" AS "InstID",

        IU."First" AS "InstFirstName",

        IU."Name" AS "InstLastName",

        TO_CHAR(GI."Date",'MON DD, YYYY') AS "Date",

        GI."Note" AS "Note",

        GI."Item" AS "Item",

        TI."IsRequired" AS "IsRequired",

        TI."Marking" AS "MarkingType",

        TI.INSTRUCTION AS "Instruction",                              --AX-26600; AX-40621

        S."MarkScheme" AS "Marking",

        S."Min",

        S."Max",

        ABS(S."Increment") AS "Increment",

        S."Validate"

      FROM GRADITEM GI

      LEFT JOIN TRX TR ON GI."Type" = TR."Type" AND GI."Id" = TR."Id" AND GI."Treatment" = TR."Treatment"

      LEFT JOIN PROCEDUR PR ON TR."Procedure" = PR."Procedure"

      LEFT JOIN USERS IU ON GI."User" = IU."User"

      LEFT JOIN TITEM TI ON GI."Item" = TI."Item"

      LEFT JOIN SCHEME S ON GI."Scheme" = S."Scheme"

      WHERE TR."OrigRecNo" = vOrigRecNo

      AND GI."Grading" = vGrading

      AND GI."Item" = vItem

      AND ROWNUM = 1;

  ELSE

    results_cur := NULL;

  END IF;

END;



/**

* Procedure to GET a list of grade item list that has indicated treatment as a cumulative evaluation, and template as a form.<p/>

*

* param: vType INPUT: Treatment type<p/>

* param: vId INPUT: Treatment type<p/>

* param: vTreatment INPUT: Treatment GRADITEM."Treatment"<p/>

* param: vTemplate INPUT: GRADITEM."Template"<p/>

* param: results_cur OUTPUT: Weak cursor to contain the data retrieved<br/>

*/

PROCEDURE getcumulativegraditemlist(IN vtype integer, IN vid integer, IN vtreatment integer, IN vtemplate character varying, OUT results_cur cursor_pkg.weakcursor) IS

  vOrigRecNo INTEGER := 0;

BEGIN

  SELECT "OrigRecNo"

  INTO vOrigRecNo

  FROM TRX

  WHERE "Type" = vType

  AND "Id" = vId

  AND "Treatment" = vTreatment

  AND ROWNUM = 1;



  IF vOrigRecNo != 0 THEN

    BEGIN

      OPEN results_cur FOR

        SELECT

        TO_CHAR(G."Date",'MON DD, YYYY') AS "Date",

        TO_CHAR(G."Date",'YYYYMMDD') AS "NumDate",

        GI."Grading",

        GI."TrxSpecific",

        GI."Row",

        GI."IsHeading",

        GI."QuestionText",

        GI."Text",

        GI."Note" AS "Note",

        GI."Item" AS "Item",

        IU."User" AS "InstID",

        IU."First" AS "InstFirstName",

        IU."Name" AS "InstLastName"



        FROM GRADITEM GI

        JOIN GRADING G ON GI."Grading" = G."Grading"

        JOIN TRX TR ON GI."Type" = TR."Type" AND GI."Id" = TR."Id" AND GI."Treatment" = TR."Treatment"

        LEFT JOIN USERS IU ON GI."User" = IU."User"



        WHERE TR."OrigRecNo" = vOrigRecNo

        AND G."Deleted" <> 1

        AND G."Template" = vTemplate

        ORDER BY "Date" DESC, G."Grading" DESC, GI."Row" ASC;

    END;

  ELSE

    results_cur := NULL;

  END IF;

END;



/**

* Procedure to GET a list of grading details that has indicated treatment as a cumulative evaluation.<p/>

*

* param: vType INPUT: Treatment type<p/>

* param: vId INPUT: Treatment type<p/>

* param: vTreatment INPUT: Treatment GRADITEM."Treatment"<p/>

* param: vLevel INPUT: AX-1945 Level<p/>

* param: results_cur OUTPUT: Weak cursor to contain the data retrieved<br/>

*/

PROCEDURE getcumulativegradinglist(IN vtype integer, IN vid integer, IN vtreatment integer, IN vlevel integer, OUT results_cur cursor_pkg.weakcursor) IS

  vOrigRecNo INTEGER := 0;

BEGIN

  SELECT "OrigRecNo"

  INTO vOrigRecNo

  FROM TRX

  WHERE "Type" = vType

  AND "Id" = vId

  AND "Treatment" = vTreatment

  AND ROWNUM = 1;



  IF vOrigRecNo != 0 THEN

    BEGIN

      OPEN results_cur FOR

        SELECT

          G."Grading",

          G."Discipline",

          G."Incomplete",

          TP."Template",

          TO_CHAR(G."Date",'MON DD, YYYY') AS "Date",

          TO_CHAR(G."Date",'YYYYMMDD') AS "NumDate",

          IU."User" AS "InstID",

          TRIM(IU."First") AS "InstFirstName",

          TRIM(IU."Name") AS "InstLastName",

          HU."User" AS "HeldID",

          TRIM(HU."First") AS "HeldFirstName",

          TRIM(HU."Name") AS "HeldLastName",

          PR."Producer" AS "Producer",

          TRIM(PR."FirstName") AS "ProvFirstName",

          TRIM(PR."LastName") AS "ProvLastName",

          NVL((SELECT TA."Access" FROM TEMPLACC TA WHERE TA."Template" = TP."Template" AND TA."SLevel" = vLevel), 1) AS "Access"

        FROM GRADITEM I

        JOIN TITEM TI ON I."Item" = TI."Item"

        JOIN TRX TR ON I."Type" = TR."Type" AND I."Id" = TR."Id" AND I."Treatment" = TR."Treatment"

        JOIN GRADING G ON I."Grading" = G."Grading"

        JOIN TEMPLATE TP ON G."Template" = TP."Template"

        LEFT JOIN USERS IU ON G."Instructor" = IU."User"

        LEFT JOIN USERS HU ON G."HeldForUser" = HU."User"

        LEFT JOIN PRODUCER PR ON G."Producer" = PR."Producer"

        WHERE TR."OrigRecNo" = vOrigRecNo

        AND G."Deleted" <> 1

        AND TP."CanContinue" = 1

        AND

        (

          TI."IsLimited" = 0

          OR

          EXISTS (

            SELECT 1

            FROM TITEMPR TIPR

            WHERE TIPR."Item" = TI."Item"

            AND (

              TRIM(TR."Procedure") BETWEEN "ProcFrom" AND "ProcTo"

              OR

              TRIM(TR."Procedure") = TRIM("ProcFrom")

              OR

              TRIM(TR."Procedure") = TRIM("ProcTo")

            )

          )

        )

        ORDER BY

          G."Template" ASC,

          G."Date" DESC,

          G."Grading" DESC,

          I."Row" ASC;



      EXCEPTION WHEN NO_DATA_FOUND THEN

        results_cur := NULL;

    END;

  ELSE

    results_cur := NULL;

  END IF;

END;



/**

* Procedure to Check if the instructor evaluated the treatment today.<p/>

*

* param: vInstructor INPUT: instructor ID<p/>

* param: vChartTrx INPUT: Chart Trx ID<p/>

* param: vResult OUTPUT: indicator who evaluated the treatment (0 = no one; 1 = self; 2 = other instructor)<br/>

*/

PROCEDURE validatetxevaluatedtoday(IN vinstructor integer, IN vcharttrx integer, OUT vresult integer) IS

  vRowCount INTEGER;



  CURSOR curTrx IS

    SELECT * FROM TRX

    WHERE "ChartTrx" = vChartTrx;

  cTrx TRX%ROWTYPE;

BEGIN

  vResult := -1;

  FOR cTrx IN curTrx LOOP

    IF vResult = -1 THEN

      BEGIN

        SELECT COUNT(1) INTO vRowCount

        FROM TRXGRADE TG

        JOIN TRX T ON TG."Type" = T."Type" AND TG."Id" = T."Id" AND TG."Treatment" = T."Treatment"

        JOIN GRADING G ON TG."Grading" = G."Grading"

        WHERE TRUNC(G."Date") = TRUNC(SYSDATE)

        AND G."Instructor" = vInstructor

        AND T."OrigRecNo" = cTrx."OrigRecNo"

        AND G."Deleted" = 0;



        IF vRowCount > 0 THEN

          vResult := 1;

        ELSE

          BEGIN

            SELECT COUNT(1) INTO vRowCount

            FROM TRXGRADE TG

            JOIN TRX T ON TG."Type" = T."Type" AND TG."Id" = T."Id" AND TG."Treatment" = T."Treatment"

            JOIN GRADING G ON TG."Grading" = G."Grading"

            WHERE TRUNC(G."Date") = TRUNC(SYSDATE)

            AND T."OrigRecNo" = cTrx."OrigRecNo"

            AND G."Deleted" = 0;



            IF vRowCount > 0 THEN

              vResult := 2;

            ELSE

              vResult := 0;

            END IF;

          END;

        END IF;

      END;

    END IF;

  END LOOP;



  IF vResult = -1 THEN

    vResult := 0;

  END IF;

END;



/**

* Procedure Get Server Date Time.<p/>

*

* param: vResult OUTPUT: Server DateTime in format 'DD-MON-YYYY HH24:MI:SS'<br/>

*/

PROCEDURE getservertime(IN stationid integer, INOUT vresult character) IS

	vIniDef INTEGER := 0;

	vIniset INTEGER := 0;

	vTimeZoneOff INTEGER := 0;

	vDateTime DATE;

BEGIN

    -- Get current date in string format and Date format

	SELECT (TO_CHAR(SYSDATE,'DD-MON-YYYY HH24:MI:SS')), SYSDATE

	INTO vResult, vDateTime FROM DUAL;

  -- Look fo TimeZone offset in IniDef table

  BEGIN

    SELECT "Inidef", "Default" INTO vInidef, vTimeZoneOff FROM INIDEF WHERE "Key" = 'TimeZoneOffset';

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vInidef := 0;

      vTimeZoneOff := 0;

  END;



  IF vInidef > 0 AND stationId > 0 THEN

    BEGIN

      -- Get Iniset from Iniset and only for active station

      SELECT INISET."Iniset" INTO vIniset FROM STATION, INISET WHERE STATION."Deleted" = '0' AND STATION."StationId" = INISET."Station" AND STATION."StationId" = stationId;

      EXCEPTION WHEN NO_DATA_FOUND THEN

        vIniset := 0;

    END;

      IF vIniset > 0 THEN

        BEGIN

          -- Get offset from INIITEM table

          SELECT "ValueNum" INTO vTimeZoneOff FROM INIITEM WHERE "Inidef" = vInidef AND "Iniset" = vIniset;

          EXCEPTION WHEN NO_DATA_FOUND THEN

            vIniset := 0;    -- just to do something

        END;

      END IF;

	END IF;

	IF vTimeZoneOff != 0 THEN

		vDateTime := vDateTime + vTimeZoneOff/24;

		vResult :=  TO_CHAR(vDateTime, 'DD-MON-YYYY HH24:MI:SS');

	END IF;



END;



/**

* Procedure that set FA version in FSetting table.<p/>

*

* param: vVersion INPUT: version to set<p/>

*/

PROCEDURE setfaversion(IN vversion character varying) IS

	vUser INTEGER := 0;

	vKey  VARCHAR2(255) := 'FP.General.Version';

	vScope INTEGER;

	vType INTEGER;

	vTextVal  VARCHAR2(4000);

	vIntVal NUMBER(10);

	vDateVal DATE;

	vShortDescription  VARCHAR2(255);

	vLongDescription  VARCHAR2(4000);

	vDefaultValue  VARCHAR2(4000);

	vRules  VARCHAR2(255);

BEGIN

	FPORTAL_PKG.GetFSetting(vUser, vKey, vScope, vType, vTextVal, vIntVal, vDateVal, vShortDescription, vLongDescription, vDefaultValue, vRules);

	IF vType = -1 THEN

	   -- Create FSetting

	   vType := 0;		-- 0 = Text

	   vScope := 0; 	-- 0 = Global setting

	   AddFSetting (vUser, vKey, vType, vVersion, vScope);

	ELSE

	   -- Set new version

	   SetFSetting (vUser, vKey, vVersion);



	   -- 39661455 insert audit record

	   INSERT INTO AUDITHIS VALUES (

			AUDITHIS_AUDIT_SEQ.nextval,

			TRUNC(SYSDATE),

			TO_NUMBER(TO_CHAR(SYSDATE, 'HH24'))*60+TO_NUMBER(TO_CHAR(SYSDATE, 'MI')),

			TO_NUMBER(REPLACE(vVersion,'.','')),

			0,

			'FVERSION',

			2

		);

		COMMIT;

	END IF;

END;





/**

* Procedure to Edit Notes (Update NOTES2 and delete NOTEOVR and then INSERT NOTEOVER if is necessary.<p/>

*

* param: vAuto INPUT: Auto ID<p/>

* param: vCustom1Val INPUT: Custom1Val - Product Clinic<p/>

* param: vCustom2Val INPUT: Custom2Val - Prognosis<p/>

* param: vNoteText INPUT: Note Text<p/>

*/

PROCEDURE doeditnotes(IN vauto integer, IN vcustom1val character varying, IN vcustom2val character varying, IN vnotetext character varying) IS

  -- General Note

  vSectionNum INTEGER := 0;

  vTypeNote INTEGER := 1;

  vDate  VARCHAR2(10);						-- Not used

BEGIN

  FPORTAL_PKG.EditNotes(vAuto, vTypeNote, vSectionNum, vCustom1Val, vCustom2Val, vDate, vNoteText);

END;





/**

* Procedure to Edit SOAP Notes (Update NOTES2 and delete NOTEOVR and then INSERT NOTEOVER if is necessary.<p/>

*

* param: vAuto INPUT: Auto ID<p/>

* param: vCustom1Val INPUT: Custom1Val - Product Clinic<p/>

* param: vCustom2Val INPUT: Custom2Val - Prognosis<p/>

* param: vDate INPUT: Date<p/>

* param: vSubjectiveNote INPUT: Subjetive Note Text<p/>

* param: vObjectiveNote INPUT: Objective Note Text<p/>

* param: vAssessmentNote INPUT: Assessment Note Text<p/>

* param: vPlannedNote INPUT: Planned Note Text<p/>

*/

PROCEDURE doeditsoapnotes(IN vauto integer, IN vcustom1val character varying, IN vcustom2val character varying, IN vdate character varying, IN vsubjectivenote character varying, IN vobjectivenote character varying, IN vassessmentnote character varying, IN vplannednote character varying) IS

  vSectionNum INTEGER;

  vTypeNote INTEGER := 4;

BEGIN

  -- Subjetive Note

  vSectionNum := 0;

  FPORTAL_PKG.EditNotes(vAuto, vTypeNote, vSectionNum, vCustom1Val, vCustom2Val, vDate, vSubjectiveNote);

  -- Objetive Note

  vSectionNum := 1;

  FPORTAL_PKG.EditNotes(vAuto, vTypeNote, vSectionNum, vCustom1Val, vCustom2Val, vDate, vObjectiveNote);

  -- Assessment Note

  vSectionNum := 2;

  FPORTAL_PKG.EditNotes(vAuto, vTypeNote, vSectionNum, vCustom1Val, vCustom2Val, vDate, vAssessmentNote);

  -- Planned Note

  vSectionNum := 3;

  FPORTAL_PKG.EditNotes(vAuto, vTypeNote, vSectionNum, vCustom1Val, vCustom2Val, vDate, vPlannedNote);

END;



/**

* Procedure to Edit General and SOAP Notes (Update NOTES2 and delete NOTEOVR and then INSERT NOTEOVER if is necessary.<p/>

*

* param: vAuto INPUT: Auto ID<p/>

* param: vSectionNum INPUT: SectionNum<p/>

* param: vCustom1Val INPUT: Custom1Val - Product Clinic<p/>

* param: vCustom2Val INPUT: Custom2Val - Prognosis<p/>

* param: vDate INPUT: Date<p/>

* param: vNoteText INPUT: Note Text<p/>

*/

PROCEDURE editnotes(IN vid integer, INOUT vtypenote integer, IN vsectionnum integer, IN vcustom1val character varying, IN vcustom2val character varying, IN vdate character varying, IN vnotetext character varying) IS

  vNotesLen PLS_INTEGER;

  vLenPartial PLS_INTEGER;

  vPosition PLS_INTEGER := 1;

  vOrder INTEGER := 1;

  vPatient INTEGER;

  vNotesCustom  VARCHAR2(4000);

  SQlStmt  VARCHAR2(4000);



  vAuto INTEGER;

  TYPE r_cursor is REF CURSOR;

  vNoteRecords r_cursor;

  vNoteRecord NOTES2%ROWTYPE;

  vDbDate DATE;

  vTypeCero INTEGER := 0;

BEGIN



  -- Get Notes Length

  vNotesLen := LENGTH(vNoteText);



  -- For SOAP Notes get Auto

  IF (vTypeNote = 4) THEN

    SELECT "Auto" INTO vAuto FROM NOTES2 WHERE "OtherId" = vId AND "SectionNo" = vSectionNum AND "Type" = vTypeNote;

 ELSE

    vAuto := vId;

  END IF;



  -- Delete all NOTEOVR for vId

  SQlStmt := 'DELETE NOTEOVR WHERE "ParentId" = :Auto';

  EXECUTE IMMEDIATE SQlStmt USING vAuto;

  IF (vTypeNote = 4) THEN

     OPEN vNoteRecords FOR SELECT * FROM NOTES2 WHERE "Auto" = vAuto AND "SectionNo" = vSectionNum AND "Type" = vTypeNote;

  ELSE

     OPEN vNoteRecords FOR SELECT * FROM NOTES2 WHERE "Auto" = vAuto AND "SectionNo" = vSectionNum;

  END IF;



  LOOP

    FETCH vNoteRecords INTO vNoteRecord;

    EXIT WHEN vNoteRecords%notfound;



    -- Get vPatient for NOTEOVR

    SELECT "PtxPId" INTO vPatient FROM PATIENT2 WHERE "Auto" = vNoteRecord."PId";



    -- Get Notes to write

    IF (vNotesLen > 4000) THEN

      vNotesCustom := SUBSTR(vNoteText, 1, 4000);

    ELSE

      vNotesCustom := vNoteText;

    END IF;



    -- Update NOTES2 (SOAP or General)

    IF (vTypeNote = 4) THEN

                  vDbDate := TRUNC(TO_DATE(vDate, 'yyyy/mm/dd'));

                  SQlStmt := 'UPDATE NOTES2 SET "Text" = :Text, "Custom1" = :Custom1, "Custom2" = :Custom2, "Date" = :DateNow WHERE "Auto" = :Auto AND "SectionNo" = :SectionNum AND "Type" = :TypeNote ';

                  EXECUTE IMMEDIATE SQlStmt USING vNotesCustom, vCustom1Val, vCustom2Val, vDbDate, vAuto, vSectionNum, vTypeNote;

    ELSE

                  vTypeNote := vNoteRecord."Type";

      SQlStmt := 'UPDATE NOTES2 SET "Text" = :Text, "Custom1" = :Custom1, "Custom2" = :Custom2 WHERE "Auto" = :Auto AND "SectionNo" = :SectionNum AND "Type" = :TypeNote ';

      EXECUTE IMMEDIATE SQlStmt USING vNotesCustom, vCustom1Val, vCustom2Val, vAuto, vSectionNum, vTypeNote;

    END IF;



    -- Loop to insert in NOTESOVR

    IF (vNotesLen > 4000) THEN

      LOOP

        vPosition := vPosition + 4000;

        vLenPartial := vNotesLen - vPosition + 1;

        IF (vLenPartial > 4000) THEN

          vNotesCustom := SUBSTR(vNoteText, vPosition, 4000);

        ELSE

          vNotesCustom := SUBSTR(vNoteText, vPosition, vLenPartial);

        END IF;

        SQlStmt := 'INSERT INTO NOTEOVR ("Id", "Patient", "Type", "ParentId", "Order", "Text", "Deleted", "Audit")

                                                VALUES (NOTEOVR_Id_SEQ.NEXTVAL, :1, :2, :3, :4, :5, 0, 0)';

        EXECUTE IMMEDIATE SQlStmt USING vPatient, vTypeCero, vAuto, vOrder, vNotesCustom;

        vOrder := vOrder + 1;

        EXIT WHEN vLenPartial <= 4000;

      END LOOP;

    END IF;

  END LOOP;



  COMMIT;

END;



/*

 * 29205783 Procedure to get the State of the chair<p/>

 * param: vChair INPUT: Chair<p/>

 * param: vTimer1 INPUT: Timer 1<p/>

 * param: vTimer2 INPUT: Timer 2<p/>

 * param: results_cur OUT: Chair Status<p/>

*/

PROCEDURE getchairstate(IN vchair integer, IN vtimer1 integer, IN vtimer2 integer, OUT results_cur cursor_pkg.weakcursor) IS

BEGIN

  OPEN results_cur FOR

    SELECT C."CNState"

    FROM CHAIRST C, AUDITHIS A, CHAIR CH WHERE C."Chair" IN (vChair) AND C."Audit" = A."Audit" AND CH."Chair" = C."Chair"

    AND  (C."ClinicTime" = vTimer1 OR C."ClinicTime" = vTimer2 ) ORDER BY C."Audit" DESC;



  EXCEPTION WHEN NO_DATA_FOUND THEN

    results_cur := NULL;

END;



/*

 * 29205783 Function to get the State notification name of the chair<p/>

 * param: vChair INPUT: Chair<p/>

 * param: vTimer1 INPUT: Timer 1<p/>

 * param: vTimer2 INPUT: Timer 2<p/>

 * return: ID of CNState CHAIRST."CNState" <p/>

*/

FUNCTION getchaircnstate(vchair integer, vtimer1 integer, vtimer2 integer) RETURN character varying IS

vCnState  VARCHAR(4000);

BEGIN

  BEGIN

  SELECT "CNState"

  INTO vCnState

  FROM

  (

    SELECT C."CNState"

    FROM CHAIRST C, AUDITHIS A, CHAIR CH WHERE C."Chair" IN (vChair) AND C."Audit" = A."Audit" AND CH."Chair" = C."Chair"

    AND  (C."ClinicTime" = vTimer1 OR C."ClinicTime" = vTimer2 ) ORDER BY C."Audit" DESC

  )

  WHERE ROWNUM = 1;



  EXCEPTION WHEN NO_DATA_FOUND THEN

  vCnState := NULL;

  END;

 RETURN vCnState;

END;



/*

 * 29205783 Function to get the State order of the chair<p/>

 * 61660872 Sort chair notifications by priority<p/>

 * param: vChair INPUT: Chair<p/>

 * param: vTimer1 INPUT: Timer 1<p/>

 * param: vTimer2 INPUT: Timer 2<p/>

 * return: Order from CNSTATE <p/>

*/

FUNCTION getcnstateorder(vchair integer, vtimer1 integer, vtimer2 integer) RETURN integer IS

vPriority INTEGER;

vCnState  VARCHAR(4000);

BEGIN

  BEGIN

    vCnState := FPORTAL_PKG.GetChairCNState(vChair, vTimer1, vTimer2);



	IF NOT (TRIM(vCnState) IS NULL OR LENGTH(TRIM(vCnState)) = 0) THEN

      SELECT C."Priority" INTO vPriority FROM CNSTATE C WHERE  c."CNState" = vCnState;

	ELSE

      vPriority := -1;                 -- 61660872 To avoid to mix with LowPriority whom has value of Zero

	END IF;



	EXCEPTION WHEN NO_DATA_FOUND THEN

    vPriority := -1;                   -- 61660872 To avoid to mix with LowPriority whom has value of Zero

  END;

  RETURN vPriority;

END;



/*

 * 61660872 Function to Date Chair CNSate<p/>

 * param: vChair INPUT: Chair<p/>

 * param: vTimer1 INPUT: Timer 1<p/>

 * param: vTimer2 INPUT: Timer 2<p/>

 * return: vOrderDateChair from AUDITHIS <p/>

*/

FUNCTION getdateforchairstate(vchair integer, vtimer1 integer, vtimer2 integer, stationid integer) RETURN character varying IS

    vOrderDateChair  VARCHAR(4000);

    vIniDef INTEGER := 0;

    vIniset INTEGER := 0;

    vTimeZoneOff INTEGER := 0;

BEGIN

  -- Look fo TimeZone offset in IniDef table

  BEGIN

    SELECT "Inidef", "Default" INTO vInidef, vTimeZoneOff FROM INIDEF WHERE "Key" = 'TimeZoneOffset';

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vInidef := 0;

      vTimeZoneOff := 0;

  END;

  IF vInidef > 0 AND stationId > 0 THEN

    BEGIN

      -- Get Iniset from Iniset and only for active station

      SELECT INISET."Iniset" INTO vIniset FROM STATION, INISET WHERE STATION."Deleted" = '0' AND STATION."StationId" = INISET."Station" AND STATION."StationId" = stationId;

      EXCEPTION WHEN NO_DATA_FOUND THEN

        vIniset := 0;

    END;

      IF vIniset > 0 THEN

        BEGIN

          -- Get offset from INIITEM table

          SELECT "ValueNum" INTO vTimeZoneOff FROM INIITEM WHERE "Inidef" = vInidef AND "Iniset" = vIniset;

          EXCEPTION WHEN NO_DATA_FOUND THEN

            vIniset := 0;   -- just to do something

        END;

      END IF;

	END IF;

	vTimeZoneOff := vTimeZoneOff * 60;     -- To convert to minutes



  BEGIN

    SELECT "OrderDateChair"

    INTO vOrderDateChair

    FROM

    (

      SELECT

        TO_CHAR(A."Date" + A."Time"/1440 + vTimeZoneOff/1440, 'YYYYMMDDHH24MISS' ) AS "OrderDateChair"

      FROM CHAIRST C, AUDITHIS A, CHAIR CH WHERE C."Chair" IN (vChair) AND C."Audit" = A."Audit" AND CH."Chair" = C."Chair"

      AND  (C."ClinicTime" = vTimer1 OR C."ClinicTime" = vTimer2 ) ORDER BY C."Audit" DESC

    )

    WHERE ROWNUM = 1;



    EXCEPTION WHEN NO_DATA_FOUND THEN

    vOrderDateChair := NULL;

  END;

 RETURN vOrderDateChair;

END;





/*

 * 29205783 Procedure to get the State Notification Details of the chair<p/>

 * param: vCnState INPUT: CNState<p/>

 * param: vBkgColor OUT: BkgColor<p/>

 * param: vDescription OUT: Description<p/>

 * param: vSessionBased OUT: SessionBased<p/>

 * param: vOrder OUT: Order<p/>

*/

PROCEDURE getchairstatedetails(IN vcnstate character varying, OUT vbkgcolor integer, OUT vdescription character varying, OUT vsessionbased character varying, OUT vorder integer) IS

BEGIN



  SELECT C."BkgColor", C."Description", C."SessionBased", C."Order" INTO vBkgColor, vDescription, vSessionBased, vOrder

  FROM CNSTATE C WHERE  TRIM(c."CNState") = TRIM(vCnState);

  --SELECT C."BkgColor", C."Description", C."SessionBased", C."Order" INTO vBkgColor, vDescription, vSessionBased, vOrder

  --FROM CNSTATE C, CNSACC A WHERE  A."CNState" = C."CNState" AND A."Access" > 0 AND A."SLevel" = 2 AND c."CNState" = vCnState;



  EXCEPTION WHEN NO_DATA_FOUND THEN

  vBkgColor := -1;

  vDescription := '';

  vSessionBased := 0;

  vOrder := 99999;

END;



/*

 * 29205783 Procedure to get GetClinicTime() function result <p/>

 * param: vApptId INPUT: Appointment Id<p/>

 * param: vClinicTime OUT: ClinicTime<p/>

*/

PROCEDURE getclinictimeprocedure(IN vapptid integer, OUT vclinictime integer) IS

BEGIN

  SELECT FPORTAL_PKG.GetClinicTime(vApptId) INTO vClinicTime FROM DUAL;



  EXCEPTION WHEN NO_DATA_FOUND THEN

  vClinicTime := 0;

END;



/*

 * 29205783 Procedure to Update CHAIRST table <p/>

 * param: vChair INPUT: Chair<p/>

 * param: vTimer1 INPUT: Timer 1<p/>

 * param: vTimer2 INPUT: Timer 2<p/>

 * param: vResult OUTPUT: result<p/>

*/

PROCEDURE updatechairstate(IN vchair integer, IN vtimer1 integer, IN vtimer2 integer, IN vuser integer, OUT vresult integer) IS

  vAudit AUDITHIS."Audit"%TYPE;			-- audit history

BEGIN



  vAudit := FPORTAL_PKG.AddAuditHis(vUser, 'CHAIRST', 2);



  UPDATE CHAIRST SET "CNState" = ' ', "Audit" = vAudit WHERE "Chair" = vChair AND ("ClinicTime" = vTimer1 OR "ClinicTime" = vTimer2);

  COMMIT;

    vResult := 0;



  EXCEPTION WHEN OTHERS THEN

    vResult := -1;

END;



/* 39160133 Procedure to Get CNState info.<p/>

 *

 * param: results_cur OUT: Chair Status<p/>

*/

PROCEDURE getcnstate(OUT results_cur cursor_pkg.weakcursor) IS

BEGIN

  OPEN results_cur FOR

    SELECT C."CNState", C."ShortDesc", C."Description", C."Order", C."BkgColor", C."Inactive"

    FROM CNSTATE C

	--WHERE C."Inactive" = 0

	ORDER BY C."Inactive" ASC, C."Priority" DESC, C."Description" ASC;



  EXCEPTION WHEN NO_DATA_FOUND THEN

    results_cur := NULL;

END;



  /**

  * Procedure used to get provider for "Find Provider" list

  * param: vFilterKeyword INPUT: Filter keyword to search list<p/>

  * param: vFilterField INPUT: Filter field used to filter keyword<p/>

  * param: vSearchInactive INPUT: to include inactive providers in the search result (0 = no, 1 = yes)<p/>

  * param: vOrderDirection INPUT: DESC OR ASC<p/>

  * param: vNumRows INPUT: number of records to return<p/>

  * param: vPage INPUT: set of rows (eg. page-3 and numRows-20 = 40 ~ 59 rows)<p/>

  * param: vCurrentPage OUTPUT: page number of current records<p/>

  * param: vTotalPage OUTPUT: total page numbers of current search criteria<p/>

  * param: results_cur OUTPUT: Weak cursor to contain the data retrieved, with the following columns:<br />

  * <li>Producer - Provider Code <br />

  * <li>FirstName - Provider First Name <br />

  * <li>LastName - Provider Last Name <br />

  * <li>FullName - Provider Full Name in F.LastName format <br />

  * <li>User - Provider User ID <br />

  * <li>TypeCode - Provider Type Code <br />

  * <li>PGroup - Provider Group <br />

  * <li>Year - Provider Year <br />

  */

  PROCEDURE getprovfindlist(IN vfilterkeyword character varying, IN vfilterfield character varying, IN vsearchinactive integer, IN vorderdirection character varying, IN vnumrows integer, IN vpage integer, OUT vcurrentpage integer, OUT vtotalpage integer, OUT results_cur cursor_pkg.weakcursor) IS

    SQLStmt  VARCHAR2(32000);

    vDate DATE := TRUNC(SYSDATE);

    vFilterField2  VARCHAR2(100);

    vFilterKeyword2  VARCHAR2(100);

	vMaxRow INTEGER;

	vMinRow INTEGER;

  BEGIN



    IF (TRIM(vFilterField) IS NULL OR LENGTH(TRIM(vFilterField)) = 0) THEN

      vFilterField2 := 'FirstName';

      vFilterKeyword2 := '';

    ELSE

      vFilterField2 := vFilterField;

      vFilterKeyword2 := vFilterKeyword;

    END IF;



    SELECT CEIL(COUNT(1)/vNumRows) INTO vTotalPage

    FROM (

      SELECT DISTINCT

        "Producer",

        "FirstName",

        "LastName",

        "FullName",

        "FLast",

        "LFirst",

        "User",

        "TypeCode",

        "PGroup",

        "Year",

		"Inactive",

        -1 AS "ItemCount"

      FROM

      (

        SELECT /*+ all_rows */

          TRIM(PR."FirstName") AS "FirstName",

          TRIM(PR."LastName") AS "LastName",

          TRIM(PR."Producer") AS "Producer",

          TRIM(PR."Year") AS "Year",

          UR."User",

          SUBSTR(TRIM(PR."FirstName"),1,1) || TRIM(PR."LastName") AS "FLast",

          TRIM(PR."LastName") || SUBSTR(TRIM(PR."FirstName"),1,1) AS "LFirst",

          SUBSTR(TRIM(PR."FirstName"),1,1) || '. ' || TRIM(PR."LastName") AS "FullName",

          TRIM(PR."TypeCode") AS "TypeCode",

          TRIM(PR."PGroup") AS "PGroup",

          TRIM(PR."Inactive") AS "Inactive"

        FROM PRODUCER PR, USERS UR, PRODTYPE PT

        WHERE PR."Producer" = UR."Producer"(+)

        AND NVL(UR."Deleted", 0) = 0

        /*AND LENGTH(TRIM(PR."Producer")) > 0*/

        AND PR."TypeCode" IN (SELECT PRT."Code" FROM PRODTYPE PRT WHERE PRT."Type" IN (0,1))

        AND

        (

          (vSearchInactive = 0 AND PR."Inactive" = 0) OR

          (vSearchInactive = 1)

        )

        AND

        (

          (NLS_UPPER(TRIM(vFilterField2)) = 'FIRSTNAME' AND (NLS_UPPER(TRIM(PR."FirstName")) LIKE NLS_UPPER(TRIM(vFilterKeyword2)) || '%' OR ((TRIM(PR."FirstName") IS NULL OR LENGTH(TRIM(PR."FirstName")) = 0) AND (TRIM(vFilterKeyword2) IS NULL OR LENGTH(TRIM(vFilterKeyword2)) = 0))))

          OR

          (NLS_UPPER(TRIM(vFilterField2)) = 'LASTNAME' AND (NLS_UPPER(TRIM(PR."LastName")) LIKE NLS_UPPER(TRIM(vFilterKeyword2)) || '%' OR ((TRIM(PR."LastName") IS NULL OR LENGTH(TRIM(PR."LastName")) = 0) AND (TRIM(vFilterKeyword2) IS NULL OR LENGTH(TRIM(vFilterKeyword2)) = 0))))

          OR

          (NLS_UPPER(TRIM(vFilterField2)) = 'PRODUCER' AND (NLS_UPPER(TRIM(PR."Producer")) LIKE NLS_UPPER(TRIM(vFilterKeyword2)) || '%' OR ((TRIM(PR."Producer") IS NULL OR LENGTH(TRIM(PR."Producer")) = 0) AND (TRIM(vFilterKeyword2) IS NULL OR LENGTH(TRIM(vFilterKeyword2)) = 0))))

          OR

          (NLS_UPPER(TRIM(vFilterField2)) = 'YEAR' AND (NLS_UPPER(TRIM(PR."Year")) LIKE NLS_UPPER(TRIM(vFilterKeyword2)) || '%' OR ((TRIM(PR."Year") IS NULL OR LENGTH(TRIM(PR."Year")) = 0) AND (TRIM(vFilterKeyword2) IS NULL OR LENGTH(TRIM(vFilterKeyword2)) = 0))))

          OR

          (NLS_UPPER(TRIM(vFilterField2)) = 'PGROUP' AND (NLS_UPPER(TRIM(PR."PGroup")) LIKE NLS_UPPER(TRIM(vFilterKeyword2)) || '%' OR ((TRIM(PR."PGroup") IS NULL OR LENGTH(TRIM(PR."PGroup")) = 0) AND (TRIM(vFilterKeyword2) IS NULL OR LENGTH(TRIM(vFilterKeyword2)) = 0))))

        )

      )

    );



    IF vTotalPage < vPage THEN

      vCurrentPage := vTotalPage;

    ELSIF vPage < 1 THEN

      vCurrentPage := 1;

    ELSE

      vCurrentPage := vPage;

    END IF;



    vMaxRow := vCurrentPage * vNumRows;

    vMinRow := (vCurrentPage - 1) * vNumRows + 1;



    SQLStmt := '

	SELECT R1.* FROM

	(

      SELECT R2.*, ROWNUM AS "RowNum" FROM

      (

        SELECT DISTINCT

          "Producer",

          "FirstName",

          "LastName",

          "FullName",

          "FLast",

          "LFirst",

          "User",

          "TypeCode",

          "PGroup",

          "Year",

		  "Inactive",

          -1 AS "ItemCount"

        FROM

        (

          SELECT /*+ all_rows */

            TRIM(PR."FirstName") AS "FirstName",

            TRIM(PR."LastName") AS "LastName",

            PR."Producer" AS "Producer",

            TRIM(PR."Year") AS "Year",

            UR."User",

            SUBSTR(TRIM(PR."FirstName"),1,1) || TRIM(PR."LastName") AS "FLast",

            TRIM(PR."LastName") || SUBSTR(TRIM(PR."FirstName"),1,1) AS "LFirst",

            SUBSTR(TRIM(PR."FirstName"),1,1) || ''. '' || TRIM(PR."LastName") AS "FullName",

            TRIM(PR."TypeCode") AS "TypeCode",

            TRIM(PR."PGroup") AS "PGroup",

			TRIM(PR."Inactive") AS "Inactive"

          FROM USERS UR, PRODUCER PR, PRODTYPE PT

          WHERE PR."Producer" = UR."Producer"(+)

          AND NVL(UR."Deleted", 0) = 0

          /*AND LENGTH(TRIM(PR."Producer")) > 0*/

          AND PR."TypeCode" IN (SELECT PRT."Code" FROM PRODTYPE PRT WHERE PRT."Type" IN (0,1))

          AND

          (

            (:1 = 0 AND PR."Inactive" = 0) OR

            (:2 = 1)

          )

          AND

          (

            (NLS_UPPER(TRIM(:3)) = ''FIRSTNAME'' AND (NLS_UPPER(TRIM(PR."FirstName")) LIKE NLS_UPPER(TRIM(:4)) || ''%'' OR ((TRIM(PR."FirstName") IS NULL OR LENGTH(TRIM(PR."FirstName")) = 0) AND (TRIM(:5) IS NULL OR LENGTH(TRIM(:5)) = 0))))

            OR

            (NLS_UPPER(TRIM(:6)) = ''LASTNAME'' AND (NLS_UPPER(TRIM(PR."LastName")) LIKE NLS_UPPER(TRIM(:7)) || ''%'' OR ((TRIM(PR."LastName") IS NULL OR LENGTH(TRIM(PR."LastName")) = 0) AND (TRIM(:8) IS NULL OR LENGTH(TRIM(:8)) = 0))))

            OR

            (NLS_UPPER(TRIM(:9)) = ''PRODUCER'' AND (NLS_UPPER(TRIM(PR."Producer")) LIKE NLS_UPPER(TRIM(:10)) || ''%'' OR ((TRIM(PR."Producer") IS NULL OR LENGTH(TRIM(PR."Producer")) = 0) AND (TRIM(:11) IS NULL OR LENGTH(TRIM(:11)) = 0))))

            OR

            (NLS_UPPER(TRIM(:12)) = ''YEAR'' AND (NLS_UPPER(TRIM(PR."Year")) LIKE NLS_UPPER(TRIM(:13)) || ''%'' OR ((TRIM(PR."Year") IS NULL OR LENGTH(TRIM(PR."Year")) = 0) AND (TRIM(:14) IS NULL OR LENGTH(TRIM(:14)) = 0))))

            OR

            (NLS_UPPER(TRIM(:15)) = ''PGROUP'' AND (NLS_UPPER(TRIM(PR."PGroup")) LIKE NLS_UPPER(TRIM(:16)) || ''%'' OR ((TRIM(PR."PGroup") IS NULL OR LENGTH(TRIM(PR."PGroup")) = 0) AND (TRIM(:17) IS NULL OR LENGTH(TRIM(:17)) = 0))))

          )

        )

        ORDER BY

        CASE WHEN NLS_UPPER(TRIM(:18)) = ''FIRST_ASC'' THEN NLS_UPPER("FLast" || "Producer" || "Year") END ASC,

        CASE WHEN NLS_UPPER(TRIM(:19)) = ''FIRST_DESC'' THEN NLS_UPPER("FLast" || "Producer" || "Year") END DESC,

        CASE WHEN NLS_UPPER(TRIM(:20)) = ''LAST_ASC'' THEN NLS_UPPER("LFirst" || "Producer" || "Year") END ASC,

        CASE WHEN NLS_UPPER(TRIM(:21)) = ''LAST_DESC'' THEN NLS_UPPER("LFirst" || "Producer" || "Year") END DESC

      ) R2

      WHERE ROWNUM <= :22

    ) R1

    WHERE "RowNum" >= :23';



    OPEN results_cur FOR SQLStmt USING vSearchInactive, vSearchInactive,

                                       vFilterField2, vFilterKeyword2, vFilterKeyword2,

                                       vFilterField2, vFilterKeyword2, vFilterKeyword2,

                                       vFilterField2, vFilterKeyword2, vFilterKeyword2,

                                       vFilterField2, vFilterKeyword2, vFilterKeyword2,

                                       vFilterField2, vFilterKeyword2, vFilterKeyword2,

                                       vOrderDirection, vOrderDirection, vOrderDirection, vOrderDirection,

                                       vMaxRow, vMinRow;

    EXCEPTION WHEN NO_DATA_FOUND THEN

    results_cur := NULL;

  END;











  -- check if an appointment is watched

  PROCEDURE checkapptwatcheditem(IN vappointment integer, IN vinstructor integer, OUT vcount integer) IS

  BEGIN

    SELECT COUNT(1) INTO vCount

    FROM FAPTWATCH

    WHERE "Appointment" = vAppointment

    AND "Instructor" = vInstructor

    AND "Date" = TRUNC(SYSDATE);

  END;











  -- add an item to appointment watched list

  PROCEDURE addapptwatcheditem(IN vappointment integer, IN vinstructor integer) IS

    vCount INTEGER;

  BEGIN

    -- check if same criteria already exist

    SELECT COUNT(1) INTO vCount

    FROM FAPTWATCH

    WHERE "Appointment" = vAppointment

    AND "Instructor" = vInstructor

    AND "Date" = TRUNC(SYSDATE);



    -- if there are no records in watched appointment list, add a new record

    IF vCount = 0 THEN

    BEGIN

    INSERT INTO FAPTWATCH VALUES (NULL, vAppointment, vInstructor, TRUNC(SYSDATE));

    END;

    END IF;

  END;











  -- delete an item from appointment watched list

  PROCEDURE deleteapptwatcheditem(IN vappointment integer, IN vinstructor integer) IS

  BEGIN

    -- delete

    DELETE FROM FAPTWATCH WHERE "Appointment" = vAppointment AND "Instructor" = vInstructor;

  END;





  -- delete all items from appointment watched list for a user

  PROCEDURE deleteallapptwatcheditems(IN vinstructor integer) IS

  BEGIN

    -- delete

    DELETE FROM FAPTWATCH WHERE "Instructor" = vInstructor AND "Date" = TRUNC(SYSDATE);

  END;











  -- clear all items from appointment watched list recorded before the indicated x number of days

  PROCEDURE clearapptwatchedlist(IN vday integer, IN vinstructor integer) IS

  BEGIN

    -- if instructor is not defined, than delete all instances occuring before the indicated date

    IF vInstructor = 0 THEN

    BEGIN

      DELETE FROM FAPTWATCH WHERE "Date" <= SYSDATE - vDay; --AX-40515

    END;



    -- if instructor is defined, than delete items occuring before the indicated date only for the instructor

    ELSE

    BEGIN

      DELETE FROM FAPTWATCH WHERE "Date" <= SYSDATE - vDay AND "Instructor" = vInstructor; --AX-40515

    END;

    END IF;

  END;









  --51503413 Get PatientId from UserId; Return cero if is not patient

  PROCEDURE getiuserpatientid(IN vuserid integer, OUT vpatientid integer) IS

  BEGIN

    SELECT "Id" INTO vPatientId FROM IUSER WHERE "iUser" = vUserId;

    EXCEPTION WHEN NO_DATA_FOUND THEN

       vPatientId := 0;

  END;



  -- 45532593

  /**

  * Get cursor containing all SLEVEL reocrds

  * param: results_cur OUTPUT: Weak cursor containing slevel data

  */

  PROCEDURE getslevels(OUT results_cur cursor_pkg.weakcursor) IS

  SQLStmt  VARCHAR2(4000);

BEGIN

  SQLStmt :=

		'

		SELECT

			"SLevel",

			"Description"

		FROM SLEVEL

    WHERE "Deleted" = 0 ORDER BY NLS_UPPER("Description")

		';

	BEGIN

		OPEN results_cur FOR SQLStmt;

	EXCEPTION WHEN NO_DATA_FOUND THEN

		results_cur := NULL;

	END;



END;



  /**

  * 50621785 Get Roles for Admin

  * param: results_cur OUTPUT: Weak cursor containing sRole data

  */

  PROCEDURE getsroles(OUT results_cur cursor_pkg.weakcursor) IS

  SQLStmt  VARCHAR2(4000);

BEGIN

  SQLStmt :=

		'

		SELECT

			"SRole",

			"Description"

		FROM SROLE

    WHERE "Deleted" = 0 AND "IsRider" = 0 ORDER BY NLS_UPPER("Description")

		';

	BEGIN

		OPEN results_cur FOR SQLStmt;

	EXCEPTION WHEN NO_DATA_FOUND THEN

		results_cur := NULL;

	END;



END;



-- 55408620 Get Patient Detail information for Tab panel

PROCEDURE getpatienttabdetail(IN vpatient integer, OUT results_cur cursor_pkg.weakcursor) IS

  SQLStmt  VARCHAR2(4000);

BEGIN

    SQLStmt := '

          SELECT

            PT."Patient" AS "Patient",

            PT."First" AS "FirstName",

            PT."Last" AS "LastName",

            PT."Chart" AS "Chart",

            TO_CHAR(FLOOR(MONTHS_BETWEEN(SYSDATE,PT."Birth") / 12)) AS "Age",

            DECODE(PT."Sex",0,''Unknown'',1,''Male'',2,''Female'',3,''Transgender'',4,''Gender X'',5,''Other'','''') AS "Gender",

            PT."Address1" AS "Address1",

            PT."Address2" AS "Address2",

            PT."City" AS "City",

            PT."Province" AS "Province",

            PT."Postal" AS "Postal",

			PT."AddressOther" AS "AddressOther",

			PT."PrefLanguage" AS "PrefLanguage",

            PT."ContactAt" AS "ContactAt",

            PT."ContactTime" AS "ContactTime",

            PT."HomeArea" AS "HomeArea",

            PT."HomePhone" AS "HomePhone",

            PT."WorkArea" AS "WorkArea",

            PT."WorkPhone" AS "WorkPhone",

            PT."WorkExt" as "WorkExt",

            PT."MobileArea" AS "MobileArea",

            PT."MobilePhone" AS "MobilePhone",

            PT."OtherArea" AS "OtherArea",

            PT."OtherPhone" AS "OtherPhone",

            PT."OtherExt" as "OtherExt"

          FROM PATIENT PT

          WHERE PT."Patient" = :1

    ';



	BEGIN

        OPEN results_cur FOR SQLStmt USING vPatient;

    EXCEPTION WHEN NO_DATA_FOUND THEN

        results_cur := NULL;

    END;

END;



-- 59374356 Get Notes Info by TxId and Type

PROCEDURE getnotesinfobytxandtype(IN vtxid integer, IN vtype integer, OUT results_cur cursor_pkg.weakcursor) IS

  SQLStmt  VARCHAR2(4000);

BEGIN

    SQLStmt := '

          SELECT * FROM NOTES2 N2

          WHERE N2."TxId" = :1 AND N2."Type" = :2

    ';



	BEGIN

        OPEN results_cur FOR SQLStmt USING vTxId, vType;

    EXCEPTION WHEN NO_DATA_FOUND THEN

        results_cur := NULL;

    END;

END;



/**

* Function to retrieve data about a particular Ortho Visit and return it as a rec_OrthoVisitDetail RECORD type.<p/>

*

* param: vAutoOv INPUT: ID for the Treatment2 row associated with this ortho visit<p/>

* param: vType INPUT: Flag indicating if this treatment is approved or not approved (0=not approved, 1=approved, 2=not-approved planned)<p/>

* return: rec_OrthoVisitDetail record containing the treatment data.<p/>

*/

FUNCTION getorthovisitdetail(vautoov integer, vtype integer) RETURN rec_orthovisitdetail IS

  ovInfo rec_OrthoVisitDetail;

  vNoteAuto INTEGER;



  CURSOR curNoteOvr(vAuto INTEGER) IS

    SELECT * FROM NOTEOVR

    WHERE "ParentId" = vAuto

    AND "Deleted" = 0

    ORDER BY "Order" ASC;

  vNoteOvrRecord NOTEOVR%ROWTYPE;

BEGIN

    BEGIN

        SELECT DISTINCT

            T2."Auto",

            P2."PtxPId",

            T2."PId",

            T2."Deleted",

            CASE WHEN T2."Deleted" = 0 THEN 'V' ELSE 'D' END AS "Status",

            T2."Discipline",

            T2."Custom1",

            T2."Custom2",

            T2."User",

            TO_CHAR(T2."AddDateTime",'MON DD, YYYY'),

            T2."Provider",

            TO_CHAR(TO_DATE('01-JAN-1901','DD-MON-YYYY') + T2."Days",'MON DD, YYYY') AS "TxDate",

            T2."AppUser",

            TO_CHAR(T2."AppDate",'MON DD, YYYY'),

            T2."DelAppUser",

            TO_CHAR(T2."DelAppDate",'MON DD, YYYY'),

            T2."Unit",

            T2."PId",

            TRIM(PR."Procedure"),

            PR."Description",

            N2."Text",

            N2."Auto"

          INTO ovInfo.OvAuto, ovInfo.OvPatientId, ovInfo.OvPatientAuto, ovInfo.OvDeleted,

               ovInfo.OvStatus, ovInfo.OvDiscipline, ovInfo.OvCustomVal1, ovInfo.OvCustomVal2,

               ovInfo.OvEntryUser, ovInfo.OvEntryDate, ovInfo.OvProvider, ovInfo.OvTxDate,

               ovInfo.OvAppUser, ovInfo.OvAppDate, ovInfo.OvDelUser, ovInfo.OvDelDate,

               ovInfo.OvUnit, ovInfo.OvProcId, ovInfo.OvProcCode, ovInfo.OvProcDesc,

               ovInfo.OvOrthoNote, vNoteAuto

          FROM TREATME2 T2

          LEFT JOIN PROCEDUR PR ON T2."CodeId" = PR."Id"

          LEFT JOIN PATIENT2 P2 ON T2."PId" = P2."Auto"

          LEFT JOIN NOTES2 N2 ON T2."Auto" = N2."TxId" AND N2."Type" = 3

          WHERE T2."Auto" = vAutoOv

          AND T2."Status" = 5					-- Only Ortho Visit

          AND ROWNUM = 1;



        IF vNoteAuto != 0 THEN

          FOR vNoteOvrRecord IN curNoteOvr(vNoteAuto) LOOP

            ovInfo.OvOrthoNote := ovInfo.OvOrthoNote || vNoteOvrRecord."Text";

          END LOOP;

        END IF;



        EXCEPTION WHEN NO_DATA_FOUND THEN

          ovInfo := NULL;

    END;



    RETURN ovInfo;

END;



/**

* Function to retrieve data about a ortho visit treatment from Treatme2 and return it as a rec_OrthoVisitDetail RECORD type. Similar to GetLineDetailTreatment() <p/>

*

* param: vAutoOv INPUT: ID for the Treatment2 row associated with this ortho visit<p/>

* param: vType INPUT: Flag indicating if this treatment is approved or not approved (0=not approved, 1=approved, 2=not-approved planned)<p/>

* return: rec_OrthoVisitDetail record containing the treatment data.<p/>

*/

PROCEDURE getlinedetailorthovisit(IN vautoov integer, IN vtype integer, OUT vdescription character varying, OUT vorthonote character varying, OUT results_cur cursor_pkg.weakcursor) IS

  	SQLStmt  VARCHAR2(4000);



    vCustom1Name CUSTTYPE."Description"%TYPE;

    vCustom2Name CUSTTYPE."Description"%TYPE;

    vCustom3Name CUSTTYPE."Description"%TYPE;

    vCustom4Name CUSTTYPE."Description"%TYPE;



    ovInfo rec_OrthoVisitDetail;

    ptInfo rec_PatientDetail;

    provInfo rec_UserDetail;

    provInfo2 rec_UserDetail;

    appInfo rec_UserDetail;

BEGIN



    -- get custom field names

    GetCustomFieldNames(vCustom1Name,vCustom2Name,vCustom3Name,vCustom4Name);



	-- get the Ortho Visits details

	ovInfo := GetOrthoVisitDetail(vAutoOv, vType);



	IF ovInfo.OvAuto > 0 THEN

		-- get the patient details

		ptInfo := GetPatientDetail(ovInfo.OvPatientId);



		-- get the entry user details

		provInfo := GetUserDetail(ovInfo.OvEntryUser);



        -- get the provider details

		provInfo2 := GetProviderDetail(ovInfo.OvProvider);



		-- get the approval user details

		appInfo := GetUserDetail(ovInfo.OvAppUser);

	END IF;



	-- return the description as a separate parameter

  vDescription := ovInfo.OvProcCode || ' - ' || ovInfo.OvProcDesc;

  vOrthoNote := ovInfo.OvOrthoNote;



  BEGIN

    OPEN results_cur FOR

    SELECT

      ovInfo.OvAuto AS "Auto",

      ptInfo.PtName AS "PatientName",

      ptInfo.PtFirst AS "PatientFirstName",

      ptInfo.PtLast AS "PatientLastName",

      ptInfo.PtAgeSex AS "PatientAgeSex",

      ptInfo.PtChart AS "PatientChart",

      ovInfo.OvProvider AS "Provider",

      ovInfo.OvTxDate AS "TxDate",

      provInfo.UIsProvider AS "EntryUserIsProvider",

      provInfo.UProviderId AS "EntryUserProvId",

      provInfo.UPK AS "EntryUserId",

      provInfo.UName AS "EntryUserName",

      provInfo.UFirst AS "EntryUserFirstName",

      provInfo.ULast AS "EntryUserLastName",

      provInfo2.UName AS "ProducerName",

      provInfo2.UFirst AS "ProducerFirstName",

      provInfo2.ULast AS "ProducerLastName",

      ovInfo.OvEntryDate AS "EntryDate",

      appInfo.UIsProvider AS "AppUserIsProvider",

      appInfo.UProviderId AS "AppUserProvId",

      appInfo.UName AS "AppUserName",

      appInfo.UFirst AS "AppUserFirstName",

      appInfo.ULast AS "AppUserLastName",

      ovInfo.OvAppDate AS "AppDate",

      ovInfo.OvStatus AS "Status",

      ovInfo.OvDeleted AS "Deleted",

      ovInfo.OvDiscipline AS "Discipline",

      ovInfo.OvUnit AS "Unit",

      vCustom1Name AS "Custom1Name",

      ovInfo.OvCustomVal1 AS "Custom1Val",

      vCustom2Name AS "Custom2Name",

      ovInfo.OvCustomVal2 AS "Custom2Val",

      vCustom3Name AS "Custom3Name",

      ovInfo.OvCustomVal3 AS "Custom3Val",

      vCustom4Name AS "Custom4Name",

      ovInfo.OvCustomVal4 AS "Custom4Val"

      FROM DUAL;

    EXCEPTION WHEN NO_DATA_FOUND THEN

    results_cur := null;

  END;

END;



-- 59374356 Get information containing details for a particular Ortho Visit Custom Questions and Answers

PROCEDURE getorthovisitcustomfields(IN vorthoid integer, OUT results_cur cursor_pkg.weakcursor) IS

  SQLStmt  VARCHAR2(4000);

BEGIN



    SQLStmt := '

        SELECT TQ."Item", TQ."Question", TQ."ResponseType", TQ."RespCode", T."TxQuest", T."Response"

        FROM TXQUEST TQ, TXCUST T

        WHERE TQ."Module" = 1

        AND TQ."Inactive" = 0

        AND TQ."TxQuest" = T."TxQuest"(+)

        AND T."Treatme2"(+) = :1

        ORDER BY TQ."Item"

    ';



	BEGIN

        OPEN results_cur FOR SQLStmt USING vOrthoId;

    EXCEPTION WHEN NO_DATA_FOUND THEN

        results_cur := NULL;

    END;

END;



/**

* Procedure to perform a Ortho Visits approval (Status E).<p/>

*

* param: vChartLnk INPUT: ChartLnk ID of the ortho visit (CHARTLNK.Id).<p/>

* param: vAuto INPUT: ID of TREATME2.Auto.<p/>

* param: vInstructor INPUT: User ID of the logged-in user.<p/>

* param: vResult OUTPUT: Flag to indicate if the finding was successfully approved (0=yes, -1=error encountered).<p/>

*/

PROCEDURE doapproveorthovisits(IN vchartlnk integer, IN vauto integer, IN vinstructor integer, OUT vresult integer) IS

  vDeleted INTEGER;

BEGIN

  DELETE FROM CHARTLNK WHERE "Id" = vChartLnk;



  SELECT "Deleted" INTO vDeleted FROM TREATME2 WHERE "Auto" = vAuto AND ROWNUM = 1;



  IF vDeleted = 0 THEN

    UPDATE TREATME2

    SET

    "AppUser" = vInstructor,

    "AppDate" = TRUNC(SYSDATE)

    WHERE "Auto" = vAuto;

  ELSE

    UPDATE TREATME2

    SET

    "DelAppUser" = vInstructor,

    "DelAppDate" = TRUNC(SYSDATE)

    WHERE "Auto" = vAuto;

  END IF;

  COMMIT;

    vResult := 0;

  EXCEPTION WHEN OTHERS THEN

    vResult := -1;

END;



PROCEDURE getmedicaidcodes(OUT vresult cursor_pkg.weakcursor) IS

BEGIN

	OPEN vResult FOR

	SELECT "MedicaidCode" AS "Code"

	FROM PRACTICE

	WHERE NOT (TRIM("MedicaidCode") IS NULL OR LENGTH(TRIM("MedicaidCode")) = 0)

	UNION

	SELECT "MedicaidAPGCode" AS "Code"

	FROM PRACTICE

	WHERE NOT (TRIM("MedicaidAPGCode") IS NULL OR LENGTH(TRIM("MedicaidAPGCode")) = 0);

END;



/**

* Helper function to validate and get procedure code. If Treatment is associated to Ortho Visit code is '***Ortho Visit***'

* param: vTxId INPUT: Treatment ID<p/>

* return: procedure code if the procedure is valid or '***Ortho Visit***' if procedure is associated with OrthoVisitProc, if not return 'Procedure Code - Not on File'

*/

FUNCTION getprocedurecodebytxid(vtxid integer) RETURN character varying IS

  vProcedureCode  VARCHAR2(4000);

  vStatus INTEGER;

BEGIN



  BEGIN

    SELECT TRIM(P."Procedure"), T2."Status" INTO vProcedureCode, vStatus

    FROM PROCEDUR P, TREATME2 T2

    WHERE T2."Auto" = vTxId

    AND T2."CodeId" = P."Id";



    -- Status == 5 Ortho Visits

    IF (vStatus = 5) THEN

      vProcedureCode := '***Ortho Visit***';

    END IF;



    EXCEPTION WHEN NO_DATA_FOUND THEN

    vProcedureCode := ' ';

  END;



  RETURN vProcedureCode;

END;



/**

* Get Language fields by LangCd

* param: vLangCd INPUT: Language Id<p/>

* vResult OUTPUT: Langualge fields<p/>

*/

PROCEDURE getlanguagebylangcd(IN vlangcd character varying, OUT vresult cursor_pkg.weakcursor) IS

BEGIN

  OPEN vResult FOR

    SELECT LG."LangCd", LG."Description", LG."ISOCode", LG."IsDeclined", LG."Default", LG."Inactive"

    FROM LANGCD LG

    WHERE TRIM(LG."LangCd") = TRIM(vLangCd);



  EXCEPTION WHEN NO_DATA_FOUND THEN

    vResult := NULL;

END;



FUNCTION safetonumber(vinput character varying) RETURN numeric IS

  vOutput NUMBER;

BEGIN

  vOutput := TO_NUMBER(vInput);

  RETURN vOutput;



  EXCEPTION WHEN OTHERS THEN RETURN 0;

END;







END;
CREATE OR REPLACE PACKAGE BODY lastappointtrx_pkg IS

FUNCTION ptbalance(familyid numeric) RETURN numeric IS
     PtTotal	NUMBER := 0;
     Today DATE := TRUNC(sysdate);

 BEGIN
  SELECT SUM(T."Total"-T."InsTotal") INTO PtTotal
    FROM TRX T
    WHERE
      T."Type" IN (1,2,3,6,7,73,74) AND 				--AX-24432
      T."Family"=FamilyId AND
      T."TreatmentDate"<=Today AND
      T."Deleted"=0 AND
      T."InDispute"=0 AND
      T."OrthoStatus"<>1;

   IF PtTotal IS NULL THEN
     PtTotal:= 0;
   END IF;

   RETURN PtTotal;
 END;

FUNCTION ptover30balance(familyid numeric) RETURN numeric IS
     PtCharges	NUMBER := 0;
     InsCharges	NUMBER := 0;
     HeldPayments NUMBER := 0;
     PtTotal	NUMBER := 0;
     InsTotal	NUMBER := 0;
     Today DATE := TRUNC(sysdate);

 BEGIN
  SELECT SUM("Total"-"InsTotal"+"PtAdj"+"InsTransfer"-"Payed"),
   SUM("InsTotal"-"InsAdj"-"InsTransfer"-"InsPayed") INTO PtCharges, InsCharges
   FROM TRX WHERE "Family"=FamilyId AND "Type"in(1,2) AND "TreatmentDate"<=Today-30
   AND "Deleted"=0 AND "InDispute"=0 AND "OrthoStatus"<>1;

   IF PtCharges IS NULL THEN
      PtCharges := 0;
   END IF;

   IF InsCharges IS NULL THEN
      InsCharges := 0;
   END IF;

   PtTotal := PtCharges;
   InsTotal := InsCharges;

  SELECT SUM("Payed"+"PtAdj") INTO HeldPayments FROM TRX WHERE "Family"=FamilyId AND
   "Type"in(3,6) AND "TreatmentDate"<=Today AND "Deleted"=0;

   IF HeldPayments IS NULL THEN
      HeldPayments := 0;
   END IF;

   PtTotal := PtTotal + HeldPayments;

   RETURN PtTotal;

 END;

END;
CREATE OR REPLACE PACKAGE BODY medicaid_pkg IS


FUNCTION getnymedconsolidateprocs() RETURN character varying IS
	v_nCount		NUMBER := 0;								-- AX-26071
	v_Procedures VARCHAR2(4000 ) := ' ';			-- AX-26071
BEGIN
	--AX-26071
   SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_MEDICAID_PKG' and PROCEDURE_NAME = UPPER('GetNYMedConsolidateProcs');
   IF v_nCount > 0 THEN
     -- custom package function exists
     EXECUTE IMMEDIATE 'SELECT CUSTOM_MEDICAID_PKG.GetNYMedConsolidateProcs FROM DUAL' INTO v_Procedures;
     RETURN v_Procedures;
   END IF;

	-- modify this procedure to contain all Insurance procedure codes that should
	-- be consolidated, with each code terminated by a ';'
	RETURN 'D1351;';
END;


FUNCTION isancillaryproc(vproc character) RETURN numeric IS
 vCount NUMBER := 0;
BEGIN
 SELECT COUNT(1) INTO vCount FROM PROCEDUR P
  WHERE P."Procedure" = vProc AND (P."IsLab" = 1 OR P."IsXRayExposure" = 1);

 RETURN vCount;
END;

END;
CREATE OR REPLACE PACKAGE BODY onlinereq_pkg IS



	FUNCTION getptlastname(vonlinereqid numeric) RETURN character varying IS

		vPtTableId NUMBER := 0;

		vPtLastNameFieldId NUMBER := 2;

		vName  VARCHAR2(255);

	BEGIN

		vName := GetPtProfileAnswer(vOnlineReqId, vPtTableId, vPtLastNameFieldId);	

		RETURN vName;

	END GetPtLastName;



	FUNCTION getptfirstname(vonlinereqid numeric) RETURN character varying IS

		vPtTableId NUMBER := 0;

		vPtFirstNameFieldId NUMBER := 3;

		vName  VARCHAR2(255);

	BEGIN

		vName := GetPtProfileAnswer(vOnlineReqId, vPtTableId, vPtFirstNameFieldId);	

		RETURN vName;

	END GetPtFirstName;



	FUNCTION getptpreferredname(vonlinereqid numeric) RETURN character varying IS

		vPtTableId NUMBER := 0;

		vPtPreferredNameFieldId NUMBER := 4;

		vName  VARCHAR2(255);

	BEGIN

		vName := GetPtProfileAnswer(vOnlineReqId, vPtTableId, vPtPreferredNameFieldId);	

		RETURN vName;

	END GetPtPreferredName;



	FUNCTION getptprofileanswer(vonlinereqid numeric, vtableid numeric, vfieldid numeric) RETURN character varying IS

		vAnswer  VARCHAR2(255);

		SQLStmt	 VARCHAR2(2000);

	BEGIN

		vAnswer := '';

		BEGIN 

			SQLStmt := 'SELECT A."Answer"

	        		FROM ONLINE_REQUEST_ANSWER A, ONLINE_REQUEST_QUESTION Q, ONLINE_PATCONTROLDEFN D

		       		WHERE A."OnlineRequestQuestionId" = Q."Id" AND Q."RequestId" = :1 AND 

		       		Q."ControlId" = D."Id" AND D."TableId" = :2 AND D."FieldId" = :3';

	       		

			execute immediate SQLStmt into vAnswer using vOnlineReqId, vTableId, vFieldId;

		 	EXCEPTION WHEN NO_DATA_FOUND THEN

				vAnswer := '';

		END;

		

		RETURN vAnswer;

	END GetPtProfileAnswer;

	

	

END;
CREATE OR REPLACE PACKAGE BODY overnight_std_pkg IS





-- B75126 - procedure to be run by all clients.

-- if there is something in here you do not want a

-- client to run, you must remove it from here and 

-- change every other client's overnight procedure

-- to call it explicitly

PROCEDURE all_clients_cleanup() IS

BEGIN

	PTSUMM_PKG.UpdatePtSummaries;	-- E74336

	CLEANUP_FITEM_HISTORY;	

	DELETE_EXPIRED_WAITLIST_APPTS; -- E73078.7.6

  CLEAR_PROCESSING_MESSAGES;	-- ax-11528.11629

  DELETE_DEPT_TXS_ALL;			-- AX-12536.12902

  CLEAR_CUSTOM_EVENTS;			-- AX-12536.12902

  DELETE_LABTMPTRX;				-- AX-19615.5c	

  CLEANUP_CAPREQUESTS;			-- AX-22704

END;





-- Procedure to auto apply all unapplied patient payments

-- INPUT: pStation - Station Id that will be used for the audit records created

-- E137246 added new optional parameter nApplyAll to handle family and payplan allocations;

--				defaulted to 0 to maintain current behavior

--				Willamette and/or KP should have this set to 1

PROCEDURE apply_all_payments(IN pstation numeric, IN nfamilymode numeric DEFAULT 0) IS

  CURSOR C1 IS SELECT * from trx t

      where t."Type"=3 and t."Total"<=-0.01 and (t."Payed"+t."PtAdj")<=-0.01 

      and t."Deleted"=0 ORDER by "Family", "Date", "Id";



  SQLStmt    VARCHAR2(4000);

  

  --E137246 added

  nParameter1		 NUMBER(10);

  nParameter2		 NUMBER(10);

  txPatient			 NUMBER(10);

  txPayPlanId		 NUMBER(10);

  

  TYPE TxCurTyp IS REF CURSOR;

  tx_cur    TxCurTyp;

  txType	NUMBER(10);

  txId		NUMBER(10);

  txTreatment	NUMBER(10);

  Owing		NUMBER;

  loopcnt   pls_integer:=0;

  ApplyAmt	NUMBER:=0;

  ToApply	NUMBER:=0;

  AllocateCnt   NUMBER;

  pUser		number(10);

  bApplied  BOOLEAN;	-- B39349

  vPmtTreatment TRX."Treatment"%TYPE := 0;												--E81852

  vPmtTxCnt   pls_integer:=0;																	--E81852

  vOrigRecNo	TRX."OrigRecNo"%TYPE := 0;													--E81852

  vModifiedDate		DATE;																		--AX-1849.3279d

  TxHistoryId		NUMBER(10);						--AX-26086

  AllocateLinkId	NUMBER(10);						--AX-26086 

  TYPE IdArray IS VARRAY(100) OF NUMBER(10);		--AX-26086

  TxHistoryIds		IdArray := IdArray();			--AX-26086

  AllocateLinkIds	IdArray := IdArray();			--AX-26086

  IdsCount	NUMBER(10):=0;      					--AX-26086

  PmtHistoryId		NUMBER(10);						--AX-26086



BEGIN

  select "OvernightUser" into pUser from Axiumopt;



  <<outer_loop>>

  for c in C1 LOOP



    ToApply := -(c."Payed" + C."PtAdj");

    bApplied := FALSE;	-- B39349

  

	--B101453 added line to check if the office charge is a pre-payment

	--B135551 added  OR "ChartTrx" = 0 to pick up non-clinical treatments

	

	--E137246 added to handle family / independent payplan allocations

	 if nFamilyMode <> 0 THEN 

		-- E137246 added to load patient (who can make payments for him/herself) and all guarantees under the payor, 

		--		regardless of payplan ids; added Patient and PayPlanId; E137246.2

		SQLStmt := 'select "Patient", "Type","Id","Treatment", "PayPlanId",

       ("Total"-"InsTotal"-"Payed"+"PtAdj"+"InsTransfer") TxOwing from trx 

       where "Family" IN (SELECT :1 FROM DUAL UNION ALL SELECT "Patient" FROM PTGUAR WHERE 

       "Inactive" = 0 AND "Deleted" = 0 AND "RespPatient" =:2)

       and "Type"in (1,2) and "Deleted"=0 and "OrthoStatus" <> 1 and "InDispute" = 0 and 

	   ("Total"-"InsTotal"-"Payed"+"PtAdj"+"InsTransfer")>=0.01

	   and ("Type"=2 OR "ChartTrx" = 0 or not exists (select 1 from chartlnk C where 

       C."Previous" = "ChartTrx" or C."Auto"="ChartTrx"))

       and not ("Type"=2 and exists (select 1 from ofcharge o where o."OfficeCharge"=trx."Code" and o."IsPrepay"=1))

       order by "TreatmentDate", "Type", "Id","Treatment" ';

      nParameter1 := c."Family";

		nParameter2 := c."Patient";



	 ELSE

		-- E137246 added Patient and PayPlanId; E137246.2

		SQLStmt := 'select "Patient", "Type","Id","Treatment", "PayPlanId",										

       ("Total"-"InsTotal"-"Payed"+"PtAdj"+"InsTransfer") TxOwing from trx 

       where "Family"=:1 and "Type"in (1,2) and "PayPlanId" = :2 and 

       "Deleted"=0 and "OrthoStatus" <> 1 and "InDispute" = 0 and 

	   ("Total"-"InsTotal"-"Payed"+"PtAdj"+"InsTransfer")>=0.01

	   and ("Type"=2 OR "ChartTrx" = 0 or not exists (select 1 from chartlnk C where 

       C."Previous" = "ChartTrx" or C."Auto"="ChartTrx"))

       and not ("Type"=2 and exists (select 1 from ofcharge o where o."OfficeCharge"=trx."Code" and o."IsPrepay"=1))

       order by "TreatmentDate", "Type", "Id","Treatment" ';							

      nParameter1 := c."Family";																	-- E137246

		nParameter2 := C."PayPlanId";																-- E137246

	END IF;



    OPEN tx_cur FOR SQLStmt USING nParameter1, nParameter2;					-- E137246 changed to use preset parameters

    

	 SELECT sysdate into vModifiedDate from dual;										--AX-1849.3279d

    

    <<inner_loop>>

    LOOP

        FETCH tx_cur INTO txPatient, txType, txId, txTreatment, txPayPlanId, Owing;	-- E137246 added more output 

        EXIT inner_loop WHEN tx_cur%NOTFOUND;



        ApplyAmt := least(Owing, ToApply);

        if ApplyAmt>=0.01 then	-- B79575

            -- E00691 took out the trunc when setting ModifiedDate

        	EXECUTE IMMEDIATE 'UPDATE TRX SET "Payed"="Payed"+:1, 

                    "ModifiedDate"=:2, "User"=:3, "StationId"=:4 

                    where "Type"=:5 and "Id"=:6 and "Treatment"=:7' 

	                USING ApplyAmt,vModifiedDate,pUser,pStation,

	                txType,txId, txTreatment;													--AX-1849.3279d



			-- AX-26086

			select HISTORY_HISTORY_SEQ.nextval into TxHistoryId from dual;



	        EXECUTE IMMEDIATE 'insert into HISTORY (select 

                    :1, 3, Trx.* from trx where 

                    "Type"=:2 and "Id"=:3 and "Treatment"=:4)'

		            using TxHistoryId, txType, txId, txTreatment;



            -- B35645 update/set new User field in ALLOCATE table

	        begin



				-- AX-26086

				SELECT ALLOCATELINK_LINK_SEQ.NEXTVAL INTO AllocateLinkId FROM dual;

		

				-- AX-26086 Insert with AllocateLinkId

		        EXECUTE IMMEDIATE 'INSERT INTO ALLOCATE VALUES 

					(:1,:2,:3,:4,:5,:6,0,:7,:8,:9)'

	                USING C."Type", c."Id", c."Treatment", txType,txId, 

                    txTreatment,ApplyAmt,pUser,AllocateLinkId;

				exception

				when DUP_VAL_ON_INDEX then



				-- AX-26086 Update with AllocateLinkId; AX-26251.jso

				EXECUTE IMMEDIATE 'UPDATE ALLOCATE set "Amount"="Amount"+:1, 

                    "User"=:2, "AllocateLink"=:3 where "PayType"=:4 and "PayId"=:5 and 

                    "PayTreatment"=:6 and "TrxType"=:7 and "TrxId"=:8 and 

                    "TrxTreatment"=:9'  

	                USING ApplyAmt, pUser, AllocateLinkId, C."Type", c."Id", c."Treatment", 

                    txType,txId, txTreatment;

			end;

    			

			-- AX-26086

			IdsCount := IdsCount + 1;

            TxHistoryIds.extend;

            AllocateLinkIds.extend;

            AllocateLinkIds(IdsCount) := AllocateLinkId;

            TxHistoryIds(IdsCount) := TxHistoryId;



				--E81852 added to handle new type 73's

				-- E137246 use variables instead of payment's Family and PayPlanId throughout

		     SELECT COUNT(1) INTO vPmtTxCnt FROM TRX T WHERE T."Type" = 73 AND 

						T."Id" = C."Id" AND T."Family" = txPatient AND T."PayPlanId" = txPayPlanId;		-- E137246

						

				if vPmtTxCnt > 0  then

			        	UPDATE TRX SET "Total"="Total"-ApplyAmt, 

				            "ModifiedDate"=vModifiedDate, "User"=pUser, "StationId"=pStation, "Deleted"=0 

					         where "Type"=73 and "Id"=C."Id" and "Family"=txPatient 

					         and "PayPlanId"=txPayPlanId;																-- E137246; AX-1849.3279d

				

					   INSERT into HISTORY (select HISTORY_HISTORY_SEQ.nextval, 3, trx.* from trx where "Type"=73 

								and "Id"=C."Id" and "Family"=txPatient and "PayPlanId"=txPayPlanId);			-- E137246 

				else

				      SELECT NVL(MAX("Treatment"), 0) INTO vPmtTreatment FROM TRX T WHERE T."Type" = 73 AND T."Id" = C."Id";

				      vPmtTreatment := vPmtTreatment + 1;

						SELECT TRX_ORIGRECNO_SEQ.nextval into vOrigRecNo from dual;

						-- E00666.7.4b								

						INSERT INTO TRX values (

									73,				--Type                           NOT NULL NUMBER(5); B128448

									C."Id",			--Id                             NOT NULL NUMBER(10)

									vPmtTreatment,	--Treatment                      NOT NULL NUMBER(5)

									C."Patient",	--Patient                                 NUMBER(10)

									txPatient,		--Family                                  NUMBER(10); E137246

									' ',			--Status                                   CHAR(6)

									' ',			--EDI                                      CHAR(15)

									0,				--EDIStatus                               NUMBER(5)

									c."Date",	--Date                                    DATE

									null,			--SubmitDate                              DATE

									' ',			--ClaimDoctor                              CHAR(10)

									0,				--Submitted                               NUMBER(5)

									c."TreatmentDate", --TreatmentDate                           DATE

									c."CreationDate",	 --CreationDate                            DATE

									' ',			--Procedure                                CHAR(7)

									c."Code",	--Code                                     CHAR(6)

									' ',			--Site                                     CHAR(3)

									' ',			--Surface                                  CHAR(6)

									0,				--Unit                                    FLOAT(0)

									' ',			--Producer                                 CHAR(10)

									-ApplyAmt,	--Total                                   FLOAT(0)

									0,				--InsTotal                                FLOAT(0)

									' ',			--Company1                                 CHAR(6)	

									' ',			--Policy1                                  CHAR(15)

									' ',			--Category1                                CHAR(6)

									0,				--Item1                                   NUMBER(10)

									0,				--Deduct1                                 FLOAT(0)

									0,				--Assign1                                 NUMBER(5)

									0,				--Eligible1                               FLOAT(0)

									0,				--Pct1                                    FLOAT(0)

									0,				--Amount1                                 FLOAT(0)

									0,				--InsPayed1                               FLOAT(0)

									0,				--InsAdj1                                 FLOAT(0)

									' ',			--Company2                                 CHAR(6)

									' ',			--Policy2                                  CHAR(15)

									' ',			--Category2                                CHAR(6)

									0,				--Item2                                   NUMBER(10)

									0,				--Assign2                                 NUMBER(5)

									0,				--Deduct2                                 FLOAT(0)

									0,				--Eligible2                               FLOAT(0)

									0,				--Pct2                                    FLOAT(0)

									0,				--Amount2                                 FLOAT(0)

									0,				--InsPayed2                               FLOAT(0)

									0,				--InsAdj2                                 FLOAT(0)

									' ',			--Company3                                 CHAR(6)

									' ',			--Policy3                                  CHAR(15)

									' ',			--Category3                                CHAR(6)

									0,				--Item3                                   NUMBER(10)

									0,				--Assign3                                 NUMBER(5)

									0,				--Deduct3                                 FLOAT(0)

									0,				--Eligible3                               FLOAT(0)

									0,				--Pct3                                    FLOAT(0)

									0,				--Amount3                                 FLOAT(0)

									0,				--InsPayed3                               FLOAT(0)

									0,				--InsAdj3                                 FLOAT(0)

									TRIM(c."Description"),	--Description                              CHAR(30)

									0,				--Deleted                                 NUMBER(5)

									c."Bank",		--Bank                                     CHAR(6)

									0,				--Payed                                   FLOAT(0)

									0,				--InsPayed                                FLOAT(0)

									0,				--PtAdj                                   FLOAT(0)

									0,				--InsAdj                                  FLOAT(0)

									0,				--EstimateF                               NUMBER(10)

									' ',			--Additional                               CHAR(7)

									' ',			--TxStatus                                 CHAR(6)

									pUser,			--User                                    NUMBER(10)

									0,				--PtWriteOff                              FLOAT(0)

									0,				--PolicyId1                               NUMBER(10)

									0,				--PolicyId2                               NUMBER(10)

									0,				--PolicyId3                               NUMBER(10)

									0,				--InsStatus1                              NUMBER(5)

									0,				--InsStatus2                              NUMBER(5)

									0,				--InsStatus3                              NUMBER(5)

									0,				--IsBankDeposit                           NUMBER(5)

									0,				--ChartTrx                                NUMBER(10)

									0,				--PlanTotal                               FLOAT(0)

									' ',			--Phase                                    CHAR(2)

									0,				--Seq                                     NUMBER(5)

									0,				--AppUser                                 NUMBER(10)

									null,			--AppDate                                 DATE

									0,				--Grading                                 NUMBER(10)

									' ',			--Site2                                    CHAR(3)

									' ',			--Custom1                                  CHAR(6)

									' ',			--Custom2                                  CHAR(6)

									txPayPlanId,	--PayPlanId                            NUMBER(10)		--B86041; E137246

									' ',			--Discipline                               CHAR(15)

									0,				--DiscountedPmtId                         NUMBER(10)

									' ',			--Location                                 CHAR(6)

									0,				--OrigAssign1                             NUMBER(5)

									0,				--OrigAssign2                             NUMBER(5)

									0,				--OrigAssign3                             NUMBER(5)

									0,				--InDispute                               NUMBER(5)

									null,			--DisputeDate                             DATE

									null,			--DeletionDate                            DATE

									' ',			--EDIPat                                   CHAR(15)

									0,				--EDIPatStatus                            NUMBER(5)

									0,				--InsTransfer1                            FLOAT(0)

									0,				--InsTransfer2                            FLOAT(0)

									0,				--InsTransfer3                            FLOAT(0)

									0,				--InsTransfer                             FLOAT(0)

									0,				--InsPmtId                                NUMBER(10)

									pStation,	--StationId                               NUMBER(10)

									0,				--Practice                                NUMBER(5)

									0,				--Suspended                               NUMBER(5)

									0,				--DelAppUser                              NUMBER(10)

									null,			--DelAppDate                              DATE

									0,				--OrthoStatus                             NUMBER(5)

									0,				--CvgType                                 NUMBER(5)

									vModifiedDate,	--ModifiedDate                            DATE; AX-1849.3279d

									null,			--OrigClaimDate                           DATE

									0,				--SubmitMode                              NUMBER(5)

									' ',			--Custom3                                  CHAR(6)

									' ',			--Custom4                                  CHAR(6)

									' ',			--CorrespondCode                           CHAR(7)

									0,				--InsCvgType1                             NUMBER(5)

									0,				--InsCvgType2                             NUMBER(5)

									0,				--InsCvgType3                             NUMBER(5)

									vOrigRecNo,		--OrigRecNo                               NUMBER(10)

									pUser,			--EntryUser                               NUMBER(10)

									0,				--PlanInProcTotal                         FLOAT(0)

									0,				--TrxDep                                  NUMBER(10)

									0,				--CustomaryTotal (E53636)

									0,				--TaxRate											NUMBER

									0				--TaxAmount											NUMBER

							  );

	

						-- E137246 use variables instead of payment's Family and PayPlanId

					   INSERT into HISTORY (select HISTORY_HISTORY_SEQ.nextval, 1, trx.* from trx where "Type"=73 

								and "Id"=C."Id" and "Treatment"=vPmtTreatment and "Family"=txPatient and "PayPlanId"=txPayPlanId);	

	

				end if;

				--E81852 end

				

            -- E00691 took out the trunc when setting ModifiedDate

            EXECUTE IMMEDIATE 'UPDATE TRX SET "Payed"="Payed"+:1, 

                    "ModifiedDate"=:2, "User"=:3, "StationId"=:4 

                    where "Type"=:5 and "Id"=:6 and "Treatment"=:7' 

                    USING ApplyAmt,vModifiedDate,pUser,pStation,

                    C."Type", c."Id", c."Treatment";										--AX-1849.3279d

                    

            ToApply:=ToApply-ApplyAmt;

            bApplied := TRUE;	-- B39349

        end if;

    

        if ToApply<0.01 then

            EXIT inner_loop;

        end if;

        

    END LOOP;

    CLOSE tx_cur;



    if bApplied = TRUE then	-- B39349

		

		-- AX-26086 Getting Pmt history id.

		select HISTORY_HISTORY_SEQ.nextval into PmtHistoryId from dual;



		EXECUTE IMMEDIATE 'insert into HISTORY (select 

            :1, 3, trx.* from trx where "Type"=:2 

            and "Id"=:3 and	"Treatment"=:4)'

		    using PmtHistoryId, C."Type", C."Id", C."Treatment";



		-- AX-26086 Insert into AllocateLink table for each payment

		FOR i in 1 .. IdsCount LOOP

			EXECUTE IMMEDIATE 'INSERT INTO ALLOCATELINK VALUES 

								(:1,:2,:3,:4)'

								USING AllocateLinkIds(i), TxHistoryIds(i), PmtHistoryId, vModifiedDate;

		END LOOP;



		AllocateLinkIds.DELETE;

		TxHistoryIds.DELETE;



		IdsCount := 0;



    end if;	-- B39349



  END LOOP;

  

  commit;

  

END;



-- E21522.3; E21522.4

-- Procedure to auto apply all patient prepayments

-- INPUT: pStation - Station Id that will be used for the audit records created

--		  pOptionalUser - User Id if known, otherwise pass zero and the function 

--				will look it OvernightUser in AxiumOpt to use

--		  PPCount is the number of pre-payment this procedure processed (returned to caller) 	

PROCEDURE apply_all_prepayments(IN pstation numeric, IN poptionaluser numeric, IN patientid numeric, OUT ppcount numeric) IS

  SQLMainStmt    VARCHAR2(4000);

  SQLStmt    VARCHAR2(4000);

  SQLSubStmt    VARCHAR2(4000);

  TYPE Prepay_RecType IS RECORD (

			"Family" NUMBER(10), 

			"OChgType" NUMBER(5),

			"OChgId" NUMBER(10), 

	  		"OChgTreatment" NUMBER(5),

			"Practice" NUMBER(10), 

			"Producer"  CHAR(10), 

			"Discipline"  CHAR(15), 

			"Custom1"  CHAR(6), 

			"Custom2"  CHAR(6), 

			"Amount" NUMBER, 

			"PmtType" NUMBER(5), 

			"PmtId" NUMBER(10), 

			"PmtTreatment" NUMBER(5), 

			"PayPlanId" NUMBER(10));

  c    Prepay_RecType;

  TYPE PrepayCurTyp IS REF CURSOR;

  prepay_cur    PrepayCurTyp;

  TYPE TxCurTyp IS REF CURSOR;

  tx_cur    TxCurTyp;

  txType	NUMBER(10);

  txId		NUMBER(10);

  txTreatment	NUMBER(10);

  Owing		NUMBER;

  loopcnt   pls_integer:=0;

  ApplyAmt	NUMBER:=0;

  ToApply	NUMBER:=0;

  AllocateCnt   NUMBER;

  pUser		number(10);

  bApplied  BOOLEAN;	

  vModifiedDate		DATE;																		--AX-1849.3279d

  TxHistoryId				NUMBER(10);				--AX-26086

  AllocateLinkId			NUMBER(10);				--AX-26086

  PrepayAllocateLinkId		NUMBER(10);				--AX-26086 

  TYPE IdArray IS VARRAY(100) OF NUMBER(10);		--AX-26086

  TxHistoryIds		IdArray := IdArray();			--AX-26086

  AllocateLinkIds	IdArray := IdArray();			--AX-26086

  IdsCount					NUMBER(10):=0;      	--AX-26086

  PmtHistoryId				NUMBER(10);				--AX-26086

  OfficeChargeHistoryId		NUMBER(10);				--AX-26086

   

BEGIN

  if  pOptionalUser <> 0  then

  	pUser := pOptionalUser;

  else

    select "OvernightUser" into pUser from Axiumopt;

  end if;



  PPCount := 0;			--B48653

   	

  SQLMainStmt := 'SELECT o."Family", o."Type" "OChgType", o."Id" "OChgId", 

  		o."Treatment" "OChgTreatment", o."Practice", o."Producer", 

		o."Discipline", o."Custom1", o."Custom2", a."Amount", 

		p."Type" "PmtType", p."Id" "PmtId", p."Treatment" "PmtTreatment", 

		o."PayPlanId"																					-- B140622

	    from trx o, allocate a, trx p

        where ';

  if  PatientId <> 0   then

	  SQLMainStmt := SQLMainStmt || 'o."Family" = ' || PatientId  || ' and ';

  end if;

  

  --B138256 added Type = 3 clause; B138256.2

  SQLMainStmt := SQLMainStmt || 'o."Type"=2 and o."PlanTotal" > 0.0 

      and o."Payed" > 0.0 and o."Deleted"=0 and o."Type" = a."TrxType" 

	  and o."Id" = a."TrxId" and o."Treatment" = a."TrxTreatment" 

	  and a."PayType" = p."Type" and a."PayId" = p."Id" 

	  and a."PayTreatment" = p."Treatment" 

	  and a."PayType" = 3 and a."Amount" > 0						

	  ORDER by o."Family", o."Date", o."Id"';



  -- for each pre-payment office charge line

  OPEN prepay_cur FOR SQLMainStmt;

  <<outer_loop>>

  LOOP			-- for each tx which matches the given criteria  

    FETCH prepay_cur INTO c;

    EXIT outer_loop WHEN prepay_cur%NOTFOUND;



    ToApply := c."Amount";

    bApplied := FALSE;	



	-- load all txs which match the given criteria  

    SQLStmt := 'select "Type","Id","Treatment", 

       ("Total"-"InsTotal"-"Payed"+"PtAdj"+"InsTransfer") TxOwing from trx 

       where "Family"=:1 and "Type"in (1,2) and "PayPlanId" = :2 and 

       "Deleted"=0 and "OrthoStatus" <> 1 and "InDispute" = 0 ';

    if c."Practice" <> 0 then

		SQLStmt := SQLStmt || 'and "Practice" = ' || c."Practice";

    end if;

    if Length(TRIM(c."Producer")) > 0 then

		SQLStmt := SQLStmt || 'and "Producer" = ''' || c."Producer" || '''';

    end if;

    if Length(TRIM(c."Discipline")) > 0 then

		SQLStmt := SQLStmt || 'and "Discipline" = ''' || c."Discipline" || '''';

    end if;

    if Length(TRIM(c."Custom1")) > 0 then

		SQLStmt := SQLStmt || 'and "Custom1" = ''' || c."Custom1" || '''';

    end if;

    if Length(TRIM(c."Custom2")) > 0 then

		SQLStmt := SQLStmt || 'and "Custom2" = ''' || c."Custom2" || '''';

    end if;

	--B101453 added line to check if the office charge is a pre-payment

	--B135551 added  OR "ChartTrx" = 0 to pick up non-clinical treatments

	SQLStmt := SQLStmt || 

	   ' and ("Total"-"InsTotal"-"Payed"+"PtAdj"+"InsTransfer")>=0.01

	   and ("Type"=2 OR "ChartTrx" = 0 or not exists (select 1 from chartlnk C where 

       C."Previous" = "ChartTrx" or C."Auto"="ChartTrx"))

       and not ("Type"=2 and exists (select 1 from ofcharge o where o."OfficeCharge"=trx."Code" and o."IsPrepay"=1))

       order by "Date", "Type", "Id","Treatment" ';



    SELECT sysdate into vModifiedDate from dual;										--AX-1849.3279d



	-- AX-26086

	SELECT ALLOCATELINK_LINK_SEQ.NEXTVAL INTO PrepayAllocateLinkId FROM dual;



    OPEN tx_cur FOR SQLStmt USING c."Family", c."PayPlanId";

    <<inner_loop>>

    LOOP			-- for each tx which matches the given criteria  

        FETCH tx_cur INTO txType, txId, txTreatment, Owing;

        EXIT inner_loop WHEN tx_cur%NOTFOUND;

    

        ApplyAmt := least(Owing, ToApply);

        if ApplyAmt>=0.01 then	-- B79575

        	-- apply the pre-payment to the tx

        	EXECUTE IMMEDIATE 'UPDATE TRX SET "Payed"="Payed"+:1, 

                    "ModifiedDate"=:2, "User"=:3, "StationId"=:4 

                    where "Type"=:5 and "Id"=:6 and "Treatment"=:7' 

	                USING ApplyAmt,vModifiedDate, pUser,pStation,

	                txType,txId, txTreatment;												--AX-1849.3279d	



            -- AX-26086

            select HISTORY_HISTORY_SEQ.nextval into TxHistoryId from dual;



        	-- create history

	        EXECUTE IMMEDIATE 'insert into HISTORY (select 

                    :1, 3, Trx.* from trx where 

                    "Type"=:2 and "Id"=:3 and "Treatment"=:4)'

		            using TxHistoryId, txType, txId, txTreatment;



            -- AX-26086

            SELECT ALLOCATELINK_LINK_SEQ.NEXTVAL INTO AllocateLinkId FROM dual;

            

	        begin



	           EXECUTE IMMEDIATE 'INSERT INTO ALLOCATE VALUES 

                    (:1,:2,:3,:4,:5,:6,0,:7,:8,:9)'                         -- added AllocateLink id (AX-25978.2), AX-26086 Updated AllocatLink id with a real value.

	                USING C."PmtType", c."PmtId", c."PmtTreatment", 

					txType, txId, txTreatment, ApplyAmt, pUser, AllocateLinkId;

        	   exception

        	   when DUP_VAL_ON_INDEX then

	           EXECUTE IMMEDIATE 'UPDATE ALLOCATE set "Amount"="Amount"+:1, 

                    "User"=:2, "AllocateLink"=:3 where "PayType"=:4 and "PayId"=:5 and 

                    "PayTreatment"=:6 and "TrxType"=:7 and "TrxId"=:8 and 

                    "TrxTreatment"=:9'

	                USING ApplyAmt, pUser, AllocateLinkId, C."PmtType", c."PmtId", 

					c."PmtTreatment", txType, txId, txTreatment;    -- AX-26086; AX-26251.jso

	        end;

    

			-- AX-26086

			IdsCount := IdsCount + 1;

            TxHistoryIds.extend;

            AllocateLinkIds.extend;

            AllocateLinkIds(IdsCount) := AllocateLinkId;

            TxHistoryIds(IdsCount) := TxHistoryId;

    

    		-- update the prepayment office charge

            EXECUTE IMMEDIATE 'UPDATE TRX SET "Payed"="Payed"-:1, 

                    "ModifiedDate"=:2, "User"=:3, "StationId"=:4 

                    where "Type"=:5 and "Id"=:6 and "Treatment"=:7' 

                    USING ApplyAmt,vModifiedDate, pUser,pStation,

                    c."OChgType", c."OChgId", c."OChgTreatment";					--AX-1849.3279d

           		   

			-- AX-26086; AX-26251.jso

			EXECUTE IMMEDIATE 'UPDATE ALLOCATE set "Amount"="Amount"-:1, 

                    "User"=:2, "AllocateLink"=:3 where "PayType"=:4 and "PayId"=:5 and 

                    "PayTreatment"=:6 and "TrxType"=:7 and "TrxId"=:8 and 

                    "TrxTreatment"=:9'  

	                USING ApplyAmt, pUser, PrepayAllocateLinkId, c."PmtType", c."PmtId", 

					c."PmtTreatment", c."OChgType", c."OChgId", 

					c."OChgTreatment";

			

			-- delete the allocate if zero allocate...

            EXECUTE IMMEDIATE 'DELETE FROM ALLOCATE where "PayType"=:1 and 

		   			"PayId"=:2 and "PayTreatment"=:3 and "TrxType"=:4 and 

					"TrxId"=:5 and "TrxTreatment"=:6 and "Amount" = 0'

	                USING c."PmtType", c."PmtId", c."PmtTreatment", 

					c."OChgType", c."OChgId", c."OChgTreatment";

			

			-- update the payment record     

            EXECUTE IMMEDIATE 'UPDATE TRX SET "PlanTotal"="PlanTotal"+:1, 

                    "ModifiedDate"=:2, "User"=:3, "StationId"=:4 

                    where "Type"=:5 and "Id"=:6 and "Treatment"=:7' 

                    USING ApplyAmt,vModifiedDate, pUser,pStation,

                    c."PmtType", c."PmtId", c."PmtTreatment";						--AX-1849.3279d	

					

                    

            ToApply:=ToApply-ApplyAmt;

            bApplied := TRUE;	

        end if;

    

        if ToApply<0.01 then

            EXIT inner_loop;

        end if;

        

    END LOOP;

    CLOSE tx_cur;



    if bApplied = TRUE then	

    	

	  -- AX-26086 History id for pre-payment office charge 

      select HISTORY_HISTORY_SEQ.nextval into OfficeChargeHistoryId from dual;



	  -- create history for payment record with pre-payment

	  EXECUTE IMMEDIATE 'insert into HISTORY (select 

            :1, 3, trx.* from trx where "Type"=:2 

            and "Id"=:3 and	"Treatment"=:4)'

		    using OfficeChargeHistoryId, c."OChgType", c."OChgId", c."OChgTreatment";

   

  	  -- AX-26086 Payment history id 

      select HISTORY_HISTORY_SEQ.nextval into PmtHistoryId from dual;

	   

      -- AX-26086 

	  EXECUTE IMMEDIATE 'insert into HISTORY (select 

            :1, 3, trx.* from trx where "Type"=:2 

            and "Id"=:3 and	"Treatment"=:4)'

		    using PmtHistoryId, c."PmtType", c."PmtId", c."PmtTreatment";

		    

	  --E81852 update the type 73's; no changes in allocate amount 

      EXECUTE IMMEDIATE 'UPDATE TRX SET "ModifiedDate"=:1, 

				 "User"=:2, "StationId"=:3 

              where "Type"=73 and "Id"=:4 and "Family"=:5 and "PayPlanId"=:6' 

              USING vModifiedDate, pUser,pStation,c."PmtId", 

              c."Family", c."PayPlanId";														--AX-1849.3279d

              

      EXECUTE IMMEDIATE 'INSERT INTO HISTORY (select 

            HISTORY_HISTORY_SEQ.nextval, 3, trx.* from trx where "Type"=73 

            and "Id"=:1 and "Family"=:2 and "PayPlanId"=:3)' 

            USING c."PmtId", c."Family", c."PayPlanId";

		--E81852 end



	  PPCount := PPCount + 1;			--B48653



      -- AX-26086 Insert into AllocateLink table for each payment

      FOR i in 1 .. IdsCount LOOP

		  EXECUTE IMMEDIATE 'INSERT INTO ALLOCATELINK VALUES 

			  				(:1,:2,:3,:4)'

							USING AllocateLinkIds(i), TxHistoryIds(i), PmtHistoryId, vModifiedDate;

	  END LOOP;



	  AllocateLinkIds.DELETE;

	  TxHistoryIds.DELETE;



	  IdsCount := 0;



	  EXECUTE IMMEDIATE 'INSERT INTO ALLOCATELINK VALUES 

			  			(:1,:2,:3,:4)'

						USING PrePayAllocateLinkId, OfficeChargeHistoryId, PmtHistoryId, vModifiedDate;



	END IF;

  END LOOP;

  

  commit;

  

END;



PROCEDURE checkout_patients(IN doaudit numeric) IS

    Counter NUMBER(10);

    AuditId NUMBER(10);

BEGIN

    if DoAudit > 0 then

        select count(1) into Counter from patient where "IsIn"=1;

        if Counter > 0 then

	       AuditId := OVERNIGHT_STD_PKG.Create_Audit('PATIENT',2,1);

	       update patient p set p."IsIn"=0, "Audit"=AuditId where p."IsIn"=1;

	       commit;

        end if;

    else

        UPDATE PATIENT SET "IsIn" = 0 WHERE "IsIn" = 1;

        COMMIT;

    end if;

END;



-- Function to create an AUDITHIS record

-- INPUT: 	TableName - name of the table being audited, i.e. PATIENT, 

--          TRXPOL, etc

--		HistoryType - Action that the audit record is for

--				1 = add

--				2 = edit

--				4 = delete

--		AuditStation - Station id of the computer being audited,

--               ptr to STATION.StationId

--

-- OUTPUT:	AuditId - ptr to AUDITHIS.Audit record created

FUNCTION create_audit(tablename character, historytype numeric, auditstation numeric) RETURN numeric IS

	AuditId NUMBER(10);

	UserId NUMBER(10);

	StationId NUMBER(10);

	RecordExists NUMBER;

BEGIN

	select AUDITHIS_AUDIT_SEQ.nextval into AuditId from dual;

	select "OvernightUser" into UserId from Axiumopt;



	select count(1) into RecordExists from station where 

            "StationId"=AuditStation;

	if RecordExists = 0 then

		select min("StationId") into StationId from Station where "Deleted"=0;

	else

		StationId := AuditStation;

	end if;



	insert into audithis values (

		AuditId,	--Audit                          NOT NULL NUMBER(10)

		trunc(sysdate),	--Date                                    DATE

		trunc(to_char(sysdate,'SSSSS')/60),	--Time        NUMBER(10)

		UserId,	--User                                    NUMBER(10)

		StationId,	--StationId                               NUMBER(10)

		TableName,	--TableName                                CHAR(8)

		HistoryType	--HistoryType                             NUMBER(5)

	);

	return AuditId;

END;



--B28511 check if there is also a valid assignment and don't delete if so

--B28511.1 fixed problem with above where it wasn't removing records if 

--              the expired assignment was not deleted

PROCEDURE delete_expired_assignments() IS

BEGIN 

    delete from selected L 

        where exists (select 'x' from ptprod P, selected S, users U 

        where S."Patient"=P."Patient" and S."User"=U."User" and 

        U."Producer"=P."Producer" and (P."EndDate"< sysdate or P."Deleted"=1) 

        and S."User"=L."User" and L."Patient"=S."Patient")

        and not exists (select 'x' from ptprod P, selected S, users U 

        where S."Patient"=P."Patient" and S."User"=U."User" and 

        U."Producer"=P."Producer" and P."EndDate"> trunc(sysdate) and 

        P."StartDate" <= trunc(sysdate) and P."Deleted"=0 and 

        S."User"=L."User" and L."Patient"=S."Patient"

    );

    commit;

END;



--

-- ClearHeldPts indicates clearing SELECTED with HELD= 

PROCEDURE delete_selected_pts(IN clearheldpts numeric, IN clearallusers numeric) IS 

BEGIN

    if ClearAllUsers > 0 then

        -- clear for all users   

        if ClearHeldPts > 0 then

            -- clear all including held ones

            DELETE SELECTED;

            commit;

        else

            -- clear all except held ones

            DELETE SELECTED WHERE "Held"=0;	

            commit;

        end if;

    else

        -- clear for users with auto-select on

        if ClearHeldPts > 0 then

            -- clear all including held ones

            delete selected s where s."User" in (select distinct(u."User") 

                    from ubook u where u."AutoSelect"=1);

            commit;

        else

            -- clear all except held ones

            DELETE SELECTED WHERE "Held"=0 and "User" in (select 

                    distinct("User") from ubook where "AutoSelect"=1);	

            commit;

        end if;

    end if;

END;



-- E54754

PROCEDURE generate_ptbal(IN imethod numeric DEFAULT 0) IS

	vTableExists NUMBER;

BEGIN

	EXECUTE IMMEDIATE 'truncate table ptbal';

	EXECUTE IMMEDIATE 'truncate table ptbalbat';

	SELECT COUNT(1) INTO vTableExists from user_tables WHERE table_name = 'PTBALEXT';

	IF vTableExists > 0 THEN

		EXECUTE IMMEDIATE 'truncate table ptbalext';

	END IF;

	ptbal_pkg.PTBAL_ASAT_ALLPATIENTS(sysdate,0,iMethod,0,0);								-- E73212

END;







PROCEDURE preload_patient_list() IS 



    TYPE user_array IS VARRAY(1000) OF NUMBER(10);

    TYPE patient_array IS VARRAY(1000) OF NUMBER(10);



    v_User    user_array;

    v_Patient patient_array;

  

    CURSOR selected_cursor IS 

        SELECT * from (	    -- B30257 Changed the rownum <= 1000 

                            --  to be in an outer query

            SELECT DISTINCT U."User", P."Patient"

            FROM  USERS U, PATIENT P, APPOINT A, BOOK B, UBOOK UB,

            BOOKDET BD, BOOKCHR BC    -- B32222 joined in new tables  

            WHERE U."User" = UB."User"  -- User is from UBOOK table

            AND B."Book" = UB."Book"    -- Book is from UBOOK table

            AND B."ReservesByProvider" = 0 -- B53866 

			AND B."Inactive" = 0			-- AX-25186.5

            AND UB."AutoSelect" = 1     -- E00543 - option to preload patients

            AND A."Patient" = P."Patient"  -- Patient's family is from PATIENT, 

                                        -- and is the same patient as in APPOINT

            AND A."Date" = ROUND(SYSDATE) -- Date of appointment is tomorrow if 

                                          -- run in PM, today if run in AM

            AND B."Book" = BD."Book"      -- B32222 look for the right BOOKDET 

            AND ( A."Date" BETWEEN NVL(BD."StartDate",A."Date") 

			AND NVL(BD."EndDate", A."Date") ) -- B67346

            AND DECODE(TO_CHAR(A."Date",'D'),1,7,2,1,3,2,4,3,5,4,6,5,7,6)

		    IN (BD."Opened0"*1, BD."Opened1"*2, BD."Opened2"*3, BD."Opened3"*4, 

            BD."Opened4"*5, BD."Opened5"*6, BD."Opened6"*7)  

            AND BD."BookDetail" = BC."BookDetail" --B32222 with the right chairs

            AND A."Chair" = BC."Chair"                

            AND A."Chair" !=0  -- Appointment chair is set to a valid value

            AND A."Type" <= 2  -- Appointment type is one of the active types

            AND A."Status" = 0 -- Appointment is not deleted 

            AND P."Deleted" = 0 -- Patient is not deleted

            AND U."Deleted" = 0 -- User is not deleted

            AND NOT EXISTS (SELECT * FROM SELECTED S WHERE S."User" = U."User" 

            AND S."Patient" = P."Patient") -- row does not exist in SELECTED

            ) WHERE ROWNUM <= 1000

        ;

	-- B53866 added        

    CURSOR selected_cursor2 IS 

        SELECT * from (	  

            SELECT DISTINCT U."User", P."Patient"

            FROM  USERS U, PATIENT P, APPOINT A, BOOK B, UBOOK UB,

            BOOKDET BD, BOOKPROV BP    -- joined in new tables  

            WHERE U."User" = UB."User"  -- User is from UBOOK table

            AND B."Book" = UB."Book"    -- Book is from UBOOK table

            AND B."ReservesByProvider" = 1 

			AND B."Inactive" = 0				-- AX-25186.5

            AND UB."AutoSelect" = 1     -- E00543 - option to preload patients

            AND A."Patient" = P."Patient"  -- Patient's family is from PATIENT, 

                                        -- and is the same patient as in APPOINT

            AND A."Date" = ROUND(SYSDATE) -- Date of appointment is tomorrow if 

                                          -- run in PM, today if run in AM

            AND B."Book" = BD."Book"      -- B32222 look for the right BOOKDET 

            AND ( A."Date" BETWEEN NVL(BD."StartDate",A."Date") 

			AND NVL(BD."EndDate", A."Date") ) -- B67346

            AND DECODE(TO_CHAR(A."Date",'D'),1,7,2,1,3,2,4,3,5,4,6,5,7,6)

		    IN (BD."Opened0"*1, BD."Opened1"*2, BD."Opened2"*3, BD."Opened3"*4, 

            BD."Opened4"*5, BD."Opened5"*6, BD."Opened6"*7)  

            AND BD."BookDetail" = BP."BookDetail" --B32222 with the right chairs

            AND (A."Producer" = BP."Provider"                

            	OR A."Assistant" = BP."Provider")               

            AND A."Chair" !=0  -- Appointment chair is set to a valid value

            AND A."Type" <= 2  -- Appointment type is one of the active types

            AND A."Status" = 0 -- Appointment is not deleted 

            AND P."Deleted" = 0 -- Patient is not deleted

            AND U."Deleted" = 0 -- User is not deleted

            AND NOT EXISTS (SELECT * FROM SELECTED S WHERE S."User" = U."User" 

            AND S."Patient" = P."Patient") -- row does not exist in SELECTED

            ) WHERE ROWNUM <= 1000

        ;

        

BEGIN

    LOOP

  

        OPEN selected_cursor;



        FETCH selected_cursor

        BULK COLLECT INTO v_User, v_Patient;

    

        IF v_User.COUNT = 0 THEN

            CLOSE selected_cursor;

            EXIT;

        END IF;



        FORALL i IN v_User.FIRST..v_User.LAST

            INSERT INTO SELECTED

                ("User", "Patient", "Held")	-- E27288 - changed checkin to held

                VALUES

                (v_User(i), v_Patient(i), 0);



        CLOSE selected_cursor;

        COMMIT;



        IF v_User.LAST < 1000 THEN 

            EXIT;

        END IF;

    

    END LOOP;

	-- B53866 added to handle book by providers        

    LOOP

  

        OPEN selected_cursor2;



        FETCH selected_cursor2

        BULK COLLECT INTO v_User, v_Patient;

    

        IF v_User.COUNT = 0 THEN

            CLOSE selected_cursor2;

            EXIT;

        END IF;



        FORALL i IN v_User.FIRST..v_User.LAST

            INSERT INTO SELECTED

                ("User", "Patient", "Held")	-- E27288 - changed checkin to held

                VALUES

                (v_User(i), v_Patient(i), 0);



        CLOSE selected_cursor2;

        COMMIT;



        IF v_User.LAST < 1000 THEN 

            EXIT;

        END IF;

    

    END LOOP;

END;





PROCEDURE reset_policy_yearend() IS 

    today      DATE;

    needsReset NUMBER;

BEGIN

    SELECT TRUNC(ROUND(SysDate)) INTO today FROM dual;



    -- reset for year end

    update ptdepend PD set PD."LimitBalance"=PD."PatientLimit", 

            PD."DeductBalance"=PD."PatientDeduct",

            PD."VisitBalance"=(select I."VisitsPerYear" FROM 

            insuranc I, policy P where P."PolicyId"=PD."PolicyId" and 

            P."Company"=I."Company") where PD."Deleted" = 0 AND PD."PolicyId" 

            in (select P."PolicyId" from policy P where 

            add_months(P."YEResetDate", 12) <= today and P."Deleted"=0);



    update policy set "LimitBalance"="FamilyLimit", 

            "DeductBalance"="FamilyDeduct", 

            "YEResetDate"= add_months("YEResetDate", 12)

            where add_months("YEResetDate", 12) <= today and "Deleted"=0;

    commit;

END;



PROCEDURE reset_policy_monthend() IS 

    today      DATE;

    needsReset NUMBER;

BEGIN

    SELECT TRUNC(ROUND(SysDate)) INTO today FROM dual;



    -- handle monthly deductible

    update ptdepend PD set PD."DeductBalance"=PD."PatientDeduct"  

            where PD."Deleted" = 0 AND PD."PolicyId" in 

            (select P."PolicyId" from policy P where P."MonthlyDeduct"= 1 

            and P."Deleted"=0 and add_months(P."MEResetDate", 1) <= today);



    select count(*) into needsReset from policy where "MonthlyDeduct"= 1 

            and "Deleted"=0 and add_months("MEResetDate", 1) <= today;



    while needsReset > 0 loop

        update policy set "MEResetDate"= add_months("MEResetDate", 1)

                where "MonthlyDeduct"= 1 and "Deleted"=0 and 

                add_months("MEResetDate", 1) <= today;

    

        select count(*) into needsReset from policy 

                where "MonthlyDeduct"= 1 and "Deleted"=0 and 

                add_months("MEResetDate", 1) <= today;

    end loop;

    commit;

END;





-- E00723.7

-- Reset deplimit's resetdate, deductbalance, limitbalance for category deplimits

--  E24419.3 - added code to handle new default coverage templates

-- B35440 added new CoverageId

PROCEDURE reset_policy_deplimitcat() IS 

    today       DATE;

    iMonths NUMBER;

    my_PolicyId NUMBER(10);

    my_Patient  NUMBER(10);

    my_Category  CHAR(6);

    my_ResetDate  DATE;

    my_CatPeriod  NUMBER(10);

    my_CatFreq  NUMBER(5);

    my_CoverageId NUMBER(10);



    CURSOR c1 IS (SELECT D."PolicyId", D."Patient", D."Category", D."ResetDate", 

            P."CatPeriod", P."CatFrequency", D."CoverageId"

            FROM DEPLIMIT D, POLRANGE P, PTPOL PT WHERE D."PolicyId" = PT."PolicyId"

            AND PT."PolIns" = P."PolIns"		-- E56421.1

            AND D."CoverageId"=0 AND D."Id" = 0 AND D."Category" = P."Category" 

            AND P."HasCategory" = 1 AND P."CatPeriod" <> 0 AND 

            (P."CatFrequency" = 1 OR P."CatFrequency" = 2))

        UNION                                -- E24419.3 added

            (SELECT D."PolicyId", D."Patient", D."Category", D."ResetDate", 

            CI."CatPeriod", CI."CatFrequency", D."CoverageId"

            FROM DEPLIMIT D, COVERIT CI WHERE D."CoverageId" = CI."Coverage"

            AND D."CoverageId"<>0 AND D."Id" = 0 AND 

            D."Category" = CI."Category" AND CI."HasCategory" = 1 AND 

            CI."CatPeriod" <> 0 AND (CI."CatFrequency" = 1 

            OR CI."CatFrequency" = 2));



    -- E143071.4 - family maximums

    CURSOR cFam IS SELECT D."PolicyId", D."Category", D."ResetDate", 

            CI."CatPeriod", CI."CatFrequency", D."CoverageId"

            FROM FAMLIMIT D, COVERIT CI WHERE D."CoverageId" = CI."Coverage"

            AND D."CoverageId"<>0 AND CI."HasCatFamilyLimit" = 1 AND

            D."Category" = CI."Category" AND CI."HasCategory" = 1 AND 

            CI."CatPeriod" <> 0 AND (CI."CatFrequency" = 1 

            OR CI."CatFrequency" = 2);



BEGIN

    SELECT TRUNC(ROUND(SysDate)) INTO today FROM dual;



    OPEN c1;

    LOOP



       FETCH c1 INTO my_PolicyId, my_Patient, my_Category, my_ResetDate, 

						my_CatPeriod, my_CatFreq, my_CoverageId;

       EXIT WHEN c1%NOTFOUND;

    

       IF my_CatFreq = 1 THEN

           iMonths := my_CatPeriod;

       ELSE

           iMonths := my_CatPeriod * 12;

       END IF;



       IF (add_months(my_ResetDate, iMonths) <= today) THEN

           UPDATE DEPLIMIT SET "ResetDate" = 

                   add_months(my_ResetDate, iMonths), 

                   "DeductBalance" = "Deduct", "LimitBalance" = "Limit" 

                   WHERE "PolicyId" = my_PolicyId AND 

                   "Patient" = my_Patient AND "Id" = 0 AND 

                   "Category" = my_Category AND 

                        "CoverageId" = my_CoverageId;

       END IF;

   END LOOP;   

   CLOSE c1;

   COMMIT;



    -- E143071.4 - family maximums

    OPEN cFAm;

    LOOP



       FETCH cFAm INTO my_PolicyId, my_Category, my_ResetDate, my_CatPeriod, my_CatFreq, my_CoverageId;

       EXIT WHEN cFAm%NOTFOUND;

    

       IF my_CatFreq = 1 THEN

           iMonths := my_CatPeriod;

       ELSE

           iMonths := my_CatPeriod * 12;

       END IF;



       IF (add_months(my_ResetDate, iMonths) <= today) THEN

           UPDATE FAMLIMIT SET "ResetDate" = 

                   add_months(my_ResetDate, iMonths), 

                   "LimitBalance" = "Limit" 

                   WHERE "PolicyId" = my_PolicyId AND 

                   "Category" = my_Category AND 

                   "CoverageId" = my_CoverageId;

       END IF;

   END LOOP;   

   CLOSE cFAm;

   COMMIT;

END;



-- E00723.7

-- Reset deplimit's resetdate, limitbalance for item deplimits

--  E24419.3 - added code to handle new default coverage templates

-- B35440 added new CoverageId

PROCEDURE reset_policy_deplimititem() IS 

    today       DATE;

    iMonths NUMBER;

    my_PolicyId NUMBER(10);

    my_Patient  NUMBER(10);

    my_Id   NUMBER(10);

    my_ResetDate  DATE;

    my_ItemPeriod  NUMBER(10);

    my_ItemFreq NUMBER(5);

    my_CoverageId NUMBER(10);



    CURSOR c1 IS (SELECT D."PolicyId", D."Patient", D."Id", D."ResetDate", 

            P."ItemPeriod", P."ItemFrequency", D."CoverageId"

            FROM DEPLIMIT D, POLRANGE P, PTPOL PT WHERE D."PolicyId" = PT."PolicyId"

            AND PT."PolIns" = P."PolIns"			-- E56421.1

            AND D."CoverageId"=0                 -- E24419.3

            AND D."Id" = P."Id" AND (P."HasItemLimit" = 1 

            OR P."ItemDeduct" > 0)    -- B33438

            AND P."ItemPeriod" <> 0 AND (P."ItemFrequency" = 1 

            OR P."ItemFrequency" = 2))

        UNION                      -- E24419.3 added    

            (SELECT D."PolicyId", D."Patient", D."Id", D."ResetDate", 

            CI."ItemPeriod", CI."ItemFrequency", D."CoverageId"

            FROM DEPLIMIT D, COVERIT CI WHERE D."CoverageId" = CI."Coverage"

            AND D."CoverageId"<>0 AND D."Id" = CI."Item" AND 

            (CI."HasItemLimit" = 1 OR CI."ItemDeduct" > 0) -- E24419.8 B33438

            AND CI."ItemPeriod" <> 0 AND (CI."ItemFrequency" = 1 

            OR CI."ItemFrequency" = 2));

BEGIN

    SELECT TRUNC(ROUND(SysDate)) INTO today FROM dual;



    OPEN c1;

    LOOP



        FETCH c1 INTO my_PolicyId, my_Patient, my_Id, my_ResetDate, my_ItemPeriod, 

						my_ItemFreq, my_CoverageId;

        EXIT WHEN c1%NOTFOUND;

    

        IF my_ItemFreq = 1 THEN

            iMonths := my_ItemPeriod;

        ELSE

            iMonths := my_ItemPeriod * 12;

        END IF;

        

        IF (add_months(my_ResetDate, iMonths) <= today) THEN

            UPDATE DEPLIMIT SET 

                "ResetDate" = add_months(my_ResetDate, iMonths), 

                "DeductBalance" = "Deduct",                       -- B33438

                "LimitBalance" = "Limit" WHERE

                "PolicyId" = my_PolicyId AND "Patient" = my_Patient AND 

                "Id" = my_Id AND "CoverageId" = my_CoverageId;

        END IF;



    END LOOP;   

    CLOSE c1;

    COMMIT;

END;





PROCEDURE reverse_freeaccess_pts() IS

    Counter NUMBER(10);

    AuditId NUMBER(10);

BEGIN

    --Remove from students selected list

    delete selected s where exists (select 'x' from patient p, users u, 

            slevel l where p."Patient"=s."Patient" and u."User"=s."User" 

            and l."SLevel"=u."Level" and l."IsPtRestrict"=1

            and p."IsFreeAccess"=1);



    --Reverse PATIENT."IsFreeAccess" flag

    select count(1) into Counter from patient where "IsFreeAccess"=1;

    if Counter > 0 then

	   AuditId := OVERNIGHT_STD_PKG.Create_Audit('PATIENT',2,0);

	   update patient p set p."IsFreeAccess"=0, "Audit"=AuditId 

                where p."IsFreeAccess"=1;

	   commit;

    end if;

END;







-- E26975.8, E72760

-- Update appts to "failed" if the patient didn't show up

-- Note that this procedure should only be for clients that do patient checkins

-- Currently this is only added to TUFTSovernight_pkg.sql

--

PROCEDURE update_failed_appts(IN num_stationid numeric) IS 

    today          DATE;

    num_hour       NUMBER;

    num_minute     NUMBER;

    num_user       NUMBER;

    row_Trx  TRX%ROWTYPE;

    

  GMTTotalOffset	NUMBER (10);                                                  --B79846 start

  GMTHourOffset	NUMBER (10);

  GMTMinuteOffset NUMBER (10);                                                  --B79846 end

    

    CURSOR cur(today DATE, num_hour NUMBER, num_minute NUMBER, num_user NUMBER )



    IS

    select * from appoint A where 

      A."Type"=0 and A."CheckInTime"=0 and A."Date"<today;



BEGIN





  SELECT EXTRACT(timezone_hour FROM SYSTIMESTAMP) INTO GMTHourOffset;

  SELECT EXTRACT(timezone_minute FROM SYSTIMESTAMP) INTO GMTMinuteOffset;

  GMTTotalOffset := 0 - (GMTHourOffset*60*60);

  

  IF (GMTHourOffset < 0) THEN

	 GMTTotalOffset := GMTTotalOffset + (GMTMinuteOffset*60);

  ELSE

    GMTTotalOffset := GMTTotalOffset - (GMTMinuteOffset*60);

  END IF;                                                                       --B79846 end





    SELECT TRUNC(ROUND(SysDate)) INTO today FROM dual;

    SELECT TO_NUMBER(TO_CHAR(SysDate, 'HH24')),  

              TO_NUMBER(TO_CHAR(SysDate, 'MI')) INTO num_hour, num_minute FROM dual;

   SELECT "OvernightUser" INTO num_user FROM axiumopt;

   

     for rec in cur(today, num_hour, num_minute, num_user)



     LOOP  

            

       update appoint A set A."Type"=5, A."User"=num_user,

        A."ModifiedDateTime"=SYSDATE 				--B79846, E125010

          where  rec."Appointment" = A."Appointment";

          

        TRX_PKG.InitializeTrx(row_Trx);



        row_Trx."StationId" := num_StationId;

        row_Trx."TreatmentDate" := rec."Date";

        row_Trx."Patient" := rec."Patient"; 

        row_Trx."Family" := rec."Patient";

        row_Trx."EntryUser" := num_user;

        row_Trx."User" := num_user;

        

        TRX_PKG.AddNonTaxableOfficeCharge(row_Trx,rec."Clinic", rec."Producer", 1);

          

    END LOOP;



END;







-- E46841

-- Update appts to "checked out" if the patient didn't check out

--

PROCEDURE checkout_appts() IS 

    today      DATE;

    hour       NUMBER;

    minute     NUMBER;

    user       NUMBER;



	GMTTotalOffset	NUMBER (10);

	GMTHourOffset	NUMBER (10);

	GMTMinuteOffset NUMBER (10);

  

BEGIN

	 -- B104505 - fix time calculation to include time zone

    SELECT EXTRACT(timezone_hour FROM SYSTIMESTAMP) INTO GMTHourOffset;

    SELECT EXTRACT(timezone_minute FROM SYSTIMESTAMP) INTO GMTMinuteOffset;

    GMTTotalOffset := 0 - (GMTHourOffset*60*60);



    IF (GMTHourOffset < 0) THEN

       GMTTotalOffset := GMTTotalOffset + (GMTMinuteOffset*60);

    ELSE

       GMTTotalOffset := GMTTotalOffset - (GMTMinuteOffset*60);

    END IF;





    SELECT TRUNC(ROUND(SysDate)) INTO today FROM dual;

    SELECT TO_NUMBER(TO_CHAR(SysDate, 'HH24')),  

                TO_NUMBER(TO_CHAR(SysDate, 'MI')) INTO hour, minute FROM dual;

    SELECT "OvernightUser" INTO user FROM axiumopt;

  

    update appoint A set A."Type"=2, A."User"=user,

            A."ModifiedDateTime"= SYSDATE,			-- E125010

            A."CheckOutDate" = trunc(sysdate),			-- E68549

            A."CheckOutTime" = TO_NUMBER(TO_CHAR(SysDate, 'HH24'))*60+TO_NUMBER(TO_CHAR(SysDate, 'MI'))		-- E68549

            where A."Type"=1 and A."Date"<today;

    commit;

END;







-- E42674, B57417 changed to not stamp step txs

-- Procedure to stamp expired plan txs with different status based on the 

--          Practice options setup

-- INPUT: 	pStation - Station Id that will be used for the station field

PROCEDURE update_plantx_status(IN pstation numeric) IS



    pUser		number(10);

    CURSOR C1 IS SELECT *

        from practice p

        where p."UpdateTxStatus"=1 

        ORDER by "Id";

    SQLStmt  VARCHAR2(4000);

    txType	NUMBER(10);

    txId		NUMBER(10);

    txTreatment	NUMBER(10);

	 txChartTrx		NUMBER(10);		-- AX-17355.18326

 

 BEGIN

 

    select "OvernightUser" into pUser from Axiumopt;

    <<outer_loop>>

    for c in C1 LOOP



		-- AX-17355.18326; AX-23412

        SQLStmt := 'select t."Type",t."Id",t."Treatment", t."ChartTrx" from trx t, procedur p 

            where t."Type" = 5 and t."Deleted"=0 and t."Practice" = :1

            and (t."TxStatus" != :2 OR t."TxStatus" IS NULL)

			and t."CreationDate" <= (CURRENT_DATE - :3)

			and t."Procedure" = p."Procedure" and p."IsStepChild" = 0

			and not exists (select 1 from chartlnk c where c."Previous" = t."ChartTrx" OR c."Auto" = t."ChartTrx")

            order by t."Date", t."Type", t."Id", t."Treatment" ';



	

	FOR txType, txId, txTreatment, txChartTrx IN

	    EXECUTE SQLStmt USING c."Id", c."TxStatusCode", c."TxStatusDays"

      

        LOOP

    	    EXECUTE IMMEDIATE 'UPDATE TRX SET "TxStatus"=:1, 

                    "ModifiedDate"=sysdate, 

                    "User"=:2, "StationId"=:3 where "Type"=:4 

	                and "Id"=:5 and "Treatment"=:6' 

	                USING c."TxStatusCode",pUser,pStation, 

                    txType, txId, txTreatment;



	        EXECUTE IMMEDIATE 'insert into HISTORY (select 

                    HISTORY_HISTORY_SEQ.nextval, 2, Trx.* from trx 

                    where "Type"=:1 and "Id"=:2 and "Treatment"=:3)'

		            using txType, txId, txTreatment;



		UPDATE_PLANTX_STEPS(pStation, pUser, txChartTrx, c."TxStatusCode"); -- AX-17355.18326



        END LOOP;



    END LOOP;

    commit;

END;





-- AX-17355.18326

PROCEDURE update_plantx_steps(IN pstation numeric, IN puser numeric, IN pcharttrx numeric, IN pstatus character varying) IS



    SQLStmt  VARCHAR2(4000);

    txType	NUMBER(10);

    txId		NUMBER(10);

    txTreatment	NUMBER(10);

	 txChartTrx		NUMBER(10);	

 

 BEGIN

 

	SQLStmt := 'SELECT T."Type", T."Id", T."Treatment" FROM TRX T, TREATME2 T2 WHERE T."ChartTrx" = T2."Auto" AND T2."ParentId" = :1';

	

	

	FOR txType, txId, txTreatment IN

	    EXECUTE SQLStmt USING pChartTrx

      

	LOOP

  

		EXECUTE IMMEDIATE 'UPDATE TRX SET "TxStatus"=:1, "ModifiedDate"=sysdate, "User"=:2, "StationId"=:3 

			where "Type"=:4 and "Id"=:5 and "Treatment"=:6' 

		USING pStatus, pUser, pStation, txType, txId, txTreatment;



		EXECUTE IMMEDIATE 'insert into HISTORY (select HISTORY_HISTORY_SEQ.nextval, 2, Trx.* from trx 

			where "Type"=:1 and "Id"=:2 and "Treatment"=:3)'

		USING txType, txId, txTreatment;



	END LOOP;



END;





-- E33069 (Apr 05, 07) drb

-- Procedure to truncate the custom events table

PROCEDURE clear_custom_events() IS



BEGIN

	EXECUTE IMMEDIATE 'TRUNCATE TABLE CUSTEVNT';

	COMMIT;

END;







-- E52612 May 08, 07	dre																			

-- Procedure to clear Patient.EmancedMinor if greater than or equal to AxiumOpt.NoGuarAge

PROCEDURE clear_emancedminor() IS



BEGIN

	UPDATE PATIENT SET "EmancedMinor" = 0 WHERE "EmancedMinor" = 1 

	  AND 0 <> (SELECT "NoGuarWarn" FROM AXIUMOPT)

	  AND MONTHS_BETWEEN(sysdate, "Birth")/12 >= (SELECT "NoGuarAge" FROM AXIUMOPT);

	COMMIT;

END;





-- B75126 May 01, 09	drb																			

-- Procedure to remove duplicate fitem history

PROCEDURE cleanup_fitem_history() IS



	cursor fitemgroups is

	select max("FItem") "FItem", count(1), "OrgFItem", "DeletionDate", "DeletionTime", "Date"

		from fitem where "Deleted" > 0 and "OrgFItem" > 0

		group by "OrgFItem", "DeletionDate", "DeletionTime", "Date"

		having count(1)>1;

	

BEGIN



	for fitemrec in fitemgroups

	loop

		

		delete from fitem where "FItem" <> fitemrec."FItem"

			and "OrgFItem" = fitemrec."OrgFItem"

			and "DeletionDate" = fitemrec."DeletionDate"

			and "DeletionTime" = fitemrec."DeletionTime"

			and "Date" = fitemrec."Date"

			and "Deleted" > 0 and "OrgFItem" > 0;

		

	end loop;



	COMMIT;

END;





-- E73078.7.6	 Jul 06, 09		rmt																			

-- Procedure to remove expired wait list appointments

PROCEDURE delete_expired_waitlist_appts() IS

	overnightuser NUMBER(10);

	AuditId NUMBER(10);

	cursor waitlistitems is

		select W.* from waitlist W, waitrsn WR, appoint A where W."Status" = 0 AND 

		W."WaitRsn" = WR."WaitRsn" AND W."Appointment" = A."Appointment" AND A."Status" = 0

		AND A."Type" = 0 AND TRUNC(ROUND(SysDate)) >= A."Date" - WR."ExpiryDays";

		

	

BEGIN

	SELECT "OvernightUser" INTO overnightuser FROM axiumopt;

	AuditId := OVERNIGHT_STD_PKG.Create_Audit('WAITLIST',2,1);

	for waitlistitem in waitlistitems

	loop

	

		-- AX-640 set Status = 2, Expired.

		UPDATE WAITLIST SET "Status" = 2, "Audit" = AuditId 

						WHERE "WaitList" = waitlistitem."WaitList";

				

		INSERT INTO REQNOTE VALUES (

			REQNOTE_REQNOTE_SEQ.nextval, 

			waitlistitem."Appointment",

			trunc(sysdate),

			TO_NUMBER(TO_CHAR(SysDate, 'HH24'))*60+TO_NUMBER(TO_CHAR(SysDate, 'MI')),

			overnightuser ,

			1, 

			0,

			NULL, -- AX-40610

			'Appointment removed from the wait list (expired)'

		);

		

	end loop;

	COMMIT;	



END;



-- E127712; AX-19092

PROCEDURE clear_chairst() IS



Counter NUMBER(10);

AuditId NUMBER(10);



BEGIN



	select count(1) into Counter from CHAIRST WHERE "ClinicTime" != 0 and NOT (TRIM("CNState") IS NULL OR length(TRIM("CNState")) = 0);

    	if Counter > 0 then  

		AuditId := OVERNIGHT_STD_PKG.Create_Audit('CHAIRST',2,0);

  		UPDATE CHAIRST SET "Audit" = AuditId, "CNState" = ' ' WHERE "ClinicTime" != 0 and NOT (TRIM("CNState") IS NULL OR length(TRIM("CNState")) = 0);

	end if;

  



END;



-- E127712

PROCEDURE delete_chairst() IS



BEGIN



  DELETE CHAIRST WHERE "ClinicTime" IN (SELECT "ClinicTime" FROM CLINICT WHERE "EndDate" < Trunc(sysdate));

  

END;



--AX-2854 

PROCEDURE delete_dept_txs_all() IS

BEGIN

    DELETE FROM DEPTTX;

END;



-- AX-11528.11629

PROCEDURE clear_processing_messages() IS

BEGIN

    UPDATE MESSAGE SET "EMailStatus" = 4 WHERE "EMailStatus" = 2;

END;



-- AX-19615.5c added to clear all LABTTRX records every night

PROCEDURE delete_labtmptrx() IS

BEGIN

    DELETE FROM LABTTRX;

END;





-- AX-19762.20350 - set eLab status when future dates become current dates

PROCEDURE set_elab_status() IS



BEGIN

	-- ready -> out, in -> out

	-- set eLabs to be "out" when dateout = today (add 6 hours to in case this is being run in the evening), and dateIn either not set or future dated and lab order is in progress

	UPDATE LABORDER LO

		SET LO."LabOut" = 1, LO."Status" = 1

		WHERE LO."IseLab" = 1 AND LO."Status" <= 1

		AND LO."LabOrder" IN (select LI."LabOrder" from LABITEM LI

			where LI."Item" = LO."CurrentItem"

			AND LI."DateOut" = trunc(sysdate+(6/24)) 

			AND (LI."DateIn" is null or LI."DateIn" > LI."DateOut"));



	-- AX-20487 - fix broken auto-message triggers

	INSERT INTO CUSTEVNT 

		(SELECT 3, 'Lab order is out', 'LABITEM', '"LabOrder"="Key1", "Item"="Key2"', LI."LabOrder", LI."Item", CUSTEVNT_CUSTEVNT_SEQ.NEXTVAL

		FROM LABITEM LI

		WHERE LI."LabOrder" || '.' || LI."Item" IN (select LO."LabOrder" || '.' || LO."CurrentItem" 

			from laborder LO

			where LO."IseLab" = 1 AND LO."Status" <= 1)

		AND LI."DateOut" = trunc(sysdate+(6/24)) 

		AND (LI."DateIn" is null or LI."DateIn" > LI."DateOut")

		AND LI."LabOut" <> 1);



	UPDATE LABITEM LI

		SET LI."LabOut" = 1

		WHERE LI."LabOrder" || '.' || LI."Item" IN (select LO."LabOrder" || '.' || LO."CurrentItem" 

			from laborder LO

			where LO."IseLab" = 1 AND LO."Status" <= 1)

		AND LI."DateOut" = trunc(sysdate+(6/24)) 

		AND (LI."DateIn" is null or LI."DateIn" > LI."DateOut")

		AND LI."LabOut" <> 1;

	

	-- out -> in 

	-- set eLabs to be "in" with date in = today (add 6 hours to in case this is being run in the evening) and dateout before datein and lab order is in progress

	UPDATE LABORDER LO

		SET LO."LabOut" = 0, LO."Status" = 1

		WHERE LO."IseLab" = 1 AND LO."Status" <= 1

		AND LO."LabOrder" IN (select LI."LabOrder" from LABITEM LI

			where LI."Item" = LO."CurrentItem" 

			AND LI."DateIn" = trunc(sysdate+(6/24)) 

			AND LI."DateOut" <= LI."DateIn");



	-- AX-20487 - fix broken auto-message triggers

	INSERT INTO CUSTEVNT 

		(SELECT 2, 'Lab order is out', 'LABITEM', '"LabOrder"="Key1", "Item"="Key2"', LI."LabOrder", LI."Item", CUSTEVNT_CUSTEVNT_SEQ.NEXTVAL

		FROM LABITEM LI

		WHERE LI."LabOrder" || '.' || LI."Item" IN (select LO."LabOrder" || '.' || LO."CurrentItem" 

			from laborder LO

			where LO."IseLab" = 1 AND LO."Status" <= 1)

		AND LI."DateIn" = trunc(sysdate+(6/24)) 

		AND LI."DateOut" <= LI."DateIn"

		AND LI."LabOut" <> 0);



	UPDATE LABITEM LI

		SET LI."LabOut" = 0

		WHERE LI."LabOrder" || '.' || LI."Item" IN (select LO."LabOrder" || '.' || LO."CurrentItem" 

			from laborder LO

			where LO."IseLab" = 1 AND LO."Status" <= 1)

		AND LI."DateIn" = trunc(sysdate+(6/24)) 

		AND LI."DateOut" <= LI."DateIn"

		AND LI."LabOut" <> 0;







END;



-- AX-22704 to cleanup CAPREQ and CAPREQIT records

PROCEDURE cleanup_caprequests() IS

	AuditId NUMBER(10);



BEGIN

	AuditId := OVERNIGHT_STD_PKG.Create_Audit('CAPREQ',2,1);



	-- set status to obsolete for any outstanding request items

	UPDATE CAPREQIT IT

		SET IT."Status" = 4, IT."UpdateAudit" = AuditId

		WHERE IT."Status" = 0;



	-- set state to closed for any outstanding requests

	UPDATE CAPREQ R

		SET R."State" = 2, R."UpdateAudit" = AuditId

		WHERE R."State" = 0;



	COMMIT;	



END;





END;
CREATE OR REPLACE PACKAGE BODY pa2_pkg IS
    PROCEDURE gettemplatedata(OUT out_html clob, OUT out_css clob, OUT out_js clob) IS
        vPrimaryColor VARCHAR2(50 );
        vTextColor VARCHAR2(50 );
        vFavicon VARCHAR2(50 );
        vOrganizationLogo VARCHAR2(50 );
        vOrganizationName VARCHAR2(100 );
    BEGIN

        SELECT REPLACE("Value", '~', '..')
        INTO vOrganizationLogo
        FROM ISETTING_PA2
        WHERE "Key" = 'SiteSetting.OrganizationLogo';

        SELECT "Value"
        INTO vPrimaryColor
        FROM ISETTING_PA2
        WHERE "Key" = 'SiteSetting.PrimaryColor';

        SELECT "Value"
        INTO vTextColor
        FROM ISETTING_PA2
        WHERE "Key" = 'SiteSetting.TextColor';

        SELECT REPLACE("Value", '~', '..')
        INTO vFavicon
        FROM ISETTING_PA2
        WHERE "Key" = 'SiteSetting.Favicon';

        SELECT "Value"
        INTO vOrganizationName
        FROM ISETTING_PA2
        WHERE "Key" = 'SiteSetting.OrganizationName';

        OUT_HTML := '
<!DOCTYPE html>
<html lang=en>
<head>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css" rel=stylesheet integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9" crossorigin=anonymous>
    <!-- Favicon Replacement Area -->

    <link href="./Includes/Css/spinner.css" rel=stylesheet type="text/css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
	<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-HwwvtgBNo3bZJJLYd8oVXjrBZt8cqVSpeBNS5n7C8IVInixGAoxmnlMuBnhbgrkm" crossorigin=anonymous></script>
	<script src="https://kit.fontawesome.com/95fbe47167.js" crossorigin=anonymous></script>
    <script src="./Includes/Scripts/spin.min.js"></script>
    <script src="./Includes/Scripts/general.240530.js"></script>
    <script src="./Includes/Scripts/iframe.231520.js"></script>

    <meta name=viewport content="width=device-width, initial-scale=1.0">

    <link rel=stylesheet href="./Includes/Css/PA2.0/common.css">
    <style>
        /*Default CSS Replacement Area*/
        .dashboard-nav {
            position: fixed; left: 0; top: 0; bottom: 0; overflow: auto;
        }
    </style>
    <title> <!-- Title Replacement Area --> - ' || vOrganizationName || '</title>

    <script src="./Includes/Scripts/PA2.0/common.js"></script>
    <script>
        // Default JS Replacement Area
    </script>

</head>
<body class="overflow-hidden">


    <form id="logoutForm" method=post class="d-none">
        <input type=hidden name="action" value=logout>
        <input type=submit name="submitInput" value="1" style="display: none">
    </form>

    <aside class="dashboard-nav">

        <header>
            <a id="menu-toggle-1" class="menu-toggle">
                <i class="fas fa-bars"></i>
                <i class="fas fa-close"></i>
            </a>
            <div class="university-logo-img-container">
                <a href="#" onclick="handleLogoClick();"> <img class="university-logo-img" src="/PatientAccess/PAAdmin/Handler/ImageHandler.ashx?ImgId=' || vOrganizationLogo || '" alt="Organization Logo"> </a>
            </div>
        </header>


        <nav class="dashboard-nav-list" style="flex-grow: 1;">

            <div class="dashboard-nav-list-items">

                <!-- Sidebar Section Items Replacement Area -->

                <hr id="sidebarDivider" class="text-gray">

                <!-- Sidebar Section Items After Divider Replacement Area -->

                <a href="#" title="Sign out" id="signOutLink" onclick="handleLogoutClick();" class="dashboard-nav-item">
                    <i class="fa-solid fa-arrow-right-from-bracket"></i> Sign out
                </a>
            </div>


        </nav>
		
		<!-- Username card Replacement Area -->

    </aside>
    <main class="dashboard-app">
        <!-- For mobile, display flex but for desktop dont make any changes -->
        <header class="dashboard-toolbar d-flex d-lg-none flex-row gap-3">
            <a id="menu-toggle-2" class="menu-toggle">
                <i class="fas fa-bars"></i>
                <i class="fas fa-close"></i>
            </a>
            <a href="#" onclick="handleLogoClick();"> <img class="university-logo-img" src="/PatientAccess/PAAdmin/Handler/ImageHandler.ashx?ImgId=' || vOrganizationLogo || '" alt="Organization Logo"> </a>
        </header>
        <div class="dashboard-content">
            <div class="align-items-center d-flex flex-column flex-md-row justify-content-md-between page-header" role=region>
                <div id=pagetitle role=heading aria-level="1" class="w-100-mobile"><!--Page Title Replacement String--></div>
                <div id="AuthorRepresentDiv" class="d-none w-100-mobile">
                    <div class="d-flex">
                        <label for="AuthorRepresentDrp" id="AuthorRepresentDrpLbl" class="col-form-label form-label">View</label>
                        <select name="AuthorRepresentDrp" id="AuthorRepresentDrp" onchange="processDropdownChanged(this)" class="form-control form-select">
                        </select>
                    </div>
                </div>
            </div>

            <div class="iframe-container" role=main>
                <!--Main Content Replacement Area-->
            </div>
        </div>
    </main>

    <div id="autoLogoutModal" class=modal tabindex="-1" role=dialog>
        <div class="modal-dialog inactivity-warning-modal" role=document>
            <div class="modal-content">
                <div class="modal-header">
                    <div id="modalTitle" class="modal-title"></div>
                </div>
                <div class="modal-body">
                    <p id="modalBody"></p>
                </div>
                <div class="modal-footer">
                    <button data-purpose="OkBtn" type=button class="btn btn-primary">Ok</button>
                    <button data-purpose="CancelBtn" type=button class="btn btn-pa-secondary" data-bs-dismiss=modal>Cancel</button>
                </div>
            </div>
        </div>
    </div>

    <span id="vOrganizationName" style="display: none;">' || vOrganizationName || '</span>

    <script src="Includes/Scripts/jquery.idletimer.js"></script>
    <script src="Includes/Scripts/PA2.0/GeneralModal.js"></script>
    <script src="Includes/Scripts/PA2.0/autologout.js"></script>


</body>
</html>
        ';

        OUT_CSS := '
        :root {
            --pa2-primary-color: ' || vPrimaryColor || ';
            --pa2-text-color: ' || vTextColor || ';
            --main-section-margin: 40px;
            --main-section-margin-mobile: 16px;
            --font-family: "Helvetica Neue", Arial, sans-serif;
        }

        *, *::before, *::after {
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
        }

        iframe {
            border: 0;
        }

        html {
            font-family: var(--font-family) !important;
            line-height: 1.15;
            -webkit-text-size-adjust: 100%;
            -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
            min-height: 100%;
            display: flex;
            flex-direction: column;
        }

        nav {
            display: block;
        }


        body {
            background-color: #F2F5FA;
            flex-grow: 1;
        }

        a {
            color: #3f84fc;
            text-decoration: none;
            background-color: transparent;
        }

        .dashboard-app {
            display: flex;
            flex-grow: 2;
            flex-direction: column;
            height: 100vh;

            /* Support iOS older Safari browsers */
            display: -webkit-box;
            display: -webkit-flex;
            -webkit-box-orient: vertical;
            -webkit-box-direction: normal;
            -webkit-flex-direction: column;
            -webkit-box-flex: 2;
            -webkit-flex-grow: 2;
        }

        .dashboard-content {
            -webkit-box-flex: 2;
            -webkit-flex-grow: 2;
            -ms-flex-positive: 2;
            flex-grow: 2;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }

        /* -------------- iPhone-specific begin ------------- */

        .iphone-dashboard-app {
            /* In iPhone, set the height to default */
            height: auto !important;
        }

        .iphone-dashboard-content {
            /* In iPhone, set the height to default */
        }

        .iphone-iframe-container {
            /* In iPhone, set the height to the same as the viewport */
        }

        /* -------------- iPhone-specific end ------------- */

        .dashboard-nav {
            width: 350px;
            position: fixed;
            left: 0;
            top: 0;
            bottom: 0;
            overflow: auto;
            background-color: #FFFFFF;
			z-index: 1500;
        }

        .dashboard-compact .dashboard-nav {
            display: none;
        }

        .dashboard-nav header {
            /*min-height: 84px;*/
            /*padding: 8px 27px;*/
            display: -webkit-box;
            display: -webkit-flex;
            display: -ms-flexbox;
            display: flex;
            -webkit-box-pack: center;
            -webkit-justify-content: center;
            -ms-flex-pack: center;
            justify-content: center;
            -webkit-box-align: center;
            -webkit-align-items: center;
            -ms-flex-align: center;
            align-items: center;
        }

        .dashboard-nav header .menu-toggle {
            display: none;
            margin-right: auto;
        }

        .dashboard-nav a {
            color: inherit;
        }

        .university-logo-img-container {
            /* width: 200px; */
        }

        .university-logo-img {
            /* max-width: 100%;
            max-height: 100%; */
            overflow: hidden;
            object-fit: contain;
        }

        .dashboard-nav-list {
            display: -webkit-box;
            display: -webkit-flex;
            display: -ms-flexbox;
            display: flex;
            -webkit-box-orient: vertical;
            -webkit-box-direction: normal;
            -webkit-flex-direction: column;
            -ms-flex-direction: column;
            flex-direction: column;
            justify-content: space-between;
            margin-top: 5%;
        }

        .dashboard-nav-item {
            min-height: 50px;
            padding: 8px 20px 8px 70px;
            display: -webkit-box;
            display: -webkit-flex;
            display: -ms-flexbox;
            display: flex;
            -webkit-box-align: center;
            -webkit-align-items: center;
            -ms-flex-align: center;
            align-items: center;
            letter-spacing: 0.02em;
            transition: ease-out 0.5s;
            border-radius: 10px;
            margin: 0 10px;
			cursor: pointer;
        }

        .dashboard-nav-item i {
            width: 36px;
            font-size: 19px;
            margin-left: -40px;
        }

        .active {
            background: var(--pa2-primary-color);
            color: var(--pa2-text-color) !important;
        }

        .dashboard-nav-dropdown {
            display: -webkit-box;
            display: -webkit-flex;
            display: -ms-flexbox;
            display: flex;
            -webkit-box-orient: vertical;
            -webkit-box-direction: normal;
            -webkit-flex-direction: column;
            -ms-flex-direction: column;
            flex-direction: column;
        }

        .dashboard-nav-dropdown.show {
            background: rgba(255, 255, 255, 0.04);
        }


        .dashboard-nav-dropdown.show > .dashboard-nav-dropdown-menu {
            display: -webkit-box;
            display: -webkit-flex;
            display: -ms-flexbox;
            display: flex;
        }
		
		.dashboard-nav-expand-collapse-icon {
			margin-left: 20px !important;
			display: inline-block;
			font-size: 15px !important;
		}

        .dashboard-nav-dropdown-menu {
            display: none;
            -webkit-box-orient: vertical;
            -webkit-box-direction: normal;
            -webkit-flex-direction: column;
            -ms-flex-direction: column;
            flex-direction: column;
            border-radius: 10px;
            margin: 0 10px;
        }

        .dashboard-nav-dropdown-item {
            min-height: 40px;
            padding: 8px 20px 8px 70px;
            display: -webkit-box;
            display: -webkit-flex;
            display: -ms-flexbox;
            display: flex;
            -webkit-box-align: center;
            -webkit-align-items: center;
            -ms-flex-align: center;
            align-items: center;
            transition: ease-out 0.5s;
            border-radius: 10px;
            margin: 0 10px;
        }

        .menu-toggle {
            position: relative;
            /*width: 42px;*/
            height: 80px;
            display: -webkit-box;
            display: -webkit-flex;
            display: -ms-flexbox;
            display: flex;
            -webkit-box-align: center;
            -webkit-align-items: center;
            -ms-flex-align: center;
            align-items: center;
            -webkit-box-pack: center;
            -webkit-justify-content: center;
            -ms-flex-pack: center;
            justify-content: center;
            color: #443ea2;
        }

        .menu-toggle:active, .menu-toggle:focus {
            text-decoration: none;
            color: #875de5;
        }

        .menu-toggle, .menu-toggle:hover {
            text-decoration: none !important;
        }

        .menu-toggle i {
            font-size: 28px;
            color: #000;
        }

        .dashboard-toolbar {
            min-height: 84px;
            background-color: #FFFFFF;
            display: -webkit-box;
            display: -webkit-flex;
            display: -ms-flexbox;
            display: flex;
            -webkit-box-align: center;
            -webkit-align-items: center;
            -ms-flex-align: center;
            align-items: center;
            padding: 8px 16px;
            position: fixed;
            top: 0;
            right: 0;
            left: 0;
			z-index: 1500;
        }

        .nav-item-divider {
            height: 1px;
            margin: 1rem 0;
            overflow: hidden;
            background-color: rgba(236, 238, 239, 0.3);
        }

        .card-username {
            margin-left: 25px;
            margin-right: 25px;
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            align-items: center;
            margin-top: auto;
            border-radius: 15px;
			border: 1px solid #CED4DA;
        }

        .profile-user-badge {
            display: inline-block;
            background-color: var(--pa2-primary-color);
            color: var(--pa2-text-color);
            border-radius: 50%;
            font-size: 20px;
            line-height: 42px;
            width: 42px;
            height: 42px;
            text-align: center;
            vertical-align: middle;
            text-transform: uppercase;
        }

        .username {
            padding-left: 1rem;
        }

        .page-header {
            margin: 1% var(--main-section-margin);
        }

        .iframe-container {
            margin: 0 var(--main-section-margin);
            padding: 0;
        }
		
		.user-key-icon {
			color: #6C757D;
		}

        #pagetitle {
            font-family: var(--font-family);
            font-size: 26px;
            font-weight: 500;
            line-height: 1.5;
        }

        #AuthorRepresentDiv {
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: space-between;
        }

        #AuthorRepresentDrp,
        #AuthorRepresentDrp option,
        #AuthorRepresentDrpLbl {
            font-weight: 400;
        }

        #AuthorRepresentDrp,
        #AuthorRepresentDrp option {
            padding-right: 5px;
        }

        #AuthorRepresentDrpLbl {
            margin-right: 0.5rem;
        }

        @media (max-width: 1200px) {
            #AuthorRepresentDrp,
            #AuthorRepresentDrp option {
                text-overflow: ellipsis;
                max-width: 88%;
            }

            #AuthorRepresentDiv {
                justify-content: flex-end;
                overflow-x: auto;
                margin: 10px 0;
            }
        }


        @media (max-width: 992px) {
			.dashboard-nav {
                display: none;
                position: fixed;
                top: 0;
                right: 0;
                left: 0;
                bottom: 0;
                /*z-index: 1070;*/
                width: 100%;
            }

            .dashboard-nav.mobile-show {
                display: flex;
                flex-direction: column;
            }

            .dashboard-nav header {
                justify-content: flex-start;
            }

            .page-header {
                /* margin: 80px 10px 10px 1.5%; */
                margin-top: calc(80px + var(--main-section-margin-mobile));
                margin-left: var(--main-section-margin-mobile);
                margin-right: var(--main-section-margin-mobile);
                margin-bottom: 10px;
            }

            .dashboard-nav header .menu-toggle {
                display: -webkit-box;
                display: -webkit-flex;
                display: -ms-flexbox;
                display: flex;
                margin-right: initial;
            }

            .iframe-container {
                margin: 0 var(--main-section-margin-mobile);
            }

            .profile-user-badge {
                line-height: 46px;
            }
        }

        /* Large devices (desktops, 992px and up) */
        @media (min-width: 992px) {
            .dashboard-toolbar {
                display: none;
            }

            .dashboard-compact .dashboard-toolbar {
                left: 0;
            }

            .dashboard-nav {
                display: flex;
                flex-direction: column;
            }

            .dashboard-app {
                margin-left: 350px;
            }

            .dashboard-compact .dashboard-app {
                margin-left: 0;
            }
			
			.card-username .user-key-icon {
				display: none;
			}

			.card-username:hover .user-key-icon {
				display: inline-block;
			}
        }

        /* Small devices (landscape phones, 576px and up) */
        @media only screen and (max-width: 575.98px) {
            .university-logo-container {
                text-align: center;
                height: 12%;
                align-items: center;
                justify-content: center;
                display: flex;
            }

            .university-logo-img {
                width: auto;
                height: 5rem;
            }

            .dashboard-app {
                margin-top: 10px;
                height: 99vh;
                overflow: hidden;
            }

            .fa-close {
                display: none;
            }

            .w-100-mobile {
                width: 100% !important;
            }
        }

        @media (min-width: 576px) {
            .university-logo-container {
                width: auto;
                overflow: hidden;
                display: flex;
                flex-direction: column-reverse;
                align-items: center;
                margin-top: 13%;
            }

            .university-logo-img {
                width: auto;
                height: 5rem;
            }
        }
        @media (max-height: 900px) {
            .dashboard-nav.mobile-show {
                display: flex;
                flex-direction: column;
            }
        }';
        OUT_JS := '
        const controller = new AbortController();
        const signal = controller.signal;

        const mobileScreen = window.matchMedia("(max-width: 990px )");

        $(document).ready(function () {
            window.addEventListener(beforeunload, () => {
                controller.abort();
            });

            $("#firstLetter").text($("#loggedInUserName").text().charAt(0));

            $(".dashboard-nav-dropdown-toggle").click(function () {
                $(this).closest(".dashboard-nav-dropdown")
                    .toggleClass("show")
                    .find(".dashboard-nav-dropdown")
                    .removeClass("show");
                $(this).parent()
                    .siblings()
                    .removeClass("show");
				$(this).find(".dashboard-nav-expand-collapse-icon")
					.toggleClass("fa-chevron-up")
					.toggleClass("fa-chevron-down");
            });

            $(".menu-toggle").click(function () {
                if (mobileScreen.matches) {
                    $(".dashboard-nav").toggleClass("mobile-show");
                } else {
                    $(".dashboard").toggleClass("dashboard-compact");
                }

                // If dashboard-nav is visible, show the close icon, else show the bars icon
                toggleMenuIcon();
            });

            var users = $("#AuthorRepresentDrp");
            var viewDiv = $("#AuthorRepresentDiv");

            function showAuthRepDropdownIfNotUsingTempPassword() {
               fetch("/PatientAccess/Default.aspx/IsLoginUserUsingTempPassword", {
                   method: POST,
                   headers: {
                       "Content-Type": "application/json; charset=utf-8"
                   },
                   signal: signal
               })
               .then(response => response.json())
               .then(data => {
                   if (!data.d) {
                       viewDiv.removeClass("d-none");
                   }
               })
               .catch(err => {
                    console.log(err);
					const cancelledByUser = err.name == "AbortError" || (isiPhone() && err.name == "TypeError");
					if (cancelledByUser) {
						return;
					}
					alert("An error occurred while getting data on whether current user is using temp password.");
               });
            }

            fetch("/PatientAccess/Default.aspx/GetAuthorizedRepresentatives", {
                method: POST,
                headers: {
                    "Content-Type": "application/json; charset=utf-8"
                },
                signal: signal
            })
            .then(response => response.json())
            .then(data => {
                if (data.d[2].length > 0) {
                    data.d[2].forEach(obj => {
                        const user = $("<option></option>");
                        user.attr(value, obj.FullName);
                        user.text(obj.FullName);
                        user.val(obj.Iuser);
                        users.append(user);
                    });
                    users.val(parseInt(data.d[1].iUserCurrent));
                    showAuthRepDropdownIfNotUsingTempPassword();
					adjustStylesForiPhone();
                }
            })
            .catch(err => {
                console.log(err);
                const cancelledByUser = err.name == "AbortError" || (isiPhone() && err.name == "TypeError");
				if (cancelledByUser) {
                    return;
                }
                alert("An error occurred while retrieving patient list.");
            });

            // If the user is using an iPhone, adjust the styles
            adjustStylesForiPhone();
			
			toggleMenuIcon();
			
			// init with modal spinner running
			openModalSpinner();
			
			initializeAllTooltips();
        });
		
		function isTouchDevice(){
			return (ontouchstart in window || window.DocumentTouch && document instanceof DocumentTouch);
		}
		
		function initializeAllTooltips() {
			if (!isTouchDevice()) {
				var tooltipTriggerList = [].slice.call(document.querySelectorAll(''[data-bs-toggle=tooltip]''))
				var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
					return new bootstrap.Tooltip(tooltipTriggerEl);
				});
			}
		}

        function processDropdownChanged(element) {
            var elementVal = { "AuthorRepresentDrpVal": element.value };
            fetch("/PatientAccess/Default.aspx/AuthorRepresentDrpChanged", {
                method: POST,
                headers: {
                    "Content-Type": "application/json; charset=utf-8"
                },
                body: JSON.stringify(elementVal),
                signal: signal
            })
            .then(response => response.json())
            .then(data => {
                element.value = parseInt(data.d);
            })
            .then(() => {
                getParentWindow(window).location.reload();
            })
            .catch(err => {
                if (err.name == "AbortError") {
                    return;
                }
                console.log(err);
                alert("An error occurred while changing users.");
            });
            // else { //May be useful later if we rework the Confirm window and it returns true/false instead of returning nothing
            //     $.ajax({
            //         url: "/PatientAccess/Default.aspx/GetCurrentUserId",
            //         dataType: json,
            //         type: POST,
            //         contentType: "application/json; charset=utf-8",
            //         success: function (data) {
            //                 element.value = data.d;
            //         },
            //         error: function (err) {
            //             console.log(err);
            //             alert("An error occurred while changing users.");
            //         }
            //     });

            // }
        }
		
		function redirectIFrameTo(url) {
            const iframe = document.getElementById("iFrameId");

            const onIframeLoad = function () {
                iframe.removeEventListener("load", onIframeLoad);

                // Get iframe current URL
                const currentUrl = iframe.contentWindow.location.href;

                // If the iframe URL is Unauthorized.aspx, redirect the parent to the login page
                if (currentUrl.toLowerCase().includes("unauthorized.aspx")) {
                    parent.window.location.href = "/PatientAccess/Default.aspx";
                }
            };

            iframe.addEventListener("load", onIframeLoad);

            iframe.src = url;
        }
		
		function toggleMobileMenu() {
			if (mobileScreen.matches) {
				$(".dashboard-nav").toggleClass("mobile-show");
			}

            toggleMenuIcon();
		}

        function submitLogoutForm() {
            document.getElementById("logoutForm").submit();
            return false;
        }
		
		function initParentTooltipsOnClick() {
			$("body").tooltip({ selector: ''[data-bs-toggle=tooltip]'', trigger: ''click'' });
			$("body").on(click, function (e) {
				var $parent = $(e.target).closest(''[data-bs-toggle=tooltip]'');
				if ($parent.length) {
					$(''[data-bs-toggle=tooltip]'').not($parent).tooltip(hide);
				}
				else {
					$(''[data-bs-toggle=tooltip]'').tooltip(hide);
				}
			});
		}
		
		function toggleNavItem(el) {
			// remove active class from all items
			$(".dashboard-nav-item").removeClass(active);
			$(".dashboard-nav-dropdown-item").removeClass(active);

			// add active class for the clicked item
			if (el != undefined) {
                if($(el).hasClass("dashboard-nav-dropdown-item") || $(el).hasClass("dashboard-nav-item")) {
                    $(el).addClass(active);
                }
                else {
                    $(el).children("div:first").addClass(active);
                }
			}
		}

        function cancelPageRedirects() {
            if (mobileScreen.matches) {
                $(".dashboard-nav").toggleClass("mobile-show");
            } else {
                $(".dashboard").toggleClass("dashboard-compact");
            }

            toggleMenuIcon();
        }

        function toggleMenuIcon() {
            if ($(".dashboard-nav").hasClass("mobile-show")) {
                $(".fa-close").css(display, "var(--fa-display, inline-block)");
                $(".fa-bars").css(display, "none");
            } else {
                $(".fa-close").css(display, "none");
                $(".fa-bars").css(display, "var(--fa-display, inline-block)");
            }
        }

        function isiPhone() {
            return /iPhone/.test(navigator.userAgent) && !window.MSStream;
        }

        function adjustStylesForiPhone() {
            if (isiPhone()) {
				console.log("User agent is iPhone, adjusting styles");
            }
			
			$(".dashboard-app").addClass("iphone-dashboard-app");
			$(".dashboard-content").addClass("iphone-dashboard-content");
            $(".iframe-container").addClass("iphone-iframe-container");
			var $iphoneiFrameContainer = $(".iphone-iframe-container");
			$iphoneiFrameContainer.css(height, `calc(100dvh - ${$iphoneiFrameContainer.n_offset().top}px)`);
        }

        function changeUrl(pageId) {
            history.pushState({}, "", `/PatientAccess/Default.aspx?id=${pageId}`);
        }

        function getParentWindow(currentWindow) {
            // If the current window is the top-level window, return it.
            if (currentWindow.parent === currentWindow) {
                return currentWindow;
            }

            try {
                // Check if the current window''s pathname matches "Default.aspx".
                // This ensures we''re returning the correct parent window when PA and 1A are on the same host.
                if (currentWindow.location.pathname === "/PatientAccess/Default.aspx") {
                    return currentWindow;
                }
            } catch (e) {
                // Handle cross-domain access error gracefully.
                return currentWindow;
            }

            // Recursively call getParentWindow with the parent window.
            return getParentWindow(currentWindow.parent);
        }
        ';
    END;

END;
CREATE OR REPLACE PACKAGE BODY pa2template_pkg IS

FUNCTION pa2template_html(panavid numeric DEFAULT 0) RETURN clob IS
   v_nCount		        NUMBER := 0;
   v_nUseNewTemplate    NUMBER := 0;
   v_nTemplateId        NUMBER := 0;
   v_nPanavId           NUMBER := 0;
   Result1 CLOB;
BEGIN
   SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_PA2TEMPLATE_PKG' and PROCEDURE_NAME = UPPER('CUSTOM_PA2TEMPLATE_HTML');

    BEGIN
        SELECT S."Value"
        INTO v_nUseNewTemplate
        FROM SYSOPTS S
        WHERE S."Name" = 'PA_Use_New_Template';
    END;

   IF v_nCount > 0 AND v_nUseNewTemplate > 0 THEN
     -- custom package function exists
     EXECUTE IMMEDIATE 'SELECT CUSTOM_PA2TEMPLATE_PKG.PA2TEMPLATE_HTML FROM DUAL' INTO Result1;
     RETURN Result1;
   END IF;
    v_nPanavId := panavId;
    BEGIN
        SELECT PATEMPLATEID_FK
        INTO v_nTemplateId
        FROM PANAV
        WHERE "PANAVID" = v_nPanavId;
    END;

    BEGIN
        SELECT PATEMPLATEHTML
        INTO Result1
        FROM PATEMPLATE
        WHERE "PATEMPLATEID" = v_nTemplateId;
    END;

   RETURN Result1;
END;


FUNCTION pa2template_css(panavid numeric DEFAULT 0) RETURN clob IS
   v_nCount		        NUMBER := 0;
   v_nUseNewTemplate    NUMBER := 0;
   v_nTemplateId        NUMBER := 0;
   v_nPanavId           NUMBER := 0;
   Result1 CLOB;
BEGIN
   SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_PA2TEMPLATE_PKG' and PROCEDURE_NAME = UPPER('CUSTOM_PA2TEMPLATE_CSS');

    BEGIN
        SELECT S."Value"
        INTO v_nUseNewTemplate
        FROM SYSOPTS S
        WHERE S."Name" = 'PA_Use_New_Template';
    END;

   IF v_nCount > 0 AND v_nUseNewTemplate > 0 THEN
     -- custom package function exists
     EXECUTE IMMEDIATE 'SELECT CUSTOM_PA2TEMPLATE_PKG.CUSTOM_PA2TEMPLATE_CSS FROM DUAL' INTO Result1;
     RETURN Result1;
   END IF;
    v_nPanavId := panavId;
    BEGIN
        SELECT PATEMPLATEID_FK
        INTO v_nTemplateId
        FROM PANAV
        WHERE "PANAVID" = v_nPanavId;
    END;

    BEGIN
        SELECT PATEMPLATECSS
        INTO Result1
        FROM PATEMPLATE
        WHERE "PATEMPLATEID" = v_nTemplateId;
    END;

   RETURN Result1;
END;


FUNCTION pa2template_js(panavid numeric DEFAULT 0) RETURN clob IS
   v_nCount		        NUMBER := 0;
   v_nUseNewTemplate    NUMBER := 0;
   v_nTemplateId        NUMBER := 0;
   v_nPanavId           NUMBER := 0;
   Result1 CLOB;
BEGIN
   SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_PA2TEMPLATE_PKG' and PROCEDURE_NAME = UPPER('CUSTOM_PA2TEMPLATE_JS');

    BEGIN
        SELECT S."Value"
        INTO v_nUseNewTemplate
        FROM SYSOPTS S
        WHERE S."Name" = 'PA_Use_New_Template';
    END;

   IF v_nCount > 0 AND v_nUseNewTemplate > 0 THEN
     -- custom package function exists
     EXECUTE IMMEDIATE 'SELECT CUSTOM_PA2TEMPLATE_PKG.CUSTOM_PA2TEMPLATE_JS FROM DUAL' INTO Result1;
     RETURN Result1;
   END IF;
    v_nPanavId := panavId;
    BEGIN
        SELECT PATEMPLATEID_FK
        INTO v_nTemplateId
        FROM PANAV
        WHERE "PANAVID" = v_nPanavId;
    END;

    BEGIN
        SELECT PATEMPLATEJS
        INTO Result1
        FROM PATEMPLATE
        WHERE "PATEMPLATEID" = v_nTemplateId;
    END;

   RETURN Result1;
END;


END;
CREATE OR REPLACE PACKAGE BODY patient_pkg IS



    /**************************************************************************/

    PROCEDURE chartmerge(IN vpatientbad numeric, IN vpatientgood numeric, IN vuser numeric, IN vstationid numeric, OUT vsuccess numeric) IS

      PRAGMA AUTONOMOUS_TRANSACTION;			--AX-41069

      vPatientGoodRec PATIENT%ROWTYPE;

      vPatientBadRec PATIENT%ROWTYPE;

      vPatient2BadRec PATIENT2%ROWTYPE;

      vPatient2GoodRec PATIENT2%ROWTYPE;

      vErrMsg  VARCHAR2(255) := NULL;

      vCount NUMBER(10);

      vMergeEprSuccess NUMBER(1);

      vSql  VARCHAR2(2000);

      vOldiUserId NUMBER;														--E37209.3.4

      vNewiUserId NUMBER;														--E37209.3.4

      vNewestPrevCarePatient NUMBER;										-- B138400

      vPrevCarePatient NUMBER;												-- B138400

      v_MergeDesc  VARCHAR2(2000);										-- B142286

			vCountPtRace NUMBER(10);                  -- AX-1113.2410

			vCountPtGender NUMBER(10);                -- AX-18695y

      

		-- AX-974.1059 - start

		VISFIRSTINSERT BOOLEAN;

		VISFIRSTUPDATE BOOLEAN;

		

		VINSERTAUDIT AUDITHIS."Audit"%TYPE;

		vupdateaudit audithis."Audit"%type;



		CURSOR CURPTRACE (PPATIENT PATIENT."Patient"%TYPE) IS

		select * from ptrace where "Patient" = pPatient AND "Deleted" = 0;   -- AX-1113.2410 check for deleted

		-- AX-974.1059 - end



		-- AX-17822

		v_Relation				PTDEPEND."Relation"%TYPE;

		CURSOR DependantsCur

		IS 

			SELECT G."Patient" FROM PTGUAR G, PATIENT P 

			WHERE G."RespPatient" = vPatientGood AND G."Deleted" = 0

			  AND G."Patient" = P."Patient" AND P."Deleted" = 0;



		-- AX-17822c

		CURSOR BadDependantsCur

		IS 

			SELECT G."Patient" FROM PTGUAR G, PATIENT P 

			WHERE G."RespPatient" = vPatientBad AND G."Deleted" = 0

			  AND G."Patient" = P."Patient" AND P."Deleted" = 0;

    

		vCurPtRaceRowType CURPTRACE%rowtype;										-- AX-1113.2527



		-- AX-20768

		vRecordId CLOB := '';

		vRecordContent CLOB := '';

		

    BEGIN

      vSuccess := 0;



      BEGIN



        SELECT *

          INTO vPatientBadRec

          FROM patient

         WHERE "Patient" = vPatientBad;

  

        SELECT *

          INTO vPatientGoodRec

          FROM patient

         WHERE "Patient" = vPatientGood;



        -- AX-578.18773

        -- Update patient2 records

        UPDATE patient2 

        SET "ToothState" = '00000000000000000000000000000000' 

        WHERE "PtxPId" = vPatientBadRec."Patient" 

        AND SUBSTR("ToothState", 0, 1) = ' ';



        UPDATE patient2 

        SET "PermanentState" = '00000000000000000000000000000000' 

        WHERE "PtxPId" = vPatientBadRec."Patient" 

        AND SUBSTR("PermanentState", 0, 1) = ' ';



        UPDATE patient2 

        SET "PrimaryState" = '00000000000000000000000000000000' 

        WHERE "PtxPId" = vPatientBadRec."Patient" 

        AND SUBSTR("PrimaryState", 0, 1) = ' ';



        -- If all operations succeed, commit the transaction

        COMMIT;

        

      EXCEPTION 

        WHEN NO_DATA_FOUND THEN

          -- Roll back any changes and set success flag

          ROLLBACK;

        vSuccess := 1;

        GOTO end_of_process;

        WHEN OTHERS THEN

          -- Roll back any changes and set success flag

          ROLLBACK;

          vSuccess := 1;

          GOTO end_of_process;

      END;



		BEGIN

        SELECT *

          INTO vPatient2BadRec

          FROM patient2

         WHERE "PtxPId" = vPatientBadRec."Patient";

      EXCEPTION WHEN NO_DATA_FOUND THEN

        vPatient2BadRec := NULL;

      END;



		-- AX-578.18773

		BEGIN

        UPDATE patient2 set "ToothState" = '00000000000000000000000000000000' WHERE "PtxPId" = vPatientGoodRec."Patient" AND SUBSTR("ToothState", 0, 1) = ' ';

		  UPDATE patient2 set "PermanentState" = '00000000000000000000000000000000' WHERE "PtxPId" = vPatientGoodRec."Patient" AND SUBSTR("PermanentState", 0, 1) = ' ';

		  UPDATE patient2 set "PrimaryState" = '00000000000000000000000000000000' WHERE "PtxPId" = vPatientGoodRec."Patient" AND SUBSTR("PrimaryState", 0, 1) = ' ';

      END;



      BEGIN

        SELECT *

          INTO vPatient2GoodRec

          FROM patient2

         WHERE "PtxPId" = vPatientGoodRec."Patient";

      EXCEPTION WHEN NO_DATA_FOUND THEN

        vPatient2GoodRec := NULL;

      END;

      

      -- B142286 - auditlog for chart merge

      IF ( AUDITLOG_PKG.GetSecureLog() <> 0 ) THEN

	      v_MergeDesc := 'Invalid Chart Number: ' || TRIM(vPatientBadRec."Chart") || ', Valid Chart Number: ' || TRIM(vPatientGoodRec."Chart");

	      AUDITLOG_PKG.InsertAuditLog(vPatientGoodRec."Patient", AUDITLOG_PKG.c_nActionEdit, '', 'Chart Merge', v_MergeDesc);

      END IF;





      IF vPatient2GoodRec."Auto" IS NULL THEN

        SELECT PATIENT2_AUTO_SEQ.NEXTVAL,

               "Chart","Last","First","Middle",0,vUser,vPatientGoodRec."Patient",

               NVL(vPatient2BadRec."ToothState",'00000000000000000000000000000000'),

               NVL(vPatient2BadRec."PermanentState",'00000000000000000000000000000000'),

               NVL(vPatient2BadRec."PrimaryState",'00000000000000000000000000000000'),

               TRUNC(SYSDATE),vStationId

          INTO vPatient2GoodRec."Auto",

               vPatient2GoodRec."ChartId",

               vPatient2GoodRec."LastName",

               vPatient2GoodRec."FirstName",

               vPatient2GoodRec."MidName",

               vPatient2GoodRec."Status",

               vPatient2GoodRec."User",

               vPatient2GoodRec."PtxPId",

               vPatient2GoodRec."ToothState",

               vPatient2GoodRec."PermanentState",

               vPatient2GoodRec."PrimaryState",

               vPatient2GoodRec."Date",

               vPatient2GoodRec."StationId"

          FROM patient

         WHERE "Patient" = vPatientGoodRec."Patient";



        INSERT INTO patient2("Auto","ChartId","LastName","FirstName","MidName",

                             "Status","User","PtxPId","ToothState","PermanentState",

                             "PrimaryState","Date","StationId")

        VALUES (vPatient2GoodRec."Auto",

                vPatient2GoodRec."ChartId",

                vPatient2GoodRec."LastName",

                vPatient2GoodRec."FirstName",

                vPatient2GoodRec."MidName",

                vPatient2GoodRec."Status",

                vPatient2GoodRec."User",

                vPatient2GoodRec."PtxPId",

                vPatient2GoodRec."ToothState",

                vPatient2GoodRec."PermanentState",

                vPatient2GoodRec."PrimaryState",

                vPatient2GoodRec."Date",

                vPatient2GoodRec."StationId");

      ELSIF vPatient2BadRec."Auto" IS NULL THEN

        SELECT PATIENT2_AUTO_SEQ.NEXTVAL,

               "Chart","Last","First","Middle",0,vUser,vPatientBadRec."Patient",

               '00000000000000000000000000000000',

               '00000000000000000000000000000000',

               '00000000000000000000000000000000',

               TRUNC(SYSDATE),vStationId

          INTO vPatient2BadRec."Auto",

               vPatient2BadRec."ChartId",

               vPatient2BadRec."LastName",

               vPatient2BadRec."FirstName",

               vPatient2BadRec."MidName",

               vPatient2BadRec."Status",

               vPatient2BadRec."User",

               vPatient2BadRec."PtxPId",

               vPatient2BadRec."ToothState",

               vPatient2BadRec."PermanentState",

               vPatient2BadRec."PrimaryState",

               vPatient2BadRec."Date",

               vPatient2BadRec."StationId"

          FROM patient

         WHERE "Patient" = vPatientGoodRec."Patient";



        INSERT INTO patient2("Auto","ChartId","LastName","FirstName","MidName",

                             "Status","User","PtxPId","ToothState","PermanentState",

                             "PrimaryState","Date","StationId")

        VALUES (vPatient2BadRec."Auto",

                vPatient2BadRec."ChartId",

                vPatient2BadRec."LastName",

                vPatient2BadRec."FirstName",

                vPatient2BadRec."MidName",

                vPatient2BadRec."Status",

                vPatient2BadRec."User",

                vPatient2BadRec."PtxPId",

                vPatient2BadRec."ToothState",

                vPatient2BadRec."PermanentState",

                vPatient2BadRec."PrimaryState",

                vPatient2BadRec."Date",

                vPatient2BadRec."StationId");



      ELSE

        BEGIN

          IF (LENGTH(TRIM(vPatient2BadRec."ToothState")) != 32 AND vPatient2BadRec."ToothState" != ' ') OR

             (LENGTH(TRIM(vPatient2BadRec."PermanentState")) != 32 AND vPatient2BadRec."PermanentState" != ' ' ) OR

             (LENGTH(TRIM(vPatient2BadRec."PrimaryState")) != 32 AND vPatient2BadRec."PrimaryState" != ' ') OR

             (LENGTH(TRIM(vPatient2GoodRec."ToothState")) != 32 AND vPatient2GoodRec."ToothState" != ' ') OR

             (LENGTH(TRIM(vPatient2GoodRec."PermanentState")) != 32 AND vPatient2GoodRec."PermanentState" != ' ') OR

             (LENGTH(TRIM(vPatient2GoodRec."PrimaryState")) != 32 AND vPatient2GoodRec."PrimaryState" != ' ')

          THEN

            vSuccess := 2;

            GOTO end_of_process;

          END IF;



          IF vPatient2BadRec."ToothState" = ' ' THEN

             vPatient2BadRec."ToothState" := '00000000000000000000000000000000';

          END IF;

          

          IF vPatient2BadRec."PermanentState" = ' ' THEN

             vPatient2BadRec."PermanentState" := '00000000000000000000000000000000';

          END IF;

          

          IF vPatient2BadRec."PrimaryState" = ' ' THEN

             vPatient2BadRec."PrimaryState" := '00000000000000000000000000000000';

          END IF;

          

          IF vPatient2GoodRec."ToothState" = ' ' THEN

             vPatient2GoodRec."ToothState" := '00000000000000000000000000000000';

          END IF;

          

          IF vPatient2GoodRec."PermanentState" = ' ' THEN

             vPatient2GoodRec."PermanentState" := '00000000000000000000000000000000';

          END IF;

          

          IF vPatient2GoodRec."PrimaryState" = ' ' THEN

             vPatient2GoodRec."PrimaryState" := '00000000000000000000000000000000';

          END IF;



          FOR i IN 1..32 LOOP

            IF SUBSTR(vPatient2BadRec."ToothState",i,1) > SUBSTR(vPatient2GoodRec."ToothState",i,1) THEN

              vPatient2GoodRec."ToothState" := SUBSTR(vPatient2GoodRec."ToothState",1,i-1) || SUBSTR(vPatient2BadRec."ToothState",i,1) || SUBSTR(vPatient2GoodRec."ToothState",i+1);

            END IF;



            IF SUBSTR(vPatient2BadRec."PermanentState",i,1) > SUBSTR(vPatient2GoodRec."PermanentState",i,1) THEN

              vPatient2GoodRec."PermanentState" := SUBSTR(vPatient2GoodRec."PermanentState",1,i-1) || SUBSTR(vPatient2BadRec."PermanentState",i,1) || SUBSTR(vPatient2GoodRec."PermanentState",i+1);

            END IF;



            IF SUBSTR(vPatient2BadRec."PrimaryState",i,1) > SUBSTR(vPatient2GoodRec."PrimaryState",i,1) THEN

              vPatient2GoodRec."PrimaryState" := SUBSTR(vPatient2GoodRec."PrimaryState",1,i-1) || SUBSTR(vPatient2BadRec."PrimaryState",i,1) || SUBSTR(vPatient2GoodRec."PrimaryState",i+1);

            END IF;

          END LOOP;

        END;

      END IF;

      

      -- AX-18695y check if PtGender exist for good patient

      -- if so, leave it; else move the one from bad patient to good patient

      SELECT COUNT(1) INTO vCountPtGender FROM ptgender WHERE "Patient" = vPatientGood;

      IF vCountPtGender = 0 THEN

        UPDATE ptgendrh SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



        UPDATE ptgender SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";

      END IF;





      UPDATE answer2 SET "PId" = vPatient2GoodRec."Auto" WHERE "PId" = vPatient2BadRec."Auto";



      UPDATE apexpert SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE ap_note SET "AP_NOTE_PatientId" = vPatientGoodRec."Patient" WHERE "AP_NOTE_PatientId" = vPatientBadRec."Patient";



      UPDATE ap_note SET "AP_NOTE_AppId" = vPatientGoodRec."Patient" WHERE "AP_NOTE_AppId" = vPatientBadRec."Patient" AND "AP_NOTE_Type" IN (3,4,5);



      FOR rec IN (SELECT "Appointment" FROM appoint WHERE "Patient" = vPatientBadRec."Patient") LOOP

        UPDATE appthis SET "Patient" = vPatientGoodRec."Patient" WHERE "Appointment" = rec."Appointment";



        UPDATE appoint SET "Patient" = vPatientGoodRec."Patient" WHERE "Appointment" = rec."Appointment";

      END LOOP;



      UPDATE charthis SET "Patient" = vPatientGoodRec."Patient", "Chart" = vPatientGoodRec."Chart" WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE chartlnk SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      FOR rec_req IN (SELECT "CApReq" FROM CAPREQ WHERE "Patient" = vPatientBadRec."Patient") LOOP

		UPDATE capreq SET "Patient" = vPatientGoodRec."Patient" WHERE "CApReq" = rec_req."CApReq";						--AX-22027.22097; AX-22027a

	  END LOOP;



      UPDATE checkin SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE claim SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE claimit SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";

      

      -- E77745

      UPDATE claimh SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";

      UPDATE claimith SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      SELECT COUNT(1)

        INTO vCount

        FROM user_tables

       WHERE table_name='TXPLAN';																	

      IF vCount = 1 THEN

        vSql := 'UPDATE TXPLAN SET "Patient" = :1 WHERE "Patient" = :2';

        EXECUTE IMMEDIATE vSql USING vPatientGoodRec."Patient", vPatientBadRec."Patient";

      END IF;



      -- B31978

      UPDATE contract SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" =vPatientBadRec."Patient";



      UPDATE deplimit D SET D."Patient" = vPatientGoodRec."Patient"

       WHERE D."Patient" = vPatientBadRec."Patient"

         AND NOT EXISTS (SELECT 1

                           FROM deplimit D2

                          WHERE D2."PolicyId" = D."PolicyId"

                                AND D2."Patient" = vPatientGoodRec."Patient"

                            AND D2."Id" = D."Id"

                            AND D2."Category" = D."Category");



      DELETE FROM deplimit WHERE "Patient" = vPatientBadRec."Patient";





      UPDATE detail2 SET "PId" = vPatient2GoodRec."Auto" WHERE "PId" = vPatient2BadRec."Auto";



      UPDATE grading SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE graphp2 SET "PId" = vPatient2GoodRec."Auto" WHERE "PId" = vPatient2BadRec."Auto";



      UPDATE graphhis SET "PId" = vPatient2GoodRec."Auto" WHERE "PId" = vPatient2BadRec."Auto";



-- B133473 took out the "Family" = vPatientBadRec."Patient" clause

--      UPDATE history SET "Patient" = vPatientGoodRec."Patient" WHERE "Family" = vPatientBadRec."Patient" AND "Patient" = vPatientBadRec."Patient";

      UPDATE history SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE history SET "Family" = vPatientGoodRec."Patient" WHERE "Family" = vPatientBadRec."Patient";



		UPDATE INDLOG SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient"; -- E136962



		-- AX-20768 - write to MERGELOG...

		FOR labrec IN (SELECT * FROM LABORDER

                   WHERE "Patient" = vPatientBadRec."Patient" AND "IseLab" = 1) LOOP

      BEGIN

		  vRecordId := '{"LabOrder":' || labrec."LabOrder" || '}';	

		  vRecordContent := '{

										"LabOrder":' || labrec."LabOrder" || ',

										"CaseNo":"' || NVL(TRIM(labrec."CaseNo"), '') || '",

										"Patient":' || labrec."Patient" || ',

										"LabProcedure":"' || NVL(TRIM(labrec."LabProcedure"), '') || '",

										"Discipline":"' ||NVL(TRIM( labrec."Discipline"), '') || '",

										"Date":"' || TO_CHAR(labrec."Date") || '",

										"RemakeStudent":' || labrec."RemakeStudent" || ',

										"RemakeStaff":' || labrec."RemakeStaff" || ',

										"RemakeLabOrder":' || labrec."RemakeLabOrder" || ',

										"WaiveCharges":' || labrec."WaiveCharges" || ',

										"LabOut":' || labrec."LabOut" || ',

										"LabCode":"' || NVL(TRIM(labrec."LabCode"), '') || '",

										"DateOut":"' || TO_CHAR(labrec."DateOut") || '",

										"TimeOut":' || labrec."TimeOut" || ',

										"User":' || labrec."User" || ',

										"Deleted":' || labrec."Deleted" || ',

										"CurrentItem":' || labrec."CurrentItem" || ',

										"Status":' || labrec."Status" || ',

										"CompletionDate":"' || TO_CHAR(labrec."CompletionDate") || '",

										"TotalCost":' || labrec."TotalCost" || ',

										"TotalCharge":' || labrec."TotalCharge" || ',

										"IsOrtho":' || labrec."IsOrtho" || ',

										"OrigRecNo":' || labrec."OrigRecNo" || ',

										"Audit":' || labrec."Audit" || ',

										"IseLab":' || labrec."IseLab" || '

									}';

		  

		  INSERT INTO MERGELOG VALUES(MERGELOG_MERGELOG_SEQ.NEXTVAL, vPatientBadRec."Patient", vPatientGoodRec."Patient", SYSDATE, 'LABORDER', 

		  vRecordId, vRecordContent, 0);

      END;

      END LOOP;

		

      SELECT COUNT(1)

        INTO vCount

        FROM user_tables

       WHERE table_name='LABORDER';

      IF vCount = 1 THEN

        vSql := 'UPDATE laborder SET "Patient" = :1 WHERE "Patient" = :2';

        EXECUTE IMMEDIATE vSQL USING vPatientGoodRec."Patient", vPatientBadRec."Patient";

      END IF;



		-- AX-20714

		SELECT COUNT(1)

        INTO vCount

        FROM user_tables

       WHERE table_name='LABORDH';

      IF vCount = 1 THEN

        vSql := 'UPDATE LABORDH SET "Patient" = :1 WHERE "Patient" = :2';

        EXECUTE IMMEDIATE vSQL USING vPatientGoodRec."Patient", vPatientBadRec."Patient";

      END IF;



		UPDATE LABTTRX SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient"; -- AX-20714



		

      UPDATE noteovr SET "Patient" = vPatientGoodRec."Patient"

       WHERE "Patient" = vPatientBadRec."Patient"

         AND "Type" = 0

         AND "ParentId" IN (SELECT "Auto" FROM notes2 WHERE "PId" = vPatient2BadRec."Auto");



      SELECT COUNT(1)

        INTO vCount

        FROM user_tables

       WHERE table_name='TXPNOTE';



      IF vCount = 1 THEN

        vSql := 'UPDATE noteovr SET "Patient" = :1 WHERE "Patient" = :2 AND "Type" = 2

                 AND "ParentId" IN (SELECT "TxPNote" FROM txpnote WHERE "Patient" = :3)';

        EXECUTE IMMEDIATE vSql USING vPatientGoodRec."Patient", vPatientBadRec."Patient", vPatientBadRec."Patient";

      END IF;



      UPDATE notes2 SET "PId" = vPatient2GoodRec."Auto" WHERE "PId" = vPatient2BadRec."Auto";



        -- B23814

      UPDATE odmsgsnt SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE pat2his SET "Auto" = vPatient2GoodRec."Auto", "ChartId" = vPatientGoodRec."Chart" WHERE "Auto" = vPatient2BadRec."Auto";



      DELETE FROM pat2his P

       WHERE P."Auto" = vPatient2GoodRec."Auto"		-- B69793

         AND P."Pat2His" != (SELECT MIN(P2."Pat2His")

                               FROM Pat2his P2

                              WHERE P2."Auto" = P."Auto"

                                AND P2."HistoryType" = 1

                                AND P."HistoryType" = P2."HistoryType");



      UPDATE pathis SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE pathis SET "Family" = vPatientGoodRec."Patient" WHERE "Family" = vPatientBadRec."Patient";



      -- B31978

      UPDATE payplan SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE payplan SET "Family" = vPatientGoodRec."Patient" WHERE "Family" = vPatientBadRec."Patient";



      -- B31978

      UPDATE payplan SET "RespId" = vPatientGoodRec."Patient" WHERE "RespId" = vPatientBadRec."Patient";



      UPDATE planhis SET "RespId" = vPatientGoodRec."Patient" WHERE "RespId" = vPatientBadRec."Patient";



      UPDATE picture SET "Patient" = vPatientGoodRec."Patient"

       WHERE "Patient" = vPatientBadRec."Patient"

         AND NOT EXISTS (SELECT "Patient" FROM picture WHERE "Patient" = vPatientGoodRec."Patient");



      DELETE FROM picture WHERE "Patient" = vPatientBadRec."Patient";



	   -- E37209.3.4  added

	   Merge_iInfo (vPatientBadRec."Patient", vPatientGoodRec."Patient", 

	  					vOldiUserId, vNewiUserId);



      MERGE_EPR(vPatientBadRec."Patient", vPatientGoodRec."Patient", 

	  					vOldiUserId, vNewiUserId,

	  					vMergeEprSuccess);



      IF vMergeEprSuccess = 0 THEN

        vSuccess := 3;

        GOTO end_of_process;

      END IF;





      -- B31978

      UPDATE planhis SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";

      UPDATE planhis SET "Family" = vPatientGoodRec."Patient" WHERE "Family" = vPatientBadRec."Patient";



		-- B142152

		UPDATE ptalert SET "eRxSyncAudit" = 0 WHERE "Patient" = vPatientBadRec."Patient";

		-- E126674

		UPDATE ptalert SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";

		UPDATE ptalerth SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      -- AX-25164 moved from below	

      UPDATE ptdepend SET "Patient" = vPatientGoodRec."Patient"

       WHERE "Patient" = vPatientBadRec."Patient"

         AND "PolicyId" NOT IN (SELECT "PolicyId" FROM ptdepend WHERE "Patient" = vPatientGoodRec."Patient");

		

      UPDATE ptdepext SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE ptdephis SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";





	-- AX-17822c

	FOR rec IN (SELECT "PolicyId" FROM ptpol WHERE "Patient" = vPatientGoodRec."Patient") LOOP

        BEGIN



			-- Add bad patient's dependants to good patient's policies...

			FOR BadDependantsRec IN BadDependantsCur 

					LOOP

							-- Try to set Relationship from a previous dependancy

							BEGIN

								SELECT "Relation"

									INTO v_Relation

									FROM PTDEPEND D, PTPOL P

									WHERE D."Patient" = BadDependantsRec."Patient"

									AND D."PolicyId" = rec."PolicyId"

									AND ROWNUM = 1;

							EXCEPTION WHEN NO_DATA_FOUND THEN

								IF vPatientBadRec."Patient" = BadDependantsRec."Patient" THEN

									v_Relation := 0; -- self

								ELSE

									v_Relation := 4; -- other

								END IF;

							END;



					POLINS_PKG.AddGuarantorDependant(vPatientGoodRec."Patient", BadDependantsRec."Patient", v_Relation, vUser, vStationId);



				END LOOP;

			END;

			END LOOP;		





      -- E0037

      -- B31978

      -- E56421.1

		-- AX-17891

      FOR rec IN (SELECT "PolicyId" FROM ptpol

                   WHERE "Patient" = vPatientBadRec."Patient") LOOP

      BEGIN



		  	-- AX-17822

			-- Add good patient's dependants to bad patient's policies...

			FOR DependantsRec IN DependantsCur 

					LOOP

							-- Try to set Relationship from a previous dependancy

							BEGIN

								SELECT "Relation"

								  INTO v_Relation

								  FROM PTDEPEND D, PTPOL P

								 WHERE D."Patient" = DependantsRec."Patient"

									AND D."PolicyId" = rec."PolicyId"

									AND ROWNUM = 1;

							EXCEPTION WHEN NO_DATA_FOUND THEN

								IF vPatientGoodRec."Patient" = DependantsRec."Patient" THEN

									v_Relation := 0; -- self

								ELSE

									v_Relation := 4; -- other

								END IF;

							END;



					POLINS_PKG.AddGuarantorDependant(vPatientBadRec."Patient", DependantsRec."Patient", v_Relation, vUser, vStationId);



				END LOOP;



        UPDATE ptpolh SET

          "Patient" = vPatientGoodRec."Patient",

          "Family" = vPatientGoodRec."Family"

         WHERE "PolicyId" = rec."PolicyId";



        UPDATE ptpol SET

          "Patient" = vPatientGoodRec."Patient",

          "Family" = vPatientGoodRec."Family"

        WHERE "PolicyId" = rec."PolicyId";



      END;

      END LOOP;



      FOR rec IN (SELECT "PolicyId" FROM ptpol

                   WHERE "Family" = vPatientBadRec."Family"

                     AND "Patient" != vPatientBadRec."Patient") LOOP

      BEGIN

        UPDATE ptpolh SET "Family" = vPatientGoodRec."Family" WHERE "PolicyId" = rec."PolicyId";



        UPDATE ptpol SET "Family" = vPatientGoodRec."Family" WHERE "PolicyId" = rec."PolicyId";

      END;

      END LOOP;



      -- B31978





		-- AX-20768 - write to MERGELOG...

		FOR rec IN (SELECT * FROM PRESCRIP

                   WHERE "Patient" = vPatientBadRec."Patient" AND "RcopiaID" IS NOT NULL) LOOP

      BEGIN

		  vRecordId := '{"Prescription":' || rec."Prescription" || '}';	

		  vRecordContent := '{

										"Prescription":' || rec."Prescription" || ',

										"Patient":' || rec."Patient" || ',

										"Date":"' || TO_CHAR(rec."Date") || '",

										"Practice":' || rec."Practice" || ',

										"Provider":"' || NVL(TRIM(rec."Provider"), '') || '",

										"DrugDescription":"' || NVL(TRIM(rec."DrugDescription"), '') || '",

										"Dose":" ' || NVL(TRIM(rec."Dose"), '') || '",

										"DrugFrqDesc":"' || NVL(TRIM(rec."DrugFrqDesc"), '') || '",

										"Total":"' || NVL(TRIM(rec."Total"), '') || '",

										"Refills":' || rec."Refills" || ',

										"Note":"' || NVL(TRIM(rec."Note"), '') || '",

										"IsPhoned":' || rec."IsPhoned" || ',

										"Area":" ' || NVL(TRIM(rec."Area"), '') || '",

										"Telephone":"' || NVL(TRIM(rec."Telephone"), '') || '",

										"Pharmacy":"' || NVL(TRIM(rec."Pharmacy"), '') || '",

										"Audit":' || rec."Audit" || ',

										"ApprovalUser":' || rec."ApprovalUser" || ',

										"ApprovalDate":"' || TO_CHAR(rec."ApprovalDate") || '",

										"IsVoided":' || rec."IsVoided" || ',

										"VoidReason":"' || NVL(TRIM(rec."VoidReason"), '') || '",

										"VoidAudit":' || rec."VoidAudit" || ',

										"VoidAppUser":' || rec."VoidAppUser" || ',

										"Reference":"' || NVL(TRIM(rec."Reference"), '') || '",

										"Custom1":"' || NVL(TRIM(rec."Custom1"), '') || '",

										"Custom2":"' || NVL(TRIM(rec."Custom2"), '') || '",

										"IsFaxed":' || rec."IsFaxed" || ',

										"FaxArea":"' || NVL(TRIM(rec."FaxArea"), '') || '",

										"FaxPhone":"' || NVL(TRIM(rec."FaxPhone"), '') || '",

										"Drug":"' || NVL(TRIM(rec."Drug"), '') || '",

										"PrescripType":' || rec."PrescripType" || ',

										"StartDate":"' || TO_CHAR(rec."StartDate") || '",

										"EndDate":"' || TO_CHAR(rec."EndDate") || '",

										"Deleted":' || rec."Deleted" || ',

										"eRxSyncAudit":' || rec."eRxSyncAudit" || ',

										"RxNorm":"' || NVL(TRIM(rec."RxNorm"), '') || '",

										"RcopiaID":"' || NVL(TRIM(rec."RcopiaID"), '') || '",

										"DrugSchedule":"' || NVL(TRIM(rec."DrugSchedule"), '') || '",

										"IsSentEDI":' || rec."IsSentEDI" || ',

										"IsPrinted":' || rec."IsPrinted" || '

									}';

		  

		  INSERT INTO MERGELOG VALUES(MERGELOG_MERGELOG_SEQ.NEXTVAL, vPatientBadRec."Patient", vPatientGoodRec."Patient", SYSDATE, 'PRESCRIP', 

		  vRecordId, vRecordContent, 0);

      END;

      END LOOP;



      -- B133602 set eRxSyncAudit to 0 so merged medications will sync to RCopia

      UPDATE prescrip SET "eRxSyncAudit" = 0 WHERE "Patient" = vPatientBadRec."Patient" AND "PrescripType" = 0;

      -- B31978

      UPDATE prescrip SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";

      -- B133602

      UPDATE prescrih SET "eRxSyncAudit" = 0 WHERE "Patient" = vPatientBadRec."Patient" AND "PrescripType" = 0;

      -- E105423.2.3

      UPDATE prescrih SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";

      -- B133602

      -- don't merge PTERX as it would mess up sync with RCopia

      

      -- E133016.7 logical thing to do here but might be confusing to the user... 

      -- might need to be re-considered differently, pending on how PRESCRIP table will be handled 

      --    esp. with RCopia integration involved...

      UPDATE EPREVIEW SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";

      

      -- E136891.4

      UPDATE mtestord SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



	  --B58918

      UPDATE ptprb SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



	  --B58918

      UPDATE ptprbh SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      FOR rec IN (SELECT "Contact" FROM ptcont WHERE "Patient" = vPatientBadRec."Patient") LOOP

        UPDATE ptconhis SET "Patient" = vPatientGoodRec."Patient" WHERE "Contact" = rec."Contact";



        UPDATE ptcont SET "Patient" = vPatientGoodRec."Patient" WHERE "Contact" = rec."Contact";

      END LOOP;

				

      UPDATE ptemploy SET "Patient" = vPatientGoodRec."Patient"

       WHERE "Patient" = vPatientBadRec."Patient"

         AND "Employer" NOT IN (SELECT "Employer" FROM ptemploy WHERE "Patient" = vPatientGoodRec."Patient");



      DELETE FROM ptemploy WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE ptemphis SET "Patient" = vPatientGoodRec."Patient"

       WHERE "Patient" = vPatientBadRec."Patient"

         AND "Employer" NOT IN (SELECT DISTINCT "Employer" FROM ptemphis WHERE "Patient" = vPatientGoodRec."Patient");



      DELETE FROM ptemphis WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE pthist SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE ptguar SET "Patient" = vPatientGoodRec."Patient"

       WHERE "Patient" = vPatientBadRec."Patient"

         AND "RespPatient" NOT IN (SELECT "RespPatient" FROM ptguar WHERE "Patient" = vPatientGoodRec."Patient");



      DELETE FROM ptguar WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE ptguar SET "RespPatient" = vPatientGoodRec."Patient"

       WHERE "RespPatient" = vPatientBadRec."Patient"

         AND "Patient" NOT IN (SELECT "Patient" FROM ptguar WHERE "RespPatient" = vPatientGoodRec."Patient");



      DELETE FROM ptguar WHERE "RespPatient" = vPatientBadRec."Patient";



	  -- AX-10591.10917

      UPDATE ptguar SET "IsPolicyGuarantor" = 1

       WHERE "RespPatient" = vPatientGoodRec."Patient" AND "IsPolicyGuarantor" = 0 AND

		EXISTS (SELECT 1 FROM POLICY WHERE "Patient" = vPatientGoodRec."Patient" AND "Deleted" = 0);





      UPDATE ptguahis SET "Patient" = vPatientGoodRec."Patient"

       WHERE "Patient" = vPatientBadRec."Patient"

         AND "RespPatient" NOT IN (SELECT distinct "RespPatient" FROM ptguahis WHERE "Patient" = vPatientGoodRec."Patient");



      DELETE FROM ptguahis WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE ptguahis SET "RespPatient" = vPatientGoodRec."Patient"

       WHERE "RespPatient" = vPatientBadRec."Patient"

         AND "Patient" NOT IN (SELECT distinct "Patient" FROM ptguahis WHERE "RespPatient" = vPatientGoodRec."Patient");



      DELETE FROM ptguahis WHERE "RespPatient" = vPatientBadRec."Patient";



      SELECT count(1)

        INTO vCount

        FROM ptguar

       WHERE "Patient" = vPatientGoodRec."Patient"

         AND "IsPrimaryGuarantor" = 1

         AND "Deleted" = 0

		 AND "Inactive" = 0;



      IF vCount > 1 THEN

        UPDATE PTGUAR SET "IsPrimaryGuarantor" = 1, "IsSecondaryGuarantor" = 0

         WHERE "Patient" = vPatientGoodRec."Patient"

           AND "RespPatient" = (SELECT MAX("RespPatient") FROM PTGUAR WHERE 

		   "Patient" = vPatientGoodRec."Patient" AND "Deleted" = 0 AND "Inactive" = 0);



        UPDATE PTGUAR SET "IsPrimaryGuarantor" = 0, "IsSecondaryGuarantor" = 1

         WHERE "Patient" = vPatientGoodRec."Patient"

           AND "RespPatient" <> (SELECT MAX("RespPatient") FROM PTGUAR WHERE 

		   "Patient" = vPatientGoodRec."Patient" AND "Deleted" = 0 AND "Inactive" = 0);

      END IF;



      UPDATE ptletter SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      -- B31978

      -- Start B33339

      UPDATE ptlog a SET "Patient" = vPatientGoodRec."Patient"

       WHERE a."Patient" = vPatientBadRec."Patient"

         AND NOT EXISTS (SELECT 1 FROM ptlog b

                          WHERE b."Patient" = vPatientGoodRec."Patient"

                            AND b."Date" = a."Date"

                            AND b."User" = a."User"

                            AND b."StationId" = a."StationId"

                            AND b."ModuleID" = a."ModuleID");



      DELETE FROM ptlog WHERE "Patient" = vPatientBadRec."Patient";

      -- End B33339





      UPDATE ptmanage SET "Patient" = vPatientGoodRec."Patient"

       WHERE "Patient" = vPatientBadRec."Patient"

         AND "User" NOT IN (SELECT "User" FROM ptmanage WHERE "Patient" = vPatientGoodRec."Patient");



      DELETE FROM ptmanage WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE ptmanagh SET "Patient" = vPatientGoodRec."Patient"

       WHERE "Patient" = vPatientBadRec."Patient"

         AND "User" NOT IN (SELECT distinct "User" FROM ptmanagh WHERE "Patient" = vPatientGoodRec."Patient");



      DELETE FROM ptmanagh WHERE "Patient" = vPatientBadRec."Patient";



        -- B31978

      UPDATE ptneed SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE ptneehis SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      FOR rec IN (SELECT "PtNote" FROM ptnote WHERE "Patient" = vPatientBadRec."Patient") LOOP

        UPDATE ptnoteh SET "Patient" = vPatientGoodRec."Patient" WHERE "PtNote" = rec."PtNote";



        UPDATE ptnote SET "Patient" = vPatientGoodRec."Patient" WHERE "PtNote" = rec."PtNote";

      END LOOP;



      -- B23814

      UPDATE ptovrdue SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE ptovrext SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE ptperco SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE ptperhis SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE ptperio SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE ptperst SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE ptpsthis SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



		UPDATE ptphys SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient"; -- B137199

		UPDATE ptphysh SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient"; -- B137199



		-- B137199

		-- B138400

    BEGIN

      SELECT

        P."Patient"

      INTO

        vNewestPrevCarePatient

      FROM

        PTPREVH P,

        AUDITHIS A

      WHERE

        P."Audit" (+) = A."Audit"

      AND P."PtPrevH" =

        (

          SELECT

            NVL(MAX(P2."PtPrevH"), -1)

          FROM

            PTPREVH P2,

            AUDITHIS A2

          WHERE

            P2."Patient" IN (vPatientGoodRec."Patient", vPatientBadRec."Patient")

          AND P2."Audit"  = A2."Audit"

        );

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vNewestPrevCarePatient := 0;

    END;



		IF vNewestPrevCarePatient > 0 THEN  

			IF vNewestPrevCarePatient = vPatientGoodRec."Patient" THEN

				 vPrevCarePatient := vPatientBadRec."Patient";

			ELSE

				vPrevCarePatient := vPatientGoodRec."Patient";

			END IF;  

		

			DELETE FROM PTPREV WHERE "Patient" = vPrevCarePatient AND "Completed" = 0 AND "Deleted" = 0; 

    		DELETE FROM PTPREVH WHERE "Patient" = vPrevCarePatient AND "Completed" = 0 AND "Deleted" = 0;

			UPDATE PTPREV SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";

			Update Ptprevh Set "Patient" = Vpatientgoodrec."Patient" Where "Patient" = Vpatientbadrec."Patient";

		END IF;			  

 		



      UPDATE ptprod SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



		UPDATE ptprodh SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      FOR rec IN (SELECT "Id" FROM ptrecall WHERE "Patient" = vPatientBadRec."Patient") LOOP

        UPDATE ptrechis SET "Patient" = vPatientGoodRec."Patient" WHERE "Id" = rec."Id";



        UPDATE ptrecall SET "Patient" = vPatientGoodRec."Patient" WHERE "Id" = rec."Id";

      END LOOP;



      UPDATE ptrefer SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE ptrefhis SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";

      

      -- B143533

      DELETE FROM ptsumm WHERE "Patient" = vPatientBadRec."Patient" AND "SummCode" 

			IN (SELECT "SummCode" FROM ptsumm WHERE "Patient" = vPatientGoodRec."Patient");

		DELETE FROM ptsummh WHERE "Patient" = vPatientBadRec."Patient" AND "SummCode" 

			IN (SELECT "SummCode" FROM ptsummh WHERE "Patient" = vPatientGoodRec."Patient");	

      

      UPDATE ptsumm SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient"; -- B137199

      UPDATE ptsummh SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient"; -- B137199



      UPDATE pttypes SET "Patient" = vPatientGoodRec."Patient"

       WHERE "Patient" = vPatientBadRec."Patient"

         AND "PatType" NOT IN (SELECT "PatType" FROM pttypes WHERE "Patient" = vPatientGoodRec."Patient");



      DELETE FROM pttypes WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE pttyphis SET "Patient" = vPatientGoodRec."Patient"

       WHERE "Patient" = vPatientBadRec."Patient"

         AND "PatType" NOT IN (SELECT "PatType" FROM pttyphis WHERE "Patient" = vPatientGoodRec."Patient");



      DELETE FROM pttyphis WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE ptxray SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE ptxrahis SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE request SET "Patient" = vPatientGoodRec."Patient", "Chart" = vPatientGoodRec."Chart" WHERE "Chart" = vPatientBadRec."Chart";



      UPDATE resphis SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      SELECT COUNT(1)

        INTO vCount

        FROM user_tables

       WHERE table_name='SIGNATUR';



      IF vCount = 1 THEN

        vSql := 'UPDATE signatur SET "Patient" = :1 WHERE "Patient" = :2';

        EXECUTE IMMEDIATE vSql USING vPatientGoodRec."Patient", vPatientGoodRec."Patient";

      END IF;



      -- B31978

      UPDATE startchk SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE statemnt SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      UPDATE treatme2 SET "PId" = vPatient2GoodRec."Auto" WHERE "PId" = vPatient2Badrec."Auto";



      -- S33282

      Update trx set "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



      -- S33282

      Update trx set "Family" = vPatientGoodRec."Patient" WHERE "Family" = vPatientBadRec."Patient";



		-- B132297 added

		Handle_TRXType74Records (vPatientGoodRec."Patient");

		Handle_TRXType73Records (vPatientGoodRec."Patient");



      UPDATE trxmed SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



		--E78551.7

      UPDATE ptfund SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";

      

      --AX-28407.28652 added; AX-29370

      UPDATE online_request SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";

      



      -- AX-1113.2410 - start

      SELECT COUNT(1) INTO vCountPtRace FROM ptrace WHERE "Patient" = vPatientGood AND "Deleted" = 0;

      -- AX-1113.2410 - end

      

		-- AX-974.1059 - start

		vIsFirstInsert := true;  

      vIsFirstUpdate := true;  

			

      -- AX-1113.2410 - start

      IF vCountPtRace = 0 AND vPatientGoodRec."RaceEthDeclined" = 0 THEN

      -- AX-1113.2410 - end			

				for cPtRace in curPtRace(vPatientBad) loop

					if vIsFirstInsert then

						VISFIRSTINSERT := FALSE;

						select audithis_audit_seq.nextval into vInsertAudit from dual;

						insert into audithis values(

							vInsertAudit,

							trunc(sysdate),

							to_number ( to_char ( sysdate, 'HH24' ) ) * 60 + to_number ( to_char ( sysdate, 'MI' ) ),

							vUser,

							vStationId,

							'PTRACE',

							1

						);

					end if;

					begin

						insert into ptrace values (

							vPatientGoodRec."Patient",

							cPtRace."Race",

							cPtRace."Deleted",

							vInsertAudit

						) ;

					exception

						when dup_val_on_index then            

							if vIsFirstUpdate then

								VISFIRSTUPDATE := FALSE;

								select audithis_audit_seq.nextval into vUpdateAudit from dual;

								insert into audithis values(

									vUpdateAudit,

									trunc(sysdate),

									to_number ( to_char ( sysdate, 'HH24' ) ) * 60 + to_number ( to_char ( sysdate, 'MI' ) ),

									vUser,

									vStationId,

									'PTRACE',

									2

								);

							end if;

							update ptrace set 

								"Deleted" = 0, 

								"Audit" = vUpdateAudit 

							where 

								"Patient" = vPatientGood and 

								"Race" = cPtRace."Race" and 

								"Deleted" = 1;

							-- should not raise an exception if no data found

					end;

				END LOOP;			

				-- AX-974.1059 - end

      -- AX-1113.2410 - start

      END IF;

      -- AX-1113.2410 - end



      -- AX-1113.2527 now update BadPatient at PTRACE - start

			open curPtRace(vPatientBad);

			fetch curptrace into vCurPtRaceRowType;

			

			if curPtRace%FOUND then			 

        select audithis_audit_seq.nextval into vUpdateAudit from dual;

        insert into audithis("Audit","Date","Time","User","StationId","TableName","HistoryType")

                     values (vUpdateAudit,TRUNC(SYSDATE),TO_CHAR(SYSDATE,'SSSSS')/60,vUser,vStationId,'PTRACE',4);

			

        update ptrace set "Deleted" = 1, "Audit" = vUpdateAudit where "Patient" = vPatientBadRec."Patient";

			end if;

			close curPtRace;

      -- AX-1113.2527 now update BadPatient at PTRACE - end

		

      SELECT COUNT(1)

        INTO vCount

        FROM user_tables

       WHERE table_name='TXPNOTE';

      IF vCount = 1 THEN

        -- B31978 -- S33282

        vSql := 'UPDATE txpnohis SET "Patient" = :1 WHERE "Patient" = :2';

        EXECUTE IMMEDIATE vSql USING vPatientGoodRec."Patient", vPatientBadRec."Patient";



        vSql := 'UPDATE txpnote SET "Patient" = :1 WHERE "Patient" = :2';

        EXECUTE IMMEDIATE vSql USING vPatientGoodRec."Patient", vPatientBadRec."Patient";

      END IF;



      -- Update patient faulty

      FOR iModule IN 0..2 LOOP

      BEGIN

        SELECT COUNT(1)

          INTO vCount

          FROM PTFACUL P, CLASS C

         WHERE P."Discipline" = C."Class"

           AND C."Module" = iModule

             AND P."Patient" = vPatientGoodRec."Patient"

           AND P."Deleted" = 0

           AND P."IsPrimary" = 1;



        IF vCount > 0 THEN

        BEGIN

          SELECT COUNT(1)

            INTO vCount

            FROM PTFACUL P, CLASS C

           WHERE P."Discipline" = C."Class"

             AND C."Module" = iModule

             AND P."Patient" = vPatientBadRec."Patient"

             AND P."Deleted" = 0

             AND P."IsPrimary" = 1;



          IF vCount > 0 THEN

          BEGIN

            UPDATE PTFACUL P SET P."IsPrimary" = 0

             WHERE P."Patient" = vPatientBadRec."Patient"

               AND P."Discipline" IN (SELECT C."Class" FROM CLASS C WHERE C."Module" = iModule);



            UPDATE PTFACULH P SET P."IsPrimary" = 0

             WHERE P."Patient" = vPatientBadRec."Patient"

               AND P."Discipline" IN (SELECT C."Class" FROM CLASS C WHERE C."Module" = iModule);



                UPDATE PTFACUL P SET P."Patient" = vPatientGoodRec."Patient"

             WHERE P."Patient" = vPatientBadRec."Patient"

               AND P."Discipline" IN (SELECT C."Class" FROM CLASS C WHERE C."Module" = iModule);



                UPDATE PTFACULH P SET P."Patient" = vPatientGoodRec."Patient"

             WHERE P."Patient" = vPatientBadRec."Patient"

               AND P."Discipline" IN (SELECT C."Class" FROM CLASS C WHERE C."Module" = iModule);

          END;

          ELSE

              BEGIN

                  UPDATE PTFACUL P SET P."Patient" = vPatientGoodRec."Patient"

               WHERE P."Patient" = vPatientBadRec."Patient"

                 AND P."Discipline" IN (SELECT C."Class" FROM CLASS C WHERE C."Module" = iModule);



                  UPDATE PTFACULH P SET P."Patient" = vPatientGoodRec."Patient"

               WHERE P."Patient" = vPatientBadRec."Patient"

                 AND P."Discipline" IN (SELECT C."Class" FROM CLASS C WHERE C."Module" = iModule);

            END;

          END IF;

        END;

        ELSE

            BEGIN

              UPDATE PTFACUL P SET P."Patient" = vPatientGoodRec."Patient"

             WHERE P."Patient" = vPatientBadRec."Patient"

               AND P."Discipline" IN (SELECT C."Class" FROM CLASS C WHERE C."Module" = iModule);



              UPDATE PTFACULH P SET P."Patient" = vPatientGoodRec."Patient"

             WHERE P."Patient" = vPatientBadRec."Patient"

               AND P."Discipline" IN (SELECT C."Class" FROM CLASS C WHERE C."Module" = iModule);

          END;

        END IF;

      END;

      END LOOP;



      -- DELETE FROM patient2 WHERE "Auto" = vPatient2BadRec."Auto";



      -- update patient record; E60169 need to treat address as a whole, shouldn't copy bit   pieces...

      IF ((vPatientGoodRec."Address1" = ' ' OR vPatientGoodRec."Address1" IS NULL) AND	--B56196

          (vPatientGoodRec."Address2" = ' ' OR vPatientGoodRec."Address2" IS NULL) AND

          (vPatientGoodRec."AddressOther" = ' ' OR vPatientGoodRec."AddressOther" IS NULL) AND

      	  (vPatientGoodRec."City" = ' ' OR vPatientGoodRec."City" IS NULL) AND 	    

      	  (vPatientGoodRec."Province" = ' ' OR vPatientGoodRec."Province" IS NULL) AND

      	  (vPatientGoodRec."Postal" = ' ' OR vPatientGoodRec."Postal" IS NULL) AND

      	  (vPatientGoodRec."Country" = ' ' OR vPatientGoodRec."Country" IS NULL) ) 	    

      THEN

      		vPatientGoodRec."Address1" := vPatientBadRec."Address1";

      		vPatientGoodRec."Address2" := vPatientBadRec."Address2";

      		vPatientGoodRec."AddressOther" := vPatientBadRec."AddressOther";

      		vPatientGoodRec."City" := vPatientBadRec."City";

      		vPatientGoodRec."Province" := vPatientBadRec."Province";

      		vPatientGoodRec."Postal" := vPatientBadRec."Postal";

      		vPatientGoodRec."Country" := vPatientBadRec."Country";

      END IF;

      

      

      if ((vPatientGoodRec."HomeArea" = ' ' OR vPatientGoodRec."HomeArea" IS NULL) AND

          (vPatientGoodRec."HomePhone" = ' ' OR vPatientGoodRec."HomePhone" IS NULL) AND

		  (vPatientGoodRec."HomeExt" = ' ' OR vPatientGoodRec."HomeExt" IS NULL)) -- E60169

      THEN

      		vPatientGoodRec."HomeArea" := vPatientBadRec."HomeArea";

      		vPatientGoodRec."HomePhone" := vPatientBadRec."HomePhone";

      		vPatientGoodRec."HomeExt" := vPatientBadRec."HomeExt";				-- E60169

      END IF;

      

      IF ((vPatientGoodRec."WorkArea" = ' ' OR vPatientGoodRec."WorkArea" IS NULL) AND

          (vPatientGoodRec."WorkPhone" = ' ' OR vPatientGoodRec."WorkPhone" IS NULL) AND

		  (vPatientGoodRec."WorkExt" = ' ' OR vPatientGoodRec."WorkExt" IS NULL))

      THEN

      		vPatientGoodRec."WorkArea" := vPatientBadRec."WorkArea";

      		vPatientGoodRec."WorkPhone" := vPatientBadRec."WorkPhone";

      		vPatientGoodRec."WorkExt" := vPatientBadRec."WorkExt";

      END IF;

      

      IF (vPatientGoodRec."Birth" IS NULL)

      THEN

      		vPatientGoodRec."Birth" := vPatientBadRec."Birth";

      END IF;

      

      IF (vPatientBadRec."Sin" != ' ' AND vPatientBadRec."Sin" IS NOT NULL) AND

         (vPatientGoodRec."Sin" = ' ' OR vPatientGoodRec."Sin" IS NULL)

      THEN

          vPatientGoodRec."Sin" := vPatientBadRec."Sin";

      END IF;



      IF (vPatientBadRec."Office1" != ' ' AND vPatientBadRec."Office1" IS NOT NULL) AND

         (vPatientGoodRec."Office1" = ' ' OR vPatientGoodRec."Office1" IS NULL)

      THEN

          vPatientGoodRec."Office1" := vPatientBadRec."Office1";

      END IF;



      IF (vPatientBadRec."Office2" != ' ' AND vPatientBadRec."Office2" IS NOT NULL) AND

         (vPatientGoodRec."Office2" = ' ' OR vPatientGoodRec."Office2" IS NULL)

      THEN

          vPatientGoodRec."Office2" := vPatientBadRec."Office2";

      END IF;



      IF (vPatientBadRec."Office3" != ' ' AND vPatientBadRec."Office3" IS NOT NULL) AND

         (vPatientGoodRec."Office3" = ' ' OR vPatientGoodRec."Office3" IS NULL)

      THEN

          vPatientGoodRec."Office3" := vPatientBadRec."Office3";

      END IF;



      IF (vPatientBadRec."Office4" != ' ' AND vPatientBadRec."Office4" IS NOT NULL) AND

         (vPatientGoodRec."Office4" = ' ' OR vPatientGoodRec."Office4" IS NULL)

      THEN

          vPatientGoodRec."Office4" := vPatientBadRec."Office4";

      END IF;



      IF (vPatientBadRec."Office5" != ' ' AND vPatientBadRec."Office5" IS NOT NULL) AND

         (vPatientGoodRec."Office5" = ' ' OR vPatientGoodRec."Office5" IS NULL)

      THEN

          vPatientGoodRec."Office5" := vPatientBadRec."Office5";

      END IF;



      IF (vPatientBadRec."Alert1" != ' ' AND vPatientBadRec."Alert1" IS NOT NULL) AND

         (vPatientGoodRec."Alert1" = ' ' OR vPatientGoodRec."Alert1" IS NULL)

      THEN

          vPatientGoodRec."Alert1" := vPatientBadRec."Alert1";

      END IF;



      IF (vPatientBadRec."Alert2" != ' ' AND vPatientBadRec."Alert2" IS NOT NULL) AND

         (vPatientGoodRec."Alert2" = ' ' OR vPatientGoodRec."Alert2" IS NULL)

      THEN

          vPatientGoodRec."Alert2" := vPatientBadRec."Alert2";

      END IF;



      IF (vPatientBadRec."Alert3" != ' ' AND vPatientBadRec."Alert3" IS NOT NULL) AND

         (vPatientGoodRec."Alert3" = ' ' OR vPatientGoodRec."Alert3" IS NULL)

      THEN

          vPatientGoodRec."Alert3" := vPatientBadRec."Alert3";

      END IF;



      IF (vPatientBadRec."Alert4" != ' ' AND vPatientBadRec."Alert4" IS NOT NULL) AND

         (vPatientGoodRec."Alert4" = ' ' OR vPatientGoodRec."Alert4" IS NULL)

      THEN

          vPatientGoodRec."Alert4" := vPatientBadRec."Alert4";

      END IF;



      IF (vPatientBadRec."Alert5" != ' ' AND vPatientBadRec."Alert5" IS NOT NULL) AND

         (vPatientGoodRec."Alert5" = ' ' OR vPatientGoodRec."Alert5" IS NULL)

      THEN

          vPatientGoodRec."Alert5" := vPatientBadRec."Alert5";

      END IF;



      IF (vPatientBadRec."CustomCode1" != ' ' AND vPatientBadRec."CustomCode1" IS NOT NULL) AND

         (vPatientGoodRec."CustomCode1" = ' ' OR vPatientGoodRec."CustomCode1" IS NULL)

      THEN

          vPatientGoodRec."CustomCode1" := vPatientBadRec."CustomCode1";

      END IF;



      IF (vPatientBadRec."CustomCode2" != ' ' AND vPatientBadRec."CustomCode2" IS NOT NULL) AND

         (vPatientGoodRec."CustomCode2" = ' ' OR vPatientGoodRec."CustomCode2" IS NULL)

      THEN

          vPatientGoodRec."CustomCode2" := vPatientBadRec."CustomCode2";

      END IF;



      IF (vPatientBadRec."CustomCode3" != ' ' AND vPatientBadRec."CustomCode3" IS NOT NULL) AND

         (vPatientGoodRec."CustomCode3" = ' ' OR vPatientGoodRec."CustomCode3" IS NULL)

      THEN

          vPatientGoodRec."CustomCode3" := vPatientBadRec."CustomCode3";

      END IF;



      IF (vPatientBadRec."CustomCode4" != ' ' AND vPatientBadRec."CustomCode4" IS NOT NULL) AND

         (vPatientGoodRec."CustomCode4" = ' ' OR vPatientGoodRec."CustomCode4" IS NULL)

      THEN

          vPatientGoodRec."CustomCode4" := vPatientBadRec."CustomCode4";

      END IF;



      IF (vPatientBadRec."CustomCode5" != ' ' AND vPatientBadRec."CustomCode5" IS NOT NULL) AND

         (vPatientGoodRec."CustomCode5" = ' ' OR vPatientGoodRec."CustomCode5" IS NULL)

      THEN

          vPatientGoodRec."CustomCode5" := vPatientBadRec."CustomCode5";

      END IF;



      IF (vPatientBadRec."CustomCode6" != ' ' AND vPatientBadRec."CustomCode6" IS NOT NULL) AND

         (vPatientGoodRec."CustomCode6" = ' ' OR vPatientGoodRec."CustomCode6" IS NULL)

      THEN

        vPatientGoodRec."CustomCode6" := vPatientBadRec."CustomCode6";

      END IF;



      IF (vPatientBadRec."CustomCode7" != ' ' AND vPatientBadRec."CustomCode7" IS NOT NULL) AND

         (vPatientGoodRec."CustomCode7" = ' ' OR vPatientGoodRec."CustomCode7" IS NULL)

      THEN

          vPatientGoodRec."CustomCode7" := vPatientBadRec."CustomCode7";

      END IF;



      IF (vPatientBadRec."CustomCode8" != ' ' AND vPatientBadRec."CustomCode8" IS NOT NULL) AND

         (vPatientGoodRec."CustomCode8" = ' ' OR vPatientGoodRec."CustomCode8" IS NULL)

      THEN

          vPatientGoodRec."CustomCode8" := vPatientBadRec."CustomCode8";

      END IF;



      IF (vPatientBadRec."CustomCode9" != ' ' AND vPatientBadRec."CustomCode9" IS NOT NULL) AND

         (vPatientGoodRec."CustomCode9" = ' ' OR vPatientGoodRec."CustomCode9" IS NULL)

      THEN

        vPatientGoodRec."CustomCode9" := vPatientBadRec."CustomCode9";

      END IF;



      IF (vPatientBadRec."CustomCode10" != ' ' AND vPatientBadRec."CustomCode10" IS NOT NULL) AND

         (vPatientGoodRec."CustomCode10" = ' ' OR vPatientGoodRec."CustomCode10" IS NULL)

      THEN

        vPatientGoodRec."CustomCode10" := vPatientBadRec."CustomCode10";

      END IF;



        -- If the old chart has ortho information copy it over

      IF vPatientBadRec."IsOrtho" = 1 AND vPatientGoodRec."IsOrtho" = 0

      THEN

        vPatientGoodRec."IsOrtho" := 1;

        vPatientGoodRec."OrthoSet" := vPatientBadRec."OrthoSet";

      END IF;



        -- Compare dates and SET the good chart appropriately; E60169.2 added IS NULL clause to all date fields

      IF vPatientGoodRec."FirstTreatment" IS NULL OR vPatientBadRec."FirstTreatment" < vPatientGoodRec."FirstTreatment"

      THEN

        vPatientGoodRec."FirstTreatment" := vPatientBadRec."FirstTreatment";

      END IF;



      IF vPatientGoodRec."LastClaimDate" IS NULL OR vPatientBadRec."LastClaimDate" > vPatientGoodRec."LastClaimDate"

      THEN

        vPatientGoodRec."LastClaimDate" := vPatientBadRec."LastClaimDate";

        vPatientGoodRec."LastClaimAmount" := vPatientBadRec."LastClaimAmount";

      END IF;



      IF vPatientGoodRec."LastVisit" IS NULL OR vPatientBadRec."LastVisit" > vPatientGoodRec."LastVisit"

      THEN

        vPatientGoodRec."LastVisit" := vPatientBadRec."LastVisit";

      END IF;



      IF vPatientGoodRec."LastStatementDate" IS NULL OR vPatientBadRec."LastStatementDate" > vPatientGoodRec."LastStatementDate"

      THEN

        vPatientGoodRec."LastStatementDate" := vPatientBadRec."LastStatementDate";

        vPatientGoodRec."LastStatementAmount" := vPatientBadRec."LastStatementAmount";

      END IF;



      IF vPatientGoodRec."LastPmtDate" IS NULL OR vPatientBadRec."LastPmtDate" > vPatientGoodRec."LastPmtDate"

      THEN

        vPatientGoodRec."LastPmtDate" := vPatientBadRec."LastPmtDate";

        vPatientGoodRec."LastPaymentAmount" := vPatientBadRec."LastPaymentAmount";

      END IF;



      IF vPatientBadRec."XRayReceived" = 1 AND vPatientGoodRec."XRayReceived" = 0

      THEN

        vPatientGoodRec."XRayReceived" := 1;

        vPatientGoodRec."DateXRayReceived" := vPatientBadRec."DateXRayReceived";

      END IF;



      -- B2329

      vPatientGoodRec."XRayExposures" := vPatientBadRec."XRayExposures" + vPatientGoodRec."XRayExposures";



      -- E0002.4

      vPatientGoodRec."MergedChart" := vPatientBadRec."Chart";

	

	       

	  -- E60169.2      

      IF vPatientBadRec."Marital" > 0 AND vPatientGoodRec."Marital" = 0

      THEN

        vPatientGoodRec."Marital" := vPatientBadRec."Marital";

      END IF;

      

      -- E60169 need to check   copy other fields as well

      IF vPatientBadRec."Sex" > 0 AND vPatientGoodRec."Sex" = 0

      THEN

        vPatientGoodRec."Sex" := vPatientBadRec."Sex";

      END IF;



      if ((vPatientGoodRec."OtherArea" = ' ' OR vPatientGoodRec."OtherArea" IS NULL) AND

          (vPatientGoodRec."OtherPhone" = ' ' OR vPatientGoodRec."OtherPhone" IS NULL) AND

		  (vPatientGoodRec."OtherExt" = ' ' OR vPatientGoodRec."OtherExt" IS NULL)) 

      THEN

      		vPatientGoodRec."OtherArea" := vPatientBadRec."OtherArea";

      		vPatientGoodRec."OtherPhone" := vPatientBadRec."OtherPhone";

      		vPatientGoodRec."OtherExt" := vPatientBadRec."OtherExt";				

      END IF;

      

      IF (vPatientBadRec."OtherLocation" != ' ' AND vPatientBadRec."OtherLocation" IS NOT NULL) AND

         (vPatientGoodRec."OtherLocation" = ' ' OR vPatientGoodRec."OtherLocation" IS NULL)

      THEN

          vPatientGoodRec."OtherLocation" := vPatientBadRec."OtherLocation";

      END IF;



      IF (vPatientBadRec."ContactTime" != ' ' AND vPatientBadRec."ContactTime" IS NOT NULL) AND

         (vPatientGoodRec."ContactTime" = ' ' OR vPatientGoodRec."ContactTime" IS NULL)

      THEN

          vPatientGoodRec."ContactTime" := vPatientBadRec."ContactTime";

      END IF;



      IF (vPatientBadRec."School" != ' ' AND vPatientBadRec."School" IS NOT NULL) AND

         (vPatientGoodRec."School" = ' ' OR vPatientGoodRec."School" IS NULL)

      THEN

          vPatientGoodRec."School" := vPatientBadRec."School";

      END IF;



      IF (vPatientBadRec."Health" != ' ' AND vPatientBadRec."Health" IS NOT NULL) AND

         (vPatientGoodRec."Health" = ' ' OR vPatientGoodRec."Health" IS NULL)

      THEN

          vPatientGoodRec."Health" := vPatientBadRec."Health";

      END IF;



      IF (vPatientBadRec."AccountStatus" != ' ' AND vPatientBadRec."AccountStatus" IS NOT NULL) AND

         (vPatientGoodRec."AccountStatus" = ' ' OR vPatientGoodRec."AccountStatus" IS NULL)

      THEN

          vPatientGoodRec."AccountStatus" := vPatientBadRec."AccountStatus";

      END IF;



      IF (vPatientBadRec."Fee" != ' ' AND vPatientBadRec."Fee" IS NOT NULL) AND

         (vPatientGoodRec."Fee" = ' ' OR vPatientGoodRec."Fee" IS NULL)

      THEN

          vPatientGoodRec."Fee" := vPatientBadRec."Fee";

          vPatientGoodRec."FeeOverride" := vPatientBadRec."FeeOverride";		-- E60169.2

      END IF;



      IF vPatientBadRec."Physician" > 0 AND vPatientGoodRec."Physician" = 0

      THEN

        vPatientGoodRec."Physician" := vPatientBadRec."Physician";

      END IF;

      

      IF ((vPatientGoodRec."EmergLast" = ' ' OR vPatientGoodRec."EmergLast" IS NULL) AND	

          (vPatientGoodRec."EmergFirst" = ' ' OR vPatientGoodRec."EmergFirst" IS NULL) AND

          (vPatientGoodRec."EmergMiddle" = ' ' OR vPatientGoodRec."EmergMiddle" IS NULL) ) 	    

      THEN

      		vPatientGoodRec."EmergLast" := vPatientBadRec."EmergLast";

      		vPatientGoodRec."EmergFirst" := vPatientBadRec."EmergFirst";

      		vPatientGoodRec."EmergMiddle" := vPatientBadRec."EmergMiddle";

      END IF;

      

      IF (vPatientBadRec."EmergRelation" != ' ' AND vPatientBadRec."EmergRelation" IS NOT NULL) AND

         (vPatientGoodRec."EmergRelation" = ' ' OR vPatientGoodRec."EmergRelation" IS NULL)

      THEN

          vPatientGoodRec."EmergRelation" := vPatientBadRec."EmergRelation";

      END IF;



      IF ((vPatientGoodRec."EmergAddress" = ' ' OR vPatientGoodRec."EmergAddress" IS NULL) AND	

          (vPatientGoodRec."EmergAddress2" = ' ' OR vPatientGoodRec."EmergAddress2" IS NULL) AND

          (vPatientGoodRec."EmergAddressOther" = ' ' OR vPatientGoodRec."EmergAddressOther" IS NULL) AND

      	  (vPatientGoodRec."EmergCity" = ' ' OR vPatientGoodRec."EmergCity" IS NULL) AND 	    

      	  (vPatientGoodRec."EmergProvince" = ' ' OR vPatientGoodRec."EmergProvince" IS NULL) AND

      	  (vPatientGoodRec."EmergPostal" = ' ' OR vPatientGoodRec."EmergPostal" IS NULL) ) 	    

      THEN

      		vPatientGoodRec."EmergAddress" := vPatientBadRec."EmergAddress";

      		vPatientGoodRec."EmergAddress2" := vPatientBadRec."EmergAddress2";

      		vPatientGoodRec."EmergAddressOther" := vPatientBadRec."EmergAddressOther";

      		vPatientGoodRec."EmergCity" := vPatientBadRec."EmergCity";

      		vPatientGoodRec."EmergProvince" := vPatientBadRec."EmergProvince";

      		vPatientGoodRec."EmergPostal" := vPatientBadRec."EmergPostal";

      END IF;

      

      

      if ((vPatientGoodRec."EmergArea" = ' ' OR vPatientGoodRec."EmergArea" IS NULL) AND

          (vPatientGoodRec."EmergPhone" = ' ' OR vPatientGoodRec."EmergPhone" IS NULL) AND

		  (vPatientGoodRec."EmergExt" = ' ' OR vPatientGoodRec."EmergExt" IS NULL)) 

      THEN

      		vPatientGoodRec."EmergArea" := vPatientBadRec."EmergArea";

      		vPatientGoodRec."EmergPhone" := vPatientBadRec."EmergPhone";

      		vPatientGoodRec."EmergExt" := vPatientBadRec."EmergExt";				

      END IF;

      

      if ((vPatientGoodRec."EmergAltArea" = ' ' OR vPatientGoodRec."EmergAltArea" IS NULL) AND

          (vPatientGoodRec."EmergAltPhone" = ' ' OR vPatientGoodRec."EmergAltPhone" IS NULL) AND

		  (vPatientGoodRec."EmergAltExt" = ' ' OR vPatientGoodRec."EmergAltExt" IS NULL)) 

      THEN

      		vPatientGoodRec."EmergAltArea" := vPatientBadRec."EmergAltArea";

      		vPatientGoodRec."EmergAltPhone" := vPatientBadRec."EmergAltPhone";

      		vPatientGoodRec."EmergAltExt" := vPatientBadRec."EmergAltExt";				

      END IF;

     

      IF (vPatientBadRec."AltChart" != ' ' AND vPatientBadRec."AltChart" IS NOT NULL) AND

         (vPatientGoodRec."AltChart" = ' ' OR vPatientGoodRec."AltChart" IS NULL)

      THEN

          vPatientGoodRec."AltChart" := vPatientBadRec."AltChart";

      END IF;

      

      IF (vPatientBadRec."BankAccount" != ' ' AND vPatientBadRec."BankAccount" IS NOT NULL) AND

         (vPatientGoodRec."BankAccount" = ' ' OR vPatientGoodRec."BankAccount" IS NULL)

      THEN

          vPatientGoodRec."BankAccount" := vPatientBadRec."BankAccount";

      END IF;

      

      IF (vPatientBadRec."BoxNumber" != ' ' AND vPatientBadRec."BoxNumber" IS NOT NULL) AND

         (vPatientGoodRec."BoxNumber" = ' ' OR vPatientGoodRec."BoxNumber" IS NULL)

      THEN

          vPatientGoodRec."BoxNumber" := vPatientBadRec."BoxNumber";

      END IF;

      

      IF (vPatientBadRec."Email" != ' ' AND vPatientBadRec."Email" IS NOT NULL) AND

         (vPatientGoodRec."Email" = ' ' OR vPatientGoodRec."Email" IS NULL)

      THEN

          vPatientGoodRec."Email" := vPatientBadRec."Email";

      END IF;

      

      IF (vPatientBadRec."PrefApptTime" != ' ' AND vPatientBadRec."PrefApptTime" IS NOT NULL) AND

         (vPatientGoodRec."PrefApptTime" = ' ' OR vPatientGoodRec."PrefApptTime" IS NULL)

      THEN

          vPatientGoodRec."PrefApptTime" := vPatientBadRec."PrefApptTime";

      END IF;

      

      IF (vPatientBadRec."DiscGrp" != ' ' AND vPatientBadRec."DiscGrp" IS NOT NULL) AND

         (vPatientGoodRec."DiscGrp" = ' ' OR vPatientGoodRec."DiscGrp" IS NULL)

      THEN

          vPatientGoodRec."DiscGrp" := vPatientBadRec."DiscGrp";

      END IF;



		-- E99403      

      if ((vPatientGoodRec."MobileArea" = ' ' OR vPatientGoodRec."MobileArea" IS NULL) AND

          (vPatientGoodRec."MobilePhone" = ' ' OR vPatientGoodRec."MobilePhone" IS NULL) )

      THEN

      		vPatientGoodRec."MobileArea" := vPatientBadRec."MobileArea";

      		vPatientGoodRec."MobilePhone" := vPatientBadRec."MobilePhone";

      END IF;

      

      -- E135945

      IF (vPatientBadRec."PrefLanguage" != ' ' AND vPatientBadRec."PrefLanguage" IS NOT NULL) AND

         (vPatientGoodRec."PrefLanguage" = ' ' OR vPatientGoodRec."PrefLanguage" IS NULL)

      THEN

          vPatientGoodRec."PrefLanguage" := vPatientBadRec."PrefLanguage";

      END IF;

            

      -- E135943 -- AX-1113.2410 check for vCountPtRace 

      IF vPatientBadRec."RaceEthDeclined" > 0 AND vPatientGoodRec."RaceEthDeclined" = 0 AND vCountPtRace = 0

      THEN

        vPatientGoodRec."RaceEthDeclined" := vPatientBadRec."RaceEthDeclined";

      END IF;



      -- E135943 -- AX-1113.2547

			IF vPatientGoodRec."RaceEthDeclined" = 1 

			THEN

          vPatientGoodRec."Ethnic" := NULL;

      ELSIF (vPatientBadRec."Ethnic" != ' ' AND vPatientBadRec."Ethnic" IS NOT NULL) AND

         (vPatientGoodRec."Ethnic" = ' ' OR vPatientGoodRec."Ethnic" IS NULL)

      THEN

          vPatientGoodRec."Ethnic" := vPatientBadRec."Ethnic";

      END IF;

			

		-- E104564

      IF vPatientBadRec."ApptFeesExempt" > 0 AND vPatientGoodRec."ApptFeesExempt" = 0

      THEN

        vPatientGoodRec."ApptFeesExempt" := vPatientBadRec."ApptFeesExempt";

      END IF;

            

      vPatientGoodRec."Deleted" := 0;



      SELECT audithis_audit_seq.NEXTVAL INTO vPatientGoodRec."Audit" FROM dual;

      INSERT INTO audithis("Audit","Date","Time","User","StationId","TableName","HistoryType")

      VALUES (vPatientGoodRec."Audit",TRUNC(SYSDATE),TO_CHAR(SYSDATE,'SSSSS')/60,vUser,vStationId,'PATIENT',2);



      UPDATE patient SET

        "Audit" = vPatientGoodRec."Audit",

      	"Address1" = vPatientGoodRec."Address1",

      	"Address2" = vPatientGoodRec."Address2",

      	"AddressOther" = vPatientGoodRec."AddressOther",						-- E60169	

      	"City"     = vPatientGoodRec."City",

      	"Province" = vPatientGoodRec."Province",

      	"Postal"   = vPatientGoodRec."Postal",

      	"Country"  = vPatientGoodRec."Country",									-- E60169

      	"HomeArea" = vPatientGoodRec."HomeArea",

      	"HomePhone" = vPatientGoodRec."HomePhone",

      	"HomeExt" = vPatientGoodRec."HomeExt",									-- E60169

      	"WorkArea"  = vPatientGoodRec."WorkArea",

      	"WorkPhone" = vPatientGoodRec."WorkPhone",

      	"WorkExt"  = vPatientGoodRec."WorkExt",

      	"OtherArea" = vPatientGoodRec."OtherArea",								-- E60169							

      	"OtherPhone" = vPatientGoodRec."OtherPhone",							-- E60169

      	"OtherExt" = vPatientGoodRec."OtherExt",								-- E60169

      	"OtherLocation" = vPatientGoodRec."OtherLocation",						-- E60169

      	"ContactTime" = vPatientGoodRec."ContactTime",							-- E60169

      	"Birth"    = vPatientGoodRec."Birth",

      	"Sex"    = vPatientGoodRec."Sex",										-- E60169

        "Sin" = vPatientGoodRec."Sin",

      	"AltChart"    = vPatientGoodRec."AltChart",								-- E60169

        "Office1" = vPatientGoodRec."Office1",

        "Office2" = vPatientGoodRec."Office2",

        "Office3" = vPatientGoodRec."Office3",

        "Office4" = vPatientGoodRec."Office4",

        "Office5" = vPatientGoodRec."Office5",

        "Alert1" = vPatientGoodRec."Alert1",

        "Alert2" = vPatientGoodRec."Alert2",

        "Alert3" = vPatientGoodRec."Alert3",

        "Alert4" = vPatientGoodRec."Alert4",

        "Alert5" = vPatientGoodRec."Alert5",

        "CustomCode1" = vPatientGoodRec."CustomCode1",

        "CustomCode2" = vPatientGoodRec."CustomCode2",

        "CustomCode3" = vPatientGoodRec."CustomCode3",

        "CustomCode4" = vPatientGoodRec."CustomCode4",

        "CustomCode5" = vPatientGoodRec."CustomCode5",

        "CustomCode6" = vPatientGoodRec."CustomCode6",

        "CustomCode7" = vPatientGoodRec."CustomCode7",

        "CustomCode8" = vPatientGoodRec."CustomCode8",

        "CustomCode9" = vPatientGoodRec."CustomCode9",

        "CustomCode10" = vPatientGoodRec."CustomCode10",

        "IsOrtho" = vPatientGoodRec."IsOrtho",

        "OrthoSet" = vPatientGoodRec."OrthoSet",

        "Marital" = vPatientGoodRec."Marital",									--E60169.2

        "School" = vPatientGoodRec."School",									--E60169

        "Health" = vPatientGoodRec."Health",									--E60169

        "Fee" = vPatientGoodRec."Fee",											--E60169

        "FeeOverride" = vPatientGoodRec."FeeOverride",							--E60169.2

        "Physician" = vPatientGoodRec."Physician",								--E60169

        "AccountStatus" = vPatientGoodRec."AccountStatus",						--E60169

       	"EmergLast" = vPatientGoodRec."EmergLast",								--E60169		

       	"EmergFirst" = vPatientGoodRec."EmergFirst",							--E60169		

       	"EmergMiddle" = vPatientGoodRec."EmergMiddle",							--E60169		

       	"EmergRelation" = vPatientGoodRec."EmergRelation",						--E60169		

       	"EmergAddress" = vPatientGoodRec."EmergAddress",						--E60169		

      	"EmergAddress2" = vPatientGoodRec."EmergAddress2",						--E60169		

      	"EmergAddressOther" = vPatientGoodRec."EmergAddressOther",				--E60169		

      	"EmergCity"     = vPatientGoodRec."EmergCity",							--E60169		

      	"EmergProvince" = vPatientGoodRec."EmergProvince",						--E60169			

      	"EmergPostal"   = vPatientGoodRec."EmergPostal",						--E60169		

      	"EmergArea"   = vPatientGoodRec."EmergArea",							--E60169		

      	"EmergPhone"   = vPatientGoodRec."EmergPhone",							--E60169		

      	"EmergExt"   = vPatientGoodRec."EmergExt",								--E60169		

      	"EmergAltArea"   = vPatientGoodRec."EmergAltArea",						--E60169		

      	"EmergAltPhone"   = vPatientGoodRec."EmergAltPhone",					--E60169		

      	"EmergAltExt"   = vPatientGoodRec."EmergAltExt",						--E60169		

      	"BankAccount"   = vPatientGoodRec."BankAccount",						--E60169		

      	"BoxNumber"   = vPatientGoodRec."BoxNumber",							--E60169		

      	"Email"   = vPatientGoodRec."Email",									--E60169		

      	"PrefApptTime"   = vPatientGoodRec."PrefApptTime",						--E60169		

      	"DiscGrp"   = vPatientGoodRec."DiscGrp",								--E60169		

        "FirstTreatment" = vPatientGoodRec."FirstTreatment",

        "LastClaimDate" = vPatientGoodRec."LastClaimDate",

        "LastClaimAmount" = vPatientGoodRec."LastClaimAmount",

        "LastVisit" = vPatientGoodRec."LastVisit",

        "LastStatementDate" = vPatientGoodRec."LastStatementDate",

        "LastStatementAmount" = vPatientGoodRec."LastStatementAmount",

        "LastPmtDate" = vPatientGoodRec."LastPmtDate",

        "LastPaymentAmount" = vPatientGoodRec."LastPaymentAmount",

        "XRayReceived" = vPatientGoodRec."XRayReceived",

        "DateXRayReceived" = vPatientGoodRec."DateXRayReceived",

        "XRayExposures" = vPatientGoodRec."XRayExposures",

        "MergedChart" = vPatientGoodRec."MergedChart",

        "Deleted" = vPatientGoodRec."Deleted",

        "MobileArea" = vPatientGoodRec."MobileArea",							-- E99403

        "MobilePhone" = vPatientGoodRec."MobilePhone",							-- E99403

        "PrefLanguage" = vPatientGoodRec."PrefLanguage",							-- E135945

        "RaceEthDeclined" = vPatientGoodRec."RaceEthDeclined",					-- E135943

        "Ethnic" = vPatientGoodRec."Ethnic"											-- E135943

      WHERE

        "Patient" = vPatientGoodRec."Patient";



      UPDATE VKCLAIM SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient"; -- AX-1736

      UPDATE PINVOICE SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient"; -- AX-1275

		UPDATE PINVOICH SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient"; -- AX-20714

		UPDATE PTRCGRP SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient"; -- AX-20714

		UPDATE PTRCGRPH SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient"; -- AX-20714



       -- now update BadPatient

      SELECT audithis_audit_seq.NEXTVAL INTO vPatientBadRec."Audit" FROM dual;

      INSERT INTO audithis("Audit","Date","Time","User","StationId","TableName","HistoryType")

      VALUES (vPatientBadRec."Audit",TRUNC(SYSDATE),TO_CHAR(SYSDATE,'SSSSS')/60,vUser,vStationId,'PATIENT',4);		-- B138439



      UPDATE patient SET "Deleted" = 1, "Audit" = vPatientBadRec."Audit" WHERE "Patient" = vPatientBadRec."Patient";

      

	  -- AX-13666 Jun 15, 16	co	OS3: Support new patient Case data in other areas

      -- add Oral Surgery stuff...

      UPDATE PTCASE SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";

      UPDATE PTCASEH SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



	  --AX-21098.21140c

      UPDATE PTIMPLNT SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";

      UPDATE PTIMPLNH SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";



	  --AX-26333.27197

	  FOR iEventType IN 0..3 LOOP

      BEGIN

		IF ( iEventType <> 2 ) THEN

		BEGIN

			SELECT COUNT(1)

			INTO vCount

			FROM CAREQUALITY_EVENT

			WHERE "Patient" = vPatientGoodRec."Patient"

			AND "EventType" = iEventType;

	

			IF vCount > 0 THEN

			BEGIN

				DELETE FROM CAREQUALITY_EVENT WHERE "Patient" = vPatientBadRec."Patient" AND "EventType" = iEventType;

			END;

			ELSE

			BEGIN

				UPDATE CAREQUALITY_EVENT SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient" AND "EventType" = iEventType;

			END;

			END IF;

		END;

		ELSE

		BEGIN

			DELETE

			FROM CAREQUALITY_EVENT

			WHERE "Patient" = vPatientBadRec."Patient"

			AND "EventType" = iEventType

			AND "OtherId" IN (SELECT "OtherId"

								FROM CAREQUALITY_EVENT

								WHERE "Patient" = vPatientGoodRec."Patient"

								AND "EventType" = iEventType);

	

			

			UPDATE CAREQUALITY_EVENT SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient" AND "EventType" = iEventType;

		END;

		END IF;

      END;

      END LOOP;



      UPDATE CAREQUALITY_EVENTHIS SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";

      UPDATE CAREQUALITY_DOCUMENTS SET "Patient" = vPatientGoodRec."Patient" WHERE "Patient" = vPatientBadRec."Patient";

	  

	  IF ( CAREQUALITY_PKG.GET_CAREQUALITY_STATUS() <> 0 ) THEN

		BEGIN

			INSERT INTO CAREQUALITY_EVENT("Patient","EventType","EventDate","Status","OtherId") 

			VALUES (vPatientGoodRec."Patient",2,SYSDATE,0,vPatientBadRec."Patient");

		END;

	  END IF;



        -- remove BadPatient FROM selected list

      DELETE FROM selected WHERE "Patient" = vPatientBadRec."Patient";



      <<end_of_process>>

      IF vSuccess != 0 THEN

        ROLLBACK;

      ELSE

        NULL;

        COMMIT;

      END IF;

    EXCEPTION WHEN OTHERS THEN

      ROLLBACK;

      vSuccess := 4;

    END ChartMerge;









    /**************************************************************************/

    PROCEDURE chartmergea(IN vchartbad character, IN vchartgood character, IN vuser numeric, IN vstationid numeric, OUT vsuccess numeric) IS

      vPatientBad PATIENT."Patient"%TYPE;

      vPatientGood PATIENT."Patient"%TYPE;

    BEGIN

      vSuccess := 0;



      SELECT "Patient"

        INTO vPatientBad

        FROM patient

       WHERE "Chart" = vChartBad;



      SELECT "Patient"

        INTO vPatientGood

        FROM patient

       WHERE "Chart" = vChartGood;



      ChartMerge(vPatientBad, vPatientGood, vUser, vStationId, vSuccess);



    EXCEPTION WHEN NO_DATA_FOUND THEN

      vSuccess := 1;

    END;







    /**************************************************************************/

    PROCEDURE merge_epr(IN oldpatientid numeric, IN newpatientid numeric, IN oldiuserid numeric, IN newiuserid numeric, OUT success numeric) IS

	   CURSOR pforms_csr (pOldPatientId NUMBER)

	   IS

		  SELECT P.*, F."Multiple"

			FROM PFORM P, FORM F

		   WHERE P."Patient" = pOldPatientId

			 AND P."FormCode" = F."Code";



       -- assumes FORM.Multiple = 0

	   CURSOR ppages_csr (pOldPatientId NUMBER, pNewPatientId NUMBER, pFormCode CHAR(6))		--AX-41129	

	   IS

		  SELECT   P.ctid , P."Patient", P."FItem", P."FormCode", P."PForm", P."Date",

				   P."AuditNumber"

			  FROM PPAGE P

			 WHERE P."Patient" IN (pOldPatientId, pNewPatientId)

			   AND P."FormCode" = pFormCode

		  ORDER BY P."FItem", NVL(P."Date", TO_DATE('01-01-1901', 'DD-MM-YYYY')) ASC, P."AuditNumber" ASC;



       -- assumes FORM.Multiple = 0

       -- E41114 - suppress spreadsheet rows, which will be handled in another loop, B134334

	   CURSOR pitems_csr (pOldPatientId IN NUMBER, pNewPatientId NUMBER, pFormCode CHAR(6))		--AX-41129

	   IS

		  SELECT   P."PItem", P."Patient", P."FItem", P."FormCode", P."PForm", P."Date",

				   P."AuditNumber", P."AnsType", P."Status", P."AppUser", P."AppDate"

			  FROM PITEM P

			 WHERE P."Patient" IN (pOldPatientId, pNewPatientId)

			   AND P."FormCode" = pFormCode 

			   AND P."PItemCol" = 0

		  ORDER BY P."FItem", NVL(P."Date", TO_DATE('01-01-1901', 'DD-MM-YYYY')) ASC, P."PItem" ASC;



	   vConflicting       BOOLEAN;

	   vNewPFormRec       PFORM%ROWTYPE;									-- B134334

	   vLastAppUser		 NUMBER(10);										-- B134334

	   vLastAppDate		 DATE;												-- B134334

	   vCurrentFItem      NUMBER (10);

	   vSeq               NUMBER (5);

	   vStatus            NUMBER (1);

	   vCount             NUMBER (5);

	   vCount2	      NUMBER (5);	-- B142347.2

	   viOUserId		  NUMBER (10);											--E37209.3.4	

	   viNUserId		  NUMBER (10);											--E37209.3.4	

	   

	BEGIN

	

	--E37209.3.4 added to set user id to update

		viOUserId := -1;

		viNUserId := -1;

		IF NewiUserId <> 0 AND OldiUserId <> 0 THEN

			viOUserId := OldiUserId;

			viNUserId := NewiUserId;

		END IF;

		

	   -- Loop through all PFORMs for the old patient

	   FOR pform_rec IN pforms_csr (OldPatientId)

	   LOOP



          vConflicting := FALSE;

          

          -- multiple type forms are never conflicting, just change the patient

          -- not conflicting if the form has not been answered by the new patient as well

          IF pform_rec."Multiple" = 0 THEN

          

            -- see if the new patient has the same form, B134334

		    BEGIN

              SELECT *

                INTO vNewPFormRec

                FROM PFORM

               WHERE "Patient" = NewPatientId

                 AND "FormCode" = pform_rec."FormCode";

		    EXCEPTION

				WHEN NO_DATA_FOUND THEN

				   vNewPFormRec."PForm" := 0;

			 END;

               

               

            IF vNewPFormRec."PForm" > 0 THEN

              vConflicting := TRUE;

            END IF;

           

          END IF;

          

          

          -- *** if it is a Conflicting form then must merge answers ***

          -- E37209.3.4 note that in the event of conflicting, the PFORM of the Good Patient is being kept,

          --	and the one for the Old Patient will be deleted; if this logic is changed, need to 

		  --	change how IPTFORM is updated in UPDATE_IINFO function...

          --

		  IF vConflicting = TRUE THEN

		  

		    -- use the earlier date for the new patient's PFORM (the one we're keeping), B134334

		    IF vNewPFormRec."Date" > pform_rec."Date" THEN

		      

		      UPDATE PFORM 

		         SET "Date" = pform_rec."Date",

		  	   		 "User" = DECODE(pform_rec."User", OldiUserId, NewiUserId, pform_rec."User" )	--E37209.3.4

		       WHERE "Patient" = NewPatientId

		         AND "FormCode" = pform_rec."FormCode"

		         AND "PForm" = vNewPFormRec."PForm";

		         

		    END IF;





		    -- delete the old patient's PFORM  

			DELETE FROM pform

			 WHERE "Patient" = pform_rec."Patient"

			   AND "FormCode" = pform_rec."FormCode"

			   AND "PForm" = pform_rec."PForm";      

		    

		  

		    -- resequence and update the PPAGE records

		    vCurrentFItem := -1;	-- B142347

		    vSeq := 1;			-- B142347



		    -- Update "AuditNumber" to a higher value to avoid Unique Key Constraints

		    -- when resequencing

		    UPDATE ppage

			   SET "AuditNumber" = "AuditNumber" + 1000

			 WHERE "Patient" IN (OldPatientId, NewPatientId)

			   AND "FormCode" = pform_rec."FormCode";

 

		    FOR ppage_rec IN ppages_csr (OldPatientId, NewPatientId, pform_rec."FormCode")

		    LOOP

			   -- Set reset sequence to 1 and status to 1 whenever we switch to a

			   -- different "FItem"

			   IF vCurrentFItem != ppage_rec."FItem" THEN

			 	 vCurrentFItem := ppage_rec."FItem";

			 	 vSeq := 1;

			 	 vStatus := 1;

 

			 	 -- Get the last value for the AuditNumber

			 	 SELECT COUNT (1)

			 	   INTO vCount

			 	   FROM PPAGE

			 	  WHERE "Patient" IN (OldPatientId, NewPatientId)

			 		AND "FItem" = vCurrentFItem

			 		AND "FormCode" = pform_rec."FormCode";

			   END IF;

 

 

			   -- If sequence have reached the last AuditNumber, then set the status to 0

			   IF vSeq = vCount THEN

			 	 vStatus := 0;

			   END IF;

 

 

			   -- resequence audit number and set correct status, B134334

			   UPDATE PPAGE

			 	 SET "Patient" = NewPatientId,

			 	     "PForm" = vNewPFormRec."PForm",

			 	 	 "AuditNumber" = vSeq,

			 	 	 "Status" = vStatus,

		  	   		 "User" = DECODE("User", OldiUserId, NewiUserId, "User" )	--E37209.3.4

			   WHERE ctid = ppage_rec.ctid;

 

 

 

			   vSeq := vSeq + 1;

		    END LOOP;





		    -- resequence and update the PITEM records

		    vCurrentFItem := -1;	-- B142347

		    vSeq := 1;			-- B142347





		    -- Update "AuditNumber" to a higher value to avoid Unique Key Constraints

		    -- when resequencing

		    UPDATE PITEM

			   SET "AuditNumber" = "AuditNumber" + 1000

			 WHERE "Patient" IN (OldPatientId, NewPatientId)

			   AND "FormCode" = pform_rec."FormCode";

			   

			 -- B134334

			 vLastAppUser := 0;

			 vLastAppDate := NULL;



		    FOR pitem_rec IN pitems_csr (OldPatientId, NewPatientId, pform_rec."FormCode")

		    LOOP

			   -- Set reset sequence to 1 and status to 1 whenever we switch to a

			   -- different "FItem" or "FormCode"

			   IF vCurrentFItem != pitem_rec."FItem" THEN

			 	 vCurrentFItem := pitem_rec."FItem";

			 	 vSeq := 1;

			 	 vStatus := 1;

 

			 	 SELECT COUNT (1)

			  	   INTO vCount

			 	   FROM PITEM P

			 	  WHERE P."Patient" IN (OldPatientId, NewPatientId)

			 		AND P."FItem" = vCurrentFItem

			 		AND P."FormCode" = pform_rec."FormCode";

			   END IF;

 



 

			   IF vSeq = vCount THEN

			 	 vStatus := 0;

			   END IF;

			   

			   -- E41114 - if we are about to delete a spreadsheet type question that was

			   -- previously not deleted, then delete it's children too; AX-12321.12403

			   IF pitem_rec."AnsType" = 9 AND pitem_rec."Status" = 0 AND vStatus = 1 THEN

			   	

			   	UPDATE PITEM P SET P."Status" = 1 where P."Status" = 0 

					AND P."Patient" IN (OldPatientId, NewPatientId)

					AND P."PForm" = pform_rec."PForm"

					AND P."FItem" in (

			   		select F."FItem" from FITEM F

			   		where F."ParentFItem" = pitem_rec."FItem" and F."Deleted" = 0);

			   	

			   END IF;

			   

			   -- B134334 - determine the last approval user and date

			   if pitem_rec."AppUser" > 0 and (vLastAppDate IS NULL or vLastAppDate < pitem_rec."AppDate") then

			   	vLastAppUser := pitem_rec."AppUser";

			   	vLastAppDate := pitem_rec."AppDate";

			   end if;

 

			   -- not multiple type form, resequence audit number and set correct status, B134334

			   UPDATE PITEM

			 	  SET "Patient" = NewPatientId,

			 	      "PForm" = vNewPFormRec."PForm",

			 	      "AuditNumber" = vSeq,

			 	      "Status" = vStatus,

		  	   		  "User" = DECODE("User", OldiUserId, NewiUserId, "User" )	--E37209.3.4

			 	WHERE "PItem" = pitem_rec."PItem";

			 	

			 	

			 	-- B134334 - set pform approval flag after merge

			 	-- B142347.2 - use vCount2 so value in vCount is not wiped out

 				SELECT COUNT(1) 

 				INTO vCount2 

 				FROM PITEM P, FITEM F 

 				WHERE P."FItem" = F."FItem" AND P."Patient" = NewPatientId AND P."FormCode" = vNewPFormRec."FormCode" 

 				AND P."PForm" = vNewPFormRec."PForm" AND P."Status" = 0 AND P."AppUser" = 0 

				AND P."ASAType"=0 AND F."Deleted" = 0 AND F."Type" >= 2 AND ROWNUM < 2;

				

				if vCount2 > 0 then

					UPDATE PFORM SET "Approved" = 0, "LastAppUser" = vLastAppUser, "LastAppDate" = vLastAppDate WHERE "PForm" = vNewPFormRec."PForm";

				elsif vCount2 = 0 then

					UPDATE PFORM SET "Approved" = 1, "LastAppUser" = vLastAppUser, "LastAppDate" = vLastAppDate WHERE "PForm" = vNewPFormRec."PForm";

				end if;

 

			   vSeq := vSeq + 1;

		    END LOOP;



	   

		  

		  

		  ELSE -- *** not conflicting, just change the patient ***

		  

		  	-- PFORM

		  	UPDATE PFORM 

		  	   SET "Patient" = NewPatientId,

		  	   		"User" = DECODE("User", OldiUserId, NewiUserId, "User" )	--E37209.3.4

		  	 WHERE "Patient" = pform_rec."Patient"

		  	   AND "FormCode" = pform_rec."FormCode"

		  	   AND "PForm" = pform_rec."PForm";

		  

		  	-- PPAGE

		  	UPDATE PPAGE

		  	   SET "Patient" = NewPatientId,

		  	   		"User" = DECODE("User", OldiUserId, NewiUserId, "User" )	--E37209.3.4

		  	 WHERE "Patient" = pform_rec."Patient"

		  	   AND "FormCode" = pform_rec."FormCode"

		  	   AND "PForm" = pform_rec."PForm";

		  	   

		  	-- PITEM

		  	UPDATE PITEM

		  	   SET "Patient" = NewPatientId,

		  	   		"User" = DECODE("User", OldiUserId, NewiUserId, "User" )	--E37209.3.4

		  	 WHERE "Patient" = pform_rec."Patient"

		  	   AND "FormCode" = pform_rec."FormCode"

		  	   AND "PForm" = pform_rec."PForm";

		  	   

		  	   

		  END IF;







	   END LOOP;



	   Success := 1;

	   COMMIT;



	   EXCEPTION

		 WHEN OTHERS THEN

			ROLLBACK;

			Success := 0;

			

    END Merge_EPR; -- Procedure



    /**************************************************************************/

    --B132297 note that Family   Patient are the same for type 74's 

    PROCEDURE handle_trxtype74records(IN patientid numeric) IS

	   CURSOR Type74_csr (pPatientId NUMBER)

	   IS

		  SELECT DISTINCT T."Patient", T."Id", T."PayPlanId" 

			FROM TRX T

		   WHERE T."Patient" = pPatientId

			 AND T."Type" = 74 AND 

			 Exists (Select 1 From Trx T2 Where T."Type"=T2."Type" And 

				T."Id"=T2."Id" And T."Patient"=T2."Patient" And T."PayPlanId"=T2."PayPlanId" And 

				t."OrigRecNo"!=t2."OrigRecNo");

				

	 BEGIN

	

	   -- Loop through all duplicate Type 74's

	   FOR trx_rec IN Type74_csr (PatientId)

	   LOOP

			Merge_TRXTypeRecords(trx_rec."Patient", 74, trx_rec."Id", trx_rec."PayPlanId");	

	   END LOOP;



       COMMIT;

	   EXCEPTION

		 WHEN OTHERS THEN

			ROLLBACK;

			RAISE;

    END Handle_TRXType74Records; -- Procedure

		

    /**************************************************************************/

    --B132297 note that Patient is the payor, family is the patient for type 73's

    PROCEDURE handle_trxtype73records(IN patientid numeric) IS

	   CURSOR Type73_csr (pPatientId NUMBER)

	   IS

		  SELECT DISTINCT T."Family", T."Id", T."PayPlanId" 

			FROM TRX T

		   WHERE T."Family" = pPatientId

			 AND T."Type" = 73 AND 

			 Exists (Select 1 From Trx T2 Where T."Type"=T2."Type" And 

				T."Id"=T2."Id" And T."Family"=T2."Family" And T."PayPlanId"=T2."PayPlanId" And 

				t."OrigRecNo"!=t2."OrigRecNo");

	   

	 BEGIN

	

	   -- Loop through all duplicate Type 73's

	   FOR trx_rec IN Type73_csr (PatientId)

	   LOOP

			Merge_TRXTypeRecords(trx_rec."Family", 73, trx_rec."Id", trx_rec."PayPlanId");	

	   END LOOP;

			

       COMMIT;

	   EXCEPTION

		 WHEN OTHERS THEN

			ROLLBACK;

			RAISE;

    END Handle_TRXType73Records; -- Procedure

    

    /**************************************************************************/

    --B132297 decided to use Family in this situation

		PROCEDURE merge_trxtyperecords(IN patientid numeric, IN paymenttype numeric, IN paymentid numeric, IN payplanid numeric) IS

		  vFirstOrigRecNo TRX."OrigRecNo"                   %TYPE := 0;

		  vFirstTreatment TRX."Treatment"                   %TYPE := 0;

		  vPreviousUpdatedTotal TRX."Total"                 %TYPE;

		  vPreviousUpdatedHistoryType HISTORY."HistoryType" %TYPE;

		  vPreviousUpdatedDeleted TRX."Deleted"             %TYPE;

		  vNewTotal TRX."Total"                             %TYPE;

		  vNewInsTotal TRX."InsTotal"                       %TYPE;					--xxx

		  vNewHistoryType HISTORY."HistoryType"             %TYPE;

		  vNewDeleted TRX."Deleted"                         %TYPE;

		  vAdjustmentCount                                  NUMBER;

		  vMaxHistory HISTORY."History"                     %TYPE;

		TYPE aOrigRecNo_Type

		IS

		  TABLE OF NUMBER INDEX BY BINARY_INTEGER;

		  vPreviousTotalForOrigRecNo aOrigRecNo_Type;

		  CURSOR cPaymentHistoryRecords

		  IS

			 SELECT HISTORY.*,

				MAX (HISTORY."History") OVER (PARTITION BY HISTORY."Type", HISTORY."Id", HISTORY."Patient") "MaxHistory"

			 FROM HISTORY

			 WHERE "OrigRecNo" IN

				(SELECT "OrigRecNo"

				FROM TRX

				WHERE "Type"  = PaymentType										--xxx

				AND "Id"      = PaymentId

				AND "Family"  = PatientId											--xxx

				AND "PayPlanId" = PayPlanId

				)

		  ORDER BY "History";

		BEGIN

		  FOR rPaymentHistoryRecord IN cPaymentHistoryRecords

		  LOOP

			 IF vFirstOrigRecNo = 0 THEN

				-- If this is the first HISTORY record for this insurance payment allocation to this patient,

				-- save the OrigRecNo and Treatment to update all subsequent records.

				vFirstOrigRecNo := rPaymentHistoryRecord."OrigRecNo";

				vFirstTreatment := rPaymentHistoryRecord."Treatment";

				vNewTotal       := rPaymentHistoryRecord."Total";

				vNewInsTotal    := rPaymentHistoryRecord."InsTotal";							--xxx

			 ELSE

				-- If this is not the first HISTORY record for this insurance payment allocation to this patient,

				-- update the HistoryType, Treatment, Total, InsTotal, and Deleted columns, as required.

				IF vPreviousTotalForOrigRecNo.EXISTS (rPaymentHistoryRecord."OrigRecNo") THEN

				  -- If this is not the first HISTORY record for this OrigRecNo, add the difference between this record's Total

				  -- and the Total for the previous HISTORY record for this OrigRecNo to the Total for the previous HISTORY record.

				  vNewTotal := vPreviousUpdatedTotal + rPaymentHistoryRecord."Total" - vPreviousTotalForOrigRecNo (rPaymentHistoryRecord."OrigRecNo");

				ELSE

				  -- If this is the first HISTORY record for this OrigRecNo, add this record's Total to the Total for

				  -- the previous HISTORY record.

				  vNewTotal := vPreviousUpdatedTotal + rPaymentHistoryRecord."Total";

				END IF;

				

				IF vNewTotal = 0 THEN

				

					IF PaymentType = 74 THEN														--xxx

						  -- If the Total has been reduced to zero, check to see if there were any adjustments for this patient

						  -- and insurance payment at the time.

						  SELECT COUNT (1)

						  INTO vAdjustmentCount

						  FROM HISTORY

						  WHERE "Type"                = 7

						  AND "InsPmtId"              = rPaymentHistoryRecord."Id"

						  AND "Patient"               = rPaymentHistoryRecord."Patient"

						  AND HISTORY."ModifiedDate" <= rPaymentHistoryRecord."ModifiedDate"

						  AND NOT EXISTS

							 (SELECT 1

							 FROM HISTORY LATER_HISTORY

							 WHERE LATER_HISTORY."OrigRecNo"   = HISTORY."OrigRecNo"

							 AND LATER_HISTORY."History"       > HISTORY."History"

							 AND LATER_HISTORY."ModifiedDate" <= rPaymentHistoryRecord."ModifiedDate"

							 );

						  IF vAdjustmentCount = 0 THEN

							 -- If there were no adjustments for this patient and insurance payment at the time, mark the record as deleted

							 -- and a deletion history type.

							 vNewHistoryType := 4;

							 vNewDeleted     := 1;

						  ELSE

							 -- If there were adjustments for this patient and insurance payment at the time, mark the record as not deleted

							 -- and an allocation history type.

							 vNewHistoryType := 3;

							 vNewDeleted     := 0;

						  END IF;

					 ELSE

						-- xxx type 73's, if amount is down to zero, stamped as deleted

						 vNewHistoryType := 4;

						 vNewDeleted     := 1;

					 END IF;

				ELSE

				  -- If the Total has not been reduced to zero, mark the record as not deleted

				  -- and an allocation history type.

				  vNewHistoryType := 3;

				  vNewDeleted     := 0;

				END IF;

			 END IF;

			 

			 --xxx

			 IF PaymentType = 74 THEN														

				vNewInsTotal    := vNewTotal;		

			 ELSE

				-- patient payment; no ins total

				vNewInsTotal    := 0;		

			 END IF;

			 

			 IF vNewTotal = vPreviousUpdatedTotal AND vNewHistoryType = vPreviousUpdatedHistoryType AND vNewDeleted = vPreviousUpdatedDeleted THEN

				-- If this record has the same updated Total, HistoryType, and Deleted values as the previous record, delete it.

				DELETE

				FROM HISTORY

				WHERE "History" = rPaymentHistoryRecord."History";

			 ELSE

				-- If this record has a different updated Total, HistoryType, or Deleted value as the previous record, update it,

				-- if necessary.

				IF vNewHistoryType <> rPaymentHistoryRecord."HistoryType" OR vFirstTreatment <> rPaymentHistoryRecord."Treatment" OR vNewDeleted <> rPaymentHistoryRecord."Deleted" OR vNewTotal <> rPaymentHistoryRecord."Total" OR vFirstOrigRecNo <> rPaymentHistoryRecord."OrigRecNo" THEN

				  -- Don't bother updating the record if nothing has changed.

				  UPDATE HISTORY

				  SET "HistoryType" = vNewHistoryType,

					 "Treatment"     = vFirstTreatment,

					 "Deleted"       = vNewDeleted,

					 "Total"         = vNewTotal,

					 "InsTotal"      = vNewInsTotal,									--xxx

					 "OrigRecNo"     = vFirstOrigRecNo

				  WHERE "History"   = rPaymentHistoryRecord."History";

				END IF;

			 END IF;

			 vPreviousUpdatedTotal                                          := vNewTotal;

			 vPreviousUpdatedHistoryType                                    := vNewHistoryType;

			 vPreviousUpdatedDeleted                                        := vNewDeleted;

			 vPreviousTotalForOrigRecNo (rPaymentHistoryRecord."OrigRecNo") := rPaymentHistoryRecord."Total";

			 IF rPaymentHistoryRecord."History"                              = rPaymentHistoryRecord."MaxHistory" THEN

				-- Update the transaction with the same Treatment number to match the last history record.

				UPDATE TRX

				SET "Patient"            = rPaymentHistoryRecord."Patient",

				  "Family"               = rPaymentHistoryRecord."Family",

				  "Status"               = rPaymentHistoryRecord."Status",

				  "EDI"                  = rPaymentHistoryRecord."EDI",

				  "EDIStatus"            = rPaymentHistoryRecord."EDIStatus",

				  "Date"                 = rPaymentHistoryRecord."Date",

				  "SubmitDate"           = rPaymentHistoryRecord."SubmitDate",

				  "ClaimDoctor"          = rPaymentHistoryRecord."ClaimDoctor",

				  "Submitted"            = rPaymentHistoryRecord."Submitted",

				  "TreatmentDate"        = rPaymentHistoryRecord."TreatmentDate",

				  "CreationDate"         = rPaymentHistoryRecord."CreationDate",

				  "Procedure"            = rPaymentHistoryRecord."Procedure",

				  "Code"                 = rPaymentHistoryRecord."Code",

				  "Site"                 = rPaymentHistoryRecord."Site",

				  "Surface"              = rPaymentHistoryRecord."Surface",

				  "Unit"                 = rPaymentHistoryRecord."Unit",

				  "Producer"             = rPaymentHistoryRecord."Producer",

				  "Total"                = vNewTotal,

				  "InsTotal"             = vNewInsTotal,											--xxx

				  "Company1"             = rPaymentHistoryRecord."Company1",

				  "Policy1"              = rPaymentHistoryRecord."Policy1",

				  "Category1"            = rPaymentHistoryRecord."Category1",

				  "Item1"                = rPaymentHistoryRecord."Item1",

				  "Deduct1"              = rPaymentHistoryRecord."Deduct1",

				  "Assign1"              = rPaymentHistoryRecord."Assign1",

				  "Eligible1"            = rPaymentHistoryRecord."Eligible1",

				  "Pct1"                 = rPaymentHistoryRecord."Pct1",

				  "Amount1"              = rPaymentHistoryRecord."Amount1",

				  "InsPayed1"            = rPaymentHistoryRecord."InsPayed1",

				  "InsAdj1"              = rPaymentHistoryRecord."InsAdj1",

				  "Company2"             = rPaymentHistoryRecord."Company2",

				  "Policy2"              = rPaymentHistoryRecord."Policy2",

				  "Category2"            = rPaymentHistoryRecord."Category2",

				  "Item2"                = rPaymentHistoryRecord."Item2",

				  "Assign2"              = rPaymentHistoryRecord."Assign2",

				  "Deduct2"              = rPaymentHistoryRecord."Deduct2",

				  "Eligible2"            = rPaymentHistoryRecord."Eligible2",

				  "Pct2"                 = rPaymentHistoryRecord."Pct2",

				  "Amount2"              = rPaymentHistoryRecord."Amount2",

				  "InsPayed2"            = rPaymentHistoryRecord."InsPayed2",

				  "InsAdj2"              = rPaymentHistoryRecord."InsAdj2",

				  "Company3"             = rPaymentHistoryRecord."Company3",

				  "Policy3"              = rPaymentHistoryRecord."Policy3",

				  "Category3"            = rPaymentHistoryRecord."Category3",

				  "Item3"                = rPaymentHistoryRecord."Item3",

				  "Assign3"              = rPaymentHistoryRecord."Assign3",

				  "Deduct3"              = rPaymentHistoryRecord."Deduct3",

				  "Eligible3"            = rPaymentHistoryRecord."Eligible3",

				  "Pct3"                 = rPaymentHistoryRecord."Pct3",

				  "Amount3"              = rPaymentHistoryRecord."Amount3",

				  "InsPayed3"            = rPaymentHistoryRecord."InsPayed3",

				  "InsAdj3"              = rPaymentHistoryRecord."InsAdj3",

				  "Description"          = rPaymentHistoryRecord."Description",

				  "Deleted"              = vNewDeleted,

				  "Bank"                 = rPaymentHistoryRecord."Bank",

				  "Payed"                = rPaymentHistoryRecord."Payed",

				  "InsPayed"             = rPaymentHistoryRecord."InsPayed",

				  "PtAdj"                = rPaymentHistoryRecord."PtAdj",

				  "InsAdj"               = rPaymentHistoryRecord."InsAdj",

				  "EstimateF"            = rPaymentHistoryRecord."EstimateF",

				  "Additional"           = rPaymentHistoryRecord."Additional",

				  "TxStatus"             = rPaymentHistoryRecord."TxStatus",

				  "User"                 = rPaymentHistoryRecord."User",

				  "PtWriteOff"           = rPaymentHistoryRecord."PtWriteOff",

				  "PolicyId1"            = rPaymentHistoryRecord."PolicyId1",

				  "PolicyId2"            = rPaymentHistoryRecord."PolicyId2",

				  "PolicyId3"            = rPaymentHistoryRecord."PolicyId3",

				  "InsStatus1"           = rPaymentHistoryRecord."InsStatus1",

				  "InsStatus2"           = rPaymentHistoryRecord."InsStatus2",

				  "InsStatus3"           = rPaymentHistoryRecord."InsStatus3",

				  "IsBankDeposit"        = rPaymentHistoryRecord."IsBankDeposit",

				  "ChartTrx"             = rPaymentHistoryRecord."ChartTrx",

				  "PlanTotal"            = rPaymentHistoryRecord."PlanTotal",

				  "Phase"                = rPaymentHistoryRecord."Phase",

				  "Seq"                  = rPaymentHistoryRecord."Seq",

				  "AppUser"              = rPaymentHistoryRecord."AppUser",

				  "AppDate"              = rPaymentHistoryRecord."AppDate",

				  "Grading"              = rPaymentHistoryRecord."Grading",

				  "Site2"                = rPaymentHistoryRecord."Site2",

				  "Custom1"              = rPaymentHistoryRecord."Custom1",

				  "Custom2"              = rPaymentHistoryRecord."Custom2",

				  "PayPlanId"            = rPaymentHistoryRecord."PayPlanId",

				  "Discipline"           = rPaymentHistoryRecord."Discipline",

				  "DiscountedPmtId"      = rPaymentHistoryRecord."DiscountedPmtId",

				  "Location"             = rPaymentHistoryRecord."Location",

				  "OrigAssign1"          = rPaymentHistoryRecord."OrigAssign1",

				  "OrigAssign2"          = rPaymentHistoryRecord."OrigAssign2",

				  "OrigAssign3"          = rPaymentHistoryRecord."OrigAssign3",

				  "InDispute"            = rPaymentHistoryRecord."InDispute",

				  "DisputeDate"          = rPaymentHistoryRecord."DisputeDate",

				  "DeletionDate"         = rPaymentHistoryRecord."DeletionDate",

				  "EDIPat"               = rPaymentHistoryRecord."EDIPat",

				  "EDIPatStatus"         = rPaymentHistoryRecord."EDIPatStatus",

				  "InsTransfer1"         = rPaymentHistoryRecord."InsTransfer1",

				  "InsTransfer2"         = rPaymentHistoryRecord."InsTransfer2",

				  "InsTransfer3"         = rPaymentHistoryRecord."InsTransfer3",

				  "InsTransfer"          = rPaymentHistoryRecord."InsTransfer",

				  "InsPmtId"             = rPaymentHistoryRecord."InsPmtId",

				  "StationId"            = rPaymentHistoryRecord."StationId",

				  "Practice"             = rPaymentHistoryRecord."Practice",

				  "Suspended"            = rPaymentHistoryRecord."Suspended",

				  "DelAppUser"           = rPaymentHistoryRecord."DelAppUser",

				  "DelAppDate"           = rPaymentHistoryRecord."DelAppDate",

				  "OrthoStatus"          = rPaymentHistoryRecord."OrthoStatus",

				  "CvgType"              = rPaymentHistoryRecord."CvgType",

				  "ModifiedDate"         = rPaymentHistoryRecord."ModifiedDate",

				  "OrigClaimDate"        = rPaymentHistoryRecord."OrigClaimDate",

				  "SubmitMode"           = rPaymentHistoryRecord."SubmitMode",

				  "Custom3"              = rPaymentHistoryRecord."Custom3",

				  "Custom4"              = rPaymentHistoryRecord."Custom4",

				  "CorrespondCode"       = rPaymentHistoryRecord."CorrespondCode",

				  "InsCvgType1"          = rPaymentHistoryRecord."InsCvgType1",

				  "InsCvgType2"          = rPaymentHistoryRecord."InsCvgType2",

				  "InsCvgType3"          = rPaymentHistoryRecord."InsCvgType3",

				  "OrigRecNo"            = rPaymentHistoryRecord."OrigRecNo",

				  "EntryUser"            = rPaymentHistoryRecord."EntryUser",

				  "PlanInProcTotal"      = rPaymentHistoryRecord."PlanInProcTotal",

				  "TrxDep"               = rPaymentHistoryRecord."TrxDep",

				  "CustomaryTotal"       = rPaymentHistoryRecord."CustomaryTotal",

				  "TaxRate"              = rPaymentHistoryRecord."TaxRate",

				  "TaxAmount"            = rPaymentHistoryRecord."TaxAmount" -- E130137 removed diagcode

				WHERE "Type"             = PaymentType										--xxx

				AND "Id"                 = PaymentId

				AND "Treatment"          = vFirstTreatment

				AND "PayPlanId"			 = PayPlanId;										--xxx	

				-- Delete the transactions that have different treatment numbers.

				DELETE

				FROM TRX

				WHERE "Type"     = PaymentType												--xxx

				AND "Id"         = PaymentId

				AND "Treatment" <> vFirstTreatment

				AND "Family"     = PatientId													--xxx

				AND "PayPlanId"  = PayPlanId;													--xxx

			 END IF;

		  END LOOP;

		END;

    

    /**************************************************************************/



  -- E37209.3.4   added

  PROCEDURE merge_iinfo(IN oldpatientid numeric, IN newpatientid numeric, OUT oldiuserid numeric, OUT newiuserid numeric) IS

  	iFormsExists	NUMBER;

	SQLStmt			 VARCHAR2(2000);

  BEGIN



	SELECT COUNT(1) INTO iFormsExists FROM user_tables WHERE table_name = 'IUSER';

	IF iFormsExists = 1 THEN

		BEGIN

			SQLStmt := 'SELECT "iUser"

        		FROM IUSER

	       		WHERE "Type" = 0 

    	   		AND "Deleted" = 0

	   			AND "Id" = :1';

			execute immediate SQLStmt into OldiUserId using OldPatientId;

   	  	EXCEPTION WHEN NO_DATA_FOUND THEN

				OldiUserId := 0;

	    END;

		

		BEGIN

			SQLStmt := 'SELECT "iUser"

    	    	FROM IUSER

       			WHERE "Type" = 0 

       			AND "Deleted" = 0

		   		AND "Id" = :1';

			execute immediate SQLStmt into NewiUserId using NewPatientId;

    	EXCEPTION WHEN NO_DATA_FOUND THEN

				NewiUserId := 0;

	    END;

		

		IF OldiUserId <> 0 THEN

			IF NewiUserId <> 0 THEN 

				-- mark old IUSER as deleted

				SQLStmt := 'UPDATE IUSER SET

					"Deleted" = 1 WHERE "Type" = 0 

			   		AND "Id" = :1';

				execute immediate SQLStmt using OldPatientId;

	

				-- change all IACCESS records to new Patient as well

				--AX-3503.7953	delete duplicate records

				SQLStmt := 'DELETE FROM IACCESS I1 WHERE I1."iUser" = :1 

					AND EXISTS (SELECT 1 FROM IACCESS I2

                    WHERE I2."iUser" = :2 AND I2."RespiUser" = I1."RespiUser")';

				execute immediate SQLStmt using OldiUserId, NewiUserId;

				SQLStmt := 'DELETE FROM IACCESSH I1 WHERE I1."iUser" = :1 

					AND EXISTS (SELECT 1 FROM IACCESSH I2

                    WHERE I2."iUser" = :2 AND I2."RespiUser" = I1."RespiUser")';

				execute immediate SQLStmt using OldiUserId, NewiUserId;



				--AX-3503.7953	need to update iUser

				SQLStmt := 'UPDATE IACCESS SET "iUser" = :1 WHERE "iUser" = :2'; 

				execute immediate SQLStmt using NewiUserId, OldiUserId;

				SQLStmt := 'UPDATE IACCESSH SET "iUser" = :1 WHERE "iUser" = :2'; 

				execute immediate SQLStmt using NewiUserId, OldiUserId;



				--AX-3503.7953	delete duplicate records

				SQLStmt := 'DELETE FROM IACCESS I1 WHERE I1."RespiUser" = :1 

					AND EXISTS (SELECT 1 FROM IACCESS I2

                    WHERE I2."RespiUser" = :2 AND I2."iUser" = I1."iUser")';

				execute immediate SQLStmt using OldiUserId, NewiUserId;

				SQLStmt := 'DELETE FROM IACCESSH I1 WHERE I1."RespiUser" = :1 

					AND EXISTS (SELECT 1 FROM IACCESSH I2

                    WHERE I2."RespiUser" = :2 AND I2."iUser" = I1."iUser")';

				execute immediate SQLStmt using OldiUserId, NewiUserId;



				--AX-3503.7953	need to update iRespUser

				SQLStmt := 'UPDATE IACCESS SET "RespiUser" = :1 WHERE "RespiUser" = :2'; 

				execute immediate SQLStmt using NewiUserId, OldiUserId;

				SQLStmt := 'UPDATE IACCESSH SET "RespiUser" = :1 WHERE "RespiUser" = :2'; 

				execute immediate SQLStmt using NewiUserId, OldiUserId;



				-- need to delete duplicates iPTFORM 

				SQLStmt := 'DELETE FROM IPTFORM I1 WHERE I1."Patient" = :1 

					AND EXISTS (SELECT 1 FROM IPTFORM I2, FORM F

                    WHERE I2."Patient" = :2 AND I2."FormCode" = I1."FormCode"

					AND I2."FormCode" = F."Code" AND F."Multiple" = 0)';	--B120296

				execute immediate SQLStmt using OldPatientId, NewPatientId;

				

				

			ELSE

				NewiUserId := OldiUserId; -- AX-21753



				-- update IUSER to be for the new Patient

				SQLStmt := 'UPDATE IUSER SET

					"Id" = :1 WHERE "Type" = 0 

			   		AND "Id" = :2';

				execute immediate SQLStmt using NewPatientId, OldPatientId;

				--AX-3503.7953 update IUSERH records				

				SQLStmt := 'UPDATE IUSERH SET

					"Id" = :1 WHERE "Type" = 0 

			   		AND "Id" = :2';

				execute immediate SQLStmt using NewPatientId, OldPatientId;



				--AX-3503.7953				

				-- no need to update IACCESS records, iUser now points to the new patient

				

			END IF;

				

			-- change all IPTFORMs to new Patient as well

			SQLStmt := 'UPDATE IPTFORM SET

				"Patient" = :1 WHERE "Patient" = :2'; 

			execute immediate SQLStmt using NewPatientid, OldPatientId;



			-- AX-3503.8438	delete iACCESS records where iUser = RespiUser

			SQLStmt := 'DELETE FROM IACCESS I1 WHERE I1."RespiUser" = I1."iUser" 

				AND I1."iUser" = :1';

			execute immediate SQLStmt using NewiUserId;

			SQLStmt := 'DELETE FROM IACCESSH I1 WHERE I1."RespiUser" = I1."iUser" 

				AND I1."iUser" = :1';

			execute immediate SQLStmt using NewiUserId;



				

		END IF;

		

	ELSE

		OldiUserId := 0;

		NewiUserId := 0;

	END IF;

  		

  END Merge_iInfo;

  

  

    /**************************************************************************/

    -- B65979

    PROCEDURE convertguarantortopatient(IN patientid numeric, IN newstatus character, IN newchart character, IN newchartsort character, IN userid numeric, IN stationid numeric) IS

    	Success			NUMBER;

      vPatientRec 	PATIENT%ROWTYPE;    

	   vAuditId    	AUDITHIS."Audit"%TYPE;

	   vDate				AUDITHIS."Date"%TYPE;

	   vTime				AUDITHIS."Time"%TYPE;

	   vIsPolicyGuar	PTGUAR."IsPolicyGuarantor"%TYPE;

	   vCountry     NUMBER;

	   CURSOR policy_csr (PatientId NUMBER)

	   IS

		   SELECT "PolicyId", "Patient", "Company", "HasPatientLimit", 

				"PatientLimit", "PatientDeduct" 

				FROM POLICY 

				WHERE "Patient" = PatientId AND "Deleted" = 0;

			 

    BEGIN

	  

	   Success := 0;

   	vIsPolicyGuar := 0;



		-- lookup guarantor record

      BEGIN

        SELECT *

          INTO vPatientRec

          FROM patient

         WHERE "Patient" = PatientId;

      EXCEPTION WHEN NO_DATA_FOUND THEN

      	GOTO end_of_process;

      END;





		-- if patient = family then there is nothing to do

		IF vPatientRec."Patient" = vPatientRec."Family" THEN

		  	Success := 1;

			GOTO end_of_process;

		END IF;



		-- get audit date and time

		BEGIN

			SELECT TRUNC (SYSDATE), (to_number(to_char(sysdate, 'HH'))*60)+to_number(to_char(sysdate, 'MI'))

			  INTO vDate, vTime

			  FROM DUAL;			  

      EXCEPTION WHEN NO_DATA_FOUND THEN

      	GOTO end_of_process;

		END;



		-- add PATIENT update audit record

	 	SELECT audithis_audit_seq.NEXTVAL

		  INTO vAuditId

		  FROM DUAL;



		INSERT INTO AUDITHIS

			VALUES (vAuditId, vDate, vTime, UserId, StationId, 'PATIENT', 2);

    

    SELECT "Country" INTO vCountry FROM Practice WHERE ROWNUM = 1;

    

    IF vCountry = 2 THEN

    		UPDATE PATIENT SET 

			"Family" = PatientId,

			"Status" = NewStatus,

			"ContactAt" = 1,

			"IsPatient" = 1,

			"RequireTxConsent" = 1,

			"Chart" = NewChart,	

			"ChartSort" = NewChartSort,

			"Audit" = vAuditId

		WHERE "Patient" = PatientId;



    ELSE

		-- update the PATIENT record; B80419 	

		UPDATE PATIENT SET 

			"Family" = PatientId,

			--"Sin" = vPatientRec."RespNumber", -- AX-14323.14589

			"Status" = NewStatus,

			"ContactAt" = 1,

			"IsPatient" = 1,

			"RequireTxConsent" = 1,

			"Chart" = NewChart,	

			"ChartSort" = NewChartSort,

			"Audit" = vAuditId

		WHERE "Patient" = PatientId;

    END IF;

		

		

		-- add PTDEPEND records if needed

	   FOR policy_rec IN policy_csr (PatientId)

	   LOOP

	   	vIsPolicyGuar := 1;

	   	

	   	-- B68833 remove any bad PTDEPEND rows that may exist

	   	DELETE FROM PTDEPEND 

	   	WHERE "PolicyId" = policy_rec."PolicyId"

	   	AND "Patient" = PatientId;

	   	

	   	

			-- add PTDEPEND record

			INSERT INTO PTDEPEND VALUES (

				policy_rec."PolicyId",			-- PolicyId

				PatientId,							-- Patient

				0,										-- Number

				1,										-- IsCovered

				0,										-- Relation

				policy_rec."HasPatientLimit",	-- HasPatientLimit

				policy_rec."PatientLimit",		-- PatientLimit

				policy_rec."PatientDeduct",	-- PatientDeduct

				policy_rec."PatientLimit",		-- LimitBalance

				policy_rec."PatientDeduct",	-- DeductBalance

				vDate,								-- Date

				vTime,								-- Time

				UserId,								-- User

				StationId,							-- StationId

				0,										-- Deleted

				0,										-- BillOrder

				0, 									-- VisitBalance

				0,  									-- MedicaidCoPay

				NULL,									-- StartDate

				NULL,									-- EndDate

				'',										-- CardVerNo -- E00666.3.1

				0										-- CorrectStatus

			);

			

			-- insert category and item limits

			-- B80125 - only insert for this policy

			POLINS_PKG.InsertCatLimits(PatientId, PatientId, policy_rec."PolicyId");

			POLINS_PKG.InsertItemLimits(PatientId, PatientId, policy_rec."PolicyId");

			POLINS_PKG.InsertCatLimitsUsingTempl(PatientId, PatientId, policy_rec."PolicyId");

			POLINS_PKG.InsertItemLimitsUsingTempl(PatientId, PatientId, policy_rec."PolicyId");

	   	

		END LOOP;			





		-- add PTGUAR insert audit record

	 	SELECT audithis_audit_seq.NEXTVAL

		  INTO vAuditId

		  FROM DUAL;



		INSERT INTO AUDITHIS

			VALUES (vAuditId, vDate, vTime, UserId, StationId, 'PTGUAR', 1);





		-- add PTGUAR record

		INSERT INTO PTGUAR VALUES (

			PatientId,						-- RespPatient

			PatientId,						-- Patient

			1,									-- IsPrimaryGuarantor

			0,									-- IsSecondaryGuarantor

			vIsPolicyGuar,					-- IsPolicyGuarantor

			'Self',							-- RespRelation

			0,									-- Deleted

			vAuditId,						-- Audit

			0									-- Inactive

		);









	   Success := 1;



      <<end_of_process>>

      IF Success != 1 THEN

        ROLLBACK;

      ELSE

        NULL;

        COMMIT;

      END IF;

      

	   EXCEPTION

		 WHEN OTHERS

		 THEN

			ROLLBACK;

			Success := 0;

	

	END ConvertGuarantorToPatient;	

	

	-- E136707, E136708, B142771.1

	PROCEDURE getsmokingstatus(IN patientid numeric, OUT medalertid numeric, OUT userid numeric, OUT code character varying, OUT description character varying, OUT ptalertid numeric) IS

		CURSOR cMedAlert (PatientId NUMBER) IS 

		SELECT P."MedAlert", P."Description", P."User", P."PtAlert", M."SNOCode" FROM PTALERT P, MEDALERT M 

		WHERE P."Patient" = PatientId AND P."AlertType" = 2 AND P."Deleted" = 0 AND P."Status" = 0 

		AND P."MedAlert" = M."MedAlert";

	BEGIN

	   FOR rec IN cMedAlert(PatientId)

	   LOOP

			IF IsSmokingProblem(rec."MedAlert") = 1 THEN

				BEGIN

					MedAlertId := rec."MedAlert";

					UserId := rec."User";

					PtAlertId := rec."PtAlert";

					Code := TRIM(rec."SNOCode");

					Description := TRIM(rec."Description");	

					EXIT;

				END;

			END IF;

		END LOOP;

	END GetSmokingStatus;	

	

	--E136707 

	FUNCTION issmokingproblem(medalertid numeric) RETURN numeric IS

		vCode  CHAR(255);

		vResult NUMBER := 0;

	BEGIN

	   BEGIN

        SELECT TRIM("SNOCode")

          INTO vCode

          FROM MEDALERT

         WHERE "AlertType" = 2 AND "MedAlert" = MedAlertId;

      EXCEPTION WHEN NO_DATA_FOUND THEN

      	vCode := '';

      END;

		IF (vCode = '449868002') OR

			(vCode = '428041000124106') OR

			(vCode = '8517006') OR

			(vCode = '266919005') OR

			(vCode = '77176002') OR

			(vCode = '266927001') OR

			(vCode = '428071000124103') OR

			(vCode = '428061000124105')

		THEN

			vResult := 1;

		END IF;

		RETURN vResult;

	END IsSmokingProblem;	

	

	--E142678.js8

	FUNCTION issmokingsnomedcode(snomed character varying) RETURN numeric IS

		vCode  CHAR(255);

		vResult NUMBER := 0;

	BEGIN

		vCode := TRIM(SNOMed);

		IF (vCode = '449868002') OR

			(vCode = '428041000124106') OR

			(vCode = '8517006') OR

			(vCode = '266919005') OR

			(vCode = '77176002') OR

			(vCode = '266927001') OR

			(vCode = '428071000124103') OR

			(vCode = '428061000124105')

		THEN

			vResult := 1;

		END IF;

		RETURN vResult;

	END IsSmokingSNOMedCode;	

	

	

		--E136707, E136708, B142771.1

	FUNCTION getsmokingstatusdescription(patientid numeric) RETURN character varying IS

		vCode  CHAR(255);

		vDescription  CHAR(255);

		vId NUMBER;

		vUser NUMBER;

		vPtAlert NUMBER;

	BEGIN

		GetSmokingStatus(PatientId, vId, vUser, vCode, vDescription, vPtAlert);

		RETURN vDescription;

	END GetSmokingStatusDescription;	



	--AX-11773.11800

	PROCEDURE getnonsmokingstatuscode(OUT code character varying) IS

	BEGIN

		Code := '266927001';

	END GetNonSmokingStatusCode;





	--AX-18695.21037

	FUNCTION getsexorientation(ptsexorient numeric) RETURN character varying IS

		vDescription  VARCHAR2(255);

	BEGIN

		IF (PtSexOrient = 1) THEN

			vDescription := 'Straight or heterosexual';

		ELSIF (PtSexOrient = 2) THEN

			vDescription := 'Lesbian, gay or homosexual';

		ELSIF (PtSexOrient = 3) THEN

			vDescription := 'Bisexual';

		ELSIF (PtSexOrient = 4) THEN

			vDescription := 'Don''t know';

		ELSE

			vDescription := '';

		END IF;

		RETURN vDescription;

	END GetSexOrientation;

	

	--AX-18695.21037; AX-18695x

	FUNCTION getgenderidentity(ptgenderid numeric) RETURN character varying IS

		vDescription  VARCHAR2(255);

	BEGIN

		vDescription := '';



		IF (BITAND(PtGenderId,1) = 1) THEN

			vDescription := 'Male';

		END IF;

		IF (BITAND(PtGenderId,2) = 2) THEN

			BEGIN

				if LENGTH(vDescription) > 0 THEN

					vDescription := vDescription || ', ';

				END IF;

				vDescription := vDescription || 'Female';

			END;

		END IF;

		IF (BITAND(PtGenderId,4) = 4) THEN

			BEGIN

				if LENGTH(vDescription) > 0 THEN

					vDescription := vDescription || ', ';

				END IF;

				vDescription := vDescription || 'Transgender male';

			END;

		END IF;

		IF (BITAND(PtGenderId,8) = 8) THEN

			BEGIN

				if LENGTH(vDescription) > 0 THEN

					vDescription := vDescription || ', ';

				END IF;

				vDescription := vDescription || 'Transgender female';

			END;

		END IF;

		IF (BITAND(PtGenderId,16) = 16) THEN

			BEGIN

				if LENGTH(vDescription) > 0 THEN

					vDescription := vDescription || ', ';

				END IF;

				vDescription := vDescription || 'Genderqueer';

			END;

		END IF;

	

		RETURN vDescription;

	END GetGenderIdentity;

	

	--AX-32710

	FUNCTION getgenderpronouns(ptpreferpronouns numeric) RETURN character varying IS

		vDescription  VARCHAR2(255);

	BEGIN

		IF (PtPreferPronouns = 1) THEN

			vDescription := 'He/Him';

		ELSIF (PtPreferPronouns = 2) THEN

			vDescription := 'She/Her';

		ELSIF (PtPreferPronouns = 3) THEN

			vDescription := 'They/Them';

		ELSIF (PtPreferPronouns = 4) THEN

			vDescription := 'Don''t know';

		ELSE

			vDescription := '';

		END IF;

		RETURN vDescription;

	END GetGenderPronouns;

	

	--AX-32713

	FUNCTION getpatientpronouns(patientid numeric) RETURN character varying IS

		vDescription  VARCHAR2(255);

		vPatientGender PTGENDER%ROWTYPE;

	BEGIN

		SELECT *

			INTO vPatientGender

			FROM PTGENDER

			WHERE "Patient" = PatientId;

			

		IF (vPatientGender."PtPronounsDeclined" = 1) THEN 

			vDescription := '';

		ELSIF (NOT (vPatientGender."PtPronounsOther" IS NULL OR length(vPatientGender."PtPronounsOther") = 0)) THEN

			vDescription := vPatientGender."PtPronounsOther";

		ELSE

			vDescription := GetGenderPronouns(vPatientGender."PtPreferPronouns");

		END IF;

		

		RETURN vDescription;

	EXCEPTION WHEN NO_DATA_FOUND THEN

		RETURN '';

	END GetPatientPronouns;







END;
CREATE OR REPLACE PACKAGE BODY payplan_bal_pkg IS

FUNCTION pp_open_bal(patient numeric) RETURN numeric IS
  AR NUMBER := 0;

BEGIN

select sum(p."Total") + sum(NVL(TRXSUB."Total", 0)) + sum(NVL(TRXHELD."Total",0))
			+ sum(NVL(ORTHOINS."Total", 0)) INTO AR
from payplan p,
    (select pp."PlanId", sum(NVL(t."Total",0)) AS "Total" from trx t, payplan pp
     where t."Family" = pp."Patient" and t."PayPlanId" = pp."PlanId" AND (t."Type"  = 73 OR t."Type"  = 6) AND
           t."Deleted" = 0 AND pp."Patient" = Patient and pp."Status" = 0 GROUP BY pp."PlanId") TRXSUB,
    (select pp."PlanId", sum(NVL(t."Payed",0)) AS "Total" from trx t, payplan pp
     where t."Family" = pp."Patient" and t."PayPlanId" = pp."PlanId" AND t."Type"  = 3  AND
           t."Deleted" = 0 AND pp."Patient" = Patient and pp."Status" = 0 GROUP BY pp."PlanId") TRXHELD,
    (select pp."PlanId", sum(NVL(t."Total",0)) AS "Total" from trx t, payplan pp
     where t."Family" = pp."Patient" and t."PayPlanId" = pp."PlanId" AND (t."Type"  = 74 OR t."Type"  = 7) AND
           t."Deleted" = 0 AND pp."Patient" = Patient AND pp."Type" = 2 AND pp."Status" = 0 GROUP BY pp."PlanId") ORTHOINS
where p."Patient" = patient and p."Status" = 0
		and p."PlanId" = TRXSUB."PlanId"(+) and p."PlanId" = TRXHELD."PlanId"(+)
		and p."PlanId" = ORTHOINS."PlanId"(+);


 IF AR IS NULL THEN
   AR := 0;
 END IF;

 RETURN AR;
END;

END;
CREATE OR REPLACE PACKAGE BODY pe_custom_pkg IS
FUNCTION get_golive_date() RETURN timestamp without time zone IS
	v_GoLiveDate DATE;
	v_nCount		NUMBER := 0;								-- AX-26071
BEGIN

	--AX-26071
   SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_PE_CUSTOM_PKG' and PROCEDURE_NAME = 'GET_GOLIVE_DATE';
   IF v_nCount > 0 THEN
     -- custom package function exists
     EXECUTE IMMEDIATE 'SELECT CUSTOM_PE_CUSTOM_PKG.GET_GOLIVE_DATE() FROM DUAL' INTO v_GoLiveDate;
     RETURN v_GoLiveDate;
   END IF;


	-- look up go live date (possibly from SYSOPTS!?!), and return
	v_GoLiveDate := trunc(sysdate)-30;
	return v_GoLiveDate;
END;

FUNCTION get_books_touse() RETURN character varying IS
	v_BookIds VARCHAR2(4000);
	v_nCount		NUMBER := 0;								-- AX-26071
BEGIN

	--AX-26071
   SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_PE_CUSTOM_PKG' and PROCEDURE_NAME = 'GET_BOOKS_TOUSE';
   IF v_nCount > 0 THEN
     -- custom package function exists
     EXECUTE IMMEDIATE 'SELECT CUSTOM_PE_CUSTOM_PKG.GET_BOOKS_TOUSE FROM DUAL' INTO v_BookIds;
     RETURN v_BookIds;
   END IF;


	-- can be a comma delimited hardcoded list of BOOK IDs, or a select query (as below) to get at those Ids
	-- v_BookIds := '120, 370';

	-- this will return all books that are setup to be chair books w/o reservation and having legit booking details
	SELECT STRING_AGG(b."Book", ', ')  "BookList"
		into v_BookIds
		FROM BOOK b
		WHERE 1=1
		AND b."HasReserves" = 0
		AND b."ReservesByProvider" = 0
		AND EXISTS (SELECT 1
              FROM BOOKDET d
              WHERE 1=1
              and d."Book" = b."Book"
              AND (d."EndDate" IS NULL
              OR d."EndDate" >= PE_CUSTOM_PKG.GET_GOLIVE_DATE()));

	return nvl(v_BookIds, '0');

	exception
	when others then
    return v_BookIds;

END;

END;
CREATE OR REPLACE PACKAGE BODY "pkg_elmah$get_error" IS
    PROCEDURE geterrorxml(IN v_application character varying, IN v_errorid character varying, OUT v_allxml clob) IS
    BEGIN
        SELECT  allxml
        INTO    v_AllXml
        FROM    elmah$error
        WHERE   errorid = NLS_UPPER(v_ErrorId)
        AND     application = v_Application;
    EXCEPTION
        WHEN NO_DATA_FOUND THEN
            v_AllXml := NULL;
    END GetErrorXml;

    PROCEDURE geterrorsxml(IN v_application character varying, IN v_pageindex numeric DEFAULT 0, IN v_pagesize numeric DEFAULT 15, OUT v_totalcount numeric, OUT v_results t_cursor) IS
        l_StartRowIndex NUMBER;
        l_EndRowIndex   NUMBER;
    BEGIN

        l_StartRowIndex := v_PageIndex * v_PageSize + 1;
        l_EndRowIndex := l_StartRowIndex + v_PageSize - 1;


        SELECT  COUNT(*)
        INTO    v_TotalCount
        FROM    elmah$error
        WHERE   application = v_Application;

        OPEN v_Results FOR
            SELECT  *
            FROM
            (
                SELECT  e.*,
                        ROWNUM row_number
                FROM
                (
                    SELECT
                            errorid,
                            application,
                            host,
                            type,
                            source,
                            message,
                            username,
                            statuscode,
                            timeutc
                    FROM    elmah$error
                    WHERE   application = v_Application
                    ORDER BY
                            timeutc DESC,
                            sequencenumber DESC
                ) e
                WHERE ROWNUM <= l_EndRowIndex
            )
            WHERE   row_number >= l_StartRowIndex;

    END GetErrorsXml;

END;
CREATE OR REPLACE PACKAGE BODY "pkg_elmah$log_error" IS
    PROCEDURE logerror(IN v_errorid character varying, IN v_application character varying, IN v_host character varying, IN v_type character varying, IN v_source character varying, IN v_message character varying, IN v_user character varying, IN v_allxml clob, IN v_statuscode numeric, IN v_timeutc timestamp without time zone) IS
    BEGIN
        INSERT INTO elmah$error
            (
                errorid,
                application,
                host,
                type,
                source,
                message,
                username,
                allxml,
                statuscode,
                timeutc
            )
        VALUES
            (
                NLS_UPPER(v_ErrorId),
                v_Application,
                v_Host,
                v_Type,
                v_Source,
                v_Message,
                v_User,
                v_AllXml,
                v_StatusCode,
                v_TimeUtc
            );

    END LogError;

END;
CREATE OR REPLACE PACKAGE BODY polins_pkg IS



/**************************************************************************/



-- main merge routine for initial conversion  

-- 	pStation: Station Id to use for corresponding history records

-- 	pUser: User Id to use for corresponding history records

-- 	bStrict: TRUE/FALSE to determine whether to check for identical POLRANGE

PROCEDURE polinsmergeprocess(IN pstation numeric, IN puser numeric, IN bstrict boolean) IS

	SQLStmt   		 VARCHAR2(4000);

	PolInsCur	    PolInsCurTyp;

	PolInsRec		PolInsRecTyp;

  

BEGIN

	-- gather distinct info for POLINS with corresponding #count; E66122; B69331; E142886.8

	SQLStmt := 'SELECT 

		NVL(TRIM(P."Group"),'' ''), 

		NVL(TRIM(P."Division"),'' ''),

		P."FormsTo", 

  		NVL(TRIM(P."Company"), '' ''),

  		NVL(TRIM(P."GovPolicy"), '' ''), 

  		NVL(TRIM(P."Fee"), '' ''), 

  		P."Employer", P."HasFamilyLimit", P."FamilyDeduct", P."FamilyLimit",

  		P."HasPatientLimit", P."PatientDeduct", P."PatientLimit",

  		P."YearEnd", P."Assignment", P."Signature", P."WriteOff",

  		P."PlanType", P."MonthlyDeduct", 

  		NVL(TRIM(P."TrojanId"), '' ''), 

  		P."YearEndDay",

  		P."ChildCoverage", P."AdultCoverage", P."YoungAdultCoverage", P."Copay",		

  		NVL(P."StartDate", TO_DATE(''01-01-1901'', ''DD-MM-YYYY'')),

  		NVL(P."EndDate", TO_DATE(''01-01-1901'', ''DD-MM-YYYY'')),

		COUNT(1)

  		FROM POLINS P WHERE P."Deleted" = 0 AND P."SharablePlan" = 1

		GROUP BY 

		NVL(TRIM(P."Group"),'' ''), 

		NVL(TRIM(P."Division"),'' ''), P."FormsTo", 

  		NVL(TRIM(P."Company"), '' ''), 

  		NVL(TRIM(P."GovPolicy"), '' ''), 

  		NVL(TRIM(P."Fee"), '' ''), P."Employer",

  		P."HasFamilyLimit", P."FamilyDeduct", P."FamilyLimit",

  		P."HasPatientLimit", P."PatientDeduct", P."PatientLimit",

  		P."YearEnd", P."Assignment", P."Signature", P."WriteOff",

  		P."PlanType", P."MonthlyDeduct", 

  		NVL(TRIM(P."TrojanId"), '' ''), P."YearEndDay",

  		P."ChildCoverage", P."AdultCoverage", P."YoungAdultCoverage", P."Copay", 

  		NVL(P."StartDate", TO_DATE(''01-01-1901'', ''DD-MM-YYYY'')), 

		NVL(P."EndDate", TO_DATE(''01-01-1901'', ''DD-MM-YYYY''))';



	OPEN PolInsCur FOR SQLStmt;

	<<distinct_polins_loop>>

    LOOP

    	-- for each distinct POLINS

        FETCH PolInsCur INTO PolInsRec;

        EXIT distinct_polins_loop WHEN PolInsCur%NOTFOUND;

    

        if PolInsRec.Count > 1 then

        	-- only need to call merge if there'r more than one

	        MergeDistinctPolIns(PolInsRec, pStation, pUser, bStrict);

        end if;

	END LOOP;

    CLOSE PolInsCur;

END PolInsMergeProcess;



/**************************************************************************/



-- merge routine for all POLINS's having similar info as PolInsRec passed in

-- 	p: partial POLINS record to be merged

-- 	pStation: Station Id to use for corresponding history records

-- 	pUser: User Id to use for corresponding history records

-- 	bStrict: TRUE/FALSE to determine whether to check for identical POLRANGE

PROCEDURE mergedistinctpolins(IN p polinsrectyp, IN pstation numeric, IN puser numeric, IN bstrict boolean) IS

	SQLStmt   		 VARCHAR2(4000);

	PolInsCur	  	PolInsCurTyp;

	MasterPolInsId 	NUMBER := 0;

	PolInsId 		NUMBER := 0;

  

BEGIN

	-- select all POLINS's matching the pass in distinct information; E66122; B69331; E142886.8

	SQLStmt := 'SELECT P."PolIns"

		FROM POLINS P WHERE P."Deleted" = 0 AND P."SharablePlan" = 1 AND 

		NVL(TRIM(P."Group"), '' '')=NVL(TRIM(:1), '' '') AND 

		NVL(TRIM(P."Division"), '' '')=NVL(TRIM(:2), '' '') AND 

		P."FormsTo"=:3 AND 

  		NVL(TRIM(P."Company"), '' '')=NVL(TRIM(:4), '' '') AND 

  		NVL(TRIM(P."GovPolicy"), '' '')=NVL(TRIM(:5), '' '') AND 

  		NVL(TRIM(P."Fee"), '' '')=NVL(TRIM(:6), '' '') AND 

		P."Employer"=:7 AND	P."HasFamilyLimit"=:8 AND P."FamilyDeduct"=:9 AND 

		P."FamilyLimit"=:10 AND P."HasPatientLimit"=:11 AND 

		P."PatientDeduct"=:12 AND P."PatientLimit"=:13 AND P."YearEnd"=:14 AND 

		P."Assignment"=:15 AND P."Signature"=:16 AND P."WriteOff"=:17 AND 

		P."PlanType"=:18 AND P."MonthlyDeduct"=:19 AND 

		NVL(TRIM(P."TrojanId"), '' '')=NVL(TRIM(:20), '' '') AND 

		P."YearEndDay"=:21 AND P."ChildCoverage"=:22 AND 

		P."AdultCoverage"=:23 AND P."YoungAdultCoverage"=:24 AND P."Copay"=:25 AND

		NVL(P."StartDate", TO_DATE(''01-01-1901'', ''DD-MM-YYYY''))=:26 AND 

		NVL(P."EndDate", TO_DATE(''01-01-1901'', ''DD-MM-YYYY''))=:27 

		ORDER BY P."ChangeDate" DESC';



	OPEN PolInsCur FOR SQLStmt using p."Group", p."Division", 

		p."FormsTo", p."Company", p."GovPolicy", p."Fee", p."Employer",

  		p."HasFamilyLimit", p."FamilyDeduct", p."FamilyLimit",

  		p."HasPatientLimit", p."PatientDeduct", p."PatientLimit",

  		p."YearEnd", p."Assignment", p."Signature", p."WriteOff",

  		p."PlanType", p."MonthlyDeduct", p."TrojanId", p."YearEndDay",

  		p."ChildCoverage", p."AdultCoverage", p."YoungAdultCoverage", p."Copay", 

		p."StartDate", p."EndDate";

	<<polins_loop>>

    LOOP

    	-- for each POLINS

        FETCH PolInsCur INTO PolInsId;

        EXIT polins_loop WHEN PolInsCur%NOTFOUND;

    

        IF MasterPolInsId = 0 THEN

        	-- with first one being the master (based on ChangeDate)

        	MasterPolInsId := PolInsId;

        ELSE

        	-- only continue to merge if not strict or having same POLRANGE's

			IF	(p."ChildCoverage" > 0 AND p."AdultCoverage" > 0) 

					OR ArePolRangeTheSame(MasterPolInsId, PolInsId)  THEN

		        MergePolIns(MasterPolInsId, PolInsId, pStation, 

							pUser, CLONEALLRECORDS);

		    ELSIF bStrict = FALSE THEN 

		        MergePolIns(MasterPolInsId, PolInsId, pStation, 

							pUser, CLONEALLEXCEPTDEPLIMIT);

		    END IF;

		    

        END IF;

	END LOOP;

    CLOSE PolInsCur;

    

    COMMIT;



END MergeDistinctPolIns;





/**************************************************************************/



-- routine to check it the POLRANGE records are identical for the given PolIns's

-- 	MasterPolInsId: POLINS id of the master record to merge to

-- 	PolInsId: POLINS id of the record to merge from

-- 	return TRUE if the records are the same; else return FALSE

FUNCTION arepolrangethesame(masterpolinsid numeric, polinsid numeric) RETURN boolean IS

	SQLStmt  	 VARCHAR2(4000);

  	nCount1 	NUMBER := 0;

  	nCount2 	NUMBER := 0;

 	bSame 		BOOLEAN := FALSE;



BEGIN

	SQLStmt := 'SELECT COUNT(1) FROM POLRANGE P WHERE P."PolIns"=:1';

	EXECUTE IMMEDIATE SQLStmt INTO nCount1 USING MasterPolInsId;

	EXECUTE IMMEDIATE SQLStmt INTO nCount2 USING PolInsId;

	

	IF  nCount1 = nCount2  THEN

		-- only continue if same # rows in POLRANGE; B69331

 		SQLStmt := 'SELECT COUNT(1) FROM POLRANGE P1 WHERE P1."PolIns"=:1 

			AND NOT EXISTS (SELECT 1 FROM POLRANGE P2 WHERE P2."PolIns"=:2 AND

			NVL(TRIM(P2."Id"), '' '') = NVL(TRIM(P1."Id"), '' '') AND 

			NVL(TRIM(P2."Category"), '' '') = NVL(TRIM(P1."Category"), '' '') AND 

			NVL(TRIM(P2."From"), '' '') = NVL(TRIM(P1."From"), '' '') AND 

			NVL(TRIM(P2."To"), '' '') = NVL(TRIM(P1."To"), '' '') AND 

			P2."Percent" = P1."Percent" AND P2."Times" = P1."Times" AND 

			P2."Frequency" = P1."Frequency" AND 

			P2."FrequencyCode" = P1."FrequencyCode" AND 

			P2."HasCatLimit" = P1."HasCatLimit" AND 

			P2."CatLimit" = P1."CatLimit" AND P2."CatPeriod" = P1."CatPeriod" AND 

			P2."CatFrequency" = P1."CatFrequency" AND 

			P2."HasItemLimit" = P1."HasItemLimit" AND 

			P2."ItemLimit" = P1."ItemLimit" AND P2."ItemPeriod" = P1."ItemPeriod" AND 

			P2."ItemFrequency" = P1."ItemFrequency" AND 

			P2."CatDeduct" = P1."CatDeduct" AND 

			P2."CatAffectFamily" = P1."CatAffectFamily" AND 

			P2."HasCategory" = P1."HasCategory" AND 

			P2."ItemDeduct" = P1."ItemDeduct" AND 

			P2."ItemAffectFamily" = P1."ItemAffectFamily" AND 

			P2."ItemPtChg" = P1."ItemPtChg")';

			

		EXECUTE IMMEDIATE SQLStmt INTO nCount1 USING MasterPolInsId, PolInsId;

	   	IF nCount1 = 0 THEN

	   		-- no differences 

    		bSame := TRUE;

		END IF;

		

	END IF;



   	RETURN bSame;

END;



/**************************************************************************/



-- routine for merging the two given POLINS records

-- 	MasterPolInsId: POLINS id of the master record to merge to

-- 	PolInsId: POLINS id of the record to merge from

-- 	pStation: Station Id to use for corresponding history records

-- 	pUser: User Id to use for corresponding history records

--	iMode is one of CLONEALLRECORDS = 4, 

--					CLONEALLEXCEPTDEPLIMIT = 3,

--					COPYALLKEEPLIMITDED = 2, 

--					COPYALLUSENEWLIMITDEDANDRESET = 1

--					COPYALLUSENEWLIMITDEDANDRECAL = 0

PROCEDURE mergepolins(IN masterpolinsid numeric, IN polinsid numeric, IN pstation numeric, IN puser numeric, IN imode numeric) IS

	SQLStmt   		 VARCHAR2(4000);

	PtPolCur	  	PtPolCurTyp;

	MasterPolInsRec	PolInsRecTyp;

	OrigPolInsRec	PolInsRecTyp;

	PolicyId		NUMBER;

	SharedEntryId	NUMBER;

BEGIN

	-- retrieve the policy info for the master record; E66122; E142886.8

	SQLStmt := 'SELECT P."Group", P."Division", P."FormsTo", 

  		P."Company", P."GovPolicy", P."Fee", P."Employer",

  		P."HasFamilyLimit", P."FamilyDeduct", P."FamilyLimit",

  		P."HasPatientLimit", P."PatientDeduct", P."PatientLimit",

  		P."YearEnd", P."Assignment", P."Signature", P."WriteOff",

  		P."PlanType", P."MonthlyDeduct", P."TrojanId", P."YearEndDay",

  		P."ChildCoverage", P."AdultCoverage", P."YoungAdultCoverage", P."Copay", 

		P."StartDate", P."EndDate", 0

  		FROM POLINS P WHERE P."PolIns"=:1';

	EXECUTE IMMEDIATE SQLStmt INTO MasterPolInsRec USING MasterPolInsId;

	

	-- retrieve the policy info for the record to be merged; E66122; E142886.8

	SQLStmt := 'SELECT P."Group", P."Division", P."FormsTo", 

  		P."Company", P."GovPolicy", P."Fee", P."Employer",

  		P."HasFamilyLimit", P."FamilyDeduct", P."FamilyLimit",

  		P."HasPatientLimit", P."PatientDeduct", P."PatientLimit",

  		P."YearEnd", P."Assignment", P."Signature", P."WriteOff",

  		P."PlanType", P."MonthlyDeduct", P."TrojanId", P."YearEndDay",

  		P."ChildCoverage", P."AdultCoverage", P."YoungAdultCoverage", P."Copay", 

		P."StartDate", P."EndDate", 0

  		FROM POLINS P WHERE P."PolIns"=:1';

	EXECUTE IMMEDIATE SQLStmt INTO OrigPolInsRec USING PolInsId;

	

	-- select all policies under the old POLINS

	SQLStmt := 'SELECT P."PolicyId" 

		FROM PTPOL P WHERE P."PolIns" = :1 AND P."Deleted" = 0';



	OPEN PtPolCur FOR SQLStmt using PolInsId;

	<<polins_loop>>

    LOOP

    	-- for each policy under old PTPOL, call merge

        FETCH PtPolCur INTO PolicyId;

        EXIT polins_loop WHEN PtPolCur%NOTFOUND;

   

 		MergePolicy(MasterPolInsId, MasterPolInsRec, OrigPolInsRec, 

					PolicyId, pStation, pUser, iMode);

	END LOOP;

    CLOSE PtPolCur;

    

	-- mark the old one as deleted    

	SELECT POLICY_SHAREDENTRYID_SEQ.NEXTVAL INTO SharedEntryId FROM DUAL;

	EXECUTE IMMEDIATE 'UPDATE POLINS P SET P."Deleted"=1, 

					P."Date"=trunc(sysdate),

					P."Time"=:1,

					P."User"=:2, 

					P."StationId"=:3,

					P."SharedEntryId"=:4

					WHERE P."PolIns"=:5 '

	                USING trunc(to_char(sysdate,'SSSSS')/60), pUser, 

					pStation, SharedEntryId, PolInsId;

	-- mark the master as sharableplan if it's not already so

	-- Note not necessary from main merge script (conversion); 

	--			but will be if call from axiUm

	EXECUTE IMMEDIATE 'UPDATE POLINS P SET P."SharablePlan"=1, 

					P."Date"=trunc(sysdate),

					P."Time"=:1,

					P."User"=:2, 

					P."StationId"=:3,

					P."SharedEntryId"=:4

					WHERE P."PolIns"=:5 AND P."SharablePlan"=0'

	                USING trunc(to_char(sysdate,'SSSSS')/60), pUser, 

					pStation, SharedEntryId, MasterPolInsId;

    

END MergePolIns;





/**************************************************************************/



-- routine for merging the two given POLINS records

-- 	MasterPolInsId: POLINS id of the master record to merge to

--	mp: master partial POLINS record

--	op: original partial POLINS record

-- 	OldPolicyId: PTPOL PolicyId of the record to merge

-- 	pStation: Station Id to use for corresponding history records

-- 	pUser: User Id to use for corresponding history records

--	iMode is one of CLONEALLRECORDS = 4, 

--					CLONEALLEXCEPTDEPLIMIT = 3,

--					COPYALLKEEPLIMITDED = 2, 

--					COPYALLUSENEWLIMITDEDANDRESET = 1

--					COPYALLUSENEWLIMITDEDANDRECAL = 0

PROCEDURE mergepolicy(IN masterpolinsid numeric, IN mp polinsrectyp, IN op polinsrectyp, IN oldpolicyid numeric, IN pstation numeric, IN puser numeric, IN imode numeric) IS

	PolicyId		NUMBER;

BEGIN



	-- get new PolicyId

	SELECT PTPOL_POLICYID_SEQ.NEXTVAL INTO PolicyId FROM DUAL;

	

	-- call routines to add corresponding records to new POLINS

	MergePtPol(MasterPolInsId, mp, op, OldPolicyId, PolicyId, 

				pStation, pUser, iMode);

				

	-- B67952

	UpdateTrx(OldPolicyId, PolicyId, pStation, pUser);

				

	MergePtDepend(MasterPolInsId, mp, op, OldPolicyId, PolicyId, 

				pStation, pUser, iMode);

	MergeDepLimit(MasterPolInsId, mp, op, OldPolicyId, PolicyId, 

				pStation, pUser, iMode);

				

END MergePolicy;



-- routine for merging the two given POLINS records

-- 	MasterPolInsId: POLINS id of the master record to merge to

-- 	PolicyId: PTPOL PolicyId of the record to merge

-- 	pStation: Station Id to use for corresponding history records

-- 	pUser: User Id to use for corresponding history records

--	iMode is one of CLONEALLRECORDS = 4, 

--					CLONEALLEXCEPTDEPLIMIT = 3,

--					COPYALLKEEPLIMITDED = 2, 

--					COPYALLUSENEWLIMITDEDANDRESET = 1

--					COPYALLUSENEWLIMITDEDANDRECAL = 0

PROCEDURE mergepolicyalt(IN masterpolinsid numeric, IN policyid numeric, IN pstation numeric, IN puser numeric, IN imode numeric) IS

	SQLStmt   		 VARCHAR2(4000);

	MasterPolInsRec	PolInsRecTyp;

	OrigPolInsRec	PolInsRecTyp;

BEGIN



	-- retrieve the policy info for the master record; E66122; E142886.8

	SQLStmt := 'SELECT P."Group", P."Division", P."FormsTo", 

  		P."Company", P."GovPolicy", P."Fee", P."Employer",

  		P."HasFamilyLimit", P."FamilyDeduct", P."FamilyLimit",

  		P."HasPatientLimit", P."PatientDeduct", P."PatientLimit",

  		P."YearEnd", P."Assignment", P."Signature", P."WriteOff",

  		P."PlanType", P."MonthlyDeduct", P."TrojanId", P."YearEndDay",

  		P."ChildCoverage", P."AdultCoverage", P."YoungAdultCoverage", P."Copay",

		P."StartDate", P."EndDate", 0

  		FROM POLINS P WHERE P."PolIns"=:1';

	EXECUTE IMMEDIATE SQLStmt INTO MasterPolInsRec USING MasterPolInsId;

	

	-- retrieve the policy info for the record to be merged; E66122; E142886.8

	SQLStmt := 'SELECT P."Group", P."Division", P."FormsTo", 

  		P."Company", P."GovPolicy", P."Fee", P."Employer",

  		P."HasFamilyLimit", P."FamilyDeduct", P."FamilyLimit",

  		P."HasPatientLimit", P."PatientDeduct", P."PatientLimit",

  		P."YearEnd", P."Assignment", P."Signature", P."WriteOff",

  		P."PlanType", P."MonthlyDeduct", P."TrojanId", P."YearEndDay",

  		P."ChildCoverage", P."AdultCoverage", P."YoungAdultCoverage", P."Copay", 

		P."StartDate", P."EndDate", 0

  		FROM POLINS P, PTPOL PP WHERE PP."PolicyId"=:1 

		AND PP."PolIns" = P."PolIns" ';

	EXECUTE IMMEDIATE SQLStmt INTO OrigPolInsRec USING PolicyId;

	

	MergePolicy(MasterPolInsId, MasterPolInsRec, OrigPolInsRec, 

				PolicyId, pStation, pUser, iMode);



END MergePolicyAlt;

 

-- routine for merging the PTPOL records

-- 	PolInsId: POLINS id of the master record to merge to

--	mp: master partial POLINS record

--	op: original partial POLINS record

-- 	OldPolicyId: old PTPOL PolicyId of the record

-- 	NewPolicyId: new PTPOL PolicyId to use

-- 	pStation: Station Id to use for corresponding history records

-- 	pUser: User Id to use for corresponding history records

--	iMode is one of CLONEALLRECORDS = 4, 

--					CLONEALLEXCEPTDEPLIMIT = 3,

--					COPYALLKEEPLIMITDED = 2, 

--					COPYALLUSENEWLIMITDEDANDRESET = 1

--					COPYALLUSENEWLIMITDEDANDRECAL = 0

PROCEDURE mergeptpol(IN polinsid numeric, IN mp polinsrectyp, IN op polinsrectyp, IN oldpolicyid numeric, IN newpolicyid numeric, IN pstation numeric, IN puser numeric, IN imode numeric) IS

	SharedEntryId	NUMBER;

	SQLStmt   		 VARCHAR2(4000);

	nCount			NUMBER := 0;

	PatientId		NUMBER;

BEGIN

	SELECT POLICY_SHAREDENTRYID_SEQ.NEXTVAL INTO SharedEntryId FROM DUAL;

	

	-- add new PTPOL

	EXECUTE IMMEDIATE 'INSERT INTO PTPOL (SELECT 

                    :1, :2, P."Family", P."Patient", P."Policy", 

                    POLINS_PKG.AdjustLimitBalance(:3, :4, P."LimitBalance", :5, :6, :7), 	

					POLINS_PKG.AdjustDeductBalance(:8, P."DeductBalance", :9, :10), 	

					P."ResetDate", P."StartDate", P."YEResetDate", 

					P."MEResetDate", P."Deleted", trunc(sysdate), 

					:11, :12, :13, :14

					FROM PTPOL P WHERE P."PolicyId"=:15 AND P."Deleted"=0)'

		            USING NewPolicyId, PolInsId, op."HasFamilyLimit",

		            op."FamilyLimit", mp."HasFamilyLimit", mp."FamilyLimit", 

					iMode, op."FamilyDeduct", mp."FamilyDeduct", iMode,

					trunc(to_char(sysdate,'SSSSS')/60), pUser, pStation, 

					SharedEntryId, OldPolicyId;

					

	-- mark old one as deleted

	EXECUTE IMMEDIATE 'UPDATE PTPOL P SET P."Deleted"=1, 

					P."Date"=trunc(sysdate),

					P."Time"=:1,

					P."User"=:2, 

					P."StationId"=:3,

					P."SharedEntryId"=:4

					WHERE P."PolicyId"=:5 AND P."Deleted"=0'

	                USING trunc(to_char(sysdate,'SSSSS')/60), pUser, 

					pStation, SharedEntryId, OldPolicyId;

					

	

	-- add/update PTEMPLOY if necessary 

	IF mp."Employer" <> op."Employer" THEN

		SQLStmt := 'SELECT P."Patient" FROM PTPOL P WHERE P."PolicyId"=:1';

		EXECUTE IMMEDIATE SQLStmt INTO PatientId USING NewPolicyId;

		

		SQLStmt := 'SELECT COUNT(1) FROM PTEMPLOY P WHERE P."Patient"=:1

					AND P."Employer"=:2';

		EXECUTE IMMEDIATE SQLStmt INTO nCount USING PatientId, mp."Employer";

		IF nCount > 0 THEN

			EXECUTE IMMEDIATE 'UPDATE PTEMPLOY P SET P."Deleted"=0, 

					P."Date"=trunc(sysdate),

					P."Time"=:1,

					P."User"=:2, 

					P."StationId"=:3

					WHERE P."Patient"=:4 AND P."Employer"=:5 AND P."Deleted"=1'

	                USING trunc(to_char(sysdate,'SSSSS')/60), pUser, 

					pStation, PatientId, mp."Employer";

		ELSE

			-- B64769

			EXECUTE IMMEDIATE 'INSERT INTO PTEMPLOY VALUES (:1, :2, 0, :3, :4, 

					:5, :6, trunc(sysdate), :7, :8, :9, 0, NULL)'

		            USING PatientId, mp."Employer", ' ', ' ', '', ' ',

					trunc(to_char(sysdate,'SSSSS')/60), pUser, pStation;

		END IF;

		

	END IF;  

	

END MergePtPol;

 

-- routine for merging the PTDEPEND records

-- 	PolInsId: POLINS id of the master record to merge to

--	mp: master partial POLINS record

--	op: original partial POLINS record

-- 	OldPolicyId: old PTPOL PolicyId of the record

-- 	NewPolicyId: new PTPOL PolicyId to use

-- 	pStation: Station Id to use for corresponding history records

-- 	pUser: User Id to use for corresponding history records

--	iMode is one of CLONEALLRECORDS = 4, 

--					CLONEALLEXCEPTDEPLIMIT = 3,

--					COPYALLKEEPLIMITDED = 2, 

--					COPYALLUSENEWLIMITDEDANDRESET = 1

--					COPYALLUSENEWLIMITDEDANDRECAL = 0

PROCEDURE mergeptdepend(IN polinsid numeric, IN mp polinsrectyp, IN op polinsrectyp, IN oldpolicyid numeric, IN newpolicyid numeric, IN pstation numeric, IN puser numeric, IN imode numeric) IS

BEGIN

	-- add new PTDEPEND

	EXECUTE IMMEDIATE 'INSERT INTO PTDEPEND (SELECT 

                    :1, P."Patient", P."Number", P."IsCovered",

                    P."Relation", :2, :3, :4,

                    POLINS_PKG.AdjustLimitBalance(:5, :6, P."LimitBalance", :7, :8, :9), 	

					POLINS_PKG.AdjustDeductBalance(:10, P."DeductBalance", :11, :12), 	

                    trunc(sysdate), 

					:13, :14, :15, 

					P."Deleted", P."BillOrder", P."VisitBalance",

					P."MedicaidCoPay", P."StartDate", P."EndDate", P."CardVerNo",

					p."CorrectStatus"                                                     -- AX-32290

					FROM PTDEPEND P WHERE P."PolicyId"=:16 AND P."Deleted"=0)'

		            using NewPolicyId, mp."HasPatientLimit", mp."PatientLimit", 

		            mp."PatientDeduct", op."HasPatientLimit",

		            op."PatientLimit", mp."HasPatientLimit", mp."PatientLimit", 

					iMode, op."PatientDeduct", mp."PatientDeduct", iMode,

					trunc(to_char(sysdate,'SSSSS')/60),

					pUser, pStation, OldPolicyId;

	-- mark old one as deleted

	EXECUTE IMMEDIATE 'UPDATE PTDEPEND P SET P."Deleted"=1, 

					P."Date"=trunc(sysdate),

					P."Time"=:1,

					P."User"=:2, P."StationId"=:3

					WHERE P."PolicyId"=:4 AND P."Deleted"=0 '

	                USING trunc(to_char(sysdate,'SSSSS')/60),

					pUser, pStation, OldPolicyId;

END MergePtDepend;

								

-- routine for merging the DEPLIMIT records

-- 	PolInsId: POLINS id of the master record to merge to

--	mp: master partial POLINS record

--	op: original partial POLINS record

-- 	OldPolicyId: old PTPOL PolicyId of the record

-- 	NewPolicyId: new PTPOL PolicyId to use

-- 	pStation: Station Id to use for corresponding history records

-- 	pUser: User Id to use for corresponding history records

--	iMode is one of CLONEALLRECORDS = 4, 

--					CLONEALLEXCEPTDEPLIMIT = 3,

--					COPYALLKEEPLIMITDED = 2, 

--					COPYALLUSENEWLIMITDEDANDRESET = 1

--					COPYALLUSENEWLIMITDEDANDRECAL = 0

PROCEDURE mergedeplimit(IN polinsid numeric, IN mp polinsrectyp, IN op polinsrectyp, IN oldpolicyid numeric, IN newpolicyid numeric, IN pstation numeric, IN puser numeric, IN imode numeric) IS

BEGIN

	IF  iMode = CLONEALLRECORDS  THEN

		-- add new DEPLIMIT

		EXECUTE IMMEDIATE 'INSERT INTO DEPLIMIT (SELECT 

                    :1, P."Patient", P."Id", P."Category",

                    P."Limit", P."Description",

                    P."LimitBalance", 			

                    P."Deduct",

					P."DeductBalance", 		

					P."ResetDate", P."CoverageId",

					P."LimitOnPatient"

					FROM DEPLIMIT P WHERE P."PolicyId"=:2)'

		            using NewPolicyId, OldPolicyId;

		-- leave the old records around!?!

		--EXECUTE IMMEDIATE 'DELETE FROM DEPLIMIT P 

		--				WHERE P."PolicyId"=:1  '

		--              USING OldPolicyId;

	ELSE   	-- CLONEALLEXCEPTDEPLIMIT; COPYALLKEEPLIMITDED;

			-- COPYALLUSENEWLIMITDEDANDRESET; COPYALLUSENEWLIMITDEDANDRECAL

		IF	mp."ChildCoverage" > 0 AND mp."AdultCoverage" > 0  THEN

			CreateDepLimitFromCoverage(PolInsId, NewPolicyId, OldPolicyId, 

							mp."ChildCoverage", mp."AdultCoverage", mp."YoungAdultCoverage", iMode);	--E142886.8

		ELSE

			CreateDepLimitFromPolRange(PolInsId, NewPolicyId, OldPolicyId, iMode);

		END IF;	

	END IF;

	

END MergeDepLimit;



--B67952 added to update the corresponding TRX / TRXPOL records

-- 	OldPolicyId: old PTPOL PolicyId of the record

-- 	NewPolicyId: new PTPOL PolicyId to use

-- 	pStation: Station Id to use for corresponding history records

-- 	pUser: User Id to use for corresponding history records

PROCEDURE updatetrx(IN oldpolicyid numeric, IN newpolicyid numeric, IN pstation numeric, IN puser numeric) IS

  PtSQLStmt  VARCHAR2(4000);

  TYPE PtCurTyp IS REF CURSOR;

  pt_cur   PtCurTyp;

  ptId	   NUMBER(10);

  

   SQLStmt  VARCHAR2(4000);

  TYPE TxCurTyp IS REF CURSOR;

  tx_cur   TxCurTyp;

  txType	NUMBER(10);

  txId		NUMBER(10);

  txTreatment	NUMBER(10);

  auditId 	NUMBER(10):=0;

   

BEGIN



	-- safe guard the code 

 	IF OldPolicyId = 0 OR NewPolicyId = 0 THEN

 		RETURN;

 	END IF;

 	

	PtSQLStmt := 'select D."Patient" from PTDEPEND D where 

			D."PolicyId"=:1	and D."Deleted"=0';

			

	OPEN pt_cur FOR PtSQLStmt USING OldPolicyId;

	<<outer_loop>>

	LOOP

	FETCH pt_cur INTO ptId;

		EXIT outer_loop WHEN pt_cur%NOTFOUND;



		SQLStmt := 'select "Type", "Id", "Treatment" from trx 

			where "Patient"=:1 and "Type" in (1,5) and 

			"Status" <> ''C'' and	"Deleted" = 0 and 

			("PolicyId1" = :2 OR "PolicyId2" = :3 OR 

			"PolicyId3" = :4)

		    order by "Date", "Type", "Id","Treatment" ';



		OPEN tx_cur FOR SQLStmt USING ptId, OldPolicyId, 

					OldPolicyId, OldPolicyId;

		<<inner_loop>>

		LOOP

		FETCH tx_cur INTO txType, txId, txTreatment;

			EXIT inner_loop WHEN tx_cur%NOTFOUND;

    

			EXECUTE IMMEDIATE 'UPDATE TRX SET 

				"PolicyId1" = DECODE("PolicyId1",:1,:2,"PolicyId1"), 

				"PolicyId2" = DECODE("PolicyId2",:3,:4,"PolicyId2"), 

				"PolicyId3" = DECODE("PolicyId3",:5,:6,"PolicyId3"), 

				"ModifiedDate"=sysdate, "User"=:7, "StationId"=:8 

				where "Type"=:9 and "Id"=:10 and "Treatment"=:11' 

	    	   USING OldPolicyId, NewPolicyId, OldPolicyId, NewPolicyId, 

			   OldPolicyId, NewPolicyId, pUser, pStation, 

			   txType, txId, txTreatment;



			EXECUTE IMMEDIATE 'INSERT INTO HISTORY (select 

				HISTORY_HISTORY_SEQ.nextval, 2, Trx.* from trx where 

				"Type"=:1 and "Id"=:2 and "Treatment"=:3)'

				using txType, txId, txTreatment;



			IF auditId = 0 THEN

				SELECT audithis_audit_seq.NEXTVAL INTO auditId FROM dual;

				INSERT INTO audithis values ( auditId,	

					trunc(sysdate),	trunc(to_char(sysdate,'SSSSS')/60),	

					pUser, pStation, 'TRXPOL', 2 );

			END IF;

	

	    	EXECUTE IMMEDIATE 'UPDATE TRXPOL SET "PolicyId"=:1, 

	    			"Audit"=:2 where "Type"=:3 and "Id"=:4 and 

					"Treatment"=:5 and "PolicyId"=:6' 

			       USING NewPolicyId, auditId, txType, txId, 

				   txTreatment, OldPolicyId;

			

			-- update allocate as well	   

			IF txType = 1 THEN

	    		EXECUTE IMMEDIATE 'UPDATE ALLOCATE SET "PolicyId"=:1, 

	    				"User"=:2 where "TrxType"=:3 and "TrxId"=:4 and 

						"TrxTreatment"=:5 and "PayType" in (4,7) and 

						"PolicyId"=:6' 

				       USING NewPolicyId, pUser, txType, txId, 

					   txTreatment, OldPolicyId;

			END IF;

			

     

	  END LOOP;

	  CLOSE tx_cur;



  END LOOP;

  CLOSE pt_cur;

	

END UpdateTrx;



							

 

-- routine for adjusting the limit balance

-- 	OrigHasLimit: original has limit flag

--	OrigLimitAmt: original limit amount

--	OrigLimitBal: original limit balance

--	NewHasLimit: current has limit flag

--	NewLimitAmt: current limit amount

--	iMode is one of CLONEALLRECORDS = 4, 

--					CLONEALLEXCEPTDEPLIMIT = 3,

--					COPYALLKEEPLIMITDED = 2, 

--					COPYALLUSENEWLIMITDEDANDRESET = 1

--					COPYALLUSENEWLIMITDEDANDRECAL = 0

FUNCTION adjustlimitbalance(orighaslimit numeric, origlimitamt numeric, origlimitbal numeric, newhaslimit numeric, newlimitamt numeric, imode numeric) RETURN numeric IS

BEGIN



	IF  NewHasLimit = 0 THEN

		-- no limit set; N/A

		RETURN 0;

	ELSIF  OrigHasLimit = 0 THEN

		-- no limit before, now it does

		RETURN NewLimitAmt;

	ELSIF  iMode = CLONEALLRECORDS OR

			iMode = CLONEALLEXCEPTDEPLIMIT  THEN

		-- cloning, should not be affected

		RETURN OrigLimitBal;

	ELSIF  iMode = COPYALLKEEPLIMITDED  THEN

		-- keep current balance, as long as it's not over the new limit

		IF  OrigLimitBal > NewLimitAmt THEN

			RETURN NewLimitAmt;

		ELSE

			RETURN OrigLimitBal;

		END IF;

	ELSIF  iMode = COPYALLUSENEWLIMITDEDANDRESET  THEN

		-- default to the new limit amount

		RETURN NewLimitAmt;

	ELSE   -- COPYALLUSENEWLIMITDEDANDRECAL

		-- need to recalculate the balance

		IF  OrigLimitAmt > NewLimitAmt THEN

			-- limit amount lower, decrement the balance accordingly

			IF  OrigLimitBal > (OrigLimitAmt-NewLimitAmt) THEN

				RETURN OrigLimitBal-(OrigLimitAmt-NewLimitAmt);

			ELSE

				RETURN 0;

			END IF;

		ELSE

			-- limit amount is more, increase the balance accordingly 

			IF  OrigLimitBal+(NewLimitAmt-OrigLimitAmt) > NewLimitAmt THEN

				RETURN NewLimitAmt;

			ELSE

				RETURN OrigLimitBal+(NewLimitAmt-OrigLimitAmt);

			END IF;

		END IF;

	END IF;

	

END;

				

-- routine for adjusting the deduct balance

-- 	OrigDeductAmt: original deductible amount

-- 	OrigDeductBal: original deductible balance

-- 	NewDeductAmt: new deductible amount

--	iMode is one of CLONEALLRECORDS = 4, 

--					CLONEALLEXCEPTDEPLIMIT = 3,

--					COPYALLKEEPLIMITDED = 2, 

--					COPYALLUSENEWLIMITDEDANDRESET = 1

--					COPYALLUSENEWLIMITDEDANDRECAL = 0

FUNCTION adjustdeductbalance(origdeductamt numeric, origdeductbal numeric, newdeductamt numeric, imode numeric) RETURN numeric IS



BEGIN

	IF  NewDeductAmt = 0 THEN

		-- no deductible set; N/A

		RETURN 0;

	ELSIF  OrigDeductAmt = 0 THEN

		-- no deductible before, now it does

		RETURN NewDeductAmt;

	ELSIF  iMode = CLONEALLRECORDS OR

			iMode = CLONEALLEXCEPTDEPLIMIT  THEN

		-- cloning, should not be affected

		RETURN OrigDeductBal;

	ELSIF  iMode = COPYALLKEEPLIMITDED  THEN

		-- keep current balance, as long as it's not over the new deductible

		--		or deductible balance is already zero(!?!)

		IF  OrigDeductBal > 0 AND 

				OrigDeductBal > NewDeductAmt THEN

			RETURN NewDeductAmt;

		ELSE

			RETURN OrigDeductBal;

		END IF;

	ELSIF  iMode = COPYALLUSENEWLIMITDEDANDRESET  THEN

		-- default to the new deductible amount

		RETURN NewDeductAmt;

	ELSE   -- COPYALLUSENEWLIMITDEDANDRECAL

		-- need to recalculate the balance

		IF  OrigDeductBal > 0   THEN

			IF  OrigDeductAmt > NewDeductAmt  THEN

				-- deduct amount lower, decrement the balance accordingly

				IF  OrigDeductBal > (OrigDeductAmt-NewDeductAmt) THEN

					RETURN OrigDeductBal-(OrigDeductAmt-NewDeductAmt);

				ELSE

					RETURN 0;

				END IF;

			ELSE

				-- deduct amount is more, increase the balance accordingly 

				IF  OrigDeductBal+(NewDeductAmt-OrigDeductAmt) > NewDeductAmt THEN

					RETURN NewDeductAmt;

				ELSE

					RETURN OrigDeductBal+(NewDeductAmt-OrigDeductAmt);

				END IF;

			END IF;

		ELSE 

			--	deductible balance is already zero(!?!), can't adjust

			RETURN 0;

		END IF;

	END IF;

	

END;



-- routine to create deplimit from coverage template

-- 	PolInsId: POLINS id of the master record to merge to

-- 	NewPolicyId: new PTPOL PolicyId

-- 	OldPolicyId: old PTPOL PolicyId

-- 	ChildCoverage: Coverage Id for new policy

-- 	AdultCoverage: Coverage Id for new policy

-- 	YoungAdultCoverage: Coverage Id for new policy (E142886.8)

--	iMode is one of CLONEALLRECORDS = 4, 

--					CLONEALLEXCEPTDEPLIMIT = 3,

--					COPYALLKEEPLIMITDED = 2, 

--					COPYALLUSENEWLIMITDEDANDRESET = 1

--					COPYALLUSENEWLIMITDEDANDRECAL = 0

PROCEDURE createdeplimitfromcoverage(IN polinsid numeric, IN newpolicyid numeric, IN oldpolicyid numeric, IN childcoverage numeric, IN adultcoverage numeric, IN youngadultcoverage numeric, IN imode numeric) IS

BEGIN

	-- add new DEPLIMIT for category limits

	-- E81850 - no change needed, because of DISTINCT clause, and all fields in question are the same for all age ranges

	-- E85560; E142886.8

	EXECUTE IMMEDIATE 'INSERT INTO DEPLIMIT (SELECT 

				DISTINCT P."PolicyId", D."Patient", 0, 

				C."Category", C."CatLimit", :1,

                C."CatLimit", C."CatDeduct", C."CatDeduct",

				P."YEResetDate", C."Coverage", C."LimitOnPatient"

				FROM PTPOL P, PTDEPEND D, COVERIT C, POLRIDER PR WHERE 

				P."PolicyId"=:2 AND P."PolicyId"=D."PolicyId"

				AND P."PolIns" = PR."PolIns" (+)

				AND D."Deleted"=0 

				AND C."Coverage" IN (:3, :4, :5, PR."RiderChildCoverage", PR."RiderAdultCoverage", PR."RiderYoungAdultCoverage")

				AND C."HasCategory"=1 )'

		        using 'Category', NewPolicyId, ChildCoverage, AdultCoverage, YoungAdultCoverage;

	-- add new DEPLIMIT for item limits

	EXECUTE IMMEDIATE 'INSERT INTO DEPLIMIT (SELECT 

				DISTINCT P."PolicyId", D."Patient", C."Item", 

				:1, C."ItemLimit", C."Description",

                C."ItemLimit", C."ItemDeduct", C."ItemDeduct",

				P."YEResetDate", C."Coverage", 0

				FROM PTPOL P, PTDEPEND D, COVERIT C, POLRIDER PR WHERE 

				P."PolicyId"=:2 AND P."PolicyId"=D."PolicyId"

				AND P."PolIns" = PR."PolIns" (+)

				AND D."Deleted"=0 

				AND C."Coverage" IN (:3, :4, :5, PR."RiderChildCoverage", PR."RiderAdultCoverage", PR."RiderYoungAdultCoverage")

				AND (C."HasItemLimit" = 1 OR C."ItemDeduct" > 0) )'

		        using '      ', NewPolicyId, ChildCoverage, AdultCoverage, YoungAdultCoverage;

END CreateDepLimitFromCoverage;



-- routine to create deplimit from PolRange records

-- 	PolInsId: POLINS id of the master record to merge to

-- 	NewPolicyId: new PTPOL PolicyId

-- 	OldPolicyId: old PTPOL PolicyId

--	iMode is one of CLONEALLRECORDS = 4, 

--					CLONEALLEXCEPTDEPLIMIT = 3,

--					COPYALLKEEPLIMITDED = 2, 

--					COPYALLUSENEWLIMITDEDANDRESET = 1

--					COPYALLUSENEWLIMITDEDANDRECAL = 0

PROCEDURE createdeplimitfrompolrange(IN polinsid numeric, IN newpolicyid numeric, IN oldpolicyid numeric, IN imode numeric) IS

BEGIN

	-- add new DEPLIMIT for category limits

	EXECUTE IMMEDIATE 'INSERT INTO DEPLIMIT (SELECT 

				DISTINCT P."PolicyId", D."Patient", 0, 

				R."Category", R."CatLimit", :1,

                R."CatLimit", R."CatDeduct", R."CatDeduct",

				P."YEResetDate", 0, R."LimitOnPatient"

				FROM PTPOL P, PTDEPEND D, POLRANGE R WHERE 

				P."PolicyId"=:2 AND P."PolicyId"=D."PolicyId"

				AND D."Deleted"=0 AND R."PolIns"=P."PolIns"

				AND R."HasCategory"=1 )'

		        using 'Category', NewPolicyId;

	-- add new DEPLIMIT for item limits

	EXECUTE IMMEDIATE 'INSERT INTO DEPLIMIT (SELECT 

				DISTINCT P."PolicyId", D."Patient", R."Id", 

				:1, R."ItemLimit", R."Description",

                R."ItemLimit", R."ItemDeduct", R."ItemDeduct",

				P."YEResetDate", 0, 0

				FROM PTPOL P, PTDEPEND D, POLRANGE R WHERE 

				P."PolicyId"=:2 AND P."PolicyId"=D."PolicyId"

				AND D."Deleted"=0 AND R."PolIns"=P."PolIns"

				AND (R."HasItemLimit" = 1 OR R."ItemDeduct" > 0) )'

		        using '      ', NewPolicyId;

END CreateDepLimitFromPolRange;







-- B65979 routines for category and item limits

-- B80125 - changed to be by policy

--***********************************************************

PROCEDURE insertcatlimits(IN patientid numeric, IN policyholder numeric, IN policyid numeric) IS

BEGIN

	INSERT INTO DEPLIMIT (SELECT DISTINCT POLICY."PolicyId", PatientId, 

		0, POLRANGE."Category", POLRANGE."CatLimit", 'Category', 

		POLRANGE."CatLimit", POLRANGE."CatDeduct", POLRANGE."CatDeduct",  

		POLICY."YEResetDate", 0, POLRANGE."LimitOnPatient"  

		FROM POLRANGE, POLICY WHERE POLICY."PolIns" = POLRANGE."PolIns" 

		AND POLICY."Patient" = PolicyHolder AND POLICY."ChildCoverage" = 0 

		AND POLICY."PolicyId" = PolicyId

		AND POLICY."AdultCoverage" = 0 AND POLRANGE."HasCategory" = 1);

END InsertCatLimits;





    

--***********************************************************

PROCEDURE insertitemlimits(IN patientid numeric, IN policyholder numeric, IN policyid numeric) IS

BEGIN

	INSERT INTO DEPLIMIT (SELECT POLICY."PolicyId", PatientId, POLRANGE."Id", 

		'     ', POLRANGE."ItemLimit", POLRANGE."Description", 

		POLRANGE."ItemLimit", POLRANGE."ItemDeduct", POLRANGE."ItemDeduct", 

		POLICY."YEResetDate", 0, 0 

		FROM POLRANGE, POLICY WHERE POLICY."PolIns" = POLRANGE."PolIns" 

		AND POLICY."Patient" = PolicyHolder AND POLICY."ChildCoverage" = 0 

		AND POLICY."PolicyId" = PolicyId

		AND POLICY."AdultCoverage" = 0 

		AND (POLRANGE."HasItemLimit" = 1 OR POLRANGE."ItemDeduct" > 0));

END InsertItemLimits;





    

--***********************************************************

-- E81850 - no change needed, because of DISTINCT clause, and all fields in question are the same for all age ranges

-- E85560; E142886.8

PROCEDURE insertcatlimitsusingtempl(IN patientid numeric, IN policyholder numeric, IN policyid numeric) IS

BEGIN

	INSERT INTO DEPLIMIT (SELECT DISTINCT POLICY."PolicyId", PatientId, 0, 

		COVERIT."Category", COVERIT."CatLimit", 'Category', COVERIT."CatLimit", 

		COVERIT."CatDeduct", COVERIT."CatDeduct", POLICY."YEResetDate", 

		COVERIT."Coverage", COVERIT."LimitOnPatient"  

		FROM COVERIT, POLICY, POLRIDER WHERE POLICY."Patient" = PolicyHolder 

		AND POLICY."ChildCoverage" <> 0 AND POLICY."AdultCoverage" <> 0 

		AND POLICY."PolicyId" = PolicyId

		AND POLICY."PolIns" = POLRIDER."PolIns" (+)

		AND COVERIT."Coverage" IN ( POLICY."ChildCoverage", POLICY."AdultCoverage", POLICY."YoungAdultCoverage", 

		POLRIDER."RiderChildCoverage", POLRIDER."RiderAdultCoverage", POLRIDER."RiderYoungAdultCoverage" ) 

		AND COVERIT."HasCategory" = 1);

END InsertCatLimitsUsingTempl;





    

--***********************************************************

-- E81850 - no change needed, because of DISTINCT clause, and all fields in question are the same for all age ranges

-- E85560; E142886.8

PROCEDURE insertitemlimitsusingtempl(IN patientid numeric, IN policyholder numeric, IN policyid numeric) IS

BEGIN

	INSERT INTO DEPLIMIT (SELECT DISTINCT POLICY."PolicyId", PatientId, COVERIT."Item", 

	'     ', COVERIT."ItemLimit", COVERIT."Description", COVERIT."ItemLimit", 

	COVERIT."ItemDeduct", COVERIT."ItemDeduct", POLICY."YEResetDate", 

	COVERIT."Coverage", 0  

	FROM COVERIT, POLICY, POLRIDER WHERE POLICY."Patient" = PolicyHolder 

	AND POLICY."ChildCoverage" <> 0 AND POLICY."AdultCoverage" <> 0 

	AND POLICY."PolicyId" = PolicyId

	AND POLICY."PolIns" = POLRIDER."PolIns" (+)

	AND COVERIT."Coverage" IN ( POLICY."ChildCoverage", POLICY."AdultCoverage", POLICY."YoungAdultCoverage", 

	POLRIDER."RiderChildCoverage", POLRIDER."RiderAdultCoverage", POLRIDER."RiderYoungAdultCoverage" ) 

	AND (COVERIT."HasItemLimit" = 1 OR COVERIT."ItemDeduct" > 0));

END InsertItemLimitsUsingTempl;





    

/**************************************************************************/



-- B69753 merge routine for EMPLOYER

-- 	pStation: Station Id to use for corresponding history records

-- 	pUser: User Id to use for corresponding history records

PROCEDURE employermergeprocess(IN pstation numeric, IN puser numeric) IS

	SQLStmt   		 VARCHAR2(4000);

	EmployerCur	   EmployerCurTyp;

	EmployerRec		EmployerRecTyp;

	AuditId 			NUMBER:=0;

	SharedEntryId	NUMBER:=0;

  

BEGIN

	-- gather distinct info for EMPLOYER with corresponding #count

	SQLStmt := 'SELECT 

		NVL(TRIM(E."Name"),'' ''), 

		NVL(TRIM(E."Address1"),'' ''),

  		NVL(TRIM(E."Address2"), '' ''),

  		NVL(TRIM(E."City"), '' ''), 

  		NVL(TRIM(E."Province"), '' ''), 

  		NVL(TRIM(E."Postal"), '' ''), 

  		NVL(TRIM(E."Area"), '' ''), 

  		NVL(TRIM(E."Telephone"), '' ''), 

  		NVL(TRIM(E."Ext"), '' ''), 

  		NVL(TRIM(E."AddressOther"), '' ''), 

		COUNT(1)

  		FROM EMPLOYER E WHERE E."Deleted" = 0

		GROUP BY 

		NVL(TRIM(E."Name"),'' ''), 

		NVL(TRIM(E."Address1"),'' ''),

  		NVL(TRIM(E."Address2"), '' ''),

  		NVL(TRIM(E."City"), '' ''), 

  		NVL(TRIM(E."Province"), '' ''), 

  		NVL(TRIM(E."Postal"), '' ''), 

  		NVL(TRIM(E."Area"), '' ''), 

  		NVL(TRIM(E."Telephone"), '' ''), 

  		NVL(TRIM(E."Ext"), '' ''), 

  		NVL(TRIM(E."AddressOther"), '' '')';



	OPEN EmployerCur FOR SQLStmt;

	<<distinct_employer_loop>>

   LOOP

    	-- for each distinct EMPLOYER

        FETCH EmployerCur INTO EmployerRec;

        EXIT distinct_employer_loop WHEN EmployerCur%NOTFOUND;

    

        if EmployerRec.Count > 1 then

				IF AuditId = 0 THEN

					SELECT audithis_audit_seq.NEXTVAL INTO AuditId FROM dual;

					INSERT INTO audithis values ( AuditId,	

						trunc(sysdate),	trunc(to_char(sysdate,'SSSSS')/60),	

						pUser, pStation, 'EMPLOYER', 2 );

				END IF;

				

				IF SharedEntryId = 0 THEN

					SELECT POLICY_SHAREDENTRYID_SEQ.NEXTVAL INTO SharedEntryId FROM DUAL;

				END IF;



        	-- only need to call merge if there'r more than one

	        MergeDistinctEmployer(EmployerRec, pStation, pUser, AuditId, SharedEntryId);

	        

        end if;

	END LOOP;

   CLOSE EmployerCur;

   

END EmployerMergeProcess;



/**************************************************************************/



-- B69753 merge routine for all EMPLOYER's having similar info as EmployerRec passed in

-- 	e: partial EMPLOYER record to be merged

-- 	pStation: Station Id to use for corresponding history records

-- 	pUser: User Id to use for corresponding history records

--		AuditId: for auditing

--		SharedEntryId: for auditing

PROCEDURE mergedistinctemployer(IN e employerrectyp, IN pstation numeric, IN puser numeric, IN auditid numeric, IN sharedentryid numeric) IS

	SQLStmt   		 VARCHAR2(4000);

	EmployerCur	  	EmployerCurTyp;

	MasterEmployerId 	NUMBER := 0;

	EmployerId 		NUMBER := 0;

  

BEGIN

	-- select all EMPLOYER's matching the pass in distinct information

	SQLStmt := 'SELECT E."Employer"

		FROM EMPLOYER E WHERE E."Deleted" = 0 AND 

		NVL(TRIM(E."Name"), '' '')=NVL(TRIM(:1), '' '') AND 

		NVL(TRIM(E."Address1"), '' '')=NVL(TRIM(:2), '' '') AND 

		NVL(TRIM(E."Address2"), '' '')=NVL(TRIM(:3), '' '') AND 

		NVL(TRIM(E."City"), '' '')=NVL(TRIM(:4), '' '') AND 

		NVL(TRIM(E."Province"), '' '')=NVL(TRIM(:5), '' '') AND 

		NVL(TRIM(E."Postal"), '' '')=NVL(TRIM(:6), '' '') AND 

		NVL(TRIM(E."Area"), '' '')=NVL(TRIM(:7), '' '') AND 

		NVL(TRIM(E."Telephone"), '' '')=NVL(TRIM(:8), '' '') AND 

		NVL(TRIM(E."Ext"), '' '')=NVL(TRIM(:9), '' '') AND 

		NVL(TRIM(E."AddressOther"), '' '')=NVL(TRIM(:10), '' '')

		ORDER BY E."Employer"';



	OPEN EmployerCur FOR SQLStmt using e."Name", e."Address1", e."Address2", 

		e."City", e."Province", e."Postal", e."Area", e."Telephone", 

		e."Ext", e."AddressOther";

	<<employer_loop>>

   LOOP

    	-- for each EMPLOYER

        FETCH EmployerCur INTO EmployerId;

        EXIT employer_loop WHEN EmployerCur%NOTFOUND;

    

        IF MasterEmployerId = 0 THEN

		     	-- with first one being the master

			  	MasterEmployerId := EmployerId;

        ELSE

        		-- only continue to merge

				MergeEmployer(MasterEmployerId, EmployerId, pStation, 

								pUser, AuditId, SharedEntryId);

        END IF;

	END LOOP;

   CLOSE EmployerCur;

    

   COMMIT;



END MergeDistinctEmployer;



/**************************************************************************/



-- routine for merging the two given EMPLOYER records

-- 	MasterEmployerId: EMPLOYER id of the master record to merge to

-- 	EmployerId: EMPLOYER id of the record to merge from

-- 	pStation: Station Id to use for corresponding history records

-- 	pUser: User Id to use for corresponding history records

--		AuditId: for auditing

--		SharedEntryId: for auditing

PROCEDURE mergeemployer(IN masteremployerid numeric, IN employerid numeric, IN pstation numeric, IN puser numeric, IN auditid numeric, IN sharedentryid numeric) IS

	SQLStmt   			 VARCHAR2(4000);

	MasterEmployerRec	EmployerRecTyp;

BEGIN

	

	-- retrieve the policy info for the master record; E66122

	SQLStmt := 'SELECT E."Name", E."Address1", E."Address2", 

  		E."City", E."Province", E."Postal", E."Area",

  		E."Telephone", E."Ext", E."AddressOther", 0

  		FROM EMPLOYER E WHERE E."Employer"=:1';

	EXECUTE IMMEDIATE SQLStmt INTO MasterEmployerRec USING MasterEmployerId;

	

	-- update all PTEMPLOY's linked to old employer

	EXECUTE IMMEDIATE 'UPDATE PTEMPLOY P SET 

				P."Employer"=:1,

				P."Area"=:2,

				P."Tel"=:3,

				P."Ext"=:4,

				P."Date"=trunc(sysdate),

				P."Time"=:5,

				P."User"=:6, 

				P."StationId"=:7,

				P."Deleted" = 0

				WHERE P."Employer"=:8 AND 

				NOT EXISTS (SELECT 1 FROM PTEMPLOY P2 WHERE 

				P2."Patient"=P."Patient" AND P2."Employer" = :9)' 

					USING MasterEmployerId, MasterEmployerRec."Area",

					MasterEmployerRec."Telephone", MasterEmployerRec."Ext",

					trunc(to_char(sysdate,'SSSSS')/60), 

					pUser, pStation, EmployerId, MasterEmployerId;



	EXECUTE IMMEDIATE 'UPDATE PTEMPLOY P SET 

				P."Deleted"=1,

				P."Date"=trunc(sysdate),

				P."Time"=:1,

				P."User"=:2, 

				P."StationId"=:3

				WHERE P."Employer"=:4 AND P."Deleted"=0' 

					USING trunc(to_char(sysdate,'SSSSS')/60), 

					pUser, pStation, EmployerId;

    

	-- update all POLINS's linked to old employer

	EXECUTE IMMEDIATE 'UPDATE POLINS P SET 

					P."Employer"=:1, 

					P."Date"=trunc(sysdate),

					P."Time"=:2,

					P."User"=:3, 

					P."StationId"=:4,

					P."SharedEntryId"=:5

					WHERE P."Employer"=:6 AND P."Deleted" = 0'

	               USING MasterEmployerId, trunc(to_char(sysdate,'SSSSS')/60), 

	               pUser, pStation, SharedEntryId, EmployerId;



	-- update old employer to be deleted						

	EXECUTE IMMEDIATE 'UPDATE EMPLOYER E SET 

					E."Deleted"=1,

					E."Audit"=:1

					WHERE E."Employer"=:2'

	               USING AuditId, EmployerId;

    

END MergeEmployer;







/**************************************************************************/



-- 	E72587 - routine to add a policy	

-- 	HolderId: Patient id of the policy holder

--		FamilyId: Family id of the policy holder

-- 	PolInsId: id of the Benefit Plan to add a policy for

-- 	StartDate: effective date of policy (can be NULL)

-- 	EndDate: expiry date of policy (can be NULL)

--		UserId: id of User who is adding the policy

--		StationId: id of station that policy is being added from

--    AddDepends: if 1, add dependents to policy, if 0, do not. (S87161)

-- 		OrigPolicyId: if > 0, ensure depenants match original policy (for renew or transfer)



PROCEDURE addpolicy(IN holderid numeric, IN familyid numeric, IN polinsid numeric, IN subscribernum character varying, IN startdate timestamp without time zone, IN enddate timestamp without time zone, IN userid numeric, IN stationid numeric, IN adddepends numeric, IN origpolicyid numeric, OUT policyid numeric) IS



	PolInsRec				POLINS%ROWTYPE;

   v_Relation				PTDEPEND."Relation"%TYPE;

   v_AuditId				AUDITHIS."Audit"%TYPE;

   v_YEResetDate			PTPOL."YEResetDate"%TYPE;



	v_PtPolCount			NUMBER;





	CURSOR DependantsCur(GuarantorId NUMBER)

		IS 

	SELECT G."Patient" FROM PTGUAR G, PATIENT P 

	WHERE G."RespPatient" = GuarantorId AND G."Deleted" = 0

	  AND G."Patient" = P."Patient" AND P."Deleted" = 0;

	

BEGIN



	-- Find out if PTPOL records exist

	SELECT count(1) 

	  INTO v_PtPolCount

	  FROM PTPOL

	 WHERE "PolIns" = PolInsId

		AND "Patient" = HolderId

		AND "Deleted" = 0;

	

	IF v_PtPolCount = 0 THEN

	

		-- Get POLINS record

		BEGIN

			SELECT *

			  INTO PolInsRec

			  FROM POLINS

			 WHERE "PolIns" = PolInsId;

		EXCEPTION WHEN NO_DATA_FOUND THEN

			RETURN;

		END;

		

		

		-- Calculate Year End Reset Date

		begin

			v_YEResetDate := TO_DATE(TO_CHAR(sysdate, 'YYYY') || TO_CHAR(PolInsRec."YearEnd", '09') || TO_CHAR(PolInsRec."YearEndDay", '09'), 'YYYYMMDD');

		exception when others then

			IF v_YEResetDate IS NULL AND PolInsRec."YearEnd" = 2 AND PolInsRec."YearEndDay" = 29 THEN

				v_YEResetDate := TO_DATE(TO_CHAR(sysdate, 'YYYY') || '0228', 'YYYYMMDD');						

			END IF;

		end;

		

		v_YEResetDate := v_YEResetDate + 1;

		

		IF v_YEResetDate > trunc(sysdate) THEN

			v_YEResetDate := TO_DATE(TO_CHAR(TO_NUMBER(TO_CHAR(v_YEResetDate, 'YYYY')) - 1, '0009') || TO_CHAR(v_YEResetDate, 'MM') || TO_CHAR(v_YEResetDate, 'DD'), 'YYYYMMDD');

		END IF;

		

		

		-- Add a PTPOL

		SELECT ptpol_policyid_seq.NEXTVAL

		  INTO PolicyId

		  FROM DUAL;





		INSERT INTO PTPOL ("PolicyId", "PolIns", "Family", "Patient",

			"Policy", "LimitBalance", "DeductBalance", "ResetDate", "StartDate",

			"YEResetDate", "MEResetDate", "Deleted", "Date", "Time", "User", 

			"StationId", "SharedEntryId")

		VALUES(PolicyId, 				-- PolicyId

			PolInsRec."PolIns", 			-- PolIns

			FamilyId,			 			-- Family

			HolderId,						-- Patient

			SubscriberNum,	 				-- Policy

			DECODE(PolInsRec."HasFamilyLimit", 1, PolInsRec."FamilyLimit", 0),	-- LimitBalance

			PolInsRec."FamilyDeduct", 	-- DeductBalance										--B80493

			EndDate, 						-- ResetDate

			StartDate,						-- StartDate

			v_YEResetDate,					-- YEResetDate

			NULL, 							-- MEResetDate

			0, 								-- Deleted

			trunc(sysdate), 				-- Date

			TO_NUMBER(TO_CHAR(SysDate, 'HH24'))*60+TO_NUMBER(TO_CHAR(SysDate, 'MI')), 	-- Time

			UserId, 								-- User

			StationId, 								-- StationId

			POLICY_SharedEntryId_SEQ.NEXTVAL);	-- SharedEntryId





		-- Update insured patient to be a policy holder

		SELECT audithis_audit_seq.NEXTVAL INTO v_AuditId FROM dual;

		

		INSERT INTO audithis

			  VALUES (v_AuditId, TRUNC (SYSDATE), 0, UserId, StationId, 'PTGUAR', 2);



		UPDATE PTGUAR SET "IsPolicyGuarantor" = 1, "Audit" = v_AuditId

			WHERE "RespPatient" = HolderId

			AND "Deleted" = 0 AND "IsPolicyGuarantor" = 0;









		-- Add PTDEPEND Records for all dependants

		FOR DependantsRec IN DependantsCur(HolderId) 

		LOOP

		

			-- S87161 - add all dependents, or just the holder

			-- B101882 - changed to always call AddPolicyDependant to create the PTDEPEND records passing AddDepends to the procedure to 

			--	indicate whether the patient is covered on the policy

--			IF AddDepends = 1 OR DependantsRec."Patient" = HolderId THEN

			

				-- Try to set Relationship from a previous dependancy

				BEGIN

					SELECT "Relation"

					  INTO v_Relation

					  FROM PTDEPEND D, PTPOL P

					 WHERE D."Patient" = DependantsRec."Patient"

						AND D."PolicyId" = P."PolicyId"

						AND P."Patient" = HolderId

						AND ROWNUM = 1;

				EXCEPTION WHEN NO_DATA_FOUND THEN

					IF HolderId = DependantsRec."Patient" THEN

						v_Relation := 0; -- self

					ELSE

						v_Relation := 4; -- other

					END IF;

				END;





				-- Add dependant for this policy

				-- B101882 pass AddDepends to AddPoilcyDependant for new IsCovered parameter

				AddPolicyDependant(PolicyId, HolderId, DependantsRec."Patient",

					PolInsRec."HasPatientLimit", PolInsRec."PatientLimit", 

					PolInsRec."PatientDeduct", v_Relation,

					UserId, StationId, AddDepends);

					

--			END IF;	-- B100822



		END LOOP;

		

		

		-- B116767 - now make sure any dependants that were not covered by the original policy are not covered by this new policy

		IF OrigPolicyId > 0 THEN

			UPDATE PTDEPEND SET "IsCovered"=0 WHERE "PolicyId"=PolicyId AND "Patient" NOT IN (select "Patient" from ptdepend p2 where p2."PolicyId"=OrigPolicyId and p2."Deleted"=0 and p2."IsCovered"=1);

		END IF;

		

		

		-- E143071.4 - add category family maximum entry if needed

		INSERT INTO FAMLIMIT (SELECT DISTINCT PO."PolicyId", CI."Coverage", 

			CI."Category", 'Category', CI."CatFamilyLimit", CI."LimitOnPatient", 

			CI."CatFamilyLimit", PO."YEResetDate" 

			FROM COVERIT CI, POLICY PO, POLRIDER PR WHERE 

			PO."PolicyId" = PolicyId 

			AND PO."Deleted" = 0 

			AND PO."ChildCoverage" <> 0 

			AND PO."AdultCoverage" <> 0 

			AND PO."PolIns" = PR."PolIns" (+) 

			AND CI."Coverage" IN (PO."ChildCoverage", PO."AdultCoverage", PO."YoungAdultCoverage", 

			PR."RiderChildCoverage", PR."RiderChildCoverage", PR."RiderYoungAdultCoverage") 

			AND CI."HasCatFamilyLimit" = 1);

	

	END IF;



END AddPolicy;









/**************************************************************************/



-- 	E72587 - routine to hook a patient up to his guarantor's policies				

--	B101882 - Added IsCovered parameter to indicate whether patients should be covered on the policies

-- 	GuarantorId: Patient id of the guarantor

-- 	PatientId: Patient id of the patient

--		UserId: id of User who is adding the policy

--		StationId: id of station that policy is being added from

--		IsCovered: whether the patient is covered on the policy

PROCEDURE addguarantordependant(IN guarantorid numeric, IN patientid numeric, IN relationship numeric, IN userid numeric, IN stationid numeric, IN iscovered numeric DEFAULT polins_pkg.ptdependiscoveredyes) IS

  

   CURSOR PolicyCur (GuarantorId NUMBER)

    IS

   SELECT * FROM POLICY WHERE "Patient" = GuarantorId AND "Deleted" = 0;



BEGIN



	-- loop through all the guarantor's policies

	-- and hook them to the patient if it hasn't already been done.

	FOR PolicyRec IN PolicyCur(GuarantorId)

	LOOP

	

		-- B101882 Pass IsCovered parameter on to AddPolicyDependant routine

		AddPolicyDependant(PolicyRec."PolicyId", GuarantorId, PatientId, 

			PolicyRec."HasPatientLimit", PolicyRec."PatientLimit", 

			PolicyRec."PatientDeduct", Relationship, 

			UserId, StationId, IsCovered);

			

	END LOOP;



END AddGuarantorDependant;





/**************************************************************************/



-- E72587 - routine to hook a patient up as a dependant for a policy

-- B101882 - Added IsCovered parameter to indicate whether patients should be covered on the policies

-- 	PolicyId: policy to use

-- 	GuarantorId: Patient id of the guarantor

-- 	PatientId: Patient id of the patient

--		UserId: id of User who is adding the policy

--		StationId: id of station that policy is being added from

--		IsCovered: whether the patient is covered on the policy. 0 = not covered, 1 = covered, -1 = not covered unless already in as covered

PROCEDURE addpolicydependant(IN policyid numeric, IN guarantorid numeric, IN patientid numeric, IN haspatientlimit numeric, IN patientlimit numeric, IN patientdeduct numeric, IN relationship numeric, IN userid numeric, IN stationid numeric, IN iscovered numeric DEFAULT polins_pkg.ptdependiscoveredyes) IS



   v_PtDependDeleted		PTDEPEND."Deleted"%TYPE;

	v_PtDependIsCovered		PTDEPEND."IsCovered"%TYPE;	-- B101882



BEGIN



	-- Find out if PTDEPEND records exist

	-- B99327 - find out if record is deleted, and restore it if it is

	BEGIN

		SELECT "Deleted"

			, "IsCovered"								-- B101882

		  INTO v_PtDependDeleted

		  , v_PtDependIsCovered							-- B101882

		  FROM PTDEPEND

		 WHERE "PolicyId" = PolicyId

			AND "Patient" = PatientId;

	EXCEPTION WHEN NO_DATA_FOUND THEN

		v_PtDependDeleted := NULL;

		v_PtDependIsCovered := 0;						-- B101882

	END;

	

	-- B99327 - delete the old record if it exists

	IF v_PtDependDeleted = 1 THEN

	

		DELETE FROM PTDEPEND WHERE "PolicyId" = PolicyId AND "Patient" = PatientId;

		v_PtDependDeleted := NULL;

		

	END IF;



	-- Add PTDEPND if it doesn't already exist

	IF v_PtDependDeleted IS NULL THEN



		-- Add PTDEPEND

		INSERT INTO PTDEPEND ("PolicyId", "Patient", "Number", "IsCovered",

			"Relation", "HasPatientLimit", "PatientLimit", "PatientDeduct",

			"LimitBalance", "DeductBalance", "Date", "Time", "User", "StationId",

			"Deleted", "BillOrder", "VisitBalance", "MedicaidCoPay", "StartDate", 

			"EndDate", "CardVerNo", "CorrectStatus")

		VALUES(PolicyId,						-- PolicyId

			PatientId,							-- Patient

			0,										-- Number

			DECODE(IsCovered,PTDEPENDISCOVEREDNO,0,PTDEPENDISCOVEREDYES,1,PTDEPENDISCOVEREDNOIFNOTSET,0,0),		-- IsCovered		-- B101882

			Relationship,						-- Relation

			HasPatientLimit,					-- HasPatientLimit

			PatientLimit,						-- PatientLimit

			PatientDeduct,						-- PatientDeduct

			PatientLimit,						-- LimitBalance

			PatientDeduct,						-- DeductBalance									-- B80493

			trunc(sysdate), 					-- Date

			TO_NUMBER(TO_CHAR(SysDate, 'HH24'))*60+TO_NUMBER(TO_CHAR(SysDate, 'MI')), 	-- Time

			UserId, 								-- User

			StationId,							-- StationId

			0,										-- Deleted

			0,										-- BillOrder

			0,										-- LimitBalance

			0,										-- MedicaidCoPay

			NULL,									-- StartDate

			NULL, 								-- EndDate

			'',                                 -- CardVerNo

			0);									-- CorrectStatus

	

		-- Add DEPLIMIT records

		DELETE FROM DEPLIMIT WHERE "Patient" = PatientId AND "PolicyId" = PolicyId;			

		POLINS_PKG.InsertCatLimits(PatientId, GuarantorId, PolicyId);			

		POLINS_PKG.InsertItemLimits(PatientId, GuarantorId, PolicyId);			

		POLINS_PKG.InsertCatLimitsUsingTempl(PatientId, GuarantorId, PolicyId);			

		POLINS_PKG.InsertItemLimitsUsingTempl(PatientId, GuarantorId, PolicyId);			



	-- B101882 Added ELSIF condition to update PTDEPEND.IsCovered if it doesn't match IsCovered parameter

	ELSIF v_PtDependDeleted = 0 AND IsCovered != PTDEPENDISCOVEREDNOIFNOTSET AND v_ptDependIsCovered != IsCovered THEN

		UPDATE PTDEPEND SET "IsCovered" = IsCovered,

			"Date" = trunc(sysdate),

			"Time" = TO_NUMBER(TO_CHAR(SysDate, 'HH24'))*60+TO_NUMBER(TO_CHAR(SysDate, 'MI')),

			"User" = UserId,

			"StationId" = StationId

		WHERE "PolicyId" = PolicyId

			AND "Patient" = PatientId;



	END IF;



END AddPolicyDependant;







/**************************************************************************/



-- E72587 - routine to add a patient employer

-- 	PatientId: Patient id of the patient

--		EmployerId: Employer id

--		UserId: id of User who is adding the policy

--		StationId: id of station that policy is being added from



PROCEDURE addpatientemployer(IN patientid numeric, IN employerid numeric, IN isprimary numeric, IN userid numeric, IN stationid numeric) IS



	v_EmployerRec			EMPLOYER%ROWTYPE;

   v_PtEmployDeleted		PTEMPLOY."Deleted"%TYPE;



BEGIN



	-- Find out if this employer (PTEMPLOY) already exists

	-- B97869 - Must restore deleted record to avoid primary key violation

	BEGIN

		SELECT "Deleted"

		  INTO v_PtEmployDeleted

		  FROM PTEMPLOY

		 WHERE "Patient" = PatientId

			AND "Employer" = EmployerId;

	EXCEPTION WHEN NO_DATA_FOUND THEN

		v_PtEmployDeleted := NULL;

	END;

		

	

	-- Get Employer Record

	BEGIN

		SELECT *

		  INTO v_EmployerRec

		  FROM EMPLOYER

		 WHERE "Employer" = EmployerId

			AND ROWNUM = 1;

	EXCEPTION WHEN NO_DATA_FOUND THEN

		RETURN;

	END;

	



	-- Add PTEMPLOY 

	IF v_PtEmployDeleted IS NULL THEN

		INSERT INTO PTEMPLOY ("Patient", "Employer", "Primary",

			"Area", "Tel", "Ext", "Occupation", "Date", "Time",

			"User", "StationId", "Deleted", "EndDate")

		VALUES (PatientId,				-- Patient

			EmployerId,						-- Employer

			IsPrimary,						-- Primary

			v_EmployerRec."Area",		-- Area

			v_EmployerRec."Telephone",	-- Tel

			v_EmployerRec."Ext",			-- Ext

			' ',								-- Occupation

			trunc(sysdate), 				-- Date

			TO_NUMBER(TO_CHAR(SysDate, 'HH24'))*60+TO_NUMBER(TO_CHAR(SysDate, 'MI')), 	-- Time

			UserId,							-- User

			StationId,						-- StationId

			0,									-- Deleted

			NULL);							-- EndDate

	

	ELSIF v_PtEmployDeleted = 1 THEN

		

		-- B97869 - update the deleted record, bringing it back to life.

		UPDATE PTEMPLOY Set "Primary" = IsPrimary,

			"Date" = trunc(sysdate), 

			"Time" = TO_NUMBER(TO_CHAR(SysDate, 'HH24'))*60+TO_NUMBER(TO_CHAR(SysDate, 'MI')),

			"User" = UserId, 

			"StationId" = StationId, 

			"Deleted" = 0, 

			"EndDate" = NULL

		WHERE "Patient" = PatientId

		  AND "Employer" = EmployerId;



	END IF;

		

	-- set other employers to secondary if this employer is primary

	IF IsPrimary = 1 THEN

		UPDATE PTEMPLOY SET "Primary" = 0, 

			"Date" = trunc(sysdate),

			"Time" = TO_NUMBER(TO_CHAR(SysDate, 'HH24'))*60+TO_NUMBER(TO_CHAR(SysDate, 'MI')),

			"User" = UserId, 

			"StationId" = StationId 

		WHERE "Patient" = PatientId

		  AND "Employer" <> EmployerId

		  AND "Primary" = 1;

	END IF;



END AddPatientEmployer;









/**************************************************************************/



-- E72587 - routine to calculate the family deductible balance for a new policy

-- 	DeductMode: 0 = family deductible; 1 = patient deductible

-- 	PatientId: Patient id of the holder/patient (depending on mode)

-- 	Company: Company of the new policy

-- 	YEResetDate: Year End Reset Date of the new policy



FUNCTION getfamilydeductbalance(deduct numeric, patientid numeric, company character, yeresetdate timestamp without time zone) RETURN numeric IS



	v_ParentCompany		INSGROUP."ParentCompany"%TYPE;

	v_WaiveDualDeduct		INSURANC."WaiveDualDeduct"%TYPE;



	v_Result					NUMBER;



BEGIN



	-- Start with Deduct Balance = Deduct

	v_Result := Deduct;



	IF Deduct = 0 THEN

		RETURN v_Result;

	END IF;



	-- find out if the policy involved waives dual deductibles

	BEGIN

		SELECT G."ParentCompany", I."WaiveDualDeduct" 

		  INTO v_ParentCompany, v_WaiveDualDeduct

		  FROM INSGROUP G, INSURANC I 

		 WHERE G."Company" = Company

			AND G."ParentCompany" = I."Company";

	EXCEPTION WHEN NO_DATA_FOUND THEN

		RETURN v_Result;

	END;

	

	

	-- only reduct deduct balance if policy waives dual deductibles

	IF v_WaiveDualDeduct = 1 THEN

	

		v_Result := GetWaiveDualDeductBalance(0, Deduct, PatientId, 

						YEResetDate, v_ParentCompany);

	

	END IF;

	

	

	RETURN v_Result;

END;





/**************************************************************************/



-- E72587 - routine to calculate the patient deductible balance for a new policy

-- 	DeductMode: 0 = family deductible; 1 = patient deductible

-- 	PatientId: Patient id of the holder/patient (depending on mode)

-- 	PolicyId: PolicyId of the new policy



FUNCTION getpatientdeductbalance(deduct numeric, patientid numeric, policyid numeric) RETURN numeric IS



	v_ParentCompany		INSGROUP."ParentCompany"%TYPE;

	v_WaiveDualDeduct		INSURANC."WaiveDualDeduct"%TYPE;

	v_YEResetDate			PTPOL."YEResetDate"%TYPE;



	v_Result					NUMBER;



BEGIN



	-- Start with Deduct Balance = Deduct

	v_Result := Deduct;



	IF Deduct = 0 THEN

		RETURN v_Result;

	END IF;



	-- find out if the policy involved waives dual deductibles

	BEGIN

		SELECT G."ParentCompany", I."WaiveDualDeduct", P."YEResetDate" 

		  INTO v_ParentCompany, v_WaiveDualDeduct, v_YEResetDate

		  FROM POLICY P, INSGROUP G, INSURANC I

		 WHERE P."PolicyId" = PolicyId

		   AND P."Company" = G."Company"

			AND G."ParentCompany" = I."Company";

	EXCEPTION WHEN NO_DATA_FOUND THEN

		RETURN v_Result;

	END;

	

	

	-- only reduct deduct balance if policy waives dual deductibles

	IF v_WaiveDualDeduct = 1 THEN

	

		v_Result := GetWaiveDualDeductBalance(1, Deduct, PatientId, 

						v_YEResetDate, v_ParentCompany);

	

	END IF;

	

	

	RETURN v_Result;

END;





/**************************************************************************/



-- E72587 - routine to calculate the deductible balance for a new policy

-- 	DeductMode: 0 = family deductible; 1 = patient deductible

-- 	Deduct: benefit plan's family/patient deductible (depending on mode)

-- 	PatientId: Patient id of the holder/patient (depending on mode)

-- 	Company: Company of the new policy

-- 	YEResetDate: Year End Reset Date of the new policy

-- E72764.8.2 - support new TRX type

FUNCTION getwaivedualdeductbalance(deductmode numeric, deduct numeric, patientid numeric, yeresetdate timestamp without time zone, parentcompany character) RETURN numeric IS



	v_SumDeduct				NUMBER;

	v_Result					NUMBER;



	-- E85559

	CURSOR TRXCursor (YearEndDate DATE, ParentCompany INSGROUP."ParentCompany"%TYPE)

	IS

		SELECT TRX."Patient", TRX."Deduct1", TRX."Deduct2", TRX."Deduct3",

			G1."ParentCompany" "ParentCompany1", 

			G2."ParentCompany" "ParentCompany2", 

			G3."ParentCompany" "ParentCompany3"

		FROM TRX, INSGROUP G1, INSGROUP G2, INSGROUP G3 

		WHERE TRX."TreatmentDate" >= YearEndDate

		AND (TRX."Type" = 1 OR TRX."Type" = 11)

		AND TRX."Deleted" = 0 

		AND TRX."Company1" = G1."Company" (+)

		AND TRX."Company2" = G2."Company" (+)

		AND TRX."Company3" = G3."Company" (+)

		AND (TRX."PolicyId1" IN (SELECT POLICY."PolicyId" FROM POLICY, PTDEPEND, INSGROUP 

			WHERE PTDEPEND."Patient" = PatientId AND POLICY."PolicyId" = PTDEPEND."PolicyId" 

			AND (POLICY."StartDate" is null or POLICY."StartDate" <= trunc(sysdate)) 

			AND (POLICY."ResetDate" is null or POLICY."ResetDate" >= YearEndDate) 

			AND (PTDEPEND."StartDate" is null or PTDEPEND."StartDate" <= trunc(sysdate)) 

			AND (PTDEPEND."EndDate" is null or PTDEPEND."EndDate" >= YearEndDate) 

			AND (POLICY."Deleted" = 0 OR POLICY."Date" IS NULL OR POLICY."Date" >= YearEndDate) 

			AND INSGROUP."ParentCompany" = ParentCompany AND INSGROUP."Company" = POLICY."Company") 

		OR TRX."PolicyId2" IN (SELECT POLICY."PolicyId" FROM POLICY, PTDEPEND, INSGROUP 

			WHERE PTDEPEND."Patient" = PatientId AND POLICY."PolicyId" = PTDEPEND."PolicyId" 

			AND (POLICY."StartDate" is null or POLICY."StartDate" <= trunc(sysdate)) 

			AND (POLICY."ResetDate" is null or POLICY."ResetDate" >= YearEndDate) 

			AND (PTDEPEND."StartDate" is null or PTDEPEND."StartDate" <= trunc(sysdate)) 

			AND (PTDEPEND."EndDate" is null or PTDEPEND."EndDate" >= YearEndDate) 

			AND (POLICY."Deleted" = 0 OR POLICY."Date" IS NULL OR POLICY."Date" >= YearEndDate) 

			AND INSGROUP."ParentCompany" = ParentCompany AND INSGROUP."Company" = POLICY."Company") 

		OR TRX."PolicyId3" IN (SELECT POLICY."PolicyId" FROM POLICY, PTDEPEND, INSGROUP 

			WHERE PTDEPEND."Patient" = PatientId AND POLICY."PolicyId" = PTDEPEND."PolicyId" 

			AND (POLICY."StartDate" is null or POLICY."StartDate" <= sysdate) 

			AND (POLICY."ResetDate" is null or POLICY."ResetDate" >= YearEndDate) 

			AND (PTDEPEND."StartDate" is null or PTDEPEND."StartDate" <= trunc(sysdate)) 

			AND (PTDEPEND."EndDate" is null or PTDEPEND."EndDate" >= YearEndDate) 

			AND (POLICY."Deleted" = 0 OR POLICY."Date" IS NULL OR POLICY."Date" >= YearEndDate) 

			AND INSGROUP."ParentCompany" = ParentCompany AND INSGROUP."Company" = POLICY."Company"));

		



BEGIN



	-- Start with Deduct Balance = Deduct

	v_Result := Deduct;

	

	IF Deduct = 0 THEN

		RETURN v_Result;

	END IF;





	-- we need to reduce the family balance by the amount deducted during the policy year

	-- (even if the policy was terminated/deleted during the year)

	v_SumDeduct := 0;

	FOR TRXRec IN TRXCursor(YEResetDate, ParentCompany)

	LOOP



		-- Make sure the TRX is for the patient when in Patient Deductible Mode

		IF DeductMode = 0 OR TRXRec."Patient" = PatientId THEN



			IF trim(ParentCompany) = trim(TRXRec."ParentCompany1") AND TRXRec."Deduct1" > 0 THEN

				v_SumDeduct := v_SumDeduct + TRXRec."Deduct1";

			ELSIF trim(ParentCompany) = trim(TRXRec."ParentCompany2") AND TRXRec."Deduct2" > 0 THEN

				v_SumDeduct := v_SumDeduct + TRXRec."Deduct2";

			ELSIF trim(ParentCompany) = trim(TRXRec."ParentCompany3") AND TRXRec."Deduct3" > 0 THEN

				v_SumDeduct := v_SumDeduct + TRXRec."Deduct3";

			END IF;



		END IF;



	END LOOP;



	v_Result := v_Result - v_SumDeduct;

	IF v_Result < 0 THEN

		v_Result := 0;

	END IF;





	RETURN v_Result;

	

END;





/**************************************************************************/



-- B80493 added routine to calculate the deductible charged so far

--		to the current patient by any other policies within this calendar year, 

--		including expired/deleted ones	

-- 	PatientId: Patient id of the holder/patient 

-- 	PolicyId: Policy id of the policy in question

-- E72764.8.2 - support new TRX.Type = 11

FUNCTION getdeductchargedtopatientsofar(patientid numeric, policyid numeric) RETURN numeric IS



	v_ParentCompany		INSGROUP."ParentCompany"%TYPE;

	v_YEResetDate			PTPOL."YEResetDate"%TYPE;

	

	v_SumDeduct				NUMBER;

	v_Result					NUMBER;



	-- E85559

	CURSOR TRXCursor (YearEndDate DATE, ParentCompany INSGROUP."ParentCompany"%TYPE,

				PatientId NUMBER, PolicyId NUMBER)

	IS

		SELECT TRX."Patient", TRX."Deduct1", TRX."Deduct2", TRX."Deduct3",

			G1."ParentCompany" "ParentCompany1", 

			G2."ParentCompany" "ParentCompany2", 

			G3."ParentCompany" "ParentCompany3"

		FROM TRX, INSGROUP G1, INSGROUP G2, INSGROUP G3 

		WHERE TRX."TreatmentDate" >= YearEndDate

		AND (TRX."Type" = 1 OR TRX."Type" = 11)

		AND TRX."Deleted" = 0 

		AND TRX."Patient" = PatientId 

		AND TRX."Company1" = G1."Company" (+)

		AND TRX."Company2" = G2."Company" (+)

		AND TRX."Company3" = G3."Company" (+)

		AND ((TRX."PolicyId1" <> PolicyId AND

			TRX."PolicyId1" IN (SELECT POLICY."PolicyId" FROM POLICY, PTDEPEND, INSGROUP 

			WHERE PTDEPEND."Patient" = PatientId AND POLICY."PolicyId" = PTDEPEND."PolicyId" 

			AND (POLICY."StartDate" is null or POLICY."StartDate" <= trunc(sysdate)) 

			AND (POLICY."ResetDate" is null or POLICY."ResetDate" >= YearEndDate) 

			AND (PTDEPEND."StartDate" is null or PTDEPEND."StartDate" <= trunc(sysdate)) 

			AND (PTDEPEND."EndDate" is null or PTDEPEND."EndDate" >= YearEndDate) 

			AND (POLICY."Deleted" = 0 OR POLICY."Date" IS NULL OR POLICY."Date" >= YearEndDate) 

			AND INSGROUP."ParentCompany" = ParentCompany AND INSGROUP."Company" = POLICY."Company")) 

		OR (TRX."PolicyId2" <> PolicyId AND

			TRX."PolicyId2" IN (SELECT POLICY."PolicyId" FROM POLICY, PTDEPEND, INSGROUP 

			WHERE PTDEPEND."Patient" = PatientId AND POLICY."PolicyId" = PTDEPEND."PolicyId" 

			AND (POLICY."StartDate" is null or POLICY."StartDate" <= trunc(sysdate)) 

			AND (POLICY."ResetDate" is null or POLICY."ResetDate" >= YearEndDate) 

			AND (PTDEPEND."StartDate" is null or PTDEPEND."StartDate" <= trunc(sysdate)) 

			AND (PTDEPEND."EndDate" is null or PTDEPEND."EndDate" >= YearEndDate) 

			AND (POLICY."Deleted" = 0 OR POLICY."Date" IS NULL OR POLICY."Date" >= YearEndDate) 

			AND INSGROUP."ParentCompany" = ParentCompany AND INSGROUP."Company" = POLICY."Company")) 

		OR (TRX."PolicyId3" <> PolicyId AND

			TRX."PolicyId3" IN (SELECT POLICY."PolicyId" FROM POLICY, PTDEPEND, INSGROUP 

			WHERE PTDEPEND."Patient" = PatientId AND POLICY."PolicyId" = PTDEPEND."PolicyId" 

			AND (POLICY."StartDate" is null or POLICY."StartDate" <= sysdate) 

			AND (POLICY."ResetDate" is null or POLICY."ResetDate" >= YearEndDate) 

			AND (PTDEPEND."StartDate" is null or PTDEPEND."StartDate" <= trunc(sysdate)) 

			AND (PTDEPEND."EndDate" is null or PTDEPEND."EndDate" >= YearEndDate) 

			AND (POLICY."Deleted" = 0 OR POLICY."Date" IS NULL OR POLICY."Date" >= YearEndDate) 

			AND INSGROUP."ParentCompany" = ParentCompany AND INSGROUP."Company" = POLICY."Company")));

		



BEGIN



	v_Result := 0;

	

	-- get the information regarding the policy

	BEGIN

		SELECT G."ParentCompany", P."YEResetDate" 

		  INTO v_ParentCompany, v_YEResetDate

		  FROM POLICY P, INSGROUP G

		 WHERE P."PolicyId" = PolicyId

		   AND P."Company" = G."Company";

	EXCEPTION WHEN NO_DATA_FOUND THEN

		RETURN v_Result;

	END;





	-- we need to count the family balance by the amount deducted during the policy year

	-- (even if the policy was terminated/deleted during the year)

	v_SumDeduct := 0;

	

	FOR TRXRec IN TRXCursor(v_YEResetDate, v_ParentCompany, PatientId, PolicyId)

	LOOP



		IF trim(v_ParentCompany) = trim(TRXRec."ParentCompany1") AND TRXRec."Deduct1" > 0 THEN

			v_SumDeduct := v_SumDeduct + TRXRec."Deduct1";

		ELSIF trim(v_ParentCompany) = trim(TRXRec."ParentCompany2") AND TRXRec."Deduct2" > 0 THEN

			v_SumDeduct := v_SumDeduct + TRXRec."Deduct2";

		ELSIF trim(v_ParentCompany) = trim(TRXRec."ParentCompany3") AND TRXRec."Deduct3" > 0 THEN

			v_SumDeduct := v_SumDeduct + TRXRec."Deduct3";

		END IF;



	END LOOP;



	v_Result := v_SumDeduct;



	RETURN v_Result;

	

END;





/**************************************************************************/



-- E79752.5 added routine to calculate the deductible charged so far

--		to the family for the given policy within this calendar year. 

-- 	PolicyId: Policy id of the policy in question



FUNCTION getdeductchargedtofamilysofar(policyid numeric) RETURN numeric IS



	v_SumDeduct				NUMBER;

	v_Result					NUMBER;



	CURSOR PtDepCursor (PolicyId NUMBER)

	IS

		SELECT PD."PatientDeduct", PD."DeductBalance"

		FROM PTDEPEND PD, POLICY P 

		WHERE P."PolicyId" = PolicyId

		AND PD."PolicyId" = P."PolicyId" 

		AND PD."Deleted" = 0;

		



BEGIN



	v_Result := 0;

	

	BEGIN

		SELECT SUM(PD."PatientDeduct" - PD."DeductBalance")

		  INTO v_SumDeduct

		FROM PTDEPEND PD, POLICY P 

		WHERE P."PolicyId" = PolicyId

		AND PD."PolicyId" = P."PolicyId" 

		AND PD."Deleted" = 0;

	EXCEPTION WHEN NO_DATA_FOUND THEN

		RETURN v_Result;

	END;



	v_Result := v_SumDeduct;



	RETURN v_Result;

	

END;





/**************************************************************************/



-- E72598 - procedure to add policies to a renewed benefit plan

PROCEDURE renewpolicies(IN oldpolins numeric, IN newpolins numeric, IN newpolinsstartdate timestamp without time zone, IN userid numeric, IN stationid numeric) IS



	CURSOR PtPolCur(OldPolIns POLINS."PolIns"%TYPE, NewStartDate POLINS."StartDate"%TYPE) IS

		SELECT * FROM PTPOL P WHERE 

			P."PolIns" = OldPolIns AND P."Deleted" = 0 

			AND (P."ResetDate" >= NewStartDate OR P."ResetDate" IS NULL);

			

	CURSOR PtDependCur(PolicyId PTDEPEND."PolicyId"%TYPE) IS

		SELECT * FROM PTDEPEND WHERE "PolicyId" = PolicyId AND "Deleted" = 0;



	v_NewPolicyId		PTPOL."PolicyId"%TYPE := 0;

BEGIN



	-- loop through all patient policies for the old benefit plan,

	-- and add new policies for the new plan

	FOR PtPolRec in PtPolCur(OldPolIns, NewPolInsStartDate)

	LOOP

		

		-- Add new Policy

		AddPolicy(PtPolRec."Patient", PtPolRec."Family", NewPolIns,

			PtPolRec."Policy", PtPolRec."StartDate", PtPolRec."ResetDate",

			UserId, StationId, 1, PtPolRec."PolicyId", v_NewPolicyId);			-- S87161, B116767

		

		-- Update Dependents after they were added

		FOR PtDependRec in PtDependCur(PtPolRec."PolicyId")

		LOOP

			

			-- make sure a few fields are set the same as the old policy

			-- E85559, B120266 - only update the dependant returned in the loop

			UPDATE PTDEPEND SET "Number" = PtDependRec."Number",

				"BillOrder" = PtDependRec."BillOrder",

				"MedicaidCoPay" = PtDependRec."MedicaidCoPay",

				"StartDate" = PtDependRec."StartDate",

				"EndDate" = PtDependRec."EndDate"

			WHERE "PolicyId" = v_NewPolicyId

			AND "Patient" = PtDependRec."Patient";

		END LOOP;

		

	END LOOP;



END;





/**************************************************************************/



--B143420.3 -- added procedure to clone riders

PROCEDURE clonepolicyriders(IN oldpolins numeric, IN newpolins numeric) IS



BEGIN



	EXECUTE IMMEDIATE 'INSERT INTO POLRIDER (SELECT POLRIDER_POLRIDER_SEQ.nextval, :1, 

		 "Description", "RiderChildCoverage", "RiderAdultCoverage", "RiderAge", 

		 "RiderAgeStud", "RiderYoungAdultCoverage", "RiderAgeYoungAdult" 

		 FROM POLRIDER WHERE "PolIns" = :2)'

       USING NewPolIns, OldPolIns;



END;





/**************************************************************************/



-- E72598 - function to calculate a policy's year end reset date for the current year

FUNCTION getyeresetdate(polinsrec polins) RETURN timestamp without time zone IS



	v_YEResetDate DATE;

BEGIN



	-- Calculate Year End Reset Date

	begin

		v_YEResetDate := TO_DATE(TO_CHAR(sysdate, 'YYYY') || TO_CHAR(PolInsRec."YearEnd", '09') || TO_CHAR(PolInsRec."YearEndDay", '09'), 'YYYYMMDD');

	exception when others then

		IF v_YEResetDate IS NULL AND PolInsRec."YearEnd" = 2 AND PolInsRec."YearEndDay" = 29 THEN

			v_YEResetDate := TO_DATE(TO_CHAR(sysdate, 'YYYY') || '0228', 'YYYYMMDD');						

		END IF;

	end;



	v_YEResetDate := v_YEResetDate + 1;



	-- B99411 - if calcualted date is in the past, add a year 

	IF v_YEResetDate < trunc(sysdate) THEN

		begin

			v_YEResetDate := TO_DATE(TO_CHAR(TO_NUMBER(TO_CHAR(v_YEResetDate, 'YYYY'))+1, '0009') || TO_CHAR(v_YEResetDate, 'MM') || TO_CHAR(v_YEResetDate, 'DD'), 'YYYYMMDD');

		exception when others then

			v_YEResetDate := TO_DATE(TO_CHAR(TO_NUMBER(TO_CHAR(v_YEResetDate, 'YYYY'))+1, '0009') || '0228', 'YYYYMMDD');

		end;

	END IF;



	return v_YEResetDate;

END;



/**************************************************************************/



-- E68448 - procedure to transfer all policies from one benefit plan to another

-- E99167 - added KeepSubscriberNum

PROCEDURE transferpolicies(IN oldpolins numeric, IN newpolins numeric, IN effectivedate timestamp without time zone, IN keepsubscribernum numeric, IN userid numeric, IN stationid numeric) IS



	SharedEntryId POLINS."SharedEntryId"%TYPE;

	EmployerId POLINS."Employer"%TYPE;

	SubscriberNum PTPOL."Policy"%TYPE;	-- E99167

	vText  CHAR(255);							-- E99167

	vStartDate	NUMBER;

	vEndDate		NUMBER;



	-- get all active policies from the old plan whose subscribers don't already have the new plan

	CURSOR PtPolCur(OldPolIns POLINS."PolIns"%TYPE, NewPolIns POLINS."PolIns"%TYPE, NewStartDate POLINS."StartDate"%TYPE) IS

		SELECT * FROM PTPOL P WHERE 

			P."PolIns" = OldPolIns AND P."Deleted" = 0 

			AND (P."ResetDate" >= NewStartDate OR P."ResetDate" IS NULL)

			AND NOT EXISTS (select 1 from ptpol p2 where p2."PolIns" = NewPolIns

			   and P."Patient" = p2."Patient" and P."Policy" = p2."Policy" and p2."Deleted" = 0 

				and (p2."ResetDate" >= NewStartDate OR p2."ResetDate" IS NULL));

			

	CURSOR PtDependCur(PolicyId PTDEPEND."PolicyId"%TYPE) IS

		SELECT * FROM PTDEPEND WHERE "PolicyId" = PolicyId AND "Deleted" = 0;



	v_NewPolicyId		PTPOL."PolicyId"%TYPE := 0;

BEGIN



	-- Set the end date of the old benefit plan

	SELECT POLICY_SHAREDENTRYID_SEQ.NEXTVAL INTO SharedEntryId FROM DUAL;

	EXECUTE IMMEDIATE 'UPDATE POLINS P SET P."EndDate"=:1, 

					P."Date"=trunc(sysdate),

					P."Time"=:2,

					P."User"=:3, 

					P."StationId"=:4,

					P."SharedEntryId"=:5

					WHERE P."PolIns"=:6 AND (P."EndDate" is null or P."EndDate" > :7) '

	                USING EffectiveDate-1, trunc(to_char(sysdate,'SSSSS')/60), 

	                UserId, StationId, SharedEntryId, OldPolIns, EffectiveDate-1;

	

	-- Set the start date of the new benefit plan

	SELECT POLICY_SHAREDENTRYID_SEQ.NEXTVAL INTO SharedEntryId FROM DUAL;

	EXECUTE IMMEDIATE 'UPDATE POLINS P SET P."StartDate"=:1, 

					P."Date"=trunc(sysdate),

					P."Time"=:2,

					P."User"=:3, 

					P."StationId"=:4,

					P."SharedEntryId"=:5

					WHERE P."PolIns"=:6 '

	                USING EffectiveDate, trunc(to_char(sysdate,'SSSSS')/60), 

	                UserId, StationId, SharedEntryId, NewPolIns;

	

	

	-- loop through all patient policies for the old benefit plan,

	-- and add new policies for the new plan

	FOR PtPolRec in PtPolCur(OldPolIns, NewPolIns, EffectiveDate)

	LOOP

		

		-- B98978 - add employer

		begin

			select "Employer" into EmployerId from POLINS where "PolIns" = NewPolIns;

		exception when no_data_found then

			EmployerId := 0;

		end;



		if EmployerId > 0 then		

			AddPatientEmployer(PtPolRec."Patient", EmployerId, 0, UserId, StationId);

		end if;

		

		

		-- E99167 - copy subscriber number is optional

		if KeepSubscriberNum = 1 then

			SubscriberNum := PtPolRec."Policy";

		else

			SubscriberNum := 'UNKNOWN';

			vText := 'Patient has been transferred to a new benefit plan.  New subscriber number needed for insurance to take effect.' || chr(13) || chr(10) || chr(13) || chr(10) || 'Please Update.  Do not remove this note until the subscriber number has been updated.';



			SELECT CALCULATEDAYSDIFF_S(ROUND(SYSDATE) ,TO_DATE('01/01/1901') ) INTO vStartDate FROM DUAL; -- AX39652

			vEndDate := vStartDate + 365;

		end if;

		



		-- Add new Policy

		AddPolicy(PtPolRec."Patient", PtPolRec."Family", NewPolIns,

			SubscriberNum, PtPolRec."StartDate", PtPolRec."ResetDate",

			UserId, StationId, 1, PtPolRec."PolicyId", v_NewPolicyId);			-- S87161, E99167, B116767

		

		-- Update Dependents after they were added

		FOR PtDependRec in PtDependCur(PtPolRec."PolicyId")

		LOOP

			

			-- make sure a few fields are set the same as the old policy

			-- B98981 - don't copy over start and end date

			UPDATE PTDEPEND SET "Number" = PtDependRec."Number",

				"BillOrder" = PtDependRec."BillOrder",

				"MedicaidCoPay" = PtDependRec."MedicaidCoPay"

			WHERE "PolicyId" = v_NewPolicyId;





			-- E99167 - add sticky note to each dependant if not copying subscriber number

			if KeepSubscriberNum <> 1 then



				INSERT INTO AP_NOTE ("AP_NOTE_AutoDec","AP_NOTE_AppId","AP_NOTE_Type","AP_NOTE_PatientId","AddDateTime","ModifiedDateTime","AP_NOTE_Flag","AP_NOTE_Date1","AP_NOTE_Date2","AP_NOTE_PAmount","AP_NOTE_IAmount","AP_NOTE_Text","AP_NOTE_Treatment","CreationUser","ModifiedUser","StationId")

				VALUES (

					AP_NOTE_AP_NOTE_AUTODEC_SEQ.NEXTVAL,		--AP_NOTE_AutoDec                NOT NULL NUMBER(10)

					PtDependRec."Patient",								--AP_NOTE_AppId                           NUMBER(10)

					3,											--AP_NOTE_Type                            NUMBER(10)

					0,											--AP_NOTE_PatientId                       NUMBER(10)

					SYSDATE,									--AddDateTime	(E125010)

					SYSDATE,									--ModifiedDateTime	(E125010)

					24,										--AP_NOTE_Flag                            NUMBER(10)

					vStartDate,									--AP_NOTE_Date1                           NUMBER(10)

					vEndDate,									--AP_NOTE_Date2                           NUMBER(10)

					0,											--AP_NOTE_PAmount                         NUMBER

					0,											--AP_NOTE_IAmount                         NUMBER

					vText,										--AP_NOTE_Text                             CHAR(255)

					0,											--AP_NOTE_Treatment                       NUMBER(10)

					UserId,										--CreationUser                            NUMBER(10)

					0,											--ModifiedUser                            NUMBER(10)

					StationId									--StationId                               NUMBER(10)

				);

			end if;



		END LOOP;



	END LOOP;



END;





-- B123401

FUNCTION isinsurancenetworkeligibility(edicode2 character) RETURN numeric IS



	v_Result NUMBER;

BEGIN

  v_Result := 0;

  IF trim(EDICode2) = '65978' THEN

    v_Result := 1;

  END if;

  

  RETURN v_Result;

END;



/**************************************************************************/



END;
CREATE OR REPLACE PACKAGE BODY pportal_pkg IS



PROCEDURE loginuser(IN vusername character varying, IN vpassword character varying, IN vwindowinminutes integer, IN vmaxattempts integer, IN vterminal character varying, OUT visvalid integer, OUT visagreed integer, OUT vistemp integer, OUT viuser integer) IS

  vId NUMBER(10);

  vIsLocked NUMBER(5);

  vIsNoAccess NUMBER(5);     -- 59797950  

  vAttemptCount  NUMBER(5);

  vAttemptDate DATE;

  vAttemptTime NUMBER(10);

  vHashedPassword  VARCHAR2(255);

  vHashedInRecord  VARCHAR2(255);

  vTime NUMBER(10) := (to_number(to_char(current_date,'HH24'))*60) + to_number(to_char(current_date,'MI'));  -- Is there a function already existing that can call here?

BEGIN

  -- TODO: Index NLS_LOWER("UserName")

  SELECT "iUser", "Id", "Password", "IsAgreed", "IsTemp", "IsLocked", "IsNoAccess", "FailedPWAttemptCount", "FailedPWAttemptDate", "FailedPWAttemptTime"

  INTO vIUser, vId, vHashedInRecord, vIsAgreed, vIsTemp, vIsLocked, vIsNoAccess, vAttemptCount, vAttemptDate, vAttemptTime

  FROM IUSER WHERE NLS_LOWER("UserName") = NLS_LOWER(TRIM(vUserName)) AND "Deleted" = 0;		-- AX-20754 - No case sensitive 



  vHashedPassword := vPassword;

	

  IF vHashedPassword = vHashedInRecord THEN

    IF vIsLocked = 0 AND vIsNoAccess = 0 THEN

      vIsValid := 0; -- Valid username and password - successful login.

      UPDATE IUSER SET "LastAccessDateTime" = CURRENT_DATE WHERE "UserName" = TRIM(vUserName);

    ELSE

      IF vIsLocked = 0 THEN 	

         vIsValid := 5; -- 59797950 Valid username and password, but patient has not access to PA

      ELSE

         vIsValid := 4; -- Valid username and password, but account is locked.

      END IF;	  

    END IF;

    UPDATE IUSER SET "FailedPWAttemptCount" = 0, "FailedPWAttemptDate" = null, "FailedPWAttemptTime" = null  WHERE "iUser" = viUser;

  ELSE

		vIsValid := 2; -- invalid password

    -- Only increment failed password if account is not locked and has Access (59797950). Otherwise, just notify user that bad password.

    IF vIsLocked = 0  AND vIsNoAccess = 0 THEN

      IncrementFailedPassword(viUser, vAttemptCount, vAttemptDate, vAttemptTime, vWindowInMinutes, vMaxAttempts); -- Todo: get rid of magic numbers

    END IF;

  END IF;

  

  ILogEntry(vUserName, vIsValid, CURRENT_DATE, vTime, vTerminal, viUser);  

    

exception

  WHEN NO_DATA_FOUND THEN vIsValid := 2;  -- invalid username

  -- Don't worry about if more than one record found - throw error as should never happen.

  

  -- Protect against XSS attack as vUserName could be bogus and harmful in the event of no record found. Therefore, audit as "Invalid UserName" for username.



  ILogEntry('Invalid UserName', vIsValid, CURRENT_DATE, vTime, vTerminal, viUser);  

END;



PROCEDURE loginiuser(IN viuser numeric, IN vwindowinminutes numeric, IN vmaxattempts numeric, IN vterminal character varying, OUT visvalid numeric, OUT visagreed numeric, OUT vistemp numeric, OUT vusername character varying) IS

  vId NUMBER(10);

  vIsLocked NUMBER(5);

  vIsNoAccess NUMBER(5);     -- 59797950  

  vAttemptCount  NUMBER(5);

  vAttemptDate DATE;

  vAttemptTime NUMBER(10);

  vTime NUMBER(10) := (to_number(to_char(current_date,'HH24'))*60) + to_number(to_char(current_date,'MI'));  -- Is there a function already existing that can call here?

BEGIN

  SELECT "UserName", "Id", "IsAgreed", "IsTemp", "IsLocked", "IsNoAccess", "FailedPWAttemptCount", "FailedPWAttemptDate", "FailedPWAttemptTime"

  INTO vUserName, vId,  vIsAgreed, vIsTemp, vIsLocked, vIsNoAccess, vAttemptCount, vAttemptDate, vAttemptTime

  FROM IUSER WHERE "iUser" = viUser AND "Deleted" = 0;



  IF vIsLocked = 0 AND vIsNoAccess = 0 THEN

    vIsValid := 0; -- Successful login.

    UPDATE IUSER SET "LastAccessDateTime" = CURRENT_DATE WHERE "UserName" = TRIM(vUserName);

  ELSE

    IF vIsLocked = 0 THEN 

       -- vIsValid := 5; -- Patient has no access to PA

       vIsValid := 0; -- Ignore for Kiosk

    ELSE

       vIsValid := 4; -- Account is locked.

    END IF;	  

  END IF;

  UPDATE IUSER SET "FailedPWAttemptCount" = 0, "FailedPWAttemptDate" = null, "FailedPWAttemptTime" = null  WHERE "iUser" = viUser;



  ILogEntry(vUserName, vIsValid, CURRENT_DATE, vTime, vTerminal, viUser);  

exception

  WHEN NO_DATA_FOUND THEN vIsValid := 2;  -- invalid username

  -- Don't worry about if more than one record found - throw error as should never happen.

  -- Protect against XSS attack as vUserName could be bogus and harmful in the event of no record found. Therefore, audit as "Invalid UserName" for username.

  ILogEntry('Invalid UserName', vIsValid, CURRENT_DATE, vTime, vTerminal, viUser);  

END;



PROCEDURE logoutuser(IN vusername character varying, IN vterminal character varying) IS

  vIUser NUMBER(10);

  vTime NUMBER(10) := (to_number(to_char(current_date,'HH24'))*60) + to_number(to_char(current_date,'MI'));

BEGIN



  SELECT "iUser"

  INTO vIUser

  FROM IUSER WHERE NLS_LOWER("UserName") = NLS_LOWER(TRIM(vUserName)) AND "Deleted" = 0;



  IF vIUser != 0 THEN

    ILogEntry(vUserName, 1, CURRENT_DATE, vTime, vTerminal, viUser);  

  END IF;



  EXCEPTION

  WHEN NO_DATA_FOUND THEN vIUser := 0;  -- not throw error

  

END;



PROCEDURE ilogentry(IN vusername character varying, IN vaction numeric, IN vdate timestamp without time zone, IN vtime numeric, IN vterminal character varying, IN viuser numeric) IS

  vILog NUMBER(10) := 0;

BEGIN

  SELECT ILOG_ILOG_SEQ.NEXTVAL INTO vILog FROM dual;

  INSERT INTO ILOG ("iLog", "UserName", "Action", "Date", "Time", "Terminal", "iUser") VALUES (vILog, vUserName, vAction, TRUNC(vDate), vTime, vTerminal, viUser);

END;



PROCEDURE incrementfailedpassword(IN viuser numeric, IN vattemptcount numeric, IN vattemptdate timestamp without time zone, IN vattempttime numeric, IN vwindowinminutes numeric, IN vmaxattempts numeric) IS

  vAttemptDateTime DATE := NULL;

  vNewCount NUMBER(5) := 1;

  vNewDate DATE := CURRENT_DATE; -- Todo: verify whether need to set date format or whether that is already done system-wide and don't need to worry about it here.

  vNewTime NUMBER(10) := (to_number(to_char(current_date,'HH24'))*60) + to_number(to_char(current_date,'MI'));  -- Is there a function already existing that can call here?

  vNewAttempDateTime DATE := vNewDate + vNewTime/1440;    -- ARR May/7/2012 Id. 25346569 Set new time attemp

  vLockAccount NUMBER(5) := 0; -- sticking with NUMBER(5) convention instead of NUMBER(1) or BOOLEAN := FALSE;

  vAuditHis NUMBER(10); -- 55579184 

BEGIN

  IF (vAttemptDate IS NOT NULL AND vAttemptTime IS NOT NULL) THEN

    vAttemptDateTime := vAttemptDate + vAttemptTime/1440;

  END IF;

  

  -- Has there ever been a wrong password before?

  IF vAttemptDateTime IS NOT NULL THEN 

    -- Did the wrong password attempt occur within the attempt window?

    IF vAttemptDateTime + vWindowInMinutes/1440 > vNewAttempDateTime THEN

      -- Is the attempt count now over max attempt allowed before locking account?

      IF vAttemptCount >= vMaxAttempts THEN

        vLockAccount := 1;

        -- Now that the account is locked, reset all counts.

        vNewCount := 0;

        vNewDate := null;

        vNewTime := null;

      ELSE

        vNewCount := vAttemptCount + 1;

        vNewDate := vAttemptDate;

        vNewTime := vAttemptTime;

      END IF;

    ELSE

      -- ARR May/8/2012 Id. 25346569. Get next old attempt from ILOG table

      GetNextAttempt(viUser, vAttemptDate, vAttemptTime, vWindowInMinutes, vMaxAttempts, vLockAccount, vNewCount, vNewDate, vNewTime);

    END IF;

  ELSE

    -- ARR May/10/2012 Id. 25346569. Extreme case vMaxAttempts == zero

    IF vMaxAttempts <= 0 THEN

      vLockAccount := 1;

      -- Now that the account is locked, reset all counts.

      vNewCount := 0;

      vNewDate := null;

      vNewTime := null;

    END IF;

  END IF; 

  

  CreateAudithis(viUser, 'IUSER', 2, vAuditHis);	-- 55579184 Create a new AUDITHIS record and set new AuditHisId in vAuditHis variable

 

  UPDATE IUSER SET "IsLocked" = vLockAccount, "FailedPWAttemptCount" = vNewCount, "FailedPWAttemptDate" = vNewDate, "FailedPWAttemptTime" = vNewTime, "Audit" = vAuditHis

  WHERE "iUser" = viUser;   -- 55579184 include AuditHis id

END;



-- ARR May/8/2012 Id. 25346569. Get new Initial attemp and total previous attemp

PROCEDURE getnextattempt(IN viuser numeric, IN vattemptdate timestamp without time zone, IN vattempttime numeric, IN vwindowinminutes numeric, IN vmaxattempts numeric, INOUT vlockaccount numeric, INOUT vnewcount numeric, INOUT vnewdate timestamp without time zone, INOUT vnewtime numeric) IS

  vNewTimeOrig NUMBER(10) := vNewTime;

  setNewFirstAttemp BOOLEAN := FALSE; 

  iLogDateStr  VARCHAR(20) := NULL;

  vNewDateStr  VARCHAR(20) := NULL;

  CURSOR ilogs is

    SELECT IL."Date", IL."Time", IL."iLog" FROM ILOG IL 

      WHERE IL."iUser" = viUser AND IL."Date" >= vAttemptDate AND IL."Time" >= vAttemptTime AND IL."Action" = '2' AND IL."Terminal" = 'PatientAccess';

BEGIN

  FOR ilog IN ilogs

  LOOP

    iLogDateStr :=to_char(iLog."Date", 'DD-MON-YYYY');

    vNewDateStr :=to_char(vNewDate, 'DD-MON-YYYY');

    IF (iLogDateStr = vNewDateStr AND (ilog."Time" + vWindowInMinutes) > vNewTimeOrig) THEN

      vNewCount := vNewCount + 1;

      IF NOT setNewFirstAttemp  THEN

        setNewFirstAttemp := TRUE;

        vNewTime := iLog."Time";

      END IF;

    END IF;  

  END LOOP;

  IF vNewCount > vMaxAttempts THEN

        vLockAccount := 1;

        -- Now that the account is locked, reset all counts.

        vNewCount := 0;

        vNewDate := null;

        vNewTime := null;

  END IF;

END;



PROCEDURE updateusercredentials(IN vusername character varying, IN voldusername character varying, IN vcurrentpassword character varying, IN vnewpassword character varying, IN vquestion1 integer, IN vquestion2 integer, IN vquestion3 integer, IN vanswer1 character varying, IN vanswer2 character varying, IN vanswer3 character varying, OUT vstatus integer) IS

  vHashedPassword  VARCHAR2(255);

  vPasswordInRecord  VARCHAR2(255);

  vUsernameCount NUMBER(10) := 0;

  vId NUMBER(10) := 0;

  vAuditHis NUMBER(10); -- 55579184 

  vIUser NUMBER(10); -- 55579184

BEGIN



	IF NLS_LOWER(vUsername) <> NLS_LOWER(vOldUsername) THEN

		-- Check if username in use or not. Need to keep in mind logically deleted users as it's a unique username index. 

		-- Moreover, there currently is nothing in place that will actually make a logically deleted IUSER)

		SELECT COUNT(*) INTO vUsernameCount FROM IUser WHERE NLS_LOWER("UserName") = NLS_LOWER(TRIM(vUsername));

	END IF;

	

	IF vUsernameCount = 0 THEN

		SELECT "Id", "Password", "iUser" INTO vId, vPasswordInRecord, viUser FROM IUSER WHERE NLS_LOWER("UserName") = NLS_LOWER(TRIM(vOldUsername)); -- TODO: lowered username index must be implemented.

		

		IF vPasswordInRecord = vCurrentPassword THEN

			vHashedPassword := vNewPassword;

			

            CreateAudithis(viUser, 'IUSER', 2, vAuditHis);	-- 55579184 Create a new AUDITHIS record and set new AuditHisId in vAuditHis variable

			

			UPDATE IUSER 

			SET

				"Audit" = vAuditHis,

				"UserName" = vUsername,

				"Password" = vHashedPassword,

				"IsTemp" = 0,

				"PasswordQuestion1" = vQuestion1,

				"PasswordQuestion2" = vQuestion2,

				"PasswordQuestion3" = vQuestion3,

				"PwdLastChanged" = CASE

					WHEN (vPasswordInRecord = vHashedPassword) THEN "PwdLastChanged"

					ELSE current_date

					END,

				"PasswordAnswer1" = CASE

					WHEN (TRIM(vAnswer1) IS NULL OR LENGTH(TRIM(vAnswer1)) = 0) THEN "PasswordAnswer1"

					ELSE vAnswer1

					END,

				"PasswordAnswer2" = CASE

					WHEN (TRIM(vAnswer2) IS NULL OR LENGTH(TRIM(vAnswer2)) = 0) THEN "PasswordAnswer2"

					ELSE vAnswer2

					END,

				"PasswordAnswer3" = CASE

					WHEN (TRIM(vAnswer3) IS NULL OR LENGTH(TRIM(vAnswer3)) = 0) THEN "PasswordAnswer3"

					ELSE vAnswer3

					END

			WHERE "Id" = vId;



			vStatus := 0; -- Success

		ELSE

			vStatus := 2; -- Invalid credentials

		END IF;

	ELSE

		vStatus := 1; -- Username already in use.

	END IF;

	

exception

  WHEN NO_DATA_FOUND THEN vStatus := 3;  -- Invalid username. No record found. Should not happen as using current logged in user's username.

  -- Don't worry about if more than one record found - throw error as should never happen. 

END;





PROCEDURE usercrednoques(IN vusername character varying, IN voldusername character varying, IN vcurrentpassword character varying, IN vnewpassword character varying, OUT vstatus integer) IS

  vHashedPassword  VARCHAR2(255);

  vPasswordInRecord  VARCHAR2(255);

  vUsernameCount NUMBER(10) := 0;

  vId NUMBER(10) := 0;

  vAuditHis NUMBER(10); -- 55579184

  vIUser NUMBER(10); -- 55579184  

BEGIN



IF NLS_LOWER(vUsername) <> NLS_LOWER(vOldUsername) THEN

		-- Check if username in use or not. Need to keep in mind logically deleted users as it's a unique username index. 

		-- Moreover, there currently is nothing in place that will actually make a logically deleted IUSER)

		SELECT COUNT(*) INTO vUsernameCount FROM IUser WHERE NLS_LOWER("UserName") = NLS_LOWER(TRIM(vUsername));

	END IF;

	

	IF vUsernameCount = 0 THEN

		SELECT "Id", "Password", "iUser" INTO vId, vPasswordInRecord, viUser FROM IUSER WHERE NLS_LOWER("UserName") = NLS_LOWER(TRIM(vOldUsername)); -- TODO: lowered username index must be implemented.

		

		IF vPasswordInRecord = vCurrentPassword THEN

			vHashedPassword := vNewPassword;

			

            CreateAudithis(viUser, 'IUSER', 2, vAuditHis);	-- 55579184 Create a new AUDITHIS record and set new AuditHisId in vAuditHis variable



			UPDATE IUSER

			SET

				"Audit" = vAuditHis,

				"UserName" = vUsername,

				"Password" = vHashedPassword,

				"IsTemp" = 0,

				"PwdLastChanged" = CASE

					WHEN (vPasswordInRecord = vHashedPassword) THEN "PwdLastChanged"

					ELSE current_date

					END

			WHERE "Id" = vId;

			

			vStatus := 0; -- Success

		ELSE

			vStatus := 2; -- Invalid credentials

		END IF;

	ELSE

		vStatus := 1; -- Username already in use.

	END IF;

	

exception

  WHEN NO_DATA_FOUND THEN vStatus := 3;  -- Invalid username. No record found. Should not happen as using current logged in user's username.

  -- Don't worry about if more than one record found - throw error as should never happen. 



END;



PROCEDURE updatesecquesbyiuser(IN viuser integer, IN vquestion1 integer, IN vquestion2 integer, IN vquestion3 integer, IN vanswer1 character varying, IN vanswer2 character varying, IN vanswer3 character varying, OUT vstatus integer) IS

  vId NUMBER(10) := 0;

  vAuditHis NUMBER(10); -- 55579184

BEGIN

	SELECT "Id" INTO vId FROM IUSER WHERE "iUser" = viUser;

		

    CreateAudithis(viUser, 'IUSER', 2, vAuditHis);	-- 55579184 Create a new AUDITHIS record and set new AuditHisId in vAuditHis variable



	UPDATE IUSER

	SET

		"Audit" = vAuditHis,

		"PasswordQuestion1" = vQuestion1,

		"PasswordQuestion2" = vQuestion2,

		"PasswordQuestion3" = vQuestion3, 

		"PasswordAnswer1" = CASE

			WHEN (TRIM(vAnswer1) IS NULL OR LENGTH(TRIM(vAnswer1)) = 0) THEN "PasswordAnswer1"

			ELSE vAnswer1

			END,

		"PasswordAnswer2" = CASE

			WHEN (TRIM(vAnswer2) IS NULL OR LENGTH(TRIM(vAnswer2)) = 0) THEN "PasswordAnswer2"

			ELSE vAnswer2

			END,

		"PasswordAnswer3" = CASE

			WHEN (TRIM(vAnswer3) IS NULL OR LENGTH(TRIM(vAnswer3)) = 0) THEN "PasswordAnswer3"

			ELSE vAnswer3

			END

	WHERE "Id" = vId;

	

	vStatus := 0; -- Update Security Questions Success		



exception

  WHEN NO_DATA_FOUND THEN vStatus := 3;

  -- Invalid user name. No record found. Should not happen as using current logged in user's name.

  -- Don't worry about if more than one record found - throw error as should never happen. 

END;





-- Ticket. 36732337

-- Procedure validate if vUsername and vCurrentPassword (Credentials) are correct

PROCEDURE validateusercredentials(IN vusername character varying, IN voldusername character varying, IN vcurrentpassword character varying, OUT vstatus integer) IS

  vHashedPassword  VARCHAR2(255);

  vPasswordInRecord  VARCHAR2(255);

    vUsernameCount NUMBER(10) := 0;

  vId NUMBER(10) := 0;

BEGIN



IF NLS_LOWER(vUsername) <> NLS_LOWER(vOldUsername) THEN

		-- Check if username in use or not. Need to keep in mind logically deleted users as it's a unique username index. 

		-- Moreover, there currently is nothing in place that will actually make a logically deleted IUSER)

		SELECT COUNT(*) INTO vUsernameCount FROM IUser WHERE NLS_LOWER("UserName") = NLS_LOWER(TRIM(vUsername));

	END IF;

	

	IF vUsernameCount = 0 THEN

		SELECT "Id", "Password" INTO vId,vPasswordInRecord FROM IUSER WHERE NLS_LOWER("UserName") = NLS_LOWER(TRIM(vOldUsername)); -- TODO: lowered username index must be implemented.

		

		IF vPasswordInRecord = vCurrentPassword THEN

			vStatus := 0; -- Success

		ELSE

			vStatus := 2; -- Invalid credentials

		END IF;

	ELSE

		vStatus := 1; -- Username already in use.

	END IF;

	

exception

  WHEN NO_DATA_FOUND THEN vStatus := 3;  -- Invalid username. No record found. Should not happen as using current logged in user's username.

  -- Don't worry about if more than one record found - throw error as should never happen. 



END;



-- Ticket. 25076109

-- Procedure to check if the AdvancedEncryption is used in axiUm

-- return: (0 = no, 1 = yes)<p/>

PROCEDURE getencryptionmethod(OUT vencryptionmethod integer) IS

BEGIN

  SELECT "EncryptionMethod"

  INTO vEncryptionMethod

  FROM AXIUMOPT

  WHERE ROWNUM = 1;

  

  EXCEPTION WHEN NO_DATA_FOUND THEN

  vEncryptionMethod := 0;

END;





-- Procedure to check if the AuditLogging is used in axiUm

-- return: (0 = no, 1 = basic, 2 = advanced)<p/>

PROCEDURE getauditlogging(OUT vauditlogging integer) IS

BEGIN

  SELECT "AuditLogging"

  INTO vAuditLogging

  FROM AXIUMOPT

  WHERE ROWNUM = 1;

  

  EXCEPTION WHEN NO_DATA_FOUND THEN

  vAuditLogging := 0;

END;





-- Ticket. 28963759. Ability to determine version and build number from database

-- Procedure that set PA version Gen.VersionPatientAccess in ISetting table

-- param: vVersion INPUT: version to set<p/>

PROCEDURE setpaversion(IN vversion character varying) IS

	vIsetting NUMBER(5);

	vKey  VARCHAR2(255) := 'Gen.VersionPatientAccess';

	vType INTEGER;

	vGroup INTEGER;

	vPriority INTEGER;

	vValue  VARCHAR2(4000);

	vDescription  VARCHAR2(4000);

BEGIN

	GetPSetting(vKey, vIsetting, vValue); 



	IF vIsetting = -1 THEN

	   -- Create ISetting for version

	   vType := 2;		

	   vGroup := -1; 	

	   vPriority := 0;

	   vDescription := 'Patient Access Version';

	   AddPSetting (vKey, vType, vGroup, vPriority, vVersion, vDescription);

	ELSE

    -- Set new version

	  SetPSetting (vKey, vVersion);

    INSERT INTO AUDITHIS VALUES (

      AUDITHIS_AUDIT_SEQ.nextval, 

      TRUNC(SYSDATE), 

      TO_NUMBER(TO_CHAR(SYSDATE, 'HH24'))*60+TO_NUMBER(TO_CHAR(SYSDATE, 'MI')),

      TO_NUMBER(REPLACE(vVersion,'.','')),

      0,

      'PVERSION',

      2

    );

    COMMIT;

	END IF;

END;



-- Ticket. 28963759. Ability to determine version and build number from database

-- Procedure that set PA version Gen.VersionPatientAccess in ISetting table

-- param: vKey INPUT: Key to look in ISeeting<p/>

-- param: vIsetting OUTPUT: Setting id to set<p/>

-- param: vValue OUTPUT: value to set<p/>

PROCEDURE getpsetting(IN vkey character varying, OUT visetting integer, OUT vvalue character varying) IS

BEGIN

	BEGIN

      SELECT "iSetting", "Value"

      INTO vIsetting, vValue

      FROM ISETTING

      WHERE  "Key" = vKey;

     		

	  EXCEPTION WHEN NO_DATA_FOUND THEN

		vIsetting := -1; -- couldn't find the key

	END;

END;



-- Ticket. 28963759. Ability to determine version and build number from database

-- Procedure that set PA version Gen.VersionPatientAccess in ISetting table

-- param: vKey INPUT: Key of the setting to change the value (ISETTING.Key).<p/>

-- param: vValue INPUT: value to set<p/>

PROCEDURE setpsetting(IN vkey character varying, IN vvalue character varying) IS

BEGIN	

	UPDATE ISETTING SET

		"Value" = vValue

	WHERE "Key" = vKey;

	COMMIT;

END;



-- Ticket. 28963759. Add a new ISetting to determine version and build number from database

-- Procedure that Add a new ISetting record

-- param: vKey INPUT: Key of the setting to change the value (ISETTING.Key).<p/>

PROCEDURE addpsetting(IN vkey character varying, IN vtype integer, IN vgroup integer, IN vpriority integer, IN vvalue character varying, IN vdescription character varying) IS

BEGIN	



    INSERT INTO ISETTING ("Key", "SettingType", "iSettingGrp", "Priority", "Value", "Description")

    VALUES (vKey, vType, vGroup, vPriority, vValue, vDescription);

  COMMIT;

END;



  -- Ticket. 41549221 Check if patient has only one active insurance policy. If so, return the policy ID

  PROCEDURE checkifonlyactiveinspolicy(IN vpatientid integer, OUT vpolicyid integer) IS

    vCount INTEGER := 0;

    

    CURSOR cPolicy IS

      SELECT PT."PolicyId"

      FROM PATIENT P, PTDEPEND D, PTPOL PT, POLINS PI

      WHERE P."Patient" = vPatientId 

      AND D."Patient" = P."Patient" 

      AND D."Deleted" = 0 

      AND PT."PolicyId" = D."PolicyId"

      AND (PT."Deleted" = 0 

        OR (PT."Date" IS NULL AND PI."Date" IS NULL) 

        OR (GREATEST(NVL(PT."Date", PI."Date"), NVL(PI."Date", PT."Date")) > TRUNC(SYSDATE)))

      AND PT."PolIns" = PI."PolIns"

      AND (LEAST(NVL(PT."ResetDate", PI."EndDate"), NVL(PI."EndDate", PT."ResetDate")) IS NULL 

        OR LEAST(NVL(PT."ResetDate", PI."EndDate"), NVL(PI."EndDate", PT."ResetDate")) >= TRUNC(SYSDATE));

        

  BEGIN

    FOR vResult IN cPolicy LOOP

      vCount := vCount + 1;

      vPolicyId := vResult."PolicyId";

    END LOOP;

    

    IF vCount != 1 THEN

      vPolicyId := 0;

    END IF;

  END;



  -- Ticket. 33514707 Add Insurance Info related Procedure

  PROCEDURE getinspolicylist(IN vpatientid integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT 

      PT."PolicyId" AS "PolicyId",

      PT."Policy" AS "SubscriberNumber",

      PT."StartDate" AS "StartDate",

      PT."ResetDate" AS "EndDate",

      PI."Group" AS "Group",

      PI."Division" AS "Division",

      PI."PlanType",

      PT."LimitBalance",

      PT."DeductBalance",

      PI."HasFamilyLimit",

      PI."HasPatientLimit",

      H."Patient" AS "HolderId",

      H."Last" AS "HolderLastName",

      H."First" AS "HolderFirstName",

      TO_CHAR (H."Birth", 'MM') AS "HolderBirthMonth",  

      TO_CHAR (H."Birth", 'DD') AS "HolderBirthDay",

      I."Name" AS "InsCompanyName",

      I."Company" AS "InsCompanyCode",

      E."Name" AS "EmployerName",

      CASE

        WHEN LEAST(NVL(PT."ResetDate", PI."EndDate"), NVL(PI."EndDate", PT."ResetDate")) IS NOT NULL 

        AND LEAST(NVL(PT."ResetDate", PI."EndDate"), NVL(PI."EndDate", PT."ResetDate")) < TRUNC(SYSDATE) 

        THEN -1 

        

        WHEN GREATEST(NVL(PT."StartDate", PI."StartDate"), NVL(PI."StartDate", PT."StartDate")) > TRUNC(SYSDATE)

        THEN 1

        

        ELSE 0

      END AS "Status"

	  

      FROM PATIENT P, PTDEPEND D, PTPOL PT, POLINS PI, PATIENT H, INSURANC I, EMPLOYER E

      WHERE P."Patient" = vPatientId 

      AND D."Patient" = P."Patient" 

      AND D."Deleted" = 0 

      AND PT."PolicyId" = D."PolicyId"

      AND (PT."Deleted" = 0 

        OR (PT."Date" IS NULL AND PI."Date" IS NULL) 

        OR (GREATEST(NVL(PT."Date", PI."Date"), NVL(PI."Date", PT."Date")) > TRUNC(SYSDATE)))

      AND PT."PolIns" = PI."PolIns"

      AND H."Patient" = PT."Patient" 

      AND I."Company" (+)= PI."Company"

      AND  E."Employer" (+)= PI."Employer" 

      AND E."Deleted" (+) = 0

      ORDER BY LEAST(D."BillOrder", 1) DESC, 

      D."BillOrder", 

      D."Relation", 

      "HolderBirthMonth", 

      "HolderBirthDay", 

      NVL((

        SELECT t."Primary" 

        FROM ptemploy t 

        WHERE t."Patient" = PT."Patient" 

        AND t."Employer" = PI."Employer" 

        AND t."Deleted" = 0), 0) DESC, 

      PI."Company", 

      PI."Group", 

      PI."Division", 

      PT."Policy", 

      PT."PolicyId";

      

      EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;

  

  -- Ticket. 33514707 Add Insurance Info related Procedure

  PROCEDURE getinspolicydetail(IN vpolicyid integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT

      PT."PolicyId" AS "PolicyId",

      PT."Policy" AS "SubscriberNumber",

      PT."StartDate" AS "StartDate",

      PT."ResetDate" AS "EndDate",

      PI."Group" AS "Group",

      PI."Division" AS "Division",

      PI."PlanType",

      PT."LimitBalance",

      PT."DeductBalance",

      PI."HasFamilyLimit",

      PI."HasPatientLimit",

      H."Patient" AS "HolderId",

      H."Last" AS "HolderLastName",

      H."First" AS "HolderFirstName",

      TO_CHAR (H."Birth", 'MM') AS "HolderBirthMonth",  

      TO_CHAR (H."Birth", 'DD') AS "HolderBirthDay",

      I."Name" AS "InsCompanyName",

      I."Company" AS "InsCompanyCode",

      E."Name" AS "EmployerName",

      CASE

        WHEN LEAST(NVL(PT."ResetDate", PI."EndDate"), NVL(PI."EndDate", PT."ResetDate")) IS NOT NULL 

        AND LEAST(NVL(PT."ResetDate", PI."EndDate"), NVL(PI."EndDate", PT."ResetDate")) < TRUNC(SYSDATE) 

        THEN -1 

        

        WHEN GREATEST(NVL(PT."StartDate", PI."StartDate"), NVL(PI."StartDate", PT."StartDate")) > TRUNC(SYSDATE)

        THEN 1

        

        ELSE 0

      END AS "Status"



      FROM PTPOL PT, POLINS PI, PATIENT H, INSURANC I, EMPLOYER E 

      WHERE PT."PolicyId" = vPolicyId 

      AND (PT."Deleted" = 0 

        OR (PT."Date" IS NULL AND PI."Date" IS NULL) 

        OR (GREATEST(NVL(PT."Date", PI."Date"), NVL(PI."Date", PT."Date")) > TRUNC(SYSDATE)))

      AND PT."PolIns" = PI."PolIns"

      AND H."Patient" = PT."Patient" 

      AND I."Company" (+)= PI."Company"

      AND  E."Employer" (+)= PI."Employer" 

      AND E."Deleted" (+) = 0;

    

    EXCEPTION WHEN NO_DATA_FOUND THEN

    vResult := NULL;

  END;

  

  -- AX-30143 Update the correct status for insurance policy

  PROCEDURE updatecorrectstatus(IN vpolicyid integer, IN vpatient numeric, IN vstatus numeric) IS  

  BEGIN

    UPDATE PTDEPEND SET "CorrectStatus" = vStatus WHERE "PolicyId" = vPolicyId AND "Patient" = vPatient;

  END;

  

  PROCEDURE getcorrectstatus(IN vpoliciesid character varying, OUT vresult cursor_pkg.weakcursor) IS

	SQLStmt  VARCHAR2(4000);

  BEGIN

    SQLStmt := '

	  SELECT

		PTDEPEND."PolicyId",

		PTDEPEND."Patient",

		PTDEPEND."CorrectStatus"

      FROM PTDEPEND, PATIENT

      WHERE PTDEPEND."PolicyId" IN (' || vPoliciesId || ')

		AND PATIENT."Patient" = PTDEPEND."Patient" 

		AND PATIENT."Deleted" = 0

		AND PTDEPEND."Deleted" = 0 

      ORDER BY PTDEPEND."PolicyId"';

	

	OPEN vResult FOR SQLStmt;

    

    EXCEPTION WHEN NO_DATA_FOUND THEN

    vResult := NULL;

  END;



  

  -- Ticket. 33514707 Add Insurance Info related Procedure

  PROCEDURE getinspolicyuserlist(IN vpolicyid integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT

      PTDEPEND."Patient",

      PATIENT."Last" AS "LastName",

      PATIENT."Prefered" AS "FirstName",

      PTDEPEND."IsCovered",

      PTDEPEND."Relation",

      PTDEPEND."StartDate",

      PTDEPEND."EndDate",

      PTDEPEND."LimitBalance",

      PTDEPEND."DeductBalance",

	  PTDEPEND."CorrectStatus"

      FROM PTDEPEND, PATIENT

      WHERE PTDEPEND."PolicyId" = vPolicyId 

      AND PATIENT."Patient" = PTDEPEND."Patient" 

      AND PATIENT."Deleted" = 0

      AND PTDEPEND."Deleted" = 0 

      ORDER BY PTDEPEND."Patient";

    

    EXCEPTION WHEN NO_DATA_FOUND THEN

    vResult := NULL;

  END;

  

  -- Ticket. 33514727

  PROCEDURE checkstickynote(IN vtype integer, IN vpatientid integer, IN vsecondaryid integer, OUT vexist integer) IS

  BEGIN

    SELECT COUNT(1) INTO vExist FROM ISTICKYNOTE ISN

    JOIN AP_NOTE APN ON ISN."AP_NOTE_AutoDec" = APN."AP_NOTE_AutoDec"

    WHERE ISN."Type" = vType

    AND ISN."Patient" = vPatientId

    AND ISN."SecondaryId" = vSecondaryId;

  END;

  

  PROCEDURE checkstickynotebysecondarylist(IN vtype integer, IN vpatientid integer, IN vsecondaryidlist character varying, OUT vresult cursor_pkg.weakcursor) IS

  	SQLStmt  VARCHAR2(4000);

  BEGIN

    SQLStmt := 'SELECT ISN."SecondaryId" FROM ISTICKYNOTE ISN JOIN AP_NOTE APN ON ISN."AP_NOTE_AutoDec" = APN."AP_NOTE_AutoDec" WHERE ISN."Type" = ' || vType || ' AND ISN."Patient" = ' || vPatientId || ' AND ISN."SecondaryId" IN (' || vSecondaryIdList || ')';

	

	OPEN vResult FOR SQLStmt;

    

    EXCEPTION WHEN NO_DATA_FOUND THEN

    vResult := NULL;

  END;

  

  -- Ticket. 33514727

  PROCEDURE createstickynote(IN vtype integer, IN vpatientid integer, IN vsecondaryid integer, IN vmessage character varying, IN vupdateifexist integer, IN vcreationuser integer) IS

    vExist INTEGER;

    vId INTEGER;

  BEGIN

    -- Check if sticky note exist

    SELECT COUNT(1) INTO vExist FROM ISTICKYNOTE ISN

    JOIN AP_NOTE APN ON ISN."AP_NOTE_AutoDec" = APN."AP_NOTE_AutoDec"

    WHERE ISN."Type" = vType

    AND ISN."Patient" = vPatientId

    AND ISN."SecondaryId" = vSecondaryId;

	

    IF vExist = 0 OR vUpdateIfExist = 1 THEN

      BEGIN

        -- Delete any existing notes

        DELETE FROM AP_NOTE WHERE "AP_NOTE_AutoDec" IN (

          SELECT "AP_NOTE_AutoDec" 

          FROM ISTICKYNOTE 

          WHERE "Type" = vType 

          AND "Patient" = vPatientId 

          AND "SecondaryId" = vSecondaryId

        );

		

		-- Get a next note ID

		SELECT AP_NOTE_AP_NOTE_AUTODEC_SEQ.NextVal INTO vId FROM DUAL;

		

		-- Create a note in AP_NOTE table

		INSERT INTO AP_NOTE (

		  "AP_NOTE_AutoDec", "AP_NOTE_AppId", "AP_NOTE_Type", "AP_NOTE_PatientId",

		  "AddDateTime", "ModifiedDateTime", 

		  "AP_NOTE_Flag", "AP_NOTE_Date1", "AP_NOTE_Date2", "AP_NOTE_PAmount", "AP_NOTE_IAmount", 

		  "AP_NOTE_Text", 

		  "AP_NOTE_Treatment", 

		  "CreationUser", 

		  "ModifiedUser", "StationId"

		)

		VALUES (

		  vId, vPatientId, 3, 0, 

		  SYSDATE, SYSDATE, 

		  40, 0, 0, 0, 0, 

		  vMessage,

		  0, 

		  vCreationUser,

		  0, 0

		);

		

		-- Create a mapping data in ISTICKYNOTE table

		INSERT INTO ISTICKYNOTE ("Auto", "Patient", "AP_NOTE_AutoDec", "Type", "SecondaryId")

		VALUES (null, vPatientId, vId, vType, vSecondaryId);

      END;

    END IF;

  END;

  

  PROCEDURE deletestickynote(IN vtype integer, IN vpatientid integer, IN vsecondaryid integer) IS

  BEGIN

    DELETE FROM AP_NOTE WHERE "AP_NOTE_AutoDec" IN (

      SELECT "AP_NOTE_AutoDec" 

      FROM ISTICKYNOTE 

      WHERE "Type" = vType 

      AND "Patient" = vPatientId 

      AND "SecondaryId" = vSecondaryId

    );

    

    COMMIT;

  END;

  

-- Ticket. 29203967. Ability for patients to recover forgotten passwords and usernames

-- Procedure that set a record in ILog table

-- param: vUserName INPUT: User Name.<p/>

PROCEDURE setilogentry(IN vusername character varying) IS

  vIUser NUMBER(10);

  vTime NUMBER(10) := (to_number(to_char(current_date,'HH24'))*60) + to_number(to_char(current_date,'MI'));

BEGIN

  SELECT "iUser"

  INTO vIUser

  FROM IUSER WHERE NLS_LOWER("UserName") = NLS_LOWER(TRIM(vUserName)) AND "Deleted" = 0;

  

  ILogEntry(vUserName, 0, CURRENT_DATE, vTime, 'PatientAccess', viUser);

END;



-- Ticket. 29203967. Ability for patients to recover forgotten passwords and usernames

-- Procedure that set update reseted password in IUSER ILog table

-- param: vUserName INPUT: User Name.<p/>  

PROCEDURE userresetpassword(IN vusername character varying, IN vpassword character varying, OUT vstatus integer) IS  

  vHashedPassword  VARCHAR2(255);

  vId NUMBER(10) := 0;

  vAuditHis NUMBER(10); -- 55579184

  vIUser NUMBER(10); -- 55579184

BEGIN

    SELECT "Id", "iUser" INTO vId, viUser FROM IUSER WHERE NLS_LOWER("UserName") = NLS_LOWER(TRIM(vUserName)); -- TODO: lowered username index must be implemented.



	vHashedPassword := vPassword;



    CreateAudithis(viUser, 'IUSER', 2, vAuditHis);	-- 55579184 Create a new AUDITHIS record and set new AuditHisId in vAuditHis variable



	--UPDATE IUSER SET "Password" = vHashedPassword, "IsTemp" = 0 -- AX-4199.25082 Set "IsTemp" = 0

	UPDATE IUSER SET "Password" = vHashedPassword, "PwdLastChanged" = current_date, "Audit" = vAuditHis, "IsTemp" = 0

	WHERE "Id" = vId;

	vStatus := 0; -- Success

	

    exception

       WHEN NO_DATA_FOUND THEN vStatus := 3;  -- Invalid username. No record found. Should not happen as using current logged in user's username.

       -- Don't worry about if more than one record found - throw error as should never happen. 

END;



-- Ticket. 36889047. History records are not being created when patient information is updated from PA

-- Procedure insert a new record in AUDITHIS table when patient edit information

-- param: vUser INPUT: User Id<p/>  

-- param: vTableName INPUT: Table Name<p/>  

-- param: vHistoryType INPUT: Type of audit record (0=Unknown, 1=Add, 2=Edit,  4=Delete)<p/>  

-- param: vAuditHis OUTPUT: New Audithis record id<p/>  

-- AX-37592

PROCEDURE createaudithis(IN vuser numeric, IN vtablename character, IN vhistorytype numeric, OUT vaudithis numeric) IS  

  vTime NUMBER(10) := (to_number(to_char(SYSDATE,'HH24'))*60) + to_number(to_char(SYSDATE,'MI'));  -- Is there a function already existing that can call here?

BEGIN

    SELECT AUDITHIS_Audit_SEQ.NEXTVAL INTO vAuditHis FROM DUAL;

	

    INSERT INTO AUDITHIS("Audit", "Date", "Time", "User", "StationId", "TableName", "HistoryType") 

	             VALUES(vAuditHis, TRUNC(SYSDATE), vTime, vUser, 0,  vTableName, vHistoryType);       --Insert a record in AUDITHIS table

END;



-- Ticket. 59160046. iUser auditing: User field is blank after Self-registration (5.30+)

-- Procedure update UserId in AUDITHIS table for new IUSERS

-- param: vUser INPUT: User Id<p/>  

-- param: vAuditHis INPUT: Audithis record id<p/>  

-- param: vResult OUTPUT: Result: 0 - Updated, -1 - Fail<p/>

PROCEDURE updateuserinaudithis(IN vuser numeric, IN vaudithis numeric, OUT vresult integer) IS

    SQlStmt  VARCHAR2(4000);

BEGIN



    SQLStmt := 'UPDATE AUDITHIS SET "User" = :1 WHERE "Audit" = :2';       --Update UserId in AUDITHIS table

	EXECUTE IMMEDIATE SQLStmt USING vUser, vAuditHis;

	vResult := sql%rowcount;                                               --Nothing updated vResult equal cero

	EXCEPTION WHEN OTHERS THEN

	   vResult := -1;

END;





  -- Ticket 36198601 - Ability to see specific policy limit/deductible balances for insurance policies.

  PROCEDURE getinspolicylimitanddeductlist(IN vpolicyid integer, IN vpatient integer, OUT vresult cursor_pkg.weakcursor) IS

    vIsStudent INTEGER;

    vPatientAge INTEGER;

    vCoverageAge INTEGER;

    vCoverageAgeStud INTEGER;

    vAdultCoverageId INTEGER;

    vChildCoverageId INTEGER;

    vCoverageId INTEGER;

	SQlStmt  VARCHAR2(4000);

  BEGIN

  

    -- Get Patient information (Student Status, Age)

    BEGIN

      SELECT P."IsStudent", FLOOR(TRUNC(months_between(SYSDATE, P."Birth"))/12)

      INTO vIsStudent, vPatientAge

      FROM PATIENT P

      WHERE P."Patient" = vPatient;

      

      EXCEPTION WHEN NO_DATA_FOUND THEN

        vIsStudent := 0;

        vPatientAge := 0;

    END;

	

    -- Get Policy Settings for coverage types (Age for regular/students, coverage IDs)

    BEGIN

      SELECT PI."CoverageAge", PI."CoverageAgeStud", PI."AdultCoverage", PI."ChildCoverage"

      INTO vCoverageAge, vCoverageAgeStud, vAdultCoverageId, vChildCoverageId 

      FROM PTPOL PP, POLINS PI 

      WHERE PP."PolIns" = PI."PolIns"

      AND PP."PolicyId" = vPolicyId

      AND ROWNUM = 1;

      

      EXCEPTION WHEN NO_DATA_FOUND THEN

        vCoverageAge := 0;

        vCoverageAgeStud := 0;

        vAdultCoverageId := 0;

        vChildCoverageId := 0;

    END;

    

    -- Get proper coverage ID based on patient's age and student status

    BEGIN

      IF vIsStudent = 1 THEN

        IF vPatientAge > vCoverageAgeStud THEN

          vCoverageId := vAdultCoverageId;

        ELSE

          vCoverageId := vChildCoverageId;

        END IF;

      ELSE

        IF vPatientAge > vCoverageAge THEN

          vCoverageId := vAdultCoverageId;

        ELSE

          vCoverageId := vChildCoverageId;

        END IF;

      END IF;

    END;

    

    -- Check if coverage ID is available

    IF vCoverageId = 0 THEN

      BEGIN

        OPEN vResult FOR

          SELECT D.*, PP."PolIns",

            CASE WHEN NOT (TRIM("Category") IS NULL OR LENGTH(TRIM("Category")) = 0) THEN 1

            ELSE 0

            END AS "IsCategory",

          PPORTAL_PKG.GetAffectFamily(vCoverageId, "PolIns", "Id", "Category") AS "AffectFamily",

          PPORTAL_PKG.GetHasLimit(vCoverageId, "PolIns", "Id", "Category") AS "HasLimit"

          

          FROM DEPLIMIT D

          LEFT JOIN PTPOL PP ON D."PolicyId" = PP."PolicyId"

          WHERE D."PolicyId" = vPolicyId 

          AND  D."Patient" = vPatient

            

          ORDER BY D."Id", D."Category";

        

        EXCEPTION WHEN NO_DATA_FOUND THEN

          vResult := NULL;

      END;

    ELSE

      BEGIN

        OPEN vResult FOR

          SELECT D.*,

            CASE WHEN NOT (TRIM("Category") IS NULL OR LENGTH(TRIM("Category")) = 0) THEN 1

            ELSE 0

            END AS "IsCategory",

          PPORTAL_PKG.GetAffectFamily(vCoverageId, 0, "Id", "Category") AS "AffectFamily",

          PPORTAL_PKG.GetHasLimit(vCoverageId, 0, "Id", "Category") AS "HasLimit"

          FROM DEPLIMIT D

          WHERE D."PolicyId" = vPolicyId 

          AND D."Patient" = vPatient

          AND

          (

            D."CoverageId" = vCoverageId

            OR D."CoverageId" IN

            (

              select

              (

                case when

                (

                  p."Birth" IS NOT NULL and 

                  (

                    trunc(MONTHS_BETWEEN(trunc(sysdate),p."Birth")/12) < PR."RiderAge"

                    OR 

                    (

                      p."IsStudent" > 0 

                      and (trunc(MONTHS_BETWEEN(trunc(sysdate),p."Birth")/12) < PR."RiderAgeStud")

                    )

                  )

                )        

                then PR."RiderChildCoverage" 

                else PR."RiderAdultCoverage" end

              )        

              from POLRIDER PR, patient p, policy o 

              where D."PolicyId" = o."PolicyId"        

              and p."Patient" = vPatient 

              and PR."PolIns" = o."PolIns"

            )

          )  

          AND EXISTS 

          (

            select 1 

            from coverit c, patient p 

            where D."CoverageId" = c."Coverage"

            and 

            (

              (

                D."Id" > 0 

                and D."Id" = c."Item"

              ) 

              or 

              (

                D."Id" = 0 

                and D."Category" = c."Category"

              )

            )    

            and p."Patient" = vPatient 

            and 

            (

              c."AgeRules" = 0 

              OR p."Birth" = NULL      

              OR 

              (

                trunc(MONTHS_BETWEEN(trunc(sysdate),p."Birth")/12) between c."AgeFrom" and c."AgeTo"

              )

            )

          ) 

          ORDER BY D."Id", D."Category";

          

        EXCEPTION WHEN NO_DATA_FOUND THEN

          vResult := NULL;

      END;

    END IF;

  END;



  -- Ticket 36732337 - Disallow changing of password to previous passwords  

  -- param: viUser INPUT: iUser Id<p/>  

  -- param: vPassword INPUT: Password<p/>  

  -- param: vUserPwhId OUTPUT: New IUserPwh record id<p/>  

  PROCEDURE updateiuserpwh(IN viuser numeric, IN vpassword character varying, OUT vuserpwhid numeric) IS

  BEGIN

    SELECT IUSERPWH_IUSERPWH_SEQ.NEXTVAL INTO vUserPwhId FROM dual;

    INSERT INTO IUSERPWH ("iUserPwhId", "iUser", "Password", "PasswordSetDate", "Type") VALUES (vUserPwhId, viUser, vPassword, current_date, 1);

  END;



  -- Ticket 38103735 - Retain entered security questions and answers in Change Security Questions.

  -- param: vPatientId INPUT: Patient ID from PATIENT."Patient"

  -- param: vResult OUTPUT: weak cursor containing security questions and answers for the patient

  PROCEDURE getsecurityquestionsanswers(IN vpatientid integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT U."Id",

      U."PasswordQuestion1", 

      U."PasswordQuestion2", 

      U."PasswordQuestion3", 

      Q1."Description" AS "PasswordQuestionText1",

      Q2."Description" AS "PasswordQuestionText2",

      Q3."Description" AS "PasswordQuestionText3",

      U."PasswordAnswer1", 

      U."PasswordAnswer2",

      U."PasswordAnswer3" 

      FROM IUSER U 

      LEFT JOIN ISECUREQ Q1 ON U."PasswordQuestion1" = Q1."iSecureQ" 

      LEFT JOIN ISECUREQ Q2 ON U."PasswordQuestion2" = Q2."iSecureQ" 

      LEFT JOIN ISECUREQ Q3 ON U."PasswordQuestion3" = Q3."iSecureQ" 

      WHERE U."Id" = vPatientId;

  END;

  

  -- Ticket 38051723

  -- internal function to help get status for if the item affects other family members

  FUNCTION getaffectfamily(vcoverageid integer, vpolins integer, vid integer, vcategory character varying) RETURN integer IS

    vAffectFamily INTEGER;

  BEGIN

    IF NOT (TRIM(vCategory) IS NULL OR LENGTH(TRIM(vCategory)) = 0) THEN

      BEGIN

      IF vCoverageId = 0 THEN

        BEGIN

          SELECT "CatAffectFamily" INTO vAffectFamily

          FROM POLRANGE

          WHERE "PolIns" = vPolIns

          AND "Category" = vCategory

          AND ROWNUM = 1;

          

          EXCEPTION WHEN NO_DATA_FOUND THEN

            vAffectFamily := 0;

        END;

      ELSE

        BEGIN

          SELECT "CatAffectFamily" INTO vAffectFamily

          FROM COVERIT

          WHERE "Coverage" = vCoverageId

          AND "Category" = vCategory

          AND ROWNUM = 1;

          

          EXCEPTION WHEN NO_DATA_FOUND THEN

            vAffectFamily := 0;

        END;

      END IF;

      END;

    ELSE

      BEGIN

      IF vCoverageId = 0 THEN

        BEGIN

          SELECT "ItemAffectFamily" INTO vAffectFamily

          FROM POLRANGE

          WHERE "PolIns" = vPolIns

          AND "Id" = vId

          AND ROWNUM = 1;

          

          EXCEPTION WHEN NO_DATA_FOUND THEN

            vAffectFamily := 0;

        END;

      ELSE

        BEGIN

          SELECT "ItemAffectFamily" INTO vAffectFamily

          FROM COVERIT

          WHERE "Coverage" = vCoverageId

          AND "Item" = vId

          AND ROWNUM = 1;

          

          EXCEPTION WHEN NO_DATA_FOUND THEN

            vAffectFamily := 0;

        END;

      END IF;

      END;

    END IF;

    

    RETURN vAffectFamily;

  END;

  

  -- Ticket 38051723

  -- internal function to help get status for if the item has limit enabled

  FUNCTION gethaslimit(vcoverageid integer, vpolins integer, vid integer, vcategory character varying) RETURN integer IS

    vHasLimit INTEGER;

  BEGIN

    IF NOT (TRIM(vCategory) IS NULL OR LENGTH(TRIM(vCategory)) = 0) THEN

      BEGIN

      IF vCoverageId = 0 THEN

        BEGIN

          SELECT "HasCatLimit" INTO vHasLimit

          FROM POLRANGE

          WHERE "PolIns" = vPolIns

          AND "Category" = vCategory

          AND ROWNUM = 1;

          

          EXCEPTION WHEN NO_DATA_FOUND THEN

            vHasLimit := 0;

        END;

      ELSE

        BEGIN

          SELECT "HasCatLimit" INTO vHasLimit

          FROM COVERIT

          WHERE "Coverage" = vCoverageId

          AND "Category" = vCategory

          AND ROWNUM = 1;

          

          EXCEPTION WHEN NO_DATA_FOUND THEN

            vHasLimit := 0;

        END;

      END IF;

      END;

    ELSE

      BEGIN

      IF vCoverageId = 0 THEN

        BEGIN

          SELECT "HasItemLimit" INTO vHasLimit

          FROM POLRANGE

          WHERE "PolIns" = vPolIns

          AND "Id" = vId

          AND ROWNUM = 1;

          

          EXCEPTION WHEN NO_DATA_FOUND THEN

            vHasLimit := 0;

        END;

      ELSE

        BEGIN

          SELECT "HasItemLimit" INTO vHasLimit

          FROM COVERIT

          WHERE "Coverage" = vCoverageId

          AND "Item" = vId

          AND ROWNUM = 1;

          

          EXCEPTION WHEN NO_DATA_FOUND THEN

            vHasLimit := 0;

        END;

      END IF;

      END;

    END IF;

    

    RETURN vHasLimit;

  END;

  

   -- 41655511

  PROCEDURE getpatientiuserbyusername(IN vusername character varying, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT PT."Patient", PT."Last", PT."First", PT."Prefered", PT."Middle", PT."Title",	PT."Birth", PT."Address1", PT."Address2",	  

             PT."City", PT."Province", PT."Postal", PT."Country", PT."AddressOther", PT."HomeArea", PT."HomePhone",	  

             PT."WorkArea", PT."WorkPhone", PT."WorkExt", PT."OtherArea", PT."OtherPhone", PT."OtherExt",	PT."MobileArea",	  

             PT."MobilePhone", PT."ContactAt", PT."ContactTime", PT."Email", PT."InfoNotify", PT."Audit", PT."PrefLanguage", 

			 PT."RaceEthDeclined", PT."Ethnic", PT."IsPatient",

       PT."CustomCode1", PT."CustomCode2", PT."CustomCode3", PT."CustomCode4", PT."CustomCode5", PT."CustomCode6", PT."CustomCode7", PT."CustomCode8", PT."CustomCode9", PT."CustomCode10",

       PT."CustomText1", PT."CustomText2", PT."CustomText3", PT."CustomText4", PT."CustomText5",

			 PT."EmergLast", PT."EmergFirst", PT."EmergMiddle", PT."EmergAddress",

			 PT."EmergAddress2", PT."EmergCity", PT."EmergProvince", PT."EmergPostal", 

			 PT."EmergAddressOther", PT."EmergArea", PT."EmergPhone", PT."EmergExt",

			 PT."EmergRelation", PT."EmergAltArea", PT."EmergAltPhone", PT."EmergAltExt",

			 IU."iUser", IU."Id", IU."UserName", IU."IsTemp", IU."IsAgreed", IU."IsLocked", /*IU."AccessAudit",*/ IU."Deleted", IU."MsgAccess"

      FROM PATIENT PT

	  JOIN IUSER IU ON IU."Id" = PT."Patient"

      WHERE IU."UserName" = vUserName;



    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;	  

  END;

  

  -- 59797918 Get Patient and IUser infro by iUser Id

  PROCEDURE getpatientiuserbyiuser(IN viuser integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT PT."Patient", PT."Last", PT."First", PT."Prefered", PT."Middle", PT."Title",	PT."Birth", PT."Address1", PT."Address2",	  

             PT."City", PT."Province", PT."Postal", PT."Country", PT."AddressOther", PT."HomeArea", PT."HomePhone",	  

             PT."WorkArea", PT."WorkPhone", PT."WorkExt", PT."OtherArea", PT."OtherPhone", PT."OtherExt",	PT."MobileArea",	  

             PT."MobilePhone", PT."ContactAt", PT."ContactTime", PT."Email", PT."InfoNotify", PT."Audit", PT."PrefLanguage", 

			 PT."RaceEthDeclined", PT."Ethnic", PT."IsPatient",

       PT."CustomCode1", PT."CustomCode2", PT."CustomCode3", PT."CustomCode4", PT."CustomCode5", PT."CustomCode6", PT."CustomCode7", PT."CustomCode8", PT."CustomCode9", PT."CustomCode10",

       PT."CustomText1", PT."CustomText2", PT."CustomText3", PT."CustomText4", PT."CustomText5",

			 PT."EmergLast", PT."EmergFirst", PT."EmergMiddle", PT."EmergAddress",

			 PT."EmergAddress2", PT."EmergCity", PT."EmergProvince", PT."EmergPostal", 

			 PT."EmergAddressOther", PT."EmergArea", PT."EmergPhone", PT."EmergExt",

			 PT."EmergRelation", PT."EmergAltArea", PT."EmergAltPhone", PT."EmergAltExt", 

			 IU."iUser", IU."Id", IU."UserName", IU."IsTemp", IU."IsAgreed", IU."IsLocked", /*IU."AccessAudit",*/ IU."Deleted", IU."MsgAccess",

			 IU."PasswordQuestion1", IU."PasswordAnswer1", IU."PasswordQuestion2", IU."PasswordAnswer2", IU."PasswordQuestion3", IU."PasswordAnswer3",

			 IU."PersonalInfoCorrect"

      FROM PATIENT PT

	  JOIN IUSER IU ON IU."Id" = PT."Patient"

      WHERE IU."iUser" = viUser;



    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;	  

  END;

  

   -- 41655511

  PROCEDURE updatepatientinfo(IN vpatientid integer, IN vlast character varying, IN vfirst character varying, IN vprefered character varying, IN vmiddle character varying, IN vtitle character varying, IN vbirth timestamp without time zone, IN vaddress1 character varying, IN vaddress2 character varying, IN vcity character varying, IN vprovince character varying, IN vpostal character varying, IN vcountry character varying, IN vaddressother character varying, IN vhomearea character varying, IN vhomephone character varying, IN vworkarea character varying, IN vworkphone character varying, IN vworkext character varying, IN votherarea character varying, IN votherphone character varying, IN votherext character varying, IN vmobilearea character varying, IN vmobilephone character varying, IN vcontactat character varying, IN vcontacttime character varying, IN vemail character varying, IN vinfonotify integer, IN vaudit integer, IN vpreflang character varying, IN vraceethdeclined integer, IN vethnic character varying, IN vcustom1 character varying, IN vcustom2 character varying, IN vcustom3 character varying, IN vcustom4 character varying, IN vcustom5 character varying, IN vcustom6 character varying, IN vcustom7 character varying, IN vcustom8 character varying, IN vcustom9 character varying, IN vcustom10 character varying, IN vcustomtext1 character varying, IN vcustomtext2 character varying, IN vcustomtext3 character varying, IN vcustomtext4 character varying, IN vcustomtext5 character varying, IN vemerglast character varying, IN vemergfirst character varying, IN vemergmiddle character varying, IN vemergaddress character varying, IN vemergaddress2 character varying, IN vemergcity character varying, IN vemergprovince character varying, IN vemergpostal character varying, IN vemergaddressother character varying, IN vemergarea character varying, IN vemergphone character varying, IN vemergext character varying, IN vemergrelation character varying, IN vemergaltarea character varying, IN vemergaltphone character varying, IN vemergaltext character varying, OUT vresult integer) IS							  

    SQlStmt  VARCHAR2(8000);

  BEGIN



    SQLStmt := 'UPDATE PATIENT SET "Last" = :1, "First" = :2, "Prefered" = :3, "Middle" = :4, 

                     "Title" = :5, "Birth" = :6, "Address1" = :7, "Address2" = :8, "City" = :9, 

                     "Province" = :10, "Postal" = :11, "Country" = :12, "AddressOther" = :13, "HomeArea" = :14, 

                     "HomePhone" = :15, "WorkArea" = :16, "WorkPhone" = :17, "WorkExt" = :18, "OtherArea" = :19, 

                     "OtherPhone" = :20, "OtherExt" = :21, "MobileArea" = :22, "MobilePhone" = :23, "ContactAt" = :24, 

                     "ContactTime" = :25, "Email" = :26, "InfoNotify" = :27, "Audit" = :28, "PrefLanguage" = :29, 

                      "RaceEthDeclined" = :30, "Ethnic" = :31,

                      "CustomCode1" = :32, "CustomCode2" = :33, "CustomCode3" = :34, "CustomCode4" = :35, "CustomCode5" = :36, 

                      "CustomCode6" = :37, "CustomCode7" = :38, "CustomCode8" = :39, "CustomCode9" = :40, "CustomCode10" = :41, 

                      "CustomText1" = :42, "CustomText2" = :43, "CustomText3" = :44, "CustomText4" = :45, "CustomText5" = :46,

											"EmergLast" = :47, "EmergFirst" = :48, "EmergMiddle" = :49, "EmergAddress" = :50,

											"EmergAddress2" = :51, "EmergCity" = :52, "EmergProvince" = :53, "EmergPostal" = :54, 

											"EmergAddressOther" = :55, "EmergArea" = :56, "EmergPhone" = :57, "EmergExt" = :58,

											"EmergRelation" = :59, "EmergAltArea" = :60, "EmergAltPhone" = :61, "EmergAltExt" = :62,

											"LastUpper" = :63, "PrefUpper" = :64

                WHERE "Patient" = :65';  

    EXECUTE IMMEDIATE SQlStmt USING vLast, vFirst, vPrefered, vMiddle, 

                    vTitle, vBirth, vAddress1, vAddress2, vCity, 

                    vProvince, vPostal, vCountry, vAddressOther, vHomeArea, 

                    vHomePhone, vWorkArea, vWorkPhone, vWorkExt, vOtherArea, 

                    vOtherPhone, vOtherExt, vMobileArea, vMobilePhone, vContactAt, 

                    vContactTime, vEmail, vInfoNotify, vAudit, vPrefLang,

										vRaceEthDeclined, vEthnic,

                    vCustom1, vCustom2, vCustom3, vCustom4, vCustom5, 

                    vCustom6, vCustom7, vCustom8, vCustom9, vCustom10, 

                    vCustomText1, vCustomText2, vCustomText3, vCustomText4, vCustomText5,

										vEmergLast, vEmergFirst, vEmergMiddle, vEmergAddress,

										vEmergAddress2, vEmergCity, vEmergProvince, vEmergPostal, 

										vEmergAddressOther, vEmergArea, vEmergPhone, vEmergExt,

										vEmergRelation, vEmergAltArea, vEmergAltPhone, vEmergAltExt,

										NLS_UPPER(vLast), NLS_UPPER(vPrefered),

                    vPatientId;    

    COMMIT;

    vResult := 0;

    EXCEPTION WHEN OTHERS THEN

      vResult := -1;  

  END;

  

  -- 38115205 Create new IUSER with  

  PROCEDURE createiuserwithnamepassword(IN vtype numeric, IN vid numeric, IN vusername character varying, IN vpassword character varying, IN vaudit numeric, IN vquestion1 integer, IN vquestion2 integer, IN vquestion3 integer, IN vanswer1 character varying, IN vanswer2 character varying, IN vanswer3 character varying, OUT viuser numeric) IS

    vUsernameCount NUMBER(10) := 0;

  BEGIN

    SELECT COUNT(*) INTO vUsernameCount FROM IUser WHERE NLS_LOWER("UserName") = NLS_LOWER(TRIM(vUsername));



	IF vUsernameCount = 0 THEN

	  SELECT USERS_USER_SEQ.NEXTVAL INTO viUser FROM dual;

	  INSERT INTO IUSER VALUES (

		  viUser,

		  vType,

		  vId,

		  vUserName,

		  vPassword,

		  0,

		  0,

		  0,

		  vAudit,

		  0,

		  vQuestion1, vAnswer1, vQuestion2, vAnswer2, vQuestion3, vAnswer3, 0, null, 0, current_date, 1, null, 0, null, 0);	-- AX-25371.5, AX-25373.5 add null for LastEmailDateTime, AX-29988

	ELSE

		viUser := -1; -- Username already in use.

	END IF;		  

  END;



  -- 38115205 Add a IForm to a patient in IPTFORM table  

  PROCEDURE addiformtopatient(IN vpatient numeric, IN vformcode character varying, IN vpfrom numeric, IN viuser numeric, IN vaccess integer, IN vorder integer, IN vreqattention integer, OUT viptform numeric) IS

    vIFormCount NUMBER(10) := 0;

    vFormStatus NUMBER(10) := 0;

	vLastSavedPageNumber NUMBER(5) := 0;

  BEGIN

    SELECT COUNT(*) INTO vIFormCount FROM IPTFORM WHERE "Patient" = vPatient AND "FormCode" = vFormCode AND "iUser" = vIUser;



	IF vIFormCount = 0 THEN

	  SELECT IPTFORM_IPTFORM_SEQ.NEXTVAL INTO vIPtForm FROM dual;

	  

	    INSERT INTO IPTFORM ("iPtForm", "Patient", "FormCode", "PForm", "iUser", "Access", "Order", "RequiresAttention", "FormStatus", "LastSavedPageNumber") 

									 VALUES (vIPtForm,  vPatient,  vFormCode,  vPFrom,  vIUser,  vAccess,  vOrder,  vReqAttention, vFormStatus, vLastSavedPageNumber);

	ELSE

		vIPtForm := -1; -- Form already in exist

	END IF;		  

  END;



  -- 49217375 Get User First and Last name by UserId

  PROCEDURE getusernamebyid(IN vuser integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT UR."User", UR."Name", UR."First"

      FROM USERS UR

      WHERE UR."User" = vUser;



    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;	  

  END;

  

  -- 52499031 Get Language fields from LANGCD table by Language Code

  PROCEDURE getlanguagebylangcd(IN vlangcd character varying, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT LG."LangCd", LG."Description", LG."ISOCode", LG."IsDeclined", LG."Default", LG."Inactive"

      FROM LANGCD LG

      WHERE TRIM(LG."LangCd") = TRIM(vLangCd);

	

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;	  

  END;

  

  PROCEDURE getlanguagesbylangscd(IN vlangcdlist character varying, OUT vresult cursor_pkg.weakcursor) IS

  	SQLStmt  VARCHAR2(4000);

  BEGIN

    SQLStmt := 'SELECT LG."LangCd", LG."Description", LG."ISOCode", LG."IsDeclined", LG."Default", LG."Inactive" FROM LANGCD LG WHERE TRIM(LG."LangCd") IN (' || vLangCdList || ')';

	

	OPEN vResult FOR SQLStmt;

    

    EXCEPTION WHEN NO_DATA_FOUND THEN

    vResult := NULL;

  END;

  

  -- 52499051 Get Active Languages from LANGCD table

  PROCEDURE getactivelanguages(OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT LG."LangCd", LG."Description", LG."ISOCode", LG."IsDeclined", LG."Default", LG."Inactive"

      FROM LANGCD LG

      WHERE LG."Inactive" = 0

	  ORDER BY LG."Description";



      EXCEPTION WHEN NO_DATA_FOUND THEN

        vResult := NULL;	  

  END;



  -- 52498863 Get Ethnicity fields from ETHNIC table by Ethnic code

  PROCEDURE getethnicitybyethnic(IN vethnic character varying, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT ET."Ethnic", ET."Description", ET."USType", ET."Inactive"

      FROM ETHNIC ET

      WHERE ET."Ethnic" = vEthnic;



    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;	

  END;  



  -- 52499005 Get Active Ethnicity from ETHNIC table

  PROCEDURE getactiveethnicity(OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT ET."Ethnic", ET."Description", ET."USType", ET."Inactive"

      FROM ETHNIC ET

      WHERE ET."Inactive" = 0;



    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;	

  END;  

  

   -- 52498815 GetRaces from RACE table by Patient

  PROCEDURE getracesbypatient(IN vpatient character varying, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT RC."Race", RC."Description", RC."USType", RC."Inactive"

      FROM RACE RC

	  JOIN PTRACE PR ON RC."Race" = PR."Race"

      WHERE PR."Patient" = vPatient 

	  AND PR."Deleted" = 0

	  ORDER BY RC."Description";

	  

	EXCEPTION WHEN NO_DATA_FOUND THEN

	  vResult := NULL;

  END;

    

  -- 52498835 Get active Races from RACE table

  PROCEDURE getraces(OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT RC."Race", RC."Description", RC."USType", RC."Inactive"

      FROM RACE RC

      WHERE RC."Inactive" = 0

	  ORDER BY RC."Description";

	  

	EXCEPTION WHEN NO_DATA_FOUND THEN

	  vResult := NULL;

  END;

	

  -- 52498835 Get Race by Race field from RACE table

  -- AX-20931, AX-20855, AX-20377 - SF-00176875 ajcm  Mar. 02,2018  Fix GetRaceByRace to use the race date type instead of VARCHAR2.

  PROCEDURE getracebyrace(IN vrace character, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT RC."Race", RC."Description", RC."USType", RC."Inactive"

      FROM RACE RC

      WHERE RC."Race" = vRace;



    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;	

  END;  

	

  -- 52498815 GetPatient Races from PTRACE table by PatientId

  PROCEDURE getpatientracesbypatient(IN vpatient character varying, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT PR."Patient", PR."Race", PR."Deleted", PR."Audit"

      FROM PTRACE PR

      WHERE PR."Patient" = vPatient;

	  

	EXCEPTION WHEN NO_DATA_FOUND THEN

	  vResult := NULL;

  END;



  -- 52498815 GetPatient Active Races from PTRACE table by PatientId

  PROCEDURE getpatientactiveracesbypatient(IN vpatient character varying, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT PR."Patient", PR."Race", PR."Deleted", PR."Audit"

      FROM PTRACE PR

      WHERE PR."Patient" = vPatient 

      AND PR."Deleted" = 0;

	  

	EXCEPTION WHEN NO_DATA_FOUND THEN

	  vResult := NULL;

  END;

  

  -- 52498815 Update Patient Race Informationin PTRACE table

  PROCEDURE updatepatientrace(IN vpatient numeric, IN vrace character, IN vdeleted numeric, IN vaudit numeric) IS  

  BEGIN

    UPDATE PTRACE SET "Deleted" = vDeleted, "Audit" = vAudit WHERE "Patient" = vPatient AND "Race" = vRace;

  END;



  -- 52498815 Update Patient Race Informationin PTRACE table

  PROCEDURE addpatientrace(IN vpatient numeric, IN vrace character, IN vdeleted numeric, IN vaudit numeric) IS  

  BEGIN

    INSERT INTO PTRACE ("Patient", "Race", "Deleted", "Audit") VALUES (vPatient, vRace, vDeleted, vAudit);    

  END;

  

  -- 59797918 Get all patients for a Guarantor by iUser

  PROCEDURE getguarantorpatientbyiuser(IN viuser integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT DISTINCT PT."Patient", IU."iUser", IU."UserName", IA."RespiUser", PT."Title", PT."First", PT."Last", IA."RespiUser", PT."Prefered"

      FROM IACCESS IA

      JOIN IUSER IU ON  IA."iUser" = IU."iUser"

      JOIN PATIENT PT ON IU."Id" = PT."Patient"

      WHERE IA."RespiUser" = viUser

      AND IA."Deleted" = 0;



    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;

  

  -- 60293906 Get all Guarantors for a Patient by iUser (Deleted Guarantor or Historical Guarantor)

  PROCEDURE getpatientguarantorsbyiuser(IN vpatient integer, IN viuser integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

	OPEN vResult FOR

		SELECT PT."Patient", IU."iUser", IU."UserName", IA."RespiUser", PT."Title", PT."First", PT."Last"

		FROM IACCESS IA

		JOIN IUSER IU ON  IA."RespiUser" = IU."iUser"

		JOIN PATIENT PT ON IU."Id" = PT."Patient"

		WHERE IA."iUser" = viUser

		AND (IA."Deleted" = 0 OR (SELECT COUNT(1) FROM AUDITLOG AU WHERE AU."User" = IA."RespiUser" AND AU."Patient" = vPatient) > 0)

		ORDER BY IA."RespiUser";

      

		EXCEPTION WHEN NO_DATA_FOUND THEN

        vResult := NULL;

  END;



  -- 63762608 Get Audit Hash Value 

  PROCEDURE getaudithashvalue(IN npatientid numeric, IN ddate timestamp without time zone, IN nuserid numeric, IN nstationid numeric, IN nactiontype numeric, IN ctablename character varying, IN cprimaryinfo character varying, IN cadditionalinfo character varying, IN csecretkey character varying, OUT vhashvalue character varying) IS

    dFormatDate     DATE;

  BEGIN

  SELECT TO_DATE(TO_CHAR(dDate, 'YYYY-MON-DD HH24:MI:SS'), 'YYYY-MON-DD HH24:MI:SS') INTO dFormatDate FROM DUAL;

  

    vHashValue := AUDITLOG_PKG.GetHashValue(nPatientId, dFormatDate, nUserId, nStationId, nActionType, cTableName, cPrimaryInfo, cAdditionalInfo, cSecretKey);

  END;

  

  

  -- 60293906 Get AuditLog Activity

  PROCEDURE getauditlogactivity(IN vpatient integer, IN viuser integer, IN vbegindate timestamp without time zone, IN venddate timestamp without time zone, IN vactionadd integer, IN vactionedit integer, IN vactiondelete integer, IN vactionview integer, IN vactionprint integer, IN vactioncopy integer, IN vactionpreview integer, IN vorderby character varying, IN vitemsperpage integer, INOUT vpage integer, OUT vtotalpages integer, OUT vresult cursor_pkg.weakcursor) IS

  	SqlStmt  VARCHAR2(8000);

    vMaxRow INTEGER;

    vMinRow INTEGER;  

  BEGIN

		

    --Count all items with matching criteria

    IF vItemsPerPage = 0 THEN

      vTotalPages := 0;

    ELSE

      SELECT CEIL(COUNT(1)/vItemsPerPage) INTO vTotalPages

        FROM AUDITLOG AU

        JOIN IUSER IU ON AU."User" = IU."iUser"

        JOIN PATIENT PT ON IU."Id" = PT."Patient"

        WHERE AU."Patient" = vPatient

        AND (viUser = 0 OR AU."User" = viUser)

        AND (AU."Date" >= vBeginDate AND AU."Date" <= vEndDate)		 

        AND ((vActionAdd = 1 AND AU."ActionType" = 0) OR (vActionEdit = 1 AND AU."ActionType" = 1) OR (vActionDelete = 1 AND AU."ActionType" = 2) OR (vActionView = 1 AND AU."ActionType" = 3)  OR 

             (vActionPrint = 1 AND AU."ActionType" = 4) OR (vActionCopy = 1 AND AU."ActionType" = 5) OR (vActionPreview = 1 AND AU."ActionType" = 6));

    END IF;

    

    IF vTotalPages < vPage THEN

    vPage := vTotalPages;

    ELSIF vPage < 1 THEN

    vPage := 1;

    END IF;

    

    vMaxRow := vPage * vItemsPerPage;

    vMinRow := (vPage - 1) * vItemsPerPage + 1; 

    

    --Get all items within the page range

    SqlStmt := '

    SELECT A.* FROM

    (

      SELECT B.*, ROWNUM AS "RowNum" FROM

      (

        SELECT AU."Patient",

        PT."First", 

        PT."Last", 

        AU."Date", 

        AU."User", 

        AU."ActionType",

        CASE WHEN AU."ActionType" = 0 THEN ''Add'' WHEN AU."ActionType" = 1 THEN ''Edit'' WHEN AU."ActionType" = 2 THEN ''Delete'' 

             WHEN AU."ActionType" = 3 THEN ''View'' WHEN AU."ActionType" = 4 THEN ''Print'' WHEN AU."ActionType" = 5 THEN ''Copy'' WHEN AU."ActionType" = 6 THEN ''Preview'' END AS "Action",

        AU."TableName", 

        AU."PrimaryInfo", 

        AU."AdditionalInfo",

        AU."Station",

        AU."HashValue"

        FROM AUDITLOG AU

        JOIN IUSER IU ON AU."User" = IU."iUser"

        JOIN PATIENT PT ON IU."Id" = PT."Patient"

        WHERE  AU."Patient" = :PatId

        AND (:IUser1 = 0 OR AU."User" = :IUser2)

        AND (AU."Date" >= :BeginDate  AND AU."Date" <= :EndDate)			 

        AND ((:ActionAdd = 1 AND AU."ActionType" = 0) OR (:ActionEdit = 1 AND AU."ActionType" = 1) OR (:ActionDelete = 1 AND AU."ActionType" = 2) OR (:ActionView = 1 AND AU."ActionType" = 3) OR 

             (:ActionPrint = 1 AND AU."ActionType" = 4) OR (:ActionCopy = 1 AND AU."ActionType" = 5) OR (:ActionPreview = 1 AND AU."ActionType" = 6))

    ';



    CASE  

       WHEN vOrderBy = 'DATE_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') ASC, "SecondarySortKey" ASC, NLS_UPPER(TRIM("Action")) DESC';

       WHEN vOrderBy = 'DATE_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, "SecondarySortKey" DESC, NLS_UPPER(TRIM("Action")) DESC';

       WHEN vOrderBy = 'ACTIONED_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY NLS_UPPER(TRIM("First" || "Last")) ASC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, "SecondarySortKey" DESC, NLS_UPPER(TRIM("Action")) DESC';

       WHEN vOrderBy = 'ACTIONED_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY NLS_UPPER(TRIM("First" || "Last")) DESC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, "SecondarySortKey" DESC, NLS_UPPER(TRIM("Action")) DESC';

       WHEN vOrderBy = 'ACTION_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY NLS_UPPER(TRIM("Action")) ASC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, "SecondarySortKey" DESC, NLS_UPPER(TRIM("Action")) DESC';

       WHEN vOrderBy = 'ACTION_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY NLS_UPPER(TRIM("Action")) DESC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, "SecondarySortKey" DESC, NLS_UPPER(TRIM("Action")) DESC';

       WHEN vOrderBy = 'INFO_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY NLS_UPPER(TRIM("PrimaryInfo")) ASC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, "SecondarySortKey" DESC, NLS_UPPER(TRIM("Action")) DESC';

       WHEN vOrderBy = 'INFO_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY NLS_UPPER(TRIM("PrimaryInfo")) DESC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, "SecondarySortKey" DESC, NLS_UPPER(TRIM("Action")) DESC';

    END CASE;

   

    SQLStmt := SQLStmt || 

    ') B

       WHERE ROWNUM <= :MaxRow

    ) A

    WHERE "RowNum" >= :MinRow';



    --fill in data

    OPEN vResult 

    FOR SqlStmt 

    USING vPatient,

      viUser, viUser,

      vBeginDate, vEndDate,

      vActionAdd, vActionEdit, vActionDelete, vActionView,

      vActionPrint, vActionCopy, vActionPreview,

      vMaxRow, vMinRow;

      

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;   



  -- 60293906 Get Total AuditLog Activity for guarantors of a patient

  PROCEDURE gettotalactivityforguarantor(IN vpatient integer, IN viuserpatient integer, OUT vtotalactivityforguarantor integer) IS

  BEGIN

    SELECT COUNT(1) INTO vTotalActivityForGuarantor

      FROM AUDITLOG AU

      JOIN IUSER IU ON AU."User" = IU."iUser"

      JOIN PATIENT PT ON IU."Id" = PT."Patient"

      WHERE AU."Patient" = vPatient

      AND AU."User" != viUserPatient;

  END;  

  

  

  -- 52498721 Get custom code field name

  PROCEDURE getcusttype(IN vtype integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT * FROM CUSTTYPE WHERE "Type" = vType;

  

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;

  

  PROCEDURE getcusttypebytypes(IN vtypes character varying, OUT vresult cursor_pkg.weakcursor) IS

  	SQLStmt  VARCHAR2(4000);

  BEGIN

    SQLStmt := 'SELECT "Type", "Description", "Validatefield", "RequiredField" FROM CUSTTYPE WHERE "Type" IN (' || vTypes || ')';

	

	OPEN vResult FOR SQLStmt;

    

    EXCEPTION WHEN NO_DATA_FOUND THEN

    vResult := NULL;

  END;

  

  -- 52498721 Map custom code to description

  PROCEDURE getcustcode(IN vtype integer, IN vcode character varying, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT * FROM CUSTCODE WHERE "Type" = vType AND "Code" = vCode;

  

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;

  

  

  -- 52498757 Get all cust codes for this custtype

  PROCEDURE getcustcodes(IN vtype integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT * FROM CUSTCODE WHERE "Type" = vType ORDER BY "Code";

  

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;

  

  PROCEDURE getcustcodesbytypes(IN vtypes character varying, OUT vresult cursor_pkg.weakcursor) IS

	SQLStmt  VARCHAR2(4000);

  BEGIN

	SQLStmt := 'SELECT "Type", "Code", "Description", "Default", "Inactive" FROM CUSTCODE WHERE "Type" IN (' || vTypes || ') ORDER BY "Code"';

  

    OPEN vResult FOR SQLStmt;

  

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;



  -- 58348032 Get a list of Patient Access Templates in PATEMPLATE table

  PROCEDURE gettemplatelist(OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT * FROM PATEMPLATE ORDER BY "PATEMPLATEID";

    

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;

  

  PROCEDURE gettemplatebyid(IN vtemplateid integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT * FROM PATEMPLATE WHERE "PATEMPLATEID" = vTemplateId;

    

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;

  

  PROCEDURE getpagelist(OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT * 

      FROM PANAV 

      ORDER BY "PANAVAUTH", "PANAVPRIORITY", "PANAVID";

    

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;



  PROCEDURE addpage(IN vtypeid integer, OUT vresult cursor_pkg.weakcursor) IS

    vPageName  VARCHAR2(256);

    vId INTEGER;

    vCount INTEGER;

  BEGIN

    

    -- Check if PANAV table contains same type value 

    

    IF vTypeId = 0 THEN vPageName := 'New Page';

    ELSIF vTypeId = 1 THEN vPageName := 'Home: Landing Page';

    ELSIF vTypeId = 2 THEN vPageName := 'Home: Logged In Page';

    ELSIF vTypeId = 3 THEN vPageName := 'Home: Logged Out Page';

    END IF;

    

    BEGIN

      -- create a blank page if no page was found

      INSERT INTO PANAV (

        "PAPARENTID", 

        "PANAVPRIORITY",

        "PANAVAUTH", 

        "PANAVACTIVE", 

        "PATEMPLATEID_FK",

        "PANAVNAME",

        "Type",

        "PANAVHIDERES",

        "PANAVFIRSTACCESS"

        ) 

      VALUES (0, 0.0, 0, 1, 1, vPageName, vTypeId, 0, 0)

      RETURNING "PANAVID" INTO vId;

      COMMIT;

    END;

    

    OPEN vResult FOR

      SELECT * FROM PANAV WHERE "PANAVID" = vId AND ROWNUM = 1;

    

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;

  

  

  

  PROCEDURE getfirstpage(OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT * FROM

      (

        SELECT * 

        FROM PANAV 

        WHERE "PANAVACTIVE" = 1 

        AND "PAPARENTID" = 0 

        AND "Type" = 0 

        ORDER BY "PANAVAUTH", "PANAVPRIORITY", "PANAVID"

      ) 

      WHERE ROWNUM = 1;

    

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;

  

  

  PROCEDURE getfirstpagefirstaccess(OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT * FROM

      (

        SELECT * 

        FROM PANAV 

        WHERE "PANAVFIRSTACCESS" = 1 

        AND "PAPARENTID" = 0 

        AND "Type" = 0 

        ORDER BY "PANAVAUTH", "PANAVPRIORITY", "PANAVID"

      ) 

      WHERE ROWNUM = 1;

    

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;

  

  

  PROCEDURE getpagebyid(IN vpageid integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT * FROM PANAV WHERE "PANAVID" = vPageId AND ROWNUM = 1;

    

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;

  

  

  

  PROCEDURE getpagebytype(IN vtypeid integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT * FROM PANAV WHERE "Type" = vTypeId AND ROWNUM = 1;

    

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;

  

  

  

  PROCEDURE updatepage(IN vpageid integer, IN vname character varying, IN vactive integer, IN vrestricted integer, IN vparentid integer, IN vpriority numeric, IN vtemplateid integer, IN vhiderepresent integer, IN vfirstaccess integer, OUT vresult integer) IS

  BEGIN

    UPDATE PANAV

    SET

      "PANAVNAME" = vName,

      "PANAVACTIVE" = vActive,

      "PANAVAUTH" = vRestricted,

      "PAPARENTID" = vParentId,

      "PANAVPRIORITY" = vPriority,

      "PATEMPLATEID_FK" = vTemplateId,

      "PANAVHIDERES" = vHideRepresent,

      "PANAVFIRSTACCESS" = vFirstAccess

    WHERE "PANAVID" = vPageId;

    

    vResult := SQL%ROWCOUNT;

    

    COMMIT;

  END;

  

  

  

  PROCEDURE addpagecontent(IN vpageid integer, IN vname character varying, OUT vresult cursor_pkg.weakcursor) IS

    vId INTEGER;

  BEGIN

    BEGIN

      -- create a blank page if no page was found

      INSERT INTO PANAVCONTENT (

        "PANAVCONTENTNAME", 

        "PANAVCONTENTTYPE",

        "PANAVCONTENT", 

        "PANAVID_FK") 

      VALUES (vName, 1, ' ', vPageId)

      RETURNING "PANAVCONTENTID" INTO vId;

      COMMIT;

    END;

    

    OPEN vResult FOR

      SELECT * FROM PANAVCONTENT WHERE "PANAVCONTENTID" = vId AND ROWNUM = 1;

    

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;

  

  

  PROCEDURE getpagecontentlist(IN vpageid integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT * FROM PANAVCONTENT WHERE "PANAVID_FK" = vPageId;

    

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;

  

  PROCEDURE getpagecontentbyid(IN vcontentid integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT * FROM PANAVCONTENT WHERE "PANAVCONTENTID" = vContentId;

    

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;

  

  

  PROCEDURE updatepagecontenttype(IN vcontentid integer, IN vtype integer, OUT vresult integer) IS

  BEGIN

    UPDATE PANAVCONTENT

    SET

      "PANAVCONTENTTYPE" = vType

    WHERE "PANAVCONTENTID" = vContentId;

    

    vResult := SQL%ROWCOUNT;

    

    COMMIT;

  

  END;

	

-- 	69495402 Add log record for Ambulatory summary CCDA. Insert in PACCDA table

PROCEDURE insertpaccda(IN npatientid numeric, IN nuserid numeric, IN nactiontype numeric) IS 

    dDate     DATE;

		vPaccdaId NUMBER(10) := 0;

BEGIN

	SELECT TO_DATE(TO_CHAR(systimestamp, 'YYYY-MON-DD HH24:MI:SS'), 'YYYY-MON-DD HH24:MI:SS') INTO dDate FROM DUAL;

  SELECT PACCDA_PACCDAID_SEQ.NEXTVAL INTO vPaccdaId FROM dual;

	

  INSERT INTO PACCDA("PaccdaId", "Patient", "Date", "User", "ActionType")

             VALUES (vPaccdaId, nPatientId, dDate, nUserId, nActionType);

	EXCEPTION

		WHEN OTHERS THEN

			RETURN;

END InsertPaCcda;

	

  -- AX-18952 Get Documents Attached; AX-25708 Replace PTLETTER table by PTLDETAILS

  PROCEDURE getdocumentsattached(IN vpatient integer, IN vorderby character varying, IN vitemsperpage integer, INOUT vpage integer, OUT vtotalpages integer, OUT vresult cursor_pkg.weakcursor) IS

  	SqlStmt  VARCHAR2(8000);

    vMaxRow INTEGER;

    vMinRow INTEGER;  

    vPtLetterItems INTEGER;

    vContractItems INTEGER;

  BEGIN

		

    --Count all items with matching criteria

    IF vItemsPerPage = 0 THEN

      vTotalPages := 0;

    ELSE

      SELECT COUNT(1) INTO vPtLetterItems

        FROM PTLDETAILS PL

        JOIN ATTAB AT ON PL."AtTab" = AT."AtTab"

        WHERE PL."Patient" = vPatient        

        AND PL."Deleted" = 0

        AND AT."Inactive" = 0

        AND AT."AvailablePa" = 1;		

        

      SELECT COUNT(1) INTO vContractItems

        FROM CONTRACT CT

        JOIN ATTAB AT ON CT."AtTab" = AT."AtTab"

        WHERE CT."Patient" = vPatient        

        AND CT."Deleted" = 0

        AND AT."Inactive" = 0

        AND AT."AvailablePa" = 1;

        

        vTotalPages := CEIL((vPtLetterItems + vContractItems) / vItemsPerPage);

        

    END IF;

    

    IF vTotalPages < vPage THEN

    vPage := vTotalPages;

    ELSIF vPage < 1 THEN

    vPage := 1;

    END IF;

    

    vMaxRow := vPage * vItemsPerPage;

    vMinRow := (vPage - 1) * vItemsPerPage + 1; 

    

    --Get all items within the page range

    SqlStmt := '

    SELECT A.* FROM

    (

      SELECT B.*, ROWNUM AS "RowNum" FROM

      (

        SELECT * FROM (

          SELECT

            ''PTLDETAILS'' AS "TableName",

            PL."PtLetter" AS "Id",

            PL."Patient",

            PL."Description", 

            PL."Date" AS "Date",

            PL."Type",

            PL."FileExt"

          FROM PTLDETAILS PL

          JOIN ATTAB AT ON PL."AtTab" = AT."AtTab"

          WHERE PL."Patient" = :PatId1

          AND PL."Deleted" = 0

          AND AT."Inactive" = 0

          AND AT."AvailablePa" = 1

          UNION

          SELECT

            ''CONTRACT'' AS "TableName",

            CT."Contract" AS "Id",

            CT."Patient",

            CT."Description", 

            CT."Date" AS "Date",

            CT."Type",           

            CT."FileExt"

          FROM CONTRACT CT

          JOIN ATTAB AT ON CT."AtTab" = AT."AtTab"

          WHERE CT."Patient" = :PatId2

          AND CT."Deleted" = 0

          AND AT."Inactive" = 0

          AND AT."AvailablePa" = 1

        )		

    ';



    CASE  

       WHEN vOrderBy = 'DATE_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') ASC, NLS_UPPER(TRIM("Id")) DESC';

       WHEN vOrderBy = 'DATE_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, NLS_UPPER(TRIM("Id")) DESC';

       WHEN vOrderBy = 'DESCRIPTION_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY NLS_UPPER(TRIM("Description")) ASC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, NLS_UPPER(TRIM("Id")) DESC';

       WHEN vOrderBy = 'DESCRIPTION_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY NLS_UPPER(TRIM("Description")) DESC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, NLS_UPPER(TRIM("Id")) DESC';

    END CASE;

   

    SQLStmt := SQLStmt || 

    ') B

       WHERE ROWNUM <= :MaxRow

    ) A

    WHERE "RowNum" >= :MinRow';



    --fill in data

    OPEN vResult 

    FOR SqlStmt 

    USING vPatient, vPatient,

      vMaxRow, vMinRow;

      

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;   



  -- AX-25708 Use PTLDETAILS and PTLCONTENT instead of PTLETTER

  PROCEDURE getdocinptletterbyid(IN vid integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT D."PtLetter", 

	  D."Patient", 

	  D."Description", 

	  D."Date", 

	  D."Type", 

	  C.CONTENT, 

	  D."FileExt",

	  D."Deleted"

	  FROM PTLDETAILS D, PTLCONTENT C 

	  WHERE D."PtLetter" = vId

	  AND D."PtLetter" = C."PtLetter";

    

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;

  

  PROCEDURE getdocincontractbyid(IN vid integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT * FROM CONTRACT WHERE "Contract" = vId;

    

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;

    



  --AX-28119 added ability to add Online request and request patient info; AX-28337b; AX-29370 kept ONLINE_PATIENT parameter for backward compatibility

  PROCEDURE createonlinerequest(IN pvonlinereq online_request, IN pvonlinepatobsolete online_patient, OUT presult integer) IS

  	vSequence NUMBER(10);

  BEGIN

    	INSERT INTO ONLINE_REQUEST("Id", "CreateDateTime", "Type", "Status", "PatientReqId", "RequestDateTime", "Reason", "Note", "PreferMonday", 

    		     "PreferTuesday", "PreferWednesday", "PreferThursday", "PreferFriday", "PreferSaturday", "PreferSunday", "AssignedUser", "AssignedUGroup", "Patient") 

		     VALUES(ONLINE_REQUEST_ID_SEQ.NEXTVAL, SYSDATE, pvOnlineReq."Type",  pvOnlineReq."Status", 0, pvOnlineReq."RequestDateTime", 

		     pvOnlineReq."Reason", pvOnlineReq."Note", pvOnlineReq."PreferMonday", pvOnlineReq."PreferTuesday", pvOnlineReq."PreferWednesday", 

             pvOnlineReq."PreferThursday", pvOnlineReq."PreferFriday", pvOnlineReq."PreferSaturday", pvOnlineReq."PreferSunday", 0, NULL, 0);       --Insert a record in ONLINE_REQUEST table

		    

	pResult := 1;

     

  END;



  PROCEDURE updategenderinfo(IN vpatientid integer, IN vaudit integer, IN vptsexorient integer, IN vptsother character varying, IN vptsdeclined integer, IN vptgenderid integer, IN vptgother character varying, IN vptgdeclined integer, IN vptpreferpronouns integer, IN vptpronounsother character varying, IN vptpronounsdeclined integer, IN vupdatesexorient integer, IN vupdategender integer, IN vupdatepronouns integer, IN vsex integer, OUT vresult integer) IS

      vCount INTEGER;

  BEGIN

      -- Check if a record exists in PTGENDER table

      SELECT COUNT(1) INTO vCount

      FROM PTGENDER

      WHERE "Patient" = vPatientId;



      IF vCount = 0 THEN

          -- If no record, insert

          INSERT INTO PTGENDER (

              "Patient", "PtSexOrient", "PtSOther", "PtSDeclined",

              "PtGenderId", "PtGOther", "PtGDeclined", "PtPreferPronouns",

              "PtPronounsOther", "PtPronounsDeclined", "Audit"

          ) VALUES (

              vPatientId, vPtSexOrient, vPtSOther, vPtSDeclined,

              vPtGenderId, vPtGOther, vPtGDeclined, vPtPreferPronouns,

              vPtPronounsOther, vPtPronounsDeclined, vAudit

          );

      ELSE

          -- If exists, update

          UPDATE PTGENDER

          SET

              "Audit" = vAudit,

              "PtSexOrient" = CASE WHEN vUpdateSexOrient = 1 THEN vPtSexOrient ELSE "PtSexOrient" END,

              "PtSOther" = CASE WHEN vUpdateSexOrient = 1 THEN vPtSOther ELSE "PtSOther" END,

              "PtSDeclined" = CASE WHEN vUpdateSexOrient = 1 THEN vPtSDeclined ELSE "PtSDeclined" END,

              "PtGenderId" = CASE WHEN vUpdateGender = 1 THEN vPtGenderId ELSE "PtGenderId" END,

              "PtGOther" = CASE WHEN vUpdateGender = 1 THEN vPtGOther ELSE "PtGOther" END,

              "PtGDeclined" = CASE WHEN vUpdateGender = 1 THEN vPtGDeclined ELSE "PtGDeclined" END,

              "PtPreferPronouns" = CASE WHEN vUpdatePronouns = 1 THEN vPtPreferPronouns ELSE "PtPreferPronouns" END,

              "PtPronounsOther" = CASE WHEN vUpdatePronouns = 1 THEN vPtPronounsOther ELSE "PtPronounsOther" END,

              "PtPronounsDeclined" = CASE WHEN vUpdatePronouns = 1 THEN vPtPronounsDeclined ELSE "PtPronounsDeclined" END

          WHERE "Patient" = vPatientId;

      END IF;



      -- Update PATIENT Sex

      UPDATE PATIENT

      SET "Sex" = vSex

      WHERE "Patient" = vPatientId;



      -- Set output result

      vResult := SQL%ROWCOUNT;

  EXCEPTION

      WHEN OTHERS THEN

          vResult := -1;

END UpdateGenderInfo;





	

END;
CREATE OR REPLACE PACKAGE BODY pps_pkg IS



-- AX-24597

FUNCTION getptpps(patientid numeric, quadrant numeric) RETURN numeric IS

 PtPerioId NUMBER := 0;

 PPSScore  NUMBER := 0;

 PtChartDate DATE := NULL;

BEGIN

 BEGIN	

 	SELECT max(P2."ChartDate") INTO PtChartDate FROM PTPERIO P2 where P2."Patient"=PatientId AND P2."Deleted"=0;

	SELECT max(P."PtPerio") INTO PtPerioId FROM PTPERIO P			-- E33252

 		WHERE  P."Patient"=PatientId AND P."Deleted"=0 AND P."ChartDate" = PtChartDate;

 EXCEPTION

 WHEN NO_DATA_FOUND THEN

 	RETURN PPSScore;

 END;

 		



IF TRUE = IsPPSCode3 (PtPerioId, Quadrant) THEN 

  PPSScore := 3;

 ELSIF TRUE = IsPPSCode2 (PtPerioId, Quadrant) THEN 

  PPSScore := 2;

 ELSIF TRUE = IsPPSCode1 (PtPerioId, Quadrant) THEN 

  PPSScore := 1;

 END IF;

 

 RETURN PPSScore;

END; 

-- =========================================================================;

-- AX-24597

FUNCTION getptppsbydate(chartdate timestamp without time zone, patientid numeric, quadrant numeric) RETURN numeric IS

 PtPerioId NUMBER := 0;

 PPSScore  NUMBER := 0;

BEGIN

 BEGIN	

	SELECT P."PtPerio" INTO PtPerioId FROM PTPERIO P		

 	WHERE  P."Patient"=PatientId AND P."Deleted"=0 AND P."Audit" =

	 (SELECT max(P2."Audit") FROM PTPERIO P2, AUDITHIS A where P2."Patient"=PatientId 

 	AND P2."Deleted"=0 AND P2."Audit" = A."Audit" AND trunc(A."Date") = ChartDate);

 EXCEPTION

 WHEN NO_DATA_FOUND THEN

 	RETURN PPSScore;

 END;

 



 IF TRUE = IsPPSCode3 (PtPerioId, Quadrant) THEN 

  PPSScore := 3;

 ELSIF TRUE = IsPPSCode2 (PtPerioId, Quadrant) THEN 

  PPSScore := 2;

 ELSIF TRUE = IsPPSCode1 (PtPerioId, Quadrant) THEN 

  PPSScore := 1;

 END IF;

 

 RETURN PPSScore;

END;

 -- =========================================================================

 /*

    AX-24599 holds implementation planning for AX-24597

	

					  (LowerBound-UpperBound)

	Quadrant 1:   Adult bound 01-08  Child bound 45-49

	Quadrant 2:   Adult bound 09-16  Child bound 50-54

	Quadrant 3:   Adult bound 17-24  Child bound 55-59

	Quadrant 4:   Adult bound 25-32  Child bound 60-64



 */

 

 

-- AX-24597

FUNCTION isppscode1(ptperioid numeric, quadrant numeric) RETURN boolean IS

 IsCode     BOOLEAN := FALSE;

 CodeCount  NUMBER  := 0;

 UpperBound NUMBER  := 0;

 LowerBound NUMBER  := 0;

 DValueGreaterThan NUMBER :=1;

BEGIN

 IF Quadrant = 1 THEN 

  LowerBound := 1;

  UpperBound := 8;

 ELSIF Quadrant = 2 THEN

  LowerBound := 9;

  UpperBound := 16;

 ELSIF Quadrant = 3 THEN

  LowerBound := 17;

  UpperBound := 24;

 ELSIF Quadrant = 4 THEN

  LowerBound := 25;

  UpperBound := 32;



-- ELSE

-- error!

 END IF;

  

 SELECT COUNT(*) INTO CodeCount FROM PTPERIT PI, PERCOND C

 WHERE C."CondType"=2 AND C."Status"=0 AND PI."PtPerio"=PtPerioId 

 AND PI."PerCond"=C."PerCond" AND PI."Deleted"!=1					-- E33252

 AND PI."Site">=LowerBound AND PI."Site"<=UpperBound 

 AND (PI."DValue1">=DValueGreaterThan OR PI."DValue2">=DValueGreaterThan OR PI."DValue3">=DValueGreaterThan);



 IF CodeCount > 0 THEN

  IsCode := TRUE;

 END IF;



 RETURN IsCode;

END;

 -- =========================================================================

 -- AX-24597

FUNCTION isppscode2(ptperioid numeric, quadrant numeric) RETURN boolean IS

 IsCode     BOOLEAN := FALSE;

 CodeCount  NUMBER  := 0;

 UpperBound NUMBER  := 0;

 LowerBound NUMBER  := 0;

 DValueGreaterThan NUMBER :=4;

BEGIN

 IF Quadrant = 1 THEN 

  LowerBound := 1;

  UpperBound := 8;

 ELSIF Quadrant = 2 THEN

  LowerBound := 9;

  UpperBound := 16;

 ELSIF Quadrant = 3 THEN

  LowerBound := 17;

  UpperBound := 24;

 ELSIF Quadrant = 4 THEN

  LowerBound := 25;

  UpperBound := 32;



-- ELSE

-- error!

 END IF;

  

 SELECT COUNT(*) INTO CodeCount FROM PTPERIT PI, PERCOND C

 WHERE C."CondType"=2 AND C."Status"=0 AND PI."PtPerio"=PtPerioId 

 AND PI."PerCond"=C."PerCond" AND PI."Deleted"!=1					-- E33252

 AND PI."Site">=LowerBound AND PI."Site"<=UpperBound 

 AND (PI."DValue1">=DValueGreaterThan OR PI."DValue2">=DValueGreaterThan OR PI."DValue3">=DValueGreaterThan);



 IF CodeCount > 0 THEN

  IsCode := TRUE;

 END IF;



 RETURN IsCode;

END;

 -- =========================================================================

-- AX-24597

FUNCTION isppscode3(ptperioid numeric, quadrant numeric) RETURN boolean IS

 IsCode     BOOLEAN := FALSE;

 CodeCount  NUMBER  := 0;

 UpperBound NUMBER  := 0;

 LowerBound NUMBER  := 0;

 DValueGreaterThan NUMBER :=6;

BEGIN

 IF Quadrant = 1 THEN 

  LowerBound := 1;

  UpperBound := 8;

 ELSIF Quadrant = 2 THEN

  LowerBound := 9;

  UpperBound := 16;

 ELSIF Quadrant = 3 THEN

  LowerBound := 17;

  UpperBound := 24;

 ELSIF Quadrant = 4 THEN

  LowerBound := 25;

  UpperBound := 32;



-- ELSE

-- error!

 END IF;

  

 SELECT COUNT(*) INTO CodeCount FROM PTPERIT PI, PERCOND C

 WHERE C."CondType"=2 AND C."Status"=0 AND PI."PtPerio"=PtPerioId 

 AND PI."PerCond"=C."PerCond" AND PI."Deleted"!=1					-- E33252

 AND PI."Site">=LowerBound AND PI."Site"<=UpperBound 

 AND (PI."DValue1">=DValueGreaterThan OR PI."DValue2">=DValueGreaterThan OR PI."DValue3">=DValueGreaterThan);



 IF CodeCount > 0 THEN

  IsCode := TRUE;

 END IF;



 RETURN IsCode;

END;



END;
CREATE OR REPLACE PACKAGE BODY psr_pkg IS





FUNCTION getptpsr(patientid numeric, sextant numeric) RETURN numeric IS

 PtPerioId NUMBER := 0;

 PSRScore  NUMBER := 0;

 PtChartDate DATE := NULL;

BEGIN

 BEGIN	

 	SELECT max(P2."ChartDate") INTO PtChartDate FROM PTPERIO P2 where P2."Patient"=PatientId AND P2."Deleted"=0;

	SELECT max(P."PtPerio") INTO PtPerioId FROM PTPERIO P			-- E33252

 		WHERE  P."Patient"=PatientId AND P."Deleted"=0 AND P."ChartDate" = PtChartDate;

 EXCEPTION

 WHEN NO_DATA_FOUND THEN

 	RETURN PSRScore;

 END;

	



 IF TRUE = IsCode4 (PtPerioId, Sextant) THEN 

  PSRScore := 4;

 ELSIF TRUE = IsCode3 (PtPerioId, Sextant) THEN 

  PSRScore := 3;

 ELSIF TRUE = IsCode2 (PatientId, PtPerioId, Sextant) THEN 

  PSRScore := 2;

 ELSIF TRUE = IsCode1 (PatientId, PtPerioId, Sextant) THEN 

  PSRScore := 1;

 END IF;

 

 RETURN PSRScore;

END;



--AX-24528.2

FUNCTION getptpsrbydate(chartdate timestamp without time zone, patientid numeric, sextant numeric) RETURN numeric IS

 PtPerioId NUMBER := 0;

 PSRScore  NUMBER := 0;

BEGIN

 BEGIN	

	SELECT P."PtPerio" INTO PtPerioId FROM PTPERIO P		

 	WHERE  P."Patient"=PatientId AND P."Deleted"=0 AND P."Audit" =

	 (SELECT max(P2."Audit") FROM PTPERIO P2, AUDITHIS A where P2."Patient"=PatientId 

 	AND P2."Deleted"=0 AND P2."Audit" = A."Audit" AND trunc(A."Date") = ChartDate);

 EXCEPTION

 WHEN NO_DATA_FOUND THEN

 	RETURN PSRScore;

 END;

 



 IF TRUE = IsCode4 (PtPerioId, Sextant) THEN 

  PSRScore := 4;

 ELSIF TRUE = IsCode3 (PtPerioId, Sextant) THEN 

  PSRScore := 3;

 ELSIF TRUE = IsCode2 (PatientId, PtPerioId, Sextant) THEN 

  PSRScore := 2;

 ELSIF TRUE = IsCode1 (PatientId, PtPerioId, Sextant) THEN 

  PSRScore := 1;

 END IF;

 

 RETURN PSRScore;

END;



FUNCTION iscode4(ptperioid numeric, sextant numeric) RETURN boolean IS

 IsCode     BOOLEAN := FALSE;

 CodeCount  NUMBER  := 0;

 UpperBound NUMBER  := 0;

 LowerBound NUMBER  := 0;

BEGIN

 IF Sextant = 1 THEN 

  LowerBound := 1;

  UpperBound := 5;

 ELSIF Sextant = 2 THEN

  LowerBound := 6;

  UpperBound := 11;

 ELSIF Sextant = 3 THEN

  LowerBound := 12;

  UpperBound := 16;

 ELSIF Sextant = 4 THEN

  LowerBound := 17;

  UpperBound := 21;

 ELSIF Sextant = 5 THEN

  LowerBound := 22;

  UpperBound := 27;

 ELSIF Sextant = 6 THEN

  LowerBound := 28;

  UpperBound := 32;

-- ELSE

-- error!

 END IF;

  

 SELECT COUNT(*) INTO CodeCount FROM PTPERIT PI, PERCOND C

 WHERE C."CondType"=2 AND C."Status"=0 AND PI."PtPerio"=PtPerioId 

 AND PI."PerCond"=C."PerCond" AND PI."Deleted" !=1					-- E33252

 AND PI."Site">=LowerBound AND PI."Site"<=UpperBound 

 AND (PI."DValue1">=5.5 OR PI."DValue2">=5.5 OR PI."DValue3">=5.5);



 IF CodeCount > 0 THEN

  IsCode := TRUE;

 END IF;



 RETURN IsCode;

END;





FUNCTION iscode3(ptperioid numeric, sextant numeric) RETURN boolean IS

 IsCode     BOOLEAN := FALSE;

 CodeCount  NUMBER  := 0;

 UpperBound NUMBER  := 0;

 LowerBound NUMBER  := 0;

BEGIN

 IF Sextant = 1 THEN 

  LowerBound := 1;

  UpperBound := 5;

 ELSIF Sextant = 2 THEN

  LowerBound := 6;

  UpperBound := 11;

 ELSIF Sextant = 3 THEN

  LowerBound := 12;

  UpperBound := 16;

 ELSIF Sextant = 4 THEN

  LowerBound := 17;

  UpperBound := 21;

 ELSIF Sextant = 5 THEN

  LowerBound := 22;

  UpperBound := 27;

 ELSIF Sextant = 6 THEN

  LowerBound := 28;

  UpperBound := 32;

-- ELSE

-- error!

 END IF;

  

 SELECT COUNT(*) INTO CodeCount FROM PTPERIT PI, PERCOND C

 WHERE C."CondType"=2 AND C."Status"=0 AND PI."PtPerio"=PtPerioId 

 AND PI."PerCond"=C."PerCond" AND PI."Deleted" !=1					-- E33252

 AND PI."Site">=LowerBound AND PI."Site"<=UpperBound 

 AND (PI."DValue1">=3.5 OR PI."DValue2">=3.5 OR PI."DValue3">=3.5);



 IF CodeCount > 0 THEN

  IsCode := TRUE;

 END IF;



 RETURN IsCode;

END;





FUNCTION iscode2(patientid numeric, ptperioid numeric, sextant numeric) RETURN boolean IS

 IsCode     BOOLEAN := FALSE;

 CodeCount1  NUMBER := 0;

 CodeCount2  NUMBER := 0;

 CodeCount3  NUMBER := 0;

 CodeCount4  NUMBER := 0;

 CodeCount5  NUMBER := 0;

 CodeCount6  NUMBER := 0;

 UpperBound  NUMBER := 0;

 LowerBound  NUMBER := 0;

 PUpperBound NUMBER := 0;

 PLowerBound NUMBER := 0;

BEGIN

 IF Sextant = 1 THEN 

  LowerBound  := 1;

  UpperBound  := 5;

  PLowerBound := 45;

  PUpperBound := 46;

 ELSIF Sextant = 2 THEN

  LowerBound  := 6;

  UpperBound  := 11;

  PLowerBound := 47;

  PUpperBound := 52;

 ELSIF Sextant = 3 THEN

  LowerBound  := 12;

  UpperBound  := 16;

  PLowerBound := 53;

  PUpperBound := 54;

 ELSIF Sextant = 4 THEN

  LowerBound  := 17;

  UpperBound  := 21;

  PLowerBound := 55;

  PUpperBound := 56;

 ELSIF Sextant = 5 THEN

  LowerBound  := 22;

  UpperBound  := 27;

  PLowerBound := 57;

  PUpperBound := 62;

 ELSIF Sextant = 6 THEN

  LowerBound  := 28;

  UpperBound  := 32;

  PLowerBound := 63;

  PUpperBound := 64;

-- ELSE

-- error!

 END IF;



 SELECT COUNT(*) INTO CodeCount1 FROM TREATME2 T, PATIENT2 P2, PROCEDUR P

 WHERE P2."PtxPId"=PatientId AND P2."Auto"=T."PId" AND T."CodeId"=P."Id" AND P."CondType"=6

 AND T."Site">=LowerBound AND T."Site"<=UpperBound AND T."Status"=4 

 AND ((T."Deleted"=0 AND 0 = (SELECT COUNT(*) FROM CHARTLNK L WHERE L."Auto" = T."Auto" and L."Status" = 'D'))

 OR (T."Deleted"=1 AND 0 < (SELECT COUNT(*) FROM CHARTLNK L WHERE L."Auto" = T."Auto" and L."Status" = 'D')));

 

 SELECT COUNT(*) INTO CodeCount2 FROM TREATME2 T, PATIENT2 P2, PROCEDUR P

 WHERE P2."PtxPId"=PatientId AND P2."Auto"=T."PId" AND T."CodeId"=P."Id" AND P."CondType"=7

 AND T."Site">=LowerBound AND T."Site"<=UpperBound AND T."Status"=4 

 AND ((T."Deleted"=0 AND 0 = (SELECT COUNT(*) FROM CHARTLNK L WHERE L."Auto" = T."Auto" and L."Status" = 'D'))

 OR (T."Deleted"=1 AND 0 < (SELECT COUNT(*) FROM CHARTLNK L WHERE L."Auto" = T."Auto" and L."Status" = 'D')));



 SELECT COUNT(*) INTO CodeCount3 FROM TREATME2 T, PATIENT2 P2, PROCEDUR P

 WHERE P2."PtxPId"=PatientId AND P2."Auto"=T."PId" AND T."CodeId"=P."Id" AND P."CondType"=6

 AND T."Site">=PLowerBound AND T."Site"<=PUpperBound AND T."Status"=4 

 AND ((T."Deleted"=0 AND 0 = (SELECT COUNT(*) FROM CHARTLNK L WHERE L."Auto" = T."Auto" and L."Status" = 'D'))

 OR (T."Deleted"=1 AND 0 < (SELECT COUNT(*) FROM CHARTLNK L WHERE L."Auto" = T."Auto" and L."Status" = 'D')));

 

 SELECT COUNT(*) INTO CodeCount4 FROM TREATME2 T, PATIENT2 P2, PROCEDUR P

 WHERE P2."PtxPId"=PatientId AND P2."Auto"=T."PId" AND T."CodeId"=P."Id" AND P."CondType"=7

 AND T."Site">=PLowerBound AND T."Site"<=PUpperBound AND T."Status"=4 

 AND ((T."Deleted"=0 AND 0 = (SELECT COUNT(*) FROM CHARTLNK L WHERE L."Auto" = T."Auto" and L."Status" = 'D'))

 OR (T."Deleted"=1 AND 0 < (SELECT COUNT(*) FROM CHARTLNK L WHERE L."Auto" = T."Auto" and L."Status" = 'D')));

 

 SELECT COUNT(*) INTO CodeCount5 FROM PTPERIT PI, PERCOND C

 WHERE C."CondType"=6 AND C."Status"=0 AND PI."PtPerio"=PtPerioId 

 AND PI."PerCond"=C."PerCond" AND PI."Deleted" !=1					-- E33252

 AND PI."Site">=LowerBound AND PI."Site"<=UpperBound 

 AND (PI."DValue1"=1 OR PI."DValue2"=1 OR PI."DValue3"=1);

 

 SELECT COUNT(*) INTO CodeCount6 FROM PTPERIT PI, PERCOND C

 WHERE C."CondType"=7 AND C."Status"=0 AND PI."PtPerio"=PtPerioId 

 AND PI."PerCond"=C."PerCond" AND PI."Deleted" !=1					-- E33252

 AND PI."Site">=LowerBound AND PI."Site"<=UpperBound 

 AND (PI."DValue1"=1 OR PI."DValue2"=1 OR PI."DValue3"=1);

 

 IF CodeCount1 > 0 OR CodeCount2 > 0 OR CodeCount3 > 0 

 OR CodeCount4 > 0 OR CodeCount5 > 0 OR CodeCount6 > 0 THEN

  IsCode := TRUE;

 END IF;



 RETURN IsCode;

END;





FUNCTION iscode1(patientid numeric, ptperioid numeric, sextant numeric) RETURN boolean IS

 IsCode     BOOLEAN := FALSE;

 CodeCount1 NUMBER  := 0;

 CodeCount2 NUMBER  := 0;

 CodeCount3  NUMBER := 0;

 UpperBound NUMBER  := 0;

 LowerBound NUMBER  := 0;

 PUpperBound NUMBER := 0;

 PLowerBound NUMBER := 0;

BEGIN

 IF Sextant = 1 THEN 

  LowerBound  := 1;

  UpperBound  := 5;

  PLowerBound := 45;

  PUpperBound := 46;

 ELSIF Sextant = 2 THEN

  LowerBound  := 6;

  UpperBound  := 11;

  PLowerBound := 47;

  PUpperBound := 52;

 ELSIF Sextant = 3 THEN

  LowerBound  := 12;

  UpperBound  := 16;

  PLowerBound := 53;

  PUpperBound := 54;

 ELSIF Sextant = 4 THEN

  LowerBound  := 17;

  UpperBound  := 21;

  PLowerBound := 55;

  PUpperBound := 56;

 ELSIF Sextant = 5 THEN

  LowerBound  := 22;

  UpperBound  := 27;

  PLowerBound := 57;

  PUpperBound := 62;

 ELSIF Sextant = 6 THEN

  LowerBound  := 28;

  UpperBound  := 32;

  PLowerBound := 63;

  PUpperBound := 64;

-- ELSE

-- error!

 END IF;



 SELECT COUNT(*) INTO CodeCount1 FROM TREATME2 T, PATIENT2 P2, PROCEDUR P

 WHERE P2."PtxPId"=PatientId AND P2."Auto"=T."PId" AND T."CodeId"=P."Id" AND P."CondType"=4

 AND T."Site">=LowerBound AND T."Site"<=UpperBound AND T."Status"=4 

 AND ((T."Deleted"=0 AND 0 = (SELECT COUNT(*) FROM CHARTLNK L WHERE L."Auto" = T."Auto" and L."Status" = 'D'))

 OR (T."Deleted"=1 AND 0 < (SELECT COUNT(*) FROM CHARTLNK L WHERE L."Auto" = T."Auto" and L."Status" = 'D')));



 SELECT COUNT(*) INTO CodeCount2 FROM TREATME2 T, PATIENT2 P2, PROCEDUR P

 WHERE P2."PtxPId"=PatientId AND P2."Auto"=T."PId" AND T."CodeId"=P."Id" AND P."CondType"=4

 AND T."Site">=PLowerBound AND T."Site"<=PUpperBound AND T."Status"=4 

 AND ((T."Deleted"=0 AND 0 = (SELECT COUNT(*) FROM CHARTLNK L WHERE L."Auto" = T."Auto" and L."Status" = 'D'))

 OR (T."Deleted"=1 AND 0 < (SELECT COUNT(*) FROM CHARTLNK L WHERE L."Auto" = T."Auto" and L."Status" = 'D')));

 

 SELECT COUNT(*) INTO CodeCount3 FROM PTPERIT PI, PERCOND C

 WHERE C."CondType"=4 AND C."Status"=0 AND PI."PtPerio"=PtPerioId 

 AND PI."PerCond"=C."PerCond" AND PI."Deleted" !=1					-- E33252

 AND PI."Site">=LowerBound AND PI."Site"<=UpperBound 

 AND (PI."DValue1"=1 OR PI."DValue2"=1 OR PI."DValue3"=1);



 IF CodeCount1 > 0 OR CodeCount2 > 0 OR CodeCount3 > 0 THEN

  IsCode := TRUE;

 END IF;



 RETURN IsCode;

END;





END;
CREATE OR REPLACE PACKAGE BODY ptsumm_pkg IS


-- B82709
PROCEDURE calculateptsummaries(IN patientid numeric, IN userid numeric) IS
BEGIN

	RETURN; -- remove this line if using patient summaries...

	-- B82709
	CalculateCariesRisk(PatientId, UserId);
	CalculatePerioRisk(PatientId, UserId);
	
END;


PROCEDURE updateptsummaries() IS

	vUserId NUMBER := 0;
	CURSOR C1 IS SELECT * FROM Patient WHERE "IsPatient" = 1 AND "Deleted" = 0;

BEGIN

	RETURN; -- remove this line if using patient summaries...

	SELECT "OvernightUser" INTO vUserId FROM AXIUMOPT;

	for p in C1 LOOP
		CalculatePtSummaries(p."Patient", vUserId);
	END LOOP;
	
END;


-- B82593 -- B82709
PROCEDURE calculatecariesrisk(IN patientid numeric, IN userid numeric) IS

	vSummCode CHAR(6) := 'C Risk';
	vNewVal1 CHAR(30) := NULL;
	vNewVal2 CHAR(30) := NULL;
	vId NUMBER := 0;
	
BEGIN

    -- TODO: Values to be assigned here:
    vNewVal1 := 'C1';
    vNewVal2 := 'Low';
	
	 UpdateSummaryRec(PatientId, UserId, vSummCode, vNewVal1, vNewVal2);
		
END;


-- E73070.3	added
-- This function is to update the patient flag that controls honoring the DOR relationships
-- Possible values are 0 & 1
--	As discussed, will be up to individual school / client to to call these appropriately
PROCEDURE updaterecalldrflag(IN patientid numeric, IN flag numeric) IS
	vAnyDoctor NUMBER			:= 0;		-- any doctor
	vAssignedDoctor NUMBER	:= 1;		-- assigned doctor only
BEGIN
	IF Flag = vAnyDoctor OR
			Flag = vAssignedDoctor THEN
		UPDATE PATIENT SET "RecallDoctorToUse" = Flag WHERE "Patient" = PatientId;
	END IF;
END;

-- E73070.3	added
-- This function is to update the patient flag that controls honoring the DHR relationships
-- Possible values are 0, 1, 2 & 3
--	As discussed, will be up to individual school / client to to call these appropriately
PROCEDURE updaterecallhygflag(IN patientid numeric, IN flag numeric) IS
	vAnyHyg NUMBER							:= 0;		-- any hygienist
	vAssignedHyg NUMBER					:= 1;		-- assigned hygienist only
	vAssignedHygOrSameType NUMBER		:= 2;		-- assigned hygienist or same provider type
	vAnyHygOrEnhCDA NUMBER				:= 3;		-- assigned hygienist or Enhanced CDA
BEGIN
	IF Flag = vAnyHyg OR
			Flag = vAssignedHyg OR
			Flag = vAssignedHygOrSameType OR
			Flag = vAnyHygOrEnhCDA THEN
		UPDATE PATIENT SET "RecallHygToUse" = Flag WHERE "Patient" = PatientId;
	END IF;
END;

-- B82593 -- B82709
PROCEDURE calculateperiorisk(IN patientid numeric, IN userid numeric) IS

	vSummCode CHAR(6) := 'P Risk';
	vNewVal1 CHAR(30) := NULL;
	vNewVal2 CHAR(30) := NULL;
	vId NUMBER := 0;
	
BEGIN

   -- TODO: Values to be assigned here:
   vNewVal1 := 'P2';
	vNewVal2 := 'Moderate';
		
	UpdateSummaryRec(PatientId, UserId, vSummCode, vNewVal1, vNewVal2);
		
END;


-- B82709
PROCEDURE updatesummaryrec(IN patientid numeric, IN userid numeric, IN vsummcode character varying, IN vnewval1 character varying, IN vnewval2 character varying) IS

	vOldVal1 CHAR(30) := NULL;
	vOldVal2 CHAR(30) := NULL;
	vId NUMBER := 0;
	
BEGIN

	BEGIN
		SELECT "Patient", "Value1", "Value2" INTO vId, vOldVal1, vOldVal2
		FROM PTSUMM WHERE "Patient" = PatientId and "SummCode" = vSummCode;
	EXCEPTION WHEN NO_DATA_FOUND THEN
		vId := 0;
	END;
	
	IF vId = 0 THEN
		Insert into PTSUMM values (PatientId, vSummCode, TRIM(vNewVal1), TRIM(vNewVal2), CreateAuditRec(1, UserId), '', '', '', 0);
	ELSIF (TRIM(vOldVal1) <> TRIM(vNewVal1) OR TRIM(vOldVal2) <> TRIM(vNewVal2)) THEN
		UPDATE PTSUMM SET "Value1" = TRIM(vNewVal1), "Value2" = TRIM(vNewVal2), "Audit" = CreateAuditRec(2, UserId) WHERE "Patient" = PatientId and "SummCode" = vSummCode;
	END IF;
		
END;


-- B82593
FUNCTION getvalue1strings(summcode character varying) RETURN character varying IS

	vValue CHAR(255);
	
BEGIN
	IF SummCode = 'C Risk' THEN
		vValue := 'C0;C1;C2;C3';
	ELSIF SummCode = 'P Risk' THEN
		vValue := 'P1;P2;P3;P4';
	ELSE
		vValue := '';
	END IF;

	RETURN vValue;
END;

-- B82593
FUNCTION getvalue2strings(summcode character varying) RETURN character varying IS

	vValue CHAR(100);
	
BEGIN
	IF SummCode = 'C Risk' THEN
		vValue := 'Low;Moderate;High';
	ELSIF SummCode = 'P Risk' THEN
		vValue := 'Low;Moderate;High';
	ELSE
		vValue := '';
	END IF;

	RETURN vValue;
END;

-- B82709
FUNCTION createauditrec(type numeric, userid numeric) RETURN numeric IS
	
	vAudit NUMBER := 0;
	vUser NUMBER := 1;

BEGIN

	IF UserId > 0 THEN
		vUser := UserId;
	END IF;
	
	SELECT AUDITHIS_AUDIT_SEQ.NEXTVAL INTO vAudit FROM dual;

	INSERT INTO AuditHis("Audit", "Date", "Time", "User", "StationId", "TableName", "HistoryType")
	VALUES (vAudit, TRUNC(SYSDATE), TO_NUMBER(TO_CHAR(SYSDATE,'SSSSS'))/60, vUser, '1', 'PTSUMM', Type);

	return vAudit;
		
END;


END;
CREATE OR REPLACE PACKAGE BODY qrda_cfg_pkg IS

/**
* Returns the name of the sending application/>
* @return The name of the sending application<p/>
*/
FUNCTION getsendingapp() RETURN character varying IS
	vSendingApp VARCHAR2(255 );
BEGIN
	SELECT MAX('axiUm ' || "Version") INTO vSendingApp FROM PRACTICE;

	RETURN vSendingApp;
END;

/**
* Returns the name of the sending facility<p/>
* @return The name of the sending facility<p/>
*/
FUNCTION getsendingfac() RETURN character varying IS
	vSendingFac VARCHAR2(255 );
BEGIN
	SELECT SUBSTR(TRIM("Name"),1,20) INTO vSendingFac
	FROM PRACTICE
	WHERE 1=1
  		AND "Id" = (SELECT MIN("Id") FROM PRACTICE WHERE "Inactive" = 0);

	RETURN vSendingFac;
END;

/**
* Returns the name of the Sending Application
* @return The name of the Sending Application
*/
FUNCTION getphssendingapp() RETURN character varying IS
	vSendingApp VARCHAR2(255 );
BEGIN
	SELECT MAX('axiUm ' || "Version") INTO vSendingApp FROM PRACTICE;
	RETURN vSendingApp;
END;

/**
* Returns the OID (Object Identifier) associated with the Sending Application.
* @return The OID (Object Identifier) associated with the Sending Application.
*/
FUNCTION getphssendingappoid() RETURN character varying IS
	vSendingAppOID VARCHAR2(255 );
BEGIN
	vSendingAppOID := '2.16.840.1.113883.3.1496';
	RETURN vSendingAppOID;
END;

/**
* Returns the name of the Sending Facility
* @return The name of the Sending Facility
*/
FUNCTION getphssendingfac() RETURN character varying IS
	vSendingFac VARCHAR2(255 );
BEGIN
	vSendingFac := 'TEST';
	RETURN vSendingFac;
END;

/**
* Returns the OID (Object Identifier) associated with the Sending Facility.
* @return The OID (Object Identifier) associated with the Sending Facility.
*/
FUNCTION getphssendingfacoid() RETURN character varying IS
	vSendingFacOID VARCHAR2(255 );
BEGIN
	vSendingFacOID := '2.16.840.1.113883.3.1496';
	RETURN vSendingFacOID;
END;


/**
* Returns the name of the sending system for use in ASTM CCR clinical summaries (this is the ActorID for the From tag). <p/>
* @return The name of the sending system for use in ASTM CCR clinical summaries. <p/>
*/
FUNCTION getfromactorid() RETURN character varying IS
BEGIN
	RETURN 'EXAN_SOFTWARE';
END;


/**
* Returns the Oracle DIRECTORY object that QRDA XML messages are saved to.<p/>
* @return The name of the DIRECTORY object where QRDA XML messages are saved to.<p/>
*/
FUNCTION getqrdaxmlexportdir() RETURN character varying IS
BEGIN
	RETURN 'CQM_EXPORT_DIR';
END;


/**
* Creates an QRDA Type I .XML file for any given patient and returns it as a CLOB to MUD
* @return The error code indicated success or failurI. 0 = Success, anything else = Failure
*/
PROCEDURE qrda_type1_xml(IN vproducer character, IN vpatient numeric, IN vreportingyear numeric, IN vmeasure character varying, OUT verror integer, OUT voutputfile clob) IS

  vOutputFileName VARCHAR2(255 ); -- name of the output file

  vTopHeaderFile    CLOB;
  vBottomHeaderFile CLOB;
  vMeasureFile      CLOB;
  vOrganizerFile    CLOB;
  vBodyFile         CLOB;
  vFooterFile       CLOB;

  --Codesystems used in numerator
  vCodeSystem CHAR(22 );

  vCS_SNOMED  CHAR(22 ) := '2.16.840.1.113883.6.96';
  vCS_ADA     CHAR(22 ) := '2.16.840.1.113883.6.13';
  vCS_CPT4    CHAR(22 ) := '2.16.840.1.113883.6.12';
  vCS_CPT5    CHAR(22 ) := '2.16.840.1.113883.6.82';
  vCS_LOINC   CHAR(21 ) := '2.16.840.1.113883.6.1';
  vCS_RXNORM  CHAR(22 ) := '2.16.840.1.113883.6.88';

  vInstanceText VARCHAR2(255 );
  vSpecificUID  CHAR(40 );

  vMeasureFormatted VARCHAR2(10 );

  --Stores the CQM Version specific identifier
  vSpecificId      CHAR(36 );
  vSpecificNId     CHAR(36 );
  vSpecificNQF     VARCHAR2(50 );
  vSpecificCQM     VARCHAR2(10 );
  vSpecificTitle   VARCHAR2(100 );
  vSpecificVersion VARCHAR2(10 );

  vCQMTitle CQMVALSET."Title"          %TYPE;
  vCQMNeutralId CQMVALSET."NeutralId"  %TYPE;
  vCQMVersion CQMVALSET."Version"      %TYPE;
  vCQMSpecificId CQMVALSET."SpecificId"%TYPE;

  vSpecificStratificationId VARCHAR2(36 );

  vCQMHit22   NUMBER := 0;
  vCQMHit50   NUMBER := 0;
  vCQMHit68   NUMBER := 0;
  vCQMHit69   NUMBER := 0;
  vCQMHit74   NUMBER := 0;
  vCQMHit75   NUMBER := 0;
  vCQMHit124  NUMBER := 0;
  vCQMHit125  NUMBER := 0;
  vCQMHit127  NUMBER := 0;
  vCQMHit130  NUMBER := 0;
  vCQMHit138  NUMBER := 0;
  vCQMHit147  NUMBER := 0;
  vCQMHit155  NUMBER := 0;
  vCQMHit156  NUMBER := 0;
  vCQMHit165  NUMBER := 0;

  vUser USERS."User"                   %TYPE;
  vProvLast PRODUCER."LastName"        %TYPE;
  vProvFirst PRODUCER."FirstName"      %TYPE;
  vProvAddress1 PRODUCER."Address1"    %TYPE;
  vProvAddress2 PRODUCER."Address2"    %TYPE;
  vProvCity PRODUCER."City"            %TYPE;
  vProvProvince PRODUCER."Province"    %TYPE;
  vProvPostal PRODUCER."Postal"        %TYPE;
  vProvCountry PRODUCER."AddressOther" %TYPE;
  vProvArea PRODUCER."BArea"           %TYPE;
  vProvPhone PRODUCER."BTel"           %TYPE;

  vProvNPI CHAR(10 ) := 'X';
  vProvTIN CHAR(9 ) := 'X';
  vProvAddress CHAR(62 ) := ' ';

  vOrganizationName   CHAR(40 ) := ' ';

  -- Obtained once registered
  vCMSCertifcationNum CHAR(40 ) := '123456789';

  -- SF-00192544/AX-18966: value of vReportingYear being passed to the procedure changed
--    vReportingStartDate DATE := TO_DATE('01-JAN-' || TRIM(vReportingYear), 'DD-MON-YYYY' || CHR(13) || CHR(10));
--    vReportingEndDate DATE := TO_DATE('31-DEC-' || TRIM(vReportingYear), 'DD-MON-YYYY' || CHR(13) || CHR(10));
  vReportingStartDate DATE := trunc(sysdate, 'YEAR');
  vReportingEndDate DATE := (last_day(add_months(trunc(sysdate), (12 - to_number(to_char(trunc(sysdate), 'mm'))))) + (86399/86400));

  Tab1 VARCHAR2(30 ) := '  ';
  Tab002 VARCHAR2(30 ) := '    ';
  Tab00003 VARCHAR2(30 ) := '      ';
  Tab0000004 VARCHAR2(30 ) := '        ';
  Tab000000005 VARCHAR2(30 ) := '          ';
  Tab00000000006 VARCHAR2(30 ) := '            ';
  Tab0000000000007 VARCHAR2(30 ) := '              ';
  Tab000000000000008 VARCHAR2(30 ) := '                ';
  Tab00000000000000009 VARCHAR2(30 ) := '                  ';
  Tab0000000000000000010 VARCHAR2(30 ) := '                    ';
  Tab000000000000000000011 VARCHAR2(30 ) := '                      ';
  Tab00000000000000000000012 VARCHAR2(30 ) := '                        ';
  Tab0000000000000000000000013 VARCHAR2(30 ) := '                          ';

  vPatFirst PATIENT."First"                  %TYPE;
  vPatLast PATIENT."Last"                    %TYPE;
  vPatBirth PATIENT."Birth"                  %TYPE;
  vPatSex PATIENT."Sex"                      %TYPE;
  vPatRace PTRACE."Race"                     %TYPE;
  vPatEthnic PATIENT."Ethnic"                %TYPE;

  vPatArea PATIENT."HomeArea"                %TYPE;
  vPatPhone PATIENT."HomePhone"              %TYPE;

  vPrefLanguage PATIENT."PrefLanguage"       %TYPE;
  vRaceEthDeclined PATIENT."RaceEthDeclined" %TYPE;

  vPatAddress1 PATIENT."Address1"            %TYPE;
  vPatAddress2 PATIENT."Address2"            %TYPE;

  vPatCity PATIENT."City"                    %TYPE;
  vPatProvince PATIENT."Province"            %TYPE;
  vPatPostal PATIENT."Postal"                %TYPE;
  vPatCountry PATIENT."Country"              %TYPE;

  -- Used to store the Cypress Patient ID
  vPatSIN PATIENT."Email"                    %TYPE;

  vPatAddress    CHAR(62 ) := ' ';
  vPatGender     CHAR(3 )  := ' ';
  vPatPhoneCode  CHAR(3 )  := ' ';
  vPatRaceCode   CHAR(6 )  := ' ';
  vPatEthnicCode CHAR(6 )  := ' ';

  vPatRaceDisplay   VARCHAR2(100 );
  vPatEthnicDisplay VARCHAR2(100 );

  -- used to store form answers
  vPItemAnsListRefCode PITEM."AnsListRefCode"%TYPE := NULL;
  vPItemAnsListDesc PITEM."AnsListDesc"%TYPE := NULL;
  vPItemDate PITEM."AnsDate"%TYPE := NULL;
  vSNOCode SNOCODE."SNOCode"%TYPE := NULL;
  vLOINC LOINC."LOINC"%TYPE := NULL;


  -- Cursor to grab all the measures from the test data set
  CURSOR CQMMeasures
  IS
  SELECT "CQM",
    "Title",
    "NeutralId",
    "Version",
    "SpecificId"
  FROM CQMVALSET
  WHERE "CQM" IN ('22','50','68','69','74','75','124','125','127','130','138','147','155','156','165');

	-- Cursor to grab "Encounter" type instances which are classified as "Encounter, Performed".
	-- In practice, these are all CPT-coded procedures in the M90000 range
	CURSOR EncounterInstances
	IS
	SELECT
		T."Type" || T."Id" || T."Treatment" AS "Extension",
		CASE SUBSTR(T."Procedure", 1, 1)
			WHEN 'D' THEN TRIM(SUBSTR(T."Procedure", 2))
			WHEN 'M' THEN TRIM(SUBSTR(T."Procedure", 2))
			ELSE '?'
			END AS "Procedure",
		CASE SUBSTR(T."Procedure", 1, 1)
			WHEN 'D' THEN 'Dental'
			WHEN 'M' THEN 'Medical'
			ELSE '?'
			END AS "Type",
		T."TreatmentDate" AS "Date"
	FROM TRX T, PROCEDUR P
	WHERE 1 = 1
		AND T."Procedure" = P."Procedure"
		AND T."Patient"  = vPatient		
    AND T."Type"     = 1
		AND T."Deleted"  = 0
		AND T."Status"   = 'C'
    AND (INSTR(T."Procedure", 'M', 1, 1) = 1 OR INSTR(T."Procedure", 'D', 1, 1)  = 1)
    AND T."Procedure" NOT IN ('M90920', 'M44388', 'M90653', 'M97802', 'D1206');



	-- cursor of procedures (either CDA dental procedures or CPT medical procedures).
	-- Special cases which use forms to collect the data (CQMs #68, 125) will be handled separately from this cursor.
	CURSOR ProcedureInstances
	IS
	SELECT
		T."Type" || T."Id" || T."Treatment" AS "Extension",
		CASE SUBSTR(T."Procedure", 1, 1)
			WHEN 'D' THEN TRIM(SUBSTR(T."Procedure", 2))
			WHEN 'M' THEN TRIM(SUBSTR(T."Procedure", 2))
			ELSE '?'
			END AS "Procedure",
		CASE SUBSTR(T."Procedure", 1, 1)
			WHEN 'D' THEN 'Dental'
			WHEN 'M' THEN 'Medical'
			ELSE '?'
			END AS "Type",
		P."Description" AS "Description",
		T."TreatmentDate" AS "Date"
	FROM TRX T, PROCEDUR P
	WHERE 1=1
		AND T."Type" = 1
		AND T."Deleted" = 0
		AND T."Status" = 'C'
		AND T."Patient" = vPatient
		AND T."Procedure" = P."Procedure"
		AND ((P."Category" < 18) OR (SUBSTR(P."Procedure", 2, 5) IN ('90947','90945','90940','90937','90935','90925','90924','90921','90920', '90653')))
		AND (INSTR(T."Procedure", 'M', 1, 1) = 1 OR INSTR(T."Procedure", 'D', 1, 1)  = 1);


  -- cursor of procedures (either CDA dental procedures or CPT medical procedures).
	-- Special cases which use forms to collect the data (CQMs #68, 125) will be handled separately from this cursor.
	CURSOR InterventionInstances
	IS
	SELECT
		T."Type" || T."Id" || T."Treatment" AS "Extension",
		CASE SUBSTR(T."Procedure", 1, 1)
			WHEN 'D' THEN TRIM(SUBSTR(T."Procedure", 2))
			WHEN 'M' THEN TRIM(SUBSTR(T."Procedure", 2))
			ELSE '?'
			END AS "Procedure",
		CASE SUBSTR(T."Procedure", 1, 1)
			WHEN 'D' THEN 'Dental'
			WHEN 'M' THEN 'Medical'
			ELSE '?'
			END AS "Type",
		P."Description" AS "Description",
		T."TreatmentDate" AS "Date"
	FROM TRX T, PROCEDUR P
	WHERE 1=1
		AND T."Type" = 1
		AND T."Deleted" = 0
		AND T."Status" = 'C'
		AND T."Patient" = vPatient
		AND T."Procedure" = P."Procedure"
		AND ((P."Category" < 18) OR (SUBSTR(P."Procedure", 2, 5) IN ('97802')))
		AND INSTR(T."Procedure", 'M', 1, 1) = 1;

  -- Cursor to grab "Finding" type instances where which are classified as "Physical Exam, Finding"
  CURSOR FindingInstances
  IS
  SELECT "PItem" "Extension",
    CASE
      WHEN f1."Code" = 'MDH_SBP' THEN '8480-6'
      WHEN f1."Code" = 'MDH_DBP' THEN '8462-4'
      WHEN f1."Code" = 'PT_STD_BMI' THEN '39156-5'
    END "Finding",
    p1."AppDate" "Date",
    'PQ' "ObsType",
    TRIM(p1."AnsText") "ObsValue",
    CASE
      WHEN f1."Code" = 'MDH_SBP' THEN 'mmHg'
      WHEN f1."Code" = 'MDH_DBP' THEN 'mmHg'
      WHEN f1."Code" = 'PT_STD_BMI' THEN 'kg/m2'
    END "ObsUnit",
    CASE
      WHEN f1."Code" = 'MDH_SBP' THEN 'Physical Exam: Systolic Blood Pressure'
      WHEN f1."Code" = 'MDH_DBP' THEN 'Physical Exam, Finding: Diastolic Blood Pressure'
      WHEN f1."Code" = 'PT_STD_BMI' THEN 'Physical Exam, Finding: BMI'
    END "InstanceText"
  FROM PITEM p1, FITEM f1
  WHERE 1=1
  AND p1."FormCode" = 'MUMDH'
  AND p1."FItem" = f1."FItem"
  AND p1."AppDate" IS NOT NULL
  AND p1."Patient" = vPatient
  AND LENGTH(TRIM(p1."AnsText")) > 0
  AND TO_NUMBER(TRIM(p1."AnsText"), '999999.99') > 0
  AND f1."Code" IN ('MDH_SBP', 'MDH_DBP', 'PT_STD_BMI')
  ORDER BY f1."Code";

	-- Cursor of diagnoses (Medical Problems)
	CURSOR DiagnosisInstances
	IS
	SELECT
		PA."PtAlert" AS "Extension",
		PA."Description" AS "DiagText",
		PA."SNOCode" AS "Diagnosis",
		PA."OnsetDate" AS "OnsetDate",
		PA."AddDateTime" AS "AddDateTime",
		PA."Status" AS "Status",
		(AH."Date" + (AH."Time"/1440)) AS "AuditDateTime"
	FROM PTALERT PA, AUDITHIS AH
	WHERE 1=1
		AND PA."Patient" = vPatient
		AND PA."AlertType" = 2
		AND PA."Audit" = AH."Audit"
		AND PA."Deleted" = 0
    AND PA."SNOCode" NOT IN ( '8517006','8392000','53896009','405746006','360929005',
                              '360918006','360900008','360890004','281018007','266928006',
                              '266925009','266924008','266923002','266922007','266921000',
                              '266919005','228512004','228503001','228502006','228501004',
                              '160621008','160620009','160618006','105541001','105540000',
                              '105539002','82302008','81703003','77176002','65568007','449868002',
                              '428071000124103','428061000124105','428041000124106','266920004',
                              '230065006','230064005','230063004','230062009','230060001','230059006',
                              '228518000','228517005','228516001','228515002','228514003','228504007',
                              '228494002','160619003','160606002','160605003','160604004','160603005'
                            );


  -- Cursor of Patient Characteristics (Tobacco User)
	CURSOR PatientCharacteristics
	IS
	SELECT
		PA."PtAlert" AS "Extension",
		PA."Description" AS "DiagText",
		PA."SNOCode" AS "Diagnosis",
		PA."OnsetDate" AS "OnsetDate",
		PA."AddDateTime" AS "AddDateTime",
		PA."Status" AS "Status",
		(AH."Date" + (AH."Time"/1440)) AS "AuditDateTime"
	FROM PTALERT PA, AUDITHIS AH
	WHERE 1=1
		AND PA."Patient" = vPatient
		AND PA."AlertType" = 2
		AND PA."Audit" = AH."Audit"
		AND PA."Deleted" = 0
    AND PA."SNOCode" IN ( '8517006','8392000','53896009','405746006','360929005',
                          '360918006','360900008','360890004','281018007','266928006',
                          '266925009','266924008','266923002','266922007','266921000',
                          '266919005','228512004','228503001','228502006','228501004',
                          '160621008','160620009','160618006','105541001','105540000',
                          '105539002','82302008','81703003','77176002','65568007','449868002',
                          '428071000124103','428061000124105','428041000124106','266920004',
                          '230065006','230064005','230063004','230062009','230060001','230059006',
                          '228518000','228517005','228516001','228515002','228514003','228504007',
                          '228494002','160619003','160606002','160605003','160604004','160603005'
                          );


  -- Cursor of medications administered (CVX 33 - Pneumococcal vaccinations)
	CURSOR MedsAdministered
	IS
	SELECT
		PI."PItem" AS "Extension",
		SUBSTR(PI."AnsListDesc", INSTR(PI."AnsListDesc", ' - ')+3) AS "Description",
		PI."AppDate" AS "Date",
    TRIM(SUBSTR(PI."AnsListDesc", 0, 3)) "Vaccine"
	FROM PITEM PI, FITEM FI
	WHERE 1=1
		AND PI."FItem" = FI."FItem"
		AND PI."Patient" = vPatient
		AND PI."FormCode" = 'MUMDH'
		AND PI."AnsListDesc" IS NOT NULL
		AND PI."AppDate" IS NOT NULL
    AND (
          (FI."Code" = 'MDH_PNEUM2' AND PI."AnsListDesc" LIKE '33 -%')
          OR
          (FI."Code" = 'INFVACSHOT' AND PI."AnsListDesc" LIKE '111 -%')
        )
	ORDER BY "AppDate";


  -- Cursor of Medication Orders (High Risk Meds   Tobacco Use Cessation Pharmacotherapy)
	CURSOR MedicationOrders
	IS
	SELECT
    p1."Prescription" AS "Extension",
    NVL(p1."StartDate", p1."Date") AS "StartDate",
    p1."RxNorm" AS "Medication",
    CASE
      WHEN p1."RxNorm" IN ( '998679','998675','998671','993681','993567','993557',
                            '993550','993541','993536','993518','993503','896100',
                            '892244','749788','749289','636676','636671','419168',
                            '359818','359817','317136','314119','312036','311975',
                            '311973','311972','250983','205316','205315','199890',
                            '199889','199888','198047','198046','198045','198031',
                            '198030','198029','151226','1046858','1046847')
        THEN 'Medication, Order: Tobacco Use Cessation Pharmacotherapy'
      WHEN p1."RxNorm" IN ( '891888','854894','854880','854876','854873','836647','836641',
                            '828692','485465','485442','485440','313762','313761','311995',
                            '311994','311992','311989','311988','1232202','1232194')
        THEN 'Medication, Order: High Risk Medications for the Elderly With Days Supply Criteria'
      ELSE 'Medication, Order: High Risk Medications for the Elderly'
    END AS "MedicationText"
  FROM PRESCRIP p1
  WHERE 1=1
    AND p1."Patient" = vPatient
    AND p1."PrescripType" IN (1,2)
    AND p1."ApprovalUser" != 0
    AND p1."RxNorm" IN (  '1000001', '200031',
                          '998679','998675','998671','993681','993567','993557',
                          '993550','993541','993536','993518','993503','896100',
                          '892244','749788','749289','636676','636671','419168',
                          '359818','359817','317136','314119','312036','311975',
                          '311973','311972','250983','205316','205315','199890',
                          '199889','199888','198047','198046','198045','198031',
                          '198030','198029','151226','1046858','1046847', -- Tobacco Use Cessation Pharmacotherapy
                          '1000351', '1000352', '1000355', '1000356', '1000486', '1000490', '1000496',
                          '1010696', '1010807', '1010946', '1010980', '1012650', '1012690', '1012757',
                          '1012764', '1012904', '1012940', '1012950', '1012956', '1012963', '1012972',
                          '1012974', '1012980', '1012982', '1012995', '1020477', '1037364', '1037379',
                          '1041814', '1042684', '1043400', '1046751', '1047494', '1049091', '1049289',
                          '1049630', '1049633', '1049723', '1049880', '1049898', '1049900', '1049904',
                          '1049906', '1049909', '1049918', '1050077', '1050080', '1052462', '1052647',
                          '1052928', '1053138', '1053618', '1053629', '1085945', '1086463', '1086475',
                          '1086720', '1087026', '1087459', '1087607', '1088936', '1089822', '1090532',
                          '1092189', '1092373', '1092398', '1092411', '1092566', '1092570', '1093075',
                          '1093083', '1093098', '1094131', '1094330', '1094350', '1094355', '1094406',
                          '1094434', '1094473', '1094501', '1094549', '1098443', '1098881', '1098906',
                          '1099308', '1099446', '1099644', '1099653', '1099654', '1099659', '1099668',
                          '1099677', '1099684', '1099694', '1099711', '1099779', '1099788', '1099872',
                          '1099948', '1100501', '1101427', '1101439', '1101446', '1101457', '1101855',
                          '1101858', '1112489', '1112779', '1113380', '1113998', '1115329', '1117245',
                          '1119420', '1145951', '1147619', '1148155', '1149632', '1189337', '1190448',
                          '1232642', '1233546', '1234386', '1236048', '1236387', '1236395', '1236403',
                          '1236420', '1236428', '1236455', '1236459', '1237035', '1237103', '1237110',
                          '1237118', '1242072', '1242502', '1242515', '1242522', '1242582', '1242618',
                          '1242622', '1244523', '1244714', '1244743', '1244747', '1244918', '1245284',
                          '1248057', '1248354', '1249617', '1250949', '1251493', '1251499', '1251614',
                          '1251621', '1251625', '1251756', '1251762', '1251770', '1251771', '1251787',
                          '1251791', '1251792', '1251794', '1251836', '1251838', '1291711', '1291718',
                          '1291854', '1291867', '1291868', '1292097', '1292098', '1292313', '1292314',
                          '1292321', '1292322', '1292324', '1293036', '1293040', '1293706', '1293710',
                          '1294306', '1294313', '1294322', '1294338', '1294348', '1294366', '1294367',
                          '1294368', '1294370', '1294371', '1294372', '1294380', '1294382', '1294383',
                          '1294557', '1294564', '1294567', '1294572', '1294589', '1294602', '1294607',
                          '1297410', '1297514', '1297517', '1297947', '1297950', '1297967', '1297974',
                          '1298267', '1298287', '1298288', '1298295', '1298348', '1298442', '1298446',
                          '1298799', '1298834', '1300081', '1300084', '1300164', '1304533', '1305588',
                          '1305775', '1307225', '1308438', '1356800', '1356807', '1356833', '1356841',
                          '1356848', '1356859', '1356866', '1357013', '1357389', '1359123', '1359124',
                          '1359126', '1359127', '1362789', '1363011', '1363504', '1363648', '1363651',
                          '1366953', '153444', '197426', '197427', '197428', '197429', '197446', '197447',
                          '197458', '197459', '197460', '197461', '197495', '197496', '197501', '197502',
                          '197622', '197647', '197657', '197658', '197659', '197660', '197661', '197662',
                          '197663', '197666', '197667', '197668', '197669', '197670', '197737', '197743',
                          '197744', '197745', '197746', '197817', '197818', '197819', '197923', '197924',
                          '197925', '197928', '197929', '197930', '197935', '197943', '197944', '197945',
                          '197956', '197957', '197958', '197960', '197963', '198032', '198033', '198034',
                          '198035', '198036', '198083', '198084', '198085', '198086', '198089', '198270',
                          '198274', '198275', '198276', '198277', '198278', '198280', '198368', '199164',
                          '199167', '199168', '199208', '199314', '199329', '199340', '199341', '199543',
                          '199549', '199607', '199782', '199820', '200330', '200331', '200332', '200335',
                          '204434', '204452', '205254', '205333', '208545', '235760', '238003', '238004',
                          '238006', '238090', '238133', '238134', '238135', '238153', '238154', '238175',
                          '240093', '240826', '241527', '241946', '242333', '242891', '242892', '243025',
                          '243220', '243628', '245373', '248139', '248478', '282462', '282463', '283463',
                          '284437', '284438', '308162', '308163', '308164', '308165', '308169', '308170',
                          '308172', '308322', '309232', '309239', '309243', '309244', '309249', '309709',
                          '309952', '309953', '309955', '309958', '309960', '310143', '310169', '310197',
                          '310203', '310204', '310205', '310206', '310212', '310213', '310215', '310534',
                          '310536', '310537', '310539', '310661', '310991', '310992', '311534', '311536',
                          '311538', '311551', '311552', '311553', '311554', '311555', '312288', '312289',
                          '312357', '312362', '312370', '312914', '312915', '313352', '313354', '313357',
                          '313385', '313386', '313387', '313389', '313391', '313393', '313396', '313406',
                          '313492', '313496', '313497', '313498', '313499', '314000', '314132', '314267',
                          '315144', '315201', '315234', '315235', '318179', '346508', '346713', '346714',
                          '346966', '347151', '348906', '349199', '349281', '349533', '349563', '351130',
                          '351192', '351228', '351254', '351262', '351263', '359278', '359280', '359281',
                          '359375', '359376', '359431', '359923', '360042', '391980', '402242', '402250',
                          '403849', '403922', '403923', '403956', '406590', '410205', '422098', '425319',
                          '435430', '435436', '435462', '435463', '435470', '435475', '435517', '476152',
                          '476540', '476545', '477221', '477245', '477587', '483169', '485607', '487079',
                          '540358', '542947', '544218', '546174', '577027', '577029', '577154', '584640',
                          '597658', '597675', '602598', '618368', '618370', '618376', '618378', '628823',
                          '631644', '636382', '636793', '636794', '644096', '644097', '647171', '647172',
                          '668535', '672838', '686523', '688240', '688507', '692766', '695963', '700669',
                          '700850', '700851', '700860', '701393', '702220', '702519', '707680', '728118',
                          '728581', '730794', '730878', '731007', '731032', '748594', '748802', '749850',
                          '754744', '755584', '755618', '755621', '756245', '756251', '756342', '758147',
                          '759687', '762986', '828299', '828320', '828348', '828353', '828358', '834022',
                          '835564', '835568', '835572', '835577', '835582', '835589', '835591', '835593',
                          '848331', '856706', '856720', '856762', '856773', '856783', '856797', '856825',
                          '856834', '856840', '856845', '856853', '857291', '857296', '857297', '857301',
                          '857305', '857315', '857416', '857430', '857461', '858364', '858923', '859003',
                          '859250', '860092', '860096', '860103', '860107', '860113', '860114', '860115',
                          '860215', '860221', '860225', '860231', '860749', '860767', '860771', '860792',
                          '861447', '861455', '861459', '861463', '861467', '861470', '861473', '861476',
                          '861479', '861482', '861493', '861494', '861509', '861573', '861578', '861743',
                          '861748', '861753', '861846', '862006', '862013', '862019', '862025', '863669',
                          '866021', '866144', '881320', '882504', '884707', '885209', '885213', '885219',
                          '889520', '895664', '901814', '905269', '905273', '905283', '905295', '991486',
                          '991528', '992432', '992438', '992441', '992447', '992454', '992460', '992475',
                          '992478', '992858', '992900', '993943', '994012', '994226', '994237', '994521',
                          '994528', '994535', '994541', '994824', '995062', '995082', '995123', '995128',
                          '995211', '995214', '995218', '995232', '995235', '995241', '995253', '995258',
                          '995270', '995274', '995278', '995281', '995285', '995428', '995591', '995592',
                          '996640', '996757', '997008', '997272', '998254', '999434', '999731', -- High Risk Meds
                          '891888','854894','854880','854876','854873','836647','836641',
                          '828692','485465','485442','485440','313762','313761','311995',
                          '311994','311992','311989','311988','1232202','1232194'); -- High Risk Meds with Days Supply

  -- SF-00192544/AX-18966
  vStage mryear."Stage"%type := 3;
  vStage3OutputFile clob := '';

BEGIN

  -- Determine a 'unique' filename
  vOutputFileName := 'XML_QRDA_TYPE1_' || TO_CHAR(vPatient) || '_' || TO_CHAR(SYSDATE, 'MM-DD-YYYY_HH24MISS') || '.xml';

  vError := 0;

  --
  -- SF-00192544/AX-18966: perform procedure QRDA_Type1_Stage3_XML_P (assume it is always stage 3)
  --
  begin
    --
    -- determine if stage 3; if not, proceed with normal/original process
    --
    select 0
    into vError
    from
      mryear my,
      producer prod,
      users u
    where 1=1
    and u."Producer" = prod."Producer"
    and my."User" = u."User"
    and u."Deleted" = 0
    and prod."MUEligible" = 1
    and prod."Producer" = vProducer
    and my."Stage" = vStage                                                     -- works for stage 3 only
    and my."Year" = vReportingYear;

    --
    -- call QRDA_Type1_Stage3_XML_P
    --
    qrda_cfg_pkg.QRDA_Type1_Stage3_XML_P (vProducer,
                                          vPatient,
                                          vReportingYear,
                                          vError,
                                          vStage3OutputFile);

    begin
      --
      -- open file for writing
      --
      DBMS_LOB_S.createtemporary (vOutputFile, TRUE);

      --
      -- append stage 3 output file
      --
      dbms_lob.append(vOutputFile, vStage3OutputFile);

    exception
      when others then
        vError := 1;

    end;

    --
    -- return to the calling function
    --
    return;

  exception
    when no_data_found then
      --
      -- determine reporting start and end dates then proceed with original processing (before stage 3 changes)
      --
      begin
        --
        -- value of vReportingYear being passed to the procedure changed
        --
        select
          trunc(my."DateTo", 'YEAR') "CQMSDate",
          (last_day(add_months(trunc(my."DateTo"), (12 - to_number(to_char(trunc(my."DateTo"), 'mm'))))) + (86399/86400)) "CQMEDate"
        into
          vReportingStartDate,
          vReportingEndDate
        from
          mryear my,
          producer prod,
          users u
        where 1=1
        and u."Producer" = prod."Producer"
        and my."User" = u."User"
        and u."Deleted" = 0
        and prod."MUEligible" = 1
        and prod."Producer" = vProducer
        and my."Stage" = 2                                                            -- works for stage 2 only
        and my."Year" = vReportingYear;

      exception
        when others then
          --
          -- proceed with original processing (before stage 3 changes) using default dates
          --
          null;

      end;

  end;
  --
  -- end: SF-00192544/AX-18966: perform procedure QRDA_Type1_Stage3_XML_P (assume it is always stage 3)
  --

  -- Convert whats passed in from MUD to proper CQM format
  vMeasureFormatted := TRANSLATE(SUBSTR(vMeasure, 1, 3), 'ABCD', ' ');

	-- Open the file for writing
	BEGIN
    DBMS_LOB_S.createtemporary (vOutputFile, TRUE);
	EXCEPTION WHEN OTHERS THEN
		vError := 1;
	END;

  DBMS_LOB_S.createtemporary (vTopHeaderFile, TRUE);
  DBMS_LOB_S.createtemporary (vBottomHeaderFile, TRUE);
  DBMS_LOB_S.createtemporary (vMeasureFile, TRUE);
  DBMS_LOB_S.createtemporary (vOrganizerFile, TRUE);
  DBMS_LOB_S.createtemporary (vBodyFile, TRUE);
  DBMS_LOB_S.createtemporary (vFooterFile, TRUE);

  BEGIN

    SELECT "User" INTO vUser FROM USERS WHERE TRIM("Producer") = vProducer;

    -- Get provider's NPI (required) and TIN (if in use)
    BEGIN
      SELECT
        TRIM("LastName") "LastName",
        TRIM("FirstName") "FirstName",
        NVL(SUBSTR("NPI",1,10), ' ') "NPI",
        CASE "IsTIN"
          WHEN 0 THEN ' '
          WHEN 1 THEN SUBSTR("Specialist",1,9)
        END "IsTIN",
        TRIM("Address1") "Address1",
        TRIM("Address2") "Address2",
        TRIM("City") "City",
        TRIM("Province") "Province",
        TRIM("Postal") "Postal",
        TRIM("AddressOther") "AddressOther",
        TRIM("BArea") "BArea",
        TRIM("BTel") "BTel"
      INTO  vProvLast, vProvFirst, vProvNPI, vProvTIN, vProvAddress1, vProvAddress2,
            vProvCity, vProvProvince, vProvPostal, vProvCountry, vProvArea, vProvPhone
      FROM PRODUCER
      WHERE TRIM("Producer") = vProducer;

    EXCEPTION WHEN OTHERS THEN
      vProvLast := ' ';
      vProvFirst := ' ';
      vProvNPI := ' ';
      vProvTIN := ' ';
      vProvAddress1 := ' ';
      vProvAddress2 := ' ';
      vProvCity := ' ';
      vProvProvince := ' ';
      vProvPostal := ' ';
      vProvCountry := ' ';
      vProvArea := ' ';
      vProvPhone := ' ';
    END;

    IF vProvAddress2 IS NOT NULL THEN
      vProvAddress := TRIM(vProvAddress1) || ', ' || TRIM(vProvAddress2);
    ELSE
      vProvAddress := TRIM(vProvAddress1);
    END IF;


    -- Get practice name
    SELECT TRIM("Name")
    INTO vOrganizationName
    FROM PRACTICE
    WHERE "Id" = (SELECT MIN("Id") FROM PRACTICE);


    -- Get the patients information
    BEGIN
      SELECT
        TRIM("First") "First",
        TRIM("Last") "Last",
        "Birth",
        "Sex",
        CASE "Sex"
          WHEN 1 THEN 'M'
          WHEN 2 THEN 'F'
          WHEN 3 THEN 'UN'
          ELSE 'UNK'
        END "SexCode",
        NVL(( SELECT TRIM(MAX("Race"))
              FROM PTRACE PR
              WHERE PR."Patient" = P."Patient"
              AND PR."Deleted" = 0
            ), 'UNK') "Race",
        CASE NVL((SELECT TRIM(MAX("Race"))
                  FROM PTRACE PR
                  WHERE PR."Patient" = P."Patient"
                  AND PR."Deleted" = 0
                 ), 'UNK')
          WHEN 'NATIVE' THEN '1002-5'
          WHEN 'ASIAN' THEN '2028-9'
          WHEN 'BLACK' THEN '2054-5'
          WHEN 'NATIVE' THEN '2076-8'
          WHEN 'OTHER' THEN '2131-1'
          WHEN 'WHITE' THEN '2106-3'
          ELSE 'UNK'
        END "RaceCode",
        NVL(TRIM("Ethnic"), 'UNK') "Ethnic",
        CASE NVL(TRIM("Ethnic"), 'UNK')
          WHEN 'HISP' THEN '2135-2'
          WHEN 'NHISP' THEN '2186-5'
          ELSE 'UNK'
        END "EthnicCode",
        CASE "ContactAt"
          WHEN 1 THEN TRIM("HomeArea")
          WHEN 2 THEN TRIM("WorkArea")
          WHEN 3 THEN TRIM("OtherArea")
          WHEN 4 THEN TRIM("MobileArea")
        END "AreaCode",
        CASE "ContactAt"
          WHEN 1 THEN TRIM("HomePhone")
          WHEN 2 THEN TRIM("WorkPhone")
          WHEN 3 THEN TRIM("OtherPhone")
          WHEN 4 THEN TRIM("MobilePhone")
        END "Phone",
        CASE "ContactAt"
          WHEN 1 THEN 'HP'
          WHEN 2 THEN 'WP'
          WHEN 3 THEN 'HV'
          WHEN 4 THEN 'MC'
        END "PhoneCode",
        TRIM("Address1") "Address1",
        TRIM("Address2") "Address2",
        TRIM("City") "City",
        TRIM("Province") "Province",
        TRIM("Postal") "Postal",
        TRIM("Country") "Country",
        NVL(TRIM(LC."ISOCode"), 'UNK') "PrefLanguage",
        "RaceEthDeclined",
        TRIM("Email") "Sin"
      INTO  vPatFirst, vPatLast, vPatBirth, vPatSex, vPatGender, vPatRace,
            vPatRaceCode, vPatEthnic, vPatEthnicCode, vPatArea, vPatPhone,
            vPatPhoneCode, vPatAddress1, vPatAddress2, vPatCity, vPatProvince,
            vPatPostal, vPatCountry, vPrefLanguage, vRaceEthDeclined, vPatSIN
      FROM PATIENT P LEFT OUTER JOIN LANGCD LC ON P."PrefLanguage" = LC."LangCd"
      WHERE "Patient" = vPatient;

    EXCEPTION WHEN OTHERS THEN
      vPatFirst := ' ';
      vPatLast := ' ';
      vPatBirth := TRUNC(SYSDATE);
      vPatSex := 0;
      vPatGender := ' ';
      vPatRace := ' ';
      vPatRaceCode := ' ';
      vPatEthnic := ' ';
      vPatEthnicCode := ' ';
      vPatArea := ' ';
      vPatPhone := ' ';
      vPatPhoneCode := ' ';
      vPatAddress1 := ' ';
      vPatAddress2 := ' ';
      vPatCity := ' ';
      vPatProvince := ' ';
      vPatPostal := ' ';
      vPatCountry := ' ';
      vPrefLanguage := ' ';
      vRaceEthDeclined := 0;
      vPatSIN := ' ';

      vError := 2;
    END;

    IF vPatAddress2 IS NOT NULL THEN
      vPatAddress := TRIM(vPatAddress1) || ', ' || TRIM(vPatAddress2);
    ELSE
      vPatAddress := TRIM(vPatAddress1);
    END IF;

    IF vPatRaceCode = '1002-5' THEN
      vPatRaceDisplay := 'American Indian or Alaska Native';
    ELSIF vPatRaceCode = '2028-9' THEN
      vPatRaceDisplay := 'Asian';
    ELSIF vPatRaceCode = '2054-5' THEN
      vPatRaceDisplay := 'Black or African American';
    ELSIF vPatRaceCode = '2076-8' THEN
      vPatRaceDisplay := 'Native Hawaiian or Other Pacific Islander';
    ELSIF vPatRaceCode = '2131-1' THEN
      vPatRaceDisplay := 'Other Race';
    ELSIF vPatRaceCode = '2106-3' THEN
      vPatRaceDisplay := 'White';
    ELSE
      vPatRaceDisplay := ' ';
    END IF;

    IF vPatEthnicCode = '2135-2' THEN
      vPatEthnicDisplay := 'Hispanic or Latino';
    ELSIF vPatEthnicCode = '2186-5' THEN
      vPatEthnicDisplay := 'Not Hispanic or Latino';
    ELSE
      vPatEthnicDisplay := ' ';
    END IF;


    IF vError = 0 THEN

      -- write XML header
      dbms_lob.append(vTopHeaderFile, '<?xml version="1.0" encoding="utf-8"?>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, '<?xml-stylesheet type="text/xsl" href="cda.xsl"?>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, '<ClinicalDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:hl7-org:v3" xmlns:voc="urn:hl7-org:v3/voc" xmlns:sdtc="urn:hl7-org:sdtc">' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab1 || '<!-- QRDA Header -->' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab1 || '<realmCode code=US/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab1 || '<typeId root="2.16.840.1.113883.1.3" extension=POCD_HD000040/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab1 || '<!-- US Realm Header Template Id -->' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab1 || '<templateId root="2.16.840.1.113883.10.20.22.1.1"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab1 || '<!-- QRDA templateId -->' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab1 || '<templateId root="2.16.840.1.113883.10.20.24.1.1"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab1 || '<!-- QDM-based QRDA templateId -->' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab1 || '<templateId root="2.16.840.1.113883.10.20.24.1.2"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab1 || '<!-- This is the globally unique identifier for this QRDA document -->' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab1 || '<id root="5b010313-eff2-432c-9909-6193d8416fac"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab1 || '<!-- QRDA document type code -->' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab1 || '<code code="55182-0" codeSystem="2.16.840.1.113883.6.1" codeSystemName=LOINC displayName="Quality Measure Report"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab1 || '<title>QRDA Incidence Report</title>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab1 || '<!-- This is the document creation time -->' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab1 || '<effectiveTime value="' || TO_CHAR(SYSDATE,'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab1 || '<confidentialityCode code=N codeSystem="2.16.840.1.113883.5.25"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab1 || '<languageCode code=eng/>' || CHR(10));

      -- patient header
      dbms_lob.append(vTopHeaderFile, Tab1 || '<!-- reported patient -->' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab1 || '<recordTarget>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab002 || '<patientRole>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '<!-- id root="Cypress" extension="' || TO_CHAR(vPatSIN) || '"/ -->' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '<!-- axiUm PatientID number -->' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '<id extension="' || TO_CHAR(vPatient) || '" root="2.16.840.1.113883.4.572"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '<addr use=HP>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<streetAddressLine>' || HTF.ESCAPE_SC(TRIM(vPatAddress)) || '</streetAddressLine>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<city>' || HTF.ESCAPE_SC(TRIM(vPatCity)) || '</city>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<state>' || HTF.ESCAPE_SC(TRIM(vPatProvince)) || '</state>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<postalCode>' || HTF.ESCAPE_SC(TRIM(vPatPostal)) || '</postalCode>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<country>' || HTF.ESCAPE_SC(TRIM(vPatCountry)) || '</country>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '</addr>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '<telecom use="' || HTF.ESCAPE_SC(TRIM(vPatPhoneCode)) || '" value="tel:+1-' || HTF.ESCAPE_SC(TRIM(vPatArea)) || '-' || HTF.ESCAPE_SC(TRIM(vPatPhone)) || '"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '<patient>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<name>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '<given>' || HTF.ESCAPE_SC(TRIM(vPatFirst)) || '</given>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '<family>' || HTF.ESCAPE_SC(TRIM(vPatLast)) || '</family>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '</name>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<administrativeGenderCode code="' || HTF.ESCAPE_SC(TRIM(vPatGender)) || '" codeSystem="2.16.840.1.113883.5.1" codeSystemName="HL7 AdministrativeGender"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<birthTime value="' || TO_CHAR(vPatBirth,'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<raceCode code="' || HTF.ESCAPE_SC(TRIM(vPatRaceCode)) || '" displayName="' || HTF.ESCAPE_SC(TRIM(vPatRaceDisplay)) || '" codeSystemName="CDC Race and Ethnicity" codeSystem="2.16.840.1.113883.6.238"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<ethnicGroupCode code="' || HTF.ESCAPE_SC(TRIM(vPatEthnicCode)) || '" displayName="' || HTF.ESCAPE_SC(TRIM(vPatEthnicDisplay)) || '" codeSystemName="CDC Race and Ethnicity" codeSystem="2.16.840.1.113883.6.238"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<languageCommunication>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '<templateId root="2.16.840.1.113883.3.88.11.83.2" assigningAuthorityName="HITSP/C83"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '<templateId root="1.3.6.1.4.1.19376.1.5.3.1.2.1" assigningAuthorityName="IHE/PCC"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '<languageCode code="' || HTF.ESCAPE_SC(TRIM(vPrefLanguage)) || '"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '</languageCommunication>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '</patient>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab002 || '</patientRole>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab1 || '</recordTarget>' || CHR(10));

      -- author element
      dbms_lob.append(vTopHeaderFile, Tab1 || '<author>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab002 || '<time value="' || TO_CHAR(SYSDATE,'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab002 || '<assignedAuthor>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '<!-- id extension="Exan" root="2.16.840.1.113883.19.5"/ -->' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '<!-- NPI -->' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '<id extension="' || HTF.ESCAPE_SC(TRIM(vProvNPI)) || '" root="2.16.840.1.113883.4.6"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '<addr>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<streetAddressLine>' || HTF.ESCAPE_SC(TRIM(vProvAddress)) || '</streetAddressLine>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<city>' || HTF.ESCAPE_SC(TRIM(vProvCity)) || '</city>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<state>' || HTF.ESCAPE_SC(TRIM(vProvProvince)) || '</state>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<postalCode>' || HTF.ESCAPE_SC(TRIM(vProvPostal)) || '</postalCode>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<country>' || HTF.ESCAPE_SC(TRIM(vProvCountry)) || '</country>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '</addr>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '<telecom use=WP value="tel:+1-' || HTF.ESCAPE_SC(TRIM(vProvArea)) || '-' || HTF.ESCAPE_SC(TRIM(vProvPhone)) || '"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '<assignedAuthoringDevice>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<manufacturerModelName>Exan Software</manufacturerModelName>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<softwareName>axiUm</softwareName>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '</assignedAuthoringDevice>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab002 || '</assignedAuthor>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab1 || '</author>' || CHR(10));

      -- custodian element
      dbms_lob.append(vTopHeaderFile, Tab1 || '<custodian>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab002 || '<assignedCustodian>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '<representedCustodianOrganization>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<id root="2.16.840.1.113883.19.5"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<name>' || HTF.ESCAPE_SC(TRIM(vOrganizationName)) || '</name>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<telecom use=WP value="tel:+1-' || HTF.ESCAPE_SC(TRIM(vProvArea)) || '-' || HTF.ESCAPE_SC(TRIM(vProvPhone)) || '"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<addr>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '<streetAddressLine>' || HTF.ESCAPE_SC(TRIM(vProvAddress)) || '</streetAddressLine>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '<city>' || HTF.ESCAPE_SC(TRIM(vProvCity)) || '</city>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '<state>' || HTF.ESCAPE_SC(TRIM(vProvProvince)) || '</state>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '<postalCode>' || HTF.ESCAPE_SC(TRIM(vProvPostal)) || '</postalCode>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '<country>' || HTF.ESCAPE_SC(TRIM(vProvCountry)) || '</country>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '</addr>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '</representedCustodianOrganization>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab002 || '</assignedCustodian>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab1 || '</custodian>' || CHR(10));

      -- legal authenticator element
      dbms_lob.append(vTopHeaderFile, Tab1 || '<legalAuthenticator>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab002 || '<time value="' || TO_CHAR(SYSDATE,'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab002 || '<signatureCode code=S/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab002 || '<assignedEntity>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '<id root="bc01a5d1-3a34-4286-82cc-43eb04c972a7"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '<addr>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<streetAddressLine>' || HTF.ESCAPE_SC(TRIM(vProvAddress)) || '</streetAddressLine>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<city>' || HTF.ESCAPE_SC(TRIM(vProvCity)) || '</city>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<state>' || HTF.ESCAPE_SC(TRIM(vProvProvince)) || '</state>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<postalCode>' || HTF.ESCAPE_SC(TRIM(vProvPostal)) || '</postalCode>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<country>' || HTF.ESCAPE_SC(TRIM(vProvCountry)) || '</country>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '</addr>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '<telecom use=WP value="tel:+1-' || HTF.ESCAPE_SC(TRIM(vProvArea)) || '-' || HTF.ESCAPE_SC(TRIM(vProvPhone)) || '"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '<assignedPerson>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<name>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '<given>' || HTF.ESCAPE_SC(TRIM(vProvFirst)) || '</given>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '<family>' || HTF.ESCAPE_SC(TRIM(vProvLast)) || '</family>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '</name>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '</assignedPerson>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '<representedOrganization>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<id root="2.16.840.1.113883.19.5"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<name>' || HTF.ESCAPE_SC(TRIM(vOrganizationName)) || '</name>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '</representedOrganization>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab002 || '</assignedEntity>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab1 || '</legalAuthenticator>' || CHR(10));

      -- provider information
      dbms_lob.append(vTopHeaderFile, '' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab1 || '<!-- TODO: This is where the provider information will go.' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab1 || '     It is currently hard coded, but should be replaced with the providers' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab1 || '     and the time over which they are performing. --> ' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab1 || '<documentationOf typeCode=DOC>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab002 || '<serviceEvent classCode=PCPR> <!-- care provision -->' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '<effectiveTime>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<low value="' || TO_CHAR(vReportingStartDate,'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<high value="' || TO_CHAR(vReportingEndDate,'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '</effectiveTime>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '<!-- You can include multiple performers, each with an NPI, TIN, CCN. -->' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '<performer typeCode=PRF>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<time>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '<low value="' || TO_CHAR(vReportingStartDate,'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '<high value="' || TO_CHAR(vReportingEndDate,'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '</time>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<assignedEntity>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '<!-- This is the provider NPI -->' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '<id root="2.16.840.1.113883.4.6" extension="' || HTF.ESCAPE_SC(TRIM(vProvNPI)) || '" />' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '<representedOrganization>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00000000006 || '<!-- This is the organization TIN -->' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00000000006 || '<id root="2.16.840.1.113883.4.2" extension="' || HTF.ESCAPE_SC(TRIM(vProvTIN)) || '" />' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00000000006 || '<!-- This is the organization CCN -->' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00000000006 || '<id root="2.16.840.1.113883.4.336" extension="' || HTF.ESCAPE_SC(TRIM(vCMSCertifcationNum)) || '" />' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '</representedOrganization>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '</assignedEntity>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '</performer>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab002 || '</serviceEvent>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab1 || '</documentationOf>' || CHR(10));

      -- Measure section
      dbms_lob.append(vTopHeaderFile, Tab1 || '<component>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab002 || '<structuredBody>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00003 || '<component>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000004 || '<section>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '<!-- ' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '  *****************************************************************' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '  Measure Section' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '  *****************************************************************' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '-->' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '<!-- This is the templateId for Measure Section -->' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '<templateId root="2.16.840.1.113883.10.20.24.2.2"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '<!-- This is the templateId for Measure Section QDM -->' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '<templateId root="2.16.840.1.113883.10.20.24.2.3"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '<!-- This is the LOINC code for "Measure document". This stays the same for all measure section required by QRDA standard -->' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '<code code="55186-1" codeSystem="2.16.840.1.113883.6.1"/>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '<title>Measure Section</title>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000005 || '<text>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00000000006 || '<table border="1" width="100%">' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000000000007 || '<thead>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000000000008 || '<tr>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00000000000000009 || '<th>eMeasure Title</th>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00000000000000009 || '<th>Version neutral identifier</th>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00000000000000009 || '<th>eMeasure Version Number</th>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab00000000000000009 || '<th>Version specific identifier</th>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab000000000000008 || '</tr>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000000000007 || '</thead>' || CHR(10));
      dbms_lob.append(vTopHeaderFile, Tab0000000000007 || '<tbody>' || CHR(10));


      dbms_lob.append(vOrganizerFile, Tab000000005 || '<!-- 1..* Organizers, each containing a reference to an eMeasure -->' || CHR(10));

      -- Measure References
      FOR CQM IN CQMMeasures LOOP
        dbms_lob.append(vMeasureFile, Tab000000000000008 || '<tr>' || CHR(10));
        dbms_lob.append(vMeasureFile, Tab00000000000000009 || '<td>' || HTF.ESCAPE_SC(TRIM(CQM."Title")) || '</td>' || CHR(10));
        dbms_lob.append(vMeasureFile, Tab00000000000000009 || '<td>' || HTF.ESCAPE_SC(TRIM(CQM."NeutralId")) || '</td>' || CHR(10));
        dbms_lob.append(vMeasureFile, Tab00000000000000009 || '<td>' || HTF.ESCAPE_SC(TRIM(CQM."Version")) || '</td>' || CHR(10));
        dbms_lob.append(vMeasureFile, Tab00000000000000009 || '<td>' || HTF.ESCAPE_SC(TRIM(CQM."SpecificId")) || '</td>' || CHR(10));
        dbms_lob.append(vMeasureFile, Tab00000000000000009 || '<td></td>' || CHR(10));
        dbms_lob.append(vMeasureFile, Tab000000000000008 || '</tr>' || CHR(10));

        -- Organizer seection, contains a reference to an eMeasure
        dbms_lob.append(vOrganizerFile, Tab000000005 || '<entry>' || CHR(10));
        dbms_lob.append(vOrganizerFile, Tab00000000006 || '<organizer classCode="cluster" moodCode=EVN>' || CHR(10));
        dbms_lob.append(vOrganizerFile, Tab0000000000007 || '<!-- This is the templateId for Measure Reference -->' || CHR(10));
        dbms_lob.append(vOrganizerFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.24.3.98"/>' || CHR(10));
        dbms_lob.append(vOrganizerFile, Tab0000000000007 || '<!-- This is the templateId for eMeasure Reference QDM -->' || CHR(10));
        dbms_lob.append(vOrganizerFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.24.3.97"/>' || CHR(10));
        dbms_lob.append(vOrganizerFile, Tab0000000000007 || '<statusCode code=completed/>' || CHR(10));
        dbms_lob.append(vOrganizerFile, Tab0000000000007 || '<!-- Containing isBranch external references -->' || CHR(10));
        dbms_lob.append(vOrganizerFile, Tab0000000000007 || '<reference typeCode=REFR>' || CHR(10));
        dbms_lob.append(vOrganizerFile, Tab000000000000008 || '<externalDocument classCode=DOC moodCode=EVN>' || CHR(10));
        dbms_lob.append(vOrganizerFile, Tab00000000000000009 || '<!-- SHALL: This is the version specific identifier for eMeasure: QualityMeasureDocument/id it is a GUID-->' || CHR(10));
        dbms_lob.append(vOrganizerFile, Tab00000000000000009 || '<id root="' || HTF.ESCAPE_SC(TRIM(CQM."SpecificId")) || '"/>' || CHR(10));
        dbms_lob.append(vOrganizerFile, Tab00000000000000009 || '<!-- SHOULD This is the title of the eMeasure -->' || CHR(10));
        dbms_lob.append(vOrganizerFile, Tab00000000000000009 || '<text>' || HTF.ESCAPE_SC(TRIM(CQM."Title")) || '</text>' || CHR(10));
        dbms_lob.append(vOrganizerFile, Tab00000000000000009 || '<!-- SHOULD: setId is the eMeasure version neutral id  -->' || CHR(10));
        dbms_lob.append(vOrganizerFile, Tab00000000000000009 || '<setId root="' || HTF.ESCAPE_SC(TRIM(CQM."NeutralId")) || '"/>' || CHR(10));
        dbms_lob.append(vOrganizerFile, Tab00000000000000009 || '<!-- This is the sequential eMeasure Version number -->' || CHR(10));
        dbms_lob.append(vOrganizerFile, Tab00000000000000009 || '<versionNumber value="' || HTF.ESCAPE_SC(TRIM(CQM."Version")) || '"/>' || CHR(10));
        dbms_lob.append(vOrganizerFile, Tab000000000000008 || '</externalDocument>' || CHR(10));
        dbms_lob.append(vOrganizerFile, Tab0000000000007 || '</reference>' || CHR(10));
        dbms_lob.append(vOrganizerFile, Tab00000000006 || '</organizer>' || CHR(10));
        dbms_lob.append(vOrganizerFile, Tab000000005 || '</entry>' || CHR(10));
      END LOOP;


      -- Bottom of Measure section
      dbms_lob.append(vMeasureFile, Tab0000000000007 || '</tbody>' || CHR(10));
      dbms_lob.append(vMeasureFile, Tab00000000006 || '</table>' || CHR(10));
      dbms_lob.append(vMeasureFile, Tab000000005 || '</text>' || CHR(10));

      -- Bottom of Organizer section
      dbms_lob.append(vOrganizerFile, Tab0000004 || '</section>' || CHR(10));
      dbms_lob.append(vOrganizerFile, Tab00003 || '</component>' || CHR(10));

      -- Reporting parameter section
      dbms_lob.append(vBottomHeaderFile, Tab00003 || '<component>' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab0000004 || '<section>' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab000000005 || '<!-- This is the templateId for Reporting Parameters section -->' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab000000005 || '<templateId root="2.16.840.1.113883.10.20.17.2.1"/>' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab000000005 || '<code code="55187-9" codeSystem="2.16.840.1.113883.6.1"/>' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab000000005 || '<title>Reporting Parameters</title>' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab000000005 || '<text>' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab00000000006 || '<list>' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab0000000000007 || '<item>Reporting period: ' || TRIM(TO_CHAR(vReportingStartDate,'Month')) || TO_CHAR(vReportingStartDate,' DD, YYYY HH24:MI') || ' - ' || TRIM(TO_CHAR(vReportingEndDate + (86399/86400),'Month')) || TO_CHAR(vReportingEndDate + (86399/86400),' DD, YYYY HH24:MI') || '</item>' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab00000000006 || '</list>' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab000000005 || '</text>' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab000000005 || '<entry typeCode=DRIV>' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab00000000006 || '<act classCode=ACT moodCode=EVN>' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab0000000000007 || '<!-- This is the templateId for Reporting Parameteres Act -->' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.17.3.8"/>' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab0000000000007 || '<code code="252116004" codeSystem="2.16.840.1.113883.6.96" displayName="Observation Parameters"/>' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab0000000000007 || '<effectiveTime>' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab000000000000008 || '<low value="' || TO_CHAR(vReportingStartDate,'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab000000000000008 || '<high value="' || TO_CHAR(vReportingEndDate + (86399/86400),'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab0000000000007 || '</effectiveTime>' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab00000000006 || '</act>' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab000000005 || '</entry>' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab0000004 || '</section>' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab00003 || '</component>' || CHR(10));

      -- Patient data section
      dbms_lob.append(vBottomHeaderFile, Tab00003 || '<component>' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab0000004 || '<section>' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab000000005 || '<!-- This is the templateId for Patient Data section -->' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab000000005 || '<templateId root="2.16.840.1.113883.10.20.17.2.4"/>' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab000000005 || '<!-- This is the templateId for Patient Data QDM section -->' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab000000005 || '<templateId root="2.16.840.1.113883.10.20.24.2.1"/>' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab000000005 || '<code code="55188-7" codeSystem="2.16.840.1.113883.6.1"/>' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab000000005 || '<title>Patient Data</title>' || CHR(10));
      dbms_lob.append(vBottomHeaderFile, Tab000000005 || '<text></text>' || CHR(10));

      /*
          This is the order we should follow to ensure our output matches up
          with the test patient Cat 1 Files. This will ease us in troubleshooting.

            NEW ORDER:

            Order 1 - Encounters
            Order 2 - Physical Exam
            Order 3 - Diagnosis
            Order 4 - Procedures
            Order 5 - Laboratory Tests
            Order 6 - Interventions
            Order 7 - Communication from Provider to Provider
            Order 8 - Diagnostic Study Results
            Order 9 - Patient Characteristics
            Order 10 - Medications
      */

      -- Order 1 - Encounters
      FOR I IN EncounterInstances LOOP
        vSpecificUID := '';

        IF I."Type" = 'Dental' THEN
          vCodeSystem := vCS_ADA;
        ELSIF I."Type" = 'Medical' THEN
          vCodeSystem := vCS_CPT4;
        ELSE
          vCodeSystem := ' ';
        END IF;

        -- get the UID for the procedure using the mapping table
        BEGIN
          IF I."Type" = 'Dental' THEN
            SELECT TRIM("UID") INTO vSpecificUID
            FROM QRDAVALSET Q
            WHERE 1=1
              AND TRIM(Q."Code")  = 'D' || TRIM(I."Procedure")
              AND Q."DataElement" = 3
              AND Q."CQMId"       = vMeasureFormatted
              AND ROWNUM          = 1;
          ELSIF I."Type" = 'Medical' THEN
            SELECT TRIM("UID") INTO vSpecificUID
              FROM QRDAVALSET Q
              WHERE 1=1
                AND TRIM(Q."Code")  = 'M' || TRIM(I."Procedure")
                AND Q."DataElement" = 3
                AND Q."CQMId"       = vMeasureFormatted
                AND ROWNUM          = 1;
          END IF;

        EXCEPTION
          WHEN NO_DATA_FOUND THEN
            IF I."Type" = 'Dental' THEN
              SELECT NVL(MAX(TRIM("UID")), 'NO_UID_FOUND') INTO vSpecificUID
              FROM QRDAVALSET Q
              WHERE 1=1
                AND TRIM(Q."Code")  = 'D' || TRIM(I."Procedure")
                AND Q."DataElement" = 3
                AND ROWNUM          = 1;
            ELSIF I."Type" = 'Medical' THEN
              SELECT NVL(MAX(TRIM("UID")), 'NO_UID_FOUND') INTO vSpecificUID
                FROM QRDAVALSET Q
                WHERE 1=1
                  AND TRIM(Q."Code")  = 'M' || TRIM(I."Procedure")
                  AND Q."DataElement" = 3
                  AND ROWNUM          = 1;
            END IF;

          WHEN OTHERS THEN
            vSpecificId := 'UNK';
        END;

        dbms_lob.append(vBodyFile, Tab000000005 || '<entry>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000006 || '<encounter classCode=ENC moodCode=EVN>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<!--  Encounter activities template -->' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.22.4.49"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<!-- Encounter performed template -->' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.24.3.23"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<id root="1.3.6.1.4.1.115" extension="' || I."Extension" || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<code code="' || TRIM(I."Procedure") || '" codeSystem="' || TRIM(vCodeSystem) || '" sdtc:valueSet="' || TRIM(vSpecificUID) || '">' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<originalText>Encounter, Performed: Office Visit</originalText>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</code>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<text>Encounter, Performed: Office Visit</text>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<statusCode code=completed/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<effectiveTime>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<!-- We try to look for the admit/discharge times on the encounter if they are' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '     there. If not, we fall back to the typical start/end date. -->' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<low value="' || TO_CHAR(I."Date",'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<high value="' || TO_CHAR(I."Date",'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</effectiveTime>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000006 || '</encounter>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000005 || '</entry>' || CHR(10));

      END LOOP;


      -- Order 2 - Physical Exam Finding Instances
      FOR I IN FindingInstances LOOP
        vSpecificUID := '';
        vCodeSystem := vCS_LOINC;

        -- get the UID for the finding using the mapping table
        BEGIN
          SELECT TRIM("UID") INTO vSpecificUID
          FROM QRDAVALSET Q
          WHERE 1=1
            AND TRIM(Q."Code") = TRIM(I."Finding")
            AND Q."DataElement" = 5
            AND ROWNUM          = 1;

        EXCEPTION WHEN OTHERS THEN
          vSpecificId := 'UNK';
        END;

        dbms_lob.append(vBodyFile, Tab000000005 || '<entry>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000006 || '<!-- Physical Exam Finding -->' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000006 || '<observation classCode=OBS moodCode=EVN>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<!-- Result observation template -->' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.22.4.2"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<!-- Physical Exam, Finding template -->' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.24.3.57"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<id root="1.3.6.1.4.1.115" extension="' || TRIM(I."Extension") || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<code code="' || TRIM(I."Finding") || '" codeSystem="' || TRIM(vCodeSystem) || '" sdtc:valueSet="' || TRIM(vSpecificUID) || '">' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<originalText>' || TRIM(I."InstanceText") || '</originalText>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</code>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<statusCode code=completed/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<effectiveTime>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<low value="' || TO_CHAR(I."Date",'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<high value="' || TO_CHAR(I."Date",'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</effectiveTime>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<value xsi:type="' || TRIM(I."ObsType") || '" value="' || TRIM(I."ObsValue") || '" unit="' || TRIM(I."ObsUnit") || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000006 || '</observation>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000005 || '</entry>' || CHR(10));

      END LOOP;


      -- Order 3 - Diagnosis
      FOR I IN DiagnosisInstances LOOP
        vSpecificUID := '';
        vCodeSystem := vCS_SNOMED;

        -- get the UID for the diagnosis using the mapping table
        BEGIN
          SELECT TRIM("UID") INTO vSpecificUID
          FROM QRDAVALSET Q
          WHERE 1=1
            AND TRIM(Q."Code")  = TRIM(I."Diagnosis")
            AND Q."DataElement" = 0
            AND Q."CQMId"       = vMeasureFormatted
            AND ROWNUM          = 1;

        EXCEPTION
          WHEN NO_DATA_FOUND THEN
            SELECT NVL(MAX(TRIM("UID")), 'NO_UID_FOUND') INTO vSpecificUID
            FROM QRDAVALSET Q
            WHERE 1=1
              AND TRIM(Q."Code") = TRIM(I."Diagnosis")
              AND Q."DataElement" = 0
              AND ROWNUM          = 1;

          WHEN OTHERS THEN
            vSpecificId := 'UNK';
        END;

        -- write out diagnosis entry
        dbms_lob.append(vBodyFile, Tab000000005 || '<entry>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000006 || '<observation classCode=OBS moodCode=EVN>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<!--  Problem observation template -->' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.22.4.4"/>' || CHR(10));

        IF I."Status" = 0 THEN
          -- use Diagnosis: Active template
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<!--  Diagnosis active template -->' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.24.3.11"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<id root="1.3.6.1.4.1.115" extension="' || TRIM(I."Extension") || '"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<code code="282291009" displayName="Diagnosis" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED-CT"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<text>Diagnosis, Active: ' || TRIM(I."DiagText") || '</text>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<statusCode code=completed/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<effectiveTime>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<!-- Attribute: admission datetime -->' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<low value="' || TO_CHAR(NVL(I."OnsetDate", I."AddDateTime"),'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<!-- Attribute: discharge datetime -->' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<high nullFlavor=UNK/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '</effectiveTime>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<value code="' || TRIM(I."Diagnosis") || '" codeSystem="' || TRIM(vCodeSystem) || '" xsi:type=CD sdtc:valueSet="' || TRIM(vSpecificUID) || '">' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<originalText>Diagnosis, Active: ' || TRIM(I."DiagText") || '</originalText>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '</value>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<entryRelationship typeCode=REFR>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<observation classCode=OBS moodCode=EVN>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000000000009 || '<!-- Problem Status (consolidation) template -->' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000000000009 || '<templateId root="2.16.840.1.113883.10.20.22.4.6"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000000000009 || '<!-- Problem Status, Active template -->' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000000000009 || '<templateId root="2.16.840.1.113883.10.20.24.3.94"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000000000009 || '<id root="2.16.840.1.113883.3.1496"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000000000009 || '<code code="33999-4" codeSystem="2.16.840.1.113883.6.1" codeSystemName=LOINC displayName="Status" />' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000000000009 || '<statusCode code=completed/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000000000009 || '<value xsi:type=CD code="55561003" displayName="Active" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '</observation>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '</entryRelationship>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000006 || '</observation>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000005 || '</entry>' || CHR(10));

        ELSIF I."Status" = 1 THEN
          -- use Diagnosis: Inactive template
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<!--  Diagnosis inactive template -->' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.24.3.13"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<id root="1.3.6.1.4.1.115" extension="' || TRIM(I."Extension") || '"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<code code="282291009" displayName="Diagnosis" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED-CT"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<text>Diagnosis, Inactive: ' || TRIM(I."DiagText") || '</text>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<statusCode code=completed/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<effectiveTime>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<low value="' || TO_CHAR(NVL(I."OnsetDate", I."AddDateTime"),'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<high value="' || TO_CHAR(NVL(I."OnsetDate", I."AddDateTime"),'YYYYMMDDHH24MISS') || '"/>' || CHR(10)); --assume that the latest edit is the one that made it inactive
          dbms_lob.append(vBodyFile, Tab0000000000007 || '</effectiveTime>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<value code="' || TRIM(I."Diagnosis") || '" codeSystem="' || TRIM(vCodeSystem) || '" xsi:type=CD sdtc:valueSet="' || TRIM(vSpecificUID) || '">' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<originalText>Diagnosis, Inactive: ' || TRIM(I."DiagText") || '</originalText>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '</value>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<entryRelationship typeCode=REFR>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<observation classCode=OBS moodCode=EVN>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000000000009 || '<!-- Problem Status (consolidation) template -->' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000000000009 || '<templateId root="2.16.840.1.113883.10.20.22.4.6"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000000000009 || '<!-- Problem Status, Inactive template -->' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000000000009 || '<templateId root="2.16.840.1.113883.10.20.24.3.95"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000000000009 || '<id root="2.16.840.1.113883.3.1496"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000000000009 || '<code code="33999-4" codeSystem="2.16.840.1.113883.6.1" codeSystemName=LOINC displayName="Status" />' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000000000009 || '<statusCode code=completed/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000000000009 || '<value xsi:type=CD code="73425007" displayName="Inactive" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '</observation>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '</entryRelationship>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000006 || '</observation>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000005 || '</entry>' || CHR(10));

        ELSIF I."Status" = 2 THEN
          -- use Diagnosis: Resolved template
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<!--  Diagnosis resolved template -->' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.24.3.14"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<id root="1.3.6.1.4.1.115" extension="' || TRIM(I."Extension") || '"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<code code="282291009" displayName="Diagnosis" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED-CT"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<text>Diagnosis, Resolved: ' || TRIM(I."DiagText") || '</text>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<statusCode code=completed/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<effectiveTime>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<low value="' || TO_CHAR(NVL(I."OnsetDate", I."AddDateTime"),'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<high value="' || TO_CHAR(NVL(I."OnsetDate", I."AddDateTime"),'YYYYMMDDHH24MISS') || '"/>' || CHR(10)); -- assume that the latest edit is the one that made it resolved
          dbms_lob.append(vBodyFile, Tab0000000000007 || '</effectiveTime>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<value code="' || TRIM(I."Diagnosis") || '" codeSystem="' || TRIM(vCodeSystem) || '" xsi:type=CD sdtc:valueSet="' || TRIM(vSpecificUID) || '">' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<originalText>Diagnosis, Rsolved: ' || TRIM(I."DiagText") || '</originalText>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '</value>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<entryRelationship typeCode=REFR>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<observation classCode=OBS moodCode=EVN>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000000000009 || '<!-- Problem Status (consolidation) template -->' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000000000009 || '<templateId root="2.16.840.1.113883.10.20.22.4.6"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000000000009 || '<!-- Problem Status, Resolved template -->' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000000000009 || '<templateId root="2.16.840.1.113883.10.20.24.3.96"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000000000009 || '<id root="2.16.840.1.113883.3.1496"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000000000009 || '<code code="33999-4" codeSystem="2.16.840.1.113883.6.1" codeSystemName=LOINC displayName="Status" />' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000000000009 || '<statusCode code=completed/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000000000009 || '<value xsi:type=CD code="413322009" displayName="Resolved" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '</observation>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '</entryRelationship>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000006 || '</observation>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000005 || '</entry>' || CHR(10));
        END IF;
      END LOOP;


      -- Order 4 - Procedures (EXTRA NEEDED FOR SOME REASON???)
      FOR I IN EncounterInstances LOOP
        vSpecificUID := '';
        vCodeSystem := vCS_SNOMED;

        IF TRIM(I."Procedure") IN ('99202', '99381') THEN
          dbms_lob.append(vBodyFile, Tab000000005 || '<entry>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000006 || '<encounter classCode=ENC moodCode=EVN>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<!--  Encounter activities template -->' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.22.4.49"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<!-- Encounter performed template -->' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.24.3.23"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<id root="1.3.6.1.4.1.115" extension="' || I."Extension" || '"/>' || CHR(10));

          IF TRIM(vMeasureFormatted) = '147' THEN
            dbms_lob.append(vBodyFile, Tab0000000000007 || '<code code="185349003" codeSystem="' || TRIM(vCodeSystem) || '" sdtc:valueSet="2.16.840.1.113883.3.526.3.1012">' || CHR(10));
          ELSIF TRIM(vMeasureFormatted) IN ('74','155') THEN
            dbms_lob.append(vBodyFile, Tab0000000000007 || '<code code="185349003" codeSystem="' || TRIM(vCodeSystem) || '" sdtc:valueSet="2.16.840.1.113883.3.464.1003.101.12.1048">' || CHR(10));
          ELSE
            dbms_lob.append(vBodyFile, Tab0000000000007 || '<code code="185349003" codeSystem="' || TRIM(vCodeSystem) || '" sdtc:valueSet="?????">' || CHR(10));
          END IF;

          dbms_lob.append(vBodyFile, Tab000000000000008 || '<originalText>Encounter, Performed: Office Visit</originalText>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '</code>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<text>Encounter, Performed: Office Visit</text>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<statusCode code=completed/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<effectiveTime>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<!-- We try to look for the admit/discharge times on the encounter if they are' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '     there. If not, we fall back to the typical start/end date. -->' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<low value="' || TO_CHAR(I."Date",'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<high value="' || TO_CHAR(I."Date",'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '</effectiveTime>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000006 || '</encounter>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000005 || '</entry>' || CHR(10));
        END IF;

      END LOOP;


      FOR I IN EncounterInstances LOOP
        vSpecificUID := '';

        IF I."Type" = 'Dental' THEN
          vCodeSystem := vCS_ADA;
        ELSIF I."Type" = 'Medical' THEN
          vCodeSystem := vCS_CPT4;
        ELSE
          vCodeSystem := ' ';
        END IF;

        -- get the UID for the procedure using the mapping table
        BEGIN
          IF I."Type" = 'Dental' THEN
            SELECT TRIM("UID") INTO vSpecificUID
            FROM QRDAVALSET Q
            WHERE 1=1
              AND TRIM(Q."Code")  = 'D' || TRIM(I."Procedure")
              AND Q."DataElement" = 3
              AND Q."CQMId"       = vMeasureFormatted
              AND ROWNUM          = 1;
          ELSIF I."Type" = 'Medical' THEN
            SELECT TRIM("UID") INTO vSpecificUID
              FROM QRDAVALSET Q
              WHERE 1=1
                AND TRIM(Q."Code")  = 'M' || TRIM(I."Procedure")
                AND Q."DataElement" = 3
                AND Q."CQMId"       = vMeasureFormatted
                AND ROWNUM          = 1;
          END IF;

        EXCEPTION WHEN NO_DATA_FOUND THEN
          IF I."Type" = 'Dental' THEN
            SELECT NVL(MAX(TRIM("UID")), 'NO_UID_FOUND') INTO vSpecificUID
            FROM QRDAVALSET Q
            WHERE 1=1
              AND TRIM(Q."Code")  = 'D' || TRIM(I."Procedure")
              AND Q."DataElement" = 3
              AND ROWNUM          = 1;
          ELSIF I."Type" = 'Medical' THEN
            SELECT NVL(MAX(TRIM("UID")), 'NO_UID_FOUND') INTO vSpecificUID
              FROM QRDAVALSET Q
              WHERE 1=1
                AND TRIM(Q."Code")  = 'M' || TRIM(I."Procedure")
                AND Q."DataElement" = 3
                AND ROWNUM          = 1;
          END IF;

        WHEN OTHERS THEN
          vSpecificId := 'UNK';
        END;


        IF vSpecificUID IN ('2.16.840.1.113883.3.464.1003.101.12.1001', '2.16.840.1.113883.3.464.1003.101.12.1022') THEN
          dbms_lob.append(vBodyFile, Tab000000005 || '<entry>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000006 || '<encounter classCode=ENC moodCode=EVN>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<!--  Encounter activities template -->' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.22.4.49"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<!-- Encounter performed template -->' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.24.3.23"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<id root="1.3.6.1.4.1.115" extension="' || I."Extension" || '"/>' || CHR(10));

          IF TRIM(vMeasureFormatted) IN ('74','147','155') THEN
            dbms_lob.append(vBodyFile, Tab0000000000007 || '<code code="' || TRIM(I."Procedure") || '" codeSystem="' || TRIM(vCodeSystem) || '" sdtc:valueSet="2.16.840.1.113883.3.526.3.1252">' || CHR(10));
          ELSIF TRIM(vMeasureFormatted) = '69' THEN
            dbms_lob.append(vBodyFile, Tab0000000000007 || '<code code="' || TRIM(I."Procedure") || '" codeSystem="' || TRIM(vCodeSystem) || '" sdtc:valueSet="2.16.840.1.113883.3.600.1.1751">' || CHR(10));
          ELSE
            dbms_lob.append(vBodyFile, Tab0000000000007 || '<code code="' || TRIM(I."Procedure") || '" codeSystem="' || TRIM(vCodeSystem) || '" sdtc:valueSet="2.16.840.1.113883.3.600.1.1834">' || CHR(10));
          END IF;

          dbms_lob.append(vBodyFile, Tab000000000000008 || '<originalText>Encounter, Performed: Office Visit</originalText>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '</code>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<text>Encounter, Performed: Office Visit</text>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<statusCode code=completed/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<effectiveTime>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<!-- We try to look for the admit/discharge times on the encounter if they are' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '     there. If not, we fall back to the typical start/end date. -->' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<low value="' || TO_CHAR(I."Date",'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<high value="' || TO_CHAR(I."Date",'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '</effectiveTime>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000006 || '</encounter>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000005 || '</entry>' || CHR(10));
        END IF;


      END LOOP;


      FOR I IN ProcedureInstances LOOP
        vSpecificUID := '';

        -- get codesystem based on the procedure code
        IF I."Type" = 'Dental' THEN
          vCodeSystem := vCS_ADA;
        ELSIF I."Type" = 'Medical' THEN
          vCodeSystem := vCS_CPT4;
        ELSE
          vCodeSystem := ' ';
        END IF;

        -- get the UID for the procedure using the mapping table
        BEGIN
          SELECT TRIM("UID") INTO vSpecificUID
          FROM QRDAVALSET Q
          WHERE 1=1
            AND TRIM(Q."Code") = TRIM(I."Procedure")
            AND Q."DataElement" = 1
            AND ROWNUM          = 1;

        EXCEPTION
          WHEN NO_DATA_FOUND THEN
            SELECT NVL(MAX(TRIM("UID")), 'NO_UID_FOUND') INTO vSpecificUID
            FROM QRDAVALSET Q
            WHERE 1=1
              AND TRIM(Q."Code") = TRIM(I."Procedure")
              AND Q."DataElement" = 1
              AND ROWNUM          = 1;

          WHEN OTHERS THEN
            vSpecificId := 'UNK';
        END;

        dbms_lob.append(vBodyFile, Tab000000005 || '<entry>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000006 || '<procedure classCode=PROC moodCode=EVN>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<!--  Procedure performed template -->' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.24.3.64"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<!-- Procedure Activity Procedure-->' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.22.4.14"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<id root="1.3.6.1.4.1.115" extension="' || TRIM(I."Extension") || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<code code="' || TRIM(I."Procedure") || '" codeSystem="' || TRIM(vCodeSystem) || '" sdtc:valueSet="' || TRIM(vSpecificUID) || '">' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<originalText>Procedure, Performed: ' || TRIM(I."Description") || '</originalText>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</code>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<text>Procedure, Performed: ' || TRIM(I."Description") || '</text>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<statusCode code=completed/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<effectiveTime>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<low value="' || TO_CHAR(I."Date",'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<high value="' || TO_CHAR(I."Date",'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</effectiveTime>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000006 || '</procedure>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000005 || '</entry>' || CHR(10));
      END LOOP;

      -- Special handling for CQMs #68, 125
      vCodeSystem := vCS_SNOMED;

      BEGIN
        -- CQM#68 - check the MUMDH form, MDH_MEDREV question
        SELECT PI."AnsListRefCode" , PI."EntryDateTime"
        INTO vPItemAnsListRefCode, vPItemDate
        FROM PITEM PI, FITEM FI
        WHERE 1=1
          AND PI."FItem" = FI."FItem"
          AND PI."FormCode" ='MUMDH'
          AND FI."Code" = 'MDH_MEDREV'
          AND PI."Patient" = vPatient
          AND PI."AuditNumber" = (SELECT MAX(p2n."AuditNumber")
                                  FROM PITEM p2n, FITEM f2n
                                  WHERE 1=1
                                    AND p2n."FormCode" = PI."FormCode"
                                    AND p2n."FItem" = f2n."FItem"
                                    AND p2n."Patient" = PI."Patient"
                                    AND f2n."Code" = FI."Code"
                                    AND p2n."AppUser" != 0
                                    AND p2n."AppDate" IS NOT NULL
                                  GROUP BY f2n."Code"
                                 );

      EXCEPTION WHEN OTHERS THEN
        vPItemAnsListRefCode := NULL;
        vPItemDate := NULL;
      END;

      IF vPItemAnsListRefCode IS NOT NULL THEN
        IF vPItemAnsListRefCode = 'MEDREV_DOC' THEN
          vSpecificUID := '2.16.840.1.113883.3.600.1.462';

          dbms_lob.append(vBodyFile, Tab000000005 || '<entry>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000006 || '<procedure classCode=PROC moodCode=EVN>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<!--  Procedure performed template -->' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.24.3.64"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<!-- Procedure Activity Procedure-->' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.22.4.14"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<id root="1.3.6.1.4.1.115" extension=DOC/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<code code="428191000124101" codeSystem="' || TRIM(vCodeSystem) || '" sdtc:valueSet="' || TRIM(vSpecificUID) || '">' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<originalText>Procedure, Performed: Current Medications Documented</originalText>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '</code>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<text>Procedure, Performed: Current Medications Documented</text>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<statusCode code=completed/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<effectiveTime>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<low value="' || TO_CHAR(vPItemDate,'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<high value="' || TO_CHAR(vPItemDate,'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '</effectiveTime>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000006 || '</procedure>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000005 || '</entry>' || CHR(10));

        ELSIF vPItemAnsListRefCode = 'MEDREV_R1' THEN
          vSpecificUID := '2.16.840.1.113883.3.600.1.462';

          dbms_lob.append(vBodyFile, Tab000000005 || '<entry>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000006 || '<procedure classCode=PROC moodCode=EVN>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<!--  Procedure performed template -->' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.24.3.64"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<!-- Procedure Activity Procedure-->' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.22.4.14"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<id root="1.3.6.1.4.1.115" extension=R1/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<code code="407563006" codeSystem="' || TRIM(vCodeSystem) || '" sdtc:valueSet="' || TRIM(vSpecificUID) || '">' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<originalText>Procedure not performed: Current Medications Not Documented - Treatment not tolerated</originalText>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '</code>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<text>Procedure not performed: Current Medications Not Documented - Treatment not tolerated</text>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<statusCode code=completed/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<effectiveTime>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<low value="' || TO_CHAR(vPItemDate,'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<high value="' || TO_CHAR(vPItemDate,'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '</effectiveTime>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000006 || '</procedure>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000005 || '</entry>' || CHR(10));

        ELSIF vPItemAnsListRefCode = 'MEDREV_R2' THEN
          vSpecificUID := '2.16.840.1.113883.3.600.1.1502';

          dbms_lob.append(vBodyFile, Tab000000005 || '<entry>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000006 || '<procedure classCode=PROC moodCode=EVN>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<!--  Procedure performed template -->' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.24.3.64"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<!-- Procedure Activity Procedure-->' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.22.4.14"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<id root="1.3.6.1.4.1.115" extension=R2/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<code code="397745006" codeSystem="' || TRIM(vCodeSystem) || '" sdtc:valueSet="' || TRIM(vSpecificUID) || '">' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<originalText>Procedure not performed: Current Medications Not Documented - Medical Contraindication</originalText>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '</code>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<text>Procedure not performed: Current Medications Not Documented - Medical Contraindication</text>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<statusCode code=completed/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<effectiveTime>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<low value="' || TO_CHAR(vPItemDate,'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<high value="' || TO_CHAR(vPItemDate,'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '</effectiveTime>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000006 || '</procedure>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000005 || '</entry>' || CHR(10));

        ELSIF vPItemAnsListRefCode = 'MEDREV_R3' THEN
          vSpecificUID := '2.16.840.1.113883.3.600.1.1502';

          dbms_lob.append(vBodyFile, Tab000000005 || '<entry>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000006 || '<procedure classCode=PROC moodCode=EVN>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<!--  Procedure performed template -->' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.24.3.64"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<!-- Procedure Activity Procedure-->' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.22.4.14"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<id root="1.3.6.1.4.1.115" extension=R3/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<code code="183932001" codeSystem="' || TRIM(vCodeSystem) || '" sdtc:valueSet="' || TRIM(vSpecificUID) || '">' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<originalText>Procedure not performed: Current Medications Not Documented - Procedure Contraindicated</originalText>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '</code>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<text>Procedure not performed: Current Medications Not Documented - Procedure Contraindicated</text>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<statusCode code=completed/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '<effectiveTime>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<low value="' || TO_CHAR(vPItemDate,'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000000000008 || '<high value="' || TO_CHAR(vPItemDate,'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab0000000000007 || '</effectiveTime>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab00000000006 || '</procedure>' || CHR(10));
          dbms_lob.append(vBodyFile, Tab000000005 || '</entry>' || CHR(10));
        END IF;
      END IF;

      -- CQM#125, check the CANCER form, BREASTEX1/BREASTEX2 questions
      BEGIN
        -- BREASTEX1
        SELECT
          SUBSTR(PI."AnsListDesc", 1, INSTR(PI."AnsListDesc", ' - ')),
          SUBSTR(PI."AnsListDesc", INSTR(PI."AnsListDesc", ' - ')+3, LENGTH(PI."AnsListDesc"))
        INTO vSNOCode, vPItemAnsListDesc
        FROM PITEM PI, FITEM FI
        WHERE 1=1
          AND PI."FItem" = FI."FItem"
          AND PI."FormCode" ='CANCER'
          AND FI."Code" = 'BREASTEX1'
          AND PI."Patient" = vPatient
          AND PI."AuditNumber" = (SELECT MAX(p2n."AuditNumber")
                                  FROM PITEM p2n, FITEM f2n
                                  WHERE 1=1
                                    AND p2n."FormCode" = PI."FormCode"
                                    AND p2n."FItem" = f2n."FItem"
                                    AND p2n."Patient" = PI."Patient"
                                    AND f2n."Code" = FI."Code"
                                    AND p2n."AppUser" != 0
                                    AND p2n."AppDate" IS NOT NULL
                                  GROUP BY f2n."Code"
                                 );

        SELECT PI."AnsDate"
        INTO vPItemDate
        FROM PITEM PI, FITEM FI
        WHERE 1=1
          AND PI."FItem" = FI."FItem"
          AND PI."FormCode" ='CANCER'
          AND FI."Code" = 'BREASTEXD1'
          AND PI."Patient" = vPatient
          AND PI."AuditNumber" = (SELECT MAX(p2n."AuditNumber")
                                  FROM PITEM p2n, FITEM f2n
                                  WHERE 1=1
                                    AND p2n."FormCode" = PI."FormCode"
                                    AND p2n."FItem" = f2n."FItem"
                                    AND p2n."Patient" = PI."Patient"
                                    AND f2n."Code" = FI."Code"
                                    AND p2n."AppUser" != 0
                                    AND p2n."AppDate" IS NOT NULL
                                  GROUP BY f2n."Code"
                                 );

      EXCEPTION WHEN OTHERS THEN
        vSNOCode := NULL;
        vPItemAnsListDesc := NULL;
        vPItemDate := NULL;
      END;

      IF vSNOCode IS NOT NULL AND vPItemDate IS NOT NULL THEN

        -- get the UID for the procedure using the mapping table
        BEGIN
          SELECT TRIM("UID") INTO vSpecificUID
          FROM QRDAVALSET Q
          WHERE 1=1
            AND TRIM(Q."Code") = TRIM(vSNOCode)
            AND Q."DataElement" = 1
            AND ROWNUM          = 1;

        EXCEPTION WHEN OTHERS THEN
          vSpecificId := 'UNK';
        END;

        dbms_lob.append(vBodyFile, Tab000000005 || '<entry>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000006 || '<procedure classCode=PROC moodCode=EVN>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<!--  Procedure performed template -->' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.24.3.64"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<!-- Procedure Activity Procedure-->' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.22.4.14"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<id root="1.3.6.1.4.1.115" extension=R3/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<code code="183932001" codeSystem="' || TRIM(vCodeSystem) || '" sdtc:valueSet="' || TRIM(vSpecificUID) || '">' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<originalText>Procedure, Performed: ' || TRIM(vPItemAnsListDesc) || '</originalText>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</code>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<text>Procedure, Performed: ' || TRIM(vPItemAnsListDesc) || '</text>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<statusCode code=completed/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<effectiveTime>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<low value="' || TO_CHAR(vPItemDate,'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<high value="' || TO_CHAR(vPItemDate,'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</effectiveTime>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000006 || '</procedure>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000005 || '</entry>' || CHR(10));
      END IF;

      BEGIN
        -- BREASTEX2
        SELECT
          SUBSTR(PI."AnsListDesc", 1, INSTR(PI."AnsListDesc", ' - ')),
          SUBSTR(PI."AnsListDesc", INSTR(PI."AnsListDesc", ' - ')+3, LENGTH(PI."AnsListDesc"))
        INTO vSNOCode, vPItemAnsListDesc
        FROM PITEM PI, FITEM FI
        WHERE 1=1
          AND PI."FItem" = FI."FItem"
          AND PI."FormCode" ='CANCER'
          AND FI."Code" = 'BREASTEX2'
          AND PI."Patient" = vPatient
          AND PI."AuditNumber" = (SELECT MAX(p2n."AuditNumber")
                                  FROM PITEM p2n, FITEM f2n
                                  WHERE 1=1
                                    AND p2n."FormCode" = PI."FormCode"
                                    AND p2n."FItem" = f2n."FItem"
                                    AND p2n."Patient" = PI."Patient"
                                    AND f2n."Code" = FI."Code"
                                    AND p2n."AppUser" != 0
                                    AND p2n."AppDate" IS NOT NULL
                                  GROUP BY f2n."Code"
                                 );

        SELECT PI."AnsDate"
        INTO vPItemDate
        FROM PITEM PI, FITEM FI
        WHERE 1=1
          AND PI."FItem" = FI."FItem"
          AND PI."FormCode" ='CANCER'
          AND FI."Code" = 'BREASTEXD2'
          AND PI."Patient" = vPatient
          AND PI."AuditNumber" = (SELECT MAX(p2n."AuditNumber")
                                  FROM PITEM p2n, FITEM f2n
                                  WHERE 1=1
                                    AND p2n."FormCode" = PI."FormCode"
                                    AND p2n."FItem" = f2n."FItem"
                                    AND p2n."Patient" = PI."Patient"
                                    AND f2n."Code" = FI."Code"
                                    AND p2n."AppUser" != 0
                                    AND p2n."AppDate" IS NOT NULL
                                  GROUP BY f2n."Code"
                                 );

      EXCEPTION WHEN OTHERS THEN
        vSNOCode := NULL;
        vPItemAnsListDesc := NULL;
        vPItemDate := NULL;
      END;

      IF vSNOCode IS NOT NULL AND vPItemDate IS NOT NULL THEN

        -- get the UID for the procedure using the mapping table
        BEGIN
          SELECT TRIM("UID") INTO vSpecificUID
          FROM QRDAVALSET Q
          WHERE 1=1
            AND TRIM(Q."Code") = TRIM(vSNOCode)
            AND Q."DataElement" = 1
            AND ROWNUM          = 1;

        EXCEPTION WHEN OTHERS THEN
          vSpecificId := 'UNK';
        END;

        dbms_lob.append(vBodyFile, Tab000000005 || '<entry>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000006 || '<procedure classCode=PROC moodCode=EVN>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<!--  Procedure performed template -->' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.24.3.64"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<!-- Procedure Activity Procedure-->' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.22.4.14"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<id root="1.3.6.1.4.1.115" extension=R3/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<code code="183932001" codeSystem="' || TRIM(vCodeSystem) || '" sdtc:valueSet="' || TRIM(vSpecificUID) || '">' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<originalText>Procedure, Performed: ' || TRIM(vPItemAnsListDesc) || '</originalText>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</code>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<text>Procedure, Performed: ' || TRIM(vPItemAnsListDesc) || '</text>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<statusCode code=completed/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<effectiveTime>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<low value="' || TO_CHAR(vPItemDate,'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<high value="' || TO_CHAR(vPItemDate,'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</effectiveTime>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000006 || '</procedure>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000005 || '</entry>' || CHR(10));
      END IF;


      -- Order 5 - Laboratory Tests (Pap tests, CQM#124)
      BEGIN
        SELECT
          TRIM(SUBSTR(PI."AnsListDesc", 1, INSTR(PI."AnsListDesc", ' - '))),
          TRIM(SUBSTR(PI."AnsListDesc", INSTR(PI."AnsListDesc", ' - ')+3, LENGTH(PI."AnsListDesc")))
        INTO vLOINC, vPItemAnsListDesc
        FROM PITEM PI, FITEM FI
        WHERE 1=1
          AND PI."FItem" = FI."FItem"
          AND PI."FormCode" ='CANCER'
          AND FI."Code" = 'CERVICPROC'
          AND PI."Patient" = vPatient
          AND PI."AuditNumber" = (SELECT MAX(p2n."AuditNumber")
                                  FROM PITEM p2n, FITEM f2n
                                  WHERE 1=1
                                    AND p2n."FormCode" = PI."FormCode"
                                    AND p2n."FItem" = f2n."FItem"
                                    AND p2n."Patient" = PI."Patient"
                                    AND f2n."Code" = FI."Code"
                                    AND p2n."AppUser" != 0
                                    AND p2n."AppDate" IS NOT NULL
                                  GROUP BY f2n."Code"
                                 );

        SELECT PI."AnsDate"
        INTO vPItemDate
        FROM PITEM PI, FITEM FI
        WHERE 1=1
          AND PI."FItem" = FI."FItem"
          AND PI."FormCode" ='CANCER'
          AND FI."Code" = 'CERVICDATE'
          AND PI."Patient" = vPatient
          AND PI."AuditNumber" = (SELECT MAX(p2n."AuditNumber")
                                  FROM PITEM p2n, FITEM f2n
                                  WHERE 1=1
                                    AND p2n."FormCode" = PI."FormCode"
                                    AND p2n."FItem" = f2n."FItem"
                                    AND p2n."Patient" = PI."Patient"
                                    AND f2n."Code" = FI."Code"
                                    AND p2n."AppUser" != 0
                                    AND p2n."AppDate" IS NOT NULL
                                  GROUP BY f2n."Code"
                                 );

      EXCEPTION WHEN OTHERS THEN
        vLOINC := NULL;
        vPItemAnsListDesc := NULL;
        vPItemDate := NULL;
      END;

      IF vLOINC IS NOT NULL AND vPItemDate IS NOT NULL THEN
        vSpecificUID := '';

        -- get the UID for the procedure using the mapping table
        BEGIN
          SELECT TRIM("UID") INTO vSpecificUID
          FROM QRDAVALSET Q
          WHERE 1=1
            AND TRIM(Q."Code") = TRIM(vLOINC)
            AND Q."DataElement" = 6
            AND ROWNUM          = 1;

        EXCEPTION WHEN OTHERS THEN
          vSpecificUID := 'UNK';
        END;

        vCodeSystem := vCS_LOINC;

        dbms_lob.append(vBodyFile, Tab000000005 || '<entry>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000006 || '<observation classCode=OBS moodCode=EVN>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<!--  Result Observation (consolidation) template  -->' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.22.4.2"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<!-- Laboratory Test, Result template -->' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.24.3.40"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<id root="1.3.6.1.4.1.115" extension=LAB1/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<code code="' || TRIM(vLOINC) || '" codeSystem="' || TRIM(vCodeSystem) || '" sdtc:valueSet="' || TRIM(vSpecificUID) || '">' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<originalText>Laboratory Test, Result: Pap Test: ' || vPItemAnsListDesc || '</originalText>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</code>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<text>Laboratory Test, Result: Pap Test: ' || vPItemAnsListDesc || '</text>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<statusCode code=completed/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<effectiveTime>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<low value="' || TO_CHAR(vPItemDate,'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<high value="' || TO_CHAR(vPItemDate,'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</effectiveTime>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<value code="' || TRIM(vLOINC) || '" codeSystem="' || TRIM(vCodeSystem) || '" xsi:type=CD>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<originalText>Laboratory Test, Result: Pap Test: ' || vPItemAnsListDesc || '</originalText>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</value>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000006 || '</observation>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000005 || '</entry>' || CHR(10));
      END IF;


      -- Order 6 - Interventions
      BEGIN
        SELECT
          TRIM(SUBSTR(PI."AnsListDesc", 1, INSTR(PI."AnsListDesc", ' - '))),
          TRIM(SUBSTR(PI."AnsListDesc", INSTR(PI."AnsListDesc", ' - ')+3, LENGTH(PI."AnsListDesc")))
        INTO vSNOCode, vPItemAnsListDesc
        FROM PITEM PI, FITEM FI
        WHERE 1=1
          AND PI."FItem" = FI."FItem"
          AND PI."FormCode" ='REFERR'
          AND FI."Code" = 'REFERR_RQ'
          AND PI."Patient" = vPatient
          AND PI."AuditNumber" = (SELECT MAX(p2n."AuditNumber")
                                  FROM PITEM p2n, FITEM f2n
                                  WHERE 1=1
                                    AND p2n."FormCode" = PI."FormCode"
                                    AND p2n."FItem" = f2n."FItem"
                                    AND p2n."Patient" = PI."Patient"
                                    AND f2n."Code" = FI."Code"
                                    AND p2n."AppUser" != 0
                                    AND p2n."AppDate" IS NOT NULL
                                  GROUP BY f2n."Code"
                                 );

        SELECT PI."AnsDate"
        INTO vPItemDate
        FROM PITEM PI, FITEM FI
        WHERE 1=1
          AND PI."FItem" = FI."FItem"
          AND PI."FormCode" ='REFERR'
          AND FI."Code" = 'REFERR_RQD'
          AND PI."Patient" = vPatient
          AND PI."AuditNumber" = (SELECT MAX(p2n."AuditNumber")
                                  FROM PITEM p2n, FITEM f2n
                                  WHERE 1=1
                                    AND p2n."FormCode" = PI."FormCode"
                                    AND p2n."FItem" = f2n."FItem"
                                    AND p2n."Patient" = PI."Patient"
                                    AND f2n."Code" = FI."Code"
                                    AND p2n."AppUser" != 0
                                    AND p2n."AppDate" IS NOT NULL
                                  GROUP BY f2n."Code"
                                 );

      EXCEPTION WHEN OTHERS THEN
        vSNOCode := NULL;
        vPItemAnsListDesc := NULL;
        vPItemDate := NULL;
      END;

      IF vSNOCode IS NOT NULL AND vPItemDate IS NOT NULL THEN
        vSpecificUID := '';

        -- get the UID for the procedure using the mapping table
        BEGIN
          SELECT TRIM("UID") INTO vSpecificUID
          FROM QRDAVALSET Q
          WHERE 1=1
            AND TRIM(Q."Code") = TRIM(vSNOCode)
            AND Q."DataElement" = 2
            AND ROWNUM          = 1;

        EXCEPTION WHEN OTHERS THEN
          vSpecificUID := 'UNK';
        END;

        vCodeSystem := vCS_SNOMED;

        dbms_lob.append(vBodyFile, Tab000000005 || '<entry>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000006 || '<act classCode=ACT moodCode=EVN>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<!-- Consolidation CDA: Procedure Activity Act template -->' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.22.4.12"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.24.3.32"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<id root="1.3.6.1.4.1.115" extension=REF1/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<code code="' || TRIM(vSNOCode) || '" codeSystem="' || TRIM(vCodeSystem) || '" sdtc:valueSet="' || TRIM(vSpecificUID) || '">' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<originalText>Intervention, Performed: Referral: ' || vPItemAnsListDesc || '</originalText>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</code>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<statusCode code=completed/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<effectiveTime>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<low value="' || TO_CHAR(vPItemDate,'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<high value="' || TO_CHAR(vPItemDate,'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</effectiveTime>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000006 || '</act>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000005 || '</entry>' || CHR(10));

      END IF;

      FOR I IN InterventionInstances LOOP
        vSpecificUID := '';

        -- get codesystem based on the procedure code
        IF I."Type" = 'Dental' THEN
          vCodeSystem := vCS_ADA;
        ELSIF I."Type" = 'Medical' THEN
          vCodeSystem := vCS_CPT4;
        ELSE
          vCodeSystem := ' ';
        END IF;

        -- get the UID for the procedure using the mapping table
        BEGIN
          SELECT TRIM("UID") INTO vSpecificUID
          FROM QRDAVALSET Q
          WHERE 1=1
            AND TRIM(Q."Code") = TRIM(I."Procedure")
            AND Q."DataElement" = 2
            AND Q."CQMId"       = vMeasureFormatted
            AND ROWNUM          = 1;

        EXCEPTION
          WHEN NO_DATA_FOUND THEN
            SELECT NVL(MAX(TRIM("UID")), 'NO_UID_FOUND') INTO vSpecificUID
            FROM QRDAVALSET Q
            WHERE 1=1
              AND TRIM(Q."Code") = TRIM(I."Procedure")
              AND Q."DataElement" = 2
              AND ROWNUM          = 1;

          WHEN OTHERS THEN
            vSpecificId := 'UNK';
        END;

        dbms_lob.append(vBodyFile, Tab000000005 || '<entry>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000006 || '<act classCode=ACT moodCode=EVN>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<!-- Consolidation CDA: Procedure Activity Act template -->' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.22.4.12"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.24.3.32"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<id root="1.3.6.1.4.1.115" extension="' || I."Extension" || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<code code="' || I."Procedure" || '" codeSystem="' || TRIM(vCodeSystem) || '" sdtc:valueSet="' || TRIM(vSpecificUID) || '">' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<originalText>Intervention, Performed: ' || HTF.ESCAPE_SC(TRIM(I."Description")) || '</originalText>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</code>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<statusCode code=completed/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<effectiveTime>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<low value="' || TO_CHAR(I."Date",'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<high value="' || TO_CHAR(I."Date",'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</effectiveTime>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000006 || '</act>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000005 || '</entry>' || CHR(10));
      END LOOP;


      -- Order 7 - Communication from Provider to Provider (#50, consultant reports)
      BEGIN
        SELECT
          SUBSTR(PI."AnsListDesc", 1, INSTR(PI."AnsListDesc", ' - ')),
          SUBSTR(PI."AnsListDesc", INSTR(PI."AnsListDesc", ' - ')+3, LENGTH(PI."AnsListDesc"))
        INTO vSNOCode, vPItemAnsListDesc
        FROM PITEM PI, FITEM FI
        WHERE 1=1
          AND PI."FItem" = FI."FItem"
          AND PI."FormCode" ='REFERR'
          AND FI."Code" = 'REFERR_RS'
          AND PI."Patient" = vPatient
          AND PI."AuditNumber" = (SELECT MAX(p2n."AuditNumber")
                                  FROM PITEM p2n, FITEM f2n
                                  WHERE 1=1
                                    AND p2n."FormCode" = PI."FormCode"
                                    AND p2n."FItem" = f2n."FItem"
                                    AND p2n."Patient" = PI."Patient"
                                    AND f2n."Code" = FI."Code"
                                    AND p2n."AppUser" != 0
                                    AND p2n."AppDate" IS NOT NULL
                                  GROUP BY f2n."Code"
                                 );

        SELECT PI."AnsDate"
        INTO vPItemDate
        FROM PITEM PI, FITEM FI
        WHERE 1=1
          AND PI."FItem" = FI."FItem"
          AND PI."FormCode" ='REFERR'
          AND FI."Code" = 'REFERR_RSD'
          AND PI."Patient" = vPatient
          AND PI."AuditNumber" = (SELECT MAX(p2n."AuditNumber")
                                  FROM PITEM p2n, FITEM f2n
                                  WHERE 1=1
                                    AND p2n."FormCode" = PI."FormCode"
                                    AND p2n."FItem" = f2n."FItem"
                                    AND p2n."Patient" = PI."Patient"
                                    AND f2n."Code" = FI."Code"
                                    AND p2n."AppUser" != 0
                                    AND p2n."AppDate" IS NOT NULL
                                  GROUP BY f2n."Code"
                                 );

      EXCEPTION WHEN OTHERS THEN
        vSNOCode := NULL;
        vPItemAnsListDesc := NULL;
        vPItemDate := NULL;
      END;

      IF vSNOCode IS NOT NULL AND vPItemDate IS NOT NULL THEN
        vSpecificUID := '';

        -- get the UID for the procedure using the mapping table
        BEGIN
          SELECT TRIM("UID") INTO vSpecificUID
          FROM QRDAVALSET Q
          WHERE 1=1
            AND TRIM(Q."Code") = TRIM(vSNOCode)
            AND Q."DataElement" = 7
            AND ROWNUM          = 1;

        EXCEPTION WHEN OTHERS THEN
          vSpecificUID := 'UNK';
        END;

        vCodeSystem := vCS_SNOMED;

        dbms_lob.append(vBodyFile, Tab000000005 || '<entry>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000006 || '<act classCode=ACT moodCode=EVN>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<!-- Communication from provider to provider -->' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.24.3.4"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<id root="1.3.6.1.4.1.115" extension=COM1/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<code code="' || TRIM(vSNOCode) || '" codeSystem="' || TRIM(vCodeSystem) || '" sdtc:valueSet="' || TRIM(vSpecificUID) || '">' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<originalText>Communication: From Provider to Provider: Consultant Report: ' || vPItemAnsListDesc || '</originalText>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</code>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<text>Communication: From Provider to Provider: Consultant Report: ' || vPItemAnsListDesc || '</text>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<statusCode code=completed/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<effectiveTime>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<low value="' || TO_CHAR(vPItemDate,'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<high value="' || TO_CHAR(vPItemDate,'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</effectiveTime>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<participant typeCode=AUT>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<participantRole classCode=ASSIGNED>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000000000009 || '<code code="158965000" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" displayName="Medical Practitioner"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '</participantRole>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</participant>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<participant typeCode=IRCP>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<participantRole classCode=ASSIGNED>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000000000009 || '<code code="158965000" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" displayName="Medical Practitioner"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '</participantRole>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</participant>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000006 || '</act>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000005 || '</entry>' || CHR(10));
      END IF;


      -- Order 8 - Diagnostic Study Results (Mammogram, CQM#125)
      BEGIN
        SELECT
          TRIM(SUBSTR(PI."AnsListDesc", 1, INSTR(PI."AnsListDesc", ' - '))),
          TRIM(SUBSTR(PI."AnsListDesc", INSTR(PI."AnsListDesc", ' - ')+3, LENGTH(PI."AnsListDesc")))
        INTO vLOINC, vPItemAnsListDesc
        FROM PITEM PI, FITEM FI
        WHERE 1=1
          AND PI."FItem" = FI."FItem"
          AND PI."FormCode" ='CANCER'
          AND FI."Code" = 'BREASTPROC'
          AND PI."Patient" = vPatient
          AND PI."AuditNumber" = (SELECT MAX(p2n."AuditNumber")
                                  FROM PITEM p2n, FITEM f2n
                                  WHERE 1=1
                                    AND p2n."FormCode" = PI."FormCode"
                                    AND p2n."FItem" = f2n."FItem"
                                    AND p2n."Patient" = PI."Patient"
                                    AND f2n."Code" = FI."Code"
                                    AND p2n."AppUser" != 0
                                    AND p2n."AppDate" IS NOT NULL
                                  GROUP BY f2n."Code"
                                 );

        SELECT PI."AnsDate"
        INTO vPItemDate
        FROM PITEM PI, FITEM FI
        WHERE 1=1
          AND PI."FItem" = FI."FItem"
          AND PI."FormCode" ='CANCER'
          AND FI."Code" = 'BREASTDATE'
          AND PI."Patient" = vPatient
          AND PI."AuditNumber" = (SELECT MAX(p2n."AuditNumber")
                                  FROM PITEM p2n, FITEM f2n
                                  WHERE 1=1
                                    AND p2n."FormCode" = PI."FormCode"
                                    AND p2n."FItem" = f2n."FItem"
                                    AND p2n."Patient" = PI."Patient"
                                    AND f2n."Code" = FI."Code"
                                    AND p2n."AppUser" != 0
                                    AND p2n."AppDate" IS NOT NULL
                                  GROUP BY f2n."Code"
                                 );

      EXCEPTION WHEN OTHERS THEN
        vLOINC := NULL;
        vPItemAnsListDesc := NULL;
        vPItemDate := NULL;
      END;

      IF vLOINC IS NOT NULL AND vPItemDate IS NOT NULL THEN
        vSpecificUID := '';

        -- get the UID for the procedure using the mapping table
        BEGIN
          SELECT TRIM("UID") INTO vSpecificUID
          FROM QRDAVALSET Q
          WHERE 1=1
            AND TRIM(Q."Code") = TRIM(vLOINC)
            AND Q."DataElement" = 4
            AND ROWNUM          = 1;

        EXCEPTION WHEN OTHERS THEN
          vSpecificUID := 'UNK';
        END;

        vCodeSystem := vCS_LOINC;

        dbms_lob.append(vBodyFile, Tab000000005 || '<entry>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000006 || '<observation classCode=OBS moodCode=EVN>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<!-- Consolidated Result Observation templateId (Implied Template) -->' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.22.4.2"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<!-- Diagnostic Study, Result template -->' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.24.3.20"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<id root="1.3.6.1.4.1.115" extension=DIAG1/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<code code="' || TRIM(vLOINC) || '" codeSystem="' || TRIM(vCodeSystem) || '" xsi:type=CD sdtc:valueSet="' || TRIM(vSpecificUID) || '">' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<originalText>Diagnostic Study, Result: Mammogram: ' || vPItemAnsListDesc || '</originalText>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</code>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<text>Diagnostic Study, Result: Mammogram: ' || vPItemAnsListDesc || '</text>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<statusCode code=completed/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<effectiveTime>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<low value="' || TO_CHAR(vPItemDate,'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<high value="' || TO_CHAR(vPItemDate,'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</effectiveTime>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<value code="' || TRIM(vLOINC) || '" codeSystem="' || TRIM(vCodeSystem) || '" xsi:type=CD>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<originalText>Diagnostic Study, Result: Mammogram: ' || vPItemAnsListDesc || '</originalText>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</value>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000006 || '</observation>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000005 || '</entry>' || CHR(10));
      END IF;


      -- Order 9 - Patient Characteristics
      FOR I IN PatientCharacteristics LOOP
        vSpecificUID := '';
        vCodeSystem := vCS_SNOMED;

        -- get the UID for the diagnosis using the mapping table
        BEGIN
          SELECT TRIM("UID") INTO vSpecificUID
          FROM QRDAVALSET Q
          WHERE 1=1
            AND TRIM(Q."Code") = TRIM(I."Diagnosis")
            AND Q."DataElement" = 8
            AND ROWNUM          = 1;

        EXCEPTION WHEN OTHERS THEN
          vSpecificId := 'UNK';
        END;

        -- Write out patient characteristics entry
        dbms_lob.append(vBodyFile, Tab000000005 || '<entry>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000006 || '<observation classCode=OBS moodCode=EVN>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.22.4.85"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<id root="1.3.6.1.4.1.115" extension="' || I."Diagnosis" || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<code code="assertion" displayName="Assertion" codeSystem="2.16.840.1.113883.5.4" codeSystemName="ActCode"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<statusCode code=completed/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<effectiveTime>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<low value="' || TO_CHAR(NVL(I."OnsetDate", I."AddDateTime"),'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<high nullFlavor=UNK/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</effectiveTime>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<value code="' || TRIM(I."Diagnosis") || '" codeSystem="' || TRIM(vCodeSystem) || '" xsi:type=CD sdtc:valueSet="' || TRIM(vSpecificUID) || '">' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<originalText>Patient Characteristic: ' || TRIM(I."DiagText") || '</originalText>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</value>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000006 || '</observation>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000005 || '</entry>' || CHR(10));
      END LOOP;


      -- Order 10 - Medication Orders

      -- Medication Administered (vaccines for CQM #127)
      FOR I IN MedsAdministered LOOP
        dbms_lob.append(vBodyFile, Tab000000005 || '<entry>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000006 || '<act classCode=ACT moodCode=EVN>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<!-- Medication, Administered template -->' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.24.3.42"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<id root="1.3.6.1.4.1.115" extension="' || I."Extension" || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<code code="416118004" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" displayName="Administration"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<statusCode code=completed/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<effectiveTime xsi:type=IVL_TS>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<low value="' || TO_CHAR(I."Date",'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<high value="' || TO_CHAR(I."Date",'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</effectiveTime>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<entryRelationship typeCode=COMP>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<substanceAdministration classCode=SBADM moodCode=EVN>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000000000009 || '<!-- Medication Activity (consolidation) template -->' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000000000009 || '<templateId root="2.16.840.1.113883.10.20.22.4.16"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000000000009 || '<id root="2.16.840.1.113883.3.1496"/>' || CHR(10));

        IF I."Vaccine" = '33' THEN
          dbms_lob.append(vBodyFile, Tab00000000000000009 || '<text>Medication, Administered: Pneumococcal Conjugate Vaccine: ' || TRIM(I."Description") || '</text>' || CHR(10));
        ELSIF I."Vaccine" = '111' THEN
          dbms_lob.append(vBodyFile, Tab00000000000000009 || '<text>Medication, Administered: Influenza Vaccine: ' || TRIM(I."Description") || '</text>' || CHR(10));
        ELSE
          dbms_lob.append(vBodyFile, Tab00000000000000009 || '<text>' || TRIM(I."Description") || '</text>' || CHR(10));
        END IF;

        dbms_lob.append(vBodyFile, Tab00000000000000009 || '<statusCode code=completed/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000000000009 || '<effectiveTime xsi:type=IVL_TS>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000000000010 || '<low value="' || TO_CHAR(I."Date",'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000000000010 || '<high value="' || TO_CHAR(I."Date",'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000000000009 || '</effectiveTime>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000000000009 || '<consumable>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000000000010 || '<manufacturedProduct classCode=MANU>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000000000011 || '<!-- Medication Information (consolidation) template -->' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.22.4.23"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000000000011 || '<id root="2.16.840.1.113883.3.1496"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000000000011 || '<manufacturedMaterial>' || CHR(10));

        IF I."Vaccine" = '33' THEN
          dbms_lob.append(vBodyFile, Tab00000000000000000000012 || '<code code="33" codeSystem="2.16.840.1.113883.12.292" sdtc:valueSet="2.16.840.1.113883.3.464.1003.110.12.1027">' || CHR(10));
        ELSIF I."Vaccine" = '111' THEN
          dbms_lob.append(vBodyFile, Tab00000000000000000000012 || '<code code="111" codeSystem="2.16.840.1.113883.12.292" sdtc:valueSet="2.16.840.1.113883.3.526.3.1254">' || CHR(10));
        ELSE
          dbms_lob.append(vBodyFile, Tab00000000000000000000012 || '<code code="???" codeSystem="???" sdtc:valueSet="???">' || CHR(10));
        END IF;

        IF I."Vaccine" = '33' THEN
          dbms_lob.append(vBodyFile, Tab0000000000000000000000013 || '<originalText>Medication, Administered: Pneumococcal Conjugate Vaccine: ' || TRIM(I."Description") || '</originalText>' || CHR(10));
        ELSIF I."Vaccine" = '111' THEN
          dbms_lob.append(vBodyFile, Tab0000000000000000000000013 || '<originalText>Medication, Administered: Influenza Vaccine: ' || TRIM(I."Description") || '</originalText>' || CHR(10));
        ELSE
          dbms_lob.append(vBodyFile, Tab0000000000000000000000013 || '<originalText>' || TRIM(I."Description") || '</originalText>' || CHR(10));
        END IF;

        dbms_lob.append(vBodyFile, Tab00000000000000000000012 || '</code>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000000000011 || '</manufacturedMaterial>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000000000010 || '</manufacturedProduct>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000000000009 || '</consumable>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '</substanceAdministration>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</entryRelationship>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000006 || '</act>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000005 || '</entry>' || CHR(10));
      END LOOP;

      FOR I IN MedicationOrders LOOP
        vSpecificUID := '';
        vCodeSystem := vCS_RXNORM;

        -- get the UID for the diagnosis using the mapping table
        BEGIN
          SELECT TRIM("UID") INTO vSpecificUID
          FROM QRDAVALSET Q
          WHERE 1=1
            AND TRIM(Q."Code") = TRIM(I."Medication")
            AND Q."DataElement" = 9
            AND ROWNUM          = 1;

        EXCEPTION WHEN OTHERS THEN
          vSpecificId := 'UNK';
        END;

        dbms_lob.append(vBodyFile, Tab000000005 || '<entry>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000006 || '<!--Medication Order -->' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000006 || '<substanceAdministration classCode=SBADM moodCode=RQO >' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.22.4.42"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<!-- Medication, Order template -->' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.24.3.47"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<id root="1.3.6.1.4.1.115" extension="' || I."Extension" || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<text>' || I."MedicationText" || '</text>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<statusCode code="new"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<effectiveTime xsi:type=IVL_TS>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<low value="' || TO_CHAR(I."StartDate",'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<high value="' || TO_CHAR(I."StartDate",'YYYYMMDDHH24MISS') || '"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</effectiveTime>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '<consumable>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '<manufacturedProduct classCode=MANU>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000000000009 || '<!-- Medication Information (consolidation) template -->' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000000000009 || '<templateId root="2.16.840.1.113883.10.20.22.4.23"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000000000009 || '<id root="2.16.840.1.113883.3.1496"/>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000000000009 || '<manufacturedMaterial>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000000000010 || '<code code="' || I."Medication" || '" codeSystem="' || vCodeSystem || '" sdtc:valueSet="' || TRIM(vSpecificUID) || '">' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000000000011 || '<originalText>' || I."MedicationText" || '</originalText>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000000000010 || '</code>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000000000009 || '</manufacturedMaterial>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000000000008 || '</manufacturedProduct>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab0000000000007 || '</consumable>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab00000000006 || '</substanceAdministration>' || CHR(10));
        dbms_lob.append(vBodyFile, Tab000000005 || '</entry>' || CHR(10));
      END LOOP;


      -- Patient characteristics payer
      dbms_lob.append(vFooterFile, Tab000000005 || '<entry>' || CHR(10));
      dbms_lob.append(vFooterFile, Tab00000000006 || '<!-- Patient Characteristic Payer -->' || CHR(10));
      dbms_lob.append(vFooterFile, Tab00000000006 || '<observation classCode=OBS moodCode=EVN>' || CHR(10));
      dbms_lob.append(vFooterFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.24.3.55"/>' || CHR(10));
      dbms_lob.append(vFooterFile, Tab0000000000007 || '<id root="1.3.6.1.4.1.115" extension="' || TRIM(vPatient) || '"/>' || CHR(10));
      dbms_lob.append(vFooterFile, Tab0000000000007 || '<code code="48768-6" codeSystemName=LOINC codeSystem="2.16.840.1.113883.6.1" displayName="Payment source"/> ' || CHR(10));
      dbms_lob.append(vFooterFile, Tab0000000000007 || '<statusCode code=completed/>' || CHR(10));
      dbms_lob.append(vFooterFile, Tab0000000000007 || '<value code="349" codeSystem="2.16.840.1.113883.3.221.5" xsi:type=CD sdtc:valueSet="2.16.840.1.114222.4.11.3591">' || CHR(10));
      dbms_lob.append(vFooterFile, Tab000000000000008 || '<originalText></originalText>' || CHR(10));
      dbms_lob.append(vFooterFile, Tab0000000000007 || '</value>' || CHR(10));
      dbms_lob.append(vFooterFile, Tab00000000006 || '</observation>' || CHR(10));
      dbms_lob.append(vFooterFile, Tab000000005 || '</entry>' || CHR(10));

      /***********************
      *      QRDA CLOSE      *
      ***********************/
      dbms_lob.append(vFooterFile, Tab0000004 || '</section>' || CHR(10));
      dbms_lob.append(vFooterFile, Tab00003 || '</component>' || CHR(10));
      dbms_lob.append(vFooterFile, Tab002 || '</structuredBody>' || CHR(10));
      dbms_lob.append(vFooterFile, Tab1 || '</component>' || CHR(10));
      dbms_lob.append(vFooterFile, '</ClinicalDocument>' || CHR(10));

    END IF;

  EXCEPTION WHEN OTHERS THEN
    vError := 99;
  END;

  -- Append all the sections together
  dbms_lob.append(vOutputFile, vTopHeaderFile);
  dbms_lob.append(vOutputFile, vMeasureFile);
  dbms_lob.append(vOutputFile, vOrganizerFile);
  dbms_lob.append(vOutputFile, vBottomHeaderFile);
  dbms_lob.append(vOutputFile, vBodyFile);
  dbms_lob.append(vOutputFile, vFooterFile);

END QRDA_Type1_XML;


/**
* Creates an QRDA Type III .XML file for the selected CQMs and returns it as a CLOB to MUD
* @return The error code indicated success or failurI. 0 = Success, anything else = Failure
*/
PROCEDURE qrda_type3_xml(IN vproducer character, IN vreportingyear numeric, IN vcqm22 numeric, IN vcqm50 numeric, IN vcqm68 numeric, IN vcqm69 numeric, IN vcqm74 numeric, IN vcqm75 numeric, IN vcqm124 numeric, IN vcqm125 numeric, IN vcqm127 numeric, IN vcqm130 numeric, IN vcqm138 numeric, IN vcqm147 numeric, IN vcqm155 numeric, IN vcqm156 numeric, IN vcqm165 numeric, OUT verror integer, OUT voutputfile clob) IS

	vOutputFileName VARCHAR2(255 ); -- name of the output file

	vMRYear MRYEAR%ROWTYPE;	--
  CURSOR CQMList
  IS
    SELECT 1 "Order", '22' CQM, vCQM22 "Enabled" FROM DUAL
    UNION
    SELECT 2 "Order", '50' CQM, vCQM50 "Enabled" FROM DUAL
    UNION
    SELECT 3 "Order", '68' CQM, vCQM68 "Enabled" FROM DUAL
    UNION
    SELECT 4 "Order", '69A' CQM, vCQM69 "Enabled" FROM DUAL
    UNION
    SELECT 5 "Order", '69B' CQM, vCQM69 "Enabled" FROM DUAL
    UNION
    SELECT 6 "Order", '74' CQM, vCQM74 "Enabled" FROM DUAL
    UNION
    SELECT 7 "Order", '75' CQM, vCQM75 "Enabled" FROM DUAL
    UNION
    SELECT 8 "Order", '124' CQM, vCQM124 "Enabled" FROM DUAL
    UNION
    SELECT 9 "Order", '125' CQM, vCQM125 "Enabled" FROM DUAL
    UNION
    SELECT 10 "Order", '127' CQM, vCQM127 "Enabled" FROM DUAL
    UNION
    SELECT 11 "Order", '130' CQM, vCQM130 "Enabled" FROM DUAL
    UNION
    SELECT 12 "Order", '138' CQM, vCQM138 "Enabled" FROM DUAL
    UNION
    SELECT 13 "Order", '147' CQM, vCQM147 "Enabled" FROM DUAL
    UNION
    SELECT 14 "Order", '155' CQM, vCQM155 "Enabled" FROM DUAL
    UNION
    SELECT 15 "Order", '156' CQM, vCQM156 "Enabled" FROM DUAL
    UNION
    SELECT 16 "Order", '165' CQM, vCQM165 "Enabled" FROM DUAL
    ORDER BY "Order";


  cWeakCursor cursor_pkg.weakcursor;

  CURSOR cPatients
  IS
    SELECT p."Patient", p."Last", p."First", p."Chart", 1 "Flag", 1 "Ex", 1 "Exc", 1 "Denom" FROM patient p WHERE 1 = 2;

  TYPE tPatients
  IS
    TABLE OF cPatients%rowtype INDEX BY PLS_INTEGER;

  lPatients tPatients;

  --Stores the CQM Version specific identifier
  vSpecificId      CHAR(36 );
  vSpecificNQF     CHAR(50 );
  vSpecificCQM     VARCHAR2(10 );
  vSpecificTitle   VARCHAR2(100 );
  vSpecificVersion VARCHAR2(10 );

  vSpecificIPPId      VARCHAR2(36 );
  vSpecificDENOMId    VARCHAR2(36 );
  vSpecificNUMERId    VARCHAR2(36 );
  vSpecificNUMER2Id   VARCHAR2(36 );
  vSpecificDENEXId    VARCHAR2(36 );
  vSpecificDENEXCEPId VARCHAR2(36 );

  vSpecificStratificationId VARCHAR2(36 );
  vStratCount NUMBER := 0;

  vUser USERS."User"%TYPE;
  vProvLast PRODUCER."LastName"%TYPE;
  vProvFirst PRODUCER."FirstName"%TYPE;

  vProvNPI CHAR(10 ) := 'X';
  vProvTIN CHAR(9 ) := 'X';

  -- AX-21340
  vReportingStartDate DATE;
  vReportingEndDate DATE;

  vReportTitle VARCHAR2(255 ) := '';

  Tab1 VARCHAR2(30 ) := '  ';
  Tab002 VARCHAR2(30 ) := '    ';
  Tab00003 VARCHAR2(30 ) := '      ';
  Tab0000004 VARCHAR2(30 ) := '        ';
  Tab000000005 VARCHAR2(30 ) := '          ';
  Tab00000000006 VARCHAR2(30 ) := '            ';
  Tab0000000000007 VARCHAR2(30 ) := '              ';
  Tab000000000000008 VARCHAR2(30 ) := '                ';
  Tab00000000000000009 VARCHAR2(30 ) := '                  ';
  Tab0000000000000000010 VARCHAR2(30 ) := '                    ';
  Tab000000000000000000011 VARCHAR2(30 ) := '                      ';
  Tab00000000000000000000012 VARCHAR2(30 ) := '                        ';
  Tab0000000000000000000000013 VARCHAR2(30 ) := '                          ';

  vPatientID  NUMBER := 0;

  vIPPCount   NUMBER := 0;
  vDENOMCount NUMBER := 0;
  vNUMERCount NUMBER := 0;

  vIPPPAYERCount    NUMBER := 0;
  vDenomPAYERCount  NUMBER := 0;

  --Exclusions
  vDenExCount NUMBER := 0;

  --Exceptions
  vDenExcepCount NUMBER := 0;

  vSex PATIENT."Sex"      %TYPE;
  vRace PTRACE."Race"     %TYPE;
  vEthnic ETHNIC."Ethnic" %TYPE;

  --PATIENT.Sex = 1
  vIPPSexM      NUMBER := 0;
  vDenomSexM    NUMBER := 0;
  vNumSexM      NUMBER := 0;
  vDenExSexM    NUMBER := 0;
  vDenExcepSexM NUMBER := 0;

  --PATIENT.Sex = 2
  vIPPSexF      NUMBER := 0;
  vDenomSexF    NUMBER := 0;
  vNumSexF      NUMBER := 0;
  vDenExSexF    NUMBER := 0;
  vDenExcepSexF NUMBER := 0;

  --PATIENT.Sex NOT IN (1, 2)
  vIPPSexUN      NUMBER := 0;
  vDenomSexUN    NUMBER := 0;
  vNumSexUN      NUMBER := 0;
  vDenExSexUN    NUMBER := 0;
  vDenExcepSexUN NUMBER := 0;

  --Unknown
  vIPPSexUNK      NUMBER := 0;
  vDenomSexUNK    NUMBER := 0;
  vNumSexUNK      NUMBER := 0;
  vDenExSexUNK    NUMBER := 0;
  vDenExcepSexUNK NUMBER := 0;


  --1002-5  American Indian or Alaska Native
  vIPPRaceNative      NUMBER := 0;
  vDenomRaceNative    NUMBER := 0;
  vNumRaceNative      NUMBER := 0;
  vDenExRaceNative    NUMBER := 0;
  vDenExcepRaceNative NUMBER := 0;

  --2028-9  Asian
  vIPPRaceAsian      NUMBER := 0;
  vDenomRaceAsian    NUMBER := 0;
  vNumRaceAsian      NUMBER := 0;
  vDenExRaceAsian    NUMBER := 0;
  vDenExcepRaceAsian NUMBER := 0;

  --2054-5  Black or African American
  vIPPRaceBlack      NUMBER := 0;
  vDenomRaceBlack    NUMBER := 0;
  vNumRaceBlack      NUMBER := 0;
  vDenExRaceBlack    NUMBER := 0;
  vDenExcepRaceBlack NUMBER := 0;

  --2076-8  Native Hawaiian or Other Pacific Islander
  vIPPRaceIsland      NUMBER := 0;
  vDenomRaceIsland    NUMBER := 0;
  vNumRaceIsland      NUMBER := 0;
  vDenExRaceIsland    NUMBER := 0;
  vDenExcepRaceIsland NUMBER := 0;

  --2106-3  White
  vIPPRaceWhite      NUMBER := 0;
  vDenomRaceWhite    NUMBER := 0;
  vNumRaceWhite      NUMBER := 0;
  vDenExRaceWhite    NUMBER := 0;
  vDenExcepRaceWhite NUMBER := 0;

  --2131-1  Other Race
  vIPPRaceOther      NUMBER := 0;
  vDenomRaceOther    NUMBER := 0;
  vNumRaceOther      NUMBER := 0;
  vDenExRaceOther    NUMBER := 0;
  vDenExcepRaceOther NUMBER := 0;

  --Unknown
  vIPPRaceUNK      NUMBER := 0;
  vDenomRaceUNK    NUMBER := 0;
  vNumRaceUNK      NUMBER := 0;
  vDenExRaceUNK    NUMBER := 0;
  vDenExcepRaceUNK NUMBER := 0;

  --2135-2  Hispanic or Latino
  vIPPEthnicHisp      NUMBER := 0;
  vDenomEthnicHisp    NUMBER := 0;
  vNumEthnicHisp      NUMBER := 0;
  vDenExEthnicHisp    NUMBER := 0;
  vDenExcepEthnicHisp NUMBER := 0;

  --2186-5  Not Hispanic or Latino
  vIPPEthnicNotHisp      NUMBER := 0;
  vDenomEthnicNotHisp    NUMBER := 0;
  vNumEthnicNotHisp      NUMBER := 0;
  vDenExEthnicNotHisp    NUMBER := 0;
  vDenExcepEthnicNotHisp NUMBER := 0;

  --Unknown
  vIPPEthnicUNK      NUMBER := 0;
  vDenomEthnicUNK    NUMBER := 0;
  vNumEthnicUNK      NUMBER := 0;
  vDenExEthnicUNK    NUMBER := 0;
  vDenExcepEthnicUNK NUMBER := 0;

  -- SF-00192541/AX-18965
  vStage mryear."Stage"%type := 3;
  vStage3OutputFile clob := '';

BEGIN

  -- Determine a 'unique' filename
  vOutputFileName := 'XML_QRDA_TYPE3_' || TO_CHAR(SYSDATE, 'MM-DD-YYYY_HH24MISS') || '.xml';

  vError := 0;

  --
  -- SF-00192541/AX-18965: perform procedure QRDA_Type3_Stage3_XML_P (assume it is always stage 3)
  --
  begin
    --
    -- determine if stage 3; if not, proceed with normal/original process
    --
    select 0
    into vError
    from
      mryear my,
      producer prod,
      users u
    where 1=1
    and u."Producer" = prod."Producer"
    and my."User" = u."User"
    and u."Deleted" = 0
    and prod."MUEligible" = 1
    and prod."Producer" = vProducer
    and my."Stage" = vStage                                                     -- works for stage 3 only
    and my."Year" = vReportingYear;

    --
    -- call QRDA_Type3_Stage3_XML_P
    --
    qrda_cfg_pkg.QRDA_Type3_Stage3_XML_P (vProducer,
                                          vReportingYear,
                                          vCQM22,
                                          vCQM68,
                                          vCQM74,
                                          vCQM75,
                                          vCQM127,
                                          vCQM138,
                                          vCQM147,
                                          vCQM156,
                                          vError,
                                          vStage3OutputFile);

    begin
      --
      -- open file for writing
      --
      DBMS_LOB_S.createtemporary (vOutputFile, TRUE);

      --
      -- append stage 3 output file
      --
      dbms_lob.append(vOutputFile, vStage3OutputFile);

    exception
      when others then
        vError := 1;

    end;

    --
    -- return to the calling function
    --
    return;

  exception
    when no_data_found then
      --
      -- proceed with original processing (before stage 3 changes)
      --
      null;

  end;
  --
  -- end: SF-00192541/AX-18965: perform procedure QRDA_Type3_Stage3_XML_P (assume it is always stage 3)
  --

	-- Open the file for writing
	BEGIN
      DBMS_LOB_S.createtemporary (vOutputFile, TRUE);
	EXCEPTION
      WHEN OTHERS THEN
		vError := 1;
	END;

  -- AX-21340 Grab the User ID
  BEGIN
    SELECT "User" INTO vUser FROM USERS WHERE TRIM("Producer") = vProducer;

  EXCEPTION WHEN NO_DATA_FOUND THEN
    vError := 2;
  END;

  -- AX-21340 Get Year 2 Dates
  BEGIN
    SELECT * INTO vMRYear FROM MRYEAR WHERE "User" = vUser AND "Year" = 2 AND ROWNUM = 1;		-- Only works for Year 2!!!

  EXCEPTION WHEN OTHERS THEN
    vError := 1;
  END;

  vReportingStartDate := TO_DATE(vMRYear."DateFrom", 'DD-MON-YYYY' || CHR(13) || CHR(10));		-- AX-21340
  vReportingEndDate := TO_DATE(vMRYear."DateTo", 'DD-MON-YYYY' || CHR(13) || CHR(10)); 			-- AX-21340

  -- Get provider's NPI (required) and TIN (if in use)
  BEGIN
    SELECT
      "LastName",
      "FirstName",
      NVL(SUBSTR("NPI",1,10), ' '),
      CASE "IsTIN"
        WHEN 0 THEN ' '
        WHEN 1 THEN SUBSTR("Specialist",1,9)
      END
    INTO vProvLast, vProvFirst, vProvNPI, vProvTIN
    FROM PRODUCER
    WHERE TRIM("Producer") = vProducer;

  EXCEPTION
    WHEN NO_DATA_FOUND THEN
      vError := 3;
    WHEN OTHERS THEN
      vProvLast := ' ';
      vProvFirst := ' ';
      vProvNPI := ' ';
      vProvTIN := ' ';
  END;


  IF vCQM22 = 1 AND vReportTitle IS NULL THEN
    vReportTitle := vReportTitle || 'CMS 22';
  ELSIF vCQM22 = 1 AND vReportTitle IS NOT NULL THEN
    vReportTitle := vReportTitle || ' and CMS 22';
  END IF;
  IF vCQM50 = 1 AND vReportTitle IS NULL THEN
    vReportTitle := vReportTitle || 'CMS 50';
  ELSIF vCQM50 = 1 AND vReportTitle IS NOT NULL THEN
    vReportTitle := vReportTitle || ' and CMS 50';
  END IF;
  IF vCQM68 = 1 AND vReportTitle IS NULL THEN
    vReportTitle := vReportTitle || 'CMS 68';
  ELSIF vCQM68 = 1 AND vReportTitle IS NOT NULL THEN
    vReportTitle := vReportTitle || ' and CMS 68';
  END IF;
  IF vCQM69 = 1 AND vReportTitle IS NULL THEN
    vReportTitle := vReportTitle || 'CMS 69';
  ELSIF vCQM69 = 1 AND vReportTitle IS NOT NULL THEN
    vReportTitle := vReportTitle || ' and CMS 69';
  END IF;
  IF vCQM74 = 1 AND vReportTitle IS NULL THEN
    vReportTitle := vReportTitle || 'CMS 74';
  ELSIF vCQM74 = 1 AND vReportTitle IS NOT NULL THEN
    vReportTitle := vReportTitle || ' and CMS 74';
  END IF;
  IF vCQM75 = 1 AND vReportTitle IS NULL THEN
    vReportTitle := vReportTitle || 'CMS 75';
  ELSIF vCQM75 = 1 AND vReportTitle IS NOT NULL THEN
    vReportTitle := vReportTitle || ' and CMS 75';
  END IF;
  IF vCQM124 = 1 AND vReportTitle IS NULL THEN
    vReportTitle := vReportTitle || 'CMS 124';
  ELSIF vCQM124 = 1 AND vReportTitle IS NOT NULL THEN
    vReportTitle := vReportTitle || ' and CMS 124';
  END IF;
  IF vCQM125 = 1 AND vReportTitle IS NULL THEN
    vReportTitle := vReportTitle || 'CMS 125';
  ELSIF vCQM125 = 1 AND vReportTitle IS NOT NULL THEN
    vReportTitle := vReportTitle || ' and CMS 125';
  END IF;
  IF vCQM127 = 1 AND vReportTitle IS NULL THEN
    vReportTitle := vReportTitle || 'CMS 127';
  ELSIF vCQM127 = 1 AND vReportTitle IS NOT NULL THEN
    vReportTitle := vReportTitle || ' and CMS 127';
  END IF;
  IF vCQM130 = 1 AND vReportTitle IS NULL THEN
    vReportTitle := vReportTitle || 'CMS 130';
  ELSIF vCQM130 = 1 AND vReportTitle IS NOT NULL THEN
    vReportTitle := vReportTitle || ' and CMS 130';
  END IF;
  IF vCQM138 = 1 AND vReportTitle IS NULL THEN
    vReportTitle := vReportTitle || 'CMS 138';
  ELSIF vCQM138 = 1 AND vReportTitle IS NOT NULL THEN
    vReportTitle := vReportTitle || ' and CMS 138';
  END IF;
  IF vCQM147 = 1 AND vReportTitle IS NULL THEN
    vReportTitle := vReportTitle || 'CMS 147';
  ELSIF vCQM147 = 1 AND vReportTitle IS NOT NULL THEN
    vReportTitle := vReportTitle || ' and CMS 147';
  END IF;
  IF vCQM155 = 1 AND vReportTitle IS NULL THEN
    vReportTitle := vReportTitle || 'CMS 165';
  ELSIF vCQM155 = 1 AND vReportTitle IS NOT NULL THEN
    vReportTitle := vReportTitle || ' and CMS 165';
  END IF;
  IF vCQM156 = 1 AND vReportTitle IS NULL THEN
    vReportTitle := vReportTitle || 'CMS 156';
  ELSIF vCQM156 = 1 AND vReportTitle IS NOT NULL THEN
    vReportTitle := vReportTitle || ' and CMS 156';
  END IF;
  IF vCQM165 = 1 AND vReportTitle IS NULL THEN
    vReportTitle := vReportTitle || 'CMS 165';
  ELSIF vCQM165 = 1 AND vReportTitle IS NOT NULL THEN
    vReportTitle := vReportTitle || ' and CMS 165';
  END IF;


  IF vError = 0 THEN

    BEGIN

      -- write XML header
      dbms_lob.append(vOutputFile, '<?xml version="1.0"?>' || CHR(13) || CHR(10));

      -- header elements
      dbms_lob.append(vOutputFile, '<ClinicalDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:hl7-org:v3 ../../CDASchema/CDA.xsd" xmlns="urn:hl7-org:v3" xmlns:cda="urn:hl7-org:v3">' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab1 || '<realmCode code=US />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab1 || '<typeId root="2.16.840.1.113883.1.3" extension=POCD_HD000040 />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab1 || '<templateId root="2.16.840.1.113883.10.20.27.1.1" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab1 || '<id root="90C1415D-B430-4BAB-BE4F-9876DAD0DF5B" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab1 || '<code codeSystem="2.16.840.1.113883.6.1" code="55184-6" codeSystemName=LOINC displayName="QRDA Category 3 Calculated Summary Report" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab1 || '<title>QRDA Category 3 Calculated Summary Report For ' || TRIM(vReportTitle) || '</title>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab1 || '<effectiveTime value="' || TO_CHAR(SYSDATE,'YYYYMMDD') || '" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab1 || '<confidentialityCode codeSystem="2.16.840.1.113883.5.25" code=N />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab1 || '<languageCode code="en-US" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab1 || '<versionNumber value="1" />' || CHR(13) || CHR(10));

      -- recordTarget sub-element
      dbms_lob.append(vOutputFile, Tab1 || '<recordTarget>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab002 || '<patientRole>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab00003 || '<id nullFlavor=NA />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab002 || '</patientRole>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab1 || '</recordTarget>' || CHR(13) || CHR(10));

      -- author sub-element
      dbms_lob.append(vOutputFile, Tab1 || '<author>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab002 || '<time value="' || TO_CHAR(SYSDATE,'YYYYMMDD') || '" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab002 || '<assignedAuthor>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab00003 || '<id root="2.16.840.1.113883.4.6" extension="' || TRIM(vProvNPI) || '" assigningAuthorityName=NPI />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab00003 || '<assignedPerson>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab0000004 || '<name>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab000000005 || '<given>' || TRIM(vProvFirst) || '</given>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab000000005 || '<family>' || TRIM(vProvLast) || '</family>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab000000005 || '<suffix />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab0000004 || '</name>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab00003 || '</assignedPerson>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab00003 || '<representedOrganization>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab0000004 || '<id root="2.16.840.1.113883.19.598" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab0000004 || '<name>Exan Software</name>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab00003 || '</representedOrganization>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab002 || '</assignedAuthor>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab1 || '</author>' || CHR(13) || CHR(10));

      -- custodian sub-element
      dbms_lob.append(vOutputFile, Tab1 || '<custodian>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab002 || '<assignedCustodian>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab00003 || '<representedCustodianOrganization>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab0000004 || '<id root="2.16.840.1.113883.19.5" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab000000005 || '<name>Exan</name>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab0000004 || '</representedCustodianOrganization>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab002 || '</assignedCustodian>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab1 || '</custodian>' || CHR(13) || CHR(10));

      -- legalAuthenticator sub-element
      dbms_lob.append(vOutputFile, Tab1 || '<legalAuthenticator>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab002 || '<time value="' || TO_CHAR(SYSDATE,'YYYYMMDD') || '" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab002 || '<signatureCode code=S />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab002 || '<assignedEntity>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab00003 || '<id root="113AAEBA-4456-49DB-B7B8-67C41472E812" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab00003 || '<representedOrganization>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab0000004 || '<id root="2.16.840.1.113883.19.5" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab0000004 || '<name>Exan</name>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab00003 || '</representedOrganization>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab002 || '</assignedEntity>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab1 || '</legalAuthenticator>' || CHR(13) || CHR(10));

      dbms_lob.append(vOutputFile, Tab1 || '<authorization>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab002 || '<consent>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab00003 || '<id root="9DE871F0-A890-4D5F-856C-62808F496470" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab00003 || '<code codeSystem="2.16.840.1.113883.6.96" code="425691002" codeSystemName="SNOMED-CT" displayName="Consent given for electronic record sharing" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab00003 || '<statusCode code=completed />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab002 || '</consent>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab1 || '</authorization>' || CHR(13) || CHR(10));


      -- component sub-element
      dbms_lob.append(vOutputFile, Tab1 || '<component>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab002 || '<structuredBody>' || CHR(13) || CHR(10));

      -- Reporting Parameters sub-element
      dbms_lob.append(vOutputFile, Tab00003 || '<component>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab0000004 || '<section>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab000000005 || '<templateId root="2.16.840.1.113883.10.20.17.2.1" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab000000005 || '<templateId root="2.16.840.1.113883.10.20.27.2.2" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab000000005 || '<code codeSystem="2.16.840.1.113883.6.1" code="55187-9" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab000000005 || '<title>Reporting Parameters</title>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab000000005 || '<text>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab00000000006 || '<list>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab0000000000007 || '<item>Reporting period ' || TO_CHAR(vReportingStartDate,'MON DD YYYY') || ' - ' || TO_CHAR(vReportingEndDate,'MON DD YYYY') || '</item>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab00000000006 || '</list>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab000000005 || '</text>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab000000005 || '<entry typeCode=DRIV>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab00000000006 || '<act classCode=ACT moodCode=EVN>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.17.3.8" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab0000000000007 || '<id root="6E892703-2700-40C7-8A6A-F6244B836A5A" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab0000000000007 || '<code codeSystem="2.16.840.1.113883.6.96" code="252116004" displayName="Observation Parameters" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab0000000000007 || '<effectiveTime>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab000000000000008 || '<low value="' || TO_CHAR(vReportingStartDate,'YYYYMMDD') || '" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab000000000000008 || '<high value="' || TO_CHAR(vReportingEndDate,'YYYYMMDD') || '" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab0000000000007 || '</effectiveTime>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab00000000006 || '</act>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab000000005 || '</entry>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab000000005 || '<entry>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab00000000006 || '<encounter classCode=ENC moodCode=EVN>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.27.3.11" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab0000000000007 || '<id root="BA41DD85-3C2E-4B9D-BB96-CAC4ACE1881D" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab0000000000007 || '<effectiveTime>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab000000000000008 || '<low value="' || TO_CHAR(vReportingStartDate,'YYYYMMDD') || '" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab0000000000007 || '</effectiveTime>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab00000000006 || '</encounter>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab000000005 || '</entry>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab000000005 || '<entry>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab00000000006 || '<encounter classCode=ENC moodCode=EVN>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.27.3.11" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab0000000000007 || '<id root="9B0643C3-7339-4701-BB10-00219E86EAF6" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab0000000000007 || '<effectiveTime>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab000000000000008 || '<high value="' || TO_CHAR(vReportingEndDate,'YYYYMMDD') || '" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab0000000000007 || '</effectiveTime>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab00000000006 || '</encounter>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab000000005 || '</entry>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab0000004 || '</section>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab00003 || '</component>' || CHR(13) || CHR(10));

      -- Measure section sub-element
      dbms_lob.append(vOutputFile, Tab00003 || '<component>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab0000004 || '<section>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab000000005 || '<templateId root="2.16.840.1.113883.10.20.17.2.2" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab000000005 || '<templateId root="2.16.840.1.113883.10.20.27.2.1" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab000000005 || '<code codeSystem="2.16.840.1.113883.6.1" code="55186-1" />' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab000000005 || '<title>Measure Section</title>' || CHR(13) || CHR(10));
      dbms_lob.append(vOutputFile, Tab000000005 || '<text></text>' || CHR(13) || CHR(10));

    EXCEPTION WHEN OTHERS THEN
      vError := 4;
    END;

    -- Create an entry for each CQM
    BEGIN
      FOR c IN CQMList LOOP

        -- Need to reset for each CQM
        vPatientID := 0;

        -- Only do if CQM has been selected
        IF c."Enabled" = 1 THEN

          vIPPCount := 0;
          vDENOMCount := 0;
          vNUMERCount := 0;

          vIPPPAYERCount := 0;
          vDenomPAYERCount := 0;

          --Exclusions
          vDenExCount := 0;

          --Exceptions
          vDenExcepCount := 0;

          vSex := 0;
          vRace := ' ';
          vEthnic := ' ';


          ----------------
          --     SEX    --
          ----------------

          --PATIENT.Sex = 1
          vIPPSexM      := 0;
          vDenomSexM    := 0;
          vNumSexM      := 0;
          vDenExSexM    := 0;
          vDenExcepSexM := 0;

          --PATIENT.Sex = 2
          vIPPSexF      := 0;
          vDenomSexF    := 0;
          vNumSexF      := 0;
          vDenExSexF    := 0;
          vDenExcepSexF := 0;

          --PATIENT.Sex NOT IN (1, 2)
          vIPPSexUN      := 0;
          vDenomSexUN    := 0;
          vNumSexUN      := 0;
          vDenExSexUN    := 0;
          vDenExcepSexUN := 0;

          --Unknown
          vIPPSexUNK      := 0;
          vDenomSexUNK    := 0;
          vNumSexUNK      := 0;
          vDenExSexUNK    := 0;
          vDenExcepSexUNK := 0;


          ----------------
          --    RACE    --
          ----------------

          --1002-5  American Indian or Alaska Native
          vIPPRaceNative      := 0;
          vDenomRaceNative    := 0;
          vNumRaceNative      := 0;
          vDenExRaceNative    := 0;
          vDenExcepRaceNative := 0;

          --2028-9  Asian
          vIPPRaceAsian      := 0;
          vDenomRaceAsian    := 0;
          vNumRaceAsian      := 0;
          vDenExRaceAsian    := 0;
          vDenExcepRaceAsian := 0;

          --2054-5  Black or African American
          vIPPRaceBlack      := 0;
          vDenomRaceBlack    := 0;
          vNumRaceBlack      := 0;
          vDenExRaceBlack    := 0;
          vDenExcepRaceBlack := 0;

          --2076-8  Native Hawaiian or Other Pacific Islander
          vIPPRaceIsland      := 0;
          vDenomRaceIsland    := 0;
          vNumRaceIsland      := 0;
          vDenExRaceIsland    := 0;
          vDenExcepRaceIsland := 0;

          --2106-3  White
          vIPPRaceWhite      := 0;
          vDenomRaceWhite    := 0;
          vNumRaceWhite      := 0;
          vDenExRaceWhite    := 0;
          vDenExcepRaceWhite := 0;

          --2131-1  Other Race
          vIPPRaceOther      := 0;
          vDenomRaceOther    := 0;
          vNumRaceOther      := 0;
          vDenExRaceOther    := 0;
          vDenExcepRaceOther := 0;

          --Unknown
          vIPPRaceUNK      := 0;
          vDenomRaceUNK    := 0;
          vNumRaceUNK      := 0;
          vDenExRaceUNK    := 0;
          vDenExcepRaceUNK := 0;


          ----------------
          -- ETHINICITY --
          ----------------

          --2135-2  Hispanic or Latino
          vIPPEthnicHisp      := 0;
          vDenomEthnicHisp    := 0;
          vNumEthnicHisp      := 0;
          vDenExEthnicHisp    := 0;
          vDenExcepEthnicHisp := 0;

          --2186-5  Not Hispanic or Latino
          vIPPEthnicNotHisp      := 0;
          vDenomEthnicNotHisp    := 0;
          vNumEthnicNotHisp      := 0;
          vDenExEthnicNotHisp    := 0;
          vDenExcepEthnicNotHisp := 0;

          --Unknown
          vIPPEthnicUNK      := 0;
          vDenomEthnicUNK    := 0;
          vNumEthnicUNK      := 0;
          vDenExEthnicUNK    := 0;
          vDenExcepEthnicUNK := 0;


          ----------------
          --  MEASURES  --
          ----------------

          vSpecificId      := '';
          vSpecificNQF     := '';
          vSpecificCQM     := '';
          vSpecificTitle   := '';
          vSpecificVersion := '';

          vSpecificIPPId      := '';
          vSpecificDENOMId    := '';
          vSpecificNUMERId    := '';
          vSpecificDENEXId    := '';
          vSpecificDENEXCEPId := '';

          vSpecificStratificationId := '';
          vStratCount := 0;


          IF c.CQM = '22' THEN
            MU_CQM_PKG.CQM22_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);
            vSpecificId := '40280381-3E93-D1AF-013E-AF14FC6B5642';
            vSpecificNQF := 'BPScreen';
            vSpecificCQM := '22';
            vSpecificTitle := 'Preventive Care and Screening: Screening for High Blood Pressure and Follow-Up Documented';
            vSpecificVersion := '2';

            vSpecificIPPId := 'F18ED0C0-8B7F-4FB4-A8E4-5068B9353F6F';
            vSpecificDENOMId := '7F332A7D-B855-49F6-8ADF-7C61AEED957F';
            vSpecificNUMERId := '24935A6E-8A83-4E24-B274-A60BFC5BB6F3';
            vSpecificDENEXId := '24604384-B795-4821-BB58-4B14BFFFBDD9';
            vSpecificDENEXCEPId := 'CB969240-1D2F-4A1E-9C89-62296DB79035';
          ELSIF c.CQM = '50' THEN
            MU_CQM_PKG.CQM50_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);
            vSpecificId := '40280381-3D61-56A7-013E-7AA509DE6258';
            vSpecificNQF := 'ClosingReferralLoop';
            vSpecificCQM := '50';
            vSpecificTitle := 'Closing the referral loop - Receipt of Specialist Report';
            vSpecificVersion := '2';

            vSpecificIPPId := '6832D937-1A47-4C0B-A9D6-B29B66E92AA4';
            vSpecificDENOMId := '6BDAD3A7-4EEB-4BAC-A2D6-DE51AA4DE608';
            vSpecificNUMERId := '8A300BD2-3DB8-458D-B142-FE59B4711CC2';
            vSpecificDENEXId := '';
            vSpecificDENEXCEPId := '';
          ELSIF c.CQM = '68' THEN
            MU_CQM_PKG.CQM68_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);
            vSpecificId := '40280381-3E93-D1AF-013E-A36090B72CC8';
            vSpecificNQF := '419';
            vSpecificCQM := '68';
            vSpecificTitle := 'Documentation of Current Medications in the Medical Record';
            vSpecificVersion := '3';

            vSpecificIPPId := 'FED9910E-07EF-40E1-B8F0-8B4331CBE8F0';
            vSpecificDENOMId := 'E7F35F6D-6963-48F5-8F73-8ECE4B7F8F50';
            vSpecificNUMERId := 'C54E0789-B833-438D-A2A0-63BBB60C13E6';
            vSpecificDENEXId := '';
            vSpecificDENEXCEPId := '171D644F-3B45-4EBA-9A8C-31D3BA193088';
          ELSIF c.CQM = '69A' THEN
            MU_CQM_PKG.CQM69A_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);
            vSpecificId := '40280381-3E93-D1AF-013E-D6E2B772150D';
            vSpecificNQF := '421';
            vSpecificCQM := '69';
            vSpecificTitle := 'Preventive Care and Screening: Body Mass Index (BMI) Screening and Follow-Up';
            vSpecificVersion := '2';

            vSpecificIPPId := '3FA95131-7882-49C0-9830-2ACB82E914D8';
            vSpecificDENOMId := '47F98343-B180-4CD6-9622-1D913DE255B2';
            vSpecificNUMERId := '22AAB4CB-4452-4BA0-8A45-B340A318092D';
            vSpecificDENEXId := '6F3694A9-6AE2-4FED-923A-198489AB47B8';

            vSpecificDENEXCEPId := '';
          ELSIF c.CQM = '69B' THEN
            MU_CQM_PKG.CQM69B_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);
            vSpecificId := '40280381-3E93-D1AF-013E-D6E2B772150D';
            vSpecificNQF := '421';
            vSpecificCQM := '69';
            vSpecificTitle := 'Preventive Care and Screening: Body Mass Index (BMI) Screening and Follow-Up';
            vSpecificVersion := '2';

            vSpecificIPPId := '95D45B98-C6A1-42F4-A0F5-617DF414A2AE';
            vSpecificDENOMId := '73F6ACC4-B252-42CA-8C3B-330EC37F1294';
            vSpecificNUMERId := '875D8E62-44E5-4249-803D-1B36B57DC2DA';
            vSpecificDENEXId := 'D98C4592-BDCE-4BDF-8466-2339A98AD00B';
            vSpecificDENEXCEPId := '';
          ELSIF c.CQM = '74' THEN
            MU_CQM_PKG.CQM74A_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);
            vSpecificId := '40280381-3D61-56A7-013E-8ACBFE873BCB';
            vSpecificNQF := 'PrimaryCariesPrevention';
            vSpecificCQM := '74';
            vSpecificTitle := 'Primary caries prevention intervention as offered by Primary Care Providers, including Dentists';
            vSpecificVersion := '3';

            vSpecificIPPId := 'E91779A3-28D7-44F9-A150-6C8504809B1F';
            vSpecificDENOMId := '81DE4056-93B1-43ED-BD3E-0A93CCC70828';
            vSpecificNUMERId := '25DAB30B-E300-43BE-9558-B76B71B6E3A9';
            vSpecificDENEXId := '';
            vSpecificDENEXCEPId := '';
          ELSIF c.CQM = '75' THEN
            MU_CQM_PKG.CQM75_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);
            vSpecificId := '40280381-3D61-56A7-013E-8F2F5AD054E2';
            vSpecificNQF := 'ChildDentalDecay';
            vSpecificCQM := '75';
            vSpecificTitle := 'Children who have dental decay or cavities';
            vSpecificVersion := '2';

            vSpecificIPPId := '35814E51-399D-4DA3-AC4F-67EA95140F9B';
            vSpecificDENOMId := 'EE53E909-57C7-4B9E-A751-DED6F4DBD53E';
            vSpecificNUMERId := 'F0D11476-E49B-4C70-B557-F9A5E670248A';
            vSpecificDENEXId := '';
            vSpecificDENEXCEPId := '';
          ELSIF c.CQM = '124' THEN
            MU_CQM_PKG.CQM124_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);
            vSpecificId := '40280381-3D61-56A7-013E-669CBC034836';
            vSpecificNQF := '32';
            vSpecificCQM := '124';
            vSpecificTitle := 'Women 21-64 years of age, received one or more Pap tests for cervical cancer screening';
            vSpecificVersion := '2';

            vSpecificIPPId := '1625C924-E7DB-4849-A516-3E1D7C43B1B4';
            vSpecificDENOMId := '4897F89C-7CE0-498E-9154-4D88E095985E';
            vSpecificNUMERId := '3EFED3A9-5301-422F-87BF-E3A98186BCF1';
            vSpecificDENEXId := 'E025DE5C-0417-49C2-8A02-4DB342FF6AE2';
            vSpecificDENEXCEPId := '';
          ELSIF c.CQM = '125' THEN
            MU_CQM_PKG.CQM125_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);
            vSpecificId := '40280381-3D61-56A7-013E-66A5A5834990';
            vSpecificNQF := '31';
            vSpecificCQM := '125';
            vSpecificTitle := 'Women 40-69 years of age with a mammogram for breast cancer screening';
            vSpecificVersion := '2';

            vSpecificIPPId := '670DFFA3-F2EE-4CF7-9083-743F2C1D7D50';
            vSpecificDENOMId := 'E2FB61E6-8252-44B6-B769-C24B12C53B17';
            vSpecificNUMERId := 'E6295CB8-D421-4F5E-88C1-2EE0AD3FAF5B';
            vSpecificDENEXId := '2B8B1EC8-8230-42BF-B4EC-FD9184E9A024';
            vSpecificDENEXCEPId := '';
          ELSIF c.CQM = '127' THEN
            MU_CQM_PKG.CQM127_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);
            vSpecificId := '40280381-3D61-56A7-013E-66A79D4A4A23';
            vSpecificNQF := '43';
            vSpecificCQM := '127';
            vSpecificTitle := 'Patients 65 years of age received a pneumococcal vaccine';
            vSpecificVersion := '2';

            vSpecificIPPId := '8719C1EE-81BB-45B1-B05C-2CB6593E12F1';
            vSpecificDENOMId := '32BF25B7-7448-4B88-8CBC-AEFA213F84ED';
            vSpecificNUMERId := '43479DAE-01AD-4540-AB02-C02B78D26810';
            vSpecificDENEXId := '';
            vSpecificDENEXCEPId := '';
          ELSIF c.CQM = '130' THEN
            MU_CQM_PKG.CQM130_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);
            vSpecificId := '40280381-3D61-56A7-013E-5BFF718B5A57';
            vSpecificNQF := '34';
            vSpecificCQM := '130';
            vSpecificTitle := 'Adults 50-75 years of age who had appropriate screening for colorectal cancer';
            vSpecificVersion := '2';

            vSpecificIPPId := 'CB9A5F17-0F72-455D-8187-BB75C47930BE';
            vSpecificDENOMId := 'DBEAF435-9490-4ACF-A013-4EED4050F3F1';
            vSpecificNUMERId := 'F9D91840-0683-4EB1-A8D6-A9637C6C4E5B';
            vSpecificDENEXId := 'D63F9FC8-F883-4627-9D2C-61CEA40A36F9';
            vSpecificDENEXCEPId := '';
          ELSIF c.CQM = '138' THEN
            MU_CQM_PKG.CQM138_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);
            vSpecificId := '40280381-3D61-56A7-013E-5CD94A4D64FA';
            vSpecificNQF := '28';
            vSpecificCQM := '138';
            vSpecificTitle := 'Preventive Care and Screening: Tobacco Use: Screening and Cessation Intervention';
            vSpecificVersion := '2';

            vSpecificIPPId := 'F130623A-0505-466B-A2B7-996AC6D9C05A';
            vSpecificDENOMId := '4A7D841F-0C3A-43DB-8220-ED6B1A971AC9';
            vSpecificNUMERId := 'FB081A01-4184-43CB-9ADE-0698C1B82082';
            vSpecificDENEXId := '';
            vSpecificDENEXCEPId := 'F8B92E13-AEC3-4B52-B381-E1BD98164F84';
          ELSIF c.CQM = '147' THEN
            MU_CQM_PKG.CQM147_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);
            vSpecificId := '40280381-3D61-56A7-013E-57F49972361A';
            vSpecificNQF := '41';
            vSpecificCQM := '147';
            vSpecificTitle := 'Preventive Care and Screening: Influenza Immunization';
            vSpecificVersion := '2';

            vSpecificIPPId := '34F4027D-C59C-4DC5-834B-89B1E34C219D';
            vSpecificDENOMId := '2F7CF599-3DD4-43C0-BF34-622DAE9617AE';
            vSpecificNUMERId := '9C2D94BD-12B7-4918-9EE5-8C4DEF3AF212';
            vSpecificDENEXId := '';
            vSpecificDENEXCEPId := 'D3C49689-06FB-4702-8079-F09C074B42B7';
          ELSIF c.CQM = '155' THEN
            MU_CQM_PKG.CQM155A1_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);
            vSpecificId := '40280381-3D61-56A7-013E-5D530FD26D47';
            vSpecificNQF := '24';
            vSpecificCQM := '155';
            vSpecificTitle := 'Weight Assessment and Counselling for Nutrition and Physical Activity for Children and Adolescents';
            vSpecificVersion := '2';

            vSpecificIPPId := 'A75126FB-5455-476C-AD34-68AE645535F1';
            vSpecificDENOMId := '2E95A790-B16B-4679-AAC0-B70B46932304';
            vSpecificNUMERId := '2D775CD0-CAC4-44D1-9185-9E6AB12835FA';
            vSpecificDENEXId := '6A98DA9A-C352-4A4D-8B69-B2D08619E8A8';
            vSpecificDENEXCEPId := '';
          ELSIF c.CQM = '156' THEN
            MU_CQM_PKG.CQM156A_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

            vSpecificId := '40280381-3D61-56A7-013E-65C9C3043E54';
            vSpecificNQF := '22';
            vSpecificCQM := '156';
            vSpecificTitle := 'Use of High-Risk Medications in the Elderly';
            vSpecificVersion := '2';

            vSpecificIPPId := 'EE59C907-09FA-47C7-94CF-BB03E2F18667';
            vSpecificDENOMId := '30B2C98C-09C0-425E-94B0-98A224D8958D';
            vSpecificNUMERId := '4C09A356-D793-487E-BD27-1031D9BF35B7';
            vSpecificNUMER2Id := 'F9870989-EC28-4523-934A-544F19C34ED1';
            vSpecificDENEXId := '';
            vSpecificDENEXCEPId := '';
          ELSIF c.CQM = '165' THEN
            MU_CQM_PKG.CQM165_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);
            vSpecificId := '40280381-3D61-56A7-013E-66BC02DA4DEE';
            vSpecificNQF := '18';
            vSpecificCQM := '165';
            vSpecificTitle := 'Controlling High Blood Pressure';
            vSpecificVersion := '2';

            vSpecificIPPId := 'B936D6B5-151F-47FB-97D8-A5AB9AB00656';
            vSpecificDENOMId := '2A53CBF0-510A-429D-814D-CBCA4DC0E2A8';
            vSpecificNUMERId := '5EE417A9-32DB-452F-BAA0-74C5831A4457';
            vSpecificDENEXId := '57F3D1D7-F9FA-437F-A2B9-406A1498E8C0';
            vSpecificDENEXCEPId := '';
          END IF;


          FETCH cWeakCursor BULK COLLECT INTO lPatients;

          FOR i IN 1..lPatients.COUNT LOOP
            BEGIN

              SELECT "Sex", NVL(TRIM("Ethnic"), ' ') "Ethnic" INTO vSex, vEthnic FROM PATIENT WHERE "Patient" = lPatients(i)."Patient";
              SELECT NVL(MAX(TRIM("Race")), ' ') "Race" INTO vRace FROM PTRACE WHERE "Patient" = lPatients(i)."Patient" AND "Deleted" = 0;

              ------------------------
              --    IPP Patients    --
              ------------------------
              vIPPCount := vIPPCount + 1;

              IF vPatientID = 0 OR vPatientID <> lPatients(i)."Patient" THEN
                vIPPPAYERCount := vIPPPAYERCount + 1;

                IF vSex = 1 THEN
                  vIPPSexM := vIPPSexM + 1;
                ELSIF vSex = 2 THEN
                  vIPPSexF := vIPPSexF + 1;
                ELSIF vSex NOT IN (1, 2) THEN
                  vIPPSexUN := vIPPSexUN + 1;
                ELSE
                  vIPPSexUNK := vIPPSexUNK + 1;
                END IF;

                --Not currently considering if a patient has multiple races.
                --That might be a requirement but not needed for certification
                IF vRace = 'NATIVE' THEN
                  vIPPRaceNative := vIPPRaceNative + 1;
                ELSIF vRace = 'ASIAN' THEN
                  vIPPRaceAsian := vIPPRaceAsian + 1;
                ELSIF vRace = 'BLACK' THEN
                  vIPPRaceBlack := vIPPRaceBlack + 1;
                ELSIF vRace = 'ISLAND' THEN
                  vIPPRaceIsland := vIPPRaceIsland + 1;
                ELSIF vRace = 'WHITE' THEN
                  vIPPRaceWhite := vIPPRaceWhite + 1;
                ELSIF vRace = 'OTHER' THEN
                  vIPPRaceOther := vIPPRaceOther + 1;
                ELSE
                  vIPPRaceUNK := vIPPRaceUNK + 1;
                END IF;

                IF vEthnic = 'HISP' THEN
                  vIPPEthnicHisp := vIPPEthnicHisp + 1;
                ELSIF vEthnic = 'NHISP' THEN
                  vIPPEthnicNotHisp := vIPPEthnicNotHisp + 1;
                ELSE
                  vIPPEthnicUNK := vIPPEthnicUNK + 1;
                END IF;
              END IF;

              ------------------------
              --   DENOM Patients   --
              ------------------------
              IF lPatients(i)."Denom" = 1 THEN
                vDENOMCount := vDENOMCount + 1;
                vDenomPAYERCount := vDenomPAYERCount + 1;

                IF vPatientID = 0 OR vPatientID <> lPatients(i)."Patient" THEN
                  IF vSex = 1 THEN
                    vDenomSexM := vDenomSexM + 1;
                  ELSIF vSex = 2 THEN
                    vDenomSexF := vDenomSexF + 1;
                  ELSIF vSex NOT IN (1, 2) THEN
                    vDenomSexUN := vDenomSexUN + 1;
                  ELSE
                    vDenomSexUNK := vDenomSexUNK + 1;
                  END IF;

                  --Not currently considering if a patient has multiple races.
                  --That might be a requirement but not needed for certification
                  IF vRace = 'NATIVE' THEN
                    vDenomRaceNative := vDenomRaceNative + 1;
                  ELSIF vRace = 'ASIAN' THEN
                    vDenomRaceAsian := vDenomRaceAsian + 1;
                  ELSIF vRace = 'BLACK' THEN
                    vDenomRaceBlack := vDenomRaceBlack + 1;
                  ELSIF vRace = 'ISLAND' THEN
                    vDenomRaceIsland := vDenomRaceIsland + 1;
                  ELSIF vRace = 'WHITE' THEN
                    vDenomRaceWhite := vDenomRaceWhite + 1;
                  ELSIF vRace = 'OTHER' THEN
                    vDenomRaceOther := vDenomRaceOther + 1;
                  ELSE
                    vDenomRaceUNK := vDenomRaceUNK + 1;
                  END IF;

                  IF vEthnic = 'HISP' THEN
                    vDenomEthnicHisp := vDenomEthnicHisp + 1;
                  ELSIF vEthnic = 'NHISP' THEN
                    vDenomEthnicNotHisp := vDenomEthnicNotHisp + 1;
                  ELSE
                    vDenomEthnicUNK := vDenomEthnicUNK + 1;
                  END IF;
                END IF;

              END IF;

              ------------------------
              -- Numerator Patients --
              ------------------------
              IF lPatients(i)."Flag" = 1 THEN
                vNUMERCount := vNUMERCount + 1;

                IF vPatientID = 0 OR vPatientID <> lPatients(i)."Patient" THEN
                  IF vSex = 1 THEN
                    vNumSexM := vNumSexM + 1;
                  ELSIF vSex = 2 THEN
                    vNumSexF := vNumSexF + 1;
                  ELSIF vSex NOT IN (1, 2) THEN
                    vNumSexUN := vNumSexUN + 1;
                  ELSE
                    vNumSexUNK := vNumSexUNK + 1;
                  END IF;

                  --Not currently considering if a patient has multiple races.
                  --That might be a requirement but not needed for certification
                  IF vRace = 'NATIVE' THEN
                    vNumRaceNative := vNumRaceNative + 1;
                  ELSIF vRace = 'ASIAN' THEN
                    vNumRaceAsian := vNumRaceAsian + 1;
                  ELSIF vRace = 'BLACK' THEN
                    vNumRaceBlack := vNumRaceBlack + 1;
                  ELSIF vRace = 'ISLAND' THEN
                    vNumRaceIsland := vNumRaceIsland + 1;
                  ELSIF vRace = 'WHITE' THEN
                    vNumRaceWhite := vNumRaceWhite + 1;
                  ELSIF vRace = 'OTHER' THEN
                    vNumRaceOther := vNumRaceOther + 1;
                  ELSE
                    vNumRaceUNK := vNumRaceUNK + 1;
                  END IF;

                  IF vEthnic = 'HISP' THEN
                    vNumEthnicHisp := vNumEthnicHisp + 1;
                  ELSIF vEthnic = 'NHISP' THEN
                    vNumEthnicNotHisp := vNumEthnicNotHisp + 1;
                  ELSE
                    vNumEthnicUNK := vNumEthnicUNK + 1;
                  END IF;
                END IF;

              END IF;


              ------------------------
              -- Exclusion Patients --
              ------------------------
              IF lPatients(i)."Ex" = 1 THEN
                vDenExCount := vDenExCount + 1;

                IF vPatientID = 0 OR vPatientID <> lPatients(i)."Patient" THEN
                  IF vSex = 1 THEN
                    vDenExSexM := vDenExSexM + 1;
                  ELSIF vSex = 2 THEN
                    vDenExSexF := vDenExSexF + 1;
                  ELSIF vSex NOT IN (1, 2) THEN
                    vDenExSexUN := vDenExSexUN + 1;
                  ELSE
                    vDenExSexUNK := vDenExSexUNK + 1;
                  END IF;

                  --Not currently considering if a patient has multiple races.
                  --That might be a requirement but not needed for certification
                  IF vRace = 'NATIVE' THEN
                    vDenExRaceNative := vDenExRaceNative + 1;
                  ELSIF vRace = 'ASIAN' THEN
                    vDenExRaceAsian := vDenExRaceAsian + 1;
                  ELSIF vRace = 'BLACK' THEN
                    vDenExRaceBlack := vDenExRaceBlack + 1;
                  ELSIF vRace = 'ISLAND' THEN
                    vDenExRaceIsland := vDenExRaceIsland + 1;
                  ELSIF vRace = 'WHITE' THEN
                    vDenExRaceWhite := vDenExRaceWhite + 1;
                  ELSIF vRace = 'OTHER' THEN
                    vDenExRaceOther := vDenExRaceOther + 1;
                  ELSE
                    vDenExRaceUNK := vDenExRaceUNK + 1;
                  END IF;

                  IF vEthnic = 'HISP' THEN
                    vDenExEthnicHisp := vDenExEthnicHisp + 1;
                  ELSIF vEthnic = 'NHISP' THEN
                    vDenExEthnicNotHisp := vDenExEthnicNotHisp + 1;
                  ELSE
                    vDenExEthnicUNK := vDenExEthnicUNK + 1;
                  END IF;
                END IF;

              END IF;


              ------------------------
              -- Exception Patients --
              ------------------------
              IF lPatients(i)."Exc" = 1 THEN
                vDenExCount := vDenExCount + 1;

                IF vPatientID = 0 OR vPatientID <> lPatients(i)."Patient" THEN
                  IF vSex = 1 THEN
                    vDenExcepSexM := vDenExcepSexM + 1;
                  ELSIF vSex = 2 THEN
                    vDenExcepSexF := vDenExcepSexF + 1;
                  ELSIF vSex NOT IN (1, 2) THEN
                    vDenExcepSexUN := vDenExcepSexUN + 1;
                  ELSE
                    vDenExcepSexUNK := vDenExcepSexUNK + 1;
                  END IF;

                  --Not currently considering if a patient has multiple races.
                  --That might be a requirement but not needed for certification
                  IF vRace = 'NATIVE' THEN
                    vDenExcepRaceNative := vDenExcepRaceNative + 1;
                  ELSIF vRace = 'ASIAN' THEN
                    vDenExcepRaceAsian := vDenExcepRaceAsian + 1;
                  ELSIF vRace = 'BLACK' THEN
                    vDenExcepRaceBlack := vDenExcepRaceBlack + 1;
                  ELSIF vRace = 'ISLAND' THEN
                    vDenExcepRaceIsland := vDenExcepRaceIsland + 1;
                  ELSIF vRace = 'WHITE' THEN
                    vDenExcepRaceWhite := vDenExcepRaceWhite + 1;
                  ELSIF vRace = 'OTHER' THEN
                    vDenExcepRaceOther := vDenExcepRaceOther + 1;
                  ELSE
                    vDenExcepRaceUNK := vDenExcepRaceUNK + 1;
                  END IF;

                  IF vEthnic = 'HIPS' THEN
                    vDenExcepEthnicHisp := vDenExcepEthnicHisp + 1;
                  ELSIF vEthnic = 'NHISP' THEN
                    vDenExcepEthnicNotHisp := vDenExcepEthnicNotHisp + 1;
                  ELSE
                    vDenExcepEthnicUNK := vDenExcepEthnicUNK + 1;
                  END IF;
                END IF;

              END IF;

              -- Set variable to check if next patient is same as current patient
              vPatientID := lPatients(i)."Patient";

            EXCEPTION WHEN NO_DATA_FOUND THEN
              vError := 6;
            END;

          END LOOP;

          CLOSE cWeakCursor;


          -- Entry code for each CQM
          BEGIN
            /***********************
            *      CQM HEADER      *
            ***********************/

            dbms_lob.append(vOutputFile, Tab000000005 || '<entry>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000006 || '<organizer classCode="cluster" moodCode=EVN>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.24.3.98" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab0000000000007 || '<templateId root="2.16.840.1.113883.10.20.27.3.1" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab0000000000007 || '<statusCode code=completed />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab0000000000007 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab000000000000008 || '<externalDocument classCode=DOC moodCode=EVN>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '<id root="' || TRIM(vSpecificId) || '" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '<id root="2.16.840.1.113883.3.560.1" extension="' || TRIM(vSpecificNQF) || '" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '<id root="2.16.840.1.113883.3.560.101.2" extension="' || TRIM(vSpecificCQM) || '" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '<code codeSystem="2.16.840.1.113883.6.1" code="57024-2" codeSystemName=LOINC displayName="Health Quality Measure Document" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '<text>' || TRIM(vSpecificTitle) || '</text>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '<setId root="' || TRIM(vSpecificId) || '" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '<versionNumber value="' || TRIM(vSpecificVersion) || '" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab000000000000008 || '</externalDocument>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab0000000000007 || '</reference>' || CHR(13) || CHR(10));

            dbms_lob.append(vOutputFile, Tab0000000000007 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab000000000000008 || '<externalObservation>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '<id root="B8CA5868-7395-4941-A5C8-353C4DF45630" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '<code codeSystem="2.16.840.1.113883.6.1" code="55185-3" codeSystemName=LOINC displayName="Measure Set" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '<text>' || TRIM(vSpecificTitle) || '</text>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab000000000000008 || '</externalObservation>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab0000000000007 || '</reference>' || CHR(13) || CHR(10));


            /***********************
            *  INTIAL POPULATION   *
            ***********************/

            -- IPP Info
            dbms_lob.append(vOutputFile, Tab0000000000007 || '<component>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab000000000000008 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '<templateId root="2.16.840.1.113883.10.20.27.3.5" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '<statusCode code=completed />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '<value xsi:type=CD code=IPP codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Initial Patient Population" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type="int" value="' || vIPPCount || '" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));

            IF vSpecificCQM = '74' THEN

              /***********************
              *    Ages 0-5 Years    *
              ***********************/
              vStratCount := 0;
              vSpecificStratificationId := '2C028996-D897-4162-ADBE-8619EDBE4E7D';

              MU_CQM_PKG.CQM74B_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

              FETCH cWeakCursor BULK COLLECT INTO lPatients;

              FOR i IN 1..lPatients.COUNT LOOP
                vStratCount := vStratCount + 1;
              END LOOP;

              CLOSE cWeakCursor;

              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.4" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=IPP codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Initial Patient Population" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vStratCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<id root="' || vSpecificStratificationId || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));


              /***********************
              *   Ages 6-12 Years    *
              ***********************/
              vStratCount := 0;
              vSpecificStratificationId := '59140979-7876-4A93-85EB-1276E2ED7584';

              MU_CQM_PKG.CQM74C_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

              FETCH cWeakCursor BULK COLLECT INTO lPatients;

              FOR i IN 1..lPatients.COUNT LOOP
                vStratCount := vStratCount + 1;
              END LOOP;

              CLOSE cWeakCursor;

              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.4" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=IPP codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Initial Patient Population" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vStratCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<id root="' || vSpecificStratificationId || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));


              /***********************
              *   Ages 13-20 Years   *
              ***********************/
              vStratCount := 0;
              vSpecificStratificationId := '154FFAC4-61BF-49CE-87C4-4FC415465F68';

              MU_CQM_PKG.CQM74D_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

              FETCH cWeakCursor BULK COLLECT INTO lPatients;

              FOR i IN 1..lPatients.COUNT LOOP
                vStratCount := vStratCount + 1;
              END LOOP;

              CLOSE cWeakCursor;

              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.4" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=IPP codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Initial Patient Population" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vStratCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<id root="' || vSpecificStratificationId || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            IF vSpecificCQM = '155' THEN

              /***********************
              *    Ages 3-11 Years   *
              ***********************/
              vStratCount := 0;
              vSpecificStratificationId := '445A44EE-98BC-4614-B8B6-7A9521CD0794';

              MU_CQM_PKG.CQM155B1_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

              FETCH cWeakCursor BULK COLLECT INTO lPatients;

              FOR i IN 1..lPatients.COUNT LOOP
                vStratCount := vStratCount + 1;
              END LOOP;

              CLOSE cWeakCursor;

              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.4" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=IPP codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Initial Patient Population" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vStratCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<id root="' || vSpecificStratificationId || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));


              /***********************
              *   Ages 12-17 Years   *
              ***********************/
              vStratCount := 0;
              vSpecificStratificationId := 'AA764699-1039-4E99-817C-6ED6E9E93735';

              MU_CQM_PKG.CQM155C1_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

              FETCH cWeakCursor BULK COLLECT INTO lPatients;

              FOR i IN 1..lPatients.COUNT LOOP
                vStratCount := vStratCount + 1;
              END LOOP;

              CLOSE cWeakCursor;

              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.4" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=IPP codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Initial Patient Population" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vStratCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<id root="' || vSpecificStratificationId || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- IPP Ethnicity
            IF vIPPEthnicHisp > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.7" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="364699009" codeSystemName="SNOMED CT" displayName="Ethnic Group" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2135-2" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Hispanic or Latino" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vIPPEthnicHisp || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- IPP Ethnicity
            IF vIPPEthnicNotHisp > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.7" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="364699009" codeSystemName="SNOMED CT" displayName="Ethnic Group" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2186-5" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Not Hispanic or Latino" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vIPPEthnicNotHisp || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- IPP Ethnicity
            IF vIPPEthnicUNK > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.7" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="364699009" codeSystemName="SNOMED CT" displayName="Ethnic Group" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD nullFlavor=UNK/>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vIPPEthnicUNK || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- IPP Race
            IF vIPPRaceNative > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="1002-5" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="American Indian or Alaska Native" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vIPPRaceNative || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- IPP Race
            IF vIPPRaceAsian > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2028-9" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Asian" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vIPPRaceAsian || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- IPP Race
            IF vIPPRaceBlack > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2054-5" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Black or African American" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vIPPRaceBlack || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- IPP Race
            IF vIPPRaceIsland > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2076-8" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Native Hawaiian or Other Pacific Islander" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vIPPRaceIsland || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- IPP Race
            IF vIPPRaceWhite > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2106-3" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="White" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vIPPRaceWhite || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- IPP Race
            IF vIPPRaceOther > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2131-1" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Other Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vIPPRaceOther || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- IPP Race
            IF vIPPRaceUNK > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD nullFlavor=UNK/>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vIPPRaceUNK || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- IPP Sex
            IF vIPPSexF > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.6" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="184100006" codeSystemName="SNOMED-CT" displayName="Patient Sex" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=F codeSystem="2.16.840.1.113883.5.1" codeSystemName="HL7AdministrativeGenderCode" displayName="Female" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vIPPSexF || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- IPP Sex
            IF vIPPSexM > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.6" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="184100006" codeSystemName="SNOMED-CT" displayName="Patient Sex" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=M codeSystem="2.16.840.1.113883.5.1" codeSystemName="HL7AdministrativeGenderCode" displayName="Male" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vIPPSexM || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- IPP Sex
            IF vIPPSexUN > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.6" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="184100006" codeSystemName="SNOMED-CT" displayName="Patient Sex" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=UN codeSystem="2.16.840.1.113883.5.1" codeSystemName="HL7AdministrativeGenderCode" displayName="Undifferentiated" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vIPPSexUN || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- IPP Sex
            IF vIPPSexUNK > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.6" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="184100006" codeSystemName="SNOMED-CT" displayName="Patient Sex" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD nullFlavor=UNK/>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vIPPSexUNK || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- IPP Payor
            IF vIPPPAYERCount > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.24.3.55" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.9" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<id nullFlavor=NA />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.1" code="48768-6" codeSystemName=LOINC displayName="Payment source" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="349" codeSystem="2.16.840.1.113883.3.221.5" codeSystemName="Source of Payment Typology" displayName="Medicare" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vIPPPAYERCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- IPP Close
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<id root="' || TRIM(vSpecificIPPId) || '" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</externalObservation>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '</reference>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab000000000000008 || '</observation>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab0000000000007 || '</component>' || CHR(13) || CHR(10));


            /***********************
            *     DENOMERATOR      *
            ***********************/

            -- DENOM Info
            dbms_lob.append(vOutputFile, Tab0000000000007 || '<component>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab000000000000008 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '<templateId root="2.16.840.1.113883.10.20.27.3.5" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '<statusCode code=completed />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '<value xsi:type=CD code=DENOM codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Denominator" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type="int" value="' || vDENOMCount || '" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));

            IF vSpecificCQM = '74' THEN

              /***********************
              *    Ages 0-5 Years    *
              ***********************/
              vStratCount := 0;
              vSpecificStratificationId := '2C028996-D897-4162-ADBE-8619EDBE4E7D';

              MU_CQM_PKG.CQM74B_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

              FETCH cWeakCursor BULK COLLECT INTO lPatients;

              FOR i IN 1..lPatients.COUNT LOOP
                IF lPatients(i)."Denom" = 1 THEN
                  vStratCount := vStratCount + 1;
                END IF;
              END LOOP;

              CLOSE cWeakCursor;

              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.4" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=DENOM codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Denominator" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vStratCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<id root="' || vSpecificStratificationId || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));


              /***********************
              *   Ages 6-12 Years    *
              ***********************/
              vStratCount := 0;
              vSpecificStratificationId := '59140979-7876-4A93-85EB-1276E2ED7584';

              MU_CQM_PKG.CQM74C_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

              FETCH cWeakCursor BULK COLLECT INTO lPatients;

              FOR i IN 1..lPatients.COUNT LOOP
                IF lPatients(i)."Denom" = 1 THEN
                  vStratCount := vStratCount + 1;
                END IF;
              END LOOP;

              CLOSE cWeakCursor;

              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.4" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=DENOM codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Denominator" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vStratCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<id root="' || vSpecificStratificationId || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));


              /***********************
              *   Ages 13-20 Years   *
              ***********************/
              vStratCount := 0;
              vSpecificStratificationId := '154FFAC4-61BF-49CE-87C4-4FC415465F68';

              MU_CQM_PKG.CQM74D_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

              FETCH cWeakCursor BULK COLLECT INTO lPatients;

              FOR i IN 1..lPatients.COUNT LOOP
                IF lPatients(i)."Denom" = 1 THEN
                  vStratCount := vStratCount + 1;
                END IF;
              END LOOP;

              CLOSE cWeakCursor;

              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.4" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=DENOM codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Denominator" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vStratCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<id root="' || vSpecificStratificationId || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            IF vSpecificCQM = '155' THEN

              /***********************
              *    Ages 3-11 Years   *
              ***********************/
              vStratCount := 0;
              vSpecificStratificationId := '445A44EE-98BC-4614-B8B6-7A9521CD0794';

              MU_CQM_PKG.CQM155B1_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

              FETCH cWeakCursor BULK COLLECT INTO lPatients;

              FOR i IN 1..lPatients.COUNT LOOP
                IF lPatients(i)."Denom" = 1 THEN
                  vStratCount := vStratCount + 1;
                END IF;
              END LOOP;

              CLOSE cWeakCursor;

              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.4" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=DENOM codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Denominator" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vStratCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<id root="' || vSpecificStratificationId || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));


              /***********************
              *   Ages 12-17 Years   *
              ***********************/
              vStratCount := 0;
              vSpecificStratificationId := 'AA764699-1039-4E99-817C-6ED6E9E93735';

              MU_CQM_PKG.CQM155C1_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

              FETCH cWeakCursor BULK COLLECT INTO lPatients;

              FOR i IN 1..lPatients.COUNT LOOP
                IF lPatients(i)."Denom" = 1 THEN
                  vStratCount := vStratCount + 1;
                END IF;
              END LOOP;

              CLOSE cWeakCursor;

              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.4" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=DENOM codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Denominator" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vStratCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<id root="' || vSpecificStratificationId || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENOM Ethnicity
            IF vDenomEthnicHisp > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.7" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="364699009" codeSystemName="SNOMED CT" displayName="Ethnic Group" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2135-2" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Hispanic or Latino" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenomEthnicHisp || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENOM Ethnicity
            IF vDenomEthnicNotHisp > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.7" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="364699009" codeSystemName="SNOMED CT" displayName="Ethnic Group" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2186-5" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Not Hispanic or Latino" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenomEthnicNotHisp || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENOM Ethnicity
            IF vDenomEthnicUNK > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.7" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="364699009" codeSystemName="SNOMED CT" displayName="Ethnic Group" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD nullFlavor=UNK/>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenomEthnicUNK || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENOM Race
            IF vDenomRaceNative > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="1002-5" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="American Indian or Alaska Native" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenomRaceNative || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENOM Race
            IF vDenomRaceAsian > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2028-9" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Asian" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenomRaceAsian || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENOM Race
            IF vDenomRaceBlack > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2054-5" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Black or African American" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenomRaceBlack || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENOM Race
            IF vDenomRaceIsland > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2076-8" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Native Hawaiian or Other Pacific Islander" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenomRaceIsland || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENOM Race
            IF vDenomRaceWhite > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2106-3" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="White" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenomRaceWhite || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENOM Race
            IF vDenomRaceOther > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2131-1" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Other Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenomRaceOther || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENOM Race
            IF vDenomRaceUNK > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD nullFlavor=UNK/>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenomRaceUNK || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENOM Sex
            IF vDenomSexF > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.6" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="184100006" codeSystemName="SNOMED-CT" displayName="Patient Sex" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=F codeSystem="2.16.840.1.113883.5.1" codeSystemName="HL7AdministrativeGenderCode" displayName="Female" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenomSexF || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENOM Sex
            IF vDenomSexM > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.6" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="184100006" codeSystemName="SNOMED-CT" displayName="Patient Sex" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=M codeSystem="2.16.840.1.113883.5.1" codeSystemName="HL7AdministrativeGenderCode" displayName="Male" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenomSexM || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENOM Sex
            IF vDenomSexUN > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.6" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="184100006" codeSystemName="SNOMED-CT" displayName="Patient Sex" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=UN codeSystem="2.16.840.1.113883.5.1" codeSystemName="HL7AdministrativeGenderCode" displayName="Undifferentiated" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenomSexUN || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENOM Sex
            IF vDenomSexUNK > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.6" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="184100006" codeSystemName="SNOMED-CT" displayName="Patient Sex" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD nullFlavor=UNK/>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenomSexUNK || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENOM Payor
            IF vDenomPAYERCount > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.24.3.55" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.9" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<id nullFlavor=NA />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.1" code="48768-6" codeSystemName=LOINC displayName="Payment source" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="349" codeSystem="2.16.840.1.113883.3.221.5" codeSystemName="Source of Payment Typology" displayName="Medicare" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenomPAYERCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENOM Close
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<id root="' || TRIM(vSpecificDENOMId) || '" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</externalObservation>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '</reference>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab000000000000008 || '</observation>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab0000000000007 || '</component>' || CHR(13) || CHR(10));


            /***********************
            *      NUMERATOR       *
            ***********************/

            -- NUMER Info
            dbms_lob.append(vOutputFile, Tab0000000000007 || '<component>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab000000000000008 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '<templateId root="2.16.840.1.113883.10.20.27.3.5" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '<statusCode code=completed />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '<value xsi:type=CD code=NUMER codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Numerator" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type="int" value="' || vNUMERCount || '" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));

            IF vSpecificCQM = '74' THEN

              /***********************
              *    Ages 0-5 Years    *
              ***********************/
              vStratCount := 0;
              vSpecificStratificationId := '2C028996-D897-4162-ADBE-8619EDBE4E7D';

              MU_CQM_PKG.CQM74B_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

              FETCH cWeakCursor BULK COLLECT INTO lPatients;

              FOR i IN 1..lPatients.COUNT LOOP
                IF lPatients(i)."Flag" = 1 THEN
                  vStratCount := vStratCount + 1;
                END IF;
              END LOOP;

              CLOSE cWeakCursor;

              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.4" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=NUMER codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Numerator" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vStratCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<id root="' || vSpecificStratificationId || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));


              /***********************
              *   Ages 6-12 Years    *
              ***********************/
              vStratCount := 0;
              vSpecificStratificationId := '59140979-7876-4A93-85EB-1276E2ED7584';

              MU_CQM_PKG.CQM74C_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

              FETCH cWeakCursor BULK COLLECT INTO lPatients;

              FOR i IN 1..lPatients.COUNT LOOP
                IF lPatients(i)."Flag" = 1 THEN
                  vStratCount := vStratCount + 1;
                END IF;
              END LOOP;

              CLOSE cWeakCursor;

              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.4" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=NUMER codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Numerator" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vStratCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<id root="' || vSpecificStratificationId || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));


              /***********************
              *   Ages 13-20 Years   *
              ***********************/
              vStratCount := 0;
              vSpecificStratificationId := '154FFAC4-61BF-49CE-87C4-4FC415465F68';

              MU_CQM_PKG.CQM74D_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

              FETCH cWeakCursor BULK COLLECT INTO lPatients;

              FOR i IN 1..lPatients.COUNT LOOP
                IF lPatients(i)."Flag" = 1 THEN
                  vStratCount := vStratCount + 1;
                END IF;
              END LOOP;

              CLOSE cWeakCursor;

              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.4" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=NUMER codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Numerator" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vStratCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<id root="' || vSpecificStratificationId || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            IF vSpecificCQM = '155' THEN

              /***********************
              *    Ages 3-11 Years   *
              ***********************/
              vStratCount := 0;
              vSpecificStratificationId := '445A44EE-98BC-4614-B8B6-7A9521CD0794';

              MU_CQM_PKG.CQM155B1_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

              FETCH cWeakCursor BULK COLLECT INTO lPatients;

              FOR i IN 1..lPatients.COUNT LOOP
                IF lPatients(i)."Flag" = 1 THEN
                  vStratCount := vStratCount + 1;
                END IF;
              END LOOP;

              CLOSE cWeakCursor;

              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.4" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=NUMER codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Numerator" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vStratCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<id root="' || vSpecificStratificationId || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));


              /***********************
              *   Ages 12-17 Years   *
              ***********************/
              vStratCount := 0;
              vSpecificStratificationId := 'AA764699-1039-4E99-817C-6ED6E9E93735';

              MU_CQM_PKG.CQM155C1_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

              FETCH cWeakCursor BULK COLLECT INTO lPatients;

              FOR i IN 1..lPatients.COUNT LOOP
                IF lPatients(i)."Flag" = 1 THEN
                  vStratCount := vStratCount + 1;
                END IF;
              END LOOP;

              CLOSE cWeakCursor;

              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.4" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=NUMER codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Numerator" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vStratCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<id root="' || vSpecificStratificationId || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- NUMER Ethnicity
            IF vNumEthnicHisp > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.7" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="364699009" codeSystemName="SNOMED CT" displayName="Ethnic Group" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2135-2" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Hispanic or Latino" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumEthnicHisp || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- NUMER Ethnicity
            IF vNumEthnicNotHisp > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.7" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="364699009" codeSystemName="SNOMED CT" displayName="Ethnic Group" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2186-5" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Not Hispanic or Latino" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumEthnicNotHisp || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- NUMER Ethnicity
            IF vNumEthnicUNK > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.7" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="364699009" codeSystemName="SNOMED CT" displayName="Ethnic Group" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD nullFlavor=UNK/>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumEthnicUNK || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- NUMER Race
            IF vNumRaceNative > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="1002-5" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="American Indian or Alaska Native" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumRaceNative || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- NUMER Race
            IF vNumRaceAsian > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2028-9" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Asian" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumRaceAsian || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- NUMER Race
            IF vNumRaceBlack > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2054-5" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Black or African American" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumRaceBlack || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- NUMER Race
            IF vNumRaceIsland > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2076-8" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Native Hawaiian or Other Pacific Islander" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumRaceIsland || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- NUMER Race
            IF vNumRaceWhite > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2106-3" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="White" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumRaceWhite || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- NUMER Race
            IF vNumRaceOther > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2131-1" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Other Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumRaceOther || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- NUMER Race
            IF vNumRaceUNK > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD nullFlavor=UNK/>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumRaceUNK || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- NUMER Sex
            IF vNumSexF > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.6" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="184100006" codeSystemName="SNOMED-CT" displayName="Patient Sex" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=F codeSystem="2.16.840.1.113883.5.1" codeSystemName="HL7AdministrativeGenderCode" displayName="Female" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumSexF || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- NUMER Sex
            IF vNumSexM > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.6" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="184100006" codeSystemName="SNOMED-CT" displayName="Patient Sex" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=M codeSystem="2.16.840.1.113883.5.1" codeSystemName="HL7AdministrativeGenderCode" displayName="Male" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumSexM || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- NUMER Sex
            IF vNumSexUN > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.6" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="184100006" codeSystemName="SNOMED-CT" displayName="Patient Sex" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=UN codeSystem="2.16.840.1.113883.5.1" codeSystemName="HL7AdministrativeGenderCode" displayName="Undifferentiated" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumSexUN || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- NUMER Sex
            IF vNumSexUNK > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.6" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="184100006" codeSystemName="SNOMED-CT" displayName="Patient Sex" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD nullFlavor=UNK/>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumSexUNK || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- NUMER Payor
            IF vNUMERCount > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.24.3.55" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.9" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<id nullFlavor=NA />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.1" code="48768-6" codeSystemName=LOINC displayName="Payment source" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="349" codeSystem="2.16.840.1.113883.3.221.5" codeSystemName="Source of Payment Typology" displayName="Medicare" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNUMERCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- NUMER Close
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<id root="' || TRIM(vSpecificNUMERId) || '" />' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</externalObservation>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab00000000000000009 || '</reference>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab000000000000008 || '</observation>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab0000000000007 || '</component>' || CHR(13) || CHR(10));

            -- Numerator 2
            IF c.CQM = '155' THEN
              vPatientID         := 0;

              vNUMERCount       := 0;

              vNumSexM          := 0;
              vNumSexF          := 0;
              vNumSexUN         := 0;
              vNumSexUNK        := 0;

              vNumRaceNative    := 0;
              vNumRaceAsian     := 0;
              vNumRaceBlack     := 0;
              vNumRaceIsland    := 0;
              vNumRaceWhite     := 0;
              vNumRaceOther     := 0;
              vNumRaceUNK       := 0;

              vNumEthnicHisp    := 0;
              vNumEthnicNotHisp := 0;
              vNumEthnicUNK     := 0;

              MU_CQM_PKG.CQM155A2_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

              vSpecificNUMERId := '36B4858A-821C-40EE-90F1-007A164CD93E';

              FETCH cWeakCursor BULK COLLECT INTO lPatients;

              FOR i IN 1..lPatients.COUNT LOOP

                SELECT "Sex", NVL(TRIM("Ethnic"), ' ') "Ethnic" INTO vSex, vEthnic FROM PATIENT WHERE "Patient" = lPatients(i)."Patient";
                SELECT NVL(MAX(TRIM("Race")), ' ') "Race" INTO vRace FROM PTRACE WHERE "Patient" = lPatients(i)."Patient" AND "Deleted" = 0;

                IF lPatients(i)."Flag" = 1 THEN
                  vNUMERCount := vNUMERCount + 1;

                  IF vPatientID = 0 OR vPatientID <> lPatients(i)."Patient" THEN
                    IF vSex = 1 THEN
                      vNumSexM := vNumSexM + 1;
                    ELSIF vSex = 2 THEN
                      vNumSexF := vNumSexF + 1;
                    ELSIF vSex NOT IN (1, 2) THEN
                      vNumSexUN := vNumSexUN + 1;
                    ELSE
                      vNumSexUNK := vNumSexUNK + 1;
                    END IF;

                    --Not currently considering if a patient has multiple races.
                    --That might be a requirement but not needed for certification
                    IF vRace = 'NATIVE' THEN
                      vNumRaceNative := vNumRaceNative + 1;
                    ELSIF vRace = 'ASIAN' THEN
                      vNumRaceAsian := vNumRaceAsian + 1;
                    ELSIF vRace = 'BLACK' THEN
                      vNumRaceBlack := vNumRaceBlack + 1;
                    ELSIF vRace = 'ISLAND' THEN
                      vNumRaceIsland := vNumRaceIsland + 1;
                    ELSIF vRace = 'WHITE' THEN
                      vNumRaceWhite := vNumRaceWhite + 1;
                    ELSIF vRace = 'OTHER' THEN
                      vNumRaceOther := vNumRaceOther + 1;
                    ELSE
                      vNumRaceUNK := vNumRaceUNK + 1;
                    END IF;

                    IF vEthnic = 'HISP' THEN
                      vNumEthnicHisp := vNumEthnicHisp + 1;
                    ELSIF vEthnic = 'NHISP' THEN
                      vNumEthnicNotHisp := vNumEthnicNotHisp + 1;
                    ELSE
                      vNumEthnicUNK := vNumEthnicUNK + 1;
                    END IF;
                  END IF;

                END IF;

                -- Set variable to check if next patient is same as current patient
                vPatientID := lPatients(i)."Patient";

              END LOOP;

              CLOSE cWeakCursor;

              -- NUMER Info
              dbms_lob.append(vOutputFile, Tab0000000000007 || '<component>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000008 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<templateId root="2.16.840.1.113883.10.20.27.3.5" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<value xsi:type=CD code=NUMER codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Numerator" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type="int" value="' || vNUMERCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));

              /***********************
              *    Ages 3-11 Years   *
              ***********************/
              vStratCount := 0;
              vSpecificStratificationId := '445A44EE-98BC-4614-B8B6-7A9521CD0794';

              MU_CQM_PKG.CQM155B2_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

              FETCH cWeakCursor BULK COLLECT INTO lPatients;

              FOR i IN 1..lPatients.COUNT LOOP
                IF lPatients(i)."Flag" = 1 THEN
                  vStratCount := vStratCount + 1;
                END IF;
              END LOOP;

              CLOSE cWeakCursor;

              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.4" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=NUMER codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Numerator" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vStratCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<id root="' || vSpecificStratificationId || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));


              /***********************
              *   Ages 12-17 Years   *
              ***********************/
              vStratCount := 0;
              vSpecificStratificationId := 'AA764699-1039-4E99-817C-6ED6E9E93735';

              MU_CQM_PKG.CQM155C2_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

              FETCH cWeakCursor BULK COLLECT INTO lPatients;

              FOR i IN 1..lPatients.COUNT LOOP
                IF lPatients(i)."Flag" = 1 THEN
                  vStratCount := vStratCount + 1;
                END IF;
              END LOOP;

              CLOSE cWeakCursor;

              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.4" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=NUMER codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Numerator" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vStratCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<id root="' || vSpecificStratificationId || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));


              -- NUMER Ethnicity
              IF vNumEthnicHisp > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.7" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="364699009" codeSystemName="SNOMED CT" displayName="Ethnic Group" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2135-2" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Hispanic or Latino" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumEthnicHisp || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Ethnicity
              IF vNumEthnicNotHisp > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.7" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="364699009" codeSystemName="SNOMED CT" displayName="Ethnic Group" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2186-5" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Not Hispanic or Latino" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumEthnicNotHisp || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Ethnicity
              IF vNumEthnicUNK > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.7" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="364699009" codeSystemName="SNOMED CT" displayName="Ethnic Group" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD nullFlavor=UNK/>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumEthnicUNK || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Race
              IF vNumRaceNative > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="1002-5" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="American Indian or Alaska Native" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumRaceNative || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Race
              IF vNumRaceAsian > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2028-9" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Asian" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumRaceAsian || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Race
              IF vNumRaceBlack > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2054-5" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Black or African American" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumRaceBlack || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Race
              IF vNumRaceIsland > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2076-8" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Native Hawaiian or Other Pacific Islander" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumRaceIsland || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Race
              IF vNumRaceWhite > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2106-3" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="White" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumRaceWhite || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Race
              IF vNumRaceOther > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2131-1" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Other Race" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumRaceOther || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Race
              IF vNumRaceUNK > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD nullFlavor=UNK/>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumRaceUNK || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Sex
              IF vNumSexF > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.6" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="184100006" codeSystemName="SNOMED-CT" displayName="Patient Sex" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=F codeSystem="2.16.840.1.113883.5.1" codeSystemName="HL7AdministrativeGenderCode" displayName="Female" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumSexF || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Sex
              IF vNumSexM > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.6" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="184100006" codeSystemName="SNOMED-CT" displayName="Patient Sex" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=M codeSystem="2.16.840.1.113883.5.1" codeSystemName="HL7AdministrativeGenderCode" displayName="Male" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumSexM || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Sex
              IF vNumSexUN > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.6" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="184100006" codeSystemName="SNOMED-CT" displayName="Patient Sex" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=UN codeSystem="2.16.840.1.113883.5.1" codeSystemName="HL7AdministrativeGenderCode" displayName="Undifferentiated" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumSexUN || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Sex
              IF vNumSexUNK > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.6" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="184100006" codeSystemName="SNOMED-CT" displayName="Patient Sex" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD nullFlavor=UNK/>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumSexUNK || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Payor
              IF vNUMERCount > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.24.3.55" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.9" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<id nullFlavor=NA />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.1" code="48768-6" codeSystemName=LOINC displayName="Payment source" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="349" codeSystem="2.16.840.1.113883.3.221.5" codeSystemName="Source of Payment Typology" displayName="Medicare" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNUMERCount || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Close
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<id root="' || TRIM(vSpecificNUMERId) || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000008 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000007 || '</component>' || CHR(13) || CHR(10));

            END IF;

            -- Numerator 3
            IF c.CQM = '155' THEN
              vPatientID        := 0;

              vNUMERCount       := 0;

              vNumSexM          := 0;
              vNumSexF          := 0;
              vNumSexUN         := 0;
              vNumSexUNK        := 0;

              vNumRaceNative    := 0;
              vNumRaceAsian     := 0;
              vNumRaceBlack     := 0;
              vNumRaceIsland    := 0;
              vNumRaceWhite     := 0;
              vNumRaceOther     := 0;
              vNumRaceUNK       := 0;

              vNumEthnicHisp    := 0;
              vNumEthnicNotHisp := 0;
              vNumEthnicUNK     := 0;

              MU_CQM_PKG.CQM155A3_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

              vSpecificNUMERId := 'B11C09BA-C864-430D-9DEC-16647793774C';

              FETCH cWeakCursor BULK COLLECT INTO lPatients;

              FOR i IN 1..lPatients.COUNT LOOP

                SELECT "Sex", NVL(TRIM("Ethnic"), ' ') "Ethnic" INTO vSex, vEthnic FROM PATIENT WHERE "Patient" = lPatients(i)."Patient";
                SELECT NVL(MAX(TRIM("Race")), ' ') "Race" INTO vRace FROM PTRACE WHERE "Patient" = lPatients(i)."Patient" AND "Deleted" = 0;

                IF lPatients(i)."Flag" = 1 THEN
                  vNUMERCount := vNUMERCount + 1;

                  IF vPatientID = 0 OR vPatientID <> lPatients(i)."Patient" THEN
                    IF vSex = 1 THEN
                      vNumSexM := vNumSexM + 1;
                    ELSIF vSex = 2 THEN
                      vNumSexF := vNumSexF + 1;
                    ELSIF vSex NOT IN (1, 2) THEN
                      vNumSexUN := vNumSexUN + 1;
                    ELSE
                      vNumSexUNK := vNumSexUNK + 1;
                    END IF;

                    --Not currently considering if a patient has multiple races.
                    --That might be a requirement but not needed for certification
                    IF vRace = 'NATIVE' THEN
                      vNumRaceNative := vNumRaceNative + 1;
                    ELSIF vRace = 'ASIAN' THEN
                      vNumRaceAsian := vNumRaceAsian + 1;
                    ELSIF vRace = 'BLACK' THEN
                      vNumRaceBlack := vNumRaceBlack + 1;
                    ELSIF vRace = 'ISLAND' THEN
                      vNumRaceIsland := vNumRaceIsland + 1;
                    ELSIF vRace = 'WHITE' THEN
                      vNumRaceWhite := vNumRaceWhite + 1;
                    ELSIF vRace = 'OTHER' THEN
                      vNumRaceOther := vNumRaceOther + 1;
                    ELSE
                      vNumRaceUNK := vNumRaceUNK + 1;
                    END IF;

                    IF vEthnic = 'HISP' THEN
                      vNumEthnicHisp := vNumEthnicHisp + 1;
                    ELSIF vEthnic = 'NHISP' THEN
                      vNumEthnicNotHisp := vNumEthnicNotHisp + 1;
                    ELSE
                      vNumEthnicUNK := vNumEthnicUNK + 1;
                    END IF;
                  END IF;

                END IF;

                -- Set variable to check if next patient is same as current patient
                vPatientID := lPatients(i)."Patient";

              END LOOP;

              CLOSE cWeakCursor;

              -- NUMER Info
              dbms_lob.append(vOutputFile, Tab0000000000007 || '<component>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000008 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<templateId root="2.16.840.1.113883.10.20.27.3.5" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<value xsi:type=CD code=NUMER codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Numerator" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type="int" value="' || vNUMERCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));

              /***********************
              *    Ages 3-11 Years   *
              ***********************/
              vStratCount := 0;
              vSpecificStratificationId := '445A44EE-98BC-4614-B8B6-7A9521CD0794';

              MU_CQM_PKG.CQM155B3_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

              FETCH cWeakCursor BULK COLLECT INTO lPatients;

              FOR i IN 1..lPatients.COUNT LOOP
                IF lPatients(i)."Flag" = 1 THEN
                  vStratCount := vStratCount + 1;
                END IF;
              END LOOP;

              CLOSE cWeakCursor;

              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.4" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=NUMER codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Numerator" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vStratCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<id root="' || vSpecificStratificationId || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));


              /***********************
              *   Ages 12-17 Years   *
              ***********************/
              vStratCount := 0;
              vSpecificStratificationId := 'AA764699-1039-4E99-817C-6ED6E9E93735';

              MU_CQM_PKG.CQM155C3_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

              FETCH cWeakCursor BULK COLLECT INTO lPatients;

              FOR i IN 1..lPatients.COUNT LOOP
                IF lPatients(i)."Flag" = 1 THEN
                  vStratCount := vStratCount + 1;
                END IF;
              END LOOP;

              CLOSE cWeakCursor;

              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.4" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=NUMER codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Numerator" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vStratCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<id root="' || vSpecificStratificationId || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));


              -- NUMER Ethnicity
              IF vNumEthnicHisp > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.7" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="364699009" codeSystemName="SNOMED CT" displayName="Ethnic Group" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2135-2" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Hispanic or Latino" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumEthnicHisp || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Ethnicity
              IF vNumEthnicNotHisp > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.7" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="364699009" codeSystemName="SNOMED CT" displayName="Ethnic Group" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2186-5" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Not Hispanic or Latino" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumEthnicNotHisp || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Ethnicity
              IF vNumEthnicUNK > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.7" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="364699009" codeSystemName="SNOMED CT" displayName="Ethnic Group" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD nullFlavor=UNK/>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumEthnicUNK || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Race
              IF vNumRaceNative > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="1002-5" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="American Indian or Alaska Native" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumRaceNative || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Race
              IF vNumRaceAsian > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2028-9" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Asian" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumRaceAsian || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Race
              IF vNumRaceBlack > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2054-5" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Black or African American" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumRaceBlack || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Race
              IF vNumRaceIsland > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2076-8" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Native Hawaiian or Other Pacific Islander" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumRaceIsland || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Race
              IF vNumRaceWhite > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2106-3" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="White" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumRaceWhite || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Race
              IF vNumRaceOther > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2131-1" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Other Race" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumRaceOther || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Race
              IF vNumRaceUNK > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD nullFlavor=UNK/>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumRaceUNK || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Sex
              IF vNumSexF > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.6" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="184100006" codeSystemName="SNOMED-CT" displayName="Patient Sex" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=F codeSystem="2.16.840.1.113883.5.1" codeSystemName="HL7AdministrativeGenderCode" displayName="Female" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumSexF || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Sex
              IF vNumSexM > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.6" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="184100006" codeSystemName="SNOMED-CT" displayName="Patient Sex" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=M codeSystem="2.16.840.1.113883.5.1" codeSystemName="HL7AdministrativeGenderCode" displayName="Male" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumSexM || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Sex
              IF vNumSexUN > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.6" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="184100006" codeSystemName="SNOMED-CT" displayName="Patient Sex" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=UN codeSystem="2.16.840.1.113883.5.1" codeSystemName="HL7AdministrativeGenderCode" displayName="Undifferentiated" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumSexUN || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Sex
              IF vNumSexUNK > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.6" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="184100006" codeSystemName="SNOMED-CT" displayName="Patient Sex" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD nullFlavor=UNK/>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNumSexUNK || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Payor
              IF vNUMERCount > 0 THEN
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.24.3.55" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.9" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<id nullFlavor=NA />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.1" code="48768-6" codeSystemName=LOINC displayName="Payment source" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="349" codeSystem="2.16.840.1.113883.3.221.5" codeSystemName="Source of Payment Typology" displayName="Medicare" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vNUMERCount || '" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
                dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              END IF;

              -- NUMER Close
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<id root="' || TRIM(vSpecificNUMERId) || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000008 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000007 || '</component>' || CHR(13) || CHR(10));

            END IF;


            -- This was just temp to pass certifcation. Will need to fix this properly.
            IF c.CQM = '156' THEN
              dbms_lob.append(vOutputFile, Tab0000000000007 || '<component>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000008 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<templateId root="2.16.840.1.113883.10.20.27.3.5" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<value xsi:type=CD code=NUMER codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Numerator" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type="int" value="0" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<id root="' || TRIM(vSpecificNUMER2Id) || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000008 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000007 || '</component>' || CHR(13) || CHR(10));
            END IF;

            /***********************
            *   DENOM EXCLUSION    *
            ***********************/

            -- DENEX Info
            IF vSpecificDENEXId IS NOT NULL THEN
              dbms_lob.append(vOutputFile, Tab0000000000007 || '<component>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000008 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<templateId root="2.16.840.1.113883.10.20.27.3.5" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<value xsi:type=CD code=DENEX codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Denominator Exclusions" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type="int" value="' || vDenExCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            IF vSpecificCQM = '74' AND vSpecificDENEXId IS NOT NULL THEN

              /***********************
              *    Ages 0-5 Years    *
              ***********************/
              vStratCount := 0;
              vSpecificStratificationId := '2C028996-D897-4162-ADBE-8619EDBE4E7D';

              MU_CQM_PKG.CQM74B_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

              FETCH cWeakCursor BULK COLLECT INTO lPatients;

              FOR i IN 1..lPatients.COUNT LOOP
                IF lPatients(i)."Ex" = 1 THEN
                  vStratCount := vStratCount + 1;
                END IF;
              END LOOP;

              CLOSE cWeakCursor;

              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.4" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=DENEX codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Denominator Exclusions" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vStratCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<id root="' || vSpecificStratificationId || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));


              /***********************
              *   Ages 6-12 Years    *
              ***********************/
              vStratCount := 0;
              vSpecificStratificationId := '59140979-7876-4A93-85EB-1276E2ED7584';

              MU_CQM_PKG.CQM74C_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

              FETCH cWeakCursor BULK COLLECT INTO lPatients;

              FOR i IN 1..lPatients.COUNT LOOP
                IF lPatients(i)."Ex" = 1 THEN
                  vStratCount := vStratCount + 1;
                END IF;
              END LOOP;

              CLOSE cWeakCursor;

              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.4" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=DENEX codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Denominator Exclusions" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vStratCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<id root="' || vSpecificStratificationId || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));


              /***********************
              *   Ages 13-20 Years   *
              ***********************/
              vStratCount := 0;
              vSpecificStratificationId := '154FFAC4-61BF-49CE-87C4-4FC415465F68';

              MU_CQM_PKG.CQM74D_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

              FETCH cWeakCursor BULK COLLECT INTO lPatients;

              FOR i IN 1..lPatients.COUNT LOOP
                IF lPatients(i)."Ex" = 1 THEN
                  vStratCount := vStratCount + 1;
                END IF;
              END LOOP;

              CLOSE cWeakCursor;

              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.4" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=DENEX codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Denominator Exclusions" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vStratCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<id root="' || vSpecificStratificationId || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            IF vSpecificCQM = '155' AND vSpecificDENEXId IS NOT NULL THEN

              /***********************
              *    Ages 3-11 Years   *
              ***********************/
              vStratCount := 0;
              vSpecificStratificationId := '445A44EE-98BC-4614-B8B6-7A9521CD0794';

              MU_CQM_PKG.CQM155B1_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

              FETCH cWeakCursor BULK COLLECT INTO lPatients;

              FOR i IN 1..lPatients.COUNT LOOP
                IF lPatients(i)."Ex" = 1 THEN
                  vStratCount := vStratCount + 1;
                END IF;
              END LOOP;

              CLOSE cWeakCursor;

              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.4" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=DENEX codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Denominator Exclusions" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vStratCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<id root="' || vSpecificStratificationId || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));


              /***********************
              *   Ages 12-17 Years   *
              ***********************/
              vStratCount := 0;
              vSpecificStratificationId := 'AA764699-1039-4E99-817C-6ED6E9E93735';

              MU_CQM_PKG.CQM155C1_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

              FETCH cWeakCursor BULK COLLECT INTO lPatients;

              FOR i IN 1..lPatients.COUNT LOOP
                IF lPatients(i)."Ex" = 1 THEN
                  vStratCount := vStratCount + 1;
                END IF;
              END LOOP;

              CLOSE cWeakCursor;

              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.4" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=DENEX codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Denominator Exclusions" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vStratCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<id root="' || vSpecificStratificationId || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEX Ethnicity
            IF vDenExEthnicHisp > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.7" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="364699009" codeSystemName="SNOMED CT" displayName="Ethnic Group" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2135-2" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Hispanic or Latino" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExEthnicHisp || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEX Ethnicity
            IF vDenExEthnicNotHisp > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.7" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="364699009" codeSystemName="SNOMED CT" displayName="Ethnic Group" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2186-5" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Not Hispanic or Latino" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExEthnicNotHisp || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEX Ethnicity
            IF vDenExEthnicUNK > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.7" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="364699009" codeSystemName="SNOMED CT" displayName="Ethnic Group" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD nullFlavor=UNK/>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExEthnicUNK || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEX Race
            IF vDenExRaceNative > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="1002-5" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="American Indian or Alaska Native" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExRaceNative || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEX Race
            IF vDenExRaceAsian > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2028-9" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Asian" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExRaceAsian || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEX Race
            IF vDenExRaceBlack > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2054-5" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Black or African American" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExRaceBlack || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEX Race
            IF vDenExRaceIsland > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2076-8" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Native Hawaiian or Other Pacific Islander" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExRaceIsland || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEX Race
            IF vDenExRaceWhite > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2106-3" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="White" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExRaceWhite || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEX Race
            IF vDenExRaceOther > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2131-1" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Other Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExRaceOther || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEX Race
            IF vDenExRaceUNK > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD nullFlavor=UNK/>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExRaceUNK || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEX Sex
            IF vDenExSexF > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.6" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="184100006" codeSystemName="SNOMED-CT" displayName="Patient Sex" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=F codeSystem="2.16.840.1.113883.5.1" codeSystemName="HL7AdministrativeGenderCode" displayName="Female" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExSexF || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEX Sex
            IF vDenExSexM > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.6" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="184100006" codeSystemName="SNOMED-CT" displayName="Patient Sex" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=M codeSystem="2.16.840.1.113883.5.1" codeSystemName="HL7AdministrativeGenderCode" displayName="Male" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExSexM || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEX Sex
            IF vDenExSexUN > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.6" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="184100006" codeSystemName="SNOMED-CT" displayName="Patient Sex" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=UN codeSystem="2.16.840.1.113883.5.1" codeSystemName="HL7AdministrativeGenderCode" displayName="Undifferentiated" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExSexUN || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEX Sex
            IF vDenExSexUNK > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.6" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="184100006" codeSystemName="SNOMED-CT" displayName="Patient Sex" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD nullFlavor=UNK/>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExSexUNK || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEX Payor
            IF vDenExCount > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.24.3.55" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.9" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<id nullFlavor=NA />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.1" code="48768-6" codeSystemName=LOINC displayName="Payment source" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="349" codeSystem="2.16.840.1.113883.3.221.5" codeSystemName="Source of Payment Typology" displayName="Medicare" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEX Close
            IF vSpecificDENEXId IS NOT NULL THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<id root="' || TRIM(vSpecificDENEXId) || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000008 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000007 || '</component>' || CHR(13) || CHR(10));
            END IF;


            /***********************
            *   DENOM EXCEPTION    *
            ***********************/

            -- DENEXCEP Info
            IF vSpecificDENEXCEPId IS NOT NULL THEN
              dbms_lob.append(vOutputFile, Tab0000000000007 || '<component>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000008 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<templateId root="2.16.840.1.113883.10.20.27.3.5" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<value xsi:type=CD code=DENEXCEP codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Denominator Exception" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type="int" value="' || vDenExcepCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            IF vSpecificCQM = '74' AND vSpecificDENEXCEPId IS NOT NULL THEN

              /***********************
              *    Ages 0-5 Years    *
              ***********************/
              vStratCount := 0;
              vSpecificStratificationId := '2C028996-D897-4162-ADBE-8619EDBE4E7D';

              MU_CQM_PKG.CQM74B_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

              FETCH cWeakCursor BULK COLLECT INTO lPatients;

              FOR i IN 1..lPatients.COUNT LOOP
                IF lPatients(i)."Exc" = 1 THEN
                  vStratCount := vStratCount + 1;
                END IF;
              END LOOP;

              CLOSE cWeakCursor;

              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.4" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=DENEXCEP codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Denominator Exception" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vStratCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<id root="' || vSpecificStratificationId || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));


              /***********************
              *   Ages 6-12 Years    *
              ***********************/
              vStratCount := 0;
              vSpecificStratificationId := '59140979-7876-4A93-85EB-1276E2ED7584';

              MU_CQM_PKG.CQM74C_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

              FETCH cWeakCursor BULK COLLECT INTO lPatients;

              FOR i IN 1..lPatients.COUNT LOOP
                IF lPatients(i)."Exc" = 1 THEN
                  vStratCount := vStratCount + 1;
                END IF;
              END LOOP;

              CLOSE cWeakCursor;

              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.4" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=DENEXCEP codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Denominator Exception" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vStratCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<id root="' || vSpecificStratificationId || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));


              /***********************
              *   Ages 13-20 Years   *
              ***********************/
              vStratCount := 0;
              vSpecificStratificationId := '154FFAC4-61BF-49CE-87C4-4FC415465F68';

              MU_CQM_PKG.CQM74D_DETAILS(cWeakCursor, vUser, vReportingStartDate, vReportingEndDate);

              FETCH cWeakCursor BULK COLLECT INTO lPatients;

              FOR i IN 1..lPatients.COUNT LOOP
                IF lPatients(i)."Exc" = 1 THEN
                  vStratCount := vStratCount + 1;
                END IF;
              END LOOP;

              CLOSE cWeakCursor;

              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.4" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.5.4" code="assertion" codeSystemName="ActCode" displayName="Assertion" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=DENEXCEP codeSystem="2.16.840.1.113883.5.1063" codeSystemName="ObservationValue" displayName="Denominator Exception" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vStratCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<id root="' || vSpecificStratificationId || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEXCEP Ethnicity
            IF vDenExcepEthnicHisp > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.7" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="364699009" codeSystemName="SNOMED CT" displayName="Ethnic Group" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2135-2" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Hispanic or Latino" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExcepEthnicHisp || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEXCEP Ethnicity
            IF vDenExcepEthnicNotHisp > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.7" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="364699009" codeSystemName="SNOMED CT" displayName="Ethnic Group" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2186-5" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Not Hispanic or Latino" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExcepEthnicNotHisp || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEXCEP Ethnicity
            IF vDenExcepEthnicUNK > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.7" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="364699009" codeSystemName="SNOMED CT" displayName="Ethnic Group" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD nullFlavor=UNK/>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExcepEthnicUNK || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEXCEP Race
            IF vDenExcepRaceNative > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="1002-5" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="American Indian or Alaska Native" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExcepRaceNative || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEXCEP Race
            IF vDenExcepRaceAsian > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2028-9" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Asian" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExcepRaceAsian || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEXCEP Race
            IF vDenExcepRaceBlack > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2054-5" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Black or African American" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExcepRaceBlack || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEXCEP Race
            IF vDenExcepRaceIsland > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2076-8" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Native Hawaiian or Other Pacific Islander" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExcepRaceIsland || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEXCEP Race
            IF vDenExcepRaceWhite > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2106-3" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="White" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExcepRaceWhite || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEXCEP Race
            IF vDenExcepRaceOther > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="2131-1" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp;amp; Ethnicity - CDC" displayName="Other Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExcepRaceOther || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEXCEP Race
            IF vDenExcepRaceUNK > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.8" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="103579009" codeSystemName="SNOMED-CT" displayName="Race" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD nullFlavor=UNK/>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExcepRaceUNK || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEXCEP Sex
            IF vDenExcepSexF > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.6" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="184100006" codeSystemName="SNOMED-CT" displayName="Patient Sex" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=F codeSystem="2.16.840.1.113883.5.1" codeSystemName="HL7AdministrativeGenderCode" displayName="Female" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExcepSexF || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEXCEP Sex
            IF vDenExcepSexM > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.6" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="184100006" codeSystemName="SNOMED-CT" displayName="Patient Sex" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=M codeSystem="2.16.840.1.113883.5.1" codeSystemName="HL7AdministrativeGenderCode" displayName="Male" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExcepSexM || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEXCEP Sex
            IF vDenExcepSexUN > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.6" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="184100006" codeSystemName="SNOMED-CT" displayName="Patient Sex" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code=UN codeSystem="2.16.840.1.113883.5.1" codeSystemName="HL7AdministrativeGenderCode" displayName="Undifferentiated" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExcepSexUN || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEXCEP Sex
            IF vDenExcepSexUNK > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.6" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.96" code="184100006" codeSystemName="SNOMED-CT" displayName="Patient Sex" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD nullFlavor=UNK/>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExcepSexUNK || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEXCEP Payor
            IF vDenExcepCount > 0 THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<entryRelationship typeCode=COMP>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.24.3.55" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<templateId root="2.16.840.1.113883.10.20.27.3.9" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<id nullFlavor=NA />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<code codeSystem="2.16.840.1.113883.6.1" code="48768-6" codeSystemName=LOINC displayName="Payment source" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<statusCode code=completed />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<value xsi:type=CD code="349" codeSystem="2.16.840.1.113883.3.221.5" codeSystemName="Source of Payment Typology" displayName="Medicare" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<entryRelationship typeCode=SUBJ inversionInd="true">' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '<observation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<templateId root="2.16.840.1.113883.10.20.27.3.3" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<code codeSystem="2.16.840.1.113883.5.4" code=MSRAGG codeSystemName="ActCode" displayName="Rate Aggregation" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<value xsi:type="int" value="' || vDenExcepCount || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000000000013 || '<methodCode codeSystem="2.16.840.1.113883.5.84" code=COUNT codeSystemName="ObservationMethod" displayName="Count" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000000000012 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '</entryRelationship>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</entryRelationship>' || CHR(13) || CHR(10));
            END IF;

            -- DENEXCEP Close
            IF vSpecificDENEXCEPId IS NOT NULL THEN
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '<reference typeCode=REFR>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '<externalObservation classCode=OBS moodCode=EVN>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000000000011 || '<id root="' || TRIM(vSpecificDENEXCEPId) || '" />' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000000000010 || '</externalObservation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab00000000000000009 || '</reference>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab000000000000008 || '</observation>' || CHR(13) || CHR(10));
              dbms_lob.append(vOutputFile, Tab0000000000007 || '</component>' || CHR(13) || CHR(10));
            END IF;


            /***********************
            *      CQM FOOTER      *
            ***********************/
            dbms_lob.append(vOutputFile, Tab00000000006 || '</organizer>' || CHR(13) || CHR(10));
            dbms_lob.append(vOutputFile, Tab000000005 || '</entry>' || CHR(13) || CHR(10));

          EXCEPTION WHEN OTHERS THEN
            vError := 7;
          END;

        END IF;

      END LOOP;

    EXCEPTION WHEN OTHERS THEN
      vError := 5;
    END;


    /************************
    *      QRDA CLOSE      *
    ***********************/

    dbms_lob.append(vOutputFile, Tab0000004 || '</section>' || CHR(13) || CHR(10));
    dbms_lob.append(vOutputFile, Tab00003 || '</component>' || CHR(13) || CHR(10));
    dbms_lob.append(vOutputFile, Tab002 || '</structuredBody>' || CHR(13) || CHR(10));
    dbms_lob.append(vOutputFile, Tab1 || '</component>' || CHR(13) || CHR(10));
    dbms_lob.append(vOutputFile, '</ClinicalDocument>' || CHR(13) || CHR(10));

  END IF;

END QRDA_Type3_XML;

PROCEDURE qrda_type1_stage3_xml_p(IN pproducer character, IN ppatient numeric, IN pyear numeric, INOUT perror integer, INOUT poutputfile clob) IS

  cursor cCQMList is
    select
      cqm.*,
('             <tr>
                <td>' || cqm."Description" || '</td>
                <td>' || cqm."SpecificId" || '</td>
                <td/>
              </tr>
') "XMLTrTd",
('        <!-- 1..* Organizers, each containing a reference to an eMeasure -->
        <entry>
          <organizer classCode="cluster" moodCode=EVN>
            <!-- This is the templateId for Measure Reference -->
            <templateId root="2.16.840.1.113883.10.20.24.3.98"/>
            <!-- This is the templateId for eMeasure Reference QDM -->
            <templateId root="2.16.840.1.113883.10.20.24.3.97"/>
            <id extension="' || cqm."IdExtension" || '" root="1.3.6.1.4.1.115"/>
            <statusCode code=completed/>
            <!-- Containing isBranch external references -->
            <reference typeCode=REFR>
              <externalDocument classCode=DOC moodCode=EVN>
                <!-- SHALL: This is the version specific identifier for eMeasure: QualityMeasureDocument/id it is a GUID-->
                <id extension="' || cqm."SpecificId" || '" root="2.16.840.1.113883.4.738"/>
                <!-- SHOULD This is the title of the eMeasure -->
                <text>' || cqm."Description" || '</text>
                <!-- SHOULD: setId is the eMeasure version neutral id  -->
                <setId root="' || cqm."NeutralId" || '"/>
              </externalDocument>
            </reference>
          </organizer>
        </entry>
') "XMLOrganizer"
    from (
          select
            22 CQM,
            'Preventive Care and Screening: Screening for High Blood Pressure and Follow-Up Documented' "Title",
            'Percentage of patients aged 18 years and older seen during the reporting period who were screened for high blood pressure AND a recommended follow-up plan is documented based on the current blood pressure (BP) reading as indicated' "Description",
            '40280382-610B-E7A4-0161-9A3A392C37D5' "SpecificId",
            '9A033A94-3D9B-11E1-8634-00237D5BF174' "NeutralId",
            'c86b0290-b85b-0136-51b2-0e95690c4dba' "IdExtension"
          from dual
          where 1=1
          union all
          select
            68 CQM,
            'Documentation of Current Medications in the Medical Record' "Title",
            'Percentage of visits for patients aged 18 years and older for which the eligible professional or eligible clinician attests to documenting a list of current medications using all immediate resources available on the date of the encounter. This list must include ALL known prescriptions, over-the-counters, herbals, and vitamin/mineral/dietary (nutritional) supplements AND must contain the medications; name, dosage, frequency and route of administration.' "Description",
            '40280382-5FA6-FE85-0160-0EA3E0012376' "SpecificId",
            '9A032D9C-3D9B-11E1-8634-00237D5BF174' "NeutralId",
            'b200fdf0-b85b-0136-51b1-0e95690c4dba' "IdExtension"
          from dual
          where 1=1
          union all
          select
            74 CQM,
            'Primary Caries Prevention Intervention as Offered by Primary Care Providers, including Dentists' "Title",
            'Percentage of children, age 0-20 years, who received a fluoride varnish application during the measurement period' "Description",
            '40280382-6258-7581-0162-92FEA60316EE' "SpecificId",
            '0B81B6BA-3B30-41BF-A2F3-95BDC9F558F2' "NeutralId",
            'c3716440-b85b-0136-51b0-0e95690c4dba' "IdExtension"
          from dual
          where 1=1
          union all
          select
            75 CQM,
            'Children Who Have Dental Decay or Cavities' "Title",
            'Percentage of children, age 0-20 years, who have had tooth decay or cavities during the measurement period' "Description",
            '40280382-6258-7581-0162-930923861702' "SpecificId",
            '61947125-4376-4A7B-AB7A-AC2BE9BD9138' "NeutralId",
            'b27d9cf0-b85b-0136-51b0-0e95690c4dba' "IdExtension"
          from dual
          where 1=1
          union all
          select
            127 CQM,
            'Pneumococcal Vaccination Status for Older Adults' "Title",
            'Percentage of patients 65 years of age and older who have ever received a pneumococcal vaccine' "Description",
            '40280382-6258-7581-0162-92877E281530' "SpecificId",
            '59657B9B-01BF-4979-A090-8534DA1D0516' "NeutralId",
            'd129f590-b85b-0136-51b0-0e95690c4dba' "IdExtension"
          from dual
          where 1=1
          union all
          select
            138 CQM,
            'Preventive Care and Screening: Tobacco Use: Screening and Cessation Intervention' "Title",
            'Percentage of patients aged 18 years and older who were screened for tobacco use one or more times within 24 months AND who received tobacco cessation intervention if identified as a tobacco user

Three rates are reported:
a. Percentage of patients aged 18 years and older who were screened for tobacco use one or more times within 24 months
b. Percentage of patients aged 18 years and older who were screened for tobacco use and identified as a tobacco user who received tobacco cessation intervention
c. Percentage of patients aged 18 years and older who were screened for tobacco use one or more times within 24 months AND who received tobacco cessation intervention if identified as a tobacco user' "Description",
            '40280382-6240-B6B9-0162-54815A310C2C' "SpecificId",
            'E35791DF-5B25-41BB-B260-673337BC44A8' "NeutralId",
            'b6e2a5d0-b85b-0136-51b2-0e95690c4dba' "IdExtension"
          from dual
          where 1=1
          union all
          select
            147 CQM,
            'Preventive Care and Screening: Influenza Immunization' "Title",
            'Percentage of patients aged 6 months and older seen for a visit between October 1 and March 31 who received an influenza immunization OR who reported previous receipt of an influenza immunization' "Description",
            '40280382-6240-B6B9-0162-5096917708E0' "SpecificId",
            'A244AA29-7D11-4616-888A-86E376BFCC6F' "NeutralId",
            'd3aad170-b85b-0136-51b1-0e95690c4dba' "IdExtension"
          from dual
          where 1=1
          union all
          select
            156 CQM,
            'Elderly Patients Who Ordered High Risk Medications' "Title",
            'Percentage of patients 65 years of age and older who were ordered high-risk medications. Two rates are reported.
a. Percentage of patients who were ordered at least one high-risk medication.
b. Percentage of patients who were ordered at least two of the same high-risk medications.' "Description",
            '40280382-6258-7581-0162-92C7A9811647' "SpecificId",
            'A3837FF8-1ABC-4BA9-800E-FD4E7953ADBD' "NeutralId",
            'c4d9b9e0-b85b-0136-51b1-0e95690c4dba' "IdExtension"
          from dual
          where 1=1
         ) cqm
    where 1=1
    order by cqm.CQM;

  cursor cVisits (
                  pPatient2 patient."Patient"%type,
                  pProducer2 producer."Producer"%type,
                  pUser2 users."User"%type,
                  pDateFrom2 date,
                  pDateTo2 date
                 ) is
    select
('            <entry>
              <act classCode=ACT moodCode=EVN>
                <!--Encounter performed Act -->
                <templateId extension="2017-08-01" root="2.16.840.1.113883.10.20.24.3.133"/>
                <id extension="' || v."Appointment" || '" root="1.3.6.1.4.1.115"/>
                <code code=ENC codeSystem="2.16.840.1.113883.5.6" codeSystemName="ActClass" displayName="Encounter"/>
                <entryRelationship typeCode=SUBJ>
                  <encounter classCode=ENC moodCode=EVN>
                    <!--  Encounter activities template -->
                    <templateId extension="2015-08-01" root="2.16.840.1.113883.10.20.22.4.49"/>
                    <!-- Encounter performed template -->
                    <templateId extension="2017-08-01" root="2.16.840.1.113883.10.20.24.3.23"/>
                    <id extension="' || v."Appointment" || '" root="1.3.6.1.4.1.115"/>
                      <code code="' || v."XMLCode" || '" codeSystem="' || v."UID" || '" codeSystemName="' || v."XMLCodeSystemName" || '"/>
                    <text>' || v."UIDDescription" || '</text>
                    <statusCode code=completed/>
                    <effectiveTime><low value=''' || v."DateFrom" || '''/><high value=''' || v."DateTo" || '''/></effectiveTime>
                    <author>
                      <templateId root="2.16.840.1.113883.10.20.24.3.155" extension="2017-08-01"/>
                      <time value=''' || v."DateFrom" || '''/>
                      <assignedAuthor>
                          <id nullFlavor=NA/>
                      </assignedAuthor>
                    </author>
                  </encounter>
                </entryRelationship>
              </act>
            </entry>
') "XMLVisit"
    from (
          with
          TmpCQMDataElements as (
                                 select
                                   qvscde2."Code",
                                   qvscde2."UID",
                                   qvscde2."UIDDescription",
                                   qvscde2."XMLCode",
                                   qvscde2."XMLCodeSystemName"
                                 from (
                                       select
                                         qvscde.*,
                                         (row_number() over (partition by qvscde."Code"
                                                             order by
                                                               qvscde."RowCount" desc,
                                                               qvscde."UID",
                                                               to_number(qvscde."CQMId"))) "RowNumber"
                                       from (
                                             select
                                               cde."CQMId",
                                               qvs."Code" "Code",
                                               cde."UID",
                                               cde."UIDDescription",
                                               replace(qvs."Code", 'M') "XMLCode",
                                               decode(substr(qvs."Code", 1, 1), 'M', 'CPT',
                                                                                'D', 'CDT',
                                                                                'G', 'HCPCS',
                                                                                'UNK1') "XMLCodeSystemName",
                                               (count(*) over (partition by
                                                                 qvs."Code",
                                                                 qvs."UID")) "RowCount"
                                             from
                                               CQMDataElement cde,
                                               qrdavalset qvs
                                             where 1=1
                                             and cde."CQMId" = qvs."CQMId"
                                             and cde."UID" = qvs."UID"
                                             and qvs."DataElement" = 3          -- encounters/visits
                                             and cde."UIDDescription" not like '% Not %'
                                            ) qvscde
                                       where 1=1
                                      ) qvscde2
                                 where 1=1
                                 and qvscde2."RowNumber" = 1
                                ),
          TmpAppoint1 as (
                          select /*+ INLINE */
                            ta1."Patient",
                            ta1."Date",
                            tat1."Type",
                            tat1."Id",
                            tat1."Treatment"
                          from
                            appoint ta1,
                            apptrx tat1
                          where 1=1
                          and ta1."Appointment" = tat1."Appointment"
                          and ta1."Type" in (0, 1, 2)
                          and ta1."Status" = 0
                          and exists (select 1
                                      from TmpCQMDataElements tcde1
                                      where 1=1
                                      and trim(tcde1."Code") = trim(tat1."Procedure"))
                          and ta1."Date" between pDateFrom2 and pDateTo2
                          and ta1."Patient" = pPatient2
                         ),
          TmpAppoint2 as (
                          select
                            trim(to_char(a."Appointment", '0000000000')) "Appointment",
                            trim(to_char((a."Date" + (a."From" / 1440)), 'RRRRMMDDHH24MISS')) "DateFrom",
                            trim(to_char((a."Date" + ((a."From" + a."Time0" + a."Time1" + a."Time2" + a."Time3" + a."Time4" + a."Time5") / 1440)), 'RRRRMMDDHH24MISS')) "DateTo",
                            htf.escape_sc(nvl(trim(tcde."XMLCode"), replace(trim(at."Procedure"), 'M'))) "XMLCode",
                            htf.escape_sc(nvl(trim(tcde."XMLCodeSystemName"), decode(substr(trim(at."Procedure"), 1, 1), 'M', 'CPT',
                                                                                                                         'D', 'CDT',
                                                                                                                         'G', 'HCPCS',
                                                                                                                         'SNOMED-CT'))) "XMLCodeSystemName",
                            htf.escape_sc(nvl(trim(tcde."UID"), '2.16.840.1.113883.6.12')) "UID",
                            htf.escape_sc(nvl(trim(tcde."UIDDescription"), 'Encounter, Performed: Office Visit')) "UIDDescription",
                            1 "EncounterType",
                            a."Patient",
                            at."Type",
                            at."Id",
                            at."Treatment"
                          from
                            appoint a,
                            apptrx at,
                            TmpCQMDataElements tcde
                          where 1=1
                          and a."Appointment" = at."Appointment"
                          and at."Procedure" = tcde."Code" (+)
                          and a."Type" in (0, 1, 2)
                          and a."Status" = 0
                          and a."Date" between pDateFrom2 and pDateTo2
                          and a."Producer" = pProducer2
                          and a."Patient" = pPatient2
                         )
          select
            ta2."Appointment",
            ta2."DateFrom",
            ta2."DateTo",
            ta2."XMLCode",
            ta2."XMLCodeSystemName",
            ta2."UID",
            ta2."UIDDescription",
            ta2."EncounterType"
          from TmpAppoint2 ta2
          where 1=1
          union all
          select
            (trim(to_char(t."Type", '00000')) || '-' || trim(to_char(t."Id", '0000000000')) || '-' || trim(to_char(t."Treatment", '00000'))) "Appointment",
            trim(to_char(t."AppDate", 'RRRRMMDDHH24MISS')) "DateFrom",
            trim(to_char(t."AppDate", 'RRRRMMDDHH24MISS')) "DateTo",
            htf.escape_sc(nvl(trim(tcde2."XMLCode"), replace(trim(t."Procedure"), 'M'))) "XMLCode",
            htf.escape_sc(nvl(trim(tcde2."XMLCodeSystemName"), decode(substr(trim(t."Procedure"), 1, 1), 'M', 'CPT',
                                                                                                         'D', 'CDT',
                                                                                                         'G', 'HCPCS',
                                                                                                         'SNOMED-CT'))) "XMLCodeSystemName",
            htf.escape_sc(nvl(trim(tcde2."UID"), '2.16.840.1.113883.6.12')) "UID",
            htf.escape_sc(nvl(trim(tcde2."UIDDescription"), ('Encounter, Performed: ' || trim(t."Description")))) "UIDDescription",
            2 "EncounterType"
          from
            trx t,
            TmpCQMDataElements tcde2
          where 1=1
          and t."Procedure" = tcde2."Code" (+)
          and t."Deleted" = 0
          and t."Type" in (1, 5)
          -- SF-00135895/SF-00136121/AX-16821
          and exists (select 1
                      from TmpAppoint1 ta1b
                      where 1=1
                      and ta1b."Date" <= t."AppDate"
                      and ta1b."Patient" = t."Patient")
          and not exists (select 1
                          from TmpAppoint1 ta1c
                          where 1=1
                          and ta1c."Treatment" = t."Treatment"
                          and ta1c."Id" = t."Id"
                          and ta1c."Type" = t."Type"
                          and ta1c."Patient" = t."Patient")
          and not exists (select 1
                          from TmpAppoint2 ta2b
                          where 1=1
                          and ta2b."Treatment" = t."Treatment"
                          and ta2b."Id" = t."Id"
                          and ta2b."Type" = t."Type"
                          and ta2b."Patient" = t."Patient")
          and t."AppDate" between pDateFrom2 and pDateTo2
          and t."AppUser" = pUser2
          and t."Patient" = pPatient2
          order by
            "EncounterType",
            "DateFrom",
            "DateTo",
            "Appointment"
         ) v
    where 1=1;

  cursor cSNOMEDVisits (
                        pPatient11 patient."Patient"%type,
                        pProducer11 producer."Producer"%type,
                        pDateFrom11 date,
                        pDateTo11 date
                       ) is
    -- CQM74 and CQM75 and CQM127
    select
('            <entry>
              <act classCode=ACT moodCode=EVN>
                <!--Encounter performed Act -->
                <templateId extension="2017-08-01" root="2.16.840.1.113883.10.20.24.3.133"/>
                <id extension="' || v2."Appointment" || '" root="1.3.6.1.4.1.115"/>
                <code code=ENC codeSystem="2.16.840.1.113883.5.6" codeSystemName="ActClass" displayName="Encounter"/>
                <entryRelationship typeCode=SUBJ>
                  <encounter classCode=ENC moodCode=EVN>
                    <!--  Encounter activities template -->
                    <templateId extension="2015-08-01" root="2.16.840.1.113883.10.20.22.4.49"/>
                    <!-- Encounter performed template -->
                    <templateId extension="2017-08-01" root="2.16.840.1.113883.10.20.24.3.23"/>
                    <id extension="' || v2."Appointment" || '" root="1.3.6.1.4.1.115"/>
                      <code code="' || v2."XMLCodeSD" || '" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED-CT"/>
                    <text>' || v2."UIDDescription" || '</text>
                    <statusCode code=completed/>
                    <effectiveTime><low value=''' || v2."DateFrom" || '''/><high value=''' || v2."DateTo" || '''/></effectiveTime>
                    <sdtc:dischargeDispositionCode code="' || v2."XMLCodeOC" || '" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED-CT"/>
                    <author>
                      <templateId root="2.16.840.1.113883.10.20.24.3.155" extension="2017-08-01"/>
                      <time value=''' || v2."DateFrom" || '''/>
                      <assignedAuthor>
                          <id nullFlavor=NA/>
                      </assignedAuthor>
                    </author>
                  </encounter>
                </entryRelationship>
              </act>
            </entry>
') "XMLSNOMEDVisit"
    from (
          with
          TmpSNOMEDVisits as (
                              select
                                a."Appointment",
                                a."Date",
                                a."From",
                                a."Time0",
                                a."Time1",
                                a."Time2",
                                a."Time3",
                                a."Time4",
                                a."Time5",
                                a."Producer",
                                a."Patient",
                                nvl(substr(trim(replace(rn."Note", '[SD] ')), 1, (instr(trim(replace(rn."Note", '[SD] ')), ' ') - 1)), trim(replace(rn."Note", '[SD] '))) "XMLCodeSD",
                                trim(replace(replace(rn."Note", ('[SD] ' || nvl(substr(trim(replace(rn."Note", '[SD] ')), 1, (instr(trim(replace(rn."Note", '[SD] ')), ' ') - 1)), trim(replace(rn."Note", '[SD] '))))), ' - ')) "XMLCodeSDDesc",
                                nvl(substr(trim(replace(rn2."Note", '[OC] ')), 1, (instr(trim(replace(rn2."Note", '[OC] ')), ' ') - 1)), trim(replace(rn2."Note", '[OC] '))) "XMLCodeOC"
                              from
                                appoint a,
                                reqnote rn,
                                reqnote rn2
                              where 1=1
                              and a."Appointment" = rn."Appointment"
                              and a."Appointment" = rn2."Appointment"
                              and a."Status" = 0
                              and a."Type" in (0, 1, 2)
                              and rn."Deleted" = 0
                              and rn."Note" like '[SD] %'
                              and rn2."Note" like '[OC] %'
                              and a."Date" <= pDateTo11
                              and a."Producer" = pProducer11
                              and a."Patient" = pPatient11
                              order by
                                a."Date",
                                a."From"
                             )
          select
            trim(to_char(tsv."Appointment", '0000000000')) "Appointment",
            trim(to_char((tsv."Date" + (tsv."From" / 1440)), 'RRRRMMDDHH24MISS')) "DateFrom",
            trim(to_char((tsv."Date" + ((tsv."From" + tsv."Time0" + tsv."Time1" + tsv."Time2" + tsv."Time3" + tsv."Time4" + tsv."Time5") / 1440)), 'RRRRMMDDHH24MISS')) "DateTo",
            htf.escape_sc(nvl(trim(tsv."XMLCodeSD"), 'UNK')) "XMLCodeSD",
            htf.escape_sc(nvl(trim(tsv."XMLCodeSDDesc"), 'Encounter, Performed: Office Visit')) "UIDDescription",
            htf.escape_sc(nvl(trim(tsv."XMLCodeOC"), 'UNK')) "XMLCodeOC"
          from TmpSNOMEDVisits tsv
          where 1=1
          and tsv."XMLCodeSD" in ('385763009', '385765002', '183452005', '32485007', '8715000')
          and tsv."XMLCodeOC" in ('428371000124100', '428361000124107')
         ) v2
    where 1=1
    union all
    -- CQM68 and CQM127
    select
('            <entry>
              <act classCode=ACT moodCode=EVN>
                <!--Encounter performed Act -->
                <templateId extension="2017-08-01" root="2.16.840.1.113883.10.20.24.3.133"/>
                <id extension="' || v2."Appointment" || '" root="1.3.6.1.4.1.115"/>
                <code code=ENC codeSystem="2.16.840.1.113883.5.6" codeSystemName="ActClass" displayName="Encounter"/>
                <entryRelationship typeCode=SUBJ>
                  <encounter classCode=ENC moodCode=EVN>
                    <!--  Encounter activities template -->
                    <templateId extension="2015-08-01" root="2.16.840.1.113883.10.20.22.4.49"/>
                    <!-- Encounter performed template -->
                    <templateId extension="2017-08-01" root="2.16.840.1.113883.10.20.24.3.23"/>
                    <id extension="' || v2."Appointment" || '" root="1.3.6.1.4.1.115"/>
                      <code code="' || v2."XMLCodeSD" || '" codeSystem="2.16.840.1.113883.6.96" codeSystemName="' || v2."XMLCodeSystemName" || '"/>
                    <text>' || v2."UIDDescription" || '</text>
                    <statusCode code=completed/>
                    <effectiveTime><low value=''' || v2."DateFrom" || '''/><high value=''' || v2."DateTo" || '''/></effectiveTime>
                    <author>
                      <templateId root="2.16.840.1.113883.10.20.24.3.155" extension="2017-08-01"/>
                      <time value=''' || v2."DateFrom" || '''/>
                      <assignedAuthor>
                          <id nullFlavor=NA/>
                      </assignedAuthor>
                    </author>
                  </encounter>
                </entryRelationship>
              </act>
            </entry>
') "XMLSNOMEDVisit"
    from (
          with
          TmpSNOMEDVisits as (
                              select
                                a."Appointment",
                                a."Date",
                                a."From",
                                a."Time0",
                                a."Time1",
                                a."Time2",
                                a."Time3",
                                a."Time4",
                                a."Time5",
                                a."Producer",
                                a."Patient",
                                nvl(substr(trim(replace(rn."Note", '[SD] ')), 1, (instr(trim(replace(rn."Note", '[SD] ')), ' ') - 1)), trim(replace(rn."Note", '[SD] '))) "XMLCodeSD",
                                trim(replace(replace(rn."Note", ('[SD] ' || nvl(substr(trim(replace(rn."Note", '[SD] ')), 1, (instr(trim(replace(rn."Note", '[SD] ')), ' ') - 1)), trim(replace(rn."Note", '[SD] '))))), ' - ')) "XMLCodeSDDesc"
                              from
                                appoint a,
                                reqnote rn
                              where 1=1
                              and a."Appointment" = rn."Appointment"
                              and a."Status" = 0
                              and a."Type" in (0, 1, 2)
                              and rn."Deleted" = 0
                              and rn."Note" like '[SD] %'
                              and a."Date" between pDateFrom11 and pDateTo11
                              and a."Producer" = pProducer11
                              and a."Patient" = pPatient11
                              order by
                                a."Date",
                                a."From"
                             )
          select
            trim(to_char(tsv."Appointment", '0000000000')) "Appointment",
            trim(to_char((tsv."Date" + (tsv."From" / 1440)), 'RRRRMMDDHH24MISS')) "DateFrom",
            trim(to_char((tsv."Date" + ((tsv."From" + tsv."Time0" + tsv."Time1" + tsv."Time2" + tsv."Time3" + tsv."Time4" + tsv."Time5") / 1440)), 'RRRRMMDDHH24MISS')) "DateTo",
            htf.escape_sc(nvl(trim(tsv."XMLCodeSD"), 'UNK')) "XMLCodeSD",
            htf.escape_sc(nvl(trim(tsv."XMLCodeSDDesc"), 'Encounter, Performed: Office Visit')) "UIDDescription",
            decode(substr(tsv."XMLCodeSD", 1, 1), 'M', 'CPT',
                                                  'D', 'CDT',
                                                  'G', 'HCPCS',
                                                  'SNOMED-CT') "XMLCodeSystemName"
          from TmpSNOMEDVisits tsv
          where 1=1
          and tsv."XMLCodeSD" in ('G0101', 'G0108', 'G0270', 'G0402', 'G0438', 'G0439', '10197000', '108220007', '108221006', '108224003',
                                  '108311000', '13607009', '14736009', '165171009', '18091003', '18512000', '185349003', '185463005', '185465003', '209099002',
                                  '210098006', '225967005', '252592009', '252624005', '270427003', '270430005', '273643004', '274803000', '277404009', '284015009',
                                  '30346009', '308335008', '32537008', '34651001', '35025007', '36228007', '370803007', '37894004', '385973000', '386372009',
                                  '390906007', '405096004', '406547006', '408983003', '410155007', '410157004', '410158009', '410160006', '410170008', '439708006',
                                  '439952009', '440524004', '46662001', '48423005', '50357006', '53555003', '54290001', '63547008', '66902005', '78318003',
                                  '83607001', '8411005', '86013001', '90526000', '91573000')
         ) v2
    where 1=1;

  cursor cMedicationOrders (
                            pPatient3 patient."Patient"%type,
                            pDateFrom3 date,
                            pDateTo3 date
                           ) is
    select
('            <entry>
              <!--Medication Order -->
              <substanceAdministration classCode=SBADM moodCode=RQO >
                <templateId root="2.16.840.1.113883.10.20.22.4.42" extension="2014-06-09"/>
                <!-- Medication, Order template -->
                <templateId root="2.16.840.1.113883.10.20.24.3.47" extension="2017-08-01"/>
                <id root="1.3.6.1.4.1.115" extension="' || m."Prescription" || '"/>
                <text>' || m."UIDDescription" || '</text>
                <statusCode code=active/>
                <effectiveTime xsi:type=IVL_TS><low value=''' || m."DateAdded" || '''/><high value=''' || m."DateAdded" || '''/></effectiveTime>
                <consumable>
                  <manufacturedProduct classCode=MANU>
                    <!-- Medication Information (consolidation) template -->
                    <templateId root="2.16.840.1.113883.10.20.22.4.23" extension="2014-06-09"/>
                    <id root="c4de27f0-b85b-0136-51b1-0e95690c4dba"/>
                    <manufacturedMaterial>
                        <code code="' || m."XMLCode" || '" codeSystem="' || m."UID" || '" codeSystemName="' || m."XMLCodeSystemName" || '"/>
                    </manufacturedMaterial>
                  </manufacturedProduct>
                </consumable>
                <author>
                  <templateId root="2.16.840.1.113883.10.20.24.3.155" extension="2017-08-01"/>
                  <time value=''' || m."DateAdded" || '''/>
                  <assignedAuthor>
                      <id nullFlavor=NA/>
                  </assignedAuthor>
                </author>
              </substanceAdministration>
            </entry>
') "XMLMedicationOrder"
    from (
          with
          TmpCQMDataElements as (
                                 select
                                   qvscde2."Code",
                                   qvscde2."UID",
                                   qvscde2."UIDDescription",
                                   qvscde2."XMLCode",
                                   qvscde2."XMLCodeSystemName"
                                 from (
                                       select
                                         qvscde.*,
                                         (row_number() over (partition by qvscde."Code"
                                                             order by
                                                               qvscde."RowCount" desc,
                                                               qvscde."UID",
                                                               to_number(qvscde."CQMId"))) "RowNumber"
                                       from (
                                             select
                                               cde."CQMId",
                                               qvs."Code" "Code",
                                               cde."UID",
                                               cde."UIDDescription",
                                               replace(qvs."Code", 'M') "XMLCode",
                                               decode(substr(qvs."Code", 1, 1), 'M', 'CPT',
                                                                                'D', 'CDT',
                                                                                'G', 'HCPCS',
                                                                                'RXNORM') "XMLCodeSystemName",
                                               (count(*) over (partition by
                                                                 qvs."Code",
                                                                 qvs."UID")) "RowCount"
                                             from
                                               CQMDataElement cde,
                                               qrdavalset qvs
                                             where 1=1
                                             and cde."CQMId" = qvs."CQMId"
                                             and cde."UID" = qvs."UID"
                                             and qvs."DataElement" = 9          -- medication orders
                                             and cde."UIDDescription" not like '% Not %'
                                             --
                                             -- for CQM138:
                                             --   insert into CQMDataElement values ('138', '2.16.840.1.113883.6.88', 'Medication, Order: High Risk Medications for the Elderly');
                                             --   insert into qrdavalset values ('138', 9, '2.16.840.1.113883.6.88', '993541');
                                             --
                                            ) qvscde
                                       where 1=1
                                      ) qvscde2
                                 where 1=1
                                 and qvscde2."RowNumber" = 1
                                )
          select
            trim(to_char(prh."Prescription", '0000000000')) "Prescription",
            htf.escape_sc(nvl(trim(tcde."XMLCode"), 'UNK')) "XMLCode",
            htf.escape_sc(nvl(trim(tcde."XMLCodeSystemName"), 'UNK')) "XMLCodeSystemName",
            htf.escape_sc(nvl(trim(tcde."UID"), '2.16.840.1.113883.6.88')) "UID",
            htf.escape_sc(nvl(trim(tcde."UIDDescription"), 'Medication, Order: High Risk Medications for the Elderly')) "UIDDescription",
            trim(to_char((ah."Date" + (ah."Time" / 1440)), 'RRRRMMDDHH24MISS')) "DateAdded",
            htf.escape_sc(nvl(trim(prh."RxNorm"), ' ')) "RxNorm"
          from
            prescrih prh,
            audithis ah,
            TmpCQMDataElements tcde
          where 1=1
          and prh."Audit" = ah."Audit"
          and trim(prh."RxNorm") = trim(tcde."Code")
          and prh."PrescripType" in (1, 2)
          and prh."ApprovalUser" <> 0
          and prh."Deleted" = 0
          and prh."IsVoided" = 0
          and ah."TableName" = 'PRESCRIP'
          and ah."HistoryType" = 1
          and exists (select 1
                      from prescrip px
                      where 1=1
                      and px."IsVoided" = 0
                      and px."Deleted" = 0
                      and px."Prescription" = prh."Prescription")
          and ah."Date" between pDateFrom3 and pDateTo3
          and prh."Patient" = pPatient3
          and trim(prh."Note") is null
          order by
            ah."Date",
            ah."Time",
            prh."Prescription"
         ) m
    where 1=1
    union all
    select
('            <entry>
              <!--Medication Order -->
              <substanceAdministration classCode=SBADM moodCode=RQO negationInd="true">
                <templateId root="2.16.840.1.113883.10.20.22.4.42" extension="2014-06-09"/>
                <!-- Medication, Order template -->
                <templateId root="2.16.840.1.113883.10.20.24.3.47" extension="2017-08-01"/>
                <id root="1.3.6.1.4.1.115" extension="' || m."Prescription" || '"/>
                <text>' || m."UIDDescription" || '</text>
                <statusCode code=active/>
                <effectiveTime xsi:type=IVL_TS><low value=''' || m."DateAdded" || '''/><high value=''' || m."DateAdded" || '''/></effectiveTime>
                <consumable>
                  <manufacturedProduct classCode=MANU>
                    <!-- Medication Information (consolidation) template -->
                    <templateId root="2.16.840.1.113883.10.20.22.4.23" extension="2014-06-09"/>
                    <id root="c4de27f0-b85b-0136-51b1-0e95690c4dba"/>
                    <manufacturedMaterial>
					'
					||
					CASE WHEN m."Note"='10548000699' THEN
					'<code nullFlavor=NA sdtc:valueSet="2.16.840.1.113883.3.600.1476"/>'
					ELSE
                        '<code code="' || m."XMLCode" || '" codeSystem="' || m."UID" || '" codeSystemName="' || m."XMLCodeSystemName" || '"/>
						'
					END
					||
                    '</manufacturedMaterial>
                  </manufacturedProduct>
                </consumable>
                <author>
                  <templateId root="2.16.840.1.113883.10.20.24.3.155" extension="2017-08-01"/>
                  <time value=''' || m."DateAdded" || '''/>
                  <assignedAuthor>
                      <id nullFlavor=NA/>
                  </assignedAuthor>
                </author>
                <entryRelationship typeCode=RSON>
                  <observation classCode=OBS moodCode=EVN>
                    <templateId root="2.16.840.1.113883.10.20.24.3.88" extension="2014-12-01"/>
                     <id root="1.3.6.1.4.1.115" extension="' || m."Prescription" || '"/>
                    <code code="77301-0" codeSystem="2.16.840.1.113883.6.1" displayName=reason codeSystemName=LOINC/>
                    <statusCode code=completed/>
                    <effectiveTime><low value=''' || m."DateAdded" || '''/><high nullFlavor=''UNK''/></effectiveTime>
						'||
						CASE WHEN m."Note"='10548000699' THEN
						'<value code="105480006" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED-CT" xsi:type=CD/>'
						ELSE
						'<value code="' || m."Note" || '" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED-CT" xsi:type=CD/>
						'
						END
                  ||'</observation>
                </entryRelationship>
              </substanceAdministration>
            </entry>
') "XMLMedicationOrder"
    from (
          with
          TmpCQMDataElements as (
                                 select
                                   qvscde2."Code",
                                   qvscde2."UID",
                                   qvscde2."UIDDescription",
                                   qvscde2."XMLCode",
                                   qvscde2."XMLCodeSystemName"
                                 from (
                                       select
                                         qvscde.*,
                                         (row_number() over (partition by qvscde."Code"
                                                             order by
                                                               qvscde."RowCount" desc,
                                                               qvscde."UID",
                                                               to_number(qvscde."CQMId"))) "RowNumber"
                                       from (
                                             select
                                               cde."CQMId",
                                               qvs."Code" "Code",
                                               cde."UID",
                                               cde."UIDDescription",
                                               replace(qvs."Code", 'M') "XMLCode",
                                               decode(substr(qvs."Code", 1, 1), 'M', 'CPT',
                                                                                'D', 'CDT',
                                                                                'G', 'HCPCS',
                                                                                'RXNORM') "XMLCodeSystemName",
                                               (count(*) over (partition by
                                                                 qvs."Code",
                                                                 qvs."UID")) "RowCount"
                                             from
                                               CQMDataElement cde,
                                               qrdavalset qvs
                                             where 1=1
                                             and cde."CQMId" = qvs."CQMId"
                                             and cde."UID" = qvs."UID"
                                             and qvs."DataElement" = 9          -- medication orders
                                             and cde."UIDDescription" not like '% Not %'
                                             --
                                             -- for CQM138:
                                             --   insert into CQMDataElement values ('138', '2.16.840.1.113883.6.88', 'Medication, Order: High Risk Medications for the Elderly');
                                             --   insert into qrdavalset values ('138', 9, '2.16.840.1.113883.6.88', '993541');
                                             --
                                            ) qvscde
                                       where 1=1
                                      ) qvscde2
                                 where 1=1
                                 and qvscde2."RowNumber" = 1
                                )
          select
            trim(to_char(prh."Prescription", '0000000000')) "Prescription",
            htf.escape_sc(nvl(trim(tcde."XMLCode"), 'UNK')) "XMLCode",
            htf.escape_sc(nvl(trim(tcde."XMLCodeSystemName"), 'UNK')) "XMLCodeSystemName",
            htf.escape_sc(nvl(trim(tcde."UID"), '2.16.840.1.113883.6.88')) "UID",
            htf.escape_sc(nvl(trim(tcde."UIDDescription"), 'Medication, Order: High Risk Medications for the Elderly')) "UIDDescription",
            trim(to_char((ah."Date" + (ah."Time" / 1440)), 'RRRRMMDDHH24MISS')) "DateAdded",
            htf.escape_sc(nvl(trim(prh."RxNorm"), ' ')) "RxNorm",
            htf.escape_sc(nvl(nvl(substr(trim(prh."Note"), 1, (instr(trim(prh."Note"), ' ') - 1)), trim(prh."Note")), 'Unknown')) "Note"
          from
            prescrih prh,
            audithis ah,
            TmpCQMDataElements tcde
          where 1=1
          and prh."Audit" = ah."Audit"
          and trim(prh."RxNorm") = trim(tcde."Code")
          and prh."PrescripType" in (1, 2)
          and prh."ApprovalUser" <> 0
          and prh."Deleted" = 0
          and prh."IsVoided" = 0
          and ah."TableName" = 'PRESCRIP'
          and ah."HistoryType" = 1
          and exists (select 1
                      from prescrip px
                      where 1=1
                      and px."IsVoided" = 0
                      and px."Deleted" = 0
                      and px."Prescription" = prh."Prescription")
          and ah."Date" between pDateFrom3 and pDateTo3
          and prh."Patient" = pPatient3
          and trim(prh."Note") is not null
          order by
            ah."Date",
            ah."Time",
            prh."Prescription"
         ) m
    where 1=1;

  cursor cProcedures (
                      pPatient4 patient."Patient"%type,
                      pDateFrom4 date,
                      pDateTo4 date
                     ) is
    select
('            <entry>
              <procedure classCode=PROC moodCode=EVN >
                <!--  Procedure performed template -->
                <templateId root="2.16.840.1.113883.10.20.24.3.64" extension="2017-08-01"/>
                <!-- Procedure Activity Procedure-->
                <templateId root="2.16.840.1.113883.10.20.22.4.14" extension="2014-06-09"/>
                <id root="1.3.6.1.4.1.115" extension="' || t2."IdExtension" || '"/>
                <code code="' || t2."XMLCode" || '" codeSystem="' || t2."UID" || '" codeSystemName="' || t2."XMLCodeSystemName" || '"/>
                <text>' || t2."UIDDescription" || '</text>
                <statusCode code=completed/>
                <effectiveTime><low value=''' || t2."TreatmentDate" || '''/><high value=''' || t2."TreatmentDate" || '''/></effectiveTime>
                <author>
                  <templateId root="2.16.840.1.113883.10.20.24.3.155" extension="2017-08-01"/>
                  <time value=''' || t2."TreatmentDate" || '''/>
                  <assignedAuthor>
                      <id nullFlavor=NA/>
                  </assignedAuthor>
                </author>
              </procedure>
            </entry>
') "XMLProcedure"
    from (
          with
          TmpCQMDataElements as (
                                 select
                                   qvscde2."Code",
                                   qvscde2."UID",
                                   qvscde2."UIDDescription",
                                   qvscde2."XMLCode",
                                   qvscde2."XMLCodeSystemName"
                                 from (
                                       select
                                         qvscde.*,
                                         (row_number() over (partition by qvscde."Code"
                                                             order by
                                                               qvscde."RowCount" desc,
                                                               qvscde."UID",
                                                               to_number(qvscde."CQMId"))) "RowNumber"
                                       from (
                                             select
                                               cde."CQMId",
                                               qvs."Code" "Code",
                                               cde."UID",
                                               cde."UIDDescription",
                                               replace(qvs."Code", 'M') "XMLCode",
                                               decode(substr(qvs."Code", 1, 1), 'M', 'CPT',
                                                                                'D', 'CDT',
                                                                                'G', 'HCPCS',
                                                                                'UNK') "XMLCodeSystemName",
                                               (count(*) over (partition by
                                                                 qvs."Code",
                                                                 qvs."UID")) "RowCount"
                                             from
                                               CQMDataElement cde,
                                               qrdavalset qvs
                                             where 1=1
                                             and cde."CQMId" = qvs."CQMId"
                                             and cde."UID" = qvs."UID"
                                             and qvs."DataElement" = 1          -- procedures
                                             and cde."UIDDescription" not like '% Not %'
                                            ) qvscde
                                       where 1=1
                                      ) qvscde2
                                 where 1=1
                                 and qvscde2."RowNumber" = 1
                                ),
          TmpPForm as (
                       select
                         pf1."FormCode",
                         pf1."Patient",
                         pf1."PForm"
                       from pform pf1
                       where 1=1
                       and pf1."Inactive" = 0
                       and pf1."Approved" = 1
                       and exists (select 1
                                   from fitem fi1
                                   where 1=1
                                   and fi1."Deleted" = 0
                                   and fi1."Code" = 'MDH_MEDREV'
                                   and fi1."FormCode" = pf1."FormCode")
                       and pf1."Patient" = pPatient4
                      ),
          TmpPItem as (
                       select
                         pi."PItem",
                         nvl(pi."AppDateTime", pi."AppDate") "AppDateTime",
                         trim(replace(mu_core_pkg.GetEPRFormItemAnswer_F(pi."FormCode",
                                                                         pi."Patient",
                                                                         pi."PForm",
                                                                         pi."FItem",
                                                                         pi."AuditNumber",
                                                                         pi."PItemCol"), pi."AnsListRefCode")) "Answer",
                         pi."AnsListRefCode"
                       from
                         pitem pi,
                         fitem fi
                       where 1=1
                       and pi."FItem" = fi."FItem"
                       and pi."FormCode" = fi."FormCode"
                       and pi."AppUser" > 0
                       and fi."Deleted" = 0
                       and fi."Code" = 'MDH_MEDREV'
                       and trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi."FormCode",
                                                                   pi."Patient",
                                                                   pi."PForm",
                                                                   pi."FItem",
                                                                   pi."AuditNumber",
                                                                   pi."PItemCol")) is not null
                       and exists (select 1
                                   from TmpPForm tpf
                                   where 1=1
                                   and tpf."PForm" = pi."PForm"
                                   and tpf."Patient" = pi."Patient"
                                   and tpf."FormCode" = pi."FormCode")
                       and pi."AnsListRefCode" = 'MEDREV_DOC'
                       and pi."AppDate" between pDateFrom4 and pDateTo4
                      ),
          TmpPForm2 as (
                        select
                          pf1."FormCode",
                          pf1."Patient",
                          pf1."PForm"
                        from pform pf1
                        where 1=1
                        and pf1."Inactive" = 0
                        and pf1."Approved" = 1
                        and exists (select 1
                                    from fitem fi1
                                    where 1=1
                                    and fi1."Deleted" = 0
                                    and fi1."Code" = 'MDH_PNEUM2'
                                    and fi1."FormCode" = pf1."FormCode")
                        and pf1."Patient" = pPatient4
                      ),
          TmpPItem2 as (
                        select
                          pi."PItem",
                          nvl(pi."AppDateTime", pi."AppDate") "AppDateTime",
                          trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi."FormCode",
                                                                  pi."Patient",
                                                                  pi."PForm",
                                                                  pi."FItem",
                                                                  pi."AuditNumber",
                                                                  pi."PItemCol")) "Answer"
                        from
                          pitem pi,
                          fitem fi
                        where 1=1
                        and pi."FItem" = fi."FItem"
                        and pi."FormCode" = fi."FormCode"
                        and pi."AppUser" > 0
                        and fi."Deleted" = 0
                        and fi."Code" = 'MDH_PNEUM2'
                        and trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi."FormCode",
                                                                    pi."Patient",
                                                                    pi."PForm",
                                                                    pi."FItem",
                                                                    pi."AuditNumber",
                                                                    pi."PItemCol")) is not null
                        and exists (select 1
                                    from TmpPForm2 tpf
                                    where 1=1
                                    and tpf."PForm" = pi."PForm"
                                    and tpf."Patient" = pi."Patient"
                                    and tpf."FormCode" = pi."FormCode")
                        and pi."AppDate" <= pDateTo4
                       )
          select
            (trim(to_char(t."Type", '00000')) || '-' || trim(to_char(t."Id", '0000000000')) || '-' || trim(to_char(t."Treatment", '00000'))) "IdExtension",
            htf.escape_sc(nvl(trim(tcde."XMLCode"), 'UNK')) "XMLCode",
            htf.escape_sc(nvl(trim(tcde."XMLCodeSystemName"), 'UNK')) "XMLCodeSystemName",
            htf.escape_sc(nvl(trim(tcde."UID"), '2.16.840.1.113883.6.13')) "UID",
            htf.escape_sc(nvl(trim(tcde."UIDDescription"), 'Procedure, Performed: Fluoride Varnish Application for Children')) "UIDDescription",
            trim(to_char(t."TreatmentDate", 'RRRRMMDDHH24MISS')) "TreatmentDate",
            1 "XMLType"
          from
            trx t,
            TmpCQMDataElements tcde
          where 1=1
          and t."Procedure" = tcde."Code"
          and t."Type" = 1
          and t."Deleted" = 0
          and t."Status" = 'C'
          and t."TreatmentDate" between pDateFrom4 and pDateTo4
          and t."Patient" = pPatient4
          union all
          -- CQM68
          select
            trim(to_char(tpi."PItem", '0000000000')) "IdExtension",
            htf.escape_sc(nvl(nvl(substr(trim(tpi."Answer"), 1, (instr(trim(tpi."Answer"), ' ') - 1)), trim(tpi."Answer")), 'Unknown')) "XMLCode",
            'SNOMED-CT' "XMLCodeSystemName",
            '2.16.840.1.113883.6.96' "UID",
            'Procedure, Performed: Documentation of current medications (procedure)'  "UIDDescription",
            trim(to_char(tpi."AppDateTime", 'RRRRMMDDHH24MISS')) "TreatmentDate",
            2 "XMLType"
          from TmpPItem tpi
          where 1=1
          union all
          -- CQM127
          select
            trim(to_char(tpi2."PItem", '0000000000')) "IdExtension",
            htf.escape_sc(nvl(substr(tpi2."Answer", 1, (instr(tpi2."Answer", ' ') - 1)), tpi2."Answer")) "XMLCode",
            'SNOMED-CT' "XMLCodeSystemName",
            '2.16.840.1.113883.6.96' "UID",
            'Procedure, Performed: Documentation of current medications (procedure)'  "UIDDescription",
            trim(to_char(tpi2."AppDateTime", 'RRRRMMDDHH24MISS')) "TreatmentDate",
            3 "XMLType"
          from TmpPItem2 tpi2
          where 1=1
          and nvl(substr(tpi2."Answer", 1, (instr(tpi2."Answer", ' ') - 1)), tpi2."Answer") in ('12866006', '394678003')
          order by
            "XMLType",
            "TreatmentDate"
         ) t2
    where 1=1
    union all
    -- CQM68
    select
('            <entry>
              <procedure classCode=PROC moodCode=EVN negationInd="true">
                <!--  Procedure performed template -->
                <templateId root="2.16.840.1.113883.10.20.24.3.64" extension="2017-08-01"/>
                <!-- Procedure Activity Procedure-->
                <templateId root="2.16.840.1.113883.10.20.22.4.14" extension="2014-06-09"/>
                <id root="1.3.6.1.4.1.115" extension="' || t2."IdExtension" || '"/>
                  <code code="428191000124101" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED-CT"/>
                <text>Procedure, Performed: Documentation of current medications (procedure)</text>
                <statusCode code=completed/>
                <effectiveTime><low value=''' || t2."AppDateTime" || '''/><high nullFlavor=''UNK''/></effectiveTime>
                <author>
                  <templateId root="2.16.840.1.113883.10.20.24.3.155" extension="2017-08-01"/>
                  <time value=''' || t2."AppDateTime" || '''/>
                  <assignedAuthor>
                      <id nullFlavor=NA/>
                  </assignedAuthor>
                </author>
                <entryRelationship typeCode=RSON>
                  <observation classCode=OBS moodCode=EVN>
                    <templateId root="2.16.840.1.113883.10.20.24.3.88" extension="2014-12-01"/>
                    <id root="1.3.6.1.4.1.115" extension="' || t2."IdExtension" || '"/>
                    <code code="77301-0" codeSystem="2.16.840.1.113883.6.1" displayName=reason codeSystemName=LOINC/>
                    <statusCode code=completed/>
                    <effectiveTime><low value=''' || t2."AppDateTime" || '''/><high nullFlavor=''UNK''/></effectiveTime>
                    <value code="' || t2."XMLCode" || '" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED-CT" xsi:type=CD/>
                  </observation>
                </entryRelationship>
              </procedure>
            </entry>
') "XMLProcedure"
    from (
          with
          TmpPForm as (
                       select
                         pf1."FormCode",
                         pf1."Patient",
                         pf1."PForm"
                       from pform pf1
                       where 1=1
                       and pf1."Inactive" = 0
                       and pf1."Approved" = 1
                       and exists (select 1
                                   from fitem fi1
                                   where 1=1
                                   and fi1."Deleted" = 0
                                   and fi1."Code" = 'MDH_MEDREV'
                                   and fi1."FormCode" = pf1."FormCode")
                       and pf1."Patient" = pPatient4
                      ),
          TmpPItem as (
                       select
                         pi."PItem",
                         nvl(pi."AppDateTime", pi."AppDate") "AppDateTime",
                         trim(replace(mu_core_pkg.GetEPRFormItemAnswer_F(pi."FormCode",
                                                                         pi."Patient",
                                                                         pi."PForm",
                                                                         pi."FItem",
                                                                         pi."AuditNumber",
                                                                         pi."PItemCol"), pi."AnsListRefCode")) "Answer",
                         pi."AnsListRefCode"
                       from
                         pitem pi,
                         fitem fi
                       where 1=1
                       and pi."FItem" = fi."FItem"
                       and pi."FormCode" = fi."FormCode"
                       and pi."AppUser" > 0
                       and fi."Deleted" = 0
                       and fi."Code" = 'MDH_MEDREV'
                       and trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi."FormCode",
                                                                   pi."Patient",
                                                                   pi."PForm",
                                                                   pi."FItem",
                                                                   pi."AuditNumber",
                                                                   pi."PItemCol")) is not null
                       and exists (select 1
                                   from TmpPForm tpf
                                   where 1=1
                                   and tpf."PForm" = pi."PForm"
                                   and tpf."Patient" = pi."Patient"
                                   and tpf."FormCode" = pi."FormCode")
                       and pi."AnsListRefCode" in ('MEDREV_R1', 'MEDREV_R2', 'MEDREV_R3', 'MEDREV_R4')
                       and pi."AppDate" between pDateFrom4 and pDateTo4
                      )
          select
            trim(to_char(tpi."PItem", '0000000000')) "IdExtension",
            htf.escape_sc(nvl(nvl(substr(trim(tpi."Answer"), 1, (instr(trim(tpi."Answer"), ' ') - 1)), trim(tpi."Answer")), 'Unknown')) "XMLCode",
            'SNOMED-CT' "XMLCodeSystemName",
            '2.16.840.1.113883.6.96' "UID",
            'Procedure, Performed: Documentation of current medications (procedure)'  "UIDDescription",
            trim(to_char(tpi."AppDateTime", 'RRRRMMDDHH24MISS')) "AppDateTime"
          from TmpPItem tpi
          where 1=1
          order by "AppDateTime"
         ) t2
    where 1=1;

  cursor cProceduresCQM147 (
                            pPatient patient."Patient"%type,
                            pDateFrom date,
                            pDateTo date,
                            pDateFrom2 date,
                            pDateTo2 date,
                            pDateFrom3 date,
                            pDateTo3 date
                           ) is
    select
('            <entry>
              <procedure classCode=PROC moodCode=EVN >
                <!--  Procedure performed template -->
                <templateId root="2.16.840.1.113883.10.20.24.3.64" extension="2017-08-01"/>
                <!-- Procedure Activity Procedure-->
                <templateId root="2.16.840.1.113883.10.20.22.4.14" extension="2014-06-09"/>
                <id root="1.3.6.1.4.1.115" extension="' || t2."IdExtension" || '"/>
                <code code="' || t2."XMLCode" || '" codeSystem="' || t2."UID" || '" codeSystemName="' || t2."XMLCodeSystemName" || '"/>
                <text>' || t2."UIDDescription" || '</text>
                <statusCode code=completed/>
                <effectiveTime><low value=''' || t2."DateFrom" || '''/><high value=''' || t2."DateTo" || '''/></effectiveTime>
                <author>
                  <templateId root="2.16.840.1.113883.10.20.24.3.155" extension="2017-08-01"/>
                  <time value=''' || t2."DateFrom" || '''/>
                  <assignedAuthor>
                      <id nullFlavor=NA/>
                  </assignedAuthor>
                </author>
              </procedure>
            </entry>
') "XMLProcedureCQM147"
    from (
          with
          TmpTrx as (
                     select
                       (trim(to_char(t."Type", '00000')) || '-' || trim(to_char(t."Id", '0000000000')) || '-' || trim(to_char(t."Treatment", '00000'))) "IdExtension",
                       trim(replace(t."Procedure", 'M')) "XMLCode",
                       'CPT' "XMLCodeSystemName",
                       '2.16.840.1.113883.6.12' "UID",
                       trim(t."Description") "UIDDescription",
                       trim(to_char(t."TreatmentDate", 'RRRRMMDDHH24MISS')) "DateFrom",
                       trim(to_char(t."TreatmentDate", 'RRRRMMDDHH24MISS')) "DateTo",
                       t."TreatmentDate",
                       trim(t."Procedure") "Procedure"
                     from trx t
                     where 1=1
                     and t."Type" = 1
                     and t."Deleted" = 0
                     and t."Status" = 'C'
                     and t."TreatmentDate" between pDateFrom3 and pDateTo
                     and t."Procedure" in (
                                           -- denominator
                                           'M90951', 'M90952', 'M90953', 'M90954', 'M90955', 'M90956', 'M90957', 'M90958', 'M90959', 'M90960',
                                           'M90961', 'M90962', 'M90963', 'M90964', 'M90965', 'M90966', 'M90967', 'M90968', 'M90969', 'M90970',
                                           'M99512', 'M90945', 'M90947', 'M90951', 'M90952', 'M90953', 'M90954', 'M90955', 'M90956', 'M90957',
                                           'M90958', 'M90959', 'M90960', 'M90961', 'M90962', 'M90963', 'M90964', 'M90965', 'M90966', 'M90967',
                                           'M90968', 'M90969', 'M90970',
                                           -- numerator
                                           'M90630', 'M90653', 'M90654', 'M90655', 'M90656', 'M90657', 'M90658', 'M90661', 'M90662', 'M90666',
                                           'M90667', 'M90668', 'M90673', 'M90685', 'M90686', 'M90687', 'M90688'
                                           )
                     and t."Patient" = pPatient
                ),
          TmpAppointSD as (
                           select
                             trim(to_char(a2."Appointment", '0000000000')) "IdExtension",
                             trim(a2."Procedure") "XMLCode",
                             'SNOMED-CT' "XMLCodeSystemName",
                             '2.16.840.1.113883.6.96' "UID",
                             trim(a2."Description") "UIDDescription",
                             trim(to_char(a2."DateFrom", 'RRRRMMDDHH24MISS')) "DateFrom",
                             trim(to_char(a2."DateTo", 'RRRRMMDDHH24MISS')) "DateTo",
                             a2."Date",
                             a2."Procedure"
                           from (
                                 select
                                   a."Appointment",
                                   nvl(substr(trim(replace(rn."Note", '[SD] ')), 1, (instr(trim(replace(rn."Note", '[SD] ')), ' ') - 1)), trim(replace(rn."Note", '[SD] '))) "Procedure",
                                   trim(replace(replace(rn."Note", ('[SD] ' || nvl(substr(trim(replace(rn."Note", '[SD] ')), 1, (instr(trim(replace(rn."Note", '[SD] ')), ' ') - 1)), trim(replace(rn."Note", '[SD] '))))), ' - ')) "Description",
                                   (a."Date" + (a."From" / 1440)) "DateFrom",
                                   (a."Date" + ((a."From" + a."Time0" + a."Time1" + a."Time2" + a."Time3" + a."Time4" + a."Time5") / 1440)) "DateTo",
                                   a."Date"
                                 from
                                   appoint a,
                                   reqnote rn
                                 where 1=1
                                 and a."Appointment" = rn."Appointment"
                                 and a."Status" = 0
                                 and a."Type" in (0, 1, 2)
                                 and rn."Deleted" = 0
                                 and rn."Note" like '[SD] %'
                                 and a."Date" between pDateFrom3 and pDateTo
                                 and a."Patient" = pPatient
                                ) a2
                           where 1=1
                          ),
          TmpPForm0 as (
                        select
                          pf."FormCode",
                          pf."Patient",
                          pf."PForm"
                        from pform pf
                        where 1=1
                        and pf."Inactive" = 0
                        and pf."Approved" = 1
                        and exists (select 1
                                    from fitem fi
                                    where 1=1
                                    and fi."Deleted" = 0
                                    and fi."Code" = 'MUSMPROC'
                                    and fi."FormCode" = pf."FormCode")
                        and exists (select 1
                                    from fitem fi2
                                    where 1=1
                                    and fi2."Deleted" = 0
                                    and fi2."Code" = 'MUSMDATE'
                                    and fi2."FormCode" = pf."FormCode")
                        and pf."Patient" = pPatient
                       ),
          TmpPItem0 as (
                        select
                          trim(to_char(pi."PItem", '0000000000')) "IdExtension",
                          trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi."FormCode",
                                                                  pi."Patient",
                                                                  pi."PForm",
                                                                  pi."FItem",
                                                                  pi."AuditNumber",
                                                                  pi."PItemCol")) "XMLCode",
                          'Procedure, Performed: Influenza Vaccination' "UIDDescription",
                          trim(to_char(nvl(pi."AppDateTime", pi."AppDate"), 'RRRRMMDDHH24MISS')) "DateFrom",
                          trim(to_char(nvl(pi."AppDateTime", pi."AppDate"), 'RRRRMMDDHH24MISS')) "DateTo",
                          nvl(pi."AppDateTime", pi."AppDate") "AppDateTime"
                        from
                          pitem pi,
                          fitem fi,
                          (select
                             pi3."FormCode",
                             pi3."Patient",
                             pi3."PForm",
                             pi3."PItem",
                             pi3."AnsDate"
                           from
                             pitem pi3,
                             fitem fi3
                           where 1=1
                           and pi3."FItem" = fi3."FItem"
                           and pi3."FormCode" = fi3."FormCode"
                           and pi3."AppUser" > 0
                           and fi3."Deleted" = 0
                           and fi3."Code" = 'MUSMDATE'
                           and pi3."AnsDate" between pDateFrom3 and pDateTo
                           and pi3."AnsType" = 4                                      --date answer only
                           and exists (select 1
                                       from TmpPForm0 tpf3
                                       where 1=1
                                       and tpf3."PForm" = pi3."PForm"
                                       and tpf3."Patient" = pi3."Patient"
                                       and tpf3."FormCode" = pi3."FormCode")) pifi
                        where 1=1
                        and pi."FItem" = fi."FItem"
                        and pi."FormCode" = fi."FormCode"
                        and pi."AppUser" > 0
                        and fi."Deleted" = 0
                        and fi."Code" = 'MUSMPROC'
                        and trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi."FormCode",
                                                                    pi."Patient",
                                                                    pi."PForm",
                                                                    pi."FItem",
                                                                    pi."AuditNumber",
                                                                    pi."PItemCol")) is not null
                        and exists (select 1
                                    from TmpPForm0 tpf
                                    where 1=1
                                    and tpf."PForm" = pi."PForm"
                                    and tpf."Patient" = pi."Patient"
                                    and tpf."FormCode" = pi."FormCode")
                        and pi."PForm" = pifi."PForm"
                        and pi."Patient" = pifi."Patient"
                        and pi."FormCode" = pifi."FormCode"
                       )
          select
            htf.escape_sc(nvl(trim(t1."IdExtension"), '00000000000000000000')) "IdExtension",
            htf.escape_sc(nvl(trim(t1."XMLCode"), 'UNK')) "XMLCode",
            htf.escape_sc(nvl(trim(t1."XMLCodeSystemName"), 'CPT')) "XMLCodeSystemName",
            htf.escape_sc(nvl(trim(t1."UID"), '2.16.840.1.113883.6.12')) "UID",
            htf.escape_sc(nvl(trim(t1."UIDDescription"), 'Procedure, Performed: Influenza Vaccination')) "UIDDescription",
            htf.escape_sc(nvl(trim(t1."DateFrom"), '00000000000000000000')) "DateFrom",
            htf.escape_sc(nvl(trim(t1."DateTo"), '00000000000000000000')) "DateTo",
            1 "XMLType"
          from TmpTrx t1
          where 1=1
          and ((((t1."TreatmentDate" > pDateTo2                               -- Mar. 31st
                  and t1."TreatmentDate" <= pDateTo)                               -- Dec. 31st
                 or (t1."TreatmentDate" >= pDateFrom2                               -- Oct. 1st
                     and t1."TreatmentDate" < pDateFrom)                                 -- Jan. 1st
                 or (t1."TreatmentDate" >= pDateFrom                                -- Jan. 1st
                     and t1."TreatmentDate" <= pDateTo2))                               -- Mar. 31st
                and t1."Procedure" in ('M90951', 'M90952', 'M90953', 'M90954', 'M90955', 'M90956', 'M90957', 'M90958', 'M90959', 'M90960',
                                       'M90961', 'M90962', 'M90963', 'M90964', 'M90965', 'M90966', 'M90967', 'M90968', 'M90969', 'M90970',
                                       'M99512', 'M90945', 'M90947', 'M90951', 'M90952', 'M90953', 'M90954', 'M90955', 'M90956', 'M90957',
                                       'M90958', 'M90959', 'M90960', 'M90961', 'M90962', 'M90963', 'M90964', 'M90965', 'M90966', 'M90967',
                                       'M90968', 'M90969', 'M90970'))
               or ((t1."TreatmentDate" between pDateFrom3 and pDateTo3)
                    and t1."Procedure" in ('M90630', 'M90653', 'M90654', 'M90655', 'M90656', 'M90657', 'M90658', 'M90661', 'M90662', 'M90666',
                                           'M90667', 'M90668', 'M90673', 'M90685', 'M90686', 'M90687', 'M90688')))
          union all
          select
            htf.escape_sc(nvl(trim(arn."IdExtension"), '00000000000000000000')) "IdExtension",
            htf.escape_sc(nvl(trim(arn."XMLCode"), 'UNK')) "XMLCode",
            htf.escape_sc(nvl(trim(arn."XMLCodeSystemName"), 'SNOMED-CT')) "XMLCodeSystemName",
            htf.escape_sc(nvl(trim(arn."UID"), '2.16.840.1.113883.6.96')) "UID",
            htf.escape_sc(nvl(trim(arn."UIDDescription"), 'Procedure, Performed: Influenza Vaccination')) "UIDDescription",
            htf.escape_sc(nvl(trim(arn."DateFrom"), '00000000000000000000')) "DateFrom",
            htf.escape_sc(nvl(trim(arn."DateTo"), '00000000000000000000')) "DateTo",
            2 "XMLType"
          from TmpAppointSD arn
          where 1=1
          and ((arn."Date" > pDateTo2                               -- Mar. 31st
                and arn."Date" <= pDateTo                               -- Dec. 31st
                and arn."Procedure" in ('12843005', '18170008', '185349003', '185463005', '185465003', '19681004', '207195004', '270427003', '270430005', '308335008',
                                        '390906007', '406547006', '439708006', '87790002', '90526000'))
               or (arn."Date" >= pDateFrom2                               -- Oct. 1st
                   and arn."Date" < pDateFrom                                 -- Jan. 1st
                   and arn."Procedure" in ('11797002', '12843005', '18170008', '185316007', '185317003', '185318008', '185320006', '185321005', '185349003', '185463005',
                                           '185465003', '19681004', '207195004', '270424005', '270427003', '270430005', '308335008', '308720009', '386473003', '390906007',
                                           '401267002', '401271004', '406547006', '438515009', '438516005', '439708006', '445450000', '448337001', '4525004', '87790002',
                                           '90526000'))
               or (arn."Date" >= pDateFrom                                -- Jan. 1st
                   and arn."Date" <= pDateTo2                               -- Mar. 31st
                   and arn."Procedure" in (
                                           -- regular season
                                           '12843005', '18170008', '185349003', '185463005', '185465003', '19681004', '207195004', '270427003', '270430005', '308335008',
                                           '390906007', '406547006', '439708006', '87790002', '90526000',
                                           -- influenza season
                                           '11797002', '12843005', '18170008', '185316007', '185317003', '185318008', '185320006', '185321005', '185349003', '185463005',
                                           '185465003', '19681004', '207195004', '270424005', '270427003', '270430005', '308335008', '308720009', '386473003', '390906007',
                                           '401267002', '401271004', '406547006', '438515009', '438516005', '439708006', '445450000', '448337001', '4525004', '87790002',
                                           '90526000'
                                           )))
          union all
          select
            htf.escape_sc(nvl(trim(arn."IdExtension"), '00000000000000000000')) "IdExtension",
            htf.escape_sc(nvl(trim(arn."XMLCode"), 'UNK')) "XMLCode",
            htf.escape_sc(nvl(trim(arn."XMLCodeSystemName"), 'HCPCS')) "XMLCodeSystemName",
            htf.escape_sc(nvl(trim(arn."UID"), '2.16.840.1.113883.6.285')) "UID",
            htf.escape_sc(nvl(trim(arn."UIDDescription"), 'Procedure, Performed: Influenza Vaccination')) "UIDDescription",
            htf.escape_sc(nvl(trim(arn."DateFrom"), '00000000000000000000')) "DateFrom",
            htf.escape_sc(nvl(trim(arn."DateTo"), '00000000000000000000')) "DateTo",
            3 "XMLType"
          from TmpAppointSD arn
          where 1=1
          and ((arn."Date" > pDateTo2                               -- Mar. 31st
                and arn."Date" <= pDateTo                               -- Dec. 31st
                and arn."Procedure" in ('G0438', 'G0439'))
               or (arn."Date" >= pDateFrom2                               -- Oct. 1st
                   and arn."Date" < pDateFrom                                 -- Jan. 1st
                   and arn."Procedure" in ('G0438', 'G0439'))
               or (arn."Date" >= pDateFrom                                -- Jan. 1st
                   and arn."Date" <= pDateTo2                               -- Mar. 31st
                   and arn."Procedure" in ('G0438', 'G0439')))
          union all
          select
            htf.escape_sc(nvl(trim(tpi01."IdExtension"), '00000000000000000000')) "IdExtension",
            htf.escape_sc(nvl(trim(tpi01."XMLCode"), 'UNK')) "XMLCode",
            htf.escape_sc('SNOMED-CT') "XMLCodeSystemName",
            htf.escape_sc('2.16.840.1.113883.6.96') "UID",
            htf.escape_sc(nvl(trim(tpi01."UIDDescription"), 'Procedure, Performed: Influenza Vaccination')) "UIDDescription",
            htf.escape_sc(nvl(trim(tpi01."DateFrom"), '00000000000000000000')) "DateFrom",
            htf.escape_sc(nvl(trim(tpi01."DateTo"), '00000000000000000000')) "DateTo",
            4 "XMLType"
          from TmpPItem0 tpi01
          where 1=1
          and ((((tpi01."AppDateTime" > pDateTo2                               -- Mar. 31st
                  and tpi01."AppDateTime" <= pDateTo)                               -- Dec. 31st
                 or (tpi01."AppDateTime" >= pDateFrom2                               -- Oct. 1st
                     and tpi01."AppDateTime" < pDateFrom)                                 -- Jan. 1st
                 or (tpi01."AppDateTime" >= pDateFrom                                -- Jan. 1st
                     and tpi01."AppDateTime" <= pDateTo2))                               -- Mar. 31st
                and tpi01."XMLCode" in ('302497006', '14684005', '225230008', '238318009', '238319001', '238321006', '238322004', '238323009', '428648006', '676002', '71192002'))
               or ((tpi01."AppDateTime" between pDateFrom3 and pDateTo3)
                   and tpi01."XMLCode" = '86198006'))
          union all
          select
            htf.escape_sc(nvl(trim(tpi02."IdExtension"), '00000000000000000000')) "IdExtension",
            htf.escape_sc(nvl(trim(tpi02."XMLCode"), 'UNK')) "XMLCode",
            htf.escape_sc('HCPCS') "XMLCodeSystemName",
            htf.escape_sc('2.16.840.1.113883.6.285') "UID",
            htf.escape_sc(nvl(trim(tpi02."UIDDescription"), 'Procedure, Performed: Influenza Vaccination')) "UIDDescription",
            htf.escape_sc(nvl(trim(tpi02."DateFrom"), '00000000000000000000')) "DateFrom",
            htf.escape_sc(nvl(trim(tpi02."DateTo"), '00000000000000000000')) "DateTo",
            5 "XMLType"
          from TmpPItem0 tpi02
          where 1=1
          and tpi02."AppDateTime" between pDateFrom3 and pDateTo3
          and tpi02."XMLCode" in ('G0008', 'Q2034', 'Q2035', 'Q2036', 'Q2037', 'Q2038', 'Q2039')
          order by
            "XMLType",
            "DateFrom",
            "DateTo"
         ) t2
    where 1=1;

  cursor cMedicalProblems (
                           pPatient5 patient."Patient"%type,
                           pProducer5 producer."Producer"%type,
                           pUser5 users."User"%type,
                           pDateFrom5 date,
                           pDateTo5 date,
                           pDateFrom5B date,
                           pDateTo5B date,
                           pDateFrom5C date,
                           pDateTo5C date
                          ) is
    select
('            <entry>
              <act classCode=ACT moodCode=EVN>
                <!-- Conforms to C-CDA 2.1 Problem Concern Act (V3) -->
                <templateId root="2.16.840.1.113883.10.20.22.4.3" extension="2015-08-01" />
                <!-- Diagnosis Concern Act -->
                <templateId root="2.16.840.1.113883.10.20.24.3.137" extension="2017-08-01"/>
                <id root="1.3.6.1.4.1.115" extension="' || mp."IdExtension" || '"/>
                <code code=CONC codeSystem="2.16.840.1.113883.5.6" displayName="Concern" />
                <statusCode code=completed />
                <effectiveTime>
                  <low value=''' || mp."OnsetDate" || '''/>
                  <high nullFlavor=''UNK''/>
                </effectiveTime>
                <entryRelationship typeCode=SUBJ>
                  <observation classCode=OBS moodCode=EVN>
                    <!-- Conforms to C-CDA R2.1 Problem Observation (V3) -->
                    <templateId root="2.16.840.1.113883.10.20.22.4.4" extension="2015-08-01" />
                    <!-- Diagnosis template -->
                    <templateId root="2.16.840.1.113883.10.20.24.3.135" extension="2017-08-01" />
                    <id root="1.3.6.1.4.1.115" extension="' || mp."IdExtension" || '"/>
                    <code code="29308-4" codeSystem="2.16.840.1.113883.6.1">
                      <translation code="282291009" codeSystem="2.16.840.1.113883.6.96"/>
                    </code>
                    <statusCode code=completed />
                    <effectiveTime>
                      <low value=''' || mp."OnsetDate" || '''/>
                      <high nullFlavor=''UNK''/>
                    </effectiveTime>' ||
                    (case mp."XMLCode"
                      when 'UNK' then
                        '
                        <value xsi:type=CD code="404.92" codeSystem="2.16.840.1.113883.6.103" codeSystemName="ICD-9-CM">
                      <translation code="I13.0" codeSystem="2.16.840.1.113883.6.90" codeSystemName="ICD-10-CM"/>
                      </value>
                      '
                       else
                        '
                         <value xsi:type=CD code="' || mp."XMLCode" || '" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED-CT"></value>
                         '
                     end) ||
                  '</observation>
                </entryRelationship>
              </act>
            </entry>
') "XMLDiagnosis"
    from (
          with
          TmpCQMDataElements as (
                                 select
                                   qvscde2."Code",
                                   qvscde2."UID",
                                   qvscde2."UIDDescription",
                                   qvscde2."XMLCode",
                                   qvscde2."XMLCodeSystemName"
                                 from (
                                       select
                                         qvscde.*,
                                         (row_number() over (partition by qvscde."Code"
                                                             order by
                                                               qvscde."RowCount" desc,
                                                               qvscde."UID",
                                                               to_number(qvscde."CQMId"))) "RowNumber"
                                       from (
                                             select
                                               cde."CQMId",
                                               qvs."Code" "Code",
                                               cde."UID",
                                               cde."UIDDescription",
                                               replace(qvs."Code", 'M') "XMLCode",
                                               decode(substr(qvs."Code", 1, 1), 'M', 'CPT',
                                                                                'D', 'CDT',
                                                                                'G', 'HCPCS',
                                                                                'SNOMEDCT') "XMLCodeSystemName",
                                               (count(*) over (partition by
                                                                 qvs."Code",
                                                                 qvs."UID")) "RowCount"
                                             from
                                               CQMDataElement cde,
                                               qrdavalset qvs
                                             where 1=1
                                             and cde."CQMId" = qvs."CQMId"
                                             and cde."UID" = qvs."UID"
                                             and qvs."DataElement" = 0          -- diagnosis
                                             and cde."UIDDescription" not like '% Not %'
                                            ) qvscde
                                       where 1=1
                                      ) qvscde2
                                 where 1=1
                                 and qvscde2."RowNumber" = 1
                                ),
          -- CQM22
          TmpAppoint1 as (
                          select /*+ INLINE */
                            ta1."Producer",
                            ta1."Patient",
                            ta1."Date",
                            tat1."Procedure",
                            tat1."Type",
                            tat1."Id",
                            tat1."Treatment"
                          FROM
                            APPOINT ta1,
                            APPTRX tat1
                          WHERE 1=1
                          AND ta1."Type" IN (0, 1, 2)
                          AND ta1."Status" = 0
                          AND ta1."Date" BETWEEN pDateFrom5 AND pDateTo5
                          AND ta1."Appointment" = tat1."Appointment"
                          -- SF-00192551/AX-21332
                          and tat1."Procedure" in ('M90791', 'M90792', 'M92002', 'M92004', 'M92012', 'M92014', 'M99201', 'M99202', 'M99203', 'M99204',
                                                   'M99205', 'M99212', 'M99213', 'M99214', 'M99215', 'M99281', 'M99282', 'M99283', 'M99284', 'M99285',
                                                   'M99304', 'M99305', 'M99306', 'M99307', 'M99308', 'M99309', 'M99310', 'M99318', 'M99324', 'M99325',
                                                   'M99326', 'M99327', 'M99328', 'M99334', 'M99335', 'M99336', 'M99337', 'M99341', 'M99342', 'M99343',
                                                   'M99344', 'M99345', 'M99347', 'M99348', 'M99349', 'M99350', 'M99385', 'M99386', 'M99387', 'M99395',
                                                   'M99396', 'M99397', 'D7140', 'D7210', 'G0101', 'G0402', 'G0438', 'G0439')
                          and ta1."Patient" = pPatient5
                         ),
          TmpAppoint2 as (
                          select
                            ta1a."Patient",
                            ta1a."Date"
                          from TmpAppoint1 ta1a
                          where 1=1
                          and ta1a."Producer" = pProducer5
                          union all
                          select
                            t1b."Patient",
                            t1b."TreatmentDate" "Date"
                          from trx t1b
                          where 1=1
                          and t1b."Deleted" = 0
                          and t1b."Type" in (1, 5)
                          and t1b."AppDate" between pDateFrom5 and pDateTo5
                          and t1b."AppUser" = pUser5
                          -- SF-00135895/SF-00136121/AX-16821
                          and exists (select 1
                                      from TmpAppoint1 ta1b
                                      where 1=1
                                      and ta1b."Date" <= t1b."AppDate"
                                      and ta1b."Patient" = t1b."Patient")
                          and t1b."Patient" = pPatient5
                         )
          -- CQM22
          select distinct
            trim(to_char(ph1."PtAlert", '0000000000')) "IdExtension",
            htf.escape_sc(nvl(trim(tcde1."XMLCode"), 'UNK')) "XMLCode",
            htf.escape_sc(nvl(trim(tcde1."XMLCodeSystemName"), 'UNK')) "XMLCodeSystemName",
            htf.escape_sc(nvl(trim(tcde1."UID"), '2.16.840.1.113883.6.96')) "UID",
            htf.escape_sc(nvl(trim(tcde1."UIDDescription"), 'Diagnosis: Dental Caries')) "UIDDescription",
            trim(to_char(nvl(ph1."OnsetDate", trunc(ph1."AddDateTime")), 'RRRRMMDDHH24MISS')) "OnsetDate"
          from
            ptalerth ph1,
            TmpCQMDataElements tcde1,
            TmpAppoint2 ta2
          where 1=1
          and trim(ph1."SNOCode") = trim(tcde1."Code" (+))
          and ph1."Patient" = ta2."Patient"
          and ph1."AlertType" = 2
          and ph1."Status" = 0
          and ph1."Deleted" = 0
          -- start: SF-00192551/AX-21332
          and ph1."SNOCode" in ('102932008', '10725009', '10964002', '1201005', '123799005', '123800009', '14973001', '170577003', '170578008', '170579000',
                                '170586008', '185264001', '185716009', '185717000', '194783001', '194785008', '194788005', '194791005', '19769006', '23130000',
                                '233815004', '233941006', '233942004', '233943009', '233944003', '233945002', '233946001', '234072000', '234073005', '234075003',
                                '237279007', '270440008', '28119000', '288250001', '31992008', '34742003', '371125006', '371622005', '38341003', '39018007',
                                '395050009', '397748008', '398254007', '401117004', '402832006', '4210003', '423674003', '428575007', '429198000', '429457004',
                                '44772007', '46481004', '46764007', '48146000', '48194001', '52698002', '56218007', '57684003', '59621000', '59720008',
                                '59997006', '65518004', '68267002','70272006', '73410007', '74451002', '78975002', '81626002', '84094009', '8762007',
                                '89242004', '65443008')
          -- not deleted on or before the end of the reporting period
          and not exists (select 1
                          from
                            ptalerth ph2,
                            audithis ah2
                          where 1=1
                          and ph2."Audit" = ah2."Audit"
                          and ah2."HistoryType" = 4                     -- deleted
                          and ah2."TableName" = 'PTALERT'
                          and ph2."Deleted" = 1
                          and ah2."Date" < ta2."Date"
                          and ph2."PtAlertH" > ph1."PtAlertH"
                          and ph2."PtAlert" = ph1."PtAlert")
--AX-21948b
--          and nvl(ph1."OnsetDate", trunc(ph1."AddDateTime")) < ta2."Date"
          and ph1."Patient" = pPatient5
          union
          -- CQM75
          select
            trim(to_char(ph1."PtAlert", '0000000000')) "IdExtension",
            htf.escape_sc(nvl(trim(tcde1."XMLCode"), 'UNK')) "XMLCode",
            htf.escape_sc(nvl(trim(tcde1."XMLCodeSystemName"), 'UNK')) "XMLCodeSystemName",
            htf.escape_sc(nvl(trim(tcde1."UID"), '2.16.840.1.113883.6.96')) "UID",
            htf.escape_sc(nvl(trim(tcde1."UIDDescription"), 'Diagnosis: Dental Caries')) "UIDDescription",
            trim(to_char(nvl(ph1."OnsetDate", trunc(ph1."AddDateTime")), 'RRRRMMDDHH24MISS')) "OnsetDate"
          from
            ptalerth ph1,
            TmpCQMDataElements tcde1
          where 1=1
          and trim(ph1."SNOCode") = trim(tcde1."Code")
          and ph1."AlertType" = 2
          and ph1."Status" = 0
          and ph1."Deleted" = 0
          -- start: SF-00192551/AX-21332
          and ph1."SNOCode" in ('109564008', '109566005', '109568006', '109569003', '109571003', '109572005', '109573000', '109574006', '109575007', '109576008',
                                '109577004', '109578009', '109580003', '109581004', '15733007', '163152009', '196298000', '196299008', '196301001', '196302008',
                                '196305005', '234976000', '30512007', '442231009', '442551007', '699489009', '699490000', '699491001', '699492008', '699494009',
                                '699495005', '700046006', '702402003', '80353004', '80753001', '80967001', '95246007', '95247003', '95248008', '95249000',
                                '95252008', '95253003', '95254009')
          -- not deleted on or before the end of the reporting period
          and not exists (select 1
                          from
                            ptalerth ph2,
                            audithis ah2
                          where 1=1
                          and ph2."Audit" = ah2."Audit"
                          and ah2."HistoryType" = 4                     -- deleted
                          and ah2."TableName" = 'PTALERT'
                          and ph2."Deleted" = 1
                          and ah2."Date" between pDateFrom5 and pDateTo5
                          and ph2."PtAlertH" > ph1."PtAlertH"
                          and ph2."PtAlert" = ph1."PtAlert")

          and nvl(ph1."OnsetDate", ph1."AddDateTime") between pDateFrom5 and pDateTo5            -- active at anytime during the reporting period
          and ph1."Patient" = pPatient5
          union
          -- CQM138
          select
            trim(to_char(ph1exc1."PtAlert", '0000000000')) "IdExtension",
            htf.escape_sc(nvl(trim(tcde2."XMLCode"), 'UNK')) "XMLCode",
            htf.escape_sc(nvl(trim(tcde2."XMLCodeSystemName"), 'UNK')) "XMLCodeSystemName",
            htf.escape_sc(nvl(trim(tcde2."UID"), '2.16.840.1.113883.6.96')) "UID",
            htf.escape_sc(nvl(trim(tcde2."UIDDescription"), 'Diagnosis: Dental Caries')) "UIDDescription",
            trim(to_char(nvl(ph1exc1."OnsetDate", trunc(ph1exc1."AddDateTime")), 'RRRRMMDDHH24MISS')) "OnsetDate"
          from
            ptalert ph1exc1,
            TmpCQMDataElements tcde2
          where 1=1
          and trim(ph1exc1."SNOCode") = trim(tcde2."Code")
          and ph1exc1."AlertType" = 2
          and ph1exc1."Status" = 0
          and ph1exc1."Deleted" = 0
          and ph1exc1."SNOCode" in ('183932001', '183964008', '183966005', '216952002', '266721009', '269191009', '274512008', '31438003', '35688006', '371133007',
                                    '397745006', '407563006', '410534003', '410536001', '416098002', '416406003', '428119001', '445528004', '59037007', '62014003',
                                    '79899007')
          and ph1exc1."AddDateTime" > pDateTo5B
          and ph1exc1."AddDateTime" <= pDateTo5
          and ph1exc1."Patient" = pPatient5
          union
          select
            trim(to_char(ph1exc1b."PtAlert", '0000000000')) "IdExtension",
            htf.escape_sc(nvl(trim(tcde3."XMLCode"), 'UNK')) "XMLCode",
            htf.escape_sc(nvl(trim(tcde3."XMLCodeSystemName"), 'UNK')) "XMLCodeSystemName",
            htf.escape_sc(nvl(trim(tcde3."UID"), '2.16.840.1.113883.6.96')) "UID",
            htf.escape_sc(nvl(trim(tcde3."UIDDescription"), 'Diagnosis: Dental Caries')) "UIDDescription",
            trim(to_char(nvl(ph1exc1b."OnsetDate", trunc(ph1exc1b."AddDateTime")), 'RRRRMMDDHH24MISS')) "OnsetDate"
          from
            ptalert ph1exc1b,
            TmpCQMDataElements tcde3
          where 1=1
          and trim(ph1exc1b."SNOCode") = trim(tcde3."Code")
          and ph1exc1b."AlertType" = 2
          and ph1exc1b."Status" = 0
          and ph1exc1b."Deleted" = 0
          and ph1exc1b."SNOCode" in ('183932001', '183964008', '183966005', '216952002', '266721009', '269191009', '274512008', '31438003', '35688006', '371133007',
                                     '397745006', '407563006', '410534003', '410536001', '416098002', '416406003', '428119001', '445528004', '59037007', '62014003',
                                     '79899007')
          and ph1exc1b."AddDateTime" <= pDateTo5B
          and ph1exc1b."Patient" = pPatient5
          union
          select
            trim(to_char(ph1exc2."PtAlert", '0000000000')) "IdExtension",
            htf.escape_sc(nvl(trim(tcde4."XMLCode"), 'UNK')) "XMLCode",
            htf.escape_sc(nvl(trim(tcde4."XMLCodeSystemName"), 'UNK')) "XMLCodeSystemName",
            htf.escape_sc(nvl(trim(tcde4."UID"), '2.16.840.1.113883.6.96')) "UID",
            htf.escape_sc(nvl(trim(tcde4."UIDDescription"), 'Diagnosis: Dental Caries')) "UIDDescription",
            trim(to_char(nvl(ph1exc2."OnsetDate", trunc(ph1exc2."AddDateTime")), 'RRRRMMDDHH24MISS')) "OnsetDate"
          from
            ptalert ph1exc2,
            TmpCQMDataElements tcde4
          where 1=1
          and trim(ph1exc2."SNOCode") = trim(tcde4."Code")
          and ph1exc2."AlertType" = 2
          and ph1exc2."Status" = 0
          and ph1exc2."Deleted" = 0
          and ph1exc2."SNOCode" in ('162607003', '162608008', '170969009', '27143004', '300936002')

          and nvl(ph1exc2."OnsetDate", ph1exc2."AddDateTime") <= pDateTo5
          and ph1exc2."Patient" = pPatient5
          union
          select
            trim(to_char(ph1n1."PtAlert", '0000000000')) "IdExtension",
            htf.escape_sc(nvl(trim(tcde5."XMLCode"), 'UNK')) "XMLCode",
            htf.escape_sc(nvl(trim(tcde5."XMLCodeSystemName"), 'UNK')) "XMLCodeSystemName",
            htf.escape_sc(nvl(trim(tcde5."UID"), '2.16.840.1.113883.6.96')) "UID",
            htf.escape_sc(nvl(trim(tcde5."UIDDescription"), 'Diagnosis: Dental Caries')) "UIDDescription",
            trim(to_char(nvl(ph1n1."OnsetDate", trunc(ph1n1."AddDateTime")), 'RRRRMMDDHH24MISS')) "OnsetDate"
          from
            ptalert ph1n1,
            TmpCQMDataElements tcde5
          where 1=1
          and trim(ph1n1."SNOCode") = trim(tcde5."Code")
          and ph1n1."AlertType" = 2
          and ph1n1."Status" = 0
          and ph1n1."Deleted" = 0
          and ph1n1."SNOCode" in (
                                  -- tobacco user
                                  '160603005', '160604004', '160605003', '160606002', '160619003', '228494002', '228504007', '228514003', '228515002', '228516001',
                                  '228517005', '228518000', '230059006', '230060001', '230062009', '230063004', '230064005', '230065006', '266920004', '428041000124106',
                                  '428061000124105', '428071000124103', '449868002', '59978006', '65568007', '77176002', '81703003', '82302008',
                                  -- non-tobacco user
                                  '105539002', '105540000', '105541001', '160618006', '160620009', '160621008', '228501004', '228502006', '228503001', '228512004',
                                  '266919005', '266921000', '266922007', '266923002', '266924008', '266925009', '266928006', '281018007', '360890004', '360900008',
                                  '360918006', '360929005', '405746006', '53896009', '8392000', '8517006', '87739003'
                                 )
          and ph1n1."AddDateTime" > pDateTo5B
          and ph1n1."AddDateTime" <= pDateTo5
          and ph1n1."Patient" = pPatient5
          union
          select
            trim(to_char(ph1n2."PtAlert", '0000000000')) "IdExtension",
            htf.escape_sc(nvl(trim(tcde6."XMLCode"), 'UNK')) "XMLCode",
            htf.escape_sc(nvl(trim(tcde6."XMLCodeSystemName"), 'UNK')) "XMLCodeSystemName",
            htf.escape_sc(nvl(trim(tcde6."UID"), '2.16.840.1.113883.6.96')) "UID",
            htf.escape_sc(nvl(trim(tcde6."UIDDescription"), 'Diagnosis: Dental Caries')) "UIDDescription",
            trim(to_char(nvl(ph1n2."OnsetDate", trunc(ph1n2."AddDateTime")), 'RRRRMMDDHH24MISS')) "OnsetDate"
          from
            ptalert ph1n2,
            TmpCQMDataElements tcde6
          where 1=1
          and trim(ph1n2."SNOCode") = trim(tcde6."Code")
          and ph1n2."AlertType" = 2
          and ph1n2."Status" = 0
          and ph1n2."Deleted" = 0
          and ph1n2."SNOCode" in (
                                  -- tobacco user
                                  '160603005', '160604004', '160605003', '160606002', '160619003', '228494002', '228504007', '228514003', '228515002', '228516001',
                                  '228517005', '228518000', '230059006', '230060001', '230062009', '230063004', '230064005', '230065006', '266920004', '428041000124106',
                                  '428061000124105', '428071000124103', '449868002', '59978006', '65568007', '77176002', '81703003', '82302008',
                                  -- non-tobacco user
                                  '105539002', '105540000', '105541001', '160618006', '160620009', '160621008', '228501004', '228502006', '228503001', '228512004',
                                  '266919005', '266921000', '266922007', '266923002', '266924008', '266925009', '266928006', '281018007', '360890004', '360900008',
                                  '360918006', '360929005', '405746006', '53896009', '8392000', '8517006', '87739003'
                                 )
          and ph1n2."AddDateTime" <= pDateTo5B
          and ph1n2."Patient" = pPatient5
          union
          -- CQM147
          select
            trim(to_char(ph1."PtAlert", '0000000000')) "IdExtension",
            htf.escape_sc(nvl(trim(tcde7."XMLCode"), 'UNK')) "XMLCode",
            htf.escape_sc(nvl(trim(tcde7."XMLCodeSystemName"), 'UNK')) "XMLCodeSystemName",
            htf.escape_sc(nvl(trim(tcde7."UID"), '2.16.840.1.113883.6.96')) "UID",
            htf.escape_sc(nvl(trim(tcde7."UIDDescription"), 'Diagnosis: Dental Caries')) "UIDDescription",
            trim(to_char(nvl(ph1."OnsetDate", trunc(ph1."AddDateTime")), 'RRRRMMDDHH24MISS')) "OnsetDate"
          from
            ptalerth ph1,
            TmpCQMDataElements tcde7
          where 1=1
          and trim(ph1."SNOCode") = trim(tcde7."Code")
          and ph1."AlertType" = 2
          and ph1."Status" = 0
          and ph1."Deleted" = 0
          -- start: SF-00192560/AX-21343
          and ph1."SNOCode" in ('293112000', '293113005', '390796006', '420113004', '294647003', '294648008', '294649000', '102263004', '226881001', '226885005',
                                '229955000', '256442007', '256443002', '286550009', '303300008', '414074006', '213020009', '91930004')

          and nvl(ph1."OnsetDate", ph1."AddDateTime") <= pDateTo5C            -- active at anytime on or before the end of the influenza season
          -- not deleted during the influenza season
          and not exists (select 1
                          from
                            ptalerth ph2,
                            audithis ah2
                          where 1=1
                          and ph2."Audit" = ah2."Audit"
                          and ah2."HistoryType" = 4                     -- deleted
                          and ah2."TableName" = 'PTALERT'
                          and ah2."Date" between pDateFrom5C and pDateTo5C
                          and ph2."Deleted" = 1
                          and ph2."PtAlertH" > ph1."PtAlertH"
                          and ph2."PtAlert" = ph1."PtAlert")
          and ph1."Patient" = pPatient5
         ) mp
    where 1=1
    order by
      mp."OnsetDate",
      mp."IdExtension";

  cursor cDiagnosticStudies (
                             pPatient6 patient."Patient"%type,
                             pDateFrom6 date,
                             pDateTo6 date
                            ) is
    select
('            <entry>
              <observation classCode=OBS moodCode=RQO >
                <!-- Consolidated Plan of Care Activity Observation
                     templateId (Implied Template) -->
                <templateId root="2.16.840.1.113883.10.20.22.4.44" extension="2014-06-09"/>
                <!-- Diagnostic Study, Order template -->
                <templateId root="2.16.840.1.113883.10.20.24.3.17" extension="2017-08-01"/>
                <id root="1.3.6.1.4.1.115" extension="' || tpi2."IdExtension" || '"/>
                <code code="' || tpi2."XMLCode" || '" codeSystem="2.16.840.1.113883.6.1" codeSystemName=LOINC/>
                <text>Diagnostic Study, Order: ' || tpi2."Answer" || '</text>
                <statusCode code=active/>
                <author>
                  <templateId root="2.16.840.1.113883.10.20.24.3.155" extension="2017-08-01"/>
                  <time value=''' || tpi2."AppDateTime" || '''/>
                  <assignedAuthor>
                    <id nullFlavor=NA/>
                  </assignedAuthor>
                </author>
              </observation>
            </entry>
') "XMLDiagnosticStudy"
    from (
          with
          TmpPForm as (
                       select
                         pf1."FormCode",
                         pf1."Patient",
                         pf1."PForm"
                       from pform pf1
                       where 1=1
                       and pf1."Inactive" = 0
                       and pf1."Approved" = 1
                       and exists (select 1
                                   from fitem fi1
                                   where 1=1
                                   and fi1."Deleted" = 0
                                   and fi1."Code" = 'MDH_BPFLW2'
                                   and fi1."FormCode" = pf1."FormCode")
                       and pf1."Patient" = pPatient6
                      ),
          TmpPItem as (
                       select
                         pi."PItem",
                         nvl(pi."AppDateTime", pi."AppDate") "AppDateTime",
                         trim(trim('-' from trim(replace(mu_core_pkg.GetEPRFormItemAnswer_F(pi."FormCode",
                                                                                            pi."Patient",
                                                                                            pi."PForm",
                                                                                            pi."FItem",
                                                                                            pi."AuditNumber",
                                                                                            pi."PItemCol"), pi."AnsListRefCode")))) "Answer",
                         pi."AnsListRefCode"
                       from
                         pitem pi,
                         fitem fi
                       where 1=1
                       and pi."FItem" = fi."FItem"
                       and pi."FormCode" = fi."FormCode"
                       and pi."AppUser" > 0
                       and fi."Deleted" = 0
                       and fi."Code" = 'MDH_BPFLW2'
                       and trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi."FormCode",
                                                                   pi."Patient",
                                                                   pi."PForm",
                                                                   pi."FItem",
                                                                   pi."AuditNumber",
                                                                   pi."PItemCol")) is not null
                       and exists (select 1
                                   from TmpPForm tpf
                                   where 1=1
                                   and tpf."PForm" = pi."PForm"
                                   and tpf."Patient" = pi."Patient"
                                   and tpf."FormCode" = pi."FormCode")
                       and pi."AnsListRefCode" in ('11524-6', '34534-8')
                       and pi."AppDate" between pDateFrom6 and pDateTo6
                      )
          select
            trim(to_char(tpi."PItem", '0000000000')) "IdExtension",
            htf.escape_sc(nvl(trim(tpi."AnsListRefCode"), 'UNK')) "XMLCode",
            trim(to_char(tpi."AppDateTime", 'RRRRMMDDHH24MISS')) "AppDateTime",
            htf.escape_sc(nvl(trim(tpi."Answer"), 'Unknown')) "Answer"
          from TmpPItem tpi
          where 1=1
         ) tpi2
    where 1=1
    order by
      tpi2."AppDateTime",
      tpi2."IdExtension";

  cursor cLaboratoryTests (
                           pPatient7 patient."Patient"%type,
                           pDateFrom7 date,
                           pDateTo7 date
                          ) is
    select
('            <entry>
              <observation classCode=OBS moodCode=RQO >
                <!-- Consolidation Plan of Care Activity Observation -->
                <templateId root="2.16.840.1.113883.10.20.22.4.44" extension="2014-06-09"/>
                <!-- Lab Test Order -->
                <templateId root="2.16.840.1.113883.10.20.24.3.37" extension="2017-08-01"/>
                <id root="1.3.6.1.4.1.115" extension="' || tpi2."IdExtension" || '"/>
                <code code="' || tpi2."XMLCode" || '" codeSystem="2.16.840.1.113883.6.1" codeSystemName=LOINC/>
                <text>Laboratory Test, Order: ' || tpi2."Answer" || '</text>
                <statusCode code=active/>
                <author>
                  <templateId root="2.16.840.1.113883.10.20.24.3.155" extension="2017-08-01"/>
                  <time value=''' || tpi2."AppDateTime" || '''/>
                  <assignedAuthor>
                    <id nullFlavor=NA/>
                  </assignedAuthor>
                </author>
              </observation>
            </entry>
') "XMLLaboratoryTest"
    from (
          with
          TmpPForm as (
                       select
                         pf1."FormCode",
                         pf1."Patient",
                         pf1."PForm"
                       from pform pf1
                       where 1=1
                       and pf1."Inactive" = 0
                       and pf1."Approved" = 1
                       and exists (select 1
                                   from fitem fi1
                                   where 1=1
                                   and fi1."Deleted" = 0
                                   and fi1."Code" = 'MDH_BPFLW2'
                                   and fi1."FormCode" = pf1."FormCode")
                       and pf1."Patient" = pPatient7
                      ),
          TmpPItem as (
                       select
                         pi."PItem",
                         nvl(pi."AppDateTime", pi."AppDate") "AppDateTime",
                         trim(trim('-' from trim(replace(mu_core_pkg.GetEPRFormItemAnswer_F(pi."FormCode",
                                                                                            pi."Patient",
                                                                                            pi."PForm",
                                                                                            pi."FItem",
                                                                                            pi."AuditNumber",
                                                                                            pi."PItemCol"), pi."AnsListRefCode")))) "Answer",
                         pi."AnsListRefCode"
                       from
                         pitem pi,
                         fitem fi
                       where 1=1
                       and pi."FItem" = fi."FItem"
                       and pi."FormCode" = fi."FormCode"
                       and pi."AppUser" > 0
                       and fi."Deleted" = 0
                       and fi."Code" = 'MDH_BPFLW2'
                       and trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi."FormCode",
                                                                   pi."Patient",
                                                                   pi."PForm",
                                                                   pi."FItem",
                                                                   pi."AuditNumber",
                                                                   pi."PItemCol")) is not null
                       and exists (select 1
                                   from TmpPForm tpf
                                   where 1=1
                                   and tpf."PForm" = pi."PForm"
                                   and tpf."Patient" = pi."Patient"
                                   and tpf."FormCode" = pi."FormCode")
                       and pi."AnsListRefCode" in ('24320-4', '24321-2', '24323-8', '24356-8', '24357-6', '24362-6', '2888-6', '57021-8', '57782-5', '58410-2')
                       and pi."AppDate" between pDateFrom7 and pDateTo7
                      )
          select
            trim(to_char(tpi."PItem", '0000000000')) "IdExtension",
            htf.escape_sc(nvl(trim(tpi."AnsListRefCode"), 'UNK')) "XMLCode",
            trim(to_char(tpi."AppDateTime", 'RRRRMMDDHH24MISS')) "AppDateTime",
            htf.escape_sc(nvl(trim(tpi."Answer"), 'Unknown')) "Answer"
          from TmpPItem tpi
          where 1=1
         ) tpi2
    where 1=1
    order by
      tpi2."AppDateTime",
      tpi2."IdExtension";

  cursor cCommunications (
                          pPatient8 patient."Patient"%type,
                          pDateFrom8 date,
                          pDateTo8 date
                         ) is
    select
('            <entry>
              <act classCode=ACT moodCode=EVN >
                <!-- Communication from patient to provider -->
                <templateId root="2.16.840.1.113883.10.20.24.3.2" extension="2017-08-01"/>
                <id root="1.3.6.1.4.1.115" extension="' || tpi2."IdExtension" || '"/>
                <code code="' || tpi2."XMLCode" || '" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED-CT"/>
                <text>Communication From Patient To Provider: ' || tpi2."Answer" || '</text>
                <statusCode code=completed/>
                <author>
                  <templateId root="2.16.840.1.113883.10.20.24.3.155" extension="2017-08-01"/>
                  <time value=''' || tpi2."AppDateTime" || '''/>
                  <assignedAuthor>
                    <id nullFlavor=NA/>
                  </assignedAuthor>
                </author>
                <participant typeCode=AUT>
                  <participantRole classCode=PAT>
                    <code code="116154003" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" displayName="Patient"/>
                  </participantRole>
                </participant>
                <participant typeCode=IRCP>
                  <participantRole classCode=ASSIGNED>
                    <code code="158965000" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" displayName="Medical Practitioner"/>
                  </participantRole>
                </participant>
              </act>
            </entry>
') "XMLCommunication"
    from (
          with
          TmpPForm as (
                       select
                         pf1."FormCode",
                         pf1."Patient",
                         pf1."PForm"
                       from pform pf1
                       where 1=1
                       and pf1."Inactive" = 0
                       and pf1."Approved" = 1
                       and exists (select 1
                                   from fitem fi1
                                   where 1=1
                                   and fi1."Deleted" = 0
                                   and fi1."Code" = 'INFDECLINE'
                                   and fi1."FormCode" = pf1."FormCode")
                       and pf1."Patient" = pPatient8
                       union all
                       select
                         pf2."FormCode",
                         pf2."Patient",
                         pf2."PForm"
                       from pform pf2
                       where 1=1
                       and pf2."Inactive" = 0
                       and pf2."Approved" = 1
                       and exists (select 1
                                   from fitem fi2a
                                   where 1=1
                                   and fi2a."Deleted" = 0
                                   and fi2a."Code" = 'INFVACRS'
                                   and fi2a."FormCode" = pf2."FormCode")
                       and exists (select 1
                                   from fitem fi2b
                                   where 1=1
                                   and fi2b."Deleted" = 0
                                   and fi2b."Code" = 'INFVACRD'
                                   and fi2b."FormCode" = pf2."FormCode")
                       and pf2."Patient" = pPatient8
                      ),
          TmpPItem as (
                       select
                         pi."PItem",
                         nvl(pi."AppDateTime", pi."AppDate") "AppDateTime",
                         trim(trim('-' from trim(replace(mu_core_pkg.GetEPRFormItemAnswer_F(pi."FormCode",
                                                                                            pi."Patient",
                                                                                            pi."PForm",
                                                                                            pi."FItem",
                                                                                            pi."AuditNumber",
                                                                                            pi."PItemCol"), pi."AnsListRefCode")))) "Answer",
                         pi."AnsListRefCode"
                       from
                         pitem pi,
                         fitem fi
                       where 1=1
                       and pi."FItem" = fi."FItem"
                       and pi."FormCode" = fi."FormCode"
                       and pi."AppUser" > 0
                       and fi."Deleted" = 0
                       and fi."Code" = 'INFDECLINE'
                       and trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi."FormCode",
                                                                   pi."Patient",
                                                                   pi."PForm",
                                                                   pi."FItem",
                                                                   pi."AuditNumber",
                                                                   pi."PItemCol")) is not null
                       and exists (select 1
                                   from TmpPForm tpf
                                   where 1=1
                                   and tpf."PForm" = pi."PForm"
                                   and tpf."Patient" = pi."Patient"
                                   and tpf."FormCode" = pi."FormCode")
                       and pi."AnsListRefCode" = '315640000'
                       and pi."AppDate" between pDateFrom8 and pDateTo8
                       union all
                       select
                         pi2."PItem",
                         nvl(pi2."AppDateTime", pi2."AppDate") "AppDateTime",
                         trim(trim('-' from trim(replace(mu_core_pkg.GetEPRFormItemAnswer_F(pi2."FormCode",
                                                                                            pi2."Patient",
                                                                                            pi2."PForm",
                                                                                            pi2."FItem",
                                                                                            pi2."AuditNumber",
                                                                                            pi2."PItemCol"), pi2."AnsListRefCode")))) "Answer",
                         pi2."AnsListRefCode"
                       from
                         pitem pi2,
                         fitem fi2
                       where 1=1
                       and pi2."FItem" = fi2."FItem"
                       and pi2."FormCode" = fi2."FormCode"
                       and pi2."AppUser" > 0
                       and fi2."Deleted" = 0
                       and fi2."Code" = 'INFVACRS'
                       and trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi2."FormCode",
                                                                   pi2."Patient",
                                                                   pi2."PForm",
                                                                   pi2."FItem",
                                                                   pi2."AuditNumber",
                                                                   pi2."PItemCol")) is not null
                       and exists (select 1
                                   from
                                     pitem pi3,
                                     fitem fi3
                                   where 1=1
                                   and pi3."FItem" = fi3."FItem"
                                   and pi3."FormCode" = fi3."FormCode"
                                   and pi3."AppUser" > 0
                                   and fi3."Deleted" = 0
                                   and fi3."Code" = 'INFVACRD'
                                   and pi3."AnsDate" between pDateFrom8 and pDateTo8
                                   and pi3."AnsType" = 4                                      -- date answer only
                                   and pi3."PForm" = pi2."PForm"
                                   and pi3."Patient" = pi2."Patient"
                                   and pi3."FormCode" = pi2."FormCode")
                       and exists (select 1
                                   from TmpPForm tpf2
                                   where 1=1
                                   and tpf2."PForm" = pi2."PForm"
                                   and tpf2."Patient" = pi2."Patient"
                                   and tpf2."FormCode" = pi2."FormCode")
                       and pi2."AnsListRefCode" in ('185900003', '185901004', '185902006', '416928007')
                      )
          select
            trim(to_char(tpi."PItem", '0000000000')) "IdExtension",
            htf.escape_sc(nvl(trim(tpi."AnsListRefCode"), 'UNK')) "XMLCode",
            trim(to_char(tpi."AppDateTime", 'RRRRMMDDHH24MISS')) "AppDateTime",
            htf.escape_sc(nvl(trim(tpi."Answer"), 'Unknown')) "Answer"
          from TmpPItem tpi
          where 1=1
         ) tpi2
    where 1=1
    order by
      tpi2."AppDateTime",
      tpi2."IdExtension";

  cursor cPhysicalExams (
                         pPatient9 patient."Patient"%type,
                         pDateFrom9 date,
                         pDateTo9 date
                        ) is


  ---     AX-22009


    select
('            <entry>
              <observation classCode=OBS moodCode=EVN'|| CASE WHEN LENGTH (tpi2."QuestionNegation")>0 THEN ' negationInd="true"' ELSE '' END ||'>
                <!-- Procedure Activity Procedure (Consolidation) template -->
                <templateId root="2.16.840.1.113883.10.20.22.4.13" extension="2014-06-09"/>
                <!-- Physical Exam, Performed template -->
                <templateId root="2.16.840.1.113883.10.20.24.3.59" extension="2017-08-01"/>
				<id root="1.3.6.1.4.1.115" extension="'|| CASE WHEN LENGTH (trim(tpi2."XMLCode"))>0 THEN tpi2."IdExtension" ELSE tpi2."IdExtensionNegation" END||'"/>
				<code code="'||
				CASE WHEN LENGTH (trim(tpi2."XMLCode"))>0 THEN tpi2."XMLCode"
                     ELSE
                        CASE WHEN tpi2."QuestionNegation"= 'MDH_SBP' THEN '8480-6'
                             ELSE '8462-4'
                             END
                     END
                ||'" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC"/>
                <text>Physical Exam, Performed: '||
                CASE WHEN LENGTH (trim(tpi2."XMLCode"))>0 THEN tpi2."XMLDescription"
                     ELSE
                        CASE WHEN tpi2."QuestionNegation"= 'MDH_SBP' THEN 'Systolic blood pressure'
                             ELSE 'Diastolic blood pressure'
                             END
                     END
                ||'</text>
                <statusCode code=completed/>
                '||
                CASE WHEN LENGTH (trim(tpi2."XMLCode"))>0 THEN
                    '<effectiveTime><low value='''||tpi2."AppDateTime"||'''/><high value='''||tpi2."AppDateTime"||'''/></effectiveTime>
                    '
                    ELSE
                    '<effectiveTime><low value='''||tpi2."AppDateTimeNegation"||'''/><high nullFlavor=''UNK''/></effectiveTime>
                    '
                    END
                ||CASE WHEN LENGTH (trim(tpi2."Answer"))>0 THEN '
                <value xsi:type=PQ value="'||trim(tpi2."Answer")||'" unit="mm[Hg]"/>'
                ELSE
                '<value nullFlavor=UNK xsi:type=CD/>' END ||'
                <author>
                <templateId root="2.16.840.1.113883.10.20.24.3.155" extension="2017-08-01"/>
                  <time value='''|| CASE WHEN LENGTH (trim(tpi2."XMLCode"))>0 THEN tpi2."AppDateTime" ELSE tpi2."AppDateTimeNegation" END||'''/>
                  <assignedAuthor>
                      <id nullFlavor=NA/>
                  </assignedAuthor>
                </author>'
                ||CASE WHEN LENGTH (tpi2."QuestionNegation")>0 THEN '
                <entryRelationship typeCode=RSON>
                  <observation classCode=OBS moodCode=EVN>
                    <templateId root="2.16.840.1.113883.10.20.24.3.88" extension="2014-12-01"/>
					
                    <id root="1.3.6.1.4.1.115" extension="85edb9b0-e537-0136-ce63-0e95690c4dba" />
                    <code code="77301-0" codeSystem="2.16.840.1.113883.6.1" displayName=reason codeSystemName=LOINC/>
                    <statusCode code=completed/>
					<effectiveTime><low value='''||tpi2."AppDateTimeNegation"||'''/><high nullFlavor=''UNK''/></effectiveTime>
					<value code="'||tpi2."NegationAnswCode"||'" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED-CT" xsi:type=CD/>
                  </observation>
                </entryRelationship>
                '
                ELSE '' END||
				'</observation>
            </entry>
			
') "XMLPhysicalExam"
    from (
          with
          TmpPForm as (
                       select
                         pf."FormCode",
                         pf."Patient",
                         pf."PForm"
                       from pform pf
                       where 1=1
                       and pf."Inactive" = 0
                       and pf."Approved" = 1
                       and exists (select 1
                                   from fitem fi1
                                   where 1=1
                                   and fi1."Deleted" = 0
                                   and fi1."Code" = 'MDH_SBP'
                                   and fi1."FormCode" = pf."FormCode")
                       and exists (select 1
                                   from fitem fi2
                                   where 1=1
                                   and fi2."Deleted" = 0
                                   and fi2."Code" = 'MDH_DBP'
                                   and fi2."FormCode" = pf."FormCode")
                       and pf."Patient" = pPatient9
                      ),
          TmpPItem as (
                       select
                         pi."PForm",
                         pi."PItem",
                         nvl(pi."AppDateTime", pi."AppDate") "AppDateTime",
                         trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi."FormCode",
                                                                 pi."Patient",
                                                                 pi."PForm",
                                                                 pi."FItem",
                                                                 pi."AuditNumber",
                                                                 pi."PItemCol")) "Answer",
                         '8480-6' "XMLCode",
                         'Systolic blood pressure' "XMLDescription",
                         fi."Code"
                       from
                         pitem pi,
                         fitem fi
                       where 1=1
                       and pi."FItem" = fi."FItem"
                       and pi."FormCode" = fi."FormCode"
                       and pi."AppUser" > 0
                       and fi."Deleted" = 0
                       and fi."Code" = 'MDH_SBP'
                       and trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi."FormCode",
                                                                   pi."Patient",
                                                                   pi."PForm",
                                                                   pi."FItem",
                                                                   pi."AuditNumber",
                                                                   pi."PItemCol")) is not null
                       and exists (select 1
                                   from TmpPForm tpf
                                   where 1=1
                                   and tpf."PForm" = pi."PForm"
                                   and tpf."Patient" = pi."Patient"
                                   and tpf."FormCode" = pi."FormCode")
                       and exists (select 1
                                   from
                                     pitem pi2,
                                     fitem fi2
                                   where 1=1
                                   and pi2."FItem" = fi2."FItem"
                                   and pi2."FormCode" = fi2."FormCode"
                                   and pi2."AppUser" > 0
                                   and fi2."Deleted" = 0
                                   and fi2."Code" = 'MDH_DBP'
                                   and trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi2."FormCode",
                                                                               pi2."Patient",
                                                                               pi2."PForm",
                                                                               pi2."FItem",
                                                                               pi2."AuditNumber",
                                                                               pi2."PItemCol")) is not null
                                   and pi2."AppDate" = pi."AppDate"
                                   and pi2."PForm" = pi."PForm"
                                   and pi2."Patient" = pi."Patient"
                                   and pi2."FormCode" = pi."FormCode")
                       --and pi."AppDate" between pDateFrom9 and pDateTo9
                       union all
                       select
                         pib."PForm",
                         pib."PItem",
                         nvl(pib."AppDateTime", pib."AppDate") "AppDateTime",
                         trim(mu_core_pkg.GetEPRFormItemAnswer_F(pib."FormCode",
                                                                 pib."Patient",
                                                                 pib."PForm",
                                                                 pib."FItem",
                                                                 pib."AuditNumber",
                                                                 pib."PItemCol")) "Answer",
                         '8462-4' "XMLCode",
                         'Diastolic blood pressure' "XMLDescription",
                         fib."Code"
                       from
                         pitem pib,
                         fitem fib
                       where 1=1
                       and pib."FItem" = fib."FItem"
                       and pib."FormCode" = fib."FormCode"
                       and pib."AppUser" > 0
                       and fib."Deleted" = 0
                       and fib."Code" = 'MDH_DBP'
                       and trim(mu_core_pkg.GetEPRFormItemAnswer_F(pib."FormCode",
                                                                   pib."Patient",
                                                                   pib."PForm",
                                                                   pib."FItem",
                                                                   pib."AuditNumber",
                                                                   pib."PItemCol")) is not null
                       and exists (select 1
                                   from TmpPForm tpfb
                                   where 1=1
                                   and tpfb."PForm" = pib."PForm"
                                   and tpfb."Patient" = pib."Patient"
                                   and tpfb."FormCode" = pib."FormCode")
                       and exists (select 1
                                   from
                                     pitem pi2b,
                                     fitem fi2b
                                   where 1=1
                                   and pi2b."FItem" = fi2b."FItem"
                                   and pi2b."FormCode" = fi2b."FormCode"
                                   and pi2b."AppUser" > 0
                                   and fi2b."Deleted" = 0
                                   and fi2b."Code" = 'MDH_SBP'
                                   and trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi2b."FormCode",
                                                                               pi2b."Patient",
                                                                               pi2b."PForm",
                                                                               pi2b."FItem",
                                                                               pi2b."AuditNumber",
                                                                               pi2b."PItemCol")) is not null
                                   and pi2b."AppDate" = pib."AppDate"
                                   and pi2b."PForm" = pib."PForm"
                                   and pi2b."Patient" = pib."Patient"
                                   and pi2b."FormCode" = pib."FormCode")
                       --and pib."AppDate" between pDateFrom9 and pDateTo9
                      )
, my_responses as(
        select
            tpi."PForm",
            trim(to_char(tpi."PItem", '0000000000')) "IdExtension",
            htf.escape_sc(nvl(trim(tpi."XMLCode"), 'UNK')) "XMLCode",
            htf.escape_sc(nvl(trim(tpi."XMLDescription"), 'Unknown')) "XMLDescription",
            trim(to_char(tpi."AppDateTime", 'RRRRMMDDHH24MISS')) "AppDateTime",
            htf.escape_sc(nvl(trim(tpi."Answer"), 'Unknown')) "Answer",
            tpi."Code"
          from TmpPItem tpi
          where 1=1
),
TmpPFormNega as (
                       select
                         pf."FormCode",
                         pf."Patient",
                         pf."PForm"
                       from pform pf
                       where 1=1
                       and pf."Inactive" = 0
                       and pf."Approved" = 1
                       and exists (select 1
                                   from fitem fi1
                                   where 1=1
                                   and fi1."Deleted" = 0
                                   and fi1."Code" = 'MDH_SBPR'
                                   and fi1."FormCode" = pf."FormCode")
                       and exists (select 1
                                   from fitem fi2
                                   where 1=1
                                   and fi2."Deleted" = 0
                                   and fi2."Code" = 'MDH_DBPR'
                                   and fi2."FormCode" = pf."FormCode")
                       and pf."Patient" = pPatient9
                      ),
          TmpPItemNega as (
                       select
                         pi."PForm",
                         pi."PItem",
                         nvl(pi."AppDateTime", pi."AppDate") "AppDateTime",
                         trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi."FormCode",
                                                                 pi."Patient",
                                                                 pi."PForm",
                                                                 pi."FItem",
                                                                 pi."AuditNumber",
                                                                 pi."PItemCol")) "Answer",
                         '8480-6' "XMLCode",
                         'Systolic blood pressure' "XMLDescription",
                         fi."Code"
                       from
                         pitem pi,
                         fitem fi
                       where 1=1
                       and pi."FItem" = fi."FItem"
                       and pi."FormCode" = fi."FormCode"
                       and pi."AppUser" > 0
                       and fi."Deleted" = 0
                       and fi."Code" = 'MDH_SBPR'
                       and trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi."FormCode",
                                                                   pi."Patient",
                                                                   pi."PForm",
                                                                   pi."FItem",
                                                                   pi."AuditNumber",
                                                                   pi."PItemCol")) is not null
                       and exists (select 1
                                   from TmpPFormNega tpf
                                   where 1=1
                                   and tpf."PForm" = pi."PForm"
                                   and tpf."Patient" = pi."Patient"
                                   and tpf."FormCode" = pi."FormCode")
                       and exists (select 1
                                   from
                                     pitem pi2,
                                     fitem fi2
                                   where 1=1
                                   and pi2."FItem" = fi2."FItem"
                                   and pi2."FormCode" = fi2."FormCode"
                                   and pi2."AppUser" > 0
                                   and fi2."Deleted" = 0
                                   and fi2."Code" = 'MDH_DBPR'
                                   and trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi2."FormCode",
                                                                               pi2."Patient",
                                                                               pi2."PForm",
                                                                               pi2."FItem",
                                                                               pi2."AuditNumber",
                                                                               pi2."PItemCol")) is not null
                                   and pi2."AppDate" = pi."AppDate"
                                   and pi2."PForm" = pi."PForm"
                                   and pi2."Patient" = pi."Patient"
                                   and pi2."FormCode" = pi."FormCode")
                       --and pi."AppDate" between pDateFrom9 and pDateTo9
                       union
                       select
                         pib."PForm",
                         pib."PItem",
                         nvl(pib."AppDateTime", pib."AppDate") "AppDateTime",
                         trim(mu_core_pkg.GetEPRFormItemAnswer_F(pib."FormCode",
                                                                 pib."Patient",
                                                                 pib."PForm",
                                                                 pib."FItem",
                                                                 pib."AuditNumber",
                                                                 pib."PItemCol")) "Answer",
                         '8462-4' "XMLCode",
                         'Diastolic blood pressure' "XMLDescription",
                         fib."Code"
                       from
                         pitem pib,
                         fitem fib
                       where 1=1
                       and pib."FItem" = fib."FItem"
                       and pib."FormCode" = fib."FormCode"
                       and pib."AppUser" > 0
                       and fib."Deleted" = 0
                       and fib."Code" = 'MDH_DBPR'
                       and trim(mu_core_pkg.GetEPRFormItemAnswer_F(pib."FormCode",
                                                                   pib."Patient",
                                                                   pib."PForm",
                                                                   pib."FItem",
                                                                   pib."AuditNumber",
                                                                   pib."PItemCol")) is not null
                       and exists (select 1
                                   from TmpPFormNega tpfb
                                   where 1=1
                                   and tpfb."PForm" = pib."PForm"
                                   and tpfb."Patient" = pib."Patient"
                                   and tpfb."FormCode" = pib."FormCode")
                       and exists (select 1
                                   from
                                     pitem pi2b,
                                     fitem fi2b
                                   where 1=1
                                   and pi2b."FItem" = fi2b."FItem"
                                   and pi2b."FormCode" = fi2b."FormCode"
                                   and pi2b."AppUser" > 0
                                   and fi2b."Deleted" = 0
                                   and fi2b."Code" = 'MDH_SBPR'
                                   and trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi2b."FormCode",
                                                                               pi2b."Patient",
                                                                               pi2b."PForm",
                                                                               pi2b."FItem",
                                                                               pi2b."AuditNumber",
                                                                               pi2b."PItemCol")) is not null
                                   and pi2b."AppDate" = pib."AppDate"
                                   and pi2b."PForm" = pib."PForm"
                                   and pi2b."Patient" = pib."Patient"
                                   and pi2b."FormCode" = pib."FormCode")
                       --and pib."AppDate" between pDateFrom9 and pDateTo9
                      )
, my_Negations as(
        select
            tpi."PForm" as "PFormNegation",
            trim(to_char(tpi."PItem", '0000000000')) as "IdExtensionNegation",
            htf.escape_sc(nvl(trim(tpi."XMLCode"), 'UNK')) as "XMLCodeNegation",
            htf.escape_sc(nvl(trim(tpi."XMLDescription"), 'Unknown'))as "XMLDescriptionNegation" ,
            trim(to_char(tpi."AppDateTime", 'RRRRMMDDHH24MISS')) as "AppDateTimeNegation",
            htf.escape_sc(nvl(trim(tpi."Answer"), 'Unknown')) as "AnswerNegation",
            Replace (tpi."Code", 'R','') as "QuestionNegation",
            REGEXP_SUBSTR (tpi."Answer", '^\D*(\d+) ',1, 1, NULL, 1) AS "NegationAnswCode"
          from TmpPItemNega tpi
          where 1=1
)
select
            mr."PForm",
            mr."IdExtension",
            mr."XMLCode",
            mr."XMLDescription",
            mr."AppDateTime",
            case when mn."PFormNegation" <> mr."PForm" then NULL else mr."Answer" end as "Answer",
            mr."Code",
            mn."PFormNegation",
            mn."IdExtensionNegation",
            mn."XMLCodeNegation",
            mn."XMLDescriptionNegation" ,
            mn."AppDateTimeNegation",
            mn."AnswerNegation",
            mn."QuestionNegation",
            mn."NegationAnswCode"
            from my_Negations mn
            full outer join my_responses mr  on ( mr."Code"=mn."QuestionNegation" and mn."XMLCodeNegation"=mr."XMLCode")
    )tpi2
    where 1=1
    order by
      tpi2."PForm",
      tpi2."AppDateTime",
      tpi2."IdExtension";
--- end of issue AX-22009
  cursor cImmunizations (
                         pPatient10 patient."Patient"%type,
                         pDateFrom10 date,
                         pDateTo10 date
                        ) is
    select
('            <entry>
              <substanceAdministration classCode=SBADM moodCode=EVN >
                <!-- Immunization Activity template -->
                <templateId root="2.16.840.1.113883.10.20.22.4.52" extension="2014-06-09"/>
                <!-- Immunization, Administered template -->
                <templateId root="2.16.840.1.113883.10.20.24.3.140" extension="2017-08-01"/>
                <id root="1.3.6.1.4.1.115" extension="' || tpi2."IdExtension" || '"/>
                <code code="416118004" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" displayName="Administration"/>
                <statusCode code=completed/>
                <effectiveTime value=''' || tpi2."AppDateTime" || '''/>
                <doseQuantity value="1" unit="{dose(s)}"/>
                <consumable>
                  <manufacturedProduct classCode=MANU>
                    <!-- Immunization Information (consolidation) template -->
                    <templateId root="2.16.840.1.113883.10.20.22.4.54" extension="2014-06-09"/>
                    <id root="2735e810-d4ce-0136-ff3a-0e95690c4dba"/>
                    <manufacturedMaterial>
                      <code code="' || tpi2."Answer" || '" codeSystem="2.16.840.1.113883.12.292" codeSystemName=CVX/>
                      <lotNumberText>1</lotNumberText>
                    </manufacturedMaterial>
                  </manufacturedProduct>
                </consumable>
              </substanceAdministration>
            </entry>
') "XMLImmunization"
    from (
          with
          TmpPForm as (
                       select
                         pf1."FormCode",
                         pf1."Patient",
                         pf1."PForm"
                       from pform pf1
                       where 1=1
                       and pf1."Inactive" = 0
                       and pf1."Approved" = 1
                       and exists (select 1
                                   from fitem fi1
                                   where 1=1
                                   and fi1."Deleted" = 0
                                   and fi1."Code" = 'MDH_PNEUM2'
                                   and fi1."FormCode" = pf1."FormCode")
                       and pf1."Patient" = pPatient10
                      ),
          TmpPItem as (
                       select
                         pi."PItem",
                         nvl(pi."AppDateTime", pi."AppDate") "AppDateTime",
                         trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi."FormCode",
                                                                 pi."Patient",
                                                                 pi."PForm",
                                                                 pi."FItem",
                                                                 pi."AuditNumber",
                                                                 pi."PItemCol")) "Answer"
                       from
                         pitem pi,
                         fitem fi
                       where 1=1
                       and pi."FItem" = fi."FItem"
                       and pi."FormCode" = fi."FormCode"
                       and pi."AppUser" > 0
                       and fi."Deleted" = 0
                       and fi."Code" = 'MDH_PNEUM2'
                       and trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi."FormCode",
                                                                   pi."Patient",
                                                                   pi."PForm",
                                                                   pi."FItem",
                                                                   pi."AuditNumber",
                                                                   pi."PItemCol")) is not null
                       and exists (select 1
                                   from TmpPForm tpf
                                   where 1=1
                                   and tpf."PForm" = pi."PForm"
                                   and tpf."Patient" = pi."Patient"
                                   and tpf."FormCode" = pi."FormCode")
                       and pi."AppDate" <= pDateTo10
                      ),
          TmpPForm2 as (
                        select
                          pf2."FormCode",
                          pf2."Patient",
                          pf2."PForm"
                        from pform pf2
                        where 1=1
                        and pf2."Inactive" = 0
                        and pf2."Approved" = 1
                        and exists (select 1
                                    from fitem fi2a
                                    where 1=1
                                    and fi2a."Deleted" = 0
                                    and fi2a."Code" = 'INFVACRS'
                                    and fi2a."FormCode" = pf2."FormCode")
                        and exists (select 1
                                    from fitem fi2b
                                    where 1=1
                                    and fi2b."Deleted" = 0
                                    and fi2b."Code" = 'INFVACRD'
                                    and fi2b."FormCode" = pf2."FormCode")
                        and pf2."Patient" = pPatient10
                       ),
          TmpPItem2 as (
                        select
                          pi2."PItem",
                          nvl(pi2."AppDateTime", pi2."AppDate") "AppDateTime",
                          trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi2."FormCode",
                                                                  pi2."Patient",
                                                                  pi2."PForm",
                                                                  pi2."FItem",
                                                                  pi2."AuditNumber",
                                                                  pi2."PItemCol")) "Answer"
                        from
                          pitem pi2,
                          fitem fi2
                        where 1=1
                        and pi2."FItem" = fi2."FItem"
                        and pi2."FormCode" = fi2."FormCode"
                        and pi2."AppUser" > 0
                        and fi2."Deleted" = 0
                        and fi2."Code" = 'INFVACRS'
                        and trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi2."FormCode",
                                                                    pi2."Patient",
                                                                    pi2."PForm",
                                                                    pi2."FItem",
                                                                    pi2."AuditNumber",
                                                                    pi2."PItemCol")) is not null
                        and exists (select 1
                                    from
                                      pitem pi3,
                                      fitem fi3
                                    where 1=1
                                    and pi3."FItem" = fi3."FItem"
                                    and pi3."FormCode" = fi3."FormCode"
                                    and pi3."AppUser" > 0
                                    and fi3."Deleted" = 0
                                    and fi3."Code" = 'INFVACRD'
                                    and pi3."AnsDate" between pDateFrom10 and pDateTo10
                                    and pi3."AnsType" = 4                                      -- date answer only
                                    and pi3."PForm" = pi2."PForm"
                                    and pi3."Patient" = pi2."Patient"
                                    and pi3."FormCode" = pi2."FormCode")
                        and exists (select 1
                                    from TmpPForm2 tpf2
                                    where 1=1
                                    and tpf2."PForm" = pi2."PForm"
                                    and tpf2."Patient" = pi2."Patient"
                                    and tpf2."FormCode" = pi2."FormCode")
                       )
          select
            trim(to_char(tpi."PItem", '0000000000')) "IdExtension",
            trim(to_char(tpi."AppDateTime", 'RRRRMMDDHH24MISS')) "AppDateTime",
            htf.escape_sc(nvl(substr(tpi."Answer", 1, (instr(tpi."Answer", ' ') - 1)), tpi."Answer")) "Answer"
          from TmpPItem tpi
          where 1=1
          union all
          select
            trim(to_char(tpib."PItem", '0000000000')) "IdExtension",
            trim(to_char(tpib."AppDateTime", 'RRRRMMDDHH24MISS')) "AppDateTime",
            htf.escape_sc(nvl(substr(tpib."Answer", 1, (instr(tpib."Answer", ' ') - 1)), tpib."Answer")) "Answer"
          from TmpPItem2 tpib
          where 1=1
         ) tpi2
    where 1=1
    and tpi2."Answer" in ('109', '133', '152', '33', '135', '140', '141', '144', '150', '153', '155', '158', '161', '166', '168', '171', '88')
    order by
      tpi2."AppDateTime",
      tpi2."IdExtension";

  cursor cOrderedInterventions (
                                pPatient12 patient."Patient"%type,
                                pDateTo12 date
                               ) is
    select
('            <entry>
              <act classCode=ACT moodCode=RQO >
                <!-- Plan of Care Activity Act template -->
                <templateId root="2.16.840.1.113883.10.20.22.4.39" extension="2014-06-09"/>
                <!-- Intervention Order template -->
                <templateId root="2.16.840.1.113883.10.20.24.3.31" extension="2017-08-01"/>
                <id root="1.3.6.1.4.1.115" extension="' || tpi2."IdExtension" || '"/>
                <code code="' || tpi2."XMLCode" || '" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED-CT"/>
                <text>' || tpi2."XMLDescription" || '</text>
                <statusCode code=active/>
                <author>
                  <templateId root="2.16.840.1.113883.10.20.24.3.155" extension="2017-08-01"/>
                   <time value=''' || tpi2."AppDateTime" || '''/>
                  <assignedAuthor>
                    <id nullFlavor=NA/>
                  </assignedAuthor>
                </author>
              </act>
            </entry>
') "XMLInterventionOrdered"
    from (
          with
          TmpPForm as (
                       select
                         pf."FormCode",
                         pf."Patient",
                         pf."PForm"
                       from pform pf
                       where 1=1
                       and pf."Inactive" = 0
                       and pf."Approved" = 1
                       and exists (select 1
                                   from fitem fi
                                   where 1=1
                                   and fi."Deleted" = 0
                                   and fi."Code" = 'MU_HOS1'
                                   and fi."FormCode" = pf."FormCode")
                       and exists (select 1
                                   from fitem fi2
                                   where 1=1
                                   and fi2."Deleted" = 0
                                   and fi2."Code" = 'MU_HOS1D'
                                   and fi2."FormCode" = pf."FormCode")
                       and pf."Patient" = pPatient12
                      ),
          TmpPItem as (
                       select
                         pi."PForm",
                         pi."PItem",
                         nvl(pi."AppDateTime", pi."AppDate") "AppDateTime",
                         trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi."FormCode",
                                                                 pi."Patient",
                                                                 pi."PForm",
                                                                 pi."FItem",
                                                                 pi."AuditNumber",
                                                                 pi."PItemCol")) "Answer",
                         'Intervention, Order: Hospice care ambulatory' "XMLDescription"
                       from
                         pitem pi,
                         fitem fi
                       where 1=1
                       and pi."FItem" = fi."FItem"
                       and pi."FormCode" = fi."FormCode"
                       and pi."AppUser" > 0
                       and fi."Deleted" = 0
                       and fi."Code" = 'MU_HOS1'
                       and trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi."FormCode",
                                                                   pi."Patient",
                                                                   pi."PForm",
                                                                   pi."FItem",
                                                                   pi."AuditNumber",
                                                                   pi."PItemCol")) is not null
                       and exists (select 1
                                   from TmpPForm tpf
                                   where 1=1
                                   and tpf."PForm" = pi."PForm"
                                   and tpf."Patient" = pi."Patient"
                                   and tpf."FormCode" = pi."FormCode")
                       and exists (select 1
                                   from
                                     pitem pi2,
                                     fitem fi2
                                   where 1=1
                                   and pi2."FItem" = fi2."FItem"
                                   and pi2."FormCode" = fi2."FormCode"
                                   and pi2."AppUser" > 0
                                   and fi2."Deleted" = 0
                                   and fi2."Code" = 'MU_HOS1D'
                                   and pi2."AnsDate" <= pDateTo12
                                   and pi2."AnsType" = 4                            --date answer only
                                   and pi2."PForm" = pi."PForm"
                                   and pi2."Patient" = pi."Patient"
                                   and pi2."FormCode" = pi."FormCode")
                      )
          select
            tpi."PForm",
            trim(to_char(tpi."PItem", '0000000000')) "IdExtension",
            htf.escape_sc(nvl(trim(tpi."XMLDescription"), 'Unknown')) "XMLDescription",
            trim(to_char(tpi."AppDateTime", 'RRRRMMDDHH24MISS')) "AppDateTime",
            htf.escape_sc(nvl(nvl(substr(trim(tpi."Answer"), 1, (instr(trim(tpi."Answer"), ' ') - 1)), trim(tpi."Answer")), 'Unknown')) "XMLCode"
          from TmpPItem tpi
          where 1=1
         ) tpi2
    where 1=1
    order by
      tpi2."PForm",
      tpi2."AppDateTime",
      tpi2."IdExtension";

  cursor cOrderedInterventionsCQM22 (
                                     pPatient12 patient."Patient"%type,
                                     pDateFrom12 date,
                                     pDateTo12 date
                                    ) is
    select
('          <entry>
              <act classCode=ACT moodCode=RQO >
                <!-- Plan of Care Activity Act template -->
                <templateId root="2.16.840.1.113883.10.20.22.4.39" extension="2014-06-09"/>
                <!-- Intervention Order template -->
                <templateId root="2.16.840.1.113883.10.20.24.3.31" extension="2017-08-01"/>
                <id root="1.3.6.1.4.1.115" extension="' || tpi2."IdExtension" || '"/>
                <code code="' || tpi2."XMLCode" || '" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED-CT"/>
                <text>Intervention, Order: ' || tpi2."XMLDescription" || '</text>
                <statusCode code=active/>
                <author>
                  <templateId root="2.16.840.1.113883.10.20.24.3.155" extension="2017-08-01"/>
                  <time value=''' || tpi2."AppDateTime" || '''/>
                  <assignedAuthor>
                      <id nullFlavor=NA/>
                  </assignedAuthor>
                </author>
              </act>
            </entry>
') "XMLInterventionOrdered"
    from (
          with
          TmpPForm as (
                       select
                         pf."FormCode",
                         pf."Patient",
                         pf."PForm"
                       from pform pf
                       where 1=1
                       and pf."Inactive" = 0
                       and pf."Approved" = 1
                       and exists (select 1
                                   from fitem fi
                                   where 1=1
                                   and fi."Deleted" = 0
                                   and fi."Code" in ('MDH_BPFLWP', 'MDH_BPFLW2', 'MDH_BPREFR') --  removed this code, 'MDH_BPRCMD'
                                   and fi."FormCode" = pf."FormCode")
                       and pf."Patient" = pPatient12
                      ),
          TmpPItem as (
                       select
                         pi."PForm",
                         pi."PItem",
                         nvl(pi."AppDateTime", pi."AppDate") "AppDateTime",
                         trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi."FormCode",
                                                                 pi."Patient",
                                                                 pi."PForm",
                                                                 pi."FItem",
                                                                 pi."AuditNumber",
                                                                 pi."PItemCol")) "Answer"
                       from
                         pitem pi,
                         fitem fi
                       where 1=1
                       and pi."FItem" = fi."FItem"
                       and pi."FormCode" = fi."FormCode"
                       and pi."AppUser" > 0
                       and fi."Deleted" = 0
 					   and fi."Code" in ('MDH_BPFLWP', 'MDH_BPFLW2',  'MDH_BPREFR') -- removed this code 'MDH_BPRCMD',
                       and trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi."FormCode",
                                                                   pi."Patient",
                                                                   pi."PForm",
                                                                   pi."FItem",
                                                                   pi."AuditNumber",
                                                                   pi."PItemCol")) is not null
--AX-21948c added
                       and not exists
                       (
                         select 1
                         from pitem pi2,
                           fitem fi2
                         where 1=1
                         and fi."Code" = 'MDH_BPFLWP'
                         and pi."PForm" = pi2."PForm"
                         and pi2."FItem" = fi2."FItem"
                         and pi2."AppUser" > 0
                         and fi2."Deleted" = 0
                         and fi2."Code" = 'MUMDH_BPR'
                         and trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi2."FormCode",
                                                                    pi2."Patient",
                                                                    pi2."PForm",
                                                                    pi2."FItem",
                                                                    pi2."AuditNumber",
                                                                   pi2."PItemCol")) is not null)
--AX-21948c end
                       and exists (select 1
                                   from TmpPForm tpf
                                   where 1=1
                                   and tpf."PForm" = pi."PForm"
                                   and tpf."Patient" = pi."Patient"
                                   and tpf."FormCode" = pi."FormCode")
                       and pi."AppDate" between pDateFrom12 and pDateTo12
                      )
          select
            tpi."PForm",
            trim(to_char(tpi."PItem", '0000000000')) "IdExtension",
            htf.escape_sc(nvl(substr(trim(tpi."Answer"), (instr(trim(tpi."Answer"), ' - ') + 3)), 'Unknown')) "XMLDescription",
            trim(to_char(tpi."AppDateTime", 'RRRRMMDDHH24MISS')) "AppDateTime",
            htf.escape_sc(nvl(nvl(substr(trim(tpi."Answer"), 1, (instr(trim(tpi."Answer"), ' ') - 1)), trim(tpi."Answer")), 'Unknown')) "XMLCode"
          from TmpPItem tpi
          where 1=1
         ) tpi2
    where 1=1
    union all
    select
('            <entry>
              <act classCode=ACT moodCode=RQO negationInd="true">
                <!-- Plan of Care Activity Act template -->
                <templateId root="2.16.840.1.113883.10.20.22.4.39" extension="2014-06-09"/>
                <!-- Intervention Order template -->
                <templateId root="2.16.840.1.113883.10.20.24.3.31" extension="2017-08-01"/>
                <id root="1.3.6.1.4.1.115" extension="' || tpi2."IdExtension" || '"/>
                '||
				CASE WHEN  tpi2."XMLCode"='999999' THEN
				'<code nullFlavor=NA sdtc:valueSet="2.16.840.1.113883.3.600.823"/>'
				ELSE
                '<code code="' || tpi2."XMLCode" || '" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED-CT"/>
				' END
                ||'<text>Intervention, Order: ' || tpi2."XMLDescription" || '</text>
                <statusCode code=active/>
                <author>
                  <templateId root="2.16.840.1.113883.10.20.24.3.155" extension="2017-08-01"/>
                  <time value=''' || tpi2."AppDateTime" || '''/>
                  <assignedAuthor>
                      <id nullFlavor=NA/>
                  </assignedAuthor>
                </author>
                <entryRelationship typeCode=RSON>
                  <observation classCode=OBS moodCode=EVN>
                    <templateId root="2.16.840.1.113883.10.20.24.3.88" extension="2014-12-01"/>
                    <id root="1.3.6.1.4.1.115" extension="' || tpi2."IdExtension2" || '" />
                    <code code="77301-0" codeSystem="2.16.840.1.113883.6.1" displayName=reason codeSystemName=LOINC/>
                    <statusCode code=completed/>
                    <value code="' || tpi2."XMLCode2" || '" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED-CT" xsi:type=CD/>
                  </observation>
                </entryRelationship>
              </act>
            </entry>
') "XMLInterventionOrdered"
    from (
          with
          TmpPForm as (
                       select
                         pf."FormCode",
                         pf."Patient",
                         pf."PForm"
                       from pform pf
                       where 1=1
                       and pf."Inactive" = 0
                       and pf."Approved" = 1
                       and exists (select 1
                                   from fitem fi
                                   where 1=1
                                   and fi."Deleted" = 0
                                   and fi."Code" = 'MDH_BPFLWP'						--AX-21948c
                                   and fi."FormCode" = pf."FormCode")
                       and exists (select 1
                                   from fitem fi2
                                   where 1=1
                                   and fi2."Deleted" = 0
                                   and fi2."Code" = 'MUMDH_BPR'
                                   and fi2."FormCode" = pf."FormCode")
                       and pf."Patient" = pPatient12
                      ),
          TmpPItem as (
                       select
                         pi."PForm",
                         pi."PItem",
                         nvl(pi."AppDateTime", pi."AppDate") "AppDateTime",
                         trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi."FormCode",
                                                                 pi."Patient",
                                                                 pi."PForm",
                                                                 pi."FItem",
                                                                 pi."AuditNumber",
                                                                 pi."PItemCol")) "Answer",
                         pi2."PItem" "PItem2",
                         trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi2."FormCode",
                                                                 pi2."Patient",
                                                                 pi2."PForm",
                                                                 pi2."FItem",
                                                                 pi2."AuditNumber",
                                                                 pi2."PItemCol")) "Answer2"
                       from
                         pitem pi,
                         fitem fi,
                         pitem pi2,
                         fitem fi2
                       where 1=1
                       and pi."FItem" = fi."FItem"
                       and pi."FormCode" = fi."FormCode"
                       and pi."AppUser" > 0
                       and fi."Deleted" = 0
                       and fi."Code" = 'MDH_BPFLWP'									--AX-21948c
                       and trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi."FormCode",
                                                                   pi."Patient",
                                                                   pi."PForm",
                                                                   pi."FItem",
                                                                   pi."AuditNumber",
                                                                   pi."PItemCol")) is not null
                       and exists (select 1
                                   from TmpPForm tpf
                                   where 1=1
                                   and tpf."PForm" = pi."PForm"
                                   and tpf."Patient" = pi."Patient"
                                   and tpf."FormCode" = pi."FormCode")
                       and pi2."FItem" = fi2."FItem"
                       and pi2."FormCode" = fi2."FormCode"
                       and pi2."AppUser" > 0
                       and fi2."Deleted" = 0
                       and fi2."Code" = 'MUMDH_BPR'
                       and trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi2."FormCode",
                                                                   pi2."Patient",
                                                                   pi2."PForm",
                                                                   pi2."FItem",
                                                                   pi2."AuditNumber",
                                                                   pi2."PItemCol")) is not null
                       and pi2."PForm" = pi."PForm"
                       and pi2."Patient" = pi."Patient"
                       and pi2."FormCode" = pi."FormCode"
                       and pi."AppDate" between pDateFrom12 and pDateTo12
                      )
          select
            tpi."PForm",
            trim(to_char(tpi."PItem", '0000000000')) "IdExtension",
            htf.escape_sc(nvl(substr(trim(tpi."Answer"), (instr(trim(tpi."Answer"), ' - ') + 3)), 'Unknown')) "XMLDescription",
            trim(to_char(tpi."AppDateTime", 'RRRRMMDDHH24MISS')) "AppDateTime",
            htf.escape_sc(nvl(nvl(substr(trim(tpi."Answer"), 1, (instr(trim(tpi."Answer"), ' ') - 1)), trim(tpi."Answer")), 'Unknown')) "XMLCode",
            trim(to_char(tpi."PItem2", '0000000000')) "IdExtension2",
            htf.escape_sc(nvl(nvl(substr(trim(tpi."Answer2"), 1, (instr(trim(tpi."Answer2"), ' ') - 1)), trim(tpi."Answer2")), 'Unknown')) "XMLCode2"
          from TmpPItem tpi
          where 1=1
         ) tpi2
    where 1=1
    -- AX-22004 added on December 21 to handle negations and lab tests and diagnostic codes
    union
    select
('            <entry>
              <observation classCode=OBS moodCode=RQO'|| CASE WHEN LENGTH (BPRCMD."NegationCode")>0 THEN ' negationInd="true"' ELSE '' END ||'>
                 <!-- Consolidation Plan of Care Activity Observation -->
                <templateId root="2.16.840.1.113883.10.20.22.4.44" extension="2014-06-09"/>
                <!-- Lab Test Order -->
                <templateId root="'|| BPRCMD."TemplateId"||'" extension="2017-08-01"/>
                <id root="1.3.6.1.4.1.115" extension="'|| BPRCMD."IdExtension" ||'"/>
				'
				||
				CASE WHEN BPRCMD."ProcedureCode"='199999' THEN
				'<code nullFlavor=NA sdtc:valueSet="2.16.840.1.113883.3.600.2448"/>
				'
					 WHEN BPRCMD."ProcedureCode"='299999' THEN
				'<code nullFlavor=NA sdtc:valueSet="2.16.840.1.113883.3.600.1482"/>
				'	
					ELSE
                '  <code code="'||BPRCMD."ProcedureCode"||'" codeSystem="'||BPRCMD."CodeSystem" ||'" codeSystemName="'||BPRCMD."CodeSystemName"||'"/>
				'
                    END||
                '<text>'||BPRCMD."ProcedureCodeDescription" ||' </text>
                <statusCode code=active/>
                <author>
                  <templateId root="2.16.840.1.113883.10.20.24.3.155" extension="2017-08-01"/>
                  <time value='''|| BPRCMD."Date"||'''/>
                  <assignedAuthor>
                      <id nullFlavor=NA/>
                  </assignedAuthor>
                </author>'||
                CASE WHEN LENGTH (BPRCMD."NegationCode")>0 THEN
                '<entryRelationship typeCode=RSON>
                  <observation classCode=OBS moodCode=EVN>
                    <templateId root="2.16.840.1.113883.10.20.24.3.88" extension="2014-12-01"/>
                    <id root="1.3.6.1.4.1.115" extension="'|| BPRCMD."IdExtension"||'a" />
                    <code code="77301-0" codeSystem="2.16.840.1.113883.6.1" displayName=reason codeSystemName=LOINC/>
                    <statusCode code=completed/>
                    <value code="'||BPRCMD."NegationCode"||'" codeSystem="' ||BPRCMD."NegationSystem" || '" codeSystemName="'||BPRCMD."NegationSysName"||'" xsi:type=CD/>
                  </observation>
                </entryRelationship>'
                   ELSE '' END ||
                 '</observation>
            </entry>
') "XMLInterventionOrdered"
    from (
        with my_negation as (
                            select * from (
                                SELECT
                                        p2."PForm",
                                        REGEXP_SUBSTR (p2."AnsListDesc",'^\D*(\d+) ',1,1,NULL,1) AS "NegationCode",
                                        SUBSTR (p2."AnsListDesc",INSTR (p2."AnsListDesc",REGEXP_SUBSTR (p2."AnsListDesc",'[[:alpha:]]+',1,1),1,1),LENGTH (p2."AnsListDesc")) AS "NegationDescription",
                                        p2."AuditNumber",
                                        DENSE_RANK () OVER (PARTITION BY p2."Patient", p2."PForm" ORDER BY p2."AuditNumber" DESC) AS D_RANK_NUM,
                                        p2."Patient",
                                        p2."Date",
                                        p2."FormCode",
                                        f2."Code",
                                        p2."AnsListDesc",
                                        trim(to_char(p2."PItem", '0000000000')) "IdExtension",
                                        'SNOMED-CT' as "NegationSysName",
                                        '2.16.840.1.113883.6.96' as "NegationSystem"
                                FROM PITEM p2 join FITEM f2 on  p2."FItem" = f2."FItem"
                                  WHERE     1 = 1
                                        AND f2."Code" = 'MDH_BPRCMR'
                                       and p2."Patient" = pPatient12
                                   )
                                   where D_RANK_NUM =1
                                )
            SELECT
                    "Status" as "PStatus"
                    ,'2.16.840.1.113883.6.1' as "CodeSystem"
                    , "PForm"
                    , 'LOINC' as "CodeSystemName"
                    , htf.escape_sc(nvl(nvl(substr(trim("AnsListDesc"), 1, (instr(trim("AnsListDesc"), ' ') - 1)), trim("AnsListDesc")), 'Unknown')) as "ProcedureCode"
                    , "ProcedureDescription" "ProcedureCodeDescription"
                    , "Patient"
                    , trim(to_char("Date", 'RRRRMMDDHH24MISS')) "Date"
                    , "IdExtension"
                    , "AnsListDesc"
                    , CASE WHEN htf.escape_sc(nvl(nvl(substr(trim("AnsListDesc"), 1, (instr(trim("AnsListDesc"), ' ') - 1)), trim("AnsListDesc")), 'Unknown'))
                            in ('11524-6', '34534-8') THEN 'Diagnostic Study'
                            ELSE 'Laboratory Test' END As "DataCategory"
                    , CASE WHEN htf.escape_sc(nvl(nvl(substr(trim("AnsListDesc"), 1, (instr(trim("AnsListDesc"), ' ') - 1)), trim("AnsListDesc")), 'Unknown'))
                            in ('11524-6', '34534-8',  '199999') THEN '2.16.840.1.113883.10.20.24.3.17'

                          ELSE '2.16.840.1.113883.10.20.24.3.37' END As "TemplateId"
                    , "NegationCode"
                    , "NegationDescription"
                    , "NegationSysName"
                    , "NegationSystem"
                    , "Status"
                           FROM
                           (SELECT
                                        p2."Status",
                                        p2."PForm",
                                        REGEXP_SUBSTR (p2."AnsListDesc", '^\D*(\d+) ',1, 1, NULL, 1) AS "ProcedureCode",
                                        SUBSTR (p2."AnsListDesc", INSTR (p2."AnsListDesc", REGEXP_SUBSTR (p2."AnsListDesc",'[[:alpha:]]+',1,1),1,1),LENGTH (p2."AnsListDesc")) AS "ProcedureDescription",
                                        p2."AuditNumber",
                                        DENSE_RANK () OVER (PARTITION BY p2."Patient", p2."PForm" ORDER BY p2."AuditNumber" DESC) AS D_RANK_NUM,
                                        p2."Patient",
                                        p2."Date",
                                        p2."FormCode",
                                        f2."Code",
                                        p2."AnsListDesc",
                                        trim(to_char(p2."PItem", '0000000000')) "IdExtension",
                                        mn."NegationCode",
                                        mn."NegationDescription",
                                        mn."NegationSysName",
                                        mn."NegationSystem"
                                   FROM PITEM p2
                                   join FITEM f2 on p2."FItem" = f2."FItem"
                                  left join my_negation mn on mn."PForm" = p2."PForm"
                                  WHERE     1 = 1
                                        AND f2."Code" = 'MDH_BPRCMD'
                                       and p2."Patient" = pPatient12
                                 ) a
        WHERE a.D_RANK_NUM = 1
    ) BPRCMD    ;
-- end of AX-22004

  cursor cPerformedInterventions (
                                  pPatient13 patient."Patient"%type,
                                  pDateTo13 date
                                 ) is
    select
('            <entry>
              <act classCode=ACT moodCode=EVN >
                <!-- Consolidation CDA: Procedure Activity Act template -->
                <templateId root="2.16.840.1.113883.10.20.22.4.12" extension="2014-06-09"/>
                <!-- Intervention Performed Template -->
                <templateId root="2.16.840.1.113883.10.20.24.3.32" extension="2017-08-01"/>
                <id root="1.3.6.1.4.1.115" extension="' || tpi2."IdExtension" || '"/>
                  <code code="' || tpi2."XMLCode" || '" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED-CT"/>
                <text>' || tpi2."XMLDescription" || '</text>
                <statusCode code=completed/>
                <effectiveTime><low value=''' || tpi2."AppDateTime" || '''/><high value=''' || tpi2."AppDateTime" || '''/></effectiveTime>
                <author>
                  <templateId root="2.16.840.1.113883.10.20.24.3.155" extension="2017-08-01"/>
                  <time value=''' || tpi2."AppDateTime" || '''/>
                  <assignedAuthor>
                      <id nullFlavor=NA/>
                  </assignedAuthor>
                </author>
              </act>
            </entry>
') "XMLInterventionPerformed"
    from (
          with
          TmpPForm as (
                       select
                         pf."FormCode",
                         pf."Patient",
                         pf."PForm"
                       from pform pf
                       where 1=1
                       and pf."Inactive" = 0
                       and pf."Approved" = 1
                       and exists (select 1
                                   from fitem fi
                                   where 1=1
                                   and fi."Deleted" = 0
                                   and fi."Code" = 'MU_HOS2'
                                   and fi."FormCode" = pf."FormCode")
                       and exists (select 1
                                   from fitem fi2
                                   where 1=1
                                   and fi2."Deleted" = 0
                                   and fi2."Code" = 'MU_HOS2D'
                                   and fi2."FormCode" = pf."FormCode")
                       and pf."Patient" = pPatient13
                      ),
          TmpPItem as (
                       select
                         pi."PForm",
                         pi."PItem",
                         nvl(pi."AppDateTime", pi."AppDate") "AppDateTime",
                         trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi."FormCode",
                                                                 pi."Patient",
                                                                 pi."PForm",
                                                                 pi."FItem",
                                                                 pi."AuditNumber",
                                                                 pi."PItemCol")) "Answer",
                         'Intervention, Performed: Hospice care ambulatory' "XMLDescription"
                       from
                         pitem pi,
                         fitem fi
                       where 1=1
                       and pi."FItem" = fi."FItem"
                       and pi."FormCode" = fi."FormCode"
                       and pi."AppUser" > 0
                       and fi."Deleted" = 0
                       and fi."Code" = 'MU_HOS2'
                       and trim(mu_core_pkg.GetEPRFormItemAnswer_F(pi."FormCode",
                                                                   pi."Patient",
                                                                   pi."PForm",
                                                                   pi."FItem",
                                                                   pi."AuditNumber",
                                                                   pi."PItemCol")) is not null
                       and exists (select 1
                                   from TmpPForm tpf
                                   where 1=1
                                   and tpf."PForm" = pi."PForm"
                                   and tpf."Patient" = pi."Patient"
                                   and tpf."FormCode" = pi."FormCode")
                       and exists (select 1
                                   from
                                     pitem pi2,
                                     fitem fi2
                                   where 1=1
                                   and pi2."FItem" = fi2."FItem"
                                   and pi2."FormCode" = fi2."FormCode"
                                   and pi2."AppUser" > 0
                                   and fi2."Deleted" = 0
                                   and fi2."Code" = 'MU_HOS2D'
                                   and pi2."AnsDate" <= pDateTo13
                                   and pi2."AnsType" = 4                            --date answer only
                                   and pi2."PForm" = pi."PForm"
                                   and pi2."Patient" = pi."Patient"
                                   and pi2."FormCode" = pi."FormCode")
                      )
          select
            tpi."PForm",
            trim(to_char(tpi."PItem", '0000000000')) "IdExtension",
            htf.escape_sc(nvl(trim(tpi."XMLDescription"), 'Unknown')) "XMLDescription",
            trim(to_char(tpi."AppDateTime", 'RRRRMMDDHH24MISS')) "AppDateTime",
            htf.escape_sc(nvl(nvl(substr(trim(tpi."Answer"), 1, (instr(trim(tpi."Answer"), ' ') - 1)), trim(tpi."Answer")), 'Unknown')) "XMLCode"
          from TmpPItem tpi
          where 1=1
         ) tpi2
    where 1=1
    order by
      tpi2."PForm",
      tpi2."AppDateTime",
      tpi2."IdExtension";

---------- Samir_Boudjebla Added this section
-- cursor of allergies
	-- Special cases which use forms to collect the data 147.
  cursor cAllergies (pPatient14 patient."Patient"%type) is
    select
('            <entry>
              <observation classCode=OBS moodCode=EVN>
                <!-- Conforms to C-CDA R2.1 Substance or Device Allergy - Intolerance Observation (V2) -->
                <templateId root="2.16.840.1.113883.10.20.24.3.90" extension="2014-06-09"/>
                <!-- Allergy Intolerance -->
                <templateId root="2.16.840.1.113883.10.20.24.3.147" extension="2017-08-01"/>
                <id root="1.3.6.1.4.1.115" extension="' || a2."IdExtension" || '"/>
                <code code="assertion" codeSystem="2.16.840.1.113883.5.4"/>
                <statusCode code=completed/>
                <effectiveTime><low value=''' || a2."Date" || '''/><high nullFlavor=''UNK''/></effectiveTime>
                <value xsi:type=CD
                       code="419199007"
                       displayName="Allergy to substance"
                       codeSystem="2.16.840.1.113883.6.96"
                       codeSystemName="SNOMED CT"/>
                <author>
                  <templateId root="2.16.840.1.113883.10.20.24.3.155" extension="2017-08-01"/>
                  <time value=''' || a2."Date" || '''/>
                  <assignedAuthor>
                      <id nullFlavor=NA/>
                  </assignedAuthor>
                </author>                <participant typeCode=CSM>
                  <participantRole classCode=MANU>
                    <playingEntity classCode=MMAT>
                        <code code="' || a2."ProcedureCode" || '" codeSystem="' || a2."CodeSystem" || '" codeSystemName="' || a2."CodeSystemName" || '"/>
                      <name>Allergy/Intolerance: ' || a2."ProcedureCodeDescription" || '</name>
                    </playingEntity>
                  </participantRole>
                </participant>
              </observation>
            </entry>
') "XMLAllergy"
    from (
                SELECT
                     '2.16.840.1.113883.12.292' as "CodeSystem"
                    , 'CVX' as "CodeSystemName"
                    ,"ProcedureCode"
                    , htf.escape_sc("ProcedureCodeDescription") "ProcedureCodeDescription"
                    , "Patient"
                    , trim(to_char("Date", 'RRRRMMDDHH24MISS')) "Date"
                    , "IdExtension"
                           FROM (SELECT p2."PForm",
                                        REGEXP_SUBSTR (p2."AnsListDesc",
                                                       '^\D*(\d+) ',
                                                       1,
                                                       1,
                                                       NULL,
                                                       1)
                                            AS "ProcedureCode",
                                        SUBSTR (p2."AnsListDesc",
                                                INSTR (p2."AnsListDesc",
                                                       REGEXP_SUBSTR (p2."AnsListDesc",
                                                                      '[[:alpha:]]+',
                                                                      1,
                                                                      1),
                                                       1,
                                                       1),
                                                LENGTH (p2."AnsListDesc"))
                                            AS "ProcedureCodeDescription",
                                        p2."AnsListDesc"
                                            AS "PneumococcalAnsListDesc",
                                        p2."AuditNumber"
                                            AS "PneumococcalAuditNumber",
                                        DENSE_RANK ()
                                            OVER (PARTITION BY p2."Patient", p2."PForm"
                                                  ORDER BY p2."AuditNumber" DESC)
                                            AS D_RANK_NUM,
                                        p2."Patient",
                                        p2."Date",
                                        p2."FormCode",
                                        f2."Code",
                                        trim(to_char(p2."PItem", '0000000000')) "IdExtension"
                                   FROM PITEM p2, FITEM f2
                                  WHERE     1 = 1
                                        --AND p2."FormCode" = vFormCode
                                        AND p2."FItem" = f2."FItem"
                                        AND f2."Code" = 'INFLACVX'
                                       and p2."Patient" = pPatient14
                                 ) a
                          WHERE a.D_RANK_NUM = 1
            union
            select
                    "CodeSystem"
                    , 'SNOMED-CT' as "CodeSystemName"
                    , "ProcedureCode"
                    , htf.escape_sc("ProcedureCodeDescription") "ProcedureCodeDescription"
                    , "Patient"
                    , trim(to_char("Date", 'RRRRMMDDHH24MISS')) "Date"
                    , "IdExtension"
                FROM (
                        select
                                '2.16.840.1.113883.6.96' as "CodeSystem"
                                , ptal."SNOCode" AS "ProcedureCode"
                                , ptal."Description" AS "ProcedureCodeDescription"
                                , ptal."Patient"
                                , CAST (ptal."AddDateTime" AS DATE)AS "Date"
                                , DENSE_RANK () OVER (PARTITION BY ptal."Patient"ORDER BY ptal."Audit" DESC)  AS D_RANK_NUM
                                , trim(to_char(ptal."PtAlert", '0000000000')) "IdExtension"
                        from PTALERTH ptal
                        where   ptal."Status" = 0
                            AND ptal."Deleted" = 0
                            and ptal."AlertType" = 2
                            -- allergies
                            AND ptal."SNOCode" IN ('102263004','226881001','226885005','229955000','256442007','256443002','286550009','303300008',
                                                                  '414074006', '86198006')
                            and ptal."Patient" = pPatient14
                      ) a
                      where a.D_RANK_NUM = 1
         ) a2
    where 1=1;

  vXMLHeaderTemplate clob :=
'<?xml version="1.0" encoding="utf-8"?>
<ClinicalDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:hl7-org:v3" xmlns:voc="urn:hl7-org:v3/voc" xmlns:sdtc="urn:hl7-org:sdtc">

<!-- QRDA Header -->
<realmCode code=US/>
<typeId root="2.16.840.1.113883.1.3" extension=POCD_HD000040/>
<!-- US Realm Header Template Id -->
<templateId root="2.16.840.1.113883.10.20.22.1.1" extension="2015-08-01"/>
<!-- QRDA templateId -->
<templateId root="2.16.840.1.113883.10.20.24.1.1" extension="2017-08-01"/>
<!-- QDM-based QRDA templateId -->
<templateId root="2.16.840.1.113883.10.20.24.1.2" extension="2017-08-01"/>
<!-- CMS QRDA templateId -->
<templateId root="2.16.840.1.113883.10.20.24.1.3" extension="2018-02-01"/>
<!-- This is the globally unique identifier for this QRDA document -->
<id root="c8665400-b85b-0136-51b2-0e95690c4dba"/>
<!-- QRDA document type code -->
<code code="55182-0" codeSystem="2.16.840.1.113883.6.1" codeSystemName=LOINC displayName="Quality Measure Report"/>
<title>QRDA Incidence Report</title>
<!-- This is the document creation time -->
<effectiveTime value="xxxDateTimexxx"/>
<confidentialityCode code=N codeSystem="2.16.840.1.113883.5.25"/>
<languageCode code=en/>
<!-- reported patient -->
<recordTarget>
  <patientRole>
    <!--id extension="a3312ac3-d215-438e-8c73-709c290b1cbd_43" root="Bonnie"/-->
    <!--id extension="a3312ac3-d215-438e-8c73-709c290b1cbd_43" root="1.3.6.1.4.1.115" /-->
    <!-- axiUm PatientID number -->
    <id extension="xxxPatientxxx" root="1.3.6.1.4.1.115" />
    <addr use=HP>
      <streetAddressLine>xxxAddressxxx</streetAddressLine>
      <city>xxxCityxxx</city>
      <state>xxxStatexxx</state>
      <postalCode>xxxPostalxxx</postalCode>
      <country>xxxCountryxxx</country>
    </addr>
    <telecom use="xxxPhoneCodexxx" value="xxxPhonexxx"/>
    <patient>
      <name>
        <given>xxxFirstxxx</given>
        <family>xxxLastxxx</family>
      </name>
      <administrativeGenderCode code="xxxGenderxxx" codeSystem="2.16.840.1.113883.5.1" codeSystemName="HL7 AdministrativeGender"/>
      <birthTime value="xxxBirthxxx"/>
      <raceCode code="xxxRaceCodexxx" displayName="xxxRaceDescriptionxxx" codeSystemName="CDC Race and Ethnicity" codeSystem="2.16.840.1.113883.6.238"/>
      <ethnicGroupCode code="xxxEthnicCodexxx" displayName="xxxEthnicDescriptionxxx" codeSystemName="CDC Race and Ethnicity" codeSystem="2.16.840.1.113883.6.238"/>
      <languageCommunication>
        <templateId root="2.16.840.1.113883.3.88.11.83.2" assigningAuthorityName="HITSP/C83"/>
        <templateId root="1.3.6.1.4.1.19376.1.5.3.1.2.1" assigningAuthorityName="IHE/PCC"/>
        <languageCode code="xxxLanguageCodexxx"/>
      </languageCommunication>
    </patient>
  </patientRole>
</recordTarget><author>
  <time value="xxxDateTimexxx"/>
  <assignedAuthor>
    <!-- NPI -->
      <id extension="xxxProviderNPIxxx" root="2.16.840.1.113883.4.6"/>
    <addr>
      <streetAddressLine>xxxProviderAddressxxx</streetAddressLine>
      <city>xxxProviderCityxxx</city>
      <state>xxxProviderStatexxx</state>
      <postalCode>xxxProviderPostalxxx</postalCode>
      <country>xxxDefaultCountryxxx</country>
    </addr>
    <telecom use=WP value="xxxProviderPhonexxx"/>
    <assignedAuthoringDevice>
      <manufacturerModelName>Exan Software</manufacturerModelName>
      <softwareName>axiUm</softwareName>
    </assignedAuthoringDevice>
  </assignedAuthor>
</author><custodian>
  <assignedCustodian>
    <representedCustodianOrganization>
        <id extension="xxxPracticeNPIxxx" root="2.16.840.1.113883.4.336"/>
      <name>xxxPracticeNamexxx</name>
      <telecom use=WP value="xxxPracticePhonexxx"/>
        <addr use=HP>
          <streetAddressLine>xxxPracticeAddressxxx</streetAddressLine>
          <city>xxxPracticeCityxxx</city>
          <state>xxxPracticeStatexxx</state>
          <postalCode>xxxPracticePostalxxx</postalCode>
          <country>xxxDefaultCountryxxx</country>
        </addr>
    </representedCustodianOrganization>
  </assignedCustodian>
</custodian>
<legalAuthenticator>
  <time value="xxxDateTimexxx"/>
  <signatureCode code=S/>
  <assignedEntity>
    <id root="bc01a5d1-3a34-4286-82cc-43eb04c972a7"/>
    <addr>
      <streetAddressLine>xxxProviderAddressxxx</streetAddressLine>
      <city>xxxProviderCityxxx</city>
      <state>xxxProviderStatexxx</state>
      <postalCode>xxxProviderPostalxxx</postalCode>
      <country>xxxDefaultCountryxxx</country>
    </addr>
    <telecom use=WP value="xxxProviderPhonexxx"/>
    <assignedPerson>
      <name>
        <given>xxxProviderFirstNamexxx</given>
        <family>xxxProviderLastNamexxx</family>
      </name>
    </assignedPerson>
    <representedOrganization>
      <id root="2.16.840.1.113883.19.5"/>
      <name>xxxPracticeNamexxx</name>
    </representedOrganization>
  </assignedEntity>
</legalAuthenticator><participant typeCode=DEV>
  <associatedEntity classCode=RGPR>
    <!-- CMS EHR Certification Number (formerly known as Office of the
        National Coordinator Certification Number) -->
    <id extension="xxxCertificationNumberxxx" root="2.16.840.1.113883.3.2074.1"/>
  </associatedEntity>
</participant>

<component>
  <structuredBody>
    <component>
      <section>
        <!--
          *****************************************************************
          Measure Section
          *****************************************************************
        -->
        <!-- This is the templateId for Measure Section -->
        <templateId root="2.16.840.1.113883.10.20.24.2.2"/>
        <!-- This is the templateId for Measure Section QDM -->
        <templateId root="2.16.840.1.113883.10.20.24.2.3"/>
        <!-- This is the LOINC code for "Measure document". This stays the same for all measure section required by QRDA standard -->
        <code code="55186-1" codeSystem="2.16.840.1.113883.6.1"/>
        <title>Measure Section</title>
        <text>
          <table border="1" width="100%">
            <thead>
              <tr>
                <th>eMeasure Title</th>
                <th>Version specific identifier</th>
              </tr>
            </thead>
            <tbody>
xxxXMLTrTdTempxxx
            </tbody>
          </table>
        </text>
xxxXMLOrganizerTempxxx
      </section>
    </component>

    <component>
      <section>
        <!-- This is the templateId for Reporting Parameters section -->
        <templateId root="2.16.840.1.113883.10.20.17.2.1"/>
        <templateId extension="2016-03-01" root="2.16.840.1.113883.10.20.17.2.1.1"/>
        <code code="55187-9" codeSystem="2.16.840.1.113883.6.1"/>
        <title>Reporting Parameters</title>
        <text></text>
        <entry typeCode=DRIV>
          <act classCode=ACT moodCode=EVN>
            <!-- This is the templateId for Reporting Parameteres Act -->
            <templateId root="2.16.840.1.113883.10.20.17.3.8"/>
            <templateId extension="2016-03-01" root="2.16.840.1.113883.10.20.17.3.8.1"/>
            <id extension="c86b1d00-b85b-0136-51b2-0e95690c4dba" root="1.3.6.1.4.1.115"/>
            <code code="252116004" codeSystem="2.16.840.1.113883.6.96" displayName="Observation Parameters"/>
            <effectiveTime>
              <low value="xxxCQMSDateTimexxx"/>
              <high value="xxxCQMEDateTimexxx"/>
            </effectiveTime>
          </act>
        </entry>
      </section>
    </component>

    <component>
        <section>
          <!-- This is the templateId for Patient Data section -->
          <templateId root="2.16.840.1.113883.10.20.17.2.4"/>
          <!-- This is the templateId for Patient Data QDM section -->
          <templateId extension="2017-08-01" root="2.16.840.1.113883.10.20.24.2.1"/>
          <templateId extension="2018-02-01" root="2.16.840.1.113883.10.20.24.2.1.1"/>
          <code code="55188-7" codeSystem="2.16.840.1.113883.6.1"/>
          <title>Patient Data</title>
          <text/>
xxxXMLAllergyTempxxx
xxxXMLVisitTempxxx
xxxXMLSNOMEDVisitTempxxx
xxxXMLMedicationOrderTempxxx
xxxXMLProcedureTempxxx
xxxXMLProcedureCQM147Tempxxx
xxxXMLDiagnosisTempxxx
xxxXMLDiagnosticStudyTempxxx
xxxXMLLaboratoryTestTempxxx
xxxXMLCommunicationTempxxx
xxxXMLPhysicalExamTempxxx
xxxXMLImmunizationTempxxx
xxxXMLInterventionOrderedTempxxx
xxxXMLInterventionOrderedCQM22Tempxxx
xxxXMLInterventionPerformedTempxxx
        </section>
      </component>
    </structuredBody>
  </component>
</ClinicalDocument>
';

  vXMLTrTdTemp clob := '';
  vXMLOrganizerTemp clob := '';
  vXMLVisitTemp clob := '';
  vXMLSNOMEDVisitTemp clob := '';
  vXMLMedicationOrderTemp clob := '';
  vXMLProcedureTemp clob := '';
  vXMLProcedureCQM147Temp clob := '';
  vXMLDiagnosisTemp clob := '';
  vXMLDiagnosticStudyTemp clob := '';
  vXMLLaboratoryTestTemp clob := '';
  vXMLCommunicationTemp clob := '';
  vXMLPhysicalExamTemp clob := '';
  vXMLImmunizationTemp clob := '';
  vXMLInterventionOrderedTemp clob := '';
  vXMLInterventionPerformedTemp clob := '';
  vXMLAllergyTemp clob := '';

  vCertificationNumber varchar2(4000) := '123456789';                           -- should be replace with actual number after certification
  vDateTime varchar2(4000) := trim(to_char(sysdate, 'RRRRMMDDHH24MISS'));
  vPatient varchar2(4000) := '';
  vAddress varchar2(4000) := '';
  vCity varchar2(4000) := '';
  vState varchar2(4000) := '';
  vPostal varchar2(4000) := '';
  vCountry varchar2(4000) := '';
  vPhoneCode varchar2(4000) := '';
  vPhone varchar2(4000) := '';
  vFirst varchar2(4000) := '';
  vLast varchar2(4000) := '';
  vGender varchar2(4000) := '';
  vBirth varchar2(4000) := '';
  vRaceCode varchar2(4000) := '';
  vRaceDescription varchar2(4000) := '';
  vEthnicCode varchar2(4000) := '';
  vEthnicDescription varchar2(4000) := '';
  vLanguageCode varchar2(4000) := '';

  vProviderNPI varchar2(4000) := '';
  vProviderAddress varchar2(4000) := '';
  vProviderCity varchar2(4000) := '';
  vProviderState varchar2(4000) := '';
  vProviderPostal varchar2(4000) := '';
  vProviderPhone varchar2(4000) := '';
  vDefaultPractice producer."DefaultPractice"%type := 0;
  vDefaultCountry varchar2(4000) := 'United States of America';
  vProviderFirstName varchar2(4000) := '';
  vProviderLastName varchar2(4000) := '';
  vCQMSDateTime varchar2(4000) := '';
  vCQMEDateTime varchar2(4000) := '';
  vCQMSDate date := to_date(null);
  vCQMEDate date := to_date(null);
  vCQMSDate2 date := to_date(null);
  vCQMEDate2 date := to_date(null);
  vCQMSDate3 date := to_date(null);
  vCQMEDate3 date := to_date(null);
  vUser users."User"%type := 0;

  vPracticeNPI varchar2(4000) := '';
  vPracticeName varchar2(4000) := '';
  vPracticePhone varchar2(4000) := '';
  vPracticeAddress varchar2(4000) := '';
  vPracticeCity varchar2(4000) := '';
  vPracticeState varchar2(4000) := '';
  vPracticePostal varchar2(4000) := '';

  vStage mryear."Stage"%type := 3;                                              -- works for stage 3 only
  vStep INTEGER := 0;

begin
  --
  -- populate producer related variables
  --
  vStep := 10;

  select
    htf.escape_sc(nvl(trim(prod."NPI"), ' ')) "ProviderNPI",
    htf.escape_sc(nvl((trim(prod."Address1") || nvl2(trim(prod."Address1"), ', ', '') || trim(prod."Address2")), ' ')) "ProviderAddress",
    htf.escape_sc(nvl(trim(prod."City"), ' ')) "ProviderCity",
    htf.escape_sc(nvl(trim(prod."Province"), ' ')) "ProviderState",
    htf.escape_sc(nvl(trim(prod."Postal"), ' ')) "ProviderPostal",
    htf.escape_sc(('tel:+1-' || trim(prod."BArea") || '-' || trim(prod."BTel"))) "ProviderPhone",
    prod."DefaultPractice",
    htf.escape_sc(nvl(trim(prod."FirstName"), ' ')) "ProviderFirstName",
    htf.escape_sc(nvl(trim(prod."LastName"), ' ')) "ProviderLastName",
    to_char(trunc(my."DateFrom"), 'RRRRMMDDHH24MISS') "CQMSDateTime",    			-- AX-24377
	to_char(trunc(my."DateTo") + (86399/86400), 'RRRRMMDDHH24MISS') "CQMEDateTime",	-- AX-24377
    trunc(my."DateFrom") "CQMSDate",												-- AX-24377
    trunc(my."DateTo") + (86399/86400) "CQMEDate",									-- AX-24377
    my."User"
  into
    vProviderNPI,
    vProviderAddress,
    vProviderCity,
    vProviderState,
    vProviderPostal,
    vProviderPhone,
    vDefaultPractice,
    vProviderFirstName,
    vProviderLastName,
    vCQMSDateTime,
    vCQMEDateTime,
    vCQMSDate,
    vCQMEDate,
    vUser
  from
    producer prod,
    users u,
    mryear my
  where 1=1
  and u."Producer" = prod."Producer"
  and my."User" = u."User"
  and u."Deleted" = 0
  and prod."MUEligible" = 1
  and prod."Producer" = pProducer
  and my."Stage" = vStage
  and my."Year" = pYear;

  --
  -- populate other date variables
  --
  vStep := 20;

  vCQMSDate2 := add_months(vCQMSDate, -3);                  -- October 1st
  vCQMEDate2 := (add_months(vCQMSDate, 3) - (1/86400));     -- March 31st (one second before midnight)
  vCQMSDate3 := add_months(vCQMSDate, -5);                  -- August 1st
  vCQMEDate3 := vCQMEDate2;                                 -- March 31st (one second before midnight)

  --
  -- replace producer related variables with actual values
  --
  vStep := 30;

  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxProviderNPIxxx', vProviderNPI);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxProviderAddressxxx', vProviderAddress);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxProviderCityxxx', vProviderCity);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxProviderStatexxx', vProviderState);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxProviderPostalxxx', vProviderPostal);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxProviderPhonexxx', vProviderPhone);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxDefaultCountryxxx', vDefaultCountry);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxProviderFirstNamexxx', vProviderFirstName);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxProviderLastNamexxx', vProviderLastName);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxCQMSDateTimexxx', vCQMSDateTime);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxCQMEDateTimexxx', vCQMEDateTime);

  --
  -- populate patient related variables
  --
  vStep := 40;

  with
  TmpRace as (
              select
                rptr."Patient",
                rptr."Race",
                rptr."RaceCode",
                rptr."RaceDescription"
              from (
                    select
                      ptr."Patient",
                      ptr."Race",
                      (case ptr."Race"
                         when 'NATIVE' then '1002-5'
                         when 'ASIAN' then '2028-9'
                         when 'BLACK' then '2054-5'
                         when 'ISLAND' then '2076-8'
                         when 'WHITE' then '2106-3'
                         when 'OTHER' then '2131-1'
                         else 'UNK'
                       end) "RaceCode",
                      trim(r."Description") "RaceDescription",
                      (row_number() over (partition by ptr."Patient"
                                          order by ptr."Audit" desc)) "RowNumber"
                    from
                      ptrace ptr,
                      race r
                    where 1=1
                    and r."Race" = ptr."Race"
                    and ptr."Deleted" = 0
                   ) rptr
              where 1=1
              and rptr."RowNumber" = 1
                 ),
  TmpEthnic as (
                select
                  e."Ethnic",
                  (case e."USType"
                     when 0 then '2135-2'
                     when 1 then '2186-5'
                     else 'UNK'
                   end) "EthnicCode",
                  trim(e."Description") "EthnicDescription"
                from ethnic e
                where 1=1
               )
  select
    trim(to_char(p."Patient")) "Patient",
    htf.escape_sc(nvl((trim(p."Address1") || nvl2(trim(p."Address1"), ', ', '') || trim(p."Address2")), ' ')) "Address",
    htf.escape_sc(nvl(trim(p."City"), ' ')) "City",
    htf.escape_sc(nvl(trim(p."Province"), ' ')) "State",
    htf.escape_sc(nvl(trim(p."Postal"), ' ')) "Postal",
    htf.escape_sc(nvl(trim(p."Country"), ' ')) "Country",
    (case p."ContactAt"
       when 1 then 'HP'
       when 2 then 'WP'
       when 3 then 'HV'
       when 4 then 'MC'
       else ' '
     end) "PhoneCode",
    htf.escape_sc((case p."ContactAt"
                     when 1 then ('tel:+1-' || trim(p."HomeArea") || '-' || trim(p."HomePhone"))
                     when 2 then ('tel:+1-' || trim(p."WorkArea") || '-' || trim(p."WorkPhone"))
                     when 3 then ('tel:+1-' || trim(p."OtherArea") || '-' || trim(p."OtherPhone"))
                     when 4 then ('tel:+1-' || trim(p."MobileArea") || '-' || trim(p."MobilePhone"))
                     else ' '
                   end)) "Phone",
    htf.escape_sc(nvl(trim(p."First"), ' ')) "First",
    htf.escape_sc(nvl(trim(p."Last"), ' ')) "Last",
    (case p."Sex"
       when 1 then 'M'
       when 2 then 'F'
       else 'UNK'
     end) "Gender",
    nvl(trim(to_char(p."Birth", 'RRRRMMDDHH24MISS')), '00000000000000') "Birth",
    (case p."RaceEthDeclined"
       when 0 then nvl(tr."RaceCode", 'UNK')
       else 'UNK'
     end) "RaceCode",
    htf.escape_sc((case p."RaceEthDeclined"
                     when 0 then nvl(tr."RaceDescription", 'UNK')
                     else 'UNK'
                   end)) "RaceDescription",
    (case p."RaceEthDeclined"
       when 0 then nvl(te."EthnicCode", 'UNK')
       else 'UNK'
     end) "EthnicCode",
    htf.escape_sc((case p."RaceEthDeclined"
                     when 0 then nvl(te."EthnicDescription", 'UNK')
                     else 'UNK'
                   end)) "EthnicDescription",
    htf.escape_sc(nvl(trim(lc."ISOCode"), 'UNK')) "LanguageCode"
  into
    vPatient,
    vAddress,
    vCity,
    vState,
    vPostal,
    vCountry,
    vPhoneCode,
    vPhone,
    vFirst,
    vLast,
    vGender,
    vBirth,
    vRaceCode,
    vRaceDescription,
    vEthnicCode,
    vEthnicDescription,
    vLanguageCode
  from
    patient p,
    TmpRace tr,
    TmpEthnic te,
    langcd lc
  where 1=1
  and p."Patient" = tr."Patient" (+)
  and p."Ethnic" = te."Ethnic" (+)
  and p."PrefLanguage" = lc."LangCd" (+)
  and p."Patient" = pPatient
  and rownum = 1;                                                               -- a patient can have multiple races; this will pick the first record randomly

  --
  -- replace patient related variables with actual values
  --
  vStep := 50;

  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxCertificationNumberxxx', vCertificationNumber);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxDateTimexxx', vDateTime);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxPatientxxx', vPatient);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxAddressxxx', vAddress);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxCityxxx', vCity);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxStatexxx', vState);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxPostalxxx', vPostal);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxCountryxxx', vCountry);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxPhoneCodexxx', vPhoneCode);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxPhonexxx', vPhone);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxFirstxxx', vFirst);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxLastxxx', vLast);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxGenderxxx', vGender);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxBirthxxx', vBirth);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxRaceCodexxx', vRaceCode);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxRaceDescriptionxxx', vRaceDescription);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxEthnicCodexxx', vEthnicCode);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxEthnicDescriptionxxx', vEthnicDescription);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxLanguageCodexxx', vLanguageCode);

  --
  -- populate practice related variables
  --
  begin
    --
    -- get information from default practice of provider
    --
    vStep := 60;

    select
      htf.escape_sc(nvl(trim(pr."NPI"), ' ')) "PracticeNPI",
      htf.escape_sc(nvl(trim(pr."Name"), ' ')) "PracticeName",
      htf.escape_sc(('tel:+1-' || trim(pr."Area") || '-' || trim(pr."Phone"))) "PracticePhone",
      htf.escape_sc(nvl((trim(pr."Address1") || nvl2(trim(pr."Address1"), ', ', '') || trim(pr."Address2")), ' ')) "PracticeAddress",
      htf.escape_sc(nvl(trim(pr."City"), ' ')) "PracticeCity",
      htf.escape_sc(nvl(trim(pr."Province"), ' ')) "PracticeState",
      htf.escape_sc(nvl(trim(pr."Postal"), ' ')) "PracticePostal"
    into
      vPracticeNPI,
      vPracticeName,
      vPracticePhone,
      vPracticeAddress,
      vPracticeCity,
      vPracticeState,
      vPracticePostal
    from practice pr
    where 1=1
    and pr."Inactive" = 0
    and pr."Id" = vDefaultPractice;

  exception
    when no_data_found then
      --
      -- get information from 1st practice entered
      --
      vStep := 70;

      select
        htf.escape_sc(nvl(trim(pr."NPI"), ' ')) "PracticeNPI",
        htf.escape_sc(nvl(trim(pr."Name"), ' ')) "PracticeName",
        htf.escape_sc(('tel:+1-' || trim(pr."Area") || '-' || trim(pr."Phone"))) "PracticePhone",
        htf.escape_sc(nvl((trim(pr."Address1") || nvl2(trim(pr."Address1"), ', ', '') || trim(pr."Address2")), ' ')) "PracticeAddress",
        htf.escape_sc(nvl(trim(pr."City"), ' ')) "PracticeCity",
        htf.escape_sc(nvl(trim(pr."Province"), ' ')) "PracticeState",
        htf.escape_sc(nvl(trim(pr."Postal"), ' ')) "PracticePostal"
      into
        vPracticeNPI,
        vPracticeName,
        vPracticePhone,
        vPracticeAddress,
        vPracticeCity,
        vPracticeState,
        vPracticePostal
      from practice pr
      where 1=1
      and pr."Inactive" = 0
      and pr."Id" = (select min(pr2."Id")
                     from practice pr2
                     where 1=1
                     and pr2."Inactive" = 0);

  end;

  --
  -- replace practice related variables with actual values
  --
  vStep := 80;

  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxPracticeNPIxxx', vPracticeNPI);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxPracticeNamexxx', vPracticeName);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxPracticePhonexxx', vPracticePhone);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxPracticeAddressxxx', vPracticeAddress);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxPracticeCityxxx', vPracticeCity);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxPracticeStatexxx', vPracticeState);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxPracticePostalxxx', vPracticePostal);

  --
  -- compose the measure descriptions part of the XML
  --
  vStep := 90;

  for pCQMList in cCQMList loop
    --
    -- add to the XML variable
    --
    vStep := 100;

    vXMLTrTdTemp := (vXMLTrTdTemp || pCQMList."XMLTrTd");

  end loop pCQMList;

  --
  -- add the measure descriptions XML
  --
  vStep := 110;

  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxXMLTrTdTempxxx', vXMLTrTdTemp);

  --
  -- compose the organizers part of the XML
  --
  vStep := 120;

  for pCQMList in cCQMList loop
    --
    -- add to the XML variable
    --
    vStep := 130;

    vXMLOrganizerTemp := (vXMLOrganizerTemp || pCQMList."XMLOrganizer");

  end loop pCQMList;

  --
  -- add the organizers XML
  --
  vStep := 140;

  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxXMLOrganizerTempxxx', vXMLOrganizerTemp);

  --
  -- compose the allergies part of the XML
  --
  vStep := 142;

  for pAllergies in cAllergies (pPatient) loop
    --
    -- add to the XML variable
    --
    vStep := 144;

    vXMLAllergyTemp := (vXMLAllergyTemp || pAllergies."XMLAllergy");

  end loop pAllergies;

  --
  -- add the allergies XML
  --
  vStep := 146;

  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxXMLAllergyTempxxx', vXMLAllergyTemp);

  --
  -- compose the visits part of the XML
  --
  vStep := 150;

  for pVisits in cVisits (
                          pPatient,
                          pProducer,
                          vUser,
                          vCQMSDate,
                          vCQMEDate
                         ) loop
    --
    -- add to the XML variable
    --
    vStep := 160;

    vXMLVisitTemp := (vXMLVisitTemp || pVisits."XMLVisit");

  end loop pVisits;

  --
  -- add the visits XML
  --
  vStep := 170;

  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxXMLVisitTempxxx', vXMLVisitTemp);

  --
  -- compose the SNOMED visits part of the XML
  --
  vStep := 172;

  for pSNOMEDVisits in cSNOMEDVisits (
                                      pPatient,
                                      pProducer,
                                      vCQMSDate,
                                      vCQMEDate
                                     ) loop
    --
    -- add to the XML variable
    --
    vStep := 174;

    vXMLSNOMEDVisitTemp := (vXMLSNOMEDVisitTemp || pSNOMEDVisits."XMLSNOMEDVisit");

  end loop pSNOMEDVisits;

  --
  -- add the SNOMED visits XML
  --
  vStep := 176;

  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxXMLSNOMEDVisitTempxxx', vXMLSNOMEDVisitTemp);

  --
  -- compose the medication orders part of the XML
  --
  vStep := 180;

  for pMedicationOrders in cMedicationOrders (
                                              pPatient,
                                              vCQMSDate,
                                              vCQMEDate
                                             ) loop
    --
    -- add to the XML variable
    --
    vStep := 190;

    vXMLMedicationOrderTemp := (vXMLMedicationOrderTemp || pMedicationOrders."XMLMedicationOrder");

  end loop pMedicationOrders;

  --
  -- add the medication orders XML
  --
  vStep := 200;

  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxXMLMedicationOrderTempxxx', vXMLMedicationOrderTemp);

  --
  -- compose the procedures part of the XML
  --
  vStep := 210;

  for pProcedures in cProcedures (
                                  pPatient,
                                  vCQMSDate,
                                  vCQMEDate
                                 ) loop
    --
    -- add to the XML variable
    --
    vStep := 220;

    vXMLProcedureTemp := (vXMLProcedureTemp || pProcedures."XMLProcedure");

  end loop pProcedures;

  --
  -- add the procedures to the XML
  --
  vStep := 230;

  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxXMLProcedureTempxxx', vXMLProcedureTemp);

  --
  -- compose the CQM147 procedures part of the XML
  --
  vStep := 232;

  for pProceduresCQM147 in cProceduresCQM147 (
                                              pPatient,
                                              vCQMSDate,
                                              vCQMEDate,
                                              vCQMSDate2,
                                              vCQMEDate2,
                                              vCQMSDate3,
                                              vCQMEDate3
                                             ) loop
    --
    -- add to the XML variable
    --
    vStep := 234;

    vXMLProcedureCQM147Temp := (vXMLProcedureCQM147Temp || pProceduresCQM147."XMLProcedureCQM147");

  end loop pProceduresCQM147;

  --
  -- add the CQM147 procedures to the XML
  --
  vStep := 236;

  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxXMLProcedureCQM147Tempxxx', vXMLProcedureCQM147Temp);

  --
  -- compose the medical problems part of the XML
  --
  vStep := 240;

  for pMedicalProblems in cMedicalProblems (
                                            pPatient,
                                            pProducer,
                                            vUser,
                                            vCQMSDate,
                                            vCQMEDate,
                                            vCQMSDate2,
                                            vCQMEDate2,
                                            vCQMSDate3,
                                            vCQMEDate3
                                           ) loop
    --
    -- add to the XML variable
    --
    vStep := 250;

    vXMLDiagnosisTemp := (vXMLDiagnosisTemp || pMedicalProblems."XMLDiagnosis");

  end loop pMedicalProblems;

  --
  -- add the medical problems to the XML
  --
  vStep := 260;

  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxXMLDiagnosisTempxxx', vXMLDiagnosisTemp);

  --
  -- compose the diagnostic studies part of the XML
  --
  vStep := 270;

  for pDiagnosticStudies in cDiagnosticStudies (
                                                pPatient,
                                                vCQMSDate,
                                                vCQMEDate
                                               ) loop
    --
    -- add to the XML variable
    --
    vStep := 280;

    vXMLDiagnosticStudyTemp := (vXMLDiagnosticStudyTemp || pDiagnosticStudies."XMLDiagnosticStudy");

  end loop pDiagnosticStudies;

  --
  -- add the  diagnostic studies to the XML
  --
  vStep := 290;

  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxXMLDiagnosticStudyTempxxx', vXMLDiagnosticStudyTemp);

  --
  -- compose the laboratory tests part of the XML
  --
  vStep := 300;

  for pLaboratoryTests in cLaboratoryTests (
                                            pPatient,
                                            vCQMSDate,
                                            vCQMEDate
                                           ) loop
    --
    -- add to the XML variable
    --
    vStep := 310;

    vXMLLaboratoryTestTemp := (vXMLLaboratoryTestTemp || pLaboratoryTests."XMLLaboratoryTest");

  end loop pLaboratoryTests;

  --
  -- add the laboratory tests  to the XML
  --
  vStep := 320;

  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxXMLLaboratoryTestTempxxx', vXMLLaboratoryTestTemp);

  --
  -- compose the communications part of the XML
  --
  vStep := 330;

  for pCommunications in cCommunications (
                                          pPatient,
                                          vCQMSDate3,
                                          vCQMEDate3
                                         ) loop
    --
    -- add to the XML variable
    --
    vStep := 340;

    vXMLCommunicationTemp := (vXMLCommunicationTemp || pCommunications."XMLCommunication");

  end loop pCommunications;

  --
  -- add the communications to the XML
  --
  vStep := 350;

  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxXMLCommunicationTempxxx', vXMLCommunicationTemp);

  --
  -- compose the physical exams part of the XML
  --
  vStep := 360;

  for pPhysicalExams in cPhysicalExams (
                                        pPatient,
                                        vCQMSDate,
                                        vCQMEDate
                                       ) loop
    --
    -- add to the XML variable
    --
    vStep := 370;

    vXMLPhysicalExamTemp := (vXMLPhysicalExamTemp || pPhysicalExams."XMLPhysicalExam");

  end loop pPhysicalExams;

  --
  -- add the physical exams to the XML
  --
  vStep := 380;

  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxXMLPhysicalExamTempxxx', vXMLPhysicalExamTemp);

  --
  -- compose the immunizations part of the XML
  --
  vStep := 390;

  for pImmunizations in cImmunizations (
                                        pPatient,
                                        vCQMSDate,
                                        vCQMEDate
                                       ) loop
    --
    -- add to the XML variable
    --
    vStep := 400;

    vXMLImmunizationTemp := (vXMLImmunizationTemp || pImmunizations."XMLImmunization");

  end loop pImmunizations;

  --
  -- add the immunizations to the XML
  --
  vStep := 410;

  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxXMLImmunizationTempxxx', vXMLImmunizationTemp);

  --
  -- compose the intervention ordered part of the XML
  --
  vStep := 420;

  for pOrderedInterventions in cOrderedInterventions (
                                                      pPatient,
                                                      vCQMEDate
                                                     ) loop
    --
    -- add to the XML variable
    --
    vStep := 430;

    vXMLInterventionOrderedTemp := (vXMLInterventionOrderedTemp || pOrderedInterventions."XMLInterventionOrdered");

  end loop pOrderedInterventions;

  --
  -- add the intervention ordered to the XML
  --
  vStep := 440;

  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxXMLInterventionOrderedTempxxx', vXMLInterventionOrderedTemp);

  --
  -- clear the variable for ordered intervention
  --
  vStep := 442;

  vXMLInterventionOrderedTemp := '';

  --
  -- compose the intervention ordered part of the XML
  --
  vStep := 442;

  for pOrderedInterventionsCQM22 in cOrderedInterventionsCQM22 (
                                                                pPatient,
                                                                vCQMSDate,
                                                                vCQMEDate
                                                               ) loop
    --
    -- add to the XML variable
    --
    vStep := 444;

    vXMLInterventionOrderedTemp := (vXMLInterventionOrderedTemp || pOrderedInterventionsCQM22."XMLInterventionOrdered");

  end loop pOrderedInterventionsCQM22;

  --
  -- add the intervention ordered to the XML
  --
  vStep := 446;

  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxXMLInterventionOrderedCQM22Tempxxx', vXMLInterventionOrderedTemp);

  --
  -- compose the intervention performed part of the XML
  --
  vStep := 450;

  for pPerformedInterventions in cPerformedInterventions (
                                                          pPatient,
                                                          vCQMEDate
                                                         ) loop
    --
    -- add to the XML variable
    --
    vStep := 460;

    vXMLInterventionPerformedTemp := (vXMLInterventionPerformedTemp || pPerformedInterventions."XMLInterventionPerformed");

  end loop pPerformedInterventions;

  --
  -- add the intervention performed to the XML
  --
  vStep := 470;

  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxXMLInterventionPerformedTempxxx', vXMLInterventionPerformedTemp);

  --
  -- create final XML
  --
  vStep := 480;

  pOutputFile := vXMLHeaderTemplate;
  pError := 0;

exception
  when no_data_found then
    --
    -- return a null output file and return an error
    --
    vStep := 490;

    pOutputFile := '';
    pError := 1;

  when others then
    --
    -- return a null outputfile and return an error
    --

    vStep := 500;

    pOutputFile := '';
    pError := 2;

end QRDA_Type1_Stage3_XML_P;

PROCEDURE qrda_type3_stage3_xml_p(IN pproducer character, IN pyear numeric, IN piscqm22 integer, IN piscqm68 integer, IN piscqm74 integer, IN piscqm75 integer, IN piscqm127 integer, IN piscqm138 integer, IN piscqm147 integer, IN piscqm156 integer, INOUT perror integer, INOUT poutputfile clob) IS

  cursor cCQMList (pUser_2 mryear."User"%type,
                   pYear_2 mryear."Year"%type,
                   pIsCQM22_2 INTEGER,
                   pIsCQM68_2 INTEGER,
                   pIsCQM74_2 INTEGER,
                   pIsCQM75_2 INTEGER,
                   pIsCQM127_2 INTEGER,
                   pIsCQM138_2 INTEGER,
                   pIsCQM147_2 INTEGER,
                   pIsCQM156_2 INTEGER) is
    select cqm.*
    from (
          select
            22 CQM,
            1 "Order",
            my."User",
            my."DateFrom",
            my."DateTo",
            mu_cqm_pkg.CQM22_IPP (my."User", my."DateFrom", my."DateTo") "InitialPatientPopulation",
            mu_cqm_pkg.CQM22_N (my."User", my."DateFrom", my."DateTo") "Numerator",
            mu_cqm_pkg.CQM22_D (my."User", my."DateFrom", my."DateTo") "Denominator",
            mu_cqm_pkg.CQM22_EX (my."User", my."DateFrom", my."DateTo") "Exclusion",
            mu_cqm_pkg.CQM22_EXC (my."User", my."DateFrom", my."DateTo") "Exception",
            '40280382-610B-E7A4-0161-9A3A392C37D5' "IdExtension",
            'Preventive Care and Screening: Screening for High Blood Pressure and Follow-Up Documented' "MeasureTitle",
            '9A033A94-3D9B-11E1-8634-00237D5BF174' "SetIdRoot",
            ' and CMS 22' "ReportTitle"
          from mryear my
          where 1 = pIsCQM22
          and my."Year" = pYear_2
          and my."User" = pUser_2
          union all
          select
            68 CQM,
            1 "Order",
            my."User",
            my."DateFrom",
            my."DateTo",
            mu_cqm_pkg.CQM68_IPP (my."User", my."DateFrom", my."DateTo") "InitialPatientPopulation",
            mu_cqm_pkg.CQM68_N (my."User", my."DateFrom", my."DateTo") "Numerator",
            (mu_cqm_pkg.CQM68_D (my."User", my."DateFrom", my."DateTo") + mu_cqm_pkg.CQM68_EXC (my."User", my."DateFrom", my."DateTo")) "Denominator",
            0 "Exclusion",
            mu_cqm_pkg.CQM68_EXC (my."User", my."DateFrom", my."DateTo") "Exception",
            '40280382-5FA6-FE85-0160-0EA3E0012376' "IdExtension",
            'Documentation of Current Medications in the Medical Record' "MeasureTitle",
            '9A032D9C-3D9B-11E1-8634-00237D5BF174' "SetIdRoot",
            ' and CMS 68' "ReportTitle"
          from mryear my
          where 1 = pIsCQM68
          and my."Year" = pYear_2
          and my."User" = pUser_2
          union all
          select
            74 CQM,
            1 "Order",
            my."User",
            my."DateFrom",
            my."DateTo",
            mu_cqm_pkg.CQM74A_IPP (my."User", my."DateFrom", my."DateTo") "InitialPatientPopulation",
            mu_cqm_pkg.CQM74A_N (my."User", my."DateFrom", my."DateTo") "Numerator",
            (mu_cqm_pkg.CQM74A_D (my."User", my."DateFrom", my."DateTo") + mu_cqm_pkg.CQM74A_EX (my."User", my."DateFrom", my."DateTo"))"Denominator",
            mu_cqm_pkg.CQM74A_EX (my."User", my."DateFrom", my."DateTo") "Exclusion",
            0 "Exception",
            '40280382-6258-7581-0162-92FEA60316EE' "IdExtension",
            'Primary Caries Prevention Intervention as Offered by Primary Care Providers, including Dentists' "MeasureTitle",
            '0B81B6BA-3B30-41BF-A2F3-95BDC9F558F2' "SetIdRoot",
            ' and CMS 74' "ReportTitle"
          from mryear my
          where 1 = pIsCQM74
          and my."Year" = pYear_2
          and my."User" = pUser_2
          union all
          select
            75 CQM,
            1 "Order",
            my."User",
            my."DateFrom",
            my."DateTo",
            mu_cqm_pkg.CQM75_IPP (my."User", my."DateFrom", my."DateTo") "InitialPatientPopulation",
            mu_cqm_pkg.CQM75_N (my."User", my."DateFrom", my."DateTo") "Numerator",
            (mu_cqm_pkg.CQM75_D (my."User", my."DateFrom", my."DateTo") + mu_cqm_pkg.CQM75_EX (my."User", my."DateFrom", my."DateTo")) "Denominator",
            mu_cqm_pkg.CQM75_EX (my."User", my."DateFrom", my."DateTo") "Exclusion",
            0 "Exception",
            '40280382-6258-7581-0162-930923861702' "IdExtension",
            'Children Who Have Dental Decay or Cavities' "MeasureTitle",
            '61947125-4376-4A7B-AB7A-AC2BE9BD9138' "SetIdRoot",
            ' and CMS 75' "ReportTitle"
          from mryear my
          where 1 = pIsCQM75
          and my."Year" = pYear_2
          and my."User" = pUser_2
          union all
          select
            127 CQM,
            1 "Order",
            my."User",
            my."DateFrom",
            my."DateTo",
            mu_cqm_pkg.CQM127_IPP (my."User", my."DateFrom", my."DateTo") "InitialPatientPopulation",
            mu_cqm_pkg.CQM127_N (my."User", my."DateFrom", my."DateTo") "Numerator",
            (mu_cqm_pkg.CQM127_D (my."User", my."DateFrom", my."DateTo") + mu_cqm_pkg.CQM127_EX (my."User", my."DateFrom", my."DateTo")) "Denominator",
            mu_cqm_pkg.CQM127_EX (my."User", my."DateFrom", my."DateTo") "Exclusion",
            0 "Exception",
            '40280382-6258-7581-0162-92877E281530' "IdExtension",
            'Pneumococcal Vaccination Status for Older Adults' "MeasureTitle",
            '59657B9B-01BF-4979-A090-8534DA1D0516' "SetIdRoot",
            ' and CMS 127' "ReportTitle"
          from mryear my
          where 1 = pIsCQM127
          and my."Year" = pYear_2
          and my."User" = pUser_2
          union all
          select
            138 CQM,
            1 "Order",
            my."User",
            my."DateFrom",
            my."DateTo",
            mu_cqm_pkg.CQM138_IPP1 (my."User", my."DateFrom", my."DateTo") "InitialPatientPopulation",
            mu_cqm_pkg.CQM138_N1 (my."User", my."DateFrom", my."DateTo") "Numerator",
            (mu_cqm_pkg.CQM138_D1 (my."User", my."DateFrom", my."DateTo") + mu_cqm_pkg.CQM138_EXC1 (my."User", my."DateFrom", my."DateTo")) "Denominator",
            0 "Exclusion",
            mu_cqm_pkg.CQM138_EXC1 (my."User", my."DateFrom", my."DateTo") "Exception",
            '40280382-6240-B6B9-0162-54815A310C2C' "IdExtension",
            'Preventive Care and Screening: Tobacco Use: Screening and Cessation Intervention' "MeasureTitle",
            'E35791DF-5B25-41BB-B260-673337BC44A8' "SetIdRoot",
            ' and CMS 138' "ReportTitle"
          from mryear my
          where 1 = pIsCQM138
          and my."Year" = pYear_2
          and my."User" = pUser_2
          union all
          select
            138 CQM,
            2 "Order",
            my."User",
            my."DateFrom",
            my."DateTo",
            mu_cqm_pkg.CQM138_IPP2 (my."User", my."DateFrom", my."DateTo") "InitialPatientPopulation",
            mu_cqm_pkg.CQM138_N2 (my."User", my."DateFrom", my."DateTo") "Numerator",
            (mu_cqm_pkg.CQM138_D2 (my."User", my."DateFrom", my."DateTo") + mu_cqm_pkg.CQM138_EXC2 (my."User", my."DateFrom", my."DateTo")) "Denominator",
            0 "Exclusion",
            mu_cqm_pkg.CQM138_EXC2 (my."User", my."DateFrom", my."DateTo") "Exception",
            '40280382-6240-B6B9-0162-54815A310C2C' "IdExtension",
            'Preventive Care and Screening: Tobacco Use: Screening and Cessation Intervention' "MeasureTitle",
            'E35791DF-5B25-41BB-B260-673337BC44A8' "SetIdRoot",
            '' "ReportTitle"
          from mryear my
          where 1 = pIsCQM138
          and my."Year" = pYear_2
          and my."User" = pUser_2
          union all
          select
            138 CQM,
            3 "Order",
            my."User",
            my."DateFrom",
            my."DateTo",
            mu_cqm_pkg.CQM138_IPP3 (my."User", my."DateFrom", my."DateTo") "InitialPatientPopulation",
            mu_cqm_pkg.CQM138_N3 (my."User", my."DateFrom", my."DateTo") "Numerator",
            (mu_cqm_pkg.CQM138_D3 (my."User", my."DateFrom", my."DateTo") + mu_cqm_pkg.CQM138_EXC3 (my."User", my."DateFrom", my."DateTo")) "Denominator",
            0 "Exclusion",
            mu_cqm_pkg.CQM138_EXC3 (my."User", my."DateFrom", my."DateTo") "Exception",
            '40280382-6240-B6B9-0162-54815A310C2C' "IdExtension",
            'Preventive Care and Screening: Tobacco Use: Screening and Cessation Intervention' "MeasureTitle",
            'E35791DF-5B25-41BB-B260-673337BC44A8' "SetIdRoot",
            '' "ReportTitle"
          from mryear my
          where 1 = pIsCQM138
          and my."Year" = pYear_2
          and my."User" = pUser_2
          union all
          select
            147 CQM,
            1 "Order",
            my."User",
            my."DateFrom",
            my."DateTo",
            mu_cqm_pkg.CQM147_IPP (my."User", my."DateFrom", my."DateTo") "InitialPatientPopulation",
            mu_cqm_pkg.CQM147_N (my."User", my."DateFrom", my."DateTo") "Numerator",
            mu_cqm_pkg.CQM147_D (my."User", my."DateFrom", my."DateTo") "Denominator",
            0 "Exclusion",
            mu_cqm_pkg.CQM147_EXC (my."User", my."DateFrom", my."DateTo") "Exception",
            '40280382-6240-B6B9-0162-5096917708E0' "IdExtension",
            'Preventive Care and Screening: Influenza Immunization' "MeasureTitle",
            'A244AA29-7D11-4616-888A-86E376BFCC6F' "SetIdRoot",
            ' and CMS 147' "ReportTitle"
          from mryear my
          where 1 = pIsCQM147
          and my."Year" = pYear_2
          and my."User" = pUser_2
          union all
          select
            156 CQM,
            1 "Order",
            my."User",
            my."DateFrom",
            my."DateTo",
            mu_cqm_pkg.CQM156A_IPP (my."User", my."DateFrom", my."DateTo") "InitialPatientPopulation",
            mu_cqm_pkg.CQM156A_N (my."User", my."DateFrom", my."DateTo") "Numerator",
            (mu_cqm_pkg.CQM156A_D (my."User", my."DateFrom", my."DateTo") +  mu_cqm_pkg.CQM156A_EX (my."User", my."DateFrom", my."DateTo")) "Denominator",
            mu_cqm_pkg.CQM156A_EX (my."User", my."DateFrom", my."DateTo") "Exclusion",
            0 "Exception",
            '40280382-6258-7581-0162-92C7A9811647' "IdExtension",
            'Use of High-Risk Medications in the Elderly' "MeasureTitle",
            'A3837FF8-1ABC-4BA9-800E-FD4E7953ADBD' "SetIdRoot",
            ' and CMS 156' "ReportTitle"
          from mryear my
          where 1 = pIsCQM156
          and my."Year" = pYear_2
          and my."User" = pUser_2
/*
          union all
          select
            156 CQM,
            2 "Order",
            my."User",
            my."DateFrom",
            my."DateTo",
            mu_cqm_pkg.CQM156B_IPP (my."User", my."DateFrom", my."DateTo") "InitialPatientPopulation",
            mu_cqm_pkg.CQM156B_N (my."User", my."DateFrom", my."DateTo") "Numerator",
            (mu_cqm_pkg.CQM156B_D (my."User", my."DateFrom", my."DateTo") + mu_cqm_pkg.CQM156B_EX (my."User", my."DateFrom", my."DateTo")) "Denominator",
            mu_cqm_pkg.CQM156B_EX (my."User", my."DateFrom", my."DateTo") "Exclusion",
            0 "Exception",
            '40280382-6258-7581-0162-92C7A9811647' "IdExtension",
            'Use of High-Risk Medications in the Elderly' "MeasureTitle",
            'A3837FF8-1ABC-4BA9-800E-FD4E7953ADBD' "SetIdRoot",
            '' "ReportTitle"
          from mryear my
          where 1 = pIsCQM156
          and my."Year" = pYear_2
          and my."User" = pUser_2
*/
         ) cqm
    where 1=1
    order by
      cqm.CQM,
      cqm."Order";

  cursor cCQMMeasures (pCQM INTEGER,
                       pOrder INTEGER) is
    select cqmm.*
    from (
          -- CQM22
          select 22 CQM, 1 "Order", 1 "Order2", 'IPOP' "MeasureCode", 'D019FA53-2049-43D9-B006-E4AB7DA01878' "IdRoot" from dual union all
          select 22 CQM, 1 "Order", 2 "Order2", 'DENOM' "MeasureCode", '75FDA064-6A0C-463E-84B2-B307A1F8959F' "IdRoot"from dual union all
          select 22 CQM, 1 "Order", 3 "Order2", 'DENEX' "MeasureCode", '72097A3E-8090-486C-ABCD-9419C9A04291' "IdRoot"from dual union all
          select 22 CQM, 1 "Order", 4 "Order2", 'NUMER' "MeasureCode", '54790C8F-7C20-4261-B895-39E915B73F42' "IdRoot"from dual union all
          select 22 CQM, 1 "Order", 5 "Order2", 'DENEXCEP' "MeasureCode", '0EA1313C-BCF6-4526-9AD6-365E8A400805' "IdRoot"from dual union all
          -- CQM68
          select 68 CQM, 1 "Order", 1 "Order2", 'IPOP' "MeasureCode", '2C662755-088C-4C75-8401-FF2DA63A971E' "IdRoot" from dual union all
          select 68 CQM, 1 "Order", 2 "Order2", 'DENOM' "MeasureCode", 'D4D2DEE7-385A-4C28-A09C-884A062A97AA' "IdRoot"from dual union all
          select 68 CQM, 1 "Order", 3 "Order2", 'NUMER' "MeasureCode", '4E058941-CA3D-48BF-BABC-358F3A9FE2AF' "IdRoot"from dual union all
          select 68 CQM, 1 "Order", 4 "Order2", 'DENEXCEP' "MeasureCode", '146E4DDD-4E52-492D-B150-61DF3BE52676' "IdRoot"from dual union all
          -- CQM74
          select 74 CQM, 1 "Order", 1 "Order2", 'IPOP' "MeasureCode", '4DAE1F06-ACAC-4FE8-B2DB-6819D5106076' "IdRoot" from dual union all
          select 74 CQM, 1 "Order", 2 "Order2", 'DENOM' "MeasureCode", '8A1CEA1D-8C98-441A-BB1B-2844586B5E82' "IdRoot"from dual union all
          select 74 CQM, 1 "Order", 3 "Order2", 'DENEX' "MeasureCode", '072B2944-36FE-4557-B332-EB91FE97421A' "IdRoot"from dual union all
          select 74 CQM, 1 "Order", 4 "Order2", 'NUMER' "MeasureCode", 'A89FFB85-F438-466C-AB5F-7EB31310285B' "IdRoot"from dual union all
          -- CQM75
          select 75 CQM, 1 "Order", 1 "Order2", 'IPOP' "MeasureCode", 'E3EAD500-A4F2-45C2-A370-B5C191DC7825' "IdRoot" from dual union all
          select 75 CQM, 1 "Order", 2 "Order2", 'DENOM' "MeasureCode", '466991C9-1413-4FDA-9DE5-B1B0A262271B' "IdRoot"from dual union all
          select 75 CQM, 1 "Order", 3 "Order2", 'DENEX' "MeasureCode", '7CAC738B-EEBA-4683-88C6-CF344BF47A87' "IdRoot"from dual union all
          select 75 CQM, 1 "Order", 4 "Order2", 'NUMER' "MeasureCode", '007F6693-32AC-43C3-B97D-6DBCA05F9F3E' "IdRoot"from dual union all
          -- CQM127
          select 127 CQM, 1 "Order", 1 "Order2", 'IPOP' "MeasureCode", 'AD7E66D5-D06C-4079-8086-8B2978CA1AEF' "IdRoot" from dual union all
          select 127 CQM, 1 "Order", 2 "Order2", 'DENOM' "MeasureCode", 'FC166E13-A380-466E-8E38-2E86261ADB21' "IdRoot"from dual union all
          select 127 CQM, 1 "Order", 3 "Order2", 'DENEX' "MeasureCode", 'A791271E-6A92-406C-B67B-C6F6175F3FE7' "IdRoot"from dual union all
          select 127 CQM, 1 "Order", 4 "Order2", 'NUMER' "MeasureCode", 'BE0E99DE-0998-4E13-AEE7-8012513CF47E' "IdRoot"from dual union all
          -- CQM138
          select 138 CQM, 1 "Order", 1 "Order2", 'IPOP' "MeasureCode", 'D03DA272-DBB3-4F46-B19B-CF3262A23C2E' "IdRoot" from dual union all
          select 138 CQM, 1 "Order", 2 "Order2", 'DENOM' "MeasureCode", '0F1384E0-350D-43B9-8C17-1140837F342E' "IdRoot"from dual union all
          select 138 CQM, 1 "Order", 3 "Order2", 'NUMER' "MeasureCode", '1356052C-4C82-4859-85B4-D04ACF269564' "IdRoot"from dual union all
          select 138 CQM, 1 "Order", 4 "Order2", 'DENEXCEP' "MeasureCode", 'A8DBEC91-05EF-4897-80E4-39400B23F030' "IdRoot"from dual union all
          -- CQM138
          select 138 CQM, 2 "Order", 5 "Order2", 'IPOP' "MeasureCode", 'C4D32BC0-8DBE-4766-BF47-7718D1569C79' "IdRoot" from dual union all
          select 138 CQM, 2 "Order", 6 "Order2", 'DENOM' "MeasureCode", 'C1195308-7F73-409B-A4FF-8F17A4AA772E' "IdRoot"from dual union all
          select 138 CQM, 2 "Order", 7 "Order2", 'NUMER' "MeasureCode", 'D10D6789-32F2-4A72-9588-611C4765FC13' "IdRoot"from dual union all
          select 138 CQM, 2 "Order", 8 "Order2", 'DENEXCEP' "MeasureCode", '29CD08BD-BFA6-4208-80C6-24DD96862EB4' "IdRoot"from dual union all
          -- CQM138
          select 138 CQM, 3 "Order", 9 "Order2", 'IPOP' "MeasureCode", '1D17B8A9-4DBF-448A-BB7F-879223A0A825' "IdRoot" from dual union all
          select 138 CQM, 3 "Order", 10 "Order2", 'DENOM' "MeasureCode", 'C33FDC75-14E2-4A57-A18E-130D26411C92' "IdRoot"from dual union all
          select 138 CQM, 3 "Order", 11 "Order2", 'NUMER' "MeasureCode", '98958164-44A0-4759-AF5C-86EFB56AF1BA' "IdRoot"from dual union all
          select 138 CQM, 3 "Order", 12 "Order2", 'DENEXCEP' "MeasureCode", 'EA9FE5F4-3057-495E-B5E5-83554CE39944' "IdRoot"from dual union all
          -- CQM147
          select 147 CQM, 1 "Order", 1 "Order2", 'IPOP' "MeasureCode", '4034509E-A7C9-4067-AEC6-B356CA0DD2F5' "IdRoot" from dual union all
          select 147 CQM, 1 "Order", 2 "Order2", 'DENOM' "MeasureCode", '4AE15148-711D-4785-8433-4385D9D257DC' "IdRoot"from dual union all
          select 147 CQM, 1 "Order", 3 "Order2", 'NUMER' "MeasureCode", 'CAD38C39-7093-4BA4-B8BD-5A297079F1CF' "IdRoot"from dual union all
          select 147 CQM, 1 "Order", 4 "Order2", 'DENEXCEP' "MeasureCode", 'F9FF5A51-8FBE-4DAC-92CD-17F295496456' "IdRoot"from dual union all
          -- CQM156
          select 156 CQM, 1 "Order", 1 "Order2", 'IPOP' "MeasureCode", '35872DE4-ADC6-4D3D-B439-B3248FEF3456' "IdRoot" from dual union all
          select 156 CQM, 1 "Order", 2 "Order2", 'DENOM' "MeasureCode", '2FCB1E4B-CA28-4F1E-827D-2F5E378FF222' "IdRoot"from dual union all
          select 156 CQM, 1 "Order", 3 "Order2", 'DENEX' "MeasureCode", 'BD7DEC25-34DE-4E75-843E-50720AD7FF8C' "IdRoot"from dual union all
          select 156 CQM, 1 "Order", 4 "Order2", 'NUMER' "MeasureCode", 'A5797141-A910-4FA0-8A5F-32FB348848A0' "IdRoot"from dual union all
          -- CQM156
          select 156 CQM, 2 "Order", 5 "Order2", 'IPOP' "MeasureCode", 'FEDC857A-3B2E-49D5-89BC-366075AD6403' "IdRoot" from dual union all
          select 156 CQM, 2 "Order", 6 "Order2", 'DENOM' "MeasureCode", '877B83EF-716C-4B0B-AE4C-0F9689A946A8' "IdRoot"from dual union all
          select 156 CQM, 2 "Order", 7 "Order2", 'DENEX' "MeasureCode", 'DEDFBFA0-DB7C-413B-8B22-A734590D83CE' "IdRoot"from dual union all
          select 156 CQM, 2 "Order", 8 "Order2", 'NUMER' "MeasureCode", '51CCFD8B-C7B1-492F-88DE-041AD08FDAED' "IdRoot"from dual
         ) cqmm
    where 1=1
--    and cqmm."Order" = pOrder
    and cqmm.CQM = pCQM
    order by
      cqmm."Order",
      cqmm."Order2";

  cursor cCQMStrata (pCQM_3 INTEGER,
                     pUser_3 mryear."User"%type,
                     pDateFrom_3 mryear."DateFrom"%type,
                     pDateTo_3 mryear."DateTo"%type) is
    --
    -- only CQM74 has stratification for now
    --
    select cqms.*
    from (
          select
            74 CQM,
            1 "Order",
            '69C80D2F-2C9D-40CB-B75A-2B29B8C37786' "StratumIdRoot",
            mu_cqm_pkg.CQM74B_IPP (pUser_3, pDateFrom_3, pDateTo_3) "InitialPatientPopulation",
            mu_cqm_pkg.CQM74B_N (pUser_3, pDateFrom_3, pDateTo_3) "Numerator",
--            mu_cqm_pkg.CQM74B_D (pUser_3, pDateFrom_3, pDateTo_3) "Denominator",
            (mu_cqm_pkg.CQM74B_D (pUser_3, pDateFrom_3, pDateTo_3) + mu_cqm_pkg.CQM74B_EX (pUser_3, pDateFrom_3, pDateTo_3))"Denominator",
            mu_cqm_pkg.CQM74B_EX (pUser_3, pDateFrom_3, pDateTo_3) "Exclusion",
            0 "Exception",
            'Ages 0-5 years' "OriginalText"
          from dual
          where 74 = pCQM_3
          union all
          select
            74 CQM,
            2 "Order",
            '087992AE-837D-43B9-88C5-EB55BA2E810B' "StratumIdRoot",
            mu_cqm_pkg.CQM74C_IPP (pUser_3, pDateFrom_3, pDateTo_3) "InitialPatientPopulation",
            mu_cqm_pkg.CQM74C_N (pUser_3, pDateFrom_3, pDateTo_3) "Numerator",
--            mu_cqm_pkg.CQM74C_D (pUser_3, pDateFrom_3, pDateTo_3) "Denominator",
            (mu_cqm_pkg.CQM74C_D (pUser_3, pDateFrom_3, pDateTo_3) + mu_cqm_pkg.CQM74C_EX (pUser_3, pDateFrom_3, pDateTo_3))"Denominator",
            mu_cqm_pkg.CQM74C_EX (pUser_3, pDateFrom_3, pDateTo_3) "Exclusion",
            0 "Exception",
            'Ages 6-12 years' "OriginalText"
          from dual
          where 74 = pCQM_3
          union all
          select
            74 CQM,
            3 "Order",
            'F4FC32F4-C178-477D-9250-CB60081D5222' "StratumIdRoot",
            mu_cqm_pkg.CQM74D_IPP (pUser_3, pDateFrom_3, pDateTo_3) "InitialPatientPopulation",
            mu_cqm_pkg.CQM74D_N (pUser_3, pDateFrom_3, pDateTo_3) "Numerator",
--            mu_cqm_pkg.CQM74D_D (pUser_3, pDateFrom_3, pDateTo_3) "Denominator",
            (mu_cqm_pkg.CQM74D_D (pUser_3, pDateFrom_3, pDateTo_3) + mu_cqm_pkg.CQM74D_EX (pUser_3, pDateFrom_3, pDateTo_3)) "Denominator",
            mu_cqm_pkg.CQM74D_EX (pUser_3, pDateFrom_3, pDateTo_3) "Exclusion",
            0 "Exception",
            'Ages 13-20 years' "OriginalText"
          from dual
          where 74 = pCQM_3
         ) cqms
    where 1=1
    and cqms.CQM = pCQM_3
    order by cqms."Order";

  cursor cSupplementalData (pCQM INTEGER,
                            pOrder INTEGER,
                            pMeasureCode varchar2) is
    select *
    from (
          -- CQM22
          select 22 CQM, 1 "Order", 'IPOP' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM22_IPP_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 22 CQM, 1 "Order", 'DENOM' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM22_D_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 22 CQM, 1 "Order", 'DENEX' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM22_EX_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 22 CQM, 1 "Order", 'NUMER' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM22_N_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 22 CQM, 1 "Order", 'DENEXCEP' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM22_EXC_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          -- CQM68
          select 68 CQM, 1 "Order", 'IPOP' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM68_IPP_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 68 CQM, 1 "Order", 'DENOM' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM68_D_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 68 CQM, 1 "Order", 'NUMER' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM68_N_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 68 CQM, 1 "Order", 'DENEXCEP' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM68_EXC_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          -- CQM74
          select 74 CQM, 1 "Order", 'IPOP' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM74A_IPP_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 74 CQM, 1 "Order", 'DENOM' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM74A_D_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 74 CQM, 1 "Order", 'DENEX' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM74A_EX_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 74 CQM, 1 "Order", 'NUMER' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM74A_N_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          -- CQM75
          select 75 CQM, 1 "Order", 'IPOP' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM75_IPP_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 75 CQM, 1 "Order", 'DENOM' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM75_D_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 75 CQM, 1 "Order", 'DENEX' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM75_EX_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 75 CQM, 1 "Order", 'NUMER' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM75_N_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          -- CQM127
          select 127 CQM, 1 "Order", 'IPOP' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM127_IPP_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 127 CQM, 1 "Order", 'DENOM' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM127_D_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 127 CQM, 1 "Order", 'DENEX' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM127_EX_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 127 CQM, 1 "Order", 'NUMER' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM127_N_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          -- CQM138
          select 138 CQM, 1 "Order", 'IPOP' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM138_IPP1_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 138 CQM, 1 "Order", 'DENOM' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM138_D_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 138 CQM, 1 "Order", 'NUMER' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM138_N1_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 138 CQM, 1 "Order", 'DENEXCEP' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM138_EXC1_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          -- CQM138
          select 138 CQM, 2 "Order", 'IPOP' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM138_IPP2_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 138 CQM, 2 "Order", 'DENOM' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM138_D_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 138 CQM, 2 "Order", 'NUMER' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM138_N2_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 138 CQM, 2 "Order", 'DENEXCEP' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM138_EXC2_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          -- CQM138
          select 138 CQM, 3 "Order", 'IPOP' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM138_IPP3_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 138 CQM, 3 "Order", 'DENOM' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM138_D_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 138 CQM, 3 "Order", 'NUMER' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM138_N3_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 138 CQM, 3 "Order", 'DENEXCEP' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM138_EXC3_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          -- CQM147
          select 147 CQM, 1 "Order", 'IPOP' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM147_IPP_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 147 CQM, 1 "Order", 'DENOM' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM147_D_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 147 CQM, 1 "Order", 'NUMER' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM147_N_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 147 CQM, 1 "Order", 'DENEXCEP' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM147_EXC_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          -- CQM156
          select 156 CQM, 1 "Order", 'IPOP' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM156A_IPP_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 156 CQM, 1 "Order", 'DENOM' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM156A_D_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 156 CQM, 1 "Order", 'DENEX' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM156A_EX_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 156 CQM, 1 "Order", 'NUMER' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM156A_N_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          -- CQM156
          select 156 CQM, 2 "Order", 'IPOP' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM156B_IPP_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 156 CQM, 2 "Order", 'DENOM' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM156B_D_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 156 CQM, 2 "Order", 'DENEX' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM156B_EX_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual union all
          select 156 CQM, 2 "Order", 'NUMER' "MeasureCode", 'begin mu_cqm_qrda_pkg.CQM156B_N_P (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19); end;' "Procedure" from dual
         )
    where 1=1
    and "MeasureCode" = pMeasureCode
    and "Order" = pOrder
    and CQM = pCQM;

  cursor cSupplementalDataDetails (pMeasureCode varchar2,
                                   pGenderM INTEGER,
                                   pGenderF INTEGER,
                                   pGenderUNK INTEGER,
                                   pRaceNATIVE INTEGER,
                                   pRaceASIAN INTEGER,
                                   pRaceBLACK INTEGER,
                                   pRaceISLAND INTEGER,
                                   pRaceWHITE INTEGER,
                                   pRaceOTHER INTEGER,
                                   pRaceUNK INTEGER,
                                   pEthnicLATINO INTEGER,
                                   pEthnicOTHER INTEGER,
                                   pEthnicUNK INTEGER,
                                   pPayer1 INTEGER,
                                   pPayer2 INTEGER,
                                   pPayer349 INTEGER) is
    select
('
  <!--    ' || s."Supplement" || ' Supplemental Data Reporting for ' || pMeasureCode || '      -->
  <entryRelationship typeCode=COMP>
    <observation classCode=OBS moodCode=EVN>
      <!-- ' || initcap(s."Supplement") || ' Supplemental Data -->
        <templateId root="' || s."TemplateIdRoot" || '" extension="' || s."TemplateIdExtension" || '"/>
        <id nullFlavor=NA />
      <code code="' || s."CodeCode" || '"
            codeSystem="2.16.840.1.113883.6.1"/>
      <statusCode code=completed/>

      <value xsi:type=CD
             code="' || s."ValueCode" || '"
             codeSystem="' || s."ValueCodeSystem" || '"/>
      <entryRelationship typeCode=SUBJ inversionInd="true">
        <!-- Aggregate Count template -->
        <observation classCode=OBS moodCode=EVN>
          <templateId root="2.16.840.1.113883.10.20.27.3.3"/>
          <code code=MSRAGG
                displayName="rate aggregation"
                codeSystem="2.16.840.1.113883.5.4"
                codeSystemName="ActCode"/>
          <value xsi:type="int" value="' || s."ValueValue" || '"/>
          <methodCode code=COUNT
                      displayName="Count"
                      codeSystem="2.16.840.1.113883.5.84"
                      codeSystemName="ObservationMethod"/>
        </observation>
      </entryRelationship>
    </observation>
  </entryRelationship>
') "XMLSupplement"
    from (
          with
          TmpSupplement as (
                            select 1 "Order", 'SEX' "Supplement", '2.16.840.1.113883.10.20.27.3.6' "TemplateIdRoot", '2016-09-01' "TemplateIdExtension", '76689-9' "CodeCode", '2.16.840.1.113883.5.1' "ValueCodeSystem" from dual union all
                            select 2 "Order", 'ETHNICITY' "Supplement", '2.16.840.1.113883.10.20.27.3.7' "TemplateIdRoot", '2016-09-01' "TemplateIdExtension", '69490-1' "CodeCode", '2.16.840.1.113883.6.238' "ValueCodeSystem" from dual union all
                            select 3 "Order", 'RACE' "Supplement", '2.16.840.1.113883.10.20.27.3.8' "TemplateIdRoot", '2016-09-01' "TemplateIdExtension", '72826-1' "CodeCode", '2.16.840.1.113883.6.238' "ValueCodeSystem" from dual union all
                            select 4 "Order", 'PAYER' "Supplement", '2.16.840.1.113883.10.20.27.3.9' "TemplateIdRoot", '2016-02-01' "TemplateIdExtension", '48768-6' "CodeCode", '2.16.840.1.113883.3.221.5' "ValueCodeSystem" from dual
                           )
          -- gender
          select 1 "Order2", pGenderF "ValueValue", 'F' "ValueCode", "Order", "Supplement", "TemplateIdRoot", "TemplateIdExtension", "CodeCode", "ValueCodeSystem" from TmpSupplement where "Supplement" = 'SEX' and pGenderF > 0 union all
          select 2 "Order2", pGenderM "ValueValue", 'M' "ValueCode", "Order", "Supplement", "TemplateIdRoot", "TemplateIdExtension", "CodeCode", "ValueCodeSystem" from TmpSupplement where "Supplement" = 'SEX' and pGenderM > 0 union all
          select 3 "Order2", pGenderUNK "ValueValue", 'UNK' "ValueCode", "Order", "Supplement", "TemplateIdRoot", "TemplateIdExtension", "CodeCode", "ValueCodeSystem" from TmpSupplement where "Supplement" = 'SEX' and pGenderUNK > 0 union all
          -- ethnicity
          select 4 "Order2", pEthnicLATINO "ValueValue", '2135-2' "ValueCode", "Order", "Supplement", "TemplateIdRoot", "TemplateIdExtension", "CodeCode", "ValueCodeSystem" from TmpSupplement where "Supplement" = 'ETHNICITY' and pEthnicLATINO > 0 union all
          select 5 "Order2", pEthnicOTHER "ValueValue", '2186-5' "ValueCode", "Order", "Supplement", "TemplateIdRoot", "TemplateIdExtension", "CodeCode", "ValueCodeSystem" from TmpSupplement where "Supplement" = 'ETHNICITY' and pEthnicOTHER > 0 union all
          select 6 "Order2", pEthnicUNK "ValueValue", 'UNK' "ValueCode", "Order", "Supplement", "TemplateIdRoot", "TemplateIdExtension", "CodeCode", "ValueCodeSystem" from TmpSupplement where "Supplement" = 'ETHNICITY' and pEthnicUNK > 0 union all
          -- race
          select 7 "Order2", pRaceNATIVE "ValueValue", '1002-5' "ValueCode", "Order", "Supplement", "TemplateIdRoot", "TemplateIdExtension", "CodeCode", "ValueCodeSystem" from TmpSupplement where "Supplement" = 'RACE' and pRaceNATIVE > 0 union all
          select 8 "Order2", pRaceASIAN "ValueValue", '2028-9' "ValueCode", "Order", "Supplement", "TemplateIdRoot", "TemplateIdExtension", "CodeCode", "ValueCodeSystem" from TmpSupplement where "Supplement" = 'RACE' and pRaceASIAN > 0 union all
          select 9 "Order2", pRaceBLACK "ValueValue", '2054-5' "ValueCode", "Order", "Supplement", "TemplateIdRoot", "TemplateIdExtension", "CodeCode", "ValueCodeSystem" from TmpSupplement where "Supplement" = 'RACE' and pRaceBLACK > 0 union all
          select 10 "Order2", pRaceISLAND "ValueValue", '2076-8' "ValueCode", "Order", "Supplement", "TemplateIdRoot", "TemplateIdExtension", "CodeCode", "ValueCodeSystem" from TmpSupplement where "Supplement" = 'RACE' and pRaceISLAND > 0 union all
          select 11 "Order2", pRaceWHITE "ValueValue", '2106-3' "ValueCode", "Order", "Supplement", "TemplateIdRoot", "TemplateIdExtension", "CodeCode", "ValueCodeSystem" from TmpSupplement where "Supplement" = 'RACE' and pRaceWHITE > 0 union all
          select 12 "Order2", pRaceOTHER "ValueValue", '2131-1' "ValueCode", "Order", "Supplement", "TemplateIdRoot", "TemplateIdExtension", "CodeCode", "ValueCodeSystem" from TmpSupplement where "Supplement" = 'RACE' and pRaceOTHER > 0 union all
          select 13 "Order2", pRaceUNK "ValueValue", 'UNK' "ValueCode", "Order", "Supplement", "TemplateIdRoot", "TemplateIdExtension", "CodeCode", "ValueCodeSystem" from TmpSupplement where "Supplement" = 'RACE' and pRaceUNK > 0 union all
          -- payer
          select 14 "Order2", pPayer1 "ValueValue", '1' "ValueCode", "Order", "Supplement", "TemplateIdRoot", "TemplateIdExtension", "CodeCode", "ValueCodeSystem" from TmpSupplement where "Supplement" = 'PAYER' and pPayer1 > 0 union all
          select 15 "Order2", pPayer2 "ValueValue", '2' "ValueCode", "Order", "Supplement", "TemplateIdRoot", "TemplateIdExtension", "CodeCode", "ValueCodeSystem" from TmpSupplement where "Supplement" = 'PAYER' and pPayer2 > 0 union all
          select 16 "Order2", pPayer349 "ValueValue", '349' "ValueCode", "Order", "Supplement", "TemplateIdRoot", "TemplateIdExtension", "CodeCode", "ValueCodeSystem" from TmpSupplement where "Supplement" = 'PAYER' and pPayer349 > 0
         ) s
    where 1=1
    order by
      s."Order",
      s."Order2";

  vXMLHeaderTemplate clob :=
'<?xml version="1.0" encoding="utf-8"?>
<ClinicalDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="urn:hl7-org:v3"
 xmlns:cda="urn:hl7-org:v3">

  <!--
    ********************************************************
    CDA Header
    ********************************************************
  -->
  <realmCode code=US/>
  <typeId root="2.16.840.1.113883.1.3" extension=POCD_HD000040/>
  <!-- QRDA Category III template ID (this template ID differs from QRDA III comment only template ID). -->
  <templateId root="2.16.840.1.113883.10.20.27.1.1" extension="2017-06-01"/>
  <id root="90C1415D-B430-4BAB-BE4F-9876DAD0DF5B"/>


  <!-- SHALL QRDA III document type code -->
  <code code="55184-6" codeSystem="2.16.840.1.113883.6.1" codeSystemName=LOINC
    displayName="QRDA Category 3 Calculated Summary Report"/>
  <!-- SHALL Title, SHOULD have this content -->
  <title>xxxReportTitlexxx</title>
  <!-- SHALL  -->
  <effectiveTime value="xxxDateTimexxx"/>
  <confidentialityCode codeSystem="2.16.840.1.113883.5.25" code=N/>
  <languageCode code="en-US"/>
  <!-- SHOULD The version of the file being submitted. -->
  <versionNumber value="1"/>
  <!-- SHALL contain recordTarget and ID - but ID is nulled to NA. This is an aggregate summary report. Therefore CDA"s required patient identifier is nulled. -->
  <recordTarget>
    <patientRole>
      <id nullFlavor=NA/>
    </patientRole>
  </recordTarget>

   <!-- SHALL have 1..* author. MAY be device or person. -->
  <author>
    <time value="xxxDateTimexxx"/>
    <assignedAuthor>
      <id root="2.16.840.1.113883.4.6" extension="xxxNPIxxx" assigningAuthorityName=NPI/>
      <assignedPerson>
        <name>
          <given>xxxFirstNamexxx</given>
          <family>xxxLastNamexxx</family>
          <suffix>xxxTitlexxx</suffix>
        </name>
      </assignedPerson>
      <representedOrganization>
        <id root="2.16.840.1.113883.19.598"/>
        <name>Exan Software</name>
      </representedOrganization>
    </assignedAuthor>
  </author>
  <custodian>
    <assignedCustodian>
      <representedCustodianOrganization>
        <id root="2.16.840.1.113883.19.5"/>
          <name>Exan</name>
        </representedCustodianOrganization>
    </assignedCustodian>
  </custodian>
  <legalAuthenticator>
    <time value="xxxDateTimexxx"/>
    <signatureCode code=S/>
    <assignedEntity>
      <id root="113AAEBA-4456-49DB-B7B8-67C41472E812"/>
      <representedOrganization>
        <id root="2.16.840.1.113883.19.5"/>
        <name>Exan</name>
      </representedOrganization>
    </assignedEntity>
  </legalAuthenticator>
  <authorization>
    <consent>
      <id root="9DE871F0-A890-4D5F-856C-62808F496470"/>
      <code codeSystem="2.16.840.1.113883.6.96" code="425691002" codeSystemName="SNOMED-CT" displayName="Consent given for electronic record sharing"/>
      <statusCode code=completed/>
    </consent>
  </authorization>



  <!--
********************************************************
CDA Body
********************************************************
-->
  <component>
    <structuredBody>
      <!--
********************************************************
QRDA Category III Reporting Parameters
********************************************************
-->
      <component>
        <section>
          <templateId root="2.16.840.1.113883.10.20.17.2.1" />
          <templateId root="2.16.840.1.113883.10.20.27.2.2" />
          <code codeSystem="2.16.840.1.113883.6.1" code="55187-9" />
          <title>Reporting Parameters</title>
          <text>
            <list>
              <item>xxxReportingPeriodxxx</item>
            </list>
          </text>
          <entry typeCode=DRIV>
            <act classCode=ACT moodCode=EVN>
              <templateId root="2.16.840.1.113883.10.20.17.3.8" />
              <id root="6E892703-2700-40C7-8A6A-F6244B836A5A" />
              <code codeSystem="2.16.840.1.113883.6.96" code="252116004" displayName="Observation Parameters" />
              <effectiveTime>
                <low value="xxxCQMSDateTimexxx" />
                <high value="xxxCQMEDateTimexxx" />
              </effectiveTime>
            </act>
          </entry>
          <entry>
            <encounter classCode=ENC moodCode=EVN>
              <templateId root="2.16.840.1.113883.10.20.27.3.11" />
              <id root="BA41DD85-3C2E-4B9D-BB96-CAC4ACE1881D" />
              <effectiveTime>
                <low value="xxxCQMSDateTimexxx" />
              </effectiveTime>
            </encounter>
          </entry>
          <entry>
            <encounter classCode=ENC moodCode=EVN>
              <templateId root="2.16.840.1.113883.10.20.27.3.11" />
              <id root="9B0643C3-7339-4701-BB10-00219E86EAF6" />
              <effectiveTime>
                <high value="xxxCQMEDateTimexxx" />
              </effectiveTime>
            </encounter>
          </entry>
        </section>
      </component>
      <!--
********************************************************
Measure Section
********************************************************
-->
      <component>
        <section>
          <!-- Implied template Measure Section templateId -->
          <templateId root="2.16.840.1.113883.10.20.24.2.2"/>
          <!-- In this case the query is using an eMeasure -->
          <!-- QRDA Category III Measure Section template -->
          <templateId root="2.16.840.1.113883.10.20.27.2.1" extension="2017-06-01"/>
          <code code="55186-1" codeSystem="2.16.840.1.113883.6.1"/>
          <title>Measure Section</title>
          <text>

          </text>
';

  vXMLMeasuresFinal clob := '';
  vXMLMeasuresTemp clob := '';
  vXMLMeasuresHeaderTemp clob := '';

  vXMLMeasuresHeaderTemplate clob :=
'          <entry>
            <organizer classCode="cluster" moodCode=EVN>
              <!-- Implied template Measure Reference templateId -->
              <templateId root="2.16.840.1.113883.10.20.24.3.98"/>
              <!-- SHALL 1..* (one for each referenced measure) Measure Reference and Results template -->
              <templateId root="2.16.840.1.113883.10.20.27.3.1" extension="2016-09-01"/>
              <id extension="xxxIdExtensionxxx"/>
              <statusCode code=completed/>
              <reference typeCode=REFR>
                <externalDocument classCode=DOC moodCode=EVN>
                  <!-- SHALL: required Id but not restricted to the eMeasure Document/Id-->
                  <!-- QualityMeasureDocument/id This is the version specific identifier for eMeasure -->
                  <id root="2.16.840.1.113883.4.738" extension="xxxIdExtensionxxx"/>

                  <!-- SHOULD This is the title of the eMeasure -->
                  <text>xxxMeasureTitlexxx</text>
                  <!-- SHOULD: setId is the eMeasure version neutral id  -->
                  <setId root="xxxSetIdRootxxx"/>
                  <!-- This is the sequential eMeasure Version number -->
                  <versionNumber value="1"/>
                </externalDocument>
              </reference>
';

  vXMLMeasuresTemplate clob :=
'              <component>

<!--   MEASURE DATA REPORTING FOR xxxMeasureCodexxx  -->
<observation classCode=OBS moodCode=EVN>
  <!-- Measure Data template -->
  <templateId root="2.16.840.1.113883.10.20.27.3.5" extension="2016-09-01"/>
  <code code="assertion"
        codeSystem="2.16.840.1.113883.5.4"
        displayName="Assertion"
        codeSystemName="ActCode"/>
  <statusCode code=completed/>
  <value xsi:type=CD code="xxxMeasureCodexxx"
         codeSystem="2.16.840.1.113883.5.4"
         codeSystemName="ActCode"/>
  <!-- Aggregate Count -->
  <entryRelationship typeCode=SUBJ inversionInd="true">
    <observation classCode=OBS moodCode=EVN>
      <templateId root="2.16.840.1.113883.10.20.27.3.3"/>
      <code code=MSRAGG
        displayName="rate aggregation"
        codeSystem="2.16.840.1.113883.5.4"
        codeSystemName="ActCode"/>
      <value xsi:type="int" value="xxxMeasureCountxxx"/>
      <methodCode code=COUNT
        displayName="Count"
        codeSystem="2.16.840.1.113883.5.84"
        codeSystemName="ObservationMethod"/>
    </observation>
  </entryRelationship>
';

  vXMLMeasuresTail2 clob :=
'
  xxxXMLSupplementTempxxx

  <reference typeCode=REFR>
     <externalObservation classCode=OBS moodCode=EVN>
        <id root="xxxIdRootxxx"/>
     </externalObservation>
  </reference>
</observation>
              </component>
';

  vXMLMeasuresTail clob :=
'            </organizer>
          </entry>
';

  vXMLTailTemplate clob :=
'
          <entry>
                      <act classCode=ACT moodCode=EVN>
              <!-- This is the templateId for Reporting Parameters Act -->
              <templateId root="2.16.840.1.113883.10.20.17.3.8"/>
              <id extension=F79FD35B8E3CD0C5DE2DB8871D4A6BFE />
              <code code="252116004" codeSystem="2.16.840.1.113883.6.96" displayName="Observation Parameters"/>
              <effectiveTime>
                <low value="xxxCQMSDateTimexxx"/>
                <high value="xxxCQMEDateTimexxx"/>
              </effectiveTime>
            </act>
          </entry>
        </section>
      </component>
    </structuredBody>
  </component>
</ClinicalDocument>';

  vXMLStratumTemp clob := '';

  vXMLStratumTemplate clob :=
'
  <!--  Stratification Reporting Template for xxxMeasureCodexxx  -->

  <entryRelationship typeCode=COMP>
    <observation classCode=OBS moodCode=EVN>
      <templateId root="2.16.840.1.113883.10.20.27.3.4"/>
      <code code="assertion"
            codeSystem="2.16.840.1.113883.5.4"
            displayName="Assertion"
            codeSystemName="ActCode"/>
      <statusCode code=completed/>
      <value xsi:type=CD nullFlavor=OTH>
       <originalText>xxxOriginalTextxxx</originalText>
      </value>
      <entryRelationship typeCode=SUBJ inversionInd="true">
        <observation classCode=OBS moodCode=EVN>
          <templateId root="2.16.840.1.113883.10.20.27.3.3"/>
          <code code=MSRAGG
                displayName="rate aggregation"
                codeSystem="2.16.840.1.113883.5.4"
                codeSystemName="ActCode"/>
          <value xsi:type="int" value="xxxStratumCountxxx"/>
          <methodCode code=COUNT
                      displayName="Count"
                      codeSystem="2.16.840.1.113883.5.84"
                      codeSystemName="ObservationMethod"/>
        </observation>
      </entryRelationship>
      <reference typeCode=REFR>
        <externalObservation classCode=OBS moodCode=EVN>
          <id root="xxxStratumIdRootxxx"/>
        </externalObservation>
      </reference>
    </observation>
  </entryRelationship>
';

  vReportTitle varchar2(4000) := 'QRDA Category 3 Calculated Summary Report For';
  vDateTime varchar2(4000) := trim(to_char(sysdate, 'RRRRMMDDHH24MISS'));
  vFirstName varchar2(4000) := '';
  vLastName varchar2(4000) := '';
  vTitle varchar2(4000) := '';
  vNPI varchar2(4000) := '';
  vReportingPeriod varchar2(4000) := '';
  vCQMSDateTime varchar2(4000) := '';
  vCQMEDateTime varchar2(4000) := '';
  vUser users."User"%type := 0;

  vMeasureCount INTEGER := 0;

  -- Supplemental Data
  vXMLSupplementTemp clob := '';
  vGenderM INTEGER := 0;
  vGenderF INTEGER := 0;
  vGenderUNK INTEGER := 0;
  vRaceNATIVE INTEGER := 0;
  vRaceASIAN INTEGER := 0;
  vRaceBLACK INTEGER := 0;
  vRaceISLAND INTEGER := 0;
  vRaceWHITE INTEGER := 0;
  vRaceOTHER INTEGER := 0;
  vRaceUNK INTEGER := 0;
  vEthnicLATINO INTEGER := 0;
  vEthnicOTHER INTEGER := 0;
  vEthnicUNK INTEGER := 0;
  vPayer1 INTEGER := 0;
  vPayer2 INTEGER := 0;
  vPayer349 INTEGER := 0;
  vCQMSDate date := to_date(null);
  vCQMEDate date := to_date(null);

  vStage mryear."Stage"%type := 3;                                              -- works for stage 3 only
  vStep INTEGER := 0;

begin
  --
  -- populate variables
  --
  vStep := 10;

  select
    htf.escape_sc(nvl(trim(prod."FirstName"), ' ')) "FirstName",
    htf.escape_sc(nvl(trim(prod."LastName"), ' ')) "LastName",
    htf.escape_sc(nvl(trim(prod."Title"), ' ')) "Title",
    htf.escape_sc(nvl(trim(substr(prod."NPI", 1, 10)), ' ')) "NPI",
    trim(to_char(sysdate, 'RRRRMMDDHH24MISS')) "DateTime",	
    to_char(trunc(my."DateFrom"), 'RRRRMMDDHH24MISS') "CQMSDateTime",    			-- AX-24377
	to_char(trunc(my."DateTo") + (86399/86400), 'RRRRMMDDHH24MISS') "CQMEDateTime",	-- AX-24377	
	replace(replace(('Reporting period: ' || to_char(my."DateFrom", 'Month DD, RRRR') || ' - ' || to_char(my."DateTo", 'Month DD, RRRR')), '   ', ' '), '  ', ' ') "ReportingPeriod",						  -- AX-24377
    u."User" "User",	
    trunc(my."DateFrom") "CQMSDate",												-- AX-24377
    trunc(my."DateTo") + (86399/86400) "CQMEDate"									-- AX-24377	
  into
    vFirstName,
    vLastName,
    vTitle,
    vNPI,
    vDateTime,
    vCQMSDateTime,
    vCQMEDateTime,
    vReportingPeriod,
    vUser,
    vCQMSDate,
    vCQMEDate
  from
    mryear my,
    producer prod,
    users u
  where 1=1
  and u."Producer" = prod."Producer"
  and my."User" = u."User"
  and u."Deleted" = 0
  and prod."MUEligible" = 1
  and (pIsCQM22 = 1
       or pIsCQM68 = 1
       or pIsCQM74 = 1
       or pIsCQM75 = 1
       or pIsCQM127 = 1
       or pIsCQM138 = 1
       or pIsCQM147 = 1
       or pIsCQM156 = 1)
  and prod."Producer" = pProducer
  and my."Stage" = vStage                                                       -- works for stage 3 only
  and my."Year" = pYear;

  --
  -- replace xxx variables with actual values
  --
  vStep := 20;

  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxDateTimexxx', vDateTime);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxNPIxxx', vNPI);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxFirstNamexxx', vFirstName);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxLastNamexxx', vLastName);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxTitlexxx', vTitle);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxReportingPeriodxxx', vReportingPeriod);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxCQMSDateTimexxx', vCQMSDateTime);
  vXMLHeaderTemplate := replace(vXMLHeaderTemplate, 'xxxCQMEDateTimexxx', vCQMEDateTime);

  vXMLTailTemplate := replace(vXMLTailTemplate, 'xxxCQMSDateTimexxx', vCQMSDateTime);
  vXMLTailTemplate := replace(vXMLTailTemplate, 'xxxCQMEDateTimexxx', vCQMEDateTime);

  --
  -- compose the Measures XML
  --
  vStep := 30;

  for pCQMList in cCQMList (vUser,
                            pYear,
                            pIsCQM22,
                            pIsCQM68,
                            pIsCQM74,
                            pIsCQM75,
                            pIsCQM127,
                            pIsCQM138,
                            pIsCQM147,
                            pIsCQM156) loop
    --
    -- add each CQM to the Measures XML
    --
    vStep := 40;

    vXMLMeasuresHeaderTemp :=  vXMLMeasuresHeaderTemplate;
    vXMLMeasuresHeaderTemp := replace(vXMLMeasuresHeaderTemp, 'xxxIdExtensionxxx', pCQMList."IdExtension");
    vXMLMeasuresHeaderTemp := replace(vXMLMeasuresHeaderTemp, 'xxxMeasureTitlexxx', pCQMList."MeasureTitle");
    vXMLMeasuresHeaderTemp := replace(vXMLMeasuresHeaderTemp, 'xxxSetIdRootxxx', pCQMList."SetIdRoot");

    --
    -- process each measure
    --
    vStep := 50;

    for pCQMMeasures in cCQMMeasures (pCQMList.CQM,
                                      pCQMList."Order") loop
      --
      -- reset measure count value; reset supplemental XML
      --
      vStep := 60;

      vMeasureCount := 0;
      vXMLSupplementTemp := '';

      --
      -- determine which measure to add
      --
      vStep := 70;

      if ((pCQMMeasures.CQM = 156) and (pCQMMeasures."Order" = 2)) then

        if (pCQMMeasures."MeasureCode" = 'IPOP') then
          vMeasureCount := mu_cqm_pkg.CQM156B_IPP (vUser, vCQMSDate, vCQMEDate);
        elsif (pCQMMeasures."MeasureCode" = 'DENOM') then
          vMeasureCount := (mu_cqm_pkg.CQM156B_D (vUser, vCQMSDate, vCQMEDate) + mu_cqm_pkg.CQM156B_EX (vUser, vCQMSDate, vCQMEDate));
        elsif (pCQMMeasures."MeasureCode" = 'DENEX') then
          vMeasureCount := mu_cqm_pkg.CQM156B_EX (vUser, vCQMSDate, vCQMEDate);
        elsif (pCQMMeasures."MeasureCode" = 'NUMER') then
          vMeasureCount := mu_cqm_pkg.CQM156B_N (vUser, vCQMSDate, vCQMEDate);
        elsif (pCQMMeasures."MeasureCode" = 'DENEXCEP') then
          vMeasureCount := 0;
        else
          vMeasureCount := 0;
        end if;

      else

        if (pCQMMeasures."MeasureCode" = 'IPOP') then
          vMeasureCount := pCQMList."InitialPatientPopulation";
        elsif (pCQMMeasures."MeasureCode" = 'DENOM') then
          vMeasureCount := pCQMList."Denominator";
        elsif (pCQMMeasures."MeasureCode" = 'DENEX') then
          vMeasureCount := pCQMList."Exclusion";
        elsif (pCQMMeasures."MeasureCode" = 'NUMER') then
          vMeasureCount := pCQMList."Numerator";
        elsif (pCQMMeasures."MeasureCode" = 'DENEXCEP') then
          vMeasureCount := pCQMList."Exception";
        else
          vMeasureCount := 0;
        end if;

      end if;

      --
      -- add each measure to the Measures XML
      --
      vStep := 80;

      vXMLMeasuresTemp := vXMLMeasuresTemplate;
      vXMLMeasuresTemp := replace(vXMLMeasuresTemp, 'xxxMeasureCodexxx', pCQMMeasures."MeasureCode");
      vXMLMeasuresTemp := replace(vXMLMeasuresTemp, 'xxxMeasureCountxxx', vMeasureCount);

      --
      -- add Measures XML for the current CQM
      --
      vStep := 90;

      vXMLMeasuresHeaderTemp := (vXMLMeasuresHeaderTemp || vXMLMeasuresTemp);

      --
      -- process supplemental data for the current CQM
      --
      vStep := 91;

      for pSupplementalData in cSupplementalData (pCQMList.CQM,
                                                  pCQMList."Order",
                                                  pCQMMeasures."MeasureCode") loop
        --
        -- execute procedure
        --
        vStep := 92;

        execute immediate pSupplementalData."Procedure" using vUser, vCQMSDate, vCQMEDate, out vGenderM, out vGenderF, out vGenderUNK, out vRaceNATIVE, out vRaceASIAN, out vRaceBLACK, out vRaceISLAND, out vRaceWHITE, out vRaceOTHER, out vRaceUNK, out vEthnicLATINO, out vEthnicOTHER, out vEthnicUNK, out vPayer1, out vPayer2, out vPayer349;

        --
        -- process supplemental data for the current measure code and CQM
        --
        vStep := 93;

        for pSupplementalDataDetails in cSupplementalDataDetails (pCQMMeasures."MeasureCode", vGenderM, vGenderF, vGenderUNK, vRaceNATIVE, vRaceASIAN, vRaceBLACK, vRaceISLAND, vRaceWHITE, vRaceOTHER, vRaceUNK, vEthnicLATINO, vEthnicOTHER, vEthnicUNK, vPayer1, vPayer2, vPayer349) loop
          --
          -- create the XML for the supplemental data
          --
          vStep := 94;

          vXMLSupplementTemp := (vXMLSupplementTemp || pSupplementalDataDetails."XMLSupplement");

        end loop pSupplementalDataDetails;

      end loop pSupplementalData;

      --
      -- process CQMs with stratifications
      --
      vStep := 100;

      for pCQMStrata in cCQMStrata (pCQMList.CQM,
                                    pCQMList."User",
                                    pCQMList."DateFrom",
                                    pCQMList."DateTo") loop
        --
        -- reset measure count value
        --
        vStep := 110;

        vMeasureCount := 0;

        --
        -- determine which measure to add
        --
        vStep := 120;

        if (pCQMMeasures."MeasureCode" = 'IPOP') then
          vMeasureCount := pCQMStrata."InitialPatientPopulation";
        elsif (pCQMMeasures."MeasureCode" = 'DENOM') then
          vMeasureCount := pCQMStrata."Denominator";
        elsif (pCQMMeasures."MeasureCode" = 'DENEX') then
          vMeasureCount := pCQMStrata."Exclusion";
        elsif (pCQMMeasures."MeasureCode" = 'NUMER') then
          vMeasureCount := pCQMStrata."Numerator";
        elsif (pCQMMeasures."MeasureCode" = 'DENEXCEP') then
          vMeasureCount := pCQMStrata."Exception";
        else
          vMeasureCount := 0;
        end if;

        --
        -- add each stratum to the Measures XML
        --
        vStep := 130;

        vXMLStratumTemp := vXMLStratumTemplate;
        vXMLStratumTemp := replace(vXMLStratumTemp, 'xxxMeasureCodexxx', pCQMMeasures."MeasureCode");
        vXMLStratumTemp := replace(vXMLStratumTemp, 'xxxOriginalTextxxx', pCQMStrata."OriginalText");
        vXMLStratumTemp := replace(vXMLStratumTemp, 'xxxStratumCountxxx', vMeasureCount);
        vXMLStratumTemp := replace(vXMLStratumTemp, 'xxxStratumIdRootxxx', pCQMStrata."StratumIdRoot");

        --
        -- add stratum XML for the current CQM
        --
        vStep := 140;

        vXMLMeasuresHeaderTemp := (vXMLMeasuresHeaderTemp || vXMLStratumTemp);

      end loop pCQMStrata;

      --
      -- add Measures XML tail for the current CQM
      --
      vStep := 150;

      vXMLMeasuresHeaderTemp := (vXMLMeasuresHeaderTemp || vXMLMeasuresTail2);
      vXMLMeasuresHeaderTemp := replace(vXMLMeasuresHeaderTemp, 'xxxIdRootxxx', pCQMMeasures."IdRoot");

      --
      -- add the Supplemental Data Details for the current CQM
      --
      vStep := 155;

      vXMLMeasuresHeaderTemp := replace(vXMLMeasuresHeaderTemp, 'xxxXMLSupplementTempxxx', vXMLSupplementTemp);

    end loop pCQMMeasures;

    --
    -- add Measures XML for the current CQM
    --
    vStep := 160;

    vXMLMeasuresFinal :=  (vXMLMeasuresFinal || vXMLMeasuresHeaderTemp || vXMLMeasuresTail);

    --
    -- add CQM to the report title
    --
    vStep := 170;

    vReportTitle := (vReportTitle || pCQMList."ReportTitle");

  end loop pCQMList;

  --
  -- update report title
  --
  vStep := 180;

  vXMLHeaderTemplate := replace(replace(vXMLHeaderTemplate, 'xxxReportTitlexxx', vReportTitle), 'For and', 'For');

  --
  -- create final XML
  --
  vStep := 190;

  pOutputFile := (vXMLHeaderTemplate || vXMLMeasuresFinal || vXMLTailTemplate);
  pError := 0;

exception
  when no_data_found then
    --
    -- return a null output file and return an error
    --
    vStep := 200;

    pOutputFile := '';
    pError := 1;

  when others then
    --
    -- return a null outputfile and return an error
    --

    vStep := 210;

    pOutputFile := '';
    pError := 2;

end QRDA_Type3_Stage3_XML_P;

END;
CREATE OR REPLACE PACKAGE BODY sched_pkg IS



--

-- main procedure to return if the given date "TargetDate" is 

--		within the given cycle criteria

-- return 1 if the date is within the cycle constraints; else 0

--

FUNCTION dateiswithincycle(cycletype numeric, cyclecnt numeric, cyclestart timestamp without time zone, cyclefrq numeric, targetdate timestamp without time zone) RETURN numeric IS

BEGIN

	IF CycleType = 0 THEN

		RETURN IsWithInWeeklyCycle(CycleCnt, CycleStart, TargetDate);

	ELSE

		RETURN IsWithInMonthlyCycle(CycleCnt, CycleStart, CycleFrq, TargetDate);

	END IF;

END;



--

-- procedure to return if the given date "TargetDate" is 

--		within the given weekly cycle criteria

-- return 1 if the date is within the weekly cycle constraints; else 0

--

FUNCTION iswithinweeklycycle(cyclecnt numeric, cyclestart timestamp without time zone, targetdate timestamp without time zone) RETURN numeric IS

	CntToUse  NUMBER;

BEGIN

	IF CycleCnt = 1 THEN

		RETURN 1;

	ELSE

	        --AX-39131

	        CntToUse = CycleCnt;

	        IF CycleCnt = 0 THEN

	        	CntToUse = 1;

	        END IF;

		IF  MOD( FLOOR((TO_NUMBER(TO_CHAR(CycleStart, 'J'))-TO_NUMBER(TO_CHAR(TargetDate, 'J')))/7), CntToUse) = 0  THEN

			RETURN 1;

		ELSE

			RETURN 0;

		END IF;

	END IF;

END;



--

-- procedure to return if the given date "TargetDate" is 

--		within the given monthly cycle criteria

-- return 1 if the date is within the monthly cycle constraints; else 0

--

FUNCTION iswithinmonthlycycle(cyclecnt numeric, cyclestart timestamp without time zone, cyclefrq numeric, targetdate timestamp without time zone) RETURN numeric IS

BEGIN

	IF CycleCnt <> 1 THEN

		IF  MOD( ABS(FLOOR(EXTRACT(YEAR FROM TargetDate) * 12 + EXTRACT(MONTH FROM TargetDate) - EXTRACT(YEAR FROM CycleStart) * 12 - EXTRACT(MONTH FROM CycleStart))), CycleCnt) <> 0  THEN			--AX-4303.7875

			RETURN 0;	

		END IF;	

	END IF;

	

	IF CycleFrq = 4 THEN

		RETURN IsLastWeekOfMonth(TargetDate);

	ELSE

		if GetWeekOfMonth(TargetDate) = CycleFrq THEN

			RETURN 1;

		else

			RETURN 0;

		END IF;

	END IF;

END;



--

-- procedure to return if the given date "TargetDate" is 

--		is in the last week of the month

-- return 1 if the date is within the last week of the month; else 0

--

FUNCTION islastweekofmonth(targetdate timestamp without time zone) RETURN numeric IS

BEGIN

	IF  (last_day(TargetDate) - TargetDate) < 7  THEN

		RETURN 1;

	ELSE

		RETURN 0;

	END IF;

END;



--

-- procedure to return the week of the month for the 

--		given date "TargetDate" 

-- return the week of the month; 0 - First, 1 Second, 2 Third, 3 - Fourth

--

FUNCTION getweekofmonth(targetdate timestamp without time zone) RETURN numeric IS

	FirstDayOfTheMonth DATE;

	CurrentWeek NUMBER;

BEGIN

	FirstDayOfTheMonth := TO_DATE((TO_CHAR(TargetDate, 'YYYYMM')||'01'), 'YYYYMMDD');

	CurrentWeek := FLOOR((TO_NUMBER(TO_CHAR(TargetDate, 'J'))-TO_NUMBER(TO_CHAR(FirstDayOfTheMonth, 'J')))/7);	--AX-39131



	RETURN CurrentWeek;	

END;



FUNCTION getmaxschdate(txtype numeric, txid numeric, txtreatment numeric, excludeapptid numeric) RETURN timestamp without time zone IS

	MaxDate DATE;

BEGIN

  BEGIN 

    SELECT MAX(AP."Date")

      INTO MaxDate

      FROM APPTRX A, APPOINT AP

      WHERE A."Type" = TxType 

	  	AND A."Id" = TxId 

		AND A."Treatment" = TxTreatment

		AND A."Appointment" = AP."Appointment"

		AND AP."Status" = 0 

		AND AP."Type" NOT IN (3,4,5,6,7,10) -- E129403.3c

		AND AP."Appointment" <> ExcludeApptId;

  EXCEPTION WHEN NO_DATA_FOUND THEN

  	MaxDate := NULL;

  END;



  RETURN MaxDate;

END;



-- E98324

FUNCTION isreserveavailable(rreserve numeric, rdate timestamp without time zone, rchair numeric, rstart numeric, rend numeric, rprovider character, duration numeric, apptcode character) RETURN numeric IS

  Result NUMBER;

  iStart NUMBER;

  

  CURSOR C1 (R_Reserve NUMBER, R_Date DATE, R_Chair NUMBER, R_End NUMBER, R_Start NUMBER) IS

    SELECT A."From", A."Time0"+A."Time1"+A."Time2"+A."Time3"+A."Time4"+A."Time5" ApptLength

     FROM APPOINT A 

     WHERE 

     ((A."Reserve"=R_Reserve) OR 

      (A."Date"=R_Date AND A."Chair"=R_Chair AND A."From"<R_End

       and (A."From"+A."Time0"+A."Time1"+A."Time2"+A."Time3"+A."Time4"+A."Time5")>R_Start))

     and A."Type" IN (0,1,2)

   ORDER BY A."From";

   

BEGIN

  IF REnd - RStart < Duration THEN

    return 0;

  END IF;



  Result := 1;

  iStart := RStart;

  

  FOR rec IN C1(RReserve, RDate, RChair, REnd, RStart) LOOP

    IF rec."From" - iStart >= Duration THEN

      return 1;

    ELSE

      iStart := rec."From" + rec.ApptLength;

      IF REnd - iStart < Duration THEN

        return 0;

      END IF;

    END IF;

       

  END LOOP;



  RETURN (Result);

END;



-- E37995.22   added 

FUNCTION getapptrx(appointment numeric) RETURN character IS

	szProcedures	 VARCHAR2(255);

	CURSOR C1 (ApptId NUMBER) IS

			SELECT RTRIM(AT."Procedure") szProc FROM APPTRX AT 

			WHERE AT."Appointment"=ApptId;

   

BEGIN

	szProcedures := '';

	

	FOR rec IN C1(Appointment) LOOP

		IF LENGTH(szProcedures) > 0 THEN

			szProcedures := szProcedures || ', ';

		END IF;

		szProcedures := szProcedures || rec.szProc;

		IF LENGTH(szProcedures) > 200 THEN

			EXIT;

		END IF;

   END LOOP;



	IF LENGTH(szProcedures) > 200 THEN

		szProcedures := SUBSTR(szProcedures, 1, 196);

		szProcedures := szProcedures || '...';

	END IF;

	

	RETURN szProcedures;

END;



--B79114

PROCEDURE removefromwaitlist(IN nappointmentid numeric, IN nuser numeric, IN nstationid numeric, IN naudit numeric) IS

nWaitListCount NUMBER(10);

vSql  VARCHAR2(2000);



BEGIN



  SELECT COUNT(1)

        INTO nWaitListCount

        FROM WAITLIST

       WHERE "Appointment"  = nAppointmentID;

      IF nWaitListCount = 1 THEN

        vSql := 'Update WAITLIST set "Status" =1, "Audit" = :1 where "Appointment"  = :2';

        EXECUTE IMMEDIATE vSql USING nAudit, nAppointmentID;

        

        INSERT INTO REQNOTE VALUES (

	REQNOTE_REQNOTE_SEQ.nextval, 

  nAppointmentID,--nAppointment

  trunc(sysdate),

	TO_NUMBER(TO_CHAR(SysDate, 'HH24'))*60+TO_NUMBER(TO_CHAR(SysDate, 'MI')),

	nUser ,

	nStationId, 

	0,

  NULL, -- AX-40610

	'Appointment removed from the  wait list(resolved)'

);



      END IF;

      

END REMOVEFROMWAITLIST;





-- E100080 added capability outside of axiUm to dictate what requires startcheck and what's not

-- defaulted to always return true; but clients can have their own custom version with their own rules

-- AX-14934.15658: resolved start check issue causing slow down; basically not needed

FUNCTION requiresstartchk(nappointmentid numeric) RETURN numeric IS

  nResult NUMBER := 0;

	v_nCount		NUMBER := 0;								-- AX-26071

--  nCount	NUMBER := 0;



--	CURSOR C1 (ApptId NUMBER) IS

--			SELECT RTRIM(AT."Procedure") szProc FROM APPTRX AT 

--			WHERE AT."Appointment"=ApptId;

  

BEGIN



	nResult := 1;

	

	-- Example: this demostrates if RequiresTrxStartChk return true 

	--				then the following returns true, else false (E100080.5)

	-- 

	--nResult := 0; 

	--FOR rec IN C1(nAppointmentID) LOOP

	--	nCount := nCount + 1;

	--   if  RequiresTrxStartChk(nAppointmentID, rec.szProc) = 1 THEN

	--	   nResult := 1;

	--	   EXIT;

	--   END IF;

	--END LOOP;

	

	-- if no APPTRX, simply return true as well

	--if nCount = 0 THEN

	--   nResult := 1;

	--END IF;

   

	--AX-26071

   SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_SCHED_PKG' and PROCEDURE_NAME = UPPER('RequiresStartChk');

   IF v_nCount > 0 THEN

     -- custom package function exists 

     EXECUTE IMMEDIATE 'SELECT CUSTOM_SCHED_PKG.RequiresStartChk('||nAppointmentID||') FROM DUAL' INTO nResult;

     RETURN nResult;

	ELSE

		-- no customization, start check is always required

		RETURN 1;

   END IF;

	

END RequiresStartChk;



FUNCTION requirestrxstartchk(nappointmentid numeric, cprocedure character) RETURN numeric IS

  nResult NUMBER := 0;

	v_nCount		NUMBER := 0;								-- AX-26071



BEGIN



	nResult := 1;

	

	-- Example: this demostrates if procedures starting with T requires start check 

	--				then the following returns true, else false

	-- 

	-- nResult := 0; 

	-- if  SUBSTR(cProcedure, 1) = 'T'  THEN

	--		nResult := 1;

	-- END IF;

    

	--AX-26071

   SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_SCHED_PKG' and PROCEDURE_NAME = UPPER('RequiresTrxStartChk');

   IF v_nCount > 0 THEN

     -- custom package function exists 

     EXECUTE IMMEDIATE 'SELECT CUSTOM_SCHED_PKG.RequiresTrxStartChk('||nAppointmentID||', '''||cProcedure||''') FROM DUAL' INTO nResult;

     RETURN nResult;

	ELSE

		-- no customization, start check is always required

		RETURN 1;

   END IF;

	

END RequiresTrxStartChk;





-- E131368

FUNCTION getwaitdays(nappointmentid numeric) RETURN numeric IS

  nResult NUMBER := 0;

BEGIN

  BEGIN 

    SELECT COALESCE(EXTRACT(DAY FROM (DATE_TRUNC('day', CURRENT_TIMESTAMP)::date - H."Date"::date)), 0)

      INTO nResult

      FROM APPOINT A, WAITLIST W, AUDITHIS H

      WHERE A."Appointment" = nAppointmentID

		AND A."Appointment" =  W."Appointment"

		AND W."CreateAudit" = H."Audit"(+);

  EXCEPTION WHEN NO_DATA_FOUND THEN

  	nResult := 0;

  END;

  RETURN nResult;

END GetWaitDays;



-- AX-17107.17477d; AX-18706

FUNCTION appointhasunapprovedwaste(nappointmentid numeric, nuser numeric) RETURN numeric IS

  nResult NUMBER := 0;

BEGIN

  BEGIN 

    SELECT COUNT(1)

	 INTO nResult

		FROM PTSURG PS,

		  PTSDRUG PD,

		  AUDITHIS A

		WHERE PS."Appointment"      = PD."Appointment"

		AND PS."WasteApprovalUser" <= 0

		AND PD."Appointment"        = nAppointmentID

		AND PD."Waste"              > 1

		AND PD."Deleted"            = 0

		AND PD."WasteAmount"		> -1 

		AND PD."WasteDeleted"		= 0

		AND PD."WasteAudit" (+)		 = A."Audit"

		AND A."User"                = nUser;

  EXCEPTION WHEN NO_DATA_FOUND THEN

  	nResult := 0;

  END;

  RETURN nResult;

END AppointHasUnapprovedWaste;



-- AX-17559.18658b

FUNCTION appointproviderhasunapproved(nappointmentid numeric, nuser numeric) RETURN numeric IS

  nResult NUMBER := 0;

BEGIN

  BEGIN 

    SELECT COUNT(1)

	 INTO nResult

		FROM APPOINT A,

		  USERS U,

		  PATIENT PT,

		  PTSURG S

		WHERE A."Appointment"   = nAppointmentID

		AND A."User"            = nUser

		AND A."User"            = U."User"

		AND A."Appointment"     = S."Appointment"

		AND S."ApprovalUser"    = 0

		AND A."Producer"        = U."Producer"

		AND U."SurgeryNeedsApp" = 1

		AND A."Patient"         = PT."Patient"

		AND (EXISTS

		  (SELECT 1 FROM PTVITAL V WHERE V."Appointment" = S."Appointment"

		  )

		OR EXISTS

		  (SELECT 1

		  FROM PTSDRUG D,

			 PTSDOSE DS

		  WHERE D."Appointment" = S."Appointment"

		  AND D."PtSDrug"       = DS."PtSDrug"

		  ));

  EXCEPTION WHEN NO_DATA_FOUND THEN

  	nResult := 0;

  END;

  RETURN nResult;

END AppointProviderHasUnapproved;





END;
CREATE OR REPLACE PACKAGE BODY slevel_pkg IS


PROCEDURE add_extra(IN slevel numeric) IS
 veForms NUMBER := 0;
 NUMBER_OF_EHR_TABS CONSTANT NUMBER := 13; -- AX-32658
BEGIN

 IF SLevel < 0 THEN
	RETURN; -- E85107.8
 END IF;

 -- ACCESS tables
 INSERT INTO PATACCES (SELECT "PatType", SLevel, 0, 0, 0, 0, 0 FROM PATTYPE);

 INSERT INTO ATACCESS (SELECT "AtTab", SLevel, 0 FROM ATTAB);

 INSERT INTO DRUGACC (SELECT "Drug", SLevel, 0, 0 FROM DRUG);					-- E50367

 INSERT INTO FIACCESS (SELECT FI."FormCode", FI."FItem", SLevel, 0, 0 FROM FORM F, FITEM FI		-- E50367, E53214.4
		WHERE F."Code" = FI."FormCode" AND FI."Type" = 0 AND FI."Deleted" = 0 AND F."Type" <> 6);

 INSERT INTO CRACCESS (SELECT "CustRpt", SLevel, 0, 0, 0, 0, 0,0 FROM CUSTRPT WHERE "Type" <> 3);	-- E44244, E40397, B122354 -- E141865; AX-25118.3
 INSERT INTO CRACCESS (SELECT "CustRpt", SLevel, 1, 0, 0, 0, 0,0 FROM CUSTRPT WHERE "Type" = 3);	-- AX-25118.3

 INSERT INTO PCACCESS (SELECT "PCView", "RecType", SLevel, 0 FROM PCVITEM);

 INSERT INTO PCVACC (SELECT "PCView", SLevel, 0 FROM PCVIEW);

 INSERT INTO TXHVACC (SELECT "TxHView", SLevel, 0 FROM TXHVIEW);

 -- AX-20065.20091 we are using the same value (EHRTAB_ORALSURGERY) for both Oral Surgery and Chart in EHRACC (depending on Oral Surgery Mode). No need for value 0
 --AX-26942 INSERT INTO EHRACC (SELECT ROWNUM, SLevel, 0 FROM ALL_OBJECTS WHERE ROWNUM < 13);   -- AX-20065.20091	-- E136891.2 -- AX-13241; AX-21082.21089
 INSERT INTO EHRACC (SELECT ROWNUM, SLevel, 0 FROM DUAL CONNECT BY LEVEL < NUMBER_OF_EHR_TABS + 1);			--AX-26942, AX-32658

 INSERT INTO LINKACC (SELECT "LinkDef", SLevel, 0 FROM LINKDEF);

 INSERT INTO ADJACC (SELECT "Adjust", SLevel, 1, 0, 0 FROM ADJUST);	-- E53578

 INSERT INTO INFOPACC (SELECT "InfoProc", SLevel, 0 FROM INFOPROC);	-- E38602

 INSERT INTO INDACC (SELECT I."Indicat", SLevel, 0, I."Indicat" + 1 FROM INDICAT I); -- E124381	

 INSERT INTO CNSACC (SELECT "CNState", SLevel, 0 FROM CNSTATE);     -- E127712

 -- B132202
 INSERT INTO CONSACC (SELECT "Consent", SLevel, 0 FROM CONSENT);     -- E96625

 --AX-671.2466
 INSERT INTO TEMPLACC (SELECT "Template", SLevel, 0 FROM TEMPLATE);     -- AX-671.2466c

 INSERT INTO OSTEMACC (SELECT "OSTempl", SLevel, 0 FROM OSTEMPL); -- AX-16509.18056

 -- E42200		
INSERT INTO CQACCESS (SELECT "CUST_QRY_AutoDec", SLevel, 0, 0 FROM CUST_QRY);
INSERT INTO LLACCESS (SELECT 0, "LETTERS_AutoDec", SLevel, 0, 0 FROM LETTERS);
INSERT INTO LLACCESS (SELECT 1, "LABELS_AutoDec", SLevel, 0, 0 FROM LABELS);
INSERT INTO DTACCESS (SELECT "Type", "DocTempl", SLevel, 0, 0 FROM DOCTEMPL WHERE "Type" = 0);
INSERT INTO DTACCESS (SELECT "Type", "DocTempl", SLevel, 0, 0 FROM DOCTEMPL WHERE "Type" = 1);	
 -- AX-11227.11597
INSERT INTO CTBLACC (SELECT "CTblFile", SLevel, 0 FROM CTBLFILE);

INSERT INTO COMACC (SELECT "Auto", SLevel, 0 FROM COMMENT2);  -- AX-25980.AX-26000

INSERT INTO TPARTYACC (SELECT "TPartyDef", SLevel, 0 FROM TPARTYDEF);  -- AX-27166

END;


PROCEDURE copy_extra(IN newslevel numeric, IN oldslevel numeric) IS
	m_EHROpts 		NUMBER := 0;
	m_OldEHROpts	NUMBER := 0;
	m_EHRCat  		NUMBER := 0;

  veForms NUMBER := 0;
	 	
	CURSOR ehrcat_csr (EHROpts NUMBER)
	IS
	SELECT * FROM EHRCAT WHERE "EHROpts" = EHROpts;

	CURSOR ehrcitem_csr (EHRCat NUMBER)
	IS
	SELECT * FROM EHRCITEM WHERE "EHRCat" = EHRCat;
	
	-- B123878
	CURSOR ehrdcat_csr (EHROpts NUMBER)
	IS
	SELECT * FROM EHRDCAT WHERE "EHROpts" = EHROpts;

	CURSOR ehrditem_csr (EHRDCat NUMBER)
	IS
	SELECT * FROM EHRDITEM WHERE "EHRDCat" = EHRDCat;

 	
BEGIN

 IF NewSLevel < 0 OR OldSLevel < 0 THEN
	RETURN; -- E85107.8
 END IF;

 -- ACCESS tables
 -- E54824, AX-24316
 INSERT INTO PATACCES (SELECT "PatType", NewSLevel, "Patients",
 		"AddTxs", "MultiProcedure", "AddFees", "Reporting"
		FROM PATACCES WHERE "SLevel" = OldSLevel);
		
 INSERT INTO ATACCESS (SELECT "AtTab", NewSLevel, "Access"
		FROM ATACCESS WHERE "SLevel" = OldSLevel);

 INSERT INTO DRUGACC (SELECT "Drug", NewSLevel, "Access", "CanApprove"	-- E50367
		FROM DRUGACC WHERE "SLevel" = OldSLevel);

 INSERT INTO FIACCESS (SELECT "FormCode", "FItem", NewSLevel, "Access", "CanApprove"	-- E50367
		FROM FIACCESS WHERE "SLevel" = OldSLevel);

 INSERT INTO CRACCESS (SELECT "CustRpt", NewSLevel, "Access", "DisablePrint", "DisableExport", "IsDefault", "DisableAttach", "UserId" -- B122354 -- E141865
		FROM CRACCESS WHERE "SLevel" = OldSLevel);	-- E44244, E40397

 INSERT INTO PCACCESS (SELECT "PCView", "RecType", NewSLevel, "Access"
		FROM PCACCESS WHERE "SLevel" = OldSLevel);

 INSERT INTO PCVACC (SELECT "PCView", NewSLevel, "Access"
		FROM PCVACC WHERE "SLevel" = OldSLevel);

 INSERT INTO TXHVACC (SELECT "TxHView", NewSLevel, "Access"
		FROM TXHVACC WHERE "SLevel" = OldSLevel);

 INSERT INTO EHRACC (SELECT "EHRTab", NewSLevel, "Access"
		FROM EHRACC WHERE "SLevel" = OldSLevel);

 INSERT INTO LINKACC (SELECT "LinkDef", NewSLevel, "Access"
		FROM LINKACC WHERE "SLevel" = OldSLevel);
				
 -- E53578
 INSERT INTO ADJACC (SELECT "Adjust", NewSLevel, "Access", "MaxAmount", "LimitedTo"
		FROM ADJACC WHERE "SLevel" = OldSLevel);
		
 -- E38602
 INSERT INTO INFOPACC (SELECT "InfoProc", NewSLevel, "Access"
 		FROM INFOPACC WHERE "SLevel" = OldSLevel);
 		
 -- E124381
 INSERT INTO INDACC (SELECT "Indicat", NewSLevel, "Show", "Order"
 		FROM INDACC WHERE "SLevel" = OldSLevel);
 		
 -- E42200		
INSERT INTO CQACCESS (SELECT "CustQry", NewSLevel, "UserId", "Access"
	FROM CQACCESS WHERE "SLevel" = OldSLevel);
INSERT INTO LLACCESS (SELECT "LLType", "Id", NewSLevel, "UserId", "Access"
	FROM LLACCESS WHERE "SLevel" = OldSLevel);
INSERT INTO DTACCESS (SELECT "DTType", "DocTempl", NewSLevel, "UserId", "Access"
	FROM DTACCESS WHERE "SLevel" = OldSLevel);

-- AX-22287 added
INSERT INTO CTBLACC (SELECT "CTblFile", NewSLevel, 0
	FROM CTBLACC WHERE "SLevel" = OldSLevel);

-- E127712
-- B132202
INSERT INTO CNSACC (SELECT "CNState", NewSLevel, "Access" FROM CNSACC WHERE "SLevel" = OldSLevel);

-- E96625
-- B132202
INSERT INTO CONSACC (SELECT "Consent", NewSLevel, "Access" FROM CONSACC WHERE "SLevel" = OldSLevel);

INSERT INTO COMACC (SELECT "Auto", NewSLevel, "Access" FROM COMACC WHERE "SLevel" = OldSLevel); -- AX-25980.AX-26000

INSERT INTO TPARTYACC (SELECT "TPartyDef", NewSLevel, "Access" FROM TPARTYACC WHERE "SLevel" = OldSLevel); --AX-27166

--AX-671.2466b
INSERT INTO TEMPLACC (SELECT "Template", NewSLevel, "Access" FROM TEMPLACC WHERE "SLevel" = OldSLevel);

-- AX-16509.18056
INSERT INTO OSTEMACC (SELECT "OSTempl", NewSLevel, "Access" FROM OSTEMACC WHERE "SLevel" = OldSLevel);

 -- ehr options; E45982, E64055
 SELECT MAX("EHROpts") INTO m_OldEHROpts FROM EHROPTS WHERE "SLevel" = OldSLevel;
 SELECT EHROPTS_EHROPTS_SEQ.NEXTVAL INTO m_EHROpts FROM DUAL;

 INSERT INTO EHROPTS (SELECT m_EHROpts, NewSLevel,
 		"User", "Status", "Background", "PerioCond1", "PerioSection1",
 		"PerioCond2", "PerioSection2", "PerioCond3", "PerioSection3",
 		"PerioCond4", "PerioSection4", "DefaultTab", "DefaultMaximized",
 		"ShowAlert", "ShowPtAlert", "ShowPtNeed", "ShowPtOffice", "DefaultAddTxTab",
 		"DefaultTxHView", "DefaultForm", "TabOrder", "InProgressView", "OpenToolbars",
 		"DefaultOrthoView", "DefaultPerioView", "InProgressSteps", "DefaultSubTab",
 		"ShowMedications", "ShowPtSummaries", "UseDiagProc", "ShowDiagFull",					 -- E130137, E72773
 		"ShowAllergies", "ShowMedProb"																	 -- E142022
		, "EHRisOS"																			-- AX-13242.13408
		FROM EHROPTS WHERE "EHROpts" = m_OldEHROpts);
		
		
 -- insert ehr quicklist categories		
 FOR ehrcat_rec IN ehrcat_csr (m_OldEHROpts)
 LOOP
		
	 SELECT EHRCAT_EHRCAT_SEQ.NEXTVAL INTO m_EHRCat FROM DUAL;
	
	 INSERT INTO EHRCAT VALUES (m_EHRCat, m_EHROpts,
			ehrcat_rec."Type", ehrcat_rec."Index", ehrcat_rec."Category", ehrcat_rec."OpenMode"); -- B123878
			
	 -- insert ehr quicklist category items
	 FOR ehrcitem_rec IN ehrcitem_csr (ehrcat_rec."EHRCat")
	 LOOP
	
	 	-- E22348 changed field name ("Code" from "Procedure") and added "Type" field
	 	INSERT INTO EHRCITEM VALUES (EHRCITEM_EHRCITEM_SEQ.NEXTVAL, m_EHRCat,
	 		ehrcitem_rec."IsHeading", ehrcitem_rec."Parent", ehrcitem_rec."Index",
	 		ehrcitem_rec."Description", ehrcitem_rec."Code", ehrcitem_rec."Type");
	
	 END LOOP;
 END LOOP;

 -- B123878 - insert ehr diagnosis quicklist categories		
 FOR ehrdcat_rec IN ehrdcat_csr (m_OldEHROpts)
 LOOP
		
	 SELECT EHRDCAT_EHRDCAT_SEQ.NEXTVAL INTO m_EHRCat FROM DUAL;
	
	 INSERT INTO EHRDCAT VALUES (m_EHRCat, m_EHROpts, ehrdcat_rec."Index",
		ehrdcat_rec."Category", ehrdcat_rec."OpenMode");
			
	 -- insert ehr quicklist category items
	 FOR ehrditem_rec IN ehrditem_csr (ehrdcat_rec."EHRDCat")
	 LOOP

	 	INSERT INTO EHRDITEM VALUES (EHRDITEM_EHRDITEM_SEQ.NEXTVAL, m_EHRCat,
	 		ehrditem_rec."IsHeading", ehrditem_rec."Parent", ehrditem_rec."Index",
	 		ehrditem_rec."Description", ehrditem_rec."DiagCode");
	
	 END LOOP;
 END LOOP;

 INSERT INTO PROBSLEV (SELECT NewSLevel, "Problem"
		FROM PROBSLEV WHERE "SLevel" = OldSLevel);

END;



PROCEDURE delete_extra(IN slevel numeric) IS
 veForms NUMBER := 0;
BEGIN

 IF SLevel < 0 THEN
	RETURN; -- E85107.8
 END IF;

 -- ACCESS tables
 DELETE FROM PATACCES WHERE "SLevel" = SLevel;
 DELETE FROM ATACCESS WHERE "SLevel" = SLevel;
 DELETE FROM DRUGACC WHERE "SLevel" = SLevel;
 DELETE FROM FIACCESS WHERE "SLevel" = SLevel;
 DELETE FROM CRACCESS WHERE "SLevel" = SLevel;
 DELETE FROM PCACCESS WHERE "SLevel" = SLevel;
 DELETE FROM PCVACC WHERE "SLevel" = SLevel;
 DELETE FROM TXHVACC WHERE "SLevel" = SLevel;
 DELETE FROM EHRACC WHERE "SLevel" = SLevel;
 DELETE FROM LINKACC WHERE "SLevel" = SLevel;
 DELETE FROM ADJACC WHERE "SLevel" = SLevel;		-- E53578
 DELETE FROM INFOPACC WHERE "SLevel" = SLevel;	-- E38602
 DELETE FROM INDACC WHERE "SLevel" = SLevel;		-- E124381
 DELETE FROM CNSACC WHERE "SLevel" = SLevel;		-- E127712
 DELETE FROM CONSACC WHERE "SLevel" = SLevel;		-- E96625
 DELETE FROM TEMPLACC WHERE "SLevel" = SLevel;		--AX-671.2466b
 DELETE FROM OSTEMACC WHERE "SLevel" = SLevel;		-- AX-16509.18056

 DELETE FROM CQACCESS WHERE "SLevel" = SLevel;	-- E42200
 DELETE FROM LLACCESS WHERE "SLevel" = SLevel;	-- E42200
 DELETE FROM DTACCESS WHERE "SLevel" = SLevel;	-- E42200
 DELETE FROM CTBLACC WHERE "SLevel" = SLevel;  -- AX-11227.11597
 DELETE FROM COMACC WHERE "SLevel" = SLevel; -- AX-25980.AX-26000

 DELETE FROM TPARTYACC WHERE "SLevel" = SLevel;		 -- AX-27166


 -- ehr options
 DELETE FROM EHRCITEM WHERE "EHRCat" in (
 	SELECT C."EHRCat" FROM EHRCAT C, EHROPTS O
 	WHERE C."EHROpts" = O."EHROpts" AND O."SLevel" = SLevel);
 DELETE FROM EHRCAT WHERE "EHROpts" in (
	SELECT "EHROpts" FROM EHROPTS WHERE "SLevel" = SLevel);
	
 -- B123878
 DELETE FROM EHRDITEM WHERE "EHRDCat" in (
 	SELECT C."EHRDCat" FROM EHRDCAT C, EHROPTS O
 	WHERE C."EHROpts" = O."EHROpts" AND O."SLevel" = SLevel);
 DELETE FROM EHRDCAT WHERE "EHROpts" in (
	SELECT "EHROpts" FROM EHROPTS WHERE "SLevel" = SLevel);	
	
 DELETE FROM EHROPTS WHERE "SLevel" = SLevel;

 -- other tables
 DELETE FROM PROBSLEV WHERE "SLevel" = SLevel;

END;




END;
CREATE OR REPLACE PACKAGE BODY split_pkg IS



-- FUNCTION TRX_ESTIMATE

--

-- Function to return the Estimated Amount that a patient will be charged for a treatment

--

-- INPUT: TrxType,TrxId,TrxTreatment - TRX record (Charge)

--    BindingQuote 0=No, 1=Yes, use binding quote

--    BillMethod: 0=Doctor Fee, 1=Patient Fee, 2=Higher Fee

--    CalculateOwing:0=Return Total for appt/Treatment,	1=Return Owing portion of appt/treatment

-- RETURN: Estimated Patient Amount for the treatment

--

-- NOTE{E76232}: As per E76232, there are now two separate flags for binding quote - one for planned and one for in process txs

--			However from analysing the routines involved, the binding quote parameter isn't being referenced throughout!!

--			Between Mark and myself, we have decided to leave this for now; add this comment to indicate that:

--			If we ever reference the binding quote parameter in any of these functions, we'll need to enhance these further

--			to either take additional parameter, or pass different variable parameter based on the tx type.

--





FUNCTION trx_estimate(trxtype numeric, trxid numeric, trxtreatment numeric, bindingquote numeric, billmethod numeric, calculateowing numeric, provider character, frompayment numeric) RETURN numeric IS

  Total NUMBER := 0;



BEGIN

 

 IF CalculateOwing = 0 THEN

  BEGIN

   SELECT (T."Total"-T."InsTotal") into Total from trx t where t."Type"=TrxType

    and t."Id"=TrxId and t."Treatment"=TrxTreatment and t."Deleted"=0;							--AX-27917

  EXCEPTION

   WHEN NO_DATA_FOUND THEN

    Total := 0;

  END;   

 ELSE

  -- B76598 added type 1

  -- B121599 only do type 1 if not from payment screen

  IF TrxType = 5 OR (TrxType = 1 AND FromPayment = 0) THEN

   BEGIN

    SELECT (T."Total"-T."InsTotal"-T."Payed"+T."PtAdj"+T."InsTransfer") into Total from trx t where t."Type"=TrxType

     and t."Id"=TrxId and t."Treatment"=TrxTreatment and t."Deleted"=0;							--AX-27917						

   EXCEPTION

    WHEN NO_DATA_FOUND THEN

     Total := 0;

   END;   

  END IF;

 END IF;

 

 IF Total IS NULL THEN

    Total := 0;

 END IF;



 RETURN Total;

END;



-- FUNCTION APPOINT_ESTIMATE

--

-- Function to return the Estimated Amount that a patient will be charged for an appt

--

-- INPUT: Appointment - APPOINT record

--    BindingQuote 0=No, 1=Yes, use binding quote

--    BillMethod: 0=Doctor Fee, 1=Patient Fee, 2=Higher Fee

--    CalculateOwing:0=Return Total for appt/Treatment,	1=Return Owing portion of appt/treatment

--    FromPayment: 0 = not from trx payment screen

-- RETURN: Estimated Patient Amount for the appointment



FUNCTION appoint_estimate(appointment numeric, bindingquote numeric, billmethod numeric, calculateowing numeric, frompayment numeric) RETURN numeric IS

  Total NUMBER := 0;



BEGIN

 

 BEGIN

   SELECT SUM(split_pkg.TRX_ESTIMATE(T."Type",T."Id",T."Treatment",BindingQuote,BillMethod,CalculateOwing,A."Producer", FromPayment)) INTO Total -- B121599

    FROM APPTRX T, APPOINT A WHERE A."Appointment"=Appointment AND T."Appointment"=Appointment AND T."Id">0;

 EXCEPTION

   WHEN NO_DATA_FOUND THEN

    Total := 0;

 END;   



   IF Total IS NULL THEN

    Total := 0;

   END IF;



   RETURN Total;

END;







-- FUNCTION GET_FEEDATES

--

-- Function to return the FeesDate id for a fee schedule and date

--

-- INPUT: Fee - a fee schedule

--    AsOfDate - date to look for a valid FEEDATES

-- RETURN: FEEDATES.FeeDates of record found, or 0 if no record found



FUNCTION get_feedates(fee character, asofdate timestamp without time zone) RETURN numeric IS

	Result NUMBER := 0;

BEGIN

	

	SELECT "FeeDates" INTO Result FROM FEEDATES 

	 WHERE "Fee" = Fee 

	   AND nvl("StartDate", sysdate-50000) <= AsOfDate

		AND nvl("EndDate", sysdate+50000) >= AsOfDate;

		

	RETURN Result;

	EXCEPTION

		WHEN NO_DATA_FOUND THEN

    RETURN NULL;

END;





END;
CREATE OR REPLACE PACKAGE BODY swipepin_pkg IS


FUNCTION isvalidpin("PIN" character varying) RETURN numeric IS
	vErrNum NUMBER := 0;

BEGIN
	IF LENGTH("PIN") < 4 THEN
		vErrNum := 1;
	ELSIF LENGTH("PIN") > 10 THEN
		vErrNum := 2;
	END IF;

	RETURN vErrNum;
END;

FUNCTION geterrorstr(errnum numeric) RETURN character varying IS
	vErrStr CHAR(255) := '';

BEGIN
	IF ErrNum = 1 THEN
		vErrStr := 'Swipe PIN must contain at least 4 digits.';
	ELSIF ErrNum = 2 THEN
		vErrStr := 'Swipe PIN must not be longer than 10 digits.';
	END IF;

	RETURN vErrStr;
END;


END;
CREATE OR REPLACE PACKAGE BODY treatme2_pkg IS
	FUNCTION display_code(pcodeid numeric) RETURN character IS
		vCode CHAR(7) := ' ';
	BEGIN
		SELECT "Procedure" INTO vCode FROM PROCEDUR WHERE "Id" = pCodeId;
		return vCode;
	END;
	FUNCTION display_date(pdate numeric) RETURN timestamp without time zone IS
	  vDate DATE;
	BEGIN
	  vDate := TO_DATE ('1901-JAN-01', 'YYYY-MON-DD') + pDate;
	  RETURN vDate;
	END;
	FUNCTION display_site(psite numeric) RETURN character IS
	  vSite CHAR (3);
	BEGIN
	  SELECT
		 CASE pSite
			WHEN 0
			THEN ' '
			WHEN 33
			THEN 'UA'
			WHEN 34
			THEN 'LA'
			WHEN 35
			THEN 'UR'
			WHEN 36
			THEN 'UL'
			WHEN 37
			THEN 'LR'
			WHEN 38
			THEN 'LL'
			WHEN 39
			THEN 'URS'
			WHEN 40
			THEN 'UCS'
			WHEN 41
			THEN 'ULS'
			WHEN 42
			THEN 'LRS'
			WHEN 43
			THEN 'LCS'
			WHEN 44
			THEN 'LLS'
			WHEN 45
			THEN 'A'
			WHEN 46
			THEN 'B'
			WHEN 47
			THEN 'C'
			WHEN 48
			THEN 'D'
			WHEN 49
			THEN 'E'
			WHEN 50
			THEN 'F'
			WHEN 51
			THEN 'G'
			WHEN 52
			THEN 'H'
			WHEN 53
			THEN 'I'
			WHEN 54
			THEN 'J'
			WHEN 55
			THEN 'K'
			WHEN 56
			THEN 'L'
			WHEN 57
			THEN 'M'
			WHEN 58
			THEN 'N'
			WHEN 59
			THEN 'O'
			WHEN 60
			THEN 'P'
			WHEN 61
			THEN 'Q'
			WHEN 62
			THEN 'R'
			WHEN 63
			THEN 'S'
			WHEN 64
			THEN 'T'
			WHEN 65
			THEN 'FM'
			WHEN 66
			THEN '99'
			ELSE TO_CHAR (pSite)
		 END
	  INTO vSite
	  FROM dual;
	  RETURN vSite;
	END;
	FUNCTION surface_b_or_f(psite numeric) RETURN character IS
	  vBOrF CHAR (1);
	BEGIN
	  IF pSite IN (1, 2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 28, 29, 30, 31, 32) THEN
		 vBOrF := 'B';
	  ELSE
		 vBOrF := 'F';
	  END IF;
	  RETURN vBOrF;
	END;
	FUNCTION surface_o_or_i(psite numeric) RETURN character IS
	  vBOrI CHAR (1);
	BEGIN
	  IF pSite IN (1, 2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 28, 29, 30, 31, 32) THEN
		 vBOrI := 'O';
	  ELSE
		 vBOrI := 'I';
	  END IF;
	  RETURN vBOrI;
	END;
	FUNCTION display_surface(psite numeric, psurface numeric) RETURN character IS
	  vSurface CHAR (5);
	BEGIN
	  IF pSite    = 0 THEN
		 vSurface := ' ';
	  ELSE
		 SELECT
			CASE pSurface
			  WHEN 0
			  THEN ' '
			  WHEN 1
			  THEN TREATME2_PKG.SURFACE_B_OR_F (pSite)
			  WHEN 2
			  THEN 'D'
			  WHEN 3
			  THEN 'D'
				 || TREATME2_PKG.SURFACE_B_OR_F (pSite)
			  WHEN 4
			  THEN 'L'
			  WHEN 5
			  THEN 'FL'
			  WHEN 6
			  THEN 'DL'
			  WHEN 7
			  THEN 'DBL'
			  WHEN 8
			  THEN 'M'
			  WHEN 9
			  THEN 'M'
				 || TREATME2_PKG.SURFACE_B_OR_F (pSite)
			  WHEN 10
			  THEN 'MD'
			  WHEN 11
			  THEN 'BMD'
			  WHEN 12
			  THEN 'ML'
			  WHEN 13
			  THEN 'ML'
				 || TREATME2_PKG.SURFACE_B_OR_F (pSite)
			  WHEN 14
			  THEN 'MLD'
			  WHEN 15
			  THEN 'MBDL'
			  WHEN 16
			  THEN TREATME2_PKG.SURFACE_O_OR_I (pSite)
			  WHEN 17
			  THEN TREATME2_PKG.SURFACE_B_OR_F (pSite)
				 || TREATME2_PKG.SURFACE_O_OR_I (pSite)
			  WHEN 18
			  THEN 'D'
				 || TREATME2_PKG.SURFACE_O_OR_I (pSite)
			  WHEN 19
			  THEN 'D'
				 || TREATME2_PKG.SURFACE_B_OR_F (pSite)
				 || TREATME2_PKG.SURFACE_O_OR_I (pSite)
			  WHEN 20
			  THEN TREATME2_PKG.SURFACE_O_OR_I (pSite)
				 || 'L'
			  WHEN 21
			  THEN TREATME2_PKG.SURFACE_O_OR_I (pSite)
				 || 'L'
				 || TREATME2_PKG.SURFACE_B_OR_F (pSite)
			  WHEN 22
			  THEN 'DL'
				 || TREATME2_PKG.SURFACE_O_OR_I (pSite)
			  WHEN 23
			  THEN 'DL'
				 || TREATME2_PKG.SURFACE_O_OR_I (pSite)
				 || TREATME2_PKG.SURFACE_B_OR_F (pSite)
			  WHEN 24
			  THEN 'M'
				 || TREATME2_PKG.SURFACE_O_OR_I (pSite)
			  WHEN 25
			  THEN 'M'
				 || TREATME2_PKG.SURFACE_B_OR_F (pSite)
				 || TREATME2_PKG.SURFACE_O_OR_I (pSite)
			  WHEN 26
			  THEN 'MD'
				 || TREATME2_PKG.SURFACE_O_OR_I (pSite)
			  WHEN 27
			  THEN 'MD'
				 || TREATME2_PKG.SURFACE_B_OR_F (pSite)
				 || TREATME2_PKG.SURFACE_O_OR_I (pSite)
			  WHEN 28
			  THEN 'ML'
				 || TREATME2_PKG.SURFACE_O_OR_I (pSite)
			  WHEN 29
			  THEN 'ML'
				 || TREATME2_PKG.SURFACE_B_OR_F (pSite)
				 || TREATME2_PKG.SURFACE_O_OR_I (pSite)
			  WHEN 30
			  THEN 'MLD'
				 || TREATME2_PKG.SURFACE_O_OR_I (pSite)
			  WHEN 31
			  THEN 'MLD'
				 || TREATME2_PKG.SURFACE_O_OR_I (pSite)
				 || TREATME2_PKG.SURFACE_B_OR_F (pSite)
			END
		 INTO vSurface
		 FROM dual;
	  END IF;
	  RETURN vSurface;
	END;
END;
CREATE OR REPLACE PACKAGE BODY trx_pkg IS

  --

  -- fucntion to return if the given Id / Type / Treatment has AP_NOTE records

  -- return 1 if has one or more AP_NOTE; else 0

  --

FUNCTION hasstickynote(notetype numeric, id numeric, treatment numeric) RETURN numeric IS

  Result NUMBER;

BEGIN

  Result := 0;

  BEGIN

    SELECT COUNT(1)

       INTO Result

       FROM AP_NOTE

       WHERE "AP_NOTE_AppId"		= Id

			AND "AP_NOTE_Type"      = NoteType

			AND "AP_NOTE_Treatment" = Treatment

			AND ROWNUM              < 2;

		EXCEPTION

		WHEN NO_DATA_FOUND THEN

			Result := 0;

  END;

  

  IF Result = 0 THEN

    RETURN 0;

  ELSE

    RETURN 1;

  END IF;

END;





--

-- fucntion to return if the given TRX with Id / Treatment has AP_NOTE record

-- return 1 if has AP_NOTE; else 0

--

FUNCTION hastrxstickynote(id numeric, treatment numeric) RETURN numeric IS

BEGIN

  RETURN HasStickyNote(6, Id, Treatment);

END;



/*****************************************************************************/

-- E72760; E00666.7.4b

PROCEDURE initializetrx(INOUT row_trx trx) IS

BEGIN

  row_Trx."Type"                 := 0;

  row_Trx."Id"                   := 0;

  row_Trx."Treatment"            := 0;

  row_Trx."Patient"              := 0;

  row_Trx."Family"               := 0;

  row_Trx."Status"               := ' ';

  row_Trx."EDI"                  := ' ';

  row_Trx."EDIStatus"            := 0;

  row_Trx."Date"                 := TRUNC(SYSDATE);

  row_Trx."SubmitDate"           := NULL;

  row_Trx."ClaimDoctor"          := ' ';

  row_Trx."Submitted"            := 0;

  row_Trx."TreatmentDate"        := NULL;

  row_Trx."CreationDate"         := TRUNC(SYSDATE);

  row_Trx."Procedure"            := ' ';

  row_Trx."Code"                 := ' ';

  row_Trx."Site"                 := ' ';

  row_Trx."Surface"              := ' ';

  row_Trx."Unit"                 := 0;

  row_Trx."Producer"             := ' ';

  row_Trx."Total"                := 0;

  row_Trx."InsTotal"             := 0;

  row_Trx."Company1"             := ' ';

  row_Trx."Policy1"              := ' ';

  row_Trx."Category1"            := ' ';

  row_Trx."Item1"                := 0;

  row_Trx."Deduct1"              := 0;

  row_Trx."Assign1"              := 0;

  row_Trx."Eligible1"            := 0;

  row_Trx."Pct1"                 := 0;

  row_Trx."Amount1"              := 0;

  row_Trx."InsPayed1"            := 0;

  row_Trx."InsAdj1"              := 0;

  row_Trx."Company2"             := ' ';

  row_Trx."Policy2"              := ' ';

  row_Trx."Category2"            := ' ';

  row_Trx."Item2"                := 0;

  row_Trx."Assign2"              := 0;

  row_Trx."Deduct2"              := 0;

  row_Trx."Eligible2"            := 0;

  row_Trx."Pct2"                 := 0;

  row_Trx."Amount2"              := 0;

  row_Trx."InsPayed2"            := 0;

  row_Trx."InsAdj2"              := 0;

  row_Trx."Company3"             := ' ';

  row_Trx."Policy3"              := ' ';

  row_Trx."Category3"            := ' ';

  row_Trx."Item3"                := 0;

  row_Trx."Assign3"              := 0;

  row_Trx."Deduct3"              := 0;

  row_Trx."Eligible3"            := 0;

  row_Trx."Pct3"                 := 0;

  row_Trx."Amount3"              := 0;

  row_Trx."InsPayed3"            := 0;

  row_Trx."InsAdj3"              := 0;

  row_Trx."Description"          := ' ';

  row_Trx."Deleted"              := 0;

  row_Trx."Bank"                 := ' ';

  row_Trx."Payed"                := 0;

  row_Trx."InsPayed"             := 0;

  row_Trx."PtAdj"                := 0;

  row_Trx."InsAdj"               := 0;

  row_Trx."EstimateF"            := 0;

  row_Trx."Additional"           := ' ';

  row_Trx."TxStatus"             := ' ';

  row_Trx."User"                 := 1;

  row_Trx."PtWriteOff"           := 0;

  row_Trx."PolicyId1"            := 0;

  row_Trx."PolicyId2"            := 0;

  row_Trx."PolicyId3"            := 0;

  row_Trx."InsStatus1"           := 0;

  row_Trx."InsStatus2"           := 0;

  row_Trx."InsStatus3"           := 0;

  row_Trx."IsBankDeposit"        := 0;

  row_Trx."ChartTrx"             := 0;

  row_Trx."PlanTotal"            := 0;

  row_Trx."Phase"                := ' ';

  row_Trx."Seq"                  := 0;

  row_Trx."AppUser"              := 0;

  row_Trx."AppDate"              := NULL;

  row_Trx."Grading"              := 0;

  row_Trx."Site2"                := ' ';

  row_Trx."Custom1"              := ' ';

  row_Trx."Custom2"              := ' ';

  row_Trx."PayPlanId"            := 0;

  row_Trx."Discipline"           := ' ';

  row_Trx."DiscountedPmtId"      := 0;

  row_Trx."Location"             := ' ';

  row_Trx."OrigAssign1"          := 0;

  row_Trx."OrigAssign2"          := 0;

  row_Trx."OrigAssign3"          := 0;

  row_Trx."InDispute"            := 0;

  row_Trx."DisputeDate"          := NULL;

  row_Trx."DeletionDate"         := NULL;

  row_Trx."EDIPat"               := ' ';

  row_Trx."EDIPatStatus"         := 0;

  row_Trx."InsTransfer1"         := 0;

  row_Trx."InsTransfer2"         := 0;

  row_Trx."InsTransfer3"         := 0;

  row_Trx."InsTransfer"          := 0;

  row_Trx."InsPmtId"             := 0;

  row_Trx."StationId"            := 1;

  row_Trx."Practice"             := 0;

  row_Trx."Suspended"            := 0;

  row_Trx."DelAppUser"           := 0;

  row_Trx."DelAppDate"           := NULL;

  row_Trx."OrthoStatus"          := 0;

  row_Trx."CvgType"              := 0;

  row_Trx."ModifiedDate"         := SYSDATE;

  row_Trx."OrigClaimDate"        := NULL;

  row_Trx."SubmitMode"           := 0;

  row_Trx."Custom3"              := ' ';

  row_Trx."Custom4"              := ' ';

  row_Trx."CorrespondCode"       := ' ';

  row_Trx."InsCvgType1"          := 0;

  row_Trx."InsCvgType2"          := 0;

  row_Trx."InsCvgType3"          := 0;

  row_Trx."OrigRecNo"            := 0;

  row_Trx."EntryUser"            := 0;

  row_Trx."PlanInProcTotal"      := 0;

  row_Trx."TrxDep"               := 0;

  row_Trx."CustomaryTotal"       := 0;

  row_Trx."TaxRate"              := 0;

  row_Trx."TaxAmount"            := 0;

END InitializeTrx;



/*****************************************************************************/

-- only called by the overnight process to add a missed appointment charge

-- E72760, E104564

PROCEDURE adddefaultmissedapptcharge(INOUT row_trx trx, IN num_clinic numeric, IN char_producer character, IN num_cancelfailtype numeric) IS

  char_ChargeCode	OFCHARGE."OfficeCharge"%TYPE;

  

BEGIN

  BEGIN

    SELECT "ChargeCode" INTO char_ChargeCode FROM CANCEL

      WHERE "Type" = num_CancelFailType AND "Default" = 1 AND "Inactive" = 0;

    EXCEPTION

      WHEN NO_DATA_FOUND THEN

        RETURN;

  END;

 

  AddMissedApptCharge(row_Trx, num_Clinic, char_Producer, num_CancelFailType, char_ChargeCode);



END AddDefaultMissedApptCharge;



/*****************************************************************************/

-- E72760; E00666.7.4b

PROCEDURE inserttrx(IN row_trx trx) IS

BEGIN

   INSERT INTO TRX

    (

      "Type"                ,

      "Id"                  ,

      "Treatment"           ,

      "Patient"             ,

      "Family"              ,

      "Status"              ,

      "EDI"                 ,

      "EDIStatus"           ,

      "Date"                ,

      "SubmitDate"          ,

      "ClaimDoctor"         ,

      "Submitted"           ,

      "TreatmentDate"       ,

      "CreationDate"        ,

      "Procedure"           ,

      "Code"                ,

      "Site"                ,

      "Surface"             ,

      "Unit"                ,

      "Producer"            ,

      "Total"               ,

      "InsTotal"            ,

      "Company1"            ,

      "Policy1"             ,

      "Category1"           ,

      "Item1"               ,

      "Deduct1"             ,

      "Assign1"             ,

      "Eligible1"           ,

      "Pct1"                ,

      "Amount1"             ,

      "InsPayed1"           ,

      "InsAdj1"             ,

      "Company2"            ,

      "Policy2"             ,

      "Category2"           ,

      "Item2"               ,

      "Assign2"             ,

      "Deduct2"             ,

      "Eligible2"           ,

      "Pct2"                ,

      "Amount2"             ,

      "InsPayed2"           ,

      "InsAdj2"             ,

      "Company3"            ,

      "Policy3"             ,

      "Category3"           ,

      "Item3"               ,

      "Assign3"             ,

      "Deduct3"             ,

      "Eligible3"           ,

      "Pct3"                ,

      "Amount3"             ,

      "InsPayed3"           ,

      "InsAdj3"             ,

      "Description"         ,

      "Deleted"             ,

      "Bank"                ,

      "Payed"               ,

      "InsPayed"            ,

      "PtAdj"               ,

      "InsAdj"              ,

      "EstimateF"           ,

      "Additional"          ,

      "TxStatus"            ,

      "User"                ,

      "PtWriteOff"          ,

      "PolicyId1"           ,

      "PolicyId2"           ,

      "PolicyId3"           ,

      "InsStatus1"          ,

      "InsStatus2"          ,

      "InsStatus3"          ,

      "IsBankDeposit"       ,

      "ChartTrx"            ,

      "PlanTotal"           ,

      "Phase"               ,

      "Seq"                 ,

      "AppUser"             ,

      "AppDate"             ,

      "Grading"             ,

      "Site2"               ,

      "Custom1"             ,

      "Custom2"             ,

      "PayPlanId"           ,

      "Discipline"          ,

      "DiscountedPmtId"     ,

      "Location"            ,

      "OrigAssign1"         ,

      "OrigAssign2"         ,

      "OrigAssign3"         ,

      "InDispute"           ,

      "DisputeDate"         ,

      "DeletionDate"        ,

      "EDIPat"              ,

      "EDIPatStatus"        ,

      "InsTransfer1"        ,

      "InsTransfer2"        ,

      "InsTransfer3"        ,

      "InsTransfer"         ,

      "InsPmtId"            ,

      "StationId"           ,

      "Practice"            ,

      "Suspended"           ,

      "DelAppUser"          ,

      "DelAppDate"          ,

      "OrthoStatus"         ,

      "CvgType"             ,

      "ModifiedDate"        ,

      "OrigClaimDate"       ,

      "SubmitMode"          ,

      "Custom3"             ,

      "Custom4"             ,

      "CorrespondCode"      ,

      "InsCvgType1"         ,

      "InsCvgType2"         ,

      "InsCvgType3"         ,

      "OrigRecNo"           ,

      "EntryUser"           ,

      "PlanInProcTotal"     ,

      "TrxDep"              ,

      "CustomaryTotal"      ,

      "TaxRate"             ,

      "TaxAmount"

    )

    VALUES

    (

      row_Trx."Type"                ,

      row_Trx."Id"                  ,

      row_Trx."Treatment"           ,

      row_Trx."Patient"             ,

      row_Trx."Family"              ,

      row_Trx."Status"              ,

      row_Trx."EDI"                 ,

      row_Trx."EDIStatus"           ,

      row_Trx."Date"                ,

      row_Trx."SubmitDate"          ,

      row_Trx."ClaimDoctor"         ,

      row_Trx."Submitted"           ,

      row_Trx."TreatmentDate"       ,

      row_Trx."CreationDate"        ,

      row_Trx."Procedure"           ,

      row_Trx."Code"                ,

      row_Trx."Site"                ,

      row_Trx."Surface"             ,

      row_Trx."Unit"                ,

      row_Trx."Producer"            ,

      row_Trx."Total"               ,

      row_Trx."InsTotal"            ,

      row_Trx."Company1"            ,

      row_Trx."Policy1"             ,

      row_Trx."Category1"           ,

      row_Trx."Item1"               ,

      row_Trx."Deduct1"             ,

      row_Trx."Assign1"             ,

      row_Trx."Eligible1"           ,

      row_Trx."Pct1"                ,

      row_Trx."Amount1"             ,

      row_Trx."InsPayed1"           ,

      row_Trx."InsAdj1"             ,

      row_Trx."Company2"            ,

      row_Trx."Policy2"             ,

      row_Trx."Category2"           ,

      row_Trx."Item2"               ,

      row_Trx."Assign2"             ,

      row_Trx."Deduct2"             ,

      row_Trx."Eligible2"           ,

      row_Trx."Pct2"                ,

      row_Trx."Amount2"             ,

      row_Trx."InsPayed2"           ,

      row_Trx."InsAdj2"             ,

      row_Trx."Company3"            ,

      row_Trx."Policy3"             ,

      row_Trx."Category3"           ,

      row_Trx."Item3"               ,

      row_Trx."Assign3"             ,

      row_Trx."Deduct3"             ,

      row_Trx."Eligible3"           ,

      row_Trx."Pct3"                ,

      row_Trx."Amount3"             ,

      row_Trx."InsPayed3"           ,

      row_Trx."InsAdj3"             ,

      row_Trx."Description"         ,

      row_Trx."Deleted"             ,

      row_Trx."Bank"                ,

      row_Trx."Payed"               ,

      row_Trx."InsPayed"            ,

      row_Trx."PtAdj"               ,

      row_Trx."InsAdj"              ,

      row_Trx."EstimateF"           ,

      row_Trx."Additional"          ,

      row_Trx."TxStatus"            ,

      row_Trx."User"                ,

      row_Trx."PtWriteOff"          ,

      row_Trx."PolicyId1"           ,

      row_Trx."PolicyId2"           ,

      row_Trx."PolicyId3"           ,

      row_Trx."InsStatus1"          ,

      row_Trx."InsStatus2"          ,

      row_Trx."InsStatus3"          ,

      row_Trx."IsBankDeposit"       ,

      row_Trx."ChartTrx"            ,

      row_Trx."PlanTotal"           ,

      row_Trx."Phase"               ,

      row_Trx."Seq"                 ,

      row_Trx."AppUser"             ,

      row_Trx."AppDate"             ,

      row_Trx."Grading"             ,

      row_Trx."Site2"               ,

      row_Trx."Custom1"             ,

      row_Trx."Custom2"             ,

      row_Trx."PayPlanId"           ,

      row_Trx."Discipline"          ,

      row_Trx."DiscountedPmtId"     ,

      row_Trx."Location"            ,

      row_Trx."OrigAssign1"         ,

      row_Trx."OrigAssign2"         ,

      row_Trx."OrigAssign3"         ,

      row_Trx."InDispute"           ,

      row_Trx."DisputeDate"         ,

      row_Trx."DeletionDate"        ,

      row_Trx."EDIPat"              ,

      row_Trx."EDIPatStatus"        ,

      row_Trx."InsTransfer1"        ,

      row_Trx."InsTransfer2"        ,

      row_Trx."InsTransfer3"        ,

      row_Trx."InsTransfer"         ,

      row_Trx."InsPmtId"            ,

      row_Trx."StationId"           ,

      row_Trx."Practice"            ,

      row_Trx."Suspended"           ,

      row_Trx."DelAppUser"          ,

      row_Trx."DelAppDate"          ,

      row_Trx."OrthoStatus"         ,

      row_Trx."CvgType"             ,

      row_Trx."ModifiedDate"        ,

      row_Trx."OrigClaimDate"       ,

      row_Trx."SubmitMode"          ,

      row_Trx."Custom3"             ,

      row_Trx."Custom4"             ,

      row_Trx."CorrespondCode"      ,

      row_Trx."InsCvgType1"         ,

      row_Trx."InsCvgType2"         ,

      row_Trx."InsCvgType3"         ,

      row_Trx."OrigRecNo"           ,

      row_Trx."EntryUser"           ,

      row_Trx."PlanInProcTotal"     ,

      row_Trx."TrxDep"              ,

      row_Trx."CustomaryTotal"      ,

      row_Trx."TaxRate"             ,

      row_Trx."TaxAmount"

      

    );

EXCEPTION

  WHEN OTHERS THEN

    RETURN;

END InsertTrx;



/*****************************************************************************/

-- E72760

PROCEDURE inserthistory(IN row_trx trx) IS

BEGIN

   INSERT INTO history

    (

      SELECT HISTORY_HISTORY_SEQ.nextval,

      1                              ,

      trx.* FROM trx

        WHERE "Id"		 = row_Trx."Id"

			AND "Type"      = row_Trx."Type"

			AND "Treatment" = row_Trx."Treatment"

	 );

END InsertHistory;



/*****************************************************************************/

-- E72760

--B78890 AddNonTaxableOfficeCharge MUST only be called by overnight type procedures 

--that add non-taxable charges only since it cannot chanrge taxes (and not anything that adds goods or serve type office charges)

PROCEDURE addnontaxableofficecharge(INOUT row_trx trx, IN num_clinic numeric, IN char_producer character, IN num_cancelfailtype numeric) IS

BEGIN

  AddDefaultMissedApptCharge(row_Trx, num_Clinic, char_Producer, num_CancelFailType);

  

END AddNonTaxableOfficeCharge;											--B78890



/*****************************************************************************/

-- E72759.3.1, E72759.3.2.1, B81239 

--nOperation = 0 - add visit fee( C++ code rererence VISIT_FEE_ADD_OPERATION)

--nOperation = 1 - check if visit fee needs to be added (C++ code rererence VISIT_FEE_UPDATE_OPERATION)

--nResult = 0 - no visit fee added (if nOperation = 0) or should be added (if nOperation = 1)

--nResult = 1 -  visit fee added (if nOperation = 0) or should be added (if nOperation = 1)  

FUNCTION checkaddvisitfeetotrxandhist(INOUT row_trxvisitfee trx, nvisitfee numeric, noperation numeric, OUT ntotal numeric, OUT nerror numeric) RETURN numeric IS

  nResult NUMBER;

  nReturn NUMBER;

  v_nCount		NUMBER := 0;								-- AX-27968

  v_sqlBlock	VARCHAR2(1000);				                -- AX-27968



BEGIN

  nError	 := 0;

  nResult := 0;

  nReturn := 0;



   --AX-27968

   SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_TRX_PKG' and PROCEDURE_NAME = UPPER('CheckAddVisitFeeToTrxAndHist');

   IF v_nCount > 0 THEN

      -- custom package function exists  

 	  v_sqlBlock := 'begin :1 := CUSTOM_TRX_PKG.CheckAddVisitFeeToTrxAndHist(:2, :3, :4, :5, :6); end;';

	  EXECUTE IMMEDIATE v_sqlBlock 

						USING out nResult, in out row_TrxVisitFee, in nVisitFee, in nOperation, out nTotal, out nError;

      RETURN nResult;

   END IF;





  IF IsNonClinicalTx('OVFEE') = 1 THEN

	  BEGIN

		 SELECT Count (1) INTO nResult FROM TRX T

		 WHERE T."Type" = 1 

			AND T."Patient" = row_TrxVisitFee."Patient"

			AND T."Procedure" = 'OVFEE'

			AND T."TreatmentDate"   =  row_TrxVisitFee."TreatmentDate"

			AND T."Producer"  = row_TrxVisitFee."Producer"

			AND T."Deleted" = 0;

		 EXCEPTION WHEN NO_DATA_FOUND THEN

			nResult := 0;

	  END;

  ELSE

	  BEGIN

		 SELECT Count (1) INTO nResult FROM TRX T

		 WHERE T."Type" = 2 

			AND T."Patient" = row_TrxVisitFee."Patient"

			AND T."Code" = 'OVFEE'

			AND T."TreatmentDate"   =  row_TrxVisitFee."TreatmentDate"

			AND T."Producer"  = row_TrxVisitFee."Producer"

			AND T."Deleted" = 0;

		 EXCEPTION WHEN NO_DATA_FOUND THEN

			nResult := 0;

	  END;

  END IF;

   

  IF nResult = 0 THEN

	  IF nOperation = 0 THEN 

		  row_TrxVisitFee."Total" := nVisitFee;



		  IF IsNonClinicalTx('OVFEE') = 1 THEN

			  -- e.g. WD

				row_TrxVisitFee."Procedure"		:= 'OVFEE';

				row_TrxVisitFee."CustomaryTotal" := nVisitFee;

				

				BEGIN

					SELECT "Description" INTO row_TrxVisitFee."Description" 

						FROM PROCEDUR WHERE "Procedure"= 'OVFEE';

				EXCEPTION

					WHEN NO_DATA_FOUND THEN

					BEGIN

						nError := 7;	-- OVFEE not a procedure zzz

						RETURN 0;

					END;

				END;

			ELSE

				-- e.g. KP

				row_TrxVisitFee."Code" := 'OVFEE';

				

				BEGIN

					SELECT "Description" INTO row_TrxVisitFee."Description" 

						FROM OFCHARGE WHERE "OfficeCharge"= 'OVFEE';

				EXCEPTION

					WHEN NO_DATA_FOUND THEN

					BEGIN

						nError := 8;	-- OVFEE not an office charge  zzz

						RETURN 0;

					END;

				END;

			END IF;

			

			InsertTrx(row_TrxVisitFee);

			InsertHistory(row_TrxVisitFee);

	  END IF;



	  nTotal  := nVisitFee * 100; -- convert dollars to cents

	  nReturn := 1;

  ELSE

     nError := 9; -- OVFEE already exists zzz

  END IF;

  

  RETURN nReturn;	

  

END CheckAddVisitFeeToTrxAndHist;



/*****************************************************************************/

-- E125910 

--nOperation = 0 - add visit fee( C++ code rererence VISIT_FEE_ADD_OPERATION)

--nOperation = 1 - check if visit fee needs to be added (C++ code rererence VISIT_FEE_UPDATE_OPERATION)

--nOperation = 2 - delete operation(C++ code rererence VISIT_FEE_DELETE_OPERATION)

--nResult = 0 - no visit fee added (if nOperation = 0) or should be added (if nOperation = 1) - check nError

--				1 -  visit fee added (if nOperation = 0) or should be added (if nOperation = 1) 

--nError =  1 - no treatment 

--				2 - patient exempt 

--				3 - no policy 

--				4 - dual coverage 

--				5 - patient charged (no benefit) 

--				6 - policies don't charge a visit fee

--				7 - OVFEE not a procedure 

--				8 - OVFEE not an office charge  

--				9 - OVFEE already exists 

--

PROCEDURE addvisitfee(IN nid numeric, IN ntreatment numeric, IN noperation numeric, IN nintotalcents numeric, OUT nresult numeric, OUT nouttotal numeric, OUT nerror numeric) IS

	row_Trx					TRX%ROWTYPE;

	row_TrxVisitFee		TRX%ROWTYPE;

	

	nPatientExempt			NUMBER;

	nInTotal					NUMBER;



	nHasVisitFees1			NUMBER;

	nVisitFee1				NUMBER;

	nHasVisitFees2			NUMBER;

	nVisitFee2				NUMBER;

	nHasVisitFees3			NUMBER;

	nVisitFee3				NUMBER;

	nFamilyDeduct1       NUMBER;

	nFamilyDeduct2       NUMBER;

	nFamilyDeduct3       NUMBER;

	nPatientDeduct1      NUMBER;

	nPatientDeduct2      NUMBER;

	nPatientDeduct3      NUMBER;

	nProcedureCategory   NUMBER;

	nPolIns1             NUMBER;

	nPolIns2             NUMBER;

	nPolIns3             NUMBER;



	v_nCount		NUMBER := 0;						-- AX-27968

	v_sqlBlock		VARCHAR2(1000);                     -- AX-27968





BEGIN

	nResult            := 0; 

	nOutTotal			 := 0;

	nError				 := 0;

	

	nPatientExempt		 := 0;



	nHasVisitFees1     := 0;

	nHasVisitFees2     := 0;

	nHasVisitFees3     := 0;

	nVisitFee1         := 0;

	nVisitFee2         := 0;

	nVisitFee3         := 0;

	nFamilyDeduct1     := 0;

	nFamilyDeduct2     := 0;

	nFamilyDeduct3     := 0;

	nPatientDeduct1    := 0;

	nPatientDeduct2    := 0;

	nPatientDeduct3    := 0;

	nProcedureCategory := 0;

	nPolIns1           := 0;

	nPolIns2           := 0;

	nPolIns3           := 0;



	--AX-27968

   SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_TRX_PKG' and PROCEDURE_NAME = UPPER('AddVisitFee');

   IF v_nCount > 0 THEN

	 -- custom package function exists  

	  v_sqlBlock := 'BEGIN CUSTOM_TRX_PKG.AddVisitFee(:1, :2, :3, :4, :5, :6, :7); END;';

	  EXECUTE IMMEDIATE v_sqlBlock USING in nId, in nTreatment, in nOperation, in nInTotalCents, out nResult, out nOutTotal, out nError;

	  RETURN;

   END IF;



	-- get Trx visit fee is for

	TRX_PKG.InitializeTrx(row_Trx);



	BEGIN

	  SELECT * INTO row_Trx FROM TRX WHERE "Type" = 1 AND "Id" = nId And "Treatment" = nTreatment;

	EXCEPTION

	WHEN NO_DATA_FOUND THEN	

	  nError := 1; -- no treatment zzz

	  RETURN;	

	END;



   --97901 added the condition on Office4														*** Custom ***

   SELECT COUNT (1) INTO nPatientExempt FROM PATIENT P

    WHERE P."Patient" = row_Trx."Patient" AND P."Office4" = 'NO OFF';

   

   IF nPatientExempt > 0 THEN	

     nError := 2; -- patient exempt zzz

     RETURN;	

   END IF;



	-- get policy info

   BEGIN

     SELECT 

      I1."HasVisitFees"		  ,

      P1."VisitFee"          ,

      I2."HasVisitFees"      ,

      P2."VisitFee"          ,

      I3."HasVisitFees"      ,

      P3."VisitFee"          ,

      P1."FamilyDeduct"      ,

      P2."FamilyDeduct"      ,

      P3."FamilyDeduct"      ,

      P1."PatientDeduct"     ,

      P2."PatientDeduct"     ,

      P3."PatientDeduct"     ,

      PR."Category"			  ,

      P1."PolIns"				  ,

      P2."PolIns"				  ,

      P3."PolIns"

     INTO 

      nHasVisitFees1		  ,

      nVisitFee1          ,

      nHasVisitFees2      ,

      nVisitFee2          ,

      nHasVisitFees3      ,

      nVisitFee3          ,

      nFamilyDeduct1      ,

      nFamilyDeduct2      ,

      nFamilyDeduct3      ,

      nPatientDeduct1     ,

      nPatientDeduct2     ,

      nPatientDeduct3     ,

      nProcedureCategory  ,

      nPolIns1				  ,

      nPolIns2				  ,

      nPolIns3

     FROM 

      INSURANC I1		  ,

      POLINS P1        ,

      PTPOL PP1        ,

      INSURANC I2      ,

      POLINS P2        ,

      PTPOL PP2        ,

      INSURANC I3      ,

      POLINS P3        ,

      PTPOL PP3        ,

      PROCEDUR PR		  , 

      TRX T

     WHERE 

          I1."Company"(+)		= T."Company1"

		AND I2."Company"(+)     = T."Company2"

		AND I3."Company"(+)     = T."Company3"

		AND P1."PolIns"(+)      = PP1."PolIns"

		AND PP1."PolicyId"(+)   = T."PolicyId1"

		AND P2."PolIns"(+)      = PP2."PolIns"

		AND PP2."PolicyId"(+)   = T."PolicyId2"

		AND P3."PolIns"(+)      = PP3."PolIns"

		AND PP3."PolicyId"(+)   = T."PolicyId3"

		AND PR."Procedure"(+)   = T."Procedure"

		AND T."Type"				= 1

		AND T."Id"					= row_Trx."Id"

		AND T."Treatment"			= row_Trx."Treatment";

	  EXCEPTION

		 WHEN NO_DATA_FOUND THEN

		 BEGIN

		   nError := 3; -- no policy zzz

		   RETURN;

		 END;

   END;

   

   -- convert nInTotal from cents to dollars

   nInTotal := nInTotalCents / 100;

   

   -- set visit fee info

   TRX_PKG.InitializeTrx(row_TrxVisitFee);

   

   IF IsNonClinicalTx('OVFEE') = 1 THEN													-- E125910

		-- e.g. WD

		row_TrxVisitFee."Type"				:= 1;		

		row_TrxVisitFee."Id"					:= row_Trx."Id";

		SELECT MAX("Treatment") + 1 INTO row_TrxVisitFee."Treatment" 

			FROM TRX	WHERE "Type" = 1 AND "Id" = row_Trx."Id";

		

		row_TrxVisitFee."Status"			:= 'C';

		row_TrxVisitFee."Date"				:= TRUNC(sysdate);				

		row_TrxVisitFee."ClaimDoctor"		:= row_Trx."ClaimDoctor";

		row_TrxVisitFee."Submitted"		:= 0;

		row_TrxVisitFee."CreationDate"	:= TRUNC(sysdate);

		row_TrxVisitFee."InsTotal"			:= 0;

		row_TrxVisitFee."TxStatus"			:= ' ';								

		row_TrxVisitFee."Location"			:= row_TRX."Location";						-- B127693

		row_TrxVisitFee."CvgType"			:= 0;		-- Dental

		row_TrxVisitFee."ChartTrx"			:= 0;

		row_TrxVisitFee."ModifiedDate"	:= sysdate;

		row_TrxVisitFee."OrigClaimDate"	:= row_TRX."OrigClaimDate";				

		row_TrxVisitFee."SubmitMode"		:= 0;		-- Bill Current Policy

		row_TrxVisitFee."AppUser"			:= row_Trx."AppUser";

		row_TrxVisitFee."AppDate"			:= row_Trx."AppDate";

		

		-- set Insurance info

		row_TrxVisitFee."Company1"			:= row_Trx."Company1";

		row_TrxVisitFee."Policy1"			:= row_Trx."Policy1";

		row_TrxVisitFee."PolicyId1"		:= row_Trx."PolicyId1";

		row_TrxVisitFee."Company2"			:= row_Trx."Company2";

		row_TrxVisitFee."Policy2"			:= row_Trx."Policy2";

		row_TrxVisitFee."PolicyId2"		:= row_Trx."PolicyId2";

		row_TrxVisitFee."Company3"			:= row_Trx."Company3";

		row_TrxVisitFee."Policy3"			:= row_Trx."Policy3";

		row_TrxVisitFee."PolicyId3"		:= row_Trx."PolicyId3";



   ELSE

		-- e.g. KP

		row_TrxVisitFee."Type"				:= 2;

		SELECT TRX_ID_OFFICECHARGES_SEQ.NEXTVAL INTO row_TrxVisitFee."Id" FROM dual;	-- E72767 fixed sequence

		row_TrxVisitFee."Treatment"		:= 1;

   

		row_TrxVisitFee."Custom1"			:= row_Trx."Custom1";

		row_TrxVisitFee."Custom2"			:= row_Trx."Custom2";

   END IF;



	row_TrxVisitFee."Patient"				:= row_Trx."Patient";

	row_TrxVisitFee."Family"				:= row_Trx."Family";

	row_TrxVisitFee."TreatmentDate"		:= row_Trx."TreatmentDate";

	row_TrxVisitFee."Producer"				:= row_Trx."Producer";

	row_TrxVisitFee."Discipline"			:= row_Trx."Discipline";

	row_TrxVisitFee."Practice"				:= row_Trx."Practice";

	row_TrxVisitFee."User"					:= row_Trx."User";

	row_TrxVisitFee."StationId"			:= row_Trx."StationId";

	row_TrxVisitFee."EntryUser"			:= row_Trx."EntryUser";

   

   SELECT TRX_ORIGRECNO_SEQ.NEXTVAL INTO row_TrxVisitFee."OrigRecNo" FROM dual;		--B84706

	

	-- get default fee

	IF nInTotal = 0 THEN

		nVisitFee1 := TRX_PKG.GET_VISIT_FEE(nVisitFee1, nPolIns1, row_Trx."Producer");

		nVisitFee2 := TRX_PKG.GET_VISIT_FEE(nVisitFee2, nPolIns2, row_Trx."Producer");

		nVisitFee3 := TRX_PKG.GET_VISIT_FEE(nVisitFee3, nPolIns3, row_Trx."Producer");

	ELSE

		nVisitFee1 := nInTotal;

		nVisitFee2 := nInTotal;

		nVisitFee3 := nInTotal;

	END IF;



	IF (row_Trx."Amount1" > 0 OR row_Trx."Total" = 0)				-- *** Custom ***

	  AND nHasVisitFees1 = 1 AND nVisitFee1 > 0																-- E92778

	THEN

     IF TRX_PKG.CHECKPARENTINSURANCE(row_Trx."Id", row_Trx."Company1", row_Trx."Company2", row_Trx."Company3") = 0 THEN

       IF nOperation = 2 THEN																						--B81315

         nResult := 1;

       ELSE

         nResult := TRX_PKG.CheckAddVisitFeeToTrxAndHist(row_TrxVisitFee, nVisitFee1, nOperation, nOutTotal, nError);

       END IF;

     ELSE

       nError := 4; -- dual coverage zzz

     END IF;

   ELSE IF (row_Trx."Amount2" > 0 OR row_Trx."Total" = 0)		-- *** Custom ***

     AND nHasVisitFees2 = 1 AND nVisitFee2 > 0																-- E92778

   THEN

     IF TRX_PKG.CHECKPARENTINSURANCE(row_Trx."Id", row_Trx."Company2", row_Trx."Company1", row_Trx."Company3") = 0 THEN

       IF nOperation = 2 THEN																						--B81315

         nResult := 1;

       ELSE

         nResult := TRX_PKG.CheckAddVisitFeeToTrxAndHist(row_TrxVisitFee, nVisitFee2, nOperation, nOutTotal, nError);

       END IF;

     ELSE

       nError := 4; -- dual coverage zzz

     END IF;

   ELSE IF (row_Trx."Amount3" > 0 OR row_Trx."Total" = 0)		-- *** Custom ***

     AND nHasVisitFees3 = 1 AND nVisitFee3 > 0																-- E92778

	THEN

     IF TRX_PKG.CHECKPARENTINSURANCE(row_Trx."Id", row_Trx."Company3", row_Trx."Company1", row_Trx."Company2") = 0 THEN

       IF nOperation = 2 THEN                                                    --B81315

         nResult := 1;

       ELSE

         nResult := TRX_PKG.CheckAddVisitFeeToTrxAndHist(row_TrxVisitFee, nVisitFee3, nOperation, nOutTotal, nError);

       END IF;

     ELSE

       nError := 4; -- dual coverage zzz

     END IF;

   ELSE

	  IF row_Trx."Amount1" = 0 AND row_Trx."Total" <> 0 THEN

		 nError := 5; -- patient charged (no benefit) zzz

	  ELSE

	    nError := 6; -- policies don't charge a visit fee

	  END IF;

   END IF;

 END IF;

END IF;



END AddVisitFee;



/*****************************************************************************/

-- E72759.3.1, B81076

-- see description of AddVisitFee

PROCEDURE processvisitfee(IN nid numeric, IN ntreatment numeric, IN noperation numeric, OUT nresult numeric) IS

	nInTotal		NUMBER;

	nOutTotal	NUMBER;

	nError		NUMBER;

	nApptExist  NUMBER;

	nCount		NUMBER;



	v_nCount		NUMBER := 0;						-- AX-27968

	v_sqlBlock		VARCHAR2(1000);                     -- AX-27968







BEGIN

	nResult     := 0; 

	nInTotal		:= 0;

	nOutTotal	:= 0;

	nError		:= 0;

	nApptExist  := 0;

	nCount		:= 0;



	--AX-27968

   SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_TRX_PKG' and PROCEDURE_NAME = UPPER('ProcessVisitFee');

   IF v_nCount > 0 THEN

	 -- custom package function exists  

	  v_sqlBlock := 'BEGIN CUSTOM_TRX_PKG.ProcessVisitFee(:1, :2, :3, :4); END;';

	  EXECUTE IMMEDIATE v_sqlBlock USING in nId, in nTreatment, in nOperation, out nResult;

	  RETURN;

   END IF;





	-- checks only done if called from overnight package

   SELECT COUNT (1) INTO nApptExist FROM APPOINT A, TRX T

    WHERE T."Type" = 1 AND T."Id" = nId And T."Treatment" = nTreatment

		AND A."Patient"   = T."Patient"

		AND A."Type"		IN (0, 1, 2)

		AND A."Date"      = T."TreatmentDate"

		AND A."Producer"  = T."Producer";



   IF nApptExist = 0 THEN	

     RETURN;	-- no appt to miss

   END IF;



  IF IsNonClinicalTx('OVFEE') = 1 THEN

	  BEGIN

		 SELECT Count (1) INTO nCount FROM TRX T1, TRX T2

		 WHERE T1."Type" = 1 AND T1."Id" = nId And T1."Treatment" = nTreatment

		   AND T2."Type" = 1 

			AND T2."Patient" = T1."Patient"

			AND T2."Procedure" = 'OVFEE'

			AND T2."TreatmentDate"   =  T1."TreatmentDate"

			AND T2."Producer"  = T1."Producer";

		 EXCEPTION WHEN NO_DATA_FOUND THEN

			nCount := 0;

	  END;

  ELSE

	  BEGIN

		 SELECT Count (1) INTO nCount FROM TRX T1, TRX T2

		 WHERE T1."Type" = 1 AND T1."Id" = nId And T1."Treatment" = nTreatment

		   AND T2."Type" = 2 

			AND T2."Patient" = T1."Patient"

			AND T2."Code" = 'OVFEE'

			AND T2."TreatmentDate"   =  T1."TreatmentDate"

			AND T2."Producer"  = T1."Producer";

		 EXCEPTION WHEN NO_DATA_FOUND THEN

			nCount := 0;

	  END;

  END IF;

   

  IF nCount = 0 THEN

	  AddVisitFee(nId, nTreatment, nOperation, nInTotal, nResult, nOutTotal, nError); 

  END IF;



END ProcessVisitFee;





/*****************************************************************************/

-- E72759.3, B92853

-- waive OVFEE if patient has dual coverage (patient has coverage under Company1)

-- check if patient has dual coverage (i.e. Company2/3 has same parent as Company1)

FUNCTION checkparentinsurance(nid numeric, company1 character, company2 character, company3 character) RETURN numeric IS

    nResult NUMBER;



	v_nCount		NUMBER := 0;						-- AX-27968

	v_sqlBlock		VARCHAR2(1000);                     -- AX-27968



  BEGIN

	 nResult := 0;



	--AX-27968

	SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_TRX_PKG' and PROCEDURE_NAME = UPPER('CHECKPARENTINSURANCE');

	IF v_nCount > 0 THEN

		-- custom package function exists 

		EXECUTE IMMEDIATE 'SELECT CUSTOM_TRX_PKG.CHECKPARENTINSURANCE(:1, :2, :3, :4) FROM DUAL' INTO nResult

					USING nId, Company1, Company2, Company3;

		RETURN nResult;

	END IF;





	SELECT COUNT(1) INTO nResult FROM INSGROUP I

		WHERE ( ( (SELECT "ParentCompany" FROM INSGROUP WHERE "Company" = Company1) 

						= (SELECT "ParentCompany" FROM INSGROUP WHERE "Company" = Company2) )

				OR ( (SELECT "ParentCompany" FROM INSGROUP WHERE "Company" = Company1) 

						= (SELECT "ParentCompany" FROM INSGROUP WHERE "Company" = Company3) ) )

	     AND rownum < 2;

	

	 RETURN nResult;

  END CHECKPARENTINSURANCE;

  

/*****************************************************************************/

-- E72759.3

FUNCTION get_visit_fee(nvisitfee numeric, npolins numeric, szproducer character) RETURN numeric IS

  nResult NUMBER;



BEGIN

  nResult := 0;

	

  BEGIN

    SELECT NVL(v."VisitFee", nVisitFee) into nResult

    FROM visitfee v,  PRODUCER D 

    WHERE v."PolIns"(+)  =  nPolIns

		AND D."Producer" = szProducer

		AND v."ProdType"(+) = D."TypeCode";

	 EXCEPTION WHEN NO_DATA_FOUND THEN

		nResult := nVisitFee;

  END;

  

  RETURN nResult;	

END GET_VISIT_FEE;



/*****************************************************************************/

-- B81315

--nOperation - 2 delete operation (C++ code rererence VISIT_FEE_DELETE_OPERATION)

--nResult = 0 - visit fee doesn't exist

--nResult = 2 -  visit fee exists 

PROCEDURE checktodeletevisitfee(IN nid numeric, IN ntreatment numeric, IN noperation numeric, OUT nresult numeric) IS

  nCurrentResult			NUMBER;

  row_Trx					TRX%ROWTYPE;

  nOtherTrxNotExist		NUMBER;

  nNoFeeToDeleteExists	NUMBER;

  

  cursor c1 is

     SELECT T2.* FROM TRX T1, TRX T2

	  WHERE  T1."Type"				= 1

		  AND T1."Id"					= nId

		  AND T1."Treatment"			= nTreatment

		  AND T1."Patient"			= T2."Patient" 

		  AND T1."Producer"			= T2."Producer"

		  AND T1."TreatmentDate"	= T2."TreatmentDate"

		  AND (T1."Id" <> T2."Id" 

		       OR (T2."Type" = T1."Type" AND T1."Id" = T2."Id" AND T1."Treatment" <> T2."Treatment" )) 

		  AND (T2."Amount1" > 0 OR T2."Amount2" > 0 OR T2."Amount3" > 0 OR T2."Total" = 0)		-- E92778

		  AND T2."Type" = 1 AND T2."Deleted" = 0 

		  AND (T2."Status" = 'C' OR T2."Status" = 'I')

		  AND T2."OrthoStatus" = 0 ;

    

BEGIN

  nResult					:= 0;

  nOtherTrxNotExist		:= 0;

  nCurrentResult			:= 0;

  nNoFeeToDeleteExists	:= 0;



  FOR rec in c1

  LOOP

    row_Trx := rec;

    TRX_PKG.ProcessVisitFee(row_Trx."Id", nTreatment, nOperation,  nOtherTrxNotExist);

    

    EXIT WHEN  nOtherTrxNotExist = 1;

  END LOOP;



  IF nOtherTrxNotExist = 0 THEN

    BEGIN

      -- B96306: fix multiple rows returned scenario

      IF IsNonClinicalTx('OVFEE') = 1 THEN

			BEGIN

				SELECT T2.* into row_Trx FROM TRX T1, TRX T2

				WHERE T1."Type" = 1 

				  AND T1."Id"   = nId

				  AND T1."Treatment" = nTreatment

				  AND T1."Producer" = T2."Producer"

				  AND T1."Patient"  = T2."Patient" 

				  AND T1."TreatmentDate"  = T2."TreatmentDate" 

				  AND T2."Type" = 1

				  AND T2."Procedure" = 'OVFEE'

				  AND T2."Total" > 0

				  AND ROWNUM < 2; 

				EXCEPTION

				  WHEN NO_DATA_FOUND THEN

					 nNoFeeToDeleteExists   := 1;

			END;

      ELSE

			BEGIN

				SELECT T2.* into row_Trx FROM TRX T1, TRX T2

				WHERE T1."Type" = 1 

				  AND T1."Id"   = nId

				  AND T1."Treatment" = nTreatment

				  AND T1."Producer" = T2."Producer"

				  AND T1."Patient"  = T2."Patient" 

				  AND T1."TreatmentDate"  = T2."TreatmentDate" 

				  AND T2."Type" = 2

				  AND T2."Code" = 'OVFEE'

				  AND T2."Total" > 0

				  AND ROWNUM < 2; 

				EXCEPTION

				  WHEN NO_DATA_FOUND THEN

					 nNoFeeToDeleteExists   := 1;

			END;

      END IF;

    END;



    IF nNoFeeToDeleteExists = 0 THEN

      nResult := 2;

    END IF;



  END IF;



END CheckToDeleteVisitFee;



/*****************************************************************************/

-- Returns	1 if Procedure is a non-clinical treatment code

--				0 otherwise

--

FUNCTION isnonclinicaltx(code character) RETURN numeric IS

  Result NUMBER;

	v_nCount		NUMBER := 0;								-- AX-26071



BEGIN

	

	--AX-26071; AX-32573

	IF v_HasCustomIsNonClinicalTx = -1 THEN

		SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_TRX_PKG' and PROCEDURE_NAME = UPPER('IsNonClinicalTx');

		IF v_nCount > 0 THEN

			v_HasCustomIsNonClinicalTx := 1;

		ELSE

			v_HasCustomIsNonClinicalTx := 0;

		END IF;

	END IF;



	IF v_HasCustomIsNonClinicalTx = 1 THEN

     -- custom package function exists  

     EXECUTE IMMEDIATE 'SELECT CUSTOM_TRX_PKG.IsNonClinicalTx('''||Code||''') FROM DUAL' INTO Result;

     RETURN Result;

   END IF;



   Result := 0;						-- *** Custom ***

    

   RETURN Result;

END;

  

/*****************************************************************************/  

-- returns a ';' delimited list of non-clinical procedure codes

FUNCTION getnonclinicaltx() RETURN character varying IS

	v_nCount		NUMBER := 0;								-- AX-26071

	v_Procedures  VARCHAR2(4000) := ' ';			-- AX-26071

BEGIN



	--AX-26071

   SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_TRX_PKG' and PROCEDURE_NAME = UPPER('GetNonClinicalTx');

   IF v_nCount > 0 THEN

     -- custom package function exists 

     EXECUTE IMMEDIATE 'SELECT CUSTOM_TRX_PKG.GetNonClinicalTx FROM DUAL' INTO v_Procedures;

     RETURN v_Procedures;

   END IF;



   RETURN ' ';						-- *** Custom ***

END;  

  

/*****************************************************************************/  

-- determines how Procedure should be handled by claim processing for insurance 

--	company InsCo

-- Returns	0 if Procedure should be excluded from claim

--				1 if Procedure should show as a line on the claim

--				2 if Procedure should not appear as a line but the amount should be 

--				  consolidated on another treatment line

--

FUNCTION shouldaddproctoclaim(insco character, code character) RETURN numeric IS

  Result				NUMBER;

  ParentCompany	INSGROUP."ParentCompany"%TYPE;

	v_nCount		NUMBER := 0;								-- AX-26071

  

BEGIN



	--AX-26071

   SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_TRX_PKG' and PROCEDURE_NAME = UPPER('ShouldAddProcToClaim');

   IF v_nCount > 0 THEN

     -- custom package function exists  

     EXECUTE IMMEDIATE 'SELECT CUSTOM_TRX_PKG.ShouldAddProcToClaim('''||InsCo||''', '''||Code||''') FROM DUAL' INTO Result;

     RETURN Result;

   END IF;





  Result := 1;

  

  RETURN Result;

END;





/*****************************************************************************/

-- returns default ClaimDoctor for clinic

-- called when adding a missed appt charge

FUNCTION getdefaultclaimdoctor(num_clinic numeric) RETURN character varying IS

	v_nCount		NUMBER := 0;								-- AX-26071

	v_ClaimDr	 VARCHAR2(4000) := ' ';			-- AX-26071

BEGIN



	--AX-26071

   SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_TRX_PKG' and PROCEDURE_NAME = UPPER('GetDefaultClaimDoctor');

   IF v_nCount > 0 THEN

     -- custom package function exists  

     EXECUTE IMMEDIATE 'SELECT CUSTOM_TRX_PKG.GetDefaultClaimDoctor('||num_Clinic||') FROM DUAL' INTO v_ClaimDr;

     RETURN v_ClaimDr;

   END IF;



  RETURN ' ';							-- *** Custom ***

END;  

  



-- E130137.E5

FUNCTION getdiagdesc(charttrx numeric) RETURN character varying IS



  vResult  VARCHAR2(64);

  

  vCount NUMBER(5);

  

  cursor c1 is 

    select D."Description" from DIAGCODE D, TXDIAG TD 

      WHERE TD."DiagCode" = D."DiagCode" AND TD."ChartTrx" = ChartTrx order by D."Description";



BEGIN

  vResult := ' ';

  vCount := 0;

  

  FOR rec in c1

  LOOP

    IF (vCount > 0) THEN

      vResult := '+ ' || vResult; -- E130137.E5.2, E136780

      EXIT;

    END IF;

    

    vResult := rec."Description";

    vCount := vCount + 1;  

  END LOOP;

  

  RETURN vResult;



END;

  

/*****************************************************************************/

-- puts patient's primary, secondary and tertiary dental coverage into passed in TRX

-- called when adding a missed appt charge

-- B125611 - additional order by clauses to guarantee consistent order throughout program

PROCEDURE adddefaultpolicies(INOUT row_trx trx) IS

	num_Count		NUMBER;

	IsCovered		BOOLEAN;													--E142886.8

	--E142886.8 added patient / dependent fields for coverage checkd 

	--			changed the age checks to be >= rather than > to account for the new CvgOnBirth rule

	cursor c1 is

		SELECT O.*, D."Relation", P."Birth",

		P."IsStudent", TRUNC(NVL(MONTHS_BETWEEN(SYSDATE, P."Birth")/12, 0)) as "Age"  

		FROM  PATIENT P, PTDEPEND D, POLICY O, PATIENT H, INSURANC I, BILLING B, EMPLOYER E 

		WHERE P."Patient" = row_Trx."Patient" AND D."Patient" = P."Patient" 

		  AND D."Deleted" = 0 AND D."IsCovered" = 1 

		  AND O."PolicyId" = D."PolicyId" AND O."StartDate" <= sysdate 

		  AND (O."Deleted" = 0 OR O."Date" IS NULL OR O."Date" > sysdate) 

		  AND (O."StartDate" is null OR O."StartDate" <= sysdate)

		  AND (O."ResetDate" is null OR O."ResetDate" >= sysdate)

		  AND (D."StartDate" is null OR D."StartDate" <= sysdate)

		  AND (D."EndDate" is null OR D."EndDate" >= sysdate)

		  AND (D."Relation" <> 3 OR P."IsHandicaped" <> 0 OR P."Birth" is null 

				 OR (O."CoverageAge" <> 0 AND O."CoverageAge" >= TRUNC(MONTHS_BETWEEN(SYSDATE, P."Birth")/12)) 

				 OR (O."CoverageAgeStud" <> 0 AND P."IsStudent" <> 0 

						AND O."CoverageAgeStud" >= TRUNC(MONTHS_BETWEEN(SYSDATE, P."Birth")/12))

				 OR (O."CoverageAgeYoungAdult" <> 0 AND O."CoverageAgeYoungAdult" >= TRUNC(MONTHS_BETWEEN(SYSDATE, P."Birth")/12)))

		  AND H."Patient" = O."Patient" 

		  AND I."Company" (+)= O."Company" 

		  AND E."Employer" (+)= O."Employer" AND E."Deleted" (+) = 0 

		  AND B."Company" (+)= O."Company" AND B."Producer" (+)= ' ' 

		ORDER BY LEAST(D."BillOrder", 1) DESC, D."BillOrder", D."Relation", 

			TO_CHAR (H."Birth", 'MM'), TO_CHAR (H."Birth", 'DD'), 

			(select t."Primary" from ptemploy t where t."Patient" = O."Patient" 

			 and t."Employer" = O."Employer") DESC,

			 O."Company", O."Group", O."Division", O."Policy", O."PolicyId";



	v_nCount		NUMBER := 0;								-- AX-27968

	v_sqlBlock		VARCHAR2(1000);				                -- AX-27968



BEGIN

	num_Count := 0;



	--AX-27968

	SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_TRX_PKG' and PROCEDURE_NAME = UPPER('AddDefaultPolicies');

	IF v_nCount > 0 THEN

		-- custom package function exists  

		v_sqlBlock := 'BEGIN CUSTOM_TRX_PKG.AddDefaultPolicies(:1); END;';

		EXECUTE IMMEDIATE v_sqlBlock USING in out row_Trx;

		RETURN;

	END IF;



	

	FOR rec in c1

	LOOP

		-- determine which coverage template to use (child vs. adult); E142886.8 rewrote

		IsCovered := false;

		IF rec."Age" = 0 THEN

				IsCovered := true;

		ELSIF (IsCvgOnBirth(rec."Age", rec."Birth", rec."CoverageAge", rec."CvgOnBirthChild") OR

					(rec."IsStudent" = 1 AND 

					IsCvgOnBirth(rec."Age", rec."Birth", rec."CoverageAgeStud", rec."CvgOnBirthStudent"))) THEN

				IsCovered := true;

		ELSIF (rec."Relation" = 3 AND IsCvgOnBirth(rec."Age", rec."Birth", rec."CoverageAgeYoungAdult", rec."CvgOnBirthYoungAdult")) THEN

				IsCovered := true;

		ELSE

				IsCovered := true;

		END IF;

	

		IF IsCovered = true AND ShouldAddProcToClaim(rec."Company", row_Trx."Procedure") <> 0 THEN

			IF num_Count = 0 THEN

				row_Trx."PolicyId1"	:= rec."PolicyId";

				row_Trx."Policy1"		:= rec."Policy";

				row_Trx."Company1"	:= rec."Company";

			END IF;



			IF num_Count = 1 THEN

				row_Trx."PolicyId2"	:= rec."PolicyId";

				row_Trx."Policy2"		:= rec."Policy";

				row_Trx."Company2"	:= rec."Company";

			END IF;



			IF num_Count = 2 THEN

				row_Trx."PolicyId3"	:= rec."PolicyId";

				row_Trx."Policy3"		:= rec."Policy";

				row_Trx."Company3"	:= rec."Company";

			END IF;



		num_Count := num_Count + 1;

	 END IF;

	 

	 EXIT WHEN num_Count = 3;

	END LOOP;



END AddDefaultPolicies;

  



FUNCTION iscvgonbirth(age numeric, birthdate timestamp without time zone, coverageage numeric, cvgonbirth numeric) RETURN boolean IS

 BEGIN

 

	IF  CoverageAge = 0 THEN

		RETURN false;

	END IF;

	

	IF  Age < CoverageAge  THEN

		RETURN true;

	ELSIF Age = CoverageAge THEN

		IF CvgOnBirth = 2 THEN

			IF (TO_NUMBER(TO_CHAR(BirthDate, 'YYYY'))+CoverageAge) = TO_NUMBER(TO_CHAR(sysdate, 'YYYY')) THEN

				RETURN true;

			END IF;

		ELSIF CvgOnBirth = 1 THEN

			IF TO_NUMBER(TO_CHAR(BirthDate, 'MM')) = TO_NUMBER(TO_CHAR(sysdate, 'MM')) THEN

				RETURN true;

			END IF;

		END IF;	

	END IF;	

	

	RETURN false;

	

 END IsCvgOnBirth;

 

  

/*****************************************************************************/

-- called by AddMissedApptCharge and by Add Non-Clinical Treatment dialog

-- returns the minimum Patient Charge amount for Code in all patient policies 

-- Note: this could be zero

-- Note: this routine assumes age-specific coverage and policy riders are not being used to determine non-clinical fees!

-- -1 returned if no coverage found  

FUNCTION getnonclinicaltotal(patient numeric, code character) RETURN numeric IS

	vTotal	NUMBER;

	vCoverageId COVERAGE."Coverage"%TYPE;

	vItemPtChg COVERIT."ItemPtChg"%TYPE;



	-- cursor to get all effective patient policies; E142886.8 added young adult coverages / CvgOnBirth fields

	--			changed the age checks to be >= rather than > to account for the new CvgOnBirth rule

	cursor c1 is

		SELECT O."ChildCoverage", O."AdultCoverage", O."YoungAdultCoverage", 

		O."CoverageAge", O."CoverageAgeStud", O."CoverageAgeYoungAdult", 

		O."CvgOnBirthChild", O."CvgOnBirthStudent", O."CvgOnBirthYoungAdult", 

		D."Relation", P."Birth",

		P."IsStudent", TRUNC(NVL(MONTHS_BETWEEN(SYSDATE, P."Birth")/12, 0)) as "Age"

		FROM  PATIENT P, PTDEPEND D, POLICY O, BILLING B, EMPLOYER E 

		WHERE P."Patient" = Patient AND D."Patient" = P."Patient" 

		  AND D."Deleted" = 0 AND D."IsCovered" = 1 

		  AND O."PolicyId" = D."PolicyId" AND O."StartDate" <= sysdate 

		  AND (O."Deleted" = 0 OR O."Date" IS NULL OR O."Date" > sysdate) 

		  AND (O."StartDate" is null OR O."StartDate" <= sysdate)

		  AND (O."ResetDate" is null OR O."ResetDate" >= sysdate)

		  AND (D."StartDate" is null OR D."StartDate" <= sysdate)

		  AND (D."EndDate" is null OR D."EndDate" >= sysdate)

		  AND (D."Relation" <> 3 OR P."IsHandicaped" <> 0 OR P."Birth" is null 

				 OR (O."CoverageAge" <> 0 AND O."CoverageAge" >= TRUNC(MONTHS_BETWEEN(SYSDATE, P."Birth")/12)) 

				 OR (O."CoverageAgeStud" <> 0 AND P."IsStudent" <> 0 

						AND O."CoverageAgeStud" >= TRUNC(MONTHS_BETWEEN(SYSDATE, P."Birth")/12))

				 OR (O."CoverageAgeYoungAdult" <> 0 AND O."CoverageAgeYoungAdult" >= TRUNC(MONTHS_BETWEEN(SYSDATE, P."Birth")/12)))

		  AND E."Employer" (+)= O."Employer" AND E."Deleted" (+) = 0 

		  AND B."Company" (+)= O."Company" AND B."Producer" (+)= ' ';



BEGIN

	vTotal := -1;

	

	IF IsNonClinicalTx(Code) = 1 THEN



		-- loop through effective policies to set Total to minimum Patient Charge 

		FOR rec in c1

		LOOP

			

			-- determine which coverage template to use (child vs. adult); E142886.8 rewrote

			vCoverageId := 0;

			IF rec."ChildCoverage" = rec."AdultCoverage" AND 

					(rec."YoungAdultCoverage" = 0 OR rec."ChildCoverage" = rec."YoungAdultCoverage") THEN

				vCoverageId := rec."ChildCoverage";

			ELSIF rec."Age" = 0 THEN

				vCoverageId := rec."AdultCoverage";

			ELSIF (IsCvgOnBirth(rec."Age", rec."Birth", rec."CoverageAge", rec."CvgOnBirthChild") OR

					(rec."IsStudent" = 1 AND 

					IsCvgOnBirth(rec."Age", rec."Birth", rec."CoverageAgeStud", rec."CvgOnBirthStudent"))) THEN

				vCoverageId := rec."ChildCoverage";

			ELSIF (rec."Relation" = 3 AND IsCvgOnBirth(rec."Age", rec."Birth", rec."CoverageAgeYoungAdult", rec."CvgOnBirthYoungAdult")) THEN

				vCoverageId := rec."YoungAdultCoverage";

			ELSIF rec."Relation" <> 3 THEN		-- CHILD should already be taken care in above clauses

				vCoverageId := rec."AdultCoverage";				

			END IF;

			

			

			-- if we've found a valid coverage template, see if there is a line for this fee

			-- Note: this routine assumes age-specific coverage and policy riders are not being used to determine non-clinical fees!

			IF vCoverageId > 0 THEN



				begin				

					select "ItemPtChg" into vItemPtChg from COVERIT

						where "Coverage" = vCoverageId

						and Code between "FromProcedure" and "ToProcedure";

				exception when NO_DATA_FOUND then

					vItemPtChg := -1;

				end;

				

				-- if a charge is found that is lower than total, then use it

				IF vItemPtChg > -1 AND (vTotal = -1 OR vItemPtChg < vTotal) THEN

					vTotal := vItemPtChg;

				END IF;

				

			END IF;

		

		END LOOP;

		

	END IF;



	RETURN vTotal;

END;

  

  

/*****************************************************************************/

-- called by AddMissedApptCharge and from Transactions

-- NOTE: Total is in cents (not dollars) due to db layer restriction when called from Transactions

--nError =  1 - invalid Patient 

--				2 - invalid Practice 

--				3 - invalid Date 

--				4 - invalid Producer 

--				5 - invalid Code 

--				6 - invalid Description 

--				7 - invalid User

--				8 - invalid EntryUser 

--				9 - invalid StationId 

--			  10 - invalid ClaimDoctor 

PROCEDURE addcharge(IN patient numeric, IN practice numeric, IN claimdoctor character, IN dtmonth numeric, IN dtday numeric, IN dtyear numeric, IN producer character, IN code character, IN description character varying, IN totalcents numeric, IN discipline character, IN custom1 character, IN custom2 character, IN userid numeric, IN entryuser numeric, IN stationid numeric, OUT nerror numeric) IS

	row_Trx  TRX%ROWTYPE;

	Total		NUMBER;



	v_nCount		NUMBER := 0;								-- AX-27968

	v_sqlBlock		VARCHAR2(1000);				                -- AX-27968



BEGIN

	nError	 := 0;

	

	--AX-27968

	SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_TRX_PKG' and PROCEDURE_NAME = UPPER('AddCharge');

	IF v_nCount > 0 THEN

		-- custom package function exists  

		v_sqlBlock := 'BEGIN CUSTOM_TRX_PKG.AddCharge(:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17); END;';

		EXECUTE IMMEDIATE v_sqlBlock USING in Patient, in Practice, in ClaimDoctor, in dtMonth, in dtDay, in dtYear, in Producer, in Code,

							in Description, in TotalCents, in Discipline, in Custom1, in Custom2, in UserID, in EntryUser, in StationId, out nError;

		RETURN;

	END IF;





	-- validate fields have been set

	IF Patient < 1 THEN

		nError := 1;

		RETURN;

	END IF;

	

	IF Practice < 1 THEN

		nError := 2;

		RETURN;

	END IF;

	

	--IF TreatmentDate IS NULL THEN

	IF dtMonth < 1 OR dtMonth > 12 OR dtDay < 1 OR dtDay > 31 

		OR dtYear < 1901 OR dtYear > TO_NUMBER(TO_CHAR(sysdate, 'YYYY'))

	THEN

		nError := 3;

		RETURN;

	END IF;

	

	IF Producer = '' OR Producer = ' ' OR Producer IS NULL THEN

		nError := 4;

		RETURN;

	END IF;

	

	IF Code = '' OR Code = ' ' OR Code IS NULL THEN

		nError := 5;

		RETURN;

	END IF;

	

	IF Description = '' OR Description = ' ' OR Description IS NULL THEN

		nError := 6;

		RETURN;

	END IF;

	

	IF UserID < 0 THEN

		nError := 7;

		RETURN;

	END IF;

	

	IF EntryUser < 0 THEN

		nError := 8;

		RETURN;

	END IF;

	

	IF StationId < 0 THEN

		nError := 9;

		RETURN;

	END IF;

	

	-- convert Total from cents to dollars

	Total := TotalCents/100;



	--

	TRX_PKG.InitializeTrx(row_Trx);

	

	row_Trx."Patient"			:= Patient;

	row_Trx."Family"			:= Patient;

	row_Trx."Practice"		:= Practice;

	row_Trx."ClaimDoctor"	:= ClaimDoctor;

	--row_Trx."TreatmentDate"	:= TreatmentDate;

	row_Trx."TreatmentDate"	:= TO_DATE(TO_CHAR(dtMonth) || '-' || TO_CHAR(dtDay)

												  || '-' || TO_CHAR(dtYear), 'MM-DD-YYYY');

	row_Trx."Producer"		:= Producer;

	row_Trx."Code"				:= Code;

	row_Trx."Description"	:= Description;

	row_Trx."Total"			:= Total;

	row_Trx."Discipline"		:= Discipline;

	row_Trx."Custom1"			:= Custom1;

	row_Trx."Custom2"			:= Custom2;

	row_Trx."User"				:= UserID;

	row_Trx."EntryUser"		:= EntryUser;

	row_Trx."StationId"		:= StationId;

	

	-- determine TRX.Type

	IF IsNonClinicalTx(row_Trx."Code") = 1 THEN

		-- e.g. WD																					-- E125910

		

		-- Type 1 validation only

		IF row_Trx."ClaimDoctor" = '' OR row_Trx."ClaimDoctor" = ' ' 

			OR row_Trx."ClaimDoctor" IS NULL 

		THEN 

			nError := 10;

			RETURN;

		END IF;



		-- set Type 1 fields		

		row_Trx."Type"					:= 1;		

		SELECT TRX_ID_TREATMENT_SEQ.NEXTVAL INTO row_Trx."Id" FROM dual;	

							

		row_Trx."Procedure"			:= row_Trx."Code";



		-- clear Type 2 fields

		row_Trx."Code"					:= ' ';

		row_Trx."Custom1"				:= ' ';

		row_Trx."Custom2"				:= ' ';

			

		-- default Type 1 values

		IF row_Trx."Date" IS NULL THEN

			row_Trx."Date"				:= TRUNC(sysdate);

		END IF;

	

		IF row_Trx."CreationDate" IS NULL THEN

			row_Trx."CreationDate"	:= TRUNC(sysdate);

		END IF;

		

		IF row_Trx."AppUser" <= 0 THEN

			row_Trx."AppUser"			:= row_Trx."EntryUser";

		END IF;

	

		IF row_Trx."AppDate" IS NULL THEN

			row_Trx."AppDate"			:= row_Trx."CreationDate";

		END IF;



		row_Trx."Status"				:= 'C';

		row_Trx."Submitted"			:= 0;

		row_Trx."CustomaryTotal"	:= row_Trx."Total";

		row_Trx."InsTotal"			:= 0;

		row_Trx."TxStatus"			:= ' ';										

		row_Trx."CvgType"				:= 0;		-- Dental

		row_Trx."ChartTrx"			:= 0;

		row_Trx."OrigClaimDate"		:= row_Trx."Date";

		row_Trx."SubmitMode"			:= 0;		-- Bill Current Policy

		

		AddDefaultPolicies(row_Trx);

		

	ELSE	

		-- e.g. KP

		row_Trx."Type"					:= 2;		

		SELECT TRX_ID_OFFICECHARGES_SEQ.NEXTVAL INTO row_Trx."Id" FROM dual;		-- E72767 fixed sequence

		

		-- clear Type 1 fields

		row_Trx."ClaimDoctor"		:= ' ';

	END IF;



	-- 

	row_Trx."Treatment"				:= 1;

	row_Trx."ModifiedDate"			:= sysdate;

	SELECT TRX_ORIGRECNO_SEQ.NEXTVAL INTO row_Trx."OrigRecNo" FROM dual;



	InsertTrx(row_Trx);

	InsertHistory(row_Trx);

	

END AddCharge;

  

  

/*****************************************************************************/

-- adds a missed appointment charge

-- called from: 

-- 1) overnight process (via AddDefaultMissedApptCharge)

PROCEDURE addmissedapptcharge(INOUT row_trx trx, IN num_clinic numeric, IN char_producer character, IN num_cancelfailtype numeric, IN char_chargecode character) IS

  num_Exempt	PATIENT."ApptFeesExempt"%TYPE;

  row_Clinic	CLINIC%ROWTYPE;

  row_OfCharge OFCHARGE%ROWTYPE;

  Total			NUMBER;

  nError			NUMBER;



BEGIN

  BEGIN																								-- E104564

    SELECT "ApptFeesExempt" INTO num_Exempt FROM PATIENT

      WHERE "Patient" = row_TRX."Patient";



    IF num_Exempt <> 0 THEN

      RETURN;

    END IF;

    EXCEPTION

      WHEN NO_DATA_FOUND THEN

        RETURN;

  END;



  BEGIN

    IF num_CancelFailType = 1 THEN

       SELECT * INTO row_Clinic FROM CLINIC

         WHERE "Clinic" = num_Clinic AND "FailCharge"<>0;

    ELSE

       SELECT * INTO row_Clinic FROM CLINIC

         WHERE "Clinic" = num_Clinic AND "CancelCharge"<>0;

    END IF;

    EXCEPTION

      WHEN NO_DATA_FOUND THEN

        RETURN;

  END;



  BEGIN

     SELECT * INTO row_OfCharge FROM OFCHARGE

       WHERE "OfficeCharge"= char_ChargeCode;

     EXCEPTION

       WHEN NO_DATA_FOUND THEN

         --DBMS_OUTPUT.PUT_LINE('OfficeCharge in OFCHARGE = '|| char_ChargeCode);

         RETURN;

  END;

  	  

	IF row_Clinic."UseApptProvider" = 0 THEN

	  row_Trx."Producer"   := row_Clinic."Provider";

	ELSE

	  row_Trx."Producer"	  := char_Producer;

	END IF;

	  

	-- Type 2 fields

	row_Trx."Type"      := 2;

	row_Trx."Code"      := row_OfCharge."OfficeCharge";

	row_Trx."Custom1"   := row_Clinic."Custom1";	

	row_Trx."Custom2"   := row_Clinic."Custom2";



	-- Type 1 fields

	row_Trx."ClaimDoctor" := GetDefaultClaimDoctor(num_Clinic);



	-- common fields

	row_Trx."Discipline"	  := row_Clinic."Discipline";

	row_Trx."Practice"	  := row_Clinic."Practice";

	row_Trx."Description"  := row_OfCharge."Description";

	row_Trx."Total"        := row_OfCharge."Amount";

		

	Total := GetNonClinicalTotal(row_Trx."Patient", row_Trx."Code");

	IF Total >= 0 THEN

		row_Trx."Total" := Total;

	END IF;

	

	TRX_PKG.AddCharge(row_Trx."Patient",

							row_Trx."Practice",

							row_Trx."ClaimDoctor",

							TO_NUMBER(TO_CHAR(row_Trx."TreatmentDate", 'MM')),

							TO_NUMBER(TO_CHAR(row_Trx."TreatmentDate", 'DD')),

							TO_NUMBER(TO_CHAR(row_Trx."TreatmentDate", 'YYYY')),

							row_Trx."Producer",

							row_Trx."Code",

							row_Trx."Description",

							row_Trx."Total" * 100,	-- pass cents (not dollars)

							row_Trx."Discipline",

							row_Trx."Custom1",

							row_Trx."Custom2",

							row_Trx."User",

							row_Trx."EntryUser",

							row_Trx."StationId",

							nError

						  );

	

END AddMissedApptCharge;





-- E135338

/*****************************************************************************/  

-- determines if include $0 in claim submission for the given ins co.

--	company InsCo

-- Returns	0 if not to include

--				1 if to be included

--

FUNCTION shouldsubmitzeroproc(insco character) RETURN numeric IS

  Result				NUMBER;

  ParentCompany	INSGROUP."ParentCompany"%TYPE;

	v_nCount		NUMBER := 0;								-- AX-26071

  

BEGIN



	--AX-26071

   SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_TRX_PKG' and PROCEDURE_NAME = UPPER('ShouldSubmitZeroProc');

   IF v_nCount > 0 THEN

     -- custom package function exists  

     EXECUTE IMMEDIATE 'SELECT CUSTOM_TRX_PKG.ShouldSubmitZeroProc('''||InsCo||''') FROM DUAL' INTO Result;

     RETURN Result;

   END IF;





  Result := 0;

  

  RETURN Result;

END;



--E136353

/*****************************************************************************/  

-- determines the patient charge method for the given ins co.

--	company InsCo

-- Returns	0 if charge patient always (default behavior)

--				1 if only charge if not covered by primary



FUNCTION getpatientchargemethod(insco character) RETURN numeric IS

  Result				NUMBER;

  ParentCompany	INSGROUP."ParentCompany"%TYPE;

	v_nCount		NUMBER := 0;								-- AX-26071

  

BEGIN



	--AX-26071

   SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_TRX_PKG' and PROCEDURE_NAME = UPPER('GetPatientChargeMethod');

   IF v_nCount > 0 THEN

     -- custom package function exists  

     EXECUTE IMMEDIATE 'SELECT CUSTOM_TRX_PKG.GetPatientChargeMethod('''||InsCo||''') FROM DUAL' INTO Result;

     RETURN Result;

   END IF;



  Result := 0;

  

  RETURN Result;

END;



-- AX-2180.2923

/*****************************************************************************/  

-- determines determine the patient charge method for the given insurance co  	 	

--						and procedure code 

-- Note: this will only be called in case of dual coverage under same company

--				otherwise, will be calling GetPatientChargeMethod instead

--	company InsCo

-- procedure user code UserCode

-- Returns	0 if charge patient always (default behavior)

--				1 if only charge if not covered by primary



FUNCTION getptchargemethodforproc(insco character, usercode character) RETURN numeric IS

  Result				NUMBER;

  ParentCompany	INSGROUP."ParentCompany"%TYPE;

	v_nCount		NUMBER := 0;								-- AX-26071

  

BEGIN

  Result := 0;

  

-- Note: This is just sample code that WDE can use to achieve what they 

--			requested for to handle the special procedure codes 

-- BEGIN

--    SELECT "ParentCompany" INTO ParentCompany FROM INSGROUP WHERE "Company" = InsCo;

--  EXCEPTION

--    WHEN NO_DATA_FOUND THEN

--      ParentCompany := ' ';

--  END;



--  IF ParentCompany = 'WDG' THEN	

--		 IF UserCode = 'D2392' OR UserCode = 'D2393' OR UserCode = 'D2394' THEN

--				Result := 0;

--		 ELSE			

--				Result := 1;

--		 END IF;

--  ELSE

--     Result := 0;

--  END IF;



	--AX-26071

   SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_TRX_PKG' and PROCEDURE_NAME = UPPER('GetPtChargeMethodForProc');

   IF v_nCount > 0 THEN

     -- custom package function exists  

     EXECUTE IMMEDIATE 'SELECT CUSTOM_TRX_PKG.GetPtChargeMethodForProc('''||InsCo||''', '''||UserCode||''') FROM DUAL' INTO Result;

     RETURN Result;

   END IF;

    

   RETURN Result;

END;



--E136761

/*****************************************************************************/  

-- determines if use ins adjusted amount as paid amount for the given ins co.

--	company InsCo

-- Returns	0 if not to use adjusted amount as paid amount 

--				1 if ok to use adjusted amount as paid amount



FUNCTION useadjustamountaspaidamount(insco character) RETURN numeric IS

  Result				NUMBER;

  ParentCompany	INSGROUP."ParentCompany"%TYPE;

	v_nCount		NUMBER := 0;								-- AX-26071

  

BEGIN



	--AX-26071

   SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_TRX_PKG' and PROCEDURE_NAME = UPPER('UseAdjustAmountAsPaidAmount');

   IF v_nCount > 0 THEN

     -- custom package function exists  

     EXECUTE IMMEDIATE 'SELECT CUSTOM_TRX_PKG.UseAdjustAmountAsPaidAmount('''||InsCo||''') FROM DUAL' INTO Result;

     RETURN Result;

   END IF;

    



  Result := 0;

  

  RETURN Result;

END;



-- E136559	

/*****************************************************************************/  

-- determines if the given ins co. cares if there're other PPO policies

--	company InsCo

-- Returns	0 if it doesn't care 

--				1 if it does



FUNCTION needtouseppofeeifapplcable(policyid numeric) RETURN numeric IS

  Result				NUMBER;

  ParentCompany	INSGROUP."ParentCompany"%TYPE;

	v_nCount		NUMBER := 0;								-- AX-26071

  

BEGIN



	--AX-26071

   SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_TRX_PKG' and PROCEDURE_NAME = UPPER('NeedToUsePPOFeeIfApplcable');

   IF v_nCount > 0 THEN

     -- custom package function exists  

     EXECUTE IMMEDIATE 'SELECT CUSTOM_TRX_PKG.NeedToUsePPOFeeIfApplcable('||PolicyId||') FROM DUAL' INTO Result;

     RETURN Result;

   END IF;



  Result := 0;

  

  RETURN Result;

END;

  



-- E136559	

/*****************************************************************************/  

-- determines if the given ins co. is PPO (contract type)

--	company InsCo

-- Returns	0 if it is not PPO

--				1 if it is



FUNCTION isppoinsurancepolicy(policyid numeric) RETURN numeric IS

  Result				NUMBER;

  GovPolicy		   INSURANC."GovPolicy"%TYPE;

  PlanType			INSURANC."PlanType"%TYPE;

  

BEGIN

  Result := 0;

  

  BEGIN

	 SELECT "GovPolicy", "PlanType" INTO GovPolicy, PlanType FROM POLICY WHERE "PolicyId" = PolicyId;

  EXCEPTION

    WHEN NO_DATA_FOUND THEN

    BEGIN

      GovPolicy := ' ';

      PlanType := 0;

     END;

  END;



  IF  ( GovPolicy <> ' ' AND PlanType = 10 ) THEN	

     Result := 1;

  ELSE

     Result := 0;

  END IF;

  

  RETURN Result;

END;



  

--	B136211		changes to handle undefined procedure for EDI 5010 claim

-- parameters include Ins Company, procedure user code / insurance code

-- return NULL if it's not

-- else return the user definable procedure description to be used for EDI submission

FUNCTION isundefinedprocedurecode(insco character, usercode character, inscode character) RETURN character varying IS

  vResult  VARCHAR2(81);

	v_nCount		NUMBER := 0;								-- AX-26071

  

BEGIN

  vResult := '';



-- Note: This is just sample code that Michigan can use to achieve what the X12N 5010 requires 

--			to handle the undefined procedures; simply uncomment and re-run the package to use 



	-- need to check InsCo if applicable; if not, can just leave it...

	

	-- use insurance code to determine if it's undefined procedure

--	IF  ( InsCode = 'M21089' 

--			OR InsCode = 'M41899' 	 

			-- OR ....

--		)	 

--	THEN

	     -- it's one of the undefined procedures, need to do the lookup

	     --		or could be hardcoded

--		  BEGIN

					-- use user code to load specific procedures

--					SELECT P."PrintDesc" INTO vResult FROM PROCEDUR P WHERE P."Procedure" = UserCode;

--			EXCEPTION

--			WHEN NO_DATA_FOUND THEN

--				  vResult := '';

--		  END;



--	END IF;



	--AX-26071

   SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_TRX_PKG' and PROCEDURE_NAME = UPPER('IsUndefinedProcedureCode');

   IF v_nCount > 0 THEN

     -- custom package function exists  

     EXECUTE IMMEDIATE 'SELECT CUSTOM_TRX_PKG.IsUndefinedProcedureCode('''||InsCo||''', '''||UserCode||''', '''||InsCode||''') FROM DUAL' INTO vResult;

     RETURN vResult;

   END IF;

    



	

  RETURN vResult;



END;

  

  -- AX-2999.3727 - determine invoice payment due date, AX-2999.3743b

  FUNCTION getinvoicepmtduedate(patientid numeric, invoicedate timestamp without time zone, defaultduedays numeric) RETURN timestamp without time zone IS



	v_nCount		NUMBER := 0;								-- AX-26071

	v_dtDate		DATE;											-- AX-26071

  

  BEGIN



	--AX-26071

   SELECT COUNT(1) INTO v_nCount FROM USER_PROCEDURES WHERE OBJECT_NAME = 'CUSTOM_TRX_PKG' and PROCEDURE_NAME = UPPER('GetInvoicePmtDueDate');

   IF v_nCount > 0 THEN

     -- custom package function exists  

     EXECUTE IMMEDIATE 'SELECT CUSTOM_TRX_PKG.GetInvoicePmtDueDate(:1, :2, :3) FROM DUAL' INTO v_dtDate

     			USING PatientId, InvoiceDate, DefaultDueDays;							--AX-27290

     RETURN v_dtDate;

   END IF;

    





  	-- can be customized if rules change over time

  	return InvoiceDate + DefaultDueDays;

  END;





-- AX-20838.20911b

PROCEDURE setdenticaltxgroupallowed(IN nfunctionallowed numeric) IS

BEGIN



	v_nDenticalTxGroupAllowed := nFunctionAllowed;

	

END SetDenticalTxGroupAllowed;



-- AX-19219 to get the give PreAuth status for the given tx and InsNumber

-- AX-19409 altered to handle unexpected TRXPOL records

-- AX-19409b made company optional joint; added procedure to filter out step children; 

--				added logic with N/A vs Not Req'd

--	Return:

--		0 : not required

--		1 : required

--		2 : sent

--		3 : accepted

--		4 : denied

--		5 : expired

--		6 : not effective						-- AX-19219.2

--      7 : N/A									-- AX-19409

--      8 : accepted (R)						-- AX-20838.20911a; AX-20838.20911b

--      9 : accepted (U)						-- AX-20838.20911b

FUNCTION getpreauthstatus(ntype numeric, nid numeric, ntreatment numeric, ninsnumber numeric, datefor timestamp without time zone, OUT nmultiins numeric) RETURN numeric IS



  nPreAuthNotRequired     NUMBER := 0;

  nPreAuthRequired		  NUMBER := 1;

  nPreAuthSent			  NUMBER := 2;

  nPreAuthAccepted		  NUMBER := 3;

  nPreAuthDenied		  NUMBER := 4;

  nPreAuthExpired		  NUMBER := 5;

  nPreAuthNotEffective	  NUMBER := 6;							-- AX-19219.2

  nPreAuthNotApplicable	  NUMBER := 7;							-- AX-19409

  nPreAuthAcceptRegular	  NUMBER := 8;							-- AX-20838.20911a; AX-20838.20911b

  nPreAuthAcceptUniversity  NUMBER := 9;						-- AX-20838.20911b



  -- AX-20838.20911b

  nDentiCalForm				NUMBER := 8;

  nDentiCalNPIForm			NUMBER := 24;



  nResult		   NUMBER;

  sStatus		   TRX."Status"%TYPE;							-- AX-19409

  nPolicyId		   TRX."PolicyId1"%TYPE;						-- AX-19409

  nOtherPolicyId   TRX."PolicyId1"%TYPE;						-- AX-19450

  nPercent		   TRX."Pct1"%TYPE;								-- AX-19409

  nAmount		   TRX."Amount1"%TYPE;							-- AX-19450

  nOnlyCovered	   INSURANC."OnlyCoveredOnClaim"%TYPE;			-- AX-20838.20911b

  nFormType		   CFORMCD."FormType"%TYPE;						-- AX-19409

  nNeedAuth		   INSPROC."NeedAuth"%TYPE;

  nTrxPolId        TRXPOL."TrxPol"%TYPE; 						-- AX-19409

  PreAuthStartDate TRXPOL."PreAuthStartDate"%TYPE; 	

  PreAuthEndDate   TRXPOL."PreAuthEndDate"%TYPE; 	

  nSubmitted       TRXPOL."Submitted"%TYPE; 	

  nReceived        TRXPOL."Received"%TYPE; 	

  nDenied          TRXPOL."Denied"%TYPE; 	





BEGIN



  nResult := -1;

  nMultiIns := 0;										--AX-19450

  

  BEGIN

	IF nInsNumber = 2 THEN -- AX-20838.20911b 

		 SELECT T."Status", T."PolicyId2", T."PolicyId1", T."Pct2", T."Amount2", NVL(I."OnlyCoveredOnClaim",0), 

			NVL(IF."FormType", 0), NVL(IP."NeedAuth", 0), 

		    NVL(TP."TrxPol", -1), TP."PreAuthStartDate", TP."PreAuthEndDate", NVL(TP."Submitted", -1), 

			NVL(TP."Received", -1), NVL(TP."Denied", -1) 

			INTO sStatus, nPolicyId, nOtherPolicyId, nPercent, nAmount, nOnlyCovered, nFormType, nNeedAuth, nTrxPolId,

			PreAuthStartDate, PreAuthEndDate, nSubmitted, nReceived, nDenied  

			FROM TRX T, PROCEDUR P, INSURANC I, CFORMCD IF, INSPROC IP, TRXPOL TP  

			WHERE T."Type" = nType

		  AND T."Id" = nId

		  AND T."Treatment" = nTreatment

		  AND T."Procedure" = P."Procedure" 

		  AND P."IsStepChild" = 0

		  AND T."Company2" = I."Company"(+)

		  AND I."Form" = IF."CFormCdId"(+)

		  AND T."Procedure" = IP."Procedure"(+) 

		  AND T."Company2" = IP."Company"(+)

		  AND T."Type" = TP."Type" (+)

		  AND T."Id" = TP."Id" (+)

		  AND T."Treatment" = TP."Treatment" (+)

		  AND T."PolicyId2" = TP."PolicyId" (+);

	ELSIF  nInsNumber = 3 THEN     -- AX-20838.20911b

		 SELECT T."Status", T."PolicyId3", T."PolicyId1", T."Pct3", T."Amount3", NVL(I."OnlyCoveredOnClaim",0), 

			NVL(IF."FormType", 0), NVL(IP."NeedAuth", 0), 

		    NVL(TP."TrxPol", -1), TP."PreAuthStartDate", TP."PreAuthEndDate", NVL(TP."Submitted", -1), 

			NVL(TP."Received", -1), NVL(TP."Denied", -1) 

			INTO sStatus, nPolicyId, nOtherPolicyId, nPercent, nAmount, nOnlyCovered, nFormType, nNeedAuth, nTrxPolId,

			PreAuthStartDate, PreAuthEndDate, nSubmitted, nReceived, nDenied  

			FROM TRX T, PROCEDUR P, INSURANC I, CFORMCD IF, INSPROC IP, TRXPOL TP  

			WHERE T."Type" = nType

		  AND T."Id" = nId

		  AND T."Treatment" = nTreatment

		  AND T."Procedure" = P."Procedure" 

		  AND P."IsStepChild" = 0

		  AND T."Company3" = I."Company"(+)

		  AND I."Form" = IF."CFormCdId"(+)

		  AND T."Procedure" = IP."Procedure"(+) 

		  AND T."Company3" = IP."Company"(+)

		  AND T."Type" = TP."Type" (+)

		  AND T."Id" = TP."Id" (+)

		  AND T."Treatment" = TP."Treatment" (+)

		  AND T."PolicyId3" = TP."PolicyId" (+);

	ELSE	--nInsNumber = 1; AX-20838.20911b

		 SELECT T."Status", T."PolicyId1", T."PolicyId2", T."Pct1", T."Amount1", NVL(I."OnlyCoveredOnClaim",0), 

			NVL(IF."FormType", 0), NVL(IP."NeedAuth", 0), 

		    NVL(TP."TrxPol", -1), TP."PreAuthStartDate", TP."PreAuthEndDate", NVL(TP."Submitted", -1), 

			NVL(TP."Received", -1), NVL(TP."Denied", -1) 

			INTO sStatus, nPolicyId, nOtherPolicyId, nPercent, nAmount, nOnlyCovered, nFormType, nNeedAuth, nTrxPolId,

			PreAuthStartDate, PreAuthEndDate, nSubmitted, nReceived, nDenied  

			FROM TRX T, PROCEDUR P, INSURANC I, CFORMCD IF, INSPROC IP, TRXPOL TP  

			WHERE T."Type" = nType

		  AND T."Id" = nId

		  AND T."Treatment" = nTreatment

		  AND T."Procedure" = P."Procedure" 

		  AND P."IsStepChild" = 0

		  AND T."Company1" = I."Company"(+)					

		  AND I."Form" = IF."CFormCdId"(+)

		  AND T."Procedure" = IP."Procedure"(+) 

		  AND T."Company1" = IP."Company"(+)

		  AND T."Type" = TP."Type" (+)

		  AND T."Id" = TP."Id" (+)

		  AND T."Treatment" = TP."Treatment" (+)

		  AND T."PolicyId1" = TP."PolicyId" (+);

	END IF;



	--AX-19450

	IF nOtherPolicyId <> 0 THEN

		nMultiIns := 1;

	END IF;



	IF TRIM(sStatus) = 'C' THEN								-- completed tx, N/A

		nResult := nPreAuthNotApplicable;

	ELSIF nPolicyId = 0 THEN								-- no insurance, not req'd (may be N/A)

		IF nInsNumber = 1 THEN								-- AX-19409b Not Req'd if primary; else N/A

			nResult := nPreAuthNotRequired;

		ELSE

			nResult := nPreAuthNotApplicable;

		END IF;

	ELSIF nTrxPolId = -1 THEN								-- no TRXPOL record; do regular checks

		IF nNeedAuth <> 1 OR								-- does not require PreAuth

				(nOnlyCovered = 1 AND nPercent = 0 AND nAmount = 0) THEN	-- only incl covered but procedure is not; AX-19450

			nResult := nPreAuthNotRequired;

		END IF;

	END IF;



	IF nResult = -1 THEN

		IF nSubmitted = -1	THEN -- no TRXPOL, so not sent

			nResult := nPreAuthRequired;

		ELSE   -- nSubmitted = 0 or 1 

			IF nReceived = 0 THEN  -- not received yet

				IF nSubmitted = 1 THEN -- submitted, so waiting (sent)

				

					-- AX-21960

					IF nNeedAuth <> 1 THEN

						nResult := nPreAuthNotRequired;

					ELSE

						nResult := nPreAuthSent;

					END IF;



				ELSE	-- nSubmitted = 0; not submitted yet, need to send (required)

					IF nNeedAuth <> 1 OR								-- AX-19409c DUMMY TRXPOL, still need to honor the flag

							(nOnlyCovered = 1 AND nPercent = 0 AND nAmount = 0) THEN	-- only incl covered but procedure is not; AX-19450

						nResult := nPreAuthNotRequired;

					ELSE

						nResult := nPreAuthRequired;

					END IF;

				END IF;

			ELSE -- nReceived = 1

				IF nDenied = 1 THEN -- denied

					nResult := nPreAuthDenied;

				ELSE -- nDenied = 0;  AX-20838.20911a can now be Denied = 2 

					IF PreAuthStartDate IS NOT NULL AND PreAuthStartDate > DateFor THEN

						nResult := nPreAuthNotEffective;

					ELSE

						IF PreAuthEndDate IS NOT NULL AND PreAuthEndDate < DateFor THEN

							nResult := nPreAuthExpired;

						ELSE

						    -- AX-20838.20911a; AX-20838.20911b

							if v_nDenticalTxGroupAllowed = 0 OR (nFormType <> nDentiCalForm AND nFormType <> nDentiCalNPIForm) THEN

								nResult := nPreAuthAccepted;

							ELSE

								if nDenied = 0 THEN									-- AX-21078.21079

									nResult := nPreAuthAcceptRegular;

								ELSE

									nResult := nPreAuthAcceptUniversity;

								END IF;

							END IF;

						END IF;

					END IF;

				END IF;

			END IF;

		END IF;



	END IF;



  EXCEPTION

    WHEN NO_DATA_FOUND THEN

    BEGIN

		nResult := nPreAuthNotApplicable;							--AX-19409

    END;

  END;



  RETURN nResult;





END;



-- AX-19219; AX-19450

FUNCTION getpreauthstatusforinsnumber(ntype numeric, nid numeric, ntreatment numeric, ninsnumber numeric, datefor timestamp without time zone) RETURN numeric IS



    nResult		NUMBER := -1;

	nMultiIns	NUMBER := 0;



  BEGIN



	nResult := GetPreAuthStatus(nType, nId, nTreatment, nInsNumber, DateFor, nMultiIns);

	--ignore the nMulitIns parameter returned

	return nResult;



  END;





-- AX-19450

FUNCTION getpreauthstatusforprimary(ntype numeric, nid numeric, ntreatment numeric, datefor timestamp without time zone) RETURN numeric IS



  nResult					NUMBER := -1;

  nMultiIns					NUMBER := 0;

  nPreAuthHasMultipleIns	NUMBER := 32;	



  BEGIN



	nResult := GetPreAuthStatus(nType, nId, nTreatment, 1, DateFor, nMultiIns);

	if nMultiIns > 0 THEN

		nResult := nResult + nPreAuthHasMultipleIns;

	END IF;

	return nResult;

  END;



-- AX-12108.19496

PROCEDURE addlockboxpayment(IN chartno character, IN pmtcode character, IN bank character, IN description character varying, IN edipat character, IN audituser numeric, IN auditstation numeric, IN paymentdate timestamp without time zone, IN amountincents numeric, IN practice numeric, OUT trxid numeric) IS

	vOrigRecNo	TRX."OrigRecNo"%TYPE;

	vPatientId	PATIENT."Patient"%TYPE;

	vCustom1		TRX."Custom1"%TYPE;		-- AX-12108.19496b

	vCustom2		TRX."Custom2"%TYPE;		-- AX-12108.19496b

	row_Trx		TRX%ROWTYPE;



BEGIN



	BEGIN



		SELECT P."Patient" INTO vPatientId FROM PATIENT P WHERE P."Chart" = ChartNo; -- AX-12111.19538hij

		SELECT TRX_ID_PAYMENT_SEQ.NEXTVAL INTO TrxId FROM DUAL;

		SELECT TRX_ORIGRECNO_SEQ.NEXTVAL INTO vOrigRecNo FROM DUAL;



		EXCEPTION WHEN NO_DATA_FOUND THEN

		BEGIN

			TrxId := -1;

		END;

	END;



	-- AX-12108.19496b

	BEGIN

		SELECT NVL("Code", '') INTO vCustom1 FROM CUSTCODE WHERE "Type" = 41 AND "Default" = 1 AND "Inactive" != 1; 

		EXCEPTION WHEN NO_DATA_FOUND THEN

		BEGIN

			vCustom1 := '';

		END;

	END;

	BEGIN

		SELECT NVL("Code", '') INTO vCustom2 FROM CUSTCODE WHERE "Type" = 42 AND "Default" = 1 AND "Inactive" != 1;

		EXCEPTION WHEN NO_DATA_FOUND THEN

		BEGIN

			vCustom2 := '';

		END;

	END;



  TRX_PKG.InitializeTrx(row_Trx);

  

  row_Trx."Type"          := 3;

	row_Trx."Id"            := TrxId;

	row_Trx."Treatment"     := 1;

	row_Trx."Patient"       := vPatientId;

	row_Trx."Family"        := vPatientId;

	row_Trx."Date"          := PaymentDate; -- AX-12108.19496d

	row_Trx."TreatmentDate" := PaymentDate;

	row_Trx."CreationDate"  := TRUNC(SYSDATE);

	row_Trx."Code"          := PmtCode;

	row_Trx."Total"         := (AmountInCents / 100) * -1;

	row_Trx."Description"   := Description;

	row_Trx."Bank"          := Bank;

	row_Trx."Payed"         := (AmountInCents / 100) * -1;

	row_Trx."EDIPat"        := EDIPat;

	row_Trx."User"          := AuditUser;

	row_Trx."StationId"     := AuditStation;

	row_Trx."ModifiedDate"  := SYSDATE;

	row_Trx."OrigRecNo"     := vOrigRecNo;		

	row_Trx."EntryUser"     := AuditUser;

	row_Trx."Custom1"			:= vCustom1;	-- AX-12108.19496b

	row_Trx."Custom2"			:= vCustom2;	-- AX-12108.19496b

	row_Trx."Practice"		:= Practice;		-- AX-26015

	TRX_PKG.InsertTrx(row_Trx);

	TRX_PKG.InsertHistory(row_Trx);	



END AddLockBoxPayment;



-- AX-28836.29971

FUNCTION getsrpdateforclaim(npatientid numeric, ntype numeric, nid numeric, ninsco character) RETURN timestamp without time zone IS

	SPRDate			DATE := NULL;



BEGIN



	-- can block the lookup if certain InsCo could not handle the new SRPDate; example

	-- IF nInsCo = 'NYM' THEN

	--		RETURN NULL;

	-- END IF;



	IF nType = 5 THEN

		BEGIN

			SELECT MAX(T."TreatmentDate") 

				INTO SPRDate

			FROM TRX T

			WHERE 

				T."Patient" = nPatientId

				AND T."Type" = 1

				AND T."Procedure" IN ('D4341', 'D4342')

				AND T."Status" = 'C'

				AND T."Deleted" = 0;

			EXCEPTION WHEN NO_DATA_FOUND THEN

			BEGIN

				SPRDate := NULL;

			END;

		END;			

	ELSE  -- nType = 1 THEN

		BEGIN

			SELECT MAX(T."TreatmentDate") 

				INTO SPRDate

			FROM TRX T

			WHERE 

				T."Patient" = nPatientId

				AND T."Type" = nType

				AND T."Procedure" IN ('D4341', 'D4342')

				AND T."Status" = 'C'

				AND T."Deleted" = 0

				AND T."TreatmentDate"  < 

				(SELECT MIN(T2."TreatmentDate") FROM TRX T2 

				WHERE T2."Type" = nType

				AND T2."Id" = nId 

				AND T2."Deleted" = 0);

			EXCEPTION WHEN NO_DATA_FOUND THEN

			BEGIN

				SPRDate := NULL;

			END;

		END;

	END IF;



	-- can include additional subclause to filter the fact only need SRPDate if the given claim has a certain procedure; example

	-- AND EXISTS (SELECT 1 FROM TRX T3 WHERE  

	--		WHERE T3."Type" = nType

	--		AND T3."Id" = nId 

	--		AND T3."Procedure" IN ('D4348')

	--		AND T3."Deleted" = 0)



	RETURN SPRDate;



END GetSRPDateForClaim;





/*****************************************************************************/

END;
CREATE OR REPLACE PACKAGE BODY web_common_pkg IS



  PROCEDURE getaxiumpracticeminversion(OUT vversion character varying) IS
  BEGIN
    SELECT MIN("Version") INTO vVersion FROM PRACTICE;

    EXCEPTION WHEN NO_DATA_FOUND THEN
		vVersion := NULL;
  END;



  PROCEDURE getaxiumpracticemaxversion(OUT vversion character varying) IS
  BEGIN
    SELECT MAX("Version") INTO vVersion FROM PRACTICE;

    EXCEPTION WHEN NO_DATA_FOUND THEN
		vVersion := NULL;
  END;

END;
CREATE OR REPLACE PACKAGE BODY web_epr_pkg IS

  PROCEDURE getrepresentativelist(IN vwebuserid integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

	OPEN vResult FOR

		SELECT "RespiUser"

		FROM IACCESS

		WHERE "iUser" = vWebUserId

		AND "Deleted" = 0

		ORDER BY "RespiUser";



		EXCEPTION WHEN NO_DATA_FOUND THEN

        vResult := NULL;

  END;



  PROCEDURE getinternetformlist(IN vwebuserid integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT

        I."iPtForm",

        F."Id",

        P."PForm",

        F."Code",

        F."Description",

        P."Date",

        GREATEST(F."Inactive", P."Inactive") AS "Inactive",

        I."Access",

        I."RequiresAttention",

        I."FormStatus",

		I."LastSavedPageNumber"

      FROM IPTFORM I

      JOIN FORM F ON I."FormCode" = F."Code"

      LEFT JOIN PFORM P ON I."PForm" = P."PForm" AND P."PForm" != 0

      WHERE I."iUser" = vWebUserId

      AND F."iForm" = 1

      ORDER BY "Order" ASC;



      EXCEPTION WHEN NO_DATA_FOUND THEN

        vResult := NULL;

  END;



  PROCEDURE getinternetformdetail(IN vwebuserid integer, IN vinternetformid integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT

        I."iPtForm",

        F."Id",

        P."PForm",

        F."Code",

        F."Description",

        P."Date",

        GREATEST(F."Inactive", P."Inactive") AS "Inactive",

        I."Access",

        I."RequiresAttention",

        I."FormStatus",

		I."LastSavedPageNumber"

      FROM IPTFORM I

      JOIN FORM F ON I."FormCode" = F."Code"

      LEFT JOIN PFORM P ON I."PForm" = P."PForm" AND P."PForm" != 0

      WHERE I."iUser" = vWebUserId

      AND I."iPtForm" = vInternetFormId

      AND F."iForm" = 1

      AND ROWNUM = 1;



      EXCEPTION WHEN NO_DATA_FOUND THEN

        vResult := NULL;

  END;



  PROCEDURE getformdetail(IN vformid integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT

        F."Id",

        F."Code",

        F."Description",

        F."Instructions",

        F."Inactive",

        F."Multiple",

        F."CanBeAssigned"

      FROM FORM F

      WHERE F."Id" = vFormId

      AND ROWNUM = 1;



      EXCEPTION WHEN NO_DATA_FOUND THEN

        vResult := NULL;

  END;



  PROCEDURE getformitemlist(IN vformid integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT

        I."FItem",

        I."Page",

        I."Row",

        I."Type",

        I."AnsType",

        I."Text",

        I."HasChildQuestions",

        I."ParentFItem",

        I."Instructions",

        I."LimitChildAnswers",

        I."AllowDontKnow",

        I."SubQAnswer",

		I."CanChange",

        I."AnsList",

        I."FIScheme",

        S."Min",

        S."Max",

        S."Increment"

      FROM FITEM I

      LEFT JOIN FISCHEME S ON I."FIScheme" = S."FIScheme"

      WHERE I."FormId" = vFormId

      AND "Deleted" = 0

      AND "iForm" = 1 

      AND NOT (EXISTS (SELECT 1 FROM SYSOPTS WHERE "Name" = 'PA_Use_New_Template' AND "Value" = 1) AND "AnsType" IN (6,7,8,9))

      ORDER BY "Page", "Row" ASC;



      EXCEPTION WHEN NO_DATA_FOUND THEN

        vResult := NULL;

  END;



  PROCEDURE getformitemcolumnlist(IN vformitemid integer, IN vpatientformid integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT FIC.*, WEB_EPR_PKG.GetDefaultColumnArchived(FIC."FItemCol", vPatientFormId) AS "Archived" FROM FITEMCOL FIC

      WHERE FIC."FItem" = (SELECT "FItem" FROM FITEM WHERE "ParentFItem" = vFormItemId AND "Type" = 5 AND "Deleted" = 0 AND ROWNUM = 1)

      AND FIC."Column" > 0

      AND FIC."Deleted" = 0

      ORDER BY FIC."Column";



      EXCEPTION WHEN NO_DATA_FOUND THEN

        vResult := NULL;

  END;



  PROCEDURE getpatientformdetail(IN vptformid integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT

        P."PForm",

        P."Patient",

        P."User",

        P."Inactive",

        P."Date"

      FROM PFORM P

      WHERE P."PForm" = vPtFormId

      AND ROWNUM = 1;



      EXCEPTION WHEN NO_DATA_FOUND THEN

        vResult := NULL;

  END;



  PROCEDURE getpatientformitemlist(IN vptformid integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT

        P."PItem",

        P."FItem",

        P."AnsType",

        P."AnsYes",

        WEB_EPR_PKG.GetAnswerText(P."PItem") AS "AnsText",

        P."AnsDate",

        P."AnsListDesc",

        P."Date",

        P."Time",

        P."Status",

        P."AuditNumber",

        P."PItemCol",

        P."AppUser",

		P."User"

      FROM PITEM P

      WHERE P."PForm" = vPtFormId

      ORDER BY P."FItem" ASC, P."AuditNumber" DESC;



      EXCEPTION WHEN NO_DATA_FOUND THEN

        vResult := NULL;

  END;



  PROCEDURE getpatientformitemcolumnlist(IN vformitemid integer, IN vpatientformid integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT PIC.* FROM PITEM PI

      JOIN PITEMCOL PIC ON PI."PItemCol" = PIC."PItemCol"

      WHERE PI."PForm" = vPatientFormId

      AND PI."FItem" = (SELECT "FItem" FROM FITEM WHERE "ParentFItem" = vFormItemId AND "Type" = 5 AND "Deleted" = 0 AND ROWNUM = 1)

      AND PI."Status" = 0

      AND PIC."Deleted" = 0

      AND (

        (PI."AnsType" = 0 AND PI."AnsYes" IS NOT NULL) OR -- Yes/No

        (PI."AnsType" = 1 AND PI."AnsText" IS NOT NULL) OR -- Short Text

        (PI."AnsType" = 2 AND PI."AnsText" IS NOT NULL) OR -- Number

        (PI."AnsType" = 3 AND (PI."AnsList" != '' OR PI."AnsListDesc" IS NOT NULL)) OR -- List

        (PI."AnsType" = 4 AND PI."AnsDate" IS NOT NULL) OR -- Date

        (PI."AnsType" = 5 AND PI."AnsText" IS NOT NULL) -- Long Text

      )

      ORDER BY "VariableColumn";



      EXCEPTION WHEN NO_DATA_FOUND THEN

        vResult := NULL;

  END;



  PROCEDURE getanswerschemelist(IN vlistid character varying, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

      SELECT

        L."Description"

      FROM LISTITEM L

      WHERE TRIM(L."ListCode") = TRIM(vListId)

      AND L."Type" IN (1,99)

      ORDER BY L."Order";



      EXCEPTION WHEN NO_DATA_FOUND THEN

        vResult := NULL;

  END;



  PROCEDURE createpatientform(IN vinternetformid integer, IN vwebuserid integer, IN vfstatus character varying, OUT vpatientformid integer) IS

    vPFormId INTEGER;

    vPatient NUMBER(10);

    vFormCode  CHAR(6);

    -- vWebUser NUMBER(10);

    vDescription  CHAR(30);

  BEGIN

    --Get next PFORM ID

    SELECT PFORM_PFORM_SEQ.nextval INTO vPFormId

    FROM DUAL;



    -- Get internet form data

    SELECT I."Patient", I."FormCode", F."Description" -- , I."iUser"

    INTO vPatient, vFormCode, vDescription -- , vWebUser

    FROM IPTFORM I

    LEFT JOIN FORM F ON I."FormCode" = F."Code"

    WHERE "iPtForm" = vInternetFormId;



    -- Insert into PFORM

    INSERT INTO PFORM

    (

      "Patient",

      "FormCode",

      "Date",

      "User",

      "PForm",

      "Description",

      "OwnerType",

      "OwnerId",

      "CreatedDate",

      "Approved",

      "LastAppUser",

      "LastAppDate",

      "Inactive",

      "InactiveAppUser",

      "InactiveAppDate",

      "InactiveReason",

      "FStatus",

      "AssignedUser",

      "AssignedUGroup"

    )

    VALUES ( vPatient, vFormCode, SYSDATE, vWebUserId, vPFormId, vDescription, 0, vPatient, SYSDATE, 0, 0, null, 0, 0, null, null, vFStatus, 0, null);



    -- Update IPTFORM

    UPDATE IPTFORM

    SET

      "PForm" = vPFormId,

      "RequiresAttention" = 0

    WHERE "iPtForm" = vInternetFormId;



    COMMIT;



    vPatientFormId := vPFormId;

  END;



  PROCEDURE updatepatientform(IN vinternetformid integer) IS

    vPFormId INTEGER;

  BEGIN

    -- Get internet form data

    SELECT I."PForm"

    INTO vPFormId

    FROM IPTFORM I

    WHERE "iPtForm" = vInternetFormId;



    -- Update PFORM

    UPDATE PFORM SET "Date" = SYSDATE, "Approved" = 0 WHERE "PForm" = vPFormId;



    -- Update IPTFORM

    UPDATE IPTFORM SET "RequiresAttention" = 0 WHERE "iPtForm" = vInternetFormId;



    COMMIT;

  END;



  PROCEDURE updatepatientformcompletion(IN vinternetformid integer, IN vformstatus integer, IN vlastsavedpagenumber integer) IS

  BEGIN

    -- Update IPTFORM

    UPDATE IPTFORM SET "FormStatus" = vFormStatus, "LastSavedPageNumber" = vLastSavedPageNumber WHERE "iPtForm" = vInternetFormId;



    COMMIT;

  END;



  --AX-30362

  PROCEDURE clearpformrequireattnflag(IN vinternetformid integer) IS

  BEGIN

    -- Update IPTFORM

    UPDATE IPTFORM SET "RequiresAttention" = 0 WHERE "iPtForm" = vInternetFormId;



    COMMIT;

  END;

  



  PROCEDURE savepatientformitem(IN vinternetformid integer, IN vformitemid integer, IN vcolumnid integer, IN vanswer character varying, IN vwebuserid integer, OUT vpatientitem integer) IS



    vPatientItemId NUMBER(10);



    vPatient NUMBER(10);

    vFormCode  CHAR(6);

    vPatientForm NUMBER(10);

    vWebUser NUMBER(10);

    vAnsType NUMBER(5);

    vTime NUMBER(10);

    vAnsList  CHAR(6);

    vAnsListDesc  VARCHAR2(50);

    vAnsYesNo NUMBER(5) := 0;



    vAnsText  VARCHAR2(4000) := '';

    vAnsDate DATE := NULL;



    vText  VARCHAR2(4000);

    vOverId NUMBER(10);

    vCurrentAnsText  VARCHAR2(32000);

    vOrder NUMBER(5) := 1;



    vCount NUMBER(10);

    vAudit NUMBER(10);

    vPtAuto NUMBER(10);

    vAlertYes  CHAR(7);

    vAlertNo  CHAR(7);

    vNeedYes  CHAR(6);

    vNeedNo  CHAR(6);

  BEGIN

    -- Get internet form data

    SELECT I."Patient", I."FormCode", I."PForm" -- , I."iUser"

    INTO vPatient, vFormCode, vPatientForm --, vWebUser

    FROM IPTFORM I

    WHERE "iPtForm" = vInternetFormId;



    -- Get form item data

    SELECT "AnsType"

    INTO vAnsType

    FROM FITEM F

    WHERE "FItem" = vFormItemId;



    -- Get Time

    SELECT ((TO_NUMBER(TO_CHAR(SYSDATE,'HH24')) * 60) + TO_NUMBER(TO_CHAR(SYSDATE,'MI')))

    INTO vTime FROM DUAL;



    -- Get next PFORM ID

    SELECT PITEM_PITEM_SEQ.nextval INTO vPatientItem

    FROM DUAL;



    -- GET PITEM ID of an old answer

    BEGIN

      SELECT "PItem" INTO vPatientItemId

      FROM PITEM

      WHERE "Status" = 0

      AND "FormCode" = vFormCode

      AND "Patient" = vPatient

      AND "PForm" = vPatientForm

      AND "FItem" = vFormItemId

      AND "PItemCol" = vColumnId

      AND ROWNUM < 2;

      EXCEPTION WHEN NO_DATA_FOUND THEN

      vPatientItemId := 0;

    END;



    -- Archive old answer if there is one

    UPDATE PITEM SET "Status" = 1

    WHERE "FormCode" = vFormCode

    AND "Patient" = vPatient

    AND "PForm" = vPatientForm

    AND "FItem" = vFormItemId

    AND "PItemCol" = vColumnId;



    -- Archive old EPR notes (long text)

    UPDATE NOTEOVR

    SET "Deleted" = 1

    WHERE "Type" = 1

    AND "ParentId" IN (

      SELECT "PItem"

      FROM PITEM

      WHERE "FormCode" = vFormCode

      AND "Patient" = vPatient

      AND "PForm" = vPatientForm

      AND "FItem" = vFormItemId

      AND "PItemCol" = vColumnId );



    -- asign answer to correct variable depending on answer type

    -- 0 - Yes No

    -- 1 - Text (Short Text)

    -- 2 - Text (Number)

    -- 3 - List Description

    -- 4 - Date

    -- 5 - Text (Long)

    -- 9 - Spreadsheet

    IF vAnsType = 0 THEN

      IF vAnswer = '' OR vAnswer IS NULL THEN

        vAnsYesNo := '-1';

      ELSE

        vAnsYesNo := vAnswer;

      END IF;

    ELSIF vAnsType = 1 OR vAnsType = 2 OR vAnsType = 5 OR vAnsType = 9 THEN

      vAnsText := SUBSTR(vAnswer, 1, 4000);

    ELSIF vAnsType = 4 THEN

      vAnsDate := vAnswer;

    ELSIF vAnsType = 3 THEN

      -- validate if list is correct

      SELECT "AnsList" INTO vAnsList FROM FITEM WHERE "FItem" = vFormItemId;



      IF vAnswer = '' THEN

        vAnsListDesc := NULL;

      ELSE

        BEGIN

          SELECT "Description" INTO vAnsListDesc FROM LISTITEM WHERE TRIM("ListCode") = TRIM(vAnsList) AND "Description" = vAnswer;

          EXCEPTION WHEN NO_DATA_FOUND THEN vAnsListDesc := NULL;

        END;

      END IF;

    END IF;



    -- Insert new answer

    INSERT INTO PITEM

    (

      "Patient",

      "FormCode",

      "FItem",

      "AnsType",

      "AnsYes",

      "AnsText",

      "AnsList",

      "AnsListDesc",

      "Date",

      "User",

      "Status",

      "AuditNumber",

      "AppUser",

      "AppDate",

      "AnsDate",

      "ASAType",

      "ASAScore",

      "PItem",

      "Time",

      "PForm",

      "PItemImg",

      "AnsListRefCode",

      "EntryDateTime",

      "AppDateTime",

      "PItemCol"

    )

    VALUES

    (

      vPatient,

      vFormCode,

      vFormItemId,

      vAnsType,

      vAnsYesNo,

      vAnsText,

      vAnsList,

      vAnsListDesc,

      SYSDATE,

      vWebUserId,

      0,

      (

        --(vAuditNumber + 1),

        SELECT NVL(MAX("AuditNumber"),0) + 1

        FROM PITEM

        WHERE "FormCode" = vFormCode

        AND "Patient" = vPatient

        AND "PForm" = vPatientForm

        AND "FItem" = vFormItemId

      ),

      0,

      null,

      vAnsDate,

      0,

      0,

      vPatientItem,

      vTime,

      vPatientForm,

      0,

      null,

      SYSDATE,

      null,

      vColumnId

    );



    -- Save any note over records if answer is over 4000 characters

    IF LENGTH(vAnswer) > 4000 THEN

    BEGIN

      WHILE SUBSTR(vAnswer, (4000 * vOrder + 1), 4000) IS NOT NULL AND vOrder <= 8

      LOOP



        vText := SUBSTR(vAnswer, (4000 * vOrder + 1), 4000);

        SELECT NOTEOVR_ID_SEQ.nextval INTO vOverId FROM DUAL;

        INSERT INTO NOTEOVR ( "Id", "Patient", "Type", "ParentId", "Order", "Text", "Deleted", "Audit")

        VALUES ( vOverId, vPatient, 1, vPatientItem, vOrder, vText, 0, 0 );



        vOrder := vOrder + 1;

      END LOOP;

    END;

    END IF;

  END;



  PROCEDURE archivepatientformitem(IN vinternetformid integer, IN vformitemid integer) IS

    vPatient NUMBER(10);

    vFormCode  CHAR(6);

    vPatientForm NUMBER(10);

  BEGIN

    -- Get internet form data

    SELECT I."Patient", I."FormCode", I."PForm"

    INTO vPatient, vFormCode, vPatientForm

    FROM IPTFORM I

    WHERE "iPtForm" = vInternetFormId;



    -- Archive old answer if there is one

    UPDATE PITEM SET "Status" = 1

    WHERE "FormCode" = vFormCode

    AND "Patient" = vPatient

    AND "PForm" = vPatientForm

    AND "FItem" = vFormItemId;

  END;



  PROCEDURE addpatientcolumn(IN vinternetformid integer, OUT vpatientcolumnid integer) IS

    vPatient NUMBER(10);

    vFormCode  CHAR(6);

    vPatientForm NUMBER(10);

    vCount INTEGER;

  BEGIN

    -- Get internet form data

    SELECT I."Patient", I."FormCode", I."PForm"

    INTO vPatient, vFormCode, vPatientForm

    FROM IPTFORM I

    WHERE "iPtForm" = vInternetFormId;



    -- Create a blank Patient Item Column

    SELECT PITEMCOL_PITEMCOL_SEQ.nextVal INTO vPatientColumnId FROM DUAL;

    INSERT INTO PITEMCOL (

      "PItemCol",

      "FItemCol",

      "FormCode",

      "Patient",

      "PForm",

      "VariableColumn",

      "EntryDateTime",

      "Deleted",

      "DeletionDateTime",

      "OrgPItemCol"

    ) VALUES (

      vPatientColumnId,

      0,

      vFormCode,

      vPatient,

      vPatientForm,

      ( SELECT NVL(MAX("VariableColumn"),0) + 1

        FROM PITEMCOL

        WHERE "FItemCol" = 0

        AND "FormCode" = vFormCode

        AND "Patient" = vPatient

        AND "PForm" = vPatientForm

        AND "Deleted" = 0),

      SYSDATE,

      0,

      NULL,

      NULL

    );

  END;



  PROCEDURE savepatientcolumn(IN vinternetformid integer, IN vformcolumnid integer, OUT vpatientcolumnid integer) IS

    vPatient NUMBER(10);

    vFormCode  CHAR(6);

    vPatientForm NUMBER(10);

    vCount INTEGER;

  BEGIN

    -- Get internet form data

    SELECT I."Patient", I."FormCode", I."PForm"

    INTO vPatient, vFormCode, vPatientForm

    FROM IPTFORM I

    WHERE "iPtForm" = vInternetFormId;



    -- Check if Patient Column exist

    SELECT COUNT(1) INTO vCount

    FROM PITEMCOL

    WHERE "FItemCol" = vFormColumnId

    AND "Deleted" = 0

    AND "FormCode" = vFormCode

    AND "PForm" = vPatientForm

    AND "Patient" = vPatient;



    IF vFormColumnId = 0 THEN

      BEGIN

        SELECT PITEMCOL_PITEMCOL_SEQ.nextVal INTO vPatientColumnId FROM DUAL;



        INSERT INTO PITEMCOL (

          "PItemCol",

          "FItemCol",

          "FormCode",

          "Patient",

          "PForm",

          "VariableColumn",

          "EntryDateTime",

          "Deleted",

          "DeletionDateTime",

          "OrgPItemCol"

        ) VALUES (

          vPatientColumnId,

          vFormColumnId,

          vFormCode,

          vPatient,

          vPatientForm,

          ( SELECT NVL(MAX("VariableColumn"),0) + 1

            FROM PITEMCOL

            WHERE "FItemCol" = 0

            AND "FormCode" = vFormCode

            AND "Patient" = vPatient

            AND "PForm" = vPatientForm

            AND "Deleted" = 0),

          SYSDATE,

          0,

          NULL,

          NULL

        );

      END;

    ELSIF vCount = 0 THEN

      BEGIN

        SELECT PITEMCOL_PITEMCOL_SEQ.nextVal INTO vPatientColumnId FROM DUAL;



        INSERT INTO PITEMCOL (

          "PItemCol",

          "FItemCol",

          "FormCode",

          "Patient",

          "PForm",

          "VariableColumn",

          "EntryDateTime",

          "Deleted",

          "DeletionDateTime",

          "OrgPItemCol"

        ) VALUES (

          vPatientColumnId,

          vFormColumnId,

          vFormCode,

          vPatient,

          vPatientForm,

          0,

          SYSDATE,

          0,

          NULL,

          NULL

        );

      END;

    ELSE

      BEGIN

        SELECT "PItemCol" INTO vPatientColumnId

        FROM

        (

          SELECT "PItemCol"

          FROM PITEMCOL

          WHERE "FItemCol" = vFormColumnId

          AND "Deleted" = 0

          AND "FormCode" = vFormCode

          AND "PForm" = vPatientForm

          AND "Patient" = vPatient

          ORDER BY "VariableColumn" DESC, "PItemCol" DESC

        ) WHERE ROWNUM = 1;

      END;

    END IF;

  END;



  PROCEDURE deletepatientcolumn(IN vinternetformid integer, IN vformcolumnid integer, IN vpatientcolumnid integer) IS

    vPatient NUMBER(10);

    vFormCode  CHAR(6);

    vPatientForm NUMBER(10);

    vCount INTEGER; -- Counter for if column already exist

  BEGIN

    -- Get internet form data

    SELECT I."Patient", I."FormCode", I."PForm"

    INTO vPatient, vFormCode, vPatientForm

    FROM IPTFORM I

    WHERE "iPtForm" = vInternetFormId;



    -- If column is pre-defined column

    IF vFormColumnId != 0 AND vPatientColumnId = 0 THEN

      BEGIN



        -- Check if Patient Column exist with given form column ID

        SELECT COUNT(1) INTO vCount

        FROM PITEMCOL

        WHERE "FItemCol" = vFormColumnId

        AND "Deleted" = 0

        AND "FormCode" = vFormCode

        AND "PForm" = vPatientForm

        AND "Patient" = vPatient;



        IF vCount > 0 THEN

          BEGIN

            UPDATE PITEMCOL SET "Deleted" = 1, "DeletionDateTime" = SYSDATE

            WHERE "FItemCol" = vFormColumnId

            AND "Deleted" = 0

            AND "FormCode" = vFormCode

            AND "PForm" = vPatientForm

            AND "Patient" = vPatient;

          END;

        ELSE

          BEGIN

            INSERT INTO PITEMCOL (

              "PItemCol",

              "FItemCol",

              "FormCode",

              "Patient",

              "PForm",

              "VariableColumn",

              "EntryDateTime",

              "Deleted",

              "DeletionDateTime",

              "OrgPItemCol"

            ) VALUES (

              PITEMCOL_PITEMCOL_SEQ.nextVal,

              vFormColumnId,

              vFormCode,

              vPatient,

              vPatientForm,

              0,

              SYSDATE,

              1,

              SYSDATE,

              NULL

            );

          END;

        END IF;



      END;



    ELSIF vPatientColumnId != 0 THEN

      BEGIN

        UPDATE PITEMCOL SET "Deleted" = 1, "DeletionDateTime" = SYSDATE

        WHERE "PItemCol" = vPatientColumnId

        AND "Deleted" = 0

        AND "FormCode" = vFormCode

        AND "PForm" = vPatientForm

        AND "Patient" = vPatient;

      END;

    END IF;

  END;



  PROCEDURE resetcolumnheader(IN vinternetformid integer, IN vformitemid integer, IN vwebuserid integer) IS

    vPatient NUMBER(10);

    vFormCode  CHAR(6);

    vPatientForm NUMBER(10);



    vTime NUMBER(10);



    -- cursor for all columns

    CURSOR cColumns(vid IN INTEGER, vpt IN NUMBER) IS

    SELECT PI."PItem", PI."PItemCol", FIC.*

    FROM PITEM PI

    LEFT JOIN PITEMCOL PIC ON PI."PItemCol" = PIC."PItemCol"

    LEFT JOIN FITEMCOL FIC ON PIC."FItemCol" = FIC."FItemCol"

    WHERE PI."FItem" = vid

    AND PI."Status" = 0

    AND PI."PItemCol" > 0

    AND PI."Patient" = vpt;

  BEGIN

    -- Get internet form data

    SELECT I."Patient", I."FormCode", I."PForm"

    INTO vPatient, vFormCode, vPatientForm

    FROM IPTFORM I

    WHERE "iPtForm" = vInternetFormId;



    -- Get Time

    SELECT ((TO_NUMBER(TO_CHAR(SYSDATE,'HH24')) * 60) + TO_NUMBER(TO_CHAR(SYSDATE,'MI')))

    INTO vTime FROM DUAL;



    FOR vColumn IN cColumns(vFormItemId, vPatient) LOOP

      BEGIN

        -- Archive old answer if there is one

        UPDATE PITEM SET "Status" = 1

        WHERE "PItem" = vColumn."PItem";



        -- Archive old EPR notes (long text)

        UPDATE NOTEOVR

        SET "Deleted" = 1

        WHERE "Type" = 1

        AND "ParentId" IN (vColumn."PItem");



        IF vColumn."FItemCol" IS NULL THEN

          BEGIN

            -- Clear Answer (create an empty row)

            INSERT INTO PITEM

            (

              "Patient", "FormCode", "FItem", "AnsType", "AnsYes",

              "AnsText", "AnsList", "AnsListDesc", "Date", "User",

              "Status", "AuditNumber", "AppUser", "AppDate", "AnsDate",

              "ASAType", "ASAScore", "PItem", "Time", "PForm",

              "PItemImg", "AnsListRefCode", "EntryDateTime", "AppDateTime","PItemCol"

            )

            VALUES

            (

              vPatient, vFormCode, vFormItemId, vColumn."AnsType", -1,

              '', NULL, NULL, SYSDATE, vWebUserId,

              0, WEB_EPR_PKG.GetAuditNumber(vFormCode, vPatient, vPatientForm, vFormItemId), 0, NULL, NULL,

              0, 0, PITEM_PITEM_SEQ.nextval, vTime, vPatientForm,

              0, NULL, SYSDATE, NULL, vColumn."PItemCol"

            );

          END;

        ELSE

          BEGIN

            -- Reset Answer to default

            INSERT INTO PITEM

            (

              "Patient", "FormCode", "FItem", "AnsType", "AnsYes",

              "AnsText", "AnsList", "AnsListDesc", "Date", "User",

              "Status", "AuditNumber", "AppUser", "AppDate", "AnsDate",

              "ASAType", "ASAScore", "PItem", "Time", "PForm",

              "PItemImg", "AnsListRefCode", "EntryDateTime", "AppDateTime","PItemCol"

            )

            VALUES

            (

              vPatient, vFormCode, vFormItemId, vColumn."AnsType", vColumn."AnsType",

              vColumn."AnsText", vColumn."AnsList", vColumn."AnsListDesc", SYSDATE, vWebUserId,

              0, WEB_EPR_PKG.GetAuditNumber(vFormCode, vPatient, vPatientForm, vFormItemId), 0, NULL, vColumn."AnsDate",

              0, 0, PITEM_PITEM_SEQ.nextval, vTime, vPatientForm,

              0, NULL, SYSDATE, NULL, vColumn."PItemCol"

            );

          END;

        END IF;

      END;

    END LOOP;

  END;



  PROCEDURE resetcolumnrow(IN vinternetformid integer, IN vformitemid integer, IN vwebuserid integer) IS

    vPatient NUMBER(10);

    vFormCode  CHAR(6);

    vPatientForm NUMBER(10);



    vTime NUMBER(10);



    -- cursor for all columns

    CURSOR cAnswers(vid IN INTEGER) IS

    SELECT PI.*

    FROM PITEM PI

    WHERE PI."FItem" = vid

    AND PI."Status" = 0

    AND PI."PItemCol" > 0;

  BEGIN

    -- Get internet form data

    SELECT I."Patient", I."FormCode", I."PForm"

    INTO vPatient, vFormCode, vPatientForm

    FROM IPTFORM I

    WHERE "iPtForm" = vInternetFormId;



    -- Get Time

    SELECT ((TO_NUMBER(TO_CHAR(SYSDATE,'HH24')) * 60) + TO_NUMBER(TO_CHAR(SYSDATE,'MI')))

    INTO vTime FROM DUAL;



    FOR vAnswer IN cAnswers(vFormItemId) LOOP

      BEGIN

        -- Archive old answer if there is one

        UPDATE PITEM SET "Status" = 1

        WHERE "PItem" = vAnswer."PItem";



        -- Archive old EPR notes (long text)

        UPDATE NOTEOVR

        SET "Deleted" = 1

        WHERE "Type" = 1

        AND "ParentId" IN (vAnswer."PItem");



        -- Clear Answer (create an empty row)

        INSERT INTO PITEM

        (

          "Patient", "FormCode", "FItem", "AnsType", "AnsYes",

          "AnsText", "AnsList", "AnsListDesc", "Date", "User",

          "Status", "AuditNumber", "AppUser", "AppDate", "AnsDate",

          "ASAType", "ASAScore", "PItem", "Time", "PForm",

          "PItemImg", "AnsListRefCode", "EntryDateTime", "AppDateTime","PItemCol"

        )

        VALUES

        (

          vPatient, vFormCode, vFormItemId, vAnswer."AnsType", -1,

          '', NULL, NULL, SYSDATE, vWebUserId,

          0, WEB_EPR_PKG.GetAuditNumber(vFormCode, vPatient, vPatientForm, vFormItemId), 0, NULL, NULL,

          0, 0, PITEM_PITEM_SEQ.nextval, vTime, vPatientForm,

          0, NULL, SYSDATE, NULL, vAnswer."PItemCol"

        );

      END;

    END LOOP;

  END;



  PROCEDURE resetspreadsheet(IN vinternetformid integer, IN vformitemid integer, IN vwebuserid integer) IS

    vPatient NUMBER(10);

    vFormCode  CHAR(6);

    vPatientForm NUMBER(10);

    vCount INTEGER;

    vPatientColumnId NUMBER(10);



    -- cursor to get default columns

    CURSOR cDefaultColumns(vfc IN CHAR, vpt IN NUMBER, vpf IN NUMBER) IS

    SELECT PIC."FItemCol", FIC."FItem", FIC."AnsType", FIC."AnsText", FIC."AnsList", FIC."AnsListDesc", FIC."AnsDate", MIN(PIC."Deleted") AS "Deleted"

    FROM PITEMCOL PIC

    JOIN FITEMCOL FIC ON PIC."FItemCol" = FIC."FItemCol"

    WHERE PIC."FormCode" = vfc

    AND PIC."Patient" = vpt

    AND PIC."PForm" = vpf

    AND PIC."FItemCol" > 0

    GROUP BY PIC."FItemCol", FIC."FItem", FIC."AnsType", FIC."AnsText", FIC."AnsList", FIC."AnsListDesc", FIC."AnsDate";



  BEGIN

    -- Get internet form data

    SELECT I."Patient", I."FormCode", I."PForm"

    INTO vPatient, vFormCode, vPatientForm

    FROM IPTFORM I

    WHERE "iPtForm" = vInternetFormId;



    -- create default column, if it is marked deleted

    FOR vItem IN cDefaultColumns(vFormCode, vPatient, vPatientForm) LOOP

      IF vItem."Deleted" = 1 THEN

        SELECT PITEMCOL_PITEMCOL_SEQ.nextVal INTO vPatientColumnId FROM DUAL;



        -- Add Column Data

        INSERT INTO PITEMCOL (

          "PItemCol", "FItemCol", "FormCode", "Patient", "PForm",

          "VariableColumn", "EntryDateTime", "Deleted", "DeletionDateTime", "OrgPItemCol"

        ) VALUES (

          vPatientColumnId, vItem."FItemCol", vFormCode, vPatient, vPatientForm,

          0, SYSDATE, 0, NULL, NULL

        );



        -- Add column header cell text

        INSERT INTO PITEM (

          "Patient", "FormCode", "FItem", "AnsType", "AnsYes",

          "AnsText", "AnsList", "AnsListDesc", "Date", "User",

          "Status", "AuditNumber", "AppUser", "AppDate", "AnsDate",

          "ASAType", "ASAScore", "PItem", "Time", "PForm",

          "PItemImg", "AnsListRefCode", "EntryDateTime", "AppDateTime", "PItemCol"

        )

        VALUES (

          vPatient, vFormCode, vItem."FItem", vItem."AnsType", NULL,

          vItem."AnsText", vItem."AnsList", vItem."AnsListDesc", SYSDATE, vWebUserId,

          0, WEB_EPR_PKG.GetAuditNumber(vFormCode, vPatient, vPatientForm, vFormItemId), 0, NULL, vItem."AnsDate",

          0, 0, PITEM_PITEM_SEQ.nextval, ((TO_NUMBER(TO_CHAR(SYSDATE,'HH24')) * 60) + TO_NUMBER(TO_CHAR(SYSDATE,'MI'))), vPatientForm,

          0, NULL, SYSDATE, NULL, vPatientColumnId

        );

      END IF;

    END LOOP;



    -- Archive any pending answers



    -- Update spreadsheet as NOT "On File"

    -- Archive existing answer to "Deleted"

    UPDATE PITEM SET "Status" = 1

    WHERE "FormCode" = vFormCode

    AND "Patient" = vPatient

    AND "PForm" = vPatientForm

    AND "FItem" = vFormItemId;

    -- Create a new record with NULL value

    INSERT INTO PITEM (

      "Patient", "FormCode", "FItem", "AnsType", "AnsYes", "AnsText", "AnsList", "AnsListDesc", "Date", "User",

      "Status", "AuditNumber", "AppUser", "AppDate", "AnsDate", "ASAType", "ASAScore", "PItem", "Time", "PForm",

      "PItemImg", "AnsListRefCode", "EntryDateTime", "AppDateTime", "PItemCol"

    )

    VALUES (

      vPatient, vFormCode, vFormItemId, 9, NULL, NULL, '', NULL, SYSDATE, vWebUserId,

      0, WEB_EPR_PKG.GetAuditNumber(vFormCode, vPatient, vPatientForm, vFormItemId), 0, NULL, NULL, 0, 0, PITEM_PITEM_SEQ.nextval, ((TO_NUMBER(TO_CHAR(SYSDATE,'HH24')) * 60) + TO_NUMBER(TO_CHAR(SYSDATE,'MI'))), vPatientForm,

      0, NULL, SYSDATE, NULL, 0

    );

  END;



  FUNCTION getauditnumber(vformcode character, vpatient numeric, vpatientform numeric, vformitemid integer) RETURN numeric IS

    vAuditNumber NUMBER(10);

  BEGIN

    SELECT NVL(MAX("AuditNumber"),0) + 1 INTO vAuditNumber

    FROM PITEM

    WHERE "FormCode" = vFormCode

    AND "Patient" = vPatient

    AND "PForm" = vPatientForm

    AND "FItem" = vFormItemId;



    RETURN vAuditNumber;

  END;



  FUNCTION getanswertext(vpatientformitemid integer) RETURN clob IS

    vCount INTEGER;

    vResult CLOB;



    CURSOR vOverRecords(vParentId IN INTEGER) IS

    SELECT * FROM NOTEOVR

    WHERE "Type" = 1

    AND "ParentId" = vParentId

    AND "Deleted" = 0

    ORDER BY "Order" ASC;



  BEGIN



    SELECT P."AnsText" INTO vResult

    FROM PITEM P

    WHERE P."PItem" = vPatientFormItemId;



    SELECT COUNT(1) INTO vCount FROM NOTEOVR WHERE "Type" = 1 AND "ParentId" = vPatientFormItemId;



    IF vCount > 0 THEN

      FOR vRecord IN vOverRecords(vPatientFormItemId) LOOP

        vResult := vResult || vRecord."Text";

      END LOOP;

    END IF;



    RETURN vResult;

  END;



  FUNCTION getanswertext(vpatientformitemid numeric) RETURN clob IS

  BEGIN

    RETURN GetAnswerText(vPatientFormItemId::INTEGER);

  END;



  FUNCTION getdefaultcolumnarchived(vformcolumnid integer, vpatientformid integer) RETURN integer IS

    vArchived INTEGER := 0;

  BEGIN

    SELECT "Deleted" INTO vArchived

    FROM (

      SELECT "Deleted"

      FROM PITEMCOL

      WHERE "FItemCol" = vFormColumnId

      AND "PForm" = vPatientFormId

      ORDER BY "PItemCol" DESC

    )

    WHERE ROWNUM = 1;



    RETURN vArchived;

  END;



  FUNCTION getdefaultcolumnarchived(vformcolumnid numeric, vpatientformid integer) RETURN integer IS

  BEGIN

    RETURN GetDefaultColumnArchived(vFormColumnId::INTEGER, vPatientFormId);

  END;



  PROCEDURE getdefaultfstatus(IN vinternetformid character varying, OUT vresult cursor_pkg.weakcursor) IS

    vFormCode  CHAR(6);

  BEGIN

    -- Get internet form Code

    SELECT I."FormCode" INTO vFormCode

    FROM IPTFORM I

    LEFT JOIN FORM F ON I."FormCode" = F."Code"

    WHERE "iPtForm" = vInternetFormId;





    OPEN vResult FOR

      SELECT

        F."FStatus"

      FROM FSTATUS F

      WHERE F."FormCode" = vFormCode

      AND F."IsDefault" = 1

			AND F."Inactive" != 1;



      EXCEPTION WHEN NO_DATA_FOUND THEN

        vResult := NULL;

  END;



	--

	PROCEDURE createaudithis(IN vuser numeric, IN vtablename character, IN vhistorytype numeric, OUT vaudithis numeric) IS

		vTime NUMBER(10) := (to_number(to_char(current_date,'HH24'))*60) + to_number(to_char(current_date,'MI'));  -- Is there a function already existing that can call here?

	BEGIN

			SELECT AUDITHIS_Audit_SEQ.NEXTVAL INTO vAuditHis FROM DUAL;



			INSERT INTO AUDITHIS("Audit", "Date", "Time", "User", "StationId", "TableName", "HistoryType")

								 VALUES(vAuditHis, TRUNC(SYSDATE), vTime, vUser, 0,  vTableName, vHistoryType);       --Insert a record in AUDITHIS table

	END;



  PROCEDURE createformaction(IN vpformid integer, IN vwebuserid integer, IN vfstatus character varying, OUT vformevt integer) IS

    vPFormEvt INTEGER;

    vAuditHis NUMBER(10);

  BEGIN

		-- Create AuditHis record

		CreateAudithis(vWebUserId, 'PFORMEVT', 1, vAuditHis);



	  --Get next PFORMEVT ID

    SELECT PFORMEVT_PFORMEVT_SEQ.nextval INTO vPFormEvt

    FROM DUAL;



    -- Insert into PFORMEVT

		INSERT INTO PFORMEVT

		(

			"PFormEvt",

			"PForm",

			"Audit",

			"FStatus",

			"AssignedUser",

			"AssignedUGroup",

			"Comment"

		)

    VALUES ( vPFormEvt, vPFormId, vAuditHis, vFStatus, 0, null, null);



    COMMIT;

    vFormEvt := vPFormEvt;

  END;



END;
CREATE OR REPLACE PACKAGE BODY web_message_pkg IS

-- stolen from message_pkg

  PROCEDURE add_message(IN senduser numeric, IN senddatetime timestamp without time zone, IN priority numeric, IN subject character varying, IN text clob, OUT messageid numeric, IN isautoreply numeric, IN hashvalue character varying, IN senderrespiuser numeric) IS



    v_Date			DATE;

    v_Time			NUMBER;

  

  BEGIN

  

    -- get message id

    SELECT MESSAGE_MESSAGE_SEQ.NEXTVAL INTO MessageId FROM DUAL;

    

    v_Date := trunc(SendDateTime);

    v_Time := (to_number(to_char(SendDateTime, 'HH24')) * 60) + (to_number(to_char(SendDateTime, 'MI')));

    

    -- insert message

    -- E45786, E77769, E129605

    INSERT INTO MESSAGE("Message", "Date", "Time", "Sender", "Subject", TEXT, 

        "Deleted", "Recipients", "IsPriority", "UMsgFld", "IsAutoReply", "CCRecipients", "HashValue", "SenderRespiUser")  

      VALUES (MessageId,            -- Message

              v_Date,               -- Date

              v_Time,               -- Time

              SendUser,             -- Sender

              Subject,              -- Subject

              TEXT,                 -- Text

              0,                    -- Deleted

              '',                   -- Recipients

              Priority,             -- IsPriority

              0,                    -- UMsgFld

              IsAutoReply,          -- IsAutoReply

              '',                   -- CCRecipients

              HashValue,            -- HashValue

              SenderRespiUser       -- SenderRespiIser 60202512

          );				



  END;





  /* Internal function to retrieve time zone offset (in minutes) based on station ID */

  FUNCTION gettimezoneoffset(vstationid integer) RETURN integer IS

    vIniDef INTEGER := 0;  

    vIniset INTEGER := 0;

    vTimeZoneOff INTEGER := 0;	

  BEGIN

    -- Look fo TimeZone offset in IniDef table

    BEGIN

      SELECT "Inidef", "Default"

      INTO vInidef, vTimeZoneOff

      FROM INIDEF WHERE "Key" = 'TimeZoneOffset';

      

      EXCEPTION WHEN NO_DATA_FOUND THEN 

        vInidef := 0;

        vTimeZoneOff := 0;

    END;

    

    -- If inidef is found

    IF vInidef > 0 AND vStationId > 0 THEN

      BEGIN

        -- Get Iniset from Iniset and only for active station	  

        SELECT INISET."Iniset"

        INTO vIniset

        FROM STATION, INISET

        WHERE STATION."Deleted" = '0'

        AND STATION."StationId" = INISET."Station"

        AND STATION."StationId" = vStationId;

        

        EXCEPTION WHEN NO_DATA_FOUND THEN

          vIniset := 0;

      END;

      

      IF vIniset > 0 THEN

        BEGIN

          -- Get offset from INIITEM table

          SELECT "ValueNum" 

          INTO vTimeZoneOff 

          FROM INIITEM 

          WHERE "Inidef" = vInidef 

          AND "Iniset" = vIniset;

          

          EXCEPTION WHEN NO_DATA_FOUND THEN

            vIniset := 0; -- just to do something

        END;

      END IF;

    END IF;

    RETURN vTimeZoneOff * 60; -- To convert to minutes

  END;

  

  /* Count number of unread messages in a folder for a given user. If folder id is not defined (-1), it counts messages in inbox and all folders. */

  PROCEDURE countnewmsgs(IN vuserid integer, IN vfolderid integer, OUT vcount integer) IS

  BEGIN

    IF vFolderId = -1 THEN

      -- case when folder ID = -1, to count all inbox   folders

      SELECT COUNT(1)

      INTO vCount

      FROM MSGSENT MS

      WHERE MS."Status" = 0

      AND MS."User" = vUserId;

    ELSE

      -- case when folder ID is defined. (0 = inbox, 1+ MSGSENT.UMsgFld)

      SELECT COUNT(1)

      INTO vCount

      FROM MSGSENT MS

      WHERE MS."Status" = 0

      AND MS."User" = vUserId

      AND MS."UMsgFld" = vFolderId;

    END IF;

  END;

  

  

  PROCEDURE gettimezoneoffset(IN vstationid integer, OUT voffset integer) IS

  BEGIN

    vOffset := GetTimeZoneOffset(vStationId);

  END;

  

  /* Count number of unread messages in a folder for a given patient. If folder id is not defined (-1), it counts messages in inbox and all folders. */

  /* Check Sender is not another patient */

  PROCEDURE countnewmsgspatient(IN vuserid integer, IN vfolderid integer, OUT vcount integer) IS

  BEGIN

    IF vFolderId = -1 THEN

      -- case when folder ID = -1, to count all inbox   folders

      SELECT COUNT(1)

	  INTO vCount

      FROM MESSAGE ME, MSGSENT MS, USERS UR

      WHERE ME."Message" = MS."Message"

      AND UR."User" = ME."Sender"      

      AND MS."Status" = 0

      AND MS."User" = vUserId;

    ELSE

      -- case when folder ID is defined. (0 = inbox, 1+ MSGSENT.UMsgFld)

      SELECT COUNT(1)

	  INTO vCount

      FROM MESSAGE ME, MSGSENT MS, USERS UR

      WHERE ME."Message" = MS."Message"

      AND UR."User" = ME."Sender"      

      AND MS."Status" = 0

      AND MS."User" = vUserId

      AND MS."UMsgFld" = vFolderId;

    END IF;

  END;



  /* Count number of unread urgent messages in a folder for a given user. If folder id is not defined (-1), it counts messages in inbox and all folders. */

  PROCEDURE countnewurgmsgs(IN vuserid integer, IN vfolderid integer, OUT vcount integer) IS

  BEGIN

    IF vFolderId = -1 THEN

      -- case when folder ID = -1, to count all inbox   folders

      SELECT COUNT(1)

      INTO vCount

      FROM MESSAGE ME, MSGSENT MS

      WHERE ME."Message" = MS."Message" 

      AND MS."Status" = 0

      AND MS."User" = vUserId

      AND ME."IsPriority" = 1;

    ELSE

      -- case when folder ID is defined. (0 = inbox, 1+ MSGSENT.UMsgFld)

      SELECT COUNT(1)

      INTO vCount

      FROM MESSAGE ME, MSGSENT MS

      WHERE ME."Message" = MS."Message" 

      AND MS."Status" = 0

      AND MS."User" = vUserId

      AND MS."UMsgFld" = vFolderId

      AND ME."IsPriority" = 1;

    END IF;

  END;

  

  /* Count number of messages in a folder for a given user. If folder id is not defined (-1), it counts messages in inbox and all folders. */

  PROCEDURE countmsgs(IN vuserid integer, IN vfolderid integer, OUT vcount integer) IS

  BEGIN

    IF vFolderId = -1 THEN

      -- case when folder ID = -1, to count all inbox   folders

      SELECT COUNT(1)

      INTO vCount

      FROM MSGSENT MS

      WHERE MS."Status" = 0

      AND MS."User" = vUserId;

    ELSE

      -- case when folder ID is defined. (0 = inbox, 1+ MSGSENT.UMsgFld)

      SELECT COUNT(1)

      INTO vCount

      FROM MSGSENT MS

      WHERE MS."Status" != 2

      AND MS."User" = vUserId

      AND MS."UMsgFld" = vFolderId;

    END IF;

  END;

  

  /* Count number of messages for Patients in a folder for a given user. If folder id is not defined (-1), it counts messages in inbox and all folders. */

  /* Check Sender is not a patient*/

  PROCEDURE countmsgspatients(IN vuserid integer, IN vfolderid integer, OUT vcount integer) IS

  BEGIN

    IF vFolderId = -1 THEN

      -- case when folder ID = -1, to count all inbox   folders

      SELECT COUNT(1)

	  INTO vCount

      FROM MESSAGE ME, MSGSENT MS, USERS UR

      WHERE ME."Message" = MS."Message"

      AND UR."User" = ME."Sender"      

      AND MS."Status" != 0

      AND MS."User" = vUserId;

    ELSE

      -- case when folder ID is defined. (0 = inbox, 1+ MSGSENT.UMsgFld)

      SELECT COUNT(1)

	  INTO vCount

      FROM MESSAGE ME, MSGSENT MS, USERS UR

      WHERE ME."Message" = MS."Message"

      AND UR."User" = ME."Sender"      

      AND MS."Status" != 2

      AND MS."User" = vUserId

      AND MS."UMsgFld" = vFolderId;

    END IF;

  END;

  

  /* Retrieve a list of folders for a user */

  PROCEDURE getfolderlist(IN vuserid integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

    SELECT

    "UMsgFld",

    "Folder",

    "FolderType",

    "User"

    FROM UMSGFLD

    WHERE "User" = vUserId

    ORDER BY "FolderType", "Folder" ASC;

    

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := null;

  END;

  

  /* Retrieve details of a folder */

  PROCEDURE getfolderdetail(IN vfolderid integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

    SELECT

    "UMsgFld",

    "Folder",

    "FolderType",

    "User"

    FROM UMSGFLD

    WHERE "UMsgFld" = vFolderId

    AND ROWNUM = 1;

    

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := null;

  END;

  

  /* Retrieve a list of urgent messages for a user. */

  PROCEDURE geturgmsglist(IN vuserid integer, IN vstationid integer, IN vorderby character varying, IN vitemsperpage integer, INOUT vpage integer, OUT vtotalpages integer, OUT vresult cursor_pkg.weakcursor) IS

    SqlStmt VARCHAR2(8000);

    vTimeZoneOffset INTEGER;

    vMaxRow INTEGER;

    vMinRow INTEGER;

  BEGIN

    vTimeZoneOffset := GetTimeZoneOffset(vStationId);

    

    --Count all items with matching criteria

    IF vItemsPerPage = 0 THEN

      vTotalPages := 0;

    ELSE

      SELECT CEIL(COUNT(1)/vItemsPerPage) INTO vTotalPages

      FROM MESSAGE ME, MSGSENT MS

      WHERE ME."Message" = MS."Message"

      AND ME."IsPriority" = 1

      AND MS."Status" != 2

      AND MS."User" = vUserId;

    END IF;

    

    IF vTotalPages < vPage THEN

    vPage := vTotalPages;

    ELSIF vPage < 1 THEN

    vPage := 1;

    END IF;

    

    vMaxRow := vPage * vItemsPerPage;

    vMinRow := (vPage - 1) * vItemsPerPage + 1; 

	

    -- AX-40515

    --Get all items within the page range

    SqlStmt := '

    SELECT A.* FROM

    (

      SELECT B.*, ROWNUM AS "RowNum" FROM

      (

        SELECT ME."Message",

        ME."Date" + ME."Time" / 1440 + :TimeZoneOffset / 1440 + (ME."Time" + :TimeZoneOffset)/(1440) AS "Date",

        ME."Sender",

        UR."Name" AS "SenderLastName",

        UR."First" AS "SenderFirstName",

        UR."Provider" AS "SenderProdCode",

		UR."User" AS "SenderUserId",

		UR."Patient" AS "SenderPatientId",

		ME."SenderRespiUser",

        ME."Subject",

        ME."Recipients",

        ME."CCRecipients",

        ME."IsPriority",

		ME."HashValue",

        ME."IsAutoReply",

        ME."Deleted",

        ME."UMsgFld",

        ME."Time",

        ME."TEXT",

        MS."Status"

        FROM MESSAGE ME, MSGSENT MS, MSG_USER_VIEW UR

        WHERE ME."Message" = MS."Message"

        AND UR."User" = ME."Sender"

        AND ME."IsPriority" = 1

        AND MS."Status" != 2

        AND (ME."Deleted" = 0 OR MS."Status" = 1)

        AND MS."User" = :UserId

    ';

    

    CASE  

       WHEN vOrderBy = 'DATE_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') ASC, ME."Message" ASC';

       WHEN vOrderBy = 'DATE_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'LASTNAME_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("SenderLastName" || "SenderFirstName")) ASC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'LASTNAME_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("SenderLastName" || "SenderFirstName")) DESC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'FIRSTNAME_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("SenderFirstName" || "SenderLastName")) ASC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'FIRSTNAME_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("SenderFirstName" || "SenderLastName")) DESC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'SUBJECT_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("Subject")) ASC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC';

       WHEN vOrderBy = 'SUBJECT_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("Subject")) DESC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC';

       WHEN vOrderBy = 'PRIORITY_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY "IsPriority" ASC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'PRIORITY_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY "IsPriority" DESC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

    END CASE;

    

    SQLStmt := SQLStmt || 

    ') B

       WHERE ROWNUM <= :MaxRow

    ) A

    WHERE "RowNum" >= :MinRow';

	

    --fill in data

    OPEN vResult 

    FOR SqlStmt 

    USING vTimeZoneOffset, vTimeZoneOffset,

      vUserId, 

      vMaxRow, vMinRow;

      

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;

  

  /* Retrieve a list of inbox messages for a user. */

  PROCEDURE getinboxmsglist(IN vuserid integer, IN vfolderid integer, IN vstationid integer, IN vorderby character varying, IN vitemsperpage integer, INOUT vpage integer, OUT vtotalpages integer, OUT vresult cursor_pkg.weakcursor) IS

  	SqlStmt VARCHAR2(8000);

    vTimeZoneOffset INTEGER;

    vMaxRow INTEGER;

    vMinRow INTEGER;

  BEGIN

    vTimeZoneOffset := GetTimeZoneOffset(vStationId);

    

    --Count all items with matching criteria

    IF vItemsPerPage = 0 THEN

      vTotalPages := 0;

    ELSE

      SELECT CEIL(COUNT(1)/vItemsPerPage) INTO vTotalPages

      FROM MESSAGE ME, MSGSENT MS, MSG_USER_VIEW UR

      WHERE ME."Message" = MS."Message"

      AND UR."User" = ME."Sender"

      AND MS."Status" != 2

      AND MS."User" = vUserId

      AND MS."UMsgFld" = vFolderId;

    END IF;

    

    IF vTotalPages < vPage THEN

    vPage := vTotalPages;

    ELSIF vPage < 1 THEN

    vPage := 1;

    END IF;

    

    vMaxRow := vPage * vItemsPerPage;

    vMinRow := (vPage - 1) * vItemsPerPage + 1; 

	

    -- AX-40515

    --Get all items within the page range

    SqlStmt := '

    SELECT A.* FROM

    (

      SELECT B.*, ROWNUM AS "RowNum" FROM

      (

        SELECT ME."Message",

        ME."Date" + ME."Time" / 1440 + :TimeZoneOffset / 1440 + (ME."Time" + :TimeZoneOffset)/(1440) AS "Date",

        ME."Sender",

        UR."Name" AS "SenderLastName",

        UR."First" AS "SenderFirstName",

        UR."Provider" AS "SenderProdCode",

		UR."User" AS "SenderUserId",

		UR."Patient" AS "SenderPatientId",

		ME."SenderRespiUser",

        ME."Subject",

        ME."Recipients",

        ME."CCRecipients",

        ME."IsPriority",

		ME."HashValue",

        ME."IsAutoReply",

        ME."Deleted",

        ME."UMsgFld",

        ME."Time",

        ME."TEXT",

        MS."Status"

        FROM MESSAGE ME, MSGSENT MS, MSG_USER_VIEW UR

        WHERE ME."Message" = MS."Message"

        AND UR."User" = ME."Sender"

        AND MS."Status" != 2

        AND (ME."Deleted" = 0 OR MS."Status" = 1)

        AND MS."User" = :UserId

        AND MS."UMsgFld" = :FolderId

    ';

    

    CASE  

       WHEN vOrderBy = 'DATE_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') ASC, ME."Message" ASC';

       WHEN vOrderBy = 'DATE_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'LASTNAME_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("SenderLastName" || "SenderFirstName")) ASC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'LASTNAME_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("SenderLastName" || "SenderFirstName")) DESC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'FIRSTNAME_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("SenderFirstName" || "SenderLastName")) ASC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'FIRSTNAME_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("SenderFirstName" || "SenderLastName")) DESC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'SUBJECT_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("Subject")) ASC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC';

       WHEN vOrderBy = 'SUBJECT_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("Subject")) DESC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC';

       WHEN vOrderBy = 'PRIORITY_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY "IsPriority" ASC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'PRIORITY_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY "IsPriority" DESC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

    END CASE;

    

    SQLStmt := SQLStmt || 

    ') B

       WHERE ROWNUM <= :MaxRow

    ) A

    WHERE "RowNum" >= :MinRow';



    --fill in data

    OPEN vResult 

    FOR SqlStmt 

    USING vTimeZoneOffset, vTimeZoneOffset,

      vUserId, vFolderId, 

      vMaxRow, vMinRow;

      

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;



  

  /* Retrieve a list of outbox messages for a user. */

  PROCEDURE getoutboxmsglist(IN vuserid integer, IN vfolderid integer, IN vstationid integer, IN vorderby character varying, IN vitemsperpage integer, INOUT vpage integer, OUT vtotalpages integer, OUT vresult cursor_pkg.weakcursor) IS

    SqlStmt VARCHAR2(8000);

    vTimeZoneOffset INTEGER;

    vMaxRow INTEGER;

    vMinRow INTEGER;

  BEGIN

    vTimeZoneOffset := GetTimeZoneOffset(vStationId);

    

    --Count all items with matching criteria

    IF vItemsPerPage = 0 THEN

      vTotalPages := 0;

    ELSE

      SELECT CEIL(COUNT(1)/vItemsPerPage) INTO vTotalPages

      FROM MESSAGE ME

      WHERE ME."Deleted" = 0

      AND ME."Sender" = vUserId

      AND ME."UMsgFld" = vFolderId;

    END IF;

    

    IF vTotalPages < vPage THEN

    vPage := vTotalPages;

    ELSIF vPage < 1 THEN

    vPage := 1;

    END IF;

    

    vMaxRow := vPage * vItemsPerPage;

    vMinRow := (vPage - 1) * vItemsPerPage + 1; 

	

    -- AX-40515

    --Get all items within the page range

    SqlStmt := '

    SELECT A.* FROM

    (

      SELECT B.*, ROWNUM AS "RowNum" FROM

      (

        SELECT ME."Message",

        ME."Date" + ME."Time" / 1440 + :TimeZoneOffset / 1440 + (ME."Time" + :TimeZoneOffset)/(1440) AS "Date",

        ME."Sender",

        UR."Name" AS "SenderLastName",

        UR."First" AS "SenderFirstName",

        UR."Provider" AS "SenderProdCode",

		UR."User" AS "SenderUserId",

		UR."Patient" AS "SenderPatientId",

		ME."SenderRespiUser",

        ME."Subject",

        ME."Recipients",

        ME."CCRecipients",

        ME."IsPriority",

		ME."HashValue",

        ME."IsAutoReply",

        ME."Deleted",

        ME."UMsgFld",

        (SELECT count(1) from msgsent where "Message" = ME."Message" AND "Status" = 0) as "Unread",

        ME."Time",

        ME."TEXT"

        FROM MESSAGE ME, MSG_USER_VIEW UR

        WHERE UR."User" = ME."Sender"

        AND ME."Deleted" = 0

        AND ME."Sender" = :UserId

        AND ME."UMsgFld" = :FolderId

    ';

    

    CASE  

       WHEN vOrderBy = 'DATE_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') ASC, ME."Message" ASC';

       WHEN vOrderBy = 'DATE_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'TO_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("Recipients")) ASC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'TO_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("Recipients" )) DESC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'CC_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("CCRecipients")) ASC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'CC_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("CCRecipients")) DESC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'SUBJECT_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("Subject")) ASC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC';

       WHEN vOrderBy = 'SUBJECT_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("Subject")) DESC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC';

       WHEN vOrderBy = 'PRIORITY_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY "IsPriority" ASC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'PRIORITY_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY "IsPriority" DESC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

    END CASE;

    

    SQLStmt := SQLStmt || 

    ') B

       WHERE ROWNUM <= :MaxRow

    ) A

    WHERE "RowNum" >= :MinRow';

	

    --fill in data

    OPEN vResult 

    FOR SqlStmt 

    USING vTimeZoneOffset, vTimeZoneOffset,

      vUserId, vFolderId, 

      vMaxRow, vMinRow;

      

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;

  

  

  /* Retrieve total messages and total unread messages */

  PROCEDURE gettotalinboxpatientmsg(IN vuserid integer, IN vfolderid integer, IN vstationid integer, INOUT vtotalmsg integer, OUT vtotalunread integer) IS

  BEGIN



    --Count total messages 

    SELECT COUNT(1) INTO vTotalMsg

        FROM MESSAGE ME, MSGSENT MS, USERS UR

        WHERE ME."Message" = MS."Message"

        AND UR."User" = ME."Sender"

        AND MS."Status" != 2

        AND MS."User" = vUserId

        AND MS."UMsgFld" = vFolderId;

    

    --Count total Unread messages 

    SELECT COUNT(1) INTO vTotalUnread

        FROM MESSAGE ME, MSGSENT MS, USERS UR

        WHERE ME."Message" = MS."Message"

        AND UR."User" = ME."Sender"

        AND MS."Status" = 0

        AND MS."User" = vUserId

        AND MS."UMsgFld" = vFolderId;



  END;

  

  

  /* Retrieve a list of inbox messages for a patients. (With pagination) */

  PROCEDURE getinboxpatientmsglist(IN vuserid integer, IN vfolderid integer, IN vstationid integer, IN vorderby character varying, IN vitemsperpage integer, INOUT vpage integer, OUT vtotalpages integer, OUT vresult cursor_pkg.weakcursor) IS

  	SqlStmt VARCHAR2(8000);

    vTimeZoneOffset INTEGER;

    vMaxRow INTEGER;

    vMinRow INTEGER;

  BEGIN

    vTimeZoneOffset := GetTimeZoneOffset(vStationId);



    --Count all items with matching criteria

    IF vItemsPerPage = 0 THEN

      vTotalPages := 0;

    ELSE

      SELECT CEIL(COUNT(1)/vItemsPerPage) INTO vTotalPages

        FROM MESSAGE ME, MSGSENT MS, USERS UR

        WHERE ME."Message" = MS."Message"

        AND UR."User" = ME."Sender"

        AND MS."Status" != 2

        AND MS."User" = vUserId

        AND MS."UMsgFld" = vFolderId;

    END IF;

    

    IF vTotalPages < vPage THEN

    vPage := vTotalPages;

    ELSIF vPage < 1 THEN

    vPage := 1;

    END IF;

    

    vMaxRow := vPage * vItemsPerPage;

    vMinRow := (vPage - 1) * vItemsPerPage + 1; 

	

    -- AX-40515

    --Get all items within the page range

    SqlStmt := '

    SELECT A.* FROM

    (

      SELECT B.*, ROWNUM AS "RowNum" FROM

      (

        SELECT ME."Message",

        ME."Date" + ME."Time" / 1440 + :TimeZoneOffset / 1440 + (ME."Time" + :TimeZoneOffset)/(1440) AS "Date",

        ME."Sender",

        UR."Name" AS "SenderLastName",

        UR."First" AS "SenderFirstName",

        UR."Preferred" AS "SenderPreferredName",

        UR."Producer" AS "SenderProdCode",

        UR."Deleted" AS "SenderDeleted",

        0 AS "SenderPatientId",

        ME."SenderRespiUser",

        ME."Subject",

        ME."Recipients",

        ME."CCRecipients",

        ME."IsPriority",

        ME."HashValue",

        ME."IsAutoReply",

        ME."Deleted",

        ME."UMsgFld",

        ME."Time",

        ME."TEXT",

        MS."Status"

        FROM MESSAGE ME, MSGSENT MS, USERS UR

        WHERE ME."Message" = MS."Message"

        AND UR."User" = ME."Sender"

        AND MS."Status" != 2

        AND MS."User" = :UserId

        AND MS."UMsgFld" = :FolderId

    ';

    

    CASE  

       WHEN vOrderBy = 'DATE_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') ASC, ME."Message" ASC';

       WHEN vOrderBy = 'DATE_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'LASTNAME_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("SenderLastName" || "SenderFirstName")) ASC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'LASTNAME_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("SenderLastName" || "SenderFirstName")) DESC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'FIRSTNAME_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("SenderFirstName" || "SenderLastName")) ASC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'FIRSTNAME_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("SenderFirstName" || "SenderLastName")) DESC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'SUBJECT_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("Subject")) ASC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC';

       WHEN vOrderBy = 'SUBJECT_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("Subject")) DESC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC';

       WHEN vOrderBy = 'PRIORITY_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY "IsPriority" ASC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'PRIORITY_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY "IsPriority" DESC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

    END CASE;



    SQLStmt := SQLStmt || 

    ') B

       WHERE ROWNUM <= :MaxRow

    ) A

    WHERE "RowNum" >= :MinRow';

    

    --fill in data

    OPEN vResult 

    FOR SqlStmt 

    USING vTimeZoneOffset, vTimeZoneOffset,

      vUserId, vFolderId,

      vMaxRow, vMinRow;

      

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;



  

  

  /* Retrieve a list of outbox messages for a Patient user. (With pagination) */

  PROCEDURE getoutboxpatientmsglist(IN vuserid integer, IN vfolderid integer, IN vstationid integer, IN vorderby character varying, IN vitemsperpage integer, INOUT vpage integer, OUT vtotalpages integer, OUT vresult cursor_pkg.weakcursor) IS

    SqlStmt VARCHAR2(8000);

    vTimeZoneOffset INTEGER;

    vMaxRow INTEGER;

    vMinRow INTEGER;

  BEGIN

    vTimeZoneOffset := GetTimeZoneOffset(vStationId);



    --Count all items with matching criteria

    IF vItemsPerPage = 0 THEN

      vTotalPages := 0;

    ELSE

      SELECT CEIL(COUNT(1)/vItemsPerPage) INTO vTotalPages

        FROM MESSAGE ME, IUSER UR, PATIENT PT

        WHERE UR."iUser" = ME."Sender"

        AND PT."Patient" = UR."Id"

        AND ME."Deleted" = 0

        AND ME."Sender" = vUserId

        AND ME."UMsgFld" = vFolderId

        AND ME."Message" NOT IN (SELECT MS."Message" FROM MSGSENT MS, IUSER UR2 WHERE MS."Message" = ME."Message" AND MS."User" = UR2."iUser");

    END IF;

    

    IF vTotalPages < vPage THEN

    vPage := vTotalPages;

    ELSIF vPage < 1 THEN

    vPage := 1;

    END IF;

    

    vMaxRow := vPage * vItemsPerPage;

    vMinRow := (vPage - 1) * vItemsPerPage + 1; 

	

    --AX-40515

    --Get all items within the page range

    SqlStmt := '

    SELECT A.* FROM

    (

      SELECT B.*, ROWNUM AS "RowNum" FROM

      (

        SELECT ME."Message",

        ME."Date" + ME."Time" / 1440 + :TimeZoneOffset / 1440 + (ME."Time" + :TimeZoneOffset)/(1440) AS "Date",

        ME."Sender",

        PT."Last" AS "SenderLastName",

        PT."First" AS "SenderFirstName",

        PT."Prefered" AS "SenderPreferredName",

        UR."Deleted" AS "SenderDeleted",

        PT."Patient" AS "SenderPatientId",

        ME."SenderRespiUser",

        ME."Subject",

        ME."Recipients",

        ME."CCRecipients",

        ME."IsPriority",

        ME."HashValue",

        ME."IsAutoReply",

        ME."Deleted",

        ME."UMsgFld",

        (SELECT count(1) from msgsent where "Message" = ME."Message" AND "Status" = 0) as "Unread",

        ME."Time",

        ME."TEXT"

        FROM MESSAGE ME, IUSER UR, PATIENT PT

        WHERE UR."iUser" = ME."Sender"

        AND PT."Patient" = UR."Id"

        AND ME."Deleted" = 0

        AND ME."Sender" = :UserId

        AND ME."UMsgFld" = :FolderId

        AND ME."Message" NOT IN (SELECT MS."Message" FROM MSGSENT MS, IUSER UR2 WHERE MS."Message" = ME."Message" AND MS."User" = UR2."iUser")		

    ';

    

    CASE  

       WHEN vOrderBy = 'DATE_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') ASC, ME."Message" ASC';

       WHEN vOrderBy = 'DATE_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'TO_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("Recipients")) ASC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'TO_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("Recipients" )) DESC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'CC_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("CCRecipients")) ASC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'CC_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("CCRecipients")) DESC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'SUBJECT_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("Subject")) ASC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC';

       WHEN vOrderBy = 'SUBJECT_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("Subject")) DESC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC';

       WHEN vOrderBy = 'PRIORITY_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY "IsPriority" ASC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

       WHEN vOrderBy = 'PRIORITY_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY "IsPriority" DESC, TO_CHAR("Date", ''YYYYMMDDHH24:MI:SSSSS'') DESC, ME."Message" DESC';

    END CASE;



    SQLStmt := SQLStmt || 

    ') B

       WHERE ROWNUM <= :MaxRow

    ) A

    WHERE "RowNum" >= :MinRow';

    

        

    --fill in data

    OPEN vResult 

    FOR SqlStmt 

    USING vTimeZoneOffset, vTimeZoneOffset,

      vUserId, vFolderId,

      vMaxRow, vMinRow;

      

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;



  /* Retrieve details of a message. */

  PROCEDURE getmsgdetail(IN vmessageid integer, IN vstationid integer, OUT vresult cursor_pkg.weakcursor) IS

    vTimeZoneOffset INTEGER;

  BEGIN

    vTimeZoneOffset := GetTimeZoneOffset(vStationId);

	

    -- AX-40515

    OPEN vResult FOR

    SELECT ME."Message",

    ME."Date" + ME."Time" / 1440 + vTimeZoneOffset / 1440 + (ME."Time" + vTimeZoneOffset)/(1440) AS "Date",

    ME."Sender",

    UR."First" AS "SenderFirstName",

    UR."Name" AS "SenderLastName",

    UR."Preferred" AS "SenderPreferredName",

    UR."Producer" AS "SenderProdCode",

    UR."Deleted" AS "SenderDeleted",

    NVL(PG."PGroup", ' ') AS "SenderPGroup",

    NVL(PG."Description",' ') AS "SenderPGroupDescription",

	ME."SenderRespiUser",

    0 AS "IsPatient",

    ME."Subject",

    ME."TEXT",

    ME."Recipients",

    ME."CCRecipients",

    ME."IsPriority",

    ME."HashValue",

    ME."IsAutoReply",

    ME."Deleted",

    ME."UMsgFld",

    (SELECT count(1) from msgsent where "Message" = ME."Message" AND "Status" = 0) as "Unread",

    ME."Time",

	UR."User" AS "SenderUserId",

	0 AS "SenderPatientId"

    FROM MESSAGE ME

    JOIN USERS UR ON ME."Sender" = UR."User"

    LEFT JOIN PRODUCER PR ON PR."Producer" = UR."Producer"

    LEFT JOIN PGROUP PG ON PG."PGroup" = PR."PGroup" AND PG."Inactive" = 0

    WHERE ME."Message" = vMessageId

    AND ROWNUM = 1

UNION ALL

SELECT ME."Message",

    ME."Date" + ME."Time" / 1440 + vTimeZoneOffset / 1440 + (ME."Time" + vTimeZoneOffset)/(1440) AS "Date",

    ME."Sender",

    P."First" AS "SenderFirstName",

    P."Last" AS "SenderLastName",

    P."Prefered" AS "SenderPreferredName",

    '' AS "SenderProdCode",

    P."Deleted" AS "SenderDeleted",

    '' AS "SenderPGroup",

    '' AS "SenderPGroupDescription",

	ME."SenderRespiUser",

    1 AS "IsPatient",

    ME."Subject",

    ME."TEXT",

    ME."Recipients",

    ME."CCRecipients",

    ME."IsPriority",

    ME."HashValue",

    ME."IsAutoReply",

    ME."Deleted",

    ME."UMsgFld",

    (SELECT count(1) from msgsent where "Message" = ME."Message" AND "Status" = 0) as "Unread",

    ME."Time",

	0 AS "SenderUserId",

	P."Patient" AS "SenderPatientId"

    FROM MESSAGE ME

    JOIN IUSER I ON ME."Sender" = I."iUser"

    JOIN PATIENT P ON I."Id" = P."Patient"

    WHERE ME."Message" = vMessageId

    AND ROWNUM = 1;

    

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := null;

  END;

  

  /* Retrieve a list of all recipients (to, cc, bcc) for a given message. */

  PROCEDURE getrecipientlist(IN vmessageid integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

    SELECT DISTINCT

    CASE WHEN TRIM(MS."UGroup") != 'None' THEN 0 ELSE MS."User" END AS "User",

    CASE WHEN TRIM(MS."UGroup") != 'None' THEN 0 ELSE UR."Deleted" END AS "Deleted",

    CASE WHEN TRIM(MS."UGroup") != 'None' THEN NULL ELSE UR."Name" END AS "LastName",

    CASE WHEN TRIM(MS."UGroup") != 'None' THEN NULL ELSE UR."First" END AS "FirstName",

    CASE WHEN TRIM(MS."UGroup") != 'None' THEN NULL ELSE UR."Preferred" END AS "PreferredName",

    CASE WHEN TRIM(MS."UGroup") != 'None' THEN NULL ELSE UR."Producer" END AS "ProdCode",

    CASE WHEN TRIM(MS."UGroup") != 'None' THEN 0 ELSE UR."Deleted" END AS "Deleted",

    CASE WHEN TRIM(MS."UGroup") != 'None' OR "ExpDate" IS NULL OR "ExpDate" >= TRUNC(SYSDATE) THEN 0 ELSE 1 END AS "Expired",

    NVL(PG."PGroup", ' ') AS "PGroup",

    NVL(PG."Description",' ') AS "PGroupDescription",

    MS."UGroup",

    UG."Description",

    MS."UMsgFld", -- TODO: This field does not belong in this procedure, and should be deleted. Verify MessageLib component and delete this item.

    MS."RecType" AS "DeliveryType", 

    CASE WHEN TRIM(MS."UGroup") != 'None' THEN 1 ELSE 0 END AS "RecipientType"

    FROM MSGSENT MS

    LEFT JOIN USERS UR ON MS."User" = UR."User"

    LEFT JOIN PRODUCER PR ON PR."Producer" = UR."Producer"

    LEFT JOIN PGROUP PG ON PG."PGroup" = PR."PGroup" AND PG."Inactive" = 0

    LEFT JOIN UGROUP UG ON MS."UGroup" = UG."UGroup"

    WHERE "Message" = vMessageId

    ORDER BY "LastName";

    

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;

  

  /* 51503413 Retrieve a list of recipients Users, Patients and Groups with recipient's full name (first name + last name) or group name starting with the given keyword. */

  PROCEDURE getallrecipientlist(IN vmessageid integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

    

    -- axiUm User

    SELECT

    UR."User",

    UR."Name" AS "LastName",

    UR."First" AS "FirstName",

    UR."Preferred" AS "PreferredName",

    UR."Producer" AS "ProdCode",

    UR."Deleted",

    CASE WHEN UR."ExpDate" IS NULL OR UR."ExpDate" >= TRUNC(SYSDATE) THEN 0 ELSE 1 END AS "Expired",

    NVL(PG."PGroup", ' ') AS "PGroup",

    NVL(PG."Description",' ') AS "PGroupDescription", -- PGROUP.Description

    '' AS "UGroup",

    '' AS "Description",

    0 AS "RecipientType",

    MS."UMsgFld", -- TODO: This field does not belong in this procedure, and should be deleted. Verify MessageLib component and delete this item.

    MS."RecType" AS "DeliveryType",

    0 AS "PatientId"

    FROM MSGSENT MS

    JOIN MESSAGE ME ON MS."Message" = ME."Message"

    LEFT JOIN USERS UR ON MS."User" = UR."User"

    LEFT JOIN PRODUCER PR ON PR."Producer" = UR."Producer"

    LEFT JOIN PGROUP PG ON PG."PGroup" = PR."PGroup" AND PG."Inactive" = 0

    WHERE MS."Message" = vMessageId

    AND (ME."Deleted" = 0 OR MS."Status" = 1)

    AND UR."User" != 0

    AND MS."UGroup" = 'None'

    

    UNION

    

    -- Group 

    SELECT

    0 AS "User",

    '' AS "LastName",

    '' AS "FirstName",

    '' AS "PreferredName",

    '' AS "ProdCode",

    0 AS "Deleted",

    0 AS "Expired",

    '' AS "PGroup",

    '' AS "PGroupDescription",

    UG."UGroup",

    UG."Description",

    1 AS "RecipientType",

    MS."UMsgFld", -- TODO: This field does not belong in this procedure, and should be deleted. Verify MessageLib component and delete this item.

    MS."RecType" AS "DeliveryType",

    0 AS "PatientId"	

    FROM MSGSENT MS

    LEFT JOIN UGROUP UG ON MS."UGroup" = UG."UGroup"

    WHERE MS."Message" = vMessageId

    AND UG."UGroup" IS NOT NULL



    UNION

    

    -- Patient

    SELECT

    I."iUser" AS "User",

    P."Last" AS "LastName",

    P."First" AS "FirstName",

    P."Prefered" AS "PreferredName",

    '' AS "ProdCode",

    P."Deleted",

    0 AS "Expired",

    '' AS "PGroup",

    '' AS "PGroupDescription",

    '' AS "UGroup",

    '' AS "Description",

    0 AS "RecipientType",

    MS."UMsgFld", -- TODO: This field does not belong in this procedure, and should be deleted. Verify MessageLib component and delete this item.

    MS."RecType" AS "DeliveryType",

    I."Id" AS "PatientId"	

    FROM MSGSENT MS 

    JOIN MESSAGE ME ON MS."Message" = ME."Message"	

    LEFT JOIN IUSER I ON MS."User" = I."iUser"	

    JOIN PATIENT P ON I."Id" = P."Patient"

    WHERE MS."Message" = vMessageId

	AND (ME."Deleted" = 0 OR MS."Status" = 1)

    AND I."iUser" != 0

    

    ORDER BY "FirstName", "LastName", "UGroup";

        

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;

    

  

  /* Retrieve a list of all Group type recipients available in axiUm system */

  PROCEDURE getgrouplist(IN vorderby character varying, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

    SELECT

    "UGroup",

    "Description"

    FROM UGROUP

    ORDER BY

    CASE WHEN 'ID_ASC' = vOrderBy THEN "UGroup" END ASC, 

    CASE WHEN 'ID_DESC' = vOrderBy THEN "UGroup" END DESC,

    CASE WHEN 'DESC_ASC' = vOrderBy THEN "Description" END ASC,

    CASE WHEN 'DESC_DESC' = vOrderBy THEN "Description" END DESC;

    

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;

  

  /* Retrieve details for a User type recipient */

  PROCEDURE getuserdetail(IN vuserid integer, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

    SELECT

    UR."User",

    UR."Deleted",

    UR."Name" AS "LastName",

    UR."First" AS "FirstName",

    UR."Preferred" AS "PreferredName",

    UR."Producer" AS "ProdCode",

    UR."Deleted",

    NVL(PG."PGroup", ' ') AS "PGroup",

    NVL(PG."Description",' ') AS "PGroupDescription",

    CASE WHEN UR."ExpDate" IS NULL OR UR."ExpDate" >= TRUNC(SYSDATE) THEN 0 ELSE 1 END AS "Expired",

    0 AS "PatientId"

    FROM USERS UR

    LEFT JOIN PRODUCER PR ON PR."Producer" = UR."Producer"

    LEFT JOIN PGROUP PG ON PG."PGroup" = PR."PGroup" AND PG."Inactive" = 0

    WHERE UR."User" = vUserId

    AND ROWNUM = 1

	

	UNION

	

    SELECT

    I."iUser" AS "User",

    P."Deleted",

    P."Last" AS "LastName",

    P."First" AS "FirstName",

    P."Prefered" AS "PreferredName",

    '' AS "ProdCode",

    P."Deleted",

    '' AS "PGroup",

    '' AS "PGroupDescription",

    0 AS "Expired",

    P."Patient" AS "PatientId"

    FROM IUSER I

	JOIN PATIENT P ON I."Id" = P."Patient"

	WHERE I."iUser" = vUserId

	AND ROWNUM = 1;

    

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;

  

  /* Retrieve details for a Group type recipient */

  PROCEDURE getgroupdetail(IN vgroupid character, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

    SELECT

    "UGroup",

    "Description"

    FROM UGROUP

    WHERE "UGroup" = vGroupId

    AND ROWNUM = 1;

    

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;

  

  /* Retrieve a list of recipients with recipient's full name (first name + last name) or group name starting with the given keyword. */

  PROCEDURE getmatchingrecipientlist(IN vkeyword character varying, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

    SELECT

    UR."User",

    UR."Name" AS "LastName",

    UR."First" AS "FirstName",

    UR."Preferred" AS "PreferredName",

    UR."Producer" AS "ProdCode",

    UR."Deleted",

    CASE WHEN UR."ExpDate" IS NULL OR UR."ExpDate" >= TRUNC(SYSDATE) THEN 0 ELSE 1 END AS "Expired",

    NVL(PG."PGroup", ' ') AS "PGroup",

    NVL(PG."Description",' ') AS "PGroupDescription",

    '' AS "UGroup",

    '' AS "Description",

    0 AS "RecipientType",

    0 AS "PatientId"

    FROM USERS UR

    LEFT JOIN PRODUCER PR ON PR."Producer" = UR."Producer"

    LEFT JOIN PGROUP PG ON PG."PGroup" = PR."PGroup" AND PG."Inactive" = 0

    WHERE UPPER(TRIM(UR."First") || ' ' || TRIM(UR."Name")) LIKE UPPER(TRIM(vKeyword)) || '%'

    

    UNION

    

    SELECT

    0 AS "User",

    '' AS "LastName",

    '' AS "FirstName",

    '' AS "PreferredName",

    '' AS "ProdCode",

    0 AS "Deleted",

    0 AS "Expired",

    '' AS "PGroup",

    '' AS "PGroupDescription",

    "UGroup",

    "Description",

    1 AS "RecipientType",

    0 AS "PatientId"

    FROM UGROUP

    WHERE UPPER(TRIM("Description")) LIKE UPPER(TRIM(vKeyword)) || '%'



    UNION

	

    SELECT

    I."iUser" AS "User",

    P."Last" AS "LastName",

    P."First" AS "FirstName",

    P."Prefered" AS "PreferredName",

    '' AS "ProdCode",

    P."Deleted",

    0 AS "Expired",

    '' AS "PGroup",

    '' AS "PGroupDescription",

    '' AS "UGroup",

    '' AS "Description",

    0 AS "RecipientType",

    I."Id" AS "PatientId"

    FROM IUSER I

    JOIN PATIENT P ON I."Id" = P."Patient"

    WHERE UPPER(TRIM("First") || ' ' || TRIM("Last")) LIKE UPPER(TRIM(vKeyword)) || '%'

    

    ORDER BY "FirstName", "LastName", "UGroup";

    

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := NULL;

  END;

  

  /* Update inbox message's status to "Read" if the message is not marked "Deleted" */

  PROCEDURE markmsgread(IN vmessageid integer, IN vuserid integer) IS

  BEGIN

    UPDATE MSGSENT

    SET "Status" = 1

    WHERE "Message" = vMessageId

    AND "User" = vUserId

    AND "Status" = 0;

    

    COMMIT;

  END;

  

  /* Move inbox message from current folder to targeted folder */

  PROCEDURE moveinboxmsg(IN vmessageid integer, IN vuserid integer, IN vtargetfolderid integer) IS

  BEGIN

    UPDATE MSGSENT

    SET "UMsgFld" = vTargetFolderId

    WHERE "Message" = vMessageId

    AND "User" = vUserId;

    

    COMMIT;

  END;

  

  /* Move sent (outbox) message from current folder to targeted folder */

  PROCEDURE moveoutboxmsg(IN vmessageid integer, IN vtargetfolderid integer, IN vhash character varying) IS

  BEGIN

    UPDATE MESSAGE

    SET "UMsgFld" = vTargetFolderId,

        "HashValue" = vHash

    WHERE "Message" = vMessageId;

    

    COMMIT;

  END;

  

  /* Update inbox message's status to "Deleted" */

  PROCEDURE deleteinboxmsg(IN vmessageid integer, IN vuserid integer) IS

  BEGIN

    UPDATE MSGSENT

    SET "Status" = 2

    WHERE "Message" = vMessageId

    AND "User" = vUserId;

  END;

  

  /* Update sent (outbox) message's status to "Deleted" */

  PROCEDURE deleteoutboxmsg(IN vmessageid integer, IN vhash character varying) IS

  BEGIN

    UPDATE MESSAGE

    SET "Deleted" = 1,

        "HashValue" = vHash	

    WHERE "Message" = vMessageId;

    

    COMMIT;

  END;

  

  /* Create a new message using MESSAGE_PKG.ADD_MESSAGE, and SYSDATE */

  PROCEDURE createnewmsg(IN vuserid integer, IN vpriority integer, IN vsubject character varying, IN vtext clob, IN vdate timestamp without time zone, IN vhash character varying, IN vsenderrespiuser integer, OUT vmessageid integer) IS

  BEGIN

    ADD_MESSAGE(vUserId, vDate, vPriority, vSubject, vText, vMessageId, 0, vHash, vSenderRespiUser);

    COMMIT;

  END;

  

  /* Add a User type recipient to a given message using MESSAGE_PKG.ADD_RECIPIENT_USER or MESSAGE_PKG.ADD_RECIPIENT_STRING. */

  PROCEDURE adduser(IN vmessageid integer, IN vuserid integer, IN vdeliverytype integer) IS

    vCount INTEGER;

    vRecipientName VARCHAR2(128);

  BEGIN

    vRecipientName := MESSAGE_PKG.GET_USER_NAME(1, vUserId);

    IF NOT (TRIM(vRecipientName) IS NULL OR LENGTH(TRIM(vRecipientName)) = 0) THEN

      BEGIN

        SELECT COUNT(*) INTO vCount FROM MSGSENT WHERE "Message" = vMessageId AND "User" = vUserId;

        --If there are no duplicates in the recipient list create send a message to the user (appends to recipient string internally)

        IF vCount = 0 THEN

          MESSAGE_PKG.ADD_RECIPIENT_USER( vMessageId, vUserId, vDeliveryType);

        --If there are duplicates in the recipient list, append name to the recipient string

        ELSIF vDeliveryType = 0 THEN

          MESSAGE_PKG.ADD_RECIPIENT_STRING( vMessageId, vRecipientName);

        --If there are duplicates in the recipient list, append name to the cc recipient list

        ELSIF vDeliveryType = 1 THEN

          MESSAGE_PKG.ADD_CC_STRING( vMessageId, vRecipientName);

        END IF;

      END;

    END IF;

    COMMIT;

  END;

  

  /* Add a Group type recipient to a given message using MESSAGE_PKG.ADD_RECIPIENT_UGROUP */

  PROCEDURE addgroup(IN vmessageid integer, IN vgroupid character, IN vdeliverytype integer) IS

  BEGIN

    MESSAGE_PKG.ADD_RECIPIENT_UGROUP(vMessageId, TRIM(vGroupId), vDeliveryType);

    COMMIT;

  END;

  

  

  -- 49217375 Procedure to return a list of axiUm users that meet a search criteria. The search is based on a LIKE comparison.

  PROCEDURE docontactsearch(IN vpatientid integer, IN vsearchtypelevel character varying, IN vsearchstring character varying, IN vallowappointprov integer, IN vallowprov integer, IN vallowfaculty integer, IN vallowadmin integer, IN vcontactarray character varying, IN vsearchon integer, IN vorderby character varying, IN vitemsperpage integer, INOUT vpage integer, OUT vtotalpages integer, OUT results_cur cursor_pkg.weakcursor) IS

    SQLStmt VARCHAR2(4000);

    vMaxRow INTEGER;

    vMinRow INTEGER;

	vUnion INTEGER;

  BEGIN	

    

	vUnion := 0;

    -- Count total pages

    SQLStmt := 

      'SELECT CEIL(COUNT(1) / :1) FROM (';

    IF (vSearchTypeLevel = 'ANY' OR vSearchTypeLevel = 'PROVIDERS') AND (vAllowAppointProv = 1 OR vAllowProv = 1) THEN

      IF vAllowProv = 1 THEN

        SQLStmt := SQLStmt || '	  

          SELECT DISTINCT 

            US."User" 

          FROM USERS US 

            JOIN PTPROD PT ON PT."Producer" = US."Producer"

            --JOIN SLEVEL SL ON US."Level" = SL."SLevel"

          WHERE 1=1

            AND PT."Patient" = :2

            AND PT."Deleted" = 0

            AND (PT."StartDate" <= TRUNC(SYSDATE) OR PT."StartDate" IS NULL)

            AND (PT."EndDate" >= TRUNC(SYSDATE) OR PT."EndDate" IS NULL)

            --AND SL."Deleted" = 0

            AND US."Deleted" = 0

            AND (US."ExpDate" >= TRUNC(SYSDATE) OR US."ExpDate" IS NULL)

        ';

        IF vSearchOn = 0 THEN

          SQLStmt := SQLStmt || 'AND UPPER(TRIM(US."First")) LIKE UPPER(TRIM(:3)) || ''%'' ';

        ELSIF vSearchOn = 1 THEN

          SQLStmt := SQLStmt || 'AND UPPER(TRIM(US."Name")) LIKE UPPER(TRIM(:3)) || ''%'' ';

        ELSIF vSearchOn = 2 THEN

          SQLStmt := SQLStmt || 'AND US."User" = to_number(TRIM(:3))';

        END IF;

        IF vContactArray IS NOT NULL THEN

          SQLStmt := SQLStmt || 'AND US."User" IN (' || vContactArray || ')';		-- ReplyAll and IUSER.MsgAccess is 0, Only USERS in Message be displayed

        END IF;

        vUnion := 1;

      END IF;  -- End if of vAllowProv = 1

      IF vAllowProv = 1 AND vAllowAppointProv = 1 THEN

	    SQLStmt := SQLStmt || 'UNION';

      END IF;

	  IF vAllowAppointProv = 1 THEN

        SQLStmt := SQLStmt || '		

          SELECT DISTINCT 

            US."User"

          FROM USERS US 

            JOIN APPOINT AP ON (AP."Producer" = US."Producer") OR (AP."Assistant" = US."Producer")

            --JOIN SLEVEL SL ON US."Level" = SL."SLevel"

          WHERE 1=1

            AND AP."Patient" = :4

            AND (AP."Type" = 0 OR AP."Type" = 1 OR AP."Type" = 2)

            --AND SL."Deleted" = 0

            AND US."Deleted" = 0

            AND (US."ExpDate" >= TRUNC(SYSDATE) OR US."ExpDate" IS NULL)

            AND NOT (TRIM(US."Producer") IS NULL OR LENGTH(TRIM(US."Producer")) = 0)

          ';

        IF vSearchOn = 0 THEN

          SQLStmt := SQLStmt || 'AND UPPER(TRIM(US."First")) LIKE UPPER(TRIM(:5)) || ''%'' ';

        ELSIF vSearchOn = 1 THEN

          SQLStmt := SQLStmt || 'AND UPPER(TRIM(US."Name")) LIKE UPPER(TRIM(:5)) || ''%'' ';

        ELSIF vSearchOn = 2 THEN

          SQLStmt := SQLStmt || 'AND US."User" = to_number(TRIM(:5))';

        END IF;		

        IF vContactArray IS NOT NULL THEN

          SQLStmt := SQLStmt || 'AND US."User" IN (' || vContactArray || ')';		-- ReplyAll and IUSER.MsgAccess is 0, Only USERS in Message be displayed

        END IF;

        SQLStmt := SQLStmt || 'GROUP BY  US."User", US."First", US."Name", AP."Patient"';

        vUnion := vUnion + 1;

      END IF;  -- Enf if of vAllowAppointProv = 1

    END IF;  -- End if of vSearchTypeLevel = Providers

	

    IF vSearchTypeLevel = 'ANY' AND vUnion > 0 AND vAllowFaculty = 1 THEN

      SQLStmt := SQLStmt || ' UNION ';

    END IF;

	

    IF (vSearchTypeLevel = 'ANY' OR vSearchTypeLevel = 'FACULTY') AND vAllowFaculty = 1 THEN 

       SQLStmt := SQLStmt || '

          SELECT DISTINCT 

            US."User"

          FROM USERS US 

            JOIN PTFACUL PT ON PT."Faculty" = US."User"

            --JOIN SLEVEL SL ON US."Level" = SL."SLevel"

          WHERE 1=1

            AND PT."Patient" = :6

            AND PT."Deleted" = 0

            --AND SL."Deleted" = 0

            AND US."Deleted" = 0

            AND (US."ExpDate" >= TRUNC(SYSDATE) OR US."ExpDate" IS NULL)

        ';

      IF vSearchOn = 0 THEN

        SQLStmt := SQLStmt || 'AND UPPER(TRIM(US."First")) LIKE UPPER(TRIM(:7)) || ''%'' ';

      ELSIF vSearchOn = 1 THEN

        SQLStmt := SQLStmt || 'AND UPPER(TRIM(US."Name")) LIKE UPPER(TRIM(:7)) || ''%'' ';

      ELSIF vSearchOn = 2 THEN

        SQLStmt := SQLStmt || 'AND US."User" = to_number(TRIM(:7))';

      END IF;

      IF vContactArray IS NOT NULL THEN

        SQLStmt := SQLStmt || 'AND US."User" IN (' || vContactArray || ')';		-- ReplyAll and IUSER.MsgAccess is 0, Only USERS in Message be displayed

      END IF;

      SQLStmt := SQLStmt || 'GROUP BY US."User"';

      vUnion := vUnion + 1;

    END IF;  -- End if of vSearchTypeLevel = Faculty

	

    IF vSearchTypeLevel = 'ANY' AND vUnion > 0 AND vAllowAdmin = 1 THEN

      SQLStmt := SQLStmt || ' UNION ';

    END IF;

	

    IF (vSearchTypeLevel = 'ANY' OR vSearchTypeLevel = 'ADMINISTRATORS') AND vAllowAdmin = 1 THEN 

       SQLStmt := SQLStmt || '

          SELECT DISTINCT 

            US."User"

          FROM USERS US 

            JOIN PTMANAGE PT ON PT."User" = US."User"			

            --JOIN SLEVEL SL ON US."Level" = SL."SLevel"

          WHERE 1=1

            AND PT."Patient" = :8

            AND PT."Deleted" = 0

            --AND SL."Deleted" = 0

            AND US."Deleted" = 0

            AND (US."ExpDate" >= TRUNC(SYSDATE) OR US."ExpDate" IS NULL)

        ';

      IF vSearchOn = 0 THEN

        SQLStmt := SQLStmt || 'AND UPPER(TRIM(US."First")) LIKE UPPER(TRIM(:9)) || ''%'' ';

      ELSIF vSearchOn = 1 THEN

        SQLStmt := SQLStmt || 'AND UPPER(TRIM(US."Name")) LIKE UPPER(TRIM(:9)) || ''%'' ';

      ELSIF vSearchOn = 2 THEN

        SQLStmt := SQLStmt || 'AND US."User" = to_number(TRIM(:9))';

      END IF;

      IF vContactArray IS NOT NULL THEN

        SQLStmt := SQLStmt || 'AND US."User" IN (' || vContactArray || ')';		-- ReplyAll and IUSER.MsgAccess is 0, Only USERS in Message be displayed

      END IF;

      vUnion := vUnion + 1;

    END IF;  -- End if of vSearchTypeLevel = Administrators

	

    SQLStmt := SQLStmt || ')';

    BEGIN 

      IF vUnion = 4 THEN

        EXECUTE IMMEDIATE SQLStmt INTO vTotalPages USING vItemsPerPage, vPatientId, vSearchString, vPatientId, vSearchString, vPatientId, vSearchString, vPatientId, vSearchString;

      ELSIF vUnion = 3 THEN	

        EXECUTE IMMEDIATE SQLStmt INTO vTotalPages USING vItemsPerPage, vPatientId, vSearchString, vPatientId, vSearchString, vPatientId, vSearchString;

      ELSIF vUnion = 2 THEN	

        EXECUTE IMMEDIATE SQLStmt INTO vTotalPages USING vItemsPerPage, vPatientId, vSearchString, vPatientId, vSearchString;

      ELSE 

        EXECUTE IMMEDIATE SQLStmt INTO vTotalPages USING vItemsPerPage, vPatientId, vSearchString;

      END IF;

      EXCEPTION WHEN NO_DATA_FOUND THEN vTotalPages := 0;

    END;



    IF vTotalPages < vPage THEN

      vPage := vTotalPages;

    ELSIF vPage < 1 THEN

      vPage := 1;

    END IF;

	

    vMaxRow := vPage * vItemsPerPage;

    vMinRow := (vPage - 1) * vItemsPerPage + 1; 

    ------------------------------------------------------------

    ------   Get Contact for one page

    ------------------------------------------------------------

	vUnion := 0;



    SQLStmt := '

    SELECT A.* FROM

    (

      SELECT B.*, ROWNUM AS "RowNum" FROM

      (';

	    SQLStmt := SQLStmt || 'SELECT * FROM (';

		  

      IF (vSearchTypeLevel = 'ANY' OR vSearchTypeLevel = 'PROVIDERS') AND (vAllowAppointProv = 1 OR vAllowProv = 1) THEN

        IF vAllowProv = 1 THEN

          SQLStmt := SQLStmt || '	  

          SELECT DISTINCT 

            US."User", 

            US."First",

            US."Name",

            --SL."Description",

            PT."Patient" AS "Patient",

            ''Provider'' AS "TypeLevel"

          FROM USERS US 

            JOIN PTPROD PT ON PT."Producer" = US."Producer"

            --JOIN SLEVEL SL ON US."Level" = SL."SLevel"

          WHERE 1=1

            AND PT."Patient" = :1

            AND PT."Deleted" = 0

            AND (PT."StartDate" <= TRUNC(SYSDATE) OR PT."StartDate" IS NULL)

            AND (PT."EndDate" >= TRUNC(SYSDATE) OR PT."EndDate" IS NULL)

            --AND SL."Deleted" = 0

            AND US."Deleted" = 0

            AND (US."ExpDate" >= TRUNC(SYSDATE) OR US."ExpDate" IS NULL)

          ';

          IF vSearchOn = 0 THEN

            SQLStmt := SQLStmt || 'AND UPPER(TRIM(US."First")) LIKE UPPER(TRIM(:2)) || ''%'' ';

          ELSIF vSearchOn = 1 THEN

            SQLStmt := SQLStmt || 'AND UPPER(TRIM(US."Name")) LIKE UPPER(TRIM(:2)) || ''%'' ';

          ELSIF vSearchOn = 2 THEN

            SQLStmt := SQLStmt || 'AND US."User" = to_number(TRIM(:2))';

          END IF;

          IF vContactArray IS NOT NULL THEN

            SQLStmt := SQLStmt || 'AND US."User" IN (' || vContactArray || ')';		-- ReplyAll and IUSER.MsgAccess is 0, Only USERS in Message be displayed

          END IF;

          vUnion := 1;

	    END IF;  -- End if of vAllowProv = 1

        IF vAllowProv = 1 AND vAllowAppointProv = 1 THEN

	      SQLStmt := SQLStmt || 'UNION';

        END IF;

        IF vAllowAppointProv = 1 THEN

          SQLStmt := SQLStmt || '

            SELECT DISTINCT 

              US."User", 

              US."First",

              US."Name",

              --SL."Description",

              AP."Patient" AS "Patient",

              ''Provider'' AS "TypeLevel"

            FROM USERS US 

              JOIN APPOINT AP ON (AP."Producer" = US."Producer") OR (AP."Assistant" = US."Producer")

              --JOIN SLEVEL SL ON US."Level" = SL."SLevel"

            WHERE 1=1

              AND AP."Patient" = :3

              AND (AP."Type" = 0 OR AP."Type" = 1 OR AP."Type" = 2)

              --AND SL."Deleted" = 0

              AND US."Deleted" = 0

              AND (US."ExpDate" >= TRUNC(SYSDATE) OR US."ExpDate" IS NULL)

              AND NOT (TRIM(US."Producer") IS NULL OR LENGTH(TRIM(US."Producer")) = 0)

            ';

          IF vSearchOn = 0 THEN

            SQLStmt := SQLStmt || 'AND UPPER(TRIM(US."First")) LIKE UPPER(TRIM(:4)) || ''%'' ';

          ELSIF vSearchOn = 1 THEN

            SQLStmt := SQLStmt || 'AND UPPER(TRIM(US."Name")) LIKE UPPER(TRIM(:4)) || ''%'' ';

          ELSIF vSearchOn = 2 THEN

            SQLStmt := SQLStmt || 'AND US."User" = to_number(TRIM(:4))';

          END IF;		

          IF vContactArray IS NOT NULL THEN

            SQLStmt := SQLStmt || 'AND US."User" IN (' || vContactArray || ')';		-- ReplyAll and IUSER.MsgAccess is 0, Only USERS in Message be displayed

          END IF;

          SQLStmt := SQLStmt || 'GROUP BY  US."User", US."First", US."Name", AP."Patient"';

          vUnion := vUnion + 1;

        END IF;  -- Enf if of vAllowAppointProv = 1

      END IF;  -- End if of vSearchTypeLevel = Providers



      IF vSearchTypeLevel = 'ANY' AND vUnion > 0 AND vAllowFaculty = 1 THEN

        SQLStmt := SQLStmt || ' UNION ';

      END IF;

    

      IF (vSearchTypeLevel = 'ANY' OR vSearchTypeLevel = 'FACULTY') AND vAllowFaculty = 1 THEN 

         SQLStmt := SQLStmt || '	  

          SELECT DISTINCT 

            US."User", 

            US."First",

            US."Name",

            --SL."Description",

            PT."Patient" AS "Patient",

            ''Faculty'' AS "TypeLevel"

          FROM USERS US 

            JOIN PTFACUL PT ON PT."Faculty" = US."User"

            --JOIN SLEVEL SL ON US."Level" = SL."SLevel"

          WHERE 1=1

            AND PT."Patient" = :5

            AND PT."Deleted" = 0

            --AND SL."Deleted" = 0

            AND US."Deleted" = 0

            AND (US."ExpDate" >= TRUNC(SYSDATE) OR US."ExpDate" IS NULL)

        ';

        IF vSearchOn = 0 THEN

          SQLStmt := SQLStmt || 'AND UPPER(TRIM(US."First")) LIKE UPPER(TRIM(:6)) || ''%'' ';

        ELSIF vSearchOn = 1 THEN

          SQLStmt := SQLStmt || 'AND UPPER(TRIM(US."Name")) LIKE UPPER(TRIM(:6)) || ''%'' ';

        ELSIF vSearchOn = 2 THEN

          SQLStmt := SQLStmt || 'AND US."User" = to_number(TRIM(:6))';

        END IF;

        IF vContactArray IS NOT NULL THEN

           SQLStmt := SQLStmt || 'AND US."User" IN (' || vContactArray || ')';		-- ReplyAll and IUSER.MsgAccess is 0, Only USERS in Message be displayed

        END IF;

        vUnion := vUnion + 1;

      END IF;  -- End if of vSearchTypeLevel = Faculty



      IF vSearchTypeLevel = 'ANY' AND vUnion > 0 AND vAllowAdmin = 1 THEN

        SQLStmt := SQLStmt || ' UNION ';

      END IF;

    

      IF (vSearchTypeLevel = 'ANY' OR vSearchTypeLevel = 'ADMINISTRATORS') AND vAllowAdmin = 1 THEN 

         SQLStmt := SQLStmt || '	  

          SELECT DISTINCT 

            US."User", 

            US."First",

            US."Name",

            --SL."Description",

            PT."Patient" AS "Patient",

            ''Administrator'' AS "TypeLevel"

          FROM USERS US 

            JOIN PTMANAGE PT ON PT."User" = US."User"			

            --JOIN SLEVEL SL ON US."Level" = SL."SLevel"

          WHERE 1=1

            AND PT."Patient" = :7

            AND PT."Deleted" = 0

            --AND SL."Deleted" = 0

            AND US."Deleted" = 0

            AND (US."ExpDate" >= TRUNC(SYSDATE) OR US."ExpDate" IS NULL)

        ';

        IF vSearchOn = 0 THEN

          SQLStmt := SQLStmt || 'AND UPPER(TRIM(US."First")) LIKE UPPER(TRIM(:8)) || ''%'' ';

        ELSIF vSearchOn = 1 THEN

          SQLStmt := SQLStmt || 'AND UPPER(TRIM(US."Name")) LIKE UPPER(TRIM(:8)) || ''%'' ';

        ELSIF vSearchOn = 2 THEN

          SQLStmt := SQLStmt || 'AND US."User" = to_number(TRIM(:8))';

        END IF;

        IF vContactArray IS NOT NULL THEN

           SQLStmt := SQLStmt || 'AND US."User" IN (' || vContactArray || ')';		-- ReplyAll and IUSER.MsgAccess is 0, Only USERS in Message be displayed

        END IF;

        vUnion := vUnion + 1;

      END IF;  -- End if of vSearchTypeLevel = Administrators

	SQLStmt := SQLStmt || ')';

	SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("Name" || "First")) ASC';

--    CASE  

--       WHEN vOrderBy = 'LASTNAME_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("Name" || "First")) ASC, UPPER(TRIM("TypeLevel")) DESC';

--       WHEN vOrderBy = 'LASTNAME_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("Name" || "First")) DESC, UPPER(TRIM("TypeLevel")) DESC';

--       WHEN vOrderBy = 'FIRSTNAME_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("First" || "Name")) ASC, UPPER(TRIM("TypeLevel")) DESC';

--       WHEN vOrderBy = 'FIRSTNAME_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("First" || "Name")) DESC, UPPER(TRIM("TypeLevel")) DESC';

--       WHEN vOrderBy = 'TYPE_ASC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("TypeLevel")) ASC, UPPER(TRIM("First" || "Name")) DESC';

--       WHEN vOrderBy = 'TYPE_DESC' THEN SQLStmt := SQLStmt || ' ORDER BY UPPER(TRIM("TypeLevel")) DESC, UPPER(TRIM("First" || "Name")) DESC';

--    END CASE;

	

    SQLStmt := SQLStmt || 

    ') B

       WHERE ROWNUM <= :MaxRow

    ) A

    WHERE "RowNum" >= :MinRow';

	

    BEGIN 

      IF vUnion = 4 THEN

        OPEN results_cur FOR SQLStmt USING vPatientId, vSearchString, vPatientId, vSearchString, vPatientId, vSearchString, vPatientId, vSearchString, vMaxRow, vMinRow;

      ELSIF vUnion = 3 THEN

        OPEN results_cur FOR SQLStmt USING vPatientId, vSearchString, vPatientId, vSearchString, vPatientId, vSearchString, vMaxRow, vMinRow;

      ELSIF vUnion = 2 THEN	

        OPEN results_cur FOR SQLStmt USING vPatientId, vSearchString, vPatientId, vSearchString, vMaxRow, vMinRow;

      ELSE 

        OPEN results_cur FOR SQLStmt USING vPatientId, vSearchString, vMaxRow, vMinRow;

      END IF;

    EXCEPTION WHEN NO_DATA_FOUND THEN

      results_cur := NULL;

    END;

  END;

      

  -- 49218451 Procedure to return a list of Type Level for the axiUm user

  PROCEDURE douserlevels(IN vuserid integer, OUT results_cur cursor_pkg.weakcursor) IS

    SQLStmt VARCHAR2(4000);

  BEGIN	

	SQLStmt := '

      SELECT 

        US."User", 

        US."Producer",

        US."First",

        US."Name",

        SL."Description"

      FROM USERS US 

        JOIN SLEVEL SL ON US."Level" = SL."SLevel"

      WHERE 1=1

        AND SL."Deleted" = 0

        AND US."Deleted" = 0

        AND (US."ExpDate" >= TRUNC(SYSDATE) OR US."ExpDate" IS NULL)

        AND US."User" = :1

      ORDER BY US."First", US."Name" ASC

    ';

	BEGIN 

		OPEN results_cur FOR SQLStmt USING vUserId;

	EXCEPTION WHEN NO_DATA_FOUND THEN

		results_cur := NULL;

	END;

  END;



  -- 52923761 Procedure return Status for MessageId and UserId

  PROCEDURE getmsgstatusbyuser(IN vmessageid integer, IN vuserid integer, OUT vstatus integer) IS

  BEGIN

    SELECT MS."Status" INTO vStatus

    FROM MSGSENT MS 

    WHERE MS."Message" = vMessageId AND MS."User" = vUserId;

  EXCEPTION WHEN NO_DATA_FOUND THEN

    vStatus := 2;	-- Not exit then Return Deleted status 

  END;

  

  -- 51503855 Procedure return MsgEncryption parameter from AxiumOpt table

  PROCEDURE getmsgencryptaxiumparam(OUT vmsgencryptparam integer) IS

  BEGIN

    SELECT "MsgEncryption" INTO vMsgEncryptParam FROM AXIUMOPT WHERE ROWNUM = 1;

  EXCEPTION WHEN NO_DATA_FOUND THEN

    vMsgEncryptParam := 1;	-- All messages Encrypted

  END;



  ---------------------------------------------------------------------------------------------------------

-- get the patient's name by id

-- Format: 1=First Last   2=Last, First   

FUNCTION get_patient_name(format numeric, patientid numeric) RETURN character varying IS



	v_Name VARCHAR2(1024);

	v_Chart PATIENT."Chart"%TYPE;



BEGIN



	SELECT MESSAGE_PKG.FORMAT_NAME(Format, "First", "Middle", "Last"), "Chart"

	  INTO v_Name, v_Chart

	  FROM PATIENT

	 WHERE "Patient" = PatientId;

	 

	 --v_Name := v_Name || ' (' || TRIM(v_Chart) || ')';

	 

	 RETURN v_Name;



EXCEPTION WHEN OTHERS THEN

	RETURN '';

END;



  ------------------------------------------------------------------------------------------------------

  -- 51503855 AddRecipientPatient add Patient User as a recipient to a message, for other user AddUser()

  PROCEDURE addrecipientpatient(IN vmessageid integer, IN vuserid integer, IN vdeliverytype integer, IN vpatientid integer) IS

	v_Count			NUMBER;

	v_Recipient		VARCHAR2(128);

    v_PatId         NUMBER;

  BEGIN



	-- check if message has already been sent to this user

	SELECT COUNT(1) INTO v_Count FROM MSGSENT WHERE "Message" = vMessageId AND "User" = vUserId;

	if v_Count = 0 then

	  begin

		  BEGIN

	        SELECT "Id" INTO v_PatId FROM IUSER WHERE "iUser" = vPatientId;	   

		    -- build recipient string

		    v_Recipient := GET_PATIENT_NAME(1, v_PatId); -- v_Recipient := GET_PATIENT_NAME(1, vPatientId);

			-- add recipient name to message recipients string

			IF vDeliveryType = 0 THEN

				MESSAGE_PKG.ADD_RECIPIENT_STRING(vMessageId, v_Recipient);

			ELSIF vDeliveryType = 1 THEN

				MESSAGE_PKG.ADD_CC_STRING(vMessageId, v_Recipient);

			END IF;

		  END;



	  	-- add MSGSENT record

	  	-- E45786, E45786.2, E87150

	  	INSERT INTO MSGSENT("Message", "User", "UGroup", "Status", "UMsgFld", "RecType")

	  		VALUES (vMessageId, vUserId, 'None', 0, 0, vDeliveryType);

	  end;

	end if;

	

  EXCEPTION WHEN OTHERS THEN

	RETURN;

  END;

  

  PROCEDURE getrecentusers(IN vuserid integer, IN vnumberofrows integer, IN vorderby character varying, OUT vresult cursor_pkg.weakcursor) IS

  BEGIN

    OPEN vResult FOR

    SELECT * FROM

    (

      SELECT 

        UR."User", 

        UR."Producer",

        UR."First", 

        UR."Name", 

        NVL(PG."PGroup", ' ') AS "PGroup", 

        NVL(PG."Description", ' ') AS "Description",

        D1."Date"

      FROM

      (

        SELECT

          MS."User",

          MAX(TO_CHAR(ME."Date", 'YYYYMMDD') || ' ' || ME."Time") AS "Date"

        FROM MESSAGE ME

        JOIN MSGSENT MS ON ME."Message" = MS."Message" AND MS."UGroup" = 'None'

        WHERE ME."Sender" = vUserId

        GROUP BY MS."User"

        ORDER BY "Date" DESC

      ) D1

      JOIN USERS UR ON D1."User" = UR."User" -- Filters out IUSER entries

      LEFT JOIN PRODUCER PR ON UR."Producer" = PR."Producer"

      LEFT JOIN PGROUP PG ON PR."PGroup" = PG."PGroup"

      WHERE ROWNUM <= vNumberOfRows

    )

    ORDER BY 

      CASE WHEN vOrderBy = 'DATE_ASC' THEN "Date" END ASC,

      CASE WHEN vOrderBy = 'DATE_DESC' THEN "Date" END DESC,

      CASE WHEN vOrderBy = 'NAME_FIRST_ASC' THEN UPPER("First" || "Name" || "User") END ASC,

      CASE WHEN vOrderBy = 'NAME_FIRST_DESC' THEN UPPER("First" || "Name" || "User") END DESC,

      CASE WHEN vOrderBy = 'NAME_LAST_ASC' THEN UPPER("Name" || "First" || "User") END ASC,

      CASE WHEN vOrderBy = 'NAME_LAST_DESC' THEN UPPER("Name" || "First" || "User") END DESC,

      CASE WHEN vOrderBy = 'PGROUP_FIRST_ASC' THEN UPPER("Description" || "First" || "Name" || "User") END ASC,

      CASE WHEN vOrderBy = 'PGROUP_FIRST_DESC' THEN UPPER("Description" || "First" || "Name" || "User") END DESC,

      CASE WHEN vOrderBy = 'PGROUP_LAST_ASC' THEN UPPER("Description" || "Name" || "First" || "User") END ASC,

      CASE WHEN vOrderBy = 'PGROUP_LAST_DESC' THEN UPPER("Description" || "Name" || "First" || "User") END DESC,

      CASE WHEN vOrderBy = 'PRODUCER_FIRST_ASC' THEN UPPER("Producer" || "First" || "Name" || "User") END ASC,

      CASE WHEN vOrderBy = 'PRODUCER_FIRST_DESC' THEN UPPER("Producer" || "First" || "Name" || "User") END DESC,

      CASE WHEN vOrderBy = 'PRODUCER_LAST_ASC' THEN UPPER("Producer" || "Name" || "First" || "User") END ASC,

      CASE WHEN vOrderBy = 'PRODUCER_LAST_DESC' THEN UPPER("Producer" || "Name" || "First" || "User") END DESC;

  END;



  PROCEDURE searchusers(IN vsearchtype integer, IN vsearchkeyword character varying, IN vorderby character varying, IN vnumberofrows integer, INOUT vpagenumber integer, OUT vtotalpagenumber integer, OUT vresult cursor_pkg.weakcursor) IS

    

    vMaxRow INTEGER;

    vMinRow INTEGER;

    

  BEGIN

    

    --

    -- Get total number of items matching the description into a counter

    --

    SELECT CEIL(COUNT(1) / vNumberOfRows) INTO vTotalPageNumber

    FROM USERS UR

    LEFT JOIN PRODUCER PR ON PR."Producer" = UR."Producer"

    LEFT JOIN PGROUP PG ON PG."PGroup" = PR."PGroup" AND PG."Inactive" = 0

    WHERE UR."Deleted" = 0

    AND (UR."ExpDate" >= TRUNC(SYSDATE) OR UR."ExpDate" IS NULL)

    AND (

      (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0) -- case when keyword is blank, display all

      OR (vSearchType = 0 AND UPPER(TRIM(UR."First")) LIKE UPPER(TRIM(vSearchKeyword)) || '%')

      OR (vSearchType = 1 AND UPPER(TRIM(UR."Name")) LIKE UPPER(TRIM(vSearchKeyword)) || '%')

      OR (vSearchType = 2 AND UPPER(TRIM(PG."Description")) LIKE UPPER(TRIM(vSearchKeyword)) || '%')

      OR (vSearchType = 3 AND UPPER(TRIM(PR."Producer")) LIKE UPPER(TRIM(vSearchKeyword)) || '%')

    );

    

    --

    -- Get number of rows to get based on page number and items per page

    --

    IF vTotalPageNumber < vPageNumber THEN

      vPageNumber := vTotalPageNumber;

    ELSIF vPageNumber < 1 THEN

      vPageNumber := 1;

    END IF;

    

    vMaxRow := vPageNumber * vNumberOfRows;

    vMinRow := (vPageNumber - 1) * vNumberOfRows + 1; 

    

    --

    -- Retrieve data

    --

    OPEN vResult FOR

    SELECT D1.* FROM

    (

      SELECT D2.*, ROWNUM AS "RowNum" FROM

      (

      

        -- Start search

        SELECT 

          UR."User",

          UR."Producer",

          UR."First",

          UR."Name",

          NVL(PG."PGroup", ' ') AS "PGroup",

          NVL(PG."Description",' ') AS "Description" -- PGROUP.Description

        FROM USERS UR

        LEFT JOIN PRODUCER PR ON PR."Producer" = UR."Producer"

        LEFT JOIN PGROUP PG ON PG."PGroup" = PR."PGroup" AND PG."Inactive" = 0

        WHERE UR."Deleted" = 0

        AND (UR."ExpDate" >= TRUNC(SYSDATE) OR UR."ExpDate" IS NULL)

        AND (

          (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0) -- case when keyword is blank, display all

          OR (vSearchType = 0 AND UPPER(TRIM(UR."First")) LIKE UPPER(TRIM(vSearchKeyword)) || '%')

          OR (vSearchType = 1 AND UPPER(TRIM(UR."Name")) LIKE UPPER(TRIM(vSearchKeyword)) || '%')

          OR (vSearchType = 2 AND UPPER(TRIM(PG."Description")) LIKE UPPER(TRIM(vSearchKeyword)) || '%')

          OR (vSearchType = 3 AND UPPER(TRIM(PR."Producer")) LIKE UPPER(TRIM(vSearchKeyword)) || '%')

        )

        ORDER BY

          CASE WHEN vOrderBy = 'NAME_FIRST_ASC' THEN UPPER("First" || "Name" || "User") END ASC,

          CASE WHEN vOrderBy = 'NAME_FIRST_DESC' THEN UPPER("First" || "Name" || "User") END DESC,

          CASE WHEN vOrderBy = 'NAME_LAST_ASC' THEN UPPER("Name" || "First" || "User") END ASC,

          CASE WHEN vOrderBy = 'NAME_LAST_DESC' THEN UPPER("Name" || "First" || "User") END DESC,

          CASE WHEN vOrderBy = 'PGROUP_FIRST_ASC' THEN UPPER("Description" || "First" || "Name" || "User") END ASC,

          CASE WHEN vOrderBy = 'PGROUP_FIRST_DESC' THEN UPPER("Description" || "First" || "Name" || "User") END DESC,

          CASE WHEN vOrderBy = 'PGROUP_LAST_ASC' THEN UPPER("Description" || "Name" || "First" || "User") END ASC,

          CASE WHEN vOrderBy = 'PGROUP_LAST_DESC' THEN UPPER("Description" || "Name" || "First" || "User") END DESC,

          CASE WHEN vOrderBy = 'PRODUCER_FIRST_ASC' THEN UPPER(UR."Producer" || "First" || "Name" || "User") END ASC,

          CASE WHEN vOrderBy = 'PRODUCER_FIRST_DESC' THEN UPPER(UR."Producer" || "First" || "Name" || "User") END DESC,

          CASE WHEN vOrderBy = 'PRODUCER_LAST_ASC' THEN UPPER(UR."Producer" || "Name" || "First" || "User") END ASC,

          CASE WHEN vOrderBy = 'PRODUCER_LAST_DESC' THEN UPPER(UR."Producer" || "Name" || "First" || "User") END DESC

        

      

      ) D2

      WHERE ROWNUM <= vMaxRow

    ) D1

    WHERE "RowNum" >= vMinRow;

    

  END;

  

  PROCEDURE searchgroups(IN vsearchtype integer, IN vsearchkeyword character varying, IN vorderby character varying, IN vnumberofrows integer, INOUT vpagenumber integer, OUT vtotalpagenumber integer, OUT vresult cursor_pkg.weakcursor) IS



    vMaxRow INTEGER;

    vMinRow INTEGER;

    

  BEGIN

    

    --

    -- Get total number of items matching the description into a counter

    --

    

    SELECT CEIL(COUNT(1) / vNumberOfRows) INTO vTotalPageNumber

    FROM UGROUP

    WHERE (

      (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0) -- case when keyword is blank, display all

      OR (vSearchType = 0 AND UPPER(TRIM("UGroup")) LIKE UPPER(TRIM(vSearchKeyword)) || '%')

      OR (vSearchType = 1 AND UPPER(TRIM("Description")) LIKE UPPER(TRIM(vSearchKeyword)) || '%')

    );

    

    --

    -- Get number of rows to get based on page number and items per page

    --

    IF vTotalPageNumber < vPageNumber THEN

      vPageNumber := vTotalPageNumber;

    ELSIF vPageNumber < 1 THEN

      vPageNumber := 1;

    END IF;

    

    vMaxRow := vPageNumber * vNumberOfRows;

    vMinRow := (vPageNumber - 1) * vNumberOfRows + 1; 

    

    --

    -- Retrieve data

    --

    OPEN vResult FOR

    SELECT D1.* FROM

    (

      SELECT D2.*, ROWNUM AS "RowNum" FROM

      (

      

        -- Start search

        SELECT 

          UG."UGroup",

          UG."Description"

        FROM UGROUP UG

        WHERE (

          (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0) -- case when keyword is blank, display all

          OR (vSearchType = 0 AND UPPER(TRIM("UGroup")) LIKE UPPER(TRIM(vSearchKeyword)) || '%')

          OR (vSearchType = 1 AND UPPER(TRIM("Description")) LIKE UPPER(TRIM(vSearchKeyword)) || '%')

        )

        ORDER BY

          CASE WHEN vOrderBy = 'CODE_ASC' THEN UPPER("UGroup" || "Description") END ASC,

          CASE WHEN vOrderBy = 'CODE_DESC' THEN UPPER("UGroup" || "Description") END DESC,

          CASE WHEN vOrderBy = 'NAME_ASC' THEN UPPER("Description" || "UGroup") END ASC,

          CASE WHEN vOrderBy = 'NAME_DESC' THEN UPPER("Description" || "UGroup") END DESC

          

      ) D2

      WHERE ROWNUM <= vMaxRow

    ) D1

    WHERE "RowNum" >= vMinRow;

    

  END;

  

  PROCEDURE searchpatients(IN vsearchtype integer, IN vsearchkeyword character varying, IN vorderby character varying, IN vnumberofrows integer, IN vuserid integer, INOUT vpagenumber integer, OUT vtotalpagenumber integer, OUT vresult cursor_pkg.weakcursor) IS



    vIsPtRestrict INTEGER;

    vMaxRow INTEGER;

    vMinRow INTEGER;

    vProvCode VARCHAR2(10);

    vMsgAccess INTEGER;

  BEGIN

  

    SELECT SL."IsPtRestrict", UR."Producer", UR."MsgAccess"

    INTO vIsPtRestrict, vProvCode, vMsgAccess

    FROM USERS UR

    JOIN SLEVEL SL ON UR."Level" = SL."SLevel"

    WHERE UR."User" = vUserId

    AND ROWNUM = 1;

	

    --

    -- Get total number of items matching the description into a counter

    -- AX-24316

    SELECT CEIL(COUNT(1) / vNumberOfRows) INTO vTotalPageNumber

    FROM MSG_USER_VIEW U 

    JOIN IUSER IU ON U."User" = IU."iUser"

    JOIN PATIENT P ON U."Patient" = P."Patient"

    WHERE 

    (

      U."Patient" > 0 

      AND vMsgAccess > 0

      AND 

      (

        0 IN

        ( 

          SELECT COUNT(1) 

          FROM PTTYPES 

          WHERE PTTYPES."Patient" = U."Patient" 

          AND PTTYPES."Deleted" = 0

        )  

        OR EXISTS

        (

          SELECT 'x' 

          FROM pttypes PT,patacces PA,users US 

          WHERE PT."Patient" = U."Patient" 

          AND PT."Deleted" = 0 

          AND PT."PatType" = PA."PatType" 

          AND PA."SLevel" = US."Level" 

          AND US."User" = vUserId 

          AND PA."Patients" = 1

        )

      )

    )

    AND

    (

      vIsPtRestrict = 0

      OR

      (

        1 IN

        (

          SELECT COUNT(1) 

          FROM PTPROD 

          WHERE PTPROD."Patient" = U."Patient" 

          AND PTPROD."Producer" = vProvCode 

          AND PTPROD."Deleted" = 0 

          AND TRUNC(SYSDATE) >= PTPROD."StartDate" 

          AND TRUNC(SYSDATE) <= PTPROD."EndDate"

        ) 

        OR U."IsFreeAccess" = 1 

      ) 

    )

    AND (

      (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0) -- case when keyword is blank, display all

      OR (vSearchType = 0 AND UPPER(TRIM(U."First")) LIKE UPPER(TRIM(vSearchKeyword)) || '%')

      OR (vSearchType = 1 AND UPPER(TRIM(U."Name")) LIKE UPPER(TRIM(vSearchKeyword)) || '%')

      OR (vSearchType = 2 AND UPPER(TRIM(P."Chart")) LIKE UPPER(TRIM(vSearchKeyword)) || '%')

    );

    

    --

    -- Get number of rows to get based on page number and items per page

    --

    IF vTotalPageNumber < vPageNumber THEN

      vPageNumber := vTotalPageNumber;

    ELSIF vPageNumber < 1 THEN

      vPageNumber := 1;

    END IF;

    

    vMaxRow := vPageNumber * vNumberOfRows;

    vMinRow := (vPageNumber - 1) * vNumberOfRows + 1; 

    

    --

    -- Retrieve data

    --

    OPEN vResult FOR

    SELECT D1.* FROM

    (

      SELECT D2.*, ROWNUM AS "RowNum" FROM

      (

        -- Start search

        -- AX-24316

        SELECT 

          IU."iUser", 

          U."Name", 

          U."First",

          P."Chart",

          U."Patient"

        FROM MSG_USER_VIEW U 

        JOIN IUSER IU ON U."User" = IU."iUser"

        JOIN PATIENT P ON U."Patient" = P."Patient"

        WHERE 

        (

          U."Patient" > 0 

          AND vMsgAccess > 0

          AND 

          (

            0 IN

            ( 

              SELECT COUNT(1) 

              FROM PTTYPES 

              WHERE PTTYPES."Patient" = U."Patient" 

              AND PTTYPES."Deleted" = 0

            )  

            OR EXISTS

            (

              SELECT 'x' 

              FROM pttypes PT,patacces PA,users US 

              WHERE PT."Patient" = U."Patient" 

              AND PT."Deleted" = 0 

              AND PT."PatType" = PA."PatType" 

              AND PA."SLevel" = US."Level" 

              AND US."User" = vUserId 

              AND PA."Patients" = 1

            )

          )

        )

        AND

        (

          vIsPtRestrict = 0

          OR

          (

            1 IN

            (

              SELECT COUNT(1) 

              FROM PTPROD 

              WHERE PTPROD."Patient" = U."Patient" 

              AND PTPROD."Producer" = vProvCode 

              AND PTPROD."Deleted" = 0 

              AND TRUNC(SYSDATE) >= PTPROD."StartDate" 

              AND TRUNC(SYSDATE) <= PTPROD."EndDate"

            ) 

            OR U."IsFreeAccess" = 1 

          ) 

        )

        AND (

          (TRIM(vSearchKeyword) IS NULL OR LENGTH(TRIM(vSearchKeyword)) = 0) -- case when keyword is blank, display all

          OR (vSearchType = 0 AND UPPER(TRIM(U."First")) LIKE UPPER(TRIM(vSearchKeyword)) || '%')

          OR (vSearchType = 1 AND UPPER(TRIM(U."Name")) LIKE UPPER(TRIM(vSearchKeyword)) || '%')

          OR (vSearchType = 2 AND UPPER(TRIM(P."Chart")) LIKE UPPER(TRIM(vSearchKeyword)) || '%')

        )

        ORDER BY

          CASE WHEN vOrderBy = 'NAME_FIRST_ASC' THEN UPPER(U."First" || "Name" || "iUser") END ASC,

          CASE WHEN vOrderBy = 'NAME_FIRST_DESC' THEN UPPER(U."First" || "Name" || "iUser") END DESC,

          CASE WHEN vOrderBy = 'NAME_LAST_ASC' THEN UPPER("Name" || U."First" || "iUser") END ASC,

          CASE WHEN vOrderBy = 'NAME_LAST_DESC' THEN UPPER("Name" || U."First" || "iUser") END DESC,

          CASE WHEN vOrderBy = 'CHART_FIRST_ASC' THEN UPPER("Chart" || U."First" || "Name" || "iUser") END ASC,

          CASE WHEN vOrderBy = 'CHART_FIRST_DESC' THEN UPPER("Chart" || U."First" || "Name" || "iUser") END DESC,

          CASE WHEN vOrderBy = 'CHART_LAST_ASC' THEN UPPER("Chart" || "Name" || U."First" || "iUser") END ASC,

          CASE WHEN vOrderBy = 'CHART_LAST_DESC' THEN UPPER("Chart" || "Name" || U."First" || "iUser") END DESC

      

      ) D2

      WHERE ROWNUM <= vMaxRow

    ) D1

    WHERE "RowNum" >= vMinRow;

  END;



  PROCEDURE cansendmessagetopatient(IN vuserid integer, OUT vresult integer) IS

  BEGIN

    SELECT "MsgAccess" INTO vResult FROM USERS WHERE "User" = vUserId;

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vResult := 0;

  END;

  

  PROCEDURE cansendmessagetouser(IN vsenderuserid integer, IN vrecipientuserid integer, OUT vresult integer) IS

  BEGIN

	SELECT

	CASE

	-- Provider

	WHEN EXISTS (

	  SELECT 1 

	  FROM USERS US 

	  JOIN PTPROD PT ON PT."Producer" = US."Producer"

      JOIN IUSER IU ON PT."Patient" = IU."Id"

	  WHERE 1=1

	  AND IU."iUser" = vSenderUserId

	  AND US."User" = vRecipientUserId

	  AND PT."Deleted" = 0

	  AND (PT."StartDate" <= TRUNC(SYSDATE) OR PT."StartDate" IS NULL)

	  AND (PT."EndDate" >= TRUNC(SYSDATE) OR PT."EndDate" IS NULL)

	  AND (US."ExpDate" >= TRUNC(SYSDATE) OR US."ExpDate" IS NULL)

	  AND US."Deleted" = 0

	) THEN 1

	-- Appointment

	WHEN EXISTS (

	  SELECT 1

	  FROM USERS US 

	  JOIN APPOINT AP ON (AP."Producer" = US."Producer") OR (AP."Assistant" = US."Producer")

      JOIN IUSER IU ON AP."Patient" = IU."Id"

	  WHERE 1=1

	  AND IU."iUser" = vSenderUserId

	  AND US."User" = vRecipientUserId

	  AND AP."Type" IN (0,1,2,5,6,10) -- Active, Checked In, Checked Out, Failed, Cancelled, Deleted

	  AND (US."ExpDate" >= TRUNC(SYSDATE) OR US."ExpDate" IS NULL)

	  AND NOT (TRIM(US."Producer") IS NULL OR LENGTH(TRIM(US."Producer")) = 0)

	  AND US."Deleted" = 0

	) THEN 2

	-- Faculty

	WHEN EXISTS (

	  SELECT 1

	  FROM USERS US 

	  JOIN PTFACUL PT ON PT."Faculty" = US."User"

      JOIN IUSER IU ON PT."Patient" = IU."Id"

	  WHERE 1=1

	  AND IU."iUser" = vSenderUserId

	  AND US."User" = vRecipientUserId

	  AND PT."Deleted" = 0

	  AND (US."ExpDate" >= TRUNC(SYSDATE) OR US."ExpDate" IS NULL)

	  AND US."Deleted" = 0

	) THEN 3

	--ADMIN

	WHEN EXISTS (

	  SELECT 1

	  FROM USERS US

	  JOIN PTMANAGE PT ON PT."User" = US."User"

	  JOIN IUSER IU ON PT."Patient" = IU."Id"

	  WHERE 1=1

	  AND IU."iUser" = vSenderUserId

	  AND US."User" = vRecipientUserId

	  AND PT."Deleted" = 0

	  AND (US."ExpDate" >= TRUNC(SYSDATE) OR US."ExpDate" IS NULL)

	  AND US."Deleted" = 0

	) THEN 4

	ELSE 0

	END INTO vResult

	FROM DUAL;

  END;

  

  PROCEDURE gettotalrecipients(IN vmessageid integer, OUT vcount integer) IS

  BEGIN

     SELECT count(*) INTO vCount from MSGSENT where "Message" = vMessageId AND "Status" != 0;  -- Get Unread Recipients

    EXCEPTION WHEN NO_DATA_FOUND THEN

      vCount := 0;	 

  END;  

  

  PROCEDURE deletemsg(IN vmessageid integer) IS

  BEGIN

    DELETE FROM MESSAGE WHERE "Message" = vMessageId;	-- Delete Message

    

    COMMIT;

  END;



  PROCEDURE deletemsgunreadrecipients(IN vmessageid integer) IS

  BEGIN

    DELETE FROM MSGSENT WHERE "Message" = vMessageId AND "Status" = 0;	-- Delete all recipients with Unread status for the message

    

    COMMIT;

  END;

  

END;
 

