diff --git a/x-pack/legacy/plugins/canvas/public/components/workpad_header/workpad_export/index.ts b/x-pack/legacy/plugins/canvas/public/components/workpad_header/workpad_export/index.ts index 7f81adad6bf9b4..949264fcc9fdb1 100644 --- a/x-pack/legacy/plugins/canvas/public/components/workpad_header/workpad_export/index.ts +++ b/x-pack/legacy/plugins/canvas/public/components/workpad_header/workpad_export/index.ts @@ -6,7 +6,7 @@ import { connect } from 'react-redux'; import { compose, withProps } from 'recompose'; -import * as jobCompletionNotifications from '../../../../../reporting/public/lib/job_completion_notifications'; +import { jobCompletionNotifications } from '../../../../../../../plugins/reporting/public'; // @ts-ignore Untyped local import { getWorkpad, getPages } from '../../../state/selectors/workpad'; // @ts-ignore Untyped local diff --git a/x-pack/legacy/plugins/reporting/index.ts b/x-pack/legacy/plugins/reporting/index.ts index 9ce4e807f8ef86..89e98302cddc91 100644 --- a/x-pack/legacy/plugins/reporting/index.ts +++ b/x-pack/legacy/plugins/reporting/index.ts @@ -10,7 +10,7 @@ import { resolve } from 'path'; import { PLUGIN_ID, UI_SETTINGS_CUSTOM_PDF_LOGO } from './common/constants'; import { config as reportingConfig } from './config'; import { legacyInit } from './server/legacy'; -import { ReportingConfigOptions, ReportingPluginSpecOptions } from './types'; +import { ReportingPluginSpecOptions } from './types'; const kbToBase64Length = (kb: number) => { return Math.floor((kb * 1024 * 8) / 6); @@ -25,20 +25,6 @@ export const reporting = (kibana: any) => { config: reportingConfig, uiExports: { - shareContextMenuExtensions: [ - 'plugins/reporting/share_context_menu/register_csv_reporting', - 'plugins/reporting/share_context_menu/register_reporting', - ], - embeddableActions: ['plugins/reporting/panel_actions/get_csv_panel_action'], - home: ['plugins/reporting/register_feature'], - managementSections: ['plugins/reporting/views/management'], - injectDefaultVars(server: Legacy.Server, options?: ReportingConfigOptions) { - const config = server.config(); - return { - reportingPollConfig: options ? options.poll : {}, - enablePanelActionDownload: config.get('xpack.reporting.csv.enablePanelActionDownload'), - }; - }, uiSettingDefaults: { [UI_SETTINGS_CUSTOM_PDF_LOGO]: { name: i18n.translate('xpack.reporting.pdfFooterImageLabel', { diff --git a/x-pack/legacy/plugins/reporting/public/components/report_info_button.test.mocks.ts b/x-pack/legacy/plugins/reporting/public/components/report_info_button.test.mocks.ts deleted file mode 100644 index 9dd7cbb5fc5678..00000000000000 --- a/x-pack/legacy/plugins/reporting/public/components/report_info_button.test.mocks.ts +++ /dev/null @@ -1,8 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -export const mockJobQueueClient = { list: jest.fn(), total: jest.fn(), getInfo: jest.fn() }; -jest.mock('../lib/job_queue_client', () => ({ jobQueueClient: mockJobQueueClient })); diff --git a/x-pack/legacy/plugins/reporting/public/components/report_listing.test.tsx b/x-pack/legacy/plugins/reporting/public/components/report_listing.test.tsx deleted file mode 100644 index 87360efe04e8bf..00000000000000 --- a/x-pack/legacy/plugins/reporting/public/components/report_listing.test.tsx +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -interface JobData { - _index: string; - _id: string; - _source: { - browser_type: string; - created_at: string; - jobtype: string; - created_by: string; - payload: { - type: string; - title: string; - }; - kibana_name?: string; // undefined if job is pending (not yet claimed by an instance) - kibana_id?: string; // undefined if job is pending (not yet claimed by an instance) - output?: { content_type: string; size: number }; // undefined if job is incomplete - completed_at?: string; // undefined if job is incomplete - }; -} - -jest.mock('ui/chrome', () => ({ - getInjected() { - return { - jobsRefresh: { - interval: 10, - intervalErrorMultiplier: 2, - }, - }; - }, -})); - -jest.mock('ui/kfetch', () => ({ - kfetch: ({ pathname }: { pathname: string }): Promise => { - if (pathname === '/api/reporting/jobs/list') { - return Promise.resolve([ - { _index: '.reporting-2019.08.18', _id: 'jzoik8dh1q2i89fb5f19znm6', _source: { payload: { layout: { id: 'preserve_layout', dimensions: { width: 1635, height: 792 } }, type: 'dashboard', title: 'Names', }, max_attempts: 3, browser_type: 'chromium', created_at: '2019-08-23T19:34:24.869Z', jobtype: 'printable_pdf', created_by: 'elastic', attempts: 0, status: 'pending', }, }, // prettier-ignore - { _index: '.reporting-2019.08.18', _type: '_doc', _id: 'jzoik7tn1q2i89fb5f60e5ve', _score: null, _source: { payload: { layout: { id: 'preserve_layout', dimensions: { width: 1635, height: 792 } }, type: 'dashboard', title: 'Names', }, max_attempts: 3, browser_type: 'chromium', created_at: '2019-08-23T19:34:24.155Z', jobtype: 'printable_pdf', created_by: 'elastic', attempts: 0, status: 'pending', }, }, // prettier-ignore - { _index: '.reporting-2019.08.18', _type: '_doc', _id: 'jzoik5tb1q2i89fb5fckchny', _score: null, _source: { payload: { layout: { id: 'png', dimensions: { width: 1898, height: 876 } }, title: 'cool dashboard', type: 'dashboard', }, max_attempts: 3, browser_type: 'chromium', created_at: '2019-08-23T19:34:21.551Z', jobtype: 'PNG', created_by: 'elastic', attempts: 0, status: 'pending', }, }, // prettier-ignore - { _index: '.reporting-2019.08.18', _type: '_doc', _id: 'jzoik5a11q2i89fb5f130t2m', _score: null, _source: { payload: { layout: { id: 'png', dimensions: { width: 1898, height: 876 } }, title: 'cool dashboard', type: 'dashboard', }, max_attempts: 3, browser_type: 'chromium', created_at: '2019-08-23T19:34:20.857Z', jobtype: 'PNG', created_by: 'elastic', attempts: 0, status: 'pending', }, }, // prettier-ignore - { _index: '.reporting-2019.08.18', _type: '_doc', _id: 'jzoik3ka1q2i89fb5fdx93g7', _score: null, _source: { payload: { layout: { id: 'preserve_layout', dimensions: { width: 1898, height: 876 } }, type: 'dashboard', title: 'cool dashboard', }, max_attempts: 3, browser_type: 'chromium', created_at: '2019-08-23T19:34:18.634Z', jobtype: 'printable_pdf', created_by: 'elastic', attempts: 0, status: 'pending', }, }, // prettier-ignore - { _index: '.reporting-2019.08.18', _type: '_doc', _id: 'jzoik2vt1q2i89fb5ffw723n', _score: null, _source: { payload: { layout: { id: 'preserve_layout', dimensions: { width: 1898, height: 876 } }, type: 'dashboard', title: 'cool dashboard', }, max_attempts: 3, browser_type: 'chromium', created_at: '2019-08-23T19:34:17.753Z', jobtype: 'printable_pdf', created_by: 'elastic', attempts: 0, status: 'pending', }, }, // prettier-ignore - { _index: '.reporting-2019.08.18', _type: '_doc', _id: 'jzoik1851q2i89fb5fdge6e7', _score: null, _source: { payload: { layout: { id: 'preserve_layout', dimensions: { width: 1080, height: 720 } }, type: 'canvas workpad', title: 'My Canvas Workpad - Dark', }, max_attempts: 3, browser_type: 'chromium', created_at: '2019-08-23T19:34:15.605Z', jobtype: 'printable_pdf', created_by: 'elastic', attempts: 0, status: 'pending', }, }, // prettier-ignore - { _index: '.reporting-2019.08.18', _type: '_doc', _id: 'jzoijyre1q2i89fb5fa7xzvi', _score: null, _source: { payload: { type: 'dashboard', title: 'tests-panels', }, max_attempts: 3, browser_type: 'chromium', created_at: '2019-08-23T19:34:12.410Z', jobtype: 'printable_pdf', created_by: 'elastic', attempts: 0, status: 'pending', }, }, // prettier-ignore - { _index: '.reporting-2019.08.18', _type: '_doc', _id: 'jzoijv5h1q2i89fb5ffklnhx', _score: null, _source: { payload: { type: 'dashboard', title: 'tests-panels', }, max_attempts: 3, browser_type: 'chromium', created_at: '2019-08-23T19:34:07.733Z', jobtype: 'printable_pdf', created_by: 'elastic', attempts: 0, status: 'pending', }, }, // prettier-ignore - { _index: '.reporting-2019.08.18', _type: '_doc', _id: 'jznhgk7r1bx789fb5f6hxok7', _score: null, _source: { kibana_name: 'spicy.local', browser_type: 'chromium', created_at: '2019-08-23T02:15:47.799Z', jobtype: 'printable_pdf', created_by: 'elastic', kibana_id: 'ca75e26c-2b7d-464f-aef0-babb67c735a0', output: { content_type: 'application/pdf', size: 877114 }, completed_at: '2019-08-23T02:15:57.707Z', payload: { type: 'dashboard (legacy)', title: 'tests-panels', }, max_attempts: 3, started_at: '2019-08-23T02:15:48.794Z', attempts: 1, status: 'completed', }, }, // prettier-ignore - ]); - } - - // query for jobs count - return Promise.resolve(18); - }, -})); - -import React from 'react'; -import { mountWithIntl } from 'test_utils/enzyme_helpers'; -import { ReportListing } from './report_listing'; - -describe('ReportListing', () => { - it('Report job listing with some items', () => { - const wrapper = mountWithIntl( - - ); - wrapper.update(); - const input = wrapper.find('[data-test-subj="reportJobListing"]'); - expect(input).toMatchSnapshot(); - }); -}); diff --git a/x-pack/legacy/plugins/reporting/public/constants/job_statuses.tsx b/x-pack/legacy/plugins/reporting/public/constants/job_statuses.tsx deleted file mode 100644 index 29c51217a5c648..00000000000000 --- a/x-pack/legacy/plugins/reporting/public/constants/job_statuses.tsx +++ /dev/null @@ -1,13 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -export enum JobStatuses { - PENDING = 'pending', - PROCESSING = 'processing', - COMPLETED = 'completed', - FAILED = 'failed', - CANCELLED = 'cancelled', -} diff --git a/x-pack/legacy/plugins/reporting/public/lib/download_report.ts b/x-pack/legacy/plugins/reporting/public/lib/download_report.ts deleted file mode 100644 index 54194c87afabc4..00000000000000 --- a/x-pack/legacy/plugins/reporting/public/lib/download_report.ts +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { npStart } from 'ui/new_platform'; -import { API_BASE_URL } from '../../common/constants'; - -const { core } = npStart; - -export function getReportURL(jobId: string) { - const apiBaseUrl = core.http.basePath.prepend(API_BASE_URL); - const downloadLink = `${apiBaseUrl}/jobs/download/${jobId}`; - - return downloadLink; -} - -export function downloadReport(jobId: string) { - const location = getReportURL(jobId); - - window.open(location); -} diff --git a/x-pack/legacy/plugins/reporting/public/lib/job_queue_client.ts b/x-pack/legacy/plugins/reporting/public/lib/job_queue_client.ts deleted file mode 100644 index 87d4174168b7f8..00000000000000 --- a/x-pack/legacy/plugins/reporting/public/lib/job_queue_client.ts +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { npStart } from 'ui/new_platform'; -import { API_LIST_URL } from '../../common/constants'; - -const { core } = npStart; - -export interface JobQueueEntry { - _id: string; - _source: any; -} - -export interface JobContent { - content: string; - content_type: boolean; -} - -export interface JobInfo { - kibana_name: string; - kibana_id: string; - browser_type: string; - created_at: string; - priority: number; - jobtype: string; - created_by: string; - timeout: number; - output: { - content_type: string; - size: number; - warnings: string[]; - }; - process_expiration: string; - completed_at: string; - payload: { - layout: { id: string; dimensions: { width: number; height: number } }; - objects: Array<{ relativeUrl: string }>; - type: string; - title: string; - forceNow: string; - browserTimezone: string; - }; - meta: { - layout: string; - objectType: string; - }; - max_attempts: number; - started_at: string; - attempts: number; - status: string; -} - -class JobQueueClient { - public list = (page = 0, jobIds: string[] = []): Promise => { - const query = { page } as any; - if (jobIds.length > 0) { - // Only getting the first 10, to prevent URL overflows - query.ids = jobIds.slice(0, 10).join(','); - } - - return core.http.get(`${API_LIST_URL}/list`, { - query, - asSystemRequest: true, - }); - }; - - public total(): Promise { - return core.http.get(`${API_LIST_URL}/count`, { - asSystemRequest: true, - }); - } - - public getContent(jobId: string): Promise { - return core.http.get(`${API_LIST_URL}/output/${jobId}`, { - asSystemRequest: true, - }); - } - - public getInfo(jobId: string): Promise { - return core.http.get(`${API_LIST_URL}/info/${jobId}`, { - asSystemRequest: true, - }); - } -} - -export const jobQueueClient = new JobQueueClient(); diff --git a/x-pack/legacy/plugins/reporting/public/lib/reporting_client.ts b/x-pack/legacy/plugins/reporting/public/lib/reporting_client.ts deleted file mode 100644 index d471dc57fc9e1b..00000000000000 --- a/x-pack/legacy/plugins/reporting/public/lib/reporting_client.ts +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import { stringify } from 'query-string'; -import { npStart } from 'ui/new_platform'; -// @ts-ignore -import rison from 'rison-node'; -import { add } from './job_completion_notifications'; - -const { core } = npStart; -const API_BASE_URL = '/api/reporting/generate'; - -interface JobParams { - [paramName: string]: any; -} - -export const getReportingJobPath = (exportType: string, jobParams: JobParams) => { - const params = stringify({ jobParams: rison.encode(jobParams) }); - - return `${core.http.basePath.prepend(API_BASE_URL)}/${exportType}?${params}`; -}; - -export const createReportingJob = async (exportType: string, jobParams: any) => { - const jobParamsRison = rison.encode(jobParams); - const resp = await core.http.post(`${API_BASE_URL}/${exportType}`, { - method: 'POST', - body: JSON.stringify({ - jobParams: jobParamsRison, - }), - }); - - add(resp.job.id); - - return resp; -}; diff --git a/x-pack/legacy/plugins/reporting/public/register_feature.ts b/x-pack/legacy/plugins/reporting/public/register_feature.ts deleted file mode 100644 index 4e8d32facfcec6..00000000000000 --- a/x-pack/legacy/plugins/reporting/public/register_feature.ts +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { i18n } from '@kbn/i18n'; -import { npSetup } from 'ui/new_platform'; -import { FeatureCatalogueCategory } from '../../../../../src/plugins/home/public'; - -const { - plugins: { home }, -} = npSetup; - -home.featureCatalogue.register({ - id: 'reporting', - title: i18n.translate('xpack.reporting.registerFeature.reportingTitle', { - defaultMessage: 'Reporting', - }), - description: i18n.translate('xpack.reporting.registerFeature.reportingDescription', { - defaultMessage: 'Manage your reports generated from Discover, Visualize, and Dashboard.', - }), - icon: 'reportingApp', - path: '/app/kibana#/management/kibana/reporting', - showOnHomePage: false, - category: FeatureCatalogueCategory.ADMIN, -}); diff --git a/x-pack/legacy/plugins/reporting/public/views/management/index.js b/x-pack/legacy/plugins/reporting/public/views/management/index.js deleted file mode 100644 index 0ed6fe09ef80a4..00000000000000 --- a/x-pack/legacy/plugins/reporting/public/views/management/index.js +++ /dev/null @@ -1,7 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import './management'; diff --git a/x-pack/legacy/plugins/reporting/public/views/management/jobs.html b/x-pack/legacy/plugins/reporting/public/views/management/jobs.html deleted file mode 100644 index 5471513d64d958..00000000000000 --- a/x-pack/legacy/plugins/reporting/public/views/management/jobs.html +++ /dev/null @@ -1,3 +0,0 @@ - -
-
\ No newline at end of file diff --git a/x-pack/legacy/plugins/reporting/public/views/management/jobs.js b/x-pack/legacy/plugins/reporting/public/views/management/jobs.js deleted file mode 100644 index 7205fad8cca533..00000000000000 --- a/x-pack/legacy/plugins/reporting/public/views/management/jobs.js +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; -import { render, unmountComponentAtNode } from 'react-dom'; -import { xpackInfo } from 'plugins/xpack_main/services/xpack_info'; - -import routes from 'ui/routes'; -import template from 'plugins/reporting/views/management/jobs.html'; - -import { ReportListing } from '../../components/report_listing'; -import { i18n } from '@kbn/i18n'; -import { I18nContext } from 'ui/i18n'; -import { MANAGEMENT_BREADCRUMB } from 'ui/management'; - -const REACT_ANCHOR_DOM_ELEMENT_ID = 'reportListingAnchor'; - -routes.when('/management/kibana/reporting', { - template, - k7Breadcrumbs: () => [ - MANAGEMENT_BREADCRUMB, - { - text: i18n.translate('xpack.reporting.breadcrumb', { - defaultMessage: 'Reporting', - }), - }, - ], - controllerAs: 'jobsCtrl', - controller($scope, kbnUrl) { - $scope.$$postDigest(() => { - const node = document.getElementById(REACT_ANCHOR_DOM_ELEMENT_ID); - if (!node) { - return; - } - - render( - - - , - node - ); - }); - - $scope.$on('$destroy', () => { - const node = document.getElementById(REACT_ANCHOR_DOM_ELEMENT_ID); - if (node) { - unmountComponentAtNode(node); - } - }); - }, -}); diff --git a/x-pack/legacy/plugins/reporting/public/views/management/management.js b/x-pack/legacy/plugins/reporting/public/views/management/management.js deleted file mode 100644 index 8643e6fa8b8b4b..00000000000000 --- a/x-pack/legacy/plugins/reporting/public/views/management/management.js +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { management } from 'ui/management'; -import { i18n } from '@kbn/i18n'; -import routes from 'ui/routes'; -import { xpackInfo } from 'plugins/xpack_main/services/xpack_info'; - -import 'plugins/reporting/views/management/jobs'; - -routes.defaults(/\/management/, { - resolve: { - reportingManagementSection: function() { - const kibanaManagementSection = management.getSection('kibana'); - const showReportingLinks = xpackInfo.get('features.reporting.management.showLinks'); - - kibanaManagementSection.deregister('reporting'); - if (showReportingLinks) { - const enableReportingLinks = xpackInfo.get('features.reporting.management.enableLinks'); - const tooltipMessage = xpackInfo.get('features.reporting.management.message'); - - let url; - let tooltip; - if (enableReportingLinks) { - url = '#/management/kibana/reporting'; - } else { - tooltip = tooltipMessage; - } - - return kibanaManagementSection.register('reporting', { - order: 15, - display: i18n.translate('xpack.reporting.management.reportingTitle', { - defaultMessage: 'Reporting', - }), - url, - tooltip, - }); - } - }, - }, -}); diff --git a/x-pack/legacy/plugins/reporting/types.d.ts b/x-pack/legacy/plugins/reporting/types.d.ts index c088adf6820959..6e79dca6eea9e0 100644 --- a/x-pack/legacy/plugins/reporting/types.d.ts +++ b/x-pack/legacy/plugins/reporting/types.d.ts @@ -23,22 +23,6 @@ export type Job = EventEmitter & { }; }; -export interface ReportingConfigOptions { - browser: BrowserConfig; - poll: { - jobCompletionNotifier: { - interval: number; - intervalErrorMultiplier: number; - }; - jobsRefresh: { - interval: number; - intervalErrorMultiplier: number; - }; - }; - queue: QueueConfig; - capture: CaptureConfig; -} - export interface NetworkPolicyRule { allow: boolean; protocol: string; diff --git a/x-pack/plugins/reporting/common/poller.ts b/x-pack/plugins/reporting/common/poller.ts new file mode 100644 index 00000000000000..919d7273062a86 --- /dev/null +++ b/x-pack/plugins/reporting/common/poller.ts @@ -0,0 +1,96 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import _ from 'lodash'; +import { PollerOptions } from '..'; + +// @TODO Maybe move to observables someday +export class Poller { + private readonly functionToPoll: () => Promise; + private readonly successFunction: (...args: any) => any; + private readonly errorFunction: (error: Error) => any; + private _isRunning: boolean; + private _timeoutId: NodeJS.Timeout | null; + private pollFrequencyInMillis: number; + private trailing: boolean; + private continuePollingOnError: boolean; + private pollFrequencyErrorMultiplier: number; + + constructor(options: PollerOptions) { + this.functionToPoll = options.functionToPoll; // Must return a Promise + this.successFunction = options.successFunction || _.noop; + this.errorFunction = options.errorFunction || _.noop; + this.pollFrequencyInMillis = options.pollFrequencyInMillis; + this.trailing = options.trailing || false; + this.continuePollingOnError = options.continuePollingOnError || false; + this.pollFrequencyErrorMultiplier = options.pollFrequencyErrorMultiplier || 1; + + this._timeoutId = null; + this._isRunning = false; + } + + getPollFrequency() { + return this.pollFrequencyInMillis; + } + + _poll() { + return this.functionToPoll() + .then(this.successFunction) + .then(() => { + if (!this._isRunning) { + return; + } + + this._timeoutId = setTimeout(this._poll.bind(this), this.pollFrequencyInMillis); + }) + .catch(e => { + this.errorFunction(e); + if (!this._isRunning) { + return; + } + + if (this.continuePollingOnError) { + this._timeoutId = setTimeout( + this._poll.bind(this), + this.pollFrequencyInMillis * this.pollFrequencyErrorMultiplier + ); + } else { + this.stop(); + } + }); + } + + start() { + if (this._isRunning) { + return; + } + + this._isRunning = true; + if (this.trailing) { + this._timeoutId = setTimeout(this._poll.bind(this), this.pollFrequencyInMillis); + } else { + this._poll(); + } + } + + stop() { + if (!this._isRunning) { + return; + } + + this._isRunning = false; + + if (this._timeoutId) { + clearTimeout(this._timeoutId); + } + + this._timeoutId = null; + } + + isRunning() { + return this._isRunning; + } +} diff --git a/x-pack/plugins/reporting/constants.ts b/x-pack/plugins/reporting/constants.ts index fe5673a0b74b5d..8f47a0a6b2ac1f 100644 --- a/x-pack/plugins/reporting/constants.ts +++ b/x-pack/plugins/reporting/constants.ts @@ -14,8 +14,31 @@ export const JOB_COMPLETION_NOTIFICATIONS_POLLER_CONFIG = { }, }; -export const API_BASE_URL = '/api/reporting/jobs'; +// Routes +export const API_BASE_URL = '/api/reporting'; +export const API_LIST_URL = `${API_BASE_URL}/jobs`; +export const API_BASE_GENERATE = `${API_BASE_URL}/generate`; +export const API_GENERATE_IMMEDIATE = `${API_BASE_URL}/v1/generate/immediate/csv/saved-object`; export const REPORTING_MANAGEMENT_HOME = '/app/kibana#/management/kibana/reporting'; +// Statuses export const JOB_STATUS_FAILED = 'failed'; export const JOB_STATUS_COMPLETED = 'completed'; + +export enum JobStatuses { + PENDING = 'pending', + PROCESSING = 'processing', + COMPLETED = 'completed', + FAILED = 'failed', + CANCELLED = 'cancelled', +} + +// Types +export const PDF_JOB_TYPE = 'printable_pdf'; +export const PNG_JOB_TYPE = 'PNG'; +export const CSV_JOB_TYPE = 'csv'; +export const CSV_FROM_SAVEDOBJECT_JOB_TYPE = 'csv_from_savedobject'; +export const USES_HEADLESS_JOB_TYPES = [PDF_JOB_TYPE, PNG_JOB_TYPE]; + +// Actions +export const CSV_REPORTING_ACTION = 'downloadCsvReport'; diff --git a/x-pack/plugins/reporting/index.d.ts b/x-pack/plugins/reporting/index.d.ts index 9559de4a5bb033..7c1a2ebd7d9de5 100644 --- a/x-pack/plugins/reporting/index.d.ts +++ b/x-pack/plugins/reporting/index.d.ts @@ -57,3 +57,19 @@ export type DownloadReportFn = (jobId: JobId) => DownloadLink; type ManagementLink = string; export type ManagementLinkFn = () => ManagementLink; + +export interface PollerOptions { + functionToPoll: () => Promise; + pollFrequencyInMillis: number; + trailing?: boolean; + continuePollingOnError?: boolean; + pollFrequencyErrorMultiplier?: number; + successFunction?: (...args: any) => any; + errorFunction?: (error: Error) => any; +} + +export interface LicenseCheckResults { + enableLinks: boolean; + showLinks: boolean; + message: string; +} diff --git a/x-pack/plugins/reporting/kibana.json b/x-pack/plugins/reporting/kibana.json index 50f552b0d9fb0d..a7e2bd288f0b1a 100644 --- a/x-pack/plugins/reporting/kibana.json +++ b/x-pack/plugins/reporting/kibana.json @@ -2,7 +2,15 @@ "id": "reporting", "version": "8.0.0", "kibanaVersion": "kibana", - "requiredPlugins": [], + "requiredPlugins": [ + "home", + "management", + "licensing", + "uiActions", + "embeddable", + "share", + "kibanaLegacy" + ], "server": false, "ui": true } diff --git a/x-pack/legacy/plugins/reporting/public/components/__snapshots__/report_info_button.test.tsx.snap b/x-pack/plugins/reporting/public/components/__snapshots__/report_info_button.test.tsx.snap similarity index 100% rename from x-pack/legacy/plugins/reporting/public/components/__snapshots__/report_info_button.test.tsx.snap rename to x-pack/plugins/reporting/public/components/__snapshots__/report_info_button.test.tsx.snap diff --git a/x-pack/legacy/plugins/reporting/public/components/__snapshots__/report_listing.test.tsx.snap b/x-pack/plugins/reporting/public/components/__snapshots__/report_listing.test.tsx.snap similarity index 100% rename from x-pack/legacy/plugins/reporting/public/components/__snapshots__/report_listing.test.tsx.snap rename to x-pack/plugins/reporting/public/components/__snapshots__/report_listing.test.tsx.snap diff --git a/x-pack/plugins/reporting/public/components/general_error.tsx b/x-pack/plugins/reporting/public/components/general_error.tsx index feb0ea0062ace8..bc1ec901cc4750 100644 --- a/x-pack/plugins/reporting/public/components/general_error.tsx +++ b/x-pack/plugins/reporting/public/components/general_error.tsx @@ -7,7 +7,7 @@ import React, { Fragment } from 'react'; import { FormattedMessage } from '@kbn/i18n/react'; import { EuiCallOut, EuiSpacer } from '@elastic/eui'; -import { ToastInput } from '../../../../../src/core/public'; +import { ToastInput } from 'src/core/public'; import { toMountPoint } from '../../../../../src/plugins/kibana_react/public'; export const getGeneralErrorToast = (errorText: string, err: Error): ToastInput => ({ diff --git a/x-pack/plugins/reporting/public/components/job_failure.tsx b/x-pack/plugins/reporting/public/components/job_failure.tsx index 7544cbf9064580..628ecb56b9c21d 100644 --- a/x-pack/plugins/reporting/public/components/job_failure.tsx +++ b/x-pack/plugins/reporting/public/components/job_failure.tsx @@ -8,7 +8,7 @@ import React, { Fragment } from 'react'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; import { EuiCallOut, EuiSpacer } from '@elastic/eui'; -import { ToastInput } from '../../../../../src/core/public'; +import { ToastInput } from 'src/core/public'; import { toMountPoint } from '../../../../../src/plugins/kibana_react/public'; import { JobSummary, ManagementLinkFn } from '../../index.d'; diff --git a/x-pack/plugins/reporting/public/components/job_queue_client.test.mocks.ts b/x-pack/plugins/reporting/public/components/job_queue_client.test.mocks.ts new file mode 100644 index 00000000000000..5e9614e27e2fd4 --- /dev/null +++ b/x-pack/plugins/reporting/public/components/job_queue_client.test.mocks.ts @@ -0,0 +1,17 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export const mockAPIClient = { + http: jest.fn(), + list: jest.fn(), + total: jest.fn(), + getInfo: jest.fn(), + getContent: jest.fn(), + getReportURL: jest.fn(), + downloadReport: jest.fn(), +}; + +jest.mock('../lib/reporting_api_client', () => mockAPIClient); diff --git a/x-pack/plugins/reporting/public/components/job_success.tsx b/x-pack/plugins/reporting/public/components/job_success.tsx index b538cef030e0d8..c2feac382ca7ad 100644 --- a/x-pack/plugins/reporting/public/components/job_success.tsx +++ b/x-pack/plugins/reporting/public/components/job_success.tsx @@ -6,7 +6,7 @@ import React, { Fragment } from 'react'; import { FormattedMessage } from '@kbn/i18n/react'; -import { ToastInput } from '../../../../../src/core/public'; +import { ToastInput } from 'src/core/public'; import { toMountPoint } from '../../../../../src/plugins/kibana_react/public'; import { JobId, JobSummary } from '../../index.d'; import { ReportLink } from './report_link'; diff --git a/x-pack/plugins/reporting/public/components/job_warning_formulas.tsx b/x-pack/plugins/reporting/public/components/job_warning_formulas.tsx index 7981237c9b7810..22f656dbe738cf 100644 --- a/x-pack/plugins/reporting/public/components/job_warning_formulas.tsx +++ b/x-pack/plugins/reporting/public/components/job_warning_formulas.tsx @@ -6,7 +6,7 @@ import React, { Fragment } from 'react'; import { FormattedMessage } from '@kbn/i18n/react'; -import { ToastInput } from '../../../../../src/core/public'; +import { ToastInput } from 'src/core/public'; import { toMountPoint } from '../../../../../src/plugins/kibana_react/public'; import { JobId, JobSummary } from '../../index.d'; import { ReportLink } from './report_link'; diff --git a/x-pack/plugins/reporting/public/components/job_warning_max_size.tsx b/x-pack/plugins/reporting/public/components/job_warning_max_size.tsx index caeda6fc01678a..1abba8888bb818 100644 --- a/x-pack/plugins/reporting/public/components/job_warning_max_size.tsx +++ b/x-pack/plugins/reporting/public/components/job_warning_max_size.tsx @@ -6,7 +6,7 @@ import React, { Fragment } from 'react'; import { FormattedMessage } from '@kbn/i18n/react'; -import { ToastInput } from '../../../../../src/core/public'; +import { ToastInput } from 'src/core/public'; import { toMountPoint } from '../../../../../src/plugins/kibana_react/public'; import { JobId, JobSummary } from '../../index.d'; import { ReportLink } from './report_link'; diff --git a/x-pack/legacy/plugins/reporting/public/components/report_error_button.tsx b/x-pack/plugins/reporting/public/components/report_error_button.tsx similarity index 92% rename from x-pack/legacy/plugins/reporting/public/components/report_error_button.tsx rename to x-pack/plugins/reporting/public/components/report_error_button.tsx index 3e6fd07847f2c3..252dee9c619a98 100644 --- a/x-pack/legacy/plugins/reporting/public/components/report_error_button.tsx +++ b/x-pack/plugins/reporting/public/components/report_error_button.tsx @@ -7,11 +7,12 @@ import { EuiButtonIcon, EuiCallOut, EuiPopover } from '@elastic/eui'; import { InjectedIntl, injectI18n } from '@kbn/i18n/react'; import React, { Component } from 'react'; -import { JobContent, jobQueueClient } from '../lib/job_queue_client'; +import { JobContent, ReportingAPIClient } from '../lib/reporting_api_client'; interface Props { jobId: string; intl: InjectedIntl; + apiClient: ReportingAPIClient; } interface State { @@ -90,7 +91,7 @@ class ReportErrorButtonUi extends Component { private loadError = async () => { this.setState({ isLoading: true }); try { - const reportContent: JobContent = await jobQueueClient.getContent(this.props.jobId); + const reportContent: JobContent = await this.props.apiClient.getContent(this.props.jobId); if (this.mounted) { this.setState({ isLoading: false, error: reportContent.content }); } diff --git a/x-pack/legacy/plugins/reporting/public/components/report_info_button.test.tsx b/x-pack/plugins/reporting/public/components/report_info_button.test.tsx similarity index 60% rename from x-pack/legacy/plugins/reporting/public/components/report_info_button.test.tsx rename to x-pack/plugins/reporting/public/components/report_info_button.test.tsx index 3b9c2a84854230..2edd59e6de7a38 100644 --- a/x-pack/legacy/plugins/reporting/public/components/report_info_button.test.tsx +++ b/x-pack/plugins/reporting/public/components/report_info_button.test.tsx @@ -4,27 +4,25 @@ * you may not use this file except in compliance with the Elastic License. */ -import { mockJobQueueClient } from './report_info_button.test.mocks'; - import React from 'react'; import { mountWithIntl } from 'test_utils/enzyme_helpers'; import { ReportInfoButton } from './report_info_button'; +import { ReportingAPIClient } from '../lib/reporting_api_client'; -describe('ReportInfoButton', () => { - beforeEach(() => { - mockJobQueueClient.getInfo = jest.fn(() => ({ - payload: { title: 'Test Job' }, - })); - }); +jest.mock('../lib/reporting_api_client'); +const httpSetup = {} as any; +const apiClient = new ReportingAPIClient(httpSetup); + +describe('ReportInfoButton', () => { it('handles button click flyout on click', () => { - const wrapper = mountWithIntl(); + const wrapper = mountWithIntl(); const input = wrapper.find('[data-test-subj="reportInfoButton"]').hostNodes(); expect(input).toMatchSnapshot(); }); - it('opens flyout with info', () => { - const wrapper = mountWithIntl(); + it('opens flyout with info', async () => { + const wrapper = mountWithIntl(); const input = wrapper.find('[data-test-subj="reportInfoButton"]').hostNodes(); input.simulate('click'); @@ -32,17 +30,17 @@ describe('ReportInfoButton', () => { const flyout = wrapper.find('[data-test-subj="reportInfoFlyout"]'); expect(flyout).toMatchSnapshot(); - expect(mockJobQueueClient.getInfo).toHaveBeenCalledTimes(1); - expect(mockJobQueueClient.getInfo).toHaveBeenCalledWith('abc-456'); + expect(apiClient.getInfo).toHaveBeenCalledTimes(1); + expect(apiClient.getInfo).toHaveBeenCalledWith('abc-456'); }); it('opens flyout with fetch error info', () => { // simulate fetch failure - mockJobQueueClient.getInfo = jest.fn(() => { + apiClient.getInfo = jest.fn(() => { throw new Error('Could not fetch the job info'); }); - const wrapper = mountWithIntl(); + const wrapper = mountWithIntl(); const input = wrapper.find('[data-test-subj="reportInfoButton"]').hostNodes(); input.simulate('click'); @@ -50,7 +48,7 @@ describe('ReportInfoButton', () => { const flyout = wrapper.find('[data-test-subj="reportInfoFlyout"]'); expect(flyout).toMatchSnapshot(); - expect(mockJobQueueClient.getInfo).toHaveBeenCalledTimes(1); - expect(mockJobQueueClient.getInfo).toHaveBeenCalledWith('abc-789'); + expect(apiClient.getInfo).toHaveBeenCalledTimes(1); + expect(apiClient.getInfo).toHaveBeenCalledWith('abc-789'); }); }); diff --git a/x-pack/legacy/plugins/reporting/public/components/report_info_button.tsx b/x-pack/plugins/reporting/public/components/report_info_button.tsx similarity index 95% rename from x-pack/legacy/plugins/reporting/public/components/report_info_button.tsx rename to x-pack/plugins/reporting/public/components/report_info_button.tsx index 7f5d070948e50a..81a5af3b87957d 100644 --- a/x-pack/legacy/plugins/reporting/public/components/report_info_button.tsx +++ b/x-pack/plugins/reporting/public/components/report_info_button.tsx @@ -17,11 +17,12 @@ import { } from '@elastic/eui'; import React, { Component, Fragment } from 'react'; import { get } from 'lodash'; -import { USES_HEADLESS_JOB_TYPES } from '../../common/constants'; -import { JobInfo, jobQueueClient } from '../lib/job_queue_client'; +import { USES_HEADLESS_JOB_TYPES } from '../../constants'; +import { JobInfo, ReportingAPIClient } from '../lib/reporting_api_client'; interface Props { jobId: string; + apiClient: ReportingAPIClient; } interface State { @@ -171,6 +172,7 @@ export class ReportInfoButton extends Component { description: USES_HEADLESS_JOB_TYPES.includes(jobType) ? info.browser_type || UNKNOWN : NA, }, ]; + if (warnings) { jobInfoStatus.push({ title: 'Errors', @@ -261,17 +263,17 @@ export class ReportInfoButton extends Component { private loadInfo = async () => { this.setState({ isLoading: true }); try { - const info: JobInfo = await jobQueueClient.getInfo(this.props.jobId); + const info: JobInfo = await this.props.apiClient.getInfo(this.props.jobId); if (this.mounted) { this.setState({ isLoading: false, info }); } - } catch (kfetchError) { + } catch (err) { if (this.mounted) { this.setState({ isLoading: false, calloutTitle: 'Unable to fetch report info', info: null, - error: kfetchError, + error: err, }); } } diff --git a/x-pack/plugins/reporting/public/components/report_listing.test.tsx b/x-pack/plugins/reporting/public/components/report_listing.test.tsx new file mode 100644 index 00000000000000..5cf894580eae03 --- /dev/null +++ b/x-pack/plugins/reporting/public/components/report_listing.test.tsx @@ -0,0 +1,85 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { mountWithIntl } from 'test_utils/enzyme_helpers'; +import { ReportListing } from './report_listing'; +import { Observable } from 'rxjs'; +import { ILicense } from '../../../licensing/public'; +import { ReportingAPIClient } from '../lib/reporting_api_client'; + +const reportingAPIClient = { + list: () => + Promise.resolve([ + { _index: '.reporting-2019.08.18', _id: 'jzoik8dh1q2i89fb5f19znm6', _source: { payload: { layout: { id: 'preserve_layout', dimensions: { width: 1635, height: 792 } }, type: 'dashboard', title: 'Names', }, max_attempts: 3, browser_type: 'chromium', created_at: '2019-08-23T19:34:24.869Z', jobtype: 'printable_pdf', created_by: 'elastic', attempts: 0, status: 'pending', }, }, // prettier-ignore + { _index: '.reporting-2019.08.18', _id: 'jzoik7tn1q2i89fb5f60e5ve', _score: null, _source: { payload: { layout: { id: 'preserve_layout', dimensions: { width: 1635, height: 792 } }, type: 'dashboard', title: 'Names', }, max_attempts: 3, browser_type: 'chromium', created_at: '2019-08-23T19:34:24.155Z', jobtype: 'printable_pdf', created_by: 'elastic', attempts: 0, status: 'pending', }, }, // prettier-ignore + { _index: '.reporting-2019.08.18', _id: 'jzoik5tb1q2i89fb5fckchny', _score: null, _source: { payload: { layout: { id: 'png', dimensions: { width: 1898, height: 876 } }, title: 'cool dashboard', type: 'dashboard', }, max_attempts: 3, browser_type: 'chromium', created_at: '2019-08-23T19:34:21.551Z', jobtype: 'PNG', created_by: 'elastic', attempts: 0, status: 'pending', }, }, // prettier-ignore + { _index: '.reporting-2019.08.18', _id: 'jzoik5a11q2i89fb5f130t2m', _score: null, _source: { payload: { layout: { id: 'png', dimensions: { width: 1898, height: 876 } }, title: 'cool dashboard', type: 'dashboard', }, max_attempts: 3, browser_type: 'chromium', created_at: '2019-08-23T19:34:20.857Z', jobtype: 'PNG', created_by: 'elastic', attempts: 0, status: 'pending', }, }, // prettier-ignore + { _index: '.reporting-2019.08.18', _id: 'jzoik3ka1q2i89fb5fdx93g7', _score: null, _source: { payload: { layout: { id: 'preserve_layout', dimensions: { width: 1898, height: 876 } }, type: 'dashboard', title: 'cool dashboard', }, max_attempts: 3, browser_type: 'chromium', created_at: '2019-08-23T19:34:18.634Z', jobtype: 'printable_pdf', created_by: 'elastic', attempts: 0, status: 'pending', }, }, // prettier-ignore + { _index: '.reporting-2019.08.18', _id: 'jzoik2vt1q2i89fb5ffw723n', _score: null, _source: { payload: { layout: { id: 'preserve_layout', dimensions: { width: 1898, height: 876 } }, type: 'dashboard', title: 'cool dashboard', }, max_attempts: 3, browser_type: 'chromium', created_at: '2019-08-23T19:34:17.753Z', jobtype: 'printable_pdf', created_by: 'elastic', attempts: 0, status: 'pending', }, }, // prettier-ignore + { _index: '.reporting-2019.08.18', _id: 'jzoik1851q2i89fb5fdge6e7', _score: null, _source: { payload: { layout: { id: 'preserve_layout', dimensions: { width: 1080, height: 720 } }, type: 'canvas workpad', title: 'My Canvas Workpad - Dark', }, max_attempts: 3, browser_type: 'chromium', created_at: '2019-08-23T19:34:15.605Z', jobtype: 'printable_pdf', created_by: 'elastic', attempts: 0, status: 'pending', }, }, // prettier-ignore + { _index: '.reporting-2019.08.18', _id: 'jzoijyre1q2i89fb5fa7xzvi', _score: null, _source: { payload: { type: 'dashboard', title: 'tests-panels', }, max_attempts: 3, browser_type: 'chromium', created_at: '2019-08-23T19:34:12.410Z', jobtype: 'printable_pdf', created_by: 'elastic', attempts: 0, status: 'pending', }, }, // prettier-ignore + { _index: '.reporting-2019.08.18', _id: 'jzoijv5h1q2i89fb5ffklnhx', _score: null, _source: { payload: { type: 'dashboard', title: 'tests-panels', }, max_attempts: 3, browser_type: 'chromium', created_at: '2019-08-23T19:34:07.733Z', jobtype: 'printable_pdf', created_by: 'elastic', attempts: 0, status: 'pending', }, }, // prettier-ignore + { _index: '.reporting-2019.08.18', _id: 'jznhgk7r1bx789fb5f6hxok7', _score: null, _source: { kibana_name: 'spicy.local', browser_type: 'chromium', created_at: '2019-08-23T02:15:47.799Z', jobtype: 'printable_pdf', created_by: 'elastic', kibana_id: 'ca75e26c-2b7d-464f-aef0-babb67c735a0', output: { content_type: 'application/pdf', size: 877114 }, completed_at: '2019-08-23T02:15:57.707Z', payload: { type: 'dashboard (legacy)', title: 'tests-panels', }, max_attempts: 3, started_at: '2019-08-23T02:15:48.794Z', attempts: 1, status: 'completed', }, }, // prettier-ignore + ]), + total: () => Promise.resolve(18), +} as any; + +const validCheck = { + check: () => ({ + state: 'VALID', + message: '', + }), +}; + +const license$ = { + subscribe: (handler: any) => { + return handler(validCheck); + }, +} as Observable; + +const toasts = { + addDanger: jest.fn(), +} as any; + +describe('ReportListing', () => { + it('Report job listing with some items', () => { + const wrapper = mountWithIntl( + + ); + wrapper.update(); + const input = wrapper.find('[data-test-subj="reportJobListing"]'); + expect(input).toMatchSnapshot(); + }); + + it('subscribes to license changes, and unsubscribes on dismount', () => { + const unsubscribeMock = jest.fn(); + const subMock = { + subscribe: jest.fn().mockReturnValue({ + unsubscribe: unsubscribeMock, + }), + } as any; + + const wrapper = mountWithIntl( + } + redirect={jest.fn()} + toasts={toasts} + /> + ); + wrapper.update(); + expect(subMock.subscribe).toHaveBeenCalled(); + expect(unsubscribeMock).not.toHaveBeenCalled(); + wrapper.unmount(); + expect(unsubscribeMock).toHaveBeenCalled(); + }); +}); diff --git a/x-pack/legacy/plugins/reporting/public/components/report_listing.tsx b/x-pack/plugins/reporting/public/components/report_listing.tsx similarity index 85% rename from x-pack/legacy/plugins/reporting/public/components/report_listing.tsx rename to x-pack/plugins/reporting/public/components/report_listing.tsx index c0fe33a3a542d1..85ccced8d75f0e 100644 --- a/x-pack/legacy/plugins/reporting/public/components/report_listing.tsx +++ b/x-pack/plugins/reporting/public/components/report_listing.tsx @@ -6,11 +6,11 @@ import { i18n } from '@kbn/i18n'; import { FormattedMessage, InjectedIntl, injectI18n } from '@kbn/i18n/react'; -import moment from 'moment'; import { get } from 'lodash'; +import moment from 'moment'; import React, { Component } from 'react'; -import chrome from 'ui/chrome'; -import { toastNotifications } from 'ui/notify'; +import { Subscription } from 'rxjs'; + import { EuiBasicTable, EuiButtonIcon, @@ -21,10 +21,13 @@ import { EuiTitle, EuiToolTip, } from '@elastic/eui'; -import { Poller } from '../../../../common/poller'; -import { JobStatuses } from '../constants/job_statuses'; -import { downloadReport } from '../lib/download_report'; -import { jobQueueClient, JobQueueEntry } from '../lib/job_queue_client'; + +import { ToastsSetup, ApplicationStart } from 'src/core/public'; +import { LicensingPluginSetup, ILicense } from '../../../licensing/public'; +import { Poller } from '../../common/poller'; +import { JobStatuses, JOB_COMPLETION_NOTIFICATIONS_POLLER_CONFIG } from '../../constants'; +import { ReportingAPIClient, JobQueueEntry } from '../lib/reporting_api_client'; +import { checkLicense } from '../lib/license_check'; import { ReportErrorButton } from './report_error_button'; import { ReportInfoButton } from './report_info_button'; @@ -47,11 +50,11 @@ interface Job { } interface Props { - badLicenseMessage: string; - showLinks: boolean; - enableLinks: boolean; - redirect: (url: string) => void; intl: InjectedIntl; + apiClient: ReportingAPIClient; + license$: LicensingPluginSetup['license$']; + redirect: ApplicationStart['navigateToApp']; + toasts: ToastsSetup; } interface State { @@ -59,6 +62,9 @@ interface State { total: number; jobs: Job[]; isLoading: boolean; + showLinks: boolean; + enableLinks: boolean; + badLicenseMessage: string; } const jobStatusLabelsMap = new Map([ @@ -95,9 +101,10 @@ const jobStatusLabelsMap = new Map([ ]); class ReportListingUi extends Component { + private isInitialJobsFetch: boolean; + private licenseSubscription?: Subscription; private mounted?: boolean; private poller?: any; - private isInitialJobsFetch: boolean; constructor(props: Props) { super(props); @@ -107,6 +114,9 @@ class ReportListingUi extends Component { total: 0, jobs: [], isLoading: false, + showLinks: false, + enableLinks: false, + badLicenseMessage: '', }; this.isInitialJobsFetch = true; @@ -137,23 +147,41 @@ class ReportListingUi extends Component { public componentWillUnmount() { this.mounted = false; this.poller.stop(); + + if (this.licenseSubscription) { + this.licenseSubscription.unsubscribe(); + } } public componentDidMount() { this.mounted = true; - const { jobsRefresh } = chrome.getInjected('reportingPollConfig'); this.poller = new Poller({ functionToPoll: () => { return this.fetchJobs(); }, - pollFrequencyInMillis: jobsRefresh.interval, + pollFrequencyInMillis: + JOB_COMPLETION_NOTIFICATIONS_POLLER_CONFIG.jobCompletionNotifier.interval, trailing: false, continuePollingOnError: true, - pollFrequencyErrorMultiplier: jobsRefresh.intervalErrorMultiplier, + pollFrequencyErrorMultiplier: + JOB_COMPLETION_NOTIFICATIONS_POLLER_CONFIG.jobCompletionNotifier.intervalErrorMultiplier, }); this.poller.start(); + this.licenseSubscription = this.props.license$.subscribe(this.licenseHandler); } + private licenseHandler = (license: ILicense) => { + const { enableLinks, showLinks, message: badLicenseMessage } = checkLicense( + license.check('reporting', 'basic') + ); + + this.setState({ + enableLinks, + showLinks, + badLicenseMessage, + }); + }; + private renderTable() { const { intl } = this.props; @@ -275,7 +303,6 @@ class ReportListingUi extends Component {
{statusLabel} {maxSizeReached} - {warnings}
); }, @@ -340,7 +367,7 @@ class ReportListingUi extends Component { const { intl } = this.props; const button = ( downloadReport(record.id)} + onClick={() => this.props.apiClient.downloadReport(record.id)} iconType="importAction" aria-label={intl.formatMessage({ id: 'xpack.reporting.listing.table.downloadReportAriaLabel', @@ -386,11 +413,11 @@ class ReportListingUi extends Component { return; } - return ; + return ; }; private renderInfoButton = (record: Job) => { - return ; + return ; }; private onTableChange = ({ page }: { page: { index: number } }) => { @@ -407,19 +434,19 @@ class ReportListingUi extends Component { let jobs: JobQueueEntry[]; let total: number; try { - jobs = await jobQueueClient.list(this.state.page); - total = await jobQueueClient.total(); + jobs = await this.props.apiClient.list(this.state.page); + total = await this.props.apiClient.total(); this.isInitialJobsFetch = false; - } catch (kfetchError) { + } catch (fetchError) { if (!this.licenseAllowsToShowThisPage()) { - toastNotifications.addDanger(this.props.badLicenseMessage); - this.props.redirect('/management'); + this.props.toasts.addDanger(this.state.badLicenseMessage); + this.props.redirect('kibana#/management'); return; } - if (kfetchError.res.status !== 401 && kfetchError.res.status !== 403) { - toastNotifications.addDanger( - kfetchError.res.statusText || + if (fetchError.message === 'Failed to fetch') { + this.props.toasts.addDanger( + fetchError.message || this.props.intl.formatMessage({ id: 'xpack.reporting.listing.table.requestFailedErrorMessage', defaultMessage: 'Request failed', @@ -463,7 +490,7 @@ class ReportListingUi extends Component { }; private licenseAllowsToShowThisPage = () => { - return this.props.showLinks && this.props.enableLinks; + return this.state.showLinks && this.state.enableLinks; }; private formatDate(timestamp: string) { diff --git a/x-pack/legacy/plugins/reporting/public/components/reporting_panel_content.tsx b/x-pack/plugins/reporting/public/components/reporting_panel_content.tsx similarity index 88% rename from x-pack/legacy/plugins/reporting/public/components/reporting_panel_content.tsx rename to x-pack/plugins/reporting/public/components/reporting_panel_content.tsx index aaf4021302a970..cf107fd7128761 100644 --- a/x-pack/legacy/plugins/reporting/public/components/reporting_panel_content.tsx +++ b/x-pack/plugins/reporting/public/components/reporting_panel_content.tsx @@ -7,12 +7,14 @@ import { EuiButton, EuiCopy, EuiForm, EuiFormRow, EuiSpacer, EuiText } from '@elastic/eui'; import { FormattedMessage, InjectedIntl, injectI18n } from '@kbn/i18n/react'; import React, { Component, ReactElement } from 'react'; -import { toastNotifications } from 'ui/notify'; import url from 'url'; -import { toMountPoint } from '../../../../../../src/plugins/kibana_react/public'; -import * as reportingClient from '../lib/reporting_client'; +import { ToastsSetup } from 'src/core/public'; +import { ReportingAPIClient } from '../lib/reporting_api_client'; +import { toMountPoint } from '../../../../../src/plugins/kibana_react/public'; interface Props { + apiClient: ReportingAPIClient; + toasts: ToastsSetup; reportType: string; layoutId: string | undefined; objectId?: string; @@ -31,23 +33,6 @@ interface State { } class ReportingPanelContentUi extends Component { - public static getDerivedStateFromProps(nextProps: Props, prevState: State) { - if (nextProps.layoutId !== prevState.layoutId) { - return { - ...prevState, - absoluteUrl: ReportingPanelContentUi.getAbsoluteReportGenerationUrl(nextProps), - }; - } - return prevState; - } - - private static getAbsoluteReportGenerationUrl = (props: Props) => { - const relativePath = reportingClient.getReportingJobPath( - props.reportType, - props.getJobParams() - ); - return url.resolve(window.location.href, relativePath); - }; private mounted?: boolean; constructor(props: Props) { @@ -55,11 +40,29 @@ class ReportingPanelContentUi extends Component { this.state = { isStale: false, - absoluteUrl: '', + absoluteUrl: this.getAbsoluteReportGenerationUrl(props), layoutId: '', }; } + private getAbsoluteReportGenerationUrl = (props: Props) => { + const relativePath = this.props.apiClient.getReportingJobPath( + props.reportType, + props.getJobParams() + ); + return url.resolve(window.location.href, relativePath); + }; + + public componentDidUpdate(prevProps: Props, prevState: State) { + if (this.props.layoutId && this.props.layoutId !== prevState.layoutId) { + this.setState({ + ...prevState, + absoluteUrl: this.getAbsoluteReportGenerationUrl(this.props), + layoutId: this.props.layoutId, + }); + } + } + public componentWillUnmount() { window.removeEventListener('hashchange', this.markAsStale); window.removeEventListener('resize', this.setAbsoluteReportGenerationUrl); @@ -188,17 +191,17 @@ class ReportingPanelContentUi extends Component { if (!this.mounted) { return; } - const absoluteUrl = ReportingPanelContentUi.getAbsoluteReportGenerationUrl(this.props); + const absoluteUrl = this.getAbsoluteReportGenerationUrl(this.props); this.setState({ absoluteUrl }); }; private createReportingJob = () => { const { intl } = this.props; - return reportingClient + return this.props.apiClient .createReportingJob(this.props.reportType, this.props.getJobParams()) .then(() => { - toastNotifications.addSuccess({ + this.props.toasts.addSuccess({ title: intl.formatMessage( { id: 'xpack.reporting.panelContent.successfullyQueuedReportNotificationTitle', @@ -218,7 +221,7 @@ class ReportingPanelContentUi extends Component { }) .catch((error: any) => { if (error.message === 'not exportable') { - return toastNotifications.addWarning({ + return this.props.toasts.addWarning({ title: intl.formatMessage( { id: 'xpack.reporting.panelContent.whatCanBeExportedWarningTitle', @@ -248,7 +251,7 @@ class ReportingPanelContentUi extends Component { /> ); - toastNotifications.addDanger({ + this.props.toasts.addDanger({ title: intl.formatMessage({ id: 'xpack.reporting.panelContent.notification.reportingErrorTitle', defaultMessage: 'Reporting error', diff --git a/x-pack/legacy/plugins/reporting/public/components/screen_capture_panel_content.tsx b/x-pack/plugins/reporting/public/components/screen_capture_panel_content.tsx similarity index 91% rename from x-pack/legacy/plugins/reporting/public/components/screen_capture_panel_content.tsx rename to x-pack/plugins/reporting/public/components/screen_capture_panel_content.tsx index cf6bb948763611..9fb74a70ff1ac0 100644 --- a/x-pack/legacy/plugins/reporting/public/components/screen_capture_panel_content.tsx +++ b/x-pack/plugins/reporting/public/components/screen_capture_panel_content.tsx @@ -7,9 +7,13 @@ import { EuiSpacer, EuiSwitch } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; import React, { Component, Fragment } from 'react'; +import { ToastsSetup } from 'src/core/public'; import { ReportingPanelContent } from './reporting_panel_content'; +import { ReportingAPIClient } from '../lib/reporting_api_client'; interface Props { + apiClient: ReportingAPIClient; + toasts: ToastsSetup; reportType: string; objectId?: string; objectType: string; @@ -38,6 +42,8 @@ export class ScreenCapturePanelContent extends Component { public render() { return ( + "path": => { - return http.fetch(`${API_BASE_URL}/list`, { - query: { page: 0, ids: jobIds.join(',') }, - method: 'GET', - }); - }; - - public getContent(http: HttpService, jobId: JobId): Promise { - return http - .fetch(`${API_BASE_URL}/output/${jobId}`, { - method: 'GET', - }) - .then((data: JobContent) => data.content); - } -} - -export const jobQueueClient = new JobQueue(); diff --git a/x-pack/plugins/reporting/public/lib/license_check.test.ts b/x-pack/plugins/reporting/public/lib/license_check.test.ts new file mode 100644 index 00000000000000..24e14969d2c81d --- /dev/null +++ b/x-pack/plugins/reporting/public/lib/license_check.test.ts @@ -0,0 +1,50 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { checkLicense } from './license_check'; +import { LicenseCheck } from '../../../licensing/public'; + +describe('License check', () => { + it('enables and shows links when licenses are good mkay', () => { + expect(checkLicense({ state: 'VALID' } as LicenseCheck)).toEqual({ + enableLinks: true, + showLinks: true, + message: '', + }); + }); + + it('disables and shows links when licenses are not valid', () => { + expect(checkLicense({ state: 'INVALID' } as LicenseCheck)).toEqual({ + enableLinks: false, + showLinks: false, + message: 'Your license does not support Reporting. Please upgrade your license.', + }); + }); + + it('shows links, but disables them, on expired licenses', () => { + expect(checkLicense({ state: 'EXPIRED' } as LicenseCheck)).toEqual({ + enableLinks: false, + showLinks: true, + message: 'You cannot use Reporting because your license has expired.', + }); + }); + + it('shows links, but disables them, when license checks are unavailable', () => { + expect(checkLicense({ state: 'UNAVAILABLE' } as LicenseCheck)).toEqual({ + enableLinks: false, + showLinks: true, + message: + 'You cannot use Reporting because license information is not available at this time.', + }); + }); + + it('shows and enables links if state is not known', () => { + expect(checkLicense({ state: 'PONYFOO' } as any)).toEqual({ + enableLinks: true, + showLinks: true, + message: '', + }); + }); +}); diff --git a/x-pack/plugins/reporting/public/lib/license_check.ts b/x-pack/plugins/reporting/public/lib/license_check.ts new file mode 100644 index 00000000000000..ca803fb38ef2a8 --- /dev/null +++ b/x-pack/plugins/reporting/public/lib/license_check.ts @@ -0,0 +1,52 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { LicenseCheckResults } from '../..'; +import { LICENSE_CHECK_STATE, LicenseCheck } from '../../../licensing/public'; + +export const checkLicense = (checkResults: LicenseCheck): LicenseCheckResults => { + switch (checkResults.state) { + case LICENSE_CHECK_STATE.Valid: { + return { + showLinks: true, + enableLinks: true, + message: '', + }; + } + + case LICENSE_CHECK_STATE.Invalid: { + return { + showLinks: false, + enableLinks: false, + message: 'Your license does not support Reporting. Please upgrade your license.', + }; + } + + case LICENSE_CHECK_STATE.Unavailable: { + return { + showLinks: true, + enableLinks: false, + message: + 'You cannot use Reporting because license information is not available at this time.', + }; + } + + case LICENSE_CHECK_STATE.Expired: { + return { + showLinks: true, + enableLinks: false, + message: 'You cannot use Reporting because your license has expired.', + }; + } + + default: { + return { + showLinks: true, + enableLinks: true, + message: '', + }; + } + } +}; diff --git a/x-pack/plugins/reporting/public/lib/reporting_api_client.ts b/x-pack/plugins/reporting/public/lib/reporting_api_client.ts new file mode 100644 index 00000000000000..ddfeb144d3cd74 --- /dev/null +++ b/x-pack/plugins/reporting/public/lib/reporting_api_client.ts @@ -0,0 +1,152 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { stringify } from 'query-string'; +import rison from 'rison-node'; + +import { HttpSetup } from 'src/core/public'; +import { add } from './job_completion_notifications'; +import { + API_LIST_URL, + API_BASE_URL, + API_BASE_GENERATE, + REPORTING_MANAGEMENT_HOME, +} from '../../constants'; +import { JobId, SourceJob } from '../..'; + +export interface JobQueueEntry { + _id: string; + _source: any; +} + +export interface JobContent { + content: string; + content_type: boolean; +} + +export interface JobInfo { + kibana_name: string; + kibana_id: string; + browser_type: string; + created_at: string; + priority: number; + jobtype: string; + created_by: string; + timeout: number; + output: { + content_type: string; + size: number; + warnings: string[]; + }; + process_expiration: string; + completed_at: string; + payload: { + layout: { id: string; dimensions: { width: number; height: number } }; + objects: Array<{ relativeUrl: string }>; + type: string; + title: string; + forceNow: string; + browserTimezone: string; + }; + meta: { + layout: string; + objectType: string; + }; + max_attempts: number; + started_at: string; + attempts: number; + status: string; +} + +interface JobParams { + [paramName: string]: any; +} + +export class ReportingAPIClient { + private http: HttpSetup; + + constructor(http: HttpSetup) { + this.http = http; + } + + public getReportURL(jobId: string) { + const apiBaseUrl = this.http.basePath.prepend(API_LIST_URL); + const downloadLink = `${apiBaseUrl}/download/${jobId}`; + + return downloadLink; + } + + public downloadReport(jobId: string) { + const location = this.getReportURL(jobId); + + window.open(location); + } + + public list = (page = 0, jobIds: string[] = []): Promise => { + const query = { page } as any; + if (jobIds.length > 0) { + // Only getting the first 10, to prevent URL overflows + query.ids = jobIds.slice(0, 10).join(','); + } + + return this.http.get(`${API_LIST_URL}/list`, { + query, + asSystemRequest: true, + }); + }; + + public total(): Promise { + return this.http.get(`${API_LIST_URL}/count`, { + asSystemRequest: true, + }); + } + + public getContent(jobId: string): Promise { + return this.http.get(`${API_LIST_URL}/output/${jobId}`, { + asSystemRequest: true, + }); + } + + public getInfo(jobId: string): Promise { + return this.http.get(`${API_LIST_URL}/info/${jobId}`, { + asSystemRequest: true, + }); + } + + public findForJobIds = (jobIds: JobId[]): Promise => { + return this.http.fetch(`${API_LIST_URL}/list`, { + query: { page: 0, ids: jobIds.join(',') }, + method: 'GET', + }); + }; + + public getReportingJobPath = (exportType: string, jobParams: JobParams) => { + const params = stringify({ jobParams: rison.encode(jobParams) }); + + return `${this.http.basePath.prepend(API_BASE_URL)}/${exportType}?${params}`; + }; + + public createReportingJob = async (exportType: string, jobParams: any) => { + const jobParamsRison = rison.encode(jobParams); + const resp = await this.http.post(`${API_BASE_GENERATE}/${exportType}`, { + method: 'POST', + body: JSON.stringify({ + jobParams: jobParamsRison, + }), + }); + + add(resp.job.id); + + return resp; + }; + + public getManagementLink = () => this.http.basePath.prepend(REPORTING_MANAGEMENT_HOME); + + public getDownloadLink = (jobId: JobId) => + this.http.basePath.prepend(`${API_LIST_URL}/download/${jobId}`); + + public getBasePath = () => this.http.basePath.get(); +} diff --git a/x-pack/plugins/reporting/public/lib/stream_handler.test.ts b/x-pack/plugins/reporting/public/lib/stream_handler.test.ts index aeba2ca5406b81..3a2c7de9ad0f0a 100644 --- a/x-pack/plugins/reporting/public/lib/stream_handler.test.ts +++ b/x-pack/plugins/reporting/public/lib/stream_handler.test.ts @@ -5,9 +5,9 @@ */ import sinon, { stub } from 'sinon'; -import { HttpSetup, NotificationsStart } from '../../../../../src/core/public'; -import { SourceJob, JobSummary, HttpService } from '../../index.d'; -import { JobQueue } from './job_queue'; +import { NotificationsStart } from 'src/core/public'; +import { SourceJob, JobSummary } from '../../index.d'; +import { ReportingAPIClient } from './reporting_api_client'; import { ReportingNotifierStreamHandler } from './stream_handler'; Object.defineProperty(window, 'sessionStorage', { @@ -44,20 +44,16 @@ const mockJobsFound = [ }, ]; -const jobQueueClientMock: JobQueue = { - findForJobIds: async (http: HttpService, jobIds: string[]) => { +const jobQueueClientMock: ReportingAPIClient = { + findForJobIds: async (jobIds: string[]) => { return mockJobsFound as SourceJob[]; }, - getContent: () => { - return Promise.resolve('this is the completed report data'); + getContent: (): Promise => { + return Promise.resolve({ content: 'this is the completed report data' }); }, -}; - -const httpMock: HttpService = ({ - basePath: { - prepend: stub(), - }, -} as unknown) as HttpSetup; + getManagementLink: () => '/#management', + getDownloadLink: () => '/reporting/download/job-123', +} as any; const mockShowDanger = stub(); const mockShowSuccess = stub(); @@ -76,17 +72,13 @@ describe('stream handler', () => { }); it('constructs', () => { - const sh = new ReportingNotifierStreamHandler(httpMock, notificationsMock, jobQueueClientMock); + const sh = new ReportingNotifierStreamHandler(notificationsMock, jobQueueClientMock); expect(sh).not.toBe(null); }); describe('findChangedStatusJobs', () => { it('finds no changed status jobs from empty', done => { - const sh = new ReportingNotifierStreamHandler( - httpMock, - notificationsMock, - jobQueueClientMock - ); + const sh = new ReportingNotifierStreamHandler(notificationsMock, jobQueueClientMock); const findJobs = sh.findChangedStatusJobs([]); findJobs.subscribe(data => { expect(data).toEqual({ completed: [], failed: [] }); @@ -95,11 +87,7 @@ describe('stream handler', () => { }); it('finds changed status jobs', done => { - const sh = new ReportingNotifierStreamHandler( - httpMock, - notificationsMock, - jobQueueClientMock - ); + const sh = new ReportingNotifierStreamHandler(notificationsMock, jobQueueClientMock); const findJobs = sh.findChangedStatusJobs([ 'job-source-mock1', 'job-source-mock2', @@ -115,11 +103,7 @@ describe('stream handler', () => { describe('showNotifications', () => { it('show success', done => { - const sh = new ReportingNotifierStreamHandler( - httpMock, - notificationsMock, - jobQueueClientMock - ); + const sh = new ReportingNotifierStreamHandler(notificationsMock, jobQueueClientMock); sh.showNotifications({ completed: [ { @@ -140,11 +124,7 @@ describe('stream handler', () => { }); it('show max length warning', done => { - const sh = new ReportingNotifierStreamHandler( - httpMock, - notificationsMock, - jobQueueClientMock - ); + const sh = new ReportingNotifierStreamHandler(notificationsMock, jobQueueClientMock); sh.showNotifications({ completed: [ { @@ -166,11 +146,7 @@ describe('stream handler', () => { }); it('show csv formulas warning', done => { - const sh = new ReportingNotifierStreamHandler( - httpMock, - notificationsMock, - jobQueueClientMock - ); + const sh = new ReportingNotifierStreamHandler(notificationsMock, jobQueueClientMock); sh.showNotifications({ completed: [ { @@ -192,11 +168,7 @@ describe('stream handler', () => { }); it('show failed job toast', done => { - const sh = new ReportingNotifierStreamHandler( - httpMock, - notificationsMock, - jobQueueClientMock - ); + const sh = new ReportingNotifierStreamHandler(notificationsMock, jobQueueClientMock); sh.showNotifications({ completed: [], failed: [ @@ -217,11 +189,7 @@ describe('stream handler', () => { }); it('show multiple toast', done => { - const sh = new ReportingNotifierStreamHandler( - httpMock, - notificationsMock, - jobQueueClientMock - ); + const sh = new ReportingNotifierStreamHandler(notificationsMock, jobQueueClientMock); sh.showNotifications({ completed: [ { diff --git a/x-pack/plugins/reporting/public/lib/stream_handler.ts b/x-pack/plugins/reporting/public/lib/stream_handler.ts index e58e90d3de8ef7..1aae30f6fdfb0d 100644 --- a/x-pack/plugins/reporting/public/lib/stream_handler.ts +++ b/x-pack/plugins/reporting/public/lib/stream_handler.ts @@ -11,19 +11,16 @@ import { JOB_COMPLETION_NOTIFICATIONS_SESSION_KEY, JOB_STATUS_COMPLETED, JOB_STATUS_FAILED, - API_BASE_URL, - REPORTING_MANAGEMENT_HOME, } from '../../constants'; + import { JobId, JobSummary, JobStatusBuckets, - HttpService, NotificationsService, SourceJob, - DownloadReportFn, - ManagementLinkFn, } from '../../index.d'; + import { getSuccessToast, getFailureToast, @@ -31,7 +28,7 @@ import { getWarningMaxSizeToast, getGeneralErrorToast, } from '../components'; -import { jobQueueClient as defaultJobQueueClient } from './job_queue'; +import { ReportingAPIClient } from './reporting_api_client'; function updateStored(jobIds: JobId[]): void { sessionStorage.setItem(JOB_COMPLETION_NOTIFICATIONS_SESSION_KEY, JSON.stringify(jobIds)); @@ -49,21 +46,7 @@ function summarizeJob(src: SourceJob): JobSummary { } export class ReportingNotifierStreamHandler { - private getManagementLink: ManagementLinkFn; - private getDownloadLink: DownloadReportFn; - - constructor( - private http: HttpService, - private notifications: NotificationsService, - private jobQueueClient = defaultJobQueueClient - ) { - this.getManagementLink = () => { - return http.basePath.prepend(REPORTING_MANAGEMENT_HOME); - }; - this.getDownloadLink = (jobId: JobId) => { - return http.basePath.prepend(`${API_BASE_URL}/download/${jobId}`); - }; - } + constructor(private notifications: NotificationsService, private apiClient: ReportingAPIClient) {} /* * Use Kibana Toast API to show our messages @@ -77,23 +60,33 @@ export class ReportingNotifierStreamHandler { for (const job of completedJobs) { if (job.csvContainsFormulas) { this.notifications.toasts.addWarning( - getWarningFormulasToast(job, this.getManagementLink, this.getDownloadLink) + getWarningFormulasToast( + job, + this.apiClient.getManagementLink, + this.apiClient.getDownloadLink + ) ); } else if (job.maxSizeReached) { this.notifications.toasts.addWarning( - getWarningMaxSizeToast(job, this.getManagementLink, this.getDownloadLink) + getWarningMaxSizeToast( + job, + this.apiClient.getManagementLink, + this.apiClient.getDownloadLink + ) ); } else { this.notifications.toasts.addSuccess( - getSuccessToast(job, this.getManagementLink, this.getDownloadLink) + getSuccessToast(job, this.apiClient.getManagementLink, this.apiClient.getDownloadLink) ); } } // no download link available for (const job of failedJobs) { - const content = await this.jobQueueClient.getContent(this.http, job.id); - this.notifications.toasts.addDanger(getFailureToast(content, job, this.getManagementLink)); + const { content } = await this.apiClient.getContent(job.id); + this.notifications.toasts.addDanger( + getFailureToast(content, job, this.apiClient.getManagementLink) + ); } return { completed: completedJobs, failed: failedJobs }; }; @@ -106,7 +99,7 @@ export class ReportingNotifierStreamHandler { * session storage) but have non-processing job status on the server */ public findChangedStatusJobs(storedJobs: JobId[]): Rx.Observable { - return Rx.from(this.jobQueueClient.findForJobIds(this.http, storedJobs)).pipe( + return Rx.from(this.apiClient.findForJobIds(storedJobs)).pipe( map((jobs: SourceJob[]) => { const completedJobs: JobSummary[] = []; const failedJobs: JobSummary[] = []; diff --git a/x-pack/legacy/plugins/reporting/public/panel_actions/get_csv_panel_action.tsx b/x-pack/plugins/reporting/public/panel_actions/get_csv_panel_action.tsx similarity index 72% rename from x-pack/legacy/plugins/reporting/public/panel_actions/get_csv_panel_action.tsx rename to x-pack/plugins/reporting/public/panel_actions/get_csv_panel_action.tsx index 5ba6c4870c1a7d..c5cfa7696b391c 100644 --- a/x-pack/legacy/plugins/reporting/public/panel_actions/get_csv_panel_action.tsx +++ b/x-pack/plugins/reporting/public/panel_actions/get_csv_panel_action.tsx @@ -7,24 +7,21 @@ import dateMath from '@elastic/datemath'; import { i18n } from '@kbn/i18n'; import moment from 'moment-timezone'; - -import { npSetup, npStart } from 'ui/new_platform'; -import { - ActionByType, - IncompatibleActionError, -} from '../../../../../../src/plugins/ui_actions/public'; +import { CoreSetup } from 'src/core/public'; +import { Action, IncompatibleActionError } from '../../../../../src/plugins/ui_actions/public'; +import { LicensingPluginSetup } from '../../../licensing/public'; +import { checkLicense } from '../lib/license_check'; import { ViewMode, IEmbeddable, - CONTEXT_MENU_TRIGGER, -} from '../../../../../../src/legacy/core_plugins/embeddable_api/public/np_ready/public'; -import { SEARCH_EMBEDDABLE_TYPE } from '../../../../../../src/legacy/core_plugins/kibana/public/discover/np_ready/embeddable/constants'; -import { ISearchEmbeddable } from '../../../../../../src/legacy/core_plugins/kibana/public/discover/np_ready/embeddable/types'; +} from '../../../../../src/legacy/core_plugins/embeddable_api/public/np_ready/public'; -import { API_GENERATE_IMMEDIATE, CSV_REPORTING_ACTION } from '../../common/constants'; +// @TODO: These import paths will need to be updated once discovery moves to non-legacy dir +import { SEARCH_EMBEDDABLE_TYPE } from '../../../../../src/legacy/core_plugins/kibana/public/discover/np_ready/embeddable/constants'; +import { ISearchEmbeddable } from '../../../../../src/legacy/core_plugins/kibana/public/discover/np_ready/embeddable/types'; -const { core } = npStart; +import { API_GENERATE_IMMEDIATE, CSV_REPORTING_ACTION } from '../../constants'; function isSavedSearchEmbeddable( embeddable: IEmbeddable | ISearchEmbeddable @@ -32,23 +29,26 @@ function isSavedSearchEmbeddable( return embeddable.type === SEARCH_EMBEDDABLE_TYPE; } -export interface CSVActionContext { +interface ActionContext { embeddable: ISearchEmbeddable; } -declare module '../../../../../../src/plugins/ui_actions/public' { - export interface ActionContextMapping { - [CSV_REPORTING_ACTION]: CSVActionContext; - } -} - -class GetCsvReportPanelAction implements ActionByType { +export class GetCsvReportPanelAction implements Action { private isDownloading: boolean; - public readonly type = CSV_REPORTING_ACTION; + public readonly type = ''; public readonly id = CSV_REPORTING_ACTION; + private canDownloadCSV: boolean = false; + private core: CoreSetup; - constructor() { + constructor(core: CoreSetup, license$: LicensingPluginSetup['license$']) { this.isDownloading = false; + this.core = core; + + license$.subscribe(license => { + const results = license.check('reporting', 'basic'); + const { showLinks } = checkLicense(results); + this.canDownloadCSV = showLinks; + }); } public getIconType() { @@ -74,13 +74,17 @@ class GetCsvReportPanelAction implements ActionByType { + public isCompatible = async (context: ActionContext) => { + if (!this.canDownloadCSV) { + return false; + } + const { embeddable } = context; return embeddable.getInput().viewMode !== ViewMode.EDIT && embeddable.type === 'search'; }; - public execute = async (context: CSVActionContext) => { + public execute = async (context: ActionContext) => { const { embeddable } = context; if (!isSavedSearchEmbeddable(embeddable)) { @@ -98,7 +102,7 @@ class GetCsvReportPanelAction implements ActionByType { this.isDownloading = false; @@ -161,7 +165,7 @@ class GetCsvReportPanelAction implements ActionByType { private readonly stop$ = new Rx.ReplaySubject(1); - // FIXME: License checking: only active, non-expired licenses allowed - // Depends on https://github.com/elastic/kibana/pull/44922 + private readonly title = i18n.translate('xpack.reporting.management.reportingTitle', { + defaultMessage: 'Reporting', + }); + + private readonly breadcrumbText = i18n.translate('xpack.reporting.breadcrumb', { + defaultMessage: 'Reporting', + }); + constructor(initializerContext: PluginInitializerContext) {} - public setup(core: CoreSetup) {} + public setup( + core: CoreSetup, + { + home, + management, + licensing, + uiActions, + share, + }: { + home: HomePublicPluginSetup; + management: ManagementSetup; + licensing: LicensingPluginSetup; + uiActions: UiActionsSetup; + share: SharePluginSetup; + } + ) { + const { + http, + notifications: { toasts }, + getStartServices, + uiSettings, + } = core; + const { license$ } = licensing; + + const apiClient = new ReportingAPIClient(http); + const action = new GetCsvReportPanelAction(core, license$); + + home.featureCatalogue.register({ + id: 'reporting', + title: i18n.translate('xpack.reporting.registerFeature.reportingTitle', { + defaultMessage: 'Reporting', + }), + description: i18n.translate('xpack.reporting.registerFeature.reportingDescription', { + defaultMessage: 'Manage your reports generated from Discover, Visualize, and Dashboard.', + }), + icon: 'reportingApp', + path: '/app/kibana#/management/kibana/reporting', + showOnHomePage: false, + category: FeatureCatalogueCategory.ADMIN, + }); + + management.sections.getSection('kibana')!.registerApp({ + id: 'reporting', + title: this.title, + order: 15, + mount: async params => { + const [start] = await getStartServices(); + params.setBreadcrumbs([{ text: this.breadcrumbText }]); + ReactDOM.render( + + + , + params.element + ); + + return () => { + ReactDOM.unmountComponentAtNode(params.element); + }; + }, + }); + + uiActions.registerAction(action); + uiActions.attachAction(CONTEXT_MENU_TRIGGER, action); + + share.register(csvReportingProvider({ apiClient, toasts, license$ })); + share.register( + reportingPDFPNGProvider({ + apiClient, + toasts, + license$, + uiSettings, + }) + ); + } // FIXME: only perform these actions for authenticated routes // Depends on https://github.com/elastic/kibana/pull/39477 public start(core: CoreStart) { const { http, notifications } = core; - const streamHandler = new StreamHandler(http, notifications); + const apiClient = new ReportingAPIClient(http); + const streamHandler = new StreamHandler(notifications, apiClient); Rx.timer(0, JOBS_REFRESH_INTERVAL) .pipe( diff --git a/x-pack/legacy/plugins/reporting/public/share_context_menu/register_csv_reporting.tsx b/x-pack/plugins/reporting/public/share_context_menu/register_csv_reporting.tsx similarity index 61% rename from x-pack/legacy/plugins/reporting/public/share_context_menu/register_csv_reporting.tsx rename to x-pack/plugins/reporting/public/share_context_menu/register_csv_reporting.tsx index 3c9d1d7262587b..9d4f475cde79a8 100644 --- a/x-pack/legacy/plugins/reporting/public/share_context_menu/register_csv_reporting.tsx +++ b/x-pack/plugins/reporting/public/share_context_menu/register_csv_reporting.tsx @@ -5,14 +5,34 @@ */ import { i18n } from '@kbn/i18n'; -// @ts-ignore: implicit any for JS file -import { xpackInfo } from 'plugins/xpack_main/services/xpack_info'; import React from 'react'; -import { npSetup } from 'ui/new_platform'; + +import { ToastsSetup } from 'src/core/public'; import { ReportingPanelContent } from '../components/reporting_panel_content'; -import { ShareContext } from '../../../../../../src/plugins/share/public'; +import { ReportingAPIClient } from '../lib/reporting_api_client'; +import { checkLicense } from '../lib/license_check'; +import { LicensingPluginSetup } from '../../../licensing/public'; +import { ShareContext } from '../../../../../src/plugins/share/public'; + +interface ReportingProvider { + apiClient: ReportingAPIClient; + toasts: ToastsSetup; + license$: LicensingPluginSetup['license$']; +} + +export const csvReportingProvider = ({ apiClient, toasts, license$ }: ReportingProvider) => { + let toolTipContent = ''; + let disabled = true; + let hasCSVReporting = false; + + license$.subscribe(license => { + const { enableLinks, showLinks, message } = checkLicense(license.check('reporting', 'basic')); + + toolTipContent = message; + hasCSVReporting = showLinks; + disabled = !enableLinks; + }); -function reportingProvider() { const getShareMenuItems = ({ objectType, objectId, @@ -32,7 +52,8 @@ function reportingProvider() { }; const shareActions = []; - if (xpackInfo.get('features.reporting.csv.showLinks', false)) { + + if (hasCSVReporting) { const panelTitle = i18n.translate('xpack.reporting.shareContextMenu.csvReportsButtonLabel', { defaultMessage: 'CSV Reports', }); @@ -41,8 +62,8 @@ function reportingProvider() { shareMenuItem: { name: panelTitle, icon: 'document', - toolTipContent: xpackInfo.get('features.reporting.csv.message'), - disabled: !xpackInfo.get('features.reporting.csv.enableLinks', false) ? true : false, + toolTipContent, + disabled, ['data-test-subj']: 'csvReportMenuItem', sortOrder: 1, }, @@ -51,6 +72,8 @@ function reportingProvider() { title: panelTitle, content: ( { + let toolTipContent = ''; + let disabled = true; + let hasPDFPNGReporting = false; -const { core } = npSetup; + license$.subscribe(license => { + const { enableLinks, showLinks, message } = checkLicense(license.check('reporting', 'gold')); + + toolTipContent = message; + hasPDFPNGReporting = showLinks; + disabled = !enableLinks; + }); -async function reportingProvider() { const getShareMenuItems = ({ objectType, objectId, @@ -29,24 +52,22 @@ async function reportingProvider() { } // Dashboard only mode does not currently support reporting // https://github.com/elastic/kibana/issues/18286 - if ( - objectType === 'dashboard' && - npStart.plugins.kibanaLegacy.dashboardConfig.getHideWriteControls() - ) { + // @TODO For NP + if (objectType === 'dashboard' && false) { return []; } const getReportingJobParams = () => { // Replace hashes with original RISON values. const relativeUrl = shareableUrl.replace( - window.location.origin + core.http.basePath.get(), + window.location.origin + apiClient.getBasePath(), '' ); const browserTimezone = - core.uiSettings.get('dateFormat:tz') === 'Browser' + uiSettings.get('dateFormat:tz') === 'Browser' ? moment.tz.guess() - : core.uiSettings.get('dateFormat:tz'); + : uiSettings.get('dateFormat:tz'); return { ...sharingData, @@ -59,14 +80,14 @@ async function reportingProvider() { const getPngJobParams = () => { // Replace hashes with original RISON values. const relativeUrl = shareableUrl.replace( - window.location.origin + core.http.basePath.get(), + window.location.origin + apiClient.getBasePath(), '' ); const browserTimezone = - core.uiSettings.get('dateFormat:tz') === 'Browser' + uiSettings.get('dateFormat:tz') === 'Browser' ? moment.tz.guess() - : core.uiSettings.get('dateFormat:tz'); + : uiSettings.get('dateFormat:tz'); return { ...sharingData, @@ -77,60 +98,69 @@ async function reportingProvider() { }; const shareActions = []; - if (xpackInfo.get('features.reporting.printablePdf.showLinks', false)) { - const panelTitle = i18n.translate('xpack.reporting.shareContextMenu.pdfReportsButtonLabel', { - defaultMessage: 'PDF Reports', - }); + + if (hasPDFPNGReporting) { + const pngPanelTitle = i18n.translate( + 'xpack.reporting.shareContextMenu.pngReportsButtonLabel', + { + defaultMessage: 'PNG Reports', + } + ); + + const pdfPanelTitle = i18n.translate( + 'xpack.reporting.shareContextMenu.pdfReportsButtonLabel', + { + defaultMessage: 'PDF Reports', + } + ); shareActions.push({ shareMenuItem: { - name: panelTitle, + name: pngPanelTitle, icon: 'document', - toolTipContent: xpackInfo.get('features.reporting.printablePdf.message'), - disabled: !xpackInfo.get('features.reporting.printablePdf.enableLinks', false) - ? true - : false, - ['data-test-subj']: 'pdfReportMenuItem', + toolTipContent, + disabled, + ['data-test-subj']: 'pngReportMenuItem', sortOrder: 10, }, panel: { - id: 'reportingPdfPanel', - title: panelTitle, + id: 'reportingPngPanel', + title: pngPanelTitle, content: ( ), }, }); - } - - if (xpackInfo.get('features.reporting.png.showLinks', false)) { - const panelTitle = 'PNG Reports'; shareActions.push({ shareMenuItem: { - name: panelTitle, + name: pdfPanelTitle, icon: 'document', - toolTipContent: xpackInfo.get('features.reporting.png.message'), - disabled: !xpackInfo.get('features.reporting.png.enableLinks', false) ? true : false, - ['data-test-subj']: 'pngReportMenuItem', + toolTipContent, + disabled, + ['data-test-subj']: 'pdfReportMenuItem', sortOrder: 10, }, panel: { - id: 'reportingPngPanel', - title: panelTitle, + id: 'reportingPdfPanel', + title: pdfPanelTitle, content: ( @@ -146,8 +176,4 @@ async function reportingProvider() { id: 'screenCaptureReports', getShareMenuItems, }; -} - -(async () => { - npSetup.plugins.share.register(await reportingProvider()); -})(); +};