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