dad8832bda7955c6560c71bc83be9f96d71f1098
[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['code'] = (account['code'] or '') + '(copy)'
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='char', size=32),
656         'active': fields.boolean('Active', required=True),
657         'state': fields.selection([('draft','Draft'), ('printed','Printed'), ('done','Done')], 'Status', required=True, readonly=True),
658         'fiscalyear_id': fields.related('period_id', 'fiscalyear_id', string='Fiscal Year', type='many2one', relation='account.fiscalyear'),
659     }
660
661     def _check(self, cr, uid, ids, context={}):
662         for obj in self.browse(cr, uid, ids, context):
663             cr.execute('select * from account_move_line where journal_id=%s and period_id=%s limit 1', (obj.journal_id.id, obj.period_id.id))
664             res = cr.fetchall()
665             if res:
666                 raise osv.except_osv(_('Error !'), _('You can not modify/delete a journal with entries for this period !'))
667         return True
668
669     def write(self, cr, uid, ids, vals, context={}):
670         self._check(cr, uid, ids, context)
671         return super(account_journal_period, self).write(cr, uid, ids, vals, context)
672
673     def create(self, cr, uid, vals, context={}):
674         period_id=vals.get('period_id',False)
675         if period_id:
676             period = self.pool.get('account.period').browse(cr, uid,period_id)
677             vals['state']=period.state
678         return super(account_journal_period, self).create(cr, uid, vals, context)
679
680     def unlink(self, cr, uid, ids, context={}):
681         self._check(cr, uid, ids, context)
682         return super(account_journal_period, self).unlink(cr, uid, ids, context)
683
684     _defaults = {
685         'state': lambda *a: 'draft',
686         'active': lambda *a: True,
687     }
688     _order = "period_id"
689
690 account_journal_period()
691
692 class account_fiscalyear(osv.osv):
693     _inherit = "account.fiscalyear"
694     _description = "Fiscal Year"
695     _columns = {
696         'end_journal_period_id':fields.many2one('account.journal.period','End of Year Entries Journal', readonly=True),
697     }
698
699 account_fiscalyear()
700 #----------------------------------------------------------
701 # Entries
702 #----------------------------------------------------------
703 class account_move(osv.osv):
704     _name = "account.move"
705     _description = "Account Entry"
706     _order = 'id desc'
707
708     def name_get(self, cursor, user, ids, context=None):
709         if not len(ids):
710             return []
711         res=[]
712         data_move = self.pool.get('account.move').browse(cursor,user,ids)
713         for move in data_move:
714             if move.state=='draft':
715                 name = '*' + str(move.id)
716             else:
717                 name = move.name
718             res.append((move.id, name))
719         return res
720
721
722     def _get_period(self, cr, uid, context):
723         periods = self.pool.get('account.period').find(cr, uid)
724         if periods:
725             return periods[0]
726         else:
727             return False
728
729     def _amount_compute(self, cr, uid, ids, name, args, context, where =''):
730         if not ids: return {}
731         cr.execute('select move_id,sum(debit) from account_move_line where move_id in ('+','.join(map(str,ids))+') group by move_id')
732         result = dict(cr.fetchall())
733         for id in ids:
734             result.setdefault(id, 0.0)
735         return result
736
737     _columns = {
738         'name': fields.char('Number', size=64, required=True),
739         'ref': fields.char('Ref', size=64),
740         'period_id': fields.many2one('account.period', 'Period', required=True, states={'posted':[('readonly',True)]}),
741         'journal_id': fields.many2one('account.journal', 'Journal', required=True, states={'posted':[('readonly',True)]}),
742         'state': fields.selection([('draft','Draft'), ('posted','Posted')], 'Status', required=True, readonly=True),
743         'line_id': fields.one2many('account.move.line', 'move_id', 'Entries', states={'posted':[('readonly',True)]}),
744         'to_check': fields.boolean('To Be Verified'),
745         'partner_id': fields.related('line_id', 'partner_id', type="many2one", relation="res.partner", string="Partner"),
746         'amount': fields.function(_amount_compute, method=True, string='Amount', digits=(16,2)),
747         'date': fields.date('Date', required=True),
748         'type': fields.selection([
749             ('pay_voucher','Cash Payment'),
750             ('bank_pay_voucher','Bank Payment'),
751             ('rec_voucher','Cash Receipt'),
752             ('bank_rec_voucher','Bank Receipt'),
753             ('cont_voucher','Contra'),
754             ('journal_sale_vou','Journal Sale'),
755             ('journal_pur_voucher','Journal Purchase'),
756             ('journal_voucher','Journal Voucher'),
757         ],'Type', readonly=True, select=True, states={'draft':[('readonly',False)]}),
758     }
759     _defaults = {
760         'name': lambda *a: '/',
761         'state': lambda *a: 'draft',
762         'period_id': _get_period,
763         'type' : lambda *a : 'journal_voucher',
764         'date': lambda *a:time.strftime('%Y-%m-%d'),
765     }
766
767     def _check_centralisation(self, cursor, user, ids):
768         for move in self.browse(cursor, user, ids):
769             if move.journal_id.centralisation:
770                 move_ids = self.search(cursor, user, [
771                     ('period_id', '=', move.period_id.id),
772                     ('journal_id', '=', move.journal_id.id),
773                     ])
774                 if len(move_ids) > 1:
775                     return False
776         return True
777
778     def _check_period_journal(self, cursor, user, ids):
779         for move in self.browse(cursor, user, ids):
780             for line in move.line_id:
781                 if line.period_id.id != move.period_id.id:
782                     return False
783                 if line.journal_id.id != move.journal_id.id:
784                     return False
785         return True
786
787     _constraints = [
788         (_check_centralisation,
789             'You cannot create more than one move per period on centralized journal',
790             ['journal_id']),
791         (_check_period_journal,
792             'You cannot create entries on different periods/journals in the same move',
793             ['line_id']),
794     ]
795     def post(self, cr, uid, ids, context=None):
796         if self.validate(cr, uid, ids, context) and len(ids):
797             for move in self.browse(cr, uid, ids):
798                 if move.name =='/':
799                     new_name = False
800                     journal = move.journal_id
801                     if journal.sequence_id:
802                         c = {'fiscalyear_id': move.period_id.fiscalyear_id.id}
803                         new_name = self.pool.get('ir.sequence').get_id(cr, uid, journal.sequence_id.id, context=c)
804                     else:
805                         raise osv.except_osv(_('Error'), _('No sequence defined in the journal !'))
806                     if new_name:
807                         self.write(cr, uid, [move.id], {'name':new_name})
808
809             cr.execute('update account_move set state=%s where id in ('+','.join(map(str,ids))+')', ('posted',))
810         else:
811             raise osv.except_osv(_('Integrity Error !'), _('You can not validate a non-balanced entry !'))
812         return True
813
814     def button_validate(self, cursor, user, ids, context=None):
815         return self.post(cursor, user, ids, context=context)
816
817     def button_cancel(self, cr, uid, ids, context={}):
818         for line in self.browse(cr, uid, ids, context):
819             if not line.journal_id.update_posted:
820                 raise osv.except_osv(_('Error !'), _('You can not modify a posted entry of this journal !\nYou should set the journal to allow cancelling entries if you want to do that.'))
821         if len(ids):
822             cr.execute('update account_move set state=%s where id in ('+','.join(map(str,ids))+')', ('draft',))
823         return True
824
825     def write(self, cr, uid, ids, vals, context={}):
826         c = context.copy()
827         c['novalidate'] = True
828         result = super(osv.osv, self).write(cr, uid, ids, vals, c)
829         self.validate(cr, uid, ids, context)
830         return result
831
832     #
833     # TODO: Check if period is closed !
834     #
835     def create(self, cr, uid, vals, context={}):
836         if 'line_id' in vals:
837             if 'journal_id' in vals:
838                 for l in vals['line_id']:
839                     if not l[0]:
840                         l[2]['journal_id'] = vals['journal_id']
841                 context['journal_id'] = vals['journal_id']
842             if 'period_id' in vals:
843                 for l in vals['line_id']:
844                     if not l[0]:
845                         l[2]['period_id'] = vals['period_id']
846                 context['period_id'] = vals['period_id']
847             else:
848                 default_period = self._get_period(cr, uid, context)
849                 for l in vals['line_id']:
850                     if not l[0]:
851                         l[2]['period_id'] = default_period
852                 context['period_id'] = default_period
853
854         accnt_journal = self.pool.get('account.journal').browse(cr, uid, vals['journal_id'])
855         if 'line_id' in vals:
856             c = context.copy()
857             c['novalidate'] = True
858             result = super(account_move, self).create(cr, uid, vals, c)
859             self.validate(cr, uid, [result], context)
860         else:
861             result = super(account_move, self).create(cr, uid, vals, context)
862         return result
863
864     def copy(self, cr, uid, id, default=None, context=None):
865         if default is None:
866             default = {}
867         default = default.copy()
868         default.update({'state':'draft', 'name':'/',})
869         return super(account_move, self).copy(cr, uid, id, default, context)
870
871     def unlink(self, cr, uid, ids, context={}, check=True):
872         toremove = []
873         for move in self.browse(cr, uid, ids, context):
874             if move['state'] != 'draft':
875                 raise osv.except_osv(_('UserError'),
876                         _('You can not delete posted movement: "%s"!') % \
877                                 move['name'])
878             line_ids = map(lambda x: x.id, move.line_id)
879             context['journal_id'] = move.journal_id.id
880             context['period_id'] = move.period_id.id
881             self.pool.get('account.move.line')._update_check(cr, uid, line_ids, context)
882             self.pool.get('account.move.line').unlink(cr, uid, line_ids, context=context)
883             toremove.append(move.id)
884         result = super(account_move, self).unlink(cr, uid, toremove, context)
885         return result
886
887     def _compute_balance(self, cr, uid, id, context={}):
888         move = self.browse(cr, uid, [id])[0]
889         amount = 0
890         for line in move.line_id:
891             amount+= (line.debit - line.credit)
892         return amount
893
894     def _centralise(self, cr, uid, move, mode):
895         if mode=='credit':
896             account_id = move.journal_id.default_debit_account_id.id
897             mode2 = 'debit'
898             if not account_id:
899                 raise osv.except_osv(_('UserError'),
900                         _('There is no default default debit account defined \n' \
901                                 'on journal "%s"') % move.journal_id.name)
902         else:
903             account_id = move.journal_id.default_credit_account_id.id
904             mode2 = 'credit'
905             if not account_id:
906                 raise osv.except_osv(_('UserError'),
907                         _('There is no default default credit account defined \n' \
908                                 'on journal "%s"') % move.journal_id.name)
909
910         # find the first line of this move with the current mode
911         # or create it if it doesn't exist
912         cr.execute('select id from account_move_line where move_id=%s and centralisation=%s limit 1', (move.id, mode))
913         res = cr.fetchone()
914         if res:
915             line_id = res[0]
916         else:
917             line_id = self.pool.get('account.move.line').create(cr, uid, {
918                 'name': 'Centralisation '+mode,
919                 'centralisation': mode,
920                 'account_id': account_id,
921                 'move_id': move.id,
922                 'journal_id': move.journal_id.id,
923                 'period_id': move.period_id.id,
924                 'date': move.period_id.date_stop,
925                 'debit': 0.0,
926                 'credit': 0.0,
927             }, {'journal_id': move.journal_id.id, 'period_id': move.period_id.id})
928
929         # find the first line of this move with the other mode
930         # so that we can exclude it from our calculation
931         cr.execute('select id from account_move_line where move_id=%s and centralisation=%s limit 1', (move.id, mode2))
932         res = cr.fetchone()
933         if res:
934             line_id2 = res[0]
935         else:
936             line_id2 = 0
937
938         cr.execute('select sum('+mode+') from account_move_line where move_id=%s and id<>%s', (move.id, line_id2))
939         result = cr.fetchone()[0] or 0.0
940         cr.execute('update account_move_line set '+mode2+'=%s where id=%s', (result, line_id))
941         return True
942
943     #
944     # Validate a balanced move. If it is a centralised journal, create a move.
945     #
946     def validate(self, cr, uid, ids, context={}):
947         if context and ('__last_update' in context):
948             del context['__last_update']
949         ok = True
950         for move in self.browse(cr, uid, ids, context):
951             #unlink analytic lines on move_lines
952             for obj_line in move.line_id:
953                 for obj in obj_line.analytic_lines:
954                     self.pool.get('account.analytic.line').unlink(cr,uid,obj.id)
955
956             journal = move.journal_id
957             amount = 0
958             line_ids = []
959             line_draft_ids = []
960             company_id=None
961             for line in move.line_id:
962                 amount += line.debit - line.credit
963                 line_ids.append(line.id)
964                 if line.state=='draft':
965                     line_draft_ids.append(line.id)
966
967                 if not company_id:
968                     company_id = line.account_id.company_id.id
969                 if not company_id == line.account_id.company_id.id:
970                     raise osv.except_osv(_('Error'), _("Couldn't create move between different companies"))
971
972                 if line.account_id.currency_id:
973                     if line.account_id.currency_id.id != line.currency_id.id and (line.account_id.currency_id.id != line.account_id.company_id.currency_id.id or line.currency_id):
974                         raise osv.except_osv(_('Error'), _("""Couldn't create move with currency different from the secondary currency of the account "%s - %s". Clear the secondary currency field of the account definition if you want to accept all currencies.""" % (line.account_id.code, line.account_id.name)))
975
976             if abs(amount) < 0.0001:
977                 if not len(line_draft_ids):
978                     continue
979                 self.pool.get('account.move.line').write(cr, uid, line_draft_ids, {
980                     'journal_id': move.journal_id.id,
981                     'period_id': move.period_id.id,
982                     'state': 'valid'
983                 }, context, check=False)
984                 todo = []
985                 account = {}
986                 account2 = {}
987                 if journal.type not in ('purchase','sale'):
988                     continue
989
990                 for line in move.line_id:
991                     code = amount = 0
992                     key = (line.account_id.id, line.tax_code_id.id)
993                     if key in account2:
994                         code = account2[key][0]
995                         amount = account2[key][1] * (line.debit + line.credit)
996                     elif line.account_id.id in account:
997                         code = account[line.account_id.id][0]
998                         amount = account[line.account_id.id][1] * (line.debit + line.credit)
999                     if (code or amount) and not (line.tax_code_id or line.tax_amount):
1000                         self.pool.get('account.move.line').write(cr, uid, [line.id], {
1001                             'tax_code_id': code,
1002                             'tax_amount': amount
1003                         }, context, check=False)
1004                 #
1005                 # Compute VAT
1006                 #
1007                 continue
1008             if journal.centralisation:
1009                 self._centralise(cr, uid, move, 'debit')
1010                 self._centralise(cr, uid, move, 'credit')
1011                 self.pool.get('account.move.line').write(cr, uid, line_draft_ids, {
1012                     'state': 'valid'
1013                 }, context, check=False)
1014                 continue
1015             else:
1016                 self.pool.get('account.move.line').write(cr, uid, line_ids, {
1017                     'journal_id': move.journal_id.id,
1018                     'period_id': move.period_id.id,
1019                     #'tax_code_id': False,
1020                     #'tax_amount': False,
1021                     'state': 'draft'
1022                 }, context, check=False)
1023                 ok = False
1024         if ok:
1025             list_ids = []
1026             for tmp in move.line_id:
1027                 list_ids.append(tmp.id)
1028             self.pool.get('account.move.line').create_analytic_lines(cr, uid, list_ids, context)
1029         return ok
1030 account_move()
1031
1032 class account_move_reconcile(osv.osv):
1033     _name = "account.move.reconcile"
1034     _description = "Account Reconciliation"
1035     _columns = {
1036         'name': fields.char('Name', size=64, required=True),
1037         'type': fields.char('Type', size=16, required=True),
1038         'line_id': fields.one2many('account.move.line', 'reconcile_id', 'Entry Lines'),
1039         'line_partial_ids': fields.one2many('account.move.line', 'reconcile_partial_id', 'Partial Entry lines'),
1040         'create_date': fields.date('Creation date', readonly=True),
1041     }
1042     _defaults = {
1043         'name': lambda self,cr,uid,ctx={}: self.pool.get('ir.sequence').get(cr, uid, 'account.reconcile') or '/',
1044     }
1045     def reconcile_partial_check(self, cr, uid, ids, type='auto', context={}):
1046         for rec in self.browse(cr, uid, ids, context):
1047             total = 0.0
1048             for line in rec.line_partial_ids:
1049                 total += (line.debit or 0.0) - (line.credit or 0.0)
1050         if not total:
1051             self.pool.get('account.move.line').write(cr, uid,
1052                 map(lambda x: x.id, rec.line_partial_ids),
1053                 {'reconcile_id': rec.id }
1054             )
1055         return True
1056
1057     def name_get(self, cr, uid, ids, context=None):
1058         if not len(ids):
1059             return []
1060         result = []
1061         for r in self.browse(cr, uid, ids, context):
1062             total = reduce(lambda y,t: (t.debit or 0.0) - (t.credit or 0.0) + y, r.line_partial_ids, 0.0)
1063             if total:
1064                 name = '%s (%.2f)' % (r.name, total)
1065                 result.append((r.id,name))
1066             else:
1067                 result.append((r.id,r.name))
1068         return result
1069
1070
1071 account_move_reconcile()
1072
1073 #----------------------------------------------------------
1074 # Tax
1075 #----------------------------------------------------------
1076 """
1077 a documenter
1078 child_depend: la taxe depend des taxes filles
1079 """
1080 class account_tax_code(osv.osv):
1081     """
1082     A code for the tax object.
1083
1084     This code is used for some tax declarations.
1085     """
1086     def _sum(self, cr, uid, ids, name, args, context, where =''):
1087         ids2 = self.search(cr, uid, [('parent_id', 'child_of', ids)])
1088         acc_set = ",".join(map(str, ids2))
1089         if context.get('based_on', 'invoices') == 'payments':
1090             cr.execute('SELECT line.tax_code_id, sum(line.tax_amount) \
1091                     FROM account_move_line AS line, \
1092                         account_move AS move \
1093                         LEFT JOIN account_invoice invoice ON \
1094                             (invoice.move_id = move.id) \
1095                     WHERE line.tax_code_id in ('+acc_set+') '+where+' \
1096                         AND move.id = line.move_id \
1097                         AND ((invoice.state = \'paid\') \
1098                             OR (invoice.id IS NULL)) \
1099                     GROUP BY line.tax_code_id')
1100         else:
1101             cr.execute('SELECT line.tax_code_id, sum(line.tax_amount) \
1102                     FROM account_move_line AS line \
1103                     WHERE line.tax_code_id in ('+acc_set+') '+where+' \
1104                     GROUP BY line.tax_code_id')
1105         res=dict(cr.fetchall())
1106         for record in self.browse(cr, uid, ids, context):
1107             def _rec_get(record):
1108                 amount = res.get(record.id, 0.0)
1109                 for rec in record.child_ids:
1110                     amount += _rec_get(rec) * rec.sign
1111                 return amount
1112             res[record.id] = round(_rec_get(record), 2)
1113         return res
1114
1115     def _sum_year(self, cr, uid, ids, name, args, context):
1116         if 'fiscalyear_id' in context and context['fiscalyear_id']:
1117             fiscalyear_id = context['fiscalyear_id']
1118         else:
1119             fiscalyear_id = self.pool.get('account.fiscalyear').find(cr, uid, exception=False)
1120         where = ''
1121         if fiscalyear_id:
1122             pids = map(lambda x: str(x.id), self.pool.get('account.fiscalyear').browse(cr, uid, fiscalyear_id).period_ids)
1123             if pids:
1124                 where = ' and period_id in (' + (','.join(pids))+')'
1125         return self._sum(cr, uid, ids, name, args, context,
1126                 where=where)
1127
1128     def _sum_period(self, cr, uid, ids, name, args, context):
1129         if 'period_id' in context and context['period_id']:
1130             period_id = context['period_id']
1131         else:
1132             period_id = self.pool.get('account.period').find(cr, uid)
1133             if not len(period_id):
1134                 return dict.fromkeys(ids, 0.0)
1135             period_id = period_id[0]
1136         return self._sum(cr, uid, ids, name, args, context,
1137                 where=' and line.period_id='+str(period_id))
1138
1139     _name = 'account.tax.code'
1140     _description = 'Tax Code'
1141     _rec_name = 'code'
1142     _columns = {
1143         'name': fields.char('Tax Case Name', size=64, required=True),
1144         'code': fields.char('Case Code', size=64),
1145         'info': fields.text('Description'),
1146         'sum': fields.function(_sum_year, method=True, string="Year Sum"),
1147         'sum_period': fields.function(_sum_period, method=True, string="Period Sum"),
1148         'parent_id': fields.many2one('account.tax.code', 'Parent Code', select=True),
1149         'child_ids': fields.one2many('account.tax.code', 'parent_id', 'Child Codes'),
1150         'line_ids': fields.one2many('account.move.line', 'tax_code_id', 'Lines'),
1151         'company_id': fields.many2one('res.company', 'Company', required=True),
1152         'sign': fields.float('Sign for parent', required=True),
1153         'notprintable':fields.boolean("Not Printable in Invoice", help="Check this box if you don't want any VAT related to this Tax Code to appear on invoices"),
1154     }
1155
1156
1157     def name_get(self, cr, uid, ids, context=None):
1158         if not len(ids):
1159             return []
1160         if isinstance(ids, (int, long)):
1161             ids = [ids]
1162         reads = self.read(cr, uid, ids, ['name','code'], context, load='_classic_write')
1163         return [(x['id'], (x['code'] and x['code'] + ' - ' or '') + x['name']) \
1164                 for x in reads]
1165
1166     def _default_company(self, cr, uid, context={}):
1167         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
1168         if user.company_id:
1169             return user.company_id.id
1170         return self.pool.get('res.company').search(cr, uid, [('parent_id', '=', False)])[0]
1171     _defaults = {
1172         'company_id': _default_company,
1173         'sign': lambda *args: 1.0,
1174         'notprintable': lambda *a: False,
1175     }
1176     def _check_recursion(self, cr, uid, ids):
1177         level = 100
1178         while len(ids):
1179             cr.execute('select distinct parent_id from account_tax_code where id in ('+','.join(map(str,ids))+')')
1180             ids = filter(None, map(lambda x:x[0], cr.fetchall()))
1181             if not level:
1182                 return False
1183             level -= 1
1184         return True
1185
1186     _constraints = [
1187         (_check_recursion, 'Error ! You can not create recursive accounts.', ['parent_id'])
1188     ]
1189     _order = 'code,name'
1190 account_tax_code()
1191
1192 class account_tax(osv.osv):
1193     """
1194     A tax object.
1195
1196     Type: percent, fixed, none, code
1197         PERCENT: tax = price * amount
1198         FIXED: tax = price + amount
1199         NONE: no tax line
1200         CODE: execute python code. localcontext = {'price_unit':pu, 'address':address_object}
1201             return result in the context
1202             Ex: result=round(price_unit*0.21,4)
1203     """
1204     _name = 'account.tax'
1205     _description = 'Tax'
1206     _columns = {
1207         'name': fields.char('Tax Name', size=64, required=True, translate=True, help="This name will be displayed on reports"),
1208         'sequence': fields.integer('Sequence', required=True, help="The sequence field is used to order the tax lines from the lowest sequences to the higher ones. The order is important if you have a tax with several tax children. In this case, the evaluation order is important."),
1209         'amount': fields.float('Amount', required=True, digits=(14,4)),
1210         'active': fields.boolean('Active'),
1211         'type': fields.selection( [('percent','Percent'), ('fixed','Fixed'), ('none','None'), ('code','Python Code'),('balance','Balance')], 'Tax Type', required=True,
1212             help="The computation method for the tax amount."),
1213         'applicable_type': fields.selection( [('true','True'), ('code','Python Code')], 'Applicable Type', required=True,
1214             help="If not applicable (computed through a Python code), the tax won't appear on the invoice."),
1215         'domain':fields.char('Domain', size=32, help="This field is only used if you develop your own module allowing developers to create specific taxes in a custom domain."),
1216         'account_collected_id':fields.many2one('account.account', 'Invoice Tax Account'),
1217         'account_paid_id':fields.many2one('account.account', 'Refund Tax Account'),
1218         'parent_id':fields.many2one('account.tax', 'Parent Tax Account', select=True),
1219         'child_ids':fields.one2many('account.tax', 'parent_id', 'Child Tax Accounts'),
1220         'child_depend':fields.boolean('Tax on Children', help="Set if the tax computation is based on the computation of child taxes rather than on the total amount."),
1221         'python_compute':fields.text('Python Code'),
1222         'python_compute_inv':fields.text('Python Code (reverse)'),
1223         'python_applicable':fields.text('Python Code'),
1224         'tax_group': fields.selection([('vat','VAT'),('other','Other')], 'Tax Group', help="If a default tax is given in the partner it only overrides taxes from accounts (or products) in the same group."),
1225
1226         #
1227         # Fields used for the VAT declaration
1228         #
1229         'base_code_id': fields.many2one('account.tax.code', 'Base Code', help="Use this code for the VAT declaration."),
1230         'tax_code_id': fields.many2one('account.tax.code', 'Tax Code', help="Use this code for the VAT declaration."),
1231         'base_sign': fields.float('Base Code Sign', help="Usually 1 or -1."),
1232         'tax_sign': fields.float('Tax Code Sign', help="Usually 1 or -1."),
1233
1234         # Same fields for refund invoices
1235
1236         'ref_base_code_id': fields.many2one('account.tax.code', 'Refund Base Code', help="Use this code for the VAT declaration."),
1237         'ref_tax_code_id': fields.many2one('account.tax.code', 'Refund Tax Code', help="Use this code for the VAT declaration."),
1238         'ref_base_sign': fields.float('Base Code Sign', help="Usually 1 or -1."),
1239         'ref_tax_sign': fields.float('Tax Code Sign', help="Usually 1 or -1."),
1240         'include_base_amount': fields.boolean('Include in base amount', help="Indicate if the amount of tax must be included in the base amount for the computation of the next taxes"),
1241         'company_id': fields.many2one('res.company', 'Company', required=True),
1242         'description': fields.char('Tax Code',size=32),
1243         'price_include': fields.boolean('Tax Included in Price', help="Check this if the price you use on the product and invoices includes this tax."),
1244         'type_tax_use': fields.selection([('sale','Sale'),('purchase','Purchase'),('all','All')], 'Tax Application', required=True)
1245
1246     }
1247     def search(self, cr, uid, args, offset=0, limit=None, order=None,
1248             context=None, count=False):
1249         if context and context.has_key('type'):
1250             if context['type'] in ('out_invoice','out_refund'):
1251                 args.append(('type_tax_use','in',['sale','all']))
1252             elif context['type'] in ('in_invoice','in_refund'):
1253                 args.append(('type_tax_use','in',['purchase','all']))
1254         return super(account_tax, self).search(cr, uid, args, offset, limit, order, context, count)
1255
1256     def name_get(self, cr, uid, ids, context={}):
1257         if not len(ids):
1258             return []
1259         res = []
1260         for record in self.read(cr, uid, ids, ['description','name'], context):
1261             name = record['description'] and record['description'] or record['name']
1262             res.append((record['id'],name ))
1263         return res
1264
1265     def _default_company(self, cr, uid, context={}):
1266         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
1267         if user.company_id:
1268             return user.company_id.id
1269         return self.pool.get('res.company').search(cr, uid, [('parent_id', '=', False)])[0]
1270     _defaults = {
1271         'python_compute': lambda *a: '''# price_unit\n# address : res.partner.address object or False\n# product : product.product object or None\n# partner : res.partner object or None\n\nresult = price_unit * 0.10''',
1272         'python_compute_inv': lambda *a: '''# price_unit\n# address : res.partner.address object or False\n# product : product.product object or False\n\nresult = price_unit * 0.10''',
1273         'applicable_type': lambda *a: 'true',
1274         'type': lambda *a: 'percent',
1275         'amount': lambda *a: 0,
1276         'price_include': lambda *a: 0,
1277         'active': lambda *a: 1,
1278         'type_tax_use': lambda *a: 'all',
1279         'sequence': lambda *a: 1,
1280         'tax_group': lambda *a: 'vat',
1281         'ref_tax_sign': lambda *a: 1,
1282         'ref_base_sign': lambda *a: 1,
1283         'tax_sign': lambda *a: 1,
1284         'base_sign': lambda *a: 1,
1285         'include_base_amount': lambda *a: False,
1286         'company_id': _default_company,
1287     }
1288     _order = 'sequence'
1289
1290     def _applicable(self, cr, uid, taxes, price_unit, address_id=None, product=None, partner=None):
1291         res = []
1292         for tax in taxes:
1293             if tax.applicable_type=='code':
1294                 localdict = {'price_unit':price_unit, 'address':self.pool.get('res.partner.address').browse(cr, uid, address_id), 'product':product, 'partner':partner}
1295                 exec tax.python_applicable in localdict
1296                 if localdict.get('result', False):
1297                     res.append(tax)
1298             else:
1299                 res.append(tax)
1300         return res
1301
1302     def _unit_compute(self, cr, uid, taxes, price_unit, address_id=None, product=None, partner=None, quantity=0):
1303         taxes = self._applicable(cr, uid, taxes, price_unit, address_id, product, partner)
1304
1305         res = []
1306         cur_price_unit=price_unit
1307         for tax in taxes:
1308             # we compute the amount for the current tax object and append it to the result
1309
1310             data = {'id':tax.id,
1311                             'name':tax.name,
1312                             'account_collected_id':tax.account_collected_id.id,
1313                             'account_paid_id':tax.account_paid_id.id,
1314                             'base_code_id': tax.base_code_id.id,
1315                             'ref_base_code_id': tax.ref_base_code_id.id,
1316                             'sequence': tax.sequence,
1317                             'base_sign': tax.base_sign,
1318                             'tax_sign': tax.tax_sign,
1319                             'ref_base_sign': tax.ref_base_sign,
1320                             'ref_tax_sign': tax.ref_tax_sign,
1321                             'price_unit': cur_price_unit,
1322                             'tax_code_id': tax.tax_code_id.id,
1323                             'ref_tax_code_id': tax.ref_tax_code_id.id,
1324             }
1325             res.append(data)
1326             if tax.type=='percent':
1327                 amount = cur_price_unit * tax.amount
1328                 data['amount'] = amount
1329
1330             elif tax.type=='fixed':
1331                 data['amount'] = tax.amount
1332                 data['tax_amount']=quantity
1333                # data['amount'] = quantity
1334             elif tax.type=='code':
1335                 address = address_id and self.pool.get('res.partner.address').browse(cr, uid, address_id) or None
1336                 localdict = {'price_unit':cur_price_unit, 'address':address, 'product':product, 'partner':partner}
1337                 exec tax.python_compute in localdict
1338                 amount = localdict['result']
1339                 data['amount'] = amount
1340             elif tax.type=='balance':
1341                 data['amount'] = cur_price_unit - reduce(lambda x,y: y.get('amount',0.0)+x, res, 0.0)
1342                 data['balance'] = cur_price_unit
1343
1344             amount2 = data['amount']
1345             if len(tax.child_ids):
1346                 if tax.child_depend:
1347                     latest = res.pop()
1348                 amount = amount2
1349                 child_tax = self._unit_compute(cr, uid, tax.child_ids, amount, address_id, product, partner, quantity)
1350                 res.extend(child_tax)
1351                 if tax.child_depend:
1352                     for r in res:
1353                         for name in ('base','ref_base'):
1354                             if latest[name+'_code_id'] and latest[name+'_sign'] and not r[name+'_code_id']:
1355                                 r[name+'_code_id'] = latest[name+'_code_id']
1356                                 r[name+'_sign'] = latest[name+'_sign']
1357                                 r['price_unit'] = latest['price_unit']
1358                                 latest[name+'_code_id'] = False
1359                         for name in ('tax','ref_tax'):
1360                             if latest[name+'_code_id'] and latest[name+'_sign'] and not r[name+'_code_id']:
1361                                 r[name+'_code_id'] = latest[name+'_code_id']
1362                                 r[name+'_sign'] = latest[name+'_sign']
1363                                 r['amount'] = data['amount']
1364                                 latest[name+'_code_id'] = False
1365             if tax.include_base_amount:
1366                 cur_price_unit+=amount2
1367         return res
1368
1369     def compute(self, cr, uid, taxes, price_unit, quantity, address_id=None, product=None, partner=None):
1370
1371         """
1372         Compute tax values for given PRICE_UNIT, QUANTITY and a buyer/seller ADDRESS_ID.
1373
1374         RETURN:
1375             [ tax ]
1376             tax = {'name':'', 'amount':0.0, 'account_collected_id':1, 'account_paid_id':2}
1377             one tax for each tax id in IDS and their childs
1378         """
1379         res = self._unit_compute(cr, uid, taxes, price_unit, address_id, product, partner, quantity)
1380         total = 0.0
1381         for r in res:
1382             if r.get('balance',False):
1383                 r['amount'] = round(r['balance'] * quantity, 2) - total
1384             else:
1385                 r['amount'] = round(r['amount'] * quantity, 2)
1386                 total += r['amount']
1387
1388         return res
1389
1390     def _unit_compute_inv(self, cr, uid, taxes, price_unit, address_id=None, product=None, partner=None):
1391         taxes = self._applicable(cr, uid, taxes, price_unit, address_id, product, partner)
1392
1393         res = []
1394         taxes.reverse()
1395         cur_price_unit = price_unit
1396
1397         tax_parent_tot = 0.0
1398         for tax in taxes:
1399             if (tax.type=='percent') and not tax.include_base_amount:
1400                 tax_parent_tot += tax.amount
1401                 
1402         for tax in taxes:
1403             if (tax.type=='fixed') and not tax.include_base_amount:
1404                 cur_price_unit -= tax.amount
1405                 
1406         for tax in taxes:
1407             if tax.type=='percent':
1408                 if tax.include_base_amount:
1409                     amount = cur_price_unit - (cur_price_unit / (1 + tax.amount))
1410                 else:
1411                     amount = (cur_price_unit / (1 + tax_parent_tot)) * tax.amount
1412
1413             elif tax.type=='fixed':
1414                 amount = tax.amount
1415
1416             elif tax.type=='code':
1417                 address = address_id and self.pool.get('res.partner.address').browse(cr, uid, address_id) or None
1418                 localdict = {'price_unit':cur_price_unit, 'address':address, 'product':product, 'partner':partner}
1419                 exec tax.python_compute_inv in localdict
1420                 amount = localdict['result']
1421             elif tax.type=='balance':
1422                 data['amount'] = cur_price_unit - reduce(lambda x,y: y.get('amount',0.0)+x, res, 0.0)
1423                 data['balance'] = cur_price_unit
1424
1425
1426             if tax.include_base_amount:
1427                 cur_price_unit -= amount
1428                 todo = 0
1429             else:
1430                 todo = 1
1431             res.append({
1432                 'id': tax.id,
1433                 'todo': todo,
1434                 'name': tax.name,
1435                 'amount': amount,
1436                 'account_collected_id': tax.account_collected_id.id,
1437                 'account_paid_id': tax.account_paid_id.id,
1438                 'base_code_id': tax.base_code_id.id,
1439                 'ref_base_code_id': tax.ref_base_code_id.id,
1440                 'sequence': tax.sequence,
1441                 'base_sign': tax.base_sign,
1442                 'tax_sign': tax.tax_sign,
1443                 'ref_base_sign': tax.ref_base_sign,
1444                 'ref_tax_sign': tax.ref_tax_sign,
1445                 'price_unit': cur_price_unit,
1446                 'tax_code_id': tax.tax_code_id.id,
1447                 'ref_tax_code_id': tax.ref_tax_code_id.id,
1448             })
1449             if len(tax.child_ids):
1450                 if tax.child_depend:
1451                     del res[-1]
1452                     amount = price_unit
1453
1454             parent_tax = self._unit_compute_inv(cr, uid, tax.child_ids, amount, address_id, product, partner)
1455             res.extend(parent_tax)
1456
1457         total = 0.0
1458         for r in res:
1459             if r['todo']:
1460                 total += r['amount']
1461         for r in res:
1462             r['price_unit'] -= total
1463             r['todo'] = 0
1464         return res
1465
1466     def compute_inv(self, cr, uid, taxes, price_unit, quantity, address_id=None, product=None, partner=None):
1467         """
1468         Compute tax values for given PRICE_UNIT, QUANTITY and a buyer/seller ADDRESS_ID.
1469         Price Unit is a VAT included price
1470
1471         RETURN:
1472             [ tax ]
1473             tax = {'name':'', 'amount':0.0, 'account_collected_id':1, 'account_paid_id':2}
1474             one tax for each tax id in IDS and their childs
1475         """
1476         res = self._unit_compute_inv(cr, uid, taxes, price_unit, address_id, product, partner=None)
1477         total = 0.0
1478         for r in res:
1479             if r.get('balance',False):
1480                 r['amount'] = round(r['balance'] * quantity, 2) - total
1481             else:
1482                 r['amount'] = round(r['amount'] * quantity, 2)
1483                 total += r['amount']
1484         return res
1485 account_tax()
1486
1487 # ---------------------------------------------------------
1488 # Account Entries Models
1489 # ---------------------------------------------------------
1490
1491 class account_model(osv.osv):
1492     _name = "account.model"
1493     _description = "Account Model"
1494     _columns = {
1495         'name': fields.char('Model Name', size=64, required=True, help="This is a model for recurring accounting entries"),
1496         'ref': fields.char('Ref', size=64),
1497         'journal_id': fields.many2one('account.journal', 'Journal', required=True),
1498         'lines_id': fields.one2many('account.model.line', 'model_id', 'Model Entries'),
1499         'legend' :fields.text('Legend',readonly=True,size=100),
1500     }
1501
1502     _defaults = {
1503         'legend': lambda self, cr, uid, context:_('You can specify year, month and date in the name of the model using the following labels:\n\n%(year)s : To Specify Year \n%(month)s : To Specify Month \n%(date)s : Current Date\n\ne.g. My model on %(date)s'),
1504     }
1505     def generate(self, cr, uid, ids, datas={}, context={}):
1506         move_ids = []
1507         for model in self.browse(cr, uid, ids, context):
1508             period_id = self.pool.get('account.period').find(cr,uid, context=context)
1509             if not period_id:
1510                 raise osv.except_osv(_('No period found !'), _('Unable to find a valid period !'))
1511             period_id = period_id[0]
1512             move_id = self.pool.get('account.move').create(cr, uid, {
1513                 'ref': model.ref,
1514                 'period_id': period_id,
1515                 'journal_id': model.journal_id.id,
1516             })
1517             move_ids.append(move_id)
1518             for line in model.lines_id:
1519                 val = {
1520                     'move_id': move_id,
1521                     'journal_id': model.journal_id.id,
1522                     'period_id': period_id
1523                 }
1524                 val.update({
1525                     'name': line.name,
1526                     'quantity': line.quantity,
1527                     'debit': line.debit,
1528                     'credit': line.credit,
1529                     'account_id': line.account_id.id,
1530                     'move_id': move_id,
1531                     'ref': line.ref,
1532                     'partner_id': line.partner_id.id,
1533                     'date': time.strftime('%Y-%m-%d'),
1534                     'date_maturity': time.strftime('%Y-%m-%d')
1535                 })
1536                 c = context.copy()
1537                 c.update({'journal_id': model.journal_id.id,'period_id': period_id})
1538                 self.pool.get('account.move.line').create(cr, uid, val, context=c)
1539         return move_ids
1540 account_model()
1541
1542 class account_model_line(osv.osv):
1543     _name = "account.model.line"
1544     _description = "Account Model Entries"
1545     _columns = {
1546         'name': fields.char('Name', size=64, required=True),
1547         'sequence': fields.integer('Sequence', required=True, help="The sequence field is used to order the resources from lower sequences to higher ones"),
1548         'quantity': fields.float('Quantity', digits=(16,2), help="The optional quantity on entries"),
1549         'debit': fields.float('Debit', digits=(16,2)),
1550         'credit': fields.float('Credit', digits=(16,2)),
1551
1552         'account_id': fields.many2one('account.account', 'Account', required=True, ondelete="cascade"),
1553
1554         'model_id': fields.many2one('account.model', 'Model', required=True, ondelete="cascade", select=True),
1555
1556         'ref': fields.char('Ref.', size=16),
1557
1558         'amount_currency': fields.float('Amount Currency', help="The amount expressed in an optional other currency."),
1559         'currency_id': fields.many2one('res.currency', 'Currency'),
1560
1561         'partner_id': fields.many2one('res.partner', 'Partner Ref.'),
1562         'date_maturity': fields.selection([('today','Date of the day'), ('partner','Partner Payment Term')], 'Maturity date', help="The maturity date of the generated entries for this model. You can chosse between the date of the creation action or the the date of the creation of the entries plus the partner payment terms."),
1563         'date': fields.selection([('today','Date of the day'), ('partner','Partner Payment Term')], 'Current Date', required=True, help="The date of the generated entries"),
1564     }
1565     _defaults = {
1566         'date': lambda *a: 'today'
1567     }
1568     _order = 'sequence'
1569     _sql_constraints = [
1570         ('credit_debit1', 'CHECK (credit*debit=0)',  'Wrong credit or debit value in model !'),
1571         ('credit_debit2', 'CHECK (credit+debit>=0)', 'Wrong credit or debit value in model !'),
1572     ]
1573 account_model_line()
1574
1575 # ---------------------------------------------------------
1576 # Account Subscription
1577 # ---------------------------------------------------------
1578
1579
1580 class account_subscription(osv.osv):
1581     _name = "account.subscription"
1582     _description = "Account Subscription"
1583     _columns = {
1584         'name': fields.char('Name', size=64, required=True),
1585         'ref': fields.char('Ref', size=16),
1586         'model_id': fields.many2one('account.model', 'Model', required=True),
1587
1588         'date_start': fields.date('Start Date', required=True),
1589         'period_total': fields.integer('Number of Periods', required=True),
1590         'period_nbr': fields.integer('Period', required=True),
1591         'period_type': fields.selection([('day','days'),('month','month'),('year','year')], 'Period Type', required=True),
1592         'state': fields.selection([('draft','Draft'),('running','Running'),('done','Done')], 'Status', required=True, readonly=True),
1593
1594         'lines_id': fields.one2many('account.subscription.line', 'subscription_id', 'Subscription Lines')
1595     }
1596     _defaults = {
1597         'date_start': lambda *a: time.strftime('%Y-%m-%d'),
1598         'period_type': lambda *a: 'month',
1599         'period_total': lambda *a: 12,
1600         'period_nbr': lambda *a: 1,
1601         'state': lambda *a: 'draft',
1602     }
1603     def state_draft(self, cr, uid, ids, context={}):
1604         self.write(cr, uid, ids, {'state':'draft'})
1605         return False
1606
1607     def check(self, cr, uid, ids, context={}):
1608         todone = []
1609         for sub in self.browse(cr, uid, ids, context):
1610             ok = True
1611             for line in sub.lines_id:
1612                 if not line.move_id.id:
1613                     ok = False
1614                     break
1615             if ok:
1616                 todone.append(sub.id)
1617         if len(todone):
1618             self.write(cr, uid, todone, {'state':'done'})
1619         return False
1620
1621     def remove_line(self, cr, uid, ids, context={}):
1622         toremove = []
1623         for sub in self.browse(cr, uid, ids, context):
1624             for line in sub.lines_id:
1625                 if not line.move_id.id:
1626                     toremove.append(line.id)
1627         if len(toremove):
1628             self.pool.get('account.subscription.line').unlink(cr, uid, toremove)
1629         self.write(cr, uid, ids, {'state':'draft'})
1630         return False
1631
1632     def compute(self, cr, uid, ids, context={}):
1633         for sub in self.browse(cr, uid, ids, context):
1634             ds = sub.date_start
1635             for i in range(sub.period_total):
1636                 self.pool.get('account.subscription.line').create(cr, uid, {
1637                     'date': ds,
1638                     'subscription_id': sub.id,
1639                 })
1640                 if sub.period_type=='day':
1641                     ds = (mx.DateTime.strptime(ds, '%Y-%m-%d') + RelativeDateTime(days=sub.period_nbr)).strftime('%Y-%m-%d')
1642                 if sub.period_type=='month':
1643                     ds = (mx.DateTime.strptime(ds, '%Y-%m-%d') + RelativeDateTime(months=sub.period_nbr)).strftime('%Y-%m-%d')
1644                 if sub.period_type=='year':
1645                     ds = (mx.DateTime.strptime(ds, '%Y-%m-%d') + RelativeDateTime(years=sub.period_nbr)).strftime('%Y-%m-%d')
1646         self.write(cr, uid, ids, {'state':'running'})
1647         return True
1648 account_subscription()
1649
1650 class account_subscription_line(osv.osv):
1651     _name = "account.subscription.line"
1652     _description = "Account Subscription Line"
1653     _columns = {
1654         'subscription_id': fields.many2one('account.subscription', 'Subscription', required=True, select=True),
1655         'date': fields.date('Date', required=True),
1656         'move_id': fields.many2one('account.move', 'Entry'),
1657     }
1658     _defaults = {
1659     }
1660     def move_create(self, cr, uid, ids, context={}):
1661         tocheck = {}
1662         for line in self.browse(cr, uid, ids, context):
1663             datas = {
1664                 'date': line.date,
1665             }
1666             ids = self.pool.get('account.model').generate(cr, uid, [line.subscription_id.model_id.id], datas, context)
1667             tocheck[line.subscription_id.id] = True
1668             self.write(cr, uid, [line.id], {'move_id':ids[0]})
1669         if tocheck:
1670             self.pool.get('account.subscription').check(cr, uid, tocheck.keys(), context)
1671         return True
1672     _rec_name = 'date'
1673 account_subscription_line()
1674
1675
1676 class account_config_wizard(osv.osv_memory):
1677     _name = 'account.config.wizard'
1678
1679     def _get_charts(self, cr, uid, context):
1680         module_obj=self.pool.get('ir.module.module')
1681         ids=module_obj.search(cr, uid, [('category_id', '=', 'Account Charts'), ('state', '<>', 'installed')])
1682         res=[(m.id, m.shortdesc) for m in module_obj.browse(cr, uid, ids)]
1683         res.append((-1, 'None'))
1684         res.sort(key=lambda x: x[1])
1685         return res
1686
1687     _columns = {
1688         'name':fields.char('Name', required=True, size=64, help="Name of the fiscal year as displayed on screens."),
1689         'code':fields.char('Code', required=True, size=64, help="Name of the fiscal year as displayed in reports."),
1690         'date1': fields.date('Start Date', required=True),
1691         'date2': fields.date('End Date', required=True),
1692         'period':fields.selection([('month','Month'),('3months','3 Months')], 'Periods', required=True),
1693         'charts' : fields.selection(_get_charts, 'Charts of Account',required=True)
1694     }
1695     _defaults = {
1696         'code': lambda *a: time.strftime('%Y'),
1697         'name': lambda *a: time.strftime('%Y'),
1698         'date1': lambda *a: time.strftime('%Y-01-01'),
1699         'date2': lambda *a: time.strftime('%Y-12-31'),
1700         'period':lambda *a:'month',
1701     }
1702     def action_cancel(self,cr,uid,ids,conect=None):
1703         return {
1704                 'view_type': 'form',
1705                 "view_mode": 'form',
1706                 'res_model': 'ir.actions.configuration.wizard',
1707                 'type': 'ir.actions.act_window',
1708                 'target':'new',
1709         }
1710
1711     def install_account_chart(self, cr, uid, ids, context=None):
1712         for res in self.read(cr,uid,ids):
1713             chart_id = res['charts']
1714             if chart_id > 0:
1715                 mod_obj = self.pool.get('ir.module.module')
1716                 mod_obj.button_install(cr, uid, [chart_id], context=context)
1717         cr.commit()
1718         db, pool = pooler.restart_pool(cr.dbname, update_module=True)
1719
1720     def action_create(self, cr, uid,ids, context=None):
1721         for res in self.read(cr,uid,ids):
1722             if 'date1' in res and 'date2' in res:
1723                 res_obj = self.pool.get('account.fiscalyear')
1724                 start_date=res['date1']
1725                 end_date=res['date2']
1726                 name=res['name']#DateTime.strptime(start_date, '%Y-%m-%d').strftime('%m.%Y') + '-' + DateTime.strptime(end_date, '%Y-%m-%d').strftime('%m.%Y')
1727                 vals={
1728                     'name':name,
1729                     'code':name,
1730                     'date_start':start_date,
1731                     'date_stop':end_date,
1732                 }
1733                 new_id=res_obj.create(cr, uid, vals, context=context)
1734                 if res['period']=='month':
1735                     res_obj.create_period(cr,uid,[new_id])
1736                 elif res['period']=='3months':
1737                     res_obj.create_period3(cr,uid,[new_id])
1738         self.install_account_chart(cr,uid,ids)
1739         return {
1740                 'view_type': 'form',
1741                 "view_mode": 'form',
1742                 'res_model': 'ir.actions.configuration.wizard',
1743                 'type': 'ir.actions.act_window',
1744                 'target':'new',
1745         }
1746
1747
1748
1749 account_config_wizard()
1750
1751
1752 #  ---------------------------------------------------------------
1753 #   Account Templates : Account, Tax, Tax Code and chart. + Wizard
1754 #  ---------------------------------------------------------------
1755
1756 class account_tax_template(osv.osv):
1757     _name = 'account.tax.template'
1758 account_tax_template()
1759
1760 class account_account_template(osv.osv):
1761     _order = "code"
1762     _name = "account.account.template"
1763     _description ='Templates for Accounts'
1764
1765     _columns = {
1766         'name': fields.char('Name', size=128, required=True, select=True),
1767         'currency_id': fields.many2one('res.currency', 'Secondary Currency', help="Force all moves for this account to have this secondary currency."),
1768         'code': fields.char('Code', size=64),
1769         'type': fields.selection([
1770             ('receivable','Receivable'),
1771             ('payable','Payable'),
1772             ('view','View'),
1773             ('consolidation','Consolidation'),
1774             ('other','Others'),
1775             ('closed','Closed'),
1776             ], 'Internal Type', required=True,help="This type is used to differenciate types with "\
1777             "special effects in Open ERP: view can not have entries, consolidation are accounts that "\
1778             "can have children accounts for multi-company consolidations, payable/receivable are for "\
1779             "partners accounts (for debit/credit computations), closed for deprecated accounts."),
1780         'user_type': fields.many2one('account.account.type', 'Account Type', required=True,
1781             help="These types are defined according to your country. The type contain more information "\
1782             "about the account and it's specificities."),
1783         'reconcile': fields.boolean('Allow Reconciliation', help="Check this option if you want the user to reconcile entries in this account."),
1784         'shortcut': fields.char('Shortcut', size=12),
1785         'note': fields.text('Note'),
1786         'parent_id': fields.many2one('account.account.template','Parent Account Template', ondelete='cascade'),
1787         'child_parent_ids':fields.one2many('account.account.template','parent_id','Children'),
1788         'tax_ids': fields.many2many('account.tax.template', 'account_account_template_tax_rel','account_id','tax_id', 'Default Taxes'),
1789     }
1790
1791     _defaults = {
1792         'reconcile': lambda *a: False,
1793         'type' : lambda *a :'view',
1794     }
1795
1796     def _check_recursion(self, cr, uid, ids):
1797         level = 100
1798         while len(ids):
1799             cr.execute('select parent_id from account_account_template where id in ('+','.join(map(str,ids))+')')
1800             ids = filter(None, map(lambda x:x[0], cr.fetchall()))
1801             if not level:
1802                 return False
1803             level -= 1
1804         return True
1805
1806     _constraints = [
1807         (_check_recursion, 'Error ! You can not create recursive account templates.', ['parent_id'])
1808     ]
1809
1810
1811     def name_get(self, cr, uid, ids, context={}):
1812         if not len(ids):
1813             return []
1814         reads = self.read(cr, uid, ids, ['name','code'], context)
1815         res = []
1816         for record in reads:
1817             name = record['name']
1818             if record['code']:
1819                 name = record['code']+' '+name
1820             res.append((record['id'],name ))
1821         return res
1822
1823 account_account_template()
1824
1825 class account_tax_code_template(osv.osv):
1826
1827     _name = 'account.tax.code.template'
1828     _description = 'Tax Code Template'
1829     _order = 'code'
1830     _rec_name = 'code'
1831     _columns = {
1832         'name': fields.char('Tax Case Name', size=64, required=True),
1833         'code': fields.char('Case Code', size=64),
1834         'info': fields.text('Description'),
1835         'parent_id': fields.many2one('account.tax.code.template', 'Parent Code', select=True),
1836         'child_ids': fields.one2many('account.tax.code.template', 'parent_id', 'Child Codes'),
1837         'sign': fields.float('Sign for parent', required=True),
1838         'notprintable':fields.boolean("Not Printable in Invoice", help="Check this box if you don't want any VAT related to this Tax Code to appear on invoices"),
1839     }
1840
1841     _defaults = {
1842         'sign': lambda *args: 1.0,
1843         'notprintable': lambda *a: False,
1844     }
1845
1846     def name_get(self, cr, uid, ids, context=None):
1847         if not len(ids):
1848             return []
1849         if isinstance(ids, (int, long)):
1850             ids = [ids]
1851         reads = self.read(cr, uid, ids, ['name','code'], context, load='_classic_write')
1852         return [(x['id'], (x['code'] and x['code'] + ' - ' or '') + x['name']) \
1853                 for x in reads]
1854
1855     def _check_recursion(self, cr, uid, ids):
1856         level = 100
1857         while len(ids):
1858             cr.execute('select distinct parent_id from account_tax_code_template where id in ('+','.join(map(str,ids))+')')
1859             ids = filter(None, map(lambda x:x[0], cr.fetchall()))
1860             if not level:
1861                 return False
1862             level -= 1
1863         return True
1864
1865     _constraints = [
1866         (_check_recursion, 'Error ! You can not create recursive Tax Codes.', ['parent_id'])
1867     ]
1868     _order = 'code,name'
1869 account_tax_code_template()
1870
1871
1872 class account_chart_template(osv.osv):
1873     _name="account.chart.template"
1874     _description= "Templates for Account Chart"
1875
1876     _columns={
1877         'name': fields.char('Name', size=64, required=True),
1878         'account_root_id': fields.many2one('account.account.template','Root Account',required=True,domain=[('parent_id','=',False)]),
1879         'tax_code_root_id': fields.many2one('account.tax.code.template','Root Tax Code',required=True,domain=[('parent_id','=',False)]),
1880         'tax_template_ids': fields.one2many('account.tax.template', 'chart_template_id', 'Tax Template List', help='List of all the taxes that have to be installed by the wizard'),
1881         'bank_account_view_id': fields.many2one('account.account.template','Bank Account',required=True),
1882         'property_account_receivable': fields.many2one('account.account.template','Receivable Account'),
1883         'property_account_payable': fields.many2one('account.account.template','Payable Account'),
1884         'property_account_expense_categ': fields.many2one('account.account.template','Expense Category Account'),
1885         'property_account_income_categ': fields.many2one('account.account.template','Income Category Account'),
1886         'property_account_expense': fields.many2one('account.account.template','Expense Account on Product Template'),
1887         'property_account_income': fields.many2one('account.account.template','Income Account on Product Template'),
1888     }
1889
1890 account_chart_template()
1891
1892 class account_tax_template(osv.osv):
1893
1894     _name = 'account.tax.template'
1895     _description = 'Templates for Taxes'
1896
1897     _columns = {
1898         'chart_template_id': fields.many2one('account.chart.template', 'Chart Template', required=True),
1899         'name': fields.char('Tax Name', size=64, required=True),
1900         'sequence': fields.integer('Sequence', required=True, help="The sequence field is used to order the taxes lines from lower sequences to higher ones. The order is important if you have a tax that has several tax children. In this case, the evaluation order is important."),
1901         'amount': fields.float('Amount', required=True, digits=(14,4)),
1902         'type': fields.selection( [('percent','Percent'), ('fixed','Fixed'), ('none','None'), ('code','Python Code')], 'Tax Type', required=True),
1903         'applicable_type': fields.selection( [('true','True'), ('code','Python Code')], 'Applicable Type', required=True),
1904         'domain':fields.char('Domain', size=32, help="This field is only used if you develop your own module allowing developers to create specific taxes in a custom domain."),
1905         'account_collected_id':fields.many2one('account.account.template', 'Invoice Tax Account'),
1906         'account_paid_id':fields.many2one('account.account.template', 'Refund Tax Account'),
1907         'parent_id':fields.many2one('account.tax.template', 'Parent Tax Account', select=True),
1908         'child_depend':fields.boolean('Tax on Children', help="Indicate if the tax computation is based on the value computed for the computation of child taxes or based on the total amount."),
1909         'python_compute':fields.text('Python Code'),
1910         'python_compute_inv':fields.text('Python Code (reverse)'),
1911         'python_applicable':fields.text('Python Code'),
1912         'tax_group': fields.selection([('vat','VAT'),('other','Other')], 'Tax Group', help="If a default tax if given in the partner it only override taxes from account (or product) of the same group."),
1913
1914         #
1915         # Fields used for the VAT declaration
1916         #
1917         'base_code_id': fields.many2one('account.tax.code.template', 'Base Code', help="Use this code for the VAT declaration."),
1918         'tax_code_id': fields.many2one('account.tax.code.template', 'Tax Code', help="Use this code for the VAT declaration."),
1919         'base_sign': fields.float('Base Code Sign', help="Usually 1 or -1."),
1920         'tax_sign': fields.float('Tax Code Sign', help="Usually 1 or -1."),
1921
1922         # Same fields for refund invoices
1923
1924         'ref_base_code_id': fields.many2one('account.tax.code.template', 'Refund Base Code', help="Use this code for the VAT declaration."),
1925         'ref_tax_code_id': fields.many2one('account.tax.code.template', 'Refund Tax Code', help="Use this code for the VAT declaration."),
1926         'ref_base_sign': fields.float('Base Code Sign', help="Usually 1 or -1."),
1927         'ref_tax_sign': fields.float('Tax Code Sign', help="Usually 1 or -1."),
1928         'include_base_amount': fields.boolean('Include in Base Amount', help="Set if the amount of tax must be included in the base amount before computing the next taxes."),
1929         'description': fields.char('Internal Name', size=32),
1930         'type_tax_use': fields.selection([('sale','Sale'),('purchase','Purchase'),('all','All')], 'Tax Use In', required=True,)
1931     }
1932
1933     def name_get(self, cr, uid, ids, context={}):
1934         if not len(ids):
1935             return []
1936         res = []
1937         for record in self.read(cr, uid, ids, ['description','name'], context):
1938             name = record['description'] and record['description'] or record['name']
1939             res.append((record['id'],name ))
1940         return res
1941
1942     def _default_company(self, cr, uid, context={}):
1943         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
1944         if user.company_id:
1945             return user.company_id.id
1946         return self.pool.get('res.company').search(cr, uid, [('parent_id', '=', False)])[0]
1947
1948     _defaults = {
1949         'python_compute': lambda *a: '''# price_unit\n# address : res.partner.address object or False\n# product : product.product object or None\n# partner : res.partner object or None\n\nresult = price_unit * 0.10''',
1950         'python_compute_inv': lambda *a: '''# price_unit\n# address : res.partner.address object or False\n# product : product.product object or False\n\nresult = price_unit * 0.10''',
1951         'applicable_type': lambda *a: 'true',
1952         'type': lambda *a: 'percent',
1953         'amount': lambda *a: 0,
1954         'sequence': lambda *a: 1,
1955         'tax_group': lambda *a: 'vat',
1956         'ref_tax_sign': lambda *a: 1,
1957         'ref_base_sign': lambda *a: 1,
1958         'tax_sign': lambda *a: 1,
1959         'base_sign': lambda *a: 1,
1960         'include_base_amount': lambda *a: False,
1961         'type_tax_use': lambda *a: 'all',
1962     }
1963     _order = 'sequence'
1964
1965
1966 account_tax_template()
1967
1968 # Fiscal Position Templates
1969
1970 class account_fiscal_position_template(osv.osv):
1971     _name = 'account.fiscal.position.template'
1972     _description = 'Template for Fiscal Position'
1973
1974     _columns = {
1975         'name': fields.char('Fiscal Position Template', size=64, translate=True, required=True),
1976         'chart_template_id': fields.many2one('account.chart.template', 'Chart Template', required=True),
1977         'account_ids': fields.one2many('account.fiscal.position.account.template', 'position_id', 'Account Mapping'),
1978         'tax_ids': fields.one2many('account.fiscal.position.tax.template', 'position_id', 'Tax Mapping')
1979     }
1980
1981 account_fiscal_position_template()
1982
1983 class account_fiscal_position_tax_template(osv.osv):
1984     _name = 'account.fiscal.position.tax.template'
1985     _description = 'Fiscal Position Template Tax Mapping'
1986     _rec_name = 'position_id'
1987
1988     _columns = {
1989         'position_id': fields.many2one('account.fiscal.position.template', 'Fiscal Position', required=True, ondelete='cascade'),
1990         'tax_src_id': fields.many2one('account.tax.template', 'Tax Source', required=True),
1991         'tax_dest_id': fields.many2one('account.tax.template', 'Replacement Tax')
1992     }
1993
1994 account_fiscal_position_tax_template()
1995
1996 class account_fiscal_position_account_template(osv.osv):
1997     _name = 'account.fiscal.position.account.template'
1998     _description = 'Fiscal Position Template Account Mapping'
1999     _rec_name = 'position_id'
2000     _columns = {
2001         'position_id': fields.many2one('account.fiscal.position.template', 'Fiscal Position', required=True, ondelete='cascade'),
2002         'account_src_id': fields.many2one('account.account.template', 'Account Source', domain=[('type','<>','view')], required=True),
2003         'account_dest_id': fields.many2one('account.account.template', 'Account Destination', domain=[('type','<>','view')], required=True)
2004     }
2005
2006 account_fiscal_position_account_template()
2007
2008     # Multi charts of Accounts wizard
2009
2010 class wizard_multi_charts_accounts(osv.osv_memory):
2011     """
2012     Create a new account chart for a company.
2013     Wizards ask for:
2014         * a company
2015         * an account chart template
2016         * a number of digits for formatting code of non-view accounts
2017         * a list of bank accounts owned by the company
2018     Then, the wizard:
2019         * generates all accounts from the template and assigns them to the right company
2020         * generates all taxes and tax codes, changing account assignations
2021         * generates all accounting properties and assigns them correctly
2022     """
2023     _name='wizard.multi.charts.accounts'
2024
2025     _columns = {
2026         'company_id':fields.many2one('res.company','Company',required=True),
2027         'chart_template_id': fields.many2one('account.chart.template','Chart Template',required=True),
2028         'bank_accounts_id': fields.one2many('account.bank.accounts.wizard', 'bank_account_id', 'Bank Accounts',required=True),
2029         'code_digits':fields.integer('# of Digits',required=True,help="No. of Digits to use for account code"),
2030         'seq_journal':fields.boolean('Separated Journal Sequences',help="Check this box if you want to use a different sequence for each created journal. Otherwise, all will use the same sequence."),
2031     }
2032
2033     def _get_chart(self, cr, uid, context={}):
2034         ids = self.pool.get('account.chart.template').search(cr, uid, [], context=context)
2035         if ids:
2036             return ids[0]
2037         return False
2038     _defaults = {
2039         'company_id': lambda self, cr, uid, c: self.pool.get('res.users').browse(cr,uid,[uid],c)[0].company_id.id,
2040         'chart_template_id': _get_chart,
2041         'code_digits': lambda *a:6,
2042     }
2043
2044     def action_create(self, cr, uid, ids, context=None):
2045         obj_multi = self.browse(cr,uid,ids[0])
2046         obj_acc = self.pool.get('account.account')
2047         obj_acc_tax = self.pool.get('account.tax')
2048         obj_journal = self.pool.get('account.journal')
2049         obj_sequence = self.pool.get('ir.sequence')
2050         obj_acc_template = self.pool.get('account.account.template')
2051         obj_fiscal_position_template = self.pool.get('account.fiscal.position.template')
2052         obj_fiscal_position = self.pool.get('account.fiscal.position')
2053
2054         # Creating Account
2055         obj_acc_root = obj_multi.chart_template_id.account_root_id
2056         tax_code_root_id = obj_multi.chart_template_id.tax_code_root_id.id
2057         company_id = obj_multi.company_id.id
2058
2059         #new code
2060         acc_template_ref = {}
2061         tax_template_ref = {}
2062         tax_code_template_ref = {}
2063         todo_dict = {}
2064
2065         #create all the tax code
2066         children_tax_code_template = self.pool.get('account.tax.code.template').search(cr, uid, [('parent_id','child_of',[tax_code_root_id])], order='id')
2067         for tax_code_template in self.pool.get('account.tax.code.template').browse(cr, uid, children_tax_code_template):
2068             vals={
2069                 'name': (tax_code_root_id == tax_code_template.id) and obj_multi.company_id.name or tax_code_template.name,
2070                 'code': tax_code_template.code,
2071                 'info': tax_code_template.info,
2072                 'parent_id': tax_code_template.parent_id and ((tax_code_template.parent_id.id in tax_code_template_ref) and tax_code_template_ref[tax_code_template.parent_id.id]) or False,
2073                 'company_id': company_id,
2074                 'sign': tax_code_template.sign,
2075             }
2076             new_tax_code = self.pool.get('account.tax.code').create(cr,uid,vals)
2077             #recording the new tax code to do the mapping
2078             tax_code_template_ref[tax_code_template.id] = new_tax_code
2079
2080         #create all the tax
2081         for tax in obj_multi.chart_template_id.tax_template_ids:
2082             #create it
2083             vals_tax = {
2084                 'name':tax.name,
2085                 'sequence': tax.sequence,
2086                 'amount':tax.amount,
2087                 'type':tax.type,
2088                 'applicable_type': tax.applicable_type,
2089                 'domain':tax.domain,
2090                 'parent_id': tax.parent_id and ((tax.parent_id.id in tax_template_ref) and tax_template_ref[tax.parent_id.id]) or False,
2091                 'child_depend': tax.child_depend,
2092                 'python_compute': tax.python_compute,
2093                 'python_compute_inv': tax.python_compute_inv,
2094                 'python_applicable': tax.python_applicable,
2095                 'tax_group':tax.tax_group,
2096                 'base_code_id': tax.base_code_id and ((tax.base_code_id.id in tax_code_template_ref) and tax_code_template_ref[tax.base_code_id.id]) or False,
2097                 'tax_code_id': tax.tax_code_id and ((tax.tax_code_id.id in tax_code_template_ref) and tax_code_template_ref[tax.tax_code_id.id]) or False,
2098                 'base_sign': tax.base_sign,
2099                 'tax_sign': tax.tax_sign,
2100                 'ref_base_code_id': tax.ref_base_code_id and ((tax.ref_base_code_id.id in tax_code_template_ref) and tax_code_template_ref[tax.ref_base_code_id.id]) or False,
2101                 'ref_tax_code_id': tax.ref_tax_code_id and ((tax.ref_tax_code_id.id in tax_code_template_ref) and tax_code_template_ref[tax.ref_tax_code_id.id]) or False,
2102                 'ref_base_sign': tax.ref_base_sign,
2103                 'ref_tax_sign': tax.ref_tax_sign,
2104                 'include_base_amount': tax.include_base_amount,
2105                 'description':tax.description,
2106                 'company_id': company_id,
2107                 'type_tax_use': tax.type_tax_use
2108             }
2109             new_tax = obj_acc_tax.create(cr,uid,vals_tax)
2110             #as the accounts have not been created yet, we have to wait before filling these fields
2111             todo_dict[new_tax] = {
2112                 'account_collected_id': tax.account_collected_id and tax.account_collected_id.id or False,
2113                 'account_paid_id': tax.account_paid_id and tax.account_paid_id.id or False,
2114             }
2115             tax_template_ref[tax.id] = new_tax
2116
2117         #deactivate the parent_store functionnality on account_account for rapidity purpose
2118         self.pool._init = True
2119
2120         children_acc_template = obj_acc_template.search(cr, uid, [('parent_id','child_of',[obj_acc_root.id])])
2121         children_acc_template.sort()
2122         for account_template in obj_acc_template.browse(cr, uid, children_acc_template):
2123             tax_ids = []
2124             for tax in account_template.tax_ids:
2125                 tax_ids.append(tax_template_ref[tax.id])
2126             #create the account_account
2127
2128             dig = obj_multi.code_digits
2129             code_main = account_template.code and len(account_template.code) or 0
2130             code_acc = account_template.code or ''
2131             if code_main>0 and code_main<=dig and account_template.type != 'view':
2132                 code_acc=str(code_acc) + (str('0'*(dig-code_main)))
2133             vals={
2134                 'name': (obj_acc_root.id == account_template.id) and obj_multi.company_id.name or account_template.name,
2135                 #'sign': account_template.sign,
2136                 'currency_id': account_template.currency_id and account_template.currency_id.id or False,
2137                 'code': code_acc,
2138                 'type': account_template.type,
2139                 'user_type': account_template.user_type and account_template.user_type.id or False,
2140                 'reconcile': account_template.reconcile,
2141                 'shortcut': account_template.shortcut,
2142                 'note': account_template.note,
2143                 'parent_id': account_template.parent_id and ((account_template.parent_id.id in acc_template_ref) and acc_template_ref[account_template.parent_id.id]) or False,
2144                 'tax_ids': [(6,0,tax_ids)],
2145                 'company_id': company_id,
2146             }
2147             new_account = obj_acc.create(cr,uid,vals)
2148             acc_template_ref[account_template.id] = new_account
2149         #reactivate the parent_store functionnality on account_account
2150         self.pool._init = False
2151         self.pool.get('account.account')._parent_store_compute(cr)
2152
2153         for key,value in todo_dict.items():
2154             if value['account_collected_id'] or value['account_paid_id']:
2155                 obj_acc_tax.write(cr, uid, [key], vals={
2156                     'account_collected_id': acc_template_ref[value['account_collected_id']],
2157                     'account_paid_id': acc_template_ref[value['account_paid_id']],
2158                 })
2159
2160         # Creating Journals
2161         vals_journal={}
2162         view_id = self.pool.get('account.journal.view').search(cr,uid,[('name','=','Journal View')])[0]
2163         seq_id = obj_sequence.search(cr,uid,[('name','=','Account Journal')])[0]
2164
2165         if obj_multi.seq_journal:
2166             seq_id_sale = obj_sequence.search(cr,uid,[('name','=','Sale Journal')])[0]
2167             seq_id_purchase = obj_sequence.search(cr,uid,[('name','=','Purchase Journal')])[0]
2168         else:
2169             seq_id_sale = seq_id
2170             seq_id_purchase = seq_id
2171
2172         vals_journal['view_id'] = view_id
2173
2174         #Sales Journal
2175         vals_journal['name'] = _('Sales Journal')
2176         vals_journal['type'] = 'sale'
2177         vals_journal['code'] = _('SAJ')
2178         vals_journal['sequence_id'] = seq_id_sale
2179
2180         if obj_multi.chart_template_id.property_account_receivable:
2181             vals_journal['default_credit_account_id'] = acc_template_ref[obj_multi.chart_template_id.property_account_income_categ.id]
2182             vals_journal['default_debit_account_id'] = acc_template_ref[obj_multi.chart_template_id.property_account_income_categ.id]
2183
2184         obj_journal.create(cr,uid,vals_journal)
2185
2186         # Purchase Journal
2187         vals_journal['name'] = _('Purchase Journal')
2188         vals_journal['type'] = 'purchase'
2189         vals_journal['code'] = _('EXJ')
2190         vals_journal['sequence_id'] = seq_id_purchase
2191
2192         if obj_multi.chart_template_id.property_account_payable:
2193             vals_journal['default_credit_account_id'] = acc_template_ref[obj_multi.chart_template_id.property_account_expense_categ.id]
2194             vals_journal['default_debit_account_id'] = acc_template_ref[obj_multi.chart_template_id.property_account_expense_categ.id]
2195
2196         obj_journal.create(cr,uid,vals_journal)
2197
2198         # Bank Journals
2199         view_id_cash = self.pool.get('account.journal.view').search(cr,uid,[('name','=','Cash Journal View')])[0]
2200         view_id_cur = self.pool.get('account.journal.view').search(cr,uid,[('name','=','Multi-Currency Cash Journal View')])[0]
2201         ref_acc_bank = obj_multi.chart_template_id.bank_account_view_id
2202
2203         current_num = 1
2204         for line in obj_multi.bank_accounts_id:
2205             #create the account_account for this bank journal
2206             tmp = self.pool.get('res.partner.bank').name_get(cr, uid, [line.acc_no.id])[0][1]
2207             dig = obj_multi.code_digits
2208             if ref_acc_bank.code:
2209                 try:
2210                     new_code = str(int(ref_acc_bank.code.ljust(dig,'0')) + current_num)
2211                 except Exception,e:
2212                     new_code = str(ref_acc_bank.code.ljust(dig-len(str(current_num)),'0')) + str(current_num)
2213             vals = {
2214                 'name': line.acc_no.bank and line.acc_no.bank.name+' '+tmp or tmp,
2215                 'currency_id': line.currency_id and line.currency_id.id or False,
2216                 'code': new_code,
2217                 'type': 'other',
2218                 'user_type': account_template.user_type and account_template.user_type.id or False,
2219                 'reconcile': True,
2220                 'parent_id': acc_template_ref[ref_acc_bank.id] or False,
2221                 'company_id': company_id,
2222             }
2223             acc_cash_id  = obj_acc.create(cr,uid,vals)
2224
2225             if obj_multi.seq_journal:
2226                 vals_seq={
2227                         'name': _('Bank Journal ') + vals['name'],
2228                         'code': 'account.journal',
2229                 }
2230                 seq_id = obj_sequence.create(cr,uid,vals_seq)
2231
2232             #create the bank journal
2233             vals_journal['name']= vals['name']
2234             vals_journal['code']= _('BNK') + str(current_num)
2235             vals_journal['sequence_id'] = seq_id
2236             vals_journal['type'] = 'cash'
2237             if line.currency_id:
2238                 vals_journal['view_id'] = view_id_cur
2239                 vals_journal['currency'] = line.currency_id.id
2240             else:
2241                 vals_journal['view_id'] = view_id_cash
2242             vals_journal['default_credit_account_id'] = acc_cash_id
2243             vals_journal['default_debit_account_id'] = acc_cash_id
2244             obj_journal.create(cr,uid,vals_journal)
2245
2246             current_num += 1
2247
2248         #create the properties
2249         property_obj = self.pool.get('ir.property')
2250         fields_obj = self.pool.get('ir.model.fields')
2251
2252         todo_list = [
2253             ('property_account_receivable','res.partner','account.account'),
2254             ('property_account_payable','res.partner','account.account'),
2255             ('property_account_expense_categ','product.category','account.account'),
2256             ('property_account_income_categ','product.category','account.account'),
2257             ('property_account_expense','product.template','account.account'),
2258             ('property_account_income','product.template','account.account')
2259         ]
2260         for record in todo_list:
2261             r = []
2262             r = property_obj.search(cr, uid, [('name','=', record[0] ),('company_id','=',company_id)])
2263             account = getattr(obj_multi.chart_template_id, record[0])
2264             field = fields_obj.search(cr, uid, [('name','=',record[0]),('model','=',record[1]),('relation','=',record[2])])
2265             vals = {
2266                 'name': record[0],
2267                 'company_id': company_id,
2268                 'fields_id': field[0],
2269                 'value': account and 'account.account,'+str(acc_template_ref[account.id]) or False,
2270             }
2271             if r:
2272                 #the property exist: modify it
2273                 property_obj.write(cr, uid, r, vals)
2274             else:
2275                 #create the property
2276                 property_obj.create(cr, uid, vals)
2277
2278         fp_ids = obj_fiscal_position_template.search(cr, uid,[('chart_template_id', '=', obj_multi.chart_template_id.id)])
2279
2280         if fp_ids:
2281             for position in obj_fiscal_position_template.browse(cr, uid, fp_ids):
2282
2283                 vals_fp = {
2284                            'company_id' : company_id,
2285                            'name' : position.name,
2286                            }
2287                 new_fp = obj_fiscal_position.create(cr, uid, vals_fp)
2288
2289                 obj_tax_fp = self.pool.get('account.fiscal.position.tax')
2290                 obj_ac_fp = self.pool.get('account.fiscal.position.account')
2291
2292                 for tax in position.tax_ids:
2293                     vals_tax = {
2294                                 'tax_src_id' : tax_template_ref[tax.tax_src_id.id],
2295                                 'tax_dest_id' : tax.tax_dest_id and tax_template_ref[tax.tax_dest_id.id] or False,
2296                                 'position_id' : new_fp,
2297                                 }
2298                     obj_tax_fp.create(cr, uid, vals_tax)
2299
2300                 for acc in position.account_ids:
2301                     vals_acc = {
2302                                 'account_src_id' : acc_template_ref[acc.account_src_id.id],
2303                                 'account_dest_id' : acc_template_ref[acc.account_dest_id.id],
2304                                 'position_id' : new_fp,
2305                                 }
2306                     obj_ac_fp.create(cr, uid, vals_acc)
2307
2308         return {
2309                 'view_type': 'form',
2310                 "view_mode": 'form',
2311                 'res_model': 'ir.actions.configuration.wizard',
2312                 'type': 'ir.actions.act_window',
2313                 'target':'new',
2314         }
2315     def action_cancel(self,cr,uid,ids,conect=None):
2316         return {
2317                 'view_type': 'form',
2318                 "view_mode": 'form',
2319                 'res_model': 'ir.actions.configuration.wizard',
2320                 'type': 'ir.actions.act_window',
2321                 'target':'new',
2322         }
2323
2324
2325 wizard_multi_charts_accounts()
2326
2327 class account_bank_accounts_wizard(osv.osv_memory):
2328     _name='account.bank.accounts.wizard'
2329
2330     _columns = {
2331         'acc_no':fields.many2one('res.partner.bank','Account No.',required=True),
2332         'bank_account_id':fields.many2one('wizard.multi.charts.accounts', 'Bank Account', required=True),
2333         'currency_id':fields.many2one('res.currency', 'Currency'),
2334     }
2335
2336 account_bank_accounts_wizard()
2337
2338 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
2339