source: main/waeup.ikoba/trunk/src/waeup/ikoba/customers/export.py @ 12092

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

Singular not plural.

  • Property svn:keywords set to Id
File size: 5.9 KB
Line 
1## $Id: export.py 12076 2014-11-28 06:56:38Z henrik $
2##
3## Copyright (C) 2014 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"""Exporters for customer related stuff.
19"""
20import os
21import grok
22from datetime import datetime
23from zope.component import getUtility
24from waeup.ikoba.interfaces import (
25    IExtFileStore, IFileStoreNameChooser)
26from waeup.ikoba.interfaces import MessageFactory as _
27from waeup.ikoba.customers.catalog import CustomersQuery
28from waeup.ikoba.customers.interfaces import (
29    ICustomer, ICSVCustomerExporter, ICustomerDocument)
30from waeup.ikoba.utils.batching import ExporterBase
31from waeup.ikoba.utils.helpers import iface_names, to_timezone
32
33#: A tuple containing all exporter names referring to customers or
34#: subobjects thereof.
35EXPORTER_NAMES = ('customers', 'customerdocuments')
36
37
38def get_customers(site, cust_filter=CustomersQuery()):
39    """Get all customers registered in catalog in `site`.
40    """
41    return cust_filter.query()
42
43def get_documents(customers):
44    """Get all documents of `customers`.
45    """
46    documents = []
47    for customer in customers:
48        for document in customer.get('documents', {}).values():
49            documents.append(document)
50    return documents
51
52
53class CustomerExporterBase(ExporterBase):
54    """Exporter for customers or related objects.
55
56    This is a baseclass.
57    """
58    grok.baseclass()
59    grok.implements(ICSVCustomerExporter)
60    grok.provides(ICSVCustomerExporter)
61
62    def filter_func(self, x, **kw):
63        return x
64
65    def get_filtered(self, site, **kw):
66        """Get customers from a catalog filtered by keywords.
67
68        customers_catalog is the default catalog. The keys must be valid
69        catalog index names.
70        Returns a simple empty list, a list with `Customer`
71        objects or a catalog result set with `Customer`
72        objects.
73
74        .. seealso:: `waeup.ikoba.customers.catalog.CustomersCatalog`
75
76        """
77        # Pass only given keywords to create FilteredCatalogQuery objects.
78        # This way we avoid
79        # trouble with `None` value ambivalences and queries are also
80        # faster (normally less indexes to ask). Drawback is, that
81        # developers must look into catalog to see what keywords are
82        # valid.
83        query = CustomersQuery(**kw)
84        return query.query()
85
86    def export(self, values, filepath=None):
87        """Export `values`, an iterable, as CSV file.
88
89        If `filepath` is ``None``, a raw string with CSV data is returned.
90        """
91        writer, outfile = self.get_csv_writer(filepath)
92        for value in values:
93            self.write_item(value, writer)
94        return self.close_outfile(filepath, outfile)
95
96    def export_all(self, site, filepath=None):
97        """Export customers into filepath as CSV data.
98
99        If `filepath` is ``None``, a raw string with CSV data is returned.
100        """
101        return self.export(self.filter_func(get_customers(site)), filepath)
102
103    def export_customer(self, customer, filepath=None):
104        return self.export(self.filter_func([customer]), filepath=filepath)
105
106    def export_filtered(self, site, filepath=None, **kw):
107        """Export items denoted by `kw`.
108
109        If `filepath` is ``None``, a raw string with CSV data should
110        be returned.
111        """
112        data = self.get_filtered(site, **kw)
113        return self.export(self.filter_func(data, **kw), filepath=filepath)
114
115
116class CustomerExporter(grok.GlobalUtility, CustomerExporterBase):
117    """Exporter for Customers.
118    """
119    grok.name('customers')
120
121    #: Fieldnames considered by this exporter
122    fields = tuple(sorted(iface_names(ICustomer))) + (
123        'password', 'state', 'history',)
124
125    #: The title under which this exporter will be displayed
126    title = _(u'Customers')
127
128    def mangle_value(self, value, name, context=None):
129        if name == 'history':
130            value = value.messages
131        if name == 'phone' and value is not None:
132            # Append hash '#' to phone numbers to circumvent
133            # unwanted excel automatic
134            value = str('%s#' % value)
135        return super(
136            CustomerExporter, self).mangle_value(
137            value, name, context=context)
138
139class CustomerDocumentExporter(grok.GlobalUtility, CustomerExporterBase):
140    """Exporter for CustomerDocument instances.
141    """
142    grok.name('customerdocuments')
143
144    #: Fieldnames considered by this exporter
145    fields = tuple(
146        sorted(iface_names(
147            ICustomerDocument,
148            exclude_attribs=False,
149            omit=['is_editable',
150                  'translated_state',
151                  'formatted_transition_date',
152                  'translated_class_name']))) + (
153            'customer_id',)
154
155    #: The title under which this exporter will be displayed
156    title = _(u'Customer Documents')
157
158    def filter_func(self, x, **kw):
159        return get_documents(x, **kw)
160
161    def mangle_value(self, value, name, context=None):
162        """Treat location values special.
163        """
164        if name == 'history':
165            value = value.messages
166        if context is not None:
167            customer = context.customer
168            if name in ('customer_id',) and customer is not None:
169                value = getattr(customer, name, None)
170        return super(
171            CustomerDocumentExporter, self).mangle_value(
172            value, name, context=context)
Note: See TracBrowser for help on using the repository browser.