[MERGE] Forward-port of 7.0 fixes up to rev. 4961
[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 import os
23
24 import openerp
25 from openerp import SUPERUSER_ID, tools
26 from openerp.osv import fields, osv
27 from openerp.tools.translate import _
28 from openerp.tools.safe_eval import safe_eval as eval
29 from openerp.tools import image_resize_image
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': 'True',
55         'sequence': 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}, context=context)
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     def _get_logo_web(self, cr, uid, ids, _field_name, _args, context=None):
106         result = dict.fromkeys(ids, False)
107         for record in self.browse(cr, uid, ids, context=context):
108             size = (180, None)
109             result[record.id] = image_resize_image(record.partner_id.image, size)
110         return result
111
112     def _get_companies_from_partner(self, cr, uid, ids, context=None):
113         return self.pool['res.company'].search(cr, uid, [('partner_id', 'in', ids)], context=context)
114
115     _columns = {
116         'name': fields.related('partner_id', 'name', string='Company Name', size=128, required=True, store=True, type='char'),
117         'parent_id': fields.many2one('res.company', 'Parent Company', select=True),
118         'child_ids': fields.one2many('res.company', 'parent_id', 'Child Companies'),
119         'partner_id': fields.many2one('res.partner', 'Partner', required=True),
120         'rml_header': fields.text('RML Header', required=True),
121         'rml_header1': fields.char('Company Tagline', size=200, help="Appears by default on the top right corner of your printed documents (report header)."),
122         'rml_header2': fields.text('RML Internal Header', required=True),
123         'rml_header3': fields.text('RML Internal Header for Landscape Reports', required=True),
124         'rml_footer': fields.text('Report Footer', help="Footer text displayed at the bottom of all reports."),
125         'rml_footer_readonly': fields.related('rml_footer', type='text', string='Report Footer', readonly=True),
126         'custom_footer': fields.boolean('Custom Footer', help="Check this to define the report footer manually.  Otherwise it will be filled in automatically."),
127         'logo': fields.related('partner_id', 'image', string="Logo", type="binary"),
128         'logo_web': fields.function(_get_logo_web, string="Logo Web", type="binary", store={
129             'res.company': (lambda s, c, u, i, x: i, ['partner_id'], 10),
130             'res.partner': (_get_companies_from_partner, ['image'], 10),
131         }),
132         'currency_id': fields.many2one('res.currency', 'Currency', required=True),
133         'currency_ids': fields.one2many('res.currency', 'company_id', 'Currency'),
134         'user_ids': fields.many2many('res.users', 'res_company_users_rel', 'cid', 'user_id', 'Accepted Users'),
135         'account_no':fields.char('Account No.', size=64),
136         'street': fields.function(_get_address_data, fnct_inv=_set_address_data, size=128, type='char', string="Street", multi='address'),
137         'street2': fields.function(_get_address_data, fnct_inv=_set_address_data, size=128, type='char', string="Street2", multi='address'),
138         'zip': fields.function(_get_address_data, fnct_inv=_set_address_data, size=24, type='char', string="Zip", multi='address'),
139         'city': fields.function(_get_address_data, fnct_inv=_set_address_data, size=24, type='char', string="City", multi='address'),
140         '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'),
141         'bank_ids': fields.one2many('res.partner.bank','company_id', 'Bank Accounts', help='Bank accounts related to this company'),
142         'country_id': fields.function(_get_address_data, fnct_inv=_set_address_data, type='many2one', relation='res.country', string="Country", multi='address'),
143         'email': fields.function(_get_address_data, fnct_inv=_set_address_data, size=64, type='char', string="Email", multi='address'),
144         'phone': fields.function(_get_address_data, fnct_inv=_set_address_data, size=64, type='char', string="Phone", multi='address'),
145         'fax': fields.function(_get_address_data, fnct_inv=_set_address_data, size=64, type='char', string="Fax", multi='address'),
146         'website': fields.related('partner_id', 'website', string="Website", type="char", size=64),
147         'vat': fields.related('partner_id', 'vat', string="Tax ID", type="char", size=32),
148         'company_registry': fields.char('Company Registry', size=64),
149         'paper_format': fields.selection([('a4', 'A4'), ('us_letter', 'US Letter')], "Paper Format", required=True),
150     }
151     _sql_constraints = [
152         ('name_uniq', 'unique (name)', 'The company name must be unique !')
153     ]
154
155     def onchange_footer(self, cr, uid, ids, custom_footer, phone, fax, email, website, vat, company_registry, bank_ids, context=None):
156         if custom_footer:
157             return {}
158
159         # first line (notice that missing elements are filtered out before the join)
160         res = ' | '.join(filter(bool, [
161             phone            and '%s: %s' % (_('Phone'), phone),
162             fax              and '%s: %s' % (_('Fax'), fax),
163             email            and '%s: %s' % (_('Email'), email),
164             website          and '%s: %s' % (_('Website'), website),
165             vat              and '%s: %s' % (_('TIN'), vat),
166             company_registry and '%s: %s' % (_('Reg'), company_registry),
167         ]))
168         # second line: bank accounts
169         res_partner_bank = self.pool.get('res.partner.bank')
170         account_data = self.resolve_2many_commands(cr, uid, 'bank_ids', bank_ids, context=context)
171         account_names = res_partner_bank._prepare_name_get(cr, uid, account_data, context=context)
172         if account_names:
173             title = _('Bank Accounts') if len(account_names) > 1 else _('Bank Account')
174             res += '\n%s: %s' % (title, ', '.join(name for id, name in account_names))
175
176         return {'value': {'rml_footer': res, 'rml_footer_readonly': res}}
177
178     def on_change_country(self, cr, uid, ids, country_id, context=None):
179         currency_id = self._get_euro(cr, uid, context=context)
180         if country_id:
181             currency_id = self.pool.get('res.country').browse(cr, uid, country_id, context=context).currency_id.id
182         return {'value': {'currency_id': currency_id}}
183
184     def _search(self, cr, uid, args, offset=0, limit=None, order=None,
185             context=None, count=False, access_rights_uid=None):
186         if context is None:
187             context = {}
188         if context.get('user_preference'):
189             # We browse as superuser. Otherwise, the user would be able to
190             # select only the currently visible companies (according to rules,
191             # which are probably to allow to see the child companies) even if
192             # she belongs to some other companies.
193             user = self.pool.get('res.users').browse(cr, SUPERUSER_ID, uid, context=context)
194             cmp_ids = list(set([user.company_id.id] + [cmp.id for cmp in user.company_ids]))
195             return cmp_ids
196         return super(res_company, self)._search(cr, uid, args, offset=offset, limit=limit, order=order,
197             context=context, count=count, access_rights_uid=access_rights_uid)
198
199     def _company_default_get(self, cr, uid, object=False, field=False, context=None):
200         """
201         Check if the object for this company have a default value
202         """
203         if not context:
204             context = {}
205         proxy = self.pool.get('multi_company.default')
206         args = [
207             ('object_id.model', '=', object),
208             ('field_id', '=', field),
209         ]
210
211         ids = proxy.search(cr, uid, args, context=context)
212         user = self.pool.get('res.users').browse(cr, SUPERUSER_ID, uid, context=context)
213         for rule in proxy.browse(cr, uid, ids, context):
214             if eval(rule.expression, {'context': context, 'user': user}):
215                 return rule.company_dest_id.id
216         return user.company_id.id
217
218     @tools.ormcache()
219     def _get_company_children(self, cr, uid=None, company=None):
220         if not company:
221             return []
222         ids =  self.search(cr, uid, [('parent_id','child_of',[company])])
223         return ids
224
225     def _get_partner_hierarchy(self, cr, uid, company_id, context=None):
226         if company_id:
227             parent_id = self.browse(cr, uid, company_id)['parent_id']
228             if parent_id:
229                 return self._get_partner_hierarchy(cr, uid, parent_id.id, context)
230             else:
231                 return self._get_partner_descendance(cr, uid, company_id, [], context)
232         return []
233
234     def _get_partner_descendance(self, cr, uid, company_id, descendance, context=None):
235         descendance.append(self.browse(cr, uid, company_id).partner_id.id)
236         for child_id in self._get_company_children(cr, uid, company_id):
237             if child_id != company_id:
238                 descendance = self._get_partner_descendance(cr, uid, child_id, descendance)
239         return descendance
240
241     #
242     # This function restart the cache on the _get_company_children method
243     #
244     def cache_restart(self, cr):
245         self._get_company_children.clear_cache(self)
246
247     def create(self, cr, uid, vals, context=None):
248         if not vals.get('name', False) or vals.get('partner_id', False):
249             self.cache_restart(cr)
250             return super(res_company, self).create(cr, uid, vals, context=context)
251         obj_partner = self.pool.get('res.partner')
252         partner_id = obj_partner.create(cr, uid, {'name': vals['name'], 'is_company':True, 'image': vals.get('logo', False)}, context=context)
253         vals.update({'partner_id': partner_id})
254         self.cache_restart(cr)
255         company_id = super(res_company, self).create(cr, uid, vals, context=context)
256         obj_partner.write(cr, uid, [partner_id], {'company_id': company_id}, context=context)
257         return company_id
258
259     def write(self, cr, uid, ids, values, context=None):
260         self.cache_restart(cr)
261         return super(res_company, self).write(cr, uid, ids, values, context=context)
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             <paraStyle name="main_header"  fontName="DejaVu Sans" fontSize="8.0" leading="10" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/>
309          </stylesheet>
310         <pageGraphics>
311             <!-- You Logo - Change X,Y,Width and Height -->
312             <image x="1.3cm" y="%s" height="40.0" >[[ company.logo or removeParentNode('image') ]]</image>
313             <setFont name="DejaVu Sans" size="8"/>
314             <fill color="black"/>
315             <stroke color="black"/>
316
317             <!-- page header -->
318             <lines>1.3cm %s 20cm %s</lines>
319             <drawRightString x="20cm" y="%s">[[ company.rml_header1 ]]</drawRightString>
320             <drawString x="1.3cm" y="%s">[[ company.partner_id.name ]]</drawString>
321             <place x="1.3cm" y="%s" height="1.8cm" width="15.0cm">
322                 <para style="main_header">[[ display_address(company.partner_id) or  '' ]]</para>
323             </place>
324             <drawString x="1.3cm" y="%s">Phone:</drawString>
325             <drawRightString x="7cm" y="%s">[[ company.partner_id.phone or '' ]]</drawRightString>
326             <drawString x="1.3cm" y="%s">Mail:</drawString>
327             <drawRightString x="7cm" y="%s">[[ company.partner_id.email or '' ]]</drawRightString>
328             <lines>1.3cm %s 7cm %s</lines>
329
330             <!-- left margin -->
331             <rotate degrees="90"/>
332             <fill color="grey"/>
333             <drawString x="2.65cm" y="-0.4cm">generated by OpenERP.com</drawString>
334             <fill color="black"/>
335             <rotate degrees="-90"/>
336
337             <!--page bottom-->
338             <lines>1.2cm 2.65cm 19.9cm 2.65cm</lines>
339             <place x="1.3cm" y="0cm" height="2.55cm" width="19.0cm">
340                 <para style="main_footer">[[ company.rml_footer ]]</para>
341                 <para style="main_footer">Contact : [[ user.name ]] - Page: <pageNumber/></para>
342             </place>
343         </pageGraphics>
344     </pageTemplate>
345 </header>"""
346
347     _header_a4 = _header_main % ('21.7cm', '27.7cm', '27.7cm', '27.7cm', '27.8cm', '27.3cm', '25.3cm', '25.0cm', '25.0cm', '24.6cm', '24.6cm', '24.5cm', '24.5cm')
348     _header_letter = _header_main % ('20cm', '26.0cm', '26.0cm', '26.0cm', '26.1cm', '25.6cm', '23.6cm', '23.3cm', '23.3cm', '22.9cm', '22.9cm', '22.8cm', '22.8cm')
349
350     def onchange_paper_format(self, cr, uid, ids, paper_format, context=None):
351         if paper_format == 'us_letter':
352             return {'value': {'rml_header': self._header_letter}}
353         return {'value': {'rml_header': self._header_a4}}
354
355     _defaults = {
356         'currency_id': _get_euro,
357         'paper_format': 'a4',
358         'rml_header':_get_header,
359         'rml_header2': _header2,
360         'rml_header3': _header3,
361         'logo':_get_logo
362     }
363
364     _constraints = [
365         (osv.osv._check_recursion, 'Error! You can not create recursive companies.', ['parent_id'])
366     ]
367
368
369 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: