source: WAeUP_SRP/trunk/Widgets.py @ 1467

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

modified importReservedBeds
fixReservedBeds
added release_bed
many documentation addons for xml-files

  • Property svn:keywords set to Id
File size: 31.6 KB
RevLine 
[47]1#-*- mode: python; mode: fold -*-
[990]2# $Id: Widgets.py 1449 2007-02-20 20:23:34Z 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."""
345        logger = logging.getLogger('Secret.Validate')
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:
372                logger.info('"%(matric_no)s","mismatch", "%(value)s", "not in","%(name)s"' % vars())
373                err = 'No Name does match.'
374            else:
375                logger.info('"%(matric_no)s","found", "%(value)s", "in","%(name)s"' % vars())
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)
[1175]394        logger = logging.getLogger('MatricNo.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:
[1188]402            err = 'Invalid MatricNo String %s.' % value
[1189]403            logger.info('"%s","invalid MatricNo String"' % 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:
[1177]410                    logger.info('"%s","MatricNo not found."' % value)
[1146]411                    err = 'No Student with MatricNo %s.' % (value)
412                    continue
413                datastructure['student'] = res[0]
414                res = results(matric_no = value)
415                if len(res) < 1:
416                    err = 'No Results with MatricNo %s.' % (value)
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)
438        logger = logging.getLogger('StudentId.Validate')
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:
445            err = 'Invalid StudentId String %s.' % value
446            logger.info('"%s","invalid StudentId String"' % value)
[1449]447            datastructure['student'] = None
[1393]448        else:
449            value = value.upper()
450            res = s_cat(id = value)
451            if not res:
452                logger.info('"%s","StudentId not found."' % value)
453                err = 'No Student with StudentId %s.' % (value)
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."""
[1082]701        s_logger = logging.getLogger('Pin.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.'
[1376]720            s_logger.info('"%s","tried to use Scratchcard", "%s"' % (s_id,pin_str))
721        elif len(n) != 10:
722            do = 0
723            err = 'Invalid PIN-Number length %d' % len(n)
724            s_logger.info('"%s","Invalid PIN-Number length", "%d"' % (s_id,len(n)))
[1326]725        elif self.reference == "":
[1030]726            ref = s_id
[635]727        else:
728            ref = datastructure[self.reference]
[843]729            if datastructure.errors:
[816]730                do = 0
[977]731                datastructure.setError(widget_id, 'Errors in other data, PIN neither checked nor used.')
[1376]732                s_logger.info('"%s", "%s","entered wrong data together with pin", "%s"' % (s_id,ref,pin_str))
[816]733        while do:
734            ok = pins.searchAndSetRecord(pin,ref,prefix)
[1030]735            if ok < -2 or ok > 2:
736                err = 'Unknown error, please report!'
[1376]737                s_logger.info('"%s","%s", "caused unknown error with pin", "%s"' % (s_id,ref,pin_str))
[1030]738                break
739            elif ok == -2:
[819]740                err = 'Service already activated but with a different PIN.'
[1376]741                s_logger.info('"%s","%s", "repeatedly activated service but with different pin", "%s"' % (s_id,ref,pin_str))
[710]742                break
743            elif ok == -1:
[783]744                err = 'Invalid PIN'
[1376]745                s_logger.info('"%s","%s", "entered invalid pin", "%s"' % (s_id,ref,pin_str))
[502]746                break
747            if ok == 0:
[796]748                err = 'PIN already used.'
[1376]749                s_logger.info('"%s","%s", "entered used pin", "%s"' % (s_id,ref,pin_str))
[502]750                break
751            if ok >= 1:
[710]752                #import pdb;pdb.set_trace()
[635]753                if self.isStudent():
[992]754                    if self.reference == "jamb_reg_no":
[997]755                        err = "You are already logged in."
[1376]756                        s_logger.info('"%s","%s", "checked admission though logged in", "%s"' % (s_id,ref,pin_str))
[992]757                        break
[1082]758                    if ok == 1:
[1376]759                        s_logger.info('"%s","%s", "successfully used pin", "%s"' % (s_id,ref,pin_str))
[1032]760                    else:
[1376]761                        s_logger.info('"%s","%s", "repeatedly used pin", "%s"' % (s_id,ref,pin_str))
[637]762                    break
[635]763                else:
764                    student = getStudentByRegNo(self,ref)
[1376]765                    s_logger.info('"%s","%s","successfully used pin","%s"' % (s_id,ref,pin_str))
[502]766                if student is None:
[796]767                    err = "Student not found."
[1032]768                    s_logger.info('"%s","not found in admission list"' % (ref))
[502]769                    break
[648]770                s_id = student.getId()
[502]771                if ok == 2:
[990]772                    if self.reference == "jamb_reg_no":
773                        if hasattr(self.portal_directories.students,s_id):
774                            err = "Please login with your Student Id %s and 10-digit PIN." % s_id
[1376]775                            s_logger.info('"%s","%s", "repeatedly checked admission with pin", "%s"' % (s_id,ref,pin_str))
[990]776                            break
777                        else:
[1376]778                            s_logger.info('"%s","%s","(non-member) repeatedly checked admission with pin", "%s"' % (s_id,ref,pin_str))
[990]779                    else:
[1030]780                        err = "Unknown error" % s_id
[1376]781                        s_logger.info('"%s","%s", "repeatedly activated service with pin", "%s"' % (s_id,ref,pin_str))
[986]782                        break
783                try:
784                    student.getContent().makeStudentMember(s_id,password=pin[4:])
[1376]785                    s_logger.info('"%s","%s", "has been created using pin", "%s"' % (s_id,ref,pin_str))
[986]786                except:
[989]787                    err = "Please login with your Student Id %s and 10-digit PIN." % s_id
[1376]788                    s_logger.info('"%s","%s", "could not be made a member with pin", "%s"' % (s_id,ref,pin_str))
[986]789                    break
[502]790            break
[488]791        if err:
792            datastructure.setError(widget_id, err)
793        else:
794            datamodel = datastructure.getDataModel()
[742]795            datamodel[self.fields[0]] = ScratchCardPin(prefix,b,n)
796            datastructure[widget_id] = ScratchCardPin(prefix,b,n)
797            datastructure[widget_id+'_p'] = prefix
[488]798            datastructure[widget_id+'_b'] = b
799            datastructure[widget_id+'_n'] = n
[502]800            datastructure['s_id'] = s_id
[488]801        return not err
[444]802
[1169]803###)
804
[502]805    def render(self, mode, datastructure, **kw): ###(
[488]806        """Render in mode from datastructure."""
807        render_method = 'widget_scratch_card_pin_render'
808        meth = getattr(self, render_method, None)
809        if meth is None:
810            raise RuntimeError("Unknown Render Method %s for widget type %s"
811                               % (render_method, self.getId()))
812
813        # XXX AT: datastructure has to be set again here, in case we're in edit
814        # or create mode, because a default value has to be provided.
815        #import pdb;pdb.set_trace()
816        datamodel = datastructure.getDataModel()
817        v = datamodel[self.fields[0]]
[502]818        if v and type(v) is StringType:
[990]819            try:
820                p,b,n = v.split('-')
821                v = ScratchCardPin(p,b,n)
822            except ValueError:
[996]823                v = ScratchCardPin(self.prefix,'1',v)
824                pass
[488]825        if v:
[742]826            prefix= '%s' % v.p
[488]827            b = '%s' % v.b
828            n = '%s' % v.n
[22]829        else:
[742]830            prefix= self.prefix
831            if prefix.startswith('@'):
832                prefix= getattr(self,self.prefix[1:])()
[488]833            b = n = ''
[742]834            v = ScratchCardPin(prefix,b,n)
835        widget_id = self.getWidgetId()
836        datastructure[widget_id] = v
837        datastructure[widget_id+'_p'] = prefix
838        datastructure[widget_id+'_b'] = b
839        datastructure[widget_id+'_n'] = n
[758]840        return meth(mode=mode,
841                    datastructure=datastructure,
[488]842                    )
[523]843    ###)
[488]844
845
[22]846InitializeClass(ScratchcardPinWidget)
[199]847widgetRegistry.register(ScratchcardPinWidget)
[22]848
[47]849
850###)
851
[1169]852class WAeUPImageWidget(CPSImageWidget): ###(
[537]853    """Photo widget."""
854    meta_type = 'WAeUP Image Widget'
855
856    def render(self, mode, datastructure, **kw):
857        render_method = 'widget_waeup_image_render'
858        meth = getattr(self, render_method, None)
859        if meth is None:
860            raise RuntimeError("Unknown Render Method %s for widget type %s"
861                               % (render_method, self.getId()))
862        img_info = self.getImageInfo(datastructure)
863        return meth(mode=mode, datastructure=datastructure, **img_info)
864
[1169]865###)
[537]866
867
[1169]868
[537]869InitializeClass(WAeUPImageWidget)
870
871widgetRegistry.register(WAeUPImageWidget)
872
873
[22]874###########
875
Note: See TracBrowser for help on using the repository browser.