merge
[odoo/odoo.git] / addons / account / account.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
6 #    $Id$
7 #
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.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU General Public License for more details.
17 #
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/>.
20 #
21 ##############################################################################
22 import time
23 import netsvc
24
25 from osv import fields, osv
26
27 from tools.misc import currency
28 from tools.translate import _
29 import pooler
30 import mx.DateTime
31 from mx.DateTime import RelativeDateTime, now, DateTime, localtime
32
33
34 class account_payment_term(osv.osv):
35     _name = "account.payment.term"
36     _description = "Payment Term"
37     _columns = {
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'),
42     }
43     _defaults = {
44         'active': lambda *a: 1,
45     }
46     _order = "name"
47
48     def compute(self, cr, uid, id, value, date_ref=False, context={}):
49         if not date_ref:
50             date_ref = now().strftime('%Y-%m-%d')
51         pt = self.browse(cr, uid, id, context)
52         amount = value
53         result = []
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)
61             if amt:
62                 next_date = mx.DateTime.strptime(date_ref, '%Y-%m-%d') + RelativeDateTime(days=line.days)
63                 if line.days2 < 0:
64                     next_date += RelativeDateTime(day=line.days2)
65                 if line.days2 > 0:
66                     next_date += RelativeDateTime(day=line.days2, months=1)
67                 result.append( (next_date.strftime('%Y-%m-%d'), amt) )
68                 amount -= amt
69         return result
70
71 account_payment_term()
72
73 class account_payment_term_line(osv.osv):
74     _name = "account.payment.term.line"
75     _description = "Payment Term Line"
76     _columns = {
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),
85     }
86     _defaults = {
87         'value': lambda *a: 'balance',
88         'sequence': lambda *a: 5,
89         'days2': lambda *a: 0,
90     }
91     _order = "sequence"
92 account_payment_term_line()
93
94
95 class account_account_type(osv.osv):
96     _name = "account.account.type"
97     _description = "Account Type"
98     _columns = {
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.'),
105     }
106     _defaults = {
107         'close_method': lambda *a: 'none',
108         'sequence': lambda *a: 5,
109         'sign': lambda *a: 1,
110     }
111     _order = "sequence"
112 account_account_type()
113
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]
119
120 #----------------------------------------------------------
121 # Accounts
122 #----------------------------------------------------------
123
124 class account_tax(osv.osv):
125     _name = 'account.tax'
126 account_tax()
127
128 class account_account(osv.osv):
129     _order = "parent_left"
130     _parent_order = "code"
131     _name = "account.account"
132     _description = "Account"
133     _parent_store = True
134
135     def search(self, cr, uid, args, offset=0, limit=None, order=None,
136             context=None, count=False):
137         if context is None:
138             context = {}
139         pos = 0
140
141         while pos < len(args):
142
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':
146                 if not args[pos][2]:
147                     del args[pos]
148                     continue
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'))
152                     continue
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)
157             pos += 1
158
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)
164             return ids
165
166         return super(account_account, self).search(cr, uid, args, offset, limit,
167                 order, context=context, count=count)
168
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)
172         ids3 = []
173         for rec in self.browse(cr, uid, ids2, context=context):
174             for child in rec.child_consol_ids:
175                 ids3.append(child.id)
176         if ids3:
177             ids3 = self._get_children_and_consol(cr, uid, ids3, context)
178         return ids2 + ids3
179
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
182         mapping = {
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 "
186         }
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
191         accounts = {}
192         if ids2:
193             query = self.pool.get('account.move.line')._query_get(cr, uid,
194                     context=context)
195             cr.execute(("SELECT l.account_id as id, " +\
196                     ' , '.join(map(lambda x: mapping[x], field_names)) +
197                     "FROM " \
198                         "account_move_line l " \
199                     "WHERE " \
200                         "l.account_id IN (%s) " \
201                         "AND " + query + " " \
202                     "GROUP BY l.account_id") % (acc_set, ))
203
204             for res in cr.dictfetchall():
205                 accounts[res['id']] = res
206
207         #for the asked accounts, get from the dictionnary 'accounts' the value of it
208         res = {}
209         for id in ids:
210             res[id] = self._get_account_values(cr, uid, id, accounts, field_names, context)
211         return res
212
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:
220                     ids2.append(t)
221             for i in ids2:
222                 tmp = self._get_account_values(cr, uid, i, accounts, field_names, context)
223                 for a in field_names:
224                     res[a] += tmp[a]
225         else:
226             ids2 = self.search(cr, uid, [('parent_id', 'child_of', [browse_rec.id])])
227             for i in ids2:
228                 for a in field_names:
229                     res[a] += accounts.get(i, {}).get(a, 0.0)
230         return res
231
232     def _get_company_currency(self, cr, uid, ids, field_name, arg, context={}):
233         result = {}
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)
236         return result
237
238     def _get_child_ids(self, cr, uid, ids, field_name, arg, context={}):
239         result = {}
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]
243             else:
244                 result[record.id] = []
245
246             if record.child_consol_ids:
247                 for acc in record.child_consol_ids:
248                     result[record.id].append(acc.id)
249
250         return result
251
252     _columns = {
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'),
259             ('view', 'View'),
260             ('consolidation', 'Consolidation'),
261             ('other', 'Others'),
262             ('closed', 'Closed'),
263         ], 'Internal Type', required=True,),
264
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),
281
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',
285             help=
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.', \
290             required=True),
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."),
294     }
295
296     def _default_company(self, cr, uid, context={}):
297         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
298         if user.company_id:
299             return user.company_id.id
300         return self.pool.get('res.company').search(cr, uid, [('parent_id', '=', False)])[0]
301
302     _defaults = {
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'
309     }
310
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)):
315             return False
316         while(ids):
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()))
319             c_ids = child_ids
320             if (p_id and (p_id in c_ids)) or (obj_self.id in c_ids):
321                 return False
322             while len(c_ids):
323                 s_ids = self.search(cr, uid, [('parent_id', 'in', c_ids)])
324                 if p_id and (p_id in s_ids):
325                     return False
326                 c_ids = s_ids
327             ids = child_ids
328         return True
329
330     _constraints = [
331         (_check_recursion, 'Error ! You can not create recursive accounts.', ['parent_id'])
332     ]
333     _sql_constraints = [
334         ('code_company_uniq', 'unique (code,company_id)', 'The code of the account must be unique per company !')
335     ]
336     def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=80):
337         if not args:
338             args = []
339         if not context:
340             context = {}
341         args = args[:]
342         ids = []
343         try:
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))]
348                 name = False
349             if name and str(name).startswith('type:'):
350                 type = name.split(':')[1]
351                 args += [('type', '=', type)]
352                 name = False
353         except:
354             pass
355         if name:
356             ids = self.search(cr, user, [('code', '=like', name+"%")]+args, limit=limit)
357             if not ids:
358                 ids = self.search(cr, user, [('shortcut', '=', name)]+ args, limit=limit)
359             if not ids:
360                 ids = self.search(cr, user, [('name', operator, name)]+ args, limit=limit)
361         else:
362             ids = self.search(cr, user, args, context=context, limit=limit)
363         return self.name_get(cr, user, ids, context=context)
364
365     def name_get(self, cr, uid, ids, context={}):
366         if not len(ids):
367             return []
368         reads = self.read(cr, uid, ids, ['name', 'code'], context)
369         res = []
370         for record in reads:
371             name = record['name']
372             if record['code']:
373                 name = record['code'] + ' '+name
374             res.append((record['id'], name))
375         return res
376
377     def copy(self, cr, uid, id, default={}, context={}, done_list=[], local=False):
378         account = self.browse(cr, uid, id, context=context)
379         new_child_ids = []
380         if not default:
381             default = {}
382         default = default.copy()
383         default['parent_id'] = False
384         if not local:
385             done_list = []
386         if account.id in done_list:
387             return False
388         done_list.append(account.id)
389         if account:
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)
392                 if child_ids:
393                     new_child_ids.append(child_ids)
394             default['child_parent_ids'] = [(6, 0, new_child_ids)]
395         else:
396             default['child_parent_ids'] = False
397         return super(account_account, self).copy(cr, uid, id, default, context=context)
398
399     def write(self, cr, uid, ids, vals, context=None):
400         if not context:
401             context = {}
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)
408 account_account()
409
410 class account_journal_view(osv.osv):
411     _name = "account.journal.view"
412     _description = "Journal View"
413     _columns = {
414         'name': fields.char('Journal View', size=64, required=True),
415         'columns_id': fields.one2many('account.journal.column', 'view_id', 'Columns')
416     }
417     _order = "name"
418 account_journal_view()
419
420
421 class account_journal_column(osv.osv):
422     def _col_get(self, cr, user, context={}):
423         result = []
424         cols = self.pool.get('account.move.line')._columns
425         for col in cols:
426             result.append( (col, cols[col].string) )
427         result.sort()
428         return result
429     _name = "account.journal.column"
430     _description = "Journal Column"
431     _columns = {
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'),
438     }
439     _order = "sequence"
440 account_journal_column()
441
442 class account_journal(osv.osv):
443     _name = "account.journal"
444     _description = "Journal"
445     _columns = {
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'),
450
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')]),
453
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."),
469     }
470
471     _defaults = {
472         'active': lambda *a: 1,
473         'user_id': lambda self,cr,uid,context: uid,
474     }
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
485 #           })
486         return journal_id
487
488     def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=80):
489         if not args:
490             args=[]
491         if not context:
492             context={}
493         ids = []
494         if name:
495             ids = self.search(cr, user, [('code','ilike',name)]+ args, limit=limit)
496         if not ids:
497             ids = self.search(cr, user, [('name',operator,name)]+ args, limit=limit)
498         return self.name_get(cr, user, ids, context=context)
499 account_journal()
500
501 class account_fiscalyear(osv.osv):
502     _name = "account.fiscalyear"
503     _description = "Fiscal Year"
504     _columns = {
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),
513     }
514
515     _defaults = {
516         'state': lambda *a: 'draft',
517     }
518     _order = "date_start"
519
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:
523             return False
524         return True
525
526     _constraints = [
527         (_check_duration, 'Error ! The duration of the Fiscal Year is invalid. ', ['date_stop'])
528     ]
529
530     def create_period3(self,cr, uid, ids, context={}):
531         return self.create_period(cr, uid, ids, context, 3)
532
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)
538
539                 if de.strftime('%Y-%m-%d')>fy.date_stop:
540                     de=mx.DateTime.strptime(fy.date_stop, '%Y-%m-%d')
541
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,
548                 })
549                 ds = ds + RelativeDateTime(months=interval)
550         return True
551
552     def find(self, cr, uid, dt=None, exception=True, context={}):
553         if not dt:
554             dt = time.strftime('%Y-%m-%d')
555         ids = self.search(cr, uid, [('date_start', '<=', dt), ('date_stop', '>=', dt)])
556         if not ids:
557             if exception:
558                 raise osv.except_osv(_('Error !'), _('No fiscal year defined for this date !\nPlease create one.'))
559             else:
560                 return False
561         return ids[0]
562 account_fiscalyear()
563
564 class account_period(osv.osv):
565     _name = "account.period"
566     _description = "Account period"
567     _columns = {
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)
576     }
577     _defaults = {
578         'state': lambda *a: 'draft',
579     }
580     _order = "date_start"
581
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:
585             return False
586         return True
587
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:
591                 continue
592
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:
597                 return False
598
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:
602                     return False
603         return True
604
605     _constraints = [
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'])
608     ]
609
610     def next(self, cr, uid, period, step, context={}):
611         ids = self.search(cr, uid, [('date_start','>',period.date_start)])
612         if len(ids)>=step:
613             return ids[step-1]
614         return False
615
616     def find(self, cr, uid, dt=None, context={}):
617         if not dt:
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)])
621         if not ids:
622             raise osv.except_osv(_('Error !'), _('No period defined for this date !\nPlease create a fiscal year.'))
623         return ids
624
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':
629                 mode = 'draft'
630                 for id in ids:
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))
633         return True
634
635 account_period()
636
637 class account_journal_period(osv.osv):
638     _name = "account.journal.period"
639     _description = "Journal - Period"
640
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']):
644             result[r['id']] = {
645                 'draft': 'STOCK_NEW',
646                 'printed': 'STOCK_PRINT_PREVIEW',
647                 'done': 'STOCK_DIALOG_AUTHENTICATION',
648             }.get(r['state'], 'STOCK_NEW')
649         return result
650
651     _columns = {
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)
658     }
659
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))
663             res = cr.fetchall()
664             if res:
665                 raise osv.except_osv(_('Error !'), _('You can not modify/delete a journal with entries for this period !'))
666         return True
667
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)
671
672     def create(self, cr, uid, vals, context={}):
673         period_id=vals.get('period_id',False)
674         if period_id:
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)
678
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)
682
683     _defaults = {
684         'state': lambda *a: 'draft',
685         'active': lambda *a: True,
686     }
687     _order = "period_id"
688
689 account_journal_period()
690
691 class account_fiscalyear(osv.osv):
692     _inherit = "account.fiscalyear"
693     _description = "Fiscal Year"
694     _columns = {
695         'end_journal_period_id':fields.many2one('account.journal.period','End of Year Entries Journal', readonly=True),
696     }
697
698 account_fiscalyear()
699 #----------------------------------------------------------
700 # Entries
701 #----------------------------------------------------------
702 class account_move(osv.osv):
703     _name = "account.move"
704     _description = "Account Entry"
705     _order = 'id desc'
706
707     def name_get(self, cursor, user, ids, context=None):
708         if not len(ids):
709             return []
710         res=[]
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)
715             else:
716                 name = move.name
717             res.append((move.id, name))
718         return res
719
720
721     def _get_period(self, cr, uid, context):
722         periods = self.pool.get('account.period').find(cr, uid)
723         if periods:
724             return periods[0]
725         else:
726             return False
727
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())
732         for id in ids:
733             result.setdefault(id, 0.0)
734         return result
735
736     _columns = {
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)]}),
757     }
758     _defaults = {
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'),
764     }
765
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),
772                     ])
773                 if len(move_ids) > 1:
774                     return False
775         return True
776
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:
781                     return False
782                 if line.journal_id.id != move.journal_id.id:
783                     return False
784         return True
785
786     _constraints = [
787         (_check_centralisation,
788             'You cannot create more than one move per period on centralized journal',
789             ['journal_id']),
790         (_check_period_journal,
791             'You cannot create entries on different periods/journals in the same move',
792             ['line_id']),
793     ]
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):
797                 if move.name =='/':
798                     new_name = False
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)
803                     else:
804                         raise osv.except_osv(_('Error'), _('No sequence defined in the journal !'))
805                     if new_name:
806                         self.write(cr, uid, [move.id], {'name':new_name})
807
808             cr.execute('update account_move set state=%s where id in ('+','.join(map(str,ids))+')', ('posted',))
809         else:
810             raise osv.except_osv(_('Integrity Error !'), _('You can not validate a non-balanced entry !'))
811         return True
812
813     def button_validate(self, cursor, user, ids, context=None):
814         return self.post(cursor, user, ids, context=context)
815
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.'))
820         if len(ids):
821             cr.execute('update account_move set state=%s where id in ('+','.join(map(str,ids))+')', ('draft',))
822         return True
823
824     def write(self, cr, uid, ids, vals, context={}):
825         c = context.copy()
826         c['novalidate'] = True
827         result = super(osv.osv, self).write(cr, uid, ids, vals, c)
828         self.validate(cr, uid, ids, context)
829         return result
830
831     #
832     # TODO: Check if period is closed !
833     #
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']:
838                     if not l[0]:
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']:
843                     if not l[0]:
844                         l[2]['period_id'] = vals['period_id']
845                 context['period_id'] = vals['period_id']
846             else:
847                 default_period = self._get_period(cr, uid, context)
848                 for l in vals['line_id']:
849                     if not l[0]:
850                         l[2]['period_id'] = default_period
851                 context['period_id'] = default_period
852
853         accnt_journal = self.pool.get('account.journal').browse(cr, uid, vals['journal_id'])
854         if 'line_id' in vals:
855             c = context.copy()
856             c['novalidate'] = True
857             result = super(account_move, self).create(cr, uid, vals, c)
858             self.validate(cr, uid, [result], context)
859         else:
860             result = super(account_move, self).create(cr, uid, vals, context)
861         return result
862
863     def copy(self, cr, uid, id, default=None, context=None):
864         if default is None:
865             default = {}
866         default = default.copy()
867         default.update({'state':'draft', 'name':'/',})
868         return super(account_move, self).copy(cr, uid, id, default, context)
869
870     def unlink(self, cr, uid, ids, context={}, check=True):
871         toremove = []
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"!') % \
876                                 move['name'])
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)
884         return result
885
886     def _compute_balance(self, cr, uid, id, context={}):
887         move = self.browse(cr, uid, [id])[0]
888         amount = 0
889         for line in move.line_id:
890             amount+= (line.debit - line.credit)
891         return amount
892
893     def _centralise(self, cr, uid, move, mode):
894         if mode=='credit':
895             account_id = move.journal_id.default_debit_account_id.id
896             mode2 = 'debit'
897             if not account_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)
901         else:
902             account_id = move.journal_id.default_credit_account_id.id
903             mode2 = 'credit'
904             if not account_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)
908
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))
912         res = cr.fetchone()
913         if res:
914             line_id = res[0]
915         else:
916             line_id = self.pool.get('account.move.line').create(cr, uid, {
917                 'name': 'Centralisation '+mode,
918                 'centralisation': mode,
919                 'account_id': account_id,
920                 'move_id': move.id,
921                 'journal_id': move.journal_id.id,
922                 'period_id': move.period_id.id,
923                 'date': move.period_id.date_stop,
924                 'debit': 0.0,
925                 'credit': 0.0,
926             }, {'journal_id': move.journal_id.id, 'period_id': move.period_id.id})
927
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))
931         res = cr.fetchone()
932         if res:
933             line_id2 = res[0]
934         else:
935             line_id2 = 0
936
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))
940         return True
941
942     #
943     # Validate a balanced move. If it is a centralised journal, create a move.
944     #
945     def validate(self, cr, uid, ids, context={}):
946         if context and ('__last_update' in context):
947             del context['__last_update']
948         ok = True
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)
954
955             journal = move.journal_id
956             amount = 0
957             line_ids = []
958             line_draft_ids = []
959             company_id=None
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)
965
966                 if not company_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"))
970
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)))
974
975             if abs(amount) < 0.0001:
976                 if not len(line_draft_ids):
977                     continue
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,
981                     'state': 'valid'
982                 }, context, check=False)
983                 todo = []
984                 account = {}
985                 account2 = {}
986                 if journal.type not in ('purchase','sale'):
987                     continue
988
989                 for line in move.line_id:
990                     code = amount = 0
991                     key = (line.account_id.id, line.tax_code_id.id)
992                     if key in account2:
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)
1003                 #
1004                 # Compute VAT
1005                 #
1006                 continue
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, {
1011                     'state': 'valid'
1012                 }, context, check=False)
1013                 continue
1014             else:
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,
1020                     'state': 'draft'
1021                 }, context, check=False)
1022                 ok = False
1023         if ok:
1024             list_ids = []
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)
1028         return ok
1029 account_move()
1030
1031 class account_move_reconcile(osv.osv):
1032     _name = "account.move.reconcile"
1033     _description = "Account Reconciliation"
1034     _columns = {
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),
1040     }
1041     _defaults = {
1042         'name': lambda self,cr,uid,ctx={}: self.pool.get('ir.sequence').get(cr, uid, 'account.reconcile') or '/',
1043     }
1044     def reconcile_partial_check(self, cr, uid, ids, type='auto', context={}):
1045         for rec in self.browse(cr, uid, ids, context):
1046             total = 0.0
1047             for line in rec.line_partial_ids:
1048                 total += (line.debit or 0.0) - (line.credit or 0.0)
1049         if not total:
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 }
1053             )
1054         return True
1055
1056     def name_get(self, cr, uid, ids, context=None):
1057         if not len(ids):
1058             return []
1059         result = []
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)
1062             if total:
1063                 name = '%s (%.2f)' % (r.name, total)
1064                 result.append((r.id,name))
1065             else:
1066                 result.append((r.id,r.name))
1067         return result
1068
1069
1070 account_move_reconcile()
1071
1072 #----------------------------------------------------------
1073 # Tax
1074 #----------------------------------------------------------
1075 """
1076 a documenter
1077 child_depend: la taxe depend des taxes filles
1078 """
1079 class account_tax_code(osv.osv):
1080     """
1081     A code for the tax object.
1082
1083     This code is used for some tax declarations.
1084     """
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')
1099         else:
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
1110                 return amount
1111             res[record.id] = round(_rec_get(record), 2)
1112         return res
1113
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']
1117         else:
1118             fiscalyear_id = self.pool.get('account.fiscalyear').find(cr, uid, exception=False)
1119         where = ''
1120         if fiscalyear_id:
1121             pids = map(lambda x: str(x.id), self.pool.get('account.fiscalyear').browse(cr, uid, fiscalyear_id).period_ids)
1122             if pids:
1123                 where = ' and period_id in (' + (','.join(pids))+')'
1124         return self._sum(cr, uid, ids, name, args, context,
1125                 where=where)
1126
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']
1130         else:
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))
1137
1138     _name = 'account.tax.code'
1139     _description = 'Tax Code'
1140     _rec_name = 'code'
1141     _columns = {
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"),
1153     }
1154
1155
1156     def name_get(self, cr, uid, ids, context=None):
1157         if not len(ids):
1158             return []
1159         if isinstance(ids, (int, long)):
1160             ids = [ids]
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']) \
1163                 for x in reads]
1164
1165     def _default_company(self, cr, uid, context={}):
1166         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
1167         if user.company_id:
1168             return user.company_id.id
1169         return self.pool.get('res.company').search(cr, uid, [('parent_id', '=', False)])[0]
1170     _defaults = {
1171         'company_id': _default_company,
1172         'sign': lambda *args: 1.0,
1173         'notprintable': lambda *a: False,
1174     }
1175     def _check_recursion(self, cr, uid, ids):
1176         level = 100
1177         while len(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()))
1180             if not level:
1181                 return False
1182             level -= 1
1183         return True
1184
1185     _constraints = [
1186         (_check_recursion, 'Error ! You can not create recursive accounts.', ['parent_id'])
1187     ]
1188     _order = 'code,name'
1189 account_tax_code()
1190
1191 class account_tax(osv.osv):
1192     """
1193     A tax object.
1194
1195     Type: percent, fixed, none, code
1196         PERCENT: tax = price * amount
1197         FIXED: tax = price + amount
1198         NONE: no tax line
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)
1202     """
1203     _name = 'account.tax'
1204     _description = 'Tax'
1205     _columns = {
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."),
1224
1225         #
1226         # Fields used for the VAT declaration
1227         #
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."),
1232
1233         # Same fields for refund invoices
1234
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)
1244
1245     }
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)
1254
1255     def name_get(self, cr, uid, ids, context={}):
1256         if not len(ids):
1257             return []
1258         res = []
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 ))
1262         return res
1263
1264     def _default_company(self, cr, uid, context={}):
1265         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
1266         if user.company_id:
1267             return user.company_id.id
1268         return self.pool.get('res.company').search(cr, uid, [('parent_id', '=', False)])[0]
1269     _defaults = {
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,
1286     }
1287     _order = 'sequence'
1288
1289     def _applicable(self, cr, uid, taxes, price_unit, address_id=None, product=None, partner=None):
1290         res = []
1291         for tax in taxes:
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):
1296                     res.append(tax)
1297             else:
1298                 res.append(tax)
1299         return res
1300
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)
1303
1304         res = []
1305         cur_price_unit=price_unit
1306         for tax in taxes:
1307             # we compute the amount for the current tax object and append it to the result
1308
1309             data = {'id':tax.id,
1310                             'name':tax.name,
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,
1323             }
1324             res.append(data)
1325             if tax.type=='percent':
1326                 amount = cur_price_unit * tax.amount
1327                 data['amount'] = amount
1328
1329             elif tax.type=='fixed':
1330                 data['amount'] = tax.amount
1331                 data['tax_amount']=quantity
1332                # data['amount'] = quantity
1333             elif tax.type=='code':
1334                 address = address_id and self.pool.get('res.partner.address').browse(cr, uid, address_id) or None
1335                 localdict = {'price_unit':cur_price_unit, 'address':address, 'product':product, 'partner':partner}
1336                 exec tax.python_compute in localdict
1337                 amount = localdict['result']
1338                 data['amount'] = amount
1339             elif tax.type=='balance':
1340                 data['amount'] = cur_price_unit - reduce(lambda x,y: y.get('amount',0.0)+x, res, 0.0)
1341                 data['balance'] = cur_price_unit
1342
1343             amount2 = data['amount']
1344             if len(tax.child_ids):
1345                 if tax.child_depend:
1346                     latest = res.pop()
1347                 amount = amount2
1348                 child_tax = self._unit_compute(cr, uid, tax.child_ids, amount, address_id, product, partner, quantity)
1349                 res.extend(child_tax)
1350                 if tax.child_depend:
1351                     for r in res:
1352                         for name in ('base','ref_base'):
1353                             if latest[name+'_code_id'] and latest[name+'_sign'] and not r[name+'_code_id']:
1354                                 r[name+'_code_id'] = latest[name+'_code_id']
1355                                 r[name+'_sign'] = latest[name+'_sign']
1356                                 r['price_unit'] = latest['price_unit']
1357                                 latest[name+'_code_id'] = False
1358                         for name in ('tax','ref_tax'):
1359                             if latest[name+'_code_id'] and latest[name+'_sign'] and not r[name+'_code_id']:
1360                                 r[name+'_code_id'] = latest[name+'_code_id']
1361                                 r[name+'_sign'] = latest[name+'_sign']
1362                                 r['amount'] = data['amount']
1363                                 latest[name+'_code_id'] = False
1364             if tax.include_base_amount:
1365                 cur_price_unit+=amount2
1366         return res
1367
1368     def compute(self, cr, uid, taxes, price_unit, quantity, address_id=None, product=None, partner=None):
1369
1370         """
1371         Compute tax values for given PRICE_UNIT, QUANTITY and a buyer/seller ADDRESS_ID.
1372
1373         RETURN:
1374             [ tax ]
1375             tax = {'name':'', 'amount':0.0, 'account_collected_id':1, 'account_paid_id':2}
1376             one tax for each tax id in IDS and their childs
1377         """
1378         res = self._unit_compute(cr, uid, taxes, price_unit, address_id, product, partner, quantity)
1379         total = 0.0
1380         for r in res:
1381             if r.get('balance',False):
1382                 r['amount'] = round(r['balance'] * quantity, 2) - total
1383             else:
1384                 r['amount'] = round(r['amount'] * quantity, 2)
1385                 total += r['amount']
1386
1387         return res
1388
1389     def _unit_compute_inv(self, cr, uid, taxes, price_unit, address_id=None, product=None, partner=None):
1390         taxes = self._applicable(cr, uid, taxes, price_unit, address_id, product, partner)
1391
1392         res = []
1393         taxes.reverse()
1394         cur_price_unit=price_unit
1395
1396         tax_parent_tot = 0.0
1397         for tax in taxes:
1398             if (tax.type=='percent') and not tax.include_base_amount:
1399                 tax_parent_tot+=tax.amount
1400
1401         for tax in taxes:
1402             if tax.type=='percent':
1403                 if tax.include_base_amount:
1404                     amount = cur_price_unit - (cur_price_unit / (1 + tax.amount))
1405                 else:
1406                     amount = (cur_price_unit / (1 + tax_parent_tot)) * tax.amount
1407
1408             elif tax.type=='fixed':
1409                 amount = tax.amount
1410
1411             elif tax.type=='code':
1412                 address = address_id and self.pool.get('res.partner.address').browse(cr, uid, address_id) or None
1413                 localdict = {'price_unit':cur_price_unit, 'address':address, 'product':product, 'partner':partner}
1414                 exec tax.python_compute_inv in localdict
1415                 amount = localdict['result']
1416             elif tax.type=='balance':
1417                 data['amount'] = cur_price_unit - reduce(lambda x,y: y.get('amount',0.0)+x, res, 0.0)
1418                 data['balance'] = cur_price_unit
1419
1420
1421             if tax.include_base_amount:
1422                 cur_price_unit -= amount
1423                 todo = 0
1424             else:
1425                 todo = 1
1426             res.append({
1427                 'id': tax.id,
1428                 'todo': todo,
1429                 'name': tax.name,
1430                 'amount': amount,
1431                 'account_collected_id': tax.account_collected_id.id,
1432                 'account_paid_id': tax.account_paid_id.id,
1433                 'base_code_id': tax.base_code_id.id,
1434                 'ref_base_code_id': tax.ref_base_code_id.id,
1435                 'sequence': tax.sequence,
1436                 'base_sign': tax.base_sign,
1437                 'tax_sign': tax.tax_sign,
1438                 'ref_base_sign': tax.ref_base_sign,
1439                 'ref_tax_sign': tax.ref_tax_sign,
1440                 'price_unit': cur_price_unit,
1441                 'tax_code_id': tax.tax_code_id.id,
1442                 'ref_tax_code_id': tax.ref_tax_code_id.id,
1443             })
1444             if len(tax.child_ids):
1445                 if tax.child_depend:
1446                     del res[-1]
1447                     amount = price_unit
1448
1449             parent_tax = self._unit_compute_inv(cr, uid, tax.child_ids, amount, address_id, product, partner)
1450             res.extend(parent_tax)
1451
1452         total = 0.0
1453         for r in res:
1454             if r['todo']:
1455                 total += r['amount']
1456         for r in res:
1457             r['price_unit'] -= total
1458             r['todo'] = 0
1459         return res
1460
1461     def compute_inv(self, cr, uid, taxes, price_unit, quantity, address_id=None, product=None, partner=None):
1462         """
1463         Compute tax values for given PRICE_UNIT, QUANTITY and a buyer/seller ADDRESS_ID.
1464         Price Unit is a VAT included price
1465
1466         RETURN:
1467             [ tax ]
1468             tax = {'name':'', 'amount':0.0, 'account_collected_id':1, 'account_paid_id':2}
1469             one tax for each tax id in IDS and their childs
1470         """
1471         res = self._unit_compute_inv(cr, uid, taxes, price_unit, address_id, product, partner=None)
1472         total = 0.0
1473         for r in res:
1474             if r.get('balance',False):
1475                 r['amount'] = round(r['balance'] * quantity, 2) - total
1476             else:
1477                 r['amount'] = round(r['amount'] * quantity, 2)
1478                 total += r['amount']
1479         return res
1480 account_tax()
1481
1482 # ---------------------------------------------------------
1483 # Account Entries Models
1484 # ---------------------------------------------------------
1485
1486 class account_model(osv.osv):
1487     _name = "account.model"
1488     _description = "Account Model"
1489     _columns = {
1490         'name': fields.char('Model Name', size=64, required=True, help="This is a model for recurring accounting entries"),
1491         'ref': fields.char('Ref', size=64),
1492         'journal_id': fields.many2one('account.journal', 'Journal', required=True),
1493         'lines_id': fields.one2many('account.model.line', 'model_id', 'Model Entries'),
1494         'legend' :fields.text('Legend',readonly=True,size=100),
1495     }
1496
1497     _defaults = {
1498         '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'),
1499     }
1500     def generate(self, cr, uid, ids, datas={}, context={}):
1501         move_ids = []
1502         for model in self.browse(cr, uid, ids, context):
1503             period_id = self.pool.get('account.period').find(cr,uid, context=context)
1504             if not period_id:
1505                 raise osv.except_osv(_('No period found !'), _('Unable to find a valid period !'))
1506             period_id = period_id[0]
1507             move_id = self.pool.get('account.move').create(cr, uid, {
1508                 'ref': model.ref,
1509                 'period_id': period_id,
1510                 'journal_id': model.journal_id.id,
1511             })
1512             move_ids.append(move_id)
1513             for line in model.lines_id:
1514                 val = {
1515                     'move_id': move_id,
1516                     'journal_id': model.journal_id.id,
1517                     'period_id': period_id
1518                 }
1519                 val.update({
1520                     'name': line.name,
1521                     'quantity': line.quantity,
1522                     'debit': line.debit,
1523                     'credit': line.credit,
1524                     'account_id': line.account_id.id,
1525                     'move_id': move_id,
1526                     'ref': line.ref,
1527                     'partner_id': line.partner_id.id,
1528                     'date': time.strftime('%Y-%m-%d'),
1529                     'date_maturity': time.strftime('%Y-%m-%d')
1530                 })
1531                 c = context.copy()
1532                 c.update({'journal_id': model.journal_id.id,'period_id': period_id})
1533                 self.pool.get('account.move.line').create(cr, uid, val, context=c)
1534         return move_ids
1535 account_model()
1536
1537 class account_model_line(osv.osv):
1538     _name = "account.model.line"
1539     _description = "Account Model Entries"
1540     _columns = {
1541         'name': fields.char('Name', size=64, required=True),
1542         'sequence': fields.integer('Sequence', required=True, help="The sequence field is used to order the resources from lower sequences to higher ones"),
1543         'quantity': fields.float('Quantity', digits=(16,2), help="The optional quantity on entries"),
1544         'debit': fields.float('Debit', digits=(16,2)),
1545         'credit': fields.float('Credit', digits=(16,2)),
1546
1547         'account_id': fields.many2one('account.account', 'Account', required=True, ondelete="cascade"),
1548
1549         'model_id': fields.many2one('account.model', 'Model', required=True, ondelete="cascade", select=True),
1550
1551         'ref': fields.char('Ref.', size=16),
1552
1553         'amount_currency': fields.float('Amount Currency', help="The amount expressed in an optionnal other currency."),
1554         'currency_id': fields.many2one('res.currency', 'Currency'),
1555
1556         'partner_id': fields.many2one('res.partner', 'Partner Ref.'),
1557         '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."),
1558         'date': fields.selection([('today','Date of the day'), ('partner','Partner Payment Term')], 'Current Date', required=True, help="The date of the generated entries"),
1559     }
1560     _defaults = {
1561         'date': lambda *a: 'today'
1562     }
1563     _order = 'sequence'
1564     _sql_constraints = [
1565         ('credit_debit1', 'CHECK (credit*debit=0)',  'Wrong credit or debit value in model !'),
1566         ('credit_debit2', 'CHECK (credit+debit>=0)', 'Wrong credit or debit value in model !'),
1567     ]
1568 account_model_line()
1569
1570 # ---------------------------------------------------------
1571 # Account Subscription
1572 # ---------------------------------------------------------
1573
1574
1575 class account_subscription(osv.osv):
1576     _name = "account.subscription"
1577     _description = "Account Subscription"
1578     _columns = {
1579         'name': fields.char('Name', size=64, required=True),
1580         'ref': fields.char('Ref', size=16),
1581         'model_id': fields.many2one('account.model', 'Model', required=True),
1582
1583         'date_start': fields.date('Start Date', required=True),
1584         'period_total': fields.integer('Number of Periods', required=True),
1585         'period_nbr': fields.integer('Period', required=True),
1586         'period_type': fields.selection([('day','days'),('month','month'),('year','year')], 'Period Type', required=True),
1587         'state': fields.selection([('draft','Draft'),('running','Running'),('done','Done')], 'Status', required=True, readonly=True),
1588
1589         'lines_id': fields.one2many('account.subscription.line', 'subscription_id', 'Subscription Lines')
1590     }
1591     _defaults = {
1592         'date_start': lambda *a: time.strftime('%Y-%m-%d'),
1593         'period_type': lambda *a: 'month',
1594         'period_total': lambda *a: 12,
1595         'period_nbr': lambda *a: 1,
1596         'state': lambda *a: 'draft',
1597     }
1598     def state_draft(self, cr, uid, ids, context={}):
1599         self.write(cr, uid, ids, {'state':'draft'})
1600         return False
1601
1602     def check(self, cr, uid, ids, context={}):
1603         todone = []
1604         for sub in self.browse(cr, uid, ids, context):
1605             ok = True
1606             for line in sub.lines_id:
1607                 if not line.move_id.id:
1608                     ok = False
1609                     break
1610             if ok:
1611                 todone.append(sub.id)
1612         if len(todone):
1613             self.write(cr, uid, todone, {'state':'done'})
1614         return False
1615
1616     def remove_line(self, cr, uid, ids, context={}):
1617         toremove = []
1618         for sub in self.browse(cr, uid, ids, context):
1619             for line in sub.lines_id:
1620                 if not line.move_id.id:
1621                     toremove.append(line.id)
1622         if len(toremove):
1623             self.pool.get('account.subscription.line').unlink(cr, uid, toremove)
1624         self.write(cr, uid, ids, {'state':'draft'})
1625         return False
1626
1627     def compute(self, cr, uid, ids, context={}):
1628         for sub in self.browse(cr, uid, ids, context):
1629             ds = sub.date_start
1630             for i in range(sub.period_total):
1631                 self.pool.get('account.subscription.line').create(cr, uid, {
1632                     'date': ds,
1633                     'subscription_id': sub.id,
1634                 })
1635                 if sub.period_type=='day':
1636                     ds = (mx.DateTime.strptime(ds, '%Y-%m-%d') + RelativeDateTime(days=sub.period_nbr)).strftime('%Y-%m-%d')
1637                 if sub.period_type=='month':
1638                     ds = (mx.DateTime.strptime(ds, '%Y-%m-%d') + RelativeDateTime(months=sub.period_nbr)).strftime('%Y-%m-%d')
1639                 if sub.period_type=='year':
1640                     ds = (mx.DateTime.strptime(ds, '%Y-%m-%d') + RelativeDateTime(years=sub.period_nbr)).strftime('%Y-%m-%d')
1641         self.write(cr, uid, ids, {'state':'running'})
1642         return True
1643 account_subscription()
1644
1645 class account_subscription_line(osv.osv):
1646     _name = "account.subscription.line"
1647     _description = "Account Subscription Line"
1648     _columns = {
1649         'subscription_id': fields.many2one('account.subscription', 'Subscription', required=True, select=True),
1650         'date': fields.date('Date', required=True),
1651         'move_id': fields.many2one('account.move', 'Entry'),
1652     }
1653     _defaults = {
1654     }
1655     def move_create(self, cr, uid, ids, context={}):
1656         tocheck = {}
1657         for line in self.browse(cr, uid, ids, context):
1658             datas = {
1659                 'date': line.date,
1660             }
1661             ids = self.pool.get('account.model').generate(cr, uid, [line.subscription_id.model_id.id], datas, context)
1662             tocheck[line.subscription_id.id] = True
1663             self.write(cr, uid, [line.id], {'move_id':ids[0]})
1664         if tocheck:
1665             self.pool.get('account.subscription').check(cr, uid, tocheck.keys(), context)
1666         return True
1667     _rec_name = 'date'
1668 account_subscription_line()
1669
1670
1671 class account_config_wizard(osv.osv_memory):
1672     _name = 'account.config.wizard'
1673
1674     def _get_charts(self, cr, uid, context):
1675         module_obj=self.pool.get('ir.module.module')
1676         ids=module_obj.search(cr, uid, [('category_id', '=', 'Account Charts'), ('state', '<>', 'installed')])
1677         res=[(m.id, m.shortdesc) for m in module_obj.browse(cr, uid, ids)]
1678         res.append((-1, 'None'))
1679         res.sort(key=lambda x: x[1])
1680         return res
1681
1682     _columns = {
1683         'name':fields.char('Name', required=True, size=64, help="Name of the fiscal year as displayed on screens."),
1684         'code':fields.char('Code', required=True, size=64, help="Name of the fiscal year as displayed in reports."),
1685         'date1': fields.date('Start Date', required=True),
1686         'date2': fields.date('End Date', required=True),
1687         'period':fields.selection([('month','Month'),('3months','3 Months')], 'Periods', required=True),
1688         'charts' : fields.selection(_get_charts, 'Charts of Account',required=True)
1689     }
1690     _defaults = {
1691         'code': lambda *a: time.strftime('%Y'),
1692         'name': lambda *a: time.strftime('%Y'),
1693         'date1': lambda *a: time.strftime('%Y-01-01'),
1694         'date2': lambda *a: time.strftime('%Y-12-31'),
1695         'period':lambda *a:'month',
1696     }
1697     def action_cancel(self,cr,uid,ids,conect=None):
1698         return {
1699                 'view_type': 'form',
1700                 "view_mode": 'form',
1701                 'res_model': 'ir.actions.configuration.wizard',
1702                 'type': 'ir.actions.act_window',
1703                 'target':'new',
1704         }
1705
1706     def install_account_chart(self, cr, uid, ids, context=None):
1707         for res in self.read(cr,uid,ids):
1708             chart_id = res['charts']
1709             if chart_id > 0:
1710                 mod_obj = self.pool.get('ir.module.module')
1711                 mod_obj.button_install(cr, uid, [chart_id], context=context)
1712         cr.commit()
1713         db, pool = pooler.restart_pool(cr.dbname, update_module=True)
1714
1715     def action_create(self, cr, uid,ids, context=None):
1716         for res in self.read(cr,uid,ids):
1717             if 'date1' in res and 'date2' in res:
1718                 res_obj = self.pool.get('account.fiscalyear')
1719                 start_date=res['date1']
1720                 end_date=res['date2']
1721                 name=res['name']#DateTime.strptime(start_date, '%Y-%m-%d').strftime('%m.%Y') + '-' + DateTime.strptime(end_date, '%Y-%m-%d').strftime('%m.%Y')
1722                 vals={
1723                     'name':name,
1724                     'code':name,
1725                     'date_start':start_date,
1726                     'date_stop':end_date,
1727                 }
1728                 new_id=res_obj.create(cr, uid, vals, context=context)
1729                 if res['period']=='month':
1730                     res_obj.create_period(cr,uid,[new_id])
1731                 elif res['period']=='3months':
1732                     res_obj.create_period3(cr,uid,[new_id])
1733         self.install_account_chart(cr,uid,ids)
1734         return {
1735                 'view_type': 'form',
1736                 "view_mode": 'form',
1737                 'res_model': 'ir.actions.configuration.wizard',
1738                 'type': 'ir.actions.act_window',
1739                 'target':'new',
1740         }
1741
1742
1743
1744 account_config_wizard()
1745
1746
1747 #  ---------------------------------------------------------------
1748 #   Account Templates : Account, Tax, Tax Code and chart. + Wizard
1749 #  ---------------------------------------------------------------
1750
1751 class account_tax_template(osv.osv):
1752     _name = 'account.tax.template'
1753 account_tax_template()
1754
1755 class account_account_template(osv.osv):
1756     _order = "code"
1757     _name = "account.account.template"
1758     _description ='Templates for Accounts'
1759
1760     _columns = {
1761         'name': fields.char('Name', size=128, required=True, select=True),
1762         'currency_id': fields.many2one('res.currency', 'Secondary Currency', help="Force all moves for this account to have this secondary currency."),
1763         'code': fields.char('Code', size=64),
1764         'type': fields.selection([
1765             ('receivable','Receivable'),
1766             ('payable','Payable'),
1767             ('view','View'),
1768             ('consolidation','Consolidation'),
1769             ('other','Others'),
1770             ('closed','Closed'),
1771             ], 'Internal Type', required=True,help="This type is used to differenciate types with "\
1772             "special effects in Open ERP: view can not have entries, consolidation are accounts that "\
1773             "can have children accounts for multi-company consolidations, payable/receivable are for "\
1774             "partners accounts (for debit/credit computations), closed for deprecated accounts."),
1775         'user_type': fields.many2one('account.account.type', 'Account Type', required=True,
1776             "These types are defined according to your country. The type contain more information "\
1777             "about the account and it's specificities."),
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'),
1784     }
1785
1786     _defaults = {
1787         'reconcile': lambda *a: False,
1788         'type' : lambda *a :'view',
1789     }
1790
1791     def _check_recursion(self, cr, uid, ids):
1792         level = 100
1793         while len(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()))
1796             if not level:
1797                 return False
1798             level -= 1
1799         return True
1800
1801     _constraints = [
1802         (_check_recursion, 'Error ! You can not create recursive account templates.', ['parent_id'])
1803     ]
1804
1805
1806     def name_get(self, cr, uid, ids, context={}):
1807         if not len(ids):
1808             return []
1809         reads = self.read(cr, uid, ids, ['name','code'], context)
1810         res = []
1811         for record in reads:
1812             name = record['name']
1813             if record['code']:
1814                 name = record['code']+' '+name
1815             res.append((record['id'],name ))
1816         return res
1817
1818 account_account_template()
1819
1820 class account_tax_code_template(osv.osv):
1821
1822     _name = 'account.tax.code.template'
1823     _description = 'Tax Code Template'
1824     _order = 'code'
1825     _rec_name = 'code'
1826     _columns = {
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"),
1834     }
1835
1836     _defaults = {
1837         'sign': lambda *args: 1.0,
1838         'notprintable': lambda *a: False,
1839     }
1840
1841     def name_get(self, cr, uid, ids, context=None):
1842         if not len(ids):
1843             return []
1844         if isinstance(ids, (int, long)):
1845             ids = [ids]
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']) \
1848                 for x in reads]
1849
1850     def _check_recursion(self, cr, uid, ids):
1851         level = 100
1852         while len(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()))
1855             if not level:
1856                 return False
1857             level -= 1
1858         return True
1859
1860     _constraints = [
1861         (_check_recursion, 'Error ! You can not create recursive Tax Codes.', ['parent_id'])
1862     ]
1863     _order = 'code,name'
1864 account_tax_code_template()
1865
1866
1867 class account_chart_template(osv.osv):
1868     _name="account.chart.template"
1869     _description= "Templates for Account Chart"
1870
1871     _columns={
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'),
1883     }
1884
1885 account_chart_template()
1886
1887 class account_tax_template(osv.osv):
1888
1889     _name = 'account.tax.template'
1890     _description = 'Templates for Taxes'
1891
1892     _columns = {
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."),
1908
1909         #
1910         # Fields used for the VAT declaration
1911         #
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."),
1916
1917         # Same fields for refund invoices
1918
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,)
1926     }
1927
1928     def name_get(self, cr, uid, ids, context={}):
1929         if not len(ids):
1930             return []
1931         res = []
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 ))
1935         return res
1936
1937     def _default_company(self, cr, uid, context={}):
1938         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
1939         if user.company_id:
1940             return user.company_id.id
1941         return self.pool.get('res.company').search(cr, uid, [('parent_id', '=', False)])[0]
1942
1943     _defaults = {
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',
1957     }
1958     _order = 'sequence'
1959
1960
1961 account_tax_template()
1962
1963 # Fiscal Position Templates
1964
1965 class account_fiscal_position_template(osv.osv):
1966     _name = 'account.fiscal.position.template'
1967     _description = 'Template for Fiscal Position'
1968
1969     _columns = {
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')
1974     }
1975
1976 account_fiscal_position_template()
1977
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'
1982
1983     _columns = {
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')
1987     }
1988
1989 account_fiscal_position_tax_template()
1990
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'
1995     _columns = {
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)
1999     }
2000
2001 account_fiscal_position_account_template()
2002
2003     # Multi charts of Accounts wizard
2004
2005 class wizard_multi_charts_accounts(osv.osv_memory):
2006     """
2007     Create a new account chart for a company.
2008     Wizards ask for:
2009         * 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
2013     Then, the wizard:
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
2017     """
2018     _name='wizard.multi.charts.accounts'
2019
2020     _columns = {
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."),
2026     }
2027
2028     def _get_chart(self, cr, uid, context={}):
2029         ids = self.pool.get('account.chart.template').search(cr, uid, [], context=context)
2030         if ids:
2031             return ids[0]
2032         return False
2033     _defaults = {
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,
2037     }
2038
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')
2048
2049         # Creating Account
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
2053
2054         #new code
2055         acc_template_ref = {}
2056         tax_template_ref = {}
2057         tax_code_template_ref = {}
2058         todo_dict = {}
2059
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):
2063             vals={
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,
2070             }
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
2074
2075         #create all the tax
2076         for tax in obj_multi.chart_template_id.tax_template_ids:
2077             #create it
2078             vals_tax = {
2079                 'name':tax.name,
2080                 'sequence': tax.sequence,
2081                 'amount':tax.amount,
2082                 'type':tax.type,
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
2103             }
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,
2109             }
2110             tax_template_ref[tax.id] = new_tax
2111
2112         #deactivate the parent_store functionnality on account_account for rapidity purpose
2113         self.pool._init = True
2114
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):
2118             tax_ids = []
2119             for tax in account_template.tax_ids:
2120                 tax_ids.append(tax_template_ref[tax.id])
2121             #create the account_account
2122
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)))
2128             vals={
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,
2132                 'code': code_acc,
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,
2141             }
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)
2147
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']],
2153                 })
2154
2155         # Creating Journals
2156         vals_journal={}
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]
2159
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]
2163         else:
2164             seq_id_sale = seq_id
2165             seq_id_purchase = seq_id
2166
2167         vals_journal['view_id'] = view_id
2168
2169         #Sales Journal
2170         vals_journal['name'] = _('Sales Journal')
2171         vals_journal['type'] = 'sale'
2172         vals_journal['code'] = _('SAJ')
2173         vals_journal['sequence_id'] = seq_id_sale
2174
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]
2178
2179         obj_journal.create(cr,uid,vals_journal)
2180
2181         # Purchase 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
2186
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]
2190
2191         obj_journal.create(cr,uid,vals_journal)
2192
2193         # Bank Journals
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
2197
2198         current_num = 1
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))
2206             vals = {
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,
2209                 'code': new_code,
2210                 'type': 'other',
2211                 'user_type': account_template.user_type and account_template.user_type.id or False,
2212                 'reconcile': True,
2213                 'parent_id': acc_template_ref[ref_acc_bank.id] or False,
2214                 'company_id': company_id,
2215             }
2216             acc_cash_id  = obj_acc.create(cr,uid,vals)
2217
2218             if obj_multi.seq_journal:
2219                 vals_seq={
2220                         'name': _('Bank Journal ') + vals['name'],
2221                         'code': 'account.journal',
2222                 }
2223                 seq_id = obj_sequence.create(cr,uid,vals_seq)
2224
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
2233             else:
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)
2238
2239             current_num += 1
2240
2241         #create the properties
2242         property_obj = self.pool.get('ir.property')
2243         fields_obj = self.pool.get('ir.model.fields')
2244
2245         todo_list = [
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')
2252         ]
2253         for record in todo_list:
2254             r = []
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])])
2258             vals = {
2259                 'name': record[0],
2260                 'company_id': company_id,
2261                 'fields_id': field[0],
2262                 'value': account and 'account.account,'+str(acc_template_ref[account.id]) or False,
2263             }
2264             if r:
2265                 #the property exist: modify it
2266                 property_obj.write(cr, uid, r, vals)
2267             else:
2268                 #create the property
2269                 property_obj.create(cr, uid, vals)
2270
2271         fp_ids = obj_fiscal_position_template.search(cr, uid,[('chart_template_id', '=', obj_multi.chart_template_id.id)])
2272
2273         if fp_ids:
2274             for position in obj_fiscal_position_template.browse(cr, uid, fp_ids):
2275
2276                 vals_fp = {
2277                            'company_id' : company_id,
2278                            'name' : position.name,
2279                            }
2280                 new_fp = obj_fiscal_position.create(cr, uid, vals_fp)
2281
2282                 obj_tax_fp = self.pool.get('account.fiscal.position.tax')
2283                 obj_ac_fp = self.pool.get('account.fiscal.position.account')
2284
2285                 for tax in position.tax_ids:
2286                     vals_tax = {
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,
2290                                 }
2291                     obj_tax_fp.create(cr, uid, vals_tax)
2292
2293                 for acc in position.account_ids:
2294                     vals_acc = {
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,
2298                                 }
2299                     obj_ac_fp.create(cr, uid, vals_acc)
2300
2301         return {
2302                 'view_type': 'form',
2303                 "view_mode": 'form',
2304                 'res_model': 'ir.actions.configuration.wizard',
2305                 'type': 'ir.actions.act_window',
2306                 'target':'new',
2307         }
2308     def action_cancel(self,cr,uid,ids,conect=None):
2309         return {
2310                 'view_type': 'form',
2311                 "view_mode": 'form',
2312                 'res_model': 'ir.actions.configuration.wizard',
2313                 'type': 'ir.actions.act_window',
2314                 'target':'new',
2315         }
2316
2317
2318 wizard_multi_charts_accounts()
2319
2320 class account_bank_accounts_wizard(osv.osv_memory):
2321     _name='account.bank.accounts.wizard'
2322
2323     _columns = {
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'),
2327     }
2328
2329 account_bank_accounts_wizard()
2330
2331 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
2332