source: WAeUP_SRP/trunk/Widgets.py @ 1737

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

BETTER ERRORMESSAGE FOR w
better errormessage for WAeUPIdWidgeteupIdWidget

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