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 = {}
124 if not view_id and context.get('invoice_type', False):
125 if context.get('invoice_type', False) in ('out_invoice', 'out_refund'):
126 result = mod_obj.get_object_reference(cr, uid, 'account_voucher', 'view_vendor_receipt_form')
128 result = mod_obj.get_object_reference(cr, uid, 'account_voucher', 'view_vendor_payment_form')
129 result = result and result[1] or False
131 if not view_id and view_type == 'form' and context.get('line_type', False):
132 if context.get('line_type', False) == 'customer':
133 result = mod_obj.get_object_reference(cr, uid, 'account_voucher', 'view_vendor_receipt_form')
135 result = mod_obj.get_object_reference(cr, uid, 'account_voucher', 'view_vendor_payment_form')
136 result = result and result[1] or False
139 res = super(account_voucher, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu)
140 doc = etree.XML(res['arch'])
141 nodes = doc.xpath("//field[@name='partner_id']")
142 if context.get('type', 'sale') in ('purchase', 'payment'):
144 node.set('domain', "[('supplier', '=', True)]")
145 res['arch'] = etree.tostring(doc)
148 def _check_paid(self, cr, uid, ids, name, args, context=None):
150 for voucher in self.browse(cr, uid, ids, context=context):
152 for line in voucher.move_ids:
153 if (line.account_id.type, 'in', ('receivable', 'payable')) and not line.reconcile_id:
158 def _compute_writeoff_amount(self, cr, uid, line_dr_ids, line_cr_ids, amount, voucher_date, context=None):
161 currency_pool = self.pool.get('res.currency')
163 voucher_type = context.get('type', False)
164 counter_for_writeoff = counter_for_currency_diff = real_amount = 0.0
165 ctx.update({'date': voucher_date})
166 for l in line_dr_ids:
167 #compute the amount in voucher currency and in company currency if there aren't set yet
168 if not l.get('amount_in_company_currency', False):
169 ctx.update({'date': l['date_original']})
170 amount_in_company_currency = currency_pool.compute(cr, uid, l['currency_id'], l['company_currency_id'], l['amount'], context=ctx)
171 ctx.update({'date': voucher_date})
173 amount_in_company_currency = l.get('amount_in_company_currency', 0.0)
174 if not l.get('amount_in_voucher_currency'):
175 amount_in_voucher_currency = currency_pool.compute(cr, uid, l['currency_id'], l['voucher_currency_id'], l['amount'], context=ctx)
177 amount_in_voucher_currency = l.get('amount_in_voucher_currency', 0.0)
178 real_amount -= amount_in_company_currency
179 counter_for_writeoff -= l.get('voucher_currency_id') == l.get('currency_id') and l['amount'] or amount_in_voucher_currency
180 counter_for_currency_diff -= currency_pool.compute(cr, uid, l['currency_id'], l['company_currency_id'], l['amount'], context=ctx)
181 for l in line_cr_ids:
182 #compute the amount in voucher currency and in company currency if there aren't set yet
183 if not l.get('amount_in_company_currency', False):
184 ctx.update({'date': l['date_original']})
185 amount_in_company_currency = currency_pool.compute(cr, uid, l['currency_id'], l['company_currency_id'], l['amount'], context=ctx)
186 ctx.update({'date': voucher_date})
188 amount_in_company_currency = l.get('amount_in_company_currency', 0.0)
189 if not l.get('amount_in_voucher_currency'):
190 amount_in_voucher_currency = currency_pool.compute(cr, uid, l['currency_id'], l['voucher_currency_id'], l['amount'], context=ctx)
192 amount_in_voucher_currency = l.get('amount_in_voucher_currency', 0.0)
193 real_amount += amount_in_company_currency
194 counter_for_writeoff += l.get('voucher_currency_id') == l.get('currency_id') and l['amount'] or amount_in_voucher_currency
195 counter_for_currency_diff += currency_pool.compute(cr, uid, l['currency_id'], l['company_currency_id'], l['amount'], context=ctx)
196 sign = voucher_type in ['sale','receipt'] and 1 or -1
197 writeoff_amount = (sign * amount) - counter_for_writeoff
198 currency_rate_difference = real_amount - counter_for_currency_diff
199 return writeoff_amount, currency_rate_difference
201 def onchange_line_ids(self, cr, uid, ids, line_dr_ids, line_cr_ids, amount, voucher_date, context=None):
202 if not line_dr_ids and not line_cr_ids:
204 line_osv = self.pool.get("account.voucher.line")
205 line_dr_ids = resolve_o2m_operations(cr, uid, line_osv, line_dr_ids, ['amount'], context)
206 line_cr_ids = resolve_o2m_operations(cr, uid, line_osv, line_cr_ids, ['amount'], context)
207 writeoff_amount, currency_rate_diff = self._compute_writeoff_amount(cr, uid, line_dr_ids, line_cr_ids, amount, voucher_date, context=context)
208 return {'value': {'writeoff_amount': writeoff_amount, 'currency_rate_difference': currency_rate_diff}}
210 def _get_writeoff_amount(self, cr, uid, ids, name, args, context=None):
211 if not ids: return {}
214 res = {}.fromkeys(ids,{})
215 counter_for_writeoff = counter_for_currency_diff = real_amount = 0.0
216 currency_pool = self.pool.get('res.currency')
217 for voucher in self.browse(cr, uid, ids, context=context):
219 ctx.update({'date': voucher.date})
220 for l in voucher.line_dr_ids:
221 real_amount -= l.amount_in_company_currency
222 counter_for_writeoff -= (l.voucher_currency_id.id == l.currency_id.id) and l.amount or l.amount_in_voucher_currency
223 counter_for_currency_diff -= currency_pool.compute(cr, uid, l.currency_id.id, voucher.company_id.currency_id.id, l.amount, context=ctx)
224 for l in voucher.line_cr_ids:
225 real_amount += l.amount_in_company_currency
226 counter_for_writeoff += (l.voucher_currency_id.id == l.currency_id.id) and l.amount or l.amount_in_voucher_currency
227 counter_for_currency_diff += currency_pool.compute(cr, uid, l.currency_id.id, voucher.company_id.currency_id.id, l.amount, context=ctx)
228 sign = voucher.type in ['sale','receipt'] and 1 or -1
229 writeoff_amount = (sign * voucher.amount) - counter_for_writeoff
230 res[voucher.id]['writeoff_amount'] = writeoff_amount
231 res[voucher.id]['currency_rate_difference'] = real_amount - counter_for_currency_diff
234 def _currency_id(self, cr, uid, ids, name, args, context=None):
236 for voucher in self.browse(cr, uid, ids, context=context):
237 currency = voucher.journal_id.currency and voucher.journal_id.currency.id or voucher.company_id.currency_id.id
238 res[voucher.id] = {'currency_id': currency, 'currency_id2': currency}
241 _name = 'account.voucher'
242 _description = 'Accounting Voucher'
243 _order = "date desc, id desc"
245 'type':fields.selection([
247 ('purchase','Purchase'),
248 ('payment','Payment'),
249 ('receipt','Receipt'),
250 ],'Default Type', readonly=True, states={'draft':[('readonly',False)]}),
251 'name':fields.char('Memo', size=256, readonly=True, states={'draft':[('readonly',False)]}),
252 'date':fields.date('Date', readonly=True, select=True, states={'draft':[('readonly',False)]}, help="Effective date for accounting entries"),
253 'journal_id':fields.many2one('account.journal', 'Journal', required=True, readonly=True, states={'draft':[('readonly',False)]}, change_default=1),
254 'account_id':fields.many2one('account.account', 'Account', required=True, readonly=True, states={'draft':[('readonly',False)]}),
255 'line_ids':fields.one2many('account.voucher.line','voucher_id','Voucher Lines', readonly=True, states={'draft':[('readonly',False)]}),
256 'line_cr_ids':fields.one2many('account.voucher.line','voucher_id','Credits',
257 domain=[('type','=','cr')], context={'default_type':'cr'}, readonly=True, states={'draft':[('readonly',False)]}),
258 'line_dr_ids':fields.one2many('account.voucher.line','voucher_id','Debits',
259 domain=[('type','=','dr')], context={'default_type':'dr'}, readonly=True, states={'draft':[('readonly',False)]}),
260 'period_id': fields.many2one('account.period', 'Period', required=True, readonly=True, states={'draft':[('readonly',False)]}),
261 'narration':fields.text('Notes', readonly=True, states={'draft':[('readonly',False)]}),
262 'currency_id': fields.function(_currency_id, type='many2one', relation='res.currency', string='Currency', store=True, readonly=True, multi="currency"),
263 #duplicated field for display purposes
264 'currency_id2': fields.function(_currency_id, type='many2one', relation='res.currency', string='Currency', store=True, readonly=True, multi="currency"),
265 'company_id': fields.related('journal_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True),
266 'company_currency': fields.related('company_id','currency_id', type='many2one', relation='res.currency', string='Currency', readonly=True),
267 'state':fields.selection(
269 ('proforma','Pro-forma'),
271 ('cancel','Cancelled')
272 ], 'State', readonly=True, size=32,
273 help=' * The \'Draft\' state is used when a user is encoding a new and unconfirmed Voucher. \
274 \n* The \'Pro-forma\' when voucher is in Pro-forma state,voucher does not have an voucher number. \
275 \n* The \'Posted\' state is used when user create voucher,a voucher number is generated and voucher entries are created in account \
276 \n* The \'Cancelled\' state is used when user cancel voucher.'),
277 'amount': fields.float('Total', digits_compute=dp.get_precision('Account'), required=True, readonly=True, states={'draft':[('readonly',False)]}),
278 'tax_amount':fields.float('Tax Amount', digits_compute=dp.get_precision('Account'), readonly=True, states={'draft':[('readonly',False)]}),
279 'reference': fields.char('Ref #', size=64, readonly=True, states={'draft':[('readonly',False)]}, help="Transaction reference number."),
280 'number': fields.char('Number', size=32, readonly=True,),
281 'move_id':fields.many2one('account.move', 'Account Entry'),
282 'move_ids': fields.related('move_id','line_id', type='one2many', relation='account.move.line', string='Journal Items', readonly=True),
283 'partner_id':fields.many2one('res.partner', 'Partner', change_default=1, readonly=True, states={'draft':[('readonly',False)]}),
284 'audit': fields.related('move_id','to_check', type='boolean', help='Check this box if you are unsure of that journal entry and if you want to note it as \'to be reviewed\' by an accounting expert.', relation='account.move', string='To Review'),
285 'pay_now':fields.selection([
286 ('pay_now','Pay Directly'),
287 ('pay_later','Pay Later or Group Funds'),
288 ],'Payment', select=True, readonly=True, states={'draft':[('readonly',False)]}),
289 'tax_id':fields.many2one('account.tax', 'Tax', readonly=True, states={'draft':[('readonly',False)]}),
290 'pre_line':fields.boolean('Previous Payments ?', required=False),
291 'date_due': fields.date('Due Date', readonly=True, select=True, states={'draft':[('readonly',False)]}),
292 'payment_option':fields.selection([
293 ('without_writeoff', 'Keep Open'),
294 ('with_writeoff', 'Reconcile'),
295 ], 'Payment Difference', required=True, readonly=True, states={'draft': [('readonly', False)]}),
296 'writeoff_acc_id': fields.many2one('account.account', 'Write-Off account', readonly=True, states={'draft': [('readonly', False)]}),
297 'comment': fields.char('Write-Off Comment', size=64, required=True, readonly=True, states={'draft': [('readonly', False)]}),
298 'analytic_id': fields.many2one('account.analytic.account','Write-Off Analytic Account', readonly=True, states={'draft': [('readonly', False)]}),
299 'writeoff_amount': fields.function(_get_writeoff_amount, string='Write-Off Amount', type='float', readonly=True, multi="writeoff"),
300 'currency_rate_difference': fields.function(_get_writeoff_amount, string="Currency Rate Difference", type='float', multi="writeoff"),
301 'paid': fields.function(_check_paid, string='Paid', type='boolean', help="The Voucher has been totally paid."),
304 'period_id': _get_period,
305 'partner_id': _get_partner,
306 'journal_id':_get_journal,
307 'currency_id': _get_currency,
308 'reference': _get_reference,
309 'narration':_get_narration,
310 'amount': _get_amount,
313 'pay_now': 'pay_later',
315 'date': lambda *a: time.strftime('%Y-%m-%d'),
316 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.voucher',context=c),
318 'payment_option': 'without_writeoff',
319 'comment': _('Write-Off'),
322 def compute_tax(self, cr, uid, ids, context=None):
323 tax_pool = self.pool.get('account.tax')
324 partner_pool = self.pool.get('res.partner')
325 position_pool = self.pool.get('account.fiscal.position')
326 voucher_voucher_line_obj = self.pool.get('account.voucher.line')
327 voucher_pool = self.pool.get('account.voucher')
328 if context is None: context = {}
330 for voucher in voucher_pool.browse(cr, uid, ids, context=context):
332 for line in voucher.line_ids:
333 voucher_amount += line.untax_amount or line.amount
334 line.amount = line.untax_amount or line.amount
335 voucher_voucher_line_obj.write(cr, uid, [line.id], {'amount':line.amount, 'untax_amount':line.untax_amount})
337 if not voucher.tax_id:
338 self.write(cr, uid, [voucher.id], {'amount':voucher_amount, 'tax_amount':0.0})
341 tax = [tax_pool.browse(cr, uid, voucher.tax_id.id, context=context)]
342 partner = partner_pool.browse(cr, uid, voucher.partner_id.id, context=context) or False
343 taxes = position_pool.map_tax(cr, uid, partner and partner.property_account_position or False, tax)
344 tax = tax_pool.browse(cr, uid, taxes, context=context)
346 total = voucher_amount
349 if not tax[0].price_include:
350 for tax_line in tax_pool.compute_all(cr, uid, tax, voucher_amount, 1).get('taxes', []):
351 total_tax += tax_line.get('amount', 0.0)
354 for line in voucher.line_ids:
358 for tax_line in tax_pool.compute_all(cr, uid, tax, line.untax_amount or line.amount, 1).get('taxes', []):
359 line_tax += tax_line.get('amount', 0.0)
360 line_total += tax_line.get('price_unit')
361 total_tax += line_tax
362 untax_amount = line.untax_amount or line.amount
363 voucher_voucher_line_obj.write(cr, uid, [line.id], {'amount':line_total, 'untax_amount':untax_amount})
365 self.write(cr, uid, [voucher.id], {'amount':total, 'tax_amount':total_tax})
368 def onchange_price(self, cr, uid, ids, line_ids, tax_id, partner_id=False, context=None):
369 context = context or {}
370 tax_pool = self.pool.get('account.tax')
371 partner_pool = self.pool.get('res.partner')
372 position_pool = self.pool.get('account.fiscal.position')
373 voucher_line_obj = self.pool.get('account.voucher.line')
380 line_ids = resolve_o2m_operations(cr, uid, voucher_line_obj, line_ids, ["amount"], context)
384 for line in line_ids:
386 line_amount = line.get('amount',0.0)
387 voucher_total += line_amount
389 total = voucher_total
392 tax = [tax_pool.browse(cr, uid, tax_id, context=context)]
394 partner = partner_pool.browse(cr, uid, partner_id, context=context) or False
395 taxes = position_pool.map_tax(cr, uid, partner and partner.property_account_position or False, tax)
396 tax = tax_pool.browse(cr, uid, taxes, context=context)
398 if not tax[0].price_include:
399 for tax_line in tax_pool.compute_all(cr, uid, tax, voucher_total, 1).get('taxes', []):
400 total_tax += tax_line.get('amount')
404 'amount':total or voucher_total,
405 'tax_amount':total_tax
411 def onchange_term_id(self, cr, uid, ids, term_id, amount):
412 term_pool = self.pool.get('account.payment.term')
415 default = {'date_due':False}
416 if term_id and amount:
417 terms = term_pool.compute(cr, uid, term_id, amount)
419 due_date = terms[-1][0]
423 return {'value':default}
425 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):
427 Returns a dict that contains new values and context
429 @param partner_id: latest value from user input for field partner_id
430 @param args: other arguments
431 @param context: context arguments, like lang, time zone
433 @return: Returns a dict which contains new values, and context
439 if not partner_id or not journal_id:
442 partner_pool = self.pool.get('res.partner')
443 journal_pool = self.pool.get('account.journal')
445 journal = journal_pool.browse(cr, uid, journal_id, context=context)
446 partner = partner_pool.browse(cr, uid, partner_id, context=context)
449 if journal.type in ('sale','sale_refund'):
450 account_id = partner.property_account_receivable.id
452 elif journal.type in ('purchase', 'purchase_refund','expense'):
453 account_id = partner.property_account_payable.id
456 if not journal.default_credit_account_id or not journal.default_debit_account_id:
457 raise osv.except_osv(_('Error !'), _('Please define default credit/debit account on the %s !') % (journal.name))
458 account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
461 default['value']['account_id'] = account_id
462 default['value']['type'] = ttype or tr_type
464 vals = self.onchange_journal(cr, uid, ids, journal_id, line_ids, tax_id, partner_id, context)
465 default['value'].update(vals.get('value'))
469 def onchange_partner_id(self, cr, uid, ids, partner_id, journal_id, price, voucher_currency_id, ttype, date, context=None):
471 Returns a dict that contains new values and context
473 @param partner_id: latest value from user input for field partner_id
474 @param args: other arguments
475 @param context: context arguments, like lang, time zone
477 @return: Returns a dict which contains new values, and context
483 context_multi_currency = context.copy()
485 context_multi_currency.update({'date': date})
487 currency_pool = self.pool.get('res.currency')
488 move_line_obj = self.pool.get('account.move.line')
489 partner_pool = self.pool.get('res.partner')
490 journal_pool = self.pool.get('account.journal')
491 voucher_line_obj = self.pool.get('account.voucher.line')
493 vals = self.onchange_journal(cr, uid, ids, journal_id, [], False, partner_id, context=context)
494 vals = vals.get('value',{})
495 voucher_currency_id = vals.get('currency_id', voucher_currency_id)
497 'value':{'line_ids':[], 'line_dr_ids':[], 'line_cr_ids':[], 'pre_line': False, 'currency_id': voucher_currency_id},
501 line_ids = ids and voucher_line_obj.search(cr, uid, [('voucher_id', 'in', ids)]) or []
503 voucher_line_obj.unlink(cr, uid, line_ids, context=context)
508 journal = journal_pool.browse(cr, uid, journal_id, context=context)
509 partner = partner_pool.browse(cr, uid, partner_id, context=context)
511 if journal.type in ('sale','sale_refund'):
512 account_id = partner.property_account_receivable.id
513 elif journal.type in ('purchase', 'purchase_refund','expense'):
514 account_id = partner.property_account_payable.id
516 account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
518 default['value']['account_id'] = account_id
520 if journal.type not in ('cash', 'bank'):
523 account_type = 'receivable'
524 if ttype == 'payment':
525 account_type = 'payable'
527 account_type = 'receivable'
529 if not context.get('move_line_ids', False):
530 ids = move_line_obj.search(cr, uid, [('state','=','valid'), ('account_id.type', '=', account_type), ('reconcile_id', '=', False), ('partner_id', '=', partner_id)], context=context)
532 ids = context['move_line_ids']
534 #computation of the assignation of voucher amount on voucher lines
535 total_credit = account_type == 'receivable' and price or 0.0
536 total_debit = account_type == 'payable' and price or 0.0
537 moves = move_line_obj.browse(cr, uid, ids, context=context)
538 company_currency = journal.company_id.currency_id.id
539 invoice_id = context.get('invoice_id', False)
540 move_line_found = False
541 #order the lines by most old first
545 if line.credit and line.reconcile_partial_id and ttype == 'receipt':
547 if line.debit and line.reconcile_partial_id and ttype == 'payment':
550 if line.invoice.id == invoice_id:
551 #if the invoice linked to the voucher line is equal to the invoice_id in context
552 #then we assign the amount on that line, whatever the other voucher lines
553 move_line_found = line.id
555 elif voucher_currency_id == company_currency:
556 #otherwise treatments is the same but with other field names
557 if line.amount_residual == price:
558 #if the amount residual is equal the amount voucher, we assign it to that voucher
559 #line, whatever the other voucher lines
560 move_line_found = line.id
562 #otherwise we will split the voucher amount on each line (by most old first)
563 total_credit += line.credit or 0.0
564 total_debit += line.debit or 0.0
565 elif voucher_currency_id == line.currency_id.id:
566 if line.amount_residual_currency == price:
567 move_line_found = line.id
569 total_credit += line.credit and line.amount_currency or 0.0
570 total_debit += line.debit and line.amount_currency or 0.0
572 #voucher line creation
574 if line.credit and line.reconcile_partial_id and ttype == 'receipt':
576 if line.debit and line.reconcile_partial_id and ttype == 'payment':
578 original_amount = line.credit or line.debit or 0.0
579 amount_original, amount_unreconciled = voucher_line_obj._get_amounts(cr, uid, line, context=context)
580 currency_id = line.currency_id and line.currency_id.id or line.company_id.currency_id.id
582 'name':line.move_id.name,
583 'type': line.credit and 'dr' or 'cr',
584 'move_line_id':line.id,
585 'account_id':line.account_id.id,
586 'amount_original': amount_original,
587 'amount': (move_line_found == line.id) and min(price, amount_unreconciled) or 0.0,
588 'currency_id': currency_id,
589 'voucher_currency_id': voucher_currency_id,
590 'date_original':line.date,
591 'company_currency_id': line.company_id.currency_id.id,
592 'date_due':line.date_maturity,
593 'amount_unreconciled': amount_unreconciled,
595 #split voucher amount by most old first
596 if not move_line_found:
597 if company_currency == voucher_currency_id:
599 amount = min(amount_unreconciled, abs(total_debit))
600 rs['amount'] = amount
601 total_debit -= amount
603 amount = min(amount_unreconciled, abs(total_credit))
604 rs['amount'] = amount
605 total_credit -= amount
606 elif voucher_currency_id == line.currency_id.id:
608 amount = min(amount_unreconciled, abs(total_debit))
609 rs['amount'] = amount
610 total_debit -= amount
612 amount = min(amount_unreconciled, abs(total_credit))
613 rs['amount'] = amount
614 total_credit -= amount
616 default['value']['line_ids'].append(rs)
617 if rs['type'] == 'cr':
618 default['value']['line_cr_ids'].append(rs)
620 default['value']['line_dr_ids'].append(rs)
622 if ttype == 'payment' and len(default['value']['line_cr_ids']) > 0:
623 default['value']['pre_line'] = 1
624 elif ttype == 'receipt' and len(default['value']['line_dr_ids']) > 0:
625 default['value']['pre_line'] = 1
626 default['value']['writeoff_amount'], default['value']['currency_rate_difference'] = self._compute_writeoff_amount(cr, uid, default['value']['line_dr_ids'], default['value']['line_cr_ids'], price, date, context=context)
629 def onchange_date(self, cr, uid, ids, partner_id, journal_id, price, currency_id, ttype, date, context=None):
631 @param date: latest value from user input for field date
632 @param args: other arguments
633 @param context: context arguments, like lang, time zone
634 @return: Returns a dict which contains new values, and context
636 if context is None: context = {}
637 period_pool = self.pool.get('account.period')
638 res = self.onchange_partner_id(cr, uid, ids, partner_id, journal_id, price, currency_id, ttype, date, context=context)
639 if context.get('invoice_id', False):
640 company_id = self.pool.get('account.invoice').browse(cr, uid, context['invoice_id'], context=context).company_id.id
641 context.update({'company_id': company_id})
642 pids = period_pool.find(cr, uid, date, context=context)
644 if not 'value' in res:
646 res['value'].update({'period_id':pids[0]})
649 def onchange_journal(self, cr, uid, ids, journal_id, line_ids, tax_id, partner_id, context=None):
650 if context is None: context = {}
653 journal_pool = self.pool.get('account.journal')
654 journal = journal_pool.browse(cr, uid, journal_id, context=context)
655 account_id = journal.default_credit_account_id or journal.default_debit_account_id
657 if account_id and account_id.tax_ids:
658 tax_id = account_id.tax_ids[0].id
660 vals = self.onchange_price(cr, uid, ids, line_ids, tax_id, partner_id, context)
661 vals['value'].update({'tax_id':tax_id})
662 currency_id = journal.company_id.currency_id.id
664 currency_id = journal.currency.id
665 vals['value'].update({'currency_id':currency_id})
666 context.update({'company_id': journal.company_id.id})
667 periods = self.pool.get('account.period').find(cr, uid, context=context)
669 vals['value'].update({'period_id':periods[0]})
672 def proforma_voucher(self, cr, uid, ids, context=None):
673 self.action_move_line_create(cr, uid, ids, context=context)
676 def action_cancel_draft(self, cr, uid, ids, context=None):
677 wf_service = netsvc.LocalService("workflow")
678 for voucher_id in ids:
679 wf_service.trg_create(uid, 'account.voucher', voucher_id, cr)
680 self.write(cr, uid, ids, {'state':'draft'})
683 def cancel_voucher(self, cr, uid, ids, context=None):
684 reconcile_pool = self.pool.get('account.move.reconcile')
685 move_pool = self.pool.get('account.move')
687 for voucher in self.browse(cr, uid, ids, context=context):
689 for line in voucher.move_ids:
690 if line.reconcile_id:
691 recs += [line.reconcile_id.id]
692 if line.reconcile_partial_id:
693 recs += [line.reconcile_partial_id.id]
695 reconcile_pool.unlink(cr, uid, recs)
698 move_pool.button_cancel(cr, uid, [voucher.move_id.id])
699 move_pool.unlink(cr, uid, [voucher.move_id.id])
704 self.write(cr, uid, ids, res)
707 def unlink(self, cr, uid, ids, context=None):
708 for t in self.read(cr, uid, ids, ['state'], context=context):
709 if t['state'] not in ('draft', 'cancel'):
710 raise osv.except_osv(_('Invalid action !'), _('Cannot delete Voucher(s) which are already opened or paid !'))
711 return super(account_voucher, self).unlink(cr, uid, ids, context=context)
713 def onchange_payment(self, cr, uid, ids, pay_now, journal_id, partner_id, ttype='sale'):
717 res = {'account_id':False}
718 partner_pool = self.pool.get('res.partner')
719 journal_pool = self.pool.get('account.journal')
720 if pay_now == 'pay_later':
721 partner = partner_pool.browse(cr, uid, partner_id)
722 journal = journal_pool.browse(cr, uid, journal_id)
723 if journal.type in ('sale','sale_refund'):
724 account_id = partner.property_account_receivable.id
725 elif journal.type in ('purchase', 'purchase_refund','expense'):
726 account_id = partner.property_account_payable.id
728 account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
729 res['account_id'] = account_id
732 def action_move_line_create(self, cr, uid, ids, context=None):
734 def _get_payment_term_lines(term_id, amount):
735 term_pool = self.pool.get('account.payment.term')
736 if term_id and amount:
737 terms = term_pool.compute(cr, uid, term_id, amount)
742 move_pool = self.pool.get('account.move')
743 move_line_obj = self.pool.get('account.move.line')
744 currency_pool = self.pool.get('res.currency')
745 tax_obj = self.pool.get('account.tax')
746 seq_obj = self.pool.get('ir.sequence')
747 for voucher in self.browse(cr, uid, ids, context=context):
750 context_multi_currency = context.copy()
751 context_multi_currency.update({'date': voucher.date})
754 name = voucher.number
756 name = seq_obj.get_id(cr, uid, voucher.journal_id.sequence_id.id)
757 if not voucher.reference:
758 ref = name.replace('/','')
760 ref = voucher.reference
764 'journal_id': voucher.journal_id.id,
765 'narration': voucher.narration,
766 'date': voucher.date,
768 'period_id': voucher.period_id and voucher.period_id.id or False
770 move_id = move_pool.create(cr, uid, move)
772 #create the first line manually
773 company_currency = voucher.journal_id.company_id.currency_id.id
774 voucher_currency = voucher.currency_id.id
777 if voucher.type in ('purchase', 'payment'):
778 credit = currency_pool.compute(cr, uid, voucher_currency, company_currency, voucher.amount, context=context_multi_currency)
779 elif voucher.type in ('sale', 'receipt'):
780 debit = currency_pool.compute(cr, uid, voucher_currency, company_currency, voucher.amount, context=context_multi_currency)
787 sign = debit - credit < 0 and -1 or 1
788 #create the first line of the voucher
790 'name': voucher.name or '/',
793 'account_id': voucher.account_id.id,
795 'journal_id': voucher.journal_id.id,
796 'period_id': voucher.period_id.id,
797 'partner_id': voucher.partner_id.id,
798 'currency_id': company_currency <> voucher_currency and voucher_currency or False,
799 'amount_currency': company_currency <> voucher_currency and sign * voucher.amount or 0.0,
800 'date': voucher.date,
801 'date_maturity': voucher.date_due
803 move_line_obj.create(cr, uid, move_line)
805 #create the move line for the currency difference
806 if voucher.currency_rate_difference:
807 if voucher.currency_rate_difference > 0:
808 account_id = voucher.company_id.property_expense_currency_exchange
810 raise osv.except_osv(_('Warning'),_("Unable to create accounting entry for currency rate difference. You have to configure the field 'Income Currency Rate' on the company! "))
812 account_id = voucher.company_id.property_income_currency_exchange
814 raise osv.except_osv(_('Warning'),_("Unable to create accounting entry for currency rate difference. You have to configure the field 'Expense Currency Rate' on the company! "))
816 currency_diff_line = {
817 'name': _('Currency Difference'),
818 'debit': voucher.currency_rate_difference > 0 and voucher.currency_rate_difference or 0.0,
819 'credit': voucher.currency_rate_difference < 0 and -voucher.currency_rate_difference or 0.0,
820 'account_id': account_id.id,
822 'journal_id': voucher.journal_id.id,
823 'period_id': voucher.period_id.id,
824 'partner_id': voucher.partner_id.id,
825 'date': voucher.date,
826 'date_maturity': voucher.date_due
828 move_line_obj.create(cr, uid, currency_diff_line, context=context)
831 for line in voucher.line_ids:
832 #create one move line per voucher line where amount is not 0.0
835 #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
836 if line.amount == line.amount_unreconciled:
837 amount = line.move_line_id.amount_residual #residual amount in company currency
839 amount = line.amount_in_company_currency
841 'journal_id': voucher.journal_id.id,
842 'period_id': voucher.period_id.id,
843 'name': line.name or '/',
844 'account_id': line.account_id.id,
846 'partner_id': voucher.partner_id.id,
847 'currency_id': company_currency <> line.currency_id.id and line.currency_id.id or False,
848 'analytic_account_id': line.account_analytic_id and line.account_analytic_id.id or False,
856 if line.type == 'dr':
860 if (line.type=='dr'):
861 move_line['debit'] = amount
863 move_line['credit'] = amount
865 if voucher.tax_id and voucher.type in ('sale', 'purchase'):
867 'account_tax_id': voucher.tax_id.id,
869 if move_line.get('account_tax_id', False):
870 tax_data = tax_obj.browse(cr, uid, [move_line['account_tax_id']], context=context)[0]
871 if not (tax_data.base_code_id and tax_data.tax_code_id):
872 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))
873 sign = (move_line['debit'] - move_line['credit']) < 0 and -1 or 1
874 move_line['amount_currency'] = company_currency <> line.currency_id.id and sign * line.amount or 0.0
875 voucher_line = move_line_obj.create(cr, uid, move_line)
876 if line.move_line_id.id:
877 rec_ids = [voucher_line, line.move_line_id.id]
878 rec_list_ids.append(rec_ids)
880 if not currency_pool.is_zero(cr, uid, voucher.currency_id, voucher.writeoff_amount):
881 #create one line for the write off if needed
882 diff = currency_pool.compute(cr, uid, voucher_currency, company_currency, voucher.writeoff_amount, context=context_multi_currency)
885 if voucher.payment_option == 'with_writeoff':
886 account_id = voucher.writeoff_acc_id.id
887 write_off_name = voucher.comment
888 elif voucher.type in ('sale', 'receipt'):
889 account_id = voucher.partner_id.property_account_receivable.id
891 account_id = voucher.partner_id.property_account_payable.id
893 'name': write_off_name or name,
894 'account_id': account_id,
896 'partner_id': voucher.partner_id.id,
897 'date': voucher.date,
898 'debit': diff < 0 and -diff or 0.0,
899 'credit': diff > 0 and diff or 0.0,
900 'amount_currency': company_currency <> voucher_currency and -voucher.writeoff_amount or 0.0,
901 'currency_id': company_currency <> voucher_currency and voucher_currency or False,
903 move_line_obj.create(cr, uid, move_line)
904 self.write(cr, uid, [voucher.id], {
909 if voucher.journal_id.entry_posted:
910 move_pool.post(cr, uid, [move_id], context={})
911 for rec_ids in rec_list_ids:
912 if len(rec_ids) >= 2:
913 move_line_obj.reconcile_partial(cr, uid, rec_ids)
916 def copy(self, cr, uid, id, default={}, context=None):
921 'line_cr_ids': False,
922 'line_dr_ids': False,
925 if 'date' not in default:
926 default['date'] = time.strftime('%Y-%m-%d')
927 return super(account_voucher, self).copy(cr, uid, id, default, context)
931 class account_voucher_line(osv.osv):
932 _name = 'account.voucher.line'
933 _description = 'Voucher Lines'
934 _order = "move_line_id"
936 def _currency_id(self, cr, uid, ids, name, args, context=None):
938 for line in self.browse(cr, uid, ids, context=context):
939 move_line = line.move_line_id
941 res[line.id] = move_line.currency_id and move_line.currency_id.id or move_line.company_id.currency_id.id
943 res[line.id] = line.voucher_id.currency_id.id
946 def _get_amounts(self, cr, uid, line_browse_rec, context=None):
947 if line_browse_rec.currency_id:
948 amount_original = line_browse_rec.amount_currency or 0.0
949 amount_unreconciled = line_browse_rec.amount_residual_currency
950 elif line_browse_rec.credit > 0:
951 amount_original = line_browse_rec.credit or 0.0
952 amount_unreconciled = line_browse_rec.amount_residual
954 amount_original = line_browse_rec.debit or 0.0
955 amount_unreconciled = line_browse_rec.amount_residual
956 return amount_original, amount_unreconciled
958 def _compute_balance(self, cr, uid, ids, name, args, context=None):
959 currency_pool = self.pool.get('res.currency')
961 for line in self.browse(cr, uid, ids, context=context):
962 amount_original, amount_unreconciled = self._get_amounts(cr, uid, line.move_line_id, context)
964 'amount_original': amount_original,
965 'amount_unreconciled': amount_unreconciled,
970 def __company_currency_amount(self, cr, uid, line, amount, context=None):
974 ctx.update({'date': line.date_original})
975 currency_pool = self.pool.get('res.currency')
976 amount_company_cur = currency_pool.compute(cr, uid, line.currency_id.id, line.company_currency_id.id, amount, context=ctx)
977 ctx.update({'date': line.voucher_id.date})
978 amount_voucher_cur = currency_pool.compute(cr, uid, line.currency_id.id, line.voucher_currency_id.id, amount, context=ctx)
979 return amount_company_cur, amount_voucher_cur
981 def onchange_amount(self, cr, uid, ids, amount, context=None):
982 if not amount or not ids:
983 return {'value':{'amount_in_company_currency': 0.0, 'amount_in_voucher_currency': 0.0}}
984 for line in self.browse(cr, uid, ids, context=context):
985 amount_company_cur, amount_voucher_cur = self.__company_currency_amount(cr, uid, line, amount, context=context)
986 return {'value': {'amount_in_company_currency': amount_company_cur, 'amount_in_voucher_currency': amount_voucher_cur}}
988 def _get_amount_in_company_currency(self, cr, uid, ids, name, args, context=None):
990 for line in self.browse(cr, uid, ids, context=context):
991 amount_in_company_currency, amount_in_voucher_currency = self.__company_currency_amount(cr, uid, line, line.amount, context=context)
993 'amount_in_company_currency': amount_in_company_currency,
994 'amount_in_voucher_currency': amount_in_voucher_currency,
999 'voucher_id':fields.many2one('account.voucher', 'Voucher', required=1, ondelete='cascade'),
1000 'move_line_id': fields.many2one('account.move.line', 'Journal Item'),
1001 'type':fields.selection([('dr','Debit'),('cr','Credit')], 'Dr/Cr'),
1002 'name':fields.char('Description', size=256),
1003 'account_id':fields.many2one('account.account','Account', required=True),
1004 'account_analytic_id': fields.many2one('account.analytic.account', 'Analytic Account'),
1005 'partner_id':fields.related('voucher_id', 'partner_id', type='many2one', relation='res.partner', string='Partner'),
1006 'untax_amount':fields.float('Untax Amount'),
1008 'currency_id': fields.function(_currency_id, string='Currency', type='many2one', relation='res.currency'),
1009 'company_currency_id': fields.related('move_line_id','company_id','currency_id', type='many2one', relation='res.currency', string="Company Currency"),
1010 'voucher_currency_id': fields.related('voucher_id', 'currency_id', type='many2one', relation='res.currency', string="Voucher Currency"),
1012 'amount':fields.float('Amount', digits_compute=dp.get_precision('Account')),
1013 'amount_in_company_currency': fields.function(_get_amount_in_company_currency, string='Amount in Company Currency', type='float', digits_compute=dp.get_precision('Account'), multi="voucher_line_amount"),
1014 'amount_in_voucher_currency': fields.function(_get_amount_in_company_currency, string='Amount in Voucher Currency', type='float', digits_compute=dp.get_precision('Account'), multi="voucher_line_amount"),
1016 'date_original': fields.related('move_line_id','date', type='date', relation='account.move.line', string='Date', readonly=1),
1017 'date_due': fields.related('move_line_id','date_maturity', type='date', relation='account.move.line', string='Due Date', readonly=1),
1018 'amount_original': fields.function(_compute_balance, multi='dc', type='float', string='Original Amount', store=True),
1019 'amount_unreconciled': fields.function(_compute_balance, multi='dc', type='float', string='Open Balance', store=True),
1020 'company_id': fields.related('voucher_id','company_id', relation='res.company', type='many2one', string='Company', store=True, readonly=True),
1026 def onchange_move_line_id(self, cr, user, ids, move_line_id, context=None):
1028 Returns a dict that contains new values and context
1030 @param move_line_id: latest value from user input for field move_line_id
1031 @param args: other arguments
1032 @param context: context arguments, like lang, time zone
1034 @return: Returns a dict which contains new values, and context
1037 move_line_obj = self.pool.get('account.move.line')
1039 move_line = move_line_obj.browse(cr, user, move_line_id, context=context)
1040 if move_line.credit:
1044 account_id = move_line.account_id.id
1046 'account_id':account_id,
1053 def default_get(self, cr, user, fields_list, context=None):
1055 Returns default values for fields
1056 @param fields_list: list of fields, for which default values are required to be read
1057 @param context: context arguments, like lang, time zone
1059 @return: Returns a dict that contains default values for fields
1063 journal_id = context.get('journal_id', False)
1064 partner_id = context.get('partner_id', False)
1065 journal_pool = self.pool.get('account.journal')
1066 partner_pool = self.pool.get('res.partner')
1067 values = super(account_voucher_line, self).default_get(cr, user, fields_list, context=context)
1068 if (not journal_id) or ('account_id' not in fields_list):
1070 journal = journal_pool.browse(cr, user, journal_id, context=context)
1073 if journal.type in ('sale', 'sale_refund'):
1074 account_id = journal.default_credit_account_id and journal.default_credit_account_id.id or False
1076 elif journal.type in ('purchase', 'expense', 'purchase_refund'):
1077 account_id = journal.default_debit_account_id and journal.default_debit_account_id.id or False
1080 partner = partner_pool.browse(cr, user, partner_id, context=context)
1081 if context.get('type') == 'payment':
1083 account_id = partner.property_account_payable.id
1084 elif context.get('type') == 'receipt':
1085 account_id = partner.property_account_receivable.id
1088 'account_id':account_id,
1092 account_voucher_line()
1094 class account_bank_statement(osv.osv):
1095 _inherit = 'account.bank.statement'
1097 def button_cancel(self, cr, uid, ids, context=None):
1098 voucher_obj = self.pool.get('account.voucher')
1099 for st in self.browse(cr, uid, ids, context=context):
1101 for line in st.line_ids:
1103 voucher_ids.append(line.voucher_id.id)
1104 voucher_obj.cancel_voucher(cr, uid, voucher_ids, context)
1105 return super(account_bank_statement, self).button_cancel(cr, uid, ids, context=context)
1107 def create_move_from_st_line(self, cr, uid, st_line_id, company_currency_id, next_number, context=None):
1108 voucher_obj = self.pool.get('account.voucher')
1109 wf_service = netsvc.LocalService("workflow")
1110 move_line_obj = self.pool.get('account.move.line')
1111 bank_st_line_obj = self.pool.get('account.bank.statement.line')
1112 st_line = bank_st_line_obj.browse(cr, uid, st_line_id, context=context)
1113 if st_line.voucher_id:
1114 voucher_obj.write(cr, uid, [st_line.voucher_id.id], {'number': next_number, 'date': st_line.date}, context=context)
1115 if st_line.voucher_id.state == 'cancel':
1116 voucher_obj.action_cancel_draft(cr, uid, [st_line.voucher_id.id], context=context)
1117 wf_service.trg_validate(uid, 'account.voucher', st_line.voucher_id.id, 'proforma_voucher', cr)
1119 v = voucher_obj.browse(cr, uid, st_line.voucher_id.id, context=context)
1120 bank_st_line_obj.write(cr, uid, [st_line_id], {
1121 'move_ids': [(4, v.move_id.id, False)]
1124 return move_line_obj.write(cr, uid, [x.id for x in v.move_ids], {'statement_id': st_line.statement_id.id, 'date': st_line.date}, update_check=False, context=context)
1125 return super(account_bank_statement, self).create_move_from_st_line(cr, uid, st_line.id, company_currency_id, next_number, context=context)
1127 account_bank_statement()
1129 class account_bank_statement_line(osv.osv):
1130 _inherit = 'account.bank.statement.line'
1132 def _amount_reconciled(self, cursor, user, ids, name, args, context=None):
1137 # company_currency_id = False
1138 for line in self.browse(cursor, user, ids, context=context):
1139 # if not company_currency_id:
1140 # company_currency_id = line.company_id.id
1142 res[line.id] = line.voucher_id.amount#
1143 # res_currency_obj.compute(cursor, user,
1144 # company_currency_id, line.statement_id.currency.id,
1145 # line.voucher_id.amount, context=context)
1150 def _check_amount(self, cr, uid, ids, context=None):
1151 for obj in self.browse(cr, uid, ids, context=context):
1153 diff = abs(obj.amount) - obj.voucher_id.amount
1154 if not self.pool.get('res.currency').is_zero(cr, uid, obj.voucher_id.currency_id, diff):
1159 (_check_amount, 'The amount of the voucher must be the same amount as the one on the statement line', ['amount']),
1163 'amount_reconciled': fields.function(_amount_reconciled,
1164 string='Amount reconciled', type='float'),
1165 'voucher_id': fields.many2one('account.voucher', 'Payment'),
1169 def unlink(self, cr, uid, ids, context=None):
1170 voucher_obj = self.pool.get('account.voucher')
1171 statement_line = self.browse(cr, uid, ids, context=context)
1173 for st_line in statement_line:
1174 if st_line.voucher_id:
1175 unlink_ids.append(st_line.voucher_id.id)
1176 voucher_obj.unlink(cr, uid, unlink_ids, context=context)
1177 return super(account_bank_statement_line, self).unlink(cr, uid, ids, context=context)
1179 account_bank_statement_line()
1181 def resolve_o2m_operations(cr, uid, target_osv, operations, fields, context):
1183 for operation in operations:
1185 if not isinstance(operation, (list, tuple)):
1186 result = target_osv.read(cr, uid, operation, fields, context=context)
1187 elif operation[0] == 0:
1188 # may be necessary to check if all the fields are here and get the default values?
1189 result = operation[2]
1190 elif operation[0] == 1:
1191 result = target_osv.read(cr, uid, operation[1], fields, context=context)
1192 result.update(operation[2])
1193 elif operation[0] == 4:
1194 result = target_osv.read(cr, uid, operation[1], fields, context=context)
1196 results.append(result)
1199 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: