source: WAeUP_SRP/branches/joachim-event-branch/Accommodation.py @ 15554

Last change on this file since 15554 was 1596, checked in by joachim, 18 years ago

merged changes from trunk to joachim-event-branch

  • Property svn:keywords set to Id
File size: 10.7 KB
RevLine 
[103]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
[575]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
[404]12from Products.WAeUP_SRP.WAeUPTables import AccommodationTable
[1410]13import logging
14import csv,re,os
[623]15import Globals
16import DateTime
[638]17import re
[623]18p_home = Globals.package_home(globals())
19i_home = Globals.INSTANCE_HOME
[103]20
21class AccoFolder(CPSDocument): ###(
22    """
[575]23    WAeUP AccoFolder containing Accommodation halls
[103]24    """
25    meta_type = 'AccoFolder'
26    portal_type = meta_type
27    security = ClassSecurityInfo()
[630]28
[575]29    security.declareProtected(View,"Title")
30    def Title(self):
31        """compose title"""
[630]32        return "Accommodation Section"
[575]33
[404]34    security.declareProtected(ModifyPortalContent,"generateFreeBedsList") ###(
35    def generateFreeBedsList(self):
36        """
37        generate the free Bedslist.
38        """
[623]39        freelist = self.portal_accommodation
40        l = self.portal_catalog({'meta_type': "AccoHall"})
[404]41        halls = []
[623]42        generated = []
43        generated.append('"Bed","BedType","Student"' % vars())
[626]44        beds_generated = []
[404]45        for h in l:
46            halls.append(h.getObject())
47        for hall in halls:
[623]48            #import pdb;pdb.set_trace()
[404]49            h = hall.getContent()
[626]50            hall_gen = {}
[630]51            hall_gen['name'] = hall.Title
[626]52            count = 0
[926]53            reserved = [(r.split('/')[0],int(r.split('/')[1])) for r in re.split(',|\.| ',h.reserved_rooms)
[714]54                                     if r]
[926]55            #for block in range(1,int(h.nr_of_blocks)+1):
56            for block in 'ABCDEFGHIJ'[:int(h.nr_of_blocks)]:
[934]57                sex = 'male'
58                if block in h.blocks_for_female:
59                    sex = 'female'
[627]60                for floor in range(1,int(h.nr_of_floors)+1):
61                    for room in range(1,int(h.rooms_per_floor)+1):
[404]62                        for bed in 'ABCDEFGH'[:int(h.beds_per_room)]:
63                            room_nr = floor*100 + room
[638]64                            bt = 're'
[714]65                            if (block,room_nr) in reserved:
[623]66                                bt = "reserved"
[936]67                            elif not h.special_handling.startswith("no"):
[926]68                                bt = h.special_handling
[623]69                            elif bed in h.beds_for_fresh:
[407]70                                bt = 'fr'
[638]71                            #elif bed in h.beds_for_returning:
72                            #    bt = 're'
[407]73                            elif bed in h.beds_for_final:
74                                bt = 'fi'
[936]75                            if h.special_handling.startswith("no_"):
[952]76                                bt += "_" + h.special_handling[3:]
[575]77                            bt = "%(sex)s_%(bt)s" % vars()
[926]78                            uid = '%s_%s_%d_%s' % (hall.getId(),block,room_nr,bed)
[626]79                            try:
[627]80                                freelist.addRecord(bed = uid, bed_type = bt,hall = hall.getId())
[626]81                                count +=1
82                                generated.append('"%(uid)s","%(bt)s"' % vars())
83                            except ValueError:
[627]84                                #freelist.modifyRecord(bed = uid, bed_type = bt,hall =hall.getId())
[626]85                                pass
86            hall_gen['count']= count
87            beds_generated.append(hall_gen)
[623]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))
[650]90        return self.accommodation.acco_folder_view(beds_generated=beds_generated)
[152]91
[404]92###)
93
[1410]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 = []
[1596]109        logger = logging.getLogger('Accommodation.AccoFolder.importReservedBeds')
[1410]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
[1596]171                halls[hall] = hall_doc = hall_object.getContent()
[1410]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
[1449]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()
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()
[1596]203                    logger.info('%s changed reserved bed %s for %s' % (member,bid,sid))
[1410]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))
[1449]226        logger.info('finished loading from %s.csv' % name)
[1410]227        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
228
[1596]229
[103]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
[622]238class AccoHall(CPSDocument): ###(
[103]239    """
[622]240    WAeUP AccoHall containing Departments
[103]241    """
[622]242    meta_type = 'AccoHall'
[103]243    portal_type = meta_type
244    security = ClassSecurityInfo()
[575]245
[404]246    security.declareProtected(View,"Title") ###(
[152]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
[1393]254    ###)
[404]255
[622]256InitializeClass(AccoHall)
[103]257
[1596]258
[622]259def addAccoHall(container, id, REQUEST=None, **kw):
260    """Add a AccoHall."""
261    ob = AccoHall(id, **kw)
[103]262    return CPSBase_adder(container, ob, REQUEST=REQUEST)
263###)
Note: See TracBrowser for help on using the repository browser.