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

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

Part 2: Consider time zone when creating datetime strings for histories, filenames etc.

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