﻿



-- =============================================
-- Author:		Steamware
-- Create date: 2014.01.22
-- Description:	aggiorna le tabelle QuoteList con i dati selezionati dalla TabProdSc
-- =============================================
CREATE PROCEDURE [dbo].[stp_QL_update]
(
	@QuoteType	CHAR(1) = 'Q',
	@CodQuote	BIGINT	= 0,
	@QuoteRev	INT		= 0
) 
AS
BEGIN

    SET NOCOUNT ON;

	-- dichiaro valori da recuperare
	DECLARE	@strTemp		NVARCHAR(50) = '' --stringa temporanea x variabili "locali"

	DECLARE @valid			BIT
	DECLARE @CodDiesGroup	NVARCHAR(50)
	DECLARE @CodPlant		NVARCHAR(50)
	DECLARE @CodPlantFix	NVARCHAR(50) = ''
	DECLARE @HoleNum		INT
    -- ITEM
	DECLARE @CodItem		NVARCHAR(50) = '' --cod item
	DECLARE @ItemDescr		NVARCHAR(50) = '' -- descrizione item
    DECLARE @CodifProfilo   NVARCHAR(50) = '' -- Cod. Profilo
    DECLARE @ClasseMerc     NVARCHAR(50) = '' 
    DECLARE @CodClientAssoc NVARCHAR(50) = '' 

	DECLARE @KeyAM			NVARCHAR(50) = ''
	DECLARE @KeyAMI			NVARCHAR(50) = ''
	DECLARE @KeyAMIL		NVARCHAR(50) = ''
	DECLARE @NumSMED		INT = 0 -- numero cambi
	DECLARE @KgTeo			DECIMAL(18, 6) = 0 -- kg totali
	DECLARE @RawMat			NVARCHAR(50)
	DECLARE	@ProdTeo		DECIMAL(18,6)
	DECLARE	@ScTec			DECIMAL(18,6)
	DECLARE	@BatchQty		INT
	DECLARE	@MAC_SC			DECIMAL(18,6) -- Messa a cento scarto cesoia
	DECLARE	@MAC_ST			DECIMAL(18,6) -- Messa a cento scarto tecnico
	DECLARE	@MAC_IN			DECIMAL(18,6) -- Messa a cento difettosità all'incestatura
	DECLARE	@MAC_IM			DECIMAL(18,6) -- Messa a cento difettosità all'imballo
	DECLARE	@SSR			DECIMAL(9,6) -- percentuale vendita rottame
	DECLARE	@DiesPrice		DECIMAL(9,3) -- prezzo matrice
	DECLARE	@DiesEOLife		DECIMAL(9,2) -- durata matrice
	DECLARE	@DiesExpLife	DECIMAL(9,2) -- durata matrice
	DECLARE	@DiesPriceLife	DECIMAL(18,6) -- Price/Life matrice
	DECLARE	@OCF01			DECIMAL(18,6) = 0 -- altri costi di fase 01
	DECLARE	@VCF01			DECIMAL(18,6) = 0 -- costi variabili di fase 01
	DECLARE	@VCF04			DECIMAL(18,6) = 0 -- costi variabili di fase 04
	DECLARE	@SellCostF01	DECIMAL(18,6) = 0 -- costo vendita fase 01
	DECLARE	@SellCostF04	DECIMAL(18,6) = 0 -- costo vendita fase 04
	DECLARE	@RefCostF01		DECIMAL(18,6) = 0 -- costo rifusione fase 01 
	DECLARE	@RefCostF04		DECIMAL(18,6) = 0 -- costo rifusione fase 04
	-- IMBALLO
	DECLARE	@CodPackag		NVARCHAR(50) = '0'  -- codice dell'imballo
	DECLARE @CodClient		NVARCHAR(50) = ''   -- codice cliente
	DECLARE @NumImb			DECIMAL(9,6) = 0    -- num imballatori
	DECLARE @PkgDesc		NVARCHAR(50) = ''   -- descrizione imballo
	DECLARE @PRMWeight		DECIMAL(9,4) = 0    -- peso dell'imballo
	DECLARE @PWeight		DECIMAL(9,4) = 0    -- peso del pacco
	DECLARE @PTare			DECIMAL(9,4) = 0    -- media delal tara di imballo dichiarata
	DECLARE @PCost			DECIMAL(9,6) = 0    -- costo unitario dell'imballo (al kg) 
	DECLARE @PTareStRatio	DECIMAL(9,4) = 0    -- coefficiente di recupero tara/prodotto
    DECLARE @PTotQta        DECIMAL(18,3) = 0   -- Qta Kg Tot Imballati
    DECLARE @PDurata        DECIMAL(18,6) = 0   -- Tempo d'imballaggio
    DECLARE @PLiv           NVARCHAR(50)  = ''   -- Livello Search dati Imballo     
    DECLARE @PLivDett       NVARCHAR(50)  = ''   -- Key Livello Search Dati Imballo
	-- TRASPORTI
	DECLARE	@TranspZone		NVARCHAR(50) = '' -- codice ZONA
    DECLARE	@TranspCost		DECIMAL(9,6)      -- costo di trasporto
    DECLARE	@HasTC			INT

	-- PROVVIGIONI
	DECLARE	@Provvig		DECIMAL(9,6) -- provvigione agente

	-- default: validità è true!
	SET		@valid = 1

    -- =================================================
    --   CREAZIONE TEMP TABLE
    -- =================================================

	-- elimino e ricreo #QuoteParam temp table...
	IF OBJECT_ID('tempdb..#QuoteParam') IS NOT NULL
		DROP TABLE #QuoteParam

    CREATE TABLE #Quoteparam
    (
                 Quotetype  CHAR( 1 )           NOT NULL,
                 Codquote   BIGINT              NOT NULL,
                 Quoterev   INT                 NOT NULL,
                 Nump       INT IDENTITY( 1,1 ) NOT NULL,
                 Processnum NVARCHAR( 50 )      NOT NULL,
                 Descr      NVARCHAR( 50 )      NOT NULL,
                 Parameter  NVARCHAR( 100 )     NOT NULL,
    --PRIMARY KEY
    --		(	NumP ASC, QuoteType ASC, CodQuote ASC, QuoteRev ASC ) WITH  (PAD_INDEX  = ON, FILLFACTOR = 90 )
    );

	-- elimino e ricreo #QuoteParam temp table...
	IF OBJECT_ID('tempdb..#QuoteWorkInt') IS NOT NULL
		DROP TABLE #QuoteWorkInt

   CREATE TABLE #QuoteWorkInt
    (
        QuoteType     CHAR(1)   NOT NULL,
        CodQuote      BIGINT    NOT NULL,
        QuoteRev      INT       NOT NULL,
        NumWI         INT IDENTITY(1,1) NOT NULL,
        ProcessNum    NVARCHAR(50) NOT NULL,
        CodPlant      NVARCHAR(50) NOT NULL,
        Class01       NVARCHAR(50) NOT NULL DEFAULT (''),
        Class02       NVARCHAR(50) NOT NULL DEFAULT (''),
        Class03       NVARCHAR(50) NOT NULL DEFAULT (''),
        Class04       NVARCHAR(50) NOT NULL DEFAULT (''),
        Class05       NVARCHAR(50) NOT NULL DEFAULT (''),
        NetProd       DECIMAL(9, 3) NOT NULL DEFAULT ((0)),
        WSR           DECIMAL(9, 8) NOT NULL DEFAULT ((0)),
        MSR           DECIMAL(9, 8) NOT NULL DEFAULT ((0)),
        DSR           DECIMAL(9, 8) NOT NULL DEFAULT ((0)),
        FC4UG         DECIMAL(9, 6) NOT NULL DEFAULT ((0)),
        VC4UG         DECIMAL(9, 6) NOT NULL DEFAULT ((0)),
        OH4UG         DECIMAL(9, 6) NOT NULL DEFAULT ((0)),
        SC4UG         DECIMAL(9, 6) NOT NULL DEFAULT ((0)),
        -- campi calcolati
        WYR   AS ((1)-WSR),
        MYR   AS ((1)-MSR),
        DYR   AS ((1)-DSR),
        WCR   AS ((1)/((1)-WSR)),
        MCR   AS ((1)/((1)-MSR)),
        DCR   AS ((1)/((1)-DSR)),
        valid BIT NOT NULL DEFAULT((1)),
    )

    -- elimino e ricreo #QuoteParam temp table...
    IF OBJECT_ID('tempdb..#QuoteOC') IS NOT NULL
		DROP TABLE #QuoteOC

    CREATE TABLE #QuoteOC 
    (
	    QuoteType   CHAR(1)             NOT NULL,
	    CodQuote    BIGINT              NOT NULL,
	    QuoteRev    INT                 NOT NULL,
	    NumEx       INT IDENTITY(1,1)   NOT NULL,
	    ProcessNum  NVARCHAR(50)        NOT NULL,
	    CodPlant    NVARCHAR(50)        NOT NULL,
	    Class01     NVARCHAR(50)        NOT NULL DEFAULT (''),
	    Class02     NVARCHAR(50)        NOT NULL DEFAULT (''),
	    Class03     NVARCHAR(50)        NOT NULL DEFAULT (''),
	    Class04     NVARCHAR(50)        NOT NULL DEFAULT (''),
	    Class05     NVARCHAR(50)        NOT NULL DEFAULT (''),
	    TotQty      DECIMAL(18, 6)      NOT NULL DEFAULT ((1)),
	    TotCost     DECIMAL(18, 6)      NOT NULL DEFAULT ((0)),
	    Quota       DECIMAL(18, 6)      NOT NULL DEFAULT ((1)),
	    C4UG        AS ((TotCost*Quota)/TotQty),
	    valid       BIT NOT NULL DEFAULT ((1))
    )

    -- ===================================
    --  INIZIO TRANSAZIONE
    -- ===================================
	SET XACT_ABORT ON;
	BEGIN TRAN

		---------------------------------------
		-- svuotamento iniziale
		---------------------------------------
	
		-- elimino quote PARAMETRI!
		DELETE FROM	dbo.QuoteParam
		WHERE	QuoteType	= @QuoteType
			AND	CodQuote	= @CodQuote
			AND	QuoteRev	= @QuoteRev

    	-- elimino lavorazioni ESTERNE!
		DELETE FROM	dbo.QuoteWorkExt
		WHERE	QuoteType	= @QuoteType
			AND	CodQuote	= @CodQuote
			AND	QuoteRev	= @QuoteRev

		-- elimino lavorazioni INTERNE
		DELETE FROM	dbo.QuoteWorkInt
		WHERE	QuoteType	= @QuoteType
			AND	CodQuote	= @CodQuote
			AND	QuoteRev	= @QuoteRev

		-- elimino OtherCosts
		DELETE FROM	dbo.QuoteOC
		WHERE	QuoteType	= @QuoteType
			AND	CodQuote	= @CodQuote
			AND	QuoteRev	= @QuoteRev

		-- se ci sono eccezioni nella tab dell'anagrafico articoli imposto il codPlant desiderato
		SET	@CodPlantFix = ISNULL ( ( SELECT id.CodPlant FROM dbo.ItemDet id 
                                      INNER JOIN dbo.QuoteList ql ON id.CodItem = ql.CodItem
		                              WHERE ql.QuoteType   = @QuoteType
			                            AND ql.CodQuote    = @CodQuote
			                            AND ql.QuoteRev    = @QuoteRev ), '' )

		-- recupero da dati dell'offerta il valore del cliente
		SELECT	@CodClient		= CodClient
		FROM	dbo.QuoteList
		WHERE	QuoteType		= @QuoteType
			AND	CodQuote		= @CodQuote
			AND	QuoteRev		= @QuoteRev
        
		-- recupero dati!!
		SELECT	TOP 1 @CodItem	= ql.CodItem
					, @CodDiesGroup = tps.CodDiesGroup
                    , @CodPlant     = CASE WHEN @CodPlantFix <> '' THEN @CodPlantFix ELSE tps.CodPlant END
					, @HoleNum      = tps.HoleNum
					, @KeyAM	    = ql.KeyAM
					, @KeyAMI	    = ql.KeyAM + '-' + ISNULL(@CodPlant,'0000')
					, @KeyAMIL	    = ql.KeyAM + '-' + ISNULL(@CodPlant,'0000') + '-' + CAST(ISNULL(tps.HoleNum,0) AS NVARCHAR(10))
					, @ProdTeo	    = tps.ProdTeo
					, @ScTec	    = tps.ScTec
					, @KgTeo	    = tps.KgTeo
					, @NumSMED	    = tps.NumSMED
					, @RawMat	    = ql.RawMat
					, @BatchQty	    = ql.BatchQty
					, @ItemDescr    = i.ItemDescr
                    , @CodifProfilo = i.Class01
                    , @ClasseMerc   = i.Class02
                    , @CodClientAssoc = i.Class03

		FROM dbo.QuoteList ql 
        INNER JOIN dbo.TabProdSc tps ON ql.KeyAM = tps.KeyAM 
        INNER JOIN dbo.ItemDet i ON ql.CodItem = i.CodItem
		WHERE	ql.QuoteType	= @QuoteType
			AND	ql.CodQuote		= @CodQuote
			AND	ql.QuoteRev		= @QuoteRev
		ORDER BY tps.KgTeo DESC
		
        -- =================================================================================
		-- recupero dall'offerta il valore del PACKAGE/IMBALLO scelto e i dati relativi
        -- Secondo la logica Client-Item-Package ( vedi funzione )
        -- =================================================================================
        -- SET @CodPackag = ( SELECT dbo.f_getCodPackag( @CodItem , @CodClient ) )
        -- attenzione è una function tabellare
        SELECT @CodPackag = CodPackag, @PTotQta = TotQta, @PWeight = Weight, @PTare = Tare,
               @NumImb = NumImb, @PDurata = Durata, @PLiv = LivPackag , @PLivDett = LivPackagDet
        FROM f_getDataCodPackag ( @CodItem, @CodClient)

        -- e aggiorno il CodPackage in QuoteRM
		UPDATE	dbo.QuoteRM
            SET CodPackag = @CodPackag
		FROM dbo.QuoteRM
		WHERE	QuoteType		= @QuoteType
			AND	CodQuote		= @CodQuote
			AND	QuoteRev		= @QuoteRev

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		VALUES  ( @QuoteType, @CodQuote, @QuoteRev, '01', 'ItemDescr',      @ItemDescr )
            ,   ( @QuoteType, @CodQuote, @QuoteRev, '01', 'CodifProfilo',   @CodifProfilo )
            ,   ( @QuoteType, @CodQuote, @QuoteRev, '01', 'ClasseMerc',     @ClasseMerc ) 
            ,   ( @QuoteType, @CodQuote, @QuoteRev, '01', 'CodClientAssoc', @CodClientAssoc )

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT  @QuoteType, @CodQuote, @QuoteRev, '01', 'ClientNameAssoc', ClientDet.ClientName
        FROM dbo.ClientDet 
        WHERE ClientDet.CodClient = @CodClientAssoc
		
		-- INFORMAZIONI su MATRICE
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		VALUES (@QuoteType, @CodQuote, @QuoteRev, '01', 'CodDiesGroup', @CodDiesGroup )

		SET @strTemp = dbo.f_getSubstring(@CodDiesGroup, '-', 1) 
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		VALUES (@QuoteType, @CodQuote, @QuoteRev, '01', 'TipoDies', @strTemp) 

		SET @strTemp = dbo.f_getSubstring(@CodDiesGroup, '-', 2) 
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		VALUES (@QuoteType, @CodQuote, @QuoteRev, '01', 'DiamDies', @strTemp)
        
		SET @strTemp = dbo.f_getSubstring(@CodDiesGroup, '-', 3)
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		VALUES (@QuoteType, @CodQuote, @QuoteRev, '01', 'HoleNumDies', @strTemp)

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'NumDiesInList', COUNT(CodDies)
		FROM	dbo.DiesDet
		WHERE	CodDiesGroup = @CodDiesGroup AND CodItem = @CodItem

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'NumDiesExaust', COUNT(CodDies)
		FROM	dbo.DiesDet
		WHERE	CodDiesGroup = @CodDiesGroup AND Active = 0
			
		-- inserisco parametri calcolati x lavorazione estruzione
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		VALUES ( @QuoteType, @CodQuote, @QuoteRev, '01',  'CodPlant'  , @CodPlant )
               ,( @QuoteType, @CodQuote, @QuoteRev, '01', 'KeyAM'     , @KeyAM   )
               ,( @QuoteType, @CodQuote, @QuoteRev, '01', 'KeyAMIL'   , @KeyAMIL )
               ,( @QuoteType, @CodQuote, @QuoteRev, '01', 'NumSMED'   , CONVERT(NVARCHAR(100) , @NumSMED ) )
               ,( @QuoteType, @CodQuote, @QuoteRev, '01', 'KgTeo'     , CONVERT(NVARCHAR(100) , @KgTeo ) )

		-- inserisco lavorazione estrusione!
		INSERT INTO #QuoteWorkInt (QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, Class03, NetProd, WSR)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', @CodPlant, @KeyAM, @KeyAMIL, @RawMat, @ProdTeo, @ScTec

		INSERT INTO #QuoteParam (QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'KgProdotti', SUM(KgTeo)
		FROM	dbo.QuoteList ql 
		INNER JOIN dbo.TabProdSc tps ON ql.KeyAM = tps.KeyAM
		WHERE	ql.QuoteType	= @QuoteType
			AND	ql.CodQuote		= @CodQuote
			AND	ql.QuoteRev		= @QuoteRev
			
		-- inserisco dati mancanti di MSR/CSR (scarto cesoia x estrusione) - DSR è NULLO x estrusione!
		UPDATE	#QuoteWorkInt
		SET     MSR = rmd.CSR
		FROM	#QuoteWorkInt qwi
		INNER JOIN dbo.RawMatDet rmd ON qwi.Class03 = rmd.RawMat

		-- calcolo i costi legati alla fase estrusione!
		UPDATE	#QuoteWorkInt
		SET		FC4UG = (cp.FC * cp.QuotaPlantStd / cp.QuotaManStd) / qwi.NetProd
			  , VC4UG = (cp.VC * cp.QuotaPlantStd / cp.QuotaManStd) / qwi.NetProd
			  , OH4UG = (cp.OH * cp.QuotaPlantStd / cp.QuotaManStd) / qwi.NetProd
			  , SC4UG = cp.SC / ql.BatchQty
		FROM	#QuoteWorkInt qwi
		INNER JOIN dbo.Cost2Plant cp ON qwi.CodPlant = cp.CodPlant AND qwi.ProcessNum = cp.ProcessNum
		INNER JOIN dbo.QuoteList ql ON qwi.QuoteType = ql.QuoteType AND qwi.CodQuote = ql.CodQuote AND qwi.QuoteRev = ql.QuoteRev
        WHERE	qwi.ProcessNum = '01'

		-- inserisco lavorazione incestatura!
		INSERT INTO #QuoteWorkInt (QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, Class03)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '02', @CodPlant, @KeyAM, @KeyAMI, @RawMat
		
		-- inserisco dati mancanti di DSR x incestatura come 1 - OUT/IN
		UPDATE	#QuoteWorkInt
		SET		DSR = 1 - CAST(td.TotOUT AS DECIMAL(18,6))/CAST(td.TotIN AS DECIMAL(18,6))
		FROM	#QuoteWorkInt qwi
		INNER JOIN dbo.TabDifett td ON qwi.Class02 = td.KeyAMI AND qwi.ProcessNum = td.ProcessNum
		WHERE	qwi.ProcessNum = '02' -- solo incestatura
		
		-- inserisco lavorazione FORNO!
		INSERT INTO #QuoteWorkInt(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, Class03)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '03', @CodPlant, @KeyAM, @KeyAMI, @RawMat
		
		-- inserisco lavorazione imballo!
		INSERT INTO #QuoteWorkInt(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, Class03, Class04, Class05)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', @CodPlant, @KeyAM, @KeyAMIL, @RawMat, @CodItem, @KeyAMI

		UPDATE	qwi
		SET		NetProd = CASE @PDurata WHEN 0 THEN 0 ELSE @PTotQta / @PDurata END
		FROM	#QuoteWorkInt AS qwi
