~julie-w/unifield-wm/UTP-925

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
# -*- 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/>.
#
##############################################################################

from osv import fields, osv
from tools.translate import _
import decimal_precision as dp
import math
import re
import time


#----------------------------------------------------------
# Assets
#----------------------------------------------------------
class product_asset_type(osv.osv):
    _name = "product.asset.type"
    _description = "Specify the type of asset at product level"

    _columns = {
                'name': fields.char('Name', size=64, required=True),
    }
    
product_asset_type()



class product_asset(osv.osv):
    _name = "product.asset"
    _description = "A specific asset of a product"
    
    def _getRelatedProductFields(self, cr, uid, productId):
        '''
        get related fields from product
        '''
        result = {}
        # if no product, return empty dic
        if not productId:
            return result
        
        # fetch the product
        product = self.pool.get('product.product').browse(cr, uid, productId)
        
        result.update({
                       'asset_type_id': product.asset_type_id.id,
                       'prod_int_code': product.default_code,
                       'prod_int_name': product.name,
                       'nomenclature_description': product.nomenclature_description,
                     })
        
        return result
    
    def copy(self, cr, uid, id, default=None, context=None):
        '''
        override copy to update the asset code which comes from a sequence
        '''
        if not default:
            default = {}
        default.update({
            'name': self.pool.get('ir.sequence').get(cr, uid, 'product.asset'),
            'instance_id': False,
        })
        # call to super
        return super(product_asset, self).copy(cr, uid, id, default, context=context)
    
    def copy_data(self, cr, uid, id, default=None, context=None):
        '''
        do not copy asset events
        '''
        if not default:
            default = {}
        default.update({
            'event_ids': [],
            'instance_id': False,
        })
        return super(product_asset, self).copy_data(cr, uid, id, default, context=context)

    def write(self, cr, user, ids, vals, context=None):
        '''
        override write method to force readonly fields to be saved to db
        on data update
        '''
        # fetch the product
        if 'product_id' in vals:
            productId = vals['product_id']
            # add readonly fields to vals
            vals.update(self._getRelatedProductFields(cr, user, productId))
        
        # save the data to db
        return super(product_asset, self).write(cr, user, ids, vals, context)
    
    def create(self, cr, uid, vals, context=None):
        '''
        override create method to force readonly fields to be saved to db
        on data creation
        '''
        # fetch the product
        if 'product_id' in vals:
            productId = vals['product_id']
            # add readonly fields to vals
            vals.update(self._getRelatedProductFields(cr, uid, productId))
        
        # UF-1617: set the current instance into the new object if it has not been sent from the sync   
        if 'instance_id' not in vals or not vals['instance_id']:
            company = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id
            if company and company.instance_id:
                vals['instance_id'] = company.instance_id.id

        # UF-2148: make the xmlid_name from the asset name for building xmlid if it is not given in the vals 
        if 'xmlid_name' not in vals or not vals['xmlid_name']:
            vals['xmlid_name'] = vals['name'] 
            
        exist = self.search(cr, uid, [('xmlid_name', '=', vals['xmlid_name']), ('instance_id', '=', vals['instance_id']), ('product_id', '=', vals['product_id'])], context=context)
        if exist:
            # but if the value exist for xml_name, then just add a suffix to differentiate them, no constraint unique required here
            vals['xmlid_name'] = vals['xmlid_name'] + "_1"
        
        return super(product_asset, self).create(cr, uid, vals, context)
        
    def onChangeProductId(self, cr, uid, ids, productId):
        '''
        on change function when the product is changed
        '''
        result = {}
        
        # no product selected
        if not productId:
            return result
        
        result.update({'value': self._getRelatedProductFields(cr, uid, productId)
                       })
        
        return result
    
    
    def onChangeYear(self, cr, uid, ids, year):
        '''
        year must be 4 digit long and comprised between 1900 and 2100
        '''
        value = {}
        warning = {}
        result = {'value': value, 'warning': warning}
        
        if not year:
            return result
        
        # check that the year specified is a number
        try:
            intValue = int(year)
        except:
            intValue = False
        
        if not intValue:
            warning.update({
                    'title':'The format of year is invalid.',
                    'message':
                        'The format of the year must be 4 digits, e.g. 1983.'
                })
        elif len(year) != 4:
            warning.update({
                    'title':'The length of year is invalid.',
                    'message':
                        'The length of year must be 4 digits long, e.g. 1983.'
                })
        elif (intValue < 1900) or (intValue > 2100):
            warning.update({
                    'title':'The year is invalid.',
                    'message':
                        'The year must be between 1900 and 2100.'
                })
        
        # if a warning has been generated, clear the field
        if 'title' in warning:
            value.update({'year': ''})
        
        return result
        
    _columns = {
                # asset
                'name': fields.char('Asset Code', size=128, required=True),
                'asset_type_id': fields.many2one('product.asset.type', 'Asset Type', readonly=True), # from product
                'description': fields.char('Asset Description', size=128),
                'product_id': fields.many2one('product.product', 'Product', domain="[('subtype','=','asset')]", required=True, ondelete='cascade'),
                # msf codification
                'prod_int_code': fields.char('Product Code', size=128, readonly=True), # from product
                'prod_int_name': fields.char('Product Description', size=128, readonly=True), # from product
                'nomenclature_description': fields.char('Product Nomenclature', size=128, readonly=True), # from product when merged - to be added in _getRelatedProductFields and add dependency to module product_nomenclature
                'hq_ref': fields.char('HQ Reference', size=128),
                'local_ref': fields.char('Local Reference', size=128),
                # asset reference
                'serial_nb': fields.char('Serial Number', size=128, required=True),
                'brand': fields.char('Brand', size=128, required=True),
                'type': fields.char('Type', size=128, required=True),
                'model': fields.char('Model', size=128, required=True),
                'year': fields.char('Year', size=4),
                # remark
                'comment': fields.text('Comment'),
                # traceability
                'project_po': fields.char('Project PO', size=128),
                'orig_mission_code': fields.char('Original Mission Code', size=128, required=True),
                'international_po': fields.char('International PO', size=128, required=True),
                'arrival_date': fields.date('Arrival Date', required=True),
                'receipt_place': fields.char('Receipt Place', size=128, required=True),
                # Invoice
                'invo_num': fields.char('Invoice Number', size=128, required=True),
                'invo_date': fields.date('Invoice Date', required=True),
                'invo_value': fields.float('Value', required=True),
                #'invo_currency': fields.char('Currency', size=128, required=True),
                'invo_currency': fields.many2one('res.currency', 'Currency', required=True),
                'invo_supplier': fields.char('Supplier', size=128),
                'invo_donator_code': fields.char('Donator Code', size=128),
                'invo_certif_depreciation': fields.char('Certificate of Depreciation', size=128),
                # event history
                'event_ids': fields.one2many('product.asset.event', 'asset_id', 'Events'),
                # UF-1617: field only used for sync purpose
                'partner_id': fields.many2one('res.partner', string="Supplier", readonly=True, required=False),
                'instance_id': fields.many2one('msf.instance', 'Instance', readonly=True, required=True),
                'xmlid_name': fields.char('XML Code, hidden field', size=128, required=True),
    }
    
    _defaults = {
                 'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'product.asset'),
                 'arrival_date': lambda *a: time.strftime('%Y-%m-%d'),
                 'receipt_place': 'Country/Project/Activity',
    }
    # UF-2148: use this constraint with 3 attrs: name, prod and instance 
    _sql_constraints = [('asset_name_uniq', 'unique(name, product_id, instance_id)', 'Asset Code must be unique per instance and per product!'),
                        ]
    _order = 'name desc'
    
product_asset()

    
class product_asset_event(osv.osv):
    _name = "product.asset.event"
    _description = "Event for asset follow up"
    
    stateSelection = [('blank', ' '),
                      ('inUse', 'In Use'),
                      ('stock', 'Stock'),
                      ('repair', 'Repair'),
                      ]
    
    eventTypeSelection = [('reception', 'Reception'),
                          ('startUse', 'Start Use'),
                          ('repairing', 'Repairing'),
                          ('endUse', 'End Use'),
                          ('obsolete', 'Obsolete'),
                          ('loaning', 'Loaning'),
                          ('transfer', 'Transfer (internal)'),
                          ('donation', 'Donation (external)'),
                          ('other', 'Other'),
                          ]
    
    def name_get(self, cr, uid, ids, context=None):
        '''
        override because no name field is defined
        '''
        result = []
        for e in self.read(cr, uid, ids, ['asset_id', 'date'], context):
            # e = dict: {'asset_id': (68, u'AF/00045'), 'date': '2011-05-05', 'id': 75}
            result.append((e['id'], '%s - %s'%(e['asset_id'][1], e['date'])))
            
        return result
        
    def _getRelatedAssetFields(self, cr, uid, assetId):
        '''
        get related fields from product
        '''
        result = {}
        # if no asset, return empty dic
        if not assetId:
            return result
        
        # newly selected asset object
        asset = self.pool.get('product.asset').browse(cr, uid, assetId)
        
        result.update({
                       'product_id': asset.product_id.id,
                       'asset_type_id': asset.asset_type_id.id,
                       'serial_nb': asset.serial_nb, 
                       'brand': asset.brand,
                       'model': asset.model,
                    })
        
        return result
    
    def write(self, cr, user, ids, vals, context=None):
        '''
        override write method to force readonly fields to be saved to db
        on data update
        '''
        # fetch the asset
        if 'asset_id' in vals:
            assetId = vals['asset_id']
            # add readonly fields to vals
            vals.update(self._getRelatedAssetFields(cr, user, assetId))
        
        # save the data to db
        return super(product_asset_event, self).write(cr, user, ids, vals, context)
    
    def create(self, cr, user, vals, context=None):
        '''
        override create method to force readonly fields to be saved to db
        on data creation
        '''
        # fetch the asset
        if 'asset_id' in vals:
            assetId = vals['asset_id']
            # add readonly fields to vals
            vals.update(self._getRelatedAssetFields(cr, user, assetId))
        
        # save the data to db
        return super(product_asset_event, self).create(cr, user, vals, context)
    
    def onChangeAssetId(self, cr, uid, ids, assetId):
        
        result = {}
        
        # no asset selected
        if not assetId:
            return result
        
        result.update({'value': self._getRelatedAssetFields(cr, uid, assetId)})
        
        return result
    
    _columns = {
                # event information
                'date': fields.date('Date', required=True),
                'location': fields.char('Location', size=128, required=True),
                'proj_code': fields.char('Project Code', size=128, required=True),
                'event_type': fields.selection(eventTypeSelection, 'Event Type', required=True),
                'state': fields.selection(stateSelection, 'Current Status'),
                # selection
                'asset_id': fields.many2one('product.asset', 'Asset Code', required=True, ondelete='cascade'),
                'product_id': fields.many2one('product.product', 'Product', readonly=True, ondelete='cascade'),
                'serial_nb': fields.char('Serial Number', size=128, readonly=True),
                'brand': fields.char('Brand', size=128, readonly=True), # from asset
                'model': fields.char('Model', size=128, readonly=True), # from asset
                'comment': fields.text('Comment'),
                
                'asset_type_id': fields.many2one('product.asset.type', 'Asset Type', readonly=True), # from asset
    }
    
    _defaults = {
        'date': lambda *a: time.strftime('%Y-%m-%d'),
        'state': 'blank',
    }
    
product_asset_event()

#----------------------------------------------------------
# Products
#----------------------------------------------------------
class product_template(osv.osv):
    
    _inherit = "product.template"
    _description = "Product Template"
    
    PRODUCT_SUBTYPE = [('single','Single Item'),('kit', 'Kit/Module'),('asset','Asset')]
    
    _columns = {
        'subtype': fields.selection(PRODUCT_SUBTYPE, 'Product SubType', required=True, help="Will change the way procurements are processed."),
        'asset_type_id': fields.many2one('product.asset.type', 'Asset Type'),
    }

    _defaults = {
        'subtype': lambda *a: 'single',
    }

product_template()

class product_product(osv.osv):
    
    _inherit = "product.product"
    _description = "Product"
    
    def create(self, cr, uid, vals, context=None):
        if vals.get('type',False) == 'service':
            vals.update({'type': 'service_recep'})
            vals['procure_method'] = 'make_to_order'
        '''
        if a product is not of type product, it is set to single subtype
        '''
        # fetch the product
        if 'type' in vals and vals['type'] != 'product':
            vals.update(subtype='single')
#        if 'type' in vals and vals['type'] == 'consu':
# Remove these two lines to display the warning message of the constraint
#        if vals.get('type') == 'consu':
#            vals.update(procure_method='make_to_order')
        # save the data to db
        return super(product_product, self).create(cr, uid, vals, context=context)
    
    def write(self, cr, uid, ids, vals, context=None):
        '''
        if a product is not of type product, it is set to single subtype
        '''
        # fetch the product
        if 'type' in vals and vals['type'] != 'product':
            vals.update(subtype='single')
            
            
        #UF-2170: remove the standard price value from the list if the value comes from the sync
        if 'standard_price' in vals and context and context.get('sync_update_execution'):
            del vals['standard_price']
        
#        if 'type' in vals and vals['type'] == 'consu':
# Remove these two lines to display the warning message of the constraint
#        if vals.get('type') == 'consu':
#            vals.update(procure_method='make_to_order')
        # save the data to db
        return super(product_product, self).write(cr, uid, ids, vals, context=context)

    def _constaints_product_consu(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        for obj in self.browse(cr, uid, ids, context=context):
            if obj.type == 'consu' and obj.procure_method != 'make_to_order':
                return False
        return True

    
    _columns = {
        'asset_ids': fields.one2many('product.asset', 'product_id', 'Assets')
    }

    _constraints = [
        (_constaints_product_consu, 'If you select "Non-stockable" as product type then you have to select "Make to order" as procurement method', []),
    ]

product_product()

#----------------------------------------------------------
# Stock moves
#----------------------------------------------------------
class stock_move(osv.osv):

    _inherit = "stock.move"
    _description = "Stock Move"
    
    def _do_partial_hook(self, cr, uid, ids, context, *args, **kwargs):
        '''
        hook to update defaults data
        '''
        # variable parameters
        move = kwargs.get('move')
        assert move, 'missing move'
        partial_datas = kwargs.get('partial_datas')
        assert partial_datas, 'missing partial_datas'
        
        # calling super method
        defaults = super(stock_move, self)._do_partial_hook(cr, uid, ids, context, *args, **kwargs)
        assert defaults is not None
        
        assetId = partial_datas.get('move%s'%(move.id), False).get('asset_id')
        if assetId:
            defaults.update({'asset_id': assetId})
        
        return defaults
    
    def _check_asset(self, cr, uid, ids, context=None):
        """ Checks if asset is assigned to stock move or not.
        @return: True or False
        """
        for move in self.browse(cr, uid, ids, context=context):
            if move.state == 'done' and move.location_id.id != move.location_dest_id.id:
                # either the asset comes from a supplier or the asset goes to a customer
                if move.location_id.usage == 'supplier' or move.location_dest_id.usage == 'customer' or (move.picking_id and move.picking_id.type == 'out' and move.picking_id.subtype == 'picking'):
                    if move.product_id.subtype == 'asset':
                        if not move.asset_id and move.product_qty:
                            raise osv.except_osv(_('Error!'),  _('You must assign an asset for the product %s.') % move.product_id.name)
        return True
    
    def create(self, cr, uid, vals, context=None):
        '''
        override for adding subtype on creation if product is specified
        '''
        if context is None:
            context = {}
        if 'product_id' in vals:
            prod = self.pool.get('product.product').browse(cr, uid, vals['product_id'], context=context)
            vals.update({'subtype': prod.product_tmpl_id.subtype})
            
        result = super(stock_move, self).create(cr, uid, vals, context=context)
        
        return result

    def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False,
                            loc_dest_id=False, address_id=False,parent_type=False,purchase_line_id=False,out=False):
        '''
        override to clear asset_id
        '''
        result = super(stock_move, self).onchange_product_id(cr, uid, ids, prod_id, loc_id,
                            loc_dest_id, address_id, parent_type, purchase_line_id,out)
        
        if 'value' not in result:
            result['value'] = {}
        
        if prod_id:
            prod = self.pool.get('product.product').browse(cr, uid, prod_id)
            result['value'].update({'subtype': prod.product_tmpl_id.subtype})

            if parent_type and parent_type == 'internal' and loc_dest_id:
                # Test the compatibility of the product with the location
                result, test = self.pool.get('product.product')._on_change_restriction_error(cr, uid, prod_id, field_name='product_id', values=result, vals={'location_id': loc_dest_id})
                if test:
                    return result
            
        result['value'].update({'asset_id': False})
        
        return result
        
    _columns = {
        'asset_id': fields.many2one('product.asset', 'Asset'),
        'subtype': fields.char(string='Product Subtype', size=128),
    }
    
    _constraints = [
        (_check_asset,
            'You must assign an asset for this product.',
            ['asset_id']),]
    
stock_move()


class stock_picking(osv.osv):
    '''
    
    '''
    _inherit = 'stock.picking'
    _description = 'Stock Picking with hook'

    def _do_partial_hook(self, cr, uid, ids, context, *args, **kwargs):
        '''
        hook to update defaults data
        '''
        # variable parameters
        move = kwargs.get('move')
        assert move, 'missing move'
        partial_datas = kwargs.get('partial_datas')
        assert partial_datas, 'missing partial_datas'
        
        # calling super method
        defaults = super(stock_picking, self)._do_partial_hook(cr, uid, ids, context, *args, **kwargs)
        assetId = partial_datas.get('move%s'%(move.id), {}).get('asset_id')
        if assetId:
            defaults.update({'asset_id': assetId})
        
        return defaults

stock_picking()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: