~technofluid-team/openobject-addons/technofluid

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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
'''
Created on 11 juil. 2012

@author: cth
'''
from osv import osv, fields
import re
import time
from tools.translate import _
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
import netsvc
from operator import itemgetter
import calendar
import json
import math

def add_months(sourcedate,months):
    month = sourcedate.month - 1 + months
    year = sourcedate.year + month / 12
    month = month % 12 + 1
    day = min(sourcedate.day,calendar.monthrange(year,month)[1])
    return datetime(year=year,month=month,day=day)


class maintenance_element_model(osv.osv):
    _name = "maintenance.element.model"
    
    # If model has changed, update linked draft interventions
    def update_interventions(self,cr,uid,ids,context=None):
        res = True
        
        for model in self.browse(cr,uid,ids,context=context):
            # Add
            tmp=[]
            for intervention_model in model.intervention_model_ids:
                tmp.append(intervention_model.id)
                
            # Looking for interventions with products related to model (maybe several)
            generation_detail_ids = self.pool.get('maintenance.generation.detail').search(cr,uid,[('intervention_model_id','in',tmp)],context=context)
            
            tmp=[]
            for detail in self.pool.get('maintenance.generation.detail').browse(cr,uid,generation_detail_ids,context=context):
                tmp.append(detail.intervention_id.id)
            
            intervention_ids = self.pool.get('maintenance.intervention').search(cr,uid,[('state','=','draft'),('id','in',tmp)])
            
            for intervention in self.pool.get('maintenance.intervention').browse(cr,uid,intervention_ids,context=context):
                
                generation_detail_ids = self.pool.get('maintenance.generation.detail').search(cr,uid,[('intervention_id','=',intervention.id)],context=context)
                
                uniq_model_ids = list(set([m.intervention_model_id.id for m in self.pool.get('maintenance.generation.detail').browse(cr,uid,generation_detail_ids,context=context)]))
            
                # For a particular intervention, we take all maintenance elements concerned by change
                for intervention_model in self.pool.get('maintenance.intervention.model').browse(cr,uid,uniq_model_ids,context=context):
                    
                    # Delete intervention product and build the intervention products list
                    tmp=[]
                    tmp2=[]
                    product_model_ids = [product_mod.id for product_mod in intervention_model.intervention_product_model_ids]
                    for intervention_product in intervention.intervention_products:
                        if intervention_product.intervention_product_model.id not in product_model_ids and intervention_product.intervention_model.id == intervention_model.id:
                            self.pool.get('maintenance.intervention.product').unlink(cr,uid,[intervention_product.id],context=context)
                        else:
                            tmp.append(intervention_product.product_id.id)
                            tmp2.append(intervention_product.id)
                    
                    for product_model in intervention_model.intervention_product_model_ids:
                        
                        # Product Modification
                        self._update_products(cr, uid, tmp2, product_model, context=context)
                        
                        
                        # ADD - A product (from model) is not in the current intervention product list
                        if (product_model.product_id.id not in tmp):
                            value = {
                                     'intervention_product_model':product_model.id,
                                     'intervention_model':intervention.intervention_model_id.id,
                                     'quantity':product_model.quantity,
                                     'product_id':product_model.product_id.id,
                                     'intervention_id':intervention.id,
                                     'description':product_model.product_id.name_get()[0][1], 
                                     'maintenance_element_id':detail.maintenance_element_id.id, 
                                     'sale_price':product_model.product_id.list_price,
                                     'cost_price':product_model.product_id.cost_price,
                                     'discount':False,
                                     'delay':product_model.product_id.sale_delay,
                                     'type':False,
                                     }
                            self.pool.get('maintenance.intervention.product').create(cr,uid,value,context=context)
     
        return res
    
    #Update products which have different quantities
    def _update_products(self,cr,uid,ids,model,context=None):
        ids = self.pool.get('maintenance.intervention.product').search(cr, uid, [('id','in',ids)], context=context) #bug fix : some time ids of deleted products appears in "ids"
        for product in self.pool.get('maintenance.intervention.product').browse(cr,uid,ids,context=context):
            if (product.intervention_product_model and product.intervention_product_model.id == model.id and (product.quantity != model.quantity)):
                product_value={
                               'quantity':model.quantity
                               }
                self.pool.get('maintenance.intervention.product').write(cr,uid,[product.id],product_value,context=context)
    
    def get_max_period_timeofuse(self, cr, uid, ids, context=None):
        intervention_model_pool = self.pool.get('maintenance.intervention.model')
        result = {}
        for model_id in ids:
            element_ids = intervention_model_pool.search(cr, uid, [('element_model_id','=',model_id)], order="period_timeofuse desc", limit=1, context=context)
            if element_ids:
                result[model_id] = intervention_model_pool.browse(cr, uid, element_ids[0], context).period_timeofuse
        return result
    
    def get_max_period_months(self, cr, uid, ids, context=None):
        intervention_model_pool = self.pool.get('maintenance.intervention.model')
        result = {}
        for model_id in ids:
            element_ids = intervention_model_pool.search(cr, uid, [('element_model_id','=',model_id)], order="period_months desc", limit=1, context=context)
            if element_ids:
                result[model_id] = intervention_model_pool.browse(cr, uid, element_ids[0], context).period_months
        return result
    
    def search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False):
        for arg in args:
            if arg[0] == 'product_ids':
                cr.execute("select distinct maintenance_element_model.id from maintenance_element_model left join maintenance_element_model_product_rel left join product_product on product_product.id = maintenance_element_model_product_rel.product_id on maintenance_element_model_product_rel.model_id = maintenance_element_model.id where product_product.default_code ilike '%%%s%%' or name ilike '%%%s%%'"%(arg[2],arg[2]))
                model_ids = [t[0] for t in cr.fetchall()]
                args.append(('id','in',model_ids))
                args.remove(arg)
            
        return super(maintenance_element_model, self).search(cr, user, args, offset=offset, limit=limit, order=order, context=context, count=count)
    
    _columns = {
        'name':fields.char(string="Name", size=255),
        'description':fields.text("Description"),
        'product_ids':fields.many2many('product.product', 'maintenance_element_model_product_rel', 'model_id', 'product_id', string="Concerned products"),
        'intervention_model_ids':fields.one2many('maintenance.intervention.model', 'element_model_id', string="Intervention plan"),
        'serial_number_from':fields.char(size=255, string="From serial number"),
        'serial_number_to':fields.char(size=255, string="To serial number"),
    }
maintenance_element_model()

class maintenance_intervention_model(osv.osv):
    _name = 'maintenance.intervention.model'
    
    _columns = {
        'element_model_id':fields.many2one('maintenance.element.model', "Element model"),                 
        'name':fields.char(string="Name", size=255),
        'intervention_type_id':fields.many2one("maintenance.intervention.type", "Type of intervention", required=True), 
        'description':fields.text("Description"),
        'hours_cycle':fields.integer("Number of operating hours between two intervention"), 
        'hours_first':fields.integer("Number of operating hours before first intervention"),
        'months_cycle':fields.integer("Number of months between two interventions"),
        'months_first':fields.integer("Number of months before first intervention"),
        'duration':fields.float("Duration of intervention"),
        'intervention_product_model_ids':fields.one2many("maintenance.intervention.product.model", "intervention_model_id", string="Products"),
        'no_generation_of_intervention':fields.boolean('Non-contracted')
    }
    
    
maintenance_intervention_model()

class maintenance_intervention_product_model(osv.osv):
    _name="maintenance.intervention.product.model"
    
    _rec_name = 'product_id' 
    
    _columns = {
        'intervention_model_id':fields.many2one("maintenance.intervention.model", string="Intervention model"), 
        'product_id':fields.many2one("product.product", string="Product"),
        'quantity':fields.float('Quantity'),
    }
    _defaults = {  
        'quantity': 1,  
    }
maintenance_intervention_product_model()

class product_product(osv.osv):
    _inherit = 'product.product' 

    _columns = {
        'maintenance_element_model_ids':fields.many2many('maintenance.element.model', 'maintenance_element_model_product_rel', 'product_id', 'model_id', string="Concerned intervention models"), 
    }

product_product()

class maintenance_element(osv.osv):
    _inherit = 'maintenance.element'
    
    def on_change_timeofuse_history(self, cr, uid, ids, timeofuse_history,intervention_generation_first_date,expected_time_of_use):
        time_of_use_dict = [t[2] for t in timeofuse_history if len(t)>1 and t[0] != 2]
        if intervention_generation_first_date:
            start_date = datetime.strptime(intervention_generation_first_date,"%Y-%m-%d")
        else:
            start_date = datetime.now()
        start_hour = self.compute_start_hour(time_of_use_dict,start_date,expected_time_of_use)
        return {'value':{'intervention_generation_start_hours':start_hour}}
    
    # Function to calculate (and estimate) the maintenance element counter at
    # the begining of the project intervention generation date
    def compute_start_hour(self, time_of_use_dict, start_date,expected_time_of_use):
        time_reference=None
        if (time_of_use_dict[0]):
            time_reference = time_of_use_dict[0]
            
        if (not time_reference):
            return 0
        
        delta = (start_date - datetime.strptime(time_reference['date'],"%Y-%m-%d %H:%M:%S")).days
        
        # If generation start date is before last counter we take just the time of use as reference
        final_hour = time_reference['time_of_use']
        hours_diff = 0.
        # If generation start date is before last counter
        if (delta and delta >= 0):
            hours_diff = (expected_time_of_use / 365.) * delta
            final_hour = time_reference['time_of_use'] + hours_diff
            
        return final_hour
        
    
    
    def calculate_start_hour(self,cr,uid,ids, name, args, context=None):
        res = {}
        
        elements = self.pool.get('maintenance.element').browse(cr,uid,ids,context=None)
        for element in elements:
            res[element.id] = 0
            project = self._find_project(cr, uid, ids, context=context)
            if project and project.used_intervention_generation_start_date:
                expected_time_of_use = element.expected_time_of_use
                tmp=[]
                for time_of_use_history in element.timeofuse_history:
                    tmp.append({'date':time_of_use_history.date,'time_of_use':time_of_use_history.time_of_use})
                    
                if (len(tmp)==0):
                    res[element.id] = 0
                    continue
                tmp.sort(key=lambda x:x['date'],reverse=True)
                times_of_use = tmp
                
                final_hour = self.compute_start_hour(times_of_use, datetime.strptime(project.used_intervention_generation_start_date,"%Y-%m-%d"),expected_time_of_use)
                
                res[element.id] = final_hour
        return res 
    
    _columns = {
        'intervention_generation_start_hours':fields.function(calculate_start_hour,string='Counter at beginning of generation', help="When we do generation of interventions from project, we consider this value as beginning counter. This value is compute depending on last meter reading and project begin date.", method=True, ), 
        'intervention_generation_first_date':fields.date('Date of first intervention (auto. generation)', help="When we do generation of interventions from project, we consider this value as first intervention date. This date is not used if start hours are filled."),
        'element_model_id':fields.many2one('maintenance.element.model', 'Element model'),
        'main_element':fields.boolean("Main element", help="If other elements of the project do not have expected time of use, we use expected time of use of main element"),
        'current_project_start_date':fields.related('current_project_id','used_intervention_generation_start_date', type='date', string='Intervention beginning', readonly=True)
    }
    
    
    # As a maintenance element cannot be linked to one and only
    # one project, we estimate the project on which calculate
    def _find_project(self,cr,uid,ids,context=None):
        res = False
        
        for element in self.pool.get('maintenance.element').browse(cr,uid,ids,context=context):
            tmp=[]
            project = False
            
            for project in element.maintenance_projects:
                tmp.append(project.id)
            
            # Take the last created project first
            tmp.sort(key=lambda x:x,reverse=True)
            found=False
            for project_id in [project_id for project_id in tmp if not found]:
                # We take the first active project
                for project in self.pool.get('maintenance.project').browse(cr,uid,[project_id],context=context):
                    if project.state != 'disabled':
                        found=True
                        break
            
            if project and found:
                res = project
        
        return res
    
    def get_interventions(self, cr, uid, ids, project, context=None):
        
        date_from = project.used_intervention_generation_start_date
        date_to = project.date_end
        
        result = []
        begin = datetime.strptime(date_from, '%Y-%m-%d')
        
        if date_to:
            end = datetime.strptime(date_to, '%Y-%m-%d')
        else:
            end = begin+timedelta(days=365*2)
        
        diff = end-begin
        days = diff.days
        installation = project.installation_id
        
        
        merge_table = {}
        for element in self.browse(cr, uid, ids, context):
            
            #find expected time of use depending on main_element flag
            main_elt_time_of_use = [elt.expected_time_of_use for elt in element.installation_id.elements if elt.main_element]
            if main_elt_time_of_use:
                main_elt_time_of_use = main_elt_time_of_use[0]
            else:
                main_elt_time_of_use = 0
            
            if element.element_model_id:
                if element.expected_time_of_use:
                    expected_time_of_use = element.expected_time_of_use
                else:
                    expected_time_of_use = main_elt_time_of_use
                
                for intervention_model in element.element_model_id.intervention_model_ids:
                    if intervention_model.no_generation_of_intervention:
                        continue
                    
                    if not intervention_model.months_first and not  intervention_model.hours_first:
                        raise osv.except_osv(_('UserError'), _('You have to fill at least months or hours for first intervention for intervention %s of model %s.')%(intervention_model.name, element.element_model_id.name)) 
                
                    if not intervention_model.months_cycle and not  intervention_model.hours_cycle:
                        raise osv.except_osv(_('UserError'), _('You have to fill at least cycle months or cycle hours for intervention %s of model %s.')%(intervention_model.name, element.element_model_id.name))
                    
                    if not expected_time_of_use and (intervention_model.hours_first != 0 or intervention_model.hours_cycle != 0):
                        raise osv.except_osv(_('UserError'), _('You have to define expected annual time of use of element %s.')%(element.name))
                    
                    #find if element operate enough to compute days from operating time
                    #for first intervention
                    hours_until_max_time_first = (expected_time_of_use*intervention_model.months_first)/12
                    if intervention_model.hours_first == 0 or (intervention_model.months_first != 0 and hours_until_max_time_first < intervention_model.hours_first):
                        days_first = intervention_model.months_first*(365./12.)
                        hours_first = expected_time_of_use*intervention_model.months_first/12.
                    else:
                        days_first =  ((intervention_model.hours_first*12.)/expected_time_of_use)*(365./12)
                        hours_first = intervention_model.hours_first
                    
                    #for next interventions
                    hours_for_max_time = (expected_time_of_use*intervention_model.months_cycle)/12.
                    if intervention_model.hours_cycle == 0 or (intervention_model.months_cycle != 0 and hours_for_max_time < intervention_model.hours_cycle):
                        days_cycle = intervention_model.months_cycle*(365./12.)
                        hours_cycle = expected_time_of_use*intervention_model.months_cycle/12.
                    else:
                        days_cycle =  ((intervention_model.hours_cycle*12.)/expected_time_of_use)*(365./12.)
                        hours_cycle = intervention_model.hours_cycle
                    
                    #existing installation
                    if element.intervention_generation_start_hours and intervention_model.hours_cycle:
                        current_hours = hours_cycle*math.ceil((element.intervention_generation_start_hours-hours_first)/hours_cycle)+hours_first
                        days = (365*(current_hours-element.intervention_generation_start_hours))/expected_time_of_use
                        current_date = begin+timedelta(days=days)
                    elif element.intervention_generation_first_date:
                        current_date = datetime.strptime(element.intervention_generation_first_date, '%Y-%m-%d')
                        current_hours = (expected_time_of_use*(current_date-begin).days)/365.
                    #case of new installation
                    else:
                        current_date = begin+timedelta(days=days_first)
                        current_hours = hours_first
                                                
                    keep_alive = 0
                    
                    while current_date <= end:
                        if current_date >= begin:
                            keep_alive = keep_alive+1
                            if keep_alive > 1000:
                                raise osv.except_osv(_('UserError'), _('Technical problem, please call your IT support.'))
                            
                            merge_key = current_date.strftime('%Y-%m-%d')
                        
                            if not merge_table.has_key(merge_key):
                                merge_table[merge_key] = []
                                
                            intervention = {
                                'name':intervention_model.name,
                                'maint_type':intervention_model.intervention_type_id.id,
                                'date_start':current_date, 
                                'date_end':current_date+timedelta(hours=intervention_model.duration), 
                                'planned_hours':intervention_model.duration, 
                                'description':intervention_model.description, 
                                'installation_id':installation.id,
                                'contact_address_id':installation.contact_address_id.id, 
                                'intervention_products':[(0,0,{'delay':product_intervention_model.product_id.sale_delay,'cost_price':product_intervention_model.product_id.cost_price,'sale_price':product_intervention_model.product_id.list_price,'description':product_intervention_model.product_id.name_get()[0][1],'intervention_model':product_intervention_model.intervention_model_id.id,'intervention_product_model':product_intervention_model.id,'maintenance_element_id':element.id,'product_id':product_intervention_model.product_id.id, 'quantity':product_intervention_model.quantity}) for product_intervention_model in intervention_model.intervention_product_model_ids],
                                'hours':current_hours, 
                                'element_model_id':element.element_model_id.id,
                                'intervention_model_id':intervention_model.id, 
                                'project_id':project.id, 
                                'element_name':element.name
                            }
                            
                            merge_table[merge_key].append(intervention)
                        current_hours = current_hours+hours_cycle
                        current_date = current_date+timedelta(days=days_cycle)
                        
        #merge interventions of the same element for the same date
        for key in merge_table:
            #order interventions in the same date by date
            #merge_table[key] = sorted(merge_table[key], lambda elt:elt['date_start'])
            
            duration = 0
            merged_intervention = {
                'name':'', 
                'description':'', 
                'maint_type':merge_table[key][0]['maint_type'],
                'date_planned':merge_table[key][0]['date_start'],
                'date_start':merge_table[key][0]['date_start'],
                'installation_id':merge_table[key][0]['installation_id'],
                'contact_address_id':merge_table[key][0]['contact_address_id'],
                'hours':merge_table[key][0]['hours'],
                'element_model_id':merge_table[key][0]['element_model_id'],
                'project_id':merge_table[key][0]['project_id'],
                'intervention_products' : [],
                'intervention_detail':[],
            }
            
            element_names = {}
            
            max_hours = 0
            
            for intervention in merge_table[key]:
                #manage element name and hours
                if not element_names.has_key(intervention['element_name']):
                    element_names[intervention['element_name']] = {'name':'','hours':0}
                
                element_names[intervention['element_name']]['name'] = (element_names[intervention['element_name']]['name'] or '')+(intervention['name'] or '')+'+'
                
                if merged_intervention['hours'] > element_names[intervention['element_name']]['hours']:
                    element_names[intervention['element_name']]['hours'] = intervention['hours']
                
                if intervention['hours'] > max_hours:
                    max_hours = intervention['hours']
                
                merged_intervention['name'] = merged_intervention['name'] + (intervention['name'] and intervention['name'] or '') + '+'
                merged_intervention['description'] = merged_intervention['description'] + (intervention['description'] or '') + '\n'
                merged_intervention['intervention_products'] = merged_intervention['intervention_products']+intervention['intervention_products']
                merged_intervention['intervention_detail'].append({'intervention_model_id':intervention['intervention_model_id'], 'maintenance_element_id':element.id})
                duration = duration + intervention['planned_hours']
                
            intervention_name = ''
            for element_name in element_names:
                hours = element_names[element_name]['hours']
                intervention_name = intervention_name+element_name+_(': ')+element_names[element_name]['name'][0:-1]+(hours and _(' (at %sh)')%(hours,) or '')+' ; '
            intervention_name = intervention_name[0:-3]
                
            additional_labor_time = 0
            if ('installation_id' in merged_intervention) and merged_intervention['installation_id']:
                additional_labor_time = self.pool.get("maintenance.installation").browse(cr, uid, merged_intervention['installation_id'], context).additional_labor_time
            
            #compute duration (keep only one additional time)
            duration = duration+additional_labor_time
            
            merged_intervention['tasks'] = [(0,0,
                {'date_start':merge_table[key][0]['date_start'], 
                 'date_end':merge_table[key][0]['date_start']+timedelta(hours=duration), 
                 'planned_hours':duration})]
            
            merged_intervention['time_planned'] = duration
            merged_intervention['date_end'] = merged_intervention['date_start']+timedelta(hours=duration)
            merged_intervention['name'] = intervention_name
            merged_intervention['expected_time_of_use'] = max_hours
            merged_intervention['description'] = merged_intervention['description'][0:-2]
            merged_intervention['elements'] = [element]
            
            result.append(merged_intervention)
                    
                
        result = sorted(result, key=lambda elt:elt['date_start'], reverse=True)
                
        return result
    
    
    def onchange_product_id(self, cr, uid, ids, product_id, serial_number, context=None):
        res = {}
        if product_id:
            model_ids = [model.id for model in self.pool.get("product.product").browse(cr, uid, product_id, context).maintenance_element_model_ids if (not serial_number or not model.serial_number_from or not model.serial_number_to or (serial_number >= model.serial_number_from and serial_number <= model.serial_number_to))]
            if model_ids:
                res['value'] = {'element_model_id':max(model_ids)}
        return res
    
maintenance_element()


class maintenance_project(osv.osv):
    _inherit = 'maintenance.project'
    
    def generate_project_budget_lines(self, cr, uid, ids, context):
        intervention_model_pool = self.pool.get("maintenance.intervention.model")
        for project in self.browse(cr, uid, ids, context):
            #verifications
            if not project.date_start or not project.date_end:
                raise osv.except_osv(_('UserError'), _('Project dates must be filled'))
            
            #find "product" and "labor time" project line type
            product_line_type_ids = self.pool.get("maintenance.project.budget.line.type").search(cr, uid, [('default_for_product','=',True)], context=context)
            if not product_line_type_ids:
                raise osv.except_osv(_('UserError'), _('Please set at least one project line type as default for products'))
            else:
                product_line_type_id = product_line_type_ids[0]
            
            product_line_type_ids = self.pool.get("maintenance.project.budget.line.type").search(cr, uid, [('default_for_labor_time','=',True)], context=context)
            if not product_line_type_ids:
                raise osv.except_osv(_('UserError'), _('Please set at least one project line type as default for labor time'))
            else:
                labor_line_type_id = product_line_type_ids[0]
                
            product_line_type_ids = self.pool.get("maintenance.project.budget.line.type").search(cr, uid, [('default_for_travel_cost','=',True)], context=context)
            if not product_line_type_ids:
                raise osv.except_osv(_('UserError'), _('Please set at least one project line type as default for travel cost'))
            else:
                travel_cost_line_type_id = product_line_type_ids[0]
                
            if project.installation_id and project.installation_id.travel_cost_id and project.installation_id.travel_cost_id.product_id:
                travel_cost_name = project.installation_id.travel_cost_id.product_id.name
                travel_cost_product = project.installation_id.travel_cost_id.product_id
            else:
                travel_cost_name = None
                travel_cost_product = None
            
                
            #delete budget lines linked to intervention
            lines_to_delete = self.pool.get("maintenance.project.budget.line").search(cr, uid, [('intervention_model_id','!=',False)], context=context)
            self.pool.get("maintenance.project.budget.line").unlink(cr, uid, lines_to_delete, context=context)
                
                
            #browse generated interventions, and create budget lines in accordance with interventions
            for intervention in project.intervention_ids:
                
                if intervention.state == 'cancel':
                    continue
                
                #labor cost line
                self.pool.get("maintenance.project.budget.line").create(cr, uid, {
                    'name':intervention.maint_type.workforce_product_id.name_get()[0][1],
                    'time_of_use':intervention.expected_time_of_use, 
                    'project_id':project.id, 
                    'product_id':intervention.maint_type.workforce_product_id.id,
                    'sale_price':intervention.maint_type.workforce_product_id.list_price,
                    'cost_price':intervention.maint_type.workforce_product_id.cost_price,  
                    'quantity':intervention.time_planned/intervention.maint_type.workforce_product_duration,
                    'intervention_model_id':intervention.intervention_model_id.id,  
                    'budget_line_type_id':labor_line_type_id, 
                    'intervention_id':intervention.id,
                    'intervention_type_id':intervention.maint_type.id
                }, context=context)
                
                #Travel cost line
                if travel_cost_name and travel_cost_product:
                    self.pool.get("maintenance.project.budget.line").create(cr, uid, {
                        'name':travel_cost_name,
                        'time_of_use':intervention.expected_time_of_use, 
                        'project_id':project.id, 
                        'product_id':travel_cost_product.id,
                        'sale_price':travel_cost_product.list_price,
                        'cost_price':travel_cost_product.cost_price,  
                        'quantity':1, 
                        'intervention_model_id':intervention.intervention_model_id.id,  
                        'budget_line_type_id':travel_cost_line_type_id, 
                        'intervention_id':intervention.id,
                        'intervention_type_id':intervention.maint_type.id
                    }, context=context)
                
                #product lines
                for intervention_product in intervention.intervention_products:
                    self.pool.get("maintenance.project.budget.line").create(cr, uid, {
                        'time_of_use':intervention.expected_time_of_use, 
                        'project_id':project.id,
                        'name':intervention_product.description, 
                        'product_id':intervention_product.product_id.id,
                        'sale_price':intervention_product.sale_price,
                        'cost_price':intervention_product.cost_price,  
                        'quantity':intervention_product.quantity, 
                        'intervention_product_model_id':intervention_product.intervention_product_model.id,
                        'intervention_model_id':intervention.intervention_model_id.id,  
                        'element_id':intervention_product.maintenance_element_id.id, 
                        'budget_line_type_id':product_line_type_id, 
                        'maintenance_product_id':intervention_product.id, 
                        'intervention_id':intervention.id, 
                        'intervention_type_id':intervention.maint_type.id
                    }, context=context)
        return True
    
    def generate_interventions(self, cr, uid, ids, context):
        element_pool = self.pool.get('maintenance.element')
        intervention_pool = self.pool.get("maintenance.intervention")
        intervention_detail_pool = self.pool.get("maintenance.generation.detail")
        for project in self.browse(cr, uid, ids, context):
            #for technician area
            if not context:
                context = {}
            if project.installation_id:
                context['installation_id'] = project.installation_id.id
            
            #delete interventions previously generated in draft state
            intervention_todelete_ids = intervention_pool.search(cr, uid, [('project_id','=',project.id),('sale_order_id','=',False)],context=context)
            intervention_pool.unlink(cr, uid, intervention_todelete_ids, context=context)
            
            #generate interventions
            element_ids = [element.id for element in project.maintenance_elements]
            new_interventions = element_pool.get_interventions(cr, uid, element_ids, project, context=context)
            for new_intervention_tosave in new_interventions:
                intervention_id = intervention_pool.create(cr, uid, new_intervention_tosave, context=context)
                for intervention_detail in new_intervention_tosave['intervention_detail']:
                    self.pool.get("maintenance.generation.detail").create(cr, uid, {
                        'intervention_id':intervention_id, 
                        'maintenance_element_id':intervention_detail['maintenance_element_id'], 
                        'intervention_model_id':intervention_detail['intervention_model_id']
                    }, context)                
        return True
    
    def get_intervention_generation_start_date(self, cr, uid, ids, name, args, context=None):
        res = {}
        for project in self.browse(cr, uid, ids, context):
            if project.intervention_generation_start_date:
                res[project.id] = project.intervention_generation_start_date
            else:
                res[project.id] = datetime.strftime(datetime.now(), "%Y-%m-%d")
        return res
    
    
    _columns = {
        'intervention_ids':fields.one2many('maintenance.intervention', 'project_id', 'Expected interventions under project'), 
        'intervention_generation_type':fields.selection([('models','From models')], string="Intervention generation"),
        'intervention_generation_start_date':fields.date(string="From", help="Date from which interventions will be generated"),
        'used_intervention_generation_start_date':fields.function(get_intervention_generation_start_date, string='Intervention beginning', method=True, type='date', readonly=True),
    }
    
    _defaults={
        'intervention_generation_start_date': lambda *a:datetime.now().strftime('%Y-%m-%d')
    }
    
    def on_change_intervention_generation_start_date(self, cr, uid, ids, intervention_generation_start_date):
        self.write(cr, uid, ids, {'intervention_generation_start_date':intervention_generation_start_date})
        return {}
    
