~unifield-team/unifield-wm/uftp-388

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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2011 TeMPO Consulting, MSF 
#
#    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 osv, fields

import time

import inspect

from tools.translate import _
from dateutil.relativedelta import relativedelta
from datetime import datetime
from decimal import Decimal, ROUND_UP

import netsvc

class lang(osv.osv):
    '''
    define getter for date / time / datetime formats
    '''
    _inherit = 'res.lang'
    
    def _get_format(self, cr, uid, type, context=None):
        '''
        generic function
        '''
        if context is None:
            context = {}
        type = type + '_format'
        assert type in self._columns, 'Specified format field does not exist'
        user_obj = self.pool.get('res.users')
        # get user context lang
        user_lang = user_obj.read(cr, uid, uid, ['context_lang'], context=context)['context_lang']
        # get coresponding id
        lang_id = self.search(cr, uid, [('code','=',user_lang)])
        # return format value or from default function if not exists
        format = lang_id and self.read(cr, uid, lang_id[0], [type], context=context)[type] or getattr(self, '_get_default_%s'%type)(cr, uid, context=context)
        return format
    
    def _get_db_format(self, cr, uid, type, context=None):
        '''
        generic function - for now constant values
        '''
        if context is None:
            context = {}
        if type == 'date':
            return '%Y-%m-%d'
        if type == 'time':
            return '%H:%M:%S'
        # default value
        return '%Y-%m-%d'
lang()


class date_tools(osv.osv):
    '''
    date related tools for msf project
    '''
    _name = 'date.tools'
    
    def get_date_format(self, cr, uid, context=None):
        '''
        get the date format for the uid specified user
        
        from msf_order_date module
        '''
        lang_obj = self.pool.get('res.lang')
        return lang_obj._get_format(cr, uid, 'date', context=context)
    
    def get_db_date_format(self, cr, uid, context=None):
        '''
        return constant value
        '''
        lang_obj = self.pool.get('res.lang')
        return lang_obj._get_db_format(cr, uid, 'date', context=context)
    
    def get_time_format(self, cr, uid, context=None):
        '''
        get the time format for the uid specified user
        
        from msf_order_date module
        '''
        lang_obj = self.pool.get('res.lang')
        return lang_obj._get_format(cr, uid, 'time', context=context)
    
    def get_db_time_format(self, cr, uid, context=None):
        '''
        return constant value
        '''
        lang_obj = self.pool.get('res.lang')
        return lang_obj._get_db_format(cr, uid, 'time', context=context)
    
    def get_datetime_format(self, cr, uid, context=None):
        '''
        get the datetime format for the uid specified user
        '''
        return self.get_date_format(cr, uid, context=context) + ' ' + self.get_time_format(cr, uid, context=context)
    
    def get_db_datetime_format(self, cr, uid, context=None):
        '''
        return constant value
        '''
        return self.get_db_date_format(cr, uid, context=context) + ' ' + self.get_db_time_format(cr, uid, context=context)
    
    def get_date_formatted(self, cr, uid, d_type='date', datetime=None, context=None):
        '''
        Return the datetime in the format of the user
        @param d_type: 'date' or 'datetime' : determines which is the out format
        @param datetime: date to format 
        '''
        assert d_type in ('date', 'datetime'), 'Give only \'date\' or \'datetime\' as type parameter'

        if not datetime:
            datetime = time.strftime('%Y-%m-%d')
        
        if d_type == 'date':
            d_format = self.get_date_format(cr, uid)
            date = time.strptime(datetime, '%Y-%m-%d')
            return time.strftime(d_format, date)
        elif d_type == 'datetime':
            d_format = self.get_datetime_format(cr, uid)
            date = time.strptime(datetime, '%Y-%m-%d %H:%M:%S')
            return time.strftime(d_format, date)
    
date_tools()


class fields_tools(osv.osv):
    '''
    date related tools for msf project
    '''
    _name = 'fields.tools'
    
    def get_field_from_company(self, cr, uid, object=False, field=False, context=None):
        '''
        return the value for field from company for object 
        '''
        # field is required for value
        if not field:
            return False
        # object
        company_obj = self.pool.get('res.company')
        # corresponding company
        company_id = company_obj._company_default_get(cr, uid, object, context=context)
        # get the value
        res = company_obj.read(cr, uid, [company_id], [field], context=context)[0][field]
        return res
    
    def get_selection_name(self, cr, uid, object=False, field=False, key=False, context=None):
        '''
        return the name from the key of selection field
        '''
        if not object or not field or not key:
            return False
        # get the selection values list
        if isinstance(object, str):
            object = self.pool.get(object)
        list = object._columns[field].selection
        name = [x[1] for x in list if x[0] == key][0]
        return name
    
    def get_ids_from_browse_list(self, cr, uid, browse_list=False, context=None):
        '''
        return the list of ids corresponding to browse list in parameter
        '''
        if not browse_list:
            return []
        
        result = [x.id for x in browse_list]
        return result
    
fields_tools()
    

class data_tools(osv.osv):
    '''
    data related tools for msf project
    '''
    _name = 'data.tools'
    
    def load_common_data(self, cr, uid, ids, context=None):
        '''
        load common data into context
        '''
        if context is None:
            context = {}
        context.setdefault('common', {})
        # objects
        date_tools = self.pool.get('date.tools')
        obj_data = self.pool.get('ir.model.data')
        comp_obj = self.pool.get('res.company')
        # date format
        db_date_format = date_tools.get_db_date_format(cr, uid, context=context)
        context['common']['db_date_format'] = db_date_format
        date_format = date_tools.get_date_format(cr, uid, context=context)
        context['common']['date_format'] = date_format
        # date is today
        date = time.strftime(db_date_format)
        context['common']['date'] = date
        # default company id
        company_id = comp_obj._company_default_get(cr, uid, 'stock.picking', context=context)
        context['common']['company_id'] = company_id
        
        # stock location
        stock_id = obj_data.get_object_reference(cr, uid, 'stock', 'stock_location_stock')[1]
        context['common']['stock_id'] = stock_id
        # kitting location
        kitting_id = obj_data.get_object_reference(cr, uid, 'stock', 'location_production')[1]
        context['common']['kitting_id'] = kitting_id
        # input location
        input_id = obj_data.get_object_reference(cr, uid, 'msf_cross_docking', 'stock_location_input')[1]
        context['common']['input_id'] = input_id
        # quarantine analyze
        quarantine_anal = obj_data.get_object_reference(cr, uid, 'stock_override', 'stock_location_quarantine_analyze')[1]
        context['common']['quarantine_anal'] = quarantine_anal
        # quarantine before scrap
        quarantine_scrap = obj_data.get_object_reference(cr, uid, 'stock_override', 'stock_location_quarantine_scrap')[1]
        context['common']['quarantine_scrap'] = quarantine_scrap
        # log
        log = obj_data.get_object_reference(cr, uid, 'stock_override', 'stock_location_logistic')[1]
        context['common']['log'] = log
        # cross docking
        cross_docking = obj_data.get_object_reference(cr, uid, 'msf_cross_docking', 'stock_location_cross_docking')[1]
        context['common']['cross_docking'] = cross_docking
        
        # kit reason type
        reason_type_id = obj_data.get_object_reference(cr, uid, 'reason_types_moves', 'reason_type_kit')[1]
        context['common']['reason_type_id'] = reason_type_id
        # reason type goods return
        rt_goods_return = obj_data.get_object_reference(cr, uid, 'reason_types_moves', 'reason_type_goods_return')[1]
        context['common']['rt_goods_return'] = rt_goods_return
        # reason type goods replacement
        rt_goods_replacement = obj_data.get_object_reference(cr, uid, 'reason_types_moves', 'reason_type_goods_replacement')[1]
        context['common']['rt_goods_replacement'] = rt_goods_replacement
        # reason type internal supply
        rt_internal_supply = obj_data.get_object_reference(cr, uid, 'reason_types_moves', 'reason_type_internal_supply')[1]
        context['common']['rt_internal_supply'] = rt_internal_supply
        
        return True

data_tools()


class sequence_tools(osv.osv):
    '''
    sequence tools
    '''
    _name = 'sequence.tools'
    
    def reorder_sequence_number(self, cr, uid, base_object, base_seq_field, dest_object, foreign_field, foreign_ids, seq_field, context=None):
        '''
        receive a browse list corresponding to one2many lines
        recompute numbering corresponding to specified field
        compute next number of sequence
        
        we must make sure we reorder in conservative way according to original order
        
        *not used presently*
        '''
        # Some verifications
        if context is None:
            context = {}
        if isinstance(foreign_ids, (int, long)):
            foreign_ids = [foreign_ids]
            
        # objects
        base_obj = self.pool.get(base_object)
        dest_obj = self.pool.get(dest_object)
        seq_obj = self.pool.get('ir.sequence')
        
        for foreign_id in foreign_ids:
            # will be ordered by default according to db id, it's what we want according to user sequence
            item_ids = dest_obj.search(cr, uid, [(foreign_field, '=', foreign_id)], context=context)
            if item_ids:
                # read line number and id from items
                item_data = dest_obj.read(cr, uid, item_ids, [seq_field], context=context)
                # check the line number: data are ordered according to db id, so line number must be equal to index+1
                for i in range(len(item_data)):
                    if item_data[i][seq_field] != i+1:
                        dest_obj.write(cr, uid, [item_data[i]['id']], {seq_field: i+1}, context=context)
                # reset sequence to length + 1 all time, checking if needed would take much time
                # get the sequence id
                seq_id = base_obj.read(cr, uid, foreign_id, [base_seq_field], context=context)[base_seq_field][0]
                # we reset the sequence to length+1
                self.reset_next_number(cr, uid, [seq_id], value=len(item_ids)+1, context=context)
        
        return True
    
    def reorder_sequence_number_from_unlink(self, cr, uid, ids, base_object, base_seq_field, dest_object, foreign_field, seq_field, context=None):
        '''
        receive a browse list corresponding to one2many lines
        recompute numbering corresponding to specified field
        compute next number of sequence
        
        for unlink, only items with id > min(deleted id) are resequenced + reset the sequence value
        
        we must make sure we reorder in conservative way according to original order
        
        this method is called from methods of **destination object**
        '''
        # Some verifications
        if context is None:
            context = {}
        # if no ids as parameter return Tru
        if not ids:
            return True
            
        # objects
        base_obj = self.pool.get(base_object)
        dest_obj = self.pool.get(dest_object)
        seq_obj = self.pool.get('ir.sequence')
        
        # find the corresponding base ids
        base_ids = [x[foreign_field][0] for x in dest_obj.read(cr, uid, ids, [foreign_field], context=context) if x[foreign_field]]
        # simulate unique sql
        foreign_ids = set(base_ids)
        
        for foreign_id in foreign_ids:
            # will be ordered by default according to db id, it's what we want according to user sequence
            # reorder only ids bigger than min deleted + do not select deleted ones
            item_ids = dest_obj.search(cr, uid, [('id', '>', min(ids)), (foreign_field, '=', foreign_id), ('id', 'not in', ids)], context=context)
            # start numbering sequence
            start_num = 0
            # if deleted object is not the first one, we find the numbering value of previous one
            before_ids = dest_obj.search(cr, uid, [('id', '<', min(ids)), (foreign_field, '=', foreign_id)], context=context)
            if before_ids:
                # we read the numbering value of previous value (biggest id)
                start_num = dest_obj.read(cr, uid, max(before_ids), [seq_field], context=context)[seq_field]
            if item_ids:
                # read line number and id from items
                item_data = dest_obj.read(cr, uid, item_ids, [seq_field], context=context)
                # check the line number: data are ordered according to db id, so line number must be equal to index+1
                for i in range(len(item_data)):
                    # numbering value
                    start_num = start_num+1
                    if item_data[i][seq_field] != start_num:
                        cr.execute("update "+dest_obj._table+" set "+seq_field+"=%s where id=%s", (start_num, item_data[i]['id']))
                        #dest_obj.write(cr, uid, [item_data[i]['id']], {seq_field: start_num}, context=context)
            
            # reset sequence to start_num + 1 all time, checking if needed would take much time
            # get the sequence id
            seq_id = base_obj.read(cr, uid, foreign_id, [base_seq_field], context=context)[base_seq_field][0]
            # we reset the sequence to length+1, whether or not items
            self.reset_next_number(cr, uid, [seq_id], value=start_num+1, context=context)
        
        return True
    
    def reset_next_number(self, cr, uid, seq_ids, value=1, context=None):
        '''
        reset the next number of the sequence to value, default value 1
        '''
        # Some verifications
        if context is None:
            context = {}
        if isinstance(seq_ids, (int, long)):
            seq_ids = [seq_ids]
            
        # objects
        seq_obj = self.pool.get('ir.sequence')
        seq_obj.write(cr, uid, seq_ids, {'number_next': value}, context=context)
        return True
    
    def create_sequence(self, cr, uid, vals, name, code, prefix='', padding=0, context=None):
        '''
        create a new sequence
        '''
        seq_pool = self.pool.get('ir.sequence')
        seq_typ_pool = self.pool.get('ir.sequence.type')
        
        assert name, 'create sequence: missing name'
        assert code, 'create sequence: missing code'

        types = {'name': name,
                 'code': code
                 }
        seq_typ_pool.create(cr, uid, types)

        seq = {'name': name,
               'code': code,
               'prefix': prefix,
               'padding': padding,
               }
        return seq_pool.create(cr, uid, seq)
    
sequence_tools()


class picking_tools(osv.osv):
    '''
    picking related tools
    '''
    _name = 'picking.tools'
    
    def confirm(self, cr, uid, ids, context=None):
        '''
        confirm the picking
        '''
        # Some verifications
        if context is None:
            context = {}
        if isinstance(ids, (int, long)):
            ids = [ids]
            
        # objects
        pick_obj = self.pool.get('stock.picking')
        pick_obj.draft_force_assign(cr, uid, ids, context)
        return True
        
    def check_assign(self, cr, uid, ids, context=None):
        '''
        check assign the picking
        '''
        # Some verifications
        if context is None:
            context = {}
        if isinstance(ids, (int, long)):
            ids = [ids]
            
        # objects
        pick_obj = self.pool.get('stock.picking')
        pick_obj.action_assign(cr, uid, ids, context)
        return True
    
    def force_assign(self, cr, uid, ids, context=None):
        '''
        force assign the picking
        '''
        # Some verifications
        if context is None:
            context = {}
        if isinstance(ids, (int, long)):
            ids = [ids]
            
        # objects
        pick_obj = self.pool.get('stock.picking')
        pick_obj.force_assign(cr, uid, ids, context)
        return True
        
    def validate(self, cr, uid, ids, context=None):
        '''
        validate the picking
        '''
        # Some verifications
        if context is None:
            context = {}
        if isinstance(ids, (int, long)):
            ids = [ids]
            
        # objects
        pick_obj = self.pool.get('stock.picking')
        wf_service = netsvc.LocalService("workflow")
        # trigger standard workflow for validated picking ticket
        for id in ids:
            pick_obj.action_move(cr, uid, [id])
            wf_service.trg_validate(uid, 'stock.picking', id, 'button_done', cr)
        return True
        
    def all(self, cr, uid, ids, context=None):
        '''
        confirm - check - validate
        '''
        self.confirm(cr, uid, ids, context=context)
        self.check_assign(cr, uid, ids, context=context)
        self.validate(cr, uid, ids, context=context)
        return True
    
picking_tools()
    

class ir_translation(osv.osv):
    _name = 'ir.translation'
    _inherit = 'ir.translation'

    def tr_view(self, cr, name, context):
        if not context or not context.get('lang'):
            return name
        tr = self._get_source(cr, 1, False, 'view', context['lang'], name, True)
        if not tr:
            # sometimes de view name is empty and so the action name is used as view name
            tr2 = self._get_source(cr, 1, 'ir.actions.act_window,name', 'model', context['lang'], name)
            if tr2:
                return tr2
            return name
        return tr


ir_translation()


class uom_tools(osv.osv_memory):
    """
    This osv_memory class helps to check certain consistency related to the UOM.
    """
    _name = 'uom.tools'

    def check_uom(self, cr, uid, product_id, uom_id, context=None):
        """
        Check the consistency between the category of the UOM of a product and the category of a UOM.
        Return a boolean value (if false, it will raise an error).
        :param cr: database cursor
        :param product_id: takes the id of a product
        :param product_id: takes the id of a uom
        Note that this method is not consistent with the onchange method that returns a dictionary.
        """
        if context is None:
            context = {}
        if product_id and uom_id:
            if isinstance(product_id, (int, long)):
                product_id = [product_id]
            if isinstance(uom_id, (int, long)):
                uom_id = [uom_id]
            cr.execute(
                """
                SELECT COUNT(*)
                FROM product_uom AS uom,
                    product_template AS pt,
                    product_product AS pp,
                    product_uom AS uom2
                WHERE uom.id = pt.uom_id
                AND pt.id = pp.product_tmpl_id
                AND pp.id = %s
                AND uom2.category_id = uom.category_id
                AND uom2.id = %s""",
                (product_id[0], uom_id[0]))
            count = cr.fetchall()[0][0]
            return count > 0
        return True

uom_tools()


class product_uom(osv.osv):
    _inherit = 'product.uom'

    def _compute_round_up_qty(self, cr, uid, uom_id, qty, context=None):
        '''
        Round up the qty according to the UoM
        '''
        uom = self.browse(cr, uid, uom_id, context=context)
        rounding_value = Decimal(str(uom.rounding).rstrip('0'))

        return float(Decimal(str(qty)).quantize(rounding_value, rounding=ROUND_UP))

    def _change_round_up_qty(self, cr, uid, uom_id, qty, fields=[], result=None, context=None):
        '''
        Returns the error message and the rounded value
        '''
        if not result:
            result = {'value': {}, 'warning': {}}

        if isinstance(fields, str):
            fields = [fields]

        message = {'title': _('Bad rounding'),
                   'message': _('The quantity entered is not valid according to the rounding value of the UoM. The product quantity has been rounded to the highest good value.')}

        if uom_id and qty:
            new_qty = self._compute_round_up_qty(cr, uid, uom_id, qty, context=context)
            if qty != new_qty:
                for f in fields:
                    result.setdefault('value', {}).update({f: new_qty})
                result.setdefault('warning', {}).update(message)

        return result

product_uom()