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['parent_id'] = False
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='string'),
656 'active': fields.boolean('Active', required=True),
657 'state': fields.selection([('draft','Draft'), ('printed','Printed'), ('done','Done')], 'Status', required=True, readonly=True)
660 def _check(self, cr, uid, ids, context={}):
661 for obj in self.browse(cr, uid, ids, context):
662 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))
665 raise osv.except_osv(_('Error !'), _('You can not modify/delete a journal with entries for this period !'))
668 def write(self, cr, uid, ids, vals, context={}):
669 self._check(cr, uid, ids, context)
670 return super(account_journal_period, self).write(cr, uid, ids, vals, context)
672 def create(self, cr, uid, vals, context={}):
673 period_id=vals.get('period_id',False)
675 period = self.pool.get('account.period').browse(cr, uid,period_id)
676 vals['state']=period.state
677 return super(account_journal_period, self).create(cr, uid, vals, context)
679 def unlink(self, cr, uid, ids, context={}):
680 self._check(cr, uid, ids, context)
681 return super(account_journal_period, self).unlink(cr, uid, ids, context)
684 'state': lambda *a: 'draft',
685 'active': lambda *a: True,
689 account_journal_period()
691 class account_fiscalyear(osv.osv):
692 _inherit = "account.fiscalyear"
693 _description = "Fiscal Year"
695 'end_journal_period_id':fields.many2one('account.journal.period','End of Year Entries Journal', readonly=True),
699 #----------------------------------------------------------
701 #----------------------------------------------------------
702 class account_move(osv.osv):
703 _name = "account.move"
704 _description = "Account Entry"
707 def name_get(self, cursor, user, ids, context=None):
711 data_move = self.pool.get('account.move').browse(cursor,user,ids)
712 for move in data_move:
713 if move.state=='draft':
714 name = '*' + str(move.id)
717 res.append((move.id, name))
721 def _get_period(self, cr, uid, context):
722 periods = self.pool.get('account.period').find(cr, uid)
728 def _amount_compute(self, cr, uid, ids, name, args, context, where =''):
729 if not ids: return {}
730 cr.execute('select move_id,sum(debit) from account_move_line where move_id in ('+','.join(map(str,ids))+') group by move_id')
731 result = dict(cr.fetchall())
733 result.setdefault(id, 0.0)
737 'name': fields.char('Number', size=64, required=True),
738 'ref': fields.char('Ref', size=64),
739 'period_id': fields.many2one('account.period', 'Period', required=True, states={'posted':[('readonly',True)]}),
740 'journal_id': fields.many2one('account.journal', 'Journal', required=True, states={'posted':[('readonly',True)]}),
741 'state': fields.selection([('draft','Draft'), ('posted','Posted')], 'Status', required=True, readonly=True),
742 'line_id': fields.one2many('account.move.line', 'move_id', 'Entries', states={'posted':[('readonly',True)]}),
743 'to_check': fields.boolean('To Be Verified'),
744 'partner_id': fields.related('line_id', 'partner_id', type="many2one", relation="res.partner", string="Partner"),
745 'amount': fields.function(_amount_compute, method=True, string='Amount', digits=(16,2)),
746 'date': fields.date('Date', required=True),
747 'type': fields.selection([
748 ('pay_voucher','Cash Payment'),
749 ('bank_pay_voucher','Bank Payment'),
750 ('rec_voucher','Cash Receipt'),
751 ('bank_rec_voucher','Bank Receipt'),
752 ('cont_voucher','Contra'),
753 ('journal_sale_vou','Journal Sale'),
754 ('journal_pur_voucher','Journal Purchase'),
755 ('journal_voucher','Journal Voucher'),
756 ],'Type', readonly=True, select=True, states={'draft':[('readonly',False)]}),
759 'name': lambda *a: '/',
760 'state': lambda *a: 'draft',
761 'period_id': _get_period,
762 'type' : lambda *a : 'journal_voucher',
763 'date': lambda *a:time.strftime('%Y-%m-%d'),
766 def _check_centralisation(self, cursor, user, ids):
767 for move in self.browse(cursor, user, ids):
768 if move.journal_id.centralisation:
769 move_ids = self.search(cursor, user, [
770 ('period_id', '=', move.period_id.id),
771 ('journal_id', '=', move.journal_id.id),
773 if len(move_ids) > 1:
777 def _check_period_journal(self, cursor, user, ids):
778 for move in self.browse(cursor, user, ids):
779 for line in move.line_id:
780 if line.period_id.id != move.period_id.id:
782 if line.journal_id.id != move.journal_id.id:
787 (_check_centralisation,
788 'You cannot create more than one move per period on centralized journal',
790 (_check_period_journal,
791 'You cannot create entries on different periods/journals in the same move',
794 def post(self, cr, uid, ids, context=None):
795 if self.validate(cr, uid, ids, context) and len(ids):
796 for move in self.browse(cr, uid, ids):
799 journal = move.journal_id
800 if journal.sequence_id:
801 c = {'fiscalyear_id': move.period_id.fiscalyear_id.id}
802 new_name = self.pool.get('ir.sequence').get_id(cr, uid, journal.sequence_id.id, context=c)
804 raise osv.except_osv(_('Error'), _('No sequence defined in the journal !'))
806 self.write(cr, uid, [move.id], {'name':new_name})
808 cr.execute('update account_move set state=%s where id in ('+','.join(map(str,ids))+')', ('posted',))
810 raise osv.except_osv(_('Integrity Error !'), _('You can not validate a non-balanced entry !'))
813 def button_validate(self, cursor, user, ids, context=None):
814 return self.post(cursor, user, ids, context=context)
816 def button_cancel(self, cr, uid, ids, context={}):
817 for line in self.browse(cr, uid, ids, context):
818 if not line.journal_id.update_posted:
819 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.'))
821 cr.execute('update account_move set state=%s where id in ('+','.join(map(str,ids))+')', ('draft',))
824 def write(self, cr, uid, ids, vals, context={}):
826 c['novalidate'] = True
827 result = super(osv.osv, self).write(cr, uid, ids, vals, c)
828 self.validate(cr, uid, ids, context)
832 # TODO: Check if period is closed !
834 def create(self, cr, uid, vals, context={}):
835 if 'line_id' in vals:
836 if 'journal_id' in vals:
837 for l in vals['line_id']:
839 l[2]['journal_id'] = vals['journal_id']
840 context['journal_id'] = vals['journal_id']
841 if 'period_id' in vals:
842 for l in vals['line_id']:
844 l[2]['period_id'] = vals['period_id']
845 context['period_id'] = vals['period_id']
847 default_period = self._get_period(cr, uid, context)
848 for l in vals['line_id']:
850 l[2]['period_id'] = default_period
851 context['period_id'] = default_period
853 accnt_journal = self.pool.get('account.journal').browse(cr, uid, vals['journal_id'])
854 if 'line_id' in vals:
856 c['novalidate'] = True
857 result = super(account_move, self).create(cr, uid, vals, c)
858 self.validate(cr, uid, [result], context)
860 result = super(account_move, self).create(cr, uid, vals, context)
863 def copy(self, cr, uid, id, default=None, context=None):
866 default = default.copy()
867 default.update({'state':'draft', 'name':'/',})
868 return super(account_move, self).copy(cr, uid, id, default, context)
870 def unlink(self, cr, uid, ids, context={}, check=True):
872 for move in self.browse(cr, uid, ids, context):
873 if move['state'] != 'draft':
874 raise osv.except_osv(_('UserError'),
875 _('You can not delete posted movement: "%s"!') % \
877 line_ids = map(lambda x: x.id, move.line_id)
878 context['journal_id'] = move.journal_id.id
879 context['period_id'] = move.period_id.id
880 self.pool.get('account.move.line')._update_check(cr, uid, line_ids, context)
881 self.pool.get('account.move.line').unlink(cr, uid, line_ids, context=context)
882 toremove.append(move.id)
883 result = super(account_move, self).unlink(cr, uid, toremove, context)
886 def _compute_balance(self, cr, uid, id, context={}):
887 move = self.browse(cr, uid, [id])[0]
889 for line in move.line_id:
890 amount+= (line.debit - line.credit)
893 def _centralise(self, cr, uid, move, mode):
895 account_id = move.journal_id.default_debit_account_id.id
898 raise osv.except_osv(_('UserError'),
899 _('There is no default default debit account defined \n' \
900 'on journal "%s"') % move.journal_id.name)
902 account_id = move.journal_id.default_credit_account_id.id
905 raise osv.except_osv(_('UserError'),
906 _('There is no default default credit account defined \n' \
907 'on journal "%s"') % move.journal_id.name)
909 # find the first line of this move with the current mode
910 # or create it if it doesn't exist
911 cr.execute('select id from account_move_line where move_id=%s and centralisation=%s limit 1', (move.id, mode))
916 line_id = self.pool.get('account.move.line').create(cr, uid, {
917 'name': 'Centralisation '+mode,
918 'centralisation': mode,
919 'account_id': account_id,
921 'journal_id': move.journal_id.id,
922 'period_id': move.period_id.id,
923 'date': move.period_id.date_stop,
926 }, {'journal_id': move.journal_id.id, 'period_id': move.period_id.id})
928 # find the first line of this move with the other mode
929 # so that we can exclude it from our calculation
930 cr.execute('select id from account_move_line where move_id=%s and centralisation=%s limit 1', (move.id, mode2))
937 cr.execute('select sum('+mode+') from account_move_line where move_id=%s and id<>%s', (move.id, line_id2))
938 result = cr.fetchone()[0] or 0.0
939 cr.execute('update account_move_line set '+mode2+'=%s where id=%s', (result, line_id))
943 # Validate a balanced move. If it is a centralised journal, create a move.
945 def validate(self, cr, uid, ids, context={}):
946 if context and ('__last_update' in context):
947 del context['__last_update']
949 for move in self.browse(cr, uid, ids, context):
950 #unlink analytic lines on move_lines
951 for obj_line in move.line_id:
952 for obj in obj_line.analytic_lines:
953 self.pool.get('account.analytic.line').unlink(cr,uid,obj.id)
955 journal = move.journal_id
960 for line in move.line_id:
961 amount += line.debit - line.credit
962 line_ids.append(line.id)
963 if line.state=='draft':
964 line_draft_ids.append(line.id)
967 company_id = line.account_id.company_id.id
968 if not company_id == line.account_id.company_id.id:
969 raise osv.except_osv(_('Error'), _("Couldn't create move between different companies"))
971 if line.account_id.currency_id:
972 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):
973 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)))
975 if abs(amount) < 0.0001:
976 if not len(line_draft_ids):
978 self.pool.get('account.move.line').write(cr, uid, line_draft_ids, {
979 'journal_id': move.journal_id.id,
980 'period_id': move.period_id.id,
982 }, context, check=False)
986 if journal.type not in ('purchase','sale'):
989 for line in move.line_id:
991 key = (line.account_id.id, line.tax_code_id.id)
993 code = account2[key][0]
994 amount = account2[key][1] * (line.debit + line.credit)
995 elif line.account_id.id in account:
996 code = account[line.account_id.id][0]
997 amount = account[line.account_id.id][1] * (line.debit + line.credit)
998 if (code or amount) and not (line.tax_code_id or line.tax_amount):
999 self.pool.get('account.move.line').write(cr, uid, [line.id], {
1000 'tax_code_id': code,
1001 'tax_amount': amount
1002 }, context, check=False)
1007 if journal.centralisation:
1008 self._centralise(cr, uid, move, 'debit')
1009 self._centralise(cr, uid, move, 'credit')
1010 self.pool.get('account.move.line').write(cr, uid, line_draft_ids, {
1012 }, context, check=False)
1015 self.pool.get('account.move.line').write(cr, uid, line_ids, {
1016 'journal_id': move.journal_id.id,
1017 'period_id': move.period_id.id,
1018 #'tax_code_id': False,
1019 #'tax_amount': False,
1021 }, context, check=False)
1025 for tmp in move.line_id:
1026 list_ids.append(tmp.id)
1027 self.pool.get('account.move.line').create_analytic_lines(cr, uid, list_ids, context)
1031 class account_move_reconcile(osv.osv):
1032 _name = "account.move.reconcile"
1033 _description = "Account Reconciliation"
1035 'name': fields.char('Name', size=64, required=True),
1036 'type': fields.char('Type', size=16, required=True),
1037 'line_id': fields.one2many('account.move.line', 'reconcile_id', 'Entry Lines'),
1038 'line_partial_ids': fields.one2many('account.move.line', 'reconcile_partial_id', 'Partial Entry lines'),
1039 'create_date': fields.date('Creation date', readonly=True),
1042 'name': lambda self,cr,uid,ctx={}: self.pool.get('ir.sequence').get(cr, uid, 'account.reconcile') or '/',
1044 def reconcile_partial_check(self, cr, uid, ids, type='auto', context={}):
1045 for rec in self.browse(cr, uid, ids, context):
1047 for line in rec.line_partial_ids:
1048 total += (line.debit or 0.0) - (line.credit or 0.0)
1050 self.pool.get('account.move.line').write(cr, uid,
1051 map(lambda x: x.id, rec.line_partial_ids),
1052 {'reconcile_id': rec.id }
1056 def name_get(self, cr, uid, ids, context=None):
1060 for r in self.browse(cr, uid, ids, context):
1061 total = reduce(lambda y,t: (t.debit or 0.0) - (t.credit or 0.0) + y, r.line_partial_ids, 0.0)
1063 name = '%s (%.2f)' % (r.name, total)
1064 result.append((r.id,name))
1066 result.append((r.id,r.name))
1070 account_move_reconcile()
1072 #----------------------------------------------------------
1074 #----------------------------------------------------------
1077 child_depend: la taxe depend des taxes filles
1079 class account_tax_code(osv.osv):
1081 A code for the tax object.
1083 This code is used for some tax declarations.
1085 def _sum(self, cr, uid, ids, name, args, context, where =''):
1086 ids2 = self.search(cr, uid, [('parent_id', 'child_of', ids)])
1087 acc_set = ",".join(map(str, ids2))
1088 if context.get('based_on', 'invoices') == 'payments':
1089 cr.execute('SELECT line.tax_code_id, sum(line.tax_amount) \
1090 FROM account_move_line AS line, \
1091 account_move AS move \
1092 LEFT JOIN account_invoice invoice ON \
1093 (invoice.move_id = move.id) \
1094 WHERE line.tax_code_id in ('+acc_set+') '+where+' \
1095 AND move.id = line.move_id \
1096 AND ((invoice.state = \'paid\') \
1097 OR (invoice.id IS NULL)) \
1098 GROUP BY line.tax_code_id')
1100 cr.execute('SELECT line.tax_code_id, sum(line.tax_amount) \
1101 FROM account_move_line AS line \
1102 WHERE line.tax_code_id in ('+acc_set+') '+where+' \
1103 GROUP BY line.tax_code_id')
1104 res=dict(cr.fetchall())
1105 for record in self.browse(cr, uid, ids, context):
1106 def _rec_get(record):
1107 amount = res.get(record.id, 0.0)
1108 for rec in record.child_ids:
1109 amount += _rec_get(rec) * rec.sign
1111 res[record.id] = round(_rec_get(record), 2)
1114 def _sum_year(self, cr, uid, ids, name, args, context):
1115 if 'fiscalyear_id' in context and context['fiscalyear_id']:
1116 fiscalyear_id = context['fiscalyear_id']
1118 fiscalyear_id = self.pool.get('account.fiscalyear').find(cr, uid, exception=False)
1121 pids = map(lambda x: str(x.id), self.pool.get('account.fiscalyear').browse(cr, uid, fiscalyear_id).period_ids)
1123 where = ' and period_id in (' + (','.join(pids))+')'
1124 return self._sum(cr, uid, ids, name, args, context,
1127 def _sum_period(self, cr, uid, ids, name, args, context):
1128 if 'period_id' in context and context['period_id']:
1129 period_id = context['period_id']
1131 period_id = self.pool.get('account.period').find(cr, uid)
1132 if not len(period_id):
1133 return dict.fromkeys(ids, 0.0)
1134 period_id = period_id[0]
1135 return self._sum(cr, uid, ids, name, args, context,
1136 where=' and line.period_id='+str(period_id))
1138 _name = 'account.tax.code'
1139 _description = 'Tax Code'
1142 'name': fields.char('Tax Case Name', size=64, required=True),
1143 'code': fields.char('Case Code', size=64),
1144 'info': fields.text('Description'),
1145 'sum': fields.function(_sum_year, method=True, string="Year Sum"),
1146 'sum_period': fields.function(_sum_period, method=True, string="Period Sum"),
1147 'parent_id': fields.many2one('account.tax.code', 'Parent Code', select=True),
1148 'child_ids': fields.one2many('account.tax.code', 'parent_id', 'Child Codes'),
1149 'line_ids': fields.one2many('account.move.line', 'tax_code_id', 'Lines'),
1150 'company_id': fields.many2one('res.company', 'Company', required=True),
1151 'sign': fields.float('Sign for parent', required=True),
1152 '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"),
1156 def name_get(self, cr, uid, ids, context=None):
1159 if isinstance(ids, (int, long)):
1161 reads = self.read(cr, uid, ids, ['name','code'], context, load='_classic_write')
1162 return [(x['id'], (x['code'] and x['code'] + ' - ' or '') + x['name']) \
1165 def _default_company(self, cr, uid, context={}):
1166 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
1168 return user.company_id.id
1169 return self.pool.get('res.company').search(cr, uid, [('parent_id', '=', False)])[0]
1171 'company_id': _default_company,
1172 'sign': lambda *args: 1.0,
1173 'notprintable': lambda *a: False,
1175 def _check_recursion(self, cr, uid, ids):
1178 cr.execute('select distinct parent_id from account_tax_code where id in ('+','.join(map(str,ids))+')')
1179 ids = filter(None, map(lambda x:x[0], cr.fetchall()))
1186 (_check_recursion, 'Error ! You can not create recursive accounts.', ['parent_id'])
1188 _order = 'code,name'
1191 class account_tax(osv.osv):
1195 Type: percent, fixed, none, code
1196 PERCENT: tax = price * amount
1197 FIXED: tax = price + amount
1199 CODE: execute python code. localcontext = {'price_unit':pu, 'address':address_object}
1200 return result in the context
1201 Ex: result=round(price_unit*0.21,4)
1203 _name = 'account.tax'
1204 _description = 'Tax'
1206 'name': fields.char('Tax Name', size=64, required=True, translate=True, help="This name will be displayed on reports"),
1207 '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."),
1208 'amount': fields.float('Amount', required=True, digits=(14,4)),
1209 'active': fields.boolean('Active'),
1210 'type': fields.selection( [('percent','Percent'), ('fixed','Fixed'), ('none','None'), ('code','Python Code'),('balance','Balance')], 'Tax Type', required=True,
1211 help="The computation method for the tax amount."),
1212 'applicable_type': fields.selection( [('true','True'), ('code','Python Code')], 'Applicable Type', required=True,
1213 help="If not applicable (computed through a Python code), the tax won't appear on the invoice."),
1214 '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."),
1215 'account_collected_id':fields.many2one('account.account', 'Invoice Tax Account'),
1216 'account_paid_id':fields.many2one('account.account', 'Refund Tax Account'),
1217 'parent_id':fields.many2one('account.tax', 'Parent Tax Account', select=True),
1218 'child_ids':fields.one2many('account.tax', 'parent_id', 'Child Tax Accounts'),
1219 '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."),
1220 'python_compute':fields.text('Python Code'),
1221 'python_compute_inv':fields.text('Python Code (reverse)'),
1222 'python_applicable':fields.text('Python Code'),
1223 '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."),
1226 # Fields used for the VAT declaration
1228 'base_code_id': fields.many2one('account.tax.code', 'Base Code', help="Use this code for the VAT declaration."),
1229 'tax_code_id': fields.many2one('account.tax.code', 'Tax Code', help="Use this code for the VAT declaration."),
1230 'base_sign': fields.float('Base Code Sign', help="Usually 1 or -1."),
1231 'tax_sign': fields.float('Tax Code Sign', help="Usually 1 or -1."),
1233 # Same fields for refund invoices
1235 'ref_base_code_id': fields.many2one('account.tax.code', 'Refund Base Code', help="Use this code for the VAT declaration."),
1236 'ref_tax_code_id': fields.many2one('account.tax.code', 'Refund Tax Code', help="Use this code for the VAT declaration."),
1237 'ref_base_sign': fields.float('Base Code Sign', help="Usually 1 or -1."),
1238 'ref_tax_sign': fields.float('Tax Code Sign', help="Usually 1 or -1."),
1239 '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"),
1240 'company_id': fields.many2one('res.company', 'Company', required=True),
1241 'description': fields.char('Tax Code',size=32),
1242 'price_include': fields.boolean('Tax Included in Price', help="Check this if the price you use on the product and invoices includes this tax."),
1243 'type_tax_use': fields.selection([('sale','Sale'),('purchase','Purchase'),('all','All')], 'Tax Application', required=True)
1246 def search(self, cr, uid, args, offset=0, limit=None, order=None,
1247 context=None, count=False):
1248 if context and context.has_key('type'):
1249 if context['type'] in ('out_invoice','out_refund'):
1250 args.append(('type_tax_use','in',['sale','all']))
1251 elif context['type'] in ('in_invoice','in_refund'):
1252 args.append(('type_tax_use','in',['purchase','all']))
1253 return super(account_tax, self).search(cr, uid, args, offset, limit, order, context, count)
1255 def name_get(self, cr, uid, ids, context={}):
1259 for record in self.read(cr, uid, ids, ['description','name'], context):
1260 name = record['description'] and record['description'] or record['name']
1261 res.append((record['id'],name ))
1264 def _default_company(self, cr, uid, context={}):
1265 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
1267 return user.company_id.id
1268 return self.pool.get('res.company').search(cr, uid, [('parent_id', '=', False)])[0]
1270 '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''',
1271 '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''',
1272 'applicable_type': lambda *a: 'true',
1273 'type': lambda *a: 'percent',
1274 'amount': lambda *a: 0,
1275 'price_include': lambda *a: 0,
1276 'active': lambda *a: 1,
1277 'type_tax_use': lambda *a: 'all',
1278 'sequence': lambda *a: 1,
1279 'tax_group': lambda *a: 'vat',
1280 'ref_tax_sign': lambda *a: 1,
1281 'ref_base_sign': lambda *a: 1,
1282 'tax_sign': lambda *a: 1,
1283 'base_sign': lambda *a: 1,
1284 'include_base_amount': lambda *a: False,
1285 'company_id': _default_company,
1289 def _applicable(self, cr, uid, taxes, price_unit, address_id=None, product=None, partner=None):
1292 if tax.applicable_type=='code':
1293 localdict = {'price_unit':price_unit, 'address':self.pool.get('res.partner.address').browse(cr, uid, address_id), 'product':product, 'partner':partner}
1294 exec tax.python_applicable in localdict
1295 if localdict.get('result', False):
1301 def _unit_compute(self, cr, uid, taxes, price_unit, address_id=None, product=None, partner=None, quantity=0):
1302 taxes = self._applicable(cr, uid, taxes, price_unit, address_id, product, partner)
1305 cur_price_unit=price_unit
1307 # we compute the amount for the current tax object and append it to the result
1309 data = {'id':tax.id,
1311 'account_collected_id':tax.account_collected_id.id,
1312 'account_paid_id':tax.account_paid_id.id,
1313 'base_code_id': tax.base_code_id.id,
1314 'ref_base_code_id': tax.ref_base_code_id.id,
1315 'sequence': tax.sequence,
1316 'base_sign': tax.base_sign,
1317 'tax_sign': tax.tax_sign,
1318 'ref_base_sign': tax.ref_base_sign,
1319 'ref_tax_sign': tax.ref_tax_sign,
1320 'price_unit': cur_price_unit,
1321 'tax_code_id': tax.tax_code_id.id,
1322 'ref_tax_code_id': tax.ref_tax_code_id.id,
1325 if tax.type=='percent':
1326 amount = cur_price_unit * tax.amount
1327 data['amount'] = amount
1329 elif tax.type=='fixed':
1330 print "her", quantity
1332 data['amount'] = tax.amount
1333 data['tax_amount']=quantity
1334 print "DATA 2", data
1335 # data['amount'] = quantity
1336 elif tax.type=='code':
1337 address = address_id and self.pool.get('res.partner.address').browse(cr, uid, address_id) or None
1338 localdict = {'price_unit':cur_price_unit, 'address':address, 'product':product, 'partner':partner}
1339 exec tax.python_compute in localdict
1340 amount = localdict['result']
1341 data['amount'] = amount
1342 elif tax.type=='balance':
1343 data['amount'] = cur_price_unit - reduce(lambda x,y: y.get('amount',0.0)+x, res, 0.0)
1344 data['balance'] = cur_price_unit
1346 amount2 = data['amount']
1347 if len(tax.child_ids):
1348 if tax.child_depend:
1351 child_tax = self._unit_compute(cr, uid, tax.child_ids, amount, address_id, product, partner, quantity)
1352 res.extend(child_tax)
1353 if tax.child_depend:
1355 for name in ('base','ref_base'):
1356 if latest[name+'_code_id'] and latest[name+'_sign'] and not r[name+'_code_id']:
1357 r[name+'_code_id'] = latest[name+'_code_id']
1358 r[name+'_sign'] = latest[name+'_sign']
1359 r['price_unit'] = latest['price_unit']
1360 latest[name+'_code_id'] = False
1361 for name in ('tax','ref_tax'):
1362 if latest[name+'_code_id'] and latest[name+'_sign'] and not r[name+'_code_id']:
1363 r[name+'_code_id'] = latest[name+'_code_id']
1364 r[name+'_sign'] = latest[name+'_sign']
1365 r['amount'] = data['amount']
1366 latest[name+'_code_id'] = False
1367 if tax.include_base_amount:
1368 cur_price_unit+=amount2
1369 print "rress final", res
1372 def compute(self, cr, uid, taxes, price_unit, quantity, address_id=None, product=None, partner=None):
1375 Compute tax values for given PRICE_UNIT, QUANTITY and a buyer/seller ADDRESS_ID.
1379 tax = {'name':'', 'amount':0.0, 'account_collected_id':1, 'account_paid_id':2}
1380 one tax for each tax id in IDS and their childs
1382 res = self._unit_compute(cr, uid, taxes, price_unit, address_id, product, partner, quantity)
1386 if r.get('balance',False):
1387 r['amount'] = round(r['balance'] * quantity, 2) - total
1389 r['amount'] = round(r['amount'] * quantity, 2)
1390 total += r['amount']
1394 def _unit_compute_inv(self, cr, uid, taxes, price_unit, address_id=None, product=None, partner=None):
1395 taxes = self._applicable(cr, uid, taxes, price_unit, address_id, product, partner)
1399 cur_price_unit=price_unit
1401 tax_parent_tot = 0.0
1403 if (tax.type=='percent') and not tax.include_base_amount:
1404 tax_parent_tot+=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 optionnal 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,),
1777 'user_type': fields.many2one('account.account.type', 'Account Type', required=True),
1778 'reconcile': fields.boolean('Allow Reconciliation', help="Check this option if you want the user to reconcile entries in this account."),
1779 'shortcut': fields.char('Shortcut', size=12),
1780 'note': fields.text('Note'),
1781 'parent_id': fields.many2one('account.account.template','Parent Account Template', ondelete='cascade'),
1782 'child_parent_ids':fields.one2many('account.account.template','parent_id','Children'),
1783 'tax_ids': fields.many2many('account.tax.template', 'account_account_template_tax_rel','account_id','tax_id', 'Default Taxes'),
1787 'reconcile': lambda *a: False,
1788 'type' : lambda *a :'view',
1791 def _check_recursion(self, cr, uid, ids):
1794 cr.execute('select parent_id from account_account_template where id in ('+','.join(map(str,ids))+')')
1795 ids = filter(None, map(lambda x:x[0], cr.fetchall()))
1802 (_check_recursion, 'Error ! You can not create recursive account templates.', ['parent_id'])
1806 def name_get(self, cr, uid, ids, context={}):
1809 reads = self.read(cr, uid, ids, ['name','code'], context)
1811 for record in reads:
1812 name = record['name']
1814 name = record['code']+' '+name
1815 res.append((record['id'],name ))
1818 account_account_template()
1820 class account_tax_code_template(osv.osv):
1822 _name = 'account.tax.code.template'
1823 _description = 'Tax Code Template'
1827 'name': fields.char('Tax Case Name', size=64, required=True),
1828 'code': fields.char('Case Code', size=64),
1829 'info': fields.text('Description'),
1830 'parent_id': fields.many2one('account.tax.code.template', 'Parent Code', select=True),
1831 'child_ids': fields.one2many('account.tax.code.template', 'parent_id', 'Child Codes'),
1832 'sign': fields.float('Sign for parent', required=True),
1833 '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"),
1837 'sign': lambda *args: 1.0,
1838 'notprintable': lambda *a: False,
1841 def name_get(self, cr, uid, ids, context=None):
1844 if isinstance(ids, (int, long)):
1846 reads = self.read(cr, uid, ids, ['name','code'], context, load='_classic_write')
1847 return [(x['id'], (x['code'] and x['code'] + ' - ' or '') + x['name']) \
1850 def _check_recursion(self, cr, uid, ids):
1853 cr.execute('select distinct parent_id from account_tax_code_template where id in ('+','.join(map(str,ids))+')')
1854 ids = filter(None, map(lambda x:x[0], cr.fetchall()))
1861 (_check_recursion, 'Error ! You can not create recursive Tax Codes.', ['parent_id'])
1863 _order = 'code,name'
1864 account_tax_code_template()
1867 class account_chart_template(osv.osv):
1868 _name="account.chart.template"
1869 _description= "Templates for Account Chart"
1872 'name': fields.char('Name', size=64, required=True),
1873 'account_root_id': fields.many2one('account.account.template','Root Account',required=True,domain=[('parent_id','=',False)]),
1874 'tax_code_root_id': fields.many2one('account.tax.code.template','Root Tax Code',required=True,domain=[('parent_id','=',False)]),
1875 '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'),
1876 'bank_account_view_id': fields.many2one('account.account.template','Bank Account',required=True),
1877 'property_account_receivable': fields.many2one('account.account.template','Receivable Account'),
1878 'property_account_payable': fields.many2one('account.account.template','Payable Account'),
1879 'property_account_expense_categ': fields.many2one('account.account.template','Expense Category Account'),
1880 'property_account_income_categ': fields.many2one('account.account.template','Income Category Account'),
1881 'property_account_expense': fields.many2one('account.account.template','Expense Account on Product Template'),
1882 'property_account_income': fields.many2one('account.account.template','Income Account on Product Template'),
1885 account_chart_template()
1887 class account_tax_template(osv.osv):
1889 _name = 'account.tax.template'
1890 _description = 'Templates for Taxes'
1893 'chart_template_id': fields.many2one('account.chart.template', 'Chart Template', required=True),
1894 'name': fields.char('Tax Name', size=64, required=True),
1895 '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."),
1896 'amount': fields.float('Amount', required=True, digits=(14,4)),
1897 'type': fields.selection( [('percent','Percent'), ('fixed','Fixed'), ('none','None'), ('code','Python Code')], 'Tax Type', required=True),
1898 'applicable_type': fields.selection( [('true','True'), ('code','Python Code')], 'Applicable Type', required=True),
1899 '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."),
1900 'account_collected_id':fields.many2one('account.account.template', 'Invoice Tax Account'),
1901 'account_paid_id':fields.many2one('account.account.template', 'Refund Tax Account'),
1902 'parent_id':fields.many2one('account.tax.template', 'Parent Tax Account', select=True),
1903 '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."),
1904 'python_compute':fields.text('Python Code'),
1905 'python_compute_inv':fields.text('Python Code (reverse)'),
1906 'python_applicable':fields.text('Python Code'),
1907 '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."),
1910 # Fields used for the VAT declaration
1912 'base_code_id': fields.many2one('account.tax.code.template', 'Base Code', help="Use this code for the VAT declaration."),
1913 'tax_code_id': fields.many2one('account.tax.code.template', 'Tax Code', help="Use this code for the VAT declaration."),
1914 'base_sign': fields.float('Base Code Sign', help="Usually 1 or -1."),
1915 'tax_sign': fields.float('Tax Code Sign', help="Usually 1 or -1."),
1917 # Same fields for refund invoices
1919 'ref_base_code_id': fields.many2one('account.tax.code.template', 'Refund Base Code', help="Use this code for the VAT declaration."),
1920 'ref_tax_code_id': fields.many2one('account.tax.code.template', 'Refund Tax Code', help="Use this code for the VAT declaration."),
1921 'ref_base_sign': fields.float('Base Code Sign', help="Usually 1 or -1."),
1922 'ref_tax_sign': fields.float('Tax Code Sign', help="Usually 1 or -1."),
1923 '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."),
1924 'description': fields.char('Internal Name', size=32),
1925 'type_tax_use': fields.selection([('sale','Sale'),('purchase','Purchase'),('all','All')], 'Tax Use In', required=True,)
1928 def name_get(self, cr, uid, ids, context={}):
1932 for record in self.read(cr, uid, ids, ['description','name'], context):
1933 name = record['description'] and record['description'] or record['name']
1934 res.append((record['id'],name ))
1937 def _default_company(self, cr, uid, context={}):
1938 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
1940 return user.company_id.id
1941 return self.pool.get('res.company').search(cr, uid, [('parent_id', '=', False)])[0]
1944 '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''',
1945 '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''',
1946 'applicable_type': lambda *a: 'true',
1947 'type': lambda *a: 'percent',
1948 'amount': lambda *a: 0,
1949 'sequence': lambda *a: 1,
1950 'tax_group': lambda *a: 'vat',
1951 'ref_tax_sign': lambda *a: 1,
1952 'ref_base_sign': lambda *a: 1,
1953 'tax_sign': lambda *a: 1,
1954 'base_sign': lambda *a: 1,
1955 'include_base_amount': lambda *a: False,
1956 'type_tax_use': lambda *a: 'all',
1961 account_tax_template()
1963 # Fiscal Position Templates
1965 class account_fiscal_position_template(osv.osv):
1966 _name = 'account.fiscal.position.template'
1967 _description = 'Template for Fiscal Position'
1970 'name': fields.char('Fiscal Position Template', size=64, translate=True, required=True),
1971 'chart_template_id': fields.many2one('account.chart.template', 'Chart Template', required=True),
1972 'account_ids': fields.one2many('account.fiscal.position.account.template', 'position_id', 'Account Mapping'),
1973 'tax_ids': fields.one2many('account.fiscal.position.tax.template', 'position_id', 'Tax Mapping')
1976 account_fiscal_position_template()
1978 class account_fiscal_position_tax_template(osv.osv):
1979 _name = 'account.fiscal.position.tax.template'
1980 _description = 'Fiscal Position Template Tax Mapping'
1981 _rec_name = 'position_id'
1984 'position_id': fields.many2one('account.fiscal.position.template', 'Fiscal Position', required=True, ondelete='cascade'),
1985 'tax_src_id': fields.many2one('account.tax.template', 'Tax Source', required=True),
1986 'tax_dest_id': fields.many2one('account.tax.template', 'Replacement Tax')
1989 account_fiscal_position_tax_template()
1991 class account_fiscal_position_account_template(osv.osv):
1992 _name = 'account.fiscal.position.account.template'
1993 _description = 'Fiscal Position Template Account Mapping'
1994 _rec_name = 'position_id'
1996 'position_id': fields.many2one('account.fiscal.position.template', 'Fiscal Position', required=True, ondelete='cascade'),
1997 'account_src_id': fields.many2one('account.account.template', 'Account Source', domain=[('type','<>','view')], required=True),
1998 'account_dest_id': fields.many2one('account.account.template', 'Account Destination', domain=[('type','<>','view')], required=True)
2001 account_fiscal_position_account_template()
2003 # Multi charts of Accounts wizard
2005 class wizard_multi_charts_accounts(osv.osv_memory):
2007 Create a new account chart for a company.
2010 * an account chart template
2011 * a number of digits for formatting code of non-view accounts
2012 * a list of bank accounts owned by the company
2014 * generates all accounts from the template and assigns them to the right company
2015 * generates all taxes and tax codes, changing account assignations
2016 * generates all accounting properties and assigns them correctly
2018 _name='wizard.multi.charts.accounts'
2021 'company_id':fields.many2one('res.company','Company',required=True),
2022 'chart_template_id': fields.many2one('account.chart.template','Chart Template',required=True),
2023 'bank_accounts_id': fields.one2many('account.bank.accounts.wizard', 'bank_account_id', 'Bank Accounts',required=True),
2024 'code_digits':fields.integer('# of Digits',required=True,help="No. of Digits to use for account code"),
2025 '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."),
2028 def _get_chart(self, cr, uid, context={}):
2029 ids = self.pool.get('account.chart.template').search(cr, uid, [], context=context)
2034 'company_id': lambda self, cr, uid, c: self.pool.get('res.users').browse(cr,uid,[uid],c)[0].company_id.id,
2035 'chart_template_id': _get_chart,
2036 'code_digits': lambda *a:6,
2039 def action_create(self, cr, uid, ids, context=None):
2040 obj_multi = self.browse(cr,uid,ids[0])
2041 obj_acc = self.pool.get('account.account')
2042 obj_acc_tax = self.pool.get('account.tax')
2043 obj_journal = self.pool.get('account.journal')
2044 obj_sequence = self.pool.get('ir.sequence')
2045 obj_acc_template = self.pool.get('account.account.template')
2046 obj_fiscal_position_template = self.pool.get('account.fiscal.position.template')
2047 obj_fiscal_position = self.pool.get('account.fiscal.position')
2050 obj_acc_root = obj_multi.chart_template_id.account_root_id
2051 tax_code_root_id = obj_multi.chart_template_id.tax_code_root_id.id
2052 company_id = obj_multi.company_id.id
2055 acc_template_ref = {}
2056 tax_template_ref = {}
2057 tax_code_template_ref = {}
2060 #create all the tax code
2061 children_tax_code_template = self.pool.get('account.tax.code.template').search(cr, uid, [('parent_id','child_of',[tax_code_root_id])], order='id')
2062 for tax_code_template in self.pool.get('account.tax.code.template').browse(cr, uid, children_tax_code_template):
2064 'name': (tax_code_root_id == tax_code_template.id) and obj_multi.company_id.name or tax_code_template.name,
2065 'code': tax_code_template.code,
2066 'info': tax_code_template.info,
2067 '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,
2068 'company_id': company_id,
2069 'sign': tax_code_template.sign,
2071 new_tax_code = self.pool.get('account.tax.code').create(cr,uid,vals)
2072 #recording the new tax code to do the mapping
2073 tax_code_template_ref[tax_code_template.id] = new_tax_code
2076 for tax in obj_multi.chart_template_id.tax_template_ids:
2080 'sequence': tax.sequence,
2081 'amount':tax.amount,
2083 'applicable_type': tax.applicable_type,
2084 'domain':tax.domain,
2085 'parent_id': tax.parent_id and ((tax.parent_id.id in tax_template_ref) and tax_template_ref[tax.parent_id.id]) or False,
2086 'child_depend': tax.child_depend,
2087 'python_compute': tax.python_compute,
2088 'python_compute_inv': tax.python_compute_inv,
2089 'python_applicable': tax.python_applicable,
2090 'tax_group':tax.tax_group,
2091 '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,
2092 '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,
2093 'base_sign': tax.base_sign,
2094 'tax_sign': tax.tax_sign,
2095 '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,
2096 '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,
2097 'ref_base_sign': tax.ref_base_sign,
2098 'ref_tax_sign': tax.ref_tax_sign,
2099 'include_base_amount': tax.include_base_amount,
2100 'description':tax.description,
2101 'company_id': company_id,
2102 'type_tax_use': tax.type_tax_use
2104 new_tax = obj_acc_tax.create(cr,uid,vals_tax)
2105 #as the accounts have not been created yet, we have to wait before filling these fields
2106 todo_dict[new_tax] = {
2107 'account_collected_id': tax.account_collected_id and tax.account_collected_id.id or False,
2108 'account_paid_id': tax.account_paid_id and tax.account_paid_id.id or False,
2110 tax_template_ref[tax.id] = new_tax
2112 #deactivate the parent_store functionnality on account_account for rapidity purpose
2113 self.pool._init = True
2115 children_acc_template = obj_acc_template.search(cr, uid, [('parent_id','child_of',[obj_acc_root.id])])
2116 children_acc_template.sort()
2117 for account_template in obj_acc_template.browse(cr, uid, children_acc_template):
2119 for tax in account_template.tax_ids:
2120 tax_ids.append(tax_template_ref[tax.id])
2121 #create the account_account
2123 dig = obj_multi.code_digits
2124 code_main = account_template.code and len(account_template.code) or 0
2125 code_acc = account_template.code or ''
2126 if code_main>0 and code_main<=dig and account_template.type != 'view':
2127 code_acc=str(code_acc) + (str('0'*(dig-code_main)))
2129 'name': (obj_acc_root.id == account_template.id) and obj_multi.company_id.name or account_template.name,
2130 #'sign': account_template.sign,
2131 'currency_id': account_template.currency_id and account_template.currency_id.id or False,
2133 'type': account_template.type,
2134 'user_type': account_template.user_type and account_template.user_type.id or False,
2135 'reconcile': account_template.reconcile,
2136 'shortcut': account_template.shortcut,
2137 'note': account_template.note,
2138 '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,
2139 'tax_ids': [(6,0,tax_ids)],
2140 'company_id': company_id,
2142 new_account = obj_acc.create(cr,uid,vals)
2143 acc_template_ref[account_template.id] = new_account
2144 #reactivate the parent_store functionnality on account_account
2145 self.pool._init = False
2146 self.pool.get('account.account')._parent_store_compute(cr)
2148 for key,value in todo_dict.items():
2149 if value['account_collected_id'] or value['account_paid_id']:
2150 obj_acc_tax.write(cr, uid, [key], vals={
2151 'account_collected_id': acc_template_ref[value['account_collected_id']],
2152 'account_paid_id': acc_template_ref[value['account_paid_id']],
2157 view_id = self.pool.get('account.journal.view').search(cr,uid,[('name','=','Journal View')])[0]
2158 seq_id = obj_sequence.search(cr,uid,[('name','=','Account Journal')])[0]
2160 if obj_multi.seq_journal:
2161 seq_id_sale = obj_sequence.search(cr,uid,[('name','=','Sale Journal')])[0]
2162 seq_id_purchase = obj_sequence.search(cr,uid,[('name','=','Purchase Journal')])[0]
2164 seq_id_sale = seq_id
2165 seq_id_purchase = seq_id
2167 vals_journal['view_id'] = view_id
2170 vals_journal['name'] = _('Sales Journal')
2171 vals_journal['type'] = 'sale'
2172 vals_journal['code'] = _('SAJ')
2173 vals_journal['sequence_id'] = seq_id_sale
2175 if obj_multi.chart_template_id.property_account_receivable:
2176 vals_journal['default_credit_account_id'] = acc_template_ref[obj_multi.chart_template_id.property_account_income_categ.id]
2177 vals_journal['default_debit_account_id'] = acc_template_ref[obj_multi.chart_template_id.property_account_income_categ.id]
2179 obj_journal.create(cr,uid,vals_journal)
2182 vals_journal['name'] = _('Purchase Journal')
2183 vals_journal['type'] = 'purchase'
2184 vals_journal['code'] = _('EXJ')
2185 vals_journal['sequence_id'] = seq_id_purchase
2187 if obj_multi.chart_template_id.property_account_payable:
2188 vals_journal['default_credit_account_id'] = acc_template_ref[obj_multi.chart_template_id.property_account_expense_categ.id]
2189 vals_journal['default_debit_account_id'] = acc_template_ref[obj_multi.chart_template_id.property_account_expense_categ.id]
2191 obj_journal.create(cr,uid,vals_journal)
2194 view_id_cash = self.pool.get('account.journal.view').search(cr,uid,[('name','=','Cash Journal View')])[0]
2195 view_id_cur = self.pool.get('account.journal.view').search(cr,uid,[('name','=','Multi-Currency Cash Journal View')])[0]
2196 ref_acc_bank = obj_multi.chart_template_id.bank_account_view_id
2199 for line in obj_multi.bank_accounts_id:
2200 #create the account_account for this bank journal
2201 tmp = self.pool.get('res.partner.bank').name_get(cr, uid, [line.acc_no.id])[0][1]
2202 dig = obj_multi.code_digits
2203 new_code = str(current_num)
2204 if ref_acc_bank.code:
2205 new_code = str(ref_acc_bank.code.ljust(dig,'0') + str(current_num))
2207 'name': line.acc_no.bank and line.acc_no.bank.name+' '+tmp or tmp,
2208 'currency_id': line.currency_id and line.currency_id.id or False,
2211 'user_type': account_template.user_type and account_template.user_type.id or False,
2213 'parent_id': acc_template_ref[ref_acc_bank.id] or False,
2214 'company_id': company_id,
2216 acc_cash_id = obj_acc.create(cr,uid,vals)
2218 if obj_multi.seq_journal:
2220 'name': _('Bank Journal ') + vals['name'],
2221 'code': 'account.journal',
2223 seq_id = obj_sequence.create(cr,uid,vals_seq)
2225 #create the bank journal
2226 vals_journal['name']= vals['name']
2227 vals_journal['code']= _('BNK') + str(current_num)
2228 vals_journal['sequence_id'] = seq_id
2229 vals_journal['type'] = 'cash'
2230 if line.currency_id:
2231 vals_journal['view_id'] = view_id_cur
2232 vals_journal['currency'] = line.currency_id.id
2234 vals_journal['view_id'] = view_id_cash
2235 vals_journal['default_credit_account_id'] = acc_cash_id
2236 vals_journal['default_debit_account_id'] = acc_cash_id
2237 obj_journal.create(cr,uid,vals_journal)
2241 #create the properties
2242 property_obj = self.pool.get('ir.property')
2243 fields_obj = self.pool.get('ir.model.fields')
2246 ('property_account_receivable','res.partner','account.account'),
2247 ('property_account_payable','res.partner','account.account'),
2248 ('property_account_expense_categ','product.category','account.account'),
2249 ('property_account_income_categ','product.category','account.account'),
2250 ('property_account_expense','product.template','account.account'),
2251 ('property_account_income','product.template','account.account')
2253 for record in todo_list:
2255 r = property_obj.search(cr, uid, [('name','=', record[0] ),('company_id','=',company_id)])
2256 account = getattr(obj_multi.chart_template_id, record[0])
2257 field = fields_obj.search(cr, uid, [('name','=',record[0]),('model','=',record[1]),('relation','=',record[2])])
2260 'company_id': company_id,
2261 'fields_id': field[0],
2262 'value': account and 'account.account,'+str(acc_template_ref[account.id]) or False,
2265 #the property exist: modify it
2266 property_obj.write(cr, uid, r, vals)
2268 #create the property
2269 property_obj.create(cr, uid, vals)
2271 fp_ids = obj_fiscal_position_template.search(cr, uid,[('chart_template_id', '=', obj_multi.chart_template_id.id)])
2274 for position in obj_fiscal_position_template.browse(cr, uid, fp_ids):
2277 'company_id' : company_id,
2278 'name' : position.name,
2280 new_fp = obj_fiscal_position.create(cr, uid, vals_fp)
2282 obj_tax_fp = self.pool.get('account.fiscal.position.tax')
2283 obj_ac_fp = self.pool.get('account.fiscal.position.account')
2285 for tax in position.tax_ids:
2287 'tax_src_id' : tax_template_ref[tax.tax_src_id.id],
2288 'tax_dest_id' : tax_template_ref[tax.tax_dest_id.id],
2289 'position_id' : new_fp,
2291 obj_tax_fp.create(cr, uid, vals_tax)
2293 for acc in position.account_ids:
2295 'account_src_id' : acc_template_ref[acc.account_src_id.id],
2296 'account_dest_id' : acc_template_ref[acc.account_dest_id.id],
2297 'position_id' : new_fp,
2299 obj_ac_fp.create(cr, uid, vals_acc)
2302 'view_type': 'form',
2303 "view_mode": 'form',
2304 'res_model': 'ir.actions.configuration.wizard',
2305 'type': 'ir.actions.act_window',
2308 def action_cancel(self,cr,uid,ids,conect=None):
2310 'view_type': 'form',
2311 "view_mode": 'form',
2312 'res_model': 'ir.actions.configuration.wizard',
2313 'type': 'ir.actions.act_window',
2318 wizard_multi_charts_accounts()
2320 class account_bank_accounts_wizard(osv.osv_memory):
2321 _name='account.bank.accounts.wizard'
2324 'acc_no':fields.many2one('res.partner.bank','Account No.',required=True),
2325 'bank_account_id':fields.many2one('wizard.multi.charts.accounts', 'Bank Account', required=True),
2326 'currency_id':fields.many2one('res.currency', 'Currency'),
2329 account_bank_accounts_wizard()
2331 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: