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
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2011 MSF, TeMPO Consulting.
#
# 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/>.
#
##############################################################################
from osv import osv, fields
from tools.translate import _
class account_invoice(osv.osv):
_name = 'account.invoice'
_inherit = 'account.invoice'
def _check_active_product(self, cr, uid, ids, context=None):
'''
Check if the Purchase order contains a line with an inactive products
'''
inactive_lines = self.pool.get('account.invoice.line').search(cr, uid, [
('product_id.active', '=', False),
('invoice_id', 'in', ids),
('invoice_id.state', 'not in', ['draft', 'cancel', 'done'])
], context=context)
if inactive_lines:
plural = len(inactive_lines) == 1 and _('A product has') or _('Some products have')
l_plural = len(inactive_lines) == 1 and _('line') or _('lines')
p_plural = len(inactive_lines) == 1 and _('this inactive product') or _('those inactive products')
raise osv.except_osv(_('Error'), _('%s been inactivated. If you want to validate this document you have to remove/correct the %s containing %s (see red %s of the document)') % (plural, l_plural, p_plural, l_plural))
return False
return True
_constraints = [
(_check_active_product, "You cannot validate this invoice because it contains a line with an inactive product", ['invoice_line', 'state'])
]
_columns = {
'analytic_distribution_id': fields.many2one('analytic.distribution', 'Analytic Distribution', select="1"), # select: optimisation purpose
}
def _check_analytic_distribution_state(self, cr, uid, ids, context=None):
"""
Check if analytic distribution is valid
"""
if not context:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
for inv in self.browse(cr, uid, ids, context=context):
for invl in inv.invoice_line:
if invl.analytic_distribution_state != 'valid':
raise osv.except_osv(_('Error'), _('Analytic distribution is not valid for "%s"') % invl.name)
return True
def _hook_fields_for_refund(self, cr, uid, *args):
"""
Add these fields to result:
- analytic_distribution_id
"""
res = super(account_invoice, self)._hook_fields_for_refund(cr, uid, args)
res.append('analytic_distribution_id')
res.append('document_date')
return res
def _hook_fields_m2o_for_refund(self, cr, uid, *args):
"""
Add these fields to result:
- analytic_distribution_id
"""
res = super(account_invoice, self)._hook_fields_m2o_for_refund(cr, uid, args)
res.append('analytic_distribution_id')
return res
def _hook_refund_data(self, cr, uid, data, *args):
"""
Copy analytic distribution for refund invoice
"""
if not data:
return False
if 'analytic_distribution_id' in data:
if data.get('analytic_distribution_id', False):
data['analytic_distribution_id'] = self.pool.get('analytic.distribution').copy(cr, uid, data.get('analytic_distribution_id'), {}) or False
else:
data['analytic_distribution_id'] = False
return data
def _refund_cleanup_lines(self, cr, uid, lines):
"""
Add right analytic distribution values on each lines
"""
res = super(account_invoice, self)._refund_cleanup_lines(cr, uid, lines)
for el in res:
if el[2]:
# Give analytic distribution on line
if 'analytic_distribution_id' in el[2]:
if el[2].get('analytic_distribution_id', False) and el[2].get('analytic_distribution_id')[0]:
distrib_id = el[2].get('analytic_distribution_id')[0]
el[2]['analytic_distribution_id'] = self.pool.get('analytic.distribution').copy(cr, uid, distrib_id, {}) or False
else:
# default value
el[2]['analytic_distribution_id'] = False
# Give false analytic lines for 'line' in order not to give an error
if 'analytic_line_ids' in el[2]:
el[2]['analytic_line_ids'] = False
# Give false for (because not needed):
# - order_line_id
# - sale_order_line_id
for field in ['order_line_id', 'sale_order_line_id']:
if field in el[2]:
el[2][field] = el[2].get(field, False) and el[2][field][0] or False
return res
def copy(self, cr, uid, inv_id, default=None, context=None):
"""
Copy global distribution and give it to new invoice
"""
if not context:
context = {}
if not default:
default = {}
inv = self.browse(cr, uid, [inv_id], context=context)[0]
if inv.analytic_distribution_id:
new_distrib_id = self.pool.get('analytic.distribution').copy(cr, uid, inv.analytic_distribution_id.id, {}, context=context)
if new_distrib_id:
default.update({'analytic_distribution_id': new_distrib_id})
return super(account_invoice, self).copy(cr, uid, inv_id, default, context)
def refund(self, cr, uid, ids, date=None, period_id=None, description=None, journal_id=None, document_date=None):
"""
Reverse lines for given invoice
"""
if isinstance(ids, (int, long)):
ids = [ids]
for inv in self.browse(cr, uid, ids):
# Check for dates (refund must be done after invoice)
if date and date < inv.date_invoice:
raise osv.except_osv(_('Error'), _("Posting date for the refund is before the invoice's posting date!"))
if document_date and document_date < inv.document_date:
raise osv.except_osv(_('Error'), _("Document date for the refund is before the invoice's document date!"))
new_ids = super(account_invoice, self).refund(cr, uid, ids, date, period_id, description, journal_id)
# add document date
if document_date:
self.write(cr, uid, new_ids, {'document_date': document_date})
return new_ids
def line_get_convert(self, cr, uid, x, part, date, context=None):
res = super(account_invoice, self).line_get_convert(cr, uid, x, part, date, context=context)
res['analytic_distribution_id'] = x.get('analytic_distribution_id', False)
return res
def button_analytic_distribution(self, cr, uid, ids, context=None):
"""
Launch analytic distribution wizard on an invoice
"""
# Some verifications
if not context:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
# Prepare some values
invoice = self.browse(cr, uid, ids[0], context=context)
amount = 0.0
# Search elements for currency
company_currency = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.currency_id.id
currency = invoice.currency_id and invoice.currency_id.id or company_currency
for line in invoice.invoice_line:
amount += line.price_subtotal
# Get analytic_distribution_id
distrib_id = invoice.analytic_distribution_id and invoice.analytic_distribution_id.id
# Prepare values for wizard
vals = {
'total_amount': amount,
'invoice_id': invoice.id,
'currency_id': currency or False,
'state': 'dispatch',
'posting_date': invoice.date_invoice,
'document_date': invoice.document_date,
}
if distrib_id:
vals.update({'distribution_id': distrib_id,})
# Create the wizard
wiz_obj = self.pool.get('analytic.distribution.wizard')
wiz_id = wiz_obj.create(cr, uid, vals, context=context)
# Update some context values
context.update({
'active_id': ids[0],
'active_ids': ids,
})
# Open it!
return {
'name': _('Global analytic distribution'),
'type': 'ir.actions.act_window',
'res_model': 'analytic.distribution.wizard',
'view_type': 'form',
'view_mode': 'form',
'target': 'new',
'res_id': [wiz_id],
'context': context,
}
def button_reset_distribution(self, cr, uid, ids, context=None):
"""
Reset analytic distribution on all invoice lines.
To do this, just delete the analytic_distribution id link on each invoice line.
"""
if context is None:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
# Prepare some values
invl_obj = self.pool.get(self._name + '.line') # PAY ATTENTION to wizard.account.invoice.line
# Search invoice lines
to_reset = invl_obj.search(cr, uid, [('invoice_id', 'in', ids)])
invl_obj.write(cr, uid, to_reset, {'analytic_distribution_id': False})
return True
account_invoice()
class account_invoice_line(osv.osv):
_name = 'account.invoice.line'
_inherit = 'account.invoice.line'
def _get_distribution_state(self, cr, uid, ids, name, args, context=None):
"""
Get state of distribution:
- if compatible with the invoice line, then "valid"
- if no distribution, take a tour of invoice distribution, if compatible, then "valid"
- if no distribution on invoice line and invoice, then "none"
- all other case are "invalid"
"""
# Some verifications
if not context:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
# Prepare some values
res = {}
# Browse all given lines
for line in self.browse(cr, uid, ids, context=context):
if line.from_yml_test:
res[line.id] = 'valid'
else:
# UF-2115: test for elements
line_distribution_id = False
invoice_distribution_id = False
line_account_id = False
if line.analytic_distribution_id:
line_distribution_id = line.analytic_distribution_id.id
if line.invoice_id and line.invoice_id.analytic_distribution_id:
invoice_distribution_id = line.invoice_id.analytic_distribution_id.id
if line.account_id:
line_account_id = line.account_id.id
res[line.id] = self.pool.get('analytic.distribution')._get_distribution_state(cr, uid, line_distribution_id, invoice_distribution_id, line_account_id)
return res
def _have_analytic_distribution_from_header(self, cr, uid, ids, name, arg, context=None):
"""
If invoice have an analytic distribution, return False, else return True
"""
# Some verifications
if not context:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
res = {}
for inv in self.browse(cr, uid, ids, context=context):
res[inv.id] = True
if inv.analytic_distribution_id:
res[inv.id] = False
return res
def _get_is_allocatable(self, cr, uid, ids, name, arg, context=None):
"""
If analytic-a-holic account, then this account is allocatable.
"""
if isinstance(ids, (int, long)):
ids = [ids]
res = {}
for invl in self.browse(cr, uid, ids):
res[invl.id] = True
if invl.account_id and not invl.account_id.is_analytic_addicted:
res[invl.id] = False
return res
def _get_distribution_state_recap(self, cr, uid, ids, name, arg, context=None):
"""
Get a recap from analytic distribution state and if it come from header or not.
"""
if isinstance(ids, (int, long)):
ids = [ids]
res = {}
for invl in self.browse(cr, uid, ids):
res[invl.id] = ''
if not invl.is_allocatable:
continue
from_header = ''
if invl.have_analytic_distribution_from_header:
from_header = _(' (from header)')
res[invl.id] = '%s%s' % (self.pool.get('ir.model.fields').get_browse_selection(cr, uid, invl, 'analytic_distribution_state', context), from_header)
return res
def _get_inactive_product(self, cr, uid, ids, field_name, args, context=None):
'''
Fill the error message if the product of the line is inactive
'''
res = {}
for line in self.browse(cr, uid, ids, context=context):
res[line.id] = {'inactive_product': False,
'inactive_error': ''}
if line.invoice_id and line.invoice_id.state not in ('cancel', 'done') and line.product_id and not line.product_id.active:
res[line.id] = {
'inactive_product': True,
'inactive_error': _('The product in line is inactive !')
}
return res
def _get_analytic_lines(self, cr, uid, ids, field_name, arg, context=None):
"""
"""
# Checks
if context is None:
context = {}
# Prepare some values
res = {}
for invl in self.browse(cr, uid, ids):
res[invl.id] = []
for ml in (invl.move_lines or []):
if ml.analytic_lines:
res[invl.id] = self.pool.get('account.analytic.line').get_corrections_history(cr, uid, [x.id for x in ml.analytic_lines])
return res
_columns = {
'analytic_distribution_id': fields.many2one('analytic.distribution', 'Analytic Distribution', select="1"), # select is for optimisation purposes
'analytic_distribution_state': fields.function(_get_distribution_state, method=True, type='selection',
selection=[('none', 'None'), ('valid', 'Valid'), ('invalid', 'Invalid')],
string="Distribution state", help="Informs from distribution state among 'none', 'valid', 'invalid."),
'have_analytic_distribution_from_header': fields.function(_have_analytic_distribution_from_header, method=True, type='boolean',
string='Header Distrib.?'),
'newline': fields.boolean('New line'),
'is_allocatable': fields.function(_get_is_allocatable, method=True, type='boolean', string="Is allocatable?", readonly=True, store=False),
'analytic_distribution_state_recap': fields.function(_get_distribution_state_recap, method=True, type='char', size=30,
string="Distribution",
help="Informs you about analaytic distribution state among 'none', 'valid', 'invalid', from header or not, or no analytic distribution"),
'inactive_product': fields.function(_get_inactive_product, method=True, type='boolean', string='Product is inactive', store=False, multi='inactive'),
'inactive_error': fields.function(_get_inactive_product, method=True, type='char', string='Comment', store=False, multi='inactive'),
'analytic_lines': fields.function(_get_analytic_lines, method=True, type='one2many', relation='account.analytic.line', store=False, string='Analytic lines', help='Give all analytic lines linked to this invoice line. With correction ones.'),
}
_defaults = {
'newline': lambda *a: True,
'have_analytic_distribution_from_header': lambda *a: True,
'is_allocatable': lambda *a: True,
'analytic_distribution_state_recap': lambda *a: '',
'inactive_product': False,
'inactive_error': lambda *a: '',
}
def create(self, cr, uid, vals, context=None):
"""
Set newline field to False.
"""
vals.update({'newline': False,})
return super(account_invoice_line, self).create(cr, uid, vals, context)
def copy_data(self, cr, uid, l_id, default=None, context=None):
"""
Copy global distribution and give it to new invoice line
"""
# Some verifications
if not context:
context = {}
if not default:
default = {}
# Copy analytic distribution
invl = self.browse(cr, uid, [l_id], context=context)[0]
if invl.analytic_distribution_id:
new_distrib_id = self.pool.get('analytic.distribution').copy(cr, uid, invl.analytic_distribution_id.id, {}, context=context)
if new_distrib_id:
default.update({'analytic_distribution_id': new_distrib_id})
return super(account_invoice_line, self).copy_data(cr, uid, l_id, default, context)
def move_line_get_item(self, cr, uid, line, context=None):
"""
Give right analytic distribution when creating move lines
"""
# Some verifications
if not context:
context = {}
# Default result
res = super(account_invoice_line, self).move_line_get_item(cr, uid, line, context=context)
# Update result by copying analytic distribution from invoice line
ana_obj = self.pool.get('analytic.distribution')
if line.analytic_distribution_id:
new_distrib_id = ana_obj.copy(cr, uid, line.analytic_distribution_id.id, {}, context=context)
if new_distrib_id:
res['analytic_distribution_id'] = new_distrib_id
# If no distribution on invoice line, take those from invoice and copy it!
elif line.invoice_id and line.invoice_id.analytic_distribution_id:
new_distrib_id = ana_obj.copy(cr, uid, line.invoice_id.analytic_distribution_id.id, {}, context=context)
if new_distrib_id:
res['analytic_distribution_id'] = new_distrib_id
return res
def button_analytic_distribution(self, cr, uid, ids, context=None):
"""
Launch analytic distribution wizard on an invoice line
"""
# Some verifications
if not context:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
if not ids:
raise osv.except_osv(_('Error'), _('No invoice line given. Please save your invoice line before.'))
# Prepare some values
invoice_line = self.browse(cr, uid, ids[0], context=context)
negative_inv = False
amount = invoice_line.price_subtotal or 0.0
# Search elements for currency
company_currency = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.currency_id.id
currency = invoice_line.invoice_id.currency_id and invoice_line.invoice_id.currency_id.id or company_currency
# Change amount sign if necessary
if invoice_line.invoice_id.type in ['out_invoice', 'in_refund']:
negative_inv = True
if negative_inv:
amount = -1 * amount
# Get analytic distribution id from this line
distrib_id = invoice_line and invoice_line.analytic_distribution_id and invoice_line.analytic_distribution_id.id or False
# Prepare values for wizard
vals = {
'total_amount': amount,
'invoice_line_id': invoice_line.id,
'currency_id': currency or False,
'state': 'dispatch',
'account_id': invoice_line.account_id and invoice_line.account_id.id or False,
'posting_date': invoice_line.invoice_id.date_invoice,
'document_date': invoice_line.invoice_id.document_date,
}
if distrib_id:
vals.update({'distribution_id': distrib_id,})
# Create the wizard
wiz_obj = self.pool.get('analytic.distribution.wizard')
wiz_id = wiz_obj.create(cr, uid, vals, context=context)
# Update some context values
context.update({
'active_id': ids[0],
'active_ids': ids,
})
# Open it!
return {
'name': _('Analytic distribution'),
'type': 'ir.actions.act_window',
'res_model': 'analytic.distribution.wizard',
'view_type': 'form',
'view_mode': 'form',
'target': 'new',
'res_id': [wiz_id],
'context': context,
}
account_invoice_line()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|