1 # -*- encoding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
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.
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.
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/>.
20 ##############################################################################
23 from datetime import datetime
24 from dateutil.relativedelta import relativedelta
26 from osv import osv, fields
27 import decimal_precision as dp
29 class account_asset_category(osv.osv):
30 _name = 'account.asset.category'
31 _description = 'Asset category'
34 'name': fields.char('Name', size=64, required=True, select=1),
35 'note': fields.text('Note'),
36 'journal_analytic_id': fields.many2one('account.analytic.journal', 'Analytic journal'),
37 'account_analytic_id': fields.many2one('account.analytic.account', 'Analytic account'),
38 'account_asset_id': fields.many2one('account.account', 'Asset Account', required=True),
39 'account_depreciation_id': fields.many2one('account.account', 'Depreciation Account', required=True),
40 'account_expense_depreciation_id': fields.many2one('account.account', 'Depr. Expense Account', required=True),
41 'journal_id': fields.many2one('account.journal', 'Journal', required=True),
42 'company_id': fields.many2one('res.company', 'Company', required=True),
43 'method': fields.selection([('linear','Linear'),('progressif','Progressive')], 'Computation method', required=True),
44 'method_delay': fields.integer('Number of Depreciation'),
45 'method_period': fields.integer('Period Length'),
46 'method_progress_factor': fields.float('Progressif Factor'),
47 'method_time': fields.selection([('delay','Delay'),('end','Ending Period')], 'Time Method', required=True),
48 'method_end': fields.date('Ending date'),
49 'prorata':fields.boolean('Prorata Temporis', help='Indicates that the accounting entries for this asset have to be done from the purchase date instead of the first January'),
50 'open_asset': fields.boolean('Skip Draft State', help="Check this if you want to automatically confirm the assets of this category when created by invoice."),
54 'company_id': lambda self, cr, uid, context: self.pool.get('res.company')._company_default_get(cr, uid, 'account.asset.category', context=context),
57 'method_time': 'delay',
59 'method_progress_factor': 0.3,
62 account_asset_category()
64 #class one2many_mod_asset(fields.one2many):
66 # def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
67 # prinasset_property_id if context is None:
74 # #compute depreciation board
75 # depreciation_line_ids = obj.pool.get('account.asset.asset').compute_depreciation_board(cr, user, ids, context=context)
76 # for key, value in depreciation_line_ids.items():
77 # #write values on asset
78 # obj.pool.get(self._obj).write(cr, user, key, {'depreciation_line_ids': [6,0,value]})
79 # return depreciation_line_ids
81 class account_asset_asset(osv.osv):
82 _name = 'account.asset.asset'
83 _description = 'Asset'
85 def _get_period(self, cr, uid, context={}):
86 periods = self.pool.get('account.period').find(cr, uid)
92 def _get_last_depreciation_date(self, cr, uid, ids, context=None):
94 @param id: ids of a account.asset.asset objects
95 @return: Returns a dictionary of the effective dates of the last depreciation entry made for given asset ids. If there isn't any, return the purchase date of this asset
98 SELECT a.id as id, COALESCE(MAX(l.date),a.purchase_date) AS date
99 FROM account_asset_asset a
100 LEFT JOIN account_move_line l ON (l.asset_id = a.id)
102 GROUP BY a.id, a.purchase_date """, (tuple(ids),))
103 return dict(cr.fetchall())
105 def compute_depreciation_board(self, cr, uid,ids, context=None):
106 depreciation_lin_obj = self.pool.get('account.asset.depreciation.line')
107 for asset in self.browse(cr, uid, ids, context=context):
108 old_depreciation_line_ids = depreciation_lin_obj.search(cr, uid, [('asset_id', '=', asset.id), ('move_id', '=', False)])
109 if old_depreciation_line_ids:
110 depreciation_lin_obj.unlink(cr, uid, old_depreciation_line_ids, context=context)
112 amount_to_depr = residual_amount = asset.value_residual
113 depreciation_date = datetime.strptime(self._get_last_depreciation_date(cr, uid, [asset.id], context)[asset.id], '%Y-%m-%d')
114 day = depreciation_date.day
115 month = depreciation_date.month
116 year = depreciation_date.year
117 total_days = (year % 4) and 365 or 366
118 if asset.account_move_line_ids:
119 add_months = asset.method_period * len(asset.account_move_line_ids)
120 depreciation_date = (datetime(year, month, day) + relativedelta(months=+add_months))
122 undone_dotation_number = asset.method_delay - len(asset.account_move_line_ids)
123 if asset.method_time == 'end':
124 end_date = datetime.strptime(asset.method_end, '%Y-%m-%d')
125 undone_dotation_number = (end_date - depreciation_date).days / total_days
126 if asset.prorata or asset.method_time == 'end':
127 undone_dotation_number += 1
129 for i in range(1, undone_dotation_number+1):
130 if i == undone_dotation_number + 1:
131 amount = residual_amount
133 if asset.method == 'linear':
134 amount = amount_to_depr / undone_dotation_number
136 amount = amount_to_depr / asset.method_delay
138 days = total_days - float(depreciation_date.strftime('%j'))
139 amount = (amount_to_depr / asset.method_delay) / total_days * days
140 elif i == undone_dotation_number:
141 amount = (amount_to_depr / asset.method_delay) / total_days * (total_days - days)
143 amount = residual_amount * asset.method_progress_factor
144 residual_amount -= amount
147 'asset_id': asset.id,
149 'name': str(asset.id) +'/' + str(i),
150 'remaining_value': residual_amount,
151 'depreciated_value': amount_to_depr - residual_amount,
152 'depreciation_date': depreciation_date.strftime('%Y-%m-%d'),
154 depreciation_lin_obj.create(cr, uid, vals, context=context)
156 # Considering Depr. Period as months
157 day = depreciation_date.day
158 month = depreciation_date.month
159 year = depreciation_date.year
160 depreciation_date = (datetime(year, month, day) + relativedelta(months=+asset.method_period))
164 def validate(self, cr, uid, ids, context={}):
165 return self.write(cr, uid, ids, {
169 def _amount_residual(self, cr, uid, ids, name, args, context=None):
171 l.asset_id as id, round(SUM(abs(l.debit-l.credit))) AS amount
175 l.asset_id IN %s GROUP BY l.asset_id """, (tuple(ids),))
176 res=dict(cr.fetchall())
177 for asset in self.browse(cr, uid, ids, context):
178 res[asset.id] = asset.purchase_value - res.get(asset.id, 0.0) - asset.salvage_value
180 res.setdefault(id, 0.0)
184 'period_id': fields.many2one('account.period', 'First Period', required=True, readonly=True, states={'draft':[('readonly',False)]}),
185 'account_move_line_ids': fields.one2many('account.move.line', 'asset_id', 'Entries', readonly=True, states={'draft':[('readonly',False)]}),
187 'name': fields.char('Asset', size=64, required=True, select=1),
188 'code': fields.char('Reference ', size=16, select=1),
189 'purchase_value': fields.float('Gross value ', required=True, size=16, select=1),
190 'currency_id': fields.many2one('res.currency','Currency',required=True,size=5,select=1),
191 'company_id': fields.many2one('res.company', 'Company', required=True),
192 'note': fields.text('Note'),
193 'category_id': fields.many2one('account.asset.category', 'Asset category',required=True, change_default=True),
194 'localisation': fields.char('Localisation', size=32, select=2),
195 'parent_id': fields.many2one('account.asset.asset', 'Parent Asset'),
196 'child_ids': fields.one2many('account.asset.asset', 'parent_id', 'Children Assets'),
197 'purchase_date': fields.date('Purchase Date', required=True),
198 'state': fields.selection([('draft','Draft'),('open','Running'),('close','Close')], 'state', required=True),
199 'active': fields.boolean('Active', select=2),
200 'partner_id': fields.many2one('res.partner', 'Partner'),
202 'method': fields.selection([('linear','Linear'),('progressif','Progressive')], 'Computation method', required=True, readonly=True, states={'draft':[('readonly',False)]}),
203 'method_delay': fields.integer('During (interval)', readonly=True, states={'draft':[('readonly',False)]}),
204 'method_period': fields.integer('Depre. all (period)', readonly=True, states={'draft':[('readonly',False)]}),
205 'method_end': fields.date('Ending date', readonly=True, states={'draft':[('readonly',False)]}),
206 'method_progress_factor': fields.float('Progressif Factor', readonly=True, states={'draft':[('readonly',False)]}),
207 'value_residual': fields.function(_amount_residual, method=True, digits_compute=dp.get_precision('Account'), string='Residual Value'),
208 'method_time': fields.selection([('delay','Delay'),('end','Ending Period')], 'Time Method', required=True, readonly=True, states={'draft':[('readonly',False)]}),
209 'prorata':fields.boolean('Prorata Temporis', Readonly="True", help='Indicates that the accounting entries for this asset have to be done from the purchase date instead of the first January'),
210 'history_ids': fields.one2many('account.asset.history', 'asset_id', 'History', readonly=True),
211 'depreciation_line_ids': fields.one2many('account.asset.depreciation.line', 'asset_id', 'Depreciation Lines'),
212 'salvage_value': fields.float('Salvage Value', digits_compute=dp.get_precision('Account'), help="It is the amount you plan to have that you cannot depreciate."),
215 'code': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'account.asset.code'),
216 'purchase_date': lambda obj, cr, uid, context: time.strftime('%Y-%m-%d'),
217 'active': lambda obj, cr, uid, context: True,
218 'state': lambda obj, cr, uid, context: 'draft',
219 'period_id': _get_period,
220 'method': lambda obj, cr, uid, context: 'linear',
221 'method_delay': lambda obj, cr, uid, context: 5,
222 'method_time': lambda obj, cr, uid, context: 'delay',
223 'method_period': lambda obj, cr, uid, context: 12,
224 'method_progress_factor': lambda obj, cr, uid, context: 0.3,
225 'currency_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.currency_id.id,
226 'company_id': lambda self, cr, uid, context: self.pool.get('res.company')._company_default_get(cr, uid, 'account.asset.asset',context=context),
229 def _check_prorata(self, cr, uid, ids, context=None):
230 for asset in self.browse(cr, uid, ids, context=context):
231 if asset.prorata and (asset.method != 'linear' or asset.method_time != 'delay'):
236 (_check_prorata, '\nProrata temporis can be applied only for computation method linear and time method delay.', ['prorata']),
239 def onchange_category_id(self, cr, uid, ids, category_id, context=None):
241 asset_categ_obj = self.pool.get('account.asset.category')
243 category_obj = asset_categ_obj.browse(cr, uid, category_id, context=context)
245 'method': category_obj.method,
246 'method_delay': category_obj.method_delay,
247 'method_time': category_obj.method_time,
248 'method_period': category_obj.method_period,
249 'method_progress_factor': category_obj.method_progress_factor,
250 'method_end': category_obj.method_end,
251 'prorata': category_obj.prorata,
255 def onchange_method_time(self, cr, uid, ids, method='linear', method_time='delay', context=None):
257 if method != 'linear' or method_time != 'delay':
258 res['value'] = {'prorata': False}
261 def copy(self, cr, uid, id, default=None, context=None):
266 default.update({'depreciation_line_ids': [], 'state': 'draft'})
267 return super(account_asset_asset, self).copy(cr, uid, id, default, context=context)
269 def _compute_period(self, cr, uid, property, context={}):
270 if (len(property.entry_asset_ids or [])/2)>=property.method_delay:
272 if len(property.entry_asset_ids):
273 cp = property.entry_asset_ids[-1].period_id
274 cpid = self.pool.get('account.period').next(cr, uid, cp, property.method_period, context)
275 current_period = self.pool.get('account.period').browse(cr, uid, cpid, context)
277 current_period = property.asset_id.period_id
278 return current_period
280 def _compute_move(self, cr, uid, property, period, context={}):
281 #FIXME: fucntion not working OK
284 for move in property.asset_id.entry_ids:
285 total += move.debit-move.credit
286 for move in property.entry_asset_ids:
287 if move.account_id == property.account_asset_ids:
289 total += -move.credit
290 periods = (len(property.entry_asset_ids)/2) - property.method_delay
295 if property.method == 'linear':
296 amount = total / periods
298 amount = total * property.method_progress_factor
300 move_id = self.pool.get('account.move').create(cr, uid, {
301 'journal_id': property.journal_id.id,
302 'period_id': period.id,
303 'name': property.name or property.asset_id.name,
304 'ref': property.asset_id.code
307 id = self.pool.get('account.move.line').create(cr, uid, {
308 'name': property.name or property.asset_id.name,
310 'account_id': property.account_asset_id.id,
311 'debit': amount>0 and amount or 0.0,
312 'credit': amount<0 and -amount or 0.0,
313 'ref': property.asset_id.code,
314 'period_id': period.id,
315 'journal_id': property.journal_id.id,
316 'partner_id': property.asset_id.partner_id.id,
317 'date': time.strftime('%Y-%m-%d'),
319 id2 = self.pool.get('account.move.line').create(cr, uid, {
320 'name': property.name or property.asset_id.name,
322 'account_id': property.account_actif_id.id,
323 'credit': amount>0 and amount or 0.0,
324 'debit': amount<0 and -amount or 0.0,
325 'ref': property.asset_id.code,
326 'period_id': period.id,
327 'journal_id': property.journal_id.id,
328 'partner_id': property.asset_id.partner_id.id,
329 'date': time.strftime('%Y-%m-%d'),
332 self.pool.get('account.asset.asset').write(cr, uid, [property.id], {
333 'entry_asset_ids': [(4, id2, False),(4,id,False)]
335 if property.method_delay - (len(property.entry_asset_ids)/2)<=1:
336 #self.pool.get('account.asset.property')._close(cr, uid, property, context)
340 def _compute_entries(self, cr, uid, asset, period_id, context={}):
341 #FIXME: function not working CHECK all res
343 date_start = self.pool.get('account.period').browse(cr, uid, period_id, context).date_start
344 for property in asset.property_ids:
345 if property.state=='open':
346 period = self._compute_period(cr, uid, property, context)
347 if period and (period.date_start<=date_start):
348 result += self._compute_move(cr, uid, property, period, context)
350 account_asset_asset()
352 class account_asset_depreciation_line(osv.osv):
353 _name = 'account.asset.depreciation.line'
354 _description = 'Asset depreciation line'
356 def _get_move_check(self, cr, uid, ids, name, args, context=None):
358 for line in self.browse(cr, uid, ids, context=context):
359 res[line.id] = bool(line.move_id)
363 'name': fields.char('Depreciation Name', size=64, required=True, select=1),
364 'sequence': fields.integer('Sequence of the depreciation', required=True),
365 'asset_id': fields.many2one('account.asset.asset', 'Asset', required=True),
366 'amount': fields.float('Depreciation Amount', required=True),
367 'remaining_value': fields.float('Amount to Depreciate', required=True),
368 'depreciated_value': fields.float('Amount Already Depreciated', required=True),
369 'depreciation_date': fields.char('Depreciation Date', size=64, select=1),
370 'move_id': fields.many2one('account.move', 'Depreciation Entry'),
371 'move_check': fields.function(_get_move_check, method=True, type='boolean', string='Posted', store=True)
374 def create_move(self, cr, uid,ids, context=None):
377 asset_obj = self.pool.get('account.asset.asset')
378 period_obj = self.pool.get('account.period')
379 move_obj = self.pool.get('account.move')
380 move_line_obj = self.pool.get('account.move.line')
381 currency_obj = self.pool.get('res.currency')
382 for line in self.browse(cr, uid, ids, context=context):
383 depreciation_date = line.asset_id.prorata and line.asset_id.purchase_date or time.strftime('%Y-%m-%d')
384 period_ids = period_obj.find(cr, uid, depreciation_date, context=context)
385 company_currency = line.asset_id.company_id.currency_id.id
386 current_currency = line.asset_id.currency_id.id
387 context.update({'date': depreciation_date})
388 amount = currency_obj.compute(cr, uid, current_currency, company_currency, line.amount, context=context)
389 sign = line.asset_id.category_id.journal_id.type = 'purchase' and 1 or -1
392 'date': depreciation_date,
394 'period_id': period_ids and period_ids[0] or False,
395 'journal_id': line.asset_id.category_id.journal_id.id,
397 move_id = move_obj.create(cr, uid, move_vals, context=context)
398 move_line_obj.create(cr, uid, {
402 'account_id': line.asset_id.category_id.account_depreciation_id.id,
405 'period_id': period_ids and period_ids[0] or False,
406 'journal_id': line.asset_id.category_id.journal_id.id,
407 'partner_id': line.asset_id.partner_id.id,
408 'currency_id': company_currency <> current_currency and current_currency or False,
409 'amount_currency': company_currency <> current_currency and - sign * line.amount or 0.0,
410 'analytic_account_id': line.asset_id.category_id.account_analytic_id.id,
411 'date': depreciation_date,
413 move_line_obj.create(cr, uid, {
417 'account_id': line.asset_id.category_id.account_expense_depreciation_id.id,
420 'period_id': period_ids and period_ids[0] or False,
421 'journal_id': line.asset_id.category_id.journal_id.id,
422 'partner_id': line.asset_id.partner_id.id,
423 'currency_id': company_currency <> current_currency and current_currency or False,
424 'amount_currency': company_currency <> current_currency and sign * line.amount or 0.0,
425 'analytic_account_id': line.asset_id.category_id.account_analytic_id.id,
426 'date': depreciation_date,
427 'asset_id': line.asset_id.id
429 self.write(cr, uid, line.id, {'move_id': move_id}, context=context)
432 account_asset_depreciation_line()
434 #class account_asset_property(osv.osv):
435 # def _amount_total(self, cr, uid, ids, name, args, context={}):
436 # id_set=",".join(map(str,ids))
437 # cr.execute("""SELECT l.asset_id,abs(SUM(l.debit-l.credit)) AS amount FROM
438 # account_asset_property p
440 # account_move_line l on (p.asset_id=l.asset_id)
441 # WHERE p.id IN ("""+id_set+") GROUP BY l.asset_id ")
442 # res=dict(cr.fetchall())
444 # res.setdefault(id, 0.0)
447 # def _close(self, cr, uid, property, context={}):
448 # if property.state<>'close':
449 # self.pool.get('account.asset.property').write(cr, uid, [property.id], {
452 # property.state='close'
453 # ok = property.asset_id.state=='open'
454 # for prop in property.asset_id.property_ids:
455 # ok = ok and prop.state=='close'
456 # self.pool.get('account.asset.asset').write(cr, uid, [property.asset_id.id], {
461 # _name = 'account.asset.property'
462 # _description = 'Asset property'
464 # 'name': fields.char('Method name', size=64, select=1),
465 # 'type': fields.selection([('direct','Direct'),('indirect','Indirect')], 'Depr. method type', select=2, required=True),
466 # 'asset_id': fields.many2one('account.asset.asset', 'Asset', required=True),
467 # 'account_asset_id': fields.many2one('account.account', 'Asset account', required=True),
468 # 'account_actif_id': fields.many2one('account.account', 'Depreciation account', required=True),
469 # 'journal_id': fields.many2one('account.journal', 'Journal', required=True),
470 # 'journal_analytic_id': fields.many2one('account.analytic.journal', 'Analytic journal'),
471 # 'account_analytic_id': fields.many2one('account.analytic.account', 'Analytic account'),
473 # 'method': fields.selection([('linear','Linear'),('progressif','Progressive')], 'Computation method', required=True, readonly=True, states={'draft':[('readonly',False)]}),
474 # 'method_delay': fields.integer('During', readonly=True, states={'draft':[('readonly',False)]}),
475 # 'method_period': fields.integer('Depre. all', readonly=True, states={'draft':[('readonly',False)]}),
476 # 'method_end': fields.date('Ending date'),
478 # 'date': fields.date('Date created'),
479 # #'test': fields.one2many('account.pre', 'asset_id', readonly=True, states={'draft':[('readonly',False)]}),
480 # 'entry_asset_ids': fields.many2many('account.move.line', 'account_move_asset_entry_rel', 'asset_property_id', 'move_id', 'Asset Entries'),
481 # 'board_ids': fields.one2many('account.asset.board', 'asset_id', 'Asset board'),
483 # 'value_total': fields.function(_amount_total, method=True, digits=(16,2),string='Gross value'),
484 # 'state': fields.selection([('draft','Draft'), ('open','Open'), ('close','Close')], 'State', required=True),
485 # 'history_ids': fields.one2many('account.asset.property.history', 'asset_property_id', 'History', readonly=True)
486 ## 'parent_id': fields.many2one('account.asset.asset', 'Parent asset'),
487 ## 'partner_id': fields.many2one('res.partner', 'Partner'),
488 ## 'note': fields.text('Note'),
492 # 'type': lambda obj, cr, uid, context: 'direct',
493 # 'state': lambda obj, cr, uid, context: 'draft',
494 # 'method': lambda obj, cr, uid, context: 'linear',
495 # 'method_time': lambda obj, cr, uid, context: 'delay',
496 # 'method_progress_factor': lambda obj, cr, uid, context: 0.3,
497 # 'method_delay': lambda obj, cr, uid, context: 5,
498 # 'method_period': lambda obj, cr, uid, context: 12,
499 # 'date': lambda obj, cr, uid, context: time.strftime('%Y-%m-%d')
501 #account_asset_property()
503 class account_move_line(osv.osv):
504 _inherit = 'account.move.line'
506 'asset_id': fields.many2one('account.asset.asset', 'Asset'),
507 'entry_ids': fields.one2many('account.move.line', 'asset_id', 'Entries', readonly=True, states={'draft':[('readonly',False)]}),
512 class account_asset_history(osv.osv):
513 _name = 'account.asset.history'
514 _description = 'Asset history'
516 'name': fields.char('History name', size=64, select=1),
517 'user_id': fields.many2one('res.users', 'User', required=True),
518 'date': fields.date('Date', required=True),
519 'asset_id': fields.many2one('account.asset.asset', 'Asset', required=True),
520 'method_delay': fields.integer('Number of interval'),
521 'method_period': fields.integer('Period per interval'),
522 'method_end': fields.date('Ending date'),
523 'note': fields.text('Note'),
526 'date': lambda *args: time.strftime('%Y-%m-%d'),
527 'user_id': lambda self,cr, uid,ctx: uid
529 account_asset_history()
531 class account_asset_board(osv.osv):
532 _name = 'account.asset.board'
533 _description = 'Asset board'
535 'name': fields.char('Asset name', size=64, required=True, select=1),
536 'asset_id': fields.many2one('account.asset.asset', 'Asset', required=True, select=1),
537 'value_gross': fields.float('Gross value', required=True, select=1),
538 'value_asset': fields.float('Asset Value', required=True, select=1),
539 'value_asset_cumul': fields.float('Cumul. value', required=True, select=1),
540 'value_net': fields.float('Net value', required=True, select=1),
546 create or replace view account_asset_board as (
549 min(l.id) as asset_id,
552 0.0 as value_asset_cumul,
557 l.state <> 'draft' and
560 account_asset_board()
562 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: