source: WAeUP_SRP/trunk/Accommodation.py @ 5258

Last change on this file since 5258 was 5221, checked in by Henrik Bettermann, 14 years ago

use also student id for identification

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