summaryrefslogtreecommitdiffstats
path: root/src/pybind/mgr/dashboard/frontend/src/app/shared/services/device.service.ts
blob: b433f235bffd94fc139a2d292fe3bbf284d82426 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { Injectable } from '@angular/core';

import moment from 'moment';

import { CdDevice } from '../models/devices';

@Injectable({
  providedIn: 'root'
})
export class DeviceService {
  /**
   * Calculates additional data and appends them as new attributes to the given device.
   */
  calculateAdditionalData(device: CdDevice): CdDevice {
    if (!device.life_expectancy_min || !device.life_expectancy_max) {
      device.state = 'unknown';
      return device;
    }
    const hasDate = (float: string): boolean => !!Number.parseFloat(float);
    const weeks = (isoDate1: string, isoDate2: string): number =>
      !isoDate1 || !isoDate2 || !hasDate(isoDate1) || !hasDate(isoDate2)
        ? null
        : moment.duration(moment(isoDate1).diff(moment(isoDate2))).asWeeks();

    const ageOfStamp = moment
      .duration(moment(moment.now()).diff(moment(device.life_expectancy_stamp)))
      .asWeeks();
    const max = weeks(device.life_expectancy_max, device.life_expectancy_stamp);
    const min = weeks(device.life_expectancy_min, device.life_expectancy_stamp);

    if (ageOfStamp > 1) {
      device.state = 'stale';
    } else if (max !== null && max <= 2) {
      device.state = 'bad';
    } else if (min !== null && min <= 4) {
      device.state = 'warning';
    } else {
      device.state = 'good';
    }

    device.life_expectancy_weeks = {
      max: max !== null ? Math.round(max) : null,
      min: min !== null ? Math.round(min) : null
    };

    return device;
  }

  readable(device: CdDevice): CdDevice {
    device.readableDaemons = device.daemons.join(' ');
    return device;
  }

  prepareDevice(device: CdDevice): CdDevice {
    return this.readable(this.calculateAdditionalData(device));
  }
}