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 _compute_writeoff_amount(self, cr, uid, line_dr_ids, line_cr_ids, amount, voucher_date, context=None):
151 currency_pool = self.pool.get('res.currency')
153 voucher_type = context.get('type', False)
154 counter_for_writeoff = counter_for_currency_diff = real_amount = 0.0
155 ctx.update({'date': voucher_date})
156 for l in line_dr_ids:
157 #compute the amount in voucher currency and in company currency if there aren't set yet
158 if not l.get('amount_in_company_currency', False):
159 ctx.update({'date': l['date_original']})
160 amount_in_company_currency = currency_pool.compute(cr, uid, l['currency_id'], l['company_currency_id'], l['amount'], context=ctx)
161 ctx.update({'date': voucher_date})
163 amount_in_company_currency = l.get('amount_in_company_currency', 0.0)
164 if not l.get('amount_in_voucher_currency'):
165 amount_in_voucher_currency = currency_pool.compute(cr, uid, l['currency_id'], l['voucher_currency_id'], l['amount'], context=ctx)
167 amount_in_voucher_currency = l.get('amount_in_voucher_currency', 0.0)
168 real_amount -= amount_in_company_currency
169 counter_for_writeoff -= l.get('voucher_currency_id') == l.get('currency_id') and l['amount'] or amount_in_voucher_currency
170 counter_for_currency_diff -= currency_pool.compute(cr, uid, l['currency_id'], l['company_currency_id'], l['amount'], context=ctx)
171 for l in line_cr_ids:
172 #compute the amount in voucher currency and in company currency if there aren't set yet
173 if not l.get('amount_in_company_currency', False):
174 ctx.update({'date': l['date_original']})
175 amount_in_company_currency = currency_pool.compute(cr, uid, l['currency_id'], l['company_currency_id'], l['amount'], context=ctx)
176 ctx.update({'date': voucher_date})
178 amount_in_company_currency = l.get('amount_in_company_currency', 0.0)
179 if not l.get('amount_in_voucher_currency'):
180 amount_in_voucher_currency = currency_pool.compute(cr, uid, l['currency_id'], l['voucher_currency_id'], l['amount'], context=ctx)
182 amount_in_voucher_currency = l.get('amount_in_voucher_currency', 0.0)
183 real_amount += amount_in_company_currency
184 counter_for_writeoff += l.get('voucher_currency_id') == l.get('currency_id') and l['amount'] or amount_in_voucher_currency
185 counter_for_currency_diff += currency_pool.compute(cr, uid, l['currency_id'], l['company_currency_id'], l['amount'], context=ctx)
186 sign = voucher_type in ['sale','receipt'] and 1 or -1
187 writeoff_amount = (sign * amount) - counter_for_writeoff
188 currency_rate_difference = real_amount - counter_for_currency_diff
189 return writeoff_amount, currency_rate_difference
191 def onchange_line_ids(self, cr, uid, ids, line_dr_ids, line_cr_ids, amount, voucher_date, context=None):
192 if not line_dr_ids and not line_cr_ids:
194 line_osv = self.pool.get("account.voucher.line")
195 line_dr_ids = resolve_o2m_operations(cr, uid, line_osv, line_dr_ids, ['amount'], context)
196 line_cr_ids = resolve_o2m_operations(cr, uid, line_osv, line_cr_ids, ['amount'], context)
197 writeoff_amount, currency_rate_diff = self._compute_writeoff_amount(cr, uid, line_dr_ids, line_cr_ids, amount, voucher_date, context=context)
198 return {'value': {'writeoff_amount': writeoff_amount, 'currency_rate_difference': currency_rate_diff}}
200 def _get_writeoff_amount(self, cr, uid, ids, name, args, context=None):
201 if not ids: return {}
204 res = {}.fromkeys(ids,{})
205 counter_for_writeoff = counter_for_currency_diff = real_amount = 0.0
206 currency_pool = self.pool.get('res.currency')
207 for voucher in self.browse(cr, uid, ids, context=context):
209 ctx.update({'date': voucher.date})
210 for l in voucher.line_dr_ids:
211 real_amount -= l.amount_in_company_currency
212 counter_for_writeoff -= (l.voucher_currency_id.id == l.currency_id.id) and l.amount or l.amount_in_voucher_currency
213 counter_for_currency_diff -= currency_pool.compute(cr, uid, l.currency_id.id, voucher.company_id.currency_id.id, l.amount, context=ctx)
214 for l in voucher.line_cr_ids:
215 real_amount += l.amount_in_company_currency
216 counter_for_writeoff += (l.voucher_currency_id.id == l.currency_id.id) and l.amount or l.amount_in_voucher_currency
217 counter_for_currency_diff += currency_pool.compute(cr, uid, l.currency_id.id, voucher.company_id.currency_id.id, l.amount, context=ctx)
218 sign = voucher.type in ['sale','receipt'] and 1 or -1
219 writeoff_amount = (sign * voucher.amount) - counter_for_writeoff
220 res[voucher.id]['writeoff_amount'] = writeoff_amount
221 res[voucher.id]['currency_rate_difference'] = real_amount - counter_for_currency_diff
224 def _currency_id(self, cr, uid, ids, name, args, context=None):
226 for voucher in self.browse(cr, uid, ids, context=context):
227 currency = voucher.journal_id.currency and voucher.journal_id.currency.id or voucher.company_id.currency_id.id
228 res[voucher.id] = {'currency_id': currency, 'currency_id2': currency}
231 _name = 'account.voucher'
232 _description = 'Accounting Voucher'
233 _order = "date desc, id desc"
235 'type':fields.selection([
237 ('purchase','Purchase'),
238 ('payment','Payment'),
239 ('receipt','Receipt'),
240 ],'Default Type', readonly=True, states={'draft':[('readonly',False)]}),
241 'name':fields.char('Memo', size=256, readonly=True, states={'draft':[('readonly',False)]}),
242 'date':fields.date('Date', readonly=True, select=True, states={'draft':[('readonly',False)]}, help="Effective date for accounting entries"),
243 'journal_id':fields.many2one('account.journal', 'Journal', required=True, readonly=True, states={'draft':[('readonly',False)]}, change_default=1),
244 'account_id':fields.many2one('account.account', 'Account', required=True, readonly=True, states={'draft':[('readonly',False)]}),
245 'line_ids':fields.one2many('account.voucher.line','voucher_id','Voucher Lines', readonly=True, states={'draft':[('readonly',False)]}),
246 'line_cr_ids':fields.one2many('account.voucher.line','voucher_id','Credits',
247 domain=[('type','=','cr')], context={'default_type':'cr'}, readonly=True, states={'draft':[('readonly',False)]}),
248 'line_dr_ids':fields.one2many('account.voucher.line','voucher_id','Debits',
249 domain=[('type','=','dr')], context={'default_type':'dr'}, readonly=True, states={'draft':[('readonly',False)]}),
250 'period_id': fields.many2one('account.period', 'Period', required=True, readonly=True, states={'draft':[('readonly',False)]}),
251 'narration':fields.text('Notes', readonly=True, states={'draft':[('readonly',False)]}),
252 'currency_id': fields.function(_currency_id, type='many2one', relation='res.currency', string='Currency', store=True, readonly=True, multi="currency"),
253 #duplicated field for display purposes
254 'currency_id2': fields.function(_currency_id, type='many2one', relation='res.currency', string='Currency', store=True, readonly=True, multi="currency"),
255 'company_id': fields.related('journal_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True),
256 'company_currency': fields.related('company_id','currency_id', type='many2one', relation='res.currency', string='Currency', readonly=True),
257 'state':fields.selection(
259 ('proforma','Pro-forma'),
261 ('cancel','Cancelled')
262 ], 'State', readonly=True, size=32,
263 help=' * The \'Draft\' state is used when a user is encoding a new and unconfirmed Voucher. \
264 \n* The \'Pro-forma\' when voucher is in Pro-forma state,voucher does not have an voucher number. \
265 \n* The \'Posted\' state is used when user create voucher,a voucher number is generated and voucher entries are created in account \
266 \n* The \'Cancelled\' state is used when user cancel voucher.'),
267 'amount': fields.float('Total', digits_compute=dp.get_precision('Account'), required=True, readonly=True, states={'draft':[('readonly',False)]}),
268 'tax_amount':fields.float('Tax Amount', digits_compute=dp.get_precision('Account'), readonly=True, states={'draft':[('readonly',False)]}),
269 'reference': fields.char('Ref #', size=64, readonly=True, states={'draft':[('readonly',False)]}, help="Transaction reference number."),
270 'number': fields.char('Number', size=32, readonly=True,),
271 'move_id':fields.many2one('account.move', 'Account Entry'),
272 'move_ids': fields.related('move_id','line_id', type='one2many', relation='account.move.line', string='Journal Items', readonly=True),
273 'partner_id':fields.many2one('res.partner', 'Partner', change_default=1, readonly=True, states={'draft':[('readonly',False)]}),
274 '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'),
275 'pay_now':fields.selection([
276 ('pay_now','Pay Directly'),
277 ('pay_later','Pay Later or Group Funds'),
278 ],'Payment', select=True, readonly=True, states={'draft':[('readonly',False)]}),
279 'tax_id':fields.many2one('account.tax', 'Tax', readonly=True, states={'draft':[('readonly',False)]}),
280 'pre_line':fields.boolean('Previous Payments ?', required=False),
281 'date_due': fields.date('Due Date', readonly=True, select=True, states={'draft':[('readonly',False)]}),
282 'payment_option':fields.selection([
283 ('without_writeoff', 'Keep Open'),
284 ('with_writeoff', 'Reconcile'),
285 ], 'Payment Difference', required=True, readonly=True, states={'draft': [('readonly', False)]}),
286 'writeoff_acc_id': fields.many2one('account.account', 'Write-Off account', readonly=True, states={'draft': [('readonly', False)]}),
287 'comment': fields.char('Write-Off Comment', size=64, required=True, readonly=True, states={'draft': [('readonly', False)]}),
288 'analytic_id': fields.many2one('account.analytic.account','Write-Off Analytic Account', readonly=True, states={'draft': [('readonly', False)]}),
289 'writeoff_amount': fields.function(_get_writeoff_amount, string='Write-Off Amount', type='float', readonly=True, multi="writeoff"),
290 'currency_rate_difference': fields.function(_get_writeoff_amount, string="Currency Rate Difference", type='float', multi="writeoff"),
293 'period_id': _get_period,
294 'partner_id': _get_partner,
295 'journal_id':_get_journal,
296 'currency_id': _get_currency,
297 'reference': _get_reference,
298 'narration':_get_narration,
299 'amount': _get_amount,
302 'pay_now': 'pay_later',
304 'date': lambda *a: time.strftime('%Y-%m-%d'),
305 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.voucher',context=c),
307 'payment_option': 'without_writeoff',
308 'comment': _('Write-Off'),
311 def compute_tax(self, cr, uid, ids, context=None):
312 tax_pool = self.pool.get('account.tax')
313 partner_pool = self.pool.get('res.partner')
314 position_pool = self.pool.get('account.fiscal.position')
315 voucher_voucher_line_obj = self.pool.get('account.voucher.line')
316 voucher_pool = self.pool.get('account.voucher')
317 if context is None: context = {}
319 for voucher in voucher_pool.browse(cr, uid, ids, context=context):
321 for line in voucher.line_ids:
322 voucher_amount += line.untax_amount or line.amount
323 line.amount = line.untax_amount or line.amount
324 voucher_voucher_line_obj.write(cr, uid, [line.id], {'amount':line.amount, 'untax_amount':line.untax_amount})
326 if not voucher.tax_id:
327 self.write(cr, uid, [voucher.id], {'amount':voucher_amount, 'tax_amount':0.0})
330 tax = [tax_pool.browse(cr, uid, voucher.tax_id.id, context=context)]
331 partner = partner_pool.browse(cr, uid, voucher.partner_id.id, context=context) or False
332 taxes = position_pool.map_tax(cr, uid, partner and partner.property_account_position or False, tax)
333 tax = tax_pool.browse(cr, uid, taxes, context=context)
335 total = voucher_amount
338 if not tax[0].price_include:
339 for tax_line in tax_pool.compute_all(cr, uid, tax, voucher_amount, 1).get('taxes', []):
340 total_tax += tax_line.get('amount', 0.0)
343 for line in voucher.line_ids:
347 for tax_line in tax_pool.compute_all(cr, uid, tax, line.untax_amount or line.amount, 1).get('taxes', []):
348 line_tax += tax_line.get('amount', 0.0)
349 line_total += tax_line.get('price_unit')
350 total_tax += line_tax
351 untax_amount = line.untax_amount or line.amount
352 voucher_voucher_line_obj.write(cr, uid, [line.id], {'amount':line_total, 'untax_amount':untax_amount})
354 self.write(cr, uid, [voucher.id], {'amount':total, 'tax_amount':total_tax})
357 def onchange_price(self, cr, uid, ids, line_ids, tax_id, partner_id=False, context=None):
358 context = context or {}
359 tax_pool = self.pool.get('account.tax')
360 partner_pool = self.pool.get('res.partner')
361 position_pool = self.pool.get('account.fiscal.position')
362 voucher_line_obj = self.pool.get('account.voucher.line')
369 line_ids = resolve_o2m_operations(cr, uid, voucher_line_obj, line_ids, ["amount"], context)
373 for line in line_ids:
375 line_amount = line.get('amount',0.0)
376 voucher_total += line_amount
378 total = voucher_total
381 tax = [tax_pool.browse(cr, uid, tax_id, context=context)]
383 partner = partner_pool.browse(cr, uid, partner_id, context=context) or False
384 taxes = position_pool.map_tax(cr, uid, partner and partner.property_account_position or False, tax)
385 tax = tax_pool.browse(cr, uid, taxes, context=context)
387 if not tax[0].price_include:
388 for tax_line in tax_pool.compute_all(cr, uid, tax, voucher_total, 1).get('taxes', []):
389 total_tax += tax_line.get('amount')
393 'amount':total or voucher_total,
394 'tax_amount':total_tax
400 def onchange_term_id(self, cr, uid, ids, term_id, amount):
401 term_pool = self.pool.get('account.payment.term')
404 default = {'date_due':False}
405 if term_id and amount:
406 terms = term_pool.compute(cr, uid, term_id, amount)
408 due_date = terms[-1][0]
412 return {'value':default}
414 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):
416 Returns a dict that contains new values and context
418 @param partner_id: latest value from user input for field partner_id
419 @param args: other arguments
420 @param context: context arguments, like lang, time zone
422 @return: Returns a dict which contains new values, and context
428 if not partner_id or not journal_id:
431 partner_pool = self.pool.get('res.partner')
432 journal_pool = self.pool.get('account.journal')
434 journal = journal_pool.browse(cr, uid, journal_id, context=context)
435 partner = partner_pool.browse(cr, uid, partner_id, context=context)
438 if journal.type in ('sale','sale_refund'):
439 account_id = partner.property_account_receivable.id
441 elif journal.type in ('purchase', 'purchase_refund','expense'):
442 account_id = partner.property_account_payable.id
445 if not journal.default_credit_account_id or not journal.default_debit_account_id:
446 raise osv.except_osv(_('Error !'), _('Please define default credit/debit account on the %s !') % (journal.name))
447 account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
450 default['value']['account_id'] = account_id
451 default['value']['type'] = ttype or tr_type
453 vals = self.onchange_journal(cr, uid, ids, journal_id, line_ids, tax_id, partner_id, context)
454 default['value'].update(vals.get('value'))
458 def onchange_partner_id(self, cr, uid, ids, partner_id, journal_id, price, voucher_currency_id, ttype, date, context=None):
460 Returns a dict that contains new values and context
462 @param partner_id: latest value from user input for field partner_id
463 @param args: other arguments
464 @param context: context arguments, like lang, time zone
466 @return: Returns a dict which contains new values, and context
472 context_multi_currency = context.copy()
474 context_multi_currency.update({'date': date})
476 currency_pool = self.pool.get('res.currency')
477 move_line_obj = self.pool.get('account.move.line')
478 partner_pool = self.pool.get('res.partner')
479 journal_pool = self.pool.get('account.journal')
480 voucher_line_obj = self.pool.get('account.voucher.line')
482 vals = self.onchange_journal(cr, uid, ids, journal_id, [], False, partner_id, context=context)
483 vals = vals.get('value',{})
484 voucher_currency_id = vals.get('currency_id', voucher_currency_id)
486 'value':{'line_ids':[], 'line_dr_ids':[], 'line_cr_ids':[], 'pre_line': False, 'currency_id': voucher_currency_id},
490 line_ids = ids and voucher_line_obj.search(cr, uid, [('voucher_id', 'in', ids)]) or []
492 voucher_line_obj.unlink(cr, uid, line_ids, context=context)
497 journal = journal_pool.browse(cr, uid, journal_id, context=context)
498 partner = partner_pool.browse(cr, uid, partner_id, context=context)
500 if journal.type in ('sale','sale_refund'):
501 account_id = partner.property_account_receivable.id
502 elif journal.type in ('purchase', 'purchase_refund','expense'):
503 account_id = partner.property_account_payable.id
505 account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
507 default['value']['account_id'] = account_id
509 if journal.type not in ('cash', 'bank'):
512 account_type = 'receivable'
513 if ttype == 'payment':
514 account_type = 'payable'
516 account_type = 'receivable'
518 if not context.get('move_line_ids', False):
519 ids = move_line_obj.search(cr, uid, [('state','=','valid'), ('account_id.type', '=', account_type), ('reconcile_id', '=', False), ('partner_id', '=', partner_id)], context=context)
521 ids = context['move_line_ids']
523 #computation of the assignation of voucher amount on voucher lines
524 total_credit = account_type == 'receivable' and price or 0.0
525 total_debit = account_type == 'payable' and price or 0.0
526 moves = move_line_obj.browse(cr, uid, ids, context=context)
527 company_currency = journal.company_id.currency_id.id
528 invoice_id = context.get('invoice_id', False)
529 move_line_found = False
530 #order the lines by most old first
534 if line.credit and line.reconcile_partial_id and ttype == 'receipt':
536 if line.debit and line.reconcile_partial_id and ttype == 'payment':
539 if line.invoice.id == invoice_id:
540 #if the invoice linked to the voucher line is equal to the invoice_id in context
541 #then we assign the amount on that line, whatever the other voucher lines
542 move_line_found = line.id
544 elif voucher_currency_id == company_currency:
545 #otherwise treatments is the same but with other field names
546 if line.amount_residual == price:
547 #if the amount residual is equal the amount voucher, we assign it to that voucher
548 #line, whatever the other voucher lines
549 move_line_found = line.id
551 #otherwise we will split the voucher amount on each line (by most old first)
552 total_credit += line.credit or 0.0
553 total_debit += line.debit or 0.0
554 elif voucher_currency_id == line.currency_id.id:
555 if line.amount_residual_currency == price:
556 move_line_found = line.id
558 total_credit += line.credit and line.amount_currency or 0.0
559 total_debit += line.debit and line.amount_currency or 0.0
561 #voucher line creation
563 if line.credit and line.reconcile_partial_id and ttype == 'receipt':
565 if line.debit and line.reconcile_partial_id and ttype == 'payment':
567 original_amount = line.credit or line.debit or 0.0
568 amount_original, amount_unreconciled = voucher_line_obj._get_amounts(cr, uid, line, context=context)
569 currency_id = line.currency_id and line.currency_id.id or line.company_id.currency_id.id
571 'name':line.move_id.name,
572 'type': line.credit and 'dr' or 'cr',
573 'move_line_id':line.id,
574 'account_id':line.account_id.id,
575 'amount_original': amount_original,
576 'amount': (move_line_found == line.id) and min(price, amount_unreconciled) or 0.0,
577 'currency_id': currency_id,
578 'voucher_currency_id': voucher_currency_id,
579 'date_original':line.date,
580 'company_currency_id': line.company_id.currency_id.id,
581 'date_due':line.date_maturity,
582 'amount_unreconciled': amount_unreconciled,
584 #split voucher amount by most old first
585 if not move_line_found:
586 if company_currency == voucher_currency_id:
588 amount = min(amount_unreconciled, abs(total_debit))
589 rs['amount'] = amount
590 total_debit -= amount
592 amount = min(amount_unreconciled, abs(total_credit))
593 rs['amount'] = amount
594 total_credit -= amount
595 elif voucher_currency_id == line.currency_id.id:
597 amount = min(amount_unreconciled, abs(total_debit))
598 rs['amount'] = amount
599 total_debit -= amount
601 amount = min(amount_unreconciled, abs(total_credit))
602 rs['amount'] = amount
603 total_credit -= amount
605 default['value']['line_ids'].append(rs)
606 if rs['type'] == 'cr':
607 default['value']['line_cr_ids'].append(rs)
609 default['value']['line_dr_ids'].append(rs)
611 if ttype == 'payment' and len(default['value']['line_cr_ids']) > 0:
612 default['value']['pre_line'] = 1
613 elif ttype == 'receipt' and len(default['value']['line_dr_ids']) > 0:
614 default['value']['pre_line'] = 1
615 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)
618 def onchange_date(self, cr, uid, ids, partner_id, journal_id, price, currency_id, ttype, date, context=None):
620 @param date: latest value from user input for field date
621 @param args: other arguments
622 @param context: context arguments, like lang, time zone
623 @return: Returns a dict which contains new values, and context
625 if context is None: context = {}
626 period_pool = self.pool.get('account.period')
627 res = self.onchange_partner_id(cr, uid, ids, partner_id, journal_id, price, currency_id, ttype, date, context=context)
628 if context.get('invoice_id', False):
629 company_id = self.pool.get('account.invoice').browse(cr, uid, context['invoice_id'], context=context).company_id.id
630 context.update({'company_id': company_id})
631 pids = period_pool.find(cr, uid, date, context=context)
633 if not 'value' in res:
635 res['value'].update({'period_id':pids[0]})
638 def onchange_journal(self, cr, uid, ids, journal_id, line_ids, tax_id, partner_id, context=None):
639 if context is None: context = {}
642 journal_pool = self.pool.get('account.journal')
643 journal = journal_pool.browse(cr, uid, journal_id, context=context)
644 account_id = journal.default_credit_account_id or journal.default_debit_account_id
646 if account_id and account_id.tax_ids:
647 tax_id = account_id.tax_ids[0].id
649 vals = self.onchange_price(cr, uid, ids, line_ids, tax_id, partner_id, context)
650 vals['value'].update({'tax_id':tax_id})
651 currency_id = journal.company_id.currency_id.id
653 currency_id = journal.currency.id
654 vals['value'].update({'currency_id':currency_id})
655 context.update({'company_id': journal.company_id.id})
656 periods = self.pool.get('account.period').find(cr, uid, context=context)
658 vals['value'].update({'period_id':periods[0]})
661 def proforma_voucher(self, cr, uid, ids, context=None):
662 self.action_move_line_create(cr, uid, ids, context=context)
665 def action_cancel_draft(self, cr, uid, ids, context=None):
666 wf_service = netsvc.LocalService("workflow")
667 for voucher_id in ids:
668 wf_service.trg_create(uid, 'account.voucher', voucher_id, cr)
669 self.write(cr, uid, ids, {'state':'draft'})
672 def cancel_voucher(self, cr, uid, ids, context=None):
673 reconcile_pool = self.pool.get('account.move.reconcile')
674 move_pool = self.pool.get('account.move')
676 for voucher in self.browse(cr, uid, ids, context=context):
678 for line in voucher.move_ids:
679 if line.reconcile_id:
680 recs += [line.reconcile_id.id]
681 if line.reconcile_partial_id:
682 recs += [line.reconcile_partial_id.id]
684 reconcile_pool.unlink(cr, uid, recs)
687 move_pool.button_cancel(cr, uid, [voucher.move_id.id])
688 move_pool.unlink(cr, uid, [voucher.move_id.id])
693 self.write(cr, uid, ids, res)
696 def unlink(self, cr, uid, ids, context=None):
697 for t in self.read(cr, uid, ids, ['state'], context=context):
698 if t['state'] not in ('draft', 'cancel'):
699 raise osv.except_osv(_('Invalid action !'), _('Cannot delete Voucher(s) which are already opened or paid !'))
700 return super(account_voucher, self).unlink(cr, uid, ids, context=context)
702 def onchange_payment(self, cr, uid, ids, pay_now, journal_id, partner_id, ttype='sale'):
706 res = {'account_id':False}
707 partner_pool = self.pool.get('res.partner')
708 journal_pool = self.pool.get('account.journal')
709 if pay_now == 'pay_later':
710 partner = partner_pool.browse(cr, uid, partner_id)
711 journal = journal_pool.browse(cr, uid, journal_id)
712 if journal.type in ('sale','sale_refund'):
713 account_id = partner.property_account_receivable.id
714 elif journal.type in ('purchase', 'purchase_refund','expense'):
715 account_id = partner.property_account_payable.id
717 account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
718 res['account_id'] = account_id
721 def action_move_line_create(self, cr, uid, ids, context=None):
723 def _get_payment_term_lines(term_id, amount):
724 term_pool = self.pool.get('account.payment.term')
725 if term_id and amount:
726 terms = term_pool.compute(cr, uid, term_id, amount)
731 move_pool = self.pool.get('account.move')
732 move_line_obj = self.pool.get('account.move.line')
733 currency_pool = self.pool.get('res.currency')
734 tax_obj = self.pool.get('account.tax')
735 seq_obj = self.pool.get('ir.sequence')
736 for voucher in self.browse(cr, uid, ids, context=context):
739 context_multi_currency = context.copy()
740 context_multi_currency.update({'date': voucher.date})
743 name = voucher.number
745 name = seq_obj.get_id(cr, uid, voucher.journal_id.sequence_id.id)
746 if not voucher.reference:
747 ref = name.replace('/','')
749 ref = voucher.reference
753 'journal_id': voucher.journal_id.id,
754 'narration': voucher.narration,
755 'date': voucher.date,
757 'period_id': voucher.period_id and voucher.period_id.id or False
759 move_id = move_pool.create(cr, uid, move)
761 #create the first line manually
762 company_currency = voucher.journal_id.company_id.currency_id.id
763 voucher_currency = voucher.currency_id.id
766 if voucher.type in ('purchase', 'payment'):
767 credit = currency_pool.compute(cr, uid, voucher_currency, company_currency, voucher.amount, context=context_multi_currency)
768 elif voucher.type in ('sale', 'receipt'):
769 debit = currency_pool.compute(cr, uid, voucher_currency, company_currency, voucher.amount, context=context_multi_currency)
776 sign = debit - credit < 0 and -1 or 1
777 #create the first line of the voucher
779 'name': voucher.name or '/',
782 'account_id': voucher.account_id.id,
784 'journal_id': voucher.journal_id.id,
785 'period_id': voucher.period_id.id,
786 'partner_id': voucher.partner_id.id,
787 'currency_id': company_currency <> voucher_currency and voucher_currency or False,
788 'amount_currency': company_currency <> voucher_currency and sign * voucher.amount or 0.0,
789 'date': voucher.date,
790 'date_maturity': voucher.date_due
792 move_line_obj.create(cr, uid, move_line)
794 #create the move line for the currency difference
795 if voucher.currency_rate_difference:
796 if voucher.currency_rate_difference > 0:
797 account_id = voucher.company_id.property_expense_currency_exchange
799 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! "))
801 account_id = voucher.company_id.property_income_currency_exchange
803 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! "))
805 currency_diff_line = {
806 'name': _('Currency Difference'),
807 'debit': voucher.currency_rate_difference > 0 and voucher.currency_rate_difference or 0.0,
808 'credit': voucher.currency_rate_difference < 0 and -voucher.currency_rate_difference or 0.0,
809 'account_id': account_id.id,
811 'journal_id': voucher.journal_id.id,
812 'period_id': voucher.period_id.id,
813 'partner_id': voucher.partner_id.id,
814 'date': voucher.date,
815 'date_maturity': voucher.date_due
817 move_line_obj.create(cr, uid, currency_diff_line, context=context)
820 for line in voucher.line_ids:
821 #create one move line per voucher line where amount is not 0.0
824 #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
825 if line.amount == line.amount_unreconciled:
826 amount = line.move_line_id.amount_residual #residual amount in company currency
828 amount = line.amount_in_company_currency
830 'journal_id': voucher.journal_id.id,
831 'period_id': voucher.period_id.id,
832 'name': line.name or '/',
833 'account_id': line.account_id.id,
835 'partner_id': voucher.partner_id.id,
836 'currency_id': company_currency <> line.currency_id.id and line.currency_id.id or False,
837 'analytic_account_id': line.account_analytic_id and line.account_analytic_id.id or False,
845 if line.type == 'dr':
849 if (line.type=='dr'):
850 move_line['debit'] = amount
852 move_line['credit'] = amount
854 if voucher.tax_id and voucher.type in ('sale', 'purchase'):
856 'account_tax_id': voucher.tax_id.id,
858 if move_line.get('account_tax_id', False):
859 tax_data = tax_obj.browse(cr, uid, [move_line['account_tax_id']], context=context)[0]
860 if not (tax_data.base_code_id and tax_data.tax_code_id):
861 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))
862 sign = (move_line['debit'] - move_line['credit']) < 0 and -1 or 1
863 move_line['amount_currency'] = company_currency <> line.currency_id.id and sign * line.amount or 0.0
864 voucher_line = move_line_obj.create(cr, uid, move_line)
865 if line.move_line_id.id:
866 rec_ids = [voucher_line, line.move_line_id.id]
867 rec_list_ids.append(rec_ids)
869 if not currency_pool.is_zero(cr, uid, voucher.currency_id, voucher.writeoff_amount):
870 #create one line for the write off if needed
871 diff = currency_pool.compute(cr, uid, voucher_currency, company_currency, voucher.writeoff_amount, context=context_multi_currency)
874 if voucher.payment_option == 'with_writeoff':
875 account_id = voucher.writeoff_acc_id.id
876 write_off_name = voucher.comment
877 elif voucher.type in ('sale', 'receipt'):
878 account_id = voucher.partner_id.property_account_receivable.id
880 account_id = voucher.partner_id.property_account_payable.id
882 'name': write_off_name or name,
883 'account_id': account_id,
885 'partner_id': voucher.partner_id.id,
886 'date': voucher.date,
887 'debit': diff < 0 and -diff or 0.0,
888 'credit': diff > 0 and diff or 0.0,
889 'amount_currency': company_currency <> voucher_currency and -voucher.writeoff_amount or 0.0,
890 'currency_id': company_currency <> voucher_currency and voucher_currency or False,
892 move_line_obj.create(cr, uid, move_line)
893 self.write(cr, uid, [voucher.id], {
898 if voucher.journal_id.entry_posted:
899 move_pool.post(cr, uid, [move_id], context={})
900 for rec_ids in rec_list_ids:
901 if len(rec_ids) >= 2:
902 move_line_obj.reconcile_partial(cr, uid, rec_ids)
905 def copy(self, cr, uid, id, default={}, context=None):
910 'line_cr_ids': False,
911 'line_dr_ids': False,
914 if 'date' not in default:
915 default['date'] = time.strftime('%Y-%m-%d')
916 return super(account_voucher, self).copy(cr, uid, id, default, context)
920 class account_voucher_line(osv.osv):
921 _name = 'account.voucher.line'
922 _description = 'Voucher Lines'
923 _order = "move_line_id"
925 def _currency_id(self, cr, uid, ids, name, args, context=None):
927 for line in self.browse(cr, uid, ids, context=context):
928 move_line = line.move_line_id
930 res[line.id] = move_line.currency_id and move_line.currency_id.id or move_line.company_id.currency_id.id
932 res[line.id] = line.voucher_id.currency_id.id
935 def _get_amounts(self, cr, uid, line_browse_rec, context=None):
936 if line_browse_rec.currency_id:
937 amount_original = line_browse_rec.amount_currency or 0.0
938 amount_unreconciled = line_browse_rec.amount_residual_currency
939 elif line_browse_rec.credit > 0:
940 amount_original = line_browse_rec.credit or 0.0
941 amount_unreconciled = line_browse_rec.amount_residual
943 amount_original = line_browse_rec.debit or 0.0
944 amount_unreconciled = line_browse_rec.amount_residual
945 return amount_original, amount_unreconciled
947 def _compute_balance(self, cr, uid, ids, name, args, context=None):
948 currency_pool = self.pool.get('res.currency')
950 for line in self.browse(cr, uid, ids, context=context):
951 amount_original, amount_unreconciled = self._get_amounts(cr, uid, line.move_line_id, context)
953 'amount_original': amount_original,
954 'amount_unreconciled': amount_unreconciled,
959 def __company_currency_amount(self, cr, uid, line, amount, context=None):
963 ctx.update({'date': line.date_original})
964 currency_pool = self.pool.get('res.currency')
965 amount_company_cur = currency_pool.compute(cr, uid, line.currency_id.id, line.company_currency_id.id, amount, context=ctx)
966 ctx.update({'date': line.voucher_id.date})
967 amount_voucher_cur = currency_pool.compute(cr, uid, line.currency_id.id, line.voucher_currency_id.id, amount, context=ctx)
968 return amount_company_cur, amount_voucher_cur
970 def onchange_amount(self, cr, uid, ids, amount, context=None):
971 if not amount or not ids:
972 return {'value':{'amount_in_company_currency': 0.0, 'amount_in_voucher_currency': 0.0}}
973 for line in self.browse(cr, uid, ids, context=context):
974 amount_company_cur, amount_voucher_cur = self.__company_currency_amount(cr, uid, line, amount, context=context)
975 return {'value': {'amount_in_company_currency': amount_company_cur, 'amount_in_voucher_currency': amount_voucher_cur}}
977 def _get_amount_in_company_currency(self, cr, uid, ids, name, args, context=None):
979 for line in self.browse(cr, uid, ids, context=context):
980 amount_in_company_currency, amount_in_voucher_currency = self.__company_currency_amount(cr, uid, line, line.amount, context=context)
982 'amount_in_company_currency': amount_in_company_currency,
983 'amount_in_voucher_currency': amount_in_voucher_currency,
988 'voucher_id':fields.many2one('account.voucher', 'Voucher', required=1, ondelete='cascade'),
989 'move_line_id': fields.many2one('account.move.line', 'Journal Item'),
990 'type':fields.selection([('dr','Debit'),('cr','Credit')], 'Dr/Cr'),
991 'name':fields.char('Description', size=256),
992 'account_id':fields.many2one('account.account','Account', required=True),
993 'account_analytic_id': fields.many2one('account.analytic.account', 'Analytic Account'),
994 'partner_id':fields.related('voucher_id', 'partner_id', type='many2one', relation='res.partner', string='Partner'),
995 'untax_amount':fields.float('Untax Amount'),
997 'currency_id': fields.function(_currency_id, string='Currency', type='many2one', relation='res.currency'),
998 'company_currency_id': fields.related('move_line_id','company_id','currency_id', type='many2one', relation='res.currency', string="Company Currency"),
999 'voucher_currency_id': fields.related('voucher_id', 'currency_id', type='many2one', relation='res.currency', string="Voucher Currency"),
1001 'amount':fields.float('Amount', digits_compute=dp.get_precision('Account')),
1002 '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"),
1003 '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"),
1005 'date_original': fields.related('move_line_id','date', type='date', relation='account.move.line', string='Date', readonly=1),
1006 'date_due': fields.related('move_line_id','date_maturity', type='date', relation='account.move.line', string='Due Date', readonly=1),
1007 'amount_original': fields.function(_compute_balance, multi='dc', type='float', string='Original Amount', store=True),
1008 'amount_unreconciled': fields.function(_compute_balance, multi='dc', type='float', string='Open Balance', store=True),
1009 'company_id': fields.related('voucher_id','company_id', relation='res.company', type='many2one', string='Company', store=True, readonly=True),
1015 def onchange_move_line_id(self, cr, user, ids, move_line_id, context=None):
1017 Returns a dict that contains new values and context
1019 @param move_line_id: latest value from user input for field move_line_id
1020 @param args: other arguments
1021 @param context: context arguments, like lang, time zone
1023 @return: Returns a dict which contains new values, and context
1026 move_line_obj = self.pool.get('account.move.line')
1028 move_line = move_line_obj.browse(cr, user, move_line_id, context=context)
1029 if move_line.credit:
1033 account_id = move_line.account_id.id
1035 'account_id':account_id,
1042 def default_get(self, cr, user, fields_list, context=None):
1044 Returns default values for fields
1045 @param fields_list: list of fields, for which default values are required to be read
1046 @param context: context arguments, like lang, time zone
1048 @return: Returns a dict that contains default values for fields
1052 journal_id = context.get('journal_id', False)
1053 partner_id = context.get('partner_id', False)
1054 journal_pool = self.pool.get('account.journal')
1055 partner_pool = self.pool.get('res.partner')
1056 values = super(account_voucher_line, self).default_get(cr, user, fields_list, context=context)
1057 if (not journal_id) or ('account_id' not in fields_list):
1059 journal = journal_pool.browse(cr, user, journal_id, context=context)
1062 if journal.type in ('sale', 'sale_refund'):
1063 account_id = journal.default_credit_account_id and journal.default_credit_account_id.id or False
1065 elif journal.type in ('purchase', 'expense', 'purchase_refund'):
1066 account_id = journal.default_debit_account_id and journal.default_debit_account_id.id or False
1069 partner = partner_pool.browse(cr, user, partner_id, context=context)
1070 if context.get('type') == 'payment':
1072 account_id = partner.property_account_payable.id
1073 elif context.get('type') == 'receipt':
1074 account_id = partner.property_account_receivable.id
1077 'account_id':account_id,
1081 account_voucher_line()
1083 class account_bank_statement(osv.osv):
1084 _inherit = 'account.bank.statement'
1086 def button_cancel(self, cr, uid, ids, context=None):
1087 voucher_obj = self.pool.get('account.voucher')
1088 for st in self.browse(cr, uid, ids, context=context):
1090 for line in st.line_ids:
1092 voucher_ids.append(line.voucher_id.id)
1093 voucher_obj.cancel_voucher(cr, uid, voucher_ids, context)
1094 return super(account_bank_statement, self).button_cancel(cr, uid, ids, context=context)
1096 def create_move_from_st_line(self, cr, uid, st_line_id, company_currency_id, next_number, context=None):
1097 voucher_obj = self.pool.get('account.voucher')
1098 wf_service = netsvc.LocalService("workflow")
1099 move_line_obj = self.pool.get('account.move.line')
1100 bank_st_line_obj = self.pool.get('account.bank.statement.line')
1101 st_line = bank_st_line_obj.browse(cr, uid, st_line_id, context=context)
1102 if st_line.voucher_id:
1103 voucher_obj.write(cr, uid, [st_line.voucher_id.id], {'number': next_number, 'date': st_line.date}, context=context)
1104 if st_line.voucher_id.state == 'cancel':
1105 voucher_obj.action_cancel_draft(cr, uid, [st_line.voucher_id.id], context=context)
1106 wf_service.trg_validate(uid, 'account.voucher', st_line.voucher_id.id, 'proforma_voucher', cr)
1108 v = voucher_obj.browse(cr, uid, st_line.voucher_id.id, context=context)
1109 bank_st_line_obj.write(cr, uid, [st_line_id], {
1110 'move_ids': [(4, v.move_id.id, False)]
1113 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)
1114 return super(account_bank_statement, self).create_move_from_st_line(cr, uid, st_line.id, company_currency_id, next_number, context=context)
1116 account_bank_statement()
1118 class account_bank_statement_line(osv.osv):
1119 _inherit = 'account.bank.statement.line'
1121 def _amount_reconciled(self, cursor, user, ids, name, args, context=None):
1126 # company_currency_id = False
1127 for line in self.browse(cursor, user, ids, context=context):
1128 # if not company_currency_id:
1129 # company_currency_id = line.company_id.id
1131 res[line.id] = line.voucher_id.amount#
1132 # res_currency_obj.compute(cursor, user,
1133 # company_currency_id, line.statement_id.currency.id,
1134 # line.voucher_id.amount, context=context)
1139 def _check_amount(self, cr, uid, ids, context=None):
1140 for obj in self.browse(cr, uid, ids, context=context):
1142 diff = abs(obj.amount) - obj.voucher_id.amount
1143 if not self.pool.get('res.currency').is_zero(cr, uid, obj.voucher_id.currency_id, diff):
1148 (_check_amount, 'The amount of the voucher must be the same amount as the one on the statement line', ['amount']),
1152 'amount_reconciled': fields.function(_amount_reconciled,
1153 string='Amount reconciled', type='float'),
1154 'voucher_id': fields.many2one('account.voucher', 'Payment'),
1158 def unlink(self, cr, uid, ids, context=None):
1159 voucher_obj = self.pool.get('account.voucher')
1160 statement_line = self.browse(cr, uid, ids, context=context)
1162 for st_line in statement_line:
1163 if st_line.voucher_id:
1164 unlink_ids.append(st_line.voucher_id.id)
1165 voucher_obj.unlink(cr, uid, unlink_ids, context=context)
1166 return super(account_bank_statement_line, self).unlink(cr, uid, ids, context=context)
1168 account_bank_statement_line()
1170 def resolve_o2m_operations(cr, uid, target_osv, operations, fields, context):
1172 for operation in operations:
1174 if not isinstance(operation, (list, tuple)):
1175 result = target_osv.read(cr, uid, operation, fields, context=context)
1176 elif operation[0] == 0:
1177 # may be necessary to check if all the fields are here and get the default values?
1178 result = operation[2]
1179 elif operation[0] == 1:
1180 result = target_osv.read(cr, uid, operation[1], fields, context=context)
1181 result.update(operation[2])
1182 elif operation[0] == 4:
1183 result = target_osv.read(cr, uid, operation[1], fields, context=context)
1185 results.append(result)
1188 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: