-- -----------------------------------------------------
-- -----------------------------------------------------
-- -----------------------------------------------------
--[[
 API:
 engine:save(record) -- save info
 

  record example

record = { data={bid='xxx',firstname='',lastname=''}
           bot = { score = 0.9,
                   MSG = '',
                   sign = ''
                 }
         }


--]] local tick = CreateTimeServ()
local ss = analiz.libs.serv
local fileserv = CreateFileServ()
local finn_serv =analiz.mix.finnova.serv
local log = analiz.libs.logserv

 function go_pskill()
ss.l(debug.traceback())
  ss.l("go_pskill")
  ss.e("calc_param pskill_exe $(_ANALIZ_BIN)\\pskill.exe")
    ss.e("calc_param pskill_exe $(pskill_exe)")
  ss.e("GET_CURRENT_PROCESS_ID txm_pid")
    ss.e('echo execute $(pskill_exe) $(txm_pid)')
    ss.e('execute "$(pskill_exe)" $(txm_pid)')
  ss.e("_abort 1")
end

local org_engine =CreateOrgClientEngine()
 if OrgClientEngine_errors()~="" then
    ss.l(" failed load orgclients:"..OrgClientEngine_errors())
    ss.l("sleep&restart bot")
    ss.e("SLEEP sec 15")
    go_pskill()
    ss.a("1")
 end

local function fix_(val)

 if val==nil then return "" end

 val=""..val

 local function t(val,t,r) 
    if val:find(t)==nil then return val end
    return ss.ReplaceValue(val,t,r)
 end

 val=t(val,"'","''")
-- val=t(val,"\r"," ")
-- val=t(val,"\n"," ")
-- if val:len()>200 then val=val:sub(1,200) end
 return val
end

-- -----------------------------------------------------
-- -----------------------------------------------------
-- -----------------------------------------------------

local function sec_fun(key, val) return seclevel:get("data", key, val) end

function CreateBot2Nc()
  local e = {}
  e.sql_ = ss.CreateKmpSQL()
  e.whitelist_serv = botWhiteListServ
  e.white_list_cache_nc_params={}

-- ----------------------------------------------------------------------
  function e:parse(r,message_separator)
    if message_separator==nil then 
       ss.l("failed: message_separator is null")
       ss.l(debug.traceback())
    end
    local model_result = self:parse_msg(r.bot.MSG,message_separator)
    return model_result
  end


local function load_params_(p)
   local function zp(arg)
    if arg==nil then return "NULL" end
    if arg=="" then return "NULL" end
    return "'"..arg.."'"
   end
--  local sql = "SET NOCOUNT ON \nEXECUTE  [dbo].[gsp_PrepareOrgClientsSettings] ".. zp(p.F_BANK_ID)..", "..zp(p.profile)..",'NC_',"..zp(p.isTestClient)..""
  local sql = "SET NOCOUNT ON \nEXECUTE  [dbo].[gsp_PrepareOrgClientsSettings] ".. zp(p.profile)..", "..zp(p.orgclient)..",'NC_',"..zp(p.isTestClient)..""
--  local sql = "SET NOCOUNT ON \nEXECUTE  [dbo].[gsp_PrepareOrgClientsSettings_tst2] ".. zp(p.orgclient)..", "..zp(p.profile)..",'NC_',"..zp(p.isTestClient)..""


   ss.e("CREATE_OR_CLEAR_STRING_MAP tmp_map")
   ss.s("tmp",sql)
   ss.e("echo ANALIZ_SAFE_EXECUTE tmp_r emessage ADD_MAP_FROM_SQL_V1 tmp_map PLIB Name Value $(tmp)")
   ss.e("ANALIZ_SAFE_EXECUTE tmp_r emessage ADD_MAP_FROM_SQL_V1 tmp_map PLIB Name Value $(tmp)")
   local  emessage = ss.g("emessage")
   if emessage~="" then ss.l("failed:"..emessage.." sql:"..sql) end
ss.l("_____________")
  ss.e("SHOW_STRING_MAP tmp_map")
ss.l("_____________111")
   local m1 = ss.map2obj("tmp_map")
  ss.tprint(m1)
ss.l("_____________222")
   return m1,emessage

end

-- ----------------------------------------------------------------------
  function e:WhiteListFiltring(model_result,partnerID,op)
    if #model_result==0 then 
         ss.l("e:WhiteListFiltring.skip (model result.size=0)")
         return
    end

    ss.l("e:WhiteListFiltring.start")
    if op==nil then 
      ss.l("failed.op ==nil")
      ss.l(debug.traceback())
      ss.a(1)
    end

    local bank_id = op.BANK_ID
    local current_record = op.cache

--ss.tprint(val)
  local orgcli = org_engine:get_ex(bank_id)
--ss.tprint(orgcli)
  local real_profile = ss.def(current_record.PROSPERO_PROFILE_NAME,"undef_profile")

 local param_key = orgcli.orgclient_.."_"..real_profile

    local nc_params = self.white_list_cache_nc_params[param_key]
    if nc_params==nil then 
      nc_params=""
--      local curr_profile = op.org_engine:get_ex(bank_id).advanced_

   local params = load_params_({F_BANK_ID=bank_id,profile =real_profile,orgclient=orgcli.orgclient_,isTestClient=orgcli.isTest})

      for k,v in pairs(params) do
        if k:find("NC_")==1 then 
         nc_params=nc_params.."insert @params select '"..k.."','"..fix_(v).."' \n"
        end
      end
      self.white_list_cache_nc_params[param_key]=nc_params
    end

    local cache={}
local sql= [[
declare @items dbo.White_Items
declare @params dbo.Params 
]]

    for i=1,#model_result do
      local rec =model_result[i]
--     ss.l("______:"..i..":"..ss.toJson(rec))

      local listid=rec.listId
      sql = sql.."insert @items select '"..listid.."','"..fix_(rec.msg).."' \n"
      cache[listid]=i
     end
sql = sql.."\n"
sql = sql.."insert @params select 'BANK_ID','"..bank_id.."' \n"
sql = sql.."insert @params select 'CUSTOMER_ID','"..ss.def(partnerID,"").."' \n"
sql = sql.."insert @params select 'ACCOUNT','"..ss.def(current_record.ACCOUNT,"").."' \n"

sql = sql..nc_params

sql = sql.."exec dbo.WhiteListBot @items   ,@params"
--[[
local engine = createSqlEngine({sql=sql,isUpperHeader="1",ENGINE_TYPE="sqlapi",pwd="AmlWeb"})
 local res = {}
 while engine:Next() do
   local r = engine:Record()
   res[r.ID]=r.VAL
 end
engine:Destroy()
--]]
    ss.e("CREATE_OR_CLEAR_STRING_MAP map_whiteBot")
    ss.s("tmp",sql)
    ss.e("echo ADD_MAP_FROM_SQL_V1 map_whiteBot AmlWeb ID VAL $(tmp)")
    ss.e("ANALIZ_SAFE_EXECUTE tmp_r emessage ADD_MAP_FROM_SQL_V1 map_whiteBot AmlWeb ID VAL $(tmp)")  
    local emessage = ss.g("emessage")
    if emessage~="" then 
     ss.l("failed:"..emessage)
     ss.l("sql:\n"..sql)
     return emessage
    end

   ss.l("point 2")
    local res = ss.map2obj("map_whiteBot")

    for k,v in pairs(res) do
       local listid=k
       local i=cache[listid]
       if i~=nil then 
       model_result[i].whitelist=true
       else
         ss.l("failed: not found list id:"..listid)
       end
    end
ss.l("e:WhiteListFiltring.end")

   end

-- ----------------------------------------------------------------------------------
-- ----------------------------------------------------------------------------------

  function e:WhiteListFiltring_old(model_result,partnerID)
    if #model_result==0 then return end
ss.l("e:WhiteListFiltring.old.start")
    local cache={}

--    local sql= "select distinct List_ID as ID, 1 as VAL from WhiteList where PartnerID = '"..partnerID.."' and List_ID in( "

local sql= [[select distinct w.List_ID as ID, 1 as VAL , n.F_CUSTOMER_ID from WhiteList w
join staging_namecheck.dbo.NAMECHECK n on n.BUSINESSCASEID=w.PartnerID 
where n.F_CUSTOMER_ID=']]..ss.def(partnerID,"").."' and List_ID in( "



            
    for i=1,#model_result do
      local rec =model_result[i]
     ss.l("______:"..i..":"..ss.toJson(rec))

      local listid=rec.listId

      if i~=1 then sql=sql.."," end
      sql=sql.."'"..listid.."'"
      cache[listid]=i
    end
    sql=sql..")"
    ss.e("CREATE_OR_CLEAR_STRING_MAP map_whiteBot")
    ss.s("tmp",sql)
    ss.e("echo ADD_MAP_FROM_SQL_V1 map_whiteBot PLIB ID VAL $(tmp)")
    ss.e("ADD_MAP_FROM_SQL_V1 map_whiteBot PLIB ID VAL $(tmp)")
   ss.l("point 2")
    local res = ss.map2obj("map_whiteBot")

    for k,v in pairs(res) do
       local listid=k
       local i=cache[listid]
       model_result[i].whitelist=true
    end
ss.l("e:WhiteListFiltring.old.end")
  end


-- ----------------------------------------------------------------------
  function e:GetFiltredResult(model_result)

    local res={MSG=0,score=0,sign="0"}
    for i=1,#model_result do
      local rec =model_result[i]
      if not(rec.whitelist==true) then
         local rr = analiz:tonumber(rec.score)
         if rr>res.score then res.score=rr end
         res.sign="1"
         local rule = fileserv:ExtractName(rec.model)
         local msg  = rec.msg
         if res.MSG~="" then res.MSG=res.MSG..";" end
         local mm = rule..":"..msg..":"..rec.score
         res.MSG=res.MSG..mm
      end
    end
    return res
  end

-- ----------------------------------------------------------------------
  function e:save(r,model_result)
ss.l("e:save.1")
 local engine =  createSqlEngine({pwd="AmlWeb",sql="."})
--  write namecheck
ss.l("e:save.4")
 local options={}
  self:write_namecheck(engine,r,options)
ss.l("e:save.2")
  self:write_singleResult(r,model_result)
  --  write nameresult
ss.l("e:save.3")
  self:write_nameresult(engine,r,model_result)
  
ss.l("e:save.5")
  engine:Destroy()
ss.l("e:save.end")
  end
-- ---------------------
function e:show_parse(r1)
  ss.l("show_parse:"..#r1 )
  for i=1,#r1 do
   ss.l(i..":"..ss.toJson_sort(r1[i]))
  end
end

function e:parse_msg_todo(msg)

  local mm = ss.mysplit(msg,";")

  local res = {}

  local r={}
  local i = 1
  local cur_type = "rule"
  while i<#mm do
    local str = mm[i]
    if cur_type=="rule" then
     if cur_type:find("Range")==1 then
       str= ss.def(ss.mysplit(str,":")[2],"failed parse:"..str)
     end
     r={rule=str}
     cur_type = "message"
    elseif cur_type == "message" then
    end
    end

end
-- ---------------------
function e:parse_msg_ver1(msg)
  ss.l("msg:"..msg)
  local mm = ss.mysplit(msg,"[d];")
--  local mm = ss.mysplit(msg,":")
  local size = math.floor(#mm/3)


  ss.l("size(;):"..size)
-- ss.tprint(mm)
-- ss.a("1")
  local res = {}
  for i=1,size do
   local r ={}
   r.rule = mm[i*2-1]
   local str = mm[i*2]
--   ss.l(i.."__rule:"..ss.def(r.rule,"nil"))
--   ss.l(i.."___msg:"..ss.def(str,"nil"))
   local a1 = ss.mysplit(str,":")
   r.msg   = ss.def(a1[1],"")
   r.score = ss.def(a1[2],"")
  res[#res+1] = r
  end
  return res
end
-- --------------------------------------------------------------
local function parse_v2(n)
  local res={} 
  local f = n:find("[%d+];")

  while f~=nil do
    local ff = n:sub(1,f)
    n = n:sub(f+2,n:len())
    res[#res+1]=ff
    f = n:find("[%d+];")
  end
  if n~="" then     res[#res+1]=n end

  return res
end

-- --------------------------------------------------------------
local function parse_v4(n,message_sepatator)
  local res={} 
  local slen = #message_sepatator;
  local t = "[%d+]"..message_sepatator

  local f = n:find(t)

  while f~=nil do
    local ff = n:sub(1,f)
    n = n:sub(f+1+slen,n:len())
    res[#res+1]=ff
    f = n:find(t)
  end
  if n~="" then     res[#res+1]=n end

  return res
end


-- -------------------------------------
function e:parse_msg_ver2(msg)
  if msg==nil then msg="" end
  ss.l("msg:"..msg)
  local rules = parse_v2(msg)

  local size = #rules
  ss.l("size(;):"..size)
-- ss.tprint(mm)
-- ss.a("1")
  local res = {}
  for i=1,size do
   local r ={}
   local str = rules[i]
   local a1 = ss.mysplit(str,":")
   r.model = ss.def(a1[1],"")
   r.rule  = fileserv:ExtractName(r.model)
   r.listId= self.whitelist_serv:GetListID(r.model)
   r.msg   = ss.def(a1[2],"")
   r.score = ss.def(a1[3],"")
  res[#res+1] = r
  end
  return res
end

function e:parse_msg_ver3(msg)

        function split_(str)
            local i = str:find(":")
            if i == nil then return "", "" end
            return str:sub(1, i - 1), str:sub(i + 1)
        end
  if msg==nil then msg="" end
  local rules = parse_v2(msg)
  local res = {}

 local size = #rules
  ss.l("size(;):"..size)
  for i=1,size do
   local r ={}
   local str = rules[i]
  local tail

   r.model,tail =  split_(str)
   ss.l(str)
   ss.l(r.model)
   r.rule  = fileserv:ExtractName(r.model)
   r.listId= self.whitelist_serv:GetListID(r.model)

--   ss.l("tail:"..tail)
   local rtail = tail:reverse()
   local a1,a2 = split_(rtail)
   r.msg   = a2:reverse()
   r.score = a1:reverse()
  res[#res+1] = r
  end
  return res
end

function e:parse_msg_ver4(msg,message_separator)

        function split_(str)
            local i = str:find(":")
            if i == nil then return "", "" end
            return str:sub(1, i - 1), str:sub(i + 1)
        end
  if msg==nil then msg="" end
  local rules = parse_v4(msg,message_separator)
  local res = {}

 local size = #rules
  ss.l("size(;):"..size)
  for i=1,size do
   local r ={}
   local str = rules[i]
  local tail

   r.model,tail =  split_(str)
   ss.l(str)
   ss.l(r.model)
   r.rule  = fileserv:ExtractName(r.model)
   r.listId= self.whitelist_serv:GetListID(r.model)

--   ss.l("tail:"..tail)
   local rtail = tail:reverse()
   local a1,a2 = split_(rtail)
   r.msg   = a2:reverse()
   r.score = a1:reverse()
  res[#res+1] = r
  end
  return res
end

-- --------------------------------------------------------------
function e:parse_msg(msg,message_separator)

--  return self:parse_msg_ver1(msg)
--  return self:parse_msg_ver2(msg)
--  return self:parse_msg_ver3(msg) --10.10.2019
  return self:parse_msg_ver4(msg,message_separator) --15.07.2024 patch1643
end

local function adds_(val)
  if val==NULL then return ",NULL" end
  if val:find("'")~=nil then val =ss.ReplaceValue(val,"'","''") end
  if val=="not found(finasMQ)" then return ",''" end
  return ",'"..val.."'"
end

local function addf_(val) --float
  if val==NULL then return ",NULL" end
  if val:find("'")~=nil then val =ss.ReplaceValue(val,"'","") end
  if val:find("\n")~=nil then val =ss.ReplaceValue(val,"\n","") end
  if val:find("\r")~=nil then val =ss.ReplaceValue(val,"\r","") end
  if val:find(",")~=nil then val =ss.ReplaceValue(val,",",".") end
  if val=="not found(finasMQ)" then return ",NULL" end
  return ",'"..val.."'"
end

 local function adds2_(val,val2)

  if val==nil then return adds_(val2) end
  return adds_(val)
 end


-- ------------------------------------------------------------------------------
function e:write_nameresult_rec(db_engine,r,r1,ri,recno,offset)
--  ss.tprint(r)
--  ss.a("1")

--local ri = r1[num]

local lastname = "Rule based alert "..ri.rule
local sql = [[
INSERT INTO [dbo].[NAMERESULT]
([BusinessCaseID],[REC_NUMBER],[Hits],[IS_WHITELIST_HIT]
,[Firstname],[Lastname],[add_name1],[add_name2]
,[EFF_THRESHOLD_LEVEL],[Eff_Threshold],Check_Threshold
,[Fi_completeDesc],[Creation_Date],[ProcessingID],[List]
,[Marked],[Comment],[Comment_ID],[Status],[Category],[LIST_ID],
RecordType)
VALUES
           (']]..r.data.bid.."',"..recno+offset..",1,'0'"
           ..adds_(r.data.firstname)
           ..adds_(lastname)
           ..adds_(ri.msg) --add_name1
           ..adds_(r.data.add_name2)
           ..adds_('02') --,<EFF_THRESHOLD_LEVEL, varchar(2),>
           ..adds_(ri.score) --,<Eff_Threshold, varchar(20),>
           ..adds_("02") --r.data.,<Check_Threshold, varchar(2),>
           ..adds_(self:GenerateFi_completeDesc(r,ri)) --Fi_completeDesc, text,>
           ..",GetDate()"--<Creation_Date, datetime,>
           ..",NULL"--<ProcessingID, varchar(50),>
           ..adds_(ri.rule)--<List, varchar(500),>
           ..",NULL"--<Marked, varchar(2),>
           ..",NULL"--<Comment, varchar(1000),>
           ..",-1"--<Comment_ID, bigint,>
           ..",NULL"--<Status, int,>
           ..",NULL"--<Category, varchar(25),>
           ..adds_(ri.listId)
           ..adds_("RuleSet") --recordType
..")"
 ss.l("e:write_nameresult_rec.1")
 self.sql_:setSql(sql)
 ss.l("e:write_nameresult_rec.2")
 ss.l("e:write_nameresult_rec.2.sql:"..sql)
 db_engine:ExecSqlEx(self.sql_)
 ss.l("e:write_nameresult_rec.3")
end

-- ---------------------------------------------------------------------
function e:write_singleResultRec(r,rec)
local lastname = "Rule based alert "..rec.rule
local firstName=r.data.firstname
local LastName=lastname
local bid=r.data.bid
local listid=rec.listId
local score=rec.score  



 return "('"..bid.."','"..ss.def(listid,"-1").."',"..score..",GetDate(),'"..firstName.."','"..LastName.."')"
end
function e:write_singleResult(r,model_result)
  local sql = "INSERT INTO [dbo].[SingleNamecheckResults] ([BID],[RID],[SCORE],[dt],[FirstName],[LastName]) VALUES"
  for i=1,#model_result do
   if i~=1 then sql=sql..",\n" end
   sql =sql..self:write_singleResultRec(r,model_result[i])
  end
  if #model_result>0 then
    ss.s("tmp",sql)
    ss.e("EXEC_SQL PLIB $(tmp)")
  end
end
-- ---------------------------------------------------------------------
function e:write_nameresult(db_engine,r,r1)
  local offset=0
  do
   local sql = "select count(*) as C from NAMERESULT where BusinessCaseID = '"..r.data.bid.."'"
   analiz:execute("ANALIZ_SAFE_EXECUTE tmp_r tmp_e  SET_PARAM_FROM_SQL tmp AmlWeb C "..sql)
   offset = analiz:tonumber(ss.g("tmp")) 
  end
  local kk=0
  for i=1,#r1 do
   local rec =r1[i]
   if not(rec.whitelist==true) then
     kk=kk+1
     self:write_nameresult_rec(db_engine,r,r1,rec,kk,offset)
   end
  end
end



-- ---------------------------------------------------------------------
--function e:GenerateFi_completeDesc(r,r1,i)
function e:GenerateFi_completeDesc(r,ri)
--  local ri = r1[i]
--  ss.tprint(ri)
--  ss.a("1")
local buf = ss.CreateStringBuffer ()
buf:add('<?xml version="1.0" encoding="iso-8859-1" standalone="no" ?><sncrecord><nameparts>')
buf:add('<lastname>Alert generared by the business rules configuration '..ss.def(ri.rule,"rule XXX").. '</lastname>')
buf:add('<add_name1>'..ss.def(ri.rule,"rule XXX")..'</add_name1><add_name2></add_name2></nameparts><persondetails>')
buf:add('<detail key="Message" value="Country XXXX in list of countries YYYYY"/>')
buf:add('</persondetails><filterdetails><detail key="Date of publication to p.Lib repository" value=""/>')
buf:add('<detail key="Check Threshold Level" value=""/>')
buf:add('<detail key="Effective Threshold Level" value="01"/><detail key="IsWhitelist" value="no"/>')
buf:add('<detail key="Effective Threshold Value" value="1"/><detail key="Internal list name" value=""/>')
buf:add('<detail key="Version" value="0.0"/><detail key="Description" value=""/></filterdetails>')
buf:add('</sncrecord>')
 return buf:to_string()
end
-- ---------------------------------------------------------------------

function e:write_namecheck(db_engine,r,options)
 local is_kundenstamm = finn_serv.IsKundenstamm(r.data)
 if is_kundenstamm then
  self:write_namecheck_Kundenstamm(db_engine,r,options)
 else
  self:write_namecheck_CheckPayment(db_engine,r,options)
 end
end

function e:write_namecheck_Kundenstamm(db_engine,r,options)
  local op ={}
  if options==nil then options={} end
    op.lexengine = ss.def(r.meta.lex_engine,"bot_engine")--r.meta.lex_engine
  op.org_engine = org_engine
--  op.curr_profile= options.curr_profile
  local name = {raw={cache=r.data},bid=r.data.bid,USERNAME=r.data.USERNAME}
--  name.USERNAME = "todo.USERNAME"
  finn_serv.toNAMECHECK_kundenstamm(name,op)
end

function e:write_namecheck_CheckPayment(db_engine,r,options)

  local bank_id =ss.def(r.data.F_BANK_ID,"-1")
ss.l("e:write_namecheck_CheckPayment.start.bank_id:"..bank_id)
  local curr_profile = {}
  if options==nil then options={} end

  if org_engine~=nil then 
   ss.l("load profile for bank_id:"..bank_id)
   curr_profile = org_engine:get_ex(bank_id).advanced_
  else
   ss.l("org_engine is NULL")
   ss.tprint(r.data)
 end




local buf = ss.CreateStringBuffer ()
buf:add([[IF not exists(select * from NAMECHECK where BUSINESSCASEID=']]..r.data.bid..[[') ]]) 
buf:add([[INSERT INTO [dbo].[NAMECHECK]
([BUSINESSCASEID],[FIRSTNAME],[LASTNAME]
,[ADDITIONAL_NAME1],[ADDITIONAL_NAME2]
,[DATE_OF_BIRTH],[CHECK_THRESHOLD]
,[MANDANT],[COUNTRY_CODE],[WORKING_STATE]
,[TYPE_FLAG],[FEEDBACK_FLAG]
,[DOB],[Nationality],[Country]
,[Address],[USERNAME],[CREATION_DATE]
,[PartnerID],[lex_engine],[SanctionListCheckOnly]
,[StrictFiltering],[Remittance]
,[F_CUSTOMER_ID],[F_BANK_ID],[F_ORDER_ID]
,[F_ORDER_NR],[F_PAYMENT_ID],[F_PAYMENT_SYSTEM_ID]
,[F_ACCOUNT_ID],[F_PORTFOLIO_ID]
,[F_CONTRACT_ID],[F_PAYMENT_SYSTEM]
,[F_PAYMENT_TYPE],[MSG_UUID],[F_PROCESS_CODE],PROCESS_CODE
,[F_COMM_TYPE],[ExtractedNames_addr],[ExtractedNames_remittance],
F_CUSTOMER_NR,
AMOUNT,CURRENCY,SWIFT_CODE,BANK_NAME,ACCOUNT,F_CS_MSG_LNR,
NOGA_CODE,F_PARTNER_CODE]])
do
 local a = global_oracle_setting.fields.xml_fields_ex
 for i=1,#a do
   buf:add(","..a[i]:upper())
 end
end

   buf:add(") VALUES (")

-- -----------------
ss.l("write namechecking...")
ss.l("data:")
log.tprint_array(r.data,{transform=sec_fun,level=log.level.DEBUG})
buf:add("'"..r.data.bid.."'")-- <BUSINESSCASEID,varchar(50),>
if r.data.firstname==nil then
  buf:add(adds_(r.data.firstname) )--FIRSTNAME,varchar(100),>
else
  buf:add(adds_(r.data.FIRSTNAME) )--FIRSTNAME,varchar(100),>
end

buf:add(adds_(finn_serv.ExtractLastNameForNC(r.data.lastname,{curr_profile=curr_profile, isKundestamm=false})) )--LASTNAME,varchar(100),>
buf:add(adds_(r.data.addname1) )--ADDITIONAL_NAME1,varchar(100),>
buf:add(adds_(r.data.addname2) )--ADDITIONAL_NAME2,varchar(100),>
buf:add(adds_(nil) )--DATE_OF_BIRTH,datetime,>
buf:add(adds_("02") )--CHECK_THRESHOLD,varchar(2),>
buf:add(adds_(org_engine:get(r.data.F_BANK_ID)) )--MANDANT,varchar(40),>
buf:add(adds_() )--COUNTRY_CODE,varchar(3),>
buf:add(adds_("1") )--WORKING_STATE,varchar(2),>
buf:add(adds_() )--TYPE_FLAG,varchar(5),>
buf:add(adds_(nil) )--FEEDBACK_FLAG,varchar(10),>
buf:add(adds_(r.data.DOB) )--DOB,varchar(255),>
buf:add(adds_(r.data.nationality) )--Nationality,varchar(255),>
buf:add(adds_(r.data.country) )--Country,varchar(255),>
--buf:add(adds_(r.data.address) )--Address,varchar(4000),>
buf:add(adds_(r.data.ADDRESS_RAW) )
buf:add(adds_(r.data.USERNAME) )--USERNAME,varchar(20),>
buf:add(",getDate()" )--CREATION_DATE,datetime,>
buf:add(adds_(r.data.PartnerID) )--PartnerID,varchar(50),>
buf:add(adds_(ss.def(r.meta.lex_engine,"bot_engine") ))--lex_engine,varchar(255),>
buf:add(adds_() )--SanctionListCheckOnly,int,>
buf:add(adds_() )--StrictFiltering,int,>
buf:add(adds2_(r.data.REMITTANCE_RAW,r.data.remittance) )--Remittance,varchar(4000),>
buf:add(adds_(r.data.F_CUSTOMER_ID) )--F	_CUSTOMER_ID,varchar(100),>
buf:add(adds_(r.data.F_BANK_ID) )--F_BANK_ID,varchar(255),>
buf:add(adds_(r.data.F_ORDER_ID) )--F_ORDER_ID,varchar(255),>
buf:add(adds_(r.data.F_ORDER_NR) )--F_ORDER_NR,varchar(255),>
buf:add(adds_(r.data.F_PAYMENT_ID) )--F_PAYMENT_ID,varchar(255),>
--buf:add(adds_(r.data.F_PAYMENT_SYSTEM) )--F_PAYMENT_SYSTEM_ID,varchar(255),>
buf:add(adds_(r.data.F_PAYMENT_SYSTEM_ID) )--F_PAYMENT_SYSTEM_ID,varchar(255),>
buf:add(adds_(r.data.F_ACCOUNT_ID) )--,[F_ACCOUNT_ID],
buf:add(adds_(r.data.F_PORTFOLIO_ID) )--[F_PORTFOLIO_ID]

buf:add(adds_(r.data.F_CONTRACT_ID) )--,[F_CONTRACT_ID],
buf:add(adds_(r.data.F_PAYMENT_SYSTEM) )--[F_PAYMENT_SYSTEM]
buf:add(adds_(r.data.F_PAYMENT_TYPE) )--,[F_PAYMENT_TYPE],
buf:add(adds_(r.data.MSG_UUID) )--[MSG_UUID],
buf:add(adds2_(r.data.F_PROCESS_CODE,r.data.PROCESS_CODE)) --buf:add("--[F_PROCESS_CODE]\n")--[F_PROCESS_CODE]
buf:add(adds2_(r.data.PROCESS_CODE,r.data.F_PROCESS_CODE))--[PROCESS_CODE]
buf:add(adds_(r.data.F_COMM_TYPE) )--,[F_COMM_TYPE],
buf:add(adds_(r.data.ADDRESS) )--[ExtractedNames_addr],
buf:add(adds_(r.data.REMITTANCE) )--[ExtractedNames_remittance]
buf:add(adds_(r.data.F_CUSTOMER_NR))
buf:add(addf_(r.data.AMOUNT))
buf:add(adds_(r.data.CURRENCY))
buf:add(adds_(r.data.SWIFT_CODE))
buf:add(adds_(r.data.BANK_NAME))
buf:add(adds_(r.data.ACCOUNT))
buf:add(adds_(r.data.F_CS_MSG_LNR))
buf:add(adds_(r.data.F_NOGA_CODE))
buf:add(adds_(r.data.F_PARTNER_CODE))
do
 local a = global_oracle_setting.fields.xml_fields_ex
 for i=1,#a do
   local key = a[i]:upper()
   local val = r.data[key]
   buf:add(adds_(val))
 end
end
buf:add(")")


 local sql = buf:to_string()
--  ss.l("sql:"..sql)
 self.sql_:setSql(sql)
 db_engine:ExecSqlEx(self.sql_)
  ss.l("after")
end

  return e
end

