source: WAeUP_SRP/trunk/Widgets.py @ 1188

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

fix for problem if an invalid string is given for matric_no

  • Property svn:keywords set to Id
File size: 30.8 KB
Line 
1#-*- mode: python; mode: fold -*-
2# $Id: Widgets.py 1188 2007-01-03 18:22:02Z joachim $
3from cgi import escape
4from types import *
5from Globals import InitializeClass
6##from Products.CPSSchemas.Widget import CPSWidgetType
7from Products.CMFCore.utils import getToolByName
8from Products.CPSSchemas.BasicWidgets import CPSWidget, CPSStringWidget, CPSEmailWidget,CPSImageWidget
9from Products.CPSSchemas.BasicWidgets import renderHtmlTag,CPSSelectWidget, CPSStringWidget
10from Products.CPSSchemas.ExtendedWidgets import CPSDateTimeWidget
11from Products.CPSSchemas.Widget import widgetRegistry
12##from Products.CPSSchemas.WidgetTypesTool import WidgetTypeRegistry
13from DateTime.DateTime import DateTime
14from AccessControl import getSecurityManager
15from Products.WAeUP_SRP.Students import getStudentByRegNo
16from re import compile
17import logging
18
19#from zLOG import LOG, DEBUG
20
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()
46            res = renderHtmlTag('select',
47                                name='%s.%s:records' % (self.record_id,html_widget_id),
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
75class CPSStringWidgetForRecord(CPSStringWidget): ###(
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,
97                  'name': '%s.%s:records' % (self.record_id,html_widget_id),
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
110###)
111
112class CertificateCourseIdWidget(CPSStringWidget): ###(
113    """ CertificateCourseId Widget"""
114    meta_type = "CertificateCourseId Widget"
115
116    def validate(self, datastructure, **kw):
117        """Validate datastructure and update datamodel."""
118
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"})]
127            if hasattr(self.aq_parent,value):
128                err = 'Course %s already exists' % (value)
129            elif value not in c_ids:
130                err = 'Course %s does not exist' % (value)
131            if err:
132                datastructure.setError(widget_id, err)
133            else:
134                datamodel = datastructure.getDataModel()
135                datamodel[self.fields[0]] = value
136
137            return not err
138
139InitializeClass(CertificateCourseIdWidget)
140
141widgetRegistry.register(CertificateCourseIdWidget)
142###)
143
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
174###)
175
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:
191                reserved = [(r.split('/')[0],int(r.split('/')[1])) for r in re.split(',|\.| ',value)
192                                     if r]
193            except (ValueError,IndexError),msg:
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
207###)
208
209class WAeUPIdWidget(CPSStringWidget): ###(
210    """ WAeUPId Widget"""
211    meta_type = "WAeUPId Widget"
212
213    def validate(self, datastructure, **kw):
214        """Validate datastructure and update datamodel."""
215
216        valid = CPSStringWidget.validate(self, datastructure, **kw)
217        id_pat_str = r"\S"
218        inv_id_pat = compile(r"^%s$" % id_pat_str)
219        if not valid:
220            return 0
221        else:
222            portal_type_query = {'query':['Faculty',
223                                          'Department',
224                                          'Course',
225                                          'Certificate',
226                                          'CertificateCourse',]}
227            widget_id = self.getWidgetId()
228            value = datastructure[widget_id].upper()
229            err = 0
230            if len(value.split()) > 1:
231                err = 'Invalid Id, Id contains space(s).'
232            elif self.portal_catalog(portal_type=portal_type_query,id=value):
233                err = 'An object with the Id %s already exists in the Academic Section.' % (value)
234            if err:
235                datastructure.setError(widget_id, err)
236            else:
237                datamodel = datastructure.getDataModel()
238                datamodel[self.fields[0]] = value
239
240            return not err
241
242InitializeClass(WAeUPIdWidget)
243
244widgetRegistry.register(WAeUPIdWidget)
245
246
247###)
248
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
282##class StudentIdWidget(CPSStringWidget): ###(
283##    """ StudentId Widget"""
284##    meta_type = "StudentId Widget"
285##    digits = 8
286##    digits_str = "N"*digits
287##    letters = 2
288##    letters_str = "L"*letters
289##
290##    def validate(self, datastructure, **kw):
291##        """Validate datastructure and update datamodel."""
292##
293##        valid = CPSStringWidget.validate(self, datastructure, **kw)
294##        if not valid:
295##            return 0
296##        else:
297##            widget_id = self.getWidgetId()
298##            value = datastructure[widget_id]
299##            err = 0
300##            if not (len(value) == self.digits + self.letters and value[:self.digits].isdigit() and value[self.digits:].isalpha()):
301##                err = 'Invalid Registration Number in the format: %s%s with N = Number, L = Letter' % (self.digits_str,self.letters_str)
302##            if err:
303##                datastructure.setError(widget_id, err)
304##            else:
305##                datamodel = datastructure.getDataModel()
306##                datamodel[self.fields[0]] = value
307##
308##            return not err
309##
310##InitializeClass(StudentIdWidget)
311##widgetRegistry.register(StudentIdWidget)
312##
313#####)
314
315class JambRegNoWidget(CPSStringWidget): ###(
316    """ JambRegNo Widget"""
317    meta_type = "JambRegNo Widget"
318    _properties = CPSStringWidget._properties + (
319        {'id': 'catalog', 'type': 'string', 'mode': 'w',
320         'label': 'Catalog to search'},
321         {'id': 'reference', 'type': 'string', 'mode': 'w',
322         'label': 'Reference Field'},
323         )
324    catalog = "portal_pumeresults" #the catalog to search for jamb_reg_no
325    reference = ""
326    digits = 8
327    digits_str = "N"*digits
328    letters = 2
329    letters_str = "L"*letters
330    def validate(self, datastructure, **kw):
331        """Validate datastructure and update datamodel."""
332        valid = CPSStringWidget.validate(self, datastructure, **kw)
333        #import pdb;pdb.set_trace()
334        jamb_nr_catalog = getattr(self,self.catalog)
335        widget_id = self.getWidgetId()
336        value = datastructure[widget_id].upper()
337        err = 0
338        if not valid: #or not (len(value) == self.digits + self.letters and value[:self.digits].isdigit() and value[self.digits:].isalpha()):
339            #err = 'Invalid number, the expected format is: %s%s with N = Number, L = Letter' % (self.digits_str,self.letters_str)
340            err = 'Invalid number'
341        elif self.reference == '':
342            #s = getStudentByRegNo(self,value)
343            pume = jamb_nr_catalog(jamb_reg_no = value)
344            if len(pume) < 1:
345                err = 'No Student with JAMB RegNo %s.' % (value)
346            else:
347                datastructure['pume'] = pume[0]
348        else:
349            #import pdb;pdb.set_trace()
350            record = datastructure[self.reference]
351            #jamb_reg_no = getattr(record,widget_id)
352            jamb_reg_no = record.Entryregno
353            if jamb_reg_no != value:
354                err = 'Entry Registration Nr does not match.'
355        if err:
356            datastructure.setError(widget_id, err)
357        else:
358            datamodel = datastructure.getDataModel()
359            datamodel[self.fields[0]] = value
360        return not err
361
362InitializeClass(JambRegNoWidget)
363
364widgetRegistry.register(JambRegNoWidget)
365###)
366
367class SecretWidget(CPSStringWidget): ###(
368    """ Secret Widget"""
369    meta_type = "Secret Widget"
370    _properties = CPSStringWidget._properties + (
371        {'id': 'reference', 'type': 'string', 'mode': 'w',
372         'label': 'Reference Record'},
373         {'id': 'check_fields', 'type': 'tokens', 'mode': 'w',
374         'label': 'Fields to check'},
375         )
376    reference = "student"
377    check_fields = ("Firstname", "Middlename","Lastname")
378    def validate(self, datastructure, **kw):
379        """Validate datastructure and update datamodel."""
380        logger = logging.getLogger('Secret.Validate')
381        valid = CPSStringWidget.validate(self, datastructure, **kw)
382        #import pdb;pdb.set_trace()
383        widget_id = self.getWidgetId()
384        value = datastructure[widget_id].upper()
385        err = 0
386        record = datastructure[self.reference]
387        if not valid:
388            err = 'Invalid String'
389        elif not record:
390            err = 0
391        else:
392            #import pdb;pdb.set_trace()
393            found = False
394            cvs = []
395            for field in self.check_fields:
396                cv = getattr(record,field).upper()
397                cvs.append(cv)
398                if cv  == value.upper():
399                    found = True
400                    break
401            matric_no = record.matric_no
402            name = " ".join(cvs)
403            if not found:
404                logger.info('"%(matric_no)s","mismatch", "%(value)s", "not in","%(name)s"' % vars())
405                err = 'No Name does match.'
406            else:
407                logger.info('"%(matric_no)s","found", "%(value)s", "in","%(name)s"' % vars())
408        if err:
409            datastructure.setError(widget_id, err)
410        else:
411            datamodel = datastructure.getDataModel()
412            datamodel[self.fields[0]] = value
413        return not err
414
415InitializeClass(SecretWidget)
416
417widgetRegistry.register(SecretWidget)
418###)
419
420class MatricNoWidget(CPSStringWidget): ###(
421    """ MatricNo Widget"""
422    meta_type = "MatricNo Widget"
423    def validate(self, datastructure, **kw):
424        """Validate datastructure and update datamodel."""
425        valid = CPSStringWidget.validate(self, datastructure, **kw)
426        logger = logging.getLogger('MatricNo.Validate')
427        #import pdb;pdb.set_trace()
428        returning = self.returning_import
429        results = self.results_import
430        err = 0
431        if not valid:
432            value = datastructure[widget_id]
433            err = 'Invalid MatricNo String %s.' % value
434            logger.info('"%s","invalid MatricNo String","%s"' % value)
435        else:
436            widget_id = self.getWidgetId()
437            value = datastructure[widget_id].upper()
438            datastructure['student'] = None
439            while not err:
440                res = returning(matric_no = value)
441                if len(res) < 1:
442                    logger.info('"%s","MatricNo not found."' % value)
443                    err = 'No Student with MatricNo %s.' % (value)
444                    continue
445                datastructure['student'] = res[0]
446                res = results(matric_no = value)
447                if len(res) < 1:
448                    err = 'No Results with MatricNo %s.' % (value)
449                    continue
450                datastructure['results'] = res
451                break
452            if err:
453                datastructure.setError(widget_id, err)
454            else:
455                datamodel = datastructure.getDataModel()
456                datamodel[self.fields[0]] = value
457            return not err
458
459InitializeClass(MatricNoWidget)
460
461widgetRegistry.register(MatricNoWidget)
462###)
463
464class WAeUPMultilineResultsWidget(CPSStringWidget): ###(
465    """ WAeUPMultilineResults Widget"""
466    meta_type = "WAeUp Multiline Results Widget"
467    _properties = CPSWidget._properties + (
468        {'id': 'nr_of_lines', 'type': 'int', 'mode': 'w',
469         'label': 'Nr of Lines'},
470         )
471    nr_of_lines = 5
472    def prepare(self, datastructure, **kw): ###(
473        """Prepare datastructure from datamodel."""
474        datamodel = datastructure.getDataModel()
475        #import pdb;pdb.set_trace()
476        widget_id = self.getWidgetId()
477        v = datamodel[self.fields[0]]
478        if type(v) is ListType and v:
479            nr_results = len(v)
480        else:
481            v = []
482            nr_results = 0
483        count = 1
484        for s,g in v:
485            wid = "%s%02d"% (widget_id,count)
486            datastructure[wid+'_s'] = s
487            datastructure[wid+'_g'] = g
488            count += 1
489        if nr_results < self.nr_of_lines:
490            for line in range(nr_results,self.nr_of_lines):
491                v.append(('',''))
492                wid = "%s%02d"% (widget_id,line)
493                datastructure[wid+'_s'] = ''
494                datastructure[wid+'_g'] = ''
495        datastructure[widget_id] = v
496        datastructure[widget_id+'_s'] = ''
497        datastructure[widget_id+'_g'] = ''
498    ###)
499
500    def validate(self, datastructure, **kw): ###(
501        """Validate datastructure and update datamodel."""
502        #import pdb;pdb.set_trace()
503        widget_id = self.getWidgetId()
504        err = 0
505        lines = []
506        for line in range(1,30):
507            wid = "%s%02d"% (widget_id,line)
508            if not datastructure.has_key(wid+'_s'):
509                break
510            lines.append((datastructure[wid+'_s'].strip(),
511                         datastructure[wid+'_g'].strip()))
512
513        s = datastructure[widget_id+'_s'].strip()
514        g = datastructure[widget_id+'_g'].strip()
515        if s and g:
516            lines.append((s,g))
517        active = []
518        for s,g in lines:
519            if g != "":
520                active.append((s,g))
521        if err:
522            datastructure.setError(widget_id, err)
523        else:
524            datamodel = datastructure.getDataModel()
525            datamodel[self.fields[0]] = active
526        return not err
527    ###)
528
529    def render(self, mode, datastructure, **kw): ###(
530        """Render in mode from datastructure."""
531        render_method = 'widget_waeup_multiline_result_render'
532        meth = getattr(self, render_method, None)
533        if meth is None:
534            raise RuntimeError("Unknown Render Method %s for widget type %s"
535                               % (render_method, self.getId()))
536        #import pdb;pdb.set_trace()
537        datamodel = datastructure.getDataModel()
538        widget_id = self.getWidgetId()
539        lines = datamodel[self.fields[0]]
540        if len(lines) < self.nr_of_lines:
541            for line in range(len(lines),self.nr_of_lines + 1):
542                lines.append(('',''))
543        datastructure[widget_id] = lines
544        datastructure[widget_id+'_s'] = ''
545        datastructure[widget_id+'_g'] = ''
546##        count = 1
547##        for s,g in v:
548##            wid = "%s%02d"% (widget_id,count)
549##            count += 1
550        return meth(mode=mode,
551                    datastructure=datastructure,
552                    )
553    ###)
554
555
556InitializeClass(WAeUPMultilineResultsWidget)
557widgetRegistry.register(WAeUPMultilineResultsWidget)
558###)
559
560class WAeUPResultsWidget(CPSStringWidget): ###(
561    """ WAeUPResults Widget"""
562    meta_type = "WAeUp Results Widget"
563
564    def prepare(self, datastructure, **kw): ###(
565        """Prepare datastructure from datamodel."""
566        datamodel = datastructure.getDataModel()
567        v = datamodel[self.fields[0]]
568        #import pdb;pdb.set_trace()
569        widget_id = self.getWidgetId()
570        datastructure[widget_id] = v
571        datastructure[widget_id+'_s'] = ''
572        datastructure[widget_id+'_g'] = ''
573    ###)
574
575    def validate(self, datastructure, **kw): ###(
576        """Validate datastructure and update datamodel."""
577        #import pdb;pdb.set_trace()
578        widget_id = self.getWidgetId()
579        v = datastructure[widget_id]
580        err = 0
581        s = datastructure[widget_id+'_s'].strip()
582        g = datastructure[widget_id+'_g'].strip()
583        while 1:
584            if not s and g:
585                err = "no subject grad for subject %s " % s
586                break
587            i = 0
588            done = False
589            for sv,gv in v:
590                if sv == s:
591                    done = True
592                    if not g:
593                        v.pop(i)
594                        break
595                    v[i] = (s,g)
596                    break
597                i += 1
598            if done:
599                break
600            if s and g:
601                v.append((s,g))
602            break
603        if err:
604            datastructure.setError(widget_id, err)
605        else:
606            datamodel = datastructure.getDataModel()
607            datamodel[self.fields[0]] = v
608            datastructure[widget_id+'_s'] = s
609            datastructure[widget_id+'_g'] = g
610        return not err
611    ###)
612
613    def render(self, mode, datastructure, **kw): ###(
614        """Render in mode from datastructure."""
615        render_method = 'widget_waeup_result_render'
616        meth = getattr(self, render_method, None)
617        if meth is None:
618            raise RuntimeError("Unknown Render Method %s for widget type %s"
619                               % (render_method, self.getId()))
620        #import pdb;pdb.set_trace()
621        datamodel = datastructure.getDataModel()
622        widget_id = self.getWidgetId()
623        datastructure[widget_id+'_s'] = ''
624        datastructure[widget_id+'_g'] = ''
625        return meth(mode=mode,
626                    datastructure=datastructure,
627                    )
628    ###)
629
630
631InitializeClass(WAeUPResultsWidget)
632widgetRegistry.register(WAeUPResultsWidget)
633###)
634
635class ScratchCardPin: ###(
636    """the ScratchCardPin"""
637    def __init__(self,prefix,batch_no,number):
638        if not batch_no and not number:
639            s = prefix
640            if len(s) > 3:
641                prefix,batch_no,number = s[:3],s[3:-10],s[-10:]
642            else:
643                prefix,batch_no,number = s,'',''
644        self.p = prefix
645        self.b = batch_no
646        self.n = number
647
648    def __str__(self):
649        return "%s-%s-%s" % (self.p,self.b,self.n)
650
651    def __repr__(self):
652        return "%s%s%s" % (self.p,self.b,self.n)
653###)
654
655class ScratchcardPinWidget(CPSStringWidget): ###(
656    """ ScratchcardPin Widget"""
657    meta_type = "Scratchcard Pin Widget"
658    _properties = CPSWidget._properties + (
659        {'id': 'prefix', 'type': 'string', 'mode': 'w',
660         'label': 'Prefix'},
661         {'id': 'reference', 'type': 'string', 'mode': 'w',
662         'label': 'Reference Field'},
663        )
664    prefix = ''
665    reference = ''
666    def prepare(self, datastructure, **kw): ###(
667        """Prepare datastructure from datamodel."""
668        datamodel = datastructure.getDataModel()
669        v = datamodel[self.fields[0]]
670        widget_id = self.getWidgetId()
671        #import pdb;pdb.set_trace()
672        if v and type(v) is StringType:
673            try:
674                p,b,n = v.split('-')
675                v = ScratchCardPin(p,b,n)
676            except ValueError:
677                v = ScratchCardPin(v,'','')
678        if v:
679            p = '%s' % v.p
680            b = '%s' % v.b
681            n = '%s' % v.n
682        else:
683            p = self.prefix
684            if p.startswith('@'):
685                p = getattr(self,self.prefix[1:])()
686            b = n = ''
687            v = ScratchCardPin(p,b,n)
688        datastructure[widget_id] = v
689        datastructure[widget_id+'_p'] = p
690        datastructure[widget_id+'_b'] = b
691        datastructure[widget_id+'_n'] = n
692
693###)
694
695    def validate(self, datastructure, **kw): ###(
696        """Validate datastructure and update datamodel."""
697        s_logger = logging.getLogger('Pin.Validate')
698        widget_id = self.getWidgetId()
699        v = datastructure[widget_id]
700        #import pdb;pdb.set_trace()
701        err = 0
702        prefix= self.prefix
703        if prefix.startswith('@'):
704            prefix= getattr(self,self.prefix[1:])()
705        b = datastructure[widget_id+'_b'].strip()
706        n = datastructure[widget_id+'_n'].strip()
707        pins = self.portal_pins
708        pin = "%(prefix)s%(b)s%(n)s" % vars()
709        do = 1
710        s_id = str(self.portal_membership.getAuthenticatedMember())
711        if self.reference == "":
712            ref = s_id
713        else:
714            ref = datastructure[self.reference]
715            if datastructure.errors:
716                do = 0
717                datastructure.setError(widget_id, 'Errors in other data, PIN neither checked nor used.')
718                s_logger.info('"%s", "%s","entered wrong data together with pin", "%s"' % (s_id,ref,pin))
719        while do:
720            ok = pins.searchAndSetRecord(pin,ref,prefix)
721            if ok < -2 or ok > 2:
722                err = 'Unknown error, please report!'
723                s_logger.info('"%s","%s", "caused unknown error with pin", "%s"' % (s_id,ref,pin))
724                break
725            elif ok == -2:
726                err = 'Service already activated but with a different PIN.'
727                s_logger.info('"%s","%s", "repeatedly activated service but with different pin", "%s"' % (s_id,ref,pin))
728                break
729            elif ok == -1:
730                err = 'Invalid PIN'
731                s_logger.info('"%s","%s", "entered invalid pin", "%s"' % (s_id,ref,pin))
732                break
733            if ok == 0:
734                err = 'PIN already used.'
735                s_logger.info('"%s","%s", "entered used pin", "%s"' % (s_id,ref,pin))
736                break
737            if ok >= 1:
738                #import pdb;pdb.set_trace()
739                if self.isStudent():
740                    if self.reference == "jamb_reg_no":
741                        err = "You are already logged in."
742                        s_logger.info('"%s","%s", "checked admission though logged in", "%s"' % (s_id,ref,pin))
743                        break
744                    if ok == 1:
745                        s_logger.info('"%s","%s", "successfully used pin", "%s"' % (s_id,ref,pin))
746                    else:
747                        s_logger.info('"%s","%s", "repeatedly used pin", "%s"' % (s_id,ref,pin))
748                    break
749                else:
750                    student = getStudentByRegNo(self,ref)
751                    s_logger.info('"%s","%s","successfully used pin","%s"' % (s_id,ref,pin))
752                if student is None:
753                    err = "Student not found."
754                    s_logger.info('"%s","not found in admission list"' % (ref))
755                    break
756                s_id = student.getId()
757                if ok == 2:
758                    if self.reference == "jamb_reg_no":
759                        if hasattr(self.portal_directories.students,s_id):
760                            err = "Please login with your Student Id %s and 10-digit PIN." % s_id
761                            s_logger.info('"%s","%s", "repeatedly checked admission with pin", "%s"' % (s_id,ref,pin))
762                            break
763                        else:
764                            s_logger.info('"%s","%s","(non-member) repeatedly checked admission with pin", "%s"' % (s_id,ref,pin))
765                    else:
766                        err = "Unknown error" % s_id
767                        s_logger.info('"%s","%s", "repeatedly activated service with pin", "%s"' % (s_id,ref,pin))
768                        break
769                try:
770                    student.getContent().makeStudentMember(s_id,password=pin[4:])
771                    s_logger.info('"%s","%s", "has been created using pin", "%s"' % (s_id,ref,pin))
772                except:
773                    err = "Please login with your Student Id %s and 10-digit PIN." % s_id
774                    s_logger.info('"%s","%s", "could not be made a member with pin", "%s"' % (s_id,ref,pin))
775                    break
776            break
777        if err:
778            datastructure.setError(widget_id, err)
779        else:
780            datamodel = datastructure.getDataModel()
781            datamodel[self.fields[0]] = ScratchCardPin(prefix,b,n)
782            datastructure[widget_id] = ScratchCardPin(prefix,b,n)
783            datastructure[widget_id+'_p'] = prefix
784            datastructure[widget_id+'_b'] = b
785            datastructure[widget_id+'_n'] = n
786            datastructure['s_id'] = s_id
787        return not err
788
789###)
790
791    def render(self, mode, datastructure, **kw): ###(
792        """Render in mode from datastructure."""
793        render_method = 'widget_scratch_card_pin_render'
794        meth = getattr(self, render_method, None)
795        if meth is None:
796            raise RuntimeError("Unknown Render Method %s for widget type %s"
797                               % (render_method, self.getId()))
798
799        # XXX AT: datastructure has to be set again here, in case we're in edit
800        # or create mode, because a default value has to be provided.
801        #import pdb;pdb.set_trace()
802        datamodel = datastructure.getDataModel()
803        v = datamodel[self.fields[0]]
804        if v and type(v) is StringType:
805            try:
806                p,b,n = v.split('-')
807                v = ScratchCardPin(p,b,n)
808            except ValueError:
809                v = ScratchCardPin(self.prefix,'1',v)
810                pass
811        if v:
812            prefix= '%s' % v.p
813            b = '%s' % v.b
814            n = '%s' % v.n
815        else:
816            prefix= self.prefix
817            if prefix.startswith('@'):
818                prefix= getattr(self,self.prefix[1:])()
819            b = n = ''
820            v = ScratchCardPin(prefix,b,n)
821        widget_id = self.getWidgetId()
822        datastructure[widget_id] = v
823        datastructure[widget_id+'_p'] = prefix
824        datastructure[widget_id+'_b'] = b
825        datastructure[widget_id+'_n'] = n
826        return meth(mode=mode,
827                    datastructure=datastructure,
828                    )
829    ###)
830
831
832InitializeClass(ScratchcardPinWidget)
833widgetRegistry.register(ScratchcardPinWidget)
834
835
836###)
837
838class WAeUPImageWidget(CPSImageWidget): ###(
839    """Photo widget."""
840    meta_type = 'WAeUP Image Widget'
841
842    def render(self, mode, datastructure, **kw):
843        render_method = 'widget_waeup_image_render'
844        meth = getattr(self, render_method, None)
845        if meth is None:
846            raise RuntimeError("Unknown Render Method %s for widget type %s"
847                               % (render_method, self.getId()))
848        img_info = self.getImageInfo(datastructure)
849        return meth(mode=mode, datastructure=datastructure, **img_info)
850
851###)
852
853
854
855InitializeClass(WAeUPImageWidget)
856
857widgetRegistry.register(WAeUPImageWidget)
858
859
860###########
861
Note: See TracBrowser for help on using the repository browser.