--		INNER JOIN dbo.TabImbArt ti ON qwi.Class04 = ti.KeyA
        WHERE	qwi.ProcessNum = '04' -- solo imballo

		-- parametro num imballatori
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', 'QuotaMan', @NumImb
		
		-- parametro Livello search package/imballo
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', 'LivPackage', @PLiv

		-- parametro Livello search package/imballo
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', 'LivPackageDett', @PLivDett

		-- calcolo i costi legati alla fase di imballo!
		UPDATE	#QuoteWorkInt
		SET		FC4UG = ( ( cp.FC * cp.QuotaPlantStd ) * ( @NumImb / cp.QuotaManStd ) ) / qwi.NetProd
			  , VC4UG = ( ( cp.VC * cp.QuotaPlantStd ) * ( @NumImb / cp.QuotaManStd ) ) / qwi.NetProd
			  , OH4UG = ( ( cp.OH * cp.QuotaPlantStd ) * ( @NumImb / cp.QuotaManStd ) ) / qwi.NetProd
			  , SC4UG = cp.SC / ql.BatchQty
		FROM	#QuoteWorkInt qwi
		INNER JOIN dbo.Cost2Plant cp ON qwi.CodPlant = cp.CodPlant AND qwi.ProcessNum = cp.ProcessNum
		INNER JOIN dbo.QuoteList ql ON qwi.QuoteType = ql.QuoteType AND qwi.CodQuote = ql.CodQuote AND qwi.QuoteRev = ql.QuoteRev
		WHERE	qwi.ProcessNum = '04' -- solo imballo

		-- inserisco dati mancanti di DSR x imballo come 1 - OUT/IN
		UPDATE	#QuoteWorkInt
		SET		DSR = 1 - CAST(td.TotOUT AS DECIMAL(18,6))/CAST(td.TotIN AS DECIMAL(18,6))
		FROM	#QuoteWorkInt qwi
		INNER JOIN dbo.TabDifett td ON qwi.Class05 = td.KeyAMI AND qwi.ProcessNum = td.ProcessNum 
		WHERE	qwi.ProcessNum = '04' -- solo imballo
		
		-- recupero le MAC fase 01
		SELECT	 @MAC_SC	= MCR
				,@MAC_ST	= WCR
		FROM	#QuoteWorkInt
		WHERE	ProcessNum  = '01'

		-- recupero le MAC fase 02
		SELECT	@MAC_IN	    = DCR
		FROM	#QuoteWorkInt
		WHERE   ProcessNum  = '02'

		-- recupero le MAC fase 04
		SELECT	@MAC_IM		= DCR
		FROM	#QuoteWorkInt
		WHERE	ProcessNum  = '04'
		
		-- calcolo percentuale vendita rottame
		SELECT	@SSR = SSR
		FROM	dbo.RawMatDet
		WHERE	RawMat = @RawMat
				

        -- NOTA :   la transazione posso probabilmente iniziarla qui visto che è il 
        --          primo Update/insert/delete su tabelle non temporanee delete a parte

		-- update rese RawMat!
		UPDATE	dbo.QuoteRM
		SET		FCR = @MAC_SC * @MAC_ST * @MAC_IN * @MAC_IM
		WHERE	QuoteType	= @QuoteType
			AND	CodQuote	= @CodQuote
			AND	QuoteRev	= @QuoteRev
			AND	RawMat		= @RawMat

		-- inserisco i costi delle utilities in QuoteOC
			
		-- inserisco altri costi x lavorazione estrusione! GAS ed EE
		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, TotQty, TotCost, Quota)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', @CodPlant, CodUtil, @RawMat, @BatchQty, UnitCost * @BatchQty, 1
		FROM	dbo.Utilities
		WHERE	CodPlant = @CodPlant
		

		/*************************************************************
		* MATRICE
		*
		* calcolo prezzo e durata matrice con procedura a 5 step...
		* A) media ponderata prezzo ed ExpLife da DiesDet selezionando x CodItem + CodDiesGroup 
		* B) EOLLife x media ponderata su DiesDet dove Active = 0 e vita cmq superiore 5000 KG ( escludendo rotture accidentali )
		* C) SE prezzo = 0 --> prendo prezzo da DiesGroupDet selezionando x CodDiesGroup
		* D) Se EOL = 0 --> prendo ExpLife della singola matrice, se è 0 --> prendo EOLLife da DiesGroupDet selezionando x CodDiesGroup
		* E) Calcolo Price / Life
		*
		*************************************************************/

		-- (A) da DiesDet
		SELECT	@DiesPrice		= SUM(ISNULL(Price, 0)   * ISNULL(ActLife, 1)) / SUM(ISNULL(ActLife, 1)), 
				@DiesExpLife	= SUM(ISNULL(ExpLife, 0) * ISNULL(ActLife, 1)) / SUM(ISNULL(ActLife, 1))
		FROM	dbo.DiesDet
		WHERE	CodItem			= @CodItem 
			AND	CodDiesGroup	= @CodDiesGroup
		GROUP BY CodItem, CodDiesGroup

		-- (B) da DiesDet
		SELECT	@DiesEOLife		= AVG( ISNULL(ActLife, 0))
		FROM	dbo.DiesDet
		WHERE	CodItem			= @CodItem 
			AND	CodDiesGroup	= @CodDiesGroup
			AND	Active			= 0              -- solo matrici rottamate
            AND ActLife         > 5000           -- solo se hanno Life > 5000 Kg ( non rotture accidentali )
		GROUP BY CodItem, CodDiesGroup
		
		SET	@DiesPrice		= ISNULL(@DiesPrice,0)
		SET	@DiesExpLife	= ISNULL(@DiesExpLife,0)
		SET	@DiesEOLife		= ISNULL(@DiesEOLife,0)

		-- (C) verifico se prezzo è OK...
		IF (@DiesPrice = 0)
		BEGIN
			-- calcolo da DiesGroupDet
			SELECT	@DiesPrice		= ISNULL(Price, 0)
			FROM	dbo.DiesGroupDet
			WHERE	CodDiesGroup	= @CodDiesGroup
		END
		
		-- (D) verifico se vita è OK...
		IF (@DiesEOLife = 0)
		BEGIN
			-- uso exp life articolo...
			SET	@DiesEOLife = @DiesExpLife
		END
		-- controllo che non sia nulla/vuota la durata...
		IF (@DiesEOLife = 0)
		BEGIN
			SELECT	@DiesEOLife = CASE WHEN EOLLife > 0 THEN EOLLife ELSE ExpLife END
			FROM	DiesGroupDet
			WHERE	CodDiesGroup	= @CodDiesGroup
		END

		-- controllo che non sia nulla/vuota la durata...
		IF ( @DiesEOLife > 0)
          BEGIN 
       		-- (E) Calcolo price/life!
		    SET	@DiesPriceLife = @DiesPrice / @DiesEOLife
          END
        ELSE 
		  BEGIN
			SET @DiesPriceLife = 0   -- metto a zero il DiesPriceLife
			SET @valid = 0           -- indico che valore non è valido  ( ND excel )
		  END
		
		-- inserisco costi per Matrice: costo e durata da matrice, se non ci sono da gruppo, (anche solo uno dei due, ovviamente più facile trovare durata x matrice...)
		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, TotQty, TotCost, Quota, valid)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', @CodPlant, 'MATRICE', @RawMat, @BatchQty, @DiesPriceLife * @BatchQty, 1, @valid

		-- inserisco parametri calcolati x matrice
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
        VALUES	( @QuoteType, @CodQuote, @QuoteRev, '01', 'DiesPrice',   CONVERT(NVARCHAR(100), @DiesPrice) )
               ,( @QuoteType, @CodQuote, @QuoteRev, '01', 'DiesExpLife', CONVERT(NVARCHAR(100), @DiesExpLife) )
               ,( @QuoteType, @CodQuote, @QuoteRev, '01', 'DiesEOLife',  CONVERT(NVARCHAR(100), @DiesEOLife) )

		/*************************************************************
		* VENDITA ROTTAME
		*
		* calcolo COSTO DI VENDITA PER LE 2 FASI ESTRUSIONE 01 ED IMBALLO 04
		* - calcolo costi variabili fase 01 / 04
		* - calcolo costo di vendita x fase 01 / 04
		*************************************************************/

		SELECT	@OCF01 = SUM(ISNULL(C4UG,0))
		FROM	#QuoteOC
			
		SELECT	@VCF01 = @OCF01 + VC4UG	
		FROM	#QuoteWorkInt
		WHERE	ProcessNum	= '01'
			
		SELECT	@VCF04 = @OCF01 + SUM(VC4UG)
		FROM	#QuoteWorkInt
			
		SELECT	@SellCostF01 = ((@MAC_ST * @MAC_SC * @MAC_IN) - 1) * (q.RawMatCost  + q.RawMatExtraCost - CASE WHEN SSVA > 0 THEN SSVA ELSE q.RawMatCost * SSVR END + @VCF01) -- ((prodotto delle MAC = inverso del prodotto delle rese) - 1) * (costo Al - prezzo rivendita + costi var fase 01)
			  , @RefCostF01  = -- ( (A - B) / 100 - C )
							   (
								-- (A) = (costo pieno di acquisto + costi fase 1) * MAC * 100 (IN CENTESIMI)
							   	((q.RawMatCost + q.RawMatExtraCost + @VCF01) * (@MAC_ST * @MAC_SC * @MAC_IN * 100))
								-- (B) = ((MAC * 100) - 100) * Resa di fonderia * (costo pieno acquisto - costo di trasformazione))
							  -	((@MAC_ST * @MAC_SC * @MAC_IN * 100) - 100) * rmd.ProcYield * (q.RawMatCost + q.RawMatExtraCost + @VCF01 - rmd.ProcCost)
							   ) / 100 -- divido per 100 finale
							    -- (C) = sottraggo costo pieno alluminio
							  - (q.RawMatCost + q.RawMatExtraCost + @VCF01)
		FROM	dbo.RawMatDet rmd 
		INNER JOIN dbo.QuoteRM q ON q.RawMat = rmd.RawMat
		WHERE	q.QuoteType	= @QuoteType
			AND	q.CodQuote	= @CodQuote
			AND	q.QuoteRev	= @QuoteRev
			AND	q.RawMat	= @RawMat
			
		SELECT	@SellCostF04 = ((@MAC_IM) - 1) * (q.RawMatCost  + q.RawMatExtraCost - CASE WHEN SSVA > 0 THEN SSVA ELSE q.RawMatCost * SSVR END + @VCF01 + @VCF04) -- ((prodotto delle MAC = inverso del prodotto delle rese) - 1) * (costo Al - prezzo rivendita + costi var fase 04)
			  , @RefCostF04  = -- ( (A - B) / 100 - C )
							   (
								-- (A) = (costo pieno di acquisto + costi variabili fase 1 e 4) * MAC * 100 (IN CENTESIMI)
							   	((q.RawMatCost + q.RawMatExtraCost + @VCF01 + @VCF04) * (@MAC_IM * 100))
								-- (B) = ((MAC * 100) - 100) * Resa di fonderia * (costo pieno acquisto - costo di trasformazione))
							  -	((@MAC_IM * 100) - 100) * rmd.ProcYield * (q.RawMatCost + q.RawMatExtraCost + @VCF01 + @VCF04 - rmd.ProcCost)
							   ) / 100 -- divido per 100 finale
							    -- (C) = sottraggo costo pieno alluminio
							  - (q.RawMatCost + q.RawMatExtraCost + @VCF01 + @VCF04)

							  -- NOTA: usiamo (q.RawMatCost + q.RawMatExtraCost + @VCF01) e non (q.RawMatCost + q.RawMatExtraCost + @VCF01 + @RefCostF01) perché la differenza è minimale, si tratta di 10/20 PPM...

		FROM	dbo.RawMatDet rmd 
        INNER JOIN dbo.QuoteRM q ON q.RawMat = rmd.RawMat
		WHERE	q.QuoteType	= @QuoteType
			AND	q.CodQuote	= @CodQuote
			AND	q.QuoteRev	= @QuoteRev
			AND	q.RawMat	= @RawMat
		
		-- inserisco costi per VENDITA
		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, TotQty, TotCost, Quota)
		VALUES ( @QuoteType, @CodQuote, @QuoteRev, '01', @CodPlant, 'VENDITA', @RawMat, @BatchQty, @SellCostF01 * @BatchQty, @SSR )
		-- inserisco costi per ROTTAME
              ,( @QuoteType, @CodQuote, @QuoteRev, '01', @CodPlant, 'ROTTAME', @RawMat, @BatchQty, @RefCostF01 * @BatchQty, 1 - @SSR )
		-- inserisco costi per VENDITA
              ,( @QuoteType, @CodQuote, @QuoteRev, '04', @CodPlant, 'VENDITA', @RawMat, @BatchQty, @SellCostF04 * @BatchQty, @SSR )
		-- inserisco costi per ROTTAME
		      ,( @QuoteType, @CodQuote, @QuoteRev, '04', @CodPlant, 'ROTTAME', @RawMat, @BatchQty, @RefCostF04 * @BatchQty, 1 - @SSR )
	
	    -- calcolo Package Cost e RMWeight da tab PackageDet
        -- EXEC stp_packageCost @CodItem, @CodClient, @CodPackag, @PDesc=@PkgDesc OUTPUT, @RMWeight=@PRMWeight OUTPUT, @Weight=@PWeight OUTPUT, @Tare=@PTare OUTPUT, @PackCost=@PCost OUTPUT, @TareStRat=@PTareStRatio OUTPUT
        -- stored sostituita perchè la maggior parte dei calcoli li ho già fatti
	    SELECT	@PCost          = RMCost / @PWeight 
              , @PRMWeight      = RMWeight
              , @PkgDesc        = PackagDesc
              , @PTareStRatio   = ( RMWeight - @PTare) / @PWeight
	    FROM	dbo.PackagDet
	    WHERE	CodPackag = @CodPackag

		-- inserisco costi per IMBALLO
		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01,  Class02, TotQty, TotCost, Quota)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', @CodPlant, 'IMBALLO', @RawMat, @BatchQty, @PCost * @BatchQty, 1

		-- inserisco parametri calcolati x imballaggio
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		VALUES   ( @QuoteType, @CodQuote, @QuoteRev, '04', 'PkgDesc',                            @PkgDesc )
		        ,( @QuoteType, @CodQuote, @QuoteRev, '04', 'PRMWeight',   CONVERT(NVARCHAR(100), @PRMWeight ) )
		        ,( @QuoteType, @CodQuote, @QuoteRev, '04', 'PWeight',     CONVERT(NVARCHAR(100), @PWeight ) ) 
		        ,( @QuoteType, @CodQuote, @QuoteRev, '04', 'PTare',       CONVERT(NVARCHAR(100), @PTare) )
                ,( @QuoteType, @CodQuote, @QuoteRev, '04', 'TareStRatio', CONVERT(NVARCHAR(100), @PTareStRatio ) )
		
		
		---------------------------------------------	
		-- inserisco costi per TRASPORTI
		---------------------------------------------
		-- recupero zona da cliente...
		SELECT	@TranspZone = TranspZone
		FROM	dbo.ClientDet	
		WHERE	CodClient	= @CodClient

		-- recupero tipo di trasporto
		SELECT	@HasTC = ISNULL(i.HasTC, 0)
		FROM	dbo.QuoteList q INNER JOIN Incoterms i ON q.CodInco = i.CodInco
		WHERE	q.QuoteType	= @QuoteType
			AND	q.CodQuote	= @CodQuote
			AND	q.QuoteRev	= @QuoteRev

		-- recupero costi trasporto
		SELECT	@TranspCost = TranspCost
		FROM	dbo.TranspCostDet
		WHERE	TranspZone	= @TranspZone

		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01,  Class02, TotQty, TotCost, Quota)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', @CodPlant, 'TRASPORTI', @RawMat, @BatchQty, @HasTC * @TranspCost * @BatchQty, 1

		
		---------------------------------------------	
		-- inserisco costi per PROVVIGIONI
		---------------------------------------------
		SELECT	@Provvig = ISNULL(a.QuotaProvvAg, 0)
		FROM	dbo.AgentsDet a
		INNER JOIN ClientDet c ON a.CodAg = c.CodAg
		INNER JOIN QuoteList q ON q.CodClient = c.CodClient
		WHERE	q.QuoteType	= @QuoteType
			AND	q.CodQuote	= @CodQuote
			AND	q.QuoteRev	= @QuoteRev

		-- inserisco costi per PROVVIGIONI
		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01,  Class02, TotQty, TotCost, Quota)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', @CodPlant, 'PROVVIGIONI', @RawMat, @BatchQty, @Provvig * @BatchQty, 1

        /* ==================================================
             CARICO TABELLE EFFETTIVE
           ==================================================*/

		-- carico quote parametri!
		INSERT dbo.QuoteParam
		SELECT * FROM #QuoteParam

		-- carico lavorazioni INTERNE!
		INSERT dbo.QuoteWorkInt  -- ci sono valori calcolati quindi devo selezionare i campi
		SELECT QuoteType, CodQuote, QuoteRev, NumWI, ProcessNum, CodPlant, Class01, Class02, Class03, Class04, Class05
             , NetProd, WSR, MSR, DSR, FC4UG, VC4UG, OH4UG, SC4UG, valid 
        FROM #QuoteWorkInt

		-- carico OTHERCOSTS
		INSERT dbo.QuoteOC  -- ci sono valori calcolati quindi devo selezionare i campi
		SELECT QuoteType, CodQuote, QuoteRev, NumEx, ProcessNum, CodPlant, Class01, Class02, Class03, Class04
             , Class05, TotQty, TotCost, Quota, valid
        FROM #QuoteOC

	COMMIT TRAN;
	
	--SELECT * FROM #QuoteParam
	--SELECT * FROM #QuoteWorkInt
	--SELECT * FROM #QuoteOC

	-- elimino temp table...
	IF OBJECT_ID('tempdb..#QuoteParam') IS NOT NULL
		DROP TABLE #QuoteParam
    IF OBJECT_ID('tempdb..#QuoteWorkInt') IS NOT NULL
		DROP TABLE #QuoteWorkInt
    IF OBJECT_ID('tempdb..#QuoteOC') IS NOT NULL
		DROP TABLE #QuoteOC

END










