Your Name 478562c312
Some checks failed
Lint / build (20) (push) Has been cancelled
Playwright Tests / test (push) Has been cancelled
feat: migrate product planning workspace
2026-03-26 16:38:48 +08:00

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));
}