Merge branch 'feature/screen-management' of http://39.117.244.52:3000/kjs/ERP-node into feature/screen-management
This commit is contained in:
334
backend-node/src/services/bookingService.ts
Normal file
334
backend-node/src/services/bookingService.ts
Normal file
@@ -0,0 +1,334 @@
|
||||
import * as fs from "fs";
|
||||
import * as path from "path";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { logger } from "../utils/logger";
|
||||
import { query } from "../database/db";
|
||||
|
||||
const BOOKING_DIR = path.join(__dirname, "../../data/bookings");
|
||||
const BOOKING_FILE = path.join(BOOKING_DIR, "bookings.json");
|
||||
|
||||
// 환경 변수로 데이터 소스 선택
|
||||
const DATA_SOURCE = process.env.BOOKING_DATA_SOURCE || "file";
|
||||
|
||||
export interface BookingRequest {
|
||||
id: string;
|
||||
customerName: string;
|
||||
customerPhone: string;
|
||||
pickupLocation: string;
|
||||
dropoffLocation: string;
|
||||
scheduledTime: string;
|
||||
vehicleType: "truck" | "van" | "car";
|
||||
cargoType?: string;
|
||||
weight?: number;
|
||||
status: "pending" | "accepted" | "rejected" | "completed";
|
||||
priority: "normal" | "urgent";
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
acceptedAt?: string;
|
||||
rejectedAt?: string;
|
||||
completedAt?: string;
|
||||
notes?: string;
|
||||
estimatedCost?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 예약 요청 관리 서비스 (File/DB 하이브리드)
|
||||
*/
|
||||
export class BookingService {
|
||||
private static instance: BookingService;
|
||||
|
||||
private constructor() {
|
||||
if (DATA_SOURCE === "file") {
|
||||
this.ensureDataDirectory();
|
||||
this.generateMockData();
|
||||
}
|
||||
logger.info(`📋 예약 요청 데이터 소스: ${DATA_SOURCE.toUpperCase()}`);
|
||||
}
|
||||
|
||||
public static getInstance(): BookingService {
|
||||
if (!BookingService.instance) {
|
||||
BookingService.instance = new BookingService();
|
||||
}
|
||||
return BookingService.instance;
|
||||
}
|
||||
|
||||
private ensureDataDirectory(): void {
|
||||
if (!fs.existsSync(BOOKING_DIR)) {
|
||||
fs.mkdirSync(BOOKING_DIR, { recursive: true });
|
||||
logger.info(`📁 예약 데이터 디렉토리 생성: ${BOOKING_DIR}`);
|
||||
}
|
||||
if (!fs.existsSync(BOOKING_FILE)) {
|
||||
fs.writeFileSync(BOOKING_FILE, JSON.stringify([], null, 2));
|
||||
logger.info(`📄 예약 파일 생성: ${BOOKING_FILE}`);
|
||||
}
|
||||
}
|
||||
|
||||
private generateMockData(): void {
|
||||
const bookings = this.loadBookingsFromFile();
|
||||
if (bookings.length > 0) return;
|
||||
|
||||
const mockBookings: BookingRequest[] = [
|
||||
{
|
||||
id: uuidv4(),
|
||||
customerName: "김철수",
|
||||
customerPhone: "010-1234-5678",
|
||||
pickupLocation: "서울시 강남구 역삼동 123",
|
||||
dropoffLocation: "경기도 성남시 분당구 정자동 456",
|
||||
scheduledTime: new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString(),
|
||||
vehicleType: "truck",
|
||||
cargoType: "전자제품",
|
||||
weight: 500,
|
||||
status: "pending",
|
||||
priority: "urgent",
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
estimatedCost: 150000,
|
||||
},
|
||||
{
|
||||
id: uuidv4(),
|
||||
customerName: "이영희",
|
||||
customerPhone: "010-9876-5432",
|
||||
pickupLocation: "서울시 송파구 잠실동 789",
|
||||
dropoffLocation: "인천시 남동구 구월동 321",
|
||||
scheduledTime: new Date(Date.now() + 4 * 60 * 60 * 1000).toISOString(),
|
||||
vehicleType: "van",
|
||||
cargoType: "가구",
|
||||
weight: 300,
|
||||
status: "pending",
|
||||
priority: "normal",
|
||||
createdAt: new Date(Date.now() - 10 * 60 * 1000).toISOString(),
|
||||
updatedAt: new Date(Date.now() - 10 * 60 * 1000).toISOString(),
|
||||
estimatedCost: 80000,
|
||||
},
|
||||
];
|
||||
|
||||
this.saveBookingsToFile(mockBookings);
|
||||
logger.info(`✅ 예약 목 데이터 생성: ${mockBookings.length}개`);
|
||||
}
|
||||
|
||||
public async getAllBookings(filter?: {
|
||||
status?: string;
|
||||
priority?: string;
|
||||
}): Promise<{ bookings: BookingRequest[]; newCount: number }> {
|
||||
try {
|
||||
const bookings = DATA_SOURCE === "database"
|
||||
? await this.loadBookingsFromDB(filter)
|
||||
: this.loadBookingsFromFile(filter);
|
||||
|
||||
bookings.sort((a, b) => {
|
||||
if (a.priority !== b.priority) return a.priority === "urgent" ? -1 : 1;
|
||||
return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
|
||||
});
|
||||
|
||||
const fiveMinutesAgo = new Date(Date.now() - 5 * 60 * 1000);
|
||||
const newCount = bookings.filter(
|
||||
(b) => b.status === "pending" && new Date(b.createdAt) > fiveMinutesAgo
|
||||
).length;
|
||||
|
||||
return { bookings, newCount };
|
||||
} catch (error) {
|
||||
logger.error("❌ 예약 목록 조회 오류:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async acceptBooking(id: string): Promise<BookingRequest> {
|
||||
try {
|
||||
if (DATA_SOURCE === "database") {
|
||||
return await this.acceptBookingDB(id);
|
||||
} else {
|
||||
return this.acceptBookingFile(id);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error("❌ 예약 수락 오류:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async rejectBooking(id: string, reason?: string): Promise<BookingRequest> {
|
||||
try {
|
||||
if (DATA_SOURCE === "database") {
|
||||
return await this.rejectBookingDB(id, reason);
|
||||
} else {
|
||||
return this.rejectBookingFile(id, reason);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error("❌ 예약 거절 오류:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== DATABASE 메서드 ====================
|
||||
|
||||
private async loadBookingsFromDB(filter?: {
|
||||
status?: string;
|
||||
priority?: string;
|
||||
}): Promise<BookingRequest[]> {
|
||||
let sql = `
|
||||
SELECT
|
||||
id, customer_name as "customerName", customer_phone as "customerPhone",
|
||||
pickup_location as "pickupLocation", dropoff_location as "dropoffLocation",
|
||||
scheduled_time as "scheduledTime", vehicle_type as "vehicleType",
|
||||
cargo_type as "cargoType", weight, status, priority,
|
||||
created_at as "createdAt", updated_at as "updatedAt",
|
||||
accepted_at as "acceptedAt", rejected_at as "rejectedAt",
|
||||
completed_at as "completedAt", notes, estimated_cost as "estimatedCost"
|
||||
FROM booking_requests
|
||||
WHERE 1=1
|
||||
`;
|
||||
const params: any[] = [];
|
||||
let paramIndex = 1;
|
||||
|
||||
if (filter?.status) {
|
||||
sql += ` AND status = $${paramIndex++}`;
|
||||
params.push(filter.status);
|
||||
}
|
||||
if (filter?.priority) {
|
||||
sql += ` AND priority = $${paramIndex++}`;
|
||||
params.push(filter.priority);
|
||||
}
|
||||
|
||||
const rows = await query(sql, params);
|
||||
return rows.map((row: any) => ({
|
||||
...row,
|
||||
scheduledTime: new Date(row.scheduledTime).toISOString(),
|
||||
createdAt: new Date(row.createdAt).toISOString(),
|
||||
updatedAt: new Date(row.updatedAt).toISOString(),
|
||||
acceptedAt: row.acceptedAt ? new Date(row.acceptedAt).toISOString() : undefined,
|
||||
rejectedAt: row.rejectedAt ? new Date(row.rejectedAt).toISOString() : undefined,
|
||||
completedAt: row.completedAt ? new Date(row.completedAt).toISOString() : undefined,
|
||||
}));
|
||||
}
|
||||
|
||||
private async acceptBookingDB(id: string): Promise<BookingRequest> {
|
||||
const rows = await query(
|
||||
`UPDATE booking_requests
|
||||
SET status = 'accepted', accepted_at = NOW(), updated_at = NOW()
|
||||
WHERE id = $1
|
||||
RETURNING
|
||||
id, customer_name as "customerName", customer_phone as "customerPhone",
|
||||
pickup_location as "pickupLocation", dropoff_location as "dropoffLocation",
|
||||
scheduled_time as "scheduledTime", vehicle_type as "vehicleType",
|
||||
cargo_type as "cargoType", weight, status, priority,
|
||||
created_at as "createdAt", updated_at as "updatedAt",
|
||||
accepted_at as "acceptedAt", notes, estimated_cost as "estimatedCost"`,
|
||||
[id]
|
||||
);
|
||||
|
||||
if (rows.length === 0) {
|
||||
throw new Error(`예약을 찾을 수 없습니다: ${id}`);
|
||||
}
|
||||
|
||||
const row = rows[0];
|
||||
logger.info(`✅ 예약 수락: ${id} - ${row.customerName}`);
|
||||
return {
|
||||
...row,
|
||||
scheduledTime: new Date(row.scheduledTime).toISOString(),
|
||||
createdAt: new Date(row.createdAt).toISOString(),
|
||||
updatedAt: new Date(row.updatedAt).toISOString(),
|
||||
acceptedAt: new Date(row.acceptedAt).toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
private async rejectBookingDB(id: string, reason?: string): Promise<BookingRequest> {
|
||||
const rows = await query(
|
||||
`UPDATE booking_requests
|
||||
SET status = 'rejected', rejected_at = NOW(), updated_at = NOW(), rejection_reason = $2
|
||||
WHERE id = $1
|
||||
RETURNING
|
||||
id, customer_name as "customerName", customer_phone as "customerPhone",
|
||||
pickup_location as "pickupLocation", dropoff_location as "dropoffLocation",
|
||||
scheduled_time as "scheduledTime", vehicle_type as "vehicleType",
|
||||
cargo_type as "cargoType", weight, status, priority,
|
||||
created_at as "createdAt", updated_at as "updatedAt",
|
||||
rejected_at as "rejectedAt", notes, estimated_cost as "estimatedCost"`,
|
||||
[id, reason]
|
||||
);
|
||||
|
||||
if (rows.length === 0) {
|
||||
throw new Error(`예약을 찾을 수 없습니다: ${id}`);
|
||||
}
|
||||
|
||||
const row = rows[0];
|
||||
logger.info(`✅ 예약 거절: ${id} - ${row.customerName}`);
|
||||
return {
|
||||
...row,
|
||||
scheduledTime: new Date(row.scheduledTime).toISOString(),
|
||||
createdAt: new Date(row.createdAt).toISOString(),
|
||||
updatedAt: new Date(row.updatedAt).toISOString(),
|
||||
rejectedAt: new Date(row.rejectedAt).toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
// ==================== FILE 메서드 ====================
|
||||
|
||||
private loadBookingsFromFile(filter?: {
|
||||
status?: string;
|
||||
priority?: string;
|
||||
}): BookingRequest[] {
|
||||
try {
|
||||
const data = fs.readFileSync(BOOKING_FILE, "utf-8");
|
||||
let bookings: BookingRequest[] = JSON.parse(data);
|
||||
|
||||
if (filter?.status) {
|
||||
bookings = bookings.filter((b) => b.status === filter.status);
|
||||
}
|
||||
if (filter?.priority) {
|
||||
bookings = bookings.filter((b) => b.priority === filter.priority);
|
||||
}
|
||||
|
||||
return bookings;
|
||||
} catch (error) {
|
||||
logger.error("❌ 예약 파일 로드 오류:", error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private saveBookingsToFile(bookings: BookingRequest[]): void {
|
||||
try {
|
||||
fs.writeFileSync(BOOKING_FILE, JSON.stringify(bookings, null, 2));
|
||||
} catch (error) {
|
||||
logger.error("❌ 예약 파일 저장 오류:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private acceptBookingFile(id: string): BookingRequest {
|
||||
const bookings = this.loadBookingsFromFile();
|
||||
const booking = bookings.find((b) => b.id === id);
|
||||
|
||||
if (!booking) {
|
||||
throw new Error(`예약을 찾을 수 없습니다: ${id}`);
|
||||
}
|
||||
|
||||
booking.status = "accepted";
|
||||
booking.acceptedAt = new Date().toISOString();
|
||||
booking.updatedAt = new Date().toISOString();
|
||||
|
||||
this.saveBookingsToFile(bookings);
|
||||
logger.info(`✅ 예약 수락: ${id} - ${booking.customerName}`);
|
||||
|
||||
return booking;
|
||||
}
|
||||
|
||||
private rejectBookingFile(id: string, reason?: string): BookingRequest {
|
||||
const bookings = this.loadBookingsFromFile();
|
||||
const booking = bookings.find((b) => b.id === id);
|
||||
|
||||
if (!booking) {
|
||||
throw new Error(`예약을 찾을 수 없습니다: ${id}`);
|
||||
}
|
||||
|
||||
booking.status = "rejected";
|
||||
booking.rejectedAt = new Date().toISOString();
|
||||
booking.updatedAt = new Date().toISOString();
|
||||
if (reason) {
|
||||
booking.notes = reason;
|
||||
}
|
||||
|
||||
this.saveBookingsToFile(bookings);
|
||||
logger.info(`✅ 예약 거절: ${id} - ${booking.customerName}`);
|
||||
|
||||
return booking;
|
||||
}
|
||||
}
|
||||
186
backend-node/src/services/deliveryService.ts
Normal file
186
backend-node/src/services/deliveryService.ts
Normal file
@@ -0,0 +1,186 @@
|
||||
/**
|
||||
* 배송/화물 관리 서비스
|
||||
*
|
||||
* 실제 데이터베이스 연동 시 필요한 메서드들을 미리 정의
|
||||
*/
|
||||
|
||||
import pool from '../database/db';
|
||||
|
||||
export interface DeliveryItem {
|
||||
id: string;
|
||||
trackingNumber: string;
|
||||
customer: string;
|
||||
origin: string;
|
||||
destination: string;
|
||||
status: 'in_transit' | 'delivered' | 'delayed' | 'pickup_waiting';
|
||||
estimatedDelivery: string;
|
||||
delayReason?: string;
|
||||
priority: 'high' | 'normal' | 'low';
|
||||
}
|
||||
|
||||
export interface CustomerIssue {
|
||||
id: string;
|
||||
customer: string;
|
||||
trackingNumber: string;
|
||||
issueType: 'damage' | 'delay' | 'missing' | 'other';
|
||||
description: string;
|
||||
status: 'open' | 'in_progress' | 'resolved';
|
||||
reportedAt: string;
|
||||
}
|
||||
|
||||
export interface TodayStats {
|
||||
shipped: number;
|
||||
delivered: number;
|
||||
}
|
||||
|
||||
export interface DeliveryStatusResponse {
|
||||
deliveries: DeliveryItem[];
|
||||
issues: CustomerIssue[];
|
||||
todayStats: TodayStats;
|
||||
}
|
||||
|
||||
/**
|
||||
* 배송 현황 조회
|
||||
*
|
||||
* TODO: 실제 DB 연동 시 구현 필요
|
||||
* - 테이블명: deliveries (배송 정보)
|
||||
* - 테이블명: customer_issues (고객 이슈)
|
||||
*
|
||||
* 예상 쿼리:
|
||||
* SELECT * FROM deliveries WHERE DATE(created_at) = CURRENT_DATE
|
||||
* SELECT * FROM customer_issues WHERE status != 'resolved' ORDER BY reported_at DESC
|
||||
*/
|
||||
export async function getDeliveryStatus(): Promise<DeliveryStatusResponse> {
|
||||
try {
|
||||
// TODO: 실제 DB 쿼리로 교체
|
||||
// const deliveriesResult = await pool.query(
|
||||
// `SELECT
|
||||
// id, tracking_number as "trackingNumber", customer, origin, destination,
|
||||
// status, estimated_delivery as "estimatedDelivery", delay_reason as "delayReason",
|
||||
// priority
|
||||
// FROM deliveries
|
||||
// WHERE deleted_at IS NULL
|
||||
// ORDER BY created_at DESC`
|
||||
// );
|
||||
|
||||
// const issuesResult = await pool.query(
|
||||
// `SELECT
|
||||
// id, customer, tracking_number as "trackingNumber", issue_type as "issueType",
|
||||
// description, status, reported_at as "reportedAt"
|
||||
// FROM customer_issues
|
||||
// WHERE deleted_at IS NULL
|
||||
// ORDER BY reported_at DESC`
|
||||
// );
|
||||
|
||||
// const statsResult = await pool.query(
|
||||
// `SELECT
|
||||
// COUNT(*) FILTER (WHERE status = 'in_transit') as shipped,
|
||||
// COUNT(*) FILTER (WHERE status = 'delivered') as delivered
|
||||
// FROM deliveries
|
||||
// WHERE DATE(created_at) = CURRENT_DATE
|
||||
// AND deleted_at IS NULL`
|
||||
// );
|
||||
|
||||
// 임시 응답 (개발용)
|
||||
return {
|
||||
deliveries: [],
|
||||
issues: [],
|
||||
todayStats: {
|
||||
shipped: 0,
|
||||
delivered: 0,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('배송 현황 조회 실패:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 지연 배송 목록 조회
|
||||
*/
|
||||
export async function getDelayedDeliveries(): Promise<DeliveryItem[]> {
|
||||
try {
|
||||
// TODO: 실제 DB 쿼리로 교체
|
||||
// const result = await pool.query(
|
||||
// `SELECT * FROM deliveries
|
||||
// WHERE status = 'delayed'
|
||||
// AND deleted_at IS NULL
|
||||
// ORDER BY estimated_delivery ASC`
|
||||
// );
|
||||
|
||||
return [];
|
||||
} catch (error) {
|
||||
console.error('지연 배송 조회 실패:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 고객 이슈 목록 조회
|
||||
*/
|
||||
export async function getCustomerIssues(status?: string): Promise<CustomerIssue[]> {
|
||||
try {
|
||||
// TODO: 실제 DB 쿼리로 교체
|
||||
// const query = status
|
||||
// ? `SELECT * FROM customer_issues WHERE status = $1 AND deleted_at IS NULL ORDER BY reported_at DESC`
|
||||
// : `SELECT * FROM customer_issues WHERE deleted_at IS NULL ORDER BY reported_at DESC`;
|
||||
|
||||
// const result = status
|
||||
// ? await pool.query(query, [status])
|
||||
// : await pool.query(query);
|
||||
|
||||
return [];
|
||||
} catch (error) {
|
||||
console.error('고객 이슈 조회 실패:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 배송 정보 업데이트
|
||||
*/
|
||||
export async function updateDeliveryStatus(
|
||||
id: string,
|
||||
status: DeliveryItem['status'],
|
||||
delayReason?: string
|
||||
): Promise<void> {
|
||||
try {
|
||||
// TODO: 실제 DB 쿼리로 교체
|
||||
// await pool.query(
|
||||
// `UPDATE deliveries
|
||||
// SET status = $1, delay_reason = $2, updated_at = NOW()
|
||||
// WHERE id = $3`,
|
||||
// [status, delayReason, id]
|
||||
// );
|
||||
|
||||
console.log(`배송 상태 업데이트: ${id} -> ${status}`);
|
||||
} catch (error) {
|
||||
console.error('배송 상태 업데이트 실패:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 고객 이슈 상태 업데이트
|
||||
*/
|
||||
export async function updateIssueStatus(
|
||||
id: string,
|
||||
status: CustomerIssue['status']
|
||||
): Promise<void> {
|
||||
try {
|
||||
// TODO: 실제 DB 쿼리로 교체
|
||||
// await pool.query(
|
||||
// `UPDATE customer_issues
|
||||
// SET status = $1, updated_at = NOW()
|
||||
// WHERE id = $2`,
|
||||
// [status, id]
|
||||
// );
|
||||
|
||||
console.log(`이슈 상태 업데이트: ${id} -> ${status}`);
|
||||
} catch (error) {
|
||||
console.error('이슈 상태 업데이트 실패:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
282
backend-node/src/services/documentService.ts
Normal file
282
backend-node/src/services/documentService.ts
Normal file
@@ -0,0 +1,282 @@
|
||||
import { logger } from "../utils/logger";
|
||||
import { query } from "../database/db";
|
||||
|
||||
// 환경 변수로 데이터 소스 선택
|
||||
const DATA_SOURCE = process.env.DOCUMENT_DATA_SOURCE || "memory";
|
||||
|
||||
export interface Document {
|
||||
id: string;
|
||||
name: string;
|
||||
category: "계약서" | "보험" | "세금계산서" | "기타";
|
||||
fileSize: number;
|
||||
filePath: string;
|
||||
mimeType?: string;
|
||||
uploadDate: string;
|
||||
description?: string;
|
||||
uploadedBy?: string;
|
||||
relatedEntityType?: string;
|
||||
relatedEntityId?: string;
|
||||
tags?: string[];
|
||||
isArchived: boolean;
|
||||
archivedAt?: string;
|
||||
}
|
||||
|
||||
// 메모리 목 데이터
|
||||
const mockDocuments: Document[] = [
|
||||
{
|
||||
id: "doc-1",
|
||||
name: "2025년 1월 세금계산서.pdf",
|
||||
category: "세금계산서",
|
||||
fileSize: 1258291,
|
||||
filePath: "/uploads/documents/tax-invoice-202501.pdf",
|
||||
uploadDate: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000).toISOString(),
|
||||
description: "1월 매출 세금계산서",
|
||||
uploadedBy: "admin",
|
||||
isArchived: false,
|
||||
},
|
||||
{
|
||||
id: "doc-2",
|
||||
name: "차량보험증권_서울12가3456.pdf",
|
||||
category: "보험",
|
||||
fileSize: 876544,
|
||||
filePath: "/uploads/documents/insurance-vehicle-1.pdf",
|
||||
uploadDate: new Date(Date.now() - 10 * 24 * 60 * 60 * 1000).toISOString(),
|
||||
description: "1톤 트럭 종합보험",
|
||||
uploadedBy: "admin",
|
||||
isArchived: false,
|
||||
},
|
||||
{
|
||||
id: "doc-3",
|
||||
name: "운송계약서_ABC물류.pdf",
|
||||
category: "계약서",
|
||||
fileSize: 2457600,
|
||||
filePath: "/uploads/documents/contract-abc-logistics.pdf",
|
||||
uploadDate: new Date(Date.now() - 15 * 24 * 60 * 60 * 1000).toISOString(),
|
||||
description: "ABC물류 연간 운송 계약",
|
||||
uploadedBy: "admin",
|
||||
isArchived: false,
|
||||
},
|
||||
{
|
||||
id: "doc-4",
|
||||
name: "2024년 12월 세금계산서.pdf",
|
||||
category: "세금계산서",
|
||||
fileSize: 1124353,
|
||||
filePath: "/uploads/documents/tax-invoice-202412.pdf",
|
||||
uploadDate: new Date(Date.now() - 40 * 24 * 60 * 60 * 1000).toISOString(),
|
||||
uploadedBy: "admin",
|
||||
isArchived: false,
|
||||
},
|
||||
{
|
||||
id: "doc-5",
|
||||
name: "화물배상책임보험증권.pdf",
|
||||
category: "보험",
|
||||
fileSize: 720384,
|
||||
filePath: "/uploads/documents/cargo-insurance.pdf",
|
||||
uploadDate: new Date(Date.now() - 50 * 24 * 60 * 60 * 1000).toISOString(),
|
||||
description: "화물 배상책임보험",
|
||||
uploadedBy: "admin",
|
||||
isArchived: false,
|
||||
},
|
||||
{
|
||||
id: "doc-6",
|
||||
name: "차고지 임대계약서.pdf",
|
||||
category: "계약서",
|
||||
fileSize: 1843200,
|
||||
filePath: "/uploads/documents/garage-lease-contract.pdf",
|
||||
uploadDate: new Date(Date.now() - 60 * 24 * 60 * 60 * 1000).toISOString(),
|
||||
uploadedBy: "admin",
|
||||
isArchived: false,
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* 문서 관리 서비스 (Memory/DB 하이브리드)
|
||||
*/
|
||||
export class DocumentService {
|
||||
private static instance: DocumentService;
|
||||
|
||||
private constructor() {
|
||||
logger.info(`📂 문서 관리 데이터 소스: ${DATA_SOURCE.toUpperCase()}`);
|
||||
}
|
||||
|
||||
public static getInstance(): DocumentService {
|
||||
if (!DocumentService.instance) {
|
||||
DocumentService.instance = new DocumentService();
|
||||
}
|
||||
return DocumentService.instance;
|
||||
}
|
||||
|
||||
public async getAllDocuments(filter?: {
|
||||
category?: string;
|
||||
searchTerm?: string;
|
||||
uploadedBy?: string;
|
||||
}): Promise<Document[]> {
|
||||
try {
|
||||
const documents = DATA_SOURCE === "database"
|
||||
? await this.loadDocumentsFromDB(filter)
|
||||
: this.loadDocumentsFromMemory(filter);
|
||||
|
||||
// 최신순 정렬
|
||||
documents.sort((a, b) =>
|
||||
new Date(b.uploadDate).getTime() - new Date(a.uploadDate).getTime()
|
||||
);
|
||||
|
||||
return documents;
|
||||
} catch (error) {
|
||||
logger.error("❌ 문서 목록 조회 오류:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async getDocumentById(id: string): Promise<Document> {
|
||||
try {
|
||||
if (DATA_SOURCE === "database") {
|
||||
return await this.getDocumentByIdDB(id);
|
||||
} else {
|
||||
return this.getDocumentByIdMemory(id);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error("❌ 문서 조회 오류:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async getStatistics(): Promise<{
|
||||
total: number;
|
||||
byCategory: Record<string, number>;
|
||||
totalSize: number;
|
||||
}> {
|
||||
try {
|
||||
const documents = await this.getAllDocuments();
|
||||
|
||||
const byCategory: Record<string, number> = {
|
||||
"계약서": 0,
|
||||
"보험": 0,
|
||||
"세금계산서": 0,
|
||||
"기타": 0,
|
||||
};
|
||||
|
||||
documents.forEach((doc) => {
|
||||
byCategory[doc.category] = (byCategory[doc.category] || 0) + 1;
|
||||
});
|
||||
|
||||
const totalSize = documents.reduce((sum, doc) => sum + doc.fileSize, 0);
|
||||
|
||||
return {
|
||||
total: documents.length,
|
||||
byCategory,
|
||||
totalSize,
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error("❌ 문서 통계 조회 오류:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== DATABASE 메서드 ====================
|
||||
|
||||
private async loadDocumentsFromDB(filter?: {
|
||||
category?: string;
|
||||
searchTerm?: string;
|
||||
uploadedBy?: string;
|
||||
}): Promise<Document[]> {
|
||||
let sql = `
|
||||
SELECT
|
||||
id, name, category, file_size as "fileSize", file_path as "filePath",
|
||||
mime_type as "mimeType", upload_date as "uploadDate",
|
||||
description, uploaded_by as "uploadedBy",
|
||||
related_entity_type as "relatedEntityType",
|
||||
related_entity_id as "relatedEntityId",
|
||||
tags, is_archived as "isArchived", archived_at as "archivedAt"
|
||||
FROM document_files
|
||||
WHERE is_archived = false
|
||||
`;
|
||||
const params: any[] = [];
|
||||
let paramIndex = 1;
|
||||
|
||||
if (filter?.category) {
|
||||
sql += ` AND category = $${paramIndex++}`;
|
||||
params.push(filter.category);
|
||||
}
|
||||
if (filter?.searchTerm) {
|
||||
sql += ` AND (name ILIKE $${paramIndex} OR description ILIKE $${paramIndex})`;
|
||||
params.push(`%${filter.searchTerm}%`);
|
||||
paramIndex++;
|
||||
}
|
||||
if (filter?.uploadedBy) {
|
||||
sql += ` AND uploaded_by = $${paramIndex++}`;
|
||||
params.push(filter.uploadedBy);
|
||||
}
|
||||
|
||||
const rows = await query(sql, params);
|
||||
return rows.map((row: any) => ({
|
||||
...row,
|
||||
uploadDate: new Date(row.uploadDate).toISOString(),
|
||||
archivedAt: row.archivedAt ? new Date(row.archivedAt).toISOString() : undefined,
|
||||
}));
|
||||
}
|
||||
|
||||
private async getDocumentByIdDB(id: string): Promise<Document> {
|
||||
const rows = await query(
|
||||
`SELECT
|
||||
id, name, category, file_size as "fileSize", file_path as "filePath",
|
||||
mime_type as "mimeType", upload_date as "uploadDate",
|
||||
description, uploaded_by as "uploadedBy",
|
||||
related_entity_type as "relatedEntityType",
|
||||
related_entity_id as "relatedEntityId",
|
||||
tags, is_archived as "isArchived", archived_at as "archivedAt"
|
||||
FROM document_files
|
||||
WHERE id = $1`,
|
||||
[id]
|
||||
);
|
||||
|
||||
if (rows.length === 0) {
|
||||
throw new Error(`문서를 찾을 수 없습니다: ${id}`);
|
||||
}
|
||||
|
||||
const row = rows[0];
|
||||
return {
|
||||
...row,
|
||||
uploadDate: new Date(row.uploadDate).toISOString(),
|
||||
archivedAt: row.archivedAt ? new Date(row.archivedAt).toISOString() : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
// ==================== MEMORY 메서드 ====================
|
||||
|
||||
private loadDocumentsFromMemory(filter?: {
|
||||
category?: string;
|
||||
searchTerm?: string;
|
||||
uploadedBy?: string;
|
||||
}): Document[] {
|
||||
let documents = mockDocuments.filter((d) => !d.isArchived);
|
||||
|
||||
if (filter?.category) {
|
||||
documents = documents.filter((d) => d.category === filter.category);
|
||||
}
|
||||
if (filter?.searchTerm) {
|
||||
const term = filter.searchTerm.toLowerCase();
|
||||
documents = documents.filter(
|
||||
(d) =>
|
||||
d.name.toLowerCase().includes(term) ||
|
||||
d.description?.toLowerCase().includes(term)
|
||||
);
|
||||
}
|
||||
if (filter?.uploadedBy) {
|
||||
documents = documents.filter((d) => d.uploadedBy === filter.uploadedBy);
|
||||
}
|
||||
|
||||
return documents;
|
||||
}
|
||||
|
||||
private getDocumentByIdMemory(id: string): Document {
|
||||
const document = mockDocuments.find((d) => d.id === id);
|
||||
|
||||
if (!document) {
|
||||
throw new Error(`문서를 찾을 수 없습니다: ${id}`);
|
||||
}
|
||||
|
||||
return document;
|
||||
}
|
||||
}
|
||||
|
||||
267
backend-node/src/services/maintenanceService.ts
Normal file
267
backend-node/src/services/maintenanceService.ts
Normal file
@@ -0,0 +1,267 @@
|
||||
import { logger } from "../utils/logger";
|
||||
import { query } from "../database/db";
|
||||
|
||||
// 환경 변수로 데이터 소스 선택
|
||||
const DATA_SOURCE = process.env.MAINTENANCE_DATA_SOURCE || "memory";
|
||||
|
||||
export interface MaintenanceSchedule {
|
||||
id: string;
|
||||
vehicleNumber: string;
|
||||
vehicleType: string;
|
||||
maintenanceType: "정기점검" | "수리" | "타이어교체" | "오일교환" | "기타";
|
||||
scheduledDate: string;
|
||||
status: "scheduled" | "in_progress" | "completed" | "overdue";
|
||||
notes?: string;
|
||||
estimatedCost?: number;
|
||||
actualCost?: number;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
startedAt?: string;
|
||||
completedAt?: string;
|
||||
mechanicName?: string;
|
||||
location?: string;
|
||||
}
|
||||
|
||||
// 메모리 목 데이터
|
||||
const mockSchedules: MaintenanceSchedule[] = [
|
||||
{
|
||||
id: "maint-1",
|
||||
vehicleNumber: "서울12가3456",
|
||||
vehicleType: "1톤 트럭",
|
||||
maintenanceType: "정기점검",
|
||||
scheduledDate: new Date(Date.now() + 2 * 24 * 60 * 60 * 1000).toISOString(),
|
||||
status: "scheduled",
|
||||
notes: "6개월 정기점검",
|
||||
estimatedCost: 300000,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
location: "본사 정비소",
|
||||
},
|
||||
{
|
||||
id: "maint-2",
|
||||
vehicleNumber: "경기34나5678",
|
||||
vehicleType: "2.5톤 트럭",
|
||||
maintenanceType: "오일교환",
|
||||
scheduledDate: new Date(Date.now() + 1 * 24 * 60 * 60 * 1000).toISOString(),
|
||||
status: "scheduled",
|
||||
estimatedCost: 150000,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
location: "본사 정비소",
|
||||
},
|
||||
{
|
||||
id: "maint-3",
|
||||
vehicleNumber: "인천56다7890",
|
||||
vehicleType: "라보",
|
||||
maintenanceType: "타이어교체",
|
||||
scheduledDate: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString(),
|
||||
status: "overdue",
|
||||
notes: "긴급",
|
||||
estimatedCost: 400000,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
location: "외부 정비소",
|
||||
},
|
||||
{
|
||||
id: "maint-4",
|
||||
vehicleNumber: "부산78라1234",
|
||||
vehicleType: "1톤 트럭",
|
||||
maintenanceType: "수리",
|
||||
scheduledDate: new Date().toISOString(),
|
||||
status: "in_progress",
|
||||
notes: "엔진 점검 중",
|
||||
estimatedCost: 800000,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
startedAt: new Date().toISOString(),
|
||||
location: "본사 정비소",
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* 정비 일정 관리 서비스 (Memory/DB 하이브리드)
|
||||
*/
|
||||
export class MaintenanceService {
|
||||
private static instance: MaintenanceService;
|
||||
|
||||
private constructor() {
|
||||
logger.info(`🔧 정비 일정 데이터 소스: ${DATA_SOURCE.toUpperCase()}`);
|
||||
}
|
||||
|
||||
public static getInstance(): MaintenanceService {
|
||||
if (!MaintenanceService.instance) {
|
||||
MaintenanceService.instance = new MaintenanceService();
|
||||
}
|
||||
return MaintenanceService.instance;
|
||||
}
|
||||
|
||||
public async getAllSchedules(filter?: {
|
||||
status?: string;
|
||||
vehicleNumber?: string;
|
||||
}): Promise<MaintenanceSchedule[]> {
|
||||
try {
|
||||
const schedules = DATA_SOURCE === "database"
|
||||
? await this.loadSchedulesFromDB(filter)
|
||||
: this.loadSchedulesFromMemory(filter);
|
||||
|
||||
// 자동으로 overdue 상태 업데이트
|
||||
const now = new Date();
|
||||
schedules.forEach((s) => {
|
||||
if (s.status === "scheduled" && new Date(s.scheduledDate) < now) {
|
||||
s.status = "overdue";
|
||||
}
|
||||
});
|
||||
|
||||
// 정렬: 지연 > 진행중 > 예정 > 완료
|
||||
schedules.sort((a, b) => {
|
||||
const statusOrder = { overdue: 0, in_progress: 1, scheduled: 2, completed: 3 };
|
||||
if (a.status !== b.status) {
|
||||
return statusOrder[a.status] - statusOrder[b.status];
|
||||
}
|
||||
return new Date(a.scheduledDate).getTime() - new Date(b.scheduledDate).getTime();
|
||||
});
|
||||
|
||||
return schedules;
|
||||
} catch (error) {
|
||||
logger.error("❌ 정비 일정 조회 오류:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async updateScheduleStatus(
|
||||
id: string,
|
||||
status: MaintenanceSchedule["status"]
|
||||
): Promise<MaintenanceSchedule> {
|
||||
try {
|
||||
if (DATA_SOURCE === "database") {
|
||||
return await this.updateScheduleStatusDB(id, status);
|
||||
} else {
|
||||
return this.updateScheduleStatusMemory(id, status);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error("❌ 정비 상태 업데이트 오류:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== DATABASE 메서드 ====================
|
||||
|
||||
private async loadSchedulesFromDB(filter?: {
|
||||
status?: string;
|
||||
vehicleNumber?: string;
|
||||
}): Promise<MaintenanceSchedule[]> {
|
||||
let sql = `
|
||||
SELECT
|
||||
id, vehicle_number as "vehicleNumber", vehicle_type as "vehicleType",
|
||||
maintenance_type as "maintenanceType", scheduled_date as "scheduledDate",
|
||||
status, notes, estimated_cost as "estimatedCost", actual_cost as "actualCost",
|
||||
created_at as "createdAt", updated_at as "updatedAt",
|
||||
started_at as "startedAt", completed_at as "completedAt",
|
||||
mechanic_name as "mechanicName", location
|
||||
FROM maintenance_schedules
|
||||
WHERE 1=1
|
||||
`;
|
||||
const params: any[] = [];
|
||||
let paramIndex = 1;
|
||||
|
||||
if (filter?.status) {
|
||||
sql += ` AND status = $${paramIndex++}`;
|
||||
params.push(filter.status);
|
||||
}
|
||||
if (filter?.vehicleNumber) {
|
||||
sql += ` AND vehicle_number = $${paramIndex++}`;
|
||||
params.push(filter.vehicleNumber);
|
||||
}
|
||||
|
||||
const rows = await query(sql, params);
|
||||
return rows.map((row: any) => ({
|
||||
...row,
|
||||
scheduledDate: new Date(row.scheduledDate).toISOString(),
|
||||
createdAt: new Date(row.createdAt).toISOString(),
|
||||
updatedAt: new Date(row.updatedAt).toISOString(),
|
||||
startedAt: row.startedAt ? new Date(row.startedAt).toISOString() : undefined,
|
||||
completedAt: row.completedAt ? new Date(row.completedAt).toISOString() : undefined,
|
||||
}));
|
||||
}
|
||||
|
||||
private async updateScheduleStatusDB(
|
||||
id: string,
|
||||
status: MaintenanceSchedule["status"]
|
||||
): Promise<MaintenanceSchedule> {
|
||||
let additionalSet = "";
|
||||
if (status === "in_progress") {
|
||||
additionalSet = ", started_at = NOW()";
|
||||
} else if (status === "completed") {
|
||||
additionalSet = ", completed_at = NOW()";
|
||||
}
|
||||
|
||||
const rows = await query(
|
||||
`UPDATE maintenance_schedules
|
||||
SET status = $1, updated_at = NOW() ${additionalSet}
|
||||
WHERE id = $2
|
||||
RETURNING
|
||||
id, vehicle_number as "vehicleNumber", vehicle_type as "vehicleType",
|
||||
maintenance_type as "maintenanceType", scheduled_date as "scheduledDate",
|
||||
status, notes, estimated_cost as "estimatedCost",
|
||||
created_at as "createdAt", updated_at as "updatedAt",
|
||||
started_at as "startedAt", completed_at as "completedAt",
|
||||
mechanic_name as "mechanicName", location`,
|
||||
[status, id]
|
||||
);
|
||||
|
||||
if (rows.length === 0) {
|
||||
throw new Error(`정비 일정을 찾을 수 없습니다: ${id}`);
|
||||
}
|
||||
|
||||
const row = rows[0];
|
||||
return {
|
||||
...row,
|
||||
scheduledDate: new Date(row.scheduledDate).toISOString(),
|
||||
createdAt: new Date(row.createdAt).toISOString(),
|
||||
updatedAt: new Date(row.updatedAt).toISOString(),
|
||||
startedAt: row.startedAt ? new Date(row.startedAt).toISOString() : undefined,
|
||||
completedAt: row.completedAt ? new Date(row.completedAt).toISOString() : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
// ==================== MEMORY 메서드 ====================
|
||||
|
||||
private loadSchedulesFromMemory(filter?: {
|
||||
status?: string;
|
||||
vehicleNumber?: string;
|
||||
}): MaintenanceSchedule[] {
|
||||
let schedules = [...mockSchedules];
|
||||
|
||||
if (filter?.status) {
|
||||
schedules = schedules.filter((s) => s.status === filter.status);
|
||||
}
|
||||
if (filter?.vehicleNumber) {
|
||||
schedules = schedules.filter((s) => s.vehicleNumber === filter.vehicleNumber);
|
||||
}
|
||||
|
||||
return schedules;
|
||||
}
|
||||
|
||||
private updateScheduleStatusMemory(
|
||||
id: string,
|
||||
status: MaintenanceSchedule["status"]
|
||||
): MaintenanceSchedule {
|
||||
const schedule = mockSchedules.find((s) => s.id === id);
|
||||
|
||||
if (!schedule) {
|
||||
throw new Error(`정비 일정을 찾을 수 없습니다: ${id}`);
|
||||
}
|
||||
|
||||
schedule.status = status;
|
||||
schedule.updatedAt = new Date().toISOString();
|
||||
|
||||
if (status === "in_progress") {
|
||||
schedule.startedAt = new Date().toISOString();
|
||||
} else if (status === "completed") {
|
||||
schedule.completedAt = new Date().toISOString();
|
||||
}
|
||||
|
||||
return schedule;
|
||||
}
|
||||
}
|
||||
|
||||
229
backend-node/src/services/mapDataService.ts
Normal file
229
backend-node/src/services/mapDataService.ts
Normal file
@@ -0,0 +1,229 @@
|
||||
import { logger } from "../utils/logger";
|
||||
import { query } from "../database/db";
|
||||
import { ExternalDbConnectionService } from "./externalDbConnectionService";
|
||||
|
||||
interface MapDataQuery {
|
||||
connectionId?: number;
|
||||
tableName: string;
|
||||
latColumn: string;
|
||||
lngColumn: string;
|
||||
labelColumn?: string;
|
||||
statusColumn?: string;
|
||||
additionalColumns?: string[];
|
||||
whereClause?: string;
|
||||
}
|
||||
|
||||
export interface MapMarker {
|
||||
id: string | number;
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
label?: string;
|
||||
status?: string;
|
||||
additionalInfo?: Record<string, any>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 지도 데이터 서비스
|
||||
* 외부/내부 DB에서 위도/경도 데이터를 조회하여 지도 마커로 변환
|
||||
*/
|
||||
export class MapDataService {
|
||||
constructor() {
|
||||
// ExternalDbConnectionService는 static 메서드를 사용
|
||||
}
|
||||
|
||||
/**
|
||||
* 외부 DB에서 지도 데이터 조회
|
||||
*/
|
||||
async getMapData(params: MapDataQuery): Promise<MapMarker[]> {
|
||||
try {
|
||||
logger.info("🗺️ 외부 DB 지도 데이터 조회 시작:", params);
|
||||
|
||||
// SELECT할 컬럼 목록 구성
|
||||
const selectColumns = [
|
||||
params.latColumn,
|
||||
params.lngColumn,
|
||||
params.labelColumn,
|
||||
params.statusColumn,
|
||||
...(params.additionalColumns || []),
|
||||
].filter(Boolean);
|
||||
|
||||
// 중복 제거
|
||||
const uniqueColumns = Array.from(new Set(selectColumns));
|
||||
|
||||
// SQL 쿼리 구성
|
||||
let sql = `SELECT ${uniqueColumns.map((col) => `"${col}"`).join(", ")} FROM "${params.tableName}"`;
|
||||
|
||||
if (params.whereClause) {
|
||||
sql += ` WHERE ${params.whereClause}`;
|
||||
}
|
||||
|
||||
logger.info("📝 실행할 SQL:", sql);
|
||||
|
||||
// 외부 DB 쿼리 실행 (static 메서드 사용)
|
||||
const result = await ExternalDbConnectionService.executeQuery(
|
||||
params.connectionId!,
|
||||
sql
|
||||
);
|
||||
|
||||
if (!result.success || !result.data) {
|
||||
throw new Error("외부 DB 쿼리 실패");
|
||||
}
|
||||
|
||||
// 데이터를 MapMarker 형식으로 변환
|
||||
const markers = this.convertToMarkers(
|
||||
result.data,
|
||||
params.latColumn,
|
||||
params.lngColumn,
|
||||
params.labelColumn,
|
||||
params.statusColumn,
|
||||
params.additionalColumns
|
||||
);
|
||||
|
||||
logger.info(`✅ ${markers.length}개의 마커 데이터 변환 완료`);
|
||||
|
||||
return markers;
|
||||
} catch (error) {
|
||||
logger.error("❌ 외부 DB 지도 데이터 조회 오류:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 내부 DB에서 지도 데이터 조회
|
||||
*/
|
||||
async getInternalMapData(
|
||||
params: Omit<MapDataQuery, "connectionId">
|
||||
): Promise<MapMarker[]> {
|
||||
try {
|
||||
logger.info("🗺️ 내부 DB 지도 데이터 조회 시작:", params);
|
||||
|
||||
// SELECT할 컬럼 목록 구성
|
||||
const selectColumns = [
|
||||
params.latColumn,
|
||||
params.lngColumn,
|
||||
params.labelColumn,
|
||||
params.statusColumn,
|
||||
...(params.additionalColumns || []),
|
||||
].filter(Boolean);
|
||||
|
||||
// 중복 제거
|
||||
const uniqueColumns = Array.from(new Set(selectColumns));
|
||||
|
||||
// SQL 쿼리 구성
|
||||
let sql = `SELECT ${uniqueColumns.map((col) => `"${col}"`).join(", ")} FROM "${params.tableName}"`;
|
||||
|
||||
if (params.whereClause) {
|
||||
sql += ` WHERE ${params.whereClause}`;
|
||||
}
|
||||
|
||||
logger.info("📝 실행할 SQL:", sql);
|
||||
|
||||
// 내부 DB 쿼리 실행
|
||||
const rows = await query(sql);
|
||||
|
||||
// 데이터를 MapMarker 형식으로 변환
|
||||
const markers = this.convertToMarkers(
|
||||
rows,
|
||||
params.latColumn,
|
||||
params.lngColumn,
|
||||
params.labelColumn,
|
||||
params.statusColumn,
|
||||
params.additionalColumns
|
||||
);
|
||||
|
||||
logger.info(`✅ ${markers.length}개의 마커 데이터 변환 완료`);
|
||||
|
||||
return markers;
|
||||
} catch (error) {
|
||||
logger.error("❌ 내부 DB 지도 데이터 조회 오류:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* DB 결과를 MapMarker 배열로 변환
|
||||
*/
|
||||
private convertToMarkers(
|
||||
data: any[],
|
||||
latColumn: string,
|
||||
lngColumn: string,
|
||||
labelColumn?: string,
|
||||
statusColumn?: string,
|
||||
additionalColumns?: string[]
|
||||
): MapMarker[] {
|
||||
const markers: MapMarker[] = [];
|
||||
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
const row = data[i];
|
||||
|
||||
// 위도/경도 추출 (다양한 컬럼명 지원)
|
||||
const lat = this.extractCoordinate(row, latColumn);
|
||||
const lng = this.extractCoordinate(row, lngColumn);
|
||||
|
||||
// 유효한 좌표인지 확인
|
||||
if (lat === null || lng === null || isNaN(lat) || isNaN(lng)) {
|
||||
logger.warn(`⚠️ 유효하지 않은 좌표 스킵: row ${i}`, { lat, lng });
|
||||
continue;
|
||||
}
|
||||
|
||||
// 위도 범위 체크 (-90 ~ 90)
|
||||
if (lat < -90 || lat > 90) {
|
||||
logger.warn(`⚠️ 위도 범위 초과: ${lat}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// 경도 범위 체크 (-180 ~ 180)
|
||||
if (lng < -180 || lng > 180) {
|
||||
logger.warn(`⚠️ 경도 범위 초과: ${lng}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// 추가 정보 수집
|
||||
const additionalInfo: Record<string, any> = {};
|
||||
if (additionalColumns) {
|
||||
for (const col of additionalColumns) {
|
||||
if (col && row[col] !== undefined) {
|
||||
additionalInfo[col] = row[col];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 마커 생성
|
||||
markers.push({
|
||||
id: row.id || row.ID || `marker-${i}`,
|
||||
latitude: lat,
|
||||
longitude: lng,
|
||||
label: labelColumn ? row[labelColumn] : undefined,
|
||||
status: statusColumn ? row[statusColumn] : undefined,
|
||||
additionalInfo: Object.keys(additionalInfo).length > 0 ? additionalInfo : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
return markers;
|
||||
}
|
||||
|
||||
/**
|
||||
* 다양한 형식의 좌표 추출
|
||||
*/
|
||||
private extractCoordinate(row: any, columnName: string): number | null {
|
||||
const value = row[columnName];
|
||||
|
||||
if (value === null || value === undefined) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 이미 숫자인 경우
|
||||
if (typeof value === "number") {
|
||||
return value;
|
||||
}
|
||||
|
||||
// 문자열인 경우 파싱
|
||||
if (typeof value === "string") {
|
||||
const parsed = parseFloat(value);
|
||||
return isNaN(parsed) ? null : parsed;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
100
backend-node/src/services/riskAlertCacheService.ts
Normal file
100
backend-node/src/services/riskAlertCacheService.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* 리스크/알림 캐시 서비스
|
||||
* - 10분마다 자동 갱신
|
||||
* - 메모리 캐시로 빠른 응답
|
||||
*/
|
||||
|
||||
import { RiskAlertService, Alert } from './riskAlertService';
|
||||
|
||||
export class RiskAlertCacheService {
|
||||
private static instance: RiskAlertCacheService;
|
||||
private riskAlertService: RiskAlertService;
|
||||
|
||||
// 메모리 캐시
|
||||
private cachedAlerts: Alert[] = [];
|
||||
private lastUpdated: Date | null = null;
|
||||
private updateInterval: NodeJS.Timeout | null = null;
|
||||
|
||||
private constructor() {
|
||||
this.riskAlertService = new RiskAlertService();
|
||||
}
|
||||
|
||||
/**
|
||||
* 싱글톤 인스턴스
|
||||
*/
|
||||
public static getInstance(): RiskAlertCacheService {
|
||||
if (!RiskAlertCacheService.instance) {
|
||||
RiskAlertCacheService.instance = new RiskAlertCacheService();
|
||||
}
|
||||
return RiskAlertCacheService.instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* 자동 갱신 시작 (10분 간격)
|
||||
*/
|
||||
public startAutoRefresh(): void {
|
||||
console.log('🔄 리스크/알림 자동 갱신 시작 (10분 간격)');
|
||||
|
||||
// 즉시 첫 갱신
|
||||
this.refreshCache();
|
||||
|
||||
// 10분마다 갱신 (600,000ms)
|
||||
this.updateInterval = setInterval(() => {
|
||||
this.refreshCache();
|
||||
}, 10 * 60 * 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* 자동 갱신 중지
|
||||
*/
|
||||
public stopAutoRefresh(): void {
|
||||
if (this.updateInterval) {
|
||||
clearInterval(this.updateInterval);
|
||||
this.updateInterval = null;
|
||||
console.log('⏸️ 리스크/알림 자동 갱신 중지');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 캐시 갱신
|
||||
*/
|
||||
private async refreshCache(): Promise<void> {
|
||||
try {
|
||||
console.log('🔄 리스크/알림 캐시 갱신 중...');
|
||||
const startTime = Date.now();
|
||||
|
||||
const alerts = await this.riskAlertService.getAllAlerts();
|
||||
|
||||
this.cachedAlerts = alerts;
|
||||
this.lastUpdated = new Date();
|
||||
|
||||
const duration = Date.now() - startTime;
|
||||
console.log(`✅ 리스크/알림 캐시 갱신 완료! (${duration}ms)`);
|
||||
console.log(` - 총 ${alerts.length}건의 알림`);
|
||||
console.log(` - 기상특보: ${alerts.filter(a => a.type === 'weather').length}건`);
|
||||
console.log(` - 교통사고: ${alerts.filter(a => a.type === 'accident').length}건`);
|
||||
console.log(` - 도로공사: ${alerts.filter(a => a.type === 'construction').length}건`);
|
||||
} catch (error: any) {
|
||||
console.error('❌ 리스크/알림 캐시 갱신 실패:', error.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 캐시된 알림 조회 (빠름!)
|
||||
*/
|
||||
public getCachedAlerts(): { alerts: Alert[]; lastUpdated: Date | null } {
|
||||
return {
|
||||
alerts: this.cachedAlerts,
|
||||
lastUpdated: this.lastUpdated,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 수동 갱신 (필요 시)
|
||||
*/
|
||||
public async forceRefresh(): Promise<Alert[]> {
|
||||
await this.refreshCache();
|
||||
return this.cachedAlerts;
|
||||
}
|
||||
}
|
||||
|
||||
548
backend-node/src/services/riskAlertService.ts
Normal file
548
backend-node/src/services/riskAlertService.ts
Normal file
@@ -0,0 +1,548 @@
|
||||
/**
|
||||
* 리스크/알림 서비스
|
||||
* - 기상청 특보 API
|
||||
* - 국토교통부 교통사고/도로공사 API 연동
|
||||
*/
|
||||
|
||||
import axios from 'axios';
|
||||
|
||||
export interface Alert {
|
||||
id: string;
|
||||
type: 'accident' | 'weather' | 'construction';
|
||||
severity: 'high' | 'medium' | 'low';
|
||||
title: string;
|
||||
location: string;
|
||||
description: string;
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
export class RiskAlertService {
|
||||
/**
|
||||
* 기상청 특보 정보 조회 (기상청 API 허브 - 현재 발효 중인 특보 API)
|
||||
*/
|
||||
async getWeatherAlerts(): Promise<Alert[]> {
|
||||
try {
|
||||
const apiKey = process.env.KMA_API_KEY;
|
||||
|
||||
if (!apiKey) {
|
||||
console.log('⚠️ 기상청 API 키가 없습니다. 테스트 데이터를 반환합니다.');
|
||||
return this.generateDummyWeatherAlerts();
|
||||
}
|
||||
|
||||
const alerts: Alert[] = [];
|
||||
|
||||
// 기상청 특보 현황 조회 API (실제 발효 중인 특보)
|
||||
try {
|
||||
const warningUrl = 'https://apihub.kma.go.kr/api/typ01/url/wrn_now_data.php';
|
||||
const warningResponse = await axios.get(warningUrl, {
|
||||
params: {
|
||||
fe: 'f', // 발표 중인 특보
|
||||
tm: '', // 현재 시각
|
||||
disp: 0,
|
||||
authKey: apiKey,
|
||||
},
|
||||
timeout: 10000,
|
||||
responseType: 'arraybuffer', // 인코딩 문제 해결
|
||||
});
|
||||
|
||||
console.log('✅ 기상청 특보 현황 API 응답 수신 완료');
|
||||
|
||||
// 텍스트 응답 파싱 (EUC-KR 인코딩)
|
||||
const iconv = require('iconv-lite');
|
||||
const responseText = iconv.decode(Buffer.from(warningResponse.data), 'EUC-KR');
|
||||
|
||||
if (typeof responseText === 'string' && responseText.includes('#START7777')) {
|
||||
const lines = responseText.split('\n');
|
||||
|
||||
for (const line of lines) {
|
||||
// 주석 및 헤더 라인 무시
|
||||
if (line.startsWith('#') || line.trim() === '' || line.includes('7777END')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 데이터 라인 파싱
|
||||
const fields = line.split(',').map((f) => f.trim());
|
||||
if (fields.length >= 7) {
|
||||
const regUpKo = fields[1]; // 상위 특보 지역명
|
||||
const regKo = fields[3]; // 특보 지역명
|
||||
const tmFc = fields[4]; // 발표 시각
|
||||
const wrnType = fields[6]; // 특보 종류
|
||||
const wrnLevel = fields[7]; // 특보 수준 (주의보/경보)
|
||||
|
||||
// 특보 종류별 매핑
|
||||
const warningMap: Record<string, { title: string; severity: 'high' | 'medium' | 'low' }> = {
|
||||
'풍랑': { title: '풍랑주의보', severity: 'medium' },
|
||||
'강풍': { title: '강풍주의보', severity: 'medium' },
|
||||
'대설': { title: '대설특보', severity: 'high' },
|
||||
'폭설': { title: '대설특보', severity: 'high' },
|
||||
'태풍': { title: '태풍특보', severity: 'high' },
|
||||
'호우': { title: '호우특보', severity: 'high' },
|
||||
'한파': { title: '한파특보', severity: 'high' },
|
||||
'폭염': { title: '폭염특보', severity: 'high' },
|
||||
'건조': { title: '건조특보', severity: 'low' },
|
||||
'해일': { title: '해일특보', severity: 'high' },
|
||||
'너울': { title: '너울주의보', severity: 'low' },
|
||||
};
|
||||
|
||||
const warningInfo = warningMap[wrnType];
|
||||
if (warningInfo) {
|
||||
// 경보는 심각도 높이기
|
||||
const severity = wrnLevel.includes('경보') ? 'high' : warningInfo.severity;
|
||||
const title = wrnLevel.includes('경보')
|
||||
? wrnType + '경보'
|
||||
: warningInfo.title;
|
||||
|
||||
alerts.push({
|
||||
id: `warning-${Date.now()}-${alerts.length}`,
|
||||
type: 'weather' as const,
|
||||
severity: severity,
|
||||
title: title,
|
||||
location: regKo || regUpKo || '전국',
|
||||
description: `${wrnLevel} 발표 - ${regUpKo} ${regKo}`,
|
||||
timestamp: this.parseKmaTime(tmFc),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`✅ 총 ${alerts.length}건의 기상특보 감지`);
|
||||
} catch (warningError: any) {
|
||||
console.error('❌ 기상청 특보 API 오류:', warningError.message);
|
||||
return this.generateDummyWeatherAlerts();
|
||||
}
|
||||
|
||||
// 특보가 없으면 빈 배열 반환 (0건)
|
||||
if (alerts.length === 0) {
|
||||
console.log('ℹ️ 현재 발효 중인 기상특보 없음 (0건)');
|
||||
}
|
||||
|
||||
return alerts;
|
||||
} catch (error: any) {
|
||||
console.error('❌ 기상청 특보 API 오류:', error.message);
|
||||
// API 오류 시 더미 데이터 반환
|
||||
return this.generateDummyWeatherAlerts();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 교통사고 정보 조회 (국토교통부 ITS API 우선, 실패 시 한국도로공사)
|
||||
*/
|
||||
async getAccidentAlerts(): Promise<Alert[]> {
|
||||
// 1순위: 국토교통부 ITS API (실시간 돌발정보)
|
||||
const itsApiKey = process.env.ITS_API_KEY;
|
||||
if (itsApiKey) {
|
||||
try {
|
||||
const url = `https://openapi.its.go.kr:9443/eventInfo`;
|
||||
|
||||
const response = await axios.get(url, {
|
||||
params: {
|
||||
apiKey: itsApiKey,
|
||||
type: 'all',
|
||||
eventType: 'acc', // 교통사고
|
||||
minX: 124, // 전국 범위
|
||||
maxX: 132,
|
||||
minY: 33,
|
||||
maxY: 43,
|
||||
getType: 'json',
|
||||
},
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
console.log('✅ 국토교통부 ITS 교통사고 API 응답 수신 완료');
|
||||
|
||||
const alerts: Alert[] = [];
|
||||
|
||||
if (response.data?.header?.resultCode === 0 && response.data?.body?.items) {
|
||||
const items = Array.isArray(response.data.body.items) ? response.data.body.items : [response.data.body.items];
|
||||
|
||||
items.forEach((item: any, index: number) => {
|
||||
// ITS API 필드: eventType(교통사고), roadName, message, startDate, lanesBlocked
|
||||
const lanesCount = (item.lanesBlocked || '').match(/\d+/)?.[0] || 0;
|
||||
const severity = Number(lanesCount) >= 2 ? 'high' : Number(lanesCount) === 1 ? 'medium' : 'low';
|
||||
|
||||
alerts.push({
|
||||
id: `accident-its-${Date.now()}-${index}`,
|
||||
type: 'accident' as const,
|
||||
severity: severity as 'high' | 'medium' | 'low',
|
||||
title: `[${item.roadName || '고속도로'}] 교통사고`,
|
||||
location: `${item.roadName || ''} ${item.roadDrcType || ''}`.trim() || '정보 없음',
|
||||
description: item.message || `${item.eventDetailType || '사고 발생'} - ${item.lanesBlocked || '차로 통제'}`,
|
||||
timestamp: this.parseITSTime(item.startDate || ''),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (alerts.length === 0) {
|
||||
console.log('ℹ️ 현재 교통사고 없음 (0건)');
|
||||
} else {
|
||||
console.log(`✅ 총 ${alerts.length}건의 교통사고 감지 (ITS)`);
|
||||
}
|
||||
|
||||
return alerts;
|
||||
} catch (error: any) {
|
||||
console.error('❌ 국토교통부 ITS API 오류:', error.message);
|
||||
console.log('ℹ️ 2순위 API로 전환합니다.');
|
||||
}
|
||||
}
|
||||
|
||||
// 2순위: 한국도로공사 API (현재 차단됨)
|
||||
const exwayApiKey = process.env.EXWAY_API_KEY || '7820214492';
|
||||
try {
|
||||
const url = 'https://data.ex.co.kr/openapi/business/trafficFcst';
|
||||
|
||||
const response = await axios.get(url, {
|
||||
params: {
|
||||
key: exwayApiKey,
|
||||
type: 'json',
|
||||
},
|
||||
timeout: 10000,
|
||||
headers: {
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
|
||||
'Referer': 'https://data.ex.co.kr/',
|
||||
},
|
||||
});
|
||||
|
||||
console.log('✅ 한국도로공사 교통예보 API 응답 수신 완료');
|
||||
|
||||
const alerts: Alert[] = [];
|
||||
|
||||
if (response.data?.list) {
|
||||
const items = Array.isArray(response.data.list) ? response.data.list : [response.data.list];
|
||||
|
||||
items.forEach((item: any, index: number) => {
|
||||
const contentType = item.conzoneCd || item.contentType || '';
|
||||
|
||||
if (contentType === '00' || item.content?.includes('사고')) {
|
||||
const severity = contentType === '31' ? 'high' : contentType === '30' ? 'medium' : 'low';
|
||||
|
||||
alerts.push({
|
||||
id: `accident-exway-${Date.now()}-${index}`,
|
||||
type: 'accident' as const,
|
||||
severity: severity as 'high' | 'medium' | 'low',
|
||||
title: '교통사고',
|
||||
location: item.routeName || item.location || '고속도로',
|
||||
description: item.content || item.message || '교통사고 발생',
|
||||
timestamp: new Date(item.regDate || Date.now()).toISOString(),
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (alerts.length > 0) {
|
||||
console.log(`✅ 총 ${alerts.length}건의 교통사고 감지 (한국도로공사)`);
|
||||
return alerts;
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('❌ 한국도로공사 API 오류:', error.message);
|
||||
}
|
||||
|
||||
// 모든 API 실패 시 더미 데이터
|
||||
console.log('ℹ️ 모든 교통사고 API 실패. 더미 데이터를 반환합니다.');
|
||||
return this.generateDummyAccidentAlerts();
|
||||
}
|
||||
|
||||
/**
|
||||
* 도로공사 정보 조회 (국토교통부 ITS API 우선, 실패 시 한국도로공사)
|
||||
*/
|
||||
async getRoadworkAlerts(): Promise<Alert[]> {
|
||||
// 1순위: 국토교통부 ITS API (실시간 돌발정보 - 공사)
|
||||
const itsApiKey = process.env.ITS_API_KEY;
|
||||
if (itsApiKey) {
|
||||
try {
|
||||
const url = `https://openapi.its.go.kr:9443/eventInfo`;
|
||||
|
||||
const response = await axios.get(url, {
|
||||
params: {
|
||||
apiKey: itsApiKey,
|
||||
type: 'all',
|
||||
eventType: 'all', // 전체 조회 후 필터링
|
||||
minX: 124,
|
||||
maxX: 132,
|
||||
minY: 33,
|
||||
maxY: 43,
|
||||
getType: 'json',
|
||||
},
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
console.log('✅ 국토교통부 ITS 도로공사 API 응답 수신 완료');
|
||||
|
||||
const alerts: Alert[] = [];
|
||||
|
||||
if (response.data?.header?.resultCode === 0 && response.data?.body?.items) {
|
||||
const items = Array.isArray(response.data.body.items) ? response.data.body.items : [response.data.body.items];
|
||||
|
||||
items.forEach((item: any, index: number) => {
|
||||
// 공사/작업만 필터링
|
||||
if (item.eventType === '공사' || item.eventDetailType === '작업') {
|
||||
const lanesCount = (item.lanesBlocked || '').match(/\d+/)?.[0] || 0;
|
||||
const severity = Number(lanesCount) >= 2 ? 'high' : 'medium';
|
||||
|
||||
alerts.push({
|
||||
id: `construction-its-${Date.now()}-${index}`,
|
||||
type: 'construction' as const,
|
||||
severity: severity as 'high' | 'medium' | 'low',
|
||||
title: `[${item.roadName || '고속도로'}] 도로 공사`,
|
||||
location: `${item.roadName || ''} ${item.roadDrcType || ''}`.trim() || '정보 없음',
|
||||
description: item.message || `${item.eventDetailType || '작업'} - ${item.lanesBlocked || '차로 통제'}`,
|
||||
timestamp: this.parseITSTime(item.startDate || ''),
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (alerts.length === 0) {
|
||||
console.log('ℹ️ 현재 도로공사 없음 (0건)');
|
||||
} else {
|
||||
console.log(`✅ 총 ${alerts.length}건의 도로공사 감지 (ITS)`);
|
||||
}
|
||||
|
||||
return alerts;
|
||||
} catch (error: any) {
|
||||
console.error('❌ 국토교통부 ITS API 오류:', error.message);
|
||||
console.log('ℹ️ 2순위 API로 전환합니다.');
|
||||
}
|
||||
}
|
||||
|
||||
// 2순위: 한국도로공사 API
|
||||
const exwayApiKey = process.env.EXWAY_API_KEY || '7820214492';
|
||||
try {
|
||||
const url = 'https://data.ex.co.kr/openapi/business/trafficFcst';
|
||||
|
||||
const response = await axios.get(url, {
|
||||
params: {
|
||||
key: exwayApiKey,
|
||||
type: 'json',
|
||||
},
|
||||
timeout: 10000,
|
||||
headers: {
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
|
||||
'Referer': 'https://data.ex.co.kr/',
|
||||
},
|
||||
});
|
||||
|
||||
console.log('✅ 한국도로공사 교통예보 API 응답 수신 완료 (도로공사)');
|
||||
|
||||
const alerts: Alert[] = [];
|
||||
|
||||
if (response.data?.list) {
|
||||
const items = Array.isArray(response.data.list) ? response.data.list : [response.data.list];
|
||||
|
||||
items.forEach((item: any, index: number) => {
|
||||
const contentType = item.conzoneCd || item.contentType || '';
|
||||
|
||||
if (contentType === '03' || item.content?.includes('작업') || item.content?.includes('공사')) {
|
||||
const severity = contentType === '31' ? 'high' : contentType === '30' ? 'medium' : 'low';
|
||||
|
||||
alerts.push({
|
||||
id: `construction-exway-${Date.now()}-${index}`,
|
||||
type: 'construction' as const,
|
||||
severity: severity as 'high' | 'medium' | 'low',
|
||||
title: '도로 공사',
|
||||
location: item.routeName || item.location || '고속도로',
|
||||
description: item.content || item.message || '도로 공사 진행 중',
|
||||
timestamp: new Date(item.regDate || Date.now()).toISOString(),
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (alerts.length > 0) {
|
||||
console.log(`✅ 총 ${alerts.length}건의 도로공사 감지 (한국도로공사)`);
|
||||
return alerts;
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('❌ 한국도로공사 API 오류:', error.message);
|
||||
}
|
||||
|
||||
// 모든 API 실패 시 더미 데이터
|
||||
console.log('ℹ️ 모든 도로공사 API 실패. 더미 데이터를 반환합니다.');
|
||||
return this.generateDummyRoadworkAlerts();
|
||||
}
|
||||
|
||||
/**
|
||||
* 전체 알림 조회 (통합)
|
||||
*/
|
||||
async getAllAlerts(): Promise<Alert[]> {
|
||||
try {
|
||||
const [weatherAlerts, accidentAlerts, roadworkAlerts] = await Promise.all([
|
||||
this.getWeatherAlerts(),
|
||||
this.getAccidentAlerts(),
|
||||
this.getRoadworkAlerts(),
|
||||
]);
|
||||
|
||||
// 모든 알림 합치기
|
||||
const allAlerts = [...weatherAlerts, ...accidentAlerts, ...roadworkAlerts];
|
||||
|
||||
// 시간 순으로 정렬 (최신순)
|
||||
allAlerts.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
|
||||
|
||||
return allAlerts;
|
||||
} catch (error: any) {
|
||||
console.error('❌ 전체 알림 조회 오류:', error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 기상청 시간 형식 파싱 (YYYYMMDDHHmm -> ISO)
|
||||
*/
|
||||
private parseKmaTime(tmFc: string): string {
|
||||
try {
|
||||
if (!tmFc || tmFc.length !== 12) {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
const year = tmFc.substring(0, 4);
|
||||
const month = tmFc.substring(4, 6);
|
||||
const day = tmFc.substring(6, 8);
|
||||
const hour = tmFc.substring(8, 10);
|
||||
const minute = tmFc.substring(10, 12);
|
||||
|
||||
return new Date(`${year}-${month}-${day}T${hour}:${minute}:00+09:00`).toISOString();
|
||||
} catch (error) {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ITS API 시간 형식 파싱 (YYYYMMDDHHmmss -> ISO)
|
||||
*/
|
||||
private parseITSTime(dateStr: string): string {
|
||||
try {
|
||||
if (!dateStr || dateStr.length !== 14) {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
const year = dateStr.substring(0, 4);
|
||||
const month = dateStr.substring(4, 6);
|
||||
const day = dateStr.substring(6, 8);
|
||||
const hour = dateStr.substring(8, 10);
|
||||
const minute = dateStr.substring(10, 12);
|
||||
const second = dateStr.substring(12, 14);
|
||||
|
||||
return new Date(`${year}-${month}-${day}T${hour}:${minute}:${second}+09:00`).toISOString();
|
||||
} catch (error) {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 기상 특보 심각도 판단
|
||||
*/
|
||||
private getWeatherSeverity(wrnLv: string): 'high' | 'medium' | 'low' {
|
||||
if (wrnLv.includes('경보') || wrnLv.includes('특보')) {
|
||||
return 'high';
|
||||
}
|
||||
if (wrnLv.includes('주의보')) {
|
||||
return 'medium';
|
||||
}
|
||||
return 'low';
|
||||
}
|
||||
|
||||
/**
|
||||
* 기상 특보 제목 생성
|
||||
*/
|
||||
private getWeatherTitle(wrnLv: string): string {
|
||||
if (wrnLv.includes('대설')) return '대설특보';
|
||||
if (wrnLv.includes('태풍')) return '태풍특보';
|
||||
if (wrnLv.includes('강풍')) return '강풍특보';
|
||||
if (wrnLv.includes('호우')) return '호우특보';
|
||||
if (wrnLv.includes('한파')) return '한파특보';
|
||||
if (wrnLv.includes('폭염')) return '폭염특보';
|
||||
return '기상특보';
|
||||
}
|
||||
|
||||
/**
|
||||
* 교통사고 심각도 판단
|
||||
*/
|
||||
private getAccidentSeverity(accInfo: string): 'high' | 'medium' | 'low' {
|
||||
if (accInfo.includes('중대') || accInfo.includes('다중') || accInfo.includes('추돌')) {
|
||||
return 'high';
|
||||
}
|
||||
if (accInfo.includes('접촉') || accInfo.includes('경상')) {
|
||||
return 'medium';
|
||||
}
|
||||
return 'low';
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트용 날씨 특보 더미 데이터
|
||||
*/
|
||||
private generateDummyWeatherAlerts(): Alert[] {
|
||||
return [
|
||||
{
|
||||
id: `weather-${Date.now()}-1`,
|
||||
type: 'weather',
|
||||
severity: 'high',
|
||||
title: '대설특보',
|
||||
location: '강원 영동지역',
|
||||
description: '시간당 2cm 이상 폭설. 차량 운행 주의',
|
||||
timestamp: new Date(Date.now() - 30 * 60000).toISOString(),
|
||||
},
|
||||
{
|
||||
id: `weather-${Date.now()}-2`,
|
||||
type: 'weather',
|
||||
severity: 'medium',
|
||||
title: '강풍특보',
|
||||
location: '남해안 전 지역',
|
||||
description: '순간 풍속 20m/s 이상. 고속도로 주행 주의',
|
||||
timestamp: new Date(Date.now() - 90 * 60000).toISOString(),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트용 교통사고 더미 데이터
|
||||
*/
|
||||
private generateDummyAccidentAlerts(): Alert[] {
|
||||
return [
|
||||
{
|
||||
id: `accident-${Date.now()}-1`,
|
||||
type: 'accident',
|
||||
severity: 'high',
|
||||
title: '교통사고 발생',
|
||||
location: '경부고속도로 서울방향 189km',
|
||||
description: '3중 추돌사고로 2차로 통제 중. 우회 권장',
|
||||
timestamp: new Date(Date.now() - 10 * 60000).toISOString(),
|
||||
},
|
||||
{
|
||||
id: `accident-${Date.now()}-2`,
|
||||
type: 'accident',
|
||||
severity: 'medium',
|
||||
title: '사고 다발 지역',
|
||||
location: '영동고속도로 강릉방향 160km',
|
||||
description: '안개로 인한 가시거리 50m 이하. 서행 운전',
|
||||
timestamp: new Date(Date.now() - 60 * 60000).toISOString(),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트용 도로공사 더미 데이터
|
||||
*/
|
||||
private generateDummyRoadworkAlerts(): Alert[] {
|
||||
return [
|
||||
{
|
||||
id: `construction-${Date.now()}-1`,
|
||||
type: 'construction',
|
||||
severity: 'medium',
|
||||
title: '도로 공사',
|
||||
location: '서울외곽순환 목동IC~화곡IC',
|
||||
description: '야간 공사로 1차로 통제 (22:00~06:00)',
|
||||
timestamp: new Date(Date.now() - 45 * 60000).toISOString(),
|
||||
},
|
||||
{
|
||||
id: `construction-${Date.now()}-2`,
|
||||
type: 'construction',
|
||||
severity: 'low',
|
||||
title: '도로 통제',
|
||||
location: '중부내륙고속도로 김천JC~현풍IC',
|
||||
description: '도로 유지보수 작업. 차량 속도 제한 60km/h',
|
||||
timestamp: new Date(Date.now() - 120 * 60000).toISOString(),
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
449
backend-node/src/services/todoService.ts
Normal file
449
backend-node/src/services/todoService.ts
Normal file
@@ -0,0 +1,449 @@
|
||||
import * as fs from "fs";
|
||||
import * as path from "path";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { logger } from "../utils/logger";
|
||||
import { query } from "../database/db";
|
||||
|
||||
const TODO_DIR = path.join(__dirname, "../../data/todos");
|
||||
const TODO_FILE = path.join(TODO_DIR, "todos.json");
|
||||
|
||||
// 환경 변수로 데이터 소스 선택 (file | database)
|
||||
const DATA_SOURCE = process.env.TODO_DATA_SOURCE || "file";
|
||||
|
||||
export interface TodoItem {
|
||||
id: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
priority: "urgent" | "high" | "normal" | "low";
|
||||
status: "pending" | "in_progress" | "completed";
|
||||
assignedTo?: string;
|
||||
dueDate?: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
completedAt?: string;
|
||||
isUrgent: boolean;
|
||||
order: number;
|
||||
}
|
||||
|
||||
export interface TodoListResponse {
|
||||
todos: TodoItem[];
|
||||
stats: {
|
||||
total: number;
|
||||
pending: number;
|
||||
inProgress: number;
|
||||
completed: number;
|
||||
urgent: number;
|
||||
overdue: number;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* To-Do 리스트 관리 서비스 (File/DB 하이브리드)
|
||||
*/
|
||||
export class TodoService {
|
||||
private static instance: TodoService;
|
||||
|
||||
private constructor() {
|
||||
if (DATA_SOURCE === "file") {
|
||||
this.ensureDataDirectory();
|
||||
}
|
||||
logger.info(`📋 To-Do 데이터 소스: ${DATA_SOURCE.toUpperCase()}`);
|
||||
}
|
||||
|
||||
public static getInstance(): TodoService {
|
||||
if (!TodoService.instance) {
|
||||
TodoService.instance = new TodoService();
|
||||
}
|
||||
return TodoService.instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* 데이터 디렉토리 생성 (파일 모드)
|
||||
*/
|
||||
private ensureDataDirectory(): void {
|
||||
if (!fs.existsSync(TODO_DIR)) {
|
||||
fs.mkdirSync(TODO_DIR, { recursive: true });
|
||||
logger.info(`📁 To-Do 데이터 디렉토리 생성: ${TODO_DIR}`);
|
||||
}
|
||||
if (!fs.existsSync(TODO_FILE)) {
|
||||
fs.writeFileSync(TODO_FILE, JSON.stringify([], null, 2));
|
||||
logger.info(`📄 To-Do 파일 생성: ${TODO_FILE}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 To-Do 항목 조회
|
||||
*/
|
||||
public async getAllTodos(filter?: {
|
||||
status?: string;
|
||||
priority?: string;
|
||||
assignedTo?: string;
|
||||
}): Promise<TodoListResponse> {
|
||||
try {
|
||||
const todos = DATA_SOURCE === "database"
|
||||
? await this.loadTodosFromDB(filter)
|
||||
: this.loadTodosFromFile(filter);
|
||||
|
||||
// 정렬: 긴급 > 우선순위 > 순서
|
||||
todos.sort((a, b) => {
|
||||
if (a.isUrgent !== b.isUrgent) return a.isUrgent ? -1 : 1;
|
||||
const priorityOrder = { urgent: 0, high: 1, normal: 2, low: 3 };
|
||||
if (a.priority !== b.priority) return priorityOrder[a.priority] - priorityOrder[b.priority];
|
||||
return a.order - b.order;
|
||||
});
|
||||
|
||||
const stats = this.calculateStats(todos);
|
||||
|
||||
return { todos, stats };
|
||||
} catch (error) {
|
||||
logger.error("❌ To-Do 목록 조회 오류:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* To-Do 항목 생성
|
||||
*/
|
||||
public async createTodo(todoData: Partial<TodoItem>): Promise<TodoItem> {
|
||||
try {
|
||||
const newTodo: TodoItem = {
|
||||
id: uuidv4(),
|
||||
title: todoData.title || "",
|
||||
description: todoData.description,
|
||||
priority: todoData.priority || "normal",
|
||||
status: "pending",
|
||||
assignedTo: todoData.assignedTo,
|
||||
dueDate: todoData.dueDate,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
isUrgent: todoData.isUrgent || false,
|
||||
order: 0, // DB에서 자동 계산
|
||||
};
|
||||
|
||||
if (DATA_SOURCE === "database") {
|
||||
await this.createTodoDB(newTodo);
|
||||
} else {
|
||||
const todos = this.loadTodosFromFile();
|
||||
newTodo.order = todos.length > 0 ? Math.max(...todos.map((t) => t.order)) + 1 : 0;
|
||||
todos.push(newTodo);
|
||||
this.saveTodosToFile(todos);
|
||||
}
|
||||
|
||||
logger.info(`✅ To-Do 생성: ${newTodo.id} - ${newTodo.title}`);
|
||||
return newTodo;
|
||||
} catch (error) {
|
||||
logger.error("❌ To-Do 생성 오류:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* To-Do 항목 수정
|
||||
*/
|
||||
public async updateTodo(id: string, updates: Partial<TodoItem>): Promise<TodoItem> {
|
||||
try {
|
||||
if (DATA_SOURCE === "database") {
|
||||
return await this.updateTodoDB(id, updates);
|
||||
} else {
|
||||
return this.updateTodoFile(id, updates);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error("❌ To-Do 수정 오류:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* To-Do 항목 삭제
|
||||
*/
|
||||
public async deleteTodo(id: string): Promise<void> {
|
||||
try {
|
||||
if (DATA_SOURCE === "database") {
|
||||
await this.deleteTodoDB(id);
|
||||
} else {
|
||||
this.deleteTodoFile(id);
|
||||
}
|
||||
logger.info(`✅ To-Do 삭제: ${id}`);
|
||||
} catch (error) {
|
||||
logger.error("❌ To-Do 삭제 오류:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* To-Do 항목 순서 변경
|
||||
*/
|
||||
public async reorderTodos(todoIds: string[]): Promise<void> {
|
||||
try {
|
||||
if (DATA_SOURCE === "database") {
|
||||
await this.reorderTodosDB(todoIds);
|
||||
} else {
|
||||
this.reorderTodosFile(todoIds);
|
||||
}
|
||||
logger.info(`✅ To-Do 순서 변경: ${todoIds.length}개 항목`);
|
||||
} catch (error) {
|
||||
logger.error("❌ To-Do 순서 변경 오류:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== DATABASE 메서드 ====================
|
||||
|
||||
private async loadTodosFromDB(filter?: {
|
||||
status?: string;
|
||||
priority?: string;
|
||||
assignedTo?: string;
|
||||
}): Promise<TodoItem[]> {
|
||||
let sql = `
|
||||
SELECT
|
||||
id, title, description, priority, status,
|
||||
assigned_to as "assignedTo",
|
||||
due_date as "dueDate",
|
||||
created_at as "createdAt",
|
||||
updated_at as "updatedAt",
|
||||
completed_at as "completedAt",
|
||||
is_urgent as "isUrgent",
|
||||
display_order as "order"
|
||||
FROM todo_items
|
||||
WHERE 1=1
|
||||
`;
|
||||
const params: any[] = [];
|
||||
let paramIndex = 1;
|
||||
|
||||
if (filter?.status) {
|
||||
sql += ` AND status = $${paramIndex++}`;
|
||||
params.push(filter.status);
|
||||
}
|
||||
if (filter?.priority) {
|
||||
sql += ` AND priority = $${paramIndex++}`;
|
||||
params.push(filter.priority);
|
||||
}
|
||||
if (filter?.assignedTo) {
|
||||
sql += ` AND assigned_to = $${paramIndex++}`;
|
||||
params.push(filter.assignedTo);
|
||||
}
|
||||
|
||||
sql += ` ORDER BY display_order ASC`;
|
||||
|
||||
const rows = await query(sql, params);
|
||||
return rows.map((row: any) => ({
|
||||
...row,
|
||||
dueDate: row.dueDate ? new Date(row.dueDate).toISOString() : undefined,
|
||||
createdAt: new Date(row.createdAt).toISOString(),
|
||||
updatedAt: new Date(row.updatedAt).toISOString(),
|
||||
completedAt: row.completedAt ? new Date(row.completedAt).toISOString() : undefined,
|
||||
}));
|
||||
}
|
||||
|
||||
private async createTodoDB(todo: TodoItem): Promise<void> {
|
||||
// 현재 최대 order 값 조회
|
||||
const maxOrderRows = await query(
|
||||
"SELECT COALESCE(MAX(display_order), -1) + 1 as next_order FROM todo_items"
|
||||
);
|
||||
const nextOrder = maxOrderRows[0].next_order;
|
||||
|
||||
await query(
|
||||
`INSERT INTO todo_items (
|
||||
id, title, description, priority, status, assigned_to, due_date,
|
||||
created_at, updated_at, is_urgent, display_order
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,
|
||||
[
|
||||
todo.id,
|
||||
todo.title,
|
||||
todo.description,
|
||||
todo.priority,
|
||||
todo.status,
|
||||
todo.assignedTo,
|
||||
todo.dueDate ? new Date(todo.dueDate) : null,
|
||||
new Date(todo.createdAt),
|
||||
new Date(todo.updatedAt),
|
||||
todo.isUrgent,
|
||||
nextOrder,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
private async updateTodoDB(id: string, updates: Partial<TodoItem>): Promise<TodoItem> {
|
||||
const setClauses: string[] = ["updated_at = NOW()"];
|
||||
const params: any[] = [];
|
||||
let paramIndex = 1;
|
||||
|
||||
if (updates.title !== undefined) {
|
||||
setClauses.push(`title = $${paramIndex++}`);
|
||||
params.push(updates.title);
|
||||
}
|
||||
if (updates.description !== undefined) {
|
||||
setClauses.push(`description = $${paramIndex++}`);
|
||||
params.push(updates.description);
|
||||
}
|
||||
if (updates.priority !== undefined) {
|
||||
setClauses.push(`priority = $${paramIndex++}`);
|
||||
params.push(updates.priority);
|
||||
}
|
||||
if (updates.status !== undefined) {
|
||||
setClauses.push(`status = $${paramIndex++}`);
|
||||
params.push(updates.status);
|
||||
if (updates.status === "completed") {
|
||||
setClauses.push(`completed_at = NOW()`);
|
||||
}
|
||||
}
|
||||
if (updates.assignedTo !== undefined) {
|
||||
setClauses.push(`assigned_to = $${paramIndex++}`);
|
||||
params.push(updates.assignedTo);
|
||||
}
|
||||
if (updates.dueDate !== undefined) {
|
||||
setClauses.push(`due_date = $${paramIndex++}`);
|
||||
params.push(updates.dueDate ? new Date(updates.dueDate) : null);
|
||||
}
|
||||
if (updates.isUrgent !== undefined) {
|
||||
setClauses.push(`is_urgent = $${paramIndex++}`);
|
||||
params.push(updates.isUrgent);
|
||||
}
|
||||
|
||||
params.push(id);
|
||||
const sql = `
|
||||
UPDATE todo_items
|
||||
SET ${setClauses.join(", ")}
|
||||
WHERE id = $${paramIndex}
|
||||
RETURNING
|
||||
id, title, description, priority, status,
|
||||
assigned_to as "assignedTo",
|
||||
due_date as "dueDate",
|
||||
created_at as "createdAt",
|
||||
updated_at as "updatedAt",
|
||||
completed_at as "completedAt",
|
||||
is_urgent as "isUrgent",
|
||||
display_order as "order"
|
||||
`;
|
||||
|
||||
const rows = await query(sql, params);
|
||||
if (rows.length === 0) {
|
||||
throw new Error(`To-Do 항목을 찾을 수 없습니다: ${id}`);
|
||||
}
|
||||
|
||||
const row = rows[0];
|
||||
return {
|
||||
...row,
|
||||
dueDate: row.dueDate ? new Date(row.dueDate).toISOString() : undefined,
|
||||
createdAt: new Date(row.createdAt).toISOString(),
|
||||
updatedAt: new Date(row.updatedAt).toISOString(),
|
||||
completedAt: row.completedAt ? new Date(row.completedAt).toISOString() : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
private async deleteTodoDB(id: string): Promise<void> {
|
||||
const rows = await query("DELETE FROM todo_items WHERE id = $1 RETURNING id", [id]);
|
||||
if (rows.length === 0) {
|
||||
throw new Error(`To-Do 항목을 찾을 수 없습니다: ${id}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async reorderTodosDB(todoIds: string[]): Promise<void> {
|
||||
for (let i = 0; i < todoIds.length; i++) {
|
||||
await query(
|
||||
"UPDATE todo_items SET display_order = $1, updated_at = NOW() WHERE id = $2",
|
||||
[i, todoIds[i]]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== FILE 메서드 ====================
|
||||
|
||||
private loadTodosFromFile(filter?: {
|
||||
status?: string;
|
||||
priority?: string;
|
||||
assignedTo?: string;
|
||||
}): TodoItem[] {
|
||||
try {
|
||||
const data = fs.readFileSync(TODO_FILE, "utf-8");
|
||||
let todos: TodoItem[] = JSON.parse(data);
|
||||
|
||||
if (filter?.status) {
|
||||
todos = todos.filter((t) => t.status === filter.status);
|
||||
}
|
||||
if (filter?.priority) {
|
||||
todos = todos.filter((t) => t.priority === filter.priority);
|
||||
}
|
||||
if (filter?.assignedTo) {
|
||||
todos = todos.filter((t) => t.assignedTo === filter.assignedTo);
|
||||
}
|
||||
|
||||
return todos;
|
||||
} catch (error) {
|
||||
logger.error("❌ To-Do 파일 로드 오류:", error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private saveTodosToFile(todos: TodoItem[]): void {
|
||||
try {
|
||||
fs.writeFileSync(TODO_FILE, JSON.stringify(todos, null, 2));
|
||||
} catch (error) {
|
||||
logger.error("❌ To-Do 파일 저장 오류:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private updateTodoFile(id: string, updates: Partial<TodoItem>): TodoItem {
|
||||
const todos = this.loadTodosFromFile();
|
||||
const index = todos.findIndex((t) => t.id === id);
|
||||
|
||||
if (index === -1) {
|
||||
throw new Error(`To-Do 항목을 찾을 수 없습니다: ${id}`);
|
||||
}
|
||||
|
||||
const updatedTodo: TodoItem = {
|
||||
...todos[index],
|
||||
...updates,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
if (updates.status === "completed" && todos[index].status !== "completed") {
|
||||
updatedTodo.completedAt = new Date().toISOString();
|
||||
}
|
||||
|
||||
todos[index] = updatedTodo;
|
||||
this.saveTodosToFile(todos);
|
||||
|
||||
return updatedTodo;
|
||||
}
|
||||
|
||||
private deleteTodoFile(id: string): void {
|
||||
const todos = this.loadTodosFromFile();
|
||||
const filteredTodos = todos.filter((t) => t.id !== id);
|
||||
|
||||
if (todos.length === filteredTodos.length) {
|
||||
throw new Error(`To-Do 항목을 찾을 수 없습니다: ${id}`);
|
||||
}
|
||||
|
||||
this.saveTodosToFile(filteredTodos);
|
||||
}
|
||||
|
||||
private reorderTodosFile(todoIds: string[]): void {
|
||||
const todos = this.loadTodosFromFile();
|
||||
|
||||
todoIds.forEach((id, index) => {
|
||||
const todo = todos.find((t) => t.id === id);
|
||||
if (todo) {
|
||||
todo.order = index;
|
||||
todo.updatedAt = new Date().toISOString();
|
||||
}
|
||||
});
|
||||
|
||||
this.saveTodosToFile(todos);
|
||||
}
|
||||
|
||||
// ==================== 공통 메서드 ====================
|
||||
|
||||
private calculateStats(todos: TodoItem[]): TodoListResponse["stats"] {
|
||||
const now = new Date();
|
||||
return {
|
||||
total: todos.length,
|
||||
pending: todos.filter((t) => t.status === "pending").length,
|
||||
inProgress: todos.filter((t) => t.status === "in_progress").length,
|
||||
completed: todos.filter((t) => t.status === "completed").length,
|
||||
urgent: todos.filter((t) => t.isUrgent).length,
|
||||
overdue: todos.filter((t) => t.dueDate && new Date(t.dueDate) < now && t.status !== "completed").length,
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user