source: main/waeup.sirp/branches/henrik-bootstrap/src/waeup/sirp/hostels/hostel.py @ 10009

Last change on this file since 10009 was 7257, checked in by Henrik Bettermann, 13 years ago

pyflakes

  • Property svn:keywords set to Id
File size: 8.4 KB
Line 
1## $Id: hostel.py 7257 2011-12-03 05:56:47Z henrik $
2##
3## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann
4## This program is free software; you can redistribute it and/or modify
5## it under the terms of the GNU General Public License as published by
6## the Free Software Foundation; either version 2 of the License, or
7## (at your option) any later version.
8##
9## This program is distributed in the hope that it will be useful,
10## but WITHOUT ANY WARRANTY; without even the implied warranty of
11## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12## GNU General Public License for more details.
13##
14## You should have received a copy of the GNU General Public License
15## along with this program; if not, write to the Free Software
16## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17##
18"""
19These are the hostels.
20"""
21import grok
22from zope.event import notify
23from datetime import datetime
24from waeup.sirp.utils.helpers import attrs_to_fields
25from waeup.sirp.hostels.vocabularies import NOT_OCCUPIED
26from waeup.sirp.hostels.interfaces import IHostel, IBed, IBedAllocateStudent
27from waeup.sirp.students.interfaces import IBedTicket
28
29class Hostel(grok.Container):
30    """This is a hostel.
31    """
32    grok.implements(IHostel)
33    grok.provides(IHostel)
34
35    def loggerInfo(self, ob_class, comment=None):
36        target = self.__name__
37        return grok.getSite()['hostels'].logger_info(ob_class,target,comment)
38
39    def addBed(self, bed):
40        """Add a bed.
41        """
42        if not IBed.providedBy(bed):
43            raise TypeError(
44                'Hostels contain only IBed instances')
45        self[bed.bed_id] = bed
46        return
47
48    def updateBeds(self):
49        """Fill hostel with beds or update beds.
50        """
51        added_counter = 0
52        modified_counter = 0
53        removed_counter = 0
54        modified_beds = u''
55
56        # Remove all empty beds. Occupied beds remain in hostel!
57        keys = list(self.keys()) # create list copy
58        for key in keys:
59            if self[key].owner == NOT_OCCUPIED:
60                del self[key]
61                self._p_changed = True
62                removed_counter += 1
63            else:
64                self[key].bed_number = 9999
65        remaining = len(keys) - removed_counter
66
67        blocks_for_female = getattr(self,'blocks_for_female',[])
68        blocks_for_male = getattr(self,'blocks_for_male',[])
69        beds_for_fresh = getattr(self,'beds_for_fresh',[])
70        beds_for_pre = getattr(self,'beds_for_pre',[])
71        beds_for_returning = getattr(self,'beds_for_returning',[])
72        beds_for_final = getattr(self,'beds_for_final',[])
73        beds_for_all = getattr(self,'beds_for_all',[])
74        beds_reserved = getattr(self,'beds_reserved',[])
75        all_blocks = blocks_for_female + blocks_for_male
76        all_beds = (beds_for_pre + beds_for_fresh +
77            beds_for_returning + beds_for_final + beds_for_all)
78        for block in all_blocks:
79            sex = 'male'
80            if block in blocks_for_female:
81                sex = 'female'
82            for floor in range(1,int(self.floors_per_block)+1):
83                for room in range(1,int(self.rooms_per_floor)+1):
84                    for bed in all_beds:
85                        room_nr = floor*100 + room
86                        bt = 'all'
87                        if '%s_%s_%s' % (block,room_nr,bed) in beds_reserved:
88                            bt = "reserved"
89                        elif bed in beds_for_fresh:
90                            bt = 'fr'
91                        elif bed in beds_for_pre:
92                            bt = 'pr'
93                        elif bed in beds_for_final:
94                            bt = 'fi'
95                        elif bed in beds_for_returning:
96                            bt = 're'
97                        bt = u'%s_%s_%s' % (self.special_handling,sex,bt)
98                        uid = u'%s_%s_%d_%s' % (self.hostel_id,block,room_nr,bed)
99                        if self.has_key(uid):
100                            bed = self[uid]
101                            # Renumber remaining beds
102                            bed.bed_number = len(self) + 1 - remaining
103                            remaining -= 1
104                            if bed.bed_type != bt:
105                                bed.bed_type = bt
106                                modified_counter += 1
107                                modified_beds += '%s ' % uid
108                        else:
109                            bed = Bed()
110                            bed.bed_id = uid
111                            bed.bed_type = bt
112                            bed.bed_number = len(self) + 1 - remaining
113                            bed.owner = NOT_OCCUPIED
114                            self.addBed(bed)
115                            added_counter +=1
116        return removed_counter, added_counter, modified_counter, modified_beds
117
118Hostel = attrs_to_fields(Hostel)
119
120class Bed(grok.Container):
121    """This is a bed.
122    """
123    grok.implements(IBed, IBedAllocateStudent)
124    grok.provides(IBed)
125
126    def getBedCoordinates(self):
127        """Determine the coordinates from the bed_id.
128        """
129        return self.bed_id.split('_')
130
131    def bookBed(self, student_id):
132        if self.owner == NOT_OCCUPIED:
133            self.owner = student_id
134            notify(grok.ObjectModifiedEvent(self))
135            return None
136        else:
137            return self.owner
138
139    def switchReservation(self):
140        """Reserves or unreserve bed respectively.
141        """
142        sh, sex, bt = self.bed_type.split('_')
143        hostel_id, block, room_nr, bed = self.getBedCoordinates()
144        hostel = self.__parent__
145        beds_for_fresh = getattr(hostel,'beds_for_fresh',[])
146        beds_for_pre = getattr(hostel,'beds_for_pre',[])
147        beds_for_returning = getattr(hostel,'beds_for_returning',[])
148        beds_for_final = getattr(hostel,'beds_for_final',[])
149        bed_string = u'%s_%s_%s' % (block, room_nr, bed)
150        if bt == 'reserved':
151            bt = 'all'
152            if bed in beds_for_fresh:
153                bt = 'fr'
154            elif bed in beds_for_pre:
155                bt = 'pr'
156            elif bed in beds_for_final:
157                bt = 'fi'
158            elif bed in beds_for_returning:
159                bt = 're'
160            bt = u'%s_%s_%s' % (sh, sex, bt)
161            hostel.beds_reserved.remove(bed_string)
162            message = u'unreserved'
163        else:
164            bt = u'%s_%s_reserved' % (sh, sex)
165            hostel.beds_reserved.append(bed_string)
166            # Comment of Martijn:
167            # If you have a non-Persistent subobject (like a list) and you change it,
168            # you need to manually flag the persistence machinery on the object that
169            # its subobject changed, with _p_changed. This is only necessary if some
170            # of the objects are not sublclasses of Persistent. For common built-in
171            # collections in Python such as list and dictionary there are replacements
172            # (PersistentList, PersistentMapping), and more advanced building blocks
173            # for indexes (BTrees), that don't have this issue.
174            hostel._p_changed = True
175            message = u'reserved'
176        self.bed_type = bt
177        return message
178
179    def releaseBed(self):
180        if self.owner == NOT_OCCUPIED:
181            return
182        else:
183            old_owner = self.owner
184            self.owner = NOT_OCCUPIED
185            notify(grok.ObjectModifiedEvent(self))
186            accommodation_session = grok.getSite()[
187                'configuration'].accommodation_session
188            try:
189                bedticket = grok.getSite()['students'][old_owner][
190                              'accommodation'][str(accommodation_session)]
191            except KeyError:
192                return '%s without bed ticket' % old_owner
193            bedticket.bed = None
194            timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
195            bedticket.bed_coordinates = u'-- booking cancelled on %s --' % timestamp
196            return old_owner
197
198    def loggerInfo(self, ob_class, comment=None):
199        target = self.__name__
200        return grok.getSite()['hostels'].logger_info(ob_class,target,comment)
201
202Bed = attrs_to_fields(Bed)
203
204@grok.subscribe(IBedTicket, grok.IObjectRemovedEvent)
205def handle_bedticket_removed(bedticket, event):
206    """If a bed ticket is deleted, we make sure that also the owner attribute
207    of the bed is cleared (set to NOT_OCCUPIED).
208    """
209    if bedticket.bed != None:
210        bedticket.bed.owner = NOT_OCCUPIED
211        notify(grok.ObjectModifiedEvent(bedticket.bed))
Note: See TracBrowser for help on using the repository browser.