-----------------------------------------------------------01Aug2023-----------------------------------------------------------------------------------
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, "ReceiptDate" timestamp without time zone) 
    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",A."ReceiptDate" 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" "ReceiptDate"
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."ReceiptDate"
order by A."ReceiptDate" desc;
END
$BODY$;


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

CREATE OR REPLACE FUNCTION public.udf_pharmacypatientbills_finalreport(
	"billNumber" text DEFAULT NULL::text,
	"accountId" integer DEFAULT NULL::integer,
	"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,
	"pharmacyBillType" boolean DEFAULT NULL::boolean)
    RETURNS TABLE("PharmacySaleHeaderId" integer, "BillNumber" character varying, "PaidVia" character varying, "PaymentNumber" character varying, "SaleDate" timestamp without time zone, "PatientName" character varying, "PatientMobile" character varying, "UMRNo" character varying, "ProviderName" character varying, "CreatedByName" text, "RoleName" character varying, "TotalAmount" numeric, "SaleReturnHeaderId" integer, "OverallTaxes" numeric, "RetailName" text, "typeOfPayment" character, "ReceiptDate" timestamp without time zone) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$

BEGIN

return query

select PH."PharmacySaleHeaderId" ,PH."BillNumber",PH."PaidVia",PH."PaymentNumber",PH."SaleDate" "SaleDate",PH."PatientName",
PH."Mobile" ,Ph."UMRNo",PH."ProviderName",ph."CreatedByName",
ph."Role", PH."OverallNetAmount",PH."SaleReturnHeaderId" ,PH."OverallTaxes",PH."RetailName",PH."PaymentStatus",PH."ReceiptDate"
from 
(
select PH."PharmacySaleHeaderId" ,PH."BillNumber",PT."PayTypeName" as "PaidVia",PH."PaymentNumber",PH."CreatedDate" "SaleDate",
	PH."PatientName",PH."Mobile" ,Pa."UMRNo",PH."ProviderName",A."FullName" 
"CreatedByName",R."RoleName" "Role" ,
	 RC."Cost" as "OverallNetAmount",true "PharmacyBillType",null "SaleReturnHeaderId",PH."OverallTaxes",
	RP."RetailName",  PH."PaymentType" as "PaymentStatus",RC."CreatedDate" "ReceiptDate"
from "PharmacySaleHeader" PH
	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"
left join "Patient" Pa on Pa."PatientId"::text=PH."PatientId"::text
	left Join "Receipt" RC on RC."RespectiveId"=PH."PharmacySaleHeaderId"
	 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 "accountId" is null then 1=1 else PH."CreatedBy"="accountId" 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 "fromDate"<= RC."CreatedDate"  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",PT."PayTypeName", PH."PaymentNumber",PH."SaleDate", PH."OverallNetAmount",
	PH."PatientName",PH."ProviderName",Pa."UMRNo",A."FullName" 
,R."RoleName",RP."RetailName",RC."Cost",PH."PaymentType",RC."CreatedDate"
union 
	
select PH."PharmacySaleHeaderId" ,PH."BillNumber",PT."PayTypeName" as "PaidVia",PH."PaymentNumber",srh."ReturnDate" "SaleDate",PH."PatientName",
	Ph."Mobile" ,Pa."UMRNo",PH."ProviderName",A."FullName" 
"CreatedByName",R."RoleName" "Role", -srh."OverallNetAmount" "TotalAmount",false "PharmacyBillType"
,srh."SaleReturnHeaderId",srh."OverallTaxes",
	RP."RetailName", srh."BillType"::character as "PaymentStatus",RC."CreatedDate" "ReceiptDate"
	from "SaleReturnHeader" srh
Join "PharmacySaleHeader" ph on ph."PharmacySaleHeaderId"= srh."PharmacySaleHeaderId"
	join "Account" A on A."AccountId"=srh."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"
left join "Patient" Pa on Pa."PatientId"::text=PH."PatientId"::text
	left Join "Receipt" RC on RC."RespectiveId"=srh."SaleReturnHeaderId"
	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 "accountId" is null then 1=1 else srh."CreatedBy"="accountId" 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",PT."PayTypeName", PH."PaymentNumber",srh."ReturnDate", srh."OverallNetAmount",
	PH."PatientName",Pa."Mobile",Pa."UMRNo",PH."ProviderName",A."FullName" 
,R."RoleName",srh."SaleReturnHeaderId", RP."RetailName",srh."BillType",RC."CreatedDate"
) 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."ReceiptDate" desc;
END

$BODY$;

-------------------------------------------------------------Manish 01Aug2023--------------------------------------------------------
alter table if exists public."ImmunizationHistory" 
add column if not exists "Status" varchar(50);

alter table if exists public."ImmunizationHistory" 
add column if not exists "PatientId" int references "Patient"("PatientId");

alter table if exists "ImmunizationHistory"
add column if not exists "VaccineGivenBy" int references "Account"("AccountId"),
add column if not exists "VaccineGivenDate" timestamp without time zone;

---------------------------------------------------------Sravani 02Aug2023------------------------------------------------------------
INSERT INTO public."ScanLogType"("LogTypeName","Active")
SELECT 'PaymentInitiationLog',true
WHERE
NOT EXISTS (
SELECT "LogTypeName" FROM public."ScanLogType" WHERE "LogTypeName" = 'PaymentInitiationLog'
);

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

----------------------------------------------------------Mounika A 02Aug2023--------------------------------------------------------
alter table  if exists "PediatricEncounter"
add column if not exists "MChat" text;
----------------------------------------------------------Sai John 02Aug2023---------------------------------------------------------
ALTER TABLE if exists public."PackageModule" 
ADD column if not exists "DiscountType" varchar(1) NULL;
ALTER TABLE if exists public."PackageModule" 
ADD column if not exists "DiscountPercentage" numeric(8, 2) NULL;
ALTER TABLE if exists public."PackageModule" 
ADD column if not exists "DiscountAmount" numeric(8, 2) NULL;
ALTER TABLE if exists public."PackageModule" 
drop constraint if exists "FK_PackageModule_CreatedBy",
ADD CONSTRAINT "FK_PackageModule_CreatedBy" FOREIGN KEY ("CreatedBy") REFERENCES public."Account"("AccountId");
ALTER TABLE if exists public."PackageModule" 
drop constraint if exists "FK_PackageModule_ModifiedBy",
ADD CONSTRAINT "FK_PackageModule_ModifiedBy" FOREIGN KEY ("ModifiedBy") REFERENCES public."Account"("AccountId");

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

ALTER TABLE if exists public."Counseling" 
ALTER COLUMN "PatientSignature" DROP NOT NULL;
ALTER TABLE if exists public."Counseling" 
ALTER COLUMN "CounselorSignature" DROP NOT NULL;

CREATE SEQUENCE if not exists "CounselingDetail_CounselingDetailId_Seq";
CREATE TABLE if not exists public."CounselingDetail" (
	"CounselingDetailId" int4 NOT NULL DEFAULT nextval('"CounselingDetail_CounselingDetailId_Seq"'::regclass),
	"CounselingId" int4 NOT NULL,
	"PackageModuleDetailId" int4 NOT NULL,
	"Quantity" int2 NOT NULL DEFAULT 1,
	"IsFree" bool NOT NULL DEFAULT false,
	"Amount" numeric(8, 2) NOT NULL,
	"Active" bool NOT NULL DEFAULT true,
	"CreatedBy" int4 NOT NULL,
	"CreatedDate" timestamp NOT NULL DEFAULT now(),
	"ModifiedBy" int4 NULL,
	"ModifiedDate" timestamp NULL,
	CONSTRAINT "PK_CounselingDetail_CounselingDetailId" PRIMARY KEY ("CounselingDetailId")
);

--ALTER TABLE if exists public."CounselingDetail" 
--drop constraint if exists "FK_CounselingDetail_CounselingId",
--ADD CONSTRAINT "FK_CounselingDetail_CounselingId" FOREIGN KEY ("CounselingId") REFERENCES public."Counseling"("CounselingId");
--ALTER TABLE if exists public."CounselingDetail" 
--drop constraint if exists "FK_CounselingDetail_CreatedBy",
--ADD CONSTRAINT "FK_CounselingDetail_CreatedBy" FOREIGN KEY ("CreatedBy") REFERENCES public."Account"("AccountId");
--ALTER TABLE if exists public."CounselingDetail" 
--drop constraint if exists "FK_CounselingDetail_ModifiedBy",
--ADD CONSTRAINT "FK_CounselingDetail_ModifiedBy" FOREIGN KEY ("ModifiedBy") REFERENCES public."Account"("AccountId");
--ALTER TABLE if exists public."CounselingDetail" 
--drop constraint if exists "FK_CounselingDetail_PackageModuleDetailId",
--ADD CONSTRAINT "FK_CounselingDetail_PackageModuleDetailId" FOREIGN KEY ("PackageModuleDetailId") REFERENCES public."PackageModuleDetail"("PackageModuleDetailId");
--------------------------------------------------------Chandana 02Aug2023-----------------------------
alter table if exists "DietEncounter" 
add column if not exists "SpecialFeature" text;

---------------------------------------------------------Manish 02Aug2023---------------------------------

alter table if exists public."ImmunizationHistory" 
add column if not exists "Status" varchar(50);

alter table if exists public."ImmunizationHistory" 
add column if not exists "PatientId" int references "Patient"("PatientId");

alter table if exists "ImmunizationHistory"
	add column if not exists "VaccineGivenBy" int references "Account"("AccountId"),
	add column if not exists "VaccineGivenDate" timestamp without time zone;



alter table if exists "PediatricEncounter" 
add column if not exists "VaccineDetail" text;




alter table if exists "PediatricAgeWiseData" 
add column if not exists "L" numeric,
 add column if not exists "M" numeric, 
 add column if not exists "P999" numeric,
 add column if not exists "P01" numeric,
 add column if not exists "P10" numeric,
 add column if not exists "P90" numeric;


DO $$                  
    BEGIN 
        IF EXISTS
            ( SELECT 1
              FROM   information_schema.tables 
              WHERE  table_schema = 'public'
              AND    table_name = 'Menu'
            )
        THEN
            UPDATE "Menu"
            SET "EncounterKey" = 'vaccineDetail'
            where "Url"='/app/pediatric-encounter/:id/:type/immunization';
        END IF ;
    END
   $$ ;
----------------------------------------------Kalyan -----------------------------
--alter table if exists "AdmissionPackage"
--add column if not exists "CounselingId" int,
--drop constraint if exists "FK_AdmissionPackage_CounselingId",
--add CONSTRAINT "FK_AdmissionPackage_CounselingId" FOREIGN KEY ("CounselingId")
--        REFERENCES public."Counseling" ("CounselingId") MATCH SIMPLE
--        ON UPDATE NO ACTION
--        ON DELETE NO ACTION;
------------------------------------------------------Mounika A 3Aug2023-----------------------------------
alter table if exists "PediatricEncounter"
add column if not exists "FamilyHistory" text;

alter table if exists "PediatricEncounter"
add column  if not exists "BirthHistory"  text;

alter table if exists "PediatricEncounter"
add column if not exists "SpecialFeatures" text;
----------------------------------------------------Manish 3Aug2023---------------------------------------

alter table if exists "PediatricAgeWiseData"
add column if not exists "M" numeric, 
add column if not exists "L" numeric, 
add column if not exists "P999" numeric,
 add column if not exists "P01" numeric,
 add column if not exists "P10" numeric,
 add column if not exists "P90" numeric,
add column if not exists "S" numeric,
add column if not exists "Minus3SD" numeric,
add column if not exists "Minus2SD" numeric,
add column if not exists "Minus1SD" numeric,
add column if not exists "Median" numeric,
add column if not exists "1SD" numeric,
add column if not exists "2SD" numeric,
add column if not exists "3SD" numeric; 

------------------------------------Shivani 04Aug2023-------------------------------------

alter table if exists "PediatricEncounter"
add column if not exists "DiagnosisOrder" text;


alter table if exists "PediatricEncounter"
add column if not exists "NextVisitOrder" text;
------------------------------------Jayshree 04Aug2023-------------------------------------

DROP FUNCTION IF EXISTS public."udf_report_MIS_CATEGORY_WISE_VISIT_COUNT_DMY"(integer);

CREATE OR REPLACE FUNCTION public."udf_report_MIS_CATEGORY_WISE_VISIT_COUNT_DMY"(
	locationid integer DEFAULT NULL::integer)
    RETURNS TABLE("TitleName" text, "CaptionName" character varying, "RevenueDay" numeric, "CountDay" bigint, "RevenueMonth" numeric, "CountMonth" bigint, "RevenueYear" numeric, "CountYear" bigint) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
begin
return query
with category as(
				select "ReceiptAreaTypeId" as "CategoryId","Name" as "CategoryName"
		        from "ReceiptAreaType"
	            where "ReceiptAreaTypeId" in (1,3,4,8,10,12)
				)

, yearwise As  (
	select A."CategoryId" ,sum(A."YearCount") as "YearCount"
	from
	(	
	select 
			  MB."MasterBillId",RT."ReceiptAreaTypeId" as "CategoryId",RT."Name" as "CategoryName",Count(MB."MasterBillId")as "YearCount"
		   from "MasterBill" MB			
			join "Receipt" R on R."MasterBillId"=MB."MasterBillId"--joining Receipt table ,to get count those paid some amount.
 			join "ReceiptAreaType" RT on RT."ReceiptAreaTypeId"=MB."ReceiptAreaTypeId"
		where 
			R."ReceiptAreaTypeId" in (1,3,4,8,10,12) and
			DATE_PART('year', MB."BillDate"::TIMESTAMP)= DATE_PART('year',CURRENT_TIMESTAMP)	 
			and case when "locationid" is null then 1=1 else MB."LocationId" = "locationid" end					
		
		group by RT."ReceiptAreaTypeId",RT."Name",MB."MasterBillId"
EXCEPT		
		
		select 
			  MB."MasterBillId",RT."ReceiptAreaTypeId" as "CategoryId",RT."Name" as "CategoryName",Count(MB."MasterBillId")as "YearCount"
		   from "MasterBill" MB			
			join "Receipt" R on R."MasterBillId"=MB."MasterBillId"--joining Receipt table ,to get count those paid some amount.
 			join "ReceiptAreaType" RT on RT."ReceiptAreaTypeId"=MB."ReceiptAreaTypeId"
		where 
			R."ReceiptAreaTypeId" in (5,7,9,11,13) and
			DATE_PART('year', MB."BillDate"::TIMESTAMP)= DATE_PART('year',CURRENT_TIMESTAMP)	 
			and case when "locationid" is null then 1=1 else MB."LocationId" = "locationid" end					
		
		group by RT."ReceiptAreaTypeId",RT."Name",MB."MasterBillId"
		)A
	 group by A."CategoryId"

) 
 , monthwise as ( 
	 select A."CategoryId" ,sum(A."MonthCount") as "MonthCount"
	from
	(
	 	select 
			 MB."MasterBillId", RT."ReceiptAreaTypeId" as "CategoryId",RT."Name" as "CategoryName",Count(MB."MasterBillId")as "MonthCount"			
	 	    from "MasterBill" MB
		    join "Receipt" R on R."MasterBillId"=MB."MasterBillId"
			join "ReceiptAreaType" RT on RT."ReceiptAreaTypeId"=MB."ReceiptAreaTypeId"	 		
 		where 
	 		R."ReceiptAreaTypeId" in (1,3,4,8,10,12) and			
			 DATE_TRUNC('MONTH', MB."BillDate"::TIMESTAMP)= DATE_TRUNC('MONTH',CURRENT_TIMESTAMP)	
			and case when "locationid" is null then 1=1 else MB."LocationId" = "locationid" end			
	 group by RT."ReceiptAreaTypeId",RT."Name",MB."MasterBillId"
EXCEPT	 
	 select 
			 MB."MasterBillId", RT."ReceiptAreaTypeId" as "CategoryId",RT."Name" as "CategoryName",Count(MB."MasterBillId")as "MonthCount"			
	 	    from "MasterBill" MB
		    join "Receipt" R on R."MasterBillId"=MB."MasterBillId"
			join "ReceiptAreaType" RT on RT."ReceiptAreaTypeId"=MB."ReceiptAreaTypeId"	 		
 		where 
	 		R."ReceiptAreaTypeId" in (5,7,9,11,13) and			
			 DATE_TRUNC('MONTH', MB."BillDate"::TIMESTAMP)= DATE_TRUNC('MONTH',CURRENT_TIMESTAMP)	
			and case when "locationid" is null then 1=1 else MB."LocationId" = "locationid" end			
	 group by RT."ReceiptAreaTypeId",RT."Name",MB."MasterBillId"
		)A
	 group by A."CategoryId"
)
, daywise as( 
	select A."CategoryId" ,sum(A."DayCount") as "DayCount"
	from
	(
	select 
		MB."MasterBillId", RT."ReceiptAreaTypeId" as "CategoryId",RT."Name" as "CategoryName",Count(MB."MasterBillId")as "DayCount"
		from 
		"MasterBill" MB 	
		join "Receipt" R on R."MasterBillId"=MB."MasterBillId"
		join "ReceiptAreaType" RT on RT."ReceiptAreaTypeId"=MB."ReceiptAreaTypeId"		
	 where 
		RT."ReceiptAreaTypeId" in (1,3,4,8,10,12) and
		MB."BillDate"::date= NOW()::date  
		and case when "locationid" is null then 1=1 else MB."LocationId" = "locationid" end			
	 group by RT."ReceiptAreaTypeId",RT."Name",MB."MasterBillId"
EXCEPT
	select 
		MB."MasterBillId", RT."ReceiptAreaTypeId" as "CategoryId",RT."Name" as "CategoryName",Count(MB."MasterBillId")as "DayCount"
		from 
		"MasterBill" MB 	
		join "Receipt" R on R."MasterBillId"=MB."MasterBillId"
		join "ReceiptAreaType" RT on RT."ReceiptAreaTypeId"=MB."ReceiptAreaTypeId"		
	 where 
		RT."ReceiptAreaTypeId" in (5,7,9,11,13) and
		MB."BillDate"::date= NOW()::date  
		and case when "locationid" is null then 1=1 else MB."LocationId" = "locationid" end			
	 group by RT."ReceiptAreaTypeId",RT."Name",MB."MasterBillId"
		)A
	 group by A."CategoryId"
) 
select 'CATEGORY WISE VISIT COUNT' as "TitleName" ,C."CategoryName" as "CaptionName" --, C."CategoryId"
, 0::numeric as "RevenueDay",d."DayCount"::bigint as "CountDay"
,0::numeric as "RevenueMonth", m."MonthCount"::bigint as "CountMonth"
,0::numeric as "RevenueYear" ,y."YearCount" ::bigint as "CountYear"
	
from "category" C
left join "daywise" d on d."CategoryId"=C."CategoryId"
left join "monthwise" m on m."CategoryId"=C."CategoryId"
left join "yearwise" y on y."CategoryId"=C."CategoryId"

ORDER by C."CategoryName" ASC
;

end
$BODY$;

--------------Jayshree

DROP FUNCTION IF EXISTS public."udf_report_MIS_SPECIALITY_WISE_REVENUE_DMY"(integer);

CREATE OR REPLACE FUNCTION public."udf_report_MIS_SPECIALITY_WISE_REVENUE_DMY"(
	locationid integer DEFAULT NULL::integer)
    RETURNS TABLE("TitleName" text, "CaptionName" character varying, "RevenueDay" numeric, "CountDay" bigint, "RevenueMonth" numeric, "CountMonth" bigint, "RevenueYear" numeric, "CountYear" bigint) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
begin
return query
with  yearwise As  ( 	
	select 
	cd."SpecializationId",cd."SpecializationName",sum(cd."PaidAmount")-sum(cd."RefundAmount") as "Revenueyear"
	from(
		select 
		PR."SpecializationId",PR."SpecializationName" ,
		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"
		,MB."MasterBillId"  
		from 
		"Receipt" R
		left join "Appointment" A on R."RespectiveId" =A."AppointmentId" 
		Join "Specialization" PR on A."SpecializationId"=PR."SpecializationId"
		join "MasterBill" MB on MB."MasterBillId"=R."MasterBillId"
		where 
		PR."Active" <> false and
		R."ReceiptAreaTypeId" in (4,5) and --MB."LocationId"=2 and				
		DATE_PART('year', R."CreatedDate")= DATE_PART('year',CURRENT_TIMESTAMP)
		and case when "locationid" is null then 1=1 else MB."LocationId" = "locationid" end	
	)cd
	group by cd."SpecializationId",cd."SpecializationName"
) 
 , monthwise as ( 		 	 
	 select 
	cd."SpecializationId",cd."SpecializationName",sum(cd."PaidAmount")-sum(cd."RefundAmount") as "Revenuemonth"
	from(
		select 
		PR."SpecializationId",PR."SpecializationName" ,
		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"
		,MB."MasterBillId"  
		from 
		"Receipt" R
		left join "Appointment" A on R."RespectiveId" =A."AppointmentId" 
		Join "Specialization" PR on A."SpecializationId"=PR."SpecializationId"
		join "MasterBill" MB on MB."MasterBillId"=R."MasterBillId"
		where 
		PR."Active" <> false and
		R."ReceiptAreaTypeId"in (4,5) and --MB."LocationId"=2 and		
		DATE_TRUNC('MONTH', R."CreatedDate")= DATE_TRUNC('MONTH',CURRENT_TIMESTAMP)
		and case when "locationid" is null then 1=1 else MB."LocationId" = "locationid" end	
	)cd
	group by cd."SpecializationId",cd."SpecializationName"

)
, daywise as( 
		select 
	cd."SpecializationId",cd."SpecializationName",sum(cd."PaidAmount")-sum(cd."RefundAmount") as "Revenueday"
	from(
		select 
		PR."SpecializationId",PR."SpecializationName" ,
		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"
		,MB."MasterBillId"  
		from 
		"Receipt" R
		left join "Appointment" A on R."RespectiveId" =A."AppointmentId" 
		Join "Specialization" PR on A."SpecializationId"=PR."SpecializationId"
		join "MasterBill" MB on MB."MasterBillId"=R."MasterBillId"
		where 
		PR."Active" <> false and
		R."ReceiptAreaTypeId"in (4,5) and-- MB."LocationId"=1 and		
		R."CreatedDate"::date= NOW()::date
		and case when "locationid" is null then 1=1 else MB."LocationId" = "locationid" end	
	)cd
	group by cd."SpecializationId",cd."SpecializationName"
	
) 
select 'SPECIALITY 
WISE REVENUE' as "TitleName" ,C."SpecializationName" as "CaptionName" --, C."ProviderId"
, d."Revenueday" as "RevenueDay", 0::bigint as "CountDay"
,m."Revenuemonth" as "RevenueMonth", 0::bigint  as "CountMonth"
,y."Revenueyear" as "RevenueYear" , 0::bigint as "CountYear"
	
from "Specialization" C
left join "daywise" d on d."SpecializationId"=C."SpecializationId"
left join "monthwise" m on m."SpecializationId"=C."SpecializationId"
left join "yearwise" y on y."SpecializationId"=C."SpecializationId"
where C."Active" <> false
ORDER by C."SpecializationName" ASC
;

end
$BODY$;

-------------------------------------Shivani 4Aug2023------------------------------------------
alter table if exists "ObEncounter"
add column if not exists "NeonatalAssessmentForm" text;



-------------------------------------Chandhana 7Aug2023------------------------------------------
alter table if exists "Patient"
add column if not exists "TimeOfBirth" time without time zone;;

