~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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 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/>.
#
##############################################################################

from osv import fields, osv
import decimal_precision as dp
from tools.misc import flatten
from time import strftime

class analytic_distribution1(osv.osv):
    _name = "analytic.distribution"

    _columns = {
        'analytic_lines': fields.one2many('account.analytic.line', 'distribution_id', 'Analytic Lines'),
        'invoice_ids': fields.one2many('account.invoice', 'analytic_distribution_id', string="Invoices"),
        'invoice_line_ids': fields.one2many('account.invoice.line', 'analytic_distribution_id', string="Invoice Lines"),
        'register_line_ids': fields.one2many('account.bank.statement.line', 'analytic_distribution_id', string="Register Lines"),
        'move_line_ids': fields.one2many('account.move.line', 'analytic_distribution_id', string="Move Lines"),
        'commitment_ids': fields.one2many('account.commitment', 'analytic_distribution_id', string="Commitments voucher"),
        'commitment_line_ids': fields.one2many('account.commitment.line', 'analytic_distribution_id', string="Commitment voucher lines"),
    }

    def copy(self, cr, uid, id, default=None, context=None):
        """
        Copy an analytic distribution without the one2many links
        """
        if default is None:
            default = {}
        default.update({
            'analytic_lines': False,
            'invoice_ids': False,
            'invoice_line_ids': False,
            'register_line_ids': False,
            'move_line_ids': False,
            'commitment_ids': False,
            'commitment_line_ids': False,
        })
        return super(osv.osv, self).copy(cr, uid, id, default, context=context)

    def _get_distribution_state(self, cr, uid, id, parent_id, account_id, context=None):
        """
        Return distribution state
        """
        if context is None:
            context = {}
        # Have an analytic distribution on another account than expense account make no sense. So their analytic distribution is valid
        if account_id:
            account =  self.pool.get('account.account').browse(cr, uid, account_id)
            if account and account.user_type and account.user_type.code != 'expense':
                return 'valid'
        if not id:
            if parent_id:
                return self._get_distribution_state(cr, uid, parent_id, False, account_id, context)
            return 'none'
        distrib = self.browse(cr, uid, id)
        # Search MSF Private Fund element, because it's valid with all accounts
        try:
            fp_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'analytic_distribution', 
            'analytic_account_msf_private_funds')[1]
        except ValueError:
            fp_id = 0
        for fp_line in distrib.funding_pool_lines:
            account = self.pool.get('account.account').browse(cr, uid, account_id)
            if fp_line.destination_id.id not in [x.id for x in account.destination_ids]:
                return 'invalid'
            # If fp_line is MSF Private Fund, all is ok
            if fp_line.analytic_id.id == fp_id:
                continue
            if (account_id, fp_line.destination_id.id) not in [x.account_id and x.destination_id and (x.account_id.id, x.destination_id.id) for x in fp_line.analytic_id.tuple_destination_account_ids]:
                return 'invalid'
            #if fp_line.cost_center_id.id not in [x.id for x in fp_line.analytic_id.cost_center_ids]:
            #    return 'invalid'
        return 'valid'

analytic_distribution1()

class distribution_line(osv.osv):
    _name = "distribution.line"

    _columns = {
        'name': fields.char('Name', size=64),
        "distribution_id": fields.many2one('analytic.distribution', 'Associated Analytic Distribution', ondelete='cascade'),
        "analytic_id": fields.many2one('account.analytic.account', 'Analytical Account'),
        "amount": fields.float('Amount', digits_compute=dp.get_precision('Account')),
        "percentage": fields.float('Percentage', digits=(16,4)),
        "currency_id": fields.many2one('res.currency', 'Currency', required=True),
        "date": fields.date(string="Date"),
        "source_date": fields.date(string="Source Date", help="This date is for source_date for analytic lines"),
    }

    _defaults ={
        'name': 'Distribution Line',
        'date': lambda *a: strftime('%Y-%m-%d'),
        'source_date': lambda *a: strftime('%Y-%m-%d'),
    }

    def create_analytic_lines(self, cr, uid, ids, move_line_id, date, source_date=False, name=False, context=None):
        '''
        Creates an analytic lines from a distribution line and an account.move.line
        '''
        if isinstance(ids, (int, long)):
            ids = [ids]

        ret = {}
        move_line = self.pool.get('account.move.line').browse(cr, uid, move_line_id)
        company_currency_id = self.pool.get('res.users').browse(cr, uid, uid).company_id.currency_id.id

        for line in self.browse(cr, uid, ids):
            amount_cur = (move_line.credit_currency - move_line.debit_currency) * line.percentage / 100
            ctx = {'date': source_date or date}
            amount = self.pool.get('res.currency').compute(cr, uid, move_line.currency_id.id, company_currency_id, amount_cur, round=False, context=ctx)
            vals = {
                'account_id': line.analytic_id.id,
                'amount_currency': amount_cur,
                'amount': amount,
                'currency_id': move_line.currency_id.id,
                'general_account_id': move_line.account_id.id,
                'date': date,
                'source_date': source_date,
                'journal_id': move_line.journal_id and move_line.journal_id.analytic_journal_id and move_line.journal_id.analytic_journal_id.id or False,
                'move_id': move_line.id,
                'name': name or move_line.name,
                'distrib_id': line.distribution_id.id,
                'distrib_line_id': '%s,%s'%(self._name, line.id),
            }
            if self._name == 'funding.pool.distribution.line':
                vals.update({
                    'destination_id': line.destination_id and line.destination_id.id or False,
                    'cost_center_id': line.cost_center_id and line.cost_center_id.id or False,
                })
            ret[line.id] = self.pool.get('account.analytic.line').create(cr, uid, vals)

        return ret

        
distribution_line()

class cost_center_distribution_line(osv.osv):
    _name = "cost.center.distribution.line"
    _inherit = "distribution.line"
    _columns = {
        "destination_id": fields.many2one('account.analytic.account', 'Destination', domain="[('type', '!=', 'view'), ('category', '=', 'DEST')]", required=True),
    }
    
cost_center_distribution_line()

class funding_pool_distribution_line(osv.osv):
    _name = "funding.pool.distribution.line"
    _inherit = "distribution.line"
    _columns = {
        "cost_center_id": fields.many2one('account.analytic.account', 'Cost Center Account', required=True),
        "destination_id": fields.many2one('account.analytic.account', 'Destination', domain="[('type', '!=', 'view'), ('category', '=', 'DEST')]", required=True),
    }
    
funding_pool_distribution_line()

class free_1_distribution_line(osv.osv):
    _name = "free.1.distribution.line"
    _inherit = "distribution.line"
    _columns = {
        "destination_id": fields.many2one('account.analytic.account', 'Destination', domain="[('type', '!=', 'view'), ('category', '=', 'DEST')]", required=False),
    }
    
free_1_distribution_line()

class free_2_distribution_line(osv.osv):
    _name = "free.2.distribution.line"
    _inherit = "distribution.line"
    _columns = {
        "destination_id": fields.many2one('account.analytic.account', 'Destination', domain="[('type', '!=', 'view'), ('category', '=', 'DEST')]", required=False),
    }
    
free_2_distribution_line()

class analytic_distribution(osv.osv):
    _name = 'analytic.distribution'
    _inherit = "analytic.distribution"

    def _get_lines_count(self, cr, uid, ids, name=False, args=False, context=None):
        """
        Get count of each analytic distribution lines type.
        Example: with an analytic distribution with 2 cost center, 3 funding pool and 1 Free 1:
        2 CC; 3 FP; 1 F1; 0 F2; 
        (Number of chars: 20 chars + 4 x some lines number)
        """
        # Some verifications
        if not context:
            context = {}
        if isinstance(ids, (int, long)):
            ids = [ids]
        # Prepare some values
        res = {}
        # Browse given invoices
        for distrib in self.browse(cr, uid, ids, context=context):
            txt = ''
            txt += str(len(distrib.cost_center_lines) or '0') + ' CC; '
            txt += str(len(distrib.funding_pool_lines) or '0') + ' FP; '
            txt += str(len(distrib.free_1_lines) or '0') + ' F1; '
            txt += str(len(distrib.free_2_lines) or '0') + ' F2'
            if not txt:
                txt = ''
            res[distrib.id] = txt
        return res

    _columns = {
        'cost_center_lines': fields.one2many('cost.center.distribution.line', 'distribution_id', 'Cost Center Distribution'),
        'funding_pool_lines': fields.one2many('funding.pool.distribution.line', 'distribution_id', 'Funding Pool Distribution'),
        'free_1_lines': fields.one2many('free.1.distribution.line', 'distribution_id', 'Free 1 Distribution'),
        'free_2_lines': fields.one2many('free.2.distribution.line', 'distribution_id', 'Free 2 Distribution'),
        'name': fields.function(_get_lines_count, method=True, type='char', size=256, string="Name", readonly=True, store=False),
    }

    def update_distribution_line_amount(self, cr, uid, ids, amount=False, context=None):
        """
        Update amount on distribution lines for given distribution (ids)
        """
        # Some verifications
        if not context:
            context = {}
        if isinstance(ids, (int, long)):
            ids = [ids]
        if not amount:
            return False
        # Process distributions
        for distrib_id in ids:
            for dl_name in ['cost.center.distribution.line', 'funding.pool.distribution.line', 'free.1.distribution.line', 'free.2.distribution.line']:
                dl_obj = self.pool.get(dl_name)
                dl_ids = dl_obj.search(cr, uid, [('distribution_id', '=', distrib_id)], context=context)
                for dl in dl_obj.browse(cr, uid, dl_ids, context=context):
                    dl_vals = {
                        'amount': round(dl.percentage * amount) / 100.0,
                    }
                    dl_obj.write(cr, uid, [dl.id], dl_vals, context=context)
        return True

    def update_distribution_line_account(self, cr, uid, line_ids, account_id, context=None):
        """
        Update account on distribution line
        """
        # Some verifications
        if not context:
            context = {}
        if isinstance(line_ids, (int, long)):
            line_ids = [line_ids]
        if not account_id:
            return False
        # Prepare some values
        account = self.pool.get('account.analytic.account').browse(cr, uid, [account_id], context=context)[0]

        if account.category == 'OC':
            vals = {'cost_center_id': account_id}
        else:
            vals = {'analytic_id': account_id}
        return self.pool.get('funding.pool.distribution.line').write(cr, uid, line_ids, vals)

    def create_funding_pool_lines(self, cr, uid, ids, account_id=False, context=None):
        """
        Create funding pool lines regarding cost_center_lines from analytic distribution.
        If funding_pool_lines exists, then nothing appends.
        By default, add funding_pool_lines with MSF Private Fund element (written in an OpenERP demo file).
        For destination axis, get those from account_id default configuration (default_destination_id).
        """
        # Some verifications
        if not context:
            context = {}
        if isinstance(ids, (int, long)):
            ids = [ids]
        # Prepare some values
        res = {}
        # Browse distributions
        for distrib in self.browse(cr, uid, ids, context=context):
            if distrib.funding_pool_lines:
                res[distrib.id] = False
                continue
            # Browse cost center lines
            for line in distrib.cost_center_lines:
                # Search MSF Private Fund
                try:
                    pf_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'analytic_distribution', 
                    'analytic_account_msf_private_funds')[1]
                except ValueError:
                    pf_id = 0
                if pf_id:
                    vals = {
                        'analytic_id': pf_id,
                        'amount': line.amount or 0.0,
                        'percentage': line.percentage or 0.0,
                        'currency_id': line.currency_id and line.currency_id.id or False,
                        'distribution_id': distrib.id or False,
                        'cost_center_id': line.analytic_id and line.analytic_id.id or False,
                        'destination_id': line.destination_id and line.destination_id.id or False,
                    }
                    # Search default destination if no one given
                    if account_id and not vals.get('destination_id'):
                        account = self.pool.get('account.account').browse(cr, uid, account_id)
                        if account and account.user_type and account.user_type.code == 'expense':
                            vals.update({'destination_id': account.default_destination_id and account.default_destination_id.id or False})
                    new_pf_line_id = self.pool.get('funding.pool.distribution.line').create(cr, uid, vals, context=context)
            res[distrib.id] = True
        return res

    def create_analytic_lines(self, cr, uid, ids, name, date, amount, journal_id, currency_id, document_date=False, ref=False, source_date=False, general_account_id=False, \
        move_id=False, invoice_line_id=False, commitment_line_id=False, context=None):
        """
        Create analytic lines from given elements:
         - date
         - name
         - amount
         - journal_id (analytic_journal_id)
         - currency_id
         - ref (optional)
         - source_date (optional)
         - general_account_id (optional)
         - move_id (optional)
         - invoice_line_id (optional)
         - commitment_line_id (optional)
        Return all created ids, otherwise return false (or [])
        """
        # Some verifications
        if not context:
            context = {}
        if isinstance(ids, (int, long)):
            ids = [ids]
        if not name or not date or not amount or not journal_id or not currency_id:
            return False
        if not document_date:
            document_date = date
        # Prepare some values
        res = []
        vals = {
            'name': name,
            'date': source_date or date,
            'document_date': document_date,
            'ref': ref or '',
            'journal_id': journal_id,
            'general_account_id': general_account_id or False,
            'move_id': move_id or False,
            'invoice_line_id': invoice_line_id or False,
            'user_id': uid,
            'currency_id': currency_id,
            'source_date': source_date or False,
            'commitment_line_id': commitment_line_id or False,
        }
        company_currency = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.currency_id.id
        # Browse distribution(s)
        for distrib in self.browse(cr, uid, ids, context=context):
            vals.update({'distribution_id': distrib.id,})
            # create lines
            for distrib_lines in [distrib.funding_pool_lines, distrib.free_1_lines, distrib.free_2_lines]:
                for distrib_line in distrib_lines:
                    context.update({'date': source_date or date}) # for amount computing
                    anal_amount = (distrib_line.percentage * amount) / 100
                    vals.update({
                        'amount': -1 * self.pool.get('res.currency').compute(cr, uid, currency_id, company_currency, 
                            anal_amount, round=False, context=context),
                        'amount_currency': -1 * anal_amount,
                        'account_id': distrib_line.analytic_id.id,
                        'cost_center_id': False,
                        'destination_id': False,
                        'distrib_line_id': '%s,%s'%(distrib_line._name, distrib_line.id),
                    })
                    # Update values if we come from a funding pool
                    if distrib_line._name == 'funding.pool.distribution.line':
                        vals.update({'cost_center_id': distrib_line.cost_center_id and distrib_line.cost_center_id.id or False, 
                            'destination_id': distrib_line.destination_id and distrib_line.destination_id.id or False,})
                    # create analytic line
                    al_id = self.pool.get('account.analytic.line').create(cr, uid, vals, context=context)
                    res.append(al_id)
        return res

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