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