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..06f1f021bc 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 dates and times of the period are Geneva time, whatever the time zone of the browser. 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/PresentationTemplateAdapter.js b/lib/database/adapters/PresentationTemplateAdapter.js new file mode 100644 index 0000000000..de8fe01b10 --- /dev/null +++ b/lib/database/adapters/PresentationTemplateAdapter.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 presentation templates + */ +class PresentationTemplateAdapter { + /** + * Constructor + */ + constructor() { + this.toEntity = this.toEntity.bind(this); + + /** + * @type {PresentationTemplateModuleAdapter|null} + */ + this.presentationTemplateModuleAdapter = null; + } + + /** + * Converts the given database object to an entity object. + * + * @param {SequelizePresentationTemplate} databaseObject Object to convert. + * @returns {PresentationTemplate} Converted entity object. + */ + toEntity({ id, name, title, description, modules }) { + const entityObject = { + id, + name, + title, + description, + }; + + if (modules) { + entityObject.modules = modules.map(this.presentationTemplateModuleAdapter.toEntity); + } + + return entityObject; + } +} + +module.exports = PresentationTemplateAdapter; diff --git a/lib/database/adapters/PresentationTemplateModuleAdapter.js b/lib/database/adapters/PresentationTemplateModuleAdapter.js new file mode 100644 index 0000000000..d05b141f71 --- /dev/null +++ b/lib/database/adapters/PresentationTemplateModuleAdapter.js @@ -0,0 +1,39 @@ +/** + * @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 the modules of presentation templates + */ +class PresentationTemplateModuleAdapter { + /** + * Constructor + */ + constructor() { + this.toEntity = this.toEntity.bind(this); + } + + /** + * Converts the given database object to an entity object. + * + * @param {SequelizePresentationTemplateModule} databaseObject Object to convert. + * @returns {PresentationTemplateModule} Converted entity object. + */ + toEntity({ position, type, title }) { + return { + position, + type, + title, + }; + } +} + +module.exports = PresentationTemplateModuleAdapter; diff --git a/lib/database/adapters/index.js b/lib/database/adapters/index.js index 433a4febeb..7dba698720 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 PresentationTemplateAdapter = require('./PresentationTemplateAdapter.js'); +const PresentationTemplateModuleAdapter = require('./PresentationTemplateModuleAdapter.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 presentationTemplateAdapter = new PresentationTemplateAdapter(); +const presentationTemplateModuleAdapter = new PresentationTemplateModuleAdapter(); const ctpTriggerCountersAdapter = new CtpTriggerCountersAdapter(); const userAdapter = new UserAdapter(); @@ -144,6 +148,7 @@ runAdapter.tagAdapter = tagAdapter; runAdapter.userAdapter = userAdapter; tagAdapter.userAdapter = userAdapter; +presentationTemplateAdapter.presentationTemplateModuleAdapter = presentationTemplateModuleAdapter; runAdapter.qcFlagAdapter = qcFlagAdapter; simulationPassQcFlagAdapter.simulationPassAdapter = simulationPassAdapter; @@ -183,6 +188,8 @@ module.exports = { simulationPassAdapter, simulationPassQcFlagAdapter, tagAdapter, + presentationTemplateAdapter, + presentationTemplateModuleAdapter, ctpTriggerCountersAdapter, userAdapter, }; diff --git a/lib/database/migrations/v1/20261028100000-create-presentation-templates.js b/lib/database/migrations/v1/20261028100000-create-presentation-templates.js new file mode 100644 index 0000000000..457cf925f1 --- /dev/null +++ b/lib/database/migrations/v1/20261028100000-create-presentation-templates.js @@ -0,0 +1,101 @@ +/** + * @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('presentation_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('presentation_template_modules', { + id: { + allowNull: false, + autoIncrement: true, + primaryKey: true, + type: Sequelize.INTEGER, + }, + presentation_template_id: { + allowNull: false, + type: Sequelize.INTEGER, + references: { model: 'presentation_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), + }, + 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('presentation_template_modules', { + fields: ['presentation_template_id', 'position'], + type: 'unique', + name: 'presentation_template_modules_position', + transaction, + }); + }), + + down: async (queryInterface) => queryInterface.sequelize.transaction(async (transaction) => { + await queryInterface.dropTable('presentation_template_modules', { transaction }); + await queryInterface.dropTable('presentation_templates', { transaction }); + }), +}; diff --git a/lib/database/models/index.js b/lib/database/models/index.js index 87d793fac3..7f31fb8555 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 PresentationTemplate = require('./presentationTemplate.js'); +const PresentationTemplateModule = require('./presentationTemplateModule.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), + PresentationTemplate: PresentationTemplate(sequelize), + PresentationTemplateModule: PresentationTemplateModule(sequelize), CtpTriggerCounters: CtpTriggerCounters(sequelize), User: User(sequelize), }; diff --git a/lib/database/models/presentationTemplate.js b/lib/database/models/presentationTemplate.js new file mode 100644 index 0000000000..a8ee6d08e2 --- /dev/null +++ b/lib/database/models/presentationTemplate.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 PresentationTemplate = sequelize.define('PresentationTemplate', { + name: { + allowNull: false, + unique: true, + type: Sequelize.STRING(64), + }, + title: { + allowNull: false, + type: Sequelize.STRING(255), + }, + description: { + allowNull: true, + type: Sequelize.TEXT, + }, + }); + + PresentationTemplate.associate = (models) => { + PresentationTemplate.hasMany(models.PresentationTemplateModule, { + as: 'modules', + foreignKey: 'presentationTemplateId', + }); + }; + + return PresentationTemplate; +}; diff --git a/lib/database/models/presentationTemplateModule.js b/lib/database/models/presentationTemplateModule.js new file mode 100644 index 0000000000..35b8df38e7 --- /dev/null +++ b/lib/database/models/presentationTemplateModule.js @@ -0,0 +1,44 @@ +/** + * @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 PresentationTemplateModule = sequelize.define('PresentationTemplateModule', { + presentationTemplateId: { + 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), + }, + }); + + PresentationTemplateModule.associate = (models) => { + PresentationTemplateModule.belongsTo(models.PresentationTemplate, { + as: 'presentationTemplate', + foreignKey: 'presentationTemplateId', + }); + }; + + return PresentationTemplateModule; +}; diff --git a/lib/database/models/typedefs/SequelizePresentationTemplate.js b/lib/database/models/typedefs/SequelizePresentationTemplate.js new file mode 100644 index 0000000000..b4bf05ffa0 --- /dev/null +++ b/lib/database/models/typedefs/SequelizePresentationTemplate.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 SequelizePresentationTemplate + * + * @property {number} id + * @property {string} name + * @property {string} title + * @property {string|null} description + * @property {SequelizePresentationTemplateModule[]} [modules] + * @property {string} createdAt + * @property {string} updatedAt + */ diff --git a/lib/database/models/typedefs/SequelizePresentationTemplateModule.js b/lib/database/models/typedefs/SequelizePresentationTemplateModule.js new file mode 100644 index 0000000000..eae4c96572 --- /dev/null +++ b/lib/database/models/typedefs/SequelizePresentationTemplateModule.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 SequelizePresentationTemplateModule + * + * @property {number} id + * @property {number} presentationTemplateId + * @property {number} position + * @property {string} type + * @property {string|null} title + * @property {string} createdAt + * @property {string} updatedAt + */ diff --git a/lib/database/repositories/PresentationTemplateRepository.js b/lib/database/repositories/PresentationTemplateRepository.js new file mode 100644 index 0000000000..ee9aa887ee --- /dev/null +++ b/lib/database/repositories/PresentationTemplateRepository.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: { + PresentationTemplate, + }, +} = require('../'); +const Repository = require('./Repository'); + +/** + * Sequelize implementation of the PresentationTemplateRepository. + */ +class PresentationTemplateRepository extends Repository { + /** + * Creates a new `PresentationTemplateRepository` instance. + */ + constructor() { + super(PresentationTemplate); + } +} + +module.exports = new PresentationTemplateRepository(); diff --git a/lib/database/repositories/index.js b/lib/database/repositories/index.js index 53673cc9c1..8526c0d6a5 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 PresentationTemplateRepository = require('./PresentationTemplateRepository.js'); const CtpTriggerCountersRepository = require('./CtpTriggerCountersRepository'); const UserRepository = require('./UserRepository'); @@ -97,6 +98,7 @@ module.exports = { SimulationPassQcFlagRepository, StableBeamRunsRepository, TagRepository, + PresentationTemplateRepository, CtpTriggerCountersRepository, UserRepository, }; diff --git a/lib/database/seeders/20261028100000-presentation-templates.js b/lib/database/seeders/20261028100000-presentation-templates.js new file mode 100644 index 0000000000..831845be06 --- /dev/null +++ b/lib/database/seeders/20261028100000-presentation-templates.js @@ -0,0 +1,47 @@ +/** + * @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'; + +module.exports = { + up: async (queryInterface) => + queryInterface.sequelize.transaction(async (transaction) => { + await queryInterface.bulkInsert('presentation_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('presentation_template_modules', [ + { presentation_template_id: 1, position: 0, type: 'title-slide', title: 'Run Manager Weekly Report' }, + { presentation_template_id: 1, position: 1, type: 'fill-calendar', title: 'Fills and runs' }, + { presentation_template_id: 1, position: 2, type: 'fill-efficiency', title: 'Fill efficiencies' }, + { presentation_template_id: 1, position: 3, type: 'running-time', title: 'Running time' }, + { presentation_template_id: 1, position: 4, type: 'eor-reasons', title: 'End of Run reasons' }, + { presentation_template_id: 2, position: 0, type: 'title-slide', title: 'LHC Fill Summary' }, + { presentation_template_id: 2, position: 1, type: 'fill-calendar', title: 'Fills and runs' }, + { presentation_template_id: 2, position: 2, type: 'fill-efficiency', title: 'Fill efficiencies' }, + ], { transaction }); + }), + down: async (queryInterface) => + queryInterface.sequelize.transaction((transaction) => + Promise.all([queryInterface.bulkDelete('presentation_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/GetAllPresentationTemplatesDto.js b/lib/domain/dtos/GetAllPresentationTemplatesDto.js new file mode 100644 index 0000000000..a6fb6a2ed3 --- /dev/null +++ b/lib/domain/dtos/GetAllPresentationTemplatesDto.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 GetAllPresentationTemplatesDto = Joi.object({ + body: Joi.object({}), + params: Joi.object({}), + query: QueryDto, +}); + +module.exports = GetAllPresentationTemplatesDto; diff --git a/lib/domain/dtos/GetPresentationTemplateDto.js b/lib/domain/dtos/GetPresentationTemplateDto.js new file mode 100644 index 0000000000..96a864af5b --- /dev/null +++ b/lib/domain/dtos/GetPresentationTemplateDto.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({ + presentationTemplateId: EntityIdDto, +}); + +const QueryDto = Joi.object({ + token: Joi.string(), +}); + +const GetPresentationTemplateDto = Joi.object({ + body: Joi.object({}), + params: ParamsDto, + query: QueryDto, +}); + +module.exports = GetPresentationTemplateDto; diff --git a/lib/domain/dtos/index.js b/lib/domain/dtos/index.js index 01eb348934..4a489bdcb0 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 GetAllPresentationTemplatesDto = require('./GetAllPresentationTemplatesDto.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 GetPresentationTemplateDto = require('./GetPresentationTemplateDto.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, + GetAllPresentationTemplatesDto, GetAllFlpsDto, GetAttachmentDto, GetEnvironmentDto, @@ -75,6 +80,7 @@ module.exports = { StartRunDto, GetTagByNameDto, GetTagDto, + GetPresentationTemplateDto, GetFlpDto, PaginationDto, UpdateEnvironmentDto, diff --git a/lib/domain/entities/PresentationTemplate.js b/lib/domain/entities/PresentationTemplate.js new file mode 100644 index 0000000000..9c0133bc15 --- /dev/null +++ b/lib/domain/entities/PresentationTemplate.js @@ -0,0 +1,30 @@ +/** + * @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 PresentationTemplateModule + * + * @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 + */ + +/** + * @typedef PresentationTemplate + * + * @property {number} id + * @property {string} name the unique name of the presentation template + * @property {string} title the title of the presentations made with the template + * @property {string|null} description + * @property {PresentationTemplateModule[]} [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/Filters/common/filters/timeRangeFilter.js b/lib/public/components/Filters/common/filters/timeRangeFilter.js index 762805b72a..71fb0c27d8 100644 --- a/lib/public/components/Filters/common/filters/timeRangeFilter.js +++ b/lib/public/components/Filters/common/filters/timeRangeFilter.js @@ -130,13 +130,18 @@ export const timeRangeFilter = (timeRangeFilterModel) => DropdownComponent( step: 1, min: 1, max: getWeeksCount(), - onchange: (e) => timeRangeFilterModel.setValue( - { - from: getStartOfWeek(e.target.value).getTime(), - to: getStartOfWeek(parseInt(e.target.value, 10) + 1).getTime(), - }, - `Week ${e.target.value}`, - ), + onchange: (e) => { + // An emptied field is no week, so the period stays as it is + if (e.target.value !== '') { + timeRangeFilterModel.setValue( + { + from: getStartOfWeek(e.target.value).getTime(), + to: getStartOfWeek(parseInt(e.target.value, 10) + 1).getTime(), + }, + `Week ${e.target.value}`, + ); + } + }, }), ], ), 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/utilities/dateUtils.mjs b/lib/public/utilities/dateUtils.mjs index e7ff63dcd9..17518f8030 100644 --- a/lib/public/utilities/dateUtils.mjs +++ b/lib/public/utilities/dateUtils.mjs @@ -128,7 +128,7 @@ export const getStartOfWeek = (week, year) => { const startOfYear = getStartOfYear(year); // 0 is Sunday, but we want it to be Monday, so cycle every indices by -1 (add 7 before removing 1 then modulo 7 to avoid negatives) - const weekDay = (startOfYear.getDay() + 6) % 7; + const weekDay = (startOfYear.getUTCDay() + 6) % 7; /* * Week 1 of the year is the first week that includes the **first Thursday of the year**. 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..4a385e5159 --- /dev/null +++ b/lib/public/views/Presentations/PresentationsPage.js @@ -0,0 +1,85 @@ +/** + * @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, +}); + +const explanation = () => h( + 'p.mv0#presentations-explanation', + 'Choose a period and a template to generate a presentation as a PDF. A presentation covers every LHC fill with ' + + 'stable beams in the period. Each fill is shown in full, with all its PHYSICS runs, so the slides can include ' + + 'time before and after the period.', +); + +/** + * 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'), + explanation(), + 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 ', h('span.gray-darker#presentation-period-time-zone', '(Geneva time)')]), + 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..f1825e69d2 --- /dev/null +++ b/lib/public/views/Presentations/PresentationsPageModel.js @@ -0,0 +1,210 @@ +/** + * @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'; +import { asGenevaTime, utcClockAsLocalTime } from './genevaTime.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.observe(() => this._handlePeriodChange()); + 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/presentationTemplates'); + 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._discardResult(); + this.notify(); + } + + /** + * Return the selected time bounds as Unix milliseconds. + * + * The dates and times of the period picker are Geneva time for every user, whatever the time zone of the browser. + * @return {Period} the chosen period + */ + get period() { + const { value: from } = this.timeRangeModel.fromTimeInputModel; + const { value: to } = this.timeRangeModel.toTimeInputModel; + return { from: from === null ? null : asGenevaTime(from), to: to === null ? null : asGenevaTime(to) }; + } + + /** + * 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(); + } + + /** + * Show a predefined period, such as a week, as whole days, and discard the result of another period. + * + * The predefined periods of the period picker start and end at midnight in UTC, and the picker shows a moment on the + * browser's clock. The period is moved to the same dates and times on that clock, so a week runs from Monday 00:00 up + * to the next Monday 00:00 for every user. + * @return {void} + */ + _handlePeriodChange() { + if (this.timeRangeModel.periodLabel !== null) { + const { value: from } = this.timeRangeModel.fromTimeInputModel; + const { value: to } = this.timeRangeModel.toTimeInputModel; + this.timeRangeModel.setValue({ from: utcClockAsLocalTime(from), to: utcClockAsLocalTime(to) }, null, true); + } + this._discardResult(); + } + + /** + * Discard a finished result, which belongs to the template and the period it was requested for. + * @return {void} + */ + _discardResult() { + if (!this.isGenerating) { + 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/public/views/Presentations/genevaTime.js b/lib/public/views/Presentations/genevaTime.js new file mode 100644 index 0000000000..535c70cb12 --- /dev/null +++ b/lib/public/views/Presentations/genevaTime.js @@ -0,0 +1,84 @@ +/** + * @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 GENEVA_TIME_ZONE = 'Europe/Zurich'; + +const genevaClock = new Intl.DateTimeFormat('en-GB', { + timeZone: GENEVA_TIME_ZONE, + hourCycle: 'h23', + year: 'numeric', + month: 'numeric', + day: 'numeric', + hour: 'numeric', + minute: 'numeric', + second: 'numeric', +}); + +/** + * Return how far the clocks in Geneva are ahead of UTC at a given moment + * + * @param {number} timestamp the moment, as a UNIX timestamp in milliseconds + * @return {number} the difference in milliseconds + */ +const getGenevaOffset = (timestamp) => { + const parts = Object.fromEntries(genevaClock.formatToParts(new Date(timestamp)).map(({ type, value }) => [type, Number(value)])); + const shownAsUtc = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second); + return shownAsUtc - Math.floor(timestamp / 1000) * 1000; +}; + +/** + * Return the moment at which the clocks in Geneva show the date and time that the browser's clock shows at the given moment + * + * The period picker works in the time zone of the browser. With this function, the dates and times a user picks mean Geneva + * time for every user, whatever the time zone of their computer. + * + * @param {number} timestamp the picked moment, as a UNIX timestamp in milliseconds + * @return {number} the moment in Geneva time, as a UNIX timestamp in milliseconds + */ +export const asGenevaTime = (timestamp) => { + const picked = new Date(timestamp); + const pickedAsUtc = Date.UTC( + picked.getFullYear(), + picked.getMonth(), + picked.getDate(), + picked.getHours(), + picked.getMinutes(), + picked.getSeconds(), + picked.getMilliseconds(), + ); + // The difference with UTC is taken at the result, as it changes when the clocks in Geneva go forward or back + const firstGuess = pickedAsUtc - getGenevaOffset(pickedAsUtc); + return pickedAsUtc - getGenevaOffset(firstGuess); +}; + +/** + * Return the moment at which the browser's clock shows the date and time that a UTC clock shows at the given moment + * + * The predefined periods of the period picker, such as a week or a month, start and end at midnight in UTC. With this function, + * the picker shows them from midnight to midnight for every user. + * + * @param {number} timestamp the moment, as a UNIX timestamp in milliseconds + * @return {number} the moment with the same date and time on the browser's clock, as a UNIX timestamp in milliseconds + */ +export const utcClockAsLocalTime = (timestamp) => { + const utc = new Date(timestamp); + return new Date( + utc.getUTCFullYear(), + utc.getUTCMonth(), + utc.getUTCDate(), + utc.getUTCHours(), + utc.getUTCMinutes(), + utc.getUTCSeconds(), + utc.getUTCMilliseconds(), + ).getTime(); +}; diff --git a/lib/server/api-docs/API.md b/lib/server/api-docs/API.md index 70a34d614f..1df60db891 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" ``` + +## Presentation templates + +Presentation templates, each an ordered list of content modules, read by the ALICE Insights generation service. + +### `GET /presentationTemplates` - List presentation templates + +Operation id: `listPresentationTemplates` + +Returns the presentation templates ordered by title, without their modules. Not paginated: there are few presentation templates. Pagination parameters +are rejected. + +Responses: + +- `200`: The presentation 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/presentationTemplates?token=$TOKEN" +``` + +### `GET /presentationTemplates/{presentationTemplateId}` - Get a presentation template by id, with its modules + +Operation id: `getPresentationTemplate` + +| Parameter | In | Type | Required | Notes | +| --- | --- | --- | --- | --- | +| `presentationTemplateId` | path | integer | yes | Presentation template identifier. | + +Responses: + +- `200`: The presentation 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 presentation template has this id. + +```bash +curl -g "$BOOKKEEPING_URL/api/presentationTemplates/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 /presentationTemplates. | +| `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. The detail of this and every other error of ALICE Insights is the sentence with which it explains why. +- `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..a492e32534 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"
 
+

Presentation templates

+

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

+
+

GET /presentationTemplates - List presentation templates

+ +

Operation id: listPresentationTemplates

+

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

+

Responses:

+
    +
  • 200: The presentation 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/presentationTemplates?token=$TOKEN"
+
+
+
+

GET /presentationTemplates/{presentationTemplateId} - Get a presentation template by id, with its modules

+ +

Operation id: getPresentationTemplate

+ + + + + + + + + + + + + + + + + +
ParameterInTypeRequiredNotes
presentationTemplateIdpathintegeryesPresentation template identifier.
+

Responses:

+
    +
  • 200: The presentation 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 presentation template has this id.
  • +
+
curl -g "$BOOKKEEPING_URL/api/presentationTemplates/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 /presentationTemplates.
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. The detail of this and every other error of ALICE Insights is the sentence with which it explains why.
  • +
  • 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..5a6f425ae8 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: Presentation 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 } + /presentationTemplates: + get: + tags: [Presentation templates] + operationId: listPresentationTemplates + summary: List presentation templates + description: | + Returns the presentation templates ordered by title, without their modules. Not paginated: there are few presentation templates. Pagination parameters + are rejected. + responses: + '200': + description: The presentation templates. + content: + application/json: + schema: { $ref: '#/components/schemas/PresentationTemplateListResponse' } + 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' } + + /presentationTemplates/{presentationTemplateId}: + get: + tags: [Presentation templates] + operationId: getPresentationTemplate + summary: Get a presentation template by id, with its modules + parameters: + - name: presentationTemplateId + in: path + required: true + description: Presentation template identifier. + schema: { type: integer, minimum: 1 } + responses: + '200': + description: The presentation template, with its modules in presentation order. + content: + application/json: + schema: { $ref: '#/components/schemas/PresentationTemplateResponse' } + 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 } + - { position: 1, type: fill-calendar, title: Fills and runs } + - { position: 2, type: fill-efficiency, title: Fill efficiencies } + '400': { $ref: '#/components/responses/ValidationError' } + '404': + description: No presentation template has this id. + content: + application/json: + schema: { $ref: '#/components/schemas/ErrorResponse' } + example: + errors: + - { status: 404, title: Not found, detail: Presentation 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 /presentationTemplates. } + 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. The detail of this and every other error of ALICE Insights is the sentence with which it explains why.' } + '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,34 @@ components: type: array items: { $ref: '#/components/schemas/SimulationPass' } meta: { $ref: '#/components/schemas/PageMeta' } + PresentationTemplateModule: + type: object + required: [position, type, title] + 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. } + PresentationTemplate: + type: object + required: [id, name, title, description] + properties: + id: { type: integer } + name: { type: string, description: 'Unique name of the presentation 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 presentation template. + items: { $ref: '#/components/schemas/PresentationTemplateModule' } + PresentationTemplateResponse: + type: object + required: [data] + properties: + data: { $ref: '#/components/schemas/PresentationTemplate' } + PresentationTemplateListResponse: + type: object + required: [data] + properties: + data: + type: array + items: { $ref: '#/components/schemas/PresentationTemplate' } diff --git a/lib/server/controllers/index.js b/lib/server/controllers/index.js index 48184378b2..423efa5d66 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 PresentationTemplatesController = require('./presentationTemplates.controller.js'); const CtpTriggerCountersController = require('./ctpTriggerCounters.controller'); module.exports = { @@ -32,9 +34,11 @@ module.exports = { FlpsController, LhcFillsController, LogsController, + PresentationsController, RunTypesController, RunsController, StatusController, TagsController, + PresentationTemplatesController, CtpTriggerCountersController, }; diff --git a/lib/server/controllers/presentationTemplates.controller.js b/lib/server/controllers/presentationTemplates.controller.js new file mode 100644 index 0000000000..ddbf598cea --- /dev/null +++ b/lib/server/controllers/presentationTemplates.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: { GetAllPresentationTemplatesDto, GetPresentationTemplateDto } } = require('../../domain'); +const { dtoValidator } = require('../utilities'); +const { presentationTemplateService } = require('../services/presentationTemplate/PresentationTemplateService.js'); +const { updateExpressResponseFromNativeError } = require('../express/updateExpressResponseFromNativeError.js'); + +/** + * Get all presentation 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 listPresentationTemplates = async (request, response) => { + const value = await dtoValidator(GetAllPresentationTemplatesDto, request, response); + if (!value) { + return; + } + + try { + response.status(200).json({ data: await presentationTemplateService.getAll() }); + } catch (error) { + updateExpressResponseFromNativeError(response, error); + } +}; + +/** + * Get a presentation 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 getPresentationTemplateById = async (request, response) => { + const value = await dtoValidator(GetPresentationTemplateDto, request, response); + if (!value) { + return; + } + + try { + response.status(200).json({ data: await presentationTemplateService.getOneOrFail(value.params.presentationTemplateId) }); + } catch (error) { + updateExpressResponseFromNativeError(response, error); + } +}; + +module.exports = { + listPresentationTemplates, + getPresentationTemplateById, +}; 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/routers/index.js b/lib/server/routers/index.js index b3952aa86a..ebfa361371 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 presentationTemplatesRoute = require('./presentationTemplates.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, + presentationTemplatesRoute, ctpTriggerCountersRouter, ]; diff --git a/lib/server/routers/presentationTemplates.router.js b/lib/server/routers/presentationTemplates.router.js new file mode 100644 index 0000000000..0c58fce1c5 --- /dev/null +++ b/lib/server/routers/presentationTemplates.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 { PresentationTemplatesController } = require('../controllers'); + +module.exports = { + path: '/presentationTemplates', + children: [ + { + method: 'get', + controller: PresentationTemplatesController.listPresentationTemplates, + }, + { + path: ':presentationTemplateId', + children: [ + { + method: 'get', + controller: PresentationTemplatesController.getPresentationTemplateById, + }, + ], + }, + ], +}; 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/services/presentation/generatePresentation.js b/lib/server/services/presentation/generatePresentation.js new file mode 100644 index 0000000000..548a9f0c76 --- /dev/null +++ b/lib/server/services/presentation/generatePresentation.js @@ -0,0 +1,128 @@ +/** + * @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 { LogManager } = require('@aliceo2/web-ui'); +const { ServicesConfig } = require('../../../config'); + +const logger = LogManager.getLogger('PRESENTATION-GENERATION'); + +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.', +}; + +/** + * Return the sentence with which ALICE Insights explains an error, or null if its answer has none. + * + * @param {Response} response The answer of ALICE Insights. + * @returns {Promise} The sentence. + */ +const readDetail = async (response) => { + try { + const { detail } = await response.json(); + return typeof detail === 'string' ? detail : null; + } catch { + return null; + } +}; + +/** + * Send a request to ALICE Insights and return a PDF or a safe error for the caller. + * + * ALICE Insights explains every error in a sentence written for the user, which never repeats a value of the request. That + * sentence is passed on. Bookkeeping's own sentence is used when ALICE Insights gives none or cannot be reached. + * The log has the answer of ALICE Insights for every request that gives no PDF. + * + * @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) { + const detail = await readDetail(response); + logger.warnMessage(`ALICE Insights answered ${response.status} for template ${templateId}${detail ? `: ${detail}` : ''}`); + const error = upstreamErrors[response.status]; + if (!error) { + return unavailable; + } + const retryAfter = response.headers.get('retry-after'); + return { + status: response.status, + ...error, + detail: detail ?? error.detail, + 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(); + logger.errorMessage('ALICE Insights answered 200 with something else than a PDF'); + return unavailable; + } + + const pdf = Buffer.from(await response.arrayBuffer()); + if (pdf.subarray(0, 5).toString('latin1') !== '%PDF-') { + logger.errorMessage('ALICE Insights answered 200 with a file that is not a 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) { + // The address comes from the configuration and the error from the connection, so neither holds the user's token + logger.errorMessage(`ALICE Insights could not be reached at ${url}: ${error.cause?.code ?? error.name}`); + 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/presentationTemplate/PresentationTemplateService.js b/lib/server/services/presentationTemplate/PresentationTemplateService.js new file mode 100644 index 0000000000..7f49ad99a3 --- /dev/null +++ b/lib/server/services/presentationTemplate/PresentationTemplateService.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 { presentationTemplateAdapter } = require('../../../database/adapters/index.js'); +const { getAllPresentationTemplates } = require('./getAllPresentationTemplates.js'); +const { getPresentationTemplateOrFail } = require('./getPresentationTemplateOrFail.js'); + +/** + * Global service to read presentation templates + */ +class PresentationTemplateService { + /** + * Return the presentation templates sorted by title, without their modules + * + * Presentation templates are not paginated, as there are only a few of them + * + * @return {Promise} the templates + */ + async getAll() { + return (await getAllPresentationTemplates()).map(presentationTemplateAdapter.toEntity); + } + + /** + * Return the presentation 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} resolves with the template found or rejects with a NotFoundError + */ + async getOneOrFail(id) { + return presentationTemplateAdapter.toEntity(await getPresentationTemplateOrFail(id)); + } +} + +exports.PresentationTemplateService = PresentationTemplateService; + +exports.presentationTemplateService = new PresentationTemplateService(); diff --git a/lib/server/services/presentationTemplate/getAllPresentationTemplates.js b/lib/server/services/presentationTemplate/getAllPresentationTemplates.js new file mode 100644 index 0000000000..45458f6386 --- /dev/null +++ b/lib/server/services/presentationTemplate/getAllPresentationTemplates.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 { utilities: { QueryBuilder } } = require('../../../database'); +const PresentationTemplateRepository = require('../../../database/repositories/PresentationTemplateRepository.js'); + +/** + * Return the list of all the presentation templates, sorted by title + * + * @return {Promise} Promise resolving with the list of presentation templates + */ +exports.getAllPresentationTemplates = () => { + const queryBuilder = new QueryBuilder(); + queryBuilder.orderBy('title', 'ASC'); + return PresentationTemplateRepository.findAll(queryBuilder); +}; diff --git a/lib/server/services/presentationTemplate/getPresentationTemplate.js b/lib/server/services/presentationTemplate/getPresentationTemplate.js new file mode 100644 index 0000000000..1a776ed475 --- /dev/null +++ b/lib/server/services/presentationTemplate/getPresentationTemplate.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 { utilities: { QueryBuilder } } = require('../../../database'); +const PresentationTemplateRepository = require('../../../database/repositories/PresentationTemplateRepository.js'); + +/** + * Find and return a presentation template model, with its modules in presentation order, by its id + * + * @param {number} id the id of the template to find + * @return {Promise} the template found or null + */ +exports.getPresentationTemplate = (id) => { + const queryBuilder = new QueryBuilder(); + + queryBuilder.where('id').is(id); + queryBuilder.include('modules'); + queryBuilder.orderBy('position', 'ASC', 'modules'); + + return PresentationTemplateRepository.findOne(queryBuilder); +}; diff --git a/lib/server/services/presentationTemplate/getPresentationTemplateOrFail.js b/lib/server/services/presentationTemplate/getPresentationTemplateOrFail.js new file mode 100644 index 0000000000..8b507db65f --- /dev/null +++ b/lib/server/services/presentationTemplate/getPresentationTemplateOrFail.js @@ -0,0 +1,30 @@ +/** + * @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 { NotFoundError } = require('../../errors/NotFoundError.js'); +const { getPresentationTemplate } = require('./getPresentationTemplate.js'); + +/** + * Find a presentation template model by its id and reject with a NotFoundError if none is found + * + * @param {number} id the id of the template to find + * @return {Promise} resolve with the template model found or reject with a NotFoundError + */ +exports.getPresentationTemplateOrFail = async (id) => { + const presentationTemplateModel = await getPresentationTemplate(id); + if (presentationTemplateModel !== null) { + return presentationTemplateModel; + } else { + throw new NotFoundError(`Presentation template with this id (${id}) could not be found`); + } +}; diff --git a/scripts/build-api-docs.js b/scripts/build-api-docs.js index 2e4107fa4c..921d3279bd 100644 --- a/scripts/build-api-docs.js +++ b/scripts/build-api-docs.js @@ -156,19 +156,40 @@ const examplesOf = (method, route, operation, parameters) => { .filter(({ in: location, name, required }) => location === 'query' && (required || name === 'page[limit]')); const query = queryParameters.map((parameter) => `${parameter.name}=${encodeURIComponent(sampleValue(parameter))}`); // $BOOKKEEPING_URL and $TOKEN are meant to be expanded by the shell, anything coming from the spec is not - const address = `${shellDoubleQuoteEscape(`/api${url}?${[...query, 'token='].join('&')}`)}$TOKEN`; + const requestPath = `/api${url}?${[...query, 'token='].join('&')}`; + const address = `${shellDoubleQuoteEscape(requestPath)}$TOKEN`; const body = operation.requestBody?.content?.['application/json']?.example; + const downloadsPdf = Boolean(operation.responses['200']?.content?.['application/pdf']); const curlLines = [ - `curl -g${method === 'get' ? '' : ` -X ${method.toUpperCase()}`} "$BOOKKEEPING_URL${address}"`, + `curl -g${downloadsPdf ? ' --fail' : ''}${method === 'get' ? '' : ` -X ${method.toUpperCase()}`} "$BOOKKEEPING_URL${address}"`, ...body === undefined ? [] : [' -H \'content-type: application/json\'', ` -d ${shellSingleQuote(JSON.stringify(body))}`], + ...downloadsPdf ? [' --output presentation.pdf'] : [], ]; - return [ + const bashExample = [ '```bash', curlLines.join(' \\\n'), '```', ].join('\n'); + if (!downloadsPdf) { + return bashExample; + } + + const psAddress = requestPath.replace(/["$`]/g, '`$&'); + const psBody = body === undefined ? '' : ` -ContentType 'application/json' -Body '${JSON.stringify(body).replaceAll("'", "''")}'`; + const psCommand = `Invoke-WebRequest -Uri "$env:BOOKKEEPING_URL${psAddress}$env:TOKEN" -Method ${method.toUpperCase()}${psBody}`; + return [ + '**PowerShell 7+**', + '', + '```powershell', + `${psCommand} -OutFile presentation.pdf`, + '```', + '', + '**Linux/Bash**', + '', + bashExample, + ].join('\n'); }; /** diff --git a/test/api/index.js b/test/api/index.js index 3396cb9c05..ff8b480327 100644 --- a/test/api/index.js +++ b/test/api/index.js @@ -21,11 +21,13 @@ const FlpSuite = require('./flps.test.js'); const StatusSuite = require('./status.test.js'); const LogsSuite = require('./logs.test.js'); const LhcFillSuite = require('./lhcFills.test.js'); +const PresentationsSuite = require('./presentations.test.js'); const RunsSuite = require('./runs.test.js'); const RunTypesSuite = require('./runTypes.test.js'); const ShiftSuite = require('./shift.test.js'); const StatisticsSuite = require('./statistics.test.js'); const TagsSuite = require('./tags.test.js'); +const PresentationTemplatesSuite = require('./presentationTemplates.test.js'); const LhcPeriodsStatisticsSuite = require('./lhcPeriodsStatistics.test.js'); const RunsWithRunId = require('./runs-with-runId.test.js'); const DataPassesSuite = require('./dataPasses.test.js'); @@ -46,6 +48,7 @@ module.exports = () => { describe('GaqDetectors API', GaqDetectorsSuite); describe('LhcFills API', LhcFillSuite); describe('Logs API', LogsSuite); + describe('Presentations API', PresentationsSuite); describe('Runs API', RunsSuite); describe('RunsWithRunId API', RunsWithRunId); describe('RunTypes API', RunTypesSuite); @@ -53,6 +56,7 @@ module.exports = () => { describe('Status API', StatusSuite); describe('Statistics suite', StatisticsSuite); describe('Tags API', TagsSuite); + describe('PresentationTemplates API', PresentationTemplatesSuite); describe('LhcPeriodsStatistics API', LhcPeriodsStatisticsSuite); describe('DataPasses API', DataPassesSuite); describe('SimulationPasses API', SimulationPassesSuite); diff --git a/test/api/presentationTemplates.test.js b/test/api/presentationTemplates.test.js new file mode 100644 index 0000000000..c5c6bf7068 --- /dev/null +++ b/test/api/presentationTemplates.test.js @@ -0,0 +1,74 @@ +/** + * @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 { expect } = require('chai'); +const request = require('supertest'); +const { server } = require('../../lib/application'); +const { resetDatabaseContent } = require('../utilities/resetDatabaseContent.js'); + +module.exports = () => { + before(resetDatabaseContent); + + describe('GET /api/presentationTemplates', () => { + it('should return all the presentation templates sorted by title, without their modules', async () => { + const response = await request(server).get('/api/presentationTemplates'); + expect(response.status).to.equal(200); + + const { data: templates, meta } = response.body; + expect(meta).to.be.undefined; + expect(templates.map(({ name }) => name)).to.eql(['lhc-fill-summary', 'run-manager-weekly-report']); + templates.forEach((template) => expect(Object.keys(template)).to.have.members(['id', 'name', 'title', 'description'])); + }); + + it('should return 400 if a pagination parameter is given', async () => { + const response = await request(server).get('/api/presentationTemplates?page[limit]=1'); + expect(response.status).to.equal(400); + }); + }); + + describe('GET /api/presentationTemplates/:presentationTemplateId', () => { + it('should return the presentation template with its modules in presentation order', async () => { + const response = await request(server).get('/api/presentationTemplates/1'); + expect(response.status).to.equal(200); + + const { data: template } = response.body; + expect(template.name).to.equal('run-manager-weekly-report'); + expect(template.title).to.equal('Run Manager Weekly Report'); + expect(template.modules.map(({ position, type }) => [position, type])).to.eql([ + [0, 'title-slide'], + [1, 'fill-calendar'], + [2, 'fill-efficiency'], + [3, 'running-time'], + [4, 'eor-reasons'], + ]); + template.modules.forEach((module) => expect(Object.keys(module)).to.have.members(['position', 'type', 'title'])); + }); + + it('should return 404 if the presentation template does not exist', async () => { + const response = await request(server).get('/api/presentationTemplates/999999'); + expect(response.status).to.equal(404); + expect(response.body.errors).to.eql([ + { status: 404, title: 'Not found', detail: 'Presentation template with this id (999999) could not be found' }, + ]); + }); + + it('should return 400 if the presentation template id is not positive', async () => { + const response = await request(server).get('/api/presentationTemplates/-1'); + expect(response.status).to.equal(400); + + const { errors } = response.body; + const idError = errors.find((error) => error.source.pointer === '/data/attributes/params/presentationTemplateId'); + expect(idError.detail).to.equal('"params.presentationTemplateId" must be a positive number'); + }); + }); +}; diff --git a/test/api/presentations.test.js b/test/api/presentations.test.js new file mode 100644 index 0000000000..4b4f3c8978 --- /dev/null +++ b/test/api/presentations.test.js @@ -0,0 +1,201 @@ +/** + * @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 { once } = require('node:events'); +const { createServer } = require('node:http'); +const { text } = require('node:stream/consumers'); +const { expect } = require('chai'); +const request = require('supertest'); +const { server } = require('../../lib/application'); +const { ServicesConfig } = require('../../lib/config'); +const { resetDatabaseContent } = require('../utilities/resetDatabaseContent.js'); + +const PRESENTATION = { + templateId: 1, + from: Date.UTC(2026, 10, 16), + to: Date.UTC(2026, 10, 23), +}; +const PDF_BYTES = Buffer.from('%PDF-1.4\n%\xE2\xE3\xCF\xD3\n%%EOF\n', 'latin1'); +const GENERATION_FAILED = { + status: 502, + title: 'Generation failed', + detail: 'The generation service could not return a PDF. Try again later.', +}; + +module.exports = () => { + let token; + let generationService; + let generationServiceUrl; + let originalUrl; + let forwardedRequests; + let generationResponse; + + before(async () => { + await resetDatabaseContent(); + token = server.http.o2TokenService.generateToken(1, 'jdoe', 'John Doe'); + generationService = createServer(async (incoming, outgoing) => { + forwardedRequests.push({ + path: incoming.url, + method: incoming.method, + authorization: incoming.headers.authorization, + contentType: incoming.headers['content-type'], + body: await text(incoming), + }); + outgoing.writeHead(generationResponse.status, generationResponse.headers); + outgoing.end(generationResponse.body); + }); + generationService.listen(0, '127.0.0.1'); + await once(generationService, 'listening'); + generationServiceUrl = `http://127.0.0.1:${generationService.address().port}`; + originalUrl = ServicesConfig.aliceInsights.url; + }); + + beforeEach(() => { + forwardedRequests = []; + generationResponse = { + status: 200, + headers: { + 'Content-Type': 'application/pdf', + 'Content-Disposition': 'attachment; filename="weekly-report.pdf"', + }, + body: PDF_BYTES, + }; + ServicesConfig.aliceInsights.url = generationServiceUrl; + }); + + after(async () => { + ServicesConfig.aliceInsights.url = originalUrl; + await new Promise((resolve, reject) => generationService.close((error) => error ? reject(error) : resolve())); + }); + + const generate = (body) => request(server).post('/api/presentations').query({ token }).send(body); + + it('forwards the chosen period with the authenticated user and returns the PDF', async () => { + const response = await generate(PRESENTATION).buffer(true).parse((incoming, callback) => { + const chunks = []; + incoming.on('data', (chunk) => chunks.push(chunk)); + incoming.on('end', () => callback(null, Buffer.concat(chunks))); + incoming.on('error', callback); + }); + + expect(response.status).to.equal(200); + expect(response.headers['content-type']).to.equal('application/pdf'); + expect(response.headers['content-disposition']).to.equal('attachment; filename="weekly-report.pdf"'); + expect(response.headers['cache-control']).to.equal('no-store'); + expect(response.body).to.deep.equal(PDF_BYTES); + expect(forwardedRequests).to.have.lengthOf(1); + const [forwarded] = forwardedRequests; + expect(forwarded).to.include({ + path: '/presentations', + method: 'POST', + authorization: `Bearer ${token}`, + }); + expect(forwarded.contentType).to.match(/^application\/json\b/); + expect(JSON.parse(forwarded.body)).to.deep.equal({ ...PRESENTATION, templateId: '1', author: 'John Doe' }); + }); + + it('requires a user token before contacting generation', async () => { + const response = await request(server).post('/api/presentations').send(PRESENTATION); + expect(response.status).to.equal(401); + expect(forwardedRequests).to.be.empty; + }); + + for (const [problem, changes] of [ + ['an invalid template ID', { templateId: 0 }], + ['a fractional date', { from: PRESENTATION.from + 0.5 }], + ['a reversed period', { to: PRESENTATION.from - 1 }], + ['an author supplied by the browser', { author: 'Custom author' }], + ]) { + it(`rejects ${problem} before contacting generation`, async () => { + const response = await generate({ ...PRESENTATION, ...changes }); + expect(response.status).to.equal(400); + expect(response.body.errors).to.have.lengthOf.at.least(1); + expect(forwardedRequests).to.be.empty; + }); + } + + it('keeps the generator busy response and its retry delay', async () => { + generationResponse = { + status: 503, + headers: { 'Content-Type': 'application/json', 'Retry-After': '10' }, + body: JSON.stringify({ detail: 'A presentation is being made. Try again when it is done.' }), + }; + const response = await generate(PRESENTATION); + expect(response.status).to.equal(503); + expect(response.headers['retry-after']).to.equal('10'); + expect(response.body.errors).to.eql([ + { status: 503, title: 'Generation busy', detail: 'A presentation is being made. Try again when it is done.' }, + ]); + }); + + for (const [status, title, detail] of [ + [401, 'Session expired', 'Bookkeeping rejected your user token. Sign in to Bookkeeping again.'], + [422, 'Invalid presentation', 'The template has no modules.'], + [502, 'Data unavailable', 'Bookkeeping could not provide the data for this presentation.'], + ]) { + it(`passes on the sentence with which the generator explains a ${status}`, async () => { + generationResponse = { status, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ detail }) }; + const response = await generate(PRESENTATION); + expect(response.status).to.equal(status); + expect(response.body.errors).to.eql([{ status, title, detail }]); + }); + } + + for (const [answer, body] of [ + ['without a sentence', JSON.stringify({ errors: ['Not a sentence of the generator'] })], + ['that is not JSON', 'Not a sentence of the generator'], + ]) { + it(`explains an error in its own words for an answer ${answer}`, async () => { + generationResponse = { status: 422, headers: { 'Content-Type': 'application/json' }, body }; + const response = await generate(PRESENTATION); + expect(response.status).to.equal(422); + expect(response.body.errors).to.eql([ + { status: 422, title: 'Invalid presentation', detail: 'Check the selected template and period and try again.' }, + ]); + }); + } + + it('reports a non-PDF response as a generation service failure', async () => { + generationResponse = { + status: 200, + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ detail: 'A JSON response instead of a PDF' }), + }; + const response = await generate(PRESENTATION); + expect(response.status).to.equal(502); + expect(response.headers['content-disposition']).to.be.undefined; + }); + + it('reports a PDF response that holds no PDF as a generation service failure', async () => { + generationResponse = { + status: 200, + headers: { 'Content-Type': 'application/pdf' }, + body: 'Not a PDF', + }; + const response = await generate(PRESENTATION); + expect(response.status).to.equal(502); + expect(response.headers['content-disposition']).to.be.undefined; + expect(response.body.errors).to.eql([GENERATION_FAILED]); + }); + + it('reports an answer with a status the generator does not use as a generation service failure', async () => { + generationResponse = { + status: 500, + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ detail: 'Internal Server Error' }), + }; + const response = await generate(PRESENTATION); + expect(response.status).to.equal(502); + expect(response.body.errors).to.eql([GENERATION_FAILED]); + }); +}; diff --git a/test/lib/public/utilities/dateUtils.test.js b/test/lib/public/utilities/dateUtils.test.js new file mode 100644 index 0000000000..c321ae11a0 --- /dev/null +++ b/test/lib/public/utilities/dateUtils.test.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. + */ + +const { expect } = require('chai'); + +let getStartOfWeek; + +module.exports = () => { + let timeZone; + + before(async () => { + ({ getStartOfWeek } = await import('../../../../lib/public/utilities/dateUtils.mjs')); + timeZone = process.env.TZ; + }); + + after(() => { + if (timeZone === undefined) { + delete process.env.TZ; + } else { + process.env.TZ = timeZone; + } + }); + + for (const zone of ['America/Los_Angeles', 'UTC', 'Pacific/Auckland']) { + it(`should start week 47 of 2026 on Monday 16 November at midnight UTC with a clock in ${zone}`, () => { + process.env.TZ = zone; + expect(getStartOfWeek(47, 2026).toISOString()).to.equal('2026-11-16T00:00:00.000Z'); + }); + } +}; diff --git a/test/lib/public/utilities/index.js b/test/lib/public/utilities/index.js index b7163daa0f..2cfd6ddb06 100644 --- a/test/lib/public/utilities/index.js +++ b/test/lib/public/utilities/index.js @@ -11,10 +11,12 @@ * or submit itself to any jurisdiction. */ +const DateUtilsSuite = require('./dateUtils.test.js'); const FormattingSuite = require('./formatting/index.js'); const FilterOutLegacyDetectorsForNewerPeriodsSuite = require('./filterOutLegacyDetectorsForNewerPeriods.test.js'); module.exports = () => { + describe('DateUtils', DateUtilsSuite); describe('FormattingSuite', FormattingSuite); describe('FilterOutLegacyDetectorsForNewerPeriods', FilterOutLegacyDetectorsForNewerPeriodsSuite); }; diff --git a/test/lib/server/services/index.js b/test/lib/server/services/index.js index c9e7871aa2..e793458867 100644 --- a/test/lib/server/services/index.js +++ b/test/lib/server/services/index.js @@ -23,12 +23,14 @@ const EosReportSuite = require('./eosReport/index.js'); const FlpRoleSuite = require('./flpRole'); const LhcFillSuite = require('./lhcFill'); const LogSuite = require('./log'); +const PresentationGenerationSuite = require('./presentation/generatePresentation.test.js'); const RunSuite = require('./run/index.js'); const RunTypeSuite = require('./runType/index.js'); const ShiftSuite = require('./shift/index.js'); const StatisticsSuite = require('./statistics/index.js'); const StatusSuite = require('./status/index.js'); const TagSuite = require('./tag/index.js'); +const PresentationTemplateSuite = require('./presentationTemplate/index.js'); const LhcPeriodSuite = require('./lhcPeriod'); const DataPassesSuite = require('./dataPasses/index.js'); const UserSuite = require('./user/index.js'); @@ -53,12 +55,14 @@ module.exports = () => { describe('GaqDetector', GaqDetectorSuite); describe('LHC fill suite', LhcFillSuite); describe('Logs', LogSuite); + describe('Presentation generation', PresentationGenerationSuite); describe('RunType', RunTypeSuite); describe('Run', RunSuite); describe('Shift', ShiftSuite); describe('Statistics', StatisticsSuite); describe('Status', StatusSuite); describe('Tag', TagSuite); + describe('PresentationTemplate', PresentationTemplateSuite); describe('LhcPeriod', LhcPeriodSuite); describe('User', UserSuite); describe('DataPasses', DataPassesSuite); diff --git a/test/lib/server/services/presentation/generatePresentation.test.js b/test/lib/server/services/presentation/generatePresentation.test.js new file mode 100644 index 0000000000..7c6e5aa9ec --- /dev/null +++ b/test/lib/server/services/presentation/generatePresentation.test.js @@ -0,0 +1,68 @@ +/** + * @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 { expect } = require('chai'); +const sinon = require('sinon'); +const { ServicesConfig } = require('../../../../../lib/config'); +const { generatePresentation } = require('../../../../../lib/server/services/presentation/generatePresentation.js'); + +const SELECTION = { templateId: 1, from: 0, to: 1000 }; + +module.exports = () => { + let sandbox; + let fetchStub; + + beforeEach(() => { + sandbox = sinon.createSandbox(); + sandbox.replace(ServicesConfig.aliceInsights, 'url', null); + fetchStub = sandbox.stub(globalThis, 'fetch'); + }); + + afterEach(() => { + sandbox.restore(); + }); + + it('reports when generation has not been configured', async () => { + const result = await generatePresentation(SELECTION, 'John Doe', 'test-token'); + expect(result).to.deep.equal({ + status: 503, + title: 'Generation unavailable', + detail: 'Presentation generation is not configured for this Bookkeeping server.', + }); + expect(fetchStub.called).to.be.false; + }); + + it('reports when the generator takes too long', async () => { + ServicesConfig.aliceInsights.url = 'http://127.0.0.1'; + fetchStub.rejects(new DOMException('Request timed out', 'TimeoutError')); + + const result = await generatePresentation(SELECTION, 'John Doe', 'test-token'); + expect(result).to.deep.equal({ + status: 504, + title: 'Generation timed out', + detail: 'The generation service took too long to finish. Try again later.', + }); + }); + + it('reports when the generator cannot be reached', async () => { + ServicesConfig.aliceInsights.url = 'http://127.0.0.1'; + fetchStub.rejects(new TypeError('fetch failed', { cause: { code: 'ECONNREFUSED' } })); + + const result = await generatePresentation(SELECTION, 'John Doe', 'test-token'); + expect(result).to.deep.equal({ + status: 502, + title: 'Generation failed', + detail: 'The generation service could not return a PDF. Try again later.', + }); + }); +}; diff --git a/test/lib/server/services/presentationTemplate/PresentationTemplateService.test.js b/test/lib/server/services/presentationTemplate/PresentationTemplateService.test.js new file mode 100644 index 0000000000..481c5dc51d --- /dev/null +++ b/test/lib/server/services/presentationTemplate/PresentationTemplateService.test.js @@ -0,0 +1,38 @@ +/** + * @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 { presentationTemplateService } = require('../../../../../lib/server/services/presentationTemplate/PresentationTemplateService.js'); +const { NotFoundError } = require('../../../../../lib/server/errors/NotFoundError.js'); +const { expect } = require('chai'); + +module.exports = () => { + it('should successfully return all the presentation templates sorted by title, without their modules', async () => { + const templates = await presentationTemplateService.getAll(); + + expect(templates.map(({ title }) => title)).to.eql(['LHC Fill Summary', 'Run Manager Weekly Report']); + templates.forEach((template) => expect(template).to.not.have.property('modules')); + }); + + it('should successfully return a presentation template by id with its modules in presentation order', async () => { + const template = await presentationTemplateService.getOneOrFail(2); + + expect(template.name).to.equal('lhc-fill-summary'); + expect(template.modules.map(({ type }) => type)).to.eql(['title-slide', 'fill-calendar', 'fill-efficiency']); + }); + + it('should fail with a not found error when the presentation template does not exist', async () => { + const error = await presentationTemplateService.getOneOrFail(999999).catch((error) => error); + expect(error).to.be.instanceOf(NotFoundError); + expect(error.message).to.equal('Presentation template with this id (999999) could not be found'); + }); +}; diff --git a/test/lib/server/services/presentationTemplate/index.js b/test/lib/server/services/presentationTemplate/index.js new file mode 100644 index 0000000000..7c7bdf521e --- /dev/null +++ b/test/lib/server/services/presentationTemplate/index.js @@ -0,0 +1,18 @@ +/** + * @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 PresentationTemplateServiceTest = require('./PresentationTemplateService.test.js'); + +module.exports = () => { + describe('PresentationTemplateService', PresentationTemplateServiceTest); +}; diff --git a/test/public/index.js b/test/public/index.js index e737d483ce..382bde57af 100644 --- a/test/public/index.js +++ b/test/public/index.js @@ -19,6 +19,7 @@ const FlpsSuite = require('./flps'); const HomeSuite = require('./home'); const AboutSuite = require('./about'); const HeaderSuite = require('./header'); +const PresentationsSuite = require('./presentations/overview.test.js'); const EnvsSuite = require('./envs'); const ErrorSuite = require('./error'); const EosReportSuite = require('./eosReport'); @@ -45,6 +46,7 @@ module.exports = () => { describe('Home', HomeSuite); describe('About', AboutSuite); describe('Header', HeaderSuite); + describe('Presentations page', PresentationsSuite); describe('EosReport', EosReportSuite); describe('DataPasses', DataPassesSuite); describe('SimulationPasses', SimulationPassesSuite); diff --git a/test/public/presentations/overview.test.js b/test/public/presentations/overview.test.js new file mode 100644 index 0000000000..2e0c8fefa8 --- /dev/null +++ b/test/public/presentations/overview.test.js @@ -0,0 +1,289 @@ +/** + * @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 { readFile, unlink } = require('node:fs/promises'); +const { join } = require('node:path'); +const { expect } = require('chai'); +const { resetDatabaseContent } = require('../../utilities/resetDatabaseContent.js'); +const { + defaultAfter, + defaultBefore, + expectInnerText, + getPopoverSelector, + goToPage, + pressElement, + waitForDownload, +} = require('../defaults.js'); + +const FROM = '2026-11-16T00:00'; +const TO = '2026-11-23T00:00'; +// Geneva is one hour ahead of UTC in November +const GENEVA_OFFSET = '+01:00'; +const WEEK = 7 * 24 * 60 * 60 * 1000; +const PERIOD_TRIGGER = '#presentation-period .popover-trigger'; +const GENERATE_BUTTON = '#generate-presentation'; +const GENERATION_STATUS = '#presentation-generation-status'; +const DOWNLOAD_LINK = '#download-presentation'; +const PDF = '%PDF-1.4\n%%EOF\n'; +const FILENAME = 'weekly-report-test.pdf'; + +const isGenerationRequest = (request) => new URL(request.url()).pathname === '/api/presentations' && request.method() === 'POST'; + +module.exports = () => { + let page; + let browser; + + before(async () => { + await resetDatabaseContent(); + [page, browser] = await defaultBefore(); + await page.setViewport({ width: 1280, height: 800 }); + // The period is in Geneva time whatever the time zone of the browser, so the browser gets another one + await page.emulateTimezone('America/New_York'); + await page.setRequestInterception(true); + page.on('request', (request) => { + if (!isGenerationRequest(request)) { + return request.continue(); + } + }); + }); + + after(async () => { + await defaultAfter(page, browser); + }); + + const preparePresentation = async (from = FROM, to = TO) => { + await goToPage(page, 'presentations'); + await page.waitForSelector('#presentation-template option[value="1"]'); + await page.select('#presentation-template', '1'); + const popoverSelector = await getPopoverSelector(await page.$(PERIOD_TRIGGER)); + const inputs = `${popoverSelector} input[type="datetime-local"]`; + await pressElement(page, PERIOD_TRIGGER); + await page.waitForSelector(inputs, { visible: true }); + await page.$$eval(inputs, ([fromInput, toInput], from, to) => { + fromInput.value = from; + fromInput.dispatchEvent(new Event('change', { bubbles: true })); + toInput.value = to; + toInput.dispatchEvent(new Event('change', { bubbles: true })); + }, from, to); + await pressElement(page, PERIOD_TRIGGER); + await page.waitForSelector(`${GENERATE_BUTTON}:enabled`); + }; + + const startGeneration = async () => { + const [request] = await Promise.all([ + page.waitForRequest(isGenerationRequest), + pressElement(page, GENERATE_BUTTON), + ]); + return request; + }; + + it('opens from navigation and lists the existing templates', async () => { + await goToPage(page, 'home'); + await pressElement(page, '#presentations'); + await expectInnerText(page, '#presentations-page h1', 'Presentations'); + await page.waitForSelector('#presentation-template option[value="1"]'); + const templates = await page.$$eval('#presentation-template option', (options) => options.map(({ text }) => text)); + expect(templates).to.eql(['Choose a template', 'LHC Fill Summary', 'Run Manager Weekly Report']); + await page.waitForSelector(`${GENERATE_BUTTON}:disabled`); + }); + + it('explains which fills and runs a presentation covers', async () => { + await goToPage(page, 'presentations'); + const explanation = await page.$eval('#presentations-explanation', ({ innerText }) => innerText); + expect(explanation).to.include('every LHC fill with stable beams in the period'); + expect(explanation).to.include('with all its PHYSICS runs'); + }); + + it('keeps the create button fully visible with the Presentations tab on a laptop', async () => { + await goToPage(page, 'presentations'); + await page.waitForSelector('#presentations.selected'); + await page.waitForFunction(() => Array.from(document.querySelectorAll('.navbar-links a')).some(({ textContent }) => textContent === 'ALI FLP')); + const isWithinViewport = await page.$eval('#create-menu-button', (button) => button.getBoundingClientRect().right <= window.innerWidth); + expect(isWithinViewport).to.be.true; + }); + + it('shows a spinner until the selected template and period are available as a download', async () => { + await preparePresentation(); + const request = await startGeneration(); + await expectInnerText(page, `${GENERATION_STATUS} p`, 'Generating the presentation…'); + await page.waitForSelector(`${GENERATION_STATUS} .atom-spinner`); + await page.waitForSelector(`${GENERATE_BUTTON}:disabled`); + expect(JSON.parse(await request.fetchPostData())).to.eql({ + templateId: 1, + from: Date.parse(`${FROM}${GENEVA_OFFSET}`), + to: Date.parse(`${TO}${GENEVA_OFFSET}`), + }); + + await request.respond({ + status: 200, + contentType: 'application/pdf', + headers: { 'Content-Disposition': `attachment; filename="${FILENAME}"` }, + body: PDF, + }); + await page.waitForSelector(GENERATION_STATUS, { hidden: true }); + await expectInnerText(page, DOWNLOAD_LINK, 'Download PDF'); + const downloadDirectory = await waitForDownload(page, () => pressElement(page, DOWNLOAD_LINK)); + const file = join(downloadDirectory, FILENAME); + try { + expect(await readFile(file, 'utf8')).to.equal(PDF); + } finally { + await unlink(file); + } + }); + + it('says that the period is in Geneva time', async () => { + await goToPage(page, 'presentations'); + await expectInnerText(page, '#presentation-period-time-zone', '(Geneva time)'); + }); + + it('requests a predefined week from Monday to Monday in Geneva time', async () => { + await goToPage(page, 'presentations'); + await page.waitForSelector('#presentation-template option[value="1"]'); + await page.select('#presentation-template', '1'); + const popoverSelector = await getPopoverSelector(await page.$(PERIOD_TRIGGER)); + const weekInput = `${popoverSelector} input[type="number"]`; + await pressElement(page, PERIOD_TRIGGER); + await page.waitForSelector(weekInput, { visible: true }); + // Week 47 is in November in every year, when the clocks do not change + await page.$eval(weekInput, (input) => { + input.value = '47'; + input.dispatchEvent(new Event('change', { bubbles: true })); + }); + await pressElement(page, PERIOD_TRIGGER); + await page.waitForSelector(`${GENERATE_BUTTON}:enabled`); + + const request = await startGeneration(); + const { from, to } = JSON.parse(await request.fetchPostData()); + const genevaClock = new Intl.DateTimeFormat('en-GB', { + timeZone: 'Europe/Zurich', + weekday: 'long', + hour: '2-digit', + minute: '2-digit', + hourCycle: 'h23', + }); + expect(genevaClock.format(new Date(from))).to.equal('Monday 00:00'); + expect(to - from).to.equal(WEEK); + await request.respond({ status: 503, contentType: 'application/json', body: JSON.stringify({ errors: [] }) }); + await page.waitForSelector(`${GENERATE_BUTTON}:enabled`); + }); + + it('discards a finished presentation when another template is chosen', async () => { + await preparePresentation(); + const request = await startGeneration(); + await request.respond({ + status: 200, + contentType: 'application/pdf', + headers: { 'Content-Disposition': `attachment; filename="${FILENAME}"` }, + body: PDF, + }); + await page.waitForSelector(DOWNLOAD_LINK); + + await page.select('#presentation-template', '2'); + await page.waitForSelector(DOWNLOAD_LINK, { hidden: true }); + await page.waitForSelector(`${GENERATE_BUTTON}:enabled`); + }); + + it('shows the reason generation failed and lets the user retry', async () => { + await preparePresentation(); + const request = await startGeneration(); + const detail = 'A presentation is already being made. Try again shortly.'; + await request.respond({ + status: 503, + contentType: 'application/json', + body: JSON.stringify({ errors: [{ status: 503, title: 'Generation busy', detail }] }), + }); + + await expectInnerText(page, '#presentation-generation-error .alert', `Generation busy: ${detail}`); + await page.waitForSelector(GENERATION_STATUS, { hidden: true }); + await page.waitForSelector(DOWNLOAD_LINK, { hidden: true }); + await page.waitForSelector(`${GENERATE_BUTTON}:enabled`); + }); + + it('keeps the period when the week of the period picker is emptied', async () => { + await preparePresentation(); + const first = await startGeneration(); + const period = JSON.parse(await first.fetchPostData()); + await first.respond({ status: 503, contentType: 'application/json', body: JSON.stringify({ errors: [] }) }); + await page.waitForSelector(`${GENERATE_BUTTON}:enabled`); + + const popoverSelector = await getPopoverSelector(await page.$(PERIOD_TRIGGER)); + const weekInput = `${popoverSelector} input[type="number"]`; + await pressElement(page, PERIOD_TRIGGER); + await page.waitForSelector(weekInput, { visible: true }); + await page.$eval(weekInput, (input) => { + input.value = ''; + input.dispatchEvent(new Event('change', { bubbles: true })); + }); + await pressElement(page, PERIOD_TRIGGER); + + const second = await startGeneration(); + expect(JSON.parse(await second.fetchPostData())).to.deep.equal(period); + await second.respond({ status: 503, contentType: 'application/json', body: JSON.stringify({ errors: [] }) }); + await page.waitForSelector(`${GENERATE_BUTTON}:enabled`); + }); + for (const [direction, zone, from, to, expected] of [ + ['forward', 'Pacific/Auckland', '2026-03-29T01:30', '2026-03-30T00:00', { from: Date.UTC(2026, 2, 29, 0, 30), to: Date.UTC(2026, 2, 29, 22) }], + ['back', 'America/New_York', '2026-10-25T01:30', '2026-10-26T00:00', { from: Date.UTC(2026, 9, 24, 23, 30), to: Date.UTC(2026, 9, 25, 23) }], + ]) { + it(`requests the period in Geneva time on the day the clocks go ${direction}, with a browser in ${zone}`, async () => { + await page.emulateTimezone(zone); + try { + await preparePresentation(from, to); + const request = await startGeneration(); + expect(JSON.parse(await request.fetchPostData())).to.include(expected); + await request.respond({ status: 503, contentType: 'application/json', body: JSON.stringify({ errors: [] }) }); + await page.waitForSelector(`${GENERATE_BUTTON}:enabled`); + } finally { + await page.emulateTimezone('America/New_York'); + } + }); + } + + it('discards a finished presentation when another period is chosen', async () => { + await preparePresentation(); + const request = await startGeneration(); + await request.respond({ + status: 200, + contentType: 'application/pdf', + headers: { 'Content-Disposition': `attachment; filename="${FILENAME}"` }, + body: PDF, + }); + await page.waitForSelector(DOWNLOAD_LINK); + + const popoverSelector = await getPopoverSelector(await page.$(PERIOD_TRIGGER)); + const fromInput = `${popoverSelector} input[type="datetime-local"]`; + await pressElement(page, PERIOD_TRIGGER); + await page.waitForSelector(fromInput, { visible: true }); + await page.$eval(fromInput, (input) => { + input.value = '2026-11-17T00:00'; + input.dispatchEvent(new Event('change', { bubbles: true })); + }); + await page.waitForSelector(DOWNLOAD_LINK, { hidden: true }); + await pressElement(page, PERIOD_TRIGGER); + await page.waitForSelector(`${GENERATE_BUTTON}:enabled`); + }); + + it('discards the reason generation failed when another template is chosen', async () => { + await preparePresentation(); + const request = await startGeneration(); + await request.respond({ + status: 503, + contentType: 'application/json', + body: JSON.stringify({ errors: [{ status: 503, title: 'Generation busy', detail: 'Try again shortly.' }] }), + }); + await page.waitForSelector('#presentation-generation-error'); + + await page.select('#presentation-template', '2'); + await page.waitForSelector('#presentation-generation-error', { hidden: true }); + }); +}; diff --git a/test/scripts/test-header.js b/test/scripts/test-header.js index 07531dfe82..f00c470878 100644 --- a/test/scripts/test-header.js +++ b/test/scripts/test-header.js @@ -13,9 +13,11 @@ const { useApplication } = require('../utilities/useApplication.js'); const HeaderSuite = require('../public/header'); +const PresentationsSuite = require('../public/presentations/overview.test.js'); describe('Bookkeeping', () => { useApplication(); describe('Header', HeaderSuite); + describe('Presentations page', PresentationsSuite); });