1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
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.
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.
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/>.
20 ##############################################################################
23 from lxml import etree
26 from osv import osv, fields
27 import decimal_precision as dp
28 from tools.translate import _
31 class account_voucher(osv.osv):
33 def _get_type(self, cr, uid, context=None):
36 return context.get('type', False)
38 def _get_period(self, cr, uid, context=None):
39 if context is None: context = {}
40 if context.get('period_id', False):
41 return context.get('period_id')
42 if context.get('invoice_id', False):
43 company_id = self.pool.get('account.invoice').browse(cr, uid, context['invoice_id'], context=context).company_id.id
44 context.update({'company_id': company_id})
45 periods = self.pool.get('account.period').find(cr, uid, context=context)
46 return periods and periods[0] or False
48 def _get_journal(self, cr, uid, context=None):
49 if context is None: context = {}
50 journal_pool = self.pool.get('account.journal')
51 invoice_pool = self.pool.get('account.invoice')
52 if context.get('invoice_id', False):
53 currency_id = invoice_pool.browse(cr, uid, context['invoice_id'], context=context).currency_id.id
54 journal_id = journal_pool.search(cr, uid, [('currency', '=', currency_id)], limit=1)
55 return journal_id and journal_id[0] or False
56 if context.get('journal_id', False):
57 return context.get('journal_id')
58 if not context.get('journal_id', False) and context.get('search_default_journal_id', False):
59 return context.get('search_default_journal_id')
61 ttype = context.get('type', 'bank')
62 if ttype in ('payment', 'receipt'):
64 res = journal_pool.search(cr, uid, [('type', '=', ttype)], limit=1)
65 return res and res[0] or False
67 def _get_tax(self, cr, uid, context=None):
68 if context is None: context = {}
69 journal_pool = self.pool.get('account.journal')
70 journal_id = context.get('journal_id', False)
72 ttype = context.get('type', 'bank')
73 res = journal_pool.search(cr, uid, [('type', '=', ttype)], limit=1)
80 journal = journal_pool.browse(cr, uid, journal_id, context=context)
81 account_id = journal.default_credit_account_id or journal.default_debit_account_id
82 if account_id and account_id.tax_ids:
83 tax_id = account_id.tax_ids[0].id
87 def _get_currency(self, cr, uid, context=None):
88 if context is None: context = {}
89 journal_pool = self.pool.get('account.journal')
90 journal_id = context.get('journal_id', False)
92 journal = journal_pool.browse(cr, uid, journal_id, context=context)
93 # currency_id = journal.company_id.currency_id.id
95 return journal.currency.id
98 def _get_partner(self, cr, uid, context=None):
99 if context is None: context = {}
100 return context.get('partner_id', False)
102 def _get_reference(self, cr, uid, context=None):
103 if context is None: context = {}
104 return context.get('reference', False)
106 def _get_narration(self, cr, uid, context=None):
107 if context is None: context = {}
108 return context.get('narration', False)
110 def _get_amount(self, cr, uid, context=None):
113 return context.get('amount', 0.0)
115 def name_get(self, cr, uid, ids, context=None):
118 if context is None: context = {}
119 return [(r['id'], (str("%.2f" % r['amount']) or '')) for r in self.read(cr, uid, ids, ['amount'], context, load='_classic_write')]
121 def fields_view_get(self, cr, uid, view_id=None, view_type=False, context=None, toolbar=False, submenu=False):
122 mod_obj = self.pool.get('ir.model.data')
123 if context is None: context = {}
125 def get_res_id(view_type, condition):
127 if view_type == 'tree':
128 result = mod_obj.get_object_reference(cr, uid, 'account_voucher', 'view_voucher_tree')
129 elif view_type == 'form':
131 result = mod_obj.get_object_reference(cr, uid, 'account_voucher', 'view_vendor_receipt_form')
133 result = mod_obj.get_object_reference(cr, uid, 'account_voucher', 'view_vendor_payment_form')
134 return result and result[1] or False
136 if not view_id and context.get('invoice_type', False):
137 view_id = get_res_id(view_type,context.get('invoice_type', False) in ('out_invoice', 'out_refund'))
139 if not view_id and context.get('line_type', False):
140 view_id = get_res_id(view_type,context.get('line_type', False) == 'customer')
142 res = super(account_voucher, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu)
143 doc = etree.XML(res['arch'])
144 nodes = doc.xpath("//field[@name='partner_id']")
145 if context.get('type', 'sale') in ('purchase', 'payment'):
147 node.set('domain', "[('supplier', '=', True)]")
148 res['arch'] = etree.tostring(doc)
151 def _compute_writeoff_amount(self, cr, uid, line_dr_ids, line_cr_ids, amount):
153 for l in line_dr_ids:
155 for l in line_cr_ids:
156 credit += l['amount']
157 return abs(amount - abs(credit - debit))
159 def onchange_line_ids(self, cr, uid, ids, line_dr_ids, line_cr_ids, amount):
160 if not line_dr_ids and not line_cr_ids:
162 line_dr_ids = [x[2] for x in line_dr_ids]
163 line_cr_ids = [x[2] for x in line_cr_ids]
164 return {'value': {'writeoff_amount': self._compute_writeoff_amount(cr, uid, line_dr_ids, line_cr_ids, amount)}}
166 def _get_writeoff_amount(self, cr, uid, ids, name, args, context=None):
167 if not ids: return {}
170 for voucher in self.browse(cr, uid, ids, context=context):
171 for l in voucher.line_dr_ids:
173 for l in voucher.line_cr_ids:
175 res[voucher.id] = abs(voucher.amount - abs(credit - debit))
178 _name = 'account.voucher'
179 _description = 'Accounting Voucher'
180 _order = "date desc, id desc"
181 # _rec_name = 'number'
183 'type':fields.selection([
185 ('purchase','Purchase'),
186 ('payment','Payment'),
187 ('receipt','Receipt'),
188 ],'Default Type', readonly=True, states={'draft':[('readonly',False)]}),
189 'name':fields.char('Memo', size=256, readonly=True, states={'draft':[('readonly',False)]}),
190 'date':fields.date('Date', readonly=True, select=True, states={'draft':[('readonly',False)]}, help="Effective date for accounting entries"),
191 'journal_id':fields.many2one('account.journal', 'Journal', required=True, readonly=True, states={'draft':[('readonly',False)]}),
192 'account_id':fields.many2one('account.account', 'Account', required=True, readonly=True, states={'draft':[('readonly',False)]}),
193 'line_ids':fields.one2many('account.voucher.line','voucher_id','Voucher Lines', readonly=True, states={'draft':[('readonly',False)]}),
194 'line_cr_ids':fields.one2many('account.voucher.line','voucher_id','Credits',
195 domain=[('type','=','cr')], context={'default_type':'cr'}, readonly=True, states={'draft':[('readonly',False)]}),
196 'line_dr_ids':fields.one2many('account.voucher.line','voucher_id','Debits',
197 domain=[('type','=','dr')], context={'default_type':'dr'}, readonly=True, states={'draft':[('readonly',False)]}),
198 'period_id': fields.many2one('account.period', 'Period', required=True, readonly=True, states={'draft':[('readonly',False)]}),
199 'narration':fields.text('Notes', readonly=True, states={'draft':[('readonly',False)]}),
200 'currency_id':fields.many2one('res.currency', 'Currency', readonly=True, states={'draft':[('readonly',False)]}),
201 # 'currency_id': fields.related('journal_id','currency', type='many2one', relation='res.currency', string='Currency', store=True, readonly=True, states={'draft':[('readonly',False)]}),
202 'company_id': fields.many2one('res.company', 'Company', required=True, readonly=True, states={'draft':[('readonly',False)]}),
203 'state':fields.selection(
205 ('proforma','Pro-forma'),
207 ('cancel','Cancelled')
208 ], 'State', readonly=True, size=32,
209 help=' * The \'Draft\' state is used when a user is encoding a new and unconfirmed Voucher. \
210 \n* The \'Pro-forma\' when voucher is in Pro-forma state,voucher does not have an voucher number. \
211 \n* The \'Posted\' state is used when user create voucher,a voucher number is generated and voucher entries are created in account \
212 \n* The \'Cancelled\' state is used when user cancel voucher.'),
213 'amount': fields.float('Total', digits_compute=dp.get_precision('Account'), required=True, readonly=True, states={'draft':[('readonly',False)]}),
214 'tax_amount':fields.float('Tax Amount', digits_compute=dp.get_precision('Account'), readonly=True, states={'draft':[('readonly',False)]}),
215 'reference': fields.char('Ref #', size=64, readonly=True, states={'draft':[('readonly',False)]}, help="Transaction reference number."),
216 'number': fields.char('Number', size=32, readonly=True,),
217 'move_id':fields.many2one('account.move', 'Account Entry'),
218 'move_ids': fields.related('move_id','line_id', type='one2many', relation='account.move.line', string='Journal Items', readonly=True),
219 'partner_id':fields.many2one('res.partner', 'Partner', change_default=1, readonly=True, states={'draft':[('readonly',False)]}),
220 'audit': fields.related('move_id','to_check', type='boolean', relation='account.move', string='Audit Complete ?'),
221 'pay_now':fields.selection([
222 ('pay_now','Pay Directly'),
223 ('pay_later','Pay Later or Group Funds'),
224 ],'Payment', select=True, readonly=True, states={'draft':[('readonly',False)]}),
225 'tax_id':fields.many2one('account.tax', 'Tax', readonly=True, states={'draft':[('readonly',False)]}),
226 'pre_line':fields.boolean('Previous Payments ?', required=False),
227 'date_due': fields.date('Due Date', readonly=True, select=True, states={'draft':[('readonly',False)]}),
228 'payment_option':fields.selection([
229 ('without_writeoff', 'Keep Open'),
230 ('with_writeoff', 'Reconcile with Write-Off'),
231 ], 'Payment Difference', required=True, readonly=True, states={'draft': [('readonly', False)]}),
232 'writeoff_acc_id': fields.many2one('account.account', 'Write-Off account', readonly=True, states={'draft': [('readonly', False)]}),
233 'comment': fields.char('Write-Off Comment', size=64, required=True, readonly=True, states={'draft': [('readonly', False)]}),
234 'analytic_id': fields.many2one('account.analytic.account','Write-Off Analytic Account', readonly=True, states={'draft': [('readonly', False)]}),
235 'writeoff_amount': fields.function(_get_writeoff_amount, method=True, string='Write-Off Amount', type='float', readonly=True),
238 'period_id': _get_period,
239 'partner_id': _get_partner,
240 'journal_id':_get_journal,
241 'currency_id': _get_currency,
242 'reference': _get_reference,
243 'narration':_get_narration,
244 'amount': _get_amount,
247 'pay_now': 'pay_later',
249 'date': lambda *a: time.strftime('%Y-%m-%d'),
250 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.voucher',context=c),
252 'payment_option': 'without_writeoff',
253 'comment': _('Write-Off'),
256 def compute_tax(self, cr, uid, ids, context=None):
257 tax_pool = self.pool.get('account.tax')
258 partner_pool = self.pool.get('res.partner')
259 position_pool = self.pool.get('account.fiscal.position')
260 voucher_line_pool = self.pool.get('account.voucher.line')
261 voucher_pool = self.pool.get('account.voucher')
262 if context is None: context = {}
264 for voucher in voucher_pool.browse(cr, uid, ids, context=context):
266 for line in voucher.line_ids:
267 voucher_amount += line.untax_amount or line.amount
268 line.amount = line.untax_amount or line.amount
269 voucher_line_pool.write(cr, uid, [line.id], {'amount':line.amount, 'untax_amount':line.untax_amount})
271 if not voucher.tax_id:
272 self.write(cr, uid, [voucher.id], {'amount':voucher_amount, 'tax_amount':0.0})
275 tax = [tax_pool.browse(cr, uid, voucher.tax_id.id, context=context)]
276 partner = partner_pool.browse(cr, uid, voucher.partner_id.id, context=context) or False
277 taxes = position_pool.map_tax(cr, uid, partner and partner.property_account_position or False, tax)
278 tax = tax_pool.browse(cr, uid, taxes, context=context)
280 total = voucher_amount
283 if not tax[0].price_include:
284 for tax_line in tax_pool.compute_all(cr, uid, tax, voucher_amount, 1).get('taxes', []):
285 total_tax += tax_line.get('amount', 0.0)
288 for line in voucher.line_ids:
292 for tax_line in tax_pool.compute_all(cr, uid, tax, line.untax_amount or line.amount, 1).get('taxes', []):
293 line_tax += tax_line.get('amount', 0.0)
294 line_total += tax_line.get('price_unit')
295 total_tax += line_tax
296 untax_amount = line.untax_amount or line.amount
297 voucher_line_pool.write(cr, uid, [line.id], {'amount':line_total, 'untax_amount':untax_amount})
299 self.write(cr, uid, [voucher.id], {'amount':total, 'tax_amount':total_tax})
302 def onchange_price(self, cr, uid, ids, line_ids, tax_id, partner_id=False, context=None):
303 tax_pool = self.pool.get('account.tax')
304 partner_pool = self.pool.get('res.partner')
305 position_pool = self.pool.get('account.fiscal.position')
311 voucher_line_ids = []
315 for line in line_ids:
317 line_amount = line[2] and line[2].get('amount',0.0) or 0.0
318 voucher_line_ids += [line[1]]
319 voucher_total += line_amount
321 total = voucher_total
324 tax = [tax_pool.browse(cr, uid, tax_id, context=context)]
326 partner = partner_pool.browse(cr, uid, partner_id, context=context) or False
327 taxes = position_pool.map_tax(cr, uid, partner and partner.property_account_position or False, tax)
328 tax = tax_pool.browse(cr, uid, taxes, context=context)
330 if not tax[0].price_include:
331 for tax_line in tax_pool.compute_all(cr, uid, tax, voucher_total, 1).get('taxes', []):
332 total_tax += tax_line.get('amount')
336 'amount':total or voucher_total,
337 'tax_amount':total_tax
343 def onchange_term_id(self, cr, uid, ids, term_id, amount):
344 term_pool = self.pool.get('account.payment.term')
347 default = {'date_due':False}
348 if term_id and amount:
349 terms = term_pool.compute(cr, uid, term_id, amount)
351 due_date = terms[-1][0]
355 return {'value':default}
357 def onchange_journal_voucher(self, cr, uid, ids, line_ids=False, tax_id=False, price=0.0, partner_id=False, journal_id=False, ttype=False, context=None):
359 Returns a dict that contains new values and context
361 @param partner_id: latest value from user input for field partner_id
362 @param args: other arguments
363 @param context: context arguments, like lang, time zone
365 @return: Returns a dict which contains new values, and context
371 if not partner_id or not journal_id:
374 partner_pool = self.pool.get('res.partner')
375 journal_pool = self.pool.get('account.journal')
377 journal = journal_pool.browse(cr, uid, journal_id, context=context)
378 partner = partner_pool.browse(cr, uid, partner_id, context=context)
381 if journal.type in ('sale','sale_refund'):
382 account_id = partner.property_account_receivable.id
384 elif journal.type in ('purchase', 'purchase_refund','expense'):
385 account_id = partner.property_account_payable.id
388 account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
391 default['value']['account_id'] = account_id
392 default['value']['type'] = ttype or tr_type
394 vals = self.onchange_journal(cr, uid, ids, journal_id, line_ids, tax_id, partner_id, context)
395 default['value'].update(vals.get('value'))
399 def onchange_partner_id(self, cr, uid, ids, partner_id, journal_id, price, currency_id, ttype, date, context=None):
401 Returns a dict that contains new values and context
403 @param partner_id: latest value from user input for field partner_id
404 @param args: other arguments
405 @param context: context arguments, like lang, time zone
407 @return: Returns a dict which contains new values, and context
413 context_multi_currency = context.copy()
415 context_multi_currency.update({'date': date})
417 line_pool = self.pool.get('account.voucher.line')
418 line_ids = ids and line_pool.search(cr, uid, [('voucher_id', '=', ids[0])]) or False
420 line_pool.unlink(cr, uid, line_ids)
422 currency_pool = self.pool.get('res.currency')
423 move_line_pool = self.pool.get('account.move.line')
424 partner_pool = self.pool.get('res.partner')
425 journal_pool = self.pool.get('account.journal')
427 vals = self.onchange_journal(cr, uid, ids, journal_id, [], False, partner_id, context)
428 vals = vals.get('value')
429 currency_id = vals.get('currency_id', currency_id)
431 'value':{'line_ids':[], 'line_dr_ids':[], 'line_cr_ids':[], 'pre_line': False, 'currency_id':currency_id},
437 if not partner_id and ids:
438 line_ids = line_pool.search(cr, uid, [('voucher_id', '=', ids[0])])
440 line_pool.unlink(cr, uid, line_ids)
443 journal = journal_pool.browse(cr, uid, journal_id, context=context)
444 partner = partner_pool.browse(cr, uid, partner_id, context=context)
446 if journal.type in ('sale','sale_refund'):
447 account_id = partner.property_account_receivable.id
448 elif journal.type in ('purchase', 'purchase_refund','expense'):
449 account_id = partner.property_account_payable.id
451 account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
453 default['value']['account_id'] = account_id
455 if journal.type not in ('cash', 'bank'):
460 account_type = 'receivable'
461 if ttype == 'payment':
462 account_type = 'payable'
463 total_debit = price or 0.0
465 total_credit = price or 0.0
466 account_type = 'receivable'
468 if not context.get('move_line_ids', False):
469 domain = [('state','=','valid'), ('account_id.type', '=', account_type), ('reconcile_id', '=', False), ('partner_id', '=', partner_id)]
470 if context.get('invoice_id', False):
471 domain.append(('invoice', '=', context['invoice_id']))
472 ids = move_line_pool.search(cr, uid, domain, context=context)
474 ids = context['move_line_ids']
476 moves = move_line_pool.browse(cr, uid, ids, context=context)
478 company_currency = journal.company_id.currency_id.id
479 if company_currency != currency_id and ttype == 'payment':
480 total_debit = currency_pool.compute(cr, uid, currency_id, company_currency, total_debit, context=context_multi_currency)
481 elif company_currency != currency_id and ttype == 'receipt':
482 total_credit = currency_pool.compute(cr, uid, currency_id, company_currency, total_credit, context=context_multi_currency)
485 if line.credit and line.reconcile_partial_id and ttype == 'receipt':
487 if line.debit and line.reconcile_partial_id and ttype == 'payment':
489 total_credit += line.credit or 0.0
490 total_debit += line.debit or 0.0
492 if line.credit and line.reconcile_partial_id and ttype == 'receipt':
494 if line.debit and line.reconcile_partial_id and ttype == 'payment':
496 original_amount = line.credit or line.debit or 0.0
497 amount_unreconciled = currency_pool.compute(cr, uid, line.currency_id and line.currency_id.id or company_currency, currency_id, abs(line.amount_residual_currency), context=context_multi_currency)
499 'name':line.move_id.name,
500 'type': line.credit and 'dr' or 'cr',
501 'move_line_id':line.id,
502 'account_id':line.account_id.id,
503 'amount_original': currency_pool.compute(cr, uid, line.currency_id and line.currency_id.id or company_currency, currency_id, line.currency_id and abs(line.amount_currency) or original_amount, context=context_multi_currency),
504 'date_original':line.date,
505 'date_due':line.date_maturity,
506 'amount_unreconciled': amount_unreconciled,
510 amount = min(amount_unreconciled, currency_pool.compute(cr, uid, company_currency, currency_id, abs(total_debit), context=context_multi_currency))
511 rs['amount'] = amount
512 total_debit -= amount
514 amount = min(amount_unreconciled, currency_pool.compute(cr, uid, company_currency, currency_id, abs(total_credit), context=context_multi_currency))
515 rs['amount'] = amount
516 total_credit -= amount
518 default['value']['line_ids'].append(rs)
519 if rs['type'] == 'cr':
520 default['value']['line_cr_ids'].append(rs)
522 default['value']['line_dr_ids'].append(rs)
524 if ttype == 'payment' and len(default['value']['line_cr_ids']) > 0:
525 default['value']['pre_line'] = 1
526 elif ttype == 'receipt' and len(default['value']['line_dr_ids']) > 0:
527 default['value']['pre_line'] = 1
528 default['value']['writeoff_amount'] = self._compute_writeoff_amount(cr, uid, default['value']['line_dr_ids'], default['value']['line_cr_ids'], price)
532 def onchange_date(self, cr, uid, ids, partner_id, journal_id, price, currency_id, ttype, date, context=None):
534 @param date: latest value from user input for field date
535 @param args: other arguments
536 @param context: context arguments, like lang, time zone
537 @return: Returns a dict which contains new values, and context
539 if context is None: context = {}
540 period_pool = self.pool.get('account.period')
541 res = self.onchange_partner_id(cr, uid, ids, partner_id, journal_id, price, currency_id, ttype, date, context=context)
542 if context.get('invoice_id', False):
543 company_id = self.pool.get('account.invoice').browse(cr, uid, context['invoice_id'], context=context).company_id.id
544 context.update({'company_id': company_id})
545 pids = period_pool.find(cr, uid, date, context=context)
547 if not 'value' in res:
549 res['value'].update({'period_id':pids[0]})
552 def onchange_journal(self, cr, uid, ids, journal_id, line_ids, tax_id, partner_id, context=None):
555 journal_pool = self.pool.get('account.journal')
556 journal = journal_pool.browse(cr, uid, journal_id, context=context)
557 account_id = journal.default_credit_account_id or journal.default_debit_account_id
559 if account_id and account_id.tax_ids:
560 tax_id = account_id.tax_ids[0].id
562 vals = self.onchange_price(cr, uid, ids, line_ids, tax_id, partner_id, context)
563 vals['value'].update({'tax_id':tax_id})
564 currency_id = journal.company_id.currency_id.id
566 currency_id = journal.currency.id
567 vals['value'].update({'currency_id':currency_id})
570 def proforma_voucher(self, cr, uid, ids, context=None):
571 self.action_move_line_create(cr, uid, ids, context=context)
574 def action_cancel_draft(self, cr, uid, ids, context=None):
575 wf_service = netsvc.LocalService("workflow")
576 for voucher_id in ids:
577 wf_service.trg_create(uid, 'account.voucher', voucher_id, cr)
578 self.write(cr, uid, ids, {'state':'draft'})
581 def cancel_voucher(self, cr, uid, ids, context=None):
582 reconcile_pool = self.pool.get('account.move.reconcile')
583 move_pool = self.pool.get('account.move')
584 move_line_pool = self.pool.get('account.move.line')
585 for voucher in self.browse(cr, uid, ids, context=context):
586 for line in voucher.move_ids:
587 if line.reconcile_id:
588 move_lines = [move_line.id for move_line in line.reconcile_id.line_id]
589 move_lines.remove(line.id)
590 reconcile_pool.unlink(cr, uid, line.reconcile_id.id)
591 if len(move_lines) >= 2:
592 move_line_pool.reconcile_partial(cr, uid, move_lines, 'auto',context=context)
594 move_pool.button_cancel(cr, uid, [voucher.move_id.id])
595 move_pool.unlink(cr, uid, [voucher.move_id.id])
601 self.write(cr, uid, ids, res)
604 def unlink(self, cr, uid, ids, context=None):
605 for t in self.read(cr, uid, ids, ['state'], context=context):
606 if t['state'] not in ('draft', 'cancel'):
607 raise osv.except_osv(_('Invalid action !'), _('Cannot delete Voucher(s) which are already opened or paid !'))
608 return super(account_voucher, self).unlink(cr, uid, ids, context=context)
610 # TODO: may be we can remove this method if not used anyware
611 def onchange_payment(self, cr, uid, ids, pay_now, journal_id, partner_id, ttype='sale'):
615 res = {'account_id':False}
616 partner_pool = self.pool.get('res.partner')
617 journal_pool = self.pool.get('account.journal')
618 if pay_now == 'pay_later':
619 partner = partner_pool.browse(cr, uid, partner_id)
620 journal = journal_pool.browse(cr, uid, journal_id)
621 if journal.type in ('sale','sale_refund'):
622 account_id = partner.property_account_receivable.id
623 elif journal.type in ('purchase', 'purchase_refund','expense'):
624 account_id = partner.property_account_payable.id
626 account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
627 res['account_id'] = account_id
630 def action_move_line_create(self, cr, uid, ids, context=None):
632 def _get_payment_term_lines(term_id, amount):
633 term_pool = self.pool.get('account.payment.term')
634 if term_id and amount:
635 terms = term_pool.compute(cr, uid, term_id, amount)
640 move_pool = self.pool.get('account.move')
641 move_line_pool = self.pool.get('account.move.line')
642 currency_pool = self.pool.get('res.currency')
643 tax_obj = self.pool.get('account.tax')
644 seq_obj = self.pool.get('ir.sequence')
645 for inv in self.browse(cr, uid, ids, context=context):
648 context_multi_currency = context.copy()
649 context_multi_currency.update({'date': inv.date})
651 if inv.journal_id.sequence_id:
652 name = seq_obj.get_id(cr, uid, inv.journal_id.sequence_id.id)
654 raise osv.except_osv(_('Error !'), _('Please define a sequence on the journal and make sure it is activated !'))
655 if not inv.reference:
656 ref = name.replace('/','')
662 'journal_id': inv.journal_id.id,
663 'narration': inv.narration,
666 'period_id': inv.period_id and inv.period_id.id or False
668 move_id = move_pool.create(cr, uid, move)
670 #create the first line manually
671 company_currency = inv.journal_id.company_id.currency_id.id
672 current_currency = inv.currency_id.id
675 # TODO: is there any other alternative then the voucher type ??
676 # -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
677 if inv.type in ('purchase', 'payment'):
678 credit = currency_pool.compute(cr, uid, current_currency, company_currency, inv.amount, context=context_multi_currency)
679 elif inv.type in ('sale', 'receipt'):
680 debit = currency_pool.compute(cr, uid, current_currency, company_currency, inv.amount, context=context_multi_currency)
687 sign = debit - credit < 0 and -1 or 1
688 #create the first line of the voucher
690 'name': inv.name or '/',
693 'account_id': inv.account_id.id,
695 'journal_id': inv.journal_id.id,
696 'period_id': inv.period_id.id,
697 'partner_id': inv.partner_id.id,
698 'currency_id': company_currency <> current_currency and current_currency or False,
699 'amount_currency': company_currency <> current_currency and sign * inv.amount or 0.0,
701 'date_maturity': inv.date_due
703 move_line_pool.create(cr, uid, move_line)
705 line_total = debit - credit
706 if inv.type == 'sale':
707 line_total = line_total - currency_pool.compute(cr, uid, inv.currency_id.id, company_currency, inv.tax_amount, context=context_multi_currency)
708 elif inv.type == 'purchase':
709 line_total = line_total + currency_pool.compute(cr, uid, inv.currency_id.id, company_currency, inv.tax_amount, context=context_multi_currency)
711 for line in inv.line_ids:
712 #create one move line per voucher line where amount is not 0.0
715 #we check if the voucher line is fully paid or not and create a move line to balance the payment and initial invoice if needed
716 if line.amount == line.amount_unreconciled:
717 amount = line.move_line_id.amount_residual #residual amount in company currency
719 amount = currency_pool.compute(cr, uid, current_currency, company_currency, line.untax_amount or line.amount, context=context_multi_currency)
721 'journal_id': inv.journal_id.id,
722 'period_id': inv.period_id.id,
723 'name': line.name and line.name or '/',
724 'account_id': line.account_id.id,
726 'partner_id': inv.partner_id.id,
727 'currency_id': company_currency <> current_currency and current_currency or False,
728 'analytic_account_id': line.account_analytic_id and line.account_analytic_id.id or False,
735 raise osv.except_osv(_('Warning'),
736 _("Error while processing 'account.voucher %s' (id:%s) for partner '%s', amount: %s !") % (inv.name, inv.id, inv.partner_id.name, inv.amount))
739 if line.type == 'dr':
744 if (line.type=='dr'):
746 move_line['debit'] = amount
749 move_line['credit'] = amount
751 if inv.tax_id and inv.type in ('sale', 'purchase'):
753 'account_tax_id': inv.tax_id.id,
755 if move_line.get('account_tax_id', False):
756 tax_data = tax_obj.browse(cr, uid, [move_line['account_tax_id']], context=context)[0]
757 if not (tax_data.base_code_id and tax_data.tax_code_id):
758 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))
759 sign = (move_line['debit'] - move_line['credit']) < 0 and -1 or 1
760 move_line['amount_currency'] = company_currency <> current_currency and sign * line.amount or 0.0
761 voucher_line = move_line_pool.create(cr, uid, move_line)
762 if line.move_line_id.id:
763 rec_ids = [voucher_line, line.move_line_id.id]
764 rec_list_ids.append(rec_ids)
766 inv_currency_id = inv.currency_id or inv.journal_id.currency or inv.journal_id.company_id.currency_id
767 if not currency_pool.is_zero(cr, uid, inv_currency_id, line_total):
770 if inv.payment_option == 'with_writeoff':
771 account_id = inv.writeoff_acc_id.id
772 elif inv.type in ('sale', 'receipt'):
773 account_id = inv.partner_id.property_account_receivable.id
775 account_id = inv.partner_id.property_account_payable.id
778 'account_id': account_id,
780 'partner_id': inv.partner_id.id,
782 'credit': diff > 0 and diff or 0.0,
783 'debit': diff < 0 and -diff or 0.0,
784 #'amount_currency': company_currency <> current_currency and currency_pool.compute(cr, uid, company_currency, current_currency, diff * -1, context=context_multi_currency) or 0.0,
785 #'currency_id': company_currency <> current_currency and current_currency or False,
787 move_line_pool.create(cr, uid, move_line)
788 self.write(cr, uid, [inv.id], {
793 move_pool.post(cr, uid, [move_id], context={})
794 for rec_ids in rec_list_ids:
795 if len(rec_ids) >= 2:
796 move_line_pool.reconcile_partial(cr, uid, rec_ids)
799 def copy(self, cr, uid, id, default={}, context=None):
804 'line_cr_ids': False,
805 'line_dr_ids': False,
808 if 'date' not in default:
809 default['date'] = time.strftime('%Y-%m-%d')
810 return super(account_voucher, self).copy(cr, uid, id, default, context)
814 class account_voucher_line(osv.osv):
815 _name = 'account.voucher.line'
816 _description = 'Voucher Lines'
817 _order = "move_line_id"
819 def _compute_balance(self, cr, uid, ids, name, args, context=None):
820 currency_pool = self.pool.get('res.currency')
822 for line in self.browse(cr, uid, ids, context=context):
824 ctx.update({'date': line.voucher_id.date})
826 company_currency = line.voucher_id.journal_id.company_id.currency_id.id
827 voucher_currency = line.voucher_id.currency_id.id
828 move_line = line.move_line_id or False
831 res['amount_original'] = 0.0
832 res['amount_unreconciled'] = 0.0
834 elif move_line.currency_id:
835 res['amount_original'] = currency_pool.compute(cr, uid, move_line.currency_id.id, voucher_currency, move_line.amount_currency, context=ctx)
836 elif move_line and move_line.credit > 0:
837 res['amount_original'] = currency_pool.compute(cr, uid, company_currency, voucher_currency, move_line.credit, context=ctx)
839 res['amount_original'] = currency_pool.compute(cr, uid, company_currency, voucher_currency, move_line.debit, context=ctx)
842 res['amount_unreconciled'] = currency_pool.compute(cr, uid, move_line.currency_id and move_line.currency_id.id or company_currency, voucher_currency, abs(move_line.amount_residual_currency), context=ctx)
843 rs_data[line.id] = res
847 'voucher_id':fields.many2one('account.voucher', 'Voucher', required=1, ondelete='cascade'),
848 'name':fields.char('Description', size=256),
849 'account_id':fields.many2one('account.account','Account', required=True),
850 'partner_id':fields.related('voucher_id', 'partner_id', type='many2one', relation='res.partner', string='Partner'),
851 'untax_amount':fields.float('Untax Amount'),
852 'amount':fields.float('Amount', digits_compute=dp.get_precision('Account')),
853 'type':fields.selection([('dr','Debit'),('cr','Credit')], 'Cr/Dr'),
854 'account_analytic_id': fields.many2one('account.analytic.account', 'Analytic Account'),
855 'move_line_id': fields.many2one('account.move.line', 'Journal Item'),
856 'date_original': fields.related('move_line_id','date', type='date', relation='account.move.line', string='Date', readonly=1),
857 'date_due': fields.related('move_line_id','date_maturity', type='date', relation='account.move.line', string='Due Date', readonly=1),
858 'amount_original': fields.function(_compute_balance, method=True, multi='dc', type='float', string='Original Amount', store=True, digits_compute=dp.get_precision('Account')),
859 'amount_unreconciled': fields.function(_compute_balance, method=True, multi='dc', type='float', string='Open Balance', store=True, digits_compute=dp.get_precision('Account')),
860 'company_id': fields.related('voucher_id','company_id', relation='res.company', type='many2one', string='Company', store=True, readonly=True),
866 def onchange_move_line_id(self, cr, user, ids, move_line_id, context=None):
868 Returns a dict that contains new values and context
870 @param move_line_id: latest value from user input for field move_line_id
871 @param args: other arguments
872 @param context: context arguments, like lang, time zone
874 @return: Returns a dict which contains new values, and context
877 move_line_pool = self.pool.get('account.move.line')
879 move_line = move_line_pool.browse(cr, user, move_line_id, context=context)
884 account_id = move_line.account_id.id
886 'account_id':account_id,
893 def default_get(self, cr, user, fields_list, context=None):
895 Returns default values for fields
896 @param fields_list: list of fields, for which default values are required to be read
897 @param context: context arguments, like lang, time zone
899 @return: Returns a dict that contains default values for fields
903 journal_id = context.get('journal_id', False)
904 partner_id = context.get('partner_id', False)
905 journal_pool = self.pool.get('account.journal')
906 partner_pool = self.pool.get('res.partner')
907 values = super(account_voucher_line, self).default_get(cr, user, fields_list, context=context)
908 if (not journal_id) or ('account_id' not in fields_list):
910 journal = journal_pool.browse(cr, user, journal_id, context=context)
913 if journal.type in ('sale', 'sale_refund'):
914 account_id = journal.default_credit_account_id and journal.default_credit_account_id.id or False
916 elif journal.type in ('purchase', 'expense', 'purchase_refund'):
917 account_id = journal.default_debit_account_id and journal.default_debit_account_id.id or False
920 partner = partner_pool.browse(cr, user, partner_id, context=context)
921 if context.get('type') == 'payment':
923 account_id = partner.property_account_payable.id
924 elif context.get('type') == 'receipt':
925 account_id = partner.property_account_receivable.id
928 'account_id':account_id,
932 account_voucher_line()
934 class account_bank_statement(osv.osv):
935 _inherit = 'account.bank.statement'
937 def button_cancel(self, cr, uid, ids, context=None):
938 voucher_obj = self.pool.get('account.voucher')
939 for st in self.browse(cr, uid, ids, context=context):
941 for line in st.line_ids:
943 voucher_ids.append(line.voucher_id.id)
944 voucher_obj.cancel_voucher(cr, uid, voucher_ids, context)
945 return super(account_bank_statement, self).button_cancel(cr, uid, ids, context=context)
947 def create_move_from_st_line(self, cr, uid, st_line_id, company_currency_id, next_number, context=None):
948 voucher_obj = self.pool.get('account.voucher')
949 wf_service = netsvc.LocalService("workflow")
950 move_line_obj = self.pool.get('account.move.line')
951 bank_st_line_obj = self.pool.get('account.bank.statement.line')
952 st_line = bank_st_line_obj.browse(cr, uid, st_line_id, context=context)
953 if st_line.voucher_id:
954 voucher_obj.write(cr, uid, [st_line.voucher_id.id], {'number': next_number}, context=context)
955 if st_line.voucher_id.state == 'cancel':
956 voucher_obj.action_cancel_draft(cr, uid, [st_line.voucher_id.id], context=context)
957 wf_service.trg_validate(uid, 'account.voucher', st_line.voucher_id.id, 'proforma_voucher', cr)
959 v = voucher_obj.browse(cr, uid, st_line.voucher_id.id, context=context)
960 bank_st_line_obj.write(cr, uid, [st_line_id], {
961 'move_ids': [(4, v.move_id.id, False)]
964 return move_line_obj.write(cr, uid, [x.id for x in v.move_ids], {'statement_id': st_line.statement_id.id}, context=context)
965 return super(account_bank_statement, self).create_move_from_st_line(cr, uid, st_line.id, company_currency_id, next_number, context=context)
967 account_bank_statement()
969 class account_bank_statement_line(osv.osv):
970 _inherit = 'account.bank.statement.line'
972 def _amount_reconciled(self, cursor, user, ids, name, args, context=None):
977 # company_currency_id = False
978 for line in self.browse(cursor, user, ids, context=context):
979 # if not company_currency_id:
980 # company_currency_id = line.company_id.id
982 res[line.id] = line.voucher_id.amount#
983 # res_currency_obj.compute(cursor, user,
984 # company_currency_id, line.statement_id.currency.id,
985 # line.voucher_id.amount, context=context)
990 def _check_amount(self, cr, uid, ids, context=None):
991 for obj in self.browse(cr, uid, ids, context=context):
993 if not (abs(obj.amount) == obj.voucher_id.amount):
998 (_check_amount, 'The amount of the voucher must be the same amount as the one on the statement line', ['amount']),
1002 'amount_reconciled': fields.function(_amount_reconciled,
1003 string='Amount reconciled', method=True, type='float'),
1004 'voucher_id': fields.many2one('account.voucher', 'Payment'),
1008 def unlink(self, cr, uid, ids, context=None):
1009 voucher_obj = self.pool.get('account.voucher')
1010 statement_line = self.browse(cr, uid, ids, context=context)
1012 for st_line in statement_line:
1013 if st_line.voucher_id:
1014 unlink_ids.append(st_line.voucher_id.id)
1015 voucher_obj.unlink(cr, uid, unlink_ids, context=context)
1016 return super(account_bank_statement_line, self).unlink(cr, uid, ids, context=context)
1018 account_bank_statement_line()
1020 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: