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