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