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