[ADD]: new view for Unrealized Gains and losses
[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 os.path import join as opj
27 from operator import itemgetter
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         ids = modules.search(cr, uid, [('name', 'like', 'l10n_')], context=context)
42         charts = list(
43             sorted(((m.name, m.shortdesc)
44                     for m in modules.browse(cr, uid, ids, context=context)),
45                    key=itemgetter(1)))
46         charts.insert(0, ('configurable', 'Generic Chart Of Account'))
47         return charts
48
49     _columns = {
50         # Accounting
51         'charts': fields.selection(_get_charts, 'Chart of Accounts',
52             required=True,
53             help="Installs localized accounting charts to match as closely as "
54                  "possible the accounting needs of your company based on your "
55                  "country."),
56         'date_start': fields.date('Start Date', required=True),
57         'date_stop': fields.date('End Date', required=True),
58         'period': fields.selection([('month', 'Monthly'), ('3months','3 Monthly')], 'Periods', required=True),
59         'sale_tax': fields.float('Sale Tax(%)'),
60         'purchase_tax': fields.float('Purchase Tax(%)'),
61         'company_id': fields.many2one('res.company', 'Company', required=True),
62     }
63
64     def _default_company(self, cr, uid, context=None):
65         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
66         return user.company_id and user.company_id.id or False
67
68     _defaults = {
69         'date_start': lambda *a: time.strftime('%Y-01-01'),
70         'date_stop': lambda *a: time.strftime('%Y-12-31'),
71         'period': 'month',
72         'sale_tax': 0.0,
73         'purchase_tax': 0.0,
74         'company_id': _default_company,
75         'charts': 'configurable'
76     }
77
78     def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
79         res = super(account_installer, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar,submenu=False)
80         cmp_select = []
81         company_ids = self.pool.get('res.company').search(cr, uid, [], context=context)
82         #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)
83         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",))
84         configured_cmp = [r[0] for r in cr.fetchall()]
85         unconfigured_cmp = list(set(company_ids)-set(configured_cmp))
86         for field in res['fields']:
87             if field == 'company_id':
88                 res['fields'][field]['domain'] = [('id','in',unconfigured_cmp)]
89                 res['fields'][field]['selection'] = [('', '')]
90                 if unconfigured_cmp:
91                     cmp_select = [(line.id, line.name) for line in self.pool.get('res.company').browse(cr, uid, unconfigured_cmp)]
92                     res['fields'][field]['selection'] = cmp_select
93         return res
94
95     def on_change_tax(self, cr, uid, id, tax):
96         return {'value': {'purchase_tax': tax}}
97
98     def on_change_start_date(self, cr, uid, id, start_date=False):
99         if start_date:
100             start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d")
101             end_date = (start_date + relativedelta(months=12)) - relativedelta(days=1)
102             return {'value': {'date_stop': end_date.strftime('%Y-%m-%d')}}
103         return {}
104
105     def execute(self, cr, uid, ids, context=None):
106         if context is None:
107             context = {}
108         fy_obj = self.pool.get('account.fiscalyear')
109         mod_obj = self.pool.get('ir.model.data')
110         obj_acc_temp = self.pool.get('account.account.template')
111         obj_tax_code_temp = self.pool.get('account.tax.code.template')
112         obj_tax_temp = self.pool.get('account.tax.template')
113         obj_acc_chart_temp = self.pool.get('account.chart.template')
114         record = self.browse(cr, uid, ids, context=context)[0]
115         for res in self.read(cr, uid, ids, context=context):
116             if record.charts == 'configurable':
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                 s_tax = (res.get('sale_tax', 0.0))/100
121                 p_tax = (res.get('purchase_tax', 0.0))/100
122                 pur_temp_tax = mod_obj.get_object_reference(cr, uid, 'account', 'tax_code_base_purchases')
123                 pur_temp_tax_id = pur_temp_tax and pur_temp_tax[1] or False
124
125                 pur_temp_tax_paid = mod_obj.get_object_reference(cr, uid, 'account', 'tax_code_output')
126                 pur_temp_tax_paid_id = pur_temp_tax_paid and pur_temp_tax_paid[1] or False
127
128                 sale_temp_tax = mod_obj.get_object_reference(cr, uid, 'account', 'tax_code_base_sales')
129                 sale_temp_tax_id = sale_temp_tax and sale_temp_tax[1] or False
130
131                 sale_temp_tax_paid = mod_obj.get_object_reference(cr, uid, 'account', 'tax_code_input')
132                 sale_temp_tax_paid_id = sale_temp_tax_paid and sale_temp_tax_paid[1] or False
133
134                 chart_temp_ids = obj_acc_chart_temp.search(cr, uid, [('name','=','Configurable Account Chart Template')], context=context)
135                 chart_temp_id = chart_temp_ids and chart_temp_ids[0] or False
136                 if s_tax * 100 > 0.0:
137                     tax_account_ids = obj_acc_temp.search(cr, uid, [('name', '=', 'Tax Received')], context=context)
138                     sales_tax_account_id = tax_account_ids and tax_account_ids[0] or False
139                     vals_tax_code_temp = {
140                         'name': _('TAX %s%%') % (s_tax*100),
141                         'code': _('TAX %s%%') % (s_tax*100),
142                         'parent_id': sale_temp_tax_id
143                     }
144                     new_tax_code_temp = obj_tax_code_temp.create(cr, uid, vals_tax_code_temp, context=context)
145                     vals_paid_tax_code_temp = {
146                         'name': _('TAX Received %s%%') % (s_tax*100),
147                         'code': _('TAX Received %s%%') % (s_tax*100),
148                         'parent_id': sale_temp_tax_paid_id
149                     }
150                     new_paid_tax_code_temp = obj_tax_code_temp.create(cr, uid, vals_paid_tax_code_temp, context=context)
151                     sales_tax_temp = obj_tax_temp.create(cr, uid, {
152                                             'name': _('Sale TAX %s%%') % (s_tax*100),
153                                             'amount': s_tax,
154                                             'base_code_id': new_tax_code_temp,
155                                             'tax_code_id': new_paid_tax_code_temp,
156                                             'ref_base_code_id': new_tax_code_temp,
157                                             'ref_tax_code_id': new_paid_tax_code_temp,
158                                             'type_tax_use': 'sale',
159                                             'type': 'percent',
160                                             'sequence': 0,
161                                             'account_collected_id': sales_tax_account_id,
162                                             'account_paid_id': sales_tax_account_id,
163                                             'chart_template_id': chart_temp_id,
164                                 }, context=context)
165                 if p_tax * 100 > 0.0:
166                     tax_account_ids = obj_acc_temp.search(cr, uid, [('name', '=', 'Tax Paid')], context=context)
167                     purchase_tax_account_id = tax_account_ids and tax_account_ids[0] or False
168                     vals_tax_code_temp = {
169                         'name': _('TAX %s%%') % (p_tax*100),
170                         'code': _('TAX %s%%') % (p_tax*100),
171                         'parent_id': pur_temp_tax_id
172                     }
173                     new_tax_code_temp = obj_tax_code_temp.create(cr, uid, vals_tax_code_temp, context=context)
174                     vals_paid_tax_code_temp = {
175                         'name': _('TAX Paid %s%%') % (p_tax*100),
176                         'code': _('TAX Paid %s%%') % (p_tax*100),
177                         'parent_id': pur_temp_tax_paid_id
178                     }
179                     new_paid_tax_code_temp = obj_tax_code_temp.create(cr, uid, vals_paid_tax_code_temp, context=context)
180                     purchase_tax_temp = obj_tax_temp.create(cr, uid, {
181                                              'name': _('Purchase TAX %s%%') % (p_tax*100),
182                                              'amount': p_tax,
183                                              'base_code_id': new_tax_code_temp,
184                                              'tax_code_id': new_paid_tax_code_temp,
185                                              'ref_base_code_id': new_tax_code_temp,
186                                              'ref_tax_code_id': new_paid_tax_code_temp,
187                                              'type_tax_use': 'purchase',
188                                              'type': 'percent',
189                                              'sequence': 0,
190                                              'account_collected_id': purchase_tax_account_id,
191                                              'account_paid_id': purchase_tax_account_id,
192                                              'chart_template_id': chart_temp_id,
193                                     }, context=context)
194
195             if 'date_start' in res and 'date_stop' in res:
196                 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)
197                 if not f_ids:
198                     name = code = res['date_start'][:4]
199                     if int(name) != int(res['date_stop'][:4]):
200                         name = res['date_start'][:4] +'-'+ res['date_stop'][:4]
201                         code = res['date_start'][2:4] +'-'+ res['date_stop'][2:4]
202                     vals = {
203                         'name': name,
204                         'code': code,
205                         'date_start': res['date_start'],
206                         'date_stop': res['date_stop'],
207                         'company_id': res['company_id'][0]
208                     }
209                     fiscal_id = fy_obj.create(cr, uid, vals, context=context)
210                     if res['period'] == 'month':
211                         fy_obj.create_period(cr, uid, [fiscal_id])
212                     elif res['period'] == '3months':
213                         fy_obj.create_period3(cr, uid, [fiscal_id])
214         super(account_installer, self).execute(cr, uid, ids, context=context)
215
216     def modules_to_install(self, cr, uid, ids, context=None):
217         modules = super(account_installer, self).modules_to_install(
218             cr, uid, ids, context=context)
219         chart = self.read(cr, uid, ids, ['charts'],
220                           context=context)[0]['charts']
221         self.__logger.debug('Installing chart of accounts %s', chart)
222         return modules | set([chart])
223
224 account_installer()
225
226 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: