unit uSvcCustom;

interface

uses
  System.Classes,
  System.JSON,
  REST.Json,
  System.Generics.Collections,
  Winapi.ActiveX,
  System.DateUtils,
  System.SysUtils,
  JsonDataObjects,
  uSvc_Base,
  uCommons, // kvuli EServiceException
  helTabsBIDs,
  uHeoObj_Base,
  uHeOObj_Custom,
  uHeoObj_Vyroba,
  uSvc_ObehZbozi,
  uSvc_Vyroba;


const
{$I C:\_zakaznici\pluginy_obecne\HDCApi2\globalConsts.inc}

  selSpecDoklSD = '(SELECT CisloOrg FROM ' + tblCOrg + ' WHERE ID=main.IDOrg) AS CisloOrg';
  tblMichPozadavek = '[dbo].[_hdc_DataZone_MicharnaPozadavek]';
  tblMichSpotreba = '[dbo].[_hdc_DataZone_MicharnaSpotreba]';
  tblPrijataJsonData = '[dbo].[_hdc_ph_PrijataJsonData]'; // data z Pro Holdingu



type
  TSDGDokladOZService = class;
  TSDGPolozkaOZService = class;




  TRTNService = class(TServiceBase)
   public
    function NactiDataZHeliosu (jsonData: string; var respData: string): string;
    procedure ZapisJsonDoHeliosu (jsonData: string; var respString: string);
    function GetPrikazy (params: TDictionary<string,string>): TObjectList<TVyrobniPrikaz>;
   end;






  TGatemaSDDokladService = class(TServiceBase)
   public
    function GetAll: TObjectList<TGatemaSDDoklad>;
    function GetByParams(params: TDictionary<string, string>): TObjectList<TGatemaSDDoklad>;
    function GetByID (const AID: integer; const bezPolozek: boolean=false): TGatemaSDDoklad;
    function GetMeta: TJSONObject;
   end;

{
  TGatemaSDDokladOZService = class(TServiceBase)
   public
    function GetAll: TObjectList<TSDGDokladOZService>;
    function GetByParams(params: TDictionary<string, string>): TObjectList<TSDGDokladOZService>;
    function GetByID (const AID: integer; const bezPolozek: boolean=false): TSDGDokladOZService;
    function GetMeta: TJSONObject;
  end;
}

  TGatemaSDScanDataService = class(TServiceBase)
   public
    function GetByParams (params: TDictionary<string, string>): TObjectList<TGatemaSDScanData>;
    function GetByID (const AID: integer): TGatemaSDScanData;
    function GetMeta: TJSONObject;
  end;


  TSDGPolozkaOZService = class(TPolozkaOZService)
    function GetByID (const AID: integer): TPohybOZ;
    function GetByParams (params: TDictionary<string, string>): TObjectList<TPohybOZ>;
   end;


  TSDGSerioveCisloPohybOZService = class(TSerioveCisloPohybOZService)
   function GetByParams (params: TDictionary<string, string>): TObjectList<TSerioveCisloPohybOZ>;
  end;


  TSDGDokladOZService = class(TDokladOZService)
   function GetByID(const AID: integer; const bezPolozek: boolean=false): TDokladOZ; virtual;
   function GetByParams(params: TDictionary<string, string>): TObjectList<TDokladOZ>; virtual;
  end;




implementation

uses
  System.StrUtils,
  FireDAC.Stan.Option,
  FireDAC.Comp.Client,
  FireDAC.Stan.Param,
  MVCFramework.FireDAC.Utils,
  MVCFramework.DataSet.Utils,
  MVCFramework.Serializer.Commons;



{ TSDGDokladOZService }

 function TSDGDokladOZService.GetByParams (params: TDictionary<string, string>): TObjectList<TDokladOZ>;
  var lSQL, where, odDatum, doDatum, sklad, strTemp, podmSDGDoklad: string;
      lQry: TFDQuery;
      datOd, datDo: TDateTime;
      id, iDZ, cnt, rNo: integer;
      jenSeznam: Boolean;
      d: TDokladOZ;
      dList: TObjectList<TDokladOZ>;
  begin
   jenSeznam:= false;
   if (params.ContainsKey('seznam')) then
    jenSeznam:= true;


   if not(jenSeznam) then
     lSQL:= 'SELECT ' + GetTabCols('dbo', tblDZ, 'main', false) + IfThen(selSpecDZ<>'', ',' + selSpecDZ, '') + ' FROM ' + tblDZ + ' main'
    else
     lSQL:= 'SELECT main.ID, main.DruhPohybuZbo, main.RadaDokladu, main.PoradoveCislo, main.CisloOrg, main.DatPorizeni, main.DatRealizace, main.Realizovano, main.Autor FROM ' + tblDZ + ' main';

   where:= 'main.Realizovano=1';

   id:= 0;
   if (params.ContainsKey('id')) then
    if (params.Items['id']<>'') then
     if (params.Items['id']<>'0') then
      begin
       id:= params.Items['id'].ToInteger;
       where:= where + IfThen(where<>'', ' AND ', '') + 'main.ID=' + id.ToString;
      end;

   if (params.ContainsKey('organizace')) then
    if (params.Items['organizace']<>'') then
     where:= where + IfThen(where<>'', ' AND ', '') + 'main.CisloOrg=' + params.Items['organizace'];

   if (params.ContainsKey('druhpohybu')) then
    if (params.Items['druhpohybu']<>'') then
     where:= where + IfThen(where<>'', ' AND ', '') + 'main.DruhPohybuZbo=' + params.Items['druhpohybu'];

   if (params.ContainsKey('radadokladu')) then
    if (params.Items['radadokladu']<>'') then
     where:= where + IfThen(where<>'', ' AND ', '') + 'main.RadaDokladu=N' + params.Items['radadokladu'].QuotedString;

   if (params.ContainsKey('sklad')) then
    if (params.Items['sklad']<>'') then
     where:= where + IfThen(where<>'', ' AND ', '') + 'main.IDSklad=N' + params.Items['sklad'].QuotedString;


   if (params.ContainsKey('odDatum')) then
    if (params.Items['odDatum']<>'') then
     odDatum:= params.Items['odDatum'];
   if (odDatum<>'') then
     begin
      if (Length(odDatum)=8) then
       odDatum:= odDatum + '000000';
      if (Length(odDatum)=10) then
       odDatum:= odDatum + '00';
      odDatum:= MidStr(odDatum, 7, 2) + '.' + MidStr(odDatum, 5, 2) + '.' + LeftStr(odDatum, 4) + ' ' + MidStr(odDatum, 9, 2) + ':' + MidStr(odDatum, 11, 2) + ':' + MidStr(odDatum, 13, 2);
      if not(TryStrToDateTime(odDatum, datOd)) then
       datOd:= IncDay(Now, -1)
     end
    else
     datOd:= IncDay(Now, -1);


   if (params.ContainsKey('doDatum')) then
    if (params.Items['doDatum']<>'') then
     odDatum:= params.Items['doDatum'];
   if (doDatum<>'') then
     begin
      if (Length(doDatum)=8) then
       doDatum:= doDatum + '235959';
      if (Length(doDatum)=10) then
       doDatum:= doDatum + '59';
      doDatum:= MidStr(doDatum, 7, 2) + '.' + MidStr(doDatum, 5, 2) + '.' + LeftStr(doDatum, 4) + ' ' + MidStr(doDatum, 9, 2) + ':' + MidStr(doDatum, 11, 2) + ':' + MidStr(doDatum, 13, 2);
      if not(TryStrToDateTime(doDatum, datDo)) then
       datDo:= Now
     end
    else
     datDo:= Now;

   strTemp:= '';
   if (odDatum<>'') then
     strTemp:= 'CONVERT(datetime, N' + FormatDateTime('dd.mm.yyyy', datOd).QuotedString + ',104)'
    else
     strTemp:= 'DATEADD(day, -3, GETDATE())';

   where:= where + IfThen(where<>'', ' AND ', '') + 'main.DatPorizeni>=' + strTemp;

   if (doDatum<>'') then
    begin
     strTemp:= 'CONVERT(datetime, N' + FormatDateTime('dd.mm.yyyy', datDo).QuotedString + ',104)';
     where:= where + IfThen(where<>'', ' AND ', '') + 'main.DatPorizeni<=' + strTemp;
    end;


   lSQL:= lSQL + ' INNER JOIN ' + tblGSDDoklady + ' sdd ON (sdd.IdDokZbo=main.ID)';


   if (where<>'') then
    begin
     where:= where +IfThen(where<>'', ' AND ', '') + 'sdd.DatGenerovani IS NOT NULL';
     lSQL:= lSQL + ' WHERE ' + where;
    end;
   lSQL:= lSQL + ' ORDER BY main.ParovaciZnak';

   lSQL:= lSQL.Replace('TabDokladyZbozi.', 'main.');


   lQry:= TFDQuery.Create(nil);
   lQry.Connection:= FDM.sqlConn;
   lQry.FetchOptions.AutoClose:= false;
   lQry.FetchOptions.Mode:= fmAll;
   lQry.Open(lSQL);
   cnt:= lQry.RecordCount;
   if (cnt>0) then
     begin
      try
        d:= TDokladOZ.Create;
        dList:= TObjectList<TDokladOZ>.Create;
        try
          rNo:= 1;
          lQry.First;
          while (rNo<=cnt) do // nouzove reseni, lQry se po nacteni GetbyID sama uzavre !!
           begin
            lQry.RecNo:= rNo;
            iDZ:= lQry.FieldByName('ID').AsInteger;
            d:= self.GetByID(iDZ, jenSeznam);
            dList.Add(d);
            if not(lQry.Active) then
             lQry.Open;
            Inc(rNo);
           end;
          result:= dList; // FDM.sqlQry1.AsObjectList<TDokladOZ>;
         except on E:Exception do
          raise EServiceException.Create('Chyba načítání dokladu: ' + E.Message);
        end;
       finally
        FreeAndNil(lQry);
      end;
     end
    else
     raise EServiceException.Create('Vybraným podmínkám neodpovídá žádný doklad');
  end;




 function TSDGDokladOZService.GetByID(const AID: integer; const bezPolozek: boolean=false): TDokladOZ;
  var lSQL: string;
      p: TDictionary<string, string>;
      ps: TSDGPolozkaOZService;
      lQry: TFDQuery;
  begin
//   lSQL:= 'SELECT ' + GetTabCols('dbo', tblDZ, '', false) + ' FROM ' + tblDZ + ' WHERE ID=:ID';

   ps:= TSDGPolozkaOZService.Create(self.FDM);
   p:= TDictionary<string, string>.Create;
   p.Add('iddoklad', AID.ToString);

   lSQL:= 'SELECT ' + GetTabCols('dbo', tblDZ, '', false) + IfThen(selSpecDZ<>'', ',' + selSpecDZ, '') + ' FROM ' + tblDZ + ' WHERE ID=' + AID.ToString + ' AND Realizovano=1';


   lQry:= TFDQuery.Create(nil);
   lQry.Connection:= FDM.sqlConn;
   lQry.Open(lSQL);
   try
     lQry.First;
     if not(lQry.EOF) then
      begin
       result:= lQry.AsObject<TDokladOZ>;
       if not(bezPolozek) then
        result.PohybyOZ:= ps.GetByParams(p);
      end
     else
       raise EServiceException.Create('Doklad oběhu zboží s ID ' + AID.ToString + ' nebyl nalezen.');
    finally
     p.Free;
     ps.Free;
     FreeAndNil(lQry);
   end;
    end;




{ TSDGSerioveCisloPohybOZService }

 function TSDGSerioveCisloPohybOZService.GetByParams (params: TDictionary<string, string>): TObjectList<TSerioveCisloPohybOZ>;
  var lSQL, where: string;
      lQry: TFDQuery;
      id, idPZ: integer;
      s: TSerioveCisloPohybOZ;
  begin
//   lSQL:= 'SELECT ' + GetTabCols('', tblVyrCP, 'main') + IfThen(selSpecVyrCP<>'', ', ' + selSpecVyrCP.Replace('#', ''), '') + ' FROM ' + tblVyrCP + ' main';
   lSQL:= 'SELECT ID, IdPohZbo AS IDPolozkaDokladu, NULL AS IDVyrCis, VyrCislo AS VyrCis, PopisSarze AS Nazev, Mnozstvi, DatumExpirace AS DatExpirace'
        + ', 1 AS ZdrojSD, IDDokladSD AS IDDokladGSD, DatPorizeni AS DatVstup FROM ' + tblGSDScanData;
   where:= '';

   id:= 0;
   if (params.ContainsKey('id')) then
    if (params.Items['id']<>'') then
     if (params.Items['id']<>'0') then
      id:= params.Items['id'].ToInteger;

   if (params.ContainsKey('idpohzbo')) then
    if (params.Items['idpohzbo']<>'') then
     if (params.Items['idpohzbo']<>'0') then
      where:= where + IfThen(where<>'', ' AND ', '') + 'IdPohZbo=' + params.Items['idpohzbo'];

   if (where<>'') then
    lSQL:= lSQL + ' WHERE ' + IfThen(id>0, 'ID=' + id.ToString, where);
   lSQL:= lSQL + ' ORDER BY ID';


   lQry:= TFDQuery.Create(nil);
   lQry.Connection:= FDM.sqlConn;
   try
     lQry.Open(lSQL);
     result:= lQry.AsObjectList<TSerioveCisloPohybOZ>;
    finally
     lQry.Free;
   end;
  end;





{ TSDGPolozkaOZService }

 function TSDGPolozkaOZService.GetByID (const AID: Integer): TPohybOZ;
  var lSQL: string;
      p: TDictionary<string, string>;
      pds: TSDGSerioveCisloPohybOZService;
      lQry: TFDQuery;
      idDokladOZ: integer;
  begin
   lSQL:= 'SELECT ' + GetTabCols('dbo', tblPZ, '', false) + ' FROM ' + tblPZ + ' WHERE ID=:ID';


   pds:= TSDGSerioveCisloPohybOZService.Create(self.FDM);
   p:= TDictionary<string, string>.Create;
   p.Add('idPolozkaOZ', AID.ToString);

   lQry:= TFDQuery.Create(nil);
   lQry.Connection:= FDM.sqlConn;
   try
     lQry.Open(lSQL, [AID]);
     lQry.First;
     if not(lQry.EOF) then
      begin
       result:= lQry.AsObject<TPohybOZ>;
       p.Add('idpohzbo', result.ID.ToString);
       result.SerialNums:= pds.GetByParams(p);
      end
     else
       raise EServiceException.Create('Položka dokladu oběhu zboží s ID ' + AID.ToString + ' nebyla nalezena.');
    finally
     p.Free;
     pds.Free;
     lQry.Free;
   end;
  end;




 function TSDGPolozkaOZService.GetByParams (params: TDictionary<string, string>): TObjectList<TPohybOZ>;
  var lSQL, where, podmSDGPolozka: string;
      id,idPZ, cnt, rNo: integer;
      lQry: TFDQuery;
      pList: TObjectList<TPohybOZ>;
      p: TPohybOZ;
  begin
   p:= TPohybOZ.Create;
   pList:= TObjectList<TPohybOZ>.Create;

   lSQL:= 'SELECT ' + GetTabCols('dbo', tblPZ, '', false) + ' FROM ' + tblPZ;

   where:= 'KJSkontrolovano=1 AND ID IN (SELECT p.IDPohZbo FROM ' + tblGSDScanData + ' p INNER JOIN '
         + tblGSDDoklady + ' h ON (h.ID=p.IDDokladSD) WHERE h.DatGenerovani IS NOT NULL)' ;

   id:= 0;
   if (params.ContainsKey('id')) then
    if (params.Items['id']<>'') then
     if (params.Items['id']<>'0') then
      begin
       id:= params.Items['id'].ToInteger;
       where:= where + IfThen(where<>'', ' AND ', '') + 'ID=' + id.ToString;
      end;

   if (params.ContainsKey('iddoklad')) then
    if (params.Items['iddoklad']<>'') then
     where:= where + IfThen(where<>'', ' AND ', '') + 'IDDoklad=' + params.Items['iddoklad'] + ' AND IDDoklad IN (SELECT IDDokZbo FROM '
           + tblGSDDoklady + ' WHERE DatGenerovani IS NOT NULL)';

   if (where<>'') then
    lSQL:= lSQL + ' WHERE ' + where;
   lSQL:= lSQL + ' ORDER BY IDDoklad, Poradi';

//   lSQL:= lSQL.Replace('TabPohybyZbozi.', 'main.');


   lQry:= TFDQuery.Create(nil);
   lQry.Connection:= FDM.sqlConn;
   lQry.FetchOptions.AutoClose:= false;
   lQry.FetchOptions.Mode:= fmAll;
   lQry.Open(lSQL);
   try
     cnt:= lQry.RecordCount;
     pList:= TObjectList<TPohybOZ>.Create;
     try
       lQry.First;
       rNo:= 1;
       while (rNo<=cnt) do
        begin
         lQry.RecNo:= rNo;
         idPZ:= lQry.FieldByName('ID').AsInteger;

         p:= self.GetByID(idPZ);
         pList.Add(p);
         if not(lQry.Active) then
          lQry.Open;
         Inc(rNo);
        end;
       result:= pList;
      except on E:Exception do
       raise EServiceException.Create('Chyba načítání položky/položek dokladu: ' + E.Message);
     end;
    finally
     FreeAndNil(lQry);
   end;
  end;






{ TGatemaSDDokladService }

 function TGatemaSDDokladService.GetAll:TObjectList<TGatemaSDDoklad>;
  var lSQL: string;
  begin
   lSQL:= 'SELECT ' + GetTabCols('dbo', tblGSDDoklady) + ' FROM ' + tblGSDDoklady + ' ORDER BY ID';
   FDM.sqlQry1.Open(lSQL, []);
   result:= FDM.sqlQry1.AsObjectList<TGatemaSDDoklad>;
   FDM.sqlQry1.Close;
  end;



 function TGatemaSDDokladService.GetByParams(params: TDictionary<string, string>): TObjectList<TGatemaSDDoklad>;
  var lSQL, where, odDatum, doDatum, sklad, formatX, druhPohybuZbo, strTemp: string;
      lQry: TFDQuery;
      datOd, datDo: TDateTime;
      id, iDZ, cnt, rNo: integer;
      jenSeznam: Boolean;
      d: TGatemaSDDoklad;
      dList: TObjectList<TGatemaSDDoklad>;
  begin
   jenSeznam:= false;
   if (params.ContainsKey('seznam')) then
    jenSeznam:= true;

   formatX:= '';
   if (params.ContainsKey('format')) then
    formatX:= params.Items['format'];
   if (formatX<>'') then
     begin
     end
    else
     begin
      if not(jenSeznam) then
        lSQL:= 'SELECT ' + GetTabCols('dbo', tblGSDDoklady, 'main', false) + IfThen(selSpecDoklSD<>'', ',' + selSpecDoklSD, '') + ' FROM ' + tblGSDDoklady + ' main'
       else
        lSQL:= 'SELECT main.ID, main.TypDokladu, main.PodtypDokladu, main.RadaDokladu, main.Sklad, main.RadaDokladuCil, main.SkladCil, main.IDDokZbo, main.IDDokZbo_New'
             + ', main.IDOrg' + IfThen(selSpecDoklSD<>'', ',' + selSpecDoklSD, '') + ', main.DatPorizeni, main.DatGenerovani, main.DatumPripadu, main.PopisDodavky'
             + ' FROM ' + tblGSDDoklady + ' main';
     end;

   where:= '';

   id:= 0;
   if (params.ContainsKey('id')) then
    if (params.Items['id']<>'') then
     if (params.Items['id']<>'0') then
      begin
       id:= params.Items['id'].ToInteger;
       where:= where + 'main.ID=' + id.ToString;
      end;

   if (params.ContainsKey('typDokladu')) then
    if (params.Items['typDokladu']<>'') then
     where:= where + IfThen(where<>'', ' AND ', '') + 'main.TypDokladu=N' + params.Items['typDokladu'];

   if (params.ContainsKey('druhPohybu')) then
    if (params.Items['druhPohybu']<>'') then
     where:= where + IfThen(where<>'', ' AND ', '') + 'main.DruhPohybuZbo=N' + params.Items['druhPohybu'];

   if (params.ContainsKey('sklad')) then
    if (params.Items['sklad']<>'') then
     where:= where + IfThen(where<>'', ' AND ', '') + 'main.Sklad=N' + params.Items['sklad'].QuotedString;


   if (params.ContainsKey('odDatum')) then
    if (params.Items['odDatum']<>'') then
     odDatum:= params.Items['odDatum'];
   if (odDatum<>'') then
     begin
      if (Length(odDatum)=8) then
       odDatum:= odDatum + '000000';
      if (Length(odDatum)=10) then
       odDatum:= odDatum + '00';
      odDatum:= MidStr(odDatum, 7, 2) + '.' + MidStr(odDatum, 5, 2) + '.' + LeftStr(odDatum, 4) + ' ' + MidStr(odDatum, 9, 2) + ':' + MidStr(odDatum, 11, 2) + ':' + MidStr(odDatum, 13, 2);
      if not(TryStrToDateTime(odDatum, datOd)) then
       datOd:= IncDay(Now, -180)
     end
    else
     datOd:= IncDay(Now, -180);

   if (params.ContainsKey('doDatum')) then
    if (params.Items['doDatum']<>'') then
     odDatum:= params.Items['doDatum'];
   if (doDatum<>'') then
     begin
      if (Length(doDatum)=8) then
       doDatum:= doDatum + '235959';
      if (Length(doDatum)=10) then
       doDatum:= doDatum + '59';
      doDatum:= MidStr(doDatum, 7, 2) + '.' + MidStr(doDatum, 5, 2) + '.' + LeftStr(doDatum, 4) + ' ' + MidStr(doDatum, 9, 2) + ':' + MidStr(doDatum, 11, 2) + ':' + MidStr(doDatum, 13, 2);
      if not(TryStrToDateTime(doDatum, datDo)) then
       datDo:= Now
     end
    else
     datDo:= Now;


   strTemp:= '';
   if (odDatum<>'') then
     strTemp:= 'CONVERT(datetime, N' + FormatDateTime('dd.mm.yyyy', datOd).QuotedString + ',104)'
    else
     strTemp:= 'DATEADD(day, -3, GETDATE())';

   where:= where + IfThen(where<>'', ' AND ', '') + 'main.DatPorizeni>=' + strTemp;

   if (doDatum<>'') then
    begin
     strTemp:= 'CONVERT(datetime, N' + FormatDateTime('dd.mm.yyyy', datDo).QuotedString + ',104)';
     where:= where + IfThen(where<>'', ' AND ', '') + 'main.DatPorizeni<=' + strTemp;
    end;


   if (where<>'') then
    lSQL:= lSQL + ' WHERE ' + IfThen(id>0, 'main.ID=' + id.ToString, where);
   lSQL:= lSQL + ' ORDER BY main.ID';

   lSQL:= lSQL.Replace('Gatema_SDDoklady.', 'main.');



   lQry:= TFDQuery.Create(nil);
   try
     lQry.Connection:= FDM.sqlConn;
     lQry.FetchOptions.AutoClose:= false;
     lQry.FetchOptions.Mode:= fmAll;
     lQry.Open(lSQL);

     cnt:= lQry.RecordCount;
     if (cnt>0) then
       begin
          d:= TGatemaSDDoklad.Create;
          dList:= TObjectList<TGatemaSDDoklad>.Create;
          try
            rNo:= 1;
            lQry.First;
            while (rNo<=cnt) do // nouzove reseni, lQry se po nacteni GetbyID sama uzavre !!
             begin
              lQry.RecNo:= rNo;
              iDZ:= lQry.FieldByName('ID').AsInteger;
              d:= self.GetByID(iDZ, jenSeznam);
              dList.Add(d);
              if not(lQry.Active) then
               lQry.Open;
              Inc(rNo);
             end;
            result:= dList;
           except on E:Exception do
            raise EServiceException.Create('Chyba načítání dokladu: ' + E.Message);
          end;
       end
      else
       raise EServiceException.Create('Vybraným podmínkám neodpovídá žádný naskenovaný doklad');
    finally
     FreeAndNil(lQry);
   end;

  end;



 function TGatemaSDDokladService.GetByID (const AID: integer; const bezPolozek: boolean=false): TGatemaSDDoklad;
  var lSQL: string;
      p: TDictionary<string, string>;
      ps: TGatemaSDScanDataService;
      lQry: TFDQuery;
  begin

   ps:= TGatemaSDScanDataService.Create(self.FDM);
   p:= TDictionary<string, string>.Create;
   p.Add('iddoklad', AID.ToString);

   lSQL:= 'SELECT ' + GetTabCols('dbo', tblGSDDoklady, 'main', false) + IfThen(selSpecDoklSD<>'', ',' + selSpecDoklSD, '') + ' FROM ' + tblGSDDoklady + ' main WHERE main.ID=:ID';
   lQry:= TFDQuery.Create(nil);
   try
     lQry.Connection:= FDM.sqlConn;
     lQry.Open(lSQL, [AID]);
     lQry.First;
     if not(lQry.EOF) then
      begin
       result:= lQry.AsObject<TGatemaSDDoklad>;
       if not(bezPolozek) then
        result.ScanData:= ps.GetByParams(p);
      end
     else
       raise EServiceException.Create('Naskenovaný doklad s ID ' + AID.ToString + ' nebyl nalezen.');
    finally
     p.Free;
     ps.Free;
     FreeAndNil(lQry);
   end;
  end;



 function TGatemaSDDokladService.GetMeta: TJSONObject;
  var lSQL: string;
      lQry: TFDQuery;
  begin
   lSQL:= 'SELECT ' + GetTabCols('dbo', tblGSDDoklady, 'main', false) + IfThen(selSpecDoklSD<>'', ',' + selSpecDoklSD, '') + ' FROM ' + tblGSDDoklady + ' main WHERE 1=0';
   lQry:= TFDQuery.Create(nil);
//   lQry.FetchOptions.AutoClose:= false;
//   lQry.FetchOptions.Mode:= fmAll;
   try
     lQry.Connection:= FDM.sqlConn;
     lQry.Open(lSQL);
     Result:= lQry.MetadataAsJSONObject();
    finally
     lQry.Free;
   end;
  end;





{ TGatemaSDScanDataService }

 function TGatemaSDScanDataService.GetByID (const AID: integer): TGatemaSDScanData;
  var lSQL: string;
      lQry: TFDQuery;
  begin
   lSQL:= 'SELECT ' + GetTabCols('dbo', tblGSDScanData) + ' FROM ' + tblGSDScanData + ' WHERE ID=:ID';

   lQry:= TFDQuery.Create(nil);
   try
     lQry.Connection:= FDM.sqlConn;
     lQry.Open(lSQL, [AID]);
     lQry.First;
     if not(lQry.EOF) then
      result:= lQry.AsObject<TGatemaSDScanData>
     else
      raise EServiceException.Create('Naskenovaná položka s ID ' + AID.ToString + ' nebyla nalezena.');
    finally
     lQry.Free;
   end;
  end;



 function TGatemaSDScanDataService.GetMeta: TJSONObject;
  var lSQL: string;
      lQry: TFDQuery;
  begin
   lSQL:= 'SELECT ' + GetTabCols('dbo', tblGSDScanData) + ' FROM ' + tblGSDScanData + ' WHERE 1=0';
   lQry:= TFDQuery.Create(nil);
   lQry.Connection:= FDM.sqlConn;
   lQry.FetchOptions.AutoClose:= false;
   lQry.FetchOptions.Mode:= fmAll;
   try
     lQry.Open(lSQL);
     Result:= lQry.MetadataAsJSONObject();
    finally
     lQry.Free;
   end;
  end;



 function TGatemaSDScanDataService.GetByParams (params: TDictionary<string, string>): TObjectList<TGatemaSDScanData>;
  var lSQL, where: string;
      id, idPZ, idPZold, cnt, rNo: integer;
      lQry: TFDQuery;
      pList: TObjectList<TGatemaSDScanData>;
      p: TGatemaSDScanData;
  begin
   p:= TGatemaSDScanData.Create;
   pList:= TObjectList<TGatemaSDScanData>.Create;

   lSQL:= 'SELECT ' + GetTabCols('dbo', tblGSDScanData, '', false) + ' FROM ' + tblGSDScanData;

   where:= '';

   id:= 0;
   if (params.ContainsKey('id')) then
    if (params.Items['id']<>'') then
     if (params.Items['id']<>'0') then
      begin
       id:= params.Items['id'].ToInteger;
       where:= where + 'ID=' + id.ToString;
      end;

   idPZold:= 0;
   if (params.ContainsKey('idpohzbo')) then
    if (params.Items['idpohzbo']<>'') then
     if (params.Items['idpohzbo']<>'0') then
      begin
       idPZold:= params.Items['idpohzbo'].ToInteger;
       where:= where + 'IdPohZbo=' + idPZold.ToString;
      end;

   if (params.ContainsKey('iddoklad')) then
    if (params.Items['iddoklad']<>'') then
     where:= where + IfThen(where<>'', ' AND ', '') + 'IDDokladSD=' + params.Items['iddoklad'];

   if (where<>'') then
    lSQL:= lSQL + ' WHERE ' + IfThen(id>0, 'ID=' + id.ToString, where);
   lSQL:= lSQL + ' ORDER BY IDDokladSD, ID';

//   lSQL:= lSQL.Replace('TabPohybyZbozi.', 'main.');


   lQry:= TFDQuery.Create(nil);
   try
     lQry.Connection:= FDM.sqlConn;
     lQry.FetchOptions.Mode:= fmAll;
     lQry.Open(lSQL);
     cnt:= lQry.RecordCount;
     pList:= TObjectList<TGatemaSDScanData>.Create;
     try
       lQry.First;
       rNo:= 1;
       while (rNo<=cnt) do
        begin
         lQry.RecNo:= rNo;
         idPZ:= lQry.FieldByName('ID').AsInteger;
         p:= self.GetByID(idPZ);
         pList.Add(p);
         if not(lQry.Active) then
          lQry.Open;
         Inc(rNo);
        end;
       result:= pList;
      except on E:Exception do
       raise EServiceException.Create('Chyba načítání naskenované položky/položek dokladu: ' + E.Message);
     end;
    finally
     FreeAndNil(lQry);
   end;
  end;








{ TRTNService }

 function TRTNService.GetPrikazy (params: TDictionary<string,string>): TObjectList<TVyrobniPrikaz>;
  var lQry: TFDQuery;
      sqlConnX: TFDConnection;
      lSQL, where, errMsg: string;
      lokIDcka: TList<integer>;
      cnt, rNo, idVPr: integer;
      typPrikazu: integer;
      operace, material, spustene: boolean;
      odDatum, doDatum, cisOper: string;
      strTemp: string;
      datOd, datDo: TDateTime;
      vpList: TObjectList<TVyrobniPrikaz>;
      p: TVyrobniPrikaz;
      vpSvr: TVyrobniPrikazService;
      locParams: TDictionary<string, string>;
  lokIDcko: TObject;
  begin
   cisOper:= '';

   locParams:= TDictionary<string, string>.Create;
   try

     operace:= false;
     if (params.ContainsKey('operace')) then
      if (params.Items['operace']='1') then
       begin
        operace:= true;
        locParams.Add('operace', params.Items['operace']);
       end;

     material:= false;
     if (params.ContainsKey('material')) then
      if (params.Items['material']='1') then
       begin
        material:= true;
        locParams.Add('material', params.Items['material']);
       end;

     spustene:= false;
     if (params.ContainsKey('spustene')) then
      if (params.Items['spustene']='1') then
       begin
        spustene:= true;
        locParams.Add('spustene', params.Items['spustene']);
       end;



     where:= '';
     lSQL:= 'SELECT DISTINCT(main.ID) AS ID FROM ' + tblVPr + ' main';


     if (spustene) then
      where:= where + IfThen(where<>'', ' AND ', '') + 'EXISTS (SELECT 1 FROM ' + tblPrPost + ' pp INNER JOIN ' + tblRozpracOperR
                                                     + ' r ON (r.DokladPrPostup=pp.Doklad AND r.AltPrPostup=pp.Alt AND r.IDPrikaz=pp.IDPrikaz)'
                                                     + ' INNER JOIN ' + tblRozpracOper + ' h ON (h.ID=r.IDEvidRozpracOper)'
                                                     + ' WHERE pp.IDOdchylkyDo IS NULL AND pp.IDPrikaz=main.ID AND h.DatumUzavreni IS NULL)';


     typPrikazu:= 0;
     if (params.ContainsKey('typ')) then
      if not(TryStrToInt(params.Items['typ'], typPrikazu)) then
       typPrikazu:= 0;

     locParams.Add('rtn', '1');
     locParams.Add('typPrikazu', typPrikazu.ToString);

     if (typPrikazu=0) then // obecny
      where:= where + IfThen(where<>'', ' AND ', '') + 'main.IDTabKmen IN (SELECT ID FROM ' + tblKZ + ' WHERE Dilec=1 AND Blokovano=0)';



     if (typPrikazu=1) then // pro micharnu se nacitaji vyssi prikazy, tj. kde testo skonci
      begin
       locParams.Add('nazevOp', 'michani');

       where:= where + IfThen(where<>'', ' AND ', '') + 'main.Rada=N''003'' AND main.IDTabKmen IN (SELECT ID FROM ' + tblKZ + ' WHERE Blokovano=0 AND SkupZbo=N''701'')';


       if (params.ContainsKey('idstroj')) then
         begin
          if (params.Items['idstroj']<>'') then
          where:= where + ' AND (main.IDPrikazVyssi IN (SELECT p.ID FROM ' + tblPrPost + ' pp INNER JOIN dbo.TabPrikaz p ON (p.ID=pp.IDPrikaz)'
                                                                                                        + ' WHERE pp.IDOdchylkyDo IS NULL'
                                                                                                        + '   AND p.StavPrikazu IN (30,40)'
                                                                                                        + '   AND pp.IDStroje=' + params.Items['idstroj'] + ')'
                                                                               + ' OR main.IDPrikazVyssi IN (SELECT ID FROM ' + tblPrikaz
                                                                               + '                            WHERE IDPrikazVyssi IN (SELECT px.ID FROM ' + tblPrPost + ' ppx'
                                                                                                          + ' INNER JOIN dbo.TabPrikaz px ON (px.ID=ppx.IDPrikaz)'
                                                                                                        + ' WHERE ppx.IDOdchylkyDo IS NULL'
                                                                                                        + '   AND px.StavPrikazu IN (30,40)'
                                                                                                        + '   AND ppx.IDStroje=' + params.Items['idstroj'] + '))'
                                                                               + ')';
  {
           where:= where + IfThen(where<>'', ' AND ', '') + 'main.IDPrikazVyssi IN (SELECT p.ID FROM ' + tblPrPost + ' pp INNER JOIN dbo.TabPrikaz p ON (p.ID=pp.IDPrikaz)'
                                                                                  + ' WHERE pp.IDOdchylkyDo IS NULL'
                                                                                  + '   AND p.StavPrikazu IN (30,40)'
                                                                                  + '   AND pp.IDStroje=' + params.Items['idstroj'] + ')'
                                                         + ' AND main.IDTabKmen IN (SELECT ID FROM ' + tblKZ + ' WHERE Blokovano=0 AND SkupZbo=N''701'')'
  }
         end;
  {
        else
         where:= where + IfThen(where<>'', ' AND ', '') + 'main.IDTabKmen IN (SELECT ID FROM ' + tblKZ + ' WHERE Dilec=1 AND Blokovano=0 AND SkupZbo=N''701'')';
  }
       if (params.ContainsKey('idstroju')) then
        begin
          if (params.Items['idstroju']<>'') then
           where:= where + ' AND (main.IDPrikazVyssi IN (SELECT p.ID FROM ' + tblPrPost + ' pp INNER JOIN dbo.TabPrikaz p ON (p.ID=pp.IDPrikaz)'
                                                                                                        + ' WHERE pp.IDOdchylkyDo IS NULL'
                                                                                                        + '   AND p.StavPrikazu IN (30,40)'
                                                                                                        + '   AND pp.IDStroje IN ' + params.Items['idstroju'] + ')'
                                                                               + ' OR main.IDPrikazVyssi IN (SELECT ID FROM ' + tblPrikaz
                                                                               + '                            WHERE IDPrikazVyssi IN (SELECT px.ID FROM ' + tblPrPost + ' ppx'
                                                                                                          + ' INNER JOIN dbo.TabPrikaz px ON (px.ID=ppx.IDPrikaz)'
                                                                                                        + ' WHERE ppx.IDOdchylkyDo IS NULL'
                                                                                                        + '   AND px.StavPrikazu IN (30,40)'
                                                                                                        + '   AND ppx.IDStroje IN ' + params.Items['idstroju'] + '))'
                                                                               + ')';

  {
           where:= where + IfThen(where<>'', ' AND ', '') + 'main.IDPrikazVyssi IN (SELECT p.ID FROM ' + tblPrPost + ' pp INNER JOIN dbo.TabPrikaz p ON (p.ID=pp.IDPrikaz)'
                                                                                  + ' WHERE pp.IDOdchylkyDo IS NULL'
                                                                                  + '   AND p.StavPrikazu IN (30,40)'
                                                                                  + '   AND pp.IDStroje IN (' + params.Items['idstroju'] + '))'
                                                         + ' AND main.IDTabKmen IN (SELECT ID FROM ' + tblKZ + ' WHERE Dilec=1 AND Blokovano=0 AND SkupZbo=N''701'')'
  }
        end;
      end;


     if (typPrikazu=2) then // pro macirnu
      begin
       locParams.Add('nazevOp', 'máčení');
       where:= where + IfThen(where<>'', ' AND ', '') + 'main.Rada IN (N''004'', N''002'') AND EXISTS (SELECT 1 FROM ' + tblPrPost + ' pp INNER JOIN ' + tblCisStroj + ' cs'
                                                      + ' ON (cs.ID=pp.IDStroje) INNER JOIN ' + tblCisStrojE + ' cse ON (cse.ID=cs.ID) WHERE pp.IDPrikaz=main.ID'
                                                      + ' AND pp.IDOdchylkyDo IS NULL AND pp.priorita=0 AND cse._MaceciStroj=1)';
  {
       where:= where + IfThen(where<>'', ' AND ', '') + 'main.Rada=N''004'' AND main.IDZakazModif IN (SELECT ID FROM '
                                                      + tblZakazModif + ' WHERE Schvaleno=1 AND Kod LIKE N''COKO%'')';
  }
  {
       if (params.ContainsKey('idpracovist')) then
        if (params.Items['idpracovist']<>'') then
         begin
          where:= where + IfThen(where<>'', ' AND ', '') + 'main.ID IN (SELECT p.ID FROM ' + tblPrPost + ' pp INNER JOIN dbo.TabPrikaz p ON (p.ID=pp.IDPrikaz)'
                                                                     + ' WHERE pp.IDOdchylkyDo IS NULL'
                                                                     + '   AND p.StavPrikazu IN (30,40)'
                                                                     + '   AND pp.pracoviste IN (' + params.Items['idpracovist'] + '))'
                                                        + ' AND main.IDTabKmen IN (SELECT ID FROM ' + tblKZ + ' WHERE Dilec=1 AND Blokovano=0 AND SkupZbo<>N''701'')'
         end;
  }
       if (params.ContainsKey('idstroju')) then
        begin
          if (params.Items['idstroju']<>'') then
           where:= where + IfThen(where<>'', ' AND ', '') + 'main.ID IN (SELECT p.ID FROM ' + tblPrPost + ' pp INNER JOIN dbo.TabPrikaz p ON (p.ID=pp.IDPrikaz)'
                                                                      + ' WHERE pp.Typ=1 AND pp.IDOdchylkyDo IS NULL AND p.StavPrikazu IN (30,40)'
                                                                      + '   AND pp.IDStroje IN (' + params.Items['idstroju'] + '))'
                                                         + ' AND main.IDTabKmen IN (SELECT ID FROM ' + tblKZ + ' WHERE Dilec=1 AND Blokovano=0 AND SkupZbo<>N''701'')'
        end;

       if (params.ContainsKey('idstroj')) then
         begin
          if (params.Items['idstroj']<>'') then
           where:= where + IfThen(where<>'', ' AND ', '') + 'main.ID IN (SELECT p.ID FROM ' + tblPrPost + ' pp INNER JOIN dbo.TabPrikaz p ON (p.ID=pp.IDPrikaz)'
                                                                      + ' WHERE pp.Typ=1 AND pp.IDOdchylkyDo IS NULL AND p.StavPrikazu IN (30,40)'
                                                                      + '   AND pp.IDStroje IN (' + params.Items['idstroj'] + '))'
                                                         + ' AND main.IDTabKmen IN (SELECT ID FROM ' + tblKZ + ' WHERE Dilec=1 AND Blokovano=0 AND SkupZbo<>N''701'')'
         end;
  {
        else
         where:= where + IfThen(where<>'', ' AND ', '') + 'main.IDTabKmen IN (SELECT ID FROM ' + tblKZ + ' WHERE Dilec=1 AND Blokovano=0 AND SkupZbo<>N''701'')';
  }
      end;


     if (typPrikazu=3) then // pro baleni (interni)
      begin
       locParams.Add('nazevOp', 'balení');
       where:= where + IfThen(where<>'', ' AND ', '') + 'EXISTS (SELECT 1 FROM dbo.TabPrPostup WHERE IDPrikaz=main.ID AND IdOdchylkyDo IS NULL'
                                                      + ' AND LOWER(Nazev) LIKE N''%balení%'' AND IDStroje NOT IN (SELECT ID FROM ' + tblCisStroj
                                                      + ' WHERE Blokovano=0 AND Kod LIKE N''BAL-%'') AND priorita=0)'; // main.Rada=N''004''
  {
       if (params.ContainsKey('idstroj')) then
        begin
         if (params.Items['idstroj']<>'') then
          where:= where + IfThen(where<>'', ' AND ', '') + 'main.ID IN (SELECT p.ID FROM ' + tblPrPost + ' pp INNER JOIN dbo.TabPrikaz p ON (p.ID=pp.IDPrikaz)'
                                                                      + ' WHERE pp.Typ=1 AND pp.IDOdchylkyDo IS NULL AND p.StavPrikazu IN (30,40)'
                                                                      + '   AND pp.IDStroje IN (' + params.Items['idstroj'] + '))'
                                                        + ' AND main.IDTabKmen IN (SELECT ID FROM ' + tblKZ + ' WHERE Blokovano=0 AND SkupZbo<>N''701'')'
        end;

       if (params.ContainsKey('idstroju')) then
        begin
          if (params.Items['idstroju']<>'') then
           where:= where + IfThen(where<>'', ' AND ', '') + 'main.ID IN (SELECT p.ID FROM ' + tblPrPost + ' pp INNER JOIN dbo.TabPrikaz p ON (p.ID=pp.IDPrikaz)'
                                                                      + ' WHERE pp.Typ=1 AND pp.IDOdchylkyDo IS NULL AND p.StavPrikazu IN (30,40)'
                                                                      + '   AND pp.IDStroje IN (' + params.Items['idstroju'] + '))'
                                                         + ' AND main.IDTabKmen IN (SELECT ID FROM ' + tblKZ + ' WHERE Dilec=1 AND Blokovano=0 AND SkupZbo<>N''701'')';
        end;
  }
      end;


     if (typPrikazu=4) then // pro balicku finalu
      begin
       locParams.Add('nazevOp', 'balení');
       where:= where + IfThen(where<>'', ' AND ', '') + 'EXISTS (SELECT 1 FROM dbo.TabPrPostup WHERE IDPrikaz=main.ID AND IdOdchylkyDo IS NULL'
                                                      + ' AND IDStroje IN (SELECT ID FROM ' + tblCisStroj + ' WHERE Blokovano=0 AND Kod LIKE N''BAL-%''))';
      end;


     if (typPrikazu=5) then // pro EWB
      begin
       locParams.Add('nazevOp', 'balení');
       where:= where + IfThen(where<>'', ' AND ', '') + 'EXISTS (SELECT 1 FROM dbo.TabPrPostup WHERE IDPrikaz=main.ID AND IdOdchylkyDo IS NULL'
                                                      + ' AND IDStroje IN (SELECT ID FROM ' + tblCisStroj + ' WHERE Blokovano=0 AND Kod LIKE N''EWB%''))';
      end;



     if (params.ContainsKey('odDatum')) then
      if (params.Items['odDatum']<>'') then
       odDatum:= params.Items['odDatum'];
     if (odDatum<>'') then
       begin
        if (Length(odDatum)=8) then
         odDatum:= odDatum + '000000';
        if (Length(odDatum)=10) then
         odDatum:= odDatum + '00';
        odDatum:= MidStr(odDatum, 7, 2) + '.' + MidStr(odDatum, 5, 2) + '.' + LeftStr(odDatum, 4) + ' ' + MidStr(odDatum, 9, 2) + ':' + MidStr(odDatum, 11, 2) + ':' + MidStr(odDatum, 13, 2);
        if not(TryStrToDateTime(odDatum, datOd)) then
         datOd:= IncDay(Now, -180)
       end
      else
       datOd:= IncDay(Now, -180);

     if (params.ContainsKey('doDatum')) then
      if (params.Items['doDatum']<>'') then
       doDatum:= params.Items['doDatum'];
     if (doDatum<>'') then
       begin
        if (Length(doDatum)=8) then
         doDatum:= doDatum + '235959';
        if (Length(doDatum)=10) then
         doDatum:= doDatum + '59';
        doDatum:= MidStr(doDatum, 7, 2) + '.' + MidStr(doDatum, 5, 2) + '.' + LeftStr(doDatum, 4) + ' ' + MidStr(doDatum, 9, 2) + ':' + MidStr(doDatum, 11, 2) + ':' + MidStr(doDatum, 13, 2);
        if not(TryStrToDateTime(doDatum, datDo)) then
         datDo:= Now
       end
      else
       datDo:= Now;

     if (odDatum<>'') then
      begin
       strTemp:= 'CONVERT(datetime, N' + FormatDateTime('dd.mm.yyyy', datOd).QuotedString + ',104)';
       where:= where + IfThen(where<>'', ' AND ', '') + 'main.DatPorizeni>=' + strTemp;
      end;

     if (doDatum<>'') then
      begin
       strTemp:= 'CONVERT(datetime, N' + FormatDateTime('dd.mm.yyyy', datDo).QuotedString + ',104)';
       where:= where + IfThen(where<>'', ' AND ', '') + 'main.DatPorizeni<=' + strTemp;
      end;


  // pro micharnu nejsou prikazy pozastavovany
     where:= where + IfThen(where<>'', ' AND ', '') + 'main.StavPrikazu IN (30' + IfThen(typPrikazu<>1, ',40', '') + ')';
     where:= where + IfThen(where<>'', ' AND ', '') + 'main.Rada<>N''009''';
     where:= where + IfThen(where<>'', ' AND ', '') + 'main.Rada LIKE N''0%''';


     if (where<>'') then
      lSQL:= lSQL + ' WHERE ' +  where;
     lSQL:= lSQL + ' GROUP BY main.ID ORDER BY main.ID';


     vpSvr := TVyrobniPrikazService.Create (self.FDM);
     try
       sqlConnX := TFDConnection.Create (nil);
       try
         sqlConnX.ConnectionDefName := sqlPoolName;
         sqlConnX.Open;

         lokIDcka := TList<Integer>.Create;
         try
           lQry := TFDQuery.Create (nil);
           try
             lQry.Connection := sqlConnX;
             lQry.FetchOptions.Mode := fmAll;
             lQry.Open (lSQL);

             cnt := lQry.RecordCount;

             if not lQry.Active then
              lQry.Open (lSQL);

             lQry.First;
             rNo := 1;

             try
               while (rNo <= cnt) do
               begin
                 lQry.RecNo := rNo;
                 idVPr := lQry.FieldByName('ID').AsInteger;
                 lokIDcka.Add (idVPr);
                 if not lQry.Active then
                  lQry.Open (lSQL);
                 Inc(rNo);
               end;

              except
               on E: Exception do
                begin
     {$IF CompilerVersion >= 37.0}  // Delphi 13+
                 raise EServiceException.Create ('Chyba načítání naskenované položky/položek dokladu') from E;
     {$ELSE}
                 raise EServiceException.Create ('Chyba načítání naskenované položky/položek dokladu: ' + E.Message) at ExceptAddr;
     {$ENDIF}
                end;
             end;

            finally
             lQry.Free;
           end;

           vpList := TObjectList<TVyrobniPrikaz>.Create;
           try
             for idVPr in lokIDcka do
              begin
               p := vpSvr.GetByID (idVPr, locParams, sqlConnX);
               vpList.Add (p);
              end;
             result := vpList;
             vpList := nil; // zabrani uvolneni v finally
            finally
             vpList.Free;
           end;

          finally
           lokIDcka.Free;
         end;

        finally
         sqlConnX.Free;
       end;

      finally
       vpSvr.Free;
     end;

    finally
    locParams.Free;
   end;

  end;





 function TRTNService.NactiDataZHeliosu (jsonData: string; var respData: string): string;
  var lSQL: string;
      lQry: TFDQuery;
      w: TStreamWriter;
      jo: TJsonObject;
  begin
   result:= '';
   respData:= '';
   try
    finally
   end;

  respData:= '[NotImplementedYet]'

  end;




 procedure TRTNService.ZapisJsonDoHeliosu (jsonData: string; var respString: string);
  var lSQL, taskStr, strTmp, strTmp2, code, rs: string;
      akce: string;
      j, t, a, v: JsonDataObjects.TJSONObject;
      i, ii, taskDZId, taskId, intTemp, idJSON: integer;
      jeOld: boolean;
      lQry: TFDQuery;
      sqlConnX: TFDConnection;
      w: TStreamWriter;
      jo: System.JSON.TJsonObject;
  begin
   idJSON:= 0;
   respString:= '[';

   jo:= System.JSON.TJsonObject.Create;

   jsonData:= jsonData.Trim;
   if (jsonData<>'') then
     begin

      sqlConnX:= TFDConnection.Create(nil);
      sqlConnX.ConnectionDefName:= sqlPoolName;

      lQry:= TFDQuery.Create(nil);
      try
        lQry.Connection:= sqlConnX;
        try
          lSQL:= 'INSERT ' + tblPrijataJsonData + ' (JSONData) SELECT N' + jsonData.QuotedString + CRLF + 'SELECT SCOPE_IDENTITY() AS newID';
          lQry.Open(lSQL);
          if (lQry.RecordCount=1) then
           begin
            idJSON:= lQry.FieldByName('newID').AsInteger;
            respString:= 'OK';
            jo.AddPair('heliosid', idJSON.ToString);
           end;
         except on E:Exception do
          begin
           respString:= 'NOT OK';
           raise EServiceException.Create('Chyba zápisu JSON dat: ' + E.Message);
          end;
        end;
       finally
        FreeAndNil(lQry);
      end;


      j:= TJsonObject.Parse(jsonData) as JsonDataObjects.TJsonObject;
      try
          if (j<>nil) then
           if (j.Contains('akce')) then
            begin
             akce:= j.S['akce'].Trim;
             if (idJSON>0) and (akce<>'') then
              sqlConnX.ExecSQL('UPDATE ' + tblPrijataJsonData + ' SET Akce=N' + akce.QuotedString + ' WHERE ID=' + idJSON.ToString);
{
             for i:=0 to j['tasks'].Count-1 do
              begin
               try
                 t:= j['tasks'].Items[i];
                 taskDZId:= t.I['id']; // j['tasks'].Items[i].I['id'];
                 taskStr:= j['tasks'].Items[i].ObjectValue.ToString;
                except on E:Exception do
               end;
              end;
}
            end;
       finally
        j.Free;
      end;

      sqlConnX.Close;
      sqlConnX.Free;

     end
    else
     respString:= 'NO input data';

   jo.AddPair('status', respString);
   respString:= '[' +respString + ']';

   respString:= jo.ToString;


  end;



end.
