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

Last change on this file since 8184 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
RevLine 
[7195]1## $Id: hostel.py 8183 2012-04-16 21:07:28Z henrik $
2##
[6951]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
[7003]22from zope.event import notify
[8183]23from zope.component import getUtility
[6951]24from datetime import datetime
[7811]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
[8183]29from waeup.kofa.interfaces import IKofaUtils
[7811]30from waeup.kofa.interfaces import MessageFactory as _
[6951]31
32class Hostel(grok.Container):
33    """This is a hostel.
34    """
35    grok.implements(IHostel)
36    grok.provides(IHostel)
37
[6952]38    def loggerInfo(self, ob_class, comment=None):
39        target = self.__name__
40        return grok.getSite()['hostels'].logger_info(ob_class,target,comment)
41
[6963]42    def addBed(self, bed):
[6970]43        """Add a bed.
[6963]44        """
45        if not IBed.providedBy(bed):
46            raise TypeError(
47                'Hostels contain only IBed instances')
[6970]48        self[bed.bed_id] = bed
[6963]49        return
50
[6970]51    def updateBeds(self):
52        """Fill hostel with beds or update beds.
53        """
54        added_counter = 0
55        modified_counter = 0
[6978]56        removed_counter = 0
[6988]57        modified_beds = u''
[6978]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
[6998]66            else:
67                self[key].bed_number = 9999
68        remaining = len(keys) - removed_counter
[6978]69
[6970]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',[])
[6971]76        beds_for_all = getattr(self,'beds_for_all',[])
[6976]77        beds_reserved = getattr(self,'beds_reserved',[])
[6970]78        all_blocks = blocks_for_female + blocks_for_male
79        all_beds = (beds_for_pre + beds_for_fresh +
[6971]80            beds_for_returning + beds_for_final + beds_for_all)
[6970]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'
[6976]90                        if '%s_%s_%s' % (block,room_nr,bed) in beds_reserved:
[6970]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'
[6973]100                        bt = u'%s_%s_%s' % (self.special_handling,sex,bt)
[6970]101                        uid = u'%s_%s_%d_%s' % (self.hostel_id,block,room_nr,bed)
102                        if self.has_key(uid):
103                            bed = self[uid]
[6998]104                            # Renumber remaining beds
105                            bed.bed_number = len(self) + 1 - remaining
106                            remaining -= 1
[6970]107                            if bed.bed_type != bt:
108                                bed.bed_type = bt
109                                modified_counter += 1
[6988]110                                modified_beds += '%s ' % uid
[6970]111                        else:
112                            bed = Bed()
113                            bed.bed_id = uid
114                            bed.bed_type = bt
[6998]115                            bed.bed_number = len(self) + 1 - remaining
[6970]116                            bed.owner = NOT_OCCUPIED
117                            self.addBed(bed)
118                            added_counter +=1
[6988]119        return removed_counter, added_counter, modified_counter, modified_beds
[6970]120
[6951]121Hostel = attrs_to_fields(Hostel)
[6963]122
123class Bed(grok.Container):
124    """This is a bed.
125    """
[7068]126    grok.implements(IBed, IBedAllocateStudent)
[6963]127    grok.provides(IBed)
128
129    def getBedCoordinates(self):
[6974]130        """Determine the coordinates from the bed_id.
[6963]131        """
[6974]132        return self.bed_id.split('_')
[6963]133
[6996]134    def bookBed(self, student_id):
[6998]135        if self.owner == NOT_OCCUPIED:
136            self.owner = student_id
[7003]137            notify(grok.ObjectModifiedEvent(self))
[6998]138            return None
139        else:
140            return self.owner
[6996]141
[6974]142    def switchReservation(self):
[7003]143        """Reserves or unreserve bed respectively.
[6974]144        """
145        sh, sex, bt = self.bed_type.split('_')
146        hostel_id, block, room_nr, bed = self.getBedCoordinates()
[6975]147        hostel = self.__parent__
[6988]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',[])
[6976]152        bed_string = u'%s_%s_%s' % (block, room_nr, bed)
[6974]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)
[7718]164
[6991]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.
[7718]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')
[6974]190        self.bed_type = bt
[6988]191        return message
[6974]192
[7042]193    def releaseBed(self):
194        if self.owner == NOT_OCCUPIED:
[7070]195            return
[7042]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
[8183]208            tz = getUtility(IKofaUtils).tzinfo
209            timestamp = datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
[7042]210            bedticket.bed_coordinates = u'-- booking cancelled on %s --' % timestamp
211            return old_owner
212
[6963]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)
[7006]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    """
[7068]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.