source: WAeUP_SRP/base/Accommodation.py @ 2461

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

rebuild getNextInfo.py completely
fetch session from portal properties.xml
change all scripts using getSessionId
remove StudentCourseResult? relevant code from event services
make pay_by_sc.py and interswitch_cb.py work (rebuild both)

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