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):
147 for l in line_dr_ids:
149 for l in line_cr_ids:
150 credit += l['amount']
151 return abs(amount - abs(credit - debit))
153 def onchange_line_ids(self, cr, uid, ids, line_dr_ids, line_cr_ids, amount, context=None):
154 context = context or {}
155 if not line_dr_ids and not line_cr_ids:
157 line_osv = self.pool.get("account.voucher.line")
158 line_dr_ids = resolve_o2m_operations(cr, uid, line_osv, line_dr_ids, ['amount'], context)
159 line_cr_ids = resolve_o2m_operations(cr, uid, line_osv, line_cr_ids, ['amount'], context)
160 return {'value': {'writeoff_amount': self._compute_writeoff_amount(cr, uid, line_dr_ids, line_cr_ids, amount)}}
162 def _get_writeoff_amount(self, cr, uid, ids, name, args, context=None):
163 if not ids: return {}
166 for voucher in self.browse(cr, uid, ids, context=context):
167 for l in voucher.line_dr_ids:
169 for l in voucher.line_cr_ids:
171 res[voucher.id] = abs(voucher.amount - abs(credit - debit))
174 _name = 'account.voucher'
175 _description = 'Accounting Voucher'
176 _order = "date desc, id desc"
177 # _rec_name = 'number'
179 'type':fields.selection([
181 ('purchase','Purchase'),
182 ('payment','Payment'),
183 ('receipt','Receipt'),
184 ],'Default Type', readonly=True, states={'draft':[('readonly',False)]}),
185 'name':fields.char('Memo', size=256, readonly=True, states={'draft':[('readonly',False)]}),
186 'date':fields.date('Date', readonly=True, select=True, states={'draft':[('readonly',False)]}, help="Effective date for accounting entries"),
187 'journal_id':fields.many2one('account.journal', 'Journal', required=True, readonly=True, states={'draft':[('readonly',False)]}),
188 'account_id':fields.many2one('account.account', 'Account', required=True, readonly=True, states={'draft':[('readonly',False)]}),
189 'line_ids':fields.one2many('account.voucher.line','voucher_id','Voucher Lines', readonly=True, states={'draft':[('readonly',False)]}),
190 'line_cr_ids':fields.one2many('account.voucher.line','voucher_id','Credits',
191 domain=[('type','=','cr')], context={'default_type':'cr'}, readonly=True, states={'draft':[('readonly',False)]}),
192 'line_dr_ids':fields.one2many('account.voucher.line','voucher_id','Debits',
193 domain=[('type','=','dr')], context={'default_type':'dr'}, readonly=True, states={'draft':[('readonly',False)]}),
194 'period_id': fields.many2one('account.period', 'Period', required=True, readonly=True, states={'draft':[('readonly',False)]}),
195 'narration':fields.text('Notes', readonly=True, states={'draft':[('readonly',False)]}),
196 'currency_id':fields.many2one('res.currency', 'Currency', required=True, readonly=True, states={'draft':[('readonly',False)]}),
197 # 'currency_id': fields.related('journal_id','currency', type='many2one', relation='res.currency', string='Currency', store=True, readonly=True, states={'draft':[('readonly',False)]}),
198 'company_id': fields.many2one('res.company', 'Company', required=True, readonly=True, states={'draft':[('readonly',False)]}),
199 'state':fields.selection(
201 ('proforma','Pro-forma'),
203 ('cancel','Cancelled')
204 ], 'State', readonly=True, size=32,
205 help=' * The \'Draft\' state is used when a user is encoding a new and unconfirmed Voucher. \
206 \n* The \'Pro-forma\' when voucher is in Pro-forma state,voucher does not have an voucher number. \
207 \n* The \'Posted\' state is used when user create voucher,a voucher number is generated and voucher entries are created in account \
208 \n* The \'Cancelled\' state is used when user cancel voucher.'),
209 'amount': fields.float('Total', digits_compute=dp.get_precision('Account'), required=True, readonly=True, states={'draft':[('readonly',False)]}),
210 'tax_amount':fields.float('Tax Amount', digits_compute=dp.get_precision('Account'), readonly=True, states={'draft':[('readonly',False)]}),
211 'reference': fields.char('Ref #', size=64, readonly=True, states={'draft':[('readonly',False)]}, help="Transaction reference number."),
212 'number': fields.char('Number', size=32, readonly=True,),
213 'move_id':fields.many2one('account.move', 'Account Entry'),
214 'move_ids': fields.related('move_id','line_id', type='one2many', relation='account.move.line', string='Journal Items', readonly=True),
215 'partner_id':fields.many2one('res.partner', 'Partner', change_default=1, readonly=True, states={'draft':[('readonly',False)]}),
216 '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'),
217 'pay_now':fields.selection([
218 ('pay_now','Pay Directly'),
219 ('pay_later','Pay Later or Group Funds'),
220 ],'Payment', select=True, readonly=True, states={'draft':[('readonly',False)]}),
221 'tax_id':fields.many2one('account.tax', 'Tax', readonly=True, states={'draft':[('readonly',False)]}),
222 'pre_line':fields.boolean('Previous Payments ?', required=False),
223 'date_due': fields.date('Due Date', readonly=True, select=True, states={'draft':[('readonly',False)]}),
224 'payment_option':fields.selection([
225 ('without_writeoff', 'Keep Open'),
226 ('with_writeoff', 'Reconcile with Write-Off'),
227 ], 'Payment Difference', required=True, readonly=True, states={'draft': [('readonly', False)]}),
228 'writeoff_acc_id': fields.many2one('account.account', 'Write-Off account', readonly=True, states={'draft': [('readonly', False)]}),
229 'comment': fields.char('Write-Off Comment', size=64, required=True, readonly=True, states={'draft': [('readonly', False)]}),
230 'analytic_id': fields.many2one('account.analytic.account','Write-Off Analytic Account', readonly=True, states={'draft': [('readonly', False)]}),
231 'writeoff_amount': fields.function(_get_writeoff_amount, string='Write-Off Amount', type='float', readonly=True),
234 'period_id': _get_period,
235 'partner_id': _get_partner,
236 'journal_id':_get_journal,
237 'currency_id': _get_currency,
238 'reference': _get_reference,
239 'narration':_get_narration,
240 'amount': _get_amount,
243 'pay_now': 'pay_later',
245 'date': lambda *a: time.strftime('%Y-%m-%d'),
246 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.voucher',context=c),
248 'payment_option': 'without_writeoff',
249 'comment': _('Write-Off'),
252 def compute_tax(self, cr, uid, ids, context=None):
253 tax_pool = self.pool.get('account.tax')
254 partner_pool = self.pool.get('res.partner')
255 position_pool = self.pool.get('account.fiscal.position')
256 voucher_line_pool = self.pool.get('account.voucher.line')
257 voucher_pool = self.pool.get('account.voucher')
258 if context is None: context = {}
260 for voucher in voucher_pool.browse(cr, uid, ids, context=context):
262 for line in voucher.line_ids:
263 voucher_amount += line.untax_amount or line.amount
264 line.amount = line.untax_amount or line.amount
265 voucher_line_pool.write(cr, uid, [line.id], {'amount':line.amount, 'untax_amount':line.untax_amount})
267 if not voucher.tax_id:
268 self.write(cr, uid, [voucher.id], {'amount':voucher_amount, 'tax_amount':0.0})
271 tax = [tax_pool.browse(cr, uid, voucher.tax_id.id, context=context)]
272 partner = partner_pool.browse(cr, uid, voucher.partner_id.id, context=context) or False
273 taxes = position_pool.map_tax(cr, uid, partner and partner.property_account_position or False, tax)
274 tax = tax_pool.browse(cr, uid, taxes, context=context)
276 total = voucher_amount
279 if not tax[0].price_include:
280 for tax_line in tax_pool.compute_all(cr, uid, tax, voucher_amount, 1).get('taxes', []):
281 total_tax += tax_line.get('amount', 0.0)
284 for line in voucher.line_ids:
288 for tax_line in tax_pool.compute_all(cr, uid, tax, line.untax_amount or line.amount, 1).get('taxes', []):
289 line_tax += tax_line.get('amount', 0.0)
290 line_total += tax_line.get('price_unit')
291 total_tax += line_tax
292 untax_amount = line.untax_amount or line.amount
293 voucher_line_pool.write(cr, uid, [line.id], {'amount':line_total, 'untax_amount':untax_amount})
295 self.write(cr, uid, [voucher.id], {'amount':total, 'tax_amount':total_tax})
298 def onchange_price(self, cr, uid, ids, line_ids, tax_id, partner_id=False, context=None):
299 context = context or {}
300 tax_pool = self.pool.get('account.tax')
301 partner_pool = self.pool.get('res.partner')
302 position_pool = self.pool.get('account.fiscal.position')
303 line_pool = self.pool.get('account.voucher.line')
310 line_ids = resolve_o2m_operations(cr, uid, line_pool, line_ids, ["amount"], context)
314 for line in line_ids:
316 line_amount = line.get('amount',0.0)
317 voucher_total += line_amount
319 total = voucher_total
322 tax = [tax_pool.browse(cr, uid, tax_id, context=context)]
324 partner = partner_pool.browse(cr, uid, partner_id, context=context) or False
325 taxes = position_pool.map_tax(cr, uid, partner and partner.property_account_position or False, tax)
326 tax = tax_pool.browse(cr, uid, taxes, context=context)
328 if not tax[0].price_include:
329 for tax_line in tax_pool.compute_all(cr, uid, tax, voucher_total, 1).get('taxes', []):
330 total_tax += tax_line.get('amount')
334 'amount':total or voucher_total,
335 'tax_amount':total_tax
341 def onchange_term_id(self, cr, uid, ids, term_id, amount):
342 term_pool = self.pool.get('account.payment.term')
345 default = {'date_due':False}
346 if term_id and amount:
347 terms = term_pool.compute(cr, uid, term_id, amount)
349 due_date = terms[-1][0]
353 return {'value':default}
355 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):
357 Returns a dict that contains new values and context
359 @param partner_id: latest value from user input for field partner_id
360 @param args: other arguments
361 @param context: context arguments, like lang, time zone
363 @return: Returns a dict which contains new values, and context
369 if not partner_id or not journal_id:
372 partner_pool = self.pool.get('res.partner')
373 journal_pool = self.pool.get('account.journal')
375 journal = journal_pool.browse(cr, uid, journal_id, context=context)
376 partner = partner_pool.browse(cr, uid, partner_id, context=context)
379 if journal.type in ('sale','sale_refund'):
380 account_id = partner.property_account_receivable.id
382 elif journal.type in ('purchase', 'purchase_refund','expense'):
383 account_id = partner.property_account_payable.id
386 if not journal.default_credit_account_id or not journal.default_debit_account_id:
387 raise osv.except_osv(_('Error !'), _('Please define default credit/debit account on the %s !') % (journal.name))
388 account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
391 default['value']['account_id'] = account_id
392 default['value']['type'] = ttype or tr_type
394 vals = self.onchange_journal(cr, uid, ids, journal_id, line_ids, tax_id, partner_id, context)
395 default['value'].update(vals.get('value'))
399 def onchange_partner_id(self, cr, uid, ids, partner_id, journal_id, price, currency_id, ttype, date, context=None):
401 Returns a dict that contains new values and context
403 @param partner_id: latest value from user input for field partner_id
404 @param args: other arguments
405 @param context: context arguments, like lang, time zone
407 @return: Returns a dict which contains new values, and context
413 context_multi_currency = context.copy()
415 context_multi_currency.update({'date': date})
417 line_pool = self.pool.get('account.voucher.line')
418 line_ids = ids and line_pool.search(cr, uid, [('voucher_id', '=', ids[0])]) or False
420 line_pool.unlink(cr, uid, line_ids)
422 currency_pool = self.pool.get('res.currency')
423 move_line_pool = self.pool.get('account.move.line')
424 partner_pool = self.pool.get('res.partner')
425 journal_pool = self.pool.get('account.journal')
427 vals = self.onchange_journal(cr, uid, ids, journal_id, [], False, partner_id, context)
428 vals = vals.get('value')
429 currency_id = vals.get('currency_id', currency_id)
431 'value':{'line_ids':[], 'line_dr_ids':[], 'line_cr_ids':[], 'pre_line': False, 'currency_id':currency_id},
437 if not partner_id and ids:
438 line_ids = line_pool.search(cr, uid, [('voucher_id', '=', ids[0])])
440 line_pool.unlink(cr, uid, line_ids)
443 journal = journal_pool.browse(cr, uid, journal_id, context=context)
444 partner = partner_pool.browse(cr, uid, partner_id, context=context)
446 if journal.type in ('sale','sale_refund'):
447 account_id = partner.property_account_receivable.id
448 elif journal.type in ('purchase', 'purchase_refund','expense'):
449 account_id = partner.property_account_payable.id
451 account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
453 default['value']['account_id'] = account_id
455 if journal.type not in ('cash', 'bank'):
460 account_type = 'receivable'
461 if ttype == 'payment':
462 account_type = 'payable'
463 total_debit = price or 0.0
465 total_credit = price or 0.0
466 account_type = 'receivable'
468 if not context.get('move_line_ids', False):
469 ids = move_line_pool.search(cr, uid, [('state','=','valid'), ('account_id.type', '=', account_type), ('reconcile_id', '=', False), ('partner_id', '=', partner_id)], context=context)
471 ids = context['move_line_ids']
473 moves = move_line_pool.browse(cr, uid, ids, context=context)
475 company_currency = journal.company_id.currency_id.id
476 if company_currency != currency_id and ttype == 'payment':
477 total_debit = currency_pool.compute(cr, uid, currency_id, company_currency, total_debit, context=context_multi_currency)
478 elif company_currency != currency_id and ttype == 'receipt':
479 total_credit = currency_pool.compute(cr, uid, currency_id, company_currency, total_credit, context=context_multi_currency)
482 if line.credit and line.reconcile_partial_id and ttype == 'receipt':
484 if line.debit and line.reconcile_partial_id and ttype == 'payment':
486 total_credit += line.credit or 0.0
487 total_debit += line.debit or 0.0
489 if line.credit and line.reconcile_partial_id and ttype == 'receipt':
491 if line.debit and line.reconcile_partial_id and ttype == 'payment':
493 original_amount = line.credit or line.debit or 0.0
494 amount_unreconciled = currency_pool.compute(cr, uid, line.currency_id and line.currency_id.id or company_currency, currency_id, abs(line.amount_residual_currency), context=context_multi_currency)
496 'name':line.move_id.name,
497 'type': line.credit and 'dr' or 'cr',
498 'move_line_id':line.id,
499 'account_id':line.account_id.id,
500 'amount_original': currency_pool.compute(cr, uid, line.currency_id and line.currency_id.id or company_currency, currency_id, line.currency_id and abs(line.amount_currency) or original_amount, context=context_multi_currency),
501 'date_original':line.date,
502 'date_due':line.date_maturity,
503 'amount_unreconciled': amount_unreconciled,
508 amount = min(amount_unreconciled, currency_pool.compute(cr, uid, company_currency, currency_id, abs(total_debit), context=context_multi_currency))
509 rs['amount'] = amount
510 total_debit -= amount
512 amount = min(amount_unreconciled, currency_pool.compute(cr, uid, company_currency, currency_id, abs(total_credit), context=context_multi_currency))
513 rs['amount'] = amount
514 total_credit -= amount
516 default['value']['line_ids'].append(rs)
517 if rs['type'] == 'cr':
518 default['value']['line_cr_ids'].append(rs)
520 default['value']['line_dr_ids'].append(rs)
522 if ttype == 'payment' and len(default['value']['line_cr_ids']) > 0:
523 default['value']['pre_line'] = 1
524 elif ttype == 'receipt' and len(default['value']['line_dr_ids']) > 0:
525 default['value']['pre_line'] = 1
526 default['value']['writeoff_amount'] = self._compute_writeoff_amount(cr, uid, default['value']['line_dr_ids'], default['value']['line_cr_ids'], price)
529 def onchange_date(self, cr, uid, ids, partner_id, journal_id, price, currency_id, ttype, date, context=None):
531 @param date: latest value from user input for field date
532 @param args: other arguments
533 @param context: context arguments, like lang, time zone
534 @return: Returns a dict which contains new values, and context
536 period_pool = self.pool.get('account.period')
537 res = self.onchange_partner_id(cr, uid, ids, partner_id, journal_id, price, currency_id, ttype, date, context=context)
538 pids = period_pool.search(cr, uid, [('date_start', '<=', date), ('date_stop', '>=', date)])
540 if not 'value' in res:
542 res['value'].update({'period_id':pids[0]})
545 def onchange_journal(self, cr, uid, ids, journal_id, line_ids, tax_id, partner_id, context=None):
548 journal_pool = self.pool.get('account.journal')
549 journal = journal_pool.browse(cr, uid, journal_id, context=context)
550 account_id = journal.default_credit_account_id or journal.default_debit_account_id
552 if account_id and account_id.tax_ids:
553 tax_id = account_id.tax_ids[0].id
555 vals = self.onchange_price(cr, uid, ids, line_ids, tax_id, partner_id, context)
556 vals['value'].update({'tax_id':tax_id})
557 currency_id = journal.company_id.currency_id.id
559 currency_id = journal.currency.id
560 vals['value'].update({'currency_id':currency_id})
563 def proforma_voucher(self, cr, uid, ids, context=None):
564 self.action_move_line_create(cr, uid, ids, context=context)
567 def action_cancel_draft(self, cr, uid, ids, context=None):
568 wf_service = netsvc.LocalService("workflow")
569 for voucher_id in ids:
570 wf_service.trg_create(uid, 'account.voucher', voucher_id, cr)
571 self.write(cr, uid, ids, {'state':'draft'})
574 def cancel_voucher(self, cr, uid, ids, context=None):
575 reconcile_pool = self.pool.get('account.move.reconcile')
576 move_pool = self.pool.get('account.move')
578 for voucher in self.browse(cr, uid, ids, context=context):
580 for line in voucher.move_ids:
581 if line.reconcile_id:
582 recs += [line.reconcile_id.id]
583 if line.reconcile_partial_id:
584 recs += [line.reconcile_partial_id.id]
586 reconcile_pool.unlink(cr, uid, recs)
589 move_pool.button_cancel(cr, uid, [voucher.move_id.id])
590 move_pool.unlink(cr, uid, [voucher.move_id.id])
595 self.write(cr, uid, ids, res)
598 def unlink(self, cr, uid, ids, context=None):
599 for t in self.read(cr, uid, ids, ['state'], context=context):
600 if t['state'] not in ('draft', 'cancel'):
601 raise osv.except_osv(_('Invalid action !'), _('Cannot delete Voucher(s) which are already opened or paid !'))
602 return super(account_voucher, self).unlink(cr, uid, ids, context=context)
604 # TODO: may be we can remove this method if not used anyware
605 def onchange_payment(self, cr, uid, ids, pay_now, journal_id, partner_id, ttype='sale'):
609 res = {'account_id':False}
610 partner_pool = self.pool.get('res.partner')
611 journal_pool = self.pool.get('account.journal')
612 if pay_now == 'pay_later':
613 partner = partner_pool.browse(cr, uid, partner_id)
614 journal = journal_pool.browse(cr, uid, journal_id)
615 if journal.type in ('sale','sale_refund'):
616 account_id = partner.property_account_receivable.id
617 elif journal.type in ('purchase', 'purchase_refund','expense'):
618 account_id = partner.property_account_payable.id
620 account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
621 res['account_id'] = account_id
624 def action_move_line_create(self, cr, uid, ids, context=None):
626 def _get_payment_term_lines(term_id, amount):
627 term_pool = self.pool.get('account.payment.term')
628 if term_id and amount:
629 terms = term_pool.compute(cr, uid, term_id, amount)
634 move_pool = self.pool.get('account.move')
635 move_line_pool = self.pool.get('account.move.line')
636 currency_pool = self.pool.get('res.currency')
637 tax_obj = self.pool.get('account.tax')
638 seq_obj = self.pool.get('ir.sequence')
639 for inv in self.browse(cr, uid, ids, context=context):
642 context_multi_currency = context.copy()
643 context_multi_currency.update({'date': inv.date})
647 elif inv.journal_id.sequence_id:
648 name = seq_obj.get_id(cr, uid, inv.journal_id.sequence_id.id)
650 raise osv.except_osv(_('Error !'), _('Please define a sequence on the journal !'))
651 if not inv.reference:
652 ref = name.replace('/','')
658 'journal_id': inv.journal_id.id,
659 'narration': inv.narration,
662 'period_id': inv.period_id and inv.period_id.id or False
664 move_id = move_pool.create(cr, uid, move)
666 #create the first line manually
667 company_currency = inv.journal_id.company_id.currency_id.id
668 current_currency = inv.currency_id.id
671 # TODO: is there any other alternative then the voucher type ??
672 # -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
673 if inv.type in ('purchase', 'payment'):
674 credit = currency_pool.compute(cr, uid, current_currency, company_currency, inv.amount, context=context_multi_currency)
675 elif inv.type in ('sale', 'receipt'):
676 debit = currency_pool.compute(cr, uid, current_currency, company_currency, inv.amount, context=context_multi_currency)
683 sign = debit - credit < 0 and -1 or 1
684 #create the first line of the voucher
686 'name': inv.name or '/',
689 'account_id': inv.account_id.id,
691 'journal_id': inv.journal_id.id,
692 'period_id': inv.period_id.id,
693 'partner_id': inv.partner_id.id,
694 'currency_id': company_currency <> current_currency and current_currency or False,
695 'amount_currency': company_currency <> current_currency and sign * inv.amount or 0.0,
697 'date_maturity': inv.date_due
699 move_line_pool.create(cr, uid, move_line)
701 line_total = debit - credit
702 if inv.type == 'sale':
703 line_total = line_total - currency_pool.compute(cr, uid, inv.currency_id.id, company_currency, inv.tax_amount, context=context_multi_currency)
704 elif inv.type == 'purchase':
705 line_total = line_total + currency_pool.compute(cr, uid, inv.currency_id.id, company_currency, inv.tax_amount, context=context_multi_currency)
707 for line in inv.line_ids:
708 #create one move line per voucher line where amount is not 0.0
711 #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
712 if line.amount == line.amount_unreconciled:
713 amount = line.move_line_id.amount_residual #residual amount in company currency
715 amount = currency_pool.compute(cr, uid, current_currency, company_currency, line.untax_amount or line.amount, context=context_multi_currency)
717 'journal_id': inv.journal_id.id,
718 'period_id': inv.period_id.id,
719 'name': line.name or '/',
720 'account_id': line.account_id.id,
722 'partner_id': inv.partner_id.id,
723 'currency_id': company_currency <> current_currency and current_currency or False,
724 'analytic_account_id': line.account_analytic_id and line.account_analytic_id.id or False,
732 if line.type == 'dr':
736 if (line.type=='dr'):
738 move_line['debit'] = amount
741 move_line['credit'] = amount
743 if inv.tax_id and inv.type in ('sale', 'purchase'):
745 'account_tax_id': inv.tax_id.id,
747 if move_line.get('account_tax_id', False):
748 tax_data = tax_obj.browse(cr, uid, [move_line['account_tax_id']], context=context)[0]
749 if not (tax_data.base_code_id and tax_data.tax_code_id):
750 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))
751 sign = (move_line['debit'] - move_line['credit']) < 0 and -1 or 1
752 move_line['amount_currency'] = company_currency <> current_currency and sign * line.amount or 0.0
753 voucher_line = move_line_pool.create(cr, uid, move_line)
754 if line.move_line_id.id:
755 rec_ids = [voucher_line, line.move_line_id.id]
756 rec_list_ids.append(rec_ids)
758 if not currency_pool.is_zero(cr, uid, inv.currency_id, line_total):
762 if inv.payment_option == 'with_writeoff':
763 account_id = inv.writeoff_acc_id.id
764 write_off_name = inv.comment
765 elif inv.type in ('sale', 'receipt'):
766 account_id = inv.partner_id.property_account_receivable.id
768 account_id = inv.partner_id.property_account_payable.id
770 'name': write_off_name or name,
771 'account_id': account_id,
773 'partner_id': inv.partner_id.id,
775 'credit': diff > 0 and diff or 0.0,
776 'debit': diff < 0 and -diff or 0.0,
777 #'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,
778 #'currency_id': company_currency <> current_currency and current_currency or False,
780 move_line_pool.create(cr, uid, move_line)
781 self.write(cr, uid, [inv.id], {
786 if inv.journal_id.entry_posted:
787 move_pool.post(cr, uid, [move_id], context={})
788 for rec_ids in rec_list_ids:
789 if len(rec_ids) >= 2:
790 move_line_pool.reconcile_partial(cr, uid, rec_ids)
793 def copy(self, cr, uid, id, default={}, context=None):
798 'line_cr_ids': False,
799 'line_dr_ids': False,
802 if 'date' not in default:
803 default['date'] = time.strftime('%Y-%m-%d')
804 return super(account_voucher, self).copy(cr, uid, id, default, context)
808 class account_voucher_line(osv.osv):
809 _name = 'account.voucher.line'
810 _description = 'Voucher Lines'
811 _order = "move_line_id"
813 def _compute_balance(self, cr, uid, ids, name, args, context=None):
814 currency_pool = self.pool.get('res.currency')
816 for line in self.browse(cr, uid, ids, context=context):
818 ctx.update({'date': line.voucher_id.date})
820 company_currency = line.voucher_id.journal_id.company_id.currency_id.id
821 voucher_currency = line.voucher_id.currency_id.id
822 move_line = line.move_line_id or False
825 res['amount_original'] = 0.0
826 res['amount_unreconciled'] = 0.0
828 elif move_line.currency_id:
829 res['amount_original'] = currency_pool.compute(cr, uid, move_line.currency_id.id, voucher_currency, move_line.amount_currency, context=ctx)
830 elif move_line and move_line.credit > 0:
831 res['amount_original'] = currency_pool.compute(cr, uid, company_currency, voucher_currency, move_line.credit, context=ctx)
833 res['amount_original'] = currency_pool.compute(cr, uid, company_currency, voucher_currency, move_line.debit, context=ctx)
836 res['amount_unreconciled'] = currency_pool.compute(cr, uid, move_line.currency_id and move_line.currency_id.id or company_currency, voucher_currency, abs(move_line.amount_residual_currency), context=ctx)
837 rs_data[line.id] = res
841 'voucher_id':fields.many2one('account.voucher', 'Voucher', required=1, ondelete='cascade'),
842 'name':fields.char('Description', size=256),
843 'account_id':fields.many2one('account.account','Account', required=True),
844 'partner_id':fields.related('voucher_id', 'partner_id', type='many2one', relation='res.partner', string='Partner'),
845 'untax_amount':fields.float('Untax Amount'),
846 'amount':fields.float('Amount', digits_compute=dp.get_precision('Account')),
847 'type':fields.selection([('dr','Debit'),('cr','Credit')], 'Dr/Cr'),
848 'account_analytic_id': fields.many2one('account.analytic.account', 'Analytic Account'),
849 'move_line_id': fields.many2one('account.move.line', 'Journal Item'),
850 'date_original': fields.related('move_line_id','date', type='date', relation='account.move.line', string='Date', readonly=1),
851 'date_due': fields.related('move_line_id','date_maturity', type='date', relation='account.move.line', string='Due Date', readonly=1),
852 'amount_original': fields.function(_compute_balance, multi='dc', type='float', string='Original Amount', store=True),
853 'amount_unreconciled': fields.function(_compute_balance, multi='dc', type='float', string='Open Balance', store=True),
854 'company_id': fields.related('voucher_id','company_id', relation='res.company', type='many2one', string='Company', store=True, readonly=True),
860 def onchange_move_line_id(self, cr, user, ids, move_line_id, context=None):
862 Returns a dict that contains new values and context
864 @param move_line_id: latest value from user input for field move_line_id
865 @param args: other arguments
866 @param context: context arguments, like lang, time zone
868 @return: Returns a dict which contains new values, and context
871 move_line_pool = self.pool.get('account.move.line')
873 move_line = move_line_pool.browse(cr, user, move_line_id, context=context)
878 account_id = move_line.account_id.id
880 'account_id':account_id,
887 def default_get(self, cr, user, fields_list, context=None):
889 Returns default values for fields
890 @param fields_list: list of fields, for which default values are required to be read
891 @param context: context arguments, like lang, time zone
893 @return: Returns a dict that contains default values for fields
897 journal_id = context.get('journal_id', False)
898 partner_id = context.get('partner_id', False)
899 journal_pool = self.pool.get('account.journal')
900 partner_pool = self.pool.get('res.partner')
901 values = super(account_voucher_line, self).default_get(cr, user, fields_list, context=context)
902 if (not journal_id) or ('account_id' not in fields_list):
904 journal = journal_pool.browse(cr, user, journal_id, context=context)
907 if journal.type in ('sale', 'sale_refund'):
908 account_id = journal.default_credit_account_id and journal.default_credit_account_id.id or False
910 elif journal.type in ('purchase', 'expense', 'purchase_refund'):
911 account_id = journal.default_debit_account_id and journal.default_debit_account_id.id or False
914 partner = partner_pool.browse(cr, user, partner_id, context=context)
915 if context.get('type') == 'payment':
917 account_id = partner.property_account_payable.id
918 elif context.get('type') == 'receipt':
919 account_id = partner.property_account_receivable.id
922 'account_id':account_id,
926 account_voucher_line()
928 class account_bank_statement(osv.osv):
929 _inherit = 'account.bank.statement'
931 def button_cancel(self, cr, uid, ids, context=None):
932 voucher_obj = self.pool.get('account.voucher')
933 for st in self.browse(cr, uid, ids, context=context):
935 for line in st.line_ids:
937 voucher_ids.append(line.voucher_id.id)
938 voucher_obj.cancel_voucher(cr, uid, voucher_ids, context)
939 return super(account_bank_statement, self).button_cancel(cr, uid, ids, context=context)
941 def create_move_from_st_line(self, cr, uid, st_line_id, company_currency_id, next_number, context=None):
942 voucher_obj = self.pool.get('account.voucher')
943 wf_service = netsvc.LocalService("workflow")
944 move_line_obj = self.pool.get('account.move.line')
945 bank_st_line_obj = self.pool.get('account.bank.statement.line')
946 st_line = bank_st_line_obj.browse(cr, uid, st_line_id, context=context)
947 if st_line.voucher_id:
948 voucher_obj.write(cr, uid, [st_line.voucher_id.id], {'number': next_number}, context=context)
949 if st_line.voucher_id.state == 'cancel':
950 voucher_obj.action_cancel_draft(cr, uid, [st_line.voucher_id.id], context=context)
951 wf_service.trg_validate(uid, 'account.voucher', st_line.voucher_id.id, 'proforma_voucher', cr)
953 v = voucher_obj.browse(cr, uid, st_line.voucher_id.id, context=context)
954 bank_st_line_obj.write(cr, uid, [st_line_id], {
955 'move_ids': [(4, v.move_id.id, False)]
958 return move_line_obj.write(cr, uid, [x.id for x in v.move_ids], {'statement_id': st_line.statement_id.id}, context=context)
959 return super(account_bank_statement, self).create_move_from_st_line(cr, uid, st_line.id, company_currency_id, next_number, context=context)
961 account_bank_statement()
963 class account_bank_statement_line(osv.osv):
964 _inherit = 'account.bank.statement.line'
966 def _amount_reconciled(self, cursor, user, ids, name, args, context=None):
971 # company_currency_id = False
972 for line in self.browse(cursor, user, ids, context=context):
973 # if not company_currency_id:
974 # company_currency_id = line.company_id.id
976 res[line.id] = line.voucher_id.amount#
977 # res_currency_obj.compute(cursor, user,
978 # company_currency_id, line.statement_id.currency.id,
979 # line.voucher_id.amount, context=context)
984 def _check_amount(self, cr, uid, ids, context=None):
985 for obj in self.browse(cr, uid, ids, context=context):
987 diff = abs(obj.amount) - obj.voucher_id.amount
988 if not self.pool.get('res.currency').is_zero(cr, uid, obj.voucher_id.currency_id, diff):
993 (_check_amount, 'The amount of the voucher must be the same amount as the one on the statement line', ['amount']),
997 'amount_reconciled': fields.function(_amount_reconciled,
998 string='Amount reconciled', type='float'),
999 'voucher_id': fields.many2one('account.voucher', 'Payment'),
1003 def unlink(self, cr, uid, ids, context=None):
1004 voucher_obj = self.pool.get('account.voucher')
1005 statement_line = self.browse(cr, uid, ids, context=context)
1007 for st_line in statement_line:
1008 if st_line.voucher_id:
1009 unlink_ids.append(st_line.voucher_id.id)
1010 voucher_obj.unlink(cr, uid, unlink_ids, context=context)
1011 return super(account_bank_statement_line, self).unlink(cr, uid, ids, context=context)
1013 account_bank_statement_line()
1015 def resolve_o2m_operations(cr, uid, target_osv, operations, fields, context):
1017 for operation in operations:
1019 if not isinstance(operation, (list, tuple)):
1020 result = target_osv.read(cr, uid, operation, fields, context=context)
1021 elif operation[0] == 0:
1022 # may be necessary to check if all the fields are here and get the default values?
1023 result = operation[2]
1024 elif operation[0] == 1:
1025 result = target_osv.read(cr, uid, operation[1], fields, context=context)
1026 result.update(operation[2])
1027 elif operation[0] == 4:
1028 result = target_osv.read(cr, uid, operation[1], fields, context=context)
1030 results.append(result)
1033 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: