source: main/waeup.kofa/trunk/src/waeup/kofa/applicants/batching.py @ 17737

Last change on this file since 17737 was 17705, checked in by Henrik Bettermann, 7 months ago

Add backdoor to edit blocked applicants,

  • Property svn:keywords set to Id
File size: 19.4 KB
RevLine 
[7192]1## $Id: batching.py 17705 2024-02-27 12:09:35Z henrik $
[5321]2##
[7192]3## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann
[5321]4## This program is free software; you can redistribute it and/or modify
5## it under the terms of the GNU General Public License as published by
6## the Free Software Foundation; either version 2 of the License, or
7## (at your option) any later version.
[7192]8##
[5321]9## This program is distributed in the hope that it will be useful,
10## but WITHOUT ANY WARRANTY; without even the implied warranty of
11## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12## GNU General Public License for more details.
[7192]13##
[5321]14## You should have received a copy of the GNU General Public License
15## along with this program; if not, write to the Free Software
16## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17##
18"""Batch processing for applicants.
19"""
[10028]20import unicodecsv as csv # XXX: csv ops should move to dedicated module.
[5321]21import grok
[13873]22from time import time
[16472]23import unicodecsv
[7271]24from zope.schema import getFields
[5321]25from zope.interface import Interface
[13872]26from zope.component import queryUtility, getUtility
[8290]27from hurry.workflow.interfaces import IWorkflowState
[7268]28from zope.catalog.interfaces import ICatalog
[7811]29from waeup.kofa.interfaces import (
[15628]30    IBatchProcessor, IObjectConverter, FatalCSVError,
31    IGNORE_MARKER, DELETION_MARKER,
[13872]32    IObjectHistory, IUserAccount, DuplicationError)
[8290]33from waeup.kofa.interfaces import MessageFactory as _
[13872]34from waeup.kofa.payments.interfaces import IPayer
[7811]35from waeup.kofa.utils.batching import BatchProcessor
36from waeup.kofa.applicants.interfaces import (
[13872]37    IApplicantsContainer, IApplicant, IApplicantUpdateByRegNo,
38    IApplicantOnlinePayment)
[8336]39from waeup.kofa.applicants.workflow import  IMPORTABLE_STATES, CREATED
[5321]40
[7933]41class ApplicantsContainerProcessor(BatchProcessor):
[12869]42    """The Applicants Container Processor imports containers for applicants.
43    It does not import their content. There is nothing special about this
44    processor.
[5321]45    """
[5474]46    grok.implements(IBatchProcessor)
[5321]47    grok.provides(IBatchProcessor)
48    grok.context(Interface)
[8987]49    util_name = 'applicantscontainerprocessor'
[5321]50    grok.name(util_name)
51
[11891]52    name = _('ApplicantsContainer Processor')
[5475]53    mode = u'create'
[6251]54    iface = IApplicantsContainer
[5321]55
[6251]56    location_fields = ['code',]
[6282]57    factory_name = 'waeup.ApplicantsContainer'
[5321]58
59    def parentsExist(self, row, site):
[6251]60        return 'applicants' in site.keys()
[5321]61
62    def entryExists(self, row, site):
[6251]63        return row['code'] in site['applicants'].keys()
[5321]64
65    def getParent(self, row, site):
[6251]66        return site['applicants']
[5321]67
68    def getEntry(self, row, site):
69        if not self.entryExists(row, site):
70            return None
71        parent = self.getParent(row, site)
[6251]72        return parent.get(row['code'])
[5321]73
74    def addEntry(self, obj, row, site):
75        parent = self.getParent(row, site)
[6251]76        parent[row['code']] = obj
[5321]77        return
78
79    def delEntry(self, row, site):
80        parent = self.getParent(row, site)
[6251]81        del parent[row['code']]
[5321]82        return
[7262]83
[7933]84class ApplicantProcessor(BatchProcessor):
[12872]85    """The Applicant Processor imports application data (applicants).
[8331]86
[12869]87    In create mode `container_code` is required. If `application_number` is
88    given, an applicant with this number is created in the designated container.
89    If `application_number` is not given, a random `application_number` is
90    assigned. `applicant_id` is being determined by the system and can't be
91    imported.
[8331]92
[12869]93    In update or remove mode `container_code` and `application_number` columns
[12870]94    must not exist. The applicant object is solely localized by searching
95    the applicants catalog for `reg_number` or `applicant_id` .
[7262]96    """
97    grok.implements(IBatchProcessor)
98    grok.provides(IBatchProcessor)
99    grok.context(Interface)
[7933]100    util_name = 'applicantprocessor'
[7262]101    grok.name(util_name)
[11891]102    name = _('Applicant Processor')
[7262]103    iface = IApplicant
[8581]104    iface_byregnumber = IApplicantUpdateByRegNo
[7262]105    factory_name = 'waeup.Applicant'
106
107    mode = None
108
109    @property
[7268]110    def available_fields(self):
111        return sorted(list(set(
[8331]112            ['application_number',
[8290]113            'container_code','state','password'] + getFields(
[7268]114                self.iface).keys())))
[7262]115
[17705]116    def cheadminckHeaders(self, headerfields, mode='create'):
[8331]117        cond1 = 'container_code' in headerfields
118        cond2 = 'application_number' in headerfields
119        cond3 = 'applicant_id' in headerfields
120        cond4 = 'reg_number' in headerfields
[7268]121        if mode == 'create':
[8331]122            if not cond1:
123                raise FatalCSVError(
124                    "Need at least container_code column!")
125            if cond3:
126                raise FatalCSVError(
127                    "applicant_id can't be imported in create mode!")
[7268]128            for field in self.required_fields:
129                if not field in headerfields:
130                    raise FatalCSVError(
131                        "Need at least columns %s for import!" %
132                        ', '.join(["'%s'" % x for x in self.required_fields]))
[8331]133        if mode in ('update', 'remove'):
134            if not cond3 and not cond4:
135                raise FatalCSVError(
136                    "Need at least column reg_number or applicant_id!")
137            if cond1 or cond2:
138                raise FatalCSVError(
139                    "container_code or application_number can't be imported " +
140                    "in update or remove mode!")
[7268]141        # Check for fields to be ignored...
142        not_ignored_fields = [x for x in headerfields
143                              if not x.startswith('--')]
144        if len(set(not_ignored_fields)) < len(not_ignored_fields):
145            raise FatalCSVError(
146                "Double headers: each column name may only appear once.")
147        return True
[7262]148
[7268]149    def getLocator(self, row):
[8331]150        if row.get('container_code', None) not in (IGNORE_MARKER, None):
[9250]151            # create mode
[8331]152            return 'container_code'
153        elif row.get('applicant_id', None) not in (IGNORE_MARKER, None):
[9250]154            # update or remove mode
[8331]155            return 'applicant_id'
[8236]156        elif row.get('reg_number', None) not in (IGNORE_MARKER, None):
[9250]157            # update or remove mode
[7270]158            return 'reg_number'
[7268]159        else:
160            return None
[7262]161
162    def getParent(self, row, site):
[8615]163        result = None
[8331]164        if self.getLocator(row) == 'container_code':
[8615]165            result = site['applicants'].get(row['container_code'], None)
166        elif self.getLocator(row) == 'reg_number':
[8331]167            reg_number = row['reg_number']
168            cat = queryUtility(ICatalog, name='applicants_catalog')
169            results = list(
170                cat.searchResults(reg_number=(reg_number, reg_number)))
171            if results:
[8615]172                result = results[0].__parent__
173        elif self.getLocator(row) == 'applicant_id':
[8331]174            applicant_id = row['applicant_id']
175            cat = queryUtility(ICatalog, name='applicants_catalog')
176            results = list(
177                cat.searchResults(applicant_id=(applicant_id, applicant_id)))
178            if results:
[8615]179                result = results[0].__parent__
180        return result
[7262]181
[7268]182    def parentsExist(self, row, site):
183        return self.getParent(row, site) is not None
184
[7262]185    def getEntry(self, row, site):
[8331]186        if self.getLocator(row) == 'container_code':
187            if row.get('application_number', None) not in (IGNORE_MARKER, None):
188                if not self.parentsExist(row, site):
189                    return None
190                parent = self.getParent(row, site)
191                return parent.get(row['application_number'])
[7264]192            return None
[8331]193        if self.getLocator(row) == 'applicant_id':
194            applicant_id = row['applicant_id']
195            cat = queryUtility(ICatalog, name='applicants_catalog')
196            results = list(
197                cat.searchResults(applicant_id=(applicant_id, applicant_id)))
198            if results:
199                return results[0]
200        if self.getLocator(row) == 'reg_number':
[7270]201            reg_number = row['reg_number']
[7268]202            cat = queryUtility(ICatalog, name='applicants_catalog')
203            results = list(
[7270]204                cat.searchResults(reg_number=(reg_number, reg_number)))
[7268]205            if results:
206                return results[0]
207        return None
[7262]208
[7268]209    def entryExists(self, row, site):
210        return self.getEntry(row, site) is not None
211
[7262]212    def addEntry(self, obj, row, site):
213        parent = self.getParent(row, site)
214        parent.addApplicant(obj)
[8334]215        #parent.__parent__.logger.info(
216        #    'Applicant imported: %s' % obj.applicant_id)
[8290]217        history = IObjectHistory(obj)
[8334]218        history.addMessage(_('Application record imported'))
[7262]219        return
220
221    def delEntry(self, row, site):
[7268]222        applicant = self.getEntry(row, site)
223        if applicant is not None:
[8331]224            parent = applicant.__parent__
[7268]225            del parent[applicant.application_number]
[8334]226            #parent.__parent__.logger.info(
227            #    'Applicant removed: %s' % applicant.applicant_id)
[7262]228        pass
[7268]229
[9706]230    def updateEntry(self, obj, row, site, filename):
[8290]231        """Update obj to the values given in row.
232        """
233        items_changed = ''
234        # Remove application_number from row if empty
[9701]235        if 'application_number' in row and row['application_number'] in (
[8290]236            None, IGNORE_MARKER):
237            row.pop('application_number')
238
239        # Update applicant_id fom application_number and container code
240        # if application_number is given
[9701]241        if 'application_number' in row:
[8290]242            obj.applicant_id = u'%s_%s' % (
243                row['container_code'], row['application_number'])
[8334]244            items_changed += ('%s=%s, ' % ('applicant_id', obj.applicant_id))
[8290]245            row.pop('application_number')
246
[15628]247        # Update
[9701]248        if 'password' in row:
[8334]249            passwd = row.get('password', IGNORE_MARKER)
250            if passwd not in ('', IGNORE_MARKER):
[8348]251                if passwd.startswith('{SSHA}'):
252                    # already encrypted password
253                    obj.password = passwd
[15628]254                elif passwd == DELETION_MARKER:
255                    obj.password = None
[8348]256                else:
257                    # not yet encrypted password
258                    IUserAccount(obj).setPassword(passwd)
[8334]259                items_changed += ('%s=%s, ' % ('password', passwd))
[8290]260            row.pop('password')
261
262        # Update registration state
[9701]263        if 'state' in row:
[8334]264            state = row.get('state', IGNORE_MARKER)
265            if state not in (IGNORE_MARKER, ''):
266                IWorkflowState(obj).setState(state)
267                msg = _("State '${a}' set", mapping = {'a':state})
268                history = IObjectHistory(obj)
269                history.addMessage(msg)
270                items_changed += ('%s=%s, ' % ('state', state))
[8290]271            row.pop('state')
272
273        # apply other values...
[8334]274        items_changed += super(ApplicantProcessor, self).updateEntry(
[9706]275            obj, row, site, filename)
[8290]276
277        # Log actions...
278        parent = self.getParent(row, site)
[8334]279        if self.getLocator(row) == 'container_code':
[8290]280            parent.__parent__.logger.info(
[9706]281                '%s - %s - imported: %s' % (self.name, filename, items_changed))
[8290]282        else:
[8334]283            parent.__parent__.logger.info(
[9706]284                '%s - %s - updated: %s' % (self.name, filename, items_changed))
[8290]285        return items_changed
286
[7268]287    def getMapping(self, path, headerfields, mode):
288        """Get a mapping from CSV file headerfields to actually used fieldnames.
289        """
290        result = dict()
291        reader = csv.reader(open(path, 'rb'))
292        raw_header = reader.next()
293        for num, field in enumerate(headerfields):
[8331]294            if field not in ['applicant_id', 'reg_number'] and mode == 'remove':
[7268]295                continue
296            if field == u'--IGNORE--':
297                # Skip ignored columns in failed and finished data files.
298                continue
299            result[raw_header[num]] = field
300        return result
301
302    def checkConversion(self, row, mode='create'):
303        """Validates all values in row.
304        """
[8331]305        iface = self.iface
306        if self.getLocator(row) == 'reg_number' or mode == 'remove':
[8581]307            iface = self.iface_byregnumber
[7268]308        converter = IObjectConverter(iface)
309        errs, inv_errs, conv_dict =  converter.fromStringDict(
[8223]310            row, self.factory_name, mode=mode)
[8615]311        cert = conv_dict.get('course1', None)
312        if cert is not None and (mode in ('create', 'update')):
[8617]313            # course1 application category must match container's.
[12869]314            site = grok.getSite()
315            parent = self.getParent(row, site)
[10613]316            if parent is None:
317                errs.append(('container', 'not found'))
318            elif cert.application_category != parent.application_category:
[8615]319                errs.append(('course1', 'wrong application category'))
[9701]320        if 'state' in row and \
[8290]321            not row['state'] in IMPORTABLE_STATES:
322            if row['state'] not in (IGNORE_MARKER, ''):
323                errs.append(('state','not allowed'))
324            else:
325                # state is an attribute of Applicant and must not
326                # be changed if empty
327                conv_dict['state'] = IGNORE_MARKER
[8331]328        application_number = row.get('application_number', None)
[8290]329        if application_number in (IGNORE_MARKER, ''):
330                conv_dict['application_number'] = IGNORE_MARKER
[7268]331        return errs, inv_errs, conv_dict
[8336]332
333    def checkUpdateRequirements(self, obj, row, site):
334        """Checks requirements the object must fulfill when being updated.
335
336        This method is not used in case of deleting or adding objects.
337
338        Returns error messages as strings in case of requirement
339        problems.
340        """
[17705]341        # Block applicant with backdoor ...
342        if obj.state == CREATED and obj.notice != 'reset':
[8336]343            return 'Applicant is blocked.'
344        return None
[13872]345
346class ApplicantOnlinePaymentProcessor(BatchProcessor):
347    """The Applicant Online Payment Processor imports applicant payment tickets.
348    The tickets are located in the applicant container.
349
350    The `checkConversion` method checks the format of the payment identifier.
351    In create mode it does also ensures that same p_id does not exist
352    elsewhere. It must be portal-wide unique.
353
354    When adding a payment ticket, the `addEntry` method checks if a
355    payment has already been made. If so, a `DuplicationError` is raised.
356    """
357    grok.implements(IBatchProcessor)
358    grok.provides(IBatchProcessor)
359    grok.context(Interface)
360    util_name = 'applicantpaymentprocessor'
361    grok.name(util_name)
362
363    name = _('ApplicantOnlinePayment Processor')
364    iface = IApplicantOnlinePayment
365    factory_name = 'waeup.ApplicantOnlinePayment'
366
[16472]367    location_fields = ['applicant_id',]
[13872]368
369    @property
370    def available_fields(self):
371        af = sorted(list(set(
[14804]372            self.location_fields + getFields(self.iface).keys())) +
373            ['p_id',])
[13872]374        af.remove('display_item')
375        return af
376
[14804]377    def checkHeaders(self, headerfields, mode='ignore'):
378        super(ApplicantOnlinePaymentProcessor, self).checkHeaders(headerfields)
379        if mode in ('update', 'remove') and not 'p_id' in headerfields:
380            raise FatalCSVError(
381                "Need p_id for import in update and remove modes!")
382        return True
383
[16472]384    def getMapping(self, path, headerfields, mode):
385        """Get a mapping from CSV file headerfields to actually used fieldnames.
386
387        """
388        result = dict()
389        reader = unicodecsv.reader(open(path, 'rb'))
390        raw_header = reader.next()
391        for num, field in enumerate(headerfields):
392            if field not in  ['applicant_id', 'p_id'] and mode == 'remove':
393                continue
394            if field == u'--IGNORE--':
395                continue
396            result[raw_header[num]] = field
397        return result
398
[13872]399    def parentsExist(self, row, site):
400        return self.getParent(row, site) is not None
401
402    def getParent(self, row, site):
403        applicant_id = row['applicant_id']
404        cat = queryUtility(ICatalog, name='applicants_catalog')
405        results = list(
406            cat.searchResults(applicant_id=(applicant_id, applicant_id)))
407        if results:
408            return results[0]
409        return None
410
411    def getEntry(self, row, site):
412        applicant = self.getParent(row, site)
413        if applicant is None:
414            return None
415        p_id = row.get('p_id', None)
416        if p_id in (None, IGNORE_MARKER):
417            return None
418        # We can use the hash symbol at the end of p_id in import files
419        # to avoid annoying automatic number transformation
420        # by Excel or Calc
421        p_id = p_id.strip('#')
422        entry = applicant.get(p_id)
423        return entry
424
425    def entryExists(self, row, site):
426        return self.getEntry(row, site) is not None
427
428    def updateEntry(self, obj, row, site, filename):
429        """Update obj to the values given in row.
430        """
431        items_changed = super(ApplicantOnlinePaymentProcessor, self).updateEntry(
432            obj, row, site, filename)
433        applicant = self.getParent(row, site)
434        applicant.__parent__.__parent__.logger.info(
435            '%s - %s - %s - updated: %s'
436            % (self.name, filename, applicant.applicant_id, items_changed))
437        return
438
439    def samePaymentMade(self, applicant, category):
440        for key in applicant.keys():
441            ticket = applicant[key]
442            if ticket.p_state == 'paid' and\
[16202]443                ticket.p_category == category:
[16200]444                return True
[13872]445        return False
446
447    def addEntry(self, obj, row, site):
448        applicant = self.getParent(row, site)
449        p_id = row['p_id'].strip('#')
[16358]450        if not (obj.p_item and obj.p_item.startswith(
451            'Balance')) and self.samePaymentMade(applicant, obj.p_category):
[13872]452            applicant.__parent__.__parent__.logger.info(
453                '%s - %s - previous update cancelled'
454                % (self.name, applicant.applicant_id))
455            raise DuplicationError('Payment has already been made.')
456        applicant[p_id] = obj
457        return
458
459    def delEntry(self, row, site):
460        payment = self.getEntry(row, site)
461        applicant = self.getParent(row, site)
462        if payment is not None:
463            applicant.__parent__.__parent__.logger.info('%s - Payment ticket removed: %s'
464                % (applicant.applicant_id, payment.p_id))
465            del applicant[payment.p_id]
466        return
467
468    def checkConversion(self, row, mode='ignore'):
469        """Validates all values in row.
470        """
471        errs, inv_errs, conv_dict = super(
472            ApplicantOnlinePaymentProcessor, self).checkConversion(row, mode=mode)
473        # We have to check p_id.
474        p_id = row.get('p_id', None)
475        if mode == 'create' and p_id in (None, IGNORE_MARKER):
476            timestamp = ("%d" % int(time()*10000))[1:]
477            p_id = "p%s" % timestamp
478            conv_dict['p_id'] = p_id
479            return errs, inv_errs, conv_dict
480        elif p_id in (None, IGNORE_MARKER):
481            errs.append(('p_id','missing'))
482            return errs, inv_errs, conv_dict
483        else:
484            p_id = p_id.strip('#')
485            if not len(p_id) == 14:
486                errs.append(('p_id','invalid length'))
487                return errs, inv_errs, conv_dict
488        if mode == 'create':
489            cat = getUtility(ICatalog, name='payments_catalog')
490            results = list(cat.searchResults(p_id=(p_id, p_id)))
491            if len(results) > 0:
492                sids = [IPayer(payment).id for payment in results]
493                sids_string = ''
494                for id in sids:
495                    sids_string += '%s ' % id
496                errs.append(('p_id','p_id exists in %s' % sids_string))
497                return errs, inv_errs, conv_dict
498        return errs, inv_errs, conv_dict
Note: See TracBrowser for help on using the repository browser.