1 # -*- encoding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
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 General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 ##############################################################################
25 from osv import fields, osv
27 from tools.misc import currency
28 from tools.translate import _
31 from mx.DateTime import RelativeDateTime, now, DateTime, localtime
34 class account_payment_term(osv.osv):
35 _name = "account.payment.term"
36 _description = "Payment Term"
38 'name': fields.char('Payment Term', size=64, translate=True, required=True),
39 'active': fields.boolean('Active'),
40 'note': fields.text('Description', translate=True),
41 'line_ids': fields.one2many('account.payment.term.line', 'payment_id', 'Terms'),
44 'active': lambda *a: 1,
48 def compute(self, cr, uid, id, value, date_ref=False, context={}):
50 date_ref = now().strftime('%Y-%m-%d')
51 pt = self.browse(cr, uid, id, context)
54 for line in pt.line_ids:
55 if line.value == 'fixed':
56 amt = round(line.value_amount, 2)
57 elif line.value == 'procent':
58 amt = round(value * line.value_amount, 2)
59 elif line.value == 'balance':
60 amt = round(amount, 2)
62 next_date = mx.DateTime.strptime(date_ref, '%Y-%m-%d') + RelativeDateTime(days=line.days)
64 next_date += RelativeDateTime(day=line.days2)
66 next_date += RelativeDateTime(day=line.days2, months=1)
67 result.append( (next_date.strftime('%Y-%m-%d'), amt) )
71 account_payment_term()
73 class account_payment_term_line(osv.osv):
74 _name = "account.payment.term.line"
75 _description = "Payment Term Line"
77 'name': fields.char('Line Name', size=32, required=True),
78 'sequence': fields.integer('Sequence', required=True, help="The sequence field is used to order the payment term lines from the lowest sequences to the higher ones"),
79 'value': fields.selection([('procent', 'Percent'), ('balance', 'Balance'), ('fixed', 'Fixed Amount')], 'Value',required=True),
80 'value_amount': fields.float('Value Amount'),
81 'days': fields.integer('Number of Days', required=True, help="Number of days to add before computation of the day of month." \
82 "If Date=15/01, Number of Days=22, Day of Month=-1, then the due date is 28/02."),
83 'days2': fields.integer('Day of the Month', required=True, help="Day of the month, set -1 for the last day of the current month. If it's positive, it gives the day of the next month. Set 0 for net days (otherwise it's based on the beginning of the month)."),
84 'payment_id': fields.many2one('account.payment.term', 'Payment Term', required=True, select=True),
87 'value': lambda *a: 'balance',
88 'sequence': lambda *a: 5,
89 'days2': lambda *a: 0,
92 account_payment_term_line()
95 class account_account_type(osv.osv):
96 _name = "account.account.type"
97 _description = "Account Type"
99 'name': fields.char('Acc. Type Name', size=64, required=True, translate=True),
100 'code': fields.char('Code', size=32, required=True),
101 'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of account types."),
102 'partner_account': fields.boolean('Partner account'),
103 'close_method': fields.selection([('none', 'None'), ('balance', 'Balance'), ('detail', 'Detail'), ('unreconciled', 'Unreconciled')], 'Deferral Method', required=True),
104 'sign': fields.selection([(-1, 'Negative'), (1, 'Positive')], 'Sign on Reports', required=True, help='Allows you to change the sign of the balance amount displayed in the reports, so that you can see positive figures instead of negative ones in expenses accounts.'),
107 'close_method': lambda *a: 'none',
108 'sequence': lambda *a: 5,
109 'sign': lambda *a: 1,
112 account_account_type()
114 def _code_get(self, cr, uid, context={}):
115 acc_type_obj = self.pool.get('account.account.type')
116 ids = acc_type_obj.search(cr, uid, [])
117 res = acc_type_obj.read(cr, uid, ids, ['code', 'name'], context)
118 return [(r['code'], r['name']) for r in res]
120 #----------------------------------------------------------
122 #----------------------------------------------------------
124 class account_tax(osv.osv):
125 _name = 'account.tax'
128 class account_account(osv.osv):
129 _order = "parent_left"
130 _parent_order = "code"
131 _name = "account.account"
132 _description = "Account"
135 def search(self, cr, uid, args, offset=0, limit=None, order=None,
136 context=None, count=False):
141 while pos < len(args):
143 if args[pos][0] == 'code' and args[pos][1] in ('like', 'ilike') and args[pos][2]:
144 args[pos] = ('code', '=like', str(args[pos][2].replace('%', ''))+'%')
145 if args[pos][0] == 'journal_id':
149 jour = self.pool.get('account.journal').browse(cr, uid, args[pos][2])
150 if (not (jour.account_control_ids or jour.type_control_ids)) or not args[pos][2]:
151 args[pos] = ('type','not in',('consolidation','view'))
153 ids3 = map(lambda x: x.id, jour.type_control_ids)
154 ids1 = super(account_account, self).search(cr, uid, [('user_type', 'in', ids3)])
155 ids1 += map(lambda x: x.id, jour.account_control_ids)
156 args[pos] = ('id', 'in', ids1)
159 if context and context.has_key('consolidate_childs'): #add consolidated childs of accounts
160 ids = super(account_account, self).search(cr, uid, args, offset, limit,
161 order, context=context, count=count)
162 for consolidate_child in self.browse(cr, uid, context['account_id']).child_consol_ids:
163 ids.append(consolidate_child.id)
166 return super(account_account, self).search(cr, uid, args, offset, limit,
167 order, context=context, count=count)
169 def _get_children_and_consol(self, cr, uid, ids, context={}):
170 #this function search for all the children and all consolidated children (recursively) of the given account ids
171 ids2 = self.search(cr, uid, [('parent_id', 'child_of', ids)], context=context)
173 for rec in self.browse(cr, uid, ids2, context=context):
174 for child in rec.child_consol_ids:
175 ids3.append(child.id)
177 ids3 = self._get_children_and_consol(cr, uid, ids3, context)
180 def __compute(self, cr, uid, ids, field_names, arg, context={}, query=''):
181 #compute the balance/debit/credit accordingly to the value of field_name for the given account ids
183 'balance': "COALESCE(SUM(l.debit),0) - COALESCE(SUM(l.credit), 0) as balance ",
184 'debit': "COALESCE(SUM(l.debit), 0) as debit ",
185 'credit': "COALESCE(SUM(l.credit), 0) as credit "
187 #get all the necessary accounts
188 ids2 = self._get_children_and_consol(cr, uid, ids, context)
189 acc_set = ",".join(map(str, ids2))
190 #compute for each account the balance/debit/credit from the move lines
193 query = self.pool.get('account.move.line')._query_get(cr, uid,
195 cr.execute(("SELECT l.account_id as id, " +\
196 ' , '.join(map(lambda x: mapping[x], field_names)) +
198 "account_move_line l " \
200 "l.account_id IN (%s) " \
201 "AND " + query + " " \
202 "GROUP BY l.account_id") % (acc_set, ))
204 for res in cr.dictfetchall():
205 accounts[res['id']] = res
207 #for the asked accounts, get from the dictionnary 'accounts' the value of it
210 res[id] = self._get_account_values(cr, uid, id, accounts, field_names, context)
213 def _get_account_values(self, cr, uid, id, accounts, field_names, context={}):
214 res = {}.fromkeys(field_names, 0.0)
215 browse_rec = self.browse(cr, uid, id)
216 if browse_rec.type == 'consolidation':
217 ids2 = self.read(cr, uid, [browse_rec.id], ['child_consol_ids'], context)[0]['child_consol_ids']
218 for t in self.search(cr, uid, [('parent_id', 'child_of', [browse_rec.id])]):
219 if t not in ids2 and t != browse_rec.id:
222 tmp = self._get_account_values(cr, uid, i, accounts, field_names, context)
223 for a in field_names:
226 ids2 = self.search(cr, uid, [('parent_id', 'child_of', [browse_rec.id])])
228 for a in field_names:
229 res[a] += accounts.get(i, {}).get(a, 0.0)
232 def _get_company_currency(self, cr, uid, ids, field_name, arg, context={}):
234 for rec in self.browse(cr, uid, ids, context):
235 result[rec.id] = (rec.company_id.currency_id.id,rec.company_id.currency_id.code)
238 def _get_child_ids(self, cr, uid, ids, field_name, arg, context={}):
240 for record in self.browse(cr, uid, ids, context):
241 if record.child_parent_ids:
242 result[record.id] = [x.id for x in record.child_parent_ids]
244 result[record.id] = []
246 if record.child_consol_ids:
247 for acc in record.child_consol_ids:
248 result[record.id].append(acc.id)
253 'name': fields.char('Name', size=128, required=True, select=True),
254 'currency_id': fields.many2one('res.currency', 'Secondary Currency', help="Force all moves for this account to have this secondary currency."),
255 'code': fields.char('Code', size=64, required=True),
256 'type': fields.selection([
257 ('receivable', 'Receivable'),
258 ('payable', 'Payable'),
260 ('consolidation', 'Consolidation'),
262 ('closed', 'Closed'),
263 ], 'Internal Type', required=True,),
265 'user_type': fields.many2one('account.account.type', 'Account Type', required=True),
266 'parent_id': fields.many2one('account.account', 'Parent', ondelete='cascade'),
267 'child_parent_ids': fields.one2many('account.account','parent_id','Children'),
268 'child_consol_ids': fields.many2many('account.account', 'account_account_consol_rel', 'child_id', 'parent_id', 'Consolidated Children'),
269 'child_id': fields.function(_get_child_ids, method=True, type='many2many', relation="account.account", string="Child Accounts"),
270 'balance': fields.function(__compute, digits=(16, 2), method=True, string='Balance', multi='balance'),
271 'credit': fields.function(__compute, digits=(16, 2), method=True, string='Credit', multi='balance'),
272 'debit': fields.function(__compute, digits=(16, 2), method=True, string='Debit', multi='balance'),
273 'reconcile': fields.boolean('Reconcile', help="Check this if the user is allowed to reconcile entries in this account."),
274 'shortcut': fields.char('Shortcut', size=12),
275 'tax_ids': fields.many2many('account.tax', 'account_account_tax_default_rel',
276 'account_id', 'tax_id', 'Default Taxes'),
277 'note': fields.text('Note'),
278 'company_currency_id': fields.function(_get_company_currency, method=True, type='many2one', relation='res.currency', string='Company Currency'),
279 'company_id': fields.many2one('res.company', 'Company', required=True),
280 'active': fields.boolean('Active', select=2),
282 'parent_left': fields.integer('Parent Left', select=1),
283 'parent_right': fields.integer('Parent Right', select=1),
284 'currency_mode': fields.selection([('current', 'At Date'), ('average', 'Average Rate')], 'Outgoing Currencies Rate',
286 'This will select how the current currency rate for outgoing transactions is computed. '\
287 'In most countries the legal method is "average" but only a few software systems are able to '\
288 'manage this. So if you import from another software system you may have to use the rate at date. ' \
289 'Incoming transactions always use the rate at date.', \
291 'check_history': fields.boolean('Display History',
292 help="Check this box if you want to print all entries when printing the General Ledger, "\
293 "otherwise it will only print its balance."),
296 def _default_company(self, cr, uid, context={}):
297 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
299 return user.company_id.id
300 return self.pool.get('res.company').search(cr, uid, [('parent_id', '=', False)])[0]
303 'type': lambda *a : 'view',
304 'reconcile': lambda *a: False,
305 'company_id': _default_company,
306 'active': lambda *a: True,
307 'check_history': lambda *a: True,
308 'currency_mode': lambda *a: 'current'
311 def _check_recursion(self, cr, uid, ids):
312 obj_self = self.browse(cr, uid, ids[0])
313 p_id = obj_self.parent_id and obj_self.parent_id.id
314 if (obj_self in obj_self.child_consol_ids) or (p_id and (p_id is obj_self.id)):
317 cr.execute('select distinct child_id from account_account_consol_rel where parent_id in ('+','.join(map(str, ids))+')')
318 child_ids = filter(None, map(lambda x: x[0], cr.fetchall()))
320 if (p_id and (p_id in c_ids)) or (obj_self.id in c_ids):
323 s_ids = self.search(cr, uid, [('parent_id', 'in', c_ids)])
324 if p_id and (p_id in s_ids):
331 (_check_recursion, 'Error ! You can not create recursive accounts.', ['parent_id'])
334 ('code_company_uniq', 'unique (code,company_id)', 'The code of the account must be unique per company !')
336 def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=80):
344 if name and str(name).startswith('partner:'):
345 part_id = int(name.split(':')[1])
346 part = self.pool.get('res.partner').browse(cr, user, part_id, context)
347 args += [('id', 'in', (part.property_account_payable.id, part.property_account_receivable.id))]
349 if name and str(name).startswith('type:'):
350 type = name.split(':')[1]
351 args += [('type', '=', type)]
356 ids = self.search(cr, user, [('code', '=like', name+"%")]+args, limit=limit)
358 ids = self.search(cr, user, [('shortcut', '=', name)]+ args, limit=limit)
360 ids = self.search(cr, user, [('name', operator, name)]+ args, limit=limit)
362 ids = self.search(cr, user, args, context=context, limit=limit)
363 return self.name_get(cr, user, ids, context=context)
365 def name_get(self, cr, uid, ids, context={}):
368 reads = self.read(cr, uid, ids, ['name', 'code'], context)
371 name = record['name']
373 name = record['code'] + ' '+name
374 res.append((record['id'], name))
377 def copy(self, cr, uid, id, default={}, context={}, done_list=[], local=False):
378 account = self.browse(cr, uid, id, context=context)
382 default = default.copy()
383 default['code'] = (account['code'] or '') + '(copy)'
386 if account.id in done_list:
388 done_list.append(account.id)
390 for child in account.child_id:
391 child_ids = self.copy(cr, uid, child.id, default, context=context, done_list=done_list, local=True)
393 new_child_ids.append(child_ids)
394 default['child_parent_ids'] = [(6, 0, new_child_ids)]
396 default['child_parent_ids'] = False
397 return super(account_account, self).copy(cr, uid, id, default, context=context)
399 def write(self, cr, uid, ids, vals, context=None):
402 if 'active' in vals and not vals['active']:
403 line_obj = self.pool.get('account.move.line')
404 account_ids = self.search(cr, uid, [('id', 'child_of', ids)])
405 if line_obj.search(cr, uid, [('account_id', 'in', account_ids)]):
406 raise osv.except_osv(_('Error !'), _('You can not deactivate an account that contains account moves.'))
407 return super(account_account, self).write(cr, uid, ids, vals, context=context)
410 class account_journal_view(osv.osv):
411 _name = "account.journal.view"
412 _description = "Journal View"
414 'name': fields.char('Journal View', size=64, required=True),
415 'columns_id': fields.one2many('account.journal.column', 'view_id', 'Columns')
418 account_journal_view()
421 class account_journal_column(osv.osv):
422 def _col_get(self, cr, user, context={}):
424 cols = self.pool.get('account.move.line')._columns
426 result.append( (col, cols[col].string) )
429 _name = "account.journal.column"
430 _description = "Journal Column"
432 'name': fields.char('Column Name', size=64, required=True),
433 'field': fields.selection(_col_get, 'Field Name', method=True, required=True, size=32),
434 'view_id': fields.many2one('account.journal.view', 'Journal View', select=True),
435 'sequence': fields.integer('Sequence'),
436 'required': fields.boolean('Required'),
437 'readonly': fields.boolean('Readonly'),
440 account_journal_column()
442 class account_journal(osv.osv):
443 _name = "account.journal"
444 _description = "Journal"
446 'name': fields.char('Journal Name', size=64, required=True, translate=True),
447 'code': fields.char('Code', size=16),
448 'type': fields.selection([('sale', 'Sale'), ('purchase', 'Purchase'), ('cash', 'Cash'), ('general', 'General'), ('situation', 'Situation')], 'Type', size=32, required=True),
449 'refund_journal': fields.boolean('Refund Journal'),
451 'type_control_ids': fields.many2many('account.account.type', 'account_journal_type_rel', 'journal_id','type_id', 'Type Controls', domain=[('code','<>','view'), ('code', '<>', 'closed')]),
452 'account_control_ids': fields.many2many('account.account', 'account_account_type_rel', 'journal_id','account_id', 'Account', domain=[('type','<>','view'), ('type', '<>', 'closed')]),
454 'active': fields.boolean('Active'),
455 'view_id': fields.many2one('account.journal.view', 'View', required=True, help="Gives the view used when writing or browsing entries in this journal. The view tell Open ERP which fields should be visible, required or readonly and in which order. You can create your own view for a faster encoding in each journal."),
456 'default_credit_account_id': fields.many2one('account.account', 'Default Credit Account', domain="[('type','!=','view')]"),
457 'default_debit_account_id': fields.many2one('account.account', 'Default Debit Account', domain="[('type','!=','view')]"),
458 'centralisation': fields.boolean('Centralised counterpart', help="Check this box to determine that each entry of this journal won't create a new counterpart but will share the same counterpart. This is used in fiscal year closing."),
459 'update_posted': fields.boolean('Allow Cancelling Entries'),
460 'group_invoice_lines': fields.boolean('Group invoice lines', help="If this box is checked, the system will try to group the accounting lines when generating them from invoices."),
461 'sequence_id': fields.many2one('ir.sequence', 'Entry Sequence', help="The sequence gives the display order for a list of journals", required=True),
462 'user_id': fields.many2one('res.users', 'User', help="The user responsible for this journal"),
463 'groups_id': fields.many2many('res.groups', 'account_journal_group_rel', 'journal_id', 'group_id', 'Groups'),
464 'currency': fields.many2one('res.currency', 'Currency', help='The currency used to enter statement'),
465 'entry_posted': fields.boolean('Skip \'Draft\' State for Created Entries', help='Check this box if you don\'t want new account moves to pass through the \'draft\' state and instead goes directly to the \'posted state\' without any manual validation.'),
466 'company_id': fields.related('default_credit_account_id','company_id',type='many2one', relation="res.company", string="Company"),
467 'invoice_sequence_id': fields.many2one('ir.sequence', 'Invoice Sequence', \
468 help="The sequence used for invoice numbers in this journal."),
472 'active': lambda *a: 1,
473 'user_id': lambda self,cr,uid,context: uid,
475 def create(self, cr, uid, vals, context={}):
476 journal_id = super(account_journal, self).create(cr, uid, vals, context)
477 # journal_name = self.browse(cr, uid, [journal_id])[0].code
478 # periods = self.pool.get('account.period')
479 # ids = periods.search(cr, uid, [('date_stop','>=',time.strftime('%Y-%m-%d'))])
480 # for period in periods.browse(cr, uid, ids):
481 # self.pool.get('account.journal.period').create(cr, uid, {
482 # 'name': (journal_name or '')+':'+(period.code or ''),
483 # 'journal_id': journal_id,
484 # 'period_id': period.id
488 def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=80):
495 ids = self.search(cr, user, [('code','ilike',name)]+ args, limit=limit)
497 ids = self.search(cr, user, [('name',operator,name)]+ args, limit=limit)
498 return self.name_get(cr, user, ids, context=context)
501 class account_fiscalyear(osv.osv):
502 _name = "account.fiscalyear"
503 _description = "Fiscal Year"
505 'name': fields.char('Fiscal Year', size=64, required=True),
506 'code': fields.char('Code', size=6, required=True),
507 'company_id': fields.many2one('res.company', 'Company',
508 help="Keep empty if the fiscal year belongs to several companies."),
509 'date_start': fields.date('Start Date', required=True),
510 'date_stop': fields.date('End Date', required=True),
511 'period_ids': fields.one2many('account.period', 'fiscalyear_id', 'Periods'),
512 'state': fields.selection([('draft','Draft'), ('done','Done')], 'Status', readonly=True),
516 'state': lambda *a: 'draft',
518 _order = "date_start"
520 def _check_duration(self,cr,uid,ids):
521 obj_fy=self.browse(cr,uid,ids[0])
522 if obj_fy.date_stop < obj_fy.date_start:
527 (_check_duration, 'Error ! The duration of the Fiscal Year is invalid. ', ['date_stop'])
530 def create_period3(self,cr, uid, ids, context={}):
531 return self.create_period(cr, uid, ids, context, 3)
533 def create_period(self,cr, uid, ids, context={}, interval=1):
534 for fy in self.browse(cr, uid, ids, context):
535 ds = mx.DateTime.strptime(fy.date_start, '%Y-%m-%d')
536 while ds.strftime('%Y-%m-%d')<fy.date_stop:
537 de = ds + RelativeDateTime(months=interval, days=-1)
539 if de.strftime('%Y-%m-%d')>fy.date_stop:
540 de=mx.DateTime.strptime(fy.date_stop, '%Y-%m-%d')
542 self.pool.get('account.period').create(cr, uid, {
543 'name': ds.strftime('%m/%Y'),
544 'code': ds.strftime('%m/%Y'),
545 'date_start': ds.strftime('%Y-%m-%d'),
546 'date_stop': de.strftime('%Y-%m-%d'),
547 'fiscalyear_id': fy.id,
549 ds = ds + RelativeDateTime(months=interval)
552 def find(self, cr, uid, dt=None, exception=True, context={}):
554 dt = time.strftime('%Y-%m-%d')
555 ids = self.search(cr, uid, [('date_start', '<=', dt), ('date_stop', '>=', dt)])
558 raise osv.except_osv(_('Error !'), _('No fiscal year defined for this date !\nPlease create one.'))
564 class account_period(osv.osv):
565 _name = "account.period"
566 _description = "Account period"
568 'name': fields.char('Period Name', size=64, required=True),
569 'code': fields.char('Code', size=12),
570 'special': fields.boolean('Opening/Closing Period', size=12,
571 help="These periods can overlap."),
572 'date_start': fields.date('Start of Period', required=True, states={'done':[('readonly',True)]}),
573 'date_stop': fields.date('End of Period', required=True, states={'done':[('readonly',True)]}),
574 'fiscalyear_id': fields.many2one('account.fiscalyear', 'Fiscal Year', required=True, states={'done':[('readonly',True)]}, select=True),
575 'state': fields.selection([('draft','Draft'), ('done','Done')], 'Status', readonly=True)
578 'state': lambda *a: 'draft',
580 _order = "date_start"
582 def _check_duration(self,cr,uid,ids,context={}):
583 obj_period=self.browse(cr,uid,ids[0])
584 if obj_period.date_stop < obj_period.date_start:
588 def _check_year_limit(self,cr,uid,ids,context={}):
589 for obj_period in self.browse(cr,uid,ids):
590 if obj_period.special:
593 if obj_period.fiscalyear_id.date_stop < obj_period.date_stop or \
594 obj_period.fiscalyear_id.date_stop < obj_period.date_start or \
595 obj_period.fiscalyear_id.date_start > obj_period.date_start or \
596 obj_period.fiscalyear_id.date_start > obj_period.date_stop:
599 pids = self.search(cr, uid, [('date_stop','>=',obj_period.date_start),('date_start','<=',obj_period.date_stop),('special','=',False),('id','<>',obj_period.id)])
600 for period in self.browse(cr, uid, pids):
601 if period.fiscalyear_id.company_id.id==obj_period.fiscalyear_id.company_id.id:
606 (_check_duration, 'Error ! The duration of the Period(s) is/are invalid. ', ['date_stop']),
607 (_check_year_limit, 'Invalid period ! Some periods overlap or the date period is not in the scope of the fiscal year. ', ['date_stop'])
610 def next(self, cr, uid, period, step, context={}):
611 ids = self.search(cr, uid, [('date_start','>',period.date_start)])
616 def find(self, cr, uid, dt=None, context={}):
618 dt = time.strftime('%Y-%m-%d')
619 #CHECKME: shouldn't we check the state of the period?
620 ids = self.search(cr, uid, [('date_start','<=',dt),('date_stop','>=',dt)])
622 raise osv.except_osv(_('Error !'), _('No period defined for this date !\nPlease create a fiscal year.'))
625 def action_draft(self, cr, uid, ids, *args):
626 users_roles = self.pool.get('res.users').browse(cr, uid, uid).roles_id
627 for role in users_roles:
628 if role.name=='Period':
631 cr.execute('update account_journal_period set state=%s where period_id=%s', (mode, id))
632 cr.execute('update account_period set state=%s where id=%s', (mode, id))
637 class account_journal_period(osv.osv):
638 _name = "account.journal.period"
639 _description = "Journal - Period"
641 def _icon_get(self, cr, uid, ids, field_name, arg=None, context={}):
642 result = {}.fromkeys(ids, 'STOCK_NEW')
643 for r in self.read(cr, uid, ids, ['state']):
645 'draft': 'STOCK_NEW',
646 'printed': 'STOCK_PRINT_PREVIEW',
647 'done': 'STOCK_DIALOG_AUTHENTICATION',
648 }.get(r['state'], 'STOCK_NEW')
652 'name': fields.char('Journal-Period Name', size=64, required=True),
653 'journal_id': fields.many2one('account.journal', 'Journal', required=True, ondelete="cascade"),
654 'period_id': fields.many2one('account.period', 'Period', required=True, ondelete="cascade"),
655 'icon': fields.function(_icon_get, method=True, string='Icon', type='char', size=32),
656 'active': fields.boolean('Active', required=True),
657 'state': fields.selection([('draft','Draft'), ('printed','Printed'), ('done','Done')], 'Status', required=True, readonly=True),
658 'fiscalyear_id': fields.related('period_id', 'fiscalyear_id', string='Fiscal Year', type='many2one', relation='account.fiscalyear'),
661 def _check(self, cr, uid, ids, context={}):
662 for obj in self.browse(cr, uid, ids, context):
663 cr.execute('select * from account_move_line where journal_id=%s and period_id=%s limit 1', (obj.journal_id.id, obj.period_id.id))
666 raise osv.except_osv(_('Error !'), _('You can not modify/delete a journal with entries for this period !'))
669 def write(self, cr, uid, ids, vals, context={}):
670 self._check(cr, uid, ids, context)
671 return super(account_journal_period, self).write(cr, uid, ids, vals, context)
673 def create(self, cr, uid, vals, context={}):
674 period_id=vals.get('period_id',False)
676 period = self.pool.get('account.period').browse(cr, uid,period_id)
677 vals['state']=period.state
678 return super(account_journal_period, self).create(cr, uid, vals, context)
680 def unlink(self, cr, uid, ids, context={}):
681 self._check(cr, uid, ids, context)
682 return super(account_journal_period, self).unlink(cr, uid, ids, context)
685 'state': lambda *a: 'draft',
686 'active': lambda *a: True,
690 account_journal_period()
692 class account_fiscalyear(osv.osv):
693 _inherit = "account.fiscalyear"
694 _description = "Fiscal Year"
696 'end_journal_period_id':fields.many2one('account.journal.period','End of Year Entries Journal', readonly=True),
700 #----------------------------------------------------------
702 #----------------------------------------------------------
703 class account_move(osv.osv):
704 _name = "account.move"
705 _description = "Account Entry"
708 def name_get(self, cursor, user, ids, context=None):
712 data_move = self.pool.get('account.move').browse(cursor,user,ids)
713 for move in data_move:
714 if move.state=='draft':
715 name = '*' + str(move.id)
718 res.append((move.id, name))
722 def _get_period(self, cr, uid, context):
723 periods = self.pool.get('account.period').find(cr, uid)
729 def _amount_compute(self, cr, uid, ids, name, args, context, where =''):
730 if not ids: return {}
731 cr.execute('select move_id,sum(debit) from account_move_line where move_id in ('+','.join(map(str,ids))+') group by move_id')
732 result = dict(cr.fetchall())
734 result.setdefault(id, 0.0)
738 'name': fields.char('Number', size=64, required=True),
739 'ref': fields.char('Ref', size=64),
740 'period_id': fields.many2one('account.period', 'Period', required=True, states={'posted':[('readonly',True)]}),
741 'journal_id': fields.many2one('account.journal', 'Journal', required=True, states={'posted':[('readonly',True)]}),
742 'state': fields.selection([('draft','Draft'), ('posted','Posted')], 'Status', required=True, readonly=True),
743 'line_id': fields.one2many('account.move.line', 'move_id', 'Entries', states={'posted':[('readonly',True)]}),
744 'to_check': fields.boolean('To Be Verified'),
745 'partner_id': fields.related('line_id', 'partner_id', type="many2one", relation="res.partner", string="Partner"),
746 'amount': fields.function(_amount_compute, method=True, string='Amount', digits=(16,2)),
747 'date': fields.date('Date', required=True),
748 'type': fields.selection([
749 ('pay_voucher','Cash Payment'),
750 ('bank_pay_voucher','Bank Payment'),
751 ('rec_voucher','Cash Receipt'),
752 ('bank_rec_voucher','Bank Receipt'),
753 ('cont_voucher','Contra'),
754 ('journal_sale_vou','Journal Sale'),
755 ('journal_pur_voucher','Journal Purchase'),
756 ('journal_voucher','Journal Voucher'),
757 ],'Type', readonly=True, select=True, states={'draft':[('readonly',False)]}),
760 'name': lambda *a: '/',
761 'state': lambda *a: 'draft',
762 'period_id': _get_period,
763 'type' : lambda *a : 'journal_voucher',
764 'date': lambda *a:time.strftime('%Y-%m-%d'),
767 def _check_centralisation(self, cursor, user, ids):
768 for move in self.browse(cursor, user, ids):
769 if move.journal_id.centralisation:
770 move_ids = self.search(cursor, user, [
771 ('period_id', '=', move.period_id.id),
772 ('journal_id', '=', move.journal_id.id),
774 if len(move_ids) > 1:
778 def _check_period_journal(self, cursor, user, ids):
779 for move in self.browse(cursor, user, ids):
780 for line in move.line_id:
781 if line.period_id.id != move.period_id.id:
783 if line.journal_id.id != move.journal_id.id:
788 (_check_centralisation,
789 'You cannot create more than one move per period on centralized journal',
791 (_check_period_journal,
792 'You cannot create entries on different periods/journals in the same move',
795 def post(self, cr, uid, ids, context=None):
796 if self.validate(cr, uid, ids, context) and len(ids):
797 for move in self.browse(cr, uid, ids):
800 journal = move.journal_id
801 if journal.sequence_id:
802 c = {'fiscalyear_id': move.period_id.fiscalyear_id.id}
803 new_name = self.pool.get('ir.sequence').get_id(cr, uid, journal.sequence_id.id, context=c)
805 raise osv.except_osv(_('Error'), _('No sequence defined in the journal !'))
807 self.write(cr, uid, [move.id], {'name':new_name})
809 cr.execute('update account_move set state=%s where id in ('+','.join(map(str,ids))+')', ('posted',))
811 raise osv.except_osv(_('Integrity Error !'), _('You can not validate a non-balanced entry !'))
814 def button_validate(self, cursor, user, ids, context=None):
815 return self.post(cursor, user, ids, context=context)
817 def button_cancel(self, cr, uid, ids, context={}):
818 for line in self.browse(cr, uid, ids, context):
819 if not line.journal_id.update_posted:
820 raise osv.except_osv(_('Error !'), _('You can not modify a posted entry of this journal !\nYou should set the journal to allow cancelling entries if you want to do that.'))
822 cr.execute('update account_move set state=%s where id in ('+','.join(map(str,ids))+')', ('draft',))
825 def write(self, cr, uid, ids, vals, context={}):
827 c['novalidate'] = True
828 result = super(osv.osv, self).write(cr, uid, ids, vals, c)
829 self.validate(cr, uid, ids, context)
833 # TODO: Check if period is closed !
835 def create(self, cr, uid, vals, context={}):
836 if 'line_id' in vals:
837 if 'journal_id' in vals:
838 for l in vals['line_id']:
840 l[2]['journal_id'] = vals['journal_id']
841 context['journal_id'] = vals['journal_id']
842 if 'period_id' in vals:
843 for l in vals['line_id']:
845 l[2]['period_id'] = vals['period_id']
846 context['period_id'] = vals['period_id']
848 default_period = self._get_period(cr, uid, context)
849 for l in vals['line_id']:
851 l[2]['period_id'] = default_period
852 context['period_id'] = default_period
854 accnt_journal = self.pool.get('account.journal').browse(cr, uid, vals['journal_id'])
855 if 'line_id' in vals:
857 c['novalidate'] = True
858 result = super(account_move, self).create(cr, uid, vals, c)
859 self.validate(cr, uid, [result], context)
861 result = super(account_move, self).create(cr, uid, vals, context)
864 def copy(self, cr, uid, id, default=None, context=None):
867 default = default.copy()
868 default.update({'state':'draft', 'name':'/',})
869 return super(account_move, self).copy(cr, uid, id, default, context)
871 def unlink(self, cr, uid, ids, context={}, check=True):
873 for move in self.browse(cr, uid, ids, context):
874 if move['state'] != 'draft':
875 raise osv.except_osv(_('UserError'),
876 _('You can not delete posted movement: "%s"!') % \
878 line_ids = map(lambda x: x.id, move.line_id)
879 context['journal_id'] = move.journal_id.id
880 context['period_id'] = move.period_id.id
881 self.pool.get('account.move.line')._update_check(cr, uid, line_ids, context)
882 self.pool.get('account.move.line').unlink(cr, uid, line_ids, context=context)
883 toremove.append(move.id)
884 result = super(account_move, self).unlink(cr, uid, toremove, context)
887 def _compute_balance(self, cr, uid, id, context={}):
888 move = self.browse(cr, uid, [id])[0]
890 for line in move.line_id:
891 amount+= (line.debit - line.credit)
894 def _centralise(self, cr, uid, move, mode):
896 account_id = move.journal_id.default_debit_account_id.id
899 raise osv.except_osv(_('UserError'),
900 _('There is no default default debit account defined \n' \
901 'on journal "%s"') % move.journal_id.name)
903 account_id = move.journal_id.default_credit_account_id.id
906 raise osv.except_osv(_('UserError'),
907 _('There is no default default credit account defined \n' \
908 'on journal "%s"') % move.journal_id.name)
910 # find the first line of this move with the current mode
911 # or create it if it doesn't exist
912 cr.execute('select id from account_move_line where move_id=%s and centralisation=%s limit 1', (move.id, mode))
917 line_id = self.pool.get('account.move.line').create(cr, uid, {
918 'name': 'Centralisation '+mode,
919 'centralisation': mode,
920 'account_id': account_id,
922 'journal_id': move.journal_id.id,
923 'period_id': move.period_id.id,
924 'date': move.period_id.date_stop,
927 }, {'journal_id': move.journal_id.id, 'period_id': move.period_id.id})
929 # find the first line of this move with the other mode
930 # so that we can exclude it from our calculation
931 cr.execute('select id from account_move_line where move_id=%s and centralisation=%s limit 1', (move.id, mode2))
938 cr.execute('select sum('+mode+') from account_move_line where move_id=%s and id<>%s', (move.id, line_id2))
939 result = cr.fetchone()[0] or 0.0
940 cr.execute('update account_move_line set '+mode2+'=%s where id=%s', (result, line_id))
944 # Validate a balanced move. If it is a centralised journal, create a move.
946 def validate(self, cr, uid, ids, context={}):
947 if context and ('__last_update' in context):
948 del context['__last_update']
950 for move in self.browse(cr, uid, ids, context):
951 #unlink analytic lines on move_lines
952 for obj_line in move.line_id:
953 for obj in obj_line.analytic_lines:
954 self.pool.get('account.analytic.line').unlink(cr,uid,obj.id)
956 journal = move.journal_id
961 for line in move.line_id:
962 amount += line.debit - line.credit
963 line_ids.append(line.id)
964 if line.state=='draft':
965 line_draft_ids.append(line.id)
968 company_id = line.account_id.company_id.id
969 if not company_id == line.account_id.company_id.id:
970 raise osv.except_osv(_('Error'), _("Couldn't create move between different companies"))
972 if line.account_id.currency_id:
973 if line.account_id.currency_id.id != line.currency_id.id and (line.account_id.currency_id.id != line.account_id.company_id.currency_id.id or line.currency_id):
974 raise osv.except_osv(_('Error'), _("""Couldn't create move with currency different from the secondary currency of the account "%s - %s". Clear the secondary currency field of the account definition if you want to accept all currencies.""" % (line.account_id.code, line.account_id.name)))
976 if abs(amount) < 0.0001:
977 if not len(line_draft_ids):
979 self.pool.get('account.move.line').write(cr, uid, line_draft_ids, {
980 'journal_id': move.journal_id.id,
981 'period_id': move.period_id.id,
983 }, context, check=False)
987 if journal.type not in ('purchase','sale'):
990 for line in move.line_id:
992 key = (line.account_id.id, line.tax_code_id.id)
994 code = account2[key][0]
995 amount = account2[key][1] * (line.debit + line.credit)
996 elif line.account_id.id in account:
997 code = account[line.account_id.id][0]
998 amount = account[line.account_id.id][1] * (line.debit + line.credit)
999 if (code or amount) and not (line.tax_code_id or line.tax_amount):
1000 self.pool.get('account.move.line').write(cr, uid, [line.id], {
1001 'tax_code_id': code,
1002 'tax_amount': amount
1003 }, context, check=False)
1008 if journal.centralisation:
1009 self._centralise(cr, uid, move, 'debit')
1010 self._centralise(cr, uid, move, 'credit')
1011 self.pool.get('account.move.line').write(cr, uid, line_draft_ids, {
1013 }, context, check=False)
1016 self.pool.get('account.move.line').write(cr, uid, line_ids, {
1017 'journal_id': move.journal_id.id,
1018 'period_id': move.period_id.id,
1019 #'tax_code_id': False,
1020 #'tax_amount': False,
1022 }, context, check=False)
1026 for tmp in move.line_id:
1027 list_ids.append(tmp.id)
1028 self.pool.get('account.move.line').create_analytic_lines(cr, uid, list_ids, context)
1032 class account_move_reconcile(osv.osv):
1033 _name = "account.move.reconcile"
1034 _description = "Account Reconciliation"
1036 'name': fields.char('Name', size=64, required=True),
1037 'type': fields.char('Type', size=16, required=True),
1038 'line_id': fields.one2many('account.move.line', 'reconcile_id', 'Entry Lines'),
1039 'line_partial_ids': fields.one2many('account.move.line', 'reconcile_partial_id', 'Partial Entry lines'),
1040 'create_date': fields.date('Creation date', readonly=True),
1043 'name': lambda self,cr,uid,ctx={}: self.pool.get('ir.sequence').get(cr, uid, 'account.reconcile') or '/',
1045 def reconcile_partial_check(self, cr, uid, ids, type='auto', context={}):
1046 for rec in self.browse(cr, uid, ids, context):
1048 for line in rec.line_partial_ids:
1049 total += (line.debit or 0.0) - (line.credit or 0.0)
1051 self.pool.get('account.move.line').write(cr, uid,
1052 map(lambda x: x.id, rec.line_partial_ids),
1053 {'reconcile_id': rec.id }
1057 def name_get(self, cr, uid, ids, context=None):
1061 for r in self.browse(cr, uid, ids, context):
1062 total = reduce(lambda y,t: (t.debit or 0.0) - (t.credit or 0.0) + y, r.line_partial_ids, 0.0)
1064 name = '%s (%.2f)' % (r.name, total)
1065 result.append((r.id,name))
1067 result.append((r.id,r.name))
1071 account_move_reconcile()
1073 #----------------------------------------------------------
1075 #----------------------------------------------------------
1078 child_depend: la taxe depend des taxes filles
1080 class account_tax_code(osv.osv):
1082 A code for the tax object.
1084 This code is used for some tax declarations.
1086 def _sum(self, cr, uid, ids, name, args, context, where =''):
1087 ids2 = self.search(cr, uid, [('parent_id', 'child_of', ids)])
1088 acc_set = ",".join(map(str, ids2))
1089 if context.get('based_on', 'invoices') == 'payments':
1090 cr.execute('SELECT line.tax_code_id, sum(line.tax_amount) \
1091 FROM account_move_line AS line, \
1092 account_move AS move \
1093 LEFT JOIN account_invoice invoice ON \
1094 (invoice.move_id = move.id) \
1095 WHERE line.tax_code_id in ('+acc_set+') '+where+' \
1096 AND move.id = line.move_id \
1097 AND ((invoice.state = \'paid\') \
1098 OR (invoice.id IS NULL)) \
1099 GROUP BY line.tax_code_id')
1101 cr.execute('SELECT line.tax_code_id, sum(line.tax_amount) \
1102 FROM account_move_line AS line \
1103 WHERE line.tax_code_id in ('+acc_set+') '+where+' \
1104 GROUP BY line.tax_code_id')
1105 res=dict(cr.fetchall())
1106 for record in self.browse(cr, uid, ids, context):
1107 def _rec_get(record):
1108 amount = res.get(record.id, 0.0)
1109 for rec in record.child_ids:
1110 amount += _rec_get(rec) * rec.sign
1112 res[record.id] = round(_rec_get(record), 2)
1115 def _sum_year(self, cr, uid, ids, name, args, context):
1116 if 'fiscalyear_id' in context and context['fiscalyear_id']:
1117 fiscalyear_id = context['fiscalyear_id']
1119 fiscalyear_id = self.pool.get('account.fiscalyear').find(cr, uid, exception=False)
1122 pids = map(lambda x: str(x.id), self.pool.get('account.fiscalyear').browse(cr, uid, fiscalyear_id).period_ids)
1124 where = ' and period_id in (' + (','.join(pids))+')'
1125 return self._sum(cr, uid, ids, name, args, context,
1128 def _sum_period(self, cr, uid, ids, name, args, context):
1129 if 'period_id' in context and context['period_id']:
1130 period_id = context['period_id']
1132 period_id = self.pool.get('account.period').find(cr, uid)
1133 if not len(period_id):
1134 return dict.fromkeys(ids, 0.0)
1135 period_id = period_id[0]
1136 return self._sum(cr, uid, ids, name, args, context,
1137 where=' and line.period_id='+str(period_id))
1139 _name = 'account.tax.code'
1140 _description = 'Tax Code'
1143 'name': fields.char('Tax Case Name', size=64, required=True),
1144 'code': fields.char('Case Code', size=64),
1145 'info': fields.text('Description'),
1146 'sum': fields.function(_sum_year, method=True, string="Year Sum"),
1147 'sum_period': fields.function(_sum_period, method=True, string="Period Sum"),
1148 'parent_id': fields.many2one('account.tax.code', 'Parent Code', select=True),
1149 'child_ids': fields.one2many('account.tax.code', 'parent_id', 'Child Codes'),
1150 'line_ids': fields.one2many('account.move.line', 'tax_code_id', 'Lines'),
1151 'company_id': fields.many2one('res.company', 'Company', required=True),
1152 'sign': fields.float('Sign for parent', required=True),
1153 'notprintable':fields.boolean("Not Printable in Invoice", help="Check this box if you don't want any VAT related to this Tax Code to appear on invoices"),
1157 def name_get(self, cr, uid, ids, context=None):
1160 if isinstance(ids, (int, long)):
1162 reads = self.read(cr, uid, ids, ['name','code'], context, load='_classic_write')
1163 return [(x['id'], (x['code'] and x['code'] + ' - ' or '') + x['name']) \
1166 def _default_company(self, cr, uid, context={}):
1167 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
1169 return user.company_id.id
1170 return self.pool.get('res.company').search(cr, uid, [('parent_id', '=', False)])[0]
1172 'company_id': _default_company,
1173 'sign': lambda *args: 1.0,
1174 'notprintable': lambda *a: False,
1176 def _check_recursion(self, cr, uid, ids):
1179 cr.execute('select distinct parent_id from account_tax_code where id in ('+','.join(map(str,ids))+')')
1180 ids = filter(None, map(lambda x:x[0], cr.fetchall()))
1187 (_check_recursion, 'Error ! You can not create recursive accounts.', ['parent_id'])
1189 _order = 'code,name'
1192 class account_tax(osv.osv):
1196 Type: percent, fixed, none, code
1197 PERCENT: tax = price * amount
1198 FIXED: tax = price + amount
1200 CODE: execute python code. localcontext = {'price_unit':pu, 'address':address_object}
1201 return result in the context
1202 Ex: result=round(price_unit*0.21,4)
1204 _name = 'account.tax'
1205 _description = 'Tax'
1207 'name': fields.char('Tax Name', size=64, required=True, translate=True, help="This name will be displayed on reports"),
1208 'sequence': fields.integer('Sequence', required=True, help="The sequence field is used to order the tax lines from the lowest sequences to the higher ones. The order is important if you have a tax with several tax children. In this case, the evaluation order is important."),
1209 'amount': fields.float('Amount', required=True, digits=(14,4)),
1210 'active': fields.boolean('Active'),
1211 'type': fields.selection( [('percent','Percent'), ('fixed','Fixed'), ('none','None'), ('code','Python Code'),('balance','Balance')], 'Tax Type', required=True,
1212 help="The computation method for the tax amount."),
1213 'applicable_type': fields.selection( [('true','True'), ('code','Python Code')], 'Applicable Type', required=True,
1214 help="If not applicable (computed through a Python code), the tax won't appear on the invoice."),
1215 'domain':fields.char('Domain', size=32, help="This field is only used if you develop your own module allowing developers to create specific taxes in a custom domain."),
1216 'account_collected_id':fields.many2one('account.account', 'Invoice Tax Account'),
1217 'account_paid_id':fields.many2one('account.account', 'Refund Tax Account'),
1218 'parent_id':fields.many2one('account.tax', 'Parent Tax Account', select=True),
1219 'child_ids':fields.one2many('account.tax', 'parent_id', 'Child Tax Accounts'),
1220 'child_depend':fields.boolean('Tax on Children', help="Set if the tax computation is based on the computation of child taxes rather than on the total amount."),
1221 'python_compute':fields.text('Python Code'),
1222 'python_compute_inv':fields.text('Python Code (reverse)'),
1223 'python_applicable':fields.text('Python Code'),
1224 'tax_group': fields.selection([('vat','VAT'),('other','Other')], 'Tax Group', help="If a default tax is given in the partner it only overrides taxes from accounts (or products) in the same group."),
1227 # Fields used for the VAT declaration
1229 'base_code_id': fields.many2one('account.tax.code', 'Base Code', help="Use this code for the VAT declaration."),
1230 'tax_code_id': fields.many2one('account.tax.code', 'Tax Code', help="Use this code for the VAT declaration."),
1231 'base_sign': fields.float('Base Code Sign', help="Usually 1 or -1."),
1232 'tax_sign': fields.float('Tax Code Sign', help="Usually 1 or -1."),
1234 # Same fields for refund invoices
1236 'ref_base_code_id': fields.many2one('account.tax.code', 'Refund Base Code', help="Use this code for the VAT declaration."),
1237 'ref_tax_code_id': fields.many2one('account.tax.code', 'Refund Tax Code', help="Use this code for the VAT declaration."),
1238 'ref_base_sign': fields.float('Base Code Sign', help="Usually 1 or -1."),
1239 'ref_tax_sign': fields.float('Tax Code Sign', help="Usually 1 or -1."),
1240 'include_base_amount': fields.boolean('Include in base amount', help="Indicate if the amount of tax must be included in the base amount for the computation of the next taxes"),
1241 'company_id': fields.many2one('res.company', 'Company', required=True),
1242 'description': fields.char('Tax Code',size=32),
1243 'price_include': fields.boolean('Tax Included in Price', help="Check this if the price you use on the product and invoices includes this tax."),
1244 'type_tax_use': fields.selection([('sale','Sale'),('purchase','Purchase'),('all','All')], 'Tax Application', required=True)
1247 def search(self, cr, uid, args, offset=0, limit=None, order=None,
1248 context=None, count=False):
1249 if context and context.has_key('type'):
1250 if context['type'] in ('out_invoice','out_refund'):
1251 args.append(('type_tax_use','in',['sale','all']))
1252 elif context['type'] in ('in_invoice','in_refund'):
1253 args.append(('type_tax_use','in',['purchase','all']))
1254 return super(account_tax, self).search(cr, uid, args, offset, limit, order, context, count)
1256 def name_get(self, cr, uid, ids, context={}):
1260 for record in self.read(cr, uid, ids, ['description','name'], context):
1261 name = record['description'] and record['description'] or record['name']
1262 res.append((record['id'],name ))
1265 def _default_company(self, cr, uid, context={}):
1266 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
1268 return user.company_id.id
1269 return self.pool.get('res.company').search(cr, uid, [('parent_id', '=', False)])[0]
1271 'python_compute': lambda *a: '''# price_unit\n# address : res.partner.address object or False\n# product : product.product object or None\n# partner : res.partner object or None\n\nresult = price_unit * 0.10''',
1272 'python_compute_inv': lambda *a: '''# price_unit\n# address : res.partner.address object or False\n# product : product.product object or False\n\nresult = price_unit * 0.10''',
1273 'applicable_type': lambda *a: 'true',
1274 'type': lambda *a: 'percent',
1275 'amount': lambda *a: 0,
1276 'price_include': lambda *a: 0,
1277 'active': lambda *a: 1,
1278 'type_tax_use': lambda *a: 'all',
1279 'sequence': lambda *a: 1,
1280 'tax_group': lambda *a: 'vat',
1281 'ref_tax_sign': lambda *a: 1,
1282 'ref_base_sign': lambda *a: 1,
1283 'tax_sign': lambda *a: 1,
1284 'base_sign': lambda *a: 1,
1285 'include_base_amount': lambda *a: False,
1286 'company_id': _default_company,
1290 def _applicable(self, cr, uid, taxes, price_unit, address_id=None, product=None, partner=None):
1293 if tax.applicable_type=='code':
1294 localdict = {'price_unit':price_unit, 'address':self.pool.get('res.partner.address').browse(cr, uid, address_id), 'product':product, 'partner':partner}
1295 exec tax.python_applicable in localdict
1296 if localdict.get('result', False):
1302 def _unit_compute(self, cr, uid, taxes, price_unit, address_id=None, product=None, partner=None, quantity=0):
1303 taxes = self._applicable(cr, uid, taxes, price_unit, address_id, product, partner)
1306 cur_price_unit=price_unit
1308 # we compute the amount for the current tax object and append it to the result
1310 data = {'id':tax.id,
1312 'account_collected_id':tax.account_collected_id.id,
1313 'account_paid_id':tax.account_paid_id.id,
1314 'base_code_id': tax.base_code_id.id,
1315 'ref_base_code_id': tax.ref_base_code_id.id,
1316 'sequence': tax.sequence,
1317 'base_sign': tax.base_sign,
1318 'tax_sign': tax.tax_sign,
1319 'ref_base_sign': tax.ref_base_sign,
1320 'ref_tax_sign': tax.ref_tax_sign,
1321 'price_unit': cur_price_unit,
1322 'tax_code_id': tax.tax_code_id.id,
1323 'ref_tax_code_id': tax.ref_tax_code_id.id,
1326 if tax.type=='percent':
1327 amount = cur_price_unit * tax.amount
1328 data['amount'] = amount
1330 elif tax.type=='fixed':
1331 data['amount'] = tax.amount
1332 data['tax_amount']=quantity
1333 # data['amount'] = quantity
1334 elif tax.type=='code':
1335 address = address_id and self.pool.get('res.partner.address').browse(cr, uid, address_id) or None
1336 localdict = {'price_unit':cur_price_unit, 'address':address, 'product':product, 'partner':partner}
1337 exec tax.python_compute in localdict
1338 amount = localdict['result']
1339 data['amount'] = amount
1340 elif tax.type=='balance':
1341 data['amount'] = cur_price_unit - reduce(lambda x,y: y.get('amount',0.0)+x, res, 0.0)
1342 data['balance'] = cur_price_unit
1344 amount2 = data['amount']
1345 if len(tax.child_ids):
1346 if tax.child_depend:
1349 child_tax = self._unit_compute(cr, uid, tax.child_ids, amount, address_id, product, partner, quantity)
1350 res.extend(child_tax)
1351 if tax.child_depend:
1353 for name in ('base','ref_base'):
1354 if latest[name+'_code_id'] and latest[name+'_sign'] and not r[name+'_code_id']:
1355 r[name+'_code_id'] = latest[name+'_code_id']
1356 r[name+'_sign'] = latest[name+'_sign']
1357 r['price_unit'] = latest['price_unit']
1358 latest[name+'_code_id'] = False
1359 for name in ('tax','ref_tax'):
1360 if latest[name+'_code_id'] and latest[name+'_sign'] and not r[name+'_code_id']:
1361 r[name+'_code_id'] = latest[name+'_code_id']
1362 r[name+'_sign'] = latest[name+'_sign']
1363 r['amount'] = data['amount']
1364 latest[name+'_code_id'] = False
1365 if tax.include_base_amount:
1366 cur_price_unit+=amount2
1369 def compute(self, cr, uid, taxes, price_unit, quantity, address_id=None, product=None, partner=None):
1372 Compute tax values for given PRICE_UNIT, QUANTITY and a buyer/seller ADDRESS_ID.
1376 tax = {'name':'', 'amount':0.0, 'account_collected_id':1, 'account_paid_id':2}
1377 one tax for each tax id in IDS and their childs
1379 res = self._unit_compute(cr, uid, taxes, price_unit, address_id, product, partner, quantity)
1382 if r.get('balance',False):
1383 r['amount'] = round(r['balance'] * quantity, 2) - total
1385 r['amount'] = round(r['amount'] * quantity, 2)
1386 total += r['amount']
1390 def _unit_compute_inv(self, cr, uid, taxes, price_unit, address_id=None, product=None, partner=None):
1391 taxes = self._applicable(cr, uid, taxes, price_unit, address_id, product, partner)
1395 cur_price_unit = price_unit
1397 tax_parent_tot = 0.0
1399 if (tax.type=='percent') and not tax.include_base_amount:
1400 tax_parent_tot += tax.amount
1403 if (tax.type=='fixed') and not tax.include_base_amount:
1404 cur_price_unit -= tax.amount
1407 if tax.type=='percent':
1408 if tax.include_base_amount:
1409 amount = cur_price_unit - (cur_price_unit / (1 + tax.amount))
1411 amount = (cur_price_unit / (1 + tax_parent_tot)) * tax.amount
1413 elif tax.type=='fixed':
1416 elif tax.type=='code':
1417 address = address_id and self.pool.get('res.partner.address').browse(cr, uid, address_id) or None
1418 localdict = {'price_unit':cur_price_unit, 'address':address, 'product':product, 'partner':partner}
1419 exec tax.python_compute_inv in localdict
1420 amount = localdict['result']
1421 elif tax.type=='balance':
1422 data['amount'] = cur_price_unit - reduce(lambda x,y: y.get('amount',0.0)+x, res, 0.0)
1423 data['balance'] = cur_price_unit
1426 if tax.include_base_amount:
1427 cur_price_unit -= amount
1436 'account_collected_id': tax.account_collected_id.id,
1437 'account_paid_id': tax.account_paid_id.id,
1438 'base_code_id': tax.base_code_id.id,
1439 'ref_base_code_id': tax.ref_base_code_id.id,
1440 'sequence': tax.sequence,
1441 'base_sign': tax.base_sign,
1442 'tax_sign': tax.tax_sign,
1443 'ref_base_sign': tax.ref_base_sign,
1444 'ref_tax_sign': tax.ref_tax_sign,
1445 'price_unit': cur_price_unit,
1446 'tax_code_id': tax.tax_code_id.id,
1447 'ref_tax_code_id': tax.ref_tax_code_id.id,
1449 if len(tax.child_ids):
1450 if tax.child_depend:
1454 parent_tax = self._unit_compute_inv(cr, uid, tax.child_ids, amount, address_id, product, partner)
1455 res.extend(parent_tax)
1460 total += r['amount']
1462 r['price_unit'] -= total
1466 def compute_inv(self, cr, uid, taxes, price_unit, quantity, address_id=None, product=None, partner=None):
1468 Compute tax values for given PRICE_UNIT, QUANTITY and a buyer/seller ADDRESS_ID.
1469 Price Unit is a VAT included price
1473 tax = {'name':'', 'amount':0.0, 'account_collected_id':1, 'account_paid_id':2}
1474 one tax for each tax id in IDS and their childs
1476 res = self._unit_compute_inv(cr, uid, taxes, price_unit, address_id, product, partner=None)
1479 if r.get('balance',False):
1480 r['amount'] = round(r['balance'] * quantity, 2) - total
1482 r['amount'] = round(r['amount'] * quantity, 2)
1483 total += r['amount']
1487 # ---------------------------------------------------------
1488 # Account Entries Models
1489 # ---------------------------------------------------------
1491 class account_model(osv.osv):
1492 _name = "account.model"
1493 _description = "Account Model"
1495 'name': fields.char('Model Name', size=64, required=True, help="This is a model for recurring accounting entries"),
1496 'ref': fields.char('Ref', size=64),
1497 'journal_id': fields.many2one('account.journal', 'Journal', required=True),
1498 'lines_id': fields.one2many('account.model.line', 'model_id', 'Model Entries'),
1499 'legend' :fields.text('Legend',readonly=True,size=100),
1503 'legend': lambda self, cr, uid, context:_('You can specify year, month and date in the name of the model using the following labels:\n\n%(year)s : To Specify Year \n%(month)s : To Specify Month \n%(date)s : Current Date\n\ne.g. My model on %(date)s'),
1505 def generate(self, cr, uid, ids, datas={}, context={}):
1507 for model in self.browse(cr, uid, ids, context):
1508 period_id = self.pool.get('account.period').find(cr,uid, context=context)
1510 raise osv.except_osv(_('No period found !'), _('Unable to find a valid period !'))
1511 period_id = period_id[0]
1512 move_id = self.pool.get('account.move').create(cr, uid, {
1514 'period_id': period_id,
1515 'journal_id': model.journal_id.id,
1517 move_ids.append(move_id)
1518 for line in model.lines_id:
1521 'journal_id': model.journal_id.id,
1522 'period_id': period_id
1526 'quantity': line.quantity,
1527 'debit': line.debit,
1528 'credit': line.credit,
1529 'account_id': line.account_id.id,
1532 'partner_id': line.partner_id.id,
1533 'date': time.strftime('%Y-%m-%d'),
1534 'date_maturity': time.strftime('%Y-%m-%d')
1537 c.update({'journal_id': model.journal_id.id,'period_id': period_id})
1538 self.pool.get('account.move.line').create(cr, uid, val, context=c)
1542 class account_model_line(osv.osv):
1543 _name = "account.model.line"
1544 _description = "Account Model Entries"
1546 'name': fields.char('Name', size=64, required=True),
1547 'sequence': fields.integer('Sequence', required=True, help="The sequence field is used to order the resources from lower sequences to higher ones"),
1548 'quantity': fields.float('Quantity', digits=(16,2), help="The optional quantity on entries"),
1549 'debit': fields.float('Debit', digits=(16,2)),
1550 'credit': fields.float('Credit', digits=(16,2)),
1552 'account_id': fields.many2one('account.account', 'Account', required=True, ondelete="cascade"),
1554 'model_id': fields.many2one('account.model', 'Model', required=True, ondelete="cascade", select=True),
1556 'ref': fields.char('Ref.', size=16),
1558 'amount_currency': fields.float('Amount Currency', help="The amount expressed in an optional other currency."),
1559 'currency_id': fields.many2one('res.currency', 'Currency'),
1561 'partner_id': fields.many2one('res.partner', 'Partner Ref.'),
1562 'date_maturity': fields.selection([('today','Date of the day'), ('partner','Partner Payment Term')], 'Maturity date', help="The maturity date of the generated entries for this model. You can chosse between the date of the creation action or the the date of the creation of the entries plus the partner payment terms."),
1563 'date': fields.selection([('today','Date of the day'), ('partner','Partner Payment Term')], 'Current Date', required=True, help="The date of the generated entries"),
1566 'date': lambda *a: 'today'
1569 _sql_constraints = [
1570 ('credit_debit1', 'CHECK (credit*debit=0)', 'Wrong credit or debit value in model !'),
1571 ('credit_debit2', 'CHECK (credit+debit>=0)', 'Wrong credit or debit value in model !'),
1573 account_model_line()
1575 # ---------------------------------------------------------
1576 # Account Subscription
1577 # ---------------------------------------------------------
1580 class account_subscription(osv.osv):
1581 _name = "account.subscription"
1582 _description = "Account Subscription"
1584 'name': fields.char('Name', size=64, required=True),
1585 'ref': fields.char('Ref', size=16),
1586 'model_id': fields.many2one('account.model', 'Model', required=True),
1588 'date_start': fields.date('Start Date', required=True),
1589 'period_total': fields.integer('Number of Periods', required=True),
1590 'period_nbr': fields.integer('Period', required=True),
1591 'period_type': fields.selection([('day','days'),('month','month'),('year','year')], 'Period Type', required=True),
1592 'state': fields.selection([('draft','Draft'),('running','Running'),('done','Done')], 'Status', required=True, readonly=True),
1594 'lines_id': fields.one2many('account.subscription.line', 'subscription_id', 'Subscription Lines')
1597 'date_start': lambda *a: time.strftime('%Y-%m-%d'),
1598 'period_type': lambda *a: 'month',
1599 'period_total': lambda *a: 12,
1600 'period_nbr': lambda *a: 1,
1601 'state': lambda *a: 'draft',
1603 def state_draft(self, cr, uid, ids, context={}):
1604 self.write(cr, uid, ids, {'state':'draft'})
1607 def check(self, cr, uid, ids, context={}):
1609 for sub in self.browse(cr, uid, ids, context):
1611 for line in sub.lines_id:
1612 if not line.move_id.id:
1616 todone.append(sub.id)
1618 self.write(cr, uid, todone, {'state':'done'})
1621 def remove_line(self, cr, uid, ids, context={}):
1623 for sub in self.browse(cr, uid, ids, context):
1624 for line in sub.lines_id:
1625 if not line.move_id.id:
1626 toremove.append(line.id)
1628 self.pool.get('account.subscription.line').unlink(cr, uid, toremove)
1629 self.write(cr, uid, ids, {'state':'draft'})
1632 def compute(self, cr, uid, ids, context={}):
1633 for sub in self.browse(cr, uid, ids, context):
1635 for i in range(sub.period_total):
1636 self.pool.get('account.subscription.line').create(cr, uid, {
1638 'subscription_id': sub.id,
1640 if sub.period_type=='day':
1641 ds = (mx.DateTime.strptime(ds, '%Y-%m-%d') + RelativeDateTime(days=sub.period_nbr)).strftime('%Y-%m-%d')
1642 if sub.period_type=='month':
1643 ds = (mx.DateTime.strptime(ds, '%Y-%m-%d') + RelativeDateTime(months=sub.period_nbr)).strftime('%Y-%m-%d')
1644 if sub.period_type=='year':
1645 ds = (mx.DateTime.strptime(ds, '%Y-%m-%d') + RelativeDateTime(years=sub.period_nbr)).strftime('%Y-%m-%d')
1646 self.write(cr, uid, ids, {'state':'running'})
1648 account_subscription()
1650 class account_subscription_line(osv.osv):
1651 _name = "account.subscription.line"
1652 _description = "Account Subscription Line"
1654 'subscription_id': fields.many2one('account.subscription', 'Subscription', required=True, select=True),
1655 'date': fields.date('Date', required=True),
1656 'move_id': fields.many2one('account.move', 'Entry'),
1660 def move_create(self, cr, uid, ids, context={}):
1662 for line in self.browse(cr, uid, ids, context):
1666 ids = self.pool.get('account.model').generate(cr, uid, [line.subscription_id.model_id.id], datas, context)
1667 tocheck[line.subscription_id.id] = True
1668 self.write(cr, uid, [line.id], {'move_id':ids[0]})
1670 self.pool.get('account.subscription').check(cr, uid, tocheck.keys(), context)
1673 account_subscription_line()
1676 class account_config_wizard(osv.osv_memory):
1677 _name = 'account.config.wizard'
1679 def _get_charts(self, cr, uid, context):
1680 module_obj=self.pool.get('ir.module.module')
1681 ids=module_obj.search(cr, uid, [('category_id', '=', 'Account Charts'), ('state', '<>', 'installed')])
1682 res=[(m.id, m.shortdesc) for m in module_obj.browse(cr, uid, ids)]
1683 res.append((-1, 'None'))
1684 res.sort(key=lambda x: x[1])
1688 'name':fields.char('Name', required=True, size=64, help="Name of the fiscal year as displayed on screens."),
1689 'code':fields.char('Code', required=True, size=64, help="Name of the fiscal year as displayed in reports."),
1690 'date1': fields.date('Start Date', required=True),
1691 'date2': fields.date('End Date', required=True),
1692 'period':fields.selection([('month','Month'),('3months','3 Months')], 'Periods', required=True),
1693 'charts' : fields.selection(_get_charts, 'Charts of Account',required=True)
1696 'code': lambda *a: time.strftime('%Y'),
1697 'name': lambda *a: time.strftime('%Y'),
1698 'date1': lambda *a: time.strftime('%Y-01-01'),
1699 'date2': lambda *a: time.strftime('%Y-12-31'),
1700 'period':lambda *a:'month',
1702 def action_cancel(self,cr,uid,ids,conect=None):
1704 'view_type': 'form',
1705 "view_mode": 'form',
1706 'res_model': 'ir.actions.configuration.wizard',
1707 'type': 'ir.actions.act_window',
1711 def install_account_chart(self, cr, uid, ids, context=None):
1712 for res in self.read(cr,uid,ids):
1713 chart_id = res['charts']
1715 mod_obj = self.pool.get('ir.module.module')
1716 mod_obj.button_install(cr, uid, [chart_id], context=context)
1718 db, pool = pooler.restart_pool(cr.dbname, update_module=True)
1720 def action_create(self, cr, uid,ids, context=None):
1721 for res in self.read(cr,uid,ids):
1722 if 'date1' in res and 'date2' in res:
1723 res_obj = self.pool.get('account.fiscalyear')
1724 start_date=res['date1']
1725 end_date=res['date2']
1726 name=res['name']#DateTime.strptime(start_date, '%Y-%m-%d').strftime('%m.%Y') + '-' + DateTime.strptime(end_date, '%Y-%m-%d').strftime('%m.%Y')
1730 'date_start':start_date,
1731 'date_stop':end_date,
1733 new_id=res_obj.create(cr, uid, vals, context=context)
1734 if res['period']=='month':
1735 res_obj.create_period(cr,uid,[new_id])
1736 elif res['period']=='3months':
1737 res_obj.create_period3(cr,uid,[new_id])
1738 self.install_account_chart(cr,uid,ids)
1740 'view_type': 'form',
1741 "view_mode": 'form',
1742 'res_model': 'ir.actions.configuration.wizard',
1743 'type': 'ir.actions.act_window',
1749 account_config_wizard()
1752 # ---------------------------------------------------------------
1753 # Account Templates : Account, Tax, Tax Code and chart. + Wizard
1754 # ---------------------------------------------------------------
1756 class account_tax_template(osv.osv):
1757 _name = 'account.tax.template'
1758 account_tax_template()
1760 class account_account_template(osv.osv):
1762 _name = "account.account.template"
1763 _description ='Templates for Accounts'
1766 'name': fields.char('Name', size=128, required=True, select=True),
1767 'currency_id': fields.many2one('res.currency', 'Secondary Currency', help="Force all moves for this account to have this secondary currency."),
1768 'code': fields.char('Code', size=64),
1769 'type': fields.selection([
1770 ('receivable','Receivable'),
1771 ('payable','Payable'),
1773 ('consolidation','Consolidation'),
1775 ('closed','Closed'),
1776 ], 'Internal Type', required=True,help="This type is used to differenciate types with "\
1777 "special effects in Open ERP: view can not have entries, consolidation are accounts that "\
1778 "can have children accounts for multi-company consolidations, payable/receivable are for "\
1779 "partners accounts (for debit/credit computations), closed for deprecated accounts."),
1780 'user_type': fields.many2one('account.account.type', 'Account Type', required=True,
1781 help="These types are defined according to your country. The type contain more information "\
1782 "about the account and it's specificities."),
1783 'reconcile': fields.boolean('Allow Reconciliation', help="Check this option if you want the user to reconcile entries in this account."),
1784 'shortcut': fields.char('Shortcut', size=12),
1785 'note': fields.text('Note'),
1786 'parent_id': fields.many2one('account.account.template','Parent Account Template', ondelete='cascade'),
1787 'child_parent_ids':fields.one2many('account.account.template','parent_id','Children'),
1788 'tax_ids': fields.many2many('account.tax.template', 'account_account_template_tax_rel','account_id','tax_id', 'Default Taxes'),
1792 'reconcile': lambda *a: False,
1793 'type' : lambda *a :'view',
1796 def _check_recursion(self, cr, uid, ids):
1799 cr.execute('select parent_id from account_account_template where id in ('+','.join(map(str,ids))+')')
1800 ids = filter(None, map(lambda x:x[0], cr.fetchall()))
1807 (_check_recursion, 'Error ! You can not create recursive account templates.', ['parent_id'])
1811 def name_get(self, cr, uid, ids, context={}):
1814 reads = self.read(cr, uid, ids, ['name','code'], context)
1816 for record in reads:
1817 name = record['name']
1819 name = record['code']+' '+name
1820 res.append((record['id'],name ))
1823 account_account_template()
1825 class account_tax_code_template(osv.osv):
1827 _name = 'account.tax.code.template'
1828 _description = 'Tax Code Template'
1832 'name': fields.char('Tax Case Name', size=64, required=True),
1833 'code': fields.char('Case Code', size=64),
1834 'info': fields.text('Description'),
1835 'parent_id': fields.many2one('account.tax.code.template', 'Parent Code', select=True),
1836 'child_ids': fields.one2many('account.tax.code.template', 'parent_id', 'Child Codes'),
1837 'sign': fields.float('Sign for parent', required=True),
1838 'notprintable':fields.boolean("Not Printable in Invoice", help="Check this box if you don't want any VAT related to this Tax Code to appear on invoices"),
1842 'sign': lambda *args: 1.0,
1843 'notprintable': lambda *a: False,
1846 def name_get(self, cr, uid, ids, context=None):
1849 if isinstance(ids, (int, long)):
1851 reads = self.read(cr, uid, ids, ['name','code'], context, load='_classic_write')
1852 return [(x['id'], (x['code'] and x['code'] + ' - ' or '') + x['name']) \
1855 def _check_recursion(self, cr, uid, ids):
1858 cr.execute('select distinct parent_id from account_tax_code_template where id in ('+','.join(map(str,ids))+')')
1859 ids = filter(None, map(lambda x:x[0], cr.fetchall()))
1866 (_check_recursion, 'Error ! You can not create recursive Tax Codes.', ['parent_id'])
1868 _order = 'code,name'
1869 account_tax_code_template()
1872 class account_chart_template(osv.osv):
1873 _name="account.chart.template"
1874 _description= "Templates for Account Chart"
1877 'name': fields.char('Name', size=64, required=True),
1878 'account_root_id': fields.many2one('account.account.template','Root Account',required=True,domain=[('parent_id','=',False)]),
1879 'tax_code_root_id': fields.many2one('account.tax.code.template','Root Tax Code',required=True,domain=[('parent_id','=',False)]),
1880 'tax_template_ids': fields.one2many('account.tax.template', 'chart_template_id', 'Tax Template List', help='List of all the taxes that have to be installed by the wizard'),
1881 'bank_account_view_id': fields.many2one('account.account.template','Bank Account',required=True),
1882 'property_account_receivable': fields.many2one('account.account.template','Receivable Account'),
1883 'property_account_payable': fields.many2one('account.account.template','Payable Account'),
1884 'property_account_expense_categ': fields.many2one('account.account.template','Expense Category Account'),
1885 'property_account_income_categ': fields.many2one('account.account.template','Income Category Account'),
1886 'property_account_expense': fields.many2one('account.account.template','Expense Account on Product Template'),
1887 'property_account_income': fields.many2one('account.account.template','Income Account on Product Template'),
1890 account_chart_template()
1892 class account_tax_template(osv.osv):
1894 _name = 'account.tax.template'
1895 _description = 'Templates for Taxes'
1898 'chart_template_id': fields.many2one('account.chart.template', 'Chart Template', required=True),
1899 'name': fields.char('Tax Name', size=64, required=True),
1900 'sequence': fields.integer('Sequence', required=True, help="The sequence field is used to order the taxes lines from lower sequences to higher ones. The order is important if you have a tax that has several tax children. In this case, the evaluation order is important."),
1901 'amount': fields.float('Amount', required=True, digits=(14,4)),
1902 'type': fields.selection( [('percent','Percent'), ('fixed','Fixed'), ('none','None'), ('code','Python Code')], 'Tax Type', required=True),
1903 'applicable_type': fields.selection( [('true','True'), ('code','Python Code')], 'Applicable Type', required=True),
1904 'domain':fields.char('Domain', size=32, help="This field is only used if you develop your own module allowing developers to create specific taxes in a custom domain."),
1905 'account_collected_id':fields.many2one('account.account.template', 'Invoice Tax Account'),
1906 'account_paid_id':fields.many2one('account.account.template', 'Refund Tax Account'),
1907 'parent_id':fields.many2one('account.tax.template', 'Parent Tax Account', select=True),
1908 'child_depend':fields.boolean('Tax on Children', help="Indicate if the tax computation is based on the value computed for the computation of child taxes or based on the total amount."),
1909 'python_compute':fields.text('Python Code'),
1910 'python_compute_inv':fields.text('Python Code (reverse)'),
1911 'python_applicable':fields.text('Python Code'),
1912 'tax_group': fields.selection([('vat','VAT'),('other','Other')], 'Tax Group', help="If a default tax if given in the partner it only override taxes from account (or product) of the same group."),
1915 # Fields used for the VAT declaration
1917 'base_code_id': fields.many2one('account.tax.code.template', 'Base Code', help="Use this code for the VAT declaration."),
1918 'tax_code_id': fields.many2one('account.tax.code.template', 'Tax Code', help="Use this code for the VAT declaration."),
1919 'base_sign': fields.float('Base Code Sign', help="Usually 1 or -1."),
1920 'tax_sign': fields.float('Tax Code Sign', help="Usually 1 or -1."),
1922 # Same fields for refund invoices
1924 'ref_base_code_id': fields.many2one('account.tax.code.template', 'Refund Base Code', help="Use this code for the VAT declaration."),
1925 'ref_tax_code_id': fields.many2one('account.tax.code.template', 'Refund Tax Code', help="Use this code for the VAT declaration."),
1926 'ref_base_sign': fields.float('Base Code Sign', help="Usually 1 or -1."),
1927 'ref_tax_sign': fields.float('Tax Code Sign', help="Usually 1 or -1."),
1928 'include_base_amount': fields.boolean('Include in Base Amount', help="Set if the amount of tax must be included in the base amount before computing the next taxes."),
1929 'description': fields.char('Internal Name', size=32),
1930 'type_tax_use': fields.selection([('sale','Sale'),('purchase','Purchase'),('all','All')], 'Tax Use In', required=True,)
1933 def name_get(self, cr, uid, ids, context={}):
1937 for record in self.read(cr, uid, ids, ['description','name'], context):
1938 name = record['description'] and record['description'] or record['name']
1939 res.append((record['id'],name ))
1942 def _default_company(self, cr, uid, context={}):
1943 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
1945 return user.company_id.id
1946 return self.pool.get('res.company').search(cr, uid, [('parent_id', '=', False)])[0]
1949 'python_compute': lambda *a: '''# price_unit\n# address : res.partner.address object or False\n# product : product.product object or None\n# partner : res.partner object or None\n\nresult = price_unit * 0.10''',
1950 'python_compute_inv': lambda *a: '''# price_unit\n# address : res.partner.address object or False\n# product : product.product object or False\n\nresult = price_unit * 0.10''',
1951 'applicable_type': lambda *a: 'true',
1952 'type': lambda *a: 'percent',
1953 'amount': lambda *a: 0,
1954 'sequence': lambda *a: 1,
1955 'tax_group': lambda *a: 'vat',
1956 'ref_tax_sign': lambda *a: 1,
1957 'ref_base_sign': lambda *a: 1,
1958 'tax_sign': lambda *a: 1,
1959 'base_sign': lambda *a: 1,
1960 'include_base_amount': lambda *a: False,
1961 'type_tax_use': lambda *a: 'all',
1966 account_tax_template()
1968 # Fiscal Position Templates
1970 class account_fiscal_position_template(osv.osv):
1971 _name = 'account.fiscal.position.template'
1972 _description = 'Template for Fiscal Position'
1975 'name': fields.char('Fiscal Position Template', size=64, translate=True, required=True),
1976 'chart_template_id': fields.many2one('account.chart.template', 'Chart Template', required=True),
1977 'account_ids': fields.one2many('account.fiscal.position.account.template', 'position_id', 'Account Mapping'),
1978 'tax_ids': fields.one2many('account.fiscal.position.tax.template', 'position_id', 'Tax Mapping')
1981 account_fiscal_position_template()
1983 class account_fiscal_position_tax_template(osv.osv):
1984 _name = 'account.fiscal.position.tax.template'
1985 _description = 'Fiscal Position Template Tax Mapping'
1986 _rec_name = 'position_id'
1989 'position_id': fields.many2one('account.fiscal.position.template', 'Fiscal Position', required=True, ondelete='cascade'),
1990 'tax_src_id': fields.many2one('account.tax.template', 'Tax Source', required=True),
1991 'tax_dest_id': fields.many2one('account.tax.template', 'Replacement Tax')
1994 account_fiscal_position_tax_template()
1996 class account_fiscal_position_account_template(osv.osv):
1997 _name = 'account.fiscal.position.account.template'
1998 _description = 'Fiscal Position Template Account Mapping'
1999 _rec_name = 'position_id'
2001 'position_id': fields.many2one('account.fiscal.position.template', 'Fiscal Position', required=True, ondelete='cascade'),
2002 'account_src_id': fields.many2one('account.account.template', 'Account Source', domain=[('type','<>','view')], required=True),
2003 'account_dest_id': fields.many2one('account.account.template', 'Account Destination', domain=[('type','<>','view')], required=True)
2006 account_fiscal_position_account_template()
2008 # Multi charts of Accounts wizard
2010 class wizard_multi_charts_accounts(osv.osv_memory):
2012 Create a new account chart for a company.
2015 * an account chart template
2016 * a number of digits for formatting code of non-view accounts
2017 * a list of bank accounts owned by the company
2019 * generates all accounts from the template and assigns them to the right company
2020 * generates all taxes and tax codes, changing account assignations
2021 * generates all accounting properties and assigns them correctly
2023 _name='wizard.multi.charts.accounts'
2026 'company_id':fields.many2one('res.company','Company',required=True),
2027 'chart_template_id': fields.many2one('account.chart.template','Chart Template',required=True),
2028 'bank_accounts_id': fields.one2many('account.bank.accounts.wizard', 'bank_account_id', 'Bank Accounts',required=True),
2029 'code_digits':fields.integer('# of Digits',required=True,help="No. of Digits to use for account code"),
2030 'seq_journal':fields.boolean('Separated Journal Sequences',help="Check this box if you want to use a different sequence for each created journal. Otherwise, all will use the same sequence."),
2033 def _get_chart(self, cr, uid, context={}):
2034 ids = self.pool.get('account.chart.template').search(cr, uid, [], context=context)
2039 'company_id': lambda self, cr, uid, c: self.pool.get('res.users').browse(cr,uid,[uid],c)[0].company_id.id,
2040 'chart_template_id': _get_chart,
2041 'code_digits': lambda *a:6,
2044 def action_create(self, cr, uid, ids, context=None):
2045 obj_multi = self.browse(cr,uid,ids[0])
2046 obj_acc = self.pool.get('account.account')
2047 obj_acc_tax = self.pool.get('account.tax')
2048 obj_journal = self.pool.get('account.journal')
2049 obj_sequence = self.pool.get('ir.sequence')
2050 obj_acc_template = self.pool.get('account.account.template')
2051 obj_fiscal_position_template = self.pool.get('account.fiscal.position.template')
2052 obj_fiscal_position = self.pool.get('account.fiscal.position')
2055 obj_acc_root = obj_multi.chart_template_id.account_root_id
2056 tax_code_root_id = obj_multi.chart_template_id.tax_code_root_id.id
2057 company_id = obj_multi.company_id.id
2060 acc_template_ref = {}
2061 tax_template_ref = {}
2062 tax_code_template_ref = {}
2065 #create all the tax code
2066 children_tax_code_template = self.pool.get('account.tax.code.template').search(cr, uid, [('parent_id','child_of',[tax_code_root_id])], order='id')
2067 for tax_code_template in self.pool.get('account.tax.code.template').browse(cr, uid, children_tax_code_template):
2069 'name': (tax_code_root_id == tax_code_template.id) and obj_multi.company_id.name or tax_code_template.name,
2070 'code': tax_code_template.code,
2071 'info': tax_code_template.info,
2072 'parent_id': tax_code_template.parent_id and ((tax_code_template.parent_id.id in tax_code_template_ref) and tax_code_template_ref[tax_code_template.parent_id.id]) or False,
2073 'company_id': company_id,
2074 'sign': tax_code_template.sign,
2076 new_tax_code = self.pool.get('account.tax.code').create(cr,uid,vals)
2077 #recording the new tax code to do the mapping
2078 tax_code_template_ref[tax_code_template.id] = new_tax_code
2081 for tax in obj_multi.chart_template_id.tax_template_ids:
2085 'sequence': tax.sequence,
2086 'amount':tax.amount,
2088 'applicable_type': tax.applicable_type,
2089 'domain':tax.domain,
2090 'parent_id': tax.parent_id and ((tax.parent_id.id in tax_template_ref) and tax_template_ref[tax.parent_id.id]) or False,
2091 'child_depend': tax.child_depend,
2092 'python_compute': tax.python_compute,
2093 'python_compute_inv': tax.python_compute_inv,
2094 'python_applicable': tax.python_applicable,
2095 'tax_group':tax.tax_group,
2096 'base_code_id': tax.base_code_id and ((tax.base_code_id.id in tax_code_template_ref) and tax_code_template_ref[tax.base_code_id.id]) or False,
2097 'tax_code_id': tax.tax_code_id and ((tax.tax_code_id.id in tax_code_template_ref) and tax_code_template_ref[tax.tax_code_id.id]) or False,
2098 'base_sign': tax.base_sign,
2099 'tax_sign': tax.tax_sign,
2100 'ref_base_code_id': tax.ref_base_code_id and ((tax.ref_base_code_id.id in tax_code_template_ref) and tax_code_template_ref[tax.ref_base_code_id.id]) or False,
2101 'ref_tax_code_id': tax.ref_tax_code_id and ((tax.ref_tax_code_id.id in tax_code_template_ref) and tax_code_template_ref[tax.ref_tax_code_id.id]) or False,
2102 'ref_base_sign': tax.ref_base_sign,
2103 'ref_tax_sign': tax.ref_tax_sign,
2104 'include_base_amount': tax.include_base_amount,
2105 'description':tax.description,
2106 'company_id': company_id,
2107 'type_tax_use': tax.type_tax_use
2109 new_tax = obj_acc_tax.create(cr,uid,vals_tax)
2110 #as the accounts have not been created yet, we have to wait before filling these fields
2111 todo_dict[new_tax] = {
2112 'account_collected_id': tax.account_collected_id and tax.account_collected_id.id or False,
2113 'account_paid_id': tax.account_paid_id and tax.account_paid_id.id or False,
2115 tax_template_ref[tax.id] = new_tax
2117 #deactivate the parent_store functionnality on account_account for rapidity purpose
2118 self.pool._init = True
2120 children_acc_template = obj_acc_template.search(cr, uid, [('parent_id','child_of',[obj_acc_root.id])])
2121 children_acc_template.sort()
2122 for account_template in obj_acc_template.browse(cr, uid, children_acc_template):
2124 for tax in account_template.tax_ids:
2125 tax_ids.append(tax_template_ref[tax.id])
2126 #create the account_account
2128 dig = obj_multi.code_digits
2129 code_main = account_template.code and len(account_template.code) or 0
2130 code_acc = account_template.code or ''
2131 if code_main>0 and code_main<=dig and account_template.type != 'view':
2132 code_acc=str(code_acc) + (str('0'*(dig-code_main)))
2134 'name': (obj_acc_root.id == account_template.id) and obj_multi.company_id.name or account_template.name,
2135 #'sign': account_template.sign,
2136 'currency_id': account_template.currency_id and account_template.currency_id.id or False,
2138 'type': account_template.type,
2139 'user_type': account_template.user_type and account_template.user_type.id or False,
2140 'reconcile': account_template.reconcile,
2141 'shortcut': account_template.shortcut,
2142 'note': account_template.note,
2143 'parent_id': account_template.parent_id and ((account_template.parent_id.id in acc_template_ref) and acc_template_ref[account_template.parent_id.id]) or False,
2144 'tax_ids': [(6,0,tax_ids)],
2145 'company_id': company_id,
2147 new_account = obj_acc.create(cr,uid,vals)
2148 acc_template_ref[account_template.id] = new_account
2149 #reactivate the parent_store functionnality on account_account
2150 self.pool._init = False
2151 self.pool.get('account.account')._parent_store_compute(cr)
2153 for key,value in todo_dict.items():
2154 if value['account_collected_id'] or value['account_paid_id']:
2155 obj_acc_tax.write(cr, uid, [key], vals={
2156 'account_collected_id': acc_template_ref[value['account_collected_id']],
2157 'account_paid_id': acc_template_ref[value['account_paid_id']],
2162 view_id = self.pool.get('account.journal.view').search(cr,uid,[('name','=','Journal View')])[0]
2163 seq_id = obj_sequence.search(cr,uid,[('name','=','Account Journal')])[0]
2165 if obj_multi.seq_journal:
2166 seq_id_sale = obj_sequence.search(cr,uid,[('name','=','Sale Journal')])[0]
2167 seq_id_purchase = obj_sequence.search(cr,uid,[('name','=','Purchase Journal')])[0]
2169 seq_id_sale = seq_id
2170 seq_id_purchase = seq_id
2172 vals_journal['view_id'] = view_id
2175 vals_journal['name'] = _('Sales Journal')
2176 vals_journal['type'] = 'sale'
2177 vals_journal['code'] = _('SAJ')
2178 vals_journal['sequence_id'] = seq_id_sale
2180 if obj_multi.chart_template_id.property_account_receivable:
2181 vals_journal['default_credit_account_id'] = acc_template_ref[obj_multi.chart_template_id.property_account_income_categ.id]
2182 vals_journal['default_debit_account_id'] = acc_template_ref[obj_multi.chart_template_id.property_account_income_categ.id]
2184 obj_journal.create(cr,uid,vals_journal)
2187 vals_journal['name'] = _('Purchase Journal')
2188 vals_journal['type'] = 'purchase'
2189 vals_journal['code'] = _('EXJ')
2190 vals_journal['sequence_id'] = seq_id_purchase
2192 if obj_multi.chart_template_id.property_account_payable:
2193 vals_journal['default_credit_account_id'] = acc_template_ref[obj_multi.chart_template_id.property_account_expense_categ.id]
2194 vals_journal['default_debit_account_id'] = acc_template_ref[obj_multi.chart_template_id.property_account_expense_categ.id]
2196 obj_journal.create(cr,uid,vals_journal)
2199 view_id_cash = self.pool.get('account.journal.view').search(cr,uid,[('name','=','Cash Journal View')])[0]
2200 view_id_cur = self.pool.get('account.journal.view').search(cr,uid,[('name','=','Multi-Currency Cash Journal View')])[0]
2201 ref_acc_bank = obj_multi.chart_template_id.bank_account_view_id
2204 for line in obj_multi.bank_accounts_id:
2205 #create the account_account for this bank journal
2206 tmp = self.pool.get('res.partner.bank').name_get(cr, uid, [line.acc_no.id])[0][1]
2207 dig = obj_multi.code_digits
2208 if ref_acc_bank.code:
2210 new_code = str(int(ref_acc_bank.code.ljust(dig,'0')) + current_num)
2212 new_code = str(ref_acc_bank.code.ljust(dig-len(str(current_num)),'0')) + str(current_num)
2214 'name': line.acc_no.bank and line.acc_no.bank.name+' '+tmp or tmp,
2215 'currency_id': line.currency_id and line.currency_id.id or False,
2218 'user_type': account_template.user_type and account_template.user_type.id or False,
2220 'parent_id': acc_template_ref[ref_acc_bank.id] or False,
2221 'company_id': company_id,
2223 acc_cash_id = obj_acc.create(cr,uid,vals)
2225 if obj_multi.seq_journal:
2227 'name': _('Bank Journal ') + vals['name'],
2228 'code': 'account.journal',
2230 seq_id = obj_sequence.create(cr,uid,vals_seq)
2232 #create the bank journal
2233 vals_journal['name']= vals['name']
2234 vals_journal['code']= _('BNK') + str(current_num)
2235 vals_journal['sequence_id'] = seq_id
2236 vals_journal['type'] = 'cash'
2237 if line.currency_id:
2238 vals_journal['view_id'] = view_id_cur
2239 vals_journal['currency'] = line.currency_id.id
2241 vals_journal['view_id'] = view_id_cash
2242 vals_journal['default_credit_account_id'] = acc_cash_id
2243 vals_journal['default_debit_account_id'] = acc_cash_id
2244 obj_journal.create(cr,uid,vals_journal)
2248 #create the properties
2249 property_obj = self.pool.get('ir.property')
2250 fields_obj = self.pool.get('ir.model.fields')
2253 ('property_account_receivable','res.partner','account.account'),
2254 ('property_account_payable','res.partner','account.account'),
2255 ('property_account_expense_categ','product.category','account.account'),
2256 ('property_account_income_categ','product.category','account.account'),
2257 ('property_account_expense','product.template','account.account'),
2258 ('property_account_income','product.template','account.account')
2260 for record in todo_list:
2262 r = property_obj.search(cr, uid, [('name','=', record[0] ),('company_id','=',company_id)])
2263 account = getattr(obj_multi.chart_template_id, record[0])
2264 field = fields_obj.search(cr, uid, [('name','=',record[0]),('model','=',record[1]),('relation','=',record[2])])
2267 'company_id': company_id,
2268 'fields_id': field[0],
2269 'value': account and 'account.account,'+str(acc_template_ref[account.id]) or False,
2272 #the property exist: modify it
2273 property_obj.write(cr, uid, r, vals)
2275 #create the property
2276 property_obj.create(cr, uid, vals)
2278 fp_ids = obj_fiscal_position_template.search(cr, uid,[('chart_template_id', '=', obj_multi.chart_template_id.id)])
2281 for position in obj_fiscal_position_template.browse(cr, uid, fp_ids):
2284 'company_id' : company_id,
2285 'name' : position.name,
2287 new_fp = obj_fiscal_position.create(cr, uid, vals_fp)
2289 obj_tax_fp = self.pool.get('account.fiscal.position.tax')
2290 obj_ac_fp = self.pool.get('account.fiscal.position.account')
2292 for tax in position.tax_ids:
2294 'tax_src_id' : tax_template_ref[tax.tax_src_id.id],
2295 'tax_dest_id' : tax.tax_dest_id and tax_template_ref[tax.tax_dest_id.id] or False,
2296 'position_id' : new_fp,
2298 obj_tax_fp.create(cr, uid, vals_tax)
2300 for acc in position.account_ids:
2302 'account_src_id' : acc_template_ref[acc.account_src_id.id],
2303 'account_dest_id' : acc_template_ref[acc.account_dest_id.id],
2304 'position_id' : new_fp,
2306 obj_ac_fp.create(cr, uid, vals_acc)
2309 'view_type': 'form',
2310 "view_mode": 'form',
2311 'res_model': 'ir.actions.configuration.wizard',
2312 'type': 'ir.actions.act_window',
2315 def action_cancel(self,cr,uid,ids,conect=None):
2317 'view_type': 'form',
2318 "view_mode": 'form',
2319 'res_model': 'ir.actions.configuration.wizard',
2320 'type': 'ir.actions.act_window',
2325 wizard_multi_charts_accounts()
2327 class account_bank_accounts_wizard(osv.osv_memory):
2328 _name='account.bank.accounts.wizard'
2331 'acc_no':fields.many2one('res.partner.bank','Account No.',required=True),
2332 'bank_account_id':fields.many2one('wizard.multi.charts.accounts', 'Bank Account', required=True),
2333 'currency_id':fields.many2one('res.currency', 'Currency'),
2336 account_bank_accounts_wizard()
2338 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: