ここでは、セキュリティインシデント分析ダッシュボードサンプルを作成する際のポイントを紹介します。
セキュリティインシデント分析ダッシュボードの詳細
セキュリティインシデント分析ダッシュボードでは、KPIカード、チャート、ピボットテーブルを組み合わせることで、インシデントの傾向を多角的に分析できます。
インシデント種別や重要度、部署ごとの発生状況を可視化するとともに、フィルター条件の変更に応じてチャートや集計結果をリアルタイムに更新します。
PivotPanel / PivotGrid
PivotPanel と PivotGrid を利用して、セキュリティインシデントデータの集計・分析を行います。
PivotPanel では行、列、値、フィルターの設定を自由に変更でき、PivotGrid が集計結果を自動的に表示します。
また、PivotPanelでフィルター条件が変更された際は、フィルター後のデータを取得して各チャートやKPIカードを更新しています。
MultiSelect
MultiSelect を利用して、行・列・値・フィルター領域へ表示するフィールドを選択できます。
選択結果はPivotEngineと同期され、分析レイアウトを簡単に変更できます。
FlexChart
FlexChart を利用して、インシデント件数の推移や重要度別の件数を可視化しています。
日次推移は積み上げ縦棒グラフ、重要度別件数は横棒グラフで表示しています。
Series の style プロパティを設定することで、重要度ごとに異なる色を割り当て、発生状況を視覚的に把握できます。
FlexPie
FlexPie を利用して、インシデント種別ごとの構成比を表示しています。
ドーナツチャートとして表示し、中心には対象データの総件数を表示しています。
KPIカード
ダッシュボード上部では、総インシデント数、高重要度件数、中重要度件数、低重要度件数、平均対応時間をKPIカードとして表示しています。
フィルター条件の変更に応じて再集計を行い、最新の値へ更新します。
FlexGridXlsxConverter / Workbook
FlexGridXlsxConverter と Workbook を利用して、分析結果をExcelファイルとして出力します。
集計結果だけでなく、行・列・値・フィルターなどの分析条件も別シートへ出力することで、分析内容をそのまま共有できます。
Wijmoテーマの動的切り替え
Windowsのカラーモードに応じて、WijmoのテーマCSSを動的に読み込みます。
ライトモードでは「wijmo.theme.light.css」、ダークモードでは「wijmo.theme.midnight.css」を適用し、ダッシュボード全体の見た目を切り替えています。
テーマの読み込み後は、Wijmoコントロールのスタイル情報を取得し、カードやチャート、Excel出力で使用する色へ反映しています。
これにより、PivotGrid やチャートだけでなく、KPIカードや出力帳票もWijmoテーマと統一されたデザインで表示できます。
import "bootstrap.css";
import "@mescius/wijmo.cultures/wijmo.culture.ja";
import "./styles.css";
import "@mescius/wijmo.touch";
import { getData } from "./data";
import { createIncidentKpiCard } from "./incident-kpi-card.js";
import { applyFieldSlice, createPivot } from "./incident-pivot";
import { createIncidentTrendChart, updateIncidentTrendChart, } from "./incident-trend-chart";
import { createIncidentTypeChart, updateIncidentTypeChart, } from "./incident-type-chart";
import { createIncidentCountChart, updateIncidentCountChart, } from "./incident-count-chart";
import { calculateIncidentKpiMetrics, updateTerm } from "./incident-utils";
import { ColorStyle } from "./const";
import { exportPivotGrid } from "./export";
document.readyState === "complete" ? bootstrap() : (window.onload = bootstrap);
function bootstrap() {
initializeTheme().then(init);
}
function init() {
const data = getData();
updateTerm(data);
// 1列目のKPIカード
const container = document.getElementById("kpiCards");
const totalCard = createIncidentKpiCard(container, {
icon: "fa-solid fa-shield-halved",
title: "総インシデント数",
unit: "件",
color: ColorStyle.red,
});
const highCard = createIncidentKpiCard(container, {
icon: "fa-solid fa-triangle-exclamation",
title: "高重要度件数",
unit: "件",
color: ColorStyle.orange,
});
const mediumCard = createIncidentKpiCard(container, {
icon: "fa-solid fa-chart-column",
title: "中重要度件数",
unit: "件",
color: ColorStyle.yellow,
});
const lowCard = createIncidentKpiCard(container, {
icon: "fa-solid fa-circle-info",
title: "低重要度件数",
unit: "件",
color: ColorStyle.blue,
});
const timeCard = createIncidentKpiCard(container, {
icon: "fa-regular fa-clock",
title: "平均対応時間",
unit: "時間",
color: ColorStyle.green,
});
// 2行目のチャート
const trendChart = createIncidentTrendChart(data);
const typeChart = createIncidentTypeChart(data, function (incidentType) {
applyFieldSlice(pivotEngine, pivotPanel, "incidentType", incidentType);
});
const countChart = createIncidentCountChart(data);
function refreshDashboard(items) {
updateIncidentTrendChart(trendChart, items);
updateIncidentTypeChart(typeChart, items);
updateIncidentCountChart(countChart, items);
updateKpiCards(items);
updateTerm(items);
}
const { pivotEngine, pivotPanelGrid, pivotPanel } = createPivot(data, {
filteredItemsChanged: refreshDashboard,
});
const exportButton = document.querySelector(".export");
if (exportButton) {
exportButton.addEventListener("click", () => exportPivotGrid(pivotEngine, pivotPanelGrid));
}
// 動的にCSSを変更するため、Wijmoテーマの読み込み完了後にレイアウトを表示する
const layout = document.querySelector(".layout");
if (layout) {
layout.classList.add("ready");
}
/**
* KPIカードを更新する
*
* PivotPanelのフィルタ変更後のデータをもとに、
* 総件数、重要度別件数、平均対応時間を集計し、
* 各KPIカードへ反映する。
*/
function updateKpiCards(items) {
const metrics = calculateIncidentKpiMetrics(items);
totalCard.update(metrics.totalCount);
highCard.update(metrics.highCount);
mediumCard.update(metrics.mediumCount);
lowCard.update(metrics.lowCount);
timeCard.update(metrics.averageResponseHours.toFixed(1));
}
}
/**
* Windowsのカラーモードをもとにテーマを初期化する
* * @returns {Promise<void>}
*/
function initializeTheme() {
return new Promise(function (resolve) {
const isDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
document.body.classList.toggle("theme-dark", isDark);
document.body.classList.toggle("theme-light", !isDark);
/** @type {HTMLLinkElement|null} */
const themeLink = document.getElementById("wijmo-theme");
if (!themeLink) {
resolve();
return;
}
themeLink.onload = function () {
applyWijmoThemeColors();
resolve();
};
themeLink.setAttribute("href", isDark
? "node_modules/@mescius/wijmo.styles/themes/wijmo.theme.midnight.css"
: "node_modules/@mescius/wijmo.styles/themes/wijmo.theme.light.css");
});
}
/**
* 読み込まれたWijmoテーマから基本色を取得し、
* ダッシュボード用CSS変数へ反映する
*/
function applyWijmoThemeColors() {
// .wj-control のテーマ色を取得する。
const controlStyle = getWijmoStyle("wj-control");
const chartStyle = getWijmoStyle("wj-control wj-flexchart");
const headerStyleInfo = getWijmoStyle("wj-control wj-header");
document.documentElement.style.setProperty("--card-bg-color", controlStyle.backgroundColor);
document.documentElement.style.setProperty("--text-color", controlStyle.color);
document.documentElement.style.setProperty("--border-color", chartStyle.borderColor);
// Excelヘッダー用
document.documentElement.style.setProperty("--header-bg-color", headerStyleInfo.backgroundColor);
}
function getWijmoStyle(className) {
const probe = document.createElement("div");
probe.className = className;
document.body.appendChild(probe);
const style = getComputedStyle(probe);
const result = {
backgroundColor: style.backgroundColor,
color: style.color,
borderColor: style.borderColor,
};
document.body.removeChild(probe);
return result;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>MESCIUS Wijmo OLAP Pivot Panel Control Template</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- カード内で使用するアイコンCSS -->
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.3.1/css/all.min.css"
/>
<!-- Wijmoのテーマ切り替え用のCSS -->
<link id="wijmo-theme" rel="stylesheet" href="" />
<!-- SystemJS -->
<script
src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.21.5/system.src.js"
integrity="sha512-skZbMyvYdNoZfLmiGn5ii6KmklM82rYX2uWctBhzaXPxJgiv4XBwJnFGr5k8s+6tE1pcR1nuTKghozJHyzMcoA=="
crossorigin="anonymous"
></script>
<script src="systemjs.config.js"></script>
<script>
System.import("./src/app");
</script>
</head>
<body>
<div class="layout">
<div class="header-panel">
<div class="header-title">
セキュリティインシデント分析ダッシュボード
</div>
<div class="term">期間</div>
<button class="export">エクスポート</button>
</div>
<div class="first-panel">
<div id="kpiCards" class="kpi-cards"></div>
</div>
<div class="second-panel">
<section class="chart-section">
<div class="panel-title">インシデント件数の推移(日次)</div>
<div id="incidentTrendChart"></div>
</section>
<section class="chart-section">
<div class="panel-title">インシデント種別の割合</div>
<div id="incidentTypeChart"></div>
</section>
<section class="chart-section">
<div class="panel-title">重要度別インシデント件数</div>
<div id="incidentCountChart"></div>
</section>
</div>
<div class="third-panel">
<section class="pivot-grid-section">
<div class="panel-title">インシデント集計(ピボットテーブル)</div>
<div class="pivot-toolbar">
<div class="field-selector">
<label for="rowMultiSelect">行</label>
<div id="rowMultiSelect"></div>
</div>
<div class="field-selector">
<label for="columnMultiSelect">列</label>
<div id="columnMultiSelect"></div>
</div>
<div class="field-selector">
<label for="valueMultiSelect">Σ値</label>
<div id="valueMultiSelect"></div>
</div>
<div class="field-selector">
<label for="filterMultiSelect">フィルター</label>
<div id="filterMultiSelect"></div>
</div>
</div>
<div id="pivotPanelGrid"></div>
</section>
<section class="pivot-panel-section">
<div class="panel-title">ピボットパネル</div>
<div id="pivotPanel"></div>
</section>
<div>
<p>このデモサイトではFont Awesomeを利用しています。</p>
<p>Copyright (c) Fonticons, Inc.</p>
<a href="https://fontawesome.com/license/free" target="_blank"
>Font Awesomeのライセンス</a
>
</div>
</div>
</div>
</body>
</html>
import { IncidentType, PriorityLevel } from "./const";
export function getData() {
const departments = [
["営業本部", "営業部"],
["営業本部", "営業企画部"],
["技術本部", "開発部"],
["技術本部", "品質保証部"],
["コーポレート本部", "情報システム部"],
["コーポレート本部", "管理部"],
];
const incidentTypes = Object.values(IncidentType);
const priorities = Object.values(PriorityLevel);
const sources = ["EDR", "SIEM", "メールGW", "WAF", "CASB"];
const statuses = ["未対応", "調査中", "対応中", "対応済"];
const rand = (max) => Math.floor(Math.random() * max);
const data = [];
const dataNum = 950 + Math.floor(Math.random() * 300); // 950 ~ 1249
for (let i = 0; i < dataNum; i++) {
const dep = departments[rand(departments.length)];
const day = rand(28) + 1;
data.push({
datetime: new Date(2026, 7, day, rand(24), rand(60)),
date: new Date(2026, 7, day),
departmentGroup: dep[0],
department: dep[1],
priority: priorities[rand(priorities.length)],
incidentType: incidentTypes[rand(incidentTypes.length)],
source: sources[rand(sources.length)],
status: statuses[rand(statuses.length)],
responseHours: rand(5) + 1,
});
}
return data;
}
:root {
--color-green: #7cb342;
--color-orange: #f39c12;
--color-yellow: #d9a032;
--color-blue: #4a90e2;
--color-red: #e74c3c;
--color-gray: #cfcfcf;
--color-black: #000000;
--color-white: #ffffff;
--font-size-s: 10px;
--font-size-m: 12px;
--font-size-l: 14px;
--font-size-xl: 16px;
--font-size-2l: 18px;
--font-size-3l: 20px;
}
body {
overflow-y: scroll;
}
.wj-control {
font-size: var(--font-size-s);
}
.wj-tooltip {
font-size: var(--font-size-s);
}
/* 画面の背景色 */
body.theme-light {
--app-bg-color: #efeddb;
}
body.theme-dark {
--app-bg-color: #0f172a;
}
/* 画面全体:縦に配置 */
.layout {
padding: 8px;
display: flex;
flex-direction: column;
gap: 12px;
background-color: var(--app-bg-color);
opacity: 0;
}
.layout.ready {
opacity: 1;
}
.wj-flexchart,
.wj-flexpie {
background-color: var(--card-bg-color);
}
.header-panel {
display: flex;
align-items: center;
}
.header-title {
font-size: var(--font-size-l);
font-weight: bold;
color: var(--text-color);
margin-right: auto;
}
.term {
margin-left: 14px;
color: var(--text-color);
}
.export {
margin-left: 14px;
background: var(--card-bg-color);
color: var(--text-color);
}
.kpi-cards {
display: flex;
gap: 14px;
}
.kpi-card {
flex: 1;
display: flex;
align-items: flex-start;
gap: 10px;
padding: 10px;
background: var(--card-bg-color);
border: 1px solid var(--border-color);
border-radius: 6px;
}
/* 画面幅が狭い場合 */
@media (max-width: 900px) {
.kpi-card {
flex-direction: column;
align-items: center;
text-align: center;
}
}
.kpi-card-icon {
font-size: 48px;
color: var(--card-accent-color);
}
.kpi-card-title {
color: var(--text-color);
font-size: var(--font-size-m);
margin-bottom: 4px;
}
.kpi-card-value {
color: var(--text-color);
font-size: var(--font-size-3l);
font-weight: bold;
}
.kpi-card-subtext {
margin-top: 4px;
font-size: var(--font-size-s);
font-weight: bold;
}
.ratio-up {
color: var(--color-blue);
}
.ratio-down {
color: var(--color-red);
}
.ratio-same {
color: var(--color-green);
}
/* 2行目: 3つのチャート */
.second-panel {
display: flex;
gap: 10px;
}
.chart-section {
flex: 1;
min-width: 0;
}
#incidentTypeChart,
#incidentTrendChart,
#incidentCountChart {
width: 100%;
height: 260px;
}
/* 3行目 */
.third-panel {
display: grid;
grid-template-columns:
minmax(0, 1fr)
320px;
gap: 6px;
height: 480px;
min-height: 0;
}
@media (max-width: 1100px) {
.third-panel {
grid-template-columns: 1fr;
height: auto;
}
.pivot-grid-section,
.pivot-panel-section {
height: 360px;
min-height: 360px;
max-height: 360px;
overflow: hidden;
}
}
.pivot-grid-section,
.pivot-panel-section {
display: flex;
flex-direction: column;
min-width: 0;
min-height: 0;
height: 100%;
}
/* PivotGrid / PivotPanel を third-panel の高さに合わせる */
.wj-pivotgrid,
.wj-pivotpanel {
flex: 1;
min-height: 0;
height: 100%;
}
/* パネルタイトル */
.panel-title {
font-size: var(--font-size-m);
color: var(--text-color);
font-weight: bold;
margin-bottom: 8px;
}
.field-selector label {
color: var(--text-color);
font-size: var(--font-size-s);
font-weight: bold;
white-space: nowrap;
flex-shrink: 0;
}
.right-panel {
flex: 1;
width: auto;
}
/* PivotPanel カスタムレイアウト */
.wj-pivotpanel .root {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
grid-template-rows: auto minmax(0, 1fr) auto auto;
gap: 8px;
height: 100%;
min-height: 0;
box-sizing: border-box;
}
/* 左上ラベル */
.wj-pivotpanel .field-list-label {
grid-column: 1;
grid-row: 1;
min-width: 0;
}
/* 左側: フィールド一覧 */
.wj-pivotpanel .field-list {
grid-column: 1;
grid-row: 2;
min-width: 0;
min-height: 0;
}
/* 右上ラベル */
.wj-pivotpanel .drag-areas-label {
grid-column: 2;
grid-row: 1;
min-width: 0;
}
/* 右側: フィルター / 列 / 行 / 値 */
.wj-pivotpanel .areas-list {
grid-column: 2;
grid-row: 2 / span 3;
display: grid;
grid-template-rows: repeat(4, 1fr);
gap: 6px;
min-width: 0;
min-height: 0;
overflow: hidden;
}
/* 各エリア本体 */
.wj-pivotpanel .filter-list,
.wj-pivotpanel .column-list,
.wj-pivotpanel .row-list,
.wj-pivotpanel .values-list {
min-width: 0;
min-height: 0;
padding: 4px;
border: 1px solid #ddd;
border-radius: 4px;
box-sizing: border-box;
display: flex;
flex-direction: column;
}
/* 各エリア内の Wijmo コンテンツをスクロール対象にする */
.wj-pivotpanel .filter-list > div,
.wj-pivotpanel .column-list > div,
.wj-pivotpanel .row-list > div,
.wj-pivotpanel .values-list > div {
min-height: 0;
}
/* 実際の項目リスト部分 */
.wj-pivotpanel .filter-list .wj-content,
.wj-pivotpanel .column-list .wj-content,
.wj-pivotpanel .row-list .wj-content,
.wj-pivotpanel .values-list .wj-content {
flex: 1 1 auto;
min-height: 0;
overflow-y: auto;
overflow-x: hidden;
}
/* 進捗バー */
.wj-pivotpanel .progress-bar {
grid-column: 1;
grid-row: 3;
min-height: 0;
}
/* 下部コントロール */
.wj-pivotpanel .control-area {
grid-column: 1;
grid-row: 4;
min-height: 0;
}
/* ピボットテーブル上部のツールバー */
.pivot-toolbar {
display: flex;
gap: 12px;
align-items: center;
width: 100%;
min-width: 0;
}
.field-selector {
display: flex;
align-items: center;
gap: 6px;
flex: 1 1 0;
min-width: 0;
}
.field-selector .wj-multiselect {
width: 100%;
min-width: 80px;
}
export const DateTimeFormat = "yyyy/MM/dd HH:mm";
// 領域セクションは縦1列にする
export const ControlTemplate = `
<div class="root">
<div class="field-list-label">
<label wj-part="g-flds"></label>
</div>
<div class="field-list pad">
<div wj-part="d-fields"></div>
</div>
<div class="drag-areas-label">
<label wj-part="g-drag"></label>
</div>
<div class="areas-list">
<div class="filter-list pad">
<label>
<span class="wj-glyph wj-glyph-filter"></span>
<span wj-part="g-flt"></span>
</label>
<div wj-part="d-filters"></div>
</div>
<div class="column-list pad">
<label>
<span class="wj-glyph">⫴</span>
<span wj-part="g-cols"></span>
</label>
<div wj-part="d-cols"></div>
</div>
<div class="row-list pad">
<label>
<span class="wj-glyph">≡</span>
<span wj-part="g-rows"></span>
</label>
<div wj-part="d-rows"></div>
</div>
<div class="values-list pad">
<label>
<span class="wj-glyph">Σ</span>
<span wj-part="g-vals"></span>
</label>
<div wj-part="d-vals"></div>
</div>
</div>
<div wj-part="d-prog" class="progress-bar"></div>
<div class="control-area">
<label>
<input wj-part="chk-defer" type="checkbox">
<span wj-part="g-defer"></span>
</label>
<button
wj-part="btn-update"
class="wj-btn wj-state-disabled"
type="button"
disabled>
Update
</button>
</div>
</div>
`;
export const ColorStyle = {
red: getCssVar("--color-red"),
orange: getCssVar("--color-orange"),
yellow: getCssVar("--color-yellow"),
blue: getCssVar("--color-blue"),
green: getCssVar("--color-green"),
gray: getCssVar("--color-gray"),
black: getCssVar("--color-black"),
white: getCssVar("--color-white"),
};
export const Field = Object.freeze({
DateTime: {
binding: "datetime",
header: "日時",
format: DateTimeFormat,
},
Date: {
binding: "date",
header: "日付",
},
Priority: {
binding: "priority",
header: "重要度",
},
IncidentType: {
binding: "incidentType",
header: "インシデント種別",
},
Department: {
binding: "department",
header: "部署",
},
DepartmentGroup: {
binding: "departmentGroup",
header: "部署グループ",
},
Source: {
binding: "source",
header: "検知ソース",
},
Status: {
binding: "status",
header: "対応ステータス",
},
ResponseHours: {
binding: "responseHours",
header: "対応時間(時間)",
},
});
export const IncidentType = Object.freeze({
Malware: "マルウェア",
Phishing: "フィッシング",
UnauthorizedAccess: "不正アクセス",
ExploitVulnerability: "脆弱性悪用",
DataBreach: "情報漏えい",
Other: "その他",
});
export const PriorityLevel = Object.freeze({
High: "高",
Middle: "中",
Low: "低",
});
export const CHART_COLORS = {
priority: {
[PriorityLevel.High]: ColorStyle.red,
[PriorityLevel.Middle]: ColorStyle.orange,
[PriorityLevel.Low]: ColorStyle.blue,
},
incidentType: {
[IncidentType.Malware]: ColorStyle.red,
[IncidentType.Phishing]: ColorStyle.orange,
[IncidentType.UnauthorizedAccess]: ColorStyle.yellow,
[IncidentType.ExploitVulnerability]: ColorStyle.green,
[IncidentType.DataBreach]: ColorStyle.blue,
[IncidentType.Other]: ColorStyle.gray,
},
};
export function getCssVar(name) {
return getComputedStyle(document.documentElement).getPropertyValue(name);
}
import { Globalize } from "@mescius/wijmo";
import { FlexGridXlsxConverter } from "@mescius/wijmo.grid.xlsx";
import { WorkSheet, WorkbookRow, WorkbookCell, } from "@mescius/wijmo.xlsx";
import { DateTimeFormat } from "./const";
/**
* ピボットグリッドと分析条件をExcel形式で出力する
*/
export function exportPivotGrid(pivotEngine, pivotPanelGrid) {
FlexGridXlsxConverter.saveAsync(pivotPanelGrid, {
includeColumnHeaders: true,
includeRowHeaders: true,
includeStyles: true,
}, null, (base64, workbook) => {
workbook.sheets[0].name = "集計結果";
const conditionSheet = new WorkSheet();
conditionSheet.name = "分析条件";
conditionSheet.rows.push(createWorkbookRow("出力日時", Globalize.format(new Date(), DateTimeFormat)));
conditionSheet.rows.push(new WorkbookRow()); // 空行
const style = getComputedStyle(document.body);
const headerStyle = {
font: {
bold: true,
color: style.getPropertyValue("--text-color").trim(),
},
fill: {
color: style.getPropertyValue("--header-bg-color").trim(),
},
};
const cellStyle = {
font: {
bold: true,
color: style.getPropertyValue("--text-color").trim(),
},
fill: {
color: style.getPropertyValue("--card-bg-color").trim(),
},
};
conditionSheet.rows.push(createWorkbookRow("項目", "設定値", headerStyle));
conditionSheet.rows.push(createWorkbookRow("行", getFieldHeaders(pivotEngine.rowFields), cellStyle));
conditionSheet.rows.push(createWorkbookRow("列", getFieldHeaders(pivotEngine.columnFields), cellStyle));
conditionSheet.rows.push(createWorkbookRow("値", getFieldHeaders(pivotEngine.valueFields), cellStyle));
// フィルターフィールド
addFilterConditionRows(conditionSheet, pivotEngine.filterFields);
autoFitColumns(conditionSheet);
workbook.sheets.push(conditionSheet);
workbook.saveAsync("IncidentAnalysis.xlsx");
});
}
/**
* ピボットグリッドをExcel形式で出力する
*/
/**
* PivotFieldCollectionからフィールド名を取得する
*/
function getFieldHeaders(fields) {
const headers = [];
for (let i = 0; i < fields.length; i++) {
headers.push(fields[i].header);
}
return headers.join(", ");
}
/**
* WorkbookRowを作成する
*/
function createWorkbookRow(label, value, style = null) {
const workbookRow = new WorkbookRow();
const labelCell = new WorkbookCell();
labelCell.value = label;
const valueCell = new WorkbookCell();
valueCell.value = value;
if (style) {
labelCell.style = style;
valueCell.style = style;
}
workbookRow.cells.push(labelCell);
workbookRow.cells.push(valueCell);
return workbookRow;
}
/**
* ValueFilterで選択されている値を取得する
*/
function getSelectedFilterValues(valueFilter) {
if (!valueFilter.isActive || !valueFilter.showValues) {
return [];
}
return Object.keys(valueFilter.showValues).filter(function (value) {
return valueFilter.showValues[value];
});
}
/**
* 分析条件シートへフィルター条件を追加する
*/
function addFilterConditionRows(conditionSheet, filterFields) {
if (filterFields.length === 0) {
conditionSheet.rows.push(createWorkbookRow("フィルター条件", "なし"));
return;
}
let hasActiveFilter = false;
for (let i = 0; i < filterFields.length; i++) {
const field = filterFields[i];
const valueFilter = field.filter.valueFilter;
if (!valueFilter.isActive) {
continue;
}
const selectedValues = getSelectedFilterValues(valueFilter);
conditionSheet.rows.push(createWorkbookRow(field.header, selectedValues.length > 0 ? selectedValues.join(", ") : "条件なし"));
hasActiveFilter = true;
}
if (!hasActiveFilter) {
conditionSheet.rows.push(createWorkbookRow("フィルター条件", "なし"));
}
}
function autoFitColumns(sheet) {
const widths = [];
for (let r = 0; r < sheet.rows.length; r++) {
const row = sheet.rows[r];
if (!row.cells) {
continue;
}
for (let c = 0; c < row.cells.length; c++) {
const cell = row.cells[c];
const text = cell.value != null ? String(cell.value) : "";
let length = 0;
for (let i = 0; i < text.length; i++) {
length += text.charCodeAt(i) > 255 ? 2 : 1;
}
if (widths[c] == null || length > widths[c]) {
widths[c] = length;
}
}
}
for (let c = 0; c < widths.length; c++) {
sheet.columns.push({
width: Math.max(widths[c] * 10, 100),
});
}
}
import { ChartType, FlexChart, Position } from "@mescius/wijmo.chart";
import { CHART_COLORS, PriorityLevel } from "./const";
/**
* 重要度別インシデント件数チャートを作成する
*/
export function createIncidentCountChart(data) {
const chartItems = createIncidentCountItems(data);
const chart = new FlexChart("#incidentCountChart", {
itemsSource: chartItems,
chartType: ChartType.Bar,
bindingX: "priority",
series: [{ binding: "count", name: "件数" }],
legend: { position: Position.None },
axisX: { title: "件数" },
axisY: { reversed: true },
});
// カラーの変更
chart.itemFormatter = (engine, hitTestInfo, defaultRenderer) => {
const item = hitTestInfo.item;
if (item) {
engine.fill = CHART_COLORS.priority[item.priority];
}
defaultRenderer();
};
return chart;
}
export function updateIncidentCountChart(chart, data) {
chart.itemsSource = createIncidentCountItems(data);
}
function createIncidentCountItems(data) {
const counts = data.reduce((result, item) => {
const priority = item.priority;
result[priority] = (result[priority] || 0) + 1;
return result;
}, {});
// 積み上げ順を「高⇒中⇒低」にする
return Object.values(PriorityLevel).map((priority) => ({
priority,
count: counts[priority] || 0,
}));
}
import { Globalize } from "@mescius/wijmo";
export function createIncidentKpiCard(container, options) {
var card = document.createElement("div");
card.className = "kpi-card";
var previousValue = null;
if (options.color) {
card.style.setProperty("--card-accent-color", options.color);
}
card.innerHTML =
'<div class="kpi-card-icon">' +
' <i class="' +
options.icon +
'"></i>' +
"</div>" +
'<div class="kpi-card-content">' +
' <div class="kpi-card-title">' +
options.title +
"</div>" +
' <div class="kpi-card-value"></div>' +
' <div class="kpi-card-subtext"></div>' +
"</div>";
container.appendChild(card);
var valueElement = card.querySelector(".kpi-card-value");
var ratioElement = card.querySelector(".kpi-card-subtext");
function formatValue(value, unit) {
if (unit) {
return value + unit;
}
return value;
}
function initializePreviousValue(value) {
if (previousValue !== null) {
return;
}
if (value === undefined || value === null || value === 0) {
previousValue = 0;
return;
}
previousValue = createPreviousValue(Number(value));
}
function createPreviousValue(currentValue) {
return currentValue * (0.95 + Math.random() * 0.1);
}
function getRatio(currentValue, baseValue) {
if (!baseValue) {
return 0;
}
return (currentValue - baseValue) / baseValue;
}
function updateRatio(ratio) {
ratioElement.className = "kpi-card-subtext";
if (ratio === undefined || ratio === null) {
ratioElement.textContent = "";
return;
}
var symbol = "";
if (ratio > 0) {
symbol = "▲";
ratioElement.classList.add("ratio-up");
}
else if (ratio < 0) {
symbol = "▼";
ratioElement.classList.add("ratio-down");
}
else {
symbol = "-";
ratioElement.classList.add("ratio-same");
}
ratioElement.textContent = `前期間比 ${symbol} ${Globalize.format(Math.abs(ratio), "p1")}`;
}
function update(value) {
var numericValue = Number(value);
valueElement.textContent = formatValue(value, options.unit);
initializePreviousValue(numericValue);
updateRatio(getRatio(numericValue, previousValue));
}
if (options.value !== undefined && options.value !== null) {
update(options.value);
}
return {
element: card,
update: update,
};
}
import { Control } from "@mescius/wijmo";
import { FlexGrid } from "@mescius/wijmo.grid";
import { PivotEngine, PivotGrid, PivotPanel, ShowTotals, } from "@mescius/wijmo.olap";
import { MultiSelect } from "@mescius/wijmo.input";
import { ControlTemplate, Field } from "./const";
/**
* インシデントのピボットを作成する
*/
export function createPivot(data, options) {
PivotPanel.controlTemplate = ControlTemplate;
const pivotEngine = new PivotEngine({
itemsSource: data,
fields: Object.values(Field),
valueFields: [Field.Priority.header],
rowFields: [Field.Department.header],
columnFields: [Field.IncidentType.header],
filterFields: [Field.Source.header],
showRowTotals: ShowTotals.Subtotals,
});
const fieldSelectors = [
{ selector: "#rowMultiSelect", fields: pivotEngine.rowFields },
{ selector: "#columnMultiSelect", fields: pivotEngine.columnFields },
{ selector: "#valueMultiSelect", fields: pivotEngine.valueFields },
{ selector: "#filterMultiSelect", fields: pivotEngine.filterFields },
].map(function (config) {
return {
fields: config.fields,
multiSelect: createFieldMultiSelect(config.selector, pivotEngine, config.fields),
};
});
addFieldCollectionChangedHandlers(fieldSelectors);
addFieldHeaderChangedHandlers(pivotEngine, fieldSelectors.map(function (item) {
return item.multiSelect;
}));
const pivotPanel = new PivotPanel("#pivotPanel", {
itemsSource: pivotEngine,
});
const pivotPanelGrid = new PivotGrid("#pivotPanelGrid", {
itemsSource: pivotEngine,
});
localizeDetailGridHeaders(pivotPanelGrid, pivotEngine);
addChartRefreshHandler(data, pivotEngine, options);
return {
pivotEngine: pivotEngine,
pivotPanelGrid: pivotPanelGrid,
pivotPanel: pivotPanel,
};
}
/**
* PivotPanel 側で行・列・値・フィルターフィールドが変更された場合に
* MultiSelect 側へ同期する
*/
function addFieldCollectionChangedHandlers(fieldSelectors) {
fieldSelectors.forEach(function (item) {
item.fields.collectionChanged.addHandler(function () {
item.multiSelect.syncFromFields();
});
});
}
/**
* 行・列・値・フィルターフィールド用の MultiSelect を作成する
*/
function createFieldMultiSelect(selector, engine, targetFields) {
let syncingFromFields = false;
let updatingTargetFields = false;
const items = createCheckableFieldItems(engine, targetFields);
const multiSelect = new MultiSelect(selector, {
displayMemberPath: "field.header",
checkedMemberPath: "checked",
itemsSource: items,
});
multiSelect.checkedItemsChanged.addHandler(function (sender) {
if (syncingFromFields) {
return;
}
const checkedItems = sender.checkedItems.slice();
updatingTargetFields = true;
try {
engine.deferUpdate(function () {
targetFields.clear();
targetFields.push.apply(targetFields, checkedItems.map(function (item) {
return item.field;
}));
});
}
finally {
updatingTargetFields = false;
}
});
function refreshItems() {
multiSelect.collectionView.refresh();
multiSelect.invalidate();
}
function syncFromFields() {
if (updatingTargetFields) {
return;
}
syncingFromFields = true;
items.forEach(function (item) {
item.checked = containsFieldByBinding(targetFields, item.field);
});
refreshItems();
syncingFromFields = false;
}
return {
control: multiSelect,
syncFromFields: syncFromFields,
refreshItems: refreshItems,
};
}
/**
* MultiSelect 用の itemsSource を作成する
*/
function createCheckableFieldItems(engine, targetFields) {
return Array.prototype.map.call(engine.fields, function (field) {
return {
field: field,
checked: containsFieldByBinding(targetFields, field),
};
});
}
/**
* PivotFieldCollection に指定した field が含まれるかを binding で判定する
*/
function containsFieldByBinding(fieldCollection, field) {
return Array.prototype.some.call(fieldCollection, function (currentField) {
return currentField.binding === field.binding;
});
}
/**
* 詳細ビューの列ヘッダーを PivotEngine のフィールドヘッダーに合わせ、
* ヘッダーとセル内容に合わせて列幅を自動調整する
*/
function localizeDetailGridHeaders(pivotGrid, engine) {
const dialog = pivotGrid.detailDialog;
dialog.shown.addHandler(function () {
const gridElement = dialog.content.querySelector(".wj-flexgrid");
if (!gridElement) {
return;
}
const detailGrid = Control.getControl(gridElement);
if (!(detailGrid instanceof FlexGrid)) {
return;
}
const headers = createHeaderMap(engine);
Array.prototype.forEach.call(detailGrid.columns, function (column) {
if (column.binding && headers[column.binding]) {
column.header = headers[column.binding];
}
});
// ヘッダーとデータセルの両方を考慮して列幅を自動調整する
detailGrid.autoSizeColumns();
});
}
/**
* binding と header の対応表を作成する
*/
function createHeaderMap(engine) {
return Array.prototype.reduce.call(engine.fields, function (headers, field) {
if (field.binding) {
headers[field.binding] = field.header;
}
return headers;
}, {});
}
/**
* フィールド設定ダイアログでフィールド名が変更された場合に
* MultiSelect を再描画する
*/
function addFieldHeaderChangedHandlers(engine, multiSelects) {
Array.prototype.forEach.call(engine.fields, function (field) {
field.propertyChanged.addHandler(function (sender, eventArgs) {
if (eventArgs &&
eventArgs.propertyName &&
eventArgs.propertyName !== "header") {
return;
}
multiSelects.forEach(function (multiSelect) {
multiSelect.refreshItems();
});
});
});
}
/**
* PivotEngine の更新後に、PivotPanel のフィルターを適用したデータを通知する
*/
function addChartRefreshHandler(data, pivotEngine, options) {
if (!options || typeof options.filteredItemsChanged !== "function") {
return;
}
function refreshCharts() {
options.filteredItemsChanged(getFilteredItems(data, pivotEngine));
}
pivotEngine.updatedView.addHandler(function () {
refreshCharts();
});
refreshCharts();
}
/**
* PivotPanelで有効なフィルターを適用したデータを取得する
*/
function getFilteredItems(data, pivotEngine) {
return data.filter(function (item) {
return Array.prototype.every.call(pivotEngine.fields, function (field) {
// レイアウトに存在しないフィールドは無視
if (!isFieldInLayout(pivotEngine, field)) {
return true;
}
// フィルター未設定なら通す
if (!field.filter || !field.filter.isActive) {
return true;
}
return field.filter.apply(item);
});
});
}
/**
* フィールドが現在のレイアウトに含まれているか判定する
*/
function isFieldInLayout(pivotEngine, targetField) {
return (containsField(pivotEngine.rowFields, targetField) ||
containsField(pivotEngine.columnFields, targetField) ||
containsField(pivotEngine.valueFields, targetField) ||
containsField(pivotEngine.filterFields, targetField));
}
export function containsField(fields, targetField) {
return Array.prototype.some.call(fields, function (field) {
return field.binding === targetField.binding;
});
}
/**
* インシデント種別でデータをスライスする
*
* 円グラフで選択されたインシデント種別を
* PivotFieldの値フィルターへ設定する。
*
* 同じインシデント種別を再度選択した場合は、
* フィルターを解除する。
*/
export function applyFieldSlice(pivotEngine, pivotPanel, fieldBinding, value) {
const targetField = Array.prototype.find.call(pivotEngine.fields, function (field) {
return field.binding === fieldBinding;
});
if (!targetField) {
return;
}
const exists = containsField(pivotEngine.rowFields, targetField) ||
containsField(pivotEngine.columnFields, targetField) ||
containsField(pivotEngine.valueFields, targetField) ||
containsField(pivotEngine.filterFields, targetField);
if (!exists) {
pivotEngine.filterFields.push(targetField);
}
const valueFilter = targetField.filter.valueFilter;
const selectedValues = valueFilter.showValues
? Object.keys(valueFilter.showValues).filter((key) => valueFilter.showValues[key])
: [];
const isSelected = selectedValues.length === 1 && selectedValues[0] === value;
targetField.filter.clear();
if (!isSelected) {
targetField.filter.valueFilter.showValues = {
[value]: true,
};
}
pivotPanel.invalidate();
pivotEngine.refresh();
}
import { FlexChart, ChartType, Stacking, Series, Position, } from "@mescius/wijmo.chart";
import { CHART_COLORS, PriorityLevel } from "./const.js";
/**
* インシデント件数の推移(日次)チャートを作成する
*/
export function createIncidentTrendChart(data) {
const chartItems = createIncidentTrendChartItems(data);
const chart = new FlexChart("#incidentTrendChart", {
itemsSource: chartItems,
bindingX: "date",
chartType: ChartType.Column,
stacking: Stacking.Stacked,
legend: { position: Position.Top },
axisX: { format: "MM/dd" },
});
Object.values(PriorityLevel).forEach((priority) => {
chart.series.push(new Series({
name: priority,
binding: priority,
style: {
fill: CHART_COLORS.priority[priority],
stroke: CHART_COLORS.priority[priority],
},
}));
});
return chart;
}
export function updateIncidentTrendChart(chart, data) {
chart.itemsSource = createIncidentTrendChartItems(data);
}
/**
* 日付ごと、重要度ごとの件数を作成する
*/
function createIncidentTrendChartItems(data) {
const grouped = data.reduce((result, item) => {
const dateKey = formatDateKey(item.date);
const priority = item.priority;
if (!result[dateKey]) {
result[dateKey] = {
date: item.date,
dateKey: dateKey,
};
}
result[dateKey][priority] = (result[dateKey][priority] || 0) + 1;
return result;
}, {});
return Object.keys(grouped)
.map((key) => grouped[key])
.sort((a, b) => a.date - b.date);
}
/**
* グルーピング用の日付キーを作成する
*/
function formatDateKey(date) {
return [
date.getFullYear(),
String(date.getMonth() + 1).padStart(2, "0"),
String(date.getDate()).padStart(2, "0"),
].join("-");
}
import { Globalize } from "@mescius/wijmo";
import { FlexPie, Position } from "@mescius/wijmo.chart";
import { CHART_COLORS, ColorStyle, getCssVar, IncidentType } from "./const";
/**
* インシデント種別チャートを作成する
*/
export function createIncidentTypeChart(data, itemClicked) {
const chartItems = createIncidentTypeChartItems(data);
const chart = new FlexPie("#incidentTypeChart", {
binding: "count",
bindingName: "incidentTypeLabel",
itemsSource: chartItems,
innerRadius: 0.6,
legend: { position: Position.Right },
innerTextStyle: {
fill: document.body.classList.contains("theme-dark")
? ColorStyle.white
: ColorStyle.black,
fontSize: getCssVar("--font-size-l"),
fontWeight: "bold",
},
});
// チャートのクリックイベントを設定
chart.hostElement.addEventListener("click", function (event) {
const ht = chart.hitTest(event);
if (ht.pointIndex < 0) {
return;
}
const item = chart.itemsSource[ht.pointIndex];
if (itemClicked) {
itemClicked(item.incidentType);
}
});
return chart;
}
export function updateIncidentTypeChart(chart, data) {
chart.itemsSource = createIncidentTypeChartItems(data);
chart.innerText = `総数 ${data.length}`;
chart.palette = chart.itemsSource.map((item) => CHART_COLORS.incidentType[item.incidentType]);
chart.tooltip.hide();
}
/**
* インシデント種別ごとの件数を作成する
*/
function createIncidentTypeChartItems(data) {
const total = data.length;
const counts = data.reduce((result, item) => {
const type = item.incidentType;
result[type] = (result[type] || 0) + 1;
return result;
}, {});
return Object.entries(counts)
.map(([incidentType, count]) => {
const numericCount = Number(count);
return {
incidentType,
count: numericCount,
incidentTypeLabel: `${incidentType} ${Globalize.format(total > 0 ? numericCount / total : 0, "p1")}`,
};
})
.sort((a, b) => {
const aIsOther = a.incidentType === IncidentType.Other;
const bIsOther = b.incidentType === IncidentType.Other;
if (aIsOther !== bIsOther) {
return aIsOther ? 1 : -1;
}
return b.count - a.count;
});
}
(function (global) {
System.config({
transpiler: 'plugin-babel',
babelOptions: {
es2015: true
},
meta: {
'*.css': { loader: 'css' }
},
paths: {
// paths serve as alias
'npm:': 'node_modules/'
},
// map tells the System loader where to look for things
map: {
'jszip': 'npm:jszip/dist/jszip.js',
'@mescius/wijmo': 'npm:@mescius/wijmo/index.js',
'@mescius/wijmo.input': 'npm:@mescius/wijmo.input/index.js',
'@mescius/wijmo.styles': 'npm:@mescius/wijmo.styles',
'@mescius/wijmo.cultures': 'npm:@mescius/wijmo.cultures',
'@mescius/wijmo.chart': 'npm:@mescius/wijmo.chart/index.js',
'@mescius/wijmo.chart.analytics': 'npm:@mescius/wijmo.chart.analytics/index.js',
'@mescius/wijmo.chart.animation': 'npm:@mescius/wijmo.chart.animation/index.js',
'@mescius/wijmo.chart.annotation': 'npm:@mescius/wijmo.chart.annotation/index.js',
'@mescius/wijmo.chart.finance': 'npm:@mescius/wijmo.chart.finance/index.js',
'@mescius/wijmo.chart.finance.analytics': 'npm:@mescius/wijmo.chart.finance.analytics/index.js',
'@mescius/wijmo.chart.hierarchical': 'npm:@mescius/wijmo.chart.hierarchical/index.js',
'@mescius/wijmo.chart.interaction': 'npm:@mescius/wijmo.chart.interaction/index.js',
'@mescius/wijmo.chart.radar': 'npm:@mescius/wijmo.chart.radar/index.js',
'@mescius/wijmo.chart.render': 'npm:@mescius/wijmo.chart.render/index.js',
'@mescius/wijmo.chart.webgl': 'npm:@mescius/wijmo.chart.webgl/index.js',
'@mescius/wijmo.chart.map': 'npm:@mescius/wijmo.chart.map/index.js',
'@mescius/wijmo.gauge': 'npm:@mescius/wijmo.gauge/index.js',
'@mescius/wijmo.grid': 'npm:@mescius/wijmo.grid/index.js',
'@mescius/wijmo.grid.detail': 'npm:@mescius/wijmo.grid.detail/index.js',
'@mescius/wijmo.grid.filter': 'npm:@mescius/wijmo.grid.filter/index.js',
'@mescius/wijmo.grid.search': 'npm:@mescius/wijmo.grid.search/index.js',
'@mescius/wijmo.grid.style': 'npm:@mescius/wijmo.grid.style/index.js',
'@mescius/wijmo.grid.grouppanel': 'npm:@mescius/wijmo.grid.grouppanel/index.js',
'@mescius/wijmo.grid.multirow': 'npm:@mescius/wijmo.grid.multirow/index.js',
'@mescius/wijmo.grid.transposed': 'npm:@mescius/wijmo.grid.transposed/index.js',
'@mescius/wijmo.grid.transposedmultirow': 'npm:@mescius/wijmo.grid.transposedmultirow/index.js',
'@mescius/wijmo.grid.pdf': 'npm:@mescius/wijmo.grid.pdf/index.js',
'@mescius/wijmo.grid.sheet': 'npm:@mescius/wijmo.grid.sheet/index.js',
'@mescius/wijmo.grid.xlsx': 'npm:@mescius/wijmo.grid.xlsx/index.js',
'@mescius/wijmo.grid.selector': 'npm:@mescius/wijmo.grid.selector/index.js',
'@mescius/wijmo.grid.cellmaker': 'npm:@mescius/wijmo.grid.cellmaker/index.js',
'@mescius/wijmo.nav': 'npm:@mescius/wijmo.nav/index.js',
'@mescius/wijmo.odata': 'npm:@mescius/wijmo.odata/index.js',
'@mescius/wijmo.olap': 'npm:@mescius/wijmo.olap/index.js',
'@mescius/wijmo.rest': 'npm:@mescius/wijmo.rest/index.js',
'@mescius/wijmo.pdf': 'npm:@mescius/wijmo.pdf/index.js',
'@mescius/wijmo.pdf.security': 'npm:@mescius/wijmo.pdf.security/index.js',
'@mescius/wijmo.viewer': 'npm:@mescius/wijmo.viewer/index.js',
'@mescius/wijmo.xlsx': 'npm:@mescius/wijmo.xlsx/index.js',
'@mescius/wijmo.undo': 'npm:@mescius/wijmo.undo/index.js',
'@mescius/wijmo.interop.grid': 'npm:@mescius/wijmo.interop.grid/index.js',
'@mescius/wijmo.touch': 'npm:@mescius/wijmo.touch/index.js',
'@mescius/wijmo.cloud': 'npm:@mescius/wijmo.cloud/index.js',
'@mescius/wijmo.barcode': 'npm:@mescius/wijmo.barcode/index.js',
'@mescius/wijmo.barcode.common': 'npm:@mescius/wijmo.barcode.common/index.js',
'@mescius/wijmo.barcode.composite': 'npm:@mescius/wijmo.barcode.composite/index.js',
'@mescius/wijmo.barcode.specialized': 'npm:@mescius/wijmo.barcode.specialized/index.js',
'jszip': 'npm:jszip/dist/jszip.js',
'bootstrap.css': 'npm:bootstrap/dist/css/bootstrap.min.css',
'css': 'npm:systemjs-plugin-css/css.js',
'plugin-babel': 'npm:systemjs-plugin-babel/plugin-babel.js',
'systemjs-babel-build':'npm:systemjs-plugin-babel/systemjs-babel-browser.js'
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
src: {
defaultExtension: 'js'
},
"node_modules": {
defaultExtension: 'js'
},
}
});
})(this);