[IMP] base, res.currency: fixes
[odoo/odoo.git] / openerp / addons / base / res / res_currency.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21 import time
22 import netsvc
23 from osv import fields, osv
24 import tools
25
26 from tools.misc import currency
27 from tools.translate import _
28
29 class res_currency(osv.osv):
30     def _current_rate(self, cr, uid, ids, name, arg, context=None):
31         if context is None:
32             context = {}
33         res = {}
34         if 'date' in context:
35             date = context['date']
36         else:
37             date = time.strftime('%Y-%m-%d')
38         date = date or time.strftime('%Y-%m-%d')
39         currency_rate_type = context.get('currency_rate_type_id', None)
40         operator = currency_rate_type and '=' or 'is'
41         for id in ids:
42             cr.execute("SELECT currency_id, rate FROM res_currency_rate WHERE currency_id = %s AND name <= %s AND currency_rate_type_id " + operator +" %s ORDER BY name desc LIMIT 1" ,(id, date, currency_rate_type))
43             if cr.rowcount:
44                 id, rate = cr.fetchall()[0]
45                 res[id] = rate
46             else:
47                 res[id] = 0
48         return res
49     _name = "res.currency"
50     _description = "Currency"
51     _columns = {
52         # Note: 'code' column was removed as of v6.0, the 'name' should now hold the ISO code.
53         'name': fields.char('Currency', size=32, required=True, help="Currency Code (ISO 4217)"),
54         'symbol': fields.char('Symbol', size=3, help="Currency sign, to be used when printing amounts."),
55         'rate': fields.function(_current_rate, method=True, string='Current Rate', digits=(12,6),
56             help='The rate of the currency to the currency of rate 1.'),
57         'rate_ids': fields.one2many('res.currency.rate', 'currency_id', 'Rates'),
58         'accuracy': fields.integer('Computational Accuracy'),
59         'rounding': fields.float('Rounding Factor', digits=(12,6)),
60         'active': fields.boolean('Active'),
61         'company_id':fields.many2one('res.company', 'Company'),
62         'date': fields.date('Date'),
63         'base': fields.boolean('Base')
64
65     }
66     _defaults = {
67         'active': lambda *a: 1,
68         'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'res.currency', context=c)
69     }
70     _order = "name"
71
72     def read(self, cr, user, ids, fields=None, context=None, load='_classic_read'):
73         currency_rate_obj=  self.pool.get('res.currency.rate')
74         res = super(osv.osv, self).read(cr, user, ids, fields, context, load)
75         for r in res:
76             if r.__contains__('rate_ids'):
77                 rates=r['rate_ids']
78                 if rates:
79                     currency_date = currency_rate_obj.read(cr, user, rates[0], ['name'])['name']
80                     r['date'] = currency_date
81         return res
82
83     def name_get(self, cr, uid, ids, context=None):
84         if not ids:
85             return []
86         if isinstance(ids, (int, long)):
87             ids = [ids]
88         reads = self.read(cr, uid, ids, ['name','symbol'], context=context, load='_classic_write')
89         return [(x['id'], tools.ustr(x['name']) + (x['symbol'] and (' (' + tools.ustr(x['symbol']) + ')') or '')) for x in reads]
90
91     def round(self, cr, uid, currency, amount):
92         if currency.rounding == 0:
93             return 0.0
94         else:
95             # /!\ First member below must be rounded to full unit!
96             # Do not pass a rounding digits value to round()
97             return round(amount / currency.rounding) * currency.rounding
98
99     def is_zero(self, cr, uid, currency, amount):
100         return abs(self.round(cr, uid, currency, amount)) < currency.rounding
101
102     def _get_conversion_rate(self, cr, uid, from_currency, to_currency, context=None):
103         if context is None:
104             context = {}
105         ctx = context.copy()
106         ctx.update({'currency_rate_type_id': ctx.get('currency_rate_type_from', None)})
107         from_currency = self.browse(cr, uid, from_currency.id, context=ctx)
108
109         ctx.update({'currency_rate_type_id': ctx.get('currency_rate_type_to', None)})
110         to_currency = self.browse(cr, uid, to_currency.id, context=ctx)
111
112         if from_currency.rate == 0 or to_currency.rate == 0:
113             date = context.get('date', time.strftime('%Y-%m-%d'))
114             if from_currency.rate == 0:
115                 currency_symbol = from_currency.symbol
116             else:
117                 currency_symbol = to_currency.symbol
118             raise osv.except_osv(_('Error'), _('No rate found \n' \
119                     'for the currency: %s \n' \
120                     'at the date: %s') % (currency_symbol, date))
121         return to_currency.rate/from_currency.rate
122
123     def compute(self, cr, uid, from_currency_id, to_currency_id, from_amount,
124                 round=True, currency_rate_type_from=False, currency_rate_type_to=False, context=None):
125         if not context:
126             context = {}
127         if not from_currency_id:
128             from_currency_id = to_currency_id
129         if not to_currency_id:
130             to_currency_id = from_currency_id
131         xc = self.browse(cr, uid, [from_currency_id,to_currency_id], context=context)
132         from_currency = (xc[0].id == from_currency_id and xc[0]) or xc[1]
133         to_currency = (xc[0].id == to_currency_id and xc[0]) or xc[1]
134         if (to_currency_id == from_currency_id) and (currency_rate_type_from == currency_rate_type_to):
135             if round:
136                 return self.round(cr, uid, to_currency, from_amount)
137             else:
138                 return from_amount
139         else:
140             context.update({'currency_rate_type_from': currency_rate_type_from, 'currency_rate_type_to': currency_rate_type_to})
141             rate = self._get_conversion_rate(cr, uid, from_currency, to_currency, context=context)
142             if round:
143                 return self.round(cr, uid, to_currency, from_amount * rate)
144             else:
145                 return (from_amount * rate)
146
147 res_currency()
148
149 class res_currency_rate_type(osv.osv):
150     _name = "res.currency.rate.type"
151     _description = "Currency Rate Type"
152     _columns = {
153         'name': fields.char('Name', size=64, required=True, translate=True),
154     }
155
156 res_currency_rate_type()
157
158 class res_currency_rate(osv.osv):
159     _name = "res.currency.rate"
160     _description = "Currency Rate"
161
162     _columns = {
163         'name': fields.date('Date', required=True, select=True),
164         'rate': fields.float('Rate', digits=(12,6), required=True,
165             help='The rate of the currency to the currency of rate 1'),
166         'currency_id': fields.many2one('res.currency', 'Currency', readonly=True),
167         'currency_rate_type_id': fields.many2one('res.currency.rate.type', 'Currency Rate Type', help="Allow you to define your own currency rate types, like 'Average' or 'Year to Date'. Leave empty if you simply want to use the normal 'spot' rate type"),
168     }
169     _defaults = {
170         'name': lambda *a: time.strftime('%Y-%m-%d'),
171     }
172     _order = "name desc"
173
174 res_currency_rate()
175
176 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
177