source: main/waeup.kofa/trunk/src/waeup/kofa/configuration.py @ 17782

Last change on this file since 17782 was 17782, checked in by Henrik Bettermann, 4 months ago

ConfigurationContainerExporter? and tests.

  • Property svn:keywords set to Id
File size: 6.4 KB
Line 
1## $Id: configuration.py 17782 2024-05-14 07:27:45Z 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##
18"""
19Components for portal configuration.
20"""
21import grok
22from zope.component.interfaces import IFactory
23from zope.interface import implementedBy, Interface
24from waeup.kofa.utils.batching import ExporterBase
25from waeup.kofa.interfaces import ICSVExporter
26from waeup.kofa.interfaces import (
27    ISessionConfiguration, IConfigurationContainer, ISessionConfigurationAdd,
28    IBatchProcessor,
29    academic_sessions_vocab)
30from waeup.kofa.utils.helpers import attrs_to_fields, iface_names
31from waeup.kofa.utils.batching import BatchProcessor
32from waeup.kofa.interfaces import MessageFactory as _
33
34class ConfigurationContainer(grok.Container):
35    """
36    The node containing the session configuration models
37    """
38
39    grok.implements(IConfigurationContainer)
40
41    def addSessionConfiguration(self, sessionconfiguration):
42        """Add a session configuration object.
43        """
44        if not ISessionConfiguration.providedBy(sessionconfiguration):
45            raise TypeError(
46                'ConfigurationContainers contain only '
47                'ISessionConfiguration instances')
48        code = unicode(sessionconfiguration.academic_session)
49        self[code] = sessionconfiguration
50        return
51
52ConfigurationContainer = attrs_to_fields(ConfigurationContainer)
53
54class SessionConfiguration(grok.Model):
55    """
56    Session configuration model
57    """
58
59    grok.implements(ISessionConfiguration, ISessionConfigurationAdd)
60
61    def getSessionString(self):
62        """Return the session string from the vocabulary.
63        """
64        return academic_sessions_vocab.getTerm(self.academic_session).title
65
66SessionConfiguration = attrs_to_fields(SessionConfiguration)
67
68class SessionConfigurationFactory(grok.GlobalUtility):
69    """A factory for session configuration objects.
70    """
71    grok.implements(IFactory)
72    grok.name(u'waeup.SessionConfiguration')
73    title = u"Create a new session configuration object.",
74    description = u"This factory instantiates new session configurations."
75
76    def __call__(self, *args, **kw):
77        return SessionConfiguration(*args, **kw)
78
79    def getInterfaces(self):
80        return implementedBy(SessionConfiguration)
81
82class ConfigurationContainerExporter(grok.GlobalUtility, ExporterBase):
83    """The Configuration Container Exporter exports all configuration base data.
84    It also exports the last used student id.
85    """
86    grok.implements(ICSVExporter)
87    grok.name('base_configuration')
88
89    title = _(u'Base Configuration')
90    fields = tuple(sorted(iface_names(IConfigurationContainer))) + ('curr_stud_id',)
91
92    def mangle_value(self, value, name, context=None):
93        if name == 'curr_stud_id':
94            value = context.__parent__['students']._curr_stud_id
95        return super(
96            ConfigurationContainerExporter, self).mangle_value(
97            value, name, context=context)
98
99    def export_all(self, site, filepath=None):
100        """Export base configuration into filepath as CSV data.
101        If `filepath` is ``None``, a raw string with CSV data is returned.
102        """
103        writer, outfile = self.get_csv_writer(filepath)
104        configuration = site.get('configuration')
105        self.write_item(configuration, writer)
106        return self.close_outfile(filepath, outfile)
107
108class ConfigurationExporter(grok.GlobalUtility, ExporterBase):
109    """The Configuration Exporter exports all configuration data. It iterates over all
110    objects of the ``configuration`` container.
111    """
112    grok.implements(ICSVExporter)
113    grok.name('configurations')
114
115    title = _(u'Session Configurations')
116
117    fields = tuple(sorted(iface_names(ISessionConfiguration)))
118
119    def export(self, configurations, filepath=None):
120        """Export `configurations`, an iterable, as CSV file.
121
122        If `filepath` is ``None``, a raw string with CSV data is returned.
123        """
124        writer, outfile = self.get_csv_writer(filepath)
125        for configuration in configurations:
126            self.write_item(configuration, writer)
127        return self.close_outfile(filepath, outfile)
128
129    def export_all(self, site, filepath=None):
130        """Export configurations into filepath as CSV data.
131
132        If `filepath` is ``None``, a raw string with CSV data is returned.
133        """
134        configurations = site.get('configuration', {})
135        return self.export(configurations.values(), filepath)
136
137class ConfigurationProcessor(BatchProcessor):
138    """The Configuration Processor processes session configuration objects in
139    the ``configuration`` container.
140
141    """
142    grok.implements(IBatchProcessor)
143    grok.provides(IBatchProcessor)
144    grok.context(Interface)
145    util_name = 'configurationprocessor'
146    grok.name(util_name)
147
148    name = u'SessionConfiguration Processor'
149    iface = ISessionConfiguration
150    factory_name = 'waeup.SessionConfiguration'
151
152    mode = None
153
154    def parentsExist(self, row, site):
155        return 'configuration' in site.keys()
156
157    def entryExists(self, row, site):
158        return row['academic_session'] in site['configuration'].keys()
159
160    def getParent(self, row, site):
161        return site['configuration']
162
163    def getEntry(self, row, site):
164        if not self.entryExists(row, site):
165            return None
166        parent = self.getParent(row, site)
167        return parent.get(row['academic_session'])
168
169    def addEntry(self, obj, row, site):
170        parent = self.getParent(row, site)
171        parent.addSessionConfiguration(obj)
172        return
173
174    def delEntry(self, row, site):
175        configuration = self.getEntry(row, site)
176        if user is not None:
177            parent = self.getParent(row, site)
178            grok.getSite().logger.info(
179                '%s - %s - Session configuration removed' % (self.name, row['academic_session']))
180            del parent[configuration.academic_session]
181        pass
182
Note: See TracBrowser for help on using the repository browser.