-- dbo.ep_Vyroba_GenObjednavkuMatDoVyrobyNew
CREATE PROCEDURE dbo.ep_Vyroba_GenObjednavkuMatDoVyrobyNew
      @errMsg NVARCHAR(500)=N'' OUT
AS

-- HD Consulting Strakonice, T. Buzin
-- !! proceduru neupravujte, bude stejne pregenerovana pri spusteni pluginu Pekarna nebo pri startu Windows sluzby HDCDZApi !!

SET NOCOUNT ON


DECLARE
 @tranPred INT,
 @cnt INT,
 @iTemp INT

DECLARE
 @idObj INT,
 @druhPohybuZbo TINYINT=9,
 @radaExpPr NVARCHAR(3)=N'550',
 @doklVydPrevod NVARCHAR(3)=N'281',
 @idExpPrMat INT,
 @idExpPrPolo INT,

 @radaDokl NVARCHAR(3),
 @cilovySklad NVARCHAR(30),
 @radaPrijem NVARCHAR(3),
 @druhPohybuZboPrijem TINYINT,
 @idDoklad INT,
 @datumDokladuMat DATETIME,
 @datumDokladuFin DATETIME,
 @genDokladMat BIT=0,
 @idDokladMat INT,
 @genDokladFin BIT=0,
 @idDokladFin INT,
 @cOrg INT=0,
 @dzMena NVARCHAR(3),
 @dzKurz NUMERIC(19,6),
 @dzKurzEur NUMERIC(19,6),
 @jednM INT,
 @vstC TINYINT,
 @idPohyb INT,
 @idPZ INT,
 @idVCS INT,
 @idVCP INT,
 @idZboSklad INT,
 @idKmen INT,
 @sz NVARCHAR(3),
 @rc NVARCHAR(30),
 @sarze NVARCHAR(100),
 @paletList NVARCHAR(100),
 @sklMatHlavni NVARCHAR(30),  -- 311
 @sklPekarna NVARCHAR(30),    -- 211
 @sklTechnolog NVARCHAR(30),  -- 261
 @skladFin NVARCHAR(30),      -- 312
 @mnoz NUMERIC(19,6),
 @mnozVydano NUMERIC(19,6),
 @material BIT,
 @idPHIdent BIGINT,
 @idPHIdent2 BIGINT,
 @textDoPoznamky NVARCHAR(max)=NULL


IF OBJECT_ID(N'tempdb..#VyrobaGenObjednavkuMatDoVyrobyNew', N'U') IS NOT NULL
 SELECT TOP(1) @sklMatHlavni=SkladMaterial, @skladFin=SkladVyrobky
   FROM #VyrobaGenObjednavkuMatDoVyrobyNew


IF (@sklMatHlavni IS NULL)
 SELECT TOP(1) @sklMatHlavni=Cislo FROM dbo.TabStrom WHERE Nazev=N'Hlavní sklad - Materiál' AND CisloStr LIKE N'3%'
IF (@sklTechnolog IS NULL)
 SELECT TOP(1) @sklTechnolog=Cislo FROM dbo.TabStrom WHERE Nazev LIKE N'Technolog%NEÚČ%' AND Nazev NOT LIKE N'%polotov%' AND CisloStr LIKE N'2%'
IF (@sklPekarna IS NULL)
 SELECT TOP(1) @sklPekarna=Cislo FROM dbo.TabStrom WHERE Nazev LIKE N'Výroba - Pekárna' AND CisloStr LIKE N'2%'

SET @sklPekarna = ISNULL(@sklPekarna, N'')
IF (@sklPekarna=N'')
 SET @sklPekarna = N'211'

SET @sklMatHlavni = ISNULL(@sklMatHlavni, N'')
IF (@sklMatHlavni=N'')
 SET @sklMatHlavni = N'311'

SET @skladFin = ISNULL(@skladFin, N'')
IF (@skladFin=N'')
 SET @skladFin = N'312'



MERGE dbo._TabVyroba_Objednavky AS T
 USING dbo.TabKmenZbozi AS S ON (S.ID=T.IDKmenZbozi)
 WHEN MATCHED AND T.JeMaterial IS NULL THEN UPDATE SET T.JeMaterial=S.Material;
DELETE FROM dbo._TabVyroba_Objednavky_Pol WHERE IDPohybOZ NOT IN (SELECT ID FROM dbo.TabPohybyZbozi WITH(NOLOCK))




SET @genDokladMat=0
IF EXISTS (SELECT 1 FROM dbo._TabVyroba_Objednavky o WHERE o.Splneno=0 AND o.OdmitnutoSkladem=0 AND o.NocniObjednavka=0 AND o.Storno=0 AND o.Vratka=0
            AND o.JeMaterial=1 AND o.Blokovano=0 AND (o.Mnozstvi-ISNULL( (SELECT SUM(Mnozstvi) FROM dbo._TabVyroba_Objednavky_Pol WHERE IDHlava=o.ID), 0))>0
            AND DATEDIFF(day, o.DatPorizeni, GETDATE())<6
          )
 BEGIN
  SET @genDokladMat=1
  SET @datumDokladuMat = (SELECT MIN(o.DatPorizeni) FROM dbo._TabVyroba_Objednavky o WHERE o.Splneno=0 AND o.OdmitnutoSkladem=0 AND o.NocniObjednavka=0 AND o.Storno=0 AND o.Vratka=0
                           AND o.JeMaterial=1 AND o.Blokovano=0 AND (o.Mnozstvi-ISNULL( (SELECT SUM(Mnozstvi) FROM dbo._TabVyroba_Objednavky_Pol WHERE IDHlava=o.ID), 0))>0
                           AND DATEDIFF(day, o.DatPorizeni, GETDATE())<6
                          )
 END
SET @datumDokladuMat = ISNULL(@datumDokladuMat, GETDATE())



SET @genDokladFin=0
IF EXISTS (SELECT 1 FROM dbo._TabVyroba_Objednavky o WHERE o.Splneno=0 AND o.OdmitnutoSkladem=0 AND o.NocniObjednavka=0 AND o.Storno=0 AND o.Vratka=0
            AND o.JeMaterial=0 AND o.Blokovano=0 AND (o.Mnozstvi-ISNULL( (SELECT SUM(Mnozstvi) FROM dbo._TabVyroba_Objednavky_Pol WHERE IDHlava=o.ID), 0))>0
            AND DATEDIFF(day, o.DatPorizeni, GETDATE())<6
          )
 BEGIN
  SET @genDokladFin=1
  SET @datumDokladuFin = (SELECT MIN(o.DatPorizeni) FROM dbo._TabVyroba_Objednavky o WHERE o.Splneno=0 AND o.OdmitnutoSkladem=0 AND o.NocniObjednavka=0 AND o.Storno=0 AND o.Vratka=0
                           AND o.JeMaterial=0 AND o.Blokovano=0 AND (o.Mnozstvi-ISNULL( (SELECT SUM(Mnozstvi) FROM dbo._TabVyroba_Objednavky_Pol WHERE IDHlava=o.ID), 0))>0
                           AND DATEDIFF(day, o.DatPorizeni, GETDATE())<6
                         )
 END
SET @datumDokladuFin = ISNULL(@datumDokladuFin, GETDATE())





IF (@genDokladMat=1) OR (@genDokladFin=1)
 BEGIN

  DECLARE m CURSOR LOCAL FAST_FORWARD FOR
   SELECT DISTINCT(JeMaterial)
    FROM dbo._TabVyroba_Objednavky
    WHERE Splneno=0
      AND OdmitnutoSkladem=0
      AND NocniObjednavka=0
      AND Storno=0
      AND Vratka=0
      AND Blokovano=0
      AND IDPhIdent2 IS NOT NULL
      AND DATEDIFF(day, DatPorizeni, GETDATE())<6
    GROUP BY JeMaterial
  OPEN m
  WHILE (1=1)
   BEGIN
    FETCH NEXT FROM m INTO @material
    IF (@@FETCH_STATUS<>0) BREAK

    IF (@material=0)
     BEGIN
      SET @cilovySklad=@skladFin
      SET @cnt = ISNULL( (SELECT COUNT(d.ID) FROM dbo.TabDokladyZbozi d WITH(NOLOCK) WHERE d.PoradoveCislo>0 AND d.DruhPohybuZbo=@druhPohybuZbo AND d.IDSklad=@cilovySklad
                           AND d.BlokovaniEditoru IS NULL AND d.RadaDokladu=@radaExpPr AND d.Splneno=0 AND d.StavRezervace<>N'X'
                           AND CAST(d.DatPorizeni AS DATE)=CAST(@datumDokladuFin AS DATE)
                         ), 0)
      IF (@cnt=0)
       EXEC dbo.hp_InsertHlavickyOZ @Ident=@idExpPrPolo OUT, @Sklad=@cilovySklad, @DruhPohybu=@druhPohybuZbo, @RadaDokladu=@radaExpPr, @CisloOrg=@cOrg, @DatumPorizeni=@datumDokladuFin
      IF (@cnt=1)
        SET @idExpPrPolo = (SELECT d.ID FROM dbo.TabDokladyZbozi d WHERE d.PoradoveCislo>0 AND d.DruhPohybuZbo=@druhPohybuZbo AND d.IDSklad=@cilovySklad
                             AND d.BlokovaniEditoru IS NULL AND d.RadaDokladu=@radaExpPr AND d.Splneno=0 AND d.StavRezervace<>N'X'
                             AND CAST(d.DatPorizeni AS DATE)=CAST(@datumDokladuFin AS DATE)
                           )
      IF (@cnt>1)
       SET @idExpPrPolo = (SELECT TOP(1) d.ID FROM dbo.TabDokladyZbozi d WHERE d.PoradoveCislo>0 AND d.DruhPohybuZbo=@druhPohybuZbo AND d.IDSklad=@cilovySklad
                            AND d.BlokovaniEditoru IS NULL AND d.RadaDokladu=@radaExpPr AND d.Splneno=0 AND d.StavRezervace<>N'X' ORDER BY d.DatPorizeni DESC)
      IF NOT EXISTS (SELECT 1 FROM dbo.TabDokladyZbozi_EXT WHERE ID=@idExpPrPolo)
       INSERT dbo.TabDokladyZbozi_EXT (ID) VALUES (@idExpPrPolo)
      UPDATE dbo.TabDokladyZbozi_EXT SET _Vyroba_ObjednavkaMat_Typ=2, _Vydej_ObjednavkaMat=1 WHERE ID=@idExpPrPolo
      SET @idDoklad = @idExpPrPolo
     END

    IF (@material=1)
     BEGIN
      SET @cilovySklad=@sklMatHlavni
      SET @cnt = ISNULL( (SELECT COUNT(d.ID) FROM dbo.TabDokladyZbozi d WHERE d.PoradoveCislo>0 AND d.DruhPohybuZbo=@druhPohybuZbo AND d.IDSklad=@cilovySklad
                           AND d.BlokovaniEditoru IS NULL AND d.RadaDokladu=@radaExpPr AND d.Splneno=0 AND d.StavRezervace<>N'X'
                           AND CAST(d.DatPorizeni AS DATE)=CAST(@datumDokladuMat AS DATE)
                         ), 0)
      IF (@cnt=0)
       EXEC dbo.hp_InsertHlavickyOZ @Ident=@idExpPrMat OUT, @Sklad=@cilovySklad, @DruhPohybu=@druhPohybuZbo, @RadaDokladu=@radaExpPr, @CisloOrg=@cOrg, @DatumPorizeni=@datumDokladuMat
      IF (@cnt=1)
       SET @idExpPrMat = (SELECT d.ID FROM dbo.TabDokladyZbozi d WHERE d.PoradoveCislo>0 AND d.DruhPohybuZbo=@druhPohybuZbo AND d.IDSklad=@cilovySklad
                           AND d.BlokovaniEditoru IS NULL AND d.RadaDokladu=@radaExpPr AND d.Splneno=0 AND d.StavRezervace<>N'X'
                           AND CAST(d.DatPorizeni AS DATE)=CAST(@datumDokladuMat AS DATE)
                          )
      IF (@cnt>1)
       SET @idExpPrMat = (SELECT TOP(1) d.ID FROM dbo.TabDokladyZbozi d WHERE d.PoradoveCislo>0 AND d.DruhPohybuZbo=@druhPohybuZbo AND d.IDSklad=@cilovySklad
                           AND d.BlokovaniEditoru IS NULL AND d.RadaDokladu=@radaExpPr AND d.Splneno=0 AND d.StavRezervace<>N'X' ORDER BY d.DatPorizeni DESC)
      
      IF NOT EXISTS (SELECT 1 FROM dbo.TabDokladyZbozi_EXT WHERE ID=@idExpPrMat)
       INSERT dbo.TabDokladyZbozi_EXT (ID) VALUES (@idExpPrMat)
      UPDATE dbo.TabDokladyZbozi_EXT SET _Vyroba_ObjednavkaMat_Typ=1, _Vydej_ObjednavkaMat=1 WHERE ID=@idExpPrMat
      SET @idDoklad = @idExpPrMat
     END

    IF (@idDoklad IS NOT NULL)
     BEGIN
      UPDATE dbo.TabDokladyZbozi SET IDSkladPrevodu=@sklPekarna WHERE ID=@idDoklad AND IDSkladPrevodu IS NULL
      UPDATE dbo.TabDokladyZbozi SET TypPrevodky=@doklVydPrevod WHERE ID=@idDoklad AND TypPrevodky IS NULL

      SELECT @dzMena=Mena, @dzKurz=Kurz, @dzKurzEur=KurzEuro, @vstC=VstupniCena, @jednM=JednotkaMeny
        FROM dbo.TabDokladyZbozi WHERE ID=@idDoklad

      DECLARE c CURSOR LOCAL FOR
       SELECT ID, SkupZbo, RegCis, IDKmenZbozi, Mnozstvi, PaletovyList, Sarze, IdPHIdent, IdPHIdent2
        FROM dbo._TabVyroba_Objednavky
        WHERE Splneno=0
          AND OdmitnutoSkladem=0
          AND NocniObjednavka=0
          AND Storno=0
          AND Vratka=0
          AND Blokovano=0
          AND IDPhIdent2 IS NOT NULL
          AND JeMaterial=@material
          AND DATEDIFF(day, DatPorizeni, GETDATE())<6
        ORDER BY DatPorizeni
      OPEN c
      WHILE (1=1)
       BEGIN
        FETCH NEXT FROM c INTO @idObj, @sz, @rc, @idKmen, @mnoz, @paletList, @sarze, @idPHIdent, @idPHIdent2
        IF (@@FETCH_STATUS<>0) BREAK

        IF (@idKmen IS NULL)
         SET @idKmen = (SELECT ID FROM dbo.TabKmenZbozi WHERE SkupZbo=@sz AND RegCis=@rc)

        SET @mnozVydano = ISNULL( (SELECT SUM(Mnozstvi) FROM dbo._TabVyroba_Objednavky_Pol WHERE IDHlava=@idObj), 0)
        SET @mnoz = @mnoz - @mnozVydano

        IF (@mnoz>0)
         BEGIN
          SET @idZboSklad = NULL
          IF (@material=0)
           SET @idZboSklad = (SELECT ID FROM dbo.TabStavSkladu WHERE IDKmenZbozi=@idKmen AND IDSklad=@skladFin)
          ELSE
            SET @idZboSklad = (SELECT ID FROM dbo.TabStavSkladu WHERE IDKmenZbozi=@idKmen AND IDSklad=@sklMatHlavni)
          IF (@idZboSklad IS NULL)
           BEGIN
            IF (@material=0)
              EXEC dbo.hp_InsertStavSkladu @IDKmen=@idKmen, @IDSklad=@skladFin, @IDZboSklad=@idZboSklad OUT
             ELSE
              EXEC dbo.hp_InsertStavSkladu @IDKmen=@idKmen, @IDSklad=@sklMatHlavni, @IDZboSklad=@idZboSklad OUT
           END -- @idZboSklad IS NULL
          IF (@idZboSklad IS NOT NULL)
               AND NOT EXISTS (SELECT 1 FROM dbo.TabPohybyZbozi p WITH(NOLOCK) JOIN dbo.TabPohybyZbozi_EXT pe WITH(NOLOCK) ON (pe.ID=p.ID)
                                WHERE p.IDDoklad=@idDoklad AND p.IDZboSklad=@idZboSklad AND pe._Vyroba_Sarze=@sarze AND pe._Vyroba_PaletList=@paletList AND pe._HDCAPI_PHident=@idPHIdent2)
           BEGIN
            EXEC dbo.hp_InsertPolozkyOZ @Ident=@idPZ OUT, @IDDoklad=@idDoklad, @DruhPohybu=@druhPohybuZbo, @CisloOrg=@cOrg, @IDZboSklad=@idZboSklad,
                                        @Mena=@dzMena, @Kurz=@dzKurz, @KurzEuro=@dzKurzEur, @JednotkaMeny=@jednM, @SazbaSD=NULL, @SazbaDPH=NULL,
                                        @ZakazanoDPH=0, @VstupniCena=@vstC, @PovolitDuplicitu=1, @Mnozstvi=@mnoz
            IF (@idPZ IS NOT NULL)
             BEGIN
              IF NOT EXISTS (SELECT 1 FROM dbo.TabPohybyZbozi_EXT WHERE ID=@idPZ)
               INSERT dbo.TabPohybyZbozi_EXT (ID) VALUES (@idPZ)

              SET @paletList = ISNULL(@paletList, N'')
              SET @sarze = ISNULL(@sarze, N'')
              UPDATE dbo.TabPohybyZbozi_EXT SET _Vyroba_PaletList=@paletList, _Vyroba_Sarze=@sarze, _Vyroba_IDObjednavkaMat=@idObj, _HDCAPI_PHident=@idPHIdent2
                WHERE ID=@idPZ

              SET @idVCS = NULL
              IF (@material=0) -- prevadej realna VC jen u dilcu (finaly+polotovary)
               BEGIN
                SET @idVCS = (SELECT ID FROM dbo.TabVyrCS WHERE IDStavSkladu=@idZboSklad AND Nazev1=@paletList)
                IF (@idVCS IS NULL)
                 BEGIN
                  SELECT @iTemp = 1 + ISNULL( (SELECT MAX(ID) FROM dbo.TabVyrCS), 0)
                  DBCC CHECKIDENT (TabVyrCS, RESEED, @iTemp)
                  EXEC dbo.hp_OZInsertVyrCS @IDVyrCS=@idVCS OUT, @IDZboSklad=@idZboSklad, @Nazev1=@paletList
                 END

                SET @idVCP = NULL
                IF (@idVCS IS NOT NULL)
                 BEGIN
                  SELECT @iTemp = 1 + ISNULL( (SELECT MAX(ID) FROM dbo.TabVyrCP), 0)
                  DBCC CHECKIDENT (TabVyrCP, RESEED, @iTemp)
                  INSERT dbo.TabVyrCP (IDPolozkaDokladu, IDVyrCis, Nazev, Mnozstvi) SELECT @idPZ, @idVCS, @sarze, @mnoz
                  SET @idVCP = SCOPE_IDENTITY()
                 END
               END -- @material=0

              INSERT dbo._TabVyroba_Objednavky_Pol (IDHlava, IDDokladOZ, IDPohybOZ, Mnozstvi, Sarze, PaletovyList, SkupZbo, RegCis, IDVyrCP)
               SELECT @idObj, @idDoklad, @idPZ, @mnoz, @sarze, @paletList, @sz, @rc, @idVCP

              IF (@paletList<>'')
               SET @textDoPoznamky = N'PL: ' + @paletList
              IF (@sarze<>N'')
               IF (ISNULL(@textDoPoznamky,N'')=N'')
                 SET @textDoPoznamky = N'šarze: ' + @sarze
                ELSE
                 SET @textDoPoznamky = @textDoPoznamky + N' / šarze: ' + @sarze
              SET @textDoPoznamky = TRIM(@textDoPoznamky)
              IF (@textDoPoznamky=N'')
               SET @textDoPoznamky = NULL
              UPDATE dbo.TabPohybyZbozi SET Poznamka=@textDoPoznamky WHERE ID=@idPZ
             END  -- @idPZ IS NOT NULL
           END  -- @idZboSklad IS NOT NULL
         END  -- @mnoz>0

       END
      CLOSE c
      DEALLOCATE c

     END  -- @idDoklad IS NOT NULL

   END
  CLOSE m
  DEALLOCATE m
  
 END  -- mam neco k zapsani ?




IF OBJECT_ID(N'dbo.ep_Vyroba_GenObjednavkuMatDoVyrobyNew2', 'P') IS NOT NULL
 EXEC dbo.ep_Vyroba_GenObjednavkuMatDoVyrobyNew2 @idDoklad



-- oznac splnene polozky
DECLARE c CURSOR LOCAL FAST_FORWARD FOR
 SELECT ID, Mnozstvi
  FROM dbo._TabVyroba_Objednavky
  WHERE Splneno=0
    AND Vratka=0
    AND Storno=0
    AND OdmitnutoSkladem=0
    AND DATEDIFF(day, DatPorizeni, GETDATE())<14
    AND ID IN (SELECT 1 FROM dbo._TabVyroba_Objednavky_Pol p WITH(NOLOCK) WHERE p.IDHlava=ID)
OPEN c
WHILE (1=1)
 BEGIN
  FETCH NEXT FROM c INTO @idObj, @mnoz
  IF (@@FETCH_STATUS<>0) BREAK

  SET @mnozVydano = ISNULL( (SELECT SUM(op.Mnozstvi) FROM dbo._TabVyroba_Objednavky_Pol op WITH(NOLOCK) JOIN dbo.TabPohybyZbozi p WITH(NOLOCK) ON (p.ID=op.IDPohybOZ)
                              WHERE op.IDHlava=@idObj AND p.SkutecneDatReal IS NOT NULL), 0)
  IF (@mnoz=@mnozVydano)
   UPDATE dbo._TabVyroba_Objednavky SET Splneno=1 WHERE ID=@idObj

 END
CLOSE c
DEALLOCATE c

