ERP-node/frontend/lib/utils/autoGeneration.ts

293 lines
8.2 KiB
TypeScript
Raw Normal View History

"use client";
import { AutoGenerationType, AutoGenerationConfig } from "@/types/screen";
/**
*
*/
export class AutoGenerationUtils {
/**
* UUID
*/
static generateUUID(): string {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
const r = (Math.random() * 16) | 0;
const v = c === "x" ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
/**
*
*/
static generateRandomString(length: number = 8, prefix?: string, suffix?: string): string {
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let result = "";
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return `${prefix || ""}${result}${suffix || ""}`;
}
/**
*
*/
static generateRandomNumber(length: number = 6, prefix?: string, suffix?: string): string {
const min = Math.pow(10, length - 1);
const max = Math.pow(10, length) - 1;
const randomNum = Math.floor(Math.random() * (max - min + 1)) + min;
return `${prefix || ""}${randomNum}${suffix || ""}`;
}
/**
*
*/
static generateCurrentTime(format?: string): string {
console.log("🕒 generateCurrentTime 호출됨:", { format });
const now = new Date();
console.log("🕒 현재 시간 객체:", now);
let result: string;
switch (format) {
case "date":
result = now.toISOString().split("T")[0]; // YYYY-MM-DD
break;
case "time":
result = now.toTimeString().split(" ")[0]; // HH:mm:ss
break;
case "datetime":
result = now.toISOString().replace("T", " ").split(".")[0]; // YYYY-MM-DD HH:mm:ss
break;
case "timestamp":
result = now.getTime().toString();
break;
default:
result = now.toISOString(); // ISO 8601 format
break;
}
console.log("🕒 generateCurrentTime 결과:", { format, result });
return result;
}
/**
* 퀀 ( , DB 퀀 )
*/
private static sequenceCounters: Map<string, number> = new Map();
static generateSequence(key: string = "default", startValue: number = 1, prefix?: string, suffix?: string): string {
if (!this.sequenceCounters.has(key)) {
this.sequenceCounters.set(key, startValue);
}
const current = this.sequenceCounters.get(key)!;
this.sequenceCounters.set(key, current + 1);
return `${prefix || ""}${current}${suffix || ""}`;
}
/**
* ID ( )
*/
static getCurrentUserId(): string {
// TODO: 실제 인증 시스템과 연동
if (typeof window !== "undefined") {
const userInfo = localStorage.getItem("userInfo");
if (userInfo) {
try {
const parsed = JSON.parse(userInfo);
return parsed.userId || parsed.id || "unknown";
} catch {
return "unknown";
}
}
}
return "system";
}
/**
*
*/
static getCompanyCode(): string {
// TODO: 실제 회사 정보와 연동
if (typeof window !== "undefined") {
const companyInfo = localStorage.getItem("companyInfo");
if (companyInfo) {
try {
const parsed = JSON.parse(companyInfo);
return parsed.companyCode || parsed.code || "COMPANY";
} catch {
return "COMPANY";
}
}
}
return "COMPANY";
}
/**
*
*/
static getDepartmentCode(): string {
// TODO: 실제 부서 정보와 연동
if (typeof window !== "undefined") {
const userInfo = localStorage.getItem("userInfo");
if (userInfo) {
try {
const parsed = JSON.parse(userInfo);
return parsed.departmentCode || parsed.deptCode || "DEPT";
} catch {
return "DEPT";
}
}
}
return "DEPT";
}
/**
*
*/
static generateValue(config: AutoGenerationConfig, columnName?: string): string | null {
console.log("🔧 AutoGenerationUtils.generateValue 호출:", {
config,
columnName,
enabled: config.enabled,
type: config.type,
});
if (!config.enabled || config.type === "none") {
console.log("⚠️ AutoGenerationUtils.generateValue 스킵:", {
enabled: config.enabled,
type: config.type,
});
return null;
}
const options = config.options || {};
switch (config.type) {
case "uuid":
return this.generateUUID();
case "current_user":
return this.getCurrentUserId();
case "current_time":
console.log("🕒 AutoGenerationUtils.generateCurrentTime 호출:", {
format: options.format,
options,
});
const timeValue = this.generateCurrentTime(options.format);
console.log("🕒 AutoGenerationUtils.generateCurrentTime 결과:", timeValue);
return timeValue;
case "sequence":
return this.generateSequence(columnName || "default", options.startValue || 1, options.prefix, options.suffix);
case "random_string":
return this.generateRandomString(options.length || 8, options.prefix, options.suffix);
case "random_number":
return this.generateRandomNumber(options.length || 6, options.prefix, options.suffix);
case "company_code":
return this.getCompanyCode();
case "department":
return this.getDepartmentCode();
default:
console.warn(`Unknown auto generation type: ${config.type}`);
return null;
}
}
/**
*
*/
static getTypeDescription(type: AutoGenerationType): string {
const descriptions: Record<AutoGenerationType, string> = {
uuid: "고유 식별자 (UUID) 생성",
current_user: "현재 로그인한 사용자 ID",
current_time: "현재 날짜/시간",
sequence: "순차적 번호 생성",
random_string: "랜덤 문자열 생성",
random_number: "랜덤 숫자 생성",
company_code: "현재 회사 코드",
department: "현재 부서 코드",
none: "자동생성 없음",
};
return descriptions[type] || "알 수 없는 타입";
}
/**
*
*/
static generatePreviewValue(config: AutoGenerationConfig): string {
if (!config.enabled || config.type === "none") {
return "";
}
// 미리보기용으로 실제 값 대신 예시 값 반환
const options = config.options || {};
switch (config.type) {
case "uuid":
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
case "current_user":
return "user123";
case "current_time":
return this.generateCurrentTime(options.format);
case "sequence":
return `${options.prefix || ""}1${options.suffix || ""}`;
case "random_string":
return `${options.prefix || ""}ABC123${options.suffix || ""}`;
case "random_number":
return `${options.prefix || ""}123456${options.suffix || ""}`;
case "company_code":
return "COMPANY";
case "department":
return "DEPT";
default:
return "";
}
}
}
// 개발 모드에서 전역 함수로 등록 (테스트용)
if (typeof window !== "undefined") {
(window as any).__AUTO_GENERATION_TEST__ = {
generateCurrentTime: AutoGenerationUtils.generateCurrentTime,
generateValue: AutoGenerationUtils.generateValue,
test: () => {
console.log("🧪 자동생성 테스트 시작");
// 현재 시간 테스트
const dateResult = AutoGenerationUtils.generateCurrentTime("date");
console.log("📅 날짜 생성 결과:", dateResult);
// 자동생성 설정 테스트
const config = {
enabled: true,
type: "current_time" as any,
options: { format: "date" },
};
const autoResult = AutoGenerationUtils.generateValue(config);
console.log("🎯 자동생성 결과:", autoResult);
return { dateResult, autoResult };
},
};
}