source: WAeUP_SRP/base/Accommodation.py @ 2823

Last change on this file since 2823 was 2823, checked in by joachim, 17 years ago

fixed as discussed

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