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 ##############################################################################
24 from openerp.osv import fields, osv
25 from openerp.tools.translate import _
26 import openerp.addons.decimal_precision as dp
28 class account_bank_statement(osv.osv):
29 def create(self, cr, uid, vals, context=None):
30 if 'line_ids' in vals:
31 for idx, line in enumerate(vals['line_ids']):
32 line[2]['sequence'] = idx + 1
33 return super(account_bank_statement, self).create(cr, uid, vals, context=context)
35 def write(self, cr, uid, ids, vals, context=None):
36 res = super(account_bank_statement, self).write(cr, uid, ids, vals, context=context)
37 account_bank_statement_line_obj = self.pool.get('account.bank.statement.line')
38 for statement in self.browse(cr, uid, ids, context):
39 for idx, line in enumerate(statement.line_ids):
40 account_bank_statement_line_obj.write(cr, uid, [line.id], {'sequence': idx + 1}, context=context)
43 def _default_journal_id(self, cr, uid, context=None):
46 journal_pool = self.pool.get('account.journal')
47 journal_type = context.get('journal_type', False)
48 company_id = self.pool.get('res.company')._company_default_get(cr, uid, 'account.bank.statement',context=context)
50 ids = journal_pool.search(cr, uid, [('type', '=', journal_type),('company_id','=',company_id)])
55 def _end_balance(self, cursor, user, ids, name, attr, context=None):
57 for statement in self.browse(cursor, user, ids, context=context):
58 res[statement.id] = statement.balance_start
59 for line in statement.line_ids:
60 res[statement.id] += line.amount
63 def _get_period(self, cr, uid, context=None):
64 ctx = dict(context or {}, account_period_prefer_normal=True)
65 periods = self.pool.get('account.period').find(cr, uid, context=ctx)
70 def _currency(self, cursor, user, ids, name, args, context=None):
72 res_currency_obj = self.pool.get('res.currency')
73 res_users_obj = self.pool.get('res.users')
74 default_currency = res_users_obj.browse(cursor, user,
75 user, context=context).company_id.currency_id
76 for statement in self.browse(cursor, user, ids, context=context):
77 currency = statement.journal_id.currency
79 currency = default_currency
80 res[statement.id] = currency.id
82 for currency_id, currency_name in res_currency_obj.name_get(cursor,
83 user, [x for x in res.values()], context=context):
84 currency_names[currency_id] = currency_name
85 for statement_id in res.keys():
86 currency_id = res[statement_id]
87 res[statement_id] = (currency_id, currency_names[currency_id])
90 def _get_statement(self, cr, uid, ids, context=None):
92 for line in self.pool.get('account.bank.statement.line').browse(cr, uid, ids, context=context):
93 result[line.statement_id.id] = True
96 _order = "date desc, id desc"
97 _name = "account.bank.statement"
98 _description = "Bank Statement"
99 _inherit = ['mail.thread']
101 'name': fields.char('Reference', size=64, required=True, states={'draft': [('readonly', False)]}, readonly=True, help='if you give the Name other then /, its created Accounting Entries Move will be with same name as statement name. This allows the statement entries to have the same references than the statement itself'), # readonly for account_cash_statement
102 'date': fields.date('Date', required=True, states={'confirm': [('readonly', True)]}, select=True),
103 'journal_id': fields.many2one('account.journal', 'Journal', required=True,
104 readonly=True, states={'draft':[('readonly',False)]}),
105 'period_id': fields.many2one('account.period', 'Period', required=True,
106 states={'confirm':[('readonly', True)]}),
107 'balance_start': fields.float('Starting Balance', digits_compute=dp.get_precision('Account'),
108 states={'confirm':[('readonly',True)]}),
109 'balance_end_real': fields.float('Ending Balance', digits_compute=dp.get_precision('Account'),
110 states={'confirm': [('readonly', True)]}),
111 'balance_end': fields.function(_end_balance,
113 'account.bank.statement': (lambda self, cr, uid, ids, c={}: ids, ['line_ids','move_line_ids','balance_start'], 10),
114 'account.bank.statement.line': (_get_statement, ['amount'], 10),
116 string="Computed Balance", help='Balance as calculated based on Starting Balance and transaction lines'),
117 'company_id': fields.related('journal_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True),
118 'line_ids': fields.one2many('account.bank.statement.line',
119 'statement_id', 'Statement lines',
120 states={'confirm':[('readonly', True)]}),
121 'move_line_ids': fields.one2many('account.move.line', 'statement_id',
122 'Entry lines', states={'confirm':[('readonly',True)]}),
123 'state': fields.selection([('draft', 'New'),
124 ('open','Open'), # used by cash statements
125 ('confirm', 'Closed')],
126 'Status', required=True, readonly="1",
127 help='When new statement is created the status will be \'Draft\'.\n'
128 'And after getting confirmation from the bank it will be in \'Confirmed\' status.'),
129 'currency': fields.function(_currency, string='Currency',
130 type='many2one', relation='res.currency'),
131 'account_id': fields.related('journal_id', 'default_debit_account_id', type='many2one', relation='account.account', string='Account used in this journal', readonly=True, help='used in statement reconciliation domain, but shouldn\'t be used elswhere.'),
136 'date': fields.date.context_today,
138 'journal_id': _default_journal_id,
139 'period_id': _get_period,
140 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.bank.statement',context=c),
143 def _check_company_id(self, cr, uid, ids, context=None):
144 for statement in self.browse(cr, uid, ids, context=context):
145 if statement.company_id.id != statement.period_id.company_id.id:
150 (_check_company_id, 'The journal and period chosen have to belong to the same company.', ['journal_id','period_id']),
153 def onchange_date(self, cr, uid, ids, date, company_id, context=None):
155 Find the correct period to use for the given date and company_id, return it and set it in the context
158 period_pool = self.pool.get('account.period')
163 ctx.update({'company_id': company_id, 'account_period_prefer_normal': True})
164 pids = period_pool.find(cr, uid, dt=date, context=ctx)
166 res.update({'period_id': pids[0]})
167 context.update({'period_id': pids[0]})
174 def button_dummy(self, cr, uid, ids, context=None):
175 return self.write(cr, uid, ids, {}, context=context)
177 def _prepare_move(self, cr, uid, st_line, st_line_number, context=None):
178 """Prepare the dict of values to create the move from a
179 statement line. This method may be overridden to implement custom
180 move generation (making sure to call super() to establish
181 a clean extension chain).
183 :param browse_record st_line: account.bank.statement.line record to
184 create the move from.
185 :param char st_line_number: will be used as the name of the generated account move
186 :return: dict of value to create() the account.move
189 'journal_id': st_line.statement_id.journal_id.id,
190 'period_id': st_line.statement_id.period_id.id,
191 'date': st_line.date,
192 'name': st_line_number,
196 def _prepare_bank_move_line(self, cr, uid, st_line, move_id, amount, company_currency_id,
198 """Compute the args to build the dict of values to create the bank move line from a
199 statement line by calling the _prepare_move_line_vals. This method may be
200 overridden to implement custom move generation (making sure to call super() to
201 establish a clean extension chain).
203 :param browse_record st_line: account.bank.statement.line record to
204 create the move from.
205 :param int/long move_id: ID of the account.move to link the move line
206 :param float amount: amount of the move line
207 :param int/long company_currency_id: ID of currency of the concerned company
208 :return: dict of value to create() the bank account.move.line
210 anl_id = st_line.analytic_account_id and st_line.analytic_account_id.id or False
211 debit = ((amount<0) and -amount) or 0.0
212 credit = ((amount>0) and amount) or 0.0
215 if st_line.statement_id.currency.id <> company_currency_id:
216 cur_id = st_line.statement_id.currency.id
217 if st_line.account_id and st_line.account_id.currency_id and st_line.account_id.currency_id.id <> company_currency_id:
218 cur_id = st_line.account_id.currency_id.id
220 res_currency_obj = self.pool.get('res.currency')
221 amt_cur = -res_currency_obj.compute(cr, uid, company_currency_id, cur_id, amount, context=context)
223 res = self._prepare_move_line_vals(cr, uid, st_line, move_id, debit, credit,
224 amount_currency=amt_cur, currency_id=cur_id, analytic_id=anl_id, context=context)
227 def _get_counter_part_account(sefl, cr, uid, st_line, context=None):
228 """Retrieve the account to use in the counterpart move.
229 This method may be overridden to implement custom move generation (making sure to
230 call super() to establish a clean extension chain).
232 :param browse_record st_line: account.bank.statement.line record to
233 create the move from.
234 :return: int/long of the account.account to use as counterpart
236 if st_line.amount >= 0:
237 return st_line.statement_id.journal_id.default_credit_account_id.id
238 return st_line.statement_id.journal_id.default_debit_account_id.id
240 def _get_counter_part_partner(sefl, cr, uid, st_line, context=None):
241 """Retrieve the partner to use in the counterpart move.
242 This method may be overridden to implement custom move generation (making sure to
243 call super() to establish a clean extension chain).
245 :param browse_record st_line: account.bank.statement.line record to
246 create the move from.
247 :return: int/long of the res.partner to use as counterpart
249 return st_line.partner_id and st_line.partner_id.id or False
251 def _prepare_counterpart_move_line(self, cr, uid, st_line, move_id, amount, company_currency_id,
253 """Compute the args to build the dict of values to create the counter part move line from a
254 statement line by calling the _prepare_move_line_vals. This method may be
255 overridden to implement custom move generation (making sure to call super() to
256 establish a clean extension chain).
258 :param browse_record st_line: account.bank.statement.line record to
259 create the move from.
260 :param int/long move_id: ID of the account.move to link the move line
261 :param float amount: amount of the move line
262 :param int/long account_id: ID of account to use as counter part
263 :param int/long company_currency_id: ID of currency of the concerned company
264 :return: dict of value to create() the bank account.move.line
266 account_id = self._get_counter_part_account(cr, uid, st_line, context=context)
267 partner_id = self._get_counter_part_partner(cr, uid, st_line, context=context)
268 debit = ((amount > 0) and amount) or 0.0
269 credit = ((amount < 0) and -amount) or 0.0
272 if st_line.statement_id.currency.id <> company_currency_id:
273 amt_cur = st_line.amount
274 cur_id = st_line.statement_id.currency.id
275 return self._prepare_move_line_vals(cr, uid, st_line, move_id, debit, credit,
276 amount_currency = amt_cur, currency_id = cur_id, account_id = account_id,
277 partner_id = partner_id, context=context)
279 def _prepare_move_line_vals(self, cr, uid, st_line, move_id, debit, credit, currency_id = False,
280 amount_currency= False, account_id = False, analytic_id = False,
281 partner_id = False, context=None):
282 """Prepare the dict of values to create the move line from a
283 statement line. All non-mandatory args will replace the default computed one.
284 This method may be overridden to implement custom move generation (making sure to
285 call super() to establish a clean extension chain).
287 :param browse_record st_line: account.bank.statement.line record to
288 create the move from.
289 :param int/long move_id: ID of the account.move to link the move line
290 :param float debit: debit amount of the move line
291 :param float credit: credit amount of the move line
292 :param int/long currency_id: ID of currency of the move line to create
293 :param float amount_currency: amount of the debit/credit expressed in the currency_id
294 :param int/long account_id: ID of the account to use in the move line if different
295 from the statement line account ID
296 :param int/long analytic_id: ID of analytic account to put on the move line
297 :param int/long partner_id: ID of the partner to put on the move line
298 :return: dict of value to create() the account.move.line
300 acc_id = account_id or st_line.account_id.id
301 cur_id = currency_id or st_line.statement_id.currency.id
302 par_id = partner_id or (((st_line.partner_id) and st_line.partner_id.id) or False)
304 'name': st_line.name,
305 'date': st_line.date,
308 'partner_id': par_id,
309 'account_id': acc_id,
312 'statement_id': st_line.statement_id.id,
313 'journal_id': st_line.statement_id.journal_id.id,
314 'period_id': st_line.statement_id.period_id.id,
315 'currency_id': amount_currency and cur_id,
316 'amount_currency': amount_currency,
317 'analytic_account_id': analytic_id,
320 def create_move_from_st_line(self, cr, uid, st_line_id, company_currency_id, st_line_number, context=None):
321 """Create the account move from the statement line.
323 :param int/long st_line_id: ID of the account.bank.statement.line to create the move from.
324 :param int/long company_currency_id: ID of the res.currency of the company
325 :param char st_line_number: will be used as the name of the generated account move
326 :return: ID of the account.move created
331 res_currency_obj = self.pool.get('res.currency')
332 account_move_obj = self.pool.get('account.move')
333 account_move_line_obj = self.pool.get('account.move.line')
334 account_bank_statement_line_obj = self.pool.get('account.bank.statement.line')
335 st_line = account_bank_statement_line_obj.browse(cr, uid, st_line_id, context=context)
336 st = st_line.statement_id
338 context.update({'date': st_line.date})
340 move_vals = self._prepare_move(cr, uid, st_line, st_line_number, context=context)
341 move_id = account_move_obj.create(cr, uid, move_vals, context=context)
342 account_bank_statement_line_obj.write(cr, uid, [st_line.id], {
343 'move_ids': [(4, move_id, False)]
346 acc_cur = ((st_line.amount<=0) and st.journal_id.default_debit_account_id) or st_line.account_id
349 'res.currency.compute.account': acc_cur,
351 amount = res_currency_obj.compute(cr, uid, st.currency.id,
352 company_currency_id, st_line.amount, context=context)
354 bank_move_vals = self._prepare_bank_move_line(cr, uid, st_line, move_id, amount,
355 company_currency_id, context=context)
356 move_line_id = account_move_line_obj.create(cr, uid, bank_move_vals, context=context)
357 torec.append(move_line_id)
359 counterpart_move_vals = self._prepare_counterpart_move_line(cr, uid, st_line, move_id,
360 amount, company_currency_id, context=context)
361 account_move_line_obj.create(cr, uid, counterpart_move_vals, context=context)
363 for line in account_move_line_obj.browse(cr, uid, [x.id for x in
364 account_move_obj.browse(cr, uid, move_id,
365 context=context).line_id],
367 if line.state <> 'valid':
368 raise osv.except_osv(_('Error!'),
369 _('Journal item "%s" is not valid.') % line.name)
371 # Bank statements will not consider boolean on journal entry_posted
372 account_move_obj.post(cr, uid, [move_id], context=context)
375 def get_next_st_line_number(self, cr, uid, st_number, st_line, context=None):
376 return st_number + '/' + str(st_line.sequence)
378 def balance_check(self, cr, uid, st_id, journal_type='bank', context=None):
379 st = self.browse(cr, uid, st_id, context=context)
380 if not ((abs((st.balance_end or 0.0) - st.balance_end_real) < 0.0001) or (abs((st.balance_end or 0.0) - st.balance_end_real) < 0.0001)):
381 raise osv.except_osv(_('Error!'),
382 _('The statement balance is incorrect !\nThe expected balance (%.2f) is different than the computed one. (%.2f)') % (st.balance_end_real, st.balance_end))
385 def statement_close(self, cr, uid, ids, journal_type='bank', context=None):
386 return self.write(cr, uid, ids, {'state':'confirm'}, context=context)
388 def check_status_condition(self, cr, uid, state, journal_type='bank'):
389 return state in ('draft','open')
391 def button_confirm_bank(self, cr, uid, ids, context=None):
392 obj_seq = self.pool.get('ir.sequence')
396 for st in self.browse(cr, uid, ids, context=context):
397 j_type = st.journal_id.type
398 company_currency_id = st.journal_id.company_id.currency_id.id
399 if not self.check_status_condition(cr, uid, st.state, journal_type=j_type):
402 self.balance_check(cr, uid, st.id, journal_type=j_type, context=context)
403 if (not st.journal_id.default_credit_account_id) \
404 or (not st.journal_id.default_debit_account_id):
405 raise osv.except_osv(_('Configuration Error!'),
406 _('Please verify that an account is defined in the journal.'))
408 if not st.name == '/':
411 c = {'fiscalyear_id': st.period_id.fiscalyear_id.id}
412 if st.journal_id.sequence_id:
413 st_number = obj_seq.next_by_id(cr, uid, st.journal_id.sequence_id.id, context=c)
415 st_number = obj_seq.next_by_code(cr, uid, 'account.bank.statement', context=c)
417 for line in st.move_line_ids:
418 if line.state <> 'valid':
419 raise osv.except_osv(_('Error!'),
420 _('The account entries lines are not in valid state.'))
421 for st_line in st.line_ids:
422 if st_line.analytic_account_id:
423 if not st.journal_id.analytic_journal_id:
424 raise osv.except_osv(_('No Analytic Journal!'),_("You have to assign an analytic journal on the '%s' journal!") % (st.journal_id.name,))
425 if not st_line.amount:
427 st_line_number = self.get_next_st_line_number(cr, uid, st_number, st_line, context)
428 self.create_move_from_st_line(cr, uid, st_line.id, company_currency_id, st_line_number, context)
430 self.write(cr, uid, [st.id], {
432 'balance_end_real': st.balance_end
434 self.message_post(cr, uid, [st.id], body=_('Statement %s confirmed, journal items were created.') % (st_number,), context=context)
435 return self.write(cr, uid, ids, {'state':'confirm'}, context=context)
437 def button_cancel(self, cr, uid, ids, context=None):
439 account_move_obj = self.pool.get('account.move')
440 for st in self.browse(cr, uid, ids, context=context):
441 if st.state=='draft':
444 for line in st.line_ids:
445 move_ids += [x.id for x in line.move_ids]
446 account_move_obj.button_cancel(cr, uid, move_ids, context=context)
447 account_move_obj.unlink(cr, uid, move_ids, context)
449 return self.write(cr, uid, done, {'state':'draft'}, context=context)
451 def _compute_balance_end_real(self, cr, uid, journal_id, context=None):
454 cr.execute('SELECT balance_end_real \
455 FROM account_bank_statement \
456 WHERE journal_id = %s AND NOT state = %s \
457 ORDER BY date DESC,id DESC LIMIT 1', (journal_id, 'draft'))
459 return res and res[0] or 0.0
461 def onchange_journal_id(self, cr, uid, statement_id, journal_id, context=None):
464 balance_start = self._compute_balance_end_real(cr, uid, journal_id, context=context)
466 journal_data = self.pool.get('account.journal').read(cr, uid, journal_id, ['company_id', 'currency'], context=context)
467 company_id = journal_data['company_id']
468 currency_id = journal_data['currency'] or self.pool.get('res.company').browse(cr, uid, company_id[0], context=context).currency_id.id
469 return {'value': {'balance_start': balance_start, 'company_id': company_id, 'currency': currency_id}}
471 def unlink(self, cr, uid, ids, context=None):
472 stat = self.read(cr, uid, ids, ['state'], context=context)
475 if t['state'] in ('draft'):
476 unlink_ids.append(t['id'])
478 raise osv.except_osv(_('Invalid Action!'), _('In order to delete a bank statement, you must first cancel it to delete related journal items.'))
479 osv.osv.unlink(self, cr, uid, unlink_ids, context=context)
482 def copy(self, cr, uid, id, default=None, context=None):
487 default = default.copy()
488 default['move_line_ids'] = []
489 return super(account_bank_statement, self).copy(cr, uid, id, default, context=context)
491 def button_journal_entries(self, cr, uid, ids, context=None):
492 ctx = (context or {}).copy()
493 ctx['journal_id'] = self.browse(cr, uid, ids[0], context=context).journal_id.id
497 'res_model':'account.move.line',
499 'type':'ir.actions.act_window',
500 'domain':[('statement_id','in',ids)],
504 account_bank_statement()
506 class account_bank_statement_line(osv.osv):
508 def onchange_partner_id(self, cr, uid, ids, partner_id, context=None):
509 obj_partner = self.pool.get('res.partner')
514 part = obj_partner.browse(cr, uid, partner_id, context=context)
515 if not part.supplier and not part.customer:
517 elif part.supplier and part.customer:
520 if part.supplier == True:
522 if part.customer == True:
524 res_type = self.onchange_type(cr, uid, ids, partner_id=partner_id, type=type, context=context)
525 if res_type['value'] and res_type['value'].get('account_id', False):
526 return {'value': {'type': type, 'account_id': res_type['value']['account_id']}}
527 return {'value': {'type': type}}
529 def onchange_type(self, cr, uid, line_id, partner_id, type, context=None):
531 obj_partner = self.pool.get('res.partner')
537 line = self.browse(cr, uid, line_id, context=context)
538 if not line or (line and not line[0].account_id):
539 part = obj_partner.browse(cr, uid, partner_id, context=context)
540 if type == 'supplier':
541 account_id = part.property_account_payable.id
543 account_id = part.property_account_receivable.id
544 res['value']['account_id'] = account_id
547 _order = "statement_id desc, sequence"
548 _name = "account.bank.statement.line"
549 _description = "Bank Statement Line"
551 'name': fields.char('OBI', required=True, help="Originator to Beneficiary Information"),
552 'date': fields.date('Date', required=True),
553 'amount': fields.float('Amount', digits_compute=dp.get_precision('Account')),
554 'type': fields.selection([
555 ('supplier','Supplier'),
556 ('customer','Customer'),
557 ('general','General')
558 ], 'Type', required=True),
559 'partner_id': fields.many2one('res.partner', 'Partner'),
560 'account_id': fields.many2one('account.account','Account',
562 'statement_id': fields.many2one('account.bank.statement', 'Statement',
563 select=True, required=True, ondelete='cascade'),
564 'journal_id': fields.related('statement_id', 'journal_id', type='many2one', relation='account.journal', string='Journal', store=True, readonly=True),
565 'analytic_account_id': fields.many2one('account.analytic.account', 'Analytic Account'),
566 'move_ids': fields.many2many('account.move',
567 'account_bank_statement_line_move_rel', 'statement_line_id','move_id',
569 'ref': fields.char('Reference', size=32),
570 'note': fields.text('Notes'),
571 'sequence': fields.integer('Sequence', select=True, help="Gives the sequence order when displaying a list of bank statement lines."),
572 'company_id': fields.related('statement_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True),
575 'name': lambda self,cr,uid,context={}: self.pool.get('ir.sequence').get(cr, uid, 'account.bank.statement.line'),
576 'date': lambda self,cr,uid,context={}: context.get('date', fields.date.context_today(self,cr,uid,context=context)),
580 account_bank_statement_line()
582 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: