-- dbo.ep_HDCDZApi_ZpracujPrijataData
CREATE PROCEDURE dbo.ep_HDCDZApi_ZpracujPrijataData
      @idJson INT=NULL
AS

SET NOCOUNT ON
-- ! proceduru neupravujte, bude stejne pregenerovana pri startu Windows sluzby HDCDZApi !


DECLARE
 @errMsg NVARCHAR(500)=N'',
 @errProc NVARCHAR(100),
 @tranPred INT,
 @iChyba INT,
 @debugXML XML

DECLARE
 @operJson NVARCHAR(max),
 @prikJson NVARCHAR(max),
 @objekt NVARCHAR(50),
 @akce NVARCHAR(50),
 @trida NVARCHAR(50),
 @statusOp NVARCHAR(50),
 @typOperJson NVARCHAR(50),
 @jsonString NVARCHAR(max),
 @cisZam INT,
 @idZam INT,
 @idVPr INT,
 @idVCPrik INT,
 @vc NVARCHAR(100),
 @dokl INT,
 @alt NCHAR(1),
 @idPrP INT,
 @idPrPOdv INT,
 @doklOdv INT,
 @doklNew INT,
 @doklAutomat INT,
 @altAutomat NCHAR(1),
 @jeOdvadeci BIT=0,
 @datStart DATETIME,
 @datKonec DATETIME,
 @skCasSek INT,
 @mnoz NUMERIC(19,6),
 @idPrednaOp INT,
 @idPrednaOpOdv INT,
 @operPrednaOdv NVARCHAR(4),
 @operPrednaPrac INT,
 @typOper TINYINT,
 @idPrac INT,
 @idPracOld INT,
 @idStroj INT,
 @nazevOp NVARCHAR(100),
 @operPredna NVARCHAR(4),
 @odvadeciPredna BIT=0,
 @cisOper INT,
 @cisOperMax INT,
 @operMax NVARCHAR(4),
 @nazevOpMax NVARCHAR(100),
 @idKoop INT,
 @idEvidROp INT,
 @idEvidROpPol INT,
 @idMzdy INT,
 @idPrednaOpAutomat INT,
 @operPrednaOpAutomat NVARCHAR(4),
 @casSekOperPredaAutomat INT,
 @idMzdyAutomat INT,
 @datKonecOp DATETIME,
 @ksZive NUMERIC(19,6),
 @ksEvid NUMERIC(19,6)

DECLARE
 @idDZ INT,
 @sz NVARCHAR(3),
 @rc NVARCHAR(30),
 @idKZ INT,
 @idPrKVazby INT,
 @idDilec INT,
 @mnozstviPomer_A NUMERIC(19,6),
 @mnozstviPomer_B NUMERIC(19,6),
 @idGenVydejPrednaPol INT,
 @sklProVydej NVARCHAR(30)



DROP TABLE IF EXISTS #TabJSONData
CREATE TABLE #TabJSONData (ID INT IDENTITY(1,1) NOT NULL, doc NVARCHAR(max) )


DROP TABLE IF EXISTS #HDCTabPrKVazbyGen_IDMzdyPredna
CREATE TABLE #HDCTabPrKVazbyGen_IDMzdyPredna (IDPrikaz int, Doklad int, IDMzdy int) 


DROP TABLE IF EXISTS #HDCTabPrKVazbyGenPredna
CREATE TABLE #HDCTabPrKVazbyGenPredna (
 ID INT IDENTITY NOT NULL,
 Generuj BIT NOT NULL DEFAULT 1,
 PoKorekciDat BIT NOT NULL DEFAULT 0,
 IDPrKV INT NOT NULL,
 Doklad INT NOT NULL,
 IDPrikaz INT NOT NULL,
 Prednastaveno BIT NOT NULL DEFAULT 1,
 Sklad NVARCHAR(30) NULL,
 VyrStredisko NVARCHAR(30) NULL,
 IDPracoviste INT NULL,
 mnoz_zad NUMERIC(19,6) NOT NULL DEFAULT 0,
 Mnoz_nepotrebne NUMERIC(19,6) NOT NULL DEFAULT 0,
 Mnoz_skut_realizovane NUMERIC(19,6) NOT NULL DEFAULT 0,
 Cena_real NUMERIC(19,6) NOT NULL DEFAULT 0,
 Mnoz_odv NUMERIC(19,6) NOT NULL DEFAULT 0,
 Cena_odv NUMERIC(19,6) NOT NULL DEFAULT 0,
 MnozstviMax NUMERIC(19,6) NULL,
 PuvodniMnozstviPoz NUMERIC(19,6) NULL,
 MnozstviPoz NUMERIC(19,6) NOT NULL,
 PomMnozPoz NUMERIC(19,6) NOT NULL DEFAULT 0,
 IDPohZbo INT NULL,
 PoznamkaNaDoklad NTEXT NULL,
 priorita INT NOT NULL DEFAULT 0,
 vyssi INT NOT NULL,
 nizsi INT NOT NULL,
 DavkaTPV NUMERIC(19,6) NOT NULL DEFAULT 1,
 pozice NVARCHAR(100) NULL DEFAULT N'',
 Operace NCHAR(4) NULL,
 FixniMnozstvi NUMERIC(19,6) NOT NULL DEFAULT 0,
 mnozstvi NUMERIC(19,6) NOT NULL DEFAULT 1,
 ProcZtrat NUMERIC(5,2) NOT NULL DEFAULT 0,
 mnozstviSeZtratou NUMERIC(19,6) NOT NULL DEFAULT 0,
 Prirez NUMERIC(19,6) NOT NULL DEFAULT 1,
 Poznamka NTEXT NULL,
 pom_pomer_A NUMERIC(19,6) NULL,
 pom_pomer_B NUMERIC(19,6) NULL,
 Dodavatel INT NULL,
 mnoz_pozadovane AS (CONVERT(numeric(19,6),(CASE WHEN [mnoz_nepotrebne]>[mnoz_zad] THEN 0.0 ELSE [mnoz_zad] - [mnoz_nepotrebne] END))),
 PRIMARY KEY (ID)
)


SET @operPrednaOdv = N''
SET @idPrednaOpOdv = (SELECT TOP(1) ID FROM dbo.TabPredna_EXT WHERE _OdvadeciOperace=1)
IF (@idPrednaOpOdv IS NOT NULL)
 SET @operPrednaOdv = (SELECT _CIsloOperace FROM dbo.TabPredna_EXT WHERE ID=@idPrednaOpOdv)



IF (@idJson IS NOT NULL)
  DECLARE j CURSOR LOCAL FOR
   SELECT ID, JsonData, Objekt, Akce FROM dbo._hdc_ph_PrijataJsonData WHERE ID=@idJson
 ELSE
  DECLARE j CURSOR LOCAL FOR
   SELECT ID, JsonData, Objekt, Akce
    FROM dbo._hdc_ph_PrijataJsonData
    WHERE Blokovano=0
      AND DatZpracovani IS NULL
      AND ISNULL(JSONData,N'')<>N''
    ORDER BY DatPorizeni
OPEN j
WHILE (1=1)
 BEGIN
  FETCH NEXT FROM j INTO @idJson, @jsonString, @objekt, @akce
  IF (@@FETCH_STATUS<>0) BREAK

  IF (ISJSON(@jsonString)=0)
   BEGIN
    UPDATE dbo._hdc_ph_PrijataJsonData SET DatZpracovani=GETDATE(), PosledniChyba=N'Neplatna JSON data' WHERE ID=@idJson
   END

  SET @objekt = TRIM(ISNULL(@objekt, N''))
  SET @akce = TRIM(ISNULL(@akce, N''))

  BEGIN TRY
   SET @tranPred=@@TRANCOUNT
   IF (@tranPred=0)
    BEGIN TRAN


   DELETE FROM #TabJSONData
   INSERT #TabJSONData (doc) VALUES (@jsonString)
   IF (@objekt=N'')
    SELECT TOP(1) @objekt = JSON_VALUE(doc, '$.object') FROM #TabJSONData
   IF (@akce=N'')
    SELECT TOP(1) @akce = JSON_VALUE(doc, '$.action') FROM #TabJSONData

   SELECT TOP(1) @cisZam = JSON_VALUE(doc, '$.operace.worker.code') FROM #TabJSONData
   SET @idZam = (SELECT ID FROM dbo.TabCisZam WHERE Cislo=@cisZam)

   UPDATE dbo._hdc_ph_PrijataJsonData SET PosledniChyba=NULL, CisloZam=@cisZam WHERE ID=@idJson


   IF (@objekt=N'operace') AND (@idZam IS NOT NULL)
    BEGIN
     IF (@akce=N'start')
      BEGIN
       SET @idEvidROp = NULL
       SET @errMsg = N''
       SET @operPredna = N''
       SET @odvadeciPredna = 0
       SET @nazevOp = N''
       SET @operMax = N''

       SELECT @idVPr = JSON_VALUE(d2.prikaz, '$.id'), @trida = JSON_VALUE(d2.prikaz, '$.class'),
              @idPrednaOp = JSON_VALUE(d3.operace, '$.id'), @datStart = JSON_VALUE(d3.operace, '$.startAt'),
              @statusOp = JSON_VALUE(d3.operace, '$.status'), @typOperJson=JSON_VALUE(d3.operace, '$.typ')
        FROM #TabJSONData d
         CROSS APPLY OPENJSON(d.doc, N'$')
          WITH ([prikaz] NVARCHAR(max) AS JSON) AS d2
         CROSS APPLY OPENJSON(d.doc, N'$')
          WITH ([operace] NVARCHAR(max) AS JSON) AS d3

       IF (@idVPr IS NOT NULL)
        BEGIN
         SELECT @idDilec=p.IDTabKmen, @sklProVydej=rp.VydejMatPol_SkladProGenHlavDZ
          FROM dbo.TabPrikaz p INNER JOIN dbo.TabRadyPrikazu rp ON (rp.Rada=p.Rada) WHERE p.ID=@idVPr

         SET @idPrP = NULL

         IF (@typOperJson=N'prikaz')
          BEGIN
           SET @operPredna = CONVERT(nvarchar, @idPrednaOp)
           SET @idPrednaOp = (SELECT TOP(1) ID FROM dbo.TabPredna_EXT WHERE _CIsloOperace=@operPredna)
           SET @typOperJson=N'prednastavena'
          END

         IF (@typOperJson=N'prednastavena')
          BEGIN
           IF (@idPrednaOp IS NOT NULL)
            BEGIN
             SELECT @operPrednaPrac=IDpracoviste FROM dbo.TabPredna WHERE ID=@idPrednaOp
             IF EXISTS(SELECT 1 FROM dbo.TabPrikaz WHERE ID=@idVPr AND StavPrikazu IN (20,30,40) AND BlokovaniEditoru IS NULL)
                  AND EXISTS(SELECT 1 FROM dbo.TabPredna WHERE ID=@idPrednaOp AND BlokovaniEditoru IS NULL)
              SELECT @typOper=Typ, @nazevOp=nazev, @idPrac=IDpracoviste, @idStroj=IDStroje, @idKoop=IDkooperace
               FROM dbo.TabPredna WHERE ID=@idPrednaOp
             IF (COL_LENGTH(N'dbo.TabPredna_EXT', N'_CisloOperace') IS NOT NULL)
              SET @operPredna = (SELECT _CisloOperace FROM dbo.TabPredna_EXT WHERE ID=@idPrednaOp)
             IF (COL_LENGTH(N'dbo.TabPredna_EXT', N'_OdvadeciOperace') IS NOT NULL)
              SET @odvadeciPredna = (SELECT _OdvadeciOperace FROM dbo.TabPredna_EXT WHERE ID=@idPrednaOp)
            END
          END


         SET @operPredna = ISNULL(@operPredna,N'')
         IF (@operPredna=N'')
          BEGIN
           UPDATE dbo._hdc_ph_PrijataJsonData SET PosledniChyba=N'CHYBA: přednastavení ID ' + CONVERT(nvarchar, @idPrednaOp) + N' nemá zadané číslo operace.' WHERE ID=@idJson
           CONTINUE
          END
--         SET @operPredna=dbo.hf_ZarovnejOperaciTechPos(@operPredna)

/*
         SET @idPrP = (SELECT TOP(1) ID FROM dbo.TabPrPostup WHERE IDPrikaz=@idVPr AND IDOdchylkyDo IS NULL AND typ=@typOper AND nazev=@nazevOp
                        AND ISNULL(pracoviste,0)=ISNULL(@idPrac,0) AND ISNULL(IDkooperace,0)=ISNULL(@idKoop,0) AND ISNULL(IDStroje,0)=ISNULL(@idStroj,0))
*/
         SET @idPrP = (SELECT TOP(1) ID FROM dbo.TabPrPostup WHERE priorita=0 AND IDPrikaz=@idVPr AND IDOdchylkyDo IS NULL AND typ=@typOper AND operace=@operPredna)

-- existuje odvadeci operace v Prednastaveni pro operace a v prikazu ? pokud neni v prikazu, pridej ji do prikazu
         SET @doklOdv = NULL
         SET @idPrPOdv = (SELECT ID FROM dbo.TabPrPostup WHERE priorita=0 AND IDPrikaz=@idVPr AND IDOdchylkyDo IS NULL AND Operace=@operPrednaOdv)

-- pokud prednastavena Odvadeci jeste neni v prikazu, pridej ji tam
         IF (@idPrPOdv IS NULL) AND (@idPrednaOpOdv IS NOT NULL)
          BEGIN
           EXEC @idPrPOdv = dbo.hp_NewPozadavek_TabPrPostup @IDPrikaz=@idVPr, @IDPrednastaveni=@idPrednaOpOdv, @Operace=@operPrednaOdv
           IF (@idPrPOdv IS NOT NULL)
            BEGIN
-- korekce cisla dokladu odvadeci operace, posun na konec seznamu operaci
             SET @doklOdv=9990
             UPDATE dbo.TabPrPostup SET Odvadeci=0 WHERE ID<>@idPrPOdv AND IDPrikaz=@idVPr AND IDOdchylkyDo IS NULL
             UPDATE dbo.TabPrPostup SET Doklad=@doklOdv, Odvadeci=1 WHERE ID=@idPrPOdv
            END
          END
         IF (@doklOdv IS NULL) AND (@idPrPOdv IS NOT NULL)
          SELECT @doklOdv=Doklad FROM dbo.TabPrPostup WHERE ID=@idPrPOdv


-- prednastavena operace v prikazu jeste neni, pridej ji
         IF (@idPrP IS NULL)
          BEGIN
           EXEC @idPrP = dbo.hp_NewPozadavek_TabPrPostup @IDPrikaz=@idVPr, @IDPrednastaveni=@idPrednaOp, @Operace=@operPredna
           IF (@idPrP IS NOT NULL)
            BEGIN
-- korekce cisla dokladu, pred odvadeci opeaci
             SELECT @dokl=ISNULL(MAX(Doklad),0)+1 FROM dbo.TabPrPostup WITH (TABLOCKX) WHERE IDPrikaz=@idVPr AND Doklad<9990
             UPDATE dbo.TabPrPostup SET Doklad=@dokl, Odvadeci=0, VyraditZKontrolyPosloupOper=1 WHERE ID=@idPrP
            END
          END

         SET @idPrednaOpAutomat = NULL
         SET @operPrednaOpAutomat = N''

         IF (@idPrP IS NOT NULL)
          BEGIN
           SELECT @dokl=Doklad, @alt=Alt FROM dbo.TabPrPostup WHERE ID=@idPrP
           UPDATE dbo.TabPrPostup SET VyraditZKontrolyPosloupOper=1 WHERE ID=@idPrP AND Odvadeci=0

-- korekce cisla dokladu aby bylo pred odvadeci operaci
           IF (@doklOdv IS NOT NULL)
            IF (@dokl>@doklOdv)
             BEGIN
              SET @doklNew = 1 + ISNULL( (SELECT MAX(Doklad) FROM dbo.TabPrPostup
                                             WHERE IDPrikaz=@idVPr AND IDOdchylkyDo IS NULL AND Doklad<@doklOdv AND ID<>@idPrP), 0)
              IF (@doklNew IS NOT NULL)
               BEGIN
                UPDATE dbo.TabPrPostup SET Doklad=@doklNew WHERE ID=@idPrP
                SET @dokl = @doklNew
               END
             END
           
           EXEC @idEvidROp = dbo.ep_Vyroba_InsertEvidRozpracOper @IDZamestnance=@idZam, @IDPracoviste=@idPrac, @IDStroje=@idStroj, @CasZahajeni=@datStart, @errMsg = @errMsg OUT
           IF (@idEvidROp IS NOT NULL)
            BEGIN
             SET @idVCPrik = NULL
             IF 1=ISNULL( (SELECT COUNT(ID) FROM dbo.TabVyrCisPrikaz WHERE IDPrikaz=@idVPr), 0)
              SET @idVCPrik = (SELECT TOP(1) ID FROM dbo.TabVyrCisPrikaz WHERE IDPrikaz=@idVPr)
             EXEC @idEvidROpPol = dbo.ep_Vyroba_InsertEvidRozpracOperPol @IDEvidRozpOper=@idEvidROp, @IdPrikaz=@idVPr, @doklPrPost=@dokl,
                                                                         @altPrPost=@alt, @IdVyrCis=@idVCPrik, @errMsg = @errMsg OUT
            END -- idEvidROp IS NOT NULL
          END -- idPrP IS NOT NULL

-- pokud mam naslednou automatickou operaci, zkontrolu a pripadne ji pridej na prikaz
         IF (COL_LENGTH(N'dbo.TabPredna_EXT', N'_IDNasledujiciOperaceAutomat') IS NOT NULL)
          SET @idPrednaOpAutomat = (SELECT _IDNasledujiciOperaceAutomat FROM dbo.TabPredna_EXT WHERE ID=@idPrednaOp)
         IF (COL_LENGTH(N'dbo.TabPredna_EXT', N'_CisloOperace') IS NOT NULL) AND (@idPrednaOpAutomat IS NOT NULL)
           SELECT @operPrednaOpAutomat = _CisloOperace FROM dbo.TabPredna_EXT WHERE ID=@idPrednaOpAutomat
         SET @operPrednaOpAutomat = ISNULL(@operPrednaOpAutomat, N'')
         IF (@operPrednaOpAutomat<>N'')
          BEGIN
           SET @idPrP = (SELECT ID FROM dbo.TabPrPostup WHERE IDPrikaz=@idVPr AND IDOdchylkyDo IS NULL AND Operace=@operPrednaOpAutomat)
           IF (@idPrP IS NULL)
            EXEC @idPrP = dbo.hp_NewPozadavek_TabPrPostup @IDPrikaz=@idVPr, @IDPrednastaveni=@idPrednaOpAutomat, @Operace=@operPrednaOpAutomat

           IF (@idPrP IS NOT NULL)
            BEGIN
-- korekce cisla dokladu
             SELECT @dokl=Doklad FROM dbo.TabPrPostup WHERE ID=@idPrP
             IF (@dokl>@doklOdv)
              BEGIN
               SET @doklNew = 1 + ISNULL( (SELECT MAX(Doklad) FROM dbo.TabPrPostup
                                              WHERE IDPrikaz=@idVPr AND IDOdchylkyDo IS NULL AND Doklad<@doklOdv AND ID<>@idPrP), 0)
               IF (@doklNew IS NOT NULL)
                BEGIN
                 UPDATE dbo.TabPrPostup SET Doklad=@doklNew WHERE ID=@idPrP AND Operace=@operPrednaOpAutomat
                 SET @dokl = @doklNew
                END
              END  -- @dokl>@doklOdv
            END  -- @idPrP IS NOT NULL
          END  -- @operPrednaOpAutomat<>N''


        END -- idVPr IS NOT NULL

       IF (@errMsg<>N'')
        UPDATE dbo._hdc_ph_PrijataJsonData SET PosledniChyba=N'CHYBA: ' + @errMsg WHERE ID=@idJson
       UPDATE dbo._hdc_ph_PrijataJsonData SET DatZpracovani=GETDATE(), IDEvidRozpOp=@idEvidROp WHERE ID=@idJson
      END -- akce Start




     IF (@akce=N'stop')
      BEGIN
       SET @errMsg = N''

       SELECT @idVPr = JSON_VALUE(d2.prikaz, '$.id'), @trida = JSON_VALUE(d2.prikaz, '$.class'),
              @idPrednaOp = JSON_VALUE(d3.operace, '$.id'), @statusOp = JSON_VALUE(d3.operace, '$.status'),
              @datStart = JSON_VALUE(d3.operace, '$.startAt'), @datKonec = JSON_VALUE(d3.operace, '$.stopAt'),
              @operJson=d3.operace, @typOperJson=JSON_VALUE(d3.operace, '$.typ')
        FROM #TabJSONData d
         CROSS APPLY OPENJSON(d.doc, '$')
          WITH ([prikaz] NVARCHAR(max) AS JSON) AS d2
         CROSS APPLY OPENJSON(d.doc, '$')
          WITH ([operace] NVARCHAR(max) AS JSON) AS d3

       IF EXISTS (SELECT 1 FROM dbo.TabPrikaz WHERE ID=@idVPr AND StavPrikazu<>30)
        BEGIN
         UPDATE dbo._hdc_ph_PrijataJsonData SET DatZpracovani=GETDATE(), PosledniChyba=N'Vyrobni prikaz neni ve stavu Zadano' WHERE ID=@idJson
         CONTINUE
        END

       SELECT @ksZive=p.kusy_zive, @sklProVydej=rp.VydejMatPol_SkladProGenHlavDZ
        FROM dbo.TabPrikaz p INNER JOIN dbo.TabRadyPrikazu rp ON (rp.Rada=p.Rada) WHERE p.ID=@idVPr

       IF (@datKonec<=@datStart)
        SET @datKonec = DATEADD(s, 1, @datStart)

       IF (@idVPr IS NOT NULL) AND (@operJson IS NOT NULL)
        BEGIN
         SELECT @idDilec = IDTabKmen FROM dbo.TabPrikaz WHERE ID=@idVPr
         SET @idPrP = NULL
         SET @operPredna = N''
         SET @idPrednaOpAutomat = NULL
         SET @operPrednaOpAutomat = N''

         IF (@typOperJson=N'prikaz')
          BEGIN
           SET @operPredna = CONVERT(nvarchar, @idPrednaOp)
           SET @idPrednaOp = (SELECT TOP(1) ID FROM dbo.TabPredna_EXT WHERE _CIsloOperace=@operPredna)
           SET @typOperJson=N'prednastavena'
          END

         IF (@idPrednaOp IS NOT NULL)
          BEGIN
           IF (COL_LENGTH(N'dbo.TabPredna_EXT', N'_CisloOperace') IS NOT NULL) AND (@idPrednaOp IS NOT NULL)
            SET @operPredna = (SELECT _CisloOperace FROM dbo.TabPredna_EXT WHERE ID=@idPrednaOp)
           SET @operPredna = ISNULL(@operPredna, N'')
           IF (@operPredna=N'')
            BEGIN
             UPDATE dbo._hdc_ph_PrijataJsonData SET DatZpracovani=GETDATE(), PosledniChyba=N'Nebylo nalezeno cislo operace Prednastaveni' WHERE ID=@idJson
             CONTINUE
            END

-- zjisti vyrobni cislo
           SET @idVCPrik = NULL
           IF 1=ISNULL( (SELECT COUNT(ID) FROM dbo.TabVyrCisPrikaz WHERE IDPrikaz=@idVPr), 0)
            SET @idVCPrik = (SELECT TOP(1) ID FROM dbo.TabVyrCisPrikaz WHERE IDPrikaz=@idVPr)

-- zjisti operaci automatu
           IF (COL_LENGTH(N'dbo.TabPredna_EXT', N'_IDNasledujiciOperaceAutomat') IS NOT NULL)
            SET @idPrednaOpAutomat = (SELECT _IDNasledujiciOperaceAutomat FROM dbo.TabPredna_EXT WHERE ID=@idPrednaOp)
           IF (COL_LENGTH(N'dbo.TabPredna_EXT', N'_CisloOperace') IS NOT NULL) AND (@idPrednaOpAutomat IS NOT NULL)
             SELECT @operPrednaOpAutomat = _CisloOperace FROM dbo.TabPredna_EXT WHERE ID=@idPrednaOpAutomat
           SET @operPrednaOpAutomat = ISNULL(@operPrednaOpAutomat, N'')
           SET @casSekOperPredaAutomat = ISNULL( (SELECT TAC_Obsluhy_J_S FROM dbo.TabPredna WHERE ID=@idPrednaOpAutomat), 0)


           IF EXISTS(SELECT 1 FROM dbo.TabPrikaz WHERE ID=@idVPr AND StavPrikazu IN (20,30,40) AND BlokovaniEditoru IS NULL)
                AND EXISTS(SELECT 1 FROM dbo.TabPredna WHERE ID=@idPrednaOp AND BlokovaniEditoru IS NULL)
            SELECT @typOper=Typ, @nazevOp=nazev, @idPrac=IDpracoviste, @idStroj=IDStroje, @idKoop=IDkooperace
             FROM dbo.TabPredna WHERE ID=@idPrednaOp
           END

         SET @idPrP = (SELECT TOP(1) ID FROM dbo.TabPrPostup WHERE priorita=0 AND IDPrikaz=@idVPr AND IDOdchylkyDo IS NULL AND typ=@typOper AND operace=@operPredna)
/*
         SET @idPrP = (SELECT TOP(1) ID FROM dbo.TabPrPostup WHERE IDPrikaz=@idVPr AND IDOdchylkyDo IS NULL AND typ=@typOper AND nazev=@nazevOp
                        AND ISNULL(pracoviste,0)=ISNULL(@idPrac,0) AND ISNULL(IDkooperace,0)=ISNULL(@idKoop,0) AND ISNULL(IDStroje,0)=ISNULL(@idStroj,0))
*/
         SELECT @jeOdvadeci=Odvadeci, @dokl=Doklad, @alt=Alt FROM dbo.TabPrPostup WHERE ID=@idPrP
         SET @ksEvid = ISNULL( (SELECT SUM(kusy_odv+kusy_zmet_opr+kusy_zmet_neopr) FROM dbo.TabPrikazMzdyAZmetky
                                 WHERE IDPrikaz=@idVPr AND DokladPrPostup=@dokl AND AltPrPostup=@alt), 0)
-- muzu jeste odvest kusy ?
         IF (@jeOdvadeci=1) AND (@ksEvid>=@ksZive)
          BEGIN
           UPDATE dbo._hdc_ph_PrijataJsonData SET DatZpracovani=GETDATE(), PosledniChyba=N'Nelze evidovat, uz je vse odvedeno' WHERE ID=@idJson
           CONTINUE
          END


         SET @idMzdy = NULL
         SET @iChyba = -1
         SET @idEvidROp = (SELECT TOP(1) h.ID FROM dbo.TabEvidRozpracOperR r INNER JOIN dbo.TabEvidRozpracOper h ON (h.ID=r.IDEvidRozpracOper)
                            WHERE h.IDZamestnance=@idZam AND h.CasUkonceni IS NULL AND r.DokladPrPostup=@dokl AND r.AltPrPostup=@alt AND r.IDPrikaz=@idVPr)
         IF (@idEvidROp IS NOT NULL)
          BEGIN
           SELECT @idPracOld=IDPracoviste FROM dbo.TabEvidRozpracOper WHERE ID=@idEvidROp
           SET @skCasSek = DATEDIFF(s, @datStart, @datKonec)
           UPDATE dbo.TabEvidRozpracOperR SET Mnoz_odv=CASE WHEN (@jeOdvadeci=1) THEN 1 ELSE 0 END,
                                              Sk_cas=CASE Sk_Cas_T WHEN 0 THEN @skCasSek WHEN 1 THEN (@skCasSek/60.0) WHEN 2 THEN (@skCasSek/3600.0) END,
                                              Sk_cas_Obsluhy=CASE Sk_Cas_Obsluhy_T WHEN 0 THEN @skCasSek WHEN 1 THEN (@skCasSek/60.0) WHEN 2 THEN (@skCasSek/3600.0) END
              WHERE IDEvidRozpracOper=@idEvidROp
           UPDATE dbo.TabEvidRozpracOper SET CasUkonceni=@datKonec, CelkovyCas_T=0, CelkovyCas=DATEDIFF(s, @datStart, @datKonec) WHERE ID=@idEvidROp
           EXEC dbo.hp_EvidRozpracOper_AktualizaceCasuOper @IDEvidRozpracOper=@idEvidROp, @CelkovyCas_S=@skCasSek, @KVO=1

           SET @idEvidROpPol = (SELECT TOP(1) ID FROM dbo.TabEvidRozpracOperR WHERE IDEvidRozpracOper=@idEvidROp AND IDPrikaz=@idVPr AND DokladPrPostup=@dokl AND AltPrPostup=@alt)
           EXEC @idMzdy = dbo.hp_EvidenceOperace @IDEvidRozpracOperR=@idEvidROpPol, @Stav=0
           UPDATE dbo.TabEvidRozpracOper SET DatumUzavreni=GETDATE(), AutorUzavreni=SUSER_SNAME() WHERE ID=@idEvidROp

           IF (@idMzdy IS NOT NULL) AND (@idPracOld IS NOT NULL)
            EXEC dbo.hp_ZmenaStavuMezdAZmetku @ID=@idMzdy, @Stav=1, @ZapisZmenu=0
          END  -- @idEvidROp IS NOT NULL


         IF (@idMzdy IS NOT NULL)
          BEGIN
           UPDATE dbo.TabPrikazMzdyAZmetky SET Datum=CONVERT(datetime, CONVERT(int, CONVERT(float, @datStart))) WHERE ID=@idMZdy

           SELECT @datKonecOp = DatumUkonceniOp FROM dbo.TabPrikazMzdyAZmetky WHERE ID=@idMzdy

-- zkus zaevidovat operaci automatu
           IF (@operPrednaOpAutomat<>N'')
            BEGIN
-- pouzij cas ukonceni predchozi operace
             SET @datStart = DATEADD(second, 1, @datKonecOp)
             SET @datKonec = DATEADD(second, @casSekOperPredaAutomat, @datStart)

             SELECT @doklAutomat=Doklad, @altAutomat=Alt FROM dbo.TabPrPostup WHERE IDPrikaz=@idVPr AND IDOdchylkyDo IS NULL AND Operace=@operPrednaOpAutomat
             IF (@doklAutomat IS NOT NULL)
              BEGIN
               SET @idMzdyAutomat = NULL
               EXEC @idMzdyAutomat = dbo.hp_EvidenceOperace @IDPrikaz=@idVPr, @Doklad=@doklAutomat, @Alt=@altAutomat, @Datum=@datStart, @IDVyrCis=@idVCPrik,
                                                            @Sk_Cas_S=@casSekOperPredaAutomat, @Sk_Cas_Obsluhy_S=0, @IDZam=@idZam,
                                                            @DatumZahajeniOp=@datStart, @DatumUkonceniOp=@datKonec
              END
            END

-- generuj vydejku materialu
           SET @sz = NULL
           DELETE FROM #TabJSONData
           INSERT #TabJSONData (doc) SELECT @operJson
           DECLARE m CURSOR LOCAL FOR
            SELECT m.skupina, m.regcis, m.quantity
             FROM #TabJSONData d
              CROSS APPLY OPENJSON(d.doc, N'$.material')
              WITH (skupina NVARCHAR(3), regcis NVARCHAR(30), quantity NUMERIC(19,6)) AS m
           OPEN m
           WHILE (1=1)
            BEGIN
             FETCH NEXT FROM m INTO @sz, @rc, @mnoz
             IF (@@FETCH_STATUS<>0) BREAK
             SET @idKZ = (SELECT ID FROM dbo.TabKmenZbozi WHERE SkupZbo=@sz AND RegCis=@rc)
             IF (@idKZ IS NOT NULL)
              BEGIN
               UPDATE dbo.TabKmenZbozi SET Material=1 WHERE ID=@idKZ AND Dilec=0 AND Material=0
               SET @idPrKVazby=(SELECT TOP(1) ID FROM dbo.TabPrKVazby WHERE IDOdchylkyDo IS NULL AND IDPrikaz=@idVPr
                                 AND vyssi=@idDilec AND nizsi=@idKZ ORDER BY Prednastaveno DESC)
               IF (@idPrKVazby IS NULL)
                EXEC @idPrKVazby = dbo.hp_NewPozadavek_TabPrKVazby @IDPrikaz=@idVPr, @IDKmenZbozi=@idKZ, @Mnozstvi=@mnoz
               SET @dokl = NULL
               IF (@idPrKVazby IS NOT NULL)
                BEGIN
                 SELECT @dokl=Doklad FROM dbo.TabPrKVazby WHERE ID=@idPrKVazby
                 SELECT @mnozstviPomer_A=(MZ.kusy_odv+MZ.kusy_zmet_opr+MZ.kusy_zmet_neopr), @mnozstviPomer_B=PrP.kusy_zad
                   FROM dbo.TabPrikazMzdyAZmetky MZ
                    INNER JOIN dbo.TabPrPostup PrP ON (PrP.IDPrikaz=MZ.IDPrikaz AND PrP.Doklad=MZ.DokladPrPostup AND PrP.Alt=MZ.AltPrPostup AND PrP.IDOdchylkyDo IS NULL) 
                   WHERE MZ.ID=@idMzdy 
                 INSERT INTO #HDCTabPrKVazbyGenPredna (IDPrKV,  MnozstviPoz, pom_pomer_A, pom_pomer_B, Doklad, IDPrikaz, Prednastaveno, Sklad, VyrStredisko,
                                                    IDPracoviste, mnoz_zad, Mnoz_nepotrebne, Mnoz_skut_realizovane, Cena_real, Mnoz_odv, Cena_odv, priorita, vyssi, nizsi,
                                                    DavkaTPV, pozice, Operace, FixniMnozstvi, mnozstvi, ProcZtrat, mnozstviSeZtratou, Prirez, Poznamka) 
                   SELECT PrKV.ID, @mnoz, @mnozstviPomer_A, @mnozstviPomer_B,  PrKV.Doklad, PrKV.IDPrikaz,
                          PrKV.Prednastaveno, PrKV.Sklad, PrKV.VyrStredisko, PrKV.IDPracoviste, PrKV.mnoz_zad, PrKV.Mnoz_nepotrebne, PrKV.Mnoz_skut_realizovane,
                          PrKV.Cena_real, PrKV.Mnoz_odv, PrKV.Cena_odv, PrKV.priorita, PrKV.vyssi, PrKV.nizsi, PrKV.DavkaTPV, PrKV.pozice, PrKV.Operace,
                          PrKV.FixniMnozstvi, PrKV.mnozstvi, PrKV.ProcZtrat, PrKV.mnozstviSeZtratou, PrKV.Prirez, PrKV.Poznamka 
                     FROM dbo.TabPrKVazby PrKV 
                     WHERE PrKV.ID=@idPrKVazby AND PrKV.uzavreno=0
                 SET @idGenVydejPrednaPol = SCOPE_IDENTITY()

-- pokud neni prednastaveny sklad pro vydej, zkus to z rady prikazu
                 UPDATE #HDCTabPrKVazbyGenPredna SET Sklad=@sklProVydej WHERE ID=@idGenVydejPrednaPol AND Sklad IS NULL AND @sklProVydej IS NOT NULL

                 IF (@dokl IS NOT NULL) 
                  INSERT INTO #HDCTabPrKVazbyGen_IDMzdyPredna (IDPrikaz, Doklad, IDMzdy) SELECT @idVPr, @dokl, @idMzdy
                END -- idPrKVazby IS NOT NULL
              END -- idKZ
            END
           CLOSE m
           DEALLOCATE m
           
           SET @debugXML = (SELECT * FROM #HDCTabPrKVazbyGenPredna FOR XML AUTO)
           

           IF (@idMzdy IS NOT NULL) AND (@sz IS NOT NULL) -- pokud prosel loopem na materialy, sz nemuze byt null
            IF OBJECT_ID(N'dbo.ep_Vyroba_GenVydejZeMzdy', N'P') IS NOT NULL
             BEGIN
              SET @idDZ = NULL
              BEGIN TRY
               EXEC @iChyba = dbo.ep_Vyroba_GenVydejZeMzdy @IDMzdy=@idMzdy, @IDDoklad=@idDZ OUT, @errMsg=@errMsg OUT, @realizujVydej=1
               IF (@errMsg<>N'')
                UPDATE dbo.TabDokladyZbozi SET BLokovaniEditoru=NULL WHERE ID=@idDZ
              END TRY
              BEGIN CATCH
               UPDATE dbo.TabDokladyZbozi SET BlokovaniEditoru=NULL WHERE ID=@idDZ
              END CATCH
             END


-- pokud je odvadeci, generuj odvod na sklad
           IF (@idMzdy IS NOT NULL) AND (@jeOdvadeci=1)
            BEGIN
             IF OBJECT_ID(N'dbo.ep_Vyroba_GenOdvodZeMzdy', N'P') IS NOT NULL
              BEGIN
               SET @idDZ = NULL
               BEGIN TRY
                EXEC @iChyba = dbo.ep_Vyroba_GenOdvodZeMzdy @IDMzdy=@idMzdy, @bezVyrCis=0, @errMsg=@errMsg OUT, @realizujPrijem=1, @IDDoklad=@idDZ OUT
                IF (@errMsg<>N'')
                 UPDATE dbo.TabDokladyZbozi SET BLokovaniEditoru=NULL WHERE ID=@idDZ
               END TRY
               BEGIN CATCH
                UPDATE dbo.TabDokladyZbozi SET BlokovaniEditoru=NULL WHERE ID=@idDZ
               END CATCH
              END
            END


          END -- idMzdy IS NOT NULL
        END -- idVPr IS NOT NULL AND operJson IS NOT NULL

       SET @errMsg = ISNULL(@errMsg,N'')
       IF (@errMsg<>N'')
        UPDATE dbo._hdc_ph_PrijataJsonData SET PosledniChyba=N'CHYBA: ' + @errMsg WHERE ID=@idJson
       UPDATE dbo._hdc_ph_PrijataJsonData SET DatZpracovani=GETDATE(), IDMzda=@idMzdy WHERE ID=@idJson
      END -- akce Stop

    END -- objekt Operace AND idZam IS NOT NULL


   IF (@tranPred=0) AND (@@TRANCOUNT>0)
    COMMIT TRAN
  END TRY
  BEGIN CATCH
   SET @errMsg = ERROR_MESSAGE()
   SET @errProc = ERROR_PROCEDURE()
   IF (@tranPred=0) AND (@@TRANCOUNT>0)
    ROLLBACK TRAN
   UPDATE dbo._hdc_ph_PrijataJsonData SET DatZpracovani=GETDATE(), PosledniChyba=N'CHYBA: ' + @errMsg WHERE ID=@idJson
  END CATCH

 END
CLOSE j
DEALLOCATE j



-- cisteni
DROP TABLE IF EXISTS #HDCTabPrKVazbyGenPredna
DROP TABLE IF EXISTS #TabJSONData
