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