[merge]
[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         if not view_id and context.get('invoice_type', False):
125             if context.get('invoice_type', False) in ('out_invoice', 'out_refund'):
126                 result = mod_obj.get_object_reference(cr, uid, 'account_voucher', 'view_vendor_receipt_form')
127             else:
128                 result = mod_obj.get_object_reference(cr, uid, 'account_voucher', 'view_vendor_payment_form')
129             result = result and result[1] or False
130             view_id = result
131         if not view_id and view_type == 'form' and context.get('line_type', False):
132             if context.get('line_type', False) == 'customer':
133                 result = mod_obj.get_object_reference(cr, uid, 'account_voucher', 'view_vendor_receipt_form')
134             else:
135                 result = mod_obj.get_object_reference(cr, uid, 'account_voucher', 'view_vendor_payment_form')
136             result = result and result[1] or False
137             view_id = result
138
139         res = super(account_voucher, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu)
140         doc = etree.XML(res['arch'])
141         nodes = doc.xpath("//field[@name='partner_id']")
142         if context.get('type', 'sale') in ('purchase', 'payment'):
143             for node in nodes:
144                 node.set('domain', "[('supplier', '=', True)]")
145             res['arch'] = etree.tostring(doc)
146         return res
147
148     def _compute_writeoff_amount(self, cr, uid, line_dr_ids, line_cr_ids, amount, voucher_date, context=None):
149         if context is None:
150             context = {}
151         currency_pool = self.pool.get('res.currency')
152         ctx = context.copy()
153         voucher_type = context.get('type', False)
154         counter_for_writeoff = counter_for_currency_diff = real_amount = 0.0
155         ctx.update({'date': voucher_date})
156         for l in line_dr_ids:
157             #compute the amount in voucher currency and in company currency if there aren't set yet
158             if not l.get('amount_in_company_currency', False):
159                 ctx.update({'date': l['date_original']})
160                 amount_in_company_currency = currency_pool.compute(cr, uid, l['currency_id'], l['company_currency_id'], l['amount'], context=ctx)
161                 ctx.update({'date': voucher_date})
162             else:
163                 amount_in_company_currency = l.get('amount_in_company_currency', 0.0)
164             if not l.get('amount_in_voucher_currency'):
165                 amount_in_voucher_currency = currency_pool.compute(cr, uid, l['currency_id'], l['voucher_currency_id'], l['amount'], context=ctx)
166             else:
167                 amount_in_voucher_currency = l.get('amount_in_voucher_currency', 0.0)
168             real_amount -= amount_in_company_currency
169             counter_for_writeoff -= l.get('voucher_currency_id') == l.get('currency_id') and l['amount'] or  amount_in_voucher_currency
170             counter_for_currency_diff -= currency_pool.compute(cr, uid, l['currency_id'], l['company_currency_id'], l['amount'], context=ctx)
171         for l in line_cr_ids:
172             #compute the amount in voucher currency and in company currency if there aren't set yet
173             if not l.get('amount_in_company_currency', False):
174                 ctx.update({'date': l['date_original']})
175                 amount_in_company_currency = currency_pool.compute(cr, uid, l['currency_id'], l['company_currency_id'], l['amount'], context=ctx)
176                 ctx.update({'date': voucher_date})
177             else:
178                 amount_in_company_currency = l.get('amount_in_company_currency', 0.0)
179             if not l.get('amount_in_voucher_currency'):
180                 amount_in_voucher_currency = currency_pool.compute(cr, uid, l['currency_id'], l['voucher_currency_id'], l['amount'], context=ctx)
181             else:
182                 amount_in_voucher_currency = l.get('amount_in_voucher_currency', 0.0)
183             real_amount += amount_in_company_currency
184             counter_for_writeoff += l.get('voucher_currency_id') == l.get('currency_id') and l['amount'] or  amount_in_voucher_currency
185             counter_for_currency_diff += currency_pool.compute(cr, uid, l['currency_id'], l['company_currency_id'], l['amount'], context=ctx)
186         sign = voucher_type in ['sale','receipt'] and 1 or -1
187         writeoff_amount = (sign * amount) - counter_for_writeoff
188         currency_rate_difference = real_amount - counter_for_currency_diff
189         return writeoff_amount, currency_rate_difference
190
191     def onchange_line_ids(self, cr, uid, ids, line_dr_ids, line_cr_ids, amount, voucher_date, context=None):
192         if not line_dr_ids and not line_cr_ids:
193             return {'value':{}}
194         line_osv = self.pool.get("account.voucher.line")
195         line_dr_ids = resolve_o2m_operations(cr, uid, line_osv, line_dr_ids, ['amount'], context)
196         line_cr_ids = resolve_o2m_operations(cr, uid, line_osv, line_cr_ids, ['amount'], context)
197         writeoff_amount, currency_rate_diff = self._compute_writeoff_amount(cr, uid, line_dr_ids, line_cr_ids, amount, voucher_date, context=context)
198         return {'value': {'writeoff_amount': writeoff_amount, 'currency_rate_difference': currency_rate_diff}}
199
200     def _get_writeoff_amount(self, cr, uid, ids, name, args, context=None):
201         if not ids: return {}
202         if context is None:
203             context = {}
204         res = {}.fromkeys(ids,{})
205         counter_for_writeoff = counter_for_currency_diff = real_amount = 0.0
206         currency_pool = self.pool.get('res.currency')
207         for voucher in self.browse(cr, uid, ids, context=context):
208             ctx = context.copy()
209             ctx.update({'date': voucher.date})
210             for l in voucher.line_dr_ids:
211                 real_amount -= l.amount_in_company_currency
212                 counter_for_writeoff -= (l.voucher_currency_id.id == l.currency_id.id) and l.amount or l.amount_in_voucher_currency
213                 counter_for_currency_diff -= currency_pool.compute(cr, uid, l.currency_id.id, voucher.company_id.currency_id.id, l.amount, context=ctx)
214             for l in voucher.line_cr_ids:
215                 real_amount += l.amount_in_company_currency
216                 counter_for_writeoff += (l.voucher_currency_id.id == l.currency_id.id) and l.amount or l.amount_in_voucher_currency
217                 counter_for_currency_diff += currency_pool.compute(cr, uid, l.currency_id.id, voucher.company_id.currency_id.id, l.amount, context=ctx)
218             sign = voucher.type in ['sale','receipt'] and 1 or -1
219             writeoff_amount = (sign * voucher.amount) - counter_for_writeoff
220             res[voucher.id]['writeoff_amount'] = writeoff_amount
221             res[voucher.id]['currency_rate_difference'] = real_amount - counter_for_currency_diff
222         return res
223
224     def _currency_id(self, cr, uid, ids, name, args, context=None):
225         res = {}
226         for voucher in self.browse(cr, uid, ids, context=context):
227             currency = voucher.journal_id.currency and voucher.journal_id.currency.id or voucher.company_id.currency_id.id
228             res[voucher.id] = {'currency_id': currency, 'currency_id2': currency}
229         return res
230
231     _name = 'account.voucher'
232     _description = 'Accounting Voucher'
233     _order = "date desc, id desc"
234     _columns = {
235         'type':fields.selection([
236             ('sale','Sale'),
237             ('purchase','Purchase'),
238             ('payment','Payment'),
239             ('receipt','Receipt'),
240         ],'Default Type', readonly=True, states={'draft':[('readonly',False)]}),
241         'name':fields.char('Memo', size=256, readonly=True, states={'draft':[('readonly',False)]}),
242         'date':fields.date('Date', readonly=True, select=True, states={'draft':[('readonly',False)]}, help="Effective date for accounting entries"),
243         'journal_id':fields.many2one('account.journal', 'Journal', required=True, readonly=True, states={'draft':[('readonly',False)]}, change_default=1),
244         'account_id':fields.many2one('account.account', 'Account', required=True, readonly=True, states={'draft':[('readonly',False)]}),
245         'line_ids':fields.one2many('account.voucher.line','voucher_id','Voucher Lines', readonly=True, states={'draft':[('readonly',False)]}),
246         'line_cr_ids':fields.one2many('account.voucher.line','voucher_id','Credits',
247             domain=[('type','=','cr')], context={'default_type':'cr'}, readonly=True, states={'draft':[('readonly',False)]}),
248         'line_dr_ids':fields.one2many('account.voucher.line','voucher_id','Debits',
249             domain=[('type','=','dr')], context={'default_type':'dr'}, readonly=True, states={'draft':[('readonly',False)]}),
250         'period_id': fields.many2one('account.period', 'Period', required=True, readonly=True, states={'draft':[('readonly',False)]}),
251         'narration':fields.text('Notes', readonly=True, states={'draft':[('readonly',False)]}),
252         'currency_id': fields.function(_currency_id, type='many2one', relation='res.currency', string='Currency', store=True, readonly=True, multi="currency"),
253          #duplicated field for display purposes
254         'currency_id2': fields.function(_currency_id, type='many2one', relation='res.currency', string='Currency', store=True, readonly=True, multi="currency"),
255         'company_id': fields.related('journal_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True),
256         'company_currency': fields.related('company_id','currency_id', type='many2one', relation='res.currency', string='Currency', readonly=True),
257         'state':fields.selection(
258             [('draft','Draft'),
259              ('proforma','Pro-forma'),
260              ('posted','Posted'),
261              ('cancel','Cancelled')
262             ], 'State', readonly=True, size=32,
263             help=' * The \'Draft\' state is used when a user is encoding a new and unconfirmed Voucher. \
264                         \n* The \'Pro-forma\' when voucher is in Pro-forma state,voucher does not have an voucher number. \
265                         \n* The \'Posted\' state is used when user create voucher,a voucher number is generated and voucher entries are created in account \
266                         \n* The \'Cancelled\' state is used when user cancel voucher.'),
267         'amount': fields.float('Total', digits_compute=dp.get_precision('Account'), required=True, readonly=True, states={'draft':[('readonly',False)]}),
268         'tax_amount':fields.float('Tax Amount', digits_compute=dp.get_precision('Account'), readonly=True, states={'draft':[('readonly',False)]}),
269         'reference': fields.char('Ref #', size=64, readonly=True, states={'draft':[('readonly',False)]}, help="Transaction reference number."),
270         'number': fields.char('Number', size=32, readonly=True,),
271         'move_id':fields.many2one('account.move', 'Account Entry'),
272         'move_ids': fields.related('move_id','line_id', type='one2many', relation='account.move.line', string='Journal Items', readonly=True),
273         'partner_id':fields.many2one('res.partner', 'Partner', change_default=1, readonly=True, states={'draft':[('readonly',False)]}),
274         'audit': fields.related('move_id','to_check', type='boolean', help='Check this box if you are unsure of that journal entry and if you want to note it as \'to be reviewed\' by an accounting expert.', relation='account.move', string='To Review'),
275         'pay_now':fields.selection([
276             ('pay_now','Pay Directly'),
277             ('pay_later','Pay Later or Group Funds'),
278         ],'Payment', select=True, readonly=True, states={'draft':[('readonly',False)]}),
279         'tax_id':fields.many2one('account.tax', 'Tax', readonly=True, states={'draft':[('readonly',False)]}),
280         'pre_line':fields.boolean('Previous Payments ?', required=False),
281         'date_due': fields.date('Due Date', readonly=True, select=True, states={'draft':[('readonly',False)]}),
282         'payment_option':fields.selection([
283                                            ('without_writeoff', 'Keep Open'),
284                                            ('with_writeoff', 'Reconcile'),
285                                            ], 'Payment Difference', required=True, readonly=True, states={'draft': [('readonly', False)]}),
286         'writeoff_acc_id': fields.many2one('account.account', 'Write-Off account', readonly=True, states={'draft': [('readonly', False)]}),
287         'comment': fields.char('Write-Off Comment', size=64, required=True, readonly=True, states={'draft': [('readonly', False)]}),
288         'analytic_id': fields.many2one('account.analytic.account','Write-Off Analytic Account', readonly=True, states={'draft': [('readonly', False)]}),
289         'writeoff_amount': fields.function(_get_writeoff_amount, string='Write-Off Amount', type='float', readonly=True, multi="writeoff"),
290         'currency_rate_difference': fields.function(_get_writeoff_amount, string="Currency Rate Difference", type='float', multi="writeoff"),
291     }
292     _defaults = {
293         'period_id': _get_period,
294         'partner_id': _get_partner,
295         'journal_id':_get_journal,
296         'currency_id': _get_currency,
297         'reference': _get_reference,
298         'narration':_get_narration,
299         'amount': _get_amount,
300         'type':_get_type,
301         'state': 'draft',
302         'pay_now': 'pay_later',
303         'name': '',
304         'date': lambda *a: time.strftime('%Y-%m-%d'),
305         'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.voucher',context=c),
306         'tax_id': _get_tax,
307         'payment_option': 'without_writeoff',
308         'comment': _('Write-Off'),
309     }
310
311     def compute_tax(self, cr, uid, ids, context=None):
312         tax_pool = self.pool.get('account.tax')
313         partner_pool = self.pool.get('res.partner')
314         position_pool = self.pool.get('account.fiscal.position')
315         voucher_voucher_line_obj = self.pool.get('account.voucher.line')
316         voucher_pool = self.pool.get('account.voucher')
317         if context is None: context = {}
318
319         for voucher in voucher_pool.browse(cr, uid, ids, context=context):
320             voucher_amount = 0.0
321             for line in voucher.line_ids:
322                 voucher_amount += line.untax_amount or line.amount
323                 line.amount = line.untax_amount or line.amount
324                 voucher_voucher_line_obj.write(cr, uid, [line.id], {'amount':line.amount, 'untax_amount':line.untax_amount})
325
326             if not voucher.tax_id:
327                 self.write(cr, uid, [voucher.id], {'amount':voucher_amount, 'tax_amount':0.0})
328                 continue
329
330             tax = [tax_pool.browse(cr, uid, voucher.tax_id.id, context=context)]
331             partner = partner_pool.browse(cr, uid, voucher.partner_id.id, context=context) or False
332             taxes = position_pool.map_tax(cr, uid, partner and partner.property_account_position or False, tax)
333             tax = tax_pool.browse(cr, uid, taxes, context=context)
334
335             total = voucher_amount
336             total_tax = 0.0
337
338             if not tax[0].price_include:
339                 for tax_line in tax_pool.compute_all(cr, uid, tax, voucher_amount, 1).get('taxes', []):
340                     total_tax += tax_line.get('amount', 0.0)
341                 total += total_tax
342             else:
343                 for line in voucher.line_ids:
344                     line_total = 0.0
345                     line_tax = 0.0
346
347                     for tax_line in tax_pool.compute_all(cr, uid, tax, line.untax_amount or line.amount, 1).get('taxes', []):
348                         line_tax += tax_line.get('amount', 0.0)
349                         line_total += tax_line.get('price_unit')
350                     total_tax += line_tax
351                     untax_amount = line.untax_amount or line.amount
352                     voucher_voucher_line_obj.write(cr, uid, [line.id], {'amount':line_total, 'untax_amount':untax_amount})
353
354             self.write(cr, uid, [voucher.id], {'amount':total, 'tax_amount':total_tax})
355         return True
356
357     def onchange_price(self, cr, uid, ids, line_ids, tax_id, partner_id=False, context=None):
358         context = context or {}
359         tax_pool = self.pool.get('account.tax')
360         partner_pool = self.pool.get('res.partner')
361         position_pool = self.pool.get('account.fiscal.position')
362         voucher_line_obj = self.pool.get('account.voucher.line')
363         res = {
364             'tax_amount': False,
365             'amount': False,
366         }
367         voucher_total = 0.0
368
369         line_ids = resolve_o2m_operations(cr, uid, voucher_line_obj, line_ids, ["amount"], context)
370
371         total = 0.0
372         total_tax = 0.0
373         for line in line_ids:
374             line_amount = 0.0
375             line_amount = line.get('amount',0.0)
376             voucher_total += line_amount
377
378         total = voucher_total
379         total_tax = 0.0
380         if tax_id:
381             tax = [tax_pool.browse(cr, uid, tax_id, context=context)]
382             if partner_id:
383                 partner = partner_pool.browse(cr, uid, partner_id, context=context) or False
384                 taxes = position_pool.map_tax(cr, uid, partner and partner.property_account_position or False, tax)
385                 tax = tax_pool.browse(cr, uid, taxes, context=context)
386
387             if not tax[0].price_include:
388                 for tax_line in tax_pool.compute_all(cr, uid, tax, voucher_total, 1).get('taxes', []):
389                     total_tax += tax_line.get('amount')
390                 total += total_tax
391
392         res.update({
393             'amount':total or voucher_total,
394             'tax_amount':total_tax
395         })
396         return {
397             'value':res
398         }
399
400     def onchange_term_id(self, cr, uid, ids, term_id, amount):
401         term_pool = self.pool.get('account.payment.term')
402         terms = False
403         due_date = False
404         default = {'date_due':False}
405         if term_id and amount:
406             terms = term_pool.compute(cr, uid, term_id, amount)
407         if terms:
408             due_date = terms[-1][0]
409             default.update({
410                 'date_due':due_date
411             })
412         return {'value':default}
413
414     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):
415         """price
416         Returns a dict that contains new values and context
417
418         @param partner_id: latest value from user input for field partner_id
419         @param args: other arguments
420         @param context: context arguments, like lang, time zone
421
422         @return: Returns a dict which contains new values, and context
423         """
424         default = {
425             'value':{},
426         }
427
428         if not partner_id or not journal_id:
429             return default
430
431         partner_pool = self.pool.get('res.partner')
432         journal_pool = self.pool.get('account.journal')
433
434         journal = journal_pool.browse(cr, uid, journal_id, context=context)
435         partner = partner_pool.browse(cr, uid, partner_id, context=context)
436         account_id = False
437         tr_type = False
438         if journal.type in ('sale','sale_refund'):
439             account_id = partner.property_account_receivable.id
440             tr_type = 'sale'
441         elif journal.type in ('purchase', 'purchase_refund','expense'):
442             account_id = partner.property_account_payable.id
443             tr_type = 'purchase'
444         else:
445             if not journal.default_credit_account_id or not journal.default_debit_account_id:
446                 raise osv.except_osv(_('Error !'), _('Please define default credit/debit account on the %s !') % (journal.name))
447             account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
448             tr_type = 'receipt'
449
450         default['value']['account_id'] = account_id
451         default['value']['type'] = ttype or tr_type
452
453         vals = self.onchange_journal(cr, uid, ids, journal_id, line_ids, tax_id, partner_id, context)
454         default['value'].update(vals.get('value'))
455
456         return default
457
458     def onchange_partner_id(self, cr, uid, ids, partner_id, journal_id, price, voucher_currency_id, ttype, date, context=None):
459         """price
460         Returns a dict that contains new values and context
461
462         @param partner_id: latest value from user input for field partner_id
463         @param args: other arguments
464         @param context: context arguments, like lang, time zone
465
466         @return: Returns a dict which contains new values, and context
467         """
468         if not journal_id:
469             return {}
470         if context is None:
471             context = {}
472         context_multi_currency = context.copy()
473         if date:
474             context_multi_currency.update({'date': date})
475
476         currency_pool = self.pool.get('res.currency')
477         move_line_obj = self.pool.get('account.move.line')
478         partner_pool = self.pool.get('res.partner')
479         journal_pool = self.pool.get('account.journal')
480         voucher_line_obj = self.pool.get('account.voucher.line')
481         #get default values
482         vals = self.onchange_journal(cr, uid, ids, journal_id, [], False, partner_id, context=context)
483         vals = vals.get('value',{})
484         voucher_currency_id = vals.get('currency_id', voucher_currency_id)
485         default = {
486             'value':{'line_ids':[], 'line_dr_ids':[], 'line_cr_ids':[], 'pre_line': False, 'currency_id': voucher_currency_id},
487         }
488
489         #drop existing lines
490         line_ids = ids and voucher_line_obj.search(cr, uid, [('voucher_id', 'in', ids)]) or []
491         if line_ids:
492             voucher_line_obj.unlink(cr, uid, line_ids, context=context)
493
494         if not partner_id:
495             return default
496
497         journal = journal_pool.browse(cr, uid, journal_id, context=context)
498         partner = partner_pool.browse(cr, uid, partner_id, context=context)
499         account_id = False
500         if journal.type in ('sale','sale_refund'):
501             account_id = partner.property_account_receivable.id
502         elif journal.type in ('purchase', 'purchase_refund','expense'):
503             account_id = partner.property_account_payable.id
504         else:
505             account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
506
507         default['value']['account_id'] = account_id
508
509         if journal.type not in ('cash', 'bank'):
510             return default
511
512         account_type = 'receivable'
513         if ttype == 'payment':
514             account_type = 'payable'
515         else:
516             account_type = 'receivable'
517
518         if not context.get('move_line_ids', False):
519             ids = move_line_obj.search(cr, uid, [('state','=','valid'), ('account_id.type', '=', account_type), ('reconcile_id', '=', False), ('partner_id', '=', partner_id)], context=context)
520         else:
521             ids = context['move_line_ids']
522
523         #computation of the assignation of voucher amount on voucher lines
524         total_credit =  account_type == 'receivable' and price or 0.0
525         total_debit = account_type == 'payable' and price or 0.0
526         moves = move_line_obj.browse(cr, uid, ids, context=context)
527         company_currency = journal.company_id.currency_id.id
528         invoice_id = context.get('invoice_id', False)
529         move_line_found = False
530         #order the lines by most old first
531         ids.reverse()
532
533         for line in moves:
534             if line.credit and line.reconcile_partial_id and ttype == 'receipt':
535                 continue
536             if line.debit and line.reconcile_partial_id and ttype == 'payment':
537                 continue
538             if invoice_id:
539                 if line.invoice.id == invoice_id:
540                     #if the invoice linked to the voucher line is equal to the invoice_id in context
541                     #then we assign the amount on that line, whatever the other voucher lines
542                     move_line_found = line.id
543                     break
544             elif voucher_currency_id == company_currency:
545                 #otherwise treatments is the same but with other field names
546                 if line.amount_residual == price:
547                     #if the amount residual is equal the amount voucher, we assign it to that voucher 
548                     #line, whatever the other voucher lines
549                     move_line_found = line.id
550                     break
551                 #otherwise we will split the voucher amount on each line (by most old first)
552                 total_credit += line.credit or 0.0
553                 total_debit += line.debit or 0.0
554             elif voucher_currency_id == line.currency_id.id:
555                 if line.amount_residual_currency == price:
556                     move_line_found = line.id
557                     break
558                 total_credit += line.credit and line.amount_currency or 0.0
559                 total_debit += line.debit and line.amount_currency or 0.0
560
561         #voucher line creation
562         for line in moves:
563             if line.credit and line.reconcile_partial_id and ttype == 'receipt':
564                 continue
565             if line.debit and line.reconcile_partial_id and ttype == 'payment':
566                 continue
567             original_amount = line.credit or line.debit or 0.0
568             amount_original, amount_unreconciled = voucher_line_obj._get_amounts(cr, uid, line, context=context)
569             currency_id = line.currency_id and line.currency_id.id or line.company_id.currency_id.id
570             rs = {
571                 'name':line.move_id.name,
572                 'type': line.credit and 'dr' or 'cr',
573                 'move_line_id':line.id,
574                 'account_id':line.account_id.id,
575                 'amount_original': amount_original,
576                 'amount': (move_line_found == line.id) and min(price, amount_unreconciled) or 0.0,
577                 'currency_id': currency_id,
578                 'voucher_currency_id': voucher_currency_id,
579                 'date_original':line.date,
580                 'company_currency_id': line.company_id.currency_id.id,
581                 'date_due':line.date_maturity,
582                 'amount_unreconciled': amount_unreconciled,
583             }
584             #split voucher amount by most old first
585             if not move_line_found:
586                 if company_currency == voucher_currency_id:
587                     if line.credit:
588                         amount = min(amount_unreconciled, abs(total_debit))
589                         rs['amount'] = amount
590                         total_debit -= amount
591                     else:
592                         amount = min(amount_unreconciled, abs(total_credit))
593                         rs['amount'] = amount
594                         total_credit -= amount
595                 elif voucher_currency_id == line.currency_id.id:
596                     if line.credit:
597                         amount = min(amount_unreconciled, abs(total_debit))
598                         rs['amount'] = amount
599                         total_debit -= amount
600                     else:
601                         amount = min(amount_unreconciled, abs(total_credit))
602                         rs['amount'] = amount
603                         total_credit -= amount
604
605             default['value']['line_ids'].append(rs)
606             if rs['type'] == 'cr':
607                 default['value']['line_cr_ids'].append(rs)
608             else:
609                 default['value']['line_dr_ids'].append(rs)
610
611             if ttype == 'payment' and len(default['value']['line_cr_ids']) > 0:
612                 default['value']['pre_line'] = 1
613             elif ttype == 'receipt' and len(default['value']['line_dr_ids']) > 0:
614                 default['value']['pre_line'] = 1
615         default['value']['writeoff_amount'], default['value']['currency_rate_difference'] = self._compute_writeoff_amount(cr, uid, default['value']['line_dr_ids'], default['value']['line_cr_ids'], price, date, context=context)
616         return default
617
618     def onchange_date(self, cr, uid, ids, partner_id, journal_id, price, currency_id, ttype, date, context=None):
619         """
620         @param date: latest value from user input for field date
621         @param args: other arguments
622         @param context: context arguments, like lang, time zone
623         @return: Returns a dict which contains new values, and context
624         """
625         if context is None: context = {}
626         period_pool = self.pool.get('account.period')
627         res = self.onchange_partner_id(cr, uid, ids, partner_id, journal_id, price, currency_id, ttype, date, context=context)
628         if context.get('invoice_id', False):
629             company_id = self.pool.get('account.invoice').browse(cr, uid, context['invoice_id'], context=context).company_id.id
630             context.update({'company_id': company_id})
631         pids = period_pool.find(cr, uid, date, context=context)
632         if pids:
633             if not 'value' in res:
634                 res['value'] = {}
635             res['value'].update({'period_id':pids[0]})
636         return res
637
638     def onchange_journal(self, cr, uid, ids, journal_id, line_ids, tax_id, partner_id, context=None):
639         if context is None: context = {}
640         if not journal_id:
641             return {}
642         journal_pool = self.pool.get('account.journal')
643         journal = journal_pool.browse(cr, uid, journal_id, context=context)
644         account_id = journal.default_credit_account_id or journal.default_debit_account_id
645         tax_id = False
646         if account_id and account_id.tax_ids:
647             tax_id = account_id.tax_ids[0].id
648
649         vals = self.onchange_price(cr, uid, ids, line_ids, tax_id, partner_id, context)
650         vals['value'].update({'tax_id':tax_id})
651         currency_id = journal.company_id.currency_id.id
652         if journal.currency:
653             currency_id = journal.currency.id
654         vals['value'].update({'currency_id':currency_id})
655         context.update({'company_id': journal.company_id.id})
656         periods = self.pool.get('account.period').find(cr, uid, context=context)
657         if periods:
658             vals['value'].update({'period_id':periods[0]})
659         return vals
660
661     def proforma_voucher(self, cr, uid, ids, context=None):
662         self.action_move_line_create(cr, uid, ids, context=context)
663         return True
664
665     def action_cancel_draft(self, cr, uid, ids, context=None):
666         wf_service = netsvc.LocalService("workflow")
667         for voucher_id in ids:
668             wf_service.trg_create(uid, 'account.voucher', voucher_id, cr)
669         self.write(cr, uid, ids, {'state':'draft'})
670         return True
671
672     def cancel_voucher(self, cr, uid, ids, context=None):
673         reconcile_pool = self.pool.get('account.move.reconcile')
674         move_pool = self.pool.get('account.move')
675
676         for voucher in self.browse(cr, uid, ids, context=context):
677             recs = []
678             for line in voucher.move_ids:
679                 if line.reconcile_id:
680                     recs += [line.reconcile_id.id]
681                 if line.reconcile_partial_id:
682                     recs += [line.reconcile_partial_id.id]
683
684             reconcile_pool.unlink(cr, uid, recs)
685
686             if voucher.move_id:
687                 move_pool.button_cancel(cr, uid, [voucher.move_id.id])
688                 move_pool.unlink(cr, uid, [voucher.move_id.id])
689         res = {
690             'state':'cancel',
691             'move_id':False,
692         }
693         self.write(cr, uid, ids, res)
694         return True
695
696     def unlink(self, cr, uid, ids, context=None):
697         for t in self.read(cr, uid, ids, ['state'], context=context):
698             if t['state'] not in ('draft', 'cancel'):
699                 raise osv.except_osv(_('Invalid action !'), _('Cannot delete Voucher(s) which are already opened or paid !'))
700         return super(account_voucher, self).unlink(cr, uid, ids, context=context)
701
702     def onchange_payment(self, cr, uid, ids, pay_now, journal_id, partner_id, ttype='sale'):
703         res = {}
704         if not partner_id:
705             return res
706         res = {'account_id':False}
707         partner_pool = self.pool.get('res.partner')
708         journal_pool = self.pool.get('account.journal')
709         if pay_now == 'pay_later':
710             partner = partner_pool.browse(cr, uid, partner_id)
711             journal = journal_pool.browse(cr, uid, journal_id)
712             if journal.type in ('sale','sale_refund'):
713                 account_id = partner.property_account_receivable.id
714             elif journal.type in ('purchase', 'purchase_refund','expense'):
715                 account_id = partner.property_account_payable.id
716             else:
717                 account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
718             res['account_id'] = account_id
719         return {'value':res}
720
721     def action_move_line_create(self, cr, uid, ids, context=None):
722
723         def _get_payment_term_lines(term_id, amount):
724             term_pool = self.pool.get('account.payment.term')
725             if term_id and amount:
726                 terms = term_pool.compute(cr, uid, term_id, amount)
727                 return terms
728             return False
729         if context is None:
730             context = {}
731         move_pool = self.pool.get('account.move')
732         move_line_obj = self.pool.get('account.move.line')
733         currency_pool = self.pool.get('res.currency')
734         tax_obj = self.pool.get('account.tax')
735         seq_obj = self.pool.get('ir.sequence')
736         for voucher in self.browse(cr, uid, ids, context=context):
737             if voucher.move_id:
738                 continue
739             context_multi_currency = context.copy()
740             context_multi_currency.update({'date': voucher.date})
741
742             if voucher.number:
743                 name = voucher.number
744             else:
745                 name = seq_obj.get_id(cr, uid, voucher.journal_id.sequence_id.id)
746             if not voucher.reference:
747                 ref = name.replace('/','')
748             else:
749                 ref = voucher.reference
750
751             move = {
752                 'name': name,
753                 'journal_id': voucher.journal_id.id,
754                 'narration': voucher.narration,
755                 'date': voucher.date,
756                 'ref': ref,
757                 'period_id': voucher.period_id and voucher.period_id.id or False
758             }
759             move_id = move_pool.create(cr, uid, move)
760
761             #create the first line manually
762             company_currency = voucher.journal_id.company_id.currency_id.id
763             voucher_currency = voucher.currency_id.id
764             debit = 0.0
765             credit = 0.0
766             if voucher.type in ('purchase', 'payment'):
767                 credit = currency_pool.compute(cr, uid, voucher_currency, company_currency, voucher.amount, context=context_multi_currency)
768             elif voucher.type in ('sale', 'receipt'):
769                 debit = currency_pool.compute(cr, uid, voucher_currency, company_currency, voucher.amount, context=context_multi_currency)
770             if debit < 0:
771                 credit = -debit
772                 debit = 0.0
773             if credit < 0:
774                 debit = -credit
775                 credit = 0.0
776             sign = debit - credit < 0 and -1 or 1
777             #create the first line of the voucher
778             move_line = {
779                 'name': voucher.name or '/',
780                 'debit': debit,
781                 'credit': credit,
782                 'account_id': voucher.account_id.id,
783                 'move_id': move_id,
784                 'journal_id': voucher.journal_id.id,
785                 'period_id': voucher.period_id.id,
786                 'partner_id': voucher.partner_id.id,
787                 'currency_id': company_currency <> voucher_currency and  voucher_currency or False,
788                 'amount_currency': company_currency <> voucher_currency and sign * voucher.amount or 0.0,
789                 'date': voucher.date,
790                 'date_maturity': voucher.date_due
791             }
792             move_line_obj.create(cr, uid, move_line)
793
794             #create the move line for the currency difference
795             if voucher.currency_rate_difference:
796                 if voucher.currency_rate_difference > 0:
797                     account_id = voucher.company_id.property_expense_currency_exchange
798                     if not account_id:
799                         raise osv.except_osv(_('Warning'),_("Unable to create accounting entry for currency rate difference. You have to configure the field 'Income Currency Rate' on the company! "))
800                 else:
801                     account_id = voucher.company_id.property_income_currency_exchange
802                     if not account_id:
803                         raise osv.except_osv(_('Warning'),_("Unable to create accounting entry for currency rate difference. You have to configure the field 'Expense Currency Rate' on the company! "))
804
805                 currency_diff_line = {
806                     'name': _('Currency Difference'),
807                     'debit': voucher.currency_rate_difference > 0 and voucher.currency_rate_difference or 0.0,
808                     'credit': voucher.currency_rate_difference < 0 and -voucher.currency_rate_difference or 0.0,
809                     'account_id': account_id.id,
810                     'move_id': move_id,
811                     'journal_id': voucher.journal_id.id,
812                     'period_id': voucher.period_id.id,
813                     'partner_id': voucher.partner_id.id,
814                     'date': voucher.date,
815                     'date_maturity': voucher.date_due
816                 }
817                 move_line_obj.create(cr, uid, currency_diff_line, context=context)
818
819             rec_list_ids = []
820             for line in voucher.line_ids:
821                 #create one move line per voucher line where amount is not 0.0
822                 if not line.amount:
823                     continue
824                 #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
825                 if line.amount == line.amount_unreconciled:
826                     amount = line.move_line_id.amount_residual #residual amount in company currency
827                 else:
828                     amount = line.amount_in_company_currency
829                 move_line = {
830                     'journal_id': voucher.journal_id.id,
831                     'period_id': voucher.period_id.id,
832                     'name': line.name or '/',
833                     'account_id': line.account_id.id,
834                     'move_id': move_id,
835                     'partner_id': voucher.partner_id.id,
836                     'currency_id': company_currency <> line.currency_id.id and line.currency_id.id or False,
837                     'analytic_account_id': line.account_analytic_id and line.account_analytic_id.id or False,
838                     'quantity': 1,
839                     'credit': 0.0,
840                     'debit': 0.0,
841                     'date': voucher.date
842                 }
843                 if amount < 0:
844                     amount = -amount
845                     if line.type == 'dr':
846                         line.type = 'cr'
847                     else:
848                         line.type = 'dr'
849                 if (line.type=='dr'):
850                     move_line['debit'] = amount
851                 else:
852                     move_line['credit'] = amount
853
854                 if voucher.tax_id and voucher.type in ('sale', 'purchase'):
855                     move_line.update({
856                         'account_tax_id': voucher.tax_id.id,
857                     })
858                 if move_line.get('account_tax_id', False):
859                     tax_data = tax_obj.browse(cr, uid, [move_line['account_tax_id']], context=context)[0]
860                     if not (tax_data.base_code_id and tax_data.tax_code_id):
861                         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))
862                 sign = (move_line['debit'] - move_line['credit']) < 0 and -1 or 1
863                 move_line['amount_currency'] = company_currency <> line.currency_id.id and sign * line.amount or 0.0
864                 voucher_line = move_line_obj.create(cr, uid, move_line)
865                 if line.move_line_id.id:
866                     rec_ids = [voucher_line, line.move_line_id.id]
867                     rec_list_ids.append(rec_ids)
868
869             if not currency_pool.is_zero(cr, uid, voucher.currency_id, voucher.writeoff_amount):
870                 #create one line for the write off if needed
871                 diff = currency_pool.compute(cr, uid, voucher_currency, company_currency, voucher.writeoff_amount, context=context_multi_currency)
872                 account_id = False
873                 write_off_name = ''
874                 if voucher.payment_option == 'with_writeoff':
875                     account_id = voucher.writeoff_acc_id.id
876                     write_off_name = voucher.comment
877                 elif voucher.type in ('sale', 'receipt'):
878                     account_id = voucher.partner_id.property_account_receivable.id
879                 else:
880                     account_id = voucher.partner_id.property_account_payable.id
881                 move_line = {
882                     'name': write_off_name or name,
883                     'account_id': account_id,
884                     'move_id': move_id,
885                     'partner_id': voucher.partner_id.id,
886                     'date': voucher.date,
887                     'debit': diff < 0 and -diff or 0.0,
888                     'credit': diff > 0 and diff or 0.0,
889                     'amount_currency': company_currency <> voucher_currency and -voucher.writeoff_amount or 0.0,
890                     'currency_id': company_currency <> voucher_currency and voucher_currency or False,
891                 }
892                 move_line_obj.create(cr, uid, move_line)
893             self.write(cr, uid, [voucher.id], {
894                 'move_id': move_id,
895                 'state': 'posted',
896                 'number': name,
897             })
898             if voucher.journal_id.entry_posted:
899                 move_pool.post(cr, uid, [move_id], context={})
900             for rec_ids in rec_list_ids:
901                 if len(rec_ids) >= 2:
902                     move_line_obj.reconcile_partial(cr, uid, rec_ids)
903         return True
904
905     def copy(self, cr, uid, id, default={}, context=None):
906         default.update({
907             'state': 'draft',
908             'number': False,
909             'move_id': False,
910             'line_cr_ids': False,
911             'line_dr_ids': False,
912             'reference': False
913         })
914         if 'date' not in default:
915             default['date'] = time.strftime('%Y-%m-%d')
916         return super(account_voucher, self).copy(cr, uid, id, default, context)
917
918 account_voucher()
919
920 class account_voucher_line(osv.osv):
921     _name = 'account.voucher.line'
922     _description = 'Voucher Lines'
923     _order = "move_line_id"
924
925     def _currency_id(self, cr, uid, ids, name, args, context=None):
926         res = {}
927         for line in self.browse(cr, uid, ids, context=context):
928             move_line = line.move_line_id
929             if move_line:
930                 res[line.id] = move_line.currency_id and move_line.currency_id.id or move_line.company_id.currency_id.id
931             else:
932                 res[line.id] = line.voucher_id.currency_id.id
933         return res
934
935     def _get_amounts(self, cr, uid, line_browse_rec, context=None):
936         if line_browse_rec.currency_id:
937             amount_original = line_browse_rec.amount_currency or 0.0
938             amount_unreconciled = line_browse_rec.amount_residual_currency
939         elif line_browse_rec.credit > 0:
940             amount_original = line_browse_rec.credit or 0.0
941             amount_unreconciled = line_browse_rec.amount_residual
942         else:
943             amount_original = line_browse_rec.debit or 0.0
944             amount_unreconciled = line_browse_rec.amount_residual
945         return amount_original, amount_unreconciled
946
947     def _compute_balance(self, cr, uid, ids, name, args, context=None):
948         currency_pool = self.pool.get('res.currency')
949         res = {}
950         for line in self.browse(cr, uid, ids, context=context):
951             amount_original, amount_unreconciled = self._get_amounts(cr, uid, line.move_line_id, context)
952             res[line.id] = {
953                 'amount_original': amount_original,
954                 'amount_unreconciled': amount_unreconciled,
955             }
956
957         return res
958
959     def __company_currency_amount(self, cr, uid, line, amount, context=None):
960         if context is None:
961             context = {}
962         ctx = context.copy()
963         ctx.update({'date': line.date_original})
964         currency_pool = self.pool.get('res.currency')
965         amount_company_cur = currency_pool.compute(cr, uid, line.currency_id.id, line.company_currency_id.id, amount, context=ctx)
966         ctx.update({'date': line.voucher_id.date})
967         amount_voucher_cur = currency_pool.compute(cr, uid, line.currency_id.id, line.voucher_currency_id.id, amount, context=ctx)
968         return amount_company_cur, amount_voucher_cur
969
970     def onchange_amount(self, cr, uid, ids, amount, context=None):
971         if not amount or not ids:
972             return {'value':{'amount_in_company_currency': 0.0, 'amount_in_voucher_currency': 0.0}}
973         for line in self.browse(cr, uid, ids, context=context):
974             amount_company_cur, amount_voucher_cur  = self.__company_currency_amount(cr, uid, line, amount, context=context)
975         return {'value': {'amount_in_company_currency': amount_company_cur, 'amount_in_voucher_currency': amount_voucher_cur}}
976
977     def _get_amount_in_company_currency(self, cr, uid, ids, name, args, context=None):
978         res = {}
979         for line in self.browse(cr, uid, ids, context=context):
980             amount_in_company_currency, amount_in_voucher_currency = self.__company_currency_amount(cr, uid, line, line.amount, context=context)
981             res[line.id] = {
982                  'amount_in_company_currency': amount_in_company_currency,
983                  'amount_in_voucher_currency': amount_in_voucher_currency,
984             }
985         return res
986
987     _columns = {
988         'voucher_id':fields.many2one('account.voucher', 'Voucher', required=1, ondelete='cascade'),
989         'move_line_id': fields.many2one('account.move.line', 'Journal Item'),
990         'type':fields.selection([('dr','Debit'),('cr','Credit')], 'Dr/Cr'),
991         'name':fields.char('Description', size=256),
992         'account_id':fields.many2one('account.account','Account', required=True),
993         'account_analytic_id':  fields.many2one('account.analytic.account', 'Analytic Account'),
994         'partner_id':fields.related('voucher_id', 'partner_id', type='many2one', relation='res.partner', string='Partner'),
995         'untax_amount':fields.float('Untax Amount'),
996
997         'currency_id': fields.function(_currency_id, string='Currency', type='many2one', relation='res.currency'),
998         'company_currency_id': fields.related('move_line_id','company_id','currency_id', type='many2one', relation='res.currency', string="Company Currency"),
999         'voucher_currency_id': fields.related('voucher_id', 'currency_id', type='many2one', relation='res.currency', string="Voucher Currency"),
1000
1001         'amount':fields.float('Amount', digits_compute=dp.get_precision('Account')),
1002         'amount_in_company_currency': fields.function(_get_amount_in_company_currency, string='Amount in Company Currency', type='float', digits_compute=dp.get_precision('Account'), multi="voucher_line_amount"),
1003         'amount_in_voucher_currency': fields.function(_get_amount_in_company_currency, string='Amount in Voucher Currency', type='float', digits_compute=dp.get_precision('Account'), multi="voucher_line_amount"),
1004
1005         'date_original': fields.related('move_line_id','date', type='date', relation='account.move.line', string='Date', readonly=1),
1006         'date_due': fields.related('move_line_id','date_maturity', type='date', relation='account.move.line', string='Due Date', readonly=1),
1007         'amount_original': fields.function(_compute_balance, multi='dc', type='float', string='Original Amount', store=True),
1008         'amount_unreconciled': fields.function(_compute_balance, multi='dc', type='float', string='Open Balance', store=True),
1009         'company_id': fields.related('voucher_id','company_id', relation='res.company', type='many2one', string='Company', store=True, readonly=True),
1010     }
1011     _defaults = {
1012         'name': ''
1013     }
1014
1015     def onchange_move_line_id(self, cr, user, ids, move_line_id, context=None):
1016         """
1017         Returns a dict that contains new values and context
1018
1019         @param move_line_id: latest value from user input for field move_line_id
1020         @param args: other arguments
1021         @param context: context arguments, like lang, time zone
1022
1023         @return: Returns a dict which contains new values, and context
1024         """
1025         res = {}
1026         move_line_obj = self.pool.get('account.move.line')
1027         if move_line_id:
1028             move_line = move_line_obj.browse(cr, user, move_line_id, context=context)
1029             if move_line.credit:
1030                 ttype = 'dr'
1031             else:
1032                 ttype = 'cr'
1033             account_id = move_line.account_id.id
1034             res.update({
1035                 'account_id':account_id,
1036                 'type': ttype
1037             })
1038         return {
1039             'value':res,
1040         }
1041
1042     def default_get(self, cr, user, fields_list, context=None):
1043         """
1044         Returns default values for fields
1045         @param fields_list: list of fields, for which default values are required to be read
1046         @param context: context arguments, like lang, time zone
1047
1048         @return: Returns a dict that contains default values for fields
1049         """
1050         if context is None:
1051             context = {}
1052         journal_id = context.get('journal_id', False)
1053         partner_id = context.get('partner_id', False)
1054         journal_pool = self.pool.get('account.journal')
1055         partner_pool = self.pool.get('res.partner')
1056         values = super(account_voucher_line, self).default_get(cr, user, fields_list, context=context)
1057         if (not journal_id) or ('account_id' not in fields_list):
1058             return values
1059         journal = journal_pool.browse(cr, user, journal_id, context=context)
1060         account_id = False
1061         ttype = 'cr'
1062         if journal.type in ('sale', 'sale_refund'):
1063             account_id = journal.default_credit_account_id and journal.default_credit_account_id.id or False
1064             ttype = 'cr'
1065         elif journal.type in ('purchase', 'expense', 'purchase_refund'):
1066             account_id = journal.default_debit_account_id and journal.default_debit_account_id.id or False
1067             ttype = 'dr'
1068         elif partner_id:
1069             partner = partner_pool.browse(cr, user, partner_id, context=context)
1070             if context.get('type') == 'payment':
1071                 ttype = 'dr'
1072                 account_id = partner.property_account_payable.id
1073             elif context.get('type') == 'receipt':
1074                 account_id = partner.property_account_receivable.id
1075
1076         values.update({
1077             'account_id':account_id,
1078             'type':ttype
1079         })
1080         return values
1081 account_voucher_line()
1082
1083 class account_bank_statement(osv.osv):
1084     _inherit = 'account.bank.statement'
1085
1086     def button_cancel(self, cr, uid, ids, context=None):
1087         voucher_obj = self.pool.get('account.voucher')
1088         for st in self.browse(cr, uid, ids, context=context):
1089             voucher_ids = []
1090             for line in st.line_ids:
1091                 if line.voucher_id:
1092                     voucher_ids.append(line.voucher_id.id)
1093             voucher_obj.cancel_voucher(cr, uid, voucher_ids, context)
1094         return super(account_bank_statement, self).button_cancel(cr, uid, ids, context=context)
1095
1096     def create_move_from_st_line(self, cr, uid, st_line_id, company_currency_id, next_number, context=None):
1097         voucher_obj = self.pool.get('account.voucher')
1098         wf_service = netsvc.LocalService("workflow")
1099         move_line_obj = self.pool.get('account.move.line')
1100         bank_st_line_obj = self.pool.get('account.bank.statement.line')
1101         st_line = bank_st_line_obj.browse(cr, uid, st_line_id, context=context)
1102         if st_line.voucher_id:
1103             voucher_obj.write(cr, uid, [st_line.voucher_id.id], {'number': next_number, 'date': st_line.date}, context=context)
1104             if st_line.voucher_id.state == 'cancel':
1105                 voucher_obj.action_cancel_draft(cr, uid, [st_line.voucher_id.id], context=context)
1106             wf_service.trg_validate(uid, 'account.voucher', st_line.voucher_id.id, 'proforma_voucher', cr)
1107
1108             v = voucher_obj.browse(cr, uid, st_line.voucher_id.id, context=context)
1109             bank_st_line_obj.write(cr, uid, [st_line_id], {
1110                 'move_ids': [(4, v.move_id.id, False)]
1111             })
1112
1113             return move_line_obj.write(cr, uid, [x.id for x in v.move_ids], {'statement_id': st_line.statement_id.id, 'date': st_line.date}, update_check=False, context=context)
1114         return super(account_bank_statement, self).create_move_from_st_line(cr, uid, st_line.id, company_currency_id, next_number, context=context)
1115
1116 account_bank_statement()
1117
1118 class account_bank_statement_line(osv.osv):
1119     _inherit = 'account.bank.statement.line'
1120
1121     def _amount_reconciled(self, cursor, user, ids, name, args, context=None):
1122         if not ids:
1123             return {}
1124
1125         res = {}
1126 #        company_currency_id = False
1127         for line in self.browse(cursor, user, ids, context=context):
1128 #            if not company_currency_id:
1129 #                company_currency_id = line.company_id.id
1130             if line.voucher_id:
1131                 res[line.id] = line.voucher_id.amount#
1132 #                        res_currency_obj.compute(cursor, user,
1133 #                        company_currency_id, line.statement_id.currency.id,
1134 #                        line.voucher_id.amount, context=context)
1135             else:
1136                 res[line.id] = 0.0
1137         return res
1138
1139     def _check_amount(self, cr, uid, ids, context=None):
1140         for obj in self.browse(cr, uid, ids, context=context):
1141             if obj.voucher_id:
1142                 diff = abs(obj.amount) - obj.voucher_id.amount
1143                 if not self.pool.get('res.currency').is_zero(cr, uid, obj.voucher_id.currency_id, diff):
1144                     return False
1145         return True
1146
1147     _constraints = [
1148         (_check_amount, 'The amount of the voucher must be the same amount as the one on the statement line', ['amount']),
1149     ]
1150
1151     _columns = {
1152         'amount_reconciled': fields.function(_amount_reconciled,
1153             string='Amount reconciled', type='float'),
1154         'voucher_id': fields.many2one('account.voucher', 'Payment'),
1155
1156     }
1157
1158     def unlink(self, cr, uid, ids, context=None):
1159         voucher_obj = self.pool.get('account.voucher')
1160         statement_line = self.browse(cr, uid, ids, context=context)
1161         unlink_ids = []
1162         for st_line in statement_line:
1163             if st_line.voucher_id:
1164                 unlink_ids.append(st_line.voucher_id.id)
1165         voucher_obj.unlink(cr, uid, unlink_ids, context=context)
1166         return super(account_bank_statement_line, self).unlink(cr, uid, ids, context=context)
1167
1168 account_bank_statement_line()
1169
1170 def resolve_o2m_operations(cr, uid, target_osv, operations, fields, context):
1171     results = []
1172     for operation in operations:
1173         result = None
1174         if not isinstance(operation, (list, tuple)):
1175             result = target_osv.read(cr, uid, operation, fields, context=context)
1176         elif operation[0] == 0:
1177             # may be necessary to check if all the fields are here and get the default values?
1178             result = operation[2]
1179         elif operation[0] == 1:
1180             result = target_osv.read(cr, uid, operation[1], fields, context=context)
1181             result.update(operation[2])
1182         elif operation[0] == 4:
1183             result = target_osv.read(cr, uid, operation[1], fields, context=context)
1184         if result != None:
1185             results.append(result)
1186     return results
1187
1188 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: