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