-------------------------------------ShivaRam 7Aug2023------------------------------------------
ALTER TABLE IF EXISTS public."Relations" 
ADD COLUMN if not exists  "RO" text ;
-------------------------------------Tej 8Aug2023------------------------------------------
alter table IF EXISTS "Appointment"
add column if not exists  "IsHealthCard" boolean;
------------------------------------Shivani 8Aug2023-----------------------------------------
alter table if exists "ObEncounter"
add column if not exists "ScanAppointmentDetails" text;


------------------------------Chandana 8Aug2023-----------------------------------------------------------

 DROP FUNCTION IF EXISTS public."udf_uiReport_fetch_Appointments_Location1"(integer, text, integer[], integer[], integer[], text, integer[], text, text, integer, date, date, integer[], boolean, text[], integer, integer);

CREATE OR REPLACE FUNCTION public."udf_uiReport_fetch_Appointments_Location1"(
	locationid integer DEFAULT NULL::integer,
	"appointmentNo" text DEFAULT NULL::text,
	"departmentId" integer[] DEFAULT NULL::integer[],
	"providerId" integer[] DEFAULT NULL::integer[],
	"patientId" integer[] DEFAULT NULL::integer[],
	"uMRNo" text DEFAULT NULL::text,
	"patientReferredById" integer[] DEFAULT NULL::integer[],
	"referredByName" text DEFAULT NULL::text,
	mobile text DEFAULT NULL::text,
	"payTypeId" integer DEFAULT NULL::integer,
	"fromDate" date DEFAULT NULL::date,
	"toDate" date DEFAULT NULL::date,
	"appointmentTypeId" integer[] DEFAULT NULL::integer[],
	"paymentStatus" boolean DEFAULT NULL::boolean,
	status text[] DEFAULT NULL::text[],
	"pageIndex" integer DEFAULT 0,
	"pageSize" integer DEFAULT 10)
    RETURNS TABLE("DepartmentId" text, "DepartmentName" character varying, "ProviderId" text, "ProviderName" character varying, "AppointmentTypeName" character varying, "AppointmentDate" date, "AppointmentNo" character varying, "PatientId" integer, "Name" character varying, "ReferredByName" character varying, "PatientName" character varying, "PatientAge" smallint, "UMRNo" character varying, "Mobile" character varying, "PatientGender" character, "AppointmentTime" time without time zone, "VisitType" character, "PaymentType" character varying, "PaymentNumber" character varying, "TotalAppointments" bigint, "TotalAmount" bigint, "TotalAmountStr" text, "ReceiptCreatedByName" text, "ReceiptDate" timestamp without time zone, "ReceiptId" integer, "StreetAdress" character varying, "City" character varying, "State" character varying, "FatherOrHusband" text, "PaymentStatus" boolean, "EncounterType" encountertype_elements, "Status" text, "TypeOfPayment" character, "IsHealthCard" boolean) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
BEGIN

return query 

with cts as (select coalesce(A."DepartmentId"::text,'GrandTotal') "DepartmentId",
			 A."ProviderId"::text as "ProviderId", 
			 A."AppointmentDate",A."AppointmentTypeId",
			ATN."Name" "AppointmentTypeName",
			 A."AppointmentNo",A."PatientId" "PatientId",PRB."Name",Pa."ReferredByName",
			 Pa."FullName",Pa."UMRNo",Pa."Mobile",A."AppointmentTime",A."VisitType",
			 case when ATN."Name"='Follow Up' and sum(A."Total")=0 then 'Free Follow Up'
			 else PT."PayTypeName" end as "PaymentType" ,A."PaymentNumber",
			 A."AppointmentId",
			 case when A."Status"='B' then 'Booked' when A."Status"='R' then 'Rescheduled' when A."Status"='C' then 'Cancel' end::text as "Status",
			 COUNT(A."AppointmentNo") as "TotalAppointments" ,sum(R."Cost")::text as "TotalAmountStr" ,
			 sum(R."Cost")::bigint as "TotalAmount" ,
			 Pa."FatherOrHusband",
			 A."PaymentStatus",
			 A."EncounterType",
			 A."PaymentType" as "TypeOfPayment",R."ReceiptId",A."IsHealthCard"
			 from "Appointment" A
 			left join "Patient" Pa on Pa."PatientId"::text=A."PatientId"::text
			 
			 left join "PatientReferredBy" PRB on PRB."PatientReferredById"::text=Pa."PatientReferredById"::text			
		left join "AppointmentType" ATN on A."AppointmentTypeId"=ATN."AppointmentTypeId"
			 left Join "Receipt" R on R."RespectiveId"=A."AppointmentId"  and R."ReceiptAreaTypeId"=4
			  left join "PayType" PT on PT."PayTypeId"=R."PayTypeId"
where 
			 --A."Status"<>'C' and 
case when "departmentId" is null then 1=1 else  A."DepartmentId"  = any("departmentId") end and 
CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE A."LocationId"=locationId END and
case when "patientId" is null then 1=1 else  Pa."PatientId"  = any("patientId") end and 
case when "appointmentNo" is null then 1=1 when "appointmentNo" ='' then 1=1 else A."AppointmentNo" ilike'%'||"appointmentNo" ||'%' end  and
case when "providerId" is null then 1=1 else  A."ProviderId"  = any("providerId") end and 
case when "uMRNo" is null then 1=1 when "uMRNo" ='' then 1=1 else Pa."UMRNo" ilike'%'||"uMRNo" ||'%' end  and
case when "patientReferredById" is null then 1=1 else  Pa."PatientReferredById"  = any("patientReferredById") end and 
case when "appointmentTypeId" is null then 1=1 else  ATN."AppointmentTypeId"  = any("appointmentTypeId") end and 
case when "referredByName" is null then 1=1 when "referredByName" ='' then 1=1 else Pa."ReferredByName" ilike'%'||"referredByName" ||'%' end and 
case when "mobile" is null then 1=1 when "mobile" ='' then 1=1 else Pa."Mobile" ilike'%'||"mobile" ||'%' end  and
case when "payTypeId" is null then 1=1  else A."PayTypeId" ="payTypeId" end  and
case when "fromDate" is null then 1=1 else "fromDate" <=A."AppointmentDate" and A."AppointmentDate" <="toDate" end and
case when "paymentStatus" is null then 1=1  else A."PaymentStatus" ="paymentStatus" end			 
and case when "status" is null then 1=1 else  A."Status"  =any("status") end	
			 
GROUP BY GROUPING SETS((A."DepartmentId",A."ProviderId",A."PatientId",PRB."Name",
						Pa."ReferredByName",Pa."FullName",Pa."UMRNo",Pa."Mobile",A."AppointmentDate",A."AppointmentTime",
						A."AppointmentNo",A."AppointmentTypeId",
						ATN."Name" ,
						A."VisitType",
						PT."PayTypeName",A."PaymentNumber",
						A."AppointmentId",R."ReceiptId",
						A."Status",Pa."FatherOrHusband",A."PaymentStatus",A."EncounterType",A."PaymentType",A."IsHealthCard"), (A."DepartmentId",A."ProviderId"), ())     
order by A."AppointmentId")

select A."DepartmentId",coalesce(D."DepartmentName",'GrandTotal') "DepartmentName",
case when A."AppointmentNo" is null then 'Total'  else A."ProviderId" end "ProviderId",
case when A."AppointmentNo" is null  then 'Total'  else  Pr."FullName"  end  as "ProviderName",
 ATN."Name" "AppointmentTypeName",
A."AppointmentDate",
A."AppointmentNo",A."PatientId",
case when A."AppointmentNo" is null  then null else PRB."Name"::varchar end as "Name",
case when A."AppointmentNo" is null  then null else Pa."ReferredByName"::varchar end as "ReferredByName",
case when A."AppointmentNo" is null  then null else Pa."FullName"::varchar end as "PatientName",
case when A."AppointmentNo" is null  then null else Pa."Age" end  "PatientAge",
case when A."AppointmentNo" is null  then null else Pa."UMRNo" end  "UMRNo",
case when A."AppointmentNo" is null  then null else Pa."Mobile" end  "Mobile",
case when A."AppointmentNo" is null  then null else Pa."Gender" end "PatientGender",
A."AppointmentTime",
A."VisitType",A."PaymentType",A."PaymentNumber",A."TotalAppointments",A."TotalAmount",A."TotalAmountStr",
 CA."FullName"  "ReceiptCreatedByName", R."CreatedDate" "ReceiptDate",R."ReceiptId",
 case when A."AppointmentNo" is null  then null else Pa."StreetAddress" end "StreetAddress",
case when A."AppointmentNo" is null  then null else Pa."City" end "City",
case when A."AppointmentNo" is null  then null else Pa."State" end "State",
A."FatherOrHusband",
A."PaymentStatus",A."EncounterType",A."Status",A."TypeOfPayment",A."IsHealthCard"
from cts A
left join "Department" D on A."DepartmentId"=D."DepartmentId"::text
left join "Provider" Pr on Pr."ProviderId"::text=A."ProviderId"
left join "Patient" Pa on Pa."PatientId"::text=A."PatientId"::text
left Join "Receipt" R on R."RespectiveId"=A."AppointmentId"  and R."ReceiptAreaTypeId"=4 and R."ReceiptId"=A."ReceiptId"
Left Join "Account" CA on CA."AccountId"=R."CreatedBy"
left join "PatientReferredBy" PRB on PRB."PatientReferredById"::text=Pa."PatientReferredById"::text
 left join  "AppointmentType" ATN on ATN."AppointmentTypeId"=A."AppointmentTypeId"
order by A."AppointmentId"
 ;

END

$BODY$;

------------------------------------------------------------Kalyan 9Aug2023----------------------------------------------------
CREATE SEQUENCE IF NOT EXISTS "MasterOperatingRoom_MasterOperatingRoomId_seq";

