def __init__(self, QMainWindow, app_model):

        self._parent = QMainWindow
        self._app_model = app_model
        self._pt_model = Pricing_Template_Model(self._parent)
        self._com_model = Common_Model()

        self._ut_dup_bool = False
        self._selected = None
        self._continue_flag = True
        self._dia_pt_response = False

        self._selected_op = {'isPricingTemp': False, 'isPricingVal': False}

        self._progress_op = {
            True: self._progress_on,
            False: self._progress_off
        }

        # set connects for pricing template

        self._setupConnections()

        # Toggle Progress display

        self._progress_toggle()
示例#2
0
    def __init__(self, QMainWindow, app_model):

        self._parent = QMainWindow
        self._app_model = app_model
        self._ct_model = Contract_Template_Model(self._parent)
        self._com_model = Common_Model()

        self._dia_ct_response = False

        self._template_op = {
            'isContractTypeTemp': False,
            'isDebitCredit': False,
            'isContractStep1': False,
            'isContractStep3': False
        }

        self._progress_op = {
            True: self._progress_on,
            False: self._progress_off
        }

        # Toggle Progress display

        self._progress_toggle()

        self._setupConnections()
	def __init__(self, QMainWindow):

		self.ParentWindow = QMainWindow
		self._templates = OrderedDict()
		self._open_doc = defaultdict(lambda: 'open ')
		self._open_doc['Windows'] = 'start'

		self._model_ui = main_app_Model()
		self._common_mod = Common_Model()

		# Initialize Dialogs

		self.Dialog = QDialog(self.ParentWindow)
		self.dialog_ui = Pricing_Template_Dialog()
		self.dialog_ui.setupUi(self.Dialog)

		self.Dialog_warn = QDialog(self.ParentWindow)
		self.dialog_warn_ui = Template_Warning_Dialog()
		self.dialog_warn_ui.setupUi(self.Dialog_warn)

		self.Dialog_finish = QDialog(self.ParentWindow)
		self.Dialog_fin_ui = PricingTemplate_finish()
		self.Dialog_fin_ui.setupUi(self.Dialog_finish)

		self.Dialog_report = QDialog(self.ParentWindow)
		self.Dialog_report_ui = Pricing_Template_Report()
		self.Dialog_report_ui.setupUi(self.Dialog_report)

		self.Dialog_select = QDialog(self.ParentWindow)
		self.Dialog_select_ui = Pricing_Template_Select()
		self.Dialog_select_ui.setupUi(self.Dialog_select)

		self._config = self._model_ui._conf_data['PricingTempConfig']

		self.replyBtn = None
示例#4
0
    def __init__(self, src_folder, tgt_folder, keyword, templates, pt_model):
        super(Pricing_Validation_Main, self).__init__()

        self._src_folder = src_folder
        self._tgt_folder = tgt_folder
        self._keyword = keyword
        self._l_templates = templates
        self._pt_model = pt_model
        self._common_mod = Common_Model()
        self._pv_model = Pricing_Validation_Model(self._common_mod,
                                                  self._pt_model)

        self.timer = QTime()
        self.elapsed_time = None

        self.is_running = True
        self._progress_count = 0
        self._abort_flg = False
        self._cancel_flg = False
        self._main_dir = os.getcwd()

        self.preval_price_df = None
    def __init__(self, QMainWindow):

        self.ParentWindow = QMainWindow

        self._model_ui = main_app_Model()
        self._common_mod = Common_Model()

        # Initialize Dialogs

        self.Dialog = QDialog(self.ParentWindow)
        self.dialog_ui = Contract_Template_Dialog()
        self.dialog_ui.setupUi(self.Dialog)

        self._ct_config = self._model_ui._conf_data['ContractTempConfig']
        self._dc_config = self._model_ui._conf_data['DebitCreditConfig']
        self._cv1_config = self._model_ui._conf_data[
            'ContractPreValStep1Config']
        self._cv3_config = self._model_ui._conf_data[
            'ContractPreValStep3Config']

        self.replyBtn = None
示例#6
0
class Pricing_Validation_Main(QThread):
    """
	Runs in thread.
	"""

    txtProgress = pyqtSignal(str)
    countProgress = pyqtSignal(int)
    currStatus = pyqtSignal(list)

    def __init__(self, src_folder, tgt_folder, keyword, templates, pt_model):
        super(Pricing_Validation_Main, self).__init__()

        self._src_folder = src_folder
        self._tgt_folder = tgt_folder
        self._keyword = keyword
        self._l_templates = templates
        self._pt_model = pt_model
        self._common_mod = Common_Model()
        self._pv_model = Pricing_Validation_Model(self._common_mod,
                                                  self._pt_model)

        self.timer = QTime()
        self.elapsed_time = None

        self.is_running = True
        self._progress_count = 0
        self._abort_flg = False
        self._cancel_flg = False
        self._main_dir = os.getcwd()

        self.preval_price_df = None

    def run(self):
        ''' 
		Read source file to DataFrame and Excel file (for validation)
		Filter dataframe per Usage Type
		Perform Mappings
		Populate the validated dataframe to template
		'''

        # Start timer

        self.timer.start()

        self.txtProgress.emit('Loading source file to dataframes.')

        success = False
        while not success:
            try:

                df_price_all = self._pv_model.read_source_to_DF(
                    self._keyword, self._src_folder, 'Pricing')
                df_scales_all = self._pv_model.read_source_to_DF(
                    self._keyword, self._src_folder, 'Scales')
                df_minf_all = self._pv_model.read_source_to_DF(
                    self._keyword, self._src_folder, 'MINF')

                success = True
            except Exception as e:

                self.currStatus.emit([self._keyword, 'Load Source', str(e)])

                response = None
                while response is None:
                    response = self._pt_model.replyBtn
                    time.sleep(1)

                if response == QMessageBox.Close:
                    self._abort_flg = True
                    self._pt_model.replyBtn = None
                    success = True

        if not self._abort_flg:

            #Loop on the templates found

            for i in self._l_templates:

                usage_type = i[0]

                if self._cancel_flg: break

                status = self._pt_model.get_template_status(usage_type)

                if status == '':

                    wb_name = 'OTC_{}_Pricing_Pre_Validation_Report_{}.xlsx'.format(
                        usage_type, self._keyword.upper())
                    output_filenm = self._tgt_folder + "\\" + wb_name

                    # Create a Pandas Excel writer using XlsxWriter as the engine.
                    writer = pd.ExcelWriter(
                        output_filenm,
                        engine='xlsxwriter',
                        options={'strings_to_numbers': False})

                    # Get the xlsxwriter workbook and worksheet objects.
                    workbook = writer.book

                    #Set workbook formats

                    self._common_mod.set_workbook_formats(workbook)

                    l_price_tabs = self._pv_model._config['PricingTabs']

                    success = False
                    while not success:
                        try:

                            for d_tab in l_price_tabs:

                                for k, v in d_tab.items():

                                    tab = k
                                    template_sheet_name = v[
                                        'Template_Sheet_Name']
                                    template_mapping_idx = v[
                                        'Template_Mapping_Index']
                                    template_column_idx = v[
                                        'Template_Column_Index']
                                    chart_sheet_name = v['Chart_Sheeet_Name']
                                    details_sheet_name = v[
                                        'Details_Sheet_Name']

                                    self.txtProgress.emit(
                                        'Started: Processing {} - Initializing {} DataFrame.'
                                        .format(usage_type, tab))

                                    #Filter dataframe

                                    if tab == 'Price':
                                        preval_df = df_price_all[
                                            df_price_all['USAGE_TYPE_CD'] ==
                                            usage_type]
                                    elif tab == 'Scale':
                                        preval_df = df_scales_all[
                                            df_scales_all['USAGE_TYPE_CD'] ==
                                            usage_type]
                                    else:
                                        preval_df = df_minf_all[
                                            df_minf_all['USAGE_TYPE_CD'] ==
                                            usage_type]

                                    #Initialize Pricing dataframe

                                    preval_df = self._pv_model.initialize_preval_df(
                                        preval_df, tab)

                                    self.txtProgress.emit(
                                        'Finished: Processing {} - Initializing {} DataFrame.'
                                        .format(usage_type, tab))
                                    time.sleep(3)

                                    #Read Template columns for mapping

                                    self.txtProgress.emit(
                                        'Started: Processing {} - Get {} Template Column Mappings.'
                                        .format(usage_type, tab))

                                    template_columns = self._pv_model.get_template_mappings(
                                        usage_type, template_sheet_name,
                                        template_mapping_idx)

                                    self.txtProgress.emit(
                                        'Started: Processing {} - Get {} Template Column Mappings.'
                                        .format(usage_type, tab))
                                    time.sleep(3)

                                    #Generate Price template DF

                                    self.txtProgress.emit(
                                        'Started: Processing {} - Generating {} Template DataFrame.'
                                        .format(usage_type, tab))

                                    if tab == 'Price':
                                        self.preval_price_df = preval_df.copy()
                                        template_df = self._pv_model.generate_template_df(
                                            usage_type, preval_df,
                                            template_sheet_name,
                                            template_columns,
                                            template_column_idx, tab)
                                    elif tab == 'Scale':

                                        merge_scale_price_df = self._pv_model.merge_scale_price_df(
                                            preval_df, self.preval_price_df)
                                        template_df = self._pv_model.generate_template_df(
                                            usage_type, merge_scale_price_df,
                                            template_sheet_name,
                                            template_columns,
                                            template_column_idx, tab,
                                            self.preval_price_df)

                                    else:
                                        merge_minf_price_df = self._pv_model.merge_minf_price_df(
                                            preval_df, self.preval_price_df)
                                        template_df = self._pv_model.generate_template_df(
                                            usage_type, merge_minf_price_df,
                                            template_sheet_name,
                                            template_columns,
                                            template_column_idx, tab,
                                            self.preval_price_df)

                                    self.txtProgress.emit(
                                        'Finished: Processing {} - Generating {} Template DataFrame.'
                                        .format(usage_type, tab))
                                    time.sleep(3)

                                    #Populate Summary Chart

                                    self.txtProgress.emit(
                                        'Started: Processing {} - Populating {} Summary Chart.'
                                        .format(usage_type, tab))

                                    print(template_df.columns.to_list())
                                    self._pv_model.populate_summary_chart(
                                        usage_type, workbook, template_df,
                                        chart_sheet_name, template_column_idx)

                                    self.txtProgress.emit(
                                        'Finished: Processing {} - Populating {} Summary Chart.'
                                        .format(usage_type, tab))
                                    time.sleep(3)

                                    #Populate Details sheet

                                    self.txtProgress.emit(
                                        'Started: Processing {} - Populating {} Details Sheet.'
                                        .format(usage_type, tab))

                                    self._pv_model.populate_details_worksheet(
                                        writer, template_df,
                                        details_sheet_name,
                                        template_column_idx)

                                    self.txtProgress.emit(
                                        'Finished: Processing {} - Populating {} Details Sheet.'
                                        .format(usage_type, tab))
                                    time.sleep(3)

                                    #Generating Template Counts

                                    if not self._abort_flg:

                                        self.txtProgress.emit(
                                            'Started: Processing {} - Generating Data Counts.'
                                            .format(usage_type))

                                        data = {
                                            'Source': 0,
                                            'Template': preval_df.shape[0]
                                        }
                                        self._pt_model.append_template_logs(
                                            usage_type, 3, tab, data)

                                        self.txtProgress.emit(
                                            'Finished: Processing {} - Generating Data Counts.'
                                            .format(usage_type))

                            success = True

                        except Exception as e:

                            self.currStatus.emit([
                                usage_type, 'Populate Worksheet', tab,
                                str(e)
                            ])

                            response = None
                            while response is None:
                                response = self._pt_model.replyBtn
                                time.sleep(1)

                                if response == QMessageBox.Abort:
                                    self._abort_flg = True
                                    self._pt_model.replyBtn = None
                                    success = True
                                elif response == QMessageBox.Retry:
                                    self._pt_model.replyBtn = None
                                    workbook.close()
                                elif response == QMessageBox.Ignore:
                                    self._pt_model.update_template_status(
                                        usage_type, 'i')
                                    self._pt_model.replyBtn = None
                                    success = True
                                elif response == QMessageBox.Close:
                                    self._abort_flg = True
                                    self._pt_model.replyBtn = None
                                    success = True

                    if self._cancel_flg: break

                    #Save to workbook in output folder

                    status = self._pt_model.get_template_status(usage_type)

                    if status == '' and not self._abort_flg:

                        success = False
                        while not success:
                            try:
                                self.txtProgress.emit(
                                    'Started: Processing {} - Saving Workbook to Output Folder.'
                                    .format(usage_type))

                                writer.save()

                                self.txtProgress.emit(
                                    'Finished: Processing {} - Saving Workbook to Output Folder.'
                                    .format(usage_type))
                                time.sleep(3)

                                #Update Status
                                self._pt_model.update_template_status(
                                    usage_type, 'c')

                                success = True
                            except Exception as e:

                                self.currStatus.emit([
                                    usage_type, 'Save Template', wb_name,
                                    str(e)
                                ])

                                response = None
                                while response is None:
                                    response = self._pt_model.replyBtn
                                    time.sleep(1)

                                    if response == QMessageBox.Abort:
                                        self._abort_flg = True
                                        self._pt_model.replyBtn = None
                                        success = True
                                    elif response == QMessageBox.Retry:
                                        self._pt_model.replyBtn = None
                                    elif response == QMessageBox.Ignore:
                                        self._pt_model.update_template_status(
                                            usage_type, 'i')
                                        self._pt_model.replyBtn = None
                                        success = True
                                    elif response == QMessageBox.Close:
                                        self._abort_flg = True
                                        self._pt_model.replyBtn = None
                                        success = True
                    else:

                        workbook.close()

                self._progress_count += 1
                self.countProgress.emit(self._progress_count)

        ### Display Elapsed Time ###

        self.update_elapsed_time()

        self.txtProgress.emit('Finished')

    def update_elapsed_time(self):

        secs = self.timer.elapsed() / 1000
        mins = (secs / 60) % 60
        hours = (secs / 3600)
        seconds = secs % 60

        self.elapsed_time = str(hours).split('.')[0] + ' Hours ' + str(
            mins).split('.')[0] + ' Minutes ' + str(seconds).split(
                '.')[0] + ' Seconds'
class Pricing_Validation_Main(QThread):
    """
	Runs in thread.
	"""

    txtProgress = pyqtSignal(str)
    countProgress = pyqtSignal(int)
    currStatus = pyqtSignal(list)

    def __init__(self, src_folder, tgt_folder, keyword, templates, pt_model):
        super(Pricing_Validation_Main, self).__init__()

        self._src_folder = src_folder
        self._tgt_folder = tgt_folder
        self._keyword = keyword
        self._l_templates = templates
        self._pt_model = pt_model
        self._common_mod = Common_Model()
        self._pv_model = Pricing_Validation_Model(self._common_mod,
                                                  self._pt_model)

        self.timer = QTime()
        self.elapsed_time = None

        self.is_running = True
        self._progress_count = 0
        self._abort_flg = False
        self._cancel_flg = False
        self._main_dir = os.getcwd()

        self.preval_price_df = None

    def run(self):
        ''' 
		Read source file to DataFrame and Excel file (for validation)
		Filter dataframe per Usage Type
		Perform Mappings
		Populate the validated dataframe to template
		'''

        # Start timer

        self.timer.start()

        self.txtProgress.emit('Loading source file to dataframes.')

        success = False
        while not success:
            try:

                df_price_all = self._pv_model.read_source_to_DF(
                    self._keyword, self._src_folder, 'Pricing')
                df_scales_all = self._pv_model.read_source_to_DF(
                    self._keyword, self._src_folder, 'Scales')
                df_minf_all = self._pv_model.read_source_to_DF(
                    self._keyword, self._src_folder, 'MINF')

                success = True
            except Exception as e:

                self.currStatus.emit([self._keyword, 'Load Source', str(e)])

                response = None
                while response is None:
                    response = self._pt_model.replyBtn
                    time.sleep(1)

                if response == QMessageBox.Close:
                    self._abort_flg = True
                    self._pt_model.replyBtn = None
                    success = True

        if not self._abort_flg:

            #Loop on the templates found

            for i in self._l_templates:

                usage_type = i[0]

                wb_name = 'OTC_{}_Pricing_Pre_Validation_Report_{}.xlsx'.format(
                    usage_type, self._keyword.upper())
                output_filenm = self._tgt_folder + "\\" + wb_name

                # Create a Pandas Excel writer using XlsxWriter as the engine.
                writer = pd.ExcelWriter(output_filenm,
                                        engine='xlsxwriter',
                                        options={'strings_to_numbers': False})

                # Get the xlsxwriter workbook and worksheet objects.
                workbook = writer.book

                #Set workbook formats

                self._common_mod.set_workbook_formats(workbook)

                l_price_tabs = [{
                    'Price': {
                        'Template_Sheet_Name': 'Customer prices',
                        'Template_Mapping_Index': 4,
                        'Template_Column_Index': 9,
                        'Chart_Sheeet_Name': 'Pricing_Summary',
                        'Details_Sheet_Name': 'Price_PreValidation_Details'
                    }
                }, {
                    'Scale': {
                        'Template_Sheet_Name': 'Customer scale price',
                        'Template_Mapping_Index': 4,
                        'Template_Column_Index': 8,
                        'Chart_Sheeet_Name': 'Scales_Summary',
                        'Details_Sheet_Name': 'Scales_PreValidation_Details'
                    }
                }, {
                    'MINF': {
                        'Template_Sheet_Name': 'MINF Details MTable',
                        'Template_Mapping_Index': 1,
                        'Template_Column_Index': 6,
                        'Chart_Sheeet_Name': 'MINF_Summary',
                        'Details_Sheet_Name': 'MINF_PreValidation_Details'
                    }
                }]

                for d_tab in l_price_tabs:

                    for k, v in d_tab.items():

                        tab = k
                        template_sheet_name = v['Template_Sheet_Name']
                        template_mapping_idx = v['Template_Mapping_Index']
                        template_column_idx = v['Template_Column_Index']
                        chart_sheet_name = v['Chart_Sheeet_Name']
                        details_sheet_name = v['Details_Sheet_Name']

                        self.txtProgress.emit(
                            'Started: Processing {} - Initializing {} DataFrame.'
                            .format(usage_type, tab))

                        #Filter dataframe

                        if tab == 'Price':
                            preval_df = df_price_all[
                                df_price_all['USAGE_TYPE_CD'] == usage_type]
                        elif tab == 'Scale':
                            preval_df = df_scales_all[
                                df_scales_all['USAGE_TYPE_CD'] == usage_type]
                        else:
                            preval_df = df_minf_all[
                                df_minf_all['USAGE_TYPE_CD'] == usage_type]

                        #Initialize Pricing dataframe

                        preval_df = self._pv_model.initialize_preval_df(
                            preval_df, tab)

                        self.txtProgress.emit(
                            'Finished: Processing {} - Initializing {} DataFrame.'
                            .format(usage_type, tab))
                        time.sleep(3)

                        #Read Template columns for mapping

                        self.txtProgress.emit(
                            'Started: Processing {} - Get {} Template Column Mappings.'
                            .format(usage_type, tab))

                        template_columns = self._pv_model.get_template_mappings(
                            usage_type, template_sheet_name,
                            template_mapping_idx)

                        self.txtProgress.emit(
                            'Started: Processing {} - Get {} Template Column Mappings.'
                            .format(usage_type, tab))
                        time.sleep(3)

                        #Generate Price template DF

                        self.txtProgress.emit(
                            'Started: Processing {} - Generating {} Template DataFrame.'
                            .format(usage_type, tab))

                        if tab == 'Price':
                            self.preval_price_df = preval_df.copy()
                            template_df = self._pv_model.generate_template_df(
                                usage_type, preval_df, template_columns,
                                template_column_idx, tab)
                        else:
                            template_df = self._pv_model.generate_template_df(
                                usage_type, preval_df, template_columns,
                                template_column_idx, tab, self.preval_price_df)
                        self.txtProgress.emit(
                            'Finished: Processing {} - Generating {} Template DataFrame.'
                            .format(usage_type, tab))
                        time.sleep(3)

                        #Populate Summary Chart

                        self.txtProgress.emit(
                            'Started: Processing {} - Populating {} Summary Chart.'
                            .format(usage_type, tab))

                        self._pv_model.populate_summary_chart(
                            usage_type, workbook, template_df,
                            chart_sheet_name, template_column_idx)

                        self.txtProgress.emit(
                            'Finished: Processing {} - Populating {} Summary Chart.'
                            .format(usage_type, tab))
                        time.sleep(3)

                        #Populate Details sheet

                        self.txtProgress.emit(
                            'Started: Processing {} - Populating {} Details Sheet.'
                            .format(usage_type, tab))

                        self._pv_model.populate_details_worksheet(
                            writer, template_df, details_sheet_name,
                            template_column_idx)

                        self.txtProgress.emit(
                            'Finished: Processing {} - Populating {} Details Sheet.'
                            .format(usage_type, tab))
                        time.sleep(3)

                # ###################### PRICE TAB ########################

                # self.txtProgress.emit('Started: Processing {} - Initializing Pricing DataFrame.'.format(usage_type))

                # #Filter dataframe

                # preval_price_df = df_price_all[df_price_all['USAGE_TYPE_CD'] == usage_type]

                # #Initialize Pricing dataframe

                # preval_price_df = self._pv_model.initialize_preval_df(preval_price_df, 'Price')

                # self.txtProgress.emit('Finished: Processing {} - Initializing Pricing DataFrame.'.format(usage_type))
                # time.sleep(3)

                # #Read Template columns for mapping

                # self.txtProgress.emit('Started: Processing {} - Get Pricing Template Column Mappings.'.format(usage_type))

                # template_columns = self._pv_model.get_template_mappings(usage_type, 'Customer prices', 4)

                # self.txtProgress.emit('Started: Processing {} - Get Pricing Template Column Mappings.'.format(usage_type))
                # time.sleep(3)

                # #Generate Price template DF

                # self.txtProgress.emit('Started: Processing {} - Generating Pricing Template DataFrame.'.format(usage_type))

                # price_df = self._pv_model.generate_template_df(usage_type, preval_price_df, template_columns, 9, 'Price')

                # self.txtProgress.emit('Finished: Processing {} - Generating Pricing Template DataFrame.'.format(usage_type))
                # time.sleep(3)

                # wb_name = 'OTC_{}_Pricing_Pre_Validation_Report_{}.xlsx'.format(usage_type, self._keyword.upper())
                # output_filenm = self._tgt_folder + "\\" + wb_name

                # # Create a Pandas Excel writer using XlsxWriter as the engine.
                # writer = pd.ExcelWriter(output_filenm, engine='xlsxwriter', options={'strings_to_numbers': False})

                # # Get the xlsxwriter workbook and worksheet objects.
                # workbook  = writer.book

                # #Set workbook formats

                # self._common_mod.set_workbook_formats(workbook)

                # #Populate Summary Chart

                # self.txtProgress.emit('Started: Processing {} - Populating Pricing Summary Chart.'.format(usage_type))

                # self._pv_model.populate_summary_chart(usage_type, workbook, price_df, 'Pricing_Summary', 9)

                # self.txtProgress.emit('Finished: Processing {} - Populating Pricing Summary Chart.'.format(usage_type))
                # time.sleep(3)

                # #Populate Details sheet

                # self.txtProgress.emit('Started: Processing {} - Populating Pricing Details Sheet.'.format(usage_type))

                # sheet_name = 'Pricing_PreValidation_Details'
                # self._pv_model.populate_details_worksheet(writer, price_df, sheet_name, 9)

                # self.txtProgress.emit('Finished: Processing {} - Populating Pricing Details Sheet.'.format(usage_type))
                # time.sleep(3)

                # ###################### SCALES TAB ########################

                # self.txtProgress.emit('Started: Processing {} - Initializing Scales DataFrame.'.format(usage_type))

                # #Filter dataframe

                # preval_scales_df = df_scales_all[df_scales_all['USAGE_TYPE_CD'] == usage_type]

                # #Initialize Pricing dataframe

                # preval_scales_df = self._pv_model.initialize_preval_df(preval_scales_df, 'Scales')

                # self.txtProgress.emit('Finished: Processing {} - Initializing Scales DataFrame.'.format(usage_type))
                # time.sleep(3)

                # #Read Template columns for mapping

                # self.txtProgress.emit('Started: Processing {} - Get Scales Template Column Mappings.'.format(usage_type))

                # template_columns = self._pv_model.get_template_mappings(usage_type, 'Customer scale price', 4)

                # self.txtProgress.emit('Started: Processing {} - Get Scales Template Column Mappings.'.format(usage_type))
                # time.sleep(3)

                # #Generate Scales template DF

                # self.txtProgress.emit('Started: Processing {} - Generating Scales Template DataFrame.'.format(usage_type))

                # scales_df = self._pv_model.generate_template_df(usage_type, preval_scales_df, template_columns, 8, 'Scales', preval_price_df)

                # self.txtProgress.emit('Finished: Processing {} - Generating Scales Template DataFrame.'.format(usage_type))
                # time.sleep(3)

                # #Populate Summary Chart

                # self.txtProgress.emit('Started: Processing {} - Populating Scales Summary Chart.'.format(usage_type))

                # self._pv_model.populate_summary_chart(usage_type, workbook, scales_df, 'Scales_Summary', 8)

                # self.txtProgress.emit('Finished: Processing {} - Populating Scales Summary Chart.'.format(usage_type))
                # time.sleep(3)

                # #Populate Details sheet

                # self.txtProgress.emit('Started: Processing {} - Populating Scales Details Sheet.'.format(usage_type))

                # sheet_name = 'Scales_PreValidation_Details'
                # self._pv_model.populate_details_worksheet(writer, scales_df, sheet_name, 8)

                # self.txtProgress.emit('Finished: Processing {} - Populating Scales Details Sheet.'.format(usage_type))
                # time.sleep(3)

                # print(self._pt_model._templates)

                # ###################### MINF TAB ########################

                # self.txtProgress.emit('Started: Processing {} - Initializing MINF DataFrame.'.format(usage_type))

                # #Filter dataframe

                # preval_minf_df = df_minf_all[df_minf_all['USAGE_TYPE_CD'] == usage_type]

                # #Initialize Pricing dataframe

                # preval_minf_df = self._pv_model.initialize_preval_df(preval_minf_df, 'MINF')

                # self.txtProgress.emit('Finished: Processing {} - Initializing MINF DataFrame.'.format(usage_type))
                # time.sleep(3)

                # #Read Template columns for mapping

                # self.txtProgress.emit('Started: Processing {} - Get MINF Template Column Mappings.'.format(usage_type))

                # template_columns = self._pv_model.get_template_mappings(usage_type, 'MINF Details MTable', 1)

                # self.txtProgress.emit('Started: Processing {} - Get MINF Template Column Mappings.'.format(usage_type))
                # time.sleep(3)

                # #Generate MINF template DF

                # self.txtProgress.emit('Started: Processing {} - Generating MINF Template DataFrame.'.format(usage_type))

                # minf_df = self._pv_model.generate_template_df(usage_type, preval_minf_df, template_columns, 6, 'MINF', preval_price_df)

                # self.txtProgress.emit('Finished: Processing {} - Generating MINF Template DataFrame.'.format(usage_type))
                # time.sleep(3)

                # #Populate Summary Chart

                # self.txtProgress.emit('Started: Processing {} - Populating MINF Summary Chart.'.format(usage_type))

                # self._pv_model.populate_summary_chart(usage_type, workbook, minf_df, 'MINF_Summary', 6)

                # self.txtProgress.emit('Finished: Processing {} - Populating MINF Summary Chart.'.format(usage_type))
                # time.sleep(3)

                # #Populate Details sheet

                # self.txtProgress.emit('Started: Processing {} - Populating MINF Details Sheet.'.format(usage_type))

                # sheet_name = 'MINF_PreValidation_Details'
                # self._pv_model.populate_details_worksheet(writer, minf_df, sheet_name, 6)

                # self.txtProgress.emit('Finished: Processing {} - Populating MINF Details Sheet.'.format(usage_type))
                # time.sleep(3)

                print(self._pt_model._templates)

                #Save Workbook

                self.txtProgress.emit(
                    'Started: Processing {} - Saving Workbook to Output folder.'
                    .format(usage_type))

                writer.save()

                self.txtProgress.emit(
                    'Finished: Processing {} - Saving Workbook to Output folder.'
                    .format(usage_type))
                time.sleep(3)
class Pricing_Template_Controller():
    def __init__(self, QMainWindow, app_model):

        self._parent = QMainWindow
        self._app_model = app_model
        self._pt_model = Pricing_Template_Model(self._parent)
        self._com_model = Common_Model()

        self._ut_dup_bool = False
        self._selected = None
        self._continue_flag = True
        self._dia_pt_response = False

        self._selected_op = {'isPricingTemp': False, 'isPricingVal': False}

        self._progress_op = {
            True: self._progress_on,
            False: self._progress_off
        }

        # set connects for pricing template

        self._setupConnections()

        # Toggle Progress display

        self._progress_toggle()

    def _setupConnections(self):

        #========Pricing Template Dialog =========#

        self._pt_model.dialog_ui._cbUsageFlows.activated[int].connect(
            self._usageflow_changed)
        self._pt_model.dialog_ui._btnChangeSrc.clicked.connect(
            self._updateSourceFolder)
        self._pt_model.dialog_ui._btnChangeOut.clicked.connect(
            self._updateOutputFolder)
        self._pt_model.dialog_ui._btnGenerate.clicked.connect(
            self._showSelection)
        self._pt_model.dialog_ui._btnDelete.clicked.connect(
            self._deleteUsageFlow)
        self._pt_model.dialog_warn_ui._btnBox.accepted.connect(
            self._dialog_warn_accept)
        self._pt_model.dialog_warn_ui._btnBox.rejected.connect(
            self._dialog_warn_reject)

        #========Pricing Template Finish Dialog =========#

        self._pt_model.Dialog_fin_ui._btnReport.clicked.connect(
            self._display_pricing_template_report)
        self._pt_model.Dialog_fin_ui._btnClose.clicked.connect(
            self._dialog_finish_close)

        #========Pricing Template Report Dialog =========#

        self._pt_model.Dialog_report_ui._btnClose.clicked.connect(
            self._dialog_report_close)

        #========Pricing Template Select Dialog =========#

        self._pt_model.Dialog_select_ui.buttonBox.accepted.connect(
            self._getSelection)
        self._pt_model.Dialog_select_ui.buttonBox.rejected.connect(
            self._closeSelectDialog)

    def _updateSourceFolder(self):

        starting_dir = self._pt_model.dialog_ui._leSourceFolder.text()

        path = self._com_model._fileDialog(starting_dir, True, '', True)
        abs_path = os.path.abspath(path)

        self._pt_model.dialog_ui._leSourceFolder.setText(abs_path)

    def _updateOutputFolder(self):

        starting_dir = self._pt_model.dialog_ui._leOutputFolder.text()

        path = self._com_model._fileDialog(starting_dir, True, '', True)
        abs_path = os.path.abspath(path)

        self._pt_model.dialog_ui._leOutputFolder.setText(abs_path)

    def _showPricingTemplate(self):

        # Update Window Title

        self._pt_model.dialog_ui.updateWindowTitle(self._pt_model.Dialog,
                                                   "Pricing Template")

        # Populate Usage Flow combo box

        self._populateUsageFlows()

        # Load settings

        settings_data = self._app_model.parse_config('settings.json')
        self._com_model._load_settings(
            'PricingTemplate', settings_data,
            self._pt_model.dialog_ui._leSourceFolder,
            self._pt_model.dialog_ui._leOutputFolder)

        # Clear Template list

        self._pt_model.dialog_ui._leKeyword.setText("")
        self._pt_model.remove_template_list()

        # Update selection

        self._selected_op['isPricingTemp'] = True
        self._selected_op['isPricingVal'] = False

        response = self._pt_model.Dialog.exec()

        if response == self._pt_model.Dialog.Accepted:
            pass
        else:
            self._pt_model.Dialog.accept()
            self._pt_model.dialog_ui._lvUsageFlow.clear()

            #Save settings to settings.json

            src_folder = self._pt_model.dialog_ui._leSourceFolder.text()
            output_folder = self._pt_model.dialog_ui._leOutputFolder.text()

            self._com_model._save_settings('PricingTemplate', src_folder,
                                           output_folder)

    def _showPricingValidation(self):

        # Update Window Title

        self._pt_model.dialog_ui.updateWindowTitle(self._pt_model.Dialog,
                                                   "Pricing Validation")

        # Populate Usage Flow combo box

        self._populateUsageFlows()

        # Load settings

        settings_data = self._app_model.parse_config('settings.json')
        self._com_model._load_settings(
            'PricingValidation', settings_data,
            self._pt_model.dialog_ui._leSourceFolder,
            self._pt_model.dialog_ui._leOutputFolder)

        # Clear Template list

        self._pt_model.dialog_ui._leKeyword.setText("")
        self._pt_model.remove_template_list()

        # Update selection

        self._selected_op['isPricingTemp'] = False
        self._selected_op['isPricingVal'] = True

        response = self._pt_model.Dialog.exec()

        if response == self._pt_model.Dialog.Accepted:
            pass
        else:
            self._pt_model.Dialog.accept()
            self._pt_model.dialog_ui._lvUsageFlow.clear()

            #Save settings to settings.json

            src_folder = self._pt_model.dialog_ui._leSourceFolder.text()
            output_folder = self._pt_model.dialog_ui._leOutputFolder.text()

            self._com_model._save_settings('PricingValidation', src_folder,
                                           output_folder)

    def _get_usagetype(self):
        ''' Returns the currently selection workspace from combobox. '''
        return str(self._pt_model.dialog_ui._cbUsageFlows.currentText())

    def _usageflow_changed(self):
        if self._get_usagetype() == "ALL":
            self._pt_model.dialog_ui._lvUsageFlow.clear()
            self._app_model.delete_usage_types()
        else:
            self._populateUsageTypeList()

    def _add_usage_type(self, usage_type):
        self._app_model.add_usagetype(usage_type)

    def _selectionChanged(self):
        l_selected = []
        l_selected_obj = self._pt_model.dialog_ui._lvUsageFlow.selectedItems()

        for item in l_selected_obj:
            u_type = item.text().split('-')[0].strip()
            l_selected.append(u_type)

        return l_selected

    def _deleteUsageFlow(self):

        l_to_be_deleted = self._selectionChanged()

        for i in l_to_be_deleted:
            self._app_model.remove_usageflow(i)

        l_usage_types = self._app_model.get_usage_types()

        self._refreshUsageTypeList(l_usage_types)

    def _showSelection(self):

        # Display Selection dialog

        if self._get_usagetype() == "ALL":

            self._pt_model.Dialog_select.exec()

        else:

            self._generatePricingTemplate()

    def _getSelection(self):

        boxElements = self._pt_model.Dialog_select_ui.groupBox.children()

        radioButtons = [
            elem for elem in boxElements if isinstance(elem, QRadioButton)
        ]

        for rb in radioButtons:
            if rb.isChecked():
                checkedOnRb = rb.text()

        self._selected = checkedOnRb.split('-')[0].strip()

        self._closeSelectDialog()
        self._generatePricingTemplate()

    def _closeSelectDialog(self):
        self._pt_model.Dialog_select.close()

    def _generatePricingTemplate(self):

        self.keyword = self._pt_model.dialog_ui._leKeyword.text()
        self.src_folder = self._pt_model.dialog_ui._leSourceFolder.text()
        self.tgt_folder = self._pt_model.dialog_ui._leOutputFolder.text()

        if self.keyword:

            #Get Usage Type List

            if self._get_usagetype() == "ALL" and self._selected.upper(
            ) == "ALL":
                l_usage_types = self._app_model.get_usageflows()[1:]
            elif self._get_usagetype() == "ALL" and self._selected.upper(
            ) is not None:
                l_usage_types = [
                    usage_type
                    for usage_type in self._app_model.get_usageflows()[1:]
                    if usage_type in self._app_model.
                    get_usagetype_by_report_type(self._selected)
                ]
            else:
                l_usage_types = self._app_model.get_usage_types()

            #Get Templates found

            self.l_templates_found = self._pt_model.get_template_list(
                l_usage_types)

            self.l_templates_not_found = self._pt_model.get_template_list_not_found(
                l_usage_types)

            if self._continue_flag:

                if len(self.l_templates_found) > 0:

                    #Notify user of missing template

                    if self.l_templates_not_found:

                        self._populate_text_template_logs(
                            self.l_templates_not_found,
                            self._pt_model.dialog_warn_ui._teUsageTypes)
                        self._pt_model.Dialog_warn.exec()

                    else:

                        self._dia_pt_response = True

                    # Run the Main Program on Thread

                    if self._selected_op['isPricingTemp']:

                        # Show the Progress Layout
                        self._progress_toggle()

                        # Set max value for progress bar
                        max_progress_count = len(self.l_templates_found)
                        self._pt_model.dialog_ui._progressBar.setMaximum(
                            max_progress_count)

                        self.pt_main = Pricing_Template_Main(
                            self.src_folder, self.tgt_folder, self.keyword,
                            self.l_templates_found, self._pt_model)
                        self.pt_main.countProgress.connect(
                            self._updateProgressBar)
                        self.pt_main.txtProgress.connect(
                            self._updateProgressLabel)
                        self.pt_main.currStatus.connect(self._showErrorDialog)
                        self.pt_main.finished.connect(self._on_finished)
                        self.pt_main.start()

                    else:

                        # Show the Progress Layout
                        self._progress_toggle()

                        # Set max value for progress bar
                        max_progress_count = len(self.l_templates_found)
                        self._pt_model.dialog_ui._progressBar.setMaximum(
                            max_progress_count)

                        self.pv_main = Pricing_Validation_Main(
                            self.src_folder, self.tgt_folder, self.keyword,
                            self.l_templates_found, self._pt_model)
                        self.pv_main.countProgress.connect(
                            self._updateProgressBar)
                        self.pv_main.txtProgress.connect(
                            self._updateProgressLabel)
                        self.pv_main.currStatus.connect(self._showErrorDialog)
                        self.pv_main.finished.connect(self._on_finished)
                        self.pv_main.start()

                else:

                    self._pt_model.showDialog(
                        'warning', 'Error - Pricing Template',
                        'No template found for the selected Usage flow(s).',
                        None, None)

        else:

            # Display Dialog

            self._pt_model.showDialog('warning', 'No Keyword',
                                      'Please enter a valid keyword', None,
                                      None)

    def _dialog_warn_accept(self):

        self._continue_flag = True
        self._dia_pt_response = True
        self._pt_model.Dialog_warn.close()

    def _dialog_warn_reject(self):

        self._continue_flag = False
        self._dia_pt_response = False

        # Clear template list
        self._pt_model.remove_template_list()

        self._pt_model.Dialog_warn.close()

    def _dialog_report_close(self):

        self._pt_model.Dialog_report.close()
        self._back_to_default()

    def _dialog_finish_close(self):

        self._pt_model.Dialog_finish.close()

    def _cancelProgram(self):

        title = 'Cancel operation'
        msg = 'Are you sure you want to cancel?'

        reply = self._pt_model.showDialog('question', title, msg, None, None,
                                          True)

        if reply == QMessageBox.Yes:
            self.pt_main._cancel_flg = True

    def _showErrorDialog(self, value):

        if value[1] == 'Load Source':
            self._pt_model.showDialog(
                'warning', 'Warning',
                'Failed to load source file for keyword ' + value[0] +
                ' to a dataframe.', 'See details for more info.', value[2])
        elif value[1] == 'Load Template':
            self._pt_model.showDialog(
                'error', 'Error',
                'Failed to load the Pricing Template File for ' + value[0] +
                ' to a dataframe.', 'See details for more info.', value[2])
        elif value[1] == 'Populate Worksheet':
            self._pt_model.showDialog(
                'error', 'Error',
                value[0] + ' - Failed to populate worksheet ' + value[2] + '.',
                'See details for more info.', value[3])
        elif value[1] == 'Save Template':
            self._pt_model.showDialog(
                'error', 'Error',
                value[0] + ' - Failed to save template to ' + value[2] + '.',
                None, value[3])

    def _on_finished(self):

        if self._selected_op['isPricingTemp']:

            if self.pt_main._abort_flg or self.pt_main._cancel_flg:

                #self._pt_model.Dialog.close()
                self._back_to_default()

            else:

                self._display_finish_dialog()

        else:

            if self.pv_main._abort_flg or self.pv_main._cancel_flg:

                #self._pt_model.Dialog.close()
                self._back_to_default()
            else:

                self._display_finish_dialog()

        self._back_to_default()

    #======================= PROGRESS TOGGLE MODE =================================

    def _progress_toggle(self):
        self._progress_op[self._dia_pt_response]()
        self._pt_model.dialog_ui._lblProgress.setVisible(self._dia_pt_response)
        self._pt_model.dialog_ui._progressBar.setVisible(self._dia_pt_response)

    def _progress_on(self):

        try:
            self._pt_model.dialog_ui._btnGenerate.disconnect()
        except Exception:
            pass

        self._pt_model.dialog_ui._btnGenerate.clicked.connect(
            self._cancelProgram)
        self._pt_model.dialog_ui._btnGenerate.setText('Cancel')

    def _progress_off(self):

        self._pt_model.dialog_ui._btnGenerate.setText('Generate')

    def _updateProgressLabel(self, value):
        self._pt_model.dialog_ui._lblProgress.setText(value)

    def _updateProgressBar(self, value):
        self._pt_model.dialog_ui._progressBar.setValue(value)

    #==================================== DISPLAY =================================#

    def _populateUsageFlows(self):

        #Add All usage type

        self._app_model.add_usageflow('ALL')

        for u in self._app_model._conf_data['usageFlows']:
            usagetype = u['UsageType']
            self._app_model.add_usageflow(str(usagetype))

        # Populate combobox

        self._pt_model.dialog_ui._cbUsageFlows.clear()
        self._pt_model.dialog_ui._cbUsageFlows.addItems(
            self._app_model.get_usageflows())

    def _refreshUsageTypeList(self, l_usage_type):

        # Clear List Widget

        self._pt_model.dialog_ui._lvUsageFlow.clear()

        for usage_type in l_usage_type:

            #Add selected item to List Widget
            item = QListWidgetItem(self._pt_model.dialog_ui._lvUsageFlow)
            item.setText(usage_type + ' - ' +
                         self._app_model.get_usage_type_details(
                             usage_type, usage_type)[0])

    def _populateUsageTypeList(self):

        usage_type = self._get_usagetype()

        self._continue_flag = True

        self._ut_dup_bool = self._app_model.check_dup_usage_type(usage_type)

        if not self._ut_dup_bool:

            #Add usage type to OD
            self._add_usage_type(usage_type)

            #Add selected item to List Widget
            item = QListWidgetItem(self._pt_model.dialog_ui._lvUsageFlow)
            item.setText(usage_type + ' - ' +
                         self._app_model.get_usage_type_details(
                             usage_type, usage_type)[0])

        else:

            # Display Dialog

            self._pt_model.showDialog(
                'inform', 'Usage Type Selection',
                'Duplicate: ' + usage_type + ' already added on the list.',
                None, None)

    def _generate_pricing_template_report(self):

        cnt_source = self._pt_model.get_template_counts()
        self._pt_model.Dialog_report_ui.widget_Bar.display_result(cnt_source)

    def _generate_pricing_table_report(self):

        model = self._pt_model.get_missing_columns_df()

        self._pt_model.Dialog_report_ui._tblMissingColumns.setModel(model)

        # set horizontal header properties
        hh = self._pt_model.Dialog_report_ui._tblMissingColumns.horizontalHeader(
        )
        hh.setStretchLastSection(True)

        # set column width to fit contents
        self._pt_model.Dialog_report_ui._tblMissingColumns.resizeColumnsToContents(
        )

        # set minimum size
        self._pt_model.Dialog_report_ui._tblMissingColumns.setMinimumSize(
            QtCore.QSize(0, 200))

        # set row height
        # nrows = len(df.index)
        # for row in xrange(nrows):
        #     tv.setRowHeight(row, 14)

    def _display_finish_dialog(self):

        # Display finish dialog

        if len(self.l_templates_found) == 0:

            self._pt_model.Dialog_fin_ui._btnReport.setEnabled(False)

        #Total complete templates

        cnt = 0
        for i in self.l_templates_found:

            usage_type = i[0]
            status = self._pt_model.get_template_status(usage_type)

            if status == 'c':
                cnt += 1

        self._pt_model.Dialog_fin_ui._leTotalTemp.setText(str(cnt))
        self._pt_model.Dialog_fin_ui._teOutputFolder.setText(self.tgt_folder)

        if self._selected_op['isPricingTemp']:
            self._pt_model.Dialog_fin_ui._le_TotalTime.setText(
                self.pt_main.elapsed_time)
        else:
            self._pt_model.Dialog_fin_ui._le_TotalTime.setText(
                self.pv_main.elapsed_time)

        self._pt_model.Dialog_finish.exec()

    def _display_pricing_template_report(self):

        # Close finish dialog

        self._dialog_finish_close()

        # Generate Report

        self._generate_pricing_template_report()

        # Populate Table

        self._generate_pricing_table_report()

        # Populate List of templates not found

        self._populate_text_template_logs(
            self.l_templates_not_found,
            self._pt_model.Dialog_report_ui._te_templates)

        if self._selected_op['isPricingTemp']:

            # Populate List of Missing usage types

            set_usage_type_src = set(self.pt_main.get_all_usage_types())
            set_usage_type_app = set([
                t['UsageType']
                for t in self._app_model._conf_data['usageFlows']
            ])

            l_missing = list(sorted(set_usage_type_src - set_usage_type_app))

            self._populate_text_logs(
                l_missing, self._pt_model.Dialog_report_ui._te_usagetype)

        # Show Dialog report

        self._pt_model.Dialog_report.exec()

    def _populate_text_logs(self, l_object, te_object):

        if l_object:

            # Clear Line Edit
            te_object.clear()

            for i in l_object:
                te_object.append(i)

    def _populate_text_template_logs(self, l_object, te_object):

        if l_object:

            # Clear Line Edit
            te_object.clear()

            for i in l_object:
                te_object.append(i[0])

    def _back_to_default(self):

        self._continue_flag = True
        self._dia_pt_response = False

        #Clear Selected templates list
        self._pt_model.remove_template_list()

        # Set default valud of Progress Bar
        self._updateProgressBar(0)

        try:
            self._pt_model.dialog_ui._btnGenerate.disconnect()
        except Exception:
            pass
        self._pt_model.dialog_ui._btnGenerate.clicked.connect(
            self._showSelection)

        self._progress_toggle()
示例#9
0
class Contract_Template_Controller():
    def __init__(self, QMainWindow, app_model):

        self._parent = QMainWindow
        self._app_model = app_model
        self._ct_model = Contract_Template_Model(self._parent)
        self._com_model = Common_Model()

        self._dia_ct_response = False

        self._template_op = {
            'isContractTypeTemp': False,
            'isDebitCredit': False,
            'isContractStep1': False,
            'isContractStep3': False
        }

        self._progress_op = {
            True: self._progress_on,
            False: self._progress_off
        }

        # Toggle Progress display

        self._progress_toggle()

        self._setupConnections()

    def _setupConnections(self):

        #========Contract Type Template Dialog =========#

        self._ct_model.dialog_ui.btnOutputFolder.clicked.connect(
            self._updateOutputFolder)
        self._ct_model.dialog_ui.btnGenerate.clicked.connect(
            self._generateTemplate)

    #======================= PROGRESS TOGGLE MODE =================================

    def _progress_toggle(self):
        self._progress_op[self._dia_ct_response]()
        self._ct_model.dialog_ui._lblProgress.setVisible(self._dia_ct_response)
        self._ct_model.dialog_ui._progressBar.setVisible(self._dia_ct_response)

    def _progress_on(self):

        try:
            self._ct_model.dialog_ui.btnGenerate.disconnect()
        except Exception:
            pass

        self._ct_model.dialog_ui.btnGenerate.clicked.connect(
            self._cancelProgram)
        self._ct_model.dialog_ui.btnGenerate.setText('Cancel')

    def _progress_off(self):

        self._ct_model.dialog_ui.btnGenerate.setText('Generate')

    def _updateProgressLabel(self, value):
        self._ct_model.dialog_ui._lblProgress.setText(value)

    def _updateProgressBar(self, value):
        self._ct_model.dialog_ui._progressBar.setValue(value)

    def _cancelProgram(self):

        title = 'Cancel operation'
        msg = 'Are you sure you want to cancel?'

        reply = self._ct_model.showDialog('question', title, msg, None, None,
                                          True)

        if reply == QMessageBox.Yes:

            if self._template_op['isContractTypeTemp']:
                self.ct_main._cancel_flg = True
            elif self._template_op['isDebitCredit']:
                self.dc_main._cancel_flg = True
            elif self._template_op['isContractStep1']:
                self.cv1_main._cancel_flg = True
            else:
                self.cv3_main._cancel_flg = True

    #======================= RADIO BUTTONS TOGGLE MODE =================================

    def _button_toggle(self, display):
        self._ct_model.dialog_ui.rbtnDebit.setVisible(display)
        self._ct_model.dialog_ui.rbtnCredit.setVisible(display)
        self._ct_model.dialog_ui.rbtnAll.setVisible(display)

    #======================= MAIN FUNCTIONS =================================

    def _updateSourceFolder(self):

        try:
            self._ct_model.dialog_ui.btnSourceFolder.disconnect()
        except Exception:
            pass

        starting_dir = self._ct_model.dialog_ui.leSourceFolder.text()

        if self._template_op['isContractTypeTemp'] or self._template_op[
                'isContractStep1']:

            path = self._com_model._fileDialog(starting_dir, True, '')
            abs_path = os.path.abspath(path)
        else:
            path = self._com_model._fileDialog(starting_dir, True, '', True)
            abs_path = os.path.abspath(path)

        self._ct_model.dialog_ui.btnSourceFolder.clicked.connect(
            self._updateSourceFolder)

        self._ct_model.dialog_ui.leSourceFolder.setText(abs_path)

    def _updateOutputFolder(self):

        starting_dir = self._ct_model.dialog_ui.leOutputFolder.text()

        path = self._com_model._fileDialog(starting_dir, True, '', True)
        abs_path = os.path.abspath(path)

        self._ct_model.dialog_ui.leOutputFolder.setText(abs_path)

    ########################### Contract Templates ##############################

    def _showContractTypeTemplate(self):

        # Update Window Title

        self._ct_model.dialog_ui.updateWindowTitle(self._ct_model.Dialog,
                                                   "Contract Type Template")

        # Clear Template list

        self._ct_model.dialog_ui.leKeyword.setText("")

        # Load settings

        settings_data = self._app_model.parse_config('settings.json')
        self._com_model._load_settings('ContractTypeTemplate', settings_data,
                                       self._ct_model.dialog_ui.leSourceFolder,
                                       self._ct_model.dialog_ui.leOutputFolder)

        # Update selection

        self._template_op['isContractTypeTemp'] = True
        self._template_op['isDebitCredit'] = False
        self._template_op['isContractStep1'] = False
        self._template_op['isContractStep3'] = False

        # Hide Radio Buttons

        self._button_toggle(False)

        # set connection for Source folder

        self._ct_model.dialog_ui.btnSourceFolder.clicked.connect(
            self._updateSourceFolder)

        response = self._ct_model.Dialog.exec()

        if response == self._ct_model.Dialog.Accepted:
            pass
        else:
            self._ct_model.Dialog.accept()

            #Save settings to settings.json

            src_folder = self._ct_model.dialog_ui.leSourceFolder.text()
            output_folder = self._ct_model.dialog_ui.leOutputFolder.text()

            self._com_model._save_settings('ContractTypeTemplate', src_folder,
                                           output_folder)

    def _showDebitCreditTemplate(self):

        # Update Window Title

        self._ct_model.dialog_ui.updateWindowTitle(self._ct_model.Dialog,
                                                   "Debit Credit Template")
        self._ct_model.dialog_ui.lblSource.setText("Source Folder:")

        # Clear Template list

        self._ct_model.dialog_ui.leKeyword.setText("")

        # Load settings

        settings_data = self._app_model.parse_config('settings.json')
        self._com_model._load_settings('DebitCreditTemplate', settings_data,
                                       self._ct_model.dialog_ui.leSourceFolder,
                                       self._ct_model.dialog_ui.leOutputFolder)

        # Update selection

        self._template_op['isContractTypeTemp'] = False
        self._template_op['isDebitCredit'] = True
        self._template_op['isContractStep1'] = False
        self._template_op['isContractStep3'] = False

        # Show Radio Buttons

        self._button_toggle(True)

        # set connection for Source folder

        self._ct_model.dialog_ui.btnSourceFolder.clicked.connect(
            self._updateSourceFolder)

        response = self._ct_model.Dialog.exec()

        if response == self._ct_model.Dialog.Accepted:
            pass
        else:
            self._ct_model.Dialog.accept()

            #Save settings to settings.json

            src_folder = self._ct_model.dialog_ui.leSourceFolder.text()
            output_folder = self._ct_model.dialog_ui.leOutputFolder.text()

            self._com_model._save_settings('DebitCreditTemplate', src_folder,
                                           output_folder)

    ########################### Contract Validations ##############################

    def _showContractPreValStep1Template(self):

        # Update Window Title

        self._ct_model.dialog_ui.updateWindowTitle(
            self._ct_model.Dialog, "Contract Type PreVal Step 1 Template")

        # Clear Template list

        self._ct_model.dialog_ui.leKeyword.setText("")

        # Load settings

        settings_data = self._app_model.parse_config('settings.json')
        self._com_model._load_settings('ContractStep1Template', settings_data,
                                       self._ct_model.dialog_ui.leSourceFolder,
                                       self._ct_model.dialog_ui.leOutputFolder)

        # Update selection

        self._template_op['isContractTypeTemp'] = False
        self._template_op['isDebitCredit'] = False
        self._template_op['isContractStep1'] = True
        self._template_op['isContractStep3'] = False

        # Hide Radio Buttons

        self._button_toggle(False)

        # set connection for Source folder

        self._ct_model.dialog_ui.btnSourceFolder.clicked.connect(
            self._updateSourceFolder)

        response = self._ct_model.Dialog.exec()

        if response == self._ct_model.Dialog.Accepted:
            pass
        else:
            self._ct_model.Dialog.accept()

            #Save settings to settings.json

            src_folder = self._ct_model.dialog_ui.leSourceFolder.text()
            output_folder = self._ct_model.dialog_ui.leOutputFolder.text()

            self._com_model._save_settings('ContractStep1Template', src_folder,
                                           output_folder)

    def _showContractPreValStep3Template(self):

        # Update Window Title

        self._ct_model.dialog_ui.updateWindowTitle(
            self._ct_model.Dialog, "Contract Type PreVal Step 3 Template")

        # Clear Template list

        self._ct_model.dialog_ui.leKeyword.setText("")

        # Load settings

        settings_data = self._app_model.parse_config('settings.json')
        self._com_model._load_settings('ContractStep3Template', settings_data,
                                       self._ct_model.dialog_ui.leSourceFolder,
                                       self._ct_model.dialog_ui.leOutputFolder)

        # Update selection

        self._template_op['isContractTypeTemp'] = False
        self._template_op['isDebitCredit'] = False
        self._template_op['isContractStep1'] = False
        self._template_op['isContractStep3'] = True

        # Hide Radio Buttons

        self._button_toggle(False)

        # set connection for Source folder

        self._ct_model.dialog_ui.btnSourceFolder.clicked.connect(
            self._updateSourceFolder)

        response = self._ct_model.Dialog.exec()

        if response == self._ct_model.Dialog.Accepted:
            pass
        else:
            self._ct_model.Dialog.accept()

            #Save settings to settings.json

            src_folder = self._ct_model.dialog_ui.leSourceFolder.text()
            output_folder = self._ct_model.dialog_ui.leOutputFolder.text()

            self._com_model._save_settings('ContractStep3Template', src_folder,
                                           output_folder)

    def _generateTemplate(self):

        self.keyword = self._ct_model.dialog_ui.leKeyword.text()
        self.src_file = self._ct_model.dialog_ui.leSourceFolder.text()
        self.tgt_folder = self._ct_model.dialog_ui.leOutputFolder.text()

        if self.keyword:

            if self._template_op['isContractTypeTemp']:

                #Notify user of missing template

                folder_path = os.getcwd(
                ) + "\\resources\\" + self._ct_model._ct_config[
                    'TemplateFolder']
                template_name = self._ct_model._ct_config['ContractTypeName']
                template_fname = folder_path + '\\' + template_name

                template_exist = self._ct_model.checkContractTypeTemplate(
                    folder_path, template_name)

                if template_exist:

                    #Read source file to DF

                    ct_file_name = '{}_{}.csv'.format(
                        self._ct_model._ct_config['SourceFileName'],
                        self.keyword)
                    src_file_name = self.src_file.split('\\')[-1]

                    if src_file_name == ct_file_name:

                        self._dia_ct_response = True

                        # Show the Progress Layout
                        self._progress_toggle()

                        # Set max value for progress bar
                        self._ct_model.dialog_ui._progressBar.setMaximum(5)

                        self.ct_main = Contract_Template_Main(
                            template_fname, self.src_file, self.tgt_folder,
                            self.keyword, self._ct_model, self._com_model)
                        self.ct_main.currStatus.connect(self._showErrorDialog)
                        self.ct_main.countProgress.connect(
                            self._updateProgressBar)
                        self.ct_main.txtProgress.connect(
                            self._updateProgressLabel)
                        self.ct_main.isCancel.connect(self._on_finished)
                        self.ct_main.finished.connect(self._on_finished)
                        self.ct_main.start()

                    else:

                        self._ct_model.showDialog(
                            'warning', 'Contract Type Template',
                            'Invalid Source File Name\n{}'.format(
                                src_file_name), None, None)
                else:

                    self._ct_model.showDialog(
                        'warning', 'Contract Type Template',
                        'Contract Type Template not found.', None, None)

            elif self._template_op['isDebitCredit']:

                # Get Selection

                selected = self._getSelection()

                # Check Template

                folder_path = os.getcwd(
                ) + "\\resources\\" + self._ct_model._dc_config[
                    'TemplateFolder']

                tup_template = self._ct_model.checkDebitCreditTemplate(
                    folder_path, selected)
                l_missing = tup_template[1]

                if not l_missing:

                    # Check Source Files

                    tup_source = self._ct_model.checkDebitCreditSource(
                        self.keyword, self.src_file, selected)
                    l_missing_src = tup_source[1]

                    if not l_missing_src:

                        l_template = tup_template[0]
                        l_details = tup_source[0]

                        self._dia_ct_response = True

                        # Show the Progress Layout
                        self._progress_toggle()

                        # Set max value for progress bar

                        max_cnt = ((len(l_details) * 4) * len(l_template)) + 2
                        self._ct_model.dialog_ui._progressBar.setMaximum(
                            max_cnt)

                        self.dc_main = Debit_Credit_Main(
                            self.keyword, self.tgt_folder, l_template,
                            l_details, self._ct_model, self._com_model)
                        self.dc_main.currStatus.connect(self._showErrorDialog)
                        self.dc_main.countProgress.connect(
                            self._updateProgressBar)
                        self.dc_main.txtProgress.connect(
                            self._updateProgressLabel)
                        self.dc_main.isCancel.connect(self._on_finished)
                        self.dc_main.finished.connect(self._on_finished)
                        self.dc_main.start()

                    else:

                        temp_missing = ''

                        for t, s, f in l_missing_src:

                            temp_missing = temp_missing + '{} : {} - {}\n'.format(
                                t, s, f)

                        self._ct_model.showDialog(
                            'warning', 'Debit Credit Template',
                            'Source File Not Found:\n {}'.format(temp_missing),
                            None, None)

                else:

                    temp_missing = ''

                    for t, f in l_missing:

                        temp_missing = temp_missing + '{}\n'.format(f)

                    self._ct_model.showDialog(
                        'warning', 'Debit Credit Template',
                        'Templates Not Found:\n {}'.format(temp_missing), None,
                        None)

            elif self._template_op['isContractStep1']:

                #Notify user of missing template

                folder_path = os.getcwd(
                ) + "\\resources\\" + self._ct_model._cv1_config[
                    'TemplateFolder']
                template_name = self._ct_model._cv1_config[
                    'PrevalStep1TempName']
                template_fname = folder_path + '\\' + template_name

                template_exist = self._ct_model.checkContractTypeTemplate(
                    folder_path, template_name)

                if template_exist:

                    #Read source file to DF

                    ct_file_name = '{}_{}.csv'.format(
                        self._ct_model.
                        _cv1_config['PrevalStep1SourceFileName'], self.keyword)
                    src_file_name = self.src_file.split('\\')[-1]

                    if src_file_name == ct_file_name:

                        self._dia_ct_response = True

                        # Show the Progress Layout
                        self._progress_toggle()

                        # Set max value for progress bar
                        self._ct_model.dialog_ui._progressBar.setMaximum(5)

                        self.cv1_main = Contract_Preval_Step1_Main(
                            template_fname, self.src_file, self.tgt_folder,
                            self.keyword, self._ct_model, self._com_model)
                        self.cv1_main.currStatus.connect(self._showErrorDialog)
                        self.cv1_main.countProgress.connect(
                            self._updateProgressBar)
                        self.cv1_main.txtProgress.connect(
                            self._updateProgressLabel)
                        self.cv1_main.isCancel.connect(self._on_finished)
                        self.cv1_main.finished.connect(self._on_finished)
                        self.cv1_main.start()

                    else:

                        self._ct_model.showDialog(
                            'warning', 'Contract Type PreVal Step 1 Template',
                            'Invalid Source File Name\n{}'.format(
                                src_file_name), None, None)

                else:

                    self._ct_model.showDialog(
                        'warning', 'Contract Type PreVal Step 1 Template',
                        'Contract Type PreVal Step 1 Template not found.',
                        None, None)

            else:

                #Notify user of missing template

                folder_path = os.getcwd(
                ) + "\\resources\\" + self._ct_model._cv3_config[
                    'TemplateFolder']
                template_name = self._ct_model._cv3_config[
                    'PrevalStep3TempName']
                template_fname = folder_path + '\\' + template_name

                template_exist = self._ct_model.checkContractTypeTemplate(
                    folder_path, template_name)

                if template_exist:

                    # Check Source Files

                    tup_source = self._ct_model.checkContractPreValStep3Source(
                        self.keyword, self.src_file)
                    l_missing_src = tup_source[1]

                    if not l_missing_src:

                        l_details = tup_source[0]

                        self._dia_ct_response = True

                        # Show the Progress Layout
                        self._progress_toggle()

                        # Set max value for progress bar

                        max_cnt = ((len(l_details) * 4)) + 2
                        self._ct_model.dialog_ui._progressBar.setMaximum(
                            max_cnt)

                        self.cv3_main = Contract_Preval_Step3_Main(
                            self.keyword, template_fname, self.tgt_folder,
                            l_details, self._ct_model, self._com_model)
                        self.cv3_main.currStatus.connect(self._showErrorDialog)
                        self.cv3_main.countProgress.connect(
                            self._updateProgressBar)
                        self.cv3_main.txtProgress.connect(
                            self._updateProgressLabel)
                        self.cv3_main.isCancel.connect(self._on_finished)
                        self.cv3_main.finished.connect(self._on_finished)
                        self.cv3_main.start()

                    else:

                        temp_missing = ''

                        for s, f in l_missing_src:

                            temp_missing = temp_missing + '{} - {}\n'.format(
                                s, f)

                        self._ct_model.showDialog(
                            'warning', 'Contract Type PreVal Step 3 Template',
                            'Source File Not Found:\n {}'.format(temp_missing),
                            None, None)

                else:

                    self._ct_model.showDialog(
                        'warning', 'Contract Type PreVal Step 3 Template',
                        'Contract Type PreVal Step 3 Template not found.',
                        None, None)

        else:

            # Display Dialog

            self._ct_model.showDialog('warning', 'No Keyword',
                                      'Please enter a valid keyword', None,
                                      None)

    def _getSelection(self):

        boxElements = self._ct_model.dialog_ui.groupBox_2.children()

        radioButtons = [
            elem for elem in boxElements if isinstance(elem, QRadioButton)
        ]

        for rb in radioButtons:
            if rb.isChecked():
                checkedOnRb = rb.text()

        selected = checkedOnRb.split('-')[0].strip()

        return selected

    def _on_finished(self):

        self._back_to_default()

        if self._template_op['isContractTypeTemp']:

            if not self.ct_main._cancel_flg and self.ct_main.is_successful:

                self._ct_model.showDialog(
                    'inform', 'Contract Type Template',
                    '{} file successfully saved.'.format(
                        self.ct_main.output_filenm), None, None)

        elif self._template_op['isDebitCredit']:

            if not self.dc_main._cancel_flg and self.dc_main.is_successful:

                self._ct_model.showDialog(
                    'inform', 'Debit Credit Enrichment Template',
                    '{} file successfully saved.'.format(
                        self.dc_main.output_filenm), None, None)

        elif self._template_op['isContractStep1']:

            if not self.cv1_main._cancel_flg and self.cv1_main.is_successful:

                self._ct_model.showDialog(
                    'inform', 'Contract Type PreVal Step 1 Template',
                    '{} file successfully saved.'.format(
                        self.cv1_main.output_filenm), None, None)

        elif self._template_op['isContractStep3']:

            if not self.cv3_main._cancel_flg and self.cv3_main.is_successful:

                self._ct_model.showDialog(
                    'inform', 'Contract Type PreVal Step 3 Template',
                    '{} file successfully saved.'.format(
                        self.cv3_main.output_filenm), None, None)

        else:

            pass

    def _showErrorDialog(self, value):

        if value[1] == 'Load Source':
            self._ct_model.showDialog(
                'warning', 'Warning',
                'Failed to load source file for keyword ' + value[0] +
                ' to a dataframe.', 'See details for more info.', value[2])
        elif value[1] == 'Load Template':
            self._ct_model.showDialog(
                'error', 'Error',
                'Failed to load the Pricing Template File for ' + value[0] +
                ' to a dataframe.', 'See details for more info.', value[2])
        elif value[1] == 'Populate Worksheet':
            self._ct_model.showDialog(
                'error', 'Error',
                'Failed to populate worksheet ' + value[0] + '.',
                'See details for more info.', value[2])
        elif value[1] == 'Save Template':
            self._ct_model.showDialog(
                'error', 'Error',
                'Failed to save template to ' + value[0] + '.', None, value[2])

    def _back_to_default(self):

        self._dia_ct_response = False

        # Set default valud of Progress Bar
        self._updateProgressBar(0)

        try:
            self._ct_model.dialog_ui.btnGenerate.disconnect()
        except Exception:
            pass
        self._ct_model.dialog_ui.btnGenerate.clicked.connect(
            self._generateTemplate)

        self._progress_toggle()