コンバータ: #TSV 文字列 to #Butterfly-MdChart 文字列

Overview

コンバータ: #TSV 文字列 to #Butterfly-MdChart 文字列

Converter: #TSV String to #Butterfly-MdChart String

数値TSV文字列を「Markdownに埋め込み可能な積み上げバタフライチャート(左右対称棒グラフ)」(ButterflyMdChart文字列)に変換します。データ行内で非数値文字列となる中央の列が自動的に「年月」や「四半期」などの集計単位ラベルとして認識され、その左側の列は左方向へ、右側の列は右方向へと積み上げ描画されます。

Auto Step icon
Configs for this Auto Step
StrConfA
A: TSV文字列をセットしてください *#{EL}
StrConfB1
B1: 表示幅ピクセル値(ユニット名・片側棒グラフ・片側合計値)をCSVでセットしてください(デフォルト: 60,200,60)#{EL}
StrConfB2L
B2L: 左系列の色(中央から外側へ)をCSVでセットしてください(デフォルト: “#c23,#e54,#f85,#fa9″)#{EL}
StrConfB2R
B2R: 右系列の色(中央から外側へ)をCSVでセットしてください(デフォルト: “#17c,#29e,#8ce,#bdf”)#{EL}
StrConfB3
B3: グラフ目盛りの最大値をセットしてください(デフォルト: 100)#{EL}
StrConfB4
B4: 片側目盛り文字列(中央0から最大値へ)をCSVでセットしてください(デフォルト: “0,50,100%”)#{EL}
StrConfB5
B5: 合計値の接頭辞・接尾辞をCSVでセットしてください(例: “¥,”, “,千円”)#{EL}
BoolConfB6
B6: 凡例 (色見本+系列名), 表示しない ⇔ 表示する
BoolConfB7
B7: 目盛りラベル, 表示しない ⇔ 表示する
SelectConfC
C: 変換されたMarkdown文字列を格納するデータを選択してください (更新) *
StrConfB8
B8: 生成されるMdChart文字列の最大数をセットしてください(デフォルト: 8000)#{EL}
SelectConfD1
D1: TSV行数を格納する数値型データを選択してください (更新)
SelectConfD2
D2: TSV行数(空行を無視)を格納する数値型データを選択してください (更新)
Script (click to open)
// Script Example of Business Process Automation
// for 'engine type: 3' ("GraalJS standard mode")


//////// START "main()" /////////////////////////////////////////////////////////////////
main();
function main(){ 

//// == Config Retrieving / 工程コンフィグの参照 ==
const strTsv        = configs.get       ( "StrConfA" );     // REQUIRED
  const arr2dTsv    = parseAsRectangular( strTsv );
  if( arr2dTsv.length === 0 ){
    throw new Error( "\n AutomatedTask ConfigError:" +
                     " Config {A: TSV} is empty \n" );
  }
  if( arr2dTsv.length === 1 ){
    throw new Error( "\n AutomatedTask ConfigError:" +
                     " Config {A: TSV} requires at least 2 lines (header and data) \n" );
  }

// 表示幅: [ユニット名, 片側棒グラフ, 片側合計値]
const strWidths     = configs.get       ( "StrConfB1" ) || "60,200,60"; // default
const arrWidths     = strWidths.split(",");
const numWidthUnit  = parseInt (arrWidths[0], 10) || 60;
const numWidthBar   = parseInt (arrWidths[1], 10) || 200;
const numWidthTotal = parseInt (arrWidths[2], 10) || 60;

// 色パレット: 同系グラデーション(中央から外側へ)
const strColorsL    = configs.get       ( "StrConfB2L" ) || "#c23,#e54,#f85,#fa9"; // default 赤橙グラデーション
const arrColorsL    = strColorsL.split(",").map(s => s.trim());
const strColorsR    = configs.get       ( "StrConfB2R" ) || "#17c,#29e,#8ce,#bdf"; // default 青系グラデーション
const arrColorsR    = strColorsR.split(",").map(s => s.trim());

const parsedScale   = parseFloat( configs.get( "StrConfB3" ) );
const numMaxScale   = (parsedScale > 0) ? parsedScale : 100;

// 片側目盛りラベル (中央0から最大値へ)
const strLabels     = configs.get       ( "StrConfB4" ) || "0,50,100%";
const arrLabels     = strLabels.split(",");
const leftLabels    = arrLabels.slice().reverse(); // 左側用 (最大値 -> 0)
const rightLabels   = arrLabels;                  // 右側用 (0 -> 最大値)

const strPrefSuf    = configs.get       ( "StrConfB5" ) || ","; // デフォルトはカンマのみ
const arrPrefSuf    = strPrefSuf.split(",");
const strPrefix     = escaper.escapeHtml( arrPrefSuf[0] || "" );
const strSuffix     = escaper.escapeHtml( arrPrefSuf.length > 1 ? arrPrefSuf[1] : "" );
const isShowLegend  = configs.getObject ( "BoolConfB6" );
const isShowLabels  = configs.getObject ( "BoolConfB7" );
const numMaxLength  = parseInt(configs.get("StrConfB8" ), 10) || 8000;
const strPocketC    = configs.getObject ( "SelectConfC" );
const numPocketD1   = configs.getObject ( "SelectConfD1" );
const numPocketD2   = configs.getObject ( "SelectConfD2" );


//// == Data Parsing & Label Column Detection ==
// データ行(2行目以降)を走査して、集計単位となる「中央ラベル列(非数値列)」を特定
const numCols = arr2dTsv[0].length;
let labelColIndex = -1;

for (let c = 0; c < numCols; c++) {
  let isNumericCol = true;
  for (let r = 1; r < arr2dTsv.length; r++) {
    const rawVal = arr2dTsv[r][c].trim();
    if (rawVal === "") continue;
    // カンマ、空白、通貨記号(¥, ¥, $, €)のみを除去して純粋な数値か判定
    const numCandidate = rawVal.replace(/[,\s¥¥$€%]/g, "");
    if (numCandidate === "" || isNaN(Number(numCandidate))) {
      isNumericCol = false;
      break;
    }
  }
  if (!isNumericCol) {
    labelColIndex = c;
    break; // 非数値(ラベル)が含まれる列を中心ラベル列と特定
  }
}

// 全列が純粋な数値(例: 202601 等のYYYYMM形式)で見つからない場合のフォールバック(中央列)
if (labelColIndex === -1) {
  labelColIndex = Math.floor(numCols / 2);
  engine.log(" AutomatedTask Warning: Label column not detected by text format. Defaulted to column index " + labelColIndex + ".");
}


//// == Calculating / 演算 ==
let strMarkdown = "";

// 1. 凡例の表示
// TSVの物理的並び順(左端列0から右端列numCols-1まで自然に流す)に統一
if (isShowLegend) {
  let strLegend = "";
  // 左系列: 列0から labelColIndex - 1 へ(画面の左端から中央へ向かう順)
  for (let i = 0; i < labelColIndex; i++) {
    const distFromCenter = (labelColIndex - 1) - i;
    const color = arrColorsL[distFromCenter % arrColorsL.length];
    strLegend += `<span style="color:${color}">■${escaper.escapeHtml(arr2dTsv[0][i])}</span> `;
  }
  // 中央ラベル列のヘッダー名
  strLegend += `<span style="color:#555;font-weight:bold">[${escaper.escapeHtml(arr2dTsv[0][labelColIndex])}]</span> `;
  // 右系列: labelColIndex + 1 から numCols - 1 へ(中央から右端へ向かう順)
  for (let i = labelColIndex + 1; i < numCols; i++) {
    const distFromCenter = i - (labelColIndex + 1);
    const color = arrColorsR[distFromCenter % arrColorsR.length];
    strLegend += `<span style="color:${color}">■${escaper.escapeHtml(arr2dTsv[0][i])}</span> `;
  }
  strMarkdown += strLegend + "\n";
}

// 2. 目盛りの表示
if (isShowLabels) {
  let strScale = `<div style="display:flex;align-items:center;color:#777;font-size:11px">`;
  strScale += `<span style="width:${numWidthTotal}px"></span>`;

  // 左目盛り (外側 -> 中央0)
  strScale += `<span style="display:flex;width:${numWidthBar}px;justify-content:space-between">`;
  for (let i = 0; i < leftLabels.length; i++) {
    strScale += `<span>${escaper.escapeHtml(leftLabels[i])}</span>`;
  }
  strScale += `</span>`;

  // 中央ラベルスペース
  strScale += `<span style="width:${numWidthUnit}px"></span>`;

  // 右目盛り (中央0 -> 外側)
  strScale += `<span style="display:flex;width:${numWidthBar}px;justify-content:space-between">`;
  for (let i = 0; i < rightLabels.length; i++) {
    strScale += `<span>${escaper.escapeHtml(rightLabels[i])}</span>`;
  }
  strScale += `</span>`;

  strScale += `<span style="width:${numWidthTotal}px"></span></div>`;
  strMarkdown += strScale + "\n";
}

// 3. 棒グラフの表示
for (let i = 1; i < arr2dTsv.length; i++) {
  let strRow = "";

  // 左系列の計算(中央から外側へ: labelColIndex - 1 から 0 へ)
  let totalValL = 0;
  const barsL = [];
  for (let j = labelColIndex - 1; j >= 0; j--) {
    const rawVal = arr2dTsv[i][j] ? arr2dTsv[i][j].replace(/[^0-9.-]/g, "") : "";
    const cellValue = parseFloat(rawVal) || 0;
    totalValL += cellValue;
    const distFromCenter = (labelColIndex - 1) - j;
    const color = arrColorsL[distFromCenter % arrColorsL.length];
    barsL.push({ val: cellValue, color: color });
  }

  // 右系列の計算(中央から外側へ: labelColIndex + 1 から numCols - 1 へ)
  let totalValR = 0;
  const barsR = [];
  for (let j = labelColIndex + 1; j < numCols; j++) {
    const rawVal = arr2dTsv[i][j] ? arr2dTsv[i][j].replace(/[^0-9.-]/g, "") : "";
    const cellValue = parseFloat(rawVal) || 0;
    totalValR += cellValue;
    const distFromCenter = j - (labelColIndex + 1);
    const color = arrColorsR[distFromCenter % arrColorsR.length];
    barsR.push({ val: cellValue, color: color });
  }

  // 1行のflexコンテナ開始
  strRow += `<div style="display:flex;align-items:center">`;

  // ① 左合計値(一番左端)
  strRow += `<span style="width:${numWidthTotal}px;text-align:right">`;
  strRow += `${strPrefix}${totalValL.toLocaleString()}${strSuffix} </span>`;

  // ② 左側棒グラフ(値が0より大きいセグメントのみ出力して文字数を節約)
  strRow += `<span style="width:${numWidthBar}px;background:#eee">`;
  strRow += `<span style="display:flex;flex-direction:row-reverse;height:10px">`;
  for (let b = 0; b < barsL.length; b++) {
    const ratio = Math.max(0, barsL[b].val / numMaxScale);
    const ratioRounded = parseFloat(ratio.toFixed(4));
    if (ratioRounded > 0) {
      strRow += `<span style="flex:${ratioRounded};background:${barsL[b].color}"></span>`;
    }
  }
  const blankRatioL = parseFloat(Math.max(0, 1 - (totalValL / numMaxScale)).toFixed(4));
  if (blankRatioL > 0) {
    strRow += `<span style="flex:${blankRatioL}"></span>`;
  }
  strRow += `</span></span>`;

  // ③ 中央ユニット名
  strRow += `<span style="width:${numWidthUnit}px;text-align:center;font-size:12px;overflow:hidden;white-space:nowrap">`;
  strRow += escaper.escapeHtml( arr2dTsv[i][labelColIndex] );
  strRow += `</span>`;

  // ④ 右側棒グラフ(左から右へ積む: flex-direction: row)
  strRow += `<span style="width:${numWidthBar}px;background:#eee">`;
  strRow += `<span style="display:flex;height:10px">`;
  for (let b = 0; b < barsR.length; b++) {
    const ratio = Math.max(0, barsR[b].val / numMaxScale);
    const ratioRounded = parseFloat(ratio.toFixed(4));
    if (ratioRounded > 0) {
      strRow += `<span style="flex:${ratioRounded};background:${barsR[b].color}"></span>`;
    }
  }
  // 余白(外側)
  const blankRatioR = parseFloat(Math.max(0, 1 - (totalValR / numMaxScale)).toFixed(4));
  if (blankRatioR > 0) {
    strRow += `<span style="flex:${blankRatioR}"></span>`;
  }
  strRow += `</span></span>`;

  // ⑤ 右合計値(一番右端)
  strRow += `<span style="width:${numWidthTotal}px">`;
  strRow += ` ${strPrefix}${totalValR.toLocaleString()}${strSuffix}</span>`;

  strRow += `</div>\n`;

  // 文字数制限チェック (B8)
  if (strMarkdown.length + strRow.length > numMaxLength) {
    engine.log("Warning: Reached Max Length (" + numMaxLength + ") at row " + i + ". Stopping chart generation to prevent unclosed HTML tags.");
    break; 
  }
  strMarkdown += strRow;
}


//// == Data Updating / ワークフローデータへの代入 ==

if ( strPocketC !== null) { 
  engine.setData( strPocketC, strMarkdown );
}

// オリジナルのTSV文字列の行数 (D1)
if ( numPocketD1 !== null) { 
  const totalLines = strTsv.replace(/\r\n?/g, "\n").split("\n").length;
  engine.setData( numPocketD1, new java.math.BigDecimal(totalLines) );
}

// 空行を除いたTSV行数 (D2)
if ( numPocketD2 !== null) { 
  engine.setData( numPocketD2, new java.math.BigDecimal(arr2dTsv.length) );
}

} //////// END "main()" /////////////////////////////////////////////////////////////////


/**
 * Parses TSV string as a two-dimensional rectangular data matrix and creates a 2D array.
 * @param {string} strTsv - The input TSV string
 * @returns {Array<Array<string>>} Rectangular 2D array
 */
function parseAsRectangular( strTsv ){
  const arrTsv = strTsv.replace(/\r\n?/g, "\n").split("\n");
  let numMinWidth   = Infinity;
  let numMaxWidth   = 0;
  let numBlanklines = 0;
  
  const parsedRows = [];
  for( let i = 0; i < arrTsv.length; i++ ){
    const line = arrTsv[i];
    if( line === "" ){
      numBlanklines++;
      continue;
    }
    const arrCells = line.split("\t");
    const len = arrCells.length;
    if( len < numMinWidth ){ numMinWidth = len; }
    if( len > numMaxWidth ){ numMaxWidth = len; }
    parsedRows.push( arrCells );
  }
  if( numMinWidth === Infinity ){
    numMinWidth = 0;
  }
  engine.log( " AutomatedTask TsvDataCheck:" + 
              " MinWidth:" + numMinWidth +
              " MaxWidth:" + numMaxWidth +
              " Lines:" + arrTsv.length +
              " (BlankLines:" + numBlanklines + ")" );

  for( let i = 0; i < parsedRows.length; i++ ){
    const row = parsedRows[i];
    while( row.length < numMaxWidth ){
      row.push( "" );
    }
  }
  return parsedRows;
}


/*
### NOTES-en
- A stacked butterfly chart (ButterflyMdChart string) is automatically generated each time a Case reaches this Automated Step.
    - The TSV format expects the unit label (such as "Quarter" or "YYYY-MM") to be in the middle column, flanked by left data series and right data series.
    - Data rows from the second line onward are inspected to automatically detect the aggregation unit column (the column containing non-numeric strings).
        - Characters like currency symbols ($ / ¥ / €) and thousands separator commas (,) are stripped before evaluating numeric values.
        - If all columns are numeric (e.g. pure numbers like "202601"), the center column is chosen as a fail-safe fallback.
    - The "ButterflyMdChart string" is an HTML string where `div` and `span` elements are arranged using flexbox.
        - Left series are accumulated and rendered from the center baseline outwards to the left (`flex-direction: row-reverse`).
        - Right series are accumulated and rendered from the center baseline outwards to the right (`flex-direction: row`).
        - Flex values are rounded to 4 decimal places to minimize HTML string length and prevent hitting character limits.
- The input TSV is parsed as the "simplest tab-separated string".
    - Double quotes and other characters within the TSV string are retained as is.
- The number of lines in the input TSV string can also be saved as Case Data.

### NOTES-ja
- このアドオン自動工程にケース(案件)が到達する度に、自動的に左右対称の積み上げバタフライチャート(ButterflyMdChart文字列)が生成されます。
    - 入力TSVは、中央の集計単位ラベル(「四半期」や「年月」など)を挟んで、左側に左系列データ、右側に右系列データが配置された形式を想定しています。
    - 2行目以降のデータ行を解析し、非数値文字列が含まれる列(中央列)が集計単位ラベルとして自動判定されます。
        - 通貨記号(¥, $, €)や桁区切りカンマ(,)は除去された上で数値判定が行われるため、"FY2026" や "2026-Q1" といった英字・記号付きラベルも正確に判定されます。
        - 全列が純粋な数値文字列("202601" など)の場合は、フェイルセーフとして中央付近の列が集計単位ラベルとして採用されます。
    - "ButterflyMdChart文字列" は `div` と `span` が flex 配置されたHTML文字列です。
        - 中央ラベル列の左側にある各系列は、中央軸から外側(左方向)へ積み上げ描画されます。
        - 中央ラベル列の右側にある各系列は、中央軸から外側(右方向)へ積み上げ描画されます。
        - flex比率は小数点第4位に丸められ、HTML文字列長の消費(8,000文字上限)を抑えるよう最適化されています。
- 入力TSVは「もっともシンプルなタブ区切り文字列」としてパースされます。
    - TSV文字列内のダブルクオート文字等も、そのまま保持されます。
- 入力TSV文字列の行数もケースデータとして格納可能です。

#### TSV example
SG&A	R&D	Labor	Material	Quarter	Domestic	NorthAmerica	Europe	APAC
10	12	18	22	2025-Q1	28	20	14	10
11	13	19	23	2025-Q2	30	22	15	11
12	14	20	24	2025-Q3	31	23	16	12
13	15	21	26	2025-Q4	34	26	18	14
11	14	19	24	2026-Q1	31	23	16	12
12	15	20	25	2026-Q2	33	25	17	13
13	16	21	26	2026-Q3	35	26	18	14

### APPENDIX-en
- Blank lines within the input TSV string are ignored.
- Pixel Widths (B1): Set CSV values as "Unit Width, Bar Width (one side), Total Width (one side)". The entire row width will be Total + Bar + Unit + Bar + Total.
- Scale Labels (B4): Specify scale values from center (0) to outer edge (max). Left-side labels are automatically reversed.
- The order of colors specified in CSV applies from the center baseline outwards to the sides:
    - Left Series Colors (B2L): The 1st color is assigned to the column immediately to the left of the center label, the 2nd color to the next column outward, and so on.
    - Right Series Colors (B2R): The 1st color is assigned to the column immediately to the right of the center label, the 2nd color to the next column outward, and so on.
- The legend order matches the visual left-to-right order of the TSV table and stacked bars.
- You can specify a prefix and suffix for total values on both ends:
    - To add only a prefix: Set `$,` → `$62`
    - To add only a suffix: Set `,M` → `62M`
    - To add both: Set `approx. , units` → `approx. 62 units`

### APPENDIX-ja
- 入力TSV文字列内の空行は無視されます。
- 表示幅(B1):「ユニット名幅, 棒グラフ幅(片側), 合計値幅(片側)」をCSVで指定します。行全体の表示幅は「合計値 + 棒グラフ + ユニット名 + 棒グラフ + 合計値」となります。
- 目盛り文字列(B4):「中央(0)から最大値に向かう順」で指定します。左側目盛りには自動的に反転した順序で配置されます。
- 系列色のCSV設定は、左右ともに「中央軸から外側に向かう順」で適用されます。
    - 左系列(B2L):1番目の色が中央ラベルの直左の列に、2番目の色がさらにその外側の列に適用されます。
    - 右系列(B2R):1番目の色が中央ラベルの直右の列に、2番目の色がさらにその外側の列に適用されます。
- 凡例は、チャートおよびTSVの並びと同じく「左端から中央を経て右端へ流れる自然な順序」で出力されます。
- 左右の合計値には共通の接頭辞・接尾辞を指定できます。
    - 前だけにつけたい場合: `¥,` と設定 → `¥62`
    - 後ろだけにつけたい場合: `,百万円` と設定 → `62百万円`
    - 前後両方につけたい場合: `約,件` と設定 → `約62件`
*/

Download

warning 自由改変可能な JavaScript (ECMAScript) コードです。いかなる保証もありません。
(アドオン自動工程のインストールは Professional editionでのみ可能です)

Notes

  • このアドオン自動工程にケース(案件)が到達する度に、自動的に左右対称の積み上げバタフライチャート(ButterflyMdChart文字列)が生成されます。
    • 入力TSVは、中央の集計単位ラベル(「四半期」や「年月」など)を挟んで、左側に左系列データ、右側に右系列データが配置された形式を想定しています。
    • 2行目以降のデータ行を解析し、非数値文字列が含まれる列(中央列)が集計単位ラベルとして自動判定されます。
      • 通貨記号(¥, $, ?)や桁区切りカンマ(,)は除去された上で数値判定が行われるため、”FY2026″ や “2026-Q1” といった英字・記号付きラベルも正確に判定されます。
      • 全列が純粋な数値文字列(”202601″ など)の場合は、フェイルセーフとして中央付近の列が集計単位ラベルとして採用されます。
    • “ButterflyMdChart文字列” は div と span が flex 配置されたHTML文字列です。
      • 中央ラベル列の左側にある各系列は、中央軸から外側(左方向)へ積み上げ描画されます。
      • 中央ラベル列の右側にある各系列は、中央軸から外側(右方向)へ積み上げ描画されます。
      • flex比率は小数点第4位に丸められ、HTML文字列長の消費(8,000文字上限)を抑えるよう最適化されています。
  • 入力TSVは「もっともシンプルなタブ区切り文字列」としてパースされます。
    • TSV文字列内のダブルクオート文字等も、そのまま保持されます。
  • 入力TSV文字列の行数もケースデータとして格納可能です。

Capture

Appendix

  • 入力TSV文字列内の空行は無視されます。
  • 表示幅(B1):「ユニット名幅, 棒グラフ幅(片側), 合計値幅(片側)」をCSVで指定します。行全体の表示幅は「合計値 + 棒グラフ + ユニット名 + 棒グラフ + 合計値」となります。
  • 目盛り文字列(B4):「中央(0)から最大値に向かう順」で指定します。左側目盛りには自動的に反転した順序で配置されます。
  • 系列色のCSV設定は、左右ともに「中央軸から外側に向かう順」で適用されます。
    • 左系列(B2L):1番目の色が中央ラベルの直左の列に、2番目の色がさらにその外側の列に適用されます。
    • 右系列(B2R):1番目の色が中央ラベルの直右の列に、2番目の色がさらにその外側の列に適用されます。
  • 凡例は、チャートおよびTSVの並びと同じく「左端から中央を経て右端へ流れる自然な順序」で出力されます。
  • 左右の合計値には共通の接頭辞・接尾辞を指定できます。
    • 前だけにつけたい場合: ¥, と設定 → ¥62
    • 後ろだけにつけたい場合: ,百万円 と設定 → 62百万円
    • 前後両方につけたい場合: 約,件 と設定 → 約62件

See Also