source: WAeUP_SRP/trunk/Widgets.py @ 1442

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

new method book_reserved_bed to book a reserved bed for a student

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