[FIX]account_voucher:when we specify the analytic_id but it does not appear in accoun...
[odoo/odoo.git] / addons / account_voucher / account_voucher.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6 #
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.
11 #
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.
16 #
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/>.
19 #
20 ##############################################################################
21
22 import time
23 from lxml import etree
24
25 import netsvc
26 from osv import osv, fields
27 import decimal_precision as dp
28 from tools.translate import _
29
30
31 class account_voucher(osv.osv):
32
33     def _get_type(self, cr, uid, context=None):
34         if context is None:
35             context = {}
36         return context.get('type', False)
37
38     def _get_period(self, cr, uid, context=None):
39         if context is None: context = {}
40         if context.get('period_id', False):
41             return context.get('period_id')
42         if context.get('invoice_id', False):
43             company_id = self.pool.get('account.invoice').browse(cr, uid, context['invoice_id'], context=context).company_id.id
44             context.update({'company_id': company_id})
45         periods = self.pool.get('account.period').find(cr, uid, context=context)
46         return periods and periods[0] or False
47
48     def _get_journal(self, cr, uid, context=None):
49         if context is None: context = {}
50         journal_pool = self.pool.get('account.journal')
51         invoice_pool = self.pool.get('account.invoice')
52         if context.get('invoice_id', False):
53             currency_id = invoice_pool.browse(cr, uid, context['invoice_id'], context=context).currency_id.id
54             journal_id = journal_pool.search(cr, uid, [('currency', '=', currency_id)], limit=1)
55             return journal_id and journal_id[0] or False
56         if context.get('journal_id', False):
57             return context.get('journal_id')
58         if not context.get('journal_id', False) and context.get('search_default_journal_id', False):
59             return context.get('search_default_journal_id')
60
61         ttype = context.get('type', 'bank')
62         if ttype in ('payment', 'receipt'):
63             ttype = 'bank'
64         res = journal_pool.search(cr, uid, [('type', '=', ttype)], limit=1)
65         return res and res[0] or False
66
67     def _get_tax(self, cr, uid, context=None):
68         if context is None: context = {}
69         journal_pool = self.pool.get('account.journal')
70         journal_id = context.get('journal_id', False)
71         if not journal_id:
72             ttype = context.get('type', 'bank')
73             res = journal_pool.search(cr, uid, [('type', '=', ttype)], limit=1)
74             if not res:
75                 return False
76             journal_id = res[0]
77
78         if not journal_id:
79             return False
80         journal = journal_pool.browse(cr, uid, journal_id, context=context)
81         account_id = journal.default_credit_account_id or journal.default_debit_account_id
82         if account_id and account_id.tax_ids:
83             tax_id = account_id.tax_ids[0].id
84             return tax_id
85         return False
86
87     def _get_currency(self, cr, uid, context=None):
88         if context is None: context = {}
89         journal_pool = self.pool.get('account.journal')
90         journal_id = context.get('journal_id', False)
91         if journal_id:
92             journal = journal_pool.browse(cr, uid, journal_id, context=context)
93 #            currency_id = journal.company_id.currency_id.id
94             if journal.currency:
95                 return journal.currency.id
96         return False
97
98     def _get_partner(self, cr, uid, context=None):
99         if context is None: context = {}
100         return context.get('partner_id', False)
101
102     def _get_reference(self, cr, uid, context=None):
103         if context is None: context = {}
104         return context.get('reference', False)
105
106     def _get_narration(self, cr, uid, context=None):
107         if context is None: context = {}
108         return context.get('narration', False)
109
110     def _get_amount(self, cr, uid, context=None):
111         if context is None:
112             context= {}
113         return context.get('amount', 0.0)
114
115     def name_get(self, cr, uid, ids, context=None):
116         if not ids:
117             return []
118         if context is None: context = {}
119         return [(r['id'], (str("%.2f" % r['amount']) or '')) for r in self.read(cr, uid, ids, ['amount'], context, load='_classic_write')]
120
121     def fields_view_get(self, cr, uid, view_id=None, view_type=False, context=None, toolbar=False, submenu=False):
122         mod_obj = self.pool.get('ir.model.data')
123         if context is None: context = {}
124
125         def get_res_id(view_type, condition):
126             result = False
127             if view_type == 'tree':
128                 result = mod_obj.get_object_reference(cr, uid, 'account_voucher', 'view_voucher_tree')
129             elif view_type == 'form':
130                 if condition:
131                     result = mod_obj.get_object_reference(cr, uid, 'account_voucher', 'view_vendor_receipt_form')
132                 else:
133                     result = mod_obj.get_object_reference(cr, uid, 'account_voucher', 'view_vendor_payment_form')
134             return result and result[1] or False
135
136         if not view_id and context.get('invoice_type', False):
137             view_id = get_res_id(view_type,context.get('invoice_type', False) in ('out_invoice', 'out_refund'))
138
139         if not view_id and context.get('line_type', False):
140             view_id = get_res_id(view_type,context.get('line_type', False) == 'customer')
141
142         res = super(account_voucher, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu)
143         doc = etree.XML(res['arch'])
144         nodes = doc.xpath("//field[@name='partner_id']")
145         if context.get('type', 'sale') in ('purchase', 'payment'):
146             for node in nodes:
147                 node.set('domain', "[('supplier', '=', True)]")
148             res['arch'] = etree.tostring(doc)
149         return res
150
151     def _compute_writeoff_amount(self, cr, uid, line_dr_ids, line_cr_ids, amount):
152         debit = credit = 0.0
153         for l in line_dr_ids:
154             debit += l['amount']
155         for l in line_cr_ids:
156             credit += l['amount']
157         return abs(amount - abs(credit - debit))
158
159     def onchange_line_ids(self, cr, uid, ids, line_dr_ids, line_cr_ids, amount):
160         if not line_dr_ids and not line_cr_ids:
161             return {'value':{}}
162         line_dr_ids = [x[2] for x in line_dr_ids]
163         line_cr_ids = [x[2] for x in line_cr_ids]
164         return {'value': {'writeoff_amount': self._compute_writeoff_amount(cr, uid, line_dr_ids, line_cr_ids, amount)}}
165
166     def _get_writeoff_amount(self, cr, uid, ids, name, args, context=None):
167         if not ids: return {}
168         res = {}
169         debit = credit = 0.0
170         for voucher in self.browse(cr, uid, ids, context=context):
171             for l in voucher.line_dr_ids:
172                 debit += l.amount
173             for l in voucher.line_cr_ids:
174                 credit += l.amount
175             res[voucher.id] =  abs(voucher.amount - abs(credit - debit))
176         return res
177
178     _name = 'account.voucher'
179     _description = 'Accounting Voucher'
180     _order = "date desc, id desc"
181 #    _rec_name = 'number'
182     _columns = {
183         'type':fields.selection([
184             ('sale','Sale'),
185             ('purchase','Purchase'),
186             ('payment','Payment'),
187             ('receipt','Receipt'),
188         ],'Default Type', readonly=True, states={'draft':[('readonly',False)]}),
189         'name':fields.char('Memo', size=256, readonly=True, states={'draft':[('readonly',False)]}),
190         'date':fields.date('Date', readonly=True, select=True, states={'draft':[('readonly',False)]}, help="Effective date for accounting entries"),
191         'journal_id':fields.many2one('account.journal', 'Journal', required=True, readonly=True, states={'draft':[('readonly',False)]}),
192         'account_id':fields.many2one('account.account', 'Account', required=True, readonly=True, states={'draft':[('readonly',False)]}),
193         'line_ids':fields.one2many('account.voucher.line','voucher_id','Voucher Lines', readonly=True, states={'draft':[('readonly',False)]}),
194         'line_cr_ids':fields.one2many('account.voucher.line','voucher_id','Credits',
195             domain=[('type','=','cr')], context={'default_type':'cr'}, readonly=True, states={'draft':[('readonly',False)]}),
196         'line_dr_ids':fields.one2many('account.voucher.line','voucher_id','Debits',
197             domain=[('type','=','dr')], context={'default_type':'dr'}, readonly=True, states={'draft':[('readonly',False)]}),
198         'period_id': fields.many2one('account.period', 'Period', required=True, readonly=True, states={'draft':[('readonly',False)]}),
199         'narration':fields.text('Notes', readonly=True, states={'draft':[('readonly',False)]}),
200         'currency_id':fields.many2one('res.currency', 'Currency', readonly=True, states={'draft':[('readonly',False)]}),
201 #        'currency_id': fields.related('journal_id','currency', type='many2one', relation='res.currency', string='Currency', store=True, readonly=True, states={'draft':[('readonly',False)]}),
202         'company_id': fields.many2one('res.company', 'Company', required=True, readonly=True, states={'draft':[('readonly',False)]}),
203         'state':fields.selection(
204             [('draft','Draft'),
205              ('proforma','Pro-forma'),
206              ('posted','Posted'),
207              ('cancel','Cancelled')
208             ], 'State', readonly=True, size=32,
209             help=' * The \'Draft\' state is used when a user is encoding a new and unconfirmed Voucher. \
210                         \n* The \'Pro-forma\' when voucher is in Pro-forma state,voucher does not have an voucher number. \
211                         \n* The \'Posted\' state is used when user create voucher,a voucher number is generated and voucher entries are created in account \
212                         \n* The \'Cancelled\' state is used when user cancel voucher.'),
213         'amount': fields.float('Total', digits_compute=dp.get_precision('Account'), required=True, readonly=True, states={'draft':[('readonly',False)]}),
214         'tax_amount':fields.float('Tax Amount', digits_compute=dp.get_precision('Account'), readonly=True, states={'draft':[('readonly',False)]}),
215         'reference': fields.char('Ref #', size=64, readonly=True, states={'draft':[('readonly',False)]}, help="Transaction reference number."),
216         'number': fields.char('Number', size=32, readonly=True,),
217         'move_id':fields.many2one('account.move', 'Account Entry'),
218         'move_ids': fields.related('move_id','line_id', type='one2many', relation='account.move.line', string='Journal Items', readonly=True),
219         'partner_id':fields.many2one('res.partner', 'Partner', change_default=1, readonly=True, states={'draft':[('readonly',False)]}),
220         'audit': fields.related('move_id','to_check', type='boolean', relation='account.move', string='Audit Complete ?'),
221         'pay_now':fields.selection([
222             ('pay_now','Pay Directly'),
223             ('pay_later','Pay Later or Group Funds'),
224         ],'Payment', select=True, readonly=True, states={'draft':[('readonly',False)]}),
225         'tax_id':fields.many2one('account.tax', 'Tax', readonly=True, states={'draft':[('readonly',False)]}),
226         'pre_line':fields.boolean('Previous Payments ?', required=False),
227         'date_due': fields.date('Due Date', readonly=True, select=True, states={'draft':[('readonly',False)]}),
228         'payment_option':fields.selection([
229                                            ('without_writeoff', 'Keep Open'),
230                                            ('with_writeoff', 'Reconcile with Write-Off'),
231                                            ], 'Payment Difference', required=True, readonly=True, states={'draft': [('readonly', False)]}),
232         'writeoff_acc_id': fields.many2one('account.account', 'Write-Off account', readonly=True, states={'draft': [('readonly', False)]}),
233         'comment': fields.char('Write-Off Comment', size=64, required=True, readonly=True, states={'draft': [('readonly', False)]}),
234         'analytic_id': fields.many2one('account.analytic.account','Write-Off Analytic Account', readonly=True, states={'draft': [('readonly', False)]}),
235         'writeoff_amount': fields.function(_get_writeoff_amount, method=True, string='Write-Off Amount', type='float', readonly=True),
236     }
237     _defaults = {
238         'period_id': _get_period,
239         'partner_id': _get_partner,
240         'journal_id':_get_journal,
241         'currency_id': _get_currency,
242         'reference': _get_reference,
243         'narration':_get_narration,
244         'amount': _get_amount,
245         'type':_get_type,
246         'state': 'draft',
247         'pay_now': 'pay_later',
248         'name': '',
249         'date': lambda *a: time.strftime('%Y-%m-%d'),
250         'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.voucher',context=c),
251         'tax_id': _get_tax,
252         'payment_option': 'without_writeoff',
253         'comment': _('Write-Off'),
254     }
255
256     def compute_tax(self, cr, uid, ids, context=None):
257         tax_pool = self.pool.get('account.tax')
258         partner_pool = self.pool.get('res.partner')
259         position_pool = self.pool.get('account.fiscal.position')
260         voucher_line_pool = self.pool.get('account.voucher.line')
261         voucher_pool = self.pool.get('account.voucher')
262         if context is None: context = {}
263
264         for voucher in voucher_pool.browse(cr, uid, ids, context=context):
265             voucher_amount = 0.0
266             for line in voucher.line_ids:
267                 voucher_amount += line.untax_amount or line.amount
268                 line.amount = line.untax_amount or line.amount
269                 voucher_line_pool.write(cr, uid, [line.id], {'amount':line.amount, 'untax_amount':line.untax_amount})
270
271             if not voucher.tax_id:
272                 self.write(cr, uid, [voucher.id], {'amount':voucher_amount, 'tax_amount':0.0})
273                 continue
274
275             tax = [tax_pool.browse(cr, uid, voucher.tax_id.id, context=context)]
276             partner = partner_pool.browse(cr, uid, voucher.partner_id.id, context=context) or False
277             taxes = position_pool.map_tax(cr, uid, partner and partner.property_account_position or False, tax)
278             tax = tax_pool.browse(cr, uid, taxes, context=context)
279
280             total = voucher_amount
281             total_tax = 0.0
282
283             if not tax[0].price_include:
284                 for tax_line in tax_pool.compute_all(cr, uid, tax, voucher_amount, 1).get('taxes', []):
285                     total_tax += tax_line.get('amount', 0.0)
286                 total += total_tax
287             else:
288                 for line in voucher.line_ids:
289                     line_total = 0.0
290                     line_tax = 0.0
291
292                     for tax_line in tax_pool.compute_all(cr, uid, tax, line.untax_amount or line.amount, 1).get('taxes', []):
293                         line_tax += tax_line.get('amount', 0.0)
294                         line_total += tax_line.get('price_unit')
295                     total_tax += line_tax
296                     untax_amount = line.untax_amount or line.amount
297                     voucher_line_pool.write(cr, uid, [line.id], {'amount':line_total, 'untax_amount':untax_amount})
298
299             self.write(cr, uid, [voucher.id], {'amount':total, 'tax_amount':total_tax})
300         return True
301
302     def onchange_price(self, cr, uid, ids, line_ids, tax_id, partner_id=False, context=None):
303         tax_pool = self.pool.get('account.tax')
304         partner_pool = self.pool.get('res.partner')
305         position_pool = self.pool.get('account.fiscal.position')
306         res = {
307             'tax_amount': False,
308             'amount': False,
309         }
310         voucher_total = 0.0
311         voucher_line_ids = []
312
313         total = 0.0
314         total_tax = 0.0
315         for line in line_ids:
316             line_amount = 0.0
317             line_amount = line[2] and line[2].get('amount',0.0) or 0.0
318             voucher_line_ids += [line[1]]
319             voucher_total += line_amount
320
321         total = voucher_total
322         total_tax = 0.0
323         if tax_id:
324             tax = [tax_pool.browse(cr, uid, tax_id, context=context)]
325             if partner_id:
326                 partner = partner_pool.browse(cr, uid, partner_id, context=context) or False
327                 taxes = position_pool.map_tax(cr, uid, partner and partner.property_account_position or False, tax)
328                 tax = tax_pool.browse(cr, uid, taxes, context=context)
329
330             if not tax[0].price_include:
331                 for tax_line in tax_pool.compute_all(cr, uid, tax, voucher_total, 1).get('taxes', []):
332                     total_tax += tax_line.get('amount')
333                 total += total_tax
334
335         res.update({
336             'amount':total or voucher_total,
337             'tax_amount':total_tax
338         })
339         return {
340             'value':res
341         }
342
343     def onchange_term_id(self, cr, uid, ids, term_id, amount):
344         term_pool = self.pool.get('account.payment.term')
345         terms = False
346         due_date = False
347         default = {'date_due':False}
348         if term_id and amount:
349             terms = term_pool.compute(cr, uid, term_id, amount)
350         if terms:
351             due_date = terms[-1][0]
352             default.update({
353                 'date_due':due_date
354             })
355         return {'value':default}
356
357     def onchange_journal_voucher(self, cr, uid, ids, line_ids=False, tax_id=False, price=0.0, partner_id=False, journal_id=False, ttype=False, context=None):
358         """price
359         Returns a dict that contains new values and context
360
361         @param partner_id: latest value from user input for field partner_id
362         @param args: other arguments
363         @param context: context arguments, like lang, time zone
364
365         @return: Returns a dict which contains new values, and context
366         """
367         default = {
368             'value':{},
369         }
370
371         if not partner_id or not journal_id:
372             return default
373
374         partner_pool = self.pool.get('res.partner')
375         journal_pool = self.pool.get('account.journal')
376
377         journal = journal_pool.browse(cr, uid, journal_id, context=context)
378         partner = partner_pool.browse(cr, uid, partner_id, context=context)
379         account_id = False
380         tr_type = False
381         if journal.type in ('sale','sale_refund'):
382             account_id = partner.property_account_receivable.id
383             tr_type = 'sale'
384         elif journal.type in ('purchase', 'purchase_refund','expense'):
385             account_id = partner.property_account_payable.id
386             tr_type = 'purchase'
387         else:
388             account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
389             tr_type = 'receipt'
390
391         default['value']['account_id'] = account_id
392         default['value']['type'] = ttype or tr_type
393
394         vals = self.onchange_journal(cr, uid, ids, journal_id, line_ids, tax_id, partner_id, context)
395         default['value'].update(vals.get('value'))
396
397         return default
398
399     def onchange_partner_id(self, cr, uid, ids, partner_id, journal_id, price, currency_id, ttype, date, context=None):
400         """price
401         Returns a dict that contains new values and context
402
403         @param partner_id: latest value from user input for field partner_id
404         @param args: other arguments
405         @param context: context arguments, like lang, time zone
406
407         @return: Returns a dict which contains new values, and context
408         """
409         if context is None:
410             context = {}
411         if not journal_id:
412             return {}
413         context_multi_currency = context.copy()
414         if date:
415             context_multi_currency.update({'date': date})
416
417         line_pool = self.pool.get('account.voucher.line')
418         line_ids = ids and line_pool.search(cr, uid, [('voucher_id', '=', ids[0])]) or False
419         if line_ids:
420             line_pool.unlink(cr, uid, line_ids)
421
422         currency_pool = self.pool.get('res.currency')
423         move_line_pool = self.pool.get('account.move.line')
424         partner_pool = self.pool.get('res.partner')
425         journal_pool = self.pool.get('account.journal')
426
427         vals = self.onchange_journal(cr, uid, ids, journal_id, [], False, partner_id, context)
428         vals = vals.get('value')
429         currency_id = vals.get('currency_id', currency_id)
430         default = {
431             'value':{'line_ids':[], 'line_dr_ids':[], 'line_cr_ids':[], 'pre_line': False, 'currency_id':currency_id},
432         }
433
434         if not partner_id:
435             return default
436
437         if not partner_id and ids:
438             line_ids = line_pool.search(cr, uid, [('voucher_id', '=', ids[0])])
439             if line_ids:
440                 line_pool.unlink(cr, uid, line_ids)
441             return default
442
443         journal = journal_pool.browse(cr, uid, journal_id, context=context)
444         partner = partner_pool.browse(cr, uid, partner_id, context=context)
445         account_id = False
446         if journal.type in ('sale','sale_refund'):
447             account_id = partner.property_account_receivable.id
448         elif journal.type in ('purchase', 'purchase_refund','expense'):
449             account_id = partner.property_account_payable.id
450         else:
451             account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
452
453         default['value']['account_id'] = account_id
454
455         if journal.type not in ('cash', 'bank'):
456             return default
457
458         total_credit = 0.0
459         total_debit = 0.0
460         account_type = 'receivable'
461         if ttype == 'payment':
462             account_type = 'payable'
463             total_debit = price or 0.0
464         else:
465             total_credit = price or 0.0
466             account_type = 'receivable'
467
468         if not context.get('move_line_ids', False):
469             domain = [('state','=','valid'), ('account_id.type', '=', account_type), ('reconcile_id', '=', False), ('partner_id', '=', partner_id)]
470             ids = move_line_pool.search(cr, uid, domain, context=context)
471         else:
472             ids = context['move_line_ids']
473         ids.reverse()
474         moves = move_line_pool.browse(cr, uid, ids, context=context)
475         move_line_found = False
476         invoice_id = context.get('invoice_id', False)
477         company_currency = journal.company_id.currency_id.id
478         if company_currency != currency_id and ttype == 'payment':
479             total_debit = currency_pool.compute(cr, uid, currency_id, company_currency, total_debit, context=context_multi_currency)
480         elif company_currency != currency_id and ttype == 'receipt':
481             total_credit = currency_pool.compute(cr, uid, currency_id, company_currency, total_credit, context=context_multi_currency)
482
483         for line in moves:
484             if line.reconcile_partial_id and line.amount_residual_currency < 0:
485                 # skip line that are totally used within partial reconcile
486                 continue
487             if invoice_id:
488                 if line.invoice.id == invoice_id:
489                     #if the invoice linked to the voucher line is equal to the invoice_id in context
490                     #then we assign the amount on that line, whatever the other voucher lines
491                     move_line_found = line.id
492                     break
493             elif currency_id == company_currency:
494                 #otherwise treatments is the same but with other field names
495                 if line.amount_residual == price:
496                     #if the amount residual is equal the amount voucher, we assign it to that voucher
497                     #line, whatever the other voucher lines
498                     move_line_found = line.id
499                     break
500                 #otherwise we will split the voucher amount on each line (by most old first)
501                 total_credit += line.credit or 0.0
502                 total_debit += line.debit or 0.0
503             elif currency_id == line.currency_id.id:
504                 if line.amount_residual_currency == price:
505                     move_line_found = line.id
506                     break
507                 total_credit += line.credit and line.amount_currency or 0.0
508                 total_debit += line.debit and line.amount_currency or 0.0
509         for line in moves:
510             if line.reconcile_partial_id and line.amount_residual_currency < 0:
511                 # skip line that are totally used within partial reconcile
512                 continue
513             original_amount = line.credit or line.debit or 0.0
514             amount_unreconciled = currency_pool.compute(cr, uid, line.currency_id and line.currency_id.id or company_currency, currency_id, abs(line.amount_residual_currency), context=context_multi_currency)
515             line_currency_id = line.currency_id and line.currency_id.id or company_currency
516             rs = {
517                 'name':line.move_id.name,
518                 'type': line.credit and 'dr' or 'cr',
519                 'move_line_id':line.id,
520                 'account_id':line.account_id.id,
521                 'amount': (move_line_found == line.id) and min(price, amount_unreconciled) or 0.0,
522                 'amount_original': currency_pool.compute(cr, uid, line.currency_id and line.currency_id.id or company_currency, currency_id, line.currency_id and abs(line.amount_currency) or original_amount, context=context_multi_currency),
523                 'date_original':line.date,
524                 'date_due':line.date_maturity,
525                 'amount_unreconciled': amount_unreconciled,
526                 'currency_id': line_currency_id,
527             }
528             if not move_line_found:
529                 if currency_id == line_currency_id:
530                     if line.credit:
531                         amount = min(amount_unreconciled, abs(total_debit))
532                         rs['amount'] = amount
533                         total_debit -= amount
534                     else:
535                         amount = min(amount_unreconciled, abs(total_credit))
536                         rs['amount'] = amount
537                         total_credit -= amount
538
539             default['value']['line_ids'].append(rs)
540             if rs['type'] == 'cr':
541                 default['value']['line_cr_ids'].append(rs)
542             else:
543                 default['value']['line_dr_ids'].append(rs)
544
545             if ttype == 'payment' and len(default['value']['line_cr_ids']) > 0:
546                 default['value']['pre_line'] = 1
547             elif ttype == 'receipt' and len(default['value']['line_dr_ids']) > 0:
548                 default['value']['pre_line'] = 1
549             default['value']['writeoff_amount'] = self._compute_writeoff_amount(cr, uid, default['value']['line_dr_ids'], default['value']['line_cr_ids'], price)
550
551         return default
552
553     def onchange_date(self, cr, uid, ids, partner_id, journal_id, price, currency_id, ttype, date, context=None):
554         """
555         @param date: latest value from user input for field date
556         @param args: other arguments
557         @param context: context arguments, like lang, time zone
558         @return: Returns a dict which contains new values, and context
559         """
560         if context is None: context = {}
561         period_pool = self.pool.get('account.period')
562         res = self.onchange_partner_id(cr, uid, ids, partner_id, journal_id, price, currency_id, ttype, date, context=context)
563         if context.get('invoice_id', False):
564             company_id = self.pool.get('account.invoice').browse(cr, uid, context['invoice_id'], context=context).company_id.id
565             context.update({'company_id': company_id})
566         pids = period_pool.find(cr, uid, date, context=context)
567         if pids:
568             if not 'value' in res:
569                 res['value'] = {}
570             res['value'].update({'period_id':pids[0]})
571         return res
572
573     def onchange_journal(self, cr, uid, ids, journal_id, line_ids, tax_id, partner_id, context=None):
574         if not journal_id:
575             return False
576         journal_pool = self.pool.get('account.journal')
577         journal = journal_pool.browse(cr, uid, journal_id, context=context)
578         account_id = journal.default_credit_account_id or journal.default_debit_account_id
579         tax_id = False
580         if account_id and account_id.tax_ids:
581             tax_id = account_id.tax_ids[0].id
582
583         vals = self.onchange_price(cr, uid, ids, line_ids, tax_id, partner_id, context)
584         vals['value'].update({'tax_id':tax_id})
585         currency_id = journal.company_id.currency_id.id
586         if journal.currency:
587             currency_id = journal.currency.id
588         vals['value'].update({'currency_id':currency_id})
589         return vals
590
591     def proforma_voucher(self, cr, uid, ids, context=None):
592         self.action_move_line_create(cr, uid, ids, context=context)
593         return True
594
595     def action_cancel_draft(self, cr, uid, ids, context=None):
596         wf_service = netsvc.LocalService("workflow")
597         for voucher_id in ids:
598             wf_service.trg_create(uid, 'account.voucher', voucher_id, cr)
599         self.write(cr, uid, ids, {'state':'draft'})
600         return True
601
602     def cancel_voucher(self, cr, uid, ids, context=None):
603         reconcile_pool = self.pool.get('account.move.reconcile')
604         move_pool = self.pool.get('account.move')
605         move_line_pool = self.pool.get('account.move.line')
606         for voucher in self.browse(cr, uid, ids, context=context):
607             for line in voucher.move_ids:
608                 if line.reconcile_id:
609                     move_lines = [move_line.id for move_line in line.reconcile_id.line_id]
610                     move_lines.remove(line.id)
611                     reconcile_pool.unlink(cr, uid, line.reconcile_id.id)
612                     if len(move_lines) >= 2:
613                         move_line_pool.reconcile_partial(cr, uid, move_lines, 'auto',context=context)
614             if voucher.move_id:
615                 move_pool.button_cancel(cr, uid, [voucher.move_id.id])
616                 move_pool.unlink(cr, uid, [voucher.move_id.id])
617         res = {
618             'state':'cancel',
619             'move_id':False,
620             'number': ''
621         }
622         self.write(cr, uid, ids, res)
623         return True
624
625     def unlink(self, cr, uid, ids, context=None):
626         for t in self.read(cr, uid, ids, ['state'], context=context):
627             if t['state'] not in ('draft', 'cancel'):
628                 raise osv.except_osv(_('Invalid action !'), _('Cannot delete Voucher(s) which are already opened or paid !'))
629         return super(account_voucher, self).unlink(cr, uid, ids, context=context)
630
631     # TODO: may be we can remove this method if not used anyware
632     def onchange_payment(self, cr, uid, ids, pay_now, journal_id, partner_id, ttype='sale'):
633         res = {}
634         if not partner_id:
635             return res
636         res = {'account_id':False}
637         partner_pool = self.pool.get('res.partner')
638         journal_pool = self.pool.get('account.journal')
639         if pay_now == 'pay_later':
640             partner = partner_pool.browse(cr, uid, partner_id)
641             journal = journal_pool.browse(cr, uid, journal_id)
642             if journal.type in ('sale','sale_refund'):
643                 account_id = partner.property_account_receivable.id
644             elif journal.type in ('purchase', 'purchase_refund','expense'):
645                 account_id = partner.property_account_payable.id
646             else:
647                 account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
648             res['account_id'] = account_id
649         return {'value':res}
650
651     def action_move_line_create(self, cr, uid, ids, context=None):
652
653         def _get_payment_term_lines(term_id, amount):
654             term_pool = self.pool.get('account.payment.term')
655             if term_id and amount:
656                 terms = term_pool.compute(cr, uid, term_id, amount)
657                 return terms
658             return False
659         if context is None:
660             context = {}
661         move_pool = self.pool.get('account.move')
662         move_line_pool = self.pool.get('account.move.line')
663         currency_pool = self.pool.get('res.currency')
664         tax_obj = self.pool.get('account.tax')
665         seq_obj = self.pool.get('ir.sequence')
666         for inv in self.browse(cr, uid, ids, context=context):
667             if inv.move_id:
668                 continue
669             context_multi_currency = context.copy()
670             context_multi_currency.update({'date': inv.date})
671             
672             if inv.journal_id.sequence_id:
673                 name = seq_obj.get_id(cr, uid, inv.journal_id.sequence_id.id)
674             if not name:
675                 raise osv.except_osv(_('Error !'), _('Please define a sequence on the journal and make sure it is activated !'))
676             if not inv.reference:
677                 ref = name.replace('/','')
678             else:
679                 ref = inv.reference
680
681             move = {
682                 'name': name,
683                 'journal_id': inv.journal_id.id,
684                 'narration': inv.narration,
685                 'date': inv.date,
686                 'ref': ref,
687                 'period_id': inv.period_id and inv.period_id.id or False
688             }
689             move_id = move_pool.create(cr, uid, move)
690
691             #create the first line manually
692             company_currency = inv.journal_id.company_id.currency_id.id
693             current_currency = inv.currency_id.id
694             debit = 0.0
695             credit = 0.0
696             # TODO: is there any other alternative then the voucher type ??
697             # -for sale, purchase we have but for the payment and receipt we do not have as based on the bank/cash journal we can not know its payment or receipt
698             if inv.type in ('purchase', 'payment'):
699                 credit = currency_pool.compute(cr, uid, current_currency, company_currency, inv.amount, context=context_multi_currency)
700             elif inv.type in ('sale', 'receipt'):
701                 debit = currency_pool.compute(cr, uid, current_currency, company_currency, inv.amount, context=context_multi_currency)
702             if debit < 0:
703                 credit = -debit
704                 debit = 0.0
705             if credit < 0:
706                 debit = -credit
707                 credit = 0.0
708             sign = debit - credit < 0 and -1 or 1
709             #create the first line of the voucher
710             move_line = {
711                 'name': inv.name or '/',
712                 'debit': debit,
713                 'credit': credit,
714                 'account_id': inv.account_id.id,
715                 'move_id': move_id,
716                 'journal_id': inv.journal_id.id,
717                 'period_id': inv.period_id.id,
718                 'partner_id': inv.partner_id.id,
719                 'currency_id': company_currency <> current_currency and  current_currency or False,
720                 'amount_currency': company_currency <> current_currency and sign * inv.amount or 0.0,
721                 'date': inv.date,
722                 'date_maturity': inv.date_due
723             }
724             move_line_pool.create(cr, uid, move_line)
725             rec_list_ids = []
726             line_total = debit - credit
727             if inv.type == 'sale':
728                 line_total = line_total - currency_pool.compute(cr, uid, inv.currency_id.id, company_currency, inv.tax_amount, context=context_multi_currency)
729             elif inv.type == 'purchase':
730                 line_total = line_total + currency_pool.compute(cr, uid, inv.currency_id.id, company_currency, inv.tax_amount, context=context_multi_currency)
731
732             for line in inv.line_ids:
733                 #create one move line per voucher line where amount is not 0.0
734                 if not line.amount:
735                     continue
736                 #we check if the voucher line is fully paid or not and create a move line to balance the payment and initial invoice if needed
737                 if line.amount == line.amount_unreconciled:
738                     amount = line.move_line_id.amount_residual #residual amount in company currency
739                 else:
740                     amount = currency_pool.compute(cr, uid, current_currency, company_currency, line.untax_amount or line.amount, context=context_multi_currency)
741                 move_line = {
742                     'journal_id': inv.journal_id.id,
743                     'period_id': inv.period_id.id,
744                     'name': line.name and line.name or '/',
745                     'account_id': line.account_id.id,
746                     'move_id': move_id,
747                     'partner_id': inv.partner_id.id,
748                     'currency_id': company_currency <> current_currency and current_currency or False,
749                     'analytic_account_id': line.account_analytic_id and line.account_analytic_id.id or False,
750                     'quantity': 1,
751                     'credit': 0.0,
752                     'debit': 0.0,
753                     'date': inv.date
754                 }
755                 if not amount:
756                     raise osv.except_osv(_('Warning'),
757                         _("Error while processing 'account.voucher %s' (id:%s) for partner '%s', amount: %s !") % (inv.name, inv.id, inv.partner_id.name, inv.amount))
758                 if amount < 0:
759                     amount = -amount
760                     if line.type == 'dr':
761                         line.type = 'cr'
762                     else:
763                         line.type = 'dr'
764
765                 if (line.type=='dr'):
766                     line_total += amount
767                     move_line['debit'] = amount
768                 else:
769                     line_total -= amount
770                     move_line['credit'] = amount
771
772                 if inv.tax_id and inv.type in ('sale', 'purchase'):
773                     move_line.update({
774                         'account_tax_id': inv.tax_id.id,
775                     })
776                 if move_line.get('account_tax_id', False):
777                     tax_data = tax_obj.browse(cr, uid, [move_line['account_tax_id']], context=context)[0]
778                     if not (tax_data.base_code_id and tax_data.tax_code_id):
779                         raise osv.except_osv(_('No Account Base Code and Account Tax Code!'),_("You have to configure account base code and account tax code on the '%s' tax!") % (tax_data.name))
780                 sign = (move_line['debit'] - move_line['credit']) < 0 and -1 or 1
781                 move_line['amount_currency'] = company_currency <> current_currency and sign * line.amount or 0.0
782                 voucher_line = move_line_pool.create(cr, uid, move_line)
783                 if line.move_line_id.id:
784                     rec_ids = [voucher_line, line.move_line_id.id]
785                     rec_list_ids.append(rec_ids)
786
787             inv_currency_id = inv.currency_id or inv.journal_id.currency or inv.journal_id.company_id.currency_id
788             if not currency_pool.is_zero(cr, uid, inv_currency_id, line_total):
789                 diff = line_total
790                 account_id = False
791                 if inv.payment_option == 'with_writeoff':
792                     account_id = inv.writeoff_acc_id.id
793                 elif inv.type in ('sale', 'receipt'):
794                     account_id = inv.partner_id.property_account_receivable.id
795                 else:
796                     account_id = inv.partner_id.property_account_payable.id
797                 move_line = {
798                     'name': name,
799                     'account_id': account_id,
800                     'move_id': move_id,
801                     'partner_id': inv.partner_id.id,
802                     'date': inv.date,
803                     'credit': diff > 0 and diff or 0.0,
804                     'debit': diff < 0 and -diff or 0.0,
805                     'analytic_account_id': inv.analytic_id and inv.analytic_id.id or False,
806                     #'amount_currency': company_currency <> current_currency and currency_pool.compute(cr, uid, company_currency, current_currency, diff * -1, context=context_multi_currency) or 0.0,
807                     #'currency_id': company_currency <> current_currency and current_currency or False,
808                 }
809                 move_line_pool.create(cr, uid, move_line)
810             self.write(cr, uid, [inv.id], {
811                 'move_id': move_id,
812                 'state': 'posted',
813                 'number': name,
814             })
815             move_pool.post(cr, uid, [move_id], context={})
816             for rec_ids in rec_list_ids:
817                 if len(rec_ids) >= 2:
818                     move_line_pool.reconcile_partial(cr, uid, rec_ids)
819         return True
820
821     def copy(self, cr, uid, id, default={}, context=None):
822         default.update({
823             'state': 'draft',
824             'number': False,
825             'move_id': False,
826             'line_cr_ids': False,
827             'line_dr_ids': False,
828             'reference': False
829         })
830         if 'date' not in default:
831             default['date'] = time.strftime('%Y-%m-%d')
832         return super(account_voucher, self).copy(cr, uid, id, default, context)
833
834 account_voucher()
835
836 class account_voucher_line(osv.osv):
837     _name = 'account.voucher.line'
838     _description = 'Voucher Lines'
839     _order = "move_line_id"
840
841     def _compute_balance(self, cr, uid, ids, name, args, context=None):
842         currency_pool = self.pool.get('res.currency')
843         rs_data = {}
844         for line in self.browse(cr, uid, ids, context=context):
845             ctx = context.copy()
846             ctx.update({'date': line.voucher_id.date})
847             res = {}
848             company_currency = line.voucher_id.journal_id.company_id.currency_id.id
849             voucher_currency = line.voucher_id.currency_id.id
850             move_line = line.move_line_id or False
851
852             if not move_line:
853                 res['amount_original'] = 0.0
854                 res['amount_unreconciled'] = 0.0
855
856             elif move_line.currency_id:
857                 res['amount_original'] = currency_pool.compute(cr, uid, move_line.currency_id.id, voucher_currency, move_line.amount_currency, context=ctx)
858             elif move_line and move_line.credit > 0:
859                 res['amount_original'] = currency_pool.compute(cr, uid, company_currency, voucher_currency, move_line.credit, context=ctx)
860             else:
861                 res['amount_original'] = currency_pool.compute(cr, uid, company_currency, voucher_currency, move_line.debit, context=ctx)
862
863             if move_line:
864                 res['amount_unreconciled'] = currency_pool.compute(cr, uid, move_line.currency_id and move_line.currency_id.id or company_currency, voucher_currency, abs(move_line.amount_residual_currency), context=ctx)
865             rs_data[line.id] = res
866         return rs_data
867
868     _columns = {
869         'voucher_id':fields.many2one('account.voucher', 'Voucher', required=1, ondelete='cascade'),
870         'name':fields.char('Description', size=256),
871         'account_id':fields.many2one('account.account','Account', required=True),
872         'partner_id':fields.related('voucher_id', 'partner_id', type='many2one', relation='res.partner', string='Partner'),
873         'untax_amount':fields.float('Untax Amount'),
874         'amount':fields.float('Amount', digits_compute=dp.get_precision('Account')),
875         'type':fields.selection([('dr','Debit'),('cr','Credit')], 'Cr/Dr'),
876         'account_analytic_id':  fields.many2one('account.analytic.account', 'Analytic Account'),
877         'move_line_id': fields.many2one('account.move.line', 'Journal Item'),
878         'date_original': fields.related('move_line_id','date', type='date', relation='account.move.line', string='Date', readonly=1),
879         'date_due': fields.related('move_line_id','date_maturity', type='date', relation='account.move.line', string='Due Date', readonly=1),
880         'amount_original': fields.function(_compute_balance, method=True, multi='dc', type='float', string='Original Amount', store=True, digits_compute=dp.get_precision('Account')),
881         'amount_unreconciled': fields.function(_compute_balance, method=True, multi='dc', type='float', string='Open Balance', store=True, digits_compute=dp.get_precision('Account')),
882         'company_id': fields.related('voucher_id','company_id', relation='res.company', type='many2one', string='Company', store=True, readonly=True),
883     }
884     _defaults = {
885         'name': ''
886     }
887     
888     def fields_view_get(self, cr, uid, view_id=None, view_type=False, context=None, toolbar=False, submenu=False):
889         res = super(account_voucher_line, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu)
890         if view_type == 'form':
891             doc = etree.XML(res['arch'])
892             nodes = doc.xpath("//field[@name='account_id']")
893             for node in nodes:
894                 if context.get('default_type') == 'dr':
895                     if context.get('type') == 'payment':
896                         node.set('domain', "[('type','=','payable')]")
897                     elif context.get('type') == 'receipt':
898                         node.set('domain', "[('type','=','receivable')]")
899                     elif context.get('type') == 'purchase':
900                         node.set('domain', "[('user_type.report_type','=','expense'), ('type','!=','view')]")
901                 elif context.get('default_type') == 'cr':
902                     if context.get('type') == 'sale':
903                         node.set('domain', "[('user_type.report_type','=','income'),('type','!=','view')]")
904                     elif context.get('type') == 'receipt':
905                         node.set('domain', "[('type','=','receivable')]")
906                     elif context.get('type') == 'payment':
907                         node.set('domain', "[('type','=','payable')]")
908                 else:
909                     node.set('domain', "[('type','!=','view')]")
910             res['arch'] = etree.tostring(doc)
911         return res
912
913
914     def onchange_move_line_id(self, cr, user, ids, move_line_id, context=None):
915         """
916         Returns a dict that contains new values and context
917
918         @param move_line_id: latest value from user input for field move_line_id
919         @param args: other arguments
920         @param context: context arguments, like lang, time zone
921
922         @return: Returns a dict which contains new values, and context
923         """
924         res = {}
925         move_line_pool = self.pool.get('account.move.line')
926         if move_line_id:
927             move_line = move_line_pool.browse(cr, user, move_line_id, context=context)
928             if move_line.credit:
929                 ttype = 'dr'
930             else:
931                 ttype = 'cr'
932             account_id = move_line.account_id.id
933             res.update({
934                 'account_id':account_id,
935                 'type': ttype
936             })
937         return {
938             'value':res,
939         }
940
941     def default_get(self, cr, user, fields_list, context=None):
942         """
943         Returns default values for fields
944         @param fields_list: list of fields, for which default values are required to be read
945         @param context: context arguments, like lang, time zone
946
947         @return: Returns a dict that contains default values for fields
948         """
949         if context is None:
950             context = {}
951         journal_id = context.get('journal_id', False)
952         partner_id = context.get('partner_id', False)
953         journal_pool = self.pool.get('account.journal')
954         partner_pool = self.pool.get('res.partner')
955         values = super(account_voucher_line, self).default_get(cr, user, fields_list, context=context)
956         if (not journal_id) or ('account_id' not in fields_list):
957             return values
958         journal = journal_pool.browse(cr, user, journal_id, context=context)
959         account_id = False
960         ttype = 'cr'
961         if journal.type in ('sale', 'sale_refund'):
962             account_id = journal.default_credit_account_id and journal.default_credit_account_id.id or False
963             ttype = 'cr'
964         elif journal.type in ('purchase', 'expense', 'purchase_refund'):
965             account_id = journal.default_debit_account_id and journal.default_debit_account_id.id or False
966             ttype = 'dr'
967         elif partner_id:
968             partner = partner_pool.browse(cr, user, partner_id, context=context)
969             if context.get('type') == 'payment':
970                 ttype = 'dr'
971                 account_id = partner.property_account_payable.id
972             elif context.get('type') == 'receipt':
973                 account_id = partner.property_account_receivable.id
974
975         values.update({
976             'account_id':account_id,
977             'type':ttype
978         })
979         return values
980 account_voucher_line()
981
982 class account_bank_statement(osv.osv):
983     _inherit = 'account.bank.statement'
984
985     def button_cancel(self, cr, uid, ids, context=None):
986         voucher_obj = self.pool.get('account.voucher')
987         for st in self.browse(cr, uid, ids, context=context):
988             voucher_ids = []
989             for line in st.line_ids:
990                 if line.voucher_id:
991                     voucher_ids.append(line.voucher_id.id)
992             voucher_obj.cancel_voucher(cr, uid, voucher_ids, context)
993         return super(account_bank_statement, self).button_cancel(cr, uid, ids, context=context)
994
995     def create_move_from_st_line(self, cr, uid, st_line_id, company_currency_id, next_number, context=None):
996         voucher_obj = self.pool.get('account.voucher')
997         wf_service = netsvc.LocalService("workflow")
998         move_line_obj = self.pool.get('account.move.line')
999         bank_st_line_obj = self.pool.get('account.bank.statement.line')
1000         st_line = bank_st_line_obj.browse(cr, uid, st_line_id, context=context)
1001         if st_line.voucher_id:
1002             voucher_obj.write(cr, uid, [st_line.voucher_id.id],
1003                             {'number': next_number,
1004                             'date': st_line.date,
1005                             'period_id': st_line.statement_id.period_id.id},
1006                             context=context)
1007             if st_line.voucher_id.state == 'cancel':
1008                 voucher_obj.action_cancel_draft(cr, uid, [st_line.voucher_id.id], context=context)
1009             wf_service.trg_validate(uid, 'account.voucher', st_line.voucher_id.id, 'proforma_voucher', cr)
1010
1011             v = voucher_obj.browse(cr, uid, st_line.voucher_id.id, context=context)
1012             bank_st_line_obj.write(cr, uid, [st_line_id], {
1013                 'move_ids': [(4, v.move_id.id, False)]
1014             })
1015
1016             return move_line_obj.write(cr, uid, [x.id for x in v.move_ids], {'statement_id': st_line.statement_id.id}, context=context)
1017         return super(account_bank_statement, self).create_move_from_st_line(cr, uid, st_line.id, company_currency_id, next_number, context=context)
1018
1019 account_bank_statement()
1020
1021 class account_bank_statement_line(osv.osv):
1022     _inherit = 'account.bank.statement.line'
1023
1024     def _amount_reconciled(self, cursor, user, ids, name, args, context=None):
1025         if not ids:
1026             return {}
1027
1028         res = {}
1029 #        company_currency_id = False
1030         for line in self.browse(cursor, user, ids, context=context):
1031 #            if not company_currency_id:
1032 #                company_currency_id = line.company_id.id
1033             if line.voucher_id:
1034                 res[line.id] = line.voucher_id.amount#
1035 #                        res_currency_obj.compute(cursor, user,
1036 #                        company_currency_id, line.statement_id.currency.id,
1037 #                        line.voucher_id.amount, context=context)
1038             else:
1039                 res[line.id] = 0.0
1040         return res
1041
1042     def _check_amount(self, cr, uid, ids, context=None):
1043         for obj in self.browse(cr, uid, ids, context=context):
1044             if obj.voucher_id:
1045                 if not (abs(obj.amount) == obj.voucher_id.amount):
1046                     return False
1047         return True
1048
1049     _constraints = [
1050         (_check_amount, 'The amount of the voucher must be the same amount as the one on the statement line', ['amount']),
1051     ]
1052
1053     _columns = {
1054         'amount_reconciled': fields.function(_amount_reconciled,
1055             string='Amount reconciled', method=True, type='float'),
1056         'voucher_id': fields.many2one('account.voucher', 'Payment'),
1057
1058     }
1059
1060     def unlink(self, cr, uid, ids, context=None):
1061         voucher_obj = self.pool.get('account.voucher')
1062         statement_line = self.browse(cr, uid, ids, context=context)
1063         unlink_ids = []
1064         for st_line in statement_line:
1065             if st_line.voucher_id:
1066                 unlink_ids.append(st_line.voucher_id.id)
1067         voucher_obj.unlink(cr, uid, unlink_ids, context=context)
1068         return super(account_bank_statement_line, self).unlink(cr, uid, ids, context=context)
1069
1070 account_bank_statement_line()
1071
1072 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: