You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

683 lines
26 KiB

  1. # -*- coding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # Copyright (C) 2009 EduSense BV (<http://www.edusense.nl>).
  5. # (C) 2011 - 2013 Therp BV (<http://therp.nl>).
  6. #
  7. # All other contributions are (C) by their respective contributors
  8. #
  9. # All Rights Reserved
  10. #
  11. # This program is free software: you can redistribute it and/or modify
  12. # it under the terms of the GNU Affero General Public License as
  13. # published by the Free Software Foundation, either version 3 of the
  14. # License, or (at your option) any later version.
  15. #
  16. # This program is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. # GNU Affero General Public License for more details.
  20. #
  21. # You should have received a copy of the GNU Affero General Public License
  22. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. #
  24. ##############################################################################
  25. '''
  26. This module shows resemblance to both account_bankimport/bankimport.py,
  27. account/account_bank_statement.py and account_payment(_export). All hail to
  28. the makers. account_bankimport is only referenced for their ideas and the
  29. framework of the filters, which they in their turn seem to have derived
  30. from account_coda.
  31. Modifications are extensive:
  32. 1. In relation to account/account_bank_statement.py:
  33. account.bank.statement is effectively stripped from its account.period
  34. association, while account.bank.statement.line is extended with the same
  35. association, thereby reflecting real world usage of bank.statement as a
  36. list of bank transactions and bank.statement.line as a bank transaction.
  37. 2. In relation to account/account_bankimport:
  38. All filter objects and extensions to res.company are removed. Instead a
  39. flexible auto-loading and auto-browsing plugin structure is created,
  40. whereby business logic and encoding logic are strictly separated.
  41. Both parsers and business logic are rewritten from scratch.
  42. The association of account.journal with res.company is replaced by an
  43. association of account.journal with res.partner.bank, thereby allowing
  44. multiple bank accounts per company and one journal per bank account.
  45. The imported bank statement file does not result in a single 'bank
  46. statement', but in a list of bank statements by definition of whatever the
  47. bank sees as a statement. Every imported bank statement contains at least
  48. one bank transaction, which is a modded account.bank.statement.line.
  49. 3. In relation to account_payment:
  50. An additional state was inserted between 'open' and 'done', to reflect a
  51. exported bank orders file which was not reported back through statements.
  52. The import of statements matches the payments and reconciles them when
  53. needed, flagging them 'done'. When no export wizards are found, the
  54. default behavior is to flag the orders as 'sent', not as 'done'.
  55. Rejected payments from the bank receive on import the status 'rejected'.
  56. '''
  57. from openerp.osv import orm, fields
  58. from openerp.osv.osv import except_osv
  59. from openerp.tools.translate import _
  60. from openerp import netsvc
  61. from openerp.addons.decimal_precision import decimal_precision as dp
  62. class account_banking_account_settings(orm.Model):
  63. '''Default Journal for Bank Account'''
  64. _name = 'account.banking.account.settings'
  65. _description = __doc__
  66. _columns = {
  67. 'company_id': fields.many2one('res.company', 'Company', select=True,
  68. required=True),
  69. 'partner_bank_id': fields.many2one('res.partner.bank', 'Bank Account',
  70. select=True, required=True),
  71. 'journal_id': fields.many2one('account.journal', 'Journal',
  72. required=True),
  73. 'partner_id': fields.related(
  74. 'company_id', 'partner_id',
  75. type='many2one', relation='res.partner',
  76. string='Partner'),
  77. 'default_credit_account_id': fields.many2one(
  78. 'account.account', 'Default credit account', select=True,
  79. help=('The account to use when an unexpected payment was signaled.'
  80. ' This can happen when a direct debit payment is cancelled '
  81. 'by a customer, or when no matching payment can be found. '
  82. 'Mind that you can correct movements before confirming them.'
  83. ),
  84. required=True
  85. ),
  86. 'default_debit_account_id': fields.many2one(
  87. 'account.account', 'Default debit account',
  88. select=True, required=True,
  89. help=('The account to use when an unexpected payment is received. '
  90. 'This can be needed when a customer pays in advance or when '
  91. 'no matching invoice can be found. Mind that you can '
  92. 'correct movements before confirming them.'
  93. ),
  94. ),
  95. 'costs_account_id': fields.many2one(
  96. 'account.account', 'Bank Costs Account', select=True,
  97. help=('The account to use when the bank invoices its own costs. '
  98. 'Leave it blank to disable automatic invoice generation '
  99. 'on bank costs.'
  100. ),
  101. ),
  102. 'invoice_journal_id': fields.many2one(
  103. 'account.journal', 'Costs Journal',
  104. help=('This is the journal used to create invoices for bank costs.'
  105. ),
  106. ),
  107. 'bank_partner_id': fields.many2one(
  108. 'res.partner', 'Bank Partner',
  109. help=('The partner to use for bank costs. Banks are not partners '
  110. 'by default. You will most likely have to create one.'
  111. ),
  112. ),
  113. }
  114. def _default_company(self, cr, uid, context=None):
  115. """
  116. Return the user's company or the first company found
  117. in the database
  118. """
  119. user = self.pool.get('res.users').read(
  120. cr, uid, uid, ['company_id'], context=context)
  121. if user['company_id']:
  122. return user['company_id'][0]
  123. return self.pool.get('res.company').search(
  124. cr, uid, [('parent_id', '=', False)])[0]
  125. def _default_partner_id(self, cr, uid, context=None, company_id=False):
  126. if not company_id:
  127. company_id = self._default_company(cr, uid, context=context)
  128. return self.pool.get('res.company').read(
  129. cr, uid, company_id, ['partner_id'],
  130. context=context)['partner_id'][0]
  131. def _default_journal(self, cr, uid, context=None, company_id=False):
  132. if not company_id:
  133. company_id = self._default_company(cr, uid, context=context)
  134. journal_ids = self.pool.get('account.journal').search(
  135. cr, uid, [('type', '=', 'bank'), ('company_id', '=', company_id)])
  136. return journal_ids and journal_ids[0] or False
  137. def _default_partner_bank_id(
  138. self, cr, uid, context=None, company_id=False):
  139. if not company_id:
  140. company_id = self._default_company(cr, uid, context=context)
  141. partner_id = self.pool.get('res.company').read(
  142. cr, uid, company_id, ['partner_id'],
  143. context=context)['partner_id'][0]
  144. bank_ids = self.pool.get('res.partner.bank').search(
  145. cr, uid, [('partner_id', '=', partner_id)], context=context)
  146. return bank_ids and bank_ids[0] or False
  147. def _default_debit_account_id(
  148. self, cr, uid, context=None, company_id=False):
  149. localcontext = context and context.copy() or {}
  150. localcontext['force_company'] = (
  151. company_id or self._default_company(cr, uid, context=context))
  152. account_def = self.pool.get('ir.property').get(
  153. cr, uid, 'property_account_receivable',
  154. 'res.partner', context=localcontext)
  155. return account_def and account_def.id or False
  156. def _default_credit_account_id(
  157. self, cr, uid, context=None, company_id=False):
  158. localcontext = context and context.copy() or {}
  159. localcontext['force_company'] = (
  160. company_id or self._default_company(cr, uid, context=context))
  161. account_def = self.pool.get('ir.property').get(
  162. cr, uid, 'property_account_payable',
  163. 'res.partner', context=localcontext)
  164. return account_def and account_def.id or False
  165. def find(self, cr, uid, journal_id, partner_bank_id=False, context=None):
  166. domain = [('journal_id', '=', journal_id)]
  167. if partner_bank_id:
  168. domain.append(('partner_bank_id', '=', partner_bank_id))
  169. return self.search(cr, uid, domain, context=context)
  170. def onchange_partner_bank_id(
  171. self, cr, uid, ids, partner_bank_id, context=None):
  172. values = {}
  173. if partner_bank_id:
  174. bank = self.pool.get('res.partner.bank').read(
  175. cr, uid, partner_bank_id, ['journal_id'], context=context)
  176. if bank['journal_id']:
  177. values['journal_id'] = bank['journal_id'][0]
  178. return {'value': values}
  179. def onchange_company_id(
  180. self, cr, uid, ids, company_id=False, context=None):
  181. if not company_id:
  182. return {}
  183. result = {
  184. 'partner_id': self._default_partner_id(
  185. cr, uid, company_id=company_id, context=context),
  186. 'journal_id': self._default_journal(
  187. cr, uid, company_id=company_id, context=context),
  188. 'default_debit_account_id': self._default_debit_account_id(
  189. cr, uid, company_id=company_id, context=context),
  190. 'default_credit_account_id': self._default_credit_account_id(
  191. cr, uid, company_id=company_id, context=context),
  192. }
  193. return {'value': result}
  194. _defaults = {
  195. 'company_id': _default_company,
  196. 'partner_id': _default_partner_id,
  197. 'journal_id': _default_journal,
  198. 'default_debit_account_id': _default_debit_account_id,
  199. 'default_credit_account_id': _default_credit_account_id,
  200. 'partner_bank_id': _default_partner_bank_id,
  201. }
  202. account_banking_account_settings()
  203. class account_banking_imported_file(orm.Model):
  204. '''Imported Bank Statements File'''
  205. _name = 'account.banking.imported.file'
  206. _description = __doc__
  207. _rec_name = 'date'
  208. _columns = {
  209. 'company_id': fields.many2one(
  210. 'res.company',
  211. 'Company',
  212. select=True,
  213. readonly=True,
  214. ),
  215. 'date': fields.datetime(
  216. 'Import Date',
  217. readonly=True,
  218. select=True,
  219. states={'draft': [('readonly', False)]},
  220. ),
  221. 'format': fields.char(
  222. 'File Format',
  223. size=20,
  224. readonly=True,
  225. states={'draft': [('readonly', False)]},
  226. ),
  227. 'file': fields.binary(
  228. 'Raw Data',
  229. readonly=True,
  230. states={'draft': [('readonly', False)]},
  231. ),
  232. 'file_name': fields.char('File name', size=256),
  233. 'log': fields.text(
  234. 'Import Log',
  235. readonly=True,
  236. states={'draft': [('readonly', False)]},
  237. ),
  238. 'user_id': fields.many2one(
  239. 'res.users',
  240. 'Responsible User',
  241. readonly=True,
  242. select=True,
  243. states={'draft': [('readonly', False)]},
  244. ),
  245. 'state': fields.selection(
  246. [
  247. ('unfinished', 'Unfinished'),
  248. ('error', 'Error'),
  249. ('review', 'Review'),
  250. ('ready', 'Finished'),
  251. ],
  252. 'State',
  253. select=True,
  254. readonly=True,
  255. ),
  256. 'statement_ids': fields.one2many(
  257. 'account.bank.statement',
  258. 'banking_id',
  259. 'Statements',
  260. readonly=False,
  261. ),
  262. }
  263. _defaults = {
  264. 'date': fields.date.context_today,
  265. 'user_id': lambda self, cr, uid, context: uid,
  266. }
  267. account_banking_imported_file()
  268. class account_bank_statement(orm.Model):
  269. '''
  270. Implement changes to this model for the following features:
  271. * bank statement lines have their own period_id, derived from
  272. their effective date. The period and date are propagated to
  273. the move lines created from each statement line
  274. * bank statement lines have their own state. When a statement
  275. is confirmed, all lines are confirmed too. When a statement
  276. is reopened, lines remain confirmed until reopened individually.
  277. * upon confirmation of a statement line, the move line is
  278. created and reconciled according to the matched entry(/ies)
  279. '''
  280. _inherit = 'account.bank.statement'
  281. _columns = {
  282. 'period_id': fields.many2one(
  283. 'account.period',
  284. 'Period',
  285. required=False,
  286. readonly=True,
  287. ),
  288. 'banking_id': fields.many2one(
  289. 'account.banking.imported.file',
  290. 'Imported File',
  291. readonly=True,
  292. ),
  293. }
  294. _defaults = {
  295. 'period_id': False,
  296. }
  297. def _check_company_id(self, cr, uid, ids, context=None):
  298. """
  299. Adapt this constraint method from the account module to reflect the
  300. move of period_id to the statement line: also check the periods of the
  301. lines. Update the statement period if it does not have one yet.
  302. Don't call super, because its check is integrated below and
  303. it will break if a statement does not have any lines yet and
  304. therefore may not have a period.
  305. """
  306. for statement in self.browse(cr, uid, ids, context=context):
  307. if (statement.period_id and
  308. statement.company_id != statement.period_id.company_id):
  309. return False
  310. for line in statement.line_ids:
  311. if (line.period_id and
  312. statement.company_id != line.period_id.company_id):
  313. return False
  314. if not statement.period_id:
  315. statement.write({'period_id': line.period_id.id})
  316. statement.refresh()
  317. return True
  318. # Redefine the constraint, or it still refer to the original method
  319. _constraints = [
  320. (_check_company_id,
  321. 'The journal and period chosen have to belong to the same company.',
  322. ['journal_id', 'period_id']),
  323. ]
  324. def _get_period(self, cr, uid, date=False, context=None):
  325. """
  326. Used in statement line's _defaults, so it is always triggered
  327. on installation or module upgrade even if there are no records
  328. without a value. For that reason, we need
  329. to be tolerant and allow for the situation in which no period
  330. exists for the current date (i.e. when no date is specified).
  331. Cannot be used directly as a defaults method due to lp:1296229
  332. """
  333. local_ctx = dict(context or {}, account_period_prefer_normal=True)
  334. try:
  335. return self.pool.get('account.period').find(
  336. cr, uid, dt=date, context=local_ctx)[0]
  337. except except_osv:
  338. if date:
  339. raise
  340. return False
  341. def _prepare_move(
  342. self, cr, uid, st_line, st_line_number, context=None):
  343. """
  344. Add the statement line's period to the move, overwriting
  345. the period on the statement
  346. """
  347. res = super(account_bank_statement, self)._prepare_move(
  348. cr, uid, st_line, st_line_number, context=context)
  349. if context and context.get('period_id'):
  350. res['period_id'] = context['period_id']
  351. return res
  352. def _prepare_move_line_vals(
  353. self, cr, uid, st_line, move_id, debit, credit, currency_id=False,
  354. amount_currency=False, account_id=False, analytic_id=False,
  355. partner_id=False, context=None):
  356. """
  357. Add the statement line's period to the move lines, overwriting
  358. the period on the statement
  359. """
  360. res = super(account_bank_statement, self)._prepare_move_line_vals(
  361. cr, uid, st_line, move_id, debit, credit, currency_id=currency_id,
  362. amount_currency=amount_currency, account_id=account_id,
  363. analytic_id=analytic_id, partner_id=partner_id, context=context)
  364. if context and context.get('period_id'):
  365. res['period_id'] = context['period_id']
  366. return res
  367. def create_move_from_st_line(self, cr, uid, st_line_id,
  368. company_currency_id, st_line_number,
  369. context=None):
  370. if context is None:
  371. context = {}
  372. account_move_obj = self.pool.get('account.move')
  373. account_move_line_obj = self.pool.get('account.move.line')
  374. account_bank_statement_line_obj = self.pool.get(
  375. 'account.bank.statement.line')
  376. st_line = account_bank_statement_line_obj.browse(
  377. cr, uid, st_line_id, context=context)
  378. # Take period from statement line and write to context
  379. # this will be picked up by the _prepare_move* methods
  380. period_id = self._get_period(
  381. cr, uid, date=st_line.date, context=context)
  382. localctx = context.copy()
  383. localctx['period_id'] = period_id
  384. # Write date & period on the voucher, delegate to account_voucher's
  385. # override of this method. Then post the related move and return.
  386. if st_line.voucher_id:
  387. voucher_pool = self.pool.get('account.voucher')
  388. voucher_pool.write(
  389. cr, uid, [st_line.voucher_id.id], {
  390. 'date': st_line.date,
  391. 'period_id': period_id,
  392. }, context=context)
  393. res = super(account_bank_statement, self).create_move_from_st_line(
  394. cr, uid, st_line_id, company_currency_id, st_line_number,
  395. context=localctx)
  396. st_line.refresh()
  397. if st_line.voucher_id:
  398. if not st_line.voucher_id.journal_id.entry_posted:
  399. account_move_obj.post(
  400. cr, uid, [st_line.voucher_id.move_id.id], context={})
  401. else:
  402. # Write stored reconcile_id and pay invoices through workflow
  403. if st_line.reconcile_id:
  404. move_ids = [move.id for move in st_line.move_ids]
  405. torec = account_move_line_obj.search(
  406. cr, uid, [
  407. ('move_id', 'in', move_ids),
  408. ('account_id', '=', st_line.account_id.id)],
  409. context=context)
  410. account_move_line_obj.write(cr, uid, torec, {
  411. (st_line.reconcile_id.line_partial_ids
  412. and 'reconcile_partial_id'
  413. or 'reconcile_id'): st_line.reconcile_id.id
  414. }, context=context)
  415. for move_line in (st_line.reconcile_id.line_id or []) + (
  416. st_line.reconcile_id.line_partial_ids or []):
  417. netsvc.LocalService("workflow").trg_trigger(
  418. uid, 'account.move.line', move_line.id, cr)
  419. return res
  420. def button_confirm_bank(self, cr, uid, ids, context=None):
  421. """
  422. Assign journal sequence to statements without a name
  423. """
  424. if context is None:
  425. context = {}
  426. obj_seq = self.pool.get('ir.sequence')
  427. if ids and isinstance(ids, (int, long)):
  428. ids = [ids]
  429. noname_ids = self.search(
  430. cr, uid, [('id', 'in', ids), ('name', '=', '/')],
  431. context=context)
  432. for st in self.browse(cr, uid, noname_ids, context=context):
  433. if st.journal_id.sequence_id:
  434. period_id = self._get_period(
  435. cr, uid, date=st.date, context=context)
  436. year = self.pool.get('account.period').browse(
  437. cr, uid, period_id, context=context).fiscalyear_id.id
  438. c = {'fiscalyear_id': year}
  439. st_number = obj_seq.get_id(
  440. cr, uid, st.journal_id.sequence_id.id, context=c)
  441. self.write(
  442. cr, uid, ids, {'name': st_number}, context=context)
  443. return super(account_bank_statement, self).button_confirm_bank(
  444. cr, uid, ids, context)
  445. class account_voucher(orm.Model):
  446. _inherit = 'account.voucher'
  447. def _get_period(self, cr, uid, context=None):
  448. if context is None:
  449. context = {}
  450. if not context.get('period_id') and context.get('move_line_ids'):
  451. move_line = self.pool.get('account.move.line').browse(
  452. cr, uid, context.get('move_line_ids')[0], context=context)
  453. return move_line.period_id.id
  454. return super(account_voucher, self)._get_period(cr, uid, context)
  455. class account_bank_statement_line(orm.Model):
  456. '''
  457. Extension on basic class:
  458. 1. Extra links to account.period and res.partner.bank for tracing and
  459. matching.
  460. 2. Extra 'trans' field to carry the transaction id of the bank.
  461. 3. Readonly states for most fields except when in draft.
  462. '''
  463. _inherit = 'account.bank.statement.line'
  464. _description = 'Bank Transaction'
  465. def _get_period(self, cr, uid, date=False, context=None):
  466. return self.pool['account.bank.statement']._get_period(
  467. cr, uid, date=date, context=context)
  468. def _get_period_context(self, cr, uid, context=None):
  469. """
  470. Workaround for lp:1296229, context is passed positionally
  471. """
  472. return self._get_period(cr, uid, context=context)
  473. def _get_currency(self, cr, uid, context=None):
  474. '''
  475. Get the default currency (required to allow other modules to function,
  476. which assume currency to be a calculated field and thus optional)
  477. Remark: this is only a fallback as the real default is in the journal,
  478. which is inaccessible from within this method.
  479. '''
  480. res_users_obj = self.pool.get('res.users')
  481. return res_users_obj.browse(
  482. cr, uid, uid, context=context).company_id.currency_id.id
  483. def _get_invoice_id(self, cr, uid, ids, name, args, context=None):
  484. res = {}
  485. for st_line in self.browse(cr, uid, ids, context):
  486. res[st_line.id] = False
  487. for move_line in (
  488. st_line.reconcile_id and
  489. (st_line.reconcile_id.line_id or
  490. st_line.reconcile_id.line_partial_ids) or
  491. st_line.import_transaction_id and
  492. st_line.import_transaction_id.move_line_id and
  493. [st_line.import_transaction_id.move_line_id] or []):
  494. if move_line.invoice:
  495. res[st_line.id] = move_line.invoice.id
  496. continue
  497. return res
  498. _columns = {
  499. # Redefines. Todo: refactor away to view attrs
  500. 'amount': fields.float(
  501. 'Amount',
  502. readonly=True,
  503. digits_compute=dp.get_precision('Account'),
  504. states={'draft': [('readonly', False)]},
  505. ),
  506. 'ref': fields.char(
  507. 'Ref.',
  508. size=32,
  509. readonly=True,
  510. states={'draft': [('readonly', False)]},
  511. ),
  512. 'name': fields.char(
  513. 'Name',
  514. size=64,
  515. required=False,
  516. readonly=True,
  517. states={'draft': [('readonly', False)]},
  518. ),
  519. 'date': fields.date(
  520. 'Date',
  521. required=True,
  522. readonly=True,
  523. states={'draft': [('readonly', False)]},
  524. ),
  525. # New columns
  526. 'trans': fields.char(
  527. 'Bank Transaction ID',
  528. size=15,
  529. required=False,
  530. readonly=True,
  531. states={'draft': [('readonly', False)]},
  532. ),
  533. 'partner_bank_id': fields.many2one(
  534. 'res.partner.bank',
  535. 'Bank Account',
  536. required=False,
  537. readonly=True,
  538. states={'draft': [('readonly', False)]},
  539. ),
  540. 'period_id': fields.many2one(
  541. 'account.period',
  542. 'Period',
  543. required=True,
  544. states={'confirmed': [('readonly', True)]},
  545. ),
  546. 'currency': fields.many2one(
  547. 'res.currency',
  548. 'Currency',
  549. required=True,
  550. states={'confirmed': [('readonly', True)]},
  551. ),
  552. 'reconcile_id': fields.many2one(
  553. 'account.move.reconcile',
  554. 'Reconciliation',
  555. readonly=True,
  556. ),
  557. 'invoice_id': fields.function(
  558. _get_invoice_id,
  559. method=True,
  560. string='Linked Invoice',
  561. type='many2one',
  562. relation='account.invoice',
  563. ),
  564. }
  565. _defaults = {
  566. 'period_id': _get_period_context,
  567. 'currency': _get_currency,
  568. }
  569. class invoice(orm.Model):
  570. '''
  571. Create other reference types as well.
  572. Descendant classes can extend this function to add more reference
  573. types, ie.
  574. def _get_reference_type(self, cr, uid, context=None):
  575. return super(my_class, self)._get_reference_type(cr, uid,
  576. context=context) + [('my_ref', _('My reference')]
  577. Don't forget to redefine the column "reference_type" as below or
  578. your method will never be triggered.
  579. TODO: move 'structured' part to account_banking_payment module
  580. where it belongs
  581. '''
  582. _inherit = 'account.invoice'
  583. def test_undo_paid(self, cr, uid, ids, context=None):
  584. """
  585. Called from the workflow. Used to unset paid state on
  586. invoices that were paid with bank transfers which are being cancelled
  587. """
  588. for invoice in self.read(cr, uid, ids, ['reconciled'], context):
  589. if invoice['reconciled']:
  590. return False
  591. return True
  592. def _get_reference_type(self, cr, uid, context=None):
  593. '''
  594. Return the list of reference types
  595. '''
  596. return [('none', _('Free Reference')),
  597. ('structured', _('Structured Reference')),
  598. ]
  599. _columns = {
  600. 'reference_type': fields.selection(_get_reference_type,
  601. 'Reference Type', required=True
  602. )
  603. }
  604. class account_move_line(orm.Model):
  605. _inherit = "account.move.line"
  606. def get_balance(self, cr, uid, ids, context=None):
  607. """
  608. Return the balance of any set of move lines.
  609. Not to be confused with the 'balance' field on this model, which
  610. returns the account balance that the move line applies to.
  611. """
  612. total = 0.0
  613. if not ids:
  614. return total
  615. for line in self.read(
  616. cr, uid, ids, ['debit', 'credit'], context=context):
  617. total += (line['debit'] or 0.0) - (line['credit'] or 0.0)
  618. return total