Launchpad automatic translations update.
[odoo/odoo.git] / addons / account / installer.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 datetime
23 from dateutil.relativedelta import relativedelta
24 import logging
25 from operator import itemgetter
26 from os.path import join as opj
27 import time
28
29 from openerp import netsvc, tools
30 from openerp.tools.translate import _
31 from openerp.osv import fields, osv
32
33 _logger = logging.getLogger(__name__)
34
35 class account_installer(osv.osv_memory):
36     _name = 'account.installer'
37     _inherit = 'res.config.installer'
38
39     def _get_charts(self, cr, uid, context=None):
40         modules = self.pool.get('ir.module.module')
41         # Looking for the module with the 'Account Charts' category
42         category_name, category_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'base', 'module_category_localization_account_charts')
43         ids = modules.search(cr, uid, [('category_id', '=', category_id)], context=context)
44         charts = list(
45             sorted(((m.name, m.shortdesc)
46                     for m in modules.browse(cr, uid, ids, context=context)),
47                    key=itemgetter(1)))
48         charts.insert(0, ('configurable', _('Custom')))
49         return charts
50
51     _columns = {
52         # Accounting
53         'charts': fields.selection(_get_charts, 'Accounting Package',
54             required=True,
55             help="Installs localized accounting charts to match as closely as "
56                  "possible the accounting needs of your company based on your "
57                  "country."),
58         'date_start': fields.date('Start Date', required=True),
59         'date_stop': fields.date('End Date', required=True),
60         'period': fields.selection([('month', 'Monthly'), ('3months','3 Monthly')], 'Periods', required=True),
61         'company_id': fields.many2one('res.company', 'Company', required=True),
62         'has_default_company' : fields.boolean('Has Default Company', readonly=True),
63     }
64
65     def _default_company(self, cr, uid, context=None):
66         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
67         return user.company_id and user.company_id.id or False
68
69     def _default_has_default_company(self, cr, uid, context=None):
70         count = self.pool.get('res.company').search_count(cr, uid, [], context=context)
71         return bool(count == 1)
72
73     _defaults = {
74         'date_start': lambda *a: time.strftime('%Y-01-01'),
75         'date_stop': lambda *a: time.strftime('%Y-12-31'),
76         'period': 'month',
77         'company_id': _default_company,
78         'has_default_company': _default_has_default_company,
79         'charts': 'configurable'
80     }
81     
82     def get_unconfigured_cmp(self, cr, uid, context=None):
83         """ get the list of companies that have not been configured yet
84         but don't care about the demo chart of accounts """
85         cmp_select = []
86         company_ids = self.pool.get('res.company').search(cr, uid, [], context=context)
87         cr.execute("SELECT company_id FROM account_account WHERE active = 't' AND account_account.parent_id IS NULL AND name != %s", ("Chart For Automated Tests",))
88         configured_cmp = [r[0] for r in cr.fetchall()]
89         return list(set(company_ids)-set(configured_cmp))
90     
91     def check_unconfigured_cmp(self, cr, uid, context=None):
92         """ check if there are still unconfigured companies """
93         if not self.get_unconfigured_cmp(cr, uid, context=context):
94             raise osv.except_osv(_('No unconfigured company !'), _("There is currently no company without chart of account. The wizard will therefore not be executed."))
95     
96     def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
97         if context is None:context = {}
98         res = super(account_installer, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar,submenu=False)
99         cmp_select = []
100         # display in the widget selection only the companies that haven't been configured yet
101         unconfigured_cmp = self.get_unconfigured_cmp(cr, uid, context=context)
102         for field in res['fields']:
103             if field == 'company_id':
104                 res['fields'][field]['domain'] = [('id','in',unconfigured_cmp)]
105                 res['fields'][field]['selection'] = [('', '')]
106                 if unconfigured_cmp:
107                     cmp_select = [(line.id, line.name) for line in self.pool.get('res.company').browse(cr, uid, unconfigured_cmp)]
108                     res['fields'][field]['selection'] = cmp_select
109         return res
110
111     def on_change_start_date(self, cr, uid, id, start_date=False):
112         if start_date:
113             start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d")
114             end_date = (start_date + relativedelta(months=12)) - relativedelta(days=1)
115             return {'value': {'date_stop': end_date.strftime('%Y-%m-%d')}}
116         return {}
117
118     def execute(self, cr, uid, ids, context=None):
119         self.execute_simple(cr, uid, ids, context)
120         super(account_installer, self).execute(cr, uid, ids, context=context)
121
122     def execute_simple(self, cr, uid, ids, context=None):
123         if context is None:
124             context = {}
125         fy_obj = self.pool.get('account.fiscalyear')
126         for res in self.read(cr, uid, ids, context=context):
127             if 'date_start' in res and 'date_stop' in res:
128                 f_ids = fy_obj.search(cr, uid, [('date_start', '<=', res['date_start']), ('date_stop', '>=', res['date_stop']), ('company_id', '=', res['company_id'][0])], context=context)
129                 if not f_ids:
130                     name = code = res['date_start'][:4]
131                     if int(name) != int(res['date_stop'][:4]):
132                         name = res['date_start'][:4] +'-'+ res['date_stop'][:4]
133                         code = res['date_start'][2:4] +'-'+ res['date_stop'][2:4]
134                     vals = {
135                         'name': name,
136                         'code': code,
137                         'date_start': res['date_start'],
138                         'date_stop': res['date_stop'],
139                         'company_id': res['company_id'][0]
140                     }
141                     fiscal_id = fy_obj.create(cr, uid, vals, context=context)
142                     if res['period'] == 'month':
143                         fy_obj.create_period(cr, uid, [fiscal_id])
144                     elif res['period'] == '3months':
145                         fy_obj.create_period3(cr, uid, [fiscal_id])
146
147     def modules_to_install(self, cr, uid, ids, context=None):
148         modules = super(account_installer, self).modules_to_install(
149             cr, uid, ids, context=context)
150         chart = self.read(cr, uid, ids, ['charts'],
151                           context=context)[0]['charts']
152         _logger.debug('Installing chart of accounts %s', chart)
153         return modules | set([chart])
154
155 account_installer()
156
157 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: