import com.dvelop.d3.server.core.D3Interface;
import groovy.json.JsonSlurper;
 
String delReason    = "Aufbewahrungsfrist abgelaufen";
String sqlGetDocIDs = """SELECT doc_id, delete_date, db_tables_data FROM doc_recycler WHERE delete_reason = '${delReason}'
                            AND delete_date >= TO_DATE('2019-11-29', 'YYYY-MM-DD')
                            AND doc_id NOT IN (SELECT dokuid FROM bla_loeschprotokoll)""";
 
D3Interface d3 = getProperty("d3");
 
try {
   def mappingDocsSet = d3.sql.executeAndGet(sqlGetDocIDs);
   mappingDocsSet.each {
      String docID           = it.doc_id;
      String docTyp          = "";
      String docBemerkung    = "";
      String docIdentifier   = "";
      String docErstelldatum = "";
      String docDelDate      = it.delete_date.toString();
      docDelDate             = docDelDate.substring(0,10);//YYYY-MM-DD
 
      def slurper = new JsonSlurper();
      def docAttributes = slurper.parseText(it.db_tables_data);
      d3.log.info(docAttributes.get("com.dvelop.d3.DocumentData").get("firmen_spezifisch").get("dok_dat_feld_23"));
      docTyp          = docAttributes.get("com.dvelop.d3.DocumentData").get("firmen_spezifisch").get("dok_dat_feld_41");
      docBemerkung    = docAttributes.get("com.dvelop.d3.DocumentData").get("phys_datei").get("text");
      docIdentifier   = docAttributes.get("com.dvelop.d3.DocumentData").get("firmen_spezifisch").get("dok_dat_feld_23");
      docErstelldatum = docAttributes.get("com.dvelop.d3.DocumentData").get("firmen_spezifisch").get("dok_dat_feld_59");
      if (!docErstelldatum?.trim())
      {
         docErstelldatum = docAttributes.get("com.dvelop.d3.DocumentData").get("phys_datei").get("datum_einbring");
      }
      docErstelldatum = docErstelldatum.substring(0,10);//YYYY-MM-DD
 
      String sqlInsertLoschprotokoll = """INSERT INTO bla_loeschprotokoll (dokuid, typ, bemerkung, identifier, erstelldatum, loeschdatum)
                                          VALUES ('$docID', '$docTyp', '$docBemerkung', '$docIdentifier', TO_DATE('$docErstelldatum', 'YYYY-MM-DD'), TO_DATE('$docDelDate', 'YYYY-MM-DD'))""";
      try {
         d3.sql.execute(sqlInsertLoschprotokoll);
      } catch (Exception e) {
         d3.log.error("Fehler " + e.getMessage() + " beim Schreiben von bla_loeschprotokoll");
      }
   }
 
} catch (Exception e) {
   d3.log.error("Fehler " + e.getMessage() + " beim Lesen von doc_recycler");
}