source: WAeUP_SRP/trunk/Widgets.py @ 952

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

loading of cps_portlets by generic_setup

  • Property svn:keywords set to Id
File size: 19.7 KB
RevLine 
[47]1#-*- mode: python; mode: fold -*-
[295]2
3from cgi import escape
[502]4from types import *
[22]5from Globals import InitializeClass
[199]6##from Products.CPSSchemas.Widget import CPSWidgetType
[295]7from Products.CMFCore.utils import getToolByName
[537]8from Products.CPSSchemas.BasicWidgets import CPSWidget, CPSStringWidget, CPSEmailWidget,CPSImageWidget
[295]9from Products.CPSSchemas.BasicWidgets import renderHtmlTag,CPSSelectWidget, CPSStringWidget
[22]10from Products.CPSSchemas.ExtendedWidgets import CPSDateTimeWidget
[199]11from Products.CPSSchemas.Widget import widgetRegistry
12##from Products.CPSSchemas.WidgetTypesTool import WidgetTypeRegistry
[22]13from DateTime.DateTime import DateTime
14from AccessControl import getSecurityManager
[502]15from Products.WAeUP_SRP.Students import getStudentByRegNo
[22]16from re import compile
[952]17import logging
[22]18
[952]19#from zLOG import LOG, DEBUG
[22]20
[295]21class CPSSelectWidgetForRecord(CPSSelectWidget): ###(
22    """Select widget. with record names"""
23    meta_type = 'Select Widget for Records'
24
25    field_types = ('CPS String Field',)
26    field_inits = ({'is_searchabletext': 1,},)
27
28    _properties = CPSSelectWidget._properties + (
29        {'id': 'record_id', 'type': 'string', 'mode': 'w',
30         'label': 'Record Id', 'is_required' : 1},
31        )
32
33    def render(self, mode, datastructure, **kw):
34        """Render in mode from datastructure."""
35        value = datastructure[self.getWidgetId()]
36        vocabulary = self._getVocabulary(datastructure)
37        portal = getToolByName(self, 'portal_url').getPortalObject()
38        cpsmcat = portal.translation_service
39        if mode == 'view':
40            if self.translated:
41                return escape(cpsmcat(vocabulary.getMsgid(value, value)).encode('ISO-8859-15', 'ignore'))
42            else:
43                return escape(vocabulary.get(value, value))
44        elif mode == 'edit':
45            html_widget_id = self.getHtmlWidgetId()
[444]46            res = renderHtmlTag('select',
47                                name='%s.%s:records' % (self.record_id,html_widget_id),
[295]48                                id=html_widget_id)
49            in_selection = 0
50            for k, v in vocabulary.items():
51                if self.translated:
52                    kw = {'value': k,
53                          'contents': cpsmcat(vocabulary.getMsgid(k, k)).encode('ISO-8859-15', 'ignore')
54                          }
55                else:
56                    kw = {'value': k, 'contents': v}
57                if value == k:
58                    kw['selected'] = 'selected'
59                    in_selection = 1
60                res += renderHtmlTag('option', **kw)
61            if value and not in_selection:
62                kw = {'value': value, 'contents': 'invalid: '+ str(value),
63                      'selected': 'selected'}
64                res += renderHtmlTag('option', **kw)
65            res += '</select>'
66            return res
67        raise RuntimeError('unknown mode %s' % mode)
68
69InitializeClass(CPSSelectWidgetForRecord)
70
71widgetRegistry.register(CPSSelectWidgetForRecord)
72
73###)
74
[373]75class CPSStringWidgetForRecord(CPSStringWidget): ###(
[295]76    """String widget."""
77    meta_type = 'String Widget For Record'
78
79    field_types = ('CPS String Field',)
80    field_inits = ({'is_searchabletext': 1,},)
81    _properties = CPSStringWidget._properties + (
82        {'id': 'record_id', 'type': 'string', 'mode': 'w',
83         'label': 'Record Id', 'is_required' : 1},
84        )
85
86    def render(self, mode, datastructure, **kw):
87        """Render in mode from datastructure."""
88        value = datastructure[self.getWidgetId()]
89        if mode == 'view':
90            return escape(value)
91        elif mode == 'edit':
92            # XXX TODO should use an other name than kw !
93            # XXX change this everywhere
94            html_widget_id = self.getHtmlWidgetId()
95            kw = {'type': 'text',
96                  'id'  : html_widget_id,
[444]97                  'name': '%s.%s:records' % (self.record_id,html_widget_id),
[295]98                  'value': escape(value),
99                  'size': self.display_width,
100                  }
101            if self.size_max:
102                kw['maxlength'] = self.size_max
103            return renderHtmlTag('input', **kw)
104        raise RuntimeError('unknown mode %s' % mode)
105
106InitializeClass(CPSStringWidgetForRecord)
107
108widgetRegistry.register(CPSStringWidgetForRecord)
109
[373]110###)
111
112class CertificateCourseIdWidget(CPSStringWidget): ###(
113    """ CertificateCourseId Widget"""
114    meta_type = "CertificateCourseId Widget"
[444]115
[373]116    def validate(self, datastructure, **kw):
117        """Validate datastructure and update datamodel."""
[444]118
[373]119        valid = CPSStringWidget.validate(self, datastructure, **kw)
120        if not valid:
121            return 0
122        else:
123            widget_id = self.getWidgetId()
124            value = datastructure[widget_id].upper()
125            err = 0
126            c_ids = [c.id for c in self.portal_catalog({'meta_type': "Course"})]
[381]127            if hasattr(self.aq_parent,value):
[444]128                err = 'Course %s already exists' % (value)
[381]129            elif value not in c_ids:
[444]130                err = 'Course %s does not exist' % (value)
[373]131            if err:
132                datastructure.setError(widget_id, err)
133            else:
134                datamodel = datastructure.getDataModel()
135                datamodel[self.fields[0]] = value
[444]136
[373]137            return not err
138
139InitializeClass(CertificateCourseIdWidget)
140
141widgetRegistry.register(CertificateCourseIdWidget)
[551]142###)
[373]143
144
[551]145class CourseIdWidget(CPSStringWidget): ###(
146    """ CourseId Widget"""
147    meta_type = "CourseId Widget"
148
149    def validate(self, datastructure, **kw):
150        """Validate datastructure and update datamodel."""
151
152        valid = CPSStringWidget.validate(self, datastructure, **kw)
153        if not valid:
154            return 0
155        else:
156            widget_id = self.getWidgetId()
157            value = datastructure[widget_id].upper()
158            err = 0
159            res = self.portal_catalog(meta_type= "Course",id = value)
160            if len(res) > 0:
161                err = 'Course %s already exists' % (value)
162            if err:
163                datastructure.setError(widget_id, err)
164            else:
165                datamodel = datastructure.getDataModel()
166                datamodel[self.fields[0]] = value
167
168            return not err
169
170InitializeClass(CourseIdWidget)
171
172widgetRegistry.register(CourseIdWidget)
173
174
[373]175###)
176
[714]177class WAeUPReservedRoomsWidget(CPSStringWidget): ###(
178    """ WAeUPReservedRooms Widget"""
179    meta_type = "WAeUPReservedRooms Widget"
180
181    def validate(self, datastructure, **kw):
182        """Validate datastructure and update datamodel."""
183        import re
184        valid = CPSStringWidget.validate(self, datastructure, **kw)
185        if not valid:
186            return 0
187        else:
188            widget_id = self.getWidgetId()
189            value = datastructure[widget_id]
190            err = 0
191            try:
[926]192                reserved = [(r.split('/')[0],int(r.split('/')[1])) for r in re.split(',|\.| ',value)
[714]193                                     if r]
194            except ValueError,msg:
195                err = str(msg)
196            if err:
197                datastructure.setError(widget_id, err)
198            else:
199                datamodel = datastructure.getDataModel()
200                datamodel[self.fields[0]] = value
201            return not err
202
203InitializeClass(WAeUPReservedRoomsWidget)
204
205widgetRegistry.register(WAeUPReservedRoomsWidget)
206
207
208###)
209
[388]210class WAeUPIdWidget(CPSStringWidget): ###(
211    """ WAeUPId Widget"""
212    meta_type = "WAeUPId Widget"
[444]213
[388]214    def validate(self, datastructure, **kw):
215        """Validate datastructure and update datamodel."""
[444]216
[388]217        valid = CPSStringWidget.validate(self, datastructure, **kw)
[422]218        id_pat_str = r"\S"
219        inv_id_pat = compile(r"^%s$" % id_pat_str)
[388]220        if not valid:
221            return 0
222        else:
[586]223            portal_type_query = {'query':['Faculty',
224                                          'Department',
225                                          'Course',
226                                          'Certificate',
227                                          'CertificateCourse',]}
[388]228            widget_id = self.getWidgetId()
229            value = datastructure[widget_id].upper()
230            err = 0
[440]231            if len(value.split()) > 1:
[783]232                err = 'Invalid Id, Id contains space(s).'
[586]233            elif self.portal_catalog(portal_type=portal_type_query,id=value):
[783]234                err = 'An object with the Id %s already exists in the Academic Section.' % (value)
[388]235            if err:
236                datastructure.setError(widget_id, err)
237            else:
238                datamodel = datastructure.getDataModel()
239                datamodel[self.fields[0]] = value
[444]240
[388]241            return not err
242
243InitializeClass(WAeUPIdWidget)
244
245widgetRegistry.register(WAeUPIdWidget)
246
247
248###)
249
[710]250##class StudentIdWidget(CPSStringWidget): ###(
251##    """ StudentId Widget"""
252##    meta_type = "StudentId Widget"
253##    digits = 8
254##    digits_str = "N"*digits
255##    letters = 2
256##    letters_str = "L"*letters
257##
258##    def validate(self, datastructure, **kw):
259##        """Validate datastructure and update datamodel."""
260##
261##        valid = CPSStringWidget.validate(self, datastructure, **kw)
262##        if not valid:
263##            return 0
264##        else:
265##            widget_id = self.getWidgetId()
266##            value = datastructure[widget_id]
267##            err = 0
268##            if not (len(value) == self.digits + self.letters and value[:self.digits].isdigit() and value[self.digits:].isalpha()):
269##                err = 'Invalid Registration Number in the format: %s%s with N = Number, L = Letter' % (self.digits_str,self.letters_str)
270##            if err:
271##                datastructure.setError(widget_id, err)
272##            else:
273##                datamodel = datastructure.getDataModel()
274##                datamodel[self.fields[0]] = value
275##
276##            return not err
277##
278##InitializeClass(StudentIdWidget)
279##widgetRegistry.register(StudentIdWidget)
280##
281#####)
[444]282
[463]283class JambRegNoWidget(CPSStringWidget): ###(
284    """ JambRegNo Widget"""
285    meta_type = "JambRegNo Widget"
286    digits = 8
287    digits_str = "N"*digits
288    letters = 2
289    letters_str = "L"*letters
290
291    def validate(self, datastructure, **kw):
292        """Validate datastructure and update datamodel."""
293
294        valid = CPSStringWidget.validate(self, datastructure, **kw)
[816]295        #import pdb;pdb.set_trace()
[463]296        if not valid:
297            return 0
298        else:
299            widget_id = self.getWidgetId()
[912]300            value = datastructure[widget_id].upper()
[463]301            err = 0
302            if not (len(value) == self.digits + self.letters and value[:self.digits].isdigit() and value[self.digits:].isalpha()):
[783]303                err = 'Invalid number, the expected format is: %s%s with N = Number, L = Letter' % (self.digits_str,self.letters_str)
[463]304            else:
[502]305                s = getStudentByRegNo(self,value)
306                if s is None:
[710]307                    err = 'No Student with JAMB-Reg-No %s' % (value)
[780]308                else:
309                    s_id = s.getId()
310                    datastructure['s_id'] = s_id
[463]311            if err:
312                datastructure.setError(widget_id, err)
313            else:
314                datamodel = datastructure.getDataModel()
315                datamodel[self.fields[0]] = value
316            return not err
317
318InitializeClass(JambRegNoWidget)
319
320widgetRegistry.register(JambRegNoWidget)
[47]321###)
322
[794]323class WAeUPResultsWidget(CPSStringWidget): ###(
324    """ WAeUPResults Widget"""
325    meta_type = "WAeUp Results Widget"
326
327    def prepare(self, datastructure, **kw): ###(
328        """Prepare datastructure from datamodel."""
329        datamodel = datastructure.getDataModel()
330        v = datamodel[self.fields[0]]
331        #import pdb;pdb.set_trace()
332        widget_id = self.getWidgetId()
[807]333        datastructure[widget_id] = v
[794]334        datastructure[widget_id+'_s'] = ''
335        datastructure[widget_id+'_g'] = ''
336    ###)
337
338    def validate(self, datastructure, **kw): ###(
339        """Validate datastructure and update datamodel."""
[807]340        #import pdb;pdb.set_trace()
[794]341        widget_id = self.getWidgetId()
342        v = datastructure[widget_id]
343        err = 0
344        s = datastructure[widget_id+'_s'].strip()
345        g = datastructure[widget_id+'_g'].strip()
[807]346        while 1:
347            if not s and g:
348                err = "no subject grad for subject %s " % s
349                break
350            i = 0
351            done = False
352            for sv,gv in v:
353                if sv == s:
354                    done = True
355                    if not g:
356                        v.pop(i)
357                        break
358                    v[i] = (s,g)
359                    break
360                i += 1
361            if done:
362                break
363            if s and g:
364                v.append((s,g))
365            break
[794]366        if err:
367            datastructure.setError(widget_id, err)
368        else:
369            datamodel = datastructure.getDataModel()
370            datamodel[self.fields[0]] = v
371            datastructure[widget_id+'_s'] = s
372            datastructure[widget_id+'_g'] = g
373        return not err
374    ###)
375
376    def render(self, mode, datastructure, **kw): ###(
377        """Render in mode from datastructure."""
378        render_method = 'widget_waeup_result_render'
379        meth = getattr(self, render_method, None)
380        if meth is None:
381            raise RuntimeError("Unknown Render Method %s for widget type %s"
382                               % (render_method, self.getId()))
383        #import pdb;pdb.set_trace()
384        datamodel = datastructure.getDataModel()
385        widget_id = self.getWidgetId()
386        v = datamodel[self.fields[0]]
[807]387        datastructure[widget_id] = v
[794]388        datastructure[widget_id+'_s'] = ''
389        datastructure[widget_id+'_g'] = ''
390        return meth(mode=mode,
391                    datastructure=datastructure,
392                    )
393    ###)
394
395
396InitializeClass(WAeUPResultsWidget)
397widgetRegistry.register(WAeUPResultsWidget)
398###)
399
[488]400class ScratchCardPin: ###(
401    """the ScratchCardPin"""
402    def __init__(self,prefix,batch_no,number):
403        self.p = prefix
404        self.b = batch_no
405        self.n = number
406
407    def __str__(self):
408        return "%s-%s-%s" % (self.p,self.b,self.n)
409###)
410
[47]411class ScratchcardPinWidget(CPSStringWidget): ###(
[22]412    """ ScratchcardPin Widget"""
[199]413    meta_type = "Scratchcard Pin Widget"
[488]414    _properties = CPSWidget._properties + (
415        {'id': 'prefix', 'type': 'string', 'mode': 'w',
416         'label': 'Prefix'},
417         {'id': 'reference', 'type': 'string', 'mode': 'w',
418         'label': 'Reference Field'},
419
420        )
421    prefix = ''
422    reference = ''
[502]423    def prepare(self, datastructure, **kw): ###(
[488]424        """Prepare datastructure from datamodel."""
425        datamodel = datastructure.getDataModel()
426        v = datamodel[self.fields[0]]
427        widget_id = self.getWidgetId()
[742]428        #import pdb;pdb.set_trace()
[747]429        if v and type(v) is StringType:
430            p,b,n = v.split('-')
431            v = ScratchCardPin(v,b,n)
[488]432        if v:
[742]433            p = '%s' % v.p
[488]434            b = '%s' % v.b
435            n = '%s' % v.n
436        else:
[742]437            p = self.prefix
438            if p.startswith('@'):
439                p = getattr(self,self.prefix[1:])()
[488]440            b = n = ''
[742]441            v = ScratchCardPin(p,b,n)
[488]442        datastructure[widget_id] = v
[742]443        datastructure[widget_id+'_p'] = p
[488]444        datastructure[widget_id+'_b'] = b
445        datastructure[widget_id+'_n'] = n
[758]446
[502]447###)
448
[22]449    def validate(self, datastructure, **kw):
450        """Validate datastructure and update datamodel."""
[817]451        #import pdb;pdb.set_trace()
[952]452        s_logger = logging.getLogger('students_pin_usage')
[488]453        widget_id = self.getWidgetId()
454        v = datastructure[widget_id]
455        err = 0
[742]456        prefix= self.prefix
457        if prefix.startswith('@'):
458            prefix= getattr(self,self.prefix[1:])()
[488]459        b = datastructure[widget_id+'_b'].strip()
460        n = datastructure[widget_id+'_n'].strip()
[502]461        pins = self.portal_pins
[742]462        pin = "%(prefix)s%(b)s%(n)s" % vars()
[816]463        do = 1
[843]464        s_id = ''
[635]465        if self.reference == "":
466            ref = str(self.portal_membership.getAuthenticatedMember())
467        else:
468            ref = datastructure[self.reference]
[843]469            if datastructure.errors:
[816]470                do = 0
[843]471                datastructure.setError(widget_id, 'Errors in other data, PIN not checked and used')
[816]472        while do:
473            ok = pins.searchAndSetRecord(pin,ref,prefix)
[710]474            if ok == -2:
[819]475                err = 'Service already activated but with a different PIN.'
[710]476                break
477            elif ok == -1:
[783]478                err = 'Invalid PIN'
[502]479                break
480            if ok == 0:
[796]481                err = 'PIN already used.'
[502]482                break
483            if ok >= 1:
[710]484                #import pdb;pdb.set_trace()
[635]485                if self.isStudent():
486                    student = self.getStudentInfo()['student']
[637]487                    s_id = student.getId()
[952]488                    s_logger.info("Student %s used Pin %s" % (s_id,pin))
[637]489                    break
[635]490                else:
491                    student = getStudentByRegNo(self,ref)
[502]492                if student is None:
[796]493                    err = "Student not found."
[502]494                    break
[648]495                s_id = student.getId()
[502]496                if ok == 2:
[796]497                    err = "You are a portal member, please login with your Student Id and Password."
[502]498                    break
[511]499                student.getContent().makeStudentMember(s_id,password=pin[4:])
[952]500                s_logger.info("Student %s created using Pin %s" % (s_id,pin))
[502]501            break
[488]502        if err:
503            datastructure.setError(widget_id, err)
504        else:
505            datamodel = datastructure.getDataModel()
[742]506            datamodel[self.fields[0]] = ScratchCardPin(prefix,b,n)
507            datastructure[widget_id] = ScratchCardPin(prefix,b,n)
508            datastructure[widget_id+'_p'] = prefix
[488]509            datastructure[widget_id+'_b'] = b
510            datastructure[widget_id+'_n'] = n
[502]511            datastructure['s_id'] = s_id
[488]512        return not err
[444]513
[502]514    def render(self, mode, datastructure, **kw): ###(
[488]515        """Render in mode from datastructure."""
516        render_method = 'widget_scratch_card_pin_render'
517        meth = getattr(self, render_method, None)
518        if meth is None:
519            raise RuntimeError("Unknown Render Method %s for widget type %s"
520                               % (render_method, self.getId()))
521
522        # XXX AT: datastructure has to be set again here, in case we're in edit
523        # or create mode, because a default value has to be provided.
524        #import pdb;pdb.set_trace()
525        datamodel = datastructure.getDataModel()
526        v = datamodel[self.fields[0]]
[502]527        if v and type(v) is StringType:
[742]528            prefix,b,n = v.split('-')
529            v = ScratchCardPin(prefix,b,n)
[488]530        if v:
[742]531            prefix= '%s' % v.p
[488]532            b = '%s' % v.b
533            n = '%s' % v.n
[22]534        else:
[742]535            prefix= self.prefix
536            if prefix.startswith('@'):
537                prefix= getattr(self,self.prefix[1:])()
[488]538            b = n = ''
[742]539            v = ScratchCardPin(prefix,b,n)
540        widget_id = self.getWidgetId()
541        datastructure[widget_id] = v
542        datastructure[widget_id+'_p'] = prefix
543        datastructure[widget_id+'_b'] = b
544        datastructure[widget_id+'_n'] = n
[758]545        return meth(mode=mode,
546                    datastructure=datastructure,
[488]547                    )
[523]548    ###)
[488]549
550
[22]551InitializeClass(ScratchcardPinWidget)
[199]552widgetRegistry.register(ScratchcardPinWidget)
[22]553
[47]554
555###)
556
[537]557class WAeUPImageWidget(CPSImageWidget):
558    """Photo widget."""
559    meta_type = 'WAeUP Image Widget'
560
561    def render(self, mode, datastructure, **kw):
562        render_method = 'widget_waeup_image_render'
563        meth = getattr(self, render_method, None)
564        if meth is None:
565            raise RuntimeError("Unknown Render Method %s for widget type %s"
566                               % (render_method, self.getId()))
567        img_info = self.getImageInfo(datastructure)
568        return meth(mode=mode, datastructure=datastructure, **img_info)
569
570
571
572InitializeClass(WAeUPImageWidget)
573
574widgetRegistry.register(WAeUPImageWidget)
575
576
[22]577###########
578
Note: See TracBrowser for help on using the repository browser.