--------------------------------------------------------------------------Srilekha 03-07-2023---------------------------------------------------------------------------

alter table  IF EXISTS "PharmacyPurchaseHeader" 
add column IF NOT EXISTS "PayTypeId" integer,
add column IF NOT EXISTS "PaymentNumber" text;
--------------------------------------------------------------------------Mounika A 03-07-2023----------------------------------------------------------------------
ALTER TABLE IF EXISTS "PediatricEncounter"
drop column IF EXISTS  "PatientId";
---------------------------------------------------------- Vikas 03 july 2023-------------------------------------------------------------------------------------

DROP FUNCTION if exists "udf_uiReport_Receipts_Appointments_Location"(integer[],integer,integer,integer[],character varying,integer,character varying,character varying,integer,integer,integer,timestamp without time zone,timestamp without time zone);

CREATE OR REPLACE FUNCTION public."udf_uiReport_Receipts_Appointments_Location"("accountId" integer[] DEFAULT NULL::integer[], "providerId" integer DEFAULT NULL::integer, "locationId" integer DEFAULT NULL::integer, "roleId" integer[] DEFAULT NULL::integer[], "appointmentNo" character varying DEFAULT NULL::text, "patientId" integer DEFAULT NULL::integer, "uMRNo" character varying DEFAULT NULL::text, "patientMobile" character varying DEFAULT NULL::text, "receiptId" integer DEFAULT NULL::integer, "createdBy" integer DEFAULT NULL::integer, "payTypeId" integer DEFAULT NULL::integer, "fromDate" timestamp without time zone DEFAULT (now())::timestamp without time zone, "toDate" timestamp without time zone DEFAULT (now())::timestamp without time zone)
 RETURNS TABLE("ReceiptCreatedBy" text, "RoleName" character varying, "ReceiptDate" timestamp without time zone, 
 "ReceiptId" text, 
 "AppointmentNo" character varying, "FollowUpForAppointmentId" integer, "AppointmentDate" date,
 "AppointmentTime" text,
 "PatientName" text,
 "UMRNo" character varying, 
 "PatientMobile" character varying, 
 "ProviderName" character varying, 
 "PaymentType" text, 
 "PayTypeName" character varying, 
 "PaymentDetails" character varying, 
 "PaidAmount" numeric, "RefundAmount" numeric, 
 "BalanceAmount" numeric, "AppointmentId" integer,
 "IsAppointmentReceipt" boolean)
 LANGUAGE plpgsql
AS $function$
BEGIN

return query 

select coalesce(A."FullName",'GrandTotal') "ReceiptCreatedBy",A."RoleName",A."CreatedDate" "ReceiptDate",
coalesce(A."ReceiptId"::text,'Total')"ReceiptId"
,A."AppointmentNo",A."FollowUpForAppointmentId",
A."AppointmentDate"::date as "AppointmentDate", to_char( 
	A."AppointmentTime" , 'HH12:MI PM' ) "AppointmentTime",
A."PatientName" "PatientName",A."UMRNo",A."Mobile", A."ProviderName" as "ProviderName",A."PaymentType"::text
,A."PayTypeName",A."PaymentDetails",sum(A."PaidAmount") "PaidAmount",sum(A."RefundAmount") "RefundAmount" 

