~unifield-team/unifield-wm/us-826

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2011 MSF, TeMPO Consulting.
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

import datetime
from osv import fields, osv
from tools.translate import _
from time import strftime

class account_analytic_chart(osv.osv_memory):
    _inherit = "account.analytic.chart"
    _columns = {
        'show_inactive': fields.boolean('Show inactive accounts'),
        'currency_id': fields.many2one('res.currency', 'Currency', help="Only display items from the given currency"),
        'fiscalyear': fields.many2one('account.fiscalyear', 'Fiscal year', help = 'Keep empty for all open fiscal years'),
        'output_currency_id': fields.many2one('res.currency', 'Output currency', help="Add a new column that display lines amounts in the given currency"),
    }

    _defaults = {
        'fiscalyear': lambda self, cr, uid, c: self.pool.get('account.fiscalyear').find(cr, uid, datetime.date.today(), False, c),
    }

    def onchange_fiscalyear(self, cr, uid, ids, fiscalyear_id=False, context=None):
        res = {}
        res['value'] = {}
        if fiscalyear_id:
            start_period = end_period = False
            cr.execute('''
                SELECT * FROM (SELECT p.id
                               FROM account_period p
                               LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id)
                               WHERE f.id = %s
                               ORDER BY p.date_start ASC
                               LIMIT 1) AS period_start
                UNION
                SELECT * FROM (SELECT p.id
                               FROM account_period p
                               LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id)
                               WHERE f.id = %s
                               AND p.date_start < NOW()
                               ORDER BY p.date_stop DESC
                               LIMIT 1) AS period_stop''', (fiscalyear_id, fiscalyear_id))
            periods =  [i[0] for i in cr.fetchall()]
            if periods and len(periods) > 1:
                p1 = self.pool.get('account.period').browse(cr, uid, [periods[0]])[0]
                start_period = p1.date_start
                p2 = self.pool.get('account.period').browse(cr, uid, [periods[1]])[0]
                end_period = p2.date_stop
            res['value'] = {'from_date': start_period, 'to_date': end_period}
        return res

    def analytic_account_chart_open_window(self, cr, uid, ids, context=None):
        result = super(account_analytic_chart, self).analytic_account_chart_open_window(cr, uid, ids, context=context)
        # add 'active_test' to the result's context; this allows to show or hide inactive items
        data = self.read(cr, uid, ids, [], context=context)[0]
        context = eval(result['context'])
        context['filter_inactive'] = not data['show_inactive']
        if data['currency_id']:
            context['currency_id'] = data['currency_id']
        result['name'] = _('Balance by analytic account')
        if data['fiscalyear']:
            result['name'] += ': ' + self.pool.get('account.fiscalyear').read(cr, uid, [data['fiscalyear']], context=context)[0]['code']
        if data['output_currency_id']:
            context['output_currency_id'] = data['output_currency_id']
        # Display FP on result
        context['display_fp'] = True
        result['context'] = unicode(context)
        # UF-1718: Add a link on each account to display linked analytic items
        try:
            tree_view_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'analytic_distribution', 'balance_analytic_tree')
        except:
            tree_view_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'account', 'view_account_analytic_account_tree')
        finally:
            tree_view_id = tree_view_id and tree_view_id[1] or False
        result['view_id'] = [tree_view_id]
        result['views'] = [(tree_view_id, 'tree')]
        return result

    def button_export(self, cr, uid, ids, context=None):
        """
        Export chart of analytic account in a XML file
        """
        if not context:
            context = {}
        account_ids = []
        wiz_fields = {}
        for wiz in self.browse(cr, uid, ids):
            args = [('filter_active', '=', True)]
            if wiz.show_inactive == True:
                args += [('filter_active', 'in', [True, False])]
            if wiz.currency_id:
                context.update({'currency_id': wiz.currency_id.id,})
            if wiz.instance_ids:
                context.update({'instance_ids': [x.id for x in wiz.instance_ids],})
            if wiz.output_currency_id:
                context.update({'output_currency_id': wiz.output_currency_id.id})
            account_ids = self.pool.get('account.analytic.account').search(cr, uid, args, context=context)
            wiz_fields = {
                'fy': wiz.fiscalyear and wiz.fiscalyear.name or '',
                'from_date': wiz.from_date or '',
                'to_date': wiz.to_date or '',
                'instances': wiz.instance_ids and ','.join([x.name for x in wiz.instance_ids]) or '',
                'show_inactive': wiz.show_inactive and 'X' or '',
                'currency_filtering': wiz.currency_id and wiz.currency_id.name or '',
            }
        # UF-1718: Add currency name used from the wizard. If none, set it to "All" (no currency filtering)
        currency_name = _("No one specified")
        if context.get('output_currency_id', False):
            currency_name = self.pool.get('res.currency').browse(cr, uid, context.get('output_currency_id')).name or currency_name
        else:
            currency_name = self.pool.get('res.users').browse(cr, uid, uid).company_id.currency_id.name or currency_name
        # Prepare datas for the report
        instance_code = self.pool.get('res.users').browse(cr, uid, uid).company_id.instance_id.code
        datas = {
            'ids': account_ids,
            'context': context,
            'currency': currency_name,
            'wiz_fields': wiz_fields,
            'target_filename': "Balance by analytic account_%s_%s" % (instance_code, strftime('%Y%m%d')),
        } # context permit balance to be processed regarding context's elements
        return {
            'type': 'ir.actions.report.xml',
            'report_name': 'account.analytic.chart.export',
            'datas': datas,
        }

account_analytic_chart()

class account_analytic_coa(osv.osv_memory):
    _name = 'account.analytic.coa'
    _columns = {
        'fiscalyear': fields.many2one('account.fiscalyear', 'Fiscalyear'),
        'show_inactive': fields.boolean('Show inactive accounts'),
    }

    _defaults = {
        'show_inactive': lambda *a: False,
        'fiscalyear': lambda self, cr, uid, c: self.pool.get('account.fiscalyear').find(cr, uid, datetime.date.today(), False, c),
    }

    def button_validate(self, cr, uid, ids, context=None):
        """
        Open a chart of analytic account as a tree/tree
        """
        # Some checks
        if not context:
            context = {}
        # Prepare some values
        mod_obj = self.pool.get('ir.model.data')
        act_obj = self.pool.get('ir.actions.act_window')
        period_obj = self.pool.get('account.period')
        fy_obj = self.pool.get('account.fiscalyear')
        data = self.read(cr, uid, ids, [], context=context)[0]
        # Set period_from/to if fiscalyear given
        if data['fiscalyear']:
            periods = self.pool.get('account.analytic.chart').onchange_fiscalyear(cr, uid, ids, data['fiscalyear'], context)
            if 'value' in periods:
                data.update(periods.get('value'))
        # Create result
        result = mod_obj.get_object_reference(cr, uid, 'account', 'action_account_analytic_account_tree2')
        i = result and result[1] or False
        result = act_obj.read(cr, uid, [i], context=context)[0]
        result['periods'] = []
        if data.get('period_from', False) and data.get('period_to', False):
            result['periods'] = period_obj.build_ctx_periods(cr, uid, data['period_from'], data['period_to'])
        result['context'] = str({'fiscalyear': data['fiscalyear'], 'periods': result['periods']})
        result['name'] = _('Chart of Analytic Accounts')
        if data['fiscalyear']:
            result['name'] += ': ' + fy_obj.read(cr, uid, [data['fiscalyear']], context=context)[0]['code']
        # Set context regarding show_inactive field
        context['filter_inactive'] = not data['show_inactive']
        # Display FP on result
        context['display_fp'] = True
        result['context'] = unicode(context)
        # UF-1718: Add a link on each account to display linked analytic items
        tree_view_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'analytic_distribution', 'view_account_analytic_account_tree_coa')
        tree_view_id = tree_view_id and tree_view_id[1] or False
        result['view_id'] = [tree_view_id]
        result['views'] = [(tree_view_id, 'tree')]
        return result

account_analytic_coa()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: