forked from acsone/account-financial-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
account_asset.py
1722 lines (1623 loc) · 73.3 KB
/
account_asset.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
#
# Copyright (C) 2010-2012 OpenERP s.a. (<http://openerp.com>).
# Copyright (c) 2014 Noviat nv/sa (www.noviat.com). All rights reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import time
import calendar
from datetime import datetime
from dateutil.relativedelta import relativedelta
from openerp.osv import fields, orm
from openerp.addons.decimal_precision import decimal_precision as dp
from openerp import tools
from openerp.tools.translate import _
from openerp import SUPERUSER_ID
import logging
_logger = logging.getLogger(__name__)
class dummy_fy(object):
def __init__(self, *args, **argv):
for key, arg in argv.items():
setattr(self, key, arg)
class account_asset_category(orm.Model):
_name = 'account.asset.category'
_description = 'Asset category'
_order = 'name'
def _get_method(self, cr, uid, context=None):
return[
('linear', _('Linear')),
('degressive', _('Degressive')),
('degr-linear', _('Degressive-Linear'))
]
def _get_method_time(self, cr, uid, context=None):
return [
('year', _('Number of Years')),
# ('number', _('Number of Depreciations')),
# ('end', _('Ending Date'))
]
def _get_company(self, cr, uid, context=None):
return self.pool.get('res.company')._company_default_get(
cr, uid, 'account.asset.category', context=context)
_columns = {
'name': fields.char('Name', size=64, required=True, select=1),
'note': fields.text('Note'),
'account_analytic_id': fields.many2one(
'account.analytic.account', 'Analytic account',
domain=[('type', '!=', 'view'),
('state', 'not in', ('close', 'cancelled'))]),
'account_asset_id': fields.many2one(
'account.account', 'Asset Account', required=True,
domain=[('type', '=', 'other')]),
'account_depreciation_id': fields.many2one(
'account.account', 'Depreciation Account', required=True,
domain=[('type', '=', 'other')]),
'account_expense_depreciation_id': fields.many2one(
'account.account', 'Depr. Expense Account', required=True,
domain=[('type', '=', 'other')]),
'account_plus_value_id': fields.many2one(
'account.account', 'Plus-Value Account',
domain=[('type', '=', 'other')]),
'account_min_value_id': fields.many2one(
'account.account', 'Min-Value Account',
domain=[('type', '=', 'other')]),
'account_residual_value_id': fields.many2one(
'account.account', 'Residual Value Account',
domain=[('type', '=', 'other')]),
'journal_id': fields.many2one(
'account.journal', 'Journal', required=True),
'company_id': fields.many2one(
'res.company', 'Company', required=True),
'parent_id': fields.many2one(
'account.asset.asset',
'Parent Asset',
domain=[('type', '=', 'view')]),
'method': fields.selection(
_get_method, 'Computation Method',
required=True,
help="Choose the method to use to compute "
"the amount of depreciation lines.\n"
" * Linear: Calculated on basis of: "
"Gross Value / Number of Depreciations\n"
" * Degressive: Calculated on basis of: "
"Residual Value * Degressive Factor"
" * Degressive-Linear (only for Time Method = Year): "
"Degressive becomes linear when the annual linear "
"depreciation exceeds the annual degressive depreciation"),
'method_number': fields.integer(
'Number of Years',
help="The number of years needed to depreciate your asset"),
'method_period': fields.selection([
('month', 'Month'),
('quarter', 'Quarter'),
('year', 'Year'),
], 'Period Length', required=True,
help="Period length for the depreciation accounting entries"),
'method_progress_factor': fields.float('Degressive Factor'),
'method_time': fields.selection(
_get_method_time,
'Time Method', required=True,
help="Choose the method to use to compute the dates and "
"number of depreciation lines.\n"
" * Number of Years: Specify the number of years "
"for the depreciation.\n"
# " * Number of Depreciations: Fix the number of "
# "depreciation lines and the time between 2 depreciations.\n"
# " * Ending Date: Choose the time between 2 depreciations "
# "and the date the depreciations won't go beyond."
),
'prorata': fields.boolean(
'Prorata Temporis',
help="Indicates that the first depreciation entry for this asset "
"has to be done from the depreciation start date instead of "
"the first day of the fiscal year."),
'open_asset': fields.boolean(
'Skip Draft State',
help="Check this if you want to automatically confirm the assets "
"of this category when created by invoices."),
'active': fields.boolean('Active'),
}
_defaults = {
'active': 1,
'company_id': _get_company,
'method': 'linear',
'method_number': 5,
'method_time': 'year',
'method_period': 'year',
'method_progress_factor': 0.3,
}
def _check_method(self, cr, uid, ids, context=None):
for asset in self.browse(cr, uid, ids, context=context):
if asset.method == 'degr-linear' and asset.method_time != 'year':
return False
return True
_constraints = [(
_check_method,
"Degressive-Linear is only supported for Time Method = Year.",
['method']
)]
def onchange_method_time(self, cr, uid, ids,
method_time='number', context=None):
res = {'value': {}}
if method_time != 'year':
res['value'] = {'prorata': True}
return res
def create(self, cr, uid, vals, context=None):
if vals.get('method_time') != 'year' and not vals.get('prorata'):
vals['prorata'] = True
categ_id = super(account_asset_category, self).create(
cr, uid, vals, context=context)
acc_obj = self.pool.get('account.account')
acc_id = vals.get('account_asset_id')
if acc_id:
account = acc_obj.browse(cr, uid, acc_id)
if not account.asset_category_id:
acc_obj.write(
cr, uid, [acc_id], {'asset_category_id': categ_id})
return categ_id
def write(self, cr, uid, ids, vals, context=None):
if isinstance(ids, (int, long)):
ids = [ids]
if vals.get('method_time'):
if vals['method_time'] != 'year' and not vals.get('prorata'):
vals['prorata'] = True
super(account_asset_category, self).write(cr, uid, ids, vals, context)
acc_obj = self.pool.get('account.account')
for categ in self.browse(cr, uid, ids, context):
acc_id = vals.get('account_asset_id')
if acc_id:
account = acc_obj.browse(cr, uid, acc_id)
if not account.asset_category_id:
acc_obj.write(
cr, uid, [acc_id], {'asset_category_id': categ.id})
return True
class account_asset_recompute_trigger(orm.Model):
_name = 'account.asset.recompute.trigger'
_description = "Asset table recompute triggers"
_columns = {
'reason': fields.char(
'Reason', size=64, required=True),
'company_id': fields.many2one(
'res.company', 'Company', required=True),
'date_trigger': fields.datetime(
'Trigger Date',
readonly=True,
help="Date of the event triggering the need to "
"recompute the Asset Tables."),
'date_completed': fields.datetime(
'Completion Date', readonly=True),
'state': fields.selection(
[('open', 'Open'), ('done', 'Done')],
'State',
readonly=True),
}
_defaults = {
'state': 'open',
}
class account_asset_asset(orm.Model):
_name = 'account.asset.asset'
_description = 'Asset'
_order = 'date_start desc, name'
_parent_store = True
def unlink(self, cr, uid, ids, context=None):
for asset in self.browse(cr, uid, ids, context=context):
if asset.state != 'draft':
raise orm.except_orm(
_('Invalid action!'),
_("You can only delete assets in draft state."))
if asset.account_move_line_ids:
raise orm.except_orm(
_('Error!'),
_("You cannot delete an asset that contains "
"posted depreciation lines."))
parent = asset.parent_id
super(account_asset_asset, self).unlink(
cr, uid, [asset.id], context=context)
if parent:
# Trigger store function
parent.write({'salvage_value': parent.salvage_value})
return True
def _get_period(self, cr, uid, context=None):
ctx = dict(context or {}, account_period_prefer_normal=True)
periods = self.pool.get('account.period').find(cr, uid, context=ctx)
if periods:
return periods[0]
else:
return False
def _get_fy_duration(self, cr, uid, fy_id, option='days', context=None):
"""
Returns fiscal year duration.
@param option:
- days: duration in days
- months: duration in months,
a started month is counted as a full month
- years: duration in calendar years, considering also leap years
"""
# pylint: disable=sql-injection
cr.execute(
"SELECT date_start, date_stop, "
"date_stop-date_start+1 AS total_days "
"FROM account_fiscalyear WHERE id=%s" % fy_id)
fy_vals = cr.dictfetchall()[0]
days = fy_vals['total_days']
months = (int(fy_vals['date_stop'][:4]) -
int(fy_vals['date_start'][:4])) * 12 + \
(int(fy_vals['date_stop'][5:7]) -
int(fy_vals['date_start'][5:7])) + 1
if option == 'days':
return days
elif option == 'months':
return months
elif option == 'years':
fy_date_start = datetime.strptime(
fy_vals['date_start'], '%Y-%m-%d')
fy_year_start = int(fy_vals['date_start'][:4])
fy_date_stop = datetime.strptime(
fy_vals['date_stop'], '%Y-%m-%d')
fy_year_stop = int(fy_vals['date_stop'][:4])
year = fy_year_start
cnt = fy_year_stop - fy_year_start + 1
for i in range(cnt):
cy_days = calendar.isleap(year) and 366 or 365
if i == 0: # first year
if fy_date_stop.year == year:
duration = (fy_date_stop - fy_date_start).days + 1
else:
duration = (
datetime(year, 12, 31) - fy_date_start).days + 1
factor = float(duration) / cy_days
elif i == cnt - 1: # last year
duration = (
fy_date_stop - datetime(year, 01, 01)).days + 1
factor += float(duration) / cy_days
else:
factor += 1.0
year += 1
return factor
def _get_fy_duration_factor(self, cr, uid, entry,
asset, firstyear, context=None):
"""
localization: override this method to change the logic used to
calculate the impact of extended/shortened fiscal years
"""
duration_factor = 1.0
fy_id = entry['fy_id']
if asset.prorata:
if firstyear:
depreciation_date_start = datetime.strptime(
asset.date_start, '%Y-%m-%d')
fy_date_stop = entry['date_stop']
first_fy_asset_days = \
(fy_date_stop - depreciation_date_start).days + 1
if fy_id:
first_fy_duration = self._get_fy_duration(
cr, uid, fy_id, option='days')
first_fy_year_factor = self._get_fy_duration(
cr, uid, fy_id, option='years')
duration_factor = \
float(first_fy_asset_days) / first_fy_duration \
* first_fy_year_factor
else:
first_fy_duration = \
calendar.isleap(entry['date_start'].year) \
and 366 or 365
duration_factor = \
float(first_fy_asset_days) / first_fy_duration
elif fy_id:
duration_factor = self._get_fy_duration(
cr, uid, fy_id, option='years')
elif fy_id:
fy_months = self._get_fy_duration(
cr, uid, fy_id, option='months')
duration_factor = float(fy_months) / 12
return duration_factor
def _get_depreciation_start_date(self, cr, uid, asset, fy, context=None):
"""
In case of 'Linear': the first month is counted as a full month
if the fiscal year starts in the middle of a month.
"""
if asset.prorata:
depreciation_start_date = datetime.strptime(
asset.date_start, '%Y-%m-%d')
else:
fy_date_start = datetime.strptime(fy.date_start, '%Y-%m-%d')
depreciation_start_date = datetime(
fy_date_start.year, fy_date_start.month, 1)
return depreciation_start_date
def _get_depreciation_stop_date(self, cr, uid, asset,
depreciation_start_date, context=None):
if asset.method_time == 'year':
depreciation_stop_date = depreciation_start_date + \
relativedelta(years=asset.method_number, days=-1)
elif asset.method_time == 'number':
if asset.method_period == 'month':
depreciation_stop_date = depreciation_start_date + \
relativedelta(months=asset.method_number, days=-1)
elif asset.method_period == 'quarter':
depreciation_stop_date = depreciation_start_date + \
relativedelta(months=asset.method_number * 3, days=-1)
elif asset.method_period == 'year':
depreciation_stop_date = depreciation_start_date + \
relativedelta(years=asset.method_number, days=-1)
elif asset.method_time == 'end':
depreciation_stop_date = datetime.strptime(
asset.method_end, '%Y-%m-%d')
return depreciation_stop_date
def _compute_year_amount(self, cr, uid, asset, amount_to_depr,
residual_amount, context=None):
"""
Localization: override this method to change the degressive-linear
calculation logic according to local legislation.
"""
if asset.method_time == 'year':
divisor = asset.method_number
elif asset.method_time == 'number':
if asset.method_period == 'month':
divisor = asset.method_number / 12.0
elif asset.method_period == 'quarter':
divisor = asset.method_number * 3 / 12.0
elif asset.method_period == 'year':
divisor = asset.method_number
elif asset.method_time == 'end':
duration = \
(datetime.strptime(asset.method_end, '%Y-%m-%d') -
datetime.strptime(asset.date_start, '%Y-%m-%d')).days + 1
divisor = duration / 365.0
year_amount_linear = amount_to_depr / divisor
if asset.method == 'linear':
return year_amount_linear
year_amount_degressive = residual_amount * \
asset.method_progress_factor
if asset.method == 'degressive':
return year_amount_degressive
if asset.method == 'degr-linear':
if year_amount_linear > year_amount_degressive:
return year_amount_linear
else:
return year_amount_degressive
else:
raise orm.except_orm(
_('Programming Error!'),
_("Illegal value %s in asset.method.") % asset.method)
def _compute_depreciation_table(self, cr, uid, asset, context=None):
if not context:
context = {}
context = context.copy()
table = []
if not asset.method_number:
return table
context['company_id'] = asset.company_id.id
fy_obj = self.pool.get('account.fiscalyear')
init_flag = False
try:
fy_id = fy_obj.find(cr, uid, asset.date_start, context=context)
fy = fy_obj.browse(cr, uid, fy_id)
if fy.state == 'done':
init_flag = True
fy_date_start = datetime.strptime(fy.date_start, '%Y-%m-%d')
fy_date_stop = datetime.strptime(fy.date_stop, '%Y-%m-%d')
except:
# The following logic is used when no fiscalyear
# is defined for the asset start date:
# - We lookup the first fiscal year defined in the system
# - The 'undefined' fiscal years are assumed to be years
# with a duration equals to calendar year
cr.execute(
"SELECT id, date_start, date_stop "
"FROM account_fiscalyear ORDER BY date_stop ASC LIMIT 1")
first_fy = cr.dictfetchone()
first_fy_date_start = datetime.strptime(
first_fy['date_start'], '%Y-%m-%d')
asset_date_start = datetime.strptime(asset.date_start, '%Y-%m-%d')
fy_date_start = first_fy_date_start
if asset_date_start > fy_date_start:
asset_ref = asset.code and '%s (ref: %s)' \
% (asset.name, asset.code) or asset.name
raise orm.except_orm(
_('Error!'),
_("You cannot compute a depreciation table for an asset "
"starting in an undefined future fiscal year."
"\nPlease correct the start date for asset '%s'.")
% asset_ref)
while asset_date_start < fy_date_start:
fy_date_start = fy_date_start - relativedelta(years=1)
fy_date_stop = fy_date_start + relativedelta(years=1, days=-1)
fy_id = False
fy = dummy_fy(
date_start=fy_date_start.strftime('%Y-%m-%d'),
date_stop=fy_date_stop.strftime('%Y-%m-%d'),
id=False,
state='done',
dummy=True)
init_flag = True
depreciation_start_date = self._get_depreciation_start_date(
cr, uid, asset, fy, context=context)
depreciation_stop_date = self._get_depreciation_stop_date(
cr, uid, asset, depreciation_start_date, context=context)
while fy_date_start <= depreciation_stop_date:
table.append({
'fy_id': fy_id,
'date_start': fy_date_start,
'date_stop': fy_date_stop,
'init': init_flag})
fy_date_start = fy_date_stop + relativedelta(days=1)
try:
fy_id = fy_obj.find(cr, uid, fy_date_start, context=context)
init_flag = False
except:
fy_id = False
if fy_id:
fy = fy_obj.browse(cr, uid, fy_id)
if fy.state == 'done':
init_flag = True
fy_date_stop = datetime.strptime(fy.date_stop, '%Y-%m-%d')
else:
fy_date_stop = fy_date_stop + relativedelta(years=1)
digits = self.pool.get('decimal.precision').precision_get(
cr, uid, 'Account')
amount_to_depr = residual_amount = asset.asset_value
# step 1: calculate depreciation amount per fiscal year
fy_residual_amount = residual_amount
i_max = len(table) - 1
asset_sign = asset.asset_value >= 0 and 1 or -1
for i, entry in enumerate(table):
year_amount = self._compute_year_amount(
cr, uid, asset, amount_to_depr,
fy_residual_amount, context=context)
if asset.method_period == 'year':
period_amount = year_amount
elif asset.method_period == 'quarter':
period_amount = year_amount/4
elif asset.method_period == 'month':
period_amount = year_amount/12
if i == i_max:
fy_amount = fy_residual_amount
else:
firstyear = i == 0 and True or False
fy_factor = self._get_fy_duration_factor(
cr, uid, entry, asset, firstyear, context=context)
fy_amount = year_amount * fy_factor
if asset_sign * (fy_amount - fy_residual_amount) > 0:
fy_amount = fy_residual_amount
period_amount = round(period_amount, digits)
fy_amount = round(fy_amount, digits)
entry.update({
'period_amount': period_amount,
'fy_amount': fy_amount,
})
fy_residual_amount -= fy_amount
if round(fy_residual_amount, digits) == 0:
break
i_max = i
table = table[:i_max + 1]
# step 2: spread depreciation amount per fiscal year
# over the depreciation periods
fy_residual_amount = residual_amount
line_date = False
for i, entry in enumerate(table):
period_amount = entry['period_amount']
fy_amount = entry['fy_amount']
period_duration = (asset.method_period == 'year' and 12) \
or (asset.method_period == 'quarter' and 3) or 1
if period_duration == 12:
if asset_sign * (fy_amount - fy_residual_amount) > 0:
fy_amount = fy_residual_amount
lines = [{'date': entry['date_stop'], 'amount': fy_amount}]
fy_residual_amount -= fy_amount
elif period_duration in [1, 3]:
lines = []
fy_amount_check = 0.0
if not line_date:
if period_duration == 3:
m = [x for x in [3, 6, 9, 12]
if x >= depreciation_start_date.month][0]
line_date = depreciation_start_date + \
relativedelta(month=m, day=31)
else:
line_date = depreciation_start_date + \
relativedelta(months=0, day=31)
while line_date <= \
min(entry['date_stop'], depreciation_stop_date) and \
asset_sign * (fy_residual_amount - period_amount) > 0:
lines.append({'date': line_date, 'amount': period_amount})
fy_residual_amount -= period_amount
fy_amount_check += period_amount
line_date = line_date + \
relativedelta(months=period_duration, day=31)
if i == i_max and \
(not lines or
depreciation_stop_date > lines[-1]['date']):
# last year, last entry
period_amount = fy_residual_amount
lines.append({'date': line_date, 'amount': period_amount})
fy_amount_check += period_amount
if round(fy_amount_check - fy_amount, digits) != 0:
# handle rounding and extended/shortened
# fiscal year deviations
diff = fy_amount_check - fy_amount
fy_residual_amount += diff
if i == 0: # first year: deviation in first period
lines[0]['amount'] = period_amount - diff
else: # other years: deviation in last period
lines[-1]['amount'] = period_amount - diff
else:
raise orm.except_orm(
_('Programming Error!'),
_("Illegal value %s in asset.method_period.")
% asset.method_period)
for line in lines:
line['depreciated_value'] = amount_to_depr - residual_amount
residual_amount -= line['amount']
line['remaining_value'] = residual_amount
entry['lines'] = lines
return table
def _get_depreciation_entry_name(self, cr, uid, asset, seq, context=None):
""" use this method to customise the name of the accounting entry """
return (asset.code or str(asset.id)) + '/' + str(seq)
def compute_depreciation_board(self, cr, uid, ids, context=None):
if not context:
context = {}
context = context.copy()
depreciation_lin_obj = self.pool.get(
'account.asset.depreciation.line')
digits = self.pool.get('decimal.precision').precision_get(
cr, uid, 'Account')
for asset in self.browse(cr, uid, ids, context=context):
if asset.value_residual == 0.0:
continue
domain = [
('asset_id', '=', asset.id),
('type', '=', 'depreciate'),
'|', ('move_check', '=', True), ('init_entry', '=', True)]
posted_depreciation_line_ids = depreciation_lin_obj.search(
cr, uid, domain, order='line_date desc')
if (len(posted_depreciation_line_ids) > 0):
last_depreciation_line = depreciation_lin_obj.browse(
cr, uid, posted_depreciation_line_ids[0], context=context)
else:
last_depreciation_line = False
domain = [
('asset_id', '=', asset.id),
('type', '=', 'depreciate'),
('move_id', '=', False),
('init_entry', '=', False)]
old_depreciation_line_ids = depreciation_lin_obj.search(
cr, uid, domain)
if old_depreciation_line_ids:
depreciation_lin_obj.unlink(
cr, uid, old_depreciation_line_ids, context=context)
context['company_id'] = asset.company_id.id
table = self._compute_depreciation_table(
cr, uid, asset, context=context)
if not table:
continue
# group lines prior to depreciation start period
depreciation_start_date = datetime.strptime(
asset.date_start, '%Y-%m-%d')
lines = table[0]['lines']
lines1 = []
lines2 = []
flag = lines[0]['date'] < depreciation_start_date
for line in lines:
if flag:
lines1.append(line)
if line['date'] >= depreciation_start_date:
flag = False
else:
lines2.append(line)
if lines1:
def group_lines(x, y):
y.update({'amount': x['amount'] + y['amount']})
return y
lines1 = [reduce(group_lines, lines1)]
lines1[0]['depreciated_value'] = 0.0
table[0]['lines'] = lines1 + lines2
# check table with posted entries and
# recompute in case of deviation
if (len(posted_depreciation_line_ids) > 0):
last_depreciation_date = datetime.strptime(
last_depreciation_line.line_date, '%Y-%m-%d')
last_date_in_table = table[-1]['lines'][-1]['date']
if last_date_in_table <= last_depreciation_date:
raise orm.except_orm(
_('Error!'),
_("The duration of the asset conflicts with the "
"posted depreciation table entry dates."))
for table_i, entry in enumerate(table):
residual_amount_table = \
entry['lines'][-1]['remaining_value']
if entry['date_start'] <= last_depreciation_date \
<= entry['date_stop']:
break
if entry['date_stop'] == last_depreciation_date:
table_i += 1
line_i = 0
else:
entry = table[table_i]
date_min = entry['date_start']
for line_i, line in enumerate(entry['lines']):
residual_amount_table = line['remaining_value']
if date_min <= last_depreciation_date <= line['date']:
break
date_min = line['date']
if line['date'] == last_depreciation_date:
line_i += 1
table_i_start = table_i
line_i_start = line_i
# check if residual value corresponds with table
# and adjust table when needed
cr.execute(
"SELECT COALESCE(SUM(amount), 0.0) "
"FROM account_asset_depreciation_line "
"WHERE id IN %s",
(tuple(posted_depreciation_line_ids),))
res = cr.fetchone()
depreciated_value = res[0]
residual_amount = asset.asset_value - depreciated_value
amount_diff = round(
residual_amount_table - residual_amount, digits)
if amount_diff:
entry = table[table_i_start]
cr.execute(
"SELECT COALESCE(SUM(amount), 0.0) "
"FROM account_asset_depreciation_line "
"WHERE id in %s "
" AND line_date >= %s and line_date <= %s",
(tuple(posted_depreciation_line_ids),
entry['date_start'],
entry['date_stop']))
res = cr.fetchone()
fy_amount_check = res[0]
lines = entry['lines']
for line in lines[line_i_start:-1]:
line['depreciated_value'] = depreciated_value
depreciated_value += line['amount']
fy_amount_check += line['amount']
residual_amount -= line['amount']
line['remaining_value'] = residual_amount
lines[-1]['depreciated_value'] = depreciated_value
lines[-1]['amount'] = entry['fy_amount'] - fy_amount_check
else:
table_i_start = 0
line_i_start = 0
seq = len(posted_depreciation_line_ids)
depr_line_id = last_depreciation_line and last_depreciation_line.id
last_date = table[-1]['lines'][-1]['date']
for entry in table[table_i_start:]:
for line in entry['lines'][line_i_start:]:
seq += 1
name = self._get_depreciation_entry_name(
cr, uid, asset, seq, context=context)
if line['date'] == last_date:
# ensure that the last entry of the table always
# depreciates the remaining value
cr.execute(
"SELECT COALESCE(SUM(amount), 0.0) "
"FROM account_asset_depreciation_line "
"WHERE type = 'depreciate' AND line_date < %s "
"AND asset_id = %s ",
(last_date, asset.id))
res = cr.fetchone()
amount = asset.asset_value - res[0]
else:
amount = line['amount']
vals = {
'previous_id': depr_line_id,
'amount': amount,
'asset_id': asset.id,
'name': name,
'line_date': line['date'].strftime('%Y-%m-%d'),
'init_entry': entry['init'],
}
depr_line_id = depreciation_lin_obj.create(
cr, uid, vals, context=context)
line_i_start = 0
return True
def validate(self, cr, uid, ids, context=None):
if context is None:
context = {}
currency_obj = self.pool.get('res.currency')
for asset in self.browse(cr, uid, ids, context=context):
if asset.type == 'normal' and currency_obj.is_zero(
cr, uid, asset.company_id.currency_id,
asset.value_residual):
asset.write({'state': 'close'})
else:
asset.write({'state': 'open'})
return True
def remove(self, cr, uid, ids, context=None):
for asset in self.browse(cr, uid, ids, context):
ctx = dict(context, active_ids=ids, active_id=ids[0])
if asset.value_residual:
ctx.update({'early_removal': True})
return {
'name': _("Generate Asset Removal entries"),
'view_type': 'form',
'view_mode': 'form',
'res_model': 'account.asset.remove',
'target': 'new',
'type': 'ir.actions.act_window',
'context': ctx,
'nodestroy': True,
}
def set_to_draft(self, cr, uid, ids, context=None):
return self.write(cr, uid, ids, {'state': 'draft'}, context=context)
def _asset_value_compute(self, cr, uid, asset, context=None):
if asset.type == 'view':
asset_value = 0.0
else:
asset_value = asset.purchase_value - asset.salvage_value
return asset_value
def _asset_value(self, cr, uid, ids, name, args, context=None):
res = {}
for asset in self.browse(cr, uid, ids, context):
if asset.type == 'normal':
res[asset.id] = self._asset_value_compute(
cr, uid, asset, context)
else:
def _value_get(record):
asset_value = self._asset_value_compute(
cr, uid, asset, context)
for rec in record.child_ids:
asset_value += \
rec.type == 'normal' and \
self._asset_value_compute(cr, uid, rec, context) \
or _value_get(rec)
return asset_value
res[asset.id] = _value_get(asset)
return res
def _compute_depreciation(self, cr, uid, ids, name, args, context=None):
res = {}
for asset in self.browse(cr, uid, ids, context=context):
res[asset.id] = {}
child_ids = self.search(cr, uid,
[('parent_id', 'child_of', [asset.id]),
('type', '=', 'normal')],
context=context)
if child_ids:
cr.execute(
"SELECT COALESCE(SUM(amount),0.0) AS amount "
"FROM account_asset_depreciation_line "
"WHERE asset_id in %s "
"AND type in ('depreciate','remove') "
"AND (init_entry=TRUE OR move_check=TRUE)",
(tuple(child_ids),))
value_depreciated = cr.fetchone()[0]
else:
value_depreciated = 0.0
res[asset.id]['value_residual'] = \
asset.asset_value - value_depreciated
res[asset.id]['value_depreciated'] = \
value_depreciated
return res
def _move_line_check(self, cr, uid, ids, name, args, context=None):
res = dict.fromkeys(ids, False)
for asset in self.browse(cr, uid, ids, context=context):
for line in asset.depreciation_line_ids:
if line.move_id:
res[asset.id] = True
continue
return res
def onchange_purchase_salvage_value(
self, cr, uid, ids, purchase_value,
salvage_value, date_start, context=None):
if not context:
context = {}
val = {}
purchase_value = purchase_value or 0.0
salvage_value = salvage_value or 0.0
if purchase_value or salvage_value:
val['asset_value'] = purchase_value - salvage_value
if ids:
aadl_obj = self.pool.get('account.asset.depreciation.line')
dl_create_ids = aadl_obj.search(
cr, uid, [('type', '=', 'create'), ('asset_id', 'in', ids)])
aadl_obj.write(
cr, uid, dl_create_ids,
{'amount': val['asset_value'], 'line_date': date_start})
return {'value': val}
def _get_assets(self, cr, uid, ids, context=None):
asset_ids = []
for asset in self.browse(cr, uid, ids, context=context):
def _parent_get(record):
asset_ids.append(record.id)
if record.parent_id:
_parent_get(record.parent_id)
_parent_get(asset)
return asset_ids
def _get_assets_from_dl(self, cr, uid, ids, context=None):
asset_ids = []
for dl in filter(
lambda x: x.type in ['depreciate', 'remove'] and
(x.init_entry or x.move_id),
self.pool.get('account.asset.depreciation.line').browse(
cr, uid, ids, context=context)):
res = []
def _parent_get(record):
res.append(record.id)
if record.parent_id:
res.append(_parent_get(record.parent_id))
_parent_get(dl.asset_id)
for asset_id in res:
if asset_id not in asset_ids:
asset_ids.append(asset_id)
return asset_ids
def _get_method(self, cr, uid, context=None):
return self.pool.get('account.asset.category')._get_method(
cr, uid, context)
def _get_method_time(self, cr, uid, context=None):
return self.pool.get('account.asset.category')._get_method_time(
cr, uid, context)
def _get_company(self, cr, uid, context=None):
return self.pool.get('res.company')._company_default_get(
cr, uid, 'account.asset.asset', context=context)
_columns = {
'account_move_line_ids': fields.one2many(
'account.move.line', 'asset_id', 'Entries', readonly=True),
'move_line_check': fields.function(
_move_line_check, method=True, type='boolean',
string='Has accounting entries'),
'name': fields.char(
'Asset Name', size=64, required=True,
readonly=True, states={'draft': [('readonly', False)]}),
'code': fields.char(
'Reference', size=32, readonly=True,
states={'draft': [('readonly', False)]}),
'purchase_value': fields.float(
'Purchase Value', required=True, readonly=True,
states={'draft': [('readonly', False)]},
help="\nThe Asset Value is calculated as follows:"
"\nPurchase Value - Salvage Value."),
'asset_value': fields.function(
_asset_value, method=True,
digits_compute=dp.get_precision('Account'),
string='Asset Value',
store={
'account.asset.asset': (
_get_assets,
['purchase_value', 'salvage_value', 'parent_id'], 10),
},
help="This amount represent the initial value of the asset."),
'value_residual': fields.function(
_compute_depreciation, method=True, multi='cd',
digits_compute=dp.get_precision('Account'),
string='Residual Value',
store={
'account.asset.asset': (
_get_assets, [
'purchase_value', 'salvage_value',
'parent_id', 'depreciation_line_ids'
], 20),
'account.asset.depreciation.line': (
_get_assets_from_dl,
['amount', 'init_entry', 'move_id'], 20),
}),
'value_depreciated': fields.function(
_compute_depreciation, method=True, multi='cd',
digits_compute=dp.get_precision('Account'),
string='Depreciated Value',
store={
'account.asset.asset': (
_get_assets, [
'purchase_value', 'salvage_value',
'parent_id', 'depreciation_line_ids'
], 30),
'account.asset.depreciation.line': (
_get_assets_from_dl,
['amount', 'init_entry', 'move_id'], 30),
}),
'salvage_value': fields.float(
'Salvage Value', digits_compute=dp.get_precision('Account'),
readonly=True,
states={'draft': [('readonly', False)]},
help="The estimated value that an asset will realize upon "
"its sale at the end of its useful life.\n"
"This value is used to determine the depreciation amounts."),
'note': fields.text('Note'),
'category_id': fields.many2one(
'account.asset.category', 'Asset Category',
change_default=True, readonly=True,
states={'draft': [('readonly', False)]}),
'parent_id': fields.many2one(
'account.asset.asset', 'Parent Asset', readonly=True,