80 lines
2.4 KiB
TypeScript
80 lines
2.4 KiB
TypeScript
import type { ProductPlanningTemplate } from "./types";
|
|
import { normalizeText } from "./utils";
|
|
|
|
export const PRODUCT_PLANNING_TEMPLATES_KEY = "product_planning_keyword_templates";
|
|
|
|
function toValidDateString(value: unknown) {
|
|
const text = String(value || "").trim();
|
|
if (!text) return null;
|
|
|
|
const date = new Date(text);
|
|
if (Number.isNaN(date.getTime())) return null;
|
|
return date.toISOString();
|
|
}
|
|
|
|
export function normalizeTemplateCategoryName(value: unknown) {
|
|
return normalizeText(value).replace(/\s+/g, " ");
|
|
}
|
|
|
|
export function parseProductPlanningTemplates(value: unknown) {
|
|
if (!Array.isArray(value)) return [] as ProductPlanningTemplate[];
|
|
|
|
const templates: ProductPlanningTemplate[] = [];
|
|
|
|
for (const entry of value) {
|
|
if (!entry || typeof entry !== "object") continue;
|
|
|
|
const record = entry as Record<string, unknown>;
|
|
const id = normalizeText(record.id);
|
|
const categoryName = normalizeTemplateCategoryName(record.categoryName);
|
|
const fileName = normalizeText(record.fileName);
|
|
const fileUrl = normalizeText(record.fileUrl);
|
|
const createdAt = toValidDateString(record.createdAt);
|
|
const updatedAt = toValidDateString(record.updatedAt) || createdAt;
|
|
const fileSize = Number.parseInt(String(record.fileSize || "0"), 10);
|
|
|
|
if (
|
|
!id ||
|
|
!categoryName ||
|
|
!fileName ||
|
|
!fileUrl ||
|
|
!createdAt ||
|
|
!updatedAt ||
|
|
!Number.isFinite(fileSize)
|
|
) {
|
|
continue;
|
|
}
|
|
|
|
templates.push({
|
|
id,
|
|
categoryName,
|
|
description: normalizeText(record.description) || undefined,
|
|
fileName,
|
|
fileUrl,
|
|
filePath: normalizeText(record.filePath) || undefined,
|
|
fileSize,
|
|
contentType: normalizeText(record.contentType) || undefined,
|
|
createdAt,
|
|
updatedAt,
|
|
uploadedById: normalizeText(record.uploadedById) || undefined,
|
|
});
|
|
}
|
|
|
|
return templates.sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
|
|
}
|
|
|
|
export function upsertProductPlanningTemplate(
|
|
templates: ProductPlanningTemplate[],
|
|
template: ProductPlanningTemplate
|
|
) {
|
|
return [
|
|
template,
|
|
...templates.filter(
|
|
(entry) =>
|
|
entry.id !== template.id &&
|
|
normalizeTemplateCategoryName(entry.categoryName) !==
|
|
normalizeTemplateCategoryName(template.categoryName)
|
|
),
|
|
].sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
|
|
}
|