source: WAeUP_SRP/trunk/Widgets.py @ 1757

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

make it work for display session results

  • Property svn:keywords set to Id
File size: 32.6 KB
RevLine 
[47]1#-*- mode: python; mode: fold -*-
[990]2# $Id: Widgets.py 1748 2007-05-07 21:17:31Z 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
[1747]16from Products.WAeUP_SRP.Academics import makeCertificateCode
[22]17from re import compile
[952]18import logging
[22]19
[952]20#from zLOG import LOG, DEBUG
[22]21
[295]22class CPSSelectWidgetForRecord(CPSSelectWidget): ###(
23    """Select widget. with record names"""
24    meta_type = 'Select Widget for Records'
25
26    field_types = ('CPS String Field',)
27    field_inits = ({'is_searchabletext': 1,},)
28
29    _properties = CPSSelectWidget._properties + (
30        {'id': 'record_id', 'type': 'string', 'mode': 'w',
31         'label': 'Record Id', 'is_required' : 1},
32        )
33
34    def render(self, mode, datastructure, **kw):
35        """Render in mode from datastructure."""
36        value = datastructure[self.getWidgetId()]
37        vocabulary = self._getVocabulary(datastructure)
38        portal = getToolByName(self, 'portal_url').getPortalObject()
39        cpsmcat = portal.translation_service
40        if mode == 'view':
41            if self.translated:
42                return escape(cpsmcat(vocabulary.getMsgid(value, value)).encode('ISO-8859-15', 'ignore'))
43            else:
44                return escape(vocabulary.get(value, value))
45        elif mode == 'edit':
46            html_widget_id = self.getHtmlWidgetId()
[444]47            res = renderHtmlTag('select',
48                                name='%s.%s:records' % (self.record_id,html_widget_id),
[295]49                                id=html_widget_id)
50            in_selection = 0
51            for k, v in vocabulary.items():
52                if self.translated:
53                    kw = {'value': k,
54                          'contents': cpsmcat(vocabulary.getMsgid(k, k)).encode('ISO-8859-15', 'ignore')
55                          }
56                else:
57                    kw = {'value': k, 'contents': v}
58                if value == k:
59                    kw['selected'] = 'selected'
60                    in_selection = 1
61                res += renderHtmlTag('option', **kw)
62            if value and not in_selection:
63                kw = {'value': value, 'contents': 'invalid: '+ str(value),
64                      'selected': 'selected'}
65                res += renderHtmlTag('option', **kw)
66            res += '</select>'
67            return res
68        raise RuntimeError('unknown mode %s' % mode)
69
70InitializeClass(CPSSelectWidgetForRecord)
71
72widgetRegistry.register(CPSSelectWidgetForRecord)
73
74###)
75
[373]76class CPSStringWidgetForRecord(CPSStringWidget): ###(
[295]77    """String widget."""
78    meta_type = 'String Widget For Record'
79
80    field_types = ('CPS String Field',)
81    field_inits = ({'is_searchabletext': 1,},)
82    _properties = CPSStringWidget._properties + (
83        {'id': 'record_id', 'type': 'string', 'mode': 'w',
84         'label': 'Record Id', 'is_required' : 1},
85        )
86
87    def render(self, mode, datastructure, **kw):
88        """Render in mode from datastructure."""
89        value = datastructure[self.getWidgetId()]
90        if mode == 'view':
91            return escape(value)
92        elif mode == 'edit':
93            # XXX TODO should use an other name than kw !
94            # XXX change this everywhere
95            html_widget_id = self.getHtmlWidgetId()
96            kw = {'type': 'text',
97                  'id'  : html_widget_id,
[444]98                  'name': '%s.%s:records' % (self.record_id,html_widget_id),
[295]99                  'value': escape(value),
100                  'size': self.display_width,
101                  }
102            if self.size_max:
103                kw['maxlength'] = self.size_max
104            return renderHtmlTag('input', **kw)
105        raise RuntimeError('unknown mode %s' % mode)
106
107InitializeClass(CPSStringWidgetForRecord)
108
109widgetRegistry.register(CPSStringWidgetForRecord)
110
[373]111###)
112
113class CertificateCourseIdWidget(CPSStringWidget): ###(
114    """ CertificateCourseId Widget"""
115    meta_type = "CertificateCourseId Widget"
[444]116
[373]117    def validate(self, datastructure, **kw):
118        """Validate datastructure and update datamodel."""
[444]119
[373]120        valid = CPSStringWidget.validate(self, datastructure, **kw)
121        if not valid:
122            return 0
123        else:
124            widget_id = self.getWidgetId()
125            value = datastructure[widget_id].upper()
126            err = 0
127            c_ids = [c.id for c in self.portal_catalog({'meta_type': "Course"})]
[381]128            if hasattr(self.aq_parent,value):
[444]129                err = 'Course %s already exists' % (value)
[381]130            elif value not in c_ids:
[444]131                err = 'Course %s does not exist' % (value)
[373]132            if err:
133                datastructure.setError(widget_id, err)
134            else:
135                datamodel = datastructure.getDataModel()
136                datamodel[self.fields[0]] = value
[444]137
[373]138            return not err
139
140InitializeClass(CertificateCourseIdWidget)
141
142widgetRegistry.register(CertificateCourseIdWidget)
[551]143###)
[373]144
[551]145class CourseIdWidget(CPSStringWidget): ###(
146    """ CourseId Widget"""
147    meta_type = "CourseId Widget"
148
149    def validate(self, datastructure, **kw):
150        """Validate datastructure and update datamodel."""
151
152        valid = CPSStringWidget.validate(self, datastructure, **kw)
153        if not valid:
154            return 0
155        else:
156            widget_id = self.getWidgetId()
157            value = datastructure[widget_id].upper()
158            err = 0
159            res = self.portal_catalog(meta_type= "Course",id = value)
160            if len(res) > 0:
161                err = 'Course %s already exists' % (value)
162            if err:
163                datastructure.setError(widget_id, err)
164            else:
165                datamodel = datastructure.getDataModel()
166                datamodel[self.fields[0]] = value
167
168            return not err
169
170InitializeClass(CourseIdWidget)
171
172widgetRegistry.register(CourseIdWidget)
173
174
[373]175###)
176
[714]177class WAeUPReservedRoomsWidget(CPSStringWidget): ###(
178    """ WAeUPReservedRooms Widget"""
179    meta_type = "WAeUPReservedRooms Widget"
180
181    def validate(self, datastructure, **kw):
182        """Validate datastructure and update datamodel."""
183        import re
184        valid = CPSStringWidget.validate(self, datastructure, **kw)
185        if not valid:
186            return 0
187        else:
188            widget_id = self.getWidgetId()
189            value = datastructure[widget_id]
190            err = 0
191            try:
[926]192                reserved = [(r.split('/')[0],int(r.split('/')[1])) for r in re.split(',|\.| ',value)
[714]193                                     if r]
[1038]194            except (ValueError,IndexError),msg:
[714]195                err = str(msg)
196            if err:
197                datastructure.setError(widget_id, err)
198            else:
199                datamodel = datastructure.getDataModel()
200                datamodel[self.fields[0]] = value
201            return not err
202
203InitializeClass(WAeUPReservedRoomsWidget)
204
205widgetRegistry.register(WAeUPReservedRoomsWidget)
206###)
207
[388]208class WAeUPIdWidget(CPSStringWidget): ###(
209    """ WAeUPId Widget"""
210    meta_type = "WAeUPId Widget"
[444]211
[388]212    def validate(self, datastructure, **kw):
213        """Validate datastructure and update datamodel."""
[444]214
[388]215        valid = CPSStringWidget.validate(self, datastructure, **kw)
[422]216        id_pat_str = r"\S"
217        inv_id_pat = compile(r"^%s$" % id_pat_str)
[388]218        if not valid:
219            return 0
220        else:
[586]221            portal_type_query = {'query':['Faculty',
222                                          'Department',
223                                          'Course',
224                                          'Certificate',
225                                          'CertificateCourse',]}
[388]226            widget_id = self.getWidgetId()
227            value = datastructure[widget_id].upper()
228            err = 0
[440]229            if len(value.split()) > 1:
[783]230                err = 'Invalid Id, Id contains space(s).'
[586]231            elif self.portal_catalog(portal_type=portal_type_query,id=value):
[1718]232                brain = self.portal_catalog(portal_type=portal_type_query,id=value)[0]
233                err = 'An %s object with the Id %s already exists at %s'\
234                      % (brain.portal_type,value,brain.getPath())
[388]235            if err:
236                datastructure.setError(widget_id, err)
237            else:
238                datamodel = datastructure.getDataModel()
239                datamodel[self.fields[0]] = value
[444]240
[388]241            return not err
242
243InitializeClass(WAeUPIdWidget)
244
245widgetRegistry.register(WAeUPIdWidget)
246
247
248###)
249
[1025]250class StudyCourseWidget(CPSStringWidget): ###(
251    """ StudyCourse Widget"""
252    meta_type = "StudyCourse Widget"
253
254    def validate(self, datastructure, **kw):
255        """Validate datastructure and update datamodel."""
256        #from Products.zdb import set_trace
257        #set_trace()
[1747]258##        valid = CPSStringWidget.validate(self, datastructure, **kw)
259##        if not valid:
260##            return 0
261        widget_id = self.getWidgetId()
262        value = makeCertificateCode(datastructure[widget_id]).upper()
[1025]263        id_pat_str = r"\S"
264        inv_id_pat = compile(r"^%s$" % id_pat_str)
[1747]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)
[1025]272        else:
[1747]273            datamodel = datastructure.getDataModel()
274            datamodel[self.fields[0]] = value
275        return not err
[1025]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"
[1747]344    matric_no_catalog = 'returning_import'
[1175]345    check_fields = ("Firstname", "Middlename","Lastname")
346    def validate(self, datastructure, **kw):
347        """Validate datastructure and update datamodel."""
[1571]348        logger = logging.getLogger('Widgets.SecretWidget.validate')
[1175]349        valid = CPSStringWidget.validate(self, datastructure, **kw)
350        widget_id = self.getWidgetId()
351        value = datastructure[widget_id].upper()
352        err = 0
[1189]353        record = datastructure.get(self.reference,None)
[1747]354        #import pdb;pdb.set_trace()
[1379]355        if not valid or len(value) < 2:
[1175]356            err = 'Invalid String'
[1189]357        elif not record or datastructure.errors:
[1177]358            err = 0
[1175]359        else:
360            found = False
361            cvs = []
362            for field in self.check_fields:
363                cv = getattr(record,field).upper()
[1243]364                if len(cv.split()) > 1:
365                    for splited in cv.split():
[1747]366                        cvs.append(splited.strip())
[1243]367                else:
368                    cvs.append(cv)
[1747]369            for cv in cvs:
[1175]370                if cv  == value.upper():
371                    found = True
372                    break
373            matric_no = record.matric_no
374            name = " ".join(cvs)
375            if not found:
[1573]376                logger.info('%(matric_no)s did not find %(value)s in %(name)s' % vars())
377                err = 'No name does match.'
[1175]378            else:
[1571]379                logger.info('%(matric_no)s found %(value)s in %(name)s' % vars())
[1175]380        if err:
381            datastructure.setError(widget_id, err)
382        else:
383            datamodel = datastructure.getDataModel()
384            datamodel[self.fields[0]] = value
385        return not err
386
387InitializeClass(SecretWidget)
388
389widgetRegistry.register(SecretWidget)
390###)
391
[1146]392class MatricNoWidget(CPSStringWidget): ###(
393    """ MatricNo Widget"""
394    meta_type = "MatricNo Widget"
[1747]395
396    _properties = CPSStringWidget._properties + (
397        {'id': 'matric_no_catalog', 'type': 'string', 'mode': 'w',
398         'label': 'Catalog to search for MatricNo'},
399        { 'id': 'results_catalog', 'type': 'string', 'mode': 'w',
400         'label': 'Results Catalog'},
401         )
402    matric_no_catalog = "" #the catalog to search for matric_no
[1748]403    results_catalog = "results_import" #results catalog
[1747]404
[1146]405    def validate(self, datastructure, **kw):
406        """Validate datastructure and update datamodel."""
[1747]407        #import pdb;pdb.set_trace()
[1146]408        valid = CPSStringWidget.validate(self, datastructure, **kw)
[1571]409        logger = logging.getLogger('Widgets.MatricNoWidget.validate')
[1747]410        returning = getattr(self,self.matric_no_catalog)
411        results = getattr(self,self.results_catalog,None)
[1146]412        err = 0
[1189]413        widget_id = self.getWidgetId()
414        value = datastructure[widget_id]
415        if not valid or not value:
[1571]416            err = 'Invalid matric_no string %s.' % value
[1573]417            logger.info('Invalid matric_no string %s' % value)
[1146]418        else:
[1189]419            value = value.upper()
[1177]420            datastructure['student'] = None
[1146]421            while not err:
[1151]422                res = returning(matric_no = value)
[1146]423                if len(res) < 1:
[1573]424                    logger.info('matric_no %s not found' % value)
425                    err = 'No student with matric_no %s.' % (value)
[1747]426                    break
[1146]427                datastructure['student'] = res[0]
[1747]428                if results is not None:
429                    res = results(matric_no = value)
430                    if len(res) < 1:
431                        err = 'No results with matric_no %s.' % (value)
432                        continue
433                    datastructure['results'] = res
[1146]434                break
[1189]435        if err:
436            datastructure.setError(widget_id, err)
437        else:
438            datamodel = datastructure.getDataModel()
439            datamodel[self.fields[0]] = value
440        return not err
[1146]441
442InitializeClass(MatricNoWidget)
443
444widgetRegistry.register(MatricNoWidget)
445###)
446
[1393]447class StudentIdWidget(CPSStringWidget): ###(
448    """ StudentId Widget"""
449    meta_type = "StudentId Widget"
450    def validate(self, datastructure, **kw):
451        """Validate datastructure and update datamodel."""
452        valid = CPSStringWidget.validate(self, datastructure, **kw)
[1571]453        logger = logging.getLogger('Widgets.StudentIdWidget.validate')
[1393]454        #import pdb;pdb.set_trace()
455        s_cat = self.students_catalog
456        err = 0
457        widget_id = self.getWidgetId()
458        value = datastructure[widget_id]
459        if not valid or not value:
[1571]460            err = 'Invalid id string %s.' % value
[1573]461            logger.info('Invalid id string %s' % value)
[1449]462            datastructure['student'] = None
[1393]463        else:
464            value = value.upper()
465            res = s_cat(id = value)
466            if not res:
[1573]467                logger.info('Student id %s not found' % value)
468                err = 'No student with id %s.' % (value)
[1393]469                datastructure['student'] = None
470            else:
471                datastructure['student'] = res[0]
472        if err:
473            datastructure.setError(widget_id, err)
474        else:
475            datamodel = datastructure.getDataModel()
476            datamodel[self.fields[0]] = value
477        return not err
478
479InitializeClass(StudentIdWidget)
480
481widgetRegistry.register(StudentIdWidget)
482###)
483
[1146]484class WAeUPMultilineResultsWidget(CPSStringWidget): ###(
485    """ WAeUPMultilineResults Widget"""
486    meta_type = "WAeUp Multiline Results Widget"
487    _properties = CPSWidget._properties + (
488        {'id': 'nr_of_lines', 'type': 'int', 'mode': 'w',
489         'label': 'Nr of Lines'},
490         )
491    nr_of_lines = 5
492    def prepare(self, datastructure, **kw): ###(
493        """Prepare datastructure from datamodel."""
494        datamodel = datastructure.getDataModel()
495        #import pdb;pdb.set_trace()
496        widget_id = self.getWidgetId()
497        v = datamodel[self.fields[0]]
498        if type(v) is ListType and v:
499            nr_results = len(v)
500        else:
501            v = []
502            nr_results = 0
503        count = 1
504        for s,g in v:
505            wid = "%s%02d"% (widget_id,count)
506            datastructure[wid+'_s'] = s
507            datastructure[wid+'_g'] = g
508            count += 1
509        if nr_results < self.nr_of_lines:
510            for line in range(nr_results,self.nr_of_lines):
511                v.append(('',''))
512                wid = "%s%02d"% (widget_id,line)
513                datastructure[wid+'_s'] = ''
514                datastructure[wid+'_g'] = ''
515        datastructure[widget_id] = v
516        datastructure[widget_id+'_s'] = ''
517        datastructure[widget_id+'_g'] = ''
518    ###)
519
520    def validate(self, datastructure, **kw): ###(
521        """Validate datastructure and update datamodel."""
522        #import pdb;pdb.set_trace()
523        widget_id = self.getWidgetId()
524        err = 0
525        lines = []
526        for line in range(1,30):
527            wid = "%s%02d"% (widget_id,line)
528            if not datastructure.has_key(wid+'_s'):
529                break
530            lines.append((datastructure[wid+'_s'].strip(),
531                         datastructure[wid+'_g'].strip()))
[1155]532
[1146]533        s = datastructure[widget_id+'_s'].strip()
534        g = datastructure[widget_id+'_g'].strip()
535        if s and g:
536            lines.append((s,g))
537        active = []
538        for s,g in lines:
539            if g != "":
540                active.append((s,g))
541        if err:
542            datastructure.setError(widget_id, err)
543        else:
544            datamodel = datastructure.getDataModel()
545            datamodel[self.fields[0]] = active
546        return not err
547    ###)
548
549    def render(self, mode, datastructure, **kw): ###(
550        """Render in mode from datastructure."""
551        render_method = 'widget_waeup_multiline_result_render'
552        meth = getattr(self, render_method, None)
553        if meth is None:
554            raise RuntimeError("Unknown Render Method %s for widget type %s"
555                               % (render_method, self.getId()))
556        #import pdb;pdb.set_trace()
557        datamodel = datastructure.getDataModel()
558        widget_id = self.getWidgetId()
559        lines = datamodel[self.fields[0]]
560        if len(lines) < self.nr_of_lines:
561            for line in range(len(lines),self.nr_of_lines + 1):
562                lines.append(('',''))
563        datastructure[widget_id] = lines
564        datastructure[widget_id+'_s'] = ''
565        datastructure[widget_id+'_g'] = ''
566##        count = 1
567##        for s,g in v:
568##            wid = "%s%02d"% (widget_id,count)
569##            count += 1
570        return meth(mode=mode,
571                    datastructure=datastructure,
572                    )
573    ###)
574
575
576InitializeClass(WAeUPMultilineResultsWidget)
577widgetRegistry.register(WAeUPMultilineResultsWidget)
578###)
579
[794]580class WAeUPResultsWidget(CPSStringWidget): ###(
581    """ WAeUPResults Widget"""
582    meta_type = "WAeUp Results Widget"
583
584    def prepare(self, datastructure, **kw): ###(
585        """Prepare datastructure from datamodel."""
586        datamodel = datastructure.getDataModel()
587        v = datamodel[self.fields[0]]
588        #import pdb;pdb.set_trace()
589        widget_id = self.getWidgetId()
[807]590        datastructure[widget_id] = v
[794]591        datastructure[widget_id+'_s'] = ''
592        datastructure[widget_id+'_g'] = ''
593    ###)
594
595    def validate(self, datastructure, **kw): ###(
596        """Validate datastructure and update datamodel."""
[807]597        #import pdb;pdb.set_trace()
[794]598        widget_id = self.getWidgetId()
599        v = datastructure[widget_id]
600        err = 0
601        s = datastructure[widget_id+'_s'].strip()
602        g = datastructure[widget_id+'_g'].strip()
[807]603        while 1:
604            if not s and g:
605                err = "no subject grad for subject %s " % s
606                break
607            i = 0
608            done = False
609            for sv,gv in v:
610                if sv == s:
611                    done = True
612                    if not g:
613                        v.pop(i)
614                        break
615                    v[i] = (s,g)
616                    break
617                i += 1
618            if done:
619                break
620            if s and g:
621                v.append((s,g))
622            break
[794]623        if err:
624            datastructure.setError(widget_id, err)
625        else:
626            datamodel = datastructure.getDataModel()
627            datamodel[self.fields[0]] = v
628            datastructure[widget_id+'_s'] = s
629            datastructure[widget_id+'_g'] = g
630        return not err
631    ###)
632
633    def render(self, mode, datastructure, **kw): ###(
634        """Render in mode from datastructure."""
635        render_method = 'widget_waeup_result_render'
636        meth = getattr(self, render_method, None)
637        if meth is None:
638            raise RuntimeError("Unknown Render Method %s for widget type %s"
639                               % (render_method, self.getId()))
640        #import pdb;pdb.set_trace()
641        datamodel = datastructure.getDataModel()
642        widget_id = self.getWidgetId()
643        datastructure[widget_id+'_s'] = ''
644        datastructure[widget_id+'_g'] = ''
645        return meth(mode=mode,
646                    datastructure=datastructure,
647                    )
648    ###)
649
650
651InitializeClass(WAeUPResultsWidget)
652widgetRegistry.register(WAeUPResultsWidget)
653###)
654
[488]655class ScratchCardPin: ###(
656    """the ScratchCardPin"""
657    def __init__(self,prefix,batch_no,number):
[990]658        if not batch_no and not number:
659            s = prefix
[996]660            if len(s) > 3:
[990]661                prefix,batch_no,number = s[:3],s[3:-10],s[-10:]
662            else:
[996]663                prefix,batch_no,number = s,'',''
[488]664        self.p = prefix
665        self.b = batch_no
666        self.n = number
667
668    def __str__(self):
669        return "%s-%s-%s" % (self.p,self.b,self.n)
[1146]670
671    def __repr__(self):
672        return "%s%s%s" % (self.p,self.b,self.n)
[488]673###)
674
[47]675class ScratchcardPinWidget(CPSStringWidget): ###(
[22]676    """ ScratchcardPin Widget"""
[199]677    meta_type = "Scratchcard Pin Widget"
[488]678    _properties = CPSWidget._properties + (
679        {'id': 'prefix', 'type': 'string', 'mode': 'w',
680         'label': 'Prefix'},
681         {'id': 'reference', 'type': 'string', 'mode': 'w',
682         'label': 'Reference Field'},
683        )
684    prefix = ''
685    reference = ''
[502]686    def prepare(self, datastructure, **kw): ###(
[488]687        """Prepare datastructure from datamodel."""
688        datamodel = datastructure.getDataModel()
689        v = datamodel[self.fields[0]]
690        widget_id = self.getWidgetId()
[742]691        #import pdb;pdb.set_trace()
[747]692        if v and type(v) is StringType:
[990]693            try:
694                p,b,n = v.split('-')
695                v = ScratchCardPin(p,b,n)
696            except ValueError:
697                v = ScratchCardPin(v,'','')
[488]698        if v:
[742]699            p = '%s' % v.p
[488]700            b = '%s' % v.b
701            n = '%s' % v.n
702        else:
[742]703            p = self.prefix
704            if p.startswith('@'):
705                p = getattr(self,self.prefix[1:])()
[488]706            b = n = ''
[742]707            v = ScratchCardPin(p,b,n)
[488]708        datastructure[widget_id] = v
[742]709        datastructure[widget_id+'_p'] = p
[488]710        datastructure[widget_id+'_b'] = b
711        datastructure[widget_id+'_n'] = n
[1376]712    ###)
[758]713
[1169]714    def validate(self, datastructure, **kw): ###(
[22]715        """Validate datastructure and update datamodel."""
[1571]716        s_logger = logging.getLogger('Widgets.ScratchcardPinWidget.validate')
[488]717        widget_id = self.getWidgetId()
718        v = datastructure[widget_id]
[996]719        #import pdb;pdb.set_trace()
[488]720        err = 0
[742]721        prefix= self.prefix
722        if prefix.startswith('@'):
723            prefix= getattr(self,self.prefix[1:])()
[488]724        b = datastructure[widget_id+'_b'].strip()
725        n = datastructure[widget_id+'_n'].strip()
[502]726        pins = self.portal_pins
[742]727        pin = "%(prefix)s%(b)s%(n)s" % vars()
[1376]728        pin_str = "%(prefix)s-%(b)-s%(n)s" % vars()
[816]729        do = 1
[1025]730        s_id = str(self.portal_membership.getAuthenticatedMember())
[1326]731        #import pdb;pdb.set_trace()
[1343]732        if self.isStaff():
[1326]733            do = 0
734            err ='You are not a Student. PIN neither checked nor used.'
[1571]735            s_logger.info('%s tried to use scratch card %s' % (s_id,pin_str))
[1557]736        elif len(b) > 1 and b.find('-') > -1:
737            do = 0
[1573]738            err = 'PIN must not contain "-"'
739            s_logger.info('%s entered invalid PIN  containing "-"' % (s_id))
[1557]740        elif n.find('-') > -1:
741            do = 0
[1573]742            err = 'PIN must not contain "-"'
743            s_logger.info('%s entered invalid PIN  containing "-"' % (s_id))
[1376]744        elif len(n) != 10:
745            do = 0
[1573]746            err = 'Invalid PIN length %d' % len(n)
747            s_logger.info('%s entered invalid PIN with length %d' % (s_id,len(n)))
[1326]748        elif self.reference == "":
[1030]749            ref = s_id
[635]750        else:
751            ref = datastructure[self.reference]
[843]752            if datastructure.errors:
[816]753                do = 0
[1571]754                datastructure.setError(widget_id, 'errors in other data, PIN neither checked nor used')
755                s_logger.info('%s/%s entered wrong data together with PIN %s' % (s_id,ref,pin_str))
[816]756        while do:
757            ok = pins.searchAndSetRecord(pin,ref,prefix)
[1030]758            if ok < -2 or ok > 2:
759                err = 'Unknown error, please report!'
[1571]760                s_logger.info('%s/%s caused unknown error with PIN %s' % (s_id,ref,pin_str))
[1030]761                break
762            elif ok == -2:
[819]763                err = 'Service already activated but with a different PIN.'
[1571]764                s_logger.info('%s/%s repeatedly activated service but with different PIN %s' % (s_id,ref,pin_str))
[710]765                break
766            elif ok == -1:
[783]767                err = 'Invalid PIN'
[1571]768                s_logger.info('%s/%s entered invalid PIN %s' % (s_id,ref,pin_str))
[502]769                break
770            if ok == 0:
[1571]771                err = 'PIN already used'
772                s_logger.info('%s/%s entered used PIN %s' % (s_id,ref,pin_str))
[502]773                break
774            if ok >= 1:
[710]775                #import pdb;pdb.set_trace()
[635]776                if self.isStudent():
[992]777                    if self.reference == "jamb_reg_no":
[997]778                        err = "You are already logged in."
[1573]779                        s_logger.info('%s/%s checked admission with PIN %s though logged in' % (s_id,ref,pin_str))
[992]780                        break
[1082]781                    if ok == 1:
[1571]782                        s_logger.info('%s/%s successfully used PIN %s' % (s_id,ref,pin_str))
[1032]783                    else:
[1571]784                        s_logger.info('%s/%s repeatedly used PIN %s' % (s_id,ref,pin_str))
[637]785                    break
[635]786                else:
787                    student = getStudentByRegNo(self,ref)
[1571]788                    s_logger.info('%s/%s successfully used PIN %s' % (s_id,ref,pin_str))
[502]789                if student is None:
[796]790                    err = "Student not found."
[1571]791                    s_logger.info('%s not found in admission list' % (ref))
[502]792                    break
[648]793                s_id = student.getId()
[502]794                if ok == 2:
[990]795                    if self.reference == "jamb_reg_no":
796                        if hasattr(self.portal_directories.students,s_id):
797                            err = "Please login with your Student Id %s and 10-digit PIN." % s_id
[1571]798                            s_logger.info('%s/%s repeatedly checked admission with PIN %s' % (s_id,ref,pin_str))
[990]799                            break
800                        else:
[1571]801                            s_logger.info('%s/%s (non-member) repeatedly checked admission with PIN %s' % (s_id,ref,pin_str))
[990]802                    else:
[1030]803                        err = "Unknown error" % s_id
[1571]804                        s_logger.info('%s/%s repeatedly activated service with PIN %s' % (s_id,ref,pin_str))
[986]805                        break
806                try:
807                    student.getContent().makeStudentMember(s_id,password=pin[4:])
[1571]808                    s_logger.info('%s/%s has been created using PIN %s' % (s_id,ref,pin_str))
[986]809                except:
[989]810                    err = "Please login with your Student Id %s and 10-digit PIN." % s_id
[1571]811                    s_logger.info('%s/%s could not be made a member with PIN %s' % (s_id,ref,pin_str))
[986]812                    break
[502]813            break
[488]814        if err:
815            datastructure.setError(widget_id, err)
816        else:
817            datamodel = datastructure.getDataModel()
[742]818            datamodel[self.fields[0]] = ScratchCardPin(prefix,b,n)
819            datastructure[widget_id] = ScratchCardPin(prefix,b,n)
820            datastructure[widget_id+'_p'] = prefix
[488]821            datastructure[widget_id+'_b'] = b
822            datastructure[widget_id+'_n'] = n
[502]823            datastructure['s_id'] = s_id
[488]824        return not err
[444]825
[1169]826###)
827
[502]828    def render(self, mode, datastructure, **kw): ###(
[488]829        """Render in mode from datastructure."""
830        render_method = 'widget_scratch_card_pin_render'
831        meth = getattr(self, render_method, None)
832        if meth is None:
833            raise RuntimeError("Unknown Render Method %s for widget type %s"
834                               % (render_method, self.getId()))
835
836        # XXX AT: datastructure has to be set again here, in case we're in edit
837        # or create mode, because a default value has to be provided.
838        #import pdb;pdb.set_trace()
839        datamodel = datastructure.getDataModel()
840        v = datamodel[self.fields[0]]
[502]841        if v and type(v) is StringType:
[990]842            try:
843                p,b,n = v.split('-')
844                v = ScratchCardPin(p,b,n)
845            except ValueError:
[996]846                v = ScratchCardPin(self.prefix,'1',v)
847                pass
[488]848        if v:
[742]849            prefix= '%s' % v.p
[488]850            b = '%s' % v.b
851            n = '%s' % v.n
[22]852        else:
[742]853            prefix= self.prefix
854            if prefix.startswith('@'):
855                prefix= getattr(self,self.prefix[1:])()
[488]856            b = n = ''
[742]857            v = ScratchCardPin(prefix,b,n)
858        widget_id = self.getWidgetId()
859        datastructure[widget_id] = v
860        datastructure[widget_id+'_p'] = prefix
861        datastructure[widget_id+'_b'] = b
862        datastructure[widget_id+'_n'] = n
[758]863        return meth(mode=mode,
864                    datastructure=datastructure,
[488]865                    )
[523]866    ###)
[488]867
868
[22]869InitializeClass(ScratchcardPinWidget)
[199]870widgetRegistry.register(ScratchcardPinWidget)
[22]871
[47]872
873###)
874
[1169]875class WAeUPImageWidget(CPSImageWidget): ###(
[537]876    """Photo widget."""
877    meta_type = 'WAeUP Image Widget'
878
879    def render(self, mode, datastructure, **kw):
880        render_method = 'widget_waeup_image_render'
881        meth = getattr(self, render_method, None)
882        if meth is None:
883            raise RuntimeError("Unknown Render Method %s for widget type %s"
884                               % (render_method, self.getId()))
885        img_info = self.getImageInfo(datastructure)
886        return meth(mode=mode, datastructure=datastructure, **img_info)
887
[1169]888###)
[537]889
890
[1169]891
[537]892InitializeClass(WAeUPImageWidget)
893
894widgetRegistry.register(WAeUPImageWidget)
895
896
[22]897###########
898
Note: See TracBrowser for help on using the repository browser.