d1b19ef43199475982b6f46f1721d5d179aeecb9
[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 logging
23 import time
24 import datetime
25 from dateutil.relativedelta import relativedelta
26 from operator import itemgetter
27 from os.path import join as opj
28
29 from tools.translate import _
30 from osv import fields, osv
31 import netsvc
32 import tools
33
34 class account_installer(osv.osv_memory):
35     _name = 'account.installer'
36     _inherit = 'res.config.installer'
37     __logger = logging.getLogger(_name)
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', 'Generic Chart Of Accounts'))
49         return charts
50
51     _columns = {
52         # Accounting
53         'charts': fields.selection(_get_charts, 'Chart of Accounts',
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 fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
83         res = super(account_installer, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar,submenu=False)
84         cmp_select = []
85         company_ids = self.pool.get('res.company').search(cr, uid, [], context=context)
86         #display in the widget selection of companies, only the companies that haven't been configured yet (but don't care about the demo chart of accounts)
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         unconfigured_cmp = list(set(company_ids)-set(configured_cmp))
90         for field in res['fields']:
91             if field == 'company_id':
92                 res['fields'][field]['domain'] = [('id','in',unconfigured_cmp)]
93                 res['fields'][field]['selection'] = [('', '')]
94                 if unconfigured_cmp:
95                     cmp_select = [(line.id, line.name) for line in self.pool.get('res.company').browse(cr, uid, unconfigured_cmp)]
96                     res['fields'][field]['selection'] = cmp_select
97         return res
98
99     def on_change_start_date(self, cr, uid, id, start_date=False):
100         if start_date:
101             start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d")
102             end_date = (start_date + relativedelta(months=12)) - relativedelta(days=1)
103             return {'value': {'date_stop': end_date.strftime('%Y-%m-%d')}}
104         return {}
105
106     def execute(self, cr, uid, ids, context=None):
107         self.execute_simple(cr, uid, ids, context)
108         super(account_installer, self).execute(cr, uid, ids, context=context)
109
110     def execute_simple(self, cr, uid, ids, context=None):
111         if context is None:
112             context = {}
113         fy_obj = self.pool.get('account.fiscalyear')
114         for res in self.read(cr, uid, ids, context=context):
115             if 'charts' in res and res['charts'] == 'configurable':
116                 #load generic chart of account
117                 fp = tools.file_open(opj('account', 'configurable_account_chart.xml'))
118                 tools.convert_xml_import(cr, 'account', fp, {}, 'init', True, None)
119                 fp.close()
120             if 'date_start' in res and 'date_stop' in res:
121                 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)
122                 if not f_ids:
123                     name = code = res['date_start'][:4]
124                     if int(name) != int(res['date_stop'][:4]):
125                         name = res['date_start'][:4] +'-'+ res['date_stop'][:4]
126                         code = res['date_start'][2:4] +'-'+ res['date_stop'][2:4]
127                     vals = {
128                         'name': name,
129                         'code': code,
130                         'date_start': res['date_start'],
131                         'date_stop': res['date_stop'],
132                         'company_id': res['company_id'][0]
133                     }
134                     fiscal_id = fy_obj.create(cr, uid, vals, context=context)
135                     if res['period'] == 'month':
136                         fy_obj.create_period(cr, uid, [fiscal_id])
137                     elif res['period'] == '3months':
138                         fy_obj.create_period3(cr, uid, [fiscal_id])
139
140     def modules_to_install(self, cr, uid, ids, context=None):
141         modules = super(account_installer, self).modules_to_install(
142             cr, uid, ids, context=context)
143         chart = self.read(cr, uid, ids, ['charts'],
144                           context=context)[0]['charts']
145         self.__logger.debug('Installing chart of accounts %s', chart)
146         return modules | set([chart])
147
148 account_installer()
149
150 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: