Commit 0cee204e authored by LE GAC Renaud's avatar LE GAC Renaud
Browse files

New class List2 replacing List.

parent eada1854
......@@ -4,36 +4,24 @@
"""
import json
from gluon.tools import PluginManager
from plugin_dbui import Selector
from plugin_event import get_event_minimal
from plugin_event import do_title2, List2
def lists2():
def grid2():
"""New approach to generate lists.
"""
# instantiate the selector
selector = Selector(virtdb.selector)
# configuration
cfg = db.lists2[request.vars.id_lists2]
# instantiate the dataframe
func = PluginManager("event").event.sources[cfg.source].func
kwargs = selector.as_dict()
kwargs["id_events"] = cfg.id_events
print func
print kwargs
report = List2(request.vars.id_lists2)
df = func(**kwargs)
store = report.get_store_configuration()
grid = report.get_grid_configuration()
print df
title = do_title2(report)
# as an HTML table
# as an Ext JS grid
return "lists2"
response.view = "plugin_event/grid.html"
return dict(cfg_store=store, grid=grid, title=title)
......@@ -64,7 +64,7 @@ is_db = (ctrl == "plugin_dbui" and fnct in ("call", "csv", "dbui_conf")) or \
if is_db:
# register source for the reporting
event.Event.register_source("minimal event", event.get_event_minimal)
event.Event.register_sources()
event.Core.define_tables(db, T)
event.Report.define_tables(db, T)
......
# -*- coding: utf-8 -*-
"""report_tools module
"""
import json
from gluon import current
from gluon.storage import Storage
from gluon.tools import PluginManager
from plugin_dbui import Selector, Store
FIELD_TYPES = {"gridcolumn": "string",
"booleancolumn": "boolean",
"datecolumn": "date",
"numbercolumn": "float"}
MSG_NO_DATAINDEX = "The property dataIndex is missing."
MSG_NO_XTYPE = "The property xtype is missing."
class ReportException(BaseException):
pass
def do_title2(report):
"""Build the report title.
Args:
report (BaseReport): the report
Returns:
str:
"""
T = current.T
db = current.globalenv["db"]
config = report.config
selector = report.selector
# from the configuration
title = (config.title if config.title else config.name)
# add meta data
metadata = []
if selector.id_teams:
metadata.append(db.teams[selector.id_teams].team)
if selector.id_projects:
metadata.append(db.projects[selector.id_projects].project)
if selector.category:
metadata.append(selector.category)
if selector.id_people_categories:
code = db.people_categories[selector.id_people_categories].code
metadata.append(code)
# add period
if selector.year_start and not selector.year_end:
metadata.append(str(selector.year_start))
elif selector.year_start and selector.year_end:
years = (str(selector.year_start), str(selector.year_end))
metadata.append(T("from %s to %s", lazy=False) % years)
return "%s: %s" % (title, " / ".join(metadata))
class List2(object):
"""Generate the list and related configurations for ``Ext.grid.Panel``
and ``Ext.data.Store``.
Args:
id_list: report identifier in the database
Raises:
ReportException:
when the errors are found in the configuration of the grid columns.
"""
def __init__(self, id_list):
db = current.globalenv["db"]
virtdb = current.globalenv["virtdb"]
plg_evt = PluginManager("event").event
# ....................................................................
#
# Get the user selection criteria
#
self.selector = selector = Selector(virtdb.selector)
# ....................................................................
#
# Get the configuration for the list
#
self.config = config = db.lists2[current.request.vars.id_lists2]
# extract the configuration of the grid column and check it
#
# the same name is used for Ext JS grid column, the DataFrame column
# and the field of the Ext JS store
grid_columns = [Storage(el) for el in json.loads(config.columns)]
[self._check_column(el) for el in grid_columns]
# ....................................................................
#
# Fill the report with data (DataFrame)
#
criteria = selector.as_dict()
criteria["id_events"] = config.id_events
func = plg_evt.sources[config.source].func
df = func(**criteria)
if not df.empty and config.transform not in (None, ""):
df.eval(config.transform, inplace=True)
# ....................................................................
#
# Configure Ext JS store
#
self.store = store = Store(data=[], fields=[], sorters=[])
[self._add_store_fields(col) for col in grid_columns]
[self._add_store_sorter(sorter) for sorter in config.sorters]
store.groupField = config.group_field
# add the data to the store
#
# extract the list of records as a JSON-string
# at this stage date/time are converted as an ISO8601 string
#
# convert the JSON-string into a list
#
if not df.empty:
data = df.to_json(orient="records", date_format="iso")
store.data = json.loads(data)
# ....................................................................
#
# Configure Ext JS grid
#
self.grid = Storage(columns=grid_columns, features=[])
features = config.features
if features not in (None, ''):
self.grid.features = json.loads(features)
def _add_store_fields(self, column):
"""Add ``Ext.data.Field`` to the store configuration
It is derived from the ``Ext.grid.Column`` configuration.
Args:
column (gluon.storage.Storage):
configuration for ``Ext.grid.Column``
"""
# protection against rownumberer column
if not column.dataIndex:
return
cfg = Storage(name=column.dataIndex,
type=FIELD_TYPES[column.xtype])
self.store.fields.append(cfg)
def _add_store_sorter(self, field):
"""Add sorter to the store configuration.
Args:
field (str): name of the DataFrame column either foo or ~foo.
"""
sorter = Storage(property=field.replace("~", ""))
if field.startswith("~"):
sorter.direction = "DESC"
self.store.sorters.append(sorter)
def _check_column(self, column):
"""Check column configuration:
- Raise an exception if xtype is not defined
- Raise an exception if dataIndex is not defined
Args:
column (gluon.storage.Storage):
"""
T = current.T
xtype = column.xtype
if not xtype:
raise ReportException(T(MSG_NO_XTYPE))
dataIndex = column.dataIndex
if (xtype != "rownumberer" and dataIndex is None):
raise ReportException(T(MSG_NO_DATAINDEX))
def get_grid_configuration(self):
"""Get the configuration for the ``Dbui.grid.Panel``.
Returns:
gluon.storage.Storage:
the keys are ``columns`` and ``features`` and the
corresponding values are list of dictionary.
"""
return self.grid
def get_store_configuration(self):
"""Get the configuration for the ``Ext.data.Store``.
Note:
The name of the ``Ext.data.Field`` is extract from the column
definition of the list. it matches the name of the columns in
the DataFrame.
Returns:
plugin_dbui.Store: the configuration of the ``Ext.data.Store``.
"""
return self.store
......@@ -267,7 +267,7 @@ class ViewportUi(object):
for row in db(db.lists2.id > 0).select(orderby=db.lists2.name):
panel = selector_panel
panel.baseUrl = URL("new_report", "lists2")
panel.baseUrl = URL("new_report", "grid2")
panel.baseParams = {"id_lists2": row.id}
add_child(row.name, panel)
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment