[MERGE]: Merged with latest trunk-addons as there are many changes regarding config...
[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
28 from tools.translate import _
29 from osv import fields, osv
30 import netsvc
31 import tools
32
33 class account_installer(osv.osv_memory):
34     _name = 'account.installer'
35     _inherit = 'res.config.installer'
36     __logger = logging.getLogger(_name)
37
38     def _get_charts(self, cr, uid, context=None):
39         modules = self.pool.get('ir.module.module')
40         ids = modules.search(cr, uid, [('name', 'like', 'l10n_')], context=context)
41         charts = list(
42             sorted(((m.name, m.shortdesc)
43                     for m in modules.browse(cr, uid, ids, context=context)),
44                    key=itemgetter(1)))
45         charts.insert(0, ('configurable', 'Generic Chart Of Account'))
46         return charts
47
48     _columns = {
49         # Accounting
50         'charts': fields.selection(_get_charts, 'Chart of Accounts',
51             required=True,
52             help="Installs localized accounting charts to match as closely as "
53                  "possible the accounting needs of your company based on your "
54                  "country."),
55         'date_start': fields.date('Start Date', required=True),
56         'date_stop': fields.date('End Date', required=True),
57         'period': fields.selection([('month', 'Monthly'), ('3months','3 Monthly')], 'Periods', required=True),
58         'company_id': fields.many2one('res.company', 'Company', required=True),
59     }
60
61     def _default_company(self, cr, uid, context=None):
62         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
63         return user.company_id and user.company_id.id or False
64
65     def _get_default_charts(self, cr, uid, context=None):
66         module_name = False
67         company_id = self._default_company(cr, uid, context=context)
68         company = self.pool.get('res.company').browse(cr, uid, company_id, context=context)
69         address_id = self.pool.get('res.partner').address_get(cr, uid, [company.partner_id.id])
70         if address_id['default']:
71             address = self.pool.get('res.partner.address').browse(cr, uid, address_id['default'], context=context)
72             code = address.country_id.code
73             module_name = (code and 'l10n_' + code.lower()) or False
74         if module_name:
75             module_id = self.pool.get('ir.module.module').search(cr, uid, [('name', '=', module_name)], context=context)
76             if module_id:
77                 return module_name
78         return 'configurable'
79
80     _defaults = {
81         'date_start': lambda *a: time.strftime('%Y-01-01'),
82         'date_stop': lambda *a: time.strftime('%Y-12-31'),
83         'period': 'month',
84         'company_id': _default_company,
85         'charts': _get_default_charts
86     }
87
88     def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
89         res = super(account_installer, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar,submenu=False)
90         cmp_select = []
91         company_ids = self.pool.get('res.company').search(cr, uid, [], context=context)
92         #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)
93         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",))
94         configured_cmp = [r[0] for r in cr.fetchall()]
95         unconfigured_cmp = list(set(company_ids)-set(configured_cmp))
96         for field in res['fields']:
97             if field == 'company_id':
98                 res['fields'][field]['domain'] = unconfigured_cmp
99                 res['fields'][field]['selection'] = [('', '')]
100                 if unconfigured_cmp:
101                     cmp_select = [(line.id, line.name) for line in self.pool.get('res.company').browse(cr, uid, unconfigured_cmp)]
102                     res['fields'][field]['selection'] = cmp_select
103         return res
104
105     def on_change_start_date(self, cr, uid, id, start_date=False):
106         if start_date:
107             start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d")
108             end_date = (start_date + relativedelta(months=12)) - relativedelta(days=1)
109             return {'value': {'date_stop': end_date.strftime('%Y-%m-%d')}}
110         return {}
111
112     def execute(self, cr, uid, ids, context=None):
113         if context is None:
114             context = {}
115         fy_obj = self.pool.get('account.fiscalyear')
116         for res in self.read(cr, uid, ids, context=context):
117             if 'date_start' in res and 'date_stop' in res:
118                 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)
119                 if not f_ids:
120                     name = code = res['date_start'][:4]
121                     if int(name) != int(res['date_stop'][:4]):
122                         name = res['date_start'][:4] +'-'+ res['date_stop'][:4]
123                         code = res['date_start'][2:4] +'-'+ res['date_stop'][2:4]
124                     vals = {
125                         'name': name,
126                         'code': code,
127                         'date_start': res['date_start'],
128                         'date_stop': res['date_stop'],
129                         'company_id': res['company_id'][0]
130                     }
131                     fiscal_id = fy_obj.create(cr, uid, vals, context=context)
132                     if res['period'] == 'month':
133                         fy_obj.create_period(cr, uid, [fiscal_id])
134                     elif res['period'] == '3months':
135                         fy_obj.create_period3(cr, uid, [fiscal_id])
136         super(account_installer, self).execute(cr, uid, ids, context=context)
137
138     def modules_to_install(self, cr, uid, ids, context=None):
139         modules = super(account_installer, self).modules_to_install(
140             cr, uid, ids, context=context)
141         chart = self.read(cr, uid, ids, ['charts'],
142                           context=context)[0]['charts']
143         self.__logger.debug('Installing chart of accounts %s', chart)
144         return modules | set([chart])
145
146 account_installer()
147
148 class account_installer_modules(osv.osv_memory):
149     _inherit = 'base.setup.installer'
150     _columns = {
151         'account_analytic_plans': fields.boolean('Multiple Analytic Plans',
152             help="Allows invoice lines to impact multiple analytic accounts "
153                  "simultaneously."),
154         'account_payment': fields.boolean('Suppliers Payment Management',
155             help="Streamlines invoice payment and creates hooks to plug "
156                  "automated payment systems in."),
157         'account_followup': fields.boolean('Followups Management',
158             help="Helps you generate reminder letters for unpaid invoices, "
159                  "including multiple levels of reminding and customized "
160                  "per-partner policies."),
161         'account_anglo_saxon': fields.boolean('Anglo-Saxon Accounting',
162             help="This module will support the Anglo-Saxons accounting methodology by "
163                 "changing the accounting logic with stock transactions."),
164         'account_asset': fields.boolean('Assets Management',
165             help="Helps you to manage your assets and their depreciation entries."),
166     }
167
168 account_installer_modules()
169
170 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: