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 periods = self.pool.get('account.period').find(cr, uid)
43 return periods and periods[0] or False
45 def _get_journal(self, cr, uid, context=None):
46 if context is None: context = {}
47 journal_pool = self.pool.get('account.journal')
48 invoice_pool = self.pool.get('account.invoice')
49 if context.get('invoice_id', False):
50 currency_id = invoice_pool.browse(cr, uid, context['invoice_id'], context=context).currency_id.id
51 journal_id = journal_pool.search(cr, uid, [('currency', '=', currency_id)], limit=1)
52 return journal_id and journal_id[0] or False
53 if context.get('journal_id', False):
54 return context.get('journal_id')
55 if not context.get('journal_id', False) and context.get('search_default_journal_id', False):
56 return context.get('search_default_journal_id')
58 ttype = context.get('type', 'bank')
59 if ttype in ('payment', 'receipt'):
61 res = journal_pool.search(cr, uid, [('type', '=', ttype)], limit=1)
62 return res and res[0] or False
64 def _get_tax(self, cr, uid, context=None):
65 if context is None: context = {}
66 journal_pool = self.pool.get('account.journal')
67 journal_id = context.get('journal_id', False)
69 ttype = context.get('type', 'bank')
70 res = journal_pool.search(cr, uid, [('type', '=', ttype)], limit=1)
77 journal = journal_pool.browse(cr, uid, journal_id, context=context)
78 account_id = journal.default_credit_account_id or journal.default_debit_account_id
79 if account_id and account_id.tax_ids:
80 tax_id = account_id.tax_ids[0].id
84 def _get_currency(self, cr, uid, context=None):
85 if context is None: context = {}
86 journal_pool = self.pool.get('account.journal')
87 journal_id = context.get('journal_id', False)
89 journal = journal_pool.browse(cr, uid, journal_id, context=context)
90 # currency_id = journal.company_id.currency_id.id
92 return journal.currency.id
95 def _get_partner(self, cr, uid, context=None):
96 if context is None: context = {}
97 return context.get('partner_id', False)
99 def _get_reference(self, cr, uid, context=None):
100 if context is None: context = {}
101 return context.get('reference', False)
103 def _get_narration(self, cr, uid, context=None):
104 if context is None: context = {}
105 return context.get('narration', False)
107 def _get_amount(self, cr, uid, context=None):
110 return context.get('amount', 0.0)
112 def name_get(self, cr, uid, ids, context=None):
115 if context is None: context = {}
116 return [(r['id'], (str("%.2f" % r['amount']) or '')) for r in self.read(cr, uid, ids, ['amount'], context, load='_classic_write')]
118 def fields_view_get(self, cr, uid, view_id=None, view_type=False, context=None, toolbar=False, submenu=False):
119 mod_obj = self.pool.get('ir.model.data')
120 if context is None: context = {}
121 if not view_id and context.get('invoice_type', False):
122 if context.get('invoice_type', False) in ('out_invoice', 'out_refund'):
123 result = mod_obj.get_object_reference(cr, uid, 'account_voucher', 'view_vendor_receipt_form')
125 result = mod_obj.get_object_reference(cr, uid, 'account_voucher', 'view_vendor_payment_form')
126 result = result and result[1] or False
128 if not view_id and view_type == 'form' and context.get('line_type', False):
129 if context.get('line_type', False) == 'customer':
130 result = mod_obj.get_object_reference(cr, uid, 'account_voucher', 'view_vendor_receipt_form')
132 result = mod_obj.get_object_reference(cr, uid, 'account_voucher', 'view_vendor_payment_form')
133 result = result and result[1] or False
136 res = super(account_voucher, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu)
137 doc = etree.XML(res['arch'])
138 nodes = doc.xpath("//field[@name='partner_id']")
139 if context.get('type', 'sale') in ('purchase', 'payment'):
141 node.set('domain', "[('supplier', '=', True)]")
142 res['arch'] = etree.tostring(doc)
145 def _compute_writeoff_amount(self, cr, uid, line_dr_ids, line_cr_ids, amount, context=None):
149 debit = credit = currency_rate_diff = 0.0
150 #import pdb;pdb.set_trace()
151 for l in line_dr_ids:
152 ctx.update({'date': l['date_original']})
153 currency_rate_diff += 'amount_in_company_currency' in l and l['amount_in_company_currency'] or self.pool.get('res.currency').compute(cr, uid, l['currency_id'], l['company_currency_id'], l['amount_original'], context=ctx)
155 for l in line_cr_ids:
156 ctx.update({'date': l['date_original']})
157 currency_rate_diff -= 'amount_in_company_currency' in l and l['amount_in_company_currency'] or self.pool.get('res.currency').compute(cr, uid, l['currency_id'], l['company_currency_id'], l['amount_original'], context=ctx)
158 credit += l['amount']
159 return abs(amount - abs(credit - debit)), currency_rate_diff
161 def onchange_line_ids(self, cr, uid, ids, line_dr_ids, line_cr_ids, amount, context=None):
162 if not line_dr_ids and not line_cr_ids:
164 line_osv = self.pool.get("account.voucher.line")
165 line_dr_ids = resolve_o2m_operations(cr, uid, line_osv, line_dr_ids, ['amount'], context)
166 line_cr_ids = resolve_o2m_operations(cr, uid, line_osv, line_cr_ids, ['amount'], context)
167 currency_pool = self.pool.get('res.currency')
168 writeoff_amount, currency_rate_diff = self._compute_writeoff_amount(cr, uid, line_dr_ids, line_cr_ids, amount, context=context)
169 return {'value': {'writeoff_amount': writeoff_amount,}}# 'currency_rate_difference': currency_rate_diff}}
171 def _get_writeoff_amount(self, cr, uid, ids, name, args, context=None):
172 if not ids: return {}
175 res = {}.fromkeys(ids,{})
176 counter_for_writeoff = counter_for_currency_diff = real_amount = expected_amount = 0.0
177 currency_pool = self.pool.get('res.currency')
178 for voucher in self.browse(cr, uid, ids, context=context):
180 for l in voucher.line_dr_ids:
181 real_amount -= l.amount_in_company_currency
182 ctx.update({'date': l.date_original})
183 counter_for_writeoff -= currency_pool.compute(cr, uid, voucher.company_id.currency_id.id, voucher.currency_id.id, l.amount_in_company_currency, context=ctx)
184 ctx.update({'date': voucher.date})
185 counter_for_currency_diff -= currency_pool.compute(cr, uid, l.currency_id.id, voucher.company_id.currency_id.id, l.amount, context=ctx)
186 for l in voucher.line_cr_ids:
187 real_amount += l.amount_in_company_currency
188 ctx.update({'date': l.date_original})
189 counter_for_writeoff += currency_pool.compute(cr, uid, voucher.company_id.currency_id.id, voucher.currency_id.id, l.amount_in_company_currency, context=ctx)
190 ctx.update({'date': voucher.date})
191 counter_for_currency_diff += l.amount and currency_pool.compute(cr, uid, l.currency_id.id, voucher.company_id.currency_id.id, l.amount, context=ctx)
192 writeoff_amount = voucher.amount - counter_for_writeoff
193 res[voucher.id]['writeoff_amount'] = writeoff_amount
194 res[voucher.id]['currency_rate_difference'] = real_amount - counter_for_currency_diff
197 _name = 'account.voucher'
198 _description = 'Accounting Voucher'
199 _order = "date desc, id desc"
200 # _rec_name = 'number'
202 'type':fields.selection([
204 ('purchase','Purchase'),
205 ('payment','Payment'),
206 ('receipt','Receipt'),
207 ],'Default Type', readonly=True, states={'draft':[('readonly',False)]}),
208 'name':fields.char('Memo', size=256, readonly=True, states={'draft':[('readonly',False)]}),
209 'date':fields.date('Date', readonly=True, select=True, states={'draft':[('readonly',False)]}, help="Effective date for accounting entries"),
210 'journal_id':fields.many2one('account.journal', 'Journal', required=True, readonly=True, states={'draft':[('readonly',False)]}),
211 'account_id':fields.many2one('account.account', 'Account', required=True, readonly=True, states={'draft':[('readonly',False)]}),
212 'line_ids':fields.one2many('account.voucher.line','voucher_id','Voucher Lines', readonly=True, states={'draft':[('readonly',False)]}),
213 'line_cr_ids':fields.one2many('account.voucher.line','voucher_id','Credits',
214 domain=[('type','=','cr')], context={'default_type':'cr'}, readonly=True, states={'draft':[('readonly',False)]}),
215 'line_dr_ids':fields.one2many('account.voucher.line','voucher_id','Debits',
216 domain=[('type','=','dr')], context={'default_type':'dr'}, readonly=True, states={'draft':[('readonly',False)]}),
217 'period_id': fields.many2one('account.period', 'Period', required=True, readonly=True, states={'draft':[('readonly',False)]}),
218 'narration':fields.text('Notes', readonly=True, states={'draft':[('readonly',False)]}),
219 #'currency_id':fields.many2one('res.currency', 'Currency', required=True, readonly=True, states={'draft':[('readonly',False)]}),
220 'currency_id': fields.related('journal_id','currency', type='many2one', relation='res.currency', string='Currency', store=True, readonly=True),
221 'company_id': fields.many2one('res.company', 'Company', required=True, readonly=True, states={'draft':[('readonly',False)]}),
222 'state':fields.selection(
224 ('proforma','Pro-forma'),
226 ('cancel','Cancelled')
227 ], 'State', readonly=True, size=32,
228 help=' * The \'Draft\' state is used when a user is encoding a new and unconfirmed Voucher. \
229 \n* The \'Pro-forma\' when voucher is in Pro-forma state,voucher does not have an voucher number. \
230 \n* The \'Posted\' state is used when user create voucher,a voucher number is generated and voucher entries are created in account \
231 \n* The \'Cancelled\' state is used when user cancel voucher.'),
232 'amount': fields.float('Total', digits_compute=dp.get_precision('Account'), required=True, readonly=True, states={'draft':[('readonly',False)]}),
233 'tax_amount':fields.float('Tax Amount', digits_compute=dp.get_precision('Account'), readonly=True, states={'draft':[('readonly',False)]}),
234 'reference': fields.char('Ref #', size=64, readonly=True, states={'draft':[('readonly',False)]}, help="Transaction reference number."),
235 'number': fields.char('Number', size=32, readonly=True,),
236 'move_id':fields.many2one('account.move', 'Account Entry'),
237 'move_ids': fields.related('move_id','line_id', type='one2many', relation='account.move.line', string='Journal Items', readonly=True),
238 'partner_id':fields.many2one('res.partner', 'Partner', change_default=1, readonly=True, states={'draft':[('readonly',False)]}),
239 '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'),
240 'pay_now':fields.selection([
241 ('pay_now','Pay Directly'),
242 ('pay_later','Pay Later or Group Funds'),
243 ],'Payment', select=True, readonly=True, states={'draft':[('readonly',False)]}),
244 'tax_id':fields.many2one('account.tax', 'Tax', readonly=True, states={'draft':[('readonly',False)]}),
245 'pre_line':fields.boolean('Previous Payments ?', required=False),
246 'date_due': fields.date('Due Date', readonly=True, select=True, states={'draft':[('readonly',False)]}),
247 'payment_option':fields.selection([
248 ('without_writeoff', 'Keep Open'),
249 ('with_writeoff', 'Reconcile with Write-Off'),
250 ], 'Payment Difference', required=True, readonly=True, states={'draft': [('readonly', False)]}),
251 'writeoff_acc_id': fields.many2one('account.account', 'Write-Off account', readonly=True, states={'draft': [('readonly', False)]}),
252 'comment': fields.char('Write-Off Comment', size=64, required=True, readonly=True, states={'draft': [('readonly', False)]}),
253 'analytic_id': fields.many2one('account.analytic.account','Write-Off Analytic Account', readonly=True, states={'draft': [('readonly', False)]}),
254 'writeoff_amount': fields.function(_get_writeoff_amount, string='Write-Off Amount', type='float', readonly=True, multi="writeoff"),
255 'currency_rate_difference': fields.function(_get_writeoff_amount, string="Currency Rate Difference", type='float', multi="writeoff"),
258 'period_id': _get_period,
259 'partner_id': _get_partner,
260 'journal_id':_get_journal,
261 'currency_id': _get_currency,
262 'reference': _get_reference,
263 'narration':_get_narration,
264 'amount': _get_amount,
267 'pay_now': 'pay_later',
269 'date': lambda *a: time.strftime('%Y-%m-%d'),
270 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.voucher',context=c),
272 'payment_option': 'without_writeoff',
273 'comment': _('Write-Off'),
276 def compute_tax(self, cr, uid, ids, context=None):
277 tax_pool = self.pool.get('account.tax')
278 partner_pool = self.pool.get('res.partner')
279 position_pool = self.pool.get('account.fiscal.position')
280 voucher_line_pool = self.pool.get('account.voucher.line')
281 voucher_pool = self.pool.get('account.voucher')
282 if context is None: context = {}
284 for voucher in voucher_pool.browse(cr, uid, ids, context=context):
286 for line in voucher.line_ids:
287 voucher_amount += line.untax_amount or line.amount
288 line.amount = line.untax_amount or line.amount
289 voucher_line_pool.write(cr, uid, [line.id], {'amount':line.amount, 'untax_amount':line.untax_amount})
291 if not voucher.tax_id:
292 self.write(cr, uid, [voucher.id], {'amount':voucher_amount, 'tax_amount':0.0})
295 tax = [tax_pool.browse(cr, uid, voucher.tax_id.id, context=context)]
296 partner = partner_pool.browse(cr, uid, voucher.partner_id.id, context=context) or False
297 taxes = position_pool.map_tax(cr, uid, partner and partner.property_account_position or False, tax)
298 tax = tax_pool.browse(cr, uid, taxes, context=context)
300 total = voucher_amount
303 if not tax[0].price_include:
304 for tax_line in tax_pool.compute_all(cr, uid, tax, voucher_amount, 1).get('taxes', []):
305 total_tax += tax_line.get('amount', 0.0)
308 for line in voucher.line_ids:
312 for tax_line in tax_pool.compute_all(cr, uid, tax, line.untax_amount or line.amount, 1).get('taxes', []):
313 line_tax += tax_line.get('amount', 0.0)
314 line_total += tax_line.get('price_unit')
315 total_tax += line_tax
316 untax_amount = line.untax_amount or line.amount
317 voucher_line_pool.write(cr, uid, [line.id], {'amount':line_total, 'untax_amount':untax_amount})
319 self.write(cr, uid, [voucher.id], {'amount':total, 'tax_amount':total_tax})
322 def onchange_price(self, cr, uid, ids, line_ids, tax_id, partner_id=False, context=None):
323 context = context or {}
324 tax_pool = self.pool.get('account.tax')
325 partner_pool = self.pool.get('res.partner')
326 position_pool = self.pool.get('account.fiscal.position')
327 line_pool = self.pool.get('account.voucher.line')
334 line_ids = resolve_o2m_operations(cr, uid, line_pool, line_ids, ["amount"], context)
338 for line in line_ids:
340 line_amount = line.get('amount',0.0)
341 voucher_total += line_amount
343 total = voucher_total
346 tax = [tax_pool.browse(cr, uid, tax_id, context=context)]
348 partner = partner_pool.browse(cr, uid, partner_id, context=context) or False
349 taxes = position_pool.map_tax(cr, uid, partner and partner.property_account_position or False, tax)
350 tax = tax_pool.browse(cr, uid, taxes, context=context)
352 if not tax[0].price_include:
353 for tax_line in tax_pool.compute_all(cr, uid, tax, voucher_total, 1).get('taxes', []):
354 total_tax += tax_line.get('amount')
358 'amount':total or voucher_total,
359 'tax_amount':total_tax
365 def onchange_term_id(self, cr, uid, ids, term_id, amount):
366 term_pool = self.pool.get('account.payment.term')
369 default = {'date_due':False}
370 if term_id and amount:
371 terms = term_pool.compute(cr, uid, term_id, amount)
373 due_date = terms[-1][0]
377 return {'value':default}
379 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):
381 Returns a dict that contains new values and context
383 @param partner_id: latest value from user input for field partner_id
384 @param args: other arguments
385 @param context: context arguments, like lang, time zone
387 @return: Returns a dict which contains new values, and context
393 if not partner_id or not journal_id:
396 partner_pool = self.pool.get('res.partner')
397 journal_pool = self.pool.get('account.journal')
399 journal = journal_pool.browse(cr, uid, journal_id, context=context)
400 partner = partner_pool.browse(cr, uid, partner_id, context=context)
403 if journal.type in ('sale','sale_refund'):
404 account_id = partner.property_account_receivable.id
406 elif journal.type in ('purchase', 'purchase_refund','expense'):
407 account_id = partner.property_account_payable.id
410 if not journal.default_credit_account_id or not journal.default_debit_account_id:
411 raise osv.except_osv(_('Error !'), _('Please define default credit/debit account on the %s !') % (journal.name))
412 account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
415 default['value']['account_id'] = account_id
416 default['value']['type'] = ttype or tr_type
418 vals = self.onchange_journal(cr, uid, ids, journal_id, line_ids, tax_id, partner_id, context)
419 default['value'].update(vals.get('value'))
423 def onchange_partner_id(self, cr, uid, ids, partner_id, journal_id, price, currency_id, ttype, date, context=None):
425 Returns a dict that contains new values and context
427 @param partner_id: latest value from user input for field partner_id
428 @param args: other arguments
429 @param context: context arguments, like lang, time zone
431 @return: Returns a dict which contains new values, and context
437 context_multi_currency = context.copy()
439 context_multi_currency.update({'date': date})
441 line_pool = self.pool.get('account.voucher.line')
442 line_ids = ids and line_pool.search(cr, uid, [('voucher_id', '=', ids[0])]) or False
444 line_pool.unlink(cr, uid, line_ids)
446 currency_pool = self.pool.get('res.currency')
447 move_line_pool = self.pool.get('account.move.line')
448 partner_pool = self.pool.get('res.partner')
449 journal_pool = self.pool.get('account.journal')
451 vals = self.onchange_journal(cr, uid, ids, journal_id, [], False, partner_id, context)
452 vals = vals.get('value')
453 currency_id = vals.get('currency_id', currency_id)
455 'value':{'line_ids':[], 'line_dr_ids':[], 'line_cr_ids':[], 'pre_line': False, 'currency_id':currency_id},
461 if not partner_id and ids:
462 line_ids = line_pool.search(cr, uid, [('voucher_id', '=', ids[0])])
464 line_pool.unlink(cr, uid, line_ids)
467 journal = journal_pool.browse(cr, uid, journal_id, context=context)
468 partner = partner_pool.browse(cr, uid, partner_id, context=context)
470 if journal.type in ('sale','sale_refund'):
471 account_id = partner.property_account_receivable.id
472 elif journal.type in ('purchase', 'purchase_refund','expense'):
473 account_id = partner.property_account_payable.id
475 account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
477 default['value']['account_id'] = account_id
479 if journal.type not in ('cash', 'bank'):
484 account_type = 'receivable'
485 if ttype == 'payment':
486 account_type = 'payable'
487 total_debit = price or 0.0
489 total_credit = price or 0.0
490 account_type = 'receivable'
492 if not context.get('move_line_ids', False):
493 ids = move_line_pool.search(cr, uid, [('state','=','valid'), ('account_id.type', '=', account_type), ('reconcile_id', '=', False), ('partner_id', '=', partner_id)], context=context)
495 ids = context['move_line_ids']
497 moves = move_line_pool.browse(cr, uid, ids, context=context)
499 company_currency = journal.company_id.currency_id.id
500 if company_currency != currency_id and ttype == 'payment':
501 total_debit = currency_pool.compute(cr, uid, currency_id, company_currency, total_debit, context=context_multi_currency)
502 elif company_currency != currency_id and ttype == 'receipt':
503 total_credit = currency_pool.compute(cr, uid, currency_id, company_currency, total_credit, context=context_multi_currency)
506 if line.credit and line.reconcile_partial_id and ttype == 'receipt':
508 if line.debit and line.reconcile_partial_id and ttype == 'payment':
510 total_credit += line.credit or 0.0
511 total_debit += line.debit or 0.0
513 if line.credit and line.reconcile_partial_id and ttype == 'receipt':
515 if line.debit and line.reconcile_partial_id and ttype == 'payment':
517 original_amount = line.credit or line.debit or 0.0
518 amount_original, amount_unreconciled = line_pool._get_amounts(cr, uid, line, context=context)
519 currency_id = line.currency_id and line.currency_id.id or line.company_id.currency_id.id
521 'name':line.move_id.name,
522 'type': line.credit and 'dr' or 'cr',
523 'move_line_id':line.id,
524 'account_id':line.account_id.id,
525 'amount_original': amount_original,
527 'currency_id': currency_id,
528 'date_original':line.date,
529 'company_currency_id': line.company_id.currency_id.id,
530 'date_due':line.date_maturity,
531 'amount_unreconciled': amount_unreconciled,
535 # amount = min(amount_unreconciled, currency_pool.compute(cr, uid, company_currency, currency_id, abs(total_debit), context=context_multi_currency))
536 # rs['amount'] = amount
537 # total_debit -= amount
539 # amount = min(amount_unreconciled, currency_pool.compute(cr, uid, company_currency, currency_id, abs(total_credit), context=context_multi_currency))
540 # rs['amount'] = amount
541 # total_credit -= amount
543 default['value']['line_ids'].append(rs)
544 if rs['type'] == 'cr':
545 default['value']['line_cr_ids'].append(rs)
547 default['value']['line_dr_ids'].append(rs)
549 if ttype == 'payment' and len(default['value']['line_cr_ids']) > 0:
550 default['value']['pre_line'] = 1
551 elif ttype == 'receipt' and len(default['value']['line_dr_ids']) > 0:
552 default['value']['pre_line'] = 1
553 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, context=context)
556 def onchange_date(self, cr, uid, ids, partner_id, journal_id, price, currency_id, ttype, date, context=None):
558 @param date: latest value from user input for field date
559 @param args: other arguments
560 @param context: context arguments, like lang, time zone
561 @return: Returns a dict which contains new values, and context
563 period_pool = self.pool.get('account.period')
564 res = self.onchange_partner_id(cr, uid, ids, partner_id, journal_id, price, currency_id, ttype, date, context=context)
565 pids = period_pool.search(cr, uid, [('date_start', '<=', date), ('date_stop', '>=', date)])
567 if not 'value' in res:
569 res['value'].update({'period_id':pids[0]})
572 def onchange_journal(self, cr, uid, ids, journal_id, line_ids, tax_id, partner_id, context=None):
575 journal_pool = self.pool.get('account.journal')
576 journal = journal_pool.browse(cr, uid, journal_id, context=context)
577 account_id = journal.default_credit_account_id or journal.default_debit_account_id
579 if account_id and account_id.tax_ids:
580 tax_id = account_id.tax_ids[0].id
582 vals = self.onchange_price(cr, uid, ids, line_ids, tax_id, partner_id, context)
583 vals['value'].update({'tax_id':tax_id})
584 currency_id = journal.company_id.currency_id.id
586 currency_id = journal.currency.id
587 vals['value'].update({'currency_id':currency_id})
590 def proforma_voucher(self, cr, uid, ids, context=None):
591 self.action_move_line_create(cr, uid, ids, context=context)
594 def action_cancel_draft(self, cr, uid, ids, context=None):
595 wf_service = netsvc.LocalService("workflow")
596 for voucher_id in ids:
597 wf_service.trg_create(uid, 'account.voucher', voucher_id, cr)
598 self.write(cr, uid, ids, {'state':'draft'})
601 def cancel_voucher(self, cr, uid, ids, context=None):
602 reconcile_pool = self.pool.get('account.move.reconcile')
603 move_pool = self.pool.get('account.move')
605 for voucher in self.browse(cr, uid, ids, context=context):
607 for line in voucher.move_ids:
608 if line.reconcile_id:
609 recs += [line.reconcile_id.id]
610 if line.reconcile_partial_id:
611 recs += [line.reconcile_partial_id.id]
613 reconcile_pool.unlink(cr, uid, recs)
616 move_pool.button_cancel(cr, uid, [voucher.move_id.id])
617 move_pool.unlink(cr, uid, [voucher.move_id.id])
622 self.write(cr, uid, ids, res)
625 def unlink(self, cr, uid, ids, context=None):
626 for t in self.read(cr, uid, ids, ['state'], context=context):
627 if t['state'] not in ('draft', 'cancel'):
628 raise osv.except_osv(_('Invalid action !'), _('Cannot delete Voucher(s) which are already opened or paid !'))
629 return super(account_voucher, self).unlink(cr, uid, ids, context=context)
631 # TODO: may be we can remove this method if not used anyware
632 def onchange_payment(self, cr, uid, ids, pay_now, journal_id, partner_id, ttype='sale'):
636 res = {'account_id':False}
637 partner_pool = self.pool.get('res.partner')
638 journal_pool = self.pool.get('account.journal')
639 if pay_now == 'pay_later':
640 partner = partner_pool.browse(cr, uid, partner_id)
641 journal = journal_pool.browse(cr, uid, journal_id)
642 if journal.type in ('sale','sale_refund'):
643 account_id = partner.property_account_receivable.id
644 elif journal.type in ('purchase', 'purchase_refund','expense'):
645 account_id = partner.property_account_payable.id
647 account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
648 res['account_id'] = account_id
651 def action_move_line_create(self, cr, uid, ids, context=None):
653 def _get_payment_term_lines(term_id, amount):
654 term_pool = self.pool.get('account.payment.term')
655 if term_id and amount:
656 terms = term_pool.compute(cr, uid, term_id, amount)
661 move_pool = self.pool.get('account.move')
662 move_line_pool = self.pool.get('account.move.line')
663 currency_pool = self.pool.get('res.currency')
664 tax_obj = self.pool.get('account.tax')
665 seq_obj = self.pool.get('ir.sequence')
666 for voucher in self.browse(cr, uid, ids, context=context):
669 context_multi_currency = context.copy()
670 context_multi_currency.update({'date': voucher.date})
673 name = voucher.number
675 name = seq_obj.get_id(cr, uid, voucher.journal_id.sequence_id.id)
676 if not voucher.reference:
677 ref = name.replace('/','')
679 ref = voucher.reference
683 'journal_id': voucher.journal_id.id,
684 'narration': voucher.narration,
685 'date': voucher.date,
687 'period_id': voucher.period_id and voucher.period_id.id or False
689 move_id = move_pool.create(cr, uid, move)
691 #create the first line manually
692 company_currency = voucher.journal_id.company_id.currency_id.id
693 current_currency = voucher.currency_id.id
696 # TODO: is there any other alternative then the voucher type ??
697 # -for sale, purchase we have but for the payment and receipt we do not have as based on the bank/cash journal we can not know its payment or receipt
698 if voucher.type in ('purchase', 'payment'):
699 credit = currency_pool.compute(cr, uid, current_currency, company_currency, voucher.amount, context=context_multi_currency)
700 elif voucher.type in ('sale', 'receipt'):
701 debit = currency_pool.compute(cr, uid, current_currency, company_currency, voucher.amount, context=context_multi_currency)
708 sign = debit - credit < 0 and -1 or 1
709 #create the first line of the voucher
711 'name': voucher.name or '/',
714 'account_id': voucher.account_id.id,
716 'journal_id': voucher.journal_id.id,
717 'period_id': voucher.period_id.id,
718 'partner_id': voucher.partner_id.id,
719 'currency_id': company_currency <> current_currency and current_currency or False,
720 'amount_currency': company_currency <> current_currency and sign * voucher.amount or 0.0,
721 'date': voucher.date,
722 'date_maturity': voucher.date_due
724 move_line_pool.create(cr, uid, move_line)
726 line_total = debit - credit
727 if voucher.type == 'sale':
728 line_total = line_total - currency_pool.compute(cr, uid, voucher.currency_id.id, company_currency, voucher.tax_amount, context=context_multi_currency)
729 elif voucher.type == 'purchase':
730 line_total = line_total + currency_pool.compute(cr, uid, voucher.currency_id.id, company_currency, voucher.tax_amount, context=context_multi_currency)
732 for line in voucher.line_ids:
733 #create one move line per voucher line where amount is not 0.0
736 #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
737 if line.amount == line.amount_unreconciled:
738 amount = line.move_line_id.amount_residual #residual amount in company currency
740 ctx = context_multi_currency.copy()
741 ctx.update({'date': line.date_original})
742 amount = currency_pool.compute(cr, uid, current_currency, company_currency, line.untax_amount or line.amount, context=ctx)
744 'journal_id': voucher.journal_id.id,
745 'period_id': voucher.period_id.id,
746 'name': line.name or '/',
747 'account_id': line.account_id.id,
749 'partner_id': voucher.partner_id.id,
750 'currency_id': company_currency <> current_currency and current_currency or False,
751 'analytic_account_id': line.account_analytic_id and line.account_analytic_id.id or False,
757 #TODO: assigner le montant de la diff de change sur le bon compte et pas debtor
758 #TODO: mettre le montant de company currency en onchange + readonly + computed
759 #TODO: mettre un champ difference de change sur le voucher
762 if line.type == 'dr':
766 if (line.type=='dr'):
768 move_line['debit'] = amount
771 move_line['credit'] = amount
773 if voucher.tax_id and voucher.type in ('sale', 'purchase'):
775 'account_tax_id': voucher.tax_id.id,
777 if move_line.get('account_tax_id', False):
778 tax_data = tax_obj.browse(cr, uid, [move_line['account_tax_id']], context=context)[0]
779 if not (tax_data.base_code_id and tax_data.tax_code_id):
780 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))
781 sign = (move_line['debit'] - move_line['credit']) < 0 and -1 or 1
782 move_line['amount_currency'] = company_currency <> current_currency and sign * line.amount or 0.0
783 voucher_line = move_line_pool.create(cr, uid, move_line)
784 if line.move_line_id.id:
785 rec_ids = [voucher_line, line.move_line_id.id]
786 rec_list_ids.append(rec_ids)
788 if not currency_pool.is_zero(cr, uid, voucher.currency_id, line_total):
792 if voucher.payment_option == 'with_writeoff':
793 account_id = voucher.writeoff_acc_id.id
794 write_off_name = voucher.comment
795 elif voucher.type in ('sale', 'receipt'):
796 account_id = voucher.partner_id.property_account_receivable.id
798 account_id = voucher.partner_id.property_account_payable.id
800 'name': write_off_name or name,
801 'account_id': account_id,
803 'partner_id': voucher.partner_id.id,
804 'date': voucher.date,
805 'credit': diff > 0 and diff or 0.0,
806 'debit': diff < 0 and -diff or 0.0,
807 #'amount_currency': company_currency <> current_currency and currency_pool.compute(cr, uid, company_currency, current_currency, diff * -1, context=context_multi_currency) or 0.0,
808 #'currency_id': company_currency <> current_currency and current_currency or False,
810 move_line_pool.create(cr, uid, move_line)
811 self.write(cr, uid, [voucher.id], {
816 if voucher.journal_id.entry_posted:
817 move_pool.post(cr, uid, [move_id], context={})
818 for rec_ids in rec_list_ids:
819 if len(rec_ids) >= 2:
820 move_line_pool.reconcile_partial(cr, uid, rec_ids)
823 def copy(self, cr, uid, id, default={}, context=None):
828 'line_cr_ids': False,
829 'line_dr_ids': False,
832 if 'date' not in default:
833 default['date'] = time.strftime('%Y-%m-%d')
834 return super(account_voucher, self).copy(cr, uid, id, default, context)
838 class account_voucher_line(osv.osv):
839 _name = 'account.voucher.line'
840 _description = 'Voucher Lines'
841 _order = "move_line_id"
843 def _currency_id(self, cr, uid, ids, name, args, context=None):
845 for line in self.browse(cr, uid, ids, context=context):
846 move_line = line.move_line_id
847 res[line.id] = move_line.currency_id and move_line.currency_id.id or move_line.company_id.currency_id.id
850 def _get_amounts(self, cr, uid, line_browse_rec, context=None):
851 if line_browse_rec.currency_id:
852 amount_original = line_browse_rec.amount_currency or 0.0
853 amount_unreconciled = line_browse_rec.amount_residual_currency
854 elif line_browse_rec.credit > 0:
855 amount_original = line_browse_rec.credit or 0.0
856 amount_unreconciled = line_browse_rec.amount_residual
858 amount_original = line_browse_rec.debit or 0.0
859 amount_unreconciled = line_browse_rec.amount_residual
860 return amount_original, amount_unreconciled
862 def _compute_balance(self, cr, uid, ids, name, args, context=None):
863 currency_pool = self.pool.get('res.currency')
865 for line in self.browse(cr, uid, ids, context=context):
866 amount_original, amount_unreconciled = self._get_amounts(cr, uid, line.move_line_id, context)
868 'amount_original': amount_original,
869 'amount_unreconciled': amount_unreconciled,
874 def __company_currency_amount(self, cr, uid, line, amount, context=None):
878 ctx.update({'date': line.date_original})
879 currency_pool = self.pool.get('res.currency')
880 return currency_pool.compute(cr, uid, line.currency_id.id, line.company_currency_id.id, amount, context=ctx)
882 def onchange_amount(self, cr, uid, ids, amount, context=None):
884 return {'value':{'amount_in_company_currency': 0.0}}
885 for line in self.browse(cr, uid, ids, context=context):
886 amount = self.__company_currency_amount(cr, uid, line, amount, context=context)
887 return {'value': {'amount_in_company_currency': amount}}
889 def _get_amount_in_company_currency(self, cr, uid, ids, name, args, context=None):
891 for line in self.browse(cr, uid, ids, context=context):
892 res[line.id] = self.__company_currency_amount(cr, uid, line, line.amount, context=context)
896 'voucher_id':fields.many2one('account.voucher', 'Voucher', required=1, ondelete='cascade'),
897 'name':fields.char('Description', size=256),
898 'account_id':fields.many2one('account.account','Account', required=True),
899 'partner_id':fields.related('voucher_id', 'partner_id', type='many2one', relation='res.partner', string='Partner'),
900 'currency_id': fields.function(_currency_id, string='Currency', type='many2one', relation='res.currency'),
901 'untax_amount':fields.float('Untax Amount'),
902 'amount':fields.float('Amount', digits_compute=dp.get_precision('Account')),
903 'type':fields.selection([('dr','Debit'),('cr','Credit')], 'Dr/Cr'),
904 'account_analytic_id': fields.many2one('account.analytic.account', 'Analytic Account'),
905 'move_line_id': fields.many2one('account.move.line', 'Journal Item', required=True),
906 'company_currency_id': fields.related('move_line_id','company_id','currency_id', type='many2one', relation='res.currency', string="Company Currency"),
907 'amount_in_company_currency': fields.function(_get_amount_in_company_currency, string='Amount in Company Currency', type='float', digits_compute=dp.get_precision('Account')),
908 'date_original': fields.related('move_line_id','date', type='date', relation='account.move.line', string='Date', readonly=1),
909 'date_due': fields.related('move_line_id','date_maturity', type='date', relation='account.move.line', string='Due Date', readonly=1),
910 'amount_original': fields.function(_compute_balance, multi='dc', type='float', string='Original Amount', store=True),
911 'amount_unreconciled': fields.function(_compute_balance, multi='dc', type='float', string='Open Balance', store=True),
912 'company_id': fields.related('voucher_id','company_id', relation='res.company', type='many2one', string='Company', store=True, readonly=True),
918 def onchange_move_line_id(self, cr, user, ids, move_line_id, context=None):
920 Returns a dict that contains new values and context
922 @param move_line_id: latest value from user input for field move_line_id
923 @param args: other arguments
924 @param context: context arguments, like lang, time zone
926 @return: Returns a dict which contains new values, and context
929 move_line_pool = self.pool.get('account.move.line')
931 move_line = move_line_pool.browse(cr, user, move_line_id, context=context)
936 account_id = move_line.account_id.id
938 'account_id':account_id,
945 def default_get(self, cr, user, fields_list, context=None):
947 Returns default values for fields
948 @param fields_list: list of fields, for which default values are required to be read
949 @param context: context arguments, like lang, time zone
951 @return: Returns a dict that contains default values for fields
955 journal_id = context.get('journal_id', False)
956 partner_id = context.get('partner_id', False)
957 journal_pool = self.pool.get('account.journal')
958 partner_pool = self.pool.get('res.partner')
959 values = super(account_voucher_line, self).default_get(cr, user, fields_list, context=context)
960 if (not journal_id) or ('account_id' not in fields_list):
962 journal = journal_pool.browse(cr, user, journal_id, context=context)
965 if journal.type in ('sale', 'sale_refund'):
966 account_id = journal.default_credit_account_id and journal.default_credit_account_id.id or False
968 elif journal.type in ('purchase', 'expense', 'purchase_refund'):
969 account_id = journal.default_debit_account_id and journal.default_debit_account_id.id or False
972 partner = partner_pool.browse(cr, user, partner_id, context=context)
973 if context.get('type') == 'payment':
975 account_id = partner.property_account_payable.id
976 elif context.get('type') == 'receipt':
977 account_id = partner.property_account_receivable.id
980 'account_id':account_id,
984 account_voucher_line()
986 class account_bank_statement(osv.osv):
987 _inherit = 'account.bank.statement'
989 def button_cancel(self, cr, uid, ids, context=None):
990 voucher_obj = self.pool.get('account.voucher')
991 for st in self.browse(cr, uid, ids, context=context):
993 for line in st.line_ids:
995 voucher_ids.append(line.voucher_id.id)
996 voucher_obj.cancel_voucher(cr, uid, voucher_ids, context)
997 return super(account_bank_statement, self).button_cancel(cr, uid, ids, context=context)
999 def create_move_from_st_line(self, cr, uid, st_line_id, company_currency_id, next_number, context=None):
1000 voucher_obj = self.pool.get('account.voucher')
1001 wf_service = netsvc.LocalService("workflow")
1002 move_line_obj = self.pool.get('account.move.line')
1003 bank_st_line_obj = self.pool.get('account.bank.statement.line')
1004 st_line = bank_st_line_obj.browse(cr, uid, st_line_id, context=context)
1005 if st_line.voucher_id:
1006 voucher_obj.write(cr, uid, [st_line.voucher_id.id], {'number': next_number}, context=context)
1007 if st_line.voucher_id.state == 'cancel':
1008 voucher_obj.action_cancel_draft(cr, uid, [st_line.voucher_id.id], context=context)
1009 wf_service.trg_validate(uid, 'account.voucher', st_line.voucher_id.id, 'proforma_voucher', cr)
1011 v = voucher_obj.browse(cr, uid, st_line.voucher_id.id, context=context)
1012 bank_st_line_obj.write(cr, uid, [st_line_id], {
1013 'move_ids': [(4, v.move_id.id, False)]
1016 return move_line_obj.write(cr, uid, [x.id for x in v.move_ids], {'statement_id': st_line.statement_id.id}, context=context)
1017 return super(account_bank_statement, self).create_move_from_st_line(cr, uid, st_line.id, company_currency_id, next_number, context=context)
1019 account_bank_statement()
1021 class account_bank_statement_line(osv.osv):
1022 _inherit = 'account.bank.statement.line'
1024 def _amount_reconciled(self, cursor, user, ids, name, args, context=None):
1029 # company_currency_id = False
1030 for line in self.browse(cursor, user, ids, context=context):
1031 # if not company_currency_id:
1032 # company_currency_id = line.company_id.id
1034 res[line.id] = line.voucher_id.amount#
1035 # res_currency_obj.compute(cursor, user,
1036 # company_currency_id, line.statement_id.currency.id,
1037 # line.voucher_id.amount, context=context)
1042 def _check_amount(self, cr, uid, ids, context=None):
1043 for obj in self.browse(cr, uid, ids, context=context):
1045 diff = abs(obj.amount) - obj.voucher_id.amount
1046 if not self.pool.get('res.currency').is_zero(cr, uid, obj.voucher_id.currency_id, diff):
1051 (_check_amount, 'The amount of the voucher must be the same amount as the one on the statement line', ['amount']),
1055 'amount_reconciled': fields.function(_amount_reconciled,
1056 string='Amount reconciled', type='float'),
1057 'voucher_id': fields.many2one('account.voucher', 'Payment'),
1061 def unlink(self, cr, uid, ids, context=None):
1062 voucher_obj = self.pool.get('account.voucher')
1063 statement_line = self.browse(cr, uid, ids, context=context)
1065 for st_line in statement_line:
1066 if st_line.voucher_id:
1067 unlink_ids.append(st_line.voucher_id.id)
1068 voucher_obj.unlink(cr, uid, unlink_ids, context=context)
1069 return super(account_bank_statement_line, self).unlink(cr, uid, ids, context=context)
1071 account_bank_statement_line()
1073 def resolve_o2m_operations(cr, uid, target_osv, operations, fields, context):
1075 for operation in operations:
1077 if not isinstance(operation, (list, tuple)):
1078 result = target_osv.read(cr, uid, operation, fields, context=context)
1079 elif operation[0] == 0:
1080 # may be necessary to check if all the fields are here and get the default values?
1081 result = operation[2]
1082 elif operation[0] == 1:
1083 result = target_osv.read(cr, uid, operation[1], fields, context=context)
1084 result.update(operation[2])
1085 elif operation[0] == 4:
1086 result = target_osv.read(cr, uid, operation[1], fields, context=context)
1088 results.append(result)
1091 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: