Bugfix :Problem of Report of Crossovered budget on account budget
[odoo/odoo.git] / addons / account_budget / 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 #moved from account/account.py
14 # ---------------------------------------------------------
15 # Budgets
16 # ---------------------------------------------------------
17 class account_budget_post(osv.osv):
18     _name = 'account.budget.post'
19     _description = 'Budget item'
20     _columns = {
21         'code': fields.char('Code', size=64, required=True),
22         'name': fields.char('Name', size=256, required=True),
23         'dotation_ids': fields.one2many('account.budget.post.dotation', 'post_id', 'Expenses'),
24         'account_ids': fields.many2many('account.account', 'account_budget_rel', 'budget_id', 'account_id', 'Accounts'),
25         'crossovered_budget_line': fields.one2many('crossovered.budget.lines', 'general_budget_id', 'Budget Lines'),
26     }
27     _defaults = {
28     }
29
30     def spread(self, cr, uid, ids, fiscalyear_id=False, amount=0.0):
31         dobj = self.pool.get('account.budget.post.dotation')
32         for o in self.browse(cr, uid, ids):
33             # delete dotations for this post
34             dobj.unlink(cr, uid, dobj.search(cr, uid, [('post_id','=',o.id)]))
35
36             # create one dotation per period in the fiscal year, and spread the total amount/quantity over those dotations
37             fy = self.pool.get('account.fiscalyear').browse(cr, uid, [fiscalyear_id])[0]
38             num = len(fy.period_ids)
39             for p in fy.period_ids:
40                 dobj.create(cr, uid, {'post_id': o.id, 'period_id': p.id, 'amount': amount/num})
41         return True
42 account_budget_post()
43
44 class account_budget_post_dotation(osv.osv):
45     def _tot_planned(self, cr, uid, ids,name,args,context):
46         res={}
47         for line in self.browse(cr, uid, ids):
48             if line.period_id:
49                 obj_period=self.pool.get('account.period').browse(cr, uid,line.period_id.id)
50
51                 total_days=strToDate(obj_period.date_stop) - strToDate(obj_period.date_start)
52                 budget_id=line.post_id and line.post_id.id or False
53                 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 + "')"
54                 cr.execute(query)
55                 res1=cr.fetchall()
56
57                 tot_planned=0.00
58                 for record in res1:
59                     obj_lines = self.pool.get('crossovered.budget.lines').browse(cr, uid,record[0])
60                     count_days = min(strToDate(obj_period.date_stop),strToDate(obj_lines.date_to)) - max(strToDate(obj_period.date_start), strToDate(obj_lines.date_from))
61                     days_in_period = count_days.days +1
62                     count_days = strToDate(obj_lines.date_to) - strToDate(obj_lines.date_from)
63                     total_days_of_rec = count_days.days +1
64                     tot_planned += obj_lines.planned_amount/total_days_of_rec* days_in_period
65                 res[line.id]=tot_planned
66             else:
67                 res[line.id]=0.00
68         return res
69
70     _name = 'account.budget.post.dotation'
71     _description = "Budget item endowment"
72     _columns = {
73         'name': fields.char('Name', size=64),
74         'post_id': fields.many2one('account.budget.post', 'Item', select=True),
75         'period_id': fields.many2one('account.period', 'Period'),
76 #       'quantity': fields.float('Quantity', digits=(16,2)),
77         'amount': fields.float('Amount', digits=(16,2)),
78         'tot_planned':fields.function(_tot_planned,method=True, string='Total Planned Amount',type='float',store=True),
79     }
80
81 account_budget_post_dotation()
82 #===
83
84 class crossovered_budget(osv.osv):
85     _name = "crossovered.budget"
86     _description = "Crossovered Budget"
87
88     _columns = {
89         'name': fields.char('Name', size=50, required=True,states={'done':[('readonly',True)]}),
90         'code': fields.char('Code', size=20, required=True,states={'done':[('readonly',True)]}),
91         'creating_user_id': fields.many2one('res.users','Responsible User'),
92         'validating_user_id': fields.many2one('res.users','Validate User', readonly=True),
93         'date_from': fields.date('Start Date',required=True,states={'done':[('readonly',True)]}),
94         'date_to': fields.date('End Date',required=True,states={'done':[('readonly',True)]}),
95         'state' : fields.selection([('draft','Draft'),('confirm','Confirmed'),('validate','Validated'),('done','Done'),('cancel', 'Cancelled')], 'Status', select=True, required=True, readonly=True),
96         'crossovered_budget_line': fields.one2many('crossovered.budget.lines', 'crossovered_budget_id', 'Budget Lines',states={'done':[('readonly',True)]} ),
97     }
98
99     _defaults = {
100         'state': lambda *a: 'draft',
101         'creating_user_id': lambda self,cr,uid,context: uid,
102     }
103
104 #   def action_set_to_draft(self, cr, uid, ids, *args):
105 #       self.write(cr, uid, ids, {'state': 'draft'})
106 #       wf_service = netsvc.LocalService('workflow')
107 #       for id in ids:
108 #           wf_service.trg_create(uid, self._name, id, cr)
109 #       return True
110
111     def budget_confirm(self, cr, uid, ids, *args):
112         self.write(cr, uid, ids, {
113             'state':'confirm'
114         })
115         return True
116
117     def budget_validate(self, cr, uid, ids, *args):
118         self.write(cr, uid, ids, {
119             'state':'validate',
120             'validating_user_id': uid,
121         })
122         return True
123
124     def budget_cancel(self, cr, uid, ids, *args):
125
126         self.write(cr, uid, ids, {
127             'state':'cancel'
128         })
129         return True
130
131     def budget_done(self, cr, uid, ids, *args):
132         self.write(cr, uid, ids, {
133             'state':'done'
134         })
135         return True
136
137 crossovered_budget()
138
139 class crossovered_budget_lines(osv.osv):
140
141     def _prac_amt(self, cr, uid, ids,context={}):
142         res = {}
143         for line in self.browse(cr, uid, ids):
144             acc_ids = ','.join([str(x.id) for x in line.general_budget_id.account_ids])
145             if not acc_ids:
146                 raise osv.except_osv('Error!',"The General Budget '" + str(line.general_budget_id.name) + "' has no Accounts!" )
147             date_to = line.date_to
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             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))
154             result=cr.fetchone()[0]
155             if result==None:
156                 result=0.00
157             res[line.id]=result
158         return res
159
160     def _prac(self, cr, uid, ids,name,args,context):
161         res={}
162         for line in self.browse(cr, uid, ids):
163             res[line.id]=self._prac_amt(cr,uid,[line.id],context=context)[line.id]
164
165         return res
166
167     def _theo_amt(self, cr, uid, ids,context={}):
168         res = {}
169         for line in self.browse(cr, uid, ids):
170             today=datetime.datetime.today()
171             date_to = today.strftime("%Y-%m-%d")
172             date_from = line.date_from
173             if context.has_key('wizard_date_from'):
174                 date_from = context['wizard_date_from']
175             if context.has_key('wizard_date_to'):
176                 date_to = context['wizard_date_to']
177
178             if line.paid_date:
179                 if strToDate(date_to)<=strToDate(line.paid_date):
180                     theo_amt=0.00
181                 else:
182                     theo_amt=line.planned_amount
183             else:
184                 total=strToDate(line.date_to) - strToDate(line.date_from)
185                 elapsed = min(strToDate(line.date_to),strToDate(date_to)) - max(strToDate(line.date_from),strToDate(date_from))
186                 if strToDate(date_to) < strToDate(line.date_from):
187                     elapsed = strToDate(date_to) - strToDate(date_to)
188
189                 theo_amt=float(elapsed.days/float(total.days))*line.planned_amount
190
191             res[line.id]=theo_amt
192         return res
193
194     def _theo(self, cr, uid, ids,name,args,context):
195         res={}
196         for line in self.browse(cr, uid, ids):
197             res[line.id]=self._theo_amt(cr,uid,[line.id],context=context)[line.id]
198
199         return res
200
201     def _perc(self, cr, uid, ids,name,args,context):
202         res = {}
203         for line in self.browse(cr, uid, ids):
204             if line.theoritical_amount<>0.00:
205                 res[line.id]=float(line.practical_amount / line.theoritical_amount)*100
206             else:
207                 res[line.id]=0.00
208         return res
209     _name="crossovered.budget.lines"
210     _description = "Crossovered Budget Lines"
211     _columns = {
212         'crossovered_budget_id': fields.many2one('crossovered.budget', 'Budget Ref', ondelete='cascade', select=True, required=True),
213         'analytic_account_id': fields.many2one('account.analytic.account', 'Analytic Account Ref',required=True),
214         'general_budget_id': fields.many2one('account.budget.post', 'Master Budget Ref',required=True),
215         'date_from': fields.date('Start Date',required=True),
216         'date_to': fields.date('End Date',required=True),
217         'paid_date': fields.date('Paid Date'),
218         'planned_amount':fields.float('Planned Amount',required=True),
219         'practical_amount':fields.function(_prac,method=True, string='Practical Amount',type='float'),
220         'theoritical_amount':fields.function(_theo,method=True, string='Theoritical Amount',type='float'),
221         'percentage':fields.function(_perc,method=True, string='Percentage',type='float'),
222     }
223 crossovered_budget_lines()
224
225 class account_analytic_account(osv.osv):
226     _name = 'account.analytic.account'
227     _inherit = 'account.analytic.account'
228
229     _columns = {
230     'crossovered_budget_line': fields.one2many('crossovered.budget.lines', 'analytic_account_id', 'Budget Lines'),
231     }
232
233 account_analytic_account()
234
235 #--------------------------------------------------------------
236 # moved from account/project/project.py
237 # ---------------------------------------------------------
238 # Budgets.
239 # ---------------------------------------------------------
240
241 #class account_analytic_budget_post(osv.osv):
242 #   _name = 'account.analytic.budget.post'
243 #   _description = 'Budget item'
244 #   _columns = {
245 #       'code': fields.char('Code', size=64, required=True),
246 #       'name': fields.char('Name', size=256, required=True),
247 #       'sens': fields.selection( [('charge','Charge'), ('produit','Product')], 'Direction', required=True),
248 #       'dotation_ids': fields.one2many('account.analytic.budget.post.dotation', 'post_id', 'Expenses'),
249 #       'account_ids': fields.many2many('account.analytic.account', 'account_analytic_budget_rel', 'budget_id', 'account_id', 'Accounts'),
250 #   }
251 #   _defaults = {
252 #       'sens': lambda *a: 'produit',
253 #   }
254 #
255 #   def spread(self, cr, uid, ids, fiscalyear_id=False, quantity=0.0, amount=0.0):
256 #
257 #       dobj = self.pool.get('account.analytic.budget.post.dotation')
258 #       for o in self.browse(cr, uid, ids):
259 #           # delete dotations for this post
260 #           dobj.unlink(cr, uid, dobj.search(cr, uid, [('post_id','=',o.id)]))
261 #
262 #           # create one dotation per period in the fiscal year, and spread the total amount/quantity over those dotations
263 #           fy = self.pool.get('account.fiscalyear').browse(cr, uid, [fiscalyear_id])[0]
264 #           num = len(fy.period_ids)
265 #           for p in fy.period_ids:
266 #               dobj.create(cr, uid, {'post_id': o.id, 'period_id': p.id, 'quantity': quantity/num, 'amount': amount/num})
267 #       return True
268 #account_analytic_budget_post()
269 #
270 #class account_analytic_budget_post_dotation(osv.osv):
271 #   _name = 'account.analytic.budget.post.dotation'
272 #   _description = "Budget item endowment"
273 #   _columns = {
274 #       'name': fields.char('Name', size=64),
275 #       'post_id': fields.many2one('account.analytic.budget.post', 'Item', select=True),
276 #       'period_id': fields.many2one('account.period', 'Period'),
277 #       'quantity': fields.float('Quantity', digits=(16,2)),
278 #       'amount': fields.float('Amount', digits=(16,2)),
279 #   }
280 #account_analytic_budget_post_dotation()
281
282 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
283