@opengis/bi
Version:
BI data visualization module
79 lines (63 loc) • 2.51 kB
JavaScript
import { createHash } from 'node:crypto';
import { dataInsert, dataUpdate, getPGAsync, pgClients } from "@opengis/fastify-table/utils.js";
/* eslint-disable import/extensions */
import { yamlSafe } from '../../../../utils.js';
function generateUniqueName(prefix = 'bar') {
const randomPart = Math.floor(Math.random() * 10000);
const timestamp = Date.now();
return `${prefix}_${randomPart}_${timestamp}`;
}
export default async function widgetAdd({ pg = pgClients.client, params = {}, body = {} }) {
const { name: dashboardName } = params;
if (!dashboardName) {
return { message: 'not enough params: id', status: 400 };
}
const data = body.yml ? yamlSafe.load(body.yml) : body;
const row = await pg.query(`select dashboard_id, widgets, panels, table_name, db from bi.dashboard
where $1 in (dashboard_id,name)`, [dashboardName]).then(el => el.rows?.[0] || {});
const pg1 = row?.db ? await getPGAsync(row.db) : pg;
const tableName = data.data?.table
|| data?.table
|| data.table_name
|| row.table_name;
const loadTemplate = pg1.pk?.['admin.doc_template'] ? await pg1.query(
'select body from admin.doc_template where doc_type=5 and title=$1',
[tableName]
).then(el => el.rows?.[0]?.body) : null;
if (!tableName || !(pg.pk?.[loadTemplate?.table || tableName] || pgClients[data.db || row.db || 'client']?.pk?.[loadTemplate?.table || tableName])) {
return { message: 'bad params: table', status: 400 };
}
const { dashboard_id: dashboardId } = row;
const metric = data.data?.metrics || data.data?.metric || data?.metrics || data?.metric;
Object.assign(data, {
name: generateUniqueName(data.type),
table_name: tableName,
metrics: Array.isArray(metric) ? metric[0] : metric,
});
data.widget_id = createHash('md5').update([data?.name, dashboardId].join()).digest('hex').substr(0, 10);
const res = await dataUpdate({
pg,
table: 'bi.dashboard',
id: dashboardId,
data: {
widgets: [data].concat(row.widgets || []),
panels: [{ widget: data.name, col: data.col || 3, height: data.data?.height }].concat(
row.panels || []
),
},
});
const widgetData = { ...data, data, dashboard_id: dashboardId };
if (body?.yml) Object.assign(widgetData, { yml: body.yml });
await dataInsert({
pg,
table: 'bi.widget',
data: widgetData,
});
return {
dashboard: dashboardName,
widgetId: data.widget_id,
widgetName: data.name,
status: 200,
rows: res,
};
}