source: WAeUP_SRP/branches/joachim-event-branch/Widgets.py @ 8619

Last change on this file since 8619 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: 31.9 KB
RevLine 
[47]1#-*- mode: python; mode: fold -*-
[990]2# $Id: Widgets.py 1596 2007-03-19 21:45:44Z joachim $
[295]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
[551]144class CourseIdWidget(CPSStringWidget): ###(
145    """ CourseId Widget"""
146    meta_type = "CourseId Widget"
147
148    def validate(self, datastructure, **kw):
149        """Validate datastructure and update datamodel."""
150
151        valid = CPSStringWidget.validate(self, datastructure, **kw)
152        if not valid:
153            return 0
154        else:
155            widget_id = self.getWidgetId()
156            value = datastructure[widget_id].upper()
157            err = 0
158            res = self.portal_catalog(meta_type= "Course",id = value)
159            if len(res) > 0:
160                err = 'Course %s already exists' % (value)
161            if err:
162                datastructure.setError(widget_id, err)
163            else:
164                datamodel = datastructure.getDataModel()
165                datamodel[self.fields[0]] = value
166
167            return not err
168
169InitializeClass(CourseIdWidget)
170
171widgetRegistry.register(CourseIdWidget)
172
173
[373]174###)
175
[714]176class WAeUPReservedRoomsWidget(CPSStringWidget): ###(
177    """ WAeUPReservedRooms Widget"""
178    meta_type = "WAeUPReservedRooms Widget"
179
180    def validate(self, datastructure, **kw):
181        """Validate datastructure and update datamodel."""
182        import re
183        valid = CPSStringWidget.validate(self, datastructure, **kw)
184        if not valid:
185            return 0
186        else:
187            widget_id = self.getWidgetId()
188            value = datastructure[widget_id]
189            err = 0
190            try:
[926]191                reserved = [(r.split('/')[0],int(r.split('/')[1])) for r in re.split(',|\.| ',value)
[714]192                                     if r]
[1038]193            except (ValueError,IndexError),msg:
[714]194                err = str(msg)
195            if err:
196                datastructure.setError(widget_id, err)
197            else:
198                datamodel = datastructure.getDataModel()
199                datamodel[self.fields[0]] = value
200            return not err
201
202InitializeClass(WAeUPReservedRoomsWidget)
203
204widgetRegistry.register(WAeUPReservedRoomsWidget)
205###)
206
[388]207class WAeUPIdWidget(CPSStringWidget): ###(
208    """ WAeUPId Widget"""
209    meta_type = "WAeUPId Widget"
[444]210
[388]211    def validate(self, datastructure, **kw):
212        """Validate datastructure and update datamodel."""
[444]213
[388]214        valid = CPSStringWidget.validate(self, datastructure, **kw)
[422]215        id_pat_str = r"\S"
216        inv_id_pat = compile(r"^%s$" % id_pat_str)
[388]217        if not valid:
218            return 0
219        else:
[586]220            portal_type_query = {'query':['Faculty',
221                                          'Department',
222                                          'Course',
223                                          'Certificate',
224                                          'CertificateCourse',]}
[388]225            widget_id = self.getWidgetId()
226            value = datastructure[widget_id].upper()
227            err = 0
[440]228            if len(value.split()) > 1:
[783]229                err = 'Invalid Id, Id contains space(s).'
[586]230            elif self.portal_catalog(portal_type=portal_type_query,id=value):
[783]231                err = 'An object with the Id %s already exists in the Academic Section.' % (value)
[388]232            if err:
233                datastructure.setError(widget_id, err)
234            else:
235                datamodel = datastructure.getDataModel()
236                datamodel[self.fields[0]] = value
[444]237
[388]238            return not err
239
240InitializeClass(WAeUPIdWidget)
241
242widgetRegistry.register(WAeUPIdWidget)
243
244
245###)
246
[1025]247class StudyCourseWidget(CPSStringWidget): ###(
248    """ StudyCourse Widget"""
249    meta_type = "StudyCourse Widget"
250
251    def validate(self, datastructure, **kw):
252        """Validate datastructure and update datamodel."""
253        #from Products.zdb import set_trace
254        #set_trace()
255        valid = CPSStringWidget.validate(self, datastructure, **kw)
256        id_pat_str = r"\S"
257        inv_id_pat = compile(r"^%s$" % id_pat_str)
258        if not valid:
259            return 0
260        else:
261            widget_id = self.getWidgetId()
262            value = datastructure[widget_id].upper()
263            err = 0
264            if len(value.split()) > 1:
265                err = 'Invalid Id, Id contains space(s).'
266            elif not self.portal_catalog(portal_type='Certificate',id=value):
267                err = 'No such certificate'
268            if err:
269                datastructure.setError(widget_id, err)
270            else:
271                datamodel = datastructure.getDataModel()
272                datamodel[self.fields[0]] = value
273            return not err
274
275InitializeClass(StudyCourseWidget)
276
277widgetRegistry.register(StudyCourseWidget)
278###)
279
[463]280class JambRegNoWidget(CPSStringWidget): ###(
281    """ JambRegNo Widget"""
282    meta_type = "JambRegNo Widget"
[1169]283    _properties = CPSStringWidget._properties + (
284        {'id': 'catalog', 'type': 'string', 'mode': 'w',
285         'label': 'Catalog to search'},
286         {'id': 'reference', 'type': 'string', 'mode': 'w',
287         'label': 'Reference Field'},
288         )
289    catalog = "portal_pumeresults" #the catalog to search for jamb_reg_no
290    reference = ""
[463]291    digits = 8
292    digits_str = "N"*digits
293    letters = 2
294    letters_str = "L"*letters
295    def validate(self, datastructure, **kw):
296        """Validate datastructure and update datamodel."""
297        valid = CPSStringWidget.validate(self, datastructure, **kw)
[816]298        #import pdb;pdb.set_trace()
[1169]299        jamb_nr_catalog = getattr(self,self.catalog)
300        widget_id = self.getWidgetId()
301        value = datastructure[widget_id].upper()
302        err = 0
303        if not valid: #or not (len(value) == self.digits + self.letters and value[:self.digits].isdigit() and value[self.digits:].isalpha()):
304            #err = 'Invalid number, the expected format is: %s%s with N = Number, L = Letter' % (self.digits_str,self.letters_str)
305            err = 'Invalid number'
306        elif self.reference == '':
307            #s = getStudentByRegNo(self,value)
308            pume = jamb_nr_catalog(jamb_reg_no = value)
309            if len(pume) < 1:
310                err = 'No Student with JAMB RegNo %s.' % (value)
311            else:
312                datastructure['pume'] = pume[0]
[463]313        else:
[1169]314            #import pdb;pdb.set_trace()
315            record = datastructure[self.reference]
316            #jamb_reg_no = getattr(record,widget_id)
317            jamb_reg_no = record.Entryregno
318            if jamb_reg_no != value:
319                err = 'Entry Registration Nr does not match.'
320        if err:
321            datastructure.setError(widget_id, err)
322        else:
323            datamodel = datastructure.getDataModel()
324            datamodel[self.fields[0]] = value
325        return not err
[463]326
327InitializeClass(JambRegNoWidget)
328
329widgetRegistry.register(JambRegNoWidget)
[47]330###)
331
[1175]332class SecretWidget(CPSStringWidget): ###(
333    """ Secret Widget"""
334    meta_type = "Secret Widget"
335    _properties = CPSStringWidget._properties + (
336        {'id': 'reference', 'type': 'string', 'mode': 'w',
337         'label': 'Reference Record'},
338         {'id': 'check_fields', 'type': 'tokens', 'mode': 'w',
339         'label': 'Fields to check'},
340         )
341    reference = "student"
342    check_fields = ("Firstname", "Middlename","Lastname")
343    def validate(self, datastructure, **kw):
344        """Validate datastructure and update datamodel."""
[1596]345        logger = logging.getLogger('Widgets.SecretWidget.validate')
[1175]346        valid = CPSStringWidget.validate(self, datastructure, **kw)
347        #import pdb;pdb.set_trace()
348        widget_id = self.getWidgetId()
349        value = datastructure[widget_id].upper()
350        err = 0
[1189]351        record = datastructure.get(self.reference,None)
[1379]352        if not valid or len(value) < 2:
[1175]353            err = 'Invalid String'
[1189]354        elif not record or datastructure.errors:
[1177]355            err = 0
[1175]356        else:
357            found = False
358            cvs = []
359            for field in self.check_fields:
360                cv = getattr(record,field).upper()
[1243]361                if len(cv.split()) > 1:
362                    for splited in cv.split():
363                        cvs.append(splited)
364                else:
365                    cvs.append(cv)
[1175]366                if cv  == value.upper():
367                    found = True
368                    break
369            matric_no = record.matric_no
370            name = " ".join(cvs)
371            if not found:
[1596]372                logger.info('%(matric_no)s did not find %(value)s in %(name)s' % vars())
373                err = 'No name does match.'
[1175]374            else:
[1596]375                logger.info('%(matric_no)s found %(value)s in %(name)s' % vars())
[1175]376        if err:
377            datastructure.setError(widget_id, err)
378        else:
379            datamodel = datastructure.getDataModel()
380            datamodel[self.fields[0]] = value
381        return not err
382
383InitializeClass(SecretWidget)
384
385widgetRegistry.register(SecretWidget)
386###)
387
[1146]388class MatricNoWidget(CPSStringWidget): ###(
389    """ MatricNo Widget"""
390    meta_type = "MatricNo Widget"
391    def validate(self, datastructure, **kw):
392        """Validate datastructure and update datamodel."""
393        valid = CPSStringWidget.validate(self, datastructure, **kw)
[1596]394        logger = logging.getLogger('Widgets.MatricNoWidget.validate')
[1146]395        #import pdb;pdb.set_trace()
[1151]396        returning = self.returning_import
[1146]397        results = self.results_import
398        err = 0
[1189]399        widget_id = self.getWidgetId()
400        value = datastructure[widget_id]
401        if not valid or not value:
[1596]402            err = 'Invalid matric_no string %s.' % value
403            logger.info('Invalid matric_no string %s' % value)
[1146]404        else:
[1189]405            value = value.upper()
[1177]406            datastructure['student'] = None
[1146]407            while not err:
[1151]408                res = returning(matric_no = value)
[1146]409                if len(res) < 1:
[1596]410                    logger.info('matric_no %s not found' % value)
411                    err = 'No student with matric_no %s.' % (value)
[1146]412                    continue
413                datastructure['student'] = res[0]
414                res = results(matric_no = value)
415                if len(res) < 1:
[1596]416                    err = 'No results with matric_no %s.' % (value)
[1146]417                    continue
418                datastructure['results'] = res
419                break
[1189]420        if err:
421            datastructure.setError(widget_id, err)
422        else:
423            datamodel = datastructure.getDataModel()
424            datamodel[self.fields[0]] = value
425        return not err
[1146]426
427InitializeClass(MatricNoWidget)
428
429widgetRegistry.register(MatricNoWidget)
430###)
431
[1393]432class StudentIdWidget(CPSStringWidget): ###(
433    """ StudentId Widget"""
434    meta_type = "StudentId Widget"
435    def validate(self, datastructure, **kw):
436        """Validate datastructure and update datamodel."""
437        valid = CPSStringWidget.validate(self, datastructure, **kw)
[1596]438        logger = logging.getLogger('Widgets.StudentIdWidget.validate')
[1393]439        #import pdb;pdb.set_trace()
440        s_cat = self.students_catalog
441        err = 0
442        widget_id = self.getWidgetId()
443        value = datastructure[widget_id]
444        if not valid or not value:
[1596]445            err = 'Invalid id string %s.' % value
446            logger.info('Invalid id string %s' % value)
[1449]447            datastructure['student'] = None
[1393]448        else:
449            value = value.upper()
450            res = s_cat(id = value)
451            if not res:
[1596]452                logger.info('Student id %s not found' % value)
453                err = 'No student with id %s.' % (value)
[1393]454                datastructure['student'] = None
455            else:
456                datastructure['student'] = res[0]
457        if err:
458            datastructure.setError(widget_id, err)
459        else:
460            datamodel = datastructure.getDataModel()
461            datamodel[self.fields[0]] = value
462        return not err
463
464InitializeClass(StudentIdWidget)
465
466widgetRegistry.register(StudentIdWidget)
467###)
468
[1146]469class WAeUPMultilineResultsWidget(CPSStringWidget): ###(
470    """ WAeUPMultilineResults Widget"""
471    meta_type = "WAeUp Multiline Results Widget"
472    _properties = CPSWidget._properties + (
473        {'id': 'nr_of_lines', 'type': 'int', 'mode': 'w',
474         'label': 'Nr of Lines'},
475         )
476    nr_of_lines = 5
477    def prepare(self, datastructure, **kw): ###(
478        """Prepare datastructure from datamodel."""
479        datamodel = datastructure.getDataModel()
480        #import pdb;pdb.set_trace()
481        widget_id = self.getWidgetId()
482        v = datamodel[self.fields[0]]
483        if type(v) is ListType and v:
484            nr_results = len(v)
485        else:
486            v = []
487            nr_results = 0
488        count = 1
489        for s,g in v:
490            wid = "%s%02d"% (widget_id,count)
491            datastructure[wid+'_s'] = s
492            datastructure[wid+'_g'] = g
493            count += 1
494        if nr_results < self.nr_of_lines:
495            for line in range(nr_results,self.nr_of_lines):
496                v.append(('',''))
497                wid = "%s%02d"% (widget_id,line)
498                datastructure[wid+'_s'] = ''
499                datastructure[wid+'_g'] = ''
500        datastructure[widget_id] = v
501        datastructure[widget_id+'_s'] = ''
502        datastructure[widget_id+'_g'] = ''
503    ###)
504
505    def validate(self, datastructure, **kw): ###(
506        """Validate datastructure and update datamodel."""
507        #import pdb;pdb.set_trace()
508        widget_id = self.getWidgetId()
509        err = 0
510        lines = []
511        for line in range(1,30):
512            wid = "%s%02d"% (widget_id,line)
513            if not datastructure.has_key(wid+'_s'):
514                break
515            lines.append((datastructure[wid+'_s'].strip(),
516                         datastructure[wid+'_g'].strip()))
[1155]517
[1146]518        s = datastructure[widget_id+'_s'].strip()
519        g = datastructure[widget_id+'_g'].strip()
520        if s and g:
521            lines.append((s,g))
522        active = []
523        for s,g in lines:
524            if g != "":
525                active.append((s,g))
526        if err:
527            datastructure.setError(widget_id, err)
528        else:
529            datamodel = datastructure.getDataModel()
530            datamodel[self.fields[0]] = active
531        return not err
532    ###)
533
534    def render(self, mode, datastructure, **kw): ###(
535        """Render in mode from datastructure."""
536        render_method = 'widget_waeup_multiline_result_render'
537        meth = getattr(self, render_method, None)
538        if meth is None:
539            raise RuntimeError("Unknown Render Method %s for widget type %s"
540                               % (render_method, self.getId()))
541        #import pdb;pdb.set_trace()
542        datamodel = datastructure.getDataModel()
543        widget_id = self.getWidgetId()
544        lines = datamodel[self.fields[0]]
545        if len(lines) < self.nr_of_lines:
546            for line in range(len(lines),self.nr_of_lines + 1):
547                lines.append(('',''))
548        datastructure[widget_id] = lines
549        datastructure[widget_id+'_s'] = ''
550        datastructure[widget_id+'_g'] = ''
551##        count = 1
552##        for s,g in v:
553##            wid = "%s%02d"% (widget_id,count)
554##            count += 1
555        return meth(mode=mode,
556                    datastructure=datastructure,
557                    )
558    ###)
559
560
561InitializeClass(WAeUPMultilineResultsWidget)
562widgetRegistry.register(WAeUPMultilineResultsWidget)
563###)
564
[794]565class WAeUPResultsWidget(CPSStringWidget): ###(
566    """ WAeUPResults Widget"""
567    meta_type = "WAeUp Results Widget"
568
569    def prepare(self, datastructure, **kw): ###(
570        """Prepare datastructure from datamodel."""
571        datamodel = datastructure.getDataModel()
572        v = datamodel[self.fields[0]]
573        #import pdb;pdb.set_trace()
574        widget_id = self.getWidgetId()
[807]575        datastructure[widget_id] = v
[794]576        datastructure[widget_id+'_s'] = ''
577        datastructure[widget_id+'_g'] = ''
578    ###)
579
580    def validate(self, datastructure, **kw): ###(
581        """Validate datastructure and update datamodel."""
[807]582        #import pdb;pdb.set_trace()
[794]583        widget_id = self.getWidgetId()
584        v = datastructure[widget_id]
585        err = 0
586        s = datastructure[widget_id+'_s'].strip()
587        g = datastructure[widget_id+'_g'].strip()
[807]588        while 1:
589            if not s and g:
590                err = "no subject grad for subject %s " % s
591                break
592            i = 0
593            done = False
594            for sv,gv in v:
595                if sv == s:
596                    done = True
597                    if not g:
598                        v.pop(i)
599                        break
600                    v[i] = (s,g)
601                    break
602                i += 1
603            if done:
604                break
605            if s and g:
606                v.append((s,g))
607            break
[794]608        if err:
609            datastructure.setError(widget_id, err)
610        else:
611            datamodel = datastructure.getDataModel()
612            datamodel[self.fields[0]] = v
613            datastructure[widget_id+'_s'] = s
614            datastructure[widget_id+'_g'] = g
615        return not err
616    ###)
617
618    def render(self, mode, datastructure, **kw): ###(
619        """Render in mode from datastructure."""
620        render_method = 'widget_waeup_result_render'
621        meth = getattr(self, render_method, None)
622        if meth is None:
623            raise RuntimeError("Unknown Render Method %s for widget type %s"
624                               % (render_method, self.getId()))
625        #import pdb;pdb.set_trace()
626        datamodel = datastructure.getDataModel()
627        widget_id = self.getWidgetId()
628        datastructure[widget_id+'_s'] = ''
629        datastructure[widget_id+'_g'] = ''
630        return meth(mode=mode,
631                    datastructure=datastructure,
632                    )
633    ###)
634
635
636InitializeClass(WAeUPResultsWidget)
637widgetRegistry.register(WAeUPResultsWidget)
638###)
639
[488]640class ScratchCardPin: ###(
641    """the ScratchCardPin"""
642    def __init__(self,prefix,batch_no,number):
[990]643        if not batch_no and not number:
644            s = prefix
[996]645            if len(s) > 3:
[990]646                prefix,batch_no,number = s[:3],s[3:-10],s[-10:]
647            else:
[996]648                prefix,batch_no,number = s,'',''
[488]649        self.p = prefix
650        self.b = batch_no
651        self.n = number
652
653    def __str__(self):
654        return "%s-%s-%s" % (self.p,self.b,self.n)
[1146]655
656    def __repr__(self):
657        return "%s%s%s" % (self.p,self.b,self.n)
[488]658###)
659
[47]660class ScratchcardPinWidget(CPSStringWidget): ###(
[22]661    """ ScratchcardPin Widget"""
[199]662    meta_type = "Scratchcard Pin Widget"
[488]663    _properties = CPSWidget._properties + (
664        {'id': 'prefix', 'type': 'string', 'mode': 'w',
665         'label': 'Prefix'},
666         {'id': 'reference', 'type': 'string', 'mode': 'w',
667         'label': 'Reference Field'},
668        )
669    prefix = ''
670    reference = ''
[502]671    def prepare(self, datastructure, **kw): ###(
[488]672        """Prepare datastructure from datamodel."""
673        datamodel = datastructure.getDataModel()
674        v = datamodel[self.fields[0]]
675        widget_id = self.getWidgetId()
[742]676        #import pdb;pdb.set_trace()
[747]677        if v and type(v) is StringType:
[990]678            try:
679                p,b,n = v.split('-')
680                v = ScratchCardPin(p,b,n)
681            except ValueError:
682                v = ScratchCardPin(v,'','')
[488]683        if v:
[742]684            p = '%s' % v.p
[488]685            b = '%s' % v.b
686            n = '%s' % v.n
687        else:
[742]688            p = self.prefix
689            if p.startswith('@'):
690                p = getattr(self,self.prefix[1:])()
[488]691            b = n = ''
[742]692            v = ScratchCardPin(p,b,n)
[488]693        datastructure[widget_id] = v
[742]694        datastructure[widget_id+'_p'] = p
[488]695        datastructure[widget_id+'_b'] = b
696        datastructure[widget_id+'_n'] = n
[1376]697    ###)
[758]698
[1169]699    def validate(self, datastructure, **kw): ###(
[22]700        """Validate datastructure and update datamodel."""
[1596]701        s_logger = logging.getLogger('Widgets.ScratchcardPinWidget.validate')
[488]702        widget_id = self.getWidgetId()
703        v = datastructure[widget_id]
[996]704        #import pdb;pdb.set_trace()
[488]705        err = 0
[742]706        prefix= self.prefix
707        if prefix.startswith('@'):
708            prefix= getattr(self,self.prefix[1:])()
[488]709        b = datastructure[widget_id+'_b'].strip()
710        n = datastructure[widget_id+'_n'].strip()
[502]711        pins = self.portal_pins
[742]712        pin = "%(prefix)s%(b)s%(n)s" % vars()
[1376]713        pin_str = "%(prefix)s-%(b)-s%(n)s" % vars()
[816]714        do = 1
[1025]715        s_id = str(self.portal_membership.getAuthenticatedMember())
[1326]716        #import pdb;pdb.set_trace()
[1343]717        if self.isStaff():
[1326]718            do = 0
719            err ='You are not a Student. PIN neither checked nor used.'
[1596]720            s_logger.info('%s tried to use scratch card %s' % (s_id,pin_str))
[1558]721        elif len(b) > 1 and b.find('-') > -1:
722            do = 0
[1596]723            err = 'PIN must not contain "-"'
724            s_logger.info('%s entered invalid PIN  containing "-"' % (s_id))
[1558]725        elif n.find('-') > -1:
726            do = 0
[1596]727            err = 'PIN must not contain "-"'
728            s_logger.info('%s entered invalid PIN  containing "-"' % (s_id))
[1376]729        elif len(n) != 10:
730            do = 0
[1596]731            err = 'Invalid PIN length %d' % len(n)
732            s_logger.info('%s entered invalid PIN with length %d' % (s_id,len(n)))
[1326]733        elif self.reference == "":
[1030]734            ref = s_id
[635]735        else:
736            ref = datastructure[self.reference]
[843]737            if datastructure.errors:
[816]738                do = 0
[1596]739                datastructure.setError(widget_id, 'errors in other data, PIN neither checked nor used')
740                s_logger.info('%s/%s entered wrong data together with PIN %s' % (s_id,ref,pin_str))
[816]741        while do:
742            ok = pins.searchAndSetRecord(pin,ref,prefix)
[1030]743            if ok < -2 or ok > 2:
744                err = 'Unknown error, please report!'
[1596]745                s_logger.info('%s/%s caused unknown error with PIN %s' % (s_id,ref,pin_str))
[1030]746                break
747            elif ok == -2:
[819]748                err = 'Service already activated but with a different PIN.'
[1596]749                s_logger.info('%s/%s repeatedly activated service but with different PIN %s' % (s_id,ref,pin_str))
[710]750                break
751            elif ok == -1:
[783]752                err = 'Invalid PIN'
[1596]753                s_logger.info('%s/%s entered invalid PIN %s' % (s_id,ref,pin_str))
[502]754                break
755            if ok == 0:
[1596]756                err = 'PIN already used'
757                s_logger.info('%s/%s entered used PIN %s' % (s_id,ref,pin_str))
[502]758                break
759            if ok >= 1:
[710]760                #import pdb;pdb.set_trace()
[635]761                if self.isStudent():
[992]762                    if self.reference == "jamb_reg_no":
[997]763                        err = "You are already logged in."
[1596]764                        s_logger.info('%s/%s checked admission with PIN %s though logged in' % (s_id,ref,pin_str))
[992]765                        break
[1082]766                    if ok == 1:
[1596]767                        s_logger.info('%s/%s successfully used PIN %s' % (s_id,ref,pin_str))
[1032]768                    else:
[1596]769                        s_logger.info('%s/%s repeatedly used PIN %s' % (s_id,ref,pin_str))
[637]770                    break
[635]771                else:
772                    student = getStudentByRegNo(self,ref)
[1596]773                    s_logger.info('%s/%s successfully used PIN %s' % (s_id,ref,pin_str))
[502]774                if student is None:
[796]775                    err = "Student not found."
[1596]776                    s_logger.info('%s not found in admission list' % (ref))
[502]777                    break
[648]778                s_id = student.getId()
[502]779                if ok == 2:
[990]780                    if self.reference == "jamb_reg_no":
781                        if hasattr(self.portal_directories.students,s_id):
782                            err = "Please login with your Student Id %s and 10-digit PIN." % s_id
[1596]783                            s_logger.info('%s/%s repeatedly checked admission with PIN %s' % (s_id,ref,pin_str))
[990]784                            break
785                        else:
[1596]786                            s_logger.info('%s/%s (non-member) repeatedly checked admission with PIN %s' % (s_id,ref,pin_str))
[990]787                    else:
[1030]788                        err = "Unknown error" % s_id
[1596]789                        s_logger.info('%s/%s repeatedly activated service with PIN %s' % (s_id,ref,pin_str))
[986]790                        break
791                try:
792                    student.getContent().makeStudentMember(s_id,password=pin[4:])
[1596]793                    s_logger.info('%s/%s has been created using PIN %s' % (s_id,ref,pin_str))
[986]794                except:
[989]795                    err = "Please login with your Student Id %s and 10-digit PIN." % s_id
[1596]796                    s_logger.info('%s/%s could not be made a member with PIN %s' % (s_id,ref,pin_str))
[986]797                    break
[502]798            break
[488]799        if err:
800            datastructure.setError(widget_id, err)
801        else:
802            datamodel = datastructure.getDataModel()
[742]803            datamodel[self.fields[0]] = ScratchCardPin(prefix,b,n)
804            datastructure[widget_id] = ScratchCardPin(prefix,b,n)
805            datastructure[widget_id+'_p'] = prefix
[488]806            datastructure[widget_id+'_b'] = b
807            datastructure[widget_id+'_n'] = n
[502]808            datastructure['s_id'] = s_id
[488]809        return not err
[444]810
[1169]811###)
812
[502]813    def render(self, mode, datastructure, **kw): ###(
[488]814        """Render in mode from datastructure."""
815        render_method = 'widget_scratch_card_pin_render'
816        meth = getattr(self, render_method, None)
817        if meth is None:
818            raise RuntimeError("Unknown Render Method %s for widget type %s"
819                               % (render_method, self.getId()))
820
821        # XXX AT: datastructure has to be set again here, in case we're in edit
822        # or create mode, because a default value has to be provided.
823        #import pdb;pdb.set_trace()
824        datamodel = datastructure.getDataModel()
825        v = datamodel[self.fields[0]]
[502]826        if v and type(v) is StringType:
[990]827            try:
828                p,b,n = v.split('-')
829                v = ScratchCardPin(p,b,n)
830            except ValueError:
[996]831                v = ScratchCardPin(self.prefix,'1',v)
832                pass
[488]833        if v:
[742]834            prefix= '%s' % v.p
[488]835            b = '%s' % v.b
836            n = '%s' % v.n
[22]837        else:
[742]838            prefix= self.prefix
839            if prefix.startswith('@'):
840                prefix= getattr(self,self.prefix[1:])()
[488]841            b = n = ''
[742]842            v = ScratchCardPin(prefix,b,n)
843        widget_id = self.getWidgetId()
844        datastructure[widget_id] = v
845        datastructure[widget_id+'_p'] = prefix
846        datastructure[widget_id+'_b'] = b
847        datastructure[widget_id+'_n'] = n
[758]848        return meth(mode=mode,
849                    datastructure=datastructure,
[488]850                    )
[523]851    ###)
[488]852
853
[22]854InitializeClass(ScratchcardPinWidget)
[199]855widgetRegistry.register(ScratchcardPinWidget)
[22]856
[47]857
858###)
859
[1169]860class WAeUPImageWidget(CPSImageWidget): ###(
[537]861    """Photo widget."""
862    meta_type = 'WAeUP Image Widget'
863
864    def render(self, mode, datastructure, **kw):
865        render_method = 'widget_waeup_image_render'
866        meth = getattr(self, render_method, None)
867        if meth is None:
868            raise RuntimeError("Unknown Render Method %s for widget type %s"
869                               % (render_method, self.getId()))
870        img_info = self.getImageInfo(datastructure)
871        return meth(mode=mode, datastructure=datastructure, **img_info)
872
[1169]873###)
[537]874
875
[1169]876
[537]877InitializeClass(WAeUPImageWidget)
878
879widgetRegistry.register(WAeUPImageWidget)
880
881
[22]882###########
883
Note: See TracBrowser for help on using the repository browser.