~andorrax/school-base-openerp-module/xavi

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
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
import math
import collections
# -*- coding: utf-8 -*-
##############################################################################
#
#    school module for OpenERP
#    Copyright (C) 2010 Tecnoba S.L. (http://www.tecnoba.com)
#       Pere Ramon Erro Mas <pereerro@tecnoba.com> All Rights Reserved.
#
#    This file is a part of school module
#
#    school OpenERP module is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    school OpenERP module 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 General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################


from osv import osv, fields
from datetime import datetime, date, timedelta
from tools.translate import _
from school_base.school_base import _MIN_DATETIME, _MAX_DATETIME
from collections import defaultdict

# Utility function for convert a database format date string to python date object
def str_to_date(dt):
    return date.strptime(dt, '%Y-%m-%d')

# Utility function for convert a database format datetime string to python datetime object
def str_to_datetime(dt):
    return datetime.strptime(dt, '%Y-%m-%d %H:%M:%S')

class school_impartition_week_line(osv.osv):
    _name = 'school.impartition_week_line'
school_impartition_week_line()

class school_teacher_data(osv.osv):
    _name = 'school.teacher_data'
    _rec_name = 'teacher_id'

    def _get_td_from_classe(self, cr, uid, ids, context = None):
        ret = []
        for classe in self.pool.get('school.classe').browse(cr, uid, ids, context = context):
            for iwl in classe.impartition_week_line_ids:
                for td in iwl.teachers:
                    ret.append(td.id)
        return ret

    def _get_td_from_impartition_week_line(self, cr, uid, ids, context = None):
        ret = []
        for iwl in self.pool.get('school.impartition_week_line').browse(cr, uid, ids, context = context):
            for td in iwl.teachers:
                ret.append(td.id)
        return ret

    def _get_limits(self, cr, uid, ids, field_name, arg, context = None):
        ret = collections.defaultdict(dict)
        for td in self.browse(cr, uid, ids):
            ret[td.id]['limit_from'] = max(td.datetime_from or _MIN_DATETIME,td.iwl_id.date_from or _MIN_DATETIME,td.iwl_id.classe_id.date_from)
            ret[td.id]['limit_to'] = min(td.datetime_to or _MAX_DATETIME,td.iwl_id.date_to or _MAX_DATETIME,td.iwl_id.classe_id.date_to)
        return ret

    def name_get(self, cr, uid, ids, context = None):
        iwl_dicci = collections.defaultdict(list)
        for item in self.browse(cr, uid, ids, context = context):
            iwl_dicci[item.iwl_id.id].append( (item.id,item.teacher_id.teacher_name) )
        ret = {}
        for (iwl_id, iwl_name) in self.pool.get('school.impartition_week_line').name_get(cr, uid, iwl_dicci.keys(), context = context):
            for (id,teacher_name) in iwl_dicci[iwl_id]:
                ret[id] = "%s | %s" % (iwl_name,teacher_name)
        return [(id, ret[id]) for id in ids]
    
    _columns = {
        'teacher_id' : fields.many2one('school.teacher', 'Teacher', required=True, select=1, ),
        'iwl_id' : fields.many2one('school.impartition_week_line','IWL', required=True, select=1, ondelete='cascade',),
        'title' : fields.selection([('imperative','Imperative'),('needed','Needed'),('optional','Optional'),('advisable','Advisable')], 'Title', ),
        'datetime_from' : fields.datetime('From',),
        'limit_from' : fields.function(_get_limits, string='Limit from', method = True, type = 'datetime', multi = 'limits', store = {
                'school.classe' : (_get_td_from_classe,['date_from','date_to'],10),
                'school.impartition_week_line' : (_get_td_from_impartition_week_line,['classe_id','date_from','date_to'],15),
                'school.teacher_data' : (lambda self,cr,uid,ids,context={}: ids,['iwl_id','datetime_from','datetime_to'],20),
            }),
        'datetime_to' : fields.datetime('To',),
        'limit_to' : fields.function(_get_limits, string='Limit to', method = True, type = 'datetime', multi = 'limits', store = {
                'school.classe' : (_get_td_from_classe,['date_from','date_to'],10),
                'school.impartition_week_line' : (_get_td_from_impartition_week_line,['classe_id','date_from','date_to'],15),
                'school.teacher_data' : (lambda self,cr,uid,ids,context={}: ids,['iwl_id','datetime_from','datetime_to'],20),
            }),
        'classe_id' : fields.related('iwl_id','classe_id',type='many2one',relation='school.classe',string="Classe",),
        'week_day' : fields.related('iwl_id','week_day',type='selection',string="Week day",selection=[('1','monday'),('2','tuesday'),('3','wednesday'),('4','thursday'),('5','friday'),('6','saturday'),('7','sunday')],),
        'hour_from' : fields.related('iwl_id','hour_from',type='float',string="Hour from",),
        'duration' : fields.related('iwl_id','duration',type='float',string="Hour to",),
        'weeks_to_pass' : fields.related('iwl_id','weeks_to_pass',string='Week to pass',type='integer',help="Weeks to pass until next week",),
        'week_to_init' : fields.related('iwl_id','week_to_init',string='Week to init',type='integer',help="Weeks to pass until first week"),
    }

    def join_ranges(self, cr, uid, context = None):
        query = """
        SELECT t1.id,t2.id,t1.datetime_from,t2.datetime_to
        FROM school_teacher_data AS t1,school_teacher_data AS t2
        WHERE t1.datetime_to=t2.datetime_from AND t1.teacher_id=t2.teacher_id AND t1.iwl_id=t2.iwl_id LIMIT 1"""
        cont = True
        super_obj = super(school_teacher_data, self)
        while cont:
            cont = False
            cr.execute(query)
            for (id1,id2,datetime_from,datetime_to) in cr.fetchall():
                cont = True
                super_obj.unlink(cr, uid, [id2], context = context)
                super_obj.write(cr, uid, [id1], {'datetime_from': datetime_from, 'datetime_to': datetime_to,}, context=context)
        
    def _no_overlaps(self, cr, uid, ids, context = None):
        for item in self.browse(cr, uid, ids):
            query = """
                SELECT td.id
                FROM school_teacher_data AS td
                    LEFT JOIN school_impartition_week_line AS iwl ON td.iwl_id=iwl.id
                    LEFT JOIN school_classe AS cl ON iwl.classe_id=cl.id
                WHERE td.iwl_id=%s AND td.teacher_id=%s AND COALESCE(td.datetime_from,iwl.date_from,cl.date_from)<%s AND COALESCE(td.datetime_to,iwl.date_to,cl.date_to)>%s AND td.id<>%s
                LIMIT 1"""
            limit_to = item.datetime_to or item.iwl_id.date_to or item.iwl_id.classe_id.date_to
            limit_from = item.datetime_from or item.iwl_id.date_from or item.iwl_id.classe_id.date_from
            params = (item.iwl_id.id,item.teacher_id.id,limit_to,limit_from,item.id) 
            cr.execute(query,params)
            for (lid,) in cr.fetchall():
                return False
        return True
            
    _constraints = [(_no_overlaps, 'Overlaps!',['teacher_id','iwl_id','datetime_from','datetime_to'])]
        
    def _create_teacher_seance(self, cr, uid, obj, context=None):
        args=[('iwl_id','=',obj.iwl_id.id),]
        if obj.datetime_from:
            args+=[('date','>',obj.datetime_from)]
        if obj.datetime_to:
            args+=[('date','<',obj.datetime_to)]
        seances_ids=self.pool.get('school.seance').search(cr, uid, args)
        for seance_id in seances_ids:
            if not self.pool.get('school.teacher_seance').search(cr, uid, [('seance_id','=',seance_id),('teacher_id','=',obj.teacher_id.id)]):
                self.pool.get('school.teacher_seance').create(cr, uid, {'seance_id': seance_id , 'teacher_id': obj.teacher_id.id, 'title': obj.title })

    def ids_to_unlink_teacher_seance(self, cr, uid, ids, context=None):
        ret=[]
        obj_class=self.pool.get('school.teacher_seance')
        for obj in self.browse(cr, uid, ids, context=context):            
            args=[('seance_id.iwl_id.id','=',obj.iwl_id.id),('teacher_id','=',obj.teacher_id.id),]
            if obj.datetime_from:
                args+=[('seance_id.date','>',obj.datetime_from)]
            if obj.datetime_to:
                args+=[('seance_id.date','<',obj.datetime_to)]
            ret+=obj_class.search(cr, uid, args, context=context)
        return ret
        
    def create(self, cr, uid, vals, context=None):
        ret=super(school_teacher_data, self).create(cr, uid, vals, context=context)
        obj=self.browse(cr, uid, ret)
        self._create_teacher_seance(cr, uid, obj)
        return ret

    def unlink(self, cr, uid, ids, context=None):
        ids_to_unlink=self.ids_to_unlink_teacher_seance(cr, uid, ids)
        ret=super(school_teacher_data, self).unlink(cr, uid, ids, context=context)
        self.pool.get('school.teacher_seance').unlink(cr, uid, ids_to_unlink, context=context)
        return ret

    def write(self, cr, uid, ids, vals, context=None):
        ids_to_unlink=self.ids_to_unlink_teacher_seance(cr, uid, ids)
        ret=super(school_teacher_data, self).write(cr, uid, ids, vals, context=context)
        self.pool.get('school.teacher_seance').unlink(cr, uid, ids_to_unlink, context=context)
        for obj in self.browse(cr, uid, ids, context=context):
            self._create_teacher_seance(cr, uid, obj)
        return ret
        
school_teacher_data()

class school_teacher(osv.osv):
    _name = 'school.teacher'
    _inherit = 'school.teacher'
    
    _columns = {
        'teacher_data_ids' : fields.one2many('school.teacher_data','teacher_id',string='IWLs',),

    }

school_teacher()

class school_room(osv.osv):
    _name = 'school.room'
    _inherit = 'school.room'
    _columns = {
        'impartition_week_lines' : fields.one2many('school.impartition_week_line','room_id','Horary',select=0),
    }
school_room()

class school_impartition_week_line(osv.osv):
    _name = 'school.impartition_week_line'
    _inherit = 'util.periodicity'

    def _get_days_no_work(self,cr, uid, iwl_ids):
            days_no_work_by_classe={}
            for iwl in self.browse(cr, uid, iwl_ids):
                if iwl.classe_id.id not in days_no_work_by_classe:                    
                    if iwl.classe_id.holidays_calendar_id and iwl.classe_id.holidays_calendar_id.holidays:
                        days_no_work=[]
                        for holiday in iwl.classe_id.holidays_calendar_id.holidays:
                            cdate=holiday.date_from
                            days_no_work.append(cdate)
                            while cdate<holiday.date_to:
                                cdate=(datetime.strptime(cdate,'%Y-%m-%d')+timedelta(days=1)).strftime('%Y-%m-%d')
                                days_no_work.append(cdate)
                        days_no_work_by_classe[iwl.classe_id.id]=days_no_work
                    else:
                        days_no_work_by_classe[iwl.classe_id.id]=[]
            return days_no_work_by_classe

    def get_datetimes_from_and_duration(self, cr, uid, ids, context = None):
        ret = {}
        for item in self.browse(cr, uid, ids, context = context):
            ret[item.id] = {
                'datetimes_from': self.periodicity_datetimes({'week_day': item.week_day, 'date_from': item.date_from, 'date_to': item.date_to, 'hour_from': item.hour_from, 'weeks_to_pass': item.weeks_to_pass, 'week_to_init': item.week_to_init, 'days_no_work': item.classe_id.days_no_work.split(',')}),
                'duration': item.duration,}
        return ret

    def _create_seances_sub(self, cr, uid, iwl, dates_list):
        teachers = defaultdict(list)
        for data in iwl.teachers:
            teacher_id = data.teacher_id.id
            if teacher_id not in teachers:
                teachers[(data.datetime_from or _MIN_DATETIME,data.datetime_to or _MAX_DATETIME)] += [(0,0,{'teacher_id': teacher_id, 'title': data.title})]
        for date_from in dates_list:
            date_to=datetime.strptime(date_from,'%Y-%m-%d %H:%M:%S')+timedelta(hours=iwl.duration)
            vals_teachers=[]
            for (dtf,dtt) in teachers.keys():
                if date_from < dtt and date_to.strftime('%Y-%m-%d %H:%M:%S') > dtf:
                    vals_teachers += teachers[(dtf,dtt)]
            vals={'date': date_from,
                'date_to': date_to.strftime('%Y-%m-%d %H:%M:%S'),
                'classe_id' : iwl.classe_id.id,
                'iwl_id': iwl.id,
                'room_id': iwl.room_id.id,
                'group_id': iwl.group_id.id,
                'teachers': vals_teachers,
            }
            self.pool.get('school.seance').create(cr, uid, vals)
        return

    def _limits(self, cr, uid, ids, field_name, arg, context=None):
        res={}
        for iwl in self.browse(cr, uid, ids):
            id=iwl.id
            res[id]={'limit_from' : iwl.date_from or _MIN_DATETIME[0:10], 'limit_to' : iwl.date_to or _MAX_DATETIME[0:10]}
            if res[id]['limit_from']<iwl.classe_id.date_from:
                res[id]['limit_from']=iwl.classe_id.date_from
            if res[id]['limit_to']>iwl.classe_id.date_to:
                res[id]['limit_to']=iwl.classe_id.date_to
        self.write(cr, uid, ids, {'seance_check_state': 'programmed',})
        return res

    def name_get(self, cr, uid, ids, context = None):
        ret=[]
        for iwl in self.browse(cr, uid, ids):
            ret.append((iwl.id,"%(course_name)s [%(group_name)s] %(week_day)s-%(hour_from)s:%(minute_from)s%(weeks)s%(hours)s" % {
                'course_name': iwl.classe_id.course_id.name,
                'group_name': iwl.group_id.name,
                'week_day': (',',_('monday'),_('tuesday'),_('wednesday'),_('thursday'),_('friday'),_('saturday'),_('sunday'))[int(iwl.week_day)],
                'hour_from': int(iwl.hour_from),
                'minute_from' : int( (iwl.hour_from - int(iwl.hour_from) ) * 60 ),
                'weeks' : (iwl.weeks_to_pass or iwl.week_to_init) and "-%(weeks_to_pass)s%(week_to_init)s" % {'weeks_to_pass': iwl.weeks_to_pass,'week_to_init': iwl.week_to_init,} or '',
                'hours' : (iwl.date_from or iwl.date_to) and " (%(date_from)s-%(date_to)s)" % {'date_from': iwl.date_from or '','date_to': iwl.date_to or ''} or '',
                }))
        return ret

    def name_search(self, cr, uid, name='', args=[], operator='ilike', context=None, limit=80):
        ids = self.search(cr, uid, args, context = context, limit = limit)
        print "name, args, operator : ", name, args, operator
        return self.name_get(cr, uid, ids, context = context)

    def _derived_group(self, cr, uid, ids, field_name, arg, context=None):
        ret={}
        for iwl in self.browse(cr, uid, ids):
            if iwl.subgroup:
                ret[iwl.id]=iwl.subgroup.id
            else:
                ret[iwl.id]=iwl.classe_id.group_id.id
        return ret

    def check_seances(self, cr, uid, ids, context=None):
        if not context: context={}
        seance_ids_to_unlink=[]
        days_no_work_by_classe=self._get_days_no_work(cr, uid, ids)
        for iwl in self.browse(cr, uid, ids):
            dates_to_create=self.periodicity_datetimes_str(\
                    date_from=iwl.limit_from,\
                    date_to=iwl.limit_to,\
                    hour_from=iwl.hour_from,\
                    week_day=iwl.week_day,\
                    weeks_to_pass=iwl.weeks_to_pass,\
                    week_to_init=iwl.week_to_init,\
                    days_no_work=days_no_work_by_classe[iwl.classe_id.id])
            for seance in iwl.seance_ids:
                if seance.date not in dates_to_create:
                    seance_ids_to_unlink.append(seance.id)
                else:
                    dates_to_create.remove(seance.date)
            self._create_seances_sub(cr, uid, iwl, dates_to_create)
        self.pool.get('school.seance').unlink(cr, uid, seance_ids_to_unlink)
        self.write(cr, uid, ids, {'seance_check_state': 'completed',})
        return

    def _get_hour_to(self, cr, uid, ids, field_name, arg, context = None):
        ret = {}
        for data in self.read(cr, uid, ids, ['hour_from','duration'], context = context):
            ret[data['id']] = data['hour_from'] + data['duration']
        return ret

    def _get_subgroups(self, cr, uid, parent_ids, context = None):
        if not parent_ids:
            return []
        ret = set( self.pool.get('groups.group').search(
                    cr, uid, [('parent_ids.parent_id','in',parent_ids)]) )
        ret.update( self._get_subgroups(cr, uid, list(ret), context = context) )
        return list(ret)

    def _get_subgroup_domain(self, cr, uid, ids, field_name, arg, context = None):
        ret = {}
        for item in self.browse(cr, uid, ids):
            parent_id = item.classe_id.group_id.id
            ret[item.id] = ','.join(map(str,[parent_id,]+self._get_subgroups(cr, uid, [parent_id], context = context)))
        return ret

    def _iwl_for_contact_search(self, cr, uid, obj, name, args, context=None):
        if not args:
            return []
        
        args2 = []
        contact_args = []
        date_max = None
        date_min = None
        for (field,op,value) in args:
            trossos=field.split('.', 1)
            if trossos[0]=='one_contact':
                if len(trossos)==1:
                    if type(value) in (int,long):
                        contact_args+=[('id',op,value)]
                    else:
                        contact_args+=['|',('name',op,value),('first_name',op,value)]
                else:
                    contact_args+=[(trossos[1],op,value)]
            elif trossos[0] == 'date_to' and op == '<':
                date_max = value
            elif trossos[0] == 'date' and op == '>':
                date_min = value
            else:
                args2+=[(field,op,value)]
        if contact_args:
            iwl_ids = []
            contact_ids=self.pool.get('res.partner.contact').search(cr, uid, contact_args)
            if contact_ids:

                obj_parti = self.pool.get('groups.participation')
                part_ids =obj_parti.search(cr, uid, [('participant.id','in',contact_ids)])
                if part_ids:
                    query = """
            SELECT DISTINCT i.id as iwl_id
            FROM groups_group_assignation AS ga
            INNER JOIN groups_group AS g ON ga.group_id=g.id
            INNER JOIN school_impartition_week_line AS i ON ga.group_id=i.group_id AND (i.limit_from, i.limit_to) OVERLAPS (ga.datetime_from,ga.datetime_to)
            WHERE ga.participation_id IN %(ids)s AND i.limit_to>%(datetime_from)s AND i.limit_from<%(datetime_to)s
    """
                    cr.execute(query, {'ids': tuple(part_ids), 'datetime_from': date_min or _MIN_DATETIME, 'datetime_to': date_max or _MAX_DATETIME})
                    iwl_ids = [x for (x,) in cr.fetchall()]
            args2+=[('id','in',iwl_ids)]
            return args2
        
        # not found
        return [('id','<',0)]

    def _iwl_for_teacher_search(self, cr, uid, obj, name, args, context=None):
        if not args:
            return []
        
        args2=[]
        teacher_args=[]
        for (field,op,value) in args:
            trossos=field.split('.', 1)
            if trossos[0]=='one_teacher':
                if len(trossos)==1:
                    if type(value) in (int,long):
                        teacher_args+=[('id',op,value)]
                    else:
                        teacher_args+=[('teacher_name',op,value)]
                else:
                    teacher_args+=[(trossos[1],op,value)]
            else:
                args2+=[(field,op,value)]
        if teacher_args:
            teacher_ids=self.pool.get('school.teacher').search(cr, uid, teacher_args)
            if teacher_ids:
                query="SELECT iwl_id FROM school_teacher_data WHERE teacher_id IN %s"
                cr.execute(query, (tuple(teacher_ids),))
                args2+=[('id','in',[iwl_id for (iwl_id) in cr.fetchall()])]
            else:
                args2+=[('id','=',False)]
            return args2
        
        # not found
        return [('id','<',0)]

    def _get_filled(self, cr, uid, ids, field_name, arg, context=None):
        ret = {}
        for item in self.browse(cr, uid, ids, context=context):
            ret[item.id] = item.week_day and item.duration
        return ret


    _columns = {
        'classe_id' : fields.many2one('school.classe','Classe', ondelete="cascade",select=1,required=True),
        'duration' : fields.float('Duration',help="Duration in hours",),
        'hour_to' : fields.function(_get_hour_to, type = 'float', method = True, string = 'Hour to', store = {
            'school.impartition_week_line' : (lambda self,cr,uid,ids,context={}: ids,['hour_from','duration'],10)}),
        'group_id' : fields.function(_derived_group, method=True, string='Group',
            type='many2one', obj='groups.group', store = {
            'school.classe': (lambda self,cr,uid,ids,context={}:
                self.pool.get('school.impartition_week_line').search(cr, uid, [('group_id','in',ids)]),['group_id'],10),
            'school.impartition_week_line': (lambda self,cr,uid,ids,context={}: ids, ['classe_id','subgroup'], 15),}),
        'subgroup_domain' : fields.function(_get_subgroup_domain, type='text', method=True, help="List of classe subgroup id's"),
        'room_id' : fields.many2one('school.room','Room',select=1,required=False),
        'teachers' : fields.one2many('school.teacher_data','iwl_id','Teachers',),
        'subgroup' : fields.many2one('groups.group','Subgroup',domain="[('id','in',map(int,(subgroup_domain or '0').split(',')) )]",required=False,ondelete='restrict',),
        'seance_ids' : fields.one2many('school.seance','iwl_id',),
        'limit_from' : fields.function(_limits, type='date', method=True, string='Limit from', multi='limits',store={
            'school.classe': (lambda self, cr, uid, ids, context: self.pool.get('school.impartition_week_line').search(cr, uid, [('classe_id','in',ids)]),['date_from','date_to'],10),
            'school.impartition_week_line': (lambda self, cr, uid, ids, context: ids ,['classe_id','date_from','date_to'],15)
            }),
        'limit_to' : fields.function(_limits, type='date', method=True, string='Limit to', multi='limits',store={
            'school.classe': (lambda self, cr, uid, ids, context: self.pool.get('school.impartition_week_line').search(cr, uid, [('classe_id','in',ids)]),['date_from','date_to'],10),
            'school.impartition_week_line': (lambda self, cr, uid, ids, context: ids ,['classe_id','date_from','date_to'],15)
            }),
        'wrong_seances' : fields.boolean('Wrong Seances',select=1),
        'seance_check_state' : fields.selection([('programmed','Programmed'),('completed','Completed')],string='State',select=True,help="Seance check state."),
        
        'one_teacher' : fields.function(lambda self,cr,uid,ids,*a: dict.fromkeys(ids,False),type='many2one',obj='school.teacher',method=True,string="Search Teacher",fnct_search=_iwl_for_teacher_search,select=1,help='For search IWL by teacher'),
        'one_contact' : fields.function(lambda self,cr,uid,ids,*a: dict.fromkeys(ids,False), type="many2one", obj='res.partner.contact', fnct_search=_iwl_for_contact_search, string = "Search Student", method=True,help='For search IWL by student'),
        'filled' : fields.function(_get_filled, type='boolean', method=True, string='Filled', store={
            'school.impartition_week_line' : (lambda self,cr,uid,ids,context={}: ids, ['week_day','duration',], 10),
        })
                
    }

    _constraints = [
# TODO:        (_constraint_coincidence_week_line, 'Same hour in same room or teacher.', ['impartition_week_lines']),
        ]


    def write(self, cr, uid, ids, vals, context=None):
        vals.setdefault('seance_check_state', 'programmed')
        ret=super(school_impartition_week_line, self).write(cr, uid, ids, vals, context=context)
        # Updating rooms for related seances
        if 'room_id' in vals:
            seance_ids=self.pool.get('school.seance').search(cr, uid, [('iwl_id','in',ids),('state','!=','closed')])
            self.pool.get('school.seance').write(cr, uid, seance_ids, {'room_id': vals['room_id'] })
        return ret

    def unlink(self, cr, uid, ids, context=None):
        for iwl in self.browse(cr, uid, ids):
            seance_ids=self.pool.get('school.seance').search(cr, uid, [('iwl_id','=',iwl.id),])
            self.pool.get('school.seance').unlink(cr, uid, seance_ids, context=context)
        ret=super(school_impartition_week_line, self).unlink(cr, uid, ids, context=context)
        return ret

    def create(self, cr, uid, vals, context=None):
        vals.setdefault('seance_check_state', 'programmed')
        ret=super(school_impartition_week_line, self).create(cr, uid, vals, context=context)
        return ret

school_impartition_week_line()

class school_substitution(osv.osv):
    _name = "school.substitution"
    
    def _teacher_out_seances(self, cr, uid, ids, context=None):
        ret={}
        for item in self.browse(cr, uid, ids):
            cr.execute("SELECT s.id FROM school_seance AS s INNER JOIN school_teacher_seance AS ts ON s.id=ts.seance_id AND ts.teacher_id=%s WHERE s.date>%s AND s.date_to <%s", (item.teacher_out.id, item.date_begin, item.date_end) )
            ret[item.id]=[x for (x,) in cr.fetchall()]
        return ret
    
    _columns = {
        'active' : fields.boolean('Active', select=1,),
        'teacher_out': fields.many2one('school.teacher','Teacher out',required=True,),
        'teacher_in' : fields.many2one('school.teacher','Teacher in',required=True,),
        'date_begin' : fields.datetime('Begin',help='Date time to begin substitution',required=True,),
        'date_end' : fields.datetime('End',help='Date time to end substitution',required=True,),
        'iwl_ids' : fields.many2many('school.impartition_week_line','school_subs_iwl_rel','subs_id','iwl_id',string='IWL affected'),
        'nulled' : fields.datetime('Nulled'),
    }
    
    _defaults = {
        'active': lambda *a: True,
    }
    
    def _change(self, cr, uid, teacher_out, teacher_in, date_begin, date_end, td_search_args_extra=[]):
        obj=self.pool.get('school.teacher_data')
        td_ids = obj.search(cr, uid, [('teacher_id','=',teacher_out),
                    '|',('datetime_from','=',False),('datetime_from','<',date_end),
                    '|',('datetime_to','=',False),('datetime_to','>',date_begin)     ] + td_search_args_extra )
        iwl_ids = set()
        for td in obj.browse(cr, uid, td_ids):
            iwl_ids.add(td.iwl_id.id)
            to_create = []
            to_modify = {'teacher_id': teacher_in,}
            if (not td.datetime_from) or td.datetime_from < date_begin:
                to_create.append( (td.datetime_from,date_begin) )
                to_modify['datetime_from'] = date_begin
            if (not td.datetime_to) or td.datetime_to > date_end:
                to_create.append( (date_end,td.datetime_to) )
                to_modify['datetime_to'] = date_end
            obj.write(cr, uid, [td.id], to_modify)
            for (dt_from,dt_to) in to_create:
                self.pool.get('school.teacher_data').create(cr, uid, {'teacher_id': teacher_out,
                                                                      'title': td.title, 'iwl_id': td.iwl_id.id,
                                                                      'datetime_from': dt_from, 'datetime_to': dt_to,})
        return list(iwl_ids)
        
    def create(self, cr, uid, vals, context=None):
        vals['iwl_ids'] = [(6,0,
            self._change(cr, uid, vals['teacher_out'], vals['teacher_in'], vals['date_begin'], vals['date_end']) )]
        ret = super(school_substitution, self).create(cr, uid, vals, context=context)
        self.pool.get('school.teacher_data').join_ranges(cr, uid, context = context)
        return ret
    
    def unlink(self, cr, uid, ids, context = None):
        for item in self.browse(cr, uid, ids):
            if item.active:
                self._change(cr, uid, item.teacher_in.id, item.teacher_out.id, item.date_begin, item.date_end, [('iwl_id','in',[x.id for x in item.iwl_ids])])
        super(school_substitution, self).write(cr, uid, ids, {'active': False,}, context = context)
        self.pool.get('school.teacher_data').join_ranges(cr, uid, context = context)        
            
school_substitution()

class school_holiday_interval(osv.osv):
    _name = 'school.holiday_interval'
    _inherit = 'school.holiday_interval'
    _columns = {
        'name' : fields.char('Name', size=30,),
        'date_from' : fields.date('Date from', select=1, required=True,),
        'date_to' : fields.date('Date to', select=1, required=True,),
        'calendars' : fields.many2many('school.holidays_calendar','school_holidays_calendar_intervals_rel','days_id','cal_id',string="Calendars"),
    }

    def modifica_calendari(self, cr, uid, classe_ids, date_from_ant, date_to_ant, date_from_pos, date_to_pos, context=None):
        def one_more_day(ldate):
            return (datetime.strptime(ldate,'%Y-%m-%d')+timedelta(days=1)).strftime('%Y-%m-%d')
        if date_from_ant and date_to_ant:
            for classe in self.pool.get('school.classe').browse(cr, uid, classe_ids):
                for iwl in classe.impartition_week_line_ids:
                    dates_to_create=[]
                    for cdate in self.pool.get('school.impartition_week_line').periodicity_datetimes_str(\
                            date_from=iwl.limit_from,\
                            date_to=iwl.limit_to,\
                            hour_from=iwl.hour_from,\
                            week_day=iwl.week_day,\
                            weeks_to_pass=iwl.weeks_to_pass,\
                            week_to_init=iwl.week_to_init):
                        if cdate>=date_from_ant and cdate<one_more_day(date_to_ant):
                            if date_from_pos and date_to_pos:
                                if cdate<date_from_pos or cdate>one_more_day(date_to_pos):
                                    dates_to_create.append(cdate)
                            else: dates_to_create.append(cdate)
                    self.pool.get('school.impartition_week_line')._create_seances_sub(cr, uid, iwl, dates_to_create)
        super(school_holiday_interval, self).modifica_calendari(cr, uid, classe_ids, date_from_ant, date_to_ant, date_from_pos, date_to_pos, context=context)

school_holiday_interval()

class school_classe(osv.osv):
    _name = 'school.classe'
    _inherit = 'school.classe'
    def _get_teacher_data(self, cr, uid, ids, field_name, arg, context=None):
        ret={}
        for item in self.browse(cr, uid, ids, context=context):
            ret[item.id]=[]
            for iwl in item.impartition_week_line_ids:
                for teacher_data in iwl.teachers:
                    ret[item.id].append(teacher_data.id)
        return ret
    
    def _fnct_search(self, cr, uid, obj, name, args, context=None):
        ret=[]
        for (field,op,value) in args:
            if field=='teachers':
                ret+=[('impartition_week_line_ids.teachers.teacher_id.name',op,value)]
        return ret
    
    def _search_check_state(self, cr, uid, obj, name, args, context=None):
        ret=[]
        for arg in args:
            if type(arg) in (list,tuple) and len(arg)==3 and arg[0]==name:
                iwl_obj = self.pool.get('school.impartition_week_line')
                op = arg[1]
                if arg[1] in ('==','='):
                    op = '!='
                if arg[1] == 'in':
                    op = 'not in'
                if arg[1] == 'not in':
                    op = 'in'
                if arg[1] in ('!=','<>'):
                    op = '='
                iwl_ids = iwl_obj.search(cr, uid, [('seance_check_state',op,arg[2])])
                ret += [('impartition_week_line_ids','not in',iwl_ids)]
            else:
                ret+=[arg]
        return ret
    
    def _get_seance_check_state(self, cr, uid, ids, field_name, arg, context=None):
        ret = {}
        for item in self.browse(cr, uid, ids, context=context):
            ret[item.id] = 'completed'
            for iwl in item.impartition_week_line_ids:
                if iwl.seance_check_state == 'programmed':
                    ret[item.id] = 'programmed'
        return ret
    
    def _search_all_iwl_filled(self, cr, uid, obj, name, args, context=None):
        ret=[]
        for arg in args:
            if type(arg) in (list,tuple) and len(arg)==3 and arg[0]==name:
                iwl_obj = self.pool.get('school.impartition_week_line')
                op = arg[1]
                if arg[1] in ('==','='):
                    op = '<>'
                if arg[1] in ('!=','<>'):
                    op = '='
                cr.execute("""
SELECT DISTINCT classe_id FROM school_impartition_week_line WHERE filled %s %%s
                """ % op, (arg[2] and 't' or 'f',) )
                ids = [x for (x,) in cr.fetchall()]
                ret += [('id','not in',ids)]
            else:
                ret+=[arg]
        return ret
    
    def _get_all_iwl_filled(self, cr, uid, ids, field_name, arg, context=None):
        ret = {}
        for item in self.browse(cr, uid, ids, context=context):
            ret[item.id] = True
            for iwl in item.impartition_week_line_ids:
                if not iwl.filled:
                    ret[item.id] = False 
        return ret
    
    _columns = {
        'impartition_week_line_ids': fields.one2many('school.impartition_week_line','classe_id','Week hours',required=False,),
        'teachers' : fields.function(_get_teacher_data,fnct_search=_fnct_search,type='one2many',obj='school.teacher_data',method=True,string='Teachers',),
        'seance_check_state' : fields.function(_get_seance_check_state, fnct_search=_search_check_state, type='selection', selection=[('programmed','Programmed'),('completed','Completed')], string='Seance Check State', help="Seance check state."),
        'all_iwl_filled' : fields.function(_get_all_iwl_filled, fnct_search=_search_all_iwl_filled, type='boolean', string='All IWL filled',),
    }

school_classe()

class school_create_subgroup_classe_wizard(osv.osv_memory):
    _name = 'school.create_subgroup_classe.wizard'

    _columns = {
        'group_name' : fields.char('New group name', size=200,),
        'classe_id' : fields.many2one('school.classe','Classe', help = 'Classe to change the group to the subgroup created.'),
        'subgroups_creation' : fields.boolean('Subgroups creation', help = 'The wizard will create specifics subgroups for the IWLs',),
        'sufixe' : fields.char('Sufixe', size=10, help='Characters between group name and ordinal'),
    }

    _defaults = {
        'sufixe' : lambda *a: '',
    }
    
    def default_get(self, cr, uid, fields, context = None):
        if not context:
            context = {}
        vals = super(school_create_subgroup_classe_wizard, self).default_get(cr, uid, fields, context = context)
        if 'active_ids' in context:
            classe_ids = context.get('active_ids',[])
            if classe_ids:
                classe_id = classe_ids[0]

                classe = self.pool.get('school.classe').browse(cr, uid, classe_id, context = context)
                vals['classe_id'] = classe.id
                vals['group_name'] = classe.name + '-GE'
        return dict((k,v) for (k,v) in vals.items() if k in fields)
    
    def act_action(self, cr, uid, ids, context = None):
        for item in self.browse(cr, uid, ids):
            group_id = item.classe_id.group_id
            assigs = []
            for assig in group_id.assignation_ids:
                assigs.append({'participation_id': assig.participation_id.id,
                    'datetime_from': assig.datetime_from,
                    'datetime_to': assig.datetime_to,})
            new_group_id = self.pool.get('groups.group').create(cr, uid, {
                'name': item.group_name,
                'parent_ids': [(0,0,{'direction': 'down', 'parent_id': group_id.id,})], }, context = context)
            for assig in assigs:
                assig['group_id'] = new_group_id
                self.pool.get('groups.group_assignation').create(cr, uid, assig)
            if item.subgroups_creation:
                new_subgroup_by_ilw_id = {}
                ordinal = 1
                for iwl in item.classe_id.impartition_week_line_ids:
                    if iwl.subgroup:
                        new_subgroup = new_group_id
                        if iwl.subgroup.id != group_id.id:
                            if iwl.subgroup.id not in new_subgroup_by_ilw_id:
                                subgroup_name = "%s%s%s" % (item.group_name,item.sufixe,ordinal)
                                ordinal += 1
                                new_classification_id = self.pool.get('groups.classification').create(cr, uid, {
                                            'name': subgroup_name,
                                            'method': 'order_id',
                                            'auto_active': True,})
                                new_subgroup = self.pool.get('groups.group').create(cr, uid, {
                                    'name' : subgroup_name,
                                    'parent_ids': [(0,0,{'direction': 'down', 'parent_id': new_group_id, 'classification': new_classification_id,}),
                                                   (0,0,{'direction': 'down', 'parent_id': iwl.subgroup.id, 'classification': new_classification_id,}),],
                                    }, context = context)
                                new_subgroup_by_ilw_id[iwl.subgroup.id] = new_subgroup
                            else:
                                new_subgroup = new_subgroup_by_ilw_id[iwl.subgroup.id]
                        self.pool.get('school.impartition_week_line').write(cr, uid, [iwl.id], {'subgroup': new_subgroup,})
            self.pool.get('school.classe').write(cr, uid, [item.classe_id.id], {'group_id': new_group_id,})
        return {'type': 'ir.actions.act_window_close'}

school_create_subgroup_classe_wizard()


class school_seance(osv.osv):
    _name = 'school.seance'
    _inherit = 'school.seance'

    def _get_group(self, cr, uid, ids, field_name, arg, context=None):
        res={}
        for item in self.browse(cr, uid, ids):
            group=None
            if item.iwl_id:
                if item.iwl_id.subgroup:
                    group=item.iwl_id.subgroup
            if not group:
                group=item.classe_id and item.classe_id.group_id or False
            res[item.id]=group and group.id or False
        return res

    def _get_classe(self, cr, uid, ids, field_name, args, context = None):
        ret = {}
        ids2 = []
        for item in self.browse(cr, uid, ids):
            if item.iwl_id:
                ret[item.id] = item.iwl_id.classe_id.id
            else:
                ids2.append(item.id)
        if ids2:
            cr.execute("SELECT id,classe_id FROM school_seance WHERE id IN %s", (tuple(ids2),))
            ret.update( dict( [(x,y) for (x,y) in cr.fetchall()] ) )
        return ret
    
    def _set_classe(self, cr, uid, id, name, value, fnct_inv_arg, context = None):
        item = self.browse(cr, uid, id)
        if not item.iwl_id:
            cr.execute("UPDATE school_seance SET classe_id=%s WHERE id=%s", (value, id))
         
    _columns = {
        'classe_id' : fields.function(_get_classe, fnct_inv=_set_classe, type='many2one', obj='school.classe', string='Classe', method=True, store={
            'school.seance' : (lambda self,cr,uid,ids,context: ids, ['iwl_id'], 10),
            'school.impartition_week_line' : (lambda self, cr, uid, ids, context: self.pool.get('school.seance').search(cr, uid, [('iwl_id','in',ids)]), ['classe_id'], 20),
                }),
        'iwl_id' : fields.many2one('school.impartition_week_line', 'IWL', select=1, read_only=1),
        'group_id' : fields.function(_get_group, method=True, string="Group",
            type="many2one", obj='groups.group', select=1, store={
                'school.impartition_week_line': ( lambda self, cr, uid, ids, context: self.pool.get('school.seance').search(cr, uid, [('iwl_id','in',ids)]), ['subgroup'], 10),
                'school.classe': ( lambda self, cr, uid, ids, context: self.pool.get('school.seance').search(cr, uid, [('classe_id','in',ids)]), ['group_id'], 10),
                'school.seance': ( lambda self, cr, uid, ids, context: ids, ['classe_id'],10),
                },
            ),
    }

    def compute_created_seances(self, cr, uid, context=None):
        dicci=self.compute_wrong_seances(cr, uid, limit=100, context=None)
        self.write(cr, uid, dicci['seance_ids_check_ready'], {'state': 'ready'})
        for (key,log_text) in dicci['seance_ids_dict_with_errors'].items():
            self.write(cr, uid, [key], {'state': 'wrong','change_state_log': log_text})
        if dicci['classe_ids_check_wrong']: self.pool.get('school.classe').write(cr, uid, dicci['classe_ids_check_wrong'], {'wrong_seances': True})
        wrong_iwls=set(seance.iwl_id for seance in self.browse(cr, uid, dicci['seance_ids_dict_with_errors'].keys()))
        if wrong_iwls: self.pool.get('school.impartition_week_line').write(cr, uid, list(wrong_iwls), {'wrong_seances': True})
        return True

    def create(self, cr, uid, vals, context=None):
        # @type vals dict
        if vals.get('iwl_id', False):
            iwl=self.pool.get('school.impartition_week_line').browse(cr, uid, vals['iwl_id'])
            vals['group_id']=iwl.subgroup.id or iwl.group_id.id
        return super(school_seance, self).create(cr, uid, vals, context=context)

    def _check_teachers_in_seance(self, cr, uid, ids, context=None):
        for item in self.browse(cr, uid, ids):
            if item.iwl_id:
                num_teachers_needed=0
                for teacher_iwl in item.iwl_id.teachers:
                    if teacher_iwl.title in ('imperative','needed') and teacher_iwl.iwl_id.group_id and (not teacher_iwl.datetime_from or item.date>teacher_iwl.datetime_from) and (not teacher_iwl.datetime_to or item.date<teacher_iwl.datetime_to):
                        num_teachers_needed+=1
                num_teachers_presents=len(item.teachers)
                if num_teachers_presents<num_teachers_needed:
                    return False
        return True

    _constraints = [
        (_check_teachers_in_seance, 'The needs of teachers, according to the schedule, do not comply.',['teachers']),
    ]
