Beispiel #1
0
def set_xml_to_pending_cfdi(cfdi, logger=None, sl1_execution_log=None):
    try:
        forest_db = _Utilities.set_connection_to_forest_db()
        db_CFDI = forest_db['CFDI']
        uuid = cfdi['uuid']
        # Get xml data:
        xml = cfdi['xml']
        validation = _Pauli_Helper.validate_xml(xml)
        xml_warnings = validation['warnings']
        xml_invalidations = validation['invalidations']
        # Updating data:
        updating_cfdi_data = {
            'xml': xml,
            'validated': True if validation['validated'] else False,
            'details': {
                'invalidations': xml_invalidations,
                'warnings': xml_warnings
            }  # End of details
        }  #End of updating_cfdi_data
        db_CFDI.update({'uuid': uuid}, {'$set': updating_cfdi_data})
        sl1_execution_log['forest_db']['after'][
            'pending_completed'] = sl1_execution_log['forest_db']['after'][
                'pending_completed'] + 1
    except Exception as e:
        logger.critical(e.message)
        already_handled_exception = Already_Handled_Exception(e.message)
        raise already_handled_exception
Beispiel #2
0
def set_xml_to_pending_cfdi(cfdi,logger=None,sl1_execution_log=None):
	try:
		forest_db = _Utilities.set_connection_to_forest_db()
		db_CFDI = forest_db['CFDI']
		uuid = cfdi['uuid']
		# Get xml data:
		xml = cfdi['xml']
		validation = _Pauli_Helper.validate_xml(xml)
		xml_warnings = validation['warnings']
		xml_invalidations = validation['invalidations']
		# Updating data:
		updating_cfdi_data = {
			'xml' : xml,
			'validated' : True  if validation['validated'] else False,
			'details' : {
			    'invalidations' : xml_invalidations,
			    'warnings' : xml_warnings
			}# End of details
		}#End of updating_cfdi_data
		db_CFDI.update({'uuid':uuid},{'$set':updating_cfdi_data})
		sl1_execution_log['forest_db']['after']['pending_completed'] = sl1_execution_log['forest_db']['after']['pending_completed'] + 1
	except Exception as e:
		logger.critical(e.message)
		already_handled_exception = Already_Handled_Exception(e.message)
		raise already_handled_exception
Beispiel #3
0
def create_cfdi(new_cfdi,logger=None,sl1_execution_log=None):
	try:
		forest_db = _Utilities.set_connection_to_forest_db()
		db_CFDI = forest_db['CFDI']
		uuid = new_cfdi['uuid'].upper()
		# Build new db cfdi:
		db_new_cfdi = {
			'uuid': uuid,
			'buyer': new_cfdi['buyer'],
			'seller': new_cfdi['seller'],
			'status': new_cfdi['status'],
			'voucher_effect' : new_cfdi['voucher_effect'] if 'voucher_effect' in new_cfdi else None
		}#End of db_ne_cfdi
		if 'simulated' in new_cfdi and new_cfdi['simulated'] == True:
			db_new_cfdi['certification_date'] = new_cfdi['certification_date']# It comes from db -- date is already parsed -- 
			db_new_cfdi['issued_date'] = new_cfdi['issued_date']
		else:
			db_new_cfdi['certification_date'] = _Utilities.sat_date_to_ISODate(new_cfdi['certification_date'])
			db_new_cfdi['issued_date'] = _Utilities.sat_date_to_ISODate(new_cfdi['issued_date'])
		# Get xml data:
		xml = new_cfdi['xml']
		if xml is not None and xml != '':#bug_solved, xml was '' and it causes errors in cfdi_type, currency and taxes
			cfdi_type = _Utilities.get_cfdi_type(xml,logger=logger)
			validation = _Pauli_Helper.validate_xml(xml)
			xml_warnings = validation['warnings']
			xml_invalidations = validation['invalidations']
			db_new_cfdi['xml'] = xml
			db_new_cfdi['validated'] = True  if validation['validated'] else False
			db_new_cfdi['details'] = {
				'invalidations' : xml_invalidations,
				'warnings' : xml_warnings
			}#End of details
			db_new_cfdi['cfdi_type'] = cfdi_type# It says if cfdi is a credit_note, payroll or normal
			currency = _Pauli_Helper.get_currency(xml,logger=logger)
			if currency is not None:
				db_new_cfdi['currency'] = currency
			else:
				db_new_cfdi['currency'] = 'mxn'# Default
			taxes_included = _Pauli_Helper.get_taxes_included_in_this_CFDI(xml,logger=logger)
			db_new_cfdi['_wl_ish'] = taxes_included['_wl_ish'] if taxes_included['_wl_ish'] is not None else False
			db_new_cfdi['_t_iva_16'] = taxes_included['_t_iva_16'] if taxes_included['_t_iva_16'] is not None else False
			db_new_cfdi['_t_iva_0'] = taxes_included['_t_iva_0'] if taxes_included['_t_iva_0'] is not None else False
			db_new_cfdi['_w_iva_10'] = taxes_included['_w_iva_10'] if taxes_included['_w_iva_10'] is not None else False
			db_new_cfdi['_w_isr'] = taxes_included['_w_isr'] if taxes_included['_w_isr'] is not None else False
			db_new_cfdi['_tl_ish'] = taxes_included['_tl_ish'] if taxes_included['_tl_ish'] is not None else False
			db_new_cfdi['_t_ieps'] = taxes_included['_t_ieps'] if taxes_included['_t_ieps'] is not None else False
			sl1_execution_log['forest_db']['after']['new'] = sl1_execution_log['forest_db']['after']['new'] + 1
		elif new_cfdi['status'] == _Constants.CANCELED_STATUS:
			# db_new_cfdi['xml'] = _Helper.build_default_xml(db_new_cfdi['seller'],db_new_cfdi['buyer'],db_new_cfdi['certification_date'],db_new_cfdi['issued_date'],db_new_cfdi['voucher_effect'],db_new_cfdi['uuid'])
			sl1_execution_log['forest_db']['after']['new'] = sl1_execution_log['forest_db']['after']['new'] + 1
		else:
			sl1_execution_log['forest_db']['after']['pending'] = sl1_execution_log['forest_db']['after']['pending'] + 1
		db_CFDI.insert(db_new_cfdi)
	except Exception as e:
		logger.critical(e.message)
		already_handled_exception = Already_Handled_Exception(e.message)
		raise already_handled_exception
Beispiel #4
0
def update_initialization_data_for_taxpayer(taxpayer,
                                            initialization_execution_log,
                                            logger=None):
    try:
        forest_db = _Utilities.set_connection_to_forest_db()
        db_Taxpayer = forest_db['Taxpayer']
        # Update sl1 success execution date:
        init_date = STATUS_DATES['initialization']
        initialization_date = Datetime.now()
        taxpayer[init_date] = initialization_date
        if initialization_execution_log['initialized'] == False:
            # Update synchronization logs:
            identifier = taxpayer['identifier']
            begin_date = taxpayer[
                'start_date']  #Since taxpayer claim to be synchronized
            begin_date = begin_date.replace(hour=0, minute=0)
            end_date = initialization_date
            cfdis_in_forest_db_count = _Utilities.get_cfdis_count_in_forest_for_this_taxpayer_at_period(
                taxpayer, begin_date, end_date)
            initialization_log = {
                'status': 200,
                'temporal_data': {
                    'completed_date': initialization_date,
                    'period': {
                        'year':
                        int(initialization_execution_log['year_initialized']),
                        'month':
                        int(initialization_execution_log['month_initialized'])
                    },
                },
                'cfdis': {
                    'new': initialization_execution_log['stored'],
                    'updated': 0,
                    'total': cfdis_in_forest_db_count
                }  # End of synchronization_log
            }  # End of initialization_log
            taxpayer_logs = taxpayer['logs'] if 'logs' in taxpayer and taxpayer[
                'logs'] is not None else {}
            taxpayer_initialization_logs = taxpayer_logs[_Constants.INITIALIZATION] if _Constants.INITIALIZATION in taxpayer_logs else []
            taxpayer_initialization_logs.append(initialization_log)
            taxpayer_logs[
                _Constants.INITIALIZATION] = taxpayer_initialization_logs
            taxpayer['logs'] = taxpayer_logs
        db_Taxpayer.save(taxpayer)
    except Exception as e:
        print e
        if logger is not None:
            logger.critical(e.message)
        already_handled_exception = Already_Handled_Exception(e.message)
        raise already_handled_exception
Beispiel #5
0
def update_synchronization_data_for_taxpayer(taxpayer,
                                             sl1_execution_log,
                                             logger=None):
    try:
        forest_db = _Utilities.set_connection_to_forest_db()
        db_Taxpayer = forest_db['Taxpayer']
        # Update sl1 success execution date:
        sl1_date = STATUS_DATES['synchronization_layer_1']
        synchronization_date = Datetime.now()
        taxpayer[sl1_date] = synchronization_date
        # Update synchronization logs:
        identifier = taxpayer['identifier']
        begin_date = taxpayer[
            'start_date']  #Since taxpayer claim to be synchronized
        begin_date = begin_date.replace(hour=0, minute=0)
        end_date = synchronization_date  # Until now
        cfdis_in_forest_db_count = _Utilities.get_cfdis_count_in_forest_for_this_taxpayer_at_period(
            taxpayer, begin_date, end_date)
        synchronization_log = {
            'status': 200,
            'temporal_data': {
                'completed_date': synchronization_date,
                'period': {
                    'year': synchronization_date.year,
                    'month': synchronization_date.month
                },
            },
            'cfdis': {
                'new': sl1_execution_log['stored'],
                'updated': sl1_execution_log['updated'],
                'total': cfdis_in_forest_db_count
            }  # End of synchronization_log
        }  # End of synchronization_log
        taxpayer_logs = taxpayer['logs'] if 'logs' in taxpayer and taxpayer[
            'logs'] is not None else {}
        taxpayer_synchronization_logs = taxpayer_logs[_Constants.SYNCHRONIZATION] if _Constants.SYNCHRONIZATION in taxpayer_logs else []
        taxpayer_synchronization_logs.append(synchronization_log)
        if len(taxpayer_synchronization_logs
               ) > _Constants.LIMIT_LOGS_PER_TAXPAYER:
            taxpayer_synchronization_logs[:1] = []
        taxpayer_logs[
            _Constants.SYNCHRONIZATION] = taxpayer_synchronization_logs
        taxpayer['logs'] = taxpayer_logs
        db_Taxpayer.save(taxpayer)
    except Exception as e:
        if logger is not None:
            logger.critical(e.message)
        already_handled_exception = Already_Handled_Exception(e.message)
        raise already_handled_exception
Beispiel #6
0
def set_cancelled_status_to_cfdi(cfdi,updated_cfdi,logger=None,sl1_execution_log=None):
	try:
		forest_db = _Utilities.set_connection_to_forest_db()
		db_CFDI = forest_db['CFDI']
		cfdi['status'] = updated_cfdi['status'] # Equalize status
		if 'cancelation_date' in updated_cfdi:
			cfdi['cancelation_date'] = _Helper.sat_date_to_ISODate(updated_cfdi['cancelation_date'])
		xml_exists = 'xml' in cfdi and cfdi['xml'] != ''
		if not xml_exists:
			cfdi['xml'] = _Helper.build_default_xml(cfdi['seller'],cfdi['buyer'],cfdi['certification_date'],cfdi['issued_date'],cfdi['voucher_effect'],cfdi['uuid'])
		sl1_execution_log['forest_db']['after']['updated'] = sl1_execution_log['forest_db']['after']['updated'] + 1
		db_CFDI.save(cfdi)
	except Exception as e:
		logger.critical(e.message)
		already_handled_exception = Already_Handled_Exception(e.message)
		raise already_handled_exception
Beispiel #7
0
def update_taxpayer_initialization_status(taxpayer,new_initialization_data,logger=None,initialized=False):
	try:
		taxpayer['data']['initialization'] = new_initialization_data
		if initialized == True:
			taxpayer['status'] = _Constants.SYNCHRONIZATION
		else:
			taxpayer['data']['months_initialized'] = taxpayer['data']['months_initialized'] + 1
		percentage_initialized = get_initialization_percentage_done(taxpayer)
		taxpayer['data']['percentage_initialized'] = percentage_initialized
		forest_db = _Utilities.set_connection_to_forest_db()
		db_Taxpayer = forest_db['Taxpayer']
		db_Taxpayer.save(taxpayer)
		return taxpayer	
	except Exception as e:
		if logger is not None:
			logger.critical(e.message)
		already_handled_exception = Already_Handled_Exception(e.message)
		raise already_handled_exception	
Beispiel #8
0
def update_synchronization_data_for_taxpayer(taxpayer,sl1_execution_log,logger=None):
	try:
		forest_db = _Utilities.set_connection_to_forest_db()
		db_Taxpayer = forest_db['Taxpayer']
		# Update sl1 success execution date:
		sl1_date = STATUS_DATES['synchronization_layer_1']
		synchronization_date = Datetime.now()
		taxpayer[sl1_date] = synchronization_date
		# Update synchronization logs:
		identifier = taxpayer['identifier']
		begin_date = taxpayer['start_date']#Since taxpayer claim to be synchronized
		begin_date = begin_date.replace(hour=0, minute=0)
		end_date = synchronization_date# Until now
		cfdis_in_forest_db_count = _Utilities.get_cfdis_count_in_forest_for_this_taxpayer_at_period(taxpayer,begin_date,end_date)
		synchronization_log = {
			'status' : 200,
			'temporal_data' : {
				'completed_date' : synchronization_date,
				'period' : {
					'year' : synchronization_date.year,
					'month' : synchronization_date.month
				},
			},
			'cfdis' : {
				'new' : sl1_execution_log['stored'],
				'updated' : sl1_execution_log['updated'],
				'total' : cfdis_in_forest_db_count
			}# End of synchronization_log
		}# End of synchronization_log
		taxpayer_logs = taxpayer['logs'] if 'logs' in taxpayer and taxpayer['logs'] is not None else {}
		taxpayer_synchronization_logs = taxpayer_logs[_Constants.SYNCHRONIZATION] if _Constants.SYNCHRONIZATION in taxpayer_logs else []
		taxpayer_synchronization_logs.append(synchronization_log)
		if len(taxpayer_synchronization_logs) > _Constants.LIMIT_LOGS_PER_TAXPAYER: 
			taxpayer_synchronization_logs[:1] = []
		taxpayer_logs[_Constants.SYNCHRONIZATION] = taxpayer_synchronization_logs
		taxpayer['logs'] = taxpayer_logs
		db_Taxpayer.save(taxpayer)		
	except Exception as e:
		if logger is not None:
			logger.critical(e.message)
		already_handled_exception = Already_Handled_Exception(e.message)
		raise already_handled_exception
Beispiel #9
0
def update_initialization_data_for_taxpayer(taxpayer,initialization_execution_log,logger=None):
	try:
		forest_db = _Utilities.set_connection_to_forest_db()
		db_Taxpayer = forest_db['Taxpayer']
		# Update sl1 success execution date:
		init_date = STATUS_DATES['initialization']
		initialization_date = Datetime.now()
		taxpayer[init_date] = initialization_date
		if initialization_execution_log['initialized'] == False:
			# Update synchronization logs:
			identifier = taxpayer['identifier']
			begin_date = taxpayer['start_date']#Since taxpayer claim to be synchronized
			begin_date = begin_date.replace(hour=0, minute=0)
			end_date = initialization_date
			cfdis_in_forest_db_count = _Utilities.get_cfdis_count_in_forest_for_this_taxpayer_at_period(taxpayer,begin_date,end_date)
			initialization_log = {
				'status' : 200,
				'temporal_data' : {
					'completed_date' : initialization_date,
					'period' : {
						'year' : int(initialization_execution_log['year_initialized']),
						'month' : int(initialization_execution_log['month_initialized'])
					},
				},
				'cfdis' : {
					'new' : initialization_execution_log['stored'],
					'updated' : 0,
					'total' : cfdis_in_forest_db_count
				}# End of synchronization_log
			}# End of initialization_log
			taxpayer_logs = taxpayer['logs'] if 'logs' in taxpayer and taxpayer['logs'] is not None else {}
			taxpayer_initialization_logs = taxpayer_logs[_Constants.INITIALIZATION] if _Constants.INITIALIZATION in taxpayer_logs else []
			taxpayer_initialization_logs.append(initialization_log)
			taxpayer_logs[_Constants.INITIALIZATION] = taxpayer_initialization_logs
			taxpayer['logs'] = taxpayer_logs
		db_Taxpayer.save(taxpayer)		
	except Exception as e:
		print e
		if logger is not None:
			logger.critical(e.message)
		already_handled_exception = Already_Handled_Exception(e.message)
		raise already_handled_exception
Beispiel #10
0
def update_taxpayer_initialization_status(taxpayer,
                                          new_initialization_data,
                                          logger=None,
                                          initialized=False):
    try:
        taxpayer['data']['initialization'] = new_initialization_data
        if initialized == True:
            taxpayer['status'] = _Constants.SYNCHRONIZATION
        else:
            taxpayer['data']['months_initialized'] = taxpayer['data'][
                'months_initialized'] + 1
        percentage_initialized = get_initialization_percentage_done(taxpayer)
        taxpayer['data']['percentage_initialized'] = percentage_initialized
        forest_db = _Utilities.set_connection_to_forest_db()
        db_Taxpayer = forest_db['Taxpayer']
        db_Taxpayer.save(taxpayer)
        return taxpayer
    except Exception as e:
        if logger is not None:
            logger.critical(e.message)
        already_handled_exception = Already_Handled_Exception(e.message)
        raise already_handled_exception
Beispiel #11
0
def set_cancelled_status_to_cfdi(cfdi,
                                 updated_cfdi,
                                 logger=None,
                                 sl1_execution_log=None):
    try:
        forest_db = _Utilities.set_connection_to_forest_db()
        db_CFDI = forest_db['CFDI']
        cfdi['status'] = updated_cfdi['status']  # Equalize status
        if 'cancelation_date' in updated_cfdi:
            cfdi['cancelation_date'] = _Helper.sat_date_to_ISODate(
                updated_cfdi['cancelation_date'])
        xml_exists = 'xml' in cfdi and cfdi['xml'] != ''
        if not xml_exists:
            cfdi['xml'] = _Helper.build_default_xml(
                cfdi['seller'], cfdi['buyer'], cfdi['certification_date'],
                cfdi['issued_date'], cfdi['voucher_effect'], cfdi['uuid'])
        sl1_execution_log['forest_db']['after'][
            'updated'] = sl1_execution_log['forest_db']['after']['updated'] + 1
        db_CFDI.save(cfdi)
    except Exception as e:
        logger.critical(e.message)
        already_handled_exception = Already_Handled_Exception(e.message)
        raise already_handled_exception
Beispiel #12
0
def excute_initialization_for_taxpayer(forcing_execution=False,
                                       forcing_period=False,
                                       taxpayer=None,
                                       process_logger=None,
                                       process_params=None):
    try:
        process_logger.info(2 * LOG_INDENT + 'Forcing period: ' +
                            str(forcing_period))
        initialization_data = _Locals.get_initialization_data(
            taxpayer, logger=process_logger, process_params=process_params)
        initialized = initialization_data['initialized']
        if initialized == False:
            initialization_log = _Locals.new_initialization_log(
                logger=process_logger)
            # Get CFDIs from DB:
            process_logger.info(2 * LOG_INDENT +
                                'RETRIEVING DATA FROM FOREST DB ... ')
            _year = str(initialization_data['year'])
            _month = str(initialization_data['month'])
            process_logger.info(3 * LOG_INDENT + 'Year: ' +
                                str(initialization_data['year']) + ' Month: ' +
                                str(initialization_data['month']))
            process_logger.info(3 * LOG_INDENT + 'From ' +
                                str(initialization_data['begin_date']) +
                                ' to ' + str(initialization_data['end_date']))
            cfdis_in_db = _Utilities.get_cfdis_in_forest_for_this_taxpayer_at_period(
                taxpayer,
                initialization_data['begin_date'],
                initialization_data['end_date'],
                limit=None)
            # Manage or format CFDis data:
            existing_cfdi_uuids = _Utilities.get_existing_uuids_in_forest_db(
                cfdis_in_db=cfdis_in_db, logger=process_logger)
            # Log Forest data:
            process_logger.info(3 * LOG_INDENT + 'Existing:           ' +
                                str(len(existing_cfdi_uuids)))
            # Get CFDIs from firmware:
            get_sat_updates_params = {
                'identifier': taxpayer['identifier'],
                'password': taxpayer['password'],
                'year': initialization_data['year'],
                'months': [initialization_data['month']],
                'uuids': existing_cfdi_uuids
            }  # End of get_sat_update_params
            # -------------------------------------------------------------------
            # bugSolved 12/Ago/15
            # Event: timeout value was becoming longer and longer because of connection problems (firmware servers could not be reached due to connection problems instead of logic problems)
            # firmware_timeout = taxpayer['firmware_timeout'] if 'firmware_timeout' in taxpayer and taxpayer['firmware_timeout'] is not None else _Constants.DEFAULT_FIRMWARE_TIMEOUT
            firmware_timeout = _Constants.DEFAULT_FIRMWARE_TIMEOUT
            # -------------------------------------------------------------------
            # process_logger.info(2*LOG_INDENT + 'RETRIEVING DATA FROM FIRMWARE (SAT) constant timeout = ' + str(firmware_timeout) + ' secs')
            process_logger.info(2 * LOG_INDENT +
                                'RETRIEVING DATA FROM FIRMWARE (SAT)')
            sat_updates = _Firmware.isa(instruction='get_sat_updates',
                                        params=get_sat_updates_params,
                                        log=initialization_log,
                                        logger=process_logger,
                                        timeout=firmware_timeout,
                                        taxpayer=taxpayer)
            new_cfdis = sat_updates['new']
            process_logger.info(3 * LOG_INDENT + 'CFDI new:           ' +
                                str(initialization_log['firmware']['new']))
            process_logger.info(3 * LOG_INDENT + 'CFDI to-update:     ' +
                                str(initialization_log['firmware']['update']))
            # Update Forest DB -> NEW OR COMPLETED:
            process_logger.info(2 * LOG_INDENT + 'UPDATING FOREST DB ... ')
            n = 0
            forest_db = _Utilities.set_connection_to_forest_db()
            for new_cfdi in new_cfdis:
                try:
                    uuid = new_cfdi['uuid']
                    _Utilities.create_cfdi(new_cfdi,
                                           logger=process_logger,
                                           log=initialization_log,
                                           forest_db=forest_db)
                    n = n + 1
                    process_logger.info(3 * LOG_INDENT + str(n) + '. ' + uuid +
                                        ' stored in Forest DB')
                except:
                    process_logger.info(
                        3 * LOG_INDENT + str(n) + '. ' + uuid +
                        ' could not be stored in Forest DB (ERROR)')
            process_logger.info(2 * LOG_INDENT + 'SUMMARY ... ')
            process_logger.info(
                3 * LOG_INDENT + 'New stored:         ' +
                str(initialization_log['forest_db']['after']['new']))
            process_logger.info(
                3 * LOG_INDENT + 'Pending:            ' +
                str(initialization_log['forest_db']['after']['pending']))
            initialization_result = {
                'new':
                initialization_log['firmware']['new'],
                'stored':
                initialization_log['forest_db']['after']['new'],
                'year_initialized':
                initialization_data['year'],
                'month_initialized':
                initialization_data['month'],
                'avoid_iteration':
                initialization_log['avoid_iteration']
                if 'avoid_iteration' in initialization_log else False
            }  # End of initialization_result
        else:
            initialization_result = {
                'new': _Constants.ZLATAN,
                'stored': _Constants.ZLATAN,
                'year_initialized': _Constants.ZLATAN,
                'month_initialized': _Constants.ZLATAN
            }  # End of initialization_result
        # Update taxpayer:
        new_initialization_data = initialization_data[
            'new_initialization_data']
        initialization_result['initialized'] = initialized
        if forcing_period or ('avoid_iteration' in initialization_result
                              and initialization_result['avoid_iteration']
                              == True):
            process_logger.info(
                2 * LOG_INDENT +
                'NOT updating taxpayer initialization status ... ')
            initialization_result['percentage_initialized'] = "--.-%"
        else:
            taxpayer = _Locals.update_taxpayer_initialization_status(
                taxpayer,
                new_initialization_data,
                logger=process_logger,
                initialized=initialized)
            initialization_result['percentage_initialized'] = taxpayer['data'][
                'percentage_initialized']
            process_logger.info(
                3 * LOG_INDENT + 'Percentage initialized:            ' +
                str(initialization_result['percentage_initialized']))
        if forcing_execution:
            process_logger.info(3 * LOG_INDENT +
                                'Sending telegram notification ... ')
            message = 'Ya inicialice a este vato: ' + taxpayer[
                'identifier'] + ' para el periodo ' + _month + '/' + _year
            _Utilities.send_message_to_forest_telegram_contacts(
                message, logger=process_logger)
        return initialization_result
    except Already_Handled_Exception as already_handled_exception:
        raise already_handled_exception
    except Exception as e:
        process_logger.critical(e.message)
        already_handled_exception = Already_Handled_Exception(e.message)
        raise already_handled_exception
def excute_initialization_for_taxpayer(forcing_execution=False,forcing_period=False,taxpayer=None,process_logger=None,process_params=None):
	try:
		process_logger.info(2*LOG_INDENT + 'Forcing period: ' + str(forcing_period))
		initialization_data = _Locals.get_initialization_data(taxpayer,logger=process_logger,process_params=process_params)
		initialized = initialization_data['initialized']
		if initialized == False:
			initialization_log = _Locals.new_initialization_log(logger=process_logger)
			# Get CFDIs from DB:
			process_logger.info(2*LOG_INDENT + 'RETRIEVING DATA FROM FOREST DB ... ')
			_year = str(initialization_data['year'])
			_month = str(initialization_data['month'])
			process_logger.info(3*LOG_INDENT + 'Year: ' + str(initialization_data['year']) + ' Month: ' + str(initialization_data['month']))
			process_logger.info(3*LOG_INDENT + 'From ' + str(initialization_data['begin_date']) + ' to ' + str(initialization_data['end_date']))
			cfdis_in_db = _Utilities.get_cfdis_in_forest_for_this_taxpayer_at_period(taxpayer,initialization_data['begin_date'],initialization_data['end_date'],limit=None)
			# Manage or format CFDis data:
			existing_cfdi_uuids = _Utilities.get_existing_uuids_in_forest_db(cfdis_in_db=cfdis_in_db,logger=process_logger)
			# Log Forest data:
			process_logger.info(3*LOG_INDENT + 'Existing:           ' + str(len(existing_cfdi_uuids)))
			# Get CFDIs from firmware:
			get_sat_updates_params = {
				'identifier' : taxpayer['identifier'],
				'password' : taxpayer['password'],
				'year' : initialization_data['year'],
				'months' : [initialization_data['month']],
				'uuids' : existing_cfdi_uuids
			}# End of get_sat_update_params
			# -------------------------------------------------------------------
			# bugSolved 12/Ago/15 
			# Event: timeout value was becoming longer and longer because of connection problems (firmware servers could not be reached due to connection problems instead of logic problems)
			# firmware_timeout = taxpayer['firmware_timeout'] if 'firmware_timeout' in taxpayer and taxpayer['firmware_timeout'] is not None else _Constants.DEFAULT_FIRMWARE_TIMEOUT
			firmware_timeout = _Constants.DEFAULT_FIRMWARE_TIMEOUT
			# -------------------------------------------------------------------
			# process_logger.info(2*LOG_INDENT + 'RETRIEVING DATA FROM FIRMWARE (SAT) constant timeout = ' + str(firmware_timeout) + ' secs')
			process_logger.info(2*LOG_INDENT + 'RETRIEVING DATA FROM FIRMWARE (SAT)')
			sat_updates = _Firmware.isa(instruction='get_sat_updates',params=get_sat_updates_params,log=initialization_log,logger=process_logger,timeout=firmware_timeout,taxpayer=taxpayer)
			new_cfdis = sat_updates['new']
			process_logger.info(3*LOG_INDENT + 'CFDI new:           ' + str(initialization_log['firmware']['new']))
			process_logger.info(3*LOG_INDENT + 'CFDI to-update:     ' + str(initialization_log['firmware']['update']))
			# Update Forest DB -> NEW OR COMPLETED:
			process_logger.info(2*LOG_INDENT + 'UPDATING FOREST DB ... ')
			n = 0
			forest_db = _Utilities.set_connection_to_forest_db()
			for new_cfdi in new_cfdis:
				try:
					uuid = new_cfdi['uuid']
					_Utilities.create_cfdi(new_cfdi,logger=process_logger,log=initialization_log,forest_db=forest_db)
					n = n + 1
					process_logger.info(3*LOG_INDENT + str(n) + '. ' + uuid + ' stored in Forest DB')
				except:
					process_logger.info(3*LOG_INDENT + str(n) + '. ' + uuid + ' could not be stored in Forest DB (ERROR)')
			process_logger.info(2*LOG_INDENT + 'SUMMARY ... ')
			process_logger.info(3*LOG_INDENT + 'New stored:         ' + str(initialization_log['forest_db']['after']['new']))
			process_logger.info(3*LOG_INDENT + 'Pending:            ' + str(initialization_log['forest_db']['after']['pending']))
			initialization_result = {
				'new' : initialization_log['firmware']['new'],
				'stored' : initialization_log['forest_db']['after']['new'],
				'year_initialized' : initialization_data['year'],
				'month_initialized' : initialization_data['month'],
				'avoid_iteration' : initialization_log['avoid_iteration'] if 'avoid_iteration' in initialization_log else False
			}# End of initialization_result
		else:
			initialization_result = {
				'new' : _Constants.ZLATAN,
				'stored' : _Constants.ZLATAN,
				'year_initialized' : _Constants.ZLATAN,
				'month_initialized' : _Constants.ZLATAN
			}# End of initialization_result
		# Update taxpayer:
		new_initialization_data = initialization_data['new_initialization_data']
		initialization_result['initialized'] = initialized
		if forcing_period or ('avoid_iteration' in initialization_result and initialization_result['avoid_iteration'] == True):
			process_logger.info(2*LOG_INDENT + 'NOT updating taxpayer initialization status ... ')
			initialization_result['percentage_initialized'] = "--.-%"
		else:
			taxpayer = _Locals.update_taxpayer_initialization_status(taxpayer,new_initialization_data,logger=process_logger,initialized=initialized)
			initialization_result['percentage_initialized'] = taxpayer['data']['percentage_initialized']
			process_logger.info(3*LOG_INDENT + 'Percentage initialized:            ' + str(initialization_result['percentage_initialized']))
		if forcing_execution:
			process_logger.info(3*LOG_INDENT + 'Sending telegram notification ... ')
			message = 'Ya inicialice a este vato: ' + taxpayer['identifier'] + ' para el periodo ' + _month + '/' + _year
			_Utilities.send_message_to_forest_telegram_contacts(message,logger=process_logger)
		return initialization_result
	except Already_Handled_Exception as already_handled_exception:
		raise already_handled_exception
	except Exception as e:
		process_logger.critical(e.message)
		already_handled_exception = Already_Handled_Exception(e.message)
		raise already_handled_exception
Beispiel #14
0
def create_cfdi(new_cfdi, logger=None, sl1_execution_log=None):
    try:
        forest_db = _Utilities.set_connection_to_forest_db()
        db_CFDI = forest_db['CFDI']
        uuid = new_cfdi['uuid'].upper()
        # Build new db cfdi:
        db_new_cfdi = {
            'uuid':
            uuid,
            'buyer':
            new_cfdi['buyer'],
            'seller':
            new_cfdi['seller'],
            'status':
            new_cfdi['status'],
            'voucher_effect':
            new_cfdi['voucher_effect']
            if 'voucher_effect' in new_cfdi else None
        }  #End of db_ne_cfdi
        if 'simulated' in new_cfdi and new_cfdi['simulated'] == True:
            db_new_cfdi['certification_date'] = new_cfdi[
                'certification_date']  # It comes from db -- date is already parsed --
            db_new_cfdi['issued_date'] = new_cfdi['issued_date']
        else:
            db_new_cfdi['certification_date'] = _Utilities.sat_date_to_ISODate(
                new_cfdi['certification_date'])
            db_new_cfdi['issued_date'] = _Utilities.sat_date_to_ISODate(
                new_cfdi['issued_date'])
        # Get xml data:
        xml = new_cfdi['xml']
        if xml is not None and xml != '':  #bug_solved, xml was '' and it causes errors in cfdi_type, currency and taxes
            cfdi_type = _Utilities.get_cfdi_type(xml, logger=logger)
            validation = _Pauli_Helper.validate_xml(xml)
            xml_warnings = validation['warnings']
            xml_invalidations = validation['invalidations']
            db_new_cfdi['xml'] = xml
            db_new_cfdi[
                'validated'] = True if validation['validated'] else False
            db_new_cfdi['details'] = {
                'invalidations': xml_invalidations,
                'warnings': xml_warnings
            }  #End of details
            db_new_cfdi[
                'cfdi_type'] = cfdi_type  # It says if cfdi is a credit_note, payroll or normal
            currency = _Pauli_Helper.get_currency(xml, logger=logger)
            if currency is not None:
                db_new_cfdi['currency'] = currency
            else:
                db_new_cfdi['currency'] = 'mxn'  # Default
            taxes_included = _Pauli_Helper.get_taxes_included_in_this_CFDI(
                xml, logger=logger)
            db_new_cfdi['_wl_ish'] = taxes_included[
                '_wl_ish'] if taxes_included['_wl_ish'] is not None else False
            db_new_cfdi[
                '_t_iva_16'] = taxes_included['_t_iva_16'] if taxes_included[
                    '_t_iva_16'] is not None else False
            db_new_cfdi[
                '_t_iva_0'] = taxes_included['_t_iva_0'] if taxes_included[
                    '_t_iva_0'] is not None else False
            db_new_cfdi[
                '_w_iva_10'] = taxes_included['_w_iva_10'] if taxes_included[
                    '_w_iva_10'] is not None else False
            db_new_cfdi['_w_isr'] = taxes_included['_w_isr'] if taxes_included[
                '_w_isr'] is not None else False
            db_new_cfdi['_tl_ish'] = taxes_included[
                '_tl_ish'] if taxes_included['_tl_ish'] is not None else False
            db_new_cfdi['_t_ieps'] = taxes_included[
                '_t_ieps'] if taxes_included['_t_ieps'] is not None else False
            sl1_execution_log['forest_db']['after'][
                'new'] = sl1_execution_log['forest_db']['after']['new'] + 1
        elif new_cfdi['status'] == _Constants.CANCELED_STATUS:
            # db_new_cfdi['xml'] = _Helper.build_default_xml(db_new_cfdi['seller'],db_new_cfdi['buyer'],db_new_cfdi['certification_date'],db_new_cfdi['issued_date'],db_new_cfdi['voucher_effect'],db_new_cfdi['uuid'])
            sl1_execution_log['forest_db']['after'][
                'new'] = sl1_execution_log['forest_db']['after']['new'] + 1
        else:
            sl1_execution_log['forest_db']['after'][
                'pending'] = sl1_execution_log['forest_db']['after'][
                    'pending'] + 1
        db_CFDI.insert(db_new_cfdi)
    except Exception as e:
        logger.critical(e.message)
        already_handled_exception = Already_Handled_Exception(e.message)
        raise already_handled_exception