CREATE TABLE IF NOT EXISTS public."MasterOperatingRoom"
(
    "MasterOperatingRoomId" integer NOT NULL DEFAULT nextval('"MasterOperatingRoom_MasterOperatingRoomId_seq"'::regclass),
    "MasterOperatingRoomName" character varying(255) COLLATE pg_catalog."default" NOT NULL,
    "Locations" integer[],
    "Comments" 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_MasterOperatingRoom_MasterOperatingRoomId" PRIMARY KEY ("MasterOperatingRoomId"),
    CONSTRAINT "MasterOperatingRoom_MasterOperatingRoomName_key" UNIQUE ("MasterOperatingRoomName"),
    CONSTRAINT "FK_MasterOperatingRoom_CreatedById" FOREIGN KEY ("CreatedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_MasterOperatingRoom_ModifiedBy" FOREIGN KEY ("ModifiedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
);

-------------------------------------------------------Jayshree 9Aug2023-----------------------------------------------------------------------------

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" character, "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(
	 --patient 
        SELECT A."Amount",A."DiscountInRupees" "Discount",A."Total",AT."AppointmentTransactionId"--, R."Cost"
          from "Receipt" R
         join "Patient" A on A."PatientId" = R."RespectiveId"
          join "AppointmentTransaction" AT on AT."AppointmentTransactionId" = R."TransactionId"
         where R."ReceiptAreaTypeId" = 3 and A."DiscountInRupees" > 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
	--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$;

----------------------------------------------------------Mounika A 9Aug2023------------------------------------------------------------
alter table if exists "PediatricEncounter"
drop column if exists "FamilyHistory";
						
alter table if exists "PediatricEncounter"
drop column if exists "BirthHistory";

alter table if exists "PediatricEncounter"
add column if not exists "PatientId" integer,
drop constraint if exists "Pediatric_PatientId",
add CONSTRAINT "Pediatric_PatientId" FOREIGN KEY ("PatientId")
        REFERENCES public."Patient" ("PatientId") MATCH SIMPLE
        ON UPDATE NO ACTION;

--------------------------------------------------------Manish 9Aug2023---------------------------------------------------------------

INSERT INTO public."Settings"("Name","Active","Type","Description")
SELECT 'UserCollectionWhatsAppMessage',true,'Message','used to send total amout from user-collection report'
WHERE
NOT EXISTS (
SELECT "Name" FROM public."Settings" WHERE "Name" = 'UserCollectionWhatsAppMessage'
);

--------------------------------------------------------Jayshree 9Aug2023---------------------------------------------------------

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

CREATE OR REPLACE FUNCTION public."udf_DailySalesReportByMedication"(
	"productName" text DEFAULT NULL::text,
	"genericName" text DEFAULT NULL::text,
	"categoryName" text DEFAULT NULL::text,
	"companyName" text DEFAULT NULL::text,
	"supplierName" text DEFAULT NULL::text,
	"payTypeId" integer DEFAULT NULL::integer,
	"fromDate" date DEFAULT NULL::date,
	"toDate" date DEFAULT NULL::date,
	"locationId" integer DEFAULT NULL::integer)
    RETURNS TABLE("PharmacyProductId" integer, "ProductName" character varying, "BatchNumber" character varying, "GenericName" text, "CategoryName" character varying, "CompanyName" text, "SupplierName" text, "SaleQuantity" bigint, "Mrp" numeric, "Discount" numeric, "TotalAmount" numeric, "PaidVia" character varying, "PaymentNumber" character varying, "SaleDate" timestamp without time zone, "PurchaseValue" numeric, "PurchaseUnitQty" integer, "LocationName" character varying,"OverallNetAmount" numeric) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
Declare 
BEGIN
return query 

select
A."PharmacyProductId",A."ProductName",A."BatchNumber",A."GenericName",A."CategoryName ",A."CompanyName"
,A."SupplierName"
,sum(A."Quantity") "SaleQuantity",A."Mrp",A."OverallDiscount" "Discount",sum(A."NetAmount") "TotalAmount"
,A."PaidVia",A."PaymentNumber",A."SaleDate" , TRUNC((A."PPD_NetAmount"/A."PPD_Quantity"),2)  as "PurchaseValue"
,A."PurchaseUnitQty",A."LocationName",A."OverallNetAmount"
from (
	select 
	PS."PharmacyProductId",PP."ProductName",PRS."BatchNumber",pp."GenericName",ci."Name" "CategoryName ",c."Name" "CompanyName",s."Name" "SupplierName"
	,PH."SaleDate",PS."Quantity",PRS."Mrp",PH."OverallDiscount",PS."NetAmount" , PT."PayTypeName" as "PaidVia", PH."PaymentNumber",
	  ppd."NetAmount" as "PPD_NetAmount",ppd."Quantity" as "PPD_Quantity",L."Name" as "LocationName"
	,pp."PurchaseUnitQty",PH."OverallNetAmount"
	from
	"PharmacySaleHeader" PH
	join "PharmacySaleDetail" PS on PH."PharmacySaleHeaderId"=PS."PharmacySaleHeaderId"
	join "PharmacyProduct" pp on PS."PharmacyProductId"=PP."PharmacyProductId"
	join "Company" c on c."CompanyId"=PP."CompanyId"
	join "LookupValue" ci on ci."LookupValueId"=pp."CategoryId"
	join "PharmacyRetailStock" PRS on   PRS."PharmacyRetailStockId"=PS."PharmacyRetailStockId" and PRS."PharmacyProductId"=PP."PharmacyProductId"
	left join "PharmacyPurchaseDetail" Ppd on  ppd."PharmacyStockId"=prs."PharmacyStockId" and  ppd."PharmacyProductId"=PRS."PharmacyProductId"
	left join "PharmacyPurchaseHeader" pph on pph."PharmacyPurchaseHeaderId"=Ppd."PharmacyPurchaseHeaderId"
	left join "Supplier" s on s."SupplierId"=pph."SupplierId" 
	join "Location" L on L."LocationId" = PH."LocationId"	
	left join "PayType" PT on PT."PayTypeId"=PH."PayTypeId"	
	where
	case when "productName" ='' then 1=1   when "productName" is null then 1=1  else PP."ProductName" ilike  '%'||"productName"||'%' end and 
	case when "genericName" ='' then 1=1  when "genericName" is null then 1=1  else pp."GenericName" ilike  '%'||"genericName"||'%' end and 
  case when "categoryName" ='' then 1=1  when "categoryName" is null then 1=1  else ci."Name" ilike  '%'||"categoryName"||'%' end and 
	case when "companyName" ='' then 1=1  when "companyName" is null then 1=1  else c."Name" ilike  '%'||"companyName"||'%' end and 
  case when "supplierName" ='' then 1=1  when "supplierName" is null then 1=1  else s."Name" ilike  '%'||"supplierName"||'%' 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" ::date <=PH."SaleDate"::date and PH."SaleDate"::date <="toDate" ::date end and
	case when "locationId" is null then 1=1 else PH."LocationId" = "locationId"::int end
	group by 
	PS."PharmacyProductId",PP."ProductName",PRS."BatchNumber",PH."SaleDate"
	,pp."GenericName",ci."Name",c."Name" ,s."Name" ,PS."Quantity",PS."NetAmount",PRS."Mrp",PH."OverallDiscount" ,PT."PayTypeName" , PH."PaymentNumber",
 	ppd."NetAmount", ppd."Quantity",pp."PurchaseUnitQty",L."Name",PH."OverallNetAmount"
) A
	
group by A."PharmacyProductId",A."ProductName",A."BatchNumber",A."GenericName",A."CategoryName ",
A."CompanyName",A."SupplierName",A."Mrp",A."OverallDiscount",A."PaidVia",A."PaymentNumber",A."SaleDate", (A."PPD_NetAmount"/A."PPD_Quantity") , A."PurchaseUnitQty",
A."LocationName",A."OverallNetAmount"
order  by A."ProductName"
;

END
$BODY$;
--------------------------------------------------------------------------------------Tej 10Aug2023------------------------------------------------------------------
alter table if exists "GynEncounter"
add column if not exists "ScanAppointmentDetails" text;
--------------------------------------------------------------------------------------Sravani 10Aug2023--------------------------------------------------------------
alter table if exists "BookScanAppointment" 
add column if not exists "RescheduleReason" text;
--------------------------------------------------------------------------------------Chanadana 10Aug2023--------------------------------------------------------------

--Menus Query Contact Chandana.


--------------------------------------------------------------------------------------Mounika A 10Aug2023--------------------------------------------------------------
alter table if exists "PediatricEncounter"
add column if not exists "MeasureCommonData" text;
--------------------------------------------------------------------------------------Tej 10Aug2023--------------------------------------------------------------
alter table if exists "Appointment"
add column if not exists "IsHealthCard" boolean;

DROP FUNCTION IF EXISTS public."udf_uiReport_fetch_Appointments_Location1"(integer, text, integer[], integer[], integer[], text, integer[], text, text, integer, date, date, integer[], boolean, text[], integer, integer);

CREATE OR REPLACE FUNCTION public."udf_uiReport_fetch_Appointments_Location1"(
	locationid integer DEFAULT NULL::integer,
	"appointmentNo" text DEFAULT NULL::text,
	"departmentId" integer[] DEFAULT NULL::integer[],
	"providerId" integer[] DEFAULT NULL::integer[],
	"patientId" integer[] DEFAULT NULL::integer[],
	"uMRNo" text DEFAULT NULL::text,
	"patientReferredById" integer[] DEFAULT NULL::integer[],
	"referredByName" text DEFAULT NULL::text,
	mobile text DEFAULT NULL::text,
	"payTypeId" integer DEFAULT NULL::integer,
	"fromDate" date DEFAULT NULL::date,
	"toDate" date DEFAULT NULL::date,
	"appointmentTypeId" integer[] DEFAULT NULL::integer[],
	"paymentStatus" boolean DEFAULT NULL::boolean,
	status text[] DEFAULT NULL::text[],
	"pageIndex" integer DEFAULT 0,
	"pageSize" integer DEFAULT 10)
    RETURNS TABLE("DepartmentId" text, "DepartmentName" character varying, "ProviderId" text, "ProviderName" character varying, "AppointmentTypeName" character varying, "AppointmentDate" date, "AppointmentNo" character varying, "PatientId" integer, "Name" character varying, "ReferredByName" character varying, "PatientName" character varying, "PatientAge" smallint, "UMRNo" character varying, "Mobile" character varying, "PatientGender" character, "AppointmentTime" time without time zone, "VisitType" character, "PaymentType" character varying, "PaymentNumber" character varying, "TotalAppointments" bigint, "TotalAmount" bigint, "TotalAmountStr" text, "ReceiptCreatedByName" text, "ReceiptDate" timestamp without time zone, "ReceiptId" integer, "StreetAdress" character varying, "City" character varying, "State" character varying, "FatherOrHusband" text, "PaymentStatus" boolean, "EncounterType" encountertype_elements, "Status" text, "TypeOfPayment" character, "IsHealthCard" boolean) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
BEGIN

return query 

with cts as (select coalesce(A."DepartmentId"::text,'GrandTotal') "DepartmentId",
			 A."ProviderId"::text as "ProviderId", 
			 A."AppointmentDate",A."AppointmentTypeId",
			ATN."Name" "AppointmentTypeName",
			 A."AppointmentNo",A."PatientId" "PatientId",PRB."Name",Pa."ReferredByName",
			 Pa."FullName",Pa."UMRNo",Pa."Mobile",A."AppointmentTime",A."VisitType",
			 case when ATN."Name"='Follow Up' and sum(A."Total")=0 then 'Free Follow Up'
			 else PT."PayTypeName" end as "PaymentType" ,A."PaymentNumber",
			 A."AppointmentId",
			 case when A."Status"='B' then 'Booked' when A."Status"='R' then 'Rescheduled' when A."Status"='C' then 'Cancel' end::text as "Status",
			 COUNT(A."AppointmentNo") as "TotalAppointments" ,sum(R."Cost")::text as "TotalAmountStr" ,
			 sum(R."Cost")::bigint as "TotalAmount" ,
			 Pa."FatherOrHusband",
			 A."PaymentStatus",
			 A."EncounterType",
			 A."PaymentType" as "TypeOfPayment",R."ReceiptId",A."IsHealthCard"
			 from "Appointment" A
 			left join "Patient" Pa on Pa."PatientId"::text=A."PatientId"::text
			 
			 left join "PatientReferredBy" PRB on PRB."PatientReferredById"::text=Pa."PatientReferredById"::text			
		left join "AppointmentType" ATN on A."AppointmentTypeId"=ATN."AppointmentTypeId"
			 left Join "Receipt" R on R."RespectiveId"=A."AppointmentId"  and R."ReceiptAreaTypeId"=4
			  left join "PayType" PT on PT."PayTypeId"=R."PayTypeId"
where 
			 --A."Status"<>'C' and 
case when "departmentId" is null then 1=1 else  A."DepartmentId"  = any("departmentId") end and 
CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE A."LocationId"=locationId END and
case when "patientId" is null then 1=1 else  Pa."PatientId"  = any("patientId") end and 
case when "appointmentNo" is null then 1=1 when "appointmentNo" ='' then 1=1 else A."AppointmentNo" ilike'%'||"appointmentNo" ||'%' end  and
case when "providerId" is null then 1=1 else  A."ProviderId"  = any("providerId") end and 
case when "uMRNo" is null then 1=1 when "uMRNo" ='' then 1=1 else Pa."UMRNo" ilike'%'||"uMRNo" ||'%' end  and
case when "patientReferredById" is null then 1=1 else  Pa."PatientReferredById"  = any("patientReferredById") end and 
case when "appointmentTypeId" is null then 1=1 else  ATN."AppointmentTypeId"  = any("appointmentTypeId") end and 
case when "referredByName" is null then 1=1 when "referredByName" ='' then 1=1 else Pa."ReferredByName" ilike'%'||"referredByName" ||'%' end and 
case when "mobile" is null then 1=1 when "mobile" ='' then 1=1 else Pa."Mobile" ilike'%'||"mobile" ||'%' end  and
case when "payTypeId" is null then 1=1  else A."PayTypeId" ="payTypeId" end  and
case when "fromDate" is null then 1=1 else "fromDate" <=A."AppointmentDate" and A."AppointmentDate" <="toDate" end and
case when "paymentStatus" is null then 1=1  else A."PaymentStatus" ="paymentStatus" end			 
and case when "status" is null then 1=1 else  A."Status"  =any("status") end	
			 
GROUP BY GROUPING SETS((A."DepartmentId",A."ProviderId",A."PatientId",PRB."Name",
						Pa."ReferredByName",Pa."FullName",Pa."UMRNo",Pa."Mobile",A."AppointmentDate",A."AppointmentTime",
						A."AppointmentNo",A."AppointmentTypeId",
						ATN."Name" ,
						A."VisitType",
						PT."PayTypeName",A."PaymentNumber",
						A."AppointmentId",R."ReceiptId",
						A."Status",Pa."FatherOrHusband",A."PaymentStatus",A."EncounterType",A."PaymentType",A."IsHealthCard"), (A."DepartmentId",A."ProviderId"), ())     
order by A."AppointmentId")

select A."DepartmentId",coalesce(D."DepartmentName",'GrandTotal') "DepartmentName",
case when A."AppointmentNo" is null then 'Total'  else A."ProviderId" end "ProviderId",
case when A."AppointmentNo" is null  then 'Total'  else  Pr."FullName"  end  as "ProviderName",
 ATN."Name" "AppointmentTypeName",
A."AppointmentDate",
A."AppointmentNo",A."PatientId",
case when A."AppointmentNo" is null  then null else PRB."Name"::varchar end as "Name",
case when A."AppointmentNo" is null  then null else Pa."ReferredByName"::varchar end as "ReferredByName",
case when A."AppointmentNo" is null  then null else Pa."FullName"::varchar end as "PatientName",
case when A."AppointmentNo" is null  then null else Pa."Age" end  "PatientAge",
case when A."AppointmentNo" is null  then null else Pa."UMRNo" end  "UMRNo",
case when A."AppointmentNo" is null  then null else Pa."Mobile" end  "Mobile",
case when A."AppointmentNo" is null  then null else Pa."Gender" end "PatientGender",
A."AppointmentTime",
A."VisitType",A."PaymentType",A."PaymentNumber",A."TotalAppointments",A."TotalAmount",A."TotalAmountStr",
 CA."FullName"  "ReceiptCreatedByName", R."CreatedDate" "ReceiptDate",R."ReceiptId",
 case when A."AppointmentNo" is null  then null else Pa."StreetAddress" end "StreetAddress",
case when A."AppointmentNo" is null  then null else Pa."City" end "City",
case when A."AppointmentNo" is null  then null else Pa."State" end "State",
A."FatherOrHusband",
A."PaymentStatus",A."EncounterType",A."Status",A."TypeOfPayment",A."IsHealthCard"
from cts A
left join "Department" D on A."DepartmentId"=D."DepartmentId"::text
left join "Provider" Pr on Pr."ProviderId"::text=A."ProviderId"
left join "Patient" Pa on Pa."PatientId"::text=A."PatientId"::text
left Join "Receipt" R on R."RespectiveId"=A."AppointmentId"  and R."ReceiptAreaTypeId"=4 and R."ReceiptId"=A."ReceiptId"
Left Join "Account" CA on CA."AccountId"=R."CreatedBy"
left join "PatientReferredBy" PRB on PRB."PatientReferredById"::text=Pa."PatientReferredById"::text
 left join  "AppointmentType" ATN on ATN."AppointmentTypeId"=A."AppointmentTypeId"
order by A."AppointmentId"
 ;

END

$BODY$;


--------------------------------------------------------------------------------------JayShree 10Aug2023--------------------------------------------------------------
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")
);


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

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

----------------------------------------------------------------------------------------JayShree 10Aug2023-----------------------------------------------------------

DO $$                  
    BEGIN 
        IF EXISTS
            ( SELECT 1
              FROM   information_schema.tables 
              WHERE  table_schema = 'public'
              AND    table_name = 'Menu'
            )
        THEN
            UPDATE "Menu"
            SET "EncounterKey" = 'mChat' 
            where "Url" ilike '%/app/pediatric-encounter/:id/:type/m-chart%';
        END IF ;
    END
   $$ ;

DO $$                  
    BEGIN 
        IF EXISTS
            ( SELECT 1
              FROM   information_schema.tables 
              WHERE  table_schema = 'public'
              AND    table_name = 'Menu'
            )
        THEN
            UPDATE "Menu"
            SET "EncounterKey" = 'birthHistory' 
            where "Url" ilike '%/app/pediatric-encounter/:id/:type/ob-birthhistory%';
        END IF ;
    END
   $$ ;

DO $$                  
    BEGIN 
        IF EXISTS
            ( SELECT 1
              FROM   information_schema.tables 
              WHERE  table_schema = 'public'
              AND    table_name = 'Menu'
            )
        THEN
            UPDATE "Menu"
            SET "EncounterKey" = 'familyHistory' 
            where "Url" ilike '%/app/pediatric-encounter/:id/:type/family-history%';
        END IF ;
    END
   $$ ;

DO $$                  
    BEGIN 
        IF EXISTS
            ( SELECT 1
              FROM   information_schema.tables 
              WHERE  table_schema = 'public'
              AND    table_name = 'Menu'
            )
        THEN
            UPDATE "Menu"
            SET "EncounterKey" = 'specialFeatures' 
            where "Url" ilike '%/app/pediatric-encounter/:id/:type/special-feature%';
        END IF ;
    END
   $$ ;

----------------------------------------------------------------------------Sravani 14Aug2023--------------------------------------------------------------------------
alter table IF EXISTS "SaleReturnDetail"
add column IF NOT EXISTS "PayTypeId" integer,
add column IF NOT EXISTS "PaymentNumber" character varying(50);

alter table "SaleReturnDetail"
DROP CONSTRAINT IF EXISTS "SaleReturnDetail_PayTypeId_fkey",
add CONSTRAINT "SaleReturnDetail_PayTypeId_fkey" FOREIGN KEY ("PayTypeId") 
REFERENCES public."PayType" ("PayTypeId") MATCH SIMPLE;

----------------------------------------------------------------------------Radhika 16Aug2023--------------------------------------------------------------------------
alter table IF EXISTS "ReferralForm"
add column IF NOT EXISTS "AdmissionId" integer;

----------------------------------------------------------------------------Chandana 16Aug2023--------------------------------------------------------------------------
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,"PatientPriorityId" 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."PatientPriorityId",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$;
-------------------------------------------------------------------------------------Chandana 17Aug2023--------------------------------------------------------------
--alter table IF EXISTS "AdmissionPackage" 
--add IF NOT EXISTS "CounselingId" integer references "Counseling"("CounselingId");


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,"Breakfast" time without time zone,"Lunch" time without time zone,"Dinner" time without time zone,"PatientPriorityId" 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"
	left join "PatientTiming" pt on pt."PatientId"=A."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",pt."Breakfast",pt."Lunch",pt."Dinner",A."PatientPriorityId",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"
	left join "PatientTiming" pt on pt."PatientId"=A."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",pt."Breakfast",pt."Lunch",pt."Dinner",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$;

---------------------------------------------------------------------------Manish 17Aug2023-------------------------------------------------------------------------

create table if not exists vendors."SupplierProductHeader"(
						"SupplierProductHeaderId" serial primary key,
						"SupplierId" int references "Supplier"("SupplierId"),
						"StartDate" timestamp without time zone,
						"EndDate" timestamp without time zone,
						"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 vendors."SupplierProductFormulation"(
				"SupplierProductFormulationId" serial primary key,
				"SupplierProductHeaderId" int references vendors."SupplierProductHeader"("SupplierProductHeaderId"), 
				"Operator" varchar(50),
				"Condition" varchar(50),
				"FOCQuantity" int 
);


CREATE TABLE if not exists vendors."SupplierProductDetail" (
	"SupplierProductDetailId" serial primary key,
	"SupplierProductHeaderId" int ,
	"PharmacyProductId" int ,
	"PurchaseRate" numeric ,
	"Mrp" numeric 
);

ALTER TABLE if exists vendors."SupplierProductDetail" 
 DROP CONSTRAINT IF EXISTS "SupplierProductDetail_PharmacyProductId_fkey",
ADD CONSTRAINT "SupplierProductDetail_PharmacyProductId_fkey" FOREIGN KEY ("PharmacyProductId") REFERENCES public."PharmacyProduct"("PharmacyProductId");
ALTER TABLE if exists vendors."SupplierProductDetail" 
DROP CONSTRAINT IF EXISTS "SupplierProductDetail_SupplierProductHeaderId_fkey",
ADD CONSTRAINT "SupplierProductDetail_SupplierProductHeaderId_fkey" FOREIGN KEY ("SupplierProductHeaderId") REFERENCES vendors."SupplierProductHeader"("SupplierProductHeaderId");

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


alter table if exists vendors."PurchaseOrderDetail" 
add column if not exists "Free" int;

-------------------------------------------------------------------Kalyan 17Aug2023-------------------------------------------------------------------------------
INSERT INTO public."LabBookingStatus"("Status","Active")
SELECT 'SampleUncollected',true
WHERE
NOT EXISTS (
SELECT "Status" FROM public."LabBookingStatus" WHERE "Status" = 'SampleUncollected'
);

INSERT INTO public."LabLogType"("LabLogTypeId","LogTypeName","Active")
SELECT 17,'Lab_Sample_Uncollection',true
WHERE
NOT EXISTS (
SELECT "LogTypeName" FROM public."LabLogType" WHERE "LogTypeName" = 'Lab_Sample_Uncollection'
);

alter table if exists "LabSampleCollection"
add column if not exists "ConsentFormUrl" text COLLATE pg_catalog."default",
add column if not exists "UploadedBy" integer,
add column if not exists "UploadedDate" timestamp without time zone,
DROP CONSTRAINT IF EXISTS "LabSampleCollection_UploadedBy_fkey",
add CONSTRAINT "LabSampleCollection_UploadedBy_fkey" FOREIGN KEY ("UploadedBy") 
REFERENCES public."Account" ("AccountId") MATCH SIMPLE;

INSERT INTO public."LabBookingStatus"("Status","Active")
SELECT 'ConsentFormUploaded',true
WHERE
NOT EXISTS (
SELECT "Status" FROM public."LabBookingStatus" WHERE "Status" = 'ConsentFormUploaded'
);

INSERT INTO public."LabLogType"("LabLogTypeId","LogTypeName","Active")
SELECT 18,'Lab_Sample_ConsentForm',true
WHERE
NOT EXISTS (
SELECT "LogTypeName" FROM public."LabLogType" WHERE "LogTypeName" = 'Lab_Sample_ConsentForm'
);
-----------------------------------------------------------------------JayShree 18Aug2023--------------------------------------------------------------------

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

CREATE OR REPLACE FUNCTION public."udf_DailySalesReportByMedication"(
	"productName" text DEFAULT NULL::text,
	"genericName" text DEFAULT NULL::text,
	"categoryName" text DEFAULT NULL::text,
	"companyName" text DEFAULT NULL::text,
	"supplierName" text DEFAULT NULL::text,
	"payTypeId" integer DEFAULT NULL::integer,
	"fromDate" date DEFAULT NULL::date,
	"toDate" date DEFAULT NULL::date,
	"locationId" integer DEFAULT NULL::integer)
    RETURNS TABLE("PharmacySaleHeaderId" integer, "PharmacyProductId" integer, "ProductName" character varying, "BatchNumber" character varying, "GenericName" text, "CategoryName" character varying, "CompanyName" text, "SupplierName" text, "SaleQuantity" bigint, "Mrp" numeric, "Discount" numeric, "TotalAmount" numeric, "PaidVia" character varying, "PaymentNumber" character varying, "SaleDate" timestamp without time zone, "PurchaseValue" numeric, "PurchaseUnitQty" integer, "LocationName" character varying, "OverallNetAmount" numeric) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
Declare 
BEGIN
return query 

select A."PharmacySaleHeaderId",
A."PharmacyProductId",A."ProductName",A."BatchNumber",A."GenericName",A."CategoryName ",A."CompanyName"
,A."SupplierName"
,sum(A."Quantity") "SaleQuantity",A."Mrp",A."Discount",sum(A."NetAmount") "TotalAmount"
,A."PaidVia",A."PaymentNumber",A."SaleDate" , TRUNC((A."PPD_NetAmount"/A."PPD_Quantity"),2)  as "PurchaseValue"
,A."PurchaseUnitQty",A."LocationName",A."OverallNetAmount"
from (
	select PH."PharmacySaleHeaderId",
	PS."PharmacyProductId",PP."ProductName",PRS."BatchNumber",pp."GenericName",ci."Name" "CategoryName ",c."Name" "CompanyName",s."Name" "SupplierName"
	,PH."SaleDate",PS."Quantity",PRS."Mrp",PS."Discount",PS."NetAmount" , PT."PayTypeName" as "PaidVia", PH."PaymentNumber",
	  ppd."NetAmount" as "PPD_NetAmount",ppd."Quantity" as "PPD_Quantity",L."Name" as "LocationName"
	,pp."PurchaseUnitQty",PH."OverallNetAmount"
	from
	"PharmacySaleHeader" PH
	join "PharmacySaleDetail" PS on PH."PharmacySaleHeaderId"=PS."PharmacySaleHeaderId"
	join "PharmacyProduct" pp on PS."PharmacyProductId"=PP."PharmacyProductId"
	join "Company" c on c."CompanyId"=PP."CompanyId"
	join "LookupValue" ci on ci."LookupValueId"=pp."CategoryId"
	join "PharmacyRetailStock" PRS on   PRS."PharmacyRetailStockId"=PS."PharmacyRetailStockId" and PRS."PharmacyProductId"=PP."PharmacyProductId"
	left join "PharmacyPurchaseDetail" Ppd on  ppd."PharmacyStockId"=prs."PharmacyStockId" and  ppd."PharmacyProductId"=PRS."PharmacyProductId"
	left join "PharmacyPurchaseHeader" pph on pph."PharmacyPurchaseHeaderId"=Ppd."PharmacyPurchaseHeaderId"
	left join "Supplier" s on s."SupplierId"=pph."SupplierId" 
	join "Location" L on L."LocationId" = PH."LocationId"	
	left join "PayType" PT on PT."PayTypeId"=PH."PayTypeId"	
	where
	case when "productName" ='' then 1=1   when "productName" is null then 1=1  else PP."ProductName" ilike  '%'||"productName"||'%' end and 
	case when "genericName" ='' then 1=1  when "genericName" is null then 1=1  else pp."GenericName" ilike  '%'||"genericName"||'%' end and 
  case when "categoryName" ='' then 1=1  when "categoryName" is null then 1=1  else ci."Name" ilike  '%'||"categoryName"||'%' end and 
	case when "companyName" ='' then 1=1  when "companyName" is null then 1=1  else c."Name" ilike  '%'||"companyName"||'%' end and 
  case when "supplierName" ='' then 1=1  when "supplierName" is null then 1=1  else s."Name" ilike  '%'||"supplierName"||'%' 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" ::date <=PH."SaleDate"::date and PH."SaleDate"::date <="toDate" ::date end and
	case when "locationId" is null then 1=1 else PH."LocationId" = "locationId"::int end
	group by PH."PharmacySaleHeaderId",
	PS."PharmacyProductId",PP."ProductName",PRS."BatchNumber",PH."SaleDate"
	,pp."GenericName",ci."Name",c."Name" ,s."Name" ,PS."Quantity",PS."NetAmount",PRS."Mrp",PS."Discount" ,PT."PayTypeName" , PH."PaymentNumber",
 	ppd."NetAmount", ppd."Quantity",pp."PurchaseUnitQty",L."Name",PH."OverallNetAmount"
) A
	
group by A."PharmacySaleHeaderId", A."PharmacyProductId",A."ProductName",A."BatchNumber",A."GenericName",A."CategoryName ",
A."CompanyName",A."SupplierName",A."Mrp",A."Discount",A."PaidVia",A."PaymentNumber",A."SaleDate", (A."PPD_NetAmount"/A."PPD_Quantity") , A."PurchaseUnitQty",
A."LocationName",A."OverallNetAmount"
order  by A."ProductName"
;

END
$BODY$;
-----------------------------------------------------------------------Chandana 21Aug2023--------------------------------------------------------------------

 DROP FUNCTION IF EXISTS public."udf_uiReport_Receipts_Appointments_Location1"(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_Location1"(
	"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,  "IsHealthCard" boolean,
		  "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'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
BEGIN

return query 

select coalesce(A."FullName",'GrandTotal') "ReceiptCreatedBy",A."RoleName",A."IsHealthCard",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",Ad."IsHealthCard",
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."IsHealthCard"
						,A."AppointmentTime",A."PatientName",A."UMRNo",A."Mobile",A."ProviderName",A."AppointmentId",
						A."IsAppointmentReceipt"), (A."FullName"), ())     
order by A."FullName" 
 ;

END
$BODY$;

-------------------------------------------------------------------Tej 21Aug2023-----------------------------------------------------------------------------
CREATE SEQUENCE IF NOT EXISTS public."SurgeryService_Seq"
    INCREMENT 1
    START 1
    MINVALUE 1
    MAXVALUE 9223372036854775807
    CACHE 1;

CREATE TABLE IF NOT EXISTS public."SurgeryService"
(
    "SurgeryServiceId" integer NOT NULL DEFAULT nextval('"SurgeryService_Seq"'::regclass),
	"SurgeryId" integer,
    "AdmissionId" integer,
    "CreatedDate" timestamp without time zone,
    "CreatedBy" integer,
    "ChargeId" integer,
    "Unit" integer,
    "Cost" numeric(10,2),
    "Active" boolean,
    "ModifiedDate" timestamp without time zone,
    "ModifiedBy" integer,
    "IsMain" boolean DEFAULT false,
    "Notes" text COLLATE pg_catalog."default",
    "ChargeTypeId" integer,
    "ChargeTypeMainId" integer,
    "AppointmentId" integer,
    "AdmissionPackageId" integer,
    "PackageModuleDetailId" integer,
    "UsedQuantity" integer,
    "UsedCost" numeric(10,2),
    CONSTRAINT "SurgeryService_pkey" PRIMARY KEY ("SurgeryServiceId"),	
    CONSTRAINT "FK_SurgeryService_SurgeryId" FOREIGN KEY ("SurgeryId")
        REFERENCES public."Surgery" ("SurgeryId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_SurgeryService_AdmissionId" FOREIGN KEY ("AdmissionId")
        REFERENCES public."Admission" ("AdmissionId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_SurgeryService_AdmissionPackageId" FOREIGN KEY ("AdmissionPackageId")
        REFERENCES public."AdmissionPackage" ("AdmissionPackageId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
        NOT VALID,
    CONSTRAINT "FK_SurgeryService_AppointmentId" FOREIGN KEY ("AppointmentId")
        REFERENCES public."Appointment" ("AppointmentId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_SurgeryService_ChargeId" FOREIGN KEY ("ChargeId")
        REFERENCES public."Charge" ("ChargeId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_SurgeryService_ChargeTypeId" FOREIGN KEY ("ChargeTypeId")
        REFERENCES public."ChargeType" ("ChargeTypeId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_SurgeryService_CreatedBy" FOREIGN KEY ("CreatedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_SurgeryService_ModifiedBy" FOREIGN KEY ("ModifiedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_SurgeryService_PackageModuleDetailId" FOREIGN KEY ("PackageModuleDetailId")
        REFERENCES public."PackageModuleDetail" ("PackageModuleDetailId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
        NOT VALID
);

----------------------------------------------------------------------mounika 21Aug2023----------------------------------------------------------------------
UPDATE "OrderPrescriptionMaster"
SET "Name"= 'Other Medicine'
WHERE "OrderPrescriptionMasterId"=(select "OrderPrescriptionMasterId" from "OrderPrescriptionMaster" WHERE "Name"='Other Medcine');

UPDATE "OrderPrescriptionMaster"
SET "Name"= 'Referred for Admission'
WHERE "OrderPrescriptionMasterId"=(select "OrderPrescriptionMasterId" from "OrderPrescriptionMaster" WHERE "Name"='Reffered For Admission');
DO $$                  
    BEGIN 
        IF EXISTS
            ( SELECT 1
              FROM   information_schema.tables 
              WHERE  table_schema = 'public'
              AND    table_name = 'OrderPrescriptionMaster'
            )
        THEN
            UPDATE "OrderPrescriptionMaster"
            SET "Name"= 'Other Medicine' 
            WHERE "OrderPrescriptionMasterId"=(select "OrderPrescriptionMasterId" from "OrderPrescriptionMaster" WHERE "Name"='Other Medcine');
        END IF ;
    END
   $$ ;
DO $$                  
    BEGIN 
        IF EXISTS
            ( SELECT 1
              FROM   information_schema.tables 
              WHERE  table_schema = 'public'
              AND    table_name = 'OrderPrescriptionMaster'
            )
        THEN
            UPDATE "OrderPrescriptionMaster"
            SET "Name"= 'Referred for Admission' 
            WHERE "OrderPrescriptionMasterId"=(select "OrderPrescriptionMasterId" from "OrderPrescriptionMaster" WHERE "Name"='Reffered For Admission');
        END IF ;
    END
   $$ ;
----------------------------------------------------------------------Manish 21Aug2023----------------------------------------------------------------------

create table if not exists vendors."IncomingQuotationHeader"(
				"IncomingQuotationHeaderId" bigserial primary key,
				 "ProductForQuotationHeaderId" bigint references vendors."ProductForQuotationHeader",
				 "SupplierId" int references public."Supplier"("SupplierId"),
				 "CreatedBy" int references "Account"("AccountId"),
				 "CreatedDate" timestamp without time zone,
				 "ModifiedBy" int references "Account"("AccountId"),
				 "ModifiedDate" timestamp without time zone,
				 "IsFinalized" boolean default false,
				 "FinalizedBy" int references "Account"("AccountId"),
				 "FinalizedDate" timestamp without time zone,
				 "DeliveryDate" date,
				 "TotalAmount" numeric,
				 "TotalTax" numeric,
				 "TotalNetAmount" numeric,
				 "TotalDiscount" numeric
);

create table if not exists vendors."IncomingQuotationDetail"(
					"IncomingQuotationDetailId" bigserial primary key,
					"PharmacyProductApprovalId" bigint references vendors."PharmacyProductApproval"("PharmacyProductApprovalId"),
					"IncomingQuotationHeaderId" bigint references vendors."IncomingQuotationHeader"("IncomingQuotationHeaderId"),
					"ProductForQuotationDetailId" bigint references vendors."ProductForQuotationDetail"("ProductForQuotationDetailId"),
					"PharmacyProductId" int references public."PharmacyProduct"("PharmacyProductId"),
					"Tax" int,
					"PurchaseRate" numeric,
					"MRP" numeric,
					"Amount" numeric,
					"TaxAmount" numeric,
					"DiscountPercentage" numeric,
					"DiscountAmount" numeric,
					"NetAmount" numeric,
					"Quantity" int,
					"Free" int					
);

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

--------------------------------------------------------------------Tej 22Aug2023----------------------------------------------------------------------------------

CREATE SEQUENCE IF NOT EXISTS public."SurgeryService_Seq"
    INCREMENT 1
    START 1
    MINVALUE 1
    MAXVALUE 9223372036854775807
    CACHE 1;


CREATE TABLE IF NOT EXISTS public."SurgeryService"
(
    "SurgeryServiceId" integer NOT NULL DEFAULT nextval('"SurgeryService_Seq"'::regclass),
	"SurgeryId" integer,
    "AdmissionId" integer,
    "CreatedDate" timestamp without time zone,
    "CreatedBy" integer,
    "Unit" integer,
    "Cost" numeric(10,2),
    "Active" boolean,
    "ModifiedDate" timestamp without time zone,
    "ModifiedBy" integer,
    "IsMain" boolean DEFAULT false,
    "Notes" text COLLATE pg_catalog."default",
    "ChargeCategoryId" integer,
    "AppointmentId" integer,
    "AdmissionPackageId" integer,
    "PackageModuleDetailId" integer,
    "UsedQuantity" integer,
    "UsedCost" numeric(10,2),
    CONSTRAINT "SurgeryService_pkey" PRIMARY KEY ("SurgeryServiceId"),	
    CONSTRAINT "FK_SurgeryService_SurgeryId" FOREIGN KEY ("SurgeryId")
        REFERENCES public."Surgery" ("SurgeryId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_SurgeryService_AdmissionId" FOREIGN KEY ("AdmissionId")
        REFERENCES public."Admission" ("AdmissionId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_SurgeryService_AdmissionPackageId" FOREIGN KEY ("AdmissionPackageId")
        REFERENCES public."AdmissionPackage" ("AdmissionPackageId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
        NOT VALID,
    CONSTRAINT "FK_SurgeryService_AppointmentId" FOREIGN KEY ("AppointmentId")
        REFERENCES public."Appointment" ("AppointmentId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_SurgeryService_ChargeCategoryId" FOREIGN KEY ("ChargeCategoryId")
        REFERENCES public."ChargeCategory" ("ChargeCategoryId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_SurgeryService_CreatedBy" FOREIGN KEY ("CreatedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_SurgeryService_ModifiedBy" FOREIGN KEY ("ModifiedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_SurgeryService_PackageModuleDetailId" FOREIGN KEY ("PackageModuleDetailId")
        REFERENCES public."PackageModuleDetail" ("PackageModuleDetailId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
        NOT VALID
);

--------------------------------------------------------------------Chaandana 22Aug 2023-------------------------------------------------------
alter table if exists "Admission" 
add column if not exists "CounsellingId" integer references "Counselling"("CounsellingId");


-----------------------------------------------------------------------Sravani 24Aug2023------------------------------------------------------------------
ALTER TABLE "BookScanAppointment" 
ADD COLUMN if not exists "BookedStatus" text;

-----------------------------------------------------------------------Mounika A  24Aug2023------------------------------------------------------------------
 DO $$
BEGIN
  IF EXISTS(SELECT *
    FROM information_schema.columns
    WHERE table_name='PediatricEncounter' and column_name='OrdersPrescription')
  THEN
      ALTER TABLE "public"."PediatricEncounter" RENAME COLUMN "OrdersPrescription" TO "OrderPrescription";
  END IF;
END $$;
--------------------------------------------------------------------------------Radhika 24Aug2023------------------------------------------------------------
DROP FUNCTION if exists public."udf_NurseNoteReport"(integer);

CREATE OR REPLACE FUNCTION public."udf_NurseNoteReport"(
	"admissionId" integer DEFAULT NULL::integer)
    RETURNS TABLE("CreatedDate" timestamp without time zone, "BedId" integer,"AdmissionNo" text,"Note" text, "UMRNo" character varying, "FullName" text, "CreatedByName" text, "BedNumber" character varying) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
BEGIN

return query
select (NN."CreatedDate":: timestamp without time zone),Adm."BedId",Adm."AdmissionNo" ,NN."Note",Pat."UMRNo",Pat."FullName",
Acc."FullName" as NurseName,bd."BedNumber"

                            from "NurseNote" NN
                             join "Admission" Adm on Adm."AdmissionId" = NN."AdmissionId"

                             join "Patient" pat on Pat."PatientId" = Adm."PatientId"

                             join "Account" Acc on Acc."AccountId" = NN."CreatedBy"

                             join "Bed" bd on bd."BedId" = Adm."BedId"
							where case when "admissionId"is null then 1=1 else  NN."AdmissionId"="admissionId" end 
							
							 group by NN."CreatedDate", Adm."BedId",Adm."AdmissionNo" ,NN."Note",Pat."UMRNo",Pat."FullName",Acc."FullName" ,bd."BedNumber";
							 
            
END
$BODY$;

------------------------------------------------------------------Sravani 24Aug2023---------------------------------------------------------------------
INSERT INTO public."LogType"("LogTypeId","LogTypeName","Active")
SELECT 82,'DiscountManagement',true
WHERE
NOT EXISTS (
SELECT "LogTypeName" FROM public."LogType" WHERE "LogTypeName" = 'DiscountManagement'
);
INSERT INTO public."LogType"("LogTypeId","LogTypeName","Active")
SELECT 83,'AppointmentTypes',true
WHERE
NOT EXISTS (
SELECT "LogTypeName" FROM public."LogType" WHERE "LogTypeName" = 'AppointmentTypes'
);
INSERT INTO public."LogType"("LogTypeId","LogTypeName","Active")
SELECT 84,'DietGuidelines',true
WHERE
NOT EXISTS (
SELECT "LogTypeName" FROM public."LogType" WHERE "LogTypeName" = 'DietGuidelines'
);

------------------------------------------------------------------Shiva 24Aug2023---------------------------------------------------------------------
 DROP FUNCTION IF EXISTS public.udf_pharmacypatientbills_finalreport(text, integer, integer, character varying, character varying, integer, integer, integer, timestamp without time zone, timestamp without time zone, text, integer, text, boolean);

CREATE OR REPLACE FUNCTION public.udf_pharmacypatientbills_finalreport(
	"billNumber" text DEFAULT NULL::text,
	"accountId" integer DEFAULT NULL::integer,
	"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,
	"pharmacyBillType" boolean DEFAULT NULL::boolean)
    RETURNS TABLE("PharmacySaleHeaderId" integer, "BillNumber" character varying, "PaidVia" character varying, "PaymentNumber" character varying, "SaleDate" timestamp without time zone, "PatientName" character varying, "PatientMobile" character varying, "UMRNo" character varying, "ProviderName" character varying, "CreatedByName" text, "RoleName" character varying, "TotalAmount" numeric, "SaleReturnHeaderId" integer, "OverallTaxes" numeric, "RetailName" text, "typeOfPayment" character, "ReceiptDate" timestamp without time zone) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$

BEGIN

return query

select PH."PharmacySaleHeaderId" ,PH."BillNumber",PH."PaidVia",PH."PaymentNumber",PH."SaleDate" "SaleDate",PH."PatientName",
PH."Mobile" ,Ph."UMRNo",PH."ProviderName",ph."CreatedByName",
ph."Role", PH."OverallNetAmount",PH."SaleReturnHeaderId" ,PH."OverallTaxes",PH."RetailName",PH."PaymentStatus",PH."ReceiptDate"
from 
(
select PH."PharmacySaleHeaderId" ,PH."BillNumber",PT."PayTypeName" as "PaidVia",PH."PaymentNumber",PH."CreatedDate" "SaleDate",
	PH."PatientName",PH."Mobile" ,Pa."UMRNo",PH."ProviderName",A."FullName" 
"CreatedByName",R."RoleName" "Role" ,
	 RC."Cost" as "OverallNetAmount",true "PharmacyBillType",null "SaleReturnHeaderId",PH."OverallTaxes",
	RP."RetailName",  PH."PaymentType" as "PaymentStatus",RC."CreatedDate" "ReceiptDate"
from "PharmacySaleHeader" PH
	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"
left join "Patient" Pa on Pa."PatientId"::text=PH."PatientId"::text
	left Join "Receipt" RC on RC."RespectiveId"=PH."PharmacySaleHeaderId" and "ReceiptAreaTypeId"=1 and "ReceiptTypeId"=1
	 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 "accountId" is null then 1=1 else PH."CreatedBy"="accountId" 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 "fromDate"<= RC."CreatedDate"  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",PT."PayTypeName", PH."PaymentNumber",PH."SaleDate", PH."OverallNetAmount",
	PH."PatientName",PH."ProviderName",Pa."UMRNo",A."FullName" 
,R."RoleName",RP."RetailName",RC."Cost",PH."PaymentType",RC."CreatedDate"
union 
	
select PH."PharmacySaleHeaderId" ,PH."BillNumber",PT."PayTypeName" as "PaidVia",PH."PaymentNumber",srh."ReturnDate" "SaleDate",PH."PatientName",
	Ph."Mobile" ,Pa."UMRNo",PH."ProviderName",A."FullName" 
"CreatedByName",R."RoleName" "Role", -RC."Cost" "TotalAmount",false "PharmacyBillType"
,srh."SaleReturnHeaderId",srh."OverallTaxes",
	RP."RetailName", srh."BillType"::character as "PaymentStatus",RC."CreatedDate" "ReceiptDate"
	from "SaleReturnHeader" srh
Join "PharmacySaleHeader" ph on ph."PharmacySaleHeaderId"= srh."PharmacySaleHeaderId"
	join "Account" A on A."AccountId"=srh."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"
left join "Patient" Pa on Pa."PatientId"::text=PH."PatientId"::text
	left Join "Receipt" RC on RC."RespectiveId"=srh."SaleReturnHeaderId" and "ReceiptAreaTypeId"=7 and "ReceiptTypeId"=2
	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 "accountId" is null then 1=1 else srh."CreatedBy"="accountId" 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",PT."PayTypeName", PH."PaymentNumber",srh."ReturnDate", srh."OverallNetAmount",
	PH."PatientName",Pa."Mobile",Pa."UMRNo",PH."ProviderName",A."FullName" 
,R."RoleName",srh."SaleReturnHeaderId", RP."RetailName",srh."BillType",RC."CreatedDate",RC."Cost"
) 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."ReceiptDate" desc;
END

$BODY$;
------------------------------------------------------------------------------Manish 24Aug2023-----------------------------------------------------------------------
alter table if exists public."PharmacyProduct" 
add column if not exists "InventoryItem" boolean default false;

create table if not exists public."PharmacyInPatientReturn"(
			"PharmacyInPatientReturnId" bigserial primary key,
			"PharmacyIssueDetailId" int references "PharmacyIssueDetail"("PharmacyIssueDetailId"),
			"ReturnQuantity" int,
			"CreatedBy" int references "Account"("AccountId"),
			"CreatedDate" timestamp without time zone,
			"AcceptedBy" int references "Account"("AccountId"),
			"AcceptedDate" timestamp without time zone
);


alter table if exists "PharmacyIssueDetail" 
add column if not exists "PharmacyIndentDetailId" int references "PharmacyIndentDetail"("PharmacyIndentDetailId");
--------------------------------------------------------------------------Mounika A 24Aug2023---------------------------------------------------------------------
DO $$                  
    BEGIN 
        IF EXISTS
            ( SELECT 1
              FROM   information_schema.tables 
              WHERE  table_schema = 'public'
              AND    table_name = 'Menu'
            )
        THEN
            UPDATE "Menu"
            SET "EncounterKey" = 'guideDietLines' 
            where "Url" ilike '%/app/pediatric-encounter/:id/:type/pediatric-guidelines%';
        END IF ;
    END
   $$ ;

DO $$                  
    BEGIN 
        IF EXISTS
            ( SELECT 1
              FROM   information_schema.tables 
              WHERE  table_schema = 'public'
              AND    table_name = 'Menu'
            )
        THEN
            UPDATE "Menu"
            SET "EncounterKey" = 'orderPrescription' 
            where "Url" = '/app/pediatric-encounter/:id/:type/order-prescription' and "EncounterKey"='ordersPrescription';
        END IF ;
    END
   $$ ;

--------------------------------------------------------------------------Tej 25Aug2023---------------------------------------------------------------------



CREATE SEQUENCE IF NOT EXISTS public."ScanService_Seq"
    INCREMENT 1
    START 1
    MINVALUE 1
    MAXVALUE 9223372036854775807
    CACHE 1;



CREATE TABLE IF NOT EXISTS public."ScanService"
(
    "ScanServiceId" integer NOT NULL DEFAULT nextval('"ScanService_Seq"'::regclass),
	"ScanTestMasterId" integer,
    "AdmissionId" integer,
    "CreatedDate" timestamp without time zone,
    "CreatedBy" integer,
    "Unit" integer,
    "Cost" numeric(10,2),
    "Active" boolean,
    "ModifiedDate" timestamp without time zone,
    "ModifiedBy" integer,
    "IsMain" boolean DEFAULT false,
    "Notes" text COLLATE pg_catalog."default",
    "ChargeCategoryId" integer,
    "AppointmentId" integer,
    "AdmissionPackageId" integer,
    "PackageModuleDetailId" integer,
    "UsedQuantity" integer,
    "UsedCost" numeric(10,2),
    CONSTRAINT "ScanService_pkey" PRIMARY KEY ("ScanServiceId"),	
    CONSTRAINT "FK_SurgeryService_ScanTestMasterId" FOREIGN KEY ("ScanTestMasterId")
        REFERENCES public."ScanTestMaster" ("ScanTestMasterId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_ScanService_AdmissionId" FOREIGN KEY ("AdmissionId")
        REFERENCES public."Admission" ("AdmissionId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_ScanService_AdmissionPackageId" FOREIGN KEY ("AdmissionPackageId")
        REFERENCES public."AdmissionPackage" ("AdmissionPackageId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
        NOT VALID,
    CONSTRAINT "FK_ScanService_AppointmentId" FOREIGN KEY ("AppointmentId")
        REFERENCES public."Appointment" ("AppointmentId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_ScanService_ChargeCategoryId" FOREIGN KEY ("ChargeCategoryId")
        REFERENCES public."ChargeCategory" ("ChargeCategoryId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_ScanService_CreatedBy" FOREIGN KEY ("CreatedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_ScanService_ModifiedBy" FOREIGN KEY ("ModifiedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_ScanService_PackageModuleDetailId" FOREIGN KEY ("PackageModuleDetailId")
        REFERENCES public."PackageModuleDetail" ("PackageModuleDetailId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
        NOT VALID
);

-------------------------------------------------------------------------Radhika 28Aug2023------------------------------------------------------------------------
DROP FUNCTION if exists public."revenue_EmployeeDetailTransactionWise1"(date, date, integer, integer);

CREATE OR REPLACE FUNCTION public."revenue_EmployeeDetailTransactionWise1"(
	"fromDate" date DEFAULT NULL::date,
	"toDate" date DEFAULT NULL::date,
	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, "IsHealthCard" boolean) 
    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",a."Active"
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"
, R."Cost"  as "PaidAmount" ,R."ReceiptTypeId",Ad."IsHealthCard"
 ,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",R."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
	--R."CreatedBy" =6776 and Ad."LocationId" = 2
--and R."CreatedDate"::date ='2023-04-18'
 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"::date end 
 		and case when "toDate" is null then 1=1 else R."CreatedDate"::date<=  "toDate" end 
 
)
,patient as(			
						select 
                                R."Cost" as "PaidAmount", 
	
                                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 "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 LAM."LocationId"=2 and R."CreatedDate"::date='2023-04-14 and R."CreatedBy"=6776
									
 	and case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::date end and
 	case when "toDate" is null then 1=1 else R."CreatedDate"::date<=  "toDate" end and
	case when "locationid" is null then 1=1 else  LAM."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" 
 ,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
	--and  Ad."LocationId"=2 and  R."CreatedBy"=6776
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"::date end 
 		and case when "toDate" is null then 1=1 else R."CreatedDate"::date<=  "toDate" end  

)
,lab as (
-- 	select 
--  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"

SELECT 
	 R."Cost" as "PaidAmount",PT."PayTypeName",R."PaymentDetails", 
	 AR."FullName" "ReceiptCreatedBy",Rl."RoleName",R."CreatedBy",
	 nlbh."RequisitionNumber",e."Active",
	 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"::date end and
	case when "toDate" is null then 1=1 else R."CreatedDate"::date<=  "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 
	 R."Cost" as "PaidAmount", PT."PayTypeName",R."PaymentDetails",
	 AR."FullName" "ReceiptCreatedBy" ,Rl."RoleName",R."CreatedBy",
	 nlbh."RequisitionNumber",nlbh."Active",
	 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"::date end and
	case when "toDate" is null then 1=1 else R."CreatedDate"::date<=  "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 
 R."Cost" as "PaidAmount", PT."PayTypeName",R."PaymentDetails",
	PH."PharmacySaleHeaderId" ,PH."BillNumber",A."Active",
	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  PH."LocationId"=2 and R."CreatedDate"::date='2023-04-18' 	
	 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"::date end and
 	case when "toDate" is null then 1=1 else R."CreatedDate"::date<=  "toDate" end and
  	case when "locationid" is null then 1=1 else PH."LocationId" = "locationid" end
UNION
	
select 
	 R."Cost" as "PaidAmount", PT."PayTypeName",R."PaymentDetails",
		PH."PharmacySaleHeaderId" ,PH."BillNumber",A."Active",
		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"::date end and
		case when "toDate" is null then 1=1 else R."CreatedDate"::date<=  "toDate" end and
		case when "locationid" is null then 1=1 else PH."LocationId" = "locationid" end		
)
,scan as(

select 
		 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", A."Active"
	
		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)
		--PH."LocationId"=2  and R."CreatedDate"::date='2023-04-14' 		
		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"::date end and
		case when "toDate" is null then 1=1 else R."CreatedDate"::date<=  "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",O."PayTypeName",O."PaymentDetails"
,O."PaidAmount",--O."RefundAmount",O."BalanceAmount",
O."PatientName",O."UMRNo",O."Mobile",O."IsHealthCard"
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",AP."IsHealthCard"
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",A."Active"
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",A."Active"
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",A."Active"
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",A."Active"
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",A."Active"
from accountdata A
join scan AP on AP."CreatedBy"=A."AccountId"	
	
)O
order by O."AccountId",O."ReceiptDate" desc;

end
$BODY$;

------------------------------------------------------------Shivani 28Aug2023-------------------------------------------------------------------

DROP FUNCTION  if exists "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, "PatientPriorityId" 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, "UnitName" 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."PatientPriorityId",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",DM."UnitName"
	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 "DoctorUnitMaster" DM on DM."DoctorUnitMasterId"=A."DoctorUnitMasterId"
	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",DM."UnitName"
	,newr."RoomName"
    order by A."AdmissionId" desc 
 limit "pageSize" offset ("pageSize"*"pageIndex");

END
$BODY$;
------------------------------------------------------------------------Kalyan 28Aug2023------------------------------------------------------------------------

INSERT INTO public."LabLogType"("LabLogTypeId","LogTypeName","Active")
SELECT 19,'Lab_Sample_Reject',true
WHERE
NOT EXISTS (
SELECT "LogTypeName" FROM public."LabLogType" WHERE "LogTypeName" = 'Lab_Sample_Reject'
);

INSERT INTO public."LabLogType"("LabLogTypeId","LogTypeName","Active")
SELECT 20,'Lab_Sample_Verified',true
WHERE
NOT EXISTS (
SELECT "LogTypeName" FROM public."LabLogType" WHERE "LogTypeName" = 'Lab_Sample_Verified'
);

INSERT INTO public."LabLogType"("LabLogTypeId","LogTypeName","Active")
SELECT 21,'Lab_Parameter_Added',true
WHERE
NOT EXISTS (
SELECT "LogTypeName" FROM public."LabLogType" WHERE "LogTypeName" = 'Lab_Parameter_Added'
);

INSERT INTO public."LabLogType"("LabLogTypeId","LogTypeName","Active")
SELECT 22,'Lab_Document_Upload',true
WHERE
NOT EXISTS (
SELECT "LogTypeName" FROM public."LabLogType" WHERE "LogTypeName" = 'Lab_Document_Upload'
);

INSERT INTO public."LabLogType"("LabLogTypeId","LogTypeName","Active")
SELECT 23,'Lab_Technician_Verified',true
WHERE
NOT EXISTS (
SELECT "LogTypeName" FROM public."LabLogType" WHERE "LogTypeName" = 'Lab_Technician_Verified'
);

INSERT INTO public."LabLogType"("LabLogTypeId","LogTypeName","Active")
SELECT 24,'Lab_Doctor_Verified',true
WHERE
NOT EXISTS (
SELECT "LogTypeName" FROM public."LabLogType" WHERE "LogTypeName" = 'Lab_Doctor_Verified'
);

---------------------------------------------------------------Sravani 29/08/2023------------------------------------------------------
alter table if exists "BookScanAppointment" add column IF NOT EXISTS "IsPatRegPaid" boolean;
--------------------------------------------------------------Shivani 29/08/2023-------------------------------------------------------


create sequence if not exists "PackageDocument_PackageDocumentId_seq";


CREATE TABLE IF NOT EXISTS public."PackageDocument"
(
    "PackageDocumentId" integer NOT NULL DEFAULT nextval('"PackageDocument_PackageDocumentId_seq"'::regclass),
    "PackageModuleId" integer NOT NULL,
    "DocumentName" character varying(100)  NOT NULL,
    "ContentType" character varying(50)  NOT NULL,
    "Size" double precision NOT NULL,
    "DocumentUrl" text NOT NULL,
    "ThumbnailUrl" text  NOT NULL,
    "UploadedDate" timestamp(6) without time zone NOT NULL,
    "UploadedBy" integer NOT NULL,
    CONSTRAINT "PackageDocumentId_pkey" PRIMARY KEY ("PackageDocumentId"),
    CONSTRAINT "FK_PackageDocument_PackageModuleId" FOREIGN KEY ("PackageModuleId")
        REFERENCES public."PackageModule" ("PackageModuleId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
	CONSTRAINT "FK_PackageDocument_UploadedBy" FOREIGN KEY ("UploadedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE
);

-----------------------------------------------------------------------------manish 31/08/2023-------------------------


alter table  vendors."SupplierProductFormulation" drop column if exists "SupplierProductHeaderId";
alter table  vendors."SupplierProductFormulation"  add column if not exists  "SupplierProductDetailId" int references vendors."SupplierProductDetail"("SupplierProductDetailId");
-----
alter table vendors."SupplierProductHeader" add column if not exists "RateCardUrl" text;

-----------------------------------------------------------------------------kalyan 31/08/2023--------------------------------------
alter table if exists "LabTransferDetail"
add column if not exists "ReceivedBy" integer ,
add column if not exists "ReceivedDate" timestamp without time zone,
drop constraint if exists "FK_LabTransferDetail_ReceivedBy",
ADD CONSTRAINT "FK_LabTransferDetail_ReceivedBy" FOREIGN KEY ("ReceivedBy") REFERENCES public."Account"("AccountId");

INSERT INTO public."LabBookingStatus"("Status","Active")
SELECT 'DepartmentReceived',true
WHERE
NOT EXISTS (
SELECT "Status" FROM public."LabBookingStatus" WHERE "Status" = 'DepartmentReceived'
);

INSERT INTO public."LabLogType"("LabLogTypeId","LogTypeName","Active")
SELECT 25,'Lab_Department_Accept',true
WHERE
NOT EXISTS (
SELECT "LogTypeName" FROM public."LabLogType" WHERE "LogTypeName" = 'Lab_Department_Accept'
);

alter table if exists "LabTransferDetail"
add column if not exists "DepartmentReceivedBy" integer ,
add column if not exists "DepartmentReceivedDate" timestamp without time zone,
drop constraint if exists "FK_LabTransferDetail_DepartmentReceivedBy",
ADD CONSTRAINT "FK_LabTransferDetail_DepartmentReceivedBy" FOREIGN KEY ("DepartmentReceivedBy") REFERENCES public."Account"("AccountId");

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