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