added from extra-addons
[odoo/odoo.git] / addons / account_budget_crossover / crossovered_budget.py
1 # -*- encoding: utf-8 -*-
2 from osv import osv,fields
3 import tools
4 import netsvc
5 from mx import DateTime
6 import time
7 import datetime
8
9
10 def strToDate(dt):
11         dt_date=datetime.date(int(dt[0:4]),int(dt[5:7]),int(dt[8:10]))
12         return dt_date
13
14 class crossovered_budget(osv.osv):
15     _name = "crossovered.budget"
16     _description = "Crossovered Budget"
17
18     _columns = {
19         'name': fields.char('Name', size=50, required=True,states={'done':[('readonly',True)]}),
20         'code': fields.char('Code', size=20, required=True,states={'done':[('readonly',True)]}),
21         'creating_user_id': fields.many2one('res.users','Responsible User'),
22         'validating_user_id': fields.many2one('res.users','Validate User', readonly=True),
23         'date_from': fields.date('Start Date',required=True,states={'done':[('readonly',True)]}),
24         'date_to': fields.date('End Date',required=True,states={'done':[('readonly',True)]}),
25         'state' : fields.selection([('draft','Draft'),('confirm','Confirmed'),('validate','Validated'),('done','Done'),('cancel', 'Cancelled')], 'State', select=True, required=True, readonly=True),
26         'crossovered_budget_line': fields.one2many('crossovered.budget.lines', 'crossovered_budget_id', 'Budget Lines',states={'done':[('readonly',True)]} ),
27     }
28
29     _defaults = {
30         'state': lambda *a: 'draft',
31         'creating_user_id': lambda self,cr,uid,context: uid,
32     }
33
34 #   def action_set_to_draft(self, cr, uid, ids, *args):
35 #       self.write(cr, uid, ids, {'state': 'draft'})
36 #       wf_service = netsvc.LocalService('workflow')
37 #       for id in ids:
38 #           wf_service.trg_create(uid, self._name, id, cr)
39 #       return True
40
41     def budget_confirm(self, cr, uid, ids, *args):
42         self.write(cr, uid, ids, {
43             'state':'confirm'
44         })
45         return True
46
47     def budget_validate(self, cr, uid, ids, *args):
48         self.write(cr, uid, ids, {
49             'state':'validate',
50             'validating_user_id': uid,
51         })
52         return True
53
54     def budget_cancel(self, cr, uid, ids, *args):
55
56         self.write(cr, uid, ids, {
57             'state':'cancel'
58         })
59         return True
60
61     def budget_done(self, cr, uid, ids, *args):
62         self.write(cr, uid, ids, {
63             'state':'done'
64         })
65         return True
66
67 crossovered_budget()
68
69 class crossovered_budget_lines(osv.osv):
70
71     def _pra_amt(self, cr, uid, ids,name,args,context):
72         res = {}
73         for line in self.browse(cr, uid, ids):
74             acc_ids = ','.join([str(x.id) for x in line.general_budget_id.account_ids])
75             if not acc_ids:
76                 raise osv.except_osv('Error!',"The General Budget '" + str(line.general_budget_id.name) + "' has no Accounts!" )
77             date_to = line.date_to
78             date_from = line.date_from
79             if context.has_key('wizard_date_from'):
80                 date_from = context['wizard_date_from']
81             if context.has_key('wizard_date_to'):
82                 date_to = context['wizard_date_to']
83             cr.execute("select sum(amount) from account_analytic_line where account_id=%d and (date between to_date('%s','yyyy-mm-dd') and to_date('%s','yyyy-mm-dd')) and general_account_id in (%s)"%(line.analytic_account_id.id,date_from,date_to,acc_ids))
84             result=cr.fetchone()[0]
85             if result==None:
86                 result=0.00
87             res[line.id]=result
88         return res
89
90     def _theo_amt(self, cr, uid, ids,name,args,context):
91         res = {}
92         for line in self.browse(cr, uid, ids):
93             today=datetime.datetime.today()
94             date_to = today.strftime("%Y-%m-%d")
95             date_from = line.date_from
96             if context.has_key('wizard_date_from'):
97                 date_from = context['wizard_date_from']
98             if context.has_key('wizard_date_to'):
99                 date_to = context['wizard_date_to']
100
101             if line.paid_date:
102                 if strToDate(date_to)<=strToDate(line.paid_date):
103                     theo_amt=0.00
104                 else:
105                     theo_amt=line.planned_amount
106             else:
107                 total=strToDate(line.date_to) - strToDate(line.date_from)
108                 elapsed = min(strToDate(line.date_to),strToDate(date_to)) - max(strToDate(line.date_from),strToDate(date_from))
109                 if strToDate(date_to) < strToDate(line.date_from):
110                     elapsed = strToDate(date_to) - strToDate(date_to)
111
112                 theo_amt=float(elapsed.days/float(total.days))*line.planned_amount
113
114             res[line.id]=theo_amt
115         return res
116
117     def _perc(self, cr, uid, ids,name,args,context):
118         res = {}
119         for line in self.browse(cr, uid, ids):
120             if line.theoritical_amount<>0.00:
121                 res[line.id]=float(line.practical_amount / line.theoritical_amount)*100
122             else:
123                 res[line.id]=0.00
124         return res
125     _name="crossovered.budget.lines"
126     _description = "Crossovered Budget Lines"
127     _columns = {
128         'crossovered_budget_id': fields.many2one('crossovered.budget', 'Budget Ref', ondelete='cascade', select=True, required=True),
129         'analytic_account_id': fields.many2one('account.analytic.account', 'Analytic Account Ref',required=True),
130         'general_budget_id': fields.many2one('account.budget.post', 'Master Budget Ref',required=True),
131         'date_from': fields.date('Start Date',required=True),
132         'date_to': fields.date('End Date',required=True),
133         'paid_date': fields.date('Paid Date'),
134         'planned_amount':fields.float('Planned Amount',required=True),
135         'practical_amount':fields.function(_pra_amt,method=True, string='Practical Amount',type='float'),
136         'theoritical_amount':fields.function(_theo_amt,method=True, string='Theoritical Amount',type='float'),
137         'percentage':fields.function(_perc,method=True, string='Percentage',type='float'),
138     }
139 crossovered_budget_lines()
140
141 class account_budget_post(osv.osv):
142     _name = 'account.budget.post'
143     _inherit = 'account.budget.post'
144     _columns = {
145     'crossovered_budget_line': fields.one2many('crossovered.budget.lines', 'general_budget_id', 'Budget Lines'),
146     }
147 account_budget_post()
148
149 class account_budget_post_dotation(osv.osv):
150     _name = 'account.budget.post.dotation'
151     _inherit = 'account.budget.post.dotation'
152
153     def _tot_planned(self, cr, uid, ids,name,args,context):
154         res={}
155         for line in self.browse(cr, uid, ids):
156             if line.period_id:
157                 obj_period=self.pool.get('account.period').browse(cr, uid,line.period_id.id)
158
159                 total_days=strToDate(obj_period.date_stop) - strToDate(obj_period.date_start)
160                 budget_id=line.post_id and line.post_id.id or False
161                 query="select id from crossovered_budget_lines where  general_budget_id= '"+ str(budget_id) + "' AND (date_from  >='"  +obj_period.date_start +"'  and date_from <= '"+obj_period.date_stop + "') OR (date_to  >='"  +obj_period.date_start +"'  and date_to <= '"+obj_period.date_stop + "') OR (date_from  <'"  +obj_period.date_start +"'  and date_to > '"+obj_period.date_stop + "')"
162                 cr.execute(query)
163                 res1=cr.fetchall()
164
165                 tot_planned=0.00
166                 for record in res1:
167                     obj_lines = self.pool.get('crossovered.budget.lines').browse(cr, uid,record[0])
168                     count_days = min(strToDate(obj_period.date_stop),strToDate(obj_lines.date_to)) - max(strToDate(obj_period.date_start), strToDate(obj_lines.date_from))
169                     days_in_period = count_days.days +1
170                     count_days = strToDate(obj_lines.date_to) - strToDate(obj_lines.date_from)
171                     total_days_of_rec = count_days.days +1
172                     tot_planned += obj_lines.planned_amount/total_days_of_rec* days_in_period
173                 res[line.id]=tot_planned
174             else:
175                 res[line.id]=0.00
176         return res
177
178     _columns = {
179     'tot_planned':fields.function(_tot_planned,method=True, string='Total Planned Amount',type='float',store=True),
180     }
181
182 account_budget_post_dotation()
183
184 class account_analytic_account(osv.osv):
185     _name = 'account.analytic.account'
186     _inherit = 'account.analytic.account'
187
188     _columns = {
189     'crossovered_budget_line': fields.one2many('crossovered.budget.lines', 'analytic_account_id', 'Budget Lines'),
190     }
191
192 account_analytic_account()
193
194
195 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
196