Compare commits
20 Commits
8a3727ea61
...
HW_Dashboa
| Author | SHA1 | Date | |
|---|---|---|---|
| f656f0a439 | |||
| 1d32a0350b | |||
| abc531a41e | |||
| 8451101325 | |||
| 3e69e74bc9 | |||
| 723c4723f6 | |||
| a44283281f | |||
| fa87f383e2 | |||
| 6118141f6e | |||
| 05e23883b8 | |||
| 8c406fd0b8 | |||
| e678f9d653 | |||
| 132e37d0d3 | |||
| d6e75f8b2c | |||
| c35f57acab | |||
| 97cecb8b50 | |||
| a4b620099c | |||
| 407b9ba531 | |||
| 55c43aa250 | |||
| 9186eb50ca |
30
index.html
30
index.html
@@ -19,36 +19,6 @@
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<!-- Login Screen -->
|
||||
<div id="login-container" class="login-layout">
|
||||
<div class="login-card">
|
||||
<div class="login-header">
|
||||
<img src="/image 92.png" alt="Logo" class="login-logo" />
|
||||
<h2>ITAM 시스템</h2>
|
||||
<p>자산 관리 포털에 오신 것을 환영합니다</p>
|
||||
</div>
|
||||
<div id="login-selection" class="login-selection">
|
||||
<div class="role-card" data-role="admin">
|
||||
<div class="role-icon">
|
||||
<i data-lucide="settings"></i>
|
||||
</div>
|
||||
<h3>관리자</h3>
|
||||
<p>시스템 설정 및 자산 마스터 관리</p>
|
||||
</div>
|
||||
<div class="role-card" data-role="user">
|
||||
<div class="role-icon">
|
||||
<i data-lucide="monitor"></i>
|
||||
</div>
|
||||
<h3>실무자</h3>
|
||||
<p>자산 조회 및 현황 확인</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="login-footer">
|
||||
<p>© 2026 BARON Consultant Co,Ltd. All rights reserved.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="app-layout" id="app-layout" style="display: none;">
|
||||
<!-- Single-Line Integrated Header -->
|
||||
<header class="main-header">
|
||||
|
||||
177
server.js
177
server.js
@@ -28,6 +28,32 @@ const pool = mysql.createPool({
|
||||
queueLimit: 0
|
||||
});
|
||||
|
||||
// Database startup check (ensure job_spec_standards table exists)
|
||||
(async () => {
|
||||
let connection;
|
||||
try {
|
||||
connection = await pool.getConnection();
|
||||
await connection.query(`
|
||||
CREATE TABLE IF NOT EXISTS job_spec_standards (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
job_name VARCHAR(100) UNIQUE NOT NULL,
|
||||
cpu_standard VARCHAR(255),
|
||||
ram_standard VARCHAR(100),
|
||||
gpu_standard VARCHAR(100),
|
||||
min_score INT DEFAULT 0,
|
||||
remarks TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
`);
|
||||
console.log('✅ job_spec_standards table verification completed.');
|
||||
} catch (err) {
|
||||
console.error('❌ Failed to verify/create job_spec_standards table:', err);
|
||||
} finally {
|
||||
if (connection) connection.release();
|
||||
}
|
||||
})();
|
||||
|
||||
// Error Handler
|
||||
const handleError = (res, err, label) => {
|
||||
console.error(`❌ [${label}] Error:`, err);
|
||||
@@ -36,25 +62,24 @@ const handleError = (res, err, label) => {
|
||||
|
||||
// --- Global Constants ---
|
||||
const CATEGORY_TABLE_MAP = {
|
||||
pc: 'asset_pc',
|
||||
server: 'asset_server',
|
||||
storage: 'asset_storage',
|
||||
network: 'asset_remote',
|
||||
equipment: 'asset_equipment',
|
||||
officeSupplies: 'asset_office_supplies',
|
||||
survey: 'asset_survey',
|
||||
vip: 'asset_vip',
|
||||
swInternal: 'sw_internal',
|
||||
swExternal: 'sw_external',
|
||||
cloud: 'asset_cloud',
|
||||
pc: 'asset_core',
|
||||
server: 'asset_core',
|
||||
storage: 'asset_core',
|
||||
network: 'asset_core',
|
||||
equipment: 'asset_core',
|
||||
officeSupplies: 'asset_core',
|
||||
survey: 'asset_core',
|
||||
vip: 'asset_core',
|
||||
pcParts: 'asset_core',
|
||||
swInternal: 'asset_software_perpetual',
|
||||
swExternal: 'asset_software_subscription',
|
||||
swUsers: 'asset_software_assignment',
|
||||
users: 'system_users',
|
||||
swUsers: 'sw_assignment',
|
||||
logs: 'asset_history'
|
||||
};
|
||||
|
||||
const ASSET_TABLES = [
|
||||
'asset_pc', 'asset_server', 'asset_storage', 'asset_remote',
|
||||
'asset_equipment', 'asset_office_supplies', 'asset_survey', 'asset_vip'
|
||||
'asset_core'
|
||||
];
|
||||
|
||||
// --- API Endpoints ---
|
||||
@@ -101,8 +126,9 @@ app.post('/api/:table/batch', async (req, res) => {
|
||||
|
||||
// 2. Get All Assets (Integrated Master Data from Normalized V3 Schema)
|
||||
app.get('/api/assets/master', async (req, res) => {
|
||||
let connection;
|
||||
try {
|
||||
const connection = await pool.getConnection();
|
||||
connection = await pool.getConnection();
|
||||
|
||||
const masterData = {
|
||||
pc: [], server: [], storage: [], network: [],
|
||||
@@ -110,6 +136,7 @@ app.get('/api/assets/master', async (req, res) => {
|
||||
swInternal: [], swExternal: [], swUsers: [], users: [], logs: [], partsMaster: []
|
||||
};
|
||||
|
||||
// Load from V3 Normalized Schema
|
||||
const [rows] = await connection.query(`
|
||||
SELECT
|
||||
c.*,
|
||||
@@ -150,6 +177,7 @@ app.get('/api/assets/master', async (req, res) => {
|
||||
const [users] = await connection.query('SELECT * FROM system_users');
|
||||
const [logs] = await connection.query('SELECT * FROM asset_history ORDER BY created_at DESC');
|
||||
const [partsMaster] = await connection.query('SELECT * FROM hardware_components_master ORDER BY category, component_name');
|
||||
const [jobSpecs] = await connection.query('SELECT * FROM job_spec_standards ORDER BY job_name');
|
||||
|
||||
masterData.swInternal = swInternal;
|
||||
masterData.swExternal = swExternal;
|
||||
@@ -157,11 +185,13 @@ app.get('/api/assets/master', async (req, res) => {
|
||||
masterData.users = users;
|
||||
masterData.logs = logs;
|
||||
masterData.partsMaster = partsMaster;
|
||||
masterData.jobSpecs = jobSpecs;
|
||||
|
||||
connection.release();
|
||||
res.json(masterData);
|
||||
} catch (err) {
|
||||
handleError(res, err, 'MASTER DATA');
|
||||
} finally {
|
||||
if (connection) connection.release();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -179,15 +209,11 @@ app.post('/api/asset/:category/save', async (req, res) => {
|
||||
const oldCore = oldCoreRows[0] || {};
|
||||
const oldSpec = oldSpecRows[0] || {};
|
||||
|
||||
console.log(`🔍 [History Check] ID: ${asset.id}`);
|
||||
console.log(` - Dept: [${oldCore.current_dept}] -> [${asset.current_dept}]`);
|
||||
console.log(` - User: [${oldCore.user_current}] -> [${asset.user_current}]`);
|
||||
|
||||
const historyLogs = [];
|
||||
const logDate = new Date().toISOString().split('T')[0]; // YYYY-MM-DD
|
||||
const logUser = '관리자';
|
||||
|
||||
// 조직 변동 감지 (null/undefined/empty string 세이프 처리)
|
||||
// 3.0.1 Core 변동 감지 (Dept, User)
|
||||
const oldDept = oldCore.current_dept || '';
|
||||
const newDept = asset.current_dept || '';
|
||||
if (newDept !== '' && oldDept !== newDept) {
|
||||
@@ -200,7 +226,6 @@ app.post('/api/asset/:category/save', async (req, res) => {
|
||||
});
|
||||
}
|
||||
|
||||
// 사용자 변동 감지
|
||||
const oldUser = oldCore.user_current || '';
|
||||
const newUser = asset.user_current || '';
|
||||
if (newUser !== '' && oldUser !== newUser) {
|
||||
@@ -213,26 +238,27 @@ app.post('/api/asset/:category/save', async (req, res) => {
|
||||
});
|
||||
}
|
||||
|
||||
// 유형/용도 변경 감지
|
||||
const oldType = oldCore.asset_type || '';
|
||||
const newType = asset.asset_type || '';
|
||||
if (newType !== '' && oldType !== newType) {
|
||||
historyLogs.push({
|
||||
event_type: 'ROLE_CHANGE',
|
||||
details: `[유형 변경] ${oldType || '(없음)'} -> ${newType}`
|
||||
});
|
||||
}
|
||||
// 3.0.2 Spec 변동 감지 (CPU, RAM, GPU, OS, Mainboard 등)
|
||||
const specFieldsToTrack = [
|
||||
{ key: 'cpu', label: 'CPU' },
|
||||
{ key: 'ram', label: 'RAM' },
|
||||
{ key: 'gpu', label: 'GPU' },
|
||||
{ key: 'os', label: 'OS' },
|
||||
{ key: 'mainboard', label: '메인보드' }
|
||||
];
|
||||
|
||||
const oldRole = oldCore.current_role || '';
|
||||
const newRole = asset.current_role || '';
|
||||
if (newRole !== '' && oldRole !== newRole) {
|
||||
historyLogs.push({
|
||||
event_type: 'ROLE_CHANGE',
|
||||
details: `[용도 변경] ${oldRole || '(없음)'} -> ${newRole}`
|
||||
});
|
||||
}
|
||||
specFieldsToTrack.forEach(field => {
|
||||
const oldVal = String(oldSpec[field.key] || '').trim();
|
||||
const newVal = String(asset[field.key] || '').trim();
|
||||
if (newVal !== '' && oldVal !== newVal) {
|
||||
historyLogs.push({
|
||||
event_type: 'SPEC_CHANGE',
|
||||
details: `[사양 변경] ${field.label}: ${oldVal || '(없음)'} -> ${newVal}`
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// 상태 변경 감지
|
||||
// 3.0.3 상태 변경 감지
|
||||
const oldStatus = oldSpec.hw_status || '';
|
||||
const newStatus = asset.hw_status || '';
|
||||
if (newStatus !== '' && oldStatus !== newStatus) {
|
||||
@@ -242,8 +268,6 @@ app.post('/api/asset/:category/save', async (req, res) => {
|
||||
});
|
||||
}
|
||||
|
||||
console.log(` - Logs Generated: ${historyLogs.length}`);
|
||||
|
||||
// 로그 일괄 삽입
|
||||
for (const log of historyLogs) {
|
||||
await connection.query(
|
||||
@@ -258,8 +282,23 @@ app.post('/api/asset/:category/save', async (req, res) => {
|
||||
const coreData = {};
|
||||
coreFields.forEach(f => { if (asset[f] !== undefined) coreData[f] = asset[f]; });
|
||||
const coreKeys = Object.keys(coreData);
|
||||
const coreSql = `INSERT INTO asset_core (${coreKeys.join(', ')}) VALUES (${coreKeys.map(() => '?').join(', ')}) ON DUPLICATE KEY UPDATE ${coreKeys.map(k => `${k} = VALUES(${k})`).join(', ')}`;
|
||||
await connection.query(coreSql, Object.values(coreData));
|
||||
|
||||
console.log(`[DEBUG] Saving Asset ID: ${asset.id}, Code: ${asset.asset_code}`);
|
||||
const [existingCore] = await connection.query('SELECT id FROM asset_core WHERE id = ?', [asset.id]);
|
||||
console.log(`[DEBUG] Existing Core Check for ${asset.id}: Found ${existingCore.length}`);
|
||||
|
||||
if (existingCore.length > 0) {
|
||||
// UPDATE
|
||||
const updateKeys = coreKeys.filter(k => k !== 'id');
|
||||
const coreSql = `UPDATE asset_core SET ${updateKeys.map(k => `${k} = ?`).join(', ')} WHERE id = ?`;
|
||||
const [updRes] = await connection.query(coreSql, [...updateKeys.map(k => coreData[k]), asset.id]);
|
||||
console.log(`[DEBUG] Core UPDATE result: affectedRows=${updRes.affectedRows}`);
|
||||
} else {
|
||||
// INSERT
|
||||
const coreSql = `INSERT INTO asset_core (${coreKeys.join(', ')}) VALUES (${coreKeys.map(() => '?').join(', ')})`;
|
||||
const [insRes] = await connection.query(coreSql, Object.values(coreData));
|
||||
console.log(`[DEBUG] Core INSERT result: affectedRows=${insRes.affectedRows}`);
|
||||
}
|
||||
|
||||
// 3.2 asset_spec
|
||||
const specFields = ['hw_status', 'model_name', 'mainboard', 'os', 'cpu', 'ram', 'gpu', 'monitoring', 'price', 'monitor_inch', 'serial_num'];
|
||||
@@ -535,6 +574,56 @@ app.delete('/api/hardware-components/:id', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// 6.7.1. Get Job Spec Standards
|
||||
app.get('/api/job-specs', async (req, res) => {
|
||||
try {
|
||||
const [rows] = await pool.query('SELECT * FROM job_spec_standards ORDER BY job_name');
|
||||
res.json(rows);
|
||||
} catch (err) {
|
||||
handleError(res, err, 'GET JOB SPECS');
|
||||
}
|
||||
});
|
||||
|
||||
// 6.7.2. Save Job Spec Standard (Add or Update)
|
||||
app.post('/api/job-specs/save', async (req, res) => {
|
||||
const { id, job_name, cpu_standard, ram_standard, gpu_standard, min_score, remarks } = req.body;
|
||||
let connection;
|
||||
try {
|
||||
connection = await pool.getConnection();
|
||||
if (id) {
|
||||
await connection.query(
|
||||
'UPDATE job_spec_standards SET job_name = ?, cpu_standard = ?, ram_standard = ?, gpu_standard = ?, min_score = ?, remarks = ? WHERE id = ?',
|
||||
[job_name, cpu_standard, ram_standard, gpu_standard, min_score, remarks, id]
|
||||
);
|
||||
} else {
|
||||
await connection.query(
|
||||
'INSERT INTO job_spec_standards (job_name, cpu_standard, ram_standard, gpu_standard, min_score, remarks) VALUES (?, ?, ?, ?, ?, ?)',
|
||||
[job_name, cpu_standard, ram_standard, gpu_standard, min_score, remarks]
|
||||
);
|
||||
}
|
||||
res.json({ success: true });
|
||||
} catch (err) {
|
||||
handleError(res, err, 'SAVE JOB SPEC');
|
||||
} finally {
|
||||
if (connection) connection.release();
|
||||
}
|
||||
});
|
||||
|
||||
// 6.7.3. Delete Job Spec Standard
|
||||
app.delete('/api/job-specs/:id', async (req, res) => {
|
||||
const { id } = req.params;
|
||||
let connection;
|
||||
try {
|
||||
connection = await pool.getConnection();
|
||||
await connection.query('DELETE FROM job_spec_standards WHERE id = ?', [id]);
|
||||
res.json({ success: true });
|
||||
} catch (err) {
|
||||
handleError(res, err, 'DELETE JOB SPEC');
|
||||
} finally {
|
||||
if (connection) connection.release();
|
||||
}
|
||||
});
|
||||
|
||||
// 6.8. Get System Users List
|
||||
app.get('/api/system-users', async (req, res) => {
|
||||
try {
|
||||
|
||||
@@ -324,10 +324,21 @@ class HwAssetModal extends BaseModal {
|
||||
});
|
||||
|
||||
document.getElementById('btn-gen-hw-code')?.addEventListener('click', async () => {
|
||||
const type = typeSelect.value;
|
||||
const cat = categorySelect.value;
|
||||
if (!cat) { alert('구분을 먼저 선택해주세요.'); return; }
|
||||
const prefix = TYPE_PREFIX_MAP[cat] || 'ETC';
|
||||
const purchaseDate = (document.getElementById('hw-purchase_date') as HTMLInputElement)?.value || '';
|
||||
if (!type) { alert('유형을 먼저 선택해주세요.'); return; }
|
||||
|
||||
const purchaseDateEl = document.getElementById('hw-purchase_date') as HTMLInputElement;
|
||||
const purchaseDate = purchaseDateEl?.value || '';
|
||||
|
||||
if (!purchaseDate) {
|
||||
alert('구매일자를 먼저 입력해야 자산번호 생성이 가능합니다.');
|
||||
purchaseDateEl?.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
// 유형 기반 매핑 우선, 없으면 구분 기반, 그래도 없으면 ETC
|
||||
const prefix = TYPE_PREFIX_MAP[type] || TYPE_PREFIX_MAP[cat] || 'ETC';
|
||||
try {
|
||||
const res = await fetch(`http://${location.hostname}:3000/api/generate-asset-code?prefix=${prefix}&purchaseDate=${purchaseDate}`);
|
||||
const data = await res.json();
|
||||
@@ -776,29 +787,110 @@ class HwAssetModal extends BaseModal {
|
||||
overlay.className = 'image-picker-overlay';
|
||||
const renderContent = () => {
|
||||
const imgPath = imagePaths[currentIdx];
|
||||
const digitalMap = this.generateDynamicSVG(imgPath);
|
||||
const isMulti = imagePaths.length > 1;
|
||||
const isHtmlMap = imgPath.toLowerCase().endsWith('.html');
|
||||
const digitalMap = isHtmlMap ? '' : this.generateDynamicSVG(imgPath);
|
||||
|
||||
overlay.innerHTML = `
|
||||
<div class="image-picker-header"><h3>${title}</h3><button class="btn-close-picker" style="background:none; border:none; color:white; font-size:24px; cursor:pointer;">×</button></div>
|
||||
<div class="image-picker-content"><div class="layout-map-container" id="picker-container"><img src="${imgPath}" class="layout-map-img" /><div id="picker-marker" class="layout-marker hidden"></div><div class="digital-overlay-layer">${digitalMap}</div></div></div>
|
||||
<div class="image-picker-header">
|
||||
<h3>${title} ${isMulti ? `(${currentIdx + 1}/${imagePaths.length})` : ''}</h3>
|
||||
<button class="btn-close-picker" style="background:none; border:none; color:white; font-size:24px; cursor:pointer;">×</button>
|
||||
</div>
|
||||
<div class="image-picker-content">
|
||||
${isMulti ? `
|
||||
<div class="picker-nav prev ${currentIdx === 0 ? 'disabled' : ''}" style="position: absolute; left: 10px; top: 50%; transform: translateY(-50%); z-index: 100; cursor: pointer; background: rgba(0,0,0,0.5); color: white; padding: 20px 10px; border-radius: 5px; font-size: 24px; user-select: none;">◀</div>
|
||||
<div class="picker-nav next ${currentIdx === imagePaths.length - 1 ? 'disabled' : ''}" style="position: absolute; right: 10px; top: 50%; transform: translateY(-50%); z-index: 100; cursor: pointer; background: rgba(0,0,0,0.5); color: white; padding: 20px 10px; border-radius: 5px; font-size: 24px; user-select: none;">▶</div>
|
||||
` : ''}
|
||||
<div class="layout-map-container" id="picker-container">
|
||||
${isHtmlMap
|
||||
? `<iframe src="${imgPath}" style="width:100%; height:100%; border:none; display:block;"></iframe>`
|
||||
: `<img src="${imgPath}" class="layout-map-img" /><div id="picker-marker" class="layout-marker hidden"></div><div class="digital-overlay-layer">${digitalMap}</div>`
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<div class="image-picker-footer"><button id="btn-picker-cancel" class="btn btn-outline" style="color:white; border-color:white;">취소</button><button id="btn-picker-save" class="btn btn-primary">위치 확정</button></div>`;
|
||||
|
||||
let selectedX = ''; let selectedY = '';
|
||||
const container = overlay.querySelector('#picker-container') as HTMLElement;
|
||||
const marker = overlay.querySelector('#picker-marker') as HTMLElement;
|
||||
container.addEventListener('click', (e) => {
|
||||
const rect = container.getBoundingClientRect();
|
||||
const x = ((e.clientX - rect.left) / rect.width) * 100;
|
||||
const y = ((e.clientY - rect.top) / rect.height) * 100;
|
||||
selectedX = x.toFixed(2); selectedY = y.toFixed(2);
|
||||
marker.style.left = `${selectedX}%`; marker.style.top = `${selectedY}%`; marker.classList.remove('hidden');
|
||||
});
|
||||
overlay.querySelector('.btn-close-picker')?.addEventListener('click', () => overlay.remove());
|
||||
overlay.querySelector('#btn-picker-cancel')?.addEventListener('click', () => overlay.remove());
|
||||
overlay.querySelector('#btn-picker-save')?.addEventListener('click', () => {
|
||||
if (!selectedX || !selectedY) { alert('위치를 선택해주세요.'); return; }
|
||||
setFieldValue('hw-loc_x', selectedX); setFieldValue('hw-loc_y', selectedY);
|
||||
setFieldValue('hw-location_photo', imagePaths[currentIdx]);
|
||||
this.updateMapButtonVisibility(); overlay.remove();
|
||||
});
|
||||
|
||||
if (isMulti) {
|
||||
overlay.querySelector('.picker-nav.prev')?.addEventListener('click', (e) => { e.stopPropagation(); if (currentIdx > 0) { currentIdx--; renderContent(); } });
|
||||
overlay.querySelector('.picker-nav.next')?.addEventListener('click', (e) => { e.stopPropagation(); if (currentIdx < imagePaths.length - 1) { currentIdx++; renderContent(); } });
|
||||
}
|
||||
|
||||
if (isHtmlMap) {
|
||||
// HTML 지도 메시지 리스너
|
||||
const handleMessage = (e: MessageEvent) => {
|
||||
if (e.data.type === 'PICK_LOCATION') {
|
||||
selectedX = e.data.x;
|
||||
selectedY = e.data.y;
|
||||
}
|
||||
};
|
||||
window.addEventListener('message', handleMessage);
|
||||
overlay.querySelector('.btn-close-picker')?.addEventListener('click', () => { window.removeEventListener('message', handleMessage); overlay.remove(); });
|
||||
overlay.querySelector('#btn-picker-cancel')?.addEventListener('click', () => { window.removeEventListener('message', handleMessage); overlay.remove(); });
|
||||
overlay.querySelector('#btn-picker-save')?.addEventListener('click', () => {
|
||||
if (!selectedX || !selectedY) { alert('위치를 선택해주세요.'); return; }
|
||||
setFieldValue('hw-loc_x', selectedX); setFieldValue('hw-loc_y', selectedY);
|
||||
setFieldValue('hw-location_photo', imagePaths[currentIdx]);
|
||||
this.updateMapButtonVisibility();
|
||||
window.removeEventListener('message', handleMessage);
|
||||
overlay.remove();
|
||||
});
|
||||
} else {
|
||||
const container = overlay.querySelector('#picker-container') as HTMLElement;
|
||||
const marker = overlay.querySelector('#picker-marker') as HTMLElement;
|
||||
container.addEventListener('click', (e) => {
|
||||
const rectBound = container.getBoundingClientRect();
|
||||
const clickX = ((e.clientX - rectBound.left) / rectBound.width) * 100;
|
||||
const clickY = ((e.clientY - rectBound.top) / rectBound.height) * 100;
|
||||
|
||||
let snapped = false;
|
||||
overlay.querySelectorAll('rect').forEach(rect => {
|
||||
const rx = parseFloat(rect.getAttribute('x') || '0');
|
||||
const ry = parseFloat(rect.getAttribute('y') || '0');
|
||||
const rw = parseFloat(rect.getAttribute('width') || '0');
|
||||
const rh = parseFloat(rect.getAttribute('height') || '0');
|
||||
|
||||
if (clickX >= rx && clickX <= rx + rw && clickY >= ry && clickY <= ry + rh) {
|
||||
overlay.querySelectorAll('rect').forEach(r => {
|
||||
r.style.fill = 'rgba(30,81,73,0.05)';
|
||||
r.style.stroke = 'rgba(30,81,73,0.2)';
|
||||
r.style.strokeWidth = '0.2';
|
||||
});
|
||||
rect.style.fill = 'rgba(255, 61, 0, 0.4)';
|
||||
rect.style.stroke = '#FF3D00';
|
||||
rect.style.strokeWidth = '0.8';
|
||||
|
||||
selectedX = rx.toFixed(2);
|
||||
selectedY = ry.toFixed(2);
|
||||
|
||||
marker.style.left = `${rx + rw/2}%`;
|
||||
marker.style.top = `${ry + rh/2}%`;
|
||||
marker.classList.remove('hidden');
|
||||
snapped = true;
|
||||
}
|
||||
});
|
||||
|
||||
if (!snapped) {
|
||||
selectedX = '';
|
||||
selectedY = '';
|
||||
marker.classList.add('hidden');
|
||||
overlay.querySelectorAll('rect').forEach(r => {
|
||||
r.style.fill = 'rgba(30,81,73,0.05)';
|
||||
r.style.stroke = 'rgba(30,81,73,0.2)';
|
||||
r.style.strokeWidth = '0.2';
|
||||
});
|
||||
}
|
||||
});
|
||||
overlay.querySelector('.btn-close-picker')?.addEventListener('click', () => overlay.remove());
|
||||
overlay.querySelector('#btn-picker-cancel')?.addEventListener('click', () => overlay.remove());
|
||||
overlay.querySelector('#btn-picker-save')?.addEventListener('click', () => {
|
||||
if (!selectedX || !selectedY) { alert('위치를 선택해주세요.'); return; }
|
||||
setFieldValue('hw-loc_x', selectedX); setFieldValue('hw-loc_y', selectedY);
|
||||
setFieldValue('hw-location_photo', imagePaths[currentIdx]);
|
||||
this.updateMapButtonVisibility(); overlay.remove();
|
||||
});
|
||||
}
|
||||
};
|
||||
renderContent(); document.body.appendChild(overlay);
|
||||
}
|
||||
@@ -806,13 +898,26 @@ class HwAssetModal extends BaseModal {
|
||||
private openImagePreview(imagePath: string, title: string, x: string, y: string) {
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'image-picker-overlay';
|
||||
const digitalMap = this.generateDynamicSVG(imagePath);
|
||||
const isHtmlMap = imagePath.toLowerCase().endsWith('.html');
|
||||
const digitalMap = isHtmlMap ? '' : this.generateDynamicSVG(imagePath);
|
||||
|
||||
// HTML 지도인 경우 좌표를 쿼리 파라미터로 전달
|
||||
const finalPath = isHtmlMap ? `${imagePath}?markerX=${x}&markerY=${y}` : imagePath;
|
||||
|
||||
overlay.innerHTML = `
|
||||
<div class="image-picker-header"><h3>${title}</h3><button class="btn-close-picker" style="background:none; border:none; color:white; font-size:24px; cursor:pointer;">×</button></div>
|
||||
<div class="image-picker-content"><div class="layout-map-container readonly"><img src="${imagePath}" class="layout-map-img" /><div id="preview-marker" class="layout-marker pulse-marker" style="left:${x}%; top:${y}%;"></div><div class="digital-overlay-layer">${digitalMap}</div></div></div>
|
||||
<div class="image-picker-content">
|
||||
<div class="layout-map-container readonly">
|
||||
${isHtmlMap
|
||||
? `<iframe src="${finalPath}" style="width:100%; height:100%; border:none; display:block;"></iframe>`
|
||||
: `<img src="${imagePath}" class="layout-map-img" /><div id="preview-marker" class="layout-marker pulse-marker" style="left:${x}%; top:${y}%;"></div><div class="digital-overlay-layer">${digitalMap}</div>`
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<div class="image-picker-footer"><button id="btn-preview-close" class="btn btn-primary">확인</button></div>`;
|
||||
|
||||
document.body.appendChild(overlay);
|
||||
if (digitalMap) {
|
||||
if (!isHtmlMap && digitalMap) {
|
||||
const curX = parseFloat(x || '0'); const curY = parseFloat(y || '0');
|
||||
overlay.querySelectorAll('rect').forEach(rect => {
|
||||
const sx = parseFloat(rect.getAttribute('x') || '0');
|
||||
|
||||
284
src/components/Modal/JobSpecModal.ts
Normal file
284
src/components/Modal/JobSpecModal.ts
Normal file
@@ -0,0 +1,284 @@
|
||||
import { state, saveJobSpec, deleteJobSpec } from '../../core/state';
|
||||
import { BaseModal } from './BaseModal';
|
||||
import { setFieldValue } from './ModalUtils';
|
||||
import { UI_TEXT } from '../../core/schema';
|
||||
import { calculatePcScoreDeductive } from '../../core/utils';
|
||||
|
||||
class JobSpecModal extends BaseModal {
|
||||
constructor() {
|
||||
super('job-spec', '직무별 기준 사양');
|
||||
}
|
||||
|
||||
protected renderFrameHTML(): string {
|
||||
const sharedStyle = 'height: 38px !important; box-sizing: border-box !important; font-size: 13px; margin: 0;';
|
||||
const inputStyle = sharedStyle;
|
||||
|
||||
return `
|
||||
<div id="job-spec-asset-modal" class="modal-overlay hidden">
|
||||
<style>
|
||||
.autocomplete-list {
|
||||
position: absolute;
|
||||
top: 100%;
|
||||
left: 0;
|
||||
right: 0;
|
||||
max-height: 150px;
|
||||
overflow-y: auto;
|
||||
background-color: white;
|
||||
border: 1px solid var(--border-color, #E2E8F0);
|
||||
border-top: none;
|
||||
border-radius: 0 0 4px 4px;
|
||||
z-index: 1000;
|
||||
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
.autocomplete-item {
|
||||
padding: 8px 12px;
|
||||
font-size: 13px;
|
||||
color: #334155;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.autocomplete-item:hover {
|
||||
background-color: #F1F5F9;
|
||||
color: #1E5149;
|
||||
font-weight: 600;
|
||||
}
|
||||
.hidden {
|
||||
display: none !important;
|
||||
}
|
||||
</style>
|
||||
<div class="modal-content" style="max-width: 500px; width: 100%;">
|
||||
<div class="modal-header">
|
||||
<h2 id="job-spec-modal-title" style="margin: 0; font-size: 18px; font-weight: 800; color: white;">\${this.title}</h2>
|
||||
<button id="btn-close-job-spec-modal" class="btn-icon" aria-label="닫기" style="font-size: 28px; color: white; background: none; border: none; cursor: pointer; line-height: 1;">×</button>
|
||||
</div>
|
||||
<div class="modal-body" style="padding: 24px; overflow-y: auto;">
|
||||
<form id="job-spec-asset-form" class="grid-form" style="display: flex; flex-direction: column; gap: 16px;">
|
||||
<input type="hidden" id="job-spec-id" name="id" />
|
||||
|
||||
<div class="form-group" style="display: flex; flex-direction: column; gap: 6px;">
|
||||
<label style="font-size: 11px; font-weight: 700; color: var(--text-muted);">직무명</label>
|
||||
<input type="text" id="job-spec-job-name" name="job_name" placeholder="예: BIM 모델러, 개발자, 엔지니어" required style="\${inputStyle} width: 100%;" />
|
||||
</div>
|
||||
|
||||
<div class="form-group" style="display: flex; flex-direction: column; gap: 6px; position: relative;">
|
||||
<label style="font-size: 11px; font-weight: 700; color: var(--text-muted);">권장 CPU 사양</label>
|
||||
<input type="text" id="job-spec-cpu-standard" name="cpu_standard" placeholder="CPU 검색..." required style="\${inputStyle} width: 100%;" autocomplete="off" />
|
||||
<div id="job-spec-cpu-autocomplete" class="autocomplete-list hidden"></div>
|
||||
</div>
|
||||
|
||||
<div class="form-group" style="display: flex; flex-direction: column; gap: 6px; position: relative;">
|
||||
<label style="font-size: 11px; font-weight: 700; color: var(--text-muted);">권장 RAM 사양</label>
|
||||
<input type="text" id="job-spec-ram-standard" name="ram_standard" placeholder="RAM 검색..." required style="\${inputStyle} width: 100%;" autocomplete="off" />
|
||||
<div id="job-spec-ram-autocomplete" class="autocomplete-list hidden"></div>
|
||||
</div>
|
||||
|
||||
<div class="form-group" style="display: flex; flex-direction: column; gap: 6px; position: relative;">
|
||||
<label style="font-size: 11px; font-weight: 700; color: var(--text-muted);">권장 GPU 사양</label>
|
||||
<input type="text" id="job-spec-gpu-standard" name="gpu_standard" placeholder="GPU 검색..." required style="\${inputStyle} width: 100%;" autocomplete="off" />
|
||||
<div id="job-spec-gpu-autocomplete" class="autocomplete-list hidden"></div>
|
||||
</div>
|
||||
|
||||
<div class="form-group" style="display: flex; flex-direction: column; gap: 6px;">
|
||||
<label style="font-size: 11px; font-weight: 700; color: var(--text-muted);">성능 기준 점수 (이상, 자동 계산됨)</label>
|
||||
<input type="number" id="job-spec-min-score" name="min_score" placeholder="자동 계산 대기..." required style="\${inputStyle} width: 100%;" readonly />
|
||||
</div>
|
||||
|
||||
<div class="form-group" style="display: flex; flex-direction: column; gap: 6px;">
|
||||
<label style="font-size: 11px; font-weight: 700; color: var(--text-muted);">비고 (메모)</label>
|
||||
<textarea id="job-spec-remarks" name="remarks" placeholder="기타 필요 사양 및 안내 사항" style="box-sizing: border-box !important; font-size: 13px; margin: 0; min-height: 80px; width: 100%; padding: 8px; border: 1px solid var(--border-color); border-radius: 4px; resize: vertical;"></textarea>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="modal-footer" style="display: flex; justify-content: space-between; align-items: center; padding: 16px 24px; background: #f8fafc; border-top: 1px solid var(--border-color);">
|
||||
<button id="btn-delete-job-spec-asset" class="btn btn-outline btn-danger" style="height: 42px;">삭제</button>
|
||||
<div class="footer-actions" style="display: flex; gap: 8px;">
|
||||
<button id="btn-revert-job-spec-edit" class="btn btn-outline hidden" style="height: 42px;">수정 취소</button>
|
||||
<button id="btn-cancel-job-spec-modal" class="btn btn-outline" style="height: 42px;">닫기</button>
|
||||
<button id="btn-save-job-spec-asset" class="btn btn-primary" style="height: 42px;">수정</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
protected initChildLogic(onSave: () => void, closeModals: () => void): void {
|
||||
const saveBtn = document.getElementById('btn-save-job-spec-asset')!;
|
||||
const revertBtn = document.getElementById('btn-revert-job-spec-edit')!;
|
||||
const deleteBtn = document.getElementById('btn-delete-job-spec-asset')!;
|
||||
|
||||
saveBtn.addEventListener('click', async () => {
|
||||
if (!this.currentAsset) return;
|
||||
if (!this.isEditMode) {
|
||||
this.setEditLockMode('edit');
|
||||
this.isEditMode = true;
|
||||
return;
|
||||
}
|
||||
|
||||
const jobName = (document.getElementById('job-spec-job-name') as HTMLInputElement).value.trim();
|
||||
const cpuStd = (document.getElementById('job-spec-cpu-standard') as HTMLInputElement).value.trim();
|
||||
const ramStd = (document.getElementById('job-spec-ram-standard') as HTMLInputElement).value.trim();
|
||||
const gpuStd = (document.getElementById('job-spec-gpu-standard') as HTMLInputElement).value.trim();
|
||||
const minScoreStr = (document.getElementById('job-spec-min-score') as HTMLInputElement).value;
|
||||
const remarks = (document.getElementById('job-spec-remarks') as HTMLTextAreaElement).value.trim();
|
||||
|
||||
if (!jobName) {
|
||||
alert('직무명을 입력해 주세요.');
|
||||
return;
|
||||
}
|
||||
|
||||
const updated = {
|
||||
id: this.currentAsset.id || null,
|
||||
job_name: jobName,
|
||||
cpu_standard: cpuStd,
|
||||
ram_standard: ramStd,
|
||||
gpu_standard: gpuStd,
|
||||
min_score: minScoreStr !== '' ? parseInt(minScoreStr, 10) : 0,
|
||||
remarks: remarks
|
||||
};
|
||||
|
||||
if (await saveJobSpec(updated)) {
|
||||
alert(UI_TEXT.MESSAGES.SAVE_SUCCESS);
|
||||
onSave(); this.close(); closeModals();
|
||||
}
|
||||
});
|
||||
|
||||
revertBtn.addEventListener('click', () => {
|
||||
this.setEditLockMode('view');
|
||||
if (this.currentAsset) this.fillFormData(this.currentAsset);
|
||||
});
|
||||
|
||||
deleteBtn.addEventListener('click', async () => {
|
||||
if (!this.currentAsset || !this.currentAsset.id) return;
|
||||
if (!confirm('정말로 이 직무별 기준 사양을 삭제하시겠습니까?')) return;
|
||||
|
||||
if (await deleteJobSpec(this.currentAsset.id)) {
|
||||
alert('성공적으로 삭제되었습니다.');
|
||||
onSave(); this.close(); closeModals();
|
||||
}
|
||||
});
|
||||
|
||||
// 자동완성 바인딩
|
||||
this.bindAutocomplete('job-spec-cpu-standard', 'job-spec-cpu-autocomplete', 'CPU');
|
||||
this.bindAutocomplete('job-spec-ram-standard', 'job-spec-ram-autocomplete', 'RAM');
|
||||
this.bindAutocomplete('job-spec-gpu-standard', 'job-spec-gpu-autocomplete', 'GPU');
|
||||
|
||||
// 실시간 점수 계산 이벤트 바인딩
|
||||
const inputs = ['job-spec-cpu-standard', 'job-spec-ram-standard', 'job-spec-gpu-standard'];
|
||||
inputs.forEach(id => {
|
||||
const el = document.getElementById(id);
|
||||
el?.addEventListener('input', () => this.updateMinScore());
|
||||
el?.addEventListener('change', () => this.updateMinScore());
|
||||
});
|
||||
}
|
||||
|
||||
private bindAutocomplete(inputId: string, autocompleteId: string, category: string) {
|
||||
const input = document.getElementById(inputId) as HTMLInputElement;
|
||||
const list = document.getElementById(autocompleteId) as HTMLDivElement;
|
||||
if (!input || !list) return;
|
||||
|
||||
const showList = (filterText: string = '') => {
|
||||
if (!this.isEditMode) return;
|
||||
const items = (state.masterData.partsMaster || []).filter((c: any) => c.category === category);
|
||||
const filtered = filterText
|
||||
? items.filter((c: any) => c.component_name.toLowerCase().includes(filterText.toLowerCase()))
|
||||
: items;
|
||||
|
||||
if (filtered.length === 0) {
|
||||
list.innerHTML = '<div class="autocomplete-item" style="color: #94a3b8; cursor: default;">검색 결과 없음</div>';
|
||||
} else {
|
||||
list.innerHTML = filtered.map((c: any) => `<div class="autocomplete-item" data-val="${c.component_name}">${c.component_name}</div>`).join('');
|
||||
}
|
||||
list.classList.remove('hidden');
|
||||
};
|
||||
|
||||
input.addEventListener('focus', () => {
|
||||
showList(input.value);
|
||||
});
|
||||
|
||||
input.addEventListener('input', () => {
|
||||
showList(input.value);
|
||||
});
|
||||
|
||||
list.addEventListener('mousedown', (e) => {
|
||||
const item = (e.target as HTMLElement).closest('.autocomplete-item');
|
||||
if (item && item.getAttribute('data-val')) {
|
||||
input.value = item.getAttribute('data-val') || '';
|
||||
list.classList.add('hidden');
|
||||
this.updateMinScore();
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener('mousedown', (e) => {
|
||||
if (e.target !== input && !list.contains(e.target as Node)) {
|
||||
list.classList.add('hidden');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private updateMinScore(): void {
|
||||
const cpu = (document.getElementById('job-spec-cpu-standard') as HTMLInputElement)?.value || '';
|
||||
const ram = (document.getElementById('job-spec-ram-standard') as HTMLInputElement)?.value || '';
|
||||
const gpu = (document.getElementById('job-spec-gpu-standard') as HTMLInputElement)?.value || '';
|
||||
|
||||
const score = calculatePcScoreDeductive(cpu, ram, gpu, '');
|
||||
|
||||
const minScoreEl = document.getElementById('job-spec-min-score') as HTMLInputElement;
|
||||
if (minScoreEl) {
|
||||
minScoreEl.value = score.toString();
|
||||
}
|
||||
}
|
||||
|
||||
protected fillFormData(asset: any): void {
|
||||
setFieldValue('job-spec-id', asset.id || '');
|
||||
setFieldValue('job-spec-job-name', asset.job_name || '');
|
||||
setFieldValue('job-spec-cpu-standard', asset.cpu_standard || '');
|
||||
setFieldValue('job-spec-ram-standard', asset.ram_standard || '');
|
||||
setFieldValue('job-spec-gpu-standard', asset.gpu_standard || '');
|
||||
setFieldValue('job-spec-min-score', asset.min_score !== undefined ? asset.min_score.toString() : '100');
|
||||
setFieldValue('job-spec-remarks', asset.remarks || '');
|
||||
}
|
||||
|
||||
protected onAfterOpen(asset: any, mode: string): void {
|
||||
const titleEl = document.getElementById('job-spec-modal-title');
|
||||
|
||||
if (titleEl) {
|
||||
if (mode === 'add') {
|
||||
titleEl.textContent = '신규 직무별 기준 사양 등록';
|
||||
} else {
|
||||
titleEl.textContent = '직무별 기준 사양 상세 편집';
|
||||
}
|
||||
}
|
||||
|
||||
const deleteBtn = document.getElementById('btn-delete-job-spec-asset')!;
|
||||
const saveBtn = document.getElementById('btn-save-job-spec-asset')!;
|
||||
|
||||
deleteBtn.style.display = (mode === 'add') ? 'none' : 'block';
|
||||
|
||||
if (mode === 'add') {
|
||||
this.setEditLockMode('edit');
|
||||
this.isEditMode = true;
|
||||
saveBtn.textContent = '등록';
|
||||
saveBtn.style.display = 'block';
|
||||
} else {
|
||||
this.setEditLockMode('view');
|
||||
this.isEditMode = false;
|
||||
saveBtn.textContent = '수정';
|
||||
saveBtn.style.display = 'block';
|
||||
}
|
||||
|
||||
this.updateMinScore();
|
||||
}
|
||||
}
|
||||
|
||||
export const jobSpecModal = new JobSpecModal();
|
||||
|
||||
export function initJobSpecModal(onSave: () => void, closeModals: () => void) {
|
||||
jobSpecModal.init(onSave, closeModals);
|
||||
}
|
||||
|
||||
export function openJobSpecModal(asset: any, mode: 'view' | 'edit' | 'add' = 'view') {
|
||||
jobSpecModal.open(asset, mode);
|
||||
}
|
||||
@@ -30,7 +30,7 @@ export const CATEGORY_TYPE_MAP: Record<string, string[]> = {
|
||||
// 설치위치 종속성 데이터
|
||||
export const LOCATION_DATA: Record<string, string[]> = {
|
||||
'한맥빌딩': ['MDF실', '1층', '2층', '3층', '4층', '5층', '6층', '7층', '파고라'],
|
||||
'기술개발센터': ['서버실', 'BLUE ZONE', 'GREEN ZONE', 'ORANGE ZONE', '회의실2', '회의실3', '회의실5', '회의실6', '회의실7', '사이니지룸'],
|
||||
'기술개발센터': ['서버실', '센터내부'],
|
||||
'유니온빌딩': ['4층', '5층', '6층'],
|
||||
'뉴코아빌딩': ['4층', '6층', '7층'],
|
||||
'IDC': ['서관202', '서관203', '서관204', '서관205', '동관53', '동관54']
|
||||
@@ -60,10 +60,17 @@ export const IMAGE_LOCATIONS: Record<string, Record<string, string[]>> = {
|
||||
'서버실': [
|
||||
'img/location_photo/기술개발센터/서버실/서버실_1.png',
|
||||
'img/location_photo/기술개발센터/서버실/서버실_2.png'
|
||||
]
|
||||
],
|
||||
'센터내부': ['img/location_photo/기술개발센터/센터내부/센터내부.png']
|
||||
},
|
||||
'한맥빌딩': {
|
||||
'7층': ['img/location_photo/한맥빌딩/7층_로비.png'],
|
||||
'1층': ['img/location_photo/한맥빌딩/1층.png'],
|
||||
'2층': ['img/location_photo/한맥빌딩/2층.png'],
|
||||
'3층': ['img/location_photo/한맥빌딩/3층.png'],
|
||||
'4층': ['img/location_photo/한맥빌딩/4층.png'],
|
||||
'5층': ['img/location_photo/한맥빌딩/5층.png'],
|
||||
'6층': ['img/location_photo/한맥빌딩/6층.png'],
|
||||
'7층': ['img/location_photo/한맥빌딩/7층.png'],
|
||||
'MDF실': [
|
||||
'img/location_photo/한맥빌딩/MDF실/MDF_1.png',
|
||||
'img/location_photo/한맥빌딩/MDF실/MDF_2.png',
|
||||
|
||||
@@ -160,6 +160,16 @@ export const PAGE_DESCRIPTIONS: Record<string, { title: string; description: str
|
||||
title: '임직원 사용자 관리',
|
||||
description: 'IT 자산 할당 및 관리의 기준이 되는 사내 임직원(사용자) 정보를 데이터베이스 기반으로 직접 등록하고 수정합니다.',
|
||||
icon: 'users'
|
||||
},
|
||||
'부품 마스터': {
|
||||
title: '부품 표준 정보 관리',
|
||||
description: 'PC 사양 적정성 평가의 기준이 되는 부품 표준 정보 및 등급별 감점 점수를 관리합니다.',
|
||||
icon: 'cpu'
|
||||
},
|
||||
'직무별 기준 사양': {
|
||||
title: '직무별 기준 사양 관리',
|
||||
description: 'BIM 모델러, 개발자, 엔지니어 등 사내 직무별 권장 하드웨어 기준 및 성능 합격 점수를 관리합니다.',
|
||||
icon: 'sliders'
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ export interface MasterAssetData {
|
||||
vip: any[];
|
||||
mobile?: any[]; // Legacy mobile support
|
||||
equip?: any[]; // Backward compat
|
||||
jobSpecs?: any[];
|
||||
|
||||
// Backward compatibility
|
||||
subSw: any[];
|
||||
@@ -61,7 +62,8 @@ export const state: AppState = {
|
||||
cost: [], vip: [],
|
||||
subSw: [], permSw: [],
|
||||
hw: [], sw: [],
|
||||
swUsers: [], logs: []
|
||||
swUsers: [], logs: [],
|
||||
jobSpecs: []
|
||||
}
|
||||
};
|
||||
|
||||
@@ -79,6 +81,7 @@ export async function loadMasterDataFromDB() {
|
||||
state.masterData = {
|
||||
...state.masterData,
|
||||
...data,
|
||||
jobSpecs: data.jobSpecs || [],
|
||||
logs: (data.logs || []).map((l: any) => ({
|
||||
...l,
|
||||
assetId: l.asset_id || l.assetId,
|
||||
@@ -229,3 +232,38 @@ export async function deleteSystemUser(id: string) {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function saveJobSpec(spec: any) {
|
||||
try {
|
||||
const url = `${API_BASE_URL}/api/job-specs/save`;
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(spec)
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
await loadMasterDataFromDB(); // 전역 상태 갱신
|
||||
return true;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('직무별 기준 사양 저장 실패:', err);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function deleteJobSpec(id: number) {
|
||||
try {
|
||||
const url = `${API_BASE_URL}/api/job-specs/${id}`;
|
||||
const response = await fetch(url, { method: 'DELETE' });
|
||||
|
||||
if (response.ok) {
|
||||
await loadMasterDataFromDB(); // 전역 상태 갱신
|
||||
return true;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('직무별 기준 사양 삭제 실패:', err);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -288,11 +288,12 @@ export function calculatePcScoreDeductive(cpu: string, ram: string, gpu: string,
|
||||
/**
|
||||
* 성능 점수 기준 등급 뱃지 메타 정보 가져오기
|
||||
*/
|
||||
export function getPcGrade(score: number): { name: string; class: string; color: string } {
|
||||
export function getPcGrade(score: number, isWin11Incompatible?: boolean): { name: string; class: string; color: string } {
|
||||
if (score >= 85) return { name: '최상급', class: 'b-purple', color: '#7C3AED' };
|
||||
if (score >= 70) return { name: '상급', class: 'b-primary', color: '#4F46E5' };
|
||||
if (score >= 40) return { name: '중급', class: 'b-green', color: '#10B981' };
|
||||
return { name: '보급', class: 'b-yellow', color: '#F59E0B' };
|
||||
if (score >= 20 && !isWin11Incompatible) return { name: '보급', class: 'b-yellow', color: '#F59E0B' };
|
||||
return { name: '교체 대상', class: 'badge-danger', color: '#EF4444' };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
89
src/main.ts
89
src/main.ts
@@ -9,7 +9,9 @@ import { initSwModal, openSwModal } from './components/Modal/SWModal';
|
||||
import { initSwUserModal } from './components/Modal/SWUserModal';
|
||||
import { initDomainModal, openDomainModal } from './components/Modal/DomainModal';
|
||||
import { initPartsMasterModal, openPartsMasterModal } from './components/Modal/PartsMasterModal';
|
||||
import { initJobSpecModal, openJobSpecModal } from './components/Modal/JobSpecModal';
|
||||
import { initUserModal, openUserModal } from './components/Modal/UserModal';
|
||||
import { activePartsMasterSubTab } from './views/List/PartsMasterListView';
|
||||
import { initDashboardDetailModal } from './components/Modal/DashboardDetailModal';
|
||||
import { initGuide } from './components/Guide';
|
||||
import { pcFlowModal } from './components/Modal/PCFlowModal';
|
||||
@@ -85,6 +87,7 @@ function initApp() {
|
||||
}, closeAllModals);
|
||||
initDomainModal(() => refreshAllData(), closeAllModals);
|
||||
initPartsMasterModal(() => refreshAllData(), closeAllModals);
|
||||
initJobSpecModal(() => refreshAllData(), closeAllModals);
|
||||
initUserModal(() => refreshAllData(), closeAllModals);
|
||||
|
||||
initDashboardDetailModal();
|
||||
@@ -114,7 +117,11 @@ function initApp() {
|
||||
|
||||
if (cat === 'hw') {
|
||||
if (tab === '부품 마스터') {
|
||||
openPartsMasterModal({ id: '' } as any, 'add');
|
||||
if (activePartsMasterSubTab === 'job-spec') {
|
||||
openJobSpecModal({ id: '' } as any, 'add');
|
||||
} else {
|
||||
openPartsMasterModal({ id: '' } as any, 'add');
|
||||
}
|
||||
} else {
|
||||
openHwModal({ id: newId, asset_code: '', category: tab } as any, 'add');
|
||||
}
|
||||
@@ -201,66 +208,40 @@ function initRoleSwitcher() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 로그인 처리 로직
|
||||
* 앱 초기화 (로그인 과정 없이 즉시 시작)
|
||||
*/
|
||||
function handleLogin() {
|
||||
function initializeAppDirectly() {
|
||||
const loginContainer = document.getElementById('login-container');
|
||||
const appLayout = document.getElementById('app-layout');
|
||||
const roleCards = document.querySelectorAll('.role-card');
|
||||
const checkbox = document.getElementById('role-toggle-checkbox') as HTMLInputElement;
|
||||
const userLabel = document.querySelector('.role-label.user');
|
||||
const adminLabel = document.querySelector('.role-label.admin');
|
||||
|
||||
if (!loginContainer || !appLayout || roleCards.length === 0) return;
|
||||
// 기본 권한 설정: 실무자 (User)
|
||||
state.currentUserRole = 'user';
|
||||
state.activeCategory = 'hw';
|
||||
state.activeSubTab = '서버'; // 실무자 기본 탭
|
||||
|
||||
roleCards.forEach(card => {
|
||||
card.addEventListener('click', () => {
|
||||
const role = card.getAttribute('data-role');
|
||||
const checkbox = document.getElementById('role-toggle-checkbox') as HTMLInputElement;
|
||||
|
||||
if (role === 'admin') {
|
||||
console.log('🔓 Entering as Admin');
|
||||
|
||||
state.currentUserRole = 'admin';
|
||||
state.activeCategory = 'hw';
|
||||
state.activeSubTab = '대시보드'; // 관리자는 대시보드로 진입
|
||||
|
||||
if (checkbox) checkbox.checked = true;
|
||||
if (userLabel) userLabel.classList.remove('active');
|
||||
if (adminLabel) adminLabel.classList.add('active');
|
||||
document.body.classList.add('admin-mode');
|
||||
} else if (role === 'user') {
|
||||
console.log('🔓 Entering as Practitioner');
|
||||
|
||||
state.currentUserRole = 'user';
|
||||
state.activeCategory = 'hw';
|
||||
state.activeSubTab = '서버'; // 실무자는 서버 목록으로 진입
|
||||
|
||||
if (checkbox) checkbox.checked = false;
|
||||
if (userLabel) userLabel.classList.add('active');
|
||||
if (adminLabel) adminLabel.classList.remove('active');
|
||||
document.body.classList.remove('admin-mode');
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
// UI 상태 동기화
|
||||
if (checkbox) checkbox.checked = false;
|
||||
if (userLabel) userLabel.classList.add('active');
|
||||
if (adminLabel) adminLabel.classList.remove('active');
|
||||
document.body.classList.remove('admin-mode');
|
||||
|
||||
// UI 전환
|
||||
loginContainer.style.display = 'none';
|
||||
appLayout.style.display = 'flex';
|
||||
|
||||
// 역할 스위처 및 앱 초기화 시작
|
||||
initRoleSwitcher();
|
||||
initApp();
|
||||
|
||||
// 로고 클릭 시 초기화면 복귀 로직 (한 번만 등록)
|
||||
const brand = document.querySelector('.brand') as HTMLElement;
|
||||
if (brand) {
|
||||
brand.style.cursor = 'pointer';
|
||||
brand.onclick = () => {
|
||||
location.reload(); // 즉시 초기화면으로 복귀
|
||||
};
|
||||
}
|
||||
});
|
||||
});
|
||||
// 화면 전환
|
||||
if (loginContainer) loginContainer.style.display = 'none';
|
||||
if (appLayout) appLayout.style.display = 'flex';
|
||||
|
||||
// 앱 초기화
|
||||
initRoleSwitcher();
|
||||
initApp();
|
||||
|
||||
// 로고 클릭 시 새로고침 (초기 화면 복귀 효과)
|
||||
const brand = document.querySelector('.brand') as HTMLElement;
|
||||
if (brand) {
|
||||
brand.style.cursor = 'pointer';
|
||||
brand.onclick = () => location.reload();
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', handleLogin);
|
||||
document.addEventListener('DOMContentLoaded', initializeAppDirectly);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,66 +1,171 @@
|
||||
import { state } from '../../core/state';
|
||||
import { openPartsMasterModal } from '../../components/Modal/PartsMasterModal';
|
||||
import { openJobSpecModal } from '../../components/Modal/JobSpecModal';
|
||||
import { formatInline } from '../../core/utils';
|
||||
import { createListView } from './ListFactory';
|
||||
|
||||
export let activePartsMasterSubTab: 'parts-master' | 'job-spec' = 'parts-master';
|
||||
|
||||
export function renderPartsMasterList(container: HTMLElement) {
|
||||
createListView(container, {
|
||||
title: '부품 마스터',
|
||||
dataSource: () => state.masterData.partsMaster || [],
|
||||
searchKeys: ['component_name', 'category', 'score_tier'],
|
||||
filterOptions: {
|
||||
keywordLabel: '부품명 / 등급 검색',
|
||||
showLoc: false,
|
||||
showDept: false,
|
||||
showType: false
|
||||
},
|
||||
onRowClick: (component) => openPartsMasterModal(component, 'view'),
|
||||
columns: [
|
||||
{
|
||||
header: 'ID',
|
||||
sortKey: 'id',
|
||||
align: 'center',
|
||||
width: '5%',
|
||||
render: c => c.id.toString()
|
||||
if (activePartsMasterSubTab === 'parts-master') {
|
||||
createListView(container, {
|
||||
title: '부품 마스터',
|
||||
dataSource: () => state.masterData.partsMaster || [],
|
||||
searchKeys: ['component_name', 'category', 'score_tier'],
|
||||
filterOptions: {
|
||||
keywordLabel: '부품명 / 등급 검색',
|
||||
showLoc: false,
|
||||
showDept: false,
|
||||
showType: false
|
||||
},
|
||||
{
|
||||
header: '분류',
|
||||
sortKey: 'category',
|
||||
align: 'center',
|
||||
width: '15%',
|
||||
render: c => {
|
||||
let badgeClass = 'badge-primary';
|
||||
if (c.category === 'CPU') badgeClass = 'b-primary';
|
||||
else if (c.category === 'GPU') badgeClass = 'b-purple';
|
||||
else if (c.category === 'RAM') badgeClass = 'b-green';
|
||||
return `<span class="badge ${badgeClass}">${c.category}</span>`;
|
||||
onRowClick: (component) => openPartsMasterModal(component, 'view'),
|
||||
columns: [
|
||||
{
|
||||
header: 'ID',
|
||||
sortKey: 'id',
|
||||
align: 'center',
|
||||
width: '5%',
|
||||
render: c => c.id.toString()
|
||||
},
|
||||
{
|
||||
header: '분류',
|
||||
sortKey: 'category',
|
||||
align: 'center',
|
||||
width: '15%',
|
||||
render: c => {
|
||||
let badgeClass = 'badge-primary';
|
||||
if (c.category === 'CPU') badgeClass = 'b-primary';
|
||||
else if (c.category === 'GPU') badgeClass = 'b-purple';
|
||||
else if (c.category === 'RAM') badgeClass = 'b-green';
|
||||
return `<span class="badge ${badgeClass}">${c.category}</span>`;
|
||||
}
|
||||
},
|
||||
{
|
||||
header: '부품 표준 명칭',
|
||||
sortKey: 'component_name',
|
||||
render: c => formatInline(c.component_name || '-')
|
||||
},
|
||||
{
|
||||
header: '성능 등급',
|
||||
sortKey: 'score_tier',
|
||||
align: 'center',
|
||||
width: '15%',
|
||||
render: c => c.score_tier || '-'
|
||||
},
|
||||
{
|
||||
header: '감점 점수',
|
||||
sortKey: 'deduction',
|
||||
align: 'center',
|
||||
width: '15%',
|
||||
render: c => {
|
||||
const score = c.deduction || 0;
|
||||
let color = '#3b82f6'; // blue
|
||||
if (score >= 20) color = '#ef4444'; // red
|
||||
else if (score >= 10) color = '#f59e0b'; // orange
|
||||
return `<strong style="color: ${color}; font-size: 14px;">-${score}점</strong>`;
|
||||
}
|
||||
}
|
||||
]
|
||||
});
|
||||
} else {
|
||||
createListView(container, {
|
||||
title: '직무별 기준 사양',
|
||||
dataSource: () => state.masterData.jobSpecs || [],
|
||||
searchKeys: ['job_name', 'cpu_standard', 'ram_standard', 'gpu_standard', 'remarks'],
|
||||
filterOptions: {
|
||||
keywordLabel: '직무명 / 사양 검색',
|
||||
showLoc: false,
|
||||
showDept: false,
|
||||
showType: false
|
||||
},
|
||||
{
|
||||
header: '부품 표준 명칭',
|
||||
sortKey: 'component_name',
|
||||
render: c => formatInline(c.component_name || '-')
|
||||
},
|
||||
{
|
||||
header: '성능 등급',
|
||||
sortKey: 'score_tier',
|
||||
align: 'center',
|
||||
width: '15%',
|
||||
render: c => c.score_tier || '-'
|
||||
},
|
||||
{
|
||||
header: '감점 점수',
|
||||
sortKey: 'deduction',
|
||||
align: 'center',
|
||||
width: '15%',
|
||||
render: c => {
|
||||
const score = c.deduction || 0;
|
||||
let color = '#3b82f6'; // blue
|
||||
if (score >= 20) color = '#ef4444'; // red
|
||||
else if (score >= 10) color = '#f59e0b'; // orange
|
||||
return `<strong style="color: ${color}; font-size: 14px;">-${score}점</strong>`;
|
||||
onRowClick: (jobSpec) => openJobSpecModal(jobSpec, 'view'),
|
||||
columns: [
|
||||
{
|
||||
header: 'ID',
|
||||
sortKey: 'id',
|
||||
align: 'center',
|
||||
width: '5%',
|
||||
render: j => j.id.toString()
|
||||
},
|
||||
{
|
||||
header: '직무명',
|
||||
sortKey: 'job_name',
|
||||
width: '15%',
|
||||
render: j => `<strong style="color: var(--primary-color); font-size: 14px;">${formatInline(j.job_name || '-')}</strong>`
|
||||
},
|
||||
{
|
||||
header: '권장 CPU 사양',
|
||||
sortKey: 'cpu_standard',
|
||||
render: j => formatInline(j.cpu_standard || '-')
|
||||
},
|
||||
{
|
||||
header: '권장 RAM 사양',
|
||||
sortKey: 'ram_standard',
|
||||
width: '12%',
|
||||
render: j => formatInline(j.ram_standard || '-')
|
||||
},
|
||||
{
|
||||
header: '권장 GPU 사양',
|
||||
sortKey: 'gpu_standard',
|
||||
render: j => formatInline(j.gpu_standard || '-')
|
||||
},
|
||||
{
|
||||
header: '기준 점수',
|
||||
sortKey: 'min_score',
|
||||
align: 'center',
|
||||
width: '10%',
|
||||
render: j => `<span style="font-weight: 700;">${j.min_score || 0}점 이상</span>`
|
||||
},
|
||||
{
|
||||
header: '비고',
|
||||
sortKey: 'remarks',
|
||||
width: '20%',
|
||||
render: j => formatInline(j.remarks || '-')
|
||||
}
|
||||
}
|
||||
]
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
renderSubTabs(container);
|
||||
}
|
||||
|
||||
function renderSubTabs(container: HTMLElement) {
|
||||
const header = container.querySelector('.page-header');
|
||||
if (!header) return;
|
||||
|
||||
const tabContainer = document.createElement('div');
|
||||
tabContainer.className = 'sub-tab-container';
|
||||
tabContainer.style.cssText = 'display: flex; gap: 16px; margin-top: 16px; margin-bottom: 16px; border-bottom: 1px solid var(--border-color); padding-bottom: 0;';
|
||||
|
||||
const tab1Active = activePartsMasterSubTab === 'parts-master';
|
||||
const tab2Active = activePartsMasterSubTab === 'job-spec';
|
||||
|
||||
tabContainer.innerHTML = `
|
||||
<button id="tab-parts-master" class="sub-tab-btn ${tab1Active ? 'active' : ''}" style="padding: 10px 16px; border: none; background: none; font-size: 14px; font-weight: 600; cursor: pointer; color: ${tab1Active ? 'var(--primary-color)' : 'var(--text-muted)'}; position: relative; border-bottom: 3px solid ${tab1Active ? 'var(--primary-color)' : 'transparent'};">
|
||||
부품 표준 등급
|
||||
</button>
|
||||
<button id="tab-job-spec" class="sub-tab-btn ${tab2Active ? 'active' : ''}" style="padding: 10px 16px; border: none; background: none; font-size: 14px; font-weight: 600; cursor: pointer; color: ${tab2Active ? 'var(--primary-color)' : 'var(--text-muted)'}; position: relative; border-bottom: 3px solid ${tab2Active ? 'var(--primary-color)' : 'transparent'};">
|
||||
직무별 기준 사양
|
||||
</button>
|
||||
`;
|
||||
|
||||
header.parentNode!.insertBefore(tabContainer, header.nextSibling);
|
||||
|
||||
const tabPartsMaster = tabContainer.querySelector('#tab-parts-master')!;
|
||||
const tabJobSpec = tabContainer.querySelector('#tab-job-spec')!;
|
||||
|
||||
tabPartsMaster.addEventListener('click', () => {
|
||||
if (activePartsMasterSubTab !== 'parts-master') {
|
||||
activePartsMasterSubTab = 'parts-master';
|
||||
renderPartsMasterList(container);
|
||||
}
|
||||
});
|
||||
|
||||
tabJobSpec.addEventListener('click', () => {
|
||||
if (activePartsMasterSubTab !== 'job-spec') {
|
||||
activePartsMasterSubTab = 'job-spec';
|
||||
renderPartsMasterList(container);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,18 +1,29 @@
|
||||
import { state } from '../../core/state';
|
||||
import { openHwModal } from '../../components/Modal/HWModal';
|
||||
import { sortAssets, formatInline, calculatePcScoreDeductive, getPcGrade } from '../../core/utils';
|
||||
import { sortAssets, formatInline, calculatePcScoreDeductive, getPcGrade, isWindows11Incompatible } from '../../core/utils';
|
||||
import { ASSET_SCHEMA } from '../../core/schema';
|
||||
import { createListView } from './ListFactory';
|
||||
import { SortState } from '../../core/tableHandler';
|
||||
|
||||
let persistentSortState: SortState = { key: 'updated_at', direction: 'desc' };
|
||||
|
||||
export function renderPcList(container: HTMLElement) {
|
||||
createListView(container, {
|
||||
title: 'PC',
|
||||
persistentSortState,
|
||||
dataSource: () => {
|
||||
const list = (state.masterData.pc || []).filter((a: any) => a.asset_type !== '서버PC');
|
||||
list.forEach((a: any) => {
|
||||
a['_pc_score'] = calculatePcScoreDeductive(a[ASSET_SCHEMA.CPU.key], a[ASSET_SCHEMA.RAM.key], a[ASSET_SCHEMA.GPU.key], a.purchase_date);
|
||||
});
|
||||
return sortAssets(list);
|
||||
// 변경일시(updated_at) 내림차순 정렬 (최신 변경 항목이 맨 위로)
|
||||
return list.sort((a: any, b: any) => {
|
||||
const dateA = a.updated_at || a.created_at || '';
|
||||
const dateB = b.updated_at || b.created_at || '';
|
||||
if (dateA < dateB) return 1;
|
||||
if (dateA > dateB) return -1;
|
||||
return 0;
|
||||
});
|
||||
},
|
||||
searchKeys: ['CURRENT_DEPT', 'CURRENT_USER', 'MODEL_NAME', 'MAC_ADDR', 'MANAGER_MAIN', 'ASSET_TYPE'],
|
||||
filterOptions: {
|
||||
@@ -93,7 +104,8 @@ export function renderPcList(container: HTMLElement) {
|
||||
width: '8%',
|
||||
render: a => {
|
||||
const score = a._pc_score !== undefined ? a._pc_score : calculatePcScoreDeductive(a[ASSET_SCHEMA.CPU.key], a[ASSET_SCHEMA.RAM.key], a[ASSET_SCHEMA.GPU.key], a.purchase_date);
|
||||
const grade = getPcGrade(score);
|
||||
const isWin11Incompatible = isWindows11Incompatible(a[ASSET_SCHEMA.CPU.key], a[ASSET_SCHEMA.RAM.key]);
|
||||
const grade = getPcGrade(score, isWin11Incompatible);
|
||||
return `<span class="badge ${grade.class}" title="성능 점수: ${score}점">${grade.name}</span>`;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user