source: WAeUP_SRP/base/Accommodation.py @ 2994

Last change on this file since 2994 was 2867, checked in by Henrik Bettermann, 17 years ago

2 fixes

  • Property svn:keywords set to Id
File size: 11.5 KB
Line 
1#-*- mode: python; mode: fold -*-
2from Globals import InitializeClass
3from AccessControl import ClassSecurityInfo
4
5from Products.CMFCore.utils import UniqueObject, getToolByName
6from Products.CMFCore.permissions import View
7from Products.CMFCore.permissions import ModifyPortalContent
8from Products.CPSCore.CPSBase import CPSBase_adder, CPSBaseFolder
9#from Products.CPSCore.CPSBase import CPSBaseDocument as BaseDocument
10from Products.CPSDocument.CPSDocument import CPSDocument
11from Products.CPSCore.CPSBase import CPSBaseBTreeFolder as BaseBTreeFolder
12from Products.WAeUP_SRP.WAeUPTables import AccommodationTable,NOT_OCCUPIED
13import logging
14import csv,re,os
15import Globals
16import DateTime
17import re
18p_home = Globals.package_home(globals())
19i_home = Globals.INSTANCE_HOME
20
21
22class AccoFolder(CPSDocument): ###(
23    """
24    WAeUP AccoFolder containing Accommodation halls
25    """
26    meta_type = 'AccoFolder'
27    portal_type = meta_type
28    security = ClassSecurityInfo()
29
30    security.declareProtected(View,"Title")
31    def Title(self):
32        """compose title"""
33        return "Accommodation Section"
34
35    security.declareProtected(ModifyPortalContent,"generateFreeBedsList") ###(
36    def generateFreeBedsList(self):
37        """
38        generate the free Bedslist.
39        """
40        freelist = self.portal_accommodation
41        l = self.portal_catalog({'meta_type': "AccoHall"})
42        halls = []
43        generated = []
44        generated.append('"Bed","BedType","Student"' % vars())
45        beds_generated = []
46        for h in l:
47            halls.append(h.getObject())
48        for hall in halls:
49            #import pdb;pdb.set_trace()
50            hall_doc = hall.getContent()
51            hall_gen = {}
52            hall_gen['name'] = hall.Title
53            count = 0
54            reserved = [(r.split('/')[0],int(r.split('/')[1])) for r in re.split(',|\.| ',hall_doc.reserved_rooms)
55                                     if r]
56            #for block in range(1,int(hall_doc.nr_of_blocks)+1):
57            # for block in 'ABCDEFGHIJ'[:int(hall_doc.nr_of_blocks)]:
58            if set(hall_doc.blocks_for_female).intersection(set(hall_doc.blocks_for_male)):
59                return self.accommodation.acco_folder_view(beds_generated=beds_generated)
60            for block in hall_doc.blocks_for_female + hall_doc.blocks_for_male:
61                sex = 'male'
62                if block in hall_doc.blocks_for_female:
63                    sex = 'female'
64                for floor in range(1,int(hall_doc.nr_of_floors)+1):
65                    for room in range(1,int(hall_doc.rooms_per_floor)+1):
66                        for bed in 'ABCDEFGH'[:int(hall_doc.beds_per_room)]:
67                            room_nr = floor*100 + room
68                            bt = 're'
69                            if (block,room_nr) in reserved:
70                                bt = "reserved"
71                            elif hall_doc.special_handling and not hall_doc.special_handling.startswith("no"):
72                                bt = hall_doc.special_handling
73                            elif bed in hall_doc.beds_for_fresh:
74                                bt = 'fr'
75                            elif bed in hall_doc.beds_for_pre:
76                                bt = 'pr'
77                            elif bed in hall_doc.beds_for_final:
78                                bt = 'fi'
79                            if hall_doc.special_handling.startswith("no_"):
80                                bt += "_" + hall_doc.special_handling[3:]
81                            bt = "%(sex)s_%(bt)s" % vars()
82                            uid = '%s_%s_%d_%s' % (hall.getId(),block,room_nr,bed)
83                            d = {}
84                            d['bed'] = uid
85                            d['bed_type'] = bt
86                            d['sort_id'] = getattr(hall_doc,'sort_id',0)
87                            d['hall'] = hall.getId()
88                            d['student'] = NOT_OCCUPIED
89                            try:
90                                #freelist.addRecord(bed = uid, bed_type = bt,hall = hall.getId())
91                                freelist.addRecord(**d)
92                                count +=1
93                                generated.append('"%(uid)s","%(bt)s"' % vars())
94                            except ValueError:
95                                #freelist.modifyRecord(bed = uid, bed_type = bt,hall =hall.getId())
96                                #freelist.modifyRecord(**d)
97                                pass
98            hall_gen['count']= count
99            beds_generated.append(hall_gen)
100        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
101        open("%s/import/bedlist_%s.csv" % (i_home,current),"w+").write('\n'.join(generated))
102        return self.accommodation.acco_folder_view(beds_generated=beds_generated)
103
104###)
105
106    security.declareProtected(ModifyPortalContent,"importReservedBeds")###(
107    def importReservedBeds(self):
108        """load Reserved Beds from CSV"""
109        import transaction
110        import random
111        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
112        students_folder = self.portal_url.getPortalObject().campus.students
113        acco_folder = self.portal_url.getPortalObject().campus.accommodation
114        tr_count = 1
115        total = 0
116        name = 'ReservedBeds'
117        accommodation = self.portal_accommodation
118        students_cat = self.students_catalog
119        no_import = []
120        imported = []
121        logger = logging.getLogger('Accommodation.AccoFolder.importReservedBeds')
122        try:
123            beds = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
124        except:
125            logger.error('Error reading %s.csv' % name)
126            return
127        halls = {}
128        start = True
129        for bed in beds:
130            if start:
131                start = False
132                logger.info('start loading from %s.csv' % name)
133                s = ','.join(['"%s"' % fn for fn in bed.keys()])
134                imported.append(s)
135                no_import.append('%s,"Error"' % s)
136                format = ','.join(['"%%(%s)s"' % fn for fn in bed.keys()])
137                format_error = format + ',"%(Error)s"'
138                no_certificate = "no certificate %s" % format
139            matric_no = bed.get('matric_no')
140            jamb_reg_no = bed.get('jamb_reg_no')
141            if matric_no != '':
142                res = students_cat(matric_no = matric_no)
143                if not res:
144                    bed['Error'] = "No such student"
145                    no_import.append( format_error % bed)
146                    continue
147                student = res[0]
148            elif jamb_reg_no != '':
149                res = students_cat(jamb_reg_no = jamb_reg_no)
150                if not res:
151                    bed['Error'] = "No such student"
152                    no_import.append( format_error % bed)
153                    continue
154                student = res[0]
155            else:
156                bed['Error'] = "No such student"
157                no_import.append( format_error % bed)
158                continue
159            sid = student.id
160            names = bed.get('name').split()
161            n = 0
162            for na in names:
163                if na.endswith(','):
164                    names[n] = na[:-1]
165                n += 1
166            s_names = student.name.split()
167            found = False
168            for sn in s_names:
169                if sn.upper() in names:
170                    found = True
171                    break
172            if not found:
173                bed['Error'] = "Name mismatch %s %s" % (str(names),str(s_names))
174                no_import.append( format_error % bed)
175                continue
176            hall = bed.get('hall')
177            if hall not in halls.keys():
178                hall_object = getattr(acco_folder,hall, None)
179                if hall_object is None:
180                    bed['Error'] = "No such hall"
181                    no_import.append( format_error % bed)
182                    continue
183                halls[hall] = hall_doc = hall_object.getContent()
184            bid = "%(hall)s_%(block)s_%(room)s_%(bed)s" % bed
185            res = accommodation(bed = bid)
186            psm = ''
187            while True:
188                if not res:
189                    psm = "No bed with this id"
190                    break
191                bed_brain = res[0]
192                if not bed_brain.bed_type.endswith("reserved"):
193                    psm = "Not a reserved bed"
194                    break
195                if bed_brain.student:
196                    psm = "Bed %s already reserved for %s" % (bid,bed_brain.student)
197                    break
198                if student.sex and not bed.get('block') in hall_doc.blocks_for_female:
199                    psm = "Sex does not match %s" % bid
200                    break
201                break
202            if psm != '':
203                bed['Error'] = psm
204                no_import.append( format_error % bed)
205                continue
206            already = accommodation(student=sid)
207            if already:
208                accommodation.modifyRecord(bed=already[0].bed,student='')
209                student_obj = getattr(students_folder, student.id)
210                acco_id = "accommodation_%s" % self.getSessionId()[0]
211                if acco_id in student_obj.objectIds():
212                    acco_doc = getattr(student_obj, acco_id).getContent()
213                    acco_doc.edit(mapping={'bed': bid})
214                    member = self.portal_membership.getAuthenticatedMember()
215                    logger.info('%s changed reserved bed %s for %s' % (member,bid,sid))
216            accommodation.modifyRecord(bed = bid, student = sid)
217            imported.append( format % bed)
218            tr_count += 1
219            if tr_count > 1000:
220                if len(no_import) > 0:
221                    open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
222                             '\n'.join(no_import) + '\n')
223                    no_import = []
224                open("%s/import/%simported%s.csv" % (i_home,name,current),"a").write(
225                                            '\n'.join(no_import) + "\n")
226                imported = []
227                em = '%d transactions commited total %s\n' % (tr_count,total)
228                transaction.commit()
229                regs = []
230                logger.info(em)
231                total += tr_count
232                tr_count = 0
233        #from pdb import set_trace;set_trace()
234        open("%s/import/%simported%s.csv" % (i_home,name,current),"a").write(
235                                            '\n'.join(imported))
236        open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
237                                                '\n'.join(no_import))
238        logger.info('finished loading from %s.csv' % name)
239        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
240
241
242InitializeClass(AccoFolder)
243
244def addAccoFolder(container, id, REQUEST=None, **kw):
245    """Add a AccoFolder."""
246    ob = AccoFolder(id, **kw)
247    return CPSBase_adder(container, ob, REQUEST=REQUEST)
248###)
249
250###)
251
252class AccoHall(CPSDocument): ###(
253    """
254    WAeUP AccoHall
255    """
256    meta_type = 'AccoHall'
257    portal_type = meta_type
258    security = ClassSecurityInfo()
259
260    security.declareProtected(View,"Title") ###(
261    def Title(self):
262        """compose title"""
263        content = self.getContent()
264        heading = getattr(content,'heading',None)
265        if heading is None:
266            return self.title
267        return heading
268    ###)
269
270InitializeClass(AccoHall)
271
272
273def addAccoHall(container, id, REQUEST=None, **kw):
274    """Add a AccoHall."""
275    ob = AccoHall(id, **kw)
276    return CPSBase_adder(container, ob, REQUEST=REQUEST)
277###)
Note: See TracBrowser for help on using the repository browser.