# -*- coding: utf-8 -*-

from ppms import ppms
from ppms.migration.packet import *

DBMS_ORACLE = '000002'

BEFORE_HASH = [('0fbc9acd9d18b34cd84b219ea02889d3','a4b33516708c05876a00af8f3f9672b2'),('04c0156ba438c0ffe3aa88769f9d100f','78e4bd8f63f4f461a13a50a1e3e09507'),('fd1e87bbc34745b1e1befdf616d469f5','fd1e87bbc34745b1e1befdf616d469f5'),
               ('c3cdcdcbe33e0ea0b36dff7114a64e5b','411fa8435bd65fe5c0445904cb205dce'),('57702478c23c3e5b16d6964bf697762d','ec7ae9481869e893d0ec9a1793c545dd'),('c8e02d9b24229278e1fc585a18602179','204a852fc2fa8edb6e812df17c13c4b2'),
               ('94a36cec4f6f0e162d6e25f7a38b01ed','0b38f61614890f723e0970c42940f496'),('2f6fdd08c947d6286590694ffa5a59f7','0a28846a94c9931f0abbf9165de9e1d7'),('6b0784d8c59bee8db4e7478debd71afb','6b0784d8c59bee8db4e7478debd71afb')]
               
AFTER_HASH = ['8fc225774e93d90c24d379b2af5c3b37','9cc79b97309b0824bed759be86af0278','020616456be56162874e8e36ebe088a3',
              '8926c9babd9762566ea73ef355f6c760','4b366a9661418ae8aeaea7fc4d71f91c','6b5d917673415c8aefd7e21418d37af9',
              '84be8c8c78baa691efa012f559081f2f','af7cb4e509c98148970afffb2bcd4748','e1983c52da266a5df0b21ae0dba7314e']
              
MODULES = ['009BTI','009BUE','009BTW','009BPE','009BTT','009BTZ','009BTS','009BTQ','009BUD']

FIX_FUNC = ['''mod_obj = ppms.get_target_module()

def on_load():
    mod_obj.set_current_L_var(103,['0'])
    mod_obj.set_current_L_var(102,['0'])
    mod_obj.set_current_L_var(101,['0'])
    mod_obj.menu(12)
    parameter_rec = mod_obj.get_da("import_header").get_records()[0].insert_child("import_id")

def on_reset():

    l101 = mod_obj.get_current_L_var()[101]
    if not l101:
        mod_obj.set_current_L_var(103,['0'])
        mod_obj.set_current_L_var(102,['0'])
        mod_obj.menu(12)
    else:
        mod_obj.menu(12)''',

'''from ppms import ppms
from ppms import ppms_cu

mod_obj = ppms.get_target_module()

mod_obj.menu(11)
mod_obj.menu(12)
config_header = mod_obj.get_da('background_header').get_records()[0].insert_child("config_header")

default_server_path = ppms.uvar_get('@10')
default_client_path = ppms_cu.Helper.get_global_setting("erp_export_path").alpha120.get_value()
default_filename_h = ppms_cu.Helper.get_global_setting("erp_export_file_h").alpha120.get_value()
default_filename_c = ppms_cu.Helper.get_global_setting("erp_export_file_c").alpha120.get_value()

config_header.exp_path_server.set_raw_value(default_server_path)
config_header.exp_path_client.set_raw_value(default_client_path)
config_header.file_h.set_raw_value(default_filename_h)
config_header.file_c.set_raw_value(default_filename_c)

header = config_header.header.get_raw_value()
mod_obj.set_current_L_var(103,[int(header)])
mod_obj.menu(12)
 
''',

'''mod_obj = ppms.get_target_module()
active_mod = ppms.get_active_module()
mod_obj.menu(12)
parameter_rec = mod_obj.get_da("import_header").get_records()[0].insert_child("config_parameter")
mod_obj.set_current_L_var(103,['0'])''',

'''from ppms import ppms
from ppms.sap_interface import get_records
import traceback

try:
    mod_obj = ppms.get_target_module()
    config_header = mod_obj.get_da('config_header').get_records()[0]
    header = config_header.header.get_raw_value()
    L101 = mod_obj.get_current_L_var()[101]
    is_testexport = config_header.export_mark.get_raw_value()

    def config_values(config_header):
        date_f = config_header.date_from.get_raw_value()
        date_t = config_header.date_to.get_raw_value()
        head_id = config_header.header.get_raw_value()

        if not date_f or not date_t:
            mod_obj.set_statusbar('Kein Bel. Datum')
            return "",""
        else:
            ppms.uvar_set('@D51',date_f)
            ppms.uvar_set('@D52',date_t)

            return head_id,date_t

    if header and not L101:
        head_id,date_t = config_values(config_header)
        is_deadline = config_header.deadline.get_raw_value()

        if is_deadline:
            ppms.echo_off()
            mod_parameter = mod_obj.open_module('009A0U')
            record = mod_parameter.get_das()[0].get_records()[0]
            record.deadline.set_raw_value(date_t)
            mod_parameter.menu(34)
            mod_parameter.menu(49)
            ppms.echo_on()
            mod_obj.menu(34)

        if date_t:
            get_records.fetch_records_from_DT472(header,is_testexport)
except:
    ppms.ui_message_box(traceback.format_exc())
''',

'''#!/usr/bin/env PYTHON
# -*- coding: utf8 -*-
import os
from ppms.sap_interface import file_import

SUFFIX = ['.csv','.txt']

mod_obj = ppms.get_target_module()
config_header = mod_obj.get_da('config_parameter').get_records()[0]

server_path = config_header.imp_path.get_raw_value()
file_imp = config_header.imp_filename.get_raw_value()

def check_filetype(file_imp):
    name, file_suffix = os.path.splitext(file_imp)
    if file_suffix in SUFFIX:
        return file_imp
    else:
        ppms.ui_message_id('0924')
        return False

def check_file_name(file_imp):
    if file_imp:
        file = os.path.join(server_path,file_imp)
        is_file = os.path.isfile(file)
        if is_file:
            return file_imp
        
        ppms.ui_message_id('0084')
        return False
        
    else:
        ppms.ui_message_id('0205')
        return False
        
if check_file_name(file_imp) and check_filetype(file_imp):
    if not server_path:
        ppms.ui_message_id('0247')
    
    else:
        records = file_import.read_file()''',
        
'''from ppms import ppms_cu

mod_obj = ppms.get_target_module()

class Locking:
    def __init__(self,status):
        self.status= status

    def __enter__(self):
        ppms_cu.Access.get_ppms_builtins("ppms")["lock_rec"]= self.status
        
    def __exit__(self, exc_type, exc_value, traceback):
        ppms_cu.Access.get_ppms_builtins("ppms")["lock_rec"]= ''

def set_configuration_output(mod_obj):
    finished_records = mod_obj.get_da('config_parameter').get_records()[0]
    finished_records_c = mod_obj.get_customizing().get_dac('config_parameter')
    
    field_to_output = ['740619','740617','740615',
                       '740613','740611','740607']
                       
    for df_id in field_to_output:
        finished_records.get_df_by_id(df_id).make_output()
    
    finished_records_c.get_dfc_by_id(740624).show(9)

    
# collect import parameter informations
config_records = mod_obj.get_da('config_parameter').get_records()[0]
config_id = config_records.config_id.get_raw_value()
trans_records = mod_obj.get_da('transfer_records').get_records()

if config_id and trans_records:
    auto_release = config_records.auto_release.get_raw_value()
    release_by_pl = config_records.release_by_pl.get_raw_value()
    post_all_records_to = config_records.post_all_records_to.get_raw_value()
    mod_obj.set_current_L_var(103,[config_records.config_id.get_raw_value()])
    
    #collect records with STATUS 20 for transer to DT472 / DT461
    for record in trans_records:
        is_released = record.is_released.get_raw_value()
        obligo_record = record.obligo_record.get_raw_value()
        sap_state = record.sap_state.get_raw_value()
        storno = record.storno.get_raw_value()
        
        if not obligo_record and (storno or not storno ) and is_released and (sap_state == 20 or sap_state == 12):
            values = {
                    'pr_id':record.rec_wbs_el.get_raw_value(),
                    'task_id':record.task_id_dt472.get_raw_value(),
                    'res_id':record.res_id_dt472.get_raw_value(),
                    'ct_id':record.ct_id_dt472.get_raw_value(),
                    'date':record.date_dt472.get_raw_value(),
                    'load_act':record.load_act_transfer.get_raw_value(),
                    'comment':record.comment_dt472.get_raw_value(),
                    'ou_cctr_of_res':record.ou_cctr_to_be_loaded_dt472.get_raw_value()
                    }
            
            with Locking(1):
                new_rec472 = ppms.create_record(472,values)
                new_rec472.save()
                record.get_dtp_record().sap_state.set_value(21)
                record.get_dtp_record().pos_dt472.set_value(new_rec472.item.get_value())
                record.get_dtp_record().pr_id_dt472.set_value(new_rec472.pr_id.get_value())
                new_rec472.sap_state.set_value(2)
                new_rec472.save()
                
        elif obligo_record and is_released and (sap_state == 20 or sap_state == 12):
            pr_id = record.rec_wbs_el.get_raw_value()
            rec461 = ppms.search_record(461,[pr_id],[41540,41541,41542,41543,41544],True)
            
            old_miscel_pay_oblig = rec461.miscel_pay_oblig.get_value()
            old_investm_pay_oblig = rec461.investm_pay_oblig.get_value()
            old_person_ext_pay_obl = rec461.person_ext_pay_obl.get_value()
            old_mat_costs_pay_obl = rec461.mat_costs_pay_obl.get_value()
            old_person_int_pay_obl = rec461.person_int_pay_obl.get_value()
            
            akt_miscel_pay_oblig = record.miscel_pay_oblig.get_raw_value()
            akt_investm_pay_oblig = record.investm_pay_oblig.get_raw_value()
            akt_person_ext_pay_obl = record.person_ext_pay_obl.get_raw_value()
            akt_mat_costs_pay_obl = record.mat_costs_pay_obl.get_raw_value()
            akt_person_int_pay_obl = record.person_int_pay_obl.get_raw_value()
            
            rec461.miscel_pay_oblig.set_value(old_miscel_pay_oblig+akt_miscel_pay_oblig)
            rec461.investm_pay_oblig.set_value(old_investm_pay_oblig+akt_investm_pay_oblig)
            rec461.person_ext_pay_obl.set_value(old_person_ext_pay_obl+akt_person_ext_pay_obl)
            rec461.mat_costs_pay_obl.set_value(old_mat_costs_pay_obl+akt_mat_costs_pay_obl)
            rec461.person_int_pay_obl.set_value(old_person_int_pay_obl+akt_person_int_pay_obl)
            
            rec461.save()
            mod_obj.refresh_dts((461))
            record.get_dtp_record().sap_state.set_value(21)
                
    
    mod_obj.menu(34)
    mod_obj.menu(19)
    mod_obj.set_current_L_var(103,[config_id])
    mod_obj.menu(12)
    set_configuration_output(mod_obj)

else:
    ppms.ui_message_id('0049')

''',

'''#MacroTemplate
from ppms import ppms_cu
mod_obj = ppms.get_target_module()
post_to_record = mod_obj.get_da('config_parameter').get_records()[0]

class Locking:
    def __init__(self,status):
        self.status= status

    def __enter__(self):
        ppms_cu.Access.get_ppms_builtins("ppms")["lock_rec"]= self.status

    def __exit__(self, exc_type, exc_value, traceback):
        ppms_cu.Access.get_ppms_builtins("ppms")["lock_rec"]= ''

def obligo():
    obligo_records = mod_obj.get_da('transfer_records').get_records()
    pr_id = post_to_record.pr_id.get_raw_value()
    all_post =  post_to_record.post_all_records_to.get_raw_value()
    p_pr_id = post_to_record.pr_id.get_raw_value()
    rec461 = ppms.search_record(461,[pr_id],[1001],True)
    
    if rec461:
        for record in obligo_records:
            single_post = record.get_dtp_record().post_all_records_to.get_value()
            sap_state = record.get_dtp_record().sap_state.get_value()
            if sap_state == 13 and single_post or sap_state == 13 and all_post:
                rec461 = ppms.search_record(461,[p_pr_id],[41540,41541,41542,41543,41544],True)
                
                old_miscel_pay_oblig = rec461.miscel_pay_oblig.get_value()
                old_investm_pay_oblig = rec461.investm_pay_oblig.get_value()
                old_person_ext_pay_obl = rec461.person_ext_pay_obl.get_value()
                old_mat_costs_pay_obl = rec461.mat_costs_pay_obl.get_value()
                old_person_int_pay_obl = rec461.person_int_pay_obl.get_value()

                sum_miscel_pay_oblig=record.miscel_pay_oblig.get_raw_value()
                sum_investm_pay_oblig=record.investm_pay_oblig.get_raw_value()
                sum_person_ext_pay_obl=record.person_ext_pay_obl.get_raw_value()
                sum_mat_costs_pay_obl=record.mat_costs_pay_obl.get_raw_value()
                sum_person_int_pay_obl=record.person_int_pay_obl.get_raw_value()
                
                rec461.miscel_pay_oblig.set_value(old_miscel_pay_oblig+sum_miscel_pay_oblig)
                rec461.investm_pay_oblig.set_value(old_investm_pay_oblig+sum_investm_pay_oblig)
                rec461.person_ext_pay_obl.set_value(old_person_ext_pay_obl+sum_person_ext_pay_obl)
                rec461.mat_costs_pay_obl.set_value(old_mat_costs_pay_obl+sum_mat_costs_pay_obl)
                rec461.person_int_pay_obl.set_value(old_person_int_pay_obl+sum_person_int_pay_obl)
                
                rec461.save()
                mod_obj.refresh_dts((461))
                record.get_dtp_record().sap_state.set_value(21)
        
def is_costs_import():
    cost_records = mod_obj.get_da('transfer_records').get_records()
    post_to_record = mod_obj.get_da('config_parameter').get_records()[0]

    release_by_pl = post_to_record.release_by_pl.get_raw_value()
    all_post =  post_to_record.post_all_records_to.get_raw_value()
    p_pr_id = post_to_record.pr_id.get_raw_value()
    p_task_id = post_to_record.task_id.get_raw_value()
    p_res_id = post_to_record.ressource_id.get_raw_value()
    p_ou_cost_center_id = post_to_record.ou_cost_center_id.get_raw_value()
    p_cost_type_id = post_to_record.cost_type_id.get_raw_value()
    p_storno_art = post_to_record.storno_art.get_raw_value()

    for record in cost_records:
        sap_state = record.get_dtp_record().sap_state.get_value()
        single_post = record.get_dtp_record().post_all_records_to.get_value()
        pr_id = record.rec_wbs_el.get_raw_value()
        task_id = record.task_id_dt472.get_raw_value()
        res_id = record.res_id_dt472.get_raw_value()
        ct_id = record.ct_id_dt472.get_raw_value()
        date = record.date_dt472.get_raw_value()
        load_act = record.load_act_transfer.get_raw_value()
        ou_cctr_of_res = record.ou_cctr_to_be_loaded_dt472.get_raw_value()

        if sap_state == 13  and single_post or sap_state == 13  and all_post:

            values = {
                    'pr_id':p_pr_id,
                    'task_id':p_task_id,
                    'res_id':p_res_id,
                    'ct_id':p_cost_type_id,
                    'date':record.date_dt472.get_raw_value(),
                    'load_act':record.load_act_transfer.get_raw_value(),
                    'ou_cctr_of_res':p_ou_cost_center_id
                    }

            with Locking(1):
                new_rec472 = ppms.create_record(472,values)
                if new_rec472:
                    new_rec472.save()
                    record.get_dtp_record().sap_state.set_value(21)
                    record.get_dtp_record().pos_dt472.set_value(new_rec472.item.get_value())
                    record.get_dtp_record().pr_id_dt472.set_value(new_rec472.pr_id.get_value())
                    new_rec472.sap_state.set_value(2)
                    new_rec472.save()


        elif sap_state == 20: pass
        elif sap_state == 21: pass
        elif sap_state == 99: pass

def set_configuration_output(mod_obj):
    finished_records = mod_obj.get_da('config_parameter').get_records()[0]
    finished_records_c = mod_obj.get_customizing().get_dac('config_parameter')

    field_to_output = ['740619','740617','740615',
                       '740613','740611','740607']

    for df_id in field_to_output:
        finished_records.get_df_by_id(df_id).make_output()

    finished_records_c.get_dfc_by_id(740624).show(9)

trans_records = mod_obj.get_da('transaction_header').get_records()

if trans_records:
    ppms.echo_off()
    l_103 = mod_obj.get_current_L_var()[103]
    header = mod_obj.get_da('transaction_header').get_records()[0].header.get_raw_value()
    rec593 = ppms.search_record(593,[int(l_103[0])],[61520],True)
    import_type = rec593.import_type.get_value()
    mod_obj.set_new_L_var(101,[header])

    if import_type == '350':
        obligo()
        mod_obj.menu(34)
        mod_obj.set_new_L_var(103,[int(l_103[0])])
        #mod_obj.open_module('009BTZ')
        ppms.echo_on()
        mod_obj.menu(19)
        mod_obj.set_current_L_var(103,[int(l_103[0])])
        mod_obj.menu(12)
        set_configuration_output(mod_obj)
        
    elif import_type == '351':
        is_costs_import()
        mod_obj.menu(34)
        mod_obj.set_new_L_var(103,[int(l_103[0])])
        mod_obj.open_module('009BTQ')
        mod_obj.open_module('009BTZ')
        ppms.echo_on()
        mod_obj.menu(19)
        mod_obj.set_current_L_var(103,[int(l_103[0])])
        mod_obj.menu(12)
        set_configuration_output(mod_obj)

else:
    ppms.ui_message_id('0049')''',

'''from ppms import ppms_cu

mod_obj = ppms.get_target_module()
active_mod = ppms.get_active_module()

ERRORS = { 1:ppms_cu.Access.get_text_constant(mod_obj,'001537'),#Projekt
           2:ppms_cu.Access.get_text_constant(mod_obj,'001538'),#Ressource
           3:ppms_cu.Access.get_text_constant(mod_obj,'001539'),#Kostenart
           4:ppms_cu.Access.get_text_constant(mod_obj,'001540'),#Kostenstelle
           5:ppms_cu.Access.get_text_constant(mod_obj,'001541') #Vorgang
          }

def set_comment(record,error):
    comment = record.sap_information.get_raw_value()
    status = record.sap_state.get_raw_value()
    if comment:
        if status == 10 or status == 13 or status == 11:
            record.get_dtp_record().sap_information.set_value(comment+","+''.join(ERRORS[error]))
    else: record.get_dtp_record().sap_information.set_value(ERRORS[error])
    
          
def get_project(record):    
    pr_id = record.rec_wbs_el.get_raw_value()
    rec461 = ppms.search_record(461,[pr_id],[1001],True)
    if rec461: return True
    else: 
        set_comment(record,1)
        return False

def get_task(record):
    pr_id = record.rec_wbs_el.get_raw_value()
    task_id = record.task_id_dt472.get_raw_value()
    rec463 = ppms.search_record(463,[pr_id,task_id],[1097,1098],True)
    if rec463:
        return True
    else:
        set_comment(record,5)
        return False
        
def get_ress(record):
    res_id = record.res_id_dt472.get_raw_value()
    rec467 = ppms.search_record(467,[res_id],[1218],True)
    rec511 = ppms.search_record(511, [res_id], [10635], True)
    
    if rec467:
        return True
    else:
        set_comment(record,2)
        return False
        
def get_ress_to_task(record,pr,task,ress):
    if False in (pr,task,ress): return False
    else:    
        pr_id = record.rec_wbs_el.get_raw_value()
        task_id = record.task_id_dt472.get_raw_value()
        res_id = record.res_id_dt472.get_raw_value()
        rec466 = ppms.search_record(466,[pr_id,task_id,res_id],[1390,1391,1392],True)
        
        if pr_id and task_id and res_id:
            if not rec466:
                values = {'pr_id':pr_id,
                          'task_id':task_id,
                          'res_id':res_id
                         }
                new_rec466 = ppms.create_record(466,values)
                if new_rec466:
                    new_rec466.save()
                else: return False
            else: return False
        else: return False
    
def get_cost(record):
    ct_id = record.ct_id_dt472.get_raw_value()
    rec470 = ppms.search_record(470,[ct_id],[1366],True)
    if rec470:
        return True
    else: 
        set_comment(record,3)
        return False
        
def get_ou_cctr_to_be_loaded(record):
    ou_cctr_to_be_loaded_dt472 = record.ou_cctr_to_be_loaded_dt472.get_raw_value()
    rec808 = ppms.search_record(808,[ou_cctr_to_be_loaded_dt472],[7025],True)
    if rec808:
        return True
    else: 
        set_comment(record,4)
        return False

def recheck_records(record,import_type):
    comment = record.get_dtp_record().sap_information.set_value('')
    load_act_transfer = record.load_act_transfer.get_raw_value()
    release_by_pl= mod_obj.get_da('config_parameter').get_records()[0].release_by_pl.get_raw_value()
    if import_type:
        pr = get_project(record)
        if not pr:
            record.get_dtp_record().sap_state.set_value(13)
        else:
            record.get_dtp_record().sap_state.set_value(20)
    else:
        pr = get_project(record)
        task = get_task(record)
        cost = get_cost(record)
        ress = get_ress(record)
        ress_to_task = get_ress_to_task(record,pr,task,ress)
        cctr = get_ou_cctr_to_be_loaded(record)
        if False in (pr,task,ress,cost):
            record.get_dtp_record().sap_state.set_value(13)
        else:
            if load_act_transfer < release_by_pl:
                record.get_dtp_record().sap_state.set_value(20)
            elif load_act_transfer >= release_by_pl:
                record.get_dtp_record().sap_state.set_value(12)
#Anwenderforum2013
def set_configuration_output(mod_obj):
    finished_records = mod_obj.get_da('config_parameter').get_records()[0]
    finished_records_c = mod_obj.get_customizing().get_dac('config_parameter')
    
    field_to_output = ['740619','740617','740615',
                       '740613','740611','740607']
                       
    for df_id in field_to_output:
        finished_records.get_df_by_id(df_id).make_output()
    
    finished_records_c.get_dfc_by_id(740624).show(9)                
#fetch records
ppms.echo_off()
trans_records = mod_obj.get_da('transaction_header').get_records()
if not trans_records: pass
else:
    header = mod_obj.get_da('transaction_header').get_records()[0].header.get_raw_value()
    l_103 = mod_obj.get_current_L_var()[103][0]
    mod_obj.set_new_L_var(103,l_103)
    import_type = mod_obj.get_da('config_parameter').get_records()[0].import_type.get_raw_value()
    release_by_pl= mod_obj.get_da('config_parameter').get_records()[0].release_by_pl.get_raw_value()
    records591 = mod_obj.get_da('transfer_records').get_records()
    
    for record in records591:
        obligo = record.get_dtp_record().obligo_record.get_value()
        sap_state = record.sap_state.get_raw_value()
        load_act_transfer = record.load_act_transfer.get_raw_value()
        load_act_dt472 = record.load_act_dt472.get_raw_value()
        if obligo:
            if sap_state == 13:
                recheck_records(record,obligo)
            elif sap_state == 99: pass
            else:    
                pr = get_project(record)
                if not pr: record.get_dtp_record().sap_state.set_value(13)
                else: record.get_dtp_record().sap_state.set_value(20)
        else:
            if sap_state == 13:
                recheck_records(record,obligo)
            elif sap_state == 21 or sap_state == 99: pass
            else:    
                pr = get_project(record)
                task = get_task(record)
                cost = get_cost(record)
                ress = get_ress(record)
                ress_to_task = get_ress_to_task(record,pr,task,ress)
                cctr = get_ou_cctr_to_be_loaded(record)
                comment = record.sap_information.get_raw_value()
                if comment: record.get_dtp_record().sap_state.set_value(13)
                else:
                    if load_act_dt472 < release_by_pl:
                        record.get_dtp_record().sap_state.set_value(20)
                    elif load_act_dt472 >= release_by_pl:
                        record.get_dtp_record().sap_state.set_value(12)
    mod_obj.menu(34)
    ppms.echo_on()
    mod_obj.menu(19)
    mod_obj.menu(22)
    #Anwenderforum2013
    set_configuration_output(mod_obj)''',

'''mod_obj = ppms.get_target_module()
inv_df=ppms.get_context_df()
inv_rec = mod_obj.get_invoker_rec()

import_id_record = mod_obj.get_da('import_id').get_records()[0]
import_id = import_id_record.import_id.get_raw_value()

get_childs = import_id_record.count_children()
if not get_childs and import_id:
    target_record = import_id_record.insert_child("config_parameter")
    mod_customizing = mod_obj.get_customizing().get_dac('config_parameter')

    mod_customizing.set_to_input()
    mod_customizing.get_dfc_by_id(740624).show(1)

    if import_id_record:
        if import_id:
            rec593 = ppms.search_record(593,[import_id],[],True)
            if rec593:
                for entry in [('imp_path', rec593.imp_path.get_value()),
                              ('pr_id' , rec593.pr_id.get_value()),
                              ('imp_filename' , rec593.imp_filename.get_value()),
                              ('storno' , rec593.storno.get_value()),
                              ('import_type' , rec593.import_type.get_value()),
                              ('storno_art' , rec593.storno_art.get_value()),
                              ('auto_release' , rec593.auto_release.get_value()),
                              ('post_all_records_to' , rec593.post_all_records_to.get_value()),
                              ('release_by_pl' , rec593.release_by_pl.get_value()),
                              ('cost_type_id' , rec593.cost_type_id.get_value()),
                              ('ou_cost_center_id' , rec593.ou_cost_center_id.get_value()),
                              ('ressource_id' , rec593.ressource_id.get_value()),
                              ('task_id', rec593.task_id.get_value()),
                              ('config_id' , rec593.import_id.get_value()),
                              ('file_header',rec593.file_header.get_value())]:
                    name, value = entry
                    target_record.get_df(name).set_raw_value(value)''']
    
class UpdatefixesInSAPInterfaceMacroModulesVoE(MigratePythonPacket):
    '''Change the CU after fixing the SAP interface for VoE'''
    version = 1
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 11286
    
    
    def fix(self, runner):
        errors = 0
        
        for number in range(0,len(MODULES)):
            fixfunc = lambda _: FIX_FUNC[number]
    
            if ppms.db_get_dbms_name() != DBMS_ORACLE:
                if not self.migrate_python(BEFORE_HASH[number][1], AFTER_HASH[number],self.CU_TYPE_MODULE, MODULES[number],fixfunc):
                    errors += 1
            else:
                if not self.migrate_python(BEFORE_HASH[number][0], AFTER_HASH[number],self.CU_TYPE_MODULE, MODULES[number],fixfunc):
                    errors += 1
        if not errors:
            return self.success()
            
        return self.fail('Could not make changes')
        
class UpdateLVarsOfSAPInterfaceVoE(ChangeDTPPacket):
    '''Update LVars to fix of the SAP interface on VoE'''
    version = 1
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 11286

    def fix(self, runner):
        VAL_DICT = {'@L1000':'@L101',
                    '@L1001':'@L102',
                    '@L1002':'@L103'}
        
        da_df = [('052790',740123),
                 ('052793',740105),
                 ('051980',735421),
                 ('052796',740630),
                 ('052796',740653),
                 ('052816',740192),
                 ('052817',740222),
                 ('052819',740418),
                 ('052820',740117),
                 ('052822',740303),
                 ('052824',740369),
                 ('052842',740539),
                 ('052847',735247),
                 ('052847',735248),
                 ('052850',740640),
                 ('053020',741729)]
        
        errors = 0
        
        for da, df in da_df:
            record = self.get_record(411, [da,df], [1714])
            if record:
                if not self.change_value(record, 'filter_from', '@L1000', VAL_DICT['@L1000']):
                    if not self.change_value(record, 'filter_from', '@L1001', VAL_DICT['@L1001']):
                        if not self.change_value(record, 'filter_from', '@L1002', VAL_DICT['@L1002']):
                            errors += 1

        if errors:
            return self.fail('Could not make changes')

        return self.success()
        
# -*- coding: utf-8 -*-
import os
from ppms.migration.packet import *

class PortSQLStatementsSAPInterface(SQLPacket):
    '''Port the necessary sql statements for SAP Interface VoE'''
    version = 1
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 11286

    fname = 'wi11286_sap_interface_voe.sql'

    def fix(self, runner):
        sqlpath = self.get_sql_file_path(self.sql_planta_de_dbms, self.fname)
        queries = self.get_queries_from_file(sqlpath)

        for query in queries:
            self.modify_and_log(query)

        return self.success()
        
# -*- coding: utf-8 -*-
from ppms.migration.packet import *

class ChangeListVariablesDt452(ChangeDTPPacket):
    '''Change L-Vars to new < 1000 for VoE'''
    version = 1
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 11286

    def fix(self, runner):
        VAL_DICT = {346:(101,1000),
                    347:(102,1001),
                    454:(103,1002)}
        errors = 0
        
        for ident, (new,old) in VAL_DICT.items():
            record = self.get_record(452, [ident], [9453])
            if not self.change_value(record, '_l', old, new):
                errors += 1
                continue
        
        if errors:
            return self.fail('Could not make changes')

        return self.success()

class ChangeNameToPLANTALink(ChangeDTPPacket):
    '''Update the name of the erp interface'''
    version = 1
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 11286

    def fix(self, runner):
        idents = (751856,751857)
        LANGUAGE = 'DE'
        OLD_VALUE = 'ERP-Schnittstelle'
        NEW_VALUE = 'PLANTA-Link'
        
        errors = 0
        
        for ident in idents:
            record = self.get_record(435, [ident, LANGUAGE], [1538,1550,1549])
            if not self.change_value(record, 'i_text', OLD_VALUE, NEW_VALUE):
                errors += 1
                continue
                
        if errors:
            return self.fail('Could not make changes')

        return self.success()

class ChangeButtonNameOfImportModule(ChangeDTPPacket):
    '''Rename the button Re-check '''
    version = 1
    done_after_success = True
    run_on_startup = False
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 11286

    def fix(self, runner):
        IDENT = 755128
        LANGUAGE = 'DE'
        OLD_VALUE = 'Re-check'
        NEW_VALUE = 'Daten überprüfen'
        
        record = self.get_record(435, [IDENT, LANGUAGE], [1538,1550,1549])
        if not self.change_value(record, 'i_text', OLD_VALUE, NEW_VALUE):
            return self.fail('Could not make changes')
        
        return self.success()