[TYPO] Set the right category for the Point Of Sale
[odoo/odoo.git] / addons / account_coda / account_coda.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    
6 #    Copyright (c) 2011 Noviat nv/sa (www.noviat.be). All rights reserved.
7
8 #    This program is free software: you can redistribute it and/or modify
9 #    it under the terms of the GNU Affero General Public License as
10 #    published by the Free Software Foundation, either version 3 of the
11 #    License, or (at your option) any later version.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU Affero General Public License for more details.
17 #
18 #    You should have received a copy of the GNU Affero General Public License
19 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 #
21 ##############################################################################
22
23 from osv import osv, fields
24 import decimal_precision as dp
25 from tools.translate import _
26
27 class coda_bank_account(osv.osv):
28     _name= 'coda.bank.account'
29     _description= 'CODA Bank Account Configuration'
30
31     def _check_currency(self, cr, uid, ids, context=None):
32         obj_cba = self.browse(cr, uid, ids[0], context=context)
33         if (obj_cba.state == 'normal') and obj_cba.journal and (obj_cba.currency != obj_cba.journal.currency):
34             return False
35         return True
36
37     _columns = {
38         'name': fields.char('Name', size=64, required=True),
39         'bank_id': fields.many2one('res.partner.bank', 'Bank Account', required=True, 
40             help='Bank Account Number.\nThe CODA import function will find its CODA processing parameters on this number.'),
41         'description1': fields.char('Primary Account Description', size=35,
42             help='The Primary or Secondary Account Description should match the corresponding Account Description in the CODA file.'),
43         'description2': fields.char('Secondary Account Description', size=35,
44             help='The Primary or Secondary Account Description should match the corresponding Account Description in the CODA file.'),
45         'state': fields.selection([
46             ('normal', 'Normal'),
47             ('info', 'Info')], 
48             'Type', required=True, select=1,
49             help='No Bank Statements will be generated for CODA Bank Statements from Bank Accounts of type \'Info\'.'),
50         'journal': fields.many2one('account.journal', 'Journal', 
51             domain=[('type', '=', 'bank')], 
52             states={'normal':[('required',True)],'info':[('required',False)]},
53             help='Bank Journal for the Bank Statement'),
54         'currency': fields.many2one('res.currency', 'Currency', required=True,
55             help='The currency of the CODA Bank Statement'),  
56         'coda_st_naming': fields.char('Bank Statement Naming Policy', size=64,
57             help="Define the rules to create the name of the Bank Statements generated by the CODA processing." \
58                  "\nE.g. %(code)s%(y)s/%(paper)s"     
59                  "\n\nVariables:" \
60                  "\nBank Journal Code: %(code)s" \
61                  "\nCurrent Year with Century: %(year)s" \
62                  "\nCurrent Year without Century: %(y)s" \
63                  "\nCODA sequence number: %(coda)s" \
64                  "\nPaper Statement sequence number: %(paper)s"),
65         'def_payable': fields.many2one('account.account', 'Default Payable Account', domain=[('type', '=', 'payable')], required=True,
66             help= 'Set here the payable account that will be used, by default, if the partner is not found.'),
67         'def_receivable': fields.many2one('account.account', 'Default Receivable Account', domain=[('type', '=', 'receivable')], required=True,
68             help= 'Set here the receivable account that will be used, by default, if the partner is not found.',),
69         'awaiting_account': fields.many2one('account.account', 'Default Account for Unrecognized Movement', domain=[('type', '!=', 'view')], required=True,
70             help= 'Set here the default account that will be used if the partner cannot be unambiguously identified.'),
71         'transfer_account': fields.many2one('account.account', 'Default Internal Transfer Account', domain=[('code', 'like', '58%'), ('type', '!=', 'view')], required=True,
72             help= 'Set here the default account that will be used for internal transfer between own bank accounts (e.g. transfer between current and deposit bank accounts).'),
73         'find_bbacom': fields.boolean('Lookup Invoice', required=True, help='Partner lookup via the \'BBA\' Structured Communication field of the Invoice.'),
74         'find_partner': fields.boolean('Lookup Partner', required=True, help='Partner lookup via Bank Account Number.'),
75         'active': fields.boolean('Active', help='If the active field is set to False, it will allow you to hide the Bank Account without removing it.'),
76         'company_id': fields.many2one('res.company', 'Company', required=True),
77     }
78     _defaults = {
79         'currency': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.currency_id.id,
80         'state': 'normal',
81         'coda_st_naming': '%(code)s/%(y)s/%(coda)s',
82         'active': True,   
83         'find_bbacom': True,                         
84         'find_partner': True,                         
85         'company_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
86     }
87     _sql_constraints = [
88         ('account_uniq_1', 'unique (bank_id, description1, currency)', 'The combination of Bank Account, Account Description and Currency must be unique !'),
89         ('account_uniq_2', 'unique (bank_id, description2, currency)', 'The combination of Bank Account, Account Description and Currency must be unique !'),
90     ]
91     _constraints = [
92         (_check_currency, '\n\nConfiguration Error! \nThe Bank Account Currency should match the Journal Currency !', ['currency', 'journal']),
93     ]
94     _order = 'name'
95
96     def name_get(self, cr, uid, ids, context=None):
97         res = []
98         if not len(ids):
99             return res
100         for id in self.browse(cr, uid, ids, context=context):
101             res.append((id.id, (id.bank_id.iban or id.bank_id.acc_number) + ' (' + id.currency.name + ')' + \
102                 (id.description1 and (' - ' + id.description1) or '')))
103         return res
104
105     def copy(self, cr, uid, id, default=None, context=None):
106         cba = self.browse(cr, uid, id, context=context)
107         if not default:
108             default = {}
109         default = default.copy()
110         default.update({'journal_id': None})     
111         default['description1'] = cba['description1'] or ''
112         default['description2'] = cba['description2'] or ''
113         default['name'] = (cba['name'] or '') + ' (copy)'
114         default['state'] = cba['state']        
115         return super(coda_bank_account, self).copy(cr, uid, id, default, context) 
116
117     def onchange_state(self, cr, uid, ids, state):
118         return state =='info' and {'value': {'journal': None}} or {}
119
120 coda_bank_account()
121
122 class account_coda(osv.osv):
123     _name = 'account.coda'
124     _description = 'Object to store CODA Data Files'
125     _order = 'coda_creation_date desc'
126     _columns = {
127         'name': fields.char('CODA Filename',size=128, readonly=True),
128         'coda_data': fields.binary('CODA File', readonly=True),
129         'statement_ids': fields.one2many('coda.bank.statement','coda_id','Generated CODA Bank Statements', readonly=True),
130         'note': fields.text('Import Log', readonly=True),
131         'coda_creation_date': fields.date('CODA Creation Date', readonly=True, select=True),
132         'date': fields.date('Import Date', readonly=True, select=True),
133         'user_id': fields.many2one('res.users','User', readonly=True, select=True),
134         'company_id': fields.many2one('res.company', 'Company', readonly=True)
135     }
136     _defaults = {
137         'date': fields.date.context_today,
138         'user_id': lambda self,cr,uid,context: uid,
139         'company_id': lambda s,cr,uid,c: s.pool.get('res.company')._company_default_get(cr, uid, 'account.coda', context=c),
140     }        
141     _sql_constraints = [
142         ('coda_uniq', 'unique (name, coda_creation_date)', 'This CODA has already been imported !')
143     ]  
144
145     def unlink(self, cr, uid, ids, context=None):
146         if context is None:
147             context = {}
148         context.update({'coda_unlink': True})
149         coda_st_obj = self.pool.get('coda.bank.statement')
150         bank_st_obj = self.pool.get('account.bank.statement')
151         for coda in self.browse(cr, uid, ids, context=context):
152             for coda_statement in coda.statement_ids:                 
153                 if not context.get('coda_statement_unlink', False):
154                     if coda_st_obj.exists(cr, uid, coda_statement.id, context=context):
155                         coda_st_obj.unlink(cr, uid, [coda_statement.id], context=context)    
156                 if not context.get('bank_statement_unlink', False):
157                     if coda_st_obj.exists(cr, uid, coda_statement.id, context=context) and (coda_statement.type == 'normal') and bank_st_obj.exists(cr, uid, coda_statement.statement_id.id, context=context):
158                         bank_st_obj.unlink(cr, uid, [coda_statement.statement_id.id], context=context)                   
159         context.update({'coda_unlink': False})
160         return super(account_coda, self).unlink(cr, uid, ids, context=context)
161   
162 account_coda()
163
164 class account_coda_trans_type(osv.osv):  
165     _name = 'account.coda.trans.type'
166     _description = 'CODA transaction type'
167     _rec_name = 'type' 
168     _columns = {
169         'type': fields.char('Transaction Type', size=1, required=True),
170         'parent_id': fields.many2one('account.coda.trans.type', 'Parent'),
171         'description': fields.text('Description', translate=True),
172     }
173 account_coda_trans_type()
174
175 class account_coda_trans_code(osv.osv):  
176     _name = 'account.coda.trans.code'
177     _description = 'CODA transaction code'
178     _rec_name = 'code' 
179     _columns = {
180         'code': fields.char('Code', size=2, required=True, select=1),
181         'type': fields.selection([
182                 ('code', 'Transaction Code'),
183                 ('family', 'Transaction Family')], 
184                 'Type', required=True, select=1), 
185         'parent_id': fields.many2one('account.coda.trans.code', 'Family', select=1),
186         'description': fields.char('Description', size=128, translate=True, select=2),
187         'comment': fields.text('Comment', translate=True),
188     }
189 account_coda_trans_code()
190
191 class account_coda_trans_category(osv.osv):  
192     _name = 'account.coda.trans.category'
193     _description = 'CODA transaction category'
194     _rec_name = 'category' 
195     _columns = {
196         'category': fields.char('Transaction Category', size=3, required=True),
197         'description': fields.char('Description', size=256, translate=True),
198     }
199 account_coda_trans_category()
200
201 class account_coda_comm_type(osv.osv):  
202     _name = 'account.coda.comm.type'
203     _description = 'CODA structured communication type'
204     _rec_name = 'code' 
205     _columns = {
206         'code': fields.char('Structured Communication Type', size=3, required=True, select=1),
207         'description': fields.char('Description', size=128, translate=True),
208     }
209     _sql_constraints = [
210         ('code_uniq', 'unique (code)','The Structured Communication Code must be unique !')
211         ]
212 account_coda_comm_type()
213
214 class coda_bank_statement(osv.osv):
215     _name = 'coda.bank.statement' 
216     _description = 'CODA Bank Statement'    
217     
218     def _default_journal_id(self, cr, uid, context={}):
219         if context.get('journal_id', False):
220             return context['journal_id']
221         return False
222
223     def _end_balance(self, cursor, user, ids, name, attr, context=None):
224         res = {}
225         statements = self.browse(cursor, user, ids, context=context)
226         for statement in statements:
227             res[statement.id] = statement.balance_start
228             for line in statement.line_ids:
229                     res[statement.id] += line.amount
230         for r in res:
231             res[r] = round(res[r], 2)
232         return res
233
234     def _get_period(self, cr, uid, context={}):
235         periods = self.pool.get('account.period').find(cr, uid)
236         if periods:
237             return periods[0]
238         else:
239             return False
240
241     _order = 'date desc'
242     _columns = {
243         'name': fields.char('Name', size=64, required=True, readonly=True),
244         'date': fields.date('Date', required=True, readonly=True),
245         'coda_id': fields.many2one('account.coda', 'CODA Data File', ondelete='cascade'),
246         'type': fields.selection([
247             ('normal', 'Normal'),
248             ('info', 'Info')], 
249             'Type', required=True, readonly=True,
250             help='No Bank Statements are associated with CODA Bank Statements of type \'Info\'.'),
251         'statement_id': fields.many2one('account.bank.statement', 'Associated Bank Statement'),        
252         'journal_id': fields.many2one('account.journal', 'Journal', readonly=True, domain=[('type', '=', 'bank')]),
253         'coda_bank_account_id': fields.many2one('coda.bank.account', 'Bank Account', readonly=True),        
254         'period_id': fields.many2one('account.period', 'Period', required=True, readonly=True),
255         'balance_start': fields.float('Starting Balance', digits_compute=dp.get_precision('Account'), readonly=True),
256         'balance_end_real': fields.float('Ending Balance', digits_compute=dp.get_precision('Account'), readonly=True),
257         'balance_end': fields.function(_end_balance, method=True, store=True, string='Balance'),        
258         'line_ids': fields.one2many('coda.bank.statement.line',
259             'statement_id', 'CODA Bank Statement lines', readonly=True),
260         'currency': fields.many2one('res.currency', 'Currency', required=True, readonly=True,
261             help='The currency of the CODA Bank Statement'),
262         'company_id': fields.related('journal_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True),
263     }
264     _defaults = {
265         'type': 'normal',        
266         'currency': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.currency_id.id,
267         'journal_id': _default_journal_id,
268         'period_id': _get_period,
269     }
270
271     def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False):
272         if context is None: 
273             context = {}
274         res = super(coda_bank_statement, self).search(cr, uid, args=args, offset=offset, limit=limit, order=order,
275                 context=context, count=count)
276         if context.get('bank_statement', False) and not res:
277             raise osv.except_osv('Warning', _('No CODA Bank Statement found for this Bank Statement!'))
278         return res
279
280     def unlink(self, cr, uid, ids, context=None):
281         if context is None:
282             context = {}
283         context.update({'coda_statement_unlink': True})
284         coda_obj = self.pool.get('account.coda')
285         bank_st_obj = self.pool.get('account.bank.statement')
286         
287         # find all CODA bank statements that are associated with the selected CODA bank statements via a common CODA file
288         new_ids = []       
289         for coda_statement in self.browse(cr, uid, ids, context=context):
290             if coda_obj.exists(cr, uid, coda_statement.coda_id.id, context=context):
291                 new_ids += [x.id for x in coda_obj.browse(cr, uid, coda_statement.coda_id.id, context=context).statement_ids]
292
293         # unlink CODA banks statements as well as associated bank statements and CODA files               
294         for coda_statement in self.browse(cr, uid, new_ids, context=context):
295             if coda_statement.statement_id.state == 'confirm': 
296                 raise osv.except_osv(_('Invalid action !'),
297                     _("Cannot delete CODA Bank Statement '%s' of Journal '%s'." \
298                       "\nThe associated Bank Statement has already been confirmed !" \
299                       "\nPlease undo this action first!") \
300                       % (coda_statement.name, coda_statement.journal_id.name))
301             else:
302                 if not context.get('coda_unlink', False):
303                     if coda_statement.coda_id and coda_obj.exists(cr, uid, coda_statement.coda_id.id, context=context):
304                         coda_obj.unlink(cr, uid, [coda_statement.coda_id.id], context=context)
305                 if not context.get('bank_statement_unlink', False):
306                     if coda_statement.statement_id and bank_st_obj.exists(cr, uid, coda_statement.statement_id.id, context=context):
307                         bank_st_obj.unlink(cr, uid, [coda_statement.statement_id.id], context=context)    
308
309         context.update({'coda_statement_unlink': False})
310         return super(coda_bank_statement, self).unlink(cr, uid, new_ids, context=context)
311  
312 coda_bank_statement()
313
314 class account_bank_statement(osv.osv):
315     _inherit = 'account.bank.statement'
316     _columns = {
317         'coda_statement_id': fields.many2one('coda.bank.statement', 'Associated CODA Bank Statement'),
318     }
319     
320     def unlink(self, cr, uid, ids, context=None):
321         if context is None:
322             context = {}
323         context.update({'bank_statement_unlink': True})
324         coda_obj = self.pool.get('account.coda')
325         coda_st_obj = self.pool.get('coda.bank.statement')
326
327         # find all statements that are associated with the selected bank statements via a common CODA file
328         ids_plus = []       
329         for statement in self.browse(cr, uid, ids, context=context):
330             if statement.coda_statement_id:
331                 for x in coda_obj.browse(cr, uid, statement.coda_statement_id.coda_id.id, context=context).statement_ids:
332                     if x.type == 'normal':
333                         ids_plus += [x.statement_id.id]
334                 
335         # unlink banks statements as well as associated CODA bank statements and CODA files
336         for statement in self.browse(cr, uid, ids_plus, context=context):       
337             if not context.get('coda_statement_unlink', False):
338                 if statement.coda_statement_id and coda_st_obj.exists(cr, uid, statement.coda_statement_id.id, context=context):
339                     coda_st_obj.unlink(cr, uid, [statement.coda_statement_id.id], context=context)
340             if not context.get('coda_unlink', False):
341                 if statement.coda_statement_id \
342                     and coda_st_obj.exists(cr, uid, statement.coda_statement_id.id, context=context) \
343                     and statement.coda_statement_id.coda_id \
344                     and coda_obj.exists(cr, uid, statement.coda_statement_id.coda_id.id, context=context):
345                         coda_obj.unlink(cr, uid, [statement.coda_statement_id.coda_id.id], context=context)
346
347         context.update({'bank_statement_unlink': False})
348         new_ids = list(set(ids + ids_plus))
349         return super(account_bank_statement, self).unlink(cr, uid, new_ids, context=context)
350          
351 account_bank_statement()
352
353 class coda_bank_statement_line(osv.osv):
354     _name = 'coda.bank.statement.line'     
355     _order = 'sequence'   
356     _description = 'CODA Bank Statement Line'
357     _columns = {
358         'name': fields.char('Communication', size=268, required=True),
359         'sequence': fields.integer('Sequence'),
360         'date': fields.date('Entry Date', required=True),
361         'val_date': fields.date('Valuta Date'),        
362         'account_id': fields.many2one('account.account','Account'),     # remove required=True
363         'type': fields.selection([
364             ('supplier','Supplier'),
365             ('customer','Customer'),
366             ('general','General'),
367             ('globalisation','Globalisation'),            
368             ('information','Information'),    
369             ('communication','Free Communication'),          
370             ], 'Type', required=True),
371         'globalisation_level': fields.integer('Globalisation Level', 
372                 help="The value which is mentioned (1 to 9), specifies the hierarchy level"
373                      " of the globalisation of which this record is the first."
374                      "\nThe same code will be repeated at the end of the globalisation."),
375         'globalisation_amount': fields.float('Globalisation Amount', digits_compute=dp.get_precision('Account')),      
376         'globalisation_id': fields.many2one('account.bank.statement.line.global', 'Globalisation ID', readonly=True,
377             help="Code to identify transactions belonging to the same globalisation level within a batch payment"),                                                     
378         'amount': fields.float('Amount', digits_compute=dp.get_precision('Account')),
379         'partner_id': fields.many2one('res.partner', 'Partner'),
380         'counterparty_name': fields.char('Counterparty Name', size=35),
381         'counterparty_bic': fields.char('Counterparty BIC', size=11),                     
382         'counterparty_number': fields.char('Counterparty Number', size=34),   
383         'counterparty_currency': fields.char('Counterparty Currency', size=3), 
384         'statement_id': fields.many2one('coda.bank.statement', 'CODA Bank Statement',
385             select=True, required=True, ondelete='cascade'),
386         'coda_bank_account_id': fields.related('statement_id', 'coda_bank_account_id', type='many2one', relation='coda.bank.account', string='Bank Account', store=True, readonly=True),
387         'ref': fields.char('Reference', size=32),
388         'note': fields.text('Notes'),
389         'company_id': fields.related('statement_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True),        
390     }
391
392     def unlink(self, cr, uid, ids, context=None):
393         if context is None:
394             context = {}
395         if context.get('block_statement_line_delete', False):
396             raise osv.except_osv('Warning', _('Delete operation not allowed !'))
397         return super(account_bank_statement_line, self).unlink(cr, uid, ids, context=context)
398
399 coda_bank_statement_line()       
400
401 class account_bank_statement_line_global(osv.osv):
402     _inherit = 'account.bank.statement.line.global'
403     _columns = {
404         'coda_statement_line_ids': fields.one2many('coda.bank.statement.line', 'globalisation_id', 'CODA Bank Statement Lines', readonly=True),
405     }
406 account_bank_statement_line_global()
407
408 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: