source: main/waeup.ikoba/trunk/src/waeup/ikoba/interfaces.py @ 12533

Last change on this file since 12533 was 12526, checked in by Henrik Bettermann, 10 years ago

Extend customer registration workflow.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 37.7 KB
Line 
1## $Id: interfaces.py 12526 2015-01-30 14:02:53Z henrik $
2##
3## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann
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.
8##
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.
13##
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##
18import os
19import re
20import codecs
21import zc.async.interfaces
22import zope.i18nmessageid
23from datetime import datetime
24from hurry.file.interfaces import IFileRetrieval
25from hurry.workflow.interfaces import IWorkflowInfo
26from zc.sourcefactory.basic import BasicSourceFactory
27from zope import schema
28from zope.pluggableauth.interfaces import IPrincipalInfo
29from zope.security.interfaces import IGroupClosureAwarePrincipal as IPrincipal
30from zope.component import getUtility
31from zope.component.interfaces import IObjectEvent
32from zope.configuration.fields import Path
33from zope.container.interfaces import INameChooser, IContainer
34from zope.interface import Interface, Attribute
35from zope.schema.interfaces import IObject
36from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm
37from waeup.ikoba.schema import PhoneNumber
38from waeup.ikoba.sourcefactory import SmartBasicContextualSourceFactory
39
40_ = MessageFactory = zope.i18nmessageid.MessageFactory('waeup.ikoba')
41
42DELETION_MARKER = 'XXX'
43IGNORE_MARKER = '<IGNORE>'
44WAEUP_KEY = 'waeup.ikoba'
45VIRT_JOBS_CONTAINER_NAME = 'jobs'
46
47# States for various workflows
48
49CREATED = 'created'
50
51STARTED = 'started'
52REQUESTED = 'requested'
53PROVISIONALLY = 'provisionally'
54APPROVED = 'approved'
55
56SUBMITTED = 'submitted'
57VERIFIED = 'verified'
58REJECTED = 'rejected'
59EXPIRED = 'expired'
60PUBLISHED = 'published'
61
62
63#: A dict giving job status as tuple (<STRING>, <TRANSLATED_STRING>),
64#: the latter for UI purposes.
65JOB_STATUS_MAP = {
66    zc.async.interfaces.NEW: ('new', _('new')),
67    zc.async.interfaces.COMPLETED: ('completed', _('completed')),
68    zc.async.interfaces.PENDING: ('pending', _('pending')),
69    zc.async.interfaces.ACTIVE: ('active', _('active')),
70    zc.async.interfaces.ASSIGNED: ('assigned', _('assigned')),
71    zc.async.interfaces.CALLBACKS: ('callbacks', _('callbacks')),
72    }
73
74#default_rest_frontpage = u'' + codecs.open(os.path.join(
75#        os.path.dirname(__file__), 'frontpage.rst'),
76#        encoding='utf-8', mode='rb').read()
77
78default_html_frontpage = u'' + codecs.open(os.path.join(
79        os.path.dirname(__file__), 'frontpage.html'),
80        encoding='utf-8', mode='rb').read()
81
82def SimpleIkobaVocabulary(*terms):
83    """A well-buildt vocabulary provides terms with a value, token and
84       title for each term
85    """
86    return SimpleVocabulary([
87            SimpleTerm(value, value, title) for title, value in terms])
88
89class ContextualDictSourceFactoryBase(SmartBasicContextualSourceFactory):
90    """A base for contextual sources based on IkobaUtils dicts.
91
92    To create a real source, you have to set the `DICT_NAME` attribute
93    which should be the name of a dictionary in IkobaUtils.
94    """
95    def getValues(self, context):
96        utils = getUtility(IIkobaUtils)
97        sorted_items = sorted(getattr(utils, self.DICT_NAME).items(),
98                              key=lambda item: item[1])
99        return [item[0] for item in sorted_items]
100
101    def getToken(self, context, value):
102        return str(value)
103
104    def getTitle(self, context, value):
105        utils = getUtility(IIkobaUtils)
106        return getattr(utils, self.DICT_NAME)[value]
107
108# Define a validation method for email addresses
109class NotAnEmailAddress(schema.ValidationError):
110    __doc__ = u"Invalid email address"
111
112#: Regular expression to check email-address formats. As these can
113#: become rather complex (nearly everything is allowed by RFCs), we only
114#: forbid whitespaces, commas and dots following onto each other.
115check_email = re.compile(
116    r"^[^@\s,]+@[^@\.\s,]+(\.[^@\.\s,]+)*$").match
117
118def validate_email(value):
119    if not check_email(value):
120        raise NotAnEmailAddress(value)
121    return True
122
123# Define a validation method for ids
124class NotIdValue(schema.ValidationError):
125    __doc__ = u"Invalid id"
126
127#: Regular expressions to check id formats.
128check_id = re.compile(r"^[a-zA-Z0-9_-]{2,9}$").match
129check_uuid = re.compile( r"^[a-zA-Z0-9]{32}$").match
130
131def validate_id(value):
132    if not check_id(value):
133        raise NotIdValue(value)
134    return True
135
136def validate_uuid(value):
137    # We are using also short ids in tests
138    if not check_uuid(value) and not check_id(value):
139        raise NotIdValue(value)
140    return True
141
142# Define a validation method for international phone numbers
143class InvalidPhoneNumber(schema.ValidationError):
144    __doc__ = u"Invalid phone number"
145
146# represent format +NNN-NNNN-NNNN
147RE_INT_PHONE = re.compile(r"^\+?\d+\-\d+\-[\d\-]+$")
148
149def validate_phone(value):
150    if not RE_INT_PHONE.match(value):
151        raise InvalidPhoneNumber(value)
152    return True
153
154class FatalCSVError(Exception):
155    """Some row could not be processed.
156    """
157    pass
158
159class DuplicationError(Exception):
160    """An exception that can be raised when duplicates are found.
161
162    When raising :exc:`DuplicationError` you can, beside the usual
163    message, specify a list of objects which are duplicates. These
164    values can be used by catching code to print something helpful or
165    similar.
166    """
167    def __init__(self, msg, entries=[]):
168        self.msg = msg
169        self.entries = entries
170
171    def __str__(self):
172        return '%r' % self.msg
173
174class RoleSource(BasicSourceFactory):
175    """A source for site roles.
176    """
177    def getValues(self):
178        # late import: in interfaces we should not import local modules
179        from waeup.ikoba.permissions import get_waeup_role_names
180        return get_waeup_role_names()
181
182    def getTitle(self, value):
183        # late import: in interfaces we should not import local modules
184        from waeup.ikoba.permissions import get_all_roles
185        roles = dict(get_all_roles())
186        if value in roles.keys():
187            title = roles[value].title
188            if '.' in title:
189                title = title.split('.', 2)[1]
190        return title
191
192class CaptchaSource(BasicSourceFactory):
193    """A source for captchas.
194    """
195    def getValues(self):
196        captchas = ['No captcha', 'Testing captcha', 'ReCaptcha']
197        try:
198            # we have to 'try' because IConfiguration can only handle
199            # interfaces from w.k.interface.
200            from waeup.ikoba.browser.interfaces import ICaptchaManager
201        except:
202            return captchas
203        return sorted(getUtility(ICaptchaManager).getAvailCaptchas().keys())
204
205    def getTitle(self, value):
206        return value
207
208class CurrencySource(BasicSourceFactory):
209    """A source for currencies.
210    """
211    def getValues(self):
212        currencies = getUtility(IIkobaUtils).CURRENCIES
213        return currencies.keys()
214
215    def getToken(self, value):
216        return value
217
218    def getTitle(self, value):
219        currencies = getUtility(IIkobaUtils).CURRENCIES
220        return currencies[value][1]
221
222class IIkobaUtils(Interface):
223    """A collection of methods which are subject to customization.
224    """
225
226    PORTAL_LANGUAGE = Attribute("Dict of global language setting")
227    PREFERRED_LANGUAGES_DICT = Attribute("Dict of preferred languages")
228    SYSTEM_MAX_LOAD = Attribute("Dict of maximum system loads.")
229
230    def sendContactForm(
231          from_name,from_addr,rcpt_name,rcpt_addr,
232          from_username,usertype,portal,body,subject):
233        """Send an email with data provided by forms.
234        """
235
236    def fullname(firstname,lastname,middlename):
237        """Full name constructor.
238        """
239
240    def sendCredentials(user, password, url_info, msg):
241        """Send credentials as email.
242
243        Input is the customer for which credentials are sent and the
244        password.
245
246        Returns True or False to indicate successful operation.
247        """
248
249    def genPassword(length, chars):
250        """Generate a random password.
251        """
252
253class IIkobaObject(Interface):
254    """A Ikoba object.
255
256    This is merely a marker interface.
257    """
258
259class ICompany(IIkobaObject):
260    """Representation of an company.
261    """
262
263
264class IIkobaContainer(IIkobaObject):
265    """A container for Ikoba objects.
266    """
267
268class IIkobaContained(IIkobaObject):
269    """An item contained in an IIkobaContainer.
270    """
271
272class ICSVExporter(Interface):
273    """A CSV file exporter for objects.
274    """
275    fields = Attribute("""List of fieldnames in resulting CSV""")
276
277    title = schema.TextLine(
278        title = u'Title',
279        description = u'Description to be displayed in selections.',
280        )
281    def mangle_value(value, name, obj):
282        """Mangle `value` extracted from `obj` or suobjects thereof.
283
284        This is called by export before actually writing to the result
285        file.
286        """
287
288    def get_filtered(site, **kw):
289        """Get datasets in `site` to be exported.
290
291        The set of data is specified by keywords, which might be
292        different for any implementaion of exporter.
293
294        Returns an iterable.
295        """
296
297    def export(iterable, filepath=None):
298        """Export iterables as rows in a CSV file.
299
300        If `filepath` is not given, a string with the data should be
301        returned.
302
303        What kind of iterables are acceptable depends on the specific
304        exporter implementation.
305        """
306
307    def export_all(site, filepath=None):
308        """Export all items in `site` as CSV file.
309
310        if `filepath` is not given, a string with the data should be
311        returned.
312        """
313
314    def export_filtered(site, filepath=None, **kw):
315        """Export those items in `site` specified by `args` and `kw`.
316
317        If `filepath` is not given, a string with the data should be
318        returned.
319
320        Which special keywords are supported is up to the respective
321        exporter.
322        """
323
324class IIkobaExporter(Interface):
325    """An exporter for objects.
326    """
327    def export(obj, filepath=None):
328        """Export by pickling.
329
330        Returns a file-like object containing a representation of `obj`.
331
332        This is done using `pickle`. If `filepath` is ``None``, a
333        `cStringIO` object is returned, that contains the saved data.
334        """
335
336class IIkobaXMLExporter(Interface):
337    """An XML exporter for objects.
338    """
339    def export(obj, filepath=None):
340        """Export as XML.
341
342        Returns an XML representation of `obj`.
343
344        If `filepath` is ``None``, a StringIO` object is returned,
345        that contains the transformed data.
346        """
347
348class IIkobaXMLImporter(Interface):
349    """An XML import for objects.
350    """
351    def doImport(filepath):
352        """Create Python object from XML.
353
354        Returns a Python object.
355        """
356
357class IBatchProcessor(Interface):
358    """A batch processor that handles mass-operations.
359    """
360    name = schema.TextLine(
361        title = _(u'Processor name')
362        )
363
364    def doImport(path, headerfields, mode='create', user='Unknown',
365                 logger=None, ignore_empty=True):
366        """Read data from ``path`` and update connected object.
367
368        `headerfields` is a list of headerfields as read from the file
369        to import.
370
371        `mode` gives the import mode to use (``'create'``,
372        ``'update'``, or ``'remove'``.
373
374        `user` is a string describing the user performing the
375        import. Normally fetched from current principal.
376
377        `logger` is the logger to use during import.
378
379        `ignore_emtpy` in update mode ignores empty fields if true.
380        """
381
382class IContactForm(IIkobaObject):
383    """A contact form.
384    """
385
386    email_from = schema.TextLine(
387        title = _(u'Email Address:'),
388        default = None,
389        required = True,
390        constraint=validate_email,
391        )
392
393    email_to = schema.TextLine(
394        title = _(u'Email to:'),
395        default = None,
396        required = True,
397        constraint=validate_email,
398        )
399
400    subject = schema.TextLine(
401        title = _(u'Subject:'),
402        required = True,)
403
404    fullname = schema.TextLine(
405        title = _(u'Full Name:'),
406        required = True,)
407
408    body = schema.Text(
409        title = _(u'Text:'),
410        required = True,)
411
412class IIkobaPrincipalInfo(IPrincipalInfo):
413    """Infos about principals that are users of Ikoba Ikoba.
414    """
415    email = Attribute("The email address of a user")
416    phone = Attribute("The phone number of a user")
417    public_name = Attribute("The public name of a user")
418
419
420class IIkobaPrincipal(IPrincipal):
421    """A principle for Ikoba Ikoba.
422
423    This interface extends zope.security.interfaces.IPrincipal and
424    requires also an `id` and other attributes defined there.
425    """
426
427    email = schema.TextLine(
428        title = _(u'Email Address'),
429        description = u'',
430        required=False,)
431
432    phone = PhoneNumber(
433        title = _(u'Phone'),
434        description = u'',
435        required=False,)
436
437    public_name = schema.TextLine(
438        title = _(u'Public Name'),
439        required = False,)
440
441class IFailedLoginInfo(IIkobaObject):
442    """Info about failed logins.
443
444    Timestamps are supposed to be stored as floats using time.time()
445    or similar.
446    """
447    num = schema.Int(
448        title = _(u'Number of failed logins'),
449        description = _(u'Number of failed logins'),
450        required = True,
451        default = 0,
452        )
453
454    last = schema.Float(
455        title = _(u'Timestamp'),
456        description = _(u'Timestamp of last failed login or `None`'),
457        required = False,
458        default = None,
459        )
460
461    def as_tuple():
462        """Get login info as tuple ``<NUM>, <TIMESTAMP>``.
463        """
464
465    def set_values(num=0, last=None):
466        """Set number of failed logins and timestamp of last one.
467        """
468
469    def increase():
470        """Increase the current number of failed logins and set timestamp.
471        """
472
473    def reset():
474        """Set failed login counters back to zero.
475        """
476
477
478class IUserAccount(IIkobaObject):
479    """A user account.
480    """
481
482    failed_logins = Attribute("""FailedLoginInfo for this account""")
483
484    name = schema.TextLine(
485        title = _(u'User Id'),
486        description = u'Login name of user',
487        required = True,)
488
489    title = schema.TextLine(
490        title = _(u'Full Name'),
491        required = True,)
492
493    public_name = schema.TextLine(
494        title = _(u'Public Name'),
495        description = u"Substitute for officer's real name "
496                       "in object histories.",
497        required = False,)
498
499    description = schema.Text(
500        title = _(u'Description/Notice'),
501        required = False,)
502
503    email = schema.TextLine(
504        title = _(u'Email Address'),
505        default = None,
506        required = True,
507        constraint=validate_email,
508        )
509
510    phone = PhoneNumber(
511        title = _(u'Phone'),
512        default = None,
513        required = False,
514        )
515
516    roles = schema.List(
517        title = _(u'Portal Roles'),
518        value_type = schema.Choice(source=RoleSource()),
519        required = False,
520        )
521
522
523
524class IPasswordValidator(Interface):
525    """A password validator utility.
526    """
527
528    def validate_password(password, password_repeat):
529        """Validates a password by comparing it with
530        control password and checking some other requirements.
531        """
532
533
534class IUsersContainer(IIkobaObject):
535    """A container for users (principals).
536
537    These users are used for authentication purposes.
538    """
539
540    def addUser(name, password, title=None, description=None):
541        """Add a user.
542        """
543
544    def delUser(name):
545        """Delete a user if it exists.
546        """
547
548class ILocalRolesAssignable(Interface):
549    """The local roles assignable to an object.
550    """
551    def __call__():
552        """Returns a list of dicts.
553
554        Each dict contains a ``name`` referring to the role assignable
555        for the specified object and a `title` to describe the range
556        of users to which this role can be assigned.
557        """
558
559class IConfigurationContainer(IIkobaObject):
560    """A container for session configuration objects.
561    """
562
563    name = schema.TextLine(
564        title = _(u'Name of Company'),
565        default = _(u'Sample Company'),
566        required = True,
567        )
568
569    acronym = schema.TextLine(
570        title = _(u'Abbreviated Title of Company'),
571        default = u'WAeUP.Ikoba',
572        required = True,
573        )
574
575    frontpage = schema.Text(
576        title = _(u'Content in HTML format'),
577        required = False,
578        default = default_html_frontpage,
579        )
580
581    frontpage_dict = schema.Dict(
582        title = u'Content as language dictionary with values in html format',
583        required = False,
584        default = {},
585        )
586
587    name_admin = schema.TextLine(
588        title = _(u'Name of Administrator'),
589        default = u'Administrator',
590        required = True,
591        )
592
593    email_admin = schema.TextLine(
594        title = _(u'Email Address of Administrator'),
595        default = u'contact@waeup.org',
596        required = True,
597        constraint=validate_email,
598        )
599
600    email_subject = schema.TextLine(
601        title = _(u'Subject of Email to Administrator'),
602        default = _(u'Ikoba Contact'),
603        required = True,
604        )
605
606    smtp_mailer = schema.Choice(
607        title = _(u'SMTP mailer to use when sending mail'),
608        vocabulary = 'Mail Delivery Names',
609        default = 'No email service',
610        required = True,
611        )
612
613    captcha = schema.Choice(
614        title = _(u'Captcha used for public registration pages'),
615        source = CaptchaSource(),
616        default = u'No captcha',
617        required = True,
618        )
619
620
621class IDataCenter(IIkobaObject):
622    """A data center.
623
624    A data center manages files (uploads, downloads, etc.).
625
626    Beside providing the bare paths needed to keep files, it also
627    provides some helpers to put results of batch processing into
628    well-defined final locations (with well-defined filenames).
629
630    The main use-case is managing of site-related files, i.e. files
631    for import, export etc.
632
633    DataCenters are _not_ meant as storages for object-specific files
634    like passport photographs and similar.
635
636    It is up to the datacenter implementation how to organize data
637    (paths) inside its storage path.
638    """
639    storage = schema.Bytes(
640        title = u'Path to directory where everything is kept.'
641        )
642
643    deleted_path = schema.Bytes(
644        title = u'Path were data about deleted objects should be stored.'
645        )
646
647    def getPendingFiles(sort='name'):
648        """Get a list of files stored in `storage` sorted by basename.
649        """
650
651    def getFinishedFiles():
652        """Get a list of files stored in `finished` subfolder of `storage`.
653        """
654
655    def setStoragePath(path, move=False, overwrite=False):
656        """Set the path where to store files.
657
658        If `move` is True, move over files from the current location
659        to the new one.
660
661        If `overwrite` is also True, overwrite any already existing
662        files of same name in target location.
663
664        Triggers a DataCenterStorageMovedEvent.
665        """
666
667    def distProcessedFiles(successful, source_path, finished_file,
668                           pending_file, mode='create', move_orig=True):
669        """Distribute processed files over final locations.
670        """
671
672
673class IDataCenterFile(Interface):
674    """A data center file.
675    """
676
677    name = schema.TextLine(
678        title = u'Filename')
679
680    size = schema.TextLine(
681        title = u'Human readable file size')
682
683    uploaddate = schema.TextLine(
684        title = u'Human readable upload datetime')
685
686    lines = schema.Int(
687        title = u'Number of lines in file')
688
689    def getDate():
690        """Get creation timestamp from file in human readable form.
691        """
692
693    def getSize():
694        """Get human readable size of file.
695        """
696
697    def getLinesNumber():
698        """Get number of lines of file.
699        """
700
701class IDataCenterStorageMovedEvent(IObjectEvent):
702    """Emitted, when the storage of a datacenter changes.
703    """
704
705class IObjectUpgradeEvent(IObjectEvent):
706    """Can be fired, when an object shall be upgraded.
707    """
708
709class ILocalRoleSetEvent(IObjectEvent):
710    """A local role was granted/revoked for a principal on an object.
711    """
712    role_id = Attribute(
713        "The role id that was set.")
714    principal_id = Attribute(
715        "The principal id for which the role was granted/revoked.")
716    granted = Attribute(
717        "Boolean. If false, then the role was revoked.")
718
719class IQueryResultItem(Interface):
720    """An item in a search result.
721    """
722    url = schema.TextLine(
723        title = u'URL that links to the found item')
724    title = schema.TextLine(
725        title = u'Title displayed in search results.')
726    description = schema.Text(
727        title = u'Longer description of the item found.')
728
729class IIkobaPluggable(Interface):
730    """A component that might be plugged into a Ikoba Ikoba app.
731
732    Components implementing this interface are referred to as
733    'plugins'. They are normally called when a new
734    :class:`waeup.ikoba.app.Company` instance is created.
735
736    Plugins can setup and update parts of the central site without the
737    site object (normally a :class:`waeup.ikoba.app.Company` object)
738    needing to know about that parts. The site simply collects all
739    available plugins, calls them and the plugins care for their
740    respective subarea like the cutomers area or the datacenter
741    area.
742
743    Currently we have no mechanism to define an order of plugins. A
744    plugin should therefore make no assumptions about the state of the
745    site or other plugins being run before and instead do appropriate
746    checks if necessary.
747
748    Updates can be triggered for instance by the respective form in
749    the site configuration. You normally do updates when the
750    underlying software changed.
751    """
752    def setup(site, name, logger):
753        """Create an instance of the plugin.
754
755        The method is meant to be called by the central app (site)
756        when it is created.
757
758        `site`:
759           The site that requests a setup.
760
761        `name`:
762           The name under which the plugin was registered (utility name).
763
764        `logger`:
765           A standard Python logger for the plugins use.
766        """
767
768    def update(site, name, logger):
769        """Method to update an already existing plugin.
770
771        This might be called by a site when something serious
772        changes. It is a poor-man replacement for Zope generations
773        (but probably more comprehensive and better understandable).
774
775        `site`:
776           The site that requests an update.
777
778        `name`:
779           The name under which the plugin was registered (utility name).
780
781        `logger`:
782           A standard Python logger for the plugins use.
783        """
784
785class IAuthPluginUtility(Interface):
786    """A component that cares for authentication setup at site creation.
787
788    Utilities providing this interface are looked up when a Pluggable
789    Authentication Utility (PAU) for any
790    :class:`waeup.ikoba.app.Company` instance is created and put
791    into ZODB.
792
793    The setup-code then calls the `register` method of the utility and
794    expects a modified (or unmodified) version of the PAU back.
795
796    This allows to define any authentication setup modifications by
797    submodules or third-party modules/packages.
798    """
799
800    def register(pau):
801        """Register any plugins wanted to be in the PAU.
802        """
803
804    def unregister(pau):
805        """Unregister any plugins not wanted to be in the PAU.
806        """
807
808class IObjectConverter(Interface):
809    """Object converters are available as simple adapters, adapting
810       interfaces (not regular instances).
811
812    """
813
814    def fromStringDict(self, data_dict, context, form_fields=None):
815        """Convert values in `data_dict`.
816
817        Converts data in `data_dict` into real values based on
818        `context` and `form_fields`.
819
820        `data_dict` is a mapping (dict) from field names to values
821        represented as strings.
822
823        The fields (keys) to convert can be given in optional
824        `form_fields`. If given, form_fields should be an instance of
825        :class:`zope.formlib.form.Fields`. Suitable instances are for
826        example created by :class:`grok.AutoFields`.
827
828        If no `form_fields` are given, a default is computed from the
829        associated interface.
830
831        The `context` can be an existing object (implementing the
832        associated interface) or a factory name. If it is a string, we
833        try to create an object using
834        :func:`zope.component.createObject`.
835
836        Returns a tuple ``(<FIELD_ERRORS>, <INVARIANT_ERRORS>,
837        <DATA_DICT>)`` where
838
839        ``<FIELD_ERRORS>``
840           is a list of tuples ``(<FIELD_NAME>, <ERROR>)`` for each
841           error that happened when validating the input data in
842           `data_dict`
843
844        ``<INVARIANT_ERRORS>``
845           is a list of invariant errors concerning several fields
846
847        ``<DATA_DICT>``
848           is a dict with the values from input dict converted.
849
850        If errors happen, i.e. the error lists are not empty, always
851        an empty ``<DATA_DICT>`` is returned.
852
853        If ``<DATA_DICT>` is non-empty, there were no errors.
854        """
855
856class IFieldConverter(Interface):
857    def request_data(name, value, schema_field, prefix='', mode='create'):
858        """Create a dict with key-value mapping as created by a request.
859
860        `name` and `value` are expected to be parsed from CSV or a
861        similar input and represent an attribute to be set to a
862        representation of value.
863
864        `mode` gives the mode of import.
865
866        :meth:`update_request_data` is then requested to turn this
867        name and value into vars as they would be sent by a regular
868        form submit. This means we do not create the real values to be
869        set but we only define the values that would be sent in a
870        browser request to request the creation of those values.
871
872        The returned dict should contain names and values of a faked
873        browser request for the given `schema_field`.
874
875        Field converters are normally registered as adapters to some
876        specific zope.schema field.
877        """
878
879class IObjectHistory(Interface):
880
881    messages = schema.List(
882        title = u'List of messages stored',
883        required = True,
884        )
885
886    def addMessage(message):
887        """Add a message.
888        """
889
890class IIkobaWorkflowInfo(IWorkflowInfo):
891    """A :class:`hurry.workflow.workflow.WorkflowInfo` with additional
892       methods for convenience.
893    """
894    def getManualTransitions():
895        """Get allowed manual transitions.
896
897        Get a sorted list of tuples containing the `transition_id` and
898        `title` of each allowed transition.
899        """
900
901class ISiteLoggers(Interface):
902
903    loggers = Attribute("A list or generator of registered IkobaLoggers")
904
905    def register(name, filename=None, site=None, **options):
906        """Register a logger `name` which logs to `filename`.
907
908        If `filename` is not given, logfile will be `name` with
909        ``.log`` as filename extension.
910        """
911
912    def unregister(name):
913        """Unregister a once registered logger.
914        """
915
916class ILogger(Interface):
917    """A logger cares for setup, update and restarting of a Python logger.
918    """
919
920    logger = Attribute("""A :class:`logging.Logger` instance""")
921
922
923    def __init__(name, filename=None, site=None, **options):
924        """Create a Ikoba logger instance.
925        """
926
927    def setup():
928        """Create a Python :class:`logging.Logger` instance.
929
930        The created logger is based on the params given by constructor.
931        """
932
933    def update(**options):
934        """Update the logger.
935
936        Updates the logger respecting modified `options` and changed
937        paths.
938        """
939
940class ILoggerCollector(Interface):
941
942    def getLoggers(site):
943        """Return all loggers registered for `site`.
944        """
945
946    def registerLogger(site, logging_component):
947        """Register a logging component residing in `site`.
948        """
949
950    def unregisterLogger(site, logging_component):
951        """Unregister a logger.
952        """
953
954#
955# External File Storage and relatives
956#
957class IFileStoreNameChooser(INameChooser):
958    """See zope.container.interfaces.INameChooser for base methods.
959    """
960    def checkName(name, attr=None):
961        """Check whether an object name is valid.
962
963        Raises a user error if the name is not valid.
964        """
965
966    def chooseName(name, attr=None):
967        """Choose a unique valid file id for the object.
968
969        The given name may be taken into account when choosing the
970        name (file id).
971
972        chooseName is expected to always choose a valid file id (that
973        would pass the checkName test) and never raise an error.
974
975        If `attr` is not ``None`` it might been taken into account as
976        well when generating the file id. Usual behaviour is to
977        interpret `attr` as a hint for what type of file for a given
978        context should be stored if there are several types
979        possible. For instance for a certain customer some file could
980        be the connected passport photograph or some certificate scan
981        or whatever. Each of them has to be stored in a different
982        location so setting `attr` to a sensible value should give
983        different file ids returned.
984        """
985
986class IExtFileStore(IFileRetrieval):
987    """A file storage that stores files in filesystem (not as blobs).
988    """
989    root = schema.TextLine(
990        title = u'Root path of file store.',
991        )
992
993    def getFile(file_id):
994        """Get raw file data stored under file with `file_id`.
995
996        Returns a file descriptor open for reading or ``None`` if the
997        file cannot be found.
998        """
999
1000    def getFileByContext(context, attr=None):
1001        """Get raw file data stored for the given context.
1002
1003        Returns a file descriptor open for reading or ``None`` if no
1004        such file can be found.
1005
1006        Both, `context` and `attr` might be used to find (`context`)
1007        and feed (`attr`) an appropriate file name chooser.
1008
1009        This is a convenience method.
1010        """
1011
1012    def deleteFile(file_id):
1013        """Delete file stored under `file_id`.
1014
1015        Remove file from filestore so, that it is not available
1016        anymore on next call to getFile for the same file_id.
1017
1018        Should not complain if no such file exists.
1019        """
1020
1021    def deleteFileByContext(context, attr=None):
1022        """Delete file for given `context` and `attr`.
1023
1024        Both, `context` and `attr` might be used to find (`context`)
1025        and feed (`attr`) an appropriate file name chooser.
1026
1027        This is a convenience method.
1028        """
1029
1030    def createFile(filename, f):
1031        """Create file given by f with filename `filename`
1032
1033        Returns a hurry.file.File-based object.
1034        """
1035
1036class IFileStoreHandler(Interface):
1037    """Filestore handlers handle specific files for file stores.
1038
1039    If a file to store/get provides a specific filename, a file store
1040    looks up special handlers for that type of file.
1041
1042    """
1043    def pathFromFileID(store, root, filename):
1044        """Turn file id into path to store.
1045
1046        Returned path should be absolute.
1047        """
1048
1049    def createFile(store, root, filename, file_id, file):
1050        """Return some hurry.file based on `store` and `file_id`.
1051
1052        Some kind of callback method called by file stores to create
1053        file objects from file_id.
1054
1055        Returns a tuple ``(raw_file, path, file_like_obj)`` where the
1056        ``file_like_obj`` should be a HurryFile, a IkobaImageFile or
1057        similar. ``raw_file`` is the (maybe changed) input file and
1058        ``path`` the relative internal path to store the file at.
1059
1060        Please make sure the ``raw_file`` is opened for reading and
1061        the file descriptor set at position 0 when returned.
1062
1063        This method also gets the raw input file object that is about
1064        to be stored and is expected to raise any exceptions if some
1065        kind of validation or similar fails.
1066        """
1067
1068class IPDF(Interface):
1069    """A PDF representation of some context.
1070    """
1071
1072    def __call__(view=None, note=None):
1073        """Create a bytestream representing a PDF from context.
1074
1075        If `view` is passed in additional infos might be rendered into
1076        the document.
1077
1078        `note` is optional HTML rendered at bottom of the created
1079        PDF. Please consider the limited reportlab support for HTML,
1080        but using font-tags and friends you certainly can get the
1081        desired look.
1082        """
1083
1084class IMailService(Interface):
1085    """A mail service.
1086    """
1087
1088    def __call__():
1089        """Get the default mail delivery.
1090        """
1091
1092
1093class IDataCenterConfig(Interface):
1094    path = Path(
1095        title = u'Path',
1096        description = u"Directory where the datacenter should store "
1097                      u"files by default (adjustable in web UI).",
1098        required = True,
1099        )
1100
1101
1102class IPayPalConfig(Interface):
1103    path = Path(
1104        title = u'Path',
1105        description = u"Path to config file for PayPal REST API.",
1106        required = True,
1107        )
1108
1109
1110#
1111# Asynchronous job handling and related
1112#
1113class IJobManager(IIkobaObject):
1114    """A manager for asynchronous running jobs (tasks).
1115    """
1116    def put(job, site=None):
1117        """Put a job into task queue.
1118
1119        If no `site` is given, queue job in context of current local
1120        site.
1121
1122        Returns a job_id to identify the put job. This job_id is
1123        needed for further references to the job.
1124        """
1125
1126    def jobs(site=None):
1127        """Get an iterable of jobs stored.
1128        """
1129
1130    def get(job_id, site=None):
1131        """Get the job with id `job_id`.
1132
1133        For the `site` parameter see :meth:`put`.
1134        """
1135
1136    def remove(job_id, site=None):
1137        """Remove job with `job_id` from stored jobs.
1138        """
1139
1140    def start_test_job(site=None):
1141        """Start a test job.
1142        """
1143
1144class IProgressable(Interface):
1145    """A component that can indicate its progress status.
1146    """
1147    percent = schema.Float(
1148        title = u'Percent of job done already.',
1149        )
1150
1151class IJobContainer(IContainer):
1152    """A job container contains IJob objects.
1153    """
1154
1155class IExportJob(zc.async.interfaces.IJob):
1156    def __init__(site, exporter_name):
1157        pass
1158
1159    finished = schema.Bool(
1160        title = u'`True` if the job finished.`',
1161        default = False,
1162        )
1163
1164    failed = schema.Bool(
1165        title = u"`True` iff the job finished and didn't provide a file.",
1166        default = None,
1167        )
1168
1169class IExportJobContainer(IIkobaObject):
1170    """A component that contains (maybe virtually) export jobs.
1171    """
1172    def start_export_job(exporter_name, user_id, *args, **kwargs):
1173        """Start asynchronous export job.
1174
1175        `exporter_name` is the name of an exporter utility to be used.
1176
1177        `user_id` is the ID of the user that triggers the export.
1178
1179        `args` positional arguments passed to the export job created.
1180
1181        `kwargs` keyword arguments passed to the export job.
1182
1183        The job_id is stored along with exporter name and user id in a
1184        persistent list.
1185
1186        Returns the job ID of the job started.
1187        """
1188
1189    def get_running_export_jobs(user_id=None):
1190        """Get export jobs for user with `user_id` as list of tuples.
1191
1192        Each tuples holds ``<job_id>, <exporter_name>, <user_id>`` in
1193        that order. The ``<exporter_name>`` is the utility name of the
1194        used exporter.
1195
1196        If `user_id` is ``None``, all running jobs are returned.
1197        """
1198
1199    def get_export_jobs_status(user_id=None):
1200        """Get running/completed export jobs for `user_id` as list of tuples.
1201
1202        Each tuple holds ``<raw status>, <status translated>,
1203        <exporter title>`` in that order, where ``<status
1204        translated>`` and ``<exporter title>`` are translated strings
1205        representing the status of the job and the human readable
1206        title of the exporter used.
1207        """
1208
1209    def delete_export_entry(entry):
1210        """Delete the export denoted by `entry`.
1211
1212        Removes `entry` from the local `running_exports` list and also
1213        removes the regarding job via the local job manager.
1214
1215        `entry` is a tuple ``(<job id>, <exporter name>, <user id>)``
1216        as created by :meth:`start_export_job` or returned by
1217        :meth:`get_running_export_jobs`.
1218        """
1219
1220    def entry_from_job_id(job_id):
1221        """Get entry tuple for `job_id`.
1222
1223        Returns ``None`` if no such entry can be found.
1224        """
1225
1226class IExportContainerFinder(Interface):
1227    """A finder for the central export container.
1228    """
1229    def __call__():
1230        """Return the currently used global or site-wide IExportContainer.
1231        """
1232
1233class IFilteredQuery(IIkobaObject):
1234    """A query for objects.
1235    """
1236
1237    defaults = schema.Dict(
1238        title = u'Default Parameters',
1239        required = True,
1240        )
1241
1242    def __init__(**parameters):
1243        """Instantiate a filtered query by passing in parameters.
1244        """
1245
1246    def query():
1247        """Get an iterable of objects denoted by the set parameters.
1248
1249        The search should be applied to objects inside current
1250        site. It's the caller's duty to set the correct site before.
1251
1252        Result can be any iterable like a catalog result set, a list,
1253        or similar.
1254        """
1255
1256class IFilteredCatalogQuery(IFilteredQuery):
1257    """A catalog-based query for objects.
1258    """
1259
1260    cat_name = schema.TextLine(
1261        title = u'Registered name of the catalog to search.',
1262        required = True,
1263        )
1264
1265    def query_catalog(catalog):
1266        """Query catalog with the parameters passed to constructor.
1267        """
1268
1269
1270class IIDSource(Interface):
1271    """A source for unique IDs, according to RFC 4122.
1272    """
1273    def get_uuid():
1274        """Get a random unique ID.
1275
1276        Get a 'Universially Unique IDentifier'. The result string
1277        might contain any printable characters.
1278        """
1279
1280    def get_hex_uuid():
1281        """Get a random unique ID as a string representing a hex number.
1282        """
Note: See TracBrowser for help on using the repository browser.