Note: You are currently viewing documentation for Moodle 2.4. Up-to-date documentation for the latest stable version of Moodle may be available here: Configurable reports.

Configurable reports: Difference between revisions

From MoodleDocs
(New page: == Instalación == # Descargar el fichero de instalación del bloque "Custom Report" y descomprimirlo en el directorio '''/blocks''' del directorio de instalación de Moodle. # Iniciar se...)
 
 
(25 intermediate revisions by 7 users not shown)
Line 1: Line 1:
== Instalación ==
{{Infobox plugin
|type = Block
|entry = https://moodle.org/plugins/view.php?plugin=block_configurable_reports
|tracker = http://tracker.moodle.org/browse/CONTRIB/component/10753
|discussion = https://moodle.org/mod/forum/view.php?id=7979
|maintainer = [[User:Juan Leyva|Juan Leyva]]
|float = right
}}


# Descargar el fichero de instalación del bloque "Custom Report" y descomprimirlo en el directorio '''/blocks''' del directorio de instalación de Moodle.
== Installation ==
# Iniciar sesión como administrador y pulsar en el enlace Notificaciones, dentro del bloque de administración del sitio.


Para más información véase [https://docs.moodle.org/en/Installing_contributed_modules_or_plugins Installing contributed modules or plugins] (en inglés)
# Download the Configurable Reports installation file and unzip it to the '''\blocks''' directory in your Moodle folder.
# Be sure that the final name of the directory is: configurable_reports, the full path in your Moodle installation will be blocks/configurable_reports
# Login to Moodle as Administrator and click Notifications under Site Administration.


== Resumen ==


Este bloque sirve para generar informes a medida de Moodle.
For more information see [[Installing contributed modules or plugins]]


Ha sido diseñado de forma modular para permitir a los desarrolladores crear nuevos plugins en menos de una hora.
== Overview ==


=== ¿Quién puede crear informes a medida? ===
This block is a Moodle custom reports builder.


Cualquier usuario que tenga los permisos '''block/custom_reports:managereports'', '''blocks/custom_reports:manageownreports''' o '''block/custom_report/managesqlreports''' asignados en un CURSO o en el SITIO (estos permisos se definen durante la instalación del bloque).
It is designed in a modular way to allow developers to create new plugins in less than an hour.


=== ¿Qué tipo de informes puedo crear? ===


* Informes de cursos, con informaciones relativas a los cursos.
'''Who can create custom reports?'''
* Informes de usarios, con informaciones relativas a los usuarios y su actividad en un curso.
* Informes SQL personalizados, consultas SQL personalizadas. Este bloque puede usar las mismas consultas SQL que el plugin  [http://moodle.org/mod/data/view.php?d=13&rid=2884 de consultas SQL personalizadas de Tim Hunt].


Nota para los desarrolladores: se pueden crear sus propios tipos de informes.
Anyone with block, managereports or manageownreports permissions at SITE level or COURSE level.


=== ¿Quién puede ver los informes? ===


Cuando se crea un informe se puede elegir qué usuarios pueden verlo.
'''What type of reports can I create?'''


Los informes se muestra en un bloque del curso o en la portada del sitio.
- Courses reports, with information regarding courses.


== Cómo crear un informe ==
- Categories reports, with information regarding categories. A courses report can be embedded in this type of report.


Este es un proceso muy sencillo. Si va a crear un informe para un curso, necesita añadir el bloque en el curso y pulsar sobre "Gestionar informes". Por su parte, para los informes del sitio, añada el bloque en la portada y pulse sobre el enlace "Gestionar informes".
- Users reports, with information regarding users and their activity in a course.


Necesita introducir un nombre, una descripción (opcional) y tiene que elegir el tipo de informe, paginación y formatos de exportación.
- Timeline reports, this is a special type of report that displays a timeline. A course or user report can be embedded in this timeline showing data depending on the start and end time of the current row.


Dependiendo del tipo de informe elegido habrá más o menos pestañas. Estas son las pestañas para los informes de cursos y usuarios:
- Custom SQL Reports, custom SQL queries. This block can use the same SQL queries as [http://moodle.org/mod/data/view.php?d=13&rid=2884 Tim Hunt's Custom SQL queries] plugin.


* '''Columnas''': Aquí se puede elegir las diferentes columnas del informe, dependiendo del tipo de informe (Nombre del curso, Nombre de pila del usuarios, etc.)
Note for developers: You can create your own type of reports.
* '''Condiciones''': Aquí se pueden definir las condiciones (p.ej., sólo cursos de esta categoría, sólo usuarios de España, etc.)
 
* '''Ordenación''': Aquí se puede elegir como ordenar el informe usando los campos y direcciones (ascendente, descendente).
 
* '''Filtros''': Aquí se puede elegir qué filtros se visualizarán.
'''Who can view the reports?'''
* '''Plantilla''': Se puede modificar la disposición del informe creando una plantilla.
 
* '''Permisos''': Aquí se puede escoger quien puede ver el informe.
When you create a report you can select which users can view it.
* '''Cálculos''': Aquí se pueden añadir cálculos para las columnas; p.ej., media del número de usuarios matriculados en los cursos.
 
* '''Gráficas''': Aquí se pueden añadir gráficas al informe basadas en las columnas del informe y los valores.
The reports are displayed in a block in the course or site frontpage.
* '''Ver informes''': Auto explicativa
 
== Creating a report ==
 
 
This is a very simple process. 
 
If you are going to create a report for a course, you have to add the block in the course and click in the "Manage reports" link.
 
On the other hand, for site reports, add the block in the frontpage and click in the "Manage reports" link.
 
You must enter a name, an optional description, and you have to choose the type of report, pagination and exports formats.
 
Depending on the report choosen, there will be more or less tabs. These are the tabs for the courses and users report:
 
'''Columns''': Here you can choose the differents columns of your report depending on the type of report. (Course Name, User firstname, etc..)
 
'''Conditions''': Here you can define the conditions (i.e, only courses from this category, only users from Spain, etc.)
 
'''Ordering''': Here you can choose how to order the report using fields and directions.
 
'''Filters''': Here you can choose which filters will be displayed.
 
'''Template''': You can modify the report's layout by creating a template.
 
'''Permissions''': Here you can choose who can view a report.
 
'''Calculations''': Here you can add calculations for columns, i.e: average of number of users enrolled in courses
 
'''Plots''': Here you can add graphs to your report based on the report columns and values.
 
'''View report''': Self explanatory


== Tutorial ==
== Tutorial ==


=== Como crear un informe de usuario ===
=== Creating a users' report ===
 
Requirements: ''Users from Spain, but not from Madrid, in this course. This report can be viewed only by users from Spain. A filter based on the user's city must be displayed. A pie plot showing the users' cities is required. A calculation table showing the total forum post views is required. The report must be ordered by users' lastname.''
 
 
Let's see how easy it is!
 
First of all, install the block.
 
Go to the course where the report will be created.


Requisitos: ''Usuarios de España, pero no de Madrid, en este curso. Este informe se puede ver sólo por usuarios de España. Hay que visualizar un filtro basado en la ciudad del usuario. Se pide mostrar una gráfica de tarta con las ciudades de los usuarios. Se pide una tabla calculada que muestre el total de vistas de mensajes de foros El informe debe ordenarse por el apellido de los usuarios''.
Add an instance of the Custom Reports block.


¡Veamos qué fácil es!
Click on "Manage reports"


# Primero de todo, instale el bloque.
Click on "Add report"
# Vaya al curso donde se quiere crear el informe.
# Añada una instancia del bloque "Informes personalizados".
# Pulse en "Gestionar informes".
# Pulse en "Añadir informe".
# Introduzca un nombre, una descripción y elija "Informes de usuarios" como tipo de informe.
# Opcionalmente puede marcar las casillas "Exportar en formato ODS" y "Exportar en formato XLS" si desea poder exportar el informe en alguno de estos formatos.
# Pulse el botón "Agregar".
# Se guardará el informe y se le redirigirá a la pestaña denominada "Columnas".


==== Añadir columnas ====
Enter a name, a description and choose "Users report" as Type of Report


Aquí se puede efinir las propiedades de la tabla del informe como anchura, alineación, relleno de las celdas, espaciados de las celdas, etc.
The report will be saved and you will be redirected to the first Tab named "Columns".
 
 
'''Adding Columns'''
 
Here you can define the report table properties, width, align, cell padding, cell spacing, etc.
 
Add a Column called "User profile field"
 
Choose the field "firstname" and enter a name for the column in the text field. You can leave the rest of elements blank.
 
Repeat the process above for the lastname and city fields.
 
Add a Column called "User module actions".
 
Choose a module from the list, in this example, a forum.


# Añada una columna de tipo "Campo del perfiel de usuario"
# Teclee un nombre para esta columna y en el desplegable llamado "Columna" elija el valor "firstname". Puede dejar en blanco el resto de elementos. Pulse sobre el botón "Agregar".
# Repita el proces para los campos "lastname" y "city".
# Añada una nueva columna de tipo "Acciones de usuario en el módulo".
# Teclee un nombre parae esta columna y elija un módulo de la lista, en nuestro caso, el foro sobre el que queremos elaborar el informe. Pulse sobre el botón "Agregar".
   
   
==== Añadir condiciones ====
'''Adding Conditions'''
 
Click on the Conditions Tab.
 
Add a Condition named "User field Condition".
 
Choose the column "Country", the Operator "=", and enter the value "ES" (this is the international code for Spain as Moodle stores it).
 
Add a Condition named "User field Condition".
 
Choose the column "city", the Operator "<>", and enter the value "Madrid".
 
Add a Condition named "Users in current report course".
 
These are the main conditions of the reports. Note that at the bottom there is a text box called condition, with this text:
 
"c2 and c1 and c3"
 
Here you can define a logic condition, in this case, we don't need to edit this condition but you can create complex expressions like:
 
(c1 and c2) or (c4 and c3)
 
 
'''Adding Ordering'''
 
Click on the Ordering Tab.
 
Add a ordering named "User field ordering".
 
Choose the column "Lastname" and the ordering "ASC" (Ascending).
 
 
'''Adding Filters'''
 
Click on the Filters Tab.
 
Add a filter named "User field filter".
 
Choose city.


# Pulse en la pestaña "Condiciones".
# Añada una condición del tipo "Condición sobre campo de perfil del usuario".
# Escoga la columna "country" de la lista desplegable, el operador "=" e introduzca el valor "ES" (este es el código internacional para España tal y como lo almancena Moodle internamente). Pulse el botón "Agregar".
# Añada una nueva condición del tipo "Condición sobre campo de perfil del usuario".
# Escoja la columna "city", el operador "<>" e introduzca el valor "Madrid". Pulse el botón "Agregar".
# Añada una condición del tipo "Usuarios en el curso donde se ha creado el informe" y escoja el valor "Student". Pulse el botón "Agregar".


Estas son las condiciones principales del informe. Note que en la parte inferior hay una caja de texto llamada "Condición lógica" con el texto:
'''Adding Permissions'''


  c2 and c1 and c3
Click on the Permissions Tab.


Aquí se puede definir una condición lógica cualquiera. En este caso no necesitamos editar esta condición, pero puede crear expresiones complejas como:
Choose "User field Value".


  (c1 and c2) or (c4 and c3)
Choose the column "Country", and enter the value "ES".


==== Añadir ordenación ====
Here you can add more permissions and a logic condition to be achieved.


# Pulse en la pestaña "Ordenación".
# Añada una ordenación del tipo "Ordenación por campo de usuario".
# Escoja la columna "lastname" y la ordenación "ASC" (ascendente). Pulse "Agregar".


==== Añadir filtros ====
'''Adding Calculations'''


# Pulse en la pestaña "Filtros".
Click on the Calculations tab.
# Añáda un filtro del tipo "Filtro sobre campo del perfil del usuario".
# Escoja el campo "city". Pulse "Agregar".


==== Añadir permisos ====
Choose Sum.


# Pulse en la pestaña "Permisos".
Choose the column "User module actions".
# Añada un permiso del tipo "Valor en el perfil del usuario".
# Escoja la columna "country" e introduzca el valor "ES". Pulse el botón "Agregar".


Aquí puede añadir más tipos de permisos y la condición lógica que debe cumplirse en caso de tener más un tipo de permiso.


==== Añadir cálculos ====
'''Adding Plots'''


# Pulse en la pestaña "Cálculos".
Click on the Plots tab.
# Añada un cálculo de tipo "Suma".
# Escoja la columna que representa la acción del usuario en el módulo (en nuestro caso el foro).


==== Añadir gráficas ====
Choose "Pie".


# Pulse en la pestaña "Gráficas".
Choose the colum "City" as Name and Value.
# Elija el tipo de gráfico "Tarta".
# Escoja la columna "city" tanto para la opción "Nombre" como para la opción "Valor". Pulse el botón "Agregar".


Por último, añada unos cuantos usuarios en Moodle con el país "España" y diferentes ciudades: Madrid, Barcelona, Sevilla, etc. y pruebe a visualizar el informe pulsando en la pestaña "Ver informe".


Si ha habilitado las opciones de exportar el informe en alguno de los formatos , podrá descargarlo pulsando sobre los enlaces que aparecen en la parte inferior del informe.
Finally, add a few users in Moodle with the country Spain, and different cities, Madrid, Barcelona, Seville, etc. and test the report.


[[#Informe_de_usuarios | Ver pantalla mostrando el informe]]
You can download the report in different formats (ods and xls), remember to check these options in the report page.


=== Crear un informe SQL ===
[[blocks/configurable_reports/#Users_report | See screenshot]]


Puede encontrar un montón de informes SQL aquí: [https://docs.moodle.org/en/ad-hoc_contributed_reports ad-hoc contributed reports]
=== Creating a SQL Report ===


Puesto que este bloque puede utilizar los informes de consultas SQL personalizadas de Tim Hunt, puede utilizar cualquier consulta.
You can find a lot of SQL Reports here: [[ad-hoc contributed reports]]


Recuerde añadir un filtro de tipo "Filtro de fechas" si va a usar informes con valores temporales.
Since this block supports Tim Hunt's CustomSQL Queries Reports, you can use any query.


Para crear un informe de este tipo:
Remember to add a "Time filter" if you are going to use reports with time tokens.
 
 
First of all, install the block.
 
Go to the course where the report will be created.
 
Add an instance of the Custom Reports block.
 
Click on "Manage reports".
 
Click on "Add report
 
Enter a name, description, choose "SQL" as Type of Report
 
The report will be saved and you redirect to the first Tab named "Custom SQL"
 
Add this query (''Courses activity''):


# Pulse en el enlace "Gestionar informes" del bloque de informes personalizados
# Pulse en "Añadir informe".
# Introduzca un nombre y una descripción para el informe y seleccione "Informe SQL" como el tipo del informe.
# Opcionalmente puede marcar las casillas "Exportar en formato ODS" y "Exportar en formato XLS" si desea poder exportar el informe en alguno de estos formatos.
# Pulse el botón "Agregar".
# Se guardará el informe y se le redirigirá a la pestaña denominada "Sentencia SQL".
# Añada esta consulta (''Actividad de los cursos''):
<code sql>
<code sql>
SELECT COUNT(l.id) AS hits, l.course courseId, c.fullname coursename
SELECT COUNT(l.id) hits, l.course courseId, c.fullname coursename
FROM prefix_log l INNER JOIN prefix_course c ON l.course = c.id
FROM prefix_log l INNER JOIN prefix_course c ON l.course = c.id
GROUP BY courseId
GROUP BY courseId
ORDER BY hits DESC
ORDER BY hits DESC
</code>
</code>
y pulse el botón "Guardar cambios".
# Vaya a la pestaña "Cálculos".
# Añada un cálculo de tipo "Suma" y escoja la columna "hits". Pulse el botón "Agregar".
# Vaya a la pestaña "Gráficas".
# Elija el tipo de gráfico "Tarta".
# Escoja la columna "hits" tanto para la opción "Nombre" como para la opción "Valor". Pulse el botón "Agregar".
# Pruebe a visualizar el informe pulsando en la pestaña "Ver informe".


Ahí lo tiene, un informe con una gráfica y cálculos basados en una consulta SQL.
''NOTE: use the generic term "prefix_" for your table names in queries, not the actual prefix in the database and config.php. E.g. prefix_course rather than mdl_course.''
 
 
Go to Calculations Tab
 
Add a Sum calculation, choose the hits column
 
 
Go to Plot
 
Add a Pie graph, choosing coursename as Name and hits as value
 
So, here you have a report with a Graph and calculations based on a SQL Query.
 
 
You can add a Course filter, it's very easy:
 
Go to filters, choose Courses


Puede añadir un filtro de cursos, es muy sencillo:
Edit the Custom SQL query:


# Vaya a la pestaña "Filtros" y añada un filtro de tipo "Cursos".
# Edite la consulta SQL y ponga lo siguiente:
<code sql>
<code sql>
SELECT COUNT(l.id) AS hits, l.course courseId, c.fullname coursename
SELECT COUNT(l.id) hits, l.course courseId, c.fullname coursename
FROM prefix_log l INNER JOIN prefix_course c ON l.course = c.id  
FROM prefix_log l INNER JOIN prefix_course c ON l.course = c.id  
%%FILTER_COURSES:l.course%%  
%%FILTER_COURSES:l.course%%  
Line 175: Line 256:
ORDER BY hits DESC
ORDER BY hits DESC
</code>
</code>
Observe que estamos añadiendo un token llamado %%FILTER_COURSES:l.courseid%%
# Vaya a la pestaña "Ver informe" y verá un filtro de cursos. Elija un curso y pulse en "Añadir" para ver el informe filtrado por ese curso.


También puede añadir un filtro de tipo "Filtro de fechas" para filtrar por fecha de inicio y fin:
Note that we are adding a token called: %%FILTER_COURSES:l.courseid%%
 
Go to View report, and you will see a Courses Filter, choose a Course and click on Add, here you have a report filtered.
 
 
You can also add a Starttime and endtime filter
 
Go to filters, choose Start / End date filter
 
Go to Custom SQL tab, this is the new query:


# Vaya a la pestaña "Filtros" y añada un filtro de tipo "Filtro de fechas".
# Edite la consulta SQL y ponga lo siguiente:
<code sql>
<code sql>
SELECT COUNT(l.id) AS hits, l.course courseId, c.fullname coursename
SELECT COUNT(l.id) hits, l.course courseId, c.fullname coursename
FROM prefix_log l INNER JOIN prefix_course c ON l.course = c.id  
FROM prefix_log l INNER JOIN prefix_course c ON l.course = c.id  
%%FILTER_COURSES:l.course%%  
%%FILTER_COURSES:l.course%%  
Line 190: Line 276:
ORDER BY hits DESC
ORDER BY hits DESC
</code>
</code>
Observe que estamos añadiendo un token llamado %%FILTER_STARTTIME:l.time:>%% %%FILTER_ENDTIME:l.time:<%%
# Vaya a la pestaña "Ver informe" y verá también un filtro para indicar la fecha de inicio y fin a usar para el informe.


[[#Informe_SQL | Ver pantalla mostrando el informe]]
One more example (for filtering a group of courses by category)
<code sql>
SELECT COUNT(l.id) hits, c.fullname as Course,c.id as CourseID
,(SELECT Count( ra.userid ) AS Users FROM prefix_role_assignments AS ra
JOIN prefix_context AS ctx ON ra.contextid = ctx.id
WHERE ra.roleid = 5 AND ctx.instanceid = c.id) AS Students
FROM prefix_log l INNER JOIN prefix_course c ON l.course = c.id
%%FILTER_CATEGORIES:c.category%%
GROUP BY l.course
ORDER BY hits DESC
</code>
Go to View report, now you can filter by time also
 
'''SQL variables'''
If you place this strings in your SQL queries, it will be replaced by the appropriate value (current course id, current user id, Moodle www root (url))
 
* %%COURSEID%%
* %%USERID%%
* %%WWWROOT%%
 
[[blocks/configurable_reports/#SQL_report | See screenshot]]
 
=== Creating a timeline report ===
 
''This report assumes that you have created at least one user or course report''
 
Timeline reports are a special type of reports. A timeline report displays a timeline in which a course report or user report can be embedded.
 
In this example we are going to create a report showing the user logins to the site during the last month (day per day).
 
Create a User report (see tutorial above) with three columns (firstname, lastname and user statistics)
 
Select the statistic (User logins)
 
Create a Timeline report, in the Timeline tab you can select the dates or days of the report (in this case, the last 30 days) and the interval of time for every row.
 
Add three "Other report column" columns, selecting all the previous user report columns.
 
And that's all, you can create a new type of plot (line graph). This graph is suitable for data depending on time.
 
== Advanced options ==
 


== Opciones avanzadas ==
=== Templates ===
=== Plantillas ===


Se puede personalizar el informe usando una plantilla. Sólo hace falta ir a la pestaña llamada "Plantilla" y habilitarla, y a continuación rellenar cada una de las partes de la plantilla (cabecera, plantilla para un registro y pie)
You can customize the report output using a template.


Este es un ejemplo de código HTML para visualizar una lista de usuarios:
Just enable the Template option in the same name tab.


Cabecera:
This is an example html code for displaying a list of users:
 
Header:


<code html4strict>
<code html4strict>
Line 211: Line 337:
</code>
</code>


Plantilla para un registro:
Record:


<code html4strict>
<code html4strict>
<table width="100%">
<table width="100%">
<tr>
<tr>
<td><img src="http://tu.sitio.moodle.es/user/pix.php/[[id]]/f1.jpg"></td>
<td><img src="http://yourmoodle.com/user/pix.php/[[id]]/f1.jpg"></td>
<td><h2>[[firstname]] [[lastname]]</h2>
<td><h2>[[Firstname]] [[Lastname]]</h2>
Ciudad: [[city]]
City: [[City]]
</td>
</td>
</tr>
</tr>
Line 225: Line 351:
</code>
</code>


Pie:
Footer:


<code html4strict>
<code html4strict>
Line 237: Line 363:
</code>
</code>


=== Informes incrustados ===
=== Embedded reports ===
Un informe incrustado consiste en un juego de columnas de un informe que están incrustadas entro.
 
An embedded report consists in a report's set of columns that are embedded in another report.
 
You can embed a user report into a course report, in this case, the resulting rows will be expanded duplicating each row for each user.
 
{| class="wikitable"
|-
! Type of report
! Reports that can be embedded
|-
| Courses
| Users
|-
| Categories
| Courses
|-
| Timeline
| Users, courses
|}
 
Imagine you have a courses report, you can embed a user report, every row of the course report will be cloned for each user.
 
To embed a report just add a "Other report" column, a list of your reports will be showed.
 
Inside a course report you can embed a user report and the other way.


Por ejemplo, puede incrustar un informe de usuario en un informe de curso. En este caso, las filas resultantes del curso se expandirán duplicando cada fila para cada usuario.
==== Timeline reports ====


Para incrustar un informe, simplemente añada una nueva columna de tipo "Columna de otro informe". Aparecerá una lista de informes existentes. Una vez seleccionado uno aparecerá la lista de columnas de dicho informe para que podamos escoger la deseada.
Timeline reports are a special type of reports. A timeline report displays a timeline in which a courses report or users report can be embedded.


Dentro de un informe de curso se puede incrustar un informe de usuario y viceversa. No es posible sin embargo incrustar informes de curso dentro de informes de curso, o informes de usuario dentro de informes de usuario.
Timeline reports should be used when your user or course report includes statistics (course stats or user stats columns). I.e: you can create a report showing the number of user logins to the site during a week or month.


== Documentación para desarrolladores ==
== Developers documentation ==


Es muy fácil crear nuevos tipos de informes, componentes y plugins.
It's very easy to create new report types, components and plugins.


'''Informe''': Un informe es un directorio ubicado dentro de /reports (con respecto al directorio de instalación del bloque). Este directorio contiene un fichero llamado report.class.php con la definición de la clase hija que extiende de report_base.
'''Report''': A report plugin is a folder located at /report.  
This folder contains a .class.php file with the child - class of the report_base.


Sólo necesita modificar unos pocos métodos para añadir un nuevo tipo de informe. Por favor, eche una ojeada a cualquiera de los informes existentes. El informe SQL es un ejemplo de un informe no típico, mientras que los informes de usuarios y cursos son informes estándar.
You only need to modify a few methods to add a new report type.
Please, take a look at any of the current reports. The SQL report is an example of a non-typical report,  
meanwhile the users and courses reports are standard reports.


La mejor manera de crear un nuevo informe es duplicando uno existente.
The best way to create a report is to duplicate an existing one.


'''Componente''': Un componente es parte de un informe, y puede ser usado por más de un informe. Además es un directorio ubicado dentro de /components (con respecto al directorio de instalación del bloque). Este directorio contiene un fichero llamado component.class.php con la definición de la clase hija que extiende de component_base.


El componente princial es el componente llamado "columns", que se usa para añadir las columnas de un informe. Otros componentes son los filtros, permisos, gráficas, cálculos, etc.
'''Component''': A component is part of a report, a component may be used by more than one report.
The main Component is the component Columns, that is used to add the columns of a report.


La mejor manera de crear un nuevo componente es duplicando uno existente.
Others components are filters, permissions, plot, calculations..


'''Plugin''': Un plugin es un módulo de un componente. Además es un directorio ubicado dentro de /components/nombre-del-componente/. Este directorio contiene un fichero llamado plugin.class.php con la definición de la clase hija que extiende de plugin_base.
The best way to create a component is to duplicate an existing one.


Por ejemplo, el componente columna tiene unos pocos plugins (coursefield, userfield, etc..).


Un plugin funciona normalmente para un único tipo de informe, pero existen plugins que funcionan para más de un tipo de informe.
'''Plugin''': A plugin is a component module. The component column has a few of plugins (coursefield, userfield, etc.)
A plugin usually works for a unique report, but there are plugins that work for more than one report.
The best way to create a plugin is to duplicate an existing one.


La mejor manera de crear un nuevo plugin es duplicando uno existente.
== How to request a new feature ==


== Créditos ==
* Go to the Plugin Tracker http://tracker.moodle.org/browse/CONTRIB/component/10753
Juan Leyva [http://moodle.org/user/view.php?id=49568&course=1 Perfil de Moodle]
* Check in the open issues if your feature have been already requested http://tracker.moodle.org/secure/IssueNavigator.jspa?reset=true&jqlQuery=project+%3D+CONTRIB+AND+component+%3D+%22Block%3A+Configurable+report%22+AND+status+%3D+Open+ORDER+BY+priority+DESC&mode=hide
* If not, create a New issue (Component: Non-core contributed modules Issue type: New feature) (You have to register yourself in the tracker)
* Select the component Block: Configurable Reports and your Moodle version
* Explain in the Description field your needs
* If you have funding, you can contact me using the forum or the moodle internal messaging system, since I work for a Moodle Partner I can work on your request.
* Vote and Watch the issue you have created


[http://twitter.com/jleyvadelgado Sígueme en Twitter]
== Credits ==
[[Category:Contributed code]]


== Pantallazos ==
Juan Leyva [http://moodle.org/user/view.php?id=49568&course=1 Moodle profile]
=== Informe de usuarios ===
 
[http://twitter.com/jleyvadelgado Follow me in Twitter]
 
== Screenshots ==
 
=== Users report ===
[[Image:block_custom_reports_sample_user_report.png|600px]]
[[Image:block_custom_reports_sample_user_report.png|600px]]


=== Informe SQL ===
 
=== SQL report ===
[[Image:block_custom_reports_sample_sql_report.png|600px]]
[[Image:block_custom_reports_sample_sql_report.png|600px]]


[[en:blocks/configurable_reports]]
 
== See Also ==
 
CONTRIB-2386
 
[http://tracker.moodle.org/browse/CONTRIB/component/10753 Block: Configurable reports] Tracker component
 
[http://moodle.org/plugins/view.php?plugin=block_configurable_reports Modules & Plugins] database entry
 
[http://moodle.org/mod/forum/discuss.php?d=159820 Help forum]
 
[[ad-hoc_contributed_reports|contributed reports]] (in plain SQL)
 
[[es:blocks/configurable_reports/]]

Latest revision as of 02:06, 11 April 2013

Configurable reports
Type Block
Downloads https://moodle.org/plugins/view.php?plugin=block_configurable_reports
Issues http://tracker.moodle.org/browse/CONTRIB/component/10753
Discussion https://moodle.org/mod/forum/view.php?id=7979
Maintainer(s) Juan Leyva

Installation

  1. Download the Configurable Reports installation file and unzip it to the \blocks directory in your Moodle folder.
  2. Be sure that the final name of the directory is: configurable_reports, the full path in your Moodle installation will be blocks/configurable_reports
  3. Login to Moodle as Administrator and click Notifications under Site Administration.


For more information see Installing contributed modules or plugins

Overview

This block is a Moodle custom reports builder.

It is designed in a modular way to allow developers to create new plugins in less than an hour.


Who can create custom reports?

Anyone with block, managereports or manageownreports permissions at SITE level or COURSE level.


What type of reports can I create?

- Courses reports, with information regarding courses.

- Categories reports, with information regarding categories. A courses report can be embedded in this type of report.

- Users reports, with information regarding users and their activity in a course.

- Timeline reports, this is a special type of report that displays a timeline. A course or user report can be embedded in this timeline showing data depending on the start and end time of the current row.

- Custom SQL Reports, custom SQL queries. This block can use the same SQL queries as Tim Hunt's Custom SQL queries plugin.

Note for developers: You can create your own type of reports.


Who can view the reports?

When you create a report you can select which users can view it.

The reports are displayed in a block in the course or site frontpage.

Creating a report

This is a very simple process.

If you are going to create a report for a course, you have to add the block in the course and click in the "Manage reports" link.

On the other hand, for site reports, add the block in the frontpage and click in the "Manage reports" link.

You must enter a name, an optional description, and you have to choose the type of report, pagination and exports formats.

Depending on the report choosen, there will be more or less tabs. These are the tabs for the courses and users report:

Columns: Here you can choose the differents columns of your report depending on the type of report. (Course Name, User firstname, etc..)

Conditions: Here you can define the conditions (i.e, only courses from this category, only users from Spain, etc.)

Ordering: Here you can choose how to order the report using fields and directions.

Filters: Here you can choose which filters will be displayed.

Template: You can modify the report's layout by creating a template.

Permissions: Here you can choose who can view a report.

Calculations: Here you can add calculations for columns, i.e: average of number of users enrolled in courses

Plots: Here you can add graphs to your report based on the report columns and values.

View report: Self explanatory

Tutorial

Creating a users' report

Requirements: Users from Spain, but not from Madrid, in this course. This report can be viewed only by users from Spain. A filter based on the user's city must be displayed. A pie plot showing the users' cities is required. A calculation table showing the total forum post views is required. The report must be ordered by users' lastname.


Let's see how easy it is!

First of all, install the block.

Go to the course where the report will be created.

Add an instance of the Custom Reports block.

Click on "Manage reports"

Click on "Add report"

Enter a name, a description and choose "Users report" as Type of Report

The report will be saved and you will be redirected to the first Tab named "Columns".


Adding Columns

Here you can define the report table properties, width, align, cell padding, cell spacing, etc.

Add a Column called "User profile field"

Choose the field "firstname" and enter a name for the column in the text field. You can leave the rest of elements blank.

Repeat the process above for the lastname and city fields.

Add a Column called "User module actions".

Choose a module from the list, in this example, a forum.


Adding Conditions

Click on the Conditions Tab.

Add a Condition named "User field Condition".

Choose the column "Country", the Operator "=", and enter the value "ES" (this is the international code for Spain as Moodle stores it).

Add a Condition named "User field Condition".

Choose the column "city", the Operator "<>", and enter the value "Madrid".

Add a Condition named "Users in current report course".

These are the main conditions of the reports. Note that at the bottom there is a text box called condition, with this text:

"c2 and c1 and c3"

Here you can define a logic condition, in this case, we don't need to edit this condition but you can create complex expressions like:

(c1 and c2) or (c4 and c3)


Adding Ordering

Click on the Ordering Tab.

Add a ordering named "User field ordering".

Choose the column "Lastname" and the ordering "ASC" (Ascending).


Adding Filters

Click on the Filters Tab.

Add a filter named "User field filter".

Choose city.


Adding Permissions

Click on the Permissions Tab.

Choose "User field Value".

Choose the column "Country", and enter the value "ES".

Here you can add more permissions and a logic condition to be achieved.


Adding Calculations

Click on the Calculations tab.

Choose Sum.

Choose the column "User module actions".


Adding Plots

Click on the Plots tab.

Choose "Pie".

Choose the colum "City" as Name and Value.


Finally, add a few users in Moodle with the country Spain, and different cities, Madrid, Barcelona, Seville, etc. and test the report.

You can download the report in different formats (ods and xls), remember to check these options in the report page.

See screenshot

Creating a SQL Report

You can find a lot of SQL Reports here: ad-hoc contributed reports

Since this block supports Tim Hunt's CustomSQL Queries Reports, you can use any query.

Remember to add a "Time filter" if you are going to use reports with time tokens.


First of all, install the block.

Go to the course where the report will be created.

Add an instance of the Custom Reports block.

Click on "Manage reports".

Click on "Add report

Enter a name, description, choose "SQL" as Type of Report

The report will be saved and you redirect to the first Tab named "Custom SQL"

Add this query (Courses activity):

SELECT COUNT(l.id) hits, l.course courseId, c.fullname coursename FROM prefix_log l INNER JOIN prefix_course c ON l.course = c.id GROUP BY courseId ORDER BY hits DESC

NOTE: use the generic term "prefix_" for your table names in queries, not the actual prefix in the database and config.php. E.g. prefix_course rather than mdl_course.


Go to Calculations Tab

Add a Sum calculation, choose the hits column


Go to Plot

Add a Pie graph, choosing coursename as Name and hits as value

So, here you have a report with a Graph and calculations based on a SQL Query.


You can add a Course filter, it's very easy:

Go to filters, choose Courses

Edit the Custom SQL query:

SELECT COUNT(l.id) hits, l.course courseId, c.fullname coursename FROM prefix_log l INNER JOIN prefix_course c ON l.course = c.id %%FILTER_COURSES:l.course%% GROUP BY courseId ORDER BY hits DESC

Note that we are adding a token called: %%FILTER_COURSES:l.courseid%%

Go to View report, and you will see a Courses Filter, choose a Course and click on Add, here you have a report filtered.


You can also add a Starttime and endtime filter

Go to filters, choose Start / End date filter

Go to Custom SQL tab, this is the new query:

SELECT COUNT(l.id) hits, l.course courseId, c.fullname coursename FROM prefix_log l INNER JOIN prefix_course c ON l.course = c.id %%FILTER_COURSES:l.course%% %%FILTER_STARTTIME:l.time:>%% %%FILTER_ENDTIME:l.time:<%% GROUP BY courseId ORDER BY hits DESC

One more example (for filtering a group of courses by category) SELECT COUNT(l.id) hits, c.fullname as Course,c.id as CourseID ,(SELECT Count( ra.userid ) AS Users FROM prefix_role_assignments AS ra JOIN prefix_context AS ctx ON ra.contextid = ctx.id WHERE ra.roleid = 5 AND ctx.instanceid = c.id) AS Students FROM prefix_log l INNER JOIN prefix_course c ON l.course = c.id %%FILTER_CATEGORIES:c.category%% GROUP BY l.course ORDER BY hits DESC Go to View report, now you can filter by time also

SQL variables If you place this strings in your SQL queries, it will be replaced by the appropriate value (current course id, current user id, Moodle www root (url))

  • %%COURSEID%%
  • %%USERID%%
  • %%WWWROOT%%

See screenshot

Creating a timeline report

This report assumes that you have created at least one user or course report

Timeline reports are a special type of reports. A timeline report displays a timeline in which a course report or user report can be embedded.

In this example we are going to create a report showing the user logins to the site during the last month (day per day).

Create a User report (see tutorial above) with three columns (firstname, lastname and user statistics)

Select the statistic (User logins)

Create a Timeline report, in the Timeline tab you can select the dates or days of the report (in this case, the last 30 days) and the interval of time for every row.

Add three "Other report column" columns, selecting all the previous user report columns.

And that's all, you can create a new type of plot (line graph). This graph is suitable for data depending on time.

Advanced options

Templates

You can customize the report output using a template.

Just enable the Template option in the same name tab.

This is an example html code for displaying a list of users:

Header:

##reportname##

Record:

<img src="http://yourmoodle.com/user/pix.php/id/f1.jpg">

Firstname Lastname

City: City


Footer:

    1. graphs##



    1. exportoptions##

Embedded reports

An embedded report consists in a report's set of columns that are embedded in another report.

You can embed a user report into a course report, in this case, the resulting rows will be expanded duplicating each row for each user.

Type of report Reports that can be embedded
Courses Users
Categories Courses
Timeline Users, courses

Imagine you have a courses report, you can embed a user report, every row of the course report will be cloned for each user.

To embed a report just add a "Other report" column, a list of your reports will be showed.

Inside a course report you can embed a user report and the other way.

Timeline reports

Timeline reports are a special type of reports. A timeline report displays a timeline in which a courses report or users report can be embedded.

Timeline reports should be used when your user or course report includes statistics (course stats or user stats columns). I.e: you can create a report showing the number of user logins to the site during a week or month.

Developers documentation

It's very easy to create new report types, components and plugins.

Report: A report plugin is a folder located at /report. This folder contains a .class.php file with the child - class of the report_base.

You only need to modify a few methods to add a new report type. Please, take a look at any of the current reports. The SQL report is an example of a non-typical report, meanwhile the users and courses reports are standard reports.

The best way to create a report is to duplicate an existing one.


Component: A component is part of a report, a component may be used by more than one report. The main Component is the component Columns, that is used to add the columns of a report.

Others components are filters, permissions, plot, calculations..

The best way to create a component is to duplicate an existing one.


Plugin: A plugin is a component module. The component column has a few of plugins (coursefield, userfield, etc.) A plugin usually works for a unique report, but there are plugins that work for more than one report. The best way to create a plugin is to duplicate an existing one.

How to request a new feature

Credits

Juan Leyva Moodle profile

Follow me in Twitter

Screenshots

Users report

block custom reports sample user report.png


SQL report

block custom reports sample sql report.png


See Also

CONTRIB-2386

Block: Configurable reports Tracker component

Modules & Plugins database entry

Help forum

contributed reports (in plain SQL)