Report.py 16.3 KB
Newer Older
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
##############################################################################
#
# Copyright (c) 2002 Nexedi SARL and Contributors. All Rights Reserved.
#                    Jean-Paul Smets-Solanes <jp@nexedi.com>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

29 30
from Globals import InitializeClass, DTMLFile, get_request
from AccessControl import ClassSecurityInfo
Jean-Paul Smets's avatar
Jean-Paul Smets committed
31 32
from Products.PythonScripts.Utility import allow_class
from Products.Formulator.DummyField import fields
33
from Products.Formulator.Form import ZMIForm
34
from zLOG import LOG, WARNING
Jean-Paul Smets's avatar
Jean-Paul Smets committed
35

36
from urllib import quote
Jérome Perrin's avatar
Jérome Perrin committed
37
from warnings import warn
Jean-Paul Smets's avatar
Jean-Paul Smets committed
38 39 40 41
from Products.ERP5Type import PropertySheet

from Form import ERP5Form
from Form import create_settings_form as Form_create_settings_form
42
from Selection import Selection
Jean-Paul Smets's avatar
Jean-Paul Smets committed
43 44 45 46

def create_settings_form():
    form = Form_create_settings_form()
    report_method = fields.StringField(
47 48 49 50 51 52
         'report_method',
         title='Report Method',
         description=('The method to get a list of items (object, form,'
                      ' parameters) to aggregate in a single Report'),
         default='',
         required=0)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68

    form.add_fields([report_method])
    return form

manage_addReport = DTMLFile("dtml/report_add", globals())

def addERP5Report(self, id, title="", REQUEST=None):
    """Add form to folder.
    id     -- the id of the new form to add
    title  -- the title of the form to add
    Result -- empty string
    """
    # add actual object
    id = self._setObject(id, ERP5Report(id, title))
    # respond to the add_and_edit button if necessary
    add_and_edit(self, id, REQUEST)
69
    return ''
70

Jean-Paul Smets's avatar
Jean-Paul Smets committed
71 72 73 74
class ERP5Report(ERP5Form):
    """
        An ERP5Form which allows to aggregate a list of 
        forms each of which is rendered on an object with parameters.
75

76
        Application: create an accounting book from ERP5 objects 
77

Jean-Paul Smets's avatar
Jean-Paul Smets committed
78
        - Display the total of each account (report)
79

Jean-Paul Smets's avatar
Jean-Paul Smets committed
80
        - List all accounts
81

Jean-Paul Smets's avatar
Jean-Paul Smets committed
82
        - Display the transactions of each account (one form with listbox)
83

Jean-Paul Smets's avatar
Jean-Paul Smets committed
84
        - List all clients
85

Jean-Paul Smets's avatar
Jean-Paul Smets committed
86
        - Display the transactions of each client (one form with listbox)
87

Jean-Paul Smets's avatar
Jean-Paul Smets committed
88
        - List all vendors
89

Jean-Paul Smets's avatar
Jean-Paul Smets committed
90
        - Display the transactions of each vendor (one form with listbox)
91 92 93 94 95 96

        TODO:
        - Make sure that multiple reports can be run in parallel without conflicts

        - Make sure that multiple reports can be run in parallel without losing
          consistency (ie. concurrent update of the selection)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
    """
    meta_type = "ERP5 Report"
    icon = "www/Form.png"

    # Declarative Security
    security = ClassSecurityInfo()

    # Declarative properties
    property_sheets = ( PropertySheet.Base
                      , PropertySheet.SimpleItem)

    # Constructors
    constructors =   (manage_addReport, addERP5Report)

    # This is a patched dtml formOrder
    security.declareProtected('View management screens', 'formOrder')
    formOrder = DTMLFile('dtml/formOrder', globals())

    # Default Attributes
    report_method = None
117

Jean-Paul Smets's avatar
Jean-Paul Smets committed
118 119 120
    # Special Settings
    settings_form = create_settings_form()

121 122 123
    # Default Attributes
    pt = 'report_view'

Jean-Paul Smets's avatar
Jean-Paul Smets committed
124 125
    # Proxy method to PageTemplate
    def __call__(self, *args, **kwargs):
126 127 128
        if not self.report_method:
          raise KeyError, 'report method is not set on the report'

Jean-Paul Smets's avatar
Jean-Paul Smets committed
129
        if not kwargs.has_key('args'):
130
          kwargs['args'] = args
Jean-Paul Smets's avatar
Jean-Paul Smets committed
131
        form = self
132 133 134
        obj = getattr(form, 'aq_parent', None)
        if obj is not None:
          container = obj.aq_inner.aq_parent
Jean-Paul Smets's avatar
Jean-Paul Smets committed
135 136
        else:
          container = None
137 138 139
        pt = getattr(self, self.pt)

        report_method = getattr(obj, self.report_method)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
140 141 142
        extra_context = self.pt_getContext()
        extra_context['options'] = kwargs
        extra_context['form'] = self
143
        extra_context['request'] = get_request()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
144
        extra_context['container'] = container ## PROBLEM NOT TAKEN INTO ACCOUNT
145
        extra_context['here'] = obj
Jean-Paul Smets's avatar
Jean-Paul Smets committed
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
        extra_context['report_method'] = report_method
        return pt.pt_render(extra_context=extra_context)

    def _exec(self, bound_names, args, kw):
        pt = getattr(self,self.pt)
        return pt._exec(self, bound_names, args, kw)

def add_and_edit(self, id, REQUEST):
    """Helper method to point to the object's management screen if
    'Add and Edit' button is pressed.
    id -- id of the object we just added
    """
    if REQUEST is None:
        return
    try:
        u = self.DestinationURL()
Yoshinori Okuji's avatar
Yoshinori Okuji committed
162
    except AttributeError:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
        u = REQUEST['URL1']
    if REQUEST['submit'] == " Add and Edit ":
        u = "%s/%s" % (u, quote(id))
    REQUEST.RESPONSE.redirect(u+'/manage_main')

def manage_add_report(self, id, title="", unicode_mode=0, REQUEST=None):
    """Add form to folder.
    id     -- the id of the new form to add
    title  -- the title of the form to add
    Result -- empty string
    """
    # add actual object
    id = self._setObject(id, ZMIForm(id, title, unicode_mode))
    # respond to the add_and_edit button if necessary
    add_and_edit(self, id, REQUEST)
    return ''

class ReportSection:
181
  """ A section in an ERP5Report.
182

183 184 185 186
  ERP5 Reports are made of sections, which are some standards ERP5 Forms
  rendered in a single document.
  To create a report section, you have to define which object will be
  the context of the form, the id of the form, and dictionnaries to
187 188
  override the values of the selection parameters in the constructor of
  the ReportSection.
189
  """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
190 191 192
  meta_type = "ReportSection"
  security = ClassSecurityInfo()

193 194 195 196 197 198 199 200 201 202 203 204
  def __init__(self, path='',
                     form_id='',
                     method_id=None,
                     title=None, 
                     translated_title=None, 
                     level=1,
                     param_list=None,
                     param_dict=None,
                     selection_name=None, 
                     selection_params=None,
                     listbox_display_mode=None, 
                     selection_columns=None,
205
                     selection_stats=None,
206
                     selection_sort_order=None,
207 208
                     selection_report_path=None,
                     selection_report_list=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
209 210 211
    """
      Initialize the line and set the default values
      Selected columns must be defined in parameter of listbox.render...
212 213 214 215

      In ReportTree listbox display mode, you can override :
        selection_report_path, the root category for this report 
        selection_report_list, the list of unfolded categories (defaults to all)      
Jean-Paul Smets's avatar
Jean-Paul Smets committed
216
    """
217

Jean-Paul Smets's avatar
Jean-Paul Smets committed
218 219
    self.path = path
    self.form_id = form_id
220
    self.title = title
Jérome Perrin's avatar
Jérome Perrin committed
221 222
    if translated_title is not None:
      warn("Don't use translated_title, but title directly", DeprecationWarning)
223 224 225 226 227 228 229
    self.translated_title = translated_title
    self.level = level
    self.saved_request = {}
    self.selection_name = selection_name
    self.selection_params = selection_params
    self.listbox_display_mode = listbox_display_mode
    self.selection_columns = selection_columns
230
    self.selection_stats = selection_stats
231
    self.selection_sort_order = selection_sort_order
232
    self.saved_selections = {}
233 234
    self.selection_report_path = selection_report_path
    self.selection_report_list = selection_report_list
235
    self.saved_request_form = {}
236 237 238 239
    self.param_dict = param_dict or {}
    self.param_list = param_list or []
    self.method_id = method_id

Jean-Paul Smets's avatar
Jean-Paul Smets committed
240 241 242 243
  security.declarePublic('getTitle')
  def getTitle(self):
    return self.title

244 245
  security.declarePublic('getTranslatedTitle')
  def getTranslatedTitle(self):
Jérome Perrin's avatar
Jérome Perrin committed
246
    # deprecated: use title instead (with a translated string)
247 248 249 250 251 252
    return self.translated_title

  security.declarePublic('getLevel')
  def getLevel(self):
    return self.level

Jean-Paul Smets's avatar
Jean-Paul Smets committed
253 254 255 256 257 258
  security.declarePublic('getPath')
  def getPath(self):
    return self.path

  security.declarePublic('getObject')
  def getObject(self, context):
259 260 261 262 263
    object = context.getPortalObject().restrictedTraverse(self.path)
    if self.method_id is not None:

      object = getattr(object, self.method_id)(*self.param_list, **self.param_dict)
    return object
Jean-Paul Smets's avatar
Jean-Paul Smets committed
264 265 266 267

  security.declarePublic('getFormId')
  def getFormId(self):
    return self.form_id
268

269
  _no_parameter_ = []
270

271
  security.declarePublic('pushReport')
272
  def pushReport(self, context, render_prefix=None):
273 274 275
    REQUEST = get_request()
    for k,v in self.param_dict.items():
      self.saved_request[k] = REQUEST.form.get(k, self._no_parameter_)
276
      REQUEST.form[k] = v
277

278
    portal_selections = context.portal_selections
279
    selection_list = [self.selection_name]
280
    if self.getFormId() and hasattr(context[self.getFormId()], 'listbox') :
281
      selection_name = context[self.getFormId()].listbox.get_value('selection_name')
282 283
      if render_prefix is not None:
        selection_name = '%s_%s' % (render_prefix, selection_name)
284
        REQUEST.other['prefixed_selection_name'] = selection_name
285
      selection_list += [selection_name]
286 287
    # save report's selection and orignal form's selection,
    #as ListBox will overwrite it
288 289
    for selection_name in selection_list :
      if selection_name is not None :
290 291
        if not self.saved_selections.has_key(selection_name) :
          self.saved_selections[selection_name] = {}
292
        if self.selection_report_list is not None:
293 294
          selection = portal_selections.getSelectionFor(selection_name,
                                                        REQUEST=REQUEST)
295 296 297 298
          if selection is None:
            selection = Selection()
            portal_selections.setSelectionFor(selection_name, selection, 
                                              REQUEST=REQUEST)
299 300 301
          self.saved_selections[selection_name]['report_list'] = \
               selection.getReportList()
          selection.edit(report_list=self.selection_report_list)
302
        if self.selection_report_path is not None:
303 304
          selection = portal_selections.getSelectionFor(selection_name,
                                                        REQUEST=REQUEST)
305 306 307
          self.saved_selections[selection_name]['report_path'] = \
               selection.getReportPath()
          selection.edit(report_path=self.selection_report_path)
308
        if self.listbox_display_mode is not None:
309
          self.saved_selections[selection_name]['display_mode'] = \
310
               portal_selections.getListboxDisplayMode(selection_name,
311 312 313 314 315 316
                                                       REQUEST=REQUEST)
          # XXX Dirty fix, to be able to change the display mode in form_view
          REQUEST.list_selection_name = selection_name
          portal_selections.setListboxDisplayMode(
                                           REQUEST, self.listbox_display_mode,
                                           selection_name=selection_name)
317
        if self.selection_params is not None:
318
          params = portal_selections.getSelectionParams(
319
                               selection_name, REQUEST=REQUEST)
320 321
          self.saved_selections[selection_name]['params'] = params.copy()
          params.update(self.selection_params)
322
          portal_selections.setSelectionParamsFor(selection_name,
323
                               params, REQUEST=REQUEST)
324 325
        if self.selection_columns is not None:
          self.saved_selections[selection_name]['columns'] =  \
326 327 328 329
               portal_selections.getSelectionColumns(selection_name,
                                                     REQUEST=REQUEST)
          portal_selections.setSelectionColumns(selection_name,
                                  self.selection_columns, REQUEST=REQUEST)
330 331
        if self.selection_sort_order is not None:
          self.saved_selections[selection_name]['sort_order'] =  \
332 333 334 335
               portal_selections.getSelectionSortOrder(selection_name,
                                                       REQUEST=REQUEST)
          portal_selections.setSelectionSortOrder(selection_name,
                      self.selection_sort_order, REQUEST=REQUEST)
336 337 338 339 340 341
        if self.selection_stats is not None:
          self.saved_selections[selection_name]['stats'] =  \
               portal_selections.getSelectionStats(selection_name,
                                                     REQUEST=REQUEST)
          portal_selections.setSelectionStats(selection_name,
                                  self.selection_stats, REQUEST=REQUEST)
342

343
    self.saved_request_form = REQUEST.form
344

345
  security.declarePublic('popReport')
346
  def popReport(self, context, render_prefix=None):
347 348 349
    REQUEST = get_request()
    for k,v in self.param_dict.items():
      if self.saved_request[k] is self._no_parameter_:
350 351
        if REQUEST.form.has_key(k):
          del REQUEST.form[k]
352
      else:
353
        REQUEST.form[k] = self.saved_request[k]
354

355
    portal_selections = context.portal_selections
356
    selection_list = []
357
    if self.getFormId() and hasattr(context[self.getFormId()], 'listbox') :
358
      selection_name = context[self.getFormId()].listbox.get_value('selection_name')
359
      if render_prefix is not None:
360
        del REQUEST.other['prefixed_selection_name']
361 362 363 364
        # Return before cleanup, because there is no interest in cleaning up
        # what won't be shared.
        return
      selection_list += [selection_name]
365 366 367
    selection_list += [self.selection_name]
    # restore report then form selection
    for selection_name in selection_list:
368
      if selection_name is not None:
369
        if self.selection_report_list is not None:
370 371 372 373
          selection = portal_selections.getSelectionFor(
                              selection_name, REQUEST=REQUEST)
          selection.edit(report_list =
                self.saved_selections[selection_name]['report_list'])
374
        if self.selection_report_path is not None:
375 376 377 378
          selection = portal_selections.getSelectionFor(
                selection_name, REQUEST=REQUEST)
          selection.edit(report_path =
                self.saved_selections[selection_name]['report_path'])
379
        if self.listbox_display_mode is not None:
380 381 382 383 384 385
          # XXX Dirty fix, to be able to change the display mode in form_view
          REQUEST.list_selection_name = selection_name
          portal_selections.setListboxDisplayMode(
                       REQUEST,
                       self.saved_selections[selection_name]['display_mode'],
                       selection_name=selection_name)
386
        if self.selection_params is not None:
387
          # first make sure no parameters that have been pushed are erased 
388 389
          portal_selections.setSelectionParamsFor(selection_name,
                                                  {}, REQUEST=REQUEST)
390
          # then restore the original params
391
          portal_selections.setSelectionParamsFor(selection_name,
392 393
                      self.saved_selections[selection_name]['params'],
                      REQUEST=REQUEST)
394
        if self.selection_columns is not None:
395
          portal_selections.setSelectionColumns(selection_name,
396 397
                      self.saved_selections[selection_name]['columns'],
                      REQUEST=REQUEST)
398
        if self.selection_sort_order is not None:
399
          portal_selections.setSelectionSortOrder(selection_name,
400 401
                      self.saved_selections[selection_name]['sort_order'],
                      REQUEST=REQUEST)
402 403 404 405
        if self.selection_stats is not None:
          portal_selections.setSelectionStats(selection_name,
                      self.saved_selections[selection_name]['stats'],
                      REQUEST=REQUEST)
406

407
    REQUEST.form = self.saved_request_form
408

Jean-Paul Smets's avatar
Jean-Paul Smets committed
409
InitializeClass(ReportSection)
410
allow_class(ReportSection)