Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

10.7 KB
Raw Blame
import { describe, expect, it } from 'vitest';
import type { SelectedResource } from '../ResourcePicker';
import { buildReportingRequest, getReportingRangeStart } from '../reportingPanelModel';
import type { ReportingPerformanceReportDefinition } from '../reportingCatalogModel';
import {
  buildReportSchedulePayload,
  parseReportSchedulesResponse,
  reportScheduleCadenceLabel,
  reportScheduleDeliveryLabel,
} from '../reportingSchedulesModel';

const performanceDefinition: ReportingPerformanceReportDefinition = {
  id: 'performance_reports',
  title: 'Performance Reports',
  description: 'Historical performance reporting',
  singleResourceEndpoint: '/api/admin/reports/generate',
  singleResourceMethod: 'POST',
  multiResourceEndpoint: '/api/admin/reports/generate-multi',
  singleFilenamePrefix: 'report',
  singleFilenameSubject: 'resource_id',
  multiFilenamePrefix: 'fleet-report',
  filenameDateStyle: 'utc_yyyymmdd',
  formats: [
    { value: 'pdf', label: 'PDF Report' },
    { value: 'csv', label: 'CSV Data' },
  ],
  defaultFormat: 'pdf',
  ranges: [
    {
      key: '24h',
      label: 'Last 24 Hours',
      description: 'Daily review',
      windowHours: 24,
    },
    {
      key: '7d',
      label: 'Last 7 Days',
      description: 'Weekly review',
      windowHours: 168,
    },
    {
      key: '30d',
      label: 'Last 30 Days',
      description: 'Monthly review',
      windowHours: 720,
    },
  ],
  defaultRange: '24h',
  multiResourceMax: 50,
  supportsMetricFilter: true,
  supportsCustomTitle: true,
};

describe('reporting panel model', () => {
  it('builds a single-resource reporting request and filename', () => {
    const now = new Date('2026-03-20T12:34:56.000Z');
    const resources: SelectedResource[] = [
      {
        id: 'agent-1',
        type: 'agent',
        name: 'node-a',
      },
    ];

    const request = buildReportingRequest(
      {
        end: now.toISOString(),
        format: 'pdf',
        metricType: 'cpu',
        now,
        resources,
        start: '2026-03-19T12:34:56.000Z',
        title: '',
      },
      performanceDefinition,
    );

    expect(request.filename).toBe('report-agent-1-20260320.pdf');
    // POST, never GET: only POST may narrate the PDF with Pulse Assistant.
    expect(request.request.url).toBe('/api/admin/reports/generate');
    expect(request.request.init).toMatchObject({
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
    });
    expect(JSON.parse(String(request.request.init?.body))).toEqual({
      resourceType: 'agent',
      resourceId: 'agent-1',
      format: 'pdf',
      start: '2026-03-19T12:34:56.000Z',
      end: now.toISOString(),
      metricType: 'cpu',
    });
  });

  it('keeps the query-string GET transport for backends whose catalog names GET', () => {
    const now = new Date('2026-03-20T12:34:56.000Z');
    const request = buildReportingRequest(
      {
        end: now.toISOString(),
        format: 'csv',
        metricType: 'cpu',
        now,
        resources: [{ id: 'vm-1', type: 'vm', name: 'vm-a' }],
        start: '2026-03-19T12:34:56.000Z',
        title: '',
      },
      {
        ...performanceDefinition,
        singleResourceEndpoint: '/api/reporting',
        singleResourceMethod: 'GET',
      },
    );

    expect(request.request.init).toBeUndefined();
    const url = new URL(request.request.url, 'http://pulse.local');
    expect(url.pathname).toBe('/api/reporting');
    expect(Object.fromEntries(url.searchParams)).toEqual({
      resourceType: 'vm',
      resourceId: 'vm-1',
      format: 'csv',
      start: '2026-03-19T12:34:56.000Z',
      end: now.toISOString(),
      metricType: 'cpu',
    });
  });

  it('builds a fleet reporting request body and filename', () => {
    const now = new Date('2026-03-20T12:34:56.000Z');
    const resources: SelectedResource[] = [
      {
        id: 'agent-1',
        type: 'agent',
        name: 'node-a',
      },
      {
        id: 'vm-1',
        type: 'vm',
        name: 'vm-a',
      },
    ];

    const request = buildReportingRequest(
      {
        end: now.toISOString(),
        format: 'csv',
        metricType: '',
        now,
        resources,
        start: '2026-03-19T12:34:56.000Z',
        title: '',
      },
      performanceDefinition,
    );

    expect(request.filename).toBe('fleet-report-20260320.csv');
    expect(request.request.url).toBe('/api/admin/reports/generate-multi');
    expect(request.request.init).toMatchObject({
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
    });
    expect(request.request.init?.body).toBe(
      JSON.stringify({
        resources: [
          { resourceType: 'agent', resourceId: 'agent-1' },
          { resourceType: 'vm', resourceId: 'vm-1' },
        ],
        format: 'csv',
        start: '2026-03-19T12:34:56.000Z',
        end: now.toISOString(),
        metricType: undefined,
      }),
    );
  });

  it('omits unsupported metric filters and custom titles from the request contract', () => {
    const now = new Date('2026-03-20T12:34:56.000Z');
    const resources: SelectedResource[] = [
      {
        id: 'vm-1',
        type: 'vm',
        name: 'vm-a',
      },
    ];

    const request = buildReportingRequest(
      {
        end: now.toISOString(),
        format: 'pdf',
        metricType: 'cpu',
        now,
        resources,
        start: '2026-03-19T12:34:56.000Z',
        title: 'Custom fleet title',
      },
      {
        ...performanceDefinition,
        supportsMetricFilter: false,
        supportsCustomTitle: false,
      },
    );

    const body = JSON.parse(String(request.request.init?.body));
    expect(body).not.toHaveProperty('title');
    expect(body).not.toHaveProperty('metricType');
  });

  it('passes through explicit custom titles without inventing defaults', () => {
    const now = new Date('2026-03-20T12:34:56.000Z');
    const resources: SelectedResource[] = [
      {
        id: 'vm-1',
        type: 'vm',
        name: 'vm-a',
      },
    ];

    const request = buildReportingRequest(
      {
        end: now.toISOString(),
        format: 'pdf',
        metricType: '',
        now,
        resources,
        start: '2026-03-19T12:34:56.000Z',
        title: 'Custom report title',
      },
      performanceDefinition,
    );

    expect(JSON.parse(String(request.request.init?.body)).title).toBe('Custom report title');
  });

  it('derives canonical range starts from the selected preset', () => {
    const now = new Date('2026-03-20T12:00:00.000Z');

    expect(getReportingRangeStart('24h', now, performanceDefinition).toISOString()).toBe(
      '2026-03-19T12:00:00.000Z',
    );
    expect(getReportingRangeStart('7d', now, performanceDefinition).toISOString()).toBe(
      '2026-03-13T12:00:00.000Z',
    );
    expect(getReportingRangeStart('30d', now, performanceDefinition).toISOString()).toBe(
      '2026-02-18T12:00:00.000Z',
    );
  });

  it('falls back to the backend-defined default range instead of a frontend constant', () => {
    const now = new Date('2026-03-20T12:00:00.000Z');

    expect(
      getReportingRangeStart('missing', now, {
        ...performanceDefinition,
        defaultRange: '7d',
      }).toISOString(),
    ).toBe('2026-03-13T12:00:00.000Z');
  });

  it('uses backend-defined endpoints and filename prefixes without frontend fallbacks', () => {
    const now = new Date('2026-03-20T12:34:56.000Z');
    const resources: SelectedResource[] = [
      {
        id: 'agent-1',
        type: 'agent',
        name: 'node-a',
      },
      {
        id: 'vm-1',
        type: 'vm',
        name: 'vm-a',
      },
    ];

    const request = buildReportingRequest(
      {
        end: now.toISOString(),
        format: 'csv',
        metricType: '',
        now,
        resources,
        start: '2026-03-19T12:34:56.000Z',
        title: '',
      },
      {
        ...performanceDefinition,
        multiResourceEndpoint: '/api/custom/reports/export',
        multiFilenamePrefix: 'estate',
      },
    );

    expect(request.filename).toBe('estate-20260320.csv');
    expect(request.request.url).toBe('/api/custom/reports/export');
  });

  it('sanitizes single-resource fallback filenames from the canonical resource id contract', () => {
    const now = new Date('2026-03-20T12:34:56.000Z');
    const resources: SelectedResource[] = [
      {
        id: 'lab/node:"quoted"\nvm',
        type: 'agent',
        name: 'node-a',
      },
    ];

    const request = buildReportingRequest(
      {
        end: now.toISOString(),
        format: 'pdf',
        metricType: '',
        now,
        resources,
        start: '2026-03-19T12:34:56.000Z',
        title: '',
      },
      performanceDefinition,
    );

    expect(request.filename).toBe('report-lab-node-quotedvm-20260320.pdf');
  });

  it('builds scheduled report payloads with explicit workspace scope and delivery', () => {
    const payload = buildReportSchedulePayload(
      {
        id: '',
        name: ' Acme monthly ',
        kind: 'resources',
        enabled: true,
        cadenceType: 'monthly',
        dayOfMonth: 1,
        weekday: 'monday',
        time: '06:00',
        timezone: 'Europe/London',
        format: 'pdf',
        deliveryMethod: 'email',
        recipients: '[email protected], [email protected], [email protected]',
        attach: true,
        saveToDisk: true,
        tagFilter: 'client:acme, client:acme',
        retentionCount: 12,
      },
      [
        {
          id: 'agent-1',
          type: 'agent',
          name: 'pve-a',
        },
      ],
    );

    expect(payload).toMatchObject({
      id: '',
      name: 'Acme monthly',
      enabled: true,
      cadence: {
        type: 'monthly',
        day_of_month: 1,
        time: '06:00',
        timezone: 'Europe/London',
      },
      scope: {
        resources: [{ resourceType: 'agent', resourceId: 'agent-1', name: 'pve-a' }],
        tags: ['client:acme'],
      },
      format: 'pdf',
      delivery: {
        method: 'email',
        to: ['[email protected]', '[email protected]'],
        attach: true,
        save_to_disk: true,
      },
      retention_count: 12,
    });
  });

  it('normalizes scheduled report labels from the API response contract', () => {
    const [schedule] = parseReportSchedulesResponse({
      schedules: [
        {
          id: 'weekly',
          name: 'Weekly report',
          enabled: true,
          cadence: { type: 'weekly', weekday: 'friday', time: '08:15', timezone: 'UTC' },
          scope: { resources: [], tags: ['client:acme'] },
          format: 'csv',
          delivery: { method: 'disk', attach: false, save_to_disk: true },
        },
      ],
    });

    expect(reportScheduleCadenceLabel(schedule)).toBe('Friday at 08:15');
    expect(reportScheduleDeliveryLabel(schedule)).toBe('Save to disk');
  });
});