Merge lp:~atin81/account-financial-tools/account-financial-tools into lp:~account-core-editors/account-financial-tools/6.1

Proposed by Agustín
Status: Merged
Approved by: Yannick Vaucher @ Camptocamp
Approved revision: 105
Merged at revision: 107
Proposed branch: lp:~atin81/account-financial-tools/account-financial-tools
Merge into: lp:~account-core-editors/account-financial-tools/6.1
Diff against target: 1110 lines (+349/-293)
5 files modified
currency_rate_update/__init__.py (+30/-26)
currency_rate_update/__openerp__.py (+46/-41)
currency_rate_update/company.py (+66/-68)
currency_rate_update/currency_rate_update.py (+204/-155)
currency_rate_update/currency_rate_update.xml (+3/-3)
To merge this branch: bzr merge lp:~atin81/account-financial-tools/account-financial-tools
Reviewer Review Type Date Requested Status
Yannick Vaucher @ Camptocamp code review, no tests Approve
Omar (Pexego) code review Approve
Guewen Baconnier @ Camptocamp code review Approve
Nicolas Bessi - Camptocamp (community) code review, no tests Needs Fixing
Moisés López - http://www.vauxoo.com Pending
Review via email: mp+183064@code.launchpad.net

Commit message

I have corrected the comments you done, please review it and let me know if there is anything else needed for merge it.

Description of the change

Implemented feature for auto update currency exchange using Banxico information for USD & MXN

To post a comment you must log in.
Revision history for this message
Nicolas Bessi - Camptocamp (nbessi-c2c-deactivatedaccount) wrote :

Hello,

Thanks for your proposal

res_company class renaming is not a good thing it my break monkey patch or existing imports.
class does not need to be instanciated.

Line 427
Your change is faulty some it can induce false positive, to be reverted please.

netsvc.Logger is Deprecated please use logging module "logger.debug".

Regards

Nicolas

review: Needs Fixing (code review, no tests)
105. By Agustin Cruz <email address hidden>

Corrected Nicolas comments

Revision history for this message
Moisés López - http://www.vauxoo.com (moylop260) wrote :

Hello @Nicolas,
FYI FIX commited

Revision history for this message
Guewen Baconnier @ Camptocamp (gbaconnier-c2c) wrote :

Notes on this module:
 - the license is still GPL, should be moved to AGPL.
 - A cleaning should be done (propagation of context is missing, weird constructions or idioms).

That's not the matter of this MP though, so I approve.

Thanks.

review: Approve (code review)
Revision history for this message
Omar (Pexego) (omar7r) wrote :

LGTM

review: Approve (code review)
Revision history for this message
Yannick Vaucher @ Camptocamp (yvaucher-c2c) wrote :

Ola

+1 about Guewen comment

So I approve this MP for the feature addition for 'banco de mexico'

Cheers

review: Approve (code review, no tests)

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== modified file 'currency_rate_update/__init__.py' (properties changed: +x to -x)
2--- currency_rate_update/__init__.py 2011-08-12 12:35:23 +0000
3+++ currency_rate_update/__init__.py 2013-09-17 18:13:12 +0000
4@@ -1,33 +1,37 @@
5 ##############################################################################
6 #
7-# Copyright (c) 2008 Camtocamp SA
8-# @author JB Aubort, Nicolas Bessi, Joel Grand-Guillaume
9-# European Central Bank and Polish National Bank invented by Grzegorz Grzelak
10-# $Id: $
11-#
12-# WARNING: This program as such is intended to be used by professional
13-# programmers who take the whole responsability of assessing all potential
14-# consequences resulting from its eventual inadequacies and bugs
15-# End users who are looking for a ready-to-use solution with commercial
16-# garantees and support are strongly adviced to contract a Free Software
17-# Service Company
18-#
19-# This program is Free Software; you can redistribute it and/or
20-# modify it under the terms of the GNU General Public License
21-# as published by the Free Software Foundation; either version 2
22-# of the License, or (at your option) any later version.
23-#
24-# This program is distributed in the hope that it will be useful,
25-# but WITHOUT ANY WARRANTY; without even the implied warranty of
26-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27-# GNU General Public License for more details.
28-#
29-# You should have received a copy of the GNU General Public License
30-# along with this program; if not, write to the Free Software
31-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
32+# Copyright (c) 2008 Camtocamp SA
33+# @author JB Aubort, Nicolas Bessi, Joel Grand-Guillaume
34+# European Central Bank and Polish National Bank invented by Grzegorz Grzelak
35+# Banxico implemented by Agustin Cruz openpyme.mx
36+# $Id: $
37+#
38+# WARNING: This program as such is intended to be used by professional
39+# programmers who take the whole responsability of assessing all potential
40+# consequences resulting from its eventual inadequacies and bugs
41+# End users who are looking for a ready-to-use solution with commercial
42+# garantees and support are strongly adviced to contract a Free Software
43+# Service Company
44+#
45+# This program is Free Software; you can redistribute it and/or
46+# modify it under the terms of the GNU General Public License
47+# as published by the Free Software Foundation; either version 2
48+# of the License, or (at your option) any later version.
49+#
50+# This program is free software: you can redistribute it and/or modify
51+# it under the terms of the GNU Affero General Public License as
52+# published by the Free Software Foundation, either version 3 of the
53+# License, or (at your option) any later version.
54+#
55+# This program is distributed in the hope that it will be useful,
56+# but WITHOUT ANY WARRANTY; without even the implied warranty of
57+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
58+# GNU Affero General Public License for more details.
59+#
60+# You should have received a copy of the GNU Affero General Public License
61+# along with this program. If not, see <http://www.gnu.org/licenses/>.
62 #
63 ##############################################################################
64-
65 import currency_rate_update
66 import company
67 import wizard
68
69=== modified file 'currency_rate_update/__openerp__.py' (properties changed: +x to -x)
70--- currency_rate_update/__openerp__.py 2012-07-31 14:29:55 +0000
71+++ currency_rate_update/__openerp__.py 2013-09-17 18:13:12 +0000
72@@ -1,30 +1,35 @@
73 ##############################################################################
74 #
75-# Copyright (c) 2008 Camtocamp SA
76-# @author JB Aubort, Nicolas Bessi, Joel Grand-Guillaume
77-# European Central Bank and Polish National Bank invented by Grzegorz Grzelak
78-# $Id: $
79-#
80-# WARNING: This program as such is intended to be used by professional
81-# programmers who take the whole responsability of assessing all potential
82-# consequences resulting from its eventual inadequacies and bugs
83-# End users who are looking for a ready-to-use solution with commercial
84-# garantees and support are strongly adviced to contract a Free Software
85-# Service Company
86-#
87-# This program is Free Software; you can redistribute it and/or
88-# modify it under the terms of the GNU General Public License
89-# as published by the Free Software Foundation; either version 2
90-# of the License, or (at your option) any later version.
91-#
92-# This program is distributed in the hope that it will be useful,
93-# but WITHOUT ANY WARRANTY; without even the implied warranty of
94-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
95-# GNU General Public License for more details.
96-#
97-# You should have received a copy of the GNU General Public License
98-# along with this program; if not, write to the Free Software
99-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
100+# Copyright (c) 2008 Camtocamp SA
101+# @author JB Aubort, Nicolas Bessi, Joel Grand-Guillaume
102+# European Central Bank and Polish National Bank invented by Grzegorz Grzelak
103+# Banxico implemented by Agustin Cruz openpyme.mx
104+# $Id: $
105+#
106+# WARNING: This program as such is intended to be used by professional
107+# programmers who take the whole responsability of assessing all potential
108+# consequences resulting from its eventual inadequacies and bugs
109+# End users who are looking for a ready-to-use solution with commercial
110+# garantees and support are strongly adviced to contract a Free Software
111+# Service Company
112+#
113+# This program is Free Software; you can redistribute it and/or
114+# modify it under the terms of the GNU General Public License
115+# as published by the Free Software Foundation; either version 2
116+# of the License, or (at your option) any later version.
117+#
118+# This program is free software: you can redistribute it and/or modify
119+# it under the terms of the GNU Affero General Public License as
120+# published by the Free Software Foundation, either version 3 of the
121+# License, or (at your option) any later version.
122+#
123+# This program is distributed in the hope that it will be useful,
124+# but WITHOUT ANY WARRANTY; without even the implied warranty of
125+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
126+# GNU Affero General Public License for more details.
127+#
128+# You should have received a copy of the GNU Affero General Public License
129+# along with this program. If not, see <http://www.gnu.org/licenses/>.
130 #
131 ##############################################################################
132 {
133@@ -33,9 +38,8 @@
134 "author" : "Camptocamp",
135 "website" : "http://camptocamp.com",
136 "category" : "Financial Management/Configuration",
137- "description": """Import exchange rates from the Internet.
138-
139-The module is able to use 4 different sources:
140+ "description": """
141+Import exchange rates from three different sources on the internet :
142
143 1. Admin.ch
144 Updated daily, source in CHF.
145@@ -51,36 +55,37 @@
146
147 4. Polish National Bank (Narodowy Bank Polski) (contribution by Grzegorz Grzelak)
148 Takes official rates from www.nbp.pl. Adds rate table symbol in log.
149- You should check when rates should apply to bookkeeping. If next day you should
150- change the update hour in schedule settings because in OpenERP they apply from
151+ You should check when rates should apply to bookkeeping. If next day you should
152+ change the update hour in schedule settings because in OpenERP they apply from
153 date of update (date - no hours).
154+
155+5. Banxico for USD & MXN (created by Agustín Cruz)
156+ Updated daily
157
158 In the roadmap : Google Finance.
159 Updated daily from Citibank N.A., source in EUR. Information may be delayed.
160 This is parsed from an HTML page, so it may be broken at anytime.
161
162-The update can be set under the company form.
163+The update can be set under de company form.
164 You can set for each services which currency you want to update.
165-The logs of the update are visible under the service note.
166+The log of the update are visible under the service note.
167 You can active or deactivate the update.
168 The module uses internal ir_cron feature from OpenERP, so the job is launched once
169 the server starts if the 'first execute date' is before the current day.
170-The module supports multi-company currency in two ways:
171-
172-* the currencies are shared, you can set currency update only on one
173+The module supports multi-company currency in two way :
174+ the currencies are shared, you can set currency update only on one
175 company
176-* the currency are separated, you can set currency on every company
177+ the currency are separated, you can set currency on every company
178 separately
179-
180-A function field lets you know your currency configuration.
181+A function field let you know your currency configuration.
182
183 If in multi-company mode, the base currency will be the first company's currency
184 found in database.
185
186-Thanks to main contributors: Grzegorz Grzelak, Alexis de Lattre
187+
188+Special thanks and contribs to other Main contributor: Grzegorz Grzelak, Alexis de Lattre
189 """,
190- "depends" : ["base",
191- "account"], #Added to ensure account security groups are present
192+ "depends" : ["base", "account"],
193 "init_xml" : ["security/security.xml"],
194 "update_xml" : [
195 "currency_rate_update.xml",
196
197=== modified file 'currency_rate_update/company.py'
198--- currency_rate_update/company.py 2012-02-03 13:53:02 +0000
199+++ currency_rate_update/company.py 2013-09-17 18:13:12 +0000
200@@ -1,50 +1,48 @@
201 # -*- encoding: utf-8 -*-
202 # company.py
203 # c2c_currency_update
204-# @author Nicolas Bessi
205+# @author Nicolas Bessi
206 # Copyright (c) 2009 CamptoCamp. All rights reserved.
207-##############################################################################
208-#
209-# WARNING: This program as such is intended to be used by professional
210-# programmers who take the whole responsability of assessing all potential
211-# consequences resulting from its eventual inadequacies and bugs
212-# End users who are looking for a ready-to-use solution with commercial
213-# garantees and support are strongly adviced to contract a Free Software
214-# Service Company
215-#
216-# This program is Free Software; you can redistribute it and/or
217-# modify it under the terms of the GNU General Public License
218-# as published by the Free Software Foundation; either version 2
219-# of the License, or (at your option) any later version.
220-#
221-# This program is distributed in the hope that it will be useful,
222-# but WITHOUT ANY WARRANTY; without even the implied warranty of
223-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
224-# GNU General Public License for more details.
225-#
226-# You should have received a copy of the GNU General Public License
227-# along with this program; if not, write to the Free Software
228-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
229+#
230+# WARNING: This program as such is intended to be used by professional
231+# programmers who take the whole responsability of assessing all potential
232+# consequences resulting from its eventual inadequacies and bugs
233+# End users who are looking for a ready-to-use solution with commercial
234+# garantees and support are strongly adviced to contract a Free Software
235+# Service Company
236+#
237+# This program is free software: you can redistribute it and/or modify
238+# it under the terms of the GNU Affero General Public License as
239+# published by the Free Software Foundation, either version 3 of the
240+# License, or (at your option) any later version.
241+#
242+# This program is distributed in the hope that it will be useful,
243+# but WITHOUT ANY WARRANTY; without even the implied warranty of
244+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
245+# GNU Affero General Public License for more details.
246+#
247+# You should have received a copy of the GNU Affero General Public License
248+# along with this program. If not, see <http://www.gnu.org/licenses/>.
249 #
250 ##############################################################################
251
252 import netsvc
253 from osv import fields, osv
254 class res_company(osv.osv):
255- """override company to add currency update"""
256-
257+ """Override company to add currency update"""
258+
259 def _multi_curr_enable(self, cr, uid, ids, field_name, arg, context={}):
260 "check if multi company currency is enabled"
261 result = {}
262- if self.pool.get('ir.model.fields').search(cr, uid, [('name', '=', 'company_id'), ('model', '=', 'res.currency')])==[]:
263+ if self.pool.get('ir.model.fields').search(cr, uid, [('name', '=', 'company_id'), ('model', '=', 'res.currency')]) == []:
264 enable = 0
265 else:
266 enable = 1
267 for id in ids:
268 result[id] = enable
269 return result
270-
271-
272+
273+
274 def button_refresh_currency(self, cr, uid, ids, context=None):
275 """Refrech the currency !!for all the company
276 now"""
277@@ -54,8 +52,8 @@
278 except Exception, e:
279 return False
280 return True
281-
282-
283+
284+
285 def on_change_auto_currency_up(self, cr, uid, id, value):
286 """handle the activation of the currecny update on compagnies.
287 There are two ways of implementing multi_company currency,
288@@ -65,24 +63,24 @@
289 object running.
290 If yours currency are not share you will be able to activate the
291 auto update on each separated company"""
292-
293+
294 if len(id) :
295 id = id[0]
296 else :
297 return {}
298 enable = self.browse(cr, uid, id).multi_company_currency_enable
299- compagnies = self.search(cr, uid, [])
300+ compagnies = self.search(cr, uid, [])
301 activate_cron = 'f'
302 if not value :
303 # this statement is here beacaus we do no want to save in case of error
304- self.write(cr, uid, id,{'auto_currency_up':value})
305+ self.write(cr, uid, id, {'auto_currency_up':value})
306 for comp in compagnies :
307- if self.browse(cr, uid, comp).auto_currency_up:
308+ if self.browse(cr, uid, comp).auto_currency_up:
309 activate_cron = 't'
310 break
311 self.pool.get('currency.rate.update').save_cron(
312- cr,
313- uid,
314+ cr,
315+ uid,
316 {'active':activate_cron}
317 )
318 return {}
319@@ -90,75 +88,75 @@
320 for comp in compagnies :
321 if comp != id and not enable:
322 if self.browse(cr, uid, comp).multi_company_currency_enable:
323- #we ensure taht we did not have write a true value
324- self.write(cr, uid, id,{'auto_currency_up':False})
325+ # we ensure taht we did not have write a true value
326+ self.write(cr, uid, id, {'auto_currency_up':False})
327 return {
328- 'value':{
329+ 'value':{
330 'auto_currency_up':False
331 },
332-
333+
334 'warning':{
335 'title':"Warning",
336- 'message': 'Yon can not activate auto currency '+\
337- 'update on more thant one company with this '+
338+ 'message': 'Yon can not activate auto currency ' + \
339+ 'update on more thant one company with this ' +
340 'multi company configuration'
341 }
342 }
343- self.write(cr, uid, id,{'auto_currency_up':value})
344+ self.write(cr, uid, id, {'auto_currency_up':value})
345 for comp in compagnies :
346- if self.browse(cr, uid, comp).auto_currency_up:
347+ if self.browse(cr, uid, comp).auto_currency_up:
348 activate_cron = 't'
349 self.pool.get('currency.rate.update').save_cron(
350- cr,
351- uid,
352+ cr,
353+ uid,
354 {'active':activate_cron}
355 )
356 break
357 return {}
358-
359-
360+
361+
362 def on_change_intervall(self, cr, uid, id, interval) :
363- ###Function that will update the cron
364- ###freqeuence
365+ # ##Function that will update the cron
366+ # ##freqeuence
367 self.pool.get('currency.rate.update').save_cron(
368- cr,
369- uid,
370+ cr,
371+ uid,
372 {'interval_type':interval}
373 )
374- compagnies = self.search(cr, uid, [])
375+ compagnies = self.search(cr, uid, [])
376 for comp in compagnies :
377- self.write(cr, uid, comp,{'interval_type':interval})
378+ self.write(cr, uid, comp, {'interval_type':interval})
379 return {}
380-
381+
382 _inherit = "res.company"
383 _columns = {
384- ### activate the currency update
385+ # ## activate the currency update
386 'auto_currency_up': fields.boolean('Automatical update of the currency this company'),
387 'services_to_use' : fields.one2many(
388- 'currency.rate.update.service',
389+ 'currency.rate.update.service',
390 'company_id',
391- 'Currency update services'
392+ 'Currency update services'
393 ),
394- ###predifine cron frequence
395+ # ##predifine cron frequence
396 'interval_type': fields.selection(
397 [
398- ('days','Day(s)'),
399- ('weeks', 'Week(s)'),
400+ ('days', 'Day(s)'),
401+ ('weeks', 'Week(s)'),
402 ('months', 'Month(s)')
403 ],
404 'Currency update frequence',
405 help="""changing this value will
406 also affect other compagnies"""
407 ),
408- ###function field that allows to know the
409- ###mutli company currency implementation
410+ # ##function field that allows to know the
411+ # ##mutli company currency implementation
412 'multi_company_currency_enable' : fields.function(
413- _multi_curr_enable,
414- method=True,
415- type='boolean',
416+ _multi_curr_enable,
417+ method=True,
418+ type='boolean',
419 string="Multi company currency",
420- help='if this case is not check you can'+\
421+ help='if this case is not check you can' + \
422 ' not set currency is active on two company'
423 ),
424- }
425+ }
426 res_company()
427
428=== modified file 'currency_rate_update/company_view.xml' (properties changed: +x to -x)
429=== modified file 'currency_rate_update/currency_rate_update.py' (properties changed: +x to -x)
430--- currency_rate_update/currency_rate_update.py 2012-04-23 12:19:50 +0000
431+++ currency_rate_update/currency_rate_update.py 2013-09-17 18:13:12 +0000
432@@ -2,8 +2,8 @@
433 ##############################################################################
434 #
435 # Copyright (c) 2009 Camptocamp SA
436-# @author Nicolas Bessi
437-# @source JBA and AWST inpiration
438+# @author Nicolas Bessi
439+# @source JBA and AWST inpiration
440 # @contributor Grzegorz Grzelak (grzegorz.grzelak@birdglobe.com), Joel Grand-Guillaume
441 # Copyright (c) 2010 Alexis de Lattre (alexis@via.ecp.fr)
442 # - ported XML-based webservices (Admin.ch, ECB, PL NBP) to new XML lib
443@@ -54,20 +54,19 @@
444 _name = "currency.rate.update.service"
445 _description = "Currency Rate Update"
446 _columns = {
447- ##list of webservicies the value sould be a class name
448- 'service' : fields.selection(
449+ # #list of webservicies the value sould be a class name
450+ 'service' : fields.selection(
451 [
452- ('Admin_ch_getter','Admin.ch'),
453- ('ECB_getter','European Central Bank'),
454- #('NYFB_getter','Federal Reserve Bank of NY'),
455- #('Google_getter','Google Finance'),
456- ('Yahoo_getter','Yahoo Finance '),
457- ('PL_NBP_getter','Narodowy Bank Polski'), # Added for polish rates
458+ ('Admin_ch_getter', 'Admin.ch'),
459+ ('ECB_getter', 'European Central Bank'),
460+ ('Yahoo_getter', 'Yahoo Finance '),
461+ ('PL_NBP_getter', 'Narodowy Bank Polski'), # Added for polish rates
462+ ('Banxico_getter', 'Banco de México'), # Added for mexican rates
463 ],
464 "Webservice to use",
465- required = True
466+ required=True
467 ),
468- ##list of currency to update
469+ # #list of currency to update
470 'currency_to_update' : fields.many2many(
471 'res.currency',
472 'res_curreny_auto_udate_rel',
473@@ -75,12 +74,12 @@
474 'currency_id',
475 'currency to update with this service',
476 ),
477- #back ref
478+ # back ref
479 'company_id' : fields.many2one(
480 'res.company',
481 'linked company',
482 ),
483- ##note fileds that will be used as a logger
484+ # #note fileds that will be used as a logger
485 'note':fields.text('update notice'),
486 'max_delta_days': fields.integer('Max delta days', required=True, help="If the time delta between the rate date given by the webservice and the current date exeeds this value, then the currency rate is not updated in OpenERP."),
487 }
488@@ -89,8 +88,8 @@
489 }
490 _sql_constraints = [
491 (
492- 'curr_service_unique',
493- 'unique (service, company_id)',
494+ 'curr_service_unique',
495+ 'unique (service, company_id)',
496 _('You can use a service one time per company !')
497 )
498 ]
499@@ -114,63 +113,63 @@
500 update currencies based on a web url"""
501 _name = "currency.rate.update"
502 _description = "Currency Rate Update"
503- ##dict that represent a cron object
504+ # #dict that represent a cron object
505 cron = {
506 'active' : False,
507 'priority' : 1,
508 'interval_number' : 1,
509 'interval_type' : 'weeks',
510- 'nextcall' : time.strftime("%Y-%m-%d %H:%M:%S", (datetime.today() + timedelta(days=1)).timetuple() ), #tomorrow same time
511- 'numbercall' : -1,
512+ 'nextcall' : time.strftime("%Y-%m-%d %H:%M:%S", (datetime.today() + timedelta(days=1)).timetuple()), # tomorrow same time
513+ 'numbercall' :-1,
514 'doall' : True,
515 'model' : 'currency.rate.update',
516 'function' : 'run_currency_update',
517- 'args' : '()',
518+ 'args' : '()',
519 }
520-
521- logger = netsvc.Logger()
522+
523+ logger = logging.getLogger(__name__)
524 LOG_NAME = 'cron-rates'
525- MOD_NAME = 'c2c_currency_rate_update: '
526+ MOD_NAME = 'currency_rate_update: '
527 def get_cron_id(self, cr, uid, context):
528 """return the updater cron's id. Create one if the cron does not exists """
529-
530+
531 cron_id = 0
532 cron_obj = self.pool.get('ir.cron')
533- try:
534- #find the cron that send messages
535+ try:
536+ # find the cron that send messages
537 cron_id = cron_obj.search(
538- cr,
539- uid,
540+ cr,
541+ uid,
542 [
543- ('function', 'ilike', self.cron['function']),
544+ ('function', 'ilike', self.cron['function']),
545 ('model', 'ilike', self.cron['model'])
546- ],
547+ ],
548 context={
549 'active_test': False
550- }
551+ }
552 )
553 cron_id = int(cron_id[0])
554- except Exception,e :
555+ except Exception, e :
556 self.logger.notifyChannel(
557- self.LOG_NAME,
558- netsvc.LOG_INFO,
559+ self.LOG_NAME,
560+ netsvc.LOG_INFO,
561 'warning cron not found one will be created'
562 )
563- pass # ignore if the cron is missing cause we are going to create it in db
564-
565- #the cron does not exists
566+ pass # ignore if the cron is missing cause we are going to create it in db
567+
568+ # the cron does not exists
569 if not cron_id :
570- #translate
571+ # translate
572 self.cron['name'] = _('Currency Rate Update')
573 cron_id = cron_obj.create(cr, uid, self.cron, context)
574-
575+
576 return cron_id
577-
578+
579 def save_cron(self, cr, uid, datas, context={}):
580 """save the cron config data should be a dict"""
581- #modify the cron
582- cron_id = self.get_cron_id(cr, uid, context)
583- result = self.pool.get('ir.cron').write(cr, uid, [cron_id], datas)
584+ # modify the cron
585+ cron_id = self.get_cron_id(cr, uid, context)
586+ result = self.pool.get('ir.cron').write(cr, uid, [cron_id], datas)
587
588 def run_currency_update(self, cr, uid):
589 "update currency at the given frequence"
590@@ -179,24 +178,24 @@
591 rate_obj = self.pool.get('res.currency.rate')
592 companies = self.pool.get('res.company').search(cr, uid, [])
593 for comp in self.pool.get('res.company').browse(cr, uid, companies):
594- ##the multi company currency can beset or no so we handle
595- ##the two case
596+ # #the multi company currency can beset or no so we handle
597+ # #the two case
598 if not comp.auto_currency_up :
599 continue
600- #we initialise the multi compnay search filter or not serach filter
601+ # we initialise the multi compnay search filter or not serach filter
602 search_filter = []
603 if comp.multi_company_currency_enable :
604- search_filter = [('company_id','=',comp.id)]
605- #we fetch the main currency. The main rate should be set at 1.00
606+ search_filter = [('company_id', '=', comp.id)]
607+ # we fetch the main currency. The main rate should be set at 1.00
608 main_curr = comp.currency_id.name
609 for service in comp.services_to_use :
610- print "comp.services_to_use =", comp.services_to_use
611+ logger.debug("comp.services_to_use = %s" % (comp.services_to_use))
612 note = service.note or ''
613 try :
614- ## we initalize the class that will handle the request
615- ## and return a dict of rate
616+ # # we initalize the class that will handle the request
617+ # # and return a dict of rate
618 getter = factory.register(service.service)
619- print "getter =", getter
620+ logger.debug("getter = %s" % (type(getter)))
621 curr_to_fetch = map(lambda x : x.name, service.currency_to_update)
622 res, log_info = getter.get_updated_currency(curr_to_fetch, main_curr, service.max_delta_days)
623 rate_name = time.strftime('%Y-%m-%d')
624@@ -215,27 +214,27 @@
625 'rate':res[curr.name],
626 'name': rate_name
627 }
628- rate_obj.create(
629+ rate_obj.create(
630 cr,
631 uid,
632 vals,
633 )
634-
635+
636 note = note + "\n%s currency updated. "\
637- %(datetime.strftime(datetime.today(), '%Y-%m-%d %H:%M:%S'))
638+ % (datetime.strftime(datetime.today(), '%Y-%m-%d %H:%M:%S'))
639 note = note + (log_info or '')
640 service.write({'note':note})
641 except Exception, e:
642 error_msg = note + "\n%s ERROR : %s"\
643- %(datetime.strftime(datetime.today(), '%Y-%m-%d %H:%M:%S'), str(e))
644+ % (datetime.strftime(datetime.today(), '%Y-%m-%d %H:%M:%S'), str(e))
645 self.logger.notifyChannel(self.LOG_NAME, netsvc.LOG_INFO, str(e))
646 service.write({'note':error_msg})
647-
648-
649+
650+
651 Currency_rate_update()
652
653-### Error Definition as specified in python 2.6 PEP
654-class AbstractClassError(Exception):
655+# ## Error Definition as specified in python 2.6 PEP
656+class AbstractClassError(Exception):
657 def __str__(self):
658 return 'Abstract Class'
659 def __repr__(self):
660@@ -247,25 +246,25 @@
661 def __repr__(self):
662 return 'Abstract Method'
663
664-class UnknowClassError(Exception):
665+class UnknowClassError(Exception):
666 def __str__(self):
667 return 'Unknown Class'
668 def __repr__(self):
669 return 'Unknown Class'
670-class UnsuportedCurrencyError(Exception):
671+class UnsuportedCurrencyError(Exception):
672 def __init__(self, value):
673 self.curr = value
674 def __str__(self):
675- return 'Unsupported currency '+self.curr
676+ return 'Unsupported currency ' + self.curr
677 def __repr__(self):
678- return 'Unsupported currency '+self.curr
679-
680-### end of error definition
681+ return 'Unsupported currency ' + self.curr
682+
683+# ## end of error definition
684 class Currency_getter_factory():
685 """Factory pattern class that will return
686 a currency getter class base on the name passed
687 to the register method"""
688- def register(self, class_name):
689+ def register(self, class_name):
690 allowed = [
691 'Admin_ch_getter',
692 'PL_NBP_getter',
693@@ -273,66 +272,67 @@
694 'NYFB_getter',
695 'Google_getter',
696 'Yahoo_getter',
697+ 'Banxico_getter'
698 ]
699 if class_name in allowed:
700 class_def = eval(class_name)
701 return class_def()
702 else :
703 raise UnknowClassError
704-
705+
706
707 class Curreny_getter_interface(object) :
708 "Abstract class of currency getter"
709-
710- #remove in order to have a dryer code
711+
712+ # remove in order to have a dryer code
713 # def __init__(self):
714- # raise AbstractClassError
715-
716+ # raise AbstractClassError
717+
718 log_info = " "
719-
720+
721 supported_currency_array = \
722 ['AFN', 'ALL', 'DZD', 'USD', 'USD', 'USD', 'EUR', 'AOA', 'XCD', 'XCD', 'ARS',
723-'AMD', 'AWG', 'AUD', 'EUR', 'AZN', 'EUR', 'BSD', 'BHD', 'EUR', 'BDT', 'BBD',
724-'XCD', 'BYR', 'EUR', 'BZD', 'XOF', 'BMD', 'BTN', 'INR', 'BOB', 'ANG', 'BAM',
725-'BWP', 'NOK', 'BRL', 'GBP', 'USD', 'USD', 'BND', 'BGN', 'XOF', 'MMK', 'BIF',
726-'XOF', 'USD', 'KHR', 'XAF', 'CAD', 'EUR', 'CVE', 'KYD', 'XAF', 'XAF', 'CLP',
727-'CNY', 'AUD', 'AUD', 'COP', 'XAF', 'KMF', 'XPF', 'XAF', 'CDF', 'NZD', 'CRC',
728-'HRK', 'CUP', 'ANG', 'EUR', 'CYP', 'CZK', 'DKK', 'DJF', 'XCD', 'DOP', 'EUR',
729-'XCD', 'IDR', 'USD', 'EGP', 'EUR', 'SVC', 'USD', 'GBP', 'XAF', 'ETB', 'ERN',
730-'EEK', 'ETB', 'EUR', 'FKP', 'DKK', 'FJD', 'EUR', 'EUR', 'EUR', 'XPF', 'XPF',
731-'EUR', 'XPF', 'XAF', 'GMD', 'GEL', 'EUR', 'GHS', 'GIP', 'XAU', 'GBP', 'EUR',
732-'DKK', 'XCD', 'XCD', 'EUR', 'USD', 'GTQ', 'GGP', 'GNF', 'XOF', 'GYD', 'HTG',
733-'USD', 'AUD', 'BAM', 'EUR', 'EUR', 'HNL', 'HKD', 'HUF', 'ISK', 'INR', 'IDR',
734-'XDR', 'IRR', 'IQD', 'EUR', 'IMP', 'ILS', 'EUR', 'JMD', 'NOK', 'JPY', 'JEP',
735-'JOD', 'KZT', 'AUD', 'KES', 'AUD', 'KPW', 'KRW', 'KWD', 'KGS', 'LAK', 'LVL',
736-'LBP', 'LSL', 'ZAR', 'LRD', 'LYD', 'CHF', 'LTL', 'EUR', 'MOP', 'MKD', 'MGA',
737-'EUR', 'MWK', 'MYR', 'MVR', 'XOF', 'EUR', 'MTL', 'FKP', 'USD', 'USD', 'EUR',
738-'MRO', 'MUR', 'EUR', 'AUD', 'MXN', 'USD', 'USD', 'EUR', 'MDL', 'EUR', 'MNT',
739-'EUR', 'XCD', 'MAD', 'MZN', 'MMK', 'NAD', 'ZAR', 'AUD', 'NPR', 'ANG', 'EUR',
740-'XCD', 'XPF', 'NZD', 'NIO', 'XOF', 'NGN', 'NZD', 'AUD', 'USD', 'NOK', 'OMR',
741-'PKR', 'USD', 'XPD', 'PAB', 'USD', 'PGK', 'PYG', 'PEN', 'PHP', 'NZD', 'XPT',
742-'PLN', 'EUR', 'STD', 'USD', 'QAR', 'EUR', 'RON', 'RUB', 'RWF', 'STD', 'ANG',
743-'MAD', 'XCD', 'SHP', 'XCD', 'XCD', 'EUR', 'XCD', 'EUR', 'USD', 'WST', 'EUR',
744-'SAR', 'SPL', 'XOF', 'RSD', 'SCR', 'SLL', 'XAG', 'SGD', 'ANG', 'ANG', 'EUR',
745-'EUR', 'SBD', 'SOS', 'ZAR', 'GBP', 'GBP', 'EUR', 'XDR', 'LKR', 'SDG', 'SRD',
746-'NOK', 'SZL', 'SEK', 'CHF', 'SYP', 'TWD', 'RUB', 'TJS', 'TZS', 'THB', 'IDR',
747-'TTD', 'XOF', 'NZD', 'TOP', 'TTD', 'TND', 'TRY', 'TMM', 'USD', 'TVD', 'UGX',
748-'UAH', 'AED', 'GBP', 'USD', 'USD', 'UYU', 'USD', 'UZS', 'VUV', 'EUR', 'VEB',
749+'AMD', 'AWG', 'AUD', 'EUR', 'AZN', 'EUR', 'BSD', 'BHD', 'EUR', 'BDT', 'BBD',
750+'XCD', 'BYR', 'EUR', 'BZD', 'XOF', 'BMD', 'BTN', 'INR', 'BOB', 'ANG', 'BAM',
751+'BWP', 'NOK', 'BRL', 'GBP', 'USD', 'USD', 'BND', 'BGN', 'XOF', 'MMK', 'BIF',
752+'XOF', 'USD', 'KHR', 'XAF', 'CAD', 'EUR', 'CVE', 'KYD', 'XAF', 'XAF', 'CLP',
753+'CNY', 'AUD', 'AUD', 'COP', 'XAF', 'KMF', 'XPF', 'XAF', 'CDF', 'NZD', 'CRC',
754+'HRK', 'CUP', 'ANG', 'EUR', 'CYP', 'CZK', 'DKK', 'DJF', 'XCD', 'DOP', 'EUR',
755+'XCD', 'IDR', 'USD', 'EGP', 'EUR', 'SVC', 'USD', 'GBP', 'XAF', 'ETB', 'ERN',
756+'EEK', 'ETB', 'EUR', 'FKP', 'DKK', 'FJD', 'EUR', 'EUR', 'EUR', 'XPF', 'XPF',
757+'EUR', 'XPF', 'XAF', 'GMD', 'GEL', 'EUR', 'GHS', 'GIP', 'XAU', 'GBP', 'EUR',
758+'DKK', 'XCD', 'XCD', 'EUR', 'USD', 'GTQ', 'GGP', 'GNF', 'XOF', 'GYD', 'HTG',
759+'USD', 'AUD', 'BAM', 'EUR', 'EUR', 'HNL', 'HKD', 'HUF', 'ISK', 'INR', 'IDR',
760+'XDR', 'IRR', 'IQD', 'EUR', 'IMP', 'ILS', 'EUR', 'JMD', 'NOK', 'JPY', 'JEP',
761+'JOD', 'KZT', 'AUD', 'KES', 'AUD', 'KPW', 'KRW', 'KWD', 'KGS', 'LAK', 'LVL',
762+'LBP', 'LSL', 'ZAR', 'LRD', 'LYD', 'CHF', 'LTL', 'EUR', 'MOP', 'MKD', 'MGA',
763+'EUR', 'MWK', 'MYR', 'MVR', 'XOF', 'EUR', 'MTL', 'FKP', 'USD', 'USD', 'EUR',
764+'MRO', 'MUR', 'EUR', 'AUD', 'MXN', 'USD', 'USD', 'EUR', 'MDL', 'EUR', 'MNT',
765+'EUR', 'XCD', 'MAD', 'MZN', 'MMK', 'NAD', 'ZAR', 'AUD', 'NPR', 'ANG', 'EUR',
766+'XCD', 'XPF', 'NZD', 'NIO', 'XOF', 'NGN', 'NZD', 'AUD', 'USD', 'NOK', 'OMR',
767+'PKR', 'USD', 'XPD', 'PAB', 'USD', 'PGK', 'PYG', 'PEN', 'PHP', 'NZD', 'XPT',
768+'PLN', 'EUR', 'STD', 'USD', 'QAR', 'EUR', 'RON', 'RUB', 'RWF', 'STD', 'ANG',
769+'MAD', 'XCD', 'SHP', 'XCD', 'XCD', 'EUR', 'XCD', 'EUR', 'USD', 'WST', 'EUR',
770+'SAR', 'SPL', 'XOF', 'RSD', 'SCR', 'SLL', 'XAG', 'SGD', 'ANG', 'ANG', 'EUR',
771+'EUR', 'SBD', 'SOS', 'ZAR', 'GBP', 'GBP', 'EUR', 'XDR', 'LKR', 'SDG', 'SRD',
772+'NOK', 'SZL', 'SEK', 'CHF', 'SYP', 'TWD', 'RUB', 'TJS', 'TZS', 'THB', 'IDR',
773+'TTD', 'XOF', 'NZD', 'TOP', 'TTD', 'TND', 'TRY', 'TMM', 'USD', 'TVD', 'UGX',
774+'UAH', 'AED', 'GBP', 'USD', 'USD', 'UYU', 'USD', 'UZS', 'VUV', 'EUR', 'VEB',
775 'VEF', 'VND', 'USD', 'USD', 'USD', 'XPF', 'MAD', 'YER', 'ZMK', 'ZWD']
776
777- ##updated currency this arry will contain the final result
778+ # #updated currency this arry will contain the final result
779 updated_currency = {}
780-
781+
782 def get_updated_currency(self, currency_array, main_currency, max_delta_days) :
783 """Interface method that will retrieve the currency
784 This function has to be reinplemented in child"""
785 raise AbstractMethodError
786-
787+
788 def validate_cur(self, currency) :
789 """Validate if the currency to update is supported"""
790 if currency not in self.supported_currency_array :
791- raise UnsuportedCurrencyError(currency)
792-
793+ raise UnsuportedCurrencyError(currency)
794+
795 def get_url(self, url):
796 """Return a string of a get url query"""
797 try:
798@@ -342,42 +342,43 @@
799 objfile.close()
800 return rawfile
801 except ImportError:
802- raise osv.except_osv('Error !', self.MOD_NAME+'Unable to import urllib !')
803+ raise osv.except_osv('Error !', self.MOD_NAME + 'Unable to import urllib !')
804 except IOError:
805- raise osv.except_osv('Error !', self.MOD_NAME+'Web Service does not exist !')
806+ raise osv.except_osv('Error !', self.MOD_NAME + 'Web Service does not exist !')
807
808 def check_rate_date(self, rate_date, max_delta_days):
809 """Check date constrains. WARN : rate_date must be of datetime type"""
810 days_delta = (datetime.today() - rate_date).days
811 if days_delta > max_delta_days:
812- raise Exception('The rate date from ECB (%s) is %d days away from today, which is over the limit (%d days). Rate not updated in OpenERP.'%(rate_date, days_delta, max_delta_days))
813+ raise Exception('The rate date from (%s) is %d days away from today, which is over the limit (%d days). Rate not updated in OpenERP.' % (rate_date, days_delta, max_delta_days))
814 # We always have a warning when rate_date <> today
815 rate_date_str = datetime.strftime(rate_date, '%Y-%m-%d')
816 if rate_date_str != datetime.strftime(datetime.today(), '%Y-%m-%d'):
817 self.log_info = "WARNING : the rate date from ECB (%s) is not today's date" % rate_date_str
818- netsvc.Logger().notifyChannel("rate_update", netsvc.LOG_WARNING, "the rate date from ECB (%s) is not today's date" % rate_date_str)
819-
820-
821-#Yahoo ###################################################################################
822+ logger = logging.getLogger(__name__)
823+ logger.warning("the rate date from ECB (%s) is not today's date" % rate_date_str)
824+
825+
826+#Yahoo ###################################################################################
827 class Yahoo_getter(Curreny_getter_interface) :
828 """Implementation of Currency_getter_factory interface
829 for Yahoo finance service"""
830-
831+
832 def get_updated_currency(self, currency_array, main_currency, max_delta_days):
833 """implementation of abstract method of Curreny_getter_interface"""
834 self.validate_cur(main_currency)
835- url='http://download.finance.yahoo.com/d/quotes.txt?s="%s"=X&f=sl1c1abg'
836+ url = 'http://download.finance.yahoo.com/d/quotes.txt?s="%s"=X&f=sl1c1abg'
837 if main_currency in currency_array :
838 currency_array.remove(main_currency)
839 for curr in currency_array :
840 self.validate_cur(curr)
841- res = self.get_url(url%(main_currency+curr))
842+ res = self.get_url(url % (main_currency + curr))
843 val = res.split(',')[1]
844 if val :
845 self.updated_currency[curr] = val
846 else :
847- raise Exception('Could not update the %s'%(curr))
848-
849+ raise Exception('Could not update the %s' % (curr))
850+
851 return self.updated_currency, self.log_info # empty string added by polish changes
852 ##Admin CH ############################################################################
853 class Admin_ch_getter(Curreny_getter_interface) :
854@@ -388,35 +389,35 @@
855 """ Parse a dom node to retrieve-
856 currencies data"""
857 res = {}
858- xpath_rate_currency = "/def:wechselkurse/def:devise[@code='%s']/def:kurs/text()"%(curr.lower())
859- xpath_rate_ref = "/def:wechselkurse/def:devise[@code='%s']/def:waehrung/text()"%(curr.lower())
860+ xpath_rate_currency = "/def:wechselkurse/def:devise[@code='%s']/def:kurs/text()" % (curr.lower())
861+ xpath_rate_ref = "/def:wechselkurse/def:devise[@code='%s']/def:waehrung/text()" % (curr.lower())
862 res['rate_currency'] = float(dom.xpath(xpath_rate_currency, namespaces=ns)[0])
863 res['rate_ref'] = float((dom.xpath(xpath_rate_ref, namespaces=ns)[0]).split(' ')[0])
864 return res
865
866 def get_updated_currency(self, currency_array, main_currency, max_delta_days):
867 """implementation of abstract method of Curreny_getter_interface"""
868- url='http://www.afd.admin.ch/publicdb/newdb/mwst_kurse/wechselkurse.php'
869- #we do not want to update the main currency
870+ url = 'http://www.afd.admin.ch/publicdb/newdb/mwst_kurse/wechselkurse.php'
871+ # we do not want to update the main currency
872 if main_currency in currency_array :
873 currency_array.remove(main_currency)
874 # Move to new XML lib cf Launchpad bug #645263
875 from lxml import etree
876- logger = netsvc.Logger()
877- logger.notifyChannel("rate_update", netsvc.LOG_DEBUG, "Admin.ch currency rate service : connecting...")
878+ logger = logging.getLogger(__name__)
879+ logger.debug("Admin.ch currency rate service : connecting...")
880 rawfile = self.get_url(url)
881 dom = etree.fromstring(rawfile)
882- logger.notifyChannel("rate_update", netsvc.LOG_DEBUG, "Admin.ch sent a valid XML file")
883+ logger.debug("Admin.ch sent a valid XML file")
884 adminch_ns = {'def': 'http://www.afd.admin.ch/publicdb/newdb/mwst_kurse'}
885 rate_date = dom.xpath('/def:wechselkurse/def:datum/text()', namespaces=adminch_ns)[0]
886 rate_date_datetime = datetime.strptime(rate_date, '%Y-%m-%d')
887 self.check_rate_date(rate_date_datetime, max_delta_days)
888- #we dynamically update supported currencies
889+ # we dynamically update supported currencies
890 self.supported_currency_array = dom.xpath("/def:wechselkurse/def:devise/@code", namespaces=adminch_ns)
891 self.supported_currency_array = [x.upper() for x in self.supported_currency_array]
892 self.supported_currency_array.append('CHF')
893
894- logger.notifyChannel("rate_update", netsvc.LOG_DEBUG, "Supported currencies = " + str(self.supported_currency_array))
895+ logger.debug("Supported currencies = %s" % str(self.supported_currency_array))
896 self.validate_cur(main_currency)
897 if main_currency != 'CHF':
898 main_curr_data = self.rate_retrieve(dom, adminch_ns, main_currency)
899@@ -434,7 +435,7 @@
900 else :
901 rate = main_rate * curr_data['rate_ref'] / curr_data['rate_currency']
902 self.updated_currency[curr] = rate
903- logger.notifyChannel("rate_update", netsvc.LOG_DEBUG, "Rate retrieved : 1 " + main_currency + ' = ' + str(rate) + ' ' + curr)
904+ logger.debug("Rate retrieved : 1 " + main_currency + ' = ' + str(rate) + ' ' + curr)
905 return self.updated_currency, self.log_info
906
907 ## ECB getter ############################################################################
908@@ -447,36 +448,36 @@
909 """ Parse a dom node to retrieve-
910 currencies data"""
911 res = {}
912- xpath_curr_rate = "/gesmes:Envelope/def:Cube/def:Cube/def:Cube[@currency='%s']/@rate"%(curr.upper())
913+ xpath_curr_rate = "/gesmes:Envelope/def:Cube/def:Cube/def:Cube[@currency='%s']/@rate" % (curr.upper())
914 res['rate_currency'] = float(dom.xpath(xpath_curr_rate, namespaces=ns)[0])
915 return res
916
917 def get_updated_currency(self, currency_array, main_currency, max_delta_days):
918 """implementation of abstract method of Curreny_getter_interface"""
919- url='http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'
920+ url = 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'
921 # Important : as explained on the ECB web site, the currencies are
922 # at the beginning of the afternoon ; so, until 3 p.m. Paris time
923 # the currency rates are the ones of trading day N-1
924 # see http://www.ecb.europa.eu/stats/exchange/eurofxref/html/index.en.html
925
926- #we do not want to update the main currency
927+ # we do not want to update the main currency
928 if main_currency in currency_array :
929 currency_array.remove(main_currency)
930 # Move to new XML lib cf Launchpad bug #645263
931 from lxml import etree
932- logger = netsvc.Logger()
933- logger.notifyChannel("rate_update", netsvc.LOG_DEBUG, "ECB currency rate service : connecting...")
934+ logger = logging.getLogger(__name__)
935+ logger.debug("ECB currency rate service : connecting...")
936 rawfile = self.get_url(url)
937 dom = etree.fromstring(rawfile)
938- logger.notifyChannel("rate_update", netsvc.LOG_DEBUG, "ECB sent a valid XML file")
939+ logger.debug("ECB sent a valid XML file")
940 ecb_ns = {'gesmes': 'http://www.gesmes.org/xml/2002-08-01', 'def': 'http://www.ecb.int/vocabulary/2002-08-01/eurofxref'}
941 rate_date = dom.xpath('/gesmes:Envelope/def:Cube/def:Cube/@time', namespaces=ecb_ns)[0]
942 rate_date_datetime = datetime.strptime(rate_date, '%Y-%m-%d')
943 self.check_rate_date(rate_date_datetime, max_delta_days)
944- #we dynamically update supported currencies
945+ # we dynamically update supported currencies
946 self.supported_currency_array = dom.xpath("/gesmes:Envelope/def:Cube/def:Cube/def:Cube/@currency", namespaces=ecb_ns)
947 self.supported_currency_array.append('EUR')
948- logger.notifyChannel("rate_update", netsvc.LOG_DEBUG, "Supported currencies = " + str(self.supported_currency_array))
949+ logger.debug("Supported currencies = %s" % str(self.supported_currency_array))
950 self.validate_cur(main_currency)
951 if main_currency != 'EUR':
952 main_curr_data = self.rate_retrieve(dom, ecb_ns, main_currency)
953@@ -491,11 +492,11 @@
954 else:
955 rate = curr_data['rate_currency'] / main_curr_data['rate_currency']
956 self.updated_currency[curr] = rate
957- logger.notifyChannel("rate_update", netsvc.LOG_DEBUG, "Rate retrieved : 1 " + main_currency + ' = ' + str(rate) + ' ' + curr)
958+ logger.debug("Rate retrieved : 1 " + main_currency + ' = ' + str(rate) + ' ' + curr)
959 return self.updated_currency, self.log_info
960
961 ##PL NBP ############################################################################
962-class PL_NBP_getter(Curreny_getter_interface) : # class added according to polish needs = based on class Admin_ch_getter
963+class PL_NBP_getter(Curreny_getter_interface) : # class added according to polish needs = based on class Admin_ch_getter
964 """Implementation of Currency_getter_factory interface
965 for PL NBP service"""
966
967@@ -503,39 +504,33 @@
968 """ Parse a dom node to retrieve
969 currencies data"""
970 res = {}
971- xpath_rate_currency = "/tabela_kursow/pozycja[kod_waluty='%s']/kurs_sredni/text()"%(curr.upper())
972- xpath_rate_ref = "/tabela_kursow/pozycja[kod_waluty='%s']/przelicznik/text()"%(curr.upper())
973- res['rate_currency'] = float(dom.xpath(xpath_rate_currency, namespaces=ns)[0].replace(',','.'))
974+ xpath_rate_currency = "/tabela_kursow/pozycja[kod_waluty='%s']/kurs_sredni/text()" % (curr.upper())
975+ xpath_rate_ref = "/tabela_kursow/pozycja[kod_waluty='%s']/przelicznik/text()" % (curr.upper())
976+ res['rate_currency'] = float(dom.xpath(xpath_rate_currency, namespaces=ns)[0].replace(',', '.'))
977 res['rate_ref'] = float(dom.xpath(xpath_rate_ref, namespaces=ns)[0])
978 return res
979
980 def get_updated_currency(self, currency_array, main_currency, max_delta_days):
981 """implementation of abstract method of Curreny_getter_interface"""
982- url='http://www.nbp.pl/kursy/xml/LastA.xml' # LastA.xml is always the most recent one
983- #we do not want to update the main currency
984+ url = 'http://www.nbp.pl/kursy/xml/LastA.xml' # LastA.xml is always the most recent one
985+ # we do not want to update the main currency
986 if main_currency in currency_array :
987 currency_array.remove(main_currency)
988 # Move to new XML lib cf Launchpad bug #645263
989 from lxml import etree
990- logger = netsvc.Logger()
991- logger.notifyChannel("rate_update", netsvc.LOG_DEBUG, "NBP.pl currency rate service : connecting...")
992+ logger = logging.getLogger(__name__)
993+ logger.debug("NBP.pl currency rate service : connecting...")
994 rawfile = self.get_url(url)
995- dom = etree.fromstring(rawfile) # If rawfile is not XML, it crashes here
996- ns = {} # Cool, there are no namespaces !
997- logger.notifyChannel("rate_update", netsvc.LOG_DEBUG, "NBP.pl sent a valid XML file")
998- #node = xpath.Evaluate("/tabela_kursow", dom) # BEGIN Polish - rates table name
999- #if isinstance(node, list) :
1000- # node = node[0]
1001- #self.log_info = node.getElementsByTagName('numer_tabeli')[0].childNodes[0].data
1002- #self.log_info = self.log_info + " " + node.getElementsByTagName('data_publikacji')[0].childNodes[0].data # END Polish - rates table name
1003-
1004+ dom = etree.fromstring(rawfile) # If rawfile is not XML, it crashes here
1005+ ns = {} # Cool, there are no namespaces !
1006+ logger.debug("NBP.pl sent a valid XML file")
1007 rate_date = dom.xpath('/tabela_kursow/data_publikacji/text()', namespaces=ns)[0]
1008 rate_date_datetime = datetime.strptime(rate_date, '%Y-%m-%d')
1009 self.check_rate_date(rate_date_datetime, max_delta_days)
1010- #we dynamically update supported currencies
1011+ # we dynamically update supported currencies
1012 self.supported_currency_array = dom.xpath('/tabela_kursow/pozycja/kod_waluty/text()', namespaces=ns)
1013 self.supported_currency_array.append('PLN')
1014- logger.notifyChannel("rate_update", netsvc.LOG_DEBUG, "Supported currencies = " + str(self.supported_currency_array))
1015+ logger.debug("Supported currencies = %s" % str(self.supported_currency_array))
1016 self.validate_cur(main_currency)
1017 if main_currency != 'PLN':
1018 main_curr_data = self.rate_retrieve(dom, ns, main_currency)
1019@@ -553,5 +548,59 @@
1020 else:
1021 rate = main_rate * curr_data['rate_ref'] / curr_data['rate_currency']
1022 self.updated_currency[curr] = rate
1023- logger.notifyChannel("rate_update", netsvc.LOG_DEBUG, "Rate retrieved : 1 " + main_currency + ' = ' + str(rate) + ' ' + curr)
1024+ logger.debug("Rate retrieved : 1 " + main_currency + ' = ' + str(rate) + ' ' + curr)
1025+ return self.updated_currency, self.log_info
1026+
1027+##Banco de México ############################################################################
1028+class Banxico_getter(Curreny_getter_interface) : # class added for Mexico rates
1029+ """Implementation of Currency_getter_factory interface
1030+ for Banco de México service"""
1031+
1032+ def rate_retrieve(self):
1033+ """ Get currency exchange from Banxico.xml and proccess it
1034+ TODO: Get correct data from xml instead of process string
1035+ """
1036+ url = 'http://www.banxico.org.mx/rsscb/rss?BMXC_canal=pagos&BMXC_idioma=es'
1037+
1038+ from xml.dom.minidom import parse
1039+ from StringIO import StringIO
1040+
1041+ logger = logging.getLogger(__name__)
1042+ logger.debug("Banxico currency rate service : connecting...")
1043+ rawfile = self.get_url(url)
1044+
1045+ dom = parse(StringIO(rawfile))
1046+ logger.debug("Banxico sent a valid XML file")
1047+
1048+ value = dom.getElementsByTagName('cb:value')[0]
1049+ rate = value.firstChild.nodeValue
1050+
1051+ return float(rate)
1052+
1053+
1054+ def get_updated_currency(self, currency_array, main_currency, max_delta_days=1):
1055+ """implementation of abstract method of Curreny_getter_interface"""
1056+ logger = logging.getLogger(__name__)
1057+ # we do not want to update the main currency
1058+ if main_currency in currency_array :
1059+ currency_array.remove(main_currency)
1060+
1061+ # Suported currencies
1062+ suported = ['MXN', 'USD']
1063+ for curr in currency_array :
1064+ if curr in suported:
1065+ # Get currency data
1066+ main_rate = self.rate_retrieve()
1067+ if main_currency == 'MXN':
1068+ rate = 1 / main_rate
1069+ else:
1070+ rate = main_rate
1071+ else:
1072+ """ No other currency supported
1073+ """
1074+ continue
1075+
1076+ self.updated_currency[curr] = rate
1077+ logger.debug("Rate retrieved : " + main_currency + ' = ' + str(rate) + ' ' + curr)
1078+
1079 return self.updated_currency, self.log_info
1080
1081=== modified file 'currency_rate_update/currency_rate_update.xml' (properties changed: +x to -x)
1082--- currency_rate_update/currency_rate_update.xml 2011-08-12 12:35:23 +0000
1083+++ currency_rate_update/currency_rate_update.xml 2013-09-17 18:13:12 +0000
1084@@ -9,7 +9,7 @@
1085 <tree string="Rates">
1086 <field name="service"/>
1087 <field name="currency_to_update"/>
1088- <field name="company_id"/>
1089+ <field name="company_id" groups="base.group_multi_company"/>
1090
1091 </tree>
1092 </field>
1093@@ -22,7 +22,7 @@
1094 <field name="arch" type="xml">
1095 <form string="Rate">
1096 <field name="service"/>
1097- <field name="company_id"/>
1098+ <field name="company_id" groups="base.group_multi_company"/>
1099 <field name="max_delta_days"/>
1100 <separator string="Currencies to update with this service" colspan="4"/>
1101 <field name="currency_to_update" colspan="4" nolabel="1"/>
1102@@ -33,4 +33,4 @@
1103 </record>
1104
1105 </data>
1106-</openerp>
1107+</openerp>
1108\ No newline at end of file
1109
1110=== modified file 'currency_rate_update/security/security.xml' (properties changed: +x to -x)

Subscribers

People subscribed via source and target branches