4 Commits

25 changed files with 5706 additions and 1906 deletions

3889
backup_atam_data.json Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -10,95 +10,116 @@ async function initDB() {
host: DB_HOST,
user: DB_USER,
password: DB_PASS,
port: parseInt(DB_PORT || '3306')
database: DB_NAME,
port: parseInt(DB_PORT || '3306'),
multipleStatements: true
});
console.log('🚀 DB 초기화 시작...');
console.log('🔄 DB 초기화 시작 (표준화 스키마 적용)...');
// 1. 데이터베이스 생성
await connection.query(`CREATE DATABASE IF NOT EXISTS ${DB_NAME};`);
await connection.query(`USE ${DB_NAME};`);
console.log(`✅ 데이터베이스 생성 완료: ${DB_NAME}`);
// 기존 테이블 삭제
const tablesToDrop = ['pc_assets', 'server_assets', 'storage_assets', 'equip_assets', 'mobile_assets', 'sw_sub_assets', 'sw_perm_assets', 'sw_users'];
for (const table of tablesToDrop) {
await connection.query(`DROP TABLE IF EXISTS ${table}`);
}
// 2. 하드웨어 자산 테이블
const createHwTable = `
CREATE TABLE IF NOT EXISTS hw_assets (
// 공통 하드웨어 테이블 생성 함수
const createHardwareTable = (tableName, comment) => `
CREATE TABLE ${tableName} (
id VARCHAR(50) PRIMARY KEY,
type VARCHAR(50) NOT NULL COMMENT '개인PC, 서버, 스토리지, 전산비품',
corp VARCHAR(100) COMMENT '구매법인',
asset_code VARCHAR(100) COMMENT '자산번호/코드',
asset_name VARCHAR(255) COMMENT '명칭/용도',
location VARCHAR(255) COMMENT '설치위치',
asset_code VARCHAR(100) COMMENT '자산번호',
purchase_date VARCHAR(50) COMMENT '구매일자',
type VARCHAR(50) COMMENT '유형',
detail_purpose VARCHAR(50) COMMENT '상세용도',
purpose VARCHAR(255) COMMENT '용도',
details TEXT COMMENT '상세내용',
current_org VARCHAR(255) COMMENT '현 사용조직',
prev_org VARCHAR(255) COMMENT '이전 사용조직',
location VARCHAR(255) COMMENT '설치위치',
manager_main VARCHAR(100) COMMENT '담당자(정)',
manager_sub VARCHAR(100) COMMENT '담당자(부)',
ip_address VARCHAR(100) COMMENT 'IP 주소 1',
ip_address2 VARCHAR(100) COMMENT 'IP 주소 2',
mac_address VARCHAR(100) COMMENT 'MAC 주소',
os VARCHAR(100),
cpu VARCHAR(255),
ram VARCHAR(100),
storage1 VARCHAR(255),
storage2 VARCHAR(255),
model_name VARCHAR(255),
purchase_date VARCHAR(50),
price VARCHAR(100),
vendor VARCHAR(255) COMMENT '납품업체',
doc_name VARCHAR(255) COMMENT '품의서명',
remote_tool VARCHAR(100) COMMENT '원격도구',
server_id VARCHAR(100),
server_pw VARCHAR(100),
model_name VARCHAR(255),
os VARCHAR(100),
cpu VARCHAR(255),
ram VARCHAR(100),
gpu VARCHAR(100),
storage1 VARCHAR(255),
storage2 VARCHAR(255),
storage3 VARCHAR(255),
monitoring VARCHAR(100),
price VARCHAR(100) COMMENT '금액',
remarks TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='${comment}';
`;
await connection.query(createHardwareTable('pc_assets', '개인PC 자산'));
await connection.query(createHardwareTable('server_assets', '서버 자산'));
await connection.query(createHardwareTable('storage_assets', '스토리지 자산'));
await connection.query(createHardwareTable('equip_assets', '전산비품 자산'));
await connection.query(createHardwareTable('mobile_assets', '모바일기기 자산'));
// 소프트웨어 구독 테이블
const createSubSwTable = `
CREATE TABLE sw_sub_assets (
id VARCHAR(50) PRIMARY KEY,
corp VARCHAR(100) COMMENT '구매법인',
asset_code VARCHAR(100) COMMENT '자산번호',
product_name VARCHAR(255) COMMENT '제품명',
license_type VARCHAR(100) COMMENT '라이선스 유형',
quantity INT COMMENT '수량',
price VARCHAR(100) COMMENT '금액',
purchase_date VARCHAR(50) COMMENT '구매일',
expiry_date VARCHAR(50) COMMENT '만료일',
vendor VARCHAR(255) COMMENT '납품업체',
remarks TEXT COMMENT '비고',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
`;
// 3. 소프트웨어 자산 테이블
const createSwTable = `
CREATE TABLE IF NOT EXISTS sw_assets (
// 소프트웨어 영구 테이블
const createPermSwTable = `
CREATE TABLE sw_perm_assets (
id VARCHAR(50) PRIMARY KEY,
type VARCHAR(50) NOT NULL COMMENT '구독SW, 영구SW',
category VARCHAR(100) COMMENT '분야',
corp VARCHAR(100) COMMENT '구매법인',
dept VARCHAR(100) COMMENT '부서',
product_name VARCHAR(255) NOT NULL,
purchase_date VARCHAR(50),
subscription_date VARCHAR(50),
maintenance_status TINYINT(1) DEFAULT 0,
price VARCHAR(100),
quantity INT DEFAULT 1,
account_id VARCHAR(255) COMMENT '계정명',
vendor VARCHAR(255),
remarks TEXT,
asset_code VARCHAR(100) COMMENT '자산번호',
product_name VARCHAR(255) COMMENT '제품명',
license_key VARCHAR(255) COMMENT '라이선스 키',
quantity INT COMMENT '수량',
price VARCHAR(100) COMMENT '금액',
purchase_date VARCHAR(50) COMMENT '구매일',
vendor VARCHAR(255) COMMENT '납품업체',
remarks TEXT COMMENT '비고',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
`;
// 4. 소프트웨어 사용자 매핑 테이블
// 소프트웨어 사용자 매핑 테이블
const createSwUsersTable = `
CREATE TABLE IF NOT EXISTS sw_users (
id VARCHAR(50) PRIMARY KEY,
sw_id VARCHAR(50),
corp VARCHAR(100),
dept VARCHAR(100),
team VARCHAR(100),
position VARCHAR(50),
name VARCHAR(100),
usage_period VARCHAR(100),
doc_name VARCHAR(255),
FOREIGN KEY (sw_id) REFERENCES sw_assets(id) ON DELETE CASCADE
CREATE TABLE sw_users (
id INT AUTO_INCREMENT PRIMARY KEY,
sw_id VARCHAR(50) COMMENT 'SW 자산 ID',
corp VARCHAR(100) COMMENT '법인',
dept VARCHAR(100) COMMENT '부서',
position VARCHAR(50) COMMENT '직위',
user_name VARCHAR(100) COMMENT '이름',
usage_period VARCHAR(100) COMMENT '사용기간',
doc_name VARCHAR(255) COMMENT '신청서명',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
`;
await connection.query(createHwTable);
await connection.query(createSwTable);
await connection.query(createSubSwTable);
await connection.query(createPermSwTable);
await connection.query(createSwUsersTable);
console.log('✅ 테이블 생성 완료!');
console.log('✅ 모든 테이블이 표준화된 스키마로 재생성되었습니다.');
await connection.end();
console.log('🏁 DB 초기화 프로세스 종료.');
}
initDB().catch(err => {

407
server.js
View File

@@ -11,7 +11,6 @@ const PORT = process.env.PORT || 3000;
app.use(cors());
app.use(express.json({ limit: '50mb' }));
// DB 연결 풀 생성
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
@@ -23,202 +22,292 @@ const pool = mysql.createPool({
queueLimit: 0
});
// --- API Routes ---
// 1. 하드웨어 자산 조회
app.get('/api/hw', async (req, res) => {
try {
const [rows] = await pool.query('SELECT * FROM hw_assets');
// DB 컬럼명을 프론트엔드 인터페이스(한글)에 맞게 매핑
const mapped = rows.map(r => ({
id: r.id,
type: r.type,
법인: r.corp,
자산코드: r.asset_code,
명칭: r.asset_name,
위치: r.location,
현사용조직: r.current_org,
이전사용조직: r.prev_org,
담당자_정: r.manager_main,
관리자: r.manager_main,
담당자_부: r.manager_sub,
IP주소: r.ip_address,
IP2: r.ip_address2,
MACaddress: r.mac_address,
OS: r.os,
CPU: r.cpu,
RAM: r.ram,
SSD1: r.storage1,
SSD2: r.storage2,
모델명: r.model_name,
구매일: r.purchase_date,
금액: r.price,
납품업체: r.vendor,
품의서명: r.doc_name,
용도: r.asset_name, // 서버의 경우 명칭을 용도로 사용
상세: r.remarks,
원격접속: r.remote_tool,
서버ID: r.server_id,
서버PW: r.server_pw,
모니터링: r.monitoring,
비고: r.remarks
}));
res.json(mapped);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// 2. 하드웨어 자산 일괄 저장 (항상 덮어쓰기)
app.post('/api/hw/batch', async (req, res) => {
const assets = req.body;
// 공통 배치 저장 로직
async function batchSave(tableName, assets, getQuery) {
const connection = await pool.getConnection();
try {
await connection.beginTransaction();
await connection.query('DELETE FROM hw_assets');
await connection.query(`DELETE FROM ${tableName}`);
if (assets.length > 0) {
const sql = `
INSERT INTO hw_assets (
id, type, corp, asset_code, asset_name, location, current_org, prev_org,
manager_main, manager_sub, ip_address, ip_address2, mac_address, os,
cpu, ram, storage1, storage2, model_name, purchase_date, price,
vendor, doc_name, remote_tool, server_id, server_pw, monitoring, remarks
) VALUES ?
`;
const values = assets.map(a => [
a.id, a.type, a.법인, a.자산코드, a.명칭 || a.용도, a.위치, a.현사용조직, a.이전사용조직,
a.담당자_정 || a.관리자, a.담당자_부, a.IP주소, a.IP2, a.MACaddress, a.OS,
a.CPU, a.RAM, a.SSD1, a.SSD2, a.모델명, a.구매일, a.금액,
a.납품업체, a.품의서명, a.원격접속, a.서버ID, a.서버PW, a.모니터링, a.비고 || a.상세
]);
const { sql, values } = getQuery(assets);
await connection.query(sql, [values]);
}
await connection.commit();
res.json({ success: true, count: assets.length, mode: 'overwrite' });
return { success: true, count: assets.length };
} catch (err) {
await connection.rollback();
res.status(500).json({ error: err.message });
throw err;
} finally {
connection.release();
}
}
// 공통 하드웨어 매핑 함수
const mapHardware = (r, defaultType) => ({
id: r.id,
법인: r.corp,
자산코드: r.asset_code,
구매일: r.purchase_date,
purchase_date: r.purchase_date,
type: r.type || defaultType,
상세용도: r.detail_purpose,
detail_purpose: r.detail_purpose,
용도: r.purpose,
purpose: r.purpose,
상세: r.details,
details: r.details,
현사용조직: r.current_org,
current_org: r.current_org,
이전사용조직: r.prev_org,
prev_org: r.prev_org,
위치: r.location,
location: r.location,
담당자_정: r.manager_main,
manager_main: r.manager_main,
담당자_부: r.manager_sub,
manager_sub: r.manager_sub,
IP주소: r.ip_address,
ip_address: r.ip_address,
원격접속: r.remote_tool,
remote_tool: r.remote_tool,
서버ID: r.server_id,
server_id: r.server_id,
서버PW: r.server_pw,
server_pw: r.server_pw,
모델명: r.model_name,
model_name: r.model_name,
OS: r.os,
os: r.os,
CPU: r.cpu,
cpu: r.cpu,
RAM: r.ram,
ram: r.ram,
GPU: r.gpu,
gpu: r.gpu,
SSD1: r.storage1,
storage1: r.storage1,
SSD2: r.storage2,
storage2: r.storage2,
HDD1: r.storage3,
storage3: r.storage3,
모니터링: r.monitoring,
monitoring: r.monitoring,
금액: r.price,
price: r.price,
비고: r.remarks,
remarks: r.remarks
});
// 3. 소프트웨어 자산 조회
app.get('/api/sw', async (req, res) => {
// 공통 하드웨어 저장 값 생성 함수
const getHardwareValues = (a) => [
a.id, a.법인||'', a.자산코드||'', a.구매일||'', a.type||'', a.상세용도||'', a.용도||'', a.상세||'', a.현사용조직||'', a.이전사용조직||'', a.위치||'',
a.담당자_정||'', a.담당자_부||'', a.IP주소||'', a.원격접속||'', a.서버ID||'', a.서버PW||'', a.모델명||'', a.OS||'', a.CPU||'', a.RAM||'', a.GPU||'',
a.SSD1||'', a.SSD2||'', a.HDD1||'', a.모니터링||'', a.금액||'', a.비고||''
];
const hardwareInsertSQL = (table) => `
INSERT INTO ${table}
(id, corp, asset_code, purchase_date, type, detail_purpose, purpose, details, current_org, prev_org, location, manager_main, manager_sub, ip_address, remote_tool, server_id, server_pw, model_name, os, cpu, ram, gpu, storage1, storage2, storage3, monitoring, price, remarks)
VALUES ?
`;
// --- 1. 개인PC API ---
app.get('/api/pc', async (req, res) => {
try {
const [rows] = await pool.query('SELECT * FROM sw_assets');
const [rows] = await pool.query('SELECT * FROM pc_assets');
res.json(rows.map(r => mapHardware(r, 'PC')));
} catch (err) { res.status(500).json({ error: err.message }); }
});
app.post('/api/pc/batch', async (req, res) => {
try {
const result = await batchSave('pc_assets', req.body, (assets) => ({
sql: hardwareInsertSQL('pc_assets'),
values: assets.map(getHardwareValues)
}));
res.json(result);
} catch (err) { res.status(500).json({ error: err.message }); }
});
// --- 2. 서버 API ---
app.get('/api/server', async (req, res) => {
try {
const [rows] = await pool.query('SELECT * FROM server_assets');
res.json(rows.map(r => mapHardware(r, '서버')));
} catch (err) { res.status(500).json({ error: err.message }); }
});
app.post('/api/server/batch', async (req, res) => {
try {
const result = await batchSave('server_assets', req.body, (assets) => ({
sql: hardwareInsertSQL('server_assets'),
values: assets.map(getHardwareValues)
}));
res.json(result);
} catch (err) { res.status(500).json({ error: err.message }); }
});
// --- 3. 스토리지 API ---
app.get('/api/storage', async (req, res) => {
try {
const [rows] = await pool.query('SELECT * FROM storage_assets');
res.json(rows.map(r => mapHardware(r, '스토리지')));
} catch (err) { res.status(500).json({ error: err.message }); }
});
app.post('/api/storage/batch', async (req, res) => {
try {
const result = await batchSave('storage_assets', req.body, (assets) => ({
sql: hardwareInsertSQL('storage_assets'),
values: assets.map(getHardwareValues)
}));
res.json(result);
} catch (err) { res.status(500).json({ error: err.message }); }
});
// --- 4. 전산비품 API ---
app.get('/api/equip', async (req, res) => {
try {
const [rows] = await pool.query('SELECT * FROM equip_assets');
res.json(rows.map(r => mapHardware(r, '전산비품')));
} catch (err) { res.status(500).json({ error: err.message }); }
});
app.post('/api/equip/batch', async (req, res) => {
try {
const result = await batchSave('equip_assets', req.body, (assets) => ({
sql: hardwareInsertSQL('equip_assets'),
values: assets.map(getHardwareValues)
}));
res.json(result);
} catch (err) { res.status(500).json({ error: err.message }); }
});
// --- 5. 모바일기기 API ---
app.get('/api/mobile', async (req, res) => {
try {
const [rows] = await pool.query('SELECT * FROM mobile_assets');
res.json(rows.map(r => mapHardware(r, '모바일기기')));
} catch (err) { res.status(500).json({ error: err.message }); }
});
app.post('/api/mobile/batch', async (req, res) => {
try {
const result = await batchSave('mobile_assets', req.body, (assets) => ({
sql: hardwareInsertSQL('mobile_assets'),
values: assets.map(getHardwareValues)
}));
res.json(result);
} catch (err) { res.status(500).json({ error: err.message }); }
});
// --- 6. 소프트웨어 구독 API ---
app.get('/api/sw/sub', async (req, res) => {
try {
const [rows] = await pool.query('SELECT * FROM sw_sub_assets');
const mapped = rows.map(r => ({
id: r.id,
type: r.type,
분야: r.category,
법인: r.corp,
부서: r.dept,
제품명: r.product_name,
구매일: r.purchase_date,
구독일: r.subscription_date,
유지보수여부: !!r.maintenance_status,
금액: r.price,
수량: r.quantity,
계정명: r.account_id,
납품업체: r.vendor,
비고: r.remarks
id: r.id, type: '구독SW', 법인: r.corp, 자산번호: r.asset_code, 제품명: r.product_name,
라이선스유형: r.license_type, 수량: r.quantity, 금액: r.price, 구매일: r.purchase_date,
만료일: r.expiry_date, 납품업체: r.vendor, 비고: r.remarks
}));
res.json(mapped);
} catch (err) {
res.status(500).json({ error: err.message });
}
} catch (err) { res.status(500).json({ error: err.message }); }
});
// 4. 소프트웨어 자산 일괄 저장 (항상 덮어쓰기)
app.post('/api/sw/batch', async (req, res) => {
const assets = req.body;
const connection = await pool.getConnection();
app.post('/api/sw/sub/batch', async (req, res) => {
try {
await connection.beginTransaction();
await connection.query('DELETE FROM sw_assets');
if (assets.length > 0) {
const sql = `
INSERT INTO sw_assets (
id, type, category, corp, dept, product_name, purchase_date,
subscription_date, maintenance_status, price, quantity,
account_id, vendor, remarks
) VALUES ?
`;
const values = assets.map(a => [
a.id, a.type, a.분야, a.법인, a.부서, a.제품명, a.구매일,
a.구독일, a.유지보수여부 ? 1 : 0, a.금액, a.수량,
a.계정명, a.납품업체, a.비고
]);
await connection.query(sql, [values]);
}
await connection.commit();
res.json({ success: true, count: assets.length, mode: 'overwrite' });
} catch (err) {
await connection.rollback();
res.status(500).json({ error: err.message });
} finally {
connection.release();
}
const result = await batchSave('sw_sub_assets', req.body, (assets) => ({
sql: `INSERT INTO sw_sub_assets (id, corp, asset_code, product_name, license_type, quantity, price, purchase_date, expiry_date, vendor, remarks) VALUES ?`,
values: assets.map(a => [a.id, a.법인||'', a.자산번호||'', a.제품명||'', a.라이선스유형||'', a.수량||0, a.금액||'', a.구매일||'', a.만료일||'', a.납품업체||'', a.비고||''])
}));
res.json(result);
} catch (err) { res.status(500).json({ error: err.message }); }
});
// 5. SW 사용자 매핑 조회
// --- 7. 소프트웨어 영구 API ---
app.get('/api/sw/perm', async (req, res) => {
try {
const [rows] = await pool.query('SELECT * FROM sw_perm_assets');
const mapped = rows.map(r => ({
id: r.id, type: '영구SW', 법인: r.corp, 자산번호: r.asset_code, 제품명: r.product_name,
라이선스키: r.license_key, 수량: r.quantity, 금액: r.price, 구매일: r.purchase_date,
납품업체: r.vendor, 비고: r.remarks
}));
res.json(mapped);
} catch (err) { res.status(500).json({ error: err.message }); }
});
app.post('/api/sw/perm/batch', async (req, res) => {
try {
const result = await batchSave('sw_perm_assets', req.body, (assets) => ({
sql: `INSERT INTO sw_perm_assets (id, corp, asset_code, product_name, license_key, quantity, price, purchase_date, vendor, remarks) VALUES ?`,
values: assets.map(a => [a.id, a.법인||'', a.자산번호||'', a.제품명||'', a.라이선스키||'', a.수량||0, a.금액||'', a.구매일||'', a.납품업체||'', a.비고||''])
}));
res.json(result);
} catch (err) { res.status(500).json({ error: err.message }); }
});
// --- 8. 소프트웨어 사용자 관리 API ---
app.get('/api/sw-users', async (req, res) => {
try {
const [rows] = await pool.query('SELECT * FROM sw_users');
const mapped = rows.map(r => ({
id: r.id,
swId: r.sw_id,
법인: r.corp,
부서: r.dept,
: r.team,
직위: r.position,
이름: r.name,
사용기간: r.usage_period,
신청서명: r.doc_name
const result = rows.map(u => ({
sw_id: u.sw_id,
userData: [u.corp||'', u.dept||'', u.position||'', u.user_name||'', u.usage_period||'', u.doc_name||'']
}));
res.json(mapped);
} catch (err) {
res.status(500).json({ error: err.message });
}
res.json(result);
} catch (err) { res.status(500).json({ error: err.message }); }
});
// 6. SW 사용자 일괄 저장 (항상 덮어쓰기)
app.post('/api/sw-users/batch', async (req, res) => {
const users = req.body;
const connection = await pool.getConnection();
try {
const connection = await pool.getConnection();
await connection.beginTransaction();
await connection.query('DELETE FROM sw_users');
if (users.length > 0) {
const sql = `
INSERT INTO sw_users (
id, sw_id, corp, dept, team, position, name, usage_period, doc_name
) VALUES ?
`;
const values = users.map(u => [
u.id, u.swId, u.법인, u.부서, u., u.직위, u.이름, u.사용기간, u.신청서명
]);
await connection.query(sql, [values]);
const allUsers = req.body;
if (allUsers.length > 0) {
const values = allUsers.flatMap(item =>
item.userDataList.map(u => [item.sw_id, u.구매법인||u.법인||'', u.부서||'', u.직위||'', u.이름||'', u.사용기간||'', u.신청서명||''])
);
if (values.length > 0) {
await connection.query('INSERT INTO sw_users (sw_id, corp, dept, position, user_name, usage_period, doc_name) VALUES ?', [values]);
}
}
await connection.commit();
res.json({ success: true, count: users.length, mode: 'overwrite' });
} catch (err) {
await connection.rollback();
res.status(500).json({ error: err.message });
} finally {
connection.release();
res.json({ success: true });
} catch (err) { res.status(500).json({ error: err.message }); }
});
// 자산번호 자동 생성 API
app.get('/api/generate-asset-code', async (req, res) => {
const { prefix } = req.query;
if (!prefix) return res.status(400).json({ error: 'Prefix is required' });
try {
const tables = ['server_assets', 'pc_assets', 'storage_assets', 'equip_assets', 'mobile_assets'];
let maxNum = 0;
for (const table of tables) {
const [rows] = await pool.query(
`SELECT asset_code as 자산코드 FROM ${table} WHERE asset_code LIKE ? ORDER BY asset_code DESC LIMIT 1`,
[`${prefix}%`]
);
if (rows.length > 0) {
const lastCode = rows[0].자산코드;
const lastNum = parseInt(lastCode.split('-').pop() || '0');
if (lastNum > maxNum) maxNum = lastNum;
}
}
const nextNum = String(maxNum + 1).padStart(3, '0');
res.json({ nextCode: `${prefix}${nextNum}` });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.listen(PORT, () => {
console.log(`📡 ITAM API Server running on http://localhost:${PORT}`);
console.log(`📡 ITAM Dedicated API Server running on http://localhost:${PORT}`);
});

View File

@@ -1,6 +1,17 @@
import { state } from '../../core/state';
import { HardwareAsset } from '../../core/excelHandler';
import { state, saveHardwareAsset, deleteHardwareAsset } from '../../core/state';
import { HardwareAsset, MasterAssetData } from '../../core/excelHandler';
import { openModal, closeModals } from './BaseModal';
import { createIcons, Paperclip } from 'lucide';
import { CORP_LIST, ORG_LIST, HW_TYPE_LIST, LOCATION_DATA, TYPE_PREFIX_MAP } from './SharedData';
import {
generateOptionsHTML,
setFieldValue,
getFieldValue,
parseAndSetLocation,
bindLocationEvents,
getCombinedLocation,
setEditLock
} from './ModalUtils';
let currentAsset: HardwareAsset | null = null;
let isEditMode = false;
@@ -17,15 +28,38 @@ const HW_MODAL_HTML = `
<input type="hidden" id="hw-asset-id" />
<input type="hidden" id="hw-asset-type" />
<!-- Group 1: 기본 정보 -->
<!-- Group 1: 기본 정보 (Identity) -->
<div class="form-section-title">기본 정보 (Identity)</div>
<div class="form-group">
<label for="hw-법인">법인</label>
<input type="text" id="hw-법인" required />
<label for="hw-법인">구매법인</label>
<select id="hw-법인" required>${generateOptionsHTML(CORP_LIST)}</select>
</div>
<div class="form-group">
<label for="hw-자산코드">자산번호/코드</label>
<input type="text" id="hw-자산코드" required />
<div style="display:flex; gap:0.5rem;">
<input type="text" id="hw-자산코드" readonly placeholder="번호 생성을 클릭하세요" required />
<button type="button" id="btn-generate-hw-code" class="btn btn-outline" style="white-space:nowrap; padding:0 10px; font-size:0.8rem;">번호 생성</button>
</div>
</div>
<div class="form-group">
<label for="hw-현사용조직">현 사용조직</label>
<select id="hw-현사용조직">${generateOptionsHTML(ORG_LIST)}</select>
</div>
<div class="form-group" id="hw-이전사용조직-group">
<label for="hw-이전사용조직">이전 사용조직</label>
<input type="text" id="hw-이전사용조직" readonly />
</div>
<div class="form-group" id="hw-유형-group">
<label for="hw-유형">유형</label>
<select id="hw-유형">${generateOptionsHTML(HW_TYPE_LIST)}</select>
</div>
<div class="form-group" id="hw-상세용도-group" style="display:none;">
<label for="hw-상세용도">상세용도</label>
<select id="hw-상세용도">
<option value="">선택</option>
<option value="서버">서버</option>
<option value="개인PC">개인PC</option>
</select>
</div>
<div class="form-group server-only">
<label for="hw-용도">용도</label>
@@ -35,7 +69,7 @@ const HW_MODAL_HTML = `
<label for="hw-상세">상세 내용</label>
<input type="text" id="hw-상세" />
</div>
<div class="form-group non-server">
<div class="form-group non-server" id="hw-명칭-group">
<label for="hw-명칭">명칭</label>
<input type="text" id="hw-명칭" />
</div>
@@ -44,79 +78,83 @@ const HW_MODAL_HTML = `
<input type="text" id="hw-비고" />
</div>
<!-- Group 2: 네트워크 정보 -->
<div class="form-section-title server-only">네트워크 정보 (Connectivity)</div>
<div class="form-group server-only">
<!-- Group 2: 네트워크 정보 (Connectivity) -->
<div class="form-section-title server-only" id="hw-network-title">네트워크 정보 (Connectivity)</div>
<div class="form-group server-only" id="hw-ip-group">
<label for="hw-IP주소">IP 주소 1</label>
<input type="text" id="hw-IP주소" />
</div>
<div class="form-group server-only">
<div class="form-group server-only" id="hw-ip2-group">
<label for="hw-IP2">IP 주소 2</label>
<input type="text" id="hw-IP2" />
</div>
<div class="form-group server-only">
<div class="form-group server-only" id="hw-remote-group">
<label for="hw-원격접속">원격 도구 (Anydesk/Chrome 등)</label>
<input type="text" id="hw-원격접속" />
</div>
<div class="form-group server-only">
<div class="form-group server-only" id="hw-server-id-group">
<label for="hw-서버ID">서버 ID</label>
<input type="text" id="hw-서버ID" />
</div>
<div class="form-group server-only">
<div class="form-group server-only" id="hw-server-pw-group">
<label for="hw-서버PW">서버 PW</label>
<input type="text" id="hw-서버PW" />
</div>
<div class="form-group non-server" id="hw-IP주소-group">
<div class="form-group non-server" id="hw-ip-non-server-group">
<label for="hw-IP주소-non-server">IP 주소</label>
<input type="text" id="hw-IP주소-non-server" />
</div>
<!-- Group 3: 시스템 사양 -->
<div class="form-section-title">시스템 사양 (Specifications)</div>
<div class="form-group">
<!-- Group 3: 시스템 사양 (Specifications) -->
<div class="form-section-title" id="hw-spec-title">시스템 사양 (Specifications)</div>
<div class="form-group" id="hw-model-group">
<label for="hw-모델명">모델명</label>
<input type="text" id="hw-모델명" />
</div>
<div class="form-group">
<div class="form-group" id="hw-os-group">
<label for="hw-OS">운영체제 (OS)</label>
<input type="text" id="hw-OS" />
</div>
<div class="form-group">
<div class="form-group" id="hw-cpu-group">
<label for="hw-CPU">CPU 사양</label>
<input type="text" id="hw-CPU" />
</div>
<div class="form-group">
<div class="form-group" id="hw-ram-group">
<label for="hw-RAM">RAM 용량</label>
<input type="text" id="hw-RAM" />
</div>
<div class="form-group">
<div class="form-group" id="hw-ssd1-group">
<label for="hw-SSD1">Storage 1 (SSD/HDD)</label>
<input type="text" id="hw-SSD1" />
</div>
<div class="form-group">
<div class="form-group" id="hw-ssd2-group">
<label for="hw-SSD2">Storage 2 (SSD/HDD)</label>
<input type="text" id="hw-SSD2" />
</div>
<div class="form-group server-only">
<div class="form-group server-only" id="hw-monitoring-group">
<label for="hw-모니터링">모니터링 여부</label>
<input type="text" id="hw-모니터링" />
</div>
<div class="form-group" id="hw-비품유형-group" style="display:none;">
<label for="hw-비품유형">비품유형</label>
<select id="hw-비품유형">
<option value="노트북">노트북</option><option value="태블릿">태블릿</option><option value="휴대폰">휴대폰</option>
</select>
</div>
<div class="form-group full-width non-server">
<div class="form-group full-width non-server" id="hw-hwspec-group">
<label for="hw-HW사양">H/W 사양 상세</label>
<textarea id="hw-HW사양" rows="2"></textarea>
</div>
<!-- Group 4: 관리 및 운영 -->
<div class="form-section-title">관리 및 운영 (Operation)</div>
<div class="form-group">
<label for="hw-위치">설치위치</label>
<input type="text" id="hw-위치" />
<!-- Group 4: 관리 및 운영 (Operation) -->
<div class="form-section-title" id="hw-op-title">관리 및 운영 (Operation)</div>
<div class="form-group hw-location-field">
<label for="hw-위치-빌딩">설치위치 (건물)</label>
<select id="hw-위치-빌딩">${generateOptionsHTML(Object.keys(LOCATION_DATA))}</select>
</div>
<div class="form-group hw-location-field">
<label for="hw-위치-상세">상세 위치</label>
<select id="hw-위치-상세">
<option value="">건물을 먼저 선택하세요</option>
</select>
</div>
<div class="form-group" id="hw-위치-기타-group" style="display:none;">
<label for="hw-위치-기타">직접 입력 (기타)</label>
<input type="text" id="hw-위치-기타" placeholder="상세 위치를 입력하세요" />
</div>
<div class="form-group">
<label for="hw-담당자_정">담당자 (정)</label>
@@ -126,13 +164,13 @@ const HW_MODAL_HTML = `
<label for="hw-담당자_부">담당자 (부)</label>
<input type="text" id="hw-담당자_부" />
</div>
<div class="form-group non-server">
<div class="form-group non-server" id="hw-purchase-date-group">
<label for="hw-구매일">구매일</label>
<input type="text" id="hw-구매일" />
</div>
<div class="form-group non-server">
<div class="form-group non-server" id="hw-price-group">
<label for="hw-금액">금액</label>
<input type="text" id="hw-금액" oninput="this.value = this.value.replace(/[^0-9]/g, '').replace(/\\B(?=(\\d{3})+(?!\d))/g, ',')" />
<input type="text" id="hw-금액" oninput="this.value = this.value.replace(/[^0-9]/g, '').replace(/\\\\B(?=(\\\\d{3})+(?!\d))/g, ',')" />
</div>
<div class="form-group full-width">
<label>품의서 (파일 증빙)</label>
@@ -155,180 +193,275 @@ const HW_MODAL_HTML = `
</div>
`;
export function openHwModal(asset: HardwareAsset) {
export function openHwModal(asset: HardwareAsset, mode: 'view' | 'add' = 'view') {
currentAsset = asset;
isEditMode = false;
const modal = document.getElementById('hw-asset-modal')!;
const form = document.getElementById('hw-asset-form') as HTMLFormElement;
const saveBtn = document.getElementById('btn-save-hw-asset')!;
const revertBtn = document.getElementById('btn-revert-hw-edit')!;
form.reset();
form.classList.remove('is-edit-mode');
form.classList.add('is-view-mode');
saveBtn.textContent = '수정';
revertBtn.classList.add('hidden');
// 1. 잠금 상태 통합 제어 (데이터 유무가 아닌 호출 mode에만 의존)
setEditLock('hw-asset-form', mode, {
saveBtnId: 'btn-save-hw-asset',
revertBtnId: 'btn-revert-hw-edit',
generateBtnId: 'btn-generate-hw-code'
});
isEditMode = (mode === 'add');
// 2. 데이터 바인딩
fillHwFormData(asset);
modal.classList.remove('hidden');
applyTypeSpecificUI(asset.type);
createIcons({ icons: { Paperclip } });
}
function fillHwFormData(asset: HardwareAsset) {
(document.getElementById('hw-asset-id') as HTMLInputElement).value = asset.id;
(document.getElementById('hw-asset-type') as HTMLInputElement).value = asset.type;
(document.getElementById('hw-법인') as HTMLInputElement).value = asset.;
(document.getElementById('hw-자산코드') as HTMLInputElement).value = asset.;
(document.getElementById('hw-위치') as HTMLInputElement).value = asset.;
(document.getElementById('hw-모델명') as HTMLInputElement).value = asset. || '';
(document.getElementById('hw-OS') as HTMLInputElement).value = asset.OS || '';
(document.getElementById('hw-CPU') as HTMLInputElement).value = asset.CPU || '';
(document.getElementById('hw-RAM') as HTMLInputElement).value = asset.RAM || '';
(document.getElementById('hw-SSD1') as HTMLInputElement).value = asset.SSD1 || '';
(document.getElementById('hw-SSD2') as HTMLInputElement).value = asset.SSD2 || '';
(document.getElementById('hw-담당자_정') as HTMLInputElement).value = asset._정 || asset. || '';
(document.getElementById('hw-담당자_부') as HTMLInputElement).value = asset._부 || '';
(document.getElementById('hw-품의서명') as HTMLElement).textContent = asset. || '';
function applyTypeSpecificUI(type: string) {
const detailPurpose = getFieldValue('hw-상세용도');
const form = document.getElementById('hw-asset-form') as HTMLFormElement;
if (!form) return;
const serverOnly = document.querySelectorAll('.server-only');
const nonServer = document.querySelectorAll('.non-server');
const equipGroup = document.getElementById('hw-비품유형-group')!;
const locationFields = document.querySelectorAll('.hw-location-field');
const groups: Record<string, HTMLElement | null> = {
detailPurpose: document.getElementById('hw-상세용도-group'),
model: document.getElementById('hw-model-group'),
ip: document.getElementById('hw-ip-group'),
ip2: document.getElementById('hw-ip2-group'),
remote: document.getElementById('hw-remote-group'),
os: document.getElementById('hw-os-group'),
cpu: document.getElementById('hw-cpu-group'),
ram: document.getElementById('hw-ram-group'),
ssd1: document.getElementById('hw-ssd1-group'),
ssd2: document.getElementById('hw-ssd2-group'),
monitoring: document.getElementById('hw-monitoring-group'),
serverId: document.getElementById('hw-server-id-group'),
serverPw: document.getElementById('hw-server-pw-group'),
hwSpec: document.getElementById('hw-hwspec-group'),
ipNonServer: document.getElementById('hw-ip-non-server-group'),
type: document.getElementById('hw-유형-group'),
networkTitle: document.getElementById('hw-network-title'),
specTitle: document.getElementById('hw-spec-title'),
opTitle: document.getElementById('hw-op-title')
};
if (asset.type === '서버') {
// 1. 초기화 (모든 유동 섹션 숨김)
serverOnly.forEach(el => (el as HTMLElement).style.display = 'none');
nonServer.forEach(el => (el as HTMLElement).style.display = 'none');
locationFields.forEach(el => (el as HTMLElement).style.display = 'none');
Object.values(groups).forEach(g => { if (g) g.style.display = 'none'; });
if (groups.type) groups.type.style.display = 'flex';
if (groups.opTitle) groups.opTitle.style.display = 'flex';
// 2. 유형별 정밀 규칙 적용 (사용자 정의 100% 일치)
if (type === '서버') {
serverOnly.forEach(el => (el as HTMLElement).style.display = 'flex');
nonServer.forEach(el => (el as HTMLElement).style.display = 'none');
equipGroup.style.display = 'none';
(document.getElementById('hw-용도') as HTMLInputElement).value = asset. || '';
(document.getElementById('hw-상세') as HTMLInputElement).value = asset. || '';
(document.getElementById('hw-비고') as HTMLInputElement).value = asset. || '';
(document.getElementById('hw-IP주소') as HTMLInputElement).value = asset.IP주소 || '';
(document.getElementById('hw-IP2') as HTMLInputElement).value = (asset as any).IP2 || '';
(document.getElementById('hw-원격접속') as HTMLInputElement).value = asset. || '';
(document.getElementById('hw-서버ID') as HTMLInputElement).value = (asset as any).ID || '';
(document.getElementById('hw-서버PW') as HTMLInputElement).value = (asset as any).PW || '';
(document.getElementById('hw-모니터링') as HTMLInputElement).value = asset. || '';
} else {
serverOnly.forEach(el => (el as HTMLElement).style.display = 'none');
locationFields.forEach(el => (el as HTMLElement).style.display = 'flex');
Object.values(groups).forEach(g => { if (g) g.style.display = 'flex'; });
}
else if (['스토리지', 'NAS', 'DAS'].includes(type)) {
serverOnly.forEach(el => (el as HTMLElement).style.display = 'flex');
locationFields.forEach(el => (el as HTMLElement).style.display = 'flex');
if (groups.networkTitle) groups.networkTitle.style.display = 'flex';
if (groups.ip) groups.ip.style.display = 'flex';
if (groups.specTitle) groups.specTitle.style.display = 'flex';
if (groups.model) groups.model.style.display = 'flex';
if (groups.ssd1) groups.ssd1.style.display = 'flex';
if (groups.ssd2) groups.ssd2.style.display = 'flex';
}
else if (type === 'PC' || type === '노트북') {
if (type === 'PC' && groups.detailPurpose) groups.detailPurpose.style.display = 'flex';
nonServer.forEach(el => (el as HTMLElement).style.display = 'flex');
(document.getElementById('hw-명칭') as HTMLInputElement).value = asset. || '';
(document.getElementById('hw-구매일') as HTMLInputElement).value = asset. || '';
(document.getElementById('hw-금액') as HTMLInputElement).value = asset. || '';
(document.getElementById('hw-HW사양') as HTMLTextAreaElement).value = asset.HW사양 || '';
(document.getElementById('hw-IP주소-non-server') as HTMLInputElement).value = asset.IP주소 || '';
if (asset.type === '전산비품') {
equipGroup.style.display = 'flex';
(document.getElementById('hw-비품유형') as HTMLSelectElement).value = asset. || '노트북';
} else {
equipGroup.style.display = 'none';
if (groups.specTitle) groups.specTitle.style.display = 'flex';
['model', 'os', 'cpu', 'ram', 'ssd1', 'ssd2', 'hwSpec', 'ipNonServer'].forEach(k => {
if (groups[k]) groups[k]!.style.display = 'flex';
});
if (type === 'PC' && detailPurpose === '서버') {
locationFields.forEach(el => (el as HTMLElement).style.display = 'flex');
if (groups.networkTitle) groups.networkTitle.style.display = 'flex';
['ip', 'ip2', 'remote', 'serverId', 'serverPw', 'monitoring'].forEach(k => {
if (groups[k]) groups[k]!.style.display = 'flex';
});
if (groups.ipNonServer) groups.ipNonServer.style.display = 'none';
}
}
else if (['CPU', 'GPU', '모바일'].includes(type)) {
if (groups.specTitle) groups.specTitle.style.display = 'flex';
if (groups.model) groups.model.style.display = 'flex';
}
else if (type === 'RAM') {
if (groups.specTitle) groups.specTitle.style.display = 'flex';
if (groups.ram) groups.ram.style.display = 'flex';
}
else if (type === 'HDD') {
if (groups.specTitle) groups.specTitle.style.display = 'flex';
if (groups.ssd1) groups.ssd1.style.display = 'flex';
}
else if (type === '태블릿') {
if (groups.specTitle) groups.specTitle.style.display = 'flex';
if (groups.model) groups.model.style.display = 'flex';
if (groups.ssd1) groups.ssd1.style.display = 'flex';
}
}
function fillHwFormData(asset: HardwareAsset) {
setFieldValue('hw-asset-id', asset.id);
setFieldValue('hw-asset-type', asset.type);
setFieldValue('hw-법인', asset.);
setFieldValue('hw-자산코드', asset.);
setFieldValue('hw-현사용조직', asset.);
setFieldValue('hw-이전사용조직', asset.);
setFieldValue('hw-상세용도', (asset as any).);
parseAndSetLocation(asset., 'hw-위치-빌딩', 'hw-위치-상세', 'hw-위치-기타-group', 'hw-위치-기타');
setFieldValue('hw-모델명', asset.);
setFieldValue('hw-OS', asset.OS);
setFieldValue('hw-CPU', asset.CPU);
setFieldValue('hw-RAM', asset.RAM);
setFieldValue('hw-SSD1', asset.SSD1);
setFieldValue('hw-SSD2', asset.SSD2);
setFieldValue('hw-담당자_정', asset._정 || asset.);
setFieldValue('hw-담당자_부', asset._부);
const isServerGrade = asset.type === '서버' || (asset as any). === '서버' || asset.type === '스토리지' || ['NAS', 'DAS'].includes(asset.type);
if (isServerGrade) {
setFieldValue('hw-용도', asset. || (asset as any).purpose);
setFieldValue('hw-상세', asset. || (asset as any).details);
setFieldValue('hw-비고', asset. || (asset as any).remarks);
setFieldValue('hw-구매일', asset. || (asset as any).purchase_date);
setFieldValue('hw-유형', asset.storage유형 || asset.type);
setFieldValue('hw-IP주소', asset.IP주소 || (asset as any).ip_address);
setFieldValue('hw-IP2', (asset as any).IP2 || (asset as any).ip_address_2);
setFieldValue('hw-원격접속', asset. || (asset as any).remote_tool);
setFieldValue('hw-서버ID', (asset as any).ID || (asset as any).server_id);
setFieldValue('hw-서버PW', (asset as any).PW || (asset as any).server_pw);
setFieldValue('hw-모니터링', asset. || (asset as any).monitoring);
} else {
setFieldValue('hw-명칭', asset. || asset.);
setFieldValue('hw-구매일', asset. || (asset as any).purchase_date);
setFieldValue('hw-금액', asset. || (asset as any).price);
setFieldValue('hw-HW사양', asset.HW사양 || asset. || (asset as any).details);
setFieldValue('hw-IP주소-non-server', asset.IP주소 || (asset as any).ip_address);
}
}
export function initHwModal(onSave: () => void, closeModals: () => void) {
// HTML 주입
if (!document.getElementById('hw-asset-modal')) {
document.body.insertAdjacentHTML('beforeend', HW_MODAL_HTML);
}
const modal = document.getElementById('hw-asset-modal')!;
const form = document.getElementById('hw-asset-form') as HTMLFormElement;
const closeBtn = document.getElementById('btn-close-hw-modal')!;
const cancelBtn = document.getElementById('btn-cancel-hw-modal')!;
const saveBtn = document.getElementById('btn-save-hw-asset')!;
const revertBtn = document.getElementById('btn-revert-hw-edit')!;
const deleteBtn = document.getElementById('btn-delete-hw-asset')!;
const typeSelect = document.getElementById('hw-유형') as HTMLSelectElement;
const detailPurposeSelect = document.getElementById('hw-상세용도') as HTMLSelectElement;
[typeSelect, detailPurposeSelect].forEach(el => {
el?.addEventListener('change', () => applyTypeSpecificUI(typeSelect.value));
});
const closeModal = () => {
closeModals();
bindLocationEvents('hw-위치-빌딩', 'hw-위치-상세', 'hw-위치-기타-group', 'hw-위치-기타');
const closeModalAction = () => { closeModals(); isEditMode = false; };
document.getElementById('btn-close-hw-modal')?.addEventListener('click', closeModalAction);
document.getElementById('btn-cancel-hw-modal')?.addEventListener('click', closeModalAction);
revertBtn.addEventListener('click', () => {
setEditLock('hw-asset-form', 'view', {
saveBtnId: 'btn-save-hw-asset',
revertBtnId: 'btn-revert-hw-edit',
generateBtnId: 'btn-generate-hw-code'
});
isEditMode = false;
};
if (currentAsset) fillHwFormData(currentAsset);
});
const switchToViewMode = () => {
isEditMode = false;
form.classList.remove('is-edit-mode');
form.classList.add('is-view-mode');
saveBtn.textContent = '수정';
revertBtn.classList.add('hidden');
if (currentAsset) fillHwFormData(currentAsset);
};
closeBtn.addEventListener('click', closeModal);
cancelBtn.addEventListener('click', closeModal);
modal.addEventListener('click', (e) => { if (e.target === modal) closeModal(); });
revertBtn.addEventListener('click', () => { switchToViewMode(); });
document.getElementById('btn-generate-hw-code')?.addEventListener('click', async () => {
const typeValue = typeSelect.value;
const purchaseDate = getFieldValue('hw-구매일');
const typeCode = TYPE_PREFIX_MAP[typeValue] || 'ETC';
const dateStr = purchaseDate.replace(/[^0-9]/g, '');
if (dateStr.length < 4) { alert('올바른 구매일(연월)을 입력해주세요.'); return; }
const prefix = `${typeCode}-${dateStr.substring(2, 6)}-`;
try {
const res = await fetch(`http://localhost:3000/api/generate-asset-code?prefix=${prefix}`);
const data = await res.json();
if (data.nextCode) setFieldValue('hw-자산코드', data.nextCode);
} catch (err) { alert('자산번호 생성에 실패했습니다.'); }
});
saveBtn.addEventListener('click', () => {
if (!currentAsset) return;
if (!isEditMode) {
setEditLock('hw-asset-form', 'edit', {
saveBtnId: 'btn-save-hw-asset',
revertBtnId: 'btn-revert-hw-edit'
});
isEditMode = true;
form.classList.remove('is-view-mode');
form.classList.add('is-edit-mode');
saveBtn.textContent = '저장';
revertBtn.classList.remove('hidden');
return;
}
const assetId = (document.getElementById('hw-asset-id') as HTMLInputElement).value;
const type = (document.getElementById('hw-asset-type') as HTMLInputElement).value;
const updated: HardwareAsset = {
const type = typeSelect.value;
const detailPurpose = detailPurposeSelect.value;
const updated: any = {
...currentAsset,
: (document.getElementById('hw-법인') as HTMLInputElement).value,
: (document.getElementById('hw-자산코드') as HTMLInputElement).value,
: (document.getElementById('hw-위치') as HTMLInputElement).value,
: (document.getElementById('hw-모델명') as HTMLInputElement).value,
OS: (document.getElementById('hw-OS') as HTMLInputElement).value,
CPU: (document.getElementById('hw-CPU') as HTMLInputElement).value,
RAM: (document.getElementById('hw-RAM') as HTMLInputElement).value,
SSD1: (document.getElementById('hw-SSD1') as HTMLInputElement).value,
SSD2: (document.getElementById('hw-SSD2') as HTMLInputElement).value,
_정: (document.getElementById('hw-담당자_정') as HTMLInputElement).value,
: (document.getElementById('hw-담당자_정') as HTMLInputElement).value,
_부: (document.getElementById('hw-담당자_') as HTMLInputElement).value,
법인: getFieldValue('hw-법인'),
자산코드: getFieldValue('hw-자산코드'),
현사용조직: getFieldValue('hw-현사용조직'),
이전사용조직: getFieldValue('hw-이전사용조직'),
위치: getCombinedLocation('hw-위치-빌딩', 'hw-위치-상세', 'hw-위치-기타'),
모델명: getFieldValue('hw-모델명'),
OS: getFieldValue('hw-OS'),
CPU: getFieldValue('hw-CPU'),
RAM: getFieldValue('hw-RAM'),
SSD1: getFieldValue('hw-SSD1'),
SSD2: getFieldValue('hw-SSD2'),
담당자_정: getFieldValue('hw-담당자_'),
관리자: getFieldValue('hw-담당자_정'),
담당자_부: getFieldValue('hw-담당자_부'),
type: type,
상세용도: detailPurpose
};
if (type === '서버') {
updated. = (document.getElementById('hw-용도') as HTMLInputElement).value;
updated. = (document.getElementById('hw-상세') as HTMLInputElement).value;
updated. = (document.getElementById('hw-비고') as HTMLInputElement).value;
updated.IP주소 = (document.getElementById('hw-IP주소') as HTMLInputElement).value;
(updated as any).IP2 = (document.getElementById('hw-IP2') as HTMLInputElement).value;
updated. = (document.getElementById('hw-원격접속') as HTMLInputElement).value;
(updated as any).ID = (document.getElementById('hw-서버ID') as HTMLInputElement).value;
(updated as any).PW = (document.getElementById('hw-서버PW') as HTMLInputElement).value;
updated. = (document.getElementById('hw-모니터링') as HTMLInputElement).value;
if (type === '서버' || (type === 'PC' && detailPurpose === '서버') || ['스토리지', 'NAS', 'DAS'].includes(type)) {
updated. = getFieldValue('hw-용도');
updated. = getFieldValue('hw-상세');
updated. = getFieldValue('hw-비고');
updated.storage유형 = type;
updated.IP주소 = getFieldValue('hw-IP주소');
updated.IP2 = getFieldValue('hw-IP2');
updated. = getFieldValue('hw-원격접속');
updated.ID = getFieldValue('hw-서버ID');
updated.PW = getFieldValue('hw-서버PW');
updated. = getFieldValue('hw-모니터링');
} else {
updated. = (document.getElementById('hw-명칭') as HTMLInputElement).value;
updated. = (document.getElementById('hw-구매일') as HTMLInputElement).value;
updated. = (document.getElementById('hw-금액') as HTMLInputElement).value;
updated.HW사양 = (document.getElementById('hw-HW사양') as HTMLTextAreaElement).value;
updated.IP주소 = (document.getElementById('hw-IP주소-non-server') as HTMLInputElement).value;
if (type === '전산비품') {
updated. = (document.getElementById('hw-비품유형') as HTMLSelectElement).value;
}
updated. = getFieldValue('hw-명칭');
updated. = getFieldValue('hw-구매일');
updated. = getFieldValue('hw-금액');
updated.HW사양 = getFieldValue('hw-HW사양');
updated.IP주소 = getFieldValue('hw-IP주소-non-server');
}
const idx = state.masterData.hw.findIndex(a => a.id === assetId);
if (idx > -1) {
state.masterData.hw[idx] = updated;
onSave();
switchToViewMode();
}
saveHardwareAsset(updated);
onSave();
setEditLock('hw-asset-form', 'view', {
saveBtnId: 'btn-save-hw-asset',
revertBtnId: 'btn-revert-hw-edit'
});
isEditMode = false;
});
deleteBtn.addEventListener('click', () => {
if (!currentAsset) return;
if (confirm('정말로 이 자산을 삭제하시겠습니까?')) {
state.masterData.hw = state.masterData.hw.filter(a => a.id !== currentAsset!.id);
deleteHardwareAsset(currentAsset.id);
onSave();
closeModal();
closeModals();
}
});
}

View File

@@ -0,0 +1,135 @@
import { LOCATION_DATA } from './SharedData';
/**
* 모달 조작 및 UI 생성을 위한 공통 유틸리티
*/
// 1. Select 박스의 Option HTML 생성
export function generateOptionsHTML(list: string[], defaultValue: string = '', includeSelectHint: boolean = true): string {
let html = includeSelectHint ? '<option value="">선택</option>' : '';
html += list.map(item => `<option value="${item}" ${item === defaultValue ? 'selected' : ''}>${item}</option>`).join('');
return html;
}
// 2. 안전하게 폼 필드 값 설정 (Null 에러 방지)
export function setFieldValue(id: string, value: any) {
const el = document.getElementById(id) as HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;
if (el) {
el.value = value || '';
}
}
// 3. 안전하게 폼 필드 값 읽기
export function getFieldValue(id: string): string {
const el = document.getElementById(id) as HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;
return el ? el.value : '';
}
// 4. 위치 정보 파싱 및 UI 세팅
export function parseAndSetLocation(locationStr: string, bldgId: string, detailId: string, etcGroupId: string, etcInputId: string) {
const bldgSelect = document.getElementById(bldgId) as HTMLSelectElement;
const detailSelect = document.getElementById(detailId) as HTMLSelectElement;
const etcGroup = document.getElementById(etcGroupId);
const etcInput = document.getElementById(etcInputId) as HTMLInputElement;
if (!bldgSelect || !detailSelect) return;
// 초기화
bldgSelect.value = '';
detailSelect.innerHTML = '<option value="">선택</option>';
if (etcGroup) etcGroup.style.display = 'none';
if (!locationStr) return;
const parts = locationStr.split(' ');
const bldg = parts[0];
if (LOCATION_DATA[bldg]) {
bldgSelect.value = bldg;
// 상세 목록 갱신
detailSelect.innerHTML = generateOptionsHTML(LOCATION_DATA[bldg]);
const detail = parts[1];
if (detail) {
detailSelect.value = detail;
if (detail === '기타' && etcGroup && etcInput) {
etcGroup.style.display = 'flex';
etcInput.value = parts.slice(2).join(' ');
}
}
}
}
// 5. 위치 종속성(Cascade) 이벤트 바인딩
export function bindLocationEvents(bldgId: string, detailId: string, etcGroupId: string, etcInputId: string) {
const bldgSelect = document.getElementById(bldgId) as HTMLSelectElement;
const detailSelect = document.getElementById(detailId) as HTMLSelectElement;
const etcGroup = document.getElementById(etcGroupId);
const etcInput = document.getElementById(etcInputId) as HTMLInputElement;
if (!bldgSelect || !detailSelect) return;
bldgSelect.addEventListener('change', () => {
const bldg = bldgSelect.value;
detailSelect.innerHTML = generateOptionsHTML(LOCATION_DATA[bldg] || []);
if (etcGroup) etcGroup.style.display = 'none';
if (etcInput) etcInput.value = '';
});
detailSelect.addEventListener('change', () => {
if (etcGroup) {
etcGroup.style.display = detailSelect.value === '기타' ? 'flex' : 'none';
}
});
}
// 6. 위치 문자열 조합 (저장용)
export function getCombinedLocation(bldgId: string, detailId: string, etcInputId: string): string {
const bldg = getFieldValue(bldgId);
const detail = getFieldValue(detailId);
const etc = getFieldValue(etcInputId);
let combined = bldg;
if (detail) combined += ` ${detail}`;
if (detail === '기타' && etc) combined += ` ${etc}`;
return combined.trim();
}
// 7. 조회/수정 모드 UI 통합 제어
export function setEditLock(
formId: string,
mode: 'view' | 'add' | 'edit',
options: {
saveBtnId: string,
revertBtnId: string,
generateBtnId?: string
}
) {
const form = document.getElementById(formId) as HTMLFormElement;
const saveBtn = document.getElementById(options.saveBtnId);
const revertBtn = document.getElementById(options.revertBtnId);
const generateBtn = options.generateBtnId ? document.getElementById(options.generateBtnId) : null;
if (!form || !saveBtn || !revertBtn) return;
if (mode === 'add' || mode === 'edit') {
// 편집 모드 활성화
form.classList.remove('is-view-mode');
form.classList.add('is-edit-mode');
saveBtn.textContent = '저장';
revertBtn.classList.toggle('hidden', mode === 'add'); // 신규 추가 시에는 취소 버튼 숨김 (닫기가 대신함)
// 번호 생성 버튼은 '추가' 시에만 노출
if (generateBtn) generateBtn.classList.toggle('hidden', mode !== 'add');
} else {
// 조회 모드 (잠금)
form.classList.remove('is-edit-mode');
form.classList.add('is-view-mode');
saveBtn.textContent = '수정';
revertBtn.classList.add('hidden');
// 조회 모드에서는 번호 생성 버튼 무조건 숨김
if (generateBtn) generateBtn.classList.add('hidden');
}
}

View File

@@ -1,6 +1,19 @@
import { state } from '../../core/state';
import { HardwareAsset, HardwareLog } from '../../core/excelHandler';
import { openModal } from './BaseModal';
import { state, saveHardwareAsset, deleteHardwareAsset } from '../../core/state';
import { HardwareAsset } from '../../core/excelHandler';
import { openModal, closeModals } from './BaseModal';
import { createIcons, History, X, Paperclip } from 'lucide';
import { CORP_LIST, ORG_LIST, HW_TYPE_LIST, LOCATION_DATA } from './SharedData';
import {
generateOptionsHTML,
setFieldValue,
getFieldValue,
parseAndSetLocation,
bindLocationEvents,
getCombinedLocation
} from './ModalUtils';
let currentAsset: HardwareAsset | null = null;
let isEditMode = false;
const PC_MODAL_HTML = `
<div id="pc-asset-modal" class="modal-overlay hidden">
@@ -15,78 +28,93 @@ const PC_MODAL_HTML = `
<form id="pc-asset-form" class="grid-form">
<input type="hidden" id="pc-asset-id" />
<input type="hidden" id="pc-asset-type" value="개인PC" />
<div class="form-section-title">기본 정보 (Identity)</div>
<div class="form-group">
<label for="pc-법인">법인</label>
<select id="pc-법인" required>
<option value="한맥">한맥 (HM)</option><option value="삼안">삼안 (SM)</option><option value="바론">바론 (BR)</option>
<label for="pc-법인">구매법인</label>
<select id="pc-법인" required>${generateOptionsHTML(CORP_LIST)}</select>
</div>
<div class="form-group">
<label for="pc-자산코드">자산번호/코드</label>
<input type="text" id="pc-자산코드" readonly placeholder="자동 생성됩니다" required />
</div>
<div class="form-group">
<label for="pc-유형">유형</label>
<select id="pc-유형">${generateOptionsHTML(HW_TYPE_LIST)}</select>
</div>
<div class="form-group">
<label for="pc-상세용도">상세용도</label>
<select id="pc-상세용도">
<option value="개인PC">개인PC</option>
<option value="서버">서버</option>
</select>
</div>
<div class="form-group">
<label for="pc-자산코드">자산코드</label>
<input type="text" id="pc-자산코드" placeholder="ex) HM-PC-2018-001" required />
</div>
<div class="form-group">
<label for="pc-사용자">사용자</label>
<input type="text" id="pc-사용자" required />
</div>
<div class="form-group">
<label for="pc-위치">위치</label>
<input type="text" id="pc-위치" />
<label for="pc-현사용조직">현 사용조직</label>
<select id="pc-현사용조직">${generateOptionsHTML(ORG_LIST)}</select>
</div>
<div class="form-group" id="pc-이전사용조직-group">
<label for="pc-이전사용조직">이전 사용조직</label>
<input type="text" id="pc-이전사용조직" readonly />
</div>
<div class="form-section-title">시스템 사양 (Specifications)</div>
<div class="form-group">
<label for="pc-CPU">CPU</label>
<label for="pc-모델명">모델명</label>
<input type="text" id="pc-모델명" />
</div>
<div class="form-group">
<label for="pc-OS">운영체제 (OS)</label>
<input type="text" id="pc-OS" />
</div>
<div class="form-group">
<label for="pc-CPU">CPU 사양</label>
<input type="text" id="pc-CPU" />
</div>
<div class="form-group">
<label for="pc-GPU">GPU</label>
<input type="text" id="pc-GPU" />
</div>
<div class="form-group">
<label for="pc-RAM">RAM</label>
<label for="pc-RAM">RAM 용량</label>
<input type="text" id="pc-RAM" />
</div>
<div class="form-group">
<label for="pc-SSD1">SSD1</label>
<label for="pc-SSD1">Storage 1 (SSD/HDD)</label>
<input type="text" id="pc-SSD1" />
</div>
<div class="form-group">
<label for="pc-SSD2">SSD2</label>
<label for="pc-SSD2">Storage 2 (SSD/HDD)</label>
<input type="text" id="pc-SSD2" />
</div>
<div class="form-group">
<label for="pc-HDD1">HDD1</label>
<input type="text" id="pc-HDD1" />
<div class="form-section-title" id="pc-location-title">관리 및 운영 (Operation)</div>
<div class="form-group pc-location-field">
<label for="pc-위치-빌딩">설치위치 (건물)</label>
<select id="pc-위치-빌딩">${generateOptionsHTML(Object.keys(LOCATION_DATA))}</select>
</div>
<div class="form-group">
<label for="pc-HDD2">HDD2</label>
<input type="text" id="pc-HDD2" />
<div class="form-group pc-location-field">
<label for="pc-위치-상세">상세 위치</label>
<select id="pc-위치-상세">
<option value="">건물을 먼저 선택하세요</option>
</select>
</div>
<div class="form-group" id="pc-위치-기타-group" style="display:none;">
<label for="pc-위치-기타">직접 입력 (기타)</label>
<input type="text" id="pc-위치-기타" />
</div>
<div class="form-group">
<label for="pc-구매일">구매일</label>
<input type="text" id="pc-구매일" placeholder="ex) 2024-01-01" />
<input type="text" id="pc-구매일" />
</div>
<div class="form-group">
<label for="pc-금액">금액</label>
<input type="text" id="pc-금액" placeholder="ex) 1,000,000" oninput="this.value = this.value.replace(/[^0-9]/g, '').replace(/\\B(?=(\\d{3})+(?!\d))/g, ',')" />
<input type="text" id="pc-금액" oninput="this.value = this.value.replace(/[^0-9]/g, '').replace(/\\\\B(?=(\\\\d{3})+(?!\d))/g, ',')" />
</div>
<div class="form-group">
<label for="pc-납품업체">납품업체</label>
<input type="text" id="pc-납품업체" />
</div>
<div class="form-group full-width">
<label>품의서 (파일)</label>
<div style="display:flex; align-items:center; gap:0.5rem;">
@@ -110,7 +138,7 @@ const PC_MODAL_HTML = `
<button id="btn-delete-pc-asset" class="btn btn-outline btn-danger">삭제</button>
<div class="footer-actions">
<button id="btn-revert-pc-edit" class="btn btn-outline hidden">수정 취소</button>
<button id="btn-close-pc-footer" class="btn btn-outline">닫기</button>
<button id="btn-cancel-pc-modal" class="btn btn-outline">닫기</button>
<button id="btn-save-pc-asset" class="btn btn-primary">수정</button>
</div>
</div>
@@ -118,225 +146,217 @@ const PC_MODAL_HTML = `
</div>
`;
export function initPcModal(renderContent: () => void, closeModals: () => void) {
export function openPcModal(asset: HardwareAsset, mode: 'view' | 'add' = 'view') {
currentAsset = asset;
const modal = document.getElementById('pc-asset-modal');
if (!modal) return;
const form = document.getElementById('pc-asset-form') as HTMLFormElement;
const saveBtn = document.getElementById('btn-save-pc-asset')!;
const revertBtn = document.getElementById('btn-revert-pc-edit')!;
if (form) form.reset();
if (mode === 'add') {
isEditMode = true;
if (form) {
form.classList.remove('is-view-mode');
form.classList.add('is-edit-mode');
}
saveBtn.textContent = '저장';
revertBtn.classList.add('hidden');
const prevOrgGroup = document.getElementById('pc-이전사용조직-group');
if (prevOrgGroup) prevOrgGroup.style.display = 'none';
} else {
isEditMode = false;
if (form) {
form.classList.remove('is-edit-mode');
form.classList.add('is-view-mode');
}
saveBtn.textContent = '수정';
revertBtn.classList.add('hidden');
const prevOrgGroup = document.getElementById('pc-이전사용조직-group');
if (prevOrgGroup) prevOrgGroup.style.display = 'flex';
}
fillFormData(asset);
renderHistory(asset.id);
modal.classList.remove('hidden');
applyPcTypeSpecificUI();
createIcons({ icons: { X, History, Paperclip } });
}
function applyPcTypeSpecificUI() {
const type = getFieldValue('pc-유형');
const detailPurpose = getFieldValue('pc-상세용도');
const modelGroup = document.getElementById('pc-모델명')?.closest('.form-group') as HTMLElement;
const osGroup = document.getElementById('pc-OS')?.closest('.form-group') as HTMLElement;
const cpuGroup = document.getElementById('pc-CPU')?.closest('.form-group') as HTMLElement;
const ramGroup = document.getElementById('pc-RAM')?.closest('.form-group') as HTMLElement;
const ssd1Group = document.getElementById('pc-SSD1')?.closest('.form-group') as HTMLElement;
const ssd2Group = document.getElementById('pc-SSD2')?.closest('.form-group') as HTMLElement;
const locationFields = document.querySelectorAll('.pc-location-field');
const etcGroup = document.getElementById('pc-위치-기타-group');
// 초기화 (숨김)
[modelGroup, osGroup, cpuGroup, ramGroup, ssd1Group, ssd2Group].forEach(g => { if(g) g.style.display = 'none'; });
locationFields.forEach(el => (el as HTMLElement).style.display = 'none');
if (etcGroup) etcGroup.style.display = 'none';
if (type === '서버') {
[modelGroup, osGroup, cpuGroup, ramGroup, ssd1Group, ssd2Group].forEach(g => { if(g) g.style.display = 'flex'; });
locationFields.forEach(el => (el as HTMLElement).style.display = 'flex');
}
else if (['스토리지', 'NAS', 'DAS'].includes(type)) {
[modelGroup, ssd1Group, ssd2Group].forEach(g => { if(g) g.style.display = 'flex'; });
locationFields.forEach(el => (el as HTMLElement).style.display = 'flex');
}
else if (type === 'PC' || type === '노트북') {
[modelGroup, osGroup, cpuGroup, ramGroup, ssd1Group, ssd2Group].forEach(g => { if(g) g.style.display = 'flex'; });
if (detailPurpose === '서버') {
locationFields.forEach(el => (el as HTMLElement).style.display = 'flex');
}
}
else if (['CPU', 'GPU', '모바일'].includes(type)) {
if (modelGroup) modelGroup.style.display = 'flex';
}
else if (type === 'RAM') {
if (ramGroup) ramGroup.style.display = 'flex';
}
else if (type === 'HDD') {
if (ssd1Group) ssd1Group.style.display = 'flex';
}
else if (type === '태블릿') {
if (modelGroup) modelGroup.style.display = 'flex';
if (ssd1Group) ssd1Group.style.display = 'flex';
}
}
function fillFormData(asset: HardwareAsset) {
setFieldValue('pc-asset-id', asset.id);
setFieldValue('pc-법인', asset.);
setFieldValue('pc-자산코드', asset.);
setFieldValue('pc-유형', asset.type);
setFieldValue('pc-사용자', asset.);
setFieldValue('pc-현사용조직', asset.);
setFieldValue('pc-이전사용조직', asset.);
setFieldValue('pc-상세용도', (asset as any).);
parseAndSetLocation(asset., 'pc-위치-빌딩', 'pc-위치-상세', 'pc-위치-기타-group', 'pc-위치-기타');
setFieldValue('pc-모델명', asset.);
setFieldValue('pc-OS', asset.OS);
setFieldValue('pc-CPU', asset.CPU);
setFieldValue('pc-RAM', asset.RAM);
setFieldValue('pc-SSD1', asset.SSD1);
setFieldValue('pc-SSD2', asset.SSD2);
setFieldValue('pc-구매일', asset.);
setFieldValue('pc-금액', asset.);
setFieldValue('pc-납품업체', asset.);
setFieldValue('pc-품의서명', asset.);
}
export function initPcModal(onSave: () => void, closeModalsCb: () => void) {
if (!document.getElementById('pc-asset-modal')) {
document.body.insertAdjacentHTML('beforeend', PC_MODAL_HTML);
}
const pcForm = document.getElementById('pc-asset-form') as HTMLFormElement;
const btnRevertEdit = document.getElementById('btn-revert-pc-edit') as HTMLButtonElement;
const btnSavePc = document.getElementById('btn-save-pc-asset') as HTMLButtonElement;
const btnDeletePc = document.getElementById('btn-delete-pc-asset') as HTMLButtonElement;
const btnCloseHeader = document.getElementById('btn-close-pc-modal') as HTMLButtonElement;
const btnCloseFooter = document.getElementById('btn-close-pc-footer') as HTMLButtonElement;
const saveBtn = document.getElementById('btn-save-pc-asset');
const revertBtn = document.getElementById('btn-revert-pc-edit');
const deleteBtn = document.getElementById('btn-delete-pc-asset');
let isEditMode = false;
let currentAsset: HardwareAsset | null = null;
// 유형 및 상세용도 리스너
const typeSelect = document.getElementById('pc-유형') as HTMLSelectElement;
const detailPurposeSelect = document.getElementById('pc-상세용도') as HTMLSelectElement;
[typeSelect, detailPurposeSelect].forEach(el => {
el?.addEventListener('change', () => applyPcTypeSpecificUI());
});
const setEditMode = (edit: boolean) => {
isEditMode = edit;
if (edit) {
pcForm.classList.add('is-edit-mode');
pcForm.classList.remove('is-view-mode');
btnSavePc.textContent = '저장';
btnRevertEdit.classList.remove('hidden');
btnCloseFooter.classList.add('hidden');
} else {
pcForm.classList.add('is-view-mode');
pcForm.classList.remove('is-edit-mode');
btnSavePc.textContent = '수정';
btnRevertEdit.classList.add('hidden');
btnCloseFooter.classList.remove('hidden');
if (currentAsset) fillFormData(currentAsset);
}
};
bindLocationEvents('pc-위치-빌딩', 'pc-위치-상세', 'pc-위치-기타-group', 'pc-위치-기타');
function fillFormData(asset: HardwareAsset) {
(document.getElementById('pc-asset-id') as HTMLInputElement).value = asset.id;
(document.getElementById('pc-법인') as HTMLSelectElement).value = asset.;
(document.getElementById('pc-자산코드') as HTMLInputElement).value = asset.;
(document.getElementById('pc-사용자') as HTMLInputElement).value = asset. || '';
(document.getElementById('pc-위치') as HTMLInputElement).value = asset. || '';
(document.getElementById('pc-CPU') as HTMLInputElement).value = asset.CPU || '';
(document.getElementById('pc-GPU') as HTMLInputElement).value = asset.GPU || '';
(document.getElementById('pc-RAM') as HTMLInputElement).value = asset.RAM || '';
(document.getElementById('pc-SSD1') as HTMLInputElement).value = asset.SSD1 || '';
(document.getElementById('pc-SSD2') as HTMLInputElement).value = asset.SSD2 || '';
(document.getElementById('pc-HDD1') as HTMLInputElement).value = asset.HDD1 || '';
(document.getElementById('pc-HDD2') as HTMLInputElement).value = asset.HDD2 || '';
(document.getElementById('pc-구매일') as HTMLInputElement).value = asset. || '';
(document.getElementById('pc-금액') as HTMLInputElement).value = asset. || '';
(document.getElementById('pc-납품업체') as HTMLInputElement).value = asset. || '';
(document.getElementById('pc-품의서명') as HTMLElement).innerText = asset. ? `첨부: ${asset.}` : '';
}
const handleClose = () => { closeModalsCb(); isEditMode = false; };
document.getElementById('btn-close-pc-modal')?.addEventListener('click', handleClose);
document.getElementById('btn-cancel-pc-modal')?.addEventListener('click', handleClose);
revertBtn?.addEventListener('click', () => {
isEditMode = false;
pcForm.classList.replace('is-edit-mode', 'is-view-mode');
if (saveBtn) saveBtn.textContent = '수정';
revertBtn.classList.add('hidden');
if (currentAsset) fillFormData(currentAsset);
});
btnRevertEdit?.addEventListener('click', () => setEditMode(false));
btnCloseHeader?.addEventListener('click', closeModals);
btnCloseFooter?.addEventListener('click', closeModals);
btnSavePc?.addEventListener('click', (e) => {
e.preventDefault();
saveBtn?.addEventListener('click', () => {
if (!currentAsset) return;
if (!isEditMode) {
setEditMode(true);
isEditMode = true;
pcForm.classList.replace('is-view-mode', 'is-edit-mode');
saveBtn.textContent = '저장';
revertBtn?.classList.remove('hidden');
return;
}
if (!pcForm.checkValidity()) { pcForm.reportValidity(); return; }
// ... (저장 로직 유지)
e.preventDefault();
if (!pcForm.checkValidity()) { pcForm.reportValidity(); return; }
const id = (document.getElementById('pc-asset-id') as HTMLInputElement).value;
const fileInput = document.getElementById('pc-품의서') as HTMLInputElement;
const = fileInput.files && fileInput.files.length > 0 ? fileInput.files[0].name : (document.getElementById('pc-품의서명') as HTMLElement).innerText.replace('첨부: ', '');
const newAsset: HardwareAsset = {
id: id || Math.random().toString(36).substring(2, 9),
type: '개인PC',
: (document.getElementById('pc-법인') as HTMLSelectElement).value,
: (document.getElementById('pc-자산코드') as HTMLInputElement).value,
: '',
: (document.getElementById('pc-위치') as HTMLInputElement).value,
: '', IP주소: '', MACaddress: '', HW사양: '', OS: '', : (document.getElementById('pc-납품업체') as HTMLInputElement).value,
: (document.getElementById('pc-사용자') as HTMLInputElement).value,
CPU: (document.getElementById('pc-CPU') as HTMLInputElement).value,
GPU: (document.getElementById('pc-GPU') as HTMLInputElement).value,
RAM: (document.getElementById('pc-RAM') as HTMLInputElement).value,
SSD1: (document.getElementById('pc-SSD1') as HTMLInputElement).value,
SSD2: (document.getElementById('pc-SSD2') as HTMLInputElement).value,
HDD1: (document.getElementById('pc-HDD1') as HTMLInputElement).value,
HDD2: (document.getElementById('pc-HDD2') as HTMLInputElement).value,
: (document.getElementById('pc-구매일') as HTMLInputElement).value,
: (document.getElementById('pc-금액') as HTMLInputElement).value,
const type = getFieldValue('pc-유형');
const detailPurpose = getFieldValue('pc-상세용도');
const updated: any = {
...currentAsset,
법인: getFieldValue('pc-법인'),
자산코드: getFieldValue('pc-자산코드'),
현사용조직: getFieldValue('pc-현사용조직'),
이전사용조직: getFieldValue('pc-이전사용조직'),
사용자: getFieldValue('pc-사용자'),
상세용도: detailPurpose,
위치: getCombinedLocation('pc-위치-빌딩', 'pc-위치-상세', 'pc-위치-기타'),
모델명: getFieldValue('pc-모델명'),
OS: getFieldValue('pc-OS'),
CPU: getFieldValue('pc-CPU'),
RAM: getFieldValue('pc-RAM'),
SSD1: getFieldValue('pc-SSD1'),
SSD2: getFieldValue('pc-SSD2'),
구매일: getFieldValue('pc-구매일'),
금액: getFieldValue('pc-금액'),
납품업체: getFieldValue('pc-납품업체'),
type: type || 'PC'
};
if (id) {
const idx = state.masterData.hw.findIndex(a => a.id === id);
if(idx !== -1) {
const oldAsset = state.masterData.hw[idx];
const changes = getChangeDetails(oldAsset, newAsset);
if (changes) {
state.masterData.logs.push({
id: Math.random().toString(36).substring(2, 9),
assetId: id,
date: new Date().toLocaleString(),
details: changes,
user: '관리자'
});
}
state.masterData.hw[idx] = newAsset;
}
} else {
state.masterData.hw.push(newAsset);
}
closeModals();
renderContent();
saveHardwareAsset(updated);
onSave();
isEditMode = false;
pcForm.classList.replace('is-edit-mode', 'is-view-mode');
saveBtn.textContent = '수정';
revertBtn?.classList.add('hidden');
});
btnDeletePc?.addEventListener('click', (e) => {
e.preventDefault();
const id = (document.getElementById('pc-asset-id') as HTMLInputElement).value;
deleteBtn?.addEventListener('click', () => {
if (!currentAsset) return;
if (confirm('삭제하시겠습니까?')) {
state.masterData.hw = state.masterData.hw.filter(a => a.id !== id);
closeModals();
renderContent();
deleteHardwareAsset(currentAsset.id);
onSave();
handleClose();
}
});
}
export function openPcModal(asset?: HardwareAsset) {
const pcForm = document.getElementById('pc-asset-form') as HTMLFormElement;
const deleteBtn = document.getElementById('btn-delete-pc-asset')!;
const historyArea = document.querySelector('.modal-history-area') as HTMLElement;
openModal('pc-asset-modal');
pcForm.reset();
if (asset) {
document.getElementById('pc-modal-title')!.textContent = '개인PC 상세 정보 수정';
deleteBtn.style.display = 'block';
if (historyArea) historyArea.style.display = 'flex';
(document.getElementById('pc-asset-id') as HTMLInputElement).value = asset.id;
(document.getElementById('pc-법인') as HTMLSelectElement).value = asset.;
(document.getElementById('pc-자산코드') as HTMLInputElement).value = asset.;
(document.getElementById('pc-사용자') as HTMLInputElement).value = asset. || '';
(document.getElementById('pc-위치') as HTMLInputElement).value = asset. || '';
(document.getElementById('pc-CPU') as HTMLInputElement).value = asset.CPU || '';
(document.getElementById('pc-GPU') as HTMLInputElement).value = asset.GPU || '';
(document.getElementById('pc-RAM') as HTMLInputElement).value = asset.RAM || '';
(document.getElementById('pc-SSD1') as HTMLInputElement).value = asset.SSD1 || '';
(document.getElementById('pc-SSD2') as HTMLInputElement).value = asset.SSD2 || '';
(document.getElementById('pc-HDD1') as HTMLInputElement).value = asset.HDD1 || '';
(document.getElementById('pc-HDD2') as HTMLInputElement).value = asset.HDD2 || '';
(document.getElementById('pc-구매일') as HTMLInputElement).value = asset. || '';
(document.getElementById('pc-금액') as HTMLInputElement).value = asset. || '';
(document.getElementById('pc-납품업체') as HTMLInputElement).value = asset. || '';
(document.getElementById('pc-품의서명') as HTMLElement).innerText = asset. ? `첨부: ${asset.}` : '';
renderHistory(asset.id);
} else {
document.getElementById('pc-modal-title')!.textContent = '신규 개인PC 자산 추가';
deleteBtn.style.display = 'none';
if (historyArea) historyArea.style.display = 'none';
(document.getElementById('pc-asset-id') as HTMLInputElement).value = '';
(document.getElementById('pc-법인') as HTMLSelectElement).value = '한맥';
(document.getElementById('pc-품의서명') as HTMLElement).innerText = '';
}
}
function getChangeDetails(oldAsset: HardwareAsset, newAsset: HardwareAsset): string {
const changes: string[] = [];
const fields = [
{ key: '법인', label: '법인' },
{ key: '자산코드', label: '자산코드' },
{ key: '사용자', label: '사용자' },
{ key: '위치', label: '위치' },
{ key: 'CPU', label: 'CPU' },
{ key: 'GPU', label: 'GPU' },
{ key: 'RAM', label: 'RAM' },
{ key: 'SSD1', label: 'SSD1' },
{ key: 'SSD2', label: 'SSD2' },
{ key: 'HDD1', label: 'HDD1' },
{ key: 'HDD2', label: 'HDD2' },
{ key: '구매일', label: '구매일' },
{ key: '금액', label: '금액' },
{ key: '납품업체', label: '납품업체' },
{ key: '품의서명', label: '품의서' },
];
fields.forEach(field => {
const oldVal = (oldAsset as any)[field.key] || '';
const newVal = (newAsset as any)[field.key] || '';
if (oldVal !== newVal) {
changes.push(`${field.label}: ${oldVal || '없음'}${newVal || '없음'}`);
}
});
return changes.join('\n');
}
function renderHistory(assetId: string) {
const historyList = document.getElementById('pc-history-list');
if (!historyList) return;
const logs = state.masterData.logs
.filter(l => l.assetId === assetId)
.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
if (logs.length === 0) {
historyList.innerHTML = '<div class="empty-history">이력이 없습니다.</div>';
return;
}
historyList.innerHTML = logs.map(log => `
<div class="history-item">
<div class="history-date">${log.date}</div>
<div class="history-user">수정자: ${log.user}</div>
<div class="history-details">${log.details.replace(/\\n/g, '<br>')}</div>
<div class="history-details">${log.details.replace(/\n/g, '<br>')}</div>
</div>
`).join('');
}

View File

@@ -1,14 +1,20 @@
import { state } from '../../core/state';
import { SoftwareAsset } from '../../core/excelHandler';
import { openModal } from './BaseModal';
import { createIcons, X, History, Plus } from 'lucide';
import { openModal, closeModals } from './BaseModal';
import { openSwUserModal } from './SWUserModal';
import { createIcons, History, Plus, X } from 'lucide';
import { CORP_LIST } from './SharedData';
import { generateOptionsHTML, setFieldValue, getFieldValue } from './ModalUtils';
let currentSwAsset: SoftwareAsset | null = null;
let isEditMode = false;
const SW_MODAL_HTML = `
<div id="sw-asset-modal" class="modal-overlay hidden">
<div class="modal-content wide">
<div class="modal-header">
<h2 id="sw-modal-title">S/W 상세 정보</h2>
<button id="btn-close-sw-modal" class="btn-icon" aria-label="닫기"><i data-lucide="x"></i></button>
<h2 id="sw-modal-title">소프트웨어 상세 정보</h2>
<button id="btn-close-sw-modal" class="btn-icon"><i data-lucide="x"></i></button>
</div>
<div class="modal-body">
<div class="modal-body-split">
@@ -16,51 +22,47 @@ const SW_MODAL_HTML = `
<form id="sw-asset-form" class="grid-form">
<input type="hidden" id="sw-asset-id" />
<input type="hidden" id="sw-asset-type" />
<div class="form-section-title">기본 정보 (Basic Info)</div>
<div class="form-group">
<label for="sw-분야">분야</label>
<select id="sw-분야" required>
<option value="업무공통">업무공통</option><option value="개발S/W">개발S/W</option><option value="디자인">디자인</option><option value="설계S/W">설계S/W</option>
</select>
<label for="sw-법인">구매법인</label>
<select id="sw-법인" required>${generateOptionsHTML(CORP_LIST)}</select>
</div>
<div class="form-group">
<label for="sw-법인">법인</label>
<select id="sw-법인" required>
<option value="한맥">한맥</option><option value="삼안">삼안</option><option value="바론">바론</option>
</select>
<label for="sw-자산번호">자산번호</label>
<input type="text" id="sw-자산번호" readonly placeholder="자동 생성" />
</div>
<div class="form-group full-width">
<label for="sw-제품명">제품명</label>
<input type="text" id="sw-제품명" required />
</div>
<div class="form-section-title">라이선스 정보 (License)</div>
<div class="form-group" id="sw-license-type-group">
<label for="sw-라이선스유형">라이선스 유형</label>
<input type="text" id="sw-라이선스유형" />
</div>
<div class="form-group" id="sw-license-key-group">
<label for="sw-라이선스키">라이선스 키</label>
<input type="text" id="sw-라이선스키" />
</div>
<div class="form-group">
<label for="sw-부서">부서</label>
<input type="text" id="sw-부서" placeholder="ex) 경영지원팀" required />
<label for="sw-수량">보유 수량</label>
<input type="number" id="sw-수량" min="0" />
</div>
<div class="form-group">
<label for="sw-금액">도입 금액</label>
<input type="text" id="sw-금액" oninput="this.value = this.value.replace(/[^0-9]/g, '').replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',')" />
</div>
<div class="form-section-title">구매 및 계약 (Purchase)</div>
<div class="form-group">
<label for="sw-구매일">구매일</label>
<input type="date" id="sw-구매일" />
<input type="text" id="sw-구매일" />
</div>
<div class="form-group" id="sw-구독일-group" style="grid-column: span 2;">
<label>구독 기간</label>
<div style="display: flex; align-items: center; gap: 0.5rem;">
<input type="date" id="sw-구독일-시작" style="flex: 1;" />
<span>~</span>
<input type="date" id="sw-구독일-종료" style="flex: 1;" />
</div>
</div>
<div class="form-group" id="sw-유지보수-group" style="display:none;">
<label for="sw-유지보수여부">유지보수 여부</label>
<label style="display:flex; align-items:center; gap:0.5rem; height: 38px; cursor: pointer;">
<input type="checkbox" id="sw-유지보수여부" /> 대상 여부
</label>
</div>
<div class="form-group">
<label for="sw-금액">금액</label>
<input type="text" id="sw-금액" oninput="this.value = this.value.replace(/[^0-9]/g, '') ? Number(this.value.replace(/[^0-9]/g, '')).toLocaleString() : ''" />
</div>
<div class="form-group">
<label for="sw-수량">수량 (보유량)</label>
<input type="number" id="sw-수량" min="1" value="1" />
</div>
<div class="form-group">
<label for="sw-계정명">계정명</label>
<input type="text" id="sw-계정명" />
<div class="form-group" id="sw-expiry-group">
<label for="sw-만료일">만료일 (구독)</label>
<input type="text" id="sw-만료일" />
</div>
<div class="form-group">
<label for="sw-납품업체">납품업체</label>
@@ -68,18 +70,28 @@ const SW_MODAL_HTML = `
</div>
<div class="form-group full-width">
<label for="sw-비고">비고</label>
<input type="text" id="sw-비고" />
<textarea id="sw-비고" rows="2"></textarea>
</div>
</form>
<div class="user-management-section" style="margin-top: 2rem;">
<div class="section-header" style="display:flex; justify-content:space-between; align-items:center; margin-bottom:1rem;">
<h3 style="font-size:1rem; font-weight:600;">사용자 할당 현황</h3>
<button type="button" id="btn-open-sw-update" class="btn btn-outline btn-sm">
할당 관리 <i data-lucide="plus" style="width:14px; height:14px;"></i>
</button>
</div>
<div id="sw-assigned-users-summary" class="user-summary-grid">
<!-- User summary list -->
</div>
</div>
</div>
<div class="modal-history-area">
<div class="history-header" style="display:flex; justify-content:space-between; align-items:center;">
<h3><i data-lucide="history" style="width:16px; height:16px;"></i> 업데이트 내역</h3>
<button type="button" id="btn-open-sw-update" class="btn btn-outline btn-sm"><i data-lucide="plus" style="width:14px;height:14px;"></i> 업데이트 추가</button>
</div>
<div id="sw-history-list" class="history-timeline">
<div class="empty-history">내역이 없습니다.</div>
<div class="history-header">
<h3><i data-lucide="history" style="width:16px; height:16px;"></i> 수정 이력</h3>
</div>
<div id="sw-history-list" class="history-timeline"></div>
</div>
</div>
</div>
@@ -87,332 +99,188 @@ const SW_MODAL_HTML = `
<button id="btn-delete-sw-asset" class="btn btn-outline btn-danger">삭제</button>
<div class="footer-actions">
<button id="btn-revert-sw-edit" class="btn btn-outline hidden">수정 취소</button>
<button id="btn-close-sw-footer" class="btn btn-outline">닫기</button>
<button id="btn-cancel-sw-modal" class="btn btn-outline">닫기</button>
<button id="btn-save-sw-asset" class="btn btn-primary">수정</button>
</div>
</div>
</div>
</div>
<div id="sw-update-modal" class="modal-overlay hidden" style="z-index: 1100;">
<div class="modal-content" style="max-width: 400px;">
<div class="modal-header">
<h2>계약 업데이트 반영</h2>
<button id="btn-close-sw-update" class="btn-icon"><i data-lucide="x"></i></button>
</div>
<div class="modal-body">
<div class="grid-form" style="grid-template-columns: 1fr;">
<div class="form-group">
<label>업데이트 일자</label>
<input type="date" id="sw-update-date" />
</div>
<div class="form-group sub-sw-update">
<label>새로운 구독 기간</label>
<div style="display: flex; align-items: center; gap: 0.5rem;">
<input type="date" id="sw-update-start" style="flex: 1;" />
<span>~</span>
<input type="date" id="sw-update-end" style="flex: 1;" />
</div>
</div>
<div class="form-group perm-sw-update" style="display:none;">
<label>유지보수 체결 (상태 연동)</label>
<label style="display:flex; align-items:center; gap:0.5rem; height: 38px; cursor: pointer;">
<input type="checkbox" id="sw-update-maintenance" /> 유효 상태로 갱신
</label>
</div>
<div class="form-group">
<label>발생 비용</label>
<input type="text" id="sw-update-cost" oninput="this.value = this.value.replace(/[^0-9]/g, '') ? Number(this.value.replace(/[^0-9]/g, '')).toLocaleString() : ''" placeholder="ex) 500,000" />
</div>
<div class="form-group">
<label>상세 내용 (메모)</label>
<input type="text" id="sw-update-note" placeholder="예: 25년도 구독 연장 결제 완료" />
</div>
</div>
</div>
<div class="modal-footer">
<div></div>
<div class="footer-actions">
<button id="btn-cancel-sw-update" class="btn btn-outline">취소</button>
<button id="btn-save-sw-update" class="btn btn-primary">반영하기</button>
</div>
</div>
</div>
</div>
`;
export let currentAsset: SoftwareAsset | null = null;
export let isEditMode = false;
function fillSwFormData(asset: SoftwareAsset) {
setFieldValue('sw-asset-id', asset.id);
setFieldValue('sw-asset-type', asset.type);
setFieldValue('sw-법인', asset.);
setFieldValue('sw-자산번호', asset.);
setFieldValue('sw-제품명', asset.);
setFieldValue('sw-수량', asset.);
setFieldValue('sw-금액', asset.);
setFieldValue('sw-구매일', asset.);
setFieldValue('sw-납품업체', asset.);
setFieldValue('sw-비고', asset.);
export function setEditMode(edit: boolean) {
isEditMode = edit;
const swForm = document.getElementById('sw-asset-form') as HTMLFormElement;
const btnSaveSw = document.getElementById('btn-save-sw-asset') as HTMLButtonElement;
const btnRevertEdit = document.getElementById('btn-revert-sw-edit') as HTMLButtonElement;
const btnCloseFooter = document.getElementById('btn-close-sw-footer') as HTMLButtonElement;
const type = asset.type;
const keyGroup = document.getElementById('sw-license-key-group');
const typeGroup = document.getElementById('sw-license-type-group');
const expiryGroup = document.getElementById('sw-expiry-group');
if (edit) {
swForm.classList.add('is-edit-mode');
swForm.classList.remove('is-view-mode');
btnSaveSw.textContent = '저장';
btnRevertEdit.classList.remove('hidden');
btnCloseFooter.classList.add('hidden');
Array.from(swForm.elements).forEach((el: any) => el.disabled = false);
if (type === '구독SW') {
if (keyGroup) keyGroup.style.display = 'none';
if (typeGroup) typeGroup.style.display = 'flex';
if (expiryGroup) expiryGroup.style.display = 'flex';
setFieldValue('sw-라이선스유형', (asset as any). || '');
setFieldValue('sw-만료일', (asset as any). || '');
} else {
swForm.classList.add('is-view-mode');
swForm.classList.remove('is-edit-mode');
btnSaveSw.textContent = '수정';
btnRevertEdit.classList.add('hidden');
btnCloseFooter.classList.remove('hidden');
Array.from(swForm.elements).forEach((el: any) => el.disabled = true);
if (currentAsset) fillFormData(currentAsset);
if (keyGroup) keyGroup.style.display = 'flex';
if (typeGroup) typeGroup.style.display = 'none';
if (expiryGroup) expiryGroup.style.display = 'none';
setFieldValue('sw-라이선스키', (asset as any). || '');
}
renderUserSummary(asset.id);
}
export function fillFormData(asset: SoftwareAsset) {
(document.getElementById('sw-asset-id') as HTMLInputElement).value = asset.id;
(document.getElementById('sw-asset-type') as HTMLInputElement).value = asset.type;
(document.getElementById('sw-분야') as HTMLSelectElement).value = asset. || '업무공통';
(document.getElementById('sw-법인') as HTMLSelectElement).value = asset.;
(document.getElementById('sw-부서') as HTMLInputElement).value = asset. || '';
(document.getElementById('sw-제품명') as HTMLInputElement).value = asset.;
(document.getElementById('sw-구매일') as HTMLInputElement).value = asset. || '';
if (asset.) {
const parts = asset..split('~');
(document.getElementById('sw-구독일-시작') as HTMLInputElement).value = parts[0]?.trim() || '';
(document.getElementById('sw-구독일-종료') as HTMLInputElement).value = parts[1]?.trim() || '';
} else {
(document.getElementById('sw-구독일-시작') as HTMLInputElement).value = '';
(document.getElementById('sw-구독일-종료') as HTMLInputElement).value = '';
function renderUserSummary(swId: string) {
const container = document.getElementById('sw-assigned-users-summary');
if (!container) return;
const userMapping = state.masterData.swUsers.find(u => u.sw_id === swId);
if (!userMapping || !userMapping.userData || userMapping.userData.length === 0) {
container.innerHTML = '<div class="empty-summary">할당된 사용자가 없습니다.</div>';
return;
}
(document.getElementById('sw-유지보수여부') as HTMLInputElement).checked = !!asset.;
(document.getElementById('sw-금액') as HTMLInputElement).value = asset. || '';
(document.getElementById('sw-수량') as HTMLInputElement).value = String(asset.);
(document.getElementById('sw-계정명') as HTMLInputElement).value = asset. || '';
(document.getElementById('sw-납품업체') as HTMLInputElement).value = asset. || '';
(document.getElementById('sw-비고') as HTMLInputElement).value = asset. || '';
container.innerHTML = userMapping.userData.map(u => `
<div class="user-badge-item">
<span class="u-name">${u[3] || '이름없음'}</span>
<span class="u-dept">${u[1] || '부서없음'}</span>
</div>
`).join('');
}
document.getElementById('btn-open-sw-update')!.style.display = 'flex';
function renderSwHistory(swId: string) {
const container = document.getElementById('sw-history-list');
if (!container) return;
const logs = (state.masterData.logs || []).filter(l => l.assetId === swId);
if (logs.length === 0) {
container.innerHTML = '<div class="empty-history">이력이 없습니다.</div>';
return;
}
container.innerHTML = logs.map(l => `
<div class="history-item">
<div class="history-date">${l.date}</div>
<div class="history-user">${l.user}</div>
<div class="history-details">${l.details}</div>
</div>
`).join('');
}
export function openSwModal(asset: SoftwareAsset) {
currentSwAsset = asset;
const modal = document.getElementById('sw-asset-modal')!;
const form = document.getElementById('sw-asset-form') as HTMLFormElement;
const saveBtn = document.getElementById('btn-save-sw-asset')!;
const revertBtn = document.getElementById('btn-revert-sw-edit')!;
form.reset();
const isNew = !asset.;
if (isNew) {
isEditMode = true;
form.classList.remove('is-view-mode');
form.classList.add('is-edit-mode');
saveBtn.textContent = '저장';
revertBtn.classList.add('hidden');
} else {
isEditMode = false;
form.classList.remove('is-edit-mode');
form.classList.add('is-view-mode');
saveBtn.textContent = '수정';
revertBtn.classList.add('hidden');
}
fillSwFormData(asset);
renderSwHistory(asset.id);
modal.classList.remove('hidden');
createIcons({ icons: { X, History, Plus } });
}
export function initSwModal(renderContent: () => void, closeModals: () => void) {
export function initSwModal(onSave: () => void, closeModals: () => void) {
if (!document.getElementById('sw-asset-modal')) {
document.body.insertAdjacentHTML('beforeend', SW_MODAL_HTML);
}
const swForm = document.getElementById('sw-asset-form') as HTMLFormElement;
const btnRevertEdit = document.getElementById('btn-revert-sw-edit') as HTMLButtonElement;
const btnSaveSw = document.getElementById('btn-save-sw-asset') as HTMLButtonElement;
const btnDeleteSw = document.getElementById('btn-delete-sw-asset') as HTMLButtonElement;
const btnCloseHeader = document.getElementById('btn-close-sw-modal') as HTMLButtonElement;
const btnCloseFooter = document.getElementById('btn-close-sw-footer') as HTMLButtonElement;
const form = document.getElementById('sw-asset-form') as HTMLFormElement;
const saveBtn = document.getElementById('btn-save-sw-asset')!;
const revertBtn = document.getElementById('btn-revert-sw-edit')!;
const deleteBtn = document.getElementById('btn-delete-sw-asset')!;
const userUpdateBtn = document.getElementById('btn-open-sw-update')!;
btnRevertEdit?.addEventListener('click', () => setEditMode(false));
btnCloseHeader?.addEventListener('click', closeModals);
btnCloseFooter?.addEventListener('click', closeModals);
const closeModalAction = () => { closeModals(); isEditMode = false; };
document.getElementById('btn-close-sw-modal')?.addEventListener('click', closeModalAction);
document.getElementById('btn-cancel-sw-modal')?.addEventListener('click', closeModalAction);
btnSaveSw?.addEventListener('click', (e) => {
e.preventDefault();
revertBtn.addEventListener('click', () => {
isEditMode = false;
form.classList.replace('is-edit-mode', 'is-view-mode');
saveBtn.textContent = '수정';
revertBtn.classList.add('hidden');
if (currentSwAsset) fillSwFormData(currentSwAsset);
});
saveBtn.addEventListener('click', () => {
if (!currentSwAsset) return;
if (!isEditMode) {
setEditMode(true);
isEditMode = true;
form.classList.replace('is-view-mode', 'is-edit-mode');
saveBtn.textContent = '저장';
revertBtn.classList.remove('hidden');
return;
}
if (!swForm.checkValidity()) { swForm.reportValidity(); return; }
const id = (document.getElementById('sw-asset-id') as HTMLInputElement).value;
const start = (document.getElementById('sw-구독일-시작') as HTMLInputElement).value;
const end = (document.getElementById('sw-구독일-종료') as HTMLInputElement).value;
const Str = (start || end) ? `${start || ''} ~ ${end || ''}` : '';
const newAsset: SoftwareAsset = {
id: id || Math.random().toString(36).substring(2, 9),
type: (document.getElementById('sw-asset-type') as HTMLInputElement).value,
: (document.getElementById('sw-분야') as HTMLSelectElement).value,
: (document.getElementById('sw-법인') as HTMLSelectElement).value,
: (document.getElementById('sw-부서') as HTMLInputElement).value,
: (document.getElementById('sw-제품명') as HTMLInputElement).value,
: (document.getElementById('sw-구매일') as HTMLInputElement).value,
: 구독일Str,
: (document.getElementById('sw-유지보수여부') as HTMLInputElement).checked,
: (document.getElementById('sw-금액') as HTMLInputElement).value,
수량: parseInt((document.getElementById('sw-수량') as HTMLInputElement).value || '1', 10),
: (document.getElementById('sw-계정명') as HTMLInputElement).value,
: (document.getElementById('sw-납품업체') as HTMLInputElement).value,
: (document.getElementById('sw-비고') as HTMLInputElement).value,
const type = getFieldValue('sw-asset-type');
const updated: any = {
...currentSwAsset,
법인: getFieldValue('sw-법인'),
자산번호: getFieldValue('sw-자산번호'),
제품명: getFieldValue('sw-제품명'),
수량: parseInt(getFieldValue('sw-수량') || '0'),
금액: getFieldValue('sw-금액'),
: getFieldValue('sw-구매일'),
납품업체: getFieldValue('sw-납품업체'),
비고: getFieldValue('sw-비고'),
type: type
};
if (id) {
const idx = state.masterData.sw.findIndex(a => a.id === id);
if(idx !== -1) state.masterData.sw[idx] = newAsset;
if (type === '구독SW') {
updated. = getFieldValue('sw-라이선스유형');
updated. = getFieldValue('sw-만료일');
} else {
state.masterData.sw.push(newAsset);
const now = new Date();
state.masterData.logs = state.masterData.logs || [];
state.masterData.logs.push({
id: Math.random().toString(36).substring(2, 9),
assetId: newAsset.id,
date: `${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,'0')}-${String(now.getDate()).padStart(2,'0')}`,
user: '관리자',
details: '신규 등록'
});
updated. = getFieldValue('sw-라이선스키');
}
closeModals();
renderContent();
const targetList = type === '구독SW' ? state.masterData.subSw : state.masterData.permSw;
const idx = targetList.findIndex(a => a.id === updated.id);
if (idx > -1) targetList[idx] = updated;
else targetList.push(updated);
onSave();
isEditMode = false;
form.classList.replace('is-edit-mode', 'is-view-mode');
saveBtn.textContent = '수정';
revertBtn.classList.add('hidden');
});
btnDeleteSw?.addEventListener('click', (e) => {
e.preventDefault();
const id = (document.getElementById('sw-asset-id') as HTMLInputElement).value;
deleteBtn.addEventListener('click', () => {
if (!currentSwAsset) return;
if (confirm('삭제하시겠습니까?')) {
state.masterData.sw = state.masterData.sw.filter(a => a.id !== id);
closeModals();
renderContent();
const type = currentSwAsset.type;
if (type === '구독SW') state.masterData.subSw = state.masterData.subSw.filter(a => a.id !== currentSwAsset!.id);
else state.masterData.permSw = state.masterData.permSw.filter(a => a.id !== currentSwAsset!.id);
onSave();
closeModalAction();
}
});
// Update Sub-modal integration
const subModal = document.getElementById('sw-update-modal')!;
const btnOpenUpdate = document.getElementById('btn-open-sw-update')!;
const btnCloseUpdate = document.getElementById('btn-close-sw-update')!;
const btnCancelUpdate = document.getElementById('btn-cancel-sw-update')!;
const btnSaveUpdate = document.getElementById('btn-save-sw-update')!;
const closeUpdateModal = () => subModal.classList.add('hidden');
btnCloseUpdate?.addEventListener('click', closeUpdateModal);
btnCancelUpdate?.addEventListener('click', closeUpdateModal);
btnOpenUpdate?.addEventListener('click', (e) => {
e.preventDefault();
const isSub = (document.getElementById('sw-asset-type') as HTMLInputElement).value === '구독SW';
subModal.classList.remove('hidden');
// Set default values
(document.getElementById('sw-update-date') as HTMLInputElement).value = new Date().toISOString().substring(0, 10);
(document.getElementById('sw-update-start') as HTMLInputElement).value = '';
(document.getElementById('sw-update-end') as HTMLInputElement).value = '';
(document.getElementById('sw-update-cost') as HTMLInputElement).value = '';
(document.getElementById('sw-update-note') as HTMLInputElement).value = '';
if (isSub) {
document.querySelector('.sub-sw-update')!.setAttribute('style', 'display:flex; flex-direction:column;');
document.querySelector('.perm-sw-update')!.setAttribute('style', 'display:none');
} else {
document.querySelector('.sub-sw-update')!.setAttribute('style', 'display:none');
document.querySelector('.perm-sw-update')!.setAttribute('style', 'display:flex; flex-direction:column;');
(document.getElementById('sw-update-maintenance') as HTMLInputElement).checked = (document.getElementById('sw-유지보수여부') as HTMLInputElement).checked;
}
});
btnSaveUpdate?.addEventListener('click', (e) => {
e.preventDefault();
const id = (document.getElementById('sw-asset-id') as HTMLInputElement).value;
if (!id) { alert('자산이 저장되지 않았습니다. 메인 폼을 먼저 저장해주세요.'); return; }
const isSub = (document.getElementById('sw-asset-type') as HTMLInputElement).value === '구독SW';
const date = (document.getElementById('sw-update-date') as HTMLInputElement).value;
const start = (document.getElementById('sw-update-start') as HTMLInputElement).value;
const end = (document.getElementById('sw-update-end') as HTMLInputElement).value;
const maintenance = (document.getElementById('sw-update-maintenance') as HTMLInputElement).checked;
const cost = (document.getElementById('sw-update-cost') as HTMLInputElement).value;
const note = (document.getElementById('sw-update-note') as HTMLInputElement).value;
const periodStr = (start || end) ? `${start || ''} ~ ${end || ''}` : '';
let details = `[업데이트] ${note || (isSub ? '구독 갱신' : '유지보수 계약')}\n`;
if (cost) details += `발생 비용: ${cost}\n`;
if (isSub) {
if (periodStr) details += `구독 변경: -> ${periodStr}\n`;
// Always update main fields if period is provided
if (periodStr) {
(document.getElementById('sw-구독일-시작') as HTMLInputElement).value = start;
(document.getElementById('sw-구독일-종료') as HTMLInputElement).value = end;
}
} else {
details += `유지보수 상태: -> ${maintenance ? '유효' : '없음'}\n`;
(document.getElementById('sw-유지보수여부') as HTMLInputElement).checked = maintenance;
}
if (cost) (document.getElementById('sw-금액') as HTMLInputElement).value = cost;
state.masterData.logs.push({
id: Math.random().toString(36).substring(2, 9),
assetId: id,
date,
details,
user: '관리자'
});
closeUpdateModal();
renderSwHistory(id);
// 메인 테이블 리렌더링도 트리거 (뒤에 보일 수 있게)
renderContent();
userUpdateBtn.addEventListener('click', () => {
if (currentSwAsset) openSwUserModal(currentSwAsset);
});
}
function renderSwHistory(assetId: string) {
const historyList = document.getElementById('sw-history-list');
if (!historyList) return;
if (!state.masterData.logs) state.masterData.logs = [];
const logs = state.masterData.logs
.filter(l => l.assetId === assetId)
.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
if (logs.length === 0) {
historyList.innerHTML = '<div class="empty-history">업데이트 내역이 없습니다.</div>';
return;
}
historyList.innerHTML = logs.map(log => `
<div class="history-item">
<div class="history-date">${log.date}</div>
<div class="history-user">작업자: ${log.user}</div>
<div class="history-details">${log.details.replace(/\\n/g, '<br>')}</div>
</div>
`).join('');
createIcons({ icons: { X, History, Plus } });
}
export function openSwModal(asset?: SoftwareAsset) {
currentAsset = asset || null;
const swForm = document.getElementById('sw-asset-form') as HTMLFormElement;
const deleteBtn = document.getElementById('btn-delete-sw-asset')!;
openModal('sw-asset-modal');
swForm.reset();
const subGroup = document.getElementById('sw-구독일-group')!;
const permGroup = document.getElementById('sw-유지보수-group')!;
if (state.activeSubTab === '구독SW') {
subGroup.style.display = 'flex';
permGroup.style.display = 'none';
} else {
subGroup.style.display = 'none';
permGroup.style.display = 'flex';
}
if (asset) {
document.getElementById('sw-modal-title')!.textContent = `${state.activeSubTab} 상세 정보 수정`;
deleteBtn.style.display = 'block';
fillFormData(asset);
setEditMode(false);
} else {
document.getElementById('sw-modal-title')!.textContent = `신규 ${state.activeSubTab} 자산 추가`;
deleteBtn.style.display = 'none';
(document.getElementById('sw-asset-id') as HTMLInputElement).value = '';
(document.getElementById('sw-asset-type') as HTMLInputElement).value = state.activeSubTab;
document.getElementById('btn-open-sw-update')!.style.display = 'none';
renderSwHistory('');
setEditMode(true);
}
createIcons({ icons: { X, History, Plus } });
}

View File

@@ -2,73 +2,68 @@ import { state } from '../../core/state';
import { SoftwareAsset, SWUser } from '../../core/excelHandler';
import { openModal } from './BaseModal';
import { createIcons, Edit2, X, Paperclip } from 'lucide';
import { CORP_LIST, ORG_LIST } from './SharedData';
import { generateOptionsHTML, setFieldValue, getFieldValue } from './ModalUtils';
let currentSwUserAssetId: string = '';
let currentSwUserAsset: SoftwareAsset | null = null;
let tempSwUsers: SWUser[] = [];
const SW_USER_MODAL_HTML = `
<!-- S/W 할당 사용자 목록 모달 -->
<div id="sw-user-modal" class="modal-overlay hidden">
<div class="modal-content" style="max-width: 800px;">
<div class="modal-content wide">
<div class="modal-header">
<h2 id="sw-user-modal-title">S/W 할당 사용자 목록</h2>
<button id="btn-close-sw-user-modal" class="btn-icon" aria-label="닫기"><i data-lucide="x"></i></button>
<h2 id="sw-user-title">소프트웨어 사용자 관리</h2>
<button id="btn-close-sw-user-modal" class="btn-icon"><i data-lucide="x"></i></button>
</div>
<div class="modal-body">
<input type="hidden" id="sw-user-asset-id" />
<div style="text-align: right; margin-bottom: 0.75rem;">
<div class="sw-info-summary" id="sw-user-sw-info"></div>
<div class="user-list-toolbar" style="display:flex; justify-content:space-between; margin-bottom:1rem; align-items:center;">
<h3 style="font-size:1rem; font-weight:600;">할당된 사용자 목록</h3>
<button type="button" id="btn-open-add-user" class="btn btn-primary btn-sm"><i data-lucide="plus"></i> 사용자 추가</button>
</div>
<div class="table-container">
<table style="width:100%;">
<table>
<thead>
<tr>
<th>법인</th>
<th>구매법인</th>
<th>부서/팀</th>
<th>직위</th>
<th>이름</th>
<th>사용기간</th>
<th>증빙</th>
<th style="text-align:center;">관리</th>
<th>신청서</th>
<th>관리</th>
</tr>
</thead>
<tbody id="user-list-body"></tbody>
<tbody id="sw-user-table-body"></tbody>
</table>
</div>
</div>
<div class="modal-footer">
<div></div>
<div class="footer-actions">
<button id="btn-save-sw-user-mapping" class="btn btn-primary">변경사항 저장</button>
<button id="btn-cancel-sw-user-modal" class="btn btn-outline">닫기</button>
</div>
<button id="btn-cancel-sw-user" class="btn btn-outline">취소</button>
<button id="btn-save-sw-user" class="btn btn-primary">저장</button>
</div>
</div>
</div>
<!-- 사용자 추가/수정 서브 모달 -->
<div id="sw-user-edit-modal" class="modal-overlay hidden" style="z-index: 1100;">
<div class="modal-content" style="max-width: 500px;">
<div id="sw-user-edit-modal" class="modal-overlay hidden" style="z-index:1100;">
<div class="modal-content" style="width:400px;">
<div class="modal-header">
<h2 id="sw-user-edit-modal-title">사용자 정보</h2>
<button id="btn-close-sw-user-edit" class="btn-icon"><i data-lucide="x"></i></button>
<h3 id="sw-user-edit-title">사용자 정보</h3>
<button id="btn-close-user-edit" class="btn-icon"><i data-lucide="x"></i></button>
</div>
<div class="modal-body">
<input type="hidden" id="edit-user-idx" />
<div class="grid-form" style="grid-template-columns: 1fr;">
<form id="sw-user-edit-form" class="grid-form" style="grid-template-columns: 1fr;">
<input type="hidden" id="edit-user-index" value="-1" />
<div class="form-group">
<label>법인</label>
<select id="new-user-법인">
<option value="한맥">한맥</option><option value="삼안">삼안</option><option value="바론">바론</option>
</select>
<label>구매법인</label>
<select id="new-user-법인">${generateOptionsHTML(CORP_LIST)}</select>
</div>
<div class="form-group">
<label>부서</label>
<input type="text" id="new-user-부서" />
</div>
<div class="form-group">
<label>팀</label>
<input type="text" id="new-user-팀" />
<label>부서/팀</label>
<select id="new-user-부서">${generateOptionsHTML(ORG_LIST)}</select>
</div>
<div class="form-group">
<label>직위</label>
@@ -80,156 +75,169 @@ const SW_USER_MODAL_HTML = `
</div>
<div class="form-group">
<label>사용기간</label>
<input type="text" id="new-user-사용기간" placeholder="ex) 2024.01 ~ 2024.12" />
<input type="text" id="new-user-사용기간" placeholder="ex) 2024-01-01 ~ 2024-12-31" />
</div>
<div class="form-group">
<label>신청서 (증빙파일)</label>
<label>신청서 (증빙)</label>
<input type="file" id="new-user-신청서" />
<span id="new-user-신청서명" style="font-size:0.75rem; color:var(--text-muted);"></span>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button id="btn-cancel-sw-user-edit" class="btn btn-outline">취소</button>
<button id="btn-save-edit-user" class="btn btn-primary">확인</button>
<button id="btn-close-user-sub" class="btn btn-outline">취소</button>
<button id="btn-confirm-user-edit" class="btn btn-primary">확인</button>
</div>
</div>
</div>
`;
export function initSwUserModal(renderContent: () => void, closeModals: () => void) {
export function openSwUserModal(asset: SoftwareAsset) {
currentSwUserAsset = asset;
const modal = document.getElementById('sw-user-modal')!;
const swInfo = document.getElementById('sw-user-sw-info')!;
swInfo.innerHTML = `
<div style="background:var(--bg-light); padding:1rem; border-radius:6px; margin-bottom:1.5rem;">
<div style="font-size:0.8rem; color:var(--text-muted); margin-bottom:0.25rem;">${asset.} | ${asset.}</div>
<div style="font-size:1.1rem; font-weight:700; color:var(--primary-color);">${asset.}</div>
</div>
`;
// 기존 사용자 데이터 복사 (원본 보호를 위해 temp 사용)
const existingMapping = state.masterData.swUsers.find(u => u.sw_id === asset.id);
tempSwUsers = existingMapping ? JSON.parse(JSON.stringify(existingMapping.userDataList || [])) : [];
renderUserList();
modal.classList.remove('hidden');
createIcons({ icons: { Edit2, X, Paperclip } });
}
function renderUserList() {
const tbody = document.getElementById('sw-user-table-body')!;
tbody.innerHTML = '';
if (tempSwUsers.length === 0) {
tbody.innerHTML = '<tr><td colspan="7" style="text-align:center; padding:2rem; color:var(--text-muted);">할당된 사용자가 없습니다.</td></tr>';
return;
}
tempSwUsers.forEach((user, idx) => {
const tr = document.createElement('tr');
tr.innerHTML = `
<td>${user. || user. || ''}</td>
<td>${user. || ''}</td>
<td>${user. || ''}</td>
<td>${user. || ''}</td>
<td>${user. || ''}</td>
<td style="text-align:center;">${user. ? '<i data-lucide="paperclip" class="text-primary"></i>' : '-'}</td>
<td>
<div style="display:flex; gap:0.5rem;">
<button class="btn btn-outline btn-sm btn-edit-user" data-idx="${idx}">수정</button>
<button class="btn btn-outline btn-sm btn-danger btn-del-user" data-idx="${idx}">삭제</button>
</div>
`;
tbody.appendChild(tr);
});
// 이벤트 연결
tbody.querySelectorAll('.btn-edit-user').forEach(btn => {
btn.addEventListener('click', (e) => {
const idx = parseInt((e.currentTarget as HTMLElement).getAttribute('data-idx')!);
openUserEditSubModal(idx);
});
});
tbody.querySelectorAll('.btn-del-user').forEach(btn => {
btn.addEventListener('click', (e) => {
const idx = parseInt((e.currentTarget as HTMLElement).getAttribute('data-idx')!);
if (confirm('사용자 할당을 삭제하시겠습니까?')) {
tempSwUsers.splice(idx, 1);
renderUserList();
}
});
});
createIcons({ icons: { Paperclip } });
}
function openUserEditSubModal(idx: number = -1) {
const subModal = document.getElementById('sw-user-edit-modal')!;
const form = document.getElementById('sw-user-edit-form') as HTMLFormElement;
form.reset();
setFieldValue('edit-user-index', idx);
if (idx > -1) {
const user = tempSwUsers[idx];
setFieldValue('new-user-법인', user. || user.);
setFieldValue('new-user-부서', user.);
setFieldValue('new-user-직위', user.);
setFieldValue('new-user-이름', user.);
setFieldValue('new-user-사용기간', user.);
} else {
setFieldValue('new-user-법인', currentSwUserAsset?.);
}
subModal.classList.remove('hidden');
}
export function initSwUserModal(onSave: () => void, closeModals: () => void) {
if (!document.getElementById('sw-user-modal')) {
document.body.insertAdjacentHTML('beforeend', SW_USER_MODAL_HTML);
}
const btnOpenAddUser = document.getElementById('btn-open-add-user');
const btnSaveEditUser = document.getElementById('btn-save-edit-user');
const btnSaveSwUserMapping = document.getElementById('btn-save-sw-user-mapping');
const btnCancelUserEdit = document.getElementById('btn-cancel-sw-user-edit');
const btnCloseUserEdit = document.getElementById('btn-close-sw-user-edit');
const btnCancelUserModal = document.getElementById('btn-cancel-sw-user-modal');
const btnCloseUserModal = document.getElementById('btn-close-sw-user-modal');
const mainSaveBtn = document.getElementById('btn-save-sw-user')!;
const addUserBtn = document.getElementById('btn-open-add-user')!;
const confirmUserBtn = document.getElementById('btn-confirm-user-edit')!;
btnOpenAddUser?.addEventListener('click', () => openUserEditModal(-1));
btnSaveEditUser?.addEventListener('click', () => saveUserEdit());
btnSaveSwUserMapping?.addEventListener('click', () => {
state.masterData.swUsers = state.masterData.swUsers.filter(u => u.swId !== currentSwUserAssetId);
state.masterData.swUsers.push(...tempSwUsers);
closeModals();
renderContent();
addUserBtn.addEventListener('click', () => openUserEditSubModal());
confirmUserBtn.addEventListener('click', () => {
saveUserDataToList();
});
btnCancelUserEdit?.addEventListener('click', () => document.getElementById('sw-user-edit-modal')?.classList.add('hidden'));
btnCloseUserEdit?.addEventListener('click', () => document.getElementById('sw-user-edit-modal')?.classList.add('hidden'));
btnCancelUserModal?.addEventListener('click', closeModals);
btnCloseUserModal?.addEventListener('click', closeModals);
}
function renderUserList() {
const tbody = document.getElementById('user-list-body')!;
tbody.innerHTML = '';
if (tempSwUsers.length === 0) {
tbody.innerHTML = '<tr><td colspan="7" style="padding: 2rem; text-align: center; color: var(--text-muted);">할당된 사용자가 없습니다.</td></tr>';
return;
}
tempSwUsers.forEach((user, idx) => {
const tr = document.createElement('tr');
const deptTeam = [user., user.].filter(Boolean).join(' / ') || '-';
const attachIcon = user. ? `<i data-lucide="paperclip" class="text-primary" style="width:16px; height:16px;" title="${user.}"></i>` : '-';
mainSaveBtn.addEventListener('click', () => {
if (!currentSwUserAsset) return;
tr.innerHTML = `
<td>${user.}</td>
<td>${deptTeam}</td>
<td>${user. || '-'}</td>
<td><strong>${user.}</strong></td>
<td style="text-align:center;">${user. || '-'}</td>
<td style="text-align:center;">${attachIcon}</td>
<td style="text-align:center;">
<button type="button" class="btn-icon btn-edit-user" data-idx="${idx}" style="color: var(--primary-color);"><i data-lucide="edit-2" style="width:14px; height:14px;"></i></button>
<button type="button" class="btn-icon btn-remove-user" data-idx="${idx}" style="color: var(--danger);"><i data-lucide="x" style="width:14px; height:14px;"></i></button>
</td>
`;
tbody.appendChild(tr);
// 전역 상태 업데이트
const existingIdx = state.masterData.swUsers.findIndex(u => u.sw_id === currentSwUserAsset!.id);
const newMapping = {
sw_id: currentSwUserAsset!.id,
userDataList: tempSwUsers
};
if (existingIdx > -1) state.masterData.swUsers[existingIdx] = newMapping as any;
else state.masterData.swUsers.push(newMapping as any);
onSave();
document.getElementById('sw-user-modal')?.classList.add('hidden');
});
createIcons({ icons: { Edit2, X, Paperclip } });
tbody.querySelectorAll('.btn-edit-user').forEach(btn => {
btn.addEventListener('click', (e) => {
const idx = parseInt((e.currentTarget as HTMLElement).getAttribute('data-idx')!);
openUserEditModal(idx);
});
document.getElementById('btn-close-sw-user-modal')?.addEventListener('click', () => {
document.getElementById('sw-user-modal')?.classList.add('hidden');
});
tbody.querySelectorAll('.btn-remove-user').forEach(btn => {
btn.addEventListener('click', (e) => {
const idx = parseInt((e.currentTarget as HTMLButtonElement).getAttribute('data-idx')!);
tempSwUsers.splice(idx, 1);
renderUserList();
});
document.getElementById('btn-cancel-sw-user')?.addEventListener('click', () => {
document.getElementById('sw-user-modal')?.classList.add('hidden');
});
document.getElementById('btn-close-user-edit')?.addEventListener('click', () => {
document.getElementById('sw-user-edit-modal')?.classList.add('hidden');
});
document.getElementById('btn-close-user-sub')?.addEventListener('click', () => {
document.getElementById('sw-user-edit-modal')?.classList.add('hidden');
});
}
export function openSwUserModal(asset: SoftwareAsset) {
openModal('sw-user-modal');
currentSwUserAssetId = asset.id;
tempSwUsers = state.masterData.swUsers.filter(u => u.swId === asset.id).map(u => ({...u}));
renderUserList();
}
function saveUserDataToList() {
const idx = parseInt(getFieldValue('edit-user-index'));
const Input = document.getElementById('new-user-신청서') as HTMLInputElement;
const = Input.files && Input.files.length > 0 ? Input.files[0].name : (idx > -1 ? tempSwUsers[idx]. : '');
function openUserEditModal(idx: number) {
const editModal = document.getElementById('sw-user-edit-modal')!;
editModal.classList.remove('hidden');
(document.getElementById('edit-user-idx') as HTMLInputElement).value = String(idx);
if (idx === -1) {
document.getElementById('sw-user-edit-modal-title')!.innerText = '새 사용자 추가';
(document.getElementById('new-user-법인') as HTMLSelectElement).value = '한맥';
(document.getElementById('new-user-부서') as HTMLInputElement).value = '';
(document.getElementById('new-user-팀') as HTMLInputElement).value = '';
(document.getElementById('new-user-직위') as HTMLInputElement).value = '';
(document.getElementById('new-user-이름') as HTMLInputElement).value = '';
(document.getElementById('new-user-사용기간') as HTMLInputElement).value = '';
(document.getElementById('new-user-신청서') as HTMLInputElement).value = '';
document.getElementById('new-user-신청서명')!.innerText = '';
} else {
document.getElementById('sw-user-edit-modal-title')!.innerText = '사용자 정보 수정';
const u = tempSwUsers[idx];
(document.getElementById('new-user-법인') as HTMLSelectElement).value = u.;
(document.getElementById('new-user-부서') as HTMLInputElement).value = u.;
(document.getElementById('new-user-팀') as HTMLInputElement).value = u.;
(document.getElementById('new-user-직위') as HTMLInputElement).value = u.;
(document.getElementById('new-user-이름') as HTMLInputElement).value = u.;
(document.getElementById('new-user-사용기간') as HTMLInputElement).value = u.;
(document.getElementById('new-user-신청서') as HTMLInputElement).value = '';
document.getElementById('new-user-신청서명')!.innerText = u. ? `첨부: ${u.}` : '';
}
}
function saveUserEdit() {
const idx = parseInt((document.getElementById('edit-user-idx') as HTMLInputElement).value);
const = (document.getElementById('new-user-이름') as HTMLInputElement).value.trim();
if (!) { alert('이름을 입력해주세요.'); return; }
const fileInput = document.getElementById('new-user-신청서') as HTMLInputElement;
let = '';
if (fileInput.files && fileInput.files.length > 0) {
= fileInput.files[0].name;
} else if (idx !== -1) {
= tempSwUsers[idx].;
}
const userData: SWUser = {
id: idx === -1 ? Math.random().toString(36).substring(2, 9) : tempSwUsers[idx].id,
swId: currentSwUserAssetId,
: (document.getElementById('new-user-법인') as HTMLSelectElement).value,
: (document.getElementById('new-user-부서') as HTMLInputElement).value,
: (document.getElementById('new-user-팀') as HTMLInputElement).value,
: (document.getElementById('new-user-직위') as HTMLInputElement).value,
,
: (document.getElementById('new-user-사용기간') as HTMLInputElement).value,
const userData: any = {
구매법인: getFieldValue('new-user-법인'),
부서: getFieldValue('new-user-부서'),
직위: getFieldValue('new-user-직위'),
이름: getFieldValue('new-user-이름'),
사용기간: getFieldValue('new-user-사용기간'),
};

View File

@@ -0,0 +1,33 @@
/**
* 모든 모달에서 공통으로 사용하는 리스트 데이터 및 설정
*/
// 구매법인 목록
export const CORP_LIST = ['한맥', '삼안', '장헌', '한라', 'PTC', '바론'];
// 사용조직 목록
export const ORG_LIST = ['한맥', '삼안', '장헌', '한라', 'PTC', '기술개발센터', '총괄기획실'];
// 하드웨어 자산 유형 목록
export const HW_TYPE_LIST = [
'서버', 'PC', '스토리지', 'NAS', 'DAS',
'CPU', 'HDD', 'RAM', 'GPU',
'모바일', '노트북', '태블릿'
];
// 설치위치 종속성 데이터
export const LOCATION_DATA: Record<string, string[]> = {
'한맥빌딩': ['MDF실', '1층', '2층', '3층', '4층', '5층', '6층', '7층', '파고라'],
'기술개발센터': ['서버실', '기타'],
'유니온빌딩': ['4층', '5층', '6층'],
'뉴코아빌딩': ['4층', '6층', '7층'],
'IDC': ['서관202', '서관203', '서관204', '서관205', '동관53', '동관54']
};
// 유형별 자산번호 접두사(Prefix) 매핑
export const TYPE_PREFIX_MAP: Record<string, string> = {
'서버': 'SVR', 'PC': 'PC', 'NAS': 'NAS', 'DAS': 'DAS', '스토리지': 'STO',
'CPU': 'CPU', 'HDD': 'HDD', 'RAM': 'RAM', 'GPU': 'GPU',
'모바일': 'MOB', '노트북': 'PC', '태블릿': 'TAB',
'개인PC': 'PC', '모바일기기': 'MOB'
};

View File

@@ -1,166 +0,0 @@
import { state } from '../../core/state';
import { HardwareAsset } from '../../core/excelHandler';
import { openModal } from './BaseModal';
const STORAGE_MODAL_HTML = `
<div id="storage-asset-modal" class="modal-overlay hidden">
<div class="modal-content">
<div class="modal-header">
<h2 id="storage-modal-title">스토리지 상세 정보</h2>
<button id="btn-close-storage-modal" class="btn-icon" aria-label="닫기"><i data-lucide="x"></i></button>
</div>
<div class="modal-body">
<form id="storage-asset-form" class="grid-form">
<input type="hidden" id="storage-asset-id" />
<input type="hidden" id="storage-asset-type" value="스토리지" />
<div class="form-group"><label for="storage-법인">법인</label><input type="text" id="storage-법인" required /></div>
<div class="form-group"><label for="storage-유형">유형</label><input type="text" id="storage-유형" required /></div>
<div class="form-group"><label for="storage-자산코드">자산코드</label><input type="text" id="storage-자산코드" required /></div>
<div class="form-group"><label for="storage-명칭">명칭</label><input type="text" id="storage-명칭" required /></div>
<div class="form-group"><label for="storage-위치">위치</label><input type="text" id="storage-위치" /></div>
<div class="form-group"><label for="storage-모델명">모델명</label><input type="text" id="storage-모델명" /></div>
<div class="form-group"><label for="storage-용량">용량</label><input type="text" id="storage-용량" /></div>
<div class="form-group"><label for="storage-담당자_정">담당자(정)</label><input type="text" id="storage-담당자_정" /></div>
<div class="form-group"><label for="storage-IP주소">IP주소</label><input type="text" id="storage-IP주소" /></div>
<div class="form-group"><label for="storage-구매일">구매일</label><input type="text" id="storage-구매일" /></div>
<div class="form-group"><label for="storage-금액">금액</label><input type="text" id="storage-금액" oninput="this.value = this.value.replace(/[^0-9]/g, '').replace(/\\B(?=(\\d{3})+(?!\d))/g, ',')" /></div>
</form>
</div>
<div class="modal-footer">
<button id="btn-delete-storage-asset" class="btn btn-outline btn-danger">삭제</button>
<div class="footer-actions">
<button id="btn-revert-storage-edit" class="btn btn-outline hidden">수정 취소</button>
<button id="btn-close-storage-footer" class="btn btn-outline">닫기</button>
<button id="btn-save-storage-asset" class="btn btn-primary">수정</button>
</div>
</div>
</div>
</div>
`;
export let currentAsset: HardwareAsset | null = null;
export let isEditMode = false;
export function setEditMode(edit: boolean) {
isEditMode = edit;
const storageForm = document.getElementById('storage-asset-form') as HTMLFormElement;
const btnSaveStorage = document.getElementById('btn-save-storage-asset') as HTMLButtonElement;
const btnRevertEdit = document.getElementById('btn-revert-storage-edit') as HTMLButtonElement;
const btnCloseFooter = document.getElementById('btn-close-storage-footer') as HTMLButtonElement;
if (edit) {
storageForm.classList.add('is-edit-mode');
storageForm.classList.remove('is-view-mode');
btnSaveStorage.textContent = '저장';
btnRevertEdit.classList.remove('hidden');
btnCloseFooter.classList.add('hidden');
} else {
storageForm.classList.add('is-view-mode');
storageForm.classList.remove('is-edit-mode');
btnSaveStorage.textContent = '수정';
btnRevertEdit.classList.add('hidden');
btnCloseFooter.classList.remove('hidden');
if (currentAsset) fillFormData(currentAsset);
}
}
export function fillFormData(asset: HardwareAsset) {
(document.getElementById('storage-asset-id') as HTMLInputElement).value = asset.id;
(document.getElementById('storage-법인') as HTMLInputElement).value = asset.;
(document.getElementById('storage-유형') as HTMLInputElement).value = asset.storage유형 || 'NAS';
(document.getElementById('storage-자산코드') as HTMLInputElement).value = asset.;
(document.getElementById('storage-명칭') as HTMLInputElement).value = asset.;
(document.getElementById('storage-위치') as HTMLInputElement).value = asset. || '';
(document.getElementById('storage-모델명') as HTMLInputElement).value = asset. || '';
(document.getElementById('storage-용량') as HTMLInputElement).value = asset. || '';
(document.getElementById('storage-담당자_정') as HTMLInputElement).value = asset._정 || '';
(document.getElementById('storage-IP주소') as HTMLInputElement).value = asset.IP주소 || '';
(document.getElementById('storage-구매일') as HTMLInputElement).value = asset. || '';
(document.getElementById('storage-금액') as HTMLInputElement).value = asset. || '';
}
export function initStorageModal(renderContent: () => void, closeModals: () => void) {
if (!document.getElementById('storage-asset-modal')) {
document.body.insertAdjacentHTML('beforeend', STORAGE_MODAL_HTML);
}
const storageForm = document.getElementById('storage-asset-form') as HTMLFormElement;
const btnRevertEdit = document.getElementById('btn-revert-storage-edit') as HTMLButtonElement;
const btnSaveStorage = document.getElementById('btn-save-storage-asset') as HTMLButtonElement;
const btnDeleteStorage = document.getElementById('btn-delete-storage-asset') as HTMLButtonElement;
const btnCloseHeader = document.getElementById('btn-close-storage-modal') as HTMLButtonElement;
const btnCloseFooter = document.getElementById('btn-close-storage-footer') as HTMLButtonElement;
btnRevertEdit?.addEventListener('click', () => setEditMode(false));
btnCloseHeader?.addEventListener('click', closeModals);
btnCloseFooter?.addEventListener('click', closeModals);
btnSaveStorage?.addEventListener('click', (e) => {
e.preventDefault();
if (!isEditMode) {
setEditMode(true);
return;
}
if (!storageForm.checkValidity()) { storageForm.reportValidity(); return; }
const id = (document.getElementById('storage-asset-id') as HTMLInputElement).value;
const newAsset: HardwareAsset = {
id: id || Math.random().toString(36).substring(2, 9),
type: '스토리지',
: (document.getElementById('storage-법인') as HTMLInputElement).value,
storage유형: (document.getElementById('storage-유형') as HTMLInputElement).value,
: (document.getElementById('storage-자산코드') as HTMLInputElement).value,
: (document.getElementById('storage-명칭') as HTMLInputElement).value,
: (document.getElementById('storage-위치') as HTMLInputElement).value,
: (document.getElementById('storage-모델명') as HTMLInputElement).value,
: (document.getElementById('storage-용량') as HTMLInputElement).value,
_정: (document.getElementById('storage-담당자_정') as HTMLInputElement).value,
IP주소: (document.getElementById('storage-IP주소') as HTMLInputElement).value,
: (document.getElementById('storage-구매일') as HTMLInputElement).value,
: (document.getElementById('storage-금액') as HTMLInputElement).value,
: '', MACaddress: '', HW사양: '', OS: '', : '', : ''
};
if (id) {
const idx = state.masterData.hw.findIndex(a => a.id === id);
if(idx !== -1) state.masterData.hw[idx] = newAsset;
} else {
state.masterData.hw.push(newAsset);
}
closeModals();
renderContent();
});
btnDeleteStorage?.addEventListener('click', (e) => {
e.preventDefault();
const id = (document.getElementById('storage-asset-id') as HTMLInputElement).value;
if (confirm('삭제하시겠습니까?')) {
state.masterData.hw = state.masterData.hw.filter(a => a.id !== id);
closeModals();
renderContent();
}
});
}
export function openStorageModal(asset?: HardwareAsset) {
currentAsset = asset || null;
const storageForm = document.getElementById('storage-asset-form') as HTMLFormElement;
const deleteBtn = document.getElementById('btn-delete-storage-asset')!;
openModal('storage-asset-modal');
storageForm.reset();
if (asset) {
document.getElementById('storage-modal-title')!.textContent = '스토리지 상세 정보 수정';
deleteBtn.style.display = 'block';
fillFormData(asset);
setEditMode(false);
} else {
document.getElementById('storage-modal-title')!.textContent = '신규 스토리지 자산 추가';
deleteBtn.style.display = 'none';
(document.getElementById('storage-asset-id') as HTMLInputElement).value = '';
setEditMode(true);
}
}

View File

@@ -3,7 +3,7 @@ import { state } from '../core/state';
const MENU_CONFIG = {
hw: {
label: '하드웨어',
tabs: ['대시보드', '개인PC', '서버', '스토리지', '전산비품']
tabs: ['대시보드', '개인PC', '서버', '스토리지', '전산비품', '모바일기기']
},
sw: {
label: '소프트웨어',
@@ -38,7 +38,7 @@ export function renderNavigation(onTabChange: (tab: string) => void) {
if (state.activeCategory !== catKey) {
state.activeCategory = catKey;
state.activeSubTab = '대시보드';
if (btnAddAsset) btnAddAsset.classList.add('hidden');
if (btnAddAsset) btnAddAsset.classList.remove('hidden');
render();
onTabChange('대시보드');
}
@@ -60,8 +60,7 @@ export function renderNavigation(onTabChange: (tab: string) => void) {
state.activeSubTab = tab;
if (btnAddAsset) {
if (tab === '대시보드') btnAddAsset.classList.add('hidden');
else btnAddAsset.classList.remove('hidden');
btnAddAsset.classList.remove('hidden');
}
render();

View File

@@ -42,10 +42,9 @@ export interface HardwareAsset {
이전사용조직?: string;
}
export interface SoftwareAsset {
id: string;
type: string; // '구독SW', '영구SW'
type: string; // '구독SW', '영구SW', '클라우드'
분야?: string;
법인: string;
부서?: string;
@@ -75,6 +74,7 @@ export interface SWUser {
이름: string;
사용기간: string;
신청서명: string;
userData?: any[]; // 동료 작업 호환용
}
export interface HardwareLog {
@@ -86,8 +86,13 @@ export interface HardwareLog {
}
export interface MasterAssetData {
hw: HardwareAsset[];
sw: SoftwareAsset[];
pc: HardwareAsset[];
server: HardwareAsset[];
storage: HardwareAsset[];
equip: HardwareAsset[];
mobile: HardwareAsset[];
subSw: SoftwareAsset[];
permSw: SoftwareAsset[];
swUsers: SWUser[];
logs: HardwareLog[];
}
@@ -95,178 +100,59 @@ export interface MasterAssetData {
const HW_TABS = ['개인PC', '서버', '스토리지', '전산비품'];
const SW_TABS = ['구독SW', '영구SW', '클라우드'];
// 확장된 헤더 (상세 페이지의 모든 필드 포함)
const PC_HEADERS = ['법인', '자산코드', '사용자', '위치', 'CPU', 'GPU', 'RAM', 'SSD1', 'SSD2', 'HDD1', 'HDD2', 'IP주소', 'HW사양', '구매일', '금액', '납품업체', '품의서명', '비고'];
const SERVER_HEADERS = ['법인', '자산번호', '유형', '용도', '상세내용', '현사용조직', '이전사용조직', '설치위치', '담당자(정)', '담당자(부)', 'IP 주소', '원격접속', '서버ID', '서버PW', '모델명', 'OS', 'CPU', 'RAM', 'GPU', 'SSD1', 'SSD2', 'HDD1', '모니터링', '비고'];
const STORAGE_HEADERS = ['법인', '유형', '자산코드', '명칭', '위치', '모델명', '용량', '담당자(정)', '담당자(부)', 'IP주소', 'MAC주소', '구매일', '금액', '납품업체', '품의서명', '비고'];
const HW_HEADERS = ['법인', '자산코드', '명칭', '위치', '관리자', 'IP주소', 'MACaddress', 'HW사양', 'OS', '구매일', '금액', '납품업체', '품의서명', '비고'];
const SERVER_HEADERS = ['구매법인', '자산번호', '구매일자', '유형', '용도', '상세내용', '현사용조직', '이전사용조직', '설치위치', '담당자(정)', '담당자(부)', 'IP 주소 1', 'IP 주소 2', '원격도구', '서버 ID', '서버 PW', '모델명', 'OS', 'CPU', 'RAM', 'GPU', 'Storage 1', 'Storage 2', 'Storage 3', '모니터링', '비고'];
const STORAGE_HEADERS = ['구매법인', '유형', '자산코드', '명칭', '위치', '모델명', '용량', '담당자(정)', '담당자(부)', 'IP주소', 'MAC주소', '구매일', '금액', '납품업체', '품의서명', '비고'];
const EQUIP_HEADERS = ['구매법인', '비품유형', '자산코드', '명칭', '위치', '관리자', 'IP주소', 'MACaddress', 'HW사양', 'OS', '구매일', '금액', '납품업체', '품의서명', '비고'];
const SUB_SW_HEADERS = ['ID', '분야', '법인', '부서', '제품명', '구매일', '구독일', '금액', '수량', '계정명', '납품업체', '비고'];
const PERM_SW_HEADERS = ['ID', '분야', '법인', '부서', '제품명', '구매일', '유지보수여부', '금액', '수량', '계정명', '납품업체', '비고'];
const CLOUD_HEADERS = ['ID', '플랫폼명', '법인', '부서', '사용용도(제품명)', '계정명', '결제수단', '결제일', '연결카드번호', '당월청구액', '비고'];
const SW_USER_HEADERS = ['id', 'swId', '법인', '부서', '팀', '직위', '이름', '사용기간', '신청서명'];
const HISTORY_HEADERS = ['id', 'assetId', 'date', 'details', 'user'];
/**
* 템플릿 엑셀 다중 시트로 다운로드
*/
export function downloadTemplate() {
const wb = XLSX.utils.book_new();
const tabConfigs = [
{ name: '개인PC', headers: PC_HEADERS },
{ name: '서버', headers: SERVER_HEADERS },
{ name: '스토리지', headers: STORAGE_HEADERS },
{ name: '전산비품', headers: EQUIP_HEADERS }
];
HW_TABS.forEach(tab => {
let hd = HW_HEADERS;
let wscols: any[] = [];
if (tab === '개인PC') {
hd = PC_HEADERS;
wscols = Array(hd.length).fill({wch: 15});
wscols[1] = {wch: 25}; // 자산코드
wscols[12] = {wch: 30}; // HW사양
} else if (tab === '서버') {
hd = SERVER_HEADERS;
wscols = Array(hd.length).fill({wch: 15});
wscols[3] = {wch: 25}; // 용도
wscols[4] = {wch: 30}; // 상세내용
} else if (tab === '스토리지') {
hd = STORAGE_HEADERS;
wscols = Array(hd.length).fill({wch: 15});
wscols[2] = {wch: 25}; // 자산코드
wscols[3] = {wch: 25}; // 명칭
} else {
hd = HW_HEADERS;
wscols = Array(hd.length).fill({wch: 15});
wscols[2] = {wch: 25}; // 명칭
wscols[7] = {wch: 30}; // HW사양
}
const ws = XLSX.utils.aoa_to_sheet([hd]);
ws['!cols'] = wscols;
XLSX.utils.book_append_sheet(wb, ws, tab);
tabConfigs.forEach(config => {
const ws = XLSX.utils.aoa_to_sheet([config.headers]);
ws['!cols'] = Array(config.headers.length).fill({ wch: 18 });
XLSX.utils.book_append_sheet(wb, ws, config.name);
});
SW_TABS.forEach(tab => {
let hd = tab === '구독SW' ? SUB_SW_HEADERS : (tab === '클라우드' ? CLOUD_HEADERS : PERM_SW_HEADERS);
const ws = XLSX.utils.aoa_to_sheet([hd]);
ws['!cols'] = tab === '클라우드'
? [{wch:15}, {wch:20}, {wch:15}, {wch:20}, {wch:30}, {wch:25}, {wch:15}, {wch:10}, {wch:15}, {wch:15}, {wch:30}]
: [{wch:15}, {wch:15}, {wch:15}, {wch:20}, {wch:30}, {wch:15}, {wch:20}, {wch:15}, {wch:10}, {wch:20}, {wch:20}, {wch:30}];
ws['!cols'] = Array(hd.length).fill({ wch: 18 });
XLSX.utils.book_append_sheet(wb, ws, tab);
});
const swUserWs = XLSX.utils.aoa_to_sheet([SW_USER_HEADERS]);
swUserWs['!cols'] = [{wch:15}, {wch:15}, {wch:15}, {wch:15}, {wch:15}, {wch:15}, {wch:15}, {wch:20}, {wch:25}];
XLSX.utils.book_append_sheet(wb, swUserWs, 'SW_사용자');
const historyWs = XLSX.utils.aoa_to_sheet([HISTORY_HEADERS]);
historyWs['!cols'] = [{wch:15}, {wch:20}, {wch:20}, {wch:50}, {wch:15}];
XLSX.utils.book_append_sheet(wb, historyWs, 'History');
XLSX.writeFile(wb, 'itam_assets_template.xlsx');
XLSX.writeFile(wb, 'itam_assets_template_full.xlsx');
}
/**
* 마스터 데이터를 여러 시트로 쪼개서 내보내기
*/
export function exportToExcel(masterData: MasterAssetData) {
const wb = XLSX.utils.book_new();
HW_TABS.forEach(tab => {
const targetAssets = masterData.hw.filter(a => a.type === tab);
let wsData;
let colsConfig;
if (tab === '개인PC') {
wsData = [
PC_HEADERS,
...targetAssets.map(a => [
a., a., a., a., a.CPU, a.GPU, a.RAM, a.SSD1, a.SSD2, a.HDD1, a.HDD2, a.IP주소, a.HW사양, a., a., a., a., a.
])
];
colsConfig = Array(PC_HEADERS.length).fill({wch: 15});
colsConfig[1] = {wch: 25};
colsConfig[12] = {wch: 30};
} else if (tab === '서버') {
wsData = [
SERVER_HEADERS,
...targetAssets.map(a => [
a., a., a.storage유형 || '물리', a. || '', a. || '', a. || '', a. || '', a., a._정 || '', a._부 || '',
a.IP주소, a. || '', a.ID || '', a.PW || '', a. || '', a.OS, a.CPU, a.RAM, a.GPU || '', a.SSD1 || '', a.SSD2 || '', a.HDD1 || '', a. || '', a. || ''
])
];
colsConfig = Array(SERVER_HEADERS.length).fill({wch: 15});
colsConfig[3] = {wch: 25};
colsConfig[4] = {wch: 30};
} else if (tab === '스토리지') {
wsData = [
STORAGE_HEADERS,
...targetAssets.map(a => [
a., a.storage유형, a., a., a., a., a., a._정, a._부, a.IP주소, a.MACaddress, a., a., a., a., a.
])
];
colsConfig = Array(STORAGE_HEADERS.length).fill({wch: 15});
colsConfig[2] = {wch: 25};
colsConfig[3] = {wch: 25};
} else {
wsData = [
HW_HEADERS,
...targetAssets.map(a => [
a., a., a., a., a., a.IP주소, a.MACaddress, a.HW사양, a.OS, a., a., a., a., a.
])
];
colsConfig = Array(HW_HEADERS.length).fill({wch: 15});
colsConfig[2] = {wch: 25};
colsConfig[7] = {wch: 30};
}
const ws = XLSX.utils.aoa_to_sheet(wsData);
ws['!cols'] = colsConfig;
XLSX.utils.book_append_sheet(wb, ws, tab);
});
SW_TABS.forEach(tab => {
const targetAssets = masterData.sw.filter(a => a.type === tab);
let wsData;
if (tab === '구독SW') {
wsData = [
SUB_SW_HEADERS,
...targetAssets.map(a => [a.id, a.||'', a., a.||'', a., a., a., a., a., a., a., a.])
];
} else if (tab === '클라우드') {
wsData = [
CLOUD_HEADERS,
...targetAssets.map(a => [a.id, a.||'', a., a.||'', a., a., a.||'', a.||'', a.||'', a.||'', a.])
];
} else {
wsData = [
PERM_SW_HEADERS,
...targetAssets.map(a => [a.id, a.||'', a., a.||'', a., a., a. ? 'Y' : 'N', a., a., a., a., a.])
];
}
const ws = XLSX.utils.aoa_to_sheet(wsData);
ws['!cols'] = tab === '클라우드'
? [{wch:15}, {wch:20}, {wch:15}, {wch:20}, {wch:30}, {wch:25}, {wch:15}, {wch:10}, {wch:15}, {wch:15}, {wch:30}]
: [{wch:15}, {wch:15}, {wch:15}, {wch:20}, {wch:30}, {wch:15}, {wch:20}, {wch:15}, {wch:10}, {wch:20}, {wch:20}, {wch:30}];
XLSX.utils.book_append_sheet(wb, ws, tab);
});
const swUserWsData = [
SW_USER_HEADERS,
...masterData.swUsers.map(u => [u.id, u.swId, u., u., u., u., u., u., u.])
const exportMap = [
{ tab: '개인PC', list: masterData.pc, headers: PC_HEADERS, map: (a: any) => [a., a., a., a., a.CPU, a.GPU, a.RAM, a.SSD1, a.SSD2, a.HDD1, a.HDD2, a.IP주소, a.HW사양, a., a., a., a., a.] },
{ tab: '서버', list: masterData.server, headers: SERVER_HEADERS, map: (a: any) => [a., a., a., a.storage유형 || '물리', a., a., a., a., a., a._정, a._부, a.IP주소, a.IP2, a., a.ID, a.PW, a., a.OS, a.CPU, a.RAM, a.GPU, a.SSD1, a.SSD2, a.HDD1, a., a.] },
{ tab: '스토리지', list: masterData.storage, headers: STORAGE_HEADERS, map: (a: any) => [a., a.storage유형, a., a., a., a., a., a._정, a._부, a.IP주소, a.MACaddress, a., a., a., a., a.] },
{ tab: '전산비품', list: masterData.equip, headers: EQUIP_HEADERS, map: (a: any) => [a., a., a., a., a., a., a.IP주소, a.MACaddress, a.HW사양, a.OS, a., a., a., a., a.] },
{ tab: '구독SW', list: masterData.subSw, headers: SUB_SW_HEADERS, map: (a: any) => [a.id, a., a., a., a., a., a., a., a., a., a., a.] },
{ tab: '영구SW', list: masterData.permSw, headers: PERM_SW_HEADERS, map: (a: any) => [a.id, a., a., a., a., a., a. ? 'Y' : 'N', a., a., a., a., a.] }
];
const swUserWs = XLSX.utils.aoa_to_sheet(swUserWsData);
swUserWs['!cols'] = [{wch:15}, {wch:15}, {wch:15}, {wch:15}, {wch:15}, {wch:15}, {wch:15}, {wch:20}, {wch:25}];
XLSX.utils.book_append_sheet(wb, swUserWs, 'SW_사용자');
const historyWsData = [
HISTORY_HEADERS,
...masterData.logs.map(l => [l.id, l.assetId, l.date, l.details, l.user])
];
const historyWs = XLSX.utils.aoa_to_sheet(historyWsData);
historyWs['!cols'] = [{wch:15}, {wch:20}, {wch:20}, {wch:50}, {wch:15}];
XLSX.utils.book_append_sheet(wb, historyWs, 'History');
const dateStr = new Date().toISOString().split('T')[0];
XLSX.writeFile(wb, `itam_assets_master_${dateStr}.xlsx`);
exportMap.forEach(m => {
const ws = XLSX.utils.aoa_to_sheet([m.headers, ...m.list.map(m.map)]);
XLSX.utils.book_append_sheet(wb, ws, m.tab);
});
XLSX.writeFile(wb, `itam_master_full_${new Date().toISOString().split('T')[0]}.xlsx`);
}
export async function parseExcel(file: File): Promise<MasterAssetData> {
@@ -274,153 +160,29 @@ export async function parseExcel(file: File): Promise<MasterAssetData> {
const reader = new FileReader();
reader.onload = (e) => {
try {
const data = e.target?.result;
const workbook = XLSX.read(data, { type: 'binary' });
const hwAssets: HardwareAsset[] = [];
const swAssets: SoftwareAsset[] = [];
const swUsers: SWUser[] = [];
const logs: HardwareLog[] = [];
const workbook = XLSX.read(e.target?.result, { type: 'binary' });
const data: MasterAssetData = { pc: [], server: [], storage: [], equip: [], mobile: [], subSw: [], permSw: [], swUsers: [], logs: [] };
workbook.SheetNames.forEach(sheetName => {
const worksheet = workbook.Sheets[sheetName];
const json = XLSX.utils.sheet_to_json(worksheet) as any[];
if (HW_TABS.includes(sheetName)) {
json.forEach(row => {
if (sheetName === '개인PC') {
hwAssets.push({
id: Math.random().toString(36).substring(2, 9),
type: sheetName,
법인: row['법인'] || '',
자산코드: row['자산코드'] || '',
: '',
위치: row['위치'] || '',
사용자: row['사용자'] || '',
: '',
IP주소: row['IP주소'] || '',
MACaddress: '',
HW사양: row['HW사양'] || '',
OS: row['OS'] || '',
CPU: row['CPU'] || '', GPU: row['GPU'] || '', RAM: row['RAM'] || '',
SSD1: row['SSD1'] || '', SSD2: row['SSD2'] || '', HDD1: row['HDD1'] || '', HDD2: row['HDD2'] || '',
구매일: row['구매일'] || '', 금액: row['금액'] ? String(row['금액']) : '',
납품업체: row['납품업체'] || '', 품의서명: row['품의서명'] || '',
비고: row['비고'] || ''
});
} else if (sheetName === '서버') {
hwAssets.push({
id: Math.random().toString(36).substring(2, 9),
type: sheetName,
법인: row['법인'] || '',
자산코드: row['자산번호'] || row['자산코드'] || '',
명칭: row['용도'] || row['명칭'] || '',
용도: row['용도'] || '',
상세: row['상세내용'] || row['상세'] || '',
현사용조직: row['현사용조직'] || '',
이전사용조직: row['이전사용조직'] || '',
위치: row['설치위치'] || row['위치'] || '',
관리자: row['담당자(정)'] || '', 담당자_정: row['담당자(정)'] || '', 담당자_부: row['담당자(부)'] || '',
IP주소: row['IP 주소'] || row['IP주소'] || '',
원격접속: row['원격접속'] || '',
서버ID: row['서버ID'] || '',
서버PW: row['서버PW'] || '',
모델명: row['모델명'] || '', OS: row['OS'] || '',
CPU: row['CPU'] || '', RAM: row['RAM'] || '', GPU: row['GPU'] || '',
SSD1: row['SSD1'] || row['Storage1'] || '',
SSD2: row['SSD2'] || row['Storage2'] || '',
HDD1: row['HDD1'] || row['Storage3'] || '',
모니터링: row['모니터링'] || '',
비고: row['비고'] || '',
storage유형: row['유형'] || '물리',
MACaddress: '', HW사양: '', : '', : '', : '', : '',
});
} else if (sheetName === '스토리지') {
hwAssets.push({
id: Math.random().toString(36).substring(2, 9),
type: sheetName,
법인: row['법인'] || '', 자산코드: row['자산코드'] || '', 명칭: row['명칭'] || '', 위치: row['위치'] || '',
: '', IP주소: row['IP주소'] || '', MACaddress: row['MAC주소'] || '', HW사양: '', OS: '',
storage유형: row['유형'] || '', 모델명: row['모델명'] || '', 용량: row['용량'] || '',
담당자_정: row['담당자(정)'] || '', 담당자_부: row['담당자(부)'] || '',
구매일: row['구매일'] || '', 금액: row['금액'] ? String(row['금액']) : '',
납품업체: row['납품업체'] || '', 품의서명: row['품의서명'] || '',
비고: row['비고'] || ''
});
} else {
hwAssets.push({
id: Math.random().toString(36).substring(2, 9),
type: sheetName,
법인: row['법인'] || '', 자산코드: row['자산코드'] || '', 명칭: row['명칭'] || '', 위치: row['위치'] || '',
관리자: row['관리자'] || '', IP주소: row['IP주소'] || '', MACaddress: row['MACaddress'] || '',
HW사양: row['HW사양'] || '', OS: row['OS'] || '',
구매일: row['구매일'] || '', 금액: row['금액'] ? String(row['금액']) : '',
납품업체: row['납품업체'] || '', 품의서명: row['품의서명'] || '',
비고: row['비고'] || ''
});
}
});
}
if (SW_TABS.includes(sheetName)) {
json.forEach(row => {
if (sheetName === '클라우드') {
swAssets.push({
id: row['ID'] ? String(row['ID']) : Math.random().toString(36).substring(2, 9),
type: sheetName,
플랫폼명: row['플랫폼명'] || '',
법인: row['법인'] || '',
부서: row['부서'] || '',
제품명: row['사용용도(제품명)'] || '',
: '',
: '',
수량: 1,
계정명: row['계정명'] || '',
결제수단: row['결제수단'] || '',
결제일: row['결제일'] ? String(row['결제일']) : '',
연결카드번호: row['연결카드번호'] ? String(row['연결카드번호']) : '',
당월청구액: row['당월청구액'] ? String(row['당월청구액']) : '',
: '',
비고: row['비고'] || '',
});
} else {
swAssets.push({
id: row['ID'] ? String(row['ID']) : Math.random().toString(36).substring(2, 9),
type: sheetName, 분야: row['분야'] || '', 법인: row['법인'] || '', 부서: row['부서'] || '', 제품명: row['제품명'] || '',
구매일: row['구매일'] || '', 구독일: row['구독일'] || '', 유지보수여부: row['유지보수여부'] === 'Y' || row['유지보수여부'] === true,
금액: row['금액'] ? String(row['금액']) : '', 수량: parseInt(row['수량'] || '1', 10),
계정명: row['계정명'] || '', 납품업체: row['납품업체'] || '', 비고: row['비고'] || '',
});
}
});
}
if (sheetName === 'SW_사용자') {
json.forEach(row => {
swUsers.push({
id: row['id'] ? String(row['id']) : Math.random().toString(36).substring(2, 9),
swId: row['swId'] ? String(row['swId']) : '', 법인: row['법인'] || '', 부서: row['부서'] || '',
: row['팀'] || '', 직위: row['직위'] || '', 이름: row['이름'] || '',
사용기간: row['사용기간'] || '', 신청서명: row['신청서명'] || '',
});
});
}
if (sheetName === 'History') {
json.forEach(row => {
logs.push({
id: row['id'] ? String(row['id']) : Math.random().toString(36).substring(2, 9),
assetId: row['assetId'] ? String(row['assetId']) : '',
date: row['date'] || '', details: row['details'] || '', user: row['user'] || '',
});
});
const rows = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName]) as any[];
if (sheetName === '개인PC') {
rows.forEach(r => data.pc.push({ id: Math.random().toString(36).substring(2, 9), type: '개인PC', 법인: r['법인']||'', 자산코드: r['자산코드']||'', 사용자: r['사용자']||'', 위치: r['위치']||'', CPU: r['CPU']||'', GPU: r['GPU']||'', RAM: r['RAM']||'', SSD1: r['SSD1']||'', SSD2: r['SSD2']||'', HDD1: r['HDD1']||'', HDD2: r['HDD2']||'', IP주소: r['IP주소']||'', HW사양: r['HW사양']||'', 구매일: r['구매일']||'', 금액: r['금액']||'', 납품업체: r['납품업체']||'', 품의서명: r['품의서명']||'', 비고: r['비고']||'', : '', MACaddress: '', OS: '', : '' }));
} else if (sheetName === '서버') {
rows.forEach(r => data.server.push({ id: Math.random().toString(36).substring(2, 9), type: '서버', 법인: r['구매법인']||r['법인']||'', 자산코드: r['자산번호']||r['자산코드']||'', 구매일: r['구매일자']||r['구매일']||'', storage유형: r['유형']||'물리', 용도: r['용도']||'', 상세: r['상세내용']||'', 현사용조직: r['현사용조직']||'', 이전사용조직: r['이전사용조직']||'', 위치: r['설치위치']||r['위치']||'', 담당자_정: r['담당자(정)']||'', 담당자_부: r['담당자(부)']||'', IP주소: r['IP 주소 1']||r['IP주소']||'', 원격접속: r['원격도구']||r['원격접속']||'', 서버ID: r['서버 ID']||r['서버ID']||'', 서버PW: r['서버 PW']||r['서버PW']||'', 모델명: r['모델명']||'', OS: r['OS']||'', CPU: r['CPU']||'', RAM: r['RAM']||'', GPU: r['GPU']||'', SSD1: r['Storage 1']||r['SSD1']||'', SSD2: r['Storage 2']||r['SSD2']||'', HDD1: r['Storage 3']||r['HDD1']||'', 모니터링: r['모니터링']||'', 비고: r['비고']||'', : '', : '', MACaddress: '', HW사양: '', : '', : '', : '' }));
} else if (sheetName === '스토리지') {
rows.forEach(r => data.storage.push({ id: Math.random().toString(36).substring(2, 9), type: '스토리지', 법인: r['구매법인']||r['법인']||'', storage유형: r['유형']||'', 자산코드: r['자산코드']||'', 명칭: r['명칭']||'', 위치: r['위치']||'', 모델명: r['모델명']||'', 용량: r['용량']||'', 담당자_정: r['담당자(정)']||'', 담당자_부: r['담당자(부)']||'', IP주소: r['IP주소']||'', MACaddress: r['MAC주소']||'', 구매일: r['구매일']||'', 금액: r['금액']||'', 납품업체: r['납품업체']||'', 품의서명: r['품의서명']||'', 비고: r['비고']||'', HW사양: '', OS: '', : '' }));
} else if (sheetName === '전산비품') {
rows.forEach(r => data.equip.push({ id: Math.random().toString(36).substring(2, 9), type: '전산비품', 법인: r['구매법인']||r['법인']||'', 비품유형: r['비품유형']||r['유형']||'', 자산코드: r['자산코드']||'', 명칭: r['명칭']||'', 위치: r['위치']||'', 관리자: r['관리자']||'', IP주소: r['IP주소']||'', MACaddress: r['MACaddress']||'', HW사양: r['HW사양']||'', OS: r['OS']||'', 구매일: r['구매일']||'', 금액: r['금액']||'', 납품업체: r['납품업체']||'', 품의서명: r['품의서명']||'', 비고: r['비고']||'' }));
} else if (sheetName === '구독SW') {
rows.forEach(r => data.subSw.push({ id: r['ID']||Math.random().toString(36).substring(2, 9), type: '구독SW', 분야: r['분야']||'', 법인: r['법인']||'', 부서: r['부서']||'', 제품명: r['제품명']||'', 구매일: r['구매일']||'', 구독일: r['구독일']||'', 금액: r['금액']||'', 수량: parseInt(r['수량']||'1'), 계정명: r['계정명']||'', 납품업체: r['납품업체']||'', 비고: r['비고']||'' }));
} else if (sheetName === '영구SW') {
rows.forEach(r => data.permSw.push({ id: r['ID']||Math.random().toString(36).substring(2, 9), type: '영구SW', 분야: r['분야']||'', 법인: r['법인']||'', 부서: r['부서']||'', 제품명: r['제품명']||'', 구매일: r['구매일']||'', 유지보수여부: r['유지보수여부']==='Y', 금액: r['금액']||'', 수량: parseInt(r['수량']||'1'), 계정명: r['계정명']||'', 납품업체: r['납품업체']||'', 비고: r['비고']||'' }));
} else if (sheetName === 'SW_사용자') {
rows.forEach(r => data.swUsers.push({ id: r['id']||Math.random().toString(36).substring(2, 9), swId: r['swId']||'', 법인: r['법인']||'', 부서: r['부서']||'', : r['팀']||'', 직위: r['직위']||'', 이름: r['이름']||'', 사용기간: r['사용기간']||'', 신청서명: r['신청서명']||'' }));
}
});
resolve({ hw: hwAssets, sw: swAssets, swUsers, logs });
} catch (err) {
reject(err);
}
resolve(data);
} catch (err) { reject(err); }
};
reader.onerror = (err) => reject(err);
reader.readAsBinaryString(file);
});
}

View File

@@ -1,96 +1,67 @@
import { MasterAssetData, HardwareAsset } from './excelHandler';
import { generateDummyData } from './dummyDataGenerator';
import { realServerData } from './realServerData';
import { HardwareAsset, SoftwareAsset, SWUser, HardwareLog } from './excelHandler';
// --- State Definitions ---
export interface AppState {
masterData: MasterAssetData;
activeCategory: 'hw' | 'sw' | 'ops';
activeSubTab: string;
activeCharts: any[];
export interface MasterAssetData {
pc: HardwareAsset[];
server: HardwareAsset[];
storage: HardwareAsset[];
equip: HardwareAsset[];
mobile: HardwareAsset[];
subSw: SoftwareAsset[];
permSw: SoftwareAsset[];
swUsers: SWUser[];
logs: HardwareLog[];
}
const dummy = generateDummyData();
// 서버 데이터만 실제 데이터로 교체
const mergedHw: HardwareAsset[] = [
...dummy.hw.filter(a => a.type !== '서버'),
...realServerData.map((serverData: any) => {
const s = serverData;
return {
id: s.id || Math.random().toString(36).substring(2, 9),
type: '서버',
법인: s.법인,
자산코드: s.자산코드,
명칭: s.용도 || '',
위치: s.위치,
관리자: s.담당자_정 || '홍길동',
담당자_정: s.담당자_정 || '홍길동',
담당자_부: s.담당자_부 || '김철수',
IP주소: s.IP주소,
IP2: s.IP2 || '',
MACaddress: s.MACaddress || '',
HW사양: s.HW사양 || '',
OS: s.OS,
CPU: s.CPU,
RAM: s.RAM,
SSD1: s.SSD1,
SSD2: s.SSD2,
HDD1: s.HDD1,
storage유형: s.storage유형,
모델명: s.모델명,
구매일: s.구매일 || '',
금액: s.금액 || '',
납품업체: s.납품업체 || '',
품의서명: s.품의서명 || '',
용도: s.용도,
상세: s.상세,
원격접속: s.원격접속 || '',
서버ID: s.서버ID || '',
서버PW: s.서버PW || '',
모니터링: s.모니터링 || '',
비고: s.비고 || ''
}})
];
export interface AppState {
activeCategory: 'dashboard' | 'hw' | 'sw';
activeSubTab: string; // '대시보드', '개인PC', '서버', '스토리지', '전산비품', '구독SW', '영구SW'
masterData: MasterAssetData;
}
// --- Initial State ---
// 초기 상태
export const state: AppState = {
masterData: {
...dummy,
hw: mergedHw, // 기본적으로 하드코딩된 데이터를 가지고 시작
logs: dummy.logs || []
},
activeCategory: 'hw',
activeCategory: 'dashboard',
activeSubTab: '대시보드',
activeCharts: []
masterData: {
pc: [],
server: [],
storage: [],
equip: [],
mobile: [],
subSw: [],
permSw: [],
swUsers: [],
logs: []
}
};
/**
* DB에서 데이터 로드
* 전용 API 엔드포인트들로부터 데이터 로드
*/
export async function loadMasterDataFromDB() {
try {
const [hwRes, swRes, swUserRes] = await Promise.all([
fetch('http://localhost:3000/api/hw'),
fetch('http://localhost:3000/api/sw'),
fetch('http://localhost:3000/api/sw-users')
]);
const endpoints = [
{ key: 'pc', url: 'http://localhost:3000/api/pc' },
{ key: 'server', url: 'http://localhost:3000/api/server' },
{ key: 'storage', url: 'http://localhost:3000/api/storage' },
{ key: 'equip', url: 'http://localhost:3000/api/equip' },
{ key: 'mobile', url: 'http://localhost:3000/api/mobile' },
{ key: 'subSw', url: 'http://localhost:3000/api/sw/sub' },
{ key: 'permSw', url: 'http://localhost:3000/api/sw/perm' },
{ key: 'swUsers', url: 'http://localhost:3000/api/sw-users' }
];
if (hwRes.ok) {
const hwData = await hwRes.json();
if (hwData && hwData.length > 0) state.masterData.hw = hwData;
const results = await Promise.all(endpoints.map(e => fetch(e.url)));
for (let i = 0; i < endpoints.length; i++) {
if (results[i].ok) {
const data = await results[i].json();
(state.masterData as any)[endpoints[i].key] = data || [];
}
}
if (swRes.ok) {
const swData = await swRes.json();
if (swData && swData.length > 0) state.masterData.sw = swData;
}
if (swUserRes.ok) {
const swUserData = await swUserRes.json();
if (swUserData && swUserData.length > 0) state.masterData.swUsers = swUserData;
}
console.log('✅ DB 데이터 로드 완료');
console.log('✅ 6개 테이블 데이터 로드 완료');
return true;
} catch (err) {
console.warn('⚠️ 백엔드 서버 연결 실패. 로컬 데이터를 유지합니다.');
@@ -102,3 +73,46 @@ export async function loadMasterDataFromDB() {
export function updateState(newState: Partial<AppState>) {
Object.assign(state, newState);
}
/**
* 하드웨어 자산 통합 저장 (자동 카테고리 분류)
*/
export function saveHardwareAsset(updatedAsset: HardwareAsset) {
const { type } = updatedAsset;
const detailPurpose = (updatedAsset as any). || '';
// 1. 타겟 카테고리 결정
let targetKey: keyof MasterAssetData = 'equip';
if (type === '서버' || (type === 'PC' && detailPurpose === '서버')) targetKey = 'server';
else if (['NAS', 'DAS', '스토리지'].includes(type)) targetKey = 'storage';
else if (['CPU', 'GPU', 'RAM', 'HDD'].includes(type)) targetKey = 'equip';
else if (['모바일', '태블릿', '노트북'].includes(type)) targetKey = 'mobile';
else if (type === 'PC' && detailPurpose === '개인PC') targetKey = 'pc';
// 2. 모든 카테고리에서 기존 ID 자산 삭제 (이동 가능성 대비)
const hwKeys: (keyof MasterAssetData)[] = ['pc', 'server', 'storage', 'equip', 'mobile'];
hwKeys.forEach(key => {
const arr = state.masterData[key] as HardwareAsset[];
if (Array.isArray(arr)) {
const idx = arr.findIndex(a => a.id === updatedAsset.id);
if (idx > -1) arr.splice(idx, 1);
}
});
// 3. 새로운 타겟 카테고리에 추가
(state.masterData[targetKey] as HardwareAsset[]).push(updatedAsset);
}
/**
* 하드웨어 자산 통합 삭제
*/
export function deleteHardwareAsset(assetId: string) {
const hwKeys: (keyof MasterAssetData)[] = ['pc', 'server', 'storage', 'equip', 'mobile'];
hwKeys.forEach(key => {
const arr = state.masterData[key] as HardwareAsset[];
if (Array.isArray(arr)) {
const idx = arr.findIndex(a => a.id === assetId);
if (idx > -1) arr.splice(idx, 1);
}
});
}

View File

@@ -54,3 +54,24 @@ export function getAssetChanges(oldAsset: any, newAsset: any, fields: {key: stri
});
return changes.join('\n');
}
/**
* 자산 목록 정렬 (방안 C: 구매법인별 -> 자산번호 순)
*/
export function sortAssets<T>(list: T[]): T[] {
return [...list].sort((a: any, b: any) => {
// 1순위: 구매법인 (한글 가나다순)
const corpA = String(a. || '').trim();
const corpB = String(b. || '').trim();
if (corpA < corpB) return -1;
if (corpA > corpB) return 1;
// 2순위: 자산번호 (영문/숫자순)
const codeA = String(a. || a. || '').trim();
const codeB = String(b. || b. || '').trim();
if (codeA < codeB) return -1;
if (codeA > codeB) return 1;
return 0;
});
}

View File

@@ -13,56 +13,47 @@ import { initSwUserModal } from './components/Modal/SWUserModal';
import { initDashboardDetailModal } from './components/Modal/DashboardDetailModal';
import { createIcons, Download, Upload, FileSpreadsheet, Plus, X, LayoutDashboard, Monitor, Server, Database, Laptop, CalendarClock, Key, Cpu, Layers, Users, Paperclip, Edit2, History, RefreshCcw } from 'lucide';
// --- DB 저장을 위한 헬퍼 함수 ---
async function saveAllHwToDB(assets: HardwareAsset[]) {
// --- DB 저장을 위한 세분화된 헬퍼 함수 ---
async function apiBatchSave(url: string, data: any[], label: string) {
try {
const response = await fetch('http://localhost:3000/api/hw/batch', {
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(assets)
body: JSON.stringify(data)
});
if (!response.ok) throw new Error('HW DB 저장 실패');
console.log('✅ HW DB 저장 완료');
if (!response.ok) throw new Error(`${label} DB 저장 실패`);
console.log(`${label} DB 저장 완료`);
} catch (err) {
console.error('❌ HW DB 저장 실패:', err);
console.error(`${label} DB 저장 오류:`, err);
}
}
async function saveAllSwToDB(assets: SoftwareAsset[]) {
try {
const response = await fetch('http://localhost:3000/api/sw/batch', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(assets)
});
if (!response.ok) throw new Error('SW DB 저장 실패');
console.log('✅ SW DB 저장 완료');
} catch (err) {
console.error('❌ SW DB 저장 실패:', err);
}
}
const savePcToDB = () => apiBatchSave('http://localhost:3000/api/pc/batch', state.masterData.pc, '개인PC');
const saveServerToDB = () => apiBatchSave('http://localhost:3000/api/server/batch', state.masterData.server, '서버');
const saveStorageToDB = () => apiBatchSave('http://localhost:3000/api/storage/batch', state.masterData.storage, '스토리지');
const saveEquipToDB = () => apiBatchSave('http://localhost:3000/api/equip/batch', state.masterData.equip, '전산비품');
const saveMobileToDB = () => apiBatchSave('http://localhost:3000/api/mobile/batch', state.masterData.mobile, '모바일기기');
const saveSubSwToDB = () => apiBatchSave('http://localhost:3000/api/sw/sub/batch', state.masterData.subSw, '구독SW');
const savePermSwToDB = () => apiBatchSave('http://localhost:3000/api/sw/perm/batch', state.masterData.permSw, '영구SW');
const saveSwUsersToDB = () => apiBatchSave('http://localhost:3000/api/sw-users/batch', state.masterData.swUsers, 'SW사용자');
async function saveAllSwUsersToDB(users: SWUser[]) {
try {
const response = await fetch('http://localhost:3000/api/sw-users/batch', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(users)
});
if (!response.ok) throw new Error('SW User DB 저장 실패');
console.log('✅ SW User DB 저장 완료');
} catch (err) {
console.error('❌ SW User DB 저장 실패:', err);
}
// 모든 하드웨어 DB 동기화
async function saveAllHardwareToDB() {
await Promise.all([
savePcToDB(),
saveServerToDB(),
saveStorageToDB(),
saveEquipToDB(),
saveMobileToDB()
]);
}
// --- App Initialization ---
function initApp() {
console.log('🚀 ITAM System Initializing...');
console.log('🚀 ITAM Dedicated System Initializing...');
const mainContent = document.getElementById('main-content')!;
if (!mainContent) return;
// 1. 전역 모달 및 내비게이션 초기화
const { closeAllModals } = initBaseModal();
try {
@@ -74,45 +65,29 @@ function initApp() {
}
});
initPcModal(() => {
saveAllHwToDB(state.masterData.hw);
renderSWTable(mainContent);
}, closeAllModals);
initHwModal(() => {
saveAllHwToDB(state.masterData.hw);
renderSWTable(mainContent);
}, closeAllModals);
initStorageModal(() => {
saveAllHwToDB(state.masterData.hw);
renderSWTable(mainContent);
}, closeAllModals);
// 동료의 새로운 UI 방식(renderSWTable)과 우리의 통합 저장 로직 결합
initPcModal(() => { saveAllHardwareToDB(); renderSWTable(mainContent); }, closeAllModals);
initHwModal(() => { saveAllHardwareToDB(); renderSWTable(mainContent); }, closeAllModals);
initStorageModal(() => { saveAllHardwareToDB(); renderSWTable(mainContent); }, closeAllModals);
initSwModal(() => {
saveAllSwToDB(state.masterData.sw);
if (state.activeSubTab === '구독SW') saveSubSwToDB();
else savePermSwToDB();
renderSWTable(mainContent);
}, closeAllModals);
initCloudModal(() => {
saveAllSwToDB(state.masterData.sw);
// 클라우드 저장 로직 추가 필요시 여기에 구현
renderSWTable(mainContent);
}, closeAllModals);
initSwUserModal(() => {
saveAllSwUsersToDB(state.masterData.swUsers);
renderSWTable(mainContent);
}, closeAllModals);
initSwUserModal(() => { saveSwUsersToDB(); renderSWTable(mainContent); }, closeAllModals);
initDashboardDetailModal();
} catch (e) {
console.error('❌ Initialization failed:', e);
}
} catch (e) { console.error('❌ Initialization failed:', e); }
// 2. 초기 렌더링
renderDashboard(mainContent);
// 3. 비동기 데이터 로드
loadMasterDataFromDB().then((success) => {
if (success) {
if (state.activeSubTab === '대시보드') renderDashboard(mainContent);
@@ -120,7 +95,6 @@ function initApp() {
}
});
// 4. 이벤트 바인딩
document.getElementById('btn-download-template')?.addEventListener('click', () => downloadTemplate());
document.getElementById('btn-export-excel')?.addEventListener('click', () => exportToExcel(state.masterData));
@@ -130,11 +104,9 @@ function initApp() {
if (file) {
const data = await parseExcel(file);
state.masterData = data;
// 엑셀 업로드 시 모든 카테고리 일괄 덮어쓰기 저장
await Promise.all([
saveAllHwToDB(data.hw),
saveAllSwToDB(data.sw),
saveAllSwUsersToDB(data.swUsers)
saveAllHardwareToDB(),
saveSubSwToDB(), savePermSwToDB(), saveSwUsersToDB()
]);
renderSWTable(mainContent);
}
@@ -146,7 +118,7 @@ function initApp() {
id: Math.random().toString(36).substring(2, 9),
type: state.activeSubTab,
: '한맥', : '', : '', : '', : '', IP주소: '', MACaddress: '', HW사양: '', OS: '', : '', : ''
} as any);
} as any, 'add');
} else if (state.activeSubTab === '클라우드') {
openCloudModal({ type: '클라우드', : '', : '', 수량: 1, : '', : '', : '', : '한맥', : '' } as any);
} else if (state.activeSubTab === '구독SW' || state.activeSubTab === '영구SW') {

View File

@@ -103,13 +103,21 @@
.grid-form.is-view-mode input,
.grid-form.is-view-mode select,
.grid-form.is-view-mode textarea {
border-color: transparent !important;
border: none !important;
background-color: transparent !important;
padding-left: 0;
padding-right: 0;
pointer-events: none;
color: var(--text-main);
font-weight: 500;
padding-left: 0 !important;
padding-right: 0 !important;
pointer-events: none !important;
color: var(--text-main) !important;
font-weight: 500 !important;
appearance: none !important;
-webkit-appearance: none !important;
-moz-appearance: none !important;
box-shadow: none !important;
}
.grid-form.is-view-mode select::-ms-expand {
display: none !important;
}
.grid-form.is-edit-mode input,
@@ -119,6 +127,16 @@
border: 1px solid var(--border-color);
}
/* 수동 수정 불가 필드 (자산번호 등) 전용 스타일 */
.grid-form input[readonly] {
border-color: transparent !important;
background-color: transparent !important;
pointer-events: none !important;
color: var(--text-main) !important;
font-weight: 500 !important;
cursor: default;
}
.grid-form.is-edit-mode input:focus,
.grid-form.is-edit-mode select:focus,
.grid-form.is-edit-mode textarea:focus {

View File

@@ -50,7 +50,7 @@ export function renderHwDashboard(container: HTMLElement) {
<canvas id="chart-hw-types"></canvas>
</div>
<div class="dashboard-card">
<h4 style="margin-bottom:1rem; font-size:0.9rem; color:var(--text-muted);">법인별 자산 분포</h4>
<h4 style="margin-bottom:1rem; font-size:0.9rem; color:var(--text-muted);">구매법인별 자산 분포</h4>
<canvas id="chart-hw-corps"></canvas>
</div>
</div>

View File

@@ -14,6 +14,7 @@ export function renderSwDashboard(container: HTMLElement) {
let cloudExp = 0;
const currentYear = new Date().getFullYear();
const today = new Date();
const corps = ['한맥', '삼안', '바론'];
const categories = ['업무공통', '개발S/W', '디자인', '설계S/W'];
@@ -22,9 +23,10 @@ export function renderSwDashboard(container: HTMLElement) {
const costByCat: Record<string, number> = {};
categories.forEach(c => costByCat[c] = 0);
const today = new Date();
// 통합 SW 데이터 (호환용)
const allSw = [...state.masterData.subSw, ...state.masterData.permSw];
state.masterData.sw.forEach(sw => {
allSw.forEach(sw => {
const assigned = state.masterData.swUsers.filter(u => u.swId === sw.id).length;
const qty = typeof sw. === 'number' ? sw.수량 : parseInt(sw.||'0', 10);
const priceStr = sw. ? String(sw.).replace(/,/g, '') : '0';
@@ -36,22 +38,6 @@ export function renderSwDashboard(container: HTMLElement) {
} else if (sw.type === '영구SW') {
permQty += qty; permUsed += assigned; permTotal++;
if (isSWExpiring(sw)) permExp++;
} else if (sw.type === '클라우드') {
if (sw.) {
thisMonthCloudCost += parseInt(String(sw.).replace(/,/g, ''), 10) || 0;
}
if (sw.) {
const payDay = parseInt(sw., 10);
if (!isNaN(payDay)) {
const nextPayMs = new Date(today.getFullYear(), today.getMonth(), payDay).getTime();
let diff = (nextPayMs - today.getTime()) / (1000 * 60 * 60 * 24);
if (diff < 0) {
const nextMonthMs = new Date(today.getFullYear(), today.getMonth() + 1, payDay).getTime();
diff = (nextMonthMs - today.getTime()) / (1000 * 60 * 60 * 24);
}
if (diff <= 14) cloudExp++;
}
}
}
if (sw. && sw..startsWith(String(currentYear))) {
@@ -60,14 +46,14 @@ export function renderSwDashboard(container: HTMLElement) {
}
});
// 클라우드 데이터 처리 (필요시 추가)
// ...
const subPer = subQty > 0 ? Math.round((subUsed/subQty)*100) : 0;
const permPer = permQty > 0 ? Math.round((permUsed/permQty)*100) : 0;
const subExpPer = subTotal > 0 ? Math.round((subExp/subTotal)*100) : 0;
const permExpPer = permTotal > 0 ? Math.round((permExp/permTotal)*100) : 0;
const cloudExpTotal = state.masterData.sw.filter(s => s.type === '클라우드').length;
const cloudExpPer = cloudExpTotal > 0 ? Math.round((cloudExp/cloudExpTotal)*100) : 0;
// Cloud trend & Last month cost logic
const cloudCostTrend = [0, 0, 0, 0];
const trendLabels: string[] = [];
for(let i=3; i>=0; i--) {
@@ -75,25 +61,6 @@ export function renderSwDashboard(container: HTMLElement) {
d.setMonth(d.getMonth() - i);
trendLabels.push(`${d.getMonth()+1}`);
}
if (state.masterData.logs) {
state.masterData.logs.forEach(log => {
const match = log.details.match(/[^\d]*([\d,]+)/);
if (match && (log.details.includes('청구액') || log.details.includes('비용'))) {
const cost = parseInt(match[1].replace(/,/g, ''), 10);
const logDate = new Date(log.date);
const monthDiff = (today.getFullYear() - logDate.getFullYear())*12 + (today.getMonth() - logDate.getMonth());
if (monthDiff === 1) lastMonthCloudCost += cost;
if (monthDiff >= 0 && monthDiff < 4) cloudCostTrend[3 - monthDiff] += cost;
}
});
}
const costDiff = thisMonthCloudCost - lastMonthCloudCost;
const costDiffText = lastMonthCloudCost > 0
? `${costDiff >= 0 ? '+' : ''}${((costDiff/lastMonthCloudCost)*100).toFixed(1)}%`
: 'New';
container.innerHTML = `
<div class="view-container">
@@ -143,53 +110,16 @@ export function renderSwDashboard(container: HTMLElement) {
</div>
</div>
<!-- 클라우드 전월/당월 통합 및 결제 임박 (1:1 비율) -->
<div class="dashboard-layout-2col" style="margin-bottom: 2.5rem;">
<div class="dashboard-card" data-action="cloud-billing" style="flex-direction:row; cursor:pointer; min-height:auto; align-items:center; gap: 1.5rem;">
<div style="flex:1;">
<span style="font-size:1rem; font-weight:700; color:var(--text-main);">☁️ 클라우드 청구 현황 (통합)</span>
<div style="margin-top: 0.5rem; display:flex; align-items:baseline; gap: 0.75rem;">
<span style="font-size: 2rem; font-weight:800; color:var(--primary-color);">₩ ${thisMonthCloudCost.toLocaleString()}</span>
<span style="font-size: 0.85rem; font-weight:600; color:${costDiff >= 0 ? 'var(--dash-danger)' : 'var(--dash-primary)'};">
${costDiff >= 0 ? '▲' : '▼'} ${costDiffText}
</span>
</div>
<div style="font-size: 0.8125rem; color:var(--text-muted); margin-top:0.25rem;">전월 실적: ₩ ${lastMonthCloudCost.toLocaleString()}</div>
</div>
<div style="width: 50px; height: 50px; border-radius: 50%; background: conic-gradient(var(--primary-color) 100%, var(--border-color) 0); display:flex; justify-content:center; align-items:center; opacity:0.8;">
<div style="width: 40px; height: 40px; border-radius: 50%; background: var(--white); display:flex; justify-content:center; align-items:center;">
<span style="font-size: 0.75rem; color:var(--text-muted); font-weight:600;">₩</span>
</div>
</div>
</div>
<div class="dashboard-card" data-action="cloud-exp" style="flex-direction:row; justify-content:space-between; align-items:center; cursor:pointer; min-height:auto;">
<div style="flex:1;">
<span style="font-size:1rem; font-weight:700; color:var(--text-main);">클라우드 결제 임박<br><span style="font-size:0.8rem;font-weight:400;color:var(--text-muted);">(14일 이내)</span></span>
<div style="font-size: 1.5rem; font-weight:700; color:${cloudExp > 0 ? 'var(--dash-danger)' : 'var(--text-main)'}; margin-top:0.5rem;">${cloudExp}건 청구</div>
</div>
<div style="width: 50px; height: 50px; border-radius: 50%; background: conic-gradient(var(--dash-danger) ${cloudExpPer}%, var(--border-color) 0); display:flex; justify-content:center; align-items:center;">
<div style="width: 40px; height: 40px; border-radius: 50%; background: var(--white); display:flex; justify-content:center; align-items:center;">
<span style="font-size: 0.75rem; color:var(--text-muted); font-weight:600;">${cloudExpPer}%</span>
</div>
</div>
</div>
</div>
<h3 class="dashboard-section-title">비용 분석 현황</h3>
<div style="display:grid; grid-template-columns: repeat(3, 1fr); gap: 1rem; margin-bottom: 2rem;">
<div class="dashboard-card" style="grid-column: span 1;">
<h4 style="margin-bottom:1rem; font-size:0.9rem; color:var(--text-muted);">${currentYear}년 법인별 도입 금액 (원)</h4>
<h3 class="dashboard-section-title">${currentYear}년 도입 비용 분석</h3>
<div class="dashboard-layout-2col">
<div class="dashboard-card">
<h4 style="margin-bottom:1rem; font-size:0.9rem; color:var(--text-muted);">구매법인별 도입 금액 (원)</h4>
<canvas id="chart-sw-corp"></canvas>
</div>
<div class="dashboard-card" style="grid-column: span 1;">
<h4 style="margin-bottom:1rem; font-size:0.9rem; color:var(--text-muted);">${currentYear}분야별 도입 금액 (원)</h4>
<div class="dashboard-card">
<h4 style="margin-bottom:1rem; font-size:0.9rem; color:var(--text-muted);">분야별 도입 금액 (원)</h4>
<canvas id="chart-sw-cat"></canvas>
</div>
<div class="dashboard-card" style="grid-column: span 1;">
<h4 style="margin-bottom:1rem; font-size:0.9rem; color:var(--text-muted);">직전 4개월 클라우드 결제 추이 (원)</h4>
<canvas id="chart-cloud-trend"></canvas>
</div>
</div>
</div>
`;
@@ -199,71 +129,27 @@ export function renderSwDashboard(container: HTMLElement) {
const ctxCorp = (document.getElementById('chart-sw-corp') as HTMLCanvasElement)?.getContext('2d');
if (ctxCorp) {
const chart = new Chart(ctxCorp, {
new Chart(ctxCorp, {
type: 'bar',
data: { labels: corps, datasets: [{ data: corps.map(c => costByCorp[c]), backgroundColor: 'rgba(30, 81, 73, 0.8)', borderRadius: 4 }] },
options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } } }
});
state.activeCharts.push(chart);
}
const ctxTrend = (document.getElementById('chart-cloud-trend') as HTMLCanvasElement)?.getContext('2d');
if (ctxTrend) {
const chart = new Chart(ctxTrend, {
type: 'line',
data: {
labels: trendLabels,
datasets: [{
data: cloudCostTrend,
borderColor: '#6366f1',
backgroundColor: 'rgba(99, 102, 241, 0.05)',
borderWidth: 2,
fill: true,
tension: 0.4
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: { legend: { display: false } },
scales: { y: { beginAtZero: true } }
}
});
state.activeCharts.push(chart);
}
const ctxCat = (document.getElementById('chart-sw-cat') as HTMLCanvasElement)?.getContext('2d');
if (ctxCat) {
const chart = new Chart(ctxCat, {
new Chart(ctxCat, {
type: 'bar',
data: { labels: categories, datasets: [{ data: categories.map(c => costByCat[c]), backgroundColor: 'rgba(59, 130, 246, 0.8)', borderRadius: 4 }] },
options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } } }
});
state.activeCharts.push(chart);
}
}, 100);
container.querySelector('[data-action="sub-usage"]')?.addEventListener('click', () => openSwUsageDetail('구독 소프트웨어 사용 목록', state.masterData.sw.filter(sw => sw.type === '구독SW')));
container.querySelector('[data-action="perm-usage"]')?.addEventListener('click', () => openSwUsageDetail('영구 소프트웨어 사용 목록', state.masterData.sw.filter(sw => sw.type === '영구SW')));
container.querySelector('[data-action="sub-exp"]')?.addEventListener('click', () => openSwDashboardDetail('구독 SW 만료 예정 목록', state.masterData.sw.filter(sw => sw.type === '구독SW' && isSWExpiring(sw))));
container.querySelector('[data-action="perm-exp"]')?.addEventListener('click', () => openSwDashboardDetail('유지보수 만료 예정 목록', state.masterData.sw.filter(sw => sw.type === '영구SW' && isSWExpiring(sw))));
container.querySelector('[data-action="cloud-billing"]')?.addEventListener('click', () => openCloudDashboardDetail('클라우드 청구 현황 (전체)', state.masterData.sw.filter(sw => sw.type === '클라우드')));
container.querySelector('[data-action="cloud-exp"]')?.addEventListener('click', () => {
const expiringClouds = state.masterData.sw.filter(sw => {
if (sw.type !== '클라우드' || !sw.) return false;
const payDay = parseInt(sw., 10);
if (isNaN(payDay)) return false;
const nextPayMs = new Date(today.getFullYear(), today.getMonth(), payDay).getTime();
let diff = (nextPayMs - today.getTime()) / (1000 * 60 * 60 * 24);
if (diff < 0) {
const nextMonthMs = new Date(today.getFullYear(), today.getMonth() + 1, payDay).getTime();
diff = (nextMonthMs - today.getTime()) / (1000 * 60 * 60 * 24);
}
return diff <= 14;
});
openCloudDashboardDetail('결제 임박 클라우드 목록 (14일 이내)', expiringClouds);
});
container.querySelector('[data-action="sub-usage"]')?.addEventListener('click', () => openSwUsageDetail('구독 소프트웨어 사용 목록', state.masterData.subSw));
container.querySelector('[data-action="perm-usage"]')?.addEventListener('click', () => openSwUsageDetail('영구 소프트웨어 사용 목록', state.masterData.permSw));
container.querySelector('[data-action="sub-exp"]')?.addEventListener('click', () => openSwDashboardDetail('구독 SW 만료 예정 목록', state.masterData.subSw.filter(sw => isSWExpiring(sw))));
container.querySelector('[data-action="perm-exp"]')?.addEventListener('click', () => openSwDashboardDetail('유지보수 만료 예정 목록', state.masterData.permSw.filter(sw => isSWExpiring(sw))));
}
function isSWExpiring(sw: SoftwareAsset) {
@@ -274,11 +160,15 @@ function isSWExpiring(sw: SoftwareAsset) {
const diffDays = (endMs - Date.now()) / (1000 * 60 * 60 * 24);
return diffDays >= 0 && diffDays <= 30;
}
} else if (sw.type === '영구SW' && sw. && sw..includes('유지보수: ~')) {
} else if (sw.type === '영구SW' && sw. && sw..includes('~')) {
// 임시 로직: 비고란에 날짜가 포함된 경우
try {
const endMs = new Date(normalizeDate(sw..split('~')[1])).getTime();
const diffDays = (endMs - Date.now()) / (1000 * 60 * 60 * 24);
return diffDays >= 0 && diffDays <= 30;
const dateMatch = sw..match(/\\d{4}-\\d{2}-\\d{2}/);
if (dateMatch) {
const endMs = new Date(normalizeDate(dateMatch[0])).getTime();
const diffDays = (endMs - Date.now()) / (1000 * 60 * 60 * 24);
return diffDays >= 0 && diffDays <= 30;
}
} catch { return false; }
}
return false;

View File

@@ -1,10 +1,10 @@
import { state } from '../../core/state';
import { openHwModal } from '../../components/Modal/HWModal';
import { formatInline } from '../../core/utils';
import { formatInline, sortAssets } from '../../core/utils';
import { createIcons, RefreshCcw } from 'lucide';
export function renderEquipmentList(container: HTMLElement) {
const fullList = state.masterData.hw.filter(a => a.type === '전산비품');
const fullList = sortAssets(state.masterData.equip);
const filterBar = document.createElement('div');
filterBar.className = 'search-bar';
@@ -16,7 +16,7 @@ export function renderEquipmentList(container: HTMLElement) {
<input type="text" id="filter-keyword" placeholder="검색어를 입력하세요..." autocomplete="off">
</div>
<div class="search-item">
<label>법인</label>
<label>구매법인</label>
<select id="filter-corp"><option value="">전체 법인</option>${corps.map(c => `<option value="${c}">${c}</option>`).join('')}</select>
</div>
<button id="btn-reset-filters" class="btn btn-outline btn-reset">
@@ -28,7 +28,7 @@ export function renderEquipmentList(container: HTMLElement) {
const tableWrapper = document.createElement('div');
tableWrapper.className = 'table-container';
const table = document.createElement('table');
table.innerHTML = `<thead><tr><th>No</th><th>법인</th><th>유형</th><th>자산코드</th><th>명칭</th><th>위치</th><th>관리자</th><th>구매일</th><th>금액</th><th>관리</th></tr></thead><tbody id="dynamic-tbody"></tbody>`;
table.innerHTML = `<thead><tr><th>No</th><th>구매법인</th><th>현 사용조직</th><th>유형</th><th>자산번호</th><th>모델명</th><th>관리자</th><th>구매일</th><th>금액</th><th>관리</th></tr></thead><tbody id="dynamic-tbody"></tbody>`;
tableWrapper.appendChild(table);
container.appendChild(tableWrapper);
@@ -42,7 +42,7 @@ export function renderEquipmentList(container: HTMLElement) {
const corp = corpSelect ? corpSelect.value : '';
const filtered = fullList.filter(asset => {
const matchKeyword = !keyword || String(asset.||'').toLowerCase().includes(keyword) || String(asset.||'').toLowerCase().includes(keyword);
const matchKeyword = !keyword || String(asset.||'').toLowerCase().includes(keyword) || String(asset.||'').toLowerCase().includes(keyword) || String(asset.||'').toLowerCase().includes(keyword);
const matchCorp = !corp || asset. === corp;
return matchKeyword && matchCorp;
});
@@ -59,16 +59,16 @@ export function renderEquipmentList(container: HTMLElement) {
tr.innerHTML = `
<td>${idx+1}</td>
<td>${asset.}</td>
<td>${asset.||'-'}</td>
<td>${asset.||''}</td>
<td>${asset.type}</td>
<td>${asset.}</td>
<td>${formatInline(asset.)}</td>
<td>${formatInline(asset.)}</td>
<td>${formatInline(asset.)}</td>
<td>${formatInline(asset.)}</td>
<td>${formatInline(asset._정 || asset.)}</td>
<td>${asset.||''}</td>
<td>${asset.||''}</td>
<td><button class="btn btn-outline btn-sm">수정</button></td>
`;
tr.addEventListener('click', (e) => { if (!(e.target as HTMLElement).closest('button')) openHwModal(asset); });
tr.addEventListener('click', (e) => { if (!(e.target as HTMLElement).closest('button')) openHwModal(asset, 'view'); });
tbody.appendChild(tr);
});
};

View File

@@ -0,0 +1,85 @@
import { state } from '../../core/state';
import { openHwModal } from '../../components/Modal/HWModal';
import { formatInline, sortAssets } from '../../core/utils';
import { createIcons, RefreshCcw } from 'lucide';
export function renderMobileList(container: HTMLElement) {
const fullList = sortAssets(state.masterData.mobile);
const filterBar = document.createElement('div');
filterBar.className = 'search-bar';
const corps = Array.from(new Set(fullList.map(a => a.))).filter(Boolean).sort();
filterBar.innerHTML = `
<div class="search-item flex-1">
<label>통합 검색 (자산코드/명칭)</label>
<input type="text" id="filter-keyword" placeholder="검색어를 입력하세요..." autocomplete="off">
</div>
<div class="search-item">
<label>구매법인</label>
<select id="filter-corp"><option value="">전체 법인</option>${corps.map(c => `<option value="${c}">${c}</option>`).join('')}</select>
</div>
<button id="btn-reset-filters" class="btn btn-outline btn-reset">
<i data-lucide="refresh-ccw"></i> 필터 초기화
</button>
`;
container.appendChild(filterBar);
const tableWrapper = document.createElement('div');
tableWrapper.className = 'table-container';
const table = document.createElement('table');
table.innerHTML = `<thead><tr><th>No</th><th>구매법인</th><th>현 사용조직</th><th>유형</th><th>자산번호</th><th>모델명</th><th>관리자</th><th>구매일</th><th>금액</th><th>관리</th></tr></thead><tbody id="dynamic-tbody"></tbody>`;
tableWrapper.appendChild(table);
container.appendChild(tableWrapper);
const tbody = table.querySelector('tbody')!;
const updateTable = () => {
const keywordInput = document.getElementById('filter-keyword') as HTMLInputElement;
const corpSelect = document.getElementById('filter-corp') as HTMLSelectElement;
const keyword = keywordInput ? keywordInput.value.toLowerCase().trim() : '';
const corp = corpSelect ? corpSelect.value : '';
const filtered = fullList.filter(asset => {
const matchKeyword = !keyword || String(asset.||'').toLowerCase().includes(keyword) || String(asset.||'').toLowerCase().includes(keyword) || String(asset.||'').toLowerCase().includes(keyword);
const matchCorp = !corp || asset. === corp;
return matchKeyword && matchCorp;
});
tbody.innerHTML = '';
if (filtered.length === 0) {
tbody.innerHTML = `<tr><td colspan="10" style="text-align:center; padding: 3rem; color: var(--text-muted);">검색 결과가 없습니다.</td></tr>`;
return;
}
filtered.forEach((asset, idx) => {
const tr = document.createElement('tr');
tr.style.cursor = 'pointer';
tr.innerHTML = `
<td>${idx+1}</td>
<td>${asset.}</td>
<td>${asset.||''}</td>
<td>${asset.type}</td>
<td>${asset.}</td>
<td>${formatInline(asset.)}</td>
<td>${formatInline(asset._정 || asset.)}</td>
<td>${asset.||''}</td>
<td>${asset.||''}</td>
<td><button class="btn btn-outline btn-sm">수정</button></td>
`;
tr.addEventListener('click', (e) => { if (!(e.target as HTMLElement).closest('button')) openHwModal(asset, 'view'); });
tbody.appendChild(tr);
});
};
document.getElementById('filter-keyword')?.addEventListener('input', updateTable);
document.getElementById('filter-corp')?.addEventListener('change', updateTable);
document.getElementById('btn-reset-filters')?.addEventListener('click', () => {
(document.getElementById('filter-keyword') as HTMLInputElement).value = '';
(document.getElementById('filter-corp') as HTMLSelectElement).value = '';
updateTable();
});
updateTable();
}

View File

@@ -1,10 +1,10 @@
import { state } from '../../core/state';
import { openPcModal } from '../../components/Modal/PCModal';
import { formatInline } from '../../core/utils';
import { formatInline, sortAssets } from '../../core/utils';
import { createIcons, Paperclip, RefreshCcw } from 'lucide';
export function renderPcList(container: HTMLElement) {
const fullList = state.masterData.hw.filter(a => a.type === '개인PC');
const fullList = sortAssets(state.masterData.pc);
const filterBar = document.createElement('div');
filterBar.className = 'search-bar';
@@ -16,11 +16,8 @@ export function renderPcList(container: HTMLElement) {
<input type="text" id="filter-keyword" placeholder="검색어를 입력하세요..." autocomplete="off">
</div>
<div class="search-item">
<label>법인</label>
<select id="filter-corp">
<option value="">전체 법인</option>
${corps.map(c => `<option value="${c}">${c}</option>`).join('')}
</select>
<label>구매법인</label>
<select id="filter-corp"><option value="">전체 법인</option>${corps.map(c => `<option value="${c}">${c}</option>`).join('')}</select>
</div>
<button id="btn-reset-filters" class="btn btn-outline btn-reset">
<i data-lucide="refresh-ccw"></i> 필터 초기화
@@ -31,7 +28,7 @@ export function renderPcList(container: HTMLElement) {
const tableWrapper = document.createElement('div');
tableWrapper.className = 'table-container';
const table = document.createElement('table');
table.innerHTML = `<thead><tr><th>No</th><th>법인</th><th>자산코드</th><th>사용자</th><th>위치</th><th>CPU</th><th>RAM</th><th>Storage</th><th>구매일</th><th>금액</th><th>품의서</th><th>관리</th></tr></thead><tbody id="dynamic-tbody"></tbody>`;
table.innerHTML = `<thead><tr><th>No</th><th>구매법인</th><th>현 사용조직</th><th>자산코드</th><th>사용자</th><th>위치</th><th>CPU</th><th>RAM</th><th>Storage</th><th>구매일</th><th>금액</th><th>품의서</th><th>관리</th></tr></thead><tbody id="dynamic-tbody"></tbody>`;
tableWrapper.appendChild(table);
container.appendChild(tableWrapper);
@@ -46,14 +43,14 @@ export function renderPcList(container: HTMLElement) {
const corp = corpSelect ? corpSelect.value : '';
const filtered = fullList.filter(asset => {
const matchKeyword = !keyword || String(asset.||'').toLowerCase().includes(keyword) || String(asset.||'').toLowerCase().includes(keyword);
const matchKeyword = !keyword || String(asset.||'').toLowerCase().includes(keyword) || String(asset.||'').toLowerCase().includes(keyword) || String(asset.||'').toLowerCase().includes(keyword);
const matchCorp = !corp || asset. === corp;
return matchKeyword && matchCorp;
});
tbody.innerHTML = '';
if (filtered.length === 0) {
tbody.innerHTML = `<tr><td colspan="12" style="text-align:center; padding: 3rem; color: var(--text-muted);">검색 결과가 없습니다.</td></tr>`;
tbody.innerHTML = `<tr><td colspan="13" style="text-align:center; padding: 3rem; color: var(--text-muted);">검색 결과가 없습니다.</td></tr>`;
return;
}
@@ -65,6 +62,7 @@ export function renderPcList(container: HTMLElement) {
tr.innerHTML = `
<td>${idx+1}</td>
<td>${asset.}</td>
<td>${asset.||''}</td>
<td>${asset.}</td>
<td>${asset.||''}</td>
<td>${asset.||''}</td>
@@ -76,7 +74,7 @@ export function renderPcList(container: HTMLElement) {
<td style="text-align:center;">${asset. ? '<i data-lucide="paperclip" class="text-primary"></i>' : '-'}</td>
<td><button class="btn btn-outline btn-sm">수정</button></td>
`;
tr.addEventListener('click', (e) => { if (!(e.target as HTMLElement).closest('button')) openPcModal(asset); });
tr.addEventListener('click', (e) => { if (!(e.target as HTMLElement).closest('button')) openPcModal(asset, 'view'); });
tbody.appendChild(tr);
});
createIcons({ icons: { Paperclip } });

View File

@@ -1,10 +1,10 @@
import { state } from '../../core/state';
import { openHwModal } from '../../components/Modal/HWModal';
import { formatInline, createBadge } from '../../core/utils';
import { formatInline, createBadge, sortAssets } from '../../core/utils';
import { createIcons, RefreshCcw } from 'lucide';
export function renderServerList(container: HTMLElement) {
const fullList = state.masterData.hw.filter(a => a.type === '서버');
const fullList = sortAssets(state.masterData.server);
const filterBar = document.createElement('div');
filterBar.className = 'search-bar';
@@ -17,7 +17,7 @@ export function renderServerList(container: HTMLElement) {
<input type="text" id="filter-keyword" placeholder="검색어를 입력하세요..." autocomplete="off">
</div>
<div class="search-item">
<label>법인</label>
<label>구매법인</label>
<select id="filter-corp"><option value="">전체 법인</option>${corps.map(c => `<option value="${c}">${c}</option>`).join('')}</select>
</div>
<div class="search-item">
@@ -33,7 +33,7 @@ export function renderServerList(container: HTMLElement) {
const tableWrapper = document.createElement('div');
tableWrapper.className = 'table-container';
const table = document.createElement('table');
table.innerHTML = `<thead><tr><th>No</th><th>법인</th><th>현 사용조직</th><th>자산번호</th><th>용도</th><th>상세</th><th>설치위치</th><th>담당자</th><th>IP주소</th><th>모델명</th><th>OS</th><th>CPU/RAM</th><th>Storage</th><th>관리</th></tr></thead><tbody id="dynamic-tbody"></tbody>`;
table.innerHTML = `<thead><tr><th>No</th><th>구매법인</th><th>현 사용조직</th><th>자산번호</th><th>용도</th><th>상세</th><th>설치위치</th><th>담당자</th><th>IP주소</th><th>모델명</th><th>OS</th><th>CPU/RAM</th><th>Storage</th><th>관리</th></tr></thead><tbody id="dynamic-tbody"></tbody>`;
tableWrapper.appendChild(table);
container.appendChild(tableWrapper);
@@ -89,7 +89,7 @@ export function renderServerList(container: HTMLElement) {
<td>${formatInline(storage)}</td>
<td><button class="btn btn-outline btn-sm">수정</button></td>
`;
tr.addEventListener('click', (e) => { if (!(e.target as HTMLElement).closest('button')) openHwModal(asset); });
tr.addEventListener('click', (e) => { if (!(e.target as HTMLElement).closest('button')) openHwModal(asset, 'view'); });
tbody.appendChild(tr);
});
};

View File

@@ -1,24 +1,29 @@
import { state } from '../../core/state';
import { openStorageModal } from '../../components/Modal/StorageModal';
import { formatInline } from '../../core/utils';
import { openHwModal } from '../../components/Modal/HWModal';
import { formatInline, createBadge, sortAssets } from '../../core/utils';
import { createIcons, RefreshCcw } from 'lucide';
export function renderStorageList(container: HTMLElement) {
const fullList = state.masterData.hw.filter(a => a.type === '스토리지');
const fullList = sortAssets(state.masterData.storage);
const filterBar = document.createElement('div');
filterBar.className = 'search-bar';
const corps = Array.from(new Set(fullList.map(a => a.))).filter(Boolean).sort();
const orgUnits = Array.from(new Set(fullList.map(a => a.))).filter(Boolean).sort();
filterBar.innerHTML = `
<div class="search-item flex-1">
<label>통합 검색 (자산코드/명칭/모델명)</label>
<label>통합 검색 (자산번호/조직/모델명)</label>
<input type="text" id="filter-keyword" placeholder="검색어를 입력하세요..." autocomplete="off">
</div>
<div class="search-item">
<label>법인</label>
<label>구매법인</label>
<select id="filter-corp"><option value="">전체 법인</option>${corps.map(c => `<option value="${c}">${c}</option>`).join('')}</select>
</div>
<div class="search-item">
<label>현 사용조직</label>
<select id="filter-org-unit"><option value="">전체 조직</option>${orgUnits.map(o => `<option value="${o}">${o}</option>`).join('')}</select>
</div>
<button id="btn-reset-filters" class="btn btn-outline btn-reset">
<i data-lucide="refresh-ccw"></i> 필터 초기화
</button>
@@ -28,7 +33,7 @@ export function renderStorageList(container: HTMLElement) {
const tableWrapper = document.createElement('div');
tableWrapper.className = 'table-container';
const table = document.createElement('table');
table.innerHTML = `<thead><tr><th>No</th><th>법인</th><th>유형</th><th>자산코드</th><th>명칭</th><th>위치</th><th>모델명</th><th>용량</th><th>IP주소</th><th>구매일</th><th>관리</th></tr></thead><tbody id="dynamic-tbody"></tbody>`;
table.innerHTML = `<thead><tr><th>No</th><th>구매법인</th><th>현 사용조직</th><th>자산번호</th><th>용도</th><th>상세</th><th>설치위치</th><th>담당자</th><th>모델명</th><th>Storage</th><th>관리</th></tr></thead><tbody id="dynamic-tbody"></tbody>`;
tableWrapper.appendChild(table);
container.appendChild(tableWrapper);
@@ -37,14 +42,17 @@ export function renderStorageList(container: HTMLElement) {
const updateTable = () => {
const keywordInput = document.getElementById('filter-keyword') as HTMLInputElement;
const corpSelect = document.getElementById('filter-corp') as HTMLSelectElement;
const orgSelect = document.getElementById('filter-org-unit') as HTMLSelectElement;
const keyword = keywordInput ? keywordInput.value.toLowerCase().trim() : '';
const corp = corpSelect ? corpSelect.value : '';
const orgUnit = orgSelect ? orgSelect.value : '';
const filtered = fullList.filter(asset => {
const matchKeyword = !keyword || String(asset.||'').toLowerCase().includes(keyword) || String(asset.||'').toLowerCase().includes(keyword) || String(asset.||'').toLowerCase().includes(keyword);
const matchKeyword = !keyword || String(asset.||'').toLowerCase().includes(keyword) || String(asset.||'').toLowerCase().includes(keyword) || String(asset.||'').toLowerCase().includes(keyword);
const matchCorp = !corp || asset. === corp;
return matchKeyword && matchCorp;
const matchOrg = !orgUnit || asset. === orgUnit;
return matchKeyword && matchCorp && matchOrg;
});
tbody.innerHTML = '';
@@ -56,29 +64,38 @@ export function renderStorageList(container: HTMLElement) {
filtered.forEach((asset, idx) => {
const tr = document.createElement('tr');
tr.style.cursor = 'pointer';
const mainManager = asset._정 || asset. || '';
const subManager = asset._부 || '';
const managerHtml = [mainManager ? `${createBadge('정', '#1E5149')} ${mainManager}` : '', subManager ? `${createBadge('부', '#9CA3AF')} ${subManager}` : ''].filter(v => v !== '').join(' / ');
const storage = [asset.SSD1, asset.SSD2, asset.].filter(v => v).join(' / ');
tr.innerHTML = `
<td>${idx+1}</td>
<td>${asset.}</td>
<td>${asset.storage유형||''}</td>
<td>${asset.||''}</td>
<td>${asset.}</td>
<td>${formatInline(asset.)}</td>
<td>${formatInline(asset.)}</td>
<td>${formatInline(asset.)}</td>
<td>${formatInline(asset.)}</td>
<td>${formatInline(asset.)}</td>
<td>${asset.||''}</td>
<td>${asset.IP주소||''}</td>
<td>${asset.||''}</td>
<td>${managerHtml}</td>
<td>${asset.||''}</td>
<td>${formatInline(storage)}</td>
<td><button class="btn btn-outline btn-sm">수정</button></td>
`;
tr.addEventListener('click', (e) => { if (!(e.target as HTMLElement).closest('button')) openStorageModal(asset); });
tr.addEventListener('click', (e) => { if (!(e.target as HTMLElement).closest('button')) openHwModal(asset, 'view'); });
tbody.appendChild(tr);
});
};
document.getElementById('filter-keyword')?.addEventListener('input', updateTable);
document.getElementById('filter-corp')?.addEventListener('change', updateTable);
document.getElementById('filter-org-unit')?.addEventListener('change', updateTable);
document.getElementById('btn-reset-filters')?.addEventListener('click', () => {
(document.getElementById('filter-keyword') as HTMLInputElement).value = '';
(document.getElementById('filter-corp') as HTMLSelectElement).value = '';
(document.getElementById('filter-org-unit') as HTMLSelectElement).value = '';
updateTable();
});

View File

@@ -1,11 +1,14 @@
import { state } from '../../core/state';
import { openSwModal } from '../../components/Modal/SWModal';
import { openSwUserModal } from '../../components/Modal/SWUserModal';
import { sortAssets } from '../../core/utils';
import { CORP_LIST } from '../../components/Modal/SharedData';
import { generateOptionsHTML } from '../../components/Modal/ModalUtils';
import { createIcons, Edit2, Users, RefreshCcw } from 'lucide';
export function renderSwList(container: HTMLElement) {
const fullList = state.masterData.sw.filter(a => a.type === state.activeSubTab);
const isSub = state.activeSubTab === '구독SW';
const fullList = sortAssets(isSub ? state.masterData.subSw : state.masterData.permSw);
const filterBar = document.createElement('div');
filterBar.className = 'search-bar';
@@ -25,11 +28,8 @@ export function renderSwList(container: HTMLElement) {
</select>
</div>
<div class="search-item">
<label>법인</label>
<select id="filter-corp">
<option value="">전체 법인</option>
<option value="한맥">한맥</option><option value="삼안">삼안</option><option value="바론">바론</option>
</select>
<label>구매법인</label>
<select id="filter-corp">${generateOptionsHTML(CORP_LIST, '', true)}</select>
</div>
<button id="btn-reset-filters" class="btn btn-outline btn-reset">
<i data-lucide="refresh-ccw"></i> 필터 초기화
@@ -46,7 +46,7 @@ export function renderSwList(container: HTMLElement) {
<th style="text-align:center;">No.</th>
<th style="text-align:center;">상태</th>
<th style="text-align:center;">분야</th>
<th style="text-align:center;">법인</th>
<th style="text-align:center;">구매법인</th>
<th style="text-align:center;">부서</th>
<th style="text-align:center;">제품명</th>
<th style="text-align:center;">구매일</th>
@@ -87,7 +87,7 @@ export function renderSwList(container: HTMLElement) {
}
filtered.forEach((asset, idx) => {
const assigned = state.masterData.swUsers.filter(u => u.swId === asset.id).length;
const assigned = state.masterData.swUsers.filter(u => u.sw_id === asset.id).length;
const qty = typeof asset. === 'number' ? asset.수량 : parseInt(asset.||'0', 10);
const avail = qty - assigned;
@@ -100,22 +100,14 @@ export function renderSwList(container: HTMLElement) {
const endDate = new Date(endDateStr);
if (!isNaN(endDate.getTime())) {
endDate.setHours(23, 59, 59, 999);
if (endDate < new Date()) {
isExpired = true;
}
if (endDate < new Date()) isExpired = true;
}
}
if (isExpired) {
statusHtml = `<span style="background: var(--danger, #ef4444); color: white; padding: 2px 6px; border-radius: 4px; font-size: 0.75rem; font-weight: bold; white-space: nowrap;">만료</span>`;
} else {
statusHtml = `<span style="background: var(--primary-color, #1E5149); color: white; padding: 2px 6px; border-radius: 4px; font-size: 0.75rem; font-weight: bold; white-space: nowrap;">사용중</span>`;
}
if (isExpired) statusHtml = `<span style="background: var(--danger, #ef4444); color: white; padding: 2px 6px; border-radius: 4px; font-size: 0.75rem; font-weight: bold; white-space: nowrap;">만료</span>`;
else statusHtml = `<span style="background: var(--primary-color, #1E5149); color: white; padding: 2px 6px; border-radius: 4px; font-size: 0.75rem; font-weight: bold; white-space: nowrap;">사용중</span>`;
} else {
if (asset.) {
statusHtml = `<span style="background: #3b82f6; color: white; padding: 2px 6px; border-radius: 4px; font-size: 0.75rem; font-weight: bold; white-space: nowrap;">유효</span>`;
} else {
statusHtml = `<span style="background: #6b7280; color: white; padding: 2px 6px; border-radius: 4px; font-size: 0.75rem; font-weight: bold; white-space: nowrap;">없음</span>`;
}
if (asset.) statusHtml = `<span style="background: #3b82f6; color: white; padding: 2px 6px; border-radius: 4px; font-size: 0.75rem; font-weight: bold; white-space: nowrap;">유효</span>`;
else statusHtml = `<span style="background: #6b7280; color: white; padding: 2px 6px; border-radius: 4px; font-size: 0.75rem; font-weight: bold; white-space: nowrap;">없음</span>`;
}
const tr = document.createElement('tr');
@@ -144,7 +136,7 @@ export function renderSwList(container: HTMLElement) {
tr.querySelector('.btn-users')?.addEventListener('click', (e) => { e.stopPropagation(); openSwUserModal(asset); });
tbody.appendChild(tr);
});
createIcons({ icons: { Edit2, Users } });
createIcons({ icons: { Edit2, Users, RefreshCcw } });
};
document.getElementById('filter-keyword')?.addEventListener('input', updateTable);

View File

@@ -3,6 +3,7 @@ import { renderPcList } from './List/PcListView';
import { renderServerList } from './List/ServerListView';
import { renderStorageList } from './List/StorageListView';
import { renderEquipmentList } from './List/EquipmentListView';
import { renderMobileList } from './List/MobileListView';
import { renderSwList } from './List/SwListView';
import { renderCloudList } from './List/CloudListView';
import { createIcons, Download, Upload, FileSpreadsheet, Plus, X, LayoutDashboard, Monitor, Server, Database, Laptop, CalendarClock, Key, Cpu, Layers, Users, Paperclip, Edit2, RefreshCcw } from 'lucide';
@@ -26,6 +27,7 @@ export function renderSWTable(mainContent: HTMLElement) {
else if (tab === '서버') renderServerList(container);
else if (tab === '스토리지') renderStorageList(container);
else if (tab === '전산비품') renderEquipmentList(container);
else if (tab === '모바일기기') renderMobileList(container);
else {
container.innerHTML = `<div style="padding:2rem; color:var(--text-muted);">"${tab}" 탭에 대한 하드웨어 리스트 뷰가 정의되지 않았습니다.</div>`;
}