,sum(A."PaidAmount")-sum(A."RefundAmount") "BalanceAmount",A."AppointmentId",A."IsAppointmentReceipt"
from (

select R."ReceiptId",A."FullName",Rl."RoleName",R."CreatedDate" "CreatedDate",
coalesce(case when "ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
coalesce(case when "ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,Ad."FollowUpForAppointmentId",
	Ad."AppointmentDate",Ad."AppointmentNo", Ad."AppointmentTime",Ad."LocationId",
pa."FullName" "PatientName",Pa."UMRNo",pa."Mobile",pr."FullName" as "ProviderName",Ad."PaymentType",
pt."PayTypeName",ad."PaymentNumber" as "PaymentDetails" , R."AppointmentId",R."IsAppointmentReceipt" 
	from "Receipt" R
join "Appointment" ad on Ad."AppointmentId"=R."RespectiveId" and ad."Status" <> 'C'  and ad."Active" <> false
join "Provider" pr on pr."ProviderId"= ad."ProviderId"
join "Patient" pa on Ad."PatientId"=pa."PatientId"
join "Account" A on A."AccountId"=R."CreatedBy"
join "Role" Rl on Rl."RoleId"=A."RoleId"
join "PayType" pt on pt."PayTypeId"=R."PayTypeId" 
	where  R."Active" <> false  and
case when "accountId" is null then 1=1 else  R."CreatedBy"  = any("accountId") end  
and	case when "providerId" is null then 1=1 else  pr."ProviderId"  = "providerId" end  
and case when "locationId" is null then 1=1 else Ad."LocationId" = "locationId" end
and	case when "roleId" is null then 1=1 else  A."RoleId"  = any("roleId") end  and
		 	case when "appointmentNo" is null then 1=1 else  Ad."AppointmentNo" ilike '%' || "appointmentNo" ||'%' end  and

			  case when "patientId" is null then 1=1 else  pa."PatientId"  = "patientId" end  

	and	case when "uMRNo" is null then 1=1 else  pa."UMRNo"  ilike'%'|| "uMRNo"||'%' end
	and	case when "patientMobile" is null then 1=1 else  pa."Mobile"  ilike'%'|| "patientMobile"||'%' end
	and 
	 			  case when "receiptId" is null then 1=1 else  R."ReceiptId"  = "receiptId" end  
and
	case when "createdBy" is null then 1=1 else  R."CreatedBy"  = "createdBy" end  
and
		case when "payTypeId" is null then 1=1 else  pt."PayTypeId" = "payTypeId" end and
case when "fromDate" is null then 1=1 else "fromDate" <=R."CreatedDate" and R."CreatedDate" <="toDate" and R."Active" is not false end 
	
	
	
) A
GROUP BY GROUPING SETS((A."ReceiptId",A."RoleName",A."FullName",A."CreatedDate",A."PaymentType",A."PayTypeName",A."PaymentDetails"
						,A."FollowUpForAppointmentId",A."AppointmentDate",A."AppointmentNo"
						,A."AppointmentTime",A."PatientName",A."UMRNo",A."Mobile",A."ProviderName",A."AppointmentId",
						A."IsAppointmentReceipt"), (A."FullName"), ())     
order by A."FullName" 
 ;

END
$function$
;


------------------------------------------------------------------------Sravani 04-07-2023-------------------------------------------------------------------------
DO $$                  
    BEGIN 
        IF EXISTS
            ( SELECT 1
              FROM   information_schema.tables 
              WHERE  table_schema = 'public'
              AND    table_name = 'LookupValue'
            )
        THEN
            UPDATE "LookupValue"
            SET "RowColor" = '#FAD5C0'
            where "Name" like '%Temporary Block%';
        END IF ;
    END
   $$ ;
   
DO $$                  
    BEGIN 
        IF EXISTS
            ( SELECT 1
              FROM   information_schema.tables 
              WHERE  table_schema = 'public'
              AND    table_name = 'LookupValue'
            )
        THEN
            UPDATE "LookupValue"
            SET "RowColor" = '#FFF4D2'
            where "Name" like '%Permanant Block%';
        END IF ;
    END
   $$ ;
---------------------------------------------------------------------------Shivani 04-07-2023----------------------------------------------------------------------------
alter table IF EXISTS "PatientLabHeader"
DROP CONSTRAINT IF EXISTS "PatientLabHeader_AdmissionId_fkey";
alter table IF EXISTS "PatientLabHeader"
add column IF NOT EXISTS "AdmissionId" integer,
add CONSTRAINT "PatientLabHeader_AdmissionId_fkey" FOREIGN KEY ("AdmissionId")
 REFERENCES public."Admission" ("AdmissionId") MATCH SIMPLE;

--------------------------------------------------------------------------------Shivani 05-07-2023-------------------------------------------------------------------
alter table IF EXISTS "PatientMedicationHeader"
DROP CONSTRAINT IF EXISTS "PatientMedicationHeader";
alter table IF EXISTS "PatientMedicationHeader"
add column IF NOT EXISTS "AdmissionId" integer,
add CONSTRAINT "PatientMedicationHeader" FOREIGN KEY ("AdmissionId")
 REFERENCES public."Admission" ("AdmissionId") MATCH SIMPLE;

--------------------------------------------------------------------------------Sandeep 05-07-2023---------------------------------------------------------------


CREATE SEQUENCE IF NOT EXISTS "NurseNote_NurseNoteId_seq";
CREATE TABLE IF NOT EXISTS public."NurseNote"
(
    "NurseNoteId" integer NOT NULL DEFAULT nextval('"NurseNote_NurseNoteId_seq"'::regclass),
    "Note" text COLLATE pg_catalog."default" NOT NULL,
    "CreatedBy" bigint NOT NULL,
    "CreatedDate" timestamp without time zone NOT NULL,
    "AdmissionId" integer NOT NULL,
    CONSTRAINT "PK_NurseNoteId" PRIMARY KEY ("NurseNoteId"),
    CONSTRAINT "FK_NurseNote_AdmissionId" FOREIGN KEY ("AdmissionId")
        REFERENCES public."Admission" ("AdmissionId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_NurseNote_CreatedById" FOREIGN KEY ("CreatedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
);
--------------------------------------------------------------------------------Radhika 06-07-2023--------------------------------------------------------------
alter table IF EXISTS "GynEncounter"
add column IF NOT EXISTS "Colposcopic" text,
add column IF NOT EXISTS "Ectopic" text;
-------------------------------------------------------------------------------Chandana 07 July 2023-------------------------------------------------------------
CREATE SEQUENCE IF NOT EXISTS public."BirthCertificate_BirthCertificateId_seq"
    INCREMENT 1
    START 1
    MINVALUE 1
    MAXVALUE 9223372036854775807
    CACHE 1;

ALTER SEQUENCE public."BirthCertificate_BirthCertificateId_seq"
    OWNER TO postgres;


CREATE TABLE IF NOT EXISTS public."BirthCertificate"
(
    "BirthCertificateId" integer NOT NULL DEFAULT nextval('"BirthCertificate_BirthCertificateId_seq"'::regclass),
    "BirthCertificateNo" character varying(255) COLLATE pg_catalog."default",
    "ChildName" character varying(255) COLLATE pg_catalog."default",
    "DateOfBirth" date,
    "TimeOfBirth" text COLLATE pg_catalog."default",
    "Sex" character varying(255) COLLATE pg_catalog."default",
    "PlaceOfBirth" character varying(255) COLLATE pg_catalog."default",
    "AgeOfMotherAtMarriage" integer,
    "InformantsName" text COLLATE pg_catalog."default",
    "InformantsAddress" text COLLATE pg_catalog."default",
    "PatientId" integer NOT NULL,
    "AdmissionId" integer NOT NULL,
    "Active" boolean,
    "CreatedBy" integer,
    "ModifiedBy" integer,
    "ModifiedDate" timestamp(6) without time zone,
    "CreatedDate" timestamp(6) without time zone,
    CONSTRAINT "BirthCertificate_pkey" PRIMARY KEY ("BirthCertificateId"),
    CONSTRAINT "BirthCertificate_CreatedBy_fkey" FOREIGN KEY ("CreatedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "BirthCertificate_ModifiedBy_fkey" FOREIGN KEY ("ModifiedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_BirthCertificate_AdmissionId" FOREIGN KEY ("AdmissionId")
        REFERENCES public."Admission" ("AdmissionId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_BirthCertificate_PatientId" FOREIGN KEY ("PatientId")
        REFERENCES public."Patient" ("PatientId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
)

TABLESPACE pg_default;

ALTER TABLE IF EXISTS public."BirthCertificate"
    OWNER to postgres;
---------------------------------------------------------Sai John 10July2023----------------------------------------------------------------------------------

ALTER TABLE IF EXISTS public."ServiceOrder"
    ADD COLUMN IF NOT EXISTS "AdmissionPackageId" integer;


ALTER TABLE IF EXISTS public."ServiceOrder"
    ADD COLUMN IF NOT EXISTS "PackageModuleDetailId" integer;


ALTER TABLE IF EXISTS public."ServiceOrder"
    ADD COLUMN IF NOT EXISTS "UsedQuantity" integer;


ALTER TABLE IF EXISTS public."ServiceOrder"
    ADD COLUMN IF NOT EXISTS "UsedCost" numeric(10,2);

ALTER TABLE IF EXISTS public."ServiceOrder" DROP CONSTRAINT IF EXISTS "FK_ServiceOrder_AdmissionPackageId";

ALTER TABLE IF EXISTS public."ServiceOrder"
    ADD CONSTRAINT "FK_ServiceOrder_AdmissionPackageId" FOREIGN KEY ("AdmissionPackageId")
    REFERENCES public."AdmissionPackage" ("AdmissionPackageId") MATCH SIMPLE
    ON UPDATE NO ACTION
    ON DELETE NO ACTION
    NOT VALID;

ALTER TABLE IF EXISTS public."ServiceOrder" DROP CONSTRAINT IF EXISTS "FK_ServiceOrder_PackageModuleDetailId";

ALTER TABLE IF EXISTS public."ServiceOrder"
    ADD CONSTRAINT "FK_ServiceOrder_PackageModuleDetailId" FOREIGN KEY ("PackageModuleDetailId")
    REFERENCES public."PackageModuleDetail" ("PackageModuleDetailId") MATCH SIMPLE
    ON UPDATE NO ACTION
    ON DELETE NO ACTION
    NOT VALID;

-----------------------------------------------------------------------Kalyan 10July2023---------------------------------------------------------------------------

CREATE SEQUENCE IF NOT EXISTS "ExternalLabAgency_ExternalLabAgencyId_seq";
CREATE TABLE IF NOT EXISTS public."ExternalLabAgency"
(
    "ExternalLabAgencyId" integer NOT NULL DEFAULT nextval('"ExternalLabAgency_ExternalLabAgencyId_seq"'::regclass),
    "AgencyName" character varying(255) COLLATE pg_catalog."default" NOT NULL,
    "CreatedBy" integer NOT NULL,
    "CreatedDate" timestamp without time zone NOT NULL,
    "ModifiedBy" integer ,
    "ModifiedDate" timestamp without time zone ,
    "Active" boolean NOT NULL DEFAULT true,
    CONSTRAINT "PK_ExternalLabAgency_ExternalLabAgencyId" PRIMARY KEY ("ExternalLabAgencyId"),
    CONSTRAINT "FK_ExternalLabAgency_CreatedById" FOREIGN KEY ("CreatedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_ExternalLabAgency_ModifiedBy" FOREIGN KEY ("ModifiedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
);

---------------------------------------------------------------------Radhika 10July2023----------------------------------------------------------------------------
alter table if exists "GynEncounter"
add column if not exists "SpeacialFeature" text,
add column if not exists "ReferralForm" text;

---------------------------------------------------------------------SaiJohn 11July2023-----------------------------------------------------------------------------
ALTER TABLE IF EXISTS public."LabServices"
    ADD COLUMN IF NOT EXISTS "AdmissionPackageId" integer;


ALTER TABLE IF EXISTS public."LabServices"
    ADD COLUMN IF NOT EXISTS "PackageModuleDetailId" integer;


ALTER TABLE IF EXISTS public."LabServices"
    ADD COLUMN IF NOT EXISTS "UsedQuantity" integer;



ALTER TABLE IF EXISTS public."LabServices"
    ADD COLUMN IF NOT EXISTS "UsedCost" numeric(10,2);

ALTER TABLE IF EXISTS public."LabServices" DROP CONSTRAINT IF EXISTS "FK_LabServices_AdmissionPackageId";

ALTER TABLE IF EXISTS public."LabServices"
    ADD CONSTRAINT "FK_LabServices_AdmissionPackageId" FOREIGN KEY ("AdmissionPackageId")
    REFERENCES public."AdmissionPackage" ("AdmissionPackageId") MATCH SIMPLE
    ON UPDATE NO ACTION
    ON DELETE NO ACTION
    NOT VALID;

ALTER TABLE IF EXISTS public."LabServices" 
DROP CONSTRAINT IF EXISTS "FK_LabServices_PackageModuleDetailId";

ALTER TABLE IF EXISTS public."LabServices"
    ADD CONSTRAINT "FK_LabServices_PackageModuleDetailId" FOREIGN KEY ("PackageModuleDetailId")
    REFERENCES public."PackageModuleDetail" ("PackageModuleDetailId") MATCH SIMPLE
    ON UPDATE NO ACTION
    ON DELETE NO ACTION
    NOT VALID;

----------------------------------------------------------------------------------------Shivani12July2023------------------------------------------------------------
CREATE SEQUENCE IF NOT EXISTS "ReferralForm_ReferralFormId_seq";
CREATE TABLE IF NOT EXISTS public."ReferralForm"
(
    "ReferralFormId" integer NOT NULL DEFAULT nextval('"ReferralForm_ReferralFormId_seq"'::regclass),
    "ReferralDoctor" character varying (50)  NOT NULL,
	"Reason" text,
	"RequiredDate" date,
	"Time" time  without time zone,
    "CreatedDate" timestamp without time zone NOT NULL,
	"ConsultantDoctor" character varying (50),
	"Opinion" text,
	"Active" bool default true,
	"AppointmentId" int not null,
	"ProviderId" int,
	"ReferralDoctorId" int,
	"PatientId" int,
    CONSTRAINT "PK_ReferralFormId" PRIMARY KEY ("ReferralFormId"),
	 CONSTRAINT "FK_ReferralForm_AppointmentId" FOREIGN KEY ("AppointmentId")
        REFERENCES public."Appointment" ("AppointmentId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
	CONSTRAINT "FK_ReferralForm_ProviderId" FOREIGN KEY ("ProviderId")
        REFERENCES public."Provider" ("ProviderId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
	CONSTRAINT "FK_ReferralForm_ReferralDoctorId" FOREIGN KEY ("ReferralDoctorId")
        REFERENCES public."ReferralDoctor" ("ReferralDoctorId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
	CONSTRAINT "FK_ReferralForm_PatientId" FOREIGN KEY ("PatientId")
        REFERENCES public."Patient" ("PatientId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
);

-----------------------------------------------------------------------------------Radhika 12July2023-----------------------------------------------------------
alter table if exists "GynEncounter"
add column if not exists "Measure" text,
--alter table if exists "GynEncounter"
add column if not exists "RefferalOrder" text;

------------------------------------------------------------------------------------Kalyan 13July2023-------------------------------------------------------------

CREATE SEQUENCE IF NOT EXISTS "AdmissionBedChangeRequest_AdmissionBedChangeRequestId_seq";
CREATE TABLE IF NOT EXISTS public."AdmissionBedChangeRequest"
(
    "AdmissionBedChangeRequestId" integer NOT NULL DEFAULT nextval('"AdmissionBedChangeRequest_AdmissionBedChangeRequestId_seq"'::regclass),
    "AdmissionId" integer NOT NULL,
    "ChargeCategories" integer[],
    "RequestComments" text COLLATE pg_catalog."default",
    "CreatedBy" integer NOT NULL,
    "CreatedDate" timestamp without time zone NOT NULL,
    "ModifiedBy" integer ,
    "ModifiedDate" timestamp without time zone,
    "Active" boolean NOT NULL DEFAULT true,
    CONSTRAINT "PK_AdmissionBedChangeRequest_AdmissionBedChangeRequestId" PRIMARY KEY ("AdmissionBedChangeRequestId"),
    CONSTRAINT "FK_AdmissionBedChangeRequest_AdmissionId" FOREIGN KEY ("AdmissionId")
        REFERENCES public."Admission" ("AdmissionId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_AdmissionBedChangeRequest_CreatedById" FOREIGN KEY ("CreatedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_AdmissionBedChangeRequest_ModifiedBy" FOREIGN KEY ("ModifiedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
);

CREATE SEQUENCE IF NOT EXISTS "ExternalLabAgency_ExternalLabAgencyId_seq";
CREATE TABLE IF NOT EXISTS public."ExternalLabAgency"
(
    "ExternalLabAgencyId" integer NOT NULL DEFAULT nextval('"ExternalLabAgency_ExternalLabAgencyId_seq"'::regclass),
    "AgencyName" character varying(255) COLLATE pg_catalog."default" NOT NULL,
    "CreatedBy" integer NOT NULL,
    "CreatedDate" timestamp without time zone NOT NULL,
    "ModifiedBy" integer ,
    "ModifiedDate" timestamp without time zone,
    "Active" boolean NOT NULL DEFAULT true,
    CONSTRAINT "PK_ExternalLabAgency_ExternalLabAgencyId" PRIMARY KEY ("ExternalLabAgencyId"),
    CONSTRAINT "FK_ExternalLabAgency_CreatedById" FOREIGN KEY ("CreatedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_ExternalLabAgency_ModifiedBy" FOREIGN KEY ("ModifiedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
);



INSERT INTO public."LabLogType"("LabLogTypeId","LogTypeName", "Active")
SELECT 16,'Lab_Masters_Agency',true
WHERE
NOT EXISTS (
SELECT "LabLogTypeId" FROM public."LabLogType" WHERE  "LogTypeName" = 'Lab_Masters_Agency'
);
--------------------------------------------------------------------------Shivani 13July2023-------------------------------------------------------------------
alter table IF EXISTS "ObEncounter" 
add COLUMN IF NOT EXISTS "OutSideTests" text;
--------------------------------------------------------------------------KAlyan 14July2023--------------------------------------------------------------------
DROP FUNCTION IF EXISTS public."udf_fetch_Admission_Location"(text, integer, integer, boolean, text, date, date, date, text, boolean, integer, integer, integer);

CREATE OR REPLACE FUNCTION public."udf_fetch_Admission_Location"(
	"admissionNo" text DEFAULT NULL::text,
	"providerId" integer DEFAULT NULL::integer,
	"patientId" integer DEFAULT NULL::integer,
	"isDischarged" boolean DEFAULT NULL::boolean,
	"patientMobileNo" text DEFAULT NULL::text,
	"fromDate" date DEFAULT NULL::date,
	"toDate" date DEFAULT NULL::date,
	"dischargeDate" date DEFAULT NULL::date,
	"uMRNo" text DEFAULT NULL::text,
	active boolean DEFAULT NULL::boolean,
	locationid integer DEFAULT NULL::integer,
	"pageIndex" integer DEFAULT 0,
	"pageSize" integer DEFAULT 10)
    RETURNS TABLE("AdmissionId" integer, "AdmissionNo" text, "IsConvertedFromOPtoIp" boolean, "AdmissionDate" timestamp without time zone, "AdmissionTime" time without time zone, "PatientName" text, "UMRNo" character varying, "PatientAge" smallint, "PatientGender" character, "patientMobile" character varying, "ProviderAge" smallint, "ProviderGender" character, "ProviderName" text, "DepartmentName" text, "WardName" character varying, "RoomName" character varying, "BedNumber" character varying, "AttendantName" character varying, "AttendantRelationWithPatient" character varying, "AttendantContactNo" character varying, "IsDischarged" boolean, "DischargeDate" date, "DischargeTime" time without time zone, "DischargeStatus" character varying, "IsMaternity" boolean, "EncounterId" integer, "SurgeryName" character varying, "ProviderThumbnailUrl" text, "PatientThumbnailUrl" text, "BedId" integer, "RoomId" integer, "WardId" integer, "DepartmentId" integer, "PatientId" integer, "ProviderId" integer, "SurgeryTypeId" integer, "PatientType" character, "AdmissionNotes" text, "PaidAmount" numeric, "FinalAmount" numeric, "PaymentStatus" text, "IsFinalBill" boolean, "TotalItems" bigint, "Active" boolean, "ExpectedDischargeDate" timestamp without time zone, "DischargedBy" integer, "DischargedByRole" text, "DischargedByName" text, "ChargeCategoryId" integer, "ChargeCategoryName" character varying, "CaseTypeId" integer, "AdmissionPayTypeId" integer, "ReferralDoctorId" integer, "InsuranceCompanyId" integer, "TpaId" integer, "PatientOrganization" character varying, "DoctorUnitMasterId" integer,"AdmissionBedChangeRequestId" integer,"ChargeCategoryNames" text,"RequestComments" text) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
BEGIN

return query 

With TotalItems as (

select  count(distinct A."AdmissionId")::bigint "TotalItems"
	from "Admission" A
	join "Patient" Pa on A."PatientId"=Pa."PatientId"
	join "Provider" Pr on A."ProviderId"=Pr."ProviderId"
	join "Department" D on D."DepartmentId"=A."DepartmentId"
	left join "Bed" B on B."BedId"=A."BedId"
	left join "Room" R on B."RoomId"=R."RoomId"  
	left join "Ward" W on w."WardId"=R."WardId"
    join "ChargeCategory" cc on cc."ChargeCategoryId" = R."ChargeCategoryId"
	---left join "PatientFamily" pf on pf."PatientFamilyId"=A."PatientFamilyId"
	left join "SurgeryType" st on st."SurgeryTypeId"=A."SurgeryTypeId"
	left join "Discharge" ds on ds."AdmissionId"=A."AdmissionId" and ds."Active"=true
	left join "DischargeStatus" dss on ds."DischargeStatusId"=dss."DischargeStatusId"
	
	left join "Receipt" Re on A."AdmissionId" = Re."AdmissionId" and Re."ReceiptTypeId"=1 and Re."Active"=true
---left join "Receipt" Rf on Rf."ReceiptTypeId"=2 and A."AdmissionId"= Rf ."AdmissionId" and Rf."Active"=true  and  Rf."IsRefunded" =true
left join "FinalBill" FB on  A."AdmissionId"= FB."AdmissionId" and FB."Active"=true	
	where  
	case when "admissionNo" is null then 1=1
	when "admissionNo"='' then 1=1
	else A."AdmissionNo" ilike '%'||"admissionNo"||'%' end and 
	 CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE A."LocationId"=locationId END	 AND						
	case when "patientMobileNo" is null then 1=1
	when "patientMobileNo"='' then 1=1
	else pa."Mobile" ilike '%'||"patientMobileNo"||'%' end and 
	
	case when "patientId" is null then 1=1
	else Pa."PatientId"= "patientId" end and 
	
	case when "active" is null then 1=1
	else A."Active"= "active" end and 
	
	case when "providerId" is null then 1=1
	
	else Pr."ProviderId" = "providerId" end and  
	case when "isDischarged" is null then 1=1
		when "isDischarged" =true then   ds."AdmissionId"=A."AdmissionId"  
		when "isDischarged" =false then	ds."AdmissionId" is null	
		end AND
	case when "fromDate" is null then 1=1 else "fromDate" <=A."AdmissionDate"::date and A."AdmissionDate"::date <="toDate" end 
	AND 
	case when "dischargeDate" is null then 1=1 else "dischargeDate" =ds."DischargeDate"::date end 
and
	case when "uMRNo" is null then 1=1
	when "uMRNo"='' then 1=1
	else Pa."UMRNo" ilike '%'||"uMRNo"||'%' end 

)

select  A."AdmissionId",A."AdmissionNo",A."IsConvertedFromOPtoIp",A."AdmissionDate",A."AdmissionTime",
	Pa."FullName" "PatientName",Pa."UMRNo",Pa."Age" "PatientAge",Pa."Gender" as "PatientGender",pa."Mobile" "patientMobile",Pr."Age" "ProviderAge",Pr."Gender" as "ProviderGender",
	Pr."FullName"::text "ProviderName",D."DepartmentName"::text "DepartmentName" , w."WardName", R."RoomName", B."BedNumber"
	,A."AttendantName" "AttendantName",A."AttendantRelationWithPatient" "AttendantRelationWithPatient",A."AttendantContactNo" "AttendantContactNumber",
	case when ds."DischargeId" is not null then true else false end as "IsDischarged",ds."DischargeDate",ds."DischargeTime",
	dss."DischargeStatus"
	
	,A."IsMaternity",A."EncounterId",st."SurgeryName",
	(CASE WHEN pr."ThumbnailUrl" IS NOT NULL THEN CONCAT(pr."Guid", '/', pr."ThumbnailUrl") ELSE NULL END) AS "ProviderThumbnailUrl",
(CASE WHEN pa."ThumbnailUrl" IS NOT NULL THEN CONCAT(pa."Guid", '/', pa."ThumbnailUrl") ELSE NULL END) AS "PatientThumbnailUrl"
	,A."BedId",B."RoomId",w."WardId",D."DepartmentId",A."PatientId", A."ProviderId", A."SurgeryTypeId", A."PatientType",A."AdmissionNotes"
,
sum(coalesce(Re."Cost",0))-coalesce((select sum(Rfd."Cost") from "Receipt" Rfd where Rfd."AdmissionId"=A."AdmissionId" and "ReceiptTypeId"=2 and  Rfd."Active"=true and  Rfd."IsRefunded" =true ),0) "PaidAmount"
,
FB."FinalAmount" ,
case when FB."FinalAmount"-(sum(coalesce(Re."Cost",0))-coalesce((select sum(Rfd."Cost") from "Receipt" Rfd where Rfd."AdmissionId"=A."AdmissionId" and "ReceiptTypeId"=2 and  Rfd."Active"=true and  Rfd."IsRefunded" =true ),0))=0 then 'Payment Cleared'
	 when FB."FinalAmount"-(sum(coalesce(Re."Cost",0))-coalesce((select sum(Rfd."Cost") from "Receipt" Rfd where Rfd."AdmissionId"=A."AdmissionId" and "ReceiptTypeId"=2 and  Rfd."Active"=true and  Rfd."IsRefunded" =true ),0))>0 then 'Payment Due'	
	 when FB."FinalAmount"-(sum(coalesce(Re."Cost",0))-coalesce((select sum(Rfd."Cost") from "Receipt" Rfd where Rfd."AdmissionId"=A."AdmissionId" and "ReceiptTypeId"=2 and  Rfd."Active"=true and  Rfd."IsRefunded" =true ),0))<0 then 'Pending Refund' end "PaymentStatus",
case when FB."FinalBillId" is null then false else true end "IsFinalBill",(select T."TotalItems" from TotalItems T) "TotalItems",
A."Active",
A."ExpectedDischargeDate",
A."DischargedBy" ,
case when RL."RoleId" =  '3' then DP."DepartmentName"::TEXT else RL."RoleName"::TEXT end as "DischargedByRole",
case when RL."RoleId" =  '3' then PRO."FullName" else AC."FullName" end as "DischargedByName",R."ChargeCategoryId",cc."ChargeCategoryName",A."CaseTypeId",
A."AdmissionPayTypeId",A."ReferralDoctorId",A."InsuranceCompanyId",A."TpaId" ,A."PatientOrganization",A."DoctorUnitMasterId",abcr."AdmissionBedChangeRequestId",
string_agg(DISTINCT newcc."ChargeCategoryName", ',') AS "ChargeCategoryNames",abcr."RequestComments"
	from "Admission" A
	join "Patient" Pa on A."PatientId"=Pa."PatientId"
	join "Provider" Pr on A."ProviderId"=Pr."ProviderId"
	join "Department" D on D."DepartmentId"=A."DepartmentId"
	left join "Bed" B on B."BedId"=A."BedId"
	left join "Room" R on B."RoomId"=R."RoomId"
    join "ChargeCategory" cc on cc."ChargeCategoryId" =R."ChargeCategoryId"
	left join "Ward" W on w."WardId"=R."WardId"
	---left join "PatientFamily" pf on pf."PatientFamilyId"=A."PatientFamilyId"
	left join "SurgeryType" st on st."SurgeryTypeId"=A."SurgeryTypeId"
	left join "Discharge" ds on ds."AdmissionId"=A."AdmissionId" and ds."Active"=true
	left join "DischargeStatus" dss on ds."DischargeStatusId"=dss."DischargeStatusId"
	
	left join "Receipt" Re on A."AdmissionId" = Re."AdmissionId" and Re."ReceiptTypeId"=1 and Re."Active"=true
---left join "Receipt" Rf on Rf."ReceiptTypeId"=2 and A."AdmissionId"= Rf ."AdmissionId" and Rf."Active"=true  and  Rf."IsRefunded" =true
left join "FinalBill" FB on  A."AdmissionId"= FB."AdmissionId" and FB."Active"=true
	
	left join "Account" AC on AC."AccountId"=A."DischargedBy" 
left join "Role" RL on RL."RoleId"= AC."RoleId"
left join "Provider" PRO on PRO."ProviderId"=AC."ReferenceId"
left join "Department" DP on DP."DepartmentId"=PRO."DepartmentId"
	left join "AdmissionBedChangeRequest" abcr on abcr."AdmissionId" = a."AdmissionId" and abcr."Active" = true		
	LEFT JOIN "ChargeCategory" newcc on newcc."ChargeCategoryId" = ANY(abcr."ChargeCategories") --AND newcc."Active" IS TRUE
    
    where  
	case when "admissionNo" is null then 1=1
	when "admissionNo"='' then 1=1
	else A."AdmissionNo" ilike '%'||"admissionNo"||'%' end and 
	 CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE A."LocationId"=locationId END	 AND						
	case when "patientMobileNo" is null then 1=1
	when "patientMobileNo"='' then 1=1
	else pa."Mobile" ilike '%'||"patientMobileNo"||'%' end and 
	
	case when "patientId" is null then 1=1
	else Pa."PatientId"= "patientId" end and 
	
	case when "active" is null then 1=1
	else A."Active"= "active" end and 
	
	case when "providerId" is null then 1=1
	
	else Pr."ProviderId" = "providerId" end and  
	case when "isDischarged" is null then 1=1
		when "isDischarged" =true then   ds."AdmissionId"=A."AdmissionId"  
		when "isDischarged" =false then	ds."AdmissionId" is null	
		end AND
	case when "fromDate" is null then 1=1 else "fromDate" <=A."AdmissionDate"::date and A."AdmissionDate"::date <="toDate" end 
	AND 
	case when "dischargeDate" is null then 1=1 else "dischargeDate" =ds."DischargeDate"::date end 
and
	case when "uMRNo" is null then 1=1
	when "uMRNo"='' then 1=1
	else Pa."UMRNo" ilike '%'||"uMRNo"||'%' end  
 group by  A."AdmissionId",A."AdmissionNo",A."IsConvertedFromOPtoIp",A."AdmissionDate",A."AdmissionTime",
	Pa."FullName",Pa."UMRNo",Pa."Age" ,Pa."Gender" ,Pr."Age" ,Pr."Gender" ,
	Pr."FullName",D."DepartmentName" , w."WardName", R."RoomName", B."BedNumber"
	,A."AttendantName",A."AttendantRelationWithPatient",A."AttendantContactNo" , ds."DischargeId"
																														 
	,ds."DischargeDate",ds."DischargeTime",
	dss."DischargeStatus",pa."Mobile"
	
	,A."IsMaternity",A."EncounterId",st."SurgeryName",pr."ThumbnailUrl", pr."Guid",pr."ThumbnailUrl" ,pa."Guid", pa."ThumbnailUrl",
	A."BedId",B."RoomId",w."WardId",D."DepartmentId",A."PatientId", A."ProviderId", A."SurgeryTypeId", A."PatientType",A."AdmissionNotes"
		,FB."FinalAmount"	,FB."FinalBillId",
	RL."RoleId",DP."DepartmentName",PRO."FullName",AC."FullName",R."ChargeCategoryId",cc."ChargeCategoryName",abcr."AdmissionBedChangeRequestId"
	order by A."AdmissionId" desc 
 limit "pageSize" offset ("pageSize"*"pageIndex");

END
$BODY$;

------------------------------------------------------------------------Radhika 14July2023----------------------------------------------------------------

	create sequence if not exists "CommonEncounter_CommonEncounterId-seq"
	increment 1
	start 1
	minvalue 1
	maxvalue 9223372036854775807;


---------------------------------------------------------
-- Table: public.CommonEncounter

-- DROP TABLE IF EXISTS public."CommonEncounter";

CREATE TABLE IF NOT EXISTS public."CommonEncounter"
(
    "CommonEncounterId" bigint NOT NULL DEFAULT nextval('"CommonEncounter_CommonEncounterId-seq"'::regclass),
    "AppointmentId" integer,   
    "FamilyHistory" text COLLATE pg_catalog."default",
    "ProblemList" text COLLATE pg_catalog."default",
    "OBBirthHistory" text COLLATE pg_catalog."default",   
    "Active" boolean NOT NULL DEFAULT true,
    "CreatedBy" integer NOT NULL,
    "CreatedDate" timestamp(6) without time zone NOT NULL,
    "AdmissionId" integer,   
    "PatientId" integer,
    
    CONSTRAINT "CommonEncounter_pkey" PRIMARY KEY ("CommonEncounterId"),
    CONSTRAINT "UQ_CommonEncounter" UNIQUE ("AppointmentId"),
    CONSTRAINT "GynEncounter_PatientId_fkey" FOREIGN KEY ("PatientId")
        REFERENCES public."Patient" ("PatientId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
)

TABLESPACE pg_default;

ALTER TABLE IF EXISTS public."CommonEncounter"
    OWNER to postgres;

---------------------------------------------------------------Sravani14July2023----------------------------------------
 DO $$
BEGIN
  IF EXISTS(SELECT *
    FROM information_schema.columns
    WHERE table_name='BookScanAppointment' and column_name='Comment')
  THEN
      ALTER TABLE "public"."BookScanAppointment" RENAME COLUMN "Comment" TO "Indication";
  END IF;
END $$;
-------------------------------------------Kalyan 14July2023--------------------------------------------------------------------------------
alter table if exists "ExternalLabAgency"
ALTER COLUMN "ModifiedDate" DROP NOT NULL;
------------------------------------------------------------- Radhika 17July2023---------------------------------------------------------
alter table if exists "CommonEncounter"
 add column if not exists  "Surgeries" text;

 DO $$
BEGIN
  IF EXISTS(SELECT *
    FROM information_schema.columns
    WHERE table_name='CommonEncounter' and column_name='OBBirthHistory')
  THEN
      ALTER TABLE "public"."CommonEncounter" RENAME COLUMN "OBBirthHistory" TO "BirthHistory";
  END IF;
END $$;

alter table if exists "CommonEncounter" 
add column if not exists  "ModifiedBy" integer,
add column if not exists  "ModifiedDate" timestamp(6) without time zone;

----------------------------------------------------------------Sravani 17july2023-----------------------------------------------------------
CREATE SEQUENCE if not exists  "ScanDocument_DocumentId_seq"
    INCREMENT 1
    START 1
    MINVALUE 1
    MAXVALUE 9223372036854775807
    CACHE 1;
	
CREATE TABLE if not exists  "ScanDocument"
(
    "ScanDocumentId" integer NOT NULL DEFAULT nextval('"ScanDocument_DocumentId_seq"'::regclass),
    "BookScanAppointmentId" integer NOT NULL,
    "DocumentName" character varying(100) COLLATE pg_catalog."default" NOT NULL,
    "ContentType" character varying(50) COLLATE pg_catalog."default" NOT NULL,
    "Size" double precision NOT NULL,
    "Description" character varying(250) COLLATE pg_catalog."default",
    "DocumentUrl" text COLLATE pg_catalog."default" NOT NULL,
    "ThumbnailUrl" text COLLATE pg_catalog."default" NOT NULL,
    "UploadedDate" timestamp(6) without time zone NOT NULL,
    "Active" boolean NOT NULL DEFAULT true,
    "ModifiedBy" integer,
    "ModifiedDate" timestamp(6) without time zone,
    "UploadedBy" integer NOT NULL,
    "IsRead" boolean DEFAULT false,
    CONSTRAINT "ScanDocument_pkey" PRIMARY KEY ("ScanDocumentId"),
    CONSTRAINT "FK_ScanDocument_BookScanAppointmentId" FOREIGN KEY ("BookScanAppointmentId")
        REFERENCES "BookScanAppointment" ("BookScanAppointmentId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE
);


INSERT INTO public."ScanLogType"("LogTypeName", "Active")
SELECT 'ScanReport',true
WHERE
NOT EXISTS (
SELECT "LogTypeName" FROM public."ScanLogType" WHERE "LogTypeName" = 'ScanReport'
);

---------------------------------------------------------------------tej 17July2023-----------------------------------------------------------------------
 
 alter table if exists "PatientRegistrationCharge" 
 add column if not exists "Name" character varying(50);
 
  alter table if exists "PatientRegistrationCharge"
  add column if not exists "ChargeCategoryId" integer;
  
 alter table if exists "PatientRegistrationCharge"
  add column if not exists "ModulesMasterId" integer;

INSERT INTO public."ModulesMaster"("ModulesMasterId","ModuleName")
SELECT 18,'PatientRegistration'
WHERE
NOT EXISTS (
SELECT "ModuleName" FROM public."ModulesMaster" WHERE "ModuleName" = 'PatientRegistration'
);



DO $$                  
    BEGIN 
        IF EXISTS
            ( SELECT 1
              FROM   information_schema.tables 
              WHERE  table_schema = 'public'
              AND    table_name = 'PatientRegistrationCharge'
            )
        THEN
            UPDATE "PatientRegistrationCharge"
            SET "ModulesMasterId" = 18;
        END IF ;
    END
   $$ ;




 DROP FUNCTION IF EXISTS public."collection_userLogin"(timestamp without time zone, timestamp without time zone, integer, integer);

CREATE OR REPLACE FUNCTION public."collection_userLogin"(
	"fromDate" timestamp without time zone DEFAULT NULL::timestamp without time zone,
	"toDate" timestamp without time zone DEFAULT NULL::timestamp without time zone,
	accountid integer DEFAULT NULL::integer,
	locationid integer DEFAULT NULL::integer)
    RETURNS TABLE("AccountId" integer, "ReceiptCreatedBy" text, "RoleName" character varying, "ReceiptDate" timestamp without time zone, "ReceiptId" integer, "ReceiptTypeId" integer, "AreaType" character varying, "RefId" character varying, "PayTypeName" character varying, "PaymentDetails" character varying, "PaidAmount" numeric, "PatientName" text, "UMRNo" character varying, "Mobile" character varying) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
begin
return query

with accountdata as (
select a."AccountId",a."FullName" "EmployeeName",rol."RoleName"
from "Account" a
JOIN "LocationAccountMap" LAM on LAM."AccountId"=a."AccountId"  
join "Role" rol on rol."RoleId" = a."RoleId" and lower(rol."RoleName") <> lower('Patient')
where a."RoleId"<>4  --and a."AccountId"=6776 and LAM."LocationId"=2
 and	case when accountid is null then 1=1 else a."AccountId"=accountid end   
AND CASE WHEN (locationid IS NULL OR locationid=0) THEN 1=1 ELSE LAM."LocationId"=locationid END
)
, appointment as (

select R."ReceiptId",A."FullName" "ReceiptCreatedBy",Rl."RoleName",R."CreatedDate" "ReceiptDate",R."CreatedBy",RT."Name" as "AreaType"
, coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
	--R."Cost"  as "PaidAmount" ,
	R."ReceiptTypeId"
 ,Ad."FollowUpForAppointmentId",
	Ad."AppointmentDate",Ad."AppointmentNo", Ad."AppointmentTime",Ad."LocationId",
pa."FullName" "PatientName",Pa."UMRNo",pa."Mobile",pr."FullName" as "ProviderName",Ad."PaymentType",
pt."PayTypeName",  CASE
    WHEN R."PaymentDetails" = 'null' THEN null
    ELSE R."PaymentDetails"
  END AS "PaymentDetails" , R."AppointmentId",R."IsAppointmentReceipt" 
	from "Receipt" R
join "Appointment" Ad on Ad."AppointmentId"=R."RespectiveId" 
join "Provider" pr on pr."ProviderId"= ad."ProviderId"
join "Patient" pa on Ad."PatientId"=pa."PatientId"
join "Account" A on A."AccountId"=R."CreatedBy"
join "Role" Rl on Rl."RoleId"=A."RoleId"
join "PayType" pt on pt."PayTypeId"=R."PayTypeId"
join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"
	where  R."Active" <> false  and R."ReceiptAreaTypeId" in (4,5) --and

and case when "accountid" is null then 1=1 else  R."CreatedBy"  = "accountid" end  
 and case when "locationid" is null then 1=1 else Ad."LocationId" = "locationid" end

 	and case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::timestamp without time zone end 
 		and case when "toDate" is null then 1=1 else R."CreatedDate"::timestamp without time zone<=  "toDate" end 
	
 
)
,patient as(			
						select 
                               coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
	
                                A."FullName" as "ReceiptCreatedBy",Rl."RoleName",
                                P."FullName" as "PatientName",P."FirstName",P."MiddleName",P."LastName",
                                P."Age",P."Gender",P."UMRNo",P."Mobile",P."DateOfBirth",
                                R."ReceiptId",R."CreatedBy",RT."Name" as "AreaType",P."PatientId",
				                PT."PayTypeName",R."PaymentDetails",R."CreatedDate" "ReceiptDate"	,R."ReceiptTypeId"
	                            FROM "Receipt" R
	                            join "Patient" P on P."PatientId" = R."RespectiveId"  
								--join  "Account" PA on PA."ReferenceId"=P."PatientId"
								--JOIN "LocationAccountMap" LAM on LAM."AccountId"=PA."AccountId"  
	                           join "MasterBill" MB on MB."MasterBillId"=R."MasterBillId"
								join "Account" A on A."AccountId" = R."CreatedBy"
						        join "Role" Rl on Rl."RoleId"=A."RoleId"
	                            join "PayType" PT on PT."PayTypeId" = R."PayTypeId"
							join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"
								where  R."ReceiptAreaTypeId" in (3,6)
								
 	and case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::timestamp without time zone end and
 	case when "toDate" is null then 1=1 else R."CreatedDate"::timestamp without time zone<=  "toDate" end and
	case when "locationid" is null then 1=1 else  MB."LocationId" = "locationid"::int end and
	case when "accountid" is null then 1=1 else R."CreatedBy"="accountid" end 
	
)

,admission as (
	
select R."ReceiptId",Rl."RoleName",R."CreatedDate" "ReceiptDate",
A."FullName" "ReceiptCreatedBy" ,pt."PayTypeName",R."PaymentDetails"
,R."CreatedBy",RT."Name" as "AreaType",R."ReceiptTypeId",
-- R."Cost"  as "PaidAmount" 
	coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" 
 ,Ad."AdmissionNo",ad."AdmissionDate",	
pa."FullName" "PatientName",pa."UMRNo",pa."Mobile",pr."FullName" as "ProviderName"

	from "Receipt" R
join "Admission" ad on Ad."AdmissionId"=R."RespectiveId" and ad."Active" is not false
join "Provider" pr on pr."ProviderId"= ad."ProviderId"
join "Patient" pa on Ad."PatientId"=pa."PatientId"
join "Account" A on A."AccountId"=R."CreatedBy"
join "Role" Rl on Rl."RoleId"=A."RoleId"
join "PayType" pt on pt."PayTypeId"=R."PayTypeId"
	join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"
	where R."Active" is not false and R."ReceiptAreaTypeId" in (12,13) and
	
case when "accountid" is null then 1=1 else  R."CreatedBy"  = "accountid" end 
and case when "locationid" is null then 1=1 else Ad."LocationId" = "locationid" end 
and case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::timestamp without time zone end 
 		and case when "toDate" is null then 1=1 else R."CreatedDate"::timestamp without time zone<=  "toDate" end  

)
,lab as (

SELECT 
	coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
	-- R."Cost" as "PaidAmount",
	PT."PayTypeName", CASE
    WHEN R."PaymentDetails" = 'null' THEN null
    ELSE R."PaymentDetails"
  END AS "PaymentDetails" , 
	 AR."FullName" "ReceiptCreatedBy",Rl."RoleName",R."CreatedBy",
	 nlbh."RequisitionNumber",	
	 nlbh."PatientId", nlbh."DoctorId",
	COALESCE (nlbh."PatientName" ,p."FullName" ) as "PatientName",COALESCE (p."Mobile" ,nlbh."Mobile" ) as "Mobile", p."UMRNo",           
      R."ReceiptId",RT."Name" as "AreaType" ,R."CreatedDate" "ReceiptDate"	,R."ReceiptTypeId"
			 from "Receipt" R
			join "NewLabBookingHeader" nlbh on nlbh."NewLabBookingHeaderId"=R."RespectiveId"                                
			join "PayType" pt ON PT."PayTypeId" = nlbh."PayTypeId"                                                                      
			left join "Patient" p ON p."PatientId" =nlbh."PatientId"
			left join "Provider" prv on prv."ProviderId" = nlbh."DoctorId"                                
			left join "Account" e on e."AccountId" = nlbh."EmployeeId" 
			left join "Account" AR on AR."AccountId" = R."CreatedBy"
			join "Role" Rl on Rl."RoleId"=AR."RoleId"
			join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"
		where R."ReceiptAreaTypeId" = 8
		--and nlbh."LocationId"=2 and R."CreatedDate"::date='2023-04-18'
 	and case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::timestamp without time zone end and
	case when "toDate" is null then 1=1 else R."CreatedDate"::timestamp without time zone<=  "toDate" end and
 	case when "locationid" is null then 1=1 else  nlbh."LocationId" = "locationid"::int end and
	case when "accountid" is null then 1=1 else nlbh."CreatedBy"="accountid" end 

UNION
		
SELECT 
	coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
	-- R."Cost" as "PaidAmount", 
	PT."PayTypeName",R."PaymentDetails",
	 AR."FullName" "ReceiptCreatedBy" ,Rl."RoleName",R."CreatedBy",
	 nlbh."RequisitionNumber",
	 nlbh."PatientId", nlbh."DoctorId", 
	COALESCE (nlbh."PatientName" ,p."FullName" ) as "PatientName",COALESCE (p."Mobile" ,nlbh."Mobile" ) as "Mobile", p."UMRNo",           
      R."ReceiptId",RT."Name" as "AreaType",R."CreatedDate" "ReceiptDate"	,R."ReceiptTypeId"
			
	
		from "NewLabBookingHeader" nlbh
	join "NewLabCancelBookingHeader" SH on SH."NewLabBookingHeaderId"=nlbh."NewLabBookingHeaderId"
	join "Receipt" R on R."RespectiveId"= SH."NewLabCancelBookingHeaderId"	
			join "PayType" pt ON PT."PayTypeId" = nlbh."PayTypeId"                                                                      
			left join "Patient" p ON p."PatientId" =nlbh."PatientId"		
			left join "Account" AR on AR."AccountId" = R."CreatedBy"
			join "Role" Rl on Rl."RoleId"=AR."RoleId"
			join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"
		where R."ReceiptAreaTypeId" = 9
		--and nlbh."LocationId"=2 and R."CreatedDate"::date='2023-04-18'
 	and case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::timestamp without time zone end and
	case when "toDate" is null then 1=1 else R."CreatedDate"::timestamp without time zone<=  "toDate" end and
 	case when "locationid" is null then 1=1 else  nlbh."LocationId" = "locationid"::int end and
	case when "accountid" is null then 1=1 else nlbh."CreatedBy"="accountid" end 
		
																		  								   
)

,pharma as (

select 
	coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
-- R."Cost" as "PaidAmount", 
	PT."PayTypeName",R."PaymentDetails",
	PH."PharmacySaleHeaderId" ,PH."BillNumber",
	A."FullName" "ReceiptCreatedBy",AR."RoleName" ,R."CreatedBy",
	PH."PatientName",PH."Mobile" ,Pa."UMRNo",
	 R."ReceiptId",RT."Name" as "AreaType",R."CreatedDate" "ReceiptDate",R."ReceiptTypeId"
	
	from "Receipt" R
		join "PharmacySaleHeader" PH on PH."PharmacySaleHeaderId"=R."RespectiveId"
		join "Account" A on A."AccountId"=R."CreatedBy"
		join "Role" AR on AR."RoleId"=A."RoleId"
		 join "PayType" PT ON PT."PayTypeId" = R."PayTypeId"  
		join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"	 	
		left join "Patient" Pa on Pa."PatientId"::text=PH."PatientId"::text
	where R."ReceiptAreaTypeId"=1  
 			
	 and case when "accountid" is null then 1=1 else R."CreatedBy"="accountid" end and
	
 	case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::timestamp without time zone end and
 	case when "toDate" is null then 1=1 else R."CreatedDate"::timestamp without time zone<=  "toDate" end and
  	case when "locationid" is null then 1=1 else PH."LocationId" = "locationid" end
UNION
	
select 
	coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
	 --R."Cost" as "PaidAmount", 
	PT."PayTypeName",R."PaymentDetails",
		PH."PharmacySaleHeaderId" ,PH."BillNumber",
		A."FullName" "ReceiptCreatedBy",AR."RoleName" ,R."CreatedBy",
		PH."PatientName",PH."Mobile" ,Pa."UMRNo",
		 R."ReceiptId",RT."Name" as "AreaType",R."CreatedDate" "ReceiptDate",R."ReceiptTypeId"
	from "PharmacySaleHeader" PH 
			join "SaleReturnHeader" SH on SH."PharmacySaleHeaderId"=PH."PharmacySaleHeaderId"
			join "Receipt" R on R."RespectiveId"= SH."SaleReturnHeaderId"
		join "Account" A on A."AccountId"=R."CreatedBy"
		join "Role" AR on AR."RoleId"=A."RoleId"
		 join "PayType" PT ON PT."PayTypeId" = R."PayTypeId"  
		join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"	 	
		left join "Patient" Pa on Pa."PatientId"::text=PH."PatientId"::text
	where R."ReceiptAreaTypeId"=7
	
		 and case when "accountid" is null then 1=1 else R."CreatedBy"="accountid" end and
		 case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::timestamp without time zone end and
		case when "toDate" is null then 1=1 else R."CreatedDate"::timestamp without time zone<=  "toDate" end and
		case when "locationid" is null then 1=1 else PH."LocationId" = "locationid" end		
)
,scan as(

select 
	coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
		-- R."Cost" as "PaidAmount",
	PT."PayTypeName",R."PaymentDetails",
			 PH."RequisitionNumber",
			 R."ReceiptId",RT."Name" as "AreaType",R."CreatedDate" "ReceiptDate",R."ReceiptTypeId",
			PA."FullName" as "PatientName",PA."Mobile" ,PA."UMRNo",
	R."CreatedBy",A."FullName" "ReceiptCreatedBy",AR."RoleName" 
	
		from "Receipt" R
		join "BookScanAppointment" PH on PH."BookScanAppointmentId"=R."RespectiveId" 
		join "Account" A on A."AccountId"=R."CreatedBy"
		join "Role" AR on AR."RoleId"=A."RoleId"
		 join "PayType" PT ON PT."PayTypeId" = R."PayTypeId"  
		join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"	
		left join "Patient" PA on PA."PatientId"=PH."PatientId"

	where  R."ReceiptAreaTypeId" in (10,11)
		 		
		and case when "accountid" is null then 1=1 else R."CreatedBy"="accountid" end and	
		case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::timestamp without time zone end and
		case when "toDate" is null then 1=1 else R."CreatedDate"::timestamp without time zone<=  "toDate" end and
		case when "locationid" is null then 1=1 else PH."LocationId" = "locationid" end
)
SELECT O."AccountId",O."ReceiptCreatedBy",O."RoleName",O."ReceiptDate",O."ReceiptId",O."ReceiptTypeId",
O."AreaType",O."RefId",
coalesce(O."PayTypeName"::character varying,'GRAND')"PayTypeName"
,O."PaymentDetails"--,coalesce(case when O."ReceiptTypeId"=2 then O."PaidAmount" end,0) as "RefundAmount" 
,sum(O."PaidAmount")-sum(O."RefundAmount") "PaidAmount",--O."RefundAmount",--O."BalanceAmount",sum(A."PaidAmount") "PaidAmount"
O."PatientName",O."UMRNo",O."Mobile"
from 
(
	Select  A."AccountId",AP."ReceiptCreatedBy",AP."RoleName",AP."ReceiptDate",AP."ReceiptId",AP."ReceiptTypeId",
AP."AreaType",AP."AppointmentNo" as "RefId",AP."PayTypeName",AP."PaymentDetails"
,AP."PaidAmount",AP."RefundAmount",--AP."BalanceAmount",
AP."PatientName",AP."UMRNo",AP."Mobile"
from accountdata A
join appointment AP on AP."CreatedBy"=A."AccountId"
UNION
	Select  A."AccountId",AP."ReceiptCreatedBy",AP."RoleName",AP."ReceiptDate",AP."ReceiptId",AP."ReceiptTypeId",
AP."AreaType",AP."AdmissionNo" as "RefId",AP."PayTypeName",AP."PaymentDetails"
,AP."PaidAmount",AP."RefundAmount",--AP."BalanceAmount",
AP."PatientName",AP."UMRNo",AP."Mobile"
from accountdata A
join admission AP on AP."CreatedBy"=A."AccountId"
UNION
Select  A."AccountId",AP."ReceiptCreatedBy",AP."RoleName",AP."ReceiptDate",AP."ReceiptId",AP."ReceiptTypeId",
AP."AreaType",AP."PatientId"::character varying as "RefId",AP."PayTypeName",AP."PaymentDetails"
,AP."PaidAmount",AP."RefundAmount",--AP."BalanceAmount",
AP."PatientName",AP."UMRNo",AP."Mobile"
from accountdata A
join patient AP on AP."CreatedBy"=A."AccountId"
UNION
Select  A."AccountId",AP."ReceiptCreatedBy",AP."RoleName",AP."ReceiptDate",AP."ReceiptId",AP."ReceiptTypeId",
AP."AreaType",AP."RequisitionNumber"::character varying as "RefId",AP."PayTypeName",AP."PaymentDetails"
,AP."PaidAmount",AP."RefundAmount",--AP."BalanceAmount",
AP."PatientName",AP."UMRNo",AP."Mobile"
from accountdata A
join lab AP on AP."CreatedBy"=A."AccountId"
UNION
Select  A."AccountId",AP."ReceiptCreatedBy",AP."RoleName",AP."ReceiptDate",AP."ReceiptId",AP."ReceiptTypeId",
AP."AreaType",AP."BillNumber"::character varying as "RefId",AP."PayTypeName",AP."PaymentDetails"
,AP."PaidAmount",AP."RefundAmount",--AP."BalanceAmount",
AP."PatientName",AP."UMRNo",AP."Mobile"
from accountdata A
join pharma AP on AP."CreatedBy"=A."AccountId"
	UNION
Select  A."AccountId",AP."ReceiptCreatedBy",AP."RoleName",AP."ReceiptDate",AP."ReceiptId",AP."ReceiptTypeId",
AP."AreaType",AP."RequisitionNumber"::character varying as "RefId",AP."PayTypeName",AP."PaymentDetails"
,AP."PaidAmount",AP."RefundAmount",--AP."BalanceAmount",
AP."PatientName",AP."UMRNo",AP."Mobile"
from accountdata A
join scan AP on AP."CreatedBy"=A."AccountId"	
	
)O

GROUP BY GROUPING SETS((O."AccountId",O."ReceiptCreatedBy",O."RoleName",O."ReceiptDate",
						O."ReceiptId",O."ReceiptTypeId",O."AreaType",O."RefId",O."PayTypeName",
						O."PaymentDetails",O."PatientName",O."UMRNo",O."Mobile"),(O."PayTypeName"), ())   

order by O."PayTypeName" asc, O."ReceiptDate" asc;

end
$BODY$;

DO $$                  
    BEGIN 
        IF EXISTS
            ( SELECT 1
              FROM   information_schema.tables 
              WHERE  table_schema = 'public'
              AND    table_name = 'PatientRegistrationCharge'
            )
        THEN
            UPDATE "PatientRegistrationCharge"
            SET "Name" = 'Patient Registration Charge';
        END IF ;
    END
   $$ ;
-----------------------------------------------------------------------Shivani 17July2023-----------------------------------------------------------------

 alter table IF EXISTS "ReferralForm"
drop constraint if exists "ReferralForm_ReferralDoctorId_fkey",
add column IF NOT EXISTS "ReferralDoctorId" integer,
add CONSTRAINT "ReferralForm_ReferralDoctorId_fkey" FOREIGN KEY ("ReferralDoctorId")
 REFERENCES public."Provider" ("ProviderId") MATCH SIMPLE;

-----------------------------------------------------------------------Chandana 18July2023-----------------------------------------------------------------
 alter table if exists"BirthCertificate" 
 add column IF NOT EXISTS "BabyWeight" INTEGER;
alter table if exists"BirthCertificate" 
add column IF NOT EXISTS "TypeOfDelivery" character varying;
alter table if exists"BirthCertificate" 
add column IF NOT EXISTS "MethodOfDelivery" character varying;
alter table if exists"BirthCertificate" 
add column IF NOT EXISTS "DurationOfPregnancy" character varying;
alter table if exists"BirthCertificate" 
add column IF NOT EXISTS "NoOfChildBorn" character varying;
-----------------------------------------------------------------------Tej 19July2023-----------------------------------------------------------------------
alter table if exists "Patient"
add column if not exists "Total" numeric(8,2)   default 0.00;

alter table if exists "Patient"
add column if not exists "DiscountInPercentage" numeric(8,2)  default 0.00;

alter table if exists "Patient"
add column if not exists "DiscountInRupees" numeric(8,2)   default 0.00;

alter table if exists "Appointment" 
add column if not exists "DiscountInPercentage" numeric(8,2)  default 0.00;

CREATE SEQUENCE IF NOT EXISTS public."GatePassType_Seq"
    INCREMENT 1
    START 1
    MINVALUE 1
    MAXVALUE 9223372036854775807
    CACHE 1;
-------------------------
CREATE TABLE IF NOT EXISTS public."GatePassType"
(
    "GatePassTypeId" integer NOT NULL DEFAULT nextval('"GatePassType_Seq"'::regclass),
    "Name" character varying(50) COLLATE pg_catalog."default" NOT NULL,
    "Active" boolean NOT NULL DEFAULT true,
    CONSTRAINT "GatePassType_pkey" PRIMARY KEY ("GatePassTypeId")
)
TABLESPACE pg_default;
----------------------------------

INSERT INTO public."GatePassType"("Name", "Active")
SELECT 'Provisional',true
WHERE
NOT EXISTS (
SELECT "Name" FROM public."GatePassType" WHERE "Name" = 'Provisional'
);

INSERT INTO public."GatePassType"("Name", "Active")
SELECT 'Final',true
WHERE
NOT EXISTS (
SELECT "Name" FROM public."GatePassType" WHERE "Name" = 'Final'
);

---------------------------------
ALTER TABLE if exists "GatePass"
ADD COLUMN if not exists  "TypeId" integer not null DEFAULT 2;
ALTER TABLE if exists "GatePass"
drop constraint if exists "FK_GatePass_TypeId",
ADD CONSTRAINT "FK_GatePass_TypeId" FOREIGN KEY ("TypeId")
        REFERENCES public."GatePassType" ("GatePassTypeId") ;
-----------------------------------------------------------------------------Shivani19July2023--------------------------------------------------------------------
alter table IF EXISTS "OrderPrescriptionMaster"
add column IF NOT EXISTS "ProviderId" integer,
drop constraint if exists "OrderPrescriptionMaster_ProviderId_fkey",
add CONSTRAINT "OrderPrescriptionMaster_ProviderId_fkey" FOREIGN KEY ("ProviderId")
 REFERENCES public."Provider" ("ProviderId") MATCH SIMPLE;
-----------------------------------------------------------------------------Kalyan 19July2023---------------------------------------------------------------------
CREATE SEQUENCE IF NOT EXISTS "TicketType_TicketTypeId_seq";
CREATE TABLE IF NOT EXISTS public."TicketType"
(
    "TicketTypeId" integer NOT NULL DEFAULT nextval('"TicketType_TicketTypeId_seq"'::regclass),
    "TicketTypeName" character varying(255) COLLATE pg_catalog."default" NOT NULL,
    "CreatedBy" integer NOT NULL,
    "CreatedDate" timestamp without time zone NOT NULL,
    "ModifiedBy" integer ,
    "ModifiedDate" timestamp without time zone,
    "Active" boolean NOT NULL DEFAULT true,
    CONSTRAINT "PK_TicketType_TicketTypeId" PRIMARY KEY ("TicketTypeId"),
    CONSTRAINT "FK_TicketType_CreatedById" FOREIGN KEY ("CreatedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_TicketType_ModifiedBy" FOREIGN KEY ("ModifiedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
);
------------------------------------2
CREATE SEQUENCE IF NOT EXISTS "CpxRelatedToDepartment_CpxRelatedToDepartmentId_seq";
CREATE TABLE IF NOT EXISTS public."CpxRelatedToDepartment"
(
    "CpxRelatedToDepartmentId" integer NOT NULL DEFAULT nextval('"CpxRelatedToDepartment_CpxRelatedToDepartmentId_seq"'::regclass),
    "CpxRelatedToDepartmentName" character varying(255) COLLATE pg_catalog."default" NOT NULL,
    "CreatedBy" integer NOT NULL,
    "CreatedDate" timestamp without time zone NOT NULL,
    "ModifiedBy" integer ,
    "ModifiedDate" timestamp without time zone,
    "Active" boolean NOT NULL DEFAULT true,
    CONSTRAINT "PK_CpxRelatedToDepartment_CpxRelatedToDepartmentId" PRIMARY KEY ("CpxRelatedToDepartmentId"),
    CONSTRAINT "FK_CpxRelatedToDepartment_CreatedById" FOREIGN KEY ("CreatedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_CpxRelatedToDepartment_ModifiedBy" FOREIGN KEY ("ModifiedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
);

------------------------------------3
CREATE SEQUENCE IF NOT EXISTS "RequestDepartment_RequestDepartmentId_seq";
CREATE TABLE IF NOT EXISTS public."RequestDepartment"
(
    "RequestDepartmentId" integer NOT NULL DEFAULT nextval('"RequestDepartment_RequestDepartmentId_seq"'::regclass),
    "RequestDepartmentName" character varying(255) COLLATE pg_catalog."default" NOT NULL,
    "CreatedBy" integer NOT NULL,
    "CreatedDate" timestamp without time zone NOT NULL,
    "ModifiedBy" integer ,
    "ModifiedDate" timestamp without time zone,
    "Active" boolean NOT NULL DEFAULT true,
    CONSTRAINT "PK_RequestDepartment_RequestDepartmentId" PRIMARY KEY ("RequestDepartmentId"),
    CONSTRAINT "FK_RequestDepartment_CreatedById" FOREIGN KEY ("CreatedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_RequestDepartment_ModifiedBy" FOREIGN KEY ("ModifiedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
);



CREATE SEQUENCE IF NOT EXISTS "InventoryRequest_InventoryRequestId_seq";
CREATE TABLE IF NOT EXISTS public."InventoryRequest"
(
    "InventoryRequestId" integer NOT NULL DEFAULT nextval('"InventoryRequest_InventoryRequestId_seq"'::regclass),
    "TicketTypeId" integer NOT NULL,
    "CpxRelatedToDepartmentId" integer NOT NULL,
    "RequisitionerName" character varying(100) COLLATE pg_catalog."default" NOT NULL,
    "RequestDepartmentId" integer NOT NULL,
    "LocationId" integer NOT NULL,
    "Item" character varying(100) COLLATE pg_catalog."default" NOT NULL,
    "ItemDetailsRequired" boolean NOT NULL,
    "ItemDetails" text COLLATE pg_catalog."default",
    "RepeatedItemRequired" boolean NOT NULL,
    "RepeatedItem" text COLLATE pg_catalog."default",
    "QuantityRequired" integer NOT NULL,
    "PreferredMakeandModel" character varying(250) COLLATE pg_catalog."default" NOT NULL,
    "ProductMainFeatures" character varying(250) COLLATE pg_catalog."default" NOT NULL,
    "EstimatedCost" numeric(8,2),
    "Budgeted" boolean NOT NULL ,
    "Priority" character varying(100) COLLATE pg_catalog."default" NOT NULL,
    "CreatedBy" integer NOT NULL,
    "CreatedDate" timestamp without time zone NOT NULL,
    "ModifiedBy" integer ,
    "ModifiedDate" timestamp without time zone ,
    "Active" boolean NOT NULL DEFAULT true,
    "InventoryRequestUrl" text COLLATE pg_catalog."default",
    "UploadedBy"  integer,
    "UploadedDate" timestamp without time zone,
    CONSTRAINT "PK_InventoryRequest_InventoryRequestId" PRIMARY KEY ("InventoryRequestId"),
    CONSTRAINT "FK_InventoryRequest_CreatedById" FOREIGN KEY ("CreatedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_InventoryRequest_ModifiedBy" FOREIGN KEY ("ModifiedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_InventoryRequest_TicketTypeId" FOREIGN KEY ("TicketTypeId")
        REFERENCES public."TicketType" ("TicketTypeId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_InventoryRequest_CpxRelatedToDepartmentId" FOREIGN KEY ("CpxRelatedToDepartmentId")
        REFERENCES public."CpxRelatedToDepartment" ("CpxRelatedToDepartmentId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_InventoryRequest_RequestDepartmentId" FOREIGN KEY ("RequestDepartmentId")
        REFERENCES public."RequestDepartment" ("RequestDepartmentId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_InventoryRequest_LocationId" FOREIGN KEY ("LocationId")
        REFERENCES public."Location" ("LocationId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_InventoryRequest_UploadedBy" FOREIGN KEY ("UploadedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
);
-----------------------------------------------------------------------------SaiJohn 20July2023-------------------------------------------------------------
CREATE SEQUENCE IF NOT EXISTS "Counseling_CounselingId_seq";
CREATE TABLE IF NOT EXISTS public."Counseling"
(
    "CounselingId" integer NOT NULL DEFAULT nextval('"Counseling_CounselingId_seq"'::regclass),
    "LocationId" integer NOT NULL,
    "AppointmentId" integer NOT NULL,
    "PatientId" integer NOT NULL,
    "PackageModuleId" integer NOT NULL,
    "ChargeCategoryId" integer NOT NULL,
    "SubTotal" numeric(8, 2) NOT NULL DEFAULT 0,
    "DiscountType" character varying(1),
    "DiscountPercentage" numeric(8, 2),
    "DiscountAmount" numeric(8, 2),
    "Discount" numeric(8, 2) NOT NULL DEFAULT 0,
    "Total" numeric(8, 2) NOT NULL DEFAULT 0,
    "Active" boolean NOT NULL DEFAULT true,
    "CreatedBy" integer NOT NULL,
    "CreatedDate" timestamp without time zone NOT NULL DEFAULT NOW(),
    "ModifiedBy" integer,
    "ModifiedDate" timestamp without time zone,
    CONSTRAINT "PK_Counseling_CounselingId" PRIMARY KEY ("CounselingId"),
    CONSTRAINT "FK_Counseling_PatientId" FOREIGN KEY ("PatientId")
        REFERENCES public."Patient" ("PatientId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
        NOT VALID,
    CONSTRAINT "FK_Counseling_PackageModuleId" FOREIGN KEY ("PackageModuleId")
        REFERENCES public."PackageModule" ("PackageModuleId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
        NOT VALID,
    CONSTRAINT "FK_Counseling_CreatedBy" FOREIGN KEY ("CreatedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
        NOT VALID,
    CONSTRAINT "FK_Counseling_ModifiedBy" FOREIGN KEY ("ModifiedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
        NOT VALID,
    CONSTRAINT "FK_Counseling_AppointmentId" FOREIGN KEY ("AppointmentId")
        REFERENCES public."Appointment" ("AppointmentId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
        NOT VALID,
    CONSTRAINT "FK_Counseling_LocationId" FOREIGN KEY ("LocationId")
        REFERENCES public."Location" ("LocationId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
        NOT VALID,
    CONSTRAINT "FK_Counseling_ChargeCategoryId" FOREIGN KEY ("ChargeCategoryId")
        REFERENCES public."ChargeCategory" ("ChargeCategoryId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
        NOT VALID
);

--------------------------------------------------------------Shivani 20July2023---------------------------------------------------------------------------------------
alter table IF EXISTS "ObEncounter" 
add COLUMN IF NOT EXISTS "MeasureCommonData" text;
alter table IF EXISTS "ObEncounter" 
add COLUMN IF NOT EXISTS "AncCardCloseCommonData" text;

-------------------------------------------------------------Manish 17July2023--------------------------------------------------------------------------------------

CREATE TABLE IF NOT EXISTS vendors."PharmacyProductApproval" (
	"PharmacyProductApprovalId" bigserial NOT NULL,
	"PharmacyProductId" int4 NULL,
	"PharmacyStockId" int4 NULL,
	"PurchaseRate" numeric NULL,
	"Mrp" numeric NULL,
	"SupplierId" int4 NULL,
	"TenderStatusId" int4 NULL,
	"PharmacyProductRequestId" int4 NULL,
	"CreatedBy" int4 NULL,
	"CreatedDate" timestamp NULL,
	CONSTRAINT "PharmacyProductApproval_pkey" PRIMARY KEY ("PharmacyProductApprovalId"),
	CONSTRAINT "PharmacyProductApproval_CreatedBy_fkey" FOREIGN KEY ("CreatedBy") REFERENCES public."Account"("AccountId"),
	CONSTRAINT "PharmacyProductApproval_PharmacyProductId_fkey" FOREIGN KEY ("PharmacyProductId") REFERENCES public."PharmacyProduct"("PharmacyProductId"),
	CONSTRAINT "PharmacyProductApproval_PharmacyProductRequestId_fkey" FOREIGN KEY ("PharmacyProductRequestId") REFERENCES vendors."PharmacyProductRequest"("PharmacyProductRequestId"),
	CONSTRAINT "PharmacyProductApproval_PharmacyStockId_fkey" FOREIGN KEY ("PharmacyStockId") REFERENCES public."PharmacyStock"("PharmacyStockId"),
	CONSTRAINT "PharmacyProductApproval_SupplierId_fkey" FOREIGN KEY ("SupplierId") REFERENCES public."Supplier"("SupplierId"),
	CONSTRAINT "PharmacyProductApproval_TenderStatusId_fkey" FOREIGN KEY ("TenderStatusId") REFERENCES vendors."TendorStatus"("TenderStatusId")
);
INSERT INTO vendors."TendorStatus"("Status")
SELECT 'Moved To Tender'
WHERE
NOT EXISTS (
SELECT "Status" FROM vendors."TendorStatus" WHERE  "Status" = 'Moved To Tender'
);

-------------



create table IF NOT EXISTS vendors."TenderRequestSupplierHeader"(
			"TenderRequestSupplierHeaderId" bigserial primary key,			
			"TenderStatusId" int references vendors."TendorStatus"("TenderStatusId"),			
			"TenderRaisedBy" int references "Account"("AccountId"),
			"SupplierId" int references "Supplier"("SupplierId"), 
			"TenderRaisedDate" timestamp  without time zone,
			"IsCompleteAccepted" boolean default false,
			"AcceptedDate" timestamp  without time zone,
			"IsCompleteRejected" boolean default false,
			"CompleteRejectedDate" timestamp without time zone	,
			"CompleteRejectionComment" text
);

create table IF NOT EXISTS vendors."TenderRequestSupplierDetail"(
			"TenderRequestSupplierDetailId" bigserial primary key,
			 "TenderRequestSupplierHeaderId" bigint references vendors."TenderRequestSupplierHeader"("TenderRequestSupplierHeaderId"),
			 "PharmacyProductApprovalId" bigint references vendors."PharmacyProductApproval"("PharmacyProductApprovalId"),
			 "VendorMrp" numeric,
			 "VendorPurchaseRate" numeric,
			 "TenderStatusId" int references vendors."TendorStatus"("TenderStatusId"),
			 "VendorRejected" boolean default false,
			"VendorRejectedDate" timestamp without time zone,
			"RejectionComment" text
);

-------
INSERT INTO vendors."TendorStatus"("Status")
SELECT 'Pending Vendor Acceptance'
WHERE
NOT EXISTS (
SELECT "Status" FROM vendors."TendorStatus" WHERE  "Status" = 'Pending Vendor Acceptance'
);

INSERT INTO vendors."TendorStatus"("Status")
SELECT 'PO Sent'
WHERE
NOT EXISTS (
SELECT "Status" FROM vendors."TendorStatus" WHERE  "Status" = 'PO Sent'
);

-----------

INSERT INTO vendors."TendorStatus"("Status")
SELECT 'VendorAccepted'
WHERE
NOT EXISTS (
SELECT "Status" FROM vendors."TendorStatus" WHERE  "Status" = 'VendorAccepted'
);
INSERT INTO vendors."TendorStatus"("Status")
SELECT 'VendorRejected'
WHERE
NOT EXISTS (
SELECT "Status" FROM vendors."TendorStatus" WHERE  "Status" = 'VendorRejected'
);
INSERT INTO vendors."TendorStatus"("Status")
SELECT 'PartialAccepted'
WHERE
NOT EXISTS (
SELECT "Status" FROM vendors."TendorStatus" WHERE  "Status" = 'PartialAccepted'
);

create table if not exists "PharmacyProductType"(
				"PharmacyProductTypeId" serial primary key,
				"TypeName" text,
				"Active" boolean,
				"CreatedBy" int references "Account"("AccountId"),
				"CreatedDate" timestamp without time zone,
				"ModifiedBy" int references "Account"("AccountId"),
				"ModifiedDate" timestamp without time zone
);


alter  table  if exists "PharmacyProductType" 
add column if not exists "IsGeneralItem" boolean default false;
 
create table if not exists "PharmacyProductSubType"(
				"PharmacyProductSubTypeId" serial primary key,
				"PharmacyProductTypeId" int references "PharmacyProductType"("PharmacyProductTypeId"),
				"SubTypeName" text,
				"Active" boolean,
				"CreatedBy" int references "Account"("AccountId"),
				"CreatedDate" timestamp without time zone,
				"ModifiedBy" int references "Account"("AccountId"),
				"ModifiedDate" timestamp without time zone
);

alter table if  exists "PharmacyProduct" 
add column if not exists "StorageTypeId" int references "LookupValue"("LookupValueId"),
add column if not exists "PharmacyProductTypeId" int references "PharmacyProductType"("PharmacyProductTypeId"),
add column if not exists "PharmacyProductSubTypeId" int references "PharmacyProductSubType"("PharmacyProductSubTypeId");



alter table if exists "PharmacyProduct" 
 add column if not exists "OnlyConsumable" boolean default false;


alter table if exists vendors."TenderRequestSupplierDetail" 
add column if not exists "VendorQuantity" int;

create table if not exists vendors."IncomingQuotationHeader"(
				"IncomingQuotationHeaderId" bigserial primary key,
				"TenderRequestSupplierHeaderId" bigint references vendors."TenderRequestSupplierHeader"("TenderRequestSupplierHeaderId"),
				"TenderStatusId" int references vendors."TendorStatus"("TenderStatusId"),
				"DeliveryDate" date,
				"RaisedBy" int references "Account"("AccountId"),
				"RaisedDate" timestamp without time zone,
				"ApprovedBy" int references "Account"("AccountId"),
				"ApprovedDate" timestamp without time zone
);

create table if not exists vendors."IncomingQuotationDetail"(
					"IncomingQuotationDetailId" bigserial primary key,
					"IncomingQuotationHeaderId" bigint references vendors."IncomingQuotationHeader"("IncomingQuotationHeaderId"),
					"TenderRequestSupplierDetailId" bigint references vendors."TenderRequestSupplierDetail"("TenderRequestSupplierDetailId")
);


alter table if exists vendors."PharmacyProductRequest" 
drop column if exists "PharmacyStockId",
drop column if exists "RolStocksId";

alter table if exists vendors."PharmacyProductRequest" 
add column if not exists "PharmacyWareHouseId" int references "PharmacyWareHouse"("PharmacyWareHouseId");


alter table if exists vendors."PharmacyProductApproval" 
drop column if exists "PharmacyStockId";

alter table if exists vendors."PharmacyProductApproval" 
add column if not exists "PharmacyWareHouseId" int references "PharmacyWareHouse"("PharmacyWareHouseId");

alter table if exists "Supplier" 
add column if not exists "DeliverDays" int ;


alter table if exists vendors."PharmacyProductApproval" 
add column if not exists "Quantity" int;

create table if not exists vendors."PurchaseOrderHeader"(
					"PurchaseOrderHeaderId" bigserial primary key,
					"PONumber" varchar(250),
					"PORaiseDate" timestamp without time zone,
					"EstimatedDeliveryDate" date,
					"CreatedBy" int references "Account"("AccountId"),
					"CreatedDate" timestamp without time zone,
					"TenderStatusId" int references vendors."TendorStatus"("TenderStatusId"),
					"TotalAmount" numeric,
					"TotalTax" numeric,
				    "TotalNetAmount" numeric,
				    "SupplierId" int references "Supplier"("SupplierId"),
				    "PharmacyWareHouseId" int references "PharmacyWareHouse"("PharmacyWareHouseId")
);

create table if not exists vendors."PurchaseOrderDetail"(
				"PurchaseOrderDetailId" bigserial primary key,
				"PurchaseOrderHeaderId" bigint references vendors."PurchaseOrderHeader"("PurchaseOrderHeaderId"),
				"PharmacyProductApprovalId" bigint references vendors."PharmacyProductApproval"("PharmacyProductApprovalId"),
				"Quantity" int ,
				"Amount" numeric,
				"TaxAmount" numeric,
				"NetAmount" numeric
);
                                

alter table if exists "PharmacyPurchaseHeader" 
add column if not exists "PurchaseOrderHeaderId" bigint references vendors."PurchaseOrderHeader"("PurchaseOrderHeaderId");
alter table if exists "PharmacyPurchaseDetail" 
add column if not exists "PurchaseOrderDetailId" bigint references vendors."PurchaseOrderDetail"("PurchaseOrderDetailId");

INSERT INTO vendors."TendorStatus"("Status")
SELECT 'Partial PO'
WHERE
NOT EXISTS (
SELECT "Status" FROM vendors."TendorStatus" WHERE  "Status" = 'Partial PO'
);
INSERT INTO vendors."TendorStatus"("Status")
SELECT 'Completed'
WHERE
NOT EXISTS (
SELECT "Status" FROM vendors."TendorStatus" WHERE  "Status" = 'Completed'
);

alter table if exists  vendors."PurchaseOrderDetail" 
add column if not exists "IsAddedByGrn" bool default false;
----------------------------------------------------------------------------Srilekha 21July2023---------------------------------------------

DROP FUNCTION IF EXISTS public."collection_userLogin"(timestamp without time zone, timestamp without time zone, integer, integer);

CREATE OR REPLACE FUNCTION public."collection_userLogin"(
	"fromDate" timestamp without time zone DEFAULT NULL::timestamp without time zone,
	"toDate" timestamp without time zone DEFAULT NULL::timestamp without time zone,
	accountid integer DEFAULT NULL::integer,
	locationid integer DEFAULT NULL::integer)
    RETURNS TABLE("AccountId" integer, "ReceiptCreatedBy" text, "RoleName" character varying, "ReceiptDate" timestamp without time zone, "ReceiptId" integer, "ReceiptTypeId" integer, "AreaType" character varying, "RefId" character varying, "PayTypeName" character varying, "PaymentDetails" character varying, "PaidAmount" numeric, "PatientName" text, "UMRNo" character varying, "Mobile" character varying) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
begin
return query

with accountdata as (
select a."AccountId",a."FullName" "EmployeeName",rol."RoleName"
from "Account" a
JOIN "LocationAccountMap" LAM on LAM."AccountId"=a."AccountId"  
join "Role" rol on rol."RoleId" = a."RoleId" and lower(rol."RoleName") <> lower('Patient')
where a."RoleId"<>4  --and a."AccountId"=6776 and LAM."LocationId"=2
 and	case when accountid is null then 1=1 else a."AccountId"=accountid end   
AND CASE WHEN (locationid IS NULL OR locationid=0) THEN 1=1 ELSE LAM."LocationId"=locationid END
)
, appointment as (

select R."ReceiptId",A."FullName" "ReceiptCreatedBy",Rl."RoleName",R."CreatedDate" "ReceiptDate",R."CreatedBy",RT."Name" as "AreaType"
, coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
	--R."Cost"  as "PaidAmount" ,
	R."ReceiptTypeId"
 ,Ad."FollowUpForAppointmentId",
	Ad."AppointmentDate",Ad."AppointmentNo", Ad."AppointmentTime",Ad."LocationId",
pa."FullName" "PatientName",Pa."UMRNo",pa."Mobile",pr."FullName" as "ProviderName",Ad."PaymentType",
pt."PayTypeName",  CASE
    WHEN R."PaymentDetails" = 'null' THEN null
    ELSE R."PaymentDetails"
  END AS "PaymentDetails" , R."AppointmentId",R."IsAppointmentReceipt" 
	from "Receipt" R
join "Appointment" Ad on Ad."AppointmentId"=R."RespectiveId" 
join "Provider" pr on pr."ProviderId"= ad."ProviderId"
join "Patient" pa on Ad."PatientId"=pa."PatientId"
join "Account" A on A."AccountId"=R."CreatedBy"
join "Role" Rl on Rl."RoleId"=A."RoleId"
join "PayType" pt on pt."PayTypeId"=R."PayTypeId"
join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"
	where  R."Active" <> false  and R."ReceiptAreaTypeId" in (4,5) --and

and case when "accountid" is null then 1=1 else  R."CreatedBy"  = "accountid" end  
 and case when "locationid" is null then 1=1 else Ad."LocationId" = "locationid" end

 	and case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::timestamp without time zone end 
 		and case when "toDate" is null then 1=1 else R."CreatedDate"::timestamp without time zone<=  "toDate" end 
	
 
)
,patient as(			
						select 
                               coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
	
                                A."FullName" as "ReceiptCreatedBy",Rl."RoleName",
                                P."FullName" as "PatientName",P."FirstName",P."MiddleName",P."LastName",
                                P."Age",P."Gender",P."UMRNo",P."Mobile",P."DateOfBirth",
                                R."ReceiptId",R."CreatedBy",RT."Name" as "AreaType",P."PatientId",
				                PT."PayTypeName",R."PaymentDetails",R."CreatedDate" "ReceiptDate"	,R."ReceiptTypeId"
	                            FROM "Receipt" R
	                            join "Patient" P on P."PatientId" = R."RespectiveId"  
								--join  "Account" PA on PA."ReferenceId"=P."PatientId"
								--JOIN "LocationAccountMap" LAM on LAM."AccountId"=PA."AccountId"  
	                           join "MasterBill" MB on MB."MasterBillId"=R."MasterBillId"
								join "Account" A on A."AccountId" = R."CreatedBy"
						        join "Role" Rl on Rl."RoleId"=A."RoleId"
	                            join "PayType" PT on PT."PayTypeId" = R."PayTypeId"
							join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"
								where  R."ReceiptAreaTypeId" in (3,6)
								
 	and case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::timestamp without time zone end and
 	case when "toDate" is null then 1=1 else R."CreatedDate"::timestamp without time zone<=  "toDate" end and
	case when "locationid" is null then 1=1 else  MB."LocationId" = "locationid"::int end and
	case when "accountid" is null then 1=1 else R."CreatedBy"="accountid" end 
	
)

,servicepayments as (
	
select R."ReceiptId",Rl."RoleName",R."CreatedDate" "ReceiptDate",
A."FullName" "ReceiptCreatedBy" ,pt."PayTypeName",R."PaymentDetails"
,R."CreatedBy",'Services & Payments' as "AreaType",R."ReceiptTypeId",
-- R."Cost"  as "PaidAmount" 
	coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
 --,Ad."AdmissionNo",ad."AdmissionDate",
	Ad."AppointmentNo",
pa."FullName" "PatientName",pa."UMRNo",pa."Mobile",pr."FullName" as "ProviderName"

	from "Receipt" R
join "Appointment" ad on Ad."AppointmentId"=R."RespectiveId" and ad."Active" is not false
join "Provider" pr on pr."ProviderId"= ad."ProviderId"
join "Patient" pa on Ad."PatientId"=pa."PatientId"
join "Account" A on A."AccountId"=R."CreatedBy"
join "Role" Rl on Rl."RoleId"=A."RoleId"
join "PayType" pt on pt."PayTypeId"=R."PayTypeId"
	join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"
	where R."Active" is not false and R."ReceiptAreaTypeId" in (12,13) and
	
case when "accountid" is null then 1=1 else  R."CreatedBy"  = "accountid" end 
and case when "locationid" is null then 1=1 else Ad."LocationId" = "locationid" end 
and case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::timestamp without time zone end 
 		and case when "toDate" is null then 1=1 else R."CreatedDate"::timestamp without time zone<=  "toDate" end  

)
,lab as (

SELECT 
	coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
	-- R."Cost" as "PaidAmount",
	PT."PayTypeName", CASE
    WHEN R."PaymentDetails" = 'null' THEN null
    ELSE R."PaymentDetails"
  END AS "PaymentDetails" , 
	 AR."FullName" "ReceiptCreatedBy",Rl."RoleName",R."CreatedBy",
	 nlbh."RequisitionNumber",	
	 nlbh."PatientId", nlbh."DoctorId",
	COALESCE (nlbh."PatientName" ,p."FullName" ) as "PatientName",COALESCE (p."Mobile" ,nlbh."Mobile" ) as "Mobile", p."UMRNo",           
      R."ReceiptId",RT."Name" as "AreaType" ,R."CreatedDate" "ReceiptDate"	,R."ReceiptTypeId"
			 from "Receipt" R
			join "NewLabBookingHeader" nlbh on nlbh."NewLabBookingHeaderId"=R."RespectiveId"                                
			join "PayType" pt ON PT."PayTypeId" = nlbh."PayTypeId"                                                                      
			left join "Patient" p ON p."PatientId" =nlbh."PatientId"
			left join "Provider" prv on prv."ProviderId" = nlbh."DoctorId"                                
			left join "Account" e on e."AccountId" = nlbh."EmployeeId" 
			left join "Account" AR on AR."AccountId" = R."CreatedBy"
			join "Role" Rl on Rl."RoleId"=AR."RoleId"
			join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"
		where R."ReceiptAreaTypeId" = 8
		--and nlbh."LocationId"=2 and R."CreatedDate"::date='2023-04-18'
 	and case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::timestamp without time zone end and
	case when "toDate" is null then 1=1 else R."CreatedDate"::timestamp without time zone<=  "toDate" end and
 	case when "locationid" is null then 1=1 else  nlbh."LocationId" = "locationid"::int end and
	case when "accountid" is null then 1=1 else nlbh."CreatedBy"="accountid" end 

UNION
		
SELECT 
	coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
	-- R."Cost" as "PaidAmount", 
	PT."PayTypeName",R."PaymentDetails",
	 AR."FullName" "ReceiptCreatedBy" ,Rl."RoleName",R."CreatedBy",
	 nlbh."RequisitionNumber",
	 nlbh."PatientId", nlbh."DoctorId", 
	COALESCE (nlbh."PatientName" ,p."FullName" ) as "PatientName",COALESCE (p."Mobile" ,nlbh."Mobile" ) as "Mobile", p."UMRNo",           
      R."ReceiptId",RT."Name" as "AreaType",R."CreatedDate" "ReceiptDate"	,R."ReceiptTypeId"
			
	
		from "NewLabBookingHeader" nlbh
	join "NewLabCancelBookingHeader" SH on SH."NewLabBookingHeaderId"=nlbh."NewLabBookingHeaderId"
	join "Receipt" R on R."RespectiveId"= SH."NewLabCancelBookingHeaderId"	
			join "PayType" pt ON PT."PayTypeId" = nlbh."PayTypeId"                                                                      
			left join "Patient" p ON p."PatientId" =nlbh."PatientId"		
			left join "Account" AR on AR."AccountId" = R."CreatedBy"
			join "Role" Rl on Rl."RoleId"=AR."RoleId"
			join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"
		where R."ReceiptAreaTypeId" = 9
		--and nlbh."LocationId"=2 and R."CreatedDate"::date='2023-04-18'
 	and case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::timestamp without time zone end and
	case when "toDate" is null then 1=1 else R."CreatedDate"::timestamp without time zone<=  "toDate" end and
 	case when "locationid" is null then 1=1 else  nlbh."LocationId" = "locationid"::int end and
	case when "accountid" is null then 1=1 else nlbh."CreatedBy"="accountid" end 
		
																		  								   
)

,pharma as (

select 
	coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
-- R."Cost" as "PaidAmount", 
	PT."PayTypeName",R."PaymentDetails",
	PH."PharmacySaleHeaderId" ,PH."BillNumber",
	A."FullName" "ReceiptCreatedBy",AR."RoleName" ,R."CreatedBy",
	PH."PatientName",PH."Mobile" ,Pa."UMRNo",
	 R."ReceiptId",RT."Name" as "AreaType",R."CreatedDate" "ReceiptDate",R."ReceiptTypeId"
	
	from "Receipt" R
		join "PharmacySaleHeader" PH on PH."PharmacySaleHeaderId"=R."RespectiveId"
		join "Account" A on A."AccountId"=R."CreatedBy"
		join "Role" AR on AR."RoleId"=A."RoleId"
		 join "PayType" PT ON PT."PayTypeId" = R."PayTypeId"  
		join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"	 	
		left join "Patient" Pa on Pa."PatientId"::text=PH."PatientId"::text
	where R."ReceiptAreaTypeId"=1  
 			
	 and case when "accountid" is null then 1=1 else R."CreatedBy"="accountid" end and
	
 	case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::timestamp without time zone end and
 	case when "toDate" is null then 1=1 else R."CreatedDate"::timestamp without time zone<=  "toDate" end and
  	case when "locationid" is null then 1=1 else PH."LocationId" = "locationid" end
UNION
	
select 
	coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
	 --R."Cost" as "PaidAmount", 
	PT."PayTypeName",R."PaymentDetails",
		PH."PharmacySaleHeaderId" ,PH."BillNumber",
		A."FullName" "ReceiptCreatedBy",AR."RoleName" ,R."CreatedBy",
		PH."PatientName",PH."Mobile" ,Pa."UMRNo",
		 R."ReceiptId",RT."Name" as "AreaType",R."CreatedDate" "ReceiptDate",R."ReceiptTypeId"
	from "PharmacySaleHeader" PH 
			join "SaleReturnHeader" SH on SH."PharmacySaleHeaderId"=PH."PharmacySaleHeaderId"
			join "Receipt" R on R."RespectiveId"= SH."SaleReturnHeaderId"
		join "Account" A on A."AccountId"=R."CreatedBy"
		join "Role" AR on AR."RoleId"=A."RoleId"
		 join "PayType" PT ON PT."PayTypeId" = R."PayTypeId"  
		join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"	 	
		left join "Patient" Pa on Pa."PatientId"::text=PH."PatientId"::text
	where R."ReceiptAreaTypeId"=7
	
		 and case when "accountid" is null then 1=1 else R."CreatedBy"="accountid" end and
		 case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::timestamp without time zone end and
		case when "toDate" is null then 1=1 else R."CreatedDate"::timestamp without time zone<=  "toDate" end and
		case when "locationid" is null then 1=1 else PH."LocationId" = "locationid" end		
)
,scan as(

select 
	coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
		-- R."Cost" as "PaidAmount",
	PT."PayTypeName",R."PaymentDetails",
			 PH."RequisitionNumber",
			 R."ReceiptId",RT."Name" as "AreaType",R."CreatedDate" "ReceiptDate",R."ReceiptTypeId",
			PA."FullName" as "PatientName",PA."Mobile" ,PA."UMRNo",
	R."CreatedBy",A."FullName" "ReceiptCreatedBy",AR."RoleName" 
	
		from "Receipt" R
		join "BookScanAppointment" PH on PH."BookScanAppointmentId"=R."RespectiveId" 
		join "Account" A on A."AccountId"=R."CreatedBy"
		join "Role" AR on AR."RoleId"=A."RoleId"
		 join "PayType" PT ON PT."PayTypeId" = R."PayTypeId"  
		join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"	
		left join "Patient" PA on PA."PatientId"=PH."PatientId"

	where  R."ReceiptAreaTypeId" in (10,11)
		 		
		and case when "accountid" is null then 1=1 else R."CreatedBy"="accountid" end and	
		case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::timestamp without time zone end and
		case when "toDate" is null then 1=1 else R."CreatedDate"::timestamp without time zone<=  "toDate" end and
		case when "locationid" is null then 1=1 else PH."LocationId" = "locationid" end
)
SELECT O."AccountId",O."ReceiptCreatedBy",O."RoleName",O."ReceiptDate",O."ReceiptId",O."ReceiptTypeId",
O."AreaType",O."RefId",
coalesce(O."PayTypeName"::character varying,'GRAND')"PayTypeName"
,O."PaymentDetails"--,coalesce(case when O."ReceiptTypeId"=2 then O."PaidAmount" end,0) as "RefundAmount" 
,sum(O."PaidAmount")-sum(O."RefundAmount") "PaidAmount",--O."RefundAmount",--O."BalanceAmount",sum(A."PaidAmount") "PaidAmount"
O."PatientName",O."UMRNo",O."Mobile"
from 
(
	Select  A."AccountId",AP."ReceiptCreatedBy",AP."RoleName",AP."ReceiptDate",AP."ReceiptId",AP."ReceiptTypeId",
AP."AreaType",AP."AppointmentNo" as "RefId",AP."PayTypeName",AP."PaymentDetails"
,AP."PaidAmount",AP."RefundAmount",--AP."BalanceAmount",
AP."PatientName",AP."UMRNo",AP."Mobile"
from accountdata A
join appointment AP on AP."CreatedBy"=A."AccountId"
UNION
	Select  A."AccountId",AP."ReceiptCreatedBy",AP."RoleName",AP."ReceiptDate",AP."ReceiptId",AP."ReceiptTypeId",
AP."AreaType",AP."AppointmentNo" as "RefId",AP."PayTypeName",AP."PaymentDetails"
,AP."PaidAmount",AP."RefundAmount",--AP."BalanceAmount",
AP."PatientName",AP."UMRNo",AP."Mobile"
from accountdata A
join servicepayments AP on AP."CreatedBy"=A."AccountId"
UNION
Select  A."AccountId",AP."ReceiptCreatedBy",AP."RoleName",AP."ReceiptDate",AP."ReceiptId",AP."ReceiptTypeId",
AP."AreaType",AP."PatientId"::character varying as "RefId",AP."PayTypeName",AP."PaymentDetails"
,AP."PaidAmount",AP."RefundAmount",--AP."BalanceAmount",
AP."PatientName",AP."UMRNo",AP."Mobile"
from accountdata A
join patient AP on AP."CreatedBy"=A."AccountId"
UNION
Select  A."AccountId",AP."ReceiptCreatedBy",AP."RoleName",AP."ReceiptDate",AP."ReceiptId",AP."ReceiptTypeId",
AP."AreaType",AP."RequisitionNumber"::character varying as "RefId",AP."PayTypeName",AP."PaymentDetails"
,AP."PaidAmount",AP."RefundAmount",--AP."BalanceAmount",
AP."PatientName",AP."UMRNo",AP."Mobile"
from accountdata A
join lab AP on AP."CreatedBy"=A."AccountId"
UNION
Select  A."AccountId",AP."ReceiptCreatedBy",AP."RoleName",AP."ReceiptDate",AP."ReceiptId",AP."ReceiptTypeId",
AP."AreaType",AP."BillNumber"::character varying as "RefId",AP."PayTypeName",AP."PaymentDetails"
,AP."PaidAmount",AP."RefundAmount",--AP."BalanceAmount",
AP."PatientName",AP."UMRNo",AP."Mobile"
from accountdata A
join pharma AP on AP."CreatedBy"=A."AccountId"
	UNION
Select  A."AccountId",AP."ReceiptCreatedBy",AP."RoleName",AP."ReceiptDate",AP."ReceiptId",AP."ReceiptTypeId",
AP."AreaType",AP."RequisitionNumber"::character varying as "RefId",AP."PayTypeName",AP."PaymentDetails"
,AP."PaidAmount",AP."RefundAmount",--AP."BalanceAmount",
AP."PatientName",AP."UMRNo",AP."Mobile"
from accountdata A
join scan AP on AP."CreatedBy"=A."AccountId"	
	
)O

GROUP BY GROUPING SETS((O."AccountId",O."ReceiptCreatedBy",O."RoleName",O."ReceiptDate",
						O."ReceiptId",O."ReceiptTypeId",O."AreaType",O."RefId",O."PayTypeName",
						O."PaymentDetails",O."PatientName",O."UMRNo",O."Mobile"),(O."PayTypeName"), ())   

order by O."PayTypeName" asc, O."ReceiptDate" asc;

end
$BODY$;

ALTER FUNCTION public."collection_userLogin"(timestamp without time zone, timestamp without time zone, integer, integer)
    OWNER TO postgres;

-----------------------------------Chandana25July2023-------------------------------------------
alter table if exists "DietConditionHeader" 
add column if not exists "ShiftIds" CHARACTER varying;
-----------------------------------Radhika26July2023---------------------------------------------
alter table if exists "GynEncounter"
add column if not exists "MeasureCommonData" text;
---------------------------------Srilekha26July2023-----------------------------------------------

 DROP FUNCTION if exists public."collection_userLogin"(timestamp without time zone, timestamp without time zone, integer, integer);

CREATE OR REPLACE FUNCTION public."collection_userLogin"(
	"fromDate" timestamp without time zone DEFAULT NULL::timestamp without time zone,
	"toDate" timestamp without time zone DEFAULT NULL::timestamp without time zone,
	accountid integer DEFAULT NULL::integer,
	locationid integer DEFAULT NULL::integer)
    RETURNS TABLE("AccountId" integer, "ReceiptCreatedBy" text, "RoleName" character varying, "ReceiptDate" timestamp without time zone, "ReceiptId" integer, "ReceiptTypeId" integer, "AreaType" character varying, "RefId" character varying, "PayTypeName" character varying, "PaymentDetails" character varying, "PaidAmount" numeric, "PatientName" text, "UMRNo" character varying, "Mobile" character varying) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
begin
return query

with accountdata as (
select a."AccountId",a."FullName" "EmployeeName",rol."RoleName"
from "Account" a
JOIN "LocationAccountMap" LAM on LAM."AccountId"=a."AccountId"  
join "Role" rol on rol."RoleId" = a."RoleId" and lower(rol."RoleName") <> lower('Patient')
where a."RoleId"<>4  --and a."AccountId"=6776 and LAM."LocationId"=2
 and	case when accountid is null then 1=1 else a."AccountId"=accountid end   
AND CASE WHEN (locationid IS NULL OR locationid=0) THEN 1=1 ELSE LAM."LocationId"=locationid END
)
, appointment as (

select R."ReceiptId",A."FullName" "ReceiptCreatedBy",Rl."RoleName",R."CreatedDate" "ReceiptDate",R."CreatedBy",RT."Name" as "AreaType"
, coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
	--R."Cost"  as "PaidAmount" ,
	R."ReceiptTypeId"
 ,Ad."FollowUpForAppointmentId",
	Ad."AppointmentDate",Ad."AppointmentNo", Ad."AppointmentTime",Ad."LocationId",
pa."FullName" "PatientName",Pa."UMRNo",pa."Mobile",pr."FullName" as "ProviderName",Ad."PaymentType",
pt."PayTypeName",  CASE
    WHEN R."PaymentDetails" = 'null' THEN null
    ELSE R."PaymentDetails"
  END AS "PaymentDetails" , R."AppointmentId",R."IsAppointmentReceipt" 
	from "Receipt" R
join "Appointment" Ad on Ad."AppointmentId"=R."RespectiveId" 
join "Provider" pr on pr."ProviderId"= ad."ProviderId"
join "Patient" pa on Ad."PatientId"=pa."PatientId"
join "Account" A on A."AccountId"=R."CreatedBy"
join "Role" Rl on Rl."RoleId"=A."RoleId"
join "PayType" pt on pt."PayTypeId"=R."PayTypeId"
join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"
	where  R."Active" <> false  and R."ReceiptAreaTypeId" in (4,5) --and

and case when "accountid" is null then 1=1 else  R."CreatedBy"  = "accountid" end  
 and case when "locationid" is null then 1=1 else Ad."LocationId" = "locationid" end

 	and case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::timestamp without time zone end 
 		and case when "toDate" is null then 1=1 else R."CreatedDate"::timestamp without time zone<=  "toDate" end 
	
 
)
,patient as(			
						select 
                               coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
	
                                A."FullName" as "ReceiptCreatedBy",Rl."RoleName",
                                P."FullName" as "PatientName",P."FirstName",P."MiddleName",P."LastName",
                                P."Age",P."Gender",P."UMRNo",P."Mobile",P."DateOfBirth",
                                R."ReceiptId",R."CreatedBy",RT."Name" as "AreaType",P."PatientId",
				                PT."PayTypeName",R."PaymentDetails",R."CreatedDate" "ReceiptDate"	,R."ReceiptTypeId"
	                            FROM "Receipt" R
	                            join "Patient" P on P."PatientId" = R."RespectiveId"  
								--join  "Account" PA on PA."ReferenceId"=P."PatientId"
								--JOIN "LocationAccountMap" LAM on LAM."AccountId"=PA."AccountId"  
	                           join "MasterBill" MB on MB."MasterBillId"=R."MasterBillId"
								join "Account" A on A."AccountId" = R."CreatedBy"
						        join "Role" Rl on Rl."RoleId"=A."RoleId"
	                            join "PayType" PT on PT."PayTypeId" = R."PayTypeId"
							join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"
								where  R."ReceiptAreaTypeId" in (3,6)
								
 	and case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::timestamp without time zone end and
 	case when "toDate" is null then 1=1 else R."CreatedDate"::timestamp without time zone<=  "toDate" end and
	case when "locationid" is null then 1=1 else  MB."LocationId" = "locationid"::int end and
	case when "accountid" is null then 1=1 else R."CreatedBy"="accountid" end 
	
)

,servicepayments as (
	
select R."ReceiptId",Rl."RoleName",R."CreatedDate" "ReceiptDate",
A."FullName" "ReceiptCreatedBy" ,pt."PayTypeName",R."PaymentDetails"
,R."CreatedBy",'Services & Payments' as "AreaType",R."ReceiptTypeId",
-- R."Cost"  as "PaidAmount" 
	coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
 --,Ad."AdmissionNo",ad."AdmissionDate",
	Ad."AppointmentNo",
pa."FullName" "PatientName",pa."UMRNo",pa."Mobile",pr."FullName" as "ProviderName"

	from "Receipt" R
join "Appointment" ad on Ad."AppointmentId"=R."RespectiveId" and ad."Active" is not false
join "Provider" pr on pr."ProviderId"= ad."ProviderId"
join "Patient" pa on Ad."PatientId"=pa."PatientId"
join "Account" A on A."AccountId"=R."CreatedBy"
join "Role" Rl on Rl."RoleId"=A."RoleId"
join "PayType" pt on pt."PayTypeId"=R."PayTypeId"
	join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"
	where R."Active" is not false and R."ReceiptAreaTypeId" in (12,13) and
	
case when "accountid" is null then 1=1 else  R."CreatedBy"  = "accountid" end 
and case when "locationid" is null then 1=1 else Ad."LocationId" = "locationid" end 
and case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::timestamp without time zone end 
 		and case when "toDate" is null then 1=1 else R."CreatedDate"::timestamp without time zone<=  "toDate" end  

)
,lab as (

SELECT 
	coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
	-- R."Cost" as "PaidAmount",
	PT."PayTypeName", CASE
    WHEN R."PaymentDetails" = 'null' THEN null
    ELSE R."PaymentDetails"
  END AS "PaymentDetails" , 
	 AR."FullName" "ReceiptCreatedBy",Rl."RoleName",R."CreatedBy",
	 nlbh."RequisitionNumber",	
	 nlbh."PatientId", nlbh."DoctorId",
	COALESCE (nlbh."PatientName" ,p."FullName" ) as "PatientName",COALESCE (p."Mobile" ,nlbh."Mobile" ) as "Mobile", p."UMRNo",           
      R."ReceiptId",RT."Name" as "AreaType" ,R."CreatedDate" "ReceiptDate"	,R."ReceiptTypeId"
			 from "Receipt" R
			join "NewLabBookingHeader" nlbh on nlbh."NewLabBookingHeaderId"=R."RespectiveId"                                
			join "PayType" pt ON PT."PayTypeId" = R."PayTypeId"                                                                      
			left join "Patient" p ON p."PatientId" =nlbh."PatientId"
			left join "Provider" prv on prv."ProviderId" = nlbh."DoctorId"                                
			left join "Account" e on e."AccountId" = nlbh."EmployeeId" 
			left join "Account" AR on AR."AccountId" = R."CreatedBy"
			join "Role" Rl on Rl."RoleId"=AR."RoleId"
			join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"
		where R."ReceiptAreaTypeId" = 8
		--and nlbh."LocationId"=2 and R."CreatedDate"::date='2023-04-18'
 	and case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::timestamp without time zone end and
	case when "toDate" is null then 1=1 else R."CreatedDate"::timestamp without time zone<=  "toDate" end and
 	case when "locationid" is null then 1=1 else  nlbh."LocationId" = "locationid"::int end and
	case when "accountid" is null then 1=1 else nlbh."CreatedBy"="accountid" end 

UNION
		
SELECT 
	coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
	-- R."Cost" as "PaidAmount", 
	PT."PayTypeName",R."PaymentDetails",
	 AR."FullName" "ReceiptCreatedBy" ,Rl."RoleName",R."CreatedBy",
	 nlbh."RequisitionNumber",
	 nlbh."PatientId", nlbh."DoctorId", 
	COALESCE (nlbh."PatientName" ,p."FullName" ) as "PatientName",COALESCE (p."Mobile" ,nlbh."Mobile" ) as "Mobile", p."UMRNo",           
      R."ReceiptId",RT."Name" as "AreaType",R."CreatedDate" "ReceiptDate"	,R."ReceiptTypeId"
			
	
		from "NewLabBookingHeader" nlbh
	join "NewLabCancelBookingHeader" SH on SH."NewLabBookingHeaderId"=nlbh."NewLabBookingHeaderId"
	join "Receipt" R on R."RespectiveId"= SH."NewLabCancelBookingHeaderId"	
			join "PayType" pt ON PT."PayTypeId" = R."PayTypeId"                                                                      
			left join "Patient" p ON p."PatientId" =nlbh."PatientId"		
			left join "Account" AR on AR."AccountId" = R."CreatedBy"
			join "Role" Rl on Rl."RoleId"=AR."RoleId"
			join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"
		where R."ReceiptAreaTypeId" = 9
		--and nlbh."LocationId"=2 and R."CreatedDate"::date='2023-04-18'
 	and case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::timestamp without time zone end and
	case when "toDate" is null then 1=1 else R."CreatedDate"::timestamp without time zone<=  "toDate" end and
 	case when "locationid" is null then 1=1 else  nlbh."LocationId" = "locationid"::int end and
	case when "accountid" is null then 1=1 else nlbh."CreatedBy"="accountid" end 
		
																		  								   
)

,pharma as (

select 
	coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
-- R."Cost" as "PaidAmount", 
	PT."PayTypeName",R."PaymentDetails",
	PH."PharmacySaleHeaderId" ,PH."BillNumber",
	A."FullName" "ReceiptCreatedBy",AR."RoleName" ,R."CreatedBy",
	PH."PatientName",PH."Mobile" ,Pa."UMRNo",
	 R."ReceiptId",RT."Name" as "AreaType",R."CreatedDate" "ReceiptDate",R."ReceiptTypeId"
	
	from "Receipt" R
		join "PharmacySaleHeader" PH on PH."PharmacySaleHeaderId"=R."RespectiveId"
		join "Account" A on A."AccountId"=R."CreatedBy"
		join "Role" AR on AR."RoleId"=A."RoleId"
		 join "PayType" PT ON PT."PayTypeId" = R."PayTypeId"  
		join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"	 	
		left join "Patient" Pa on Pa."PatientId"::text=PH."PatientId"::text
	where R."ReceiptAreaTypeId"=1  
 			
	 and case when "accountid" is null then 1=1 else R."CreatedBy"="accountid" end and
	
 	case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::timestamp without time zone end and
 	case when "toDate" is null then 1=1 else R."CreatedDate"::timestamp without time zone<=  "toDate" end and
  	case when "locationid" is null then 1=1 else PH."LocationId" = "locationid" end
UNION
	
select 
	coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
	 --R."Cost" as "PaidAmount", 
	PT."PayTypeName",R."PaymentDetails",
		PH."PharmacySaleHeaderId" ,PH."BillNumber",
		A."FullName" "ReceiptCreatedBy",AR."RoleName" ,R."CreatedBy",
		PH."PatientName",PH."Mobile" ,Pa."UMRNo",
		 R."ReceiptId",RT."Name" as "AreaType",R."CreatedDate" "ReceiptDate",R."ReceiptTypeId"
	from "PharmacySaleHeader" PH 
			join "SaleReturnHeader" SH on SH."PharmacySaleHeaderId"=PH."PharmacySaleHeaderId"
			join "Receipt" R on R."RespectiveId"= SH."SaleReturnHeaderId"
		join "Account" A on A."AccountId"=R."CreatedBy"
		join "Role" AR on AR."RoleId"=A."RoleId"
		 join "PayType" PT ON PT."PayTypeId" = R."PayTypeId"  
		join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"	 	
		left join "Patient" Pa on Pa."PatientId"::text=PH."PatientId"::text
	where R."ReceiptAreaTypeId"=7
	
		 and case when "accountid" is null then 1=1 else R."CreatedBy"="accountid" end and
		 case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::timestamp without time zone end and
		case when "toDate" is null then 1=1 else R."CreatedDate"::timestamp without time zone<=  "toDate" end and
		case when "locationid" is null then 1=1 else PH."LocationId" = "locationid" end		
)
,scan as(

select 
	coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
		-- R."Cost" as "PaidAmount",
	PT."PayTypeName",R."PaymentDetails",
			 PH."RequisitionNumber",
			 R."ReceiptId",RT."Name" as "AreaType",R."CreatedDate" "ReceiptDate",R."ReceiptTypeId",
			PA."FullName" as "PatientName",PA."Mobile" ,PA."UMRNo",
	R."CreatedBy",A."FullName" "ReceiptCreatedBy",AR."RoleName" 
	
		from "Receipt" R
		join "BookScanAppointment" PH on PH."BookScanAppointmentId"=R."RespectiveId" 
		join "Account" A on A."AccountId"=R."CreatedBy"
		join "Role" AR on AR."RoleId"=A."RoleId"
		 join "PayType" PT ON PT."PayTypeId" = R."PayTypeId"  
		join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"	
		left join "Patient" PA on PA."PatientId"=PH."PatientId"

	where  R."ReceiptAreaTypeId" in (10,11)
		 		
		and case when "accountid" is null then 1=1 else R."CreatedBy"="accountid" end and	
		case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::timestamp without time zone end and
		case when "toDate" is null then 1=1 else R."CreatedDate"::timestamp without time zone<=  "toDate" end and
		case when "locationid" is null then 1=1 else PH."LocationId" = "locationid" end
)
SELECT O."AccountId",O."ReceiptCreatedBy",O."RoleName",O."ReceiptDate",O."ReceiptId",O."ReceiptTypeId",
O."AreaType",O."RefId",
coalesce(O."PayTypeName"::character varying,'GRAND')"PayTypeName"
,O."PaymentDetails"--,coalesce(case when O."ReceiptTypeId"=2 then O."PaidAmount" end,0) as "RefundAmount" 
,sum(O."PaidAmount")-sum(O."RefundAmount") "PaidAmount",--O."RefundAmount",--O."BalanceAmount",sum(A."PaidAmount") "PaidAmount"
O."PatientName",O."UMRNo",O."Mobile"
from 
(
	Select  A."AccountId",AP."ReceiptCreatedBy",AP."RoleName",AP."ReceiptDate",AP."ReceiptId",AP."ReceiptTypeId",
AP."AreaType",AP."AppointmentNo" as "RefId",AP."PayTypeName",AP."PaymentDetails"
,AP."PaidAmount",AP."RefundAmount",--AP."BalanceAmount",
AP."PatientName",AP."UMRNo",AP."Mobile"
from accountdata A
join appointment AP on AP."CreatedBy"=A."AccountId"
UNION
	Select  A."AccountId",AP."ReceiptCreatedBy",AP."RoleName",AP."ReceiptDate",AP."ReceiptId",AP."ReceiptTypeId",
AP."AreaType",AP."AppointmentNo" as "RefId",AP."PayTypeName",AP."PaymentDetails"
,AP."PaidAmount",AP."RefundAmount",--AP."BalanceAmount",
AP."PatientName",AP."UMRNo",AP."Mobile"
from accountdata A
join servicepayments AP on AP."CreatedBy"=A."AccountId"
UNION
Select  A."AccountId",AP."ReceiptCreatedBy",AP."RoleName",AP."ReceiptDate",AP."ReceiptId",AP."ReceiptTypeId",
AP."AreaType",AP."PatientId"::character varying as "RefId",AP."PayTypeName",AP."PaymentDetails"
,AP."PaidAmount",AP."RefundAmount",--AP."BalanceAmount",
AP."PatientName",AP."UMRNo",AP."Mobile"
from accountdata A
join patient AP on AP."CreatedBy"=A."AccountId"
UNION
Select  A."AccountId",AP."ReceiptCreatedBy",AP."RoleName",AP."ReceiptDate",AP."ReceiptId",AP."ReceiptTypeId",
AP."AreaType",AP."RequisitionNumber"::character varying as "RefId",AP."PayTypeName",AP."PaymentDetails"
,AP."PaidAmount",AP."RefundAmount",--AP."BalanceAmount",
AP."PatientName",AP."UMRNo",AP."Mobile"
from accountdata A
join lab AP on AP."CreatedBy"=A."AccountId"
UNION
Select  A."AccountId",AP."ReceiptCreatedBy",AP."RoleName",AP."ReceiptDate",AP."ReceiptId",AP."ReceiptTypeId",
AP."AreaType",AP."BillNumber"::character varying as "RefId",AP."PayTypeName",AP."PaymentDetails"
,AP."PaidAmount",AP."RefundAmount",--AP."BalanceAmount",
AP."PatientName",AP."UMRNo",AP."Mobile"
from accountdata A
join pharma AP on AP."CreatedBy"=A."AccountId"
	UNION
Select  A."AccountId",AP."ReceiptCreatedBy",AP."RoleName",AP."ReceiptDate",AP."ReceiptId",AP."ReceiptTypeId",
AP."AreaType",AP."RequisitionNumber"::character varying as "RefId",AP."PayTypeName",AP."PaymentDetails"
,AP."PaidAmount",AP."RefundAmount",--AP."BalanceAmount",
AP."PatientName",AP."UMRNo",AP."Mobile"
from accountdata A
join scan AP on AP."CreatedBy"=A."AccountId"	
	
)O

GROUP BY GROUPING SETS((O."AccountId",O."ReceiptCreatedBy",O."RoleName",O."ReceiptDate",
						O."ReceiptId",O."ReceiptTypeId",O."AreaType",O."RefId",O."PayTypeName",
						O."PaymentDetails",O."PatientName",O."UMRNo",O."Mobile"),(O."PayTypeName"), ())   

order by O."PayTypeName" asc, O."ReceiptDate" asc;

end
$BODY$;

--------------------------------------------------------------Kalyan27July2023--------------------------------------------------

alter table if exists "NewLabBookingHeader"
alter column "OverallDiscountPercentage" type numeric(5,2);
alter table if exists "NewLabBookingDetail"
alter column "DiscountPercentage" type numeric(5,2);
-------------------------------------------------------------Shivani28July2023--------------------------------------------------
alter table IF EXISTS "PharmacySaleHeader" 
add COLUMN IF NOT EXISTS "ReasonForDiscount" CHARACTER VARYING(150);
-------------------------------------------------------------Chandana28July2023------------------------------------------------
alter table if exists "Patient" 
add column if not exists "IsBabyRegistration" BOOLEAN;
alter table if exists "Patient" 
add column if not exists "ParentPatientId" integer;
--------------------------------------------------------------Manish28July2023-------------------------------------------------
ALTER TABLE if exists "Denverchart"
ADD COLUMN if not exists "AppointmentId" integer,
ADD COLUMN if not exists "DenverChartData" text,
ADD COLUMN if not exists "Question" text;

alter table if exists public."PharmacyProduct" drop column if exists "MaxQuantity",
drop column if exists  "MinQuantity",drop column if exists  "RolQuantity",
drop column if exists "RackId",drop column if exists "Pharmacy_Source";

alter table if exists public."PharmacyProduct" add column if not exists "Potency" text, 
add column if not exists "DrugRiskId" int references "LookupValue"("LookupValueId"),
add column if not exists "Dosage" text,add column if not exists "Formula" text,
add column if not exists "NABHCategoryId" int references "LookupValue"("LookupValueId"),
add column if not exists "DosageTypeId" int references "LookupValue"("LookupValueId"),
add column if not exists "Strength" text,add column if not exists "FixedDose" numeric,
add column if not exists  "MedFrequencyMasterId" int references public."MedFrequencyMaster"("MedFrequencyMasterId"),
add column if not exists "NoOfTimes" int,add column if not exists "SaleLoose" boolean,
add column if not exists "InventoryExpiry" int,add column if not exists "FormulationId" int references "LookupValue"("LookupValueId"),
add column if not exists "MedRouteId" int references "LookupValue"("LookupValueId");

INSERT INTO public."Lookup"("Name", "Description")
SELECT 'PharmacyDrugRisk','For pharmacy drug risks'
WHERE
NOT EXISTS (
SELECT "Name" FROM public."Lookup" WHERE "Name" = 'PharmacyDrugRisk'
);

INSERT INTO public."LookupValue"("LookupId","Name", "CreatedBy", "CreatedDate")
SELECT (select "LookupId" from "Lookup" where "Name"= 'PharmacyDrugRisk'),'Low Risk',1029, now()
WHERE
NOT EXISTS (
SELECT "Name" FROM public."LookupValue" WHERE "LookupId" = (select "LookupId" from "Lookup" where "Name"= 'PharmacyDrugRisk') and "Name" = 'Low Risk'
);

INSERT INTO public."LookupValue"("LookupId","Name", "CreatedBy", "CreatedDate")
SELECT (select "LookupId" from "Lookup" where "Name"= 'PharmacyDrugRisk'),'Medium Risk',1029, now()
WHERE
NOT EXISTS (
SELECT "Name" FROM public."LookupValue" WHERE "LookupId" = (select "LookupId" from "Lookup" where "Name"= 'PharmacyDrugRisk') and "Name" = 'Medium Risk'
);

INSERT INTO public."LookupValue"("LookupId","Name", "CreatedBy", "CreatedDate")
SELECT (select "LookupId" from "Lookup" where "Name"= 'PharmacyDrugRisk'),'High Risk',1029, now()
WHERE
NOT EXISTS (
SELECT "Name" FROM public."LookupValue" WHERE "LookupId" = (select "LookupId" from "Lookup" where "Name"= 'PharmacyDrugRisk') and "Name" = 'High Risk'
);

INSERT INTO public."Lookup"("Name", "Description")
SELECT 'NABHCategory','For NABH Authority'
WHERE
NOT EXISTS (
SELECT "Name" FROM public."Lookup" WHERE "Name" = 'NABHCategory'
);

INSERT INTO public."LookupValue"("LookupId","Name", "CreatedBy", "CreatedDate")
SELECT (select "LookupId" from "Lookup" where "Name"= 'NABHCategory'),'Vital',1029, now()
WHERE
NOT EXISTS (
SELECT "Name" FROM public."LookupValue" WHERE "LookupId" = (select "LookupId" from "Lookup" where "Name"= 'NABHCategory') and "Name" = 'Vital'
);

INSERT INTO public."LookupValue"("LookupId","Name", "CreatedBy", "CreatedDate")
SELECT (select "LookupId" from "Lookup" where "Name"= 'NABHCategory'),'Essential',1029, now()
WHERE
NOT EXISTS (
SELECT "Name" FROM public."LookupValue" WHERE "LookupId" = (select "LookupId" from "Lookup" where "Name"= 'NABHCategory') and "Name" = 'Essential'
);

INSERT INTO public."LookupValue"("LookupId","Name", "CreatedBy", "CreatedDate")
SELECT (select "LookupId" from "Lookup" where "Name"= 'NABHCategory'),'Desirable',1029, now()
WHERE
NOT EXISTS (
SELECT "Name" FROM public."LookupValue" WHERE "LookupId" = (select "LookupId" from "Lookup" where "Name"= 'NABHCategory') and "Name" = 'Desirable'
);

INSERT INTO public."Lookup"("Name", "Description")
SELECT 'PharmacyDosageType','To set dose for pharmacy product'
WHERE
NOT EXISTS (
SELECT "Name" FROM public."Lookup" WHERE "Name" = 'PharmacyDosageType'
);

INSERT INTO public."LookupValue"("LookupId","Name", "CreatedBy", "CreatedDate")
SELECT (select "LookupId" from "Lookup" where "Name"= 'PharmacyDosageType'),'Regular Items',1029, now()
WHERE
NOT EXISTS (
SELECT "Name" FROM public."LookupValue" WHERE "LookupId" = (select "LookupId" from "Lookup" where "Name"= 'PharmacyDosageType') and "Name" = 'Regular Items'
);

INSERT INTO public."LookupValue"("LookupId","Name", "CreatedBy", "CreatedDate")
SELECT (select "LookupId" from "Lookup" where "Name"= 'PharmacyDosageType'),'Weight Wise',1029, now()
WHERE
NOT EXISTS (
SELECT "Name" FROM public."LookupValue" WHERE "LookupId" = (select "LookupId" from "Lookup" where "Name"= 'PharmacyDosageType') and "Name" = 'Weight Wise'
);

INSERT INTO public."LookupValue"("LookupId","Name", "CreatedBy", "CreatedDate")
SELECT (select "LookupId" from "Lookup" where "Name"= 'PharmacyDosageType'),'Age Wise',1029, now()
WHERE
NOT EXISTS (
SELECT "Name" FROM public."LookupValue" WHERE "LookupId" = (select "LookupId" from "Lookup" where "Name"= 'PharmacyDosageType') and "Name" = 'Age Wise'
);

INSERT INTO public."Lookup"("Name", "Description")
SELECT 'PharmacyFormulation','To set formulation for pharmacy product'
WHERE
NOT EXISTS (
SELECT "Name" FROM public."Lookup" WHERE "Name" = 'PharmacyFormulation'
);

alter table if exists public."PharmacyProduct" 
add column if not exists "AlchoholInteraction" text,
add column if not exists "PregnancyInteraction" text,
add column if not exists "ExpertAdvice" text,
add column if not exists "CommonSideEffects" text,
add column if not exists "MedicineFaq" text,
add column if not exists "MedicineInteraction" text,
add column if not exists "Usage" text;

create table if not exists public."VaccineAgeGroup"(
					"VaccineAgeGroupId" serial primary key,
					"AgeGroupName" text	
);

--1
INSERT INTO public."VaccineAgeGroup"("AgeGroupName")
SELECT 'At Birth'
WHERE
NOT EXISTS (
SELECT "AgeGroupName" FROM public."VaccineAgeGroup" WHERE "AgeGroupName" = 'At Birth'
);

--2
INSERT INTO public."VaccineAgeGroup"("AgeGroupName")
SELECT '1 to 6 Weeks'
WHERE
NOT EXISTS (
SELECT "AgeGroupName" FROM public."VaccineAgeGroup" WHERE "AgeGroupName" = '1 to 6 Weeks'
);

--3
INSERT INTO public."VaccineAgeGroup"("AgeGroupName")
SELECT '7 to 10 Weeks'
WHERE
NOT EXISTS (
SELECT "AgeGroupName" FROM public."VaccineAgeGroup" WHERE "AgeGroupName" = '7 to 10 Weeks'
);

--4
INSERT INTO public."VaccineAgeGroup"("AgeGroupName")
SELECT '3 to 4 Months'
WHERE
NOT EXISTS (
SELECT "AgeGroupName" FROM public."VaccineAgeGroup" WHERE "AgeGroupName" = '3 to 4 Months'
);

--5
INSERT INTO public."VaccineAgeGroup"("AgeGroupName")
SELECT '5 to 6 Months'
WHERE
NOT EXISTS (
SELECT "AgeGroupName" FROM public."VaccineAgeGroup" WHERE "AgeGroupName" = '5 to 6 Months'
);

--6
INSERT INTO public."VaccineAgeGroup"("AgeGroupName")
SELECT '7 to 8 Months'
WHERE
NOT EXISTS (
SELECT "AgeGroupName" FROM public."VaccineAgeGroup" WHERE "AgeGroupName" = '7 to 8 Months'
);

--7
INSERT INTO public."VaccineAgeGroup"("AgeGroupName")
SELECT '8 to 9 Months'
WHERE
NOT EXISTS (
SELECT "AgeGroupName" FROM public."VaccineAgeGroup" WHERE "AgeGroupName" = '8 to 9 Months'
);

--8
INSERT INTO public."VaccineAgeGroup"("AgeGroupName")
SELECT '10 to 11 Months'
WHERE
NOT EXISTS (
SELECT "AgeGroupName" FROM public."VaccineAgeGroup" WHERE "AgeGroupName" = '10 to 11 Months'
);

--9
INSERT INTO public."VaccineAgeGroup"("AgeGroupName")
SELECT '12 to 13 Months'
WHERE
NOT EXISTS (
SELECT "AgeGroupName" FROM public."VaccineAgeGroup" WHERE "AgeGroupName" = '12 to 13 Months'
);

--10
INSERT INTO public."VaccineAgeGroup"("AgeGroupName")
SELECT '13 to 15 Months'
WHERE
NOT EXISTS (
SELECT "AgeGroupName" FROM public."VaccineAgeGroup" WHERE "AgeGroupName" = '13 to 15 Months'
);

--11
INSERT INTO public."VaccineAgeGroup"("AgeGroupName")
SELECT '16 to 17 Months'
WHERE
NOT EXISTS (
SELECT "AgeGroupName" FROM public."VaccineAgeGroup" WHERE "AgeGroupName" = '16 to 17 Months'
);

--12
INSERT INTO public."VaccineAgeGroup"("AgeGroupName")
SELECT '17 to 18 Months'
WHERE
NOT EXISTS (
SELECT "AgeGroupName" FROM public."VaccineAgeGroup" WHERE "AgeGroupName" = '17 to 18 Months'
);

--13
INSERT INTO public."VaccineAgeGroup"("AgeGroupName")
SELECT '2 to 4 Years'
WHERE
NOT EXISTS (
SELECT "AgeGroupName" FROM public."VaccineAgeGroup" WHERE "AgeGroupName" = '2 to 4 Years'
);

--14
INSERT INTO public."VaccineAgeGroup"("AgeGroupName")
SELECT '4 to 6 Years'
WHERE
NOT EXISTS (
SELECT "AgeGroupName" FROM public."VaccineAgeGroup" WHERE "AgeGroupName" = '4 to 6 Years'
);

--15
INSERT INTO public."VaccineAgeGroup"("AgeGroupName")
SELECT '6 to 9 Years'
WHERE
NOT EXISTS (
SELECT "AgeGroupName" FROM public."VaccineAgeGroup" WHERE "AgeGroupName" = '6 to 9 Years'
);

--16
INSERT INTO public."VaccineAgeGroup"("AgeGroupName")
SELECT '10 to 12 Years'
WHERE
NOT EXISTS (
SELECT "AgeGroupName" FROM public."VaccineAgeGroup" WHERE "AgeGroupName" = '10 to 12 Years'
);

--17
INSERT INTO public."VaccineAgeGroup"("AgeGroupName")
SELECT '12 to 18 Years'
WHERE
NOT EXISTS (
SELECT "AgeGroupName" FROM public."VaccineAgeGroup" WHERE "AgeGroupName" = '12 to 18 Years'
);

--18
INSERT INTO public."VaccineAgeGroup"("AgeGroupName")
SELECT '18 to 100 Years'
WHERE
NOT EXISTS (
SELECT "AgeGroupName" FROM public."VaccineAgeGroup" WHERE "AgeGroupName" = '18 to 100 Years'
);

alter table if exists  public."VaccineMaster" 
add column if not exists "VaccineAgeGroupId" int references "VaccineAgeGroup"("VaccineAgeGroupId");
--------------------------------------------------------------------------Sravani 28July2023---------------------------------------------------------
alter table if exists "Appointment" 
add column if not exists "RescheduleReason" text;

-------------------------------------------------------------kalyan31July2023---------------------------------------------
alter table if exists "Admission"
add column if not exists "CurrentRoomId" int,
drop constraint if exists "FK_Admission_CurrentRoomId",
ADD CONSTRAINT "FK_Admission_CurrentRoomId" FOREIGN KEY ("CurrentRoomId")
REFERENCES public."Room" ("RoomId") ;

DROP FUNCTION IF EXISTS public."udf_fetch_Admission_Location"(text, integer, integer, boolean, text, date, date, date, text, boolean, integer, integer, integer);

CREATE OR REPLACE FUNCTION public."udf_fetch_Admission_Location"(
	"admissionNo" text DEFAULT NULL::text,
	"providerId" integer DEFAULT NULL::integer,
	"patientId" integer DEFAULT NULL::integer,
	"isDischarged" boolean DEFAULT NULL::boolean,
	"patientMobileNo" text DEFAULT NULL::text,
	"fromDate" date DEFAULT NULL::date,
	"toDate" date DEFAULT NULL::date,
	"dischargeDate" date DEFAULT NULL::date,
	"uMRNo" text DEFAULT NULL::text,
	active boolean DEFAULT NULL::boolean,
	locationid integer DEFAULT NULL::integer,
	"pageIndex" integer DEFAULT 0,
	"pageSize" integer DEFAULT 10)
    RETURNS TABLE("AdmissionId" integer, "AdmissionNo" text, "IsConvertedFromOPtoIp" boolean, "AdmissionDate" timestamp without time zone, "AdmissionTime" time without time zone, "PatientName" text, "UMRNo" character varying, "PatientAge" smallint, "PatientGender" character, "patientMobile" character varying, "ProviderAge" smallint, "ProviderGender" character, "ProviderName" text, "DepartmentName" text, "WardName" character varying, "RoomName" character varying, "BedNumber" character varying, "AttendantName" character varying, "AttendantRelationWithPatient" character varying, "AttendantContactNo" character varying, "IsDischarged" boolean, "DischargeDate" date, "DischargeTime" time without time zone, "DischargeStatus" character varying, "IsMaternity" boolean, "EncounterId" integer, "SurgeryName" character varying, "ProviderThumbnailUrl" text, "PatientThumbnailUrl" text, "BedId" integer, "RoomId" integer, "WardId" integer, "DepartmentId" integer, "PatientId" integer, "ProviderId" integer, "SurgeryTypeId" integer, "PatientType" character, "AdmissionNotes" text, "PaidAmount" numeric, "FinalAmount" numeric, "PaymentStatus" text, "IsFinalBill" boolean, "TotalItems" bigint, "Active" boolean, "ExpectedDischargeDate" timestamp without time zone, "DischargedBy" integer, "DischargedByRole" text, "DischargedByName" text, "ChargeCategoryId" integer, "ChargeCategoryName" character varying, "CaseTypeId" integer, "AdmissionPayTypeId" integer, "ReferralDoctorId" integer, "InsuranceCompanyId" integer, "TpaId" integer, "PatientOrganization" character varying, "DoctorUnitMasterId" integer, "AdmissionBedChangeRequestId" integer, "ChargeCategoryNames" text, "RequestComments" text, "CurrentRoomId" integer,"CurrentRoomName" character varying) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
BEGIN

return query 

With TotalItems as (

select  count(distinct A."AdmissionId")::bigint "TotalItems"
	from "Admission" A
	join "Patient" Pa on A."PatientId"=Pa."PatientId"
	join "Provider" Pr on A."ProviderId"=Pr."ProviderId"
	join "Department" D on D."DepartmentId"=A."DepartmentId"
	left join "Bed" B on B."BedId"=A."BedId"
	left join "Room" R on B."RoomId"=R."RoomId"  
	left join "Ward" W on w."WardId"=R."WardId"
    join "ChargeCategory" cc on cc."ChargeCategoryId" = R."ChargeCategoryId"
	---left join "PatientFamily" pf on pf."PatientFamilyId"=A."PatientFamilyId"
	left join "SurgeryType" st on st."SurgeryTypeId"=A."SurgeryTypeId"
	left join "Discharge" ds on ds."AdmissionId"=A."AdmissionId" and ds."Active"=true
	left join "DischargeStatus" dss on ds."DischargeStatusId"=dss."DischargeStatusId"
	
	left join "Receipt" Re on A."AdmissionId" = Re."AdmissionId" and Re."ReceiptTypeId"=1 and Re."Active"=true
---left join "Receipt" Rf on Rf."ReceiptTypeId"=2 and A."AdmissionId"= Rf ."AdmissionId" and Rf."Active"=true  and  Rf."IsRefunded" =true
left join "FinalBill" FB on  A."AdmissionId"= FB."AdmissionId" and FB."Active"=true	
	where  
	case when "admissionNo" is null then 1=1
	when "admissionNo"='' then 1=1
	else A."AdmissionNo" ilike '%'||"admissionNo"||'%' end and 
	 CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE A."LocationId"=locationId END	 AND						
	case when "patientMobileNo" is null then 1=1
	when "patientMobileNo"='' then 1=1
	else pa."Mobile" ilike '%'||"patientMobileNo"||'%' end and 
	
	case when "patientId" is null then 1=1
	else Pa."PatientId"= "patientId" end and 
	
	case when "active" is null then 1=1
	else A."Active"= "active" end and 
	
	case when "providerId" is null then 1=1
	
	else Pr."ProviderId" = "providerId" end and  
	case when "isDischarged" is null then 1=1
		when "isDischarged" =true then   ds."AdmissionId"=A."AdmissionId"  
		when "isDischarged" =false then	ds."AdmissionId" is null	
		end AND
	case when "fromDate" is null then 1=1 else "fromDate" <=A."AdmissionDate"::date and A."AdmissionDate"::date <="toDate" end 
	AND 
	case when "dischargeDate" is null then 1=1 else "dischargeDate" =ds."DischargeDate"::date end 
and
	case when "uMRNo" is null then 1=1
	when "uMRNo"='' then 1=1
	else Pa."UMRNo" ilike '%'||"uMRNo"||'%' end 

)

select  A."AdmissionId",A."AdmissionNo",A."IsConvertedFromOPtoIp",A."AdmissionDate",A."AdmissionTime",
	Pa."FullName" "PatientName",Pa."UMRNo",Pa."Age" "PatientAge",Pa."Gender" as "PatientGender",pa."Mobile" "patientMobile",Pr."Age" "ProviderAge",Pr."Gender" as "ProviderGender",
	Pr."FullName"::text "ProviderName",D."DepartmentName"::text "DepartmentName" , w."WardName", R."RoomName", B."BedNumber"
	,A."AttendantName" "AttendantName",A."AttendantRelationWithPatient" "AttendantRelationWithPatient",A."AttendantContactNo" "AttendantContactNumber",
	case when ds."DischargeId" is not null then true else false end as "IsDischarged",ds."DischargeDate",ds."DischargeTime",
	dss."DischargeStatus"
	
	,A."IsMaternity",A."EncounterId",st."SurgeryName",
	(CASE WHEN pr."ThumbnailUrl" IS NOT NULL THEN CONCAT(pr."Guid", '/', pr."ThumbnailUrl") ELSE NULL END) AS "ProviderThumbnailUrl",
(CASE WHEN pa."ThumbnailUrl" IS NOT NULL THEN CONCAT(pa."Guid", '/', pa."ThumbnailUrl") ELSE NULL END) AS "PatientThumbnailUrl"
	,A."BedId",B."RoomId",w."WardId",D."DepartmentId",A."PatientId", A."ProviderId", A."SurgeryTypeId", A."PatientType",A."AdmissionNotes"
,
sum(coalesce(Re."Cost",0))-coalesce((select sum(Rfd."Cost") from "Receipt" Rfd where Rfd."AdmissionId"=A."AdmissionId" and "ReceiptTypeId"=2 and  Rfd."Active"=true and  Rfd."IsRefunded" =true ),0) "PaidAmount"
,
FB."FinalAmount" ,
case when FB."FinalAmount"-(sum(coalesce(Re."Cost",0))-coalesce((select sum(Rfd."Cost") from "Receipt" Rfd where Rfd."AdmissionId"=A."AdmissionId" and "ReceiptTypeId"=2 and  Rfd."Active"=true and  Rfd."IsRefunded" =true ),0))=0 then 'Payment Cleared'
	 when FB."FinalAmount"-(sum(coalesce(Re."Cost",0))-coalesce((select sum(Rfd."Cost") from "Receipt" Rfd where Rfd."AdmissionId"=A."AdmissionId" and "ReceiptTypeId"=2 and  Rfd."Active"=true and  Rfd."IsRefunded" =true ),0))>0 then 'Payment Due'	
	 when FB."FinalAmount"-(sum(coalesce(Re."Cost",0))-coalesce((select sum(Rfd."Cost") from "Receipt" Rfd where Rfd."AdmissionId"=A."AdmissionId" and "ReceiptTypeId"=2 and  Rfd."Active"=true and  Rfd."IsRefunded" =true ),0))<0 then 'Pending Refund' end "PaymentStatus",
case when FB."FinalBillId" is null then false else true end "IsFinalBill",(select T."TotalItems" from TotalItems T) "TotalItems",
A."Active",
A."ExpectedDischargeDate",
A."DischargedBy" ,
case when RL."RoleId" =  '3' then DP."DepartmentName"::TEXT else RL."RoleName"::TEXT end as "DischargedByRole",
case when RL."RoleId" =  '3' then PRO."FullName" else AC."FullName" end as "DischargedByName",R."ChargeCategoryId",cc."ChargeCategoryName",A."CaseTypeId",
A."AdmissionPayTypeId",A."ReferralDoctorId",A."InsuranceCompanyId",A."TpaId" ,A."PatientOrganization",A."DoctorUnitMasterId",abcr."AdmissionBedChangeRequestId",
string_agg(DISTINCT newcc."ChargeCategoryName", ',') AS "ChargeCategoryNames",abcr."RequestComments", A."CurrentRoomId", newr."RoomName" as "CurrentRoomName"
	from "Admission" A
	join "Patient" Pa on A."PatientId"=Pa."PatientId"
	join "Provider" Pr on A."ProviderId"=Pr."ProviderId"
	join "Department" D on D."DepartmentId"=A."DepartmentId"
	left join "Bed" B on B."BedId"=A."BedId"
	left join "Room" R on B."RoomId"=R."RoomId"
    join "ChargeCategory" cc on cc."ChargeCategoryId" =R."ChargeCategoryId"
	left join "Ward" W on w."WardId"=R."WardId"
	---left join "PatientFamily" pf on pf."PatientFamilyId"=A."PatientFamilyId"
	left join "SurgeryType" st on st."SurgeryTypeId"=A."SurgeryTypeId"
	left join "Discharge" ds on ds."AdmissionId"=A."AdmissionId" and ds."Active"=true
	left join "DischargeStatus" dss on ds."DischargeStatusId"=dss."DischargeStatusId"
	
	left join "Receipt" Re on A."AdmissionId" = Re."AdmissionId" and Re."ReceiptTypeId"=1 and Re."Active"=true
---left join "Receipt" Rf on Rf."ReceiptTypeId"=2 and A."AdmissionId"= Rf ."AdmissionId" and Rf."Active"=true  and  Rf."IsRefunded" =true
left join "FinalBill" FB on  A."AdmissionId"= FB."AdmissionId" and FB."Active"=true
	
	left join "Account" AC on AC."AccountId"=A."DischargedBy" 
left join "Role" RL on RL."RoleId"= AC."RoleId"
left join "Provider" PRO on PRO."ProviderId"=AC."ReferenceId"
left join "Department" DP on DP."DepartmentId"=PRO."DepartmentId"
	left join "AdmissionBedChangeRequest" abcr on abcr."AdmissionId" = a."AdmissionId" and abcr."Active" = true		
	LEFT JOIN "ChargeCategory" newcc on newcc."ChargeCategoryId" = ANY(abcr."ChargeCategories") --AND newcc."Active" IS TRUE
    left join "Room" newr on newr."RoomId" = A."CurrentRoomId"
    where  
	case when "admissionNo" is null then 1=1
	when "admissionNo"='' then 1=1
	else A."AdmissionNo" ilike '%'||"admissionNo"||'%' end and 
	 CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE A."LocationId"=locationId END	 AND						
	case when "patientMobileNo" is null then 1=1
	when "patientMobileNo"='' then 1=1
	else pa."Mobile" ilike '%'||"patientMobileNo"||'%' end and 
	
	case when "patientId" is null then 1=1
	else Pa."PatientId"= "patientId" end and 
	
	case when "active" is null then 1=1
	else A."Active"= "active" end and 
	
	case when "providerId" is null then 1=1
	
	else Pr."ProviderId" = "providerId" end and  
	case when "isDischarged" is null then 1=1
		when "isDischarged" =true then   ds."AdmissionId"=A."AdmissionId"  
		when "isDischarged" =false then	ds."AdmissionId" is null	
		end AND
	case when "fromDate" is null then 1=1 else "fromDate" <=A."AdmissionDate"::date and A."AdmissionDate"::date <="toDate" end 
	AND 
	case when "dischargeDate" is null then 1=1 else "dischargeDate" =ds."DischargeDate"::date end 
and
	case when "uMRNo" is null then 1=1
	when "uMRNo"='' then 1=1
	else Pa."UMRNo" ilike '%'||"uMRNo"||'%' end  
 group by  A."AdmissionId",A."AdmissionNo",A."IsConvertedFromOPtoIp",A."AdmissionDate",A."AdmissionTime",
	Pa."FullName",Pa."UMRNo",Pa."Age" ,Pa."Gender" ,Pr."Age" ,Pr."Gender" ,
	Pr."FullName",D."DepartmentName" , w."WardName", R."RoomName", B."BedNumber"
	,A."AttendantName",A."AttendantRelationWithPatient",A."AttendantContactNo" , ds."DischargeId"
																														 
	,ds."DischargeDate",ds."DischargeTime",
	dss."DischargeStatus",pa."Mobile"
	
	,A."IsMaternity",A."EncounterId",st."SurgeryName",pr."ThumbnailUrl", pr."Guid",pr."ThumbnailUrl" ,pa."Guid", pa."ThumbnailUrl",
	A."BedId",B."RoomId",w."WardId",D."DepartmentId",A."PatientId", A."ProviderId", A."SurgeryTypeId", A."PatientType",A."AdmissionNotes"
		,FB."FinalAmount"	,FB."FinalBillId",
	RL."RoleId",DP."DepartmentName",PRO."FullName",AC."FullName",R."ChargeCategoryId",cc."ChargeCategoryName",abcr."AdmissionBedChangeRequestId"
	,newr."RoomName"
    order by A."AdmissionId" desc 
 limit "pageSize" offset ("pageSize"*"pageIndex");

END
$BODY$;
-----------------------------------------------------------------------------Srilekha 31July2023---------------------------------------------------------------------


 DROP FUNCTION public."udf_PharmacyBills_Report"(text, integer, character varying, character varying, integer, integer, integer, timestamp without time zone, timestamp without time zone, text, integer, text);

CREATE OR REPLACE FUNCTION public."udf_PharmacyBills_Report"(
	"billNumber" text DEFAULT NULL::text,
	"patientId" integer DEFAULT NULL::integer,
	"patientMobile" character varying DEFAULT NULL::text,
	"uMRNo" character varying DEFAULT NULL::text,
	"payTypeId" integer DEFAULT NULL::integer,
	"providerId" integer DEFAULT NULL::integer,
	"createdBy" integer DEFAULT NULL::integer,
	"fromDate" timestamp without time zone DEFAULT (now())::timestamp without time zone,
	"toDate" timestamp without time zone DEFAULT (now())::timestamp without time zone,
	"retailName" text DEFAULT NULL::text,
	"retailPharmacyId" integer DEFAULT NULL::integer,
	"locationId" text DEFAULT NULL::text)
    RETURNS TABLE("PharmacySaleHeaderId" integer, "BillNumber" character varying, "SaleDate" timestamp without time zone, "PatientName" character varying, "PatientMobile" character varying, "UMRNo" character varying, "PaidVia" character varying, "PaymentNumber" character varying, "CreatedByName" text, "RoleName" character varying, "ProviderName" character varying, "TotalAmount" numeric, "RetailName" text, "OverallTaxes" numeric, "LocationName" character varying, "TypeOfPayment" character) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$

BEGIN

return query

select A."PharmacySaleHeaderId" ,A."BillNumber",A."SaleDate",A."PatientName",A."Mobile" 
,A."UMRNo",A."PaidVia",A."PaymentNumber",A."CreatedByName",A."Role" ,
A."ProviderName", sum(A."Cost") as "TotalAmount"  ,A."RetailName",A."OverallTaxes",A."LocationName",
A."TypeOfPayment" from (
select PH."PharmacySaleHeaderId" ,PH."BillNumber",PH."CreatedDate" "SaleDate",PH."PatientName",PH."Mobile" 
,Pa."UMRNo",PT."PayTypeName" as "PaidVia",PH."PaymentNumber",A."FullName" 
"CreatedByName",R."RoleName" "Role" ,
PH."ProviderName", RC."Cost"  ,RP."RetailName",PH."OverallTaxes",L."Name" as "LocationName",
PH."PaymentType" as "TypeOfPayment",RC."ReceiptId",RC."CreatedDate"
from  "PharmacySaleHeader" PH
 left join "Patient" Pa on Pa."PatientId"::text=PH."PatientId"::text
join "Account" A on A."AccountId"=PH."CreatedBy"
join "Role" R on R."RoleId"=A."RoleId"
join "PharmacySaleDetail" PSD on PSD."PharmacySaleHeaderId"=PH."PharmacySaleHeaderId"
join "PharmacyRetailStock" PRS on PRS."PharmacyRetailStockId"=PSD."PharmacyRetailStockId"
join "RetailWareHouseLink" RWL on RWL."RetailWareHouseLinkId" = PRS."RetailWareHouseLinkId"
join "RetailPharmacy" RP on RP."RetailPharmacyId"=RWL."RetailPharmacyId"
join "Location" L on L."LocationId" = PH."LocationId"
	 
left Join "Receipt" RC on RC."RespectiveId"=PH."PharmacySaleHeaderId"  and RC."ReceiptAreaTypeId"=1
left join "PayType" PT on PT."PayTypeId"=RC."PayTypeId"
where	case when "billNumber" is null then 1=1 else  PH."BillNumber" ilike '%' || "billNumber" ||'%' end and 
case when "patientId" is null then 1=1 else PH."PatientId"="patientId" end and
	
	case when "patientMobile" is null then 1=1 else  PH."Mobile" ilike '%' || "patientMobile" ||'%' end  and
	case when "uMRNo" is null then 1=1 else  Pa."UMRNo" ilike '%' || "uMRNo" ||'%' end  and
				case when "payTypeId" is null then 1=1 else  PT."PayTypeId" = "payTypeId" end  and
	case when "providerId" is null then 1=1 else  PH."ProviderId" ="providerId"  end  and
		case when "createdBy" is null then 1=1 else  A."AccountId"="createdBy" end and
 case when "fromDate" is null then 1=1 else RC."CreatedDate" >= "fromDate" end and 
 case when "toDate" is null then 1=1 else RC."CreatedDate" <= "toDate" end  and
 case when "retailName" is null then 1=1 else  RP."RetailName" ilike '%' || "retailName" ||'%' end and 
 	case when "retailPharmacyId" is null then 1=1 else  RP."RetailPharmacyId" = "retailPharmacyId" end and 
case when "locationId" is null then 1=1 else PH."LocationId" = "locationId"::int end
group by PH."PharmacySaleHeaderId" ,PH."BillNumber",PH."SaleDate", PH."OverallNetAmount",PH."PatientName",PH."Mobile",Pa."UMRNo",PT."PayTypeName"
, PH."PaymentNumber", A."FullName" 
,R."RoleName" ,PH."ProviderName",RP."RetailName",PH."OverallTaxes",L."Name",RC."ReceiptId",RC."CreatedDate") A
group by A."PharmacySaleHeaderId" ,A."BillNumber",A."SaleDate",A."PatientName",A."Mobile" 
,A."UMRNo",A."PaidVia",A."PaymentNumber",A."CreatedByName",A."Role" ,
A."ProviderName"  ,A."RetailName",A."OverallTaxes",A."LocationName",
A."TypeOfPayment",A."ReceiptId",A."CreatedDate"
order by A."CreatedDate" desc;
END
$BODY$;

-----------------------------------------------------------------Shivani 31July2023-------------------------------------------------------------------------

DROP FUNCTION public."udf_PharmacyPurchaseReport1"(text, text, integer, integer, text, date, timestamp without time zone, timestamp without time zone, boolean, integer, text);

CREATE OR REPLACE FUNCTION public."udf_PharmacyPurchaseReport1"(
	"billNumber" text DEFAULT NULL::text,
	"billType" text DEFAULT NULL::text,
	"createdBy" integer DEFAULT NULL::integer,
	"supplierId" integer DEFAULT NULL::integer,
	"paidVia" text DEFAULT NULL::text,
	"dueDate" date DEFAULT NULL::date,
	"fromDate" timestamp without time zone DEFAULT (now())::timestamp without time zone,
	"toDate" timestamp without time zone DEFAULT (now())::timestamp without time zone,
	"pharmacyBillType" boolean DEFAULT NULL::boolean,
	"pharmacyWareHouseId" integer DEFAULT NULL::integer,
	"locationId" text DEFAULT NULL::text)
    RETURNS TABLE("PharmacyPurchaseHeaderId" integer, "DueDate" timestamp without time zone, "BillNumber" character varying, "BillType" character varying, "BillDate" timestamp without time zone, "CreatedByName" text, "RoleName" character varying, "SupplierName" text, "NetAmount" numeric, "WareHouseName" text, "LocationName" character varying, "PayTypeName" character varying,"Taxes" numeric) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$

BEGIN

return query
select  PH."PharmacyPurchaseHeaderId" ,PH."DueDate",PH."BillNumber",PH."BillType",PH."BillDate",ph."CreatedByName",
ph."Role",ph."SupplierName", PH."NetAmount",PH."WareHouseName",PH."LocationName",PH."PayTypeName",PH."Taxes" from 
(
select PH."PharmacyPurchaseHeaderId" ,PH."DueDate",PH."BillNumber",PH."BillType",PH."CreatedDate" "BillDate",A."FullName" 
"CreatedByName",R."RoleName" "Role",S."Name" "SupplierName",PH."Netamount" "NetAmount",true "PharmacyBillType"
,PW."WareHouseName",L."Name" as  "LocationName",PT."PayTypeName",PH."Taxes"
 from "PharmacyPurchaseHeader" PH
	join "Supplier" s on s."SupplierId"=ph."SupplierId"  
	join "Account" A on A."AccountId"=ph."CreatedBy"
	join "Role" R on R."RoleId"=A."RoleId"
	join "PharmacyWareHouse" PW on PW."PharmacyWareHouseId"=PH."PharmacyWareHouseId"
	left join "Location" L on L."LocationId" = PW."LocationId"
	left join "PharmacyPurchaseReturnHeader" pr on pr."PharmacyPurchaseHeaderId" = PH."PharmacyPurchaseHeaderId"
	left join "PayType" PT on PT."PayTypeId"=PH."PayTypeId"
 where
 case when "billNumber" is null then 1=1 else  PH."BillNumber" ilike '%' || "billNumber" ||'%' end and
	case when "billType" is null then 1=1 else  PH."BillType" ilike '%' ||"billType"||'%' end and
 	case when "createdBy" is null then 1=1 else  A."AccountId"="createdBy" end and
  --  case when "supplierName" is null then 1=1 else S."Name" ilike '%' || "supplierName" ||'%' end 
	case when "supplierId" is null then 1=1 else ph."SupplierId" = "supplierId"::int end and
	    case when "paidVia" is null then 1=1 else PH."BillType" ilike '%' || "paidVia" ||'%' end and
 	case when "dueDate" is null then 1=1 else "dueDate" =PH."DueDate"::date end 
     and case when "fromDate" is null then 1=1 
 	else (PH."CreatedDate" >= "fromDate" and PH."CreatedDate" <= "toDate")  end and
	case when "pharmacyWareHouseId" is null then 1=1 else  PW."PharmacyWareHouseId" = "pharmacyWareHouseId" end and 
	case when "locationId" is null then 1=1 else (PW."LocationId" = "locationId"::int or PW."LocationId" is null) end
group by PH."PharmacyPurchaseHeaderId" ,PH."BillNumber",PH."BillType",PH."CreatedDate", PH."Netamount",S."Name",S."SupplierId",
A."FullName" ,R."RoleName",PW."WareHouseName",L."Name",PT."PayTypeName",PH."Taxes"

union

select PH."PharmacyPurchaseHeaderId" ,PH."DueDate",PH."BillNumber",PH."BillType",prh."CreatedDate" "BillDate",A."FullName" 
"CreatedByName",R."RoleName" "Role",S."Name" "SupplierName", -prh."OverallNetamount" "Netamount",false "PharmacyBillType"
,PW."WareHouseName",L."Name" as "LocationName",'null',prh."OverallTaxes" as "Taxes"
from "PharmacyPurchaseReturnHeader" prh
	join "Account" A on A."AccountId"=prh."CreatedBy"
	join "Role" R on R."RoleId"=A."RoleId"
	Join "PharmacyPurchaseHeader" ph on ph."PharmacyPurchaseHeaderId"= prh."PharmacyPurchaseHeaderId"
	join "Supplier" s on s."SupplierId"=ph."SupplierId"  
	join "PharmacyWareHouse" PW on PW."PharmacyWareHouseId" =ph."PharmacyWareHouseId"
	left join "Location" L on L."LocationId" = PW."LocationId"
where	
 case when "billNumber" is null then 1=1 else  PH."BillNumber" ilike '%' || "billNumber" ||'%' end and
 	case when "billType" is null then 1=1 else  PH."BillType" ilike '%' ||"billType"||'%' end and
 	case when "createdBy" is null then 1=1 else  A."AccountId"="createdBy" end and
    -- case when "supplierName" is null then 1=1 else S."Name" ilike '%' || "supplierName" ||'%' end 
	case when "supplierId" is null then 1=1 else ph."SupplierId" = "supplierId"::int end 
 		 and   case when "paidVia" is null then 1=1 else PH."BillType" ilike '%' || "paidVia" ||'%' end and
 	case when "dueDate" is null then 1=1 else "dueDate" =PH."DueDate"::date end 
     --and case when "fromDate" is null then 1=1 else PH."BillDate" >= "fromDate" end 
 	--and case when "toDate" is null then 1=1 else PH."BillDate" <= "toDate" end 
 	and case when "fromDate" is null then 1=1 
 	else (PH."CreatedDate" >= "fromDate" and PH."CreatedDate" <= "toDate")  end and
	case when "pharmacyWareHouseId" is null then 1=1 else  PW."PharmacyWareHouseId" = "pharmacyWareHouseId" end and
	case when "locationId" is null then 1=1 else (PW."LocationId" = "locationId"::int or PW."LocationId" is null) end
group by PH."PharmacyPurchaseHeaderId" ,PH."DueDate",PH."BillNumber",PH."BillType",prh."CreatedDate",A."FullName" 
,R."RoleName" ,S."Name" ,s."SupplierId", prh."OverallNetamount",PW."WareHouseName",L."Name",prh."OverallTaxes"
	) Ph
where case when "pharmacyBillType" is null then 1=1 
when "pharmacyBillType" = true then "PharmacyBillType" = true
when "pharmacyBillType" = false then "PharmacyBillType" = false
end 
order by PH."BillDate" desc, PH."PharmacyPurchaseHeaderId";
END
$BODY$;

----------------------------------------------------------------------------Manish 31july2023----------------------------------------------
create table if not exists public."VaccinePharmacyLinkHeader"(
			"VaccinePharmacyLinkHeaderId" serial primary key,
			"PharmacyProductId" int references "PharmacyProduct"("PharmacyProductId"),
			"CreatedBy" int references "Account"("AccountId"),
			"CreatedDate" timestamp without time zone,
			"ModifiedBy" int references "Account"("AccountId"),
			"ModifiedDate" timestamp without time zone
);
create table if not exists public."VaccinePharmacyLinkDetail"(
					"VaccinePharmacyLinkDetailId" serial primary key,
					"VaccinePharmacyLinkHeaderId" int references "VaccinePharmacyLinkHeader"("VaccinePharmacyLinkHeaderId"),
					"VaccineMasterId" int references "VaccineMaster"("VaccineMasterId")
);
create table if not exists public."ImmunizationHistory"(
					"ImmunizationHistoryId" serial primary key,
					"PharmacyProductId" int references "PharmacyProduct"("PharmacyProductId"),
					"VaccineMasterId" int references "VaccineMaster"("VaccineMasterId"),
					"ProductName" text,
					"BillNumber" varchar(300),
					"BatchNumber" varchar(300),
					"ExpiryDate" date,
					"CreatedBy" int references "Account"("AccountId"),
					"CreatedDate" timestamp without time zone
);
-----------------------------------------------------------------------Jayshree 31July2023------------------------------------------------------
--
ALTER TABLE if exists "AppointmentTransaction"
ADD COLUMN  if not exists "PayStatus" character(1) Null;
--------------------
DROP FUNCTION IF EXISTS public."udf_report_TransactionTallyExcel"(timestamp without time zone, timestamp without time zone, integer, integer);

CREATE OR REPLACE FUNCTION public."udf_report_TransactionTallyExcel"(
	"fromDate" timestamp without time zone DEFAULT NULL::timestamp without time zone,
	"toDate" timestamp without time zone DEFAULT NULL::timestamp without time zone,
	locationid integer DEFAULT NULL::integer,
	moduleid integer DEFAULT NULL::integer)
    RETURNS TABLE("TotalItems" bigint, "TransactionDate" timestamp without time zone, "TransactionId" character varying, "VoucherNumber" character varying, "SendedVia" text, "ReceivedIn" text,"PayStatus" char, "ReceiptTypeName" character varying, "ReceiptAreaType" character varying, "AreaId" integer, "Cost" numeric, "ReceiptId" integer, "AppAmount" numeric, "AppDiscount" numeric, "AppTotal" numeric, "UMRNo" character varying) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
begin
return query

 with discountData as(
	--appointment
        SELECT A."Amount",A."Discount",A."Total",AT."AppointmentTransactionId"--, R."Cost"
          from "Receipt" R
         join "Appointment" A on A."AppointmentId" = R."RespectiveId"
          join "AppointmentTransaction" AT on AT."AppointmentTransactionId" = R."TransactionId"
         where R."ReceiptAreaTypeId" = 4 and A."Discount" > 0
	 			 and case when "fromDate" is null then 1=1 else "fromDate"<=  AT."CreatedDate" end 
 				and case when "toDate" is null then 1=1 else  AT."CreatedDate"<=  "toDate" end 
  
UNION ALL
	--scan
        SELECT A."ActualAmount" "Amount",A."DiscountAmount" "Discount",A."Amount" "Total",AT."AppointmentTransactionId"--, R."Cost"
          from "Receipt" R
         join "BookScanAppointment" A on A."BookScanAppointmentId" = R."RespectiveId"
          join "AppointmentTransaction" AT on AT."AppointmentTransactionId" = R."TransactionId"
         where R."ReceiptAreaTypeId" = 10 and A."DiscountAmount" > 0
	 		 and case when "fromDate" is null then 1=1 else "fromDate"<=  AT."CreatedDate" end 
 			and case when "toDate" is null then 1=1 else  AT."CreatedDate"<=  "toDate" end 
UNION ALL
	--lab
        SELECT A."OverallTotalAmount" "Amount",A."OverallDiscount" "Discount",A."OverallNetAmount" "Total",AT."AppointmentTransactionId"--, R."Cost"
          from "Receipt" R
         join "NewLabBookingHeader" A on A."NewLabBookingHeaderId" = R."RespectiveId"
          join "AppointmentTransaction" AT on AT."AppointmentTransactionId" = R."TransactionId"
         where R."ReceiptAreaTypeId" = 8 and A."OverallDiscount" > 0 
	 		 and case when "fromDate" is null then 1=1 else "fromDate"<=  AT."CreatedDate" end 
 			and case when "toDate" is null then 1=1 else  AT."CreatedDate" <=  "toDate" end 
UNION ALL
--pharma	
        SELECT A."Total" "Amount",A."OverallDiscount" "Discount",A."OverallNetAmount" "Total",AT."AppointmentTransactionId"--, R."Cost"
          from "Receipt" R
         join "PharmacySaleHeader" A on A."PharmacySaleHeaderId" = R."RespectiveId"
          join "AppointmentTransaction" AT on AT."AppointmentTransactionId" = R."TransactionId"
         where R."ReceiptAreaTypeId" = 1 and A."OverallDiscount" > 0 
	 		 and case when "fromDate" is null then 1=1 else "fromDate"<=  AT."CreatedDate" end 
 			and case when "toDate" is null then 1=1 else  AT."CreatedDate" <=  "toDate" end 
 )
   SELECT  COUNT(*) OVER () AS "TotalItems" ,T."TransactionDate",T."TransactionId",T."VoucherNumber",
   		T."SendedVia",T."ReceivedIn",T."PayStatus"
    ,RT."ReceiptTypeName",RA."Name" as "ReceiptAreaType",RA."ReceiptAreaTypeId" as "AreaId",
	--PM."PaymentType",
	R."Cost",R."ReceiptId"
    ,DD."Amount"  as "AppAmount",DD."Discount" as "AppDiscount",DD."Total" as "AppTotal" 
	 ,P."UMRNo"
 	from "AppointmentTransaction"  T
	left Join "ReceiptType" RT on RT."ReceiptTypeId"=T."ReceiptTypeId" 
	left Join "ReceiptAreaType" RA on   RA."ReceiptAreaTypeId"=T."ReceiptAreaTypeId"
 	left join "PaymentMode" PM on PM."PaymentModeId"=T."PaymentModeId"
 	Join "Receipt" R on R."TransactionId"=T."AppointmentTransactionId"
	left join "MasterBill" MB on MB."MasterBillId"=R."MasterBillId"
	left join "Patient" P on P."PatientId"=MB."PatientId"
 	--left join appDiscountData  AD on AD."AppointmentTransactionId"=T."AppointmentTransactionId"
	left join discountData  DD on DD."AppointmentTransactionId"=T."AppointmentTransactionId"
   where 
   	case when "moduleid" is null then 1=1 else RA."ReceiptAreaTypeId" = "moduleid" end	
	 and case when "locationid" is null then 1=1 else T."LocationId" = "locationid" end		 
	 and case when "fromDate" is null then 1=1 else "fromDate"<=  T."CreatedDate" end 
 	and case when "toDate" is null then 1=1 else  T."CreatedDate" <=  "toDate" end 

	order by T."TransactionDate" desc 
;

end
$BODY$;
