source: main/waeup.kofa/trunk/src/waeup/kofa/hostels/hostel.py @ 9200

Last change on this file since 9200 was 9199, checked in by Henrik Bettermann, 12 years ago

Add hostels and beds exporter (tests will follow).

  • Property svn:keywords set to Id
File size: 10.1 KB
Line 
1## $Id: hostel.py 9199 2012-09-18 21:07:02Z 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 zope.component import getUtility
24from datetime import datetime
25from waeup.kofa.utils.helpers import attrs_to_fields
26from waeup.kofa.hostels.vocabularies import NOT_OCCUPIED
27from waeup.kofa.hostels.interfaces import IHostel, IBed, IBedAllocateStudent
28from waeup.kofa.students.interfaces import IBedTicket
29from waeup.kofa.interfaces import IKofaUtils
30from waeup.kofa.interfaces import MessageFactory as _
31from waeup.kofa.utils.helpers import now
32
33class Hostel(grok.Container):
34    """This is a hostel.
35    """
36    grok.implements(IHostel)
37    grok.provides(IHostel)
38
39    def loggerInfo(self, ob_class, comment=None):
40        target = self.__name__
41        return grok.getSite()['hostels'].logger_info(ob_class,target,comment)
42
43    @property
44    def bed_statistics(self):
45        total = len(self.keys())
46        booked = 0
47        for value in self.values():
48            if value.owner != NOT_OCCUPIED:
49                booked += 1
50        return {'booked':booked, 'total':total}
51
52    def clearHostel(self):
53        """Remove all beds
54        """
55        keys = [i for i in self.keys()] # create deep copy
56        for bed in keys:
57            del self[bed]
58        return
59
60    def addBed(self, bed):
61        """Add a bed.
62        """
63        if not IBed.providedBy(bed):
64            raise TypeError(
65                'Hostels contain only IBed instances')
66        self[bed.bed_id] = bed
67        return
68
69    def updateBeds(self):
70        """Fill hostel with beds or update beds.
71        """
72        added_counter = 0
73        modified_counter = 0
74        removed_counter = 0
75        modified_beds = u''
76
77        # Remove all empty beds. Occupied beds remain in hostel!
78        keys = list(self.keys()) # create list copy
79        for key in keys:
80            if self[key].owner == NOT_OCCUPIED:
81                del self[key]
82                self._p_changed = True
83                removed_counter += 1
84            else:
85                self[key].bed_number = 9999
86        remaining = len(keys) - removed_counter
87
88        blocks_for_female = getattr(self,'blocks_for_female',[])
89        blocks_for_male = getattr(self,'blocks_for_male',[])
90        beds_for_fresh = getattr(self,'beds_for_fresh',[])
91        beds_for_pre = getattr(self,'beds_for_pre',[])
92        beds_for_returning = getattr(self,'beds_for_returning',[])
93        beds_for_final = getattr(self,'beds_for_final',[])
94        beds_for_all = getattr(self,'beds_for_all',[])
95        beds_reserved = getattr(self,'beds_reserved',[])
96        all_blocks = blocks_for_female + blocks_for_male
97        all_beds = (beds_for_pre + beds_for_fresh +
98            beds_for_returning + beds_for_final + beds_for_all)
99        for block in all_blocks:
100            sex = 'male'
101            if block in blocks_for_female:
102                sex = 'female'
103            for floor in range(1,int(self.floors_per_block)+1):
104                for room in range(1,int(self.rooms_per_floor)+1):
105                    for bed in all_beds:
106                        room_nr = floor*100 + room
107                        bt = 'all'
108                        if '%s_%s_%s' % (block,room_nr,bed) in beds_reserved:
109                            bt = "reserved"
110                        elif bed in beds_for_fresh:
111                            bt = 'fr'
112                        elif bed in beds_for_pre:
113                            bt = 'pr'
114                        elif bed in beds_for_final:
115                            bt = 'fi'
116                        elif bed in beds_for_returning:
117                            bt = 're'
118                        bt = u'%s_%s_%s' % (self.special_handling,sex,bt)
119                        uid = u'%s_%s_%d_%s' % (self.hostel_id,block,room_nr,bed)
120                        if self.has_key(uid):
121                            bed = self[uid]
122                            # Renumber remaining beds
123                            bed.bed_number = len(self) + 1 - remaining
124                            remaining -= 1
125                            if bed.bed_type != bt:
126                                bed.bed_type = bt
127                                modified_counter += 1
128                                modified_beds += '%s ' % uid
129                        else:
130                            bed = Bed()
131                            bed.bed_id = uid
132                            bed.bed_type = bt
133                            bed.bed_number = len(self) + 1 - remaining
134                            bed.owner = NOT_OCCUPIED
135                            self.addBed(bed)
136                            added_counter +=1
137        return removed_counter, added_counter, modified_counter, modified_beds
138
139Hostel = attrs_to_fields(Hostel)
140
141class Bed(grok.Container):
142    """This is a bed.
143    """
144    grok.implements(IBed, IBedAllocateStudent)
145    grok.provides(IBed)
146
147    @property
148    def coordinates(self):
149        """Determine the coordinates from the bed_id.
150        """
151        return self.bed_id.split('_')
152
153    # The following property attributes are only needed
154    # for the exporter to ease evaluation with  Excel.
155
156    @property
157    def hall(self):
158        return self.coordinates[0]
159
160    @property
161    def block(self):
162        return self.coordinates[1]
163
164    @property
165    def room(self):
166        return self.coordinates[2]
167
168    @property
169    def bed(self):
170        return self.coordinates[3]
171
172    @property
173    def special_handling(self):
174        return self.bed_type.split('_')[0]
175
176    @property
177    def sex(self):
178        return self.bed_type.split('_')[1]
179
180    @property
181    def bt(self):
182        return self.bed_type.split('_')[2]
183
184
185    def bookBed(self, student_id):
186        if self.owner == NOT_OCCUPIED:
187            self.owner = student_id
188            notify(grok.ObjectModifiedEvent(self))
189            return None
190        else:
191            return self.owner
192
193    def switchReservation(self):
194        """Reserves or unreserve bed respectively.
195        """
196        sh, sex, bt = self.bed_type.split('_')
197        hostel_id, block, room_nr, bed = self.coordinates
198        hostel = self.__parent__
199        beds_for_fresh = getattr(hostel,'beds_for_fresh',[])
200        beds_for_pre = getattr(hostel,'beds_for_pre',[])
201        beds_for_returning = getattr(hostel,'beds_for_returning',[])
202        beds_for_final = getattr(hostel,'beds_for_final',[])
203        bed_string = u'%s_%s_%s' % (block, room_nr, bed)
204        if bt == 'reserved':
205            bt = 'all'
206            if bed in beds_for_fresh:
207                bt = 'fr'
208            elif bed in beds_for_pre:
209                bt = 'pr'
210            elif bed in beds_for_final:
211                bt = 'fi'
212            elif bed in beds_for_returning:
213                bt = 're'
214            bt = u'%s_%s_%s' % (sh, sex, bt)
215
216            # Comment of Martijn:
217            # If you have a non-Persistent subobject (like a list) and
218            # you change it, you need to manually flag the persistence
219            # machinery on the object that its subobject changed, with
220            # _p_changed. This is only necessary if some of the
221            # objects are not sublclasses of Persistent. For common
222            # built-in collections in Python such as list and
223            # dictionary there are replacements (PersistentList,
224            # PersistentMapping), and more advanced building blocks
225            # for indexes (BTrees), that don't have this issue.
226            #hostel._p_changed = True
227
228            # Henrik: Unfortunately, this doesn't work in our case.
229            # After restarting the portal,
230            # added or removed list items are gone. The only way to ensure
231            # persistance is to reassign the list attribute.
232            br = hostel.beds_reserved
233            br.remove(bed_string)
234            hostel.beds_reserved = br
235            message = _(u'unreserved')
236        else:
237            bt = u'%s_%s_reserved' % (sh, sex)
238            # See comment above
239            br = hostel.beds_reserved
240            br.append(bed_string)
241            hostel.beds_reserved = br
242            message = _(u'reserved')
243        self.bed_type = bt
244        return message
245
246    def releaseBed(self):
247        if self.owner == NOT_OCCUPIED:
248            return
249        else:
250            old_owner = self.owner
251            self.owner = NOT_OCCUPIED
252            notify(grok.ObjectModifiedEvent(self))
253            accommodation_session = grok.getSite()[
254                'hostels'].accommodation_session
255            try:
256                bedticket = grok.getSite()['students'][old_owner][
257                              'accommodation'][str(accommodation_session)]
258            except KeyError:
259                return '%s without bed ticket' % old_owner
260            bedticket.bed = None
261            tz = getUtility(IKofaUtils).tzinfo
262            timestamp = now(tz).strftime("%Y-%m-%d %H:%M:%S %Z")
263            bedticket.bed_coordinates = u'-- booking cancelled on %s --' % (
264                timestamp,)
265            return old_owner
266
267    def loggerInfo(self, ob_class, comment=None):
268        target = self.__name__
269        return grok.getSite()['hostels'].logger_info(ob_class,target,comment)
270
271Bed = attrs_to_fields(Bed)
272
273@grok.subscribe(IBedTicket, grok.IObjectRemovedEvent)
274def handle_bedticket_removed(bedticket, event):
275    """If a bed ticket is deleted, we make sure that also the owner attribute
276    of the bed is cleared (set to NOT_OCCUPIED).
277    """
278    if bedticket.bed != None:
279        bedticket.bed.owner = NOT_OCCUPIED
280        notify(grok.ObjectModifiedEvent(bedticket.bed))
Note: See TracBrowser for help on using the repository browser.