260914_01_ENH: 1차 완성

This commit is contained in:
2026-09-14 15:07:40 +09:00
parent a6642c9a00
commit f1d21d3711
67 changed files with 5595 additions and 148 deletions

View File

@@ -0,0 +1,108 @@
import {parseLocalDateString, toLocalDateString} from "@/lib/kmusical/date";
import type {PerformanceFull, PerformanceReviewSlot} from "@/types/kmusical";
export const WEEKDAY_LABELS = ["일", "월", "화", "수", "목", "금", "토"] as const;
export const MONTH_GRID_CELL_COUNT = 42;
export type CalendarDay = {
date: Date;
dateKey: string;
isCurrentMonth: boolean;
isToday: boolean;
};
export const buildMonthGrid = (visibleMonth: Date): CalendarDay[] => {
const year = visibleMonth.getFullYear();
const month = visibleMonth.getMonth();
const firstDayOfMonth = new Date(year, month, 1);
const startDate = new Date(year, month, 1 - firstDayOfMonth.getDay());
const today = toLocalDateString();
return Array.from({length: MONTH_GRID_CELL_COUNT}, (_, index) => {
const date = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate() + index);
const dateKey = toLocalDateString(date);
return {
date,
dateKey,
isCurrentMonth: date.getMonth() === month,
isToday: dateKey === today,
};
});
};
export const chunkIntoWeeks = (days: CalendarDay[]): CalendarDay[][] => {
const weeks: CalendarDay[][] = [];
for (let index = 0; index < days.length; index += 7) {
weeks.push(days.slice(index, index + 7));
}
return weeks;
};
export const getVisiblePerformances = (
performances: PerformanceFull[],
selectedPerformanceIds: Set<string>,
selectedReviewerIds: string[]
): PerformanceFull[] => {
const reviewerIdSet = new Set(selectedReviewerIds);
return performances.filter((performance) => {
const selectedByPerformance = selectedPerformanceIds.has(performance.performanceId);
const selectedByReviewer = reviewerIdSet.size === 0
|| performance.performanceAssignList.some((assign) => reviewerIdSet.has(assign.assignUser));
return selectedByPerformance && selectedByReviewer;
});
};
const comparePerformancesInDay = (a: PerformanceFull, b: PerformanceFull) =>
(a.performanceMonitoringSchedule?.monitoringTimeInfo ?? "").localeCompare(b.performanceMonitoringSchedule?.monitoringTimeInfo ?? "", "ko")
|| a.performanceName.localeCompare(b.performanceName, "ko")
|| a.performanceId.localeCompare(b.performanceId, "ko");
export const groupPerformancesByDate = (performances: PerformanceFull[]): Map<string, PerformanceFull[]> => {
const grouped = new Map<string, PerformanceFull[]>();
for (const performance of performances) {
const date = parseLocalDateString(performance.performanceMonitoringSchedule?.monitoringDate);
if (!date) continue;
const dateKey = toLocalDateString(date);
const list = grouped.get(dateKey) ?? [];
list.push(performance);
grouped.set(dateKey, list);
}
for (const list of grouped.values()) {
list.sort(comparePerformancesInDay);
}
return grouped;
};
export const PERFORMANCE_COLOR_SLOT_COUNT = 8;
export const getPerformanceColorSlot = (performanceId: string, orderedPerformanceIds: string[]): number => {
const index = orderedPerformanceIds.indexOf(performanceId);
return index < 0 ? 0 : index % PERFORMANCE_COLOR_SLOT_COUNT;
};
export type PerformanceBadgeInfo = {
applyCount: number;
assignCount: number;
requiredAssignCount: number;
isMatchingComplete: boolean;
};
export const getPerformanceBadgeInfo = (
performance: PerformanceFull,
applyCountMap: Map<string, number>,
reviewSlots: PerformanceReviewSlot[]
): PerformanceBadgeInfo => {
const applyCount = applyCountMap.get(performance.performanceId) ?? 0;
const assignCount = performance.performanceAssignList.length;
const requiredAssignCount = reviewSlots.length;
const isMatchingComplete = requiredAssignCount > 0 && assignCount >= requiredAssignCount;
return {applyCount, assignCount, requiredAssignCount, isMatchingComplete};
};

13
src/lib/kmusical/date.ts Normal file
View File

@@ -0,0 +1,13 @@
export const toLocalDateString = (date = new Date()) => {
const pad = (value: number) => String(value).padStart(2, "0");
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
};
export const parseLocalDateString = (value: string | undefined | null): Date | null => {
const match = value ? /^(\d{4})-(\d{2})-(\d{2})/.exec(value) : null;
if (!match) return null;
const [, year, month, day] = match;
const date = new Date(Number(year), Number(month) - 1, Number(day));
return Number.isNaN(date.getTime()) ? null : date;
};

View File

@@ -0,0 +1,225 @@
"use client";
import DOMPurify, { type DOMPurify as DOMPurifyInstance } from "dompurify";
import type { KriEditorWysiwygCompatibility } from "@/components/kri-editor";
const EMAIL_ALLOWED_ATTRIBUTES = {
a: ["href", "title", "style", "target", "rel"],
area: ["shape", "coords", "href", "alt", "title", "target"],
b: ["style"],
blockquote: ["cite"],
col: ["span", "width"],
colgroup: ["span", "width"],
div: ["style", "align"],
img: ["src", "width", "height", "alt", "title", "align", "style", "loading", "usemap"],
map: ["name", "id"],
mark: ["style", "data-color"],
ol: ["start", "type"],
p: ["style"],
q: ["cite"],
qrcode: ["src", "width", "height", "alt"],
span: ["style"],
table: ["summary", "width", "height", "style", "cellpadding", "cellspacing", "border", "align", "bgcolor", "role"],
tbody: ["style", "align", "valign"],
td: ["abbr", "axis", "colspan", "rowspan", "width", "height", "style", "align", "valign", "bgcolor"],
th: ["abbr", "axis", "colspan", "rowspan", "scope", "width", "height", "style", "align", "valign", "bgcolor"],
tr: ["style", "align", "valign", "bgcolor", "height"],
ul: ["type"],
} as const;
export const EMAIL_ALLOWED_TAGS = [
"a", "area", "b", "blockquote", "br", "caption", "cite", "code", "col", "colgroup", "dd", "div", "dl", "dt",
"em", "h1", "h2", "h3", "h4", "h5", "h6", "i", "img", "li", "map", "mark", "ol", "p", "pre", "q", "qrcode",
"small", "span", "strike", "strong", "sub", "sup", "table", "tbody", "td", "tfoot", "th", "thead", "tr", "u", "ul",
] as const;
const TAGS_WITHOUT_ATTRIBUTES = new Set(
EMAIL_ALLOWED_TAGS.filter((tag) => !(tag in EMAIL_ALLOWED_ATTRIBUTES)),
);
const ALLOWED_TAG_SET = new Set<string>(EMAIL_ALLOWED_TAGS);
const ALLOWED_ATTRIBUTE_SET = new Set<string>(Object.values(EMAIL_ALLOWED_ATTRIBUTES).flat());
const ALLOWED_PROTOCOLS: Record<string, ReadonlySet<string>> = {
"a.href": new Set(["http", "https", "mailto", "tel", "ftp"]),
"area.href": new Set(["http", "https", "mailto", "tel"]),
"img.src": new Set(["http", "https"]),
"blockquote.cite": new Set(["http", "https"]),
"q.cite": new Set(["http", "https"]),
};
const WYSIWYG_ATTRIBUTES: Record<string, ReadonlySet<string>> = {
a: new Set(["href", "target", "rel", "class"]),
area: new Set(EMAIL_ALLOWED_ATTRIBUTES.area),
div: new Set(["style", "class"]),
img: new Set([...EMAIL_ALLOWED_ATTRIBUTES.img, "class", "data-kri-image"]),
map: new Set(EMAIL_ALLOWED_ATTRIBUTES.map),
mark: new Set(EMAIL_ALLOWED_ATTRIBUTES.mark),
ol: new Set(["start"]),
p: new Set(["style"]),
qrcode: new Set(EMAIL_ALLOWED_ATTRIBUTES.qrcode),
span: new Set(["style"]),
td: new Set(["colspan", "rowspan"]),
th: new Set(["colspan", "rowspan"]),
};
const WYSIWYG_TAGS = new Set([
"a", "area", "b", "br", "div", "em", "i", "img", "li", "map", "mark", "ol", "p", "qrcode", "span", "strong",
"table", "tbody", "td", "th", "tr", "u", "ul",
]);
const WYSIWYG_SPAN_STYLE_PROPERTIES = new Set(["color", "font-family", "font-size"]);
const WYSIWYG_PARAGRAPH_STYLE_PROPERTIES = new Set(["text-align"]);
function resolvePurifier(): DOMPurifyInstance | null {
if (typeof window === "undefined") return null;
if (typeof DOMPurify.sanitize === "function") return DOMPurify;
return DOMPurify(window);
}
function parseHtml(html: string): HTMLTemplateElement | null {
if (typeof document === "undefined") return null;
const template = document.createElement("template");
template.innerHTML = html;
return template;
}
function allowedAttributesFor(tagName: string): ReadonlySet<string> {
if (TAGS_WITHOUT_ATTRIBUTES.has(tagName as typeof EMAIL_ALLOWED_TAGS[number])) return new Set();
return new Set((EMAIL_ALLOWED_ATTRIBUTES as Record<string, readonly string[]>)[tagName] ?? []);
}
function hasAllowedProtocol(tagName: string, attributeName: string, value: string): boolean {
const protocols = ALLOWED_PROTOCOLS[`${tagName}.${attributeName}`];
if (!protocols) return true;
const match = /^([a-z][a-z\d+.-]*):/i.exec(value.trim());
return Boolean(match && protocols.has(match[1].toLowerCase()));
}
function styleProperties(value: string): Set<string> {
return new Set(
value.split(";")
.map((declaration) => declaration.split(":", 1)[0]?.trim().toLowerCase())
.filter((property): property is string => Boolean(property)),
);
}
function isWysiwygStyleCompatible(tagName: string, value: string): boolean {
if (tagName === "div" || tagName === "img" || tagName === "mark") return true;
const supported = tagName === "span"
? WYSIWYG_SPAN_STYLE_PROPERTIES
: tagName === "p" ? WYSIWYG_PARAGRAPH_STYLE_PROPERTIES : null;
return Boolean(supported && [...styleProperties(value)].every((property) => supported.has(property)));
}
function summarizeIssues(issues: readonly string[]): string {
const unique = [...new Set(issues)];
const visible = unique.slice(0, 3).join(", ");
const suffix = unique.length > 3 ? ` 외 ${unique.length - 3}개` : "";
return `${visible}${suffix} 항목은 WYSIWYG에서 손실될 수 있어 HTML 모드로 유지됩니다.`;
}
export function getEmailWysiwygCompatibility(html: string): KriEditorWysiwygCompatibility {
const template = parseHtml(html);
const issues: string[] = [];
if (!template) {
const tags = [...html.matchAll(/<\/?\s*([a-z][\w-]*)\b/gi)].map((match) => match[1].toLowerCase());
for (const tagName of tags) {
if (!WYSIWYG_TAGS.has(tagName)) issues.push(`<${tagName}>`);
}
} else {
for (const element of Array.from(template.content.querySelectorAll("*"))) {
const tagName = element.tagName.toLowerCase();
if (!WYSIWYG_TAGS.has(tagName)) {
issues.push(`<${tagName}>`);
continue;
}
const supportedAttributes = WYSIWYG_ATTRIBUTES[tagName] ?? new Set<string>();
for (const attribute of Array.from(element.attributes)) {
const attributeName = attribute.name.toLowerCase();
if (!supportedAttributes.has(attributeName)) {
issues.push(`<${tagName}>의 ${attributeName}`);
} else if (attributeName === "style" && !isWysiwygStyleCompatible(tagName, attribute.value)) {
issues.push(`<${tagName}>의 일부 style`);
}
}
if (tagName === "area" && element.parentElement?.tagName.toLowerCase() !== "map") {
issues.push("<map> 밖의 <area>");
}
}
}
return issues.length > 0
? { compatible: false, reason: summarizeIssues(issues) }
: { compatible: true };
}
function isEditorDecoration(tagName: string, attributeName: string, value: string): boolean {
if (tagName === "a" && attributeName === "class" && value === "kri-editor-link") return true;
if (tagName !== "img") return false;
return (attributeName === "class" && value === "max-w-full h-auto")
|| (attributeName === "data-kri-image" && value === "true");
}
export function getEmailHtmlPolicyIssues(html: string): string[] {
const template = parseHtml(html);
if (!template) return [];
const issues: string[] = [];
for (const element of Array.from(template.content.querySelectorAll("*"))) {
const tagName = element.tagName.toLowerCase();
if (!ALLOWED_TAG_SET.has(tagName)) {
issues.push(`<${tagName}> 태그`);
continue;
}
const allowedAttributes = allowedAttributesFor(tagName);
for (const attribute of Array.from(element.attributes)) {
const attributeName = attribute.name.toLowerCase();
if (isEditorDecoration(tagName, attributeName, attribute.value)) continue;
if (!allowedAttributes.has(attributeName)) {
issues.push(`<${tagName}>의 ${attributeName} 속성`);
} else if (!hasAllowedProtocol(tagName, attributeName, attribute.value)) {
issues.push(`<${tagName}>의 ${attributeName} URL`);
}
}
}
return [...new Set(issues)];
}
export function hasImageMapMarkup(html: string): boolean {
if (!html) return false;
const template = parseHtml(html);
if (!template) return /<\s*(map|area)\b/i.test(html);
return template.content.querySelector("map, area") !== null;
}
export function sanitizeEmailHtml(html: string): string {
if (!html) return "";
const purifier = resolvePurifier();
if (!purifier) return html.replace(/<[^>]*>/g, "");
const sanitized = purifier.sanitize(html, {
ALLOWED_TAGS: [...EMAIL_ALLOWED_TAGS],
ALLOWED_ATTR: [...ALLOWED_ATTRIBUTE_SET],
ALLOW_DATA_ATTR: false,
});
const template = parseHtml(sanitized);
if (!template) return "";
for (const element of Array.from(template.content.querySelectorAll("*"))) {
const tagName = element.tagName.toLowerCase();
const allowedAttributes = allowedAttributesFor(tagName);
for (const attribute of Array.from(element.attributes)) {
const attributeName = attribute.name.toLowerCase();
if (!allowedAttributes.has(attributeName) || !hasAllowedProtocol(tagName, attributeName, attribute.value)) {
element.removeAttribute(attribute.name);
}
}
}
return template.innerHTML.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g, "").trim();
}

View File

@@ -0,0 +1,61 @@
export const USER_FIELD_LABELS = {
userId: "ID",
userName: "이름",
userCmpn: "소속",
userTeam: "팀",
userGrade: "직급",
userRole: "권한",
userArea: "지역",
userGender: "성별",
userAge: "연령",
userGenre: "분야",
userHasCar: "차량 보유",
userTel: "연락처",
userEmail: "이메일",
memo: "메모",
} as const;
export const PERFORMANCE_FIELD_LABELS = {
performanceNo: "NO",
performanceId: "연번",
businessType: "사업유형",
performanceArea: "지역",
performanceAreaDetail: "지역 세부",
artistName: "단체명",
performanceName: "작품명",
performanceStartMonth: "사업 수행 월",
performanceDtInfo: "사업 일정",
performanceTimeInfo: "운영 시간",
ticketReservationStatus: "티켓 예약",
ticketReservationMemo: "티켓 비고",
performanceMemo: "메모",
monitoringDate: "모니터링 일정",
monitoringTimeInfo: "모니터링 시간",
monitoringAddress: "모니터링 방문장소",
monitoringPaymentDate: "요원 비용지급일",
consultingStatus: "컨설팅 진행여부",
checkDeliver: "교부여부",
checkReport: "보고서 확인여부",
ownStaffName: "대표자 명",
ownStaffTel1: "대표자 연락처1",
ownStaffTel2: "대표자 연락처2",
ownStaffEmail: "대표자 이메일",
contactStaffName: "실무자 명",
contactStaffTel1: "실무자 연락처1",
contactStaffTel2: "실무자 연락처2",
contactStaffEmail: "실무자 이메일",
clientManagerName: "예경 담당자 명",
} as const;
export const SEND_PARAM_LABELS = {
...USER_FIELD_LABELS,
...PERFORMANCE_FIELD_LABELS,
} as const;
export const getSendParamLabel = (key: string) =>
SEND_PARAM_LABELS[key as keyof typeof SEND_PARAM_LABELS] ?? key;

51
src/lib/kmusical/file.ts Normal file
View File

@@ -0,0 +1,51 @@
import {downloadFile} from "@kri/common/browser";
const trimDispositionValue = (value: string) => value.trim().replace(/^"|"$/g, "");
const decodeDispositionValue = (value: string) => {
const trimmed = trimDispositionValue(value);
const encodedValue = trimmed.includes("''") ? trimmed.split("''").slice(1).join("''") : trimmed;
try {
return decodeURIComponent(encodedValue);
} catch {
return encodedValue;
}
};
const getDispositionParams = (contentDisposition: string) =>
contentDisposition
.split(";")
.slice(1)
.map((part) => part.trim())
.reduce<Record<string, string>>((params, part) => {
const separatorIndex = part.indexOf("=");
if (separatorIndex < 0) return params;
const key = part.slice(0, separatorIndex).trim().toLowerCase();
const value = part.slice(separatorIndex + 1).trim();
if (key && value) params[key] = value;
return params;
}, {});
export const getFileNameFromContentDisposition = (contentDisposition?: string | null) => {
if (!contentDisposition) return undefined;
const params = getDispositionParams(contentDisposition);
const fileName = params["filename*"] || params.filename;
return fileName ? decodeDispositionValue(fileName) : undefined;
};
export const downloadBlob = (buffer: ArrayBuffer, fileName: string, type = "application/octet-stream") => {
downloadFile(new Blob([buffer], {type}), fileName);
};
export const downloadExcelBuffer = (buffer: ArrayBuffer, fileName: string) => {
downloadBlob(buffer, fileName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
};
export const downloadFromUrl = (url: string) => {
const link = document.createElement("a");
link.href = url;
link.download = "";
document.body.appendChild(link);
link.click();
link.remove();
};

View File

@@ -0,0 +1,48 @@
import {PerformanceFull, UserCompact} from "@/types/kmusical";
import {SEND_TYPE, TMPLAT_PURPOSE, Template} from "@/types/notification";
export const PHONE_VERIFICATION_PREVIEW = "인증번호는 [######] 입니다.";
export const isPhoneVerificationSupported = (template: Pick<Template, "tmplatTy">) =>
template.tmplatTy === SEND_TYPE.EMAIL || template.tmplatTy === SEND_TYPE.SMS;
export const buildTemplatePreviewBody = (template: Pick<Template, "tmplatBody" | "tmplatPurpose">) =>
template.tmplatPurpose === TMPLAT_PURPOSE.PHONE_VERIFICATION
? `${template.tmplatBody}\n${PHONE_VERIFICATION_PREVIEW}`
: template.tmplatBody;
export const getSmsByteLength = (value: string) =>
Array.from(value).reduce((total, character) => total + (character.charCodeAt(0) > 0x7f ? 2 : 1), 0);
export const toNotificationParamValue = (value: unknown) => value == null ? "" : String(value);
export const buildUserMsgParam = (user: UserCompact): Record<string, string> => ({
...Object.fromEntries(
Object.entries(user.userDetail ?? {}).map(([key, value]) => [key, toNotificationParamValue(value)])
),
userId: toNotificationParamValue(user.userId),
userCmpn: toNotificationParamValue(user.userCmpn),
userTeam: toNotificationParamValue(user.userTeam),
userName: toNotificationParamValue(user.userName),
userRole: toNotificationParamValue(user.userRole),
});
export const buildPerformanceSmsParams = (performance: PerformanceFull): Record<string, string> => ({
businessType: toNotificationParamValue(performance.businessType),
performanceArea: toNotificationParamValue(performance.performanceArea),
artistName: toNotificationParamValue(performance.artistName),
performanceName: toNotificationParamValue(performance.performanceName),
performanceStartMonth: toNotificationParamValue(performance.performanceStartMonth),
performanceDtInfo: toNotificationParamValue(performance.performanceDtInfo),
performanceTimeInfo: toNotificationParamValue(performance.performanceTimeInfo),
ticketReservationStatus: toNotificationParamValue(performance.ticketReservationStatus),
ticketReservationMemo: toNotificationParamValue(performance.ticketReservationMemo),
performanceMemo: toNotificationParamValue(performance.performanceMemo),
...Object.fromEntries(
Object.entries(performance.performanceDetail ?? {}).map(([key, value]) => [key, toNotificationParamValue(value)])
),
...Object.fromEntries(
Object.entries(performance.performanceMonitoringSchedule ?? {}).map(([key, value]) => [key, toNotificationParamValue(value)])
),
performanceId: toNotificationParamValue(performance.performanceId),
});

View File

@@ -0,0 +1,186 @@
import {Code, PerformanceAssign, PerformanceFull, PerformanceReview, PerformanceReviewSlot, REVIEW_STATUS, REVIEW_TYPE, ReviewType, UserCompact} from "@/types/kmusical";
import type {StatusPillVariant} from "@/components/kmusical/StatusPill";
export type ReviewSlot = number;
export const getReviewTypeLabel = (reviewType: ReviewType) =>
reviewType === REVIEW_TYPE.CONSULTING ? "컨설팅" : "현장 모니터링";
export type MonitoringSlot = {
reviewSlot: ReviewSlot;
reviewType?: ReviewType;
assign?: PerformanceAssign;
user?: UserCompact;
review?: PerformanceReview;
};
export type MonitoringDisplayRow = {
index: ReviewSlot;
slot: MonitoringSlot;
userId?: string;
review?: PerformanceReview;
};
export type StatusDisplay = {
label: string;
variant: StatusPillVariant;
};
export const STATUS_FILTER = {
UNASSIGNED: "-1001",
PENDING: "-1003",
DONE: "-1007",
} as const;
export const makeStatusOption = (value: string, label: string): Code => ({
codeGroup: "status_filter",
codeValue: Number(value),
codeGroupLabel: "상태",
codeLabel: label,
memo: "",
});
export const statusFilterOptions = {
unassigned: makeStatusOption(STATUS_FILTER.UNASSIGNED, "미배치"),
pending: makeStatusOption(STATUS_FILTER.PENDING, "미진행"),
done: makeStatusOption(STATUS_FILTER.DONE, "완료"),
};
export const STATUS_FILTER_OPTIONS: Code[] = [
statusFilterOptions.unassigned,
statusFilterOptions.pending,
statusFilterOptions.done,
];
export const normalizeStatusLabel = (label?: string) => label?.replace(/\s/g, "") ?? "";
export const labelHasComplete = (label?: string) => normalizeStatusLabel(label).includes("완료");
const getSlotAssign = (performance: Partial<PerformanceFull>, slot: ReviewSlot) =>
(performance.performanceAssignList ?? []).find((assign) => assign.reviewSlot === slot);
const getSlotReview = (performance: Partial<PerformanceFull>, slot: ReviewSlot) => {
const map = performance.performanceReviewMap ?? {};
for (const [userId, review] of Object.entries(map)) {
if (review.reviewSlot === slot) return {userId, review};
}
return undefined;
};
/*
* reviewSlot은 평가위원 슬롯 번호로, 사업마다 몇 개가 쓰일지(1~5 이상) 고정돼 있지 않다.
* 담당자는 관리자가 강제로 배정/취소하므로 performanceAssignList에는 배정된 건만 남는다.
*/
export const getReviewSlots = (performance: Partial<PerformanceFull>): ReviewSlot[] => {
const assignSlots = (performance.performanceAssignList ?? []).map((assign) => assign.reviewSlot);
const reviewSlots = Object.values(performance.performanceReviewMap ?? {}).map((review) => review.reviewSlot);
return Array.from(new Set([...assignSlots, ...reviewSlots])).sort((a, b) => a - b);
};
export const getMonitoringSlot = (
performance: Partial<PerformanceFull>,
reviewSlot: ReviewSlot,
reviewType?: ReviewType
): MonitoringSlot => ({
reviewSlot,
reviewType,
assign: getSlotAssign(performance, reviewSlot),
review: getSlotReview(performance, reviewSlot)?.review,
});
/*
* reviewSlots(GET /review/slots)를 전달하면 슬롯별 reviewType(모니터링/컨설팅)까지 채워서 반환한다.
* 전달하지 않으면 해당 공연의 배정/평가 데이터에 등장한 슬롯 번호만으로 구성한다(reviewType 없음).
*/
export const getMonitoringSlots = (
performance: Partial<PerformanceFull>,
reviewSlots?: PerformanceReviewSlot[]
): MonitoringSlot[] => {
if (reviewSlots) {
return reviewSlots.map(({reviewSlot, reviewType}) => getMonitoringSlot(performance, reviewSlot, reviewType));
}
return getReviewSlots(performance).map((reviewSlot) => getMonitoringSlot(performance, reviewSlot));
};
export const getMonitoringDisplayRow = (
performance: Partial<PerformanceFull>,
reviewSlot: ReviewSlot,
reviewType?: ReviewType
): MonitoringDisplayRow => {
const slot = getMonitoringSlot(performance, reviewSlot, reviewType);
return {
index: reviewSlot,
slot,
userId: slot.assign?.assignUser,
review: slot.review,
};
};
export const getReviewRows = (performance: Partial<PerformanceFull>) =>
Object.entries(performance.performanceReviewMap ?? {}).map(([userId, review]) => ({userId, review}));
export const formatDateTime = (date: Date) => {
if (Number.isNaN(date.getTime())) return "-";
const pad = (value: number) => String(value).padStart(2, "0");
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
};
export const isReviewComplete = (review?: PerformanceReview) => {
return review?.reviewStatus === REVIEW_STATUS.DONE;
};
export const getReviewFilterValue = (
review: PerformanceReview | undefined,
{
assigned = Boolean(review),
alwaysAssigned = false,
}: {
assigned?: boolean;
alwaysAssigned?: boolean;
} = {}
) => {
if (!alwaysAssigned && !assigned && !review) return STATUS_FILTER.UNASSIGNED;
if (isReviewComplete(review)) return STATUS_FILTER.DONE;
return STATUS_FILTER.PENDING;
};
export const getReviewStatusDisplay = (
label?: string,
review?: PerformanceReview,
assigned = Boolean(review)
): StatusDisplay => {
if (!assigned) return {label: "미배치", variant: "danger"};
if (isReviewComplete(review)) return {label: label || "완료", variant: "done"};
return {label: label || "미진행", variant: "pending"};
};
export const getReviewRecordedAt = (review?: PerformanceReview) => {
return review?.reviewDt ? formatDateTime(new Date(review.reviewDt)) : "-";
}
export const getCompleteRecordedAt = (review?: PerformanceReview) => {
return isReviewComplete(review) ? getReviewRecordedAt(review) : "-";
}
export const getMonitoringFilterValue = (row: MonitoringDisplayRow) => {
if (isReviewComplete(row.review)) return STATUS_FILTER.DONE;
if (!row.slot.assign) return STATUS_FILTER.UNASSIGNED;
return STATUS_FILTER.PENDING;
};
export const getMonitoringStatusDisplay = (label: string | undefined, slot?: MonitoringSlot): StatusDisplay => {
if (!slot?.assign) return {label: "미배치", variant: "danger"};
if (isReviewComplete(slot.review)) return {label: label || "완료", variant: "done"};
return {label: label || "미진행", variant: "pending"};
};
export const getMonitoringDisplayStatus = (
row: MonitoringDisplayRow,
label?: string,
reviewLabel?: string
): StatusDisplay => {
if (isReviewComplete(row.review)) return {label: reviewLabel || "완료", variant: "done"};
return getMonitoringStatusDisplay(label, row.slot);
};

View File

@@ -0,0 +1,53 @@
"use client";
import DOMPurify, { type DOMPurify as DOMPurifyInstance } from "dompurify";
export type SanitizeHtmlOptions = {
tags?: string[];
attributes?: string[];
};
// Next.js SSR(Node) 환경에서는 dompurify가 window에 바인딩된 인스턴스가 아니라
// (window: Window) => DOMPurify 형태의 factory만 노출한다. window가 없으면
// factory를 호출할 방법이 없으므로, 여기서 안전하게 null로 폴백한다.
function resolvePurifier(): DOMPurifyInstance | null {
if (typeof window === "undefined") return null;
if (typeof DOMPurify.sanitize === "function") return DOMPurify;
return DOMPurify(window);
}
export function sanitizeHtml(
input: string,
options?: SanitizeHtmlOptions,
): string {
if (!input) {
return "";
}
const purifier = resolvePurifier();
if (!purifier) {
// DOM이 없어 실제 sanitize를 수행할 수 없는 환경(SSR 등)에서는
// 검증되지 않은 HTML을 그대로 노출하지 않도록 태그를 모두 제거한 텍스트만 반환한다.
// 브라우저에서 하이드레이션된 이후 재계산될 때 실제 sanitize 결과로 대체된다.
return input.replace(/<[^>]*>/g, "");
}
return purifier.sanitize(
input,
{
USE_PROFILES: {
html: true,
},
ADD_TAGS: options?.tags ?? [],
ADD_ATTR: options?.attributes ?? [],
},
);
}
export function sanitizeHtmlForPreview(
input: string,
options?: SanitizeHtmlOptions,
): string {
return sanitizeHtml(input, options);
}

124
src/lib/kmusical/view.ts Normal file
View File

@@ -0,0 +1,124 @@
import {Code, PerformanceCompact, PerformanceFull, UserFull} from "@/types/kmusical";
import {CodeGroup} from "@/query/code";
import {getMonitoringDisplayRow, getMonitoringFilterValue} from "@/lib/kmusical/performance-status";
export const ROLE = {
ADMIN: 1001,
RESEARCHER: 1002,
FIELD_INSPECTOR: 1003,
CONTACT_AGENT: 1004,
FOUNDATION: 2011,
MONITORING: 9003,
} as const;
export const getRoleGroup = (role?: number | null) => {
if (!role) return 0;
return Math.floor(role / 1000) * 1000;
};
export const isResearcherRole = (role?: number | null) => !role ? false : role <= ROLE.RESEARCHER;
export const isInternalRole = (role?: number | null) => getRoleGroup(role) === 1000;
export const isExternalRole = (role?: number | null) => getRoleGroup(role) === 2000;
export const isMonitoringRole = (role?: number | null) => getRoleGroup(role) === 9000;
export const isFoundationRole = (role?: number | null) => role === ROLE.FOUNDATION;
export const getCodeLabel = (
codes: Partial<Record<CodeGroup, Code[]>>,
group: CodeGroup,
value: number | string | undefined | null
) => {
if (value === undefined || value === null || value === "") return "";
const numericValue = Number(value);
const found = codes[group]?.find((code) => code.codeValue === numericValue);
return found?.codeLabel ?? String(value);
};
export const getDetailValue = (
detail: Record<string, string> | undefined,
key: string,
fallback = ""
) => {
if (!detail) return fallback;
const value = detail[key];
if (value !== undefined && value !== "") return value;
return fallback;
};
export const includesText = (value: unknown, keyword: string) => {
if (!keyword) return true;
return String(value ?? "").toLowerCase().includes(keyword.toLowerCase());
};
export type PerformanceFilterState = {
businessType: string[];
area: string[];
month: string;
monitoringDate: string;
slotStatus: Record<number, string>;
keyword: string;
};
export const filterPerformance = (
item: PerformanceCompact | PerformanceFull,
filters: Partial<PerformanceFilterState>
) => {
const keyword = filters.keyword?.trim() ?? "";
const schedule = item.performanceMonitoringSchedule;
const matches = (filter: string | string[] | undefined, value: number | string) => {
if (!filter || filter.length === 0) return true;
const values = Array.isArray(filter) ? filter : [filter];
return values.includes(String(value));
};
const matchesSlotStatus = Object.entries(filters.slotStatus ?? {}).every(
([reviewSlot, status]) => !status || getMonitoringFilterValue(getMonitoringDisplayRow(item, Number(reviewSlot))) === status
);
return (
matches(filters.businessType, item.businessType) &&
matches(filters.area, item.performanceArea) &&
matches(filters.month, item.performanceStartMonth) &&
(!filters.monitoringDate || schedule?.monitoringDate === filters.monitoringDate) &&
matchesSlotStatus &&
(
includesText(item.performanceId, keyword) ||
includesText(item.performanceName, keyword) ||
includesText(item.artistName, keyword)
)
);
};
export const filterUser = (
user: UserFull,
filters: {
area?: string | string[];
gender?: string | string[];
genre?: string | string[];
keyword?: string;
}
) => {
const detail = user.userDetail ?? {};
const area = getDetailValue(detail, "userArea");
const gender = getDetailValue(detail, "userGender");
const genre = getDetailValue(detail, "userGenre");
const keyword = filters.keyword?.trim() ?? "";
const matches = (filter: string | string[] | undefined, value: string) => {
if (!filter || filter.length === 0) return true;
const values = Array.isArray(filter) ? filter : [filter];
return values.includes(value);
};
return (
matches(filters.area, area) &&
matches(filters.gender, gender) &&
matches(filters.genre, genre) &&
(
includesText(user.userId, keyword) ||
includesText(user.userName, keyword) ||
includesText(user.userTeam, keyword) ||
includesText(user.userCmpn, keyword) ||
includesText(user.memo, keyword) ||
includesText(getDetailValue(detail, "userTel"), keyword) ||
includesText(getDetailValue(detail, "userEmail"), keyword)
)
);
};