maintenance_project()

class maintenance_generation_detail(osv.osv):
    _name = 'maintenance.generation.detail'
    
    _columns = {
        'intervention_model_id':fields.many2one('maintenance.intervention.model', string="Intervention model"), 
        'intervention_id':fields.many2one('maintenance.intervention', string="Intervention"), 
        'maintenance_element_id':fields.many2one('maintenance.element', string="Maintenance element")
    }
maintenance_generation_detail()

class maintenance_intervention_product(osv.osv):
    _inherit = 'maintenance.intervention.product'
    
    _columns = {
        'intervention_product_model':fields.many2one('maintenance.intervention.product.model', 'Product model'),
        'intervention_model':fields.many2one('maintenance.intervention.model','Intervention Model')
    }
    
maintenance_intervention_product()

class maintenance_intervention(osv.osv):
    _inherit = 'maintenance.intervention'
    
    def compute_project(self, cr, uid, date_start, installation_id, intervention_id=False, enable=False, context=None):
        if intervention_id and self.browse(cr, uid, intervention_id, context).project_id:
            return self.browse(cr, uid, intervention_id, context).project_id.id
        return super(maintenance_intervention, self).compute_project(cr, uid, date_start, installation_id, intervention_id, enable, context)
        
    
    _columns = {
        'project_id':fields.many2one("maintenance.project", 'Project'),
        'project_enable':fields.related('project_id', 'enable', type="boolean", store=True, string="Project enable"), 
        'model_and_iteration_json':fields.text("Model and iteration"), 
        'expected_time_of_use':fields.float("Expected time of use"), 
        'intervention_model_id':fields.many2one('maintenance.intervention.model', 'Intervention model'),
        'element_model_id':fields.many2one('maintenance.element.model', 'Intervention model')
    }
    
maintenance_intervention()

class maintenance_installation(osv.osv):
    _inherit = 'maintenance.installation'
    
    _columns = {
        'additional_labor_time':fields.float("Additional labor time")
    }
    _defaults = {
        'additional_labor_time':1.
    }
    
    def action_generate_project_from_installation(self, cr, uid, ids, context=None):
        if context is None: 
            context = {}
        
        context['installation_ids'] = ids
        
        partial_id = self.pool.get("generate.project.wizard").create(
            cr, uid, {'installation_id':ids[0]}, context=context)
        return {
            'name':_("Generate project"),
            'view_mode': 'form',
            'view_id': False,
            'view_type': 'form',
            'res_model': 'generate.project.wizard',
            'res_id': partial_id,
            'type': 'ir.actions.act_window',
            'nodestroy': True,
            'target': 'new',
            'domain': '[]',
            'context': context
        }

maintenance_installation()

class maintenance_intervention_timeofuse(osv.osv):
    _inherit = 'maintenance.intervention.timeofuse'
    
    def check_regenerate_interventions(self, cr, uid, ids, context):
        return True
    
        projects_to_regenerate = []
        for timeofuse in self.browse(cr, uid, ids, context):
            if timeofuse.valid and timeofuse.maintenance_element_id and timeofuse.maintenance_element_id.maintenance_projects:
                projects_to_regenerate.extend([project.id for project in timeofuse.maintenance_element_id.maintenance_projects])
                #if time of use exceed expected time of use : alert 
                if timeofuse.maintenance_element_id and timeofuse.maintenance_element_id.expected_time_of_use and (timeofuse.time_of_use > timeofuse.maintenance_element_id.expected_time_of_use):
                    request =  self.pool.get('res.request')
                    res_users_pool = self.pool.get("res.users")
                    element = timeofuse.maintenance_element_id
                    me = res_users_pool.browse(cr, uid, uid, context=context)
                    users_to_send_request = [user for user in res_users_pool.browse(cr, uid, res_users_pool.search(cr, uid, [('context_section_id', '=', me.context_section_id.id)]), context) if user.receive_warehouse_request]
                    
                    subject = 'Time of use exceeded for '+element.code+' of installation '+element.installation_id.name_get()[0][1]
                    body = "Time of use read : "+str(timeofuse.time_of_use)+' \nTime of use expected : '+str(timeofuse.maintenance_element_id.expected_time_of_use)
                        
                    for user in users_to_send_request:
                        request.create(cr, uid, 
                            {
                             'name':subject,
                             'body':body,
                             'act_from': uid,
                             'act_to': user.id,
                             'state' : 'waiting',
                            })
                
        self.pool.get("maintenance.project").generate_interventions_from_model(cr, uid, projects_to_regenerate, context)
        return True
    
    def write(self, cr, uid, ids, vals, context=None):
        res = super(maintenance_intervention_timeofuse, self).write(cr, uid, ids, vals, context=context)
        self.check_regenerate_interventions(cr, uid, ids, context)
        return res
    
    def create(self, cr, uid, vals, context=None):
        res = super(maintenance_intervention_timeofuse, self).create(cr, uid, vals, context=context)
        self.check_regenerate_interventions(cr, uid, [res], context)
        return res
    
    def _store_set_values(self, cr, uid, ids, fields, context):
        res = super(maintenance_intervention_timeofuse, self)._store_set_values(cr, uid, ids, fields, context)
        self.check_regenerate_interventions(cr, uid, ids,context)
        return res
    
maintenance_intervention_timeofuse()


class maintenance_project_budget_line(osv.osv):
    _inherit = 'maintenance.project.budget.line'
    _columns = {
        'intervention_model_id':fields.many2one('maintenance.intervention.model', string="Intervention Model"),
        'intervention_product_model_id':fields.many2one('maintenance.intervention.product.model', string="Intervention product model"),
    }
maintenance_project_budget_line()

class maintenance_project_budget_line_type(osv.osv):
    _inherit='maintenance.project.budget.line.type'
    
    _columns={
              'name':fields.char('Name', size=255), 
              'default_for_product':fields.boolean('Used as default type for products generated by intervention models'),
              'default_for_labor_time':fields.boolean('Used as default type for labor time generated by intervention models'),
              'default_for_travel_cost':fields.boolean('Used as default type for travel cost generated by intervention models'),
              'display_on_contract':fields.boolean('Display on contract', help="Lines of this type are displayed on printed contracts")  
              }
    
maintenance_project_budget_line_type()