1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
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.
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.
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/>.
20 ##############################################################################
23 from dateutil.relativedelta import relativedelta
25 from operator import itemgetter
31 import simplejson as json
35 from openerp.release import serie
36 from openerp.tools.translate import _
37 from openerp.osv import fields, osv
39 _logger = logging.getLogger(__name__)
41 class account_installer(osv.osv_memory):
42 _name = 'account.installer'
43 _inherit = 'res.config.installer'
45 def _get_charts(self, cr, uid, context=None):
46 modules = self.pool.get('ir.module.module')
48 # try get the list on apps server
50 apps_server = self.pool.get('ir.config_parameter').get_param(cr, uid, 'apps.server', 'https://apps.openerp.com')
52 up = urlparse.urlparse(apps_server)
53 url = '{0.scheme}://{0.netloc}/apps/charts?serie={1}'.format(up, serie)
55 j = urllib2.urlopen(url, timeout=3).read()
56 apps_charts = json.loads(j)
58 charts = dict(apps_charts)
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)
66 charts.update((m.name, m.shortdesc) for m in modules.browse(cr, uid, ids, context=context))
68 charts = sorted(charts.items(), key=itemgetter(1))
69 charts.insert(0, ('configurable', _('Custom')))
74 'charts': fields.selection(_get_charts, 'Accounting Package',
76 help="Installs localized accounting charts to match as closely as "
77 "possible the accounting needs of your company based on your "
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),
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
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)
95 'date_start': lambda *a: time.strftime('%Y-01-01'),
96 'date_stop': lambda *a: time.strftime('%Y-12-31'),
98 'company_id': _default_company,
99 'has_default_company': _default_has_default_company,
100 'charts': 'configurable'
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 """
107 company_ids = self.pool.get('res.company').search(cr, uid, [], context=context)
108 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",))
109 configured_cmp = [r[0] for r in cr.fetchall()]
110 return list(set(company_ids)-set(configured_cmp))
112 def check_unconfigured_cmp(self, cr, uid, context=None):
113 """ check if there are still unconfigured companies """
114 if not self.get_unconfigured_cmp(cr, uid, context=context):
115 raise osv.except_osv(_('No unconfigured company!'), _("There is currently no company without chart of account. The wizard will therefore not be executed."))
117 def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
118 if context is None:context = {}
119 res = super(account_installer, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar,submenu=False)
121 # display in the widget selection only the companies that haven't been configured yet
122 unconfigured_cmp = self.get_unconfigured_cmp(cr, uid, context=context)
123 for field in res['fields']:
124 if field == 'company_id':
125 res['fields'][field]['domain'] = [('id','in',unconfigured_cmp)]
126 res['fields'][field]['selection'] = [('', '')]
128 cmp_select = [(line.id, line.name) for line in self.pool.get('res.company').browse(cr, uid, unconfigured_cmp)]
129 res['fields'][field]['selection'] = cmp_select
132 def on_change_start_date(self, cr, uid, id, start_date=False):
134 start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d")
135 end_date = (start_date + relativedelta(months=12)) - relativedelta(days=1)
136 return {'value': {'date_stop': end_date.strftime('%Y-%m-%d')}}
139 def execute(self, cr, uid, ids, context=None):
140 self.execute_simple(cr, uid, ids, context)
141 return super(account_installer, self).execute(cr, uid, ids, context=context)
143 def execute_simple(self, cr, uid, ids, context=None):
146 fy_obj = self.pool.get('account.fiscalyear')
147 for res in self.read(cr, uid, ids, context=context):
148 if 'date_start' in res and 'date_stop' in res:
149 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)
151 name = code = res['date_start'][:4]
152 if int(name) != int(res['date_stop'][:4]):
153 name = res['date_start'][:4] +'-'+ res['date_stop'][:4]
154 code = res['date_start'][2:4] +'-'+ res['date_stop'][2:4]
158 'date_start': res['date_start'],
159 'date_stop': res['date_stop'],
160 'company_id': res['company_id'][0]
162 fiscal_id = fy_obj.create(cr, uid, vals, context=context)
163 if res['period'] == 'month':
164 fy_obj.create_period(cr, uid, [fiscal_id])
165 elif res['period'] == '3months':
166 fy_obj.create_period3(cr, uid, [fiscal_id])
168 def modules_to_install(self, cr, uid, ids, context=None):
169 modules = super(account_installer, self).modules_to_install(
170 cr, uid, ids, context=context)
171 chart = self.read(cr, uid, ids, ['charts'],
172 context=context)[0]['charts']
173 _logger.debug('Installing chart of accounts %s', chart)
174 return (modules | set([chart])) - set(['has_default_company', 'configurable'])
178 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: