Beispiel #1
0
    def _parse_ecb_data(self, available_currencies):
        ''' This method is used to update the currencies by using ECB service provider.
            Rates are given against EURO
        '''
        request_url = "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"
        try:
            parse_url = requests.request('GET', request_url)
        except:
            #connection error, the request wasn't successful
            return False

        xmlstr = etree.fromstring(parse_url.content)
        data = xml2json_from_elementtree(xmlstr)
        node = data['children'][2]['children'][0]
        available_currency_names = available_currencies.mapped('name')
        rslt = {
            x['attrs']['currency']:
            (float(x['attrs']['rate']), fields.Date.today())
            for x in node['children']
            if x['attrs']['currency'] in available_currency_names
        }

        if rslt and 'EUR' in available_currency_names:
            rslt['EUR'] = (1.0, fields.Date.today())

        return rslt
    def _parse_bnr_data(self, available_currencies):
        ''' This method is used to update the currencies by using
        BNR service provider. Rates are given against RON
        '''
        request_url = "https://www.bnr.ro/nbrfxrates.xml"
        try:
            parse_url = requests.request('GET', request_url)
        except:
            #connection error, the request wasn't successful
            return False

        xmlstr = etree.fromstring(parse_url.content)
        data = xml2json_from_elementtree(xmlstr)
        available_currency_names = available_currencies.mapped('name')
        rate_date = fields.Date.today()
        rslt = {}
        rates_node = data['children'][1]['children'][2]
        if rates_node:
            rate_date = (datetime.datetime.strptime(
                rates_node['attrs']['date'], DEFAULT_SERVER_DATE_FORMAT
            ) + datetime.timedelta(days=1)).strftime(DEFAULT_SERVER_DATE_FORMAT)
            for x in rates_node['children']:
                if x['attrs']['currency'] in available_currency_names:
                    rslt[x['attrs']['currency']] = (
                        float(x['attrs'].get('multiplier', '1')) / float(x['children'][0]),
                        rate_date
                    )
        if rslt and 'RON' in available_currency_names:
            rslt['RON'] = (1.0, rate_date)
        return rslt
Beispiel #3
0
    def _update_currency_ecb(self):
        ''' This method is used to update the currencies by using ECB service provider.
            Rates are given against EURO
        '''
        Currency = self.env['res.currency']
        CurrencyRate = self.env['res.currency.rate']

        currencies = Currency.search([])
        currencies = [x.name for x in currencies]
        request_url = "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"
        try:
            parse_url = requests.request('GET', request_url)
        except:
            #connection error, the request wasn't successful
            return False
        xmlstr = etree.fromstring(parse_url.content)
        data = xml2json_from_elementtree(xmlstr)
        node = data['children'][2]['children'][0]
        currency_node = [(x['attrs']['currency'], x['attrs']['rate'])
                         for x in node['children']
                         if x['attrs']['currency'] in currencies]
        for company in self:
            base_currency_rate = 1
            if company.currency_id.name != 'EUR':
                #find today's rate for the base currency
                base_currency = company.currency_id.name
                base_currency_rates = [
                    (x['attrs']['currency'], x['attrs']['rate'])
                    for x in node['children']
                    if x['attrs']['currency'] == base_currency
                ]
                base_currency_rate = len(
                    base_currency_rates) and base_currency_rates[0][1] or 1
                currency_node += [('EUR', '1.0000')]

            for currency_code, rate in currency_node:
                rate = float(rate) / float(base_currency_rate)
                currency = Currency.search([('name', '=', currency_code)],
                                           limit=1)
                if currency:
                    CurrencyRate.create({
                        'currency_id': currency.id,
                        'rate': rate,
                        'name': fields.Datetime.now(),
                        'company_id': company.id
                    })
        return True
Beispiel #4
0
    def _parse_fta_data(self, available_currencies):
        ''' Parses the data returned in xml by FTA servers and returns it in a more
        Python-usable form.'''
        request_url = 'http://www.pwebapps.ezv.admin.ch/apps/rates/rate/getxml?activeSearchType=today'
        try:
            parse_url = requests.request('GET', request_url)
        except:
            return False

        rates_dict = {}
        available_currency_names = available_currencies.mapped('name')
        xml_tree = etree.fromstring(parse_url.content)
        data = xml2json_from_elementtree(xml_tree)
        for child_node in data['children']:
            if child_node['tag'] == 'devise':
                currency_code = child_node['attrs']['code'].upper()

                if currency_code in available_currency_names:
                    currency_xml = None
                    rate_xml = None

                    for sub_child in child_node['children']:
                        if sub_child['tag'] == 'waehrung':
                            currency_xml = sub_child['children'][0]
                        elif sub_child['tag'] == 'kurs':
                            rate_xml = sub_child['children'][0]
                        if currency_xml and rate_xml:
                            #avoid iterating for nothing on children
                            break

                    rates_dict[currency_code] = (
                        float(re.search('\d+', currency_xml).group()) /
                        float(rate_xml), fields.Date.today())

        if 'CHF' in available_currency_names:
            rates_dict['CHF'] = (1.0, fields.Date.today())

        return rates_dict
Beispiel #5
0
    def get_updated_currency(self, currency_array, main_currency, max_delta_days):
        request_url = "http://www.tcmb.gov.tr/kurlar/today.xml"

        if main_currency in currency_array:
            currency_array.remove(main_currency)

        _logger.info('TCMB Currency Rate Service: connecting..')

        #Currency = self.env['res.currency']
        # CurrencyRate = self.env['res.currency.rate'] => Bu object burada çağırılmayacak.

        #currencies = Currency.search([]) => currencies yerine parametreden gelen currency_array kullanılacak.
        #currencies = [curr.name for curr in currencies]

        try:
            parse_url = requests.request('GET', request_url)
            _logger.info("TCMB sent a valid url")
        except:
            return False

        xmlstr = etree.fromstring(parse_url.content)
        data = xml2json_from_elementtree(xmlstr)
        if data:
            _logger.info("TCMB sent a valid data")

        node = data
        self.check_date(node, max_delta_days)
        self.supported_currency_array.append('EUR')
        _logger.info('Supported currencies = %s', self.supported_currency_array)
        self.validate_cur(main_currency)

        if main_currency != 'TRY':
            main_currency_data = self.rate_retrieve(node, main_currency)

        for curr in currency_array:
            self.validate_cur(curr)
            if curr == 'TRY':
                rate = 1 / main_currency_data['rate_currency']
                rate_bb = 1 / main_currency_data['banknot_buying_currency']
                rate_fs = 1 / main_currency_data['forex_selling_currency']
                rate_fb = 1 / main_currency_data['forex_buying_currency']
            else:
                currency_data = self.rate_retrieve(node, curr)
                if main_currency == 'TRY':
                    rate = currency_data['rate_currency']
                    rate_bb = currency_data['banknot_buying_currency']
                    rate_fs = currency_data['forex_selling_currency']
                    rate_fb = currency_data['forex_buying_currency']
                else:
                    rate = currency_data['rate_currency'] / main_currency_data['rate_currency']
                    rate_bb = currency_data['banknot_buying_currency'] / main_currency_data['banknot_buying_currency']
                    rate_fs = currency_data['forex_selling_currency'] / main_currency_data['forex_selling_currency']
                    rate_fb = currency_data['forex_buying_currency'] / main_currency_data['forex_buying_currency']

            # Nested Dictionary for TCMB Döviz Alış, Döviz Satış, Efektif Alış, Efektif Satış
            self.updated_currency[curr] = {}
            self.updated_currency[curr]['rate'] = rate
            self.updated_currency[curr]['rate_bb'] = rate_bb
            self.updated_currency[curr]['rate_fs'] = rate_fs
            self.updated_currency[curr]['rate_fb'] = rate_fb
            _logger.info(
                'Kur oranlari alindi: 1 %s = %s %s (Gecerli Kur)' % (main_currency, rate, curr)
            )
        return self.updated_currency, self.log_info
    def _update_currency_tcmb(self):

        Currency = self.env['res.currency']
        CurrencyRate = self.env['res.currency.rate']

        currencies = Currency.search([])
        currencies = [x.name for x in currencies]
        request_url = "http://www.tcmb.gov.tr/kurlar/today.xml"
        try:
            parse_url = requests.request('GET', request_url)
        except:
            #connection error, the request wasn't successful
            return False

        xmlstr = etree.fromstring(parse_url.content)
        data = xml2json_from_elementtree(xmlstr)

        node = data
        currency_node = [
            (x['attrs']['CurrencyCode'], x['children'][6]['children'][0],
             x['children'][5]['children'][0], x['children'][4]['children'][0],
             x['children'][3]['children'][0]) for x in node['children']
            if x['attrs']['CurrencyCode'] in currencies
        ]

        for company in self:
            base_currency_rate = 1
            if company.currency_id.name != 'TRY':
                #find today's rate for the base currency
                base_currency = company.currency_id.name
                base_currency_rates = [
                    (x['attrs']['CurrencyCode'],
                     x['children'][6]['children'][0],
                     x['children'][5]['children'][0],
                     x['children'][4]['children'][0],
                     x['children'][3]['children'][0]) for x in node['children']
                    if x['attrs']['CurrencyCode'] == base_currency
                ]

                base_currency_rate = len(
                    base_currency_rates) and base_currency_rates[0][1] or 1

                banknot_buying = len(
                    base_currency_rates) and base_currency_rates[0][2] or 1
                forex_selling = len(
                    base_currency_rates) and base_currency_rates[0][3] or 1
                forex_buying = len(
                    base_currency_rates) and base_currency_rates[0][4] or 1

                currency_node += [('TRY', '1.0000')]

            for currency_code, rate, banknot_buying, forex_selling, forex_buying in currency_node:
                rate = float(base_currency_rate) / float(rate)

                banknot_buying_rate = float(base_currency_rate) / float(
                    banknot_buying)
                forex_selling_rate = float(base_currency_rate) / float(
                    forex_selling)
                forex_buying_rate = float(base_currency_rate) / float(
                    forex_buying)

                currency = Currency.search([('name', '=', currency_code)],
                                           limit=1)
                if currency:
                    CurrencyRate.create({
                        'currency_id': currency.id,
                        'rate': rate,
                        'banknot_buying_rate': banknot_buying_rate,
                        'forex_selling_rate': forex_selling_rate,
                        'forex_buying_rate': forex_buying_rate,
                        'name': fields.Datetime.now(),
                        'company_id': company.id
                    })

            if company.currency_id.rate != 1.0:
                CurrencyRate.create({
                    'currency_id': company.currency_id.id,
                    'rate': 1.0,
                    'banknot_buying_rate': 1.0,
                    'forex_selling_rate': 1.0,
                    'forex_buying_rate': 1.0,
                    'name': fields.Datetime.now(),
                    'company_id': company.id
                })

        return True