[FIX] account_voucher: partial reconcile disappears when we cancel partial payments
[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             if context.get('invoice_id', False):
471                     domain.append(('invoice', '=', context['invoice_id']))
472             ids = move_line_pool.search(cr, uid, domain, context=context)
473         else:
474             ids = context['move_line_ids']
475         ids.reverse()
476         moves = move_line_pool.browse(cr, uid, ids, context=context)
477
478         company_currency = journal.company_id.currency_id.id
479         if company_currency != currency_id and ttype == 'payment':
480             total_debit = currency_pool.compute(cr, uid, currency_id, company_currency, total_debit, context=context_multi_currency)
481         elif company_currency != currency_id and ttype == 'receipt':
482             total_credit = currency_pool.compute(cr, uid, currency_id, company_currency, total_credit, context=context_multi_currency)
483
484         for line in moves:
485             if line.credit and line.reconcile_partial_id and ttype == 'receipt':
486                 continue
487             if line.debit and line.reconcile_partial_id and ttype == 'payment':
488                 continue
489             total_credit += line.credit or 0.0
490             total_debit += line.debit or 0.0
491         for line in moves:
492             if line.credit and line.reconcile_partial_id and ttype == 'receipt':
493                 continue
494             if line.debit and line.reconcile_partial_id and ttype == 'payment':
495                 continue
496             original_amount = line.credit or line.debit or 0.0
497             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)
498             rs = {
499                 'name':line.move_id.name,
500                 'type': line.credit and 'dr' or 'cr',
501                 'move_line_id':line.id,
502                 'account_id':line.account_id.id,
503                 '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),
504                 'date_original':line.date,
505                 'date_due':line.date_maturity,
506                 'amount_unreconciled': amount_unreconciled,
507             }
508
509             if line.credit:
510                 amount = min(amount_unreconciled, currency_pool.compute(cr, uid, company_currency, currency_id, abs(total_debit), context=context_multi_currency))
511                 rs['amount'] = amount
512                 total_debit -= amount
513             else:
514                 amount = min(amount_unreconciled, currency_pool.compute(cr, uid, company_currency, currency_id, abs(total_credit), context=context_multi_currency))
515                 rs['amount'] = amount
516                 total_credit -= amount
517
518             default['value']['line_ids'].append(rs)
519             if rs['type'] == 'cr':
520                 default['value']['line_cr_ids'].append(rs)
521             else:
522                 default['value']['line_dr_ids'].append(rs)
523
524             if ttype == 'payment' and len(default['value']['line_cr_ids']) > 0:
525                 default['value']['pre_line'] = 1
526             elif ttype == 'receipt' and len(default['value']['line_dr_ids']) > 0:
527                 default['value']['pre_line'] = 1
528             default['value']['writeoff_amount'] = self._compute_writeoff_amount(cr, uid, default['value']['line_dr_ids'], default['value']['line_cr_ids'], price)
529
530         return default
531
532     def onchange_date(self, cr, uid, ids, partner_id, journal_id, price, currency_id, ttype, date, context=None):
533         """
534         @param date: latest value from user input for field date
535         @param args: other arguments
536         @param context: context arguments, like lang, time zone
537         @return: Returns a dict which contains new values, and context
538         """
539         if context is None: context = {}
540         period_pool = self.pool.get('account.period')
541         res = self.onchange_partner_id(cr, uid, ids, partner_id, journal_id, price, currency_id, ttype, date, context=context)
542         if context.get('invoice_id', False):
543             company_id = self.pool.get('account.invoice').browse(cr, uid, context['invoice_id'], context=context).company_id.id
544             context.update({'company_id': company_id})
545         pids = period_pool.find(cr, uid, date, context=context)
546         if pids:
547             if not 'value' in res:
548                 res['value'] = {}
549             res['value'].update({'period_id':pids[0]})
550         return res
551
552     def onchange_journal(self, cr, uid, ids, journal_id, line_ids, tax_id, partner_id, context=None):
553         if not journal_id:
554             return False
555         journal_pool = self.pool.get('account.journal')
556         journal = journal_pool.browse(cr, uid, journal_id, context=context)
557         account_id = journal.default_credit_account_id or journal.default_debit_account_id
558         tax_id = False
559         if account_id and account_id.tax_ids:
560             tax_id = account_id.tax_ids[0].id
561
562         vals = self.onchange_price(cr, uid, ids, line_ids, tax_id, partner_id, context)
563         vals['value'].update({'tax_id':tax_id})
564         currency_id = journal.company_id.currency_id.id
565         if journal.currency:
566             currency_id = journal.currency.id
567         vals['value'].update({'currency_id':currency_id})
568         return vals
569
570     def proforma_voucher(self, cr, uid, ids, context=None):
571         self.action_move_line_create(cr, uid, ids, context=context)
572         return True
573
574     def action_cancel_draft(self, cr, uid, ids, context=None):
575         wf_service = netsvc.LocalService("workflow")
576         for voucher_id in ids:
577             wf_service.trg_create(uid, 'account.voucher', voucher_id, cr)
578         self.write(cr, uid, ids, {'state':'draft'})
579         return True
580
581     def cancel_voucher(self, cr, uid, ids, context=None):
582         reconcile_pool = self.pool.get('account.move.reconcile')
583         move_pool = self.pool.get('account.move')
584
585         for voucher in self.browse(cr, uid, ids, context=context):
586             recs = []
587             for line in voucher.move_ids:
588                 if line.reconcile_id:
589                     recs = [rec.id for rec in line.reconcile_id.line_id]
590                     recs.remove(line.id)
591                     partial_ids = reconcile_pool.create(cr, uid, {
592                         'type': 'auto',
593                         'line_id': False,
594                         'line_partial_ids': [(6, 0, recs)]})
595                     self.pool.get('account.move.line').write(cr, uid, [line.id], {
596                         'reconcile_id': False,
597                         'reconcile_partial_id': False
598                         }, update_check=False)
599                     
600                     self.pool.get('account.move.line').write(cr, uid, recs, {
601                         'reconcile_id': False,
602                         'reconcile_partial_id': partial_ids
603                     }, update_check=False)
604             if recs:
605                 reconcile_pool.unlink(cr, uid, recs)
606             if voucher.move_id:
607                 move_pool.button_cancel(cr, uid, [voucher.move_id.id])
608                 move_pool.unlink(cr, uid, [voucher.move_id.id])
609         res = {
610             'state':'cancel',
611             'move_id':False,
612         }
613         self.write(cr, uid, ids, res)
614         return True
615
616     def unlink(self, cr, uid, ids, context=None):
617         for t in self.read(cr, uid, ids, ['state'], context=context):
618             if t['state'] not in ('draft', 'cancel'):
619                 raise osv.except_osv(_('Invalid action !'), _('Cannot delete Voucher(s) which are already opened or paid !'))
620         return super(account_voucher, self).unlink(cr, uid, ids, context=context)
621
622     # TODO: may be we can remove this method if not used anyware
623     def onchange_payment(self, cr, uid, ids, pay_now, journal_id, partner_id, ttype='sale'):
624         res = {}
625         if not partner_id:
626             return res
627         res = {'account_id':False}
628         partner_pool = self.pool.get('res.partner')
629         journal_pool = self.pool.get('account.journal')
630         if pay_now == 'pay_later':
631             partner = partner_pool.browse(cr, uid, partner_id)
632             journal = journal_pool.browse(cr, uid, journal_id)
633             if journal.type in ('sale','sale_refund'):
634                 account_id = partner.property_account_receivable.id
635             elif journal.type in ('purchase', 'purchase_refund','expense'):
636                 account_id = partner.property_account_payable.id
637             else:
638                 account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
639             res['account_id'] = account_id
640         return {'value':res}
641
642     def action_move_line_create(self, cr, uid, ids, context=None):
643
644         def _get_payment_term_lines(term_id, amount):
645             term_pool = self.pool.get('account.payment.term')
646             if term_id and amount:
647                 terms = term_pool.compute(cr, uid, term_id, amount)
648                 return terms
649             return False
650         if context is None:
651             context = {}
652         move_pool = self.pool.get('account.move')
653         move_line_pool = self.pool.get('account.move.line')
654         currency_pool = self.pool.get('res.currency')
655         tax_obj = self.pool.get('account.tax')
656         seq_obj = self.pool.get('ir.sequence')
657         for inv in self.browse(cr, uid, ids, context=context):
658             if inv.move_id:
659                 continue
660             context_multi_currency = context.copy()
661             context_multi_currency.update({'date': inv.date})
662
663             if inv.number:
664                 name = inv.number
665             elif inv.journal_id.sequence_id:
666                 name = seq_obj.get_id(cr, uid, inv.journal_id.sequence_id.id)
667             if not name:
668                 raise osv.except_osv(_('Error !'), _('Please define a sequence on the journal and make sure it is activated !'))
669             if not inv.reference:
670                 ref = name.replace('/','')
671             else:
672                 ref = inv.reference
673
674             move = {
675                 'name': name,
676                 'journal_id': inv.journal_id.id,
677                 'narration': inv.narration,
678                 'date': inv.date,
679                 'ref': ref,
680                 'period_id': inv.period_id and inv.period_id.id or False
681             }
682             move_id = move_pool.create(cr, uid, move)
683
684             #create the first line manually
685             company_currency = inv.journal_id.company_id.currency_id.id
686             current_currency = inv.currency_id.id
687             debit = 0.0
688             credit = 0.0
689             # TODO: is there any other alternative then the voucher type ??
690             # -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
691             if inv.type in ('purchase', 'payment'):
692                 credit = currency_pool.compute(cr, uid, current_currency, company_currency, inv.amount, context=context_multi_currency)
693             elif inv.type in ('sale', 'receipt'):
694                 debit = currency_pool.compute(cr, uid, current_currency, company_currency, inv.amount, context=context_multi_currency)
695             if debit < 0:
696                 credit = -debit
697                 debit = 0.0
698             if credit < 0:
699                 debit = -credit
700                 credit = 0.0
701             sign = debit - credit < 0 and -1 or 1
702             #create the first line of the voucher
703             move_line = {
704                 'name': inv.name or '/',
705                 'debit': debit,
706                 'credit': credit,
707                 'account_id': inv.account_id.id,
708                 'move_id': move_id,
709                 'journal_id': inv.journal_id.id,
710                 'period_id': inv.period_id.id,
711                 'partner_id': inv.partner_id.id,
712                 'currency_id': company_currency <> current_currency and  current_currency or False,
713                 'amount_currency': company_currency <> current_currency and sign * inv.amount or 0.0,
714                 'date': inv.date,
715                 'date_maturity': inv.date_due
716             }
717             move_line_pool.create(cr, uid, move_line)
718             rec_list_ids = []
719             line_total = debit - credit
720             if inv.type == 'sale':
721                 line_total = line_total - currency_pool.compute(cr, uid, inv.currency_id.id, company_currency, inv.tax_amount, context=context_multi_currency)
722             elif inv.type == 'purchase':
723                 line_total = line_total + currency_pool.compute(cr, uid, inv.currency_id.id, company_currency, inv.tax_amount, context=context_multi_currency)
724
725             for line in inv.line_ids:
726                 #create one move line per voucher line where amount is not 0.0
727                 if not line.amount:
728                     continue
729                 #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
730                 if line.amount == line.amount_unreconciled:
731                     amount = line.move_line_id.amount_residual #residual amount in company currency
732                 else:
733                     amount = currency_pool.compute(cr, uid, current_currency, company_currency, line.untax_amount or line.amount, context=context_multi_currency)
734                 move_line = {
735                     'journal_id': inv.journal_id.id,
736                     'period_id': inv.period_id.id,
737                     'name': line.name and line.name or '/',
738                     'account_id': line.account_id.id,
739                     'move_id': move_id,
740                     'partner_id': inv.partner_id.id,
741                     'currency_id': company_currency <> current_currency and current_currency or False,
742                     'analytic_account_id': line.account_analytic_id and line.account_analytic_id.id or False,
743                     'quantity': 1,
744                     'credit': 0.0,
745                     'debit': 0.0,
746                     'date': inv.date
747                 }
748                 if amount < 0:
749                     amount = -amount
750                     if line.type == 'dr':
751                         line.type = 'cr'
752                     else:
753                         line.type = 'dr'
754
755                 if (line.type=='dr'):
756                     line_total += amount
757                     move_line['debit'] = amount
758                 else:
759                     line_total -= amount
760                     move_line['credit'] = amount
761
762                 if inv.tax_id and inv.type in ('sale', 'purchase'):
763                     move_line.update({
764                         'account_tax_id': inv.tax_id.id,
765                     })
766                 if move_line.get('account_tax_id', False):
767                     tax_data = tax_obj.browse(cr, uid, [move_line['account_tax_id']], context=context)[0]
768                     if not (tax_data.base_code_id and tax_data.tax_code_id):
769                         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))
770                 sign = (move_line['debit'] - move_line['credit']) < 0 and -1 or 1
771                 move_line['amount_currency'] = company_currency <> current_currency and sign * line.amount or 0.0
772                 voucher_line = move_line_pool.create(cr, uid, move_line)
773                 if line.move_line_id.id:
774                     rec_ids = [voucher_line, line.move_line_id.id]
775                     rec_list_ids.append(rec_ids)
776
777             inv_currency_id = inv.currency_id or inv.journal_id.currency or inv.journal_id.company_id.currency_id
778             if not currency_pool.is_zero(cr, uid, inv_currency_id, line_total):
779                 diff = line_total
780                 account_id = False
781                 if inv.payment_option == 'with_writeoff':
782                     account_id = inv.writeoff_acc_id.id
783                 elif inv.type in ('sale', 'receipt'):
784                     account_id = inv.partner_id.property_account_receivable.id
785                 else:
786                     account_id = inv.partner_id.property_account_payable.id
787                 move_line = {
788                     'name': name,
789                     'account_id': account_id,
790                     'move_id': move_id,
791                     'partner_id': inv.partner_id.id,
792                     'date': inv.date,
793                     'credit': diff > 0 and diff or 0.0,
794                     'debit': diff < 0 and -diff or 0.0,
795                     #'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,
796                     #'currency_id': company_currency <> current_currency and current_currency or False,
797                 }
798                 move_line_pool.create(cr, uid, move_line)
799             self.write(cr, uid, [inv.id], {
800                 'move_id': move_id,
801                 'state': 'posted',
802                 'number': name,
803             })
804             move_pool.post(cr, uid, [move_id], context={})
805             for rec_ids in rec_list_ids:
806                 if len(rec_ids) >= 2:
807                     move_line_pool.reconcile_partial(cr, uid, rec_ids)
808         return True
809
810     def copy(self, cr, uid, id, default={}, context=None):
811         default.update({
812             'state': 'draft',
813             'number': False,
814             'move_id': False,
815             'line_cr_ids': False,
816             'line_dr_ids': False,
817             'reference': False
818         })
819         if 'date' not in default:
820             default['date'] = time.strftime('%Y-%m-%d')
821         return super(account_voucher, self).copy(cr, uid, id, default, context)
822
823 account_voucher()
824
825 class account_voucher_line(osv.osv):
826     _name = 'account.voucher.line'
827     _description = 'Voucher Lines'
828     _order = "move_line_id"
829
830     def _compute_balance(self, cr, uid, ids, name, args, context=None):
831         currency_pool = self.pool.get('res.currency')
832         rs_data = {}
833         for line in self.browse(cr, uid, ids, context=context):
834             ctx = context.copy()
835             ctx.update({'date': line.voucher_id.date})
836             res = {}
837             company_currency = line.voucher_id.journal_id.company_id.currency_id.id
838             voucher_currency = line.voucher_id.currency_id.id
839             move_line = line.move_line_id or False
840
841             if not move_line:
842                 res['amount_original'] = 0.0
843                 res['amount_unreconciled'] = 0.0
844
845             elif move_line.currency_id:
846                 res['amount_original'] = currency_pool.compute(cr, uid, move_line.currency_id.id, voucher_currency, move_line.amount_currency, context=ctx)
847             elif move_line and move_line.credit > 0:
848                 res['amount_original'] = currency_pool.compute(cr, uid, company_currency, voucher_currency, move_line.credit, context=ctx)
849             else:
850                 res['amount_original'] = currency_pool.compute(cr, uid, company_currency, voucher_currency, move_line.debit, context=ctx)
851
852             if move_line:
853                 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)
854             rs_data[line.id] = res
855         return rs_data
856
857     _columns = {
858         'voucher_id':fields.many2one('account.voucher', 'Voucher', required=1, ondelete='cascade'),
859         'name':fields.char('Description', size=256),
860         'account_id':fields.many2one('account.account','Account', required=True),
861         'partner_id':fields.related('voucher_id', 'partner_id', type='many2one', relation='res.partner', string='Partner'),
862         'untax_amount':fields.float('Untax Amount'),
863         'amount':fields.float('Amount', digits_compute=dp.get_precision('Account')),
864         'type':fields.selection([('dr','Debit'),('cr','Credit')], 'Cr/Dr'),
865         'account_analytic_id':  fields.many2one('account.analytic.account', 'Analytic Account'),
866         'move_line_id': fields.many2one('account.move.line', 'Journal Item'),
867         'date_original': fields.related('move_line_id','date', type='date', relation='account.move.line', string='Date', readonly=1),
868         'date_due': fields.related('move_line_id','date_maturity', type='date', relation='account.move.line', string='Due Date', readonly=1),
869         'amount_original': fields.function(_compute_balance, method=True, multi='dc', type='float', string='Original Amount', store=True),
870         'amount_unreconciled': fields.function(_compute_balance, method=True, multi='dc', type='float', string='Open Balance', store=True),
871         'company_id': fields.related('voucher_id','company_id', relation='res.company', type='many2one', string='Company', store=True, readonly=True),
872     }
873     _defaults = {
874         'name': ''
875     }
876
877     def onchange_move_line_id(self, cr, user, ids, move_line_id, context=None):
878         """
879         Returns a dict that contains new values and context
880
881         @param move_line_id: latest value from user input for field move_line_id
882         @param args: other arguments
883         @param context: context arguments, like lang, time zone
884
885         @return: Returns a dict which contains new values, and context
886         """
887         res = {}
888         move_line_pool = self.pool.get('account.move.line')
889         if move_line_id:
890             move_line = move_line_pool.browse(cr, user, move_line_id, context=context)
891             if move_line.credit:
892                 ttype = 'dr'
893             else:
894                 ttype = 'cr'
895             account_id = move_line.account_id.id
896             res.update({
897                 'account_id':account_id,
898                 'type': ttype
899             })
900         return {
901             'value':res,
902         }
903
904     def default_get(self, cr, user, fields_list, context=None):
905         """
906         Returns default values for fields
907         @param fields_list: list of fields, for which default values are required to be read
908         @param context: context arguments, like lang, time zone
909
910         @return: Returns a dict that contains default values for fields
911         """
912         if context is None:
913             context = {}
914         journal_id = context.get('journal_id', False)
915         partner_id = context.get('partner_id', False)
916         journal_pool = self.pool.get('account.journal')
917         partner_pool = self.pool.get('res.partner')
918         values = super(account_voucher_line, self).default_get(cr, user, fields_list, context=context)
919         if (not journal_id) or ('account_id' not in fields_list):
920             return values
921         journal = journal_pool.browse(cr, user, journal_id, context=context)
922         account_id = False
923         ttype = 'cr'
924         if journal.type in ('sale', 'sale_refund'):
925             account_id = journal.default_credit_account_id and journal.default_credit_account_id.id or False
926             ttype = 'cr'
927         elif journal.type in ('purchase', 'expense', 'purchase_refund'):
928             account_id = journal.default_debit_account_id and journal.default_debit_account_id.id or False
929             ttype = 'dr'
930         elif partner_id:
931             partner = partner_pool.browse(cr, user, partner_id, context=context)
932             if context.get('type') == 'payment':
933                 ttype = 'dr'
934                 account_id = partner.property_account_payable.id
935             elif context.get('type') == 'receipt':
936                 account_id = partner.property_account_receivable.id
937
938         values.update({
939             'account_id':account_id,
940             'type':ttype
941         })
942         return values
943 account_voucher_line()
944
945 class account_bank_statement(osv.osv):
946     _inherit = 'account.bank.statement'
947
948     def button_cancel(self, cr, uid, ids, context=None):
949         voucher_obj = self.pool.get('account.voucher')
950         for st in self.browse(cr, uid, ids, context=context):
951             voucher_ids = []
952             for line in st.line_ids:
953                 if line.voucher_id:
954                     voucher_ids.append(line.voucher_id.id)
955             voucher_obj.cancel_voucher(cr, uid, voucher_ids, context)
956         return super(account_bank_statement, self).button_cancel(cr, uid, ids, context=context)
957
958     def create_move_from_st_line(self, cr, uid, st_line_id, company_currency_id, next_number, context=None):
959         voucher_obj = self.pool.get('account.voucher')
960         wf_service = netsvc.LocalService("workflow")
961         move_line_obj = self.pool.get('account.move.line')
962         bank_st_line_obj = self.pool.get('account.bank.statement.line')
963         st_line = bank_st_line_obj.browse(cr, uid, st_line_id, context=context)
964         if st_line.voucher_id:
965             voucher_obj.write(cr, uid, [st_line.voucher_id.id], {'number': next_number}, context=context)
966             if st_line.voucher_id.state == 'cancel':
967                 voucher_obj.action_cancel_draft(cr, uid, [st_line.voucher_id.id], context=context)
968             wf_service.trg_validate(uid, 'account.voucher', st_line.voucher_id.id, 'proforma_voucher', cr)
969
970             v = voucher_obj.browse(cr, uid, st_line.voucher_id.id, context=context)
971             bank_st_line_obj.write(cr, uid, [st_line_id], {
972                 'move_ids': [(4, v.move_id.id, False)]
973             })
974
975             return move_line_obj.write(cr, uid, [x.id for x in v.move_ids], {'statement_id': st_line.statement_id.id}, context=context)
976         return super(account_bank_statement, self).create_move_from_st_line(cr, uid, st_line.id, company_currency_id, next_number, context=context)
977
978 account_bank_statement()
979
980 class account_bank_statement_line(osv.osv):
981     _inherit = 'account.bank.statement.line'
982
983     def _amount_reconciled(self, cursor, user, ids, name, args, context=None):
984         if not ids:
985             return {}
986
987         res = {}
988 #        company_currency_id = False
989         for line in self.browse(cursor, user, ids, context=context):
990 #            if not company_currency_id:
991 #                company_currency_id = line.company_id.id
992             if line.voucher_id:
993                 res[line.id] = line.voucher_id.amount#
994 #                        res_currency_obj.compute(cursor, user,
995 #                        company_currency_id, line.statement_id.currency.id,
996 #                        line.voucher_id.amount, context=context)
997             else:
998                 res[line.id] = 0.0
999         return res
1000
1001     def _check_amount(self, cr, uid, ids, context=None):
1002         for obj in self.browse(cr, uid, ids, context=context):
1003             if obj.voucher_id:
1004                 if not (abs(obj.amount) == obj.voucher_id.amount):
1005                     return False
1006         return True
1007
1008     _constraints = [
1009         (_check_amount, 'The amount of the voucher must be the same amount as the one on the statement line', ['amount']),
1010     ]
1011
1012     _columns = {
1013         'amount_reconciled': fields.function(_amount_reconciled,
1014             string='Amount reconciled', method=True, type='float'),
1015         'voucher_id': fields.many2one('account.voucher', 'Payment'),
1016
1017     }
1018
1019     def unlink(self, cr, uid, ids, context=None):
1020         voucher_obj = self.pool.get('account.voucher')
1021         statement_line = self.browse(cr, uid, ids, context=context)
1022         unlink_ids = []
1023         for st_line in statement_line:
1024             if st_line.voucher_id:
1025                 unlink_ids.append(st_line.voucher_id.id)
1026         voucher_obj.unlink(cr, uid, unlink_ids, context=context)
1027         return super(account_bank_statement_line, self).unlink(cr, uid, ids, context=context)
1028
1029 account_bank_statement_line()
1030
1031 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: