aac2e92100c94c8199f65e6a9e215cdf040b85d0
[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("%.2f" % 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=None):
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         if context is None:
351             context = {}
352         currency_pool = self.pool.get('res.currency')
353         move_pool = self.pool.get('account.move')
354         line_pool = self.pool.get('account.voucher.line')
355         move_line_pool = self.pool.get('account.move.line')
356         partner_pool = self.pool.get('res.partner')
357         journal_pool = self.pool.get('account.journal')
358
359         vals = self.onchange_journal(cr, uid, ids, journal_id, [], False, partner_id, context)
360         vals = vals.get('value')
361         currency_id = vals.get('currency_id', currency_id)
362         default = {
363             'value':{'line_ids':[], 'line_dr_ids':[], 'line_cr_ids':[], 'pre_line': False, 'currency_id':currency_id},
364         }
365
366         if not partner_id:
367             return default
368
369         if not partner_id and ids:
370             line_ids = line_pool.search(cr, uid, [('voucher_id','=',ids[0])])
371             if line_ids:
372                 line_pool.unlink(cr, uid, line_ids)
373             return default
374
375         journal = journal_pool.browse(cr, uid, journal_id)
376         partner = partner_pool.browse(cr, uid, partner_id)
377         account_id = False
378         if journal.type in ('sale','sale_refund'):
379             account_id = partner.property_account_receivable.id
380         elif journal.type in ('purchase', 'purchase_refund','expense'):
381             account_id = partner.property_account_payable.id
382         else:
383             account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
384
385         default['value']['account_id'] = account_id
386         if journal.type not in ('cash', 'bank'):
387             return default
388
389         total_credit = 0.0
390         total_debit = 0.0
391         account_type = 'receivable'
392         if ttype == 'payment':
393             account_type = 'payable'
394             total_debit = price or 0.0
395         else:
396             total_credit = price or 0.0
397             account_type = 'receivable'
398
399         if not context.get('move_line_ids', False):
400             ids = move_line_pool.search(cr, uid, [('account_id.type','=', account_type), ('reconcile_id','=', False), ('partner_id','=',partner_id)], context=context)
401         else:
402             ids = context['move_line_ids']
403         ids.reverse()
404         moves = move_line_pool.browse(cr, uid, ids)
405
406         company_currency = journal.company_id.currency_id.id
407         if company_currency != currency_id and ttype == 'payment':
408             total_debit = currency_pool.compute(cr, uid, currency_id, company_currency, total_debit)
409         elif company_currency != currency_id and ttype == 'receipt':
410             total_credit = currency_pool.compute(cr, uid, currency_id, company_currency, total_credit)
411
412         for line in moves:
413             if line.credit and line.reconcile_partial_id and ttype == 'receipt':
414                 continue
415             if line.debit and line.reconcile_partial_id and ttype == 'payment':
416                 continue
417             total_credit += line.credit or 0.0
418             total_debit += line.debit or 0.0
419
420         for line in moves:
421             if line.credit and line.reconcile_partial_id and ttype == 'receipt':
422                 continue
423             if line.debit and line.reconcile_partial_id and ttype == 'payment':
424                 continue
425
426             orignal_amount = line.credit or line.debit or 0.0
427             rs = {
428                 'name':line.move_id.name,
429                 'type': line.credit and 'dr' or 'cr',
430                 'move_line_id':line.id,
431                 'account_id':line.account_id.id,
432                 'amount_original':currency_pool.compute(cr, uid, company_currency, currency_id, orignal_amount),
433                 'date_original':line.date,
434                 'date_due':line.date_maturity,
435                 'amount_unreconciled':currency_pool.compute(cr, uid, company_currency, currency_id, line.amount_unreconciled)
436             }
437             if line.credit:
438                 amount = min(line.amount_unreconciled, total_debit)
439                 rs['amount'] = currency_pool.compute(cr, uid, company_currency, currency_id, amount)
440                 total_debit -= amount
441             else:
442                 amount = min(line.amount_unreconciled, total_credit)
443                 rs['amount'] = currency_pool.compute(cr, uid, company_currency, currency_id, amount)
444                 total_credit -= amount
445
446             default['value']['line_ids'].append(rs)
447             if rs['type'] == 'cr':
448                 default['value']['line_cr_ids'].append(rs)
449             else:
450                 default['value']['line_dr_ids'].append(rs)
451
452             if ttype == 'payment' and len(default['value']['line_cr_ids']) > 0:
453                 default['value']['pre_line'] = 1
454             elif ttype == 'receipt' and len(default['value']['line_dr_ids']) > 0:
455                 default['value']['pre_line'] = 1
456
457         return default
458
459     def onchange_date(self, cr, user, ids, date, context={}):
460         """
461         @param date: latest value from user input for field date
462         @param args: other arguments
463         @param context: context arguments, like lang, time zone
464         @return: Returns a dict which contains new values, and context
465         """
466         period_pool = self.pool.get('account.period')
467         pids = period_pool.search(cr, user, [('date_start','<=',date), ('date_stop','>=',date)])
468         if not pids:
469             return {}
470         return {
471             'value':{
472                 'period_id':pids[0]
473             }
474         }
475
476     def onchange_journal(self, cr, uid, ids, journal_id, line_ids, tax_id, partner_id, context={}):
477         if not journal_id:
478             return False
479         journal_pool = self.pool.get('account.journal')
480         journal = journal_pool.browse(cr, uid, journal_id)
481         account_id = journal.default_credit_account_id or journal.default_debit_account_id
482         tax_id = False
483         if account_id and account_id.tax_ids:
484             tax_id = account_id.tax_ids[0].id
485
486         vals = self.onchange_price(cr, uid, ids, line_ids, tax_id, partner_id, context)
487         vals['value'].update({'tax_id':tax_id})
488         currency_id = journal.company_id.currency_id.id
489         if journal.currency:
490             currency_id = journal.currency.id
491         vals['value'].update({'currency_id':currency_id})
492         return vals
493
494     def proforma_voucher(self, cr, uid, ids, context=None):
495         self.action_move_line_create(cr, uid, ids, context=context)
496         return True
497
498     def action_cancel_draft(self, cr, uid, ids, context={}):
499         wf_service = netsvc.LocalService("workflow")
500         for voucher_id in ids:
501             wf_service.trg_create(uid, 'account.voucher', voucher_id, cr)
502         self.write(cr, uid, ids, {'state':'draft'})
503         return True
504
505     def cancel_voucher(self, cr, uid, ids, context={}):
506         reconcile_pool = self.pool.get('account.move.reconcile')
507         move_pool = self.pool.get('account.move')
508         voucher_line_pool = self.pool.get('account.voucher.line')
509
510         for voucher in self.browse(cr, uid, ids):
511             recs = []
512             for line in voucher.move_ids:
513                 if line.reconcile_id:
514                     recs += [line.reconcile_id.id]
515                 if line.reconcile_partial_id:
516                     recs += [line.reconcile_partial_id.id]
517
518             reconcile_pool.unlink(cr, uid, recs)
519
520             if voucher.move_id:
521                 move_pool.button_cancel(cr, uid, [voucher.move_id.id])
522                 move_pool.unlink(cr, uid, [voucher.move_id.id])
523         res = {
524             'state':'cancel',
525             'move_id':False,
526         }
527         self.write(cr, uid, ids, res)
528         return True
529
530     def unlink(self, cr, uid, ids, context=None):
531         for t in self.read(cr, uid, ids, ['state'], context=context):
532             if t['state'] not in ('draft', 'cancel'):
533                 raise osv.except_osv(_('Invalid action !'), _('Cannot delete Voucher(s) which are already opened or paid !'))
534         return super(account_voucher, self).unlink(cr, uid, ids, context=context)
535
536     # TODO: may be we can remove this method if not used anyware
537     def onchange_payment(self, cr, uid, ids, pay_now, journal_id, partner_id, ttype='sale'):
538         res = {}
539         if not partner_id:
540             return res
541         res = {'account_id':False}
542         partner_pool = self.pool.get('res.partner')
543         journal_pool = self.pool.get('account.journal')
544         if pay_now == 'pay_later':
545             partner = partner_pool.browse(cr, uid, partner_id)
546             journal = journal_pool.browse(cr, uid, journal_id)
547             if journal.type in ('sale','sale_refund'):
548                 account_id = partner.property_account_receivable.id
549             elif journal.type in ('purchase', 'purchase_refund','expense'):
550                 account_id = partner.property_account_payable.id
551             else:
552                 account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
553             res['account_id'] = account_id
554         return {'value':res}
555
556     def action_move_line_create(self, cr, uid, ids, context=None):
557
558         def _get_payment_term_lines(term_id, amount):
559             term_pool = self.pool.get('account.payment.term')
560             if term_id and amount:
561                 terms = term_pool.compute(cr, uid, term_id, amount)
562                 return terms
563             return False
564         if not context:
565             context = {}
566         move_pool = self.pool.get('account.move')
567         move_line_pool = self.pool.get('account.move.line')
568         analytic_pool = self.pool.get('account.analytic.line')
569         currency_pool = self.pool.get('res.currency')
570         invoice_pool = self.pool.get('account.invoice')
571         bank_st_line_obj = self.pool.get('account.bank.statement.line')
572         for inv in self.browse(cr, uid, ids):
573             if inv.move_id:
574                 continue
575             if inv.number:
576                 name = inv.number
577             elif inv.journal_id.sequence_id:
578                 name = self.pool.get('ir.sequence').get_id(cr, uid, inv.journal_id.sequence_id.id)
579             else:
580                 raise osv.except_osv(_('Error !'), _('Please define a sequence on the journal !'))
581
582             move = {
583                 'name' : name,
584                 'journal_id': inv.journal_id.id,
585                 'narration' : inv.narration,
586                 'date':inv.date,
587                 'ref':inv.reference,
588                 'period_id': inv.period_id and inv.period_id.id or False
589             }
590             move_id = move_pool.create(cr, uid, move)
591             line_bank_ids = bank_st_line_obj.search(cr, uid, [('voucher_id', '=', inv.id)], context=context)
592             if line_bank_ids:
593                 bank_st_line_obj.write(cr, uid, line_bank_ids, {
594             'move_ids': [(4, move_id, False)]
595             })
596
597             #create the first line manually
598             company_currency = inv.journal_id.company_id.currency_id.id
599             debit = 0.0
600             credit = 0.0
601             # TODO: is there any other alternative then the voucher type ??
602             # -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
603             if inv.type in ('purchase', 'payment'):
604                 credit = currency_pool.compute(cr, uid, inv.currency_id.id, company_currency, inv.amount)
605             elif inv.type in ('sale', 'receipt'):
606                 debit = currency_pool.compute(cr, uid, inv.currency_id.id, company_currency, inv.amount)
607             if debit < 0:
608                 credit = -debit
609                 debit = 0.0
610             if credit < 0:
611                 debit = -credit
612                 credit = 0.0
613
614             move_line = {
615                 'name':inv.name or '/',
616                 'debit':debit,
617                 'credit':credit,
618                 'account_id':inv.account_id.id,
619                 'move_id':move_id ,
620                 'journal_id':inv.journal_id.id,
621                 'period_id':inv.period_id.id,
622                 'partner_id':inv.partner_id.id,
623                 'currency_id':inv.currency_id.id,
624                 'amount_currency':inv.amount,
625                 'date':inv.date,
626                 'date_maturity':inv.date_due
627             }
628
629             if (debit == 0.0 or credit == 0.0 or debit+credit > 0) and (debit > 0.0 or credit > 0.0):
630                 master_line = move_line_pool.create(cr, uid, move_line)
631
632             rec_list_ids = []
633             line_total = debit - credit
634             if inv.type == 'sale':
635                 line_total = line_total - currency_pool.compute(cr, uid, inv.currency_id.id, company_currency, inv.tax_amount)
636             elif inv.type == 'purchase':
637                 line_total = line_total + currency_pool.compute(cr, uid, inv.currency_id.id, company_currency, inv.tax_amount)
638
639             for line in inv.line_ids:
640                 if not line.amount:
641                     continue
642                 amount = currency_pool.compute(cr, uid, inv.currency_id.id, company_currency, line.amount)
643
644                 move_line = {
645                     'journal_id':inv.journal_id.id,
646                     'period_id':inv.period_id.id,
647                     'name':line.name and line.name or '/',
648                     'account_id':line.account_id.id,
649                     'move_id':move_id,
650                     'partner_id':inv.partner_id.id,
651                     'currency_id':inv.currency_id.id,
652                     'amount_currency':line.amount,
653                     'analytic_account_id':line.account_analytic_id and line.account_analytic_id.id or False,
654                     'quantity':1,
655                     'credit':0.0,
656                     'debit':0.0,
657                     'date':inv.date
658                 }
659                 if amount < 0:
660                     amount = -amount
661                     if line.type == 'dr':
662                         line.type = 'cr'
663                     else:
664                         line.type = 'dr'
665
666                 if (line.type=='dr'):
667                     line_total += amount
668                     move_line['debit'] = amount
669                 else:
670                     line_total -= amount
671                     move_line['credit'] = amount
672
673                 if inv.tax_id and inv.type in ('sale', 'purchase'):
674                     move_line.update({
675                         'account_tax_id':inv.tax_id.id,
676                     })
677
678                 master_line = move_line_pool.create(cr, uid, move_line)
679                 if line.move_line_id.id:
680                     rec_ids = [master_line, line.move_line_id.id]
681                     rec_list_ids.append(rec_ids)
682
683             if not self.pool.get('res.currency').is_zero(cr, uid, inv.currency_id, line_total):
684                 diff = line_total
685                 move_line = {
686                     'name':name,
687                     'account_id':False,
688                     'move_id':move_id ,
689                     'partner_id':inv.partner_id.id,
690                     'date':inv.date,
691                     'credit':diff>0 and diff or 0.0,
692                     'debit':diff<0 and -diff or 0.0,
693                 }
694                 account_id = False
695                 if inv.type in ('sale', 'receipt'):
696 #                if inv.journal_id.type in ('sale','sale_refund', 'cash', 'bank'):
697                     account_id = inv.partner_id.property_account_receivable.id
698                 else:
699                     account_id = inv.partner_id.property_account_payable.id
700                 move_line['account_id'] = account_id
701
702                 move_line_id = move_line_pool.create(cr, uid, move_line)
703
704             self.write(cr, uid, [inv.id], {
705                 'move_id': move_id,
706                 'state': 'posted',
707                 'number': name,
708             })
709             move_pool.post(cr, uid, [move_id], context={})
710             for rec_ids in rec_list_ids:
711                 if len(rec_ids) >= 2:
712                     move_line_pool.reconcile_partial(cr, uid, rec_ids)
713         return True
714
715     def copy(self, cr, uid, id, default={}, context=None):
716         default.update({
717             'state':'draft',
718             'number':False,
719             'move_id':False,
720             'line_cr_ids':False,
721             'line_dr_ids':False,
722             'reference':False
723         })
724         if 'date' not in default:
725             default['date'] = time.strftime('%Y-%m-%d')
726         return super(account_voucher, self).copy(cr, uid, id, default, context)
727
728 account_voucher()
729
730 class account_voucher_line(osv.osv):
731     _name = 'account.voucher.line'
732     _description = 'Voucher Lines'
733     _order = "move_line_id"
734
735     def _compute_balance(self, cr, uid, ids, name, args, context=None):
736         currency_pool = self.pool.get('res.currency')
737         rs_data = {}
738         for line in self.browse(cr, uid, ids):
739             res = {}
740             company_currency = line.voucher_id.journal_id.company_id.currency_id.id
741             voucher_currency = line.voucher_id.currency_id.id
742             move_line = line.move_line_id or False
743
744             if not move_line:
745                 res['amount_original'] = 0.0
746                 res['amount_unreconciled'] = 0.0
747
748             elif move_line and move_line.credit > 0:
749                 res['amount_original'] = currency_pool.compute(cr, uid, company_currency, voucher_currency, move_line.credit)
750             else:
751                 res['amount_original'] = currency_pool.compute(cr, uid, company_currency, voucher_currency, move_line.debit)
752
753             if move_line:
754                 res['amount_unreconciled'] = currency_pool.compute(cr, uid, company_currency, voucher_currency, move_line.amount_unreconciled)
755             rs_data[line.id] = res
756         return rs_data
757
758     _columns = {
759         'voucher_id':fields.many2one('account.voucher', 'Voucher', required=1, ondelete='cascade'),
760         'name':fields.char('Description', size=256),
761         'account_id':fields.many2one('account.account','Account', required=True),
762         'partner_id':fields.related('voucher_id', 'partner_id', type='many2one', relation='res.partner', string='Partner'),
763         'untax_amount':fields.float('Untax Amount'),
764         'amount':fields.float('Amount', digits=(14,2)),
765         'type':fields.selection([('dr','Debit'),('cr','Credit')], 'Cr/Dr'),
766         'account_analytic_id':  fields.many2one('account.analytic.account', 'Analytic Account'),
767         'move_line_id': fields.many2one('account.move.line', 'Journal Item'),
768         'date_original': fields.related('move_line_id','date', type='date', relation='account.move.line', string='Date', readonly=1),
769         'date_due': fields.related('move_line_id','date_maturity', type='date', relation='account.move.line', string='Due Date', readonly=1),
770         'amount_original': fields.function(_compute_balance, method=True, multi='dc', type='float', string='Originial Amount', store=True),
771         'amount_unreconciled': fields.function(_compute_balance, method=True, multi='dc', type='float', string='Open Balance', store=True),
772         'company_id': fields.related('voucher_id','company_id', relation='res.company', string='Company', store=True),
773     }
774     _defaults = {
775         'name': lambda *a: ''
776     }
777
778     def onchange_move_line_id(self, cr, user, ids, move_line_id, context={}):
779         """
780         Returns a dict that contains new values and context
781
782         @param move_line_id: latest value from user input for field move_line_id
783         @param args: other arguments
784         @param context: context arguments, like lang, time zone
785
786         @return: Returns a dict which contains new values, and context
787         """
788         res = {}
789         move_line_pool = self.pool.get('account.move.line')
790         if move_line_id:
791             move_line = move_line_pool.browse(cr, user, move_line_id, context=context)
792             move_id = move_line.move_id.id
793             if move_line.credit:
794                 ttype='dr'
795                 amount = move_line.credit
796             else:
797                 ttype='cr'
798                 amount = move_line.debit
799             account_id = move_line.account_id.id
800             res.update({
801                 'account_id':account_id,
802                 'type': ttype
803             })
804         return {
805             'value':res,
806         }
807
808     def default_get(self, cr, user, fields_list, context=None):
809         """
810         Returns default values for fields
811         @param fields_list: list of fields, for which default values are required to be read
812         @param context: context arguments, like lang, time zone
813
814         @return: Returns a dict that contains default values for fields
815         """
816         journal_id = context.get('journal_id', False)
817         partner_id = context.get('partner_id', False)
818         journal_pool = self.pool.get('account.journal')
819         partner_pool = self.pool.get('res.partner')
820         values = super(account_voucher_line, self).default_get(cr, user, fields_list, context=context)
821         if (not journal_id) or ('account_id' not in fields_list):
822             return values
823         journal = journal_pool.browse(cr, user, journal_id)
824         account_id = False
825         ttype = 'cr'
826         if journal.type in ('sale', 'sale_refund'):
827             account_id = journal.default_credit_account_id and journal.default_credit_account_id.id or False
828             ttype = 'cr'
829         elif journal.type in ('purchase', 'expense', 'purchase_refund'):
830             account_id = journal.default_debit_account_id and journal.default_debit_account_id.id or False
831             ttype = 'dr'
832         elif partner_id:
833             partner = partner_pool.browse(cr, user, partner_id, context=context)
834             if context.get('type') == 'payment':
835                 ttype = 'dr'
836                 account_id = partner.property_account_payable.id
837             elif context.get('type') == 'receipt':
838                 account_id = partner.property_account_receivable.id
839
840         if (not account_id) and 'account_id' in fields_list:
841             raise osv.except_osv(_('Invalid Error !'), _('Please change partner and try again !'))
842         values.update({
843             'account_id':account_id,
844             'type':ttype
845         })
846         return values
847 account_voucher_line()
848
849 class account_bank_statement(osv.osv):
850     _inherit = 'account.bank.statement'
851
852     def button_cancel(self, cr, uid, ids, context=None):
853         done = []
854         for st in self.browse(cr, uid, ids, context):
855             voucher_ids = []
856             for line in st.line_ids:
857                 if line.voucher_id:
858                     voucher_ids.append(line.voucher_id.id)
859             self.pool.get('account.voucher').cancel_voucher(cr, uid, voucher_ids, context)
860             self.pool.get('account.voucher').unlink(cr, uid, voucher_ids, context)
861         return super(account_bank_statement, self).button_cancel(cr, uid, ids, context=context)
862
863     def create_move_from_st_line(self, cr, uid, st_line_id, company_currency_id, next_number, context=None):
864         voucher_obj = self.pool.get('account.voucher')
865         wf_service = netsvc.LocalService("workflow")
866         st_line = self.pool.get('account.bank.statement.line').browse(cr, uid, st_line_id, context=context)
867
868         if st_line.voucher_id:
869             voucher_obj.write(cr, uid, [st_line.voucher_id.id], {'number': next_number}, context=context)
870             wf_service.trg_validate(uid, 'account.voucher', st_line.voucher_id.id, 'proforma_voucher', cr)
871             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)
872         return super(account_bank_statement, self).create_move_from_st_line(cr, uid, st_line.id, company_currency_id, next_number, context=context)
873
874 account_bank_statement()
875
876 class account_bank_statement_line(osv.osv):
877     _inherit = 'account.bank.statement.line'
878
879     def _amount_reconciled(self, cursor, user, ids, name, args, context=None):
880         if not ids:
881             return {}
882
883         res_currency_obj = self.pool.get('res.currency')
884         res = {}
885         company_currency_id = False
886         for line in self.browse(cursor, user, ids, context=context):
887 #            if not company_currency_id:
888 #                company_currency_id = line.company_id.id
889             if line.voucher_id:
890                 res[line.id] = line.voucher_id.amount#
891 #                        res_currency_obj.compute(cursor, user,
892 #                        company_currency_id, line.statement_id.currency.id,
893 #                        line.voucher_id.amount, context=context)
894             else:
895                 res[line.id] = 0.0
896         return res
897
898     _columns = {
899         'amount_reconciled': fields.function(_amount_reconciled,
900             string='Amount reconciled', method=True, type='float'),
901         'voucher_id': fields.many2one('account.voucher', 'Payment'),
902
903     }
904
905     def unlink(self, cr, uid, ids, context=None):
906         statement_line = self.browse(cr, uid, ids, context)
907         unlink_ids = []
908         for st_line in statement_line:
909             if st_line.voucher_id:
910                 unlink_ids.append(st_line.voucher_id.id)
911         self.pool.get('account.voucher').unlink(cr, uid, unlink_ids, context=context)
912         return super(account_bank_statement_line, self).unlink(cr, uid, ids, context=context)
913
914 account_bank_statement_line()