school_seance()

class school_participation_course_data(osv.osv):
    _name = 'school.participation_course_data'
    _inherit = 'school.participation_course_data'

    def _get_scheduled(self, cr, uid, ids, fields, arg, context = None):
        ret = dict.fromkeys(ids, 0)
        query = """
        SELECT pcd.id,ga.participation_id AS part_id,c.course_id,ga.limit_from,ga.limit_to,c.id as classe_id
        FROM school_participation_course_data AS pcd
            INNER JOIN groups_group_assignation AS ga ON pcd.participation_id=ga.participation_id AND ga.limit_from IS NOT NULL AND ga.limit_to IS NOT NULL
            INNER JOIN school_classe AS c ON c.course_id=pcd.course_id AND ga.group_id=c.group_id AND c.date_to>ga.limit_from AND c.date_from<ga.limit_to
        WHERE pcd.id IN %(ids)s
        """
        args = {'ids': tuple(ids),}
        cr.execute(query, args)
        hours_by_key = {}
        classe_hours_by_key = collections.defaultdict(list)
        keys_by_pcd_id = {}
        classe_hours = {}
        for (id,part_id,course_id,date_from,date_to,classe_id) in cr.fetchall():
            key = (part_id,course_id)
            keys_by_pcd_id[id]=key
            classe_hours_by_part[key].append((date_from, date_to, classe_id))
            classe_hours[tupla] = 0
        for (date_from, date_to, classe_id) in classe_hours.keys():
            iwl_ids = self.pool.get('school.impartition_week_line').search(cr, uid, [('classe_id','=',classe_id),('limit_to','>',date_from),('limit_from','<',date_to)])
            for (iwl_id,dicci) in self.pool.get('school.impartition_week_line').get_datetimes(cr, uid, iwl_ids, context = context).items():
                for date in dicci['datetimes_from']:
                    if date >= date_from and date < date_to:
                        classe_hours[(date_from, date_to, classe_id)] += dicci['duration']
        for (key,tupla) in classe_hours_by_key.items():
            if key not in hours_by_key:
                hours_by_key[key] = 0
            hours_by_key[key] += classe_hours[tupla]
        for (id,key) in keys_by_pcd_id.items():
            ret[id] = hours_by_key[key]
        return ret

    _columns = {
        'scheduled' : fields.function(_get_scheduled, method = True, type='float', string='Scheduled',),
    }
school_participation_course_data()        

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