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