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