[MERGE] Forward-port latest 7.0 bugfixes, up to f8671cb
[odoo/odoo.git] / addons / account_budget / account_budget.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 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
24 from openerp.osv import fields, osv
25 from openerp.tools import ustr
26 from openerp.tools.translate import _
27
28 import openerp.addons.decimal_precision as dp
29
30 def strToDate(dt):
31         dt_date=datetime.date(int(dt[0:4]),int(dt[5:7]),int(dt[8:10]))
32         return dt_date
33
34 # ---------------------------------------------------------
35 # Budgets
36 # ---------------------------------------------------------
37 class account_budget_post(osv.osv):
38     _name = "account.budget.post"
39     _description = "Budgetary Position"
40     _columns = {
41         'code': fields.char('Code', size=64, required=True),
42         'name': fields.char('Name', size=256, required=True),
43         'account_ids': fields.many2many('account.account', 'account_budget_rel', 'budget_id', 'account_id', 'Accounts'),
44         'crossovered_budget_line': fields.one2many('crossovered.budget.lines', 'general_budget_id', 'Budget Lines'),
45         'company_id': fields.many2one('res.company', 'Company', required=True),
46     }
47     _defaults = {
48         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.budget.post', context=c)
49     }
50     _order = "name"
51
52
53
54 class crossovered_budget(osv.osv):
55     _name = "crossovered.budget"
56     _description = "Budget"
57
58     _columns = {
59         'name': fields.char('Name', size=64, required=True, states={'done':[('readonly',True)]}),
60         'code': fields.char('Code', size=16, required=True, states={'done':[('readonly',True)]}),
61         'creating_user_id': fields.many2one('res.users', 'Responsible User'),
62         'validating_user_id': fields.many2one('res.users', 'Validate User', readonly=True),
63         'date_from': fields.date('Start Date', required=True, states={'done':[('readonly',True)]}),
64         'date_to': fields.date('End Date', required=True, states={'done':[('readonly',True)]}),
65         'state' : fields.selection([('draft','Draft'),('cancel', 'Cancelled'),('confirm','Confirmed'),('validate','Validated'),('done','Done')], 'Status', select=True, required=True, readonly=True),
66         'crossovered_budget_line': fields.one2many('crossovered.budget.lines', 'crossovered_budget_id', 'Budget Lines', states={'done':[('readonly',True)]}),
67         'company_id': fields.many2one('res.company', 'Company', required=True),
68     }
69
70     _defaults = {
71         'state': 'draft',
72         'creating_user_id': lambda self, cr, uid, context: uid,
73         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.budget.post', context=c)
74     }
75
76     def budget_confirm(self, cr, uid, ids, *args):
77         self.write(cr, uid, ids, {
78             'state': 'confirm'
79         })
80         return True
81
82     def budget_draft(self, cr, uid, ids, *args):
83         self.write(cr, uid, ids, {
84             'state': 'draft'
85         })
86         return True
87
88     def budget_validate(self, cr, uid, ids, *args):
89         self.write(cr, uid, ids, {
90             'state': 'validate',
91             'validating_user_id': uid,
92         })
93         return True
94
95     def budget_cancel(self, cr, uid, ids, *args):
96         self.write(cr, uid, ids, {
97             'state': 'cancel'
98         })
99         return True
100
101     def budget_done(self, cr, uid, ids, *args):
102         self.write(cr, uid, ids, {
103             'state': 'done'
104         })
105         return True
106
107
108 class crossovered_budget_lines(osv.osv):
109
110     def _prac_amt(self, cr, uid, ids, context=None):
111         res = {}
112         result = 0.0
113         if context is None: 
114             context = {}
115         for line in self.browse(cr, uid, ids, context=context):
116             acc_ids = [x.id for x in line.general_budget_id.account_ids]
117             if not acc_ids:
118                 raise osv.except_osv(_('Error!'),_("The Budget '%s' has no accounts!") % ustr(line.general_budget_id.name))
119             date_to = line.date_to
120             date_from = line.date_from
121             if context.has_key('wizard_date_from'):
122                 date_from = context['wizard_date_from']
123             if context.has_key('wizard_date_to'):
124                 date_to = context['wizard_date_to']
125             if line.analytic_account_id.id:
126                 cr.execute("SELECT SUM(amount) FROM account_analytic_line WHERE account_id=%s AND (date "
127                        "between to_date(%s,'yyyy-mm-dd') AND to_date(%s,'yyyy-mm-dd')) AND "
128                        "general_account_id=ANY(%s)", (line.analytic_account_id.id, date_from, date_to,acc_ids,))
129                 result = cr.fetchone()[0]
130             if result is None:
131                 result = 0.00
132             res[line.id] = result
133         return res
134
135     def _prac(self, cr, uid, ids, name, args, context=None):
136         res={}
137         for line in self.browse(cr, uid, ids, context=context):
138             res[line.id] = self._prac_amt(cr, uid, [line.id], context=context)[line.id]
139         return res
140
141     def _theo_amt(self, cr, uid, ids, context=None):
142         res = {}
143         if context is None: 
144             context = {}
145         for line in self.browse(cr, uid, ids, context=context):
146             today = datetime.datetime.today()
147             date_to = today.strftime("%Y-%m-%d")
148             date_from = line.date_from
149             if context.has_key('wizard_date_from'):
150                 date_from = context['wizard_date_from']
151             if context.has_key('wizard_date_to'):
152                 date_to = context['wizard_date_to']
153
154             if line.paid_date:
155                 if strToDate(line.date_to) <= strToDate(line.paid_date):
156                     theo_amt = 0.00
157                 else:
158                     theo_amt = line.planned_amount
159             else:
160                 total = strToDate(line.date_to) - strToDate(line.date_from)
161                 elapsed = min(strToDate(line.date_to),strToDate(date_to)) - max(strToDate(line.date_from),strToDate(date_from))
162                 if strToDate(date_to) < strToDate(line.date_from):
163                     elapsed = strToDate(date_to) - strToDate(date_to)
164
165                 if total.days:
166                     theo_amt = float((elapsed.days + 1) / float(total.days + 1)) * line.planned_amount
167                 else:
168                     theo_amt = line.planned_amount
169
170             res[line.id] = theo_amt
171         return res
172
173     def _theo(self, cr, uid, ids, name, args, context=None):
174         res = {}
175         for line in self.browse(cr, uid, ids, context=context):
176             res[line.id] = self._theo_amt(cr, uid, [line.id], context=context)[line.id]
177         return res
178
179     def _perc(self, cr, uid, ids, name, args, context=None):
180         res = {}
181         for line in self.browse(cr, uid, ids, context=context):
182             if line.theoritical_amount <> 0.00:
183                 res[line.id] = float((line.practical_amount or 0.0) / line.theoritical_amount) * 100
184             else:
185                 res[line.id] = 0.00
186         return res
187
188     _name = "crossovered.budget.lines"
189     _description = "Budget Line"
190     _columns = {
191         'crossovered_budget_id': fields.many2one('crossovered.budget', 'Budget', ondelete='cascade', select=True, required=True),
192         'analytic_account_id': fields.many2one('account.analytic.account', 'Analytic Account'),
193         'general_budget_id': fields.many2one('account.budget.post', 'Budgetary Position',required=True),
194         'date_from': fields.date('Start Date', required=True),
195         'date_to': fields.date('End Date', required=True),
196         'paid_date': fields.date('Paid Date'),
197         'planned_amount':fields.float('Planned Amount', required=True, digits_compute=dp.get_precision('Account')),
198         'practical_amount':fields.function(_prac, string='Practical Amount', type='float', digits_compute=dp.get_precision('Account')),
199         'theoritical_amount':fields.function(_theo, string='Theoretical Amount', type='float', digits_compute=dp.get_precision('Account')),
200         'percentage':fields.function(_perc, string='Percentage', type='float'),
201         'company_id': fields.related('crossovered_budget_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True)
202     }
203
204
205 class account_analytic_account(osv.osv):
206     _inherit = "account.analytic.account"
207
208     _columns = {
209         'crossovered_budget_line': fields.one2many('crossovered.budget.lines', 'analytic_account_id', 'Budget Lines'),
210     }
211
212
213 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: