Merged openproject-reporting_engine into openproject

pull/6827/head
Oliver Günther 6 years ago
commit 2dd22b8695
No known key found for this signature in database
GPG Key ID: A3A8BDAD7C0C552C
  1. 66
      modules/reporting_engine/README.md
  2. 30
      modules/reporting_engine/config/locales/crowdin/ar.yml
  3. 30
      modules/reporting_engine/config/locales/crowdin/ca.yml
  4. 30
      modules/reporting_engine/config/locales/crowdin/da.yml
  5. 30
      modules/reporting_engine/config/locales/crowdin/de.yml
  6. 30
      modules/reporting_engine/config/locales/crowdin/es-ES.yml
  7. 30
      modules/reporting_engine/config/locales/crowdin/et.yml
  8. 30
      modules/reporting_engine/config/locales/crowdin/fi.yml
  9. 30
      modules/reporting_engine/config/locales/crowdin/fr.yml
  10. 30
      modules/reporting_engine/config/locales/crowdin/hr.yml
  11. 30
      modules/reporting_engine/config/locales/crowdin/hu.yml
  12. 30
      modules/reporting_engine/config/locales/crowdin/it.yml
  13. 30
      modules/reporting_engine/config/locales/crowdin/ja.yml
  14. 5
      modules/reporting_engine/config/locales/crowdin/js-ar.yml
  15. 5
      modules/reporting_engine/config/locales/crowdin/js-ca.yml
  16. 5
      modules/reporting_engine/config/locales/crowdin/js-da.yml
  17. 5
      modules/reporting_engine/config/locales/crowdin/js-de.yml
  18. 5
      modules/reporting_engine/config/locales/crowdin/js-es-ES.yml
  19. 5
      modules/reporting_engine/config/locales/crowdin/js-et.yml
  20. 5
      modules/reporting_engine/config/locales/crowdin/js-fi.yml
  21. 5
      modules/reporting_engine/config/locales/crowdin/js-fr.yml
  22. 5
      modules/reporting_engine/config/locales/crowdin/js-hr.yml
  23. 5
      modules/reporting_engine/config/locales/crowdin/js-hu.yml
  24. 5
      modules/reporting_engine/config/locales/crowdin/js-it.yml
  25. 5
      modules/reporting_engine/config/locales/crowdin/js-ja.yml
  26. 5
      modules/reporting_engine/config/locales/crowdin/js-ko.yml
  27. 5
      modules/reporting_engine/config/locales/crowdin/js-lt.yml
  28. 5
      modules/reporting_engine/config/locales/crowdin/js-nl.yml
  29. 5
      modules/reporting_engine/config/locales/crowdin/js-no.yml
  30. 5
      modules/reporting_engine/config/locales/crowdin/js-pl.yml
  31. 5
      modules/reporting_engine/config/locales/crowdin/js-pt-BR.yml
  32. 5
      modules/reporting_engine/config/locales/crowdin/js-pt-PT.yml
  33. 5
      modules/reporting_engine/config/locales/crowdin/js-ru.yml
  34. 5
      modules/reporting_engine/config/locales/crowdin/js-sk.yml
  35. 5
      modules/reporting_engine/config/locales/crowdin/js-sv-SE.yml
  36. 5
      modules/reporting_engine/config/locales/crowdin/js-tr.yml
  37. 5
      modules/reporting_engine/config/locales/crowdin/js-zh-CN.yml
  38. 5
      modules/reporting_engine/config/locales/crowdin/js-zh-TW.yml
  39. 30
      modules/reporting_engine/config/locales/crowdin/ko.yml
  40. 30
      modules/reporting_engine/config/locales/crowdin/lt.yml
  41. 30
      modules/reporting_engine/config/locales/crowdin/nl.yml
  42. 30
      modules/reporting_engine/config/locales/crowdin/no.yml
  43. 30
      modules/reporting_engine/config/locales/crowdin/pl.yml
  44. 30
      modules/reporting_engine/config/locales/crowdin/pt-BR.yml
  45. 30
      modules/reporting_engine/config/locales/crowdin/pt-PT.yml
  46. 30
      modules/reporting_engine/config/locales/crowdin/ru.yml
  47. 30
      modules/reporting_engine/config/locales/crowdin/sk.yml
  48. 30
      modules/reporting_engine/config/locales/crowdin/sv-SE.yml
  49. 30
      modules/reporting_engine/config/locales/crowdin/tr.yml
  50. 30
      modules/reporting_engine/config/locales/crowdin/zh-CN.yml
  51. 30
      modules/reporting_engine/config/locales/crowdin/zh-TW.yml
  52. 54
      modules/reporting_engine/config/locales/en.yml
  53. 23
      modules/reporting_engine/config/locales/js-en.yml
  54. 24
      modules/reporting_engine/doc/API_CHANGES.md
  55. 18
      modules/reporting_engine/doc/COPYRIGHT.md
  56. 16
      modules/reporting_engine/doc/COPYRIGHT_short.md
  57. 674
      modules/reporting_engine/doc/GPL.txt
  58. 85
      modules/reporting_engine/lib/assets/javascripts/reporting_engine/reporting.js
  59. 157
      modules/reporting_engine/lib/assets/javascripts/reporting_engine/reporting/controls.js
  60. 371
      modules/reporting_engine/lib/assets/javascripts/reporting_engine/reporting/filters.js
  61. 191
      modules/reporting_engine/lib/assets/javascripts/reporting_engine/reporting/group_bys.js
  62. 101
      modules/reporting_engine/lib/assets/javascripts/reporting_engine/reporting/restore_query.js
  63. 24
      modules/reporting_engine/lib/assets/javascripts/reporting_engine/reporting_engine.js
  64. 452
      modules/reporting_engine/lib/assets/stylesheets/reporting_engine/reporting.css.erb
  65. 23
      modules/reporting_engine/lib/assets/stylesheets/reporting_engine/reporting_engine.css
  66. 36
      modules/reporting_engine/lib/engine.rb
  67. 213
      modules/reporting_engine/lib/report.rb
  68. 335
      modules/reporting_engine/lib/report/chainable.rb
  69. 338
      modules/reporting_engine/lib/report/controller.rb
  70. 38
      modules/reporting_engine/lib/report/filter.rb
  71. 186
      modules/reporting_engine/lib/report/filter/base.rb
  72. 29
      modules/reporting_engine/lib/report/filter/multi_choice.rb
  73. 28
      modules/reporting_engine/lib/report/filter/no_filter.rb
  74. 40
      modules/reporting_engine/lib/report/group_by.rb
  75. 108
      modules/reporting_engine/lib/report/group_by/base.rb
  76. 32
      modules/reporting_engine/lib/report/group_by/ruby_aggregation.rb
  77. 32
      modules/reporting_engine/lib/report/group_by/singleton_value.rb
  78. 37
      modules/reporting_engine/lib/report/group_by/sql_aggregation.rb
  79. 81
      modules/reporting_engine/lib/report/inherited_attribute.rb
  80. 374
      modules/reporting_engine/lib/report/operator.rb
  81. 338
      modules/reporting_engine/lib/report/query_utils.rb
  82. 299
      modules/reporting_engine/lib/report/result.rb
  83. 288
      modules/reporting_engine/lib/report/sql_statement.rb
  84. 109
      modules/reporting_engine/lib/report/table.rb
  85. 65
      modules/reporting_engine/lib/report/transformer.rb
  86. 61
      modules/reporting_engine/lib/report/validation.rb
  87. 36
      modules/reporting_engine/lib/report/validation/dates.rb
  88. 36
      modules/reporting_engine/lib/report/validation/integers.rb
  89. 26
      modules/reporting_engine/lib/report/validation/sql.rb
  90. 119
      modules/reporting_engine/lib/report/walker.rb
  91. 22
      modules/reporting_engine/lib/reporting_engine.rb
  92. 63
      modules/reporting_engine/lib/reporting_engine/engine.rb
  93. 30
      modules/reporting_engine/lib/reporting_engine/helpers/reporting_helper.rb
  94. 21
      modules/reporting_engine/lib/reporting_engine/patches.rb
  95. 40
      modules/reporting_engine/lib/reporting_engine/patches/big_decimal_patch.rb
  96. 47
      modules/reporting_engine/lib/reporting_engine/patches/to_date_patch.rb
  97. 45
      modules/reporting_engine/lib/reporting_engine/tasks/spec.rake
  98. 22
      modules/reporting_engine/lib/reporting_engine/version.rb
  99. 68
      modules/reporting_engine/lib/reporting_widget.rb
  100. 115
      modules/reporting_engine/lib/widget/base.rb
  101. Some files were not shown because too many files have changed in this diff Show More

@ -0,0 +1,66 @@
ReportingEngine
===============
The ReportingEngine is a Rails engine containing base functionality to create customized database reports. A report consists of filters and grouping criteria, each of which selects an attribute to be used for filtering and grouping. It provides base filter and grouping classes to be used for adding new filters. It also adds some base widgets to visually represent the created reports.
This engine is mainly used in the [OpenProject Reporting plugin](https://www.openproject.org/projects/plugin-reporting), allowing to create customized cost reports when the [OpenProject Costs plugin](https://www.openproject.org/projects/costs-plugin) is used to track projects costs.
Requirements
------------
The ReportingEngine requires Rails 3.2 and is compatible with MySQL or PostgreSQL. MySQL versions 5.6.0 - 5.6.12 and 5.7.0 - 5.7.1 are not supported since they contain a bug leading to wrong report results under certain circumstances.
Installation
------------
To use the ReportingEngine, add the following line to your `Gemfile`:
`gem "reporting_engine", git: "https://github.com/finnlabs/reporting_engine.git", :branch => "dev"`
If you are running OpenProject, add the above line to the `Gemfile.plugins` in your OpenProject installation folder instead.
Afterwards, run:
`bundle install`
Deinstallation
--------------
Remove the line
`gem "reporting_engine", git: "https://github.com/finnlabs/reporting_engine.git", :branch => "dev"`
from your `Gemfile` or the `Gemfile.plugins` in your OpenProject installation and run:
`bundle install`
Bug Reporting
-------------
If you find any bugs, you can create a bug ticket at
https://www.openproject.org/projects/plugin-reportingengine
Development
-----------
To contribute, you can create pull request on the official repository at
`https://github.com/finnlabs/reporting_engine`
Credits
-------
Special thanks go to
* Deutsche Telekom AG (opensource@telekom.de) for project sponsorship
Licence
-------
Copyright (C) 2010 - 2015 OpenProject Foundation (OPF)
This plugin is licensed under the GNU GPL v3. See doc/COPYRIGHT.md and doc/GPL.txt for details.

@ -0,0 +1,30 @@
ar:
description_drill_down: "أظهر التفاصيل"
label_click_to_edit: "اضغط للتعديل."
label_columns: "الأعمدة"
label_count: "العد"
label_filter: "عامل التصفية"
label_filter_add: "إضافة عامل تصفية"
label_filter_plural: "عوامل التصفية"
label_greater: ">"
label_group_by: "مجموعة بحسب"
label_group_by_add: "أضِف مجموعة بحسب السّمة"
label_inactive: "<<غير فعّال>>"
label_less: "<"
label_no: "لا"
label_none: "(لا توجد بيانات)"
label_progress_bar_explanation: "جاري إعداد التقرير..."
label_really_delete_question: "هل أنت متأكد من أنك تريد حذف هذا التقرير؟"
label_report: "التقرير"
label_rows: "الصفوف"
label_saving: "جاري الحفظ ..."
label_sum: "المجموع"
label_yes: "نعم"
load_query_question: "سيكون للتقرير %{size} من خلايا الجدول، وقد يستغرق بعض الوقت للتقديم. هل ما زلت تريد المحاولة لتقديمه؟"
units: "الوحدات"
validation_failure_date: "ليس تاريخًا صالحًا"
validation_failure_integer: "ليس عددًا صحيحًا صالحًا"
reporting:
group_by:
selected_columns: "Selected columns"
selected_rows: "Selected rows"

@ -0,0 +1,30 @@
ca:
description_drill_down: "Mostra els detalls"
label_click_to_edit: "Feu clic per editar."
label_columns: "Columnes"
label_count: "Recompte"
label_filter: "Filtre"
label_filter_add: "Afegir filtre"
label_filter_plural: "Filtres"
label_greater: ">"
label_group_by: "Agrupa per"
label_group_by_add: "Afegir grup per atribut"
label_inactive: "«inactiu»"
label_less: "<"
label_no: "No"
label_none: "(no hi ha dades)"
label_progress_bar_explanation: "Generant informe..."
label_really_delete_question: "Esteu segur que voleu suprimir aquest informe?"
label_report: "Informe"
label_rows: "Files"
label_saving: "Desant ..."
label_sum: "Suma"
label_yes: "Si"
load_query_question: "L'informe tindrà %{size} de cel·les i pot trigar algun temps per generar-se. Encara voleu intentar la generació?"
units: "Unitats"
validation_failure_date: "no és una data vàlida"
validation_failure_integer: "no és un enter vàlid"
reporting:
group_by:
selected_columns: "Selected columns"
selected_rows: "Selected rows"

@ -0,0 +1,30 @@
da:
description_drill_down: "Vis detaljer"
label_click_to_edit: "Klik for at redigere."
label_columns: "Kolonner"
label_count: "Antal"
label_filter: "Filter"
label_filter_add: "Tilføj filter"
label_filter_plural: "Filtre"
label_greater: ">"
label_group_by: "Gruppér efter"
label_group_by_add: "Tilføj Gruppér efter-attribut"
label_inactive: "«inaktiv»"
label_less: "<"
label_no: "Nej"
label_none: "(ingen data)"
label_progress_bar_explanation: "Genererer rapport..."
label_really_delete_question: "Sikker på, at du ønsker denne rapport slettet?"
label_report: "Rapport"
label_rows: "Rækker"
label_saving: "Gemmer ..."
label_sum: "Sum"
label_yes: "Ja"
load_query_question: "Rapporten vil indeholde %{size} celler og kan tage nogen tid at danne. Fortsæt alligevel?"
units: "Enheder"
validation_failure_date: "er en ugyldig dato"
validation_failure_integer: "er et ugyldigt heltal"
reporting:
group_by:
selected_columns: "Selected columns"
selected_rows: "Selected rows"

@ -0,0 +1,30 @@
de:
description_drill_down: "Details anzeigen"
label_click_to_edit: "Zum Bearbeiten hier klicken."
label_columns: "Spalten"
label_count: "Anzahl"
label_filter: "Filter"
label_filter_add: "Filter hinzufügen"
label_filter_plural: "Filter"
label_greater: ">"
label_group_by: "Gruppieren nach"
label_group_by_add: "Gruppierung hinzufügen"
label_inactive: "«nicht aktiviert»"
label_less: "<"
label_no: "Nein"
label_none: "(Keine Angabe)"
label_progress_bar_explanation: "Report wird erstellt ..."
label_really_delete_question: "Diesen Report wirklich löschen?"
label_report: "Report"
label_rows: "Zeilen"
label_saving: "Speichern ..."
label_sum: "Summe"
label_yes: "Ja"
load_query_question: "Der Report wird %{size} Tabellen-Zellen haben, was sehr rechenintensiv sein kann. Wollen Sie dennoch versuchen, den Report durch zu führen?"
units: "Einheiten"
validation_failure_date: "ist kein gültiges Datum"
validation_failure_integer: "ist keine ganze Zahl"
reporting:
group_by:
selected_columns: "Ausgewählte Spalten"
selected_rows: "Ausgewählte Zeilen"

@ -0,0 +1,30 @@
es:
description_drill_down: "Ver detalles"
label_click_to_edit: "Clic para editar."
label_columns: "Columnas"
label_count: "Contador"
label_filter: "Filtro"
label_filter_add: "Añadir filtro"
label_filter_plural: "Filtros"
label_greater: ">"
label_group_by: "Agrupar por"
label_group_by_add: "Añadir atributo de agrupación"
label_inactive: "«inactivo»"
label_less: "<"
label_no: "No"
label_none: "(sin datos)"
label_progress_bar_explanation: "Generando informe..."
label_really_delete_question: "¿Está seguro que desea eliminar este informe?"
label_report: "Informe"
label_rows: "Filas"
label_saving: "Guardando ..."
label_sum: "Suma"
label_yes: "Sí"
load_query_question: "El informe tendrá %{size} celdas de tabla y puede tardar algún tiempo en generarse. ¿Desea generarlo de todas formas?"
units: "Unidades"
validation_failure_date: "no es una fecha válida"
validation_failure_integer: "no es un entero válido"
reporting:
group_by:
selected_columns: "Columnas seleccionadas"
selected_rows: "Filas seleccionadas"

@ -0,0 +1,30 @@
et:
description_drill_down: "Näita üksikasju"
label_click_to_edit: "Muutmiseks kliki."
label_columns: "Veerud"
label_count: "Arv"
label_filter: "Filter"
label_filter_add: "Lisa filter"
label_filter_plural: "Filtrid"
label_greater: ">"
label_group_by: "Grupeeri"
label_group_by_add: "Lisa grupeerimise omadus"
label_inactive: "«mitteaktiivne»"
label_less: "<"
label_no: "Ei"
label_none: "(andmeid pole)"
label_progress_bar_explanation: "Aruande loomine..."
label_really_delete_question: "Oled sa kindel, et soovid seda aruannet kustutada?"
label_report: "Aruanne"
label_rows: "Read"
label_saving: "Salvestamine ..."
label_sum: "Summa"
label_yes: "Jah"
load_query_question: "Aruandes on %{size} tabeli lahtrit ja selle loomine võib veidi aega võtta. Kas sa siiski soovid seda luua?"
units: "Ühikud"
validation_failure_date: "pole korrektne kuupäev"
validation_failure_integer: "pole täisarv"
reporting:
group_by:
selected_columns: "Selected columns"
selected_rows: "Selected rows"

@ -0,0 +1,30 @@
fi:
description_drill_down: "Näytä tiedot"
label_click_to_edit: "Muokkaa napsauttamalla tätä."
label_columns: "Sarakkeet"
label_count: "Määrä"
label_filter: "Suodata"
label_filter_add: "Lisää suodatin"
label_filter_plural: "Suodattimet"
label_greater: ">"
label_group_by: "Ryhmittely"
label_group_by_add: "Lisää ryhmittely-valinta"
label_inactive: "«passiivinen»"
label_less: "<"
label_no: "Ei"
label_none: "(ei tietoja)"
label_progress_bar_explanation: "Luodaan raporttia..."
label_really_delete_question: "Haluat varmasti poistaa tämän raportin?"
label_report: "Raportti"
label_rows: "Rivit"
label_saving: "Tallennetaan..."
label_sum: "Yhteensä"
label_yes: "Kyllä"
load_query_question: "Raportissa tulee olemaan %{size} solua ja sen luominen voi kentää jonkin aikaa. Haluatko silti kokeilla sen luomista?"
units: "Yksiköt"
validation_failure_date: "ei ole kelvollinen päivämäärä"
validation_failure_integer: "ei ole kelvollinen kokonaisluku"
reporting:
group_by:
selected_columns: "Valitut sarakkeet"
selected_rows: "Valitut rivit"

@ -0,0 +1,30 @@
fr:
description_drill_down: "Afficher les détails"
label_click_to_edit: "Cliquez pour modifier."
label_columns: "Colonnes"
label_count: "Décompte"
label_filter: "Filtre"
label_filter_add: "Ajouter un filtre"
label_filter_plural: "Filtres"
label_greater: ">"
label_group_by: "Grouper par"
label_group_by_add: "Ajoutez l'attribut \"Grouper par\""
label_inactive: "« inactif »"
label_less: "<"
label_no: "Non"
label_none: "(aucune donnée)"
label_progress_bar_explanation: "Rapport en cours de génération..."
label_really_delete_question: "Êtes-vous sûr de vouloir supprimer ce rapport ?"
label_report: "Rapport"
label_rows: "Lignes"
label_saving: "Enregistrement en cours …"
label_sum: "Total"
label_yes: "Oui"
load_query_question: "Le rapport contiendra un tableau de %{size} cellules et peut prendre un certain temps à être généré. Voulez-vous quand même le générer ?"
units: "Unités"
validation_failure_date: "n'est pas une date valide"
validation_failure_integer: "n'est pas un nombre entier valide"
reporting:
group_by:
selected_columns: "Colonnes sélectionnées"
selected_rows: "Lignes sélectionnées"

@ -0,0 +1,30 @@
hr:
description_drill_down: "Prikaži detalje"
label_click_to_edit: "Kliknite za uređivanje."
label_columns: "Stupci"
label_count: "Zbroji"
label_filter: "Filter"
label_filter_add: "Dodaj filter"
label_filter_plural: "Filteri"
label_greater: ">"
label_group_by: "Grupiraj po"
label_group_by_add: "Dodaj grupu - po Atributu"
label_inactive: "«neaktivan»"
label_less: "<"
label_no: "Ne"
label_none: "(nema podataka)"
label_progress_bar_explanation: "Generiranje izvješća..."
label_really_delete_question: "Da li ste sigurni da želite izbrisati ovo izvješće?"
label_report: "Izvješće"
label_rows: "Redci"
label_saving: "Spremanje ..."
label_sum: "Zbroj"
label_yes: "Da"
load_query_question: "Izvješće će imati %{size} veličinu tablice te će biti potrebno određeno vrijeme za prikaz. Da li želite prikazati ga i dalje?"
units: "Jedinice"
validation_failure_date: "nije valjan datum"
validation_failure_integer: "nije valjan cijeli broj"
reporting:
group_by:
selected_columns: "Selected columns"
selected_rows: "Selected rows"

@ -0,0 +1,30 @@
hu:
description_drill_down: "Részletek megjelenítése"
label_click_to_edit: "Szerkesztéséhez kattintson ide."
label_columns: "Oszlopok"
label_count: "Darabszám"
label_filter: "Szűrő"
label_filter_add: "Szűrő hozzáadása"
label_filter_plural: "Szűrők"
label_greater: ">"
label_group_by: "Csoportosítás"
label_group_by_add: "Csoportosítási tulajdonság hozzáadása"
label_inactive: "«inaktív»"
label_less: "<"
label_no: "Nem"
label_none: "(nincs adat)"
label_progress_bar_explanation: "Jelentés létrehozása..."
label_really_delete_question: "Biztosan törli ezt a jelentést?"
label_report: "Jelentés"
label_rows: "Sorok"
label_saving: "Mentés..."
label_sum: "Össz."
label_yes: "Igen"
load_query_question: "A jelentés %{size} cellát fog tartalmazni, így eltarthat egy ideig az elkészítése. Továbbra is el szeretné készíteni?"
units: "Egységek"
validation_failure_date: "nem érvényes dátum"
validation_failure_integer: "nem érvényes egész szám"
reporting:
group_by:
selected_columns: "A kijelölt oszlopok"
selected_rows: "A kijelölt sorok"

@ -0,0 +1,30 @@
it:
description_drill_down: "Mostra dettagli"
label_click_to_edit: "Premi per modificare."
label_columns: "Colonne"
label_count: "Conteggio"
label_filter: "Filtro"
label_filter_add: "Aggiungi filtro"
label_filter_plural: "Filtri"
label_greater: ">"
label_group_by: "Raggruppa per"
label_group_by_add: "Aggiungi l'attributo Group-by"
label_inactive: "«inattivo»"
label_less: "<"
label_no: "No"
label_none: "(nessun dato)"
label_progress_bar_explanation: "Generazione Report..."
label_really_delete_question: "Sei sicuro di voler cancellare questa segnalazione?"
label_report: "Report"
label_rows: "Righe"
label_saving: "Salvataggio in corso ..."
label_sum: "Somma"
label_yes: "Si"
load_query_question: "Il report avrà le celle della tabella del %{size} e potrebbe essere necessario del tempo per eseguire il rendering. Vuoi ancora tentare di eseguirne il rendering?"
units: "Unità di misura"
validation_failure_date: "non è una data valida"
validation_failure_integer: "non è un numero intero valido"
reporting:
group_by:
selected_columns: "Colonne selezionate"
selected_rows: "Righe selezionate"

@ -0,0 +1,30 @@
ja:
description_drill_down: "詳細を表示"
label_click_to_edit: "クリックして編集"
label_columns: "列"
label_count: "回数"
label_filter: "フィルタ"
label_filter_add: "フィルタを追加"
label_filter_plural: "フィルタ"
label_greater: ">"
label_group_by: "グループ化"
label_group_by_add: "グループ化属性を追加"
label_inactive: "«非活動»"
label_less: "<"
label_no: "いいえ"
label_none: "(データなし)"
label_progress_bar_explanation: "レポートを生成中..."
label_really_delete_question: "このレポートを削除してもよろしいですか?"
label_report: "レポート"
label_rows: "行"
label_saving: "保存中…"
label_sum: "合計"
label_yes: "はい"
load_query_question: "レポートは%{size}つセルを持つために、描画するに時間がかかる場合があります。描画してもよろしいですか?"
units: "単位"
validation_failure_date: "は有効な日付ではありません。"
validation_failure_integer: "は有効な整数ではありません。"
reporting:
group_by:
selected_columns: "選択された列"
selected_rows: "選択された行"

@ -0,0 +1,5 @@
ar:
js:
reporting_engine:
label_remove: "احذف"
label_response_error: "كان هناك خطأ أثناء معالجة الطلب."

@ -0,0 +1,5 @@
ca:
js:
reporting_engine:
label_remove: "Esborra"
label_response_error: "Hi ha un error manipulant la consulta."

@ -0,0 +1,5 @@
da:
js:
reporting_engine:
label_remove: "Slet"
label_response_error: "En fejl opstod under forespørgselshåndteringen."

@ -0,0 +1,5 @@
de:
js:
reporting_engine:
label_remove: "Löschen"
label_response_error: "Bei der Bearbeitung der Anfrage ist ein Fehler aufgetreten."

@ -0,0 +1,5 @@
es:
js:
reporting_engine:
label_remove: "Eliminar"
label_response_error: "Se produjo un error procesando la consulta."

@ -0,0 +1,5 @@
et:
js:
reporting_engine:
label_remove: "Kustuta"
label_response_error: "Päringu käsitlemisel tekkis tõrge."

@ -0,0 +1,5 @@
fi:
js:
reporting_engine:
label_remove: "Poista"
label_response_error: "Kyselyn käsittely epäonnistui."

@ -0,0 +1,5 @@
fr:
js:
reporting_engine:
label_remove: "Supprimer"
label_response_error: "Une erreur s'est produite lors du traitement de la requête."

@ -0,0 +1,5 @@
hr:
js:
reporting_engine:
label_remove: "Delete"
label_response_error: "There was an error handling the query."

@ -0,0 +1,5 @@
hu:
js:
reporting_engine:
label_remove: "Töröl"
label_response_error: "Hiba lépett fel a lekérdezés kezelése közben."

@ -0,0 +1,5 @@
it:
js:
reporting_engine:
label_remove: "Elimina"
label_response_error: "Si è verificato un errore durante l'elaborazione della query."

@ -0,0 +1,5 @@
ja:
js:
reporting_engine:
label_remove: "削除"
label_response_error: "クエリを処理中にエラーが発生しました。"

@ -0,0 +1,5 @@
ko:
js:
reporting_engine:
label_remove: "삭제"
label_response_error: "쿼리 처리 중에 오류가 발생했습니다."

@ -0,0 +1,5 @@
lt:
js:
reporting_engine:
label_remove: "Ištrinti"
label_response_error: "Klaida apdorojant užklausą."

@ -0,0 +1,5 @@
nl:
js:
reporting_engine:
label_remove: "Verwijderen"
label_response_error: "Er is een fout opgetreden tijdens het verwerken van het verzoek."

@ -0,0 +1,5 @@
"no":
js:
reporting_engine:
label_remove: "Slette"
label_response_error: "En feil oppstod under behandling av spørringen."

@ -0,0 +1,5 @@
pl:
js:
reporting_engine:
label_remove: "Usuń"
label_response_error: "Wystąpił błąd podczas próby połączenia z serwerem."

@ -0,0 +1,5 @@
pt-BR:
js:
reporting_engine:
label_remove: "Excluir"
label_response_error: "Ocorreu um erro na manipulação da consulta."

@ -0,0 +1,5 @@
pt:
js:
reporting_engine:
label_remove: "Eliminar"
label_response_error: "Houve um erro ao tratar o questionário."

@ -0,0 +1,5 @@
ru:
js:
reporting_engine:
label_remove: "Удалить"
label_response_error: "Произошла ошибка при обработке запроса."

@ -0,0 +1,5 @@
sk:
js:
reporting_engine:
label_remove: "Odstrániť"
label_response_error: "Počas spracovania dotazu nastala chyba."

@ -0,0 +1,5 @@
sv:
js:
reporting_engine:
label_remove: "Ta bort"
label_response_error: "Det uppstod ett fel när frågan hanterades."

@ -0,0 +1,5 @@
tr:
js:
reporting_engine:
label_remove: "Sil"
label_response_error: "Sorguyu işlerken hata oluştu."

@ -0,0 +1,5 @@
zh-CN:
js:
reporting_engine:
label_remove: "删除"
label_response_error: "处理查询时出错。"

@ -0,0 +1,5 @@
zh-TW:
js:
reporting_engine:
label_remove: "刪除"
label_response_error: "處理查詢時發生錯誤"

@ -0,0 +1,30 @@
ko:
description_drill_down: "세부 정보 표시"
label_click_to_edit: "편집하려면 클릭하세요."
label_columns: "열"
label_count: "카운트"
label_filter: "필터"
label_filter_add: "필터 추가"
label_filter_plural: "필터"
label_greater: ">"
label_group_by: "그룹화 기준"
label_group_by_add: "그룹화 기준 특성 추가"
label_inactive: "«비활성»"
label_less: "<"
label_no: "아니요"
label_none: "(데이터 없음)"
label_progress_bar_explanation: "보고서 생성 중..."
label_really_delete_question: "이 보고서를 삭제하시겠습니까?"
label_report: "보고서"
label_rows: "행"
label_saving: "저장 중..."
label_sum: "합계"
label_yes: "예"
load_query_question: "보고서에는 %{size}개 테이블 셀이 있고 렌더링하는 데 시간이 걸릴 수 있습니다. 렌더링하시겠습니까?"
units: "단위"
validation_failure_date: "은(는) 유효한 날짜가 아닙니다."
validation_failure_integer: "은(는) 유효한 정수가 아닙니다."
reporting:
group_by:
selected_columns: "선택된 열"
selected_rows: "선택된 행"

@ -0,0 +1,30 @@
lt:
description_drill_down: "Rodyti Išsamią informaciją"
label_click_to_edit: "Spustelėkite, kad redaguoti."
label_columns: "Stulpeliai"
label_count: "Skaičius"
label_filter: "Filtras"
label_filter_add: "Pridėti filtrą"
label_filter_plural: "Filtrai"
label_greater: ">"
label_group_by: "Grupuoti pagal"
label_group_by_add: "Pridėti grupavimą pagal atributą"
label_inactive: "«neaktyvus»"
label_less: "<"
label_no: "Ne"
label_none: "(nėra duomenų)"
label_progress_bar_explanation: "Generuojama ataskaita..."
label_really_delete_question: "Ar Jūs tikri, kad norite ištrinti šią ataskaitą?"
label_report: "Ataskaita"
label_rows: "Eilutės"
label_saving: "Išsaugoma ..."
label_sum: "Suma"
label_yes: "Taip"
load_query_question: "Ataskaita turės %{size} lentelės langelių ir gali užtrukti, kol bus paruošta. Ar Jūs dar vis norite pabandyti sukurti ją?"
units: "Vienetai"
validation_failure_date: "nėra tinkama data"
validation_failure_integer: "nėra tinkamas sveikas skaičius"
reporting:
group_by:
selected_columns: "Pasirinkti stulpeliai"
selected_rows: "Pasirinktos eilutės"

@ -0,0 +1,30 @@
nl:
description_drill_down: "Details weergeven"
label_click_to_edit: "Klik om te bewerken."
label_columns: "Kolommen"
label_count: "Aantal"
label_filter: "Filter"
label_filter_add: "Filter Toevoegen"
label_filter_plural: "Filters"
label_greater: ">"
label_group_by: "Groeperen op"
label_group_by_add: "Groep, toevoegen aan Attribuut"
label_inactive: "«inactief»"
label_less: "<"
label_no: "Nee"
label_none: "(geen gegevens)"
label_progress_bar_explanation: "Rapport aan het genereren..."
label_really_delete_question: "Weet u zeker dat u dit rapport wilt verwijderen?"
label_report: "Rapport"
label_rows: "Rijen"
label_saving: "Opslaan..."
label_sum: "Som"
label_yes: "Ja"
load_query_question: "Het rapport bevat %{size} tabelcellen en kan enige tijd kosten om te renderen. Wilt u proberen het rapport toch uit te voeren?"
units: "Eenheden"
validation_failure_date: "is geen geldige datum"
validation_failure_integer: "is geen geldig geheel getal"
reporting:
group_by:
selected_columns: "Geselecteerde kolommen"
selected_rows: "Geselecteerde rijen"

@ -0,0 +1,30 @@
"no":
description_drill_down: "Vis detaljer"
label_click_to_edit: "Klikk for å redigere."
label_columns: "Kolonner"
label_count: "Antall"
label_filter: "Filter"
label_filter_add: "Legg til Filter"
label_filter_plural: "Filtre"
label_greater: ">"
label_group_by: "Grupper etter"
label_group_by_add: "Legg grupper etter attributt"
label_inactive: "«inaktiv»"
label_less: "<"
label_no: "Nei"
label_none: "(ingen data)"
label_progress_bar_explanation: "Genererer rapport..."
label_really_delete_question: "Er du sikker på at du vil slette denne rapporten?"
label_report: "Rapport"
label_rows: "Rader"
label_saving: "Lagrer ..."
label_sum: "Sum"
label_yes: "Ja"
load_query_question: "Rapporten vil ha %{size} og kan ta noe tid å gjengi. Vil du likevel gjengi den?"
units: "Enheter"
validation_failure_date: "er ikke en gyldig dato"
validation_failure_integer: "er ikke et gyldig heltall"
reporting:
group_by:
selected_columns: "Selected columns"
selected_rows: "Selected rows"

@ -0,0 +1,30 @@
pl:
description_drill_down: "Pokaż szczegóły"
label_click_to_edit: "Kliknij aby edytować."
label_columns: "Kolumny"
label_count: "Ilość"
label_filter: "Filtr"
label_filter_add: "Dodaj filtr"
label_filter_plural: "Filtry"
label_greater: ">"
label_group_by: "Grupuj według"
label_group_by_add: "Dodaj grupowanie po atrybucie"
label_inactive: "«nieaktywne»"
label_less: "<"
label_no: "Nie"
label_none: "(brak danych)"
label_progress_bar_explanation: "Generuj raport..."
label_really_delete_question: "Czy na pewno chcesz usunąć ten raport?"
label_report: "Raport"
label_rows: "Wiersze"
label_saving: "Zapisywanie ..."
label_sum: "Suma"
label_yes: "Tak"
load_query_question: "Raport będzie zawierał %{size} komórek tabeli. Eksport może zająć trochę czasu. Czy nadal chcesz wygenerować raport?"
units: "Jednostki"
validation_failure_date: "nie jest poprawną datą"
validation_failure_integer: "nie jest prawidłową liczbą całkowitą"
reporting:
group_by:
selected_columns: "Wybrane kolumny"
selected_rows: "Wybrane wiersze"

@ -0,0 +1,30 @@
pt-BR:
description_drill_down: "Exibir detalhes"
label_click_to_edit: "Clique para editar."
label_columns: "Colunas"
label_count: "Contar"
label_filter: "Filtro"
label_filter_add: "Adicionar filtro"
label_filter_plural: "Filtros"
label_greater: ">"
label_group_by: "Agrupar por"
label_group_by_add: "Adicionar atributo Agrupar por"
label_inactive: "«inativo»"
label_less: "<"
label_no: "Não"
label_none: "(sem dados)"
label_progress_bar_explanation: "Gerando relatório..."
label_really_delete_question: "Tem certeza que deseja excluir este relatório?"
label_report: "Relatório"
label_rows: "Linhas"
label_saving: "Salvando ..."
label_sum: "Soma"
label_yes: "Sim"
load_query_question: "Relatório terá %{size} células da tabela e pode levar algum tempo para processar. Você ainda quer tentar processá-lo?"
units: "Unidades"
validation_failure_date: "não é uma data válida"
validation_failure_integer: "não é um valor inteiro válido"
reporting:
group_by:
selected_columns: "Colunas selecionadas"
selected_rows: "Linhas Selecionadas"

@ -0,0 +1,30 @@
pt:
description_drill_down: "Mostrar detalhes"
label_click_to_edit: "Clique para editar."
label_columns: "Colunas"
label_count: "Quantidade"
label_filter: "Filtro"
label_filter_add: "Adicionar Filtro"
label_filter_plural: "Filtros"
label_greater: ">"
label_group_by: "Agrupar por"
label_group_by_add: "Adicionar atributo Agrupar por"
label_inactive: "«inativo»"
label_less: "<"
label_no: "Não"
label_none: "(sem dados)"
label_progress_bar_explanation: "A gerar relatório..."
label_really_delete_question: "Tem a certeza que quer apagar este relatório?"
label_report: "Relatório"
label_rows: "Linhas"
label_saving: "A guardar..."
label_sum: "Soma"
label_yes: "Sim"
load_query_question: "O relatório terá %{size} células da tabela e pode levar algum tempo a processar. Quer tentar processá-lo?"
units: "Unidades"
validation_failure_date: "não é uma data válida"
validation_failure_integer: "não é um número inteiro válido"
reporting:
group_by:
selected_columns: "Colunas selecionadas"
selected_rows: "Linhas Selecionadas"

@ -0,0 +1,30 @@
ru:
description_drill_down: "Показать в деталях"
label_click_to_edit: "Щелкнуть для изменения."
label_columns: "Столбцы"
label_count: "Количество"
label_filter: "Фильтр"
label_filter_add: "Добавить фильтр"
label_filter_plural: "Фильтры"
label_greater: ">"
label_group_by: "Группировать по"
label_group_by_add: "Добавить атрибут \"Группировать по\""
label_inactive: "«неактивен»"
label_less: "<"
label_no: "Нет"
label_none: "(нет данных)"
label_progress_bar_explanation: "Создание отчета..."
label_really_delete_question: "Вы действительно хотите удалить этот отчет?"
label_report: "Отчет"
label_rows: "Строки"
label_saving: "Сохранение ..."
label_sum: "Сумма"
label_yes: "Да"
load_query_question: "Отчет будет иметь %{size} ячеек таблицы и может занять некоторое время для визуализации. Вы все еще хотите его сформировать?"
units: "Модули"
validation_failure_date: "не является допустимой датой"
validation_failure_integer: "не является допустимым целым числом"
reporting:
group_by:
selected_columns: "Выбранные столбцы"
selected_rows: "Выбранные строки"

@ -0,0 +1,30 @@
sk:
description_drill_down: "Zobraziť Podrobnosti"
label_click_to_edit: "Kliknite pre úpravu."
label_columns: "Stĺpce"
label_count: "Počet"
label_filter: "Filtrovať"
label_filter_add: "Pridať filter"
label_filter_plural: "Filtre"
label_greater: ">"
label_group_by: "Zoskupiť podľa"
label_group_by_add: "Pridať atribút \"zoskupiť podľa\""
label_inactive: "«neaktívny»"
label_less: "<"
label_no: "Nie"
label_none: "(žiadne údaje)"
label_progress_bar_explanation: "Prebieha tvorba tlačovej zostavy..."
label_really_delete_question: "Určite chcete odstrániť túto tlačovú zostavu?"
label_report: "Tlačová zostava"
label_rows: "Riadky"
label_saving: "Ukladanie ..."
label_sum: "Súčet"
label_yes: "Áno"
load_query_question: "Výsledná tlačová zostava bude obsahovať %{size} buniek a jej vytvorenie môže trvať dlhšie. Želáte si ju aj napriek tomu vygenerovať?"
units: "Jednotky"
validation_failure_date: "nie je platný dátum"
validation_failure_integer: "nie je platné celé číslo"
reporting:
group_by:
selected_columns: "Selected columns"
selected_rows: "Selected rows"

@ -0,0 +1,30 @@
sv:
description_drill_down: "Visa detaljer"
label_click_to_edit: "Klicka för att ändra."
label_columns: "Kolumner"
label_count: "Antal"
label_filter: "Filter"
label_filter_add: "Lägg till filter"
label_filter_plural: "Filter"
label_greater: ">"
label_group_by: "Gruppera efter"
label_group_by_add: "Lägg till Gruppera-efter-Attribut"
label_inactive: "«inaktiv»"
label_less: "<"
label_no: "Nej"
label_none: "(inga data)"
label_progress_bar_explanation: "Genererar rapport..."
label_really_delete_question: "Är du säker på att du vill ta bort denna rapport?"
label_report: "Rapport"
label_rows: "Rader"
label_saving: "Sparar ..."
label_sum: "Summa"
label_yes: "Ja"
load_query_question: "Rapporten kommer att ha %{size} celler och kan ta lite tid att skapa. Vill du prova att skapa den ändå?"
units: "Enheter"
validation_failure_date: "inte är ett giltigt datum"
validation_failure_integer: "är inte ett giltigt heltal"
reporting:
group_by:
selected_columns: "Valda kolumner"
selected_rows: "Markerade rader"

@ -0,0 +1,30 @@
tr:
description_drill_down: "Ayrıntıları görüntüle"
label_click_to_edit: "Düzenlemek için tıklayınız."
label_columns: "Sütunlar"
label_count: "Sayı"
label_filter: "Filtre"
label_filter_add: "Süzgeç ekle"
label_filter_plural: "Süzgeçler"
label_greater: ">"
label_group_by: "Grupla"
label_group_by_add: "Grubu Özelliklere Ekleyin"
label_inactive: "«etkin olmayan»"
label_less: "<"
label_no: "Hayır"
label_none: "(veri yok)"
label_progress_bar_explanation: "Rapor oluşturuluyor..."
label_really_delete_question: "Bu raporu silmek istediğinizden emin misiniz?"
label_report: "Rapor"
label_rows: "Satırlar"
label_saving: "Kaydediliyor ..."
label_sum: "Toplam"
label_yes: "Evet"
load_query_question: "Rapor %{size} tablo hücreleri içeriyor ve işlenmesi biraz zaman alabilir. Raporu yine de çalıştırmayı denemek ister misin?"
units: "Birimler"
validation_failure_date: "geçerli bir tarih değil"
validation_failure_integer: "geçerli bir tamsayı değil"
reporting:
group_by:
selected_columns: "Seçili sütunlar"
selected_rows: "Seçili satırlar"

@ -0,0 +1,30 @@
zh-CN:
description_drill_down: "显示详情"
label_click_to_edit: "点击编辑。"
label_columns: "列"
label_count: "数量"
label_filter: "筛选器"
label_filter_add: "添加筛选器"
label_filter_plural: "筛选器"
label_greater: ">"
label_group_by: "分组依据"
label_group_by_add: "添加分组依据属性"
label_inactive: "«不活动»"
label_less: "<"
label_no: "否"
label_none: "(无数据)"
label_progress_bar_explanation: "生成报告中..."
label_really_delete_question: "您是否确定想要删除此报告?"
label_report: "报告"
label_rows: "行"
label_saving: "正在保存..."
label_sum: "总计"
label_yes: "是"
load_query_question: "报告有 %{size} 个表格单元格,可能需要一些时间渲染。您仍然想要尝试渲染它吗?"
units: "单位"
validation_failure_date: "不是有效的日期"
validation_failure_integer: "不是有效的整数"
reporting:
group_by:
selected_columns: "选定的列"
selected_rows: "选定的行"

@ -0,0 +1,30 @@
zh-TW:
description_drill_down: "顯示詳細資訊"
label_click_to_edit: "按一下編輯"
label_columns: "欄位"
label_count: "數量"
label_filter: "篩選器"
label_filter_add: "新增篩選器"
label_filter_plural: "篩選器"
label_greater: ">"
label_group_by: "分組依據"
label_group_by_add: "新增分組依據屬性"
label_inactive: "«不活動»"
label_less: "<"
label_no: "否"
label_none: "(沒有資料)"
label_progress_bar_explanation: "產生報告中..."
label_really_delete_question: "你確定你要刪除這個報告?"
label_report: "報告"
label_rows: "列"
label_saving: "儲存中..."
label_sum: "總和"
label_yes: "是"
load_query_question: "報告含有 %{size} 個儲存格,將要花一些時間呈現。你仍然想要嘗試顯示它嗎?"
units: "單位"
validation_failure_date: "不是一個有效日期"
validation_failure_integer: "不是一個有效的整數"
reporting:
group_by:
selected_columns: "選擇列"
selected_rows: "選定行"

@ -0,0 +1,54 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
---
en:
description_drill_down: "Show details"
label_click_to_edit: "Click to edit."
label_columns: "Columns"
label_count: "Count"
label_filter: "Filter"
label_filter_add: "Add Filter"
label_filter_plural: "Filters"
label_greater: ">"
label_group_by: "Group by"
label_group_by_add: "Add Group-by Attribute"
label_inactive: "«inactive»"
label_less: "<"
label_no: "No"
label_none: "(no data)"
label_progress_bar_explanation: "Generating report..."
label_really_delete_question: "Are you sure you want to delete this report?"
label_report: "Report"
label_rows: "Rows"
label_saving: "Saving ..."
label_sum: "Sum"
label_yes: "Yes"
load_query_question: "Report will have %{size} table cells and may take some time to render. Do you still want to try rendering it?"
units: "Units"
validation_failure_date: "is not a valid date"
validation_failure_integer: "is not a valid integer"
reporting:
group_by:
selected_columns: "Selected columns"
selected_rows: "Selected rows"

@ -0,0 +1,23 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
en:
js:
reporting_engine:
label_remove: "Delete"
label_response_error: "There was an error handling the query."

@ -0,0 +1,24 @@
<!---- copyright
ReportingEngine
Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 3.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
++-->
# Rails 3.2 Upgrade
* add Gem dependency
* require 'reporting_engine/x' instead of 'x'

@ -0,0 +1,18 @@
ReportingEngine
A Rails engine allowing to create customized database reports
Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 3.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

@ -0,0 +1,16 @@
ReportingEngine
Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 3.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 3 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, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

@ -0,0 +1,85 @@
//-- copyright
// ReportingEngine
//
// Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// version 3.
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//++
/*jslint white: false, nomen: true, devel: true, on: true, debug: false, evil: true, onevar: false, browser: true, white: false, indent: 2 */
/*global window, $, $$, Reporting, Element */
window.Reporting = (function($) {
var onload = function (func) {
$(document).ready(func);
};
var flash = function (string, type) {
if (!type) {
type = "error";
}
var options = {};
if (type === 'error') {
options = {
id: 'errorExplanation',
class: 'errorExplanation'
};
}
else {
options = {
id: 'flash_' + type,
class: 'flash ' + type
};
}
$("#" + options.id).remove();
var flash = $('<div></div>')
.attr('id', options.id)
.attr('class', options.class)
.attr('tabindex', 0)
.attr('role', 'alert')
.html(string);
$('#content').prepend(flash);
$('#' + options.id).focus();
};
var clearFlash = function () {
$('div[id^=flash]').remove();
};
var fireEvent = function (element, event) {
var evt;
if (document.createEventObject) {
// dispatch for IE
evt = document.createEventObject();
return element.fireEvent('on' + event, evt);
} else {
// dispatch for firefox + others
evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true); // event type,bubbling,cancelable
return !element.dispatchEvent(evt);
}
};
return {
fireEvent: fireEvent,
clearFlash: clearFlash,
flash: flash,
onload: onload
};
})(jQuery);

@ -0,0 +1,157 @@
//-- copyright
// ReportingEngine
//
// Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// version 3.
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//++
/*jslint white: false, nomen: true, devel: true, on: true, debug: false, evil: true, onevar: false, browser: true, white: false, indent: 2 */
/*global window, $, $$, Reporting, Effect, Ajax, Element, selectAllOptions, Form */
Reporting.Controls = function($){
var toggle_delete_form = function (e) {
e.preventDefault();
var offset = $('#query-icon-delete').offset().left;
$('#delete_form').css("left", offset + "px").toggle();
};
var toggle_save_as_form = function (e) {
e.preventDefault();
var offset = $('#query-icon-save-as').offset().left;
$('#save_as_form')
.css('left', offset + 'px')
.toggle();
};
var clear_query = function (e) {
e.preventDefault();
Reporting.Filters.clear();
Reporting.GroupBys.clear();
};
var send_settings_data = function (targetUrl, callback, failureCallback) {
if (!failureCallback) {
failureCallback = default_failure_callback;
}
Reporting.clearFlash();
$.ajax({
url: targetUrl,
method: 'POST',
data: serialize_settings_form(),
beforeSend: function () {
$('#ajax-indicator').show();
},
error: failureCallback,
success: callback
});
};
var serialize_settings_form = function() {
var ret_str, grouping_str;
ret_str = $('#query_form').serialize();
grouping_str = _.reduce(['rows', 'columns'], function(grouping, type) {
var element_map = _.map($('#group-by--' + type + ' .group-by--selected-element'), function(group_by) {
return 'groups[' + type + '][]=' + $(group_by).attr('data-group-by');
});
return grouping + _.reduce(element_map, function(all_group_str, group_str) {
return all_group_str + '&' + group_str;
}, '');
}, '');
if (grouping_str.length > 0) {
ret_str += grouping_str;
}
return ret_str;
};
var attach_settings_callback = function (element, callback) {
if (element === null) {
return;
}
failureCallback = function (response) {
$('#result-table').html("");
default_failure_callback(response);
};
element.on('click', function (e) {
e.preventDefault();
send_settings_data($(this).attr("data-target"), callback, failureCallback);
});
};
var observe_click = function (element_id, callback) {
$('#' + element_id).on('click', callback);
};
var update_result_table = function (response) {
$('#result-table').html(response);
};
var default_failure_callback = function (response) {
if (response.status >= 400 && response.status < 500) {
Reporting.flash(response.responseText);
} else {
Reporting.flash(I18n.t("js.reporting_engine.label_response_error"));
}
};
return {
attach_settings_callback: attach_settings_callback,
clear_query: clear_query,
observe_click: observe_click,
update_result_table: update_result_table,
toggle_delete_form: toggle_delete_form,
toggle_save_as_form: toggle_save_as_form
};
}(jQuery);
(function($) {
Reporting.onload(function () {
if ($('#query_saved_name').length) {
// don't concern ourselves with new queries
if ($('#query_saved_name').attr("data-is_new")) {
if ($('#query-icon-delete').length) {
Reporting.Controls.observe_click("query-icon-delete", Reporting.Controls.toggle_delete_form);
Reporting.Controls.observe_click("query-icon-delete-cancel", Reporting.Controls.toggle_delete_form);
$('#delete_form').hide();
}
if ($("#query-breadcrumb-save").length) {
// When saving an update of an exisiting query or apply filters, we replace the table on success
Reporting.Controls.attach_settings_callback($("#query-breadcrumb-save"), Reporting.Controls.update_result_table);
}
}
}
Reporting.Controls.observe_click("query-icon-save-as", Reporting.Controls.toggle_save_as_form);
Reporting.Controls.observe_click("query-icon-save-as-cancel", Reporting.Controls.toggle_save_as_form);
$('#save_as_form').hide();
// When saving a new query, the success-response is the new saved query's url -> redirect to that
Reporting.Controls.attach_settings_callback($("#query-icon-save-button"), function (newLocation) {
document.location = newLocation;
});
// When saving an update of an exisiting query or apply filters, we replace the table on success
Reporting.Controls.attach_settings_callback($("#query-icon-apply-button"), Reporting.Controls.update_result_table);
Reporting.Controls.observe_click('query-link-clear', Reporting.Controls.clear_query);
});
})(jQuery);

@ -0,0 +1,371 @@
//-- copyright
// ReportingEngine
//
// Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// version 3.
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//++
/*jslint white: false, nomen: true, devel: true, on: true, debug: false, evil: true, onevar: false, browser: true, white: false, indent: 2 */
/*global window, $, $$, Reporting, */
Reporting.Filters = function($){
var load_available_values_for_filter = function (filter_name, callback_func) {
var select, radio_options, post_select_values;
select = $('.filter-value[data-filter-name="' + filter_name + '"]').first();
// check if we might have a radio-box
radio_options = $('.' + filter_name + '_radio_option input');
if (radio_options && radio_options.length !== 0) {
radio_options.first().checked = true;
callback_func();
}
if (!select.length) {
return;
}
if (select.attr('data-loading') === "ajax" && select.children().length === 0) {
load_available_values_for_filter_from_remote(select, filter_name, callback_func);
multi_select(select, false);
} else {
callback_func();
}
};
var load_available_values_for_filter_from_remote = function(select, filter_name, callback_func) {
var url = select.attr("data-remote-url"),
json_post_select_values = select.attr('data-initially-selected'),
post_select_values;
if (json_post_select_values !== null && json_post_select_values !== undefined) {
post_select_values = $.parseJSON(json_post_select_values.replace(/'/g, '"'));
}
if (window.global_prefix === undefined) {
window.global_prefix = "";
}
$.ajax({
url: url,
method: 'POST',
data: {
filter_name: filter_name,
values: json_post_select_values
},
beforeSend: function () {
$("select[data-filter-name='" + filter_name + "']").attr('disable', true);
$('#ajax-indicator').show();
},
complete: function (xhr) {
var tagName = select.prop('tagName');
select.html(xhr.responseText);
$("select[data-filter-name='" + filter_name + "']").removeAttr('disable');
if (tagName && tagName.toLowerCase() === "select") {
if (!post_select_values || post_select_values.length === 0) {
select.selectedIndex = 0;
} else {
select_values(select, post_select_values);
}
}
callback_func();
}
});
};
var show_filter = function (field, options) {
var default_options = {
callback_func: function () {},
slowly: false,
show_filter: true,
hide_only: false
};
options = $.extend({}, default_options, options);
var field_el = $('#filter_' + field);
if (field_el !== null) {
if (!options.insert_after) {
options.insert_after = last_visible_filter();
}
if (options.insert_after && options.show_filter) {
// Move the filter down to appear after the last currently visible filter
if (field_el.attr('id') !== options.insert_after.id) {
field_el.detach();
$('#' + options.insert_after.id).after(field_el);
}
}
// the following command might be included into the callback_function (which is called after the ajax request) later
var display_functor;
if (options.show_filter) {
options.slowly ? field_el.fadeIn('slow') : field_el.show();
load_available_values_for_filter(field, options.callback_func);
$('#rm_' + field).val(field); // set the value, so the serialized form will return this filter
value_changed(field);
set_filter_value_widths(100);
} else {
options.slowly ? field_el.fadeOut('slow') : field_el.hide();
if (!options.hide_only) { // remember that this filter used to be selected
field_el.removeAttr('data-selected');
}
$('#rm_' + field).val(""); // reset the value, so the serialized form will not return this filter
set_filter_value_widths(5000);
}
operator_changed(field, $("#operators\\[" + field + "\\]"));
display_category($('#' + field_el.attr("data-label")));
}
};
/**
* Activates the filter with the given name.
*
* @param filter_name Name of the filter to be activated.
*/
var add_filter = function (filter_name) {
var field = filter_name;
// do this immediately instead of in callback to avoid concurrency issues during testing
select_option_enabled($('#add_filter_select'), filter_name, false);
show_filter(field, { slowly: true });
};
var remove_filter = function (field, hide_only) {
show_filter(field, { show_filter: false, hide_only: hide_only });
select_option_enabled($("#add_filter_select"), field, true);
};
/*
Smoothly sets the width of currently displayed filters.
Params:
delay:Int
Time to wait before resizing the filters width */
var set_filter_value_widths = function (delay) {
window.clearTimeout(set_filter_value_widths_timeout);
if (visible_filters().length > 0) {
set_filter_value_widths_timeout = window.setTimeout(function () {
var table_data = $('#filter_' + visible_filters()[0] + ' .advanced-filters--filter-value').first().parent();
var current_width = table_data.width();
var filters = $(".advanced-filters--filter");
// First, reset all widths
filters.css('width', 'auto');
// Now, get the current width
// Any width will be fine, as the table layout makes all elements the same width
var new_width = table_data.width();
if (new_width < current_width) {
// Set all widths to previous, so we can animate
filters.css('width', current_width + 'px');
}
// Now, set all widths to be the widest
if (new_width < current_width) {
filters.animate('width', new_width + 'px');
} else {
filters.css('width', new_width + 'px');
}
}, delay);
}
};
var set_filter_value_widths_timeout;
var last_visible_filter = function () {
return $('.advanced-filters--filter:visible').last()[0];
};
/* Display the given category if any of its filters are visible. Otherwise hide it */
var display_category = function (label) {
if (label.length) {
$('.advanced-filters--filter').each(function() {
var filter = $(this);
if (filter.is(':visible') && filter.attr("data-label") === label) {
$(label).show();
return;
}
$(label).hide();
});
}
};
var operator_changed = function (field, select) {
var option_tag, arity, first;
if (select === null) {
return;
}
first = false;
if (!select.attr("data-first")) {
first = true;
$(select).attr("data-first", "false");
}
option_tag = select.find('option[value="' + select.val() + '"]');
arity = parseInt(option_tag.attr("data-arity"));
change_argument_visibility(field, arity);
if (option_tag.attr("data-forced")) {
force_type(option_tag, first);
}
};
// Overwrite to customize input enforcements.
// option: 'option' HTMLElement
// first: Boolean indicating whether the operator changed for the first time
var force_type = function (option, first) {
return true;
};
var value_changed = function (field) {
var val, filter;
val = $('#' + field + '_arg_1_val');
filter = $('#filter_' + field);
if (!val) {
return;
}
if (val.value === '<<inactive>>') {
filter.addClass('inactive-filter');
} else {
filter.removeClass('inactive-filter');
}
};
var change_argument_visibility = function (field, arg_nr) {
var params, i;
params = [$('#' + field + '_arg_1'), $('#' + field + '_arg_2')];
for (i = 0; i < 2; i += 1) {
if (params[i] !== null) {
if (arg_nr >= (i + 1) || arg_nr <= (-1 - i)) {
params[i].show();
params[i].children().show();
} else {
params[i].hide();
params[i].children().hide();
}
}
}
};
var select_option_enabled = function (box, value, state) {
box.find("[value='" + value + "']").attr('disabled', !state);
};
var multi_select = function (select, multi) {
select.attr('multiple', multi);
if (multi) {
select.attr('size', 4);
// deselect first option if it's present
if (select.find('option')[0]) {
select.find('option').first().attr('selected', false);
}
} else {
select.attr('size', 1);
}
};
var toggle_multi_select = function (select) {
multi_select(select, !select.attr('multiple'));
};
var visible_filters = function () {
return _.map($("#filter_table .advanced-filters--filter:visible"), function(filter) {
return $(filter).attr("data-filter-name");
});
};
var clear = function () {
_.each(visible_filters(), function (filter) {
remove_filter(filter);
});
};
// Select the given values of the selectBox.
// Toggle multi-select state of the selectBox depending on how many values were given.
var select_values = function(selectBox, values_to_select) {
multi_select(selectBox, values_to_select.length > 1);
selectBox.val(values_to_select);
};
var exists = function (filter) {
return visible_filters().indexOf(filter) > 0;
};
return {
add_filter: add_filter,
clear: clear,
exists: exists,
operator_changed: operator_changed,
remove_filter: remove_filter,
select_option_enabled: select_option_enabled,
select_values: select_values,
toggle_multi_select: toggle_multi_select,
value_changed: value_changed
};
}(jQuery);
(function($) {
Reporting.onload(function () {
if ($("#add_filter_select")) {
$("#add_filter_select").on("change", function () {
if (!(Reporting.Filters.exists(this.value))) {
Reporting.Filters.add_filter(this.value);
var new_filter = this.value;
this.selectedIndex = 0;
setTimeout(function () {
$('#operators\\['+ new_filter +'\\]').focus();
}, 300);
}
});
}
$(".filter_rem")
.on("click", function (event) {
event.preventDefault();
var filter_name = $(this).closest('li').attr("data-filter-name");
Reporting.Filters.remove_filter(filter_name);
})
.on("keydown", function (event) {
if (event.keyCode == 13 || event.keyCode == 32) {
event.preventDefault();
var filter_name = $(this).closest('li').attr("data-filter-name"),
prevVisibleFilter = $(this).closest('li').prevAll(':visible').last().find('.advanced-filters--select');
if (prevVisibleFilter.length > 0) {
prevVisibleFilter.focus();
} else {
$('#filters > legend a')[0].focus();
}
Reporting.Filters.remove_filter(filter_name);
}
});
$(".filter_operator")
.on("change", function (evt) {
var filter_name = $(this).attr("data-filter-name");
Reporting.Filters.operator_changed(filter_name, $(this));
Reporting.fireEvent($('#' + filter_name + "_arg_1_val")[0], "change");
});
$(".filter_multi-select")
.on("click", function () {
var filter_name = $(this).attr("data-filter-name");
Reporting.Filters.toggle_multi_select($('#' + filter_name + '_arg_1_val'));
});
$(".advanced-filters--filter-value .filter-value").each(function () {
var select = $(this);
select_value = select.val();
select.attr('multiple', select_value && select_value.length > 1);
select.on("change", function (evt) {
var filter_name = $(this).closest('li').attr("data-filter-name");
Reporting.Filters.value_changed(filter_name);
});
});
});
})(jQuery);

@ -0,0 +1,191 @@
//-- copyright
// ReportingEngine
//
// Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// version 3.
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//++
/*jslint white: false, nomen: true, devel: true, on: true, debug: false, evil: true, onevar: false, browser: true, white: false, indent: 2 */
/*global window, $, $$, Reporting, Effect, Ajax, selectAllOptions, moveOptions, moveOptionUp, moveOptionDown */
Reporting.GroupBys = (function($){
var group_by_container_ids = function() {
var ids = ['group-by--columns', 'group-by--rows'];
return _.filter(ids, function (i) {
return $('#' + i).length > 0 ;
});
};
var recreate_sortables = function() {
var containers = $('.group-by--selected-elements')
.toArray();
dragula(containers,
{
// Setting the mirrorContainer to something smaller than the body
// reduces the performance hit when using dnd.
mirrorContainer: document.getElementById('group-by--area')
});
};
var initialize_drag_and_drop_areas = function() {
recreate_sortables();
};
var create_label = function(group_by, text) {
return $('<label></label>')
.attr('class', 'in_row group-by--label')
.attr('for', group_by.attr('id'))
.attr('id', group_by.attr('id') + '_label')
.html(text);
};
var create_remove_button = function(group_by) {
var remove_link, remove_icon;
remove_link = $('<a></a>');
remove_link.attr('class', 'group-by--remove in_row');
remove_link.attr('id', group_by.attr('id') + '_remove');
remove_link.attr('href', '');
remove_icon = $('<span><span>');
remove_icon.attr('class', 'icon-context icon-close icon4');
remove_link.attr('title', I18n.t("js.reporting_engine.label_remove") + ' ' + group_by.find('label').html());
remove_icon.attr('alt', I18n.t("js.reporting_engine.label_remove") + ' ' + group_by.find('label').html());
remove_link.on('click', function(e) {
e.preventDefault();
remove_element_event_action(e, group_by, remove_link);
});
remove_link.on('keypress', function(e) {
/* keyCode 32: Space */
if (e.keyCode == 32) {
e.preventDefault();
remove_element_event_action(e, group_by, remove_link);
}
});
remove_link.append(remove_icon);
return remove_link;
};
var remove_element_event_action = function(event, group_by, button) {
var link_node = group_by.next('span').find('a'),
select_node = group_by.next('select');
if (link_node.length) {
link_node.focus();
}
else if (select_node.length) {
select_node.focus();
}
remove_group_by(button.closest('.group-by--selected-element'));
};
var create_group_by = function(field, caption) {
var group_by, label, right_arrow, left_arrow, remove_button;
group_by = $('<span></span>');
group_by.attr('class', 'group-by--selected-element');
group_by.attr('data-group-by', field);
group_by.uniqueId(); // give it a unique id
label = create_label(group_by, caption);
group_by.append(label);
remove_button = create_remove_button(group_by);
group_by.append(remove_button);
return group_by;
};
// This is whether it is possible to add a new group if <<field>> through the
// add-group-by select-box or not.
var adding_group_by_enabled = function(field, state) {
_.each(['#group-by--add-columns', '#group-by--add-rows'], function(container_id) {
Reporting.Filters.select_option_enabled($(container_id), field, state);
});
};
var remove_group_by = function(group_by) {
adding_group_by_enabled(group_by.attr('data-group-by'), true);
group_by.remove();
};
var add_group_by_from_select = function(select) {
var jselect = $(select),
field = jselect.val(),
container = jselect.closest('.group-by--container'),
selected_option = jselect.find("[value='" + field + "']").first(),
caption = selected_option.attr('data-label');
Reporting.GroupBys.add_group_by(field, caption, container);
jselect.find("[value='']").first().attr('selected', true);
};
var add_group_by = function(field, caption, container) {
var group_by, add_groups_select_box, added_container;
add_groups_select_box = container.find('select').first();
group_by = Reporting.GroupBys.create_group_by(field, caption);
added_container = container.find('.group-by--selected-elements');
added_container.append(group_by);
adding_group_by_enabled(field, false);
};
var clear = function() {
_.each(visible_group_bys(), function (group_by) {
$('#' + group_by + ' .group-by--selected-element').each(function() {
remove_group_by($(this));
});
});
};
var visible_group_bys = function() {
var visible = _.filter(group_by_container_ids(), function (container) {
return $('#' + container).find('[data-group-by]');
});
return _.flatten(visible);
};
var exists = function(group_by_name) {
return _.some(visible_group_bys(), function (grp) {
return $('#' + grp).attr('data-group-by') === group_by_name;
});
};
return {
add_group_by: add_group_by,
add_group_by_from_select: add_group_by_from_select,
clear: clear,
create_group_by: create_group_by,
exists: exists,
group_by_container_ids: group_by_container_ids,
initialize_drag_and_drop_areas: initialize_drag_and_drop_areas
};
})(jQuery);
(function($) {
Reporting.onload(function () {
Reporting.GroupBys.initialize_drag_and_drop_areas();
$('#group-by--add-rows, #group-by--add-columns').on('change', function () {
if (!(Reporting.GroupBys.exists(this.value))) {
Reporting.GroupBys.add_group_by_from_select(this);
}
});
});
})(jQuery);

@ -0,0 +1,101 @@
//-- copyright
// ReportingEngine
//
// Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// version 3.
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//++
/*jslint white: false, nomen: true, devel: true, on: true, debug: false, evil: true, onevar: false, browser: true, white: false, indent: 2 */
/*global window, $, $$, Reporting, Effect, Ajax */
Reporting.RestoreQuery = function($){
var select_operator = function (field, operator) {
var select, i;
select = $("#operators_" + field);
if (select === null) {
return; // there is no such operator select field
}
for (i = 0; i < select.options.length; i += 1) {
if (select.options[i].value === operator) {
select.selectedIndex = i;
break;
}
}
Reporting.Filters.operator_changed(field, select);
};
var disable_select_option = function (select, field) {
for (var i = 0; i < select.options.length; i += 1) {
if (select.options[i].value === field) {
select.options[i].disabled = true;
break;
}
}
};
var restore_filters = function () {
var deps = _.each($('.advanced-filters--select.filter-value'), function(select) {
var jselect = $(select),
tr = jselect.closest('li');
if (tr.visible()) {
var filter = tr.attr('data-filter-name');
var dependent = jselect.attr('data-dependent');
if (filter && dependent) {
Reporting.Filters.remove_filter(filter, false);
}
}
});
_.each($("li.advanced-filters--filter[data-selected=true]"), function (e) {
var filter = $(e),
select = filter.find(".advanced-filters--filter-value select");
if (select && select.attr("data-dependent")) return;
var filter_name = filter.attr("data-filter-name");
Reporting.Filters.add_filter(filter_name);
});
};
var restore_group_bys = function () {
_.each(Reporting.GroupBys.group_by_container_ids(), function(id) {
var container = $('#' + id),
selected_containers = container.attr('data-initially-selected'),
selected_groups;
if (selected_containers) {
selected_groups = $.parseJSON(selected_containers.replace(/'/g, '"'));
_.each(selected_groups, function(group_and_label) {
var group, label;
group = group_and_label[0];
label = group_and_label[1];
Reporting.GroupBys.add_group_by(group, label, container);
});
}
});
};
return {
restore_group_bys: restore_group_bys,
restore_filters: restore_filters
};
}(jQuery);
Reporting.onload(function () {
Reporting.RestoreQuery.restore_group_bys();
Reporting.RestoreQuery.restore_filters();
});

@ -0,0 +1,24 @@
//-- copyright
// ReportingEngine
//
// Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// version 3.
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//++
//= require reporting_engine/reporting
//= require reporting_engine/reporting/filters
//= require reporting_engine/reporting/group_bys
//= require reporting_engine/reporting/restore_query
//= require reporting_engine/reporting/controls

@ -0,0 +1,452 @@
/*-- copyright
ReportingEngine
Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 3.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
++*/
.cost_types {
padding-bottom: 3px;
}
.cost_types a.active {
color: #000;
font-weight: bold;
}
.report {
text-align: center;
border-collapse: collapse;
border: solid 1px #ccc !important;
width: auto !important;
}
.report td, .report th {
min-width: 90px;
white-space: nowrap;
}
.report td {
border: dotted 1px #ddd;
color: #666;
text-align: center;
padding: 0 8px 0 8px;
line-height: 2rem;
vertical-align: middle;
}
.report tbody th, .report tbody td, .inner {
max-width: 300px;
white-space: normal !important;
}
.report td:hover {
color: #000;
outline: #ccc 1px solid;
outline-offset: 1px;
}
.report td.empty:hover {
outline: none;
}
.report th {
border: solid 1px #ccc;
background-color: #e3e3e3;
text-align: center;
font-size: 0.875rem;
line-height: 34px;
padding: 0 8px 0 8px;
}
.report .odd th.inner {
background-color: #e8e8e8;
}
.report .even th.inner {
background-color: #e3e3e3;
}
.report th.inner {
border: solid 1px #ccc;
background-color: #efefef;
text-align: right;
}
.report .odd td.inner {
background-color: #e8e8e8;
}
.report .even td.inner {
background-color: #e3e3e3;
}
.report tr.even:hover .inner,
.report tr.even:hover .bottom,
.report tr.even:hover .empty,
.report tr.even:hover .right {
background-color: #f5f5c5 !important;
}
/* IE7 made me do it! */
.report tr.odd:hover .inner,
.report tr.odd:hover .bottom,
.report tr.odd:hover .empty,
.report tr.odd:hover .right {
background-color: #f5f5c5 !important;
}
.report .top {
border-top-style: solid;
border-top-color: #ccc;
/* border-top: 2px solid #ccc !important; */
}
.report .bottom {
border-bottom-style: solid;
border-bottom-color: #ccc;
/* border-bottom: 2px solid #ccc !important; */
}
.report td.penultimate {
border-right-style: solid;
}
.report thead .inner, .report tfoot .inner {
text-align: right;
padding-right: 5px;
}
.report .result {
font-size: 120%;
text-align: right;
}
#result-table {
margin-top: 10px !important;
overflow-x: auto;
}
.report thead tr:hover .inner, .report tfoot tr:hover .inner {
background-color: #efefef;
}
.report .left {
text-align: left !important;
padding-left: 5px;
}
.report .right {
text-align: right !important;
padding-right: 5px;
}
/* Details view*/
.detail-report td {
text-align: left;
vertical-align: top;
}
#query_form fieldset.header_collapsible.collapsible {
padding-bottom: 10px;
}
/* Overwriting styling for headlines within the query. */
/* TODO: Font-size seems to be a bit odd. Needs some love. */
.new_report fieldset h3 {
font-size: 1.17em;
border: none;
}
.filter {
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
.inactive-filter {
background-color: #FCE29A !important;
}
.advanced-filters--filter-value {
white-space: nowrap;
}
.filter_radio_option {
padding-left: 5px;
padding-right: 5px;
}
#add_filter_block {
margin-top: 6px;
}
#add_filter_select {
margin-bottom: 10px;
}
/* ----- group by --- */
#group-by--area {
margin: 5px 0 10px 0;
}
#group-by--area fieldset {
border: none;
padding: 0px;
margin-bottom: 1em;
}
.in_row {
display: inline-block;
list-style: none;
border-width: 0px;
}
.group-by--selected-element {
cursor: move;
position: relative;
background-color: #767676;
padding-left: 14px;
margin-left: 18px;
}
fieldset.collapsible.header_collapsible legend.in_row {
width: inherit;
background-image: inherit;
}
.group-by--container {
overflow: hidden;
}
.group-by--label {
margin: 0px;
padding: 0px 18px 0 0;
min-width: 60px;
text-align: center;
white-space: nowrap;
font-weight: bold;
color: #fff;
height: 36px;
line-height: 36px;
cursor: move;
}
.group-by--selected-element:after, .group-by--selected-element:before {
border: solid transparent;
content: " ";
height: 0;
width: 0;
position: absolute;
pointer-events: none;
top: 50%;
border-width: 30px 0px 30px 14px;
margin-top: -30px;
}
.group-by--selected-element:after {
border-color: rgba(118, 118, 118, 0);
border-left-color: rgba(118, 118, 118, 1);
left: 100%;
}
.group-by--selected-element:before {
border-color: rgba(118, 118, 118, 1);
border-left-color: rgba(118, 118, 118, 0);
left: -14px;
}
.group-by--selected-element:hover:after {
border-color: rgba(52, 147, 179, 0);
border-left-color: rgba(52, 147, 179, 1);
}
.group-by--selected-element:hover:before {
border-color: rgba(52, 147, 179, 1);
border-left-color: rgba(52, 147, 179, 0);
}
.group-by--selected-element:hover {
background-color: #3493B3;
}
.group-by--remove {
line-height: normal;
cursor: pointer;
color: #FFFFFF;
}
.group-by--remove:hover {
background-color: #3493B3 !important;
text-decoration: none;
color: #FFFFFF;
}
.group-by--control {
margin: 0;
padding: 0;
}
.group-by--selected-elements {
background-color: #EEE;
overflow: hidden;
}
.group-by--caption {
position: relative;
color: #FFFFFF;
background-color: #4B4B4B;
font-weight: bold;
padding: 0 7px;
margin: 0;
height: inherit;
line-height: 36px;
min-width: 55px;
overflow: visible;
}
.group-by--caption:after {
left: 100%;
top: 50%;
border: solid transparent;
content: " ";
height: 0;
width: 0;
position: absolute;
pointer-events: none;
}
.group-by--caption:after {
border-color: rgba(75, 75, 75, 0);
border-left-color: #4B4B4B;
border-width: 30px 0px 30px 14px;
margin-top: -30px;
z-index: 10;
}
/* Overwrite normal h3 definition - a h-tag is needed for accessibility purposes */
h3.reporting_formatting {
font-weight:normal;
font-size: 13px;
margin:0px;
padding:0px;
color:#333;
border:0px;
}
/* -- end group-by -- */
td .drill_down, th .drill_down {
font-size: 8px;
display: block;
float: right;
font-weight: bold;
visibility: hidden;
}
td:hover .drill_down, th:hover .drill_down {
visibility: visible;
}
/*Buttons*/
.form_controls {
margin-top: 6px;
}
.form_controls .button {
margin-bottom: 0;
}
div.button_form {
/* TODO IE Compatibility! */
background-color: white;
border: 1px solid gray;
-moz-border-radius: 3px;
border-radius: 3px;
left: 100px;
position: absolute;
padding: 1.0rem;
width: 400px;
}
/***** Save and Delete Reports ****/
#save_as_form, #delete_form {
z-index: 999;
}
/* Calendar Fixes */
div.calendar /* let calendar expand properly */
{
font-size: medium;
line-height: normal;
}
div.calendar table div { /* make sure the nested divs are large enough, too */
font-size: medium;
line-height: normal;
}
.calendar .combo .label, .calendar .combo .label-IEfix { /* set the proper size for the combo boxes with months and years */
font-size: 10px;
line-height: normal;
}
.calendar tbody .day { /* avoid jitter during quick mouse-overs over days */
border: 1px dotted transparent;
padding: 1px 3px 1px 1px;
}
/* Accessibility specific styles */
fieldset#filters table td > label.hidden-for-sighted, .hidden-for-sighted {
position:absolute;
left:-10000px;
top:auto;
width:1px;
height:1px;
overflow:hidden;
}
.advanced-filters--filter-value.-binary {
display: flex;
}
@media only screen and (max-width: 679px) {
.group-by--control {
margin-top: 10px;
}
#group-by--rows .group-by--caption,
#group-by--columns .group-by--caption {
padding: 0 7px;
}
.group-by--selected-element {
display: inline-block;
padding-left: 7px;
}
.group-by--selected-element:before,
.group-by--selected-element:after {
border-width: 18px 0px 18px 14px;
margin-top: -18px;
}
.group-by--selected-element:first-of-type {
margin: 0;
}
.group-by--selected-element:first-of-type:before {
border: none;
left: 0;
}
}

@ -0,0 +1,23 @@
/*-- copyright
ReportingEngine
Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 3.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
++*/
/* *
*= require reporting_engine/reporting
*/

@ -0,0 +1,36 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
module Engine
##
# Subclass of Report to be used for constant lookup and such.
# It is considered public API to override this method i.e. in Tests.
#
# @return [Class] subclass
def engine
return @engine if @engine
if is_a? Module
@engine = Object.const_get(name[/^[^:]+/] || :Report)
elsif respond_to? :parent and parent.respond_to? :engine
parent.engine
else
self.class.engine
end
end
end

@ -0,0 +1,213 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
class Report < ActiveRecord::Base
extend Forwardable
include Enumerable
include Engine
belongs_to :user
belongs_to :project
before_save :serialize
serialize :serialized, Hash
self.abstract_class = true # lets have subclasses have their own SQL tables
def self.accepted_properties
@@accepted_properties ||= []
end
def self.reporting_connection
connection
end
def self.chain_initializer
@chain_initializer ||= []
end
def self.deserialize(hash, object = new)
object.tap do |q|
hash[:filters].each { |name, opts| q.filter(name, opts) }
hash[:group_bys].each { |name, opts| q.group_by(name, opts) }
end
end
def serialize
# have to take the reverse group_bys to retain the original order when deserializing
self.serialized = { filters: (filters.map(&:serialize).reject(&:nil?).sort { |a, b| a.first <=> b.first }),
group_bys: group_bys.map(&:serialize).reject(&:nil?).reverse }
end
def deserialize
unless @chain
hash = serialized || serialize
self.class.deserialize(hash, self)
else
raise ArgumentError, 'Cannot deserialize a report which already has a chain'
end
end
# Convenience method to generate a params hash readable by Controller#determine_settings
def to_params
params = {}
filters.select { |f| f.class.display? }.each do |f|
filter_name = f.class.underscore_name
params[:fields] << filter_name
params[:operators].merge! filter_name => f.operator.to_s
params[:values].merge! filter_name => f.values
end
group_bys.each do |g|
params[:groups] ||= { rows: [], columns: [] }
params[:groups][g.row? ? :rows : :columns] << g.class.underscore_name
end
params
end
##
# Migrates this report to look like the given report.
# This may be used to alter report properties without
# creating a new report in a database.
def migrate(report)
[:@chain, :@query, :@transformer, :@walker, :@table, :@depths, :@chain_initializer].each do |inst_var|
instance_variable_set inst_var, (report.instance_variable_get inst_var)
end
end
def available_filters
self.class::Filter.all
end
def transformer
@transformer ||= self.class::Transformer.new self
end
def walker
@walker ||= self.class::Walker.new self
end
def add_chain(type, name, options)
chain type.const_get(name.to_s.camelcase), options
@transformer, @table, @depths, @walker = nil, nil, nil, nil
self
end
def chain(klass = nil, options = {})
build_new_chain unless @chain
if klass
@chain = klass.new @chain, options
@chain.engine = self.class
end
@chain = @chain.parent until @chain.top?
@chain
end
def build_new_chain
# FIXME: is there a better way to load all filter and groups?
self.class::Filter.all && self.class::GroupBy.all
minimal_chain!
self.class.chain_initializer.each { |block| block.call self }
self
end
def filter(name, options = {})
add_chain self.class::Filter, name, options
end
def group_by(name, options = {})
add_chain self.class::GroupBy, name, options.reverse_merge(type: :column)
end
def column(name, options = {})
group_by name, options.merge(type: :column)
end
def row(name, options = {})
group_by name, options.merge(type: :row)
end
def table
@table = self.class::Table.new(self)
end
def group_bys(type = nil)
chain.select { |c| c.group_by? && (type.nil? || c.type == type) }
end
def filters
chain.select(&:filter?)
end
def depth_of(name)
@depths ||= {}
@depths[name] ||= chain.inject(0) { |sum, child| child.type == name ? sum + 1 : sum }
end
def_delegators :transformer, :column_first, :row_first
def_delegators :chain, :empty_chain, :top, :bottom, :chain_collect, :sql_statement, :all_group_fields, :child, :clear, :result
def_delegators :result, :each_direct_result, :recursive_each, :recursive_each_with_level, :each, :each_row, :count,
:units, :final_number
def_delegators :table, :row_index, :colum_index
def to_a
chain.to_a
end
def to_s
chain.to_s
end
def size
size = 0
recursive_each { |r| size += r.size }
size
end
def cache_key
deserialize unless @chain
parts = [self.class.table_name.sub('_reports', '')]
parts.concat [filters.sort, group_bys].map { |l| l.map(&:cache_key).join(' ') }
parts.join '/'
end
def self.engine
self
end
def minimal_chain!
@chain = self.class::Filter::NoFilter.new
end
def public!
self.is_public = true
end
def public?
is_public
end
def private!
self.is_public = false
end
def private?
!public?
end
end

@ -0,0 +1,335 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
# Provides convinience layer and logic shared between GroupBy::Base and Filter::Base.
# Implements a double linked list (FIXME: is that the correct term?).
class Report < ActiveRecord::Base
class Chainable
include Enumerable
include Report::QueryUtils
extend Report::InheritedAttribute
extend Forwardable
# this attr. should point to a symbol useable for translations
inherited_attribute :applies_for, default: :label_cost_entry_attributes
def_delegators :'self.class', :table_joins, :table_name, :field, :display?, :underscore_name
def self.accepts_property(*list)
engine.accepted_properties.push(*list.map(&:to_s))
end
def self.chain_list(*list)
options = list.extract_options!
options[:list] = true
list << options
inherited_attribute(*list)
end
def self.base?
superclass == engine::Chainable or self == engine::Chainable or
superclass == Chainable or self == Chainable or
self == engine::Filter::Base or self == engine::GroupBy::Base
end
def self.base
return self if base?
superclass.base
end
def self.from_base(&block)
base.instance_eval(&block)
end
def self.available
from_base { @available ||= [] }
end
def self.register(label)
available << klass
set_inherited_attribute 'label', label
end
def self.table_joins
(@table_joins ||= []).clone
end
def self.table_from(value)
return value.table_name if value.respond_to? :table_name
return value unless value.respond_to? :to_ary or value.respond_to? :to_hash
table_from value.to_a.first
end
def self.join_table(*args)
@last_table = table_from(args.last)
(@table_joins ||= []) << args
end
def self.underscore_name
name.demodulize.underscore
end
def self.put_sql_table_names(table_prefix_placement = {})
@table_prefix_placement ||= {}
@table_prefix_placement.merge! table_prefix_placement
@table_prefix_placement
end
##
# The given block is called when a new chain is created for a report.
# The query will be given to the block as a parameter.
# Example:
# initialize_query_with { |query| query.filter Report::Filter::City, :operators => '=', :values => 'Berlin, da great City' }
def self.initialize_query_with(&block)
engine.chain_initializer.push block
end
def self.cache_key
@cache_key ||= underscore_name
end
inherited_attribute :properties, list: true
def self.label
'Translation needed'
end
class << self
alias inherited_attributes inherited_attribute
alias accepts_properties accepts_property
end
attr_accessor :parent, :child, :type
accepts_property :type
def each(&block)
yield self
child.try(:each, &block)
end
def row?
type == :row
end
def column?
type == :column
end
def group_by?
!filter?
end
def to_a
[to_hash].tap { |a| a.unshift(*child.to_a) unless bottom? }
end
def top
return self if top?
parent.top
end
def top?
parent.nil?
end
def bottom?
child.nil?
end
def bottom
return self if bottom?
child.bottom
end
def initialize(child = nil, options = {})
@options = options
options.each do |key, value|
unless self.class.extra_options.include? key
raise ArgumentError, "may not set #{key}" unless engine.accepted_properties.include? key.to_s
send "#{key}=", value
end
end
self.child, child.parent = child, self if child
move_down until correct_position?
clear
end
def to_a
cached :compute_to_a
end
def compute_to_a
[[self.class.field, @options], *child.try(:to_a)].compact
end
def to_s
URI.escape to_a.map(&:join).join(',')
end
def serialize
[self.class.to_s.demodulize, @options]
end
def move_down
reorder parent, child, self, child.child
end
##
# Reorder given elements of a doubly linked list to follow the lists order.
# Don't use this for evil. Assumes there are no elements inbetween, does
# not touch the first element's parent and the last element's child.
# Does not touch elements not part of the list.
#
# @param [Array] *list Part of the linked list
def reorder(*list)
list.each_with_index do |entry, index|
next_entry = list[index + 1]
entry.try(:child=, next_entry) if index < list.size - 1
next_entry.try(:parent=, entry)
end
end
def chain_collect(name, *args, &block)
top.subchain_collect(name, *args, &block)
end
# See #chain_collect
def subchain_collect(name, *args, &block)
subchain = child.subchain_collect(name, *args, &block) unless bottom?
[* send(name, *args, &block)].push(*subchain).compact.uniq
end
# overwrite in subclass to maintain constisten state
# ie automatically turning
# FilterFoo.new(GroupByFoo.new(FilterBar.new))
# into
# GroupByFoo.new(FilterFoo.new(FilterBar.new))
# Returning false will make the
def correct_position?
true
end
def clear
@cached = nil
child.try :clear
end
def result
cached(:compute_result)
end
def compute_result
engine::Result.new engine.reporting_connection.select_all(sql_statement.to_s), {}, type
end
def cached(*args)
@cached ||= {}
@cached[args] ||= send(*args)
end
def sql_statement
raise "should not get here (#{inspect})" if bottom?
child.cached(:sql_statement).tap do |q|
chain_collect(:table_joins).each { |args| q.join(*args) } if responsible_for_sql?
end
end
inherited_attribute :db_field
def self.field
db_field || (name[/[^:]+$/] || name).to_s.underscore
end
def display?
self.class.display?
end
inherited_attribute :display, default: true
def self.display!
display true
end
def self.display?
!!display
end
def self.dont_display!
display false
not_selectable!
end
inherited_attribute :selectable, default: true
def self.selectable!
selectable true
end
def self.selectable?
!!selectable
end
def self.not_selectable!
selectable false
end
# Extra options this chainable accepts that are not defined in accepted_properties
def self.extra_options(*symbols)
@extra_option ||= []
@extra_option += symbols
end
# This chainable type can only ever occur once in a chain
def self.singleton
class << self
def new(chain = nil, options = {})
return chain if chain and chain.map(&:class).include? self
super
end
end
end
def self.last_table
@last_table ||= engine::Filter::NoFilter.table_name
end
def self.table_name(value = nil)
@table_name = table_name_for(value) if value
@table_name || last_table
end
def with_table(fields)
fields.map do |f|
place_field_name = self.class.put_sql_table_names[f] || self.class.put_sql_table_names[f].nil?
place_field_name ? (field_name_for f, self) : f
end
end
def mapping
self.class.method(:mapping).to_proc
end
def self.mapping(value)
value.to_s
end
def self.mapping_for(field)
@field_map ||= (engine::Filter.all + engine.GroupBy.all).inject(Hash.new { |h, k| h[k] = [] }) do |hash, cbl|
hash[cbl.field] << cbl.mapping
end
@field_map[field]
end
end
end

@ -0,0 +1,338 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
require 'json'
module Report::Controller
def self.included(base)
base.class_eval do
attr_accessor :report_engine
helper_method :current_user
helper_method :allowed_to?
include ReportingHelper
helper ReportingHelper
helper { def engine; @report_engine; end }
before_action :determine_engine
before_action :prepare_query, only: [:index, :create]
before_action :find_optional_report, only: [:index, :show, :update, :destroy, :rename]
before_action :possibly_only_narrow_values
end
end
def index
table
end
##
# Render the report. Renders either the complete index or the table only
def table
if set_filter? && request.xhr?
self.response_body = render_widget(Widget::Table, @query)
end
end
##
# Create a new saved query. Returns the redirect url to an XHR or redirects directly
def create
@query.name = params[:query_name].present? ? params[:query_name] : ::I18n.t(:label_default)
@query.public! if make_query_public?
@query.send("#{user_key}=", current_user.id)
@query.save!
if request.xhr? # Update via AJAX - return url for redirect
render plain: url_for(action: 'show', id: @query.id)
else # Redirect to the new record
redirect_to action: 'show', id: @query.id
end
end
##
# Show a saved record, if found. Raises RecordNotFound if the specified query
# at :id does not exist
def show
if @query
store_query(@query)
table
render action: 'index' unless performed?
else
raise ActiveRecord::RecordNotFound
end
end
##
# Delete a saved record, if found. Redirects to index on success, raises a
# RecordNotFound if the query at :id does not exist
def destroy
if @query
@query.destroy if allowed_to? :destroy, @query
else
raise ActiveRecord::RecordNotFound
end
redirect_to action: 'index', default: 1
end
##
# Update a record with new query parameters and save it. Redirects to the
# specified record or renders the updated table on XHR
def update
if params[:set_filter].to_i == 1 # save
old_query = @query
prepare_query
old_query.migrate(@query)
old_query.save!
@query = old_query
end
if request.xhr?
table
else
redirect_to action: 'show', id: @query.id
end
end
##
# Rename a record and update its publicity. Redirects to the updated record or
# renders the updated name on XHR
def rename
@query.name = params[:query_name]
@query.public! if make_query_public?
@query.save!
store_query(@query)
unless request.xhr?
redirect_to action: 'show', id: @query.id
else
render plain: @query.name
end
end
##
# Determine the available values for the specified filter and return them as
# json, if that was requested. This will be executed INSTEAD of the actual action
def possibly_only_narrow_values
if params[:narrow_values] == '1'
sources = params[:sources]
dependent = params[:dependent]
query = report_engine.new
sources.each do |dependency|
query.filter(dependency.to_sym,
operator: params[:operators][dependency],
values: params[:values][dependency])
end
query.column(dependent)
values = [[::I18n.t(:label_inactive), '<<inactive>>']] + query.result.map { |r| r.fields[query.group_bys.first.field] }
# replace null-values with corresponding placeholder
values = values.map { |value| value.nil? ? [::I18n.t(:label_none), '<<null>>'] : value }
# try to find corresponding labels to the given values
values = values.map do |value|
filter = report_engine::Filter.const_get(dependent.camelcase.to_sym)
filter_value = filter.label_for_value value
if filter_value && filter_value.first.is_a?(Symbol)
[::I18n.t(filter_value.first), filter_value.second]
elsif filter_value && filter_value.first.is_a?(String)
[filter_value.first, filter_value.second]
else
value
end
end
render json: values.to_json
end
end
##
# Determine the requested engine by constantizing from the :engine parameter
# Sets @report_engine and @title based on that, and makes the engine available
# to views and widgets via the #engine method.
# Raises RecordNotFound on failure
def determine_engine
@report_engine = params[:engine].constantize
@title = "label_#{@report_engine.name.underscore}"
rescue NameError
raise ActiveRecord::RecordNotFound, 'No engine found - override #determine_engine'
end
##
# Determines if the request contains filters to set
def set_filter? # FIXME: rename to set_query?
params[:set_filter].to_i == 1
end
##
# Return the active filters
def filter_params
filters = http_filter_parameters if set_filter?
filters ||= session[report_engine.name.underscore.to_sym].try(:[], :filters)
filters ||= default_filter_parameters
end
##
# Return the active group bys
def group_params
groups = http_group_parameters if set_filter?
groups ||= session[report_engine.name.underscore.to_sym].try(:[], :groups)
groups ||= default_group_parameters
end
##
# Extract active filters from the http params
def http_filter_parameters
params[:fields] ||= []
(params[:fields].reject(&:empty?) || []).inject(operators: {}, values: {}) do |hash, field|
hash[:operators][field.to_sym] = params[:operators][field]
hash[:values][field.to_sym] = params[:values][field]
hash
end
end
##
# Extract active group bys from the http params
def http_group_parameters
if params[:groups]
rows = params[:groups]['rows']
columns = params[:groups]['columns']
end
{ rows: (rows || []), columns: (columns || []) }
end
##
# Set a default query to cut down initial load time
def default_filter_parameters
{ operators: {}, values: {} }
end
##
# Set a default query to cut down initial load time
def default_group_parameters
{ columns: [:sector_id], rows: [:country_id] }
end
##
# Determines if the query settings should be reset
def force_default?
params[:default].to_i == 1
end
##
# Prepare the query from the request
def prepare_query
determine_settings
@query = build_query(session[report_engine.name.underscore.to_sym][:filters],
session[report_engine.name.underscore.to_sym][:groups])
end
##
# Determine the query settings the current request and save it to
# the session.
def determine_settings
if force_default?
filters = default_filter_parameters
groups = default_group_parameters
session[report_engine.name.underscore.to_sym].try :delete, :name
else
filters = filter_params
groups = group_params
end
cookie = session[report_engine.name.underscore.to_sym] || {}
session[report_engine.name.underscore.to_sym] = cookie.merge(filters: filters, groups: groups)
end
##
# Build the query from the passed session hash
def build_query(filters, groups = {})
query = report_engine.new
query.tap do |q|
filters[:operators].each do |filter, operator|
unless filters[:values][filter] == ['<<inactive>>']
values = Array(filters[:values][filter]).map { |v| v == '<<null>>' ? nil : v }
q.filter(filter.to_sym,
operator: operator,
values: values)
end
end
end
groups[:columns].try(:reverse_each) { |c| query.column(c) }
groups[:rows].try(:reverse_each) { |r| query.row(r) }
query
end
##
# Store query in the session
def store_query(_query)
cookie = {}
cookie[:groups] = @query.group_bys.inject({}) do |h, group|
((h[:"#{group.type}s"] ||= []) << group.underscore_name.to_sym) && h
end
cookie[:filters] = @query.filters.inject(operators: {}, values: {}) do |h, filter|
h[:operators][filter.underscore_name.to_sym] = filter.operator.to_s
h[:values][filter.underscore_name.to_sym] = filter.values
h
end
cookie[:name] = @query.name if @query.name
session[report_engine.name.underscore.to_sym] = cookie
end
##
# Override in subclass if user key
def user_key
'user_id'
end
##
# Override in subclass if you like
def is_public_sql(val = true)
"(is_public = #{val ? report_engine.reporting_connection.quoted_true : report_engine.reporting_connection.quoted_false})"
end
##
# Abstract: Implementation required in application
def allowed_to?(_action, _subject, _user = current_user)
raise NotImplementedError, "The #{self.class} should have implemented #allowed_to?(action, subject, user)"
end
def make_query_public?
!!params[:query_is_public]
end
# renders option tags for each available value for a single filter
def available_values
if name = params[:filter_name]
f_cls = report_engine::Filter.const_get(name.to_s.camelcase)
filter = f_cls.new.tap do |f|
f.values = JSON.parse(params[:values].gsub("'", '"')) if params[:values].present? and params[:values]
end
render_widget Widget::Filters::Option, filter, to: canvas = ''
render plain: canvas, layout: !request.xhr?
end
end
##
# Find a report if :id was passed as parameter.
# Raises RecordNotFound if an invalid :id was passed.
#
# @param query An optional query added to the disjunction qualifiying reports to be returned.
def find_optional_report(query = '1=0')
if params[:id]
@query = report_engine
.where(["#{is_public_sql} OR (#{user_key} = ?) OR (#{query})", current_user.id])
.find(params[:id].to_i)
@query.deserialize if @query
end
rescue ActiveRecord::RecordNotFound
end
end

@ -0,0 +1,38 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
require 'set'
class Report::Filter
def self.all
@all ||= Set[]
end
def self.reset!
@all = nil
end
def self.all_grouped
all.group_by(&:applies_for).to_a.sort { |a, b| a.first.to_s <=> b.first.to_s }
end
def self.from_hash
raise NotImplementedError
end
end

@ -0,0 +1,186 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
class Report::Filter
class Base < Report::Chainable
include Report::QueryUtils
engine::Operator.load
inherited_attribute :available_operators,
list: true, map: :to_operator,
uniq: true
inherited_attribute :default_operator, map: :to_operator
accepts_property :values, :value, :operator
mattr_accessor :skip_inherited_operators
self.skip_inherited_operators = [:time_operators, 'y', 'n']
attr_accessor :values
def cache_key
self.class.cache_key + operator.to_s + Array(values).join(',')
end
##
# A Filter is 'heavy' if it possibly returns a _hughe_ number of available_values.
# In that case the UI-guys should think twice about displaying all the values.
def self.heavy?
false
end
# Indicates whether this Filter is a multiple choice filter,
# meaning that the user must select a value of a given set of choices.
def self.is_multiple_choice?
false
end
# need this for sort
def <=>(other)
self.class.underscore_name <=> other.class.underscore_name
end
def self.cached(*args)
@cached ||= {}
@cached[args] ||= send(*args)
end
def value=(val)
self.values = [val]
end
##
# Always empty. You may include additional_operators as a filter module.
# This is here for the case you don't.
def additional_operators
[]
end
def self.use(*names)
operators = []
names.each do |name|
dont_inherit :available_operators if skip_inherited_operators.include? name
case name
when String, engine::Operator then operators << name.to_operator
when Symbol then operators.push(*engine::Operator.send(name))
else fail "dunno what to do with #{name.inspect}"
end
end
available_operators *operators
end
use :default_operators
def self.new(*args, &block) # :nodoc:
# this class is abstract. instances are only allowed from child classes
raise "#{name} is an abstract class" if base?
super
end
def self.inherited(klass)
if base?
self.dont_display!
klass.display!
end
super
end
##
# Returns an array of [:label_of_value, value]-kind arrays, containing
# valid id-label combinations of possible filter values
def self.available_values(_params = {})
[]
end
##
# Returns a [:label_of_value, value]-kind array (as in self.vailable_values)
# for the given value
def self.label_for_value(value)
available_values(reverse_search: true).find { |v| v.second == value || v.second.to_s == value }
end
def correct_position?
child.nil? or child.filter?
end
def from_for(scope)
super + self.class.table_joins
end
def filter?
true
end
def valid?
@operator ? @operator.validate(values) : true
end
def errors
@operator ? @operator.errors : []
end
def group_by_fields
[]
end
def initialize(child = nil, options = {})
@values = []
super
end
def might_be_responsible
parent
end
def operator
(@operator || self.class.default_operator || engine::Operator.default_operator).to_operator
end
def operator=(value)
@operator = value.to_operator.tap do |o|
unless available_operators.include?(o) || additional_operators.include?(o)
raise ArgumentError, "#{o.inspect} not supported by #{inspect}."
end
end
end
def responsible_for_sql?
top?
end
def to_hash
raise NotImplementedError
end
def transformed_values
values
end
def sql_statement
super.tap do |query|
arity = operator.arity
query_values = [*transformed_values].compact
# if there is just the nil it might be actually intendet to be there
query_values.unshift nil if Array(self.values).size == 1 && Array(self.values).first.nil?
query_values = query_values[0, arity] if query_values and arity >= 0 and arity != query_values.size
operator.modify(query, field, *query_values) unless field.empty?
end
end
end
end

@ -0,0 +1,29 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
class Report::Filter
class MultiChoice < Base
dont_inherit :available_operators
use '='
def self.is_multiple_choice?
true
end
end
end

@ -0,0 +1,28 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
class Report::Filter::NoFilter < Report::Filter::Base
table_name 'entries'
dont_display!
singleton
def sql_statement
raise NotImplementedError, "My subclass should have overwritten 'sql_statement'"
end
end

@ -0,0 +1,40 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
require 'set'
class Report::GroupBy
include Report::QueryUtils
def self.all
Set[engine::GroupBy::SingletonValue]
end
def self.reset!
@all = nil
end
def self.all_grouped
all.group_by(&:applies_for).to_a.sort { |a, b| a.first.to_s <=> b.first.to_s }
end
def self.from_hash
raise NotImplementedError
end
end

@ -0,0 +1,108 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
class Report::GroupBy
class Base < Report::Chainable
include Report::QueryUtils
inherited_attributes :group_fields, list: true, merge: false
def correct_position?
type == :row or !child.is_a?(Report::GroupBy::Base) or child.type == :column
end
def filter?
false
end
def sql_aggregation?
child.filter?
end
def cache_key
self.class.cache_key + type.to_s[0, 1]
end
##
# @param [FalseClass, TrueClass] prefix Whether or not add a table prefix the field names
# @return [Array<String,Symbol>] List of group by fields corresponding to self and all parents'
def all_group_fields(prefix = true)
@all_group_fields ||= []
@all_group_fields[prefix ? 0 : 1] ||= begin
fields = group_fields.reject { |c| c.blank? or c == 'base' }
(parent ? parent.all_group_fields(prefix) : []) + (prefix ? with_table(fields) : fields)
end.uniq
end
def self.select_fields(*fields)
unless fields.empty?
@select_fields ||= []
@select_fields += fields
end
@select_fields
end
def select_fields
# + (parent ? parent.select_fields : [])
self.class.select_fields ? self.class.select_fields : group_fields
end
##
# @param [FalseClass, TrueClass] prefix Whether or not add a table prefix the field names
# @return [Array<String,Symbol>] List of select fields corresponding to self and all parents'
def all_select_fields(prefix = true)
@all_select_fields ||= []
@all_select_fields[prefix ? 0 : 1] ||= begin
fields = select_fields.reject { |c| c.blank? or c == 'base' }
(parent ? parent.all_select_fields(prefix) : []) + (prefix ? with_table(fields) : fields)
end.uniq
end
def clear
@all_group_fields = @all_select_fields = nil
super
end
def aggregation_mixin
sql_aggregation? ? engine::GroupBy::SqlAggregation : engine::GroupBy::RubyAggregation
end
def initialize(child = nil, optios = {})
super
extend aggregation_mixin
group_fields field
end
def result
super
end
def compute_result
super.tap do |r|
r.type = type
r.important_fields = group_fields
end
end
def define_group(sql)
sql.select all_select_fields
sql.group_by all_group_fields(true)
end
end
end

@ -0,0 +1,32 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
class Report::GroupBy
module RubyAggregation
def responsible_for_sql?
false
end
##
# @return [Report::Result] aggregation
def compute_result
child.result.grouped_by(all_group_fields(false), type, group_fields)
end
end
end

@ -0,0 +1,32 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
class Report::GroupBy
class SingletonValue < Base
dont_display!
put_sql_table_names 'singleton_value' => false
select_fields '1 as singleton_value'
def define_group(sql)
sql.select '1 as singleton_value'
sql.group_by 'singleton_value'
end
end
end

@ -0,0 +1,37 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
class Report::GroupBy
module SqlAggregation
def responsible_for_sql?
true
end
def compute_result
super.tap { |r| r.important_fields = group_fields }.grouped_by(all_group_fields(false), type, group_fields)
end
def sql_statement
super.tap do |sql|
define_group sql
sql.count unless sql.selects.include? 'count'
end
end
end
end

@ -0,0 +1,81 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
require 'set'
module Report::InheritedAttribute
include Report::QueryUtils
def inherited_attribute(*attributes)
options = attributes.extract_options!
list = options[:list]
merge = options.include?(:merge) ? options[:merge] : options[:list]
default = options[:default]
uniq = options[:uniq]
map = options[:map] || proc { |e| e }
default ||= [] if list
attributes.each do |name|
define_singleton_method(name) do |*values|
# FIXME: I'm ugly
return get_inherited_attribute(name, default, list, uniq) if values.empty?
if list
old = instance_variable_get("@#{name}") if merge
old ||= []
return set_inherited_attribute(name, values.map(&map) + old)
end
raise ArgumentError, "wrong number of arguments (#{values.size} for 1)" if values.size > 1
set_inherited_attribute name, map.call(values.first)
end
define_method(name) { |*values| self.class.send(name, *values) }
end
end
def define_singleton_method(name, &block)
singleton_class.send :attr_writer, name
singleton_class.class_eval { define_method(name, &block) }
define_method(name) { instance_variable_get("@#{name}") or singleton_class.send(name) }
end
def get_inherited_attribute(name, default = nil, list = false, uniq = false)
return get_inherited_attribute(name, default, list, false).uniq if list and uniq
result = instance_variable_get("@#{name}")
super_result = superclass.get_inherited_attribute(name, default, list) if inherit? name
if result.nil?
super_result || default
else
list && super_result ? result + super_result : result
end
end
def inherit?(name)
superclass.respond_to? :get_inherited_attribute and not not_inherited.include? name
end
def not_inherited
@not_inherited ||= Set.new
end
def dont_inherit(*attributes)
not_inherited.merge attributes
end
def set_inherited_attribute(name, value)
instance_variable_set "@#{name}", value
end
end

@ -0,0 +1,374 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
class Report::Operator
include Report::QueryUtils
include Report::Validation
extend Forwardable
#############################################################################################
# Wrapped so we can place this at the top of the file.
def self.define_operators # :nodoc:
# Defaults
defaults do
def_delegators :'singleton_class', :forced?, :force!, :forced
def sql_operator
name
end
def where_clause
"%s %s '%s'"
end
def modify(query, field, *values)
query.where [where_clause, field, sql_operator, *values]
query
end
def label
@label ||= self.class.name
end
end
# Operators from Redmine
new '>t-', label: :label_less_than_ago do
include DateRange
def modify(query, field, value)
super query, field, -value.to_i, 0
end
end
new 'w', arity: 0, label: :label_this_week do
def modify(query, field, offset = nil)
offset ||= 0
first_day = begin
Integer I18n.t(:general_first_day_of_week)
rescue ArgumentError
1 # assume mondays
end
from = Time.now.at_beginning_of_week + ((first_day % 7) - 1).days
from -= offset.days
'<>d'.to_operator.modify query, field, from, from + 7.days
end
end
new 't+', label: :label_in do
include DateRange
def modify(query, field, *values)
super query, field, values.first.to_i, values.first.to_i
end
end
new '<=', label: :label_less_or_equal
new '!', label: :label_not_equals do
def modify(query, field, *values)
where_clause = "(#{field} IS NULL"
where_clause += " OR #{field} NOT IN #{collection(*values)}" unless values.compact.empty?
where_clause += ')'
query.where where_clause
query
end
end
new 't-', label: :label_ago do
include DateRange
def modify(query, field, *values)
super query, field, -values.first.to_i, -values.first.to_i
end
end
new '!~', arity: 1, label: :label_not_contains do
def modify(query, field, *values)
value = values.first || ''
query.where "LOWER(#{field}) NOT LIKE '%#{quote_string(value.to_s.downcase)}%'"
query
end
end
new '=', label: :label_equals do
def modify(query, field, *values)
case
when values.size == 1 && values.first.nil?
query.where "#{field} IS NULL"
when values.compact.empty?
query.where '1=0'
else
query.where "#{field} IN #{collection(*values)}"
end
query
end
end
new '~', arity: 1, label: :label_contains do
def modify(query, field, *values)
value = values.first || ''
query.where "LOWER(#{field}) LIKE '%#{quote_string(value.to_s.downcase)}%'"
query
end
end
new '<t+', label: :label_in_less_than do
include DateRange
def modify(query, field, value)
super query, field, 0, value.to_i
end
end
new 't', label: :label_today do
include DateRange
def modify(query, field)
super query, field, 0, 0
end
end
new '>=', label: :label_greater_or_equal
new '!*', arity: 0, where_clause: '%s IS NULL', label: :label_none
new '<t-', label: :label_more_than_ago do
include DateRange
def modify(query, field, value)
super query, field, nil, -value.to_i
end
end
new '>t+', label: :label_in_more_than do
include DateRange
def modify(query, field, value)
super query, field, value.to_i, nil
end
end
new '*', arity: 0, where_clause: '%s IS NOT NULL', label: :label_all
# Our own operators
new '<', label: :label_less
new '>', label: :label_greater
new '=n', label: :label_equals do
def modify(query, field, value)
query.where "#{field} = #{clean_currency(value)}"
query
end
end
new '0', label: :label_none, where_clause: '%s = 0'
new 'y', label: :label_yes, arity: 0, where_clause: '%s IS NOT NULL'
new 'n', label: :label_no, arity: 0, where_clause: '%s IS NULL'
new '<d', label: :label_less_or_equal, validate: :dates do
def modify(query, field, value)
return query if value.to_s.empty?
'<='.to_operator.modify query, field, quoted_date(value)
end
end
new '>d', label: :label_greater_or_equal, validate: :dates do
def modify(query, field, value)
return query if value.to_s.empty?
'>='.to_operator.modify query, field, quoted_date(value)
end
end
new '<>d', label: :label_between, validate: :dates do
def modify(query, field, from, to)
return query if from.to_s.empty? || to.to_s.empty?
query.where "#{field} BETWEEN '#{quoted_date from}' AND '#{quoted_date to}'"
query
end
end
new '=d', label: :label_date_on, validate: :dates do
def modify(query, field, value)
return query if value.to_s.empty?
'='.to_operator.modify query, field, quoted_date(value)
end
end
new '>=d', label: :label_days_ago, validate: :integers do
force! :integers
def modify(query, field, value)
now = Time.now
from = (now - value.to_i.days).beginning_of_day
'<>d'.to_operator.modify query, field, from, now
end
end
new '?=', label: :label_null_or_equal do
def modify(query, field, *values)
where_clause = "(#{field} IS NULL"
where_clause += " OR #{field} IN #{collection(*values)}" unless values.compact.empty?
where_clause += ')'
query.where where_clause
query
end
end
new '?!', label: :label_not_null_and_not_equal do
def modify(query, field, *values)
where_clause = "(#{field} IS NOT NULL"
where_clause += " AND #{field} NOT IN #{collection(*values)}" unless values.compact.empty?
where_clause += ')'
query.where where_clause
query
end
end
end
#############################################################################################
module CoreExt
::String.send :include, self
::Symbol.send :include, self
def to_operator
Report::Operator.find self
end
end
def self.force!(type)
@force = type
end
def self.forced?
!!@force
end
def self.forced
@force
end
def self.new(name, values = {}, &block)
all[name.to_s] ||= super
end
# TODO: this should be inheritable by subclasses
def self.all
@@all_operators ||= {}
end
def self.load
return if @done
@done = true
define_operators
end
def self.find(name)
all[name.to_s] or raise ArgumentError, "Operator #{name.inspect} not defined"
end
def self.exists?(name)
all.has_key?(name.to_s)
end
def self.defaults(&block)
class_eval &block
end
def self.default_operator
find '='
end
def self.integer_operators
['<', '>', '<=', '>='].map(&:to_operator)
end
def self.null_operators
['*', '!*'].map(&:to_operator)
end
def self.string_operators
['!~', '~'].map(&:to_operator)
end
def self.time_operators
# ["t-", "t+", ">t-", "<t-", ">t+", "<t+"].map { |s| s.to_operator}
['t', 'w', '<>d', '>d', '<d', '=d', '>=d'].map(&:to_operator)
end
def self.default_operators
['=', '!'].map(&:to_operator)
end
attr_reader :name
def initialize(name, values = {}, &block)
@name = name.to_s
validation_methods = values.delete(:validate)
register_validations(validation_methods) unless validation_methods.nil?
values.each do |key, value|
singleton_class.class_eval { define_method(key) { value } }
end
singleton_class.class_eval(&block) if block
end
def to_operator
self
end
def to_s
name
end
def arity
@arity ||= begin
num = method(:modify).arity
# modify takes two more arguments before the values
num < 0 ? num + 2 : num - 2
end
end
def inspect
"#<#{self.class.name}:#{name.inspect}>"
end
def <=>(other)
name <=> other.name
end
## Creates an alias for a given operator.
def aka(alt_name, alt_label)
all = self.class.all
alt = alt_name.to_s
raise ArgumentError, "Can't alias operator with an existing one's name ( #{alt} )." if all.has_key?(alt)
op = all[name].clone
op.send(:rename_to, alt_name)
op.singleton_class.send(:define_method, 'label') { alt_label }
all[alt] = op
end
module DateRange
def modify(query, field, from, to)
query.where ["#{field} > '%s'", quoted_date((Date.yesterday + from).to_time.end_of_day)] if from
query.where ["#{field} <= '%s'", quoted_date((Date.today + to).to_time.end_of_day)] if to
query
end
end
private
def rename_to(new_name)
@name = new_name
end
# Done with class method definition, let's initialize the operators
load
end

@ -0,0 +1,338 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
module Report::QueryUtils
Infinity = 1.0 / 0
include Engine
alias singleton_class metaclass unless respond_to? :singleton_class
delegate :quoted_false, :quoted_true, to: 'engine.reporting_connection'
attr_writer :engine
module PropagationHook
include Report::QueryUtils
def append_features(base)
ancestors[1..-1].reverse_each { |m| base.send(:include, m) }
base.extend PropagationHook
base.extend self
super
end
def propagate!(to = engine)
to.constants(false).each do |name|
const = to.const_get name
next unless Module === const
append_features const unless const <= self or not const < Report::QueryUtils
propagate! const
end
end
end
extend PropagationHook
##
# Graceful string quoting.
#
# @param [Object] str String to quote
# @return [Object] Quoted version
def quote_string(str)
return str unless str.respond_to? :to_str
engine.reporting_connection.quote_string(str)
end
def current_language
::I18n.locale
end
##
# Creates a SQL fragment representing a collection/array.
#
# @see quote_string
# @param [#flatten] *values Ruby collection
# @return [String] SQL collection
def collection(*values)
return '' if values.empty?
v = if values.is_a?(Array)
values.flatten.each_with_object([]) do |str, l|
l << split_with_safe_return(str)
end
else
split_with_safe_return(str)
end
"(#{v.flatten.map { |x| "'#{quote_string(x)}'" }.join(', ')})"
end
def split_with_safe_return(str)
# From ruby doc:
# When the input str is empty an empty Array is returned as the string is
# considered to have no fields to split.
str.to_s.empty? ? '' : str.to_s.split(',')
end
##
# Graceful, internationalized quoted string.
#
# @see quote_string
# @param [Object] str String to quote/translate
# @return [Object] Quoted, translated version
def quoted_label(ident)
"'#{quote_string ::I18n.t(ident)}'"
end
def quoted_date(date)
engine.reporting_connection.quoted_date date.to_dateish
end
##
# SQL date quoting.
# @param [Date,Time] date Date to quote.
# @return [String] Quoted date.
def quote_date(date)
"'#{quoted_date date}'"
end
##
# Generate a table name for any object.
#
# @example Table names
# table_name_for Issue # => 'issues'
# table_name_for :issue # => 'issues'
# table_name_for "issue" # => 'issues'
# table_name_for "issues" # => 'issues
#
# @param [#table_name, #to_s] object Object you need the table name for.
# @return [String] The table name.
def table_name_for(object)
return object.table_name if object.respond_to? :table_name
object.to_s.tableize
end
##
# Generate a field name
#
# @example Field names
# field_name_for nil # => 'NULL'
# field_name_for 'foo' # => 'foo'
# field_name_for [Issue, 'project_id'] # => 'issues.project_id'
# field_name_for [:issue, 'project_id'], :entry # => 'issues.project_id'
# field_name_for 'project_id', :entry # => 'entries.project_id'
#
# @param [Array, Object] arg Object to generate field name for.
# @param [Object, optional] default_table Table name to use if no table name is given.
# @return [String] Field name.
def field_name_for(arg, default_table = nil)
return 'NULL' unless arg
return field_name_for(arg.keys.first, default_table) if arg.is_a? Hash
return arg if arg.is_a? String and arg =~ /\.| |\(.*\)/
return table_name_for(arg.first || default_table) + '.' << arg.last.to_s if arg.is_a? Array and arg.size == 2
return arg.to_s unless default_table
field_name_for [default_table, arg]
end
##
# Sanitizes sql condition
#
# @see ActiveRecord::Base#sanitize_sql_for_conditions
# @param [Object] statement Not sanitized statement.
# @return [String] Sanitized statement.
def sanitize_sql_for_conditions(statement)
engine.send :sanitize_sql_for_conditions, statement
end
##
# FIXME: This is redmine
# Generates string representation for a currency.
#
# @see CostRate.clean_currency
# @param [BigDecimal] value
# @return [String]
def clean_currency(value)
CostRate.clean_currency(value).to_f.to_s
end
##
# Generates a SQL case statement.
#
# @example
# switch "#{table}.overridden_costs IS NULL" => [model, :costs], :else => [model, :overridden_costs]
#
# @param [Hash] options Condition => Result.
# @return [String] Case statement.
def switch(options)
desc = "#{__method__} #{options.inspect[1..-2]}".gsub(/(Cost|Time)Entry\([^\)]*\)/, '\1Entry')
options = options.with_indifferent_access
else_part = options.delete :else
"-- #{desc}\n\t" \
"CASE #{options.map { |k, v|
"\n\t\tWHEN #{field_name_for k}\n\t\t" \
"THEN #{field_name_for v}"
}.join(', ')}\n\t\tELSE #{field_name_for else_part}\n\tEND"
end
def iso_year_week(field, default_table = nil)
field = field_name_for(field, default_table)
"-- code specific for #{adapter_name}\n\t" << super(field)
end
##
# Converts value with a given behavior, but treats nil differently.
# Params
# - value: the value to convert
# - weight_of_nil (optional): How a nil should be treated.
# :infinit - makes a nil weight really heavy, which will make it stay
# at the very end when sorting
# :negative_infinit - opposite of :infinit, let's the nil stay at the very beginning
# any other object - nil's will be replaced by thyt object
# - block (optional) - defines how to convert values which are not nil
# if no block is given, values stay untouched
def convert_unless_nil(value, weight_of_nil = :infinit)
if value.nil?
if weight_of_nil == :infinit
1.0 / 0 # Infinity, which is greater than any string or number
elsif weight_of_nil == :negative_infinit
-1.0 / 0 # negative Infinity, which is smaller than any string or number
else
weight_of_nil
end
else
if block_given?
yield value
else
value
end
end
end
def map_field(key, value)
case key.to_s
when 'singleton_value', /_id$/ then convert_unless_nil(value) { |v| v.to_i }
when 'work_package_id', 'tweek', 'tmonth', 'tweek' then value.to_i
else convert_unless_nil(value) { |v| v.to_s }
end
end
def adapter_name
engine.reporting_connection.adapter_name.downcase.to_sym
end
def cache
Report::QueryUtils.cache
end
def compare(first, second)
first = Array(first).flatten
second = Array(second).flatten
first.zip second do |a, b|
return (a <=> b) || (a == Infinity ? 1 : -1) if a != b
end
second.size > first.size ? -1 : 0
end
def mysql?
[:mysql, :mysql2].include? adapter_name.to_s.downcase.to_sym
end
def sqlite?
adapter_name == :sqlite
end
def postgresql?
adapter_name == :postgresql
end
module SQL
def typed(_type, value, escape = true)
escape ? "'#{quote_string value}'" : value
end
end
module MySql
include SQL
def iso_year_week(field)
"yearweek(#{field}, 1)"
end
end
module Sqlite
include SQL
def iso_year_week(field)
# enjoy
<<-EOS
case
when strftime('%W', strftime('%Y-01-04', #{field})) = '00' then
-- 01/01 is in week 1 of the current year => %W == week - 1
case
when strftime('%W', #{field}) = '52' and strftime('%W', (strftime('%Y', #{field}) + 1) || '-01-04') = '00' then
-- we are at the end of the year, and it's the first week of the next year
(strftime('%Y', #{field}) + 1) || '01'
when strftime('%W', #{field}) < '08' then
-- we are in week 1 to 9
strftime('%Y0', #{field}) || (strftime('%W', #{field}) + 1)
else
-- we are in week 10 or later
strftime('%Y', #{field}) || (strftime('%W', #{field}) + 1)
end
else
-- 01/01 is in week 53 of the last year
case
when strftime('%W', #{field}) = '52' and strftime('%W', (strftime('%Y', #{field}) + 1) || '-01-01') = '00' then
-- we are at the end of the year, and it's the first week of the next year
(strftime('%Y', #{field}) + 1) || '01'
when strftime('%W', #{field}) = '00' then
-- we are in the week belonging to last year
(strftime('%Y', #{field}) - 1) || '53'
else
-- everything is fine
strftime('%Y%W', #{field})
end
end
EOS
end
end
module Postres
include SQL
def typed(type, value, escape = true)
"#{super}::#{type}"
end
def iso_year_week(field)
"(EXTRACT(isoyear from #{field})*100 + \n\t\t" \
"EXTRACT(week from #{field} - \n\t\t" \
"(EXTRACT(dow FROM #{field})::int+6)%7))"
end
end
include MySql if mysql?
include Sqlite if sqlite?
include Postres if postgresql?
def self.cache
@cache ||= Hash.new { |h, k| h[k] = {} }
end
def self.included(klass)
super
klass.extend self
end
end

@ -0,0 +1,299 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
class Report::Result
include Report::QueryUtils
class Base
attr_accessor :parent, :type, :important_fields
attr_accessor :key
attr_reader :value
alias values value
include Enumerable
include Report::QueryUtils
def initialize(value)
@important_fields ||= []
@type = :direct
@value = value
end
def recursive_each_with_level(level = 0, _depth_first = true, &block)
block.call(level, self)
end
def recursive_each
recursive_each_with_level { |_level, result| yield result }
end
def to_hash
fields.dup
end
def [](key)
fields[key]
end
##
# Override if you want to influence the result grouping.
#
# @return A value for grouping or nil if the given field should
# not be considered for grouping.
def map_group_by_value(_key, value)
value
end
##
# This method is called when this result is requested as #grouped_by something
# just before the result is returned.
#
# @param data This result's grouped data.
def group_by_data_ready(_data)
# good to know!
end
def grouped_by(fields, type, important_fields = [])
@grouped_by ||= {}
list = begin
@grouped_by[fields] ||= begin
# sub results, have fields
# i.e. grouping by foo, bar
data = group_by do |entry|
# index for group is a hash
# i.e. { :foo => 10, :bar => 20 } <= this is just the KEY!!!!
fields.inject({}) do |hash, key|
val = map_group_by_value(key, entry.fields[key])
hash.merge key => val
end
end
group_by_data_ready(data)
# map group back to array, all fields with same key get grouped into one list
data.keys.map { |f| engine::Result.new data[f], f, type, important_fields }
end
end
# create a single result from that list
engine::Result.new list, {}, type, important_fields
end
def inspect
"<##{self.class}: @fields=#{fields.inspect} @type=#{type.inspect} " \
"@size=#{size} @count=#{count} @units=#{units}>"
end
def row?
type == :row
end
def column?
type == :column
end
def direct?
type == :direct
end
def each_row
end
def final?(type)
type? type and (direct? or size == 0 or first.type != type)
end
def type?(type)
self.type == type
end
def depth_of(type)
if type? type or (type == :column and direct?) then 1
else 0
end
end
def final_number(type)
return 1 if final? type
return 0 if direct?
@final_number ||= {}
@final_number[type] ||= sum { |v| v.final_number type }
end
def final_row?
final? :row
end
def final_column?
final? :column
end
def render(keys = important_fields)
fields.map { |k, v| yield(k, v) if keys.include? k }.join
end
def set_key(index = [])
self.key = index.map { |k| map_field(k, fields[k]) }
end
end
class DirectResult < Base
alias fields values
def has_children?
false
end
def count
self['count'].to_i
end
def units
self['units'].to_d
end
##
# @return [Integer] Number of child results
def size
0
end
def each
return enum_for(__method__) unless block_given?
yield self
end
def each_direct_result(_cached = false)
return enum_for(__method__) unless block_given?
yield self
end
def sort!(force = false)
force
end
end
class WrappedResult < Base
include Enumerable
def set_key(index = [])
values.each { |v| v.set_key index }
super
end
def sort!(force = false)
return false if @sorted and not force
values.sort! { |a, b| compare a.key, b.key }
values.each { |e| e.sort! force }
@sorted = true
end
def depth_of(type)
super + first.depth_of(type)
end
def has_children?
true
end
def count
sum_for :count
end
def units
sum_for :units
end
def sum_for(field)
@sum_for ||= {}
@sum_for[field] ||= sum { |v| v.send(field) || 0 }
end
def recursive_each_with_level(level = 0, depth_first = true, &block)
if depth_first
super
each { |c| c.recursive_each_with_level(level + 1, depth_first, &block) }
else # width-first
to_evaluate = [self]
lvl = level
while !to_evaluate.empty?
# evaluate all stored results and find the results we need to evaluate soon
to_evaluate_soon = []
to_evaluate.each do |r|
block.call(lvl, r)
to_evaluate_soon.concat r.values if r.size > 0
end
# take new results to evaluate
lvl = lvl + 1
to_evaluate = to_evaluate_soon
end
end
def each_row
return enum_for(:each_row) unless block_given?
if final_row? then yield self
else each { |c| c.each_row(&Proc.new) }
end
end
end
def to_a
values
end
def each(&block)
values.each(&block)
end
def each_direct_result(cached = true)
return enum_for(__method__) unless block_given?
if @direct_results
@direct_results.each { |r| yield(r) }
else
values.each do |value|
value.each_direct_result(false) do |result|
(@direct_results ||= []) << result if cached
yield result
end
end
end
end
def fields
@fields ||= {}.with_indifferent_access
end
##
# @return [Integer] Number of child results
def size
values.size
end
end
def self.new(value, fields = {}, type = nil, important_fields = [])
result = begin
case value
when ActiveRecord::Result, Array then engine::Result::WrappedResult.new value.map { |e| new e, {}, nil, important_fields }
when Hash then engine::Result::DirectResult.new value.with_indifferent_access
when Base then value
else raise ArgumentError, "Cannot create Result from #{value.inspect}"
end
end
result.fields.merge! fields
result.type = type if type
result.important_fields = important_fields unless result == value
result
end
end

@ -0,0 +1,288 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
class Report::SqlStatement
class Union
attr_accessor :first, :second, :as
def initialize(first, second, as = nil)
@first, @second, @as = first, second, as
end
def to_s
"((\n#{first.gsub("\n", "\n\t")}\n) UNION (\n" \
"#{second.gsub("\n", "\n\t")}\n))#{" AS #{as}" if as}\n"
end
def each_subselect
yield first
yield second
end
def gsub(*args, &block)
to_s.gsub(*args, &block)
end
end
include Report::QueryUtils
##
# Describes the query. This may be used in a sql-comment later.
attr_accessor :desc
##
# Generates new SqlStatement.
#
# @param [String, #to_s] table Table name (or subselect) for from part.
def initialize(table, desc = '')
self.desc = desc
from table
end
##
# Creates a uninon of the caller and the callee.
#
# @param [Report::SqlStatement] other Second part of the union
# @return [String] The sql query.
def union(other, as = nil)
Union.new(self, other, as)
end
##
# Adds sum(..) part to select.
#
# @param [#to_s] field Name of the field to aggregate on
# @param [#to_s] name Name of the result (defaults to sum)
def sum(field, name = :sum, type = :sum)
@sql = nil
return sum({ name => field }, nil, type) unless field.respond_to? :to_hash
field.each { |k, v| field[k] = "#{type}(#{v})" }
select field
end
##
# Adds count(..) part to select.
#
# @param [#to_s] field Name of the field to aggregate on (defaults to *)
# @param [#to_s] name Name of the result (defaults to sum)
def count(field = '*', name = :count)
sum field, name, :count
end
##
# Generates the SQL query.
# Code looks ugly in exchange for pretty output (so one does unterstand those).
#
# @return [String] The query
def to_s
# FIXME I'm ugly
@sql ||= begin
sql = "\n-- BEGIN #{desc}\n" \
"-- DB: #{ActiveRecord::Base.connection.current_database}\n" \
"SELECT\n#{select.map { |e| "\t#{e}" }.join ",\n"}" \
"\nFROM\n\t#{from.gsub("\n", "\n\t")}" \
"\n\t#{joins.map { |e| e.gsub("\n", "\n\t") }.join "\n\t"}" \
"\nWHERE #{where.join ' AND '}\n"
sql << "GROUP BY #{group_by.join ', '}\nORDER BY #{group_by.join ', '}\n" if group_by?
sql << "-- END #{desc}\n"
sql.gsub!('--', '#') if mysql?
sql # << " LIMIT 100"
end
end
##
# @overload from
# Reads the from part.
# @return [#to_s] From part
# @overload from(table)
# Sets the from part.
# @param [#to_s] table
# @param [#to_s] From part
def from(table = nil)
return @from unless table
@sql = nil
@from = table
end
##
# Where conditions. Will be joined together by AND.
#
# @overload where
# Reads the where part
# @return [Array<#to_s>] Where clauses
# @overload where(fields)
# Adds condition to where clause
# @param [Array, Hash, String] fields Parameters passed to sanitize_sql_for_conditions.
# @see Report::QueryUtils#sanitize_sql_for_conditions
def where(fields = nil)
@where ||= ['1=1']
unless fields.nil?
@where << sanitize_sql_for_conditions(fields)
@sql = nil
end
@where
end
##
# @return [Array<String>] List of table joins
def joins
(@joins ||= []).tap(&:uniq!)
end
##
# Adds an "left outer join" (guessing field names) to #joins.
#
# @overload join(name)
# @param [Symbol, String] name Singular table name to join with, will join plural from on table.id = table_id
# @overload join(model)
# @param [#table_name, #model_name] model ActiveRecord model to join with
# @overload join(hash)
# @param [Hash<#to_s => #to_s>] hash Key is singular table name to join with, value is field to join on
# @overload join(*list)
# @param [Array<String,Symbol,Array>] list Will generate join entries (according to guessings described above)
# @see #joins
def join(*list)
@sql = nil
join_syntax = 'LEFT OUTER JOIN %1$s ON %1$s.id = %2$s_id'
list.each do |e|
case e
when Class then joins << (join_syntax % [table_name_for(e), e.lookup_ancestors.last.model_name.to_s.underscore])
when / / then joins << e
when Symbol, String then joins << (join_syntax % [table_name_for(e), e])
when Hash then e.each { |k, v| joins << (join_syntax % [table_name_for(k), field_name_for(v)]) }
when Array then join(*e)
else raise ArgumentError, "cannot join #{e.inspect}"
end
end
end
def default_select(value = nil)
@default_select = value if value
@default_select ||= ['*']
end
##
# @overload select
# @return [Array<String>] All fields/statements for select part
#
# @overload select(*fields)
# Adds fields to select query.
# @example
# SqlStatement.new.select(some_sql_statement) # [some_sql_statement.to_s]
# SqlStatement.new.select("sum(foo)") # ["sum(foo)"]
# SqlStatement.new.select(:a).select(:b) # ["a", "b"]
# SqlStatement.new.select(:bar => :foo) # ["foo as bar"]
# SqlStatement.new.select(:bar => nil) # ["NULL as bar"]
# @param [Array, Hash, String, Symbol, SqlStatement] fields Fields to add to select part
# @return [Array<String>] All fields/statements for select part
def select(*fields)
return(@select || default_select) if fields.empty?
(@select ||= []).tap do
@sql = nil
fields.reject { |f| never_select.include? f }.each do |f|
case f
when Array
if f.size == 2 and f.first.respond_to? :table_name then select field_name_for(f)
else select(*f)
end
when Hash then select f.map { |k, v| "#{field_name_for v} as #{field_name_for k}" }
when String, Symbol then @select << field_name_for(f)
when engine::SqlStatement then @select << f.to_s
else raise ArgumentError, "cannot handle #{f.inspect}"
end
end
# when doing a union in sql, both subselects must have the same order.
# by sorting here we never ever have to worry about this again, sucker!
@select = @select.uniq.sort_by { |x| x.split(' as ').last }
end
end
def unselect(*fields)
@sql = nil
@select = @select.reject do |field|
fields.find { |f| f == field }
end
end
def never_select(*fields)
(@never_select ||= []).tap do
unless fields.empty?
@never_select += fields
unselect *fields
end
end
end
##
# Return the names which have been bound through select statements
# @return [Array<String>] All fields for select part
def selects
@select.map { |s| s.split(' as ').last }
end
##
# @overload group_by
# @return [Array<String>] All fields/statements for group by part
#
# @overload group(*fields)
# Adds fields to group by query
# @param [Array, String, Symbol] fields Fields to add
def group_by(*fields)
@sql = nil unless fields.empty?
(@group_by ||= []).tap do
fields.reject { |f| never_group_by.include? f }.each do |e|
if e.is_a? Array and (e.size != 2 or !e.first.respond_to? :table_name)
group_by(*e)
else
@group_by << field_name_for(e)
end
end
@group_by.uniq!
end
end
def group_not_by(*fields)
@sql = nil
@group_by = @group_by.reject do |field|
fields.find { |f| f == field }
end
end
def never_group_by(*fields)
(@never_group_by ||= []).tap do
unless fields.empty?
@never_group_by += fields
group_not_by *fields
end
end
end
##
# @return [TrueClass, FalseClass] Whether or not to add a group by part.
def group_by?
!group_by.empty?
end
def inspect
"#<SqlStatement: #{to_s.inspect}>"
end
def gsub(*args, &block)
to_s.gsub(*args, &block)
end
end

@ -0,0 +1,109 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
# encoding: UTF-8
require 'enumerator'
class Report::Table
attr_accessor :query
include Report::QueryUtils
def initialize(query)
@query = query
end
def row_index
get_index :row
end
def column_index
get_index :column
end
def row_fields
fields_for :row
end
def column_fields
fields_for :column
end
def rows_for(result)
fields_for result, :row
end
def columns_for(result)
fields_for result, :column
end
def fields_from(result, type)
fields_for(type).map { |k| map_field k, result.fields[k] }
end
##
# @param [Array] expected Fields expected
# @param [Array,Hash,Result] given Fields/result to be tested
# @return [TrueClass,FalseClass]
def satisfies?(type, expected, given)
given = fields_from(given, type) if given.respond_to? :to_hash
zipped = expected.zip given
zipped.all? { |a, b| a == b or b.nil? }
end
def fields_for(type)
@fields_for ||= begin
child, fields = query.chain, Hash.new { |h, k| h[k] = [] }
until child.filter?
fields[child.type].push(*child.group_fields)
child = child.child
end
fields
end
@fields_for[type]
end
def get_row(*args)
@query.each_row { |result| return with_gaps_for(type, result) if satisfies? :row, args, result }
[]
end
def with_gaps_for(type, result)
return enum_for(:with_gaps_for, type, result) unless block_given?
stack = get_index(type).dup
result.each_direct_result do |subresult|
yield nil until stack.empty? or satisfies? type, stack.shift, subresult
yield subresult
end
stack.size.times { yield nil }
end
def [](x, y)
get_row(row_index[y]).first(x).last
end
def get_index(type)
@indexes ||= begin
indexes = Hash.new { |h, k| h[k] = Set.new }
query.each_direct_result { |result| [:row, :column].each { |t| indexes[t] << fields_from(result, t) } }
indexes.keys.each { |k| indexes[k] = indexes[k].sort { |x, y| compare x, y } }
indexes
end
@indexes[type]
end
end

@ -0,0 +1,65 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
# encoding: UTF-8
class Report::Transformer
attr_reader :query
def initialize(query)
@query = query
end
##
# @return [Report::Result::Base] Result tree with row group bys at the top
# @see Report::Chainable#result
def row_first
@row_first ||= query.result
end
##
# @return [Report::Result::Base] Result tree with column group bys at the top
# @see Report::Walker#row_first
def column_first
@column_first ||= begin
# reverse since we fake recursion ↓↓↓
list, all_fields = restructured.reverse, @all_fields.dup
result = list.inject(@ungrouped) do |aggregate, (current_fields, type)|
fields, all_fields = all_fields, all_fields - current_fields
aggregate.grouped_by fields, type, current_fields
end
result or query.result
end
end
##
# Important side effect: it sets @ungrouped, @all_fields.
# @return [Array<Array<Array<String,Symbol>, Symbol>>] Group by fields + types (:row or :column)
def restructured
rows, columns, current = [], [], query.chain
@all_fields = []
until current.filter?
@ungrouped = current.result if current.responsible_for_sql?
list = current.row? ? rows : columns
list << [current.group_fields, current.type]
@all_fields.push(*current.group_fields)
current = current.child
end
columns + rows
end
end

@ -0,0 +1,61 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
module Report::Validation
include Report::QueryUtils
def register_validations(*validation_methods)
validation_methods.flatten.each do |val_method|
register_validation(val_method)
end
end
def register_validation(val_method)
const_name = val_method.to_s.camelize
begin
val_module = engine::Validation.const_get const_name
singleton_class.send(:include, val_module)
val_method = 'validate_' + val_method.to_s.pluralize
if method(val_method)
validations << val_method
else
warn "#{val_module.name} does not define #{val_method}"
end
rescue NameError
warn "No Module #{engine}::Validation::#{const_name} found to validate #{val_method}"
end
self
end
def errors
@errors ||= Hash.new { |h, k| h[k] = [] }
end
def validations
@validations ||= []
end
def validate(*values)
errors.clear
return true if validations.empty?
validations.all? do |validation|
values.empty? ? true : send(validation, *values)
end
end
end

@ -0,0 +1,36 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
module Report::Validation
module Dates
def validate_dates(*values)
values = values.flatten
return true if values.empty?
values.flatten.all? do |val|
begin
!!val.to_dateish
rescue ArgumentError
errors[:date] << val
validate_dates(values - [val])
false
end
end
end
end
end

@ -0,0 +1,36 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
module Report::Validation
module Integers
def validate_integers(*values)
values = values.flatten
return true if values.empty?
values.flatten.all? do |val|
if val.to_i.to_s != val.to_s
errors[:int] << val
validate_integers(values - [val])
false
else
true
end
end
end
end
end

@ -0,0 +1,26 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
module Report::Validation
module Sql
def validate_sql(_values = [])
raise NotImplementedError, "Haven't done SQL validation just yet!"
end
end
end

@ -0,0 +1,119 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
class Report::Walker
attr_accessor :query, :header_stack
def initialize(query)
@query = query
end
def for_row(&block)
access_block(:row, &block)
end
def for_final_row(&block)
access_block(:final_row, &block) || access_block(:row)
end
def for_cell(&block)
access_block(:cell, &block)
end
def for_empty_cell(&block)
access_block(:empty_cell, &block) || access_block(:cell)
end
def access_block(name, &block)
@blocks ||= {}
@blocks[name] = block if block
@blocks[name]
end
def walk_cell(cell)
cell ? for_cell[cell] : for_empty_cell[nil]
end
def headers(result = nil, &_block)
@header_stack = []
result ||= query.column_first
sort result
last_level = -1
num_in_col = 0
level_size = 1
sublevel = 0
result.recursive_each_with_level(0, false) do |level, result|
break if result.final_column?
if first_in_col = (last_level < level)
list = []
last_level = level
num_in_col = 0
level_size = sublevel
sublevel = 0
@header_stack << list
end
num_in_col += 1
sublevel += result.size
last_in_col = (num_in_col >= level_size)
@header_stack.last << [result, first_in_col, last_in_col]
yield(result, level == 0, first_in_col, last_in_col) if block_given?
end
end
def reverse_headers
fail 'call header first' unless @header_stack
first = true
@header_stack.reverse_each do |list|
list.each do |result, first_in_col, last_in_col|
yield(result, first, first_in_col, last_in_col)
end
first = false
end
end
def headers_empty?
fail 'call header first' unless @header_stack
@header_stack.empty?
end
def sort_keys
@sort_keys ||= query.chain.map { |c| c.group_fields.map(&:to_s) if c.group_by? }.compact.flatten
end
def sort(result)
result.set_key sort_keys
result.sort!
end
def body(result = nil)
return [*body(result)].each { |a| yield a } if block_given?
result ||= query.result.tap { |r| sort(r) }
if result.row?
if result.final_row?
subresults = query.table.with_gaps_for(:column, result).map(&method(:walk_cell))
for_final_row.call result, subresults
else
subresults = result.map { |r| body(r) }
for_row.call result, subresults
end
else
# you only get here if no rows are defined
result.each_direct_result.map(&method(:walk_cell))
end
end
end

@ -0,0 +1,22 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
module ReportingEngine
require 'reporting_engine/engine'
end

@ -0,0 +1,63 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
require 'rails/engine'
module ReportingEngine
class Engine < ::Rails::Engine
engine_name :reportingengine
config.autoload_paths += Dir["#{config.root}/lib/"]
initializer 'reportingengine.precompile_assets' do
Rails.application.config.assets.precompile += %w(reporting_engine.css reporting_engine.js)
end
initializer 'check mysql version' do
connection = ActiveRecord::Base.connection
adapter_name = connection.adapter_name.to_s.downcase.to_sym
if [:mysql, :mysql2].include?(adapter_name)
# The reporting engine is incompatible with the
# following mysql versions due to a bug in MySQL itself:
# 5.6.0 - 5.6.12
# 5.7.0 - 5.7.1
# see https://www.openproject.org/issues/967 for details.
required_patch_levels = { '5.6' => 13, '5.7' => 2 }
mysql_version = connection.show_variable('VERSION')
release_version, patch_level = mysql_version.match(/(\d*\.\d*)\.(\d*)/).captures
required_patch_level = required_patch_levels[release_version]
if required_patch_level && (patch_level.to_i < required_patch_level)
raise "MySQL #{mysql_version} is not supported. Version #{release_version} \
requires patch level >= #{required_patch_level}."
end
end
end
config.to_prepare do
require 'reporting_engine/patches'
require 'reporting_engine/patches/big_decimal_patch'
require 'reporting_engine/patches/to_date_patch'
# We have to require this here because Ruby will otherwise find Date
# as Object::Date and Rails wont autoload Widget::Filters::Date
require_dependency 'widget/filters/date'
end
end
end

@ -0,0 +1,30 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
##
# A minimal ReportingHelper module. This is included in Widget and
# Controller and can be used to extend the specific widgets and
# controller functionality.
#
# It is the default hook for translations, and calls to l() in Widgets
# or Controllers will go to this module, first. The default behavior
# is to pass translation work on to I18n.t() or I18n.l(), depending on
# the type of arguments.
module ReportingHelper
end

@ -0,0 +1,21 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
module ReportingEngine::Patches
end

@ -0,0 +1,40 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
module ReportingEngine::Patches::BigDecimalPatch
module BigDecimal
::BigDecimal.send :include, self
def to_d; self end
end
module Integer
::Integer.send :include, self
def to_d; to_f.to_d end
end
module String
::String.send :include, self
def to_d; ::BigDecimal.new(self) end
end
module NilClass
::NilClass.send :include, self
def to_d; 0 end
end
end

@ -0,0 +1,47 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
require 'date'
module ReportingEngine::Patches::ToDatePatch
module StringAndNil
::String.send(:include, self)
::NilClass.send(:include, self)
def to_dateish
return Date.today if blank?
Date.parse self
end
end
module DateAndTime
::Date.send(:include, self)
::Time.send(:include, self)
def to_dateish
self
end
def force_utc
return to_time.force_utc unless respond_to? :utc_offset
return self if utc?
utc - utc_offset
end
end
end

@ -0,0 +1,45 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
begin
require 'spec/rake/spectask'
namespace :spec do
namespace :plugins do
desc 'Runs the examples for reporting_engine'
Spec::Rake::SpecTask.new(:reporting_engine) do |t|
t.spec_opts = ['--options', "\"#{Rails.root}/spec/spec.opts\""]
t.spec_files = FileList['vendor/plugins/reporting_engine/spec/**/*_spec.rb']
end
desc 'Runs the examples for reporting_engine'
Spec::Rake::SpecTask.new(:"reporting_engine:rcov") do |t|
t.spec_opts = ['--options', "\"#{Rails.root}/spec/spec.opts\""]
t.spec_files = FileList['vendor/plugins/reporting_engine/spec/**/*_spec.rb']
t.rcov = true
t.rcov_opts = ['-x', "\.rb,spec", '-i', 'reporting_engine/app/,redmine_reporting/lib/']
end
end
end
task spec: 'spec:plugins:reporting_engine'
require 'ci/reporter/rake/rspec' # use this if you're using RSpec
require 'ci/reporter/rake/test_unit' # use this if you're using Test::Unit
task :"spec:plugins:reporting_engine:ci" => ['ci:setup:rspec', 'spec:plugins:redmine_reporting']
rescue LoadError
end

@ -0,0 +1,22 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
module ReportingEngine
VERSION = "8.2.0"
end

@ -0,0 +1,68 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
require_dependency 'reporting_engine/helpers/reporting_helper'
class ReportingWidget < ActionView::Base
include ActionView::Helpers::TagHelper
include ActionView::Helpers::AssetTagHelper
include ActionView::Helpers::FormTagHelper
include ActionView::Helpers::JavaScriptHelper
include Rails.application.routes.url_helpers
include ApplicationHelper
include ReportingHelper
include Redmine::I18n
attr_accessor :output_buffer, :controller, :config, :_content_for, :_routes, :subject
def self.new(subject)
super(subject).tap do |o|
o.subject = subject
end
end
def current_language
::I18n.locale
end
def protect_against_forgery?
false
end
def method_missing(name, *args, &block)
controller.send(name, *args, &block)
rescue NoMethodError
raise NoMethodError, "undefined method `#{name}' for #<#{self.class}:0x#{object_id}>"
end
module RenderWidgetInstanceMethods
def render_widget(widget, subject, options = {}, &block)
i = widget.new(subject)
i.config = config
i._routes = _routes
i._content_for = @_content_for
i.controller = respond_to?(:controller) ? controller : self
i.request = request
i.render_with_options(options, &block)
end
end
end
ActionView::Base.send(:include, ReportingWidget::RenderWidgetInstanceMethods)
ActionController::Base.send(:include, ReportingWidget::RenderWidgetInstanceMethods)

@ -0,0 +1,115 @@
#-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
require 'digest/sha1'
require_dependency 'reporting_widget'
module ::Widget
class Base < ::ReportingWidget
attr_reader :engine, :output
attr_accessor :request
##
# Deactivate caching for certain widgets. If called on Widget::Base,
# caching is deactivated globally
def self.dont_cache!
@dont_cache = true
end
##
# Query whether this widget class should be cached.
def self.dont_cache?
@dont_cache or self != Widget::Base && Widget::Base.dont_cache?
end
def initialize(query)
@subject = query
@engine = query.class
@options = {}
end
##
# Write a string to the canvas. The string is marked as html_safe.
# This will write twice, if @cache_output is set.
def write(str)
str ||= ''
@output ||= ''.html_safe
@output = @output + '' if @output.frozen? # Rails 2 freezes tag strings
@output.concat str.html_safe
@cache_output.concat(str.html_safe) if @cache_output
str.html_safe
end
##
# Render this widget. Abstract method. Needs to call #write at least once
def render
raise NotImplementedError, "#render is missing in my subclass #{self.class}"
end
##
# Render this widget, passing options.
# Available options:
# :to => canvas - The canvas (streaming or otherwise) to render to. Has to respond to #write
def render_with_options(options = {}, &block)
set_canvas(options.delete(:to)) if options.has_key? :to
@options = options
render_with_cache(options, &block)
@output
end
def cache_key
@cache_key ||= Digest::SHA1::hexdigest begin
if subject.respond_to? :cache_key
"#{I18n.locale}/#{self.class.name.demodulize}/#{subject.cache_key}/#{@options.sort_by(&:to_s)}"
else
subject.inspect
end
end
end
def cached?
cache? && Rails.cache.exist?(cache_key)
end
private
def cache?
!self.class.dont_cache?
end
##
# Render this widget or serve it from cache
def render_with_cache(_options = {}, &block)
if cached?
write Rails.cache.fetch(cache_key)
else
render(&block)
Rails.cache.write(cache_key, @cache_output || @output) if cache?
end
end
##
# Set the canvas. If the canvas object isn't a string (e.g. cannot be cached easily),
# a @cache_output String is created, that will mirror what is being written to the canvas.
def set_canvas(canvas)
@cache_output = ''.html_safe
@output = canvas
end
end
end

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save