/* 

octpdba-497 () have removed openrowset to amavitaLiveAPS, everything is centralised now.
Each procs that have been altered exists with a copy with the suffix "octpdba-497" (typo in some, where the suffix is ctpdba-497).
The copy with the suffix holds the old code.


usage of openrowset on suncent
    Object name	Schema	Database	Type
    ABD_Cent_Load	dbo	ArizonaCUST	Procedures
    ABD_Cent_Load_CTPDBA-497	dbo	ArizonaCUST	Procedures
    ACC_Cent_Load	dbo	ArizonaCUST	Procedures
    ACC_Cent_Load_CTPDBA-497	dbo	ArizonaCUST	Procedures
    AP_Cent_Load	dbo	ArizonaCUST	Procedures
    AP_Cent_Load_OCTPDBA-497	dbo	ArizonaCUST	Procedures
    APR_Cent_Load	dbo	ArizonaCUST	Procedures
    aps_Central_Annual_Inventory_Load	dbo	ArizonaCUST	Procedures
    aps_GAL_olpFACT_controle_PHA	dbo	ArizonaCUST	Procedures
    aps_SUN_Cession_Creances	dbo	ArizonaCUST	Procedures
    aps_SUN_Get_Balanced_Scorecard_Data_From_Central	dbo	ArizonaCUST	Procedures
    AS_Cent_Load	dbo	ArizonaCUST	Procedures
    AS_Cent_Load__OCTPDBA-497	dbo	ArizonaCUST	Procedures
    AT_Cent_Aggregated_Data_Load	dbo	ArizonaCUST	Procedures
    AT_Cent_Aggregated_Data_Load_OCTPDBA-497	dbo	ArizonaCUST	Procedures
    AT_Cent_Extract_specific_pd_codes	dbo	ArizonaCUST	Procedures
    AT_Cent_Load	dbo	ArizonaCUST	Procedures
    CRMCRD_Cent_Load	dbo	ArizonaCUST	Procedures
    CRMCRD_Cent_Load_OCTPDBA-497	dbo	ArizonaCUST	Procedures
    CRSH_Cent_Load	dbo	ArizonaCUST	Procedures
    CRSO_Cent_Load	dbo	ArizonaCUST	Procedures
    CRSO_Cent_Load_OCTPDBA-497	dbo	ArizonaCUST	Procedures
    DHICI_Cent_Load	dbo	ArizonaCUST	Procedures
    DHICI_Cent_Load_OCTPDBA-497	dbo	ArizonaCUST	Procedures
    FM_Cent_Load	dbo	ArizonaCUST	Procedures
    ITSC_Cent_Load	dbo	ArizonaCUST	Procedures
    SSRS_CR_Sales_Select_For_CR_Operation	dbo	ArizonaCUST	Procedures
    SSRS_Galenicare_Invoice_Payment_List	dbo	ArizonaCUST	Procedures

stuff that stinks:
    ABD_Cent_Load
        user sqlSyncAccountingExtractionUsr with it's password in the proc

    ACC_Cent_Load
        seems that SA passwords are in there.
        not the actual SA passwords, might be old code that was not adapted

    AP_Cent_Load
        user sqlSyncAccountingExtractionUsr with it's password in the proc

    AT_Cent_Load
        Still have a link to AMAVITALIVEAPS



reports:
    FidelityCardSales
        Rapport KO. Son lancement remonte le message suivant
            An error has occurred during report processing. (rsProcessingAborted)
            Query execution failed for dataset 'DSMain'. (rsErrorExecutingCommand)
            Could not find stored procedure 'Extraction_Galenicare_Sales_Fidelity_Card'.

        Lors de la sélection de la "company", lance une query sur Gaia qui retourne toutes les OU de tous les formats ainsi que les "cost centers"
        ---------------------------
            with Pharmacy ([Company], [Code], [Code_name]) as
            (
            select coalesce(asub.Code, OU_subsidiary_prefix) 
                 , OU_code 
	             , OU_code + ' ' + OU_short_name 
              from [crs].[vwOrganizationalUnit] ou with (nolock)
             inner join phar.address_criteria adcr with (nolock)
  	            on ou.OU_pharmacy_code = adcr.ADCR_pharmacy_code 
               and ou.OU_address = adcr.ADCR_address 
             inner join phar.criteria cr with (nolock)
                on adcr.ADCR_criteria = cr.Criteria_ID
               and adcr.ADCR_pharmacy_code = cr.CR_pharmacy_code 
             inner join [phar].[Criteria_type] crt with (nolock)
                on cr.CR_criteria_type = crt.Criteria_type_ID
               and cr.CR_pharmacy_code = crt.CRT_pharmacy_code
              left join crs.AdditionalSubsidiaryLink asl with (nolock)
                on ou.Reference_Organizational_unit_ID = asl.OrganizationalUnitId 
              left join crs.AdditionalSubsidiary asub with (nolock)
                on asl.AdditionalSubsidiaryId = asub.AdditionalSubsidiaryId
             where crt.CRT_type = 1 and crt.crt_code = 'ENV' 
               and ou.OU_subsidiary_prefix is not null
            )
            select 1 as Position, [Company], null as [Code], '<All>' as [Code_name]
              from [Pharmacy]
            union 
            select 2 as Position, [Company], [Code], [Code_name]
              from Pharmacy
            order by Position, Company, Code 


            with CostCenter([Code], [Company])
            as
            (SELECT pcck.PCCK_key AS [Code], 
	               coalesce(asub.Code, ou.OU_subsidiary_prefix)  AS [Company]
              from crs.vwOrganizationalUnit ou with (nolock)
              left join crs.AdditionalSubsidiaryLink asl with (nolock)
                on ou.Reference_Organizational_unit_ID = asl.OrganizationalUnitId 
              left join crs.AdditionalSubsidiary asub with (nolock)
                on asl.AdditionalSubsidiaryId = asub.AdditionalSubsidiaryId
             inner join phar.Profit_cost_center_key pcck with (nolock)
                on pcck.PCCK_profit_cost_center = ou.OU_profit_cost_center
               and pcck.PCCK_pharmacy_code = ou.OU_pharmacy_code
             inner join phar.Fiscal_year fy with (nolock)
                on fy.Fiscal_year_ID = pcck.PCCK_fiscal_year
               and fy.FY_pharmacy_code = pcck.PCCK_pharmacy_code
               and fy.FY_subsidiary = ou.OU_subsidiary
               and fy.FY_number = 2022 
               and pcck.PCCK_type = Case When coalesce(asub.Code, ou.OU_subsidiary_prefix) in ('CVI', 'SUN') Then 3 
                                         Else 1 End
             where ou.OU_centrale_code = 'G')
            SELECT 1 as Position, null as [Code], '<All>' as [Code_name], null as [Company] from CostCenter
            union
            SELECT 2 as Position, null as [Code], '<All>' as [Code_name], [Company] from CostCenter
            union 
            SELECT 3 as Position, [Code], [Code] as [Code_name], [Company] from CostCenter
            order by Position, Company, Code 
        ---------------------------

    LifeStageInvoices
        l'ouverture rdu rapport lance 2 query. la 1ere liste les "cost centeers" comme dans le rapport précédent
        Démarre la query suivante en environ 38 secondes, index scan sur document_header:
        ----------------
            exec sp_executesql N'SELECT dh.DH_doc_number AS InvoiceNumber, 
	           dh.DH_value_date AS InvoiceDate,
               et.ET_debit_base_amount AS InvoiceAmount, 
               dh.DH_sold_to_text AS CustomerName, 
	           coalesce(et.ET_debit_base_amount, 0) - coalesce(SUM(etr.ETR_base_amount), 0) AS DueAmount,
	           dh.DH_invoice_group AS LifeStageNumber,
	           ins.PHIN_name_german AS [Debtor]
          FROM [Gaia].[phar].[Document_header] dh WITH (nolock)
         INNER JOIN phar.Entry et WITH (nolock)
            ON dh.document_header_id = et.ET_document_header
           AND dh.dh_account = et.Et_account
           AND dh.DH_pharmacy_code = et.ET_pharmacy_code
          LEFT JOIN phar.Entry_reconciliation etr WITH (nolock)
            ON et.Entry_ID = etr.ETR_entry
           AND et.ET_pharmacy_code = etr.ETR_pharmacy_code
          left join phar.PH_insurance as ins with (nolock)
            on ins.PHIN_address = dh.DH_send_bill_to
           and left(ins.PHIN_pharmacy_code, 1) = left(dh.DH_pharmacy_code, 1)
         WHERE dh.DH_invoice_group IS NOT NULL
           AND dh.DH_our_ref LIKE ''LifeStage%''
           AND dh.DH_pharmacy_code = @PharmacyLifeStage
         GROUP BY dh.DH_doc_number,
                  dh.Document_header_ID,
		          dh.DH_value_date,
                  et.ET_debit_base_amount,
                  dh.DH_sold_to_text,
		          dh.DH_BVR_reference,
	              dh.DH_account,
		          dh.DH_invoice_group,
		          dh.DH_our_ref,
		          et.ET_reconciliation_status,
		          ins.PHIN_name_german
        HAVING ((@LifeStageInvoiceNumber is not null AND dh.DH_invoice_group like @LifeStageInvoiceNumber + ''%'')
           OR (@TriaPharmInvoiceNumber is not null AND @LifeStageInvoiceNumber is null AND dh.DH_Doc_number like @TriaPharmInvoiceNumber + ''%'')
           OR (@LifeStageInvoiceNumber is null AND @TriaPharmInvoiceNumber is null AND dh.DH_value_date between @InvoiceDateFrom AND isnull(@InvoiceDateTo, cast(getDate() as date))
           AND (@OpenedInvoice = 0 OR isnull(et.ET_reconciliation_status, 1) = 1)));',N'@InvoiceDateFrom datetime,@InvoiceDateTo nvarchar(4000),@LifeStageInvoiceNumber nvarchar(4000),@OpenedInvoice bit,@TriaPharmInvoiceNumber nvarchar(4000),@PharmacyLifeStage nvarchar(6)',@InvoiceDateFrom='2022-01-01 00:00:00',@InvoiceDateTo=NULL,@LifeStageInvoiceNumber=NULL,@OpenedInvoice=1,@TriaPharmInvoiceNumber=NULL,@PharmacyLifeStage=N'GAM316'
        ----------------

    OpenInvoiceDetails:
        nécessite un "master id", l'entrée de data bidon remonte la query suivante lancée:
        -------------------
            (@InvoiceDateFrom datetime,@InvoiceDateTo nvarchar(4000),@LifeStageInvoiceNumber nvarchar(4000),@OpenedInvoice bit,@TriaPharmInvoiceNumber nvarchar(4000),@PharmacyLifeStage nvarchar(6))SELECT dh.DH_doc_number AS InvoiceNumber, 
	               dh.DH_value_date AS InvoiceDate,
                   et.ET_debit_base_amount AS InvoiceAmount, 
                   dh.DH_sold_to_text AS CustomerName, 
	               coalesce(et.ET_debit_base_amount, 0) - coalesce(SUM(etr.ETR_base_amount), 0) AS DueAmount,
	               dh.DH_invoice_group AS LifeStageNumber,
	               ins.PHIN_name_german AS [Debtor]
              FROM [Gaia].[phar].[Document_header] dh WITH (nolock)
             INNER JOIN phar.Entry et WITH (nolock)
                ON dh.document_header_id = et.ET_document_header
               AND dh.dh_account = et.Et_account
               AND dh.DH_pharmacy_code = et.ET_pharmacy_code
              LEFT JOIN phar.Entry_reconciliation etr WITH (nolock)
                ON et.Entry_ID = etr.ETR_entry
               AND et.ET_pharmacy_code = etr.ETR_pharmacy_code
              left join phar.PH_insurance as ins with (nolock)
                on ins.PHIN_address = dh.DH_send_bill_to
               and left(ins.PHIN_pharmacy_code, 1) = left(dh.DH_pharmacy_code, 1)
             WHERE dh.DH_invoice_group IS NOT NULL
               AND dh.DH_our_ref LIKE 'LifeStage%'
               AND dh.DH_pharmacy_code = @PharmacyLifeStage
             GROUP BY dh.DH_doc_number,
                      dh.Document_header_ID,
		              dh.DH_value_date,
                      et.ET_debit_base_amount,
                      dh.DH_sold_to_text,
		              dh.DH_BVR_reference,
	                  dh.DH_account,
		              dh.DH_invoice_group,
		              dh.DH_our_ref,
		              et.ET_reconciliation_status,
		              ins.PHIN_name_german
            HAVING ((@LifeStageInvoiceNumber is not null AND dh.DH_invoice_group like @LifeStageInvoiceNumber + '%')
               OR (@TriaPharmInvoiceNumber is not null AND @LifeStageInvoiceNumber is null AND dh.DH_Doc_number like @TriaPharmInvoiceNumber + '%')
               OR (@LifeStageInvoiceNumber is null AND @TriaPharmInvoiceNumber is null AND dh.DH_value_date between @InvoiceDateFrom AND isnull(@InvoiceDateTo, cast(getDate() as date))
               AND (@OpenedInvoice = 0 OR isnull(et.ET_reconciliation_status, 1) = 1)));
            -------------------

        OpenInvoice:
            lance une query en entrant sur le rapport pour lister les formats et les OU.
            -----------------
            select ou.Organizational_unit_ID [Reference_Organizational_unit_ID], 
                   case when charindex(ou.OU_code,ou.OU_short_name) > 0 then ou.OU_short_name else ou.OU_short_name + ' ' + ou.OU_code end [Name]          
            from phar.Organizational_unit as ou
              join [crs].[vwSubsidiary] as sub
                on sub.Reference_Subsidiary_ID = ou.OU_subsidiary
              join phar.PH_organizational_unit as phou
                on phou.PHOU_organizational_unit = ou.Organizational_unit_ID
	            and phou.PHOU_pharmacy_code = ou.OU_pharmacy_code
              left join phar.Organizational_unit ou2
                on ou2.OU_master_ID = ou.Organizational_unit_ID and ou2.OU_pharmacy_code = 'A00000'
             where ou.OU_pharmacy_code = 'G00000' 
              and ou.OU_subsidiary = 1
             order by ou.OU_subsidiary, ou.OU_short_name 

            select sub.Reference_Subsidiary_ID, 
                      sub.SUB_prefix  
             from crs.vwSubsidiary sub with (nolock) 
            -----------------

            Le lancement du report lance la proc reportOpenInvoice qui mouline bien sur Gaia
            ~ 7 minutes, puis des interrogation par OU et entry
            ~ 12 minutes au total lors de mon test
            -----------------
            exec crs.ReportOpenInvoices @Format=N'1',@Pharmacy=N'185;157;249;339;366;205;142;308;186;354;285;296;148;298;341;284;322;290;169;144;349;173;163;133;348;342;146;261;124;174;248;137;260;202;117;156;194;254;207;287;334;247;227;153;552;345;663;306;128;130;129;327;131;844;843;300;189;295;338;333;217;110;161;198;329;111;109;270;210;330;103;343;854;224;340;336;272;145;328;166;346;136;859;122;134;135;125;314;118;307;123;760;292;164;120;301;291;195;282;721;571;132;317;114;113;112;115;119;305;302;570;319;544;140;323;373;320;138;139;303;344;318;147;274;310;358;357;359;574;575;873;321;311;175;360;388;331;216;560;143;126;559;299;121;781;335;304',@InvoiceNumber=NULL,@NegativeAmount=0

            exec crs.ReportOpenInvoiceDetails @WithPayment=0,@EntryId=1501545291,@PharmacyCode=N'GSU191'
            exec crs.ReportOpenInvoiceDetails @WithPayment=0,@EntryId=1501567600,@PharmacyCode=N'GSU191'
            exec crs.ReportOpenInvoiceDetails @WithPayment=0,@EntryId=1501572213,@PharmacyCode=N'GSU191'
            ...
            -----------------

        Payment reconciliation:
            a l'ouverture du rapport, recherche des "company"
                select ads.Name , ads.AdditionalSubsidiaryId
                from crs.AdditionalSubsidiary ads  

            puis recherche des OU liées à cette company
                (@Company nvarchar(1))select  ou.OU_code, ou.OU_short_name, adl.OrganizationalUnitId
                  from crs.AdditionalSubsidiaryLink adl with (nolock)
                  join [crs].vwOrganizationalUnit ou
                    on ou.Reference_Organizational_unit_ID = adl.OrganizationalUnitId
                where adl.AdditionalSubsidiaryId in ( @Company ) 

            erreur lors du lancement du rapport:
                exec sp_executesql N'exec [crs].[PaymentList]
                    @in_year = @Year,
                    @in_month = @Month,
                    @in_Additionnal_subsidiary = @Company,
                    @in_organizational_unit = @Pharmacy,
                    @in_payment_mode = @Mode,
                    @in_lan_code = @Language',N'@Year int,@Month int,@Company nvarchar(1),@Pharmacy nvarchar(7),@Mode nvarchar(1),@Language nvarchar(2)',@Year=2023,@Month=3,@Company=N'1',@Pharmacy=N'480;700',@Mode=N'1',@Language=N'FR'

                An error has occurred during report processing. (rsProcessingAborted)
                Query execution failed for dataset 'Data'. (rsErrorExecutingCommand)
                The server principal "sqlReportTriaFinUser" is not able to access the database "HCITools" under the current security context.



*/