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

Last change on this file since 13167 was 13166, checked in by Henrik Bettermann, 10 years ago

Adjust logging methods in the various section.

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