feat(tkuser): 알림 시스템 이관 system1-factory → tkuser

- Phase 1: tkuser에 알림 CRUD, Push/ntfy 발송, 내부 알림 API 추가
- Phase 2: notifyHelper URL을 tkuser-api:3000으로 전환 (system2, tkpurchase, tksafety, system1)
- Phase 3: notification-bell.js API 도메인 tkuser로 변경 + 캐시 버스팅 v=4
- Phase 4: system1에서 알림 코드 제거 (routes, controllers, models, utils)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Hyungi Ahn
2026-03-17 15:56:41 +09:00
parent afa10c044f
commit 84cf222b81
30 changed files with 244 additions and 172 deletions

View File

@@ -1,6 +1,6 @@
// models/equipmentModel.js
const { getDb } = require('../dbPool');
const notificationModel = require('./notificationModel');
const notifyHelper = require('../utils/notifyHelper');
const EquipmentModel = {
// CREATE - 설비 생성
@@ -669,17 +669,16 @@ const EquipmentModel = {
['repair_needed', requestData.equipment_id]
);
try {
await notificationModel.createRepairNotification({
equipment_id: requestData.equipment_id,
equipment_name: requestData.equipment_name || '설비',
repair_type: requestData.repair_type || '일반 수리',
request_id: result.insertId,
created_by: requestData.reported_by
});
} catch (notifError) {
// 알림 생성 실패해도 수리 신청은 성공으로 처리
}
// fire-and-forget: 알림 실패가 수리 신청을 블로킹하면 안 됨
notifyHelper.send({
type: 'repair',
title: `수리 신청: ${requestData.equipment_name || '설비'}`,
message: `${requestData.repair_type || '일반 수리'} 수리가 신청되었습니다.`,
link_url: '/pages/admin/repair-management.html',
reference_type: 'work_issue_reports',
reference_id: result.insertId,
created_by: requestData.reported_by
}).catch(() => {});
return {
report_id: result.insertId,

View File

@@ -1,324 +0,0 @@
// models/notificationModel.js
const { getDb } = require('../dbPool');
// Web Push (lazy init)
let webpush = null;
let vapidConfigured = false;
function getWebPush() {
if (!webpush) {
try {
webpush = require('web-push');
if (process.env.VAPID_PUBLIC_KEY && process.env.VAPID_PRIVATE_KEY) {
webpush.setVapidDetails(
process.env.VAPID_SUBJECT || 'mailto:admin@technicalkorea.net',
process.env.VAPID_PUBLIC_KEY,
process.env.VAPID_PRIVATE_KEY
);
vapidConfigured = true;
}
} catch (e) {
console.warn('[notifications] web-push 모듈 로드 실패:', e.message);
}
}
return vapidConfigured ? webpush : null;
}
// Push 전송 헬퍼 — 알림 생성 후 호출 (ntfy 우선, 나머지 Web Push)
async function sendPushToUsers(userIds, payload) {
const pushModel = require('./pushSubscriptionModel');
const { sendNtfy } = require('../utils/ntfySender');
try {
// 1) ntfy 구독자 분리
const ntfyUserIds = userIds && userIds.length > 0
? await pushModel.getNtfyUserIds(userIds)
: await pushModel.getAllNtfyUserIds();
const ntfySet = new Set(ntfyUserIds);
// 2) ntfy 병렬 발송
if (ntfyUserIds.length > 0) {
await Promise.allSettled(
ntfyUserIds.map(uid =>
sendNtfy(uid, { title: payload.title, body: payload.body, url: payload.url })
)
);
}
// 3) Web Push — ntfy 구독자 제외
const wp = getWebPush();
if (!wp) return;
let subscriptions;
if (userIds && userIds.length > 0) {
const webPushUserIds = userIds.filter(id => !ntfySet.has(id));
subscriptions = webPushUserIds.length > 0
? await pushModel.getByUserIds(webPushUserIds)
: [];
} else {
// broadcast: 전체 구독 가져온 뒤 ntfy 사용자 제외
subscriptions = (await pushModel.getAll()).filter(s => !ntfySet.has(s.user_id));
}
const payloadStr = JSON.stringify(payload);
for (const sub of subscriptions) {
try {
await wp.sendNotification({
endpoint: sub.endpoint,
keys: { p256dh: sub.p256dh, auth: sub.auth }
}, payloadStr);
} catch (err) {
if (err.statusCode === 410 || err.statusCode === 404) {
await pushModel.deleteByEndpoint(sub.endpoint).catch(() => {});
}
}
}
} catch (e) {
console.error('[notifications] Push 전송 오류:', e.message);
}
}
// 순환 참조를 피하기 위해 함수 내에서 require
async function getRecipientIds(notificationType) {
const db = await getDb();
const [rows] = await db.query(
`SELECT user_id FROM notification_recipients
WHERE notification_type = ? AND is_active = 1`,
[notificationType]
);
return rows.map(r => r.user_id);
}
const notificationModel = {
// 알림 생성
async create(notificationData) {
const db = await getDb();
const { user_id, type, title, message, link_url, reference_type, reference_id, created_by } = notificationData;
const [result] = await db.query(
`INSERT INTO notifications (user_id, type, title, message, link_url, reference_type, reference_id, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
[user_id || null, type || 'system', title, message || null, link_url || null, reference_type || null, reference_id || null, created_by || null]
);
// Redis 캐시 무효화
this._invalidateCache(user_id);
return result.insertId;
},
// 읽지 않은 알림 조회 (특정 사용자 또는 전체)
async getUnread(userId = null) {
const db = await getDb();
const [rows] = await db.query(
`SELECT * FROM notifications
WHERE is_read = 0
AND (user_id IS NULL OR user_id = ?)
ORDER BY created_at DESC
LIMIT 50`,
[userId || 0]
);
return rows;
},
// 전체 알림 조회 (페이징)
async getAll(userId = null, page = 1, limit = 20) {
const db = await getDb();
const offset = (page - 1) * limit;
const [rows] = await db.query(
`SELECT * FROM notifications
WHERE (user_id IS NULL OR user_id = ?)
ORDER BY created_at DESC
LIMIT ? OFFSET ?`,
[userId || 0, limit, offset]
);
const [[{ total }]] = await db.query(
`SELECT COUNT(*) as total FROM notifications
WHERE (user_id IS NULL OR user_id = ?)`,
[userId || 0]
);
return { notifications: rows, total, page, limit };
},
// 알림 읽음 처리
async markAsRead(notificationId) {
const db = await getDb();
// 읽음 처리 전 user_id 조회 (캐시 무효화용)
const [[row]] = await db.query('SELECT user_id FROM notifications WHERE notification_id = ?', [notificationId]);
const [result] = await db.query(
`UPDATE notifications SET is_read = 1, read_at = NOW() WHERE notification_id = ?`,
[notificationId]
);
if (row) this._invalidateCache(row.user_id);
return result.affectedRows > 0;
},
// 모든 알림 읽음 처리
async markAllAsRead(userId = null) {
const db = await getDb();
const [result] = await db.query(
`UPDATE notifications SET is_read = 1, read_at = NOW()
WHERE is_read = 0 AND (user_id IS NULL OR user_id = ?)`,
[userId || 0]
);
this._invalidateCache(userId);
return result.affectedRows;
},
// 알림 삭제
async delete(notificationId) {
const db = await getDb();
const [result] = await db.query(
`DELETE FROM notifications WHERE notification_id = ?`,
[notificationId]
);
return result.affectedRows > 0;
},
// 오래된 알림 삭제 (30일 이상)
async deleteOld(days = 30) {
const db = await getDb();
const [result] = await db.query(
`DELETE FROM notifications WHERE created_at < DATE_SUB(NOW(), INTERVAL ? DAY)`,
[days]
);
return result.affectedRows;
},
// 읽지 않은 알림 개수 (캐싱)
async getUnreadCount(userId = null) {
const cacheKey = `notif:unread:${userId || 0}`;
try {
const cache = require('../utils/cache');
const cached = await cache.get(cacheKey);
if (cached !== null && cached !== undefined) return cached;
} catch (e) { /* 무시 */ }
const db = await getDb();
const [[{ count }]] = await db.query(
`SELECT COUNT(*) as count FROM notifications
WHERE is_read = 0 AND (user_id IS NULL OR user_id = ?)`,
[userId || 0]
);
try {
const cache = require('../utils/cache');
await cache.set(cacheKey, count, 30); // TTL 30초
} catch (e) { /* 무시 */ }
return count;
},
// 캐시 무효화
_invalidateCache(userId) {
try {
const cache = require('../utils/cache');
cache.del(`notif:unread:${userId || 0}`).catch(() => {});
if (userId) cache.del('notif:unread:0').catch(() => {});
} catch (e) { /* 무시 */ }
},
// 수리 신청 알림 생성 헬퍼 (지정된 수신자에게 전송)
async createRepairNotification(repairData) {
const { equipment_id, equipment_name, repair_type, request_id, created_by } = repairData;
// 수리 알림 수신자 목록 가져오기
const recipientIds = await getRecipientIds('repair');
if (recipientIds.length === 0) {
// 수신자가 지정되지 않은 경우 전체 알림 (user_id = null)
const id = await this.create({
type: 'repair',
title: `수리 신청: ${equipment_name || '설비'}`,
message: `${repair_type} 수리가 신청되었습니다.`,
link_url: `/pages/admin/repair-management.html`,
reference_type: 'work_issue_reports',
reference_id: request_id,
created_by
});
// Push (broadcast)
sendPushToUsers([], {
title: `수리 신청: ${equipment_name || '설비'}`,
body: `${repair_type} 수리가 신청되었습니다.`,
url: `/pages/admin/repair-management.html`
});
return id;
}
// 지정된 수신자 각각에게 알림 생성
const results = [];
for (const userId of recipientIds) {
const notificationId = await this.create({
user_id: userId,
type: 'repair',
title: `수리 신청: ${equipment_name || '설비'}`,
message: `${repair_type} 수리가 신청되었습니다.`,
link_url: `/pages/admin/repair-management.html`,
reference_type: 'work_issue_reports',
reference_id: request_id,
created_by
});
results.push(notificationId);
}
// Push 전송
sendPushToUsers(recipientIds, {
title: `수리 신청: ${equipment_name || '설비'}`,
body: `${repair_type} 수리가 신청되었습니다.`,
url: `/pages/admin/repair-management.html`
});
return results;
},
// 일반 알림 생성 (유형별 지정된 수신자에게 전송)
async createTypedNotification(notificationData) {
const { type, title, message, link_url, reference_type, reference_id, created_by } = notificationData;
// 해당 유형의 수신자 목록 가져오기
const recipientIds = await getRecipientIds(type);
if (recipientIds.length === 0) {
// 수신자가 지정되지 않은 경우 전체 알림
const id = await this.create({
type,
title,
message,
link_url,
reference_type,
reference_id,
created_by
});
// Push (broadcast)
sendPushToUsers([], { title, body: message || '', url: link_url || '/' });
return id;
}
// 지정된 수신자 각각에게 알림 생성
const results = [];
for (const userId of recipientIds) {
const notificationId = await this.create({
user_id: userId,
type,
title,
message,
link_url,
reference_type,
reference_id,
created_by
});
results.push(notificationId);
}
// Push 전송
sendPushToUsers(recipientIds, { title, body: message || '', url: link_url || '/' });
return results;
}
};
module.exports = notificationModel;

View File

@@ -92,19 +92,15 @@ const PurchaseModel = {
} catch (err) {
console.error('[purchase] 설비 자동 등록 실패:', err.message);
// admin 알림 전송
try {
const notificationModel = require('./notificationModel');
await notificationModel.createTypedNotification({
type: 'equipment',
title: `설비 자동 등록 실패: ${purchaseData.item_name}`,
message: `구매 완료 후 설비 자동 등록에 실패했습니다. 수동으로 등록해주세요. 오류: ${err.message}`,
link_url: '/pages/admin/equipments.html',
created_by: purchaseData.purchaser_id
});
} catch (notifErr) {
console.error('[purchase] 설비 등록 실패 알림 전송 오류:', notifErr.message);
}
// fire-and-forget: admin 알림 전송
const notifyHelper = require('../utils/notifyHelper');
notifyHelper.send({
type: 'equipment',
title: `설비 자동 등록 실패: ${purchaseData.item_name}`,
message: `구매 완료 후 설비 자동 등록 실패했습니다. 수동으로 등록해주세요. 오류: ${err.message}`,
link_url: '/pages/admin/equipments.html',
created_by: purchaseData.purchaser_id
}).catch(() => {});
return { success: false, error: err.message };
}

View File

@@ -1,92 +0,0 @@
// models/pushSubscriptionModel.js
const { getDb } = require('../dbPool');
const pushSubscriptionModel = {
async subscribe(userId, subscription) {
const db = await getDb();
const { endpoint, keys } = subscription;
await db.query(
`INSERT INTO push_subscriptions (user_id, endpoint, p256dh, auth)
VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE user_id = VALUES(user_id), p256dh = VALUES(p256dh), auth = VALUES(auth)`,
[userId, endpoint, keys.p256dh, keys.auth]
);
},
async unsubscribe(endpoint) {
const db = await getDb();
await db.query('DELETE FROM push_subscriptions WHERE endpoint = ?', [endpoint]);
},
async getByUserId(userId) {
const db = await getDb();
const [rows] = await db.query(
'SELECT * FROM push_subscriptions WHERE user_id = ?',
[userId]
);
return rows;
},
async getByUserIds(userIds) {
if (!userIds || userIds.length === 0) return [];
const db = await getDb();
const [rows] = await db.query(
'SELECT * FROM push_subscriptions WHERE user_id IN (?)',
[userIds]
);
return rows;
},
async getAll() {
const db = await getDb();
const [rows] = await db.query('SELECT * FROM push_subscriptions');
return rows;
},
async deleteByEndpoint(endpoint) {
const db = await getDb();
await db.query('DELETE FROM push_subscriptions WHERE endpoint = ?', [endpoint]);
},
// === ntfy 구독 관련 ===
async getNtfyUserIds(userIds) {
if (!userIds || userIds.length === 0) return [];
const db = await getDb();
const [rows] = await db.query(
'SELECT user_id FROM ntfy_subscriptions WHERE user_id IN (?)',
[userIds]
);
return rows.map(r => r.user_id);
},
async getAllNtfyUserIds() {
const db = await getDb();
const [rows] = await db.query('SELECT user_id FROM ntfy_subscriptions');
return rows.map(r => r.user_id);
},
async ntfySubscribe(userId) {
const db = await getDb();
await db.query(
'INSERT IGNORE INTO ntfy_subscriptions (user_id) VALUES (?)',
[userId]
);
},
async ntfyUnsubscribe(userId) {
const db = await getDb();
await db.query('DELETE FROM ntfy_subscriptions WHERE user_id = ?', [userId]);
},
async isNtfySubscribed(userId) {
const db = await getDb();
const [rows] = await db.query(
'SELECT 1 FROM ntfy_subscriptions WHERE user_id = ? LIMIT 1',
[userId]
);
return rows.length > 0;
}
};
module.exports = pushSubscriptionModel;