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