source: WAeUP_SRP/trunk/Accommodation.py @ 1442

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

added error, if student did already has a bed.

  • Property svn:keywords set to Id
File size: 10.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
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 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_returning:
72                            #    bt = 're'
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('Import.%s' % name)
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            already = accommodation(student=sid)
149            if already:
150                bed['Error'] = "Student already reserved %s" already[0].bed
151                no_import.append( format_error % bed)
152                continue
153            names = bed.get('name').split()
154            n = 0
155            for na in names:
156                if na.endswith(','):
157                    names[n] = na[:-1]
158                n += 1
159            s_names = student.name.split()
160            found = False
161            for sn in s_names:
162                if sn.upper() in names:
163                    found = True
164                    break
165            if not found:
166                bed['Error'] = "Name mismatch %s %s" % (str(names),str(s_names))
167                no_import.append( format_error % bed)
168                continue
169            hall = bed.get('hall')
170            if hall not in halls.keys():
171                hall_object = getattr(acco_folder,hall, None)
172                if hall_object is None:
173                    bed['Error'] = "No such hall"
174                    no_import.append( format_error % bed)
175                    continue
176                halls[hall] = hall_doc = hall_object.getContent()
177            bid = "%(hall)s_%(block)s_%(room)s_%(bed)s" % bed
178            res = accommodation(bed = bid)
179            psm = ''
180            while True:
181                if not res:
182                    psm = "No bed with this id"
183                    break
184                bed_brain = res[0]
185                if not bed_brain.bed_type.endswith("reserved"):
186                    psm = "Not a reserved bed"
187                    break
188                if bed_brain.student:
189                    psm = "Bed %s already reserved for %s" % (bid,bed_brain.student)
190                    break
191                if student.sex and not bed.get('block') in hall_doc.blocks_for_female:
192                    psm = "Sex does not match %s" % bid
193                    break
194                break
195            if psm != '':
196                bed['Error'] = psm
197                no_import.append( format_error % bed)
198                continue
199            accommodation.modifyRecord(bed = bid, student = sid)
200            imported.append( format % bed)
201            tr_count += 1
202            if tr_count > 1000:
203                if len(no_import) > 0:
204                    open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
205                             '\n'.join(no_import) + '\n')
206                    no_import = []
207                open("%s/import/%simported%s.csv" % (i_home,name,current),"a").write(
208                                            '\n'.join(no_import) + "\n")
209                imported = []
210                em = '%d transactions commited total %s\n' % (tr_count,total)
211                transaction.commit()
212                regs = []
213                logger.info(em)
214                total += tr_count
215                tr_count = 0
216        #from pdb import set_trace;set_trace()
217        open("%s/import/%simported%s.csv" % (i_home,name,current),"a").write(
218                                            '\n'.join(imported))
219        open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
220                                                '\n'.join(no_import))
221        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
222
223       
224InitializeClass(AccoFolder)
225
226def addAccoFolder(container, id, REQUEST=None, **kw):
227    """Add a AccoFolder."""
228    ob = AccoFolder(id, **kw)
229    return CPSBase_adder(container, ob, REQUEST=REQUEST)
230###)
231
232class AccoHall(CPSDocument): ###(
233    """
234    WAeUP AccoHall containing Departments
235    """
236    meta_type = 'AccoHall'
237    portal_type = meta_type
238    security = ClassSecurityInfo()
239
240    security.declareProtected(View,"Title") ###(
241    def Title(self):
242        """compose title"""
243        content = self.getContent()
244        heading = getattr(content,'heading',None)
245        if heading is None:
246            return self.title
247        return heading
248    ###)
249
250InitializeClass(AccoHall)
251
252   
253def addAccoHall(container, id, REQUEST=None, **kw):
254    """Add a AccoHall."""
255    ob = AccoHall(id, **kw)
256    return CPSBase_adder(container, ob, REQUEST=REQUEST)
257###)
Note: See TracBrowser for help on using the repository browser.