[MERGE] forward port of branch saas-3 up to 7ab4137
[odoo/odoo.git] / addons / account / account.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 import logging
23 from datetime import datetime
24 from dateutil.relativedelta import relativedelta
25 from operator import itemgetter
26 import time
27
28 import openerp
29 from openerp import SUPERUSER_ID, api
30 from openerp import tools
31 from openerp.osv import fields, osv, expression
32 from openerp.tools.translate import _
33 from openerp.tools.float_utils import float_round as round
34
35 import openerp.addons.decimal_precision as dp
36
37 _logger = logging.getLogger(__name__)
38
39 def check_cycle(self, cr, uid, ids, context=None):
40     """ climbs the ``self._table.parent_id`` chains for 100 levels or
41     until it can't find any more parent(s)
42
43     Returns true if it runs out of parents (no cycle), false if
44     it can recurse 100 times without ending all chains
45     """
46     level = 100
47     while len(ids):
48         cr.execute('SELECT DISTINCT parent_id '\
49                     'FROM '+self._table+' '\
50                     'WHERE id IN %s '\
51                     'AND parent_id IS NOT NULL',(tuple(ids),))
52         ids = map(itemgetter(0), cr.fetchall())
53         if not level:
54             return False
55         level -= 1
56     return True
57
58 class res_company(osv.osv):
59     _inherit = "res.company"
60     _columns = {
61         'income_currency_exchange_account_id': fields.many2one(
62             'account.account',
63             string="Gain Exchange Rate Account",
64             domain="[('type', '=', 'other')]",),
65         'expense_currency_exchange_account_id': fields.many2one(
66             'account.account',
67             string="Loss Exchange Rate Account",
68             domain="[('type', '=', 'other')]",),
69     }
70
71 class account_payment_term(osv.osv):
72     _name = "account.payment.term"
73     _description = "Payment Term"
74     _columns = {
75         'name': fields.char('Payment Term', translate=True, required=True),
76         'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the payment term without removing it."),
77         'note': fields.text('Description', translate=True),
78         'line_ids': fields.one2many('account.payment.term.line', 'payment_id', 'Terms', copy=True),
79     }
80     _defaults = {
81         'active': 1,
82     }
83     _order = "name"
84
85     def compute(self, cr, uid, id, value, date_ref=False, context=None):
86         if not date_ref:
87             date_ref = datetime.now().strftime('%Y-%m-%d')
88         pt = self.browse(cr, uid, id, context=context)
89         amount = value
90         result = []
91         obj_precision = self.pool.get('decimal.precision')
92         prec = obj_precision.precision_get(cr, uid, 'Account')
93         for line in pt.line_ids:
94             if line.value == 'fixed':
95                 amt = round(line.value_amount, prec)
96             elif line.value == 'procent':
97                 amt = round(value * line.value_amount, prec)
98             elif line.value == 'balance':
99                 amt = round(amount, prec)
100             if amt:
101                 next_date = (datetime.strptime(date_ref, '%Y-%m-%d') + relativedelta(days=line.days))
102                 if line.days2 < 0:
103                     next_first_date = next_date + relativedelta(day=1,months=1) #Getting 1st of next month
104                     next_date = next_first_date + relativedelta(days=line.days2)
105                 if line.days2 > 0:
106                     next_date += relativedelta(day=line.days2, months=1)
107                 result.append( (next_date.strftime('%Y-%m-%d'), amt) )
108                 amount -= amt
109
110         amount = reduce(lambda x,y: x+y[1], result, 0.0)
111         dist = round(value-amount, prec)
112         if dist:
113             result.append( (time.strftime('%Y-%m-%d'), dist) )
114         return result
115
116 class account_payment_term_line(osv.osv):
117     _name = "account.payment.term.line"
118     _description = "Payment Term Line"
119     _columns = {
120         'value': fields.selection([('procent', 'Percent'),
121                                    ('balance', 'Balance'),
122                                    ('fixed', 'Fixed Amount')], 'Computation',
123                                    required=True, help="""Select here the kind of valuation related to this payment term line. Note that you should have your last line with the type 'Balance' to ensure that the whole amount will be treated."""),
124
125         'value_amount': fields.float('Amount To Pay', digits_compute=dp.get_precision('Payment Term'), help="For percent enter a ratio between 0-1."),
126         'days': fields.integer('Number of Days', required=True, help="Number of days to add before computation of the day of month." \
127             "If Date=15/01, Number of Days=22, Day of Month=-1, then the due date is 28/02."),
128         '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)."),
129         'payment_id': fields.many2one('account.payment.term', 'Payment Term', required=True, select=True, ondelete='cascade'),
130     }
131     _defaults = {
132         'value': 'balance',
133         'days': 30,
134         'days2': 0,
135     }
136     _order = "value desc,days"
137
138     def _check_percent(self, cr, uid, ids, context=None):
139         obj = self.browse(cr, uid, ids[0], context=context)
140         if obj.value == 'procent' and ( obj.value_amount < 0.0 or obj.value_amount > 1.0):
141             return False
142         return True
143
144     _constraints = [
145         (_check_percent, 'Percentages for Payment Term Line must be between 0 and 1, Example: 0.02 for 2%.', ['value_amount']),
146     ]
147
148
149 class account_account_type(osv.osv):
150     _name = "account.account.type"
151     _description = "Account Type"
152
153     def _get_financial_report_ref(self, cr, uid, context=None):
154         obj_data = self.pool.get('ir.model.data')
155         obj_financial_report = self.pool.get('account.financial.report')
156         financial_report_ref = {}
157         for key, financial_report in [
158                     ('asset','account_financial_report_assets0'),
159                     ('liability','account_financial_report_liability0'),
160                     ('income','account_financial_report_income0'),
161                     ('expense','account_financial_report_expense0'),
162                 ]:
163             try:
164                 financial_report_ref[key] = obj_financial_report.browse(cr, uid,
165                     obj_data.get_object_reference(cr, uid, 'account', financial_report)[1],
166                     context=context)
167             except ValueError:
168                 pass
169         return financial_report_ref
170
171     def _get_current_report_type(self, cr, uid, ids, name, arg, context=None):
172         res = {}
173         financial_report_ref = self._get_financial_report_ref(cr, uid, context=context)
174         for record in self.browse(cr, uid, ids, context=context):
175             res[record.id] = 'none'
176             for key, financial_report in financial_report_ref.items():
177                 list_ids = [x.id for x in financial_report.account_type_ids]
178                 if record.id in list_ids:
179                     res[record.id] = key
180         return res
181
182     def _save_report_type(self, cr, uid, account_type_id, field_name, field_value, arg, context=None):
183         field_value = field_value or 'none'
184         obj_financial_report = self.pool.get('account.financial.report')
185         #unlink if it exists somewhere in the financial reports related to BS or PL
186         financial_report_ref = self._get_financial_report_ref(cr, uid, context=context)
187         for key, financial_report in financial_report_ref.items():
188             list_ids = [x.id for x in financial_report.account_type_ids]
189             if account_type_id in list_ids:
190                 obj_financial_report.write(cr, uid, [financial_report.id], {'account_type_ids': [(3, account_type_id)]})
191         #write it in the good place
192         if field_value != 'none':
193             return obj_financial_report.write(cr, uid, [financial_report_ref[field_value].id], {'account_type_ids': [(4, account_type_id)]})
194
195     _columns = {
196         'name': fields.char('Account Type', required=True, translate=True),
197         'code': fields.char('Code', size=32, required=True, select=True),
198         'close_method': fields.selection([('none', 'None'), ('balance', 'Balance'), ('detail', 'Detail'), ('unreconciled', 'Unreconciled')], 'Deferral Method', required=True, help="""Set here the method that will be used to generate the end of year journal entries for all the accounts of this type.
199
200  'None' means that nothing will be done.
201  'Balance' will generally be used for cash accounts.
202  'Detail' will copy each existing journal item of the previous year, even the reconciled ones.
203  'Unreconciled' will copy only the journal items that were unreconciled on the first day of the new fiscal year."""),
204         'report_type': fields.function(_get_current_report_type, fnct_inv=_save_report_type, type='selection', string='P&L / BS Category', store=True,
205             selection= [('none','/'),
206                         ('income', _('Profit & Loss (Income account)')),
207                         ('expense', _('Profit & Loss (Expense account)')),
208                         ('asset', _('Balance Sheet (Asset account)')),
209                         ('liability', _('Balance Sheet (Liability account)'))], help="This field is used to generate legal reports: profit and loss, balance sheet.", required=True),
210         'note': fields.text('Description'),
211     }
212     _defaults = {
213         'close_method': 'none',
214         'report_type': 'none',
215     }
216     _order = "code"
217
218
219 def _code_get(self, cr, uid, context=None):
220     acc_type_obj = self.pool.get('account.account.type')
221     ids = acc_type_obj.search(cr, uid, [])
222     res = acc_type_obj.read(cr, uid, ids, ['code', 'name'], context=context)
223     return [(r['code'], r['name']) for r in res]
224
225 #----------------------------------------------------------
226 # Accounts
227 #----------------------------------------------------------
228
229 class account_account(osv.osv):
230     _order = "parent_left"
231     _parent_order = "code"
232     _name = "account.account"
233     _description = "Account"
234     _parent_store = True
235
236     def search(self, cr, uid, args, offset=0, limit=None, order=None,
237             context=None, count=False):
238         if context is None:
239             context = {}
240         pos = 0
241
242         while pos < len(args):
243
244             if args[pos][0] == 'code' and args[pos][1] in ('like', 'ilike') and args[pos][2]:
245                 args[pos] = ('code', '=like', tools.ustr(args[pos][2].replace('%', ''))+'%')
246             if args[pos][0] == 'journal_id':
247                 if not args[pos][2]:
248                     del args[pos]
249                     continue
250                 jour = self.pool.get('account.journal').browse(cr, uid, args[pos][2], context=context)
251                 if (not (jour.account_control_ids or jour.type_control_ids)) or not args[pos][2]:
252                     args[pos] = ('type','not in',('consolidation','view'))
253                     continue
254                 ids3 = map(lambda x: x.id, jour.type_control_ids)
255                 ids1 = super(account_account, self).search(cr, uid, [('user_type', 'in', ids3)])
256                 ids1 += map(lambda x: x.id, jour.account_control_ids)
257                 args[pos] = ('id', 'in', ids1)
258             pos += 1
259
260         if context and context.has_key('consolidate_children'): #add consolidated children of accounts
261             ids = super(account_account, self).search(cr, uid, args, offset, limit,
262                 order, context=context, count=count)
263             for consolidate_child in self.browse(cr, uid, context['account_id'], context=context).child_consol_ids:
264                 ids.append(consolidate_child.id)
265             return ids
266
267         return super(account_account, self).search(cr, uid, args, offset, limit,
268                 order, context=context, count=count)
269
270     def _get_children_and_consol(self, cr, uid, ids, context=None):
271         #this function search for all the children and all consolidated children (recursively) of the given account ids
272         ids2 = self.search(cr, uid, [('parent_id', 'child_of', ids)], context=context)
273         ids3 = []
274         for rec in self.browse(cr, uid, ids2, context=context):
275             for child in rec.child_consol_ids:
276                 ids3.append(child.id)
277         if ids3:
278             ids3 = self._get_children_and_consol(cr, uid, ids3, context)
279         return ids2 + ids3
280
281     def __compute(self, cr, uid, ids, field_names, arg=None, context=None,
282                   query='', query_params=()):
283         """ compute the balance, debit and/or credit for the provided
284         account ids
285         Arguments:
286         `ids`: account ids
287         `field_names`: the fields to compute (a list of any of
288                        'balance', 'debit' and 'credit')
289         `arg`: unused fields.function stuff
290         `query`: additional query filter (as a string)
291         `query_params`: parameters for the provided query string
292                         (__compute will handle their escaping) as a
293                         tuple
294         """
295         mapping = {
296             'balance': "COALESCE(SUM(l.debit),0) - COALESCE(SUM(l.credit), 0) as balance",
297             'debit': "COALESCE(SUM(l.debit), 0) as debit",
298             'credit': "COALESCE(SUM(l.credit), 0) as credit",
299             # by convention, foreign_balance is 0 when the account has no secondary currency, because the amounts may be in different currencies
300             'foreign_balance': "(SELECT CASE WHEN currency_id IS NULL THEN 0 ELSE COALESCE(SUM(l.amount_currency), 0) END FROM account_account WHERE id IN (l.account_id)) as foreign_balance",
301         }
302         #get all the necessary accounts
303         children_and_consolidated = self._get_children_and_consol(cr, uid, ids, context=context)
304         #compute for each account the balance/debit/credit from the move lines
305         accounts = {}
306         res = {}
307         null_result = dict((fn, 0.0) for fn in field_names)
308         if children_and_consolidated:
309             aml_query = self.pool.get('account.move.line')._query_get(cr, uid, context=context)
310
311             wheres = [""]
312             if query.strip():
313                 wheres.append(query.strip())
314             if aml_query.strip():
315                 wheres.append(aml_query.strip())
316             filters = " AND ".join(wheres)
317             # IN might not work ideally in case there are too many
318             # children_and_consolidated, in that case join on a
319             # values() e.g.:
320             # SELECT l.account_id as id FROM account_move_line l
321             # INNER JOIN (VALUES (id1), (id2), (id3), ...) AS tmp (id)
322             # ON l.account_id = tmp.id
323             # or make _get_children_and_consol return a query and join on that
324             request = ("SELECT l.account_id as id, " +\
325                        ', '.join(mapping.values()) +
326                        " FROM account_move_line l" \
327                        " WHERE l.account_id IN %s " \
328                             + filters +
329                        " GROUP BY l.account_id")
330             params = (tuple(children_and_consolidated),) + query_params
331             cr.execute(request, params)
332
333             for row in cr.dictfetchall():
334                 accounts[row['id']] = row
335
336             # consolidate accounts with direct children
337             children_and_consolidated.reverse()
338             brs = list(self.browse(cr, uid, children_and_consolidated, context=context))
339             sums = {}
340             currency_obj = self.pool.get('res.currency')
341             while brs:
342                 current = brs.pop(0)
343 #                can_compute = True
344 #                for child in current.child_id:
345 #                    if child.id not in sums:
346 #                        can_compute = False
347 #                        try:
348 #                            brs.insert(0, brs.pop(brs.index(child)))
349 #                        except ValueError:
350 #                            brs.insert(0, child)
351 #                if can_compute:
352                 for fn in field_names:
353                     sums.setdefault(current.id, {})[fn] = accounts.get(current.id, {}).get(fn, 0.0)
354                     for child in current.child_id:
355                         if child.company_id.currency_id.id == current.company_id.currency_id.id:
356                             sums[current.id][fn] += sums[child.id][fn]
357                         else:
358                             sums[current.id][fn] += currency_obj.compute(cr, uid, child.company_id.currency_id.id, current.company_id.currency_id.id, sums[child.id][fn], context=context)
359
360                 # as we have to relay on values computed before this is calculated separately than previous fields
361                 if current.currency_id and current.exchange_rate and \
362                             ('adjusted_balance' in field_names or 'unrealized_gain_loss' in field_names):
363                     # Computing Adjusted Balance and Unrealized Gains and losses
364                     # Adjusted Balance = Foreign Balance / Exchange Rate
365                     # Unrealized Gains and losses = Adjusted Balance - Balance
366                     adj_bal = sums[current.id].get('foreign_balance', 0.0) / current.exchange_rate
367                     sums[current.id].update({'adjusted_balance': adj_bal, 'unrealized_gain_loss': adj_bal - sums[current.id].get('balance', 0.0)})
368
369             for id in ids:
370                 res[id] = sums.get(id, null_result)
371         else:
372             for id in ids:
373                 res[id] = null_result
374         return res
375
376     def _get_company_currency(self, cr, uid, ids, field_name, arg, context=None):
377         result = {}
378         for rec in self.browse(cr, uid, ids, context=context):
379             result[rec.id] = (rec.company_id.currency_id.id,rec.company_id.currency_id.symbol)
380         return result
381
382     def _get_child_ids(self, cr, uid, ids, field_name, arg, context=None):
383         result = {}
384         for record in self.browse(cr, uid, ids, context=context):
385             if record.child_parent_ids:
386                 result[record.id] = [x.id for x in record.child_parent_ids]
387             else:
388                 result[record.id] = []
389
390             if record.child_consol_ids:
391                 for acc in record.child_consol_ids:
392                     if acc.id not in result[record.id]:
393                         result[record.id].append(acc.id)
394
395         return result
396
397     def _get_level(self, cr, uid, ids, field_name, arg, context=None):
398         res = {}
399         for account in self.browse(cr, uid, ids, context=context):
400             #we may not know the level of the parent at the time of computation, so we
401             # can't simply do res[account.id] = account.parent_id.level + 1
402             level = 0
403             parent = account.parent_id
404             while parent:
405                 level += 1
406                 parent = parent.parent_id
407             res[account.id] = level
408         return res
409
410     def _set_credit_debit(self, cr, uid, account_id, name, value, arg, context=None):
411         if context.get('config_invisible', True):
412             return True
413
414         account = self.browse(cr, uid, account_id, context=context)
415         diff = value - getattr(account,name)
416         if not diff:
417             return True
418
419         journal_obj = self.pool.get('account.journal')
420         jids = journal_obj.search(cr, uid, [('type','=','situation'),('centralisation','=',1),('company_id','=',account.company_id.id)], context=context)
421         if not jids:
422             raise osv.except_osv(_('Error!'),_("You need an Opening journal with centralisation checked to set the initial balance."))
423
424         period_obj = self.pool.get('account.period')
425         pids = period_obj.search(cr, uid, [('special','=',True),('company_id','=',account.company_id.id)], context=context)
426         if not pids:
427             raise osv.except_osv(_('Error!'),_("There is no opening/closing period defined, please create one to set the initial balance."))
428
429         move_obj = self.pool.get('account.move.line')
430         move_id = move_obj.search(cr, uid, [
431             ('journal_id','=',jids[0]),
432             ('period_id','=',pids[0]),
433             ('account_id','=', account_id),
434             (name,'>', 0.0),
435             ('name','=', _('Opening Balance'))
436         ], context=context)
437         if move_id:
438             move = move_obj.browse(cr, uid, move_id[0], context=context)
439             move_obj.write(cr, uid, move_id[0], {
440                 name: diff+getattr(move,name)
441             }, context=context)
442         else:
443             if diff<0.0:
444                 raise osv.except_osv(_('Error!'),_("Unable to adapt the initial balance (negative value)."))
445             nameinv = (name=='credit' and 'debit') or 'credit'
446             move_id = move_obj.create(cr, uid, {
447                 'name': _('Opening Balance'),
448                 'account_id': account_id,
449                 'journal_id': jids[0],
450                 'period_id': pids[0],
451                 name: diff,
452                 nameinv: 0.0
453             }, context=context)
454         return True
455
456     _columns = {
457         'name': fields.char('Name', required=True, select=True),
458         'currency_id': fields.many2one('res.currency', 'Secondary Currency', help="Forces all moves for this account to have this secondary currency."),
459         'code': fields.char('Code', size=64, required=True, select=1),
460         'type': fields.selection([
461             ('view', 'View'),
462             ('other', 'Regular'),
463             ('receivable', 'Receivable'),
464             ('payable', 'Payable'),
465             ('liquidity','Liquidity'),
466             ('consolidation', 'Consolidation'),
467             ('closed', 'Closed'),
468         ], 'Internal Type', required=True, help="The 'Internal Type' is used for features available on "\
469             "different types of accounts: view can not have journal items, consolidation are accounts that "\
470             "can have children accounts for multi-company consolidations, payable/receivable are for "\
471             "partners accounts (for debit/credit computations), closed for depreciated accounts."),
472         'user_type': fields.many2one('account.account.type', 'Account Type', required=True,
473             help="Account Type is used for information purpose, to generate "
474               "country-specific legal reports, and set the rules to close a fiscal year and generate opening entries."),
475         'financial_report_ids': fields.many2many('account.financial.report', 'account_account_financial_report', 'account_id', 'report_line_id', 'Financial Reports'),
476         'parent_id': fields.many2one('account.account', 'Parent', ondelete='cascade', domain=[('type','=','view')]),
477         'child_parent_ids': fields.one2many('account.account','parent_id','Children'),
478         'child_consol_ids': fields.many2many('account.account', 'account_account_consol_rel', 'child_id', 'parent_id', 'Consolidated Children'),
479         'child_id': fields.function(_get_child_ids, type='many2many', relation="account.account", string="Child Accounts"),
480         'balance': fields.function(__compute, digits_compute=dp.get_precision('Account'), string='Balance', multi='balance'),
481         'credit': fields.function(__compute, fnct_inv=_set_credit_debit, digits_compute=dp.get_precision('Account'), string='Credit', multi='balance'),
482         'debit': fields.function(__compute, fnct_inv=_set_credit_debit, digits_compute=dp.get_precision('Account'), string='Debit', multi='balance'),
483         'foreign_balance': fields.function(__compute, digits_compute=dp.get_precision('Account'), string='Foreign Balance', multi='balance',
484                                            help="Total amount (in Secondary currency) for transactions held in secondary currency for this account."),
485         'adjusted_balance': fields.function(__compute, digits_compute=dp.get_precision('Account'), string='Adjusted Balance', multi='balance',
486                                             help="Total amount (in Company currency) for transactions held in secondary currency for this account."),
487         'unrealized_gain_loss': fields.function(__compute, digits_compute=dp.get_precision('Account'), string='Unrealized Gain or Loss', multi='balance',
488                                                 help="Value of Loss or Gain due to changes in exchange rate when doing multi-currency transactions."),
489         'reconcile': fields.boolean('Allow Reconciliation', help="Check this box if this account allows reconciliation of journal items."),
490         'exchange_rate': fields.related('currency_id', 'rate', type='float', string='Exchange Rate', digits=(12,6)),
491         'shortcut': fields.char('Shortcut', size=12),
492         'tax_ids': fields.many2many('account.tax', 'account_account_tax_default_rel',
493             'account_id', 'tax_id', 'Default Taxes'),
494         'note': fields.text('Internal Notes'),
495         'company_currency_id': fields.function(_get_company_currency, type='many2one', relation='res.currency', string='Company Currency'),
496         'company_id': fields.many2one('res.company', 'Company', required=True),
497         'active': fields.boolean('Active', select=2, help="If the active field is set to False, it will allow you to hide the account without removing it."),
498
499         'parent_left': fields.integer('Parent Left', select=1),
500         'parent_right': fields.integer('Parent Right', select=1),
501         'currency_mode': fields.selection([('current', 'At Date'), ('average', 'Average Rate')], 'Outgoing Currencies Rate',
502             help=
503             'This will select how the current currency rate for outgoing transactions is computed. '\
504             'In most countries the legal method is "average" but only a few software systems are able to '\
505             'manage this. So if you import from another software system you may have to use the rate at date. ' \
506             'Incoming transactions always use the rate at date.', \
507             required=True),
508         'level': fields.function(_get_level, string='Level', method=True, type='integer',
509              store={
510                     'account.account': (_get_children_and_consol, ['level', 'parent_id'], 10),
511                    }),
512     }
513
514     _defaults = {
515         'type': 'other',
516         'reconcile': False,
517         'active': True,
518         'currency_mode': 'current',
519         'company_id': lambda s, cr, uid, c: s.pool.get('res.company')._company_default_get(cr, uid, 'account.account', context=c),
520     }
521
522     def _check_recursion(self, cr, uid, ids, context=None):
523         obj_self = self.browse(cr, uid, ids[0], context=context)
524         p_id = obj_self.parent_id and obj_self.parent_id.id
525         if (obj_self in obj_self.child_consol_ids) or (p_id and (p_id is obj_self.id)):
526             return False
527         while(ids):
528             cr.execute('SELECT DISTINCT child_id '\
529                        'FROM account_account_consol_rel '\
530                        'WHERE parent_id IN %s', (tuple(ids),))
531             child_ids = map(itemgetter(0), cr.fetchall())
532             c_ids = child_ids
533             if (p_id and (p_id in c_ids)) or (obj_self.id in c_ids):
534                 return False
535             while len(c_ids):
536                 s_ids = self.search(cr, uid, [('parent_id', 'in', c_ids)])
537                 if p_id and (p_id in s_ids):
538                     return False
539                 c_ids = s_ids
540             ids = child_ids
541         return True
542
543     def _check_type(self, cr, uid, ids, context=None):
544         if context is None:
545             context = {}
546         accounts = self.browse(cr, uid, ids, context=context)
547         for account in accounts:
548             if account.child_id and account.type not in ('view', 'consolidation'):
549                 return False
550         return True
551
552     def _check_account_type(self, cr, uid, ids, context=None):
553         for account in self.browse(cr, uid, ids, context=context):
554             if account.type in ('receivable', 'payable') and account.user_type.close_method != 'unreconciled':
555                 return False
556         return True
557
558     def _check_company_account(self, cr, uid, ids, context=None):
559         for account in self.browse(cr, uid, ids, context=context):
560             if account.parent_id:
561                 if account.company_id != account.parent_id.company_id:
562                     return False
563         return True
564
565     _constraints = [
566         (_check_recursion, 'Error!\nYou cannot create recursive accounts.', ['parent_id']),
567         (_check_type, 'Configuration Error!\nYou cannot define children to an account with internal type different of "View".', ['type']),
568         (_check_account_type, 'Configuration Error!\nYou cannot select an account type with a deferral method different of "Unreconciled" for accounts with internal type "Payable/Receivable".', ['user_type','type']),
569         (_check_company_account, 'Error!\nYou cannot create an account which has parent account of different company.', ['parent_id']),
570     ]
571     _sql_constraints = [
572         ('code_company_uniq', 'unique (code,company_id)', 'The code of the account must be unique per company !')
573     ]
574     def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=100):
575         if not args:
576             args = []
577         args = args[:]
578         ids = []
579         try:
580             if name and str(name).startswith('partner:'):
581                 part_id = int(name.split(':')[1])
582                 part = self.pool.get('res.partner').browse(cr, user, part_id, context=context)
583                 args += [('id', 'in', (part.property_account_payable.id, part.property_account_receivable.id))]
584                 name = False
585             if name and str(name).startswith('type:'):
586                 type = name.split(':')[1]
587                 args += [('type', '=', type)]
588                 name = False
589         except:
590             pass
591         if name:
592             if operator not in expression.NEGATIVE_TERM_OPERATORS:
593                 plus_percent = lambda n: n+'%'
594                 code_op, code_conv = {
595                     'ilike': ('=ilike', plus_percent),
596                     'like': ('=like', plus_percent),
597                 }.get(operator, (operator, lambda n: n))
598
599                 ids = self.search(cr, user, ['|', ('code', code_op, code_conv(name)), '|', ('shortcut', '=', name), ('name', operator, name)]+args, limit=limit)
600
601                 if not ids and len(name.split()) >= 2:
602                     #Separating code and name of account for searching
603                     operand1,operand2 = name.split(' ',1) #name can contain spaces e.g. OpenERP S.A.
604                     ids = self.search(cr, user, [('code', operator, operand1), ('name', operator, operand2)]+ args, limit=limit)
605             else:
606                 ids = self.search(cr, user, ['&','!', ('code', '=like', name+"%"), ('name', operator, name)]+args, limit=limit)
607                 # as negation want to restric, do if already have results
608                 if ids and len(name.split()) >= 2:
609                     operand1,operand2 = name.split(' ',1) #name can contain spaces e.g. OpenERP S.A.
610                     ids = self.search(cr, user, [('code', operator, operand1), ('name', operator, operand2), ('id', 'in', ids)]+ args, limit=limit)
611         else:
612             ids = self.search(cr, user, args, context=context, limit=limit)
613         return self.name_get(cr, user, ids, context=context)
614
615     def name_get(self, cr, uid, ids, context=None):
616         if not ids:
617             return []
618         if isinstance(ids, (int, long)):
619                     ids = [ids]
620         reads = self.read(cr, uid, ids, ['name', 'code'], context=context)
621         res = []
622         for record in reads:
623             name = record['name']
624             if record['code']:
625                 name = record['code'] + ' ' + name
626             res.append((record['id'], name))
627         return res
628
629     def copy(self, cr, uid, id, default=None, context=None, done_list=None, local=False):
630         default = {} if default is None else default.copy()
631         if done_list is None:
632             done_list = []
633         account = self.browse(cr, uid, id, context=context)
634         new_child_ids = []
635         default.update(code=_("%s (copy)") % (account['code'] or ''))
636         if not local:
637             done_list = []
638         if account.id in done_list:
639             return False
640         done_list.append(account.id)
641         if account:
642             for child in account.child_id:
643                 child_ids = self.copy(cr, uid, child.id, default, context=context, done_list=done_list, local=True)
644                 if child_ids:
645                     new_child_ids.append(child_ids)
646             default['child_parent_ids'] = [(6, 0, new_child_ids)]
647         else:
648             default['child_parent_ids'] = False
649         return super(account_account, self).copy(cr, uid, id, default, context=context)
650
651     def _check_moves(self, cr, uid, ids, method, context=None):
652         line_obj = self.pool.get('account.move.line')
653         account_ids = self.search(cr, uid, [('id', 'child_of', ids)], context=context)
654
655         if line_obj.search(cr, uid, [('account_id', 'in', account_ids)], context=context):
656             if method == 'write':
657                 raise osv.except_osv(_('Error!'), _('You cannot deactivate an account that contains journal items.'))
658             elif method == 'unlink':
659                 raise osv.except_osv(_('Error!'), _('You cannot remove an account that contains journal items.'))
660         #Checking whether the account is set as a property to any Partner or not
661         values = ['account.account,%s' % (account_id,) for account_id in ids]
662         partner_prop_acc = self.pool.get('ir.property').search(cr, uid, [('value_reference','in', values)], context=context)
663         if partner_prop_acc:
664             raise osv.except_osv(_('Warning!'), _('You cannot remove/deactivate an account which is set on a customer or supplier.'))
665         return True
666
667     def _check_allow_type_change(self, cr, uid, ids, new_type, context=None):
668         restricted_groups = ['consolidation','view']
669         line_obj = self.pool.get('account.move.line')
670         for account in self.browse(cr, uid, ids, context=context):
671             old_type = account.type
672             account_ids = self.search(cr, uid, [('id', 'child_of', [account.id])])
673             if line_obj.search(cr, uid, [('account_id', 'in', account_ids)]):
674                 #Check for 'Closed' type
675                 if old_type == 'closed' and new_type !='closed':
676                     raise osv.except_osv(_('Warning!'), _("You cannot change the type of account from 'Closed' to any other type as it contains journal items!"))
677                 # Forbid to change an account type for restricted_groups as it contains journal items (or if one of its children does)
678                 if (new_type in restricted_groups):
679                     raise osv.except_osv(_('Warning!'), _("You cannot change the type of account to '%s' type as it contains journal items!") % (new_type,))
680
681         return True
682
683     # For legal reason (forbiden to modify journal entries which belongs to a closed fy or period), Forbid to modify
684     # the code of an account if journal entries have been already posted on this account. This cannot be simply 
685     # 'configurable' since it can lead to a lack of confidence in Odoo and this is what we want to change.
686     def _check_allow_code_change(self, cr, uid, ids, context=None):
687         line_obj = self.pool.get('account.move.line')
688         for account in self.browse(cr, uid, ids, context=context):
689             account_ids = self.search(cr, uid, [('id', 'child_of', [account.id])], context=context)
690             if line_obj.search(cr, uid, [('account_id', 'in', account_ids)], context=context):
691                 raise osv.except_osv(_('Warning !'), _("You cannot change the code of account which contains journal items!"))
692         return True
693
694     def write(self, cr, uid, ids, vals, context=None):
695         if context is None:
696             context = {}
697         if not ids:
698             return True
699         if isinstance(ids, (int, long)):
700             ids = [ids]
701
702         # Dont allow changing the company_id when account_move_line already exist
703         if 'company_id' in vals:
704             move_lines = self.pool.get('account.move.line').search(cr, uid, [('account_id', 'in', ids)], context=context)
705             if move_lines:
706                 # Allow the write if the value is the same
707                 for i in [i['company_id'][0] for i in self.read(cr,uid,ids,['company_id'], context=context)]:
708                     if vals['company_id']!=i:
709                         raise osv.except_osv(_('Warning!'), _('You cannot change the owner company of an account that already contains journal items.'))
710         if 'active' in vals and not vals['active']:
711             self._check_moves(cr, uid, ids, "write", context=context)
712         if 'type' in vals.keys():
713             self._check_allow_type_change(cr, uid, ids, vals['type'], context=context)
714         if 'code' in vals.keys():
715             self._check_allow_code_change(cr, uid, ids, context=context)
716         return super(account_account, self).write(cr, uid, ids, vals, context=context)
717
718     def unlink(self, cr, uid, ids, context=None):
719         self._check_moves(cr, uid, ids, "unlink", context=context)
720         return super(account_account, self).unlink(cr, uid, ids, context=context)
721
722
723 class account_journal(osv.osv):
724     _name = "account.journal"
725     _description = "Journal"
726     _columns = {
727         'with_last_closing_balance': fields.boolean('Opening With Last Closing Balance', help="For cash or bank journal, this option should be unchecked when the starting balance should always set to 0 for new documents."),
728         'name': fields.char('Journal Name', required=True),
729         'code': fields.char('Code', size=5, required=True, help="The code will be displayed on reports."),
730         'type': fields.selection([('sale', 'Sale'),('sale_refund','Sale Refund'), ('purchase', 'Purchase'), ('purchase_refund','Purchase Refund'), ('cash', 'Cash'), ('bank', 'Bank and Checks'), ('general', 'General'), ('situation', 'Opening/Closing Situation')], 'Type', size=32, required=True,
731                                  help="Select 'Sale' for customer invoices journals."\
732                                  " Select 'Purchase' for supplier invoices journals."\
733                                  " Select 'Cash' or 'Bank' for journals that are used in customer or supplier payments."\
734                                  " Select 'General' for miscellaneous operations journals."\
735                                  " Select 'Opening/Closing Situation' for entries generated for new fiscal years."),
736         'type_control_ids': fields.many2many('account.account.type', 'account_journal_type_rel', 'journal_id','type_id', 'Type Controls', domain=[('code','<>','view'), ('code', '<>', 'closed')]),
737         'account_control_ids': fields.many2many('account.account', 'account_account_type_rel', 'journal_id','account_id', 'Account', domain=[('type','<>','view'), ('type', '<>', 'closed')]),
738         'default_credit_account_id': fields.many2one('account.account', 'Default Credit Account', domain="[('type','!=','view')]", help="It acts as a default account for credit amount"),
739         'default_debit_account_id': fields.many2one('account.account', 'Default Debit Account', domain="[('type','!=','view')]", help="It acts as a default account for debit amount"),
740         'centralisation': fields.boolean('Centralized 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."),
741         'update_posted': fields.boolean('Allow Cancelling Entries', help="Check this box if you want to allow the cancellation the entries related to this journal or of the invoice related to this journal"),
742         '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."),
743         'sequence_id': fields.many2one('ir.sequence', 'Entry Sequence', help="This field contains the information related to the numbering of the journal entries of this journal.", required=True, copy=False),
744         'user_id': fields.many2one('res.users', 'User', help="The user responsible for this journal"),
745         'groups_id': fields.many2many('res.groups', 'account_journal_group_rel', 'journal_id', 'group_id', 'Groups'),
746         'currency': fields.many2one('res.currency', 'Currency', help='The currency used to enter statement'),
747         'entry_posted': fields.boolean('Autopost Created Moves', help='Check this box to automatically post entries of this journal. Note that legally, some entries may be automatically posted when the source document is validated (Invoices), whatever the status of this field.'),
748         'company_id': fields.many2one('res.company', 'Company', required=True, select=1, help="Company related to this journal"),
749         'allow_date':fields.boolean('Check Date in Period', help= 'If checked, the entry won\'t be created if the entry date is not included into the selected period'),
750         'profit_account_id' : fields.many2one('account.account', 'Profit Account'),
751         'loss_account_id' : fields.many2one('account.account', 'Loss Account'),
752         'internal_account_id' : fields.many2one('account.account', 'Internal Transfers Account', select=1),
753         'cash_control' : fields.boolean('Cash Control', help='If you want the journal should be control at opening/closing, check this option'),
754     }
755
756     _defaults = {
757         'cash_control' : False,
758         'with_last_closing_balance' : True,
759         'user_id': lambda self, cr, uid, context: uid,
760         'company_id': lambda self, cr, uid, c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
761     }
762     _sql_constraints = [
763         ('code_company_uniq', 'unique (code, company_id)', 'The code of the journal must be unique per company !'),
764         ('name_company_uniq', 'unique (name, company_id)', 'The name of the journal must be unique per company !'),
765     ]
766
767     _order = 'code'
768
769     def _check_currency(self, cr, uid, ids, context=None):
770         for journal in self.browse(cr, uid, ids, context=context):
771             if journal.currency:
772                 if journal.default_credit_account_id and not journal.default_credit_account_id.currency_id.id == journal.currency.id:
773                     return False
774                 if journal.default_debit_account_id and not journal.default_debit_account_id.currency_id.id == journal.currency.id:
775                     return False
776         return True
777
778     _constraints = [
779         (_check_currency, 'Configuration error!\nThe currency chosen should be shared by the default accounts too.', ['currency','default_debit_account_id','default_credit_account_id']),
780     ]
781
782     def copy(self, cr, uid, id, default=None, context=None):
783         default = dict(context or {})
784         journal = self.browse(cr, uid, id, context=context)
785         default.update(
786             code=_("%s (copy)") % (journal['code'] or ''),
787             name=_("%s (copy)") % (journal['name'] or ''))
788         return super(account_journal, self).copy(cr, uid, id, default, context=context)
789
790     def write(self, cr, uid, ids, vals, context=None):
791         if context is None:
792             context = {}
793         if isinstance(ids, (int, long)):
794             ids = [ids]
795         for journal in self.browse(cr, uid, ids, context=context):
796             if 'company_id' in vals and journal.company_id.id != vals['company_id']:
797                 move_lines = self.pool.get('account.move.line').search(cr, uid, [('journal_id', 'in', ids)])
798                 if move_lines:
799                     raise osv.except_osv(_('Warning!'), _('This journal already contains items, therefore you cannot modify its company field.'))
800         return super(account_journal, self).write(cr, uid, ids, vals, context=context)
801
802     def create_sequence(self, cr, uid, vals, context=None):
803         """ Create new no_gap entry sequence for every new Joural
804         """
805         # in account.journal code is actually the prefix of the sequence
806         # whereas ir.sequence code is a key to lookup global sequences.
807         prefix = vals['code'].upper()
808
809         seq = {
810             'name': vals['name'],
811             'implementation':'no_gap',
812             'prefix': prefix + "/%(year)s/",
813             'padding': 4,
814             'number_increment': 1
815         }
816         if 'company_id' in vals:
817             seq['company_id'] = vals['company_id']
818         return self.pool.get('ir.sequence').create(cr, uid, seq)
819
820     def create(self, cr, uid, vals, context=None):
821         if not 'sequence_id' in vals or not vals['sequence_id']:
822             # if we have the right to create a journal, we should be able to
823             # create it's sequence.
824             vals.update({'sequence_id': self.create_sequence(cr, SUPERUSER_ID, vals, context)})
825         return super(account_journal, self).create(cr, uid, vals, context)
826
827     def name_get(self, cr, user, ids, context=None):
828         """
829         Returns a list of tupples containing id, name.
830         result format: {[(id, name), (id, name), ...]}
831
832         @param cr: A database cursor
833         @param user: ID of the user currently logged in
834         @param ids: list of ids for which name should be read
835         @param context: context arguments, like lang, time zone
836
837         @return: Returns a list of tupples containing id, name
838         """
839         if not ids:
840             return []
841         if isinstance(ids, (int, long)):
842             ids = [ids]
843         result = self.browse(cr, user, ids, context=context)
844         res = []
845         for rs in result:
846             if rs.currency:
847                 currency = rs.currency
848             else:
849                 currency = rs.company_id.currency_id
850             name = "%s (%s)" % (rs.name, currency.name)
851             res += [(rs.id, name)]
852         return res
853
854     def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=100):
855         if not args:
856             args = []
857         if operator in expression.NEGATIVE_TERM_OPERATORS:
858             domain = [('code', operator, name), ('name', operator, name)]
859         else:
860             domain = ['|', ('code', operator, name), ('name', operator, name)]
861         ids = self.search(cr, user, expression.AND([domain, args]), limit=limit, context=context)
862         return self.name_get(cr, user, ids, context=context)
863
864
865 class account_fiscalyear(osv.osv):
866     _name = "account.fiscalyear"
867     _description = "Fiscal Year"
868     _columns = {
869         'name': fields.char('Fiscal Year', required=True),
870         'code': fields.char('Code', size=6, required=True),
871         'company_id': fields.many2one('res.company', 'Company', required=True),
872         'date_start': fields.date('Start Date', required=True),
873         'date_stop': fields.date('End Date', required=True),
874         'period_ids': fields.one2many('account.period', 'fiscalyear_id', 'Periods'),
875         'state': fields.selection([('draft','Open'), ('done','Closed')], 'Status', readonly=True, copy=False),
876         'end_journal_period_id': fields.many2one(
877              'account.journal.period', 'End of Year Entries Journal',
878              readonly=True, copy=False),
879     }
880     _defaults = {
881         'state': 'draft',
882         'company_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
883     }
884     _order = "date_start, id"
885
886
887     def _check_duration(self, cr, uid, ids, context=None):
888         obj_fy = self.browse(cr, uid, ids[0], context=context)
889         if obj_fy.date_stop < obj_fy.date_start:
890             return False
891         return True
892
893     _constraints = [
894         (_check_duration, 'Error!\nThe start date of a fiscal year must precede its end date.', ['date_start','date_stop'])
895     ]
896
897     def create_period3(self, cr, uid, ids, context=None):
898         return self.create_period(cr, uid, ids, context, 3)
899
900     def create_period(self, cr, uid, ids, context=None, interval=1):
901         period_obj = self.pool.get('account.period')
902         for fy in self.browse(cr, uid, ids, context=context):
903             ds = datetime.strptime(fy.date_start, '%Y-%m-%d')
904             period_obj.create(cr, uid, {
905                     'name':  "%s %s" % (_('Opening Period'), ds.strftime('%Y')),
906                     'code': ds.strftime('00/%Y'),
907                     'date_start': ds,
908                     'date_stop': ds,
909                     'special': True,
910                     'fiscalyear_id': fy.id,
911                 })
912             while ds.strftime('%Y-%m-%d') < fy.date_stop:
913                 de = ds + relativedelta(months=interval, days=-1)
914
915                 if de.strftime('%Y-%m-%d') > fy.date_stop:
916                     de = datetime.strptime(fy.date_stop, '%Y-%m-%d')
917
918                 period_obj.create(cr, uid, {
919                     'name': ds.strftime('%m/%Y'),
920                     'code': ds.strftime('%m/%Y'),
921                     'date_start': ds.strftime('%Y-%m-%d'),
922                     'date_stop': de.strftime('%Y-%m-%d'),
923                     'fiscalyear_id': fy.id,
924                 })
925                 ds = ds + relativedelta(months=interval)
926         return True
927
928     def find(self, cr, uid, dt=None, exception=True, context=None):
929         res = self.finds(cr, uid, dt, exception, context=context)
930         return res and res[0] or False
931
932     def finds(self, cr, uid, dt=None, exception=True, context=None):
933         if context is None: context = {}
934         if not dt:
935             dt = fields.date.context_today(self,cr,uid,context=context)
936         args = [('date_start', '<=' ,dt), ('date_stop', '>=', dt)]
937         if context.get('company_id', False):
938             company_id = context['company_id']
939         else:
940             company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id
941         args.append(('company_id', '=', company_id))
942         ids = self.search(cr, uid, args, context=context)
943         if not ids:
944             if exception:
945                 model, action_id = self.pool['ir.model.data'].get_object_reference(cr, uid, 'account', 'action_account_fiscalyear')
946                 msg = _('There is no period defined for this date: %s.\nPlease go to Configuration/Periods and configure a fiscal year.') % dt
947                 raise openerp.exceptions.RedirectWarning(msg, action_id, _('Go to the configuration panel'))
948             else:
949                 return []
950         return ids
951
952     def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=80):
953         if args is None:
954             args = []
955         if operator in expression.NEGATIVE_TERM_OPERATORS:
956             domain = [('code', operator, name), ('name', operator, name)]
957         else:
958             domain = ['|', ('code', operator, name), ('name', operator, name)]
959         ids = self.search(cr, user, expression.AND([domain, args]), limit=limit, context=context)
960         return self.name_get(cr, user, ids, context=context)
961
962
963 class account_period(osv.osv):
964     _name = "account.period"
965     _description = "Account period"
966     _columns = {
967         'name': fields.char('Period Name', required=True),
968         'code': fields.char('Code', size=12),
969         'special': fields.boolean('Opening/Closing Period',help="These periods can overlap."),
970         'date_start': fields.date('Start of Period', required=True, states={'done':[('readonly',True)]}),
971         'date_stop': fields.date('End of Period', required=True, states={'done':[('readonly',True)]}),
972         'fiscalyear_id': fields.many2one('account.fiscalyear', 'Fiscal Year', required=True, states={'done':[('readonly',True)]}, select=True),
973         'state': fields.selection([('draft','Open'), ('done','Closed')], 'Status', readonly=True, copy=False,
974                                   help='When monthly periods are created. The status is \'Draft\'. At the end of monthly period it is in \'Done\' status.'),
975         'company_id': fields.related('fiscalyear_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True)
976     }
977     _defaults = {
978         'state': 'draft',
979     }
980     _order = "date_start, special desc"
981     _sql_constraints = [
982         ('name_company_uniq', 'unique(name, company_id)', 'The name of the period must be unique per company!'),
983     ]
984
985     def _check_duration(self,cr,uid,ids,context=None):
986         obj_period = self.browse(cr, uid, ids[0], context=context)
987         if obj_period.date_stop < obj_period.date_start:
988             return False
989         return True
990
991     def _check_year_limit(self,cr,uid,ids,context=None):
992         for obj_period in self.browse(cr, uid, ids, context=context):
993             if obj_period.special:
994                 continue
995
996             if obj_period.fiscalyear_id.date_stop < obj_period.date_stop or \
997                obj_period.fiscalyear_id.date_stop < obj_period.date_start or \
998                obj_period.fiscalyear_id.date_start > obj_period.date_start or \
999                obj_period.fiscalyear_id.date_start > obj_period.date_stop:
1000                 return False
1001
1002             pids = self.search(cr, uid, [('date_stop','>=',obj_period.date_start),('date_start','<=',obj_period.date_stop),('special','=',False),('id','<>',obj_period.id)])
1003             for period in self.browse(cr, uid, pids):
1004                 if period.fiscalyear_id.company_id.id==obj_period.fiscalyear_id.company_id.id:
1005                     return False
1006         return True
1007
1008     _constraints = [
1009         (_check_duration, 'Error!\nThe duration of the Period(s) is/are invalid.', ['date_stop']),
1010         (_check_year_limit, 'Error!\nThe period is invalid. Either some periods are overlapping or the period\'s dates are not matching the scope of the fiscal year.', ['date_stop'])
1011     ]
1012
1013     @api.returns('self')
1014     def next(self, cr, uid, period, step, context=None):
1015         ids = self.search(cr, uid, [('date_start','>',period.date_start)])
1016         if len(ids)>=step:
1017             return ids[step-1]
1018         return False
1019
1020     @api.returns('self')
1021     def find(self, cr, uid, dt=None, context=None):
1022         if context is None: context = {}
1023         if not dt:
1024             dt = fields.date.context_today(self, cr, uid, context=context)
1025         args = [('date_start', '<=' ,dt), ('date_stop', '>=', dt)]
1026         if context.get('company_id', False):
1027             args.append(('company_id', '=', context['company_id']))
1028         else:
1029             company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id
1030             args.append(('company_id', '=', company_id))
1031         result = []
1032         if context.get('account_period_prefer_normal', True):
1033             # look for non-special periods first, and fallback to all if no result is found
1034             result = self.search(cr, uid, args + [('special', '=', False)], context=context)
1035         if not result:
1036             result = self.search(cr, uid, args, context=context)
1037         if not result:
1038             model, action_id = self.pool['ir.model.data'].get_object_reference(cr, uid, 'account', 'action_account_period')
1039             msg = _('There is no period defined for this date: %s.\nPlease go to Configuration/Periods.') % dt
1040             raise openerp.exceptions.RedirectWarning(msg, action_id, _('Go to the configuration panel'))
1041         return result
1042
1043     def action_draft(self, cr, uid, ids, context=None):
1044         mode = 'draft'
1045         for period in self.browse(cr, uid, ids):
1046             if period.fiscalyear_id.state == 'done':
1047                 raise osv.except_osv(_('Warning!'), _('You can not re-open a period which belongs to closed fiscal year'))
1048         cr.execute('update account_journal_period set state=%s where period_id in %s', (mode, tuple(ids),))
1049         cr.execute('update account_period set state=%s where id in %s', (mode, tuple(ids),))
1050         self.invalidate_cache(cr, uid, context=context)
1051         return True
1052
1053     def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=100):
1054         if args is None:
1055             args = []
1056         if operator in expression.NEGATIVE_TERM_OPERATORS:
1057             domain = [('code', operator, name), ('name', operator, name)]
1058         else:
1059             domain = ['|', ('code', operator, name), ('name', operator, name)]
1060         ids = self.search(cr, user, expression.AND([domain, args]), limit=limit, context=context)
1061         return self.name_get(cr, user, ids, context=context)
1062
1063     def write(self, cr, uid, ids, vals, context=None):
1064         if 'company_id' in vals:
1065             move_lines = self.pool.get('account.move.line').search(cr, uid, [('period_id', 'in', ids)])
1066             if move_lines:
1067                 raise osv.except_osv(_('Warning!'), _('This journal already contains items for this period, therefore you cannot modify its company field.'))
1068         return super(account_period, self).write(cr, uid, ids, vals, context=context)
1069
1070     def build_ctx_periods(self, cr, uid, period_from_id, period_to_id):
1071         if period_from_id == period_to_id:
1072             return [period_from_id]
1073         period_from = self.browse(cr, uid, period_from_id)
1074         period_date_start = period_from.date_start
1075         company1_id = period_from.company_id.id
1076         period_to = self.browse(cr, uid, period_to_id)
1077         period_date_stop = period_to.date_stop
1078         company2_id = period_to.company_id.id
1079         if company1_id != company2_id:
1080             raise osv.except_osv(_('Error!'), _('You should choose the periods that belong to the same company.'))
1081         if period_date_start > period_date_stop:
1082             raise osv.except_osv(_('Error!'), _('Start period should precede then end period.'))
1083
1084         # /!\ We do not include a criterion on the company_id field below, to allow producing consolidated reports
1085         # on multiple companies. It will only work when start/end periods are selected and no fiscal year is chosen.
1086
1087         #for period from = january, we want to exclude the opening period (but it has same date_from, so we have to check if period_from is special or not to include that clause or not in the search).
1088         if period_from.special:
1089             return self.search(cr, uid, [('date_start', '>=', period_date_start), ('date_stop', '<=', period_date_stop)])
1090         return self.search(cr, uid, [('date_start', '>=', period_date_start), ('date_stop', '<=', period_date_stop), ('special', '=', False)])
1091
1092
1093 class account_journal_period(osv.osv):
1094     _name = "account.journal.period"
1095     _description = "Journal Period"
1096
1097     def _icon_get(self, cr, uid, ids, field_name, arg=None, context=None):
1098         result = {}.fromkeys(ids, 'STOCK_NEW')
1099         for r in self.read(cr, uid, ids, ['state']):
1100             result[r['id']] = {
1101                 'draft': 'STOCK_NEW',
1102                 'printed': 'STOCK_PRINT_PREVIEW',
1103                 'done': 'STOCK_DIALOG_AUTHENTICATION',
1104             }.get(r['state'], 'STOCK_NEW')
1105         return result
1106
1107     _columns = {
1108         'name': fields.char('Journal-Period Name', required=True),
1109         'journal_id': fields.many2one('account.journal', 'Journal', required=True, ondelete="cascade"),
1110         'period_id': fields.many2one('account.period', 'Period', required=True, ondelete="cascade"),
1111         'icon': fields.function(_icon_get, string='Icon', type='char'),
1112         'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the journal period without removing it."),
1113         'state': fields.selection([('draft','Draft'), ('printed','Printed'), ('done','Done')], 'Status', required=True, readonly=True,
1114                                   help='When journal period is created. The status is \'Draft\'. If a report is printed it comes to \'Printed\' status. When all transactions are done, it comes in \'Done\' status.'),
1115         'fiscalyear_id': fields.related('period_id', 'fiscalyear_id', string='Fiscal Year', type='many2one', relation='account.fiscalyear'),
1116         'company_id': fields.related('journal_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True)
1117     }
1118
1119     def _check(self, cr, uid, ids, context=None):
1120         for obj in self.browse(cr, uid, ids, context=context):
1121             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))
1122             res = cr.fetchall()
1123             if res:
1124                 raise osv.except_osv(_('Error!'), _('You cannot modify/delete a journal with entries for this period.'))
1125         return True
1126
1127     def write(self, cr, uid, ids, vals, context=None):
1128         self._check(cr, uid, ids, context=context)
1129         return super(account_journal_period, self).write(cr, uid, ids, vals, context=context)
1130
1131     def create(self, cr, uid, vals, context=None):
1132         period_id = vals.get('period_id',False)
1133         if period_id:
1134             period = self.pool.get('account.period').browse(cr, uid, period_id, context=context)
1135             vals['state']=period.state
1136         return super(account_journal_period, self).create(cr, uid, vals, context)
1137
1138     def unlink(self, cr, uid, ids, context=None):
1139         self._check(cr, uid, ids, context=context)
1140         return super(account_journal_period, self).unlink(cr, uid, ids, context=context)
1141
1142     _defaults = {
1143         'state': 'draft',
1144         'active': True,
1145     }
1146     _order = "period_id"
1147
1148 #----------------------------------------------------------
1149 # Entries
1150 #----------------------------------------------------------
1151 class account_move(osv.osv):
1152     _name = "account.move"
1153     _description = "Account Entry"
1154     _order = 'id desc'
1155
1156     def account_assert_balanced(self, cr, uid, context=None):
1157         cr.execute("""\
1158             SELECT      move_id
1159             FROM        account_move_line
1160             WHERE       state = 'valid'
1161             GROUP BY    move_id
1162             HAVING      abs(sum(debit) - sum(credit)) > 0.00001
1163             """)
1164         assert len(cr.fetchall()) == 0, \
1165             "For all Journal Items, the state is valid implies that the sum " \
1166             "of credits equals the sum of debits"
1167         return True
1168
1169     def account_move_prepare(self, cr, uid, journal_id, date=False, ref='', company_id=False, context=None):
1170         '''
1171         Prepares and returns a dictionary of values, ready to be passed to create() based on the parameters received.
1172         '''
1173         if not date:
1174             date = fields.date.today()
1175         period_obj = self.pool.get('account.period')
1176         if not company_id:
1177             user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
1178             company_id = user.company_id.id
1179         if context is None:
1180             context = {}
1181         #put the company in context to find the good period
1182         ctx = context.copy()
1183         ctx.update({'company_id': company_id})
1184         return {
1185             'journal_id': journal_id,
1186             'date': date,
1187             'period_id': period_obj.find(cr, uid, date, context=ctx)[0],
1188             'ref': ref,
1189             'company_id': company_id,
1190         }
1191
1192     def name_get(self, cursor, user, ids, context=None):
1193         if isinstance(ids, (int, long)):
1194             ids = [ids]
1195         if not ids:
1196             return []
1197         res = []
1198         data_move = self.pool.get('account.move').browse(cursor, user, ids, context=context)
1199         for move in data_move:
1200             if move.state=='draft':
1201                 name = '*' + str(move.id)
1202             else:
1203                 name = move.name
1204             res.append((move.id, name))
1205         return res
1206
1207     def _get_period(self, cr, uid, context=None):
1208         ctx = dict(context or {})
1209         period_ids = self.pool.get('account.period').find(cr, uid, context=ctx)
1210         return period_ids[0]
1211
1212     def _amount_compute(self, cr, uid, ids, name, args, context, where =''):
1213         if not ids: return {}
1214         cr.execute( 'SELECT move_id, SUM(debit) '\
1215                     'FROM account_move_line '\
1216                     'WHERE move_id IN %s '\
1217                     'GROUP BY move_id', (tuple(ids),))
1218         result = dict(cr.fetchall())
1219         for id in ids:
1220             result.setdefault(id, 0.0)
1221         return result
1222
1223     def _search_amount(self, cr, uid, obj, name, args, context):
1224         ids = set()
1225         for cond in args:
1226             amount = cond[2]
1227             if isinstance(cond[2],(list,tuple)):
1228                 if cond[1] in ['in','not in']:
1229                     amount = tuple(cond[2])
1230                 else:
1231                     continue
1232             else:
1233                 if cond[1] in ['=like', 'like', 'not like', 'ilike', 'not ilike', 'in', 'not in', 'child_of']:
1234                     continue
1235
1236             cr.execute("select move_id from account_move_line group by move_id having sum(debit) %s %%s" % (cond[1]),(amount,))
1237             res_ids = set(id[0] for id in cr.fetchall())
1238             ids = ids and (ids & res_ids) or res_ids
1239         if ids:
1240             return [('id', 'in', tuple(ids))]
1241         return [('id', '=', '0')]
1242
1243     def _get_move_from_lines(self, cr, uid, ids, context=None):
1244         line_obj = self.pool.get('account.move.line')
1245         return [line.move_id.id for line in line_obj.browse(cr, uid, ids, context=context)]
1246
1247     _columns = {
1248         'name': fields.char('Number', required=True, copy=False),
1249         'ref': fields.char('Reference', copy=False),
1250         'period_id': fields.many2one('account.period', 'Period', required=True, states={'posted':[('readonly',True)]}),
1251         'journal_id': fields.many2one('account.journal', 'Journal', required=True, states={'posted':[('readonly',True)]}),
1252         'state': fields.selection(
1253               [('draft','Unposted'), ('posted','Posted')], 'Status',
1254               required=True, readonly=True, copy=False,
1255               help='All manually created new journal entries are usually in the status \'Unposted\', '
1256                    'but you can set the option to skip that status on the related journal. '
1257                    'In that case, they will behave as journal entries automatically created by the '
1258                    'system on document validation (invoices, bank statements...) and will be created '
1259                    'in \'Posted\' status.'),
1260         'line_id': fields.one2many('account.move.line', 'move_id', 'Entries',
1261                                    states={'posted':[('readonly',True)]},
1262                                    copy=True),
1263         'to_check': fields.boolean('To Review', help='Check this box if you are unsure of that journal entry and if you want to note it as \'to be reviewed\' by an accounting expert.'),
1264         'partner_id': fields.related('line_id', 'partner_id', type="many2one", relation="res.partner", string="Partner", store={
1265             _name: (lambda self, cr,uid,ids,c: ids, ['line_id'], 10),
1266             'account.move.line': (_get_move_from_lines, ['partner_id'],10)
1267             }),
1268         'amount': fields.function(_amount_compute, string='Amount', digits_compute=dp.get_precision('Account'), type='float', fnct_search=_search_amount),
1269         'date': fields.date('Date', required=True, states={'posted':[('readonly',True)]}, select=True),
1270         'narration':fields.text('Internal Note'),
1271         'company_id': fields.related('journal_id','company_id',type='many2one',relation='res.company',string='Company', store=True, readonly=True),
1272         'balance': fields.float('balance', digits_compute=dp.get_precision('Account'), help="This is a field only used for internal purpose and shouldn't be displayed"),
1273     }
1274
1275     _defaults = {
1276         'name': '/',
1277         'state': 'draft',
1278         'period_id': _get_period,
1279         'date': fields.date.context_today,
1280         'company_id': lambda self, cr, uid, c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
1281     }
1282
1283     def _check_centralisation(self, cursor, user, ids, context=None):
1284         for move in self.browse(cursor, user, ids, context=context):
1285             if move.journal_id.centralisation:
1286                 move_ids = self.search(cursor, user, [
1287                     ('period_id', '=', move.period_id.id),
1288                     ('journal_id', '=', move.journal_id.id),
1289                     ])
1290                 if len(move_ids) > 1:
1291                     return False
1292         return True
1293
1294     _constraints = [
1295         (_check_centralisation,
1296             'You cannot create more than one move per period on a centralized journal.',
1297             ['journal_id']),
1298     ]
1299
1300     def post(self, cr, uid, ids, context=None):
1301         if context is None:
1302             context = {}
1303         invoice = context.get('invoice', False)
1304         valid_moves = self.validate(cr, uid, ids, context)
1305
1306         if not valid_moves:
1307             raise osv.except_osv(_('Error!'), _('You cannot validate a non-balanced entry.\nMake sure you have configured payment terms properly.\nThe latest payment term line should be of the "Balance" type.'))
1308         obj_sequence = self.pool.get('ir.sequence')
1309         for move in self.browse(cr, uid, valid_moves, context=context):
1310             if move.name =='/':
1311                 new_name = False
1312                 journal = move.journal_id
1313
1314                 if invoice and invoice.internal_number:
1315                     new_name = invoice.internal_number
1316                 else:
1317                     if journal.sequence_id:
1318                         c = {'fiscalyear_id': move.period_id.fiscalyear_id.id}
1319                         new_name = obj_sequence.next_by_id(cr, uid, journal.sequence_id.id, c)
1320                     else:
1321                         raise osv.except_osv(_('Error!'), _('Please define a sequence on the journal.'))
1322
1323                 if new_name:
1324                     self.write(cr, uid, [move.id], {'name':new_name})
1325
1326         cr.execute('UPDATE account_move '\
1327                    'SET state=%s '\
1328                    'WHERE id IN %s',
1329                    ('posted', tuple(valid_moves),))
1330         self.invalidate_cache(cr, uid, context=context)
1331         return True
1332
1333     def button_validate(self, cursor, user, ids, context=None):
1334         for move in self.browse(cursor, user, ids, context=context):
1335             # check that all accounts have the same topmost ancestor
1336             top_common = None
1337             for line in move.line_id:
1338                 account = line.account_id
1339                 top_account = account
1340                 while top_account.parent_id:
1341                     top_account = top_account.parent_id
1342                 if not top_common:
1343                     top_common = top_account
1344                 elif top_account.id != top_common.id:
1345                     raise osv.except_osv(_('Error!'),
1346                                          _('You cannot validate this journal entry because account "%s" does not belong to chart of accounts "%s".') % (account.name, top_common.name))
1347         return self.post(cursor, user, ids, context=context)
1348
1349     def button_cancel(self, cr, uid, ids, context=None):
1350         for line in self.browse(cr, uid, ids, context=context):
1351             if not line.journal_id.update_posted:
1352                 raise osv.except_osv(_('Error!'), _('You cannot modify a posted entry of this journal.\nFirst you should set the journal to allow cancelling entries.'))
1353         if ids:
1354             cr.execute('UPDATE account_move '\
1355                        'SET state=%s '\
1356                        'WHERE id IN %s', ('draft', tuple(ids),))
1357             self.invalidate_cache(cr, uid, context=context)
1358         return True
1359
1360     def write(self, cr, uid, ids, vals, context=None):
1361         if context is None:
1362             context = {}
1363         c = context.copy()
1364         c['novalidate'] = True
1365         result = super(account_move, self).write(cr, uid, ids, vals, c)
1366         self.validate(cr, uid, ids, context=context)
1367         return result
1368
1369     #
1370     # TODO: Check if period is closed !
1371     #
1372     def create(self, cr, uid, vals, context=None):
1373         context = dict(context or {})
1374         if vals.get('line_id'):
1375             if vals.get('journal_id'):
1376                 for l in vals['line_id']:
1377                     if not l[0]:
1378                         l[2]['journal_id'] = vals['journal_id']
1379                 context['journal_id'] = vals['journal_id']
1380             if 'period_id' in vals:
1381                 for l in vals['line_id']:
1382                     if not l[0]:
1383                         l[2]['period_id'] = vals['period_id']
1384                 context['period_id'] = vals['period_id']
1385             else:
1386                 default_period = self._get_period(cr, uid, context)
1387                 for l in vals['line_id']:
1388                     if not l[0]:
1389                         l[2]['period_id'] = default_period
1390                 context['period_id'] = default_period
1391
1392             c = context.copy()
1393             c['novalidate'] = True
1394             c['period_id'] = vals['period_id'] if 'period_id' in vals else self._get_period(cr, uid, context)
1395             c['journal_id'] = vals['journal_id']
1396             if 'date' in vals: c['date'] = vals['date']
1397             result = super(account_move, self).create(cr, uid, vals, c)
1398             tmp = self.validate(cr, uid, [result], context)
1399             journal = self.pool.get('account.journal').browse(cr, uid, vals['journal_id'], context)
1400             if journal.entry_posted and tmp:
1401                 self.button_validate(cr,uid, [result], context)
1402         else:
1403             result = super(account_move, self).create(cr, uid, vals, context)
1404         return result
1405
1406     def unlink(self, cr, uid, ids, context=None, check=True):
1407         context = dict(context or {})
1408         if isinstance(ids, (int, long)):
1409             ids = [ids]
1410         toremove = []
1411         obj_move_line = self.pool.get('account.move.line')
1412         for move in self.browse(cr, uid, ids, context=context):
1413             if move['state'] != 'draft':
1414                 raise osv.except_osv(_('User Error!'),
1415                         _('You cannot delete a posted journal entry "%s".') % \
1416                                 move['name'])
1417             for line in move.line_id:
1418                 if line.invoice:
1419                     raise osv.except_osv(_('User Error!'),
1420                             _("Move cannot be deleted if linked to an invoice. (Invoice: %s - Move ID:%s)") % \
1421                                     (line.invoice.number,move.name))
1422             line_ids = map(lambda x: x.id, move.line_id)
1423             context['journal_id'] = move.journal_id.id
1424             context['period_id'] = move.period_id.id
1425             obj_move_line._update_check(cr, uid, line_ids, context)
1426             obj_move_line.unlink(cr, uid, line_ids, context=context)
1427             toremove.append(move.id)
1428         result = super(account_move, self).unlink(cr, uid, toremove, context)
1429         return result
1430
1431     def _compute_balance(self, cr, uid, id, context=None):
1432         move = self.browse(cr, uid, id, context=context)
1433         amount = 0
1434         for line in move.line_id:
1435             amount+= (line.debit - line.credit)
1436         return amount
1437
1438     def _centralise(self, cr, uid, move, mode, context=None):
1439         assert mode in ('debit', 'credit'), 'Invalid Mode' #to prevent sql injection
1440         currency_obj = self.pool.get('res.currency')
1441         account_move_line_obj = self.pool.get('account.move.line')
1442         context = dict(context or {})
1443
1444         if mode=='credit':
1445             account_id = move.journal_id.default_debit_account_id.id
1446             mode2 = 'debit'
1447             if not account_id:
1448                 raise osv.except_osv(_('User Error!'),
1449                         _('There is no default debit account defined \n' \
1450                                 'on journal "%s".') % move.journal_id.name)
1451         else:
1452             account_id = move.journal_id.default_credit_account_id.id
1453             mode2 = 'credit'
1454             if not account_id:
1455                 raise osv.except_osv(_('User Error!'),
1456                         _('There is no default credit account defined \n' \
1457                                 'on journal "%s".') % move.journal_id.name)
1458
1459         # find the first line of this move with the current mode
1460         # or create it if it doesn't exist
1461         cr.execute('select id from account_move_line where move_id=%s and centralisation=%s limit 1', (move.id, mode))
1462         res = cr.fetchone()
1463         if res:
1464             line_id = res[0]
1465         else:
1466             context.update({'journal_id': move.journal_id.id, 'period_id': move.period_id.id})
1467             line_id = account_move_line_obj.create(cr, uid, {
1468                 'name': _(mode.capitalize()+' Centralisation'),
1469                 'centralisation': mode,
1470                 'partner_id': False,
1471                 'account_id': account_id,
1472                 'move_id': move.id,
1473                 'journal_id': move.journal_id.id,
1474                 'period_id': move.period_id.id,
1475                 'date': move.period_id.date_stop,
1476                 'debit': 0.0,
1477                 'credit': 0.0,
1478             }, context)
1479
1480         # find the first line of this move with the other mode
1481         # so that we can exclude it from our calculation
1482         cr.execute('select id from account_move_line where move_id=%s and centralisation=%s limit 1', (move.id, mode2))
1483         res = cr.fetchone()
1484         if res:
1485             line_id2 = res[0]
1486         else:
1487             line_id2 = 0
1488
1489         cr.execute('SELECT SUM(%s) FROM account_move_line WHERE move_id=%%s AND id!=%%s' % (mode,), (move.id, line_id2))
1490         result = cr.fetchone()[0] or 0.0
1491         cr.execute('update account_move_line set '+mode2+'=%s where id=%s', (result, line_id))
1492         account_move_line_obj.invalidate_cache(cr, uid, [mode2], [line_id], context=context)
1493
1494         #adjust also the amount in currency if needed
1495         cr.execute("select currency_id, sum(amount_currency) as amount_currency from account_move_line where move_id = %s and currency_id is not null group by currency_id", (move.id,))
1496         for row in cr.dictfetchall():
1497             currency_id = currency_obj.browse(cr, uid, row['currency_id'], context=context)
1498             if not currency_obj.is_zero(cr, uid, currency_id, row['amount_currency']):
1499                 amount_currency = row['amount_currency'] * -1
1500                 account_id = amount_currency > 0 and move.journal_id.default_debit_account_id.id or move.journal_id.default_credit_account_id.id
1501                 cr.execute('select id from account_move_line where move_id=%s and centralisation=\'currency\' and currency_id = %slimit 1', (move.id, row['currency_id']))
1502                 res = cr.fetchone()
1503                 if res:
1504                     cr.execute('update account_move_line set amount_currency=%s , account_id=%s where id=%s', (amount_currency, account_id, res[0]))
1505                     account_move_line_obj.invalidate_cache(cr, uid, ['amount_currency', 'account_id'], [res[0]], context=context)
1506                 else:
1507                     context.update({'journal_id': move.journal_id.id, 'period_id': move.period_id.id})
1508                     line_id = account_move_line_obj.create(cr, uid, {
1509                         'name': _('Currency Adjustment'),
1510                         'centralisation': 'currency',
1511                         'partner_id': False,
1512                         'account_id': account_id,
1513                         'move_id': move.id,
1514                         'journal_id': move.journal_id.id,
1515                         'period_id': move.period_id.id,
1516                         'date': move.period_id.date_stop,
1517                         'debit': 0.0,
1518                         'credit': 0.0,
1519                         'currency_id': row['currency_id'],
1520                         'amount_currency': amount_currency,
1521                     }, context)
1522
1523         return True
1524
1525     #
1526     # Validate a balanced move. If it is a centralised journal, create a move.
1527     #
1528     def validate(self, cr, uid, ids, context=None):
1529         if context and ('__last_update' in context):
1530             del context['__last_update']
1531
1532         valid_moves = [] #Maintains a list of moves which can be responsible to create analytic entries
1533         obj_analytic_line = self.pool.get('account.analytic.line')
1534         obj_move_line = self.pool.get('account.move.line')
1535         for move in self.browse(cr, uid, ids, context):
1536             journal = move.journal_id
1537             amount = 0
1538             line_ids = []
1539             line_draft_ids = []
1540             company_id = None
1541             for line in move.line_id:
1542                 amount += line.debit - line.credit
1543                 line_ids.append(line.id)
1544                 if line.state=='draft':
1545                     line_draft_ids.append(line.id)
1546
1547                 if not company_id:
1548                     company_id = line.account_id.company_id.id
1549                 if not company_id == line.account_id.company_id.id:
1550                     raise osv.except_osv(_('Error!'), _("Cannot create moves for different companies."))
1551
1552                 if line.account_id.currency_id and line.currency_id:
1553                     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):
1554                         raise osv.except_osv(_('Error!'), _("""Cannot create move with currency different from ..""") % (line.account_id.code, line.account_id.name))
1555
1556             if abs(amount) < 10 ** -4:
1557                 # If the move is balanced
1558                 # Add to the list of valid moves
1559                 # (analytic lines will be created later for valid moves)
1560                 valid_moves.append(move)
1561
1562                 # Check whether the move lines are confirmed
1563
1564                 if not line_draft_ids:
1565                     continue
1566                 # Update the move lines (set them as valid)
1567
1568                 obj_move_line.write(cr, uid, line_draft_ids, {
1569                     'state': 'valid'
1570                 }, context, check=False)
1571
1572                 account = {}
1573                 account2 = {}
1574
1575                 if journal.type in ('purchase','sale'):
1576                     for line in move.line_id:
1577                         code = amount = 0
1578                         key = (line.account_id.id, line.tax_code_id.id)
1579                         if key in account2:
1580                             code = account2[key][0]
1581                             amount = account2[key][1] * (line.debit + line.credit)
1582                         elif line.account_id.id in account:
1583                             code = account[line.account_id.id][0]
1584                             amount = account[line.account_id.id][1] * (line.debit + line.credit)
1585                         if (code or amount) and not (line.tax_code_id or line.tax_amount):
1586                             obj_move_line.write(cr, uid, [line.id], {
1587                                 'tax_code_id': code,
1588                                 'tax_amount': amount
1589                             }, context, check=False)
1590             elif journal.centralisation:
1591                 # If the move is not balanced, it must be centralised...
1592
1593                 # Add to the list of valid moves
1594                 # (analytic lines will be created later for valid moves)
1595                 valid_moves.append(move)
1596
1597                 #
1598                 # Update the move lines (set them as valid)
1599                 #
1600                 self._centralise(cr, uid, move, 'debit', context=context)
1601                 self._centralise(cr, uid, move, 'credit', context=context)
1602                 obj_move_line.write(cr, uid, line_draft_ids, {
1603                     'state': 'valid'
1604                 }, context, check=False)
1605             else:
1606                 # We can't validate it (it's unbalanced)
1607                 # Setting the lines as draft
1608                 not_draft_line_ids = list(set(line_ids) - set(line_draft_ids))
1609                 if not_draft_line_ids:
1610                     obj_move_line.write(cr, uid, not_draft_line_ids, {
1611                         'state': 'draft'
1612                     }, context, check=False)
1613         # Create analytic lines for the valid moves
1614         for record in valid_moves:
1615             obj_move_line.create_analytic_lines(cr, uid, [line.id for line in record.line_id], context)
1616
1617         valid_moves = [move.id for move in valid_moves]
1618         return len(valid_moves) > 0 and valid_moves or False
1619
1620
1621 class account_move_reconcile(osv.osv):
1622     _name = "account.move.reconcile"
1623     _description = "Account Reconciliation"
1624     _columns = {
1625         'name': fields.char('Name', required=True),
1626         'type': fields.char('Type', required=True),
1627         'line_id': fields.one2many('account.move.line', 'reconcile_id', 'Entry Lines'),
1628         'line_partial_ids': fields.one2many('account.move.line', 'reconcile_partial_id', 'Partial Entry lines'),
1629         'create_date': fields.date('Creation date', readonly=True),
1630         'opening_reconciliation': fields.boolean('Opening Entries Reconciliation', help="Is this reconciliation produced by the opening of a new fiscal year ?."),
1631     }
1632     _defaults = {
1633         'name': lambda self,cr,uid,ctx=None: self.pool.get('ir.sequence').get(cr, uid, 'account.reconcile', context=ctx) or '/',
1634     }
1635     
1636     # You cannot unlink a reconciliation if it is a opening_reconciliation one,
1637     # you should use the generate opening entries wizard for that
1638     def unlink(self, cr, uid, ids, context=None):
1639         for move_rec in self.browse(cr, uid, ids, context=context):
1640             if move_rec.opening_reconciliation:
1641                 raise osv.except_osv(_('Error!'), _('You cannot unreconcile journal items if they has been generated by the \
1642                                                         opening/closing fiscal year process.'))
1643         return super(account_move_reconcile, self).unlink(cr, uid, ids, context=context)
1644     
1645     # Look in the line_id and line_partial_ids to ensure the partner is the same or empty
1646     # on all lines. We allow that only for opening/closing period
1647     def _check_same_partner(self, cr, uid, ids, context=None):
1648         for reconcile in self.browse(cr, uid, ids, context=context):
1649             move_lines = []
1650             if not reconcile.opening_reconciliation:
1651                 if reconcile.line_id:
1652                     first_partner = reconcile.line_id[0].partner_id.id
1653                     move_lines = reconcile.line_id
1654                 elif reconcile.line_partial_ids:
1655                     first_partner = reconcile.line_partial_ids[0].partner_id.id
1656                     move_lines = reconcile.line_partial_ids
1657                 if any([(line.account_id.type in ('receivable', 'payable') and line.partner_id.id != first_partner) for line in move_lines]):
1658                     return False
1659         return True
1660
1661     _constraints = [
1662         (_check_same_partner, 'You can only reconcile journal items with the same partner.', ['line_id', 'line_partial_ids']),
1663     ]
1664     
1665     def reconcile_partial_check(self, cr, uid, ids, type='auto', context=None):
1666         total = 0.0
1667         for rec in self.browse(cr, uid, ids, context=context):
1668             for line in rec.line_partial_ids:
1669                 if line.account_id.currency_id:
1670                     total += line.amount_currency
1671                 else:
1672                     total += (line.debit or 0.0) - (line.credit or 0.0)
1673         if not total:
1674             self.pool.get('account.move.line').write(cr, uid,
1675                 map(lambda x: x.id, rec.line_partial_ids),
1676                 {'reconcile_id': rec.id },
1677                 context=context
1678             )
1679         return True
1680
1681     def name_get(self, cr, uid, ids, context=None):
1682         if not ids:
1683             return []
1684         result = []
1685         for r in self.browse(cr, uid, ids, context=context):
1686             total = reduce(lambda y,t: (t.debit or 0.0) - (t.credit or 0.0) + y, r.line_partial_ids, 0.0)
1687             if total:
1688                 name = '%s (%.2f)' % (r.name, total)
1689                 result.append((r.id,name))
1690             else:
1691                 result.append((r.id,r.name))
1692         return result
1693
1694
1695 #----------------------------------------------------------
1696 # Tax
1697 #----------------------------------------------------------
1698 """
1699 a documenter
1700 child_depend: la taxe depend des taxes filles
1701 """
1702 class account_tax_code(osv.osv):
1703     """
1704     A code for the tax object.
1705
1706     This code is used for some tax declarations.
1707     """
1708     def _sum(self, cr, uid, ids, name, args, context, where ='', where_params=()):
1709         parent_ids = tuple(self.search(cr, uid, [('parent_id', 'child_of', ids)]))
1710         if context.get('based_on', 'invoices') == 'payments':
1711             cr.execute('SELECT line.tax_code_id, sum(line.tax_amount) \
1712                     FROM account_move_line AS line, \
1713                         account_move AS move \
1714                         LEFT JOIN account_invoice invoice ON \
1715                             (invoice.move_id = move.id) \
1716                     WHERE line.tax_code_id IN %s '+where+' \
1717                         AND move.id = line.move_id \
1718                         AND ((invoice.state = \'paid\') \
1719                             OR (invoice.id IS NULL)) \
1720                             GROUP BY line.tax_code_id',
1721                                 (parent_ids,) + where_params)
1722         else:
1723             cr.execute('SELECT line.tax_code_id, sum(line.tax_amount) \
1724                     FROM account_move_line AS line, \
1725                     account_move AS move \
1726                     WHERE line.tax_code_id IN %s '+where+' \
1727                     AND move.id = line.move_id \
1728                     GROUP BY line.tax_code_id',
1729                        (parent_ids,) + where_params)
1730         res=dict(cr.fetchall())
1731         obj_precision = self.pool.get('decimal.precision')
1732         res2 = {}
1733         for record in self.browse(cr, uid, ids, context=context):
1734             def _rec_get(record):
1735                 amount = res.get(record.id, 0.0)
1736                 for rec in record.child_ids:
1737                     amount += _rec_get(rec) * rec.sign
1738                 return amount
1739             res2[record.id] = round(_rec_get(record), obj_precision.precision_get(cr, uid, 'Account'))
1740         return res2
1741
1742     def _sum_year(self, cr, uid, ids, name, args, context=None):
1743         if context is None:
1744             context = {}
1745         move_state = ('posted', )
1746         if context.get('state', 'all') == 'all':
1747             move_state = ('draft', 'posted', )
1748         if context.get('fiscalyear_id', False):
1749             fiscalyear_id = [context['fiscalyear_id']]
1750         else:
1751             fiscalyear_id = self.pool.get('account.fiscalyear').finds(cr, uid, exception=False)
1752         where = ''
1753         where_params = ()
1754         if fiscalyear_id:
1755             pids = []
1756             for fy in fiscalyear_id:
1757                 pids += map(lambda x: str(x.id), self.pool.get('account.fiscalyear').browse(cr, uid, fy).period_ids)
1758             if pids:
1759                 where = ' AND line.period_id IN %s AND move.state IN %s '
1760                 where_params = (tuple(pids), move_state)
1761         return self._sum(cr, uid, ids, name, args, context,
1762                 where=where, where_params=where_params)
1763
1764     def _sum_period(self, cr, uid, ids, name, args, context):
1765         if context is None:
1766             context = {}
1767         move_state = ('posted', )
1768         if context.get('state', False) == 'all':
1769             move_state = ('draft', 'posted', )
1770         if context.get('period_id', False):
1771             period_id = context['period_id']
1772         else:
1773             period_id = self.pool.get('account.period').find(cr, uid, context=context)
1774             if not period_id:
1775                 return dict.fromkeys(ids, 0.0)
1776             period_id = period_id[0]
1777         return self._sum(cr, uid, ids, name, args, context,
1778                 where=' AND line.period_id=%s AND move.state IN %s', where_params=(period_id, move_state))
1779
1780     _name = 'account.tax.code'
1781     _description = 'Tax Code'
1782     _rec_name = 'code'
1783     _order = 'sequence, code'
1784     _columns = {
1785         'name': fields.char('Tax Case Name', required=True, translate=True),
1786         'code': fields.char('Case Code', size=64),
1787         'info': fields.text('Description'),
1788         'sum': fields.function(_sum_year, string="Year Sum"),
1789         'sum_period': fields.function(_sum_period, string="Period Sum"),
1790         'parent_id': fields.many2one('account.tax.code', 'Parent Code', select=True),
1791         'child_ids': fields.one2many('account.tax.code', 'parent_id', 'Child Codes'),
1792         'line_ids': fields.one2many('account.move.line', 'tax_code_id', 'Lines'),
1793         'company_id': fields.many2one('res.company', 'Company', required=True),
1794         'sign': fields.float('Coefficent for parent', required=True, help='You can specify here the coefficient that will be used when consolidating the amount of this case into its parent. For example, set 1/-1 if you want to add/substract it.'),
1795         'notprintable':fields.boolean("Not Printable in Invoice", help="Check this box if you don't want any tax related to this tax code to appear on invoices"),
1796         'sequence': fields.integer('Sequence', help="Determine the display order in the report 'Accounting \ Reporting \ Generic Reporting \ Taxes \ Taxes Report'"),
1797     }
1798
1799     def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=80):
1800         if not args:
1801             args = []
1802         if operator in expression.NEGATIVE_TERM_OPERATORS:
1803             domain = [('code', operator, name), ('name', operator, name)]
1804         else:
1805             domain = ['|', ('code', operator, name), ('name', operator, name)]
1806         ids = self.search(cr, user, expression.AND([domain, args]), limit=limit, context=context)
1807         return self.name_get(cr, user, ids, context=context)
1808
1809     def name_get(self, cr, uid, ids, context=None):
1810         if isinstance(ids, (int, long)):
1811             ids = [ids]
1812         if not ids:
1813             return []
1814         if isinstance(ids, (int, long)):
1815             ids = [ids]
1816         reads = self.read(cr, uid, ids, ['name','code'], context=context, load='_classic_write')
1817         return [(x['id'], (x['code'] and (x['code'] + ' - ') or '') + x['name']) \
1818                 for x in reads]
1819
1820     def _default_company(self, cr, uid, context=None):
1821         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
1822         if user.company_id:
1823             return user.company_id.id
1824         return self.pool.get('res.company').search(cr, uid, [('parent_id', '=', False)])[0]
1825
1826     _defaults = {
1827         'company_id': _default_company,
1828         'sign': 1.0,
1829         'notprintable': False,
1830     }
1831
1832     _check_recursion = check_cycle
1833     _constraints = [
1834         (_check_recursion, 'Error!\nYou cannot create recursive accounts.', ['parent_id'])
1835     ]
1836     _order = 'code'
1837
1838
1839 def get_precision_tax():
1840     def change_digit_tax(cr):
1841         res = openerp.registry(cr.dbname)['decimal.precision'].precision_get(cr, SUPERUSER_ID, 'Account')
1842         return (16, res+3)
1843     return change_digit_tax
1844
1845 class account_tax(osv.osv):
1846     """
1847     A tax object.
1848
1849     Type: percent, fixed, none, code
1850         PERCENT: tax = price * amount
1851         FIXED: tax = price + amount
1852         NONE: no tax line
1853         CODE: execute python code. localcontext = {'price_unit':pu}
1854             return result in the context
1855             Ex: result=round(price_unit*0.21,4)
1856     """
1857     def copy_data(self, cr, uid, id, default=None, context=None):
1858         if default is None:
1859             default = {}
1860         this = self.browse(cr, uid, id, context=context)
1861         tmp_default = dict(default, name=_("%s (Copy)") % this.name)
1862         return super(account_tax, self).copy_data(cr, uid, id, default=tmp_default, context=context)
1863
1864     _name = 'account.tax'
1865     _description = 'Tax'
1866     _columns = {
1867         'name': fields.char('Tax Name', required=True, translate=True, help="This name will be displayed on reports"),
1868         '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."),
1869         'amount': fields.float('Amount', required=True, digits_compute=get_precision_tax(), help="For taxes of type percentage, enter % ratio between 0-1."),
1870         'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the tax without removing it."),
1871         'type': fields.selection( [('percent','Percentage'), ('fixed','Fixed Amount'), ('none','None'), ('code','Python Code'), ('balance','Balance')], 'Tax Type', required=True,
1872             help="The computation method for the tax amount."),
1873         'applicable_type': fields.selection( [('true','Always'), ('code','Given by Python Code')], 'Applicability', required=True,
1874             help="If not applicable (computed through a Python code), the tax won't appear on the invoice."),
1875         'domain':fields.char('Domain', help="This field is only used if you develop your own module allowing developers to create specific taxes in a custom domain."),
1876         'account_collected_id':fields.many2one('account.account', 'Invoice Tax Account', help="Set the account that will be set by default on invoice tax lines for invoices. Leave empty to use the expense account."),
1877         'account_paid_id':fields.many2one('account.account', 'Refund Tax Account', help="Set the account that will be set by default on invoice tax lines for refunds. Leave empty to use the expense account."),
1878         'account_analytic_collected_id':fields.many2one('account.analytic.account', 'Invoice Tax Analytic Account', help="Set the analytic account that will be used by default on the invoice tax lines for invoices. Leave empty if you don't want to use an analytic account on the invoice tax lines by default."),
1879         'account_analytic_paid_id':fields.many2one('account.analytic.account', 'Refund Tax Analytic Account', help="Set the analytic account that will be used by default on the invoice tax lines for refunds. Leave empty if you don't want to use an analytic account on the invoice tax lines by default."),
1880         'parent_id':fields.many2one('account.tax', 'Parent Tax Account', select=True),
1881         'child_ids':fields.one2many('account.tax', 'parent_id', 'Child Tax Accounts'),
1882         '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."),
1883         'python_compute':fields.text('Python Code'),
1884         'python_compute_inv':fields.text('Python Code (reverse)'),
1885         'python_applicable':fields.text('Applicable Code'),
1886
1887         #
1888         # Fields used for the Tax declaration
1889         #
1890         'base_code_id': fields.many2one('account.tax.code', 'Account Base Code', help="Use this code for the tax declaration."),
1891         'tax_code_id': fields.many2one('account.tax.code', 'Account Tax Code', help="Use this code for the tax declaration."),
1892         'base_sign': fields.float('Base Code Sign', help="Usually 1 or -1.", digits_compute=get_precision_tax()),
1893         'tax_sign': fields.float('Tax Code Sign', help="Usually 1 or -1.", digits_compute=get_precision_tax()),
1894
1895         # Same fields for refund invoices
1896
1897         'ref_base_code_id': fields.many2one('account.tax.code', 'Refund Base Code', help="Use this code for the tax declaration."),
1898         'ref_tax_code_id': fields.many2one('account.tax.code', 'Refund Tax Code', help="Use this code for the tax declaration."),
1899         'ref_base_sign': fields.float('Refund Base Code Sign', help="Usually 1 or -1.", digits_compute=get_precision_tax()),
1900         'ref_tax_sign': fields.float('Refund Tax Code Sign', help="Usually 1 or -1.", digits_compute=get_precision_tax()),
1901         'include_base_amount': fields.boolean('Included in base amount', help="Indicates if the amount of tax must be included in the base amount for the computation of the next taxes"),
1902         'company_id': fields.many2one('res.company', 'Company', required=True),
1903         'description': fields.char('Tax Code'),
1904         'price_include': fields.boolean('Tax Included in Price', help="Check this if the price you use on the product and invoices includes this tax."),
1905         'type_tax_use': fields.selection([('sale','Sale'),('purchase','Purchase'),('all','All')], 'Tax Application', required=True)
1906
1907     }
1908     _sql_constraints = [
1909         ('name_company_uniq', 'unique(name, company_id)', 'Tax Name must be unique per company!'),
1910     ]
1911
1912     def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=80):
1913         """
1914         Returns a list of tupples containing id, name, as internally it is called {def name_get}
1915         result format: {[(id, name), (id, name), ...]}
1916
1917         @param cr: A database cursor
1918         @param user: ID of the user currently logged in
1919         @param name: name to search
1920         @param args: other arguments
1921         @param operator: default operator is 'ilike', it can be changed
1922         @param context: context arguments, like lang, time zone
1923         @param limit: Returns first 'n' ids of complete result, default is 80.
1924
1925         @return: Returns a list of tupples containing id and name
1926         """
1927         if not args:
1928             args = []
1929         if operator in expression.NEGATIVE_TERM_OPERATORS:
1930             domain = [('description', operator, name), ('name', operator, name)]
1931         else:
1932             domain = ['|', ('description', operator, name), ('name', operator, name)]
1933         ids = self.search(cr, user, expression.AND([domain, args]), limit=limit, context=context)
1934         return self.name_get(cr, user, ids, context=context)
1935
1936     def write(self, cr, uid, ids, vals, context=None):
1937         if vals.get('type', False) and vals['type'] in ('none', 'code'):
1938             vals.update({'amount': 0.0})
1939         return super(account_tax, self).write(cr, uid, ids, vals, context=context)
1940
1941     def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False):
1942         if context is None:
1943             context = {}
1944         journal_pool = self.pool.get('account.journal')
1945
1946         if context.get('type'):
1947             if context.get('type') in ('out_invoice','out_refund'):
1948                 args += [('type_tax_use','in',['sale','all'])]
1949             elif context.get('type') in ('in_invoice','in_refund'):
1950                 args += [('type_tax_use','in',['purchase','all'])]
1951
1952         if context.get('journal_id'):
1953             journal = journal_pool.browse(cr, uid, context.get('journal_id'))
1954             if journal.type in ('sale', 'purchase'):
1955                 args += [('type_tax_use','in',[journal.type,'all'])]
1956
1957         return super(account_tax, self).search(cr, uid, args, offset, limit, order, context, count)
1958
1959     def name_get(self, cr, uid, ids, context=None):
1960         if not ids:
1961             return []
1962         res = []
1963         for record in self.read(cr, uid, ids, ['description','name'], context=context):
1964             name = record['description'] and record['description'] or record['name']
1965             res.append((record['id'],name ))
1966         return res
1967
1968     def _default_company(self, cr, uid, context=None):
1969         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
1970         if user.company_id:
1971             return user.company_id.id
1972         return self.pool.get('res.company').search(cr, uid, [('parent_id', '=', False)])[0]
1973
1974     _defaults = {
1975         'python_compute': '''# price_unit\n# or False\n# product: product.product object or None\n# partner: res.partner object or None\n\nresult = price_unit * 0.10''',
1976         'python_compute_inv': '''# price_unit\n# product: product.product object or False\n\nresult = price_unit * 0.10''',
1977         'applicable_type': 'true',
1978         'type': 'percent',
1979         'amount': 0,
1980         'price_include': 0,
1981         'active': 1,
1982         'type_tax_use': 'all',
1983         'sequence': 1,
1984         'ref_tax_sign': 1,
1985         'ref_base_sign': 1,
1986         'tax_sign': 1,
1987         'base_sign': 1,
1988         'include_base_amount': False,
1989         'company_id': _default_company,
1990     }
1991     _order = 'sequence'
1992
1993     def _applicable(self, cr, uid, taxes, price_unit, product=None, partner=None):
1994         res = []
1995         for tax in taxes:
1996             if tax.applicable_type=='code':
1997                 localdict = {'price_unit':price_unit, 'product':product, 'partner':partner}
1998                 exec tax.python_applicable in localdict
1999                 if localdict.get('result', False):
2000                     res.append(tax)
2001             else:
2002                 res.append(tax)
2003         return res
2004
2005     def _unit_compute(self, cr, uid, taxes, price_unit, product=None, partner=None, quantity=0):
2006         taxes = self._applicable(cr, uid, taxes, price_unit ,product, partner)
2007         res = []
2008         cur_price_unit=price_unit
2009         for tax in taxes:
2010             # we compute the amount for the current tax object and append it to the result
2011             data = {'id':tax.id,
2012                     'name':tax.description and tax.description + " - " + tax.name or tax.name,
2013                     'account_collected_id':tax.account_collected_id.id,
2014                     'account_paid_id':tax.account_paid_id.id,
2015                     'account_analytic_collected_id': tax.account_analytic_collected_id.id,
2016                     'account_analytic_paid_id': tax.account_analytic_paid_id.id,
2017                     'base_code_id': tax.base_code_id.id,
2018                     'ref_base_code_id': tax.ref_base_code_id.id,
2019                     'sequence': tax.sequence,
2020                     'base_sign': tax.base_sign,
2021                     'tax_sign': tax.tax_sign,
2022                     'ref_base_sign': tax.ref_base_sign,
2023                     'ref_tax_sign': tax.ref_tax_sign,
2024                     'price_unit': cur_price_unit,
2025                     'tax_code_id': tax.tax_code_id.id,
2026                     'ref_tax_code_id': tax.ref_tax_code_id.id,
2027             }
2028             res.append(data)
2029             if tax.type=='percent':
2030                 amount = cur_price_unit * tax.amount
2031                 data['amount'] = amount
2032
2033             elif tax.type=='fixed':
2034                 data['amount'] = tax.amount
2035                 data['tax_amount']=quantity
2036                # data['amount'] = quantity
2037             elif tax.type=='code':
2038                 localdict = {'price_unit':cur_price_unit, 'product':product, 'partner':partner, 'quantity': quantity}
2039                 exec tax.python_compute in localdict
2040                 amount = localdict['result']
2041                 data['amount'] = amount
2042             elif tax.type=='balance':
2043                 data['amount'] = cur_price_unit - reduce(lambda x,y: y.get('amount',0.0)+x, res, 0.0)
2044                 data['balance'] = cur_price_unit
2045
2046             amount2 = data.get('amount', 0.0)
2047             if tax.child_ids:
2048                 if tax.child_depend:
2049                     latest = res.pop()
2050                 amount = amount2
2051                 child_tax = self._unit_compute(cr, uid, tax.child_ids, amount, product, partner, quantity)
2052                 res.extend(child_tax)
2053                 for child in child_tax:
2054                     amount2 += child.get('amount', 0.0)
2055                 if tax.child_depend:
2056                     for r in res:
2057                         for name in ('base','ref_base'):
2058                             if latest[name+'_code_id'] and latest[name+'_sign'] and not r[name+'_code_id']:
2059                                 r[name+'_code_id'] = latest[name+'_code_id']
2060                                 r[name+'_sign'] = latest[name+'_sign']
2061                                 r['price_unit'] = latest['price_unit']
2062                                 latest[name+'_code_id'] = False
2063                         for name in ('tax','ref_tax'):
2064                             if latest[name+'_code_id'] and latest[name+'_sign'] and not r[name+'_code_id']:
2065                                 r[name+'_code_id'] = latest[name+'_code_id']
2066                                 r[name+'_sign'] = latest[name+'_sign']
2067                                 r['amount'] = data['amount']
2068                                 latest[name+'_code_id'] = False
2069             if tax.include_base_amount:
2070                 cur_price_unit+=amount2
2071         return res
2072
2073     def compute_for_bank_reconciliation(self, cr, uid, tax_id, amount, context=None):
2074         """ Called by RPC by the bank statement reconciliation widget """
2075         tax = self.browse(cr, uid, tax_id, context=context)
2076         return self.compute_all(cr, uid, [tax], amount, 1) # TOCHECK may use force_exclude parameter
2077
2078     @api.v7
2079     def compute_all(self, cr, uid, taxes, price_unit, quantity, product=None, partner=None, force_excluded=False):
2080         """
2081         :param force_excluded: boolean used to say that we don't want to consider the value of field price_include of
2082             tax. It's used in encoding by line where you don't matter if you encoded a tax with that boolean to True or
2083             False
2084         RETURN: {
2085                 'total': 0.0,                # Total without taxes
2086                 'total_included: 0.0,        # Total with taxes
2087                 'taxes': []                  # List of taxes, see compute for the format
2088             }
2089         """
2090
2091         # By default, for each tax, tax amount will first be computed
2092         # and rounded at the 'Account' decimal precision for each
2093         # PO/SO/invoice line and then these rounded amounts will be
2094         # summed, leading to the total amount for that tax. But, if the
2095         # company has tax_calculation_rounding_method = round_globally,
2096         # we still follow the same method, but we use a much larger
2097         # precision when we round the tax amount for each line (we use
2098         # the 'Account' decimal precision + 5), and that way it's like
2099         # rounding after the sum of the tax amounts of each line
2100         precision = self.pool.get('decimal.precision').precision_get(cr, uid, 'Account')
2101         tax_compute_precision = precision
2102         if taxes and taxes[0].company_id.tax_calculation_rounding_method == 'round_globally':
2103             tax_compute_precision += 5
2104         totalin = totalex = round(price_unit * quantity, precision)
2105         tin = []
2106         tex = []
2107         for tax in taxes:
2108             if not tax.price_include or force_excluded:
2109                 tex.append(tax)
2110             else:
2111                 tin.append(tax)
2112         tin = self.compute_inv(cr, uid, tin, price_unit, quantity, product=product, partner=partner, precision=tax_compute_precision)
2113         for r in tin:
2114             totalex -= r.get('amount', 0.0)
2115         totlex_qty = 0.0
2116         try:
2117             totlex_qty = totalex/quantity
2118         except:
2119             pass
2120         tex = self._compute(cr, uid, tex, totlex_qty, quantity, product=product, partner=partner, precision=tax_compute_precision)
2121         for r in tex:
2122             totalin += r.get('amount', 0.0)
2123         return {
2124             'total': totalex,
2125             'total_included': totalin,
2126             'taxes': tin + tex
2127         }
2128
2129     @api.v8
2130     def compute_all(self, price_unit, quantity, product=None, partner=None, force_excluded=False):
2131         return self._model.compute_all(
2132             self._cr, self._uid, self, price_unit, quantity,
2133             product=product, partner=partner, force_excluded=force_excluded)
2134
2135     def compute(self, cr, uid, taxes, price_unit, quantity,  product=None, partner=None):
2136         _logger.warning("Deprecated, use compute_all(...)['taxes'] instead of compute(...) to manage prices with tax included.")
2137         return self._compute(cr, uid, taxes, price_unit, quantity, product, partner)
2138
2139     def _compute(self, cr, uid, taxes, price_unit, quantity, product=None, partner=None, precision=None):
2140         """
2141         Compute tax values for given PRICE_UNIT, QUANTITY and a buyer/seller ADDRESS_ID.
2142
2143         RETURN:
2144             [ tax ]
2145             tax = {'name':'', 'amount':0.0, 'account_collected_id':1, 'account_paid_id':2}
2146             one tax for each tax id in IDS and their children
2147         """
2148         if not precision:
2149             precision = self.pool.get('decimal.precision').precision_get(cr, uid, 'Account')
2150         res = self._unit_compute(cr, uid, taxes, price_unit, product, partner, quantity)
2151         total = 0.0
2152         for r in res:
2153             if r.get('balance',False):
2154                 r['amount'] = round(r.get('balance', 0.0) * quantity, precision) - total
2155             else:
2156                 r['amount'] = round(r.get('amount', 0.0) * quantity, precision)
2157                 total += r['amount']
2158         return res
2159
2160     def _unit_compute_inv(self, cr, uid, taxes, price_unit, product=None, partner=None):
2161         taxes = self._applicable(cr, uid, taxes, price_unit,  product, partner)
2162         res = []
2163         taxes.reverse()
2164         cur_price_unit = price_unit
2165
2166         tax_parent_tot = 0.0
2167         for tax in taxes:
2168             if (tax.type=='percent') and not tax.include_base_amount:
2169                 tax_parent_tot += tax.amount
2170
2171         for tax in taxes:
2172             if (tax.type=='fixed') and not tax.include_base_amount:
2173                 cur_price_unit -= tax.amount
2174
2175         for tax in taxes:
2176             if tax.type=='percent':
2177                 if tax.include_base_amount:
2178                     amount = cur_price_unit - (cur_price_unit / (1 + tax.amount))
2179                 else:
2180                     amount = (cur_price_unit / (1 + tax_parent_tot)) * tax.amount
2181
2182             elif tax.type=='fixed':
2183                 amount = tax.amount
2184
2185             elif tax.type=='code':
2186                 localdict = {'price_unit':cur_price_unit, 'product':product, 'partner':partner}
2187                 exec tax.python_compute_inv in localdict
2188                 amount = localdict['result']
2189             elif tax.type=='balance':
2190                 amount = cur_price_unit - reduce(lambda x,y: y.get('amount',0.0)+x, res, 0.0)
2191
2192             if tax.include_base_amount:
2193                 cur_price_unit -= amount
2194                 todo = 0
2195             else:
2196                 todo = 1
2197             res.append({
2198                 'id': tax.id,
2199                 'todo': todo,
2200                 'name': tax.name,
2201                 'amount': amount,
2202                 'account_collected_id': tax.account_collected_id.id,
2203                 'account_paid_id': tax.account_paid_id.id,
2204                 'account_analytic_collected_id': tax.account_analytic_collected_id.id,
2205                 'account_analytic_paid_id': tax.account_analytic_paid_id.id,
2206                 'base_code_id': tax.base_code_id.id,
2207                 'ref_base_code_id': tax.ref_base_code_id.id,
2208                 'sequence': tax.sequence,
2209                 'base_sign': tax.base_sign,
2210                 'tax_sign': tax.tax_sign,
2211                 'ref_base_sign': tax.ref_base_sign,
2212                 'ref_tax_sign': tax.ref_tax_sign,
2213                 'price_unit': cur_price_unit,
2214                 'tax_code_id': tax.tax_code_id.id,
2215                 'ref_tax_code_id': tax.ref_tax_code_id.id,
2216             })
2217             if tax.child_ids:
2218                 if tax.child_depend:
2219                     del res[-1]
2220                     amount = price_unit
2221
2222             parent_tax = self._unit_compute_inv(cr, uid, tax.child_ids, amount, product, partner)
2223             res.extend(parent_tax)
2224
2225         total = 0.0
2226         for r in res:
2227             if r['todo']:
2228                 total += r['amount']
2229         for r in res:
2230             r['price_unit'] -= total
2231             r['todo'] = 0
2232         return res
2233
2234     def compute_inv(self, cr, uid, taxes, price_unit, quantity, product=None, partner=None, precision=None):
2235         """
2236         Compute tax values for given PRICE_UNIT, QUANTITY and a buyer/seller ADDRESS_ID.
2237         Price Unit is a Tax included price
2238
2239         RETURN:
2240             [ tax ]
2241             tax = {'name':'', 'amount':0.0, 'account_collected_id':1, 'account_paid_id':2}
2242             one tax for each tax id in IDS and their children
2243         """
2244         if not precision:
2245             precision = self.pool.get('decimal.precision').precision_get(cr, uid, 'Account')
2246         res = self._unit_compute_inv(cr, uid, taxes, price_unit, product, partner=None)
2247         total = 0.0
2248         for r in res:
2249             if r.get('balance',False):
2250                 r['amount'] = round(r['balance'] * quantity, precision) - total
2251             else:
2252                 r['amount'] = round(r['amount'] * quantity, precision)
2253                 total += r['amount']
2254         return res
2255
2256
2257 # ---------------------------------------------------------
2258 # Account Entries Models
2259 # ---------------------------------------------------------
2260
2261 class account_model(osv.osv):
2262     _name = "account.model"
2263     _description = "Account Model"
2264     _columns = {
2265         'name': fields.char('Model Name', required=True, help="This is a model for recurring accounting entries"),
2266         'journal_id': fields.many2one('account.journal', 'Journal', required=True),
2267         'company_id': fields.related('journal_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True),
2268         'lines_id': fields.one2many('account.model.line', 'model_id', 'Model Entries', copy=True),
2269         'legend': fields.text('Legend', readonly=True, size=100),
2270     }
2271
2272     _defaults = {
2273         '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'),
2274     }
2275
2276     def generate(self, cr, uid, ids, data=None, context=None):
2277         if data is None:
2278             data = {}
2279         move_ids = []
2280         entry = {}
2281         account_move_obj = self.pool.get('account.move')
2282         account_move_line_obj = self.pool.get('account.move.line')
2283         pt_obj = self.pool.get('account.payment.term')
2284         period_obj = self.pool.get('account.period')
2285
2286         if context is None:
2287             context = {}
2288
2289         if data.get('date', False):
2290             context = dict(context)
2291             context.update({'date': data['date']})
2292
2293         move_date = context.get('date', time.strftime('%Y-%m-%d'))
2294         move_date = datetime.strptime(move_date,"%Y-%m-%d")
2295         for model in self.browse(cr, uid, ids, context=context):
2296             ctx = context.copy()
2297             ctx.update({'company_id': model.company_id.id})
2298             period_ids = period_obj.find(cr, uid, dt=context.get('date', False), context=ctx)
2299             period_id = period_ids and period_ids[0] or False
2300             ctx.update({'journal_id': model.journal_id.id,'period_id': period_id})
2301             try:
2302                 entry['name'] = model.name%{'year': move_date.strftime('%Y'), 'month': move_date.strftime('%m'), 'date': move_date.strftime('%Y-%m')}
2303             except:
2304                 raise osv.except_osv(_('Wrong Model!'), _('You have a wrong expression "%(...)s" in your model!'))
2305             move_id = account_move_obj.create(cr, uid, {
2306                 'ref': entry['name'],
2307                 'period_id': period_id,
2308                 'journal_id': model.journal_id.id,
2309                 'date': context.get('date', fields.date.context_today(self,cr,uid,context=context))
2310             })
2311             move_ids.append(move_id)
2312             for line in model.lines_id:
2313                 analytic_account_id = False
2314                 if line.analytic_account_id:
2315                     if not model.journal_id.analytic_journal_id:
2316                         raise osv.except_osv(_('No Analytic Journal!'),_("You have to define an analytic journal on the '%s' journal!") % (model.journal_id.name,))
2317                     analytic_account_id = line.analytic_account_id.id
2318                 val = {
2319                     'move_id': move_id,
2320                     'journal_id': model.journal_id.id,
2321                     'period_id': period_id,
2322                     'analytic_account_id': analytic_account_id
2323                 }
2324
2325                 date_maturity = context.get('date',time.strftime('%Y-%m-%d'))
2326                 if line.date_maturity == 'partner':
2327                     if not line.partner_id:
2328                         raise osv.except_osv(_('Error!'), _("Maturity date of entry line generated by model line '%s' of model '%s' is based on partner payment term!" \
2329                                                                 "\nPlease define partner on it!")%(line.name, model.name))
2330
2331                     payment_term_id = False
2332                     if model.journal_id.type in ('purchase', 'purchase_refund') and line.partner_id.property_supplier_payment_term:
2333                         payment_term_id = line.partner_id.property_supplier_payment_term.id
2334                     elif line.partner_id.property_payment_term:
2335                         payment_term_id = line.partner_id.property_payment_term.id
2336                     if payment_term_id:
2337                         pterm_list = pt_obj.compute(cr, uid, payment_term_id, value=1, date_ref=date_maturity)
2338                         if pterm_list:
2339                             pterm_list = [l[0] for l in pterm_list]
2340                             pterm_list.sort()
2341                             date_maturity = pterm_list[-1]
2342
2343                 val.update({
2344                     'name': line.name,
2345                     'quantity': line.quantity,
2346                     'debit': line.debit,
2347                     'credit': line.credit,
2348                     'account_id': line.account_id.id,
2349                     'move_id': move_id,
2350                     'partner_id': line.partner_id.id,
2351                     'date': context.get('date', fields.date.context_today(self,cr,uid,context=context)),
2352                     'date_maturity': date_maturity
2353                 })
2354                 account_move_line_obj.create(cr, uid, val, context=ctx)
2355
2356         return move_ids
2357
2358     def onchange_journal_id(self, cr, uid, ids, journal_id, context=None):
2359         company_id = False
2360
2361         if journal_id:
2362             journal = self.pool.get('account.journal').browse(cr, uid, journal_id, context=context)
2363             if journal.company_id.id:
2364                 company_id = journal.company_id.id
2365
2366         return {'value': {'company_id': company_id}}
2367
2368
2369 class account_model_line(osv.osv):
2370     _name = "account.model.line"
2371     _description = "Account Model Entries"
2372     _columns = {
2373         'name': fields.char('Name', required=True),
2374         'sequence': fields.integer('Sequence', required=True, help="The sequence field is used to order the resources from lower sequences to higher ones."),
2375         'quantity': fields.float('Quantity', digits_compute=dp.get_precision('Account'), help="The optional quantity on entries."),
2376         'debit': fields.float('Debit', digits_compute=dp.get_precision('Account')),
2377         'credit': fields.float('Credit', digits_compute=dp.get_precision('Account')),
2378         'account_id': fields.many2one('account.account', 'Account', required=True, ondelete="cascade"),
2379         'analytic_account_id': fields.many2one('account.analytic.account', 'Analytic Account', ondelete="cascade"),
2380         'model_id': fields.many2one('account.model', 'Model', required=True, ondelete="cascade", select=True),
2381         'amount_currency': fields.float('Amount Currency', help="The amount expressed in an optional other currency."),
2382         'currency_id': fields.many2one('res.currency', 'Currency'),
2383         'partner_id': fields.many2one('res.partner', 'Partner'),
2384         '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 choose between the creation date or the creation date of the entries plus the partner payment terms."),
2385     }
2386     _order = 'sequence'
2387     _sql_constraints = [
2388         ('credit_debit1', 'CHECK (credit*debit=0)',  'Wrong credit or debit value in model, they must be positive!'),
2389         ('credit_debit2', 'CHECK (credit+debit>=0)', 'Wrong credit or debit value in model, they must be positive!'),
2390     ]
2391
2392 # ---------------------------------------------------------
2393 # Account Subscription
2394 # ---------------------------------------------------------
2395
2396
2397 class account_subscription(osv.osv):
2398     _name = "account.subscription"
2399     _description = "Account Subscription"
2400     _columns = {
2401         'name': fields.char('Name', required=True),
2402         'ref': fields.char('Reference'),
2403         'model_id': fields.many2one('account.model', 'Model', required=True),
2404         'date_start': fields.date('Start Date', required=True),
2405         'period_total': fields.integer('Number of Periods', required=True),
2406         'period_nbr': fields.integer('Period', required=True),
2407         'period_type': fields.selection([('day','days'),('month','month'),('year','year')], 'Period Type', required=True),
2408         'state': fields.selection([('draft','Draft'),('running','Running'),('done','Done')], 'Status', required=True, readonly=True, copy=False),
2409         'lines_id': fields.one2many('account.subscription.line', 'subscription_id', 'Subscription Lines', copy=True)
2410     }
2411     _defaults = {
2412         'date_start': fields.date.context_today,
2413         'period_type': 'month',
2414         'period_total': 12,
2415         'period_nbr': 1,
2416         'state': 'draft',
2417     }
2418     def state_draft(self, cr, uid, ids, context=None):
2419         self.write(cr, uid, ids, {'state':'draft'})
2420         return False
2421
2422     def check(self, cr, uid, ids, context=None):
2423         todone = []
2424         for sub in self.browse(cr, uid, ids, context=context):
2425             ok = True
2426             for line in sub.lines_id:
2427                 if not line.move_id.id:
2428                     ok = False
2429                     break
2430             if ok:
2431                 todone.append(sub.id)
2432         if todone:
2433             self.write(cr, uid, todone, {'state':'done'})
2434         return False
2435
2436     def remove_line(self, cr, uid, ids, context=None):
2437         toremove = []
2438         for sub in self.browse(cr, uid, ids, context=context):
2439             for line in sub.lines_id:
2440                 if not line.move_id.id:
2441                     toremove.append(line.id)
2442         if toremove:
2443             self.pool.get('account.subscription.line').unlink(cr, uid, toremove)
2444         self.write(cr, uid, ids, {'state':'draft'})
2445         return False
2446
2447     def compute(self, cr, uid, ids, context=None):
2448         for sub in self.browse(cr, uid, ids, context=context):
2449             ds = sub.date_start
2450             for i in range(sub.period_total):
2451                 self.pool.get('account.subscription.line').create(cr, uid, {
2452                     'date': ds,
2453                     'subscription_id': sub.id,
2454                 })
2455                 if sub.period_type=='day':
2456                     ds = (datetime.strptime(ds, '%Y-%m-%d') + relativedelta(days=sub.period_nbr)).strftime('%Y-%m-%d')
2457                 if sub.period_type=='month':
2458                     ds = (datetime.strptime(ds, '%Y-%m-%d') + relativedelta(months=sub.period_nbr)).strftime('%Y-%m-%d')
2459                 if sub.period_type=='year':
2460                     ds = (datetime.strptime(ds, '%Y-%m-%d') + relativedelta(years=sub.period_nbr)).strftime('%Y-%m-%d')
2461         self.write(cr, uid, ids, {'state':'running'})
2462         return True
2463
2464
2465 class account_subscription_line(osv.osv):
2466     _name = "account.subscription.line"
2467     _description = "Account Subscription Line"
2468     _columns = {
2469         'subscription_id': fields.many2one('account.subscription', 'Subscription', required=True, select=True),
2470         'date': fields.date('Date', required=True),
2471         'move_id': fields.many2one('account.move', 'Entry'),
2472     }
2473
2474     def move_create(self, cr, uid, ids, context=None):
2475         tocheck = {}
2476         all_moves = []
2477         obj_model = self.pool.get('account.model')
2478         for line in self.browse(cr, uid, ids, context=context):
2479             data = {
2480                 'date': line.date,
2481             }
2482             move_ids = obj_model.generate(cr, uid, [line.subscription_id.model_id.id], data, context)
2483             tocheck[line.subscription_id.id] = True
2484             self.write(cr, uid, [line.id], {'move_id':move_ids[0]})
2485             all_moves.extend(move_ids)
2486         if tocheck:
2487             self.pool.get('account.subscription').check(cr, uid, tocheck.keys(), context)
2488         return all_moves
2489
2490     _rec_name = 'date'
2491
2492
2493 #  ---------------------------------------------------------------
2494 #   Account Templates: Account, Tax, Tax Code and chart. + Wizard
2495 #  ---------------------------------------------------------------
2496
2497 class account_tax_template(osv.osv):
2498     _name = 'account.tax.template'
2499
2500 class account_account_template(osv.osv):
2501     _order = "code"
2502     _name = "account.account.template"
2503     _description ='Templates for Accounts'
2504
2505     _columns = {
2506         'name': fields.char('Name', required=True, select=True),
2507         'currency_id': fields.many2one('res.currency', 'Secondary Currency', help="Forces all moves for this account to have this secondary currency."),
2508         'code': fields.char('Code', size=64, required=True, select=1),
2509         'type': fields.selection([
2510             ('receivable','Receivable'),
2511             ('payable','Payable'),
2512             ('view','View'),
2513             ('consolidation','Consolidation'),
2514             ('liquidity','Liquidity'),
2515             ('other','Regular'),
2516             ('closed','Closed'),
2517             ], 'Internal Type', required=True,help="This type is used to differentiate types with "\
2518             "special effects in Odoo: view can not have entries, consolidation are accounts that "\
2519             "can have children accounts for multi-company consolidations, payable/receivable are for "\
2520             "partners accounts (for debit/credit computations), closed for depreciated accounts."),
2521         'user_type': fields.many2one('account.account.type', 'Account Type', required=True,
2522             help="These types are defined according to your country. The type contains more information "\
2523             "about the account and its specificities."),
2524         'financial_report_ids': fields.many2many('account.financial.report', 'account_template_financial_report', 'account_template_id', 'report_line_id', 'Financial Reports'),
2525         'reconcile': fields.boolean('Allow Reconciliation', help="Check this option if you want the user to reconcile entries in this account."),
2526         'shortcut': fields.char('Shortcut', size=12),
2527         'note': fields.text('Note'),
2528         'parent_id': fields.many2one('account.account.template', 'Parent Account Template', ondelete='cascade', domain=[('type','=','view')]),
2529         'child_parent_ids':fields.one2many('account.account.template', 'parent_id', 'Children'),
2530         'tax_ids': fields.many2many('account.tax.template', 'account_account_template_tax_rel', 'account_id', 'tax_id', 'Default Taxes'),
2531         'nocreate': fields.boolean('Optional create', help="If checked, the new chart of accounts will not contain this by default."),
2532         'chart_template_id': fields.many2one('account.chart.template', 'Chart Template', help="This optional field allow you to link an account template to a specific chart template that may differ from the one its root parent belongs to. This allow you to define chart templates that extend another and complete it with few new accounts (You don't need to define the whole structure that is common to both several times)."),
2533     }
2534
2535     _defaults = {
2536         'reconcile': False,
2537         'type': 'view',
2538         'nocreate': False,
2539     }
2540
2541     _check_recursion = check_cycle
2542     _constraints = [
2543         (_check_recursion, 'Error!\nYou cannot create recursive account templates.', ['parent_id']),
2544     ]
2545
2546     def name_get(self, cr, uid, ids, context=None):
2547         if not ids:
2548             return []
2549         reads = self.read(cr, uid, ids, ['name','code'], context=context)
2550         res = []
2551         for record in reads:
2552             name = record['name']
2553             if record['code']:
2554                 name = record['code']+' '+name
2555             res.append((record['id'],name ))
2556         return res
2557
2558     def generate_account(self, cr, uid, chart_template_id, tax_template_ref, acc_template_ref, code_digits, company_id, context=None):
2559         """
2560         This method for generating accounts from templates.
2561
2562         :param chart_template_id: id of the chart template chosen in the wizard
2563         :param tax_template_ref: Taxes templates reference for write taxes_id in account_account.
2564         :paramacc_template_ref: dictionary with the mappping between the account templates and the real accounts.
2565         :param code_digits: number of digits got from wizard.multi.charts.accounts, this is use for account code.
2566         :param company_id: company_id selected from wizard.multi.charts.accounts.
2567         :returns: return acc_template_ref for reference purpose.
2568         :rtype: dict
2569         """
2570         if context is None:
2571             context = {}
2572         obj_acc = self.pool.get('account.account')
2573         company_name = self.pool.get('res.company').browse(cr, uid, company_id, context=context).name
2574         template = self.pool.get('account.chart.template').browse(cr, uid, chart_template_id, context=context)
2575         #deactivate the parent_store functionnality on account_account for rapidity purpose
2576         ctx = context.copy()
2577         ctx.update({'defer_parent_store_computation': True})
2578         level_ref = {}
2579         children_acc_criteria = [('chart_template_id','=', chart_template_id)]
2580         if template.account_root_id.id:
2581             children_acc_criteria = ['|'] + children_acc_criteria + ['&',('parent_id','child_of', [template.account_root_id.id]),('chart_template_id','=', False)]
2582         children_acc_template = self.search(cr, uid, [('nocreate','!=',True)] + children_acc_criteria, order='id')
2583         for account_template in self.browse(cr, uid, children_acc_template, context=context):
2584             # skip the root of COA if it's not the main one
2585             if (template.account_root_id.id == account_template.id) and template.parent_id:
2586                 continue
2587             tax_ids = []
2588             for tax in account_template.tax_ids:
2589                 tax_ids.append(tax_template_ref[tax.id])
2590
2591             code_main = account_template.code and len(account_template.code) or 0
2592             code_acc = account_template.code or ''
2593             if code_main > 0 and code_main <= code_digits and account_template.type != 'view':
2594                 code_acc = str(code_acc) + (str('0'*(code_digits-code_main)))
2595             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
2596             #the level as to be given as well at the creation time, because of the defer_parent_store_computation in
2597             #context. Indeed because of this, the parent_left and parent_right are not computed and thus the child_of
2598             #operator does not return the expected values, with result of having the level field not computed at all.
2599             if parent_id:
2600                 level = parent_id in level_ref and level_ref[parent_id] + 1 or obj_acc._get_level(cr, uid, [parent_id], 'level', None, context=context)[parent_id] + 1
2601             else:
2602                 level = 0
2603             vals={
2604                 'name': (template.account_root_id.id == account_template.id) and company_name or account_template.name,
2605                 'currency_id': account_template.currency_id and account_template.currency_id.id or False,
2606                 'code': code_acc,
2607                 'type': account_template.type,
2608                 'user_type': account_template.user_type and account_template.user_type.id or False,
2609                 'reconcile': account_template.reconcile,
2610                 'shortcut': account_template.shortcut,
2611                 'note': account_template.note,
2612                 'financial_report_ids': account_template.financial_report_ids and [(6,0,[x.id for x in account_template.financial_report_ids])] or False,
2613                 'parent_id': parent_id,
2614                 'tax_ids': [(6,0,tax_ids)],
2615                 'company_id': company_id,
2616                 'level': level,
2617             }
2618             new_account = obj_acc.create(cr, uid, vals, context=ctx)
2619             acc_template_ref[account_template.id] = new_account
2620             level_ref[new_account] = level
2621
2622         #reactivate the parent_store functionnality on account_account
2623         obj_acc._parent_store_compute(cr)
2624         return acc_template_ref
2625
2626
2627 class account_add_tmpl_wizard(osv.osv_memory):
2628     """Add one more account from the template.
2629
2630     With the 'nocreate' option, some accounts may not be created. Use this to add them later."""
2631     _name = 'account.addtmpl.wizard'
2632
2633     def _get_def_cparent(self, cr, uid, context=None):
2634         acc_obj = self.pool.get('account.account')
2635         tmpl_obj = self.pool.get('account.account.template')
2636         tids = tmpl_obj.read(cr, uid, [context['tmpl_ids']], ['parent_id'])
2637         if not tids or not tids[0]['parent_id']:
2638             return False
2639         ptids = tmpl_obj.read(cr, uid, [tids[0]['parent_id'][0]], ['code'])
2640         res = None
2641         if not ptids or not ptids[0]['code']:
2642             raise osv.except_osv(_('Error!'), _('There is no parent code for the template account.'))
2643             res = acc_obj.search(cr, uid, [('code','=',ptids[0]['code'])])
2644         return res and res[0] or False
2645
2646     _columns = {
2647         'cparent_id':fields.many2one('account.account', 'Parent target', help="Creates an account with the selected template under this existing parent.", required=True),
2648     }
2649     _defaults = {
2650         'cparent_id': _get_def_cparent,
2651     }
2652
2653     def action_create(self,cr,uid,ids,context=None):
2654         if context is None:
2655             context = {}
2656         acc_obj = self.pool.get('account.account')
2657         tmpl_obj = self.pool.get('account.account.template')
2658         data = self.read(cr, uid, ids)[0]
2659         company_id = acc_obj.read(cr, uid, [data['cparent_id'][0]], ['company_id'])[0]['company_id'][0]
2660         account_template = tmpl_obj.browse(cr, uid, context['tmpl_ids'])
2661         vals = {
2662             'name': account_template.name,
2663             'currency_id': account_template.currency_id and account_template.currency_id.id or False,
2664             'code': account_template.code,
2665             'type': account_template.type,
2666             'user_type': account_template.user_type and account_template.user_type.id or False,
2667             'reconcile': account_template.reconcile,
2668             'shortcut': account_template.shortcut,
2669             'note': account_template.note,
2670             'parent_id': data['cparent_id'][0],
2671             'company_id': company_id,
2672             }
2673         acc_obj.create(cr, uid, vals)
2674         return {'type':'state', 'state': 'end' }
2675
2676     def action_cancel(self, cr, uid, ids, context=None):
2677         return { 'type': 'state', 'state': 'end' }
2678
2679
2680 class account_tax_code_template(osv.osv):
2681
2682     _name = 'account.tax.code.template'
2683     _description = 'Tax Code Template'
2684     _order = 'sequence, code'
2685     _rec_name = 'code'
2686     _columns = {
2687         'name': fields.char('Tax Case Name', required=True),
2688         'code': fields.char('Case Code', size=64),
2689         'info': fields.text('Description'),
2690         'parent_id': fields.many2one('account.tax.code.template', 'Parent Code', select=True),
2691         'child_ids': fields.one2many('account.tax.code.template', 'parent_id', 'Child Codes'),
2692         'sign': fields.float('Sign For Parent', required=True),
2693         'notprintable':fields.boolean("Not Printable in Invoice", help="Check this box if you don't want any tax related to this tax Code to appear on invoices."),
2694         'sequence': fields.integer(
2695             'Sequence', help=(
2696                 "Determine the display order in the report 'Accounting "
2697                 "\ Reporting \ Generic Reporting \ Taxes \ Taxes Report'"),
2698             ),
2699     }
2700
2701     _defaults = {
2702         'sign': 1.0,
2703         'notprintable': False,
2704     }
2705
2706     def generate_tax_code(self, cr, uid, tax_code_root_id, company_id, context=None):
2707         '''
2708         This function generates the tax codes from the templates of tax code that are children of the given one passed
2709         in argument. Then it returns a dictionary with the mappping between the templates and the real objects.
2710
2711         :param tax_code_root_id: id of the root of all the tax code templates to process
2712         :param company_id: id of the company the wizard is running for
2713         :returns: dictionary with the mappping between the templates and the real objects.
2714         :rtype: dict
2715         '''
2716         obj_tax_code_template = self.pool.get('account.tax.code.template')
2717         obj_tax_code = self.pool.get('account.tax.code')
2718         tax_code_template_ref = {}
2719         company = self.pool.get('res.company').browse(cr, uid, company_id, context=context)
2720
2721         #find all the children of the tax_code_root_id
2722         children_tax_code_template = tax_code_root_id and obj_tax_code_template.search(cr, uid, [('parent_id','child_of',[tax_code_root_id])], order='id') or []
2723         for tax_code_template in obj_tax_code_template.browse(cr, uid, children_tax_code_template, context=context):
2724             vals = {
2725                 'name': (tax_code_root_id == tax_code_template.id) and company.name or tax_code_template.name,
2726                 'code': tax_code_template.code,
2727                 'info': tax_code_template.info,
2728                 '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,
2729                 'company_id': company_id,
2730                 'sign': tax_code_template.sign,
2731                 'sequence': tax_code_template.sequence,
2732             }
2733             #check if this tax code already exists
2734             rec_list = obj_tax_code.search(cr, uid, [('name', '=', vals['name']),('code', '=', vals['code']),('company_id', '=', vals['company_id'])], context=context)
2735             if not rec_list:
2736                 #if not yet, create it
2737                 new_tax_code = obj_tax_code.create(cr, uid, vals)
2738                 #recording the new tax code to do the mapping
2739                 tax_code_template_ref[tax_code_template.id] = new_tax_code
2740         return tax_code_template_ref
2741
2742     def name_get(self, cr, uid, ids, context=None):
2743         if not ids:
2744             return []
2745         if isinstance(ids, (int, long)):
2746             ids = [ids]
2747         reads = self.read(cr, uid, ids, ['name','code'], context=context, load='_classic_write')
2748         return [(x['id'], (x['code'] and x['code'] + ' - ' or '') + x['name']) \
2749                 for x in reads]
2750
2751     _check_recursion = check_cycle
2752     _constraints = [
2753         (_check_recursion, 'Error!\nYou cannot create recursive Tax Codes.', ['parent_id'])
2754     ]
2755     _order = 'code,name'
2756
2757
2758 class account_chart_template(osv.osv):
2759     _name="account.chart.template"
2760     _description= "Templates for Account Chart"
2761
2762     _columns={
2763         'name': fields.char('Name', required=True),
2764         'parent_id': fields.many2one('account.chart.template', 'Parent Chart Template'),
2765         'code_digits': fields.integer('# of Digits', required=True, help="No. of Digits to use for account code"),
2766         'visible': fields.boolean('Can be Visible?', help="Set this to False if you don't want this template to be used actively in the wizard that generate Chart of Accounts from templates, this is useful when you want to generate accounts of this template only when loading its child template."),
2767         'currency_id': fields.many2one('res.currency', 'Currency'),
2768         'complete_tax_set': fields.boolean('Complete Set of Taxes', help='This boolean helps you to choose if you want to propose to the user to encode the sale and purchase rates or choose from list of taxes. This last choice assumes that the set of tax defined on this template is complete'),
2769         'account_root_id': fields.many2one('account.account.template', 'Root Account', domain=[('parent_id','=',False)]),
2770         'tax_code_root_id': fields.many2one('account.tax.code.template', 'Root Tax Code', domain=[('parent_id','=',False)]),
2771         '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'),
2772         'bank_account_view_id': fields.many2one('account.account.template', 'Bank Account'),
2773         'property_account_receivable': fields.many2one('account.account.template', 'Receivable Account'),
2774         'property_account_payable': fields.many2one('account.account.template', 'Payable Account'),
2775         'property_account_expense_categ': fields.many2one('account.account.template', 'Expense Category Account'),
2776         'property_account_income_categ': fields.many2one('account.account.template', 'Income Category Account'),
2777         'property_account_expense': fields.many2one('account.account.template', 'Expense Account on Product Template'),
2778         'property_account_income': fields.many2one('account.account.template', 'Income Account on Product Template'),
2779         'property_account_income_opening': fields.many2one('account.account.template', 'Opening Entries Income Account'),
2780         'property_account_expense_opening': fields.many2one('account.account.template', 'Opening Entries Expense Account'),
2781     }
2782
2783     _defaults = {
2784         'visible': True,
2785         'code_digits': 6,
2786         'complete_tax_set': True,
2787     }
2788
2789
2790 class account_tax_template(osv.osv):
2791
2792     _name = 'account.tax.template'
2793     _description = 'Templates for Taxes'
2794
2795     _columns = {
2796         'chart_template_id': fields.many2one('account.chart.template', 'Chart Template', required=True),
2797         'name': fields.char('Tax Name', required=True),
2798         '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."),
2799         'amount': fields.float('Amount', required=True, digits_compute=get_precision_tax(), help="For Tax Type percent enter % ratio between 0-1."),
2800         'type': fields.selection( [('percent','Percent'), ('fixed','Fixed'), ('none','None'), ('code','Python Code'), ('balance','Balance')], 'Tax Type', required=True),
2801         'applicable_type': fields.selection( [('true','True'), ('code','Python Code')], 'Applicable Type', required=True, help="If not applicable (computed through a Python code), the tax won't appear on the invoice."),
2802         'domain':fields.char('Domain', help="This field is only used if you develop your own module allowing developers to create specific taxes in a custom domain."),
2803         'account_collected_id':fields.many2one('account.account.template', 'Invoice Tax Account'),
2804         'account_paid_id':fields.many2one('account.account.template', 'Refund Tax Account'),
2805         'parent_id':fields.many2one('account.tax.template', 'Parent Tax Account', select=True),
2806         '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."),
2807         'python_compute':fields.text('Python Code'),
2808         'python_compute_inv':fields.text('Python Code (reverse)'),
2809         'python_applicable':fields.text('Applicable Code'),
2810
2811         #
2812         # Fields used for the Tax declaration
2813         #
2814         'base_code_id': fields.many2one('account.tax.code.template', 'Base Code', help="Use this code for the tax declaration."),
2815         'tax_code_id': fields.many2one('account.tax.code.template', 'Tax Code', help="Use this code for the tax declaration."),
2816         'base_sign': fields.float('Base Code Sign', help="Usually 1 or -1."),
2817         'tax_sign': fields.float('Tax Code Sign', help="Usually 1 or -1."),
2818
2819         # Same fields for refund invoices
2820
2821         'ref_base_code_id': fields.many2one('account.tax.code.template', 'Refund Base Code', help="Use this code for the tax declaration."),
2822         'ref_tax_code_id': fields.many2one('account.tax.code.template', 'Refund Tax Code', help="Use this code for the tax declaration."),
2823         'ref_base_sign': fields.float('Refund Base Code Sign', help="Usually 1 or -1."),
2824         'ref_tax_sign': fields.float('Refund Tax Code Sign', help="Usually 1 or -1."),
2825         '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."),
2826         'description': fields.char('Internal Name'),
2827         'type_tax_use': fields.selection([('sale','Sale'),('purchase','Purchase'),('all','All')], 'Tax Use In', required=True,),
2828         'price_include': fields.boolean('Tax Included in Price', help="Check this if the price you use on the product and invoices includes this tax."),
2829     }
2830
2831     def name_get(self, cr, uid, ids, context=None):
2832         if not ids:
2833             return []
2834         res = []
2835         for record in self.read(cr, uid, ids, ['description','name'], context=context):
2836             name = record['description'] and record['description'] or record['name']
2837             res.append((record['id'],name ))
2838         return res
2839
2840     def _default_company(self, cr, uid, context=None):
2841         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
2842         if user.company_id:
2843             return user.company_id.id
2844         return self.pool.get('res.company').search(cr, uid, [('parent_id', '=', False)])[0]
2845
2846     _defaults = {
2847         'python_compute': lambda *a: '''# price_unit\n# product: product.product object or None\n# partner: res.partner object or None\n\nresult = price_unit * 0.10''',
2848         'python_compute_inv': lambda *a: '''# price_unit\n# product: product.product object or False\n\nresult = price_unit * 0.10''',
2849         'applicable_type': 'true',
2850         'type': 'percent',
2851         'amount': 0,
2852         'sequence': 1,
2853         'ref_tax_sign': 1,
2854         'ref_base_sign': 1,
2855         'tax_sign': 1,
2856         'base_sign': 1,
2857         'include_base_amount': False,
2858         'type_tax_use': 'all',
2859         'price_include': 0,
2860     }
2861     _order = 'sequence'
2862
2863     def _generate_tax(self, cr, uid, tax_templates, tax_code_template_ref, company_id, context=None):
2864         """
2865         This method generate taxes from templates.
2866
2867         :param tax_templates: list of browse record of the tax templates to process
2868         :param tax_code_template_ref: Taxcode templates reference.
2869         :param company_id: id of the company the wizard is running for
2870         :returns:
2871             {
2872             'tax_template_to_tax': mapping between tax template and the newly generated taxes corresponding,
2873             'account_dict': dictionary containing a to-do list with all the accounts to assign on new taxes
2874             }
2875         """
2876         if context is None:
2877             context = {}
2878         res = {}
2879         todo_dict = {}
2880         tax_template_to_tax = {}
2881         for tax in tax_templates:
2882             vals_tax = {
2883                 'name':tax.name,
2884                 'sequence': tax.sequence,
2885                 'amount': tax.amount,
2886                 'type': tax.type,
2887                 'applicable_type': tax.applicable_type,
2888                 'domain': tax.domain,
2889                 'parent_id': tax.parent_id and ((tax.parent_id.id in tax_template_to_tax) and tax_template_to_tax[tax.parent_id.id]) or False,
2890                 'child_depend': tax.child_depend,
2891                 'python_compute': tax.python_compute,
2892                 'python_compute_inv': tax.python_compute_inv,
2893                 'python_applicable': tax.python_applicable,
2894                 '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,
2895                 '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,
2896                 'base_sign': tax.base_sign,
2897                 'tax_sign': tax.tax_sign,
2898                 '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,
2899                 '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,
2900                 'ref_base_sign': tax.ref_base_sign,
2901                 'ref_tax_sign': tax.ref_tax_sign,
2902                 'include_base_amount': tax.include_base_amount,
2903                 'description': tax.description,
2904                 'company_id': company_id,
2905                 'type_tax_use': tax.type_tax_use,
2906                 'price_include': tax.price_include
2907             }
2908             new_tax = self.pool.get('account.tax').create(cr, uid, vals_tax)
2909             tax_template_to_tax[tax.id] = new_tax
2910             #as the accounts have not been created yet, we have to wait before filling these fields
2911             todo_dict[new_tax] = {
2912                 'account_collected_id': tax.account_collected_id and tax.account_collected_id.id or False,
2913                 'account_paid_id': tax.account_paid_id and tax.account_paid_id.id or False,
2914             }
2915         res.update({'tax_template_to_tax': tax_template_to_tax, 'account_dict': todo_dict})
2916         return res
2917
2918
2919 # Fiscal Position Templates
2920
2921 class account_fiscal_position_template(osv.osv):
2922     _name = 'account.fiscal.position.template'
2923     _description = 'Template for Fiscal Position'
2924
2925     _columns = {
2926         'name': fields.char('Fiscal Position Template', required=True),
2927         'chart_template_id': fields.many2one('account.chart.template', 'Chart Template', required=True),
2928         'account_ids': fields.one2many('account.fiscal.position.account.template', 'position_id', 'Account Mapping'),
2929         'tax_ids': fields.one2many('account.fiscal.position.tax.template', 'position_id', 'Tax Mapping'),
2930         'note': fields.text('Notes'),
2931     }
2932
2933     def generate_fiscal_position(self, cr, uid, chart_temp_id, tax_template_ref, acc_template_ref, company_id, context=None):
2934         """
2935         This method generate Fiscal Position, Fiscal Position Accounts and Fiscal Position Taxes from templates.
2936
2937         :param chart_temp_id: Chart Template Id.
2938         :param taxes_ids: Taxes templates reference for generating account.fiscal.position.tax.
2939         :param acc_template_ref: Account templates reference for generating account.fiscal.position.account.
2940         :param company_id: company_id selected from wizard.multi.charts.accounts.
2941         :returns: True
2942         """
2943         if context is None:
2944             context = {}
2945         obj_tax_fp = self.pool.get('account.fiscal.position.tax')
2946         obj_ac_fp = self.pool.get('account.fiscal.position.account')
2947         obj_fiscal_position = self.pool.get('account.fiscal.position')
2948         fp_ids = self.search(cr, uid, [('chart_template_id', '=', chart_temp_id)])
2949         for position in self.browse(cr, uid, fp_ids, context=context):
2950             new_fp = obj_fiscal_position.create(cr, uid, {'company_id': company_id, 'name': position.name, 'note': position.note})
2951             for tax in position.tax_ids:
2952                 obj_tax_fp.create(cr, uid, {
2953                     'tax_src_id': tax_template_ref[tax.tax_src_id.id],
2954                     'tax_dest_id': tax.tax_dest_id and tax_template_ref[tax.tax_dest_id.id] or False,
2955                     'position_id': new_fp
2956                 })
2957             for acc in position.account_ids:
2958                 obj_ac_fp.create(cr, uid, {
2959                     'account_src_id': acc_template_ref[acc.account_src_id.id],
2960                     'account_dest_id': acc_template_ref[acc.account_dest_id.id],
2961                     'position_id': new_fp
2962                 })
2963         return True
2964
2965
2966 class account_fiscal_position_tax_template(osv.osv):
2967     _name = 'account.fiscal.position.tax.template'
2968     _description = 'Template Tax Fiscal Position'
2969     _rec_name = 'position_id'
2970
2971     _columns = {
2972         'position_id': fields.many2one('account.fiscal.position.template', 'Fiscal Position', required=True, ondelete='cascade'),
2973         'tax_src_id': fields.many2one('account.tax.template', 'Tax Source', required=True),
2974         'tax_dest_id': fields.many2one('account.tax.template', 'Replacement Tax')
2975     }
2976
2977
2978 class account_fiscal_position_account_template(osv.osv):
2979     _name = 'account.fiscal.position.account.template'
2980     _description = 'Template Account Fiscal Mapping'
2981     _rec_name = 'position_id'
2982     _columns = {
2983         'position_id': fields.many2one('account.fiscal.position.template', 'Fiscal Mapping', required=True, ondelete='cascade'),
2984         'account_src_id': fields.many2one('account.account.template', 'Account Source', domain=[('type','<>','view')], required=True),
2985         'account_dest_id': fields.many2one('account.account.template', 'Account Destination', domain=[('type','<>','view')], required=True)
2986     }
2987
2988
2989 # ---------------------------------------------------------
2990 # Account generation from template wizards
2991 # ---------------------------------------------------------
2992
2993 class wizard_multi_charts_accounts(osv.osv_memory):
2994     """
2995     Create a new account chart for a company.
2996     Wizards ask for:
2997         * a company
2998         * an account chart template
2999         * a number of digits for formatting code of non-view accounts
3000         * a list of bank accounts owned by the company
3001     Then, the wizard:
3002         * generates all accounts from the template and assigns them to the right company
3003         * generates all taxes and tax codes, changing account assignations
3004         * generates all accounting properties and assigns them correctly
3005     """
3006     _name='wizard.multi.charts.accounts'
3007     _inherit = 'res.config'
3008
3009     _columns = {
3010         'company_id':fields.many2one('res.company', 'Company', required=True),
3011         'currency_id': fields.many2one('res.currency', 'Currency', help="Currency as per company's country."),
3012         'only_one_chart_template': fields.boolean('Only One Chart Template Available'),
3013         'chart_template_id': fields.many2one('account.chart.template', 'Chart Template', required=True),
3014         'bank_accounts_id': fields.one2many('account.bank.accounts.wizard', 'bank_account_id', 'Cash and Banks', required=True),
3015         'code_digits':fields.integer('# of Digits', required=True, help="No. of Digits to use for account code"),
3016         "sale_tax": fields.many2one("account.tax.template", "Default Sale Tax"),
3017         "purchase_tax": fields.many2one("account.tax.template", "Default Purchase Tax"),
3018         'sale_tax_rate': fields.float('Sales Tax(%)'),
3019         'purchase_tax_rate': fields.float('Purchase Tax(%)'),
3020         'complete_tax_set': fields.boolean('Complete Set of Taxes', help='This boolean helps you to choose if you want to propose to the user to encode the sales and purchase rates or use the usual m2o fields. This last choice assumes that the set of tax defined for the chosen template is complete'),
3021     }
3022
3023
3024     def _get_chart_parent_ids(self, cr, uid, chart_template, context=None):
3025         """ Returns the IDs of all ancestor charts, including the chart itself.
3026             (inverse of child_of operator)
3027         
3028             :param browse_record chart_template: the account.chart.template record
3029             :return: the IDS of all ancestor charts, including the chart itself.
3030         """
3031         result = [chart_template.id]
3032         while chart_template.parent_id:
3033             chart_template = chart_template.parent_id
3034             result.append(chart_template.id)
3035         return result
3036
3037     def onchange_tax_rate(self, cr, uid, ids, rate=False, context=None):
3038         return {'value': {'purchase_tax_rate': rate or False}}
3039
3040     def onchange_chart_template_id(self, cr, uid, ids, chart_template_id=False, context=None):
3041         res = {}
3042         tax_templ_obj = self.pool.get('account.tax.template')
3043         res['value'] = {'complete_tax_set': False, 'sale_tax': False, 'purchase_tax': False}
3044         if chart_template_id:
3045             data = self.pool.get('account.chart.template').browse(cr, uid, chart_template_id, context=context)
3046             currency_id = data.currency_id and data.currency_id.id or self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.currency_id.id
3047             res['value'].update({'complete_tax_set': data.complete_tax_set, 'currency_id': currency_id})
3048             if data.complete_tax_set:
3049             # default tax is given by the lowest sequence. For same sequence we will take the latest created as it will be the case for tax created while isntalling the generic chart of account
3050                 chart_ids = self._get_chart_parent_ids(cr, uid, data, context=context)
3051                 base_tax_domain = [("chart_template_id", "in", chart_ids), ('parent_id', '=', False)]
3052                 sale_tax_domain = base_tax_domain + [('type_tax_use', 'in', ('sale','all'))]
3053                 purchase_tax_domain = base_tax_domain + [('type_tax_use', 'in', ('purchase','all'))]
3054                 sale_tax_ids = tax_templ_obj.search(cr, uid, sale_tax_domain, order="sequence, id desc")
3055                 purchase_tax_ids = tax_templ_obj.search(cr, uid, purchase_tax_domain, order="sequence, id desc")
3056                 res['value'].update({'sale_tax': sale_tax_ids and sale_tax_ids[0] or False,
3057                                      'purchase_tax': purchase_tax_ids and purchase_tax_ids[0] or False})
3058                 res.setdefault('domain', {})
3059                 res['domain']['sale_tax'] = repr(sale_tax_domain)
3060                 res['domain']['purchase_tax'] = repr(purchase_tax_domain)
3061             if data.code_digits:
3062                res['value'].update({'code_digits': data.code_digits})
3063         return res
3064
3065     def default_get(self, cr, uid, fields, context=None):
3066         res = super(wizard_multi_charts_accounts, self).default_get(cr, uid, fields, context=context)
3067         tax_templ_obj = self.pool.get('account.tax.template')
3068         account_chart_template = self.pool['account.chart.template']
3069
3070         if 'bank_accounts_id' in fields:
3071             res.update({'bank_accounts_id': [{'acc_name': _('Cash'), 'account_type': 'cash'},{'acc_name': _('Bank'), 'account_type': 'bank'}]})
3072         if 'company_id' in fields:
3073             res.update({'company_id': self.pool.get('res.users').browse(cr, uid, [uid], context=context)[0].company_id.id})
3074         if 'currency_id' in fields:
3075             company_id = res.get('company_id') or False
3076             if company_id:
3077                 company_obj = self.pool.get('res.company')
3078                 country_id = company_obj.browse(cr, uid, company_id, context=context).country_id.id
3079                 currency_id = company_obj.on_change_country(cr, uid, company_id, country_id, context=context)['value']['currency_id']
3080                 res.update({'currency_id': currency_id})
3081
3082         ids = account_chart_template.search(cr, uid, [('visible', '=', True)], context=context)
3083         if ids:
3084             #in order to set default chart which was last created set max of ids.
3085             chart_id = max(ids)
3086             if context.get("default_charts"):
3087                 model_data = self.pool.get('ir.model.data').search_read(cr, uid, [('model','=','account.chart.template'),('module','=',context.get("default_charts"))], ['res_id'], context=context)
3088                 if model_data:
3089                     chart_id = model_data[0]['res_id']
3090             chart = account_chart_template.browse(cr, uid, chart_id, context=context)
3091             chart_hierarchy_ids = self._get_chart_parent_ids(cr, uid, chart, context=context) 
3092             if 'chart_template_id' in fields:
3093                 res.update({'only_one_chart_template': len(ids) == 1,
3094                             'chart_template_id': chart_id})
3095             if 'sale_tax' in fields:
3096                 sale_tax_ids = tax_templ_obj.search(cr, uid, [("chart_template_id", "in", chart_hierarchy_ids),
3097                                                               ('type_tax_use', 'in', ('sale','all'))],
3098                                                     order="sequence")
3099                 res.update({'sale_tax': sale_tax_ids and sale_tax_ids[0] or False})
3100             if 'purchase_tax' in fields:
3101                 purchase_tax_ids = tax_templ_obj.search(cr, uid, [("chart_template_id", "in", chart_hierarchy_ids),
3102                                                                   ('type_tax_use', 'in', ('purchase','all'))],
3103                                                         order="sequence")
3104                 res.update({'purchase_tax': purchase_tax_ids and purchase_tax_ids[0] or False})
3105         res.update({
3106             'purchase_tax_rate': 15.0,
3107             'sale_tax_rate': 15.0,
3108         })
3109         return res
3110
3111     def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
3112         if context is None:context = {}
3113         res = super(wizard_multi_charts_accounts, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar,submenu=False)
3114         cmp_select = []
3115         acc_template_obj = self.pool.get('account.chart.template')
3116         company_obj = self.pool.get('res.company')
3117
3118         company_ids = company_obj.search(cr, uid, [], context=context)
3119         #display in the widget selection of companies, only the companies that haven't been configured yet (but don't care about the demo chart of accounts)
3120         cr.execute("SELECT company_id FROM account_account WHERE active = 't' AND account_account.parent_id IS NULL AND name != %s", ("Chart For Automated Tests",))
3121         configured_cmp = [r[0] for r in cr.fetchall()]
3122         unconfigured_cmp = list(set(company_ids)-set(configured_cmp))
3123         for field in res['fields']:
3124             if field == 'company_id':
3125                 res['fields'][field]['domain'] = [('id','in',unconfigured_cmp)]
3126                 res['fields'][field]['selection'] = [('', '')]
3127                 if unconfigured_cmp:
3128                     cmp_select = [(line.id, line.name) for line in company_obj.browse(cr, uid, unconfigured_cmp)]
3129                     res['fields'][field]['selection'] = cmp_select
3130         return res
3131
3132     def check_created_journals(self, cr, uid, vals_journal, company_id, context=None):
3133         """
3134         This method used for checking journals already created or not. If not then create new journal.
3135         """
3136         obj_journal = self.pool.get('account.journal')
3137         rec_list = obj_journal.search(cr, uid, [('name','=', vals_journal['name']),('company_id', '=', company_id)], context=context)
3138         if not rec_list:
3139             obj_journal.create(cr, uid, vals_journal, context=context)
3140         return True
3141
3142     def generate_journals(self, cr, uid, chart_template_id, acc_template_ref, company_id, context=None):
3143         """
3144         This method is used for creating journals.
3145
3146         :param chart_temp_id: Chart Template Id.
3147         :param acc_template_ref: Account templates reference.
3148         :param company_id: company_id selected from wizard.multi.charts.accounts.
3149         :returns: True
3150         """
3151         journal_data = self._prepare_all_journals(cr, uid, chart_template_id, acc_template_ref, company_id, context=context)
3152         for vals_journal in journal_data:
3153             self.check_created_journals(cr, uid, vals_journal, company_id, context=context)
3154         return True
3155
3156     def _prepare_all_journals(self, cr, uid, chart_template_id, acc_template_ref, company_id, context=None):
3157         def _get_analytic_journal(journal_type):
3158             # Get the analytic journal
3159             data = False
3160             try:
3161                 if journal_type in ('sale', 'sale_refund'):
3162                     data = obj_data.get_object_reference(cr, uid, 'account', 'analytic_journal_sale')
3163                 elif journal_type in ('purchase', 'purchase_refund'):
3164                     data = obj_data.get_object_reference(cr, uid, 'account', 'exp')
3165                 elif journal_type == 'general':
3166                     pass
3167             except ValueError:
3168                 pass
3169             return data and data[1] or False
3170
3171         def _get_default_account(journal_type, type='debit'):
3172             # Get the default accounts
3173             default_account = False
3174             if journal_type in ('sale', 'sale_refund'):
3175                 default_account = acc_template_ref.get(template.property_account_income_categ.id)
3176             elif journal_type in ('purchase', 'purchase_refund'):
3177                 default_account = acc_template_ref.get(template.property_account_expense_categ.id)
3178             elif journal_type == 'situation':
3179                 if type == 'debit':
3180                     default_account = acc_template_ref.get(template.property_account_expense_opening.id)
3181                 else:
3182                     default_account = acc_template_ref.get(template.property_account_income_opening.id)
3183             return default_account
3184
3185         journal_names = {
3186             'sale': _('Sales Journal'),
3187             'purchase': _('Purchase Journal'),
3188             'sale_refund': _('Sales Refund Journal'),
3189             'purchase_refund': _('Purchase Refund Journal'),
3190             'general': _('Miscellaneous Journal'),
3191             'situation': _('Opening Entries Journal'),
3192         }
3193         journal_codes = {
3194             'sale': _('SAJ'),
3195             'purchase': _('EXJ'),
3196             'sale_refund': _('SCNJ'),
3197             'purchase_refund': _('ECNJ'),
3198             'general': _('MISC'),
3199             'situation': _('OPEJ'),
3200         }
3201
3202         obj_data = self.pool.get('ir.model.data')
3203         analytic_journal_obj = self.pool.get('account.analytic.journal')
3204         template = self.pool.get('account.chart.template').browse(cr, uid, chart_template_id, context=context)
3205
3206         journal_data = []
3207         for journal_type in ['sale', 'purchase', 'sale_refund', 'purchase_refund', 'general', 'situation']:
3208             vals = {
3209                 'type': journal_type,
3210                 'name': journal_names[journal_type],
3211                 'code': journal_codes[journal_type],
3212                 'company_id': company_id,
3213                 'centralisation': journal_type == 'situation',
3214                 'analytic_journal_id': _get_analytic_journal(journal_type),
3215                 'default_credit_account_id': _get_default_account(journal_type, 'credit'),
3216                 'default_debit_account_id': _get_default_account(journal_type, 'debit'),
3217             }
3218             journal_data.append(vals)
3219         return journal_data
3220
3221     def generate_properties(self, cr, uid, chart_template_id, acc_template_ref, company_id, context=None):
3222         """
3223         This method used for creating properties.
3224
3225         :param chart_template_id: id of the current chart template for which we need to create properties
3226         :param acc_template_ref: Mapping between ids of account templates and real accounts created from them
3227         :param company_id: company_id selected from wizard.multi.charts.accounts.
3228         :returns: True
3229         """
3230         property_obj = self.pool.get('ir.property')
3231         field_obj = self.pool.get('ir.model.fields')
3232         todo_list = [
3233             ('property_account_receivable','res.partner','account.account'),
3234             ('property_account_payable','res.partner','account.account'),
3235             ('property_account_expense_categ','product.category','account.account'),
3236             ('property_account_income_categ','product.category','account.account'),
3237             ('property_account_expense','product.template','account.account'),
3238             ('property_account_income','product.template','account.account'),
3239         ]
3240         template = self.pool.get('account.chart.template').browse(cr, uid, chart_template_id, context=context)
3241         for record in todo_list:
3242             account = getattr(template, record[0])
3243             value = account and 'account.account,' + str(acc_template_ref[account.id]) or False
3244             if value:
3245                 field = field_obj.search(cr, uid, [('name', '=', record[0]),('model', '=', record[1]),('relation', '=', record[2])], context=context)
3246                 vals = {
3247                     'name': record[0],
3248                     'company_id': company_id,
3249                     'fields_id': field[0],
3250                     'value': value,
3251                 }
3252                 property_ids = property_obj.search(cr, uid, [('name','=', record[0]),('company_id', '=', company_id)], context=context)
3253                 if property_ids:
3254                     #the property exist: modify it
3255                     property_obj.write(cr, uid, property_ids, vals, context=context)
3256                 else:
3257                     #create the property
3258                     property_obj.create(cr, uid, vals, context=context)
3259         return True
3260
3261     def _install_template(self, cr, uid, template_id, company_id, code_digits=None, obj_wizard=None, acc_ref=None, taxes_ref=None, tax_code_ref=None, context=None):
3262         '''
3263         This function recursively loads the template objects and create the real objects from them.
3264
3265         :param template_id: id of the chart template to load
3266         :param company_id: id of the company the wizard is running for
3267         :param code_digits: integer that depicts the number of digits the accounts code should have in the COA
3268         :param obj_wizard: the current wizard for generating the COA from the templates
3269         :param acc_ref: Mapping between ids of account templates and real accounts created from them
3270         :param taxes_ref: Mapping between ids of tax templates and real taxes created from them
3271         :param tax_code_ref: Mapping between ids of tax code templates and real tax codes created from them
3272         :returns: return a tuple with a dictionary containing
3273             * the mapping between the account template ids and the ids of the real accounts that have been generated
3274               from them, as first item,
3275             * a similar dictionary for mapping the tax templates and taxes, as second item,
3276             * a last identical containing the mapping of tax code templates and tax codes
3277         :rtype: tuple(dict, dict, dict)
3278         '''
3279         if acc_ref is None:
3280             acc_ref = {}
3281         if taxes_ref is None:
3282             taxes_ref = {}
3283         if tax_code_ref is None:
3284             tax_code_ref = {}
3285         template = self.pool.get('account.chart.template').browse(cr, uid, template_id, context=context)
3286         if template.parent_id:
3287             tmp1, tmp2, tmp3 = self._install_template(cr, uid, template.parent_id.id, company_id, code_digits=code_digits, acc_ref=acc_ref, taxes_ref=taxes_ref, tax_code_ref=tax_code_ref, context=context)
3288             acc_ref.update(tmp1)
3289             taxes_ref.update(tmp2)
3290             tax_code_ref.update(tmp3)
3291         tmp1, tmp2, tmp3 = self._load_template(cr, uid, template_id, company_id, code_digits=code_digits, obj_wizard=obj_wizard, account_ref=acc_ref, taxes_ref=taxes_ref, tax_code_ref=tax_code_ref, context=context)
3292         acc_ref.update(tmp1)
3293         taxes_ref.update(tmp2)
3294         tax_code_ref.update(tmp3)
3295         return acc_ref, taxes_ref, tax_code_ref
3296
3297     def _load_template(self, cr, uid, template_id, company_id, code_digits=None, obj_wizard=None, account_ref=None, taxes_ref=None, tax_code_ref=None, context=None):
3298         '''
3299         This function generates all the objects from the templates
3300
3301         :param template_id: id of the chart template to load
3302         :param company_id: id of the company the wizard is running for
3303         :param code_digits: integer that depicts the number of digits the accounts code should have in the COA
3304         :param obj_wizard: the current wizard for generating the COA from the templates
3305         :param acc_ref: Mapping between ids of account templates and real accounts created from them
3306         :param taxes_ref: Mapping between ids of tax templates and real taxes created from them
3307         :param tax_code_ref: Mapping between ids of tax code templates and real tax codes created from them
3308         :returns: return a tuple with a dictionary containing
3309             * the mapping between the account template ids and the ids of the real accounts that have been generated
3310               from them, as first item,
3311             * a similar dictionary for mapping the tax templates and taxes, as second item,
3312             * a last identical containing the mapping of tax code templates and tax codes
3313         :rtype: tuple(dict, dict, dict)
3314         '''
3315         if account_ref is None:
3316             account_ref = {}
3317         if taxes_ref is None:
3318             taxes_ref = {}
3319         if tax_code_ref is None:
3320             tax_code_ref = {}
3321         template = self.pool.get('account.chart.template').browse(cr, uid, template_id, context=context)
3322         obj_tax_code_template = self.pool.get('account.tax.code.template')
3323         obj_acc_tax = self.pool.get('account.tax')
3324         obj_tax_temp = self.pool.get('account.tax.template')
3325         obj_acc_template = self.pool.get('account.account.template')
3326         obj_fiscal_position_template = self.pool.get('account.fiscal.position.template')
3327
3328         # create all the tax code.
3329         tax_code_ref.update(obj_tax_code_template.generate_tax_code(cr, uid, template.tax_code_root_id.id, company_id, context=context))
3330
3331         # Generate taxes from templates.
3332         tax_templates = [x for x in template.tax_template_ids]
3333         generated_tax_res = obj_tax_temp._generate_tax(cr, uid, tax_templates, tax_code_ref, company_id, context=context)
3334         taxes_ref.update(generated_tax_res['tax_template_to_tax'])
3335
3336         # Generating Accounts from templates.
3337         account_template_ref = obj_acc_template.generate_account(cr, uid, template_id, taxes_ref, account_ref, code_digits, company_id, context=context)
3338         account_ref.update(account_template_ref)
3339
3340         # writing account values on tax after creation of accounts
3341         for key,value in generated_tax_res['account_dict'].items():
3342             if value['account_collected_id'] or value['account_paid_id']:
3343                 obj_acc_tax.write(cr, uid, [key], {
3344                     'account_collected_id': account_ref.get(value['account_collected_id'], False),
3345                     'account_paid_id': account_ref.get(value['account_paid_id'], False),
3346                 })
3347
3348         # Create Journals
3349         self.generate_journals(cr, uid, template_id, account_ref, company_id, context=context)
3350
3351         # generate properties function
3352         self.generate_properties(cr, uid, template_id, account_ref, company_id, context=context)
3353
3354         # Generate Fiscal Position , Fiscal Position Accounts and Fiscal Position Taxes from templates
3355         obj_fiscal_position_template.generate_fiscal_position(cr, uid, template_id, taxes_ref, account_ref, company_id, context=context)
3356
3357         return account_ref, taxes_ref, tax_code_ref
3358
3359     def _create_tax_templates_from_rates(self, cr, uid, obj_wizard, company_id, context=None):
3360         '''
3361         This function checks if the chosen chart template is configured as containing a full set of taxes, and if
3362         it's not the case, it creates the templates for account.tax.code and for account.account.tax objects accordingly
3363         to the provided sale/purchase rates. Then it saves the new tax templates as default taxes to use for this chart
3364         template.
3365
3366         :param obj_wizard: browse record of wizard to generate COA from templates
3367         :param company_id: id of the company for wich the wizard is running
3368         :return: True
3369         '''
3370         obj_tax_code_template = self.pool.get('account.tax.code.template')
3371         obj_tax_temp = self.pool.get('account.tax.template')
3372         chart_template = obj_wizard.chart_template_id
3373         vals = {}
3374         all_parents = self._get_chart_parent_ids(cr, uid, chart_template, context=context)
3375         # create tax templates and tax code templates from purchase_tax_rate and sale_tax_rate fields
3376         if not chart_template.complete_tax_set:
3377             value = obj_wizard.sale_tax_rate
3378             ref_tax_ids = obj_tax_temp.search(cr, uid, [('type_tax_use','in', ('sale','all')), ('chart_template_id', 'in', all_parents)], context=context, order="sequence, id desc", limit=1)
3379             obj_tax_temp.write(cr, uid, ref_tax_ids, {'amount': value/100.0, 'name': _('Tax %.2f%%') % value})
3380             value = obj_wizard.purchase_tax_rate
3381             ref_tax_ids = obj_tax_temp.search(cr, uid, [('type_tax_use','in', ('purchase','all')), ('chart_template_id', 'in', all_parents)], context=context, order="sequence, id desc", limit=1)
3382             obj_tax_temp.write(cr, uid, ref_tax_ids, {'amount': value/100.0, 'name': _('Purchase Tax %.2f%%') % value})
3383         return True
3384
3385     def execute(self, cr, uid, ids, context=None):
3386         '''
3387         This function is called at the confirmation of the wizard to generate the COA from the templates. It will read
3388         all the provided information to create the accounts, the banks, the journals, the taxes, the tax codes, the
3389         accounting properties... accordingly for the chosen company.
3390         '''
3391         if uid != SUPERUSER_ID and not self.pool['res.users'].has_group(cr, uid, 'base.group_erp_manager'):
3392             raise openerp.exceptions.AccessError(_("Only administrators can change the settings"))
3393         obj_data = self.pool.get('ir.model.data')
3394         ir_values_obj = self.pool.get('ir.values')
3395         obj_wizard = self.browse(cr, uid, ids[0])
3396         company_id = obj_wizard.company_id.id
3397
3398         self.pool.get('res.company').write(cr, uid, [company_id], {'currency_id': obj_wizard.currency_id.id})
3399
3400         # When we install the CoA of first company, set the currency to price types and pricelists
3401         if company_id==1:
3402             for ref in (('product','list_price'),('product','standard_price'),('product','list0'),('purchase','list0')):
3403                 try:
3404                     tmp2 = obj_data.get_object_reference(cr, uid, *ref)
3405                     if tmp2: 
3406                         self.pool[tmp2[0]].write(cr, uid, tmp2[1], {
3407                             'currency_id': obj_wizard.currency_id.id
3408                         })
3409                 except ValueError:
3410                     pass
3411
3412         # If the floats for sale/purchase rates have been filled, create templates from them
3413         self._create_tax_templates_from_rates(cr, uid, obj_wizard, company_id, context=context)
3414
3415         # Install all the templates objects and generate the real objects
3416         acc_template_ref, taxes_ref, tax_code_ref = self._install_template(cr, uid, obj_wizard.chart_template_id.id, company_id, code_digits=obj_wizard.code_digits, obj_wizard=obj_wizard, context=context)
3417
3418         # write values of default taxes for product as super user
3419         if obj_wizard.sale_tax and taxes_ref:
3420             ir_values_obj.set_default(cr, SUPERUSER_ID, 'product.template', "taxes_id", [taxes_ref[obj_wizard.sale_tax.id]], for_all_users=True, company_id=company_id)
3421         if obj_wizard.purchase_tax and taxes_ref:
3422             ir_values_obj.set_default(cr, SUPERUSER_ID, 'product.template', "supplier_taxes_id", [taxes_ref[obj_wizard.purchase_tax.id]], for_all_users=True, company_id=company_id)
3423
3424         # Create Bank journals
3425         self._create_bank_journals_from_o2m(cr, uid, obj_wizard, company_id, acc_template_ref, context=context)
3426         return {}
3427
3428     def _prepare_bank_journal(self, cr, uid, line, current_num, default_account_id, company_id, context=None):
3429         '''
3430         This function prepares the value to use for the creation of a bank journal created through the wizard of
3431         generating COA from templates.
3432
3433         :param line: dictionary containing the values encoded by the user related to his bank account
3434         :param current_num: integer corresponding to a counter of the already created bank journals through this wizard.
3435         :param default_account_id: id of the default debit.credit account created before for this journal.
3436         :param company_id: id of the company for which the wizard is running
3437         :return: mapping of field names and values
3438         :rtype: dict
3439         '''
3440         obj_data = self.pool.get('ir.model.data')
3441         obj_journal = self.pool.get('account.journal')
3442         
3443
3444         # we need to loop again to find next number for journal code
3445         # because we can't rely on the value current_num as,
3446         # its possible that we already have bank journals created (e.g. by the creation of res.partner.bank)
3447         # and the next number for account code might have been already used before for journal
3448         for num in xrange(current_num, 100):
3449             # journal_code has a maximal size of 5, hence we can enforce the boundary num < 100
3450             journal_code = _('BNK')[:3] + str(num)
3451             ids = obj_journal.search(cr, uid, [('code', '=', journal_code), ('company_id', '=', company_id)], context=context)
3452             if not ids:
3453                 break
3454         else:
3455             raise osv.except_osv(_('Error!'), _('Cannot generate an unused journal code.'))
3456
3457         vals = {
3458                 'name': line['acc_name'],
3459                 'code': journal_code,
3460                 'type': line['account_type'] == 'cash' and 'cash' or 'bank',
3461                 'company_id': company_id,
3462                 'analytic_journal_id': False,
3463                 'currency': False,
3464                 'default_credit_account_id': default_account_id,
3465                 'default_debit_account_id': default_account_id,
3466         }
3467         if line['currency_id']:
3468             vals['currency'] = line['currency_id']
3469         
3470         return vals
3471
3472     def _prepare_bank_account(self, cr, uid, line, new_code, acc_template_ref, ref_acc_bank, company_id, context=None):
3473         '''
3474         This function prepares the value to use for the creation of the default debit and credit accounts of a
3475         bank journal created through the wizard of generating COA from templates.
3476
3477         :param line: dictionary containing the values encoded by the user related to his bank account
3478         :param new_code: integer corresponding to the next available number to use as account code
3479         :param acc_template_ref: the dictionary containing the mapping between the ids of account templates and the ids
3480             of the accounts that have been generated from them.
3481         :param ref_acc_bank: browse record of the account template set as root of all bank accounts for the chosen
3482             template
3483         :param company_id: id of the company for which the wizard is running
3484         :return: mapping of field names and values
3485         :rtype: dict
3486         '''
3487         obj_data = self.pool.get('ir.model.data')
3488
3489         # Get the id of the user types fr-or cash and bank
3490         tmp = obj_data.get_object_reference(cr, uid, 'account', 'data_account_type_cash')
3491         cash_type = tmp and tmp[1] or False
3492         tmp = obj_data.get_object_reference(cr, uid, 'account', 'data_account_type_bank')
3493         bank_type = tmp and tmp[1] or False
3494         return {
3495                 'name': line['acc_name'],
3496                 'currency_id': line['currency_id'],
3497                 'code': new_code,
3498                 'type': 'liquidity',
3499                 'user_type': line['account_type'] == 'cash' and cash_type or bank_type,
3500                 'parent_id': acc_template_ref[ref_acc_bank.id] or False,
3501                 'company_id': company_id,
3502         }
3503
3504     def _create_bank_journals_from_o2m(self, cr, uid, obj_wizard, company_id, acc_template_ref, context=None):
3505         '''
3506         This function creates bank journals and its accounts for each line encoded in the field bank_accounts_id of the
3507         wizard.
3508
3509         :param obj_wizard: the current wizard that generates the COA from the templates.
3510         :param company_id: the id of the company for which the wizard is running.
3511         :param acc_template_ref: the dictionary containing the mapping between the ids of account templates and the ids
3512             of the accounts that have been generated from them.
3513         :return: True
3514         '''
3515         obj_acc = self.pool.get('account.account')
3516         obj_journal = self.pool.get('account.journal')
3517         code_digits = obj_wizard.code_digits
3518
3519         # Build a list with all the data to process
3520         journal_data = []
3521         if obj_wizard.bank_accounts_id:
3522             for acc in obj_wizard.bank_accounts_id:
3523                 vals = {
3524                     'acc_name': acc.acc_name,
3525                     'account_type': acc.account_type,
3526                     'currency_id': acc.currency_id.id,
3527                 }
3528                 journal_data.append(vals)
3529         ref_acc_bank = obj_wizard.chart_template_id.bank_account_view_id
3530         if journal_data and not ref_acc_bank.code:
3531             raise osv.except_osv(_('Configuration Error!'), _('You have to set a code for the bank account defined on the selected chart of accounts.'))
3532
3533         current_num = 1
3534         for line in journal_data:
3535             # Seek the next available number for the account code
3536             while True:
3537                 new_code = str(ref_acc_bank.code.ljust(code_digits-len(str(current_num)), '0')) + str(current_num)
3538                 ids = obj_acc.search(cr, uid, [('code', '=', new_code), ('company_id', '=', company_id)])
3539                 if not ids:
3540                     break
3541                 else:
3542                     current_num += 1
3543             # Create the default debit/credit accounts for this bank journal
3544             vals = self._prepare_bank_account(cr, uid, line, new_code, acc_template_ref, ref_acc_bank, company_id, context=context)
3545             default_account_id  = obj_acc.create(cr, uid, vals, context=context)
3546
3547             #create the bank journal
3548             vals_journal = self._prepare_bank_journal(cr, uid, line, current_num, default_account_id, company_id, context=context)
3549             obj_journal.create(cr, uid, vals_journal)
3550             current_num += 1
3551         return True
3552
3553
3554 class account_bank_accounts_wizard(osv.osv_memory):
3555     _name='account.bank.accounts.wizard'
3556
3557     _columns = {
3558         'acc_name': fields.char('Account Name.', required=True),
3559         'bank_account_id': fields.many2one('wizard.multi.charts.accounts', 'Bank Account', required=True, ondelete='cascade'),
3560         'currency_id': fields.many2one('res.currency', 'Secondary Currency', help="Forces all moves for this account to have this secondary currency."),
3561         'account_type': fields.selection([('cash','Cash'), ('check','Check'), ('bank','Bank')], 'Account Type'),
3562     }
3563
3564
3565 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: