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 osv import fields, osv
25 from tools.translate import _
26 import decimal_precision as dp
28 class account_bank_statement(osv.osv):
30 def create(self, cr, uid, vals, context=None):
32 if 'line_ids' in vals:
33 for line in vals['line_ids']:
35 line[2]['sequence'] = seq
37 return super(account_bank_statement, self).create(cr, uid, vals, context=context)
39 def write(self, cr, uid, ids, vals, context=None):
40 res = super(account_bank_statement, self).write(cr, uid, ids, vals, context=context)
41 account_bank_statement_line_obj = self.pool.get('account.bank.statement.line')
42 for statement in self.browse(cr, uid, ids, context):
44 for line in statement.line_ids:
46 account_bank_statement_line_obj.write(cr, uid, [line.id], {'sequence': seq}, context=context)
49 def _default_journal_id(self, cr, uid, context=None):
52 journal_pool = self.pool.get('account.journal')
53 journal_type = context.get('journal_type', False)
56 ids = journal_pool.search(cr, uid, [('type', '=', journal_type)])
61 def _end_balance(self, cursor, user, ids, name, attr, context=None):
62 res_currency_obj = self.pool.get('res.currency')
63 res_users_obj = self.pool.get('res.users')
66 company_currency_id = res_users_obj.browse(cursor, user, user,
67 context=context).company_id.currency_id.id
69 statements = self.browse(cursor, user, ids, context=context)
70 for statement in statements:
71 res[statement.id] = statement.balance_start
72 currency_id = statement.currency.id
73 for line in statement.move_line_ids:
75 if line.account_id.id == \
76 statement.journal_id.default_debit_account_id.id:
77 res[statement.id] += res_currency_obj.compute(cursor,
78 user, company_currency_id, currency_id,
79 line.debit, context=context)
81 if line.account_id.id == \
82 statement.journal_id.default_credit_account_id.id:
83 res[statement.id] -= res_currency_obj.compute(cursor,
84 user, company_currency_id, currency_id,
85 line.credit, context=context)
87 if statement.state in ('draft', 'open'):
88 for line in statement.line_ids:
89 res[statement.id] += line.amount
91 res[r] = round(res[r], 2)
94 def _get_period(self, cr, uid, context=None):
95 periods = self.pool.get('account.period').find(cr, uid)
100 def _currency(self, cursor, user, ids, name, args, context=None):
102 res_currency_obj = self.pool.get('res.currency')
103 res_users_obj = self.pool.get('res.users')
104 default_currency = res_users_obj.browse(cursor, user,
105 user, context=context).company_id.currency_id
106 for statement in self.browse(cursor, user, ids, context=context):
107 currency = statement.journal_id.currency
109 currency = default_currency
110 res[statement.id] = currency.id
112 for currency_id, currency_name in res_currency_obj.name_get(cursor,
113 user, [x for x in res.values()], context=context):
114 currency_names[currency_id] = currency_name
115 for statement_id in res.keys():
116 currency_id = res[statement_id]
117 res[statement_id] = (currency_id, currency_names[currency_id])
120 def _get_statement(self, cr, uid, ids, context=None):
122 for line in self.pool.get('account.bank.statement.line').browse(cr, uid, ids, context=context):
123 result[line.statement_id.id] = True
126 _order = "date desc, id desc"
127 _name = "account.bank.statement"
128 _description = "Bank Statement"
130 'name': fields.char('Name', 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
131 'date': fields.date('Date', required=True, states={'confirm': [('readonly', True)]}),
132 'journal_id': fields.many2one('account.journal', 'Journal', required=True,
133 readonly=True, states={'draft':[('readonly',False)]}),
134 'period_id': fields.many2one('account.period', 'Period', required=True,
135 states={'confirm':[('readonly', True)]}),
136 'balance_start': fields.float('Starting Balance', digits_compute=dp.get_precision('Account'),
137 states={'confirm':[('readonly',True)]}),
138 'balance_end_real': fields.float('Ending Balance', digits_compute=dp.get_precision('Account'),
139 states={'confirm': [('readonly', True)]}),
140 'balance_end': fields.function(_end_balance,
142 'account.bank.statement': (lambda self, cr, uid, ids, c={}: ids, ['line_ids','move_line_ids'], 10),
143 'account.bank.statement.line': (_get_statement, ['amount'], 10),
145 string="Computed Balance", help='Balance as calculated based on Starting Balance and transaction lines'),
146 'company_id': fields.related('journal_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True),
147 'line_ids': fields.one2many('account.bank.statement.line',
148 'statement_id', 'Statement lines',
149 states={'confirm':[('readonly', True)]}),
150 'move_line_ids': fields.one2many('account.move.line', 'statement_id',
151 'Entry lines', states={'confirm':[('readonly',True)]}),
152 'state': fields.selection([('draft', 'New'),
153 ('open','Open'), # used by cash statements
154 ('confirm', 'Closed')],
155 'State', required=True, readonly="1",
156 help='When new statement is created the state will be \'Draft\'.\n'
157 'And after getting confirmation from the bank it will be in \'Confirmed\' state.'),
158 'currency': fields.function(_currency, string='Currency',
159 type='many2one', relation='res.currency'),
160 '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.'),
165 'date': lambda *a: time.strftime('%Y-%m-%d'),
167 'journal_id': _default_journal_id,
168 'period_id': _get_period,
169 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.bank.statement',context=c),
172 def onchange_date(self, cr, user, ids, date, context=None):
174 Returns a dict that contains new values and context
175 @param cr: A database cursor
176 @param user: ID of the user currently logged in
177 @param date: latest value from user input for field date
178 @param args: other arguments
179 @param context: context arguments, like lang, time zone
180 @return: Returns a dict which contains new values, and context
183 period_pool = self.pool.get('account.period')
188 pids = period_pool.search(cr, user, [('date_start','<=',date), ('date_stop','>=',date)])
202 def button_dummy(self, cr, uid, ids, context=None):
203 return self.write(cr, uid, ids, {}, context=context)
205 def create_move_from_st_line(self, cr, uid, st_line_id, company_currency_id, st_line_number, context=None):
208 res_currency_obj = self.pool.get('res.currency')
209 account_move_obj = self.pool.get('account.move')
210 account_move_line_obj = self.pool.get('account.move.line')
211 account_bank_statement_line_obj = self.pool.get('account.bank.statement.line')
212 st_line = account_bank_statement_line_obj.browse(cr, uid, st_line_id, context=context)
213 st = st_line.statement_id
215 context.update({'date': st_line.date})
217 move_id = account_move_obj.create(cr, uid, {
218 'journal_id': st.journal_id.id,
219 'period_id': st.period_id.id,
220 'date': st_line.date,
221 'name': st_line_number,
223 account_bank_statement_line_obj.write(cr, uid, [st_line.id], {
224 'move_ids': [(4, move_id, False)]
228 if st_line.amount >= 0:
229 account_id = st.journal_id.default_credit_account_id.id
231 account_id = st.journal_id.default_debit_account_id.id
233 acc_cur = ((st_line.amount<=0) and st.journal_id.default_debit_account_id) or st_line.account_id
235 'res.currency.compute.account': acc_cur,
237 amount = res_currency_obj.compute(cr, uid, st.currency.id,
238 company_currency_id, st_line.amount, context=context)
241 'name': st_line.name,
242 'date': st_line.date,
245 'partner_id': ((st_line.partner_id) and st_line.partner_id.id) or False,
246 'account_id': (st_line.account_id) and st_line.account_id.id,
247 'credit': ((amount>0) and amount) or 0.0,
248 'debit': ((amount<0) and -amount) or 0.0,
249 'statement_id': st.id,
250 'journal_id': st.journal_id.id,
251 'period_id': st.period_id.id,
252 'currency_id': st.currency.id,
253 'analytic_account_id': st_line.analytic_account_id and st_line.analytic_account_id.id or False
256 if st.currency.id <> company_currency_id:
257 amount_cur = res_currency_obj.compute(cr, uid, company_currency_id,
258 st.currency.id, amount, context=context)
259 val['amount_currency'] = -amount_cur
261 if st_line.account_id and st_line.account_id.currency_id and st_line.account_id.currency_id.id <> company_currency_id:
262 val['currency_id'] = st_line.account_id.currency_id.id
263 amount_cur = res_currency_obj.compute(cr, uid, company_currency_id,
264 st_line.account_id.currency_id.id, amount, context=context)
265 val['amount_currency'] = -amount_cur
267 move_line_id = account_move_line_obj.create(cr, uid, val, context=context)
268 torec.append(move_line_id)
270 # Fill the secondary amount/currency
271 # if currency is not the same than the company
272 amount_currency = False
274 if st.currency.id <> company_currency_id:
275 amount_currency = st_line.amount
276 currency_id = st.currency.id
277 account_move_line_obj.create(cr, uid, {
278 'name': st_line.name,
279 'date': st_line.date,
282 'partner_id': ((st_line.partner_id) and st_line.partner_id.id) or False,
283 'account_id': account_id,
284 'credit': ((amount < 0) and -amount) or 0.0,
285 'debit': ((amount > 0) and amount) or 0.0,
286 'statement_id': st.id,
287 'journal_id': st.journal_id.id,
288 'period_id': st.period_id.id,
289 'amount_currency': amount_currency,
290 'currency_id': currency_id,
293 for line in account_move_line_obj.browse(cr, uid, [x.id for x in
294 account_move_obj.browse(cr, uid, move_id,
295 context=context).line_id],
297 if line.state <> 'valid':
298 raise osv.except_osv(_('Error !'),
299 _('Journal Item "%s" is not valid') % line.name)
301 # Bank statements will not consider boolean on journal entry_posted
302 account_move_obj.post(cr, uid, [move_id], context=context)
305 def get_next_st_line_number(self, cr, uid, st_number, st_line, context=None):
306 return st_number + '/' + str(st_line.sequence)
308 def balance_check(self, cr, uid, st_id, journal_type='bank', context=None):
309 st = self.browse(cr, uid, st_id, context=context)
310 if not (abs((st.balance_end or 0.0) - st.balance_end_real) < 0.0001):
311 raise osv.except_osv(_('Error !'),
312 _('The statement balance is incorrect !\nThe expected balance (%.2f) is different than the computed one. (%.2f)') % (st.balance_end_real, st.balance_end))
315 def statement_close(self, cr, uid, ids, journal_type='bank', context=None):
316 return self.write(cr, uid, ids, {'state':'confirm'}, context=context)
318 def check_status_condition(self, cr, uid, state, journal_type='bank'):
319 return state in ('draft','open')
321 def button_confirm_bank(self, cr, uid, ids, context=None):
322 obj_seq = self.pool.get('ir.sequence')
326 for st in self.browse(cr, uid, ids, context=context):
327 j_type = st.journal_id.type
328 company_currency_id = st.journal_id.company_id.currency_id.id
329 if not self.check_status_condition(cr, uid, st.state, journal_type=j_type):
332 self.balance_check(cr, uid, st.id, journal_type=j_type, context=context)
333 if (not st.journal_id.default_credit_account_id) \
334 or (not st.journal_id.default_debit_account_id):
335 raise osv.except_osv(_('Configuration Error !'),
336 _('Please verify that an account is defined in the journal.'))
338 if not st.name == '/':
341 if st.journal_id.sequence_id:
342 c = {'fiscalyear_id': st.period_id.fiscalyear_id.id}
343 st_number = obj_seq.next_by_id(cr, uid, st.journal_id.sequence_id.id, context=c)
345 st_number = obj_seq.next_by_code(cr, uid, 'account.bank.statement')
347 for line in st.move_line_ids:
348 if line.state <> 'valid':
349 raise osv.except_osv(_('Error !'),
350 _('The account entries lines are not in valid state.'))
351 for st_line in st.line_ids:
352 if st_line.analytic_account_id:
353 if not st.journal_id.analytic_journal_id:
354 raise osv.except_osv(_('No Analytic Journal !'),_("You have to define an analytic journal on the '%s' journal!") % (st.journal_id.name,))
355 if not st_line.amount:
357 st_line_number = self.get_next_st_line_number(cr, uid, st_number, st_line, context)
358 self.create_move_from_st_line(cr, uid, st_line.id, company_currency_id, st_line_number, context)
360 self.write(cr, uid, [st.id], {'name': st_number}, context=context)
361 self.log(cr, uid, st.id, _('Statement %s is confirmed, journal items are created.') % (st_number,))
362 return self.write(cr, uid, ids, {'state':'confirm'}, context=context)
364 def button_cancel(self, cr, uid, ids, context=None):
366 account_move_obj = self.pool.get('account.move')
367 for st in self.browse(cr, uid, ids, context=context):
368 if st.state=='draft':
371 for line in st.line_ids:
372 ids += [x.id for x in line.move_ids]
373 account_move_obj.unlink(cr, uid, ids, context)
375 return self.write(cr, uid, done, {'state':'draft'}, context=context)
377 def onchange_journal_id(self, cr, uid, statement_id, journal_id, context=None):
378 cr.execute('SELECT balance_end_real \
379 FROM account_bank_statement \
380 WHERE journal_id = %s AND NOT state = %s \
381 ORDER BY date DESC,id DESC LIMIT 1', (journal_id, 'draft'))
383 balance_start = res and res[0] or 0.0
384 account_id = self.pool.get('account.journal').read(cr, uid, journal_id, ['default_debit_account_id'], context=context)['default_debit_account_id']
385 return {'value': {'balance_start': balance_start, 'account_id': account_id}}
387 def unlink(self, cr, uid, ids, context=None):
388 stat = self.read(cr, uid, ids, ['state'], context=context)
391 if t['state'] in ('draft'):
392 unlink_ids.append(t['id'])
394 raise osv.except_osv(_('Invalid action !'), _('In order to delete a bank statement, you must first cancel it to delete related journal items.'))
395 osv.osv.unlink(self, cr, uid, unlink_ids, context=context)
398 def copy(self, cr, uid, id, default=None, context=None):
403 default = default.copy()
404 default['move_line_ids'] = []
405 return super(account_bank_statement, self).copy(cr, uid, id, default, context=context)
407 account_bank_statement()
409 class account_bank_statement_line(osv.osv):
411 def onchange_partner_id(self, cr, uid, ids, partner_id, context=None):
412 obj_partner = self.pool.get('res.partner')
417 part = obj_partner.browse(cr, uid, partner_id, context=context)
418 if not part.supplier and not part.customer:
420 elif part.supplier and part.customer:
423 if part.supplier == True:
425 if part.customer == True:
427 res_type = self.onchange_type(cr, uid, ids, partner_id=partner_id, type=type, context=context)
428 if res_type['value'] and res_type['value'].get('account_id', False):
429 return {'value': {'type': type, 'account_id': res_type['value']['account_id']}}
430 return {'value': {'type': type}}
432 def onchange_type(self, cr, uid, line_id, partner_id, type, context=None):
434 obj_partner = self.pool.get('res.partner')
440 line = self.browse(cr, uid, line_id, context=context)
441 if not line or (line and not line[0].account_id):
442 part = obj_partner.browse(cr, uid, partner_id, context=context)
443 if type == 'supplier':
444 account_id = part.property_account_payable.id
446 account_id = part.property_account_receivable.id
447 res['value']['account_id'] = account_id
450 _order = "statement_id desc, sequence"
451 _name = "account.bank.statement.line"
452 _description = "Bank Statement Line"
454 'name': fields.char('Communication', size=64, required=True),
455 'date': fields.date('Date', required=True),
456 'amount': fields.float('Amount', digits_compute=dp.get_precision('Account')),
457 'type': fields.selection([
458 ('supplier','Supplier'),
459 ('customer','Customer'),
460 ('general','General')
461 ], 'Type', required=True),
462 'partner_id': fields.many2one('res.partner', 'Partner'),
463 'account_id': fields.many2one('account.account','Account',
465 'statement_id': fields.many2one('account.bank.statement', 'Statement',
466 select=True, required=True, ondelete='cascade'),
467 'analytic_account_id': fields.many2one('account.analytic.account', 'Analytic Account'),
468 'move_ids': fields.many2many('account.move',
469 'account_bank_statement_line_move_rel', 'statement_line_id','move_id',
471 'ref': fields.char('Reference', size=32),
472 'note': fields.text('Notes'),
473 'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of bank statement lines."),
474 'company_id': fields.related('statement_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True),
477 'name': lambda self,cr,uid,context={}: self.pool.get('ir.sequence').get(cr, uid, 'account.bank.statement.line'),
478 'date': lambda self,cr,uid,context={}: context.get('date', time.strftime('%Y-%m-%d')),
482 account_bank_statement_line()
484 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: