UNPKG

@opengis/fastify-table

Version:

core-plugins

130 lines (129 loc) 5.6 kB
import getTemplate from "../../../plugins/table/funcs/getTemplate.js"; import pgClients from "../../../plugins/pg/pgClients.js"; import getToken from "../../../plugins/crud/funcs/getToken.js"; import { handlebarsSync } from "../../../../utils.js"; function dayOfTheYear(date) { const start = new Date(date.getFullYear(), 0, 0); const diff = date - start.getTime() + (start.getTimezoneOffset() - date.getTimezoneOffset()) * 60 * 1000; const oneDay = 1000 * 60 * 60 * 24; const day = Math.floor(diff / oneDay); return day; } const optionsKeys = [ "HH", "HH12", "HH24", "MI", "SS", "YYYY", "YY", "MONTH", "MON", "MM", "D", "DD", "DDD", // "NUMM", // "NUMY", ]; const regexp = new RegExp(`\\b(${optionsKeys.join("|")}|NUM[MY]\\s?\\d?)\\b`, "gi"); function getOptions(data = {}, pattern = "", numYear = 0, nextNum = 0) { const date = new Date(); const options = { HH: date.getHours(), // hours 24h: 14:00 = 14 HH12: (date.getHours() + 24) % 12 || 12, // hours 12h: 14:00 = 2 HH24: date.getHours(), // hours 24h: 14:00 = 14 MI: date.getMinutes(), // minutes SS: date.getSeconds(), // seconds YYYY: date.getFullYear(), // full year: 2025 YY: date.getFullYear().toString().substring(2, 4), // last 2 digits of year: 25 MONTH: date.toLocaleString("en", { month: "long" }).toUpperCase(), // month name: MARCH MON: date .toLocaleString("en", { month: "long" }) .substring(0, 3) .toUpperCase(), // month name abbrev: MAR MM: date.getMonth() + 1, // month number: 1 - january, 12 - december D: date.getDay(), // day of the week: 1 - monday, 7 - sunday DD: date.getDate(), // day of the month: january 4 = 4 DDD: dayOfTheYear(date), // day of the year: march 4 = 63 ...data, }; const template = pattern.match(/NUM[M|Y] ?\d?/g)?.reduce((acc, curr) => { const value = handlebarsSync.compile("{{paddingNumber value padding}}")({ padding: curr.substring(4, curr.length)?.trim?.() || 6, value: curr.startsWith("NUMY") ? +numYear : +nextNum, }); return acc.replace(curr.startsWith("{{{") ? `{{{${curr}}}}` : `{{${curr}}}`, value); }, pattern) || pattern; return { template, options }; } export default async function codeGenerator({ pg = pgClients.client, params = {}, user = {}, query = {}, }, reply) { const { token, column } = params; const data = query.data?.split?.(";") || []; if (!token || !column) { return reply.status(400).send("not enough params: token / column"); } if (!user?.uid) { return reply.status(401).send("unauthorized"); } const tokenData = (await getToken({ token, uid: user?.uid, json: 1 })) || {}; const currentYear = new Date().getFullYear(); // unique entity per table, table as key - property_text = pattern as yyyy-mm-dd/numy if (pg?.pk?.[token]) { const pattern1 = pg ? await pg .query(`select property_text from admin.properties where property_entity=$1 and property_key=$2`, [`code:${column.replace(/'/g, "''")}`, token]) .then((el) => el.rows?.[0]?.property_text) : null; // force pattern keys to upperCase for handlebars compile const pattern = (pattern1 || column).replace(regexp, (_, m) => `{{${m.toUpperCase()}}}`); const count = pg ? await pg .query(`select count(*) + 1 as count from ${token}`) .then((el) => el.rows?.[0]?.count || 0) : 0; const numYear = pg ? await pg .query(`select count(*) + 1 as count from ${token} where date_part('year', created_at)=$1`, [currentYear]) .then((el) => el.rows?.[0]?.count || 0) : 0; const { template, options } = getOptions(data, pattern, numYear, count); const result = handlebarsSync.compile(template)(options); return reply.status(200).send(result); } if (!tokenData?.form || !tokenData?.table) { return reply.status(401).send("token not allow"); } const loadTemplate = await getTemplate("form", tokenData.form); const schema = loadTemplate?.schema || loadTemplate; if (!schema) { return reply.status(404).send("form not found"); } if (!schema?.[column]?.template) { return reply.status(400).send("template not specified"); } const columnValue = data .find((el) => el.startsWith(column)) ?.split("=") ?.pop(); const loadTable = await getTemplate("table", tokenData.table); const table = loadTable?.table || tokenData.table; if (!pg.pk?.[table]) { return reply.status(404).send("table pk not found"); } const count = pg ? await pg .query(`select count(*) + 1 as count from ${table} where ${columnValue ? `${column}::text = '${columnValue}'` : "true"} limit 1`) .then((el) => el.rows?.[0]?.count || 0) : 0; const numYear = pg ? await pg .query(`select ${column} + 1 as count from ${table} where ${column} is not null and date_part('year', cdate) = $1 order by cdate desc limit 1`, [currentYear]) .then((el) => el.rows?.[0]?.count || 0) : 0; const { template, options } = getOptions(data, schema[column].template, numYear, count); const result = handlebarsSync.compile(template)(options); return reply.status(200).send(result); }