[MERGE] base: raise an exception if the format of the bank account is wrong
[odoo/odoo.git] / openerp / addons / base / res / res_company.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
22 from osv import osv
23 from osv import fields
24 import os
25 import tools
26 import openerp
27 from openerp import SUPERUSER_ID
28 from tools.translate import _
29 from tools.safe_eval import safe_eval as eval
30
31 class multi_company_default(osv.osv):
32     """
33     Manage multi company default value
34     """
35     _name = 'multi_company.default'
36     _description = 'Default multi company'
37     _order = 'company_id,sequence,id'
38
39     _columns = {
40         'sequence': fields.integer('Sequence'),
41         'name': fields.char('Name', size=256, required=True, help='Name it to easily find a record'),
42         'company_id': fields.many2one('res.company', 'Main Company', required=True,
43             help='Company where the user is connected'),
44         'company_dest_id': fields.many2one('res.company', 'Default Company', required=True,
45             help='Company to store the current record'),
46         'object_id': fields.many2one('ir.model', 'Object', required=True,
47             help='Object affected by this rule'),
48         'expression': fields.char('Expression', size=256, required=True,
49             help='Expression, must be True to match\nuse context.get or user (browse)'),
50         'field_id': fields.many2one('ir.model.fields', 'Field', help='Select field property'),
51     }
52
53     _defaults = {
54         'expression': lambda *a: 'True',
55         'sequence': lambda *a: 100,
56     }
57
58     def copy(self, cr, uid, id, default=None, context=None):
59         """
60         Add (copy) in the name when duplicate record
61         """
62         if not context:
63             context = {}
64         if not default:
65             default = {}
66         company = self.browse(cr, uid, id, context=context)
67         default = default.copy()
68         default['name'] = company.name + _(' (copy)')
69         return super(multi_company_default, self).copy(cr, uid, id, default, context=context)
70
71 multi_company_default()
72
73 class res_company(osv.osv):
74     _name = "res.company"
75     _description = 'Companies'
76     _order = 'name'
77
78     def _get_address_data(self, cr, uid, ids, field_names, arg, context=None):
79         """ Read the 'address' functional fields. """
80         result = {}
81         part_obj = self.pool.get('res.partner')
82         for company in self.browse(cr, uid, ids, context=context):
83             result[company.id] = {}.fromkeys(field_names, False)
84             if company.partner_id:
85                 address_data = part_obj.address_get(cr, openerp.SUPERUSER_ID, [company.partner_id.id], adr_pref=['default'])
86                 if address_data['default']:
87                     address = part_obj.read(cr, openerp.SUPERUSER_ID, address_data['default'], field_names, context=context)
88                     for field in field_names:
89                         result[company.id][field] = address[field] or False
90         return result
91
92     def _set_address_data(self, cr, uid, company_id, name, value, arg, context=None):
93         """ Write the 'address' functional fields. """
94         company = self.browse(cr, uid, company_id, context=context)
95         if company.partner_id:
96             part_obj = self.pool.get('res.partner')
97             address_data = part_obj.address_get(cr, uid, [company.partner_id.id], adr_pref=['default'])
98             address = address_data['default']
99             if address:
100                 part_obj.write(cr, uid, [address], {name: value or False})
101             else:
102                 part_obj.create(cr, uid, {name: value or False, 'parent_id': company.partner_id.id}, context=context)
103         return True
104
105     _columns = {
106         'name': fields.related('partner_id', 'name', string='Company Name', size=128, required=True, store=True, type='char'),
107         'parent_id': fields.many2one('res.company', 'Parent Company', select=True),
108         'child_ids': fields.one2many('res.company', 'parent_id', 'Child Companies'),
109         'partner_id': fields.many2one('res.partner', 'Partner', required=True),
110         'rml_header': fields.text('RML Header', required=True),
111         'rml_header1': fields.char('Company Slogan', size=200, help="Appears by default on the top right corner of your printed documents (report header)."),
112         'rml_header2': fields.text('RML Internal Header', required=True),
113         'rml_header3': fields.text('RML Internal Header for Landscape Reports', required=True),
114         'rml_footer': fields.text('Report Footer', help="Footer text displayed at the bottom of all reports. Automatically set based on company details, "\
115                                   "but may also be customized by directly editing it."),
116         'custom_footer': fields.boolean('Custom Footer', help="Check this to define the report footer manually.  Otherwise it will be filled in automatically."),
117         'logo': fields.related('partner_id', 'image', string="Logo", type="binary"),
118         'currency_id': fields.many2one('res.currency', 'Currency', required=True),
119         'currency_ids': fields.one2many('res.currency', 'company_id', 'Currency'),
120         'user_ids': fields.many2many('res.users', 'res_company_users_rel', 'cid', 'user_id', 'Accepted Users'),
121         'account_no':fields.char('Account No.', size=64),
122         'street': fields.function(_get_address_data, fnct_inv=_set_address_data, size=128, type='char', string="Street", multi='address'),
123         'street2': fields.function(_get_address_data, fnct_inv=_set_address_data, size=128, type='char', string="Street2", multi='address'),
124         'zip': fields.function(_get_address_data, fnct_inv=_set_address_data, size=24, type='char', string="Zip", multi='address'),
125         'city': fields.function(_get_address_data, fnct_inv=_set_address_data, size=24, type='char', string="City", multi='address'),
126         'state_id': fields.function(_get_address_data, fnct_inv=_set_address_data, type='many2one', domain="[('country_id', '=', country_id)]", relation='res.country.state', string="Fed. State", multi='address'),
127         'bank_ids': fields.one2many('res.partner.bank','company_id', 'Bank Accounts', help='Bank accounts related to this company'),
128         'country_id': fields.function(_get_address_data, fnct_inv=_set_address_data, type='many2one', relation='res.country', string="Country", multi='address'),
129         'email': fields.function(_get_address_data, fnct_inv=_set_address_data, size=64, type='char', string="Email", multi='address'),
130         'phone': fields.function(_get_address_data, fnct_inv=_set_address_data, size=64, type='char', string="Phone", multi='address'),
131         'fax': fields.function(_get_address_data, fnct_inv=_set_address_data, size=64, type='char', string="Fax", multi='address'),
132         'website': fields.related('partner_id', 'website', string="Website", type="char", size=64),
133         'vat': fields.related('partner_id', 'vat', string="Tax ID", type="char", size=32),
134         'company_registry': fields.char('Company Registry', size=64),
135         'paper_format': fields.selection([('a4', 'A4'), ('us_letter', 'US Letter')], "Paper Format", required=True),
136     }
137     _sql_constraints = [
138         ('name_uniq', 'unique (name)', 'The company name must be unique !')
139     ]
140
141     def onchange_footer(self, cr, uid, ids, context=None):
142         # when touched, the footer becomes custom
143         return {'value': {'custom_footer': True}}
144
145     def set_auto_footer(self, cr, uid, ids, context=None):
146         # unset the flag 'custom_footer'; this will automatically compute the footer
147         return self.write(cr, uid, ids, {'custom_footer': False}, context=context)
148
149     def compute_footer(self, cr, uid, ids, context=None):
150         res_partner_bank = self.pool.get('res.partner.bank')
151         for company in self.browse(cr, uid, ids, context):
152             if not company.custom_footer:
153                 # first line (notice that missing elements are filtered out before the join)
154                 res = ' | '.join(filter(bool, [
155                     company.phone            and '%s: %s' % (_('Phone'), company.phone),
156                     company.fax              and '%s: %s' % (_('Fax'), company.fax),
157                     company.email            and '%s: %s' % (_('Email'), company.email),
158                     company.website          and '%s: %s' % (_('Website'), company.website),
159                     company.vat              and '%s: %s' % (_('TIN'), company.vat),
160                     company.company_registry and '%s: %s' % (_('Reg'), company.company_registry),
161                 ]))
162                 # second line: bank accounts
163                 account_ids = [acc.id for acc in company.bank_ids if acc.footer]
164                 account_names = res_partner_bank.name_get(cr, uid, account_ids, context=context)
165                 if account_names:
166                     title = _('Bank Accounts') if len(account_names) > 1 else _('Bank Account')
167                     res += '\n%s: %s' % (title, ', '.join(name for id, name in account_names))
168                 # update footer
169                 self.write(cr, uid, [company.id], {'rml_footer': res}, context=context)
170         return True
171
172     def on_change_country(self, cr, uid, ids, country_id, context=None):
173         currency_id = self._get_euro(cr, uid, context=context)
174         if country_id:
175             currency_id = self.pool.get('res.country').browse(cr, uid, country_id, context=context).currency_id.id
176         return {'value': {'currency_id': currency_id}}
177
178     def _search(self, cr, uid, args, offset=0, limit=None, order=None,
179             context=None, count=False, access_rights_uid=None):
180         if context is None:
181             context = {}
182         if context.get('user_preference'):
183             # We browse as superuser. Otherwise, the user would be able to
184             # select only the currently visible companies (according to rules,
185             # which are probably to allow to see the child companies) even if
186             # she belongs to some other companies.
187             user = self.pool.get('res.users').browse(cr, SUPERUSER_ID, uid, context=context)
188             cmp_ids = list(set([user.company_id.id] + [cmp.id for cmp in user.company_ids]))
189             return cmp_ids
190         return super(res_company, self)._search(cr, uid, args, offset=offset, limit=limit, order=order,
191             context=context, count=count, access_rights_uid=access_rights_uid)
192
193     def _company_default_get(self, cr, uid, object=False, field=False, context=None):
194         """
195         Check if the object for this company have a default value
196         """
197         if not context:
198             context = {}
199         proxy = self.pool.get('multi_company.default')
200         args = [
201             ('object_id.model', '=', object),
202             ('field_id', '=', field),
203         ]
204
205         ids = proxy.search(cr, uid, args, context=context)
206         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
207         for rule in proxy.browse(cr, uid, ids, context):
208             if eval(rule.expression, {'context': context, 'user': user}):
209                 return rule.company_dest_id.id
210         return user.company_id.id
211
212     @tools.ormcache()
213     def _get_company_children(self, cr, uid=None, company=None):
214         if not company:
215             return []
216         ids =  self.search(cr, uid, [('parent_id','child_of',[company])])
217         return ids
218
219     def _get_partner_hierarchy(self, cr, uid, company_id, context=None):
220         if company_id:
221             parent_id = self.browse(cr, uid, company_id)['parent_id']
222             if parent_id:
223                 return self._get_partner_hierarchy(cr, uid, parent_id.id, context)
224             else:
225                 return self._get_partner_descendance(cr, uid, company_id, [], context)
226         return []
227
228     def _get_partner_descendance(self, cr, uid, company_id, descendance, context=None):
229         descendance.append(self.browse(cr, uid, company_id).partner_id.id)
230         for child_id in self._get_company_children(cr, uid, company_id):
231             if child_id != company_id:
232                 descendance = self._get_partner_descendance(cr, uid, child_id, descendance)
233         return descendance
234
235     #
236     # This function restart the cache on the _get_company_children method
237     #
238     def cache_restart(self, cr):
239         self._get_company_children.clear_cache(self)
240
241     def create(self, cr, uid, vals, context=None):
242         if not vals.get('name', False) or vals.get('partner_id', False):
243             self.cache_restart(cr)
244             return super(res_company, self).create(cr, uid, vals, context=context)
245         obj_partner = self.pool.get('res.partner')
246         partner_id = obj_partner.create(cr, uid, {'name': vals['name'], 'is_company':True}, context=context)
247         vals.update({'partner_id': partner_id})
248         self.cache_restart(cr)
249         company_id = super(res_company, self).create(cr, uid, vals, context=context)
250         obj_partner.write(cr, uid, partner_id, {'company_id': company_id}, context=context)
251         self.compute_footer(cr, uid, [company_id], context=context)
252         return company_id
253
254     def write(self, cr, uid, ids, values, context=None):
255         self.cache_restart(cr)
256         if isinstance(ids, (int, long)):
257             ids = [ids]
258         super(res_company, self).write(cr, uid, ids, values, context=context)
259         if 'rml_footer' not in values:
260             self.compute_footer(cr, uid, ids, context=context)
261         return True
262
263     def _get_euro(self, cr, uid, context=None):
264         rate_obj = self.pool.get('res.currency.rate')
265         rate_id = rate_obj.search(cr, uid, [('rate', '=', 1)], context=context)
266         return rate_id and rate_obj.browse(cr, uid, rate_id[0], context=context).currency_id.id or False
267
268     def _get_logo(self, cr, uid, ids):
269         return open(os.path.join( tools.config['root_path'], 'addons', 'base', 'res', 'res_company_logo.png'), 'rb') .read().encode('base64')
270
271     _header = """
272 <header>
273 <pageTemplate>
274     <frame id="first" x1="28.0" y1="28.0" width="%s" height="%s"/>
275     <pageGraphics>
276         <fill color="black"/>
277         <stroke color="black"/>
278         <setFont name="DejaVu Sans" size="8"/>
279         <drawString x="%s" y="%s"> [[ formatLang(time.strftime("%%Y-%%m-%%d"), date=True) ]]  [[ time.strftime("%%H:%%M") ]]</drawString>
280         <setFont name="DejaVu Sans Bold" size="10"/>
281         <drawCentredString x="%s" y="%s">[[ company.partner_id.name ]]</drawCentredString>
282         <stroke color="#000000"/>
283         <lines>%s</lines>
284     </pageGraphics>
285 </pageTemplate>
286 </header>"""
287
288     _header2 = _header % (539, 772, "1.0cm", "28.3cm", "11.1cm", "28.3cm", "1.0cm 28.1cm 20.1cm 28.1cm")
289
290     _header3 = _header % (786, 525, 25, 555, 440, 555, "25 550 818 550")
291
292     def _get_header(self,cr,uid,ids):
293         try :
294             header_file = tools.file_open(os.path.join('base', 'report', 'corporate_rml_header.rml'))
295             try:
296                 return header_file.read()
297             finally:
298                 header_file.close()
299         except:
300             return self._header_a4
301
302     _header_main = """
303 <header>
304     <pageTemplate>
305         <frame id="first" x1="1.3cm" y1="3.0cm" height="%s" width="19.0cm"/>
306          <stylesheet>
307             <paraStyle name="main_footer"  fontName="DejaVu Sans" fontSize="8.0" alignment="CENTER"/>
308          </stylesheet>
309         <pageGraphics>
310             <!-- You Logo - Change X,Y,Width and Height -->
311             <image x="1.3cm" y="%s" height="40.0" >[[ company.logo or removeParentNode('image') ]]</image>
312             <setFont name="DejaVu Sans" size="8"/>
313             <fill color="black"/>
314             <stroke color="black"/>
315
316             <!-- page header -->
317             <lines>1.3cm %s 20cm %s</lines>
318             <drawRightString x="20cm" y="%s">[[ company.rml_header1 ]]</drawRightString>
319             <drawString x="1.3cm" y="%s">[[ company.partner_id.name ]]</drawString>
320             <drawString x="1.3cm" y="%s">[[ company.partner_id.street or  '' ]]</drawString>
321             <drawString x="1.3cm" y="%s">[[ company.partner_id.city or '' ]] - [[ company.partner_id.country_id and company.partner_id.country_id.name  or '']]</drawString>
322             <drawString x="1.3cm" y="%s">Phone:</drawString>
323             <drawRightString x="7cm" y="%s">[[ company.partner_id.phone or '' ]]</drawRightString>
324             <drawString x="1.3cm" y="%s">Mail:</drawString>
325             <drawRightString x="7cm" y="%s">[[ company.partner_id.email or '' ]]</drawRightString>
326             <lines>1.3cm %s 7cm %s</lines>
327
328             <!-- left margin -->
329             <rotate degrees="90"/>
330             <fill color="grey"/>
331             <drawString x="2.65cm" y="-0.4cm">produced by OpenERP.com</drawString>
332             <fill color="black"/>
333             <rotate degrees="-90"/>
334
335             <!--page bottom-->
336             <lines>1.2cm 2.65cm 19.9cm 2.65cm</lines>
337             <place x="1.3cm" y="0cm" height="2.55cm" width="19.0cm">
338                 <para style="main_footer">[[ company.rml_footer ]]</para>
339                 <para style="main_footer">Contact : [[ user.name ]] - Page: <pageNumber/></para>
340             </place>
341         </pageGraphics>
342     </pageTemplate>
343 </header>"""
344
345     _header_a4 = _header_main % ('23.0cm', '27.6cm', '27.7cm', '27.7cm', '27.8cm', '27.2cm', '26.8cm', '26.4cm', '26.0cm', '26.0cm', '25.6cm', '25.6cm', '25.5cm', '25.5cm')
346     _header_letter = _header_main % ('21.3cm', '25.9cm', '26.0cm', '26.0cm', '26.1cm', '25.5cm', '25.1cm', '24.7cm', '24.3cm', '24.3cm', '23.9cm', '23.9cm', '23.8cm', '23.8cm')
347
348     def onchange_paper_format(self, cr, uid, ids, paper_format, context=None):
349         if paper_format == 'us_letter':
350             return {'value': {'rml_header': self._header_letter}}
351         return {'value': {'rml_header': self._header_a4}}
352
353     _defaults = {
354         'currency_id': _get_euro,
355         'paper_format': 'a4',
356         'rml_header':_get_header,
357         'rml_header2': _header2,
358         'rml_header3': _header3,
359         'logo':_get_logo
360     }
361
362     _constraints = [
363         (osv.osv._check_recursion, 'Error! You can not create recursive companies.', ['parent_id'])
364     ]
365
366
367 res_company()
368
369 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
370