diff --git a/docker-compose.yml b/docker-compose.yml index 5f3fbab782..563d4fb78d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -24,6 +24,7 @@ services: FLP_INFOLOGGER_URL: "${ALI_ECS_GUI_URL:-http://localhost:8081}" QC_GUI_URL: "${ALI_ECS_GUI_URL:-http://localhost:8082}" ALI_FLP_INDEX_URL: "${ALI_ECS_GUI_URL:-http://localhost:80}" + ALICE_INSIGHTS_URL: "${ALICE_INSIGHTS_URL:-}" CCDB_ENABLE_SYNCHRONIZATION: "${CCDB_ENABLE_SYNCHRONIZATION:-false}" CCDB_RUN_INFO_URL: "${CCDB_RUN_INFO_URL:-}" links: diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index ca0355068a..60ef5e8c36 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -29,3 +29,15 @@ The following configuration items can be set using environment variables, note t | OPENID_SECRET | Application secret | | | OPENID_REDIRECT | Authentication callback | | | OPENID_WELL_KNOWN | So-called "well-known" endpoint defining OpenID configuration. | https://auth.cern.ch/auth/realms/cern/.well-known/openid-configuration | + +## Presentations + +| Variable name | Description | Default value | +|---------------|-------------|---------------| +| `ALICE_INSIGHTS_URL` | The HTTP(S) origin of the ALICE Insights generation service, reachable from the Bookkeeping backend. Bookkeeping sends generation requests to `/presentations` on this origin. | Unset | + +In Docker Compose, set `ALICE_INSIGHTS_URL` in the `.env` file to an origin the `application` container can reach. For a native Bookkeeping process, set it in that process's environment. The browser uses Bookkeeping's API for both templates and downloads. + +Open **Presentations** in the Bookkeeping navigation, choose a reporting period and a template, then select **Generate presentation**. The page offers **Download PDF** when the file is ready. Apply Bookkeeping's template migration and seeders for a local installation with example templates. + +The API tests run Bookkeeping against a loopback stand-in for ALICE Insights and check the forwarded request and download. The browser tests use the seeded template list and simulate successful downloads and generation errors. diff --git a/lib/config/services.js b/lib/config/services.js index 9e535881a9..50850b3053 100644 --- a/lib/config/services.js +++ b/lib/config/services.js @@ -29,6 +29,9 @@ const { exports.services = { enableHousekeeping: process.env?.ENABLE_HOUSEKEEPING?.toLowerCase() === 'true', + aliceInsights: { + url: process.env?.ALICE_INSIGHTS_URL || null, + }, userCertificate: { path: USER_CERTIFICATE_PATH ?? MONALISA_CERTIFICATE_PATH, passphrase: USER_CERTIFICATE_PASSPHRASE ?? MONALISA_CERTIFICATE_PASSPHRASE, diff --git a/lib/database/adapters/TemplateAdapter.js b/lib/database/adapters/TemplateAdapter.js new file mode 100644 index 0000000000..961b188884 --- /dev/null +++ b/lib/database/adapters/TemplateAdapter.js @@ -0,0 +1,51 @@ +/** + * @license + * Copyright CERN and copyright holders of ALICE O2. This software is + * distributed under the terms of the GNU General Public License v3 (GPL + * Version 3), copied verbatim in the file "COPYING". + * + * See http://alice-o2.web.cern.ch/license for full licensing information. + * + * In applying this license CERN does not waive the privileges and immunities + * granted to it by virtue of its status as an Intergovernmental Organization + * or submit itself to any jurisdiction. + */ +/** + * Adapter for templates + */ +class TemplateAdapter { + /** + * Constructor + */ + constructor() { + this.toEntity = this.toEntity.bind(this); + + /** + * @type {TemplateModuleAdapter|null} + */ + this.templateModuleAdapter = null; + } + + /** + * Converts the given database object to an entity object. + * + * @param {SequelizeTemplate} databaseObject Object to convert. + * @returns {Template} Converted entity object. + */ + toEntity({ id, name, title, description, modules }) { + const entityObject = { + id, + name, + title, + description, + }; + + if (modules) { + entityObject.modules = modules.map(this.templateModuleAdapter.toEntity); + } + + return entityObject; + } +} + +module.exports = TemplateAdapter; diff --git a/lib/database/adapters/TemplateModuleAdapter.js b/lib/database/adapters/TemplateModuleAdapter.js new file mode 100644 index 0000000000..71639e7aeb --- /dev/null +++ b/lib/database/adapters/TemplateModuleAdapter.js @@ -0,0 +1,40 @@ +/** + * @license + * Copyright CERN and copyright holders of ALICE O2. This software is + * distributed under the terms of the GNU General Public License v3 (GPL + * Version 3), copied verbatim in the file "COPYING". + * + * See http://alice-o2.web.cern.ch/license for full licensing information. + * + * In applying this license CERN does not waive the privileges and immunities + * granted to it by virtue of its status as an Intergovernmental Organization + * or submit itself to any jurisdiction. + */ +/** + * Adapter for template modules + */ +class TemplateModuleAdapter { + /** + * Constructor + */ + constructor() { + this.toEntity = this.toEntity.bind(this); + } + + /** + * Converts the given database object to an entity object. + * + * @param {SequelizeTemplateModule} databaseObject Object to convert. + * @returns {TemplateModule} Converted entity object. + */ + toEntity({ position, type, title, options }) { + return { + position, + type, + title, + options, + }; + } +} + +module.exports = TemplateModuleAdapter; diff --git a/lib/database/adapters/index.js b/lib/database/adapters/index.js index 433a4febeb..470cf6dfb9 100644 --- a/lib/database/adapters/index.js +++ b/lib/database/adapters/index.js @@ -45,6 +45,8 @@ const RunTypeAdapter = require('./RunTypeAdapter'); const SimulationPassAdapter = require('./SimulationPassAdapter.js'); const { SimulationPassQcFlagAdapter } = require('./SimulationPassQcFlagAdapter'); const TagAdapter = require('./TagAdapter'); +const TemplateAdapter = require('./TemplateAdapter.js'); +const TemplateModuleAdapter = require('./TemplateModuleAdapter.js'); const { CtpTriggerCountersAdapter } = require('./CtpTriggerCountersAdapter'); const UserAdapter = require('./UserAdapter'); @@ -82,6 +84,8 @@ const runTypeAdapter = new RunTypeAdapter(); const simulationPassAdapter = new SimulationPassAdapter(); const simulationPassQcFlagAdapter = new SimulationPassQcFlagAdapter(); const tagAdapter = new TagAdapter(); +const templateAdapter = new TemplateAdapter(); +const templateModuleAdapter = new TemplateModuleAdapter(); const ctpTriggerCountersAdapter = new CtpTriggerCountersAdapter(); const userAdapter = new UserAdapter(); @@ -144,6 +148,7 @@ runAdapter.tagAdapter = tagAdapter; runAdapter.userAdapter = userAdapter; tagAdapter.userAdapter = userAdapter; +templateAdapter.templateModuleAdapter = templateModuleAdapter; runAdapter.qcFlagAdapter = qcFlagAdapter; simulationPassQcFlagAdapter.simulationPassAdapter = simulationPassAdapter; @@ -183,6 +188,8 @@ module.exports = { simulationPassAdapter, simulationPassQcFlagAdapter, tagAdapter, + templateAdapter, + templateModuleAdapter, ctpTriggerCountersAdapter, userAdapter, }; diff --git a/lib/database/migrations/v1/20261028100000-create-templates.js b/lib/database/migrations/v1/20261028100000-create-templates.js new file mode 100644 index 0000000000..02c729236f --- /dev/null +++ b/lib/database/migrations/v1/20261028100000-create-templates.js @@ -0,0 +1,105 @@ +/** + * @license + * Copyright CERN and copyright holders of ALICE O2. This software is + * distributed under the terms of the GNU General Public License v3 (GPL + * Version 3), copied verbatim in the file "COPYING". + * + * See http://alice-o2.web.cern.ch/license for full licensing information. + * + * In applying this license CERN does not waive the privileges and immunities + * granted to it by virtue of its status as an Intergovernmental Organization + * or submit itself to any jurisdiction. + */ + +'use strict'; + +/** @type {import('sequelize-cli').Migration} */ +module.exports = { + up: async (queryInterface, Sequelize) => queryInterface.sequelize.transaction(async (transaction) => { + await queryInterface.createTable('templates', { + id: { + allowNull: false, + autoIncrement: true, + primaryKey: true, + type: Sequelize.INTEGER, + }, + name: { + allowNull: false, + unique: true, + type: Sequelize.STRING(64), + }, + title: { + allowNull: false, + type: Sequelize.STRING(255), + }, + description: { + allowNull: true, + type: Sequelize.TEXT, + }, + created_at: { + allowNull: false, + type: Sequelize.DATE, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + }, + updated_at: { + allowNull: false, + type: Sequelize.DATE, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + }, + }, { transaction }); + + await queryInterface.createTable('template_modules', { + id: { + allowNull: false, + autoIncrement: true, + primaryKey: true, + type: Sequelize.INTEGER, + }, + template_id: { + allowNull: false, + type: Sequelize.INTEGER, + references: { model: 'templates', key: 'id' }, + onUpdate: 'CASCADE', + onDelete: 'CASCADE', + }, + position: { + allowNull: false, + type: Sequelize.INTEGER, + }, + type: { + allowNull: false, + type: Sequelize.STRING(64), + }, + title: { + allowNull: true, + type: Sequelize.STRING(255), + }, + options: { + allowNull: false, + type: Sequelize.JSON, + }, + created_at: { + allowNull: false, + type: Sequelize.DATE, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + }, + updated_at: { + allowNull: false, + type: Sequelize.DATE, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + }, + }, { transaction }); + + await queryInterface.addConstraint('template_modules', { + fields: ['template_id', 'position'], + type: 'unique', + name: 'template_modules_template_id_position', + transaction, + }); + }), + + down: async (queryInterface) => queryInterface.sequelize.transaction(async (transaction) => { + await queryInterface.dropTable('template_modules', { transaction }); + await queryInterface.dropTable('templates', { transaction }); + }), +}; diff --git a/lib/database/models/index.js b/lib/database/models/index.js index 87d793fac3..394c47074e 100644 --- a/lib/database/models/index.js +++ b/lib/database/models/index.js @@ -45,6 +45,8 @@ const SimulationPass = require('./simulationPass.js'); const SimulationPassQcFlag = require('./simulationPassQcFlag.js'); const StableBeamRun = require('./stableBeamsRun.js'); const Tag = require('./tag'); +const Template = require('./template.js'); +const TemplateModule = require('./templateModule.js'); const CtpTriggerCounters = require('./ctpTriggerCounters'); const User = require('./user'); @@ -84,6 +86,8 @@ module.exports = (sequelize) => { SimulationPassQcFlag: SimulationPassQcFlag(sequelize), StableBeamRun: StableBeamRun(sequelize), Tag: Tag(sequelize), + Template: Template(sequelize), + TemplateModule: TemplateModule(sequelize), CtpTriggerCounters: CtpTriggerCounters(sequelize), User: User(sequelize), }; diff --git a/lib/database/models/template.js b/lib/database/models/template.js new file mode 100644 index 0000000000..db7f2b96ea --- /dev/null +++ b/lib/database/models/template.js @@ -0,0 +1,41 @@ +/** + * @license + * Copyright CERN and copyright holders of ALICE O2. This software is + * distributed under the terms of the GNU General Public License v3 (GPL + * Version 3), copied verbatim in the file "COPYING". + * + * See http://alice-o2.web.cern.ch/license for full licensing information. + * + * In applying this license CERN does not waive the privileges and immunities + * granted to it by virtue of its status as an Intergovernmental Organization + * or submit itself to any jurisdiction. + */ + +const Sequelize = require('sequelize'); + +module.exports = (sequelize) => { + const Template = sequelize.define('Template', { + name: { + allowNull: false, + unique: true, + type: Sequelize.STRING(64), + }, + title: { + allowNull: false, + type: Sequelize.STRING(255), + }, + description: { + allowNull: true, + type: Sequelize.TEXT, + }, + }); + + Template.associate = (models) => { + Template.hasMany(models.TemplateModule, { + as: 'modules', + foreignKey: 'templateId', + }); + }; + + return Template; +}; diff --git a/lib/database/models/templateModule.js b/lib/database/models/templateModule.js new file mode 100644 index 0000000000..84c66e8b21 --- /dev/null +++ b/lib/database/models/templateModule.js @@ -0,0 +1,48 @@ +/** + * @license + * Copyright CERN and copyright holders of ALICE O2. This software is + * distributed under the terms of the GNU General Public License v3 (GPL + * Version 3), copied verbatim in the file "COPYING". + * + * See http://alice-o2.web.cern.ch/license for full licensing information. + * + * In applying this license CERN does not waive the privileges and immunities + * granted to it by virtue of its status as an Intergovernmental Organization + * or submit itself to any jurisdiction. + */ + +const Sequelize = require('sequelize'); + +module.exports = (sequelize) => { + const TemplateModule = sequelize.define('TemplateModule', { + templateId: { + allowNull: false, + type: Sequelize.INTEGER, + }, + position: { + allowNull: false, + type: Sequelize.INTEGER, + }, + type: { + allowNull: false, + type: Sequelize.STRING(64), + }, + title: { + allowNull: true, + type: Sequelize.STRING(255), + }, + options: { + allowNull: false, + type: Sequelize.JSON, + }, + }); + + TemplateModule.associate = (models) => { + TemplateModule.belongsTo(models.Template, { + as: 'template', + foreignKey: 'templateId', + }); + }; + + return TemplateModule; +}; diff --git a/lib/database/models/typedefs/SequelizeTemplate.js b/lib/database/models/typedefs/SequelizeTemplate.js new file mode 100644 index 0000000000..7a9d7e3e40 --- /dev/null +++ b/lib/database/models/typedefs/SequelizeTemplate.js @@ -0,0 +1,24 @@ +/** + * @license + * Copyright CERN and copyright holders of ALICE O2. This software is + * distributed under the terms of the GNU General Public License v3 (GPL + * Version 3), copied verbatim in the file "COPYING". + * + * See http://alice-o2.web.cern.ch/license for full licensing information. + * + * In applying this license CERN does not waive the privileges and immunities + * granted to it by virtue of its status as an Intergovernmental Organization + * or submit itself to any jurisdiction. + */ + +/** + * @typedef SequelizeTemplate + * + * @property {number} id + * @property {string} name + * @property {string} title + * @property {string|null} description + * @property {SequelizeTemplateModule[]} [modules] + * @property {string} createdAt + * @property {string} updatedAt + */ diff --git a/lib/database/models/typedefs/SequelizeTemplateModule.js b/lib/database/models/typedefs/SequelizeTemplateModule.js new file mode 100644 index 0000000000..2f0068997e --- /dev/null +++ b/lib/database/models/typedefs/SequelizeTemplateModule.js @@ -0,0 +1,25 @@ +/** + * @license + * Copyright CERN and copyright holders of ALICE O2. This software is + * distributed under the terms of the GNU General Public License v3 (GPL + * Version 3), copied verbatim in the file "COPYING". + * + * See http://alice-o2.web.cern.ch/license for full licensing information. + * + * In applying this license CERN does not waive the privileges and immunities + * granted to it by virtue of its status as an Intergovernmental Organization + * or submit itself to any jurisdiction. + */ + +/** + * @typedef SequelizeTemplateModule + * + * @property {number} id + * @property {number} templateId + * @property {number} position + * @property {string} type + * @property {string|null} title + * @property {Object} options + * @property {string} createdAt + * @property {string} updatedAt + */ diff --git a/lib/database/repositories/TemplateRepository.js b/lib/database/repositories/TemplateRepository.js new file mode 100644 index 0000000000..90603b533c --- /dev/null +++ b/lib/database/repositories/TemplateRepository.js @@ -0,0 +1,33 @@ +/** + * @license + * Copyright CERN and copyright holders of ALICE O2. This software is + * distributed under the terms of the GNU General Public License v3 (GPL + * Version 3), copied verbatim in the file "COPYING". + * + * See http://alice-o2.web.cern.ch/license for full licensing information. + * + * In applying this license CERN does not waive the privileges and immunities + * granted to it by virtue of its status as an Intergovernmental Organization + * or submit itself to any jurisdiction. + */ + +const { + models: { + Template, + }, +} = require('../'); +const Repository = require('./Repository'); + +/** + * Sequelize implementation of the TemplateRepository. + */ +class TemplateRepository extends Repository { + /** + * Creates a new `TemplateRepository` instance. + */ + constructor() { + super(Template); + } +} + +module.exports = new TemplateRepository(); diff --git a/lib/database/repositories/index.js b/lib/database/repositories/index.js index 53673cc9c1..9e37b8e010 100644 --- a/lib/database/repositories/index.js +++ b/lib/database/repositories/index.js @@ -52,6 +52,7 @@ const SimulationPassRepository = require('./SimulationPassRepository.js'); const SimulationPassQcFlagRepository = require('./SimulationPassQcFlagRepository.js'); const StableBeamRunsRepository = require('./StableBeamRunsRepository.js'); const TagRepository = require('./TagRepository'); +const TemplateRepository = require('./TemplateRepository.js'); const CtpTriggerCountersRepository = require('./CtpTriggerCountersRepository'); const UserRepository = require('./UserRepository'); @@ -97,6 +98,7 @@ module.exports = { SimulationPassQcFlagRepository, StableBeamRunsRepository, TagRepository, + TemplateRepository, CtpTriggerCountersRepository, UserRepository, }; diff --git a/lib/database/seeders/20261028100000-templates.js b/lib/database/seeders/20261028100000-templates.js new file mode 100644 index 0000000000..926d4ff406 --- /dev/null +++ b/lib/database/seeders/20261028100000-templates.js @@ -0,0 +1,50 @@ +/** + * @license + * Copyright CERN and copyright holders of ALICE O2. This software is + * distributed under the terms of the GNU General Public License v3 (GPL + * Version 3), copied verbatim in the file "COPYING". + * + * See http://alice-o2.web.cern.ch/license for full licensing information. + * + * In applying this license CERN does not waive the privileges and immunities + * granted to it by virtue of its status as an Intergovernmental Organization + * or submit itself to any jurisdiction. + */ +'use strict'; + +const PHYSICS_ONLY = JSON.stringify({ run_definitions: ['PHYSICS'] }); +const NO_OPTIONS = JSON.stringify({}); + +module.exports = { + up: async (queryInterface) => + queryInterface.sequelize.transaction(async (transaction) => { + await queryInterface.bulkInsert('templates', [ + { + id: 1, + name: 'run-manager-weekly-report', + title: 'Run Manager Weekly Report', + description: 'The weekly report of the run manager for the Run Coordination meeting.', + }, + { + id: 2, + name: 'lhc-fill-summary', + title: 'LHC Fill Summary', + description: 'A short summary of the LHC fills of the period and how efficiently their stable beams were used.', + }, + ], { transaction }); + + await queryInterface.bulkInsert('template_modules', [ + { template_id: 1, position: 0, type: 'title-slide', title: 'Run Manager Weekly Report', options: NO_OPTIONS }, + { template_id: 1, position: 1, type: 'fill-calendar', title: 'Fills and runs', options: PHYSICS_ONLY }, + { template_id: 1, position: 2, type: 'fill-efficiency', title: 'Fill efficiencies', options: PHYSICS_ONLY }, + { template_id: 1, position: 3, type: 'running-time', title: 'Running time', options: PHYSICS_ONLY }, + { template_id: 1, position: 4, type: 'eor-reasons', title: 'End of Run reasons', options: PHYSICS_ONLY }, + { template_id: 2, position: 0, type: 'title-slide', title: 'LHC Fill Summary', options: NO_OPTIONS }, + { template_id: 2, position: 1, type: 'fill-calendar', title: 'Fills and runs', options: PHYSICS_ONLY }, + { template_id: 2, position: 2, type: 'fill-efficiency', title: 'Fill efficiencies', options: PHYSICS_ONLY }, + ], { transaction }); + }), + down: async (queryInterface) => + queryInterface.sequelize.transaction((transaction) => + Promise.all([queryInterface.bulkDelete('templates', null, { transaction })])), +}; diff --git a/lib/domain/dtos/CreatePresentationDto.js b/lib/domain/dtos/CreatePresentationDto.js new file mode 100644 index 0000000000..4ee68f7720 --- /dev/null +++ b/lib/domain/dtos/CreatePresentationDto.js @@ -0,0 +1,29 @@ +/** + * @license + * Copyright CERN and copyright holders of ALICE O2. This software is + * distributed under the terms of the GNU General Public License v3 (GPL + * Version 3), copied verbatim in the file "COPYING". + * + * See http://alice-o2.web.cern.ch/license for full licensing information. + * + * In applying this license CERN does not waive the privileges and immunities + * granted to it by virtue of its status as an Intergovernmental Organization + * or submit itself to any jurisdiction. + */ + +const Joi = require('joi'); +const EntityIdDto = require('./EntityIdDto'); + +const timestamp = Joi.number().integer().min(0).required(); + +module.exports = Joi.object({ + body: Joi.object({ + templateId: EntityIdDto.required(), + from: timestamp, + to: timestamp.greater(Joi.ref('from')), + }).required(), + params: Joi.object({}), + query: Joi.object({ + token: Joi.string(), + }), +}); diff --git a/lib/domain/dtos/GetAllTemplatesDto.js b/lib/domain/dtos/GetAllTemplatesDto.js new file mode 100644 index 0000000000..0fc614d222 --- /dev/null +++ b/lib/domain/dtos/GetAllTemplatesDto.js @@ -0,0 +1,26 @@ +/** + * @license + * Copyright CERN and copyright holders of ALICE O2. This software is + * distributed under the terms of the GNU General Public License v3 (GPL + * Version 3), copied verbatim in the file "COPYING". + * + * See http://alice-o2.web.cern.ch/license for full licensing information. + * + * In applying this license CERN does not waive the privileges and immunities + * granted to it by virtue of its status as an Intergovernmental Organization + * or submit itself to any jurisdiction. + */ + +const Joi = require('joi'); + +const QueryDto = Joi.object({ + token: Joi.string(), +}); + +const GetAllTemplatesDto = Joi.object({ + body: Joi.object({}), + params: Joi.object({}), + query: QueryDto, +}); + +module.exports = GetAllTemplatesDto; diff --git a/lib/domain/dtos/GetTemplateDto.js b/lib/domain/dtos/GetTemplateDto.js new file mode 100644 index 0000000000..6b796037c8 --- /dev/null +++ b/lib/domain/dtos/GetTemplateDto.js @@ -0,0 +1,31 @@ +/** + * @license + * Copyright CERN and copyright holders of ALICE O2. This software is + * distributed under the terms of the GNU General Public License v3 (GPL + * Version 3), copied verbatim in the file "COPYING". + * + * See http://alice-o2.web.cern.ch/license for full licensing information. + * + * In applying this license CERN does not waive the privileges and immunities + * granted to it by virtue of its status as an Intergovernmental Organization + * or submit itself to any jurisdiction. + */ + +const Joi = require('joi'); +const EntityIdDto = require('./EntityIdDto'); + +const ParamsDto = Joi.object({ + templateId: EntityIdDto, +}); + +const QueryDto = Joi.object({ + token: Joi.string(), +}); + +const GetTemplateDto = Joi.object({ + body: Joi.object({}), + params: ParamsDto, + query: QueryDto, +}); + +module.exports = GetTemplateDto; diff --git a/lib/domain/dtos/index.js b/lib/domain/dtos/index.js index 01eb348934..11e98c6391 100644 --- a/lib/domain/dtos/index.js +++ b/lib/domain/dtos/index.js @@ -16,6 +16,7 @@ const CreateEnvironmentDto = require('./CreateEnvironmentDto.js'); const CreateFlpDto = require('./CreateFlpDto'); const CreateLhcFillDto = require('./CreateLhcFillDto'); const CreateLogDto = require('./CreateLogDto'); +const CreatePresentationDto = require('./CreatePresentationDto.js'); const CreateTagDto = require('./CreateTagDto'); const EntityIdDto = require('./EntityIdDto'); const GetAllEnvironmentsDto = require('./GetAllEnvironmentsDto'); @@ -25,6 +26,7 @@ const GetAllLogsDto = require('./GetAllLogsDto'); const GetAllRunsDto = require('./GetAllRunsDto'); const GetAllRunTypesDto = require('./GetAllRunTypesDto'); const GetAllTagsDto = require('./GetAllTagsDto'); +const GetAllTemplatesDto = require('./GetAllTemplatesDto.js'); const GetAllFlpsDto = require('./GetAllFlpsDto'); const GetAttachmentDto = require('./GetAttachmentDto'); const GetEnvironmentDto = require('./GetEnvironmentDto'); @@ -37,6 +39,7 @@ const GetRunTypeDto = require('./GetRunTypeDto'); const StartRunDto = require('./StartRunDto'); const EndRunDto = require('./EndRunDto'); const GetTagDto = require('./GetTagDto'); +const GetTemplateDto = require('./GetTemplateDto.js'); const GetFlpDto = require('./GetFlpDto'); const PaginationDto = require('./PaginationDto'); const UpdateEnvironmentDto = require('./UpdateEnvironmentDto'); @@ -53,6 +56,7 @@ module.exports = { CreateFlpDto, CreateLhcFillDto, CreateLogDto, + CreatePresentationDto, CreateTagDto, EndRunDto, EntityIdDto, @@ -63,6 +67,7 @@ module.exports = { GetAllRunsDto, GetAllRunTypesDto, GetAllTagsDto, + GetAllTemplatesDto, GetAllFlpsDto, GetAttachmentDto, GetEnvironmentDto, @@ -75,6 +80,7 @@ module.exports = { StartRunDto, GetTagByNameDto, GetTagDto, + GetTemplateDto, GetFlpDto, PaginationDto, UpdateEnvironmentDto, diff --git a/lib/domain/entities/Template.js b/lib/domain/entities/Template.js new file mode 100644 index 0000000000..9ba9b2b49d --- /dev/null +++ b/lib/domain/entities/Template.js @@ -0,0 +1,31 @@ +/** + * @license + * Copyright CERN and copyright holders of ALICE O2. This software is + * distributed under the terms of the GNU General Public License v3 (GPL + * Version 3), copied verbatim in the file "COPYING". + * + * See http://alice-o2.web.cern.ch/license for full licensing information. + * + * In applying this license CERN does not waive the privileges and immunities + * granted to it by virtue of its status as an Intergovernmental Organization + * or submit itself to any jurisdiction. + */ + +/** + * @typedef TemplateModule + * + * @property {number} position the position of the module in the presentation, starting at 0 + * @property {string} type the type of the module, as known by the generation service + * @property {string|null} title the title of the module's slides + * @property {Object} options the settings of the module + */ + +/** + * @typedef Template + * + * @property {number} id + * @property {string} name the unique name of the template + * @property {string} title the title of the presentations made with the template + * @property {string|null} description + * @property {TemplateModule[]} [modules] the modules of the template, in presentation order + */ diff --git a/lib/public/Model.js b/lib/public/Model.js index a978492a75..76a62704f4 100644 --- a/lib/public/Model.js +++ b/lib/public/Model.js @@ -27,6 +27,7 @@ import { registerFrontLinkListener } from './components/common/navigation/frontL import { EosReportModel } from './views/EosReport/EosReportModel.js'; import { AboutModel } from './views/About/About.js'; import { StatisticsPageModel } from './views/Statistics/StatisticsPageModel.js'; +import { PresentationsPageModel } from './views/Presentations/PresentationsPageModel.js'; import { LhcPeriodsModel } from './views/lhcPeriods/LhcPeriodsModel.js'; import { HomePageModel } from './views/Home/Overview/HomePageModel.js'; import { DataPassesModel } from './views/DataPasses/DataPassesModel.js'; @@ -148,6 +149,9 @@ export default class Model extends Observable { this.statisticsModel = new StatisticsPageModel(); this.statisticsModel.bubbleTo(this); + this.presentationsModel = new PresentationsPageModel(); + this.presentationsModel.bubbleTo(this); + /** * @type {TagModel} */ @@ -306,6 +310,9 @@ export default class Model extends Observable { case 'statistics': this.statisticsModel.load(this.router.params); break; + case 'presentations': + this.presentationsModel.load(); + break; case 'tag-overview': break; case 'tag-detail': diff --git a/lib/public/app.css b/lib/public/app.css index 92a684e58a..3e2cd233e5 100644 --- a/lib/public/app.css +++ b/lib/public/app.css @@ -864,6 +864,13 @@ label { } } +/* Tighten the tabs so the full navbar fits on laptop-width screens. */ +@media screen and (min-width: 1280px) and (max-width: 1439px) { + .navbar-links .btn { + padding-inline: 0.625rem; + } +} + /* runs and LHC fills overviews: labels of the timing lines have the same width so that the times are aligned, and digits have a fixed width */ .timing-label { min-width: 2.8em; diff --git a/lib/public/components/NavBar/index.js b/lib/public/components/NavBar/index.js index e8cfd8a2e1..203fad8831 100644 --- a/lib/public/components/NavBar/index.js +++ b/lib/public/components/NavBar/index.js @@ -108,6 +108,7 @@ const NAVIGATION_PAGES = [ ['run-overview', 'Runs'], ['lhc-period-overview', 'RCT'], ['statistics', 'Statistics'], + ['presentations', 'Presentations'], ]; const OVERVIEW_PAGES = [ diff --git a/lib/public/view.js b/lib/public/view.js index 7a8c7adc37..eeeb8fc1fc 100644 --- a/lib/public/view.js +++ b/lib/public/view.js @@ -31,6 +31,7 @@ import { LogTreeViewPage } from './views/Logs/Details/LogTreeViewPage.js'; import { TagDetailsPage } from './views/Tags/Details/TagDetailsPage.js'; import { EosReportCreationPage } from './views/EosReport/create/EosReportCreationPage.js'; import { StatisticsPage } from './views/Statistics/StatisticsPage.js'; +import { PresentationsPage } from './views/Presentations/PresentationsPage.js'; import { LhcPeriodsOverviewPage } from './views/lhcPeriods/Overview/LhcPeriodsOverviewPage.js'; import { RunsPerLhcPeriodOverviewPage } from './views/Runs/RunPerPeriod/RunsPerLhcPeriodOverviewPage.js'; import { HomePage } from './views/Home/Overview/HomePage.js'; @@ -104,6 +105,7 @@ export default (model) => { 'gaq-flags': GaqFlagsOverviewPage, statistics: StatisticsPage, + presentations: PresentationsPage, 'flp-overview': FlpOverview, 'flp-detail': FlpDetail, diff --git a/lib/public/views/Presentations/PresentationsPage.js b/lib/public/views/Presentations/PresentationsPage.js new file mode 100644 index 0000000000..ddae7e168a --- /dev/null +++ b/lib/public/views/Presentations/PresentationsPage.js @@ -0,0 +1,77 @@ +/** + * @license + * Copyright CERN and copyright holders of ALICE O2. This software is + * distributed under the terms of the GNU General Public License v3 (GPL + * Version 3), copied verbatim in the file "COPYING". + * + * See http://alice-o2.web.cern.ch/license for full licensing information. + * + * In applying this license CERN does not waive the privileges and immunities + * granted to it by virtue of its status as an Intergovernmental Organization + * or submit itself to any jurisdiction. + */ +import { h } from '/js/src/index.js'; +import { timeRangeFilter } from '../../components/Filters/common/filters/timeRangeFilter.js'; +import errorAlert from '../../components/common/errorAlert.js'; +import spinner from '../../components/common/spinner.js'; + +const templatePicker = (model) => model.templates.match({ + Success: (templates) => templates.length === 0 + ? h('p.gray-darker.mv0', 'No templates are available.') + : h('.flex-column.g1', [ + h('label', { for: 'presentation-template' }, 'Template'), + h('select.form-control#presentation-template', { + value: model.templateId === null ? '' : String(model.templateId), + disabled: model.isGenerating, + onchange: (event) => model.selectTemplate(event.target.value), + }, [ + h('option', { value: '' }, 'Choose a template'), + ...templates.map(({ id, title }) => h('option', { value: String(id) }, title)), + ]), + ]), + Failure: (errors) => errorAlert(errors), + Other: () => h('p.gray-darker.mv0', { role: 'status' }, 'Loading templates…'), +}); + +const generationResult = (model) => model.result.match({ + Loading: () => h('#presentation-generation-status.flex-column.g2', { role: 'status' }, [ + spinner({ size: 2, justify: 'left', absolute: false }), + h('p.mv0', 'Generating the presentation…'), + ]), + Success: ({ url, fileName }) => h('.flex-row.flex-wrap.items-center.g3', [ + h('strong', { role: 'status' }, 'Presentation ready'), + h('a.btn.btn-primary#download-presentation', { href: url, download: fileName }, 'Download PDF'), + ]), + Failure: (errors) => h('#presentation-generation-error', { role: 'alert' }, errorAlert(errors)), + Other: () => null, +}); + +/** + * Display the form for generating a presentation from a template and period. + * @param {Model} model the global model + * @return {Component} the presentations page + */ +export const PresentationsPage = ({ presentationsModel }) => h('#presentations-page.flex-column.g3', { + onremove: () => presentationsModel.close(), +}, [ + h('h1', 'Presentations'), + h('form.flex-column.g3', { + onsubmit: (event) => { + event.preventDefault(); + presentationsModel.generate(); + }, + }, [ + h('.flex-row.flex-wrap.items-end.g3', [ + h('#presentation-period.flex-column.g1', { inert: presentationsModel.isGenerating }, [ + h('span', 'Period'), + timeRangeFilter(presentationsModel.timeRangeModel), + ]), + templatePicker(presentationsModel), + ]), + h('.flex-row', h('button.btn.btn-primary#generate-presentation', { + type: 'submit', + disabled: !presentationsModel.canGenerate, + }, 'Generate presentation')), + ]), + generationResult(presentationsModel), +]); diff --git a/lib/public/views/Presentations/PresentationsPageModel.js b/lib/public/views/Presentations/PresentationsPageModel.js new file mode 100644 index 0000000000..337d598e1c --- /dev/null +++ b/lib/public/views/Presentations/PresentationsPageModel.js @@ -0,0 +1,175 @@ +/** + * @license + * Copyright CERN and copyright holders of ALICE O2. This software is + * distributed under the terms of the GNU General Public License v3 (GPL + * Version 3), copied verbatim in the file "COPYING". + * + * See http://alice-o2.web.cern.ch/license for full licensing information. + * + * In applying this license CERN does not waive the privileges and immunities + * granted to it by virtue of its status as an Intergovernmental Organization + * or submit itself to any jurisdiction. + */ +import { fetchClient, Observable, RemoteData } from '/js/src/index.js'; +import { TimeRangeInputModel } from '../../components/Filters/common/filters/TimeRangeInputModel.js'; +import { getRemoteData } from '../../utilities/fetch/getRemoteData.js'; + +const GENERATION_FAILURE_TITLE = 'Could not generate the presentation'; + +/** + * Store the form and the result of a presentation request. + */ +export class PresentationsPageModel extends Observable { + /** + * Set up the required period and empty form. + */ + constructor() { + super(); + this.timeRangeModel = new TimeRangeInputModel(null, null, { required: true }); + this.timeRangeModel.bubbleTo(this); + this.timeRangeModel.visualChange$.bubbleTo(this); + this.templates = RemoteData.notAsked(); + this.templateId = null; + this.result = RemoteData.notAsked(); + this._generationRequest = null; + } + + /** + * Load the current list of predefined templates. + * @return {Promise} resolves once the list has loaded + */ + async load() { + if (this.templates.match({ Loading: () => true, Other: () => false })) { + return; + } + + this.templates = RemoteData.loading(); + this.notify(); + try { + const { data: templates } = await getRemoteData('/api/templates'); + this.templates = RemoteData.success(templates); + if (!templates.some(({ id }) => id === this.templateId)) { + this.templateId = null; + } + } catch (errors) { + this.templates = RemoteData.failure(errors); + } + this.notify(); + } + + /** + * Select a predefined template from the picker. + * @param {string} value the chosen option's value + * @return {void} + */ + selectTemplate(value) { + this.templateId = value ? Number(value) : null; + this.notify(); + } + + /** + * Return the selected time bounds as Unix milliseconds. + * @return {Period} the chosen period + */ + get period() { + return { from: this.timeRangeModel.fromTimeInputModel.value, to: this.timeRangeModel.toTimeInputModel.value }; + } + + /** + * Indicate whether a generation request is in progress. + * @return {boolean} whether the request is in progress + */ + get isGenerating() { + return this._generationRequest !== null; + } + + /** + * Indicate whether the form can start generation. + * @return {boolean} whether the complete form is ready + */ + get canGenerate() { + const { from, to } = this.period; + const hasTemplate = this.templates.match({ + Success: (templates) => templates.some(({ id }) => id === this.templateId), + Other: () => false, + }); + return !this.isGenerating && hasTemplate && Number.isSafeInteger(from) && from >= 0 && Number.isSafeInteger(to) && from < to; + } + + /** + * Request the PDF from Bookkeeping and make it available for download. + * @return {Promise} resolves once generation succeeds or fails + */ + async generate() { + if (!this.canGenerate) { + return; + } + + this._releaseDownload(); + this._generationRequest = new AbortController(); + const { signal } = this._generationRequest; + this.result = RemoteData.loading(); + this.notify(); + + try { + const response = await fetchClient('/api/presentations', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ templateId: this.templateId, ...this.period }), + signal, + }); + if (!response.ok) { + const body = await response.json().catch(() => null); + if (!signal.aborted) { + this.result = RemoteData.failure(body?.errors ?? { + title: GENERATION_FAILURE_TITLE, + detail: body?.message ?? `Bookkeeping returned HTTP ${response.status}.`, + }); + } + return; + } + + if (response.headers.get('Content-Type')?.split(';')[0] !== 'application/pdf') { + if (!signal.aborted) { + this.result = RemoteData.failure({ title: GENERATION_FAILURE_TITLE, detail: 'Bookkeeping did not return a PDF.' }); + } + return; + } + + const pdf = await response.blob(); + if (!signal.aborted) { + const disposition = response.headers.get('Content-Disposition') ?? ''; + const fileName = /filename="([^"]+)"/i.exec(disposition)?.[1] ?? 'presentation.pdf'; + this.result = RemoteData.success({ url: URL.createObjectURL(pdf), fileName }); + } + } catch { + if (!signal.aborted) { + this.result = RemoteData.failure({ title: GENERATION_FAILURE_TITLE, detail: 'Bookkeeping could not complete the request.' }); + } + } finally { + if (!signal.aborted) { + this._generationRequest = null; + this.notify(); + } + } + } + + /** + * Discard the result and stop any active browser request when leaving the page. + * @return {void} + */ + close() { + this._generationRequest?.abort(); + this._generationRequest = null; + this._releaseDownload(); + this.result = RemoteData.notAsked(); + } + + /** + * Release the current download URL when it is no longer needed. + * @return {void} + */ + _releaseDownload() { + this.result.match({ Success: ({ url }) => URL.revokeObjectURL(url), Other: () => {} }); + } +} diff --git a/lib/server/api-docs/API.md b/lib/server/api-docs/API.md index 70a34d614f..b08dc83b86 100644 --- a/lib/server/api-docs/API.md +++ b/lib/server/api-docs/API.md @@ -10,7 +10,7 @@ Every request carries a JWT in the `token` **query parameter** (e.g. `GET /api/t The token's `access` claim lists the user's roles; operations marked with a role below return `403` otherwise. ## Response envelope -Successful responses are `{ "data": ... }`, with `meta.page` added on paginated endpoints. +Successful JSON responses are `{ "data": ... }`, with `meta.page` added on paginated endpoints. The generation endpoint returns a PDF attachment. Failed responses are `{ "errors": [ { status, title, detail?, source? } ] }`. Note that request-validation failures are sent with **HTTP 400** while each error's `status` field says `"422"`. @@ -436,3 +436,85 @@ Responses: ```bash curl -g "$BOOKKEEPING_URL/api/simulationPasses/1?token=$TOKEN" ``` + +## Templates + +Presentation templates, each an ordered list of content modules, read by the ALICE Insights generation service. + +### `GET /templates` - List presentation templates + +Operation id: `listTemplates` + +Returns the presentation templates ordered by title, without their modules. Not paginated: there are few templates. Pagination parameters +are rejected. + +Responses: + +- `200`: The templates. +- `400`: The request failed validation. HTTP status is 400 although each error's `status` field is `"422"`. `source.pointer` has the form `/data/attributes//`. + +```bash +curl -g "$BOOKKEEPING_URL/api/templates?token=$TOKEN" +``` + +### `GET /templates/{templateId}` - Get a presentation template by id, with its modules + +Operation id: `getTemplate` + +| Parameter | In | Type | Required | Notes | +| --- | --- | --- | --- | --- | +| `templateId` | path | integer | yes | Template identifier. | + +Responses: + +- `200`: The template, with its modules in presentation order. +- `400`: The request failed validation. HTTP status is 400 although each error's `status` field is `"422"`. `source.pointer` has the form `/data/attributes//`. +- `404`: No template has this id. + +```bash +curl -g "$BOOKKEEPING_URL/api/templates/1?token=$TOKEN" +``` + +## Presentations + +On-demand PDF generation for signed-in Bookkeeping users. + +### `POST /presentations` - Generate a presentation PDF + +Operation id: `generatePresentation` + +Generates a PDF from a template and reporting period. Bookkeeping uses the authenticated user's name as the author and forwards +their token to ALICE Insights. The reporting period includes its start and excludes its end. + +Request body (JSON): + +| Field | Type | Required | Notes | +| --- | --- | --- | --- | +| `templateId` | integer | yes | The ID returned by GET /templates. | +| `from` | integer | yes | Inclusive start in Unix milliseconds. | +| `to` | integer | yes | Exclusive end in Unix milliseconds. Must be greater than from. | + +Responses: + +- `200`: PDF attachment. The Content-Disposition header contains the filename. +- `400`: The request failed validation. HTTP status is 400 although each error's `status` field is `"422"`. `source.pointer` has the form `/data/attributes//`. +- `401`: A valid Bookkeeping user session is required. +- `422`: ALICE Insights rejected the template or period. +- `502`: The generation service could not return a PDF. +- `503`: Generation is unavailable or busy. A busy response can include Retry-After in seconds. +- `504`: The generation service took too long to return a PDF. + +**PowerShell 7+** + +```powershell +Invoke-WebRequest -Uri "$env:BOOKKEEPING_URL/api/presentations?token=$env:TOKEN" -Method POST -ContentType 'application/json' -Body '{"templateId":1,"from":1794783600000,"to":1795388400000}' -OutFile presentation.pdf +``` + +**Linux/Bash** + +```bash +curl -g --fail -X POST "$BOOKKEEPING_URL/api/presentations?token=$TOKEN" \ + -H 'content-type: application/json' \ + -d '{"templateId":1,"from":1794783600000,"to":1795388400000}' \ + --output presentation.pdf +``` diff --git a/lib/server/api-docs/index.html b/lib/server/api-docs/index.html index cb869dc1c8..99666fe0e2 100644 --- a/lib/server/api-docs/index.html +++ b/lib/server/api-docs/index.html @@ -64,7 +64,7 @@

Authentication

Every request carries a JWT in the token query parameter (e.g. GET /api/tags?token=<jwt>). The token's access claim lists the user's roles; operations marked with a role below return 403 otherwise.

Response envelope

-

Successful responses are { "data": ... }, with meta.page added on paginated endpoints. +

Successful JSON responses are { "data": ... }, with meta.page added on paginated endpoints. The generation endpoint returns a PDF attachment. Failed responses are { "errors": [ { status, title, detail?, source? } ] }. Note that request-validation failures are sent with HTTP 400 while each error's status field says "422".

Conventions

@@ -759,6 +759,110 @@

Simulation passes

curl -g "$BOOKKEEPING_URL/api/simulationPasses/1?token=$TOKEN"
 
+

Templates

+

Presentation templates, each an ordered list of content modules, read by the ALICE Insights generation service.

+
+

GET /templates - List presentation templates

+ +

Operation id: listTemplates

+

Returns the presentation templates ordered by title, without their modules. Not paginated: there are few templates. Pagination parameters +are rejected.

+

Responses:

+
    +
  • 200: The templates.
  • +
  • 400: The request failed validation. HTTP status is 400 although each error's status field is "422". source.pointer has the form /data/attributes/<query|params|body>/<field>.
  • +
+
curl -g "$BOOKKEEPING_URL/api/templates?token=$TOKEN"
+
+
+
+

GET /templates/{templateId} - Get a presentation template by id, with its modules

+ +

Operation id: getTemplate

+ + + + + + + + + + + + + + + + + +
ParameterInTypeRequiredNotes
templateIdpathintegeryesTemplate identifier.
+

Responses:

+
    +
  • 200: The template, with its modules in presentation order.
  • +
  • 400: The request failed validation. HTTP status is 400 although each error's status field is "422". source.pointer has the form /data/attributes/<query|params|body>/<field>.
  • +
  • 404: No template has this id.
  • +
+
curl -g "$BOOKKEEPING_URL/api/templates/1?token=$TOKEN"
+
+
+

Presentations

+

On-demand PDF generation for signed-in Bookkeeping users.

+
+

POST /presentations - Generate a presentation PDF

+ +

Operation id: generatePresentation

+

Generates a PDF from a template and reporting period. Bookkeeping uses the authenticated user's name as the author and forwards +their token to ALICE Insights. The reporting period includes its start and excludes its end.

+

Request body (JSON):

+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FieldTypeRequiredNotes
templateIdintegeryesThe ID returned by GET /templates.
fromintegeryesInclusive start in Unix milliseconds.
tointegeryesExclusive end in Unix milliseconds. Must be greater than from.
+

Responses:

+
    +
  • 200: PDF attachment. The Content-Disposition header contains the filename.
  • +
  • 400: The request failed validation. HTTP status is 400 although each error's status field is "422". source.pointer has the form /data/attributes/<query|params|body>/<field>.
  • +
  • 401: A valid Bookkeeping user session is required.
  • +
  • 422: ALICE Insights rejected the template or period.
  • +
  • 502: The generation service could not return a PDF.
  • +
  • 503: Generation is unavailable or busy. A busy response can include Retry-After in seconds.
  • +
  • 504: The generation service took too long to return a PDF.
  • +
+

PowerShell 7+

+
Invoke-WebRequest -Uri "$env:BOOKKEEPING_URL/api/presentations?token=$env:TOKEN" -Method POST -ContentType 'application/json' -Body '{"templateId":1,"from":1794783600000,"to":1795388400000}' -OutFile presentation.pdf
+
+

Linux/Bash

+
curl -g --fail -X POST "$BOOKKEEPING_URL/api/presentations?token=$TOKEN" \
+  -H 'content-type: application/json' \
+  -d '{"templateId":1,"from":1794783600000,"to":1795388400000}' \
+  --output presentation.pdf
+
+
Generated from openapi.yaml by npm run docs:api · ALICE Bookkeeping · internal use only
diff --git a/lib/server/api-docs/openapi.yaml b/lib/server/api-docs/openapi.yaml index 4a7fc919b2..4f535e5007 100644 --- a/lib/server/api-docs/openapi.yaml +++ b/lib/server/api-docs/openapi.yaml @@ -12,7 +12,7 @@ info: The token's `access` claim lists the user's roles; operations marked with a role below return `403` otherwise. ## Response envelope - Successful responses are `{ "data": ... }`, with `meta.page` added on paginated endpoints. + Successful JSON responses are `{ "data": ... }`, with `meta.page` added on paginated endpoints. The generation endpoint returns a PDF attachment. Failed responses are `{ "errors": [ { status, title, detail?, source? } ] }`. Note that request-validation failures are sent with **HTTP 400** while each error's `status` field says `"422"`. @@ -51,6 +51,11 @@ tags: description: Data used to fill end-of-shift reports. - name: Simulation passes description: Monte Carlo simulation productions. + - name: Templates + description: Presentation templates, each an ordered list of content modules, read by the ALICE Insights generation service. + + - name: Presentations + description: On-demand PDF generation for signed-in Bookkeeping users. paths: /tags: @@ -522,6 +527,107 @@ paths: errors: - { status: 404, title: Not found, detail: Simulation pass with this id (99999) could not be found } + /templates: + get: + tags: [Templates] + operationId: listTemplates + summary: List presentation templates + description: | + Returns the presentation templates ordered by title, without their modules. Not paginated: there are few templates. Pagination parameters + are rejected. + responses: + '200': + description: The templates. + content: + application/json: + schema: { $ref: '#/components/schemas/TemplateListResponse' } + example: + data: + - id: 2 + name: lhc-fill-summary + title: LHC Fill Summary + description: A short summary of the LHC fills of the period and how efficiently their stable beams were used. + '400': { $ref: '#/components/responses/ValidationError' } + + /templates/{templateId}: + get: + tags: [Templates] + operationId: getTemplate + summary: Get a presentation template by id, with its modules + parameters: + - name: templateId + in: path + required: true + description: Template identifier. + schema: { type: integer, minimum: 1 } + responses: + '200': + description: The template, with its modules in presentation order. + content: + application/json: + schema: { $ref: '#/components/schemas/TemplateResponse' } + example: + data: + id: 2 + name: lhc-fill-summary + title: LHC Fill Summary + description: A short summary of the LHC fills of the period and how efficiently their stable beams were used. + modules: + - { position: 0, type: title-slide, title: LHC Fill Summary, options: {} } + - { position: 1, type: fill-calendar, title: Fills and runs, options: { run_definitions: [PHYSICS] } } + - { position: 2, type: fill-efficiency, title: Fill efficiencies, options: { run_definitions: [PHYSICS] } } + '400': { $ref: '#/components/responses/ValidationError' } + '404': + description: No template has this id. + content: + application/json: + schema: { $ref: '#/components/schemas/ErrorResponse' } + example: + errors: + - { status: 404, title: Not found, detail: Template with this id (999999) could not be found } + + /presentations: + post: + tags: [Presentations] + operationId: generatePresentation + summary: Generate a presentation PDF + x-llm-exclude: false + description: | + Generates a PDF from a template and reporting period. Bookkeeping uses the authenticated user's name as the author and forwards + their token to ALICE Insights. The reporting period includes its start and excludes its end. + requestBody: + required: true + content: + application/json: + schema: + type: object + additionalProperties: false + required: [templateId, from, to] + properties: + templateId: { type: integer, minimum: 1, description: The ID returned by GET /templates. } + from: { type: integer, minimum: 0, description: Inclusive start in Unix milliseconds. } + to: { type: integer, minimum: 0, description: Exclusive end in Unix milliseconds. Must be greater than from. } + example: { templateId: 1, from: 1794783600000, to: 1795388400000 } + responses: + '200': + description: PDF attachment. The Content-Disposition header contains the filename. + headers: + Content-Disposition: + schema: { type: string } + content: + application/pdf: + schema: { type: string, format: binary } + '400': { $ref: '#/components/responses/ValidationError' } + '401': { description: A valid Bookkeeping user session is required. } + '422': { description: ALICE Insights rejected the template or period. } + '502': { description: The generation service could not return a PDF. } + '503': + description: Generation is unavailable or busy. A busy response can include Retry-After in seconds. + headers: + Retry-After: + schema: { type: integer, minimum: 0 } + '504': { description: The generation service took too long to return a PDF. } + components: securitySchemes: jwtQuery: @@ -819,3 +925,35 @@ components: type: array items: { $ref: '#/components/schemas/SimulationPass' } meta: { $ref: '#/components/schemas/PageMeta' } + TemplateModule: + type: object + required: [position, type, title, options] + properties: + position: { type: integer, description: 'Position of the module in the presentation, starting at 0.' } + type: { type: string, description: 'Type of the module, as known by the generation service, e.g. `fill-efficiency`.' } + title: { type: string, nullable: true, description: Title of the module's slides. } + options: { type: object, additionalProperties: true, description: Settings of the module. } + Template: + type: object + required: [id, name, title, description] + properties: + id: { type: integer } + name: { type: string, description: 'Unique name of the template, e.g. `run-manager-weekly-report`.' } + title: { type: string, description: Title of the presentations made with the template. } + description: { type: string, nullable: true } + modules: + type: array + description: Modules in presentation order. Only returned when getting a single template. + items: { $ref: '#/components/schemas/TemplateModule' } + TemplateResponse: + type: object + required: [data] + properties: + data: { $ref: '#/components/schemas/Template' } + TemplateListResponse: + type: object + required: [data] + properties: + data: + type: array + items: { $ref: '#/components/schemas/Template' } diff --git a/lib/server/controllers/index.js b/lib/server/controllers/index.js index 48184378b2..e9fc019534 100644 --- a/lib/server/controllers/index.js +++ b/lib/server/controllers/index.js @@ -18,10 +18,12 @@ const EnvironmentsController = require('./environments.controller'); const FlpsController = require('./flps.controller'); const LhcFillsController = require('./lhcFill.controller'); const LogsController = require('./logs.controller'); +const PresentationsController = require('./presentations.controller.js'); const RunTypesController = require('./runTypes.controller'); const RunsController = require('./runs.controller'); const StatusController = require('./status.controller'); const TagsController = require('./tags.controller'); +const TemplatesController = require('./templates.controller.js'); const CtpTriggerCountersController = require('./ctpTriggerCounters.controller'); module.exports = { @@ -32,9 +34,11 @@ module.exports = { FlpsController, LhcFillsController, LogsController, + PresentationsController, RunTypesController, RunsController, StatusController, TagsController, + TemplatesController, CtpTriggerCountersController, }; diff --git a/lib/server/controllers/presentations.controller.js b/lib/server/controllers/presentations.controller.js new file mode 100644 index 0000000000..0427e302d1 --- /dev/null +++ b/lib/server/controllers/presentations.controller.js @@ -0,0 +1,51 @@ +/** + * @license + * Copyright CERN and copyright holders of ALICE O2. This software is + * distributed under the terms of the GNU General Public License v3 (GPL + * Version 3), copied verbatim in the file "COPYING". + * + * See http://alice-o2.web.cern.ch/license for full licensing information. + * + * In applying this license CERN does not waive the privileges and immunities + * granted to it by virtue of its status as an Intergovernmental Organization + * or submit itself to any jurisdiction. + */ + +const { dtos: { CreatePresentationDto } } = require('../../domain'); +const { dtoValidator } = require('../utilities'); +const { generatePresentation } = require('../services/presentation/generatePresentation.js'); + +/** + * Generate a PDF using the signed-in user's Bookkeeping identity. + * + * @param {object} request The HTTP request. + * @param {object} response The HTTP response. + * @returns {Promise} Resolves once the response has been sent. + */ +exports.createPresentation = async (request, response) => { + response.set('Cache-Control', 'no-store'); + const { token } = request.query; + const author = request.session?.name?.trim(); + if (typeof token !== 'string' || !token || !request.session?.username || !author) { + response.status(401).json({ + errors: [{ status: 401, title: 'Sign-in required', detail: 'Sign in to Bookkeeping to generate a presentation.' }], + }); + return; + } + + const value = await dtoValidator(CreatePresentationDto, request, response); + if (!value) { + return; + } + + const { status, pdf, filename, title, detail, retryAfter } = await generatePresentation(value.body, author, token); + if (status === 200) { + response.attachment(filename).send(pdf); + return; + } + + if (retryAfter) { + response.set('Retry-After', retryAfter); + } + response.status(status).json({ errors: [{ status, title, detail }] }); +}; diff --git a/lib/server/controllers/templates.controller.js b/lib/server/controllers/templates.controller.js new file mode 100644 index 0000000000..66da847091 --- /dev/null +++ b/lib/server/controllers/templates.controller.js @@ -0,0 +1,66 @@ +/** + * @license + * Copyright CERN and copyright holders of ALICE O2. This software is + * distributed under the terms of the GNU General Public License v3 (GPL + * Version 3), copied verbatim in the file "COPYING". + * + * See http://alice-o2.web.cern.ch/license for full licensing information. + * + * In applying this license CERN does not waive the privileges and immunities + * granted to it by virtue of its status as an Intergovernmental Organization + * or submit itself to any jurisdiction. + */ + +const { dtos: { GetAllTemplatesDto, GetTemplateDto } } = require('../../domain'); +const { dtoValidator } = require('../utilities'); +const { templateService } = require('../services/template/TemplateService.js'); +const { updateExpressResponseFromNativeError } = require('../express/updateExpressResponseFromNativeError.js'); + +/** + * Get all templates. + * + * @param {Object} request The *request* object represents the HTTP request and has properties for the request query + * string, parameters, body, HTTP headers, and so on. + * @param {Object} response The *response* object represents the HTTP response that an Express app sends when it gets an + * HTTP request. + * @returns {undefined} + */ +const listTemplates = async (request, response) => { + const value = await dtoValidator(GetAllTemplatesDto, request, response); + if (!value) { + return; + } + + try { + response.status(200).json({ data: await templateService.getAll() }); + } catch (error) { + updateExpressResponseFromNativeError(response, error); + } +}; + +/** + * Get a template with its modules. + * + * @param {Object} request The *request* object represents the HTTP request and has properties for the request query + * string, parameters, body, HTTP headers, and so on. + * @param {Object} response The *response* object represents the HTTP response that an Express app sends when it gets an + * HTTP request. + * @returns {undefined} + */ +const getTemplateById = async (request, response) => { + const value = await dtoValidator(GetTemplateDto, request, response); + if (!value) { + return; + } + + try { + response.status(200).json({ data: await templateService.getOneOrFail(value.params.templateId) }); + } catch (error) { + updateExpressResponseFromNativeError(response, error); + } +}; + +module.exports = { + listTemplates, + getTemplateById, +}; diff --git a/lib/server/routers/index.js b/lib/server/routers/index.js index b3952aa86a..f91157bddc 100644 --- a/lib/server/routers/index.js +++ b/lib/server/routers/index.js @@ -23,12 +23,14 @@ const flpsRoute = require('./flps.router'); const { gaqDetectorsRouter } = require('./gaqDetectors.router.js'); const lhcFillRoute = require('./lhcFills.router'); const logRoute = require('./logs.router'); +const presentationsRoute = require('./presentations.router.js'); const runTypesRoute = require('./runTypes.router'); const runsRoute = require('./runs.router'); const { shiftRouter } = require('./shift.router.js'); const { statisticsRouter } = require('./statistics.router.js'); const statusRoute = require('./status.router'); const tagsRoute = require('./tags.router'); +const templatesRoute = require('./templates.router.js'); const { lhcPeriodsRouter } = require('./lhcPeriodsStatistics.router.js'); const { isInTestMode } = require('../../utilities/env-utils'); const { dataPassesRouter } = require('./dataPasses.router'); @@ -51,6 +53,7 @@ const routes = [ lhcFillRoute, lhcPeriodsRouter, logRoute, + presentationsRoute, qcFlagTypesRouter, qcFlagsRouter, runTypesRoute, @@ -60,6 +63,7 @@ const routes = [ statisticsRouter, statusRoute, tagsRoute, + templatesRoute, ctpTriggerCountersRouter, ]; diff --git a/lib/server/routers/presentations.router.js b/lib/server/routers/presentations.router.js new file mode 100644 index 0000000000..db643e1b50 --- /dev/null +++ b/lib/server/routers/presentations.router.js @@ -0,0 +1,20 @@ +/** + * @license + * Copyright CERN and copyright holders of ALICE O2. This software is + * distributed under the terms of the GNU General Public License v3 (GPL + * Version 3), copied verbatim in the file "COPYING". + * + * See http://alice-o2.web.cern.ch/license for full licensing information. + * + * In applying this license CERN does not waive the privileges and immunities + * granted to it by virtue of its status as an Intergovernmental Organization + * or submit itself to any jurisdiction. + */ + +const { PresentationsController } = require('../controllers'); + +module.exports = { + path: '/presentations', + method: 'post', + controller: PresentationsController.createPresentation, +}; diff --git a/lib/server/routers/templates.router.js b/lib/server/routers/templates.router.js new file mode 100644 index 0000000000..9b5a5310d9 --- /dev/null +++ b/lib/server/routers/templates.router.js @@ -0,0 +1,33 @@ +/** + * @license + * Copyright CERN and copyright holders of ALICE O2. This software is + * distributed under the terms of the GNU General Public License v3 (GPL + * Version 3), copied verbatim in the file "COPYING". + * + * See http://alice-o2.web.cern.ch/license for full licensing information. + * + * In applying this license CERN does not waive the privileges and immunities + * granted to it by virtue of its status as an Intergovernmental Organization + * or submit itself to any jurisdiction. + */ + +const { TemplatesController } = require('../controllers'); + +module.exports = { + path: '/templates', + children: [ + { + method: 'get', + controller: TemplatesController.listTemplates, + }, + { + path: ':templateId', + children: [ + { + method: 'get', + controller: TemplatesController.getTemplateById, + }, + ], + }, + ], +}; diff --git a/lib/server/services/presentation/generatePresentation.js b/lib/server/services/presentation/generatePresentation.js new file mode 100644 index 0000000000..a9415cfdda --- /dev/null +++ b/lib/server/services/presentation/generatePresentation.js @@ -0,0 +1,100 @@ +/** + * @license + * Copyright CERN and copyright holders of ALICE O2. This software is + * distributed under the terms of the GNU General Public License v3 (GPL + * Version 3), copied verbatim in the file "COPYING". + * + * See http://alice-o2.web.cern.ch/license for full licensing information. + * + * In applying this license CERN does not waive the privileges and immunities + * granted to it by virtue of its status as an Intergovernmental Organization + * or submit itself to any jurisdiction. + */ + +const { ServicesConfig } = require('../../../config'); + +const generationTimeout = 120_000; +const upstreamErrors = { + 401: { title: 'Session expired', detail: 'Sign in to Bookkeeping again and retry.' }, + 422: { title: 'Invalid presentation', detail: 'Check the selected template and period and try again.' }, + 502: { title: 'Data unavailable', detail: 'The generation service could not get the data for this presentation.' }, + 503: { title: 'Generation busy', detail: 'A presentation is already being made. Try again shortly.' }, +}; +const unavailable = { + status: 502, + title: 'Generation failed', + detail: 'The generation service could not return a PDF. Try again later.', +}; + +/** + * Send a request to ALICE Insights and return a PDF or a safe error for the caller. + * + * @param {object} selection The validated template and period. + * @param {number} selection.templateId The selected template ID. + * @param {number} selection.from Inclusive start of the reporting period in UTC milliseconds. + * @param {number} selection.to Exclusive end of the reporting period in UTC milliseconds. + * @param {string} author The signed-in user's name. + * @param {string} token The signed-in user's Bookkeeping token. + * @returns {Promise} The PDF download or the response status, title and detail. + */ +exports.generatePresentation = async ({ templateId, from, to }, author, token) => { + const { url } = ServicesConfig.aliceInsights; + if (!url) { + return { + status: 503, + title: 'Generation unavailable', + detail: 'Presentation generation is not configured for this Bookkeeping server.', + }; + } + + try { + const response = await fetch(new URL('/presentations', url), { + method: 'POST', + headers: { + Accept: 'application/pdf', + 'Content-Type': 'application/json', + Authorization: `Bearer ${token}`, + }, + body: JSON.stringify({ templateId: String(templateId), from, to, author }), + redirect: 'error', + signal: AbortSignal.timeout(generationTimeout), + }); + + if (response.status !== 200) { + await response.body?.cancel(); + const error = upstreamErrors[response.status]; + if (!error) { + return unavailable; + } + const retryAfter = response.headers.get('retry-after'); + return { + status: response.status, + ...error, + retryAfter: response.status === 503 && /^\d+$/.test(retryAfter) ? retryAfter : null, + }; + } + + if (response.headers.get('content-type')?.split(';', 1)[0].trim().toLowerCase() !== 'application/pdf') { + await response.body?.cancel(); + return unavailable; + } + + const pdf = Buffer.from(await response.arrayBuffer()); + if (pdf.subarray(0, 5).toString('latin1') !== '%PDF-') { + return unavailable; + } + + const disposition = response.headers.get('content-disposition'); + const filename = disposition?.match(/^attachment;\s*filename="([a-z0-9][a-z0-9._-]*\.pdf)"$/i)?.[1] ?? 'presentation.pdf'; + return { status: 200, pdf, filename }; + } catch (error) { + if (error.name === 'TimeoutError' || error.name === 'AbortError') { + return { + status: 504, + title: 'Generation timed out', + detail: 'The generation service took too long to finish. Try again later.', + }; + } + return unavailable; + } +}; diff --git a/lib/server/services/template/TemplateService.js b/lib/server/services/template/TemplateService.js new file mode 100644 index 0000000000..6a5c9798ef --- /dev/null +++ b/lib/server/services/template/TemplateService.js @@ -0,0 +1,46 @@ +/** + * @license + * Copyright CERN and copyright holders of ALICE O2. This software is + * distributed under the terms of the GNU General Public License v3 (GPL + * Version 3), copied verbatim in the file "COPYING". + * + * See http://alice-o2.web.cern.ch/license for full licensing information. + * + * In applying this license CERN does not waive the privileges and immunities + * granted to it by virtue of its status as an Intergovernmental Organization + * or submit itself to any jurisdiction. + */ + +const { templateAdapter } = require('../../../database/adapters/index.js'); +const { getAllTemplates } = require('./getAllTemplates.js'); +const { getTemplateOrFail } = require('./getTemplateOrFail.js'); + +/** + * Global service to read presentation templates + */ +class TemplateService { + /** + * Return the templates sorted by title, without their modules + * + * Templates are not paginated, as there are only a few of them + * + * @return {Promise} the templates + */ + async getAll() { + return (await getAllTemplates()).map(templateAdapter.toEntity); + } + + /** + * Return the template with the given id, with its modules in presentation order, or reject if there is none + * + * @param {number} id the id of the template to find + * @return {Promise