alter table "PayType" add column if not exists "Description" varchar(150), 
	add column if not exists "IsActive" boolean default true;

alter table "PayType" add column "PayTypeValue" varchar(10) not null default 'a';

Insert into "PayType" ("PayTypeName","Description","IsActive","PayTypeValue")
values ('UPI', 'for UPI Payments',true,'upi');

Update   "PayType" set  "PayTypeName" ='Card Swipe', "IsActive"=true, "PayTypeValue"='card' where "PayTypeId"=2;

Update   "PayType" set   "IsActive"=true, "PayTypeValue"='cash' where "PayTypeId"=1;
Update   "PayType" set   "IsActive"=false, "PayTypeValue"='cheque' where "PayTypeId"=3;
Update   "PayType" set   "IsActive"=false, "PayTypeValue"='dd' where "PayTypeId"=4;

-----------

Alter table "PharmacyProduct" add column "HSNCode" text;

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

 alter table "IssueHeader" add column "RequestIndentStatusId" integer;
									   
alter table "IssueHeader" add  CONSTRAINT "FK_IssueHeader_RequestIndentStatusId" FOREIGN KEY ("RequestIndentStatusId")
        REFERENCES public."RequestIndentStatus" ("RequestIndentStatusId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION;
		
 alter table "IssueDetail" add column	 "RequestIndentStatusId" integer;
	   
 alter table "IssueDetail" add  CONSTRAINT "FK_IssueDetail_RequestIndentStatusId" FOREIGN KEY ("RequestIndentStatusId")
        REFERENCES public."RequestIndentStatus" ("RequestIndentStatusId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION;
-----------

INSERT INTO public."PayType"(
	"PayTypeName", "Description", "IsActive", "PayTypeValue")
	VALUES ('Upi', 'For UPI Payments', true, 'Upi');

----------

UPDATE public."PayType"
	SET  "PayTypeValue"='Cash'
	WHERE "PayTypeId"=1;

	UPDATE public."PayType"
	SET  "PayTypeValue"='Card'
	WHERE "PayTypeId"=2;

	UPDATE public."PayType"
	SET  "PayTypeValue"='Cheque'
	WHERE "PayTypeId"=3;

	UPDATE public."PayType"
	SET  "PayTypeValue"='DD'
	WHERE "PayTypeId"=4;


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

alter table "Provider" add column "PracticeLocationId" integer;
								 
								 alter table "Provider" add  CONSTRAINT "FK_Provider_PracticeLocationId" FOREIGN KEY ("PracticeLocationId")
        REFERENCES public."PracticeLocation" ("PracticeLocationId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION;

update "Provider" Set "PracticeLocationId" = 17;

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

insert into "RequestIndentStatus" values (7,'Moved') ;

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

alter table "PharmacyRequestIndentDetail" add column "MovedBy" integer;

alter table "PharmacyRequestIndentDetail" add column "MovedDate" timestamp without time zone;

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

-- FUNCTION: public.udf_PharmacyPurchaseReport(text, text, integer, text, text, date, timestamp without time zone, timestamp without time zone, boolean, integer)

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

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

AS $BODY$
BEGIN

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

union

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

--ALTER FUNCTION public."udf_PharmacyPurchaseReport"(text, text, integer, text, text, date, timestamp without time zone, timestamp without time zone, boolean)
 --   OWNER TO postgres;
-------------

-- FUNCTION: public.udf_DailySalesReportByMedication(text, text, text, text, text, text, date, date)

DROP FUNCTION public."udf_DailySalesReportByMedication"(text, text, text, text, text, text, date, date);
--Select COUNT(*) OVER () AS "TotalItems",* from "udf_DailySalesReportByMedication"( null, null, null, null, null, null, '2022-04-04'::Date, '2022-04-04'::Date)
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,
	"paidVia" text DEFAULT NULL::text,
	"fromDate" date DEFAULT NULL::date,
	"toDate" date DEFAULT NULL::date)
    RETURNS TABLE("PharmacyProductId" integer, "ProductName" character varying, "BatchNumber" character varying, "GenericName" character varying, "CategoryName" character varying, "CompanyName" text, "SupplierName" text, "SaleQuantity" bigint, "Mrp" numeric, "Discount" numeric, "TotalAmount" numeric, "PaidVia" text, "SaleDate" timestamp without time zone, "PurchaseValue" 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."SaleDate" , TRUNC((A."PPD_NetAmount"/A."PPD_Quantity"),2)  as "PurchaseValue"
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",Ps."Discount" "OverallDiscount",PS."NetAmount" , PH."PaidVia",
	  ppd."NetAmount" as "PPD_NetAmount",ppd."Quantity" as "PPD_Quantity"
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"
join "PharmacyPurchaseDetail" Ppd on  ppd."PharmacyStockId"=prs."PharmacyStockId" and  ppd."PharmacyProductId"=PRS."PharmacyProductId"
join "PharmacyPurchaseHeader" pph on pph."PharmacyPurchaseHeaderId"=Ppd."PharmacyPurchaseHeaderId"
join "Supplier" s on s."SupplierId"=pph."SupplierId"  
--where PS."PharmacyProductId"= 1299  
	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 "paidVia" ='' then 1=1  when "paidVia" is null then 1=1  else PH."PaidVia" ilike  '%'||"paidVia"||'%' end  and

	case when "fromDate" is null then 1=1 else "fromDate" ::date <=PH."SaleDate"::date and PH."SaleDate"::date <="toDate" ::date 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",Ps."Discount" ,PH."PaidVia" ,
 	ppd."NetAmount", ppd."Quantity") A
	
group by A."PharmacyProductId",A."ProductName",A."BatchNumber",A."GenericName",A."CategoryName ",
A."CompanyName",A."SupplierName",A."Mrp",A."OverallDiscount",A."PaidVia",A."SaleDate", (A."PPD_NetAmount"/A."PPD_Quantity")
order  by A."ProductName"
;

END
$BODY$;

ALTER FUNCTION public."udf_DailySalesReportByMedication"(text, text, text, text, text, text, date, date)
    OWNER TO postgres;

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

ALTER TABLE IF EXISTS "PharmacyRetailer" RENAME TO "PharmacyRetailUser";

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

-- FUNCTION: public.udf_DailySalesReportByMedication(text, text, text, text, text, text, date, date)

-- 
DROP FUNCTION public."udf_DailySalesReportByMedication"(text, text, text, text, text, text, date, date);

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,
	"paidVia" text DEFAULT NULL::text,
	"fromDate" date DEFAULT NULL::date,
	"toDate" date DEFAULT NULL::date)
    RETURNS TABLE("PharmacyProductId" integer, "ProductName" character varying, "BatchNumber" character varying, "GenericName" character varying, "CategoryName" character varying, "CompanyName" text, "SupplierName" text, "SaleQuantity" bigint, "Mrp" numeric, "Discount" numeric, "TotalAmount" numeric, "PaidVia" text, "SaleDate" timestamp without time zone, "PurchaseValue" numeric,"PurchaseUnitQty" integer) 
    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."SaleDate" , TRUNC((A."PPD_NetAmount"/A."PPD_Quantity"),2)  as "PurchaseValue"
,A."PurchaseUnitQty"
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",Ps."Discount" "OverallDiscount",PS."NetAmount" , PH."PaidVia",
	  ppd."NetAmount" as "PPD_NetAmount",ppd."Quantity" as "PPD_Quantity"
	,pp."PurchaseUnitQty"
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"
join "PharmacyPurchaseDetail" Ppd on  ppd."PharmacyStockId"=prs."PharmacyStockId" and  ppd."PharmacyProductId"=PRS."PharmacyProductId"
join "PharmacyPurchaseHeader" pph on pph."PharmacyPurchaseHeaderId"=Ppd."PharmacyPurchaseHeaderId"
join "Supplier" s on s."SupplierId"=pph."SupplierId"  
--where PS."PharmacyProductId"= 1299  
	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 "paidVia" ='' then 1=1  when "paidVia" is null then 1=1  else PH."PaidVia" ilike  '%'||"paidVia"||'%' end  and

	case when "fromDate" is null then 1=1 else "fromDate" ::date <=PH."SaleDate"::date and PH."SaleDate"::date <="toDate" ::date 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",Ps."Discount" ,PH."PaidVia" ,
 	ppd."NetAmount", ppd."Quantity",pp."PurchaseUnitQty") A
	
group by A."PharmacyProductId",A."ProductName",A."BatchNumber",A."GenericName",A."CategoryName ",
A."CompanyName",A."SupplierName",A."Mrp",A."OverallDiscount",A."PaidVia",A."SaleDate", (A."PPD_NetAmount"/A."PPD_Quantity") , A."PurchaseUnitQty"
order  by A."ProductName"
;

END
$BODY$;

ALTER FUNCTION public."udf_DailySalesReportByMedication"(text, text, text, text, text, text, date, date)
    OWNER TO postgres;
	
--------

UPDATE public."PayType"
	SET  "PayTypeValue"='Upi',"PayTypeName"='UPI',"Description"='for upi payments'
	WHERE "PayTypeId"=1;
	
	UPDATE public."PayType"
	SET  "PayTypeValue"='Cash',"PayTypeName"='Cash',"Description"='for cash payments'
	WHERE "PayTypeId"=5;


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

Alter table "LabBookingHeader" add column "Notes" character varying;

---------

Alter table "MealType" rename to "MealTypes"

create sequence public."ProgressReportDiet_ProgressReportDietId_seq";
-- Table: public.ProgressReportDiet

-- DROP TABLE public."ProgressReportDiet";

CREATE TABLE public."ProgressReportDiet"
(
    "ProgressReportDietId" integer NOT NULL DEFAULT nextval('"ProgressReportDiet_ProgressReportDietId_seq"'::regclass),
    "ProgressReportId" integer NOT NULL,
    "MealTypeId" integer,
    "CreatedBy" integer NOT NULL,
    "CreatedDate" timestamp(6) without time zone NOT NULL,
    "ModifiedBy" integer,
    "ModifiedDate" timestamp(6) without time zone,
    "Active" boolean NOT NULL,
    "Duration" integer NOT NULL,
    "MedicationDurationTypeId" integer NOT NULL,
    "StopReason" text COLLATE pg_catalog."default",
    "StartDate" date NOT NULL,
    "EndDate" date NOT NULL,
    "StopDate" timestamp without time zone,
    "DietInstructions" text COLLATE pg_catalog."default",
    CONSTRAINT "ProgressReportDietId_pkey" PRIMARY KEY ("ProgressReportDietId"),
    CONSTRAINT "FK_ProgressReportDiet_CreatedBy" FOREIGN KEY ("CreatedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_ProgressReportDiet_MealTypeId" FOREIGN KEY ("MealTypeId")
        REFERENCES public."MealTypes" ("MealTypeId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_ProgressReportDiet_ModifiedBy" FOREIGN KEY ("ModifiedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_ProgressReportDiet_ProgressReportId" FOREIGN KEY ("ProgressReportId")
        REFERENCES public."ProgressReport" ("ProgressReportId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_ProgressReportMedication_MedicationDurationTypeId" FOREIGN KEY ("MedicationDurationTypeId")
        REFERENCES public."MedicineDurationType" ("MedicineDuratonTypeId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
)
WITH (
    OIDS = FALSE
)
TABLESPACE pg_default;

ALTER TABLE public."ProgressReportDiet"
    OWNER to postgres;

-------