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

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

Singular not plural.

  • Property svn:keywords set to Id
File size: 5.9 KB
RevLine 
[12006]1## $Id: export.py 12076 2014-11-28 06:56:38Z henrik $
[11958]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 (
[12032]25    IExtFileStore, IFileStoreNameChooser)
[11958]26from waeup.ikoba.interfaces import MessageFactory as _
27from waeup.ikoba.customers.catalog import CustomersQuery
28from waeup.ikoba.customers.interfaces import (
[12006]29    ICustomer, ICSVCustomerExporter, ICustomerDocument)
[11958]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.
[12006]35EXPORTER_NAMES = ('customers', 'customerdocuments')
[11958]36
[11985]37
[11958]38def get_customers(site, cust_filter=CustomersQuery()):
39    """Get all customers registered in catalog in `site`.
40    """
41    return cust_filter.query()
42
[12006]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
[11985]51
[12006]52
[11958]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
[12076]116class CustomerExporter(grok.GlobalUtility, CustomerExporterBase):
[11958]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(
[12076]136            CustomerExporter, self).mangle_value(
[11958]137            value, name, context=context)
[12006]138
[12076]139class CustomerDocumentExporter(grok.GlobalUtility, CustomerExporterBase):
[12006]140    """Exporter for CustomerDocument instances.
141    """
142    grok.name('customerdocuments')
143
144    #: Fieldnames considered by this exporter
145    fields = tuple(
146        sorted(iface_names(
[12018]147            ICustomerDocument,
148            exclude_attribs=False,
[12053]149            omit=['is_editable',
150                  'translated_state',
151                  'formatted_transition_date',
[12056]152                  'translated_class_name']))) + (
[12006]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        """
[12007]164        if name == 'history':
165            value = value.messages
[12006]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(
[12076]171            CustomerDocumentExporter, self).mangle_value(
[12006]172            value, name, context=context)
Note: See TracBrowser for help on using